sage-agent-internal 0.4.13__py3-none-any.whl → 0.5.0__py3-none-any.whl
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.
- sage_agent_internal/_version.py +1 -1
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/package.json +2 -2
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/schemas/sage-agent-internal/package.json.orig +1 -1
- sage_agent_internal-0.5.0.data/data/share/jupyter/labextensions/sage-agent-internal/static/45.9ce39966f5739629ab60.js +1 -0
- sage_agent_internal-0.5.0.data/data/share/jupyter/labextensions/sage-agent-internal/static/remoteEntry.cfadeaa34c38e95f1af6.js +1 -0
- {sage_agent_internal-0.4.13.dist-info → sage_agent_internal-0.5.0.dist-info}/METADATA +1 -1
- sage_agent_internal-0.5.0.dist-info/RECORD +34 -0
- sage_agent_internal-0.4.13.data/data/share/jupyter/labextensions/sage-agent-internal/static/581.8e016557cd083f708a6e.js +0 -1
- sage_agent_internal-0.4.13.data/data/share/jupyter/labextensions/sage-agent-internal/static/remoteEntry.f58185f0c0dc5d1feffe.js +0 -1
- sage_agent_internal-0.4.13.dist-info/RECORD +0 -34
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/install.json +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/schemas/sage-agent-internal/plugin.json +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/122.3c2c200586e65203b674.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/220.d384edfd5bbcfda33a2a.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/262.3fc4ad88e6f8c273d4ad.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/353.2c285601a208c3735929.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/363.db49bb1f85b6e9ca8bea.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/364.c2fb82c6f484097228c6.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/439.3cb9ac7022c8a6074647.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/481.96b91d018df31d54d173.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/553.b7906877d98a62265533.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/553.b7906877d98a62265533.js.LICENSE.txt +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/635.8c395c854aa2b140b668.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/713.103cb5ae248be385b08a.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/742.b204789055ded4e07883.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/747.b8e9485ebcbb3066eb4b.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/821.b58f29814f5900f1f6f8.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/845.cc2bc80fbfea6d20a396.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/888.09382cc93a2ad3932b31.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/950.b995ed106288bd5aedcc.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/973.c9d731f1117c26d913d0.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/973.c9d731f1117c26d913d0.js.LICENSE.txt +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/style.js +0 -0
- {sage_agent_internal-0.4.13.data → sage_agent_internal-0.5.0.data}/data/share/jupyter/labextensions/sage-agent-internal/static/third-party-licenses.json +0 -0
- {sage_agent_internal-0.4.13.dist-info → sage_agent_internal-0.5.0.dist-info}/WHEEL +0 -0
- {sage_agent_internal-0.4.13.dist-info → sage_agent_internal-0.5.0.dist-info}/licenses/LICENSE +0 -0
@@ -1 +0,0 @@
|
|
1
|
-
(self.webpackChunksage_agent_internal=self.webpackChunksage_agent_internal||[]).push([[581],{139:e=>{"use strict";e.exports="You are Sage AI, a world leading expert data scientist and quantitative analyst tasked with **pair-programming data analysis within a Jupyter Notebooks**. You excel in working closely with the USER on tasks related to **data exploration, analysis, model training, visualization, hypothesis testing, and summarization**. You execute data analysis tasks through precise code and concise chat coordination.\n\n## Communication Style\n**Chat responses**: 1-5 lines for simple tasks, longer when explaining tool usage or complex coordination. Direct, action-oriented. No verbose explanations or educational content in chat.\n**Notebook content**: Put detailed explanations, methodology, findings, and educational material in markdown cells. Plot important data.\n**Never repeat the entire workflow unnecessarily**, especially after \ninterruptions. If interrupted, clearly ask the user where to resume.\n**Code cells**: Concise (<30 lines), written like a top data scientist and not a software engineer. **Execute frequently** to verify correctness. **Follow every 2-3 code cells with one markdown cell** explaining what was done and what was discovered. Also write 1-2 sentences in the chat about it.\n**Maintain momentum** by continuing to the next task immediately after \ncompleting the current one, unless user input is required.\n\n## Core Workflow\n1. **Read context** efficiently - check notebook summary only when needed. Do not read empty notebooks. \n2. **ALWAYS PLAN FIRST** - Call `edit_plan` tool immediately for ANY task with multiple steps. After you get the plan, briefly summarize the plan in the chat. **Reiterate the major assumptions from the plan** and mention key numerical value choices and algorithm choices in 1-2 sentences in the chat. Do not summarize the plan **in the cells, only in chat**. Only after mentioning your assumptions, start executing the plan.\n3. After every major change, such as initial plan, major step, call wait_user_reply tool. Only after user approves the initial plan, start executing it.\n4. **Execute incrementally** - run code frequently, fix errors in-place.\n5. **Update plan progress** - Call `edit_plan` before each major step to update the progress display. Once complete, do one final update to plan showing what has been accomplished.\n6. **Visualize Data:** Make clear plots about important data and findings during data exploration, and during findings like a top data scientist.\n7. **Create markdown cells after code execution** to explain your reasoning, findings, and methodology. The goal is to produce a high quality, readable, and rigorous notebook like a top data scientist.\n8. **Add summary** - clearly summarize every executed code cell: include its purpose, libraries used, key variables, data transformations. \n\n## Tool Usage Rules\n- **Bundle searches** into comprehensive queries, not single-word searches\n- **Explain tool purpose** briefly before each call\n- **Stop after 5 tool calls** to check if user wants to continue\n- **Never call tools from code cells** - tools are for your coordination only\n- **Use `wait_user_reply`** when needing user input or confirmation\n- Use \\$ for dollar sign in MARKDOWN cells and $ for inline LaTeX math. \n- yfinance data dont have Adj Close column, use Close.\n\n## Data Science Standards\n- **Data quality**: Validate inputs, handle missing data, explore and plot data, distributions and document transformations.\n- **Kernel Awareness**: Always refer to the kernel variable summary to understand the structure of data. Do not make assumptions about the data if the data is present in the kernel.\n- Document assumptions and limitations clearly.\n- **Reproducibility**: Set random seeds, document versions, clear variable naming\n- **Statistical rigor**: Validate assumptions, test significance, document methodology\n- **Performance awareness**: Consider computational efficiency for large datasets and remind user to create a new notebook if the current one is too large. \n- **Financial data**: Handle splits/dividends properly, validate ticker symbols. First use the search tool do determine appropriate tickers and then download data with yfinance.\n\n### Error Handling\n- Fix errors directly in existing cells, don't create debug cells.\n- On interruption: ask user where to resume, don't restart from scratch.\n\n## Waiting for User Input\nWhen you need to ask the user a question or need them to confirm an action, you MUST use the `wait_user_reply` tool. This pauses your work and signals to the user that their input is required.\n\n**How to use `wait_user_reply`:**\n1. **First, send a message** containing your question or the information you want the user to review.\n2. **Immediately after**, call the `wait_user_reply` tool.\n3. **Generate 1-3 follow up responses** that are relevant to the question or action you are waiting for:\n - These should be concise and directly related to the user's potential responses.\n - They should not be speculative or unrelated to the current task.\n - Create exact responses and examples, not vague responses like \"Modify the strategy\" which can be interpreted in many ways.\n - When asking the user to proceed or continue, only provide one option to continue unless it is extremely relevant to modify the task.\n - For extremely simple tasks such as printing hello world or basic debugging tasks do not include any follow up responses.\n"},311:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 16 16%27 fill=%27none%27 stroke=%27%23212529%27 stroke-linecap=%27round%27 stroke-linejoin=%27round%27%3e%3cpath d=%27m2 5 6 6 6-6%27/%3e%3c/svg%3e"},435:(e,t,n)=>{"use strict";n.r(t),n.d(t,{ServiceFactory:()=>i,ServiceProvider:()=>o});var o,s=n(927);!function(e){e.ANTHROPIC="claude",e.GEMINI="gemini"}(o||(o={}));class i{static createService(e){const t=this.instanceCache.get(e);if(t)return t;let n;switch(e){case o.ANTHROPIC:case o.GEMINI:n=new s.A;break;default:throw new Error(`Unknown service provider: ${e}`)}return this.instanceCache.set(e,n),n}}i.instanceCache=new Map},628:(e,t,n)=>{"use strict";n.d(t,{F:()=>s});var o=n(6209);class s{static parseUserMessages(e){try{return e.map(e=>this.isUserMessage(e)?{role:"user",content:e.content}:e)}catch(t){return console.error("Error in parseUserMessages:",t,{messages:e}),e}}static isUserMessage(e){return e&&"user"===e.role}static isToolRelatedMessage(e){try{return s.isToolUseMessage(e)||s.isToolResultMessage(e)}catch(t){return console.error("Error in isToolRelatedMessage:",t,{message:e}),!1}}static isToolUseMessage(e){return e&&"assistant"===e.role&&Array.isArray(e.content)&&e.content.length>0&&"tool_use"===e.content[0].type}static isToolResultMessage(e){return e&&"user"===e.role&&Array.isArray(e.content)&&e.content.length>0&&"tool_result"===e.content[0].type}static isDiffApprovalMessage(e){return e&&"diff_approval"===e.role&&Array.isArray(e.content)&&e.content.length>0&&"diff_approval"===e.content[0].type}static filterToolMessages(e,t){var n;try{const i=s.buildCleanedConversationHistory(e,t);if(o.AppStateService.getState().maxToolCallLimit){let e=0;i.forEach(t=>{s.isToolRelatedMessage(t)&&(e+=1)}),e>o.AppStateService.getState().maxToolCallLimit&&(console.log("Max tool call limit reached, cancelling llm loop"),null===(n=o.AppStateService.getState().chatContainer)||void 0===n||n.chatWidget.cancelMessage())}const a=[],r=[],l=[];if(i.forEach((e,t)=>{s.isToolRelatedMessage(e)&&(a.push(t),s.isToolUseMessage(e)&&r.push(t),s.isToolResultMessage(e)&&l.push(t))}),r.length<=10)return[...i];const c=r.slice(r.length-10),d=new Set;for(const e of c){d.add(e);const t=l.find(t=>t>e);void 0!==t&&d.add(t)}return i.filter((e,t)=>!s.isToolRelatedMessage(e)||d.has(t))}catch(n){return t&&t(`Error in filterToolMessages: ${n}, messages: ${JSON.stringify(e)}`),console.error("Error in filterToolMessages:",n,{messagesLength:e.length}),[...e]}}static filterDiffApprovalMessages(e){return e.filter(e=>!s.isDiffApprovalMessage(e))}static normalizeMessageContent(e,t){try{let n=e.map(e=>{const t={...e};return s.isToolRelatedMessage(t)||Array.isArray(t.content)&&t.content.every(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e)&&(t.content=t.content.join(" ")),t});return s.buildCleanedConversationHistory(n,t)}catch(n){return t&&t(`Error in normalizeMessageContent: ${n}, messages: ${JSON.stringify(e)}`),console.error("Error in normalizeMessageContent:",n,{messagesLength:null==e?void 0:e.length}),e}}static buildCleanedConversationHistory(e,t){try{const t=[];for(let n=0;n<e.length;n++){const o=e[n];if(s.isToolUseMessage(o)){const i=e[n+1];s.isToolResultMessage(i)?t.push(o):console.log("Removing unmatched assistant tool_use message:",JSON.stringify(o))}else if(s.isToolResultMessage(o)){const e=t[t.length-1];if(s.isToolUseMessage(e)){if(e.content[0].id===o.content[0].tool_use_id){const e={role:o.role,content:o.content.map(e=>({tool_use_id:e.tool_use_id,content:e.content,type:e.type}))};t.push(e)}else console.log("Removing unmatched user tool_result message (ID mismatch):",JSON.stringify(o))}else console.log("Removing orphaned user tool_result message (no preceding tool_use):",JSON.stringify(o))}else t.push(o)}return t}catch(n){return t&&t(`Error in buildCleanedConversationHistory: ${n}, messages: ${JSON.stringify(e)}`),console.error("Error in buildCleanedConversationHistory:",n,{messagesLength:null==e?void 0:e.length}),e}}static async createCancelledResponse(e,t){const n={message:"Request was cancelled, skipping retry logic",requestStatus:t};return e&&await e(JSON.stringify(n)),{cancelled:!0,role:"assistant",content:[]}}}},644:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 16 16%27 fill=%27%23fff%27%3e%3cpath d=%27M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0%27/%3e%3c/svg%3e"},927:(e,t,n)=>{"use strict";n.d(t,{A:()=>p});var o=n(8397),s=n(135),i=n.n(s),a=n(4340),r=n(8533);class l{static async processStream(e,t,n){var o;if(!e){const n=new Error("Message stream is undefined");throw await(null===(o=t.errorLogger)||void 0===o?void 0:o.call(t,{message:n.message,stream:e})),n}const s=this.initializeStreamContext();this.setupTextChunkHandler(e,t);try{return await this.processStreamEvents(e,s,t),t.isRequestCancelled()?this.createCancelledResult():{...await this.getFinalMessage(e,t),needsUserConfirmation:s.needsUserConfirmation}}catch(e){return this.handleStreamError(e,t,s)}}static initializeStreamContext(){return{toolUseInfo:null,needsUserConfirmation:!1,messageContent:[],deltaChunkBuffer:"",lastDeltaUpdateTime:0}}static setupTextChunkHandler(e,t){t.onTextChunk&&e.on("text",e=>{t.isRequestCancelled()||t.onTextChunk(e)})}static async processStreamEvents(e,t,n){var o;for await(const s of e){if(n.isRequestCancelled())return void await(null===(o=n.errorLogger)||void 0===o?void 0:o.call(n,{message:"Stream processing stopped due to cancellation",event:s,requestStatus:"CANCELLED"}));await this.handleStreamEvent(s,t,n)}}static async handleStreamEvent(e,t,n){switch(e.type){case"content_block_start":this.handleContentBlockStart(e,t,n);break;case"content_block_delta":this.handleContentBlockDelta(e,t,n);break;case"content_block_stop":await this.handleContentBlockStop(t,n)}}static handleContentBlockStart(e,t,n){"text"===e.content_block.type?t.messageContent.push({type:"text",text:""}):"tool_use"===e.content_block.type&&this.handleToolUseStart(e.content_block,t,n)}static handleToolUseStart(e,t,n){var o;t.toolUseInfo=e;const s={type:"tool_use",id:e.id,name:e.name,input:e.input};null===(o=n.onToolUse)||void 0===o||o.call(n,s),t.messageContent.push(s),"execute_cell"!==e.name&&"edit_cell"!==e.name||(t.needsUserConfirmation=!0)}static handleContentBlockDelta(e,t,n){"text_delta"===e.delta.type?this.handleTextDelta(e.delta,t):"input_json_delta"===e.delta.type&&this.handleInputJsonDelta(e.delta,t,n)}static handleTextDelta(e,t){for(let n=t.messageContent.length-1;n>=0;n--)if("text"===t.messageContent[n].type){t.messageContent[n].text+=e.text;break}}static handleInputJsonDelta(e,t,n){for(let o=t.messageContent.length-1;o>=0;o--)if("tool_use"===t.messageContent[o].type){this.processInputJsonDelta(e,t,n,o);break}}static processInputJsonDelta(e,t,n,o){const s=Date.now(),i=e.partial_json;console.log("ON TOOL USE JSON",i),t.deltaChunkBuffer+=i,(t.deltaChunkBuffer.length>=this.DELTA_CHUNK_THRESHOLD||s-t.lastDeltaUpdateTime>=this.DELTA_UPDATE_INTERVAL)&&n.onToolUse&&(n.onToolUse({type:"tool_use_delta",id:t.messageContent[o].id,name:t.messageContent[o].name,input_delta:t.deltaChunkBuffer}),t.deltaChunkBuffer="",t.lastDeltaUpdateTime=s),t.messageContent[o].partialInput||(t.messageContent[o].partialInput=""),t.messageContent[o].partialInput+=i}static async handleContentBlockStop(e,t){e.deltaChunkBuffer.length>0&&t.onToolUse&&this.flushDeltaBuffer(e,t),await this.processFinalToolInput(e,t)}static flushDeltaBuffer(e,t){for(let n=e.messageContent.length-1;n>=0;n--)if("tool_use"===e.messageContent[n].type){t.onToolUse({type:"tool_use_delta",id:e.messageContent[n].id,name:e.messageContent[n].name,input_delta:e.deltaChunkBuffer});break}e.deltaChunkBuffer=""}static async processFinalToolInput(e,t){var n;try{const o=e.messageContent.find(e=>"tool_use"===e.type&&e.partialInput);if(!(null==o?void 0:o.partialInput))return;const s=o.partialInput;if(!s.trim().startsWith("{")||!s.trim().endsWith("}"))return;const i=JSON.parse(s);e.toolUseInfo&&e.toolUseInfo.id==e.toolUseInfo.id&&(e.toolUseInfo.input=i,null===(n=t.onToolUse)||void 0===n||n.call(t,{type:"tool_use_stop",id:e.toolUseInfo.id,name:e.toolUseInfo.name,input:i}))}catch(t){console.log("[AnthropicStreamHandler] Could not parse final input:",{messageContent:e.messageContent,parseError:t})}}static async getFinalMessage(e,t){var n;try{return await e.finalMessage()}catch(e){const o={message:"Error getting final message from stream",error:e instanceof Error?e.message:e};throw await(null===(n=t.errorLogger)||void 0===n?void 0:n.call(t,o)),e}}static createCancelledResult(){return{cancelled:!0,role:"assistant",content:[]}}static async handleStreamError(e,t,n){var o,s;if("AbortError"===e.name||t.isRequestCancelled())return await(null===(o=t.errorLogger)||void 0===o?void 0:o.call(t,{message:"Stream processing aborted due to cancellation",error:e instanceof Error?e.message:e})),this.createCancelledResult();throw await(null===(s=t.errorLogger)||void 0===s?void 0:s.call(t,{message:"Error during stream processing",error:e instanceof Error?e.message:e,messageContent:n.messageContent,toolUseInfo:n.toolUseInfo,needsUserConfirmation:n.needsUserConfirmation})),e}}l.DELTA_CHUNK_THRESHOLD=30,l.DELTA_UPDATE_INTERVAL=100;var c=n(6209),d=n(2364);class h{static async createMessageStream(e,t,n){const o=await this.prepareMessages(e,t,n);return e.client.beta.messages.stream({model:e.modelName,messages:[...o.initialMessages,...o.filteredHistory],tools:o.availableTools.length>0?o.availableTools:void 0,max_tokens:4096,system:[{text:o.systemPrompt,type:"text",cache_control:{type:"ephemeral"}},...o.extraSystemMessages],betas:["token-efficient-tools-2025-02-19"]},{signal:e.abortSignal,headers:{...e.customHeaders||{},"no-cors":"true","sec-fetch-mode":"no-cors",mode:"no-cors"}})}static async prepareMessages(e,t,n){const o=await this.getNotebookContext(e),s=n(this.prepareInitialMessages(o),e.errorLogger),i=n(t,e.errorLogger),a=this.determineSystemPrompt(e);return{initialMessages:s,filteredHistory:i,availableTools:this.filterTools(e),systemPrompt:a,extraSystemMessages:await this.prepareExtraSystemMessages(e)}}static async getNotebookContext(e){var t;try{if(e.notebookContextManager&&e.notebookId)return e.notebookContextManager.formatContextAsMessage(e.notebookId)}catch(n){await(null===(t=e.errorLogger)||void 0===t?void 0:t.call(e,{message:"Error getting notebook context",error:n instanceof Error?n.message:n,notebookPath:e.notebookId,notebookContextManager:!!e.notebookContextManager}))}return""}static prepareInitialMessages(e){const t=[];return e&&""!==e.trim()&&t.push({role:"user",content:e}),t}static determineSystemPrompt(e){return"ask"===e.mode?e.systemPromptAskMode:"fast"===e.mode?e.systemPromptFastMode:e.systemPrompt}static filterTools(e){return e.isFastMode&&e.toolBlacklist.length>0?e.tools.filter(t=>t.name&&!e.toolBlacklist.includes(t.name)):e.tools}static async prepareExtraSystemMessages(e){var t,n;const o=[];e.systemPromptMessages&&o.push(...e.systemPromptMessages.map(e=>({text:e,type:"text"})));const s=c.AppStateService.getInsertedSnippets();if(s.length>0){const e=s.map(e=>`Snippet Title: ${e.title}\nSnippet Description: ${e.description?`${e.description}\n`:""} === Begin ${e.title} Content === \n\n${e.content}\n\n=== END ${e.title} Content ===`).join("\n\n");o.push({type:"text",text:`The user has inserted the following code snippets for context:\n\n${e}`})}if(e.fetchNotebookState)try{const t=await e.fetchNotebookState();t&&o.push({type:"text",text:`This is the current notebook summary with edit history: ${t}`})}catch(n){await(null===(t=e.errorLogger)||void 0===t?void 0:t.call(e,{message:"Error fetching notebook state",error:n instanceof Error?n.message:n,fetchNotebookState:!!e.fetchNotebookState}))}try{const e=await d.F.getLimitedKernelPreview();console.log("KERNEL PREVIEW:",e);const t=c.AppStateService.getState().settings.databaseUrl;e&&o.push({type:"text",text:`Current Kernel Variables and Objects Preview:\n\n${e.replace(t,"<DB_URL>")}`})}catch(t){console.warn("[AnthropicMessageCreator] Error getting kernel preview:",t),await(null===(n=e.errorLogger)||void 0===n?void 0:n.call(e,{message:"Error getting kernel preview",error:t instanceof Error?t.message:t}))}return o}}var u=n(628);class p{constructor(){this.client=null,this.modelName="claude-3-7-sonnet-20250219",this.modelUrl="https://api.anthropic.com/v1/messages",this.requestStatus=a.yR.IDLE,this.abortController=null,this.systemPrompt="",this.systemPromptAskMode="",this.systemPromptFastMode="",this.isFastMode=!1,this.toolBlacklist=[]}async initialize(e){try{if(this.client)return!0;try{const t=await r.w.getConfig();console.log("Initializing Anthropic client with config:",t),e=t.claude.api_key,this.systemPrompt=t.claude.system_prompt,this.systemPromptAskMode=t.claude_ask_mode.system_prompt,this.systemPromptFastMode=t.fast_mode.system_prompt,this.modelName=t.claude.model_name,this.modelUrl=t.claude.model_url,this.toolBlacklist=t.fast_mode.tool_blacklist||[]}catch(e){console.log("AppState not available, falling back to config")}return e&&""!==e.trim()?(this.client=new(i())({apiKey:e,baseURL:this.modelUrl,dangerouslyAllowBrowser:!0}),!0):(this.client=null,!1)}catch(e){return console.error("Failed to initialize Anthropic client:",e),this.client=null,!1}}get conversationHistory(){var e;return(null===(e=c.AppStateService.getState().chatContainer)||void 0===e?void 0:e.chatWidget.messageComponent.messageHistory)||[]}getToolBlacklist(){return[...this.toolBlacklist]}async refreshSystemPrompt(){try{const e=await r.w.getConfig();this.systemPrompt=e.claude.system_prompt,this.systemPromptAskMode=e.claude_ask_mode.system_prompt,this.systemPromptFastMode=e.fast_mode.system_prompt,this.toolBlacklist=e.fast_mode.tool_blacklist||[],console.log("System prompt loaded successfully from config")}catch(e){console.error("Failed to load system prompt from config:",e),this.systemPrompt="You are a world-class data scientist and quantitative analyst, highly proficient in exploratory data analysis, statistical and ML modeling, hypothesis testing, feature engineering, and efficient use of Jupyter notebooks.",this.systemPromptAskMode="You are a world-class data scientist and quantitative analyst, highly proficient in exploratory data analysis, statistical and ML modeling, hypothesis testing, feature engineering, and efficient use of Jupyter notebooks.",this.systemPromptFastMode="You are a world-class data scientist and quantitative analyst, optimized for speed and efficiency."}}isInitialized(){return null!==this.client}setModelName(e){this.modelName=e}getModelName(){return this.modelName}getRequestStatus(){return this.requestStatus}isRequestCancelled(){return this.requestStatus===a.yR.CANCELLED}cancelRequest(){this.abortController&&(this.abortController.abort(),this.abortController=null,this.requestStatus=a.yR.CANCELLED,console.log("Request cancelled by user"))}async sendMessage(e,t=[],n="agent",o,s,i,r,l,c,d,h,u=!1){await this.validateClientInitialized(h),this.initializeRequest();const p=this.getCustomHeaders({feature:"chat",mode:n}),g=await this.getFilteredHistory(h);try{const e=await this.executeStreamRequest(g,t,n,o,i,r,l,c,d,h,p);return this.isRequestCancelled()||(this.requestStatus=a.yR.COMPLETED),e}catch(e){return await this.handleRequestError(e,s,g,t,n,o,i,r,l,c,d,h,u,p)}}async sendEphemeralMessage(e,t,n="claude-3-5-haiku-latest",o,s,i,a){if(!this.client)throw new Error("Anthropic client not initialized. Please set API key first.");const r=this.getCustomHeaders({feature:a});try{return await this.executeEphemeralRequest(e,t,n,o,s,r)}catch(a){return await this.handleEphemeralRequestError(a,e,t,n,o,s,i,r)}}async executeEphemeralRequest(e,t,n,o,s,i={}){var a,r;const l=null!==(a=null==s?void 0:s.maxTokens)&&void 0!==a?a:48,c=null!==(r=null==s?void 0:s.temperature)&&void 0!==r?r:0;if(o){const a=await this.client.messages.stream({model:n,max_tokens:l,system:t,temperature:c,stop_sequences:null==s?void 0:s.stopSequences,messages:[{role:"user",content:e}]},{headers:Object.keys(i).length>0?i:void 0});let r="";for await(const e of a)if("content_block_delta"===e.type&&"text_delta"===e.delta.type){const t=e.delta.text;r+=t,o(t)}return r}{const o=await this.client.messages.create({model:n,max_tokens:l,system:t,temperature:c,stop_sequences:null==s?void 0:s.stopSequences,messages:[{role:"user",content:e}]},{headers:Object.keys(i).length>0?i:void 0});let a="";for(const e of o.content)"text"===e.type&&(a+=e.text);return a}}async handleEphemeralRequestError(e,t,n,o,s,i,a,r={}){if(console.error("Ephemeral message error:",e),"BadRequestError"===e.name&&400===e.status)throw e;const l=[5e3,15e3,3e4],c=l.length;for(let d=1;d<=c;d++)try{return a&&await a(e,d),await this.waitForRetry(l[d-1]),await this.executeEphemeralRequest(t,n,o,s,i,r)}catch(t){if(d===c){const e=t instanceof Error?t.message:"Unknown error occurred";throw new Error(`Failed to connect to AI service after 3 attempts. ${e}`)}e=t}throw e}async validateClientInitialized(e){if(!this.client){const t={message:"Anthropic client not initialized. Please set API key first.",variables:{client:this.client,modelName:this.modelName,modelUrl:this.modelUrl,requestStatus:this.requestStatus}};throw e&&await e(JSON.stringify(t)),new Error(t.message)}}initializeRequest(){this.requestStatus=a.yR.PENDING,this.abortController=new AbortController}async getFilteredHistory(e){try{const t=u.F.filterDiffApprovalMessages(this.conversationHistory),n=u.F.filterToolMessages(t,e);return u.F.parseUserMessages(n)}catch(t){const n={message:"Error filtering tool messages",error:t instanceof Error?t.message:t,conversationHistory:this.conversationHistory};throw e&&await e(JSON.stringify(n)),t}}async executeStreamRequest(e,t,n,o,s,i,a,r,c,d,h){const u=await this.createMessageStream(e,t,n,o,s,r,c,d,h);return await l.processStream(u,{onTextChunk:i,onToolUse:a,errorLogger:d,isRequestCancelled:()=>this.isRequestCancelled()},this.conversationHistory)}async createMessageStream(e,t,n,o,s,i,a,r,l={}){try{return await h.createMessageStream({client:this.client,modelName:this.modelName,systemPrompt:this.systemPrompt,systemPromptAskMode:this.systemPromptAskMode,systemPromptFastMode:this.systemPromptFastMode,isFastMode:this.isFastMode,toolBlacklist:this.toolBlacklist,mode:n,tools:t,systemPromptMessages:o,fetchNotebookState:s,notebookContextManager:i,notebookId:a,abortSignal:this.abortController.signal,errorLogger:r,customHeaders:l},e,u.F.normalizeMessageContent)}catch(e){const o={message:"Error creating message stream",error:e instanceof Error?e.message:e,variables:{modelName:this.modelName,isFastMode:this.isFastMode,mode:n,availableTools:t.map(e=>e.name)}};throw r&&await r(JSON.stringify(o)),e}}async handleRequestError(e,t,n,o,s,i,r,l,c,d,h,p,g=!1,m={}){if(this.isRequestCancelled())return u.F.createCancelledResponse(p,this.requestStatus);if(await this.logRequestError(e,p,s,n),await this.shouldSkipRetry(e,g,p))throw e;if(t)return await this.executeRetry(t,e,n,o,s,i,r,l,c,d,h,p,m);throw this.requestStatus=a.yR.ERROR,e}async logRequestError(e,t,n,o){const s={message:"Error calling Anthropic API",error:e instanceof Error?e.message:e,modelName:this.modelName,mode:n,isFastMode:this.isFastMode,filteredHistory:o,requestStatus:this.requestStatus};t&&await t(JSON.stringify(s))}async shouldSkipRetry(e,t,n){return"BadRequestError"===e.name&&400===e.status&&!t&&(this.requestStatus=a.yR.ERROR,await(null==n?void 0:n({message:"Bad request (400) error - not retrying",error:e instanceof Error?e.message:e})),!0)}async executeRetry(e,t,n,o,s,i,r,l,d,h,p,g,m={}){var f;this.requestStatus=a.yR.RETRYING;const v=[5e3,15e3,3e4],C=v.length;for(let b=1;b<=C;b++)try{if(await e(t,b),this.isRequestCancelled())return u.F.createCancelledResponse(g,this.requestStatus);if(await this.waitForRetry(v[b-1]),this.isRequestCancelled())return u.F.createCancelledResponse(g,this.requestStatus);this.abortController=new AbortController;const c=await this.executeStreamRequest(n,o,s,i,r,l,d,h,p,g,m);return this.isRequestCancelled()||(this.requestStatus=a.yR.COMPLETED),c}catch(e){if(this.isRequestCancelled())return u.F.createCancelledResponse(g,this.requestStatus);if(b===C){await(null==g?void 0:g({message:"All retry attempts failed",error:e instanceof Error?e.message:e,requestStatus:this.requestStatus,attemptNumber:b})),this.requestStatus=a.yR.ERROR,null===(f=c.AppStateService.getState().chatContainer)||void 0===f||f.chatWidget.llmStateDisplay.hide();const t=e instanceof Error?e.message:"Unknown error occurred";throw new Error(`Failed to connect to AI service after 3 attempts. ${t}`)}await(null==g?void 0:g({message:`Retry attempt ${b} failed, will try again`,error:e instanceof Error?e.message:e,requestStatus:this.requestStatus,attemptNumber:b})),t=e}throw t}async waitForRetry(e=5e3){await new Promise(t=>{const n=setTimeout(t,e),o=setInterval(()=>{this.isRequestCancelled()&&(clearTimeout(n),clearInterval(o),t(null))},500);setTimeout(()=>clearInterval(o),e)})}setSystemPrompt(e){this.systemPrompt=e}setToolBlacklist(e){this.toolBlacklist=Array.isArray(e)?[...e]:[]}getCustomHeaders({feature:e,mode:t}){var n,s,i,a;const r={};t&&(r["X-Sage-Mode"]=t),e&&(r["X-Sage-Feature"]=e);const l=c.AppStateService.getCurrentNotebookId();l&&(r["X-Sage-Notebook-Id"]=l);const d=c.AppStateService.getState().notebookTracker,h=null==d?void 0:d.currentWidget,u=null===(s=null===(n=null==h?void 0:h.sessionContext)||void 0===n?void 0:n.session)||void 0===s?void 0:s.id;u&&(r["X-Sage-Session-Id"]=u);const p=null===(a=null===(i=c.AppStateService.getState().chatContainer)||void 0===i?void 0:i.chatWidget.chatHistoryManager.getCurrentThread())||void 0===a?void 0:a.id;p&&(r["X-Sage-Thread-Id"]=p);const g=o.PageConfig.getOption("appVersion");g&&(r["X-Sage-Client-Lab-Version"]=g);const m=c.AppStateService.getExtensions();if(m){const e=m.installed.find(e=>"sage-agent-internal"===e.name);e&&(r["X-Sage-Client-Ext-Version"]=e.installed_version)}return r}}},1087:(e,t,n)=>{"use strict";n.r(t),n.d(t,{ChatBoxWidget:()=>dt,ChatRequestStatus:()=>o.yR,CheckpointRestorationOption:()=>o.q6,DiffApprovalStatus:()=>o.fY,NotebookDiffManager:()=>ut,default:()=>mn});var o=n(4340),s=n(3550);const i={"codebase-list_repos":"Sage is listing repos...","notebook-wait_user_reply":"","notebook-edit_plan":"Sage is updating the plan...","notebook-add_cell":"Sage is adding a new cell...","notebook-edit_cell":"Sage is editing a cell...","notebook-get_cell_info":"Sage is getting cell info...","notebook-remove_cells":"Sage is removing cell...","notebook-run_cell":"Sage is running a cell...","notebook-read_cells":"Sage is reading cell...","filesystem-delete_dataset":"Sage is deleting dataset...","filesystem-list_datasets":"Sage is listing datasets...","filesystem-save_dataset":e=>e.filepath?`Sage is saving dataset ${a(e.filepath,!0)}...`:"Sage is saving dataset...","filesystem-read_dataset":e=>e.filepath?`Sage is reading dataset ${a(e.filepath,!0)}...`:"Sage is reading dataset...","web-download_dataset":e=>{var t;const n=e.tickers&&(null===(t=e.tickers)||void 0===t?void 0:t.length);return n&&e.period&&e.interval?`Sage is downloading ${e.tickers.map(a).join(", ")} dataset in the web for the period of ${a(e.period)} and interval of ${a(e.interval)}...`:n&&e.period?`Sage is downloading ${e.tickers.map(a).join(", ")} dataset in the web for the period of ${a(e.period)}...`:n&&e.interval?`Sage is downloading ${e.tickers.map(a).join(", ")} dataset in the web for the interval of ${a(e.interval)}...`:n?`Sage is downloading ${e.tickers.map(a).join(", ")} dataset in the web...`:"Sage is downloading dataset in the web..."},"web-search_dataset":e=>e.queries&&0!==e.queries.length?`Sage is searching for ${e.queries.map(a).join(", ")} dataset in the web...`:"Sage is searching for dataset in the web..."},a=(e,t=!1)=>e?t?`<code class="sage-ai-filepath">${r(e)}</code>`:`<code>${e}</code>`:"",r=e=>{const t=e.split(/[/\\]/);return t.length<=3?e:`.../${t.slice(-2).join("/")}`},l="var(--jp-ui-font-color1)",c={"codebase-list_repos":`<svg width="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M13.2686 14.2686L15 16M12.0627 6.06274L11.9373 5.93726C11.5914 5.59135 11.4184 5.4184 11.2166 5.29472C11.0376 5.18506 10.8425 5.10425 10.6385 5.05526C10.4083 5 10.1637 5 9.67452 5H6.2C5.0799 5 4.51984 5 4.09202 5.21799C3.71569 5.40973 3.40973 5.71569 3.21799 6.09202C3 6.51984 3 7.07989 3 8.2V15.8C3 16.9201 3 17.4802 3.21799 17.908C3.40973 18.2843 3.71569 18.5903 4.09202 18.782C4.51984 19 5.07989 19 6.2 19H17.8C18.9201 19 19.4802 19 19.908 18.782C20.2843 18.5903 20.5903 18.2843 20.782 17.908C21 17.4802 21 16.9201 21 15.8V10.2C21 9.0799 21 8.51984 20.782 8.09202C20.5903 7.71569 20.2843 7.40973 19.908 7.21799C19.4802 7 18.9201 7 17.8 7H14.3255C13.8363 7 13.5917 7 13.3615 6.94474C13.1575 6.89575 12.9624 6.81494 12.7834 6.70528C12.5816 6.5816 12.4086 6.40865 12.0627 6.06274ZM14 12.5C14 13.8807 12.8807 15 11.5 15C10.1193 15 9 13.8807 9 12.5C9 11.1193 10.1193 10 11.5 10C12.8807 10 14 11.1193 14 12.5Z" stroke="${l}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> </g></svg>`,"notebook-wait_user_reply":"","notebook-edit_plan":`<svg width="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M19.9994 19.2611H10.9294C10.4794 19.2611 10.1094 18.8911 10.1094 18.4411C10.1094 17.9911 10.4794 17.6211 10.9294 17.6211H19.9994C20.4494 17.6211 20.8194 17.9911 20.8194 18.4411C20.8194 18.9011 20.4494 19.2611 19.9994 19.2611Z" fill="${l}"></path> <path d="M19.9994 12.9681H10.9294C10.4794 12.9681 10.1094 12.5981 10.1094 12.1481C10.1094 11.6981 10.4794 11.3281 10.9294 11.3281H19.9994C20.4494 11.3281 20.8194 11.6981 20.8194 12.1481C20.8194 12.5981 20.4494 12.9681 19.9994 12.9681Z" fill="${l}"></path> <path d="M19.9994 6.67125H10.9294C10.4794 6.67125 10.1094 6.30125 10.1094 5.85125C10.1094 5.40125 10.4794 5.03125 10.9294 5.03125H19.9994C20.4494 5.03125 20.8194 5.40125 20.8194 5.85125C20.8194 6.30125 20.4494 6.67125 19.9994 6.67125Z" fill="${l}"></path> <path d="M4.90969 8.03187C4.68969 8.03187 4.47969 7.94187 4.32969 7.79187L3.41969 6.88188C3.09969 6.56188 3.09969 6.04187 3.41969 5.72187C3.73969 5.40187 4.25969 5.40187 4.57969 5.72187L4.90969 6.05188L7.04969 3.91187C7.36969 3.59188 7.88969 3.59188 8.20969 3.91187C8.52969 4.23188 8.52969 4.75188 8.20969 5.07188L5.48969 7.79187C5.32969 7.94187 5.12969 8.03187 4.90969 8.03187Z" fill="${l}"></path> <path d="M4.90969 14.3287C4.69969 14.3287 4.48969 14.2487 4.32969 14.0887L3.41969 13.1788C3.09969 12.8588 3.09969 12.3388 3.41969 12.0188C3.73969 11.6988 4.25969 11.6988 4.57969 12.0188L4.90969 12.3488L7.04969 10.2087C7.36969 9.88875 7.88969 9.88875 8.20969 10.2087C8.52969 10.5288 8.52969 11.0487 8.20969 11.3687L5.48969 14.0887C5.32969 14.2487 5.11969 14.3287 4.90969 14.3287Z" fill="${l}"></path> <path d="M4.90969 20.3288C4.69969 20.3288 4.48969 20.2488 4.32969 20.0888L3.41969 19.1788C3.09969 18.8588 3.09969 18.3388 3.41969 18.0188C3.73969 17.6988 4.25969 17.6988 4.57969 18.0188L4.90969 18.3488L7.04969 16.2087C7.36969 15.8888 7.88969 15.8888 8.20969 16.2087C8.52969 16.5288 8.52969 17.0488 8.20969 17.3688L5.48969 20.0888C5.32969 20.2488 5.11969 20.3288 4.90969 20.3288Z" fill="${l}"></path> </g></svg>`,"notebook-edit_cell":`<svg width="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M18.3785 8.44975L11.4637 15.3647C11.1845 15.6439 10.8289 15.8342 10.4417 15.9117L7.49994 16.5L8.08829 13.5582C8.16572 13.1711 8.35603 12.8155 8.63522 12.5363L15.5501 5.62132M18.3785 8.44975L19.7927 7.03553C20.1832 6.64501 20.1832 6.01184 19.7927 5.62132L18.3785 4.20711C17.988 3.81658 17.3548 3.81658 16.9643 4.20711L15.5501 5.62132M18.3785 8.44975L15.5501 5.62132" stroke="${l}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> <path d="M5 20H19" stroke="${l}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> </g></svg>`,"notebook-remove_cells":`<svg fill="${l}" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="20" height="20" viewBox="0 0 48 48"><path d="M 24 4 C 20.491685 4 17.570396 6.6214322 17.080078 10 L 10.238281 10 A 1.50015 1.50015 0 0 0 9.9804688 9.9785156 A 1.50015 1.50015 0 0 0 9.7578125 10 L 6.5 10 A 1.50015 1.50015 0 1 0 6.5 13 L 8.6386719 13 L 11.15625 39.029297 C 11.427329 41.835926 13.811782 44 16.630859 44 L 31.367188 44 C 34.186411 44 36.570826 41.836168 36.841797 39.029297 L 39.361328 13 L 41.5 13 A 1.50015 1.50015 0 1 0 41.5 10 L 38.244141 10 A 1.50015 1.50015 0 0 0 37.763672 10 L 30.919922 10 C 30.429604 6.6214322 27.508315 4 24 4 z M 24 7 C 25.879156 7 27.420767 8.2681608 27.861328 10 L 20.138672 10 C 20.579233 8.2681608 22.120844 7 24 7 z M 11.650391 13 L 36.347656 13 L 33.855469 38.740234 C 33.730439 40.035363 32.667963 41 31.367188 41 L 16.630859 41 C 15.331937 41 14.267499 40.033606 14.142578 38.740234 L 11.650391 13 z M 20.476562 17.978516 A 1.50015 1.50015 0 0 0 19 19.5 L 19 34.5 A 1.50015 1.50015 0 1 0 22 34.5 L 22 19.5 A 1.50015 1.50015 0 0 0 20.476562 17.978516 z M 27.476562 17.978516 A 1.50015 1.50015 0 0 0 26 19.5 L 26 34.5 A 1.50015 1.50015 0 1 0 29 34.5 L 29 19.5 A 1.50015 1.50015 0 0 0 27.476562 17.978516 z"></path></svg>`,"notebook-run_cell":`<svg fill="${l}" width="20px" viewBox="0 0 32 32" id="icon" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"><defs><style>.cls-1{fill:none;}</style></defs><title>run</title><path d="M21,16a6,6,0,1,1-6,6,6,6,0,0,1,6-6m0-2a8,8,0,1,0,8,8,8,8,0,0,0-8-8Z"></path><path d="M26,4H6A2,2,0,0,0,4,6V26a2,2,0,0,0,2,2h4V26H6V12H28V6A2,2,0,0,0,26,4ZM6,10V6H26v4Z"></path><polygon points="19 19 19 25 24 22 19 19"></polygon><rect id="_Transparent_Rectangle_" data-name="<Transparent Rectangle>" class="cls-1" width="32" height="32"></rect></g></svg>`,"filesystem-delete_dataset":`<svg width="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M17 17L21 21M21 17L17 21M13 3H8.2C7.0799 3 6.51984 3 6.09202 3.21799C5.71569 3.40973 5.40973 3.71569 5.21799 4.09202C5 4.51984 5 5.0799 5 6.2V17.8C5 18.9201 5 19.4802 5.21799 19.908C5.40973 20.2843 5.71569 20.5903 6.09202 20.782C6.51984 21 7.0799 21 8.2 21H13M13 3L19 9M13 3V7.4C13 7.96005 13 8.24008 13.109 8.45399C13.2049 8.64215 13.3578 8.79513 13.546 8.89101C13.7599 9 14.0399 9 14.6 9H19M19 9V14" stroke="${l}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> </g></svg>`,"filesystem-read_dataset":`<svg width="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M13 3H8.2C7.0799 3 6.51984 3 6.09202 3.21799C5.71569 3.40973 5.40973 3.71569 5.21799 4.09202C5 4.51984 5 5.0799 5 6.2V17.8C5 18.9201 5 19.4802 5.21799 19.908C5.40973 20.2843 5.71569 20.5903 6.09202 20.782C6.51984 21 7.0799 21 8.2 21H12M13 3L19 9M13 3V7.4C13 7.96005 13 8.24008 13.109 8.45399C13.2049 8.64215 13.3578 8.79513 13.546 8.89101C13.7599 9 14.0399 9 14.6 9H19M19 9V11M9 17H11M9 13H13M9 9H10M19.2686 19.2686L21 21M20 17.5C20 18.8807 18.8807 20 17.5 20C16.1193 20 15 18.8807 15 17.5C15 16.1193 16.1193 15 17.5 15C18.8807 15 20 16.1193 20 17.5Z" stroke="${l}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> </g></svg>`,"filesystem-list_datasets":`<svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M15 3V6.4C15 6.96005 15 7.24008 15.109 7.45399C15.2049 7.64215 15.3578 7.79513 15.546 7.89101C15.7599 8 16.0399 8 16.6 8H20M10 8H6C4.89543 8 4 8.89543 4 10V19C4 20.1046 4.89543 21 6 21H12C13.1046 21 14 20.1046 14 19V16M16 3H13.2C12.0799 3 11.5198 3 11.092 3.21799C10.7157 3.40973 10.4097 3.71569 10.218 4.09202C10 4.51984 10 5.0799 10 6.2V12.8C10 13.9201 10 14.4802 10.218 14.908C10.4097 15.2843 10.7157 15.5903 11.092 15.782C11.5198 16 12.0799 16 13.2 16H16.8C17.9201 16 18.4802 16 18.908 15.782C19.2843 15.5903 19.5903 15.2843 19.782 14.908C20 14.4802 20 13.9201 20 12.8V7L16 3Z" stroke="${l}" stroke-width="2" stroke-linejoin="round"></path> </g></svg>`,"filesystem-save_dataset":`<svg width="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M17 21V13H7V21M7 3V8H15M19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V5C3 4.46957 3.21071 3.96086 3.58579 3.58579C3.96086 3.21071 4.46957 3 5 3H16L21 8V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21Z" stroke="${l}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> </g></svg>`,"web-download_dataset":`<svg width="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path fill-rule="evenodd" clip-rule="evenodd" d="M8 10C8 7.79086 9.79086 6 12 6C14.2091 6 16 7.79086 16 10V11H17C18.933 11 20.5 12.567 20.5 14.5C20.5 16.433 18.933 18 17 18H16.9C16.3477 18 15.9 18.4477 15.9 19C15.9 19.5523 16.3477 20 16.9 20H17C20.0376 20 22.5 17.5376 22.5 14.5C22.5 11.7793 20.5245 9.51997 17.9296 9.07824C17.4862 6.20213 15.0003 4 12 4C8.99974 4 6.51381 6.20213 6.07036 9.07824C3.47551 9.51997 1.5 11.7793 1.5 14.5C1.5 17.5376 3.96243 20 7 20H7.1C7.65228 20 8.1 19.5523 8.1 19C8.1 18.4477 7.65228 18 7.1 18H7C5.067 18 3.5 16.433 3.5 14.5C3.5 12.567 5.067 11 7 11H8V10ZM13 11C13 10.4477 12.5523 10 12 10C11.4477 10 11 10.4477 11 11V16.5858L9.70711 15.2929C9.31658 14.9024 8.68342 14.9024 8.29289 15.2929C7.90237 15.6834 7.90237 16.3166 8.29289 16.7071L11.2929 19.7071C11.6834 20.0976 12.3166 20.0976 12.7071 19.7071L15.7071 16.7071C16.0976 16.3166 16.0976 15.6834 15.7071 15.2929C15.3166 14.9024 14.6834 14.9024 14.2929 15.2929L13 16.5858V11Z" fill="${l}"></path> </g></svg>`,"web-search_dataset":`<svg width="20px" height="20px" viewBox="-0.5 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M22 11.8201C22 9.84228 21.4135 7.90885 20.3147 6.26436C19.2159 4.61987 17.6542 3.33813 15.8269 2.58126C13.9996 1.82438 11.9889 1.62637 10.0491 2.01223C8.10927 2.39808 6.32748 3.35052 4.92896 4.74904C3.53043 6.14757 2.578 7.92935 2.19214 9.86916C1.80629 11.809 2.00436 13.8197 2.76123 15.6469C3.51811 17.4742 4.79985 19.036 6.44434 20.1348C8.08883 21.2336 10.0222 21.8201 12 21.8201" stroke="${l}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path> <path d="M2 11.8201H22" stroke="${l}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path> <path d="M12 21.8201C10.07 21.8201 8.5 17.3401 8.5 11.8201C8.5 6.30007 10.07 1.82007 12 1.82007C13.93 1.82007 15.5 6.30007 15.5 11.8201" stroke="${l}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path> <path d="M18.3691 21.6901C20.3021 21.6901 21.8691 20.1231 21.8691 18.1901C21.8691 16.2571 20.3021 14.6901 18.3691 14.6901C16.4361 14.6901 14.8691 16.2571 14.8691 18.1901C14.8691 20.1231 16.4361 21.6901 18.3691 21.6901Z" stroke="${l}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path> <path d="M22.9998 22.8202L20.8398 20.6702" stroke="${l}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path> </g></svg>`,"notebook-add_cell":`<svg width="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M3 10V18C3 19.1046 3.89543 20 5 20H11M3 10V6C3 4.89543 3.89543 4 5 4H19C20.1046 4 21 4.89543 21 6V10M3 10H21M21 10V13" stroke="${l}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> <path d="M17 14V17M17 20V17M17 17H14M17 17H20" stroke="${l}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> <circle cx="6" cy="7" r="1" fill="${l}"></circle> <circle cx="9" cy="7" r="1" fill="${l}"></circle> </g></svg>`,"notebook-read_cells":`<svg width="20px" height="20px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="${l}"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <rect x="0" fill="none" width="24" height="24"></rect> <g> <path d="M9 12h6v-2H9zm-7 0h5v-2H2zm15 0h5v-2h-5zm3 2v2l-6 6H6a2 2 0 0 1-2-2v-6h2v6h6v-4a2 2 0 0 1 2-2h6zM4 8V4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4h-2V4H6v4z"></path> </g> </g></svg>`,"notebook-get_cell_info":`<svg fill="${l}" width="20px" height="20px" viewBox="0 0 24 24" id="check-double" data-name="Flat Line" xmlns="http://www.w3.org/2000/svg" class="icon flat-line"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"><line id="primary" x1="13.22" y1="16.5" x2="21" y2="7.5" style="fill: none; stroke: var(--jp-ui-font-color1); stroke-linecap: round; stroke-linejoin: round; stroke-width: 2;"></line><polyline id="primary-2" data-name="primary" points="3 11.88 7 16.5 14.78 7.5" style="fill: none; stroke: var(--jp-ui-font-color1); stroke-linecap: round; stroke-linejoin: round; stroke-width: 2;"></polyline></g></svg>`},d=`\n <svg fill="${l}" width="14px" height="14px" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">\n <title></title><g data-name="Layer 2" id="Layer_2">\n <path d="M18,11a1,1,0,0,1-1,1,5,5,0,0,0-5,5,1,1,0,0,1-2,0,5,5,0,0,0-5-5,1,1,0,0,1,0-2,5,5,0,0,0,5-5,1,1,0,0,1,2,0,5,5,0,0,0,5,5A1,1,0,0,1,18,11Z"></path>\n <path d="M19,24a1,1,0,0,1-1,1,2,2,0,0,0-2,2,1,1,0,0,1-2,0,2,2,0,0,0-2-2,1,1,0,0,1,0-2,2,2,0,0,0,2-2,1,1,0,0,1,2,0,2,2,0,0,0,2,2A1,1,0,0,1,19,24Z"></path><path d="M28,17a1,1,0,0,1-1,1,4,4,0,0,0-4,4,1,1,0,0,1-2,0,4,4,0,0,0-4-4,1,1,0,0,1,0-2,4,4,0,0,0,4-4,1,1,0,0,1,2,0,4,4,0,0,0,4,4A1,1,0,0,1,28,17Z"></path></g></svg>\n`,h=`<svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M16 12.9V17.1C16 20.6 14.6 22 11.1 22H6.9C3.4 22 2 20.6 2 17.1V12.9C2 9.4 3.4 8 6.9 8H11.1C14.6 8 16 9.4 16 12.9Z" stroke="${l}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path> <path d="M22 6.9V11.1C22 14.6 20.6 16 17.1 16H16V12.9C16 9.4 14.6 8 11.1 8H8V6.9C8 3.4 9.4 2 12.9 2H17.1C20.6 2 22 3.4 22 6.9Z" stroke="${l}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path> </g></svg>`,u=`<svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M17.0998 2H12.8998C9.81668 2 8.37074 3.09409 8.06951 5.73901C8.00649 6.29235 8.46476 6.75 9.02167 6.75H11.0998C15.2998 6.75 17.2498 8.7 17.2498 12.9V14.9781C17.2498 15.535 17.7074 15.9933 18.2608 15.9303C20.9057 15.629 21.9998 14.1831 21.9998 11.1V6.9C21.9998 3.4 20.5998 2 17.0998 2Z" fill="${l}"></path> <path d="M11.1 8H6.9C3.4 8 2 9.4 2 12.9V17.1C2 20.6 3.4 22 6.9 22H11.1C14.6 22 16 20.6 16 17.1V12.9C16 9.4 14.6 8 11.1 8ZM12.29 13.65L8.58 17.36C8.44 17.5 8.26 17.57 8.07 17.57C7.88 17.57 7.7 17.5 7.56 17.36L5.7 15.5C5.42 15.22 5.42 14.77 5.7 14.49C5.98 14.21 6.43 14.21 6.71 14.49L8.06 15.84L11.27 12.63C11.55 12.35 12 12.35 12.28 12.63C12.56 12.91 12.57 13.37 12.29 13.65Z" fill="${l}"></path> </g></svg>`;function p(e,t={}){const n=i[e];return"function"==typeof n?n(t):n||"Sage is working..."}function g(e){return c[e]||d}var m=n(6209),f=n(6750);class v{constructor(){this._diffState$=new f.BehaviorSubject({pendingDiffs:new Map,allDiffsResolved:!1,notebookId:null})}static getInstance(){return v.instance||(v.instance=new v),v.instance}get diffState$(){return this._diffState$.asObservable()}get currentState(){return this._diffState$.value}getCellStateChanges$(e){return this._diffState$.pipe((0,f.map)(t=>{const n=t.pendingDiffs.get(e);return n?{cellId:e,approved:n.approved,notebookId:t.notebookId}:null}),(0,f.distinctUntilChanged)((e,t)=>JSON.stringify(e)===JSON.stringify(t)))}get allDiffsResolved$(){return this._diffState$.pipe((0,f.map)(e=>({allDiffsResolved:e.allDiffsResolved,notebookId:e.notebookId})),(0,f.distinctUntilChanged)((e,t)=>e.allDiffsResolved===t.allDiffsResolved&&e.notebookId===t.notebookId),(0,f.map)(e=>({notebookId:e.notebookId})))}getPendingDiffsForNotebook$(e){return this._diffState$.pipe((0,f.map)(t=>{const n=[];for(const[,o]of t.pendingDiffs)e&&o.notebookId!==e||n.push(o);return n}),(0,f.distinctUntilChanged)((e,t)=>JSON.stringify(e)===JSON.stringify(t)))}getCurrentState(){return this._diffState$.value}updatePendingDiffs(e,t){const n=this._diffState$.value,o=this.checkIfAllDiffsResolved(e,t);this._diffState$.next({...n,pendingDiffs:e,allDiffsResolved:o,notebookId:t})}updateDiffState(e,t,n){const o=this._diffState$.value,s=new Map(o.pendingDiffs),i=s.get(e);i&&s.set(e,{...i,approved:t,userDecision:i.userDecision||(!0===t?"approved":!1===t?"rejected":null)});const a=this.checkIfAllDiffsResolved(s,n);this._diffState$.next({...o,pendingDiffs:s,allDiffsResolved:a,notebookId:null!=n?n:o.notebookId})}updateDiffStateResult(e,t){var n;const o=this._diffState$.value,s=new Map(o.pendingDiffs),i=s.get(e);i&&s.set(e,{...i,runResult:t});const a=this.checkIfAllDiffsResolved(s,(null===(n=s.get(e))||void 0===n?void 0:n.notebookId)||o.notebookId);this._diffState$.next({...o,allDiffsResolved:a,pendingDiffs:s})}updateDiffStateToRun(e,t){const n=this._diffState$.value,o=new Map(n.pendingDiffs),s=o.get(e);s&&o.set(e,{...s,approved:!0,userDecision:"run"}),this._diffState$.next({...n,pendingDiffs:o,notebookId:null!=t?t:n.notebookId})}addPendingDiff(e,t){var n;const o=this._diffState$.value,s=new Map(o.pendingDiffs);s.set(e,t);const i=this.checkIfAllDiffsResolved(s,t.notebookId);this._diffState$.next({...o,pendingDiffs:s,allDiffsResolved:i,notebookId:null!==(n=t.notebookId)&&void 0!==n?n:o.notebookId})}removePendingDiff(e,t){const n=this._diffState$.value,o=new Map(n.pendingDiffs);o.delete(e);const s=this.checkIfAllDiffsResolved(o,t);this._diffState$.next({...n,pendingDiffs:o,allDiffsResolved:s,notebookId:null!=t?t:n.notebookId})}clearAllDiffs(e){const t=this._diffState$.value;let n;if(e){n=new Map;for(const[o,s]of t.pendingDiffs)s.notebookId!==e&&n.set(o,s)}else n=new Map;this._diffState$.next({...t,pendingDiffs:n,allDiffsResolved:0===n.size,notebookId:null!=e?e:t.notebookId})}setNotebookId(e){const t=this._diffState$.value;this._diffState$.next({...t,notebookId:e})}setNotebookPath(e){this.setNotebookId(e)}getPendingDiffCount(e){const t=this._diffState$.value;let n=0;for(const[,o]of t.pendingDiffs)e&&o.notebookId!==e||o.userDecision||n++;return n}getApprovedDiffCount(e){const t=this._diffState$.value;let n=0;for(const[,o]of t.pendingDiffs)e&&o.notebookId!==e||!0!==o.approved&&"approved"!==o.userDecision&&"run"!==o.userDecision||n++;return n}getRejectedDiffCount(e){const t=this._diffState$.value;let n=0;for(const[,o]of t.pendingDiffs)e&&o.notebookId!==e||!1!==o.approved&&"rejected"!==o.userDecision||n++;return n}areAllDiffsApproved(e){const t=this._diffState$.value,n=[];for(const[,o]of t.pendingDiffs)e&&o.notebookId!==e||n.push(o);return 0===n.length||n.every(e=>!0===e.approved||"approved"===e.userDecision||"run"===e.userDecision)}areAllDiffsRejected(e){const t=this._diffState$.value,n=[];for(const[,o]of t.pendingDiffs)e&&o.notebookId!==e||n.push(o);return 0!==n.length&&n.every(e=>!1===e.approved||"rejected"===e.userDecision)}getDiffCountChanges$(e){return this._diffState$.pipe((0,f.map)(t=>{let n=0;for(const[,o]of t.pendingDiffs)e&&o.notebookId!==e||n++;return n}),(0,f.distinctUntilChanged)())}getApprovalStatusChanges$(e){return this._diffState$.pipe((0,f.map)(t=>{let n=0,o=0,s=0;for(const[,i]of t.pendingDiffs)e&&i.notebookId!==e||(!0===i.approved||"approved"===i.userDecision||"run"===i.userDecision?o++:!1===i.approved||"rejected"===i.userDecision?s++:n++);return{pending:n,approved:o,rejected:s,allResolved:n+o+s>0&&0===n}}),(0,f.distinctUntilChanged)((e,t)=>JSON.stringify(e)===JSON.stringify(t)))}checkIfAllDiffsResolved(e,t){let n=[];for(const[,o]of e)t&&o.notebookId!==t||n.push(o);if(0===n.length)return!0;for(const e of n)if("run"===e.userDecision&&!e.runResult)return!1;return n.every(e=>void 0!==e.approved||"approved"===e.userDecision||"rejected"===e.userDecision||"run"===e.userDecision)}}v.instance=null;const C=v.getInstance();var b=n(5024),y=n(3139),k=n(195),w=n(2383),S=n(7245),_=n(3760);const x=new _.LabIcon({name:"sage-agent-internal:agent-mode-icon",svgstr:'<svg width="15" height="14" viewBox="0 0 15 14" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M12.1666 1.74998V4.08331M13.3333 2.91665H11M2.83329 9.91665V11.0833M3.41663 10.5H2.24996M6.29651 9.04165C6.24443 8.83977 6.1392 8.65554 5.99178 8.50812C5.84436 8.3607 5.66013 8.25548 5.45826 8.2034L1.87951 7.28057C1.81845 7.26324 1.76471 7.22646 1.72645 7.17583C1.68818 7.12519 1.66748 7.06345 1.66748 6.99998C1.66748 6.93651 1.68818 6.87478 1.72645 6.82414C1.76471 6.7735 1.81845 6.73673 1.87951 6.7194L5.45826 5.79598C5.66006 5.74395 5.84424 5.63882 5.99166 5.49151C6.13907 5.34419 6.24434 5.16008 6.29651 4.95832L7.21934 1.37957C7.2365 1.31827 7.27323 1.26427 7.32394 1.2258C7.37466 1.18733 7.43656 1.1665 7.50022 1.1665C7.56387 1.1665 7.62577 1.18733 7.67649 1.2258C7.7272 1.26427 7.76394 1.31827 7.78109 1.37957L8.70334 4.95832C8.75542 5.16019 8.86064 5.34442 9.00806 5.49184C9.15548 5.63926 9.33972 5.74449 9.54159 5.79657L13.1203 6.71882C13.1819 6.73579 13.2362 6.77249 13.2748 6.82328C13.3135 6.87407 13.3345 6.93614 13.3345 6.99998C13.3345 7.06382 13.3135 7.1259 13.2748 7.17669C13.2362 7.22748 13.1819 7.26417 13.1203 7.28115L9.54159 8.2034C9.33972 8.25548 9.15548 8.3607 9.00806 8.50812C8.86064 8.65554 8.75542 8.83977 8.70334 9.04165L7.78051 12.6204C7.76335 12.6817 7.72662 12.7357 7.6759 12.7742C7.62519 12.8126 7.56329 12.8335 7.49963 12.8335C7.43598 12.8335 7.37407 12.8126 7.32336 12.7742C7.27265 12.7357 7.23591 12.6817 7.21876 12.6204L6.29651 9.04165Z" stroke="#949494" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>\n'}),E=new _.LabIcon({name:"sage-agent-internal:agent-mode-shiny-icon",svgstr:'<svg width="13" height="14" viewBox="0 0 13 14" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M5.38237 8.89564C5.33401 8.70819 5.2363 8.53712 5.09941 8.40023C4.96252 8.26333 4.79145 8.16563 4.60399 8.11727L1.28087 7.26035C1.22417 7.24426 1.17427 7.21011 1.13874 7.16309C1.10321 7.11607 1.08398 7.05874 1.08398 6.99981C1.08398 6.94087 1.10321 6.88355 1.13874 6.83653C1.17427 6.78951 1.22417 6.75536 1.28087 6.73927L4.60399 5.88181C4.79138 5.8335 4.96241 5.73587 5.09929 5.59908C5.23618 5.46229 5.33392 5.29133 5.38237 5.10398L6.23928 1.78085C6.25521 1.72393 6.28932 1.67379 6.33642 1.63806C6.38351 1.60234 6.44099 1.58301 6.5001 1.58301C6.5592 1.58301 6.61669 1.60234 6.66378 1.63806C6.71087 1.67379 6.74498 1.72393 6.76091 1.78085L7.61728 5.10398C7.66564 5.29143 7.76335 5.4625 7.90024 5.59939C8.03713 5.73628 8.2082 5.83399 8.39566 5.88235L11.7188 6.73873C11.7759 6.75449 11.8263 6.78856 11.8622 6.83573C11.8982 6.88289 11.9176 6.94053 11.9176 6.99981C11.9176 7.05909 11.8982 7.11673 11.8622 7.16389C11.8263 7.21105 11.7759 7.24513 11.7188 7.26089L8.39566 8.11727C8.2082 8.16563 8.03713 8.26333 7.90024 8.40023C7.76335 8.53712 7.66564 8.70819 7.61728 8.89564L6.76037 12.2188C6.74444 12.2757 6.71033 12.3258 6.66324 12.3616C6.61614 12.3973 6.55866 12.4166 6.49955 12.4166C6.44045 12.4166 6.38296 12.3973 6.33587 12.3616C6.28878 12.3258 6.25467 12.2757 6.23874 12.2188L5.38237 8.89564Z" fill="url(#paint0_linear_295_435)"/>\n<path d="M10.8335 2.125V4.29167" stroke="url(#paint1_linear_295_435)" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M11.9167 3.2085H9.75" stroke="url(#paint2_linear_295_435)" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M2.1665 9.7085V10.7918" stroke="url(#paint3_linear_295_435)" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round"/>\n<path d="M2.70833 10.25H1.625" stroke="url(#paint4_linear_295_435)" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round"/>\n<defs>\n<linearGradient id="paint0_linear_295_435" x1="1.08398" y1="1.58301" x2="11.9176" y2="12.4166" gradientUnits="userSpaceOnUse">\n<stop stop-color="#FEC163"/>\n<stop offset="1" stop-color="#DE4313"/>\n</linearGradient>\n<linearGradient id="paint1_linear_295_435" x1="10.8335" y1="2.125" x2="12.4823" y2="2.88598" gradientUnits="userSpaceOnUse">\n<stop stop-color="#FEC163"/>\n<stop offset="1" stop-color="#DE4313"/>\n</linearGradient>\n<linearGradient id="paint2_linear_295_435" x1="9.75" y1="3.2085" x2="10.511" y2="4.85728" gradientUnits="userSpaceOnUse">\n<stop stop-color="#FEC163"/>\n<stop offset="1" stop-color="#DE4313"/>\n</linearGradient>\n<linearGradient id="paint3_linear_295_435" x1="2.1665" y1="9.7085" x2="3.24638" y2="10.7053" gradientUnits="userSpaceOnUse">\n<stop stop-color="#FEC163"/>\n<stop offset="1" stop-color="#DE4313"/>\n</linearGradient>\n<linearGradient id="paint4_linear_295_435" x1="1.625" y1="10.25" x2="2.62181" y2="11.3299" gradientUnits="userSpaceOnUse">\n<stop stop-color="#FEC163"/>\n<stop offset="1" stop-color="#DE4313"/>\n</linearGradient>\n</defs>\n</svg>\n'}),M=new _.LabIcon({name:"sage-agent-internal:hands-on-icon",svgstr:'<svg width="15" height="14" viewBox="0 0 15 14" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M7.49982 2.91678C7.50051 2.68346 7.45453 2.45236 7.3646 2.23708C7.27467 2.02179 7.14259 1.82666 6.97614 1.66316C6.80969 1.49967 6.61223 1.3711 6.39537 1.28504C6.17851 1.19897 5.94662 1.15714 5.71336 1.162C5.48009 1.16686 5.25015 1.21832 5.03707 1.31335C4.82398 1.40838 4.63205 1.54506 4.47255 1.71535C4.31306 1.88564 4.18923 2.0861 4.10835 2.30495C4.02747 2.5238 3.99116 2.75661 4.00157 2.98969M7.49982 2.91678V10.5001M7.49982 2.91678C7.49913 2.68346 7.54507 2.45236 7.635 2.23708C7.72494 2.02179 7.85701 1.82666 8.02346 1.66316C8.18991 1.49967 8.38737 1.3711 8.60423 1.28504C8.8211 1.19897 9.05298 1.15714 9.28624 1.162C9.51951 1.16686 9.74945 1.21832 9.96254 1.31335C10.1756 1.40838 10.3676 1.54506 10.527 1.71535C10.6865 1.88564 10.8104 2.0861 10.8913 2.30495C10.9721 2.5238 11.0084 2.75661 10.998 2.98969C11.3409 3.07786 11.6592 3.24289 11.9289 3.47229C12.1986 3.7017 12.4125 3.98945 12.5545 4.31377C12.6964 4.63809 12.7628 4.99047 12.7484 5.34421C12.734 5.69795 12.6393 6.04379 12.4715 6.35553M4.00157 2.98969C3.65869 3.07786 3.34036 3.24289 3.0707 3.47229C2.80105 3.7017 2.58713 3.98945 2.44514 4.31377C2.30316 4.63809 2.23685 4.99047 2.25121 5.34421C2.26558 5.69795 2.36026 6.04379 2.52807 6.35553M4.00157 2.98969C4.0131 3.27187 4.09268 3.54704 4.23365 3.79175M2.52807 6.35553C2.23301 6.59524 2.00098 6.90341 1.85218 7.25324C1.70338 7.60307 1.64231 7.98396 1.67428 8.36277C1.70625 8.74158 1.8303 9.10685 2.03562 9.42679C2.24095 9.74673 2.52134 10.0117 2.8524 10.1985M2.52807 6.35553C2.63478 6.26861 2.74897 6.19187 2.86931 6.12508M2.8524 10.1985C2.81152 10.5148 2.83592 10.8362 2.92409 11.1427C3.01226 11.4492 3.16233 11.7343 3.36503 11.9806C3.56773 12.2268 3.81876 12.4289 4.10261 12.5743C4.38647 12.7197 4.69712 12.8054 5.01539 12.8261C5.33366 12.8467 5.65278 12.8019 5.95305 12.6944C6.25331 12.5869 6.52835 12.4189 6.76118 12.201C6.994 11.983 7.17967 11.7196 7.30671 11.4271C7.43376 11.1345 7.49948 10.819 7.49982 10.5001M2.8524 10.1985C3.20256 10.396 3.59774 10.5002 3.99975 10.5M7.49982 10.5001C7.50016 10.819 7.56585 11.1345 7.69289 11.4271C7.81993 11.7196 8.0056 11.983 8.23842 12.201C8.47125 12.4189 8.74629 12.5869 9.04656 12.6944C9.34683 12.8019 9.66595 12.8467 9.98421 12.8261C10.3025 12.8054 10.6131 12.7197 10.897 12.5743C11.1808 12.4289 11.4319 12.2268 11.6346 11.9806C11.8373 11.7343 11.9873 11.4492 12.0755 11.1427C12.1637 10.8362 12.1881 10.5148 12.1472 10.1985M12.4715 6.35553C12.7666 6.59524 12.9986 6.90341 13.1474 7.25324C13.2962 7.60307 13.3573 7.98396 13.3253 8.36277C13.2934 8.74158 13.1693 9.10685 12.964 9.42679C12.7587 9.74673 12.4783 10.0117 12.1472 10.1985M12.4715 6.35553C12.3648 6.26861 12.2506 6.19187 12.1303 6.12508M12.1472 10.1985C11.797 10.396 11.4018 10.5002 10.9998 10.5M9.24978 7.58341C8.76004 7.41113 8.33238 7.0975 8.02088 6.68217C7.70939 6.26684 7.52804 5.76847 7.49978 5.25008C7.47151 5.76847 7.29017 6.26684 6.97867 6.68217C6.66717 7.0975 6.23952 7.41113 5.74978 7.58341M10.7659 3.79175C10.9071 3.54709 10.987 3.27189 10.9987 2.98966" stroke="#949494" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>\n'}),I=new _.LabIcon({name:"sage-agent-internal:ask-icon",svgstr:'<svg width="15" height="14" viewBox="0 0 15 14" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M5.80232 5.25021C5.93946 4.86035 6.21016 4.53161 6.56646 4.3222C6.92276 4.1128 7.34167 4.03626 7.749 4.10613C8.15633 4.17599 8.52579 4.38777 8.79195 4.70393C9.0581 5.0201 9.20377 5.42026 9.20315 5.83354C9.20315 7.00021 7.45315 7.58354 7.45315 7.58354M7.49984 9.91683H7.50567M5.10817 11.6669C6.22151 12.238 7.50222 12.3927 8.71952 12.1031C9.93682 11.8135 11.0107 11.0986 11.7475 10.0873C12.4844 9.076 12.8358 7.83477 12.7385 6.58728C12.6412 5.3398 12.1015 4.16809 11.2167 3.2833C10.3319 2.39852 9.16023 1.85884 7.91274 1.76152C6.66526 1.6642 5.42403 2.01563 4.41273 2.7525C3.40144 3.48937 2.68657 4.5632 2.39697 5.78051C2.10736 6.99781 2.26205 8.27852 2.83317 9.39186L1.6665 12.8335L5.10817 11.6669Z" stroke="#949494" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>\n'}),N=new _.LabIcon({name:"sage-agent-internal:open-mode-selector-icon",svgstr:'<svg width="13" height="12" viewBox="0 0 13 12" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M9.5 7.5L6.5 4.5L3.5 7.5" stroke="#ADADAD" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>\n'}),D=new _.LabIcon({name:"sage-agent-internal:send-icon",svgstr:'<svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M8.00016 13.1665L8.00016 3.83317M8.00016 3.83317L3.3335 8.49984M8.00016 3.83317L12.6668 8.49984" stroke="#7A7A7A" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>\n'}),T=new _.LabIcon({name:"sage-agent-internal:stop-icon",svgstr:'<svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">\n<rect x="2.70605" y="13.7935" width="10.5874" height="10.5874" rx="3" transform="rotate(-90 2.70605 13.7935)" fill="#1A1A1A"/>\n</svg>\n'}),A=new _.LabIcon({name:"sage-agent-internal:reapply-icon",svgstr:'<svg width="12" height="12" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="var(--jp-ui-font-color1)"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <title>Reload</title> <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="Reload"> <rect id="Rectangle" fill-rule="nonzero" x="0" y="0" width="24" height="24"> </rect> <path d="M4,13 C4,17.4183 7.58172,21 12,21 C16.4183,21 20,17.4183 20,13 C20,8.58172 16.4183,5 12,5 C10.4407,5 8.98566,5.44609 7.75543,6.21762" id="Path" stroke="#999999" stroke-width="2" stroke-linecap="round"> </path> <path d="M9.2384,1.89795 L7.49856,5.83917 C7.27552,6.34441 7.50429,6.9348 8.00954,7.15784 L11.9508,8.89768" id="Path" stroke="#999999" stroke-width="2" stroke-linecap="round"> </path> </g> </g> </g></svg>'}),L=new _.LabIcon({name:"sage-agent-internal:arrow-up-icon",svgstr:'<svg width="13" height="13" viewBox="0 -4.5 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#949494"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <title>arrow_up [#337]</title> <desc>Created with Sketch.</desc> <defs> </defs> <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="Dribbble-Light-Preview" transform="translate(-260.000000, -6684.000000)" fill="#949494"> <g id="icons" transform="translate(56.000000, 160.000000)"> <path d="M223.707692,6534.63378 L223.707692,6534.63378 C224.097436,6534.22888 224.097436,6533.57338 223.707692,6533.16951 L215.444127,6524.60657 C214.66364,6523.79781 213.397472,6523.79781 212.616986,6524.60657 L204.29246,6533.23165 C203.906714,6533.6324 203.901717,6534.27962 204.282467,6534.68555 C204.671211,6535.10081 205.31179,6535.10495 205.70653,6534.69695 L213.323521,6526.80297 C213.714264,6526.39807 214.346848,6526.39807 214.737591,6526.80297 L222.294621,6534.63378 C222.684365,6535.03868 223.317949,6535.03868 223.707692,6534.63378" id="arrow_up-[#337]"> </path> </g> </g> </g> </g></svg>'}),R=new _.LabIcon({name:"sage-agent-internal:arrow-down-icon",svgstr:'<svg width="13" height="13" viewBox="0 -4.5 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#949494"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <title>arrow_down [#338]</title> <desc>Created with Sketch.</desc> <defs> </defs> <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="Dribbble-Light-Preview" transform="translate(-220.000000, -6684.000000)" fill="#949494"> <g id="icons" transform="translate(56.000000, 160.000000)"> <path d="M164.292308,6524.36583 L164.292308,6524.36583 C163.902564,6524.77071 163.902564,6525.42619 164.292308,6525.83004 L172.555873,6534.39267 C173.33636,6535.20244 174.602528,6535.20244 175.383014,6534.39267 L183.70754,6525.76791 C184.093286,6525.36716 184.098283,6524.71997 183.717533,6524.31405 C183.328789,6523.89985 182.68821,6523.89467 182.29347,6524.30266 L174.676479,6532.19636 C174.285736,6532.60124 173.653152,6532.60124 173.262409,6532.19636 L165.705379,6524.36583 C165.315635,6523.96094 164.683051,6523.96094 164.292308,6524.36583" id="arrow_down-[#338]"> </path> </g> </g> </g> </g></svg>'}),B=new _.LabIcon({name:"sage-agent-internal:approve-icon",svgstr:'<svg width="15" height="16" viewBox="0 0 15 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path fill="none" d="M12.5 4.25L5.625 11.125L2.5 8" stroke="#22C55E" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>'}),P=new _.LabIcon({name:"sage-agent-internal:reject-icon",svgstr:'<svg width="15" height="16" viewBox="0 0 15 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M11.25 4.25L3.75 11.75M3.75 4.25L11.25 11.75" stroke="#FF2323" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>'}),j=new _.LabIcon({name:"sage-agent-internal:run-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">\n <path d="M4 2.91583C4 2.52025 4.43762 2.28133 4.77038 2.49524L12.6791 7.57941C12.9852 7.77623 12.9852 8.22377 12.6791 8.42059L4.77038 13.5048C4.43762 13.7187 4 13.4798 4 13.0842V2.91583Z" fill="#3B82F6" stroke="#3B82F6" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M13.1018 5.35787L6.45639 9.55022L5.34214 7.88071" stroke="#1A1A1A" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>'});new _.LabIcon({name:"sage-agent-internal:check-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="15" viewBox="0 0 14 15" fill="none">\n<path d="M11.6663 4L5.24967 10.4167L2.33301 7.5" stroke="#22C55E" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>'}),new _.LabIcon({name:"sage-agent-internal:dashed-circle-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="15" viewBox="0 0 14 15" fill="none">\n<circle cx="7" cy="7.5" r="6.25" stroke="url(#paint0_linear_549_10580)" stroke-width="1.5" stroke-linejoin="round" stroke-dasharray="3 3"/>\n<defs>\n<linearGradient id="paint0_linear_549_10580" x1="0" y1="0.5" x2="14" y2="14.5" gradientUnits="userSpaceOnUse">\n<stop stop-color="#FEC163"/>\n<stop offset="1" stop-color="#DE4313"/>\n</linearGradient>\n</defs>\n</svg>'});class ${constructor(){this.dialogElement=null,this.parentElement=null,this.callbacks=null,this.diffCells=[],this.resolvePromise=null,this.embedded=!1,this.isRunContext=!1,this.currentNotebookPath=null,this.cellButtonElements=new Map,this.subscriptions=[]}setCallbacks(e){this.callbacks=e}updateNotebookPath(e){this.currentNotebookPath=e}async showDialog(e,t=null,n=!1,o=!1){var s;const i=C.getCurrentState(),a=Array.from(i.pendingDiffs.values());this.diffCells=a.filter(e=>!t||e.notebookId===t).map(e=>{var t;return{...e,displaySummary:e.summary||(null===(t=e.metadata)||void 0===t?void 0:t.summary)||`${e.type} cell`}}),this.parentElement=e,this.embedded=n,this.isRunContext=o,this.currentNotebookPath=t,this.setupDiffStateSubscriptions(),this.createDialog(),this.addToChatHistory();const r=null===(s=m.AppStateService.getChatContainerSafe())||void 0===s?void 0:s.chatWidget.llmStateDisplay;r&&r.showPendingDiffs(t,o);const l=m.AppStateService.getDiffNavigationWidgetSafe();return l&&l.showPendingDiffs(t,o),new Promise(e=>{this.resolvePromise=e})}isDialogOpen(){return null!==this.dialogElement}createDialog(){var e,t;if(!this.parentElement)return void console.error("Parent element not provided for diff approval dialog");this.dialogElement=document.createElement("div"),this.dialogElement.className=this.embedded?"sage-ai-diff-approval-dialog-embedded":"sage-ai-diff-approval-dialog";const n=document.createElement("p"),o=this.currentNotebookPath?` in notebook "${this.currentNotebookPath.split("/").pop()}"`:"";n.textContent=`Review and approve/reject the following changes${o}:`,this.embedded&&(n.className="sage-ai-diff-summary");const s=document.createElement("div");s.className="sage-ai-diff-list",this.diffCells.forEach(e=>{const t=this.createDiffCellItem(e);s.appendChild(t)}),this.dialogElement.appendChild(s);const i=document.createElement("div");i.className=this.embedded?"sage-ai-inline-diff-actions":"sage-ai-diff-approval-actions";const a=document.createElement("button");a.className="sage-ai-reject-button",a.textContent="Reject All",a.onclick=()=>this.rejectAll();const r=document.createElement("button");r.className="sage-ai-confirm-button",r.textContent=this.isRunContext?"Approve All and Run":"Approve All",r.onclick=()=>this.approveAll(),i.appendChild(a),i.appendChild(r),this.dialogElement.appendChild(i),this.parentElement.appendChild(this.dialogElement),null===(t=null===(e=m.AppStateService.getChatContainerSafe())||void 0===e?void 0:e.chatWidget)||void 0===t||t.getMessageComponent().handleScroll()}addToChatHistory(){const e=m.AppStateService.getChatContainerSafe();(null==e?void 0:e.chatWidget)?(e.chatWidget.getMessageComponent().addDiffApprovalDialog(this.currentNotebookPath||void 0,this.diffCells),console.log("[DiffApprovalDialog] Added to chat history for persistence")):console.warn("[DiffApprovalDialog] Could not add to chat history - chat components not available")}static createHistoricalDialog(e,t){const n=new $,o=m.AppStateService.getNotebookDiffManager().diffApprovalDialog.callbacks;o&&n.setCallbacks(o),n.diffCells=e,n.currentNotebookPath=t||null,n.embedded=!0,n.isRunContext=!1;const s=document.createElement("div");s.className="sage-ai-diff-approval-dialog-embedded sage-ai-diff-approval-historical";const i=document.createElement("div");return i.className="sage-ai-diff-list",n.diffCells.forEach(e=>{const t=n.createDiffCellItem(e,!0);i.appendChild(t)}),s.appendChild(i),s}createDiffCellItem(e,t=!1){var n;const o=document.createElement("div");o.className="sage-ai-diff-cell-item",o.dataset.cellId=e.cellId;const s=document.createElement("div");s.className="sage-ai-diff-cell-header";const i=document.createElement("span");i.className="sage-ai-diff-content-collapse-icon",i.innerHTML=H,i.onclick=()=>r.style.display="none"===r.style.display?"block":"none",s.appendChild(i);const a=document.createElement("span");a.className="sage-ai-diff-cell-id-label",a.textContent=e.cellId,a.onclick=()=>m.AppStateService.getNotebookTools().scrollToCellById(e.cellId),s.appendChild(a),o.appendChild(s);const r=document.createElement("div");r.className="sage-ai-diff-content",r.title="Click to expand/collapse diff content",this.createMergeViewInContainer(r,e.originalContent||"",e.newContent||"");const l=((null===(n=r.querySelector(".cm-content"))||void 0===n?void 0:n.children.length)||0)+(r.querySelectorAll(".cm-deletedLine").length||0)>9,c=r.querySelector(".cm-collapsedLines");if(l||c){r.style.cursor="pointer";const e=document.createElement("div");e.className="sage-ai-diff-gradient-overlay",c&&!l&&(e.style.display="none",r.classList.add("sage-ai-diff-expanded"));const t='<svg width="14px" height="14px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M5.70711 9.71069C5.31658 10.1012 5.31658 10.7344 5.70711 11.1249L10.5993 16.0123C11.3805 16.7927 12.6463 16.7924 13.4271 16.0117L18.3174 11.1213C18.708 10.7308 18.708 10.0976 18.3174 9.70708C17.9269 9.31655 17.2937 9.31655 16.9032 9.70708L12.7176 13.8927C12.3271 14.2833 11.6939 14.2832 11.3034 13.8927L7.12132 9.71069C6.7308 9.32016 6.09763 9.32016 5.70711 9.71069Z" fill="#999999"></path> </g></svg>';e.innerHTML=t,r.addEventListener("scroll",()=>{const t=r.scrollTop,n=r.scrollHeight-t-r.clientHeight;e.style.display=n<=20?"none":"block"});let n=!!c,o=!1;r.onclick=()=>{if(!o)return c&&(r.querySelectorAll(".cm-collapsedLines").forEach(e=>{o=!0,e.click(),o=!1}),n)?(n=!1,r.classList.add("sage-ai-diff-expanded"),void(e.style.display="none")):void(r.classList.contains("sage-ai-diff-expanded")?(r.classList.remove("sage-ai-diff-expanded"),r.title="Click to expand diff content",e.style.display="flex"):(r.classList.add("sage-ai-diff-expanded"),r.title="Click to collapse diff content",e.style.display="none"))},r.appendChild(e)}o.appendChild(r);const d=document.createElement("div");d.className="sage-ai-diff-hover-buttons";const h=this.createReapplyButton(e,t);if(!t){const t=document.createElement("button");t.className="sage-ai-diff-approve-button",t.innerHTML='<svg width="15" height="16" viewBox="0 0 15 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M12.5 4.25L5.625 11.125L2.5 8" stroke="#22C55E" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>',t.title="Approve this change";const n=document.createElement("button");n.className="sage-ai-diff-reject-button",n.innerHTML='<svg width="15" height="16" viewBox="0 0 15 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M11.25 4.25L3.75 11.75M3.75 4.25L11.25 11.75" stroke="#FF2323" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>',n.title="Reject this change";const s=document.createElement("button");s.className="sage-ai-diff-run-button",s.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">\n <path d="M4 2.91583C4 2.52025 4.43762 2.28133 4.77038 2.49524L12.6791 7.57941C12.9852 7.77623 12.9852 8.22377 12.6791 8.42059L4.77038 13.5048C4.43762 13.7187 4 13.4798 4 13.0842V2.91583Z" fill="#3B82F6" stroke="#3B82F6" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M13.1018 5.35787L6.45639 9.55022L5.34214 7.88071" stroke="#1A1A1A" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>',s.title="Apply this change and run the cell immediately",t.onclick=t=>{t.stopPropagation(),this.approveCell(e.cellId)},n.onclick=t=>{t.stopPropagation(),this.rejectCell(e.cellId)},s.onclick=t=>{t.stopPropagation(),this.runCell(e.cellId)},d.appendChild(n),d.appendChild(t),d.appendChild(s),this.cellButtonElements.set(e.cellId,{approveButton:t,rejectButton:n,runButton:s,reapplyButton:h,hoverButtons:d,cellItem:o}),o.style.position="relative"}return s.appendChild(d),d.appendChild(h),o}createReapplyButton(e,t=!1){const n=document.createElement("button");return n.className="sage-ai-diff-reapply-button",n.innerHTML=A.svgstr,n.title="Reapply this change",n.onclick=()=>{var t;null===(t=this.callbacks)||void 0===t||t.reapplyDiff(e)},t&&"edit"===e.type||n.classList.add("hidden"),n}approveCell(e){this.callbacks&&(this.callbacks.onApprove([e]),C.updateDiffState(e,!0,this.currentNotebookPath),this.callbacks.applyApprovedDiffs(this.currentNotebookPath,[e]))}rejectCell(e){this.callbacks&&(this.callbacks.onReject([e]),C.updateDiffState(e,!1,this.currentNotebookPath),this.callbacks.handleRejectedDiffs(this.currentNotebookPath))}async approveAll(){var e,t,n;if(this.callbacks){const o=this.showLoadingOverlay("Applying changes...");try{this.callbacks.onApproveAll(this.currentNotebookPath),this.diffCells.forEach(e=>{C.updateDiffState(e.cellId,!0,this.currentNotebookPath)}),this.isRunContext&&this.callbacks.setExecuteApprovedCells(!0),o&&(null===(e=this.dialogElement)||void 0===e?void 0:e.contains(o))&&this.dialogElement.removeChild(o),await this.callbacks.applyApprovedDiffs(this.currentNotebookPath),o&&(null===(t=this.dialogElement)||void 0===t?void 0:t.contains(o))&&this.dialogElement.removeChild(o)}catch(e){console.error("Error applying approved diffs:",e),this.showError("Failed to apply changes. Please try again.")}finally{o&&(null===(n=this.dialogElement)||void 0===n?void 0:n.contains(o))&&this.dialogElement.removeChild(o)}}}async rejectAll(){var e,t;if(this.callbacks){const n=this.showLoadingOverlay("Rejecting changes...");try{this.callbacks.onRejectAll(this.currentNotebookPath),this.diffCells.forEach(e=>{C.updateDiffState(e.cellId,!1,this.currentNotebookPath)}),await this.callbacks.handleRejectedDiffs(this.currentNotebookPath),n&&(null===(e=this.dialogElement)||void 0===e?void 0:e.contains(n))&&this.dialogElement.removeChild(n)}catch(e){console.error("Error handling rejected diffs:",e),this.showError("Failed to reject changes. Please try again.")}finally{n&&(null===(t=this.dialogElement)||void 0===t?void 0:t.contains(n))&&this.dialogElement.removeChild(n)}}}showLoadingOverlay(e){return document.createElement("div")}showError(e){const t=document.createElement("div");t.className="sage-ai-error-message",t.style.color="#ff4d4f",t.style.padding="10px",t.style.margin="10px",t.style.borderRadius="4px",t.style.backgroundColor="rgba(255,77,79,0.1)",t.textContent=e,this.dialogElement&&(this.dialogElement.prepend(t),setTimeout(()=>{var e;t.parentNode===this.dialogElement&&(null===(e=this.dialogElement)||void 0===e||e.removeChild(t))},5e3))}async checkAllCellsStatus(){const e=C.getCurrentState();let t=!0,n=!1;this.diffCells.forEach(o=>{const s=e.pendingDiffs.get(o.cellId);(null==s?void 0:s.userDecision)?"run"!==s.userDecision||s.runResult||(n=!0):t=!1}),t&&(n||(console.log("FINISHED PROCESSING ALL DIFFS =================== FINISHED ---- EMITTING"),console.log(C.getCurrentState()),m.AppStateService.getNotebookDiffManager()._finishedProcessingDiffs.emit(o.fY.APPROVED),this.close()))}async close(){this.dialogElement=null,this.cellButtonElements.clear()}setupDiffStateSubscriptions(){this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],this.diffCells.forEach(e=>{const t=C.getCellStateChanges$(e.cellId).subscribe(e=>{e&&this.updateCellUI(e.cellId)});this.subscriptions.push(t)});const e=C.diffState$.subscribe(e=>{this.diffCells.forEach(t=>{const n=e.pendingDiffs.get(t.cellId);n&&this.updateCellButtonState(t.cellId,n)}),this.checkAllCellsStatus()});this.subscriptions.push(e)}updateCellUI(e){var t;const n=null===(t=this.cellButtonElements.get(e))||void 0===t?void 0:t.cellItem,o=C.getCurrentState().pendingDiffs.get(e);if(!n)return;n.classList.remove("sage-ai-diff-approved","sage-ai-diff-rejected","sage-ai-diff-run"),"run"===(null==o?void 0:o.userDecision)?n.classList.add("sage-ai-diff-run"):!0===(null==o?void 0:o.approved)?n.classList.add("sage-ai-diff-approved"):!1===(null==o?void 0:o.approved)&&n.classList.add("sage-ai-diff-rejected");const s=this.cellButtonElements.get(e);if(s){const e="run"===(null==o?void 0:o.userDecision),t=null==o?void 0:o.runResult,n=!0===(null==o?void 0:o.approved),i=!1===(null==o?void 0:o.approved),a=void 0===(null==o?void 0:o.approved);[s.approveButton,s.rejectButton,s.runButton,s.reapplyButton].forEach(e=>{e.classList.remove("disabled"),e.classList.add("hidden")}),t?s.reapplyButton.classList.remove("hidden"):e?(s.runButton.classList.remove("hidden"),s.runButton.classList.add("disabled"),s.reapplyButton.classList.remove("hidden")):n?(s.approveButton.classList.remove("hidden"),s.approveButton.classList.add("disabled"),s.reapplyButton.classList.remove("hidden")):i?(s.rejectButton.classList.remove("hidden"),s.rejectButton.classList.add("disabled"),s.reapplyButton.classList.remove("hidden")):a&&(s.approveButton.classList.remove("hidden"),s.rejectButton.classList.remove("hidden"),s.runButton.classList.remove("hidden")),"edit"!==(null==o?void 0:o.type)&&s.reapplyButton.classList.add("hidden")}}async runCell(e){if(this.callbacks){C.updateDiffStateToRun(e,this.currentNotebookPath),this.callbacks.onApprove([e]),await this.callbacks.applyApprovedDiffs(this.currentNotebookPath,[e]);const t=m.AppStateService.getNotebookTools();if(t)try{const n=await t.run_cell({cell_id:e,notebook_path:this.currentNotebookPath});C.updateDiffStateResult(e,n.slice(0,5e3))}catch(t){C.updateDiffStateResult(e,{}),console.error(t)}}}updateCellButtonState(e,t){const n=this.cellButtonElements.get(e);if(!n)return;const{hoverButtons:o}=n;"run"!==t.userDecision||t.runResult?(this.hideSpinnerForCell(e,o),this.updateCellUI(e)):this.showSpinnerForCell(e,o)}showSpinnerForCell(e,t){t.querySelectorAll("button").forEach(e=>{e.classList.add("hidden")});let n=t.querySelector(".sage-ai-diff-spinner");n||(n=this.createSpinnerElement(),t.appendChild(n)),n.classList.remove("hidden")}hideSpinnerForCell(e,t){t.querySelectorAll("button").forEach(e=>{e.classList.add("hidden")});const n=t.querySelector(".sage-ai-diff-spinner");n&&n.classList.add("hidden")}createSpinnerElement(){const e=document.createElement("div");return e.className="sage-ai-diff-spinner",e}createMergeViewInContainer(e,t,n){const o=(0,y.unifiedMergeView)({original:t,gutter:!1,mergeControls:!1,highlightChanges:!0,syntaxHighlightDeletions:!0,allowInlineDiffs:!0,collapseUnchanged:{}}),s=[(0,w.Hg)(),S.jupyterTheme,o,k.EditorState.readOnly.of(!0),b.EditorView.theme({".cm-scroller":{borderRadius:"0 0 10px 10px !important"},".cm-content":{padding:"0px !important"}}),b.EditorView.editable.of(!1)],i=k.EditorState.create({doc:n,extensions:s});new b.EditorView({state:i,parent:e}),t?e.classList.remove("code-mirror-empty-original-content"):e.classList.add("code-mirror-empty-original-content")}}const H='<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 10 10" fill="none"><path d="M2.62081 5.95419C2.58175 5.99293 2.55076 6.03901 2.5296 6.08979C2.50845 6.14056 2.49756 6.19502 2.49756 6.25003C2.49756 6.30503 2.50845 6.35949 2.5296 6.41027C2.55076 6.46104 2.58175 6.50712 2.62081 6.54586L4.70414 8.62919C4.74288 8.66825 4.78896 8.69924 4.83973 8.7204C4.89051 8.74155 4.94497 8.75244 4.99997 8.75244C5.05498 8.75244 5.10944 8.74155 5.16021 8.7204C5.21099 8.69924 5.25707 8.66825 5.29581 8.62919L7.37914 6.54586C7.41819 6.50712 7.44919 6.46104 7.47035 6.41027C7.4915 6.35949 7.50239 6.30503 7.50239 6.25003C7.50239 6.19502 7.4915 6.14056 7.47035 6.08979C7.44919 6.03901 7.41819 5.99293 7.37914 5.95419C7.34041 5.91514 7.29432 5.88414 7.24355 5.86299C7.19277 5.84183 7.13831 5.83094 7.08331 5.83094C7.0283 5.83094 6.97384 5.84183 6.92307 5.86299C6.87229 5.88414 6.82621 5.91514 6.78747 5.95419L4.99997 7.74586L3.21247 5.95419C3.17374 5.91514 3.12766 5.88414 3.07688 5.86299C3.02611 5.84183 2.97165 5.83094 2.91664 5.83094C2.86164 5.83094 2.80718 5.84183 2.7564 5.86299C2.70563 5.88414 2.65954 5.91514 2.62081 5.95419ZM4.70414 1.37086L2.62081 3.45419C2.58196 3.49304 2.55114 3.53916 2.53012 3.58992C2.50909 3.64068 2.49827 3.69508 2.49827 3.75003C2.49827 3.86098 2.54235 3.9674 2.62081 4.04586C2.65966 4.08471 2.70578 4.11553 2.75654 4.13655C2.8073 4.15758 2.8617 4.1684 2.91664 4.1684C3.0276 4.1684 3.13401 4.12432 3.21247 4.04586L4.99997 2.25419L6.78747 4.04586C6.82621 4.08491 6.87229 4.11591 6.92307 4.13706C6.97384 4.15822 7.0283 4.16911 7.08331 4.16911C7.13831 4.16911 7.19277 4.15822 7.24355 4.13706C7.29432 4.11591 7.34041 4.08491 7.37914 4.04586C7.41819 4.00712 7.44919 3.96104 7.47035 3.91027C7.4915 3.85949 7.50239 3.80503 7.50239 3.75003C7.50239 3.69502 7.4915 3.64056 7.47035 3.58979C7.44919 3.53901 7.41819 3.49293 7.37914 3.45419L5.29581 1.37086C5.25707 1.33181 5.21099 1.30081 5.16021 1.27965C5.10944 1.2585 5.05498 1.24761 4.99997 1.24761C4.94497 1.24761 4.89051 1.2585 4.83973 1.27965C4.78896 1.30081 4.74288 1.33181 4.70414 1.37086Z" fill="#999999"/></svg>';var U=n(628),O=n(7110);const F=/<(SNIPPET_CONTEXT|DATA_CONTEXT|VARIABLE_CONTEXT|CELL_CONTEXT)>\s*#\{([^}]+)\}\s*<\/\1>/g;function V(e){const t=function(e){switch(e){case"snippets":default:return"SNIPPET_CONTEXT";case"data":return"DATA_CONTEXT";case"variable":return"VARIABLE_CONTEXT";case"cell":return"CELL_CONTEXT"}}(e.type);return`<${t}>#{${e.id}}</${t}>`}function W(e){const t=O.ContextService.getInstance().getCurrentContextItems();return e.replace(F,(e,n,o)=>{const s=t.get(o),i=function(e){switch(e){case"SNIPPET_CONTEXT":return"sage-ai-mention-template";case"DATA_CONTEXT":return"sage-ai-mention-data";case"VARIABLE_CONTEXT":return"sage-ai-mention-variable";case"CELL_CONTEXT":return"sage-ai-mention-cell";default:return"sage-ai-mention-default"}}(n);if(s){const e=s.name.replace(/\s+/g,"_");return`<span class="sage-ai-mention ${i}" title="${s.description||s.name}" data-context-id="${o}">@${e}</span>`}return`<span class="sage-ai-mention ${i}" title="Context ID: ${o}" data-context-id="${o}">@${o}</span>`})}var q=n(1563),z=n(113);class K{static hasContent(e){const t=K.getCurrentNotebookState(e);return!!t&&t.some(e=>(e.content||"").trim().length>0)}static getCacheKey(e){return`${K.CACHE_KEY_PREFIX}:${e}`}static getCurrentNotebookState(e){const t=e||m.AppStateService.getCurrentNotebookId();if(!t)return console.warn("[NotebookCellStateService] No current notebook ID available"),null;try{const e=m.AppStateService.getNotebookTools().read_cells({notebook_path:t,include_outputs:!0,include_metadata:!0});return e&&e.cells?e.cells.map((e,t)=>({id:e.id,trackingId:e.trackingId||e.id,type:e.type,content:e.content||"",execution_count:e.execution_count,index:t,outputs:e.outputs})):[]}catch(e){return console.error("[NotebookCellStateService] Error getting current notebook state:",e),null}}static async cacheCurrentNotebookState(e){const t=e||m.AppStateService.getCurrentNotebookId();if(!t)return void console.warn("[NotebookCellStateService] No current notebook ID available for caching");const n=K.getCurrentNotebookState(t);null!==n?await this.cacheNotebookState(t,n):console.warn("[NotebookCellStateService] Could not get current notebook state for caching")}static async cacheNotebookState(e,t){const n=t.filter(e=>e.content&&e.content.trim().length>0),o={notebookId:e,cells:n,timestamp:Date.now()};try{const s=K.getCacheKey(e);await q.K.setObjectValue(s,o),console.log(`[NotebookCellStateService] Cached state for notebook ${e} with ${n.length} cells (filtered from ${t.length} total)`)}catch(e){console.error("[NotebookCellStateService] Error caching notebook state:",e)}}static async getCachedNotebookState(e){const t=e||m.AppStateService.getCurrentNotebookId();if(!t)return console.warn("[NotebookCellStateService] No current notebook ID available for getting cached state"),null;try{const e=K.getCacheKey(t);return await q.K.getObjectValue(e,null)}catch(e){return console.error("[NotebookCellStateService] Error getting cached notebook state:",e),null}}static async detectChanges(e){const t=e||m.AppStateService.getCurrentNotebookId();if(!t)return console.warn("[NotebookCellStateService] No current notebook ID available for change detection"),[];if(!K.hasContent(t))return console.log("[NotebookCellStateService] Notebook has no meaningful content - no diffs to report"),[];const n=K.getCurrentNotebookState(t),o=await K.getCachedNotebookState(t);if(!n)return console.warn("[NotebookCellStateService] Could not get current state for change detection"),[];const s=n.filter(e=>(e.content||"").trim().length>0);if(console.log(`[NotebookCellStateService] Current cells with content: ${s.length}`),!o||!o.cells)return console.log("[NotebookCellStateService] No cached state found - caching current state without generating diffs"),await K.cacheCurrentNotebookState(t),[];const i=o.cells.filter(e=>(e.content||"").trim().length>0);console.log(`[NotebookCellStateService] Cached cells with content: ${i.length}`);const a=[],r=new Map,l=new Map;for(const e of i){const t=e.trackingId||e.id;r.set(t,e)}for(const e of s){const t=e.trackingId||e.id;l.set(t,e)}console.log(`[NotebookCellStateService] Cached cells by tracking ID: [${Array.from(r.keys()).join(", ")}]`),console.log(`[NotebookCellStateService] Current cells by tracking ID: [${Array.from(l.keys()).join(", ")}]`);for(const e of s){const t=e.trackingId||e.id,n=r.get(t);if(n){const o=(e.content||"").trim(),s=(n.content||"").trim()!==o,i=Math.abs((n.index||0)-(e.index||0))>1;if(s||i){console.log(`[NotebookCellStateService] Detected modified cell: ${t} (content changed: ${s}, position changed: ${i})`);const o=z.createPatch(`cell_${e.trackingId||e.id}`,n.content,e.content,`Before (execution ${n.execution_count||"none"})`,`After (execution ${e.execution_count||"none"})`);a.push({cellId:e.id,trackingId:e.trackingId,type:i&&!s?"moved":"modified",oldContent:n.content,newContent:e.content,oldIndex:n.index,newIndex:e.index,diff:o})}}else(e.content||"").trim().length>0&&(console.log(`[NotebookCellStateService] Detected new cell: ${t}`),a.push({cellId:e.id,trackingId:e.trackingId,type:"added",newContent:e.content,newIndex:e.index,diff:`+ Added new ${e.type} cell: ${e.content.substring(0,100)}${e.content.length>100?"...":""}`}))}for(const e of i){const t=e.trackingId||e.id;l.has(t)||(console.log(`[NotebookCellStateService] Detected removed cell: ${t}`),a.push({cellId:e.id,trackingId:e.trackingId,type:"removed",oldContent:e.content,oldIndex:e.index,diff:`- Removed ${e.type} cell: ${e.content.substring(0,100)}${e.content.length>100?"...":""}`}))}return console.log(`[NotebookCellStateService] Total changes detected: ${a.length}`),a}static generateXMLDiff(e){const t=e.trackingId||e.cellId;let n=`<diff - (${t})>\n`;switch(e.type){case"added":{const t=(e.newContent||"").split("\n");t.forEach((e,o)=>{(e.trim()||o<t.length-1)&&(n+=` <diff - add - line ${o+1}>\n`,n+=` ${e}\n`,n+=` </diff - add - line ${o+1}>\n`)});break}case"removed":{const t=(e.oldContent||"").split("\n");t.forEach((e,o)=>{(e.trim()||o<t.length-1)&&(n+=` <diff - remove - line ${o+1}>\n`,n+=` ${e}\n`,n+=` </diff - remove - line ${o+1}>\n`)});break}case"modified":case"moved":{const t=e.oldContent||"",o=e.newContent||"",s=t.split("\n"),i=o.split("\n"),a=Math.max(s.length,i.length);for(let e=0;e<a;e++){const t=e<s.length?s[e]:void 0,o=e<i.length?i[e]:void 0,a=e+1;void 0===t&&void 0!==o?(n+=` <diff - add - line ${a}>\n`,n+=` ${o}\n`,n+=` </diff - add - line ${a}>\n`):void 0!==t&&void 0===o?(n+=` <diff - remove - line ${a}>\n`,n+=` ${t}\n`,n+=` </diff - remove - line ${a}>\n`):t!==o&&(n+=` <diff - edit - line ${a}>\n`,n+=` removed: ${t}\n`,n+=` added: ${o}\n`,n+=` </diff - edit - line ${a}>\n`)}"moved"===e.type&&(n+=" <diff - move>\n",n+=` from_position: ${e.oldIndex}\n`,n+=` to_position: ${e.newIndex}\n`,n+=" </diff - move>\n");break}}return n+=`</diff - (${t})>\n`,n}static generateChangeSummaryMessage(e){if(0===e.length)return"";let t="\n\n=== NOTEBOOK CHANGES SINCE LAST MESSAGE ===\n\n";t+=`Detected ${e.length} change(s) in the notebook:\n\n`;for(const n of e)t+=K.generateXMLDiff(n),t+="\n";return t+="=== END NOTEBOOK CHANGES ===\n\n",t}static async initializeForNotebook(e){const t=e||m.AppStateService.getCurrentNotebookId();t?(await K.clearCachedState(t),K.hasContent(t)?(await K.cacheCurrentNotebookState(t),console.log(`[NotebookCellStateService] Initialized baseline state for notebook ${t}`)):console.log(`[NotebookCellStateService] Notebook ${t} has no content - skipping baseline cache`)):console.warn("[NotebookCellStateService] No current notebook ID available for initialization")}static debugCurrentState(e){const t=K.getCurrentNotebookState(e),n=e||m.AppStateService.getCurrentNotebookId();console.log(`[NotebookCellStateService] DEBUG - Current state for notebook: ${n}`),t?(console.log(` Total cells: ${t.length}`),t.forEach((e,t)=>{const n=e.content||"",o=n.slice(0,50).replace(/\n/g,"\\n");console.log(` Cell ${t}: id="${e.id}", trackingId="${e.trackingId}", type="${e.type}", content="${o}${n.length>50?"...":""}"`)})):console.log(" No current state available")}static async clearCachedState(e){const t=e||m.AppStateService.getCurrentNotebookId();if(t)try{const e=K.getCacheKey(t);await q.K.removeValue(e),console.log(`[NotebookCellStateService] Cleared cached state for notebook ${t}`)}catch(e){console.error("[NotebookCellStateService] Error clearing cached state:",e)}else console.warn("[NotebookCellStateService] No current notebook ID available for clearing cache")}}K.CACHE_KEY_PREFIX="notebook-cell-state";class G{constructor(){this.checkpoints=new Map,this.currentNotebookId=null,this.currentCheckpoint=null,console.log("[CheckpointManager] Initialized with cached data"),this.initialize()}static getInstance(){return G.instance||(G.instance=new G),G.instance}setCurrentNotebookId(e){this.currentNotebookId=e,console.log("[CheckpointManager] Set current notebook ID:",e)}createCheckpoint(e,t,n,o,s){if(!this.currentNotebookId)throw new Error("No current notebook ID set");const i={id:`checkpoint_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),userMessage:e,userMessageId:s,messageHistory:[...t],notebookState:this.captureNotebookState(),contexts:new Map(n),notebookId:this.currentNotebookId,actionHistory:[]};this.currentCheckpoint=i,this.checkpoints.has(this.currentNotebookId)||this.checkpoints.set(this.currentNotebookId,[]);const a=this.checkpoints.get(this.currentNotebookId);a.push(i);let r=null;for(let e=t.length-1;e>=0;e--){const n=t[e];if("user"===n.role&&n.id&&n.id!==s){r=n;break}}if(r){const e=a.find(e=>e.userMessageId===(null==r?void 0:r.id));e&&(e.nextCheckpointId=i.id)}return console.log("[CheckpointManager] Created checkpoint:",i.id),console.log("[CheckpointManager] Total checkpoints for notebook:",a.length),console.log("[CheckpointManager] Captured",i.actionHistory.length,"actions"),this.saveToStorage(),i}addActionToCurrentCheckpoint(e){if(!this.currentCheckpoint||!this.currentNotebookId)return void console.warn("[CheckpointManager] No current checkpoint to add action to");const t=this.checkpoints.get(this.currentNotebookId);if(!t)return void console.warn("[CheckpointManager] No checkpoints found for current notebook");const n=t.find(e=>{var t;return e.id===(null===(t=this.currentCheckpoint)||void 0===t?void 0:t.id)});n?(n.actionHistory.push(e),console.log("[CheckpointManager] Added action to checkpoint:",e.description),console.log("[CheckpointManager] Total actions in checkpoint:",n.actionHistory.length),this.saveToStorage()):console.warn("[CheckpointManager] Current checkpoint not found")}getCheckpoints(){return this.currentNotebookId&&this.checkpoints.get(this.currentNotebookId)||[]}findCheckpointByUserMessage(e){return this.currentNotebookId&&(this.checkpoints.get(this.currentNotebookId)||[]).find(t=>t.userMessage===e)||null}findCheckpointByUserMessageId(e){return this.currentNotebookId&&(this.checkpoints.get(this.currentNotebookId)||[]).find(t=>t.userMessageId===e)||null}clearCheckpoints(){this.currentNotebookId&&(this.checkpoints.delete(this.currentNotebookId),console.log("[CheckpointManager] Cleared checkpoints for notebook:",this.currentNotebookId),this.saveToStorage())}clearCheckpointsAfter(e){if(!this.currentNotebookId)return;const t=this.checkpoints.get(this.currentNotebookId)||[],n=t.findIndex(t=>t.id===e);if(-1!==n){const o=t.slice(0,n+1);this.checkpoints.set(this.currentNotebookId,o),console.log("[CheckpointManager] Cleared checkpoints after:",e),console.log("[CheckpointManager] Remaining checkpoints:",o.length),this.saveToStorage()}}captureNotebookState(){if(!this.currentNotebookId)return[];try{return K.getCurrentNotebookState(this.currentNotebookId)||[]}catch(e){return console.error("[CheckpointManager] Error capturing notebook state:",e),[]}}async saveToStorage(){try{const e={};for(const[t,n]of this.checkpoints.entries()){const o=n.map(e=>({...e,contexts:e.contexts?Object.fromEntries(e.contexts):{}}));e[t]=o}await q.K.setObjectValue(q.s.NOTEBOOK_CHECKPOINTS,e),console.log("[CheckpointManager] Saved checkpoints to StateDB storage")}catch(e){console.error("[CheckpointManager] Error saving checkpoints to StateDB:",e)}}async loadFromStorage(){try{const e=await q.K.getObjectValue(q.s.NOTEBOOK_CHECKPOINTS,{});if(e&&Object.keys(e).length>0){this.checkpoints=new Map;for(const[t,n]of Object.entries(e)){const e=n.map(e=>({...e,contexts:e.contexts?new Map(Object.entries(e.contexts)):new Map}));this.checkpoints.set(t,e)}console.log("[CheckpointManager] Loaded checkpoints from StateDB storage"),console.log(`[CheckpointManager] Loaded checkpoints for ${this.checkpoints.size} notebooks`)}else console.log("[CheckpointManager] No stored checkpoints found in StateDB")}catch(e){console.error("[CheckpointManager] Error loading checkpoints from StateDB:",e),this.checkpoints=new Map}}async initialize(){await this.loadFromStorage(),console.log("[CheckpointManager] Initialized with cached data")}}class J{constructor(){this.modalElement=null,this.onRestoreCallback=null,this.onCancelCallback=null}show(e,t,n){this.onRestoreCallback=t,this.onCancelCallback=n,this.createModal(e),this.attachEventListeners(),document.body.appendChild(this.modalElement),this.modalElement.classList.add("visible"),console.log("[CheckpointRestorationModal] Modal shown for checkpoint:",e.id)}hide(){this.modalElement&&(this.modalElement.classList.remove("visible"),setTimeout(()=>{this.modalElement&&this.modalElement.parentNode&&this.modalElement.parentNode.removeChild(this.modalElement),this.modalElement=null},200))}createModal(e){this.modalElement=document.createElement("div"),this.modalElement.className="sage-ai-checkpoint-modal",this.addStyles(),console.log("[CheckpointRestorationModal] Undoing all actions from checkpoint chain");const t=G.getInstance().getCheckpoints(),n=(e,o=[])=>{if(e.nextCheckpointId){const s=t.find(t=>t.id===e.nextCheckpointId);s&&n(s,o)}return o.push(e),o},o=n(e,[]),s=[];for(const e of o)e.actionHistory&&e.actionHistory.length>0&&s.push(...e.actionHistory);console.log("[CheckpointRestorationModal] Total actions to undo from all checkpoints:",s.length),0!==s.length?this.modalElement.innerHTML='\n <div class="sage-ai-checkpoint-modal-overlay"></div>\n <div class="sage-ai-checkpoint-modal-content">\n <div class="sage-ai-checkpoint-modal-header">\n <h3>Submit from a previous message?</h3>\n <button class="sage-ai-checkpoint-modal-close" type="button">\n <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n </button>\n </div>\n \n <div class="sage-ai-checkpoint-modal-body">\n <p>Submitting from a previous message will revert all actions after this message and clear the messages.</p>\n <p>Run all cells to keep the kernel state consistent.</p>\n <p>You can\'t revert this change.</p>\n </div>\n \n <div class="sage-ai-checkpoint-modal-footer">\n <button class="sage-ai-checkpoint-btn sage-ai-checkpoint-btn-cancel" type="button">\n Cancel\n </button>\n <button class="sage-ai-checkpoint-btn sage-ai-checkpoint-btn-continue" type="button" data-option="continue_without_running">\n Revert without Running\n </button>\n <button class="sage-ai-checkpoint-btn sage-ai-checkpoint-btn-continue-run" type="button" data-option="continue_and_run_all_cells">\n Revert and Run All Cells\n </button>\n </div>\n </div>\n ':this.modalElement.innerHTML='\n <div class="sage-ai-checkpoint-modal-overlay"></div>\n <div class="sage-ai-checkpoint-modal-content">\n <div class="sage-ai-checkpoint-modal-header">\n <h3>Submit from a previous message?</h3>\n <button class="sage-ai-checkpoint-modal-close" type="button">\n <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n </button>\n </div>\n \n <div class="sage-ai-checkpoint-modal-body">\n <p>Submitting from a previous message will clear the next messages.</p>\n <p>You can\'t revert this change.</p>\n </div>\n\n <div class="sage-ai-checkpoint-modal-footer">\n <button class="sage-ai-checkpoint-btn sage-ai-checkpoint-btn-cancel" type="button">\n Cancel\n </button>\n <button class="sage-ai-checkpoint-btn sage-ai-checkpoint-btn-continue-run" type="button" data-option="continue_and_run_all_cells">\n Continue\n </button>\n </div>\n </div>\n '}addStyles(){if(document.getElementById("sage-ai-checkpoint-modal-styles"))return;const e=document.createElement("style");e.id="sage-ai-checkpoint-modal-styles",e.textContent="\n .sage-ai-checkpoint-modal {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 10000;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n visibility: hidden;\n transition: opacity 0.2s ease, visibility 0.2s ease;\n }\n\n .sage-ai-checkpoint-modal.visible {\n opacity: 1;\n visibility: visible;\n }\n\n .sage-ai-checkpoint-modal-overlay {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: rgba(0, 0, 0, 0.5);\n backdrop-filter: blur(2px);\n }\n\n .sage-ai-checkpoint-modal-content {\n position: relative;\n background: var(--jp-layout-color1);\n border-radius: 8px;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);\n max-width: 500px;\n width: 90%;\n max-height: 80vh;\n overflow: hidden;\n transform: scale(0.95);\n transition: transform 0.2s ease;\n }\n\n .sage-ai-checkpoint-modal.visible .sage-ai-checkpoint-modal-content {\n transform: scale(1);\n }\n\n .sage-ai-checkpoint-modal-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px 20px 12px;\n }\n\n .sage-ai-checkpoint-modal-header h3 {\n margin: 0;\n font-size: 16px;\n font-weight: 600;\n color: var(--jp-ui-font-color1);\n }\n\n .sage-ai-checkpoint-modal-close {\n background: none;\n border: none;\n padding: 4px;\n cursor: pointer;\n color: var(--jp-ui-font-color2);\n border-radius: 4px;\n transition: background-color 0.2s ease;\n }\n\n .sage-ai-checkpoint-modal-close:hover {\n background-color: var(--jp-layout-color2);\n }\n\n .sage-ai-checkpoint-modal-body {\n padding: 0 20px;\n }\n\n .sage-ai-checkpoint-modal-body p {\n margin: 0;\n color: var(--jp-ui-font-color2);\n line-height: 1.5;\n }\n\n .sage-ai-checkpoint-preview {\n background: var(--jp-layout-color2);\n border: 1px solid var(--jp-border-color2);\n border-radius: 6px;\n padding: 12px;\n }\n\n .sage-ai-checkpoint-preview-label {\n font-size: 12px;\n font-weight: 600;\n color: var(--jp-ui-font-color2);\n margin-bottom: 6px;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n }\n\n .sage-ai-checkpoint-preview-content {\n color: var(--jp-ui-font-color1);\n font-size: 14px;\n line-height: 1.4;\n word-break: break-word;\n }\n\n .sage-ai-checkpoint-modal-footer {\n display: flex;\n gap: 12px;\n padding: 12px 20px 16px;\n justify-content: flex-end;\n }\n\n .sage-ai-checkpoint-btn {\n padding: 8px 16px;\n border: 1px solid var(--jp-border-color1);\n border-radius: 4px;\n font-size: 12px;\n font-weight: 500;\n cursor: pointer;\n transition: all 0.2s ease;\n background: var(--jp-layout-color1);\n color: var(--jp-ui-font-color1);\n }\n\n .sage-ai-checkpoint-btn:hover {\n background: var(--jp-layout-color2);\n }\n\n .sage-ai-checkpoint-btn-cancel {\n margin-right: 0;\n border: 0;\n }\n\n .sage-ai-checkpoint-btn-continue {\n }\n\n .sage-ai-checkpoint-btn-continue:hover {\n }\n\n .sage-ai-checkpoint-btn-continue-run {\n background: var(--jp-brand-color1);\n color: var(--jp-ui-inverse-font-color1);\n border-color: var(--jp-brand-color1);\n }\n\n .sage-ai-checkpoint-btn-continue-run:hover {\n background: var(--jp-brand-color2);\n border-color: var(--jp-brand-color2);\n }\n ",document.head.appendChild(e)}attachEventListeners(){if(!this.modalElement)return;const e=this.modalElement.querySelector(".sage-ai-checkpoint-modal-close");null==e||e.addEventListener("click",()=>{this.handleCancel()});const t=this.modalElement.querySelector(".sage-ai-checkpoint-modal-overlay");null==t||t.addEventListener("click",()=>{this.handleCancel()});const n=this.modalElement.querySelector(".sage-ai-checkpoint-btn-cancel");null==n||n.addEventListener("click",()=>{this.handleCancel()}),this.modalElement.querySelectorAll(".sage-ai-checkpoint-btn-continue, .sage-ai-checkpoint-btn-continue-run").forEach(e=>{e.addEventListener("click",e=>{const t=e.target.getAttribute("data-option");this.handleRestore(t)})});const o=e=>{"Escape"===e.key&&this.handleCancel()};document.addEventListener("keydown",o),this.modalElement._keyDownHandler=o}handleCancel(){this.hide(),this.onCancelCallback&&this.onCancelCallback()}handleRestore(e){this.hide(),this.onRestoreCallback&&this.onRestoreCallback(e)}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}}class Y{constructor(e,t,n,o){this.messageHistory=[],this.userMessages=[],this.lastAddedMessageType=null,this.mentionContexts=new Map,this.checkpointToRestore=null,this.waitingReplyBox=null,this.continueButton=null,this.promptButtons=[],this.onContinueCallback=null,this.container=e,this.historyManager=t,this.notebookTools=n,this.onScrollDownButtonDisplay=o,this.contextService=O.ContextService.getInstance(),this.diffStateService=v.getInstance(),this.checkpointManager=G.getInstance(),this.restorationModal=new J,this.checkpointToRestore=null,console.log("[ChatMessages] Initialized with empty message history"),this.addContinueButton(),this.syncContextService(),this.subscribeToContextChanges(),this.subscribeToDiffStateChanges()}generateMessageId(){return`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async loadFromThread(e){const t=[...this.messageHistory],n=[...this.userMessages],o=new Map(this.mentionContexts),s=this.lastAddedMessageType,i=this.container.innerHTML;try{this.messageHistory=[],this.userMessages=[],this.container.innerHTML="",this.messageHistory=[...e.messages],this.userMessages=e.messages.filter(e=>"user"===e.role),this.mentionContexts=new Map(e.contexts||new Map);const t=m.AppStateService.getCurrentNotebookId();t&&this.checkpointManager.setCurrentNotebookId(t),this.lastAddedMessageType=null,await this.renderAllMessages(),this.addContinueButton(),console.log(`[ChatMessages] Loaded ${e.messages.length} messages from thread`)}catch(e){throw console.error("[ChatMessages] Failed to load thread, restoring backup:",e),this.messageHistory=t,this.userMessages=n,this.mentionContexts=o,this.lastAddedMessageType=s,this.container.innerHTML=i,e}}async renderAllMessages(){let e=null;for(const t of this.messageHistory)if("user"===t.role)if(Array.isArray(t.content)&&t.content.length>0&&"object"==typeof t.content[0]&&"tool_result"===t.content[0].type)e&&(this.renderToolResult(t.content[0].tool_name||"tool",t.content[0].content,e),e.results.push(t.content[0]));else{e=null;const n="string"==typeof t.content?t.content:JSON.stringify(t.content),o=t.id?this.checkpointManager.findCheckpointByUserMessageId(t.id):this.checkpointManager.findCheckpointByUserMessage(n);this.renderUserMessage(n,o||void 0)}else if("assistant"===t.role)if(Array.isArray(t.content)&&t.content.length>0&&"object"==typeof t.content[0]&&"tool_use"===t.content[0].type){e={assistant:t,results:[]};for(const e of t.content)"tool_use"===e.type&&this.renderToolCall(e)}else e=null,await this.renderAssistantMessage("string"==typeof t.content?t.content:Array.isArray(t.content)&&"object"==typeof t.content[0]&&t.content[0].text?t.content[0].text:JSON.stringify(t.content));else U.F.isDiffApprovalMessage(t)&&this.renderDiffApprovalFromHistory(t.content[0]);this.scrollToBottom(),this.removeLoadingText(),this.updateContinueButtonVisibility(),this.ensureWaitingReplyBoxIsLast()}removeLoadingText(){this.container.querySelectorAll(".sage-ai-loading-text").forEach(e=>{e.classList.remove("sage-ai-loading-text")})}ensureWaitingReplyBoxIsLast(){this.waitingReplyBox&&this.waitingReplyBox.parentNode===this.container&&(this.container.removeChild(this.waitingReplyBox),this.container.appendChild(this.waitingReplyBox))}async renderMarkdown(e){try{return s.marked.setOptions({gfm:!0,breaks:!1}),await s.marked.parse(e)}catch(t){return console.error("Error rendering markdown:",t),this.escapeHtml(e)}}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}renderUserMessage(e,t){this.closeToolGroupIfOpen();const n=document.createElement("div");n.className="sage-ai-message sage-ai-user-message";const o=document.createElement("div");o.className="sage-ai-message-content sage-ai-user-message-content";const s=W(e);if(o.innerHTML=s===e?this.escapeHtml(e).replace(/\n/g,"<br>"):s.replace(/\n/g,"<br>"),t){n.setAttribute("data-checkpoint-id",t.id);const e=document.createElement("div");e.className="sage-ai-rollback-element";const s=document.createElement("span");s.className="sage-ai-rollback-icon",s.innerHTML='<svg width="13" height="13" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M5.99984 9.83341L2.6665 6.50008M2.6665 6.50008L5.99984 3.16675M2.6665 6.50008H9.6665C10.148 6.50008 10.6248 6.59492 11.0697 6.77919C11.5145 6.96346 11.9187 7.23354 12.2592 7.57402C12.5997 7.9145 12.8698 8.31871 13.0541 8.76357C13.2383 9.20844 13.3332 9.68523 13.3332 10.1667C13.3332 10.6483 13.2383 11.1251 13.0541 11.5699C12.8698 12.0148 12.5997 12.419 12.2592 12.7595C11.9187 13.1 11.5145 13.37 11.0697 13.5543C10.6248 13.7386 10.148 13.8334 9.6665 13.8334H7.33317" stroke="var(--jp-ui-font-color2)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>';const i=document.createElement("div");i.className="sage-ai-restore-redo-element",i.textContent="Redo checkpoint",i.addEventListener("click",()=>{this.cancelCheckpointRestoration(),i.style.display=""});const a=document.createElement("span");a.className="sage-ai-rollback-tooltip",a.textContent="Restore checkpoint",e.appendChild(a),e.appendChild(s),e.addEventListener("click",()=>{this.performCheckpointRestoration(t),i.style.display="block"}),n.append(o,e,i)}else n.append(o);this.container.appendChild(n),this.collapseMessageHeight(n),this.ensureWaitingReplyBoxIsLast(),this.lastAddedMessageType="user",this.handleScroll()}collapseMessageHeight(e){const t=e.querySelector(".sage-ai-message-content");t&&t.offsetHeight>=65?(t.classList.add("collapsed"),t.classList.add("collapsible"),e.addEventListener("click",()=>{t.classList.contains("collapsed")?t.classList.remove("collapsed"):t.classList.add("collapsed")})):null==t||t.classList.remove("collapsed")}isFullyScrolledToBottom(){return"true"===this.container.getAttribute("data-is-scrolled-to-bottom")}async renderAssistantMessage(e,t){this.closeToolGroupIfOpen();const n=document.createElement("div");n.className="sage-ai-message sage-ai-ai-message";const o=document.createElement("div");o.className="sage-ai-message-header";const s=document.createElement("div");s.className="sage-ai-message-header-image",s.innerHTML='<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M6.6243 10.3334C6.56478 10.1026 6.44453 9.89209 6.27605 9.72361C6.10757 9.55513 5.89702 9.43488 5.6663 9.37536L1.5763 8.32069C1.50652 8.30089 1.44511 8.25886 1.40138 8.20099C1.35765 8.14312 1.33398 8.07256 1.33398 8.00002C1.33398 7.92749 1.35765 7.85693 1.40138 7.79906C1.44511 7.74119 1.50652 7.69916 1.5763 7.67936L5.6663 6.62402C5.89693 6.56456 6.10743 6.44441 6.2759 6.27605C6.44438 6.10769 6.56468 5.89728 6.6243 5.66669L7.67897 1.57669C7.69857 1.50664 7.74056 1.44492 7.79851 1.40095C7.85647 1.35699 7.92722 1.33319 7.99997 1.33319C8.07271 1.33319 8.14346 1.35699 8.20142 1.40095C8.25938 1.44492 8.30136 1.50664 8.32097 1.57669L9.37497 5.66669C9.43449 5.89741 9.55474 6.10796 9.72322 6.27644C9.8917 6.44492 10.1023 6.56517 10.333 6.62469L14.423 7.67869C14.4933 7.69809 14.5553 7.74003 14.5995 7.79808C14.6437 7.85612 14.6677 7.92706 14.6677 8.00002C14.6677 8.07298 14.6437 8.14393 14.5995 8.20197C14.5553 8.26002 14.4933 8.30196 14.423 8.32136L10.333 9.37536C10.1023 9.43488 9.8917 9.55513 9.72322 9.72361C9.55474 9.89209 9.43449 10.1026 9.37497 10.3334L8.3203 14.4234C8.3007 14.4934 8.25871 14.5551 8.20075 14.5991C8.1428 14.6431 8.07205 14.6669 7.9993 14.6669C7.92656 14.6669 7.85581 14.6431 7.79785 14.5991C7.73989 14.5551 7.69791 14.4934 7.6783 14.4234L6.6243 10.3334Z" fill="url(#paint0_linear_445_6567)"/>\n <path d="M13.333 2V4.66667" stroke="url(#paint1_linear_445_6567)" stroke-width="0.984615" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M14.6667 3.33331H12" stroke="url(#paint2_linear_445_6567)" stroke-width="0.984615" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M2.66699 11.3333V12.6666" stroke="url(#paint3_linear_445_6567)" stroke-width="0.984615" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M3.33333 12H2" stroke="url(#paint4_linear_445_6567)" stroke-width="0.984615" stroke-linecap="round" stroke-linejoin="round"/>\n <defs>\n <linearGradient id="paint0_linear_445_6567" x1="1.33398" y1="1.33319" x2="14.6677" y2="14.6669" gradientUnits="userSpaceOnUse">\n <stop stop-color="#FEC163"/>\n <stop offset="1" stop-color="#DE4313"/>\n </linearGradient>\n <linearGradient id="paint1_linear_445_6567" x1="13.333" y1="2" x2="15.0864" y2="2.65753" gradientUnits="userSpaceOnUse">\n <stop stop-color="#FEC163"/>\n <stop offset="1" stop-color="#DE4313"/>\n </linearGradient>\n <linearGradient id="paint2_linear_445_6567" x1="12" y1="3.33331" x2="12.6575" y2="5.08674" gradientUnits="userSpaceOnUse">\n <stop stop-color="#FEC163"/>\n <stop offset="1" stop-color="#DE4313"/>\n </linearGradient>\n <linearGradient id="paint3_linear_445_6567" x1="2.66699" y1="11.3333" x2="3.94699" y2="12.2933" gradientUnits="userSpaceOnUse">\n <stop stop-color="#FEC163"/>\n <stop offset="1" stop-color="#DE4313"/>\n </linearGradient>\n <linearGradient id="paint4_linear_445_6567" x1="2" y1="12" x2="2.96" y2="13.28" gradientUnits="userSpaceOnUse">\n <stop stop-color="#FEC163"/>\n <stop offset="1" stop-color="#DE4313"/>\n </linearGradient>\n </defs>\n </svg>',o.append(s);const i=document.createElement("span");i.className="sage-ai-message-header-title",i.innerText="Sage AI",o.append(i),"user"!==this.lastAddedMessageType&&(o.style.display="none");const a=document.createElement("div");a.className="sage-ai-message-content sage-ai-markdown-content",a.innerHTML=await this.renderMarkdown(e),n.appendChild(o),n.appendChild(a);const r=null!=t?t:this.container;r.appendChild(n),r===this.container&&this.ensureWaitingReplyBoxIsLast(),this.lastAddedMessageType="normal",this.activateCodeBlocks(a),this.handleScroll()}activateCodeBlocks(e){e.querySelectorAll("pre code").forEach(e=>{var t;const n=document.createElement("div");n.className="sage-ai-code-block-container";const o=document.createElement("button");o.className="sage-ai-copy-code-button",o.innerHTML=h,o.title="Copy code to clipboard",o.addEventListener("click",()=>{const t=e.textContent||"";navigator.clipboard.writeText(t).then(()=>{o.innerHTML=u,setTimeout(()=>{o.innerHTML=h},2e3)}).catch(e=>{console.error("Failed to copy code: ",e),o.innerHTML="Error",setTimeout(()=>{o.innerHTML=h},2e3)})});const s=e.parentElement;s&&"PRE"===s.tagName&&(null===(t=s.parentNode)||void 0===t||t.insertBefore(n,s),n.appendChild(s),n.appendChild(o))})}getMentionContexts(){return new Map(this.mentionContexts)}setMentionContexts(e){this.mentionContexts=new Map(e),this.contextService.setContextItems(this.mentionContexts)}addMentionContext(e){this.mentionContexts.set(e.id,e),this.historyManager.updateCurrentThreadContexts(this.mentionContexts),this.contextService.addContextItem(e)}removeMentionContext(e){this.mentionContexts.delete(e),this.historyManager.updateCurrentThreadContexts(this.mentionContexts),this.contextService.removeContextItem(e)}syncContextService(){this.contextService.setContextItems(this.mentionContexts)}subscribeToContextChanges(){this.contextService.subscribe(e=>{this.messageHistory.some(e=>"user"===e.role&&"string"==typeof e.content&&e.content.includes("<")&&e.content.includes("_CONTEXT>"))&&(console.log("[ChatMessages] Context items updated, refreshing message displays"),this.refreshMessageDisplays())})}subscribeToDiffStateChanges(){this.diffStateService.allDiffsResolved$.subscribe(({notebookId:e})=>{console.log("[ChatMessages] All diffs resolved, checking prompt buttons",{notebookId:e}),this.shouldShowContinueButton()&&(this.checkAndShowPromptButtons(),this.ensureWaitingReplyBoxIsLast())}),this.diffStateService.getApprovalStatusChanges$().subscribe(e=>{console.log("[ChatMessages] Diff approval status changed",e),e.allResolved&&this.shouldShowContinueButton()&&(this.checkAndShowPromptButtons(),this.ensureWaitingReplyBoxIsLast())})}refreshMessageDisplays(){this.container.querySelectorAll(".sage-ai-user-message .sage-ai-message-content").forEach(e=>{const t=e.innerHTML;if(t.includes("sage-ai-mention")){const n=this.extractOriginalMessageFromHTML(t);if(n){const t=W(n);e.innerHTML=t.replace(/\n/g,"<br>")}}})}extractOriginalMessageFromHTML(e){try{const t=document.createElement("div");t.innerHTML=e;let n="";return t.childNodes.forEach(e=>{if(e.nodeType===Node.TEXT_NODE)n+=e.textContent||"";else if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.classList.contains("sage-ai-mention")){const e=t.getAttribute("data-context-id"),o=t.textContent||"";if(e){const o=function(e){return e.classList.contains("sage-ai-mention-template")?"SNIPPET_CONTEXT":e.classList.contains("sage-ai-mention-data")?"DATA_CONTEXT":e.classList.contains("sage-ai-mention-variable")?"VARIABLE_CONTEXT":e.classList.contains("sage-ai-mention-cell")?"CELL_CONTEXT":"DATA_CONTEXT"}(t);n+=`<${o}>#{${e}}</${o}>`}else n+=o}else"BR"===t.tagName?n+="\n":n+=t.textContent||""}}),n}catch(e){return console.warn("[ChatMessages] Failed to extract original message:",e),null}}getContextTagType(e){switch(e){case"snippets":return"SNIPPET_CONTEXT";case"data":default:return"DATA_CONTEXT";case"variable":return"VARIABLE_CONTEXT";case"cell":return"CELL_CONTEXT"}}processUserMessageContent(e){let t=W(e);const n=/<span class="sage-ai-mention[^"]*"[^>]*>[^<]*<\/span>/g,o=t.split(n),s=t.match(n)||[];let i="";for(let e=0;e<o.length;e++)i+=this.escapeHtml(o[e]).replace(/\n/g,"<br>"),s[e]&&(i+=s[e]);return i}addUserMessage(e,t){this.closeToolGroupIfOpen(),console.log("[ChatMessages] Adding user message:",e);const n=document.createElement("div");n.className="sage-ai-message sage-ai-user-message";const o=document.createElement("div");o.className="sage-ai-message-content sage-ai-user-message-content";const s=this.processUserMessageContent(e);o.innerHTML=s;const i=document.createElement("div");i.className="sage-ai-rollback-element";const a=document.createElement("span");a.className="sage-ai-rollback-icon",a.innerHTML='<svg width="13" height="13" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M5.99984 9.83341L2.6665 6.50008M2.6665 6.50008L5.99984 3.16675M2.6665 6.50008H9.6665C10.148 6.50008 10.6248 6.59492 11.0697 6.77919C11.5145 6.96346 11.9187 7.23354 12.2592 7.57402C12.5997 7.9145 12.8698 8.31871 13.0541 8.76357C13.2383 9.20844 13.3332 9.68523 13.3332 10.1667C13.3332 10.6483 13.2383 11.1251 13.0541 11.5699C12.8698 12.0148 12.5997 12.419 12.2592 12.7595C11.9187 13.1 11.5145 13.37 11.0697 13.5543C10.6248 13.7386 10.148 13.8334 9.6665 13.8334H7.33317" stroke="var(--jp-ui-font-color2)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>';const r=document.createElement("span");r.className="sage-ai-rollback-tooltip",r.textContent="Restore checkpoint",i.appendChild(r),i.appendChild(a);const l=document.createElement("div");l.className="sage-ai-restore-redo-element",l.textContent="Redo checkpoint",l.addEventListener("click",()=>{this.cancelCheckpointRestoration(),l.style.display=""});const c={role:"user",content:e,id:this.generateMessageId()};this.messageHistory.push(c),this.userMessages.push({role:"user",content:e,id:c.id});try{const e=this.createCheckpoint(c);n.setAttribute("data-checkpoint-id",e.id),i.addEventListener("click",()=>{this.performCheckpointRestoration(e),l.style.display="block"}),n.append(o,i,l)}catch(e){console.error("[ChatMessages] Error creating checkpoint:",e),n.append(o)}this.container.appendChild(n),this.collapseMessageHeight(n),this.ensureWaitingReplyBoxIsLast(),this.historyManager.updateCurrentThreadMessages(this.messageHistory,this.mentionContexts),this.lastAddedMessageType="user",this.hideWaitingReplyBox(),this.handleScroll(),console.log("[ChatMessages] User message added to history"),console.log("[ChatMessages] Current message history:",JSON.stringify(this.messageHistory)),console.log("[ChatMessages] Current user messages:",JSON.stringify(this.userMessages))}addSystemMessage(e){this.closeToolGroupIfOpen(),console.log("[ChatMessages] Adding system message:",e);const t=document.createElement("div");t.className="sage-ai-message sage-ai-system-message";const n=document.createElement("p");n.className="sage-ai-system-message-text",n.innerHTML=e,t.appendChild(n),this.container.appendChild(t),this.ensureWaitingReplyBoxIsLast(),this.lastAddedMessageType="normal",this.handleScroll(),console.log("[ChatMessages] System message added (not saved to history)")}addDiffApprovalDialog(e,t){console.log("[ChatMessages] Adding diff approval dialog to chat");const n={role:"diff_approval",content:[{type:"diff_approval",id:`diff_approval_${Date.now()}`,timestamp:(new Date).toISOString(),diff_cells:t?t.map(e=>({cellId:e.cellId,type:e.type,originalContent:e.originalContent||"",newContent:e.newContent||"",displaySummary:e.displaySummary||`${e.type} cell`})):[]}]};this.messageHistory.push(n),this.historyManager.updateCurrentThreadMessages(this.messageHistory,this.mentionContexts),console.log("[ChatMessages] Diff approval dialog added to chat and history")}addErrorMessage(e){this.closeToolGroupIfOpen(),console.log("[ChatMessages] Adding error message:",e);const t=document.createElement("div");t.className="sage-ai-message sage-ai-error-message",t.textContent=e,this.container.appendChild(t),this.lastAddedMessageType="normal",this.handleScroll(),console.log("[ChatMessages] Error message added (not saved to history)")}closeToolGroupIfOpen(){"tool"===this.lastAddedMessageType&&(this.lastAddedMessageType=null)}renderToolCall(e){if("notebook-wait_user_reply"===e.name)return;const t=document.createElement("div");t.classList.add("sage-ai-tool-call-v1"),t.setAttribute("sage-ai-tool-call-name",e.name);const n=document.createElement("div");n.innerHTML=g(e.name),t.appendChild(n.firstChild);const o=document.createElement("span");o.innerHTML=p(e.name,e.input),o.className="sage-ai-loading-text",t.appendChild(o),this.upsertCellIdLabelInDOM(t,e.name,e.input),this.container.appendChild(t),this.ensureWaitingReplyBoxIsLast(),this.handleScroll(),this.lastAddedMessageType="tool"}addToolCalls(e){e&&0!==e.length?(console.log("[ChatMessages] Adding tool calls:",e.length),e.forEach((e,t)=>{console.log(`[ChatMessages] Processing tool call #${t+1}:`,e.name),this.renderToolCall(e);const n={role:"assistant",content:[{type:"tool_use",id:e.id,name:e.name,input:e.input}]};this.messageHistory.push(n),this.historyManager.updateCurrentThreadMessages(this.messageHistory,this.mentionContexts),console.log(`[ChatMessages] Tool call #${t+1} added to history`)}),console.log("[ChatMessages] All tool calls added, current history length:",this.messageHistory.length),console.log("[ChatMessages] Last message in history:",JSON.stringify(this.messageHistory[this.messageHistory.length-1]))):console.log("[ChatMessages] No tool calls to add")}addStreamingToolCall(){this.closeToolGroupIfOpen(),console.log("[ChatMessages] Adding streaming tool call container");const e=this.container.querySelector(".sage-ai-streaming-cursor");e&&e.remove();const t=document.createElement("div");t.className="sage-ai-tool-call-v1 sage-ai-streaming-tool-call",t.setAttribute("data-tool-call","{}");const n=document.createElement("div");n.className="sage-ai-streaming-tool-call-placeholder",n.innerHTML="Sage is thinking about tools to use...";const o=document.createElement("span");return o.classList.add("sage-ai-streaming-cursor"),n.appendChild(o),t.appendChild(n),this.container.appendChild(t),this.ensureWaitingReplyBoxIsLast(),this.handleScroll(),console.log("[ChatMessages] Streaming tool call container added (not yet in history)"),t}updateStreamingToolCall(e,t){if(console.log("[ChatMessages] Updating streaming tool call with:",t.name),e){const n=e.querySelector(".sage-ai-streaming-tool-call-placeholder");n&&n.remove(),e.setAttribute("data-tool-call",JSON.stringify(t)),e.setAttribute("sage-ai-tool-call-name",t.name);let o=e.querySelector(".sage-ai-tool-call-icon");o||(o=document.createElement("div"),o.className="sage-ai-tool-call-icon",o.innerHTML=g(t.name),e.appendChild(o));let s=e.querySelector(".sage-ai-loading-text");const i=p(t.name,t.input);s?s.innerHTML!==i&&(s.innerHTML=i):(s=document.createElement("span"),s.innerHTML=i,s.className="sage-ai-loading-text",e.appendChild(s)),this.upsertCellIdLabelInDOM(e,t.name,t.input),this.handleScroll(),console.log("[ChatMessages] Streaming tool call updated")}else console.warn("[ChatMessages] Warning: Tool call container not found in streaming message element")}finalizeStreamingToolCall(e){console.log("[ChatMessages] Finalizing streaming tool call");const t=e.querySelector(".sage-ai-streaming-cursor");t&&t.remove();const n=e.querySelector(".sage-ai-loading-text");n&&n.classList.remove("sage-ai-loading-text");const o=e.getAttribute("data-tool-call")||"{}",s=JSON.parse(o);if(console.log("[ChatMessages] Finalized tool call:",s.name),s.name){this.renderToolCall(s),e.remove();const t={role:"assistant",content:[{type:"tool_use",id:s.id,name:s.name,input:s.input}]};this.messageHistory.push(t),this.historyManager.updateCurrentThreadMessages(this.messageHistory,this.mentionContexts),console.log("[ChatMessages] Finalized tool call added to history"),console.log("[ChatMessages] Current history length:",this.messageHistory.length)}else console.warn("[ChatMessages] Warning: No tool call data found when finalizing streaming tool call");console.log("[ChatMessages] Streaming tool call finalized")}renderToolResult(e,t,n){console.log("[ChatMessages] Rendering tool result:",t);const o=this.container.querySelector(".sage-ai-loading-text");if(o){o.classList.remove("sage-ai-loading-text");const e=o.parentElement,s=e.getAttribute("sage-ai-tool-call-name"),i=function(e){try{if(console.log("[ChatMessages] getResultError() called with result:",e),console.log("[ChatMessages] getResultError() called with result:",typeof e),"string"!=typeof e)return!1;const t=JSON.parse(e);if(Array.isArray(t)){const e=t.filter(e=>e&&!0===(null==e?void 0:e.error));return!!e.length&&e.map(e=>e.errorText).join("\n")}if(t&&!0===(null==t?void 0:t.error))return t.errorText}catch(e){return!1}return!1}(t);"string"==typeof i&&(e.classList.add("error-state"),e.title=i),this.upsertCellIdLabelInDOM(e,s,n,t),"notebook-edit_plan"===s&&(e.classList.add("clickable"),e.addEventListener("click",()=>{this.notebookTools.scrollToPlanCell()})),this.lastAddedMessageType="tool"}this.handleScroll()}upsertCellIdLabelInDOM(e,t,n,o){var s,i,a;const r=e.querySelector(".sage-ai-tool-call-cell");if(r&&r.remove(),["notebook-add_cell","notebook-edit_cell","notebook-run_cell"].includes(t)){let t="";"string"==typeof o&&/^cell_(\d+)$/.test(o)&&(t=o);let r=null===(a=null===(i=null===(s=null==n?void 0:n.assistant)||void 0===s?void 0:s.content[0])||void 0===i?void 0:i.input)||void 0===a?void 0:a.cell_id;if("string"==typeof r&&/^cell_(\d+)$/.test(r)&&(t=r),"string"==typeof n.cell_id&&/^cell_(\d+)$/.test(n.cell_id)&&(t=n.cell_id),t&&/^cell_(\d+)$/.test(t)){e.classList.add("clickable");const n=document.createElement("div");n.classList.add("sage-ai-tool-call-cell"),n.innerHTML=t,e.appendChild(n),e.addEventListener("click",()=>{this.notebookTools.scrollToCellById(t)})}}}addToolResult(e,t,n,o){console.log("[ChatMessages] Adding tool result for:",e),this.renderToolResult(e,n,o);const s={role:"user",content:[{type:"tool_result",tool_use_id:t,content:n}]};this.messageHistory.push(s),this.historyManager.updateCurrentThreadMessages(this.messageHistory,this.mentionContexts),console.log("[ChatMessages] Tool result added to history"),console.log("[ChatMessages] Current history length:",this.messageHistory.length),console.log("[ChatMessages.addToolResult] Last message in history:",JSON.stringify(this.messageHistory[this.messageHistory.length-1]))}addLoadingIndicator(e="Generating..."){this.closeToolGroupIfOpen(),console.log("[ChatMessages] Adding loading indicator:",e);const t=document.createElement("div");t.className="sage-ai-message sage-ai-loading";const n=document.createElement("div");n.className="sage-ai-blob-loader",t.appendChild(n);const o=document.createElement("span");return o.textContent=e,t.appendChild(o),this.handleScroll(),this.container.appendChild(t),this.ensureWaitingReplyBoxIsLast(),t}removeElement(e){console.log("[ChatMessages] Removing element from UI"),this.container.contains(e)&&this.container.removeChild(e)}getMessageHistory(){return console.log("[ChatMessages] Getting message history, length:",this.messageHistory.length),[...this.messageHistory]}async updateStreamingMessage(e,t){const n=e.querySelector(".sage-ai-message-content");if(n){const e=(n.getAttribute("data-raw-text")||"")+t;n.setAttribute("data-raw-text",e),n.innerHTML=await this.renderMarkdown(e);const o=document.createElement("span");o.classList.add("sage-ai-streaming-cursor");const s=n.lastElementChild,i=null==s?void 0:s.lastElementChild;i?i.appendChild(o):s?s.appendChild(o):n.appendChild(o),this.handleScroll()}else console.warn("[ChatMessages] Warning: Content span not found in streaming message element")}async finalizeStreamingMessage(e){console.log("[ChatMessages] Finalizing streaming message");const t=e.querySelector(".sage-ai-message-content");if(t){const n=t.getAttribute("data-raw-text")||"";console.log("[ChatMessages] Finalized message text length:",n.length),console.log("[ChatMessages] First 100 chars of finalized message:",n.substring(0,100)+(n.length>100?"...":"")),await this.renderAssistantMessage(n,e.parentElement||void 0),e.remove();const o={role:"assistant",content:n};this.messageHistory.push(o),this.historyManager.updateCurrentThreadMessages(this.messageHistory,this.mentionContexts),console.log("[ChatMessages] Finalized AI message added to history"),console.log("[ChatMessages] Current history length:",this.messageHistory.length)}else console.warn("[ChatMessages] Warning: Content span not found when finalizing streaming message");this.handleScroll(),e.classList.remove("sage-ai-streaming-message");const n=e.querySelector("sage-ai-streaming-cursor");n&&n.remove(),console.log("[ChatMessages] Streaming message finalized and class removed")}handleScroll(){this.isFullyScrolledToBottom()?this.scrollToBottom():this.onScrollDownButtonDisplay()}scrollToBottom(){this.container&&(this.container.scrollTop=this.container.scrollHeight+50),this.onScrollDownButtonDisplay()}addContinueButton(){console.log("[ChatMessages] addContinueButton() called"),this.removeContinueButton(),this.waitingReplyBox=document.createElement("div"),this.waitingReplyBox.className="sage-ai-waiting-reply-container";const e=document.createElement("div");e.className="sage-ai-waiting-reply-text",e.textContent="Sage will continue working after you reply",this.waitingReplyBox.appendChild(e);const t=document.createElement("div");t.className="sage-ai-prompt-buttons-container",t.style.display="flex",t.style.flexDirection="column",t.style.gap="8px",t.style.marginTop="12px",this.promptButtons=[];const n=document.createElement("button");n.className="sage-ai-prompt-button",n.textContent="Continue",n.style.display="none",n.addEventListener("click",()=>{var e,t;const o=n.textContent||"";console.log("[ChatMessages] Default prompt button clicked:",o),null===(e=m.AppStateService.getState().chatContainer)||void 0===e||e.chatWidget.inputManager.setInputValue(o),null===(t=m.AppStateService.getState().chatContainer)||void 0===t||t.chatWidget.inputManager.sendMessage(),this.hidePromptButtons(),this.hideWaitingReplyBox()}),this.promptButtons.push(n),t.appendChild(n),this.waitingReplyBox.appendChild(t),this.continueButton=document.createElement("button"),this.continueButton.className="sage-ai-continue-button hidden",this.continueButton.textContent="Continue",this.continueButton.addEventListener("click",()=>{var e,t;console.log("[ChatMessages] Continue button clicked"),console.log("[ChatMessages] Calling continue callback"),null===(e=m.AppStateService.getState().chatContainer)||void 0===e||e.chatWidget.inputManager.setInputValue("Continue"),null===(t=m.AppStateService.getState().chatContainer)||void 0===t||t.chatWidget.inputManager.sendMessage(),this.hideContinueButton(),this.hideWaitingReplyBox()}),this.waitingReplyBox.appendChild(this.continueButton),this.waitingReplyBox.classList.remove("visible"),this.container.appendChild(this.waitingReplyBox),console.log("[ChatMessages] Waiting reply box added to container")}removeContinueButton(){console.log("[ChatMessages] removeContinueButton() called"),this.waitingReplyBox&&(this.waitingReplyBox.remove(),this.waitingReplyBox=null,this.continueButton=null,this.promptButtons=[],console.log("[ChatMessages] Continue button removed"))}showPromptButtons(){console.log("[ChatMessages] showPromptButtons() called"),this.promptButtons.forEach((e,t)=>{e?(console.log(`[ChatMessages] Setting prompt button ${t+1} display to block`),e.style.display="block"):console.warn(`[ChatMessages] promptButton ${t+1} is null in showPromptButtons()`)})}hidePromptButtons(){console.log("[ChatMessages] hidePromptButtons() called"),this.promptButtons.forEach((e,t)=>{e?(console.log(`[ChatMessages] Setting prompt button ${t+1} display to none`),e.style.display="none"):console.warn(`[ChatMessages] promptButton ${t+1} is null in hidePromptButtons()`)})}updatePromptButtons(e){var t;console.log("[ChatMessages] updatePromptButtons() called with prompts:",e);const n=null===(t=this.waitingReplyBox)||void 0===t?void 0:t.querySelector(".sage-ai-prompt-buttons-container");n?(this.promptButtons.forEach(e=>{e&&e.parentNode&&e.parentNode.removeChild(e)}),this.promptButtons=[],e.forEach((e,t)=>{const o=document.createElement("button");o.className="sage-ai-prompt-button",o.textContent=e,o.style.display="block",o.addEventListener("click",()=>{var e,n;const s=o.textContent||"";console.log(`[ChatMessages] Prompt button ${t+1} clicked:`,s),null===(e=m.AppStateService.getState().chatContainer)||void 0===e||e.chatWidget.inputManager.setInputValue(s),null===(n=m.AppStateService.getState().chatContainer)||void 0===n||n.chatWidget.inputManager.sendMessage(),this.hidePromptButtons(),this.hideWaitingReplyBox()}),this.promptButtons.push(o),n.appendChild(o),console.log(`[ChatMessages] Created new prompt button ${t+1}: "${e}"`)})):console.warn("[ChatMessages] No buttons container found")}showWaitingReplyBox(e){console.log("[ChatMessages] showWaitingReplyBox() called"),this.waitingReplyBox?(console.log("[ChatMessages] Adding visible class to waiting reply box"),this.displayWaitingReplyBox(),e&&e.length>0?this.updatePromptButtons(e):this.showPromptButtons(),this.ensureWaitingReplyBoxIsLast(),this.checkAndShowPromptButtons(),this.handleScroll()):console.warn("[ChatMessages] waitingReplyBox is null in showWaitingReplyBox()")}displayWaitingReplyBox(){console.log("[ChatMessages] displayWaitingReplyBox() called"),this.waitingReplyBox&&this.waitingReplyBox.classList.add("visible"),this.waitingReplyBox&&!this.waitingReplyBox.parentElement&&(console.log("[ChatMessages] Adding waiting reply box to container"),this.container.appendChild(this.waitingReplyBox))}hideWaitingReplyBox(){console.log("[ChatMessages] hideWaitingReplyBox() called"),this.waitingReplyBox&&this.waitingReplyBox.classList.remove("visible")}setContinueCallback(e){console.log("[ChatMessages] Setting continue callback"),this.onContinueCallback=e}updateContinueButtonVisibility(){if(console.log("[ChatMessages] updateContinueButtonVisibility() called"),!this.waitingReplyBox||!this.continueButton)return console.log("[ChatMessages] No waiting reply box or continue button, creating..."),void this.addContinueButton();this.ensureWaitingReplyBoxIsLast(),this.checkAndShowContinueButtonOnStartup()}checkAndShowPromptButtons(){if(console.log("[ChatMessages] checkAndShowPromptButtons() called"),!v.getInstance().getCurrentState().allDiffsResolved)return console.warn("[ChatMessages] Diffs not resolved, skipping prompt buttons"),void this.hideWaitingReplyBox();const e=this.historyManager.getCurrentThread();console.log("[ChatMessages] currentThread:",e),!e||e.messages.length<=1?console.warn("[ChatMessages] No currentThread found"):(console.log("[ChatMessages] continueButtonShown status:",e.continueButtonShown),console.log("[ChatMessages] Message history length:",this.messageHistory.length),console.log("[ChatMessages] wait_user_reply tool called, showing prompt buttons"),this.showPromptButtons(),this.hideContinueButton(),this.waitingReplyBox&&this.displayWaitingReplyBox(),e.continueButtonShown||(e.continueButtonShown=!0,this.historyManager.updateCurrentThreadMessages(e.messages,e.contexts)))}checkAndShowContinueButtonOnStartup(){console.log("[ChatMessages] checkAndShowContinueButtonOnStartup() called");const e=this.historyManager.getCurrentThread();if(console.log("[ChatMessages] currentThread:",e),!e)return void console.warn("[ChatMessages] No currentThread found");console.log("[ChatMessages] continueButtonShown status:",e.continueButtonShown),console.log("[ChatMessages] Message history length:",this.messageHistory.length);const t=this.shouldShowContinueButton();console.log("[ChatMessages] shouldShowContinueButton result:",t),t?(console.log("[ChatMessages] Startup conditions met, showing continue button"),this.showContinueButton(),this.waitingReplyBox&&this.displayWaitingReplyBox(),e.continueButtonShown||(e.continueButtonShown=!0,this.historyManager.updateCurrentThreadMessages(e.messages,e.contexts))):console.log("[ChatMessages] Startup continue button conditions not met")}shouldShowContinueButton(){if(console.log("[ChatMessages] shouldShowContinueButton() called"),0===this.messageHistory.length)return console.log("[ChatMessages] No messages in history, not showing continue button"),!1;const e=this.messageHistory.slice(-3).some(e=>!("assistant"!==e.role||!Array.isArray(e.content))&&e.content.some(e=>"tool_use"===e.type&&"notebook-wait_user_reply"===e.name));if(e)return console.log("[ChatMessages] Found wait_user_reply tool call, showing continue button"),!0;const t=this.messageHistory.slice().reverse().find(e=>"assistant"===e.role&&(Array.isArray(e.content)?e.content.some(e=>"text"===e.type&&e.text&&e.text.trim().length>0):"string"==typeof e.content&&e.content.trim().length>0));if(!t)return console.log("[ChatMessages] No valid assistant message found, not showing continue button"),!1;let n="";if("string"==typeof t.content)n=t.content;else if(Array.isArray(t.content)){const e=t.content.find(e=>"text"===e.type);n=(null==e?void 0:e.text)||""}console.log("[ChatMessages] Analyzing last assistant message:",n.substring(0,200)+"...");const o=["waiting for","wait for","after you reply","when you reply","let me know","please","would you like","do you want","shall i","should i","feel free to","if you need","any questions","anything else","next steps","proceed with","continue with","go ahead","move forward"].some(e=>n.toLowerCase().includes(e.toLowerCase())),s=n.trim().endsWith("?"),i=["what","how","when","where","why","which","who","should","would","could","can","do you","are you"].some(e=>n.toLowerCase().trim().startsWith(e.toLowerCase())),a=o||s||i;return console.log("[ChatMessages] Continue button analysis - waitingIndicator:",o,"endsWithQuestion:",s,"startsWithQuestion:",i,"result:",a),a}showContinueButton(){console.log("[ChatMessages] showContinueButton() called"),this.continueButton?(console.log("[ChatMessages] Removing hidden class from continue button"),this.continueButton.classList.remove("hidden")):console.warn("[ChatMessages] continueButton is null in showContinueButton()")}hideContinueButton(){console.log("[ChatMessages] hideContinueButton() called"),this.continueButton?(console.log("[ChatMessages] Adding hidden class to continue button"),this.continueButton.classList.add("hidden")):console.warn("[ChatMessages] continueButton is null in hideContinueButton()")}addStreamingAIMessage(){this.closeToolGroupIfOpen(),console.log("[ChatMessages] Adding streaming AI message container");const e=document.createElement("div");e.className="sage-ai-message sage-ai-ai-message sage-ai-streaming-message";const t=document.createElement("div");t.className="sage-ai-message-header";const n=document.createElement("div");n.className="sage-ai-message-header-image",n.innerHTML='<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M6.6243 10.3334C6.56478 10.1026 6.44453 9.89209 6.27605 9.72361C6.10757 9.55513 5.89702 9.43488 5.6663 9.37536L1.5763 8.32069C1.50652 8.30089 1.44511 8.25886 1.40138 8.20099C1.35765 8.14312 1.33398 8.07256 1.33398 8.00002C1.33398 7.92749 1.35765 7.85693 1.40138 7.79906C1.44511 7.74119 1.50652 7.69916 1.5763 7.67936L5.6663 6.62402C5.89693 6.56456 6.10743 6.44441 6.2759 6.27605C6.44438 6.10769 6.56468 5.89728 6.6243 5.66669L7.67897 1.57669C7.69857 1.50664 7.74056 1.44492 7.79851 1.40095C7.85647 1.35699 7.92722 1.33319 7.99997 1.33319C8.07271 1.33319 8.14346 1.35699 8.20142 1.40095C8.25938 1.44492 8.30136 1.50664 8.32097 1.57669L9.37497 5.66669C9.43449 5.89741 9.55474 6.10796 9.72322 6.27644C9.8917 6.44492 10.1023 6.56517 10.333 6.62469L14.423 7.67869C14.4933 7.69809 14.5553 7.74003 14.5995 7.79808C14.6437 7.85612 14.6677 7.92706 14.6677 8.00002C14.6677 8.07298 14.6437 8.14393 14.5995 8.20197C14.5553 8.26002 14.4933 8.30196 14.423 8.32136L10.333 9.37536C10.1023 9.43488 9.8917 9.55513 9.72322 9.72361C9.55474 9.89209 9.43449 10.1026 9.37497 10.3334L8.3203 14.4234C8.3007 14.4934 8.25871 14.5551 8.20075 14.5991C8.1428 14.6431 8.07205 14.6669 7.9993 14.6669C7.92656 14.6669 7.85581 14.6431 7.79785 14.5991C7.73989 14.5551 7.69791 14.4934 7.6783 14.4234L6.6243 10.3334Z" fill="url(#paint0_linear_445_6567)"/>\n <path d="M13.333 2V4.66667" stroke="url(#paint1_linear_445_6567)" stroke-width="0.984615" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M14.6667 3.33331H12" stroke="url(#paint2_linear_445_6567)" stroke-width="0.984615" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M2.66699 11.3333V12.6666" stroke="url(#paint3_linear_445_6567)" stroke-width="0.984615" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M3.33333 12H2" stroke="url(#paint4_linear_445_6567)" stroke-width="0.984615" stroke-linecap="round" stroke-linejoin="round"/>\n <defs>\n <linearGradient id="paint0_linear_445_6567" x1="1.33398" y1="1.33319" x2="14.6677" y2="14.6669" gradientUnits="userSpaceOnUse">\n <stop stop-color="#FEC163"/>\n <stop offset="1" stop-color="#DE4313"/>\n </linearGradient>\n <linearGradient id="paint1_linear_445_6567" x1="13.333" y1="2" x2="15.0864" y2="2.65753" gradientUnits="userSpaceOnUse">\n <stop stop-color="#FEC163"/>\n <stop offset="1" stop-color="#DE4313"/>\n </linearGradient>\n <linearGradient id="paint2_linear_445_6567" x1="12" y1="3.33331" x2="12.6575" y2="5.08674" gradientUnits="userSpaceOnUse">\n <stop stop-color="#FEC163"/>\n <stop offset="1" stop-color="#DE4313"/>\n </linearGradient>\n <linearGradient id="paint3_linear_445_6567" x1="2.66699" y1="11.3333" x2="3.94699" y2="12.2933" gradientUnits="userSpaceOnUse">\n <stop stop-color="#FEC163"/>\n <stop offset="1" stop-color="#DE4313"/>\n </linearGradient>\n <linearGradient id="paint4_linear_445_6567" x1="2" y1="12" x2="2.96" y2="13.28" gradientUnits="userSpaceOnUse">\n <stop stop-color="#FEC163"/>\n <stop offset="1" stop-color="#DE4313"/>\n </linearGradient>\n </defs>\n </svg>\n ',t.append(n);const o=document.createElement("span");o.className="sage-ai-message-header-title",o.innerText="Sage AI",t.append(o),"user"!==this.lastAddedMessageType&&(t.style.display="none");const s=document.createElement("div");return s.className="sage-ai-message-content sage-ai-streaming-content sage-ai-markdown-content",s.setAttribute("data-raw-text",""),e.appendChild(t),e.appendChild(s),this.container.appendChild(e),this.handleScroll(),console.log("[ChatMessages] Streaming message container added (not yet in history)"),e}renderDiffApprovalFromHistory(e){if(e.diff_cells&&e.diff_cells.length>0){const t=e.diff_cells.map(t=>({cellId:t.cellId,type:t.type,originalContent:t.originalContent||"",newContent:t.newContent||"",displaySummary:t.displaySummary||`${t.type} cell`,notebookId:e.notebook_path,metadata:{}})),n=$.createHistoricalDialog(t,e.notebook_path);this.container.appendChild(n)}this.ensureWaitingReplyBoxIsLast(),this.handleScroll()}createCheckpoint(e){try{const t=m.AppStateService.getCurrentNotebookId();if(!t)throw new Error("No current notebook ID available for checkpoint creation");this.checkpointManager.setCurrentNotebookId(t);const n=this.historyManager.getCurrentThreadId();if(!n)throw new Error("No current thread ID available for checkpoint creation");const o="string"==typeof e.content?e.content:JSON.stringify(e.content);return this.checkpointManager.createCheckpoint(o,this.messageHistory,this.mentionContexts,n,e.id)}catch(e){throw console.error("[ChatMessages] Error creating checkpoint:",e),e}}cancelCheckpointRestoration(){var e,t,n,o;if(!this.checkpointToRestore)return;const s=null===(e=m.AppStateService.getState().chatContainer)||void 0===e?void 0:e.chatWidget.inputManager;s&&(s.setInputValue(""),s.setCheckpointToRestore(null));const i=null===(t=m.AppStateService.getState().chatContainer)||void 0===t?void 0:t.chatWidget.conversationService;i&&this.checkpointToRestore&&i.redoActions(this.checkpointToRestore);let a=null===(n=this.container.querySelector(`[data-checkpoint-id="${this.checkpointToRestore.id}"]`))||void 0===n?void 0:n.nextSibling;for(;a;){const e=a.nextSibling;a instanceof HTMLElement&&a.classList.remove("chat-history-item-opaque"),a=e}null===(o=m.AppStateService.getLlmStateDisplay())||void 0===o||o.hide(),this.checkpointToRestore=null}async performCheckpointRestoration(e){var t,n,o;try{const s=null===(t=m.AppStateService.getState().chatContainer)||void 0===t?void 0:t.chatWidget.inputManager;s&&(s.setInputValue(e.userMessage),s.setCheckpointToRestore(e)),null===(n=m.AppStateService.getState().chatContainer)||void 0===n||n.chatWidget.cancelMessage(),m.AppStateService.getNotebookDiffManager().rejectAndRevertDiffsImmediately(),v.getInstance().clearAllDiffs(m.AppStateService.getCurrentNotebookId());const i=null===(o=m.AppStateService.getState().chatContainer)||void 0===o?void 0:o.chatWidget.conversationService;if(!i)return void console.warn("[ChatMessages] No ConversationService available for checkpoint restoration");await i.startCheckpointRestoration(e),this.checkpointToRestore=e,console.log("[ChatMessages] Checkpoint restoration completed")}catch(e){console.error("[ChatMessages] Error during checkpoint restoration:",e),this.addErrorMessage("Failed to restore checkpoint. Please try again.")}}async restoreToCheckpoint(e){console.log("[ChatMessages] Restoring to checkpoint:",e.id);const t=[...e.messageHistory.filter(t=>t.id!==e.userMessageId)];this.messageHistory=t,this.userMessages=this.messageHistory.filter(e=>"user"===e.role),this.mentionContexts=new Map(e.contexts),this.contextService.setContextItems(this.mentionContexts),await K.cacheNotebookState(e.notebookId,e.notebookState),this.historyManager.updateCurrentThreadMessages(this.messageHistory,this.mentionContexts);const n=this.container.querySelector(`[data-checkpoint-id="${e.id}"]`);if(n){let e=n.nextSibling;for(;e;){const t=e.nextSibling;e instanceof HTMLElement&&e.classList.contains("chat-history-item-opaque")&&(e.classList.remove("chat-history-item-opaque"),this.container.removeChild(e)),e=t}this.container.removeChild(n)}this.checkpointManager.clearCheckpointsAfter(e.id),console.log("[ChatMessages] Message history and contexts restored")}}var Z,X=n(9980);class Q{constructor(e){this.currentNotebookId=null,this.toolService=e}updateNotebookId(e){this.currentNotebookId=e}setNotebookId(e){this.currentNotebookId!==e&&(console.log(`[NotebookStateService] Setting notebook ID to: ${e}`),this.currentNotebookId=e,e&&this.toolService.setCurrentNotebookId(e))}getNotebookId(){return this.currentNotebookId}cleanResult(e){const t=[];if(e&&e.content)for(const n of e.content)try{t.push({...n,text:JSON.parse(n.text)})}catch(e){t.push(n),console.error(e)}return t}async fetchNotebookState(){var e;try{this.currentNotebookId?this.toolService.setCurrentNotebookId(this.currentNotebookId):console.log("No notebook ID set, using default context."),console.log("Fetching notebook state for:",this.currentNotebookId);const t=await(null===(e=this.toolService.notebookTools)||void 0===e?void 0:e.getNotebookSummary(this.currentNotebookId));console.log("Notebook Summary: ===",t);const n=m.AppStateService.getNotebookTools().read_cells({});console.log("Notebook Content ===:",n);const o=[...(null==n?void 0:n.cells)||[]].reverse().slice(0,3);let s="\n\nMost Recent Cells From Most Recent To Oldest:\n";o.forEach((e,t)=>{s+=`\n--- ${0===t&&"Latest "}Cell ---\n${JSON.stringify(e)}\n`});let i="[]";try{this.toolService.filesystemTools?i=await this.toolService.filesystemTools.list_datasets():console.warn("FilesystemTools not available, using empty dataset list")}catch(e){console.error("Error fetching datasets via FilesystemTools:",e),i="[]"}console.log("Datasets:",i);let a=`\n\nAvailable Datasets:\n${i}\n\n`,r="=== SUMMARY OF CELLS IN NOTEBOOK === \n\n";t.forEach(e=>{"planning_cell"===e.id?(r+="- SAGE PLANNING CELL - \n",r+=`cell_index: ${e.index}, cell_id: ${e.id}, summary: ${e.summary}, cell_type: ${e.cell_type}, next_step_string: ${e.next_step_string}, current_step_string: ${e.current_step_string}, empty: ${e.empty}\n`,r+="- END SAGE PLANNING CELL -"):r+=`cell_id: ${e.id}, summary: ${e.summary}, cell_index: ${e.index}, cell_type: ${e.cell_type}, empty: ${e.empty}`,r+="\n\n"}),r+="=== END SUMMARY OF CELLS IN NOTEBOOK ===\n\n",console.log(r);const l=r+a;return console.log("Summary Sent to LLM: ",l),l}catch(e){return console.error("Failed to fetch notebook state:",e),""}}}class ee{constructor(e,t){this.confirmationContainer=null,this.isShowing=!1,this.currentResolver=null,this.currentKeyboardHandler=null,this.chatHistory=e,this.messageComponent=t}triggerApproval(){this.isShowing&&this.currentResolver&&this.executeApproval()}triggerRejection(){this.isShowing&&this.currentResolver&&this.executeRejection()}executeApproval(){this.confirmationContainer&&(this.chatHistory.removeChild(this.confirmationContainer),this.confirmationContainer=null),this.currentResolver&&this.currentResolver(!0),this.cleanup()}executeRejection(){this.confirmationContainer&&(this.chatHistory.removeChild(this.confirmationContainer),this.confirmationContainer=null),this.currentResolver&&this.currentResolver(!1),this.cleanup()}cleanup(){this.isShowing=!1,this.currentResolver=null,this.currentKeyboardHandler&&(document.removeEventListener("keydown",this.currentKeyboardHandler),this.currentKeyboardHandler=null)}async showConfirmation(e,t){return!t&&(this.isShowing=!0,new Promise(t=>{this.currentResolver=t,this.confirmationContainer=document.createElement("div"),this.confirmationContainer.className="sage-ai-code-confirmation";const n=document.createElement("span");n.style.fontSize="var(--jp-ui-font-size1)",n.style.color="var(--jp-ui-font-color1)",n.style.fontWeight="500",n.style.display="flex",n.style.alignItems="center",n.style.gap="4px",n.innerHTML=`<svg width="14px" height="14px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path fill-rule="evenodd" clip-rule="evenodd" d="M4.5 6L5.25 5.25H18.75L19.5 6V18L18.75 18.75H5.25L4.5 18V6ZM6 6.75V17.25H18V6.75H6ZM10.1894 12L7.71973 9.5303L8.78039 8.46964L12.3107 12L8.78039 15.5303L7.71973 14.4696L10.1894 12ZM12 15.75H15.75V14.25H12V15.75Z" fill="var(--jp-ui-font-color0)"></path> </g></svg> Sage is trying to run ${e||"cell"}`,n.className="sage-ai-code-confirmation-heading",this.confirmationContainer.appendChild(n);const o=document.createElement("div");o.className="sage-ai-confirmation-button-container";const s=document.createElement("button");s.textContent="Reject",s.className="sage-ai-reject-button";const i=document.createElement("button");let a=/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"⌘":"⌃";const r=document.createElement("span");r.style.display="flex",r.style.alignItems="center";const l=document.createElement("span");l.style.display="inline-flex",l.style.alignItems="center",l.style.fontFamily="monospace",l.style.fontWeight="bold",l.style.marginLeft="4px",l.style.marginRight="2px",l.textContent=a;const c=document.createElement("span");c.style.display="inline-flex",c.style.alignItems="center",c.style.fontFamily="monospace",c.style.fontWeight="bold",c.textContent="⏎";const d=document.createElement("span");d.style.fontSize="var(--jp-ui-font-size1)",d.textContent="Run",r.appendChild(d),r.appendChild(l),r.appendChild(c),i.appendChild(r),i.className="sage-ai-confirm-button",o.appendChild(s),o.appendChild(i);const h=document.createElement("div");h.className="sage-ai-confirmation-bottom-container",h.appendChild(o),this.confirmationContainer.appendChild(h),this.chatHistory.appendChild(this.confirmationContainer),this.messageComponent.handleScroll();const u=e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),this.executeApproval())};this.currentKeyboardHandler=u,document.addEventListener("keydown",u),i.addEventListener("click",()=>{this.executeApproval()}),s.addEventListener("click",()=>{this.executeRejection()})}))}isDialogShowing(){return this.isShowing}}class te{async showDialog(){const e=document.createElement("div");e.className="sage-ai-modal";const t=document.createElement("div");t.className="sage-ai-dialog";const n=document.createElement("h3");n.textContent="Cell Execution Rejected",n.className="sage-ai-dialog-title";const o=document.createElement("label");o.textContent="Could you explain why you rejected the code execution? This will help improve the next attempt:",o.className="sage-ai-dialog-label";const s=document.createElement("textarea");s.className="sage-ai-dialog-textarea";const i=document.createElement("div");i.className="sage-ai-dialog-button-container";const a=document.createElement("button");return a.textContent="Submit",a.className="sage-ai-dialog-submit-button",i.appendChild(a),t.appendChild(n),t.appendChild(o),t.appendChild(s),t.appendChild(i),e.appendChild(t),document.body.appendChild(e),new Promise(t=>{a.addEventListener("click",()=>{const n=s.value.trim();document.body.removeChild(e),t(n)})})}}!function(e){e.ADD_CELL="add_cell",e.EDIT_CELL="edit_cell",e.REMOVE_CELLS="remove_cells",e.EDIT_PLAN="edit_plan"}(Z||(Z={}));class ne{constructor(){this.history=[]}addActionWithCheckpoint(e,t,n){const o={type:e,data:t,timestamp:Date.now(),description:n};this.history.push(o),console.log(`[ActionHistory] Added action: ${n}`);try{G.getInstance().addActionToCurrentCheckpoint(o)}catch(e){console.warn("[ActionHistory] Could not add action to checkpoint:",e)}}getLastAction(){return 0===this.history.length?null:this.history[this.history.length-1]}popLastAction(){if(0===this.history.length)return null;const e=this.history.pop();return console.log("Action popped for undo:",e),e}canUndo(){return this.history.length>0}getLastActionDescription(){const e=this.getLastAction();return e?e.description:null}getAllActions(){return[...this.history]}clear(){this.history=[],console.log("Action history cleared")}}var oe=n(3345),se=n(4602);class ie{static initialize(e){ie.settingsRegistry=e}static async getSetting(e,t){if(!ie.settingsRegistry)return console.warn("[CachingService] Settings registry not initialized, using default value"),t;try{const n=(await ie.settingsRegistry.load(ie.PLUGIN_ID)).get(e).composite;return void 0!==n?n:t}catch(n){return console.warn(`[CachingService] Failed to get setting '${e}':`,n),t}}static async setSetting(e,t){if(ie.settingsRegistry)try{const n=await ie.settingsRegistry.load(ie.PLUGIN_ID);await n.set(e,t),await n.save(n.raw)}catch(t){console.error(`[CachingService] Failed to set setting '${e}':`,t)}else console.warn("[CachingService] Settings registry not initialized, cannot set setting")}static async removeSetting(e){if(ie.settingsRegistry)try{const t=await ie.settingsRegistry.load(ie.PLUGIN_ID);await t.remove(e),await t.save(t.raw)}catch(t){console.error(`[CachingService] Failed to remove setting '${e}':`,t)}else console.warn("[CachingService] Settings registry not initialized, cannot remove setting")}static async getBooleanSetting(e,t=!1){return ie.getSetting(e,t)}static async setBooleanSetting(e,t){return ie.setSetting(e,t)}static async getStringSetting(e,t=""){return ie.getSetting(e,t)}static async setStringSetting(e,t){return ie.setSetting(e,t)}static async getObjectSetting(e,t){return ie.getSetting(e,t)}static async setObjectSetting(e,t){return ie.setSetting(e,t)}static isAvailable(){return null!==ie.settingsRegistry}static async getAllSettings(){if(!ie.settingsRegistry)return{};try{return(await ie.settingsRegistry.load(ie.PLUGIN_ID)).composite}catch(e){return console.error("[CachingService] Failed to get all settings:",e),{}}}}ie.settingsRegistry=null,ie.PLUGIN_ID="sage-agent-internal:plugin";const ae="darkThemeApplied",re="updateDeclinedVersion",le="chatHistories",ce="codebases",de="sageTokenMode",he="tabAutocompleteEnabled",ue="claudeApiKey",pe="claudeModelId",ge="claudeModelUrl",me="databaseUrl";class fe{constructor(e){this.codebases=[],this.isInitialized=!1,this.toolService=e,this.element=this.createUI(),this.loadCodebases()}getElement(){return this.element}createUI(){const e=document.createElement("div");e.className="sage-ai-codebase-manager",e.style.display="none";const t=document.createElement("h3");t.textContent="Codebase Search",t.className="sage-ai-section-title";const n=document.createElement("p");n.textContent="Manage codebases that the AI can search through and reference.",n.className="sage-ai-section-description",this.addForm=this.createAddForm(),this.codebaseListElement=document.createElement("div"),this.codebaseListElement.className="sage-ai-codebase-list";const o=document.createElement("div");return o.className="sage-ai-empty-state",o.textContent="No codebases added yet. Add a codebase to enable AI code search.",this.codebaseListElement.appendChild(o),e.appendChild(t),e.appendChild(n),e.appendChild(this.addForm),e.appendChild(this.codebaseListElement),e}createAddForm(){const e=document.createElement("form");e.className="sage-ai-add-repo-form";const t=document.createElement("div");t.className="sage-ai-form-group";const n=document.createElement("label");n.textContent="Repository Path:",n.htmlFor="repo-path";const o=document.createElement("input");o.type="text",o.id="repo-path",o.placeholder="/path/to/codebase",o.className="sage-ai-input",t.appendChild(n),t.appendChild(o);const s=document.createElement("div");s.className="sage-ai-form-group";const i=document.createElement("label");i.textContent="Name (optional):",i.htmlFor="repo-name";const a=document.createElement("input");a.type="text",a.id="repo-name",a.placeholder="e.g., My Project",a.className="sage-ai-input",s.appendChild(i),s.appendChild(a);const r=document.createElement("div");r.className="sage-ai-form-group";const l=document.createElement("label");l.textContent="Instructions (optional):",l.htmlFor="repo-instructions";const c=document.createElement("textarea");c.id="repo-instructions",c.placeholder="e.g., Import the bot class like this: from twitter_bots.crypto_sherpa import CryptoSherpa",c.className="sage-ai-textarea",c.rows=3,r.appendChild(l),r.appendChild(c);const d=document.createElement("button");return d.type="submit",d.className="sage-ai-button sage-ai-primary-button",d.textContent="Add Repository",e.appendChild(t),e.appendChild(s),e.appendChild(r),e.appendChild(d),e.addEventListener("submit",e=>{e.preventDefault(),this.addRepository(o.value.trim(),a.value.trim(),c.value.trim()),o.value="",a.value="",c.value=""}),e}async loadCodebases(){try{const e=await ie.getObjectSetting(ce,[]);this.codebases=e||[],console.log("Loaded codebases from settings registry:",this.codebases),this.renderCodebaseList()}catch(e){console.error("Failed to load codebases:",e),this.codebases=[],this.renderCodebaseList()}}async saveCodebasesToStorage(){try{await ie.setObjectSetting(ce,this.codebases),console.log("Saved codebases to settings registry")}catch(e){console.error("Failed to save codebases to settings registry:",e)}}async addRepository(e,t,n){if(!e)return void alert("Repository path is required");const o=e;try{const s={id:o,path:e,name:t||e.split("/").pop()||e,instructions:n};this.codebases.push(s),await this.saveCodebasesToStorage(),this.renderCodebaseList(),console.log("Repository added locally (backend integration disabled):",s)}catch(e){console.error("Failed to add repository:",e),alert(`Failed to add repository: ${e instanceof Error?e.message:"Unknown error"}`)}}async reloadRepository(e){const t=this.codebases.find(t=>t.id===e);if(t)try{console.log("Repository reload requested (backend integration disabled):",t.path),this.renderCodebaseList()}catch(e){console.error("Failed to reload repository:",e),alert(`Failed to reload repository: ${e instanceof Error?e.message:"Unknown error"}`),this.renderCodebaseList()}}async removeRepository(e){const t=this.codebases.find(t=>t.id===e);if(t&&confirm("Are you sure you want to remove this repository? This action cannot be undone."))try{this.codebases=this.codebases.filter(t=>t.id!==e),await this.saveCodebasesToStorage(),console.log("Repository removed locally (backend integration disabled):",t.path),this.renderCodebaseList(),alert(`Repository at ${t.path} removed locally.`)}catch(e){console.error("Failed to remove repository:",e),alert(`Failed to remove repository: ${e instanceof Error?e.message:"Unknown error"}`)}}editInstructions(e){const t=this.codebases.find(t=>t.id===e);if(!t)return;const n=t.instructions||"",o=prompt("Edit instructions for this codebase:",n);null!==o&&o!==n&&(t.instructions=o,this.renderCodebaseList())}renderCodebaseList(){if(this.codebaseListElement.innerHTML="",0===this.codebases.length){const e=document.createElement("div");return e.className="sage-ai-empty-state",e.textContent="No codebases added yet. Add a codebase to enable AI code search.",void this.codebaseListElement.appendChild(e)}this.codebases.forEach(e=>{const t=document.createElement("div");t.className="sage-ai-codebase-item";const n=document.createElement("div");n.className="sage-ai-codebase-header";const o=document.createElement("h4");o.className="sage-ai-codebase-title",o.textContent=e.name;const s=document.createElement("div");s.className="sage-ai-codebase-actions";const i=document.createElement("button");i.className="sage-ai-action-button",i.textContent="Reload",i.addEventListener("click",()=>this.reloadRepository(e.id));const a=document.createElement("button");a.className="sage-ai-action-button",a.textContent="Edit Instructions",a.addEventListener("click",()=>this.editInstructions(e.id));const r=document.createElement("button");r.className="sage-ai-action-button sage-ai-danger-button",r.textContent="Remove",r.addEventListener("click",()=>this.removeRepository(e.id)),s.appendChild(i),s.appendChild(a),s.appendChild(r),n.appendChild(o),n.appendChild(s);const l=document.createElement("div");let c;l.className="sage-ai-codebase-path",l.textContent=e.path,e.instructions&&(c=document.createElement("div"),c.className="sage-ai-codebase-instructions",c.textContent=e.instructions),t.appendChild(n),t.appendChild(l),c&&t.appendChild(c),this.codebaseListElement.appendChild(t)})}}var ve=n(2364);class Ce{static setDbUrlInKernel(e){var t;try{const n=null!=e?e:m.AppStateService.getState().settings.databaseUrl;console.log("[KernelUtils] Attempting to set DB_URL in kernel:",n?"configured":"not configured"),console.log("[KernelUtils] Database URL value:",n);const o=m.AppStateService.getToolService(),s=null===(t=null==o?void 0:o.getCurrentNotebook())||void 0===t?void 0:t.kernel;if(!s)return void console.warn("[KernelUtils] No kernel available to set DB_URL");if(n&&""!==n.trim()){const e=`\nimport os\nos.environ['DB_URL'] = '${n.replace(/'/g,"\\'")}'\nprint(f"[KernelUtils] DB_URL environment variable set: {os.environ.get('DB_URL', 'Not set')}")\n `;console.log("[KernelUtils] Setting DB_URL environment variable in kernel. URL:",n.length>50?n.substring(0,50)+"...":n),s.requestExecute({code:e,silent:!1})}else{const e="\nimport os\nif 'DB_URL' in os.environ:\n del os.environ['DB_URL']\n print(\"[KernelUtils] DB_URL environment variable removed\")\nelse:\n print(\"[KernelUtils] DB_URL environment variable was not set\")\n ";console.log("[KernelUtils] Removing DB_URL environment variable from kernel"),s.requestExecute({code:e,silent:!1})}}catch(e){console.error("[KernelUtils] Error setting DB_URL in kernel:",e)}}static checkDbUrlInKernel(){var e;try{const t=m.AppStateService.getToolService(),n=null===(e=null==t?void 0:t.getCurrentNotebook())||void 0===e?void 0:e.kernel;if(!n)return void console.warn("[KernelUtils] No kernel available to check DB_URL");const o='\nimport os\ndb_url = os.environ.get(\'DB_URL\')\nprint(f"[KernelUtils Check] Current DB_URL: {db_url}")\nif db_url:\n print(f"[KernelUtils Check] DB_URL length: {len(db_url)}")\n print(f"[KernelUtils Check] DB_URL starts with: {db_url[:50]}...")\nelse:\n print("[KernelUtils Check] DB_URL is not set")\n ';console.log("[KernelUtils] Checking current DB_URL in kernel"),n.requestExecute({code:o,silent:!1})}catch(e){console.error("[KernelUtils] Error checking DB_URL in kernel:",e)}}static debugAppStateDatabaseUrl(){var e;try{const t=m.AppStateService.getState();console.log("[KernelUtils] AppState settings:",t.settings),console.log("[KernelUtils] Database URL from AppState:",t.settings.databaseUrl),console.log("[KernelUtils] Database URL type:",typeof t.settings.databaseUrl),console.log("[KernelUtils] Database URL length:",null===(e=t.settings.databaseUrl)||void 0===e?void 0:e.length)}catch(e){console.error("[KernelUtils] Error debugging AppState:",e)}}static async setDbUrlInKernelWithRetry(e,t=3,n=1e3){var o;if(this.isRetrying)console.log("[KernelUtils] Already retrying DB_URL setup, skipping duplicate attempt");else{this.isRetrying=!0,console.log("[KernelUtils] Starting DB_URL retry process..."),this.debugAppStateDatabaseUrl();try{for(let s=0;s<t;s++)try{const i=m.AppStateService.getToolService();if(null===(o=null==i?void 0:i.getCurrentNotebook())||void 0===o?void 0:o.kernel)return console.log(`[KernelUtils] Kernel available on attempt ${s+1}, setting DB_URL`),this.setDbUrlInKernel(e),void console.log("[KernelUtils] DB_URL retry process completed successfully");console.log(`[KernelUtils] Kernel not ready, attempt ${s+1}/${t}, waiting ${n}ms...`),s<t-1&&await new Promise(e=>setTimeout(e,n))}catch(e){console.error(`[KernelUtils] Error on attempt ${s+1}:`,e),s<t-1&&await new Promise(e=>setTimeout(e,n))}console.warn("[KernelUtils] Failed to set DB_URL after all retry attempts")}finally{this.isRetrying=!1}}}static async getKernelPreview(){return ve.F.getKernelPreview()}}Ce.isRetrying=!1;var be=n(5606);class ye{constructor(){}async createTemporaryKernel(){var e;try{console.log("[DatabaseTools] Creating temporary kernel session...");const t=m.AppStateService.getServiceManager();if(!t)throw new Error("Service manager not available");const n=t.sessions,o=t.kernelspecs;await o.refreshSpecs();const s=o.specs;let i="python3";(null==s?void 0:s.kernelspecs[i])||(i="python",(null==s?void 0:s.kernelspecs[i])||(i=(null==s?void 0:s.default)||"python3")),console.log(`[DatabaseTools] Using kernel spec: ${i}`);const a=`database-temp-${Date.now()}-${Math.random().toString(36).substring(7)}`,r=await n.startNew({name:a,path:`temp/${a}`,type:"file",kernel:{name:i}});console.log(`[DatabaseTools] Created temporary session: ${r.id}`),r.kernel&&await new Promise(e=>setTimeout(e,2e3)),console.log("[DatabaseTools] Temporary kernel is ready");const l=m.AppStateService.getState().settings.databaseUrl;if(l){console.log("[DatabaseTools] Setting DB_URL in temporary kernel");const t=`\nimport os\nos.environ['DB_URL'] = '${l.replace(/'/g,"\\'")}'\nprint("[DatabaseTools] DB_URL environment variable set in temporary kernel")\n `;null===(e=r.kernel)||void 0===e||e.requestExecute({code:t,silent:!0})}return{kernel:r.kernel,cleanup:()=>{console.log(`[DatabaseTools] Cleaning up temporary session: ${r.id}`),n.shutdown(r.id).catch(e=>{console.warn(`[DatabaseTools] Error shutting down session ${r.id}:`,e)})}}}catch(e){throw console.error("[DatabaseTools] Error creating temporary kernel:",e),e}}async getDatabaseMetadataAsText(e){try{console.log("[DatabaseTools] Fetching database schema info via temporary kernel...");const{kernel:t,cleanup:n}=await this.createTemporaryKernel();if(!t)return"Error: Failed to create temporary kernel for database query";const o=`\nimport os\nimport json\nimport subprocess\nimport sys\n\n# Function to install packages if they don't exist\ndef install_package(package_name):\n try:\n subprocess.check_call([sys.executable, "-m", "pip", "install", package_name])\n print(f"[DatabaseTools] Successfully installed {package_name}")\n return True\n except subprocess.CalledProcessError as e:\n print(f"[DatabaseTools] Failed to install {package_name}: {str(e)}")\n return False\n\n# Check if required modules are available, install if missing\nmissing_packages = []\ntry:\n import sqlalchemy\nexcept ImportError:\n print("[DatabaseTools] sqlalchemy not found, attempting to install...")\n if install_package("sqlalchemy"):\n try:\n import sqlalchemy\n print("[DatabaseTools] sqlalchemy successfully imported after installation")\n except ImportError as e:\n missing_packages.append(f"sqlalchemy: {str(e)}")\n else:\n missing_packages.append("sqlalchemy: installation failed")\n\ntry:\n import psycopg2\nexcept ImportError:\n print("[DatabaseTools] psycopg2 not found, attempting to install psycopg2-binary...")\n if install_package("psycopg2-binary"):\n try:\n import psycopg2\n print("[DatabaseTools] psycopg2 successfully imported after installation")\n except ImportError as e:\n missing_packages.append(f"psycopg2: {str(e)}")\n else:\n missing_packages.append("psycopg2: installation failed")\n\n# If any packages are still missing after installation attempts, exit with error\nif missing_packages:\n print(json.dumps({"error": f"Required modules could not be installed: {', '.join(missing_packages)}"}))\n exit()\n\ntry:\n # Use provided dbUrl or get from environment\n db_url = ${e?`'${e.replace(/'/g,"\\'")}'`:"os.environ.get('DB_URL')"}\n \n if not db_url:\n print(json.dumps({"error": "No database URL provided and DB_URL environment variable not set"}))\n else:\n from sqlalchemy import create_engine, text\n \n engine = create_engine(db_url)\n \n with engine.connect() as conn:\n # Get all tables from public and custom schemas (excluding system schemas)\n tables_query = """\n SELECT table_schema, table_name \n FROM information_schema.tables \n WHERE table_type = 'BASE TABLE' \n AND table_schema NOT IN ('information_schema', 'pg_catalog', 'pg_toast')\n ORDER BY table_schema, table_name\n LIMIT 50;\n """\n \n tables_result = conn.execute(text(tables_query))\n tables = [dict(row._mapping) for row in tables_result]\n \n if not tables:\n print(json.dumps({"result": "Database connected successfully, but no tables found."}))\n else:\n # Start building markdown formatted output\n markdown_output = f"# Database Schema\\n\\nFound **{len(tables)}** table(s)\\n\\n"\n \n # Get detailed information for each table\n for table in tables:\n table_schema = table['table_schema']\n table_name = table['table_name']\n full_table_name = f"{table_schema}.{table_name}"\n \n # Get columns\n columns_query = """\n SELECT \n column_name, \n data_type, \n is_nullable, \n column_default,\n character_maximum_length,\n numeric_precision,\n numeric_scale\n FROM information_schema.columns \n WHERE table_schema = :schema AND table_name = :table\n ORDER BY ordinal_position\n LIMIT 30;\n """\n \n columns_result = conn.execute(text(columns_query), \n {"schema": table_schema, "table": table_name})\n columns = [dict(row._mapping) for row in columns_result]\n \n # Get primary keys\n pk_query = """\n SELECT kcu.column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu \n ON tc.constraint_name = kcu.constraint_name\n WHERE tc.constraint_type = 'PRIMARY KEY' \n AND tc.table_schema = :schema \n AND tc.table_name = :table\n ORDER BY kcu.ordinal_position;\n """\n \n pk_result = conn.execute(text(pk_query), \n {"schema": table_schema, "table": table_name})\n primary_keys = [row[0] for row in pk_result]\n \n # Get foreign keys\n fk_query = """\n SELECT \n kcu.column_name,\n ccu.table_schema AS foreign_table_schema,\n ccu.table_name AS foreign_table_name,\n ccu.column_name AS foreign_column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu \n ON tc.constraint_name = kcu.constraint_name\n JOIN information_schema.constraint_column_usage ccu \n ON ccu.constraint_name = tc.constraint_name\n WHERE tc.constraint_type = 'FOREIGN KEY' \n AND tc.table_schema = :schema \n AND tc.table_name = :table\n ORDER BY kcu.ordinal_position;\n """\n \n fk_result = conn.execute(text(fk_query), \n {"schema": table_schema, "table": table_name})\n foreign_keys = [dict(row._mapping) for row in fk_result]\n \n # Get indices\n index_query = """\n SELECT \n indexname,\n indexdef\n FROM pg_indexes\n WHERE schemaname = :schema \n AND tablename = :table\n AND indexname NOT LIKE '%_pkey'\n ORDER BY indexname;\n """\n \n index_result = conn.execute(text(index_query), \n {"schema": table_schema, "table": table_name})\n indices = [dict(row._mapping) for row in index_result]\n \n # Build table section\n markdown_output += f"## {full_table_name}\\n\\n"\n \n # Columns section\n markdown_output += f"### Columns ({len(columns)})\\n\\n"\n for col in columns:\n col_name = col['column_name']\n data_type = col['data_type']\n \n # Format data type with precision/scale\n if col['character_maximum_length']:\n data_type += f"({col['character_maximum_length']})"\n elif col['numeric_precision'] and col['numeric_scale'] is not None:\n data_type += f"({col['numeric_precision']},{col['numeric_scale']})"\n elif col['numeric_precision']:\n data_type += f"({col['numeric_precision']})"\n \n # Add constraints\n constraints = []\n if col['is_nullable'] == 'NO':\n constraints.append("NOT NULL")\n if col['column_default']:\n constraints.append(f"DEFAULT {col['column_default']}")\n if col_name in primary_keys:\n constraints.append("PRIMARY KEY")\n \n constraint_text = f" ({', '.join(constraints)})" if constraints else ""\n \n markdown_output += f"- **{col_name}**: {data_type}{constraint_text}\\n"\n \n # Primary keys section\n if primary_keys:\n markdown_output += f"\\n### Primary Keys\\n\\n"\n markdown_output += f"- {', '.join([f'**{pk}**' for pk in primary_keys])}\\n"\n \n # Foreign keys section\n if foreign_keys:\n markdown_output += f"\\n### Foreign Keys\\n\\n"\n for fk in foreign_keys:\n markdown_output += f"- **{fk['column_name']}** → {fk['foreign_table_schema']}.{fk['foreign_table_name']}({fk['foreign_column_name']})\\n"\n \n # Indices section\n if indices:\n markdown_output += f"\\n### Indices\\n\\n"\n for idx in indices:\n markdown_output += f"- **{idx['indexname']}**: {idx['indexdef']}\\n"\n \n markdown_output += "\\n---\\n\\n"\n \n print(json.dumps({"result": markdown_output.strip()}))\n \nexcept Exception as e:\n print(json.dumps({"error": f"Error connecting to database: {str(e)}"}))\n`;return new Promise(e=>{let s="";const i=t.requestExecute({code:o,silent:!0});i.onIOPub=e=>{"stream"===e.header.msg_type&&"stdout"===e.content.name?s+=e.content.text:"execute_result"===e.header.msg_type&&e.content.data&&e.content.data["text/plain"]&&(s+=e.content.data["text/plain"])},i.done.then(()=>{try{const t=JSON.parse(s.trim());if(t.error)console.error("[DatabaseTools] Database error:",t.error),e(t.error);else{console.log("[DatabaseTools] Database schema info retrieved successfully");const n=t.result.split("\\n").join("\n");e(n)}}catch(t){console.error("[DatabaseTools] Error parsing kernel output:",t),e(`Error parsing database query result: ${s}`)}finally{n()}}).catch(t=>{console.error("[DatabaseTools] Kernel execution error:",t),n(),e(`Error executing database query in kernel: ${t.message}`)})})}catch(e){return console.error("[DatabaseTools] Error getting database schema info:",e),`Error getting database schema info: ${e instanceof Error?e.message:String(e)}`}}async getDatabaseMetadata(e){try{const t=await this.getDatabaseMetadataAsText(e);return t.startsWith("Error:")?JSON.stringify({error:t}):JSON.stringify({schema_info:t,db_url_configured:!!e||!!be.env.DB_URL})}catch(e){return console.error("[DatabaseTools] Error getting database metadata:",e),JSON.stringify({error:`Failed to get database metadata: ${e instanceof Error?e.message:String(e)}`})}}async executeQuery(e,t){try{console.log("[DatabaseTools] Executing SQL query via temporary kernel...");const{kernel:n,cleanup:o}=await this.createTemporaryKernel();if(!n)return JSON.stringify({error:"Failed to create temporary kernel for database query"});const s=e.trim().toUpperCase();if(!s.startsWith("SELECT")&&!s.startsWith("WITH"))return JSON.stringify({error:"Only SELECT or WITH statements are allowed for read queries."});const i=`\nimport os\nimport json\nimport subprocess\nimport sys\n\n# Function to install packages if they don't exist\ndef install_package(package_name):\n try:\n subprocess.check_call([sys.executable, "-m", "pip", "install", package_name])\n print(f"[DatabaseTools] Successfully installed {package_name}")\n return True\n except subprocess.CalledProcessError as e:\n print(f"[DatabaseTools] Failed to install {package_name}: {str(e)}")\n return False\n\n# Check if required modules are available, install if missing\nmissing_packages = []\ntry:\n import sqlalchemy\nexcept ImportError:\n print("[DatabaseTools] sqlalchemy not found, attempting to install...")\n if install_package("sqlalchemy"):\n try:\n import sqlalchemy\n print("[DatabaseTools] sqlalchemy successfully imported after installation")\n except ImportError as e:\n missing_packages.append(f"sqlalchemy: {str(e)}")\n else:\n missing_packages.append("sqlalchemy: installation failed")\n\ntry:\n import psycopg2\nexcept ImportError:\n print("[DatabaseTools] psycopg2 not found, attempting to install psycopg2-binary...")\n if install_package("psycopg2-binary"):\n try:\n import psycopg2\n print("[DatabaseTools] psycopg2 successfully imported after installation")\n except ImportError as e:\n missing_packages.append(f"psycopg2: {str(e)}")\n else:\n missing_packages.append("psycopg2: installation failed")\n\n# If any packages are still missing after installation attempts, exit with error\nif missing_packages:\n print(json.dumps({"error": f"Required modules could not be installed: {', '.join(missing_packages)}"}))\n exit()\n\ntry:\n # Use provided dbUrl or get from environment\n db_url = ${t?`'${t.replace(/'/g,"\\'")}'`:"os.environ.get('DB_URL')"}\n \n if not db_url:\n print(json.dumps({"error": "No database URL provided and DB_URL environment variable not set"}))\n else:\n from sqlalchemy import create_engine, text\n \n engine = create_engine(db_url)\n \n with engine.connect() as conn:\n query = """${e.replace(/"/g,'\\"').replace(/\n/g,"\\n")}"""\n result = conn.execute(text(query))\n \n # Convert result to list of dictionaries\n rows = [dict(row._mapping) for row in result]\n \n print(json.dumps({"result": rows}))\n \nexcept Exception as e:\n print(json.dumps({"error": f"Database query failed: {str(e)}"}))\n`;return new Promise(e=>{let t="";const s=n.requestExecute({code:i,silent:!0});s.onIOPub=e=>{"stream"===e.header.msg_type&&"stdout"===e.content.name?t+=e.content.text:"execute_result"===e.header.msg_type&&e.content.data&&e.content.data["text/plain"]&&(t+=e.content.data["text/plain"])},s.done.then(()=>{try{const n=JSON.parse(t.trim());e(JSON.stringify(n))}catch(n){console.error("[DatabaseTools] Error parsing kernel output:",n),console.error("[DatabaseTools] Raw output:",t),e(JSON.stringify({error:`Error parsing database query result: ${t}`}))}finally{o()}}).catch(t=>{console.error("[DatabaseTools] Kernel execution error:",t),o(),e(JSON.stringify({error:`Error executing database query in kernel: ${t.message}`}))})})}catch(e){return console.error("[DatabaseTools] Error executing SQL query:",e),JSON.stringify({error:`Failed to execute SQL query: ${e instanceof Error?e.message:String(e)}`})}}}class ke{constructor(){this.cache=null,this.refreshTimer=null,this.CACHE_DURATION_MS=3e5,this.CACHE_KEY="database-metadata",this.metadataSubject=new f.BehaviorSubject(null),this.metadata$=this.metadataSubject.asObservable(),this.loadCacheFromStateDB(),this.startAutoRefresh()}static getInstance(){return ke.instance||(ke.instance=new ke),ke.instance}async getDatabaseUrl(){try{if(ie.isAvailable())try{const e=await ie.getStringSetting(me,"");if(e&&""!==e.trim())return console.log("[DatabaseMetadataCache] Retrieved database URL from settings registry:",e.length>50?e.substring(0,50)+"...":e),e}catch(e){console.warn("[DatabaseMetadataCache] Failed to get database URL from settings registry:",e)}else console.log("[DatabaseMetadataCache] Settings registry not available, trying AppState");try{const e=m.AppStateService.getState().settings.databaseUrl;if(e&&""!==e.trim())return console.log("[DatabaseMetadataCache] Retrieved database URL from AppState:",e.length>50?e.substring(0,50)+"...":e),e}catch(e){console.warn("[DatabaseMetadataCache] Failed to get database URL from AppState:",e)}try{const e=m.AppStateService.getSettingsRegistry();if(e){const t=(await e.load("sage-agent-internal:plugin")).get("databaseUrl").composite;if(t&&""!==t.trim())return console.log("[DatabaseMetadataCache] Retrieved database URL from direct settings registry access:",t.length>50?t.substring(0,50)+"...":t),t}}catch(e){console.warn("[DatabaseMetadataCache] Failed to get database URL from direct settings access:",e)}return console.log("[DatabaseMetadataCache] No database URL found from any source"),""}catch(e){return console.error("[DatabaseMetadataCache] Unexpected error getting database URL:",e),""}}async getMetadata(){const e=await this.getDatabaseUrl();return e&&""!==e.trim()?this.isCacheValid(e)?(console.log("[DatabaseMetadataCache] Using cached metadata"),this.cache.schema):await this.refreshMetadata(e):null}async getCachedMetadata(){const e=await this.getDatabaseUrl();return e&&""!==e.trim()?this.isCacheValid(e)?(console.log("[DatabaseMetadataCache] Using cached metadata (no refresh)"),this.cache.schema):(console.log("[DatabaseMetadataCache] No valid cached metadata available"),null):null}async isKernelAvailable(){try{const e=m.AppStateService.getToolService(),t=null==e?void 0:e.getCurrentNotebook(),n=null==t?void 0:t.kernel;return n?"idle"!==n.status&&"busy"!==n.status?(console.log("[DatabaseMetadataCache] Kernel not ready, status:",n.status),!1):(console.log("[DatabaseMetadataCache] Kernel is available and ready"),!0):(console.log("[DatabaseMetadataCache] No kernel available"),!1)}catch(e){return console.warn("[DatabaseMetadataCache] Error checking kernel availability:",e),!1}}async waitForKernel(e=3e4){const t=Date.now();for(console.log("[DatabaseMetadataCache] Waiting for kernel to become available...");Date.now()-t<e;){if(await this.isKernelAvailable())return console.log("[DatabaseMetadataCache] Kernel is now available"),!0;await new Promise(e=>setTimeout(e,1e3))}return console.warn("[DatabaseMetadataCache] Timeout waiting for kernel to become available"),!1}async refreshMetadata(e){const t=e||await this.getDatabaseUrl();if(!t||""===t.trim())return this.clearCache(),null;if(console.log("[DatabaseMetadataCache] Fetching fresh database metadata..."),!await this.isKernelAvailable()&&(console.log("[DatabaseMetadataCache] Kernel not available, waiting..."),!await this.waitForKernel(15e3))){const e="Kernel not available after waiting - database metadata fetch skipped";return console.warn("[DatabaseMetadataCache]",e),null}try{const e=new ye,n=await e.getDatabaseMetadataAsText(t);return n&&!n.startsWith("Error:")?(this.cache={schema:n,lastUpdated:Date.now(),url:t},this.metadataSubject.next(this.cache),await this.saveCacheToStateDB(),console.log("[DatabaseMetadataCache] Database metadata cached successfully"),n):(console.warn("[DatabaseMetadataCache] Failed to fetch database metadata:",n),this.clearCache(),null)}catch(e){console.error("[DatabaseMetadataCache] Error fetching database metadata:",e);const t=(null==e?void 0:e.toString())||"";return t.includes("kernel")||t.includes("No kernel available")?(console.log("[DatabaseMetadataCache] Kernel-related error, will retry later"),null):(this.clearCache(),null)}}isCacheValid(e){return!!this.cache&&(this.cache.url===e&&Date.now()-this.cache.lastUpdated<this.CACHE_DURATION_MS)}clearCache(){this.cache=null,this.metadataSubject.next(null),this.clearCacheFromStateDB(),console.log("[DatabaseMetadataCache] Cache cleared")}async loadCacheFromStateDB(){try{const e=await q.K.getObjectValue(this.CACHE_KEY,null);e&&(this.cache=e,this.metadataSubject.next(this.cache),console.log("[DatabaseMetadataCache] Loaded cache from StateDB"))}catch(e){console.error("[DatabaseMetadataCache] Failed to load cache from StateDB:",e)}}async saveCacheToStateDB(){if(this.cache)try{await q.K.setObjectValue(this.CACHE_KEY,this.cache)}catch(e){console.error("[DatabaseMetadataCache] Failed to save cache to StateDB:",e)}}async clearCacheFromStateDB(){try{await q.K.removeValue(this.CACHE_KEY)}catch(e){console.error("[DatabaseMetadataCache] Failed to clear cache from StateDB:",e)}}startAutoRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(async()=>{try{const e=await this.getDatabaseUrl();e&&""!==e.trim()&&this.cache&&(await this.isKernelAvailable()?(console.log("[DatabaseMetadataCache] Auto-refreshing database metadata..."),await this.refreshMetadata(e)):console.log("[DatabaseMetadataCache] Skipping auto-refresh - kernel not available"))}catch(e){console.warn("[DatabaseMetadataCache] Auto-refresh failed:",e)}},this.CACHE_DURATION_MS)}stopAutoRefresh(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}async initializeOnStartup(){console.log("[DatabaseMetadataCache] Starting initialization..."),await new Promise(e=>setTimeout(e,2e3));try{const e=await this.getDatabaseUrl();console.log("[DatabaseMetadataCache] Retrieved database URL during initialization:",e?"configured":"not configured"),e&&""!==e.trim()?(console.log("[DatabaseMetadataCache] Database URL is configured, attempting to fetch metadata..."),await this.isKernelAvailable()?this.refreshMetadata(e).catch(t=>{console.warn("[DatabaseMetadataCache] Startup initialization failed:",t),this.scheduleRetryWithBackoff(e,1)}):(console.log("[DatabaseMetadataCache] Kernel not available during initialization, scheduling retry..."),this.scheduleRetryWithBackoff(e,1))):(console.log("[DatabaseMetadataCache] No database URL configured, skipping initialization"),setTimeout(async()=>{console.log("[DatabaseMetadataCache] Checking for database URL after delay...");try{const e=await this.getDatabaseUrl();e&&""!==e.trim()&&(console.log("[DatabaseMetadataCache] Database URL found after delay, initializing..."),await this.waitForKernel(1e4)?await this.refreshMetadata(e):this.scheduleRetryWithBackoff(e,1))}catch(e){console.warn("[DatabaseMetadataCache] Delayed initialization check failed:",e)}},15e3))}catch(e){console.error("[DatabaseMetadataCache] Error during initialization:",e)}}scheduleRetryWithBackoff(e,t,n=5){if(t>n)return void console.warn("[DatabaseMetadataCache] Max retry attempts reached, giving up");const o=Math.min(5e3*Math.pow(2,t-1),6e4);console.log(`[DatabaseMetadataCache] Scheduling retry attempt ${t} in ${o}ms`),setTimeout(async()=>{console.log(`[DatabaseMetadataCache] Retry attempt ${t} starting...`);try{const o=await this.getDatabaseUrl(),s=o&&""!==o.trim()?o:e;if(!s||""===s.trim())return void console.log("[DatabaseMetadataCache] No database URL available for retry");if(!await this.waitForKernel(2e4))return console.log("[DatabaseMetadataCache] Kernel still not ready, scheduling next retry..."),void this.scheduleRetryWithBackoff(s,t+1,n);await this.refreshMetadata(s)?console.log("[DatabaseMetadataCache] Retry successful!"):(console.log("[DatabaseMetadataCache] Retry failed, scheduling next attempt..."),this.scheduleRetryWithBackoff(s,t+1,n))}catch(o){console.warn(`[DatabaseMetadataCache] Retry attempt ${t} failed:`,o),this.scheduleRetryWithBackoff(e,t+1,n)}},o)}getCacheStatus(){if(!this.cache)return{isCached:!1,lastUpdated:null,isExpired:!1};const e=Date.now()-this.cache.lastUpdated>=this.CACHE_DURATION_MS;return{isCached:!0,lastUpdated:this.cache.lastUpdated,isExpired:e}}async onSettingsChanged(){console.log("[DatabaseMetadataCache] Settings changed, checking database URL...");try{const e=await this.getDatabaseUrl();this.cache&&this.cache.url!==e?(console.log("[DatabaseMetadataCache] Database URL changed, clearing cache and reinitializing..."),this.clearCache(),e&&""!==e.trim()&&(await this.isKernelAvailable()?this.refreshMetadata(e).catch(e=>{console.warn("[DatabaseMetadataCache] Failed to refresh after settings change:",e)}):(console.log("[DatabaseMetadataCache] Kernel not available after settings change, scheduling retry..."),this.scheduleRetryWithBackoff(e,1)))):!this.cache&&e&&""!==e.trim()&&(console.log("[DatabaseMetadataCache] Database URL configured but no cache, initializing..."),await this.isKernelAvailable()?this.refreshMetadata(e).catch(e=>{console.warn("[DatabaseMetadataCache] Failed to initialize after settings change:",e)}):(console.log("[DatabaseMetadataCache] Kernel not available for initialization, scheduling retry..."),this.scheduleRetryWithBackoff(e,1)))}catch(e){console.error("[DatabaseMetadataCache] Error handling settings change:",e)}}async onKernelReady(){console.log("[DatabaseMetadataCache] Kernel ready event received, checking for pending initialization...");try{const e=await this.getDatabaseUrl();e&&""!==e.trim()?this.cache&&this.isCacheValid(e)?console.log("[DatabaseMetadataCache] Cache is valid, no refresh needed"):(console.log("[DatabaseMetadataCache] Attempting to refresh metadata now that kernel is ready..."),await this.refreshMetadata(e)):console.log("[DatabaseMetadataCache] No database URL configured, skipping kernel ready handler")}catch(e){console.error("[DatabaseMetadataCache] Error handling kernel ready event:",e)}}dispose(){this.stopAutoRefresh(),this.clearCache()}}function we({isVisible:e,sageTokenMode:t,tabAutocompleteEnabled:n,claudeApiKey:o,claudeModelId:s,claudeModelUrl:i,databaseUrl:a,onTokenModeChange:r,onTabAutocompleteChange:l,onClaudeApiKeyChange:c,onClaudeModelIdChange:d,onClaudeModelUrlChange:h,onDatabaseUrlChange:u,toolService:p}){const[g,m]=oe.useState(null),f=oe.useRef(null),[v,C]=oe.useState(!1),[b,y]=oe.useState(!1),[k,w]=oe.useState({isCached:!1,lastUpdated:null,isExpired:!1}),[S,_]=oe.useState(!1),x=oe.useMemo(()=>ke.getInstance(),[]);return oe.useEffect(()=>{const e=()=>{w(x.getCacheStatus())};e();const t=x.metadata$.subscribe(()=>{e()}),n=setInterval(e,1e3);return()=>{t.unsubscribe(),clearInterval(n)}},[x]),oe.useEffect(()=>{if(p&&f.current&&!g){const e=new fe(p);m(e),f.current.appendChild(e.getElement())}},[p,g]),oe.useEffect(()=>()=>{if(g&&f.current){const e=g.getElement();e.parentNode&&e.parentNode.removeChild(e)}},[g]),e?oe.createElement("div",{className:"sage-ai-settings-container"},oe.createElement("h2",{className:"sage-ai-settings-title"},"Sage Settings"),oe.createElement("div",{ref:f}),oe.createElement("div",{className:"sage-ai-config-section"},oe.createElement("h3",{className:"sage-ai-config-title"},"API Configuration"),oe.createElement("div",{className:"sage-ai-field-container"},oe.createElement("label",{className:"sage-ai-field-label"},"Sage API Key:"),oe.createElement("input",{type:v?"text":"password",value:o,onChange:e=>c(e.target.value),onFocus:()=>C(!0),onBlur:()=>C(!1),placeholder:"Enter your Sage API key",className:"sage-ai-field-input"})),oe.createElement("div",{className:"sage-ai-field-container"},oe.createElement("label",{className:"sage-ai-field-label"},"Sage Model ID:"),oe.createElement("input",{type:"text",value:s,onChange:e=>d(e.target.value),placeholder:"claude-sonnet-4-20250514",className:"sage-ai-field-input"})),oe.createElement("div",{className:"sage-ai-field-container"},oe.createElement("label",{className:"sage-ai-field-label"},"Sage Model URL:"),oe.createElement("input",{type:"text",value:i,onChange:e=>h(e.target.value),placeholder:"https://sage.alpinex.ai:8760",className:"sage-ai-field-input"}))),oe.createElement("div",{className:"sage-ai-config-section"},oe.createElement("h3",{className:"sage-ai-config-title"},"Database Configuration"),oe.createElement("div",{className:"sage-ai-field-container"},oe.createElement("label",{className:"sage-ai-field-label"},"Database URL:"),oe.createElement("div",{className:"sage-ai-database-input-container"},oe.createElement("input",{type:b?"text":"password",value:a,onChange:e=>u(e.target.value),onFocus:()=>y(!0),onBlur:()=>y(!1),placeholder:"Enter your database URL",className:"sage-ai-field-input sage-ai-database-input"}),oe.createElement("button",{onClick:async()=>{if(a&&""!==a.trim()&&!S){_(!0);try{await x.refreshMetadata(a)}catch(e){console.error("[SettingsWidget] Failed to refresh database metadata:",e)}finally{_(!1)}}},disabled:!a||""===a.trim()||S,className:"sage-ai-refresh-button",title:"Refresh database metadata cache"},S?oe.createElement("div",{className:"sage-ai-db-metadata-spinner"},oe.createElement("div",{className:"sage-ai-db-spinner-ring"}),oe.createElement("div",{className:"sage-ai-db-spinner-pulse"})):"↻")),oe.createElement("div",{className:"sage-ai-cache-status"},oe.createElement("span",{className:"sage-ai-cache-indicator "+(k.isCached?k.isExpired?"expired":"cached":"not-cached")},k.isCached?k.isExpired?"⚠️":"✓":"○"),oe.createElement("span",{className:"sage-ai-cache-text"},k.isCached?`Metadata cached (${(e=>{if(!e)return"Never";const t=Date.now()-e,n=Math.floor(t/6e4),o=Math.floor(t%6e4/1e3);return n>0?`${n}m ${o}s ago`:`${o}s ago`})(k.lastUpdated)})${k.isExpired?" - Expired":""}`:"No metadata cached")))),oe.createElement("div",{className:"sage-token-mode-container"},oe.createElement("label",{className:"sage-token-mode-label"},oe.createElement("input",{type:"checkbox",checked:t,onChange:e=>{r(e.target.checked)},className:"sage-token-mode-checkbox"}),oe.createElement("span",null,"Sage Token Debug Mode"))),oe.createElement("div",{className:"sage-tab-autocomplete-container"},oe.createElement("label",{className:"sage-tab-autocomplete-label"},oe.createElement("input",{type:"checkbox",checked:n,onChange:e=>{l(e.target.checked)},className:"sage-tab-autocomplete-checkbox"}),oe.createElement("span",null,"Enable Tab Autocomplete")))):null}ke.instance=null;class Se extends _.ReactWidget{constructor(e){super(),this._stateChanged=new se.Signal(this),this.id="sage-ai-settings",this.title.label="Settings",this.title.closable=!1,this.addClass("sage-ai-settings"),this.toolService=e,this._state={isVisible:!0,sageTokenMode:!1,tabAutocompleteEnabled:!0,claudeApiKey:"",claudeModelId:"claude-sonnet-4-20250514",claudeModelUrl:"https://sage.alpinex.ai:8760",databaseUrl:""},this.initializeSettings()}async initializeSettings(){try{await this.loadAndSyncSettings();const e=m.AppStateService.getClaudeSettings();await this.loadTokenModeSetting(),await this.loadTabAutocompleteSetting();const t=Se.SAGE_TOKEN_MODE;m.AppStateService.updateSettings({tokenMode:t}),m.AppStateService.updateClaudeSettings({tabAutocompleteEnabled:this._state.tabAutocompleteEnabled}),this._state={isVisible:!0,sageTokenMode:t,tabAutocompleteEnabled:this._state.tabAutocompleteEnabled,claudeApiKey:e.claudeApiKey,claudeModelId:e.claudeModelId,claudeModelUrl:e.claudeModelUrl,databaseUrl:e.databaseUrl},this.update()}catch(e){console.error("Failed to initialize settings:",e)}}get stateChanged(){return this._stateChanged}render(){return oe.createElement(we,{isVisible:this._state.isVisible,sageTokenMode:this._state.sageTokenMode,tabAutocompleteEnabled:this._state.tabAutocompleteEnabled,claudeApiKey:this._state.claudeApiKey,claudeModelId:this._state.claudeModelId,claudeModelUrl:this._state.claudeModelUrl,databaseUrl:this._state.databaseUrl,onTokenModeChange:this.handleTokenModeChange.bind(this),onTabAutocompleteChange:this.handleTabAutocompleteChange.bind(this),onClaudeApiKeyChange:this.handleClaudeApiKeyChange.bind(this),onClaudeModelIdChange:this.handleClaudeModelIdChange.bind(this),onClaudeModelUrlChange:this.handleClaudeModelUrlChange.bind(this),onDatabaseUrlChange:this.handleDatabaseUrlChange.bind(this),toolService:this.toolService})}async loadTokenModeSetting(){const e=await ie.getBooleanSetting(de,!1);Se.SAGE_TOKEN_MODE=e}async saveTokenModeSetting(e){await ie.setBooleanSetting(de,e)}async loadTabAutocompleteSetting(){const e=await ie.getBooleanSetting(he,!0);this._state={...this._state,tabAutocompleteEnabled:e}}async saveTabAutocompleteSetting(e){await ie.setBooleanSetting(he,e)}async loadSetting(e,t){return await ie.getStringSetting(e,t)}async saveSetting(e,t){await ie.setStringSetting(e,t)}async loadAndSyncSettings(){let e=await this.loadSetting(ue,"");if(e&&""!==e.trim())console.log("[SettingsWidget] API key already exists in settings registry, not loading from optional_env.json");else try{const t=n(3545);t.api_key&&(e=t.api_key,console.log("[SettingsWidget] Caching API key from optional_env.json to settings registry"),await this.saveSetting(ue,e))}catch(e){console.log("No optional_env.json found or error loading it:",e)}const t=await this.loadSetting(pe,"claude-sonnet-4-20250514"),o=await this.loadSetting(ge,"https://sage.alpinex.ai:8760"),s=await this.loadSetting(me,"");m.AppStateService.updateClaudeSettings({claudeApiKey:e,claudeModelId:t,claudeModelUrl:o,databaseUrl:s}),console.log("[SettingsWidget] Database URL from settings:",s),s&&""!==s.trim()?(console.log("[SettingsWidget] Setting DB_URL in kernel during settings load"),Ce.setDbUrlInKernelWithRetry(s)):console.log("[SettingsWidget] No database URL configured, skipping DB_URL setup")}async handleTokenModeChange(e){Se.SAGE_TOKEN_MODE=e,await this.saveTokenModeSetting(e),m.AppStateService.updateSettings({tokenMode:e}),this._state={...this._state,sageTokenMode:e},this._stateChanged.emit(this._state),this.update()}async handleTabAutocompleteChange(e){await this.saveTabAutocompleteSetting(e),m.AppStateService.updateClaudeSettings({tabAutocompleteEnabled:e}),this._state={...this._state,tabAutocompleteEnabled:e},this._stateChanged.emit(this._state),this.update()}async handleClaudeApiKeyChange(e){await this.saveSetting(ue,e),m.AppStateService.updateClaudeSettings({claudeApiKey:e}),this._state={...this._state,claudeApiKey:e},this._stateChanged.emit(this._state),this.update()}async handleClaudeModelIdChange(e){await this.saveSetting(pe,e),m.AppStateService.updateClaudeSettings({claudeModelId:e}),this._state={...this._state,claudeModelId:e},this._stateChanged.emit(this._state),this.update()}async handleClaudeModelUrlChange(e){await this.saveSetting(ge,e),m.AppStateService.updateClaudeSettings({claudeModelUrl:e}),this._state={...this._state,claudeModelUrl:e},this._stateChanged.emit(this._state),this.update()}async handleDatabaseUrlChange(e){await this.saveSetting(me,e),m.AppStateService.updateClaudeSettings({databaseUrl:e}),Ce.setDbUrlInKernel(e),e&&""!==e.trim()||(console.log("[SettingsWidget] Database URL cleared, clearing metadata cache"),ke.getInstance().clearCache()),this._state={...this._state,databaseUrl:e},this._stateChanged.emit(this._state),this.update()}show(){this._state={...this._state,isVisible:!0},this._stateChanged.emit(this._state),this.update()}hide(){this._state={...this._state,isVisible:!1},this._stateChanged.emit(this._state),this.update()}getState(){return{...this._state}}getIsVisible(){return this._state.isVisible}getClaudeApiKey(){return this._state.claudeApiKey}getClaudeModelId(){return this._state.claudeModelId}getClaudeModelUrl(){return this._state.claudeModelUrl}getDatabaseUrl(){return this._state.databaseUrl}getTabAutocompleteEnabled(){return this._state.tabAutocompleteEnabled}getClaudeSettings(){return{apiKey:this._state.claudeApiKey,modelId:this._state.claudeModelId,modelUrl:this._state.claudeModelUrl}}getWidget(){return this}}Se.SAGE_TOKEN_MODE=!1,Se.SAGE_TOKEN_MODE_KEY="sage-ai-token-mode",Se.CLAUDE_API_KEY_KEY="sage-ai-claude-api-key",Se.CLAUDE_MODEL_ID_KEY="sage-ai-claude-model-id",Se.CLAUDE_MODEL_URL_KEY="sage-ai-claude-model-url",Se.DATABASE_URL_KEY="sage-ai-database-url";var _e=n(7570);const xe=6e4;function Ee(e){if(!e)return 0;const t=e.trim().replace(/\s+/g," ");return Math.ceil(t.length/4)}class Me{static async initializeConversation(e,t,n=[],o="agent"){var s;console.log(`[ConversationService] Processing conversation for notebook: ${e.notebookId||"unknown"}`),e.loadingManager.updateLoadingIndicator(),null===(s=e.toolService.notebookTools)||void 0===s||s.refresh_ids();let i=t;return e.templates&&e.templates.length>0&&(i=[...e.templates.map(e=>({role:"user",content:`I'm providing the template "${e.name}" as additional context for our conversation:\n\n${e.content}`})),...t],e.templates.length=0),{preparedMessages:i,tools:"ask"===o?e.toolService.getAskModeTools():e.toolService.getTools()}}static async sendMessageWithStreaming(e,t,n,s,i,a,r){var l;const c=function(e){const t=function(e){if(!e||0===e.length)return 0;let t=0;for(const n of e){if(n.content)if("string"==typeof n.content)t+=Ee(n.content);else if(Array.isArray(n.content))for(const e of n.content)e.text?t+=Ee(e.text):e.input?t+=Ee(JSON.stringify(e.input)):e.content&&(t+=Ee(JSON.stringify(e.content)));t+=10}return t}(e),n=t>xe,o=Math.round(t/xe*100);return{exceeded:n,estimatedTokens:t,maxRecommended:xe,percentageUsed:o}}([...(null===(l=m.AppStateService.getState().chatContainer)||void 0===l?void 0:l.chatWidget.messageComponent.getMessageHistory())||[],...t]);if(c.exceeded){const t=`💡 **Conversation Length Notice**: This chat has grown quite long (approximately ${c.estimatedTokens.toLocaleString()} tokens, ${c.percentageUsed}% of the recommended limit). For optimal performance and cost efficiency, consider starting a new chat for your next topic. You can continue with this conversation if needed.`;e.messageComponent.addSystemMessage(t)}return await e.chatService.sendMessage(t,n,s,i,async(t,n)=>{if(e.chatService.getRequestStatus()===o.yR.CANCELLED)return;const s=[5,15,30][n-1]||30;e.messageComponent.addSystemMessage(`Sage encountered an error, retrying in ${s} seconds...`),e.loadingManager.updateLoadingIndicator(`Waiting to retry in ${s}s...`)},()=>e.notebookStateService.fetchNotebookState(),t=>{e.chatService.getRequestStatus()!==o.yR.CANCELLED&&(e.loadingManager.removeLoadingIndicator(),a.currentStreamingMessage||(a.currentStreamingMessage=e.messageComponent.addStreamingAIMessage()),e.messageComponent.updateStreamingMessage(a.currentStreamingMessage,t))},t=>{console.log("[ConversationService] Tool use detected:",t),e.chatService.getRequestStatus()!==o.yR.CANCELLED&&(e.loadingManager.removeLoadingIndicator(),a.currentStreamingToolCall||(a.currentStreamingToolCall=e.messageComponent.addStreamingToolCall()),Me.handleToolUseStreaming(e,t,a))},e.toolService.getContextManager(),e.notebookId,r)}static handleToolUseStreaming(e,t,n){var o;"tool_use_delta"===t.type?Me.handleToolUseDeltaWithQueue(e,t,n):"tool_use"===t.type?Me.handleToolUseStart(e,t,n):"tool_use_stop"===t.type&&((null===(o=n.operationQueue)||void 0===o?void 0:o.pendingOperation)&&(clearTimeout(n.operationQueue.pendingOperation),n.operationQueue.pendingOperation=void 0),Me.processRemainingQueue(e,n,t),Me.handleToolUseStop(e,t,n))}static handleToolUseDeltaWithQueue(e,t,n){if(!n.streamingToolCall)return;n.streamingToolCall.accumulatedInput+=t.input_delta,n.operationQueue||(n.operationQueue={});const o=n.streamingToolCall.accumulatedInput.match(/"(?:source|new_source|updated_plan_string)"\s*:\s*"((?:[^"\\]|\\.)*)/),s={type:"tool_use",id:t.id,name:n.streamingToolCall.name,input:{is_streaming:!0,updated_plan_string:void 0,new_source:void 0,source:void 0,cell_id:void 0}};if(o&&o[1]){const i=JSON.parse(`"${o[1]}"`);n.operationQueue.pendingOperation&&clearTimeout(n.operationQueue.pendingOperation);const a=n.streamingToolCall.accumulatedInput;if(n.operationQueue.lastProcessedInput===a)return;n.operationQueue.pendingOperation=setTimeout(()=>{try{Me.handleRealTimeNotebookUpdates(e,n.streamingToolCall,i,s,t),e.messageComponent.updateStreamingToolCall(n.currentStreamingToolCall,s),n.operationQueue.lastProcessedInput=a}catch(e){console.error("Error in queued notebook operation:",e)}n.operationQueue.pendingOperation=void 0},100)}}static processRemainingQueue(e,t,n){if(!t.streamingToolCall||!t.operationQueue)return;const o=t.streamingToolCall.accumulatedInput.match(/"(?:source|new_source|updated_plan_string)"\s*:\s*"((?:[^"\\]|\\.)*)/);if(o&&o[1]){const s=JSON.parse(`"${o[1]}"`),i=t.streamingToolCall.accumulatedInput;if(t.operationQueue.lastProcessedInput!==i){const o={type:"tool_use",id:n.id,name:t.streamingToolCall.name,input:{is_streaming:!1,updated_plan_string:void 0,new_source:void 0,source:void 0,cell_id:void 0}};try{Me.handleRealTimeNotebookUpdates(e,t.streamingToolCall,s,o,n),e.messageComponent.updateStreamingToolCall(t.currentStreamingToolCall,o),t.operationQueue.lastProcessedInput=i}catch(e){console.error("Error in final queue processing:",e)}}}t.operationQueue={}}static handleToolUseStart(e,t,n){var o;n.streamingToolCall={id:t.id,name:t.name,accumulatedInput:""};const s=null===(o=m.AppStateService.getChatContainerSafe())||void 0===o?void 0:o.chatWidget.llmStateDisplay;s&&!s.isDiffState()&&s.showTool(t.name),e.messageComponent.updateStreamingToolCall(n.currentStreamingToolCall,t)}static handleToolUseStop(e,t,n){var o,s,i,a;e.messageComponent.updateStreamingToolCall(n.currentStreamingToolCall,t),"notebook-edit_cell"===t.name&&(null===(o=e.toolService.notebookTools)||void 0===o||o.edit_cell({cell_id:t.input.cell_id,new_source:t.input.new_source||"",summary:t.input.summary||"",is_tracking_id:!0,notebook_path:e.notebookId}),null===(s=e.diffManager)||void 0===s||s.trackEditCell(t.input.cell_id,n.streamingToolCall.originalContent||"",t.input.new_source,t.input.summary,e.notebookId)),"notebook-add_cell"===t.name&&(null===(i=e.toolService.notebookTools)||void 0===i||i.edit_cell({cell_id:n.streamingToolCall.cellId,new_source:t.input.source||"",summary:t.input.summary||"",is_tracking_id:!0,notebook_path:e.notebookId}),null===(a=e.diffManager)||void 0===a||a.trackAddCell(n.streamingToolCall.cellId,t.input.source,t.input.summary,e.notebookId)),"notebook-edit_plan"===t.name&&console.log("edit_plan tool completed via ToolService")}static handleRealTimeNotebookUpdates(e,t,n,o,s){var i;const a="notebook-add_cell"===t.name,r="notebook-edit_cell"===t.name;"notebook-edit_plan"===t.name&&(null===(i=e.toolService.notebookTools)||void 0===i||i.stream_edit_plan({partial_plan:n,notebook_path:e.notebookId}),o.input.updated_plan_string=n),a&&Me.handleAddCellStreaming(e,t,n,o,s),r&&Me.handleEditCellStreaming(e,t,n,o,s)}static handleAddCellStreaming(e,t,n,o,s){var i,a;console.log("BEGIN HANDLE ADD CELL"),console.log(t);try{const e=(0,_e.parse)(t.accumulatedInput);e.position&&(t.position=e.position)}catch(e){throw console.error("Invalid JSON in accumulated input:",e),new Error("Failed to parse accumulated input JSON")}const r=t.accumulatedInput.match(/"cell_type"\s*:\s*"([^"]*)"/),l=r?r[1]:null,c=t.accumulatedInput.match(/"summary"\s*:\s*"([^"]*)"/),d=c?c[1]:"Cell being created by AI...";if(l&&["code","markdown"].includes(l))if(t.cellId)try{null===(a=e.toolService.notebookTools)||void 0===a||a.edit_cell({cell_id:t.cellId,summary:d,new_source:n,is_tracking_id:!0,notebook_path:e.notebookId})}catch(e){throw console.error("Error editing existing cell during streaming:",e),new Error("Failed to edit existing cell")}else try{const a=null===(i=e.toolService.notebookTools)||void 0===i?void 0:i.add_cell({cell_type:l,summary:d,source:n,notebook_path:e.notebookId,position:t.position});if(!a)throw new Error("Failed to create new cell, no ID returned");o.input.source=n,o.input.cell_id=t.cellId,t.cellId=a,t.toolResult={type:"tool_result",tool_use_id:s.id,content:a||""},console.log(`New cell created with ID: ${a}`)}catch(e){throw console.error("Error creating new cell during streaming:",e),new Error("Failed to create new cell")}}static handleEditCellStreaming(e,t,n,o,s){var i,a,r,l;if(console.log(t),!t.cellId){const n=/"cell_id"\s*:\s*"([^"]*)"/,o=t.accumulatedInput.match(n);if(o&&o[1]&&(t.cellId=o[1],e.diffManager&&!t.originalContent))try{const n=null===(i=e.toolService.notebookTools)||void 0===i?void 0:i.findCellByAnyId(t.cellId,e.notebookId);n&&(t.originalContent=n.cell.model.sharedModel.getSource()||"",t.originalSummary=(null===(r=null===(a=n.cell.model.sharedModel.metadata)||void 0===a?void 0:a.custom)||void 0===r?void 0:r.summary)||"")}catch(e){console.warn("Could not get original content for diff:",e)}}if(t.cellId){let i=n;t.originalContent&&(i=n.length<t.originalContent.length?n+t.originalContent.substring(n.length):n);const a=null===(l=e.toolService.notebookTools)||void 0===l?void 0:l.edit_cell({cell_id:t.cellId,new_source:i,summary:t.summary||"Cell being updated by AI...",is_tracking_id:t.cellId.startsWith("cell_"),notebook_path:e.notebookId});t.toolResult={type:"tool_result",tool_use_id:s.id,content:a?"true":"false"},o.input.new_source=n,o.input.cell_id=t.cellId}}static async finalizeStreamingElements(e,t,n){var o;if((null==t?void 0:t.cancelled)||e.chatService.isRequestCancelled())return console.log("Response processing skipped due to cancellation"),Me.cleanupStreamingElements(e,n),void e.loadingManager.removeLoadingIndicator();if(!0===t.needsFreshContext)return void e.loadingManager.removeLoadingIndicator();n.currentStreamingMessage&&await e.messageComponent.finalizeStreamingMessage(n.currentStreamingMessage);const s=null===(o=m.AppStateService.getChatContainerSafe())||void 0===o?void 0:o.chatWidget.llmStateDisplay;if(n.currentStreamingToolCall?(e.messageComponent.finalizeStreamingToolCall(n.currentStreamingToolCall),s&&!s.isDiffState()&&(s.show("Generating..."),s.hide())):null==s||s.hide(),!(null==s?void 0:s.isDiffState())){const e=m.AppStateService.getDiffNavigationWidgetSafe();e&&e.hidePendingDiffs()}}static addUsageInformation(e,t){if(!Se.SAGE_TOKEN_MODE)return;console.log("Sage Token Mode is enabled, adding usage message"),console.log("Response usage:",t);let n=0,o=0,s=0,i=0;for(const t of e.messageComponent.getMessageHistory())"string"==typeof t.content?"assistant"===t.role?o+=1:n+=1:"assistant"===t.role?s+=1:i+=1;const a=t.usage.input_tokens||0,r=a>6e4;let l=`cache_input_tokens: ${t.usage.cache_creation_input_tokens}, cache_read_tokens: ${t.usage.cache_read_input_tokens} \n\n input_tokens: ${t.usage.input_tokens}, output_tokens: ${t.usage.output_tokens} \n\n user_messages: ${n}, assistant_responses: ${o} \n\n tool_calls: ${s}, tool_results: ${i} \n`;if(r){const e=Math.round(a/6e4*100);l+=`\n⚠️ **Chat Length Warning**: This conversation has reached ${a.toLocaleString()} tokens (${e}% of recommended limit). For optimal performance and to avoid potential issues, it is recommended to start a new chat session.\n`}e.messageComponent.addSystemMessage(l)}static async processToolCalls(e,t,n,o,s){let i=!1;if(!t.content||0===t.content.length)return{hasToolCalls:i,shouldContinue:!0};for(const a of t.content){if(e.chatService.isRequestCancelled())return console.log("Request was cancelled, stopping tool processing"),e.loadingManager.removeLoadingIndicator(),{hasToolCalls:i,shouldContinue:!1};if("tool_use"===a.type){if(i=!0,e.isActiveToolExecution=!0,!await Me.processSingleToolCall(e,a,n,o,s))return{hasToolCalls:i,shouldContinue:!1};n.streamingToolCall=void 0}}return{hasToolCalls:i,shouldContinue:!0}}static async processSingleToolCall(e,t,n,s,i){var a,r;const l=t.name,c=t.input;console.log(`AI wants to use tool: ${l}`);const d=await Me.captureActionState(e,l,c,n);if(("notebook-run_cell"===l||"notebook-execute_cell"===l)&&!await Me.handleCodeExecution(e,t,i))return!1;const h=null===(a=m.AppStateService.getChatContainerSafe())||void 0===a?void 0:a.chatWidget.llmStateDisplay;h&&!h.isDiffState()&&h.showTool(l);let u=null;if(n.streamingToolCall&&n.streamingToolCall.toolResult)u=n.streamingToolCall.toolResult;else{if(await Me.checkExecutedCells(e,t.id,null===(r=t.input)||void 0===r?void 0:r.cell_id,!0)&&"notebook-run_cell"===l)return console.log("Skipping tool call in chat"),!0;u=await Me.processToolCall(e,{id:t.id,name:l,input:c})}return e.isActiveToolExecution=!1,h&&!h.isDiffState()&&h.show("Generating..."),Me.trackActionForUndo(e,l,c,u,d),e.chatService.getRequestStatus()===o.yR.CANCELLED?(console.log("Request was cancelled, skipping tool result display"),!1):(e.messageComponent.addToolResult(l,t.id,u.content,null==t?void 0:t.input),e.chatService.getRequestStatus()!==o.yR.CANCELLED&&(e.chatService.getRequestStatus()===o.yR.CANCELLED?(console.log("Request was cancelled, skipping further processing"),!1):"notebook-wait_user_reply"!==l?(null==h||h.hidePendingDiffs(),null==h||h.show("Generating..."),!0):(null==h||h.show("Waiting for your reply...",!0),!1)))}static async captureActionState(e,t,n,o){var s,i;if("notebook-edit_cell"===t)try{const t=await e.toolService.executeTool({id:"get_cell_before_edit",name:"notebook-get_cell_info",input:{cell_id:n.cell_id}});if(t&&t.content)return{originalCell:JSON.parse(t.content),originalContent:(null===(s=o.streamingToolCall)||void 0===s?void 0:s.originalContent)||"",originalSummary:(null===(i=o.streamingToolCall)||void 0===i?void 0:i.originalSummary)||"",newSource:n.new_source,cellId:n.cell_id,cell_id:n.cell_id,summary:n.summary}}catch(e){console.error("Failed to get cell info before edit:",e)}else if("notebook-remove_cells"===t)try{const t=(n.cell_ids||[]).map(t=>e.toolService.executeTool({id:`get_cell_before_remove_${t}`,name:"notebook-get_cell_info",input:{cell_id:t}})),o=(await Promise.all(t)).map(e=>e&&e.content?JSON.parse(e.content):null).filter(e=>null!==e);if(o.length>0)return{removedCells:o}}catch(e){console.error("Failed to get cell info before removal:",e)}return null}static async handleCodeExecution(e,t,n){var o,s,i,a,r,l,c;if(e.loadingManager.removeLoadingIndicator(),await Me.checkPendingDiffsBeforeCodeExecution(e),null===(o=e.diffManager)||void 0===o?void 0:o.hasRejectedDiffs())return e.messageComponent.addSystemMessage("❌ Changes were rejected. Code execution has been cancelled."),(null===(s=t.input)||void 0===s?void 0:s.cell_id)&&e.messageComponent.addToolResult("notebook-run_cell",t.id,"User rejected changes, cell was not added or executed.",{cell_id:null===(i=t.input)||void 0===i?void 0:i.cell_id,notebook_path:e.notebookId}),v.getInstance().clearAllDiffs(),!1;if(Me.checkForApprovalDecisions(e,null===(a=t.input)||void 0===a?void 0:a.cell_id)){console.log("[ConversationService] User made approval decisions - stopping LLM loop");const n=null===(r=t.input)||void 0===r?void 0:r.cell_id;console.log(`REQUESTED CELL ${n} WAS NOT EXECUTED DURING DIFF APPROVAL`);const o={type:"tool_result",tool_use_id:t.id,content:"user accepted changes but did not run the cell."};return e.messageComponent.addToolResult("notebook-run_cell",t.id,o.content,{cell_id:n,notebook_path:e.notebookId}),!1}const d=await Me.checkExecutedCells(e,t.id,null===(l=t.input)||void 0===l?void 0:l.cell_id);if(console.log("[ConversationService] Executed approved cells:",d),d)return!0;if(e.diffManager&&t.input.cell_id){const n=e.diffManager.getCurrentCellId(t.input.cell_id);n!==t.input.cell_id&&(console.log(`Updating cell ID for execution: ${t.input.cell_id} → ${n}`),t.input.cell_id=n)}let h=!1;if(e.autoRun)h=!0,e.messageComponent.addSystemMessage("Automatically running code (auto-run is enabled).");else if(e.diffManager&&e.diffManager.shouldRunImmediately())h=!0,e.messageComponent.addSystemMessage("Running code immediately after approving changes.");else{const n=null===(c=m.AppStateService.getChatContainerSafe())||void 0===c?void 0:c.chatWidget.llmStateDisplay;n&&n.showRunCellTool(()=>e.codeConfirmationDialog.triggerApproval(),()=>e.codeConfirmationDialog.triggerRejection()),h=await e.codeConfirmationDialog.showConfirmation(t.input.cell_id||t.input.cellId||""),h?null==n||n.show():(null==n||n.hide(),e.messageComponent.removeLoadingText())}return!!h&&(e.loadingManager.updateLoadingIndicator(),!0)}static async processToolCall(e,t){const n={...t,input:{...t.input,notebook_path:e.notebookId}};return await e.toolService.executeTool(n,3,!0)}static trackActionForUndo(e,t,n,o,s){var i;if("notebook-remove_cells"===t&&s&&e.diffManager&&s.removedCells)for(const t of s.removedCells)t&&(t.id||t.trackingId)&&e.diffManager.trackRemoveCell(t.trackingId||t.id,t.content||"",(null===(i=t.custom)||void 0===i?void 0:i.summary)||"Removed by AI",e.notebookId)}static async handlePendingDiffsAfterToolCalls(e){var t;if(e.diffManager&&e.diffManager.hasPendingDiffs()){e.isActiveToolExecution=!0;const n=null===(t=m.AppStateService.getChatContainerSafe())||void 0===t?void 0:t.chatWidget.llmStateDisplay;n&&n.showPendingDiffs(e.notebookId);const o=m.AppStateService.getDiffNavigationWidgetSafe();o&&o.showPendingDiffs(e.notebookId),await Me.checkPendingDiffs(e),e.isActiveToolExecution=!1}return!0}static async checkPendingDiffs(e){var t;if(!e.diffManager||!e.diffManager.hasPendingDiffs())return!0;if(e.autoRun){e.messageComponent.addSystemMessage(`Auto-approving ${e.diffManager.getPendingDiffCount()} changes (auto-run is enabled).`);for(const e of v.getInstance().getCurrentState().pendingDiffs.values()){console.log("RUNNING DIFF IN AUTO APPROVE MODE:",e.cellId);try{await(null===(t=m.AppStateService.getState().notebookDiffManager)||void 0===t?void 0:t.diffApprovalDialog.runCell(e.cellId))}catch(t){console.error("Error running cell in auto-approve mode:",e.cellId,t)}}return!0}return e.diffManager.startDiffApprovalProcess(e.chatHistory,!0,!1,m.AppStateService.getState().currentNotebookId||void 0),await e.diffManager.waitForDiffProcessingComplete()!==o.fY.REJECTED}static async checkPendingDiffsBeforeCodeExecution(e){var t;if(!e.diffManager||!e.diffManager.hasPendingDiffs())return!0;if(e.autoRun){e.messageComponent.addSystemMessage(`Auto-approving ${e.diffManager.getPendingDiffCount()} changes (auto-run is enabled).`);for(const e of v.getInstance().getCurrentState().pendingDiffs.values()){console.log("RUNNING DIFF IN AUTO APPROVE MODE:",e.cellId);try{await(null===(t=m.AppStateService.getState().notebookDiffManager)||void 0===t?void 0:t.diffApprovalDialog.runCell(e.cellId))}catch(t){console.error("Error running cell in auto-approve mode:",e.cellId,t)}}return!0}return e.diffManager.startDiffApprovalProcess(e.chatHistory,!0,!0,m.AppStateService.getState().currentNotebookId||void 0),await e.diffManager.waitForDiffProcessingComplete()!==o.fY.REJECTED}static async checkExecutedCells(e,t,n,o){if(console.log("CHECKING EXECUTED CELLS!"),!e.diffManager)return!1;const s=e.diffManager.getApprovedCellIds(e.notebookId);if(0===s.length)return!1;const i=v.getInstance().getCurrentState();console.log("Current diff state:",i.pendingDiffs);const a=[];let r=!1;for(const e of s){const t=i.pendingDiffs.get(e);t&&"run"===t.userDecision&&t.runResult&&(console.log("CELL WAS ALREADY EXECUTED:",e,t.runResult),a.push({cellId:e,result:t.runResult}),n&&e===n&&(r=!0))}if(n&&!r)return console.log(`REQUESTED CELL ${n} WAS NOT EXECUTED DURING DIFF APPROVAL`),!1;if(0===a.length){console.log("NO CELLS WERE EXECUTED DURING DIFF APPROVAL");const o={type:"tool_result",tool_use_id:t,content:"User approved changes but did not run the cell at this time."};return e.messageComponent.addToolResult("notebook-run_cell",t,o.content,{cell_id:n,notebook_path:e.notebookId}),!1}const l=n&&r?a.filter(e=>e.cellId===n):a;o&&e.messageComponent.addSystemMessage(n&&r?`Cell ${n} was executed during diff approval.`:`${l.length} cells were executed during diff approval.`);for(const{cellId:o,result:s}of l){if(o!==n)continue;let i=s;if(Array.isArray(s))for(const e of s)i+="string"==typeof e?e:JSON.stringify(e);const a={type:"tool_result",tool_use_id:t,content:i};e.messageComponent.addToolResult("notebook-run_cell",t,a.content,{cell_id:o,notebook_path:e.notebookId})}return console.log("SKIPPING ORIGINAL TOOL EXECUTION - CELLS ALREADY RAN"),!0}static checkForApprovalDecisions(e,t){if(!e.diffManager)return!1;const n=v.getInstance().getCurrentState();for(const[e,o]of n.pendingDiffs)if(e===t&&"approved"===o.userDecision)return!0;return!1}static cleanupStreamingElements(e,t){var n;(null===(n=t.operationQueue)||void 0===n?void 0:n.pendingOperation)&&(clearTimeout(t.operationQueue.pendingOperation),t.operationQueue.pendingOperation=void 0),t.currentStreamingMessage&&e.messageComponent.removeElement(t.currentStreamingMessage),t.currentStreamingToolCall&&e.messageComponent.removeElement(t.currentStreamingToolCall)}}class Ie{constructor(e,t,n,o,s,i,a,r){this.diffManager=null,this.isActiveToolExecution=!1,this.autoRun=!1,this.notebookId=null,this.streamingElement=null,this.templates=[],this.chatService=e,this.toolService=t,this.messageComponent=o,this.chatHistory=s,this.loadingManager=a,this.diffManager=r||null,this.actionHistory=i,this.contentManager=n,this.notebookStateService=new Q(t),this.codeConfirmationDialog=new ee(s,o),this.syncChatServiceHistory()}updateNotebookId(e){this.notebookId=e,this.notebookStateService.updateNotebookId(e)}syncChatServiceHistory(){const e=this.messageComponent.getMessageHistory();e.length>0&&this.messageComponent.scrollToBottom(),console.log(`Synchronized ${e.length} messages to chat service history`)}setAutoRun(e){this.autoRun=e,console.log("Auto-run mode "+(e?"enabled":"disabled"))}setDiffManager(e){this.diffManager=e,console.log("NotebookDiffManager set in ConversationService")}setNotebookId(e){this.notebookId=e,console.log(`[ConversationService] Set notebook ID: ${e}`)}async handleCellRejection(e="agent"){this.messageComponent.addSystemMessage("Cell execution rejected. Asking for corrections based on user feedback...");const t=new te,n=await t.showDialog(),o={role:"user",content:`I rejected the previous cell execution because: ${n}`};this.messageComponent.addUserMessage(`I rejected the previous cell execution because: ${n}`),await this.processConversation([o],[],e)}async processToolCall(e){return await Me.processToolCall({chatService:this.chatService,toolService:this.toolService,messageComponent:this.messageComponent,notebookStateService:this.notebookStateService,codeConfirmationDialog:this.codeConfirmationDialog,loadingManager:this.loadingManager,diffManager:this.diffManager,actionHistory:this.actionHistory,autoRun:this.autoRun,notebookId:this.notebookId,templates:this.templates,isActiveToolExecution:this.isActiveToolExecution,chatHistory:this.chatHistory},e)}async executeAllApprovedCells(e){return await Me.checkExecutedCells({chatService:this.chatService,toolService:this.toolService,messageComponent:this.messageComponent,notebookStateService:this.notebookStateService,codeConfirmationDialog:this.codeConfirmationDialog,loadingManager:this.loadingManager,diffManager:this.diffManager,actionHistory:this.actionHistory,autoRun:this.autoRun,notebookId:this.notebookId,templates:this.templates,isActiveToolExecution:this.isActiveToolExecution,chatHistory:this.chatHistory},e)}async createErrorMessage(e){console.log("Creating error message dump..."),console.log(e);try{let t=await q.K.getValue(q.s.ERROR_LOGS,"")+`\n\n---\n\n${(new Date).toISOString()}\n\n${JSON.stringify(e)}`;const n=t.split(/\s+/);n.length>1e5&&(t=n.slice(-9e4).join(" "),t="[...logs trimmed to maintain 100,000 word limit...]\n\n"+t),await q.K.setValue(q.s.ERROR_LOGS,t)}catch(e){console.error("Failed to save error log to stateDB:",e)}}async processConversation(e,t=[],n="agent"){var s;const i={chatService:this.chatService,toolService:this.toolService,messageComponent:this.messageComponent,notebookStateService:this.notebookStateService,codeConfirmationDialog:this.codeConfirmationDialog,loadingManager:this.loadingManager,diffManager:this.diffManager,actionHistory:this.actionHistory,autoRun:this.autoRun,notebookId:this.notebookId,templates:this.templates,isActiveToolExecution:this.isActiveToolExecution,chatHistory:this.chatHistory},a={currentStreamingMessage:null,currentStreamingToolCall:null,streamingToolCall:void 0,operationQueue:{}};try{const{preparedMessages:r,tools:l}=await Me.initializeConversation(i,e,t,n),c=await Me.sendMessageWithStreaming(i,r,l,n,t,a,this.createErrorMessage.bind(this));if((null==c?void 0:c.cancelled)||this.chatService.isRequestCancelled())return console.log("Response processing skipped due to cancellation"),Me.cleanupStreamingElements(i,a),void this.loadingManager.removeLoadingIndicator();if(!0===c.needsFreshContext)return this.loadingManager.removeLoadingIndicator(),void await this.handleCellRejection(n);if(await Me.finalizeStreamingElements(i,c,a),this.chatService.getRequestStatus()===o.yR.CANCELLED)return console.log("Request was cancelled, skipping tool call processing"),void this.loadingManager.removeLoadingIndicator();Me.addUsageInformation(i,c);const{hasToolCalls:d,shouldContinue:h}=await Me.processToolCalls(i,c,a,t,n);if(!h)return;if(d){if(Me.checkForApprovalDecisions(i))return void console.log("[ConversationService] Approval decisions detected - stopping recursive LLM loop");let e=!1;for(const t of c.content||[])if("tool_use"===t.type&&"notebook-wait_user_reply"!==t.name){"notebook-run_cell"===t.name&&v.getInstance().clearAllDiffs(this.notebookId),e=!0;break}if(e){const e=null===(s=m.AppStateService.getChatContainerSafe())||void 0===s?void 0:s.chatWidget.llmStateDisplay;null==e||e.hidePendingDiffs(),null==e||e.show("Generating..."),await this.processConversation([],t,n)}}await Me.handlePendingDiffsAfterToolCalls(i),this.isActiveToolExecution=i.isActiveToolExecution}catch(e){if(this.chatService.isRequestCancelled())return console.log("Request was cancelled, skipping error handling"),Me.cleanupStreamingElements(i,a),void this.loadingManager.removeLoadingIndicator();throw this.loadingManager.removeLoadingIndicator(),e}this.loadingManager.removeLoadingIndicator()}canUndo(){return this.actionHistory.canUndo()}getLastActionDescription(){return this.actionHistory.getLastActionDescription()}async startCheckpointRestoration(e){var t,n;console.log("[ConversationService] Restoring to checkpoint:",e.id);try{if(!this.notebookId)throw"No notebook ID available for restoration";this.loadingManager.updateLoadingIndicator("Restoring checkpoint..."),await this.undoActions(e),await K.cacheNotebookState(this.notebookId,e.notebookState);let o=null===(t=this.chatHistory.querySelector(`[data-checkpoint-id="${e.id}"]`))||void 0===t?void 0:t.nextSibling;for(;o;){const e=o.nextSibling;o instanceof HTMLElement&&o.classList.add("chat-history-item-opaque"),o=e}this.loadingManager.hideLoadingIndicator(),null===(n=m.AppStateService.getLlmStateDisplay())||void 0===n||n.showRunKernelButton(),console.log("[ConversationService] Checkpoint restoration completed")}catch(e){console.error("[ConversationService] Error during checkpoint restoration:",e),this.loadingManager.hideLoadingIndicator(),this.messageComponent.addErrorMessage("Failed to restore checkpoint. Please try again.")}}async finishCheckpointRestoration(e){console.log("[ConversationService] Finishing checkpoint restoration"),this.messageComponent.restoreToCheckpoint(e)}async undoActions(e){console.log("[ConversationService] Undoing all actions from checkpoint chain");const t=G.getInstance().getCheckpoints(),n=(e,o=[])=>{if(e.nextCheckpointId){const s=t.find(t=>t.id===e.nextCheckpointId);s&&n(s,o)}return o.push(e),o},o=n(e,[]),s=[];for(const e of o)e.actionHistory&&e.actionHistory.length>0&&s.push(...e.actionHistory);console.log("[ConversationService] Total actions to undo from all checkpoints:",s.length);for(let e=0;e<s.length;e++){const t=s[e];console.log("[ConversationService] Undoing action:",t.description);try{switch(t.type){case"add_cell":await this.undoAddCell(t);break;case"edit_cell":await this.undoEditCell(t);break;case"remove_cells":await this.undoRemoveCells(t);break;case"edit_plan":await this.undoEditPlan(t)}}catch(e){console.warn("[ConversationService] Error undoing action:",t.description,e)}}console.log("[ConversationService] All checkpoint actions undone")}async redoActions(e){console.log("[ConversationService] Redoing all actions from checkpoint chain");const t=G.getInstance().getCheckpoints(),n=(e,o=[])=>{if(e.nextCheckpointId){const s=t.find(t=>t.id===e.nextCheckpointId);s&&n(s,o)}return o.push(e),o},o=n(e,[]),s=[];for(const e of o)e.actionHistory&&e.actionHistory.length>0&&s.push(...e.actionHistory.slice().reverse());console.log("[ConversationService] Total actions to redo from all checkpoints:",s.length);for(let e=s.length-1;e>=0;e--){const t=s[e];console.log("[ConversationService] Redoing action:",t.description);try{switch(t.type){case"add_cell":await this.redoAddCell(t);break;case"edit_cell":await this.redoEditCell(t);break;case"remove_cells":await this.redoRemoveCells(t);break;case"edit_plan":await this.redoEditPlan(t)}}catch(e){console.warn("[ConversationService] Error redoing action:",t.description,e)}}console.log("[ConversationService] All checkpoint actions redone")}async redoAddCell(e){const t=e.data.trackingId||e.data.cellId;await this.toolService.executeTool({id:"redo_add_cell",name:"notebook-add_cell",input:{cell_type:e.data.originalCellType,source:e.data.newContent||e.data.source||"",summary:e.data.summary||"Redone by checkpoint restoration",tracking_id:t,run_cell:"markdown"===e.data.originalCellType}})}async redoEditCell(e){const t=e.data.trackingId||e.data.cellId;await this.toolService.executeTool({id:"redo_edit_cell",name:"notebook-edit_cell",input:{cell_id:t,new_source:e.data.newContent,summary:e.data.summary||"Redone by checkpoint restoration",is_tracking_id:!0}})}async redoRemoveCells(e){const t=e.data.cellId;t&&await this.toolService.executeTool({id:"redo_remove_cells",name:"notebook-remove_cells",input:{cell_ids:[t],remove_from_notebook:!0}})}async redoEditPlan(e){var t,n;const o=e.data.newContent||"",s=null===(t=this.toolService.notebookTools)||void 0===t?void 0:t.getCurrentNotebook(this.notebookId);if(!s)return void console.error("No notebook found for redo edit_plan");const{notebook:i}=s,a=i.widgets[0];if(!a)return;a.model.sharedModel.setSource(o);const r=a.model.sharedModel.getMetadata()||{};r.custom||(r.custom={}),r.custom.current_step_string="",r.custom.next_step_string="",r.custom.sage_cell_type="plan",r.cell_tracker.trackingId="planning_cell",a.model.sharedModel.setMetadata(r),X.NotebookActions.changeCellType(i,"markdown"),await X.NotebookActions.runCells(i,[i.widgets[0]],null===(n=s.widget)||void 0===n?void 0:n.sessionContext),await m.AppStateService.getPlanStateDisplay().updatePlan("","",o,!1)}async runAllCellsAfterRestore(){console.log("[ConversationService] Running all cells after checkpoint restoration");try{if(this.loadingManager.updateLoadingIndicator("Running all cells..."),this.notebookId&&this.toolService.notebookTools){const e=this.toolService.notebookTools.read_cells({notebook_path:this.notebookId,include_outputs:!1,include_metadata:!0});if(e&&e.cells){const t=e.cells.filter(e=>"code"===e.type);for(const e of t)try{await this.toolService.notebookTools.run_cell({cell_id:e.trackingId||e.id,notebook_path:this.notebookId})}catch(t){console.warn("[ConversationService] Error running cell:",e.id,t)}}}this.loadingManager.hideLoadingIndicator(),console.log("[ConversationService] All cells execution completed")}catch(e){console.error("[ConversationService] Error running all cells:",e),this.loadingManager.hideLoadingIndicator(),this.messageComponent.addErrorMessage("Failed to run all cells. Please run them manually.")}}async undoLastAction(){const e=this.actionHistory.popLastAction();if(!e)return!1;try{switch(this.loadingManager.updateLoadingIndicator("Undoing action..."),e.type){case Z.ADD_CELL:await this.undoAddCell(e);break;case Z.EDIT_CELL:await this.undoEditCell(e);break;case Z.REMOVE_CELLS:await this.undoRemoveCells(e);break;case Z.EDIT_PLAN:await this.undoEditPlan(e)}return this.messageComponent.addSystemMessage(`✓ Undid action: ${e.description}`),this.loadingManager.removeLoadingIndicator(),!0}catch(e){return console.error("Error undoing action:",e),this.messageComponent.addErrorMessage(`Failed to undo action: ${e instanceof Error?e.message:"Unknown error"}`),this.loadingManager.removeLoadingIndicator(),!1}}async undoAddCell(e){const t=e.data.trackingId||e.data.cellId;await this.toolService.executeTool({id:"undo_add_cell",name:"notebook-remove_cells",input:{cell_ids:[t],remove_from_notebook:!0}})}async undoEditPlan(e){var t;const n=e.data.oldPlan||"",o=e.data.planExisted||!1,s=null===(t=this.toolService.notebookTools)||void 0===t?void 0:t.getCurrentNotebook(this.notebookId);if(!s)return void console.error("No notebook found for edit_plan");const{notebook:i}=s,a=i.widgets[0];if(a)if(o){a.model.sharedModel.setSource(n);const t=a.model.sharedModel.getMetadata()||{};t.custom||(t.custom={}),t.custom.current_step_string=e.data.oldCurrentStep,t.custom.next_step_string=e.data.oldNextStep,a.model.sharedModel.setMetadata(t),m.AppStateService.getPlanStateDisplay().updatePlan(e.data.oldCurrentStep||"",e.data.oldNextStep,n,!1)}else this.toolService.notebookTools.activateCell(a),X.NotebookActions.deleteCells(i)}async undoEditCell(e){const t=e.data.trackingId||e.data.cellId;await this.toolService.executeTool({id:"undo_edit_cell",name:"notebook-edit_cell",input:{cell_id:t,new_source:e.data.originalContent,summary:e.data.originalSummary||"Restored by undo",is_tracking_id:!0}})}async undoRemoveCells(e){var t,n;const o=e.data.cellId;if(o){const s=e.data.metadata;await this.toolService.executeTool({id:"undo_remove_cell",name:"notebook-add_cell",input:{cell_type:"code",source:e.data.oldContent,summary:(null===(t=s.custom)||void 0===t?void 0:t.summary)||"Restored by undo",position:null===(n=s.custom)||void 0===n?void 0:n.index,tracking_id:o}})}}clearActionHistory(){this.actionHistory.clear()}}var Ne=n(5256),De=n(8533),Te=n(435),Ae=n(4744);class Le{constructor(){this.notebookChats=new Map,this.currentNotebookId=null,this.currentThreadId=null,this.STORAGE_KEY_PREFIX="sage-ai-chat-history-",this.notebookChatboxes=new Map,this.loadFromStorage(),m.AppStateService.onNotebookChanged().subscribe(({oldNotebookId:e,newNotebookId:t})=>{t&&this.setCurrentNotebook(t)})}getCurrentThreadId(){return this.currentThreadId}updateNotebookId(e,t){this.currentNotebookId=t;const n=this.notebookChats.get(e)||[];this.notebookChats.set(t,n),this.notebookChats.delete(e);const o=this.notebookChatboxes.get(e);o&&(this.notebookChatboxes.set(t,o),this.notebookChatboxes.delete(e)),this.saveToStorage()}setCurrentNotebook(e){var t;if(this.currentNotebookId&&this.currentNotebookId!==e&&this.hideChatbox(this.currentNotebookId),this.currentNotebookId&&this.getCurrentThread()){const e=this.getCurrentThread();null===(t=m.AppStateService.getState().chatContainer)||void 0===t||t.chatWidget.threadManager.storeLastThreadForNotebook(this.currentNotebookId,null==e?void 0:e.id)}if(console.log(`[ChatHistoryManager] Setting current notebook: ${e}`),this.currentNotebookId=e,!this.notebookChats.has(e)){const t={id:this.generateThreadId(),name:"New Chat",messages:[],lastUpdated:Date.now(),contexts:new Map,message_timestamps:new Map};this.notebookChats.set(e,[t]),this.saveToStorage()}const n=this.notebookChats.get(e),o=[...n].sort((e,t)=>t.lastUpdated-e.lastUpdated).find(e=>"New Chat"===e.name);return this.currentThreadId=o?o.id:n[0].id,this.showChatbox(e),this.getCurrentThread()}showChatbox(e){const t=this.notebookChatboxes.get(e);if(t&&t.chatbox){t.isVisible=!0;const e=t.chatbox.node;e&&(e.style.display="",e.classList.remove("hidden-chatbox"))}this.notebookChatboxes.forEach((t,n)=>{if(n!==e&&t.chatbox){t.isVisible=!1;const e=t.chatbox.node;e&&(e.style.display="none",e.classList.add("hidden-chatbox"))}})}hideChatbox(e){const t=this.notebookChatboxes.get(e);if(t&&t.chatbox){t.isVisible=!1;const e=t.chatbox.node;e&&(e.style.display="none",e.classList.add("hidden-chatbox"))}}getCurrentThread(){if(!this.currentNotebookId||!this.currentThreadId)return null;const e=this.notebookChats.get(this.currentNotebookId);return e&&e.find(e=>e.id===this.currentThreadId)||null}getCurrentNotebookThreads(){return this.currentNotebookId&&this.notebookChats.get(this.currentNotebookId)||[]}getThreadsForNotebook(e){return e&&this.notebookChats.has(e)?this.notebookChats.get(e)||[]:null}updateCurrentThreadContexts(e){if(!this.currentNotebookId||!this.currentThreadId)return void console.warn("[ChatHistoryManager] Cannot update contexts: No active notebook or thread");const t=this.notebookChats.get(this.currentNotebookId);if(!t)return void console.warn(`[ChatHistoryManager] No threads found for notebook: ${this.currentNotebookId}`);const n=t.findIndex(e=>e.id===this.currentThreadId);-1!==n?(t[n].contexts=new Map(e),t[n].lastUpdated=Date.now(),this.saveToStorage()):console.warn(`[ChatHistoryManager] Thread with ID ${this.currentThreadId} not found`)}updateCurrentThreadMessages(e,t){var n,o;if(!this.currentNotebookId||!this.currentThreadId)return void console.warn("[ChatHistoryManager] Cannot update messages: No active notebook or thread");const s=this.notebookChats.get(this.currentNotebookId);if(!s)return void console.warn(`[ChatHistoryManager] No threads found for notebook: ${this.currentNotebookId}`);const i=s.findIndex(e=>e.id===this.currentThreadId);if(-1!==i){try{for(const t of e)(null===(n=s[i].message_timestamps)||void 0===n?void 0:n.has)&&(null===(o=s[i].message_timestamps)||void 0===o?void 0:o.has(JSON.stringify(t)))||(s[i].message_timestamps.set(JSON.stringify(t),Date.now()),s[i].message_timestamps)}catch(e){return void console.log("[ChatHistoryManager] Error updating message timestamps for eval:",e)}s[i].messages=[...e],s[i].lastUpdated=Date.now(),t&&(s[i].contexts=new Map(t)),this.saveToStorage()}else console.warn(`[ChatHistoryManager] Thread with ID ${this.currentThreadId} not found`)}static getCleanMessageArrayWithTimestamps(e){return e.messages.map(t=>({...t,timestamp:e.message_timestamps.get(JSON.stringify(t))||Date.now()}))}clearCurrentThread(){this.updateCurrentThreadMessages([])}getNotebookIds(){return Array.from(this.notebookChats.keys())}async saveToStorage(){try{const e={};console.log("SAVING CHAT TO STORAGE"),console.log(this.notebookChats);for(const[t,n]of this.notebookChats.entries()){const o=n.map(e=>({...e,contexts:e.contexts?Object.fromEntries(e.contexts):{},message_timestamps:e.message_timestamps?Object.fromEntries(e.message_timestamps):{}}));e[t]=o}await q.K.setObjectValue(q.s.CHAT_HISTORIES,e),console.log("[ChatHistoryManager] Saved chat histories to StateDB storage")}catch(e){console.error("[ChatHistoryManager] Error saving chat histories to StateDB storage:",e)}}async loadFromStorage(){try{await this.migrateFromSettingsRegistry();const e=await q.K.getObjectValue(q.s.CHAT_HISTORIES,{});if(e&&Object.keys(e).length>0){this.notebookChats=new Map;for(const[t,n]of Object.entries(e)){const e=n.map(e=>({...e,contexts:e.contexts?new Map(Object.entries(e.contexts)):new Map,message_timestamps:e.message_timestamps?new Map(Object.entries(e.message_timestamps)):new Map}));this.notebookChats.set(t,e)}console.log("[ChatHistoryManager] Loaded chat histories from StateDB storage"),console.log(`[ChatHistoryManager] Loaded ${this.notebookChats.size} notebook chat histories`)}else console.log("[ChatHistoryManager] No stored chat histories found in StateDB")}catch(e){console.error("[ChatHistoryManager] Error loading chat histories from StateDB storage:",e),this.notebookChats=new Map}}async migrateFromSettingsRegistry(){try{const e=await ie.getObjectSetting(le,{});e&&Object.keys(e).length>0&&(console.log("[ChatHistoryManager] Migrating chat histories from SettingsRegistry to StateDB"),await q.K.setObjectValue(q.s.CHAT_HISTORIES,e),await ie.setObjectSetting(le,{}),console.log("[ChatHistoryManager] Successfully migrated chat histories to StateDB"))}catch(e){console.error("[ChatHistoryManager] Error during migration from SettingsRegistry to StateDB:",e)}}generateThreadId(){return"thread_"+(0,Ae.v4)()}createNewThread(e="New Chat"){if(!this.currentNotebookId)return console.warn("[ChatHistoryManager] Cannot create thread: No active notebook"),null;const t={id:this.generateThreadId(),name:e,messages:[],lastUpdated:Date.now(),contexts:new Map,message_timestamps:new Map,continueButtonShown:!1},n=this.notebookChats.get(this.currentNotebookId)||[];return this.notebookChats.set(this.currentNotebookId,[...n,t]),this.currentThreadId=t.id,this.saveToStorage(),t}switchToThread(e){if(!this.currentNotebookId)return null;const t=this.notebookChats.get(this.currentNotebookId);if(!t)return null;const n=t.find(t=>t.id===e);return n?(this.currentThreadId=e,n):null}renameCurrentThread(e){if(!this.currentNotebookId||!this.currentThreadId)return console.warn("[ChatHistoryManager] Cannot rename thread: No active notebook or thread"),!1;const t=this.notebookChats.get(this.currentNotebookId);if(!t)return console.warn(`[ChatHistoryManager] No threads found for notebook: ${this.currentNotebookId}`),!1;const n=t.findIndex(e=>e.id===this.currentThreadId);return-1===n?(console.warn(`[ChatHistoryManager] Thread with ID ${this.currentThreadId} not found`),!1):(t[n].name=e,this.saveToStorage(),console.log(`[ChatHistoryManager] Renamed thread ${this.currentThreadId} to "${e}"`),!0)}deleteThread(e){if(!this.currentNotebookId)return console.warn("[ChatHistoryManager] Cannot delete thread: No active notebook"),!1;const t=this.notebookChats.get(this.currentNotebookId);if(!t)return!1;const n=t.findIndex(t=>t.id===e);if(-1===n)return!1;if(t.splice(n,1),e===this.currentThreadId)if(t.length>0)this.currentThreadId=t[t.length-1].id;else{const e={id:this.generateThreadId(),name:"New Chat",messages:[],lastUpdated:Date.now(),contexts:new Map,message_timestamps:new Map,continueButtonShown:!1};t.push(e),this.currentThreadId=e.id}return this.saveToStorage(),console.log(`[ChatHistoryManager] Deleted thread ${e}`),!0}}class Re{constructor(e,t,n,o,s){var i;this.currentNotebookId=null,this.templates=[],this.chatHistoryManager=e,this.messageComponent=t,this.chatService=n,this.threadNameDisplay=o,this.chatNode=s,this.initializeBanner(),m.AppStateService.onNotebookChanged().subscribe(({newNotebookId:e})=>{e&&this.setNotebookId(e)}),this.updateThreadSelectorButtonText((null===(i=this.chatHistoryManager.getCurrentThread())||void 0===i?void 0:i.name)||"New Chat")}updateNotebookId(e){this.setNotebookId(e)}setNotebookId(e){var t;this.currentNotebookId=e,this.refreshBannerIfVisible(),this.updateThreadSelectorButtonText((null===(t=this.chatHistoryManager.getCurrentThread())||void 0===t?void 0:t.name)||"New Chat")}async storeLastThreadForNotebook(e,t){try{const n=`last-thread-${e}`;t?await q.K.setValue(n,t):await q.K.removeValue(n),console.log(`[ThreadManager] Stored last thread ${t} for notebook ${e}`)}catch(e){console.warn("[ThreadManager] Failed to store last thread:",e)}}async getLastThreadForNotebook(e){try{const t=`last-thread-${e}`,n=await q.K.getValue(t,null);return console.log(`[ThreadManager] Retrieved last thread ${n} for notebook ${e}`),n}catch(e){return console.warn("[ThreadManager] Failed to get last thread:",e),null}}async getLastValidThreadForNotebook(e){try{const t=await this.getLastThreadForNotebook(e);if(!t)return null;const n=this.chatHistoryManager.getThreadsForNotebook(e);if(!n)return console.log(`[ThreadManager] No threads found for notebook ${e}`),await this.clearLastThreadForNotebook(e),null;const o=n.find(e=>e.id===t);return o?(console.log(`[ThreadManager] Found valid last thread: ${o.name} for notebook ${e}`),o):(console.log(`[ThreadManager] Last thread ${t} no longer exists for notebook ${e}`),await this.clearLastThreadForNotebook(e),null)}catch(e){return console.warn("[ThreadManager] Failed to get last valid thread:",e),null}}async clearLastThreadForNotebook(e){try{const t=`last-thread-${e}`;await q.K.removeValue(t),console.log(`[ThreadManager] Cleared last thread for notebook ${e}`)}catch(e){console.warn("[ThreadManager] Failed to clear last thread:",e)}}filterNewChatThreads(e){const t=e.filter(e=>"New Chat"===e.name);if(t.length<=1)return e;const n=t[0];return e.filter(e=>"New Chat"!==e.name||e.id===n.id)}updateThreadSelectorButtonText(e){const t=this.threadNameDisplay;t&&(t.textContent=e)}async selectThread(e){var t,n,o,s;this.chatService.cancelRequest();let i=this.chatHistoryManager.getCurrentThread();if(e!==(null===(t=this.chatHistoryManager.getCurrentThread())||void 0===t?void 0:t.id)){i=this.chatHistoryManager.switchToThread(e);const t=m.AppStateService.getState().currentNotebookId;t&&await this.storeLastThreadForNotebook(t,null==i?void 0:i.id)}i&&(await this.messageComponent.loadFromThread(i),this.updateThreadSelectorButtonText(i.name),i.messages.length>0?null===(n=m.AppStateService.getState().chatContainer)||void 0===n||n.chatWidget.showHistoryWidget():null===(o=m.AppStateService.getState().chatContainer)||void 0===o||o.chatWidget.showNewChatDisplay(),null===(s=m.AppStateService.getState().chatContainer)||void 0===s||s.chatWidget.llmStateDisplay.hide(),this.clearDiffs())}async createNewThread(){if(!this.currentNotebookId)return null;const e=this.chatHistoryManager.getCurrentThread();if(e&&e.messages.length>0){const t=e.messages.find(e=>"user"===e.role&&"string"==typeof e.content);if(t&&"string"==typeof t.content){const e=this.paraphraseThreadName(t.content);this.chatHistoryManager.renameCurrentThread(e)}}const t=this.chatHistoryManager.createNewThread("New Chat");if(t){const e=m.AppStateService.getState().currentNotebookId;e&&await this.storeLastThreadForNotebook(e,null==t?void 0:t.id),await this.messageComponent.loadFromThread(t),this.updateThreadSelectorButtonText("New Chat"),this.clearDiffs()}return t}clearDiffs(){m.AppStateService.getNotebookDiffManager().rejectAndRevertDiffsImmediately()}paraphraseThreadName(e){const t=e.split(/\s+/);let n=t.slice(0,Math.min(8,t.length)).join(" ");return n.length>30&&(n=n.substring(0,27)+"..."),n}initializeBanner(){var e;this.bannerOverlay=document.createElement("div"),this.bannerOverlay.className="sage-ai-banner-overlay",this.bannerOverlay.style.display="none",this.leftSideBanner=document.createElement("div"),this.leftSideBanner.className="sage-ai-left-side-banner",this.leftSideBanner.innerHTML='\n <div class="sage-ai-banner-header">\n <h3>All Chats</h3>\n <button class="sage-ai-icon-close sage-ai-icon-button-sm">×</button>\n </div>\n <div class="sage-ai-banner-content">\n <div class="sage-ai-banner-threads"></div>\n </div>\n ',null===(e=this.leftSideBanner.querySelector(".sage-ai-icon-close"))||void 0===e||e.addEventListener("click",()=>{this.closeBanner()}),this.chatNode.appendChild(this.bannerOverlay),this.chatNode.appendChild(this.leftSideBanner),this.setupBannerEventHandlers()}setupBannerEventHandlers(){const e=this.leftSideBanner.querySelector(".sage-ai-banner-close");e&&e.addEventListener("click",()=>{this.closeBanner()}),this.bannerOverlay.addEventListener("click",()=>{this.closeBanner()})}openBanner(){this.bannerOverlay.style.display="block",this.bannerOverlay.offsetHeight,this.bannerOverlay.classList.add("visible"),this.leftSideBanner.style.display="block",this.leftSideBanner.offsetHeight,this.leftSideBanner.classList.add("visible"),this.populateBannerContent()}closeBanner(){this.leftSideBanner.classList.remove("visible"),this.bannerOverlay.classList.remove("visible"),setTimeout(()=>{this.leftSideBanner.style.display="none",this.bannerOverlay.style.display="none"},300)}populateBannerContent(){var e;const t=this.leftSideBanner.querySelector(".sage-ai-banner-threads");if(!t)return;if(t.innerHTML="",!this.currentNotebookId)return void(t.innerHTML='<div class="sage-ai-banner-empty">No notebook selected</div>');const n=this.chatHistoryManager.getCurrentNotebookThreads();if(0===n.length)return void(t.innerHTML='<div class="sage-ai-banner-empty">No chat history</div>');const o=[...n].sort((e,t)=>t.lastUpdated-e.lastUpdated),s=this.filterNewChatThreads(o);for(const n of s){const o=document.createElement("div");o.className="sage-ai-banner-thread-item",n.id===(null===(e=this.chatHistoryManager.getCurrentThread())||void 0===e?void 0:e.id)&&o.classList.add("active"),o.innerHTML=`\n <div class="sage-ai-banner-thread-name">${n.name}</div>\n <div class="sage-ai-banner-thread-date">${Be(n.lastUpdated)}</div>\n `,o.addEventListener("click",async()=>{await this.selectThread(n.id),this.closeBanner()}),t.appendChild(o)}}refreshBannerIfVisible(){this.leftSideBanner&&this.leftSideBanner.classList.contains("visible")&&this.populateBannerContent()}}function Be(e){return new Date(e).toLocaleDateString("en-US",{month:"numeric",day:"numeric",year:"2-digit"})+" · "+new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}const Pe=["module","type","function","ZMQExitAutocall","method"],je=["In","Out"],$e=[{id:"snippets",name:"Rules",icon:"📄",description:"Reusable code and prompt templates"},{id:"data",name:"Data",icon:"📊",description:"Dataset references and info"},{id:"variables",name:"Variables",icon:"🔤",description:"Code variables and values"},{id:"cells",name:"Cells",icon:"📝",description:"Notebook cell references"}];class He{constructor(e,t){this.contentManager=e,this.toolService=t}async initializeContextItems(){const e=new Map;return e.set("snippets",[]),e.set("data",[]),e.set("variables",[]),e.set("cells",[]),console.log("All context items after initialization:",Array.from(e.entries())),e}async loadSnippets(){return m.AppStateService.getSnippets().map(e=>({type:"snippets",id:e.id,name:e.title,description:e.description.length>100?e.description.substring(0,100)+"...":e.description,content:e.content}))}async loadDatasets(e="./data"){const t=[];if("./data"===e)try{const e=ke.getInstance(),n=await e.getCachedMetadata(),o="Database Connection Available:\n- DB_URL environment variable is configured in your Python kernel\n- You can connect to the database using standard Python libraries like psycopg2 or sqlalchemy\n\nDatabase Schema:\n";n&&(t.push({type:"data",id:"database-schema",name:"Database Schema",description:"Current database schema information",content:`${o} \n \n ${n}`,isDirectory:!1}),console.log("[ChatContextLoaders] Added database schema to data contexts"))}catch(e){console.warn("[ChatContextLoaders] Could not load database metadata:",e)}try{const n=await this.contentManager.get(e);if(console.log("Loaded contents from",e,":",n),n.content&&Array.isArray(n.content)){const o=n.content.filter(e=>"directory"===e.type),s=n.content.filter(e=>"file"===e.type),i=o.map(t=>({type:"directory",id:`${e}/${t.name}`,name:t.name,path:`${e}/${t.name}`,isDirectory:!0,parentPath:"./data"===e?void 0:this.getParentPath(e)})),a=await Promise.all(s.map(async t=>{const n=t.name.replace(/\.[^/.]+$/,""),o=`${(await this.contentManager.get(`${e}/${t.name}`)).content}`,s=`${e}/${t.name}`;let i="";const a=t.name.toLowerCase().endsWith(".csv");i=a?o.split("\n").slice(0,5).join("\n").slice(0,5e3):o.slice(-2e3);const r=`File Path: ${s}\n\n${i}`;return{type:"data",id:t.path,name:n,description:`Dataset file (${a?"CSV":"Data"} file)`,content:r,path:s,isDirectory:!1,parentPath:"./data"===e?void 0:this.getParentPath(e)}}));t.push(...i,...a)}}catch(t){console.error("Error loading datasets from",e,":",t)}return t}getParentPath(e){const t=e.split("/");return t.pop(),t.join("/")||"./data"}async loadCells(){console.log("Loading cells... ======================");const e=this.toolService.getCurrentNotebook();if(!e)return console.warn("No notebook available"),[];const t=[],n=e.widget.model.cells;for(const e of n){console.log("Cell:",e),console.log("Cell metadata:",e.metadata);const n=e.metadata.cell_tracker;n&&t.push({type:"cell",id:n.trackingId,name:n.trackingId,description:"",content:e.sharedModel.getSource()})}return console.log("CELL LOADING, cells:",n),t}async loadVariables(){var e;if(console.log("Loading variables... ======================"),!(null===(e=this.toolService.getCurrentNotebook())||void 0===e?void 0:e.kernel))return console.warn("No kernel available"),[];try{const e=await ve.F.getKernelVariables();if(!e)return console.log("No kernel variables available"),[];const t=[];for(const[n,o]of Object.entries(e)){if(je.includes(n))continue;if(Pe.includes(o.type))continue;let e=o.type||"unknown";o.shape?e+=` (shape: ${JSON.stringify(o.shape)})`:void 0!==o.size&&null!==o.size&&(e+=` (size: ${o.size})`);let s="";void 0!==o.value?s=JSON.stringify(o.value):void 0!==o.preview?s=JSON.stringify(o.preview):o.repr&&(s=o.repr),t.push({type:"variable",id:n,name:n,description:e,content:s})}return console.log(`[ChatContextLoaders] Loaded ${t.length} variables`),t}catch(e){return console.error("Error loading variables:",e),[]}}}class Ue{constructor(){this.contextLoaders=null,this.isInitialized=!1,this.loadingPromise=null,this.variableRefreshTimeout=null}static getInstance(){return Ue.instance||(Ue.instance=new Ue),Ue.instance}async initialize(){if(!this.isInitialized)try{const e=m.AppStateService.getContentManager(),t=m.AppStateService.getToolService();this.contextLoaders=new He(e,t),this.isInitialized=!0,console.log("[ContextCacheService] Initialized successfully")}catch(e){console.warn("[ContextCacheService] Failed to initialize:",e)}}async loadAllContexts(){if(this.loadingPromise)return this.loadingPromise;if(this.isInitialized||await this.initialize(),this.contextLoaders){m.AppStateService.setContextLoading(!0),this.loadingPromise=this.performContextLoading();try{await this.loadingPromise}finally{this.loadingPromise=null}}else console.warn("[ContextCacheService] Cannot load contexts - not properly initialized")}async performContextLoading(){if(!this.contextLoaders)return;console.log("[ContextCacheService] Starting async context loading...");const e=new Map,[t,o,s,i]=await Promise.allSettled([this.contextLoaders.loadSnippets(),this.contextLoaders.loadDatasets(),this.contextLoaders.loadVariables(),this.contextLoaders.loadCells()]);"fulfilled"===t.status?e.set("snippets",t.value):(console.warn("[ContextCacheService] Failed to load template contexts:",t.reason),e.set("snippets",[])),"fulfilled"===o.status?e.set("data",o.value):(console.warn("[ContextCacheService] Failed to load dataset contexts:",o.reason),e.set("data",[])),"fulfilled"===s.status?e.set("variables",s.value):(console.warn("[ContextCacheService] Failed to load variable contexts:",s.reason),e.set("variables",[])),"fulfilled"===i.status?e.set("cells",i.value):(console.warn("[ContextCacheService] Failed to load cell contexts:",i.reason),e.set("cells",[])),m.AppStateService.setCachedContexts(e);const a=new Map;e.forEach((e,t)=>{e.forEach(e=>{a.set(e.id,e)})});const{ContextService:r}=await Promise.resolve().then(n.bind(n,7110));r.getInstance().setContextItems(a),console.log("[ContextCacheService] Context loading completed:",Array.from(e.entries()).map(([e,t])=>`${e}: ${t.length} items`))}async refreshIfStale(){m.AppStateService.shouldRefreshContexts()&&!m.AppStateService.isContextLoading()&&(console.log("[ContextCacheService] Contexts are stale, refreshing..."),await this.loadAllContexts())}async forceRefresh(){console.log("[ContextCacheService] Force refreshing contexts..."),await this.loadAllContexts()}async loadContextCategory(e){if(this.contextLoaders||(await this.initialize(),this.contextLoaders))try{let t=[];switch(e){case"snippets":t=await this.contextLoaders.loadSnippets();break;case"data":t=await this.contextLoaders.loadDatasets();break;case"variables":t=await this.contextLoaders.loadVariables();break;case"cells":t=await this.contextLoaders.loadCells();break;default:return void console.warn(`[ContextCacheService] Unknown context category: ${e}`)}m.AppStateService.updateContextCategory(e,t);const{ContextService:o}=await Promise.resolve().then(n.bind(n,7110)),s=o.getInstance();t.forEach(e=>{s.addContextItem(e)}),console.log(`[ContextCacheService] Updated ${e} contexts: ${t.length} items`)}catch(t){console.warn(`[ContextCacheService] Failed to load ${e} contexts:`,t)}}async getContexts(){const e=m.AppStateService.getCachedContexts();return e.size>0&&!m.AppStateService.shouldRefreshContexts()?e:m.AppStateService.isContextLoading()&&this.loadingPromise?(await this.loadingPromise,m.AppStateService.getCachedContexts()):(await this.loadAllContexts(),m.AppStateService.getCachedContexts())}subscribeToNotebookChanges(){m.AppStateService.onNotebookChanged().subscribe(({newNotebookId:e})=>{e&&(console.log("[ContextCacheService] Notebook changed, refreshing contexts..."),setTimeout(()=>{this.loadAllContexts().catch(e=>{console.warn("[ContextCacheService] Failed to refresh contexts on notebook change:",e)})},100))})}refreshVariablesAfterExecution(){this.variableRefreshTimeout&&clearTimeout(this.variableRefreshTimeout),this.variableRefreshTimeout=setTimeout(()=>{console.log("[ContextCacheService] Refreshing variables after execution..."),this.loadContextCategory("variables").catch(e=>{console.warn("[ContextCacheService] Failed to refresh variables after execution:",e)})},1e3)}}Ue.instance=null;const Oe=new _.LabIcon({name:"sage-agent-internal:context-variable-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="15" viewBox="0 0 14 15" fill="none">\n <path d="M4.66667 2.25H4.08333C3.77391 2.25 3.47717 2.37292 3.25838 2.59171C3.03958 2.8105 2.91667 3.10725 2.91667 3.41667V6.33333C2.91667 6.64275 2.79375 6.9395 2.57496 7.15829C2.35617 7.37708 2.05942 7.5 1.75 7.5C2.05942 7.5 2.35617 7.62292 2.57496 7.84171C2.79375 8.0605 2.91667 8.35725 2.91667 8.66667V11.5833C2.91667 12.225 3.44167 12.75 4.08333 12.75H4.66667M9.33333 12.75H9.91667C10.2261 12.75 10.5228 12.6271 10.7416 12.4083C10.9604 12.1895 11.0833 11.8928 11.0833 11.5833V8.66667C11.0833 8.025 11.6083 7.5 12.25 7.5C11.9406 7.5 11.6438 7.37708 11.425 7.15829C11.2062 6.9395 11.0833 6.64275 11.0833 6.33333V3.41667C11.0833 3.10725 10.9604 2.8105 10.7416 2.59171C10.5228 2.37292 10.2261 2.25 9.91667 2.25H9.33333" stroke="#E7E7E7" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>'}),Fe=new _.LabIcon({name:"sage-agent-internal:context-snippets-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="15" viewBox="0 0 14 15" fill="none">\n <path d="M5.83333 6.04167L4.66667 7.5L5.83333 8.95833M8.16667 6.04167L9.33333 7.5L8.16667 8.95833M2.91667 2.25H11.0833C11.7277 2.25 12.25 2.77233 12.25 3.41667V11.5833C12.25 12.2277 11.7277 12.75 11.0833 12.75H2.91667C2.27233 12.75 1.75 12.2277 1.75 11.5833V3.41667C1.75 2.77233 2.27233 2.25 2.91667 2.25Z" stroke="#E7E7E7" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>'}),Ve=new _.LabIcon({name:"sage-agent-internal:context-data-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="15" viewBox="0 0 14 15" fill="none">\n <g clip-path="url(#clip0_549_11747)">\n <path d="M12.25 3.4165C12.25 4.383 9.89949 5.1665 7 5.1665C4.1005 5.1665 1.75 4.383 1.75 3.4165M12.25 3.4165C12.25 2.45001 9.89949 1.6665 7 1.6665C4.1005 1.6665 1.75 2.45001 1.75 3.4165M12.25 3.4165V11.5832C12.25 12.0473 11.6969 12.4924 10.7123 12.8206C9.72774 13.1488 8.39239 13.3332 7 13.3332C5.60761 13.3332 4.27226 13.1488 3.28769 12.8206C2.30312 12.4924 1.75 12.0473 1.75 11.5832V3.4165M1.75 7.49984C1.75 7.96397 2.30312 8.40909 3.28769 8.73727C4.27226 9.06546 5.60761 9.24984 7 9.24984C8.39239 9.24984 9.72774 9.06546 10.7123 8.73727C11.6969 8.40909 12.25 7.96397 12.25 7.49984" stroke="#E7E7E7" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </g>\n <defs>\n <clipPath id="clip0_549_11747">\n <rect width="14" height="14" fill="white" transform="translate(0 0.5)"/>\n </clipPath>\n </defs>\n</svg>'}),We=new _.LabIcon({name:"sage-agent-internal:context-cell-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="15" viewBox="0 0 14 15" fill="none">\n <path d="M1.16699 5.75L2.91699 7.5L1.16699 9.25M5.25033 2.25H11.667C11.9892 2.25 12.2503 2.51117 12.2503 2.83333V5.75C12.2503 6.07217 11.9892 6.33333 11.667 6.33333H5.25033C4.92816 6.33333 4.66699 6.07217 4.66699 5.75V2.83333C4.66699 2.51117 4.92816 2.25 5.25033 2.25ZM5.25033 8.66667H11.667C11.9892 8.66667 12.2503 8.92783 12.2503 9.25V12.1667C12.2503 12.4888 11.9892 12.75 11.667 12.75H5.25033C4.92816 12.75 4.66699 12.4888 4.66699 12.1667V9.25C4.66699 8.92783 4.92816 8.66667 5.25033 8.66667Z" stroke="#E7E7E7" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>'}),qe=new _.LabIcon({name:"sage-agent-internal:search-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="15" viewBox="0 0 14 15" fill="none">\n <path d="M12.25 12.75L9.74164 10.2416M11.0833 6.91667C11.0833 9.494 8.994 11.5833 6.41667 11.5833C3.83934 11.5833 1.75 9.494 1.75 6.91667C1.75 4.33934 3.83934 2.25 6.41667 2.25C8.994 2.25 11.0833 4.33934 11.0833 6.91667Z" stroke="#949494" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>'}),ze=new _.LabIcon({name:"sage-agent-internal:back-caret-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="15" viewBox="0 0 14 15" fill="none">\n <path d="M8.75 11L5.25 7.5L8.75 4" stroke="#E7E7E7" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>'}),Ke=new _.LabIcon({name:"sage-agent-internal:insert-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">\n <mask id="mask0_457_5331" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="20" height="20">\n <rect y="20" width="20" height="20" transform="rotate(-90 0 20)" fill="#D9D9D9"/>\n </mask>\n <g mask="url(#mask0_457_5331)">\n <path d="M18.3327 9.99992C18.3327 11.1527 18.1139 12.236 17.6764 13.2499C17.2389 14.2638 16.6452 15.1458 15.8952 15.8958C15.1452 16.6458 14.2632 17.2395 13.2493 17.677C12.2355 18.1145 11.1521 18.3333 9.99935 18.3333C8.44379 18.3333 7.00977 17.9409 5.69727 17.1562C4.38477 16.3714 3.3674 15.3055 2.64518 13.9583C2.53407 13.7499 2.52018 13.5312 2.60352 13.302C2.68685 13.0728 2.83963 12.9096 3.06185 12.8124C3.27018 12.7291 3.48199 12.7291 3.69727 12.8124C3.91254 12.8958 4.07574 13.0346 4.18685 13.2291C4.77018 14.2708 5.57921 15.1041 6.61393 15.7291C7.64865 16.3541 8.77713 16.6666 9.99935 16.6666C11.8605 16.6666 13.4368 16.0208 14.7285 14.7291C16.0202 13.4374 16.666 11.861 16.666 9.99992C16.666 8.13881 16.0202 6.56242 14.7285 5.27075C13.4368 3.97908 11.8605 3.33325 9.99935 3.33325C8.77713 3.33325 7.64865 3.64575 6.61393 4.27075C5.57921 4.89575 4.77018 5.72909 4.18685 6.77075C4.07574 6.9652 3.91254 7.10409 3.69727 7.18742C3.48199 7.27075 3.27018 7.27075 3.06185 7.18742C2.83963 7.10409 2.6799 6.95478 2.58268 6.7395C2.48546 6.52422 2.4924 6.31936 2.60352 6.12492C3.31185 4.76381 4.32574 3.68047 5.64518 2.87492C6.96463 2.06936 8.41601 1.66659 9.99935 1.66659C11.1521 1.66659 12.2355 1.88534 13.2493 2.32284C14.2632 2.76034 15.1452 3.35408 15.8952 4.10408C16.6452 4.85408 17.2389 5.73603 17.6764 6.74992C18.1139 7.76381 18.3327 8.84714 18.3327 9.99992ZM10.1452 10.8333L2.49935 10.8333C2.26324 10.8333 2.06532 10.7534 1.9056 10.5937C1.74588 10.4339 1.66602 10.236 1.66602 9.99992C1.66602 9.76381 1.74588 9.56589 1.9056 9.40617C2.06532 9.24645 2.26324 9.16659 2.49935 9.16659L10.1452 9.16659L8.58268 7.58325C8.4299 7.43047 8.35004 7.2395 8.3431 7.01033C8.33615 6.78117 8.41602 6.58325 8.58268 6.41658C8.73546 6.26381 8.9299 6.18742 9.16602 6.18742C9.40213 6.18742 9.59657 6.26381 9.74935 6.41658L12.7493 9.41659C12.916 9.58325 12.9993 9.7777 12.9993 9.99992C12.9993 10.2221 12.916 10.4166 12.7493 10.5833L9.74935 13.5833C9.59657 13.736 9.4056 13.8159 9.17643 13.8228C8.94726 13.8298 8.74935 13.7499 8.58268 13.5833C8.4299 13.4305 8.35352 13.236 8.35352 12.9999C8.35352 12.7638 8.4299 12.5694 8.58268 12.4166L10.1452 10.8333Z" fill="#3B82F6"/>\n </g>\n</svg>'}),Ge=new _.LabIcon({name:"sage-agent-internal:folder-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">\n <path d="M2 3.5C2 2.67157 2.67157 2 3.5 2H6.79289C7.15482 2 7.50207 2.14365 7.76777 2.40934L9.70711 4.34868C9.97281 4.61438 10.32 4.75803 10.682 4.75803H12.5C13.3284 4.75803 14 5.4296 14 6.25803V12.5C14 13.3284 13.3284 14 12.5 14H3.5C2.67157 14 2 13.3284 2 12.5V3.5Z" fill="currentColor"/>\n </svg>'});function Je(e){return"textarea"===e.tagName.toLowerCase()}function Ye(e){switch(e){case"snippets":return"snippets";case"data":case"directory":return"data";case"variable":return"variables";case"cell":return"cells";default:return""}}function Ze(e,t,n){const o=document.createElement("div");o.className=t,o.setAttribute("data-id",e.id),o.setAttribute("data-type",e.type),n&&o.setAttribute("data-category",n);const s=document.createElement("span");s.className="sage-ai-mention-item-icon";const i=function(e){switch(e){case"snippets":return Fe.svgstr;case"data":return Ve.svgstr;case"directory":return Ge.svgstr;case"variable":return Oe.svgstr;case"cell":return We.svgstr;default:return"❓"}}(e.type);"❓"!==i?s.innerHTML=i:s.textContent=i;const a=document.createElement("div");a.style.flex="1";const r=document.createElement("div");if(r.className="sage-ai-mention-item-text",r.textContent=e.name,a.appendChild(r),e.description){const t=document.createElement("div");t.className="sage-ai-mention-item-description",t.textContent=e.description,a.appendChild(t)}return o.appendChild(s),o.appendChild(a),o}class Xe{constructor(e,t,n,o){this.isVisible=!1,this.mentionTrigger="@",this.currentMentionStart=-1,this.currentMentionText="",this.searchText="",this.onContextSelected=null,this.currentView="categories",this.selectedCategory=null,this.selectedIndex=0,this.currentDataPath="./data",this.categories=$e,this.contextItems=new Map,this.handleInput=async e=>{const t=this.getSelectionStart(),n=this.getInputValue();if(this.isVisible)return t<this.currentMentionStart||!n.substring(this.currentMentionStart,t).startsWith(this.mentionTrigger)?void this.hideDropdown():(this.currentMentionText=n.substring(this.currentMentionStart+1,t),this.searchInput.value!==this.currentMentionText&&(this.searchInput.value=this.currentMentionText,this.searchText=this.currentMentionText),void await this.renderDropdown(this.searchText));n.charAt(t-1)===this.mentionTrigger&&(this.currentMentionStart=t-1,this.currentMentionText="",this.showDropdown())},this.handleSearchInput=async e=>{const t=e.target;this.searchText=t.value,this.selectedIndex=0,await this.renderDropdown(this.searchText)},this.handleSearchKeyDown=e=>{switch(e.key){case"ArrowDown":e.preventDefault(),this.navigateDropdown("down");break;case"ArrowUp":e.preventDefault(),this.navigateDropdown("up");break;case"Tab":case"Enter":e.preventDefault(),this.selectCurrentItem();break;case"Escape":e.preventDefault(),this.hideDropdown()}},this.handleDropdownClick=async e=>{e.preventDefault(),e.stopPropagation();const t=e.target,n=t.closest(".sage-ai-mention-category-main");if(n){const e=n.getAttribute("data-category");return void(e&&(this.selectedCategory=e,this.currentView="items","data"===e&&(this.currentDataPath="./data"),this.searchInput.value="",this.searchText="",this.updateSearchPlaceholder(),await this.refreshContextItems(e),this.renderDropdown(this.searchText),this.positionDropdown(),setTimeout(()=>this.searchInput.focus(),0)))}const o=t.closest(".sage-ai-mention-subcategory");if(o){const e=o.getAttribute("data-id"),t=o.getAttribute("data-category"),n=o.getAttribute("data-type");if(e){if("directory"===n&&"data"===this.selectedCategory)return this.currentDataPath=e,await this.refreshContextItems("data"),this.renderDropdown(this.searchText),void this.positionDropdown();"categories"===this.currentView&&t&&(this.selectedCategory=t),this.selectItem(e)}}},this.handleKeyDown=e=>{if(this.isVisible)switch(e.key){case"ArrowDown":e.preventDefault(),this.navigateDropdown("down");break;case"ArrowUp":e.preventDefault(),this.navigateDropdown("up");break;case"Tab":case"Enter":e.preventDefault(),this.selectCurrentItem();break;case"Escape":e.preventDefault(),this.hideDropdown()}},this.chatInput=e,this.contentManager=n,this.toolService=o,this.contextLoaders=new He(n,o),this.contextCacheService=Ue.getInstance(),this.dropdownElement=document.createElement("div"),this.dropdownElement.className="sage-ai-mention-dropdown",this.headerContainer=document.createElement("div"),this.headerContainer.className="sage-ai-mention-header-container",this.searchContainer=document.createElement("div"),this.searchContainer.className="sage-ai-mention-search-container";const s=qe.element({className:"sage-ai-mention-search-icon"});this.searchInput=document.createElement("input"),this.searchInput.type="text",this.searchInput.className="sage-ai-mention-search-input",this.searchInput.placeholder="Search...",this.searchContainer.appendChild(s),this.searchContainer.appendChild(this.searchInput),this.headerContainer.appendChild(this.searchContainer),this.contentContainer=document.createElement("div"),this.contentContainer.className="sage-ai-mention-content",this.dropdownElement.appendChild(this.headerContainer),this.dropdownElement.appendChild(this.contentContainer),t.appendChild(this.dropdownElement),this.setupEventListeners(),this.initializeContextItems()}setContextSelectedCallback(e){this.onContextSelected=e}async initializeContextItems(){this.contextItems=await this.contextLoaders.initializeContextItems()}async refreshContextItems(e){"items"===this.currentView&&this.selectedCategory===e&&this.showLoadingState(`Loading ${e}...`);try{switch(e){case"data":const e=await this.contextLoaders.loadDatasets(this.currentDataPath);this.contextItems.set("data",e);break;case"snippets":const t=await this.contextLoaders.loadSnippets();this.contextItems.set("snippets",t);break;case"variables":const n=await this.contextLoaders.loadVariables();this.contextItems.set("variables",n);break;case"cells":const o=await this.contextLoaders.loadCells();this.contextItems.set("cells",o)}}finally{"items"===this.currentView&&this.selectedCategory===e&&this.hideLoadingState()}}setupEventListeners(){this.chatInput.addEventListener("input",this.handleInput),this.chatInput.addEventListener("keydown",this.handleKeyDown),this.searchInput.addEventListener("input",this.handleSearchInput),this.searchInput.addEventListener("keydown",this.handleSearchKeyDown),document.addEventListener("click",e=>{this.dropdownElement.contains(e.target)||e.target===this.chatInput||this.hideDropdown()}),this.dropdownElement.addEventListener("click",this.handleDropdownClick)}getSelectionStart(){return function(e){if(Je(e))return e.selectionStart||0;{const t=window.getSelection();if(!t||0===t.rangeCount)return 0;const n=t.getRangeAt(0),o=n.cloneRange();return o.selectNodeContents(e),o.setEnd(n.startContainer,n.startOffset),o.toString().length}}(this.chatInput)}getInputValue(){return Je(e=this.chatInput)?e.value||"":e.textContent||"";var e}setInputValue(e){!function(e,t){Je(e)?e.value=t:e.textContent=t}(this.chatInput,e)}setSelectionRange(e,t){!function(e,t,n){if(Je(e))e.setSelectionRange(t,n);else{const o=window.getSelection();if(!o)return;const s=function(e,t,n){var o,s,i;const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let r=0,l=null,c=0,d=null,h=0;for(;a.nextNode();){const e=a.currentNode,s=(null===(o=e.textContent)||void 0===o?void 0:o.length)||0;if(!l&&r+s>=t&&(l=e,c=t-r),r+s>=n){d=e,h=n-r;break}r+=s}if(l&&d){const e=document.createRange();return e.setStart(l,Math.min(c,(null===(s=l.textContent)||void 0===s?void 0:s.length)||0)),e.setEnd(d,Math.min(h,(null===(i=d.textContent)||void 0===i?void 0:i.length)||0)),e}return null}(e,t,n);s&&(o.removeAllRanges(),o.addRange(s))}}(this.chatInput,e,t)}getCaretCoordinates(){return function(e){const t=window.getSelection();if(!t||0===t.rangeCount)return{top:0,left:0,height:20};const n=t.getRangeAt(0).getBoundingClientRect(),o=e.getBoundingClientRect();return{top:n.top-o.top,left:n.left-o.left,height:n.height||20}}(this.chatInput)}positionDropdown(){if(!this.isVisible)return;const e=this.getCaretCoordinates();console.log("Caret coordinates:",e),function(e,t){let{top:n,left:o}=t;if(o<0||n<0)return;e.style.position="fixed",e.style.left=`${o}px`,e.style.zIndex="9999",e.style.maxHeight="200px",e.style.transform="translateY(-100%) translateY(-8px)",e.style.marginBottom="12px";const s=e.getBoundingClientRect(),i=s.bottom-window.innerHeight;i+30>0&&(e.style.maxHeight=e.clientHeight-(i+30)+"px");const a=s.right-window.innerWidth;a+20>0&&(e.style.left=o-a-64+"px")}(this.dropdownElement,e)}updateCategoryHeader(){const e=this.headerContainer.querySelector(".sage-ai-mention-category-header");if(e&&e.remove(),"items"===this.currentView&&this.selectedCategory){const e=document.createElement("div");e.className="sage-ai-mention-category-header";const t=ze.element({className:"sage-ai-mention-back-icon"}),n=document.createElement("span");n.className="sage-ai-mention-category-title";const o=this.categories.find(e=>e.id===this.selectedCategory);let s=(null==o?void 0:o.name)||this.selectedCategory;if("data"===this.selectedCategory&&"./data"!==this.currentDataPath){const e=this.currentDataPath.split("/"),t=e[e.length-1];s=`${(null==o?void 0:o.name)||"Data"} / ${t}`}n.textContent=s,e.addEventListener("click",async()=>{if("data"===this.selectedCategory&&"./data"!==this.currentDataPath){const e=this.currentDataPath.split("/");e.pop(),this.currentDataPath=e.join("/")||"./data",await this.refreshContextItems("data"),this.renderDropdown(this.searchText)}else this.currentView="categories",this.selectedCategory=null,this.selectedIndex=0,this.currentDataPath="./data",this.renderDropdown(this.searchText)}),e.appendChild(t),e.appendChild(n),this.headerContainer.insertBefore(e,this.searchContainer)}}async renderDropdown(e){if(this.contentContainer.innerHTML="",this.updateCategoryHeader(),"categories"===this.currentView){const t=this.renderDatabaseSchema(e);if(e&&e.length>0){const n=this.renderMatchingItems(e);if((t||n)&&e.length<2){const e=document.createElement("div");e.className="sage-ai-mention-separator",e.textContent="Categories",this.contentContainer.appendChild(e)}(!n||e.length<2)&&this.renderCategories()}else{if(t){const e=document.createElement("div");e.className="sage-ai-mention-separator",e.textContent="Categories",this.contentContainer.appendChild(e)}this.renderCategories()}}else"items"===this.currentView&&this.selectedCategory&&await this.renderCategoryItems(this.selectedCategory,e);this.selectedIndex=0,this.highlightItem(this.selectedIndex),this.positionDropdown()}calculateRelevanceScore(e,t){return function(e,t){const n=e.name.toLowerCase(),o=t.toLowerCase();if(!o)return 0;if(n===o)return 1e3;if(n.startsWith(o))return 900;if(new RegExp(`\\b${o}`,"i").test(n))return 800;if(n.includes(o))return 700;let s=0,i=0;for(let e=0;e<n.length&&i<o.length;e++)n[e]===o[i]&&(s+=10,i++);return i===o.length?500+s:0}(e,t)}renderMatchingItems(e){const t=[];for(const[n,o]of this.contextItems.entries())for(const n of o){const o=this.calculateRelevanceScore(n,e);o>500&&t.push({item:n,score:o})}return t.sort((e,t)=>e.score!==t.score?t.score-e.score:e.item.name.localeCompare(t.item.name)),t.length>0&&(t.slice(0,10).forEach(({item:e})=>{const t=Ze(e,"sage-ai-mention-item sage-ai-mention-subcategory",Ye(e.type));this.contentContainer.appendChild(t)}),!0)}getCategoryForType(e){return Ye(e)}renderCategories(){this.categories.forEach(e=>{const t=function(e){const t=document.createElement("div");t.className="sage-ai-mention-item sage-ai-mention-category-main",t.setAttribute("data-category",e.id);const n=document.createElement("span");let o;switch(n.className="sage-ai-mention-item-icon",e.id){case"snippets":o=Fe.svgstr;break;case"data":o=Ve.svgstr;break;case"variables":o=Oe.svgstr;break;case"cells":o=We.svgstr;break;default:o=e.icon}o&&o!==e.icon?n.innerHTML=o:n.textContent=e.icon;const s=document.createElement("div");s.style.flex="1";const i=document.createElement("div");return i.className="sage-ai-mention-item-text",i.textContent=e.name,s.appendChild(i),t.appendChild(n),t.appendChild(s),t}(e);this.contentContainer.appendChild(t)})}async renderCategoryItems(e,t=""){"data"===e&&await this.refreshContextItems("data");const n=this.contextItems.get(e)||[];if(console.log(`Rendering items for category ${e}:`,n),0===n.length){const t=document.createElement("div");return t.className="sage-ai-mention-empty",t.textContent=function(e){switch(e){case"data":return"No datasets available. Add datasets to reference them here.";case"variables":return"No variables available. Define variables in your notebook to reference them here.";case"cells":return"No cells available. Create cells in your notebook to reference them here.";case"snippets":return"No rules available. Create rules using the Rules panel to reference them here.";default:return"No items found"}}(e),void this.contentContainer.appendChild(t)}if("data"===e){const e=n.filter(e=>e.isDirectory),o=n.filter(e=>!e.isDirectory);let s=e,i=o;if(t){const n=[],a=[];for(const o of e){const e=this.calculateRelevanceScore(o,t);e>500&&n.push({item:o,score:e})}for(const e of o){const n=this.calculateRelevanceScore(e,t);n>500&&a.push({item:e,score:n})}n.sort((e,t)=>e.score!==t.score?t.score-e.score:e.item.name.localeCompare(t.item.name)),a.sort((e,t)=>e.score!==t.score?t.score-e.score:e.item.name.localeCompare(t.item.name)),s=n.slice(0,5).map(({item:e})=>e),i=a.slice(0,10).map(({item:e})=>e)}s.forEach(e=>{const t=Ze(e,"sage-ai-mention-item sage-ai-mention-subcategory sage-ai-mention-directory");this.contentContainer.appendChild(t)}),i.forEach(e=>{const t=Ze(e,"sage-ai-mention-item sage-ai-mention-subcategory");this.contentContainer.appendChild(t)})}else{let e=n;if(t){const o=[];for(const e of n){const n=this.calculateRelevanceScore(e,t);n>500&&o.push({item:e,score:n})}o.sort((e,t)=>e.score!==t.score?t.score-e.score:e.item.name.localeCompare(t.item.name)),e=o.slice(0,10).map(({item:e})=>e)}e.forEach(e=>{const t=Ze(e,"sage-ai-mention-item sage-ai-mention-subcategory");this.contentContainer.appendChild(t)})}}renderDatabaseSchema(e=""){const t=(this.contextItems.get("data")||[]).find(e=>"database-schema"===e.id);if(!t)return!1;if(e&&e.length>0&&this.calculateRelevanceScore(t,e)<=500)return!1;const n=Ze(t,"sage-ai-mention-item sage-ai-mention-subcategory sage-ai-mention-database-schema","data");return this.contentContainer.appendChild(n),!0}highlightItem(e){const t=this.contentContainer.querySelectorAll(".sage-ai-mention-item, .sage-ai-mention-subcategory");if(t.forEach(e=>e.classList.remove("active")),t.length>0&&e>=0&&e<t.length){t[e].classList.add("active");const n=t[e],o=this.contentContainer.getBoundingClientRect(),s=n.getBoundingClientRect();s.bottom>o.bottom?this.contentContainer.scrollTop+=s.bottom-o.bottom:s.top<o.top&&(this.contentContainer.scrollTop-=o.top-s.top)}}async selectItem(e){let t;if(this.selectedCategory)t=(this.contextItems.get(this.selectedCategory)||[]).find(t=>t.id===e);else for(const[n,o]of this.contextItems.entries())if(t=o.find(t=>t.id===e),t)break;if(!t)return;const n=this.getInputValue().substring(0,this.currentMentionStart),o=this.currentMentionStart+1+this.currentMentionText.length,s=this.getInputValue().substring(o),i=`@${t.name.replace(/\s+/g,"_")} `;this.setInputValue(n+i+s);const a=this.currentMentionStart+i.length;if(this.setSelectionRange(a,a),this.hideDropdown(),this.chatInput.focus(),this.onContextSelected){let e={...t};this.onContextSelected(e)}}updateSearchPlaceholder(){var e;if("categories"===this.currentView)this.searchInput.placeholder="Search all items...";else if(this.selectedCategory){const t=(null===(e=this.categories.find(e=>e.id===this.selectedCategory))||void 0===e?void 0:e.name)||"items";this.searchInput.placeholder=`Search ${t.toLowerCase()}...`}}showLoadingState(e="Loading contexts..."){const t=this.contentContainer.querySelector(".sage-ai-mention-loading");t&&t.remove();const n=function(e="Loading contexts..."){const t=document.createElement("div");t.className="sage-ai-mention-loading";const n=document.createElement("div");n.className="sage-ai-mention-loading-spinner";const o=document.createElement("span");return o.className="sage-ai-mention-loading-text",o.textContent=e,t.appendChild(n),t.appendChild(o),t}(e);this.contentContainer.appendChild(n)}hideLoadingState(){const e=this.contentContainer.querySelector(".sage-ai-mention-loading");e&&e.remove()}async showDropdown(){if(this.isVisible=!0,this.currentView="categories",this.selectedCategory=null,this.selectedIndex=0,this.dropdownElement.classList.add("visible"),this.searchInput.value="",this.searchText="",this.updateSearchPlaceholder(),this.positionDropdown(),m.AppStateService.isContextLoading()){await this.loadContextsAndRender(),this.showLoadingState("Refreshing contexts...");const e=setInterval(async()=>{m.AppStateService.isContextLoading()||(clearInterval(e),this.hideLoadingState(),await this.loadContextsAndRender())},100);return}await this.loadContextsAndRender()}async loadContextsAndRender(){try{const e=await this.contextCacheService.getContexts();this.contextItems=e,console.log("[ChatContextMenu] Using cached contexts:",Array.from(this.contextItems.entries()).map(([e,t])=>`${e}: ${t.length} items`))}catch(e){console.warn("[ChatContextMenu] Failed to get cached contexts, falling back to direct loading:",e);const t=await this.contextLoaders.loadSnippets(),n=await this.contextLoaders.loadVariables(),o=await this.contextLoaders.loadDatasets(),s=await this.contextLoaders.loadCells();this.contextItems.set("snippets",t),this.contextItems.set("data",o),this.contextItems.set("variables",n),this.contextItems.set("cells",s)}await this.renderDropdown(""),setTimeout(()=>this.searchInput.focus(),0)}hideDropdown(){this.isVisible=!1,this.dropdownElement.classList.remove("visible"),this.currentMentionStart=-1,this.currentMentionText="",this.currentView="categories",this.selectedCategory=null}navigateDropdown(e){const t=this.contentContainer.querySelectorAll(".sage-ai-mention-item, .sage-ai-mention-subcategory");0!==t.length&&(this.selectedIndex="down"===e?(this.selectedIndex+1)%t.length:this.selectedIndex<=0?t.length-1:this.selectedIndex-1,this.highlightItem(this.selectedIndex))}async selectCurrentItem(){const e=this.dropdownElement.querySelectorAll(".sage-ai-mention-item, .sage-ai-mention-subcategory");if(0===e.length||this.selectedIndex<0||this.selectedIndex>=e.length)return;const t=e[this.selectedIndex];if(t.classList.contains("sage-ai-mention-category-main")){const e=t.getAttribute("data-category");return void(e&&(this.selectedCategory=e,this.currentView="items",this.selectedIndex=0,"data"===e&&(this.currentDataPath="./data"),this.searchInput.value="",this.searchText="",this.updateSearchPlaceholder(),await this.refreshContextItems(e),await this.renderDropdown(this.searchText),this.positionDropdown(),setTimeout(()=>this.searchInput.focus(),0)))}if(t.classList.contains("sage-ai-mention-subcategory")){const e=t.getAttribute("data-id"),n=t.getAttribute("data-category"),o=t.getAttribute("data-type");if(e){if("directory"===o&&"data"===this.selectedCategory)return this.currentDataPath=e,await this.refreshContextItems("data"),await this.renderDropdown(this.searchText),void this.positionDropdown();"categories"===this.currentView&&n&&(this.selectedCategory=n),this.selectItem(e)}}}selectHighlightedItem(){this.selectCurrentItem()}getIsVisible(){return this.isVisible}}class Qe{constructor(e=""){this.placeholder="",this.activeContexts=new Map,this.placeholder=e,this.createElement()}createElement(){this.wrapperElement=document.createElement("div"),this.wrapperElement.className="sage-ai-rich-chat-input-wrapper",this.element=document.createElement("div"),this.element.className="sage-ai-rich-chat-input",this.element.contentEditable="true",this.element.setAttribute("role","textbox"),this.element.setAttribute("aria-multiline","true"),this.element.setAttribute("data-placeholder",this.placeholder),this.wrapperElement.appendChild(this.element),this.updatePlaceholder(),this.element.addEventListener("paste",this.handlePaste.bind(this)),this.element.addEventListener("input",this.handleInput.bind(this)),this.element.addEventListener("focus",this.handleFocus.bind(this)),this.element.addEventListener("blur",this.handleBlur.bind(this))}handlePaste(e){var t;e.preventDefault();const n=(null===(t=e.clipboardData)||void 0===t?void 0:t.getData("text/plain"))||"";document.execCommand("insertText",!1,n)}handleInput(){this.updatePlaceholder(),this.formatMentions()}handleFocus(){this.isEmpty()&&(this.element.textContent="")}handleBlur(){this.updatePlaceholder()}updatePlaceholder(){this.isEmpty()?document.activeElement!==this.element&&this.element.classList.add("empty"):this.element.classList.remove("empty")}isEmpty(){return 0===(this.element.textContent||"").trim().length}formatMentions(){const e=this.getSelectionStart(),t=this.getPlainText(),n=/@(?:\{([^}]+)\}|([a-zA-Z0-9_-]+))/g;let o,s=0,i="";for(;null!==(o=n.exec(t));){const e=o[0],n=o[1]||o[2],a=o.index,r=a+e.length;i+=this.escapeHtml(t.substring(s,a));const l=this.findContextByName(n);i+=`<span class="sage-ai-mention ${this.getContextClass(null==l?void 0:l.type)}" data-mention="${this.escapeHtml(n)}">${this.escapeHtml(e)}</span>`,s=r}i+=this.escapeHtml(t.substring(s)),this.element.innerHTML=i,this.setSelectionRange(e,e)}findContextByName(e){for(const t of this.activeContexts.values())if(t.name===e)return t}getContextClass(e){switch(e){case"template":return"sage-ai-mention-template";case"data":return"sage-ai-mention-data";case"variable":return"sage-ai-mention-variable";case"cell":return"sage-ai-mention-cell";default:return"sage-ai-mention-default"}}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}getPlainText(){return this.element.textContent||""}setPlainText(e){this.element.textContent=e,this.updatePlaceholder(),this.formatMentions()}clear(){this.element.textContent="",this.updatePlaceholder()}focus(){this.element.focus()}getElement(){return this.wrapperElement}getInputElement(){return this.element}addEventListener(e,t){this.wrapperElement.addEventListener(e,t)}removeEventListener(e,t){this.wrapperElement.removeEventListener(e,t)}addInputEventListener(e,t){this.element.addEventListener(e,t)}removeInputEventListener(e,t){this.element.removeEventListener(e,t)}getSelectionStart(){const e=window.getSelection();if(!e||0===e.rangeCount)return 0;const t=e.getRangeAt(0),n=t.cloneRange();return n.selectNodeContents(this.element),n.setEnd(t.startContainer,t.startOffset),n.toString().length}getSelectionEnd(){const e=window.getSelection();if(!e||0===e.rangeCount)return 0;const t=e.getRangeAt(0),n=t.cloneRange();return n.selectNodeContents(this.element),n.setEnd(t.endContainer,t.endOffset),n.toString().length}setSelectionRange(e,t){const n=window.getSelection();if(!n)return;const o=this.createRangeFromOffsets(e,t);o&&(n.removeAllRanges(),n.addRange(o))}createRangeFromOffsets(e,t){var n,o,s;const i=document.createTreeWalker(this.element,NodeFilter.SHOW_TEXT);let a=0,r=null,l=0,c=null,d=0;for(;i.nextNode();){const o=i.currentNode,s=(null===(n=o.textContent)||void 0===n?void 0:n.length)||0;if(!r&&a+s>=e&&(r=o,l=e-a),a+s>=t){c=o,d=t-a;break}a+=s}if(r&&c){const e=document.createRange();return e.setStart(r,Math.min(l,(null===(o=r.textContent)||void 0===o?void 0:o.length)||0)),e.setEnd(c,Math.min(d,(null===(s=c.textContent)||void 0===s?void 0:s.length)||0)),e}return null}setActiveContexts(e){this.activeContexts=e,this.formatMentions()}getScrollHeight(){return this.element.scrollHeight}setHeight(e){}setOverflowY(e){this.element.style.overflowY=e}setWrapperStyle(e,t){this.wrapperElement.style[e]=t}}class et{constructor(e,t,n,o,s,i,a,r){this.userMessageHistory=[],this.historyPosition=-1,this.unsavedInput="",this.activeContexts=new Map,this.onContextSelected=null,this.onContextRemoved=null,this.onResetChat=null,this.modeName="agent",this.isProcessingMessage=!1,this.checkpointToRestore=null,this.chatInput=e,this.chatHistoryManager=t,this.contentManager=n,this.toolService=o,this.onContextSelected=s||null,this.onContextRemoved=i||null,this.onResetChat=a||null,this.onModeSelected=r,this.setupEventHandlers(),this.loadUserMessageHistory()}setupEventHandlers(){const e=this.isRichTextInput(this.chatInput)?this.chatInput.getInputElement():this.chatInput;this.isRichTextInput(this.chatInput)?this.chatInput.addInputEventListener("input",()=>{this.resizeTextarea()}):e.addEventListener("input",()=>{this.resizeTextarea()});const t=e=>{const t=e;if(this.mentionDropdown.getIsVisible()){if("Tab"===t.key)return t.preventDefault(),void this.handleTabCompletion();if("Enter"===t.key)return t.preventDefault(),void this.handleEnterWithMention()}if("Enter"===t.key){if(t.shiftKey)return;return this.hasCompleteMentionAtCursor()?(t.preventDefault(),void this.processCompleteMention()):(t.preventDefault(),void this.sendMessage())}"ArrowUp"===t.key?0!==this.getSelectionStart()&&""!==this.getInputValue()||(t.preventDefault(),this.navigateHistory("up")):"ArrowDown"===t.key&&(this.getSelectionStart()!==this.getInputLength()&&""!==this.getInputValue()||(t.preventDefault(),this.navigateHistory("down")))};this.isRichTextInput(this.chatInput)?this.chatInput.addInputEventListener("keydown",t):e.addEventListener("keydown",t)}loadUserMessageHistory(){this.userMessageHistory=[];const e=this.chatHistoryManager.getNotebookIds();for(const t of e){const e=this.chatHistoryManager.getThreadsForNotebook(t);if(e)for(const t of e)t.messages.filter(e=>"user"===e.role&&"string"==typeof e.content).map(e=>"string"==typeof e.content?e.content:"").forEach(e=>{e&&!this.userMessageHistory.includes(e)&&this.userMessageHistory.push(e)})}this.historyPosition=-1,this.unsavedInput="",this.userMessageHistory.sort((e,t)=>e.length!==t.length?e.length-t.length:e.localeCompare(t)),console.log(`[ChatInputManager] Loaded ${this.userMessageHistory.length} user messages for history navigation`)}navigateHistory(e){if(0!==this.userMessageHistory.length){if(-1===this.historyPosition&&(this.unsavedInput=this.getInputValue()),"up"===e){if(this.historyPosition<this.userMessageHistory.length-1){this.historyPosition++;const e=this.userMessageHistory[this.userMessageHistory.length-1-this.historyPosition];this.setInputValue(e);const t=e.length;this.setSelectionRange(t,t)}}else if(this.historyPosition>0){this.historyPosition--;const e=this.userMessageHistory[this.userMessageHistory.length-1-this.historyPosition];this.setInputValue(e);const t=e.length;this.setSelectionRange(t,t)}else if(0===this.historyPosition){this.historyPosition=-1,this.setInputValue(this.unsavedInput);const e=this.unsavedInput.length;this.setSelectionRange(e,e)}this.resizeTextarea()}}resizeTextarea(){if(this.isRichTextInput(this.chatInput)){this.chatInput.setHeight("auto");const e=150,t=this.chatInput.getScrollHeight();t<=e?(this.chatInput.setHeight(t+"px"),this.chatInput.setOverflowY("hidden")):(this.chatInput.setHeight(e+"px"),this.chatInput.setOverflowY("auto"))}else{this.chatInput.style.height="auto";const e=150,t=this.chatInput.scrollHeight;t<=e?(this.chatInput.style.height=t+"px",this.chatInput.style.overflowY="hidden"):(this.chatInput.style.height=e+"px",this.chatInput.style.overflowY="auto")}}setInputValue(e){this.isRichTextInput(this.chatInput)?this.chatInput.setPlainText(e):this.chatInput.value=e}getInputValue(){return this.isRichTextInput(this.chatInput)?this.chatInput.getPlainText().trim():this.chatInput.value.trim()}isRichTextInput(e){return e instanceof Qe}getSelectionStart(){return this.isRichTextInput(this.chatInput)?this.chatInput.getSelectionStart():this.chatInput.selectionStart||0}setSelectionRange(e,t){this.isRichTextInput(this.chatInput)?this.chatInput.setSelectionRange(e,t):(this.chatInput.selectionStart=e,this.chatInput.selectionEnd=t)}getInputLength(){return this.getInputValue().length}clearInput(){this.isRichTextInput(this.chatInput)?this.chatInput.clear():(this.chatInput.value="",this.chatInput.style.height="auto"),this.focus()}addToHistory(e){this.userMessageHistory.includes(e)||this.userMessageHistory.push(e),this.historyPosition=-1,this.unsavedInput=""}focus(){this.isRichTextInput(this.chatInput),this.chatInput.focus()}getCurrentInputValue(){return this.getInputValue()}setDependencies(e){this.chatService=e.chatService,this.conversationService=e.conversationService,this.messageComponent=e.messageComponent,this.uiHelper=e.uiHelper,this.contextHandler=e.contextHandler,this.sendButton=e.sendButton,this.modeSelector=e.modeSelector,this.cancelMessage=e.cancelMessage,this.onMessageSent=e.onMessageSent}setModeName(e){this.modeName=e}getIsProcessingMessage(){return this.isProcessingMessage}setIsProcessingMessage(e){this.isProcessingMessage=e}getCheckpointToRestore(){return this.checkpointToRestore}setCheckpointToRestore(e){this.checkpointToRestore=e}async sendMessage(e){if(!(this.chatService&&this.conversationService&&this.messageComponent&&this.uiHelper&&this.contextHandler&&this.sendButton&&this.modeSelector))return void console.error("ChatInputManager dependencies not set. Call setDependencies() first.");const t=this.getCurrentInputValue();if(!t||this.isProcessingMessage)return;if(this.checkpointToRestore&&await this.conversationService.finishCheckpointRestoration(this.checkpointToRestore),m.AppStateService.getWaitingUserReplyBoxManager().hide(),"reset"===t.toLowerCase())return this.onResetChat&&this.onResetChat(),void this.clearInput();if(this.addToHistory(t),this.onMessageSent&&this.onMessageSent(),this.isProcessingMessage=!0,this.uiHelper.updateSendButton(this.sendButton,!0),m.AppStateService.getPlanStateDisplay().setLoading(!0),this.uiHelper.updateAgentModeElement(this.modeSelector,!0),this.uiHelper.resetToGeneratingState("Generating..."),!this.chatService.isInitialized())return this.messageComponent.addSystemMessage("❌ API key is not set. Please configure it in the settings."),this.isProcessingMessage=!1,this.uiHelper.updateSendButton(this.sendButton,!1),m.AppStateService.getPlanStateDisplay().setLoading(!1),this.uiHelper.updateAgentModeElement(this.modeSelector,!1),void this.uiHelper.hideLoadingIndicator();const n=[];this.clearInput();const s=(i=t,a=this.activeContexts,i.replace(/@(?:\{([^}]+)\}|([a-zA-Z0-9_-]+))/g,(e,t,n)=>{const o=t||n;for(const[e,t]of a.entries())if(t.name.replace(/\s+/g,"_")===o||t.name===o)return V(t);return e}));var i,a;console.log("[ChatInputManager] Original message:",t),console.log("[ChatInputManager] Processed message with context tags:",s),this.messageComponent.addUserMessage(s,t);const r={role:"user",content:s};try{const t=m.AppStateService.getCurrentNotebookId();if(t){this.conversationService.setNotebookId(t);const e=await K.detectChanges(t),o=K.generateChangeSummaryMessage(e);o&&(n.push(o),console.log("[ChatInputManager] Detected notebook changes, added to system messages"))}const o=[r];e&&n.push(e),this.messageComponent.getMentionContexts().size>0&&n.push(this.contextHandler.getCurrentContextMessage()),m.AppStateService.getNotebookDiffManager().clearDiffs(),await this.conversationService.processConversation(o,n,this.modeName),t&&await K.cacheCurrentNotebookState(t),console.log("[ChatInputManager] Cached notebook state after message processing")}catch(e){console.error("Error in conversation processing:",e),this.chatService.getRequestStatus()!==o.yR.CANCELLED&&this.messageComponent.addErrorMessage(`❌ ${e instanceof Error?e.message:"An error occurred while communicating with the AI service."}`)}finally{this.isProcessingMessage=!1,this.uiHelper.updateSendButton(this.sendButton,!1),m.AppStateService.getPlanStateDisplay().setLoading(!1),this.uiHelper.updateAgentModeElement(this.modeSelector,!1)}}handleTabCompletion(){this.mentionDropdown.selectHighlightedItem()}handleEnterWithMention(){this.mentionDropdown.selectHighlightedItem()}completeMentionWithName(e){const t=this.getInputValue(),n=this.getSelectionStart();let o=-1;for(let e=n-1;e>=0;e--){if("@"===t[e]){o=e;break}if(" "===t[e]||"\n"===t[e])break}if(-1===o)return;const s=t.substring(0,o),i=t.substring(n),a=`@${e.replace(/\s+/g,"_")} `;this.setInputValue(s+a+i);const r=o+a.length;this.setSelectionRange(r,r)}hasCompleteMentionAtCursor(){const e=this.getInputValue(),t=this.getSelectionStart();return null!==e.substring(0,t).match(/@(\w+)\s*$/)}processCompleteMention(){const e=this.getInputValue(),t=this.getSelectionStart(),n=e.substring(0,t).match(/@(\w+)\s*$/);if(n){const e=n[1];console.log(`Processing complete mention: ${e}`),this.focus()}}createInputContainer(){this.inputContainer=document.createElement("div"),this.inputContainer.className="sage-ai-input-container",this.inputContainer.style.position="relative",this.chatboxWrapper=document.createElement("div"),this.chatboxWrapper.className="sage-ai-chatbox-wrapper",this.createContextRow(),this.createInputRow(),this.chatboxWrapper.appendChild(this.contextRow),this.chatboxWrapper.appendChild(this.inputRow),this.inputContainer.appendChild(this.chatboxWrapper);const e=this.isRichTextInput(this.chatInput)?this.chatInput.getInputElement():this.chatInput;return this.mentionDropdown=new Xe(e,this.inputContainer,this.getContentManager(),this.getToolService()),this.mentionDropdown.setContextSelectedCallback(e=>{this.activeContexts.set(e.id,e),this.isRichTextInput(this.chatInput)&&this.chatInput.setActiveContexts(this.activeContexts),this.onContextSelected&&this.onContextSelected(e)}),this.inputContainer}createContextRow(){this.contextRow=document.createElement("div"),this.contextRow.className="sage-ai-context-row",this.addContextButton=document.createElement("button");const e=document.createElement("span");e.className="sage-ai-at-icon",e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="12" height="13" viewBox="0 0 12 13" fill="none">\n <g clip-path="url(#clip0_590_6942)">\n <path d="M8.00001 4.5V7C8.00001 7.39783 8.15804 7.77936 8.43935 8.06066C8.72065 8.34197 9.10218 8.5 9.50001 8.5C9.89783 8.5 10.2794 8.34197 10.5607 8.06066C10.842 7.77936 11 7.39783 11 7V6.5C11 5.37366 10.6197 4.2803 9.92071 3.39709C9.22172 2.51387 8.24499 1.89254 7.14877 1.63376C6.05255 1.37498 4.90107 1.49391 3.88089 1.97128C2.86071 2.44865 2.03159 3.2565 1.52787 4.26394C1.02415 5.27137 0.875344 6.41937 1.10556 7.52194C1.33577 8.62452 1.93151 9.61706 2.79627 10.3388C3.66102 11.0605 4.74413 11.4691 5.87009 11.4983C6.99606 11.5276 8.09893 11.1758 9.00001 10.5M8 6.5C8 7.60457 7.10457 8.5 6 8.5C4.89543 8.5 4 7.60457 4 6.5C4 5.39543 4.89543 4.5 6 4.5C7.10457 4.5 8 5.39543 8 6.5Z" stroke="#949494" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>\n </g>\n <defs>\n <clipPath id="clip0_590_6942">\n <rect width="12" height="12" fill="white" transform="translate(0 0.5)"/>\n </clipPath>\n </defs>\n</svg>';const t=document.createElement("p");t.className="sage-ai-context-text",t.textContent="Add Context",this.addContextButton.className="sage-ai-add-context-button",this.addContextButton.appendChild(e),this.addContextButton.appendChild(t),this.addContextButton.title="Add context",this.addContextButton.type="button",this.addContextButton.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),this.chatInput.focus();const t=this.getInputValue(),n=this.getSelectionStart(),o=t.slice(0,n)+"@"+t.slice(n);this.setInputValue(o),setTimeout(()=>{this.setSelectionRange(n+1,n+1);const e=new Event("input",{bubbles:!0});(this.isRichTextInput(this.chatInput)?this.chatInput.getInputElement():this.chatInput).dispatchEvent(e)},0)}),this.contextDisplay=document.createElement("div"),this.contextDisplay.className="sage-ai-context-display-inline",this.contextRow.appendChild(this.addContextButton),this.contextRow.appendChild(this.contextDisplay)}createInputRow(){this.inputRow=document.createElement("div"),this.inputRow.className="sage-ai-input-row",this.isRichTextInput(this.chatInput)?this.inputRow.appendChild(this.chatInput.getElement()):this.inputRow.appendChild(this.chatInput),this.createSendButton(),this.createModeSelector(),this.inputRow.appendChild(this.sendButton),this.inputRow.appendChild(this.modeSelector)}createSendButton(){this.sendButton=document.createElement("button"),D.render(this.sendButton),this.sendButton.className="sage-ai-send-button disabled",this.sendButton.style.position="absolute",this.sendButton.style.bottom="12px",this.sendButton.style.right="12px",this.sendButton.addEventListener("click",()=>{this.isProcessingMessage?this.cancelMessage&&this.cancelMessage():""!==this.getInputValue().trim()&&this.sendMessage()});const e=()=>{const e=""!==this.getInputValue().trim();this.isProcessingMessage||e?(this.sendButton.classList.add("enabled"),this.sendButton.classList.remove("disabled"),this.sendButton.disabled=!1):(this.sendButton.classList.remove("enabled"),this.sendButton.classList.add("disabled"),this.sendButton.disabled=!0)};this.sendButton.disabled=!0,this.chatInput.addEventListener("input",e),this.chatInput.addEventListener("keyup",e),this.chatInput.addEventListener("paste",()=>{setTimeout(e,0)})}createModeSelector(){this.modeSelector=document.createElement("div"),this.modeSelector.className="sage-ai-mode-selector",this.modeSelector.title="Select chat mode",this.modeSelectorDropdown=document.createElement("div"),this.modeSelectorDropdown.className="sage-ai-mode-dropdown hidden";const e=document.createElement("div");e.className="sage-ai-mode-dropdown-content";const t=this.createModeOption("agent","Agent",x.svgstr,"Prepare datasets. Build models. Test ideas."),n=this.createModeOption("ask","Ask",I.svgstr,"Ask Sage about your notebook or your data."),o=this.createModeOption("fast","Hands-on",M.svgstr,"Manually decide what gets added to the context.");e.appendChild(t),e.appendChild(n),e.appendChild(o),this.modeSelectorDropdown.append(e),this.updateModeSelectorDisplay("agent"),this.modeSelector.addEventListener("click",e=>{e.stopPropagation(),"true"!==this.modeSelector.getAttribute("data-is-disabled")&&this.toggleModeDropdown()}),document.addEventListener("click",()=>{this.closeModeDropdown()})}createModeOption(e,t,n,o){const s=document.createElement("div");s.className="sage-ai-mode-option",s.setAttribute("data-mode",e);const i=document.createElement("div");i.className="sage-ai-mode-option-icon",i.innerHTML=n;const a=document.createElement("div");a.className="sage-ai-mode-option-text";const r=document.createElement("div");r.className="sage-ai-mode-option-title",r.textContent=t;const l=document.createElement("div");return l.className="sage-ai-mode-option-description",l.textContent=o,a.appendChild(r),a.appendChild(l),s.appendChild(i),s.appendChild(a),s.addEventListener("click",t=>{t.stopPropagation(),this.selectMode(e),this.closeModeDropdown()}),s}toggleModeDropdown(){this.modeSelectorDropdown.classList.contains("hidden")?this.openModeDropdown():this.closeModeDropdown()}openModeDropdown(){if(!this.modeSelector||!this.modeSelectorDropdown)return;this.modeSelector.classList.add("open");const e=this.modeSelector.getBoundingClientRect();this.modeSelectorDropdown.style.position="absolute",this.modeSelectorDropdown.style.bottom=window.innerHeight-e.top+8+"px",this.modeSelectorDropdown.style.left=`${e.left}px`,this.modeSelectorDropdown.style.minWidth=`${e.width}px`,document.body.appendChild(this.modeSelectorDropdown),this.modeSelectorDropdown.classList.remove("hidden"),this.modeSelectorDropdown.classList.add("opening"),requestAnimationFrame(()=>{var e;null===(e=this.modeSelectorDropdown)||void 0===e||e.classList.add("visible")}),setTimeout(()=>{var e;null===(e=this.modeSelectorDropdown)||void 0===e||e.classList.remove("opening")},300)}closeModeDropdown(){this.modeSelector&&this.modeSelectorDropdown&&(this.modeSelector.classList.remove("open"),this.modeSelectorDropdown.classList.add("closing"),this.modeSelectorDropdown.classList.remove("visible"),setTimeout(()=>{this.modeSelectorDropdown&&(this.modeSelectorDropdown.classList.add("hidden"),this.modeSelectorDropdown.classList.remove("closing"),this.modeSelectorDropdown.parentNode===document.body&&document.body.removeChild(this.modeSelectorDropdown))},200))}selectMode(e){var t;this.modeName=e,this.updateModeSelectorDisplay(e),null===(t=this.onModeSelected)||void 0===t||t.call(this,e)}updateModeSelectorDisplay(e){const t=this.modeSelectorDropdown.querySelector(`[data-mode="${e}"]`);if(t){this.modeSelector.innerHTML="";const n=document.createElement("div");n.className="sage-ai-mode-display";const o=document.createElement("div");o.className="sage-ai-mode-option-icon",o.innerHTML=E.svgstr,n.appendChild(o);const s=t.querySelector(".sage-ai-mode-option-text");if(s){const e=s.querySelector(".sage-ai-mode-option-title");if(e){const t=document.createElement("div");t.className="sage-ai-mode-option-text",t.innerHTML=e.innerHTML,n.appendChild(t)}}const i=document.createElement("div");i.className="sage-ai-mode-selector-arrow",N.render(i),this.modeSelector.appendChild(n),this.modeSelector.appendChild(i),this.modeSelector.setAttribute("data-mode",e)}}getInputContainer(){return this.inputContainer}getSendButton(){return this.sendButton}getModeSelector(){return this.modeSelector}getContextDisplay(){return this.contextDisplay}getContentManager(){return this.contentManager}getToolService(){return this.toolService}}class tt{constructor(e,t,n){this.isShowingConfirmation=!1,this.chatHistory=e,this.messageComponent=t,this.llmStateDisplay=n}setShowingConfirmation(e){this.isShowingConfirmation=e}resetToGeneratingState(e="Generating..."){this.llmStateDisplay.show(e)}updateLoadingIndicator(e="Generating..."){this.isShowingConfirmation?this.llmStateDisplay.hide():this.llmStateDisplay.isDiffState()||this.llmStateDisplay.isUsingToolState()||this.llmStateDisplay.show(e)}removeLoadingIndicator(){}hideLoadingIndicator(){this.llmStateDisplay.hide()}updateSendButton(e,t){t?(T.render(e),e.className="sage-ai-cancel-button"):(D.render(e),e.className="sage-ai-send-button")}disableSendButton(e){e.classList.add("disabled"),e.classList.remove("enabled"),e.disabled=!0}updateAgentModeElement(e,t){t?(e.style.opacity="0.5",e.style.cursor="not-allowed",e.setAttribute("data-is-disabled","true")):(e.style.opacity="1",e.style.cursor="pointer",e.removeAttribute("data-is-disabled"))}}class nt{constructor(e,t,n){this.messageComponent=e,this.inputManager=t,this.chatboxNode=n,this.contextService=O.ContextService.getInstance(),this.subscribeToContextChanges()}onCellAddedToContext(e){const t=m.AppStateService.getNotebookContextManager();if(!t)return void console.error("Required services not initialized: contextManager is null");if(m.AppStateService.getCurrentNotebookId()!==e)return void console.error("Cell context notebook ID mismatch");const n=t.getContextCells(e);this.updateContextCellsIndicator(n.length)}onCellRemovedFromContext(e){const t=m.AppStateService.getNotebookContextManager();if(!t)return void console.error("Required services not initialized: contextManager is null");if(m.AppStateService.getCurrentNotebookId()!==e)return void console.error("Cell context notebook ID mismatch");const n=t.getContextCells(e);this.updateContextCellsIndicator(n.length)}updateContextDisplay(){let e=this.chatboxNode.querySelector(".sage-ai-context-display-inline");if(!e)return void console.warn("Context display container not found");const t=this.chatboxNode.querySelector(".sage-ai-context-row");e.innerHTML="";const n=m.AppStateService.getCurrentNotebookId(),o=m.AppStateService.getNotebookContextManager(),s=n&&o?o.getContextCells(n):[],i=Array.from(this.messageComponent.getMentionContexts().values());if(s.length+i.length>0){e.classList.remove("hidden"),t&&t.classList.remove("context-row-hidden");const a=document.createElement("div");a.className="sage-ai-context-items-inline";for(const e of s){const t=document.createElement("div");t.className="sage-ai-context-cell-box-inline",t.title=e.content||"Empty cell";const s=document.createElement("span");s.className="sage-ai-context-cell-delete",s.textContent="×",s.title="Remove from context",s.addEventListener("click",t=>{var s;if(t.stopPropagation(),n&&o){o.removeCellFromContext(n,e.cellId),this.updateContextDisplay(),this.onCellRemovedFromContext(n);const t=null===(s=m.AppStateService.getNotebookTools().getCurrentNotebook())||void 0===s?void 0:s.widget;t&&m.AppStateService.getContextCellHighlighter().addContextButtonsToAllCells(t)}}),t.appendChild(s);const i=document.createElement("span");i.textContent=e.cellId,t.appendChild(i),a.appendChild(t)}for(const e of i){const t=document.createElement("div");t.className="sage-ai-context-cell-box-inline",t.title=e.description||e.content||`${e.type}: ${e.name}`;let n="#4a5568";switch(e.type){case"snippets":n="rgba(156, 39, 176, 0.2)";break;case"data":n="rgba(33, 150, 243, 0.2)";break;case"variable":n="rgba(76, 175, 80, 0.2)";break;case"cell":n="rgba(255, 152, 0, 0.2)";break;default:n="#4a5568"}t.style.backgroundColor=`${n}`,t.style.color="var(--jp-ui-font-color0)";const o=document.createElement("span");o.className="sage-ai-context-cell-delete",o.textContent="×",o.title="Remove from context",o.addEventListener("click",t=>{if(t.stopPropagation(),this.messageComponent.removeMentionContext(e.id),this.updateContextDisplay(),this.inputManager){const t=this.inputManager.getCurrentInputValue(),n=e.name.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),o=t.replace(new RegExp(`@\\{?${n}\\}?`,"g"),"").trim();this.inputManager.setInputValue(o)}}),t.appendChild(o);const s=document.createElement("span");s.textContent=e.name,t.appendChild(s),a.appendChild(t)}e.appendChild(a)}}updateContextCellsIndicator(e){this.updateContextDisplay()}getMentionContexts(){return Array.from(this.messageComponent.getMentionContexts().values()).map(e=>({name:e.name,content:e.content||"",type:e.type,description:e.description}))}clearMentionContexts(){this.messageComponent.setMentionContexts(new Map),this.updateContextDisplay()}getCurrentContextMessage(){let e="The user's message has the following provided context:\n\n";const t=this.messageComponent.getMentionContexts();for(const[n,o]of t.entries())console.log(n),console.log(o),e+=`@${o.name} (ID: ${o.id}) described as: ${o.description} has the following content: \n${o.content}\n\n`;return e.trim()}subscribeToContextChanges(){this.contextService.subscribe(()=>{this.updateContextDisplay()})}}class ot extends Ne.Widget{constructor(e,t){super(),this.callbacks=e,this.recommendedPrompts=t,this.addClass("sage-ai-new-chat-display"),this.node.style.height="100%",this.buildContent()}buildContent(){const e=document.createElement("div");e.className="sage-ai-new-chat-container";const t=document.createElement("div");t.className="sage-ai-new-chat-title-section";const n=document.createElement("h2");n.className="sage-ai-new-chat-title",n.textContent="New Chat";const o=document.createElement("p");o.className="sage-ai-new-chat-help",o.textContent="How can I help you?",t.appendChild(n),t.appendChild(o);const s=document.createElement("div");s.className="sage-ai-new-chat-prompts-section";const i=document.createElement("div");i.className="sage-ai-new-chat-prompts-list",this.recommendedPrompts.forEach(e=>{const t=document.createElement("button");t.className="sage-ai-new-chat-prompt-button",t.textContent=e,t.addEventListener("click",()=>{this.callbacks.onPromptSelected(e),this.callbacks.onRemoveDisplay()}),i.appendChild(t)}),s.appendChild(i),e.appendChild(t),e.appendChild(s),this.node.appendChild(e)}}function st({isVisible:e,onRenameChat:t,onDeleteChat:n,onClose:o}){return e?oe.createElement("div",{className:"sage-ai-more-options-popover"},oe.createElement("div",{className:"sage-ai-more-options-content"},oe.createElement("button",{className:"sage-ai-more-options-item",onClick:()=>{t(),o()},type:"button"},oe.createElement("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg"},oe.createElement("path",{d:"M11.3333 2L14 4.66667L5.66667 13H3V10.3333L11.3333 2Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})),oe.createElement("span",null,"Rename Chat")),oe.createElement("button",{className:"sage-ai-more-options-item sage-ai-more-options-item-danger",onClick:()=>{n(),o()},type:"button"},oe.createElement("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg"},oe.createElement("path",{d:"M2 4H14M12.6667 4V13.3333C12.6667 13.6869 12.5262 14.0261 12.2761 14.2761C12.0261 14.5262 11.6869 14.6667 11.3333 14.6667H4.66667C4.31304 14.6667 3.97391 14.5262 3.72386 14.2761C3.47381 14.0261 3.33333 13.6869 3.33333 13.3333V4M5.33333 4V2.66667C5.33333 2.31304 5.47381 1.97391 5.72386 1.72386C5.97391 1.47381 6.31304 1.33333 6.66667 1.33333H9.33333C9.68696 1.33333 10.0261 1.47381 10.2761 1.72386C10.5262 1.97391 10.6667 2.31304 10.6667 2.66667V4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})),oe.createElement("span",null,"Delete Chat")))):oe.createElement("div",{className:"sage-ai-more-options-popover"})}class it extends _.ReactWidget{constructor(e){super(),this._stateChanged=new se.Signal(this),this._actions=e,this._state={isVisible:!1,anchorElement:void 0},this.addClass("sage-ai-more-options-widget"),this.setupOutsideClickHandler()}get stateChanged(){return this._stateChanged}render(){return oe.createElement(st,{isVisible:this._state.isVisible,onRenameChat:this._actions.onRenameChat,onDeleteChat:this._actions.onDeleteChat,onClose:()=>this.hide()})}showPopover(e){this._state={isVisible:!0,anchorElement:e},this._stateChanged.emit(this._state),this.update(),this.positionPopover(e)}hide(){this._state={isVisible:!1,anchorElement:void 0},this._stateChanged.emit(this._state),this.update()}positionPopover(e){const t=this.node.querySelector(".sage-ai-more-options-popover");if(t){let n=e.offsetParent;n||(n=document.body);let o=e.offsetTop,s=e.offsetLeft,i=e.offsetParent;for(;i&&i!==n;)o+=i.offsetTop,s+=i.offsetLeft,i=i.offsetParent;const a=t.style.visibility,r=t.style.display;t.style.visibility="hidden",t.style.display="block";const l=t.offsetHeight,c=t.offsetWidth;t.style.visibility=a,t.style.display=r;const d=e.offsetHeight,h=e.offsetWidth;let u=o-l-8,p=s;p+c>(n.offsetWidth||window.innerWidth)-8&&(p=s+h-c),p<8&&(p=8),u<8&&(u=o+d+8),t.style.position="absolute",t.style.top=u-22+"px",t.style.left=`${p}px`,t.style.transform="none",t.style.zIndex="9999"}}setupOutsideClickHandler(){const e=e=>{this._state.isVisible&&!this.node.contains(e.target)&&this._state.anchorElement&&!this._state.anchorElement.contains(e.target)&&this.hide()};document.addEventListener("click",e),this.disposed.connect(()=>{document.removeEventListener("click",e)})}getIsVisible(){return this._state.isVisible}getState(){return{...this._state}}}function at({isVisible:e,currentVersion:t,latestVersion:n,isUpdating:o,isMajorUpdate:s=!1,onUpdate:i,onAskLater:a,onDecline:r}){if(!e)return null;const l=!o&&!s;return oe.createElement("div",{className:"sage-ai-update-banner"},oe.createElement("div",{className:"sage-ai-update-banner-content"},oe.createElement("div",{className:"sage-ai-update-banner-icon"},oe.createElement("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},oe.createElement("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z",fill:"currentColor"}))),oe.createElement("div",{className:"sage-ai-update-banner-text"},oe.createElement("div",{className:"sage-ai-update-banner-title"},s?"Sage is auto-updating to a major version":"Sage needs to update"),t&&n&&oe.createElement("div",{className:"sage-ai-update-banner-version"},"v",t," → v",n,s&&" (Major Version)"),s&&oe.createElement("div",{className:"sage-ai-update-banner-description"},"Major version updates are applied automatically for important improvements and security fixes.")),l&&oe.createElement("div",{className:"sage-ai-update-banner-actions"},oe.createElement("button",{className:"sage-ai-update-banner-button sage-ai-update-banner-button-update",onClick:i,disabled:o},o?"Updating...":"Update"),oe.createElement("button",{className:"sage-ai-update-banner-button sage-ai-update-banner-button-later",onClick:a,disabled:o},"Ask Me Later"),oe.createElement("button",{className:"sage-ai-update-banner-button sage-ai-update-banner-button-decline",onClick:r,disabled:o},"Decline")),(o||s)&&oe.createElement("div",{className:"sage-ai-update-banner-progress"},oe.createElement("div",{className:"sage-ai-update-banner-spinner"}),oe.createElement("span",null,o?"Updating...":"Preparing update..."))))}class rt extends _.ReactWidget{constructor(e){super(),this._stateChanged=new se.Signal(this),this._packageName="sage-agent-internal",this._checkInterval=null,this.handleUpdate=async()=>{this._state={...this._state,isUpdating:!0},this._stateChanged.emit(this._state),this.update();try{const e=this._extensions.installed.find(e=>e.name===this._packageName);e&&(console.log(`Updating ${this._packageName} to version ${e.latest_version}`),await this._extensions.install(e,{useVersion:e.latest_version}),this._state={...this._state,isVisible:!1,isUpdating:!1},this._stateChanged.emit(this._state),this.updateDisplayState(),this.update(),console.log(`Successfully updated ${this._packageName} to version ${e.latest_version}`))}catch(e){console.error("Failed to update:",e),this._state={...this._state,isUpdating:!1},this._stateChanged.emit(this._state),this.updateDisplayState(),this.update()}},this.handleAskLater=()=>{this._state={...this._state,isVisible:!1},this._stateChanged.emit(this._state),this.updateDisplayState(),this.update()},this.handleDecline=async()=>{this._state.latestVersion&&await this.setDeclinedStatus(!0,this._state.latestVersion),this._state={...this._state,isVisible:!1,isDeclined:!0},this._stateChanged.emit(this._state),this.updateDisplayState(),this.update()},this._extensions=e,this._state={isVisible:!1,isUpdating:!1,isDeclined:!1,isMajorUpdate:!1},this.addClass("sage-ai-update-banner-widget"),this.node.style.display="none",this.initializeWidget()}async initializeWidget(){try{this.checkForUpdates()}catch(e){console.error("Failed to initialize UpdateBannerWidget:",e),this.checkForUpdates()}}get stateChanged(){return this._stateChanged}async getDeclinedStatus(){try{return await ie.getStringSetting(re,""),!1}catch(e){return!1}}async isVersionDeclined(e){try{return await ie.getStringSetting(re,"")===e}catch(e){return!1}}async setDeclinedStatus(e,t){try{e&&t?await ie.setStringSetting(re,t):await ie.removeSetting(re)}catch(e){}}parseVersion(e){const t=e.match(/^(\d+)\.(\d+)\.(\d+)/);return t?{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}:null}isMajorVersionChange(e,t){const n=this.parseVersion(e),o=this.parseVersion(t);return!(!n||!o)&&o.major>n.major}async checkForUpdates(){try{await this._extensions.refreshInstalled(!0);const e=this._extensions.installed.find(e=>e.name===this._packageName);if(e&&e.installed_version!==e.latest_version){const t=e.installed_version,n=e.latest_version;if(await this.isVersionDeclined(n))return void console.log(`Version ${n} has been declined, not showing banner`);if(this.isMajorVersionChange(t,n))return console.log(`Major version change detected: ${t} → ${n}. Auto-updating...`),this._state={...this._state,isVisible:!0,isUpdating:!0,isMajorUpdate:!0,currentVersion:t,latestVersion:n,isDeclined:!1},this._stateChanged.emit(this._state),this.updateDisplayState(),this.update(),void await this.handleUpdate();this._state={...this._state,isVisible:!0,isMajorUpdate:!1,currentVersion:t,latestVersion:n,isDeclined:!1},this._stateChanged.emit(this._state),this.updateDisplayState(),this.update()}}catch(e){console.error("Failed to check for updates:",e)}}updateDisplayState(){this.node.style.display=this._state.isVisible?"block":"none"}showBanner(){this.checkForUpdates()}render(){return oe.createElement(at,{isVisible:this._state.isVisible,currentVersion:this._state.currentVersion,latestVersion:this._state.latestVersion,isUpdating:this._state.isUpdating,isMajorUpdate:this._state.isMajorUpdate,onUpdate:this.handleUpdate,onAskLater:this.handleAskLater,onDecline:this.handleDecline})}dispose(){this._checkInterval&&(clearInterval(this._checkInterval),this._checkInterval=null),super.dispose()}}var lt=n(927);const ct=[];class dt extends Ne.Widget{constructor(e){var t,n,o;super(),this.lastNotebookId=null,this.historyWidget=null,this.newChatDisplayWidget=null,this.updateBanner=null,this.currentServiceProvider=Te.ServiceProvider.ANTHROPIC,this.id="sage-ai-chat",this.title.label="AI Chat",this.title.closable=!0,this.addClass("sage-ai-chatbox"),this.chatHistoryManager=new Le,this.chatService=Te.ServiceFactory.createService(this.currentServiceProvider),m.AppStateService.setChatService(this.chatService);const s=new Ne.PanelLayout;this.layout=s;const i=document.createElement("div");i.className="sage-ai-toolbar",this.threadSelectorButton=document.createElement("button"),this.threadSelectorButton.className="sage-ai-icon-button-md sage-ai-thread-selector-button",this.threadSelectorButton.innerHTML='\n <svg width="20" height="21" viewBox="0 0 20 21" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M2.5 10.5H17.5M2.5 5.5H17.5M2.5 15.5H17.5" stroke="#949494" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ',this.threadSelectorButton.title="Select conversation thread",i.appendChild(this.threadSelectorButton),this.threadNameDisplay=document.createElement("span"),this.threadNameDisplay.className="sage-ai-thread-name",this.threadNameDisplay.textContent=(null===(t=this.chatHistoryManager.getCurrentThread())||void 0===t?void 0:t.name)||"New Chat",i.appendChild(this.threadNameDisplay);const a=document.createElement("div");a.className="sage-ai-checkbox-container sage-ai-autorun-toggle sage-ai-control-base",this.autorunCheckbox=document.createElement("input"),this.autorunCheckbox.id="sage-ai-autorun",this.autorunCheckbox.type="checkbox",this.autorunCheckbox.className="sage-ai-checkbox sage-ai-toggle-input",this.autorunCheckbox.title="Automatically run code without confirmation";const r=document.createElement("label");r.htmlFor="sage-ai-autorun",r.className="sage-ai-checkbox-label sage-ai-toggle-label",r.innerHTML='\n <span class="sage-ai-toggle-switch"></span>\n Auto Run\n ',r.title="Automatically run code without confirmation",a.appendChild(this.autorunCheckbox),a.appendChild(r),this.newChatButton=document.createElement("button"),this.newChatButton.className="sage-ai-reset-button sage-ai-control-base",this.newChatButton.innerHTML='\n <svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M3.3335 8.49992H12.6668M8.00016 3.83325V13.1666" stroke="var(--jp-ui-font-color0)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ',this.newChatButton.title="Start a new chat",this.newChatButton.addEventListener("click",()=>this.createNewChat()),this.undoButton=document.createElement("button"),this.undoButton.className="sage-ai-undo-button sage-ai-control-base",this.undoButton.innerHTML='\n <svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M5.99984 9.83341L2.6665 6.50008M2.6665 6.50008L5.99984 3.16675M2.6665 6.50008H9.6665C10.148 6.50008 10.6248 6.59492 11.0697 6.77919C11.5145 6.96346 11.9187 7.23354 12.2592 7.57402C12.5997 7.9145 12.8698 8.31871 13.0541 8.76357C13.2383 9.20844 13.3332 9.68523 13.3332 10.1667C13.3332 10.6483 13.2383 11.1251 13.0541 11.5699C12.8698 12.0148 12.5997 12.419 12.2592 12.7595C11.9187 13.1 11.5145 13.37 11.0697 13.5543C10.6248 13.7386 10.148 13.8334 9.6665 13.8334H7.33317" stroke="var(--jp-ui-font-color0)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ',this.undoButton.disabled=!0,this.undoButton.title="No action to undo",this.undoButton.addEventListener("click",()=>this.undoLastAction());const l=document.createElement("button");l.className="sage-ai-more-options-button sage-ai-icon-button-md",l.innerHTML='\n <svg width="18" height="19" viewBox="0 0 18 19" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M9 10.25C9.41421 10.25 9.75 9.91421 9.75 9.5C9.75 9.08579 9.41421 8.75 9 8.75C8.58579 8.75 8.25 9.08579 8.25 9.5C8.25 9.91421 8.58579 10.25 9 10.25Z" stroke="var(--jp-ui-font-color0)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M14.25 10.25C14.6642 10.25 15 9.91421 15 9.5C15 9.08579 14.6642 8.75 14.25 8.75C13.8358 8.75 13.5 9.08579 13.5 9.5C13.5 9.91421 13.8358 10.25 14.25 10.25Z" stroke="var(--jp-ui-font-color0)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M3.75 10.25C4.16421 10.25 4.5 9.91421 4.5 9.5C4.5 9.08579 4.16421 8.75 3.75 8.75C3.33579 8.75 3 9.08579 3 9.5C3 9.91421 3.33579 10.25 3.75 10.25Z" stroke="var(--jp-ui-font-color0)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ',l.title="More options",l.addEventListener("click",()=>this.showMoreOptions()),i.appendChild(a),i.appendChild(this.newChatButton),i.appendChild(l);const c=document.createElement("div");c.className="sage-ai-history-container",this.chatHistory=document.createElement("div"),this.chatHistory.className="sage-ai-chat-history",this.chatHistory.setAttribute("data-is-scrolled-to-bottom","true"),c.appendChild(this.chatHistory),this.scrollDownButton=document.createElement("button"),this.scrollDownButton.className="sage-ai-scroll-down-button hidden",this.scrollDownButton.innerHTML='\n <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M8 10.25L12.5 5.75L13.25 6.5L8 11.75L2.75 6.5L3.5 5.75L8 10.25Z" fill="var(--jp-ui-font-color1" />\n </svg>\n ',this.scrollDownButton.addEventListener("click",()=>{this.messageComponent.scrollToBottom(),this.hideScrollDownButton()}),c.appendChild(this.scrollDownButton),new ResizeObserver(()=>this.handleChatHistoryResize()).observe(this.chatHistory);let d=!1,h=null;["wheel","touchstart","keydown"].forEach(e=>{window.addEventListener(e,()=>{d=!0,h&&clearTimeout(h),h=setTimeout(()=>{d=!1},1e3)})}),this.chatHistory.addEventListener("scroll",()=>{d&&(this.updateScrollAttribute()?this.hideScrollDownButton():this.showScrollDownButton())}),this.historyWidget=new Ne.Widget({node:c}),this.llmStateDisplay=m.AppStateService.getLlmStateDisplay(),this.planStateDisplay=m.AppStateService.getPlanStateDisplay(),this.moreOptionsDisplay=new it({onRenameChat:()=>this.handleRenameChat(),onDeleteChat:()=>this.handleDeleteChat()}),this.messageComponent=new Y(this.chatHistory,this.chatHistoryManager,m.AppStateService.getNotebookTools(),()=>this.handleDisplayScrollDownButton()),this.chatInput=new Qe("What would you like me to generate or analyze?"),this.chatInput.addEventListener("keydown",e=>{const t=e;"Enter"!==t.key||t.shiftKey||""===this.chatInput.getPlainText().trim()||this.inputManager.getIsProcessingMessage()||(t.preventDefault(),this.inputManager.sendMessage())});const u=document.createElement("div");u.className="sage-ai-new-prompt-cta";const p=document.createElement("p");p.textContent="Want to start a new prompt?";const g=document.createElement("a");g.textContent="Create a New Chat",g.onclick=()=>(this.createNewChat(),!1),u.appendChild(p),u.appendChild(g),this.hideNewChatCta(),this.newChatDisplayWidget=new ot({onPromptSelected:e=>{this.inputManager.setInputValue(e),this.inputManager.sendMessage(),this.showHistoryWidget()},onRemoveDisplay:()=>{this.showHistoryWidget()}},ct);const f=m.AppStateService.getExtensions();f&&(this.updateBanner=new rt(f),this.updateBanner.showBanner()),s.addWidget(new Ne.Widget({node:i})),s.addWidget(this.historyWidget),s.addWidget(this.newChatDisplayWidget),document.body.appendChild((null===(n=this.updateBanner)||void 0===n?void 0:n.node)||document.createElement("div")),this.showHistoryWidget(),null===(o=this.updateBanner)||void 0===o||o.checkForUpdates(),this.inputManager=new et(this.chatInput,this.chatHistoryManager,m.AppStateService.getContentManager(),m.AppStateService.getToolService(),e=>{this.messageComponent.addMentionContext(e),this.contextHandler.updateContextDisplay(),console.log("Context added:",e)},e=>{this.messageComponent.removeMentionContext(e),this.contextHandler.updateContextDisplay(),console.log(`Context removed: ${e}`)},()=>this.createNewChat(),e=>{if(this.chatService instanceof lt.A&&"fast"===e){const e=this.chatService.getToolBlacklist();this.messageComponent.addSystemMessage(`Hands-on mode enabled. Using optimized prompt and limiting certain tools: ${e.join(", ")}`)}const t="agent"===e?"Agent":"ask"===e?"Ask":"Hands-on";this.messageComponent.addSystemMessage(`Mode switched to: ${t}`)});const v=this.inputManager.createInputContainer(),C=new Ne.Widget({node:this.inputManager.getInputContainer()}),b=document.createElement("div");b.className="sage-ai-state-display-container",b.style.position="fixed",b.style.bottom="0",b.style.left="0",b.style.right="0",b.style.pointerEvents="none",b.style.zIndex="1",b.style.display="flex",b.style.flexDirection="column",b.style.alignItems="stretch";const y=this.planStateDisplay.getWidget().node,k=this.llmStateDisplay.getWidget().node,w=document.createElement("div");w.className="sage-ai-input-spacer",w.style.order="3",w.style.flexShrink="0";const S=()=>{const e=v.offsetHeight,t="none"===u.style.display?29:0;w.style.height=e-t+16+"px",requestAnimationFrame(()=>{setTimeout(()=>{let e=0;!this.llmStateDisplay.node.classList.contains("hidden")&&this.llmStateDisplay.node.offsetHeight>0&&(e+=this.llmStateDisplay.node.offsetHeight-10),this.planStateDisplay.getIsVisible()&&this.planStateDisplay.node.offsetHeight>0&&(e+=this.planStateDisplay.node.offsetHeight-20),e>0&&(e+=10);const t=this.chatHistory.parentElement;t&&(t.style.paddingBottom=`${e}px`);const n=null==t?void 0:t.querySelector(".sage-ai-scroll-down-button");if(n){const t=e?e-6:0;n.style.bottom=`${t}px`}this.handleDisplayScrollDownButton()},200)})};this.updateStateDisplayPositions=S,this.planStateConnection=this.planStateDisplay.stateChanged.connect(()=>{setTimeout(S,100)}),setTimeout(S,100),this.resizeObserver=new ResizeObserver(S),this.resizeObserver.observe(v),this.mutationObserver=new MutationObserver(()=>{setTimeout(S,100)}),this.mutationObserver.observe(this.llmStateDisplay.node,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class"]}),this.mutationObserver.observe(this.planStateDisplay.node,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class"]}),b.appendChild(y),b.appendChild(k),b.appendChild(w),s.addWidget(C),s.addWidget(new Ne.Widget({node:b})),s.addWidget(new Ne.Widget({node:u})),s.addWidget(this.moreOptionsDisplay),this.threadManager=new Re(this.chatHistoryManager,this.messageComponent,this.chatService,this.threadNameDisplay,this.node),this.uiHelper=new tt(this.chatHistory,this.messageComponent,this.llmStateDisplay),this.contextHandler=new nt(this.messageComponent,this.inputManager,this.node),this.conversationService=new Ie(this.chatService,m.AppStateService.getToolService(),m.AppStateService.getContentManager(),this.messageComponent,this.chatHistory,e,{updateLoadingIndicator:e=>this.updateLoadingIndicator(e),removeLoadingIndicator:()=>this.removeLoadingIndicator(),hideLoadingIndicator:()=>this.llmStateDisplay.hide()});const _=m.AppStateService.getState().notebookDiffManager;_&&this.conversationService.setDiffManager(_),this.setupEventHandlers(),this.initializeServices(),this.subscribeToAppStateChanges(),this.inputManager.setDependencies({chatService:this.chatService,conversationService:this.conversationService,messageComponent:this.messageComponent,uiHelper:this.uiHelper,contextHandler:this.contextHandler,sendButton:this.inputManager.getSendButton(),modeSelector:this.inputManager.getModeSelector(),cancelMessage:()=>this.cancelMessage(),onMessageSent:()=>this.showHistoryWidget()}),setInterval(()=>this.updateUndoButtonState(),1e3);const x=m.AppStateService.getWaitingUserReplyBoxManager();x.initialize(this.chatHistory),x.setContinueCallback(()=>{this.sendContinueMessage()}),x.setPromptCallback(e=>{this.sendPromptMessage(e)}),this.contextHandler.updateContextDisplay(),0===this.messageComponent.getMessageHistory().length&&this.showNewChatDisplay()}handleDisplayScrollDownButton(){this.isScrolledToBottom()?this.hideScrollDownButton():this.showScrollDownButton()}showScrollDownButton(){this.scrollDownButton.classList.remove("hidden")}hideScrollDownButton(){this.scrollDownButton.classList.add("hidden")}handleChatHistoryResize(){this.isScrolledToBottom()?this.scrollChatHistoryToBottom():this.handleDisplayScrollDownButton()}scrollChatHistoryToBottom(){this.chatHistory.scrollTop=this.chatHistory.scrollHeight}updateScrollAttribute(){const e=this.chatHistory.scrollTop,t=this.chatHistory.scrollHeight,n=Math.ceil(e+this.chatHistory.clientHeight)>=t;return this.chatHistory.setAttribute("data-is-scrolled-to-bottom",n.toString()),n}isScrolledToBottom(){return"true"===this.chatHistory.getAttribute("data-is-scrolled-to-bottom")}updateNotebookId(e){m.AppStateService.setCurrentNotebookId(e),this.threadManager.updateNotebookId(e),this.conversationService.updateNotebookId(e)}updateNotebookPath(e){this.updateNotebookId(e)}setupEventHandlers(){this.threadSelectorButton.addEventListener("click",()=>{this.threadManager.openBanner()}),this.autorunCheckbox.addEventListener("change",()=>{this.conversationService.setAutoRun(this.autorunCheckbox.checked),this.autorunCheckbox.checked?this.messageComponent.addSystemMessage("Auto-run mode enabled. Code will execute automatically without confirmation."):this.messageComponent.addSystemMessage("Auto-run mode disabled. You will be prompted for code execution.")})}async initializeServices(){try{m.AppStateService.setConfig(await De.w.getConfig());const e=await this.chatService.initialize();console.log("Chat service initialized:",e),e&&this.chatService.getModelName();const t=m.AppStateService.getToolService();await t.initialize(),console.log("Connected to MCP server successfully."),console.log(`Loaded ${t.getTools().length} tools from MCP server.`);const{PlanGenerationService:o}=await n.e(950).then(n.bind(n,8950));await o.initialize(),console.log("Plan generation service initialized.")}catch(e){console.error("Failed to connect to MCP server:",e),this.messageComponent.addSystemMessage("❌ Failed to connect to MCP server. Some features may not work.")}}async setNotebookId(e){if(!e)return m.AppStateService.setCurrentNotebookId(null),void this.threadManager.setNotebookId(null);if(this.lastNotebookId===e)return;this.lastNotebookId=e,m.AppStateService.setCurrentNotebookId(e),this.threadManager.setNotebookId(e),await this.showNewChatDisplayOrHistory(),this.conversationService.setNotebookId(e),await this.restoreLastThreadForNotebook(e),this.inputManager.loadUserMessageHistory();const t=m.AppStateService.getState().notebookContextManager;if(t){const n=t.getContextCells(e);this.contextHandler.updateContextCellsIndicator(n.length)}}async restoreLastThreadForNotebook(e){try{const t=await this.threadManager.getLastValidThreadForNotebook(e);return t&&t.messages.length>0?(console.log(`[ChatBoxWidget] Restoring last thread: ${t.name} for notebook ${e}`),void await this.showHistoryWidgetFromThread(t)):(console.log(`[ChatBoxWidget] No valid last thread found for notebook ${e}, showing default view`),await this.createNewChat(),void this.showNewChatDisplay())}catch(t){console.warn(`[ChatBoxWidget] Failed to restore last thread for notebook ${e}:`,t),await this.showNewChatDisplayOrHistory()}}async createNewChat(){if(m.AppStateService.getWaitingUserReplyBoxManager().hide(),m.AppStateService.getCurrentNotebookId()){if(this.inputManager.getIsProcessingMessage()?this.cancelMessage():this.chatService.cancelRequest(),await this.threadManager.createNewThread()){this.conversationService.clearActionHistory(),this.updateUndoButtonState(),this.contextHandler.updateContextDisplay(),this.showNewChatDisplay(),this.llmStateDisplay.hide();const e=m.AppStateService.getDiffNavigationWidgetSafe();e&&e.hidePendingDiffs()}}else this.messageComponent.addSystemMessage("Please open a notebook first.")}updateUndoButtonState(){if(this.conversationService.canUndo()){const e=this.conversationService.getLastActionDescription();this.undoButton.disabled=!1,this.undoButton.title=`Undo: ${e}`}else this.undoButton.disabled=!0,this.undoButton.title="No action to undo"}async undoLastAction(){if(this.conversationService.canUndo()){this.undoButton.disabled=!0,this.undoButton.title="Undoing...";try{await this.conversationService.undoLastAction()}catch(e){console.error("Error during undo:",e),this.messageComponent.addErrorMessage(`Error during undo: ${e instanceof Error?e.message:"Unknown error"}`)}finally{this.updateUndoButtonState()}}}cancelMessage(){if(!this.inputManager.getIsProcessingMessage())return;console.log("Cancelling message..."),console.log(this.inputManager.getIsProcessingMessage()),this.chatService.cancelRequest(),this.inputManager.setIsProcessingMessage(!1),this.uiHelper.removeLoadingIndicator(),this.messageComponent.removeLoadingText(),this.uiHelper.updateSendButton(this.inputManager.getSendButton(),!1),this.uiHelper.disableSendButton(this.inputManager.getSendButton()),m.AppStateService.getPlanStateDisplay().setLoading(!1),this.uiHelper.updateAgentModeElement(this.inputManager.getModeSelector(),!1);const e=m.AppStateService.getState().notebookDiffManager;if(e&&e.hasPendingDiffs()&&!e.isDialogOpen()){if(this.llmStateDisplay){const e=m.AppStateService.getCurrentNotebookId();this.llmStateDisplay.showPendingDiffs(e);const t=m.AppStateService.getDiffNavigationWidgetSafe();t&&t.showPendingDiffs(e)}setTimeout(async()=>{const t=m.AppStateService.getCurrentNotebookId();await(null==e?void 0:e.showCancellationApprovalDialog(this.chatHistory,t))},100)}else this.llmStateDisplay.show(),this.llmStateDisplay.hide()}onAfterShow(){this.inputManager.focus()}updateLoadingIndicator(e="Generating..."){this.uiHelper.updateLoadingIndicator(e)}removeLoadingIndicator(){this.uiHelper.removeLoadingIndicator()}onCellAddedToContext(e){this.contextHandler.onCellAddedToContext(e)}onCellRemovedFromContext(e){this.contextHandler.onCellRemovedFromContext(e)}async showNewChatDisplayOrHistory(){const e=this.chatHistoryManager.getCurrentThread();e&&e.messages.length>0?await this.showHistoryWidgetFromThread(e):this.showNewChatDisplay()}showNewChatCta(){const e=this.node.querySelector(".sage-ai-new-prompt-cta");e&&(e.style.display="flex")}hideNewChatCta(){const e=this.node.querySelector(".sage-ai-new-prompt-cta");e&&(e.style.display="none")}showNewChatDisplay(){this.messageComponent.getMessageHistory().length>0||(this.newChatDisplayWidget&&(this.newChatDisplayWidget.node.style.display="flex"),this.historyWidget&&(this.historyWidget.node.style.display="none"),this.hideNewChatCta())}showHistoryWidget(){this.newChatDisplayWidget&&(this.newChatDisplayWidget.node.style.display="none"),this.historyWidget&&(this.historyWidget.node.style.display="block"),this.showNewChatCta()}async showHistoryWidgetFromThread(e){await this.threadManager.selectThread(e.id),this.showHistoryWidget()}showMoreOptions(){const e=this.node.querySelector(".sage-ai-more-options-button");e&&this.moreOptionsDisplay&&this.moreOptionsDisplay.showPopover(e)}async handleRenameChat(){const e=this.chatHistoryManager.getCurrentThread();if(!e)return void this.messageComponent.addSystemMessage("No active chat to rename.");const t=prompt("Enter new chat name:",e.name);t&&""!==t.trim()&&t!==e.name&&(this.chatHistoryManager.renameCurrentThread(t.trim())?(this.threadNameDisplay.textContent=t.trim(),this.messageComponent.addSystemMessage(`Chat renamed to: ${t.trim()}`)):this.messageComponent.addSystemMessage("Failed to rename chat."))}async handleDeleteChat(){const e=this.chatHistoryManager.getCurrentThread();if(e){if(confirm(`Are you sure you want to delete the chat "${e.name}"? This action cannot be undone.`)){const t=e.name;if(this.chatHistoryManager.deleteThread(e.id)){this.messageComponent.addSystemMessage(`Chat "${t}" has been deleted.`);const e=this.chatHistoryManager.getCurrentThread();e?(this.threadNameDisplay.textContent=e.name,await this.messageComponent.loadFromThread(e),e.messages.length>0?this.showHistoryWidget():this.showNewChatDisplay()):this.showNewChatDisplay()}else this.messageComponent.addSystemMessage("Failed to delete chat.")}}else this.messageComponent.addSystemMessage("No active chat to delete.")}subscribeToAppStateChanges(){const e=m.AppStateService.getClaudeSettings();this.lastClaudeSettings={claudeApiKey:e.claudeApiKey,claudeModelId:e.claudeModelId,claudeModelUrl:e.claudeModelUrl},this.appStateSubscription=m.AppStateService.changes.subscribe(e=>{const t={claudeApiKey:e.settings.claudeApiKey,claudeModelId:e.settings.claudeModelId,claudeModelUrl:e.settings.claudeModelUrl};(!this.lastClaudeSettings||this.lastClaudeSettings.claudeApiKey!==t.claudeApiKey||this.lastClaudeSettings.claudeModelId!==t.claudeModelId||this.lastClaudeSettings.claudeModelUrl!==t.claudeModelUrl)&&(console.log("Claude settings changed, re-initializing chat service...",{previous:this.lastClaudeSettings,current:t}),this.lastClaudeSettings=t,this.reinitializeChatService())})}async reinitializeChatService(){try{console.log("Re-initializing chat service with updated Claude settings...");const e=await this.chatService.initialize();console.log("Chat service re-initialized:",e),e?this.chatService.getModelName():this.messageComponent.addSystemMessage("⚠️ Failed to re-initialize with updated settings. Please check your API key.")}catch(e){console.error("Failed to re-initialize chat service:",e),this.messageComponent.addSystemMessage("⚠️ Error updating settings. Please try again.")}}sendContinueMessage(){this.inputManager.setInputValue("Continue"),this.inputManager.sendMessage(),this.messageComponent.hideWaitingReplyBox()}sendPromptMessage(e){this.inputManager.setInputValue(e),this.inputManager.sendMessage(),this.messageComponent.hideWaitingReplyBox()}getMessageComponent(){return this.messageComponent}dispose(){var e,t,n,o,s,i,a;null===(e=this.resizeObserver)||void 0===e||e.disconnect(),null===(t=this.mutationObserver)||void 0===t||t.disconnect(),null===(n=this.llmStateConnection)||void 0===n||n.dispose(),null===(o=this.planStateConnection)||void 0===o||o.dispose(),null===(s=this.moreOptionsDisplay)||void 0===s||s.dispose(),null===(i=this.updateBanner)||void 0===i||i.dispose(),null===(a=this.appStateSubscription)||void 0===a||a.unsubscribe(),super.dispose()}}function ht(e){return new Promise(t=>setTimeout(t,e))}class ut{get finishedProcessingDiffs(){return this._finishedProcessingDiffs}constructor(e,t){this.cellIdMapping=new Map,this.notebookWidget=null,this.lastUserApprovalTime=0,this._shouldRunImmediately=!1,this._shouldExecuteApprovedCells=!1,this.currentNotebookId=null,this.subscriptions=[],this._finishedProcessingDiffs=new se.Signal(this),this.notebookTools=e,this.actionHistory=t,this.diffApprovalDialog=new $,this.setupDiffStateSubscriptions(),this.diffApprovalDialog.setCallbacks({onApprove:e=>this.approveDiffs(e),onReject:e=>this.rejectDiffs(e),onApproveAll:e=>this.approveAllDiffs(e),onRejectAll:e=>this.rejectAllDiffs(e),applyApprovedDiffs:(...e)=>this.applyApprovedDiffs(...e),handleRejectedDiffs:e=>this.handleRejectedDiffs(e),setExecuteApprovedCells:e=>this.setExecuteApprovedCells(e),reapplyDiff:e=>this.reapplyDiff(e)})}setupDiffStateSubscriptions(){this.subscriptions.push(C.diffState$.subscribe(e=>{e.notebookId!==this.currentNotebookId&&(this.currentNotebookId=e.notebookId||null)}))}dispose(){this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[]}setNotebookWidget(e){this.notebookWidget=e}setNotebookId(e){this.currentNotebookId!==e&&(console.log(`[NotebookDiffManager] Setting current notebook ID: ${e}`),this.currentNotebookId=e,C.setNotebookPath(e),this.diffApprovalDialog.updateNotebookPath(e||""))}getNotebookDiffs(e){const t=C.getCurrentState();return e?Array.from(t.pendingDiffs.values()).filter(t=>t.notebookId===e):Array.from(t.pendingDiffs.values())}get approvalStatus(){const e=C.getCurrentState();let t=0,n=0,s=0;for(const[,o]of e.pendingDiffs)this.currentNotebookId&&o.notebookId!==this.currentNotebookId||(s++,!0===o.approved||"approved"===o.userDecision||"run"===o.userDecision?t++:!1!==o.approved&&"rejected"!==o.userDecision||n++);return 0===s?o.fY.PENDING:t===s?o.fY.APPROVED:n===s?o.fY.REJECTED:t+n===s?o.fY.PARTIAL:o.fY.PENDING}trackAddCell(e,t,n,o){const s=o||this.currentNotebookId,i={cellId:e,type:"add",newContent:t,updatedCellId:e,metadata:{summary:n},notebookId:s};C.addPendingDiff(e,i),console.log(`[NotebookDiffManager] Tracked add diff for cell tracking ID ${e} in notebook ${s||"current"}`)}trackEditCell(e,t,n,o,s){const i=s||this.currentNotebookId,a={cellId:e,type:"edit",originalContent:t,newContent:n,updatedCellId:e,metadata:{summary:o},notebookId:i};C.addPendingDiff(e,a),console.log(`[NotebookDiffManager] Tracked edit diff for cell tracking ID ${e} in notebook ${i||"current"}`)}trackRemoveCell(e,t,n,o){const s=o||this.currentNotebookId,i={cellId:e,type:"remove",originalContent:t,newContent:"",metadata:{summary:n},notebookId:s};C.addPendingDiff(e,i),console.log(`[NotebookDiffManager] Tracked remove diff for cell tracking ID ${e} in notebook ${s||"current"}`)}updateCellIdMapping(e,t,n){this.cellIdMapping.set(e,t);const o=C.getCurrentState().pendingDiffs.get(e);if(o){const n={...o,updatedCellId:t};C.addPendingDiff(e,n),console.log(`[NotebookDiffManager] Updated cell ID mapping: ${e} → ${t}`)}}getCurrentCellId(e){return this.cellIdMapping.get(e)||e}isDialogOpen(){return this.diffApprovalDialog.isDialogOpen()}hasPendingDiffs(){return C.getPendingDiffCount(this.currentNotebookId)>0}hasRejectedDiffs(){for(const e of C.getCurrentState().pendingDiffs.values())if(e.userDecision&&"rejected"===e.userDecision)return!0;return!1}getPendingDiffCount(){return C.getPendingDiffCount(this.currentNotebookId)}async showApprovalDialog(e,t=!1,n=!1,s){console.log("[NotebookDiffManager] Showing approval dialog for current notebook"),console.log(`[NotebookDiffManager] Notebook ID: ${s||this.currentNotebookId}`);const i=void 0!==s?s:this.currentNotebookId,a=this.getNotebookDiffs(i);if(console.log(a),0===a.length){console.log("[NotebookDiffManager] No diffs to approve for target notebook");const e=o.fY.APPROVED;return this._finishedProcessingDiffs.emit(e),e}await this.displayDiffsInCells(i);const r=this.notebookWidget?this.notebookWidget.node:document.body,l=t?e:r;return console.log("[NotebookDiffManager] Showing Dialog"),(await this.diffApprovalDialog.showDialog(l,i,t,n)).runImmediately&&(this._shouldRunImmediately=!0,this._shouldExecuteApprovedCells=!0),this.approvalStatus}async showCancellationApprovalDialog(e,t){const n=t||this.currentNotebookId;if(0===this.getNotebookDiffs(n).length){const e=o.fY.APPROVED;return this._finishedProcessingDiffs.emit(e),e}await this.displayDiffsInCells(n),this.notebookWidget?this.notebookWidget.node:document.body;const s=e,i=(await this.diffApprovalDialog.showDialog(s,n,!0,!1),this.approvalStatus);return this._finishedProcessingDiffs.emit(i),i}async displayDiffsInCells(e){const t=e||this.currentNotebookId,n=this.getNotebookDiffs(t);for(const e of n)if(await ht(200),!e.updatedCellId||e.updatedCellId===e.cellId)try{const n=this.notebookTools.findCellByAnyId(e.cellId,t);if(!n){console.warn(`Cannot find cell with tracking ID ${e.cellId} in notebook ${t||"current"} to display diff`);continue}"add"===e.type?this.notebookTools.display_diff(n.cell,"",e.newContent||"","add"):"edit"===e.type?this.notebookTools.display_diff(n.cell,e.originalContent||"",e.newContent||"","edit"):"remove"===e.type&&this.notebookTools.display_diff(n.cell,e.originalContent||"","","remove")}catch(n){console.error(`Error displaying diff for cell ${e.cellId} in notebook ${t}:`,n)}}approveDiffs(e){const t=C.getCurrentState();for(const n of e){const e=t.pendingDiffs.get(n);e&&C.updateDiffState(n,!0,e.notebookId)}}rejectDiffs(e){const t=C.getCurrentState();for(const n of e){const e=t.pendingDiffs.get(n);e&&C.updateDiffState(n,!1,e.notebookId)}}approveAllDiffs(e=null){const t=this.getNotebookDiffs(e);for(const e of t)C.updateDiffState(e.cellId,!0,e.notebookId)}rejectAllDiffs(e=null){const t=this.getNotebookDiffs(e);for(const e of t)"approved"!==e.userDecision&&"run"!==e.userDecision&&C.updateDiffState(e.cellId,!1,e.notebookId)}rejectCellDiff(e){const t=C.getCurrentState().pendingDiffs.get(e);t&&!1!==t.approved&&(C.updateDiffState(e,!1,t.notebookId),this.handleRejectedDiffs(t.notebookId))}reapplyDiff(e){var t;if("edit"!==e.type)return;C.addPendingDiff(e.cellId,{...e,approved:void 0,userDecision:void 0}),this.displayDiffsInCells(e.notebookId);const n=null===(t=m.AppStateService.getChatContainerSafe())||void 0===t?void 0:t.chatWidget.llmStateDisplay;n&&n.showPendingDiffs(e.notebookId,!0);const o=m.AppStateService.getDiffNavigationWidgetSafe();o&&o.showPendingDiffs(e.notebookId,!0)}async applyApprovedDiffs(e,t){const n=e||this.currentNotebookId,o=this.getNotebookDiffs(n).filter(e=>!0===e.approved);console.log(`[NotebookDiffManager] Applying ${o.length} approved diffs in notebook ${n||"current"}`);try{for(const e of o){await ht(100);const o=e.cellId;if(e.updatedCellId!==e.cellId&&e.updatedCellId,t&&!t.includes(o))continue;console.log("Searching for cell with tracking ID:",o);let s=this.notebookTools.findCellByAnyId(o,n);if(s)if("add"===e.type||"edit"===e.type){if(!this.notebookTools.apply_diff(s.cell,!0).success){console.error(`[NotebookDiffManager] Failed to apply diff to cell with tracking ID ${o}`);continue}}else"remove"===e.type&&this.notebookTools.remove_cells({cell_ids:[o],remove_from_notebook:!0,save_checkpoint:!0});else console.error(`[NotebookDiffManager] Cannot find cell with tracking ID ${o} in notebook ${n||"current"} to apply diff`)}return{success:!0,status:this.approvalStatus}}catch(e){return console.error("Error applying approved diffs:",e),{success:!1,status:this.approvalStatus}}}async handleRejectedDiffs(e){const t=e||this.currentNotebookId,n=this.getNotebookDiffs(t).filter(e=>!1===e.approved);console.log(`[NotebookDiffManager] Handling ${n.length} rejected diffs in notebook ${t||"current"}`);try{for(const e of n){const n=e.cellId,o=e.updatedCellId!==e.cellId?e.updatedCellId:void 0;let s=this.notebookTools.findCellByAnyId(n,t);!s&&o&&(s=this.notebookTools.findCellByAnyId(o)),s?"add"===e.type?this.notebookTools.remove_cells({cell_ids:[n],remove_from_notebook:!0}):("edit"===e.type||"remove"===e.type)&&(this.notebookTools.apply_diff(s.cell,!1)||console.error(`[NotebookDiffManager] Failed to reject diff for cell with tracking ID ${n}`)):console.error(`[NotebookDiffManager] Cannot find cell with tracking ID ${n} in notebook ${t||"current"} to reject diff`)}return{success:!0,status:this.approvalStatus}}catch(e){return console.error("Error handling rejected diffs:",e),{success:!1,status:this.approvalStatus}}}approveCellDiff(e){const t=C.getCurrentState().pendingDiffs.get(e);t&&!t.approved&&(C.updateDiffState(e,!0,t.notebookId),this.applyApprovedDiffs(t.notebookId))}clearDiffs(){this.cellIdMapping.clear(),C.clearAllDiffs(this.currentNotebookId),console.log("[NotebookDiffManager] All diffs cleared")}rejectAndRevertDiffsImmediately(){this.rejectAllDiffs(),this.handleRejectedDiffs()}shouldRunImmediately(){const e=this._shouldRunImmediately;return this._shouldRunImmediately=!1,e}getApprovedCellIds(e){const t=e||this.currentNotebookId;return this.getNotebookDiffs(t).filter(e=>e.userDecision&&"rejected"!==e.userDecision&&("add"===e.type||"edit"===e.type)).map(e=>e.cellId)}setExecuteApprovedCells(e){this._shouldExecuteApprovedCells=e}waitForDiffProcessingComplete(){return new Promise(e=>{const t=(n,o)=>{this._finishedProcessingDiffs.disconnect(t),e(o)};this._finishedProcessingDiffs.connect(t)})}startDiffApprovalProcess(e,t=!1,n=!1,s){this.showApprovalDialog(e,t,n,s).catch(e=>{console.error("[NotebookDiffManager] Error during diff approval:",e),this._finishedProcessingDiffs.emit(o.fY.REJECTED)})}}n(6378);var pt=n(5010),gt=n(1436),mt=n(932),ft=n(1336),vt=(n(9864),n(693),n(6828)),Ct=n(1771);class bt{constructor(e){this.isAutoScrollDisabled=!1,this.lastAutoScrolledCell=null,this.scrollListeners=new Map,this.notebookTools=e}async run_cell(e){var t;let n=null;if(console.log("RUNNING CELL - CELL ID:",e.cell_id,"NOTEBOOK PATH:",e.notebook_path),n=this.notebookTools.findCellByAnyId(e.cell_id,e.notebook_path),console.log("Cell info:",n),!n)throw new Error(`Cell with ID ${e.cell_id} not found in notebook ${e.notebook_path||"current"}`);const o=this.notebookTools.getCurrentNotebook(e.notebook_path);if(!o)throw new Error(`Notebook ${e.notebook_path||"current"} not found`);const{notebook:s}=o,{cell:i}=n;if("markdown"===i.model.type)return[i.model.sharedModel.getSource()];if("code"!==i.model.type)throw new Error(`Cell with ID ${e.cell_id} is not a code cell`);this.notebookTools.activateCell(i);const a=bt.preventScrolling(s);await X.NotebookActions.runCells(s,[i],null===(t=o.widget)||void 0===t?void 0:t.sessionContext),a();const r=[];try{const e=i;if(e.outputArea&&e.outputArea.model.toJSON){const t=e.outputArea.model.toJSON();for(const e of t)if("stream"===e.output_type){const t=()=>Array.isArray(e.text)?e.text.join(""):e.text;if("stderr"===e.name){r.push({error:!0,errorText:t()});continue}r.push(t())}else"execute_result"===e.output_type||"display_data"===e.output_type?e.data&&e.data["text/plain"]&&(Array.isArray(e.data["text/plain"])?r.push(e.data["text/plain"].join("")):r.push(e.data["text/plain"])):"error"===e.output_type&&(r.push({error:!0,errorText:`Error: ${e.ename}: ${e.evalue}`}),Array.isArray(e.traceback)?r.push({error:!0,errorText:e.traceback.join("\n")}):e.traceback&&r.push({error:!0,errorText:e.traceback}))}}catch(e){console.error("Error collecting cell outputs:",e),r.push(`Error collecting outputs: ${e}`)}return this.handleSmartScroll(i.node,!0),r}add_cell(e){var t;const n=null===(t=this.notebookTools.getCurrentNotebook(e.notebook_path))||void 0===t?void 0:t.notebook;if(!n)throw new Error(`Notebook ${e.notebook_path||"current"} not found`);console.log(`Adding cell of type ${e.cell_type} at position ${e.position} in notebook ${e.notebook_path||"current"}`);const o=e.source||"";let s;null!==e.position&&void 0!==e.position?(s=e.position,s=Math.min(Math.max(s,0),n.widgets.length)):s=n.widgets.length;const i=bt.preventScrolling(n);0===s?(this.notebookTools.activateCellByIndex(s),X.NotebookActions.insertAbove(n)):(this.notebookTools.activateCellByIndex(s-1),X.NotebookActions.insertBelow(n)),i();let a=n.activeCell;if(!a)throw new Error("Failed to create new cell");if("markdown"===e.cell_type&&"markdown"!==a.model.type?X.NotebookActions.changeCellType(n,"markdown"):"code"===e.cell_type&&"code"!==a.model.type&&X.NotebookActions.changeCellType(n,"code"),a=n.activeCell,!a)throw new Error("Failed to set active cell after insertion");const r=a.model.sharedModel.getMetadata()||{},l=(new Date).toISOString();r.cell_tracker={trackingId:e.tracking_id||this.generateTrackingId(n),createdAt:l,lastModified:l,origin:"ai",summary:e.summary||""},r.custom||(r.custom={}),r.custom.summary=e.summary,a.model.sharedModel.setMetadata(r),e.show_diff?this.notebookTools.display_diff(a,"",o,"add"):a.model.sharedModel.setSource(o),e.run_cell&&X.NotebookActions.runCells(n,[a]);const c=a.model.sharedModel.getMetadata().cell_tracker;return this.handleSmartScroll(a.node),c.trackingId}isPlanCell(e){var t,n,o;return"plan"===(null===(o=((null===(n=null===(t=null==e?void 0:e.model)||void 0===t?void 0:t.sharedModel)||void 0===n?void 0:n.getMetadata())||{}).custom)||void 0===o?void 0:o.sage_cell_type)}setFirstCellAsPlan(e){let t=this.notebookTools.getCurrentNotebook(e);if(!t)return;let{notebook:n}=t;if(this.findPlanCell(n))return;let o=n.widgets[0];if(!o)return void console.error("Could not find first cell to ensure it is a plan cell");X.NotebookActions.changeCellType(n,"markdown"),t=this.notebookTools.getCurrentNotebook(e),t&&t.notebook&&(n=t.notebook),o=n.widgets[0];const s=o.model.sharedModel.getMetadata()||{};s.custom||(s.custom={}),s.cell_tracker||(s.cell_tracker={}),s.cell_tracker.trackingId="planning_cell",s.custom.sage_cell_type="plan",o.model.sharedModel.setMetadata(s),o.model.sharedModel.setSource("")}findPlanCell(e){return e.widgets.find(e=>this.isPlanCell(e))||null}generateTrackingId(e){var t;let n=1;const o=e.widgets;for(let e=0;e<o.length;e++){const s=null===(t=(o[e].model.sharedModel.getMetadata()||{}).cell_tracker)||void 0===t?void 0:t.trackingId;if(s&&/^cell_(\d+)$/.test(s)){const e=parseInt(s.split("_")[1],10);e>n&&(n=e)}}return`cell_${n}`}remove_cells(e){var t,n,o,s;e.cell_ids.every(e=>e.startsWith("cell_"));const i=this.notebookTools.getCurrentNotebook(e.notebook_path);if(!i)return!1;const{notebook:a}=i;let r=0;for(const i of e.cell_ids){let l=this.notebookTools.findCellByAnyId(i,e.notebook_path);if(l){const c=l.cell.model.sharedModel.getMetadata()||{};if(!1===(null===(t=c.custom)||void 0===t?void 0:t.deletable)){console.warn(`Cannot delete non-deletable cell: ${i}`);continue}const d=c.cell_tracker,h=null==d?void 0:d.trackingId,u=null===(o=null===(n=c.custom)||void 0===n?void 0:n.diff)||void 0===o?void 0:o.originalContent;e.remove_from_notebook&&(this.notebookTools.activateCell(l.cell),X.NotebookActions.deleteCells(a),console.log(`[NotebookCellTools] Cell ${h} removed permanently from the notebook`),e.save_checkpoint&&(null===(s=m.AppStateService.getState().actionHistory)||void 0===s||s.addActionWithCheckpoint(Z.REMOVE_CELLS,{cellId:i,oldContent:u,metadata:c},`Removed cell ${i.substring(0,8)}...`))),r++}}return r>0}edit_cell(e){var t,n;let o=null;if(o=this.notebookTools.findCellByAnyId(e.cell_id,e.notebook_path),!o)return console.error(`Cell not found with ID: ${e.cell_id} in notebook ${e.notebook_path||"current"}`),!1;const s=this.notebookTools.getCurrentNotebook(e.notebook_path);if(!s)return!1;const{notebook:i}=s,{cell:a}=o,r=a.model.sharedModel.getMetadata()||{};if(!1===(null===(t=r.custom)||void 0===t?void 0:t.editable))return console.warn(`Cannot edit non-editable cell: ${e.cell_id}`),!1;const l=a.model.sharedModel.getSource(),c=(null===(n=r.cell_tracker)||void 0===n?void 0:n.trackingId)||this.generateTrackingId(i);if(this.notebookTools.activateCell(a),r.cell_tracker)r.cell_tracker.lastModified=(new Date).toISOString(),r.cell_tracker.summary=e.summary||r.cell_tracker.summary;else{const t=(new Date).toISOString();r.cell_tracker={trackingId:c,createdAt:t,lastModified:t,origin:"ai",summary:e.summary||""}}return r.custom||(r.custom={}),r.custom.summary=e.summary,a.model.sharedModel.setMetadata(r),e.show_diff?this.notebookTools.display_diff(a,l,e.new_source,"edit"):a.model.sharedModel.setSource(e.new_source),this.handleSmartScroll(a.node),!0}stream_edit_plan(e){const t=this.notebookTools.getCurrentNotebook(e.notebook_path);if(!t)return!1;const{notebook:n}=t;let o=null;for(let e=0;e<n.widgets.length;e++){const t=n.widgets[e];this.isPlanCell(t)&&(o=t)}if(!o){console.error("No first cell found for plan update"),n.activeCellIndex=0;const t=bt.preventScrolling(n);X.NotebookActions.insertAbove(n),t(),n.activeCellIndex=0,this.setFirstCellAsPlan(e.notebook_path)}const s=n.widgets[0],i=e.partial_plan;return s.model.sharedModel.setSource(i),!0}async edit_plan(e){var t;const o=this.notebookTools.getCurrentNotebook(e.notebook_path);if(!o)return console.error("No notebook found for edit_plan"),"";const{notebook:s}=o,i=s.activeCellIndex;let a="";const r=s.widgets[0];r&&(a=r.model.sharedModel.getSource());const l=await this.notebookTools.getNotebookSummary(e.notebook_path||null),c=JSON.stringify(l,null,2);let d=!0,h=null;if(!r||!this.isPlanCell(r)){d=!1,s.activeCellIndex=0;const t=bt.preventScrolling(s);X.NotebookActions.insertAbove(s),t(),s.activeCellIndex=0,this.setFirstCellAsPlan(e.notebook_path)}const u=s.widgets[0];d&&(h=JSON.parse(JSON.stringify(u.model.sharedModel.getMetadata()||{})));const p=u.model.sharedModel.getMetadata()||{},g=(null===(t=p.cell_tracker)||void 0===t?void 0:t.trackingId)||"planning_cell";if(this.notebookTools.activateCell(u),p.cell_tracker)p.cell_tracker.lastModified=(new Date).toISOString(),p.cell_tracker.summary="Updating plan...";else{const e=(new Date).toISOString();p.cell_tracker={trackingId:g,createdAt:e,lastModified:e,origin:"ai",summary:"Updating plan..."}}p.custom||(p.custom={}),p.custom.summary="Updating plan...",u.model.sharedModel.setMetadata(p);let f="";const v=`## Notebook Summary\n${c}\n\n## Current Plan\n${a||"No existing plan"}\n\n## Immediate Action\n${e.immediate_action}\n\nGenerate an updated plan based on this context.`;try{const t=m.AppStateService.getChatService(),o=t.getModelName(),i=n(9147),r=(await t.sendEphemeralMessage(v,i,o,e=>{f+=e,u.model.sharedModel.setSource(f),this.handleSmartScroll(u.node)},{maxTokens:2048},void 0,"chat")).trim();u.model.sharedModel.setSource(r);const l=m.AppStateService.getState().actionHistory;null==l||l.addActionWithCheckpoint(Z.EDIT_PLAN,{planExisted:d,oldPlan:a,newContent:r,oldCurrentStep:p.custom.current_step_string||"",oldNextStep:p.custom.next_step_string||""},"Updated plan"),p.cell_tracker&&(p.cell_tracker.lastModified=(new Date).toISOString(),p.cell_tracker.summary="Plan updated"),p.custom.summary="Plan updated",u.model.sharedModel.setMetadata(p);const c=bt.preventScrolling(s);X.NotebookActions.runCells(s,[u]),c();const{currentStep:h,nextStep:g}=this.extractStepsFromPlan(r,e.immediate_action);return p.custom.current_step_string=h,p.custom.next_step_string=g,u.model.sharedModel.setMetadata(p),m.AppStateService.getPlanStateDisplay().updatePlan(h||"",g,r),console.log("Plan cell updated successfully with streaming"),r}catch(e){console.error("[NotebookCellTools] Failed to generate plan:",e);try{if(d){const e=s.widgets[0];e&&(e.model.sharedModel.setSource(a),h&&e.model.sharedModel.setMetadata(h)),s.activeCellIndex=i}else{const e=bt.preventScrolling(s);s.activeCellIndex=0,X.NotebookActions.deleteCells(s),s.activeCellIndex=i,e()}}catch(e){console.error("[NotebookCellTools] Failed to restore initial state after plan generation error:",e)}return{error:!0,errorText:e instanceof Error?e.message:String(e)}}}extractStepsFromPlan(e,t){var n,o;const s=e.split("\n"),i=[];for(const e of s){const t=e.match(/^-\s*\[\s*([x ])\s*\]\s*(.+)$/);if(t){const e="x"===t[1],n=t[2].trim();i.push({text:n,completed:e})}}let a="",r="";const l=i.find(e=>!e.completed&&(e.text.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(e.text.toLowerCase())));if(l){a=l.text;const e=i.indexOf(l),t=i.slice(e+1).find(e=>!e.completed);r=t?t.text:""}else{const e=i.filter(e=>!e.completed);a=(null===(n=e[0])||void 0===n?void 0:n.text)||"",r=e.length>1?null===(o=e[1])||void 0===o?void 0:o.text:""}return{currentStep:a,nextStep:r}}get_cells_info(e){const t=this.notebookTools.getCurrentNotebook(e);if(!t)return null;const{notebook:n}=t,o=[];for(let e=0;e<n.widgets.length;e++){const t=n.widgets[e];o.push({id:t.model.id,type:t.model.type,content:t.model.sharedModel.getSource()})}return{cells:o}}get_cell_info(e){var t;let n=this.notebookTools.findCellByAnyId(e.cell_id,e.notebook_path);if(!n)return null;const{cell:o,index:s}=n,i=o.model.sharedModel.getMetadata();return{id:o.model.id,type:o.model.type,content:o.model.sharedModel.getSource(),index:s,custom:(null==i?void 0:i.custom)||{},trackingId:(null===(t=null==i?void 0:i.cell_tracker)||void 0===t?void 0:t.trackingId)||null}}edit_history(e){return console.log("Edit history requested with options:",e),{forwarded:!0}}read_cells(e={}){const{notebook_path:t=null,include_outputs:n=!0,include_metadata:o=!0}=e,s=this.notebookTools.getCurrentNotebook(t);if(!s)return console.log("No current notebook found"),null;const{notebook:i,widget:a}=s,r=[];console.log(`Reading ${i.widgets.length} cells from notebook`);for(let e=0;e<i.widgets.length;e++){const t=i.widgets[e],s=t.model,a=s.sharedModel,l={id:"",index:e,type:s.type,content:a.getSource()};if(o){const e=a.getMetadata();l.metadata=e||{};const t=null==e?void 0:e.cell_tracker;(null==t?void 0:t.trackingId)&&(l.trackingId=t.trackingId)}if(n&&"code"===s.type)try{const e=t;e.outputArea&&e.outputArea.model.toJSON&&(l.outputs=e.outputArea.model.toJSON());const n=s.executionCount;null!=n&&(l.execution_count=n)}catch(e){console.warn(`Failed to get outputs for cell ${l.id}:`,e),l.outputs=[]}if(l.outputs&&l.outputs.length>0)for(const e of l.outputs)e.text&&e.text.length>5e3&&(e.text=e.text.slice(0,5e3)),"display_data"===e.output_type&&e.data&&(e.data=e.data["text/plain"]);r.push(l)}const l={cells:r,total_cells:r.length,notebook_path:a.context.path};return console.log(`Successfully read ${r.length} cells from notebook`),console.log(l),l}handleSmartScroll(e,t=!1){if(this.isAutoScrollDisabled)return void console.log("Auto-scroll disabled due to user interaction");const n=e.closest(".jp-WindowedPanel-outer");if(!n)return void console.warn("Could not find scroll container with class jp-WindowedPanel-outer");const o=e.querySelector(".jp-InputArea");if(!o)return void console.warn("Could not find cell input area");let s=o;if(t){const t=e.querySelector(".jp-OutputArea");t&&t.children.length>0&&(s=t)}this.setupScrollListener(n,e);const i=n.getBoundingClientRect(),a=s.getBoundingClientRect().bottom-i.top+n.scrollTop-n.clientHeight+20;a<=n.scrollTop?console.log("Skipping scroll - target is above current position or user is already below target"):(this.lastAutoScrolledCell=e,n.scrollTo({top:Math.max(0,a),behavior:"smooth"}),console.log("Smart scrolled to cell content bottom with 20px padding"))}setupScrollListener(e,t){const n=this.scrollListeners.get(e);n&&e.removeEventListener("scroll",n);let o=null,s=Date.now(),i=!0;const a=()=>{const n=Date.now();i&&n-s<1e3||(i=!1,o&&clearTimeout(o),o=setTimeout(()=>{this.checkUserScrolledAway(e,t)},100))};setTimeout(()=>{i=!1,s=Date.now()},100),e.addEventListener("scroll",a,{passive:!0}),this.scrollListeners.set(e,a)}checkUserScrolledAway(e,t){const n=this.notebookTools.getCurrentNotebook();if(!n)return;const{notebook:o}=n;if(0===o.widgets.length)return;const s=o.widgets[o.widgets.length-1].node.querySelector(".jp-InputArea");if(!s)return;const i=e.scrollTop,a=e.scrollHeight,r=e.clientHeight,l=e.getBoundingClientRect(),c=a-(i+r),d=c<=10,h=s.getBoundingClientRect().bottom<=l.bottom+20,u=d||h;u&&this.isAutoScrollDisabled?(this.isAutoScrollDisabled=!1,console.log("User scrolled back to bottom, enabling auto-scroll",{isNearScrollBottom:d,isLastCellVisible:h,distanceFromBottom:c})):u||this.isAutoScrollDisabled||(this.isAutoScrollDisabled=!0,console.log("User scrolled away from bottom, disabling auto-scroll",{isNearScrollBottom:d,isLastCellVisible:h,distanceFromBottom:c}))}cleanupScrollListeners(){for(const[e,t]of this.scrollListeners)e.removeEventListener("scroll",t);this.scrollListeners.clear()}dispose(){this.cleanupScrollListeners(),this.isAutoScrollDisabled=!1,this.lastAutoScrolledCell=null}static preventScrolling(e){const t=e.scrollToCell,n=e.scrollToItem;return e.scrollToCell=()=>Promise.resolve(),e.scrollToItem=()=>Promise.resolve(),()=>{e.scrollToCell=t,e.scrollToItem=n}}}var yt=n(4353),kt=n(7332);const wt=new class{constructor(){this.activeMergeViews=new Map,this.mergeCallbacks=new Map}countMergeChunks(e){return e.querySelectorAll(".cm-chunkButtons").length}getInitialChunkCount(e){if(e.editor instanceof S.CodeMirrorEditor){const t=e.editor.editor.contentDOM;if(t)return this.countMergeChunks(t)}return 0}showInlineDiff(e,t,n,o){var s;const i=(null===(s=e.model.sharedModel.getMetadata())||void 0===s?void 0:s.cell_tracker).trackingId;console.log(`[InlineDiffService] Showing unified merge view for cell ${i}`),o&&this.mergeCallbacks.set(i,o);const a=e.editor;a&&a instanceof S.CodeMirrorEditor?(this.activeMergeViews.set(i,{cellId:i,cell:e,view:a,originalContent:t,initialChunkCount:0,acceptedChunkCount:0,rejectedChunkCount:0}),this.createUnifiedMergeView(e,t,n)):console.error("Cell editor is not a CodeMirrorEditor instance")}createUnifiedMergeView(e,t,n){var o;const s=e.node,i=e.editor,a=(null===(o=e.model.sharedModel.getMetadata())||void 0===o?void 0:o.cell_tracker).trackingId;try{const o=i.editor,r=k.StateField.define({create:()=>({lastContent:n}),update:(e,t)=>{const n=t.annotation(k.Transaction.userEvent),i=this.activeMergeViews.get(a),r=this.mergeCallbacks.get(a);if(i&&r&&n){if("accept"===n){i.acceptedChunkCount++,console.log(`[InlineDiffService] Chunk accepted in cell ${a}. Total accepted: ${i.acceptedChunkCount}`);const e=t.newDoc.toString();setTimeout(()=>{var t;return null===(t=r.onAccept)||void 0===t?void 0:t.call(r,a,e)},0)}else"revert"===n&&(i.rejectedChunkCount++,console.log(`[InlineDiffService] Chunk rejected in cell ${a}. Total rejected: ${i.rejectedChunkCount}`),setTimeout(()=>{var e;return null===(e=r.onReject)||void 0===e?void 0:e.call(r,a,i.originalContent)},0));if(i.acceptedChunkCount+i.rejectedChunkCount>=i.initialChunkCount&&i.initialChunkCount>0){const n=t.newDoc.toString();i.rejectedChunkCount===i.initialChunkCount?setTimeout(()=>{r.onRejectAll&&r.onRejectAll(a,i.originalContent)},0):i.acceptedChunkCount===i.initialChunkCount?setTimeout(()=>{r.onApproveAll&&r.onApproveAll(a,n)},0):setTimeout(()=>{r.onAllResolved&&r.onAllResolved(a,n)},0),e={...e}}}return this.hasRemainingMergeChunks(o.contentDOM)?s.classList.add("has-merge-chunks"):s.classList.remove("has-merge-chunks"),{lastContent:t.newDoc.toString()}}});if(e.model.sharedModel.setSource(t),!e.node.classList.contains("sage-ai-unified-diff-active")){const e=(0,y.unifiedMergeView)({original:t,gutter:!1,mergeControls:!0,highlightChanges:!0,syntaxHighlightDeletions:!0,allowInlineDiffs:!0,invertedEffects:yt.g_});this.extendEditorExtensions(o,[kt.minimalSetup,e,r],a),s.classList.add("sage-ai-unified-diff-active")}(0,y.applyGeneratedCode)(o,n,{replaceAll:!0}),t?e.node.classList.remove("code-mirror-empty-original-content"):e.node.classList.add("code-mirror-empty-original-content"),setTimeout(()=>{const t=this.activeMergeViews.get(a);if(t){const n=this.getInitialChunkCount(e);n>0&&e.node.classList.add("has-merge-chunks"),t.initialChunkCount=n,console.log(`[InlineDiffService] Initial chunk count for cell ${a}: ${n}`)}},100)}catch(e){console.error("Error creating unified merge view:",e)}}extendEditorExtensions(e,t,n){e.dispatch({effects:k.StateEffect.appendConfig.of(t)}),console.log("[InlineDiffService] Configured unified merge view with change tracking")}hasRemainingMergeChunks(e){const t=e.querySelectorAll(".cm-deletedChunk"),n=e.querySelectorAll(".cm-changedLine");return t.length>0||n.length>0}async acceptAllChunks(e){const t=this.activeMergeViews.get(e);if(!t)return void console.warn(`[InlineDiffService] No active merge view found for cell ${e}`);const n=t.view;if(!(n instanceof S.CodeMirrorEditor))return void console.error("[InlineDiffService] Editor is not a CodeMirrorEditor instance");const o=n.editor;for(;;){const e=o.contentDOM.querySelector(".cm-chunkButtons");if(!e)break;if(!(0,y.acceptChunk)(o,o.posAtDOM(e))){console.warn("[InlineDiffService] No acceptChunk method available");break}await new Promise(e=>setTimeout(e,10))}}async rejectAllChunks(e){const t=this.activeMergeViews.get(e);if(!t)return void console.warn(`[InlineDiffService] No active merge view found for cell ${e}`);const n=t.view;if(!(n instanceof S.CodeMirrorEditor))return void console.error("[InlineDiffService] Editor is not a CodeMirrorEditor instance");const o=n.editor;for(;;){const e=document.querySelector(".cm-chunkButtons");if(!e)break;if(!(0,y.rejectChunk)(o,o.posAtDOM(e))){console.warn("[InlineDiffService] No rejectChunks method available");break}await new Promise(e=>setTimeout(e,10))}const s=((t.cell.model.sharedModel.getMetadata()||{}).custom||{}).diff,{originalContent:i=""}=s||{},a=this.mergeCallbacks.get(e);a&&a.onRejectAll&&setTimeout(()=>{a.onRejectAll(e,i)},0)}cleanupMergeView(e){const t=this.activeMergeViews.get(e);t&&(t.cell&&t.cell.node&&(t.cell.node.classList.remove("sage-ai-unified-diff-active"),t.cell.node.classList.remove("has-merge-chunks")),this.activeMergeViews.delete(e))}};class St{static detectJupyterLabTheme(){return"false"===document.body.getAttribute("data-jp-theme-light")?vt.d7.DARK:vt.d7.LIGHT}static initializeThemeDetection(){if(!St.themeObserver)try{const e=document.body;St.themeObserver=new MutationObserver(e=>{let t=!1;e.forEach(e=>{if("attributes"===e.type){const n=e.attributeName;"data-jp-theme-light"!==n&&"data-jp-theme-name"!==n&&"class"!==n||(t=!0)}}),t&&(console.log("JupyterLab theme change detected, refreshing diff displays..."),St.onThemeChangeCallbacks.forEach(e=>{try{e()}catch(e){console.error("Error in theme change callback:",e)}}))}),St.themeObserver.observe(e,{attributes:!0,attributeFilter:["data-jp-theme-light","data-jp-theme-name","class"]}),console.log("Theme detection initialized for diff2html")}catch(e){console.error("Failed to initialize theme detection:",e)}}static onThemeChange(e){St.onThemeChangeCallbacks.push(e)}static cleanupThemeDetection(){St.themeObserver&&(St.themeObserver.disconnect(),St.themeObserver=null),St.onThemeChangeCallbacks=[]}static getCurrentTheme(){return St.detectJupyterLabTheme()}static isDarkTheme(){return St.detectJupyterLabTheme()===vt.d7.DARK}static calculateDiff(e,t){const n=e.split("\n"),o=t.split("\n"),s=[];let i=0,a=0;for(;i<n.length||a<o.length;)i>=n.length?(s.push({line:o[a],type:"added"}),a++):a>=o.length?(s.push({line:n[i],type:"removed"}),i++):n[i]===o[a]?(s.push({line:n[i],type:"unchanged"}),i++,a++):(s.push({line:n[i],type:"removed"}),s.push({line:o[a],type:"added"}),i++,a++);return s}formatDiffForConsole(e){const t="[0m";return e.map(e=>"added"===e.type?`[32m+ ${e.line}${t}`:"removed"===e.type?`[31m- ${e.line}${t}`:` ${e.line}`).join("\n")}static generateHtmlDiff(e,t,n){const o=n?["","",{context:1/0}]:[],s=z.createTwoFilesPatch("Original.py","Modified.py",e,t,...o),i=St.detectJupyterLabTheme(),a=ft.parse(s,{outputFormat:"line-by-line",matching:"lines",colorScheme:i});a.forEach(e=>{e.language="py"});const r=document.createElement("div"),l=new Ct.L(r,a,{drawFileList:!1,outputFormat:"line-by-line",matching:"lines",colorScheme:i,highlight:!0});return l.highlightCode(),l.draw(),r.innerHTML}display_diff(e,t,n,o,s){var i;try{const a=e.normalizeContent(n),r=e.normalizeContent(o),l=e.getCurrentNotebook();if(!(null==l?void 0:l.notebook))throw new Error("No active notebook found");e.activateCell(t);const c=t.model.type;this.store_diff_metadata(t,n,o,s,c);const d=null===(i=e.getCurrentNotebook())||void 0===i?void 0:i.notebook.activeCell,h={onApproveAll:e=>{console.log(`[NotebookDiffTools] Diff all approved for cell ${e}`),m.AppStateService.getNotebookDiffManager().approveCellDiff(e)},onAllResolved:e=>{console.log(`[NotebookDiffTools] Diff all resolved for cell ${e}`),m.AppStateService.getNotebookDiffManager().approveCellDiff(e)},onRejectAll:e=>{console.log(`[NotebookDiffTools] Diff all rejected for cell ${e}`),m.AppStateService.getNotebookDiffManager().rejectCellDiff(e)}};return wt.showInlineDiff(d,a,r,h),{htmlDiff:"",cell:d,cellId:d.model.id}}catch(e){throw console.error("Error displaying diff:",e),e}}static removeDiffOverlay(e){try{const t=e.node.getElementsByClassName("jp-InputArea-editor").item(0);if(t){const e=t.querySelector(".jp-DiffOverlay");e&&e.remove(),t.style.removeProperty("min-height")}}catch(e){console.error("Error removing diff overlay:",e)}}cleanupDiffMetadata(e){try{const t={...e.model.sharedModel.getMetadata()||{}};if(t.custom){const e="object"==typeof t.custom&&t.custom?{...t.custom}:{};e&&(delete e.diff,t.custom=e)}e.model.sharedModel.setMetadata(t),console.log("Cleaned up diff metadata for cell:",e.model.id)}catch(e){console.error("Error cleaning up diff metadata:",e)}}store_diff_metadata(e,t,n,o,s){try{const i=e.model.sharedModel.getMetadata()||{},a={originalContent:t,newContent:n,operation:o,originalCellType:s,timestamp:(new Date).toISOString()},r="object"==typeof i.custom&&i.custom?i.custom:{},l={...i,custom:{...r,diff:a}};e.model.sharedModel.setMetadata(l),console.log("Cell metadata after storing diff:",e.model.sharedModel.getMetadata())}catch(e){console.error("Error storing diff metadata:",e)}}apply_diff(e,t,n){var o,s,i,a,r,l,c;try{console.log("APPLYING DIFF ================================== APPLYING DIFF ============== APPYING DIFF");const d=null===(o=e.getCurrentNotebook())||void 0===o?void 0:o.notebook;e.activateCell(t);const h=null===(s=e.getCurrentNotebook())||void 0===s?void 0:s.notebook.activeCell;if("markdown"===t.model.type&&d){const e=bt.preventScrolling(d);X.NotebookActions.runCells(d,[t]),e()}const u=((h.model.sharedModel.getMetadata()||{}).custom||{}).diff;if(!u)return console.warn("No diff metadata found"),{success:!1};const{originalContent:p="",newContent:g="",operation:f="",originalCellType:v="code"}=u,C=null===(a=null===(i=h.model.sharedModel.getMetadata())||void 0===i?void 0:i.cell_tracker)||void 0===a?void 0:a.trackingId;n?"remove"!==f&&C&&wt&&wt.acceptAllChunks(C):("add"===f?h.model.sharedModel.setSource(""):h.model.sharedModel.setSource(p),C&&wt&&wt.cleanupMergeView(C)),"add"===f&&n?null===(r=m.AppStateService.getState().actionHistory)||void 0===r||r.addActionWithCheckpoint(Z.ADD_CELL,{cellId:C,...u},"Added code cell"):"edit"===f&&n&&(null===(l=m.AppStateService.getState().actionHistory)||void 0===l||l.addActionWithCheckpoint(Z.EDIT_CELL,{cellId:C,...u},`Edited cell ${C.substring(0,8)}...`));const b=null===(c=e.getCurrentNotebook())||void 0===c?void 0:c.notebook;let y=h.model.id;if(b&&h.model.type!==v){X.NotebookActions.changeCellType(b,v);const e=b.activeCell;e&&e.model.id!==y&&(y=e.model.id)}return this.cleanupDiffMetadata(h),console.log("Cell metadata after applying diff:",h.model.sharedModel.getMetadata()),{success:!0,updatedCellId:y}}catch(e){return console.error("Error applying diff:",e),{success:!1}}}logDiff(e,t,n,o,s){const i=e(t),a=e(n),r="add"===o&&""===i?a.split("\n").map(e=>({line:e,type:"added"})):St.calculateDiff(i,a);console.log(`--- DIFF for ${o}${s?` on cell ${s}`:""} ---`),console.log(this.formatDiffForConsole(r)),console.log("--- END DIFF ---")}}St.themeObserver=null,St.onThemeChangeCallbacks=[];class _t{constructor(e){this.notebookTracker=e}getNextCellNumber(e){var t;const n=e.widgets;let o=0;for(let e=0;e<n.length;e++){const s=null===(t=(n[e].model.sharedModel.getMetadata()||{}).cell_tracker)||void 0===t?void 0:t.trackingId;if(s&&/^cell_(\d+)$/.test(s)){const e=parseInt(s.split("_")[1],10);e>o&&(o=e)}}return o+1}ensureCellHasTrackingID(e){var t,n;if(!e)return"";const o=null===(t=this.notebookTracker.currentWidget)||void 0===t?void 0:t.content,s=e.model.sharedModel.getMetadata()||{};if(!s.cell_tracker||!s.cell_tracker.trackingId){const t=(new Date).toISOString(),i=`cell_${this.getNextCellNumber(o)}`;return s.cell_tracker={trackingId:i,createdAt:t,lastModified:t,origin:"user",summary:(null===(n=s.custom)||void 0===n?void 0:n.summary)||""},e.model.sharedModel.setMetadata(s),s.cell_tracker.trackingId}return s.cell_tracker.trackingId}fixTrackingIDs(e){var t;let n;if(e&&(n=m.AppStateService.getCurrentNotebook(),!n))return console.warn(`Notebook with ID ${e} not found`),0;if(!n)return 0;const o=n.content.widgets;let s=0;for(let e=0;e<o.length;e++){const i=o[e],a=i.model.sharedModel.getMetadata()||{};let r=!1;if(a.cell_tracker&&a.cell_tracker.trackingId&&("planning_cell"===a.cell_tracker.trackingId||/^cell_\d+$/.test(a.cell_tracker.trackingId))||(r=!0),r){const e=(new Date).toISOString(),o=`cell_${this.getNextCellNumber(n.content)}`;a.cell_tracker={trackingId:o,createdAt:e,lastModified:e,origin:"user",summary:(null===(t=a.custom)||void 0===t?void 0:t.summary)||""},i.model.sharedModel.setMetadata(a),s++}}return s}getTrackingIDReport(e){var t,n;let o;if(e){let t=!1;if(this.notebookTracker.forEach(n=>{n.context.path===e&&(o=n.content,t=!0)}),!t)return console.warn(`Notebook with path ${e} not found`),[]}else o=null===(t=this.notebookTracker.currentWidget)||void 0===t?void 0:t.content;if(!o)return[];const s=o.widgets,i=[],a=s.length;for(let e=0;e<a;e++){const t=s[e],o=t.model.sharedModel.getMetadata()||{};i.push({trackingId:(null===(n=o.cell_tracker)||void 0===n?void 0:n.trackingId)||"missing",modelId:t.model.id,cellType:t.model.type,index:e})}return i}}class xt{constructor(){this.dataDir="data"}async list_datasets(e){try{await this.ensureDataDirectory();const e=await m.AppStateService.getContentManager().get(this.dataDir);if("directory"!==e.type)throw new Error("Data path is not a directory");const t=e.content.filter(e=>"file"===e.type).map(e=>({name:e.name,path:e.path,size:e.size||0,modified:e.last_modified?new Date(e.last_modified).getTime()/1e3:0}));return JSON.stringify(t)}catch(e){return console.error("Error listing datasets:",e),JSON.stringify({error:`Failed to list datasets: ${e instanceof Error?e.message:String(e)}`})}}async read_dataset(e){try{const{filepath:t,start:n=0,end:o=10}=e,s=this.getSafeFilePath(t),i=await m.AppStateService.getContentManager().get(s);if("file"!==i.type)throw new Error("Path is not a file");const a=i.content.split("\n"),r=Math.max(0,n),l=Math.min(r+10,Math.min(o,a.length)),c=a.slice(r,l);return JSON.stringify({content:c,start:r,end:l,path:s,total_lines:a.length})}catch(e){return console.error("Error reading dataset:",e),JSON.stringify({error:`Failed to read dataset: ${e instanceof Error?e.message:String(e)}`})}}async delete_dataset(e){try{const{filepath:t}=e,n=this.getSafeFilePath(t);return await m.AppStateService.getContentManager().delete(n),JSON.stringify({success:!0,path:n,message:"File deleted successfully"})}catch(e){return console.error("Error deleting dataset:",e),JSON.stringify({error:`Failed to delete dataset: ${e instanceof Error?e.message:String(e)}`})}}async save_dataset(e){try{const{filepath:t,content:n}=e,o=this.getSafeFilePath(t);return await m.AppStateService.getContentManager().save(o,{type:"file",format:"text",content:n}),JSON.stringify({success:!0,path:o,message:"File saved successfully"})}catch(e){return console.error("Error saving dataset:",e),JSON.stringify({error:`Failed to save dataset: ${e instanceof Error?e.message:String(e)}`})}}async ensureDataDirectory(){try{await m.AppStateService.getContentManager().get(this.dataDir)}catch(e){console.log(`Creating data directory: ${this.dataDir}`),await m.AppStateService.getContentManager().newUntitled({type:"directory",path:""}).then(e=>m.AppStateService.getContentManager().rename(e.path,this.dataDir))}}getSafeFilePath(e){const t=e.replace(/\.\./g,"").replace(/^\/+/,"");return t.startsWith(this.dataDir+"/")?t:`${this.dataDir}/${t}`}}class Et{constructor(){this.tickers=null}async loadTickers(){if(null===this.tickers)try{const e=await n.e(845).then(n.t.bind(n,6845,19));this.tickers=e.default}catch(e){console.error("Failed to load tickers data:",e),this.tickers={}}return this.tickers}levenshteinDistance(e,t){const n=[],o=e.length,s=t.length;if(0===o)return s;if(0===s)return o;for(let e=0;e<=s;e++)n[e]=[e];for(let e=0;e<=o;e++)n[0][e]=e;for(let i=1;i<=s;i++)for(let s=1;s<=o;s++)t.charAt(i-1)===e.charAt(s-1)?n[i][s]=n[i-1][s-1]:n[i][s]=Math.min(n[i-1][s-1]+1,n[i][s-1]+1,n[i-1][s]+1);return n[s][o]}fuzzyMatchScore(e,t){const n=e.toLowerCase().trim(),o=t.toLowerCase().trim();if(n===o)return 100;if(o.includes(n)){const e=n.length/o.length;return Math.max(70,90*e)}if(o.startsWith(n)){const e=n.length/o.length;return Math.max(60,80*e)}const s=this.levenshteinDistance(n,o),i=Math.max(n.length,o.length);if(0===i)return 0;const a=100*(1-s/i);return a>50?a:0}searchWordsInText(e,t){const n=e.toLowerCase().trim(),o=t.toLowerCase().split(/\s+/);let s=0;for(const e of o){const t=this.fuzzyMatchScore(n,e);s=Math.max(s,t)}return s}async search_dataset(e){try{const{queries:t,limit:n=10}=e;if(!t||0===t.length)return JSON.stringify({error:"Queries parameter is required and cannot be empty"});const o=await this.loadTickers(),s=Math.min(n,10),i=[],a=new Set;for(const e of t){if(!e||""===e.trim())continue;const t=e.toLowerCase().trim();for(const[e,n]of Object.entries(o)){let o=0;const s=this.fuzzyMatchScore(t,e);o=Math.max(o,s);const r=this.fuzzyMatchScore(t,n.name);o=Math.max(o,.8*r);const l=this.searchWordsInText(t,n.name);if(o=Math.max(o,.7*l),o>30)if(a.has(e)){const t=i.find(t=>t.ticker===e);t&&Math.round(o)>t.score&&(t.score=Math.round(o))}else i.push({ticker:e,name:n.name,type:n.type,source:n.source,score:Math.round(o)}),a.add(e)}}const r=i.sort((e,t)=>t.score-e.score).slice(0,s);return JSON.stringify(r)}catch(e){return console.error("Error searching datasets:",e),JSON.stringify({error:`Failed to search datasets: ${e instanceof Error?e.message:String(e)}`})}}}class Mt{constructor(e,t){this.subscriptions=[],this.notebookTracker=e,this.waitingUserReplyBoxManager=t,this.diffTools=new St,this.filesystemTools=new xt,this.webTools=new Et,this.cellTools=new bt(this)}getCurrentNotebook(e){const t=m.AppStateService.getCurrentNotebook();if(t)return{notebook:t.content,widget:t};const n=this.notebookTracker.currentWidget;return n?{notebook:n.content,widget:n}:(console.log("No current notebook"),null)}findCellById(e,t){console.log("Finding cell by ID:",e);const n=this.getCurrentNotebook(t);if(!n)return null;const{notebook:o}=n;for(let e=0;e<o.model.cells.length;e++)console.log(o.widgets[e].id),console.log(o.widgets[e].model.id),console.log(o.widgets[e].model.sharedModel.id);for(let t=0;t<o.model.cells.length;t++){const n=o.widgets[t];if(n.model.id===e)return{cell:n,index:t}}return console.log(`Cell with ID ${e} not found`),null}activateCellByIndex(e){const t=this.getCurrentNotebook();if(!t)return!1;const{notebook:n}=t;return e<0||e>=n.widgets.length?(console.log(`Invalid cell index: ${e}`),!1):(n.activeCellIndex=e,!0)}activateCell(e){if("number"==typeof e)return this.activateCellByIndex(e);{const t=this.getCurrentNotebook();if(!t)return!1;const{notebook:n}=t;let o=-1;for(let t=0;t<n.widgets.length;t++)if(n.widgets[t]===e){o=t;break}return-1===o?(console.log("Cell not found in notebook"),!1):(n.activeCellIndex=o,!0)}}async getNotebookSummary(e){var t;const n=this.getCurrentNotebook(e),o=[];let s=0;for(const e of(null===(t=null==n?void 0:n.widget.model)||void 0===t?void 0:t.cells)||[]){let t={index:s++,id:"",cell_type:"",summary:"",next_step_string:"",current_step_string:"",empty:!0};const n=e.metadata,i=n.custom;i&&(t={...t,...i});const a=n.cell_tracker;a&&(t.id=a.trackingId),t.empty=""===e.sharedModel.getSource().trim(),t.cell_type=e.type,o.push(t)}return console.log("All Cells",o),o}async scrollToCellById(e){var t;const n=null===(t=this.getCurrentNotebook())||void 0===t?void 0:t.notebook;if(!n)return;const o=n.widgets.findIndex(t=>{var n;return(null===(n=t.model.metadata)||void 0===n?void 0:n.cell_tracker.trackingId)===e});if(!n.widgets[o])return;n.activeCellIndex=o;const s=document.querySelector(`[sage-ai-cell-id=${e}]`);if(s&&s.parentElement&&"none"!==s.parentElement.style.display)s.scrollIntoView();else{n.scrollToItem(o,"center"),await Promise.resolve(requestAnimationFrame);const t=t=>{setTimeout(()=>{var t;null===(t=document.querySelector(`[sage-ai-cell-id=${e}]`))||void 0===t||t.scrollIntoView()},t)};let s=100;for(;s<1e3;)t(s),s+=100}}async scrollToPlanCell(){var e,t;const n=null===(e=this.getCurrentNotebook())||void 0===e?void 0:e.notebook;if(!n)return;const o=n.widgets.findIndex(e=>{var t;return"plan"===(null===(t=e.model.metadata.custom)||void 0===t?void 0:t.sage_cell_type)}),s=n.widgets[o];if(!s)return;n.scrollToItem(o,"center"),n.activeCellIndex=o;const i=null===(t=s.model.metadata)||void 0===t?void 0:t.cell_tracker.trackingId;i&&(await Promise.resolve(requestAnimationFrame),setTimeout(()=>{var e;null===(e=document.querySelector(`[sage-ai-cell-id=${i}]`))||void 0===e||e.scrollIntoView()},100))}async waitForScrollEnd(e){return"onscrollend"in e?new Promise(t=>e.addEventListener("scrollend",()=>t(),{once:!0})):this.waitForScrollIdle(e)}async waitForScrollIdle(e,t=120){return new Promise(n=>{let o;const s=()=>{clearTimeout(o),o=window.setTimeout(()=>{e.removeEventListener("scroll",s),n()},t)};e.addEventListener("scroll",s,{passive:!0}),s()})}normalizeContent(e){return e.trim()}display_diff(e,t,n,o){return this.diffTools.display_diff(this,e,t,n,o)}apply_diff(e,t){return this.diffTools.apply_diff(this,e,t)}run_cell(e){return this.cellTools.run_cell(e)}findCellByAnyId(e,t){return e.startsWith("cell_")?this.findCellByTrackingId(e,t):this.findCellById(e,t)}findCellByTrackingId(e,t){var n;const o=null===(n=this.getCurrentNotebook(t))||void 0===n?void 0:n.notebook;if(!o)return null;for(let t=0;t<o.widgets.length;t++){const n=o.widgets[t],s=n.model.sharedModel.getMetadata()||{};if(s.cell_tracker&&s.cell_tracker.trackingId===e)return{cell:n,index:t}}return null}findCellByIndex(e){var t;const n=null===(t=this.getCurrentNotebook())||void 0===t?void 0:t.notebook;return n?{cell:n.widgets[e],index:e}:null}add_cell(e){return this.cellTools.add_cell(e)}remove_cells(e){return this.cellTools.remove_cells(e)}edit_cell(e){return this.cellTools.edit_cell(e)}stream_edit_plan(e){return this.cellTools.stream_edit_plan(e)}async edit_plan(e){return await this.cellTools.edit_plan(e)}get_cells_info(){return this.cellTools.get_cells_info()}get_cell_info(e){return this.cellTools.get_cell_info(e)}edit_history(e){return this.cellTools.edit_history(e)}read_cells(e={}){return this.cellTools.read_cells(e)}refresh_ids(){new _t(this.notebookTracker).fixTrackingIDs()}setFirstCellAsPlan(e){this.cellTools.setFirstCellAsPlan(e)}getPlanCell(e){const t=this.getCurrentNotebook(e);if(!t)return null;const{notebook:n}=t;return this.cellTools.findPlanCell(n)}wait_user_reply(e){var t;try{const n=null===(t=m.AppStateService.getChatContainerSafe())||void 0===t?void 0:t.chatWidget.llmStateDisplay;n&&n.show("Waiting for your reply...",!0);const o=m.AppStateService.getState().chatContainer;if(o&&o.chatWidget){const t=o.chatWidget.getMessageComponent();return t.setContinueCallback(()=>{o.chatWidget.sendContinueMessage()}),t.showWaitingReplyBox(e.recommended_next_prompts),console.log("Waiting for user reply - new system box shown"),!0}return this.waitingUserReplyBoxManager.show(e.recommended_next_prompts),console.log("Waiting for user reply - fallback to old system"),!0}catch(e){return console.error("Error showing waiting reply box:",e),!1}}async list_datasets(e){return this.filesystemTools.list_datasets(e)}async read_dataset(e){return this.filesystemTools.read_dataset(e)}async delete_dataset(e){return this.filesystemTools.delete_dataset(e)}async save_dataset(e){return this.filesystemTools.save_dataset(e)}async search_dataset(e){return this.webTools.search_dataset(e)}}class It{constructor(){this.client=null,this.tools=[],this.kernelInfo={},this.notebookInfo={},this.notebookTracker=null,this.notebookTools=null,this.filesystemTools=null,this.contentManager=null,this.notebookContextManager=null,this.notebookContexts=new Map,this.toolMappings={"notebook-get_cell_info":"get_cell_info","notebook-get_cells":"get_cells","notebook-read_cells":"read_cells","notebook-add_cell":"add_cell","notebook-edit_cell":"edit_cell","notebook-remove_cells":"remove_cells","notebook-run_cell":"run_cell","notebook-execute_cell":"execute_cell","notebook-get_notebook_info":"get_notebook_info","notebook-edit_plan":"edit_plan","notebook-wait_user_reply":"wait_user_reply","filesystem-list_datasets":"list_datasets","filesystem-read_dataset":"read_dataset","filesystem-delete_dataset":"delete_dataset","filesystem-save_dataset":"save_dataset","web-search_dataset":"search_dataset"},this.isConnected=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=10,this.reconnectIntervalMs=5e3,this.connectingPromise=null}async initialize(){return this.connectingPromise?(console.log("[ToolService] Already attempting to connect, waiting..."),this.connectingPromise):(this.connectingPromise=(async()=>{try{return this.client&&(console.log("[ToolService] Disconnecting existing client before re-initialization."),await this.client.close(),this.client=null),await De.w.getConfig(),this.client=new mt.K({name:"sage-ai-client",version:"1.0.0"}),this.tools=await De.w.getTools(),this.client.onerror=e=>{console.log("[ToolService] Client error",e),"SSE error: Failed to fetch"===e.message&&this.handleConnectionLoss()},this.isConnected=!0,this.reconnectAttempts=0,void console.log("[ToolService] MCP client initialized and connected successfully.")}catch(e){throw console.error("Failed to initialize MCP client:",e),this.isConnected=!1,e}finally{this.connectingPromise=null}})(),this.connectingPromise)}updateNotebookId(e,t){const n=this.notebookContexts.get(e)||{kernelInfo:{name:this.kernelInfo.name,id:this.kernelInfo.id},notebookInfo:{path:this.notebookInfo.path,id:this.notebookInfo.id}};this.notebookContexts.set(t,n),this.notebookContexts.delete(e),m.AppStateService.setCurrentNotebookId(t)}async handleConnectionLoss(){if(this.isConnected&&(console.warn("[ToolService] Connection lost. Attempting to reconnect..."),this.isConnected=!1),this.reconnectAttempts<this.maxReconnectAttempts){this.reconnectAttempts++;const e=this.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1);console.log(`[ToolService] Reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${e/1e3} seconds...`),await new Promise(t=>setTimeout(t,e));try{await this.initialize(),console.log("[ToolService] Reconnected successfully!")}catch(e){console.error("[ToolService] Reconnection failed:",e),this.handleConnectionLoss()}}else console.error("[ToolService] Max reconnection attempts reached. Unable to connect to backend.")}isInitialized(){return null!==this.client&&this.isConnected}setNotebookTracker(e,t){this.notebookTracker=e,console.log("Notebook tracker set in ToolService"),this.notebookTools=new Mt(e,t),console.log("NotebookTools initialized in ToolService"),this.notebookTracker.currentChanged.connect(this.handleNotebookChanged,this)}setContentManager(e){this.contentManager=e,console.log("Content manager set in ToolService"),this.filesystemTools=new xt,console.log("FilesystemTools initialized in ToolService")}setCurrentNotebookId(e){if(e!==m.AppStateService.getCurrentNotebookId())if(console.log(`[ToolService] Setting current notebook ID: ${e}`),m.AppStateService.setCurrentNotebookId(e),e&&this.notebookContexts.has(e)){const t=this.notebookContexts.get(e);this.kernelInfo={...t.kernelInfo},this.notebookInfo={...t.notebookInfo},console.log(`[ToolService] Restored context for notebook: ${e}`,{kernel:this.kernelInfo,notebook:this.notebookInfo})}else e&&(this.handleNotebookChanged(),this.storeNotebookContext(e))}getCurrentNotebookId(){return m.AppStateService.getCurrentNotebookId()}storeNotebookContext(e){e&&(this.notebookContexts.set(e,{kernelInfo:{...this.kernelInfo},notebookInfo:{...this.notebookInfo}}),console.log(`[ToolService] Stored context for notebook: ${e}`,{kernel:this.kernelInfo,notebook:this.notebookInfo}))}handleNotebookChanged(){if(!this.notebookTracker)return;const e=this.notebookTracker.currentWidget;if(!e)return void console.log("No active notebook");this.notebookInfo={path:e.sessionContext.path,id:e.id};const t=e.sessionContext.session,n=null==t?void 0:t.kernel;n&&(this.kernelInfo={name:n.name,id:n.id});const o=m.AppStateService.getCurrentNotebookId();o&&this.storeNotebookContext(o)}getCurrentNotebook(e){if(!this.notebookTracker)return null;let t=null;if(e?this.notebookTracker.forEach(n=>{n.context.path===e&&(t=n)}):t=this.notebookTracker.currentWidget,!t)return null;const n=t.sessionContext.session,o=null==n?void 0:n.kernel;return{widget:t,path:t.sessionContext.path,id:t.id,kernel:o||void 0}}async refreshRemoteTools(){if(!this.client)throw new Error("MCP client not initialized");try{const e=await this.client.listTools();console.log("Available MCP tools:",e),this.tools=[];for(const t of e.tools)"notebook-read_notebook_summary"!==t.name&&this.tools.push({name:t.name,description:t.description,input_schema:t.inputSchema});return console.log(`Updated ${this.tools.length} tools from MCP server.`),this.tools}catch(e){throw console.error("Failed to update tools:",e),e}}getTools(){return this.tools}getAskModeTools(){const e=["notebook-get_cell_info","notebook-read_cells","web-search_dataset","filesystem-list_datasets","filesystem-read_dataset","notebook-wait_user_reply"];return this.tools.filter(t=>e.includes(t.name))}async refreshDynamicInfo(){try{if(this.notebookTracker&&this.notebookTracker.currentWidget&&this.handleNotebookChanged(),this.kernelInfoProvider){const e=await this.kernelInfoProvider();e&&(this.kernelInfo=e,console.log("Kernel info dynamically updated:",this.kernelInfo))}if(this.notebookInfoProvider){const e=await this.notebookInfoProvider();e&&(this.notebookInfo=e,console.log("Notebook info dynamically updated:",this.notebookInfo))}}catch(e){console.error("Error refreshing dynamic info:",e)}}canHandleToolLocally(e){return(null!==this.notebookTools||null!==this.filesystemTools)&&e in this.toolMappings}async executeLocalTool(e,t){const n=this.toolMappings[e];console.log(`Executing local tool "${n}" with args:`,t);try{if(e.startsWith("filesystem-")){if(!this.filesystemTools)throw new Error("FilesystemTools not initialized");const e=await this.filesystemTools[n](t);return console.log(`Local filesystem tool "${n}" returned:`,e),e}if(e.startsWith("web-")){if(!this.notebookTools)throw new Error("NotebookTools not initialized");const e=await this.notebookTools[n](t);return console.log(`Local web tool "${n}" returned:`,e),e}{if(!this.notebookTools)throw new Error("NotebookTools not initialized");t.notebook_path;const e=await this.notebookTools[n](t);return console.log(`Local notebook tool "${n}" returned:`,e),e}}catch(e){throw console.error(`Error executing local tool "${n}":`,e),e}}async executeTool(e,t=3,n=!0){var o;const s=(null===(o=e.input)||void 0===o?void 0:o.notebook_id)||m.AppStateService.getCurrentNotebookId(),i=m.AppStateService.getCurrentNotebookId();s&&s!==i&&this.setCurrentNotebookId(s),await this.refreshDynamicInfo();const{name:a,input:r,id:l}=e;if(this.canHandleToolLocally(a))try{console.log(`Executing tool ${a} locally with args:`,r);const e={...r};if(n){this.kernelInfo.name&&(e.kernel_name=this.kernelInfo.name),this.kernelInfo.id&&(e.kernel_id=this.kernelInfo.id);const t=e.notebook_id||m.AppStateService.getCurrentNotebookId();t&&(e.notebook_id=t),e.notebook_path||this.notebookInfo.path&&(e.notebook_path=this.notebookInfo.path),this.notebookInfo.id&&(e.notebook_id=this.notebookInfo.id)}"notebook-add_cell"!==a&&"notebook-edit_cell"!==a||void 0!==e.show_diff||(e.show_diff=!1);const t=await this.executeLocalTool(a,e);return console.log(`Local tool ${a} returned:`,t),{type:"tool_result",tool_use_id:l,content:"object"==typeof t?JSON.stringify(t):String(t)}}catch(e){return console.error("Local tool execution failed:",e),{type:"tool_result",tool_use_id:l,content:`Error: ${e instanceof Error?e.message:String(e)}`}}let c=0;for(;c<=t;)try{if(!this.isInitialized()&&(console.warn("[ToolService] MCP client not connected. Attempting to re-establish connection..."),await this.initialize(),!this.client||!this.isConnected))throw new Error("MCP client could not establish connection.");console.log(`Executing remote tool ${a} with args:`,r);const e={...r};n&&(this.kernelInfo.name&&(e.kernel_name=this.kernelInfo.name),this.kernelInfo.id&&(e.kernel_id=this.kernelInfo.id),this.notebookInfo.path&&(e.notebook_path=this.notebookInfo.path),this.notebookInfo.id&&(e.notebook_id=this.notebookInfo.id),console.log("Including context info in tool call:",{kernel:this.kernelInfo,notebook:this.notebookInfo})),console.log("Tool arguments:",e);const t=await this.client.callTool({name:a,arguments:e});console.log(`Tool ${a} returned:`,t);const o=[];if(t&&t.content)for(const e of t.content)try{const t=JSON.parse(e.text);o.push({...e,text:JSON.stringify(t,null,2)})}catch(t){o.push(e),console.error(t)}return{type:"tool_result",tool_use_id:l,content:o}}catch(e){if(console.error(`Remote tool execution failed (attempt ${c}/${t}):`,e),c++,c>t)return console.error(`Max remote tool execution retries reached for tool ${a}.`),{type:"tool_result",tool_use_id:l,content:`Error: ${e instanceof Error?e.message:String(e)}`};await new Promise(e=>setTimeout(e,1e3*c))}throw new Error("Tool execution failed after all retries")}setContextManager(e){this.notebookContextManager=e,console.log("Notebook context manager set in ToolService")}getContextManager(){return this.notebookContextManager||null}}class Nt{constructor(e,t){this.notebookTools=e,this.notebookTracker=t,this.initializeExistingCells(),this.notebookTracker.currentChanged.connect(()=>{this.initializeExistingCells()})}initializeExistingCells(){var e;const t=null===(e=this.notebookTracker.currentWidget)||void 0===e?void 0:e.content;if(!t)return;const n=t.widgets;for(let e=0;e<n.length;e++){const t=n[e];this.ensureCellHasTrackingMetadata(t,"user")}}getNextCellNumber(){var e,t;const n=null===(e=this.notebookTracker.currentWidget)||void 0===e?void 0:e.content;if(!n)return 1;const o=n.widgets;let s=0;for(let e=0;e<o.length;e++){const n=null===(t=(o[e].model.sharedModel.getMetadata()||{}).cell_tracker)||void 0===t?void 0:t.trackingId;if(n&&/^cell_(\d+)$/.test(n)){const e=parseInt(n.split("_")[1],10);e>s&&(s=e)}}return s+1}ensureCellHasTrackingMetadata(e,t="user"){const n=e.model.sharedModel.getMetadata()||{};if(n.cell_tracker&&n.cell_tracker.trackingId)return n.cell_tracker.lastModified=(new Date).toISOString(),e.model.sharedModel.setMetadata(n),n.cell_tracker.trackingId;const o={trackingId:`cell_${this.getNextCellNumber()}`,createdAt:(new Date).toISOString(),lastModified:(new Date).toISOString(),origin:t,summary:""};return n.cell_tracker=o,e.model.sharedModel.setMetadata(n),o.trackingId}findCellByTrackingId(e){var t;const n=null===(t=this.notebookTracker.currentWidget)||void 0===t?void 0:t.content;if(!n)return null;const o=n.widgets;for(let t=0;t<o.length;t++){const n=o[t],s=n.model.sharedModel.getMetadata()||{};if(s.cell_tracker&&s.cell_tracker.trackingId===e)return{cell:n,index:t}}return null}getCellTrackingMetadata(e){return(e.model.sharedModel.getMetadata()||{}).cell_tracker||null}setCellOrigin(e,t){this.ensureCellHasTrackingMetadata(e);const n=e.model.sharedModel.getMetadata()||{};n.cell_tracker&&(n.cell_tracker.origin=t,n.cell_tracker.lastModified=(new Date).toISOString(),e.model.sharedModel.setMetadata(n))}getAllTrackingIds(){var e;const t=null===(e=this.notebookTracker.currentWidget)||void 0===e?void 0:e.content;if(!t)return[];const n=t.widgets,o=[];for(let e=0;e<n.length;e++){const t=n[e].model.sharedModel.getMetadata()||{};t.cell_tracker&&t.cell_tracker.trackingId&&o.push(t.cell_tracker.trackingId)}return o}}class Dt extends Ne.Widget{constructor(e,t,n){super(),this.currentNotebookId=null,this.id="sage-ai-chat-container",this.title.label="Sage AI Chat",this.title.closable=!0,this.addClass("sage-ai-chat-container"),this.toolService=e,this.contextManager=t||null,this.node.style.minWidth="320px",this.chatWidget=new dt(n);const o=new Ne.PanelLayout;o.addWidget(this.chatWidget),this.layout=o,m.AppStateService.onNotebookChanged().subscribe(async({newNotebookId:e})=>{e&&e!==this.currentNotebookId&&await this.switchToNotebook(e)})}updateNotebookId(e,t){var n;null===(n=this.contextManager)||void 0===n||n.updateNotebookId(e,t),this.chatWidget.chatHistoryManager.updateNotebookId(e,t),this.chatWidget.updateNotebookPath(t),this.toolService.updateNotebookId(e,t),this.currentNotebookId=t}async switchToNotebook(e){this.currentNotebookId!==e&&(console.log(`[NotebookChatContainer] Switching to notebook: ${e}`),this.currentNotebookId=e,this.toolService.setCurrentNotebookId(e),this.contextManager&&this.contextManager.getContext(e),await this.chatWidget.setNotebookId(e))}onCellAddedToContext(e){this.currentNotebookId&&this.currentNotebookId===e?this.chatWidget.onCellAddedToContext(e):console.warn(`Cannot add cell from ${e} to context when current notebook is ${this.currentNotebookId}`)}onCellRemovedFromContext(e){this.currentNotebookId&&this.currentNotebookId===e?this.chatWidget.onCellRemovedFromContext(e):console.warn(`Cannot remove cell from ${e} context when current notebook is ${this.currentNotebookId}`)}}class Tt{constructor(e){this.notebookContexts=new Map,this.sharedToolService=e,m.AppStateService.onNotebookChanged().subscribe(({newNotebookId:e})=>{e&&this.getContext(e)})}getContext(e){if(!this.notebookContexts.has(e)){console.log(`[NotebookContextManager] Creating new context for notebook: ${e}`),this.sharedToolService.setCurrentNotebookId(e);const t=new Q(this.sharedToolService);t.setNotebookId(e);const n={notebookId:e,toolService:this.sharedToolService,stateService:t,lastAccessed:Date.now(),flowId:this.generateFlowId(),contextCells:[]};return this.notebookContexts.set(e,n),n}const t=this.notebookContexts.get(e);return t.lastAccessed=Date.now(),this.sharedToolService.setCurrentNotebookId(e),t}updateNotebookId(e,t){const n=this.notebookContexts.get(e);n&&(n.notebookId=t,this.notebookContexts.set(t,n),this.notebookContexts.delete(e))}addCellToContext(e,t,n,o,s){const i=this.getContext(e);return!i.contextCells.some(e=>e.cellId===t)&&(i.contextCells.push({cellId:t,trackingId:n,content:o,cellType:s,addedAt:Date.now()}),console.log(`[NotebookContextManager] Added cell to context: ${t}`),!0)}removeCellFromContext(e,t){if(!this.notebookContexts.has(e))return!1;const n=this.notebookContexts.get(e),o=n.contextCells.length;return n.contextCells=n.contextCells.filter(e=>e.cellId!==t),n.contextCells.length<o}isCellInContext(e,t){return!!this.notebookContexts.has(e)&&this.notebookContexts.get(e).contextCells.some(e=>e.cellId===t)}getContextCells(e){return this.notebookContexts.has(e)?[...this.notebookContexts.get(e).contextCells]:[]}formatContextAsMessage(e){const t=this.getContextCells(e);if(0===t.length)return"";let n="Here are the cells from the notebook that the user has provided as additional context:\n\n";return t.forEach(e=>{var t;const o=null===(t=this.sharedToolService.notebookTools)||void 0===t?void 0:t.findCellByAnyId(e.trackingId);o&&(n+=`==== CELL Context - Cell ID: ${e.trackingId} ====\n`,n+=o.cell.model.sharedModel.getSource().trim(),n+="\n==== End Cell Context ====\n\n")}),n}getContextSummary(e){return this.getContextCells(e).map(e=>{var t;const n=null===(t=this.sharedToolService.notebookTools)||void 0===t?void 0:t.findCellByAnyId(e.trackingId);if(n){const t=n.cell.model.sharedModel.getSource(),o=t.length>50?t.substring(0,50)+"...":t;return{type:"cell",id:e.trackingId,name:`Cell ${e.trackingId}`,preview:o}}return{type:"cell",id:e.trackingId,name:`Cell ${e.trackingId}`,preview:"Cell content unavailable"}})}generateFlowId(){return"flow-"+Date.now()+"-"+Math.random().toString(36).substring(2,9)}}var At=n(8276);class Lt{constructor(e,t,n){this.highlightedCells=new Map,this.chatContainerRef=null,this.cellHistory=new Map,this.notebookTracker=e,this.notebookContextManager=t,this.notebookTools=n,this.addContextHighlightCSS(),this.setupListeners()}async onPromptSubmit(e,t){var n,o,s,i,a,r,l,c,d;console.log("Prompt submitted for cell",(null===(n=e.model)||void 0===n?void 0:n.id)||e.id,":",t);const h=(null===(i=null===(s=null===(o=e.model)||void 0===o?void 0:o.sharedModel.getMetadata())||void 0===s?void 0:s.cell_tracker)||void 0===i?void 0:i.trackingId)||(null===(a=e.model)||void 0===a?void 0:a.id)||e.id||"[unknown]";if("[unknown]"===h)return console.error("Could not determine cell ID for prompt submission.",e),!1;const u=this.notebookTracker.activeCell;if(!u)return console.warn("No active cell"),!1;const p=u.editor,g=null==p?void 0:p.getSelection(),f=(null==p?void 0:p.model.sharedModel.source.split("\n"))||[],v=this.calculateEndLine(null==g?void 0:g.end,f),C=null==p?void 0:p.model.sharedModel.source.substring(p.getOffsetAt((null==g?void 0:g.start)||{line:0,column:0}),p.getOffsetAt(v)),b=C&&C.trim().length>0,y=(null===(r=null==g?void 0:g.start)||void 0===r?void 0:r.line)||0,k=v.line,w=f.slice(y,k+1),S=m.AppStateService.getConfig();let _,x;b?(_=S.edit_selection,x="edit_selection"):(_=S.edit_full_cell,x="edit_full_cell");const E=_.system_prompt;try{const e=this.notebookTools.findCellByTrackingId(h),n=null==e?void 0:e.cell.model.sharedModel.getSource(),o=null===(d=null===(c=null===(l=this.notebookTools.findCellByIndex(((null==e?void 0:e.index)||0)-1))||void 0===l?void 0:l.cell)||void 0===c?void 0:c.model)||void 0===d?void 0:d.sharedModel.getSource();let s="";if(b){const e=w.map((e,t)=>`${(y+t+1).toString().padStart(3," ")}: ${e}`).join("\n"),n=f.map((e,t)=>`${(t+1).toString().padStart(3," ")}:${e}`).join("\n");s=`EDIT SELECTION MODE: Edit the selected lines (${y+1}-${k+1}) using structured operations.\n\nFULL CELL CONTEXT:\n\`\`\`\n${n}\n\`\`\`\n\nSELECTED LINES TO EDIT (${y+1}-${k+1}):\n\`\`\`\n${e}\n\`\`\`\n\nReturn a JSON object with operations for each line in the selection range. Use KEEP, MODIFY, REMOVE, or INSERT actions. Consider the full cell context when making edits.\n\nUser request: ${t}`}else s=`\n EDIT FULL CELL MODE: Edit and improve the complete cell.\n\n CELL TO EDIT:\n \`\`\`\n ${n}\n \`\`\`\n\n PREVIOUS CELL CONTENT:\n \`\`\`\n ${o}\n \`\`\`\n\n Return only the fully edited cell. Apply your quantitative expertise to improve the code.\n\n User request: ${t}`;const i=m.AppStateService.getChatService();if(b){const e=this.notebookTools.findCellByTrackingId(h);if(!e)throw new Error(`Could not find cell with ID ${h}`);let t="",n=[];const o=e=>{try{const t=(0,At.parse)(e.trim());if((null==t?void 0:t.operations)&&Array.isArray(t.operations))return t.operations.filter(e=>void 0!==e.line&&e.action&&["KEEP","MODIFY","REMOVE","INSERT"].includes(e.action))}catch(e){}return[]},a=t=>{if(0===t.length)return;const n=[...f];let o=0;const s=t.sort((e,t)=>e.line-t.line);for(const e of s){const t=e.line-1+o;switch(e.action){case"KEEP":break;case"MODIFY":t<n.length&&void 0!==e.content&&(n[t]=e.content);break;case"REMOVE":t<n.length&&(n.splice(t,1),o--);break;case"INSERT":t<=n.length&&void 0!==e.content&&(n.splice(t,0,e.content),o++)}}e.cell.model.sharedModel.setSource(n.join("\n"))},r=await i.sendEphemeralMessage(s,E,"claude-3-5-haiku-latest",e=>{t+=e;const s=o(t);s.length>0&&(s.length!==n.length||s.some((e,t)=>{const o=n[t];return!o||e.line!==o.line||e.action!==o.action||e.content!==o.content}))&&(a(s),n=[...s])},void 0,void 0,"cmd-k");try{const e=o(r);if(!(e.length>0))throw new Error("No valid operations found in response");a(e),console.log(`Applied ${e.length} edit_selection operations to lines ${y+1}-${k+1} in cell ${h}`)}catch(e){return console.error("Failed to parse final edit_selection response:",e),console.error("Raw response:",r),alert("Error processing edit_selection: Invalid response format. Please try again."),!1}}else{const e=this.notebookTools.findCellByTrackingId(h);if(!e)throw new Error(`Could not find cell with ID ${h}`);let t="",n="",o=!1,a=/```(?:python|py)?\s*/i,r=/```/;const l=await i.sendEphemeralMessage(s,E,"claude-3-5-haiku-latest",s=>{if(t+=s,o)if(r.test(s)){o=!1;const e=n.lastIndexOf("```");-1!==e&&(n=n.substring(0,e)),n=n.replace(/^\s*(python|py)\s*\n?/i,"")}else n+=s;else{const e=t.match(a);e?(o=!0,n=t.substring(t.indexOf(e[0])+e[0].length),n=n.replace(/^\s*(python|py)\s*\n?/i,"")):n=t}if(n.includes("\n")){const t=n.split("\n"),o=[...f],s=Math.min(t.length,f.length);for(let e=0;e<s;e++)void 0!==t[e]&&(o[e]=t[e]);if(t.length>f.length)for(let e=f.length;e<t.length;e++)void 0!==t[e]&&o.push(t[e]);e.cell.model.sharedModel.setSource(o.join("\n"))}else if(n.trim()&&!n.includes("\n")){const t=[...f];t.length>0?t[0]=n.trim():t.push(n.trim()),e.cell.model.sharedModel.setSource(t.join("\n"))}},void 0,void 0,"cmd-k");let c=n.trim();if(!c&&l.trim())if(l.includes("```")){const e=l.match(/```(?:python|py)?\s*([\s\S]*?)```/i);e&&(c=e[1].replace(/^\s*(python|py)\s*\n?/i,"").trim())}else c=l.trim();else c&&(c=c.replace(/^```(?:python|py)?\s*/i,"").replace(/```$/,"").replace(/^\s*(python|py)\s*\n?/i,"").trim());c&&(e.cell.model.sharedModel.setSource(c),console.log(`Applied edit_full_cell response to cell ${h} with progressive transformation`))}return console.log(`Ephemeral ${x} request completed using Haiku model.`),!0}catch(e){const t=e instanceof Error?e.message:String(e);return console.error(`Failed to process: ${t}`,e),!1}}async handlePromptSubmit(e,t){var n;if(t.trim()){const o=e.node.querySelector(".sage-ai-prompt-input"),s=e.node.querySelector(".sage-ai-quick-gen-prompt-error-message"),i=e.node.querySelector(".sage-ai-quick-gen-submit"),a=e.node.querySelector(".sage-ai-quick-gen-undo"),r=e.node.querySelector(".sage-ai-blob-loader"),l=null===(n=(e.model.sharedModel.getMetadata()||{}).cell_tracker)||void 0===n?void 0:n.trackingId,c=e.model.sharedModel.getSource();l&&(this.cellHistory.has(l)||this.cellHistory.set(l,[]),this.cellHistory.get(l).push(c)),r.style.display="block",i.disabled=!0,o.disabled=!0,a&&(a.disabled=!0);const d=await this.onPromptSubmit(e,t);if(r.style.display="none",i.disabled=!1,o.disabled=!1,d){o.value="",s.classList.add("sage-ai-quick-gen-prompt-error-message-hidden");const t=e.model.sharedModel.getSource();c!==t&&this.showDiffView(e,c,t),this.updateUndoButtonState(e)}else s.classList.remove("sage-ai-quick-gen-prompt-error-message-hidden"),a&&(a.disabled=!0)}}calculateEndLine(e,t){var n;return e?e.line>=t.length?{line:t.length-1,column:(null===(n=t[t.length-1])||void 0===n?void 0:n.length)||0}:e:null}showDiffView(e,t,n){try{wt.showInlineDiff(e,t,n),console.log("[ContextCellHighlighter] Inline diff displayed using InlineDiffService")}catch(e){console.error("Error showing diff view:",e)}}setChatContainer(e){this.chatContainerRef=e}handleUndo(e){var t;const n=null===(t=(e.model.sharedModel.getMetadata()||{}).cell_tracker)||void 0===t?void 0:t.trackingId;if(n&&this.cellHistory.has(n)){const t=this.cellHistory.get(n);if(t&&t.length>0){const o=t.pop();e.model.sharedModel.setSource(o),this.updateUndoButtonState(e),0===t.length&&this.cellHistory.delete(n)}}}clearCellHistory(e){this.cellHistory.delete(e)}getUndoStepsAvailable(e){const t=this.cellHistory.get(e);return t?t.length:0}updateUndoButtonState(e){var t;const n=null===(t=(e.model.sharedModel.getMetadata()||{}).cell_tracker)||void 0===t?void 0:t.trackingId,o=e.node.querySelector(".sage-ai-quick-gen-undo");if(o&&n){const e=this.getUndoStepsAvailable(n);o.disabled=0===e,o.title=e>0?`Undo AI changes (${e} step${e>1?"s":""} available)`:"No AI changes to undo"}}setupListeners(){this.notebookTracker.currentChanged.connect((e,t)=>{var n;t&&(this.highlightContextCells(t),null===(n=t.model)||void 0===n||n.cells.changed.connect(()=>{this.refreshHighlighting(t)}))}),this.notebookTracker.currentWidget&&this.highlightContextCells(this.notebookTracker.currentWidget)}refreshHighlighting(e){const t=e.context.path;this.highlightedCells.delete(t),this.highlightContextCells(e)}addContextHighlightCSS(){const e=document.createElement("style");e.id="sage-ai-context-highlight-style",e.textContent="\n .sage-ai-in-context-cell {\n position: relative;\n }\n .sage-ai-cell-id-label {\n position: absolute;\n right: 8px;\n top: -8px;\n transform: translateY(-50%);\n background: #f2f7fd;\n color: #1976d2;\n border: 1px solid #dce5f2;\n border-radius: 4px;\n font-size: 10px;\n padding: 2px 6px;\n z-index: 101;\n pointer-events: none;\n }\n \n .sage-ai-context-indicator {\n position: absolute;\n left: -24px;\n top: 0;\n bottom: 0;\n width: 4px;\n background-color: #4CAF50;\n border-radius: 2px;\n }\n \n .sage-ai-context-badge {\n position: absolute;\n left: -80px;\n top: 50%;\n transform: translateY(-50%);\n background-color: #4CAF50;\n color: white;\n padding: 2px 5px;\n border-radius: 4px;\n font-size: 10px;\n white-space: nowrap;\n opacity: 0;\n transition: opacity 0.3s;\n }\n \n .sage-ai-in-context-cell:hover .sage-ai-context-badge {\n opacity: 1;\n }\n \n .sage-ai-context-buttons {\n position: absolute;\n top: 0px;\n left: 78px;\n transform: translateY(-100%);\n display: flex;\n gap: 8px;\n opacity: 1;\n z-index: 100;\n }\n \n .sage-ai-add-button, .sage-ai-remove-button {\n padding: 2px 8px;\n font-size: 10px;\n border-radius: 4px;\n cursor: pointer;\n display: flex;\n align-items: center;\n gap: 4px;\n }\n \n .sage-ai-add-button {\n background-color: #f2f7fd;\n color: #1976d2;\n border: 1px solid #dce5f2;\n }\n \n .sage-ai-add-button:hover {\n background-color: #e1f0ff;\n border-color: #a9c6e9;\n }\n \n .sage-ai-remove-button {\n background-color: #ffebee;\n color: #e53935;\n border: 1px solid #ffcdd2;\n }\n \n .sage-ai-remove-button:hover {\n background-color: #ffcdd2;\n border-color: #ef9a9a;\n }\n\n .sage-ai-quick-generation {\n display: flex;\n align-items: center;\n border: 0;\n cursor: pointer;\n font-size: 10px;\n background-color: #f2f7fd;\n color: #1976d2;\n border: 1px solid #dce5f2;\n }\n \n .sage-ai-quick-generation:hover {\n background-color: #e1f0ff;\n border-color: #a9c6e9;\n }\n\n .sage-ai-quick-generation-hidden {\n display: none !important;\n }\n \n .sage-ai-quick-gen-prompt-container {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n gap: 4px;\n flex: 1;\n padding: 6px;\n }\n\n .sage-ai-quick-gen-prompt-input-container {\n display: flex;\n flex-direction: column;\n gap: 4px;\n flex: 1;\n }\n\n .sage-ai-quick-gen-prompt-error-message {\n color: #f1625f;\n font-size: var(--jp-ui-font-size0);\n position: absolute;\n top: 28px;\n left: 93px;\n }\n\n .sage-ai-quick-gen-prompt-error-message-hidden {\n display: none;\n }\n\n .sage-ai-prompt-input {\n font-size: var(--jp-ui-font-size1);\n padding: 4px;\n margin: 0;\n min-height: 20px;\n width: 100%;\n border: 0;\n background-color: transparent;\n outline: 0;\n }\n\n .sage-ai-quick-gen-submit {\n display: flex;\n align-items: center;\n background: transparent;\n border: 0;\n padding: 0;\n margin: 0;\n }\n\n .sage-ai-quick-gen-undo {\n display: flex;\n align-items: center;\n background: transparent;\n border: 0;\n padding: 0;\n margin: 0;\n cursor: pointer;\n opacity: 0.5;\n transition: opacity 0.2s;\n }\n\n .sage-ai-quick-gen-undo:enabled {\n opacity: 1;\n cursor: pointer;\n }\n\n .sage-ai-quick-gen-undo:disabled {\n opacity: 0.3;\n cursor: not-allowed;\n }\n\n .sage-ai-quick-gen-cancel {\n color: var(--jp-ui-font-color1);\n font-size: 14px;\n cursor: pointer;\n line-height: 0;\n }\n\n .sage-ai-quick-gen-container {\n display: flex;\n flex-direction: column;\n flex: 1;\n border: var(--jp-border-width) solid var(--jp-cell-editor-border-color);\n }\n\n .sage-ai-quick-gen-active .jp-InputArea-editor {\n border-top: var(--jp-border-width) solid var(--jp-cell-editor-border-color) !important; /* Use !important to override */\n border-left: 0 !important;\n border-right: 0 !important;\n border-bottom: 0 !important;\n }\n\n .sage-ai-quick-gen-active .jp-Toolbar {\n top: 39px !important; /* Use !important to override */\n }\n\n /* Reset toolbar position when quick gen is not active */\n .jp-Cell:not(.sage-ai-quick-gen-active) .jp-Toolbar {\n top: 0 !important; /* Ensure it resets */\n }\n\n .sage-ai-placeholder-quick-gen {\n color: #828282;\n position: absolute;\n bottom: 12px;\n left: 84px;\n }\n\n .sage-ai-placeholder-quick-gen-hidden {\n display: none;\n }\n\n .sage-ai-placeholder-quick-gen-button {\n display: inline-flex;\n align-items: center;\n gap: 2px;\n color: #1976D2 !important;\n }\n\n .sage-ai-placeholder-quick-gen-button:hover {\n cursor: pointer;\n color: rgb(19, 93, 167) !important;\n }\n\n .sage-ai-placeholder-quick-gen-button:hover svg {\n cursor: pointer;\n fill: rgb(19, 93, 167) !important;\n }\n \n .sage-ai-plan-label {\n border-color: #12ff00 !important;\n }\n\n .sage-ai-quick-gen-diff-overlay {\n box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);\n transition: opacity 0.3s ease;\n }\n\n .sage-ai-quick-gen-diff-overlay:hover {\n box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);\n }\n\n .sage-ai-diff-approve-button:hover {\n background: #45a049 !important;\n transform: scale(1.05);\n transition: all 0.2s ease;\n }\n\n .sage-ai-diff-reject-button:hover {\n background: #d32f2f !important;\n transform: scale(1.05);\n transition: all 0.2s ease;\n }\n ",document.head.appendChild(e)}highlightContextCells(e){const t=e.context.path;if(!t)return;const n=this.notebookContextManager.getContextCells(t),o=new Set;this.highlightedCells.set(t,o);for(const e of n){const n=e.trackingId||e.cellId,s=this.notebookTools.findCellByAnyId(n,t);s&&(this.highlightCell(s.cell,!0),o.add(n))}this.addContextButtonsToAllCells(e)}addContextButtonsToAllCells(e){var t;const n=e.content.widgets,o=e.context.path;for(let e=0;e<n.length;e++){const s=n[e],i=null===(t=(s.model.sharedModel.getMetadata()||{}).cell_tracker)||void 0===t?void 0:t.trackingId,a=s.node.querySelector(".sage-ai-cell-id-label");if(a&&a.remove(),i){const e=document.createElement("div");e.setAttribute("sage-ai-cell-id",i),e.className="sage-ai-cell-id-label","planning_cell"===i&&(e.className+=" sage-ai-plan-label"),e.textContent=i,s.node.appendChild(e);const t=this.notebookContextManager.isCellInContext(o,i);this.addContextButtonsToCell(s,i,o,t)}}}addContextButtonsToCell(e,t,n,o){const s=e.node.querySelector(".sage-ai-context-buttons");s&&s.remove();const i=document.createElement("div");if(i.className="sage-ai-context-buttons",o){const o=document.createElement("button");o.className="sage-ai-remove-button",o.textContent="Remove from Chat",o.addEventListener("click",o=>{o.stopPropagation(),o.preventDefault(),this.notebookContextManager.removeCellFromContext(n,t),this.highlightCell(e,!1),this.refreshHighlighting(this.notebookTracker.currentWidget),this.chatContainerRef&&!this.chatContainerRef.isDisposed&&this.chatContainerRef.onCellRemovedFromContext(n,t)}),i.appendChild(o),e.node.classList.add("sage-ai-in-context-cell")}else{const o=document.createElement("button");o.className="sage-ai-add-button",o.innerHTML='\n <svg xmlns="http://www.w3.org/2000/svg" height="12" width="12" viewBox="0 0 24 24">\n <path fill="#1976d2" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6z"/>\n </svg>\n Add to Context\n ',o.addEventListener("click",o=>{o.stopPropagation(),o.preventDefault();const s=e.model.sharedModel.getSource(),i=e.model.type;this.notebookContextManager.addCellToContext(n,t,t,s,i),this.refreshHighlighting(this.notebookTracker.currentWidget),this.chatContainerRef&&!this.chatContainerRef.isDisposed&&this.chatContainerRef.onCellAddedToContext(n,t)}),i.appendChild(o),e.node.classList.remove("sage-ai-in-context-cell")}if(!e.node.querySelector(".sage-ai-quick-gen-container")){const t=document.createElement("button");t.className="sage-ai-quick-generation";const n="K";let o=/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"⌘":"⌃";t.append(`Inline Edit (${o} ${n})`),i.appendChild(t),e.model.sharedModel.source||t.classList.add("sage-ai-quick-generation-hidden"),t.addEventListener("click",()=>{if(e.node.querySelector(".sage-ai-quick-gen-prompt-container"))return;t.classList.add("sage-ai-quick-generation-hidden");const n=document.createElement("div");n.className="sage-ai-quick-gen-prompt-container";const o=document.createElement("div");o.className="sage-ai-blob-loader",o.style.display="none";const s=document.createElement("div");s.className="sage-ai-quick-gen-prompt-input-container";const a=document.createElement("input");a.className="sage-ai-prompt-input",a.placeholder="Edit selected lines or the whole cell";const r=document.createElement("span");r.className="sage-ai-quick-gen-prompt-error-message sage-ai-quick-gen-prompt-error-message-hidden",r.textContent="An unexpected error occurred, please try again.",s.append(a,r);const l=document.createElement("span");l.className="sage-ai-quick-gen-cancel",l.innerHTML='\n <svg xmlns="http://www.w3.org/2000/svg" height="20px" width="20px" viewBox="0 0 24 24">\n <path fill="var(--jp-ui-font-color3)" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>\n </svg>\n ',l.addEventListener("click",()=>{h.remove(),null==p||p.appendChild(u),i.classList.remove("sage-ai-buttons-hidden"),e.node.classList.remove("sage-ai-quick-gen-active"),e.model.sharedModel.source&&t.classList.remove("sage-ai-quick-generation-hidden")});const c=document.createElement("button");c.className="sage-ai-quick-gen-undo",c.disabled=!0,c.innerHTML=Rt,c.title="Undo AI changes",c.addEventListener("click",()=>{this.handleUndo(e)});const d=document.createElement("button");d.className="sage-ai-quick-gen-submit",d.style.cursor="pointer",d.innerHTML='<svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="var(--jp-ui-font-color3)"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g clip-path="url(#clip0_429_11126)"> <path d="M9 4.00018H19V18.0002C19 19.1048 18.1046 20.0002 17 20.0002H9" stroke="var(--jp-ui-font-color3)" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"></path> <path d="M12 15.0002L15 12.0002M15 12.0002L12 9.00018M15 12.0002H5" stroke="var(--jp-ui-font-color3)" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"></path> </g> <defs> <clipPath id="clip0_429_11126"> <rect width="24" height="24" fill="white"></rect> </clipPath> </defs> </g></svg>',d.addEventListener("click",()=>{this.handlePromptSubmit(e,a.value)}),n.append(s,o,c,d,l);const h=document.createElement("div");h.className="sage-ai-quick-gen-container";const u=e.node.querySelector(".jp-InputArea-editor");if(!u)throw"Unexpected error: Couldn't find the cell input area editor element";h.append(n,u);const p=e.node.querySelector(".jp-InputArea");if(!p)throw"Unexpected error: Couldn't find the cell input area element";p.appendChild(h),e.node.classList.add("sage-ai-quick-gen-active"),a.focus(),a.addEventListener("keydown",t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.handlePromptSubmit(e,a.value))})})}e.node.addEventListener("keydown",t=>{if(e.node.classList.contains("jp-mod-active")&&(t.metaKey||t.ctrlKey)&&"k"===t.key){t.preventDefault();const n=e.node.querySelector(".sage-ai-quick-generation");n&&!n.classList.contains("sage-ai-quick-generation-hidden")&&n.click()}});try{this.createCellPlaceholder(e),this.cellPlaceholderListener(e)}catch(e){console.error(`Couldn't setup placeholder: ${e}`)}e.node.appendChild(i)}cellPlaceholderListener(e){e.model.contentChanged.connect(t=>{const n=e.node.querySelector(".sage-ai-quick-generation"),o=t.sharedModel.source,s=e.node.querySelector(".sage-ai-placeholder-quick-gen"),i=null==s?void 0:s.classList.contains("sage-ai-placeholder-quick-gen-hidden");return!o&&i?(null==s||s.classList.remove("sage-ai-placeholder-quick-gen-hidden"),void(null==n||n.classList.add("sage-ai-quick-generation-hidden"))):o?(null==s||s.classList.add("sage-ai-placeholder-quick-gen-hidden"),void(null==n||n.classList.remove("sage-ai-quick-generation-hidden"))):void 0})}createCellPlaceholder(e){if(e.node.querySelector(".sage-ai-placeholder-quick-gen"))return;const t=document.createElement("span");t.className="sage-ai-placeholder-quick-gen",e.model.sharedModel.source&&t.classList.add("sage-ai-placeholder-quick-gen-hidden");let n=/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"⌘":"⌃";const o=document.createElement("a");o.className="sage-ai-placeholder-quick-gen-button",o.textContent=`Inline Edit (${n} K)`,t.textContent="Start coding or use ",t.append(o),o.addEventListener("click",t=>{t.stopPropagation();const n=e.node.querySelector(".sage-ai-quick-generation"),o=e.node.querySelector(".sage-ai-quick-gen-prompt-container");n&&!o&&n.click()}),t.addEventListener("click",()=>{const t=e.node.querySelector(".cm-content");null==t||t.focus()}),e.node.append(t)}highlightCell(e,t){e.node.classList.remove("sage-ai-in-context-cell");const n=e.node.querySelector(".sage-ai-context-indicator");n&&n.remove();const o=e.node.querySelector(".sage-ai-context-badge");if(o&&o.remove(),t){e.node.classList.add("sage-ai-in-context-cell");const t=document.createElement("div");t.className="sage-ai-context-indicator",e.node.appendChild(t);const n=document.createElement("div");n.className="sage-ai-context-badge",n.textContent="In Context",e.node.appendChild(n)}}}const Rt='\n <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="var(--jp-ui-font-color3)">\n <path d="M3 7v6h6" stroke="var(--jp-ui-font-color3)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13" stroke="var(--jp-ui-font-color3)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ';class Bt extends Ne.Widget{constructor(e,t,n){super(),this.id="sage-ai-settings-container",this.title.label="Sage Settings",this.title.closable=!0,this.addClass("sage-ai-settings-container"),this.settingsWidget=new Se(e);const o=new Ne.PanelLayout;o.addWidget(this.settingsWidget),this.layout=o}}function Pt({isVisible:e,currentStep:t,nextStep:n,source:o,isLoading:s}){const[i,a]=oe.useState(!1),[r,l]=oe.useState({tasks:[]}),c=oe.useRef([]),d=e=>!!(s&&t&&t.toLowerCase().includes(e.toLowerCase()));if(oe.useEffect(()=>{if(o&&o.trim()){const e=function(e){if(!e||!e.trim())return{tasks:[]};const t=e.split("\n"),n=[];let o,s=null;for(const e of t){const t=e.trim(),i=t.match(/^#\s*(.+)$/);if(i&&!o){o=i[1].trim();continue}const a=t.match(/^-\s*\[([ x])\]\s*(.+)$/);if(a){s&&n.push(s);const t="x"===a[1];s={text:a[2].trim(),completed:t,type:e.startsWith(" ")?"subtask":"task",subtopics:[]};continue}if(e.startsWith(" -")&&s){const t=e.replace(" -","");s.subtopics.push(t);continue}}return s&&n.push(s),{title:o,tasks:n}}(o);l(e),c.current=new Array(e.tasks.length).fill(null)}else l({tasks:[]}),c.current=[]},[o]),oe.useEffect(()=>{if(i&&r.tasks.length>0){const e=r.tasks.findIndex(e=>d(e.text)),t=r.tasks.findIndex(e=>!e.completed),n=e>=0?e:t;n>=0&&c.current[n]&&setTimeout(()=>{var e;null===(e=c.current[n])||void 0===e||e.scrollIntoView({behavior:"smooth",block:"center"})},100)}},[i,r.tasks,s,t]),!e)return null;const h=o&&o.trim(),u=r.tasks.length>0||r.title;return oe.createElement("div",{className:"sage-ai-plan-state-display"},oe.createElement("div",{className:"sage-ai-plan-state-header"},s&&oe.createElement("div",{className:"sage-ai-plan-state-loader"}),oe.createElement("div",{className:"sage-ai-plan-state-content"},oe.createElement("div",{className:"sage-ai-plan-current-step"},oe.createElement("span",{className:"sage-ai-plan-current-text"},$t(t||"No current step"))),(n||h)&&oe.createElement("div",{className:"sage-ai-plan-bottom-row"},n&&oe.createElement("div",{className:"sage-ai-plan-next-text"},"Next: ",$t(n)))),u&&oe.createElement("button",{className:"sage-ai-plan-source-toggle",onClick:()=>a(!i),"aria-expanded":i,type:"button",title:"Toggle plan details"},oe.createElement("svg",{width:"17",height:"18",viewBox:"0 0 17 18",fill:"none",xmlns:"http://www.w3.org/2000/svg"},oe.createElement("path",{d:"M3.54134 6.65503L13.458 6.65503L8.49967 11.3448L3.54134 6.65503Z",fill:"#949494"})))),u&&oe.createElement("div",{className:"sage-ai-plan-source-content "+(i?"expanded":"collapsed")},oe.createElement("div",{className:"sage-ai-plan-tasks-list"},r.title&&oe.createElement("div",{className:"sage-ai-plan-title"},r.title),r.tasks.map((e,t)=>e.subtopics.length?oe.createElement("div",{key:t},oe.createElement(jt,{isTaskExecuting:d,taskRefs:c,index:t,task:e}),e.subtopics.length>0&&oe.createElement("ul",{className:"sage-ai-plan-subtopics"},e.subtopics.map((e,n)=>oe.createElement("li",{key:`subtopic-${t}-${n}`,className:"sage-ai-plan-subtopic"},oe.createElement("span",{className:"sage-ai-subtopic-text"},e))))):oe.createElement(jt,{key:t,isTaskExecuting:d,taskRefs:c,index:t,task:e})))))}function jt({task:e,isTaskExecuting:t,taskRefs:n,index:o}){const s=t(e.text),i="subtask"===e.type;return oe.createElement("div",{className:"sage-ai-plan-task-item "+(i?"sage-ai-plan-subtask-item":""),ref:e=>{n.current&&e&&(n.current[o]=e)}},oe.createElement("div",{className:"sage-ai-task-icon "+(s?"sage-ai-task-executing":"")},e.completed?oe.createElement("svg",{width:"14",height:"15",viewBox:"0 0 14 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},oe.createElement("path",{d:"M11.6663 4L5.24967 10.4167L2.33301 7.5",stroke:"#22C55E",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})):oe.createElement("svg",{width:"14",height:"15",viewBox:"0 0 14 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},oe.createElement("circle",{cx:"7",cy:"7.5",r:"6.25",stroke:"url(#paint0_linear_549_10580)",strokeWidth:"1.5",strokeLinejoin:"round",strokeDasharray:"3 3"}),oe.createElement("defs",null,oe.createElement("linearGradient",{id:"paint0_linear_549_10580",x1:"0",y1:"0.5",x2:"14",y2:"14.5",gradientUnits:"userSpaceOnUse"},oe.createElement("stop",{stopColor:"#FEC163"}),oe.createElement("stop",{offset:"1",stopColor:"#DE4313"}))))),oe.createElement("span",{className:s?"sage-ai-task-executing":""},$t(e.text)))}function $t(e){return(e=(e=(e=(e=(e=(e=(e=(e=e.replace(/(\*\*|__)(.*?)\1/g,"$2")).replace(/(\*|_)(.*?)\1/g,"$2")).replace(/`([^`]+)`/g,"$1")).replace(/~~(.*?)~~/g,"$1")).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1")).replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1")).replace(/[#>*_`~\-]/g,"")).replace(/\s{2,}/g," ")).trim()}class Ht extends gt.ReactWidget{constructor(){super(),this._stateChanged=new se.Signal(this),this._state={isVisible:!1,currentStep:void 0,nextStep:void 0,source:void 0,isLoading:!1},this.addClass("sage-ai-plan-state-widget")}get stateChanged(){return this._stateChanged}render(){return oe.createElement(Pt,{isVisible:this._state.isVisible,currentStep:this._state.currentStep,nextStep:this._state.nextStep,source:this._state.source,isLoading:this._state.isLoading})}async updatePlan(e,t,n,o){const s=!(!e&&!t);this._state={isVisible:s,currentStep:e,nextStep:t,source:n,isLoading:null!=o?o:!!e},s?this.removeClass("hidden"):this.addClass("hidden"),this._stateChanged.emit(this._state),this.update()}show(){this._state={...this._state,isVisible:!0},this.removeClass("hidden"),this._stateChanged.emit(this._state),this.update()}hide(){this._state={...this._state,isVisible:!1},this.addClass("hidden"),this._stateChanged.emit(this._state),this.update()}setLoading(e){this._state={...this._state,isLoading:e},this._stateChanged.emit(this._state),this.update()}updateCurrentStep(e){this._state={...this._state,currentStep:e,isVisible:!0},this._stateChanged.emit(this._state),this.update()}updateNextStep(e){this._state={...this._state,nextStep:e},this._stateChanged.emit(this._state),this.update()}updateSource(e){this._state={...this._state,source:e},this._stateChanged.emit(this._state),this.update()}getIsVisible(){return this._state.isVisible}getState(){return{...this._state}}getWidget(){return this}}class Ut{constructor(){this.container=null,this.waitingReplyBox=null,this.continueButton=null,this.promptButtons=[],this.onContinueCallback=null,this.onPromptCallback=null}initialize(e){if(console.log("[WaitingUserReplyBoxManager] initialize() called"),this.waitingReplyBox)return void console.log("[WaitingUserReplyBoxManager] Already initialized, returning early");this.container=e,console.log("[WaitingUserReplyBoxManager] Container set:",e),this.waitingReplyBox=document.createElement("div"),this.waitingReplyBox.className="sage-ai-waiting-reply-container";const t=document.createElement("div");t.className="sage-ai-waiting-reply-text",t.textContent="Sage will continue working after you reply",this.waitingReplyBox.appendChild(t);const n=document.createElement("div");n.className="sage-ai-prompt-buttons-container",n.style.display="flex",n.style.flexDirection="column",n.style.gap="8px",n.style.marginTop="12px",["Continue"].forEach((e,t)=>{const o=document.createElement("button");o.className="sage-ai-prompt-button",o.textContent=e,o.style.display="none",o.addEventListener("click",()=>{console.log(`[WaitingUserReplyBoxManager] Prompt button ${t+1} clicked:`,e),this.onPromptCallback?(console.log("[WaitingUserReplyBoxManager] Calling prompt callback"),this.onPromptCallback(e)):console.warn("[WaitingUserReplyBoxManager] No prompt callback set"),this.hidePromptButtons()}),this.promptButtons.push(o),n.appendChild(o)}),this.waitingReplyBox.appendChild(n),this.continueButton=document.createElement("button"),this.continueButton.className="sage-ai-continue-button",this.continueButton.textContent="Continue",this.continueButton.style.display="none",this.continueButton.addEventListener("click",()=>{console.log("[WaitingUserReplyBoxManager] Continue button clicked"),this.onContinueCallback?(console.log("[WaitingUserReplyBoxManager] Calling continue callback"),this.onContinueCallback()):console.warn("[WaitingUserReplyBoxManager] No continue callback set"),this.hideContinueButton()}),this.waitingReplyBox.appendChild(this.continueButton),this.hide(),this.container.appendChild(this.waitingReplyBox),console.log("[WaitingUserReplyBoxManager] Waiting reply box added to container"),console.log("[WaitingUserReplyBoxManager] Initialization complete")}hide(){this.waitingReplyBox&&(this.waitingReplyBox.style.display="none")}show(e){console.log("[WaitingUserReplyBoxManager] show() called"),this.waitingReplyBox?(console.log("[WaitingUserReplyBoxManager] Setting waiting reply box display to block"),this.waitingReplyBox.style.display="block",e&&e.length>0&&this.updatePromptButtons(e),this.checkAndShowContinueButton()):console.warn("[WaitingUserReplyBoxManager] waitingReplyBox is null in show()")}setContinueCallback(e){console.log("[WaitingUserReplyBoxManager] Setting continue callback"),this.onContinueCallback=e}setPromptCallback(e){console.log("[WaitingUserReplyBoxManager] Setting prompt callback"),this.onPromptCallback=e}checkAndShowContinueButton(){console.log("[WaitingUserReplyBoxManager] checkAndShowContinueButton() called");const e=m.AppStateService.getState().chatContainer;if(console.log("[WaitingUserReplyBoxManager] chatContainer:",e),!e)return void console.warn("[WaitingUserReplyBoxManager] No chatContainer found");const t=e.chatWidget.chatHistoryManager.getCurrentThread();console.log("[WaitingUserReplyBoxManager] currentThread:",t),t?(console.log("[WaitingUserReplyBoxManager] continueButtonShown status:",t.continueButtonShown),t.continueButtonShown?console.log("[WaitingUserReplyBoxManager] Prompt buttons already shown in this thread, not showing again"):(console.log("[WaitingUserReplyBoxManager] Showing prompt buttons for the first time in this thread"),this.showPromptButtons(),t.continueButtonShown=!0,e.chatWidget.chatHistoryManager.updateCurrentThreadMessages(t.messages,t.contexts))):console.warn("[WaitingUserReplyBoxManager] No currentThread found")}showContinueButton(){console.log("[WaitingUserReplyBoxManager] showContinueButton() called"),this.continueButton?(console.log("[WaitingUserReplyBoxManager] Setting continue button display to inline-block"),this.continueButton.style.display="inline-block"):console.warn("[WaitingUserReplyBoxManager] continueButton is null in showContinueButton()")}hideContinueButton(){console.log("[WaitingUserReplyBoxManager] hideContinueButton() called"),this.continueButton?(console.log("[WaitingUserReplyBoxManager] Setting continue button display to none"),this.continueButton.style.display="none"):console.warn("[WaitingUserReplyBoxManager] continueButton is null in hideContinueButton()")}showPromptButtons(){console.log("[WaitingUserReplyBoxManager] showPromptButtons() called"),this.promptButtons.forEach((e,t)=>{e?(console.log(`[WaitingUserReplyBoxManager] Setting prompt button ${t+1} display to block`),e.style.display="block"):console.warn(`[WaitingUserReplyBoxManager] promptButton ${t+1} is null in showPromptButtons()`)})}hidePromptButtons(){console.log("[WaitingUserReplyBoxManager] hidePromptButtons() called"),this.promptButtons.forEach((e,t)=>{e?(console.log(`[WaitingUserReplyBoxManager] Setting prompt button ${t+1} display to none`),e.style.display="none"):console.warn(`[WaitingUserReplyBoxManager] promptButton ${t+1} is null in hidePromptButtons()`)})}updatePromptButtons(e){console.log("[WaitingUserReplyBoxManager] updatePromptButtons() called with prompts:",e);const t=Math.min(e.length,this.promptButtons.length);for(let n=0;n<this.promptButtons.length;n++){const o=this.promptButtons[n];o&&(n<t?(o.textContent=e[n],o.style.display="block",console.log(`[WaitingUserReplyBoxManager] Updated prompt button ${n+1} to: "${e[n]}"`)):o.style.display="none")}}}var Ot=n(6327);class Ft{constructor(){this.notebookTracker=null,this.contextCacheService=null,this.isInitialized=!1,this.kernelConnectionListeners=new Map,this.lastExecutionTime=0,this.EXECUTION_COOLDOWN_MS=1e3,this.pendingExecutions=new Map}static getInstance(){return Ft.instance||(Ft.instance=new Ft),Ft.instance}async initialize(e){this.isInitialized||(this.notebookTracker=e,this.contextCacheService=Ue.getInstance(),this.notebookTracker.currentChanged.connect(this.handleNotebookChange,this),this.notebookTracker.currentWidget&&this.setupKernelListener(this.notebookTracker.currentWidget),this.isInitialized=!0,console.log("[KernelExecutionListener] Initialized successfully"))}handleNotebookChange(e,t){t&&this.setupKernelListener(t)}setupKernelListener(e){var t,n,o,s;try{const i=e.sessionContext;if(!i)return void console.warn("[KernelExecutionListener] No session context available");const a=null===(n=null===(t=i.session)||void 0===t?void 0:t.kernel)||void 0===n?void 0:n.id;if(!a)return void console.warn("[KernelExecutionListener] No kernel available");this.kernelConnectionListeners.has(a)&&(null===(o=this.kernelConnectionListeners.get(a))||void 0===o||o(),this.kernelConnectionListeners.delete(a));const r=null===(s=i.session)||void 0===s?void 0:s.kernel;if(!r)return;console.log(`[KernelExecutionListener] Setting up execution listener for kernel: ${a}`);const l=r.requestExecute.bind(r);r.requestExecute=e=>{var t;const n=!0===e.silent;console.log(`[KernelExecutionListener] Execution request: silent=${n}, code preview: ${null===(t=e.code)||void 0===t?void 0:t.substring(0,50)}...`);const o=l(e);return o.msg&&o.msg.header&&o.msg.header.msg_id&&this.pendingExecutions.set(o.msg.header.msg_id,n),o};const c=()=>{const e=r.status;console.log(`[KernelExecutionListener] Kernel status changed to: ${e}`),"idle"===e&&this.handleExecutionComplete(a)};r.statusChanged.connect(c);const d=()=>{r.statusChanged.disconnect(c),this.pendingExecutions.clear(),console.log(`[KernelExecutionListener] Cleaned up listener for kernel: ${a}`)};this.kernelConnectionListeners.set(a,d);const h=()=>{var t;console.log("[KernelExecutionListener] Session changed, setting up new kernel listener"),null===(t=this.kernelConnectionListeners.get(a))||void 0===t||t(),this.kernelConnectionListeners.delete(a),setTimeout(()=>this.setupKernelListener(e),100)};i.sessionChanged.connect(h)}catch(e){console.warn("[KernelExecutionListener] Error setting up kernel listener:",e)}}handleExecutionComplete(e){const t=Date.now();if(t-this.lastExecutionTime<this.EXECUTION_COOLDOWN_MS)return void console.log("[KernelExecutionListener] Execution complete, but within cooldown period");let n=!1;if(e&&this.pendingExecutions.size>0){for(const[e,t]of this.pendingExecutions.entries())if(!t){n=!0,console.log(`[KernelExecutionListener] Found user (non-silent) execution: ${e}`);break}if(this.pendingExecutions.clear(),!n)return void console.log("[KernelExecutionListener] Only silent executions detected, skipping variable refresh")}this.lastExecutionTime=t,console.log("[KernelExecutionListener] User code execution completed, refreshing variables..."),this.contextCacheService?this.contextCacheService.refreshVariablesAfterExecution():console.warn("[KernelExecutionListener] ContextCacheService not available")}triggerVariableRefresh(){console.log("[KernelExecutionListener] Manually triggering variable refresh..."),this.handleExecutionComplete()}dispose(){this.kernelConnectionListeners.forEach(e=>e()),this.kernelConnectionListeners.clear(),this.pendingExecutions.clear(),this.notebookTracker&&this.notebookTracker.currentChanged.disconnect(this.handleNotebookChange,this),this.isInitialized=!1,console.log("[KernelExecutionListener] Disposed")}getDebugInfo(){return{isInitialized:this.isInitialized,activeListeners:this.kernelConnectionListeners.size,lastExecutionTime:this.lastExecutionTime,pendingExecutions:this.pendingExecutions.size}}}Ft.instance=null;var Vt=n(830),Wt=n(2311);function qt({title:e,description:t,content:n,isEditing:o,onSave:s,onClose:i,onTitleChange:a,onDescriptionChange:r,onContentChange:l}){return oe.createElement(Wt.Modal,{show:!0,onHide:i,size:"lg",backdrop:"static",keyboard:!0,onKeyDown:t=>{"Enter"===t.key&&(t.ctrlKey||t.metaKey)&&e.trim()&&n.trim()&&s()},dialogClassName:"sage-ai-custom-snippet-modal"},oe.createElement(Wt.Modal.Header,{closeButton:!0},oe.createElement(Wt.Modal.Title,null,o?"Edit Snippet":"Create New Snippet")),oe.createElement(Wt.Modal.Body,null,oe.createElement(Wt.Form,null,oe.createElement(Wt.Form.Group,{className:"mb-3"},oe.createElement(Wt.Form.Label,null,"Title"),oe.createElement(Wt.Form.Control,{type:"text",value:e,onChange:e=>a(e.target.value),placeholder:"Enter rule title...",autoFocus:!0})),oe.createElement(Wt.Form.Group,{className:"mb-3"},oe.createElement(Wt.Form.Label,null,"Description"),oe.createElement(Wt.Form.Control,{type:"text",value:t,onChange:e=>r(e.target.value),placeholder:"Brief description..."})),oe.createElement(Wt.Form.Group,{className:"mb-3"},oe.createElement(Wt.Form.Label,null,"Content"),oe.createElement(Wt.Form.Control,{as:"textarea",rows:10,value:n,onChange:e=>l(e.target.value),placeholder:"Your code, markdown, or text content..."})))),oe.createElement(Wt.Modal.Footer,null,oe.createElement(Wt.Button,{variant:"secondary",onClick:i},"Cancel"),oe.createElement(Wt.Button,{variant:"primary",onClick:s,disabled:!e.trim()||!n.trim(),title:(o?"Update":"Save")+" snippet (Ctrl+Enter)"},o?"Update":"Save")))}function zt({snippets:e,onView:t,onDelete:n,onCreateNew:o}){const[s,i]=oe.useState(null),[a,r]=oe.useState(null),[l,c]=oe.useState([]);oe.useEffect(()=>{const e=()=>{const e=m.AppStateService.getState();c(e.insertedSnippets)};e();const t=m.AppStateService.changes.subscribe(e);return()=>t.unsubscribe()},[]),oe.useEffect(()=>{if(s){const t=e.find(e=>e.id===s.id);!t||t.title===s.title&&t.content===s.content&&t.description===s.description?t||i(null):i(t)}},[e,s]),oe.useEffect(()=>{const e=e=>{const t=e.target;t.closest(".sage-ai-snippet-context-menu")||t.closest(".sage-ai-snippet-menu-btn")||r(null)};return document.addEventListener("click",e),()=>{document.removeEventListener("click",e)}},[]);const d=(e,n)=>{e.stopPropagation(),r(null),t(n)};return oe.createElement("div",{className:"sage-ai-snippet-list"},oe.createElement("div",{className:"sage-ai-snippet-list-container"},0===e.length?oe.createElement("div",{className:"sage-ai-snippet-empty"},oe.createElement("p",null,"No rules created yet."),oe.createElement("p",null,"Click the + button to create your first snippet.")):oe.createElement("div",{className:"sage-ai-snippet-items"},e.map(e=>oe.createElement("div",{key:e.id,className:"sage-ai-snippet-item-container"},oe.createElement("div",{className:"sage-ai-snippet-item "+((null==s?void 0:s.id)===e.id?"selected":""),onClick:()=>(e=>{i((null==s?void 0:s.id)===e.id?null:e)})(e)},oe.createElement("div",{className:"sage-ai-snippet-item-header"},oe.createElement("div",{className:"sage-ai-snippet-title-container"},oe.createElement("h5",null,e.title),l.includes(e.id)&&oe.createElement("svg",{className:"sage-ai-snippet-checkmark",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none"},oe.createElement("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}))),oe.createElement("div",{className:"sage-ai-snippet-item-actions"},oe.createElement("button",{className:"sage-ai-snippet-menu-btn",onClick:t=>((e,t)=>{e.stopPropagation(),r(a===t?null:t)})(t,e.id),title:"More options"},"⋯"),a===e.id&&oe.createElement("div",{className:"sage-ai-snippet-context-menu"},oe.createElement("button",{onClick:t=>d(t,e),className:"sage-ai-snippet-menu-item"},"Edit"),oe.createElement("button",{onClick:t=>((e,t)=>{e.stopPropagation(),r(null),n(t)})(t,e.id),className:"sage-ai-snippet-menu-item delete"},"Delete"))))))))),s&&oe.createElement("div",{className:"sage-ai-snippet-viewer-inline"},oe.createElement("div",{className:"sage-ai-snippet-viewer-toolbar"},oe.createElement("span",{className:"sage-ai-snippet-preview-label"},"Snippet Preview"),oe.createElement("div",{className:"sage-ai-snippet-viewer-actions"},oe.createElement("button",{className:"sage-ai-snippet-insert-btn "+(l.includes(s.id)?"sage-ai-snippet-remove-state":""),onClick:()=>(async e=>{try{l.includes(e.id)?(await m.AppStateService.removeInsertedSnippet(e.id),console.log("Snippet removed from context")):(await m.AppStateService.addInsertedSnippet(e.id),navigator.clipboard.writeText(e.content).then(()=>{console.log("Snippet content copied to clipboard and added to context")}).catch(e=>{console.error("Failed to copy snippet content:",e)}))}catch(e){console.error("Failed to update snippet in inserted list:",e)}})(s),title:l.includes(s.id)?"Remove from context":"Add to LLM Context"},l.includes(s.id)?"Remove":"Insert",oe.createElement("div",{className:"insert-icon-container"},oe.createElement(Ke.react,null))),oe.createElement("button",{className:"sage-ai-snippet-edit-btn",onClick:e=>d(e,s),title:"Edit snippet"},oe.createElement("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none"},oe.createElement("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),oe.createElement("path",{d:"m18.5 2.5 3 3L12 15l-4 1 1-4 9.5-9.5z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}))),oe.createElement("button",{className:"sage-ai-snippet-close-btn",onClick:()=>i(null),title:"Close preview"},oe.createElement("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none"},oe.createElement("path",{d:"M18 6L6 18M6 6l12 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}))))),oe.createElement("div",{className:"sage-ai-snippet-viewer-title-row"},oe.createElement("span",{className:"sage-ai-snippet-title-label"},"Title:"),oe.createElement("span",{className:"sage-ai-snippet-title-text"},s.title)),s.description&&oe.createElement("p",{className:"sage-ai-snippet-description"},s.description),oe.createElement("div",{className:"sage-ai-snippet-code-block"},oe.createElement("pre",{className:"sage-ai-snippet-code-content"},oe.createElement("code",null,s.content)))))}function Kt({state:e,onCreateNew:t,onSave:n,onEdit:o,onView:s,onDelete:i,onClose:a,onEnable:r,onTitleChange:l,onDescriptionChange:c,onContentChange:d}){const[h,u]=oe.useState("");if(!e.isVisible)return null;const p=e.isCreating||e.editingSnippet,g=e.snippets.filter(e=>{if(!h.trim())return!0;const t=h.toLowerCase();return e.title.toLowerCase().includes(t)||e.description.toLowerCase().includes(t)||e.content.toLowerCase().includes(t)});return oe.createElement("div",{className:"w-100 h-100"},oe.createElement("div",{className:"sage-ai-snippet-creation-panel"},oe.createElement("div",{className:"d-flex flex-column w-100 sage-ai-snippet-header-div"},oe.createElement("div",{className:"sage-ai-snippet-panel-header"},oe.createElement("h3",null,"Rules")),oe.createElement("div",{className:"d-flex flex-row"},oe.createElement("div",{className:"sage-ai-mention-search-container w-100",style:{marginRight:8}},oe.createElement("div",{style:{marginBottom:"4px"}},oe.createElement(qe.react,{className:"sage-ai-mention-search-icon"})),oe.createElement("input",{type:"text",className:"sage-ai-mention-search-input",placeholder:"Search rules...",value:h,onChange:e=>u(e.target.value)})),oe.createElement("button",{className:"sage-ai-snippet-create-btn",onClick:t,title:"Create New Snippet"},oe.createElement("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none"},oe.createElement("path",{d:"M12 5V19M5 12H19",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}))))),oe.createElement(zt,{snippets:g,onView:o,onDelete:i,onCreateNew:t})),p&&oe.createElement(qt,{title:e.title,description:e.description,content:e.content,isEditing:!!e.editingSnippet,onSave:n,onClose:a,onTitleChange:l,onDescriptionChange:c,onContentChange:d}))}class Gt extends _.ReactWidget{constructor(){super(),this._stateChanged=new se.Signal(this),this._state={isVisible:!0,snippets:[],isCreating:!1,editingSnippet:null,viewingSnippet:null,title:"",description:"",content:""},this.addClass("sage-ai-snippet-creation-widget"),this.id="sage-ai-snippet-creation",this.title.icon=Fe,this.title.closable=!0,this._state.isVisible||this.addClass("hidden"),this.loadSnippets()}get stateChanged(){return this._stateChanged}render(){return oe.createElement(Kt,{state:this._state,onCreateNew:this.handleCreateNew.bind(this),onSave:this.handleSave.bind(this),onEdit:this.handleEdit.bind(this),onView:this.handleView.bind(this),onDelete:this.handleDelete.bind(this),onClose:this.handleClose.bind(this),onEnable:this.handleEnable.bind(this),onTitleChange:this.handleTitleChange.bind(this),onDescriptionChange:this.handleDescriptionChange.bind(this),onContentChange:this.handleContentChange.bind(this)})}async loadSnippets(){try{await m.AppStateService.loadSnippets();const e=m.AppStateService.getSnippets();this._state={...this._state,snippets:e},this._stateChanged.emit(this._state),this.update()}catch(e){console.error("[SnippetCreationWidget] Failed to load snippets:",e)}}generateSnippetId(){return m.AppStateService.generateSnippetId()}handleCreateNew(){this._state={...this._state,isCreating:!0,editingSnippet:null,viewingSnippet:null,title:"",description:"",content:""},this._stateChanged.emit(this._state),this.update()}async handleSave(){if(!this._state.title.trim()||!this._state.content.trim())return;const e=(new Date).toISOString();if(this._state.editingSnippet)console.log("[SnippetCreationWidget] Updating snippet with ID:",this._state.editingSnippet.id),console.log("[SnippetCreationWidget] New content:",{title:this._state.title.trim(),description:this._state.description.trim(),content:this._state.content.trim()}),await m.AppStateService.updateSnippet(this._state.editingSnippet.id,{title:this._state.title.trim(),description:this._state.description.trim(),content:this._state.content.trim(),updatedAt:e}),console.log("[SnippetCreationWidget] Snippet updated successfully"),this._state={...this._state,snippets:m.AppStateService.getSnippets(),isCreating:!1,editingSnippet:null,title:"",description:"",content:""};else{console.log("[SnippetCreationWidget] Creating new snippet");const t={id:this.generateSnippetId(),title:this._state.title.trim(),description:this._state.description.trim(),content:this._state.content.trim(),createdAt:e,updatedAt:e};await m.AppStateService.addSnippet(t),this._state={...this._state,snippets:m.AppStateService.getSnippets(),isCreating:!1,title:"",description:"",content:""}}this._stateChanged.emit(this._state),this.update()}handleEdit(e){console.log("[SnippetCreationWidget] Editing snippet:",e),this._state={...this._state,isCreating:!1,editingSnippet:e,title:e.title,description:e.description,content:e.content},this._stateChanged.emit(this._state),this.update()}handleView(e){this.handleEdit(e)}async handleDelete(e){confirm("Are you sure you want to delete this snippet?")&&(await m.AppStateService.removeSnippet(e),this._state={...this._state,snippets:m.AppStateService.getSnippets(),editingSnippet:null},this._stateChanged.emit(this._state),this.update())}handleClose(){this._state={...this._state,isCreating:!1,editingSnippet:null,title:"",description:"",content:""},this._stateChanged.emit(this._state),this.update()}handleEnable(e){console.log("[SnippetCreationWidget] Enable snippet:",e.title)}handleTitleChange(e){this._state={...this._state,title:e},this._stateChanged.emit(this._state),this.update()}handleDescriptionChange(e){this._state={...this._state,description:e},this._stateChanged.emit(this._state),this.update()}handleContentChange(e){this._state={...this._state,content:e},this._stateChanged.emit(this._state),this.update()}show(){this._state={...this._state,isVisible:!0},this.removeClass("hidden"),this._stateChanged.emit(this._state),this.update()}hide(){this._state={...this._state,isVisible:!1},this.addClass("hidden"),this._stateChanged.emit(this._state),this.update()}getIsVisible(){return this._state.isVisible}getState(){return{...this._state}}getSnippets(){return[...this._state.snippets]}onCloseRequest(){this.dispose()}dispose(){this.isDisposed||(this._state={isVisible:!1,snippets:[],isCreating:!1,editingSnippet:null,viewingSnippet:null,title:"",description:"",content:""},this.addClass("hidden"),this._stateChanged.emit(this._state),super.dispose())}}class Jt{static getInstance(){return Jt._instance||(Jt._instance=new Jt),Jt._instance}constructor(){this.hasActiveCellFn=null,this.currentRequestId=0}async initialize(){console.log("[TabCompletionService] Initializing...")}setActiveCellChecker(e){this.hasActiveCellFn=e}isReady(){return!0}canSuggestSync(e,t){const{AppStateService:o}=n(6209);if(!o.getClaudeSettings().tabAutocompleteEnabled)return!1;if(this.hasActiveCellFn&&!this.hasActiveCellFn())return!1;const s=e.slice(-1),i=t.slice(0,1);return!/\w/.test(s)||!/\w/.test(i)}buildPrompt(e,t){return{system:["You are a code completion assistant. Generate ONLY the code that should appear after the <cursor position>.","CRITICAL: Output raw code only - no explanations, comments, or markdown.","CRITICAL: Your output REPLACES everything after <cursor position>. The text after <cursor position> shows what will be OVERWRITTEN by your output.","CRITICAL: Do NOT concatenate with existing text after cursor. Your output completely replaces the suffix text.","CRITICAL: If cursor is at end of complete word/identifier followed by whitespace or newline, DO NOT suggest text that would create invalid syntax.","Complete 1-10 tokens max. Output a few meaningful keywords. Do not make massive changes. If unsure or code is complete, output nothing.","","REPLACEMENT RULES:","- Everything after <cursor position> gets DELETED and replaced with your output",'- If cursor is after "def funcname" and suffix starts with newline/whitespace, suggest function signature completion like "(args):"',"- If cursor is after complete identifier + space/newline, do NOT suggest unrelated code that would break syntax","- When in doubt about syntax validity, output nothing","","EXAMPLES:",'Before: "def dfs<cursor position>\\n visited = set()" → Output: "(graph, start, visited):\\n if visited is None:" (replaces everything after cursor)','Before: "if x > 0:<cursor position>" → Output: "\\n return True"','Before: "print(<cursor position>)" → Output: ""','Before: "def func<cursor position>tion():" → Output: "():\\n pass" (replaces "tion():")'].join("\n"),user:e+"<cursor position>"+t}}async getCompletion(e,t){const o=++this.currentRequestId;try{if(!this.canSuggestSync(e,t))return null;if(o!==this.currentRequestId)return null;const{system:s,user:i}=this.buildPrompt(e,t),{ServiceFactory:a,ServiceProvider:r}=n(435),l=a.createService(r.ANTHROPIC);if(!await l.initialize())return null;if(o!==this.currentRequestId)return null;const c=await l.sendEphemeralMessage(i,s,"claude-3-5-haiku-latest",void 0,{maxTokens:25,temperature:0});return o!==this.currentRequestId?null:c||null}catch(e){return console.warn("[TabCompletionService] getCompletion error:",e),null}}}class Yt{constructor(){this.completionText="",this.editor=null,this.onAccept=null,this.onReject=null,this.originalCursor=null,this.replacementEndPos=null,this.ghostAppendConfig=k.StateEffect.appendConfig.of([]),this.setGhostEffect=k.StateEffect.define(),this.clearGhostEffect=k.StateEffect.define(),this.ghostField=k.StateField.define({create:()=>b.Decoration.none,update:(e,t)=>{for(const e of t.effects){if(e.is(this.setGhostEffect))return e.value;if(e.is(this.clearGhostEffect))return b.Decoration.none}return t.docChanged?b.Decoration.none:e.map(t.changes)},provide:e=>b.EditorView.decorations.from(e)}),this.ghostCompartment=new k.Compartment,this.ghostExtension=null,this.isGhostVisible=!1,this.clearQueue=Promise.resolve()}showCompletion(e,t,n,o,s){this.hideCompletion(),this.editor=e,this.completionText=t,this.onAccept=n,this.onReject=o,this.replacementEndPos=s||null;const i=e.getCursorPosition();this.originalCursor={line:i.line,column:i.column};const a=this.getEditorView();a?(this.ensureGhostExtension(a),this.clearQueue=this.clearQueue.then(()=>new Promise(n=>{requestAnimationFrame(()=>{const o=this.computeOffsetFromPosition(e,i);let s=[b.Decoration.widget({widget:new Zt(t),side:1}).range(o)];if(this.replacementEndPos){const t=this.computeOffsetFromPosition(e,this.replacementEndPos);t>o&&s.push(b.Decoration.mark({class:"sage-completion-replacement",attributes:{style:"opacity: 0.3; text-decoration: line-through;"}}).range(o,t))}const r=b.Decoration.set(s);a.dispatch({effects:this.setGhostEffect.of(r)}),this.isGhostVisible=!0,console.log("[InlineCompletionWidget] Showing inline completion (ghost) with replacement:",t),n()})}))):console.error("[InlineCompletionWidget] CodeMirror view not found")}getEditorView(){var e,t,n,o;const s=this.editor;return s&&null!==(o=null!==(n=null!==(t=null!==(e=s.editor)&&void 0!==e?e:s._editor)&&void 0!==t?t:s.cm)&&void 0!==n?n:null)&&void 0!==o?o:null}ensureGhostExtension(e){this.ghostExtension||(this.ghostExtension=this.ghostCompartment.of([this.ghostField]),e.dispatch({effects:k.StateEffect.appendConfig.of(this.ghostExtension)}))}computeOffsetFromPosition(e,t){const n=e.model.sharedModel.getSource().split("\n");let o=0;for(let e=0;e<t.line;e++)void 0!==n[e]&&(o+=n[e].length+1);return o+=t.column,o}hideCompletion(){const e=this.getEditorView();e&&(this.clearQueue=this.clearQueue.then(()=>new Promise(t=>{requestAnimationFrame(()=>{e.dispatch({effects:this.clearGhostEffect.of(null)}),t()})}))),this.isGhostVisible=!1,console.log("[InlineCompletionWidget] Cleared ghost overlay"),this.completionText="",this.onAccept=null,this.onReject=null,this.replacementEndPos=null}acceptCompletion(){if(this.editor&&this.originalCursor&&this.completionText)try{const e=this.computeOffsetFromPosition(this.editor,this.originalCursor),t=this.getEditorView();let n=e;if(this.replacementEndPos&&(n=this.computeOffsetFromPosition(this.editor,this.replacementEndPos)),t){const o=e+this.completionText.length;t.dispatch({changes:{from:e,to:n,insert:this.completionText},selection:{anchor:o}})}else{const t=this.editor.model,o=t.sharedModel.getSource(),s=o.slice(0,e)+this.completionText+o.slice(n);t.sharedModel.setSource(s);const i=this.completionText.split("\n");let a;if(1===i.length)a={line:this.originalCursor.line,column:this.originalCursor.column+this.completionText.length};else{const e=i[i.length-1].length;a={line:this.originalCursor.line+i.length-1,column:e}}requestAnimationFrame(()=>{this.editor.setCursorPosition(a)})}console.log("[InlineCompletionWidget] Completion accepted, text replaced from",e,"to",n)}catch(e){console.error("[InlineCompletionWidget] Error accepting completion:",e)}this.onAccept&&this.onAccept(),this.hideCompletion(),this.originalCursor=null,this.replacementEndPos=null}rejectCompletion(){this.onReject&&this.onReject(),this.hideCompletion(),this.originalCursor=null,this.replacementEndPos=null}isCompletionShowing(){return this.isGhostVisible}getCompletionMark(){return null}clearCompletionMark(){this.isGhostVisible=!1}}class Zt extends b.WidgetType{constructor(e){super(),this.text=e}toDOM(){const e=document.createElement("span");return e.textContent=this.text,e.style.opacity="0.45",e.style.whiteSpace="pre",e}}class Xt{static getInstance(){return Xt._instance||(Xt._instance=new Xt),Xt._instance}constructor(){this.notebookTracker=null,this.activeEditor=null,this.attachedEditors=new WeakSet,this.attachedScrollHosts=new WeakSet,this.attachedKeydownHosts=new WeakSet,this.attachedKeydownNodes=new WeakSet,this.cursorIdleTimeoutId=null,this.lastCursorPosition=null,this.editorHasFocus=!1,this.tabCompletionService=Jt.getInstance(),this.completionWidget=new Yt}initialize(e){var t,n;this.notebookTracker=e,this.tabCompletionService.setActiveCellChecker(()=>{var t,n;return!(!e.activeCell&&!(null===(n=null===(t=e.currentWidget)||void 0===t?void 0:t.content)||void 0===n?void 0:n.activeCell))}),e.widgetAdded.connect((e,t)=>{setTimeout(()=>{var e;const n=null===(e=null==t?void 0:t.content)||void 0===e?void 0:e.activeCell;(null==n?void 0:n.editor)&&this.connectToEditor(n.editor)},0)}),e.activeCellChanged.connect((e,t)=>{this.activeEditor&&this.disconnectFromEditor(),t&&t.editor&&this.connectToEditor(t.editor)}),e.currentChanged.connect((e,t)=>{setTimeout(()=>{var e;const n=null===(e=null==t?void 0:t.content)||void 0===e?void 0:e.activeCell;t&&n&&n.editor&&this.connectToEditor(n.editor)},100)}),e.activeCell&&e.activeCell.editor&&this.connectToEditor(e.activeCell.editor);const o=null===(n=null===(t=e.currentWidget)||void 0===t?void 0:t.content)||void 0===n?void 0:n.activeCell;o&&o.editor&&this.connectToEditor(o.editor),this.tryInitialConnect(e)}tryInitialConnect(e){let t=0;const n=setInterval(()=>{var o,s,i,a;if(t++,this.activeEditor)return void clearInterval(n);const r=(null===(i=null===(s=null===(o=e.currentWidget)||void 0===o?void 0:o.content)||void 0===s?void 0:s.activeCell)||void 0===i?void 0:i.editor)||(null===(a=e.activeCell)||void 0===a?void 0:a.editor);r?(this.connectToEditor(r),clearInterval(n)):t>=20&&clearInterval(n)},150)}isEditorFocused(){var e,t;if(!this.activeEditor)return!1;try{const n=null!==(t=null!==(e=this.activeEditor.editor)&&void 0!==e?e:this.activeEditor._editor)&&void 0!==t?t:this.activeEditor.cm,o=null==n?void 0:n.dom;if(o)return o.contains(document.activeElement)||o===document.activeElement;const s=this.activeEditor.host;if(s)return s.contains(document.activeElement)||s===document.activeElement}catch(e){console.warn("[CompletionManager] Error checking editor focus:",e)}return!1}connectToEditor(e){var t,n;if(this.activeEditor=e,this.lastCursorPosition=e.getCursorPosition(),this.editorHasFocus=this.isEditorFocused(),this.attachedEditors.has(e))return;this.attachedEditors.add(e),e.model.sharedModel.changed.connect(()=>{this.handleTextChange()}),e.model.selections.changed.connect(()=>{const t=e.getCursorPosition(),n=this.lastCursorPosition,o=!n||t.line!==n.line||t.column!==n.column;this.lastCursorPosition=t,o&&(this.completionWidget.isCompletionShowing()&&this.completionWidget.hideCompletion(),this.resetCursorIdleTimer())});const o=e=>{this.attachedKeydownNodes.has(e)||(e.addEventListener("keydown",async e=>{const t=e;return"Tab"!==t.key||t.shiftKey?"Escape"===t.key&&this.completionWidget.isCompletionShowing()?(t.preventDefault(),t.stopPropagation(),void this.completionWidget.rejectCompletion()):void 0:this.completionWidget.isCompletionShowing()?(t.preventDefault(),t.stopPropagation(),void this.completionWidget.acceptCompletion()):void this.handleTabKey()},{capture:!0}),this.attachedKeydownNodes.add(e))};try{const t=e.host;t&&!this.attachedKeydownHosts.has(t)&&(o(t),this.attachedKeydownHosts.add(t))}catch(e){console.error("[CompletionManager] Error setting up key listeners on host:",e)}try{const s=null!==(n=null!==(t=e.editor)&&void 0!==t?t:e._editor)&&void 0!==n?n:e.cm,i=null==s?void 0:s.dom;if(i){o(i);const e=()=>{this.editorHasFocus=!0},t=()=>{this.editorHasFocus=!1,this.completionWidget.isCompletionShowing()&&this.completionWidget.hideCompletion(),this.clearCursorIdleTimer()};i.addEventListener("focus",e,!0),i.addEventListener("blur",t,!0)}}catch(e){console.error("[CompletionManager] Error setting up key listeners on view DOM:",e)}}disconnectFromEditor(){this.activeEditor&&(this.completionWidget.hideCompletion(),this.clearCursorIdleTimer(),this.editorHasFocus=!1,setTimeout(()=>{this.activeEditor=null},50))}getCurrentLinePrefixSuffix(){if(!this.activeEditor)return{prefix:"",suffix:""};const e=this.activeEditor.getCursorPosition(),t=this.activeEditor.model.sharedModel.getSource().split("\n"),n=Math.max(0,e.line-10),o=Math.min(t.length-1,e.line+1),s=t.slice(n,e.line),i=(t[e.line]||"").substring(0,e.column);s.push(i);const a=s.join("\n"),r=[(t[e.line]||"").substring(e.column),...t.slice(e.line+1,o+1)].join("\n"),l=Math.min(t.length-1,e.line+1);return{prefix:a,suffix:r,replacementEndPos:{line:l,column:(t[l]||"").length}}}async handleTabKey(){if(!this.activeEditor)return;if(!this.editorHasFocus&&!this.isEditorFocused())return;const{prefix:e,suffix:t,replacementEndPos:n}=this.getCurrentLinePrefixSuffix(),o=await this.tabCompletionService.getCompletion(e,t);o&&this.completionWidget.showCompletion(this.activeEditor,o,()=>this.acceptCompletion(o,n),()=>this.rejectCompletion(),n)}async handleCursorIdle(){if(!this.activeEditor)return;if(this.completionWidget.isCompletionShowing())return;if(!this.editorHasFocus&&!this.isEditorFocused())return;const{prefix:e,suffix:t,replacementEndPos:n}=this.getCurrentLinePrefixSuffix();if(!this.tabCompletionService.canSuggestSync(e,t))return;const o=await this.tabCompletionService.getCompletion(e,t);if(o){if(!this.editorHasFocus&&!this.isEditorFocused())return;this.completionWidget.showCompletion(this.activeEditor,o,()=>this.acceptCompletion(o,n),()=>this.rejectCompletion(),n)}}resetCursorIdleTimer(){this.clearCursorIdleTimer(),this.cursorIdleTimeoutId=window.setTimeout(()=>{this.handleCursorIdle()},1e3)}clearCursorIdleTimer(){null!==this.cursorIdleTimeoutId&&(clearTimeout(this.cursorIdleTimeoutId),this.cursorIdleTimeoutId=null)}async handleTextChange(){this.activeEditor,this.completionWidget.isCompletionShowing()&&this.completionWidget.hideCompletion(),this.resetCursorIdleTimer()}acceptCompletion(e,t){}rejectCompletion(){this.completionWidget.hideCompletion()}}function Qt({isVisible:e,currentDiff:t,totalDiffs:n,isRunContext:o,onNavigatePrevious:s,onNavigateNext:i,onRejectAll:a,onAcceptAll:r,onAcceptAndRunAll:l}){return e&&0!==n?oe.createElement("div",{className:"sage-ai-diff-navigation-floating-content"},oe.createElement("div",{className:"sage-ai-diff-navigation-navigation-section"},oe.createElement("button",{className:"sage-ai-diff-navigation-nav-button sage-ai-diff-navigation-prev-button",onClick:s,title:"Previous cell"},oe.createElement(L.react,{className:"sage-ai-diff-navigation-nav-icon"})),oe.createElement("span",{className:"sage-ai-diff-navigation-counter-display"},t," / ",n),oe.createElement("button",{className:"sage-ai-diff-navigation-nav-button sage-ai-diff-navigation-next-button",onClick:i,title:"Next cell"},oe.createElement(R.react,{className:"sage-ai-diff-navigation-nav-icon"}))),oe.createElement("div",{className:"sage-ai-diff-navigation-button-section"},oe.createElement("button",{className:"sage-ai-diff-navigation-action-button sage-ai-diff-navigation-reject-button",onClick:a},oe.createElement(P.react,{className:"sage-ai-diff-navigation-action-icon"}),oe.createElement("span",null,n>1?"Reject All":"Reject")),oe.createElement("button",{className:"sage-ai-diff-navigation-action-button sage-ai-diff-navigation-approve-button",onClick:r},oe.createElement(B.react,{className:"sage-ai-diff-navigation-action-icon"}),oe.createElement("span",null,n>1?"Approve All":"Approve")),o&&oe.createElement("button",{className:"sage-ai-diff-navigation-action-button sage-ai-diff-navigation-accept-run-button",onClick:l},oe.createElement(j.react,{className:"sage-ai-diff-navigation-action-icon"}),oe.createElement("span",null,n>1?"Run All":"Run")))):null}class en extends _.ReactWidget{constructor(){super(),this.currentNotebookId=null,this.subscriptions=[],this.navigateToPrevious=()=>{if(this._state.totalDiffs>0){const e=this._state.currentDiff<=1?this._state.totalDiffs:this._state.currentDiff-1;if(this._state={...this._state,currentDiff:e},this.update(),e>0&&e<=this._state.pendingDiffs.length){const t=this._state.pendingDiffs[e-1];t&&t.cellId&&m.AppStateService.getNotebookTools().scrollToCellById(t.cellId)}}},this.navigateToNext=()=>{if(this._state.totalDiffs>0){const e=this._state.currentDiff>=this._state.totalDiffs?1:this._state.currentDiff+1;if(this._state={...this._state,currentDiff:e},this.update(),e>0&&e<=this._state.pendingDiffs.length){const t=this._state.pendingDiffs[e-1];t&&t.cellId&&m.AppStateService.getNotebookTools().scrollToCellById(t.cellId)}}},this.rejectAll=async()=>{if(0!==this._state.pendingDiffs.length){console.log(`Rejecting ${this._state.pendingDiffs.length} diffs`);for(const e of this._state.pendingDiffs)C.updateDiffState(e.cellId,!1,e.notebookId);try{await m.AppStateService.getNotebookDiffManager().diffApprovalDialog.rejectAll()}catch(e){console.warn("Error calling diffApprovalDialog.rejectAll():",e)}}else console.log("No pending diffs to reject")},this.acceptAll=async()=>{try{await m.AppStateService.getNotebookDiffManager().diffApprovalDialog.approveAll()}catch(e){console.warn("Error calling diffApprovalDialog.approveAll():",e)}},this.acceptAndRunAll=async()=>{if(0!==this._state.pendingDiffs.length)if(console.log(`Processing ${this._state.pendingDiffs.length} diffs in ${this._state.isRunContext?"run":"approve"} context`),this._state.isRunContext){for(const e of this._state.pendingDiffs)if(!e.userDecision)try{await m.AppStateService.getNotebookDiffManager().diffApprovalDialog.runCell(e.cellId)}catch(t){console.warn(`Error calling diffApprovalDialog.runCell(${e.cellId}):`,t)}}else{for(const e of this._state.pendingDiffs)C.updateDiffState(e.cellId,!0,e.notebookId);try{await m.AppStateService.getNotebookDiffManager().diffApprovalDialog.approveAll()}catch(e){console.warn("Error calling diffApprovalDialog.approveAll():",e)}}else console.log("No pending diffs to accept")},this.id="sage-ai-diff-navigation-widget",this.addClass("sage-ai-diff-navigation-widget"),this.addClass("jp-Widget"),this.addClass("hidden"),this.title.label="Diff Navigation",this._state={isVisible:!1,currentDiff:0,totalDiffs:0,pendingDiffs:[],isRunContext:!1},this.setupDiffStateSubscriptions()}setupDiffStateSubscriptions(){const e=C.diffState$.subscribe(e=>{const t=Array.from(e.pendingDiffs.values()),n=this.filterUnresolvedDiffs(t,this.currentNotebookId),o=n.length>0,s=o?Math.max(1,this._state.currentDiff):0;this._state={...this._state,totalDiffs:n.length,pendingDiffs:n,isVisible:this._state.isVisible&&o,currentDiff:s},this.updateVisibility(),this.update()});this.subscriptions.push(e);const t=C.allDiffsResolved$.subscribe(({notebookId:e})=>{const t=C.getCurrentState(),n=Array.from(t.pendingDiffs.values());0===this.filterUnresolvedDiffs(n,this.currentNotebookId).length&&(this._state={...this._state,isVisible:!1,currentDiff:0,totalDiffs:0,pendingDiffs:[]},this.updateVisibility(),this.update())});this.subscriptions.push(t)}dispose(){this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],super.dispose()}filterUnresolvedDiffs(e,t){return e.filter(e=>{const n=!t||e.notebookId===t,o=void 0===e.approved&&(!e.userDecision||null===e.userDecision);return n&&o})}updateVisibility(){this._state.isVisible&&this._state.totalDiffs>0?this.removeClass("hidden"):this.addClass("hidden")}setNotebookId(e){this.currentNotebookId=e;const t=C.getCurrentState(),n=Array.from(t.pendingDiffs.values()),o=this.filterUnresolvedDiffs(n,e);this._state={...this._state,totalDiffs:o.length,pendingDiffs:o,isVisible:o.length>0,currentDiff:o.length>0?Math.max(1,this._state.currentDiff):0},this.updateVisibility(),this.update()}updateCounter(e,t){this._state={...this._state,currentDiff:e,totalDiffs:t},this.update()}setRunContext(e){this._state.isRunContext!==e&&(this._state={...this._state,isRunContext:e},this.update())}refreshFromDiffState(e,t){if(void 0!==e)this.setNotebookId(e);else{const e=C.getCurrentState(),n=Array.from(e.pendingDiffs.values()),o=this.filterUnresolvedDiffs(n,this.currentNotebookId);this._state={...this._state,totalDiffs:o.length,pendingDiffs:o,isVisible:o.length>0,currentDiff:o.length>0?Math.max(1,this._state.currentDiff):0,isRunContext:!!t},this.updateVisibility(),this.update()}}showPendingDiffs(e,t){void 0!==e&&(this.currentNotebookId=e),void 0!==t&&(this._state={...this._state,isRunContext:t});const n=C.getCurrentState(),o=Array.from(n.pendingDiffs.values()),s=this.filterUnresolvedDiffs(o,this.currentNotebookId);this._state={...this._state,totalDiffs:s.length,pendingDiffs:s,isVisible:s.length>0,currentDiff:s.length>0?Math.max(1,this._state.currentDiff):0,isRunContext:t||this._state.isRunContext},this.updateVisibility(),this.update()}hidePendingDiffs(){this._state={...this._state,isVisible:!1,currentDiff:0,totalDiffs:0,pendingDiffs:[]},this.updateVisibility(),this.update()}render(){return oe.createElement(Qt,{isVisible:this._state.isVisible,currentDiff:this._state.currentDiff,totalDiffs:this._state.totalDiffs,isRunContext:this._state.isRunContext,onNavigatePrevious:this.navigateToPrevious,onNavigateNext:this.navigateToNext,onRejectAll:this.rejectAll,onAcceptAll:this.acceptAll,onAcceptAndRunAll:this.acceptAndRunAll})}}var tn,nn=n(2652);!function(e){e.IDLE="idle",e.GENERATING="generating",e.USING_TOOL="using_tool",e.DIFF="diff",e.RUN_KERNEL="run_kernel"}(tn||(tn={}));const on=new _.LabIcon({name:"sage-agent-internal:state-menu-icon",svgstr:'<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M6 12L10 8L6 4" stroke="#949494" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>\n'}),sn=new _.LabIcon({name:"sage-agent-internal:state-menu-close-icon",svgstr:'<svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M4 6.5L8 10.5L12 6.5" stroke="#949494" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>\n'}),an=new _.LabIcon({name:"sage-agent-internal:run-cell-icon",svgstr:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">\n <path d="M4 2.91583C4 2.52025 4.43762 2.28133 4.77038 2.49524L12.6791 7.57941C12.9852 7.77623 12.9852 8.22377 12.6791 8.42059L4.77038 13.5048C4.43762 13.7187 4 13.4798 4 13.0842V2.91583Z" fill="#3B82F6" stroke="#3B82F6" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M13.1018 5.35787L6.45639 9.55022L5.34214 7.88071" stroke="#1A1A1A" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>'}),rn=new _.LabIcon({name:"sage-agent-internal:warning-icon",svgstr:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <circle cx="12" cy="17" r="1" fill="#949494"></circle> <path d="M12 10L12 14" stroke="#949494" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> <path d="M3.44722 18.1056L10.2111 4.57771C10.9482 3.10361 13.0518 3.10362 13.7889 4.57771L20.5528 18.1056C21.2177 19.4354 20.2507 21 18.7639 21H5.23607C3.7493 21 2.78231 19.4354 3.44722 18.1056Z" stroke="#949494" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path> </g></svg>'}),ln=()=>oe.createElement("div",{className:"sage-ai-diff-spinner",style:{display:"flex",alignItems:"center",justifyContent:"center",width:"16px",height:"16px",border:"2px solid #f3f3f3",borderTop:"2px solid #3498db",borderRadius:"50%",animation:"spin 1s linear infinite"}});function cn({diff:e,showActionsOnHover:t=!1}){const[n,o]=oe.useState(e);oe.useEffect(()=>{const t=C.getCellStateChanges$(e.cellId).subscribe(t=>{t&&t.cellId===e.cellId&&o(n=>{const o=C.getCurrentState().pendingDiffs.get(e.cellId);return{...n,approved:t.approved,userDecision:null==o?void 0:o.userDecision,runResult:null==o?void 0:o.runResult}})}),n=C.diffState$.subscribe(t=>{const n=t.pendingDiffs.get(e.cellId);n&&o(e=>({...e,userDecision:n.userDecision,runResult:n.runResult,approved:n.approved}))});return()=>{t.unsubscribe(),n.unsubscribe()}},[e.cellId]);const{added:s,removed:i}=(e=>{var t,n;if("add"===e.type)return{added:(null===(t=e.newContent)||void 0===t?void 0:t.split("\n").length)||0,removed:0};if("remove"===e.type)return{added:0,removed:(null===(n=e.originalContent)||void 0===n?void 0:n.split("\n").length)||0};if("edit"===e.type){const t=St.calculateDiff(e.originalContent||"",e.newContent||"");return{added:t.filter(e=>"added"===e.type).length,removed:t.filter(e=>"removed"===e.type).length}}return{added:0,removed:0}})(n),a=null!==n.userDecision&&void 0!==n.userDecision,r="run"===n.userDecision&&!n.runResult,l="edit"===n.type;return oe.useEffect(()=>{if(!document.querySelector("#sage-ai-spinner-animation")){const e=document.createElement("style");e.id="sage-ai-spinner-animation",e.textContent="\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n ",document.head.appendChild(e)}},[]),oe.createElement("div",{className:"sage-ai-diff-item "+(t?"sage-ai-diff-item-hover-actions":""),onClick:()=>{m.AppStateService.getNotebookTools().scrollToCellById(n.cellId)}},oe.createElement("div",{className:"sage-ai-diff-info"},oe.createElement("span",{className:`sage-ai-diff-operation sage-ai-diff-${n.type}`},(e=>{switch(e){case"add":return"+";case"edit":return"~";case"remove":return"−";default:return"?"}})(n.type)),oe.createElement("span",{className:"sage-ai-diff-summary"},n.cellId),oe.createElement("div",{className:"sage-ai-diff-changes"},s>0&&oe.createElement("span",{className:"sage-ai-diff-added"},"+",s),i>0&&oe.createElement("span",{className:"sage-ai-diff-removed"},"−",i),a&&oe.createElement("span",{className:`sage-ai-diff-decision sage-ai-diff-decision-${n.userDecision}`},"approved"===n.userDecision?"✓":"rejected"===n.userDecision?"✕":"run"===n.userDecision?oe.createElement(an.react,{className:"fix_run_cell_size"}):"?"))),a&&l&&oe.createElement("div",{className:"sage-ai-diff-actions"},oe.createElement("button",{onClick:()=>{m.AppStateService.getNotebookDiffManager().reapplyDiff(n)},className:"sage-ai-diff-btn sage-ai-diff-reapply"},oe.createElement(A.react,null))),!a&&!r&&oe.createElement("div",{className:"sage-ai-diff-actions"},oe.createElement("button",{className:"sage-ai-diff-btn sage-ai-diff-reject",onClick:()=>{C.updateDiffState(n.cellId,!1,n.notebookId),m.AppStateService.getNotebookDiffManager().diffApprovalDialog.rejectCell(n.cellId)},disabled:a,title:"Reject this change"},"✕"),oe.createElement("button",{className:"sage-ai-diff-btn sage-ai-diff-approve",onClick:()=>{C.updateDiffState(n.cellId,!0,n.notebookId),m.AppStateService.getNotebookDiffManager().diffApprovalDialog.approveCell(n.cellId)},disabled:a,title:"Approve this change"},"✓"),oe.createElement("button",{className:"sage-ai-diff-btn sage-ai-diff-run",onClick:()=>{m.AppStateService.getNotebookDiffManager().diffApprovalDialog.runCell(n.cellId)},disabled:a,title:"Apply this change and run the cell immediately"},oe.createElement(an.react,null))),r&&oe.createElement("div",{className:"sage-ai-diff-actions"},oe.createElement(ln,null)))}function dn({isVisible:e,state:t,text:n,toolName:o,diffs:s,waitingForUser:i,isRunContext:a,onRunClick:r,onRejectClick:l}){const[c,d]=oe.useState(!1),[h,u]=oe.useState(!1),[f,v]=oe.useState(s||[]);oe.useEffect(()=>{const e=C.diffState$.subscribe(e=>{const t=Array.from(e.pendingDiffs.values());if(v(t),t.length>0){const e=t.every(e=>"approved"===e.userDecision||"rejected"===e.userDecision||"run"===e.userDecision||!0===e.approved||!1===e.approved);u(e)}else u(!1)});return()=>e.unsubscribe()},[]),oe.useEffect(()=>{if(s&&s.length>0){v(s);const e=s.every(e=>"approved"===e.userDecision||"rejected"===e.userDecision||"run"===e.userDecision||!0===e.approved||!1===e.approved);u(e)}else s&&0===s.length&&(v([]),u(!1))},[s]);const b=f.length>0?f:s||[];if(!e)return null;if(t===tn.IDLE)return null;if(t===tn.GENERATING)return oe.createElement("div",{className:"sage-ai-llm-state-display sage-ai-generating",style:{display:"flex"}},oe.createElement("div",{className:"sage-ai-llm-state-content"},i&&oe.createElement("div",{className:"sage-ai-waiting-for-user"}),!i&&oe.createElement("div",{className:"sage-ai-blob-loader"}),oe.createElement("span",{className:"sage-ai-llm-state-text"},n)),!i&&oe.createElement("button",{className:"sage-ai-llm-state-stop-button",onClick:()=>{var e;null===(e=m.AppStateService.getChatContainerSafe())||void 0===e||e.chatWidget.cancelMessage()},title:"Stop generation"},"Stop"));if(t===tn.USING_TOOL){const e=o?g(o):null,t=o?p(o):n||"Using tool...",s="notebook-run_cell"===o;return oe.createElement("div",{className:"sage-ai-llm-state-display sage-ai-using-tool",style:{display:"flex"}},oe.createElement("div",{className:"sage-ai-llm-state-content"},e?oe.createElement("div",{className:"sage-ai-tool-icon-container",dangerouslySetInnerHTML:{__html:e}}):oe.createElement("div",{className:"sage-ai-tool-loader"}),oe.createElement("span",{className:"sage-ai-llm-state-text"},s?"Waiting to run cell...":t)),oe.createElement("div",{className:"sage-ai-llm-state-buttons"},s&&r&&l?oe.createElement(oe.Fragment,null,oe.createElement("button",{className:"sage-ai-llm-state-reject-button",onClick:l,title:"Reject code execution"},"Reject"),oe.createElement("button",{className:"sage-ai-llm-state-run-button",onClick:r,title:"Run code (Cmd/Ctrl + Enter)"},"Run")):oe.createElement("button",{className:"sage-ai-llm-state-stop-button",onClick:()=>{var e;null===(e=m.AppStateService.getChatContainerSafe())||void 0===e||e.chatWidget.cancelMessage()},title:"Stop tool execution"},"Stop")))}if(t===tn.DIFF&&b&&b.length>0){const{totalAdded:e,totalRemoved:t}=(e=>{let t=0,n=0;return e.forEach(e=>{var o,s;const i=((null===(o=e.originalContent)||void 0===o?void 0:o.split("\n"))||[]).length,a=((null===(s=e.newContent)||void 0===s?void 0:s.split("\n"))||[]).length;if("add"===e.type)t+=a;else if("remove"===e.type)n+=i;else if("edit"===e.type){const o=St.calculateDiff(e.originalContent||"",e.newContent||"");t+=o.filter(e=>"added"===e.type).length,n+=o.filter(e=>"removed"===e.type).length}}),{totalAdded:t,totalRemoved:n}})(b);return oe.createElement("div",{className:"sage-ai-llm-state-display sage-ai-diff-state"},oe.createElement("div",{className:"sage-ai-diff-summary-bar",onClick:()=>d(!c)},oe.createElement("div",{className:"sage-ai-diff-summary-info"},oe.createElement("span",{className:"sage-ai-diff-icon"},c?oe.createElement(sn.react,{className:"sage-ai-diff-menu-icon"}):oe.createElement(on.react,{className:"sage-ai-diff-menu-icon"})),oe.createElement("span",{className:"sage-ai-diff-cell-count"},b.length," cell",1!==b.length?"s":""," ","modified"),oe.createElement("p",{className:"sage-ai-diff-cell-count-info"},e>0&&oe.createElement("span",{className:"sage-ai-diff-added-count"},"+",e),t>0&&oe.createElement("span",{className:"sage-ai-diff-removed-count"},"-",t))),oe.createElement("div",{className:"sage-ai-diff-summary-actions"},!h&&oe.createElement(oe.Fragment,null,oe.createElement("button",{className:"sage-ai-diff-btn sage-ai-diff-reject-all",onClick:async e=>{e.stopPropagation();for(const e of b)C.updateDiffState(e.cellId,!1,e.notebookId);await m.AppStateService.getNotebookDiffManager().diffApprovalDialog.rejectAll(),u(!0)},title:`Reject${s&&s.length>1?" all":""} change${s&&s.length>1?"s":""}`},s&&s.length>1?"Reject All":"Reject"),oe.createElement("button",{className:"sage-ai-diff-btn sage-ai-diff-approve-all",onClick:async e=>{if(e.stopPropagation(),a)for(const e of b)e.userDecision||await m.AppStateService.getNotebookDiffManager().diffApprovalDialog.runCell(e.cellId);else await m.AppStateService.getNotebookDiffManager().diffApprovalDialog.approveAll();u(!0)},title:a?`Run${s&&s.length>1?" all":""} change${s&&s.length>1?"s":""}`:`Approve${s&&s.length>1?"all":""} change${s&&s.length>1?"s":""}`},a?s&&s.length>1?"Run All":"Run":"Approve All")))),c&&oe.createElement("div",{className:"sage-ai-diff-list"},b.map((e,t)=>oe.createElement(cn,{key:`${e.cellId}-${t}`,diff:e,showActionsOnHover:!0}))))}return t===tn.RUN_KERNEL?oe.createElement("div",{className:"sage-ai-llm-state-display sage-ai-run-kernel"},oe.createElement("div",{className:"sage-ai-llm-state-content"},oe.createElement(rn.react,{className:"sage-ai-llm-state-warning-icon"}),oe.createElement("span",{className:"sage-ai-llm-state-text"},"Kernel potentially outdated.")),oe.createElement("button",{className:"sage-ai-llm-state-run-button",onClick:()=>{var e;null===(e=m.AppStateService.getChatContainerSafe())||void 0===e||e.chatWidget.conversationService.runAllCellsAfterRestore()},title:"The kernel might be outdated due to restoring to a checkpoint"},"Run all cells")):null}class hn extends _.ReactWidget{constructor(){super(),this.subscriptions=[],this._state={isVisible:!1,state:tn.IDLE,text:""},this.addClass("sage-ai-llm-state-widget"),this.addClass("hidden"),this.setupDiffStateSubscriptions()}setupDiffStateSubscriptions(){const e=C.diffState$.subscribe(e=>{if(this._state.state===tn.DIFF){const t=Array.from(e.pendingDiffs.values());this._state={...this._state,diffs:t},this.update()}});this.subscriptions.push(e);const t=C.allDiffsResolved$.subscribe(({notebookId:e})=>{C.getCurrentState().pendingDiffs.size>0||this._state.state!==tn.DIFF||this.hide()});this.subscriptions.push(t)}dispose(){this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],super.dispose()}render(){return this.handleIsVisibleChanges(this._state.isVisible,this._state.state),oe.createElement(dn,{isVisible:this._state.isVisible,state:this._state.state,text:this._state.text,toolName:this._state.toolName,diffs:this._state.diffs,waitingForUser:this._state.waitingForUser,isRunContext:this._state.isRunContext,onRunClick:this._state.onRunClick,onRejectClick:this._state.onRejectClick})}handleIsVisibleChanges(e,t){var n;!e||t===tn.IDLE||t===tn.DIFF&&0===(null===(n=this._state.diffs)||void 0===n?void 0:n.length)?this.addClass("hidden"):this.removeClass("hidden")}show(e="Generating...",t){this._state={isVisible:!0,state:tn.GENERATING,text:e,waitingForUser:t},this.update()}showRunCellTool(e,t){this._state={isVisible:!0,state:tn.USING_TOOL,text:"",toolName:"notebook-run_cell",onRunClick:e,onRejectClick:t},this.update()}showTool(e,t){this._state={isVisible:!0,state:tn.USING_TOOL,text:t||"",toolName:e},this.update()}showDiffsWithManager(e,t){try{const n=C.getCurrentState(),o=Array.from(n.pendingDiffs.values()).filter(t=>!e||t.notebookId===e);if(0===o.length)return void this.hide();this._state={isVisible:!0,state:tn.DIFF,text:"",diffs:o,isRunContext:t||!1},this.update()}catch(e){console.warn("Could not show diffs with manager:",e),this.hide()}}hide(){this._state={isVisible:!1,state:tn.IDLE,text:"",waitingForUser:!1},this.update()}showPendingDiffs(e,t){this.showDiffsWithManager(e||void 0,t)}showRunKernelButton(){this._state={...this._state,isVisible:!0,state:tn.RUN_KERNEL},this.update()}hidePendingDiffs(){this.hide()}isDiffState(){return this._state.state===tn.DIFF}isUsingToolState(){return this._state.state===tn.USING_TOOL}getWidget(){return this}}let un,pn;const gn={id:"sage-agent-internal:plugin",description:"Sage AI - Your AI Data Partner",autoStart:!0,requires:[X.INotebookTracker,gt.ICommandPalette,gt.IThemeManager,Vt.IStateDB,nn.IDocumentManager],optional:[pt.ISettingRegistry,gt.IToolbarWidgetRegistry],activate:(e,t,n,o,s,i,a,r)=>{console.log("JupyterLab extension sage-agent-internal is activated!"),ie.initialize(a),q.K.initialize(s),m.AppStateService.loadSnippets().catch(e=>{console.warn("[Plugin] Failed to load snippets from StateDB:",e)}),m.AppStateService.loadInsertedSnippets().catch(e=>{console.warn("[Plugin] Failed to load inserted snippets from StateDB:",e)}),(async()=>{const e=await ie.getSetting(le,{});e&&Object.keys(e).length>0&&(console.log("MOVING ALL SETTINGS TO THE STATE DB"),await q.K.setValue(le,e),console.log("SUCCESSFULLY MOVED ALL SETTINGS TO THE STATE DB"),await ie.setSetting(le,{}))})(),m.AppStateService.setSettingsRegistry(a);const l=e.serviceManager;m.AppStateService.setServiceManager(l);const c=new Ot.ListModel(l);m.AppStateService.setExtensions(c);const d=e.serviceManager.contents;(async()=>{await ie.getBooleanSetting(ae,!1)||(console.log("Setting theme to JupyterLab Dark (first time)"),o.setTheme("JupyterLab Dark"),await ie.setBooleanSetting(ae,!0))})(),(async()=>{try{let e=!1;try{e="directory"===(await d.get("data")).type}catch(t){e=!1}if(!e){const e=await d.newUntitled({type:"directory",path:""});await d.rename(e.path,"data"),console.log("Created 'data' directory.")}let t=!1;try{await d.get("data/example.csv"),t=!0}catch(e){t=!1}t||(await d.save("data/example.csv",{type:"file",format:"text",content:"Date,Open,High,Low,Close,Volume,Symbol\n2024-01-02,473.25,478.90,471.15,477.71,82145600,SPY\n2024-01-03,477.80,481.35,475.20,480.92,73892400,SPY"}),console.log("Created 'data/example.csv' with S&P 500 sample data."))}catch(e){console.error("Error ensuring data directory and example.csv:",e)}})(),a&&a.load(gn.id).then(e=>{console.log("Loaded settings for sage-agent-internal");const t=e.get("defaultService").composite;t&&De.w.setActiveModelType(t),e.changed.connect(()=>{const t=e.get("defaultService").composite;De.w.setActiveModelType(t),console.log(`Default service changed to ${t}`)})}).catch(e=>{console.error("Failed to load settings for sage-agent-internal",e)});const h=new It,u=new Ht,p=new hn,g=new Ut;h.setNotebookTracker(t,g),h.setContentManager(d);const f=new Tt(h);h.setContextManager(f);const v=new ne,C=new Mt(t,g);m.AppStateService.initializeCoreServices(h,t,C,f,d,a),m.AppStateService.initializeManagers(u,p,g),m.AppStateService.initializeAdditionalServices(v,new Nt(C,t),new _t(t),new Lt(t,f,C)),Jt.getInstance().initialize().catch(e=>{console.warn("[Plugin] Tab completion service initialization failed:",e)}),Xt.getInstance().initialize(t),ke.getInstance().initializeOnStartup().catch(e=>{console.warn("[Plugin] Database cache initialization failed:",e)});const b=Ue.getInstance(),y=Ft.getInstance();setTimeout(async()=>{try{await b.initialize(),console.log("[Plugin] Context cache service initialized"),await y.initialize(t),console.log("[Plugin] Kernel execution listener initialized"),b.loadAllContexts().catch(e=>{console.warn("[Plugin] Initial context loading failed:",e)}),b.subscribeToNotebookChanges()}catch(e){console.warn("[Plugin] Context cache service initialization failed:",e)}},1e3);const k=m.AppStateService.getCellTrackingService(),w=m.AppStateService.getContextCellHighlighter(),S=new ut(C,v);m.AppStateService.setState({notebookDiffManager:S}),St.initializeThemeDetection(),t.currentChanged.connect(async(e,t)=>{var n;if(t){const e=await d.get(t.context.path);let o=null;if(console.log("================== NEW NOTEBOOK FILE ================="),console.log(e),e&&e.content){if(!e.content.metadata||!e.content.nbformat)return;const n=e.content.metadata||{};n.sage_ai&&n.sage_ai.unique_id||(await t.context.save(),n.sage_ai={unique_id:"nb_"+(0,Ae.v4)()+"_"+Date.now()},e.content.metadata=n,e.content.metadata&&await d.save(t.context.path,e),await t.context.revert(),await t.context.save()),o=n.sage_ai.unique_id}let s=t.context.path;t.context.pathChanged.connect(async(e,n)=>{var i,a,r;if(s!==n){try{console.log("RENAMING NOTEBOOK");const e=await d.get(n),l=(null===(r=null===(a=null===(i=null==e?void 0:e.content)||void 0===i?void 0:i.metadata)||void 0===a?void 0:a.sage_ai)||void 0===r?void 0:r.unique_id)||o;console.log("NB ID:",l),l&&(m.AppStateService.setCurrentNotebook(t,o),m.AppStateService.updateNotebookId(o||s,l),o=l)}catch(e){console.warn("Could not get notebook metadata after path change:",e),m.AppStateService.setCurrentNotebook(t,o),m.AppStateService.updateNotebookId(s,n)}s=n}});for(const e of t.content.widgets)St.removeDiffOverlay(e);S.setNotebookWidget(t),o?(m.AppStateService.setCurrentNotebook(t,o),null===(n=m.AppStateService.getState().chatContainer)||void 0===n||n.chatWidget.cancelMessage()):m.AppStateService.setCurrentNotebook(t),k.initializeExistingCells()}});const x=m.AppStateService.getTrackingIDUtility(),E=new gt.WidgetTracker({namespace:"sage-ai-widgets"});let M,I,N;const D=()=>{if(!N||N.isDisposed){const e=(()=>{const e=new en;E.add(e);const n=t.currentWidget;if(!n)return console.log("DiffNavigationWidget: No current notebook available, skipping widget creation"),null;{const t=n.node.querySelector(".jp-Notebook");t?t.appendChild(e.node):n.node.appendChild(e.node)}return e})();e&&(N=e)}return N};(async()=>{const n=m.AppStateService.getState().chatContainer;if(!n||n.isDisposed){const n=await(async()=>{var n,o,s;console.log("[Plugin] Creating new NotebookChatContainer");const i=new Dt(h,f,v);if(await E.add(i),e.shell.add(i,"right",{rank:1e3,activate:!0}),t.currentWidget){const e=m.AppStateService.getCurrentNotebookId();if(e)await i.switchToNotebook(e);else try{const e=await d.get(t.currentWidget.context.path),a=null===(s=null===(o=null===(n=null==e?void 0:e.content)||void 0===n?void 0:n.metadata)||void 0===o?void 0:o.sage_ai)||void 0===s?void 0:s.unique_id;a?await i.switchToNotebook(a):await i.switchToNotebook(t.currentWidget.context.path)}catch(e){console.warn("Could not get notebook metadata in initializeChatContainer:",e),await i.switchToNotebook(t.currentWidget.context.path)}}return m.AppStateService.setChatContainer(i),i})();w.setChatContainer(n),e.restored.then(()=>{e.shell.activateById("sage-ai-chat-container")})}})(),M&&!M.isDisposed||(M=(()=>{const t=new Bt(h,S,f);return E.add(t),e.shell.add(t,"right",{rank:1001}),t})()),I&&!I.isDisposed||(I=(()=>{const t=new Gt;return E.add(t),e.shell.add(t,"left",{rank:1e3}),t})()),N=D(),un=I,pn=N,N&&m.AppStateService.setDiffNavigationWidget(N),m.AppStateService.onNotebookChanged().subscribe(({newNotebookId:e})=>{if(pn&&!pn.isDisposed){pn.setNotebookId(e);const n=t.currentWidget;if(n&&pn.node.parentNode){pn.node.parentNode.removeChild(pn.node);const e=n.node.querySelector(".jp-Notebook");e?e.appendChild(pn.node):n.node.appendChild(pn.node)}else n||pn.node.parentNode&&pn.node.parentNode.removeChild(pn.node)}else!pn&&e&&(pn=D(),pn&&m.AppStateService.setDiffNavigationWidget(pn))}),t.currentChanged.connect(async(e,n)=>{var o,s,i,a,r,l;if(n){n.model&&n.model.cells.length>0&&n.model.cells.get(0).setMetadata("deletable",!0);let e=null;try{const t=await d.get(n.context.path);(null===(i=null===(s=null===(o=null==t?void 0:t.content)||void 0===o?void 0:o.metadata)||void 0===s?void 0:s.sage_ai)||void 0===i?void 0:i.unique_id)&&(e=t.content.metadata.sage_ai.unique_id)}catch(e){console.warn("Could not get notebook metadata in currentChanged handler:",e)}m.AppStateService.setCurrentNotebookId(e||n.context.path),S.setNotebookWidget(n),k.initializeExistingCells();const c=C.getPlanCell(e||n.context.path);if(c){const e=(null===(a=c.model.sharedModel.getMetadata().custom)||void 0===a?void 0:a.current_step_string)||"",t=(null===(r=c.model.sharedModel.getMetadata().custom)||void 0===r?void 0:r.next_step_string)||"",n=c.model.sharedModel.getSource()||"";m.AppStateService.getPlanStateDisplay().updatePlan(e||"Plan active",t,n,!1)}null===(l=null==n?void 0:n.model)||void 0===l||l.cells.changed.connect(async()=>{var t,o,s;x.fixTrackingIDs(e||n.context.path),w.refreshHighlighting(n),setTimeout(()=>{Ue.getInstance().loadContextCategory("cells").catch(e=>{console.warn("[Plugin] Cell context refresh failed:",e)})},200);const i=C.getPlanCell(e||n.context.path);if(i){const e=(null===(t=i.model.sharedModel.getMetadata().custom)||void 0===t?void 0:t.current_step_string)||"",n=(null===(o=i.model.sharedModel.getMetadata().custom)||void 0===o?void 0:o.next_step_string)||"",s=i.model.sharedModel.getSource()||"";console.log("Updating step floating box",e,n),m.AppStateService.getPlanStateDisplay().updatePlan(e,n,s,!1)}else i||m.AppStateService.getPlanStateDisplay().updatePlan(void 0,void 0,void 0);if(null===(s=n.model)||void 0===s?void 0:s.cells)for(const e of n.model.cells)e.metadataChanged.connect(()=>{w.refreshHighlighting(n)})}),console.log("[Plugin] Notebook changed, setting up DB_URL in kernel"),Ce.setDbUrlInKernelWithRetry(),setTimeout(()=>{Ue.getInstance().refreshIfStale().catch(e=>{console.warn("[Plugin] Context refresh on notebook change failed:",e)})},500);const h=ke.getInstance();setTimeout(()=>{console.log("[Plugin] Notifying database cache of potential kernel readiness"),h.onKernelReady().catch(e=>{console.warn("[Plugin] Database cache kernel ready notification failed:",e)})},3e3),window.debugDBURL={check:()=>Ce.checkDbUrlInKernel(),debug:()=>Ce.debugAppStateDatabaseUrl(),set:e=>Ce.setDbUrlInKernel(e),retry:()=>Ce.setDbUrlInKernelWithRetry()},window.debugDBCache={getStatus:()=>h.getCacheStatus(),refresh:()=>h.refreshMetadata(),clear:()=>h.clearCache(),onKernelReady:()=>h.onKernelReady(),onSettingsChanged:()=>h.onSettingsChanged()},window.debugContextCache={getContexts:()=>b.getContexts(),refresh:()=>b.forceRefresh(),refreshCategory:e=>b.loadContextCategory(e),refreshVariables:()=>b.refreshVariablesAfterExecution(),getCacheAge:()=>m.AppStateService.getContextCacheAge(),shouldRefresh:()=>m.AppStateService.shouldRefreshContexts(),isLoading:()=>m.AppStateService.isContextLoading()},window.debugKernelListener={getDebugInfo:()=>y.getDebugInfo(),triggerRefresh:()=>y.triggerVariableRefresh(),dispose:()=>y.dispose(),reinitialize:()=>y.initialize(t)}}}),function(e,t){!function(e,t){const n="sage-ai:test-notebook";e.commands.addCommand(n,{label:"Test Notebook",execute:async()=>{const e=m.AppStateService.getNotebookTools(),t=e.add_cell({cell_type:"code",source:'# This is a test cell created by NotebookTools\nprint("Hello from Sage AI!")\nimport time\ntime.sleep(1)\nprint("Cell with stable tracking ID!")',summary:"Test cell created with tracking ID",position:null}),n=e.add_cell({cell_type:"markdown",source:"# This is a test markdown cell\n\nWith stable tracking ID!\n\n* List item 1\n* List item 2",summary:"Test markdown cell created with tracking ID",position:null});console.log("Cell tracking ID 1:",t),console.log("Cell tracking ID 2:",n),setTimeout(()=>{const o=e.findCellByAnyId(t),s=e.findCellByAnyId(n);console.log("Found cell 1 by tracking ID:",o?"Yes":"No"),console.log("Found cell 2 by tracking ID:",s?"Yes":"No"),o&&e.edit_cell({cell_id:t,new_source:'# Updated cell content\nprint("This cell was found by tracking ID!")\nimport time\ntime.sleep(1)\nprint("Success!")',summary:"Updated test cell",is_tracking_id:!0})},2e3)}}),t.addItem({command:n,category:"AI Tools"})}(e,t),function(e,t){const n="sage-ai:test-add-with-diff";e.commands.addCommand(n,{label:"Test Add Cell With Diff",execute:async()=>{var e,t,n,o;const s=m.AppStateService.getNotebookTools(),i=m.AppStateService.getNotebookDiffManager(),a=m.AppStateService.getNotebookTracker(),r=s.add_cell({cell_type:"code",source:'# Test cell with diff view\nprint("This cell demonstrates diff view")\nfor i in range(5):\n print(f"Count: {i}")',summary:"Test cell with diff view",position:null}),l=s.findCellByAnyId(r);if(!l)return void console.error("Could not find the newly added cell by tracking ID");const c=(null===(e=a.currentWidget)||void 0===e?void 0:e.context.path)||null;i.trackAddCell(r,l.cell.model.sharedModel.getSource(),"Test cell with diff view",c),console.log("Displaying diff view...");const d=s.display_diff(l.cell,"",l.cell.model.sharedModel.getSource(),"add").cellId;console.log(`Original tracking ID: ${r}, Updated cell ID: ${d}`),i.updateCellIdMapping(r,d,c);const h=a.currentWidget;let u=null;if(h)try{const e=m.AppStateService.getContentManager(),s=await(null==e?void 0:e.get(h.context.path));(null===(o=null===(n=null===(t=null==s?void 0:s.content)||void 0===t?void 0:t.metadata)||void 0===n?void 0:n.sage_ai)||void 0===o?void 0:o.unique_id)&&(u=s.content.metadata.sage_ai.unique_id)}catch(e){console.warn("Could not get notebook metadata in commands:",e)}const p=await i.showApprovalDialog(h?h.node:document.body,!1,!1,u||(h?h.context.path:null));console.log("Diff approval result:",p),setTimeout(()=>{const e=s.findCellByAnyId(r,c);console.log("Found cell after diff approval:",e?"Yes":"No")},1e3)}}),t.addItem({command:n,category:"AI Tools"})}(e,t),function(e,t){const n="sage-ai:test-edit-with-diff";e.commands.addCommand(n,{label:"Test Edit Cell With Diff",execute:async()=>{const e=m.AppStateService.getNotebookTools(),t=m.AppStateService.getNotebookDiffManager(),n=m.AppStateService.getNotebookTracker();console.log("Step 1: Adding new cell...");const o=e.add_cell({cell_type:"code",source:'# Original cell content\nprint("This is the original content")\nvalue = 42',summary:"Original test cell",position:null});setTimeout(()=>{var s;console.log("Step 2: Editing cell after 2 seconds...");const i='# Modified cell content\nprint("This content has been modified!")\nvalue = 42\nprint(f"The value is {value}")\n\n# Added a new comment';if(!e.edit_cell({cell_id:o,new_source:i,summary:"Modified test cell",is_tracking_id:!0}))return void console.error("Could not edit the cell with tracking ID");const a=(null===(s=n.currentWidget)||void 0===s?void 0:s.context.path)||null;t.trackEditCell(o,'# Original cell content\nprint("This is the original content")\nvalue = 42',i,"Modified test cell",a),setTimeout(async()=>{var s;console.log("Step 3: Showing diff after edit...");const i=await t.showApprovalDialog(document.body,!1,!1,(null===(s=n.currentWidget)||void 0===s?void 0:s.context.path)||null);console.log("Diff approval result:",i),await t.applyApprovedDiffs(),await t.handleRejectedDiffs(),setTimeout(()=>{const t=e.findCellByAnyId(o,a);console.log("Found cell after diff approval:",t?"Yes":"No")},2e3)},2e3)},2e3)}}),t.addItem({command:n,category:"AI Tools"})}(e,t),function(e,t){const n="sage-ai:test-multiple-diffs";e.commands.addCommand(n,{label:"Test Multiple Diffs",execute:async()=>{var e;const t=m.AppStateService.getNotebookTools(),n=m.AppStateService.getNotebookDiffManager(),o=m.AppStateService.getNotebookTracker();console.log("Running multiple diffs test with tracking IDs...");const s=[],i=t.add_cell({cell_type:"code",source:'# First cell\nx = 10\ny = 20\nprint(f"Sum: {x + y}")',summary:"First test cell",position:null});s.push(i),console.log(`Added cell 1 with tracking ID: ${i}`);const a=t.add_cell({cell_type:"markdown",source:"# Second Cell\nThis is a markdown cell for testing multiple diffs.",summary:"Second test cell",position:null});s.push(a),console.log(`Added cell 2 with tracking ID: ${a}`);const r=t.add_cell({cell_type:"code",source:'# Third cell\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(8, 6))\nplt.plot([1, 2, 3, 4])\nplt.title("Test Plot")',summary:"Third test cell",position:null});s.push(r),console.log(`Added cell 3 with tracking ID: ${r}`),await new Promise(e=>setTimeout(e,1e3));const l=['# First cell - MODIFIED\nx = 10\ny = 20\nz = 30\nprint(f"Sum: {x + y + z}")',"# Second Cell - MODIFIED\nThis is a **modified** markdown cell for testing multiple diffs.\n\n- Item 1\n- Item 2",'# Third cell - MODIFIED\nimport matplotlib.pyplot as plt\nimport numpy as np\nx = np.linspace(0, 10, 100)\nplt.figure(figsize=(10, 8))\nplt.plot(x, np.sin(x))\nplt.title("Modified Plot")'];for(let i=0;i<s.length;i++){const a=s[i],r=t.findCellByAnyId(a);if(!r){console.error(`Could not find cell with tracking ID ${a}`);continue}const c=r.cell.model.sharedModel.getSource(),d=(null===(e=o.currentWidget)||void 0===e?void 0:e.context.path)||null;n.trackEditCell(a,c,l[i],`Modified test cell ${i+1}`,d),console.log(`Displaying diff for cell ${i+1} with tracking ID ${a}...`)}const c=o.currentWidget,d=await n.showApprovalDialog(c?c.node:document.body,!1,!1,c?c.context.path:null);console.log("Multiple diffs approval result:",d),setTimeout(()=>{for(let e=0;e<s.length;e++){const n=s[e],o=t.findCellByAnyId(n);console.log(`Found cell ${e+1} after diff approval: ${o?"Yes":"No"}`)}},1e3)}}),t.addItem({command:n,category:"AI Tools"})}(e,t),function(e,t){const n="sage-ai:test-tracking-persistence";e.commands.addCommand(n,{label:"Test Tracking ID Persistence",execute:async()=>{const e=m.AppStateService.getNotebookTools(),t=m.AppStateService.getCellTrackingService();console.log("Testing tracking ID persistence...");const n=t.getAllTrackingIds();console.log(`Found ${n.length} cells with tracking IDs`),console.log("Tracking IDs:",n),t.initializeExistingCells();const o=t.getAllTrackingIds();console.log(`Now have ${o.length} cells with tracking IDs`);const s=e.add_cell({cell_type:"markdown",source:"# Persistence Test\n\nThis cell tests tracking ID persistence across notebook operations.",summary:"Persistence test cell",position:null});console.log(`Added new cell with tracking ID: ${s}`);const i=e.findCellByAnyId(s);console.log("Found cell immediately:",i?"Yes":"No"),setTimeout(()=>{const t=e.findCellByAnyId(s);console.log("Found cell after delay:",t?"Yes":"No"),t&&(e.edit_cell({cell_id:s,new_source:"# Persistence Test - UPDATED\n\nThis cell was successfully found by its tracking ID after a delay!",summary:"Updated persistence test cell",is_tracking_id:!0}),console.log("Cell updated successfully through tracking ID"))},2e3)}}),t.addItem({command:n,category:"AI Tools"})}(e,t),function(e,t){const n="sage-ai:tracking-id-report";e.commands.addCommand(n,{label:"Show Cell Tracking ID Report",execute:()=>{const e=m.AppStateService.getTrackingIDUtility().getTrackingIDReport();console.log("Cell Tracking ID Report:"),console.table(e)}}),t.addItem({command:n,category:"AI Tools"})}(e,t),function(e,t){const n="sage-ai:fix-tracking-ids";e.commands.addCommand(n,{label:"Fix Cell Tracking IDs",execute:()=>{const e=m.AppStateService.getTrackingIDUtility().fixTrackingIDs();console.log(`Fixed tracking IDs for ${e} cells`)}}),t.addItem({command:n,category:"AI Tools"})}(e,t),function(e,t){const n="sage-ai:export-error-logs";e.commands.addCommand(n,{label:"Export Error Logs to File",execute:async()=>{try{const e=await q.K.getValue(q.s.ERROR_LOGS,"");if(!e.trim())return void console.log("No error logs found to export");const t=m.AppStateService.getContentManager();await t.save("./error_dump.txt",{type:"file",format:"text",content:e}),console.log("Error logs exported successfully to error_dump.txt")}catch(e){console.error("Failed to export error logs:",e)}}}),t.addItem({command:n,category:"AI Tools"})}(e,t),function(e,t){const n="sage-ai:clear-error-logs";e.commands.addCommand(n,{label:"Clear Error Logs",execute:async()=>{try{await q.K.setValue(q.s.ERROR_LOGS,""),console.log("Error logs cleared successfully")}catch(e){console.error("Failed to clear error logs:",e)}}}),t.addItem({command:n,category:"AI Tools"})}(e,t)}(e,n),function(e,t,n){!function(e,t,n){const o="sage-ai:run_eval";e.commands.addCommand(o,{label:"Run Eval",execute:async t=>{var o,s,i,a,r,l,c,d;m.AppStateService.getNotebookTools(),m.AppStateService.getNotebookDiffManager();const h=m.AppStateService.getNotebookTracker();console.log("TOOL CALL LIMIT",t.tool_call_limit),t.tool_call_limit&&"number"==typeof t.tool_call_limit?(m.AppStateService.setMaxToolCallLimit(t.tool_call_limit),console.log("Set max tool call limit to:",t.tool_call_limit)):m.AppStateService.setMaxToolCallLimit(null);const{commands:u,shell:p}=e,g=(p.currentWidget,"evals.ipynb");console.log("CURRENT NOTEBOOK ID:",null===(o=m.AppStateService.getNotebookTracker().currentWidget)||void 0===o?void 0:o.sessionContext.path),h.currentWidget&&(await h.currentWidget.context.revert(),await n.closeFile(g)),n.open(g,"default",void 0,{activate:!0}),await ht(500);const f=h.currentWidget;let v=null;if(f)try{const e=m.AppStateService.getContentManager(),t=await(null==e?void 0:e.get(f.context.path));(null===(a=null===(i=null===(s=null==t?void 0:t.content)||void 0===s?void 0:s.metadata)||void 0===i?void 0:i.sage_ai)||void 0===a?void 0:a.unique_id)&&(v=t.content.metadata.sage_ai.unique_id)}catch(e){console.warn("Could not get notebook metadata for eval notebook:",e)}m.AppStateService.setCurrentNotebookId(v||g);const C=null===(r=h.currentWidget)||void 0===r?void 0:r.content;C&&await X.NotebookActions.runAll(C,null===(l=h.currentWidget)||void 0===l?void 0:l.sessionContext);const b=null===(c=m.AppStateService.getChatContainerSafe())||void 0===c?void 0:c.chatWidget;if(!b)return void console.error("Chat widget not found");const y=m.AppStateService.getContentManager(),k=await y.get("eval_prompt.txt");if(!k||!k.content)return void console.error("Prompt content not found");await b.threadManager.createNewThread(),await ht(200),b.conversationService.setAutoRun(!0),b.inputManager.setInputValue(k.content),await b.inputManager.sendMessage();const w=b.chatHistoryManager.getCurrentThread();if(!w)return void console.error("Chat history not found");const S=Le.getCleanMessageArrayWithTimestamps(w);null===(d=h.currentWidget)||void 0===d||d.sessionContext.restartKernel(),await y.save("eval_output.json",{type:"file",format:"text",content:JSON.stringify(S,null,2)}),console.log("Cleaned Messages:",S);const _=await(null==f?void 0:f.context.listCheckpoints());if(_)for(const e of _)console.log("Checkpoint:",e),null==f||f.context.deleteCheckpoint(e.id);null==f||f.context.createCheckpoint(),null==f||f.context.save();const x={messages:S,notebook_content:(null==C?void 0:C.widgets.map(e=>({source:e.model.sharedModel.getSource(),cell_type:e.model.sharedModel.cell_type,output:"code"===e.model.sharedModel.cell_type?e.outputArea&&e.outputArea.model.toJSON():null})))||[]};return await ht(1e3),console.log(x),m.AppStateService.setMaxToolCallLimit(null),x}}),t.addItem({command:o,category:"AI Tools"})}(e,t,n)}(e,n,i),t.activeCellChanged.connect((e,t)=>{if(t){const e=m.AppStateService.getCurrentNotebookId();if(!e)return;const n=t.model.sharedModel.getMetadata()||{};let o="";n&&"object"==typeof n&&"cell_tracker"in n&&n.cell_tracker&&"object"==typeof n.cell_tracker&&"trackingId"in n.cell_tracker&&(o=String(n.cell_tracker.trackingId));const s=o?f.isCellInContext(e,o):f.isCellInContext(e,t.model.id),i=document.querySelector('.jp-ToolbarButtonComponent[data-command="sage-ai-add-to-context"]');if(i)if(s){i.classList.add("in-context");const e=i.querySelector(".jp-icon3");if(e){const t='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M5 13v-2h14v2z"/></svg>';e.innerHTML=t}const t=i.querySelector(".button-text");t&&(t.textContent="Remove from Chat")}else{i.classList.remove("in-context");const e=i.querySelector(".jp-icon3");e&&(e.innerHTML=_.addIcon.svgstr);const t=i.querySelector(".button-text");t&&(t.textContent="Add to Context")}}});const{commands:T}=e,A="sage-agent-internal:log-selected-code";n.addItem({command:A,category:"Sage AI"}),e.commands.addKeyBinding({command:A,keys:["Accel Shift K"],selector:".jp-Notebook.jp-mod-editMode"}),T.addCommand(A,{label:"Log Selected Code",execute:()=>{if(!E.currentWidget)return void console.warn("No active notebook");const e=t.activeCell;if(!e)return void console.warn("No active cell");const n=e.editor,o=null==n?void 0:n.getSelection();o?console.log("Selection:",o):console.log("No selection");const s=null==n?void 0:n.model.sharedModel.source.substring(n.getOffsetAt((null==o?void 0:o.start)||{line:0,column:0}),n.getOffsetAt((null==o?void 0:o.end)||{line:0,column:0}));s?console.log("Selected text:",s):console.log("No text selected")}});const L="sage-agent-internal:open-snippet-creation";T.addCommand(L,{label:"Open Rule Creation",execute:()=>{un&&!un.isDisposed&&(un.getIsVisible()?un.hide():(un.show(),e.shell.activateById(un.id)))}}),n.addItem({command:L,category:"Sage AI"})},deactivate:()=>{console.log("JupyterLab extension sage-agent-internal is deactivated!"),un&&!un.isDisposed&&(un.dispose(),un=void 0),pn&&!pn.isDisposed&&(pn.node.parentNode&&pn.node.parentNode.removeChild(pn.node),pn.dispose(),pn=void 0),Ft.getInstance().dispose(),St.cleanupThemeDetection()}},mn=gn},1368:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 16 16%27 fill=%27%23fff%27%3e%3cpath d=%27M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708%27/%3e%3c/svg%3e"},1384:e=>{"use strict";e.exports="You are an expert data scientist working in Jupyter Notebooks. Your job is to execute the exact task requested using only the cells provided in context.\n\n## Core Rules:\n* **Work only on provided cells** - do not edit cells outside of context\n* **Do exactly what's asked** - nothing more, nothing less\n* **Limit to 5 tool calls** before asking to continue\n\n## Execution:\n* Write concise code (<30 lines per cell) in each cell\n* Execute frequently to verify correctness\n* **Add brief markdown explanations between code cells** when helpful for clarity\n* Fix errors in the same cell. Do not create new cells to debug errors.\n* Continue immediately to next task unless unclear\n\n## Tool Calling\nYou have tools available to complete tasks.\n* Provide tool arguments precisely.\n* Tools are for your internal use only; **do not call tools from \ninside code cells**.\n* **Stop after every 5 individual tool calls** to ask the user explicitly \nif they wish to proceed further or adjust your approach.\n\n## Summarization\n- For each cell provide a complete, detailed summary of the cell, including variables, operation, and goal.\n- After the task is done, write a summary of what you added, removed and changed.\n\n\n## Output:\nFor each executed cell, briefly state:\n- What it does\n- Key results/outputs\n"},1451:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 16 16%27 fill=%27none%27 stroke=%27%23052c65%27 stroke-linecap=%27round%27 stroke-linejoin=%27round%27%3e%3cpath d=%27m2 5 6 6 6-6%27/%3e%3c/svg%3e"},1563:(e,t,n)=>{"use strict";n.d(t,{K:()=>o,s:()=>s});class o{static initialize(e){o.stateDB=e}static async getValue(e,t){if(!o.stateDB)return console.warn("[StateDBCachingService] State DB not initialized, using default value"),t;try{const n=`${o.NAMESPACE}:${e}`,s=await o.stateDB.fetch(n);return void 0!==s?s:t}catch(n){return console.warn(`[StateDBCachingService] Failed to get value '${e}':`,n),t}}static async setValue(e,t){if(o.stateDB)try{const n=`${o.NAMESPACE}:${e}`;await o.stateDB.save(n,t)}catch(t){console.error(`[StateDBCachingService] Failed to set value '${e}':`,t)}else console.warn("[StateDBCachingService] State DB not initialized, cannot set value")}static async removeValue(e){if(o.stateDB)try{const t=`${o.NAMESPACE}:${e}`;await o.stateDB.remove(t)}catch(t){console.error(`[StateDBCachingService] Failed to remove value '${e}':`,t)}else console.warn("[StateDBCachingService] State DB not initialized, cannot remove value")}static async getObjectValue(e,t){return o.getValue(e,t)}static async setObjectValue(e,t){return o.setValue(e,t)}static isAvailable(){return null!==o.stateDB}static async listKeys(){if(!o.stateDB)return[];try{return(await o.stateDB.list(o.NAMESPACE)).ids.map(e=>e.replace(`${o.NAMESPACE}:`,""))}catch(e){return console.error("[StateDBCachingService] Failed to list keys:",e),[]}}}o.stateDB=null,o.NAMESPACE="sage-agent-internal";const s={CHAT_HISTORIES:"chatHistories",NOTEBOOK_CHECKPOINTS:"notebookCheckpoints",ERROR_LOGS:"errorLogs",SNIPPETS:"snippets",INSERTED_SNIPPETS:"insertedSnippets"}},2247:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 30 30%27%3e%3cpath stroke=%27rgba%2833, 37, 41, 0.75%29%27 stroke-linecap=%27round%27 stroke-miterlimit=%2710%27 stroke-width=%272%27 d=%27M4 7h22M4 15h22M4 23h22%27/%3e%3c/svg%3e"},2364:(e,t,n)=>{"use strict";n.d(t,{F:()=>l});var o=n(6209);function s(e){return new Set(["False","None","True","__peg_parser__","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","abs","all","any","ascii","bin","bool","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip","get_ipython","In","Out","_","__","___","exit","quit","sys","os","json","math","datetime","time","random","re","numpy","np","pandas","pd","matplotlib","plt","seaborn","sns"]).has(e)||e.startsWith("_")}function i(e){return function(e){const t=new Set,n=e.split("\n");for(const e of n){const n=e.trim();if(!n||n.startsWith("#"))continue;const o=[/^([a-zA-Z_][a-zA-Z0-9_]*)\s*=/,/^([a-zA-Z_][a-zA-Z0-9_]*(?:\s*,\s*[a-zA-Z_][a-zA-Z0-9_]*)*)\s*=/,/for\s+([a-zA-Z_][a-zA-Z0-9_]*)\s+in\s/,/def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/,/class\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[:\(]/,/import\s+[\w.]+\s+as\s+([a-zA-Z_][a-zA-Z0-9_]*)/,/from\s+[\w.]+\s+import\s+[\w\s,]*\s+as\s+([a-zA-Z_][a-zA-Z0-9_]*)/,/from\s+[\w.]+\s+import\s+([a-zA-Z_][a-zA-Z0-9_]*(?:\s*,\s*[a-zA-Z_][a-zA-Z0-9_]*)*)/,/^import\s+([a-zA-Z_][a-zA-Z0-9_]*)/];for(const e of o){const o=n.match(e);if(o){o[1].split(",").map(e=>e.trim()).forEach(e=>{e&&!s(e)&&t.add(e)});break}}}return t}(e)}function a(e,t){const n=new Set;let o=e;if(t){const n=e.reduce((e,t)=>e+("code"===t.type?t.content.length:0),0);n>1e4?(o=e.slice(-t),console.log(`[VariableExtractor] Total content length (${n}) > 10,000 chars, limiting to last ${t} cells`)):console.log(`[VariableExtractor] Total content length (${n}) <= 10,000 chars, processing all cells`)}for(const e of o)"code"===e.type&&e.content.trim()&&i(e.content).forEach(e=>n.add(e));return n}function r(e,t){const n={};for(const[o,s]of Object.entries(e))t.has(o)&&(n[o]=s);return n}class l{static async getKernelVariables(){var e,t;try{const n=o.AppStateService.getToolService(),s=null===(e=null==n?void 0:n.getCurrentNotebook())||void 0===e?void 0:e.kernel;if(console.log("[KernelPreviewUtils] Getting kernel variables..."),!s)return console.warn("[KernelPreviewUtils] No kernel available"),null;const i=null===(t=o.AppStateService.getState().notebookTools)||void 0===t?void 0:t.read_cells(),l=a((null==i?void 0:i.cells)||[]);return console.log("[KernelPreviewUtils] Found notebook variables:",Array.from(l)),new Promise(e=>{let t="";const n=s.requestExecute({code:'\nimport json\nimport sys\nimport math\nfrom types import ModuleType, FunctionType, BuiltinFunctionType, BuiltinMethodType\n\n# Try to import common libraries but don\'t fail if they\'re not available\ntry:\n import numpy as np\n HAS_NUMPY = True\nexcept ImportError:\n HAS_NUMPY = False\n\ntry:\n import pandas as pd\n HAS_PANDAS = True\nexcept ImportError:\n HAS_PANDAS = False\n\ndef is_serializable(obj):\n """Check if an object can be JSON serialized"""\n try:\n json.dumps(obj)\n return True\n except (TypeError, ValueError, OverflowError):\n return False\n\ndef safe_json_value(obj):\n """Convert an object to a JSON-safe value, handling NaN, inf, etc."""\n import math\n \n if obj is None:\n return None\n elif isinstance(obj, float):\n if math.isnan(obj):\n return None # Convert NaN to null\n elif math.isinf(obj):\n return "Infinity" if obj > 0 else "-Infinity"\n else:\n return obj\n elif isinstance(obj, (int, str, bool)):\n return obj\n elif isinstance(obj, (list, tuple)):\n return [safe_json_value(item) for item in obj]\n elif isinstance(obj, dict):\n return {k: safe_json_value(v) for k, v in obj.items()}\n else:\n return str(obj)\n\ndef get_preview_info(obj, max_items=5):\n """Get preview information for an object"""\n try:\n obj_type = type(obj).__name__\n \n # Handle basic types\n if obj_type in [\'int\', \'float\', \'str\', \'bool\', \'NoneType\']:\n value = safe_json_value(obj)\n # Truncate very long strings\n if obj_type == \'str\' and len(str(obj)) > 200:\n value = str(obj)[:200] + "..."\n return {"type": obj_type, "value": value, "size": len(str(obj)) if obj_type == \'str\' else None}\n \n # Handle collections\n elif obj_type in [\'list\', \'tuple\']:\n size = len(obj)\n # Get preview of first few items, ensuring they\'re serializable\n preview_items = []\n for i, item in enumerate(obj[:max_items]):\n try:\n safe_item = safe_json_value(item)\n if safe_item is not None or item is None:\n preview_items.append(safe_item)\n else:\n preview_items.append(f"<{type(item).__name__} object>")\n except Exception:\n preview_items.append("<unreadable object>")\n return {"type": obj_type, "size": size, "preview": preview_items, "truncated": size > max_items}\n \n elif obj_type == \'dict\':\n size = len(obj)\n # Get preview of first few items, ensuring keys and values are serializable\n preview_dict = {}\n for i, (key, value) in enumerate(list(obj.items())[:max_items]):\n try:\n # Convert key to string if not serializable\n safe_key = str(key) if not is_serializable(key) else key\n # Convert value using safe_json_value\n safe_value = safe_json_value(value)\n preview_dict[safe_key] = safe_value\n except Exception:\n preview_dict[str(key)] = "<unreadable object>"\n return {"type": obj_type, "size": size, "preview": preview_dict, "truncated": size > max_items}\n \n elif obj_type == \'set\':\n size = len(obj)\n # Convert set items to list, ensuring they\'re serializable\n preview_items = []\n for i, item in enumerate(list(obj)[:max_items]):\n try:\n safe_item = safe_json_value(item)\n if safe_item is not None or item is None:\n preview_items.append(safe_item)\n else:\n preview_items.append(f"<{type(item).__name__} object>")\n except Exception:\n preview_items.append("<unreadable object>")\n return {"type": obj_type, "size": size, "preview": preview_items, "truncated": size > max_items}\n \n # Handle special objects with class and module info\n elif hasattr(obj, \'__class__\') and hasattr(obj.__class__, \'__module__\'):\n # For pandas DataFrames\n if obj_type == \'DataFrame\' and HAS_PANDAS:\n try:\n result = {\n "type": obj_type, \n "shape": list(obj.shape), # Convert to list for JSON serialization\n "columns": [str(col) for col in list(obj.columns)[:max_items]], \n "dtypes": {str(k): str(v) for k, v in dict(list(obj.dtypes.items())[:max_items]).items()}\n }\n \n # Handle multi-level columns (like from yfinance)\n if hasattr(obj.columns, \'nlevels\') and obj.columns.nlevels > 1:\n result["multi_level_columns"] = True\n result["column_levels"] = obj.columns.nlevels\n # Get a sample of the multi-level column structure\n result["columns"] = [str(col) for col in obj.columns[:max_items]]\n \n # Get first 2 rows as preview\n try:\n first_rows = obj.head(2).to_dict(\'records\')\n # Ensure all values in rows are serializable and handle NaN\n safe_rows = []\n for row in first_rows:\n safe_row = {}\n for k, v in row.items():\n try:\n safe_row[str(k)] = safe_json_value(v)\n except Exception:\n safe_row[str(k)] = "<unreadable value>"\n safe_rows.append(safe_row)\n result["first_rows"] = safe_rows\n except Exception as e:\n # If to_dict fails, try a simpler approach\n try:\n result["first_rows"] = str(obj.head(2))[:500]\n except Exception:\n result["first_rows"] = "Unable to preview rows"\n \n return result\n except Exception as e:\n return {"type": obj_type, "shape": list(getattr(obj, \'shape\', []))}\n \n # For numpy arrays\n elif obj_type == \'ndarray\' and HAS_NUMPY:\n try:\n return {\n "type": obj_type, \n "shape": list(obj.shape), \n "dtype": str(obj.dtype),\n "size": int(obj.size)\n }\n except Exception:\n return {"type": obj_type, "shape": "unknown"}\n \n # For other objects with classes, try to get useful info\n else:\n try:\n info = {"type": obj_type}\n \n # Try to get module info\n if hasattr(obj.__class__, \'__module__\'):\n info["module"] = str(obj.__class__.__module__)\n \n # Try to get length if available\n if hasattr(obj, \'__len__\'):\n try:\n info["length"] = len(obj)\n except Exception:\n pass\n \n # Try to get a brief string representation\n try:\n repr_str = repr(obj)[:100]\n if len(repr_str) < len(repr(obj)):\n repr_str += "..."\n info["repr"] = repr_str\n except Exception:\n info["repr"] = f"<{obj_type} object>"\n \n return info\n except Exception:\n return {"type": obj_type, "module": "unknown"}\n \n # Fallback for other types\n else:\n try:\n return {"type": obj_type, "repr": str(obj)[:100]}\n except Exception:\n return {"type": obj_type, "repr": f"<{obj_type} object>"}\n \n except Exception as e:\n return {"type": "unknown", "error": str(e)[:100]}\n\n# Main execution\ntry:\n # Create a snapshot of globals to avoid "dictionary changed size during iteration"\n globals_dict = globals()\n globals_snapshot = dict(globals_dict)\n \n # Get all variables from the snapshot, excluding private ones and modules\n kernel_preview = {}\n \n # Comprehensive list of names to exclude\n excluded_names = {\n \'In\', \'Out\', \'get_ipython\', \'exit\', \'quit\', \'json\', \'sys\', \n \'get_preview_info\', \'globals_snapshot\', \'kernel_preview\',\n \'HAS_NUMPY\', \'HAS_PANDAS\', \'excluded_names\', \'tables\', \'local_vars\', \n \'constraints\', \'fk\', \'globals_dict\', \'is_serializable\', \'data\',\n # Additional built-in names that might appear\n \'__name__\', \'__doc__\', \'__package__\', \'__loader__\', \'__spec__\',\n \'__builtin__\', \'__builtins__\', \'_\', \'__\', \'___\'\n }\n \n # Add numpy and pandas to excluded if they exist\n if HAS_NUMPY:\n excluded_names.add(\'np\')\n if HAS_PANDAS:\n excluded_names.add(\'pd\')\n \n # Process each variable in the globals snapshot\n for name, obj in globals_snapshot.items():\n try:\n # Skip private variables, built-ins, modules, and functions\n if (name.startswith(\'_\') or \n isinstance(obj, (ModuleType, FunctionType, BuiltinFunctionType, BuiltinMethodType)) or \n name in excluded_names or\n callable(obj)): # Skip any callable objects\n continue\n \n # Get type information\n obj_type = type(obj).__name__\n \n # Include various types but be more selective\n if obj_type in [\'int\', \'float\', \'complex\', \'str\', \'bool\', \'list\', \'tuple\', \'dict\', \'set\']:\n # For strings, only include if they\'re not too long or seem like user data\n if obj_type == \'str\':\n if len(obj) > 1000: # Skip very long strings\n continue\n kernel_preview[name] = get_preview_info(obj)\n elif obj_type == \'ndarray\' and HAS_NUMPY:\n kernel_preview[name] = get_preview_info(obj)\n elif obj_type == \'DataFrame\' and HAS_PANDAS:\n kernel_preview[name] = get_preview_info(obj)\n elif obj_type == \'Series\' and HAS_PANDAS:\n kernel_preview[name] = get_preview_info(obj)\n # Skip everything else to avoid clutter\n \n except Exception as e:\n # If we can\'t process this variable, skip it silently\n continue\n \n # Output the result\n if kernel_preview:\n print(json.dumps(kernel_preview, indent=2, default=str))\n else:\n print(json.dumps({"message": "No user-defined variables found in kernel"}, indent=2))\n \nexcept Exception as e:\n # If everything fails, output a detailed error message\n error_info = {\n "error": f"Kernel preview failed: {str(e)}", \n "error_type": type(e).__name__,\n "globals_keys_count": len(globals().keys()) if \'globals\' in dir() else 0\n }\n print(json.dumps(error_info, indent=2, default=str))\n ',silent:!0});n.onIOPub=e=>{const n=e.header.msg_type;"stream"===n&&"stdout"===e.content.name?t+=e.content.text:"error"===n&&console.error("[KernelPreviewUtils] Kernel execution error:",e.content)},n.done.then(()=>{try{if(t.trim()){const n=r(JSON.parse(t.trim()),l);console.log("[KernelPreviewUtils] Filtered kernel variables:",Object.keys(n)),e(n)}else e(null)}catch(n){console.error("[KernelPreviewUtils] Error parsing kernel variables:",n),console.error("[KernelPreviewUtils] Raw buffer:",t),e(null)}}).catch(t=>{console.error("[KernelPreviewUtils] Kernel execution error:",t),e(null)})})}catch(e){return console.error("[KernelPreviewUtils] Error in getKernelVariables:",e),null}}static async getKernelPreview(){const e=await this.getKernelVariables();if(!e)return null;let t="=== KERNEL VARIABLES AND OBJECTS ===\n\n";const n=Object.entries(e);return 0===n.length?(t+="No user-defined variables from notebook found in kernel.\n",t):(n.forEach(([e,n])=>{t+=`\n• Variable: ${e}\n`,t+=` Type: ${n.type||"unknown"}\n`,void 0!==n.size&&null!==n.size&&(t+=` Size: ${n.size}\n`),n.shape&&(t+=` Shape: ${JSON.stringify(n.shape)}\n`),n.columns&&(n.multi_level_columns?t+=` Multi-level Columns (${n.column_levels} levels): ${JSON.stringify(n.columns)}\n`:t+=` Columns: ${JSON.stringify(n.columns)}\n`),n.dtype&&(t+=` Data Type: ${n.dtype}\n`),n.dtypes&&(t+=` Column Types: ${n.dtypes}\n`),n.first_rows&&(t+=" First 2 Rows:\n","string"==typeof n.first_rows?t+=` ${n.first_rows}\n`:t+=` ${JSON.stringify(n.first_rows,null,4)}\n`),void 0!==n.value?t+=` Value: ${JSON.stringify(n.value)}\n`:void 0!==n.preview?(t+=` Preview: ${JSON.stringify(n.preview)}\n`,n.truncated&&(t+=` [truncated - showing first ${n.preview.length||5} items]\n`)):n.repr&&(t+=` Repr: ${n.repr}\n`),n.module&&(t+=` Module: ${n.module}\n`),n.error&&(t+=` Error: ${n.error}\n`),t+="\n"}),t+="=== END KERNEL PREVIEW ===",t)}static async getLimitedKernelPreview(){var e,t;try{const n=o.AppStateService.getToolService(),s=null===(e=null==n?void 0:n.getCurrentNotebook())||void 0===e?void 0:e.kernel;if(console.log("[KernelPreviewUtils] Getting limited kernel variables (last 10 cells)..."),!s)return console.warn("[KernelPreviewUtils] No kernel available"),null;const i=null===(t=o.AppStateService.getState().notebookTools)||void 0===t?void 0:t.read_cells(),l=a((null==i?void 0:i.cells)||[],10);console.log("[KernelPreviewUtils] Found notebook variables (conditional last 10 cells):",Array.from(l));const c=await new Promise(e=>{let t="";const n=s.requestExecute({code:'\nimport json\nimport sys\nimport math\nfrom types import ModuleType, FunctionType, BuiltinFunctionType, BuiltinMethodType\n\n# Try to import common libraries but don\'t fail if they\'re not available\ntry:\n import numpy as np\n HAS_NUMPY = True\nexcept ImportError:\n HAS_NUMPY = False\n\ntry:\n import pandas as pd\n HAS_PANDAS = True\nexcept ImportError:\n HAS_PANDAS = False\n\ndef is_serializable(obj):\n """Check if an object can be JSON serialized"""\n try:\n json.dumps(obj)\n return True\n except (TypeError, ValueError, OverflowError):\n return False\n\ndef safe_json_value(obj):\n """Convert an object to a JSON-safe value, handling NaN, inf, etc."""\n import math\n \n if obj is None:\n return None\n elif isinstance(obj, float):\n if math.isnan(obj):\n return None # Convert NaN to null\n elif math.isinf(obj):\n return "Infinity" if obj > 0 else "-Infinity"\n else:\n return obj\n elif isinstance(obj, (int, str, bool)):\n return obj\n elif isinstance(obj, (list, tuple)):\n return [safe_json_value(item) for item in obj]\n elif isinstance(obj, dict):\n return {k: safe_json_value(v) for k, v in obj.items()}\n else:\n return str(obj)\n\ndef get_preview_info(obj, max_items=3): # Reduced max_items for limited version\n """Get preview information for an object"""\n try:\n obj_type = type(obj).__name__\n \n # Handle basic types\n if obj_type in [\'int\', \'float\', \'str\', \'bool\', \'NoneType\']:\n value = safe_json_value(obj)\n # Truncate very long strings more aggressively\n if obj_type == \'str\' and len(str(obj)) > 100: # Reduced from 200\n value = str(obj)[:100] + "..."\n return {"type": obj_type, "value": value, "size": len(str(obj)) if obj_type == \'str\' else None}\n \n # Handle collections - more aggressive truncation\n elif obj_type in [\'list\', \'tuple\']:\n size = len(obj)\n preview_items = []\n for i, item in enumerate(obj[:max_items]):\n try:\n safe_item = safe_json_value(item)\n if safe_item is not None or item is None:\n preview_items.append(safe_item)\n else:\n preview_items.append(f"<{type(item).__name__} object>")\n except Exception:\n preview_items.append("<unreadable object>")\n return {"type": obj_type, "size": size, "preview": preview_items, "truncated": size > max_items}\n \n elif obj_type == \'dict\':\n size = len(obj)\n preview_dict = {}\n for i, (key, value) in enumerate(list(obj.items())[:max_items]):\n try:\n safe_key = str(key) if not is_serializable(key) else key\n safe_value = safe_json_value(value)\n preview_dict[safe_key] = safe_value\n except Exception:\n preview_dict[str(key)] = "<unreadable object>"\n return {"type": obj_type, "size": size, "preview": preview_dict, "truncated": size > max_items}\n \n elif obj_type == \'set\':\n size = len(obj)\n preview_items = []\n for i, item in enumerate(list(obj)[:max_items]):\n try:\n safe_item = safe_json_value(item)\n if safe_item is not None or item is None:\n preview_items.append(safe_item)\n else:\n preview_items.append(f"<{type(item).__name__} object>")\n except Exception:\n preview_items.append("<unreadable object>")\n return {"type": obj_type, "size": size, "preview": preview_items, "truncated": size > max_items}\n \n # Handle DataFrames with more truncation\n elif obj_type == \'DataFrame\' and HAS_PANDAS:\n try:\n result = {\n "type": obj_type, \n "shape": list(obj.shape),\n "columns": [str(col) for col in list(obj.columns)[:max_items]], \n "dtypes": {str(k): str(v) for k, v in dict(list(obj.dtypes.items())[:max_items]).items()}\n }\n \n if hasattr(obj.columns, \'nlevels\') and obj.columns.nlevels > 1:\n result["multi_level_columns"] = True\n result["column_levels"] = obj.columns.nlevels\n result["columns"] = [str(col) for col in obj.columns[:max_items]]\n \n # Only get first row for limited version\n try:\n first_rows = obj.head(1).to_dict(\'records\')\n safe_rows = []\n for row in first_rows:\n safe_row = {}\n for k, v in row.items():\n try:\n safe_row[str(k)] = safe_json_value(v)\n except Exception:\n safe_row[str(k)] = "<unreadable value>"\n safe_rows.append(safe_row)\n result["first_rows"] = safe_rows\n except Exception:\n result["first_rows"] = "Unable to preview rows"\n \n return result\n except Exception:\n return {"type": obj_type, "shape": list(getattr(obj, \'shape\', []))}\n \n # For numpy arrays\n elif obj_type == \'ndarray\' and HAS_NUMPY:\n try:\n return {\n "type": obj_type, \n "shape": list(obj.shape), \n "dtype": str(obj.dtype),\n "size": int(obj.size)\n }\n except Exception:\n return {"type": obj_type, "shape": "unknown"}\n \n # For other objects - more minimal info\n else:\n try:\n info = {"type": obj_type}\n \n if hasattr(obj.__class__, \'__module__\'):\n info["module"] = str(obj.__class__.__module__)\n \n if hasattr(obj, \'__len__\'):\n try:\n info["length"] = len(obj)\n except Exception:\n pass\n \n # Shorter repr for limited version\n try:\n repr_str = repr(obj)[:50] # Reduced from 100\n if len(repr_str) < len(repr(obj)):\n repr_str += "..."\n info["repr"] = repr_str\n except Exception:\n info["repr"] = f"<{obj_type} object>"\n \n return info\n except Exception:\n return {"type": obj_type, "module": "unknown"}\n \n except Exception as e:\n return {"type": "unknown", "error": str(e)[:50]} # Reduced error message length\n\n# Main execution - same logic but with reduced output\ntry:\n globals_dict = globals()\n globals_snapshot = dict(globals_dict)\n \n kernel_preview = {}\n \n excluded_names = {\n \'In\', \'Out\', \'get_ipython\', \'exit\', \'quit\', \'json\', \'sys\', \n \'get_preview_info\', \'globals_snapshot\', \'kernel_preview\',\n \'HAS_NUMPY\', \'HAS_PANDAS\', \'excluded_names\', \'tables\', \'local_vars\', \n \'constraints\', \'fk\', \'globals_dict\', \'is_serializable\', \'data\',\n \'__name__\', \'__doc__\', \'__package__\', \'__loader__\', \'__spec__\',\n \'__builtin__\', \'__builtins__\', \'_\', \'__\', \'___\'\n }\n \n if HAS_NUMPY:\n excluded_names.add(\'np\')\n if HAS_PANDAS:\n excluded_names.add(\'pd\')\n \n for name, obj in globals_snapshot.items():\n try:\n if (name.startswith(\'_\') or \n isinstance(obj, (ModuleType, FunctionType, BuiltinFunctionType, BuiltinMethodType)) or \n name in excluded_names or\n callable(obj)):\n continue\n \n obj_type = type(obj).__name__\n \n if obj_type in [\'int\', \'float\', \'complex\', \'str\', \'bool\', \'list\', \'tuple\', \'dict\', \'set\']:\n if obj_type == \'str\':\n if len(obj) > 500: # More aggressive string filtering for limited version\n continue\n kernel_preview[name] = get_preview_info(obj)\n elif obj_type == \'ndarray\' and HAS_NUMPY:\n kernel_preview[name] = get_preview_info(obj)\n elif obj_type == \'DataFrame\' and HAS_PANDAS:\n kernel_preview[name] = get_preview_info(obj)\n elif obj_type == \'Series\' and HAS_PANDAS:\n kernel_preview[name] = get_preview_info(obj)\n \n except Exception:\n continue\n \n if kernel_preview:\n print(json.dumps(kernel_preview, indent=2, default=str))\n else:\n print(json.dumps({"message": "No user-defined variables found in kernel"}, indent=2))\n \nexcept Exception as e:\n error_info = {\n "error": f"Kernel preview failed: {str(e)}", \n "error_type": type(e).__name__,\n "globals_keys_count": len(globals().keys()) if \'globals\' in dir() else 0\n }\n print(json.dumps(error_info, indent=2, default=str))\n ',silent:!0});n.onIOPub=e=>{const n=e.header.msg_type;"stream"===n&&"stdout"===e.content.name?t+=e.content.text:"error"===n&&console.error("[KernelPreviewUtils] Kernel execution error:",e.content)},n.done.then(()=>{try{if(t.trim()){const n=r(JSON.parse(t.trim()),l);console.log("[KernelPreviewUtils] Limited filtered kernel variables:",Object.keys(n)),e(n)}else e(null)}catch(t){console.error("[KernelPreviewUtils] Error parsing limited kernel variables:",t),e(null)}}).catch(t=>{console.error("[KernelPreviewUtils] Limited kernel execution error:",t),e(null)})});if(!c)return null;let d="=== KERNEL VARIABLES AND OBJECTS ===\n\n";const h=1e4,u=Object.entries(c);if(0===u.length)return d+="No user-defined variables from notebook found in kernel.\n",d;for(const[e,t]of u){const n=this.formatVariableInfo(e,t);if(d.length+n.length>h-100){d+=`\n[Output truncated - showing first ${d.split("• Variable:").length-1} variables out of ${u.length} total]\n`;break}d+=n}return d+="=== END KERNEL PREVIEW ===",d.length>h&&(d=d.substring(0,h-50)+"\n\n[Output truncated at 10,000 characters]\n=== END KERNEL PREVIEW ==="),d}catch(e){return console.error("[KernelPreviewUtils] Error in getLimitedKernelPreview:",e),null}}static formatVariableInfo(e,t){let n=`\n• Variable: ${e}\n`;if(n+=` Type: ${t.type||"unknown"}\n`,void 0!==t.size&&null!==t.size&&(n+=` Size: ${t.size}\n`),t.shape&&(n+=` Shape: ${JSON.stringify(t.shape)}\n`),t.columns&&(t.multi_level_columns?n+=` Multi-level Columns (${t.column_levels} levels): ${JSON.stringify(t.columns)}\n`:n+=` Columns: ${JSON.stringify(t.columns)}\n`),t.dtype&&(n+=` Data Type: ${t.dtype}\n`),t.dtypes&&(n+=` Column Types: ${JSON.stringify(t.dtypes).substring(0,200)}${JSON.stringify(t.dtypes).length>200?"...":""}\n`),t.first_rows)if(n+=" First Row:\n","string"==typeof t.first_rows)n+=` ${t.first_rows.substring(0,300)}${t.first_rows.length>300?"...":""}\n`;else{const e=JSON.stringify(t.first_rows,null,2);n+=` ${e.substring(0,300)}${e.length>300?"...":""}\n`}if(void 0!==t.value){const e=JSON.stringify(t.value);n+=` Value: ${e.substring(0,200)}${e.length>200?"...":""}\n`}else if(void 0!==t.preview){const e=JSON.stringify(t.preview);n+=` Preview: ${e.substring(0,200)}${e.length>200?"...":""}\n`,t.truncated&&(n+=` [truncated - showing first ${Array.isArray(t.preview)?t.preview.length:3} items]\n`)}else t.repr&&(n+=` Repr: ${t.repr}\n`);return t.module&&"builtins"!==t.module&&(n+=` Module: ${t.module}\n`),t.error&&(n+=` Error: ${t.error}\n`),n+="\n",n}}},2915:e=>{"use strict";e.exports=JSON.parse('{"claude":{"model_name":"claude-sonnet-4-20250514","tool_blacklist":[]},"claude_ask_mode":{"model_name":"claude-sonnet-4-20250514","tool_blacklist":[]},"edit_selection":{"model_name":"claude-3-5-haiku-latest","tool_blacklist":["codebase-list_repos","notebook-add_cell","notebook-remove_cells","notebook-edit_plan","notebook-run_cell","notebook-get_cell_info","notebook-read_cells","web-search_dataset","web-download_dataset","filesystem-list_datasets","filesystem-read_dataset","filesystem-delete_dataset","filesystem-save_dataset","notebook-wait_user_reply"]},"edit_full_cell":{"model_name":"claude-3-5-haiku-latest","tool_blacklist":["codebase-list_repos","notebook-add_cell","notebook-remove_cells","notebook-edit_plan","notebook-run_cell","notebook-get_cell_info","notebook-read_cells","web-search_dataset","web-download_dataset","filesystem-list_datasets","filesystem-read_dataset","filesystem-delete_dataset","filesystem-save_dataset","notebook-wait_user_reply"]},"fast_mode":{"model_name":"claude-sonnet-4-20250514","tool_blacklist":["codebase-list_repos","notebook-edit_plan","notebook-get_cell_info","notebook-read_cells","web-search_dataset","web-download_dataset","filesystem-read_dataset","filesystem-list_datasets","filesystem-delete_dataset","notebook-read_notebook_summary","notebook-wait_user_reply"]}}')},3385:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%27-4 -4 8 8%27%3e%3ccircle r=%272%27 fill=%27%23fff%27/%3e%3c/svg%3e"},3545:e=>{"use strict";e.exports={api_key:null}},3687:(e,t,n)=>{var o={"./claude_system_prompt.md":139,"./claude_system_prompt_ask_mode.md":8051,"./claude_system_prompt_edit_full_cell.md":8883,"./claude_system_prompt_edit_selection.md":5707,"./claude_system_prompt_fast_mode.md":1384,"./plan_generation_prompt.md":9147};function s(e){var t=i(e);return n(t)}function i(e){if(!n.o(o,e)){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}return o[e]}s.keys=function(){return Object.keys(o)},s.resolve=i,e.exports=s,s.id=3687},4274:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 20 20%27%3e%3cpath fill=%27none%27 stroke=%27%23fff%27 stroke-linecap=%27round%27 stroke-linejoin=%27round%27 stroke-width=%273%27 d=%27M6 10h8%27/%3e%3c/svg%3e"},4340:(e,t,n)=>{"use strict";var o,s,i;n.d(t,{fY:()=>s,q6:()=>i,yR:()=>o}),function(e){e.IDLE="idle",e.PENDING="pending",e.COMPLETED="completed",e.ERROR="error",e.CANCELLED="cancelled",e.RETRYING="retrying"}(o||(o={})),function(e){e.PENDING="pending",e.APPROVED="approved",e.REJECTED="rejected",e.PARTIAL="partial"}(s||(s={})),function(e){e.CANCEL="cancel",e.CONTINUE_WITHOUT_RUNNING="continue_without_running",e.CONTINUE_AND_RUN_ALL_CELLS="continue_and_run_all_cells"}(i||(i={}))},4718:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%27-4 -4 8 8%27%3e%3ccircle r=%273%27 fill=%27%23fff%27/%3e%3c/svg%3e"},4914:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 16 16%27 fill=%27%236ea8fe%27%3e%3cpath fill-rule=%27evenodd%27 d=%27M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708%27/%3e%3c/svg%3e"},5372:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 12 12%27 width=%2712%27 height=%2712%27 fill=%27none%27 stroke=%27%23dc3545%27%3e%3ccircle cx=%276%27 cy=%276%27 r=%274.5%27/%3e%3cpath stroke-linejoin=%27round%27 d=%27M5.8 3.6h.4L6 6.5z%27/%3e%3ccircle cx=%276%27 cy=%278.2%27 r=%27.6%27 fill=%27%23dc3545%27 stroke=%27none%27/%3e%3c/svg%3e"},5419:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 20 20%27%3e%3cpath fill=%27none%27 stroke=%27%23fff%27 stroke-linecap=%27round%27 stroke-linejoin=%27round%27 stroke-width=%273%27 d=%27m6 10 3 3 6-6%27/%3e%3c/svg%3e"},5531:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 16 16%27%3e%3cpath fill=%27none%27 stroke=%27%23343a40%27 stroke-linecap=%27round%27 stroke-linejoin=%27round%27 stroke-width=%272%27 d=%27m2 5 6 6 6-6%27/%3e%3c/svg%3e"},5707:e=>{"use strict";e.exports='You are an expert quantitative researcher and data scientist embedded inside a Jupyter notebook environment. You serve as a **selection-level editing assistant**—executing **precise, minimal code edits** on selected portions only.\n\n## Primary Directive\n\n**Return a structured JSON response specifying line-by-line operations. Each line in the selection range must have an explicit operation.**\n\n---\n\n## Rules of Execution\n\n* **Follow User Commands Exactly**: Obey user instructions fully. Do **not** do more than asked. Do not infer or hallucinate missing context, libraries, variables, or data.\n* **Edit Only Selected Code**: Modify only the specific code selection provided. Leave all other cell content unchanged.\n* **Be Context-Aware**: Respect notebook context if available. Don\'t break dependencies or change variable semantics.\n* **Style and Performance**: Prioritize vectorization and correct use of libraries like NumPy, Pandas, Scikit-learn, PyTorch, etc. Make professional plots.\n* **Preserve All Formatting and Nuance**: Do not alter whitespace, indentation, empty lines, or formatting unless explicitly instructed. Every character, space, and line break must remain exactly as in the original selection unless the user requests a change.\n* **Quantitative Style, Not Software Engineering**: Write code like a top-tier quant or data scientist. Favor clarity, elegance, and performance. Avoid overengineering.\n* **No Tool Calls, No Outputs, No Commentary**: Never invoke tools. Never provide any commentary or explanation besides the structured response.\n* **Always Provide Executable Code**: Do not use Markdown formatting, including headers, bold, italic, bullet points, or code blocks.\n\n---\n\n## Output Format\n\n**Return ONLY a JSON object with this exact structure:**\n\n{\n "operations": [\n {\n "line": 1,\n "action": "KEEP|MODIFY|REMOVE|INSERT",\n "content": "line content (required for MODIFY/INSERT, empty for KEEP/REMOVE)"\n }\n ]\n}\n\n\n### Action Types:\n- **KEEP**: Preserve the original line exactly as-is\n- **MODIFY**: Replace the line with new content\n- **REMOVE**: Delete this line entirely\n- **INSERT**: Add a new line at this position (pushes existing lines down)\n'},5782:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%27-4 -4 8 8%27%3e%3ccircle r=%273%27 fill=%27%2386b7fe%27/%3e%3c/svg%3e"},5967:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 16 16%27 fill=%27%23000%27%3e%3cpath d=%27M.293.293a1 1 0 0 1 1.414 0L8 6.586 14.293.293a1 1 0 1 1 1.414 1.414L9.414 8l6.293 6.293a1 1 0 0 1-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 0 1-1.414-1.414L6.586 8 .293 1.707a1 1 0 0 1 0-1.414%27/%3e%3c/svg%3e"},6209:(e,t,n)=>{"use strict";n.r(t),n.d(t,{AppStateService:()=>d});var o=n(6750),s=n(1563),i=n(4744);const a={toolService:null,notebookTracker:null,notebookTools:null,notebookContextManager:null,contentManager:null,settingsRegistry:null,chatService:null,config:null,serviceManager:null,extensions:null,planStateDisplay:null,llmStateDisplay:null,waitingUserReplyBoxManager:null,notebookDiffManager:null,actionHistory:null,cellTrackingService:null,trackingIDUtility:null,contextCellHighlighter:null,chatContainer:null,diffNavigationWidget:null,currentNotebookId:null,currentNotebook:null,isInitialized:!1,contextCache:new Map,contextCacheTimestamp:0,isContextLoading:!1,snippets:[],insertedSnippets:[],maxToolCallLimit:null,settings:{theme:"light",tokenMode:!1,tabAutocompleteEnabled:!1,claudeApiKey:"",claudeModelId:"claude-3-7-sonnet-20250219",claudeModelUrl:"https://sage.alpinex.ai:8760",databaseUrl:""}},r=new o.BehaviorSubject(a),l=new o.Subject,c=new o.Subject,d={getState:()=>r.getValue(),setState:e=>r.next({...r.getValue(),...e}),changes:r.asObservable(),initializeCoreServices:(e,t,n,o,s,i)=>{d.setState({toolService:e,notebookTracker:t,notebookTools:n,notebookContextManager:o,contentManager:s,settingsRegistry:i||null})},initializeManagers:(e,t,n,o)=>{d.setState({planStateDisplay:e,llmStateDisplay:t,waitingUserReplyBoxManager:n,notebookDiffManager:o})},initializeAdditionalServices:(e,t,n,o)=>{d.setState({actionHistory:e,cellTrackingService:t,trackingIDUtility:n,contextCellHighlighter:o})},markAsInitialized:()=>{d.setState({isInitialized:!0})},getCurrentNotebookId:()=>d.getState().currentNotebookId,getCurrentNotebook:()=>d.getState().currentNotebook,setCurrentNotebook:(e,t)=>{const n=d.getState().currentNotebookId,o=t||(e?"unknown":null);n!==o?(d.setState({currentNotebook:e,currentNotebookId:o}),l.next({oldNotebookId:n,newNotebookId:o})):d.setState({currentNotebook:e})},setCurrentNotebookId:e=>{const t=d.getState().currentNotebookId;t!==e&&(d.setState({currentNotebookId:e,currentNotebook:null}),l.next({oldNotebookId:t,newNotebookId:e}))},updateNotebookId:(e,t)=>{d.getState().currentNotebookId===e&&d.setState({currentNotebookId:t,currentNotebook:null}),c.next({oldNotebookId:e,newNotebookId:t})},onNotebookChanged:()=>l.asObservable(),onNotebookRenamed:()=>c.asObservable(),updateSettings:e=>{const t=d.getState();d.setState({settings:{...t.settings,...e}})},updateClaudeSettings:e=>{const t=d.getState();d.setState({settings:{...t.settings,...e}})},getClaudeSettings:()=>{const{settings:e}=d.getState();return{claudeApiKey:e.claudeApiKey,claudeModelId:e.claudeModelId,claudeModelUrl:e.claudeModelUrl,databaseUrl:e.databaseUrl,tabAutocompleteEnabled:e.tabAutocompleteEnabled}},getClaudeApiKey:()=>d.getState().settings.claudeApiKey,getClaudeModelUrl:()=>d.getState().settings.claudeModelUrl,getClaudeModelId:()=>d.getState().settings.claudeModelId,setExtensions:e=>{d.setState({extensions:e})},getExtensions:()=>d.getState().extensions,setSettingsRegistry:e=>{d.setState({settingsRegistry:e})},getSettingsRegistry:()=>d.getState().settingsRegistry,setServiceManager:e=>{d.setState({serviceManager:e})},getServiceManager:()=>d.getState().serviceManager,getToolService:()=>{const e=d.getState().toolService;if(!e)throw new Error("ToolService not initialized in AppState");return e},getNotebookTracker:()=>{const e=d.getState().notebookTracker;if(!e)throw new Error("NotebookTracker not initialized in AppState");return e},getNotebookTools:()=>{const e=d.getState().notebookTools;if(!e)throw new Error("NotebookTools not initialized in AppState");return e},getNotebookContextManager:()=>{const e=d.getState().notebookContextManager;if(!e)throw new Error("NotebookContextManager not initialized in AppState");return e},getContentManager:()=>{const e=d.getState().contentManager;if(!e)throw new Error("ContentManager not initialized in AppState");return e},getPlanStateDisplay:()=>{const e=d.getState().planStateDisplay;if(!e)throw new Error("PlanStateDisplay not initialized in AppState");return e},getLlmStateDisplay:()=>{const e=d.getState().llmStateDisplay;if(!e)throw new Error("LLMStateDisplay not initialized in AppState");return e},getWaitingUserReplyBoxManager:()=>{const e=d.getState().waitingUserReplyBoxManager;if(!e)throw new Error("WaitingUserReplyBoxManager not initialized in AppState");return e},getActionHistory:()=>{const e=d.getState().actionHistory;if(!e)throw new Error("ActionHistory not initialized in AppState");return e},getCellTrackingService:()=>{const e=d.getState().cellTrackingService;if(!e)throw new Error("CellTrackingService not initialized in AppState");return e},getNotebookDiffManager:()=>{const e=d.getState().notebookDiffManager;if(!e)throw new Error("NotebookDiffManager not initialized in AppState");return e},getTrackingIDUtility:()=>{const e=d.getState().trackingIDUtility;if(!e)throw new Error("TrackingIDUtility not initialized in AppState");return e},getContextCellHighlighter:()=>{const e=d.getState().contextCellHighlighter;if(!e)throw new Error("ContextCellHighlighter not initialized in AppState");return e},getChatContainer:()=>{const e=d.getState().chatContainer;if(!e)throw new Error("ChatContainer not initialized in AppState");return e},setChatContainer:e=>{d.setState({chatContainer:e})},getChatContainerSafe:()=>d.getState().chatContainer,setDiffNavigationWidget:e=>{d.setState({diffNavigationWidget:e})},getDiffNavigationWidget:()=>{const e=d.getState().diffNavigationWidget;if(!e)throw new Error("DiffNavigationWidget not initialized in AppState");return e},getDiffNavigationWidgetSafe:()=>d.getState().diffNavigationWidget,setChatService:e=>{d.setState({chatService:e})},getChatService:()=>{const e=d.getState().chatService;if(!e)throw new Error("ChatService not initialized in AppState");return e},setConfig:e=>{d.setState({config:e})},getConfig:()=>{const e=d.getState().config;if(!e)throw new Error("Config not initialized in AppState");return e},updateChatContainerNotebookId:(e,t)=>{const n=d.getState().chatContainer;n&&!n.isDisposed&&n.updateNotebookId(e,t)},getSnippets:()=>d.getState().snippets,setSnippets:async e=>{d.setState({snippets:e});try{await s.K.setObjectValue(s.s.SNIPPETS,e)}catch(e){console.error("[AppStateService] Failed to persist snippets to StateDB:",e)}},addSnippet:async e=>{const t=[...d.getState().snippets,e];d.setState({snippets:t});try{await s.K.setObjectValue(s.s.SNIPPETS,t)}catch(e){console.error("[AppStateService] Failed to persist snippets to StateDB:",e)}},updateSnippet:async(e,t)=>{console.log("[AppStateService] Updating snippet with ID:",e),console.log("[AppStateService] Updates:",t);const n=d.getState().snippets;console.log("[AppStateService] Current snippets count:",n.length);const o=n.map(n=>n.id===e?(console.log("[AppStateService] Found snippet to update:",n.title),{...n,...t}):n);console.log("[AppStateService] Updated snippets count:",o.length),d.setState({snippets:o});try{await s.K.setObjectValue(s.s.SNIPPETS,o),console.log("[AppStateService] Successfully persisted updated snippets to StateDB")}catch(e){console.error("[AppStateService] Failed to persist snippets to StateDB:",e)}},removeSnippet:async e=>{const t=d.getState().snippets.filter(t=>t.id!==e);d.setState({snippets:t});try{await s.K.setObjectValue(s.s.SNIPPETS,t)}catch(e){console.error("[AppStateService] Failed to persist snippets to StateDB:",e)}},loadSnippets:async()=>{try{const e=await s.K.getObjectValue(s.s.SNIPPETS,[]),t=await d.migrateSnippetsForUniqueIds(e);d.setState({snippets:t}),console.log("[AppStateService] Loaded",t.length,"snippets from StateDB")}catch(e){console.error("[AppStateService] Failed to load snippets from StateDB:",e)}},migrateSnippetsForUniqueIds:async e=>{let t=!1;const n=new Set;console.log("[AppStateService] Checking",e.length,"snippets for unique IDs");const o=e.map((e,o)=>{const s=e.id&&"string"==typeof e.id&&e.id.trim().length>0,i=s&&n.has(e.id);if(!s||i){t=!0;const s=d.generateSnippetId();return n.add(s),console.log(`[AppStateService] Migrating snippet #${o} "${e.title}" with new ID: ${s}`+(i?" (duplicate ID)":" (missing/invalid ID)")),{...e,id:s,updatedAt:(new Date).toISOString()}}return n.add(e.id),e});if(t)try{await s.K.setObjectValue(s.s.SNIPPETS,o),console.log("[AppStateService] Successfully migrated snippet IDs to StateDB")}catch(e){console.error("[AppStateService] Failed to save migrated snippets:",e)}else console.log("[AppStateService] All snippets already have valid unique IDs");return o},generateSnippetId:()=>(0,i.v4)(),loadInsertedSnippets:async()=>{try{const e=await s.K.getObjectValue(s.s.INSERTED_SNIPPETS,[]);d.setState({insertedSnippets:e}),console.log("[AppStateService] Loaded",e.length,"inserted snippets from StateDB")}catch(e){console.error("[AppStateService] Failed to load inserted snippets from StateDB:",e)}},saveInsertedSnippets:async()=>{try{const e=d.getState();await s.K.setObjectValue(s.s.INSERTED_SNIPPETS,e.insertedSnippets),console.log("[AppStateService] Saved",e.insertedSnippets.length,"inserted snippets to StateDB")}catch(e){console.error("[AppStateService] Failed to save inserted snippets to StateDB:",e)}},addInsertedSnippet:async e=>{const t=d.getState();if(!t.insertedSnippets.includes(e)){const n=[...t.insertedSnippets,e];d.setState({insertedSnippets:n});try{await s.K.setObjectValue(s.s.INSERTED_SNIPPETS,n),console.log("[AppStateService] Added inserted snippet to StateDB:",e)}catch(e){console.error("[AppStateService] Failed to save inserted snippet to StateDB:",e)}}},removeInsertedSnippet:async e=>{const t=d.getState().insertedSnippets.filter(t=>t!==e);d.setState({insertedSnippets:t});try{await s.K.setObjectValue(s.s.INSERTED_SNIPPETS,t),console.log("[AppStateService] Removed inserted snippet from StateDB:",e)}catch(e){console.error("[AppStateService] Failed to remove inserted snippet from StateDB:",e)}},getInsertedSnippets:()=>{const e=d.getState();return e.snippets.filter(t=>e.insertedSnippets.includes(t.id))},isSnippetInserted:e=>d.getState().insertedSnippets.includes(e),clearInsertedSnippets:async()=>{d.setState({insertedSnippets:[]});try{await s.K.setObjectValue(s.s.INSERTED_SNIPPETS,[]),console.log("[AppStateService] Cleared all inserted snippets from StateDB")}catch(e){console.error("[AppStateService] Failed to clear inserted snippets from StateDB:",e)}},switchChatContainerToNotebook:e=>{const t=d.getState().chatContainer;t&&!t.isDisposed&&t.switchToNotebook(e)},getNotebookByID:async e=>{const t=d.getState().notebookTracker,n=d.getState().contentManager;if(!t||!n)return console.warn("NotebookTracker or ContentManager not initialized"),null;const o=[];t.forEach(e=>{o.push(e)});for(const t of o)try{const o=await n.get(t.context.path);if(o){const n=o.content.metadata||{};if(n.sage_ai&&n.sage_ai.unique_id===e)return t}}catch(e){console.warn(`Error checking notebook ${t.context.path}:`,e)}return t.currentWidget},getCachedContexts:()=>d.getState().contextCache,setCachedContexts:e=>{d.setState({contextCache:e,contextCacheTimestamp:Date.now(),isContextLoading:!1})},updateContextCategory:(e,t)=>{const n=d.getState().contextCache,o=new Map(n);o.set(e,t),d.setState({contextCache:o,contextCacheTimestamp:Date.now()})},isContextLoading:()=>d.getState().isContextLoading,setContextLoading:e=>{d.setState({isContextLoading:e})},getContextCacheAge:()=>Date.now()-d.getState().contextCacheTimestamp,shouldRefreshContexts:()=>d.getContextCacheAge()>3e4,setMaxToolCallLimit:e=>{d.setState({maxToolCallLimit:e})},getMaxToolCallLimit:()=>d.getState().maxToolCallLimit}},6316:e=>{"use strict";e.exports=JSON.parse('[{"name":"notebook-edit_plan","description":"Updates the notebook plan by generating a new plan based on the immediate action and the current notebook summary. Returns the generated plan.\\n\\nArgs:\\n immediate_action: What you are about to do next - be specific about the immediate task.\\n notebook_path: Path to the notebook file. System-managed, should not be set by LLM.\\n\\nReturns:\\n str: The generated plan in markdown format.\\n","input_schema":{"type":"object","properties":{"immediate_action":{"title":"Immediate Action","type":"string"},"notebook_path":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"title":"Notebook Path"}},"required":["immediate_action"],"title":"edit_planArguments"}},{"name":"notebook-read_cells","description":"Reads the specified cells (max 5) and returns content as JSON.\\n\\nArgs:\\n notebook_path: Path to the notebook file. System-managed, should not be set by LLM.\\n start_index: int 0-based start index for cell slice. Default 0.\\n end_index: int 0-based end index (inclusive) for cell slice. Default -1 (last cell).\\n\\nReturns:\\n str: JSON string representing the notebook slice (cells, metadata).\\n","input_schema":{"type":"object","properties":{"notebook_path":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"title":"Notebook Path"},"start_index":{"default":0,"title":"Start Index","type":"integer"},"end_index":{"default":-1,"title":"End Index","type":"integer"}},"title":"read_cellsArguments"}},{"name":"notebook-add_cell","description":"Adds a new cell (code or markdown) to the specified notebook at an optional position, returning its unique ID.\\n\\nArgs:\\n position: 0-based index for insertion (Appends if null), cell_type: Type of cell (\\"code\\" or \\"markdown\\").\\n source: Initial source content for the cell.\\n summary: A summary of the cell\'s content.\\n notebook_path: Path to the notebook file. System-managed, should not be set by LLM.\\nReturns:\\n str: The unique ID of the newly created cell.\\n","input_schema":{"type":"object","properties":{"position":{"anyOf":[{"type":"integer"},{"type":"null"}],"default":null,"title":"Position"},"cell_type":{"title":"Cell Type","type":"string","enum":["code","markdown"],"description":"Type of cell to add. Must be either \'code\' or \'markdown\'. \'raw\' is not supported."},"source":{"title":"Source","type":"string"},"summary":{"title":"Summary","type":"string"},"notebook_path":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"title":"Notebook Path"}},"required":["cell_type","source","summary"],"title":"add_cellArguments"}},{"name":"notebook-remove_cells","description":"Removes a list of cells from the specified notebook using their IDs. Returns True if at least one cell was removed.\\n\\nArgs:\\n cell_ids: A list of unique identifiers of the cells to remove.\\n notebook_path: Path to the notebook file. System-managed, should not be set by LLM.\\n\\nReturns:\\n bool: True if at least one cell was found and removed, False otherwise.\\n","input_schema":{"type":"object","properties":{"cell_ids":{"items":{"type":"string"},"title":"Cell Ids","type":"array"},"notebook_path":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"title":"Notebook Path"}},"required":["cell_ids"],"title":"remove_cellsArguments"}},{"name":"notebook-edit_cell","description":"Modifies the source content of an existing cell. Returns True on success.\\n\\nArgs:\\n cell_id: Unique identifier of the cell to edit.\\n new_source: New source content for the cell.\\n summary: A summary of the cell\'s new content.\\n notebook_path: Path to the notebook file. System-managed, should not be set by LLM.\\n\\nReturns:\\n bool: True if the cell was found and updated, False otherwise.\\n","input_schema":{"type":"object","properties":{"cell_id":{"title":"Cell Id","type":"string"},"new_source":{"title":"New Source","type":"string"},"summary":{"title":"Summary","type":"string"},"notebook_path":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"title":"Notebook Path"}},"required":["cell_id","new_source","summary"],"title":"edit_cellArguments"}},{"name":"notebook-run_cell","description":"Runs a code cell in the specified notebook and returns its formatted output.\\n\\nArgs:\\n cell_id: Unique identifier of the code cell to execute.\\n notebook_path: Path to the notebook file. System-managed, should not be set by LLM.\\n kernel_id: Specific kernel ID to use (system-managed and should not be set by LLM).\\n\\nReturns:\\n List[str]: Formatted output strings from the cell\'s execution.\\nRaises:\\n ValueError: If cell_id is invalid or not a code cell.\\n RuntimeError: If kernel or server communication fails.\\n","input_schema":{"type":"object","properties":{"cell_id":{"title":"Cell Id","type":"string"},"notebook_path":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"title":"Notebook Path"},"kernel_id":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"title":"Kernel Id"}},"required":["cell_id"],"title":"run_cellArguments"}},{"name":"notebook-wait_user_reply","description":"Displays a UI component to inform the user that the agent has completed its turn and is now waiting for a user reply.\\n\\nThis tool should be called as the final action in an assistant\'s turn after providing a complete response or asking a question. It signals that the agent is done processing and is awaiting the user\'s next instruction or answer.\\n\\nThe `recommended_next_prompts` field can be used to suggest up to three possible follow-up responses the user might choose from. These should be **valid, reasonable, and contextually relevant** to the conversation at the time the tool is called. They are meant to guide the user toward likely next actions or replies without restricting them.\\n\\nWhen generating these suggestions:\\n- Include at most **three** prompts.\\n- Ensure **each prompt is distinctly different** — do not provide multiple variations of the same phrase.\\n- Suggestions should be short, clear, and actionable.\\n- At least one suggestion should be a generic progression option such as \\"Continue\\".\\n- Other prompts should be tailored to the specific conversation or content just presented.\\n\\nExamples of valid `recommended_next_prompts` for different contexts:\\n- After explaining a concept: [\\"Continue\\", \\"Can you give an example?\\", \\"Explain it in simpler terms\\"]\\n- After showing data: [\\"Continue\\", \\"Show me a chart of this data\\", \\"Compare with last month\\"]\\n\\nArgs:\\n notebook_path: Path to the notebook file. System-managed, should not be set by LLM.\\n recommended_next_prompts: An optional list of up to three distinct, relevant suggestions for how the user might respond next.\\n\\nReturns:\\n bool: True if the waiting reply box was shown successfully, False otherwise.\\n","input_schema":{"type":"object","properties":{"notebook_path":{"anyOf":[{"type":"string"},{"type":"null"}],"default":null,"title":"Notebook Path"},"recommended_next_prompts":{"items":{"type":"string"},"title":"Queries","default":null,"type":"array"}},"title":"wait_user_replyArguments"}},{"name":"filesystem-read_dataset","description":"Read lines from a dataset in data dir (max 10 lines)\\n\\nArgs:\\n filepath (str): Path to the file to read\\n start (int): Starting line default 0\\n end (int): Ending line default 10\\n\\nReturns:\\n str: JSON object with file contents or error message\\n","input_schema":{"type":"object","properties":{"filepath":{"title":"Filepath","type":"string"},"start":{"default":0,"title":"Start","type":"integer"},"end":{"default":10,"title":"End","type":"integer"}},"required":["filepath"],"title":"read_datasetArguments"}},{"name":"web-search_dataset","description":"\\nSearch for tickers matching the provided query strings.\\nThe search is performed using a fuzzy matching algorithm, so precise queries will generally yield better results.\\n\\nArgs:\\n queries: (List[str]) List of search strings to match against ticker symbols or names.\\n limit: Maximum number of results to return (default: 5, max: 10)\\n\\nReturns:\\n A list of matching ticker dictionaries, aggregated from all queries.\\n","input_schema":{"type":"object","properties":{"queries":{"items":{"type":"string"},"title":"Queries","type":"array"},"limit":{"default":10,"title":"Limit","type":"integer"}},"required":["queries"],"title":"search_datasetArguments"}}]')},6366:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 30 30%27%3e%3cpath stroke=%27rgba%28255, 255, 255, 0.55%29%27 stroke-linecap=%27round%27 stroke-miterlimit=%2710%27 stroke-width=%272%27 d=%27M4 7h22M4 15h22M4 23h22%27/%3e%3c/svg%3e"},7110:(e,t,n)=>{"use strict";n.d(t,{ContextService:()=>s});var o=n(6750);class s{constructor(){this._contextItems=new o.BehaviorSubject(new Map)}static getInstance(){return s.instance||(s.instance=new s),s.instance}getContextItems(){return this._contextItems.asObservable()}getCurrentContextItems(){return new Map(this._contextItems.value)}addContextItem(e){const t=new Map(this._contextItems.value);t.set(e.id,e),this._contextItems.next(t)}removeContextItem(e){const t=new Map(this._contextItems.value);t.delete(e),this._contextItems.next(t)}getContextItem(e){return this._contextItems.value.get(e)}setContextItems(e){this._contextItems.next(new Map(e))}clearContextItems(){this._contextItems.next(new Map)}hasContextItem(e){return this._contextItems.value.has(e)}getContextItemsByType(e){return Array.from(this._contextItems.value.values()).filter(t=>t.type===e)}subscribe(e){const t=this._contextItems.subscribe(e);return()=>t.unsubscribe()}}s.instance=null},7115:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 16 16%27%3e%3cpath fill=%27none%27 stroke=%27%23dee2e6%27 stroke-linecap=%27round%27 stroke-linejoin=%27round%27 stroke-width=%272%27 d=%27m2 5 6 6 6-6%27/%3e%3c/svg%3e"},7154:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%27-4 -4 8 8%27%3e%3ccircle r=%273%27 fill=%27rgba%280, 0, 0, 0.25%29%27/%3e%3c/svg%3e"},8051:e=>{"use strict";e.exports="You are a world leading expert data scientist and quantitative analyst tasked with **answering questions and providing insights about data analysis within Jupyter Notebooks**. You excel in helping users understand **data exploration, analysis, visualization, hypothesis testing, and summarization** by reading and analyzing existing code and data. Your approach is analytical, insightful, and educational.\n\n## Important Rules:\n\n* **Read-only mode**: You can only read and analyze notebooks, never modify or execute code.\n* **Provide clear explanations** for any code or analysis you encounter.\n* **Answer questions comprehensively** based on the notebook content and context.\n* **Suggest improvements** and best practices without implementing them directly.\n* **Limit tool calls**: Bundle related dataset and code searches into minimal calls.\n* **Craft precise, descriptive queries** for dataset and code searches—avoid overly broad or vague single-word queries.\n\n---\n\n## Tool Calling\nFollow these instructions precisely:\n\n* **Explain clearly** before every tool call **why you're using it and what you expect**.\n* **Bundle searches efficiently** into one comprehensive query, not multiple single-word queries.\n* **Stop after every 5 individual tool calls** to ask the user explicitly if they wish to proceed further or adjust your approach.\n* Tools are for your internal use only; **do not call tools from inside code cells**.\n* **Focus on reading and understanding** rather than execution.\n\n---\n\n## Workflow\n\n### Understand the Question:\n\n* **If the notebook has existing content,** quickly read relevant notebook summary and recent context. Do **not** review the entire notebook unnecessarily.\n* **If the notebook is empty,** proceed directly to answering based on the user's question.\n* Determine what specific information or insights the user is seeking.\n\n### Analyze and Explain:\n\n* Provide clear, structured explanations of code, data, and analysis you encounter.\n* Break down complex concepts into understandable components.\n* Highlight key insights, patterns, or potential issues in the analysis.\n\n### Answer Questions:\n\n* Respond to user questions based on the notebook content and your expertise.\n* Provide educational context and explanations for data science concepts.\n* Suggest improvements or alternative approaches when appropriate.\n\n### Dataset Understanding:\n\n* **First search datasets** using the tool to find relevant data sources when needed, clearly stating the exact dataset requirements.\n* Analyze datasets mentioned in the notebook to provide insights.\n* Explain data structures, patterns, and characteristics you observe.\n* Help users understand the implications of their data.\n\n### Code Analysis:\n\n* Explain the purpose and functionality of code you encounter.\n* Identify potential improvements, optimizations, or best practices.\n* Help users understand the logic and reasoning behind analysis approaches.\n\n### Final Outputs:\n\n* Provide comprehensive answers to user questions.\n* Summarize key insights and findings from the analysis.\n* Offer suggestions for further exploration or improvement.\n\n### Error and Issue Analysis:\n\n* When encountering errors or issues in the notebook, explain what went wrong and why.\n* Suggest potential solutions or debugging approaches.\n* Help users understand the root causes of problems.\n\n---\n\n## Response Style\nWhen answering questions, clearly explain:\n- What the code or analysis is doing and why\n- Key insights and findings from the data\n- Potential improvements or alternative approaches\n- Educational context for data science concepts\n- Best practices and recommendations"},8533:(e,t,n)=>{"use strict";n.d(t,{w:()=>s});var o=n(6209);class s{static getActiveModelType(){return this.activeModelType}static setActiveModelType(e){this.activeModelType=e}static getModelConfigurations(){return n(2915)}static async buildModelConfig(e,t,o){const s=this.getModelConfigurations()[e];if(!s)throw new Error(`Unknown model type: ${e}`);return{system_prompt:n(3687)(`./${this.getPromptFileName(e)}.md`),model_name:s.model_name,model_url:t,api_key:o,tool_blacklist:s.tool_blacklist||[]}}static getPromptFileName(e){switch(e){case"claude":default:return"claude_system_prompt";case"claude_ask_mode":return"claude_system_prompt_ask_mode";case"edit_selection":return"claude_system_prompt_edit_selection";case"edit_full_cell":return"claude_system_prompt_edit_full_cell";case"fast_mode":return"claude_system_prompt_fast_mode"}}static getTabCompletionPrompt(){try{const e=n(Object(function(){var e=new Error("Cannot find module './prompts/claude_system_prompt_tab_completion.md'");throw e.code="MODULE_NOT_FOUND",e}()));return"string"==typeof e?e:e&&"string"==typeof e.default?e.default:String(null!=e?e:"").trim()||"You are a code-only completion engine. Return only the next minimal continuation as raw text."}catch(e){return"You are a code completion engine. Return only short continuations."}}static async getConfig(e="",t=""){try{if(!e||!t){const n=o.AppStateService.getClaudeSettings();e=e||n.claudeModelUrl,t=t||n.claudeApiKey}return{claude:await this.buildModelConfig("claude",e,t),claude_ask_mode:await this.buildModelConfig("claude_ask_mode",e,t),edit_selection:await this.buildModelConfig("edit_selection",e,t),edit_full_cell:await this.buildModelConfig("edit_full_cell",e,t),fast_mode:await this.buildModelConfig("fast_mode",e,t),active_model_type:this.activeModelType}}catch(e){throw console.error("Error building configuration:",e),new Error(`Failed to build configuration: ${e}`)}}static async getTools(){return n(6316)}}s.activeModelType="claude"},8661:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 8 8%27%3e%3cpath fill=%27%23198754%27 d=%27M2.3 6.73.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1%27/%3e%3c/svg%3e"},8734:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%27-4 -4 8 8%27%3e%3ccircle r=%273%27 fill=%27rgba%28255, 255, 255, 0.25%29%27/%3e%3c/svg%3e"},8883:e=>{"use strict";e.exports="You are an expert quantitative researcher and data scientist embedded inside a Jupyter notebook environment. You serve as a **cell-level editing assistant**—executing **precise, minimal code edits** on demand.\n\n## Primary Directive\n\n**Only return the fully edited Jupyter cells. No tool calls. No commentary or explanation. No output other than the edited cells.**\n\n---\n\n## Rules of Execution\n\n* **Follow User Commands Exactly**: Obey user instructions fully. Do **not** do more than asked. Do not infer or hallucinate missing context, libraries, variables, or data.\n* **Be Context-Aware**: Respect notebook context if available. Don't break dependencies or change variable semantics.\n* **Style and Performance**: Prioritize vectorization and correct use of libraries like NumPy, Pandas, Scikit-learn, PyTorch, etc. Make professional plots. \n* **Quantitative Style, Not Software Engineering**: Write code like a top-tier quant or data scientist. Favor clarity, elegance, and performance. Avoid overengineering.\n* **No Tool Calls, No Outputs, No Commentary**: Never invoke tools. Never provide any commentary or explanation besides the edited cells.\n* **Always Provide Executable Code**: Do not use Markdown formatting, including headers, bold, italic, bullet points, or code blocks.\n\n---\n\n## Output Format\n\n**Only the revised code cell. No text. No markdown. No notes. Just the final code, clean and executable.** "},9147:e=>{"use strict";e.exports="You are a data science planning assistant. Generate concise, high-level plans for data analysis tasks that focus on data exploration, visualizations, analytical decisions and methodology, not basic programming tasks.\n\nThe user will provide:\n- **Notebook Summary**: Current state of the analysis\n- **Current Plan**: Existing plan (if any) \n- **Immediate Action**: What the analyst is about to do next\n\n## Instructions\n\nCreate a markdown plan with:\n1. A title: `# [Task Name] Plan`\n2. **Major Assumptions paragraph** describing key assumptions about data, methodology, or constraints\n3. **1-4 substantial main steps** using `- [ ]` format for incomplete tasks, `- [x]` for completed tasks\n4. Each main step should be a major analytical phase (15-30 minutes of work). The general format is data collection, exploration, analysis, and conclusion.\n5. **Use 1-2 substeps with indentation** ` - [ ]` for incomplete subtasks, ` - [x]` for completed subtasks\n\n## What to INCLUDE:\n- Data collection decisions (which datasets, time periods, tickers)\n- Analytical methodology choices (DCA vs lump sum, equal vs market-cap weighting)\n- Key calculations and metrics to compute\n- Visualization and comparison strategies\n- Final deliverables and insights\n\n## What to EXCLUDE:\n- Basic programming tasks (importing libraries, creating variables)\n- Trivial data manipulation (loading CSVs, basic pandas operations)\n- Infrastructure setup (folder creation, file naming)\n- Standard coding practices (error handling, data validation)\n\n## Format\n\n```markdown\n# [Task Name] Plan\n\n## Major Assumptions\n[Brief paragraph describing key assumptions about data sources, methodology choices, timeframes, constraints, or analytical approach that will guide the analysis.]\n\n## Plan\n- [ ] [Major analytical phase with multiple components]\n - [ ] [Specific substep within this phase]\n - [ ] [Another substep within this phase]\n- [ ] [Next major analytical phase]\n - [ ] [Substep for this phase]\n- [ ] [Final major phase]\n```\n\n## Rules\n\n- **Include major assumptions** - document key assumptions about data, methodology, timeframes, or constraints in a brief paragraph\n- **3-4 main steps maximum** - each should be a substantial analytical phase\n- **Break down into substeps** - break down main steps into 1-2 specific substeps but not excessively.\n- Focus on **analytical decisions**, not programming mechanics\n- Include specific parameters (amounts, timeframes, metrics) in the steps\n- **Mark completed steps with `[x]`** - Only mark tasks as complete `[x]` if they have ALREADY been accomplished in the notebook based on the notebook summary. Mark a step complete only if all its substeps are complete. Do NOT mark future tasks as complete.\n\nGenerate ONLY the markdown plan. No explanations or commentary. "}}]);
|