@galaxyproject/jupyterlite 0.0.17 → 0.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +4 -3
- package/static/dist/_output/build/schemas/all_federated.json +1 -1
- package/static/dist/_output/extensions/@jupyterlite/ai/install.json +5 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/package.json +252 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/schemas/@jupyterlite/ai/settings-model.json +194 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/116.010504c67cccbe983101.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/155.33f38a7e48ddbeb5bb6e.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/180.96635ff74c0413e0c580.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/19.a1bb726875fe6561330e.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/306.17ff80cd7d3702012f98.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/313.e439dd0f4960f6e7585f.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/324.77487b82034275866b8c.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/340.e42ea25ea5b1b374a682.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/374.d7b4dcf29eb3d2ebfd70.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/472.05d097796e83ea9a22b4.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/529.600d1aebb2de2d73fecb.js +2 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/529.600d1aebb2de2d73fecb.js.LICENSE.txt +8 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/537.eb8d9ccd76231e36d75f.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/593.284fd5d2b50defc573f3.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/665.564d208c226b2753e13b.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/669.0094374ba6e3143702f7.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/692.911f4d7dca73b3737833.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/694.e439dd0f4960f6e7585f.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/709.7578153f9eed366ee430.js +2 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/709.7578153f9eed366ee430.js.LICENSE.txt +19 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/728.d7c2cb9a2f7fdd846b35.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/764.312b4b53ed50be5bf3f8.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/798.dca29a3fc3b23c555f6b.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/88.898492ebc5b41a4607c6.js +2 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/88.898492ebc5b41a4607c6.js.LICENSE.txt +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/885.1670a5138e0a13def795.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/918.e91fcd78edba173284a4.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/92.55c2fe71a33184c2e66d.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/952.003f03c751075980ac7f.js +183 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/remoteEntry.2f103c13fd640ab93eb9.js +1 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/style.js +4 -0
- package/static/dist/_output/extensions/@jupyterlite/ai/static/third-party-licenses.json +352 -0
- package/static/dist/_output/extensions/jl-galaxy/extension.js +1 -1
- package/static/dist/_output/extensions/jupyter-secrets-manager/install.json +5 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/package.json +207 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/schemas/jupyter-secrets-manager/manager.json +14 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/static/728.69cdb8043c4eb7a36084.js +1 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/static/810.7ac328ef761c19894484.js +1 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/static/remoteEntry.6610dc2c9e0921c7f94a.js +1 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/static/style.js +4 -0
- package/static/dist/_output/extensions/jupyter-secrets-manager/static/third-party-licenses.json +16 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/install.json +5 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/package.json +90 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/374.f7ab05aeba5c1aa173c9.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/432.7cb3263d05824765a0d2.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/509.9384daafd8fb72a4ff3a.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/993.f7ab05aeba5c1aa173c9.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/remoteEntry.f80ac7a8e97b08d2a2fd.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/style.js +4 -0
- package/static/dist/_output/extensions/jupyterlab-cell-input-footer-extension/static/third-party-licenses.json +22 -0
- package/static/dist/_output/extensions/jupyterlab-diff/install.json +5 -0
- package/static/dist/_output/extensions/jupyterlab-diff/package.json +224 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/299.07069b808cb23f84a242.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/379.2e2a6add1111d74422d2.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/383.dbd292b18614d410ed4b.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/499.e9c141febe62f251e965.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/680.07069b808cb23f84a242.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/728.559a28b17e14994cba46.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/747.e3256716cc1134700a59.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/879.749253139a5186f32109.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/remoteEntry.4830528fbe7c3ca55989.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/style.js +4 -0
- package/static/dist/_output/extensions/jupyterlab-diff/static/third-party-licenses.json +94 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/install.json +5 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/package.json +90 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/432.57100b29bc9fea211a0e.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/509.d1cc43983763b6a85f45.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/666.84cadfe40c86b502f11d.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/remoteEntry.5577376b289c1f9e2dc2.js +1 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/style.js +4 -0
- package/static/dist/_output/extensions/jupyterlab-eventlistener-extension/static/third-party-licenses.json +22 -0
- package/static/dist/_output/jupyter-lite.json +43 -20
- package/static/dist/_output/pypi/attrs-25.4.0-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/gxy-0.0.0-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/jupyter_core-5.9.1-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/narwhals-2.13.0-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/{platformdirs-4.4.0-py3-none-any.whl → platformdirs-4.5.1-py3-none-any.whl} +0 -0
- package/static/dist/_output/pypi/referencing-0.37.0-py3-none-any.whl +0 -0
- package/static/dist/index.js +2 -2
- package/static/dist/_output/pypi/attrs-25.3.0-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/jupyter_core-5.8.1-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/narwhals-2.6.0-py3-none-any.whl +0 -0
- package/static/dist/_output/pypi/referencing-0.36.2-py3-none-any.whl +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";(self.webpackChunk_jupyterlite_ai=self.webpackChunk_jupyterlite_ai||[]).push([[764,918],{2918:(e,t,o)=>{o.r(t),o.d(t,{CommandIds:()=>n,IAISettingsModel:()=>x,IAgentManager:()=>S,IAgentManagerFactory:()=>M,IChatModelRegistry:()=>I,IDiffManager:()=>P,IProviderRegistry:()=>w,IToolRegistry:()=>C,SECRETS_NAMESPACE:()=>k,SECRETS_REPLACEMENT:()=>E,default:()=>nt});var n,a=o(7495),r=o(7246),i=o(7324),s=o(220),l=o(3070),c=o(1256),d=o(6766),p=o(53),u=o(5596),m=o(9816),g=o(1956),h=o(5882),v=o(6685),f=o(7262),y=o(4602),b=o(7963);class _{name;cacheToolsList;toolFilter=void 0;constructor(e){this._options=e,this.name=e.name||`browser-mcp-server: ${e.url}`,this.cacheToolsList=e.cacheToolsList??!1}async connect(){try{const{StreamableHTTPClientTransport:e}=await Promise.all([o.e(92),o.e(324),o.e(661)]).then(o.bind(o,2324)),{Client:t}=await Promise.all([o.e(92),o.e(88),o.e(661)]).then(o.bind(o,5088)),n={mode:"cors",credentials:"omit",...this._options.requestInit};this._transport=new e(new URL(this._options.url),{authProvider:this._options.authProvider,requestInit:n,fetch:this._options.fetch||fetch,reconnectionOptions:this._options.reconnectionOptions,sessionId:this._options.sessionId}),this._session=new t({name:this.name,version:"1.0.0"}),await this._session.connect(this._transport)}catch(e){throw console.error("Error initializing MCP server:",e),await this.close(),e}}async close(){if(this._session){try{await this._session.close()}catch(e){console.error("Error closing MCP server session:",e)}this._session=null}if(this._transport){try{await this._transport.close()}catch(e){console.error("Error closing MCP server transport:",e)}this._transport=null}}async listTools(){if(!this._session)throw new Error("Server not initialized. Call connect() first.");if(this.cacheToolsList&&!this._cacheDirty&&this._toolsList.length>0)return this._toolsList;try{const{ListToolsResultSchema:e}=await Promise.all([o.e(92),o.e(661)]).then(o.bind(o,8092)),t=await this._session.listTools(),n=e.parse(t);return this._toolsList=n.tools.map(e=>({name:e.name,description:e.description,inputSchema:{type:"object",properties:e.inputSchema?.properties||{},required:e.inputSchema?.required||[],additionalProperties:e.inputSchema?.additionalProperties??!1}})),this._cacheDirty=!1,this._toolsList}catch(e){throw console.error(`Error listing tools from ${this.name}:`,e),e}}async callTool(e,t){if(!this._session)throw new Error("Server not initialized. Call connect() first.");try{const{CallToolResultSchema:n}=await Promise.all([o.e(92),o.e(661)]).then(o.bind(o,8092)),a=await this._session.callTool({name:e,arguments:t??{}},void 0,{timeout:this._options.timeout??3e4});return n.parse(a).content}catch(t){throw console.error(`Error calling tool ${e}:`,t),t}}async invalidateToolsCache(){this._cacheDirty=!0}_session=null;_toolsList=[];_cacheDirty=!0;_transport=null;_options}!function(e){e.openSettings="@jupyterlite/ai:open-settings",e.reposition="@jupyterlite/ai:reposition",e.openChat="@jupyterlite/ai:open-chat",e.moveChat="@jupyterlite/ai:move-chat"}(n||(n={}));const C=new f.Token("@jupyterlite/ai:tool-registry","Tool registry for AI agent functionality"),w=new f.Token("@jupyterlite/ai:provider-registry","Registry for AI providers"),x=new f.Token("@jupyterlite/ai:IAISettingsModel"),S=new f.Token("@jupyterlite/ai:agent-manager"),k="@jupyterlite/ai:providers",E="***",M=new f.Token("@jupyterlite/ai:agent-manager-factory"),I=new f.Token("@jupyterlite/ai:chat-model-registry"),P=new f.Token("@jupyterlite/ai:diff-manager");class T{constructor(e){j.setToken(e.token),this._settingsModel=e.settingsModel,this._secretsManager=e.secretsManager,this._mcpServers=[],this._mcpConnectionChanged=new y.Signal(this),this._initializeAgents().catch(e=>console.warn("Failed to initialize agent in constructor:",e)),this._settingsModel.stateChanged.connect(this._onSettingsChanged,this)}createAgent(e){const t=new A({...e,secretsManager:this._secretsManager});return this._agentManagers.push(t),t}get mcpConnectionChanged(){return this._mcpConnectionChanged}isMCPServerConnected(e){return this._mcpServers.some(t=>t.name===e)}_onSettingsChanged(){this._initializeAgents().catch(e=>console.warn("Failed to initialize agent on settings change:",e))}async _initializeMCPServers(){const e=this._settingsModel.config.mcpServers.filter(e=>e.enabled);let t=!1;for(const e of this._mcpServers)try{await e.close(),t=!0}catch(e){console.warn("Error closing MCP server:",e)}this._mcpServers=[];for(const o of e)try{const e=new _({url:o.url,name:o.name});await e.connect(),this._mcpServers.push(e),t=!0}catch(e){console.warn(`Failed to connect to MCP server "${o.name}" at ${o.url}:`,e)}t&&this._mcpConnectionChanged.emit(this._mcpServers.length>0)}async _initializeAgents(){if(!this._isInitializing){this._isInitializing=!0;try{await this._initializeMCPServers();const e=this._mcpServers.filter(e=>null!==e);this._agentManagers.forEach(t=>{t.initializeAgent(e)})}catch(e){console.warn("Failed to initialize agents:",e)}finally{this._isInitializing=!1}}}_agentManagers=[];_settingsModel;_secretsManager;_mcpServers;_mcpConnectionChanged;_isInitializing=!1}class A{constructor(e){this._settingsModel=e.settingsModel,this._toolRegistry=e.toolRegistry,this._providerRegistry=e.providerRegistry,this._secretsManager=e.secretsManager,this._selectedToolNames=[],this._agent=null,this._runner=new b.Runner({tracingDisabled:!0}),this._history=[],this._mcpServers=[],this._isInitializing=!1,this._controller=null,this._pendingApprovals=new Map,this._interruptedState=null,this._agentEvent=new y.Signal(this),this._tokenUsage=e.tokenUsage??{inputTokens:0,outputTokens:0},this._tokenUsageChanged=new y.Signal(this),this.activeProvider=e.activeProvider??this._settingsModel.config.defaultProvider,this._toolRegistry&&(this._selectedToolNames=Object.keys(this._toolRegistry.tools))}get agentEvent(){return this._agentEvent}get activeProviderChanged(){return this._activeProviderChanged}get tokenUsage(){return this._tokenUsage}get tokenUsageChanged(){return this._tokenUsageChanged}get activeProvider(){return this._activeProvider}set activeProvider(e){this._activeProvider=e,this.initializeAgent(),this._activeProviderChanged.emit(this._activeProvider)}setSelectedTools(e){this._selectedToolNames=[...e],this.initializeAgent().catch(e=>console.warn("Failed to initialize agent on tools change:",e))}get selectedAgentTools(){if(!this._toolRegistry)return[];const e=[];for(const t of this._selectedToolNames){const o=this._toolRegistry.get(t);o&&e.push(o)}return e}hasValidConfig(){const e=this._settingsModel.getProvider(this._activeProvider);if(!e)return!1;if(!e.model)return!1;if(this._providerRegistry){const t=this._providerRegistry.getProviderInfo(e.provider);if("required"===t?.apiKeyRequirement)return!!e.apiKey}return!0}clearHistory(){this._history=[],this._runner=new b.Runner({tracingDisabled:!0}),this._pendingApprovals.clear(),this._interruptedState=null,this._tokenUsage={inputTokens:0,outputTokens:0},this._tokenUsageChanged.emit(this._tokenUsage)}stopStreaming(){this._controller?.abort()}async generateResponse(e){const t=this._settingsModel.config;this._controller=new AbortController;try{if(this._agent||await this.initializeAgent(),!this._agent)throw new Error("Failed to initialize agent");const o=t.toolsEnabled&&this._selectedToolNames.length>0&&this._toolRegistry&&Object.keys(this._toolRegistry.tools).length>0&&this._supportsToolCalling();this._history.push((0,b.user)(e));const n=this._settingsModel.getProvider(this._activeProvider),a=n?.parameters?.maxTurns??25;let r=await this._runner.run(this._agent,this._history,{stream:!0,signal:this._controller.signal,...o&&{maxTurns:a}});await this._processRunResult(r);let i=r.interruptions&&r.interruptions.length>0;for(;i;){this._interruptedState=r;const e=r.interruptions;for(e.length>1?await this._handleGroupedToolApprovals(e):await this._handleSingleToolApproval(e[0]);this._pendingApprovals.size>0;)await new Promise(e=>setTimeout(e,100));r=await this._runner.run(this._agent,r.state,{stream:!0,signal:this._controller.signal,maxTurns:a}),await this._processRunResult(r),i=r.interruptions&&r.interruptions.length>0}this._interruptedState=null,this._history=r.history}catch(e){this._agentEvent.emit({type:"error",data:{error:e}})}finally{this._controller=null}}async approveToolCall(e){const t=this._pendingApprovals.get(e);t?(this._interruptedState&&this._interruptedState.state.approve(t.interruption),t.approved=!0,this._pendingApprovals.delete(e)):console.warn(`No pending approval found for interruption ${e}`)}async rejectToolCall(e){const t=this._pendingApprovals.get(e);t?(this._interruptedState&&this._interruptedState.state.reject(t.interruption),t.approved=!1,this._pendingApprovals.delete(e)):console.warn(`No pending approval found for interruption ${e}`)}async approveGroupedToolCalls(e,t){for(const o of t){const t=this._pendingApprovals.get(o);t&&t.groupId===e&&(this._interruptedState&&this._interruptedState.state.approve(t.interruption),t.approved=!0,this._pendingApprovals.delete(o))}}async rejectGroupedToolCalls(e,t){for(const o of t){const t=this._pendingApprovals.get(o);t&&t.groupId===e&&(this._interruptedState&&this._interruptedState.state.reject(t.interruption),t.approved=!1,this._pendingApprovals.delete(o))}}initializeAgent=async e=>{if(!this._isInitializing){this._isInitializing=!0;try{const t=this._settingsModel.config;void 0!==e&&(this._mcpServers=e);const o=await this._createModel(),n=t.toolsEnabled&&this._selectedToolNames.length>0&&this._toolRegistry&&Object.keys(this._toolRegistry.tools).length>0&&this._supportsToolCalling(),a=n?this.selectedAgentTools:[],r=this._settingsModel.getProvider(this._activeProvider),i=r?.parameters?.temperature??.7,s=r?.parameters?.maxTokens;this._agent=new b.Agent({name:"Assistant",instructions:n?this._getEnhancedSystemPrompt(t.systemPrompt||""):t.systemPrompt||"You are a helpful assistant.",model:o,mcpServers:this._mcpServers,tools:a,...i&&{modelSettings:{temperature:i,maxTokens:s}}})}catch(e){console.warn("Failed to initialize agent:",e),this._agent=null}finally{this._isInitializing=!1}}};async _processRunResult(e){let t="",o=null;for await(const n of e)if("raw_model_stream_event"===n.type){const e=n.data;if("response_started"===e.type)o=`msg-${Date.now()}-${Math.random()}`,t="",this._agentEvent.emit({type:"message_start",data:{messageId:o}});else if("output_text_delta"===e.type){if(o){const n=e.delta||"";t+=n,this._agentEvent.emit({type:"message_chunk",data:{messageId:o,chunk:n,fullContent:t}})}}else if("response_done"===e.type){o&&(this._agentEvent.emit({type:"message_complete",data:{messageId:o,content:t}}),o=null);const n=e.response.usage,{inputTokens:a,outputTokens:r}=n;this._tokenUsage.inputTokens+=a,this._tokenUsage.outputTokens+=r,this._tokenUsageChanged.emit(this._tokenUsage)}else if("model"===e.type){const t=e.event;"tool-call"===t.type&&this._handleToolCallStart(t)}}else"run_item_stream_event"===n.type&&"tool_output"===n.name&&this._handleToolOutput(n)}_formatToolInput(e){try{const t=JSON.parse(e);return JSON.stringify(t,null,2)}catch{return e}}_handleToolCallStart(e){const t=e.toolCallId,o=e.toolName,n=e.input;this._agentEvent.emit({type:"tool_call_start",data:{callId:t,toolName:o,input:this._formatToolInput(n)}})}_handleToolOutput(e){const t=e.item,o=t.rawItem.callId,n="string"==typeof t.output?t.output:JSON.stringify(t.output,null,2),a="function_call_result"===t.rawItem.type&&"incomplete"===t.rawItem.status,r="function_call_result"===t.rawItem.type?t.rawItem.name:"Unknown Tool";this._agentEvent.emit({type:"tool_call_complete",data:{callId:o,toolName:r,output:n,isError:a}})}async _handleSingleToolApproval(e){const t=e.rawItem.name||"Unknown Tool",o=e.rawItem.arguments||"{}",n=`int-${Date.now()}-${Math.random()}`,a="function_call"===e.rawItem.type?e.rawItem.callId:void 0;this._pendingApprovals.set(n,{interruption:e}),this._agentEvent.emit({type:"tool_approval_required",data:{interruptionId:n,toolName:t,toolInput:this._formatToolInput(o),callId:a}})}async _handleGroupedToolApprovals(e){const t=`group-${Date.now()}-${Math.random()}`,o=e.map(e=>{const o=e.rawItem.name||"Unknown Tool",n=e.rawItem.arguments||"{}",a=`int-${Date.now()}-${Math.random()}`;return this._pendingApprovals.set(a,{interruption:e,groupId:t}),{interruptionId:a,toolName:o,toolInput:this._formatToolInput(n)}});this._agentEvent.emit({type:"grouped_approval_required",data:{groupId:t,approvals:o}})}_supportsToolCalling(){const e=this._settingsModel.getProvider(this._activeProvider);if(!e||!this._providerRegistry)return!1;const t=this._providerRegistry.getProviderInfo(e.provider);return!1!==t?.supportsToolCalling}async _createModel(){if(!this._activeProvider)throw new Error("No active provider configured");const e=this._settingsModel.getProvider(this._activeProvider);if(!e)throw new Error("No active provider configured");const t=e.provider,o=e.model,n=e.baseURL;let a;return a=this._secretsManager&&this._settingsModel.config.useSecretsManager?(await this._secretsManager.get(j.getToken(),k,`${t}:apiKey`))?.value??"":this._settingsModel.getApiKey(e.id),function(e,t){if(!t)throw new Error("Provider registry not available");const o=t.createChatModel(e.provider,e);if(!o)throw new Error(`Provider ${e.provider} not found or failed to create model`);return o}({provider:t,model:o,apiKey:a,baseURL:n},this._providerRegistry)}_getEnhancedSystemPrompt(e){return e+"\n\nIMPORTANT: Follow this message flow pattern for better user experience:\n\n1. FIRST: Explain what you're going to do and your approach\n2. THEN: Execute tools (these will show automatically with step numbers)\n3. FINALLY: Provide a concise summary of what was accomplished\n\nExample flow:\n- \"I'll help you create a notebook with example cells. Let me first create the file structure, then add Python and Markdown cells.\"\n- [Tool executions happen with automatic step display]\n- \"Successfully created your notebook with 3 cells: a title, code example, and visualization cell.\"\n\nGuidelines:\n- Start responses with your plan/approach before tool execution\n- Let the system handle tool execution display (don't duplicate details)\n- End with a brief summary of accomplishments\n- Use natural, conversational tone throughout\n\nCOMMAND DISCOVERY:\n- When you want to execute JupyterLab commands, ALWAYS use the 'discover_commands' tool first to find available commands and their metadata, with the optional query parameter.\n- The query should typically be a single word, e.g., 'terminal', 'notebook', 'cell', 'file', 'edit', 'view', 'run', etc, to find relevant commands.\n- If searching with a query does not yield the desired command, try again with a different query or use an empty query to list all commands.\n- This ensures you have complete information about command IDs, descriptions, and required arguments before attempting to execute them. Only after discovering the available commands should you use the 'execute_command' tool with the correct command ID and arguments.\n\nTOOL SELECTION GUIDELINES:\n- For file operations (create, read, write, modify files and directories): Use dedicated file manipulation tools\n- For general JupyterLab UI interactions (opening panels, running commands, navigating interface): Use the general command tool (execute_command)\n- Examples of file operations: Creating notebooks, editing code files, managing project structure\n- Examples of UI interactions: Opening terminal, switching tabs, running notebook cells, accessing menus\n"}_settingsModel;_toolRegistry;_providerRegistry;_secretsManager;_selectedToolNames;_agent;_runner;_history;_mcpServers;_isInitializing;_controller;_pendingApprovals;_interruptedState;_agentEvent;_tokenUsage;_tokenUsageChanged;_activeProvider="";_activeProviderChanged=new y.Signal(this)}var j;!function(e){let t;e.setToken=function(e){t=e},e.getToken=function(){return t}}(j||(j={}));var R=o(5311);class ${get providers(){return{...this._providers}}get providersChanged(){return this._providersChanged}registerProvider(e){if(e.id in this._providers)throw new Error(`Provider with id "${e.id}" is already registered`);this._providers[e.id]={...e},this._providersChanged.emit()}getProviderInfo(e){return this._providers[e]||null}createChatModel(e,t){const o=this._providers[e];if(!o)return null;const n=o.factory(t);return(0,R.aisdk)(n)}createCompletionModel(e,t){const o=this._providers[e];return o?o.factory(t):null}getAvailableProviders(){return Object.keys(this._providers)}_providers={};_providersChanged=new y.Signal(this)}class N{constructor(e){this._chatPanel=e.chatPanel,this._chatModel=this._chatPanel.model,this._setupApprovalHandlers(),this._setupMessageProcessing()}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._mutationObserver&&(this._mutationObserver.disconnect(),this._mutationObserver=void 0),this._chatPanel.node.querySelectorAll(".jp-ai-approval-btn").forEach(e=>{e.removeEventListener("click",this._handleButtonClick)}),this._chatPanel.node.querySelectorAll(".jp-ai-group-approval-buttons button").forEach(e=>{e.removeEventListener("click",this._handleGroupedButtonClick)}),this._chatModel=null,this._chatPanel=null)}_setupApprovalHandlers(){this._chatPanel.node.querySelectorAll(".jp-ai-approval-btn").forEach(e=>{this._addButtonHandler(e)})}_addButtonHandler(e){e.removeEventListener("click",this._handleButtonClick),e.addEventListener("click",this._handleButtonClick)}_handleButtonClick=async e=>{const t=e.target;e.preventDefault(),e.stopPropagation();const o=t.closest(".jp-ai-tool-approval-buttons");if(!o)return;const n=o.getAttribute("data-interruption-id");if(!n)return;const a=o.getAttribute("data-message-id"),r=t.classList.contains("jp-ai-approval-approve");this._showApprovalStatus(o,r),r?await this._chatModel.approveToolCall(n,a||void 0):t.classList.contains("jp-ai-approval-reject")&&await this._chatModel.rejectToolCall(n,a||void 0)};_addGroupedButtonHandler(e){e.removeEventListener("click",this._handleGroupedButtonClick),e.addEventListener("click",this._handleGroupedButtonClick)}_handleGroupedButtonClick=async e=>{const t=e.target;e.preventDefault(),e.stopPropagation();const o=t.closest(".jp-ai-group-approval-buttons");if(!o)return;const n=o.getAttribute("data-group-id"),a=o.getAttribute("data-interruption-ids");if(!n||!a)return;const r=a.split(","),i=o.getAttribute("data-message-id"),s=t.classList.contains("jp-ai-group-approve-all");this._showGroupApprovalStatus(o,s),s?await this._chatModel.approveGroupedToolCalls(n,r,i||void 0):t.classList.contains("jp-ai-group-reject-all")&&await this._chatModel.rejectGroupedToolCalls(n,r,i||void 0)};_showApprovalStatus(e,t){e.innerHTML="";const o=document.createElement("div");o.className="jp-ai-approval-status "+(t?"jp-ai-approval-status-approved":"jp-ai-approval-status-rejected");const n=document.createElement("span");n.className="jp-ai-approval-icon",n.textContent=t?"✅":"❌";const a=document.createElement("span");a.textContent=t?"Tools approved":"Tools rejected",o.appendChild(n),o.appendChild(a),e.appendChild(o)}_showGroupApprovalStatus(e,t){e.innerHTML="";const o=document.createElement("div");o.className="jp-ai-group-approval-status "+(t?"jp-ai-group-approval-status-approved":"jp-ai-group-approval-status-rejected");const n=document.createElement("span");n.className="jp-ai-approval-icon",n.textContent=t?"✅":"❌";const a=document.createElement("span");a.textContent=t?"Tools approved":"Tools rejected",o.appendChild(n),o.appendChild(a),e.appendChild(o)}_setupMessageProcessing(){this._mutationObserver=new MutationObserver(e=>{this._isDisposed||e.forEach(e=>{e.addedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;this._processApprovalButtons(t)}})})}),this._mutationObserver.observe(this._chatPanel.node,{childList:!0,subtree:!0})}_processApprovalButtons(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),o=[];let n;for(;n=t.nextNode();)o.push(n);o.forEach(e=>{const t=e.textContent||"",o=t.match(/\[APPROVAL_BUTTONS:([^\]]+)\]/);if(o)return void this._createSingleApprovalButtons(e,o[1]);const n=t.match(/\[GROUP_APPROVAL_BUTTONS:([^:]+):([^\]]+)\]/);n&&this._createGroupedApprovalButtons(e,n[1],n[2])})}_createApprovalButton(e,t,o=""){const n=document.createElement("button"),a=t?"jp-ai-approval-approve":"jp-ai-approval-reject";return n.className=`jp-ai-approval-btn ${a}${o?" "+o:""}`,n.textContent=e,n}_createSingleApprovalButtons(e,t){const o=document.createElement("div");o.className="jp-ai-tool-approval-buttons",o.setAttribute("data-interruption-id",t);const n=this._findMessageId(e);n&&o.setAttribute("data-message-id",n);const a=this._createApprovalButton("Approve",!0),r=this._createApprovalButton("Reject",!1);this._addButtonHandler(a),this._addButtonHandler(r),o.appendChild(a),o.appendChild(r);const i=e.parentNode;i&&i.replaceChild(o,e)}_createGroupedApprovalButtons(e,t,o){const n=document.createElement("div");n.className="jp-ai-group-approval-buttons",n.setAttribute("data-group-id",t),n.setAttribute("data-interruption-ids",o);const a=this._findMessageId(e);a&&n.setAttribute("data-message-id",a);const r=this._createApprovalButton("Approve",!0,"jp-ai-group-approve-all"),i=this._createApprovalButton("Reject",!1,"jp-ai-group-reject-all");this._addGroupedButtonHandler(r),this._addGroupedButtonHandler(i),n.appendChild(r),n.appendChild(i);const s=e.parentNode;s&&s.replaceChild(n,e)}_findMessageId(e){let t=e.parentNode;for(;t&&t!==document.body;){if(t.nodeType===Node.ELEMENT_NODE){const e=t,o=e.getAttribute("data-message-id")||e.getAttribute("id")||e.querySelector("[data-message-id]")?.getAttribute("data-message-id");if(o)return o}t=t.parentNode}return null}_chatPanel;_chatModel;_isDisposed=!1;_mutationObserver}var F=o(3603);const z=new h.LabIcon({name:"@jupyterlite/ai:jupyternaut",svgstr:'<?xml version="1.0" encoding="UTF-8"?>\n<svg fill="none" version="1.1" viewBox="0 0 38 38" xmlns="http://www.w3.org/2000/svg">\n <g>\n <circle cx="19" cy="19" r="19" fill="#f7dc1e"/>\n <path d="m19.948 6.8365c0.6344-0.21603 1.0908-0.81693 1.0908-1.5244 0-0.88916-0.7208-1.61-1.61-1.61s-1.61 0.72081-1.61 1.61c0 0.70739 0.4562 1.3082 1.0905 1.5243v1.1674h-0.5394c-6.2858 0-11.399 5.1132-11.399 11.399 0 6.2859 5.1133 11.399 11.399 11.399h1.398c6.2859 0 11.399-5.1132 11.399-11.399 0-6.2253-5.0159-11.301-11.219-11.397v-1.1687zm-1.5781 22.163h1.398c5.3669 0 9.7303-4.9787 9.7303-8.3455 0-5.3669-4.3634-9.7303-9.7303-9.7303h-1.398c-5.3668 0-9.7302 4.3634-9.7302 9.7303 0 3.3668 4.3634 8.3455 9.7302 8.3455zm14.522-5.003c0.7341 0 0.7375-0.5123 0.7422-1.2408v-1e-4c0.0012-0.1847 0.0025-0.3833 0.0158-0.591 0.0573-0.8624 0.0739-1.7008 0.0573-2.4892l-0.0033-0.119c-0.0373-1.3318-0.0436-1.5579-1.3047-1.8058l-0.1479-0.0246 0.0015 0.0495c0.0076 0.2465 0.0151 0.493 0.0151 0.739 0 1.8018-0.2712 3.5478-0.773 5.189-0.1363 0.4459 0.3433 0.8629 0.7534 0.6411l0.6436-0.3481zm-27.612 0c-0.73409 0-0.73741-0.5123-0.74215-1.2407-0.0012-0.1848-0.00249-0.3834-0.01581-0.5912-0.0573-0.8624-0.07392-1.7007-0.05731-2.4892l0.00336-0.1189c0.03721-1.3319 0.04352-1.5579 1.3047-1.8058l0.14784-0.0247-0.00151 0.0495c-0.00756 0.2465-0.01511 0.493-0.01511 0.739 0 1.8019 0.27119 3.5478 0.773 5.189 0.13634 0.4459-0.34326 0.8629-0.7534 0.6411l-0.64361-0.3481zm14.242-12.005c-4.6297 0-8.4776 2.9361-9.4584 6.7577-0.13379 0.5212 0.5513 0.6935 0.877 0.2653 1.3829-1.818 3.1418-2.153 4.7068-2.4511 2.1143-0.4027 3.8746-0.7379 3.8746-4.5719z" clip-rule="evenodd" fill="#000" fill-rule="evenodd"/>\n </g>\n</svg>'}),O=`data:image/svg+xml;base64,${btoa(z.svgstr)}`;class U extends r.AbstractChatModel{constructor(e){super({activeCellManager:e.activeCellManager,documentManager:e.documentManager,config:{enableCodeToolbar:!0,sendWithShiftEnter:e.settingsModel.config.sendWithShiftEnter}}),this._settingsModel=e.settingsModel,this._user=e.user,this._agentManager=e.agentManager,this._agentManager.agentEvent.connect(this._onAgentEvent,this),this._settingsModel.stateChanged.connect(this._onSettingsChanged,this),this.setReady()}get name(){return super.name}set name(e){super.name=e,this._nameChanged.emit(e)}get nameChanged(){return this._nameChanged}get user(){return this._user}get tokenUsageChanged(){return this._agentManager.tokenUsageChanged}get agentManager(){return this._agentManager}createChatContext(){return{name:this.name,user:{username:"me"},users:[],messages:this.messages,stopStreaming:()=>this.stopStreaming(),clearMessages:()=>this.clearMessages(),agentManager:this._agentManager}}stopStreaming=()=>{this._agentManager.stopStreaming()};clearMessages=()=>{this.messagesDeleted(0,this.messages.length),this._pendingToolCalls.clear(),this._agentManager.clearHistory()};async sendMessage(e){const t={body:e.body,sender:this.user||{username:"user",display_name:"User"},id:f.UUID.uuid4(),time:Date.now()/1e3,type:"msg",raw_time:!1,attachments:[...this.input.attachments]};if(this.messageAdded(t),!this._agentManager.hasValidConfig()){const e={body:"Please configure your AI settings first. Open the AI Settings to set your API key and model.",sender:this._getAIUser(),id:f.UUID.uuid4(),time:Date.now()/1e3,type:"msg",raw_time:!1};return void this.messageAdded(e)}try{let t=e.body;if(this.input.attachments.length>0){const e=await this._processAttachments(this.input.attachments);this.input.clearAttachments(),e.length>0&&(t+="\n\n--- Attached Files ---\n"+e.join("\n\n"))}this.updateWriters([{user:this._getAIUser()}]),await this._agentManager.generateResponse(t)}catch(e){const t={body:`Error generating AI response: ${e.message}`,sender:this._getAIUser(),id:f.UUID.uuid4(),time:Date.now()/1e3,type:"msg",raw_time:!1};this.messageAdded(t)}finally{this.updateWriters([])}}async approveToolCall(e,t){await this._agentManager.approveToolCall(e),t&&this._updateToolCallBoxStatus(t,"Approved",!0)}async rejectToolCall(e,t){await this._agentManager.rejectToolCall(e),t&&this._updateToolCallBoxStatus(t,"Rejected",!1)}async approveGroupedToolCalls(e,t,o){await this._agentManager.approveGroupedToolCalls(e,t),o&&this._updateGroupedApprovalStatus(o,"Tools approved",!0)}async rejectGroupedToolCalls(e,t,o){await this._agentManager.rejectGroupedToolCalls(e,t),o&&this._updateGroupedApprovalStatus(o,"Tools rejected",!1)}_getAIUser(){return{username:"ai-assistant",display_name:"Jupyternaut",initials:"JN",color:"#2196F3",avatar_url:O}}_onSettingsChanged(){const e=this._settingsModel.config;this.config={...e,enableCodeToolbar:!0}}_onAgentEvent(e,t){switch(t.type){case"message_start":this._handleMessageStart(t);break;case"message_chunk":this._handleMessageChunk(t);break;case"message_complete":this._handleMessageComplete(t);break;case"tool_call_start":this._handleToolCallStartEvent(t);break;case"tool_call_complete":this._handleToolCallCompleteEvent(t);break;case"tool_approval_required":this._handleToolApprovalRequired(t);break;case"grouped_approval_required":this._handleGroupedApprovalRequired(t);break;case"error":this._handleErrorEvent(t)}}_handleMessageStart(e){const t={body:"",sender:this._getAIUser(),id:e.data.messageId,time:Date.now()/1e3,type:"msg",raw_time:!1};this._currentStreamingMessage=t,this.messageAdded(t)}_handleMessageChunk(e){this._currentStreamingMessage&&this._currentStreamingMessage.id===e.data.messageId&&(this._currentStreamingMessage.body=e.data.fullContent,this.messageAdded(this._currentStreamingMessage))}_handleMessageComplete(e){this._currentStreamingMessage&&this._currentStreamingMessage.id===e.data.messageId&&(this._currentStreamingMessage.body=e.data.content,this.messageAdded(this._currentStreamingMessage),this._currentStreamingMessage=null)}_handleToolCallStartEvent(e){const t=f.UUID.uuid4(),o={body:`<details class="jp-ai-tool-call jp-ai-tool-pending">\n<summary class="jp-ai-tool-header">\n<div class="jp-ai-tool-icon">⚡</div>\n<div class="jp-ai-tool-title">${e.data.toolName}</div>\n<div class="jp-ai-tool-status jp-ai-tool-status-pending">Running...</div>\n</summary>\n<div class="jp-ai-tool-body">\n<div class="jp-ai-tool-section">\n<div class="jp-ai-tool-label">Input</div>\n<pre class="jp-ai-tool-code"><code>${e.data.input}</code></pre>\n</div>\n</div>\n</details>`,sender:this._getAIUser(),id:t,time:Date.now()/1e3,type:"msg",raw_time:!1};e.data.callId&&this._pendingToolCalls.set(e.data.callId,t),this.messageAdded(o)}_handleToolCallCompleteEvent(e){const t=this._pendingToolCalls.get(e.data.callId);if(t){const o=this.messages.findIndex(e=>e.id===t);if(-1!==o){const t=this.messages[o],n=t.body.match(/<code>([\s\S]*?)<\/code>/)?.[1]||"",a=e.data.isError?"jp-ai-tool-error":"jp-ai-tool-completed",r=e.data.isError?"Error":"Completed",i=e.data.isError?"jp-ai-tool-status-error":"jp-ai-tool-status-completed",s={...t,body:`<details class="jp-ai-tool-call ${a}">\n<summary class="jp-ai-tool-header">\n<div class="jp-ai-tool-icon">⚡</div>\n<div class="jp-ai-tool-title">${e.data.toolName}</div>\n<div class="jp-ai-tool-status ${i}">${r}</div>\n</summary>\n<div class="jp-ai-tool-body">\n<div class="jp-ai-tool-section">\n<div class="jp-ai-tool-label">Input</div>\n<pre class="jp-ai-tool-code"><code>${n}</code></pre>\n</div>\n<div class="jp-ai-tool-section">\n<div class="jp-ai-tool-label">${e.data.isError?"Error":"Result"}</div>\n<pre class="jp-ai-tool-code"><code>${e.data.output}</code></pre>\n</div>\n</div>\n</details>`};this.messageAdded(s),this._pendingToolCalls.delete(e.data.callId)}}}_handleToolApprovalRequired(e){if(e.data.callId){const t=this._pendingToolCalls.get(e.data.callId);if(t){const o=this.messages.findIndex(e=>e.id===t);if(-1!==o){const t=this.messages[o],n=this._getAIUser().display_name,a={...t,body:`<details class="jp-ai-tool-call jp-ai-tool-pending" open>\n<summary class="jp-ai-tool-header">\n<div class="jp-ai-tool-icon">⚡</div>\n<div class="jp-ai-tool-title">${e.data.toolName}</div>\n<div class="jp-ai-tool-status jp-ai-tool-status-pending">Needs Approval</div>\n</summary>\n<div class="jp-ai-tool-body">\n<div class="jp-ai-tool-section">\n<div class="jp-ai-tool-label">${n} wants to execute this tool. Do you approve?</div>\n<pre class="jp-ai-tool-code"><code>${e.data.toolInput}</code></pre>\n</div>\n[APPROVAL_BUTTONS:${e.data.interruptionId}]\n</div>\n</details>`};return this.messageAdded(a),void this.updateWriters([])}}}const t=f.UUID.uuid4(),o=this._getAIUser().display_name,n={body:`**🤖 Tool Approval Required: ${e.data.toolName}**\n\n${o} wants to execute this tool. Do you approve?\n\n\`\`\`json\n${e.data.toolInput}\n\`\`\`\n\n[APPROVAL_BUTTONS:${e.data.interruptionId}]`,sender:this._getAIUser(),id:t,time:Date.now()/1e3,type:"msg",raw_time:!1};this.messageAdded(n),this.updateWriters([])}_handleGroupedApprovalRequired(e){const t=this._getAIUser().display_name,o=f.UUID.uuid4(),n=e.data.approvals.map((e,t)=>`**${t+1}. ${e.toolName}**\n\`\`\`json\n${e.toolInput}\n\`\`\`\n`).join("\n\n"),a={body:`**🤖 Multiple Tool Approvals Required**\n\n${t} wants to execute ${e.data.approvals.length} tools. Do you approve?\n\n${n}\n\n[GROUP_APPROVAL_BUTTONS:${e.data.groupId}:${e.data.approvals.map(e=>e.interruptionId).join(",")}]`,sender:this._getAIUser(),id:o,time:Date.now()/1e3,type:"msg",raw_time:!1};this.messageAdded(a),this.updateWriters([])}_handleErrorEvent(e){const t={body:`Error generating response: ${e.data.error.message}`,sender:this._getAIUser(),id:f.UUID.uuid4(),time:Date.now()/1e3,type:"msg",raw_time:!1};this.messageAdded(t)}async _processAttachments(e){const t=[];for(const o of e)try{if("notebook"===o.type&&o.cells?.length){const e=await this._readNotebookCells(o);e&&t.push(e)}else{const e=await this._readFileAttachment(o);if(e){const n=".ipynb"===F.PathExt.extname(o.value).toLowerCase()?"json":"";t.push(`**File: ${o.value}**\n\`\`\`${n}\n${e}\n\`\`\``)}}}catch(e){console.warn(`Failed to read attachment ${o.value}:`,e),t.push(`**File: ${o.value}** (Could not read file)`)}return t}async _readNotebookCells(e){if("notebook"!==e.type||!e.cells)return null;try{const t=await(this.input.documentManager?.services.contents.get(e.value));if(!t||"notebook"!==t.type)return null;const o=t.content?.metadata?.language_info?.name||t.content?.metadata?.kernelspec?.language||"text",n=e.cells.map(e=>{const n=t.content.cells.find(t=>t.id===e.id);if(!n)return null;const a=n.source||"",r=n.cell_type,i="code"===r?o:r,s=["application/vnd.jupyter.widget-view+json","application/javascript","text/html","image/svg+xml","image/png","image/jpeg","text/markdown","text/latex","text/plain"];let l="";return"code"===r&&Array.isArray(n.outputs)&&(l=n.outputs.map(e=>{if("stream"===e.output_type)return e.text;if("error"===e.output_type){const t=e;return`${t.ename}: ${t.evalue}\n${(t.traceback||[]).join("\n")}`}if("execute_result"===e.output_type||"display_data"===e.output_type){const t=e.data;if(!t)return"";try{return function(e){for(const t of s){if(!(t in e))continue;const o=e[t];if(o)switch(t){case"application/vnd.jupyter.widget-view+json":return`Widget: ${o.model_id??"unknown model"}`;case"image/png":return`}...)`;case"image/jpeg":return`}...)`;case"image/svg+xml":return String(o).slice(0,500)+"...\n[svg truncated]";case"text/html":return String(o).slice(0,1e3)+(String(o).length>1e3?"\n...[truncated]":"");case"text/markdown":case"text/latex":case"text/plain":{let e=Array.isArray(o)?o.join(""):String(o);return e.length>2e3&&(e=e.slice(0,2e3)+"\n...[truncated]"),e}default:return JSON.stringify(o).slice(0,2e3)}}return JSON.stringify(e).slice(0,2e3)}(t)}catch(e){return console.error("Cannot extract cell output",e),""}}return""}).filter(Boolean).join("\n---\n"),l.length>2e3&&(l=l.slice(0,2e3)+"\n...[truncated]")),`**Cell [${e.id}] (${r}):**\n\`\`\`${i}\n${a}\n\`\`\``+(l?`\n**Outputs:**\n\`\`\`text\n${l}\n\`\`\``:"")}).filter(Boolean).join("\n\n");return`**Notebook: ${e.value}**\n${n}`}catch(t){return console.warn(`Failed to read notebook cells from ${e.value}:`,t),null}}async _readFileAttachment(e){if("file"!==e.type&&"notebook"!==e.type)return null;try{const t=await(this.input.documentManager?.services.contents.get(e.value));if(!t?.content)return null;if("file"===t.type)return t.content;if("notebook"===t.type){const e={cells:t.content.cells.map(e=>{const t={...e};return t.outputs&&(t.outputs=[]),t.execution_count&&(t.execution_count=null),t}),metadata:t.metadata||{},nbformat:t.nbformat||4,nbformat_minor:t.nbformat_minor||4};return JSON.stringify(e)}return null}catch(t){return console.warn(`Failed to read file ${e.value}:`,t),null}}_updateGroupedApprovalStatus(e,t,o){const n=this.messages.findIndex(t=>t.id===e);if(-1!==n){const e=this.messages[n],a=e.body.match(/execute (\d+) tools/),r=a?a[1]:"multiple",i=o?"✅":"❌",s=o?"approved":"rejected",l={...e,body:`**${i} Group Tool Approval: ${t}**\n\nThe request to execute ${r} tools has been **${s}**.\n\n<div class="jp-ai-group-approval-${s}">\nStatus: ${t}\n</div>`};this.messageAdded(l)}}_updateToolCallBoxStatus(e,t,o){const n=this.messages.findIndex(t=>t.id===e);if(-1!==n){const e=this.messages[n],a=e.body.match(/<div class="jp-ai-tool-title">([^<]+)<\/div>/),r=a?a[1]:"Unknown Tool",i=e.body.match(/<code>([\s\S]*?)<\/code>/),s=i?i[1]:"{}",l=o?"jp-ai-tool-completed":"jp-ai-tool-error",c=o?"jp-ai-tool-status-completed":"jp-ai-tool-status-error",d={...e,body:`<details class="jp-ai-tool-call ${l}">\n<summary class="jp-ai-tool-header">\n<div class="jp-ai-tool-icon">⚡</div>\n<div class="jp-ai-tool-title">${r}</div>\n<div class="jp-ai-tool-status ${c}">${t}</div>\n</summary>\n<div class="jp-ai-tool-body">\n<div class="jp-ai-tool-section">\n<div class="jp-ai-tool-label">Input</div>\n<pre class="jp-ai-tool-code"><code>${s}</code></pre>\n</div>\n</div>\n</details>`};this.messageAdded(d)}}_settingsModel;_user;_pendingToolCalls=new Map;_agentManager;_currentStreamingMessage=null;_nameChanged=new y.Signal(this)}class L{constructor(e){this._docManager=e.docManager,this._agentManagerFactory=e.agentManagerFactory,this._settingsModel=e.settingsModel,this._toolRegistry=e.toolRegistry,this._providerRegistry=e.providerRegistry,this._activeCellManager=e.activeCellManager}createModel(e,t,o){const n=this._agentManagerFactory.createAgent({settingsModel:this._settingsModel,toolRegistry:this._toolRegistry,providerRegistry:this._providerRegistry,activeProvider:t,tokenUsage:o}),a=new U({user:{username:"user",display_name:"User"},settingsModel:this._settingsModel,agentManager:n,activeCellManager:this._activeCellManager,documentManager:this._docManager});if(!e||-1!==this._models.findIndex(t=>t.name===e)){const t=this.getAll().map(e=>e.name),o=this._settingsModel.getProvider(n.activeProvider)?.name||f.UUID.uuid4();e=o;let a=1;for(;t.includes(e);)e=`${o}-${a}`,a+=1}return a.name=e,this.add(a),a}add(e){this._models.find(t=>t.name===e.name)||this._models.push(e)}get(e){return this._models.find(t=>t.name===e)}getAll(){return this._models}remove(e){const t=this._models.findIndex(t=>t.name===e);-1!==t&&this._models.splice(t,1)}_models=[];_docManager;_agentManagerFactory;_settingsModel;_toolRegistry;_providerRegistry;_activeCellManager}var D=o(7048),B=o(7055),q=o(7431),W=o(8503),J=o(644);const K={id:"anthropic",name:"Anthropic Claude",apiKeyRequirement:"required",defaultModels:["claude-sonnet-4-5","claude-sonnet-4-5-20250929","claude-haiku-4-5","claude-haiku-4-5-20251001","claude-opus-4-1","claude-opus-4-0","claude-sonnet-4-0","claude-opus-4-1-20250805","claude-opus-4-20250514","claude-sonnet-4-20250514","claude-3-7-sonnet-latest","claude-3-7-sonnet-20250219","claude-3-5-haiku-latest","claude-3-5-haiku-20241022","claude-3-haiku-20240307"],supportsBaseURL:!0,supportsHeaders:!0,factory:e=>{if(!e.apiKey)throw new Error("API key required for Anthropic");return(0,D.createAnthropic)({apiKey:e.apiKey,headers:{"anthropic-dangerous-direct-browser-access":"true",...e.headers},...e.baseURL&&{baseURL:e.baseURL}})(e.model??"")}},G={id:"google",name:"Google Generative AI",apiKeyRequirement:"required",defaultModels:["gemini-2.5-flash","gemini-2.5-pro","gemini-2.5-flash-image-preview","gemini-2.5-flash-lite","gemini-2.5-flash-lite-preview-09-2025","gemini-2.5-flash-preview-04-17","gemini-2.5-flash-preview-09-2025","gemini-2.5-pro-exp-03-25","gemini-2.0-flash","gemini-2.0-flash-001","gemini-2.0-flash-live-001","gemini-2.0-flash-lite","gemini-2.0-pro-exp-02-05","gemini-2.0-flash-thinking-exp-01-21","gemini-2.0-flash-exp","gemini-1.5-flash","gemini-1.5-flash-latest","gemini-1.5-flash-001","gemini-1.5-flash-002","gemini-1.5-flash-8b","gemini-1.5-flash-8b-latest","gemini-1.5-flash-8b-001","gemini-1.5-pro","gemini-1.5-pro-latest","gemini-1.5-pro-001","gemini-1.5-pro-002","gemini-exp-1206","gemma-3-12b-it","gemma-3-27b-it"],supportsBaseURL:!0,factory:e=>{if(!e.apiKey)throw new Error("API key required for Google Generative AI");return(0,B.createGoogleGenerativeAI)({apiKey:e.apiKey,...e.baseURL&&{baseURL:e.baseURL}})(e.model||"gemini-2.5-flash")}},H={id:"mistral",name:"Mistral AI",apiKeyRequirement:"required",defaultModels:["ministral-3b-latest","ministral-8b-latest","mistral-large-latest","mistral-medium-latest","mistral-medium-2508","mistral-medium-2505","mistral-small-latest","codestral-latest","pixtral-large-latest","magistral-small-2507","magistral-medium-2507","magistral-small-2506","magistral-medium-2506","pixtral-12b-2409","open-mistral-7b","open-mixtral-8x7b","open-mixtral-8x22b"],supportsBaseURL:!0,factory:e=>{if(!e.apiKey)throw new Error("API key required for Mistral");return(0,q.createMistral)({apiKey:e.apiKey,...e.baseURL&&{baseURL:e.baseURL}})(e.model||"mistral-large-latest")}},V={id:"openai",name:"OpenAI",apiKeyRequirement:"required",defaultModels:["o1","o1-2024-12-17","o3-mini","o3-mini-2025-01-31","o3","o3-2025-04-16","gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-mini","gpt-4o-mini-2024-07-18","gpt-4-turbo","gpt-4-turbo-2024-04-09","gpt-4","gpt-4-0613","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-3.5-turbo-0125","gpt-3.5-turbo","gpt-3.5-turbo-1106","chatgpt-4o-latest","gpt-5","gpt-5-2025-08-07","gpt-5-mini","gpt-5-mini-2025-08-07","gpt-5-nano","gpt-5-nano-2025-08-07","gpt-5-chat-latest"],supportsBaseURL:!0,supportsHeaders:!0,factory:e=>{if(!e.apiKey)throw new Error("API key required for OpenAI");return(0,W.createOpenAI)({apiKey:e.apiKey,...e.baseURL&&{baseURL:e.baseURL},...e.headers&&{headers:e.headers}})(e.model||"gpt-4o")}},Y={id:"generic",name:"Generic (OpenAI-compatible)",apiKeyRequirement:"optional",defaultModels:[],supportsBaseURL:!0,supportsHeaders:!0,supportsToolCalling:!0,description:"Uses /chat/completions endpoint",baseUrls:[{url:"http://localhost:4000",description:"Default for local LiteLLM server"},{url:"http://localhost:11434/v1",description:"Default for local Ollama server"}],factory:e=>(0,J.createOpenAICompatible)({name:e.provider,apiKey:e.apiKey||"dummy",baseURL:e.baseURL??"",...e.headers&&{headers:e.headers}})(e.model||"gpt-4o")};var X,Q=o(4108);class Z{constructor(e){X.setToken(e.token),this._settingsModel=e.settingsModel,this._providerRegistry=e.providerRegistry,this._secretsManager=e.secretsManager,this._settingsModel.stateChanged.connect(()=>{this._updateModel()}),this._updateModel()}identifier="@jupyterlite/ai:completer";get name(){const e=this._settingsModel.getCompleterProvider();return e?`${e.provider}-completer`:"none"}get systemPrompt(){return this._settingsModel.config.completionSystemPrompt}async fetch(e,t){if(!this._model)return{items:[]};const{text:o,offset:n}=e,a=o.slice(0,n),r=o.slice(n),i=this._settingsModel.getCompleterProvider();if(!i)return{items:[]};const s=i.provider,l=this._getProviderCompletionConfig();try{let o;t.widget instanceof d.NotebookPanel?o=this._extractNotebookContext(t,e):(o=a.trim(),l.supportsFillInMiddle&&r.trim()&&(o=`<PRE>${a}<SUF>${r}<MID>`));const{text:n}=await(0,Q.generateText)({model:this._model,prompt:o,system:this.systemPrompt,temperature:l.temperature||.3});return{items:[{insertText:n.replace(/<PRE>/g,"").replace(/<SUF>/g,"").replace(/<MID>/g,"").replace(/```[\s\S]*?```/g,"").trim(),filterText:l.useFilterText?a.substring(o.length):void 0}]}}catch(e){return console.error(`Error fetching completions from ${s}:`,e),{items:[]}}}async _updateModel(){const e=this._settingsModel.getCompleterProvider();if(!e)return void(this._model=null);const t=e.provider,o=e.model,n=e.baseURL;let a;a=this._secretsManager&&this._settingsModel.config.useSecretsManager?(await this._secretsManager.get(X.getToken(),k,`${t}:apiKey`))?.value??"":this._settingsModel.getApiKey(e.id);try{this._model=function(e,t){if(!t)throw new Error("Provider registry not available");const o=t.createCompletionModel(e.provider,e);if(!o)throw new Error(`Provider ${e.provider} not found or failed to create model`);return o}({provider:t,model:o,apiKey:a,baseURL:n},this._providerRegistry)}catch(e){console.error(`Error creating model for ${t}:`,e),this._model=null}}_extractNotebookContext(e,t){const{text:o,offset:n}=t;let a=o.slice(0,n),r=o.slice(n);const i=e.widget.content,s=i.activeCellIndex,l=i.widgets,c=[],d=[];for(let e=0;e<s;e++){const t=l[e];if("code"===t.model.type){const e=t.model.sharedModel.source;e.trim()&&c.push(e.trim())}}for(let e=s+1;e<l.length;e++){const t=l[e];if("code"===t.model.type){const e=t.model.sharedModel.source;e.trim()&&d.push(e.trim())}}c.length>0&&(a=`${c.map((e,t)=>`# Cell ${t+1}:\n${e}`).join("\n\n")}\n\n# Current cell:\n${a}`),d.length>0&&(r=`${r}\n\n# Cells below:\n${d.map((e,t)=>`# Cell ${t+1}:\n${e}`).join("\n\n")}`);const p=[];return a&&(p.push("# Code before cursor:"),p.push(a)),p.push("# Complete the code at cursor position"),r&&(p.push("# Code after cursor:"),p.push(r)),p.length>1?p.join("\n\n")+"\n\n":""}_getProviderCompletionConfig(){const e=this._settingsModel.getCompleterProvider();return{temperature:e?.parameters?.temperature??.3,supportsFillInMiddle:e?.parameters?.supportsFillInMiddle??!1,useFilterText:e?.parameters?.useFilterText??!1}}_settingsModel;_providerRegistry;_model=null;_secretsManager}!function(e){let t;e.setToken=function(e){t=e},e.getToken=function(){return t}}(X||(X={}));var ee=o(3345),te=o.n(ee);const oe=({tokenUsageChanged:e,settingsModel:t,initialTokenUsage:o})=>te().createElement(h.UseSignal,{signal:t.stateChanged,initialArgs:void 0},()=>t.config.showTokenUsage?te().createElement(h.UseSignal,{signal:e,initialArgs:o},(e,t)=>{if(!t)return null;const o=t.inputTokens+t.outputTokens;return 0===o?null:te().createElement("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontSize:"12px",color:"var(--jp-ui-font-color2)",padding:"4px 8px",backgroundColor:"var(--jp-layout-color1)",border:"1px solid var(--jp-border-color1)",borderRadius:"4px",whiteSpace:"nowrap"},title:`Token Usage - Sent: ${t.inputTokens.toLocaleString()}, Received: ${t.outputTokens.toLocaleString()}, Total: ${o.toLocaleString()}`},te().createElement("span",{style:{display:"flex",alignItems:"center",gap:"2px"}},te().createElement("span",null,"↑"),te().createElement("span",null,t.inputTokens.toLocaleString())),te().createElement("span",{style:{display:"flex",alignItems:"center",gap:"2px"}},te().createElement("span",null,"↓"),te().createElement("span",null,t.outputTokens.toLocaleString())))}):null);class ne extends h.ReactWidget{constructor(e){super(),this._options=e}render(){return te().createElement(oe,{...this._options})}_options}var ae=o(709),re=o(4848);const ie=(0,ae.A)((0,re.jsx)("path",{d:"M6 6h12v12H6z"}),"Stop");const se=(0,ae.A)((0,re.jsx)("path",{d:"M19 6.41 17.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"}),"Clear");const le=(0,ae.A)((0,re.jsx)("path",{d:"m22.7 19-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4"}),"Build"),ce=(0,ae.A)((0,re.jsx)("path",{d:"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"}),"Check");var de=o(2136);function pe(e){const{toolRegistry:t,onToolSelectionChange:o,toolsEnabled:n}=e,[a,i]=(0,ee.useState)([]),[s,l]=(0,ee.useState)(t?.namedTools||[]),[c,d]=(0,ee.useState)(null),[p,u]=(0,ee.useState)(!1),m=(0,ee.useCallback)(e=>{d(e),u(!0)},[]),g=(0,ee.useCallback)(()=>{u(!1)},[]),h=(0,ee.useCallback)(e=>{const t=[...a],n=t.indexOf(e);-1!==n?t.splice(n,1):t.push(e),i(t),o(t)},[a,o]);return(0,ee.useEffect)(()=>{const e=()=>{l(t?.namedTools||[])};if(t)return e(),t.toolsChanged.connect(e),()=>{t.toolsChanged.disconnect(e)}},[t]),(0,ee.useEffect)(()=>{if(s.length>0&&0===a.length){const e=s.map(e=>e.name);i(e),o(e)}},[s,a.length,o]),n&&0!==s.length?te().createElement(te().Fragment,null,te().createElement(r.TooltippedButton,{onClick:e=>{m(e.currentTarget)},tooltip:`Tools (${a.length}/${s.length} selected)`,buttonProps:{size:"small",variant:a.length>0?"contained":"outlined",color:"primary",title:"Select AI Tools",onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(m(e.currentTarget),e.stopPropagation())}},sx:0===a.length?{backgroundColor:"var(--jp-layout-color3)"}:{}},te().createElement(le,null)),te().createElement(de.Menu,{open:p,onClose:g,anchorEl:c,anchorOrigin:{vertical:"top",horizontal:"right"},transformOrigin:{vertical:"bottom",horizontal:"right"},sx:{"& .MuiMenuItem-root":{padding:"0.5em",paddingRight:"2em"}}},s.map(e=>te().createElement(de.Tooltip,{key:e.name,title:e.tool.description||e.name,placement:"left"},te().createElement(de.MenuItem,{className:"jp-AIToolSelect-item",onClick:t=>{h(e.name),t.stopPropagation()}},a.includes(e.name)?te().createElement(ce,{sx:{marginRight:"8px",color:"var(--jp-brand-color1, #2196F3)"}}):te().createElement("div",{style:{width:"24px",marginRight:"8px"}}),te().createElement(de.Typography,{variant:"body2"},e.name)))))):te().createElement(te().Fragment,null)}function ue(e){const{settingsModel:t,model:o}=e,n=o.chatContext.agentManager,[a,i]=(0,ee.useState)(n.activeProvider??""),[s,l]=(0,ee.useState)(""),[c,d]=(0,ee.useState)(null),[p,u]=(0,ee.useState)(!1),m=t.providers,g=(0,ee.useCallback)(e=>{d(e),u(!0)},[]),h=(0,ee.useCallback)(()=>{u(!1)},[]),v=(0,ee.useCallback)(async e=>{n.activeProvider=e,h()},[t,h]);(0,ee.useEffect)(()=>{const e=()=>{if(!n.activeProvider)return;const e=t.getProvider(n.activeProvider);e&&(i(e.id),l(e.model))};return e(),n.activeProviderChanged.connect(e),()=>{n.activeProviderChanged.disconnect(e)}},[t]);const f=t.getProvider(a),y=f?.name||a,b=m.map(e=>({provider:e.id,providerLabel:e.name,model:e.model,isSelected:e.id===a&&e.model===s}));return 0===b.length?te().createElement(r.TooltippedButton,{onClick:()=>{},tooltip:"No providers configured. Please go to AI Settings to add a provider.",buttonProps:{size:"small",variant:"outlined",color:"warning",disabled:!0,title:"No Providers Available"},sx:{minWidth:"auto",display:"flex",alignItems:"center",height:"29px"}},te().createElement(de.Typography,{variant:"caption",sx:{fontSize:"0.7rem",fontWeight:500}},"No Providers")):te().createElement(te().Fragment,null,te().createElement(r.TooltippedButton,{onClick:e=>{g(e.currentTarget)},tooltip:`Current Model: ${y} - ${s}`,buttonProps:{size:"small",variant:"contained",color:"primary",title:"Select AI Model",onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(g(e.currentTarget),e.stopPropagation())}},sx:{minWidth:"auto",display:"flex",alignItems:"center",height:"29px"}},te().createElement(de.Typography,{variant:"caption",sx:{fontSize:"0.7rem",fontWeight:500,textTransform:"none"}},y)),te().createElement(de.Menu,{open:p,onClose:h,anchorEl:c,anchorOrigin:{vertical:"top",horizontal:"right"},transformOrigin:{vertical:"bottom",horizontal:"right"},sx:{"& .MuiPaper-root":{maxHeight:"300px",overflowY:"auto"},"& .MuiMenuItem-root":{padding:"0.5em",paddingRight:"2em",minWidth:"200px"}}},b.map(({provider:e,providerLabel:t,isSelected:o})=>te().createElement(de.MenuItem,{key:e,onClick:async t=>{await v(e),t.stopPropagation()},sx:{backgroundColor:o?"var(--jp-brand-color3, rgba(33, 150, 243, 0.1))":"transparent","&:hover":{backgroundColor:o?"var(--jp-brand-color3, rgba(33, 150, 243, 0.15))":"var(--jp-layout-color1)"},display:"flex",alignItems:"center",gap:"8px"}},o?te().createElement(ce,{sx:{color:"var(--jp-brand-color1, #2196F3)",fontSize:16}}):te().createElement("div",{style:{width:"16px"}}),te().createElement(de.Typography,{variant:"body2",component:"div",sx:{fontWeight:o?600:400,color:o?"var(--jp-brand-color1, #2196F3)":"inherit"}},t)))))}function me(e){const[t,o]=(0,ee.useState)(!0),[n,a]=(0,ee.useState)("");return(0,ee.useEffect)(()=>{const t=e=>{e.config.useSameProviderForChatAndCompleter?(o(!1),a(`Completion using ${e.getDefaultProvider()?.model}`)):e.config.activeCompleterProvider?(o(!1),a(`Completion using ${e.getProvider(e.config.activeCompleterProvider)?.model}`)):(o(!0),a("No completion"))};return e.settingsModel.stateChanged.connect(t),t(e.settingsModel),()=>{e.settingsModel.stateChanged.disconnect(t)}},[e.settingsModel]),te().createElement(z.react,{className:t?"jp-ai-completion-disabled":"",top:"2px",width:"16px",stylesheet:"statusBar",title:n})}class ge extends h.ReactWidget{constructor(e){super(),this.addClass("jp-ai-completion-status"),this._props=e}render(){return te().createElement(me,{...this._props})}_props}class he extends h.VDomModel{_config={useSecretsManager:!0,providers:[],defaultProvider:"",activeCompleterProvider:void 0,useSameProviderForChatAndCompleter:!0,mcpServers:[],contextAwareness:!0,codeExecution:!1,toolsEnabled:!0,sendWithShiftEnter:!1,showTokenUsage:!1,showCellDiff:!0,showFileDiff:!0,diffDisplayMode:"split",commandsRequiringApproval:["notebook:restart-run-all","notebook:run-cell","notebook:run-cell-and-select-next","notebook:run-cell-and-insert-below","notebook:run-all-cells","notebook:run-all-above","notebook:run-all-below","console:execute","console:execute-forced","fileeditor:run-code","kernelmenu:run","kernelmenu:restart-and-run-all","runmenu:run-all"],systemPrompt:'You are Jupyternaut, an AI coding assistant built specifically for the JupyterLab environment.\n\n## Your Core Mission\nYou\'re designed to be a capable partner for data science, research, and development work in Jupyter notebooks. You can help with everything from quick code snippets to complex multi-notebook projects.\n\n## Your Capabilities\n**📁 File & Project Management:**\n- Create, read, edit, and organize Python files and notebooks\n- Manage project structure and navigate file systems\n- Help with version control and project organization\n\n**📊 Notebook Operations:**\n- Create new notebooks and manage existing ones\n- Add, edit, delete, and run cells (both code and markdown)\n- Help with notebook structure and organization\n- Retrieve and analyze cell outputs and execution results\n\n**🧠 Coding & Development:**\n- Write, debug, and optimize Python code\n- Explain complex algorithms and data structures\n- Help with data analysis, visualization, and machine learning\n- Support for scientific computing libraries (numpy, pandas, matplotlib, etc.)\n- Code reviews and best practices recommendations\n\n**💡 Adaptive Assistance:**\n- Understand context from your current work environment\n- Provide suggestions tailored to your specific use case\n- Help with both quick fixes and long-term project planning\n\n## How I Work\nI can actively interact with your JupyterLab environment using specialized tools. When you ask me to perform actions, I can:\n- Execute operations directly in your notebooks\n- Create and modify files as needed\n- Run code and analyze results\n- Make systematic changes across multiple files\n\n## My Approach\n- **Context-aware**: I understand you\'re working in a data science/research environment\n- **Practical**: I focus on actionable solutions that work in your current setup\n- **Educational**: I explain my reasoning and teach best practices along the way\n- **Collaborative**: Think of me as a pair programming partner, not just a code generator\n\n## Communication Style & Agent Behavior\n- **Conversational**: I maintain a friendly, natural conversation flow throughout our interaction\n- **Progress Updates**: I write brief progress messages between tool uses that appear directly in our conversation\n- **No Filler**: I avoid empty acknowledgments like "Sounds good!" or "Okay, I will..." - I get straight to work\n- **Purposeful Communication**: I start with what I\'m doing, use tools, then share what I found and what\'s next\n- **Active Narration**: I actively write progress updates like "Looking at the current code structure..." or "Found the issue in the notebook..." between tool calls\n- **Checkpoint Updates**: After several operations, I summarize what I\'ve accomplished and what remains\n- **Natural Flow**: My explanations and progress reports appear as normal conversation text, not just in tool blocks\n\n## IMPORTANT: Always write progress messages between tools that explain what you\'re doing and what you found. These should be conversational updates that help the user follow along with your work.\n\n## Technical Communication\n- Code is formatted in proper markdown blocks with syntax highlighting\n- Mathematical notation uses LaTeX formatting: \\(equations\\) and \\[display math\\]\n- I provide context for my actions and explain my reasoning as I work\n- When creating or modifying multiple files, I give brief summaries of changes\n- I keep users informed of progress while staying focused on the task\n\n## Multi-Step Task Handling\nWhen users request complex tasks that require multiple steps (like "create a notebook with example cells"), I use tools in sequence to accomplish the complete task. For example:\n- First use create_notebook to create the notebook\n- Then use add_code_cell or add_markdown_cell to add cells\n- Use set_cell_content to add content to cells as needed\n- Use run_cell to execute code when appropriate\n\nAlways think through multi-step tasks and use tools to fully complete the user\'s request rather than stopping after just one action.\n\nReady to help you build something great! What are you working on?',completionSystemPrompt:"You are an AI code completion assistant. Complete the given code fragment with appropriate code.\nRules:\n- Return only the completion text, no explanations or comments\n- Do not include code block markers (``` or similar)\n- Make completions contextually relevant to the surrounding code and notebook context\n- Follow the language-specific conventions and style guidelines for the detected programming language\n- Keep completions concise but functional\n- Do not repeat the existing code that comes before the cursor\n- Use variables, imports, functions, and other definitions from previous notebook cells when relevant"};_settingRegistry;_settings=null;constructor(e){super(),this._settingRegistry=e.settingRegistry,this.initializeSettings()}async initializeSettings(){try{this._settings=await this._settingRegistry.load("@jupyterlite/ai:settings-model"),this.loadFromSettings(),this._settings.changed.connect(this.onSettingsChanged,this),this.stateChanged.emit(void 0)}catch(e){console.warn("Failed to load JupyterLab settings:",e),this.stateChanged.emit(void 0)}}onSettingsChanged(){this.loadFromSettings(),this.stateChanged.emit(void 0)}loadFromSettings(){if(!this._settings)return;const e=this._settings.composite;this._config={...this._config,...e}}get config(){return{...this._config}}get providers(){return[...this._config.providers]}getProvider(e){return this._config.providers.find(t=>t.id===e)}getDefaultProvider(){return this.getProvider(this._config.defaultProvider)}getCompleterProvider(){return this._config.useSameProviderForChatAndCompleter?this.getDefaultProvider():this._config.activeCompleterProvider?this.getProvider(this._config.activeCompleterProvider):void 0}async addProvider(e){const t=`${e.provider}-${Date.now()}`,o={id:t,name:e.name,provider:e.provider,model:e.model,apiKey:e.apiKey,baseURL:e.baseURL,headers:e.headers,parameters:e.parameters,customSettings:e.customSettings};return this._config.providers.push(o),1===this._config.providers.length?(await this.saveSetting("providers",this._config.providers),this._config.defaultProvider=t,await this.saveSetting("defaultProvider",this._config.defaultProvider)):await this.saveSetting("providers",this._config.providers),t}async removeProvider(e){const t=this._config.providers.findIndex(t=>t.id===e);-1!==t&&(this._config.providers.splice(t,1),await this.saveSetting("providers",this._config.providers),this._config.defaultProvider===e&&(this._config.defaultProvider=this._config.providers.length>0?this._config.providers[0].id:"",await this.saveSetting("defaultProvider",this._config.defaultProvider)),this._config.activeCompleterProvider===e&&(this._config.activeCompleterProvider=void 0,await this.saveSetting("activeCompleterProvider",this._config.activeCompleterProvider)))}async updateProvider(e,t){const o=this.getProvider(e);o&&(Object.assign(o,t),Object.keys(o).forEach(e=>{"id"!==e&&void 0===t[e]&&delete o[e]}),await this.saveSetting("providers",this._config.providers))}async setActiveProvider(e){this.getProvider(e)&&(this._config.defaultProvider=e,await this.saveSetting("defaultProvider",this._config.defaultProvider))}async setActiveCompleterProvider(e){this._config.activeCompleterProvider=e,await this.saveSetting("activeCompleterProvider",this._config.activeCompleterProvider)}get mcpServers(){return[...this._config.mcpServers]}getMCPServer(e){return this._config.mcpServers.find(t=>t.id===e)}async addMCPServer(e){const t=`mcp-${Date.now()}`,o={id:t,name:e.name,url:e.url,enabled:e.enabled};return this._config.mcpServers.push(o),await this.saveSetting("mcpServers",this._config.mcpServers),t}async removeMCPServer(e){const t=this._config.mcpServers.findIndex(t=>t.id===e);-1!==t&&(this._config.mcpServers.splice(t,1),await this.saveSetting("mcpServers",this._config.mcpServers))}async updateMCPServer(e,t){const o=this.getMCPServer(e);o&&(Object.assign(o,t),await this.saveSetting("mcpServers",this._config.mcpServers))}async updateConfig(e){const t=[];for(const[o,n]of Object.entries(e))o in this._config&&this._config[o]!==n&&(this._config[o]=n,t.push(this.saveSetting(o,n)));await Promise.all(t)}getApiKey(e){const t=this.getCompleterProvider();if(t&&t.id===e)return t.apiKey||"";const o=this.getProvider(e);return o&&o.apiKey||""}async saveSetting(e,t){try{this._settings&&(void 0!==t?await this._settings.set(e,t):await this._settings.remove(e))}catch(t){console.warn(`Failed to save setting '${e}' to JupyterLab settings, falling back to localStorage:`,t)}}}class ve{constructor(e){this._commands=e.commands,this._settingsModel=e.settingsModel}async showCellDiff(e){if(!this._settingsModel.config.showCellDiff)return;const t="unified"===this._settingsModel.config.diffDisplayMode?"jupyterlab-diff:unified-cell-diff":"jupyterlab-diff:split-cell-diff";await this._commands.execute(t,{originalSource:e.original,newSource:e.modified,cellId:e.cellId,showActionButtons:e.showActionButtons??!0,openDiff:e.openDiff??!0,notebookPath:e.notebookPath})}async showFileDiff(e){this._settingsModel.config.showFileDiff&&await this._commands.execute("jupyterlab-diff:unified-file-diff",{originalSource:e.original,newSource:e.modified,filePath:e.filePath,showActionButtons:e.showActionButtons??!0})}_commands;_settingsModel}class fe{get tools(){return{...this._tools}}get namedTools(){return Object.entries(this._tools).map(([e,t])=>({name:e,tool:t}))}get toolsChanged(){return this._toolsChanged}add(e,t){this._tools[e]=t,this._toolsChanged.emit()}get(e){return null===e?null:this._tools[e]||null}remove(e){return e in this._tools&&(delete this._tools[e],this._toolsChanged.emit(),!0)}_tools={};_toolsChanged=new y.Signal(this)}var ye=o(6797),be=o(8005),_e=o(3906);async function Ce(e,t,o){if(e){let o=t.findWidget(e);if(o||(o=t.openOrReveal(e)),!(o instanceof d.NotebookPanel))throw new Error(`Widget for ${e} is not a notebook panel`);return o??null}return o?.currentWidget||null}var we=o(4583);const xe=(0,ae.A)((0,re.jsx)("path",{d:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6z"}),"Add"),Se=(0,ae.A)((0,re.jsx)("path",{d:"M20 5V4c0-.55-.45-1-1-1h-2c-.55 0-1 .45-1 1v1h-1v4c0 .55.45 1 1 1h1v7c0 1.1-.9 2-2 2s-2-.9-2-2V7c0-2.21-1.79-4-4-4S5 4.79 5 7v7H4c-.55 0-1 .45-1 1v4h1v1c0 .55.45 1 1 1h2c.55 0 1-.45 1-1v-1h1v-4c0-.55-.45-1-1-1H7V7c0-1.1.9-2 2-2s2 .9 2 2v10c0 2.21 1.79 4 4 4s4-1.79 4-4v-7h1c.55 0 1-.45 1-1V5z"}),"Cable"),ke=(0,ae.A)((0,re.jsx)("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-2 15-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8z"}),"CheckCircle"),Ee=(0,ae.A)((0,re.jsx)("path",{d:"M16.59 7.58 10 14.17l-3.59-3.58L5 12l5 5 8-8zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"}),"CheckCircleOutline"),Me=(0,ae.A)((0,re.jsx)("path",{d:"M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM19 4h-3.5l-1-1h-5l-1 1H5v2h14z"}),"Delete"),Ie=(0,ae.A)((0,re.jsx)("path",{d:"M3 17.25V21h3.75L17.81 9.94l-3.75-3.75zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34a.996.996 0 0 0-1.41 0l-1.83 1.83 3.75 3.75z"}),"Edit"),Pe=(0,ae.A)((0,re.jsx)("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m1 15h-2v-2h2zm0-4h-2V7h2z"}),"Error"),Te=(0,ae.A)((0,re.jsx)("path",{d:"M11 15h2v2h-2zm0-8h2v6h-2zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"}),"ErrorOutline"),Ae=(0,ae.A)((0,re.jsx)("path",{d:"M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2m0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"}),"MoreVert");var je=o(5764);const Re=(0,ae.A)((0,re.jsx)("path",{d:"M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z"}),"ExpandMore"),$e=(0,ae.A)((0,re.jsx)("path",{d:"M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5M12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5m0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3"}),"Visibility"),Ne=(0,ae.A)((0,re.jsx)("path",{d:"M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7M2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2m4.31-.78 3.15 3.15.02-.16c0-1.66-1.34-3-3-3z"}),"VisibilityOff"),Fe=({open:e,onClose:t,onSave:o,initialConfig:n,mode:a,providerRegistry:r,handleSecretField:i})=>{const s=te().useRef(),[l,c]=te().useState(n?.name||""),[d,p]=te().useState(n?.provider||"anthropic"),[u,m]=te().useState(n?.model||""),[g,h]=te().useState(n?.apiKey||""),[v,f]=te().useState(n?.baseURL||""),[y,b]=te().useState(!1),[_,C]=te().useState(n?.parameters||{}),[w,x]=te().useState(!1),S=te().useMemo(()=>{const e=r.providers;return Object.keys(e).map(t=>{const o=e[t];return{value:t,label:o.name,models:o.defaultModels,apiKeyRequirement:o.apiKeyRequirement,allowCustomModel:"generic"===t,supportsBaseURL:o.supportsBaseURL,description:o.description,baseUrls:o.baseUrls}})},[r]),k=S.find(e=>e.value===d);te().useEffect(()=>{e?(c(n?.name||""),p(n?.provider||"anthropic"),m(n?.model||""),h(n?.apiKey||""),f(n?.baseURL||""),C(n?.parameters||{}),b(!1),x(!1)):x(!1)},[e,n]),te().useEffect(()=>{k&&k.models.length>0&&!u&&m(k.models[0])},[d,k,u]),te().useEffect(()=>{e&&s.current&&i(s.current,d,"apiKey")},[e,d,s.current]);const E=l.trim()&&d&&u&&("required"!==k?.apiKeyRequirement||g);return te().createElement(de.Dialog,{open:e,onClose:t,maxWidth:"md",fullWidth:!0},te().createElement(de.DialogTitle,null,"add"===a?"Add New Provider":"Edit Provider"),te().createElement(de.DialogContent,null,te().createElement(de.Box,{sx:{display:"flex",flexDirection:"column",gap:2,pt:1}},te().createElement(de.TextField,{fullWidth:!0,label:"Provider Name",value:l,onChange:e=>c(e.target.value),placeholder:"e.g., My Anthropic Config, Work Provider",helperText:"A friendly name to identify this provider configuration",required:!0}),te().createElement(de.FormControl,{fullWidth:!0,required:!0},te().createElement(de.InputLabel,null,"Provider Type"),te().createElement(de.Select,{value:d,label:"Provider Type",onChange:e=>p(e.target.value)},S.map(e=>te().createElement(de.MenuItem,{key:e.value,value:e.value},te().createElement(de.Box,null,te().createElement(de.Box,{sx:{display:"flex",alignItems:"center",gap:1}},e.label,"required"===e.apiKeyRequirement&&te().createElement(de.Chip,{size:"small",label:"API Key",color:"default",variant:"outlined"})),e.description&&te().createElement(de.Typography,{variant:"caption",color:"text.secondary"},e.description)))))),k?.allowCustomModel?te().createElement(de.TextField,{fullWidth:!0,label:"Model",value:u,onChange:e=>m(e.target.value),placeholder:"Enter model name",helperText:"Enter any compatible model name",required:!0}):te().createElement(de.FormControl,{fullWidth:!0,required:!0},te().createElement(de.InputLabel,null,"Model"),te().createElement(de.Select,{value:u,label:"Model",onChange:e=>m(e.target.value)},k?.models.map(e=>te().createElement(de.MenuItem,{key:e,value:e},te().createElement(de.Box,null,te().createElement(de.Typography,{variant:"body1"},e),te().createElement(de.Typography,{variant:"caption",color:"text.secondary"},e.includes("sonnet")?"Balanced performance":e.includes("opus")?"Advanced reasoning":e.includes("haiku")?"Fast and lightweight":e.includes("large")?"Most capable model":e.includes("small")?"Fast and efficient":e.includes("codestral")?"Code-specialized":"General purpose")))))),k&&"none"!==k?.apiKeyRequirement&&te().createElement(de.TextField,{fullWidth:!0,inputRef:s,label:"required"===k?.apiKeyRequirement?"API Key":"API Key (Optional)",type:y?"text":"password",value:g,onChange:e=>h(e.target.value),placeholder:"Enter your API key...",required:"required"===k?.apiKeyRequirement,InputProps:{endAdornment:te().createElement(de.InputAdornment,{position:"end"},te().createElement(de.IconButton,{onClick:()=>b(!y),edge:"end"},y?te().createElement(Ne,null):te().createElement($e,null)))}}),k?.supportsBaseURL&&te().createElement(de.Autocomplete,{freeSolo:!0,fullWidth:!0,options:(k.baseUrls??[]).map(e=>e.url),value:v||"",onChange:(e,t)=>{t&&"string"==typeof t&&f(t)},inputValue:v||"",renderOption:(e,t)=>{const o=(k.baseUrls??[]).find(e=>e.url===t);return te().createElement(de.Box,{component:"li",...e,key:t},te().createElement(de.Box,null,te().createElement(de.Typography,{variant:"body2"},t),o?.description&&te().createElement(de.Typography,{variant:"caption",color:"text.secondary"},o.description)))},renderInput:e=>te().createElement(de.TextField,{...e,fullWidth:!0,label:"Base URL",placeholder:"https://api.example.com/v1",onChange:e=>f(e.target.value)}),clearOnBlur:!1}),te().createElement(de.Accordion,{expanded:w,onChange:(e,t)=>x(t),sx:{mt:2,bgcolor:"transparent",boxShadow:"none",border:1,borderColor:"divider",borderRadius:1}},te().createElement(de.AccordionSummary,{expandIcon:te().createElement(Re,null)},te().createElement(de.Typography,{variant:"subtitle1",fontWeight:"medium"},"Advanced Settings")),te().createElement(de.AccordionDetails,{sx:{bgcolor:"transparent"}},te().createElement(de.Box,{sx:{display:"flex",flexDirection:"column",gap:2}},te().createElement(de.Box,null,te().createElement(de.Typography,{gutterBottom:!0},"Temperature: ",_.temperature??"Default"),te().createElement(de.Slider,{value:_.temperature??.7,onChange:(e,t)=>C({..._,temperature:t}),min:0,max:2,step:.1,valueLabelDisplay:"auto"}),te().createElement(de.Typography,{variant:"caption",color:"text.secondary"},"Temperature for the model (lower values are more deterministic)")),te().createElement(de.TextField,{fullWidth:!0,label:"Max Tokens (Optional)",type:"number",value:_.maxTokens??"",onChange:e=>C({..._,maxTokens:e.target.value?Number(e.target.value):void 0}),placeholder:"Leave empty for provider default",helperText:"Maximum length of AI responses",inputProps:{min:1}}),te().createElement(de.TextField,{fullWidth:!0,label:"Max Turns (Optional)",type:"number",value:_.maxTurns??"",onChange:e=>C({..._,maxTurns:e.target.value?Number(e.target.value):void 0}),placeholder:"Default: 25",helperText:"Maximum number of tool execution turns",inputProps:{min:1,max:100}}),te().createElement(de.Typography,{variant:"body2",color:"text.secondary",sx:{mt:2,mb:1}},"Completion Options"),te().createElement(de.FormControlLabel,{control:te().createElement(de.Switch,{checked:_.supportsFillInMiddle??!1,onChange:e=>C({..._,supportsFillInMiddle:e.target.checked})}),label:"Fill-in-the-middle support"}),te().createElement(de.FormControlLabel,{control:te().createElement(de.Switch,{checked:_.useFilterText??!1,onChange:e=>C({..._,useFilterText:e.target.checked})}),label:"Use filter text"})))))),te().createElement(de.DialogActions,null,te().createElement(de.Button,{onClick:t},"Cancel"),te().createElement(de.Button,{onClick:()=>{if(!l.trim()||!d||!u)return;const e=Object.keys(_).some(e=>void 0!==_[e]),n={name:l.trim(),provider:d,model:u,...g&&{apiKey:g},...v&&{baseURL:v},...e&&{parameters:_}};o(n),t()},variant:"contained",disabled:!E},"add"===a?"Add Provider":"Save Changes")))},ze=e=>{const t=!!e?.theme&&!e.isLight(e.theme);return(0,de.createTheme)({palette:{mode:t?"dark":"light"}})};class Oe extends h.ReactWidget{constructor(e){super(),De.setToken(e.token),this._settingsModel=e.settingsModel,this._agentManagerFactory=e.agentManagerFactory,this._themeManager=e.themeManager,this._providerRegistry=e.providerRegistry,this._secretsManager=e.secretsManager,this.id="jupyterlite-ai-settings",this.title.label="AI Settings",this.title.caption="Configure AI providers and behavior",this.title.closable=!0}render(){return te().createElement(Ue,{model:this._settingsModel,agentManagerFactory:this._agentManagerFactory,themeManager:this._themeManager,providerRegistry:this._providerRegistry,secretsManager:this._secretsManager})}_settingsModel;_agentManagerFactory;_themeManager;_providerRegistry;_secretsManager}const Ue=({model:e,agentManagerFactory:t,themeManager:o,providerRegistry:n,secretsManager:a})=>{if(!e)return te().createElement("div",null,"Settings model not available");const[r,i]=(0,ee.useState)(e.config||{}),[s,l]=(0,ee.useState)(()=>ze(o)),[c,d]=(0,ee.useState)(0),[p,u]=(0,ee.useState)(!1),[m,g]=(0,ee.useState)(),[h,v]=(0,ee.useState)(null),[f,y]=(0,ee.useState)(""),[b,_]=(0,ee.useState)(!1),[C,w]=(0,ee.useState)(),[x,S]=(0,ee.useState)(null),[M,I]=(0,ee.useState)(""),[P,T]=(0,ee.useState)(r.systemPrompt),A=te().useRef(r.systemPrompt),[j,R]=(0,ee.useState)(r.completionSystemPrompt),$=te().useRef(r.completionSystemPrompt);(0,ee.useEffect)(()=>{if(!e||!e.stateChanged)return;const t=()=>{i(e.config||{})};return e.stateChanged.connect(t),()=>{e.stateChanged.disconnect(t)}},[e]),(0,ee.useEffect)(()=>{if(!o)return;const e=()=>{l(ze(o))};return o.themeChanged.connect(e),()=>{o.themeChanged.disconnect(e)}},[o]),(0,ee.useEffect)(()=>{if(!t)return;const e=()=>{i(e=>({...e}))};return t.mcpConnectionChanged.connect(e),()=>{t.mcpConnectionChanged.disconnect(e)}},[t]),(0,ee.useEffect)(()=>{T(r.systemPrompt),A.current=r.systemPrompt},[r.systemPrompt]),(0,ee.useEffect)(()=>{R(r.completionSystemPrompt),$.current=r.completionSystemPrompt},[r.completionSystemPrompt]);const N=(0,ee.useMemo)(()=>new we.Debouncer(async()=>{await O({systemPrompt:A.current,completionSystemPrompt:$.current})},1e3),[]);(0,ee.useEffect)(()=>()=>{N.dispose()},[N]);const F=async(e,t)=>{const o=await(a?.get(De.getToken(),k,`${e}:${t}`));return o?.value},z=async(e,t,o)=>{await(a?.set(De.getToken(),k,`${e}:${t}`,{namespace:k,id:`${e}:${t}`,value:o}))},O=async t=>{if(void 0!==t.useSecretsManager)if(t.useSecretsManager)for(const t of e.config.providers)await F(t.provider,"apiKey")||z(t.provider,"apiKey",t.apiKey??""),t.apiKey=E,await e.updateProvider(t.id,t);else for(const t of e.config.providers){const o=await F(t.provider,"apiKey");o&&(t.apiKey=o,await e.updateProvider(t.id,t))}await e.updateConfig(t)};return te().createElement(de.ThemeProvider,{theme:s},te().createElement(de.Box,{sx:{height:"100%",maxHeight:"100vh",overflow:"auto",p:2,pb:4,boxSizing:"border-box",fontSize:"0.9rem"}},te().createElement(de.Box,{sx:{mb:2,display:"flex",alignItems:"center",gap:2}},te().createElement(je.A,{color:"primary",sx:{fontSize:24}}),te().createElement(de.Typography,{variant:"h5",component:"h1",sx:{fontWeight:600}},"AI Settings")),te().createElement(de.Box,{sx:{borderBottom:1,borderColor:"divider",mb:2}},te().createElement(de.Tabs,{value:c,onChange:(e,t)=>d(t)},te().createElement(de.Tab,{label:"Providers"}),te().createElement(de.Tab,{label:"Behavior"}),te().createElement(de.Tab,{label:"MCP Servers"}))),0===c&&te().createElement(de.Box,{sx:{display:"flex",flexDirection:"column",gap:2}},r.providers.length>0&&te().createElement(de.Card,{elevation:2},te().createElement(de.CardContent,null,te().createElement(de.Typography,{variant:"h6",component:"h2",gutterBottom:!0},"Default Providers"),te().createElement(de.Box,{sx:{display:"flex",flexDirection:"column",gap:2}},te().createElement(de.FormControl,{fullWidth:!0},te().createElement(de.InputLabel,null,"Chat Provider"),te().createElement(de.Select,{value:r.defaultProvider,label:"Chat Provider",onChange:t=>e.setActiveProvider(t.target.value)},r.providers.map(e=>te().createElement(de.MenuItem,{key:e.id,value:e.id},e.name)))),te().createElement(de.FormControlLabel,{control:te().createElement(de.Switch,{checked:r.useSameProviderForChatAndCompleter,onChange:e=>O({useSameProviderForChatAndCompleter:e.target.checked}),color:"primary"}),label:"Use same provider for chat and completions"}),!r.useSameProviderForChatAndCompleter&&te().createElement(de.FormControl,{fullWidth:!0},te().createElement(de.InputLabel,null,"Completion Provider"),te().createElement(de.Select,{value:r.activeCompleterProvider||"",label:"Completion Provider",className:"jp-ai-completion-provider-select",onChange:t=>e.setActiveCompleterProvider(t.target.value||void 0)},te().createElement(de.MenuItem,{value:""},te().createElement("em",null,"No completion")),r.providers.map(e=>te().createElement(de.MenuItem,{key:e.id,value:e.id},e.name))))))),te().createElement(de.Card,{elevation:2},te().createElement(de.CardContent,null,te().createElement(de.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:2}},te().createElement(de.Box,{sx:{display:"flex",alignItems:"center",gap:1}},te().createElement(de.Typography,{variant:"h6",component:"h2"},"Configured Providers")),te().createElement(de.Button,{variant:"contained",startIcon:te().createElement(xe,null),onClick:()=>{g(void 0),u(!0)},size:"small"},"Add Provider")),0===r.providers.length?te().createElement(de.Alert,{severity:"info"},'No providers configured yet. Click "Add Provider" to get started.'):te().createElement(de.List,null,r.providers.map(e=>{const t=r.defaultProvider===e.id,o=r.useSameProviderForChatAndCompleter?t:r.activeCompleterProvider===e.id,n=e.parameters;return te().createElement(de.ListItem,{key:e.id,sx:{flexDirection:"column",alignItems:"stretch",py:2}},te().createElement(de.Box,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",width:"100%",mb:1}},te().createElement(de.Box,{sx:{flex:1}},te().createElement(de.Box,{sx:{display:"flex",alignItems:"center",gap:1,mb:.5}},te().createElement(de.Typography,{variant:"subtitle1",fontWeight:"medium"},e.name),t&&te().createElement(de.Chip,{label:"Chat",size:"small",color:"primary",icon:te().createElement(ke,null)}),o&&te().createElement(de.Chip,{label:"Completion",size:"small",color:"secondary",icon:te().createElement(ke,null)})),te().createElement(de.Typography,{variant:"body2",color:"text.secondary",gutterBottom:!0},e.provider," • ",e.model,e.description&&` • ${e.description}`),n&&(void 0!==n.temperature||void 0!==n.maxTokens||void 0!==n.maxTurns)&&te().createElement(de.Box,{sx:{display:"flex",flexWrap:"wrap",gap:1,mt:1}},void 0!==n.temperature&&te().createElement(de.Chip,{label:`Temp: ${n.temperature}`,size:"small",variant:"outlined"}),void 0!==n.maxTokens&&te().createElement(de.Chip,{label:`Tokens: ${n.maxTokens}`,size:"small",variant:"outlined"}),void 0!==n.maxTurns&&te().createElement(de.Chip,{label:`Turns: ${n.maxTurns}`,size:"small",variant:"outlined"}))),te().createElement(de.IconButton,{onClick:t=>{return o=t,n=e.id,v(o.currentTarget),void y(n);var o,n},size:"small"},te().createElement(Ae,null))))})))),void 0!==a&&te().createElement(de.FormControlLabel,{control:te().createElement(de.Switch,{checked:r.useSecretsManager,onChange:e=>O({useSecretsManager:e.target.checked}),color:"primary",sx:{alignSelf:"flex-start"}}),label:te().createElement("div",null,te().createElement("span",null,"Use the secrets manager to manage API keys"),!r.useSecretsManager&&te().createElement(de.Alert,{severity:"warning",icon:te().createElement(Pe,null),sx:{mb:2}},"The secrets are stored in plain text in settings"))})),1===c&&te().createElement(de.Card,{elevation:2},te().createElement(de.CardContent,null,te().createElement(de.Typography,{variant:"h6",component:"h2",gutterBottom:!0},"Behavior Settings"),te().createElement(de.Box,{sx:{display:"flex",flexDirection:"column",gap:2}},te().createElement(de.FormControlLabel,{control:te().createElement(de.Switch,{checked:r.toolsEnabled,onChange:e=>O({toolsEnabled:e.target.checked}),color:"primary"}),label:te().createElement(de.Box,null,te().createElement(de.Typography,{variant:"body1"},"Enable Tools"),te().createElement(de.Typography,{variant:"caption",color:"text.secondary"},"Allow the AI to use tools like notebook operations, code execution, and file management"))}),te().createElement(de.FormControlLabel,{control:te().createElement(de.Switch,{checked:r.sendWithShiftEnter,onChange:e=>O({sendWithShiftEnter:e.target.checked}),color:"primary"}),label:te().createElement(de.Box,null,te().createElement(de.Typography,{variant:"body1"},"Send with Shift+Enter"),te().createElement(de.Typography,{variant:"caption",color:"text.secondary"},"Use Shift+Enter to send messages (Enter creates new line)"))}),te().createElement(de.FormControlLabel,{control:te().createElement(de.Switch,{checked:r.showTokenUsage,onChange:e=>O({showTokenUsage:e.target.checked}),color:"primary"}),label:te().createElement(de.Box,null,te().createElement(de.Typography,{variant:"body1"},"Show Token Usage"),te().createElement(de.Typography,{variant:"caption",color:"text.secondary"},"Display token usage information in the chat toolbar"))}),te().createElement(de.FormControlLabel,{control:te().createElement(de.Switch,{checked:r.showCellDiff,onChange:e=>O({showCellDiff:e.target.checked}),color:"primary"}),label:te().createElement(de.Box,null,te().createElement(de.Typography,{variant:"body1"},"Show Cell Diff"),te().createElement(de.Typography,{variant:"caption",color:"text.secondary"},"Show diff view when AI modifies cell content"))}),r.showCellDiff&&te().createElement(de.FormControl,{sx:{ml:4}},te().createElement(de.InputLabel,null,"Diff Display Mode"),te().createElement(de.Select,{value:r.diffDisplayMode,label:"Diff Display Mode",onChange:e=>O({diffDisplayMode:e.target.value})},te().createElement(de.MenuItem,{value:"split"},"Split View"),te().createElement(de.MenuItem,{value:"unified"},"Unified View"))),te().createElement(de.FormControlLabel,{control:te().createElement(de.Switch,{checked:r.showFileDiff,onChange:e=>O({showFileDiff:e.target.checked}),color:"primary"}),label:te().createElement(de.Box,null,te().createElement(de.Typography,{variant:"body1"},"Show File Diff"),te().createElement(de.Typography,{variant:"caption",color:"text.secondary"},"Show diff view when AI modifies file content"))}),te().createElement(de.Divider,{sx:{my:1}}),te().createElement(de.TextField,{fullWidth:!0,multiline:!0,rows:3,label:"System Prompt",value:P,onChange:e=>{return t=e.target.value,T(t),A.current=t,void N.invoke();var t},placeholder:"Define the AI's behavior and personality...",helperText:"Instructions that define how the AI should behave and respond"}),te().createElement(de.TextField,{fullWidth:!0,multiline:!0,rows:3,label:"Completion System Prompt",value:j,onChange:e=>{return t=e.target.value,R(t),$.current=t,void N.invoke();var t},placeholder:"Define how the AI should generate code completions...",helperText:"Instructions that define how the AI should generate code completions"}),te().createElement(de.Divider,{sx:{my:2}}),te().createElement(de.Box,null,te().createElement(de.Typography,{variant:"body1",gutterBottom:!0},"Commands Requiring Approval"),te().createElement(de.Typography,{variant:"caption",color:"text.secondary",gutterBottom:!0,sx:{display:"block"}},"Commands that require user approval before AI can execute them"),te().createElement(de.List,{sx:{mb:2,maxHeight:200,overflow:"auto"}},r.commandsRequiringApproval.map((e,t)=>te().createElement(de.ListItem,{key:t,divider:!0},te().createElement(de.ListItemText,{primary:e}),te().createElement(de.ListItemSecondaryAction,null,te().createElement(de.IconButton,{onClick:()=>{const e=[...r.commandsRequiringApproval];e.splice(t,1),O({commandsRequiringApproval:e})},size:"small"},te().createElement(Me,null)))))),te().createElement(de.TextField,{fullWidth:!0,label:"Add New Command",placeholder:"e.g., notebook:run-cell",onKeyDown:e=>{if("Enter"===e.key){const t=e.target.value.trim();if(t&&!r.commandsRequiringApproval.includes(t)){const o=[...r.commandsRequiringApproval,t];O({commandsRequiringApproval:o}),e.target.value=""}}},helperText:"Press Enter to add a command. Common commands: notebook:run-cell, console:execute, fileeditor:run-code"}))))),2===c&&te().createElement(de.Card,{elevation:2},te().createElement(de.CardContent,null,te().createElement(de.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:2}},te().createElement(de.Box,{sx:{display:"flex",alignItems:"center",gap:1}},te().createElement(Se,{color:"primary"}),te().createElement(de.Typography,{variant:"h6",component:"h2"},"Remote MCP Servers")),te().createElement(de.Button,{variant:"contained",startIcon:te().createElement(xe,null),onClick:()=>{w(void 0),_(!0)},size:"small"},"Add Server")),te().createElement(de.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2}},"Configure remote Model Context Protocol (MCP) servers to extend the AI's capabilities with external tools and data sources."),0===r.mcpServers.length?te().createElement(de.Alert,{severity:"info"},'No MCP servers configured yet. Click "Add Server" to connect to remote MCP services.'):te().createElement(de.List,null,r.mcpServers.map(o=>te().createElement(de.ListItem,{key:o.id,divider:!0},te().createElement(de.ListItemText,{primary:te().createElement(de.Box,{sx:{display:"flex",alignItems:"center",gap:1}},te().createElement(de.Typography,{variant:"body1"},o.name),o.enabled&&t?.isMCPServerConnected(o.name)&&te().createElement(Ee,{sx:{color:"success.main",fontSize:16}}),o.enabled&&!t?.isMCPServerConnected(o.name)&&te().createElement(Te,{sx:{color:"error.main",fontSize:16}}),te().createElement(de.Switch,{checked:o.enabled,onChange:t=>e.updateMCPServer(o.id,{enabled:t.target.checked}),size:"small",color:"primary"})),secondary:te().createElement(de.Box,null,te().createElement(de.Typography,{variant:"body2",color:"text.secondary"},o.url),o.enabled&&t&&te().createElement(de.Typography,{variant:"caption",color:"text.secondary"},"Status:"," ",t.isMCPServerConnected(o.name)?"Connected":"Connection failed"))}),te().createElement(de.ListItemSecondaryAction,null,te().createElement(de.IconButton,{onClick:e=>{return t=e,n=o.id,S(t.currentTarget),void I(n);var t,n},size:"small"},te().createElement(Ae,null)))))))),te().createElement(Fe,{open:p,onClose:()=>u(!1),onSave:m?async t=>{m&&(e.config.useSecretsManager&&a&&t.apiKey&&(t.apiKey=E),await e.updateProvider(m.id,t),g(void 0))}:async t=>{e.config.useSecretsManager&&a&&t.apiKey&&(t.apiKey=E),await e.addProvider(t)},initialConfig:m,mode:m?"edit":"add",providerRegistry:n,handleSecretField:async(t,o,n)=>{e.config.useSecretsManager&&a&&await(a?.attach(De.getToken(),k,`${o}:${n}`,t))}}),te().createElement(de.Menu,{anchorEl:h,open:Boolean(h),onClose:()=>{v(null),y("")}},te().createElement(de.MenuItem,{onClick:()=>{const t=r.providers.find(e=>e.id===f);t&&(async t=>{e.config.useSecretsManager&&a&&(t.apiKey=await F(t.provider,"apiKey")??""),g(t),u(!0),v(null)})(t)}},te().createElement(Ie,{sx:{mr:1}}),"Edit"),te().createElement(de.MenuItem,{onClick:()=>(async t=>{await e.removeProvider(t),v(null)})(f),sx:{color:"error.main"}},te().createElement(Me,{sx:{mr:1}}),"Delete")),te().createElement(Le,{open:b,onClose:()=>_(!1),onSave:C?async t=>{C&&(await e.updateMCPServer(C.id,t),w(void 0))}:async t=>{await e.addMCPServer(t)},initialConfig:C,mode:C?"edit":"add"}),te().createElement(de.Menu,{anchorEl:x,open:Boolean(x),onClose:()=>{S(null),I("")}},te().createElement(de.MenuItem,{onClick:()=>{const e=r.mcpServers.find(e=>e.id===M);e&&(e=>{w(e),_(!0),S(null)})(e)}},te().createElement(Ie,{sx:{mr:1}}),"Edit"),te().createElement(de.MenuItem,{onClick:()=>(async t=>{await e.removeMCPServer(t),S(null)})(M),sx:{color:"error.main"}},te().createElement(Me,{sx:{mr:1}}),"Delete"))))},Le=({open:e,onClose:t,onSave:o,initialConfig:n,mode:a})=>{const[r,i]=(0,ee.useState)(n?.name||""),[s,l]=(0,ee.useState)(n?.url||""),[c,d]=(0,ee.useState)(n?.enabled??!0);(0,ee.useEffect)(()=>{e&&(i(n?.name||""),l(n?.url||""),d(n?.enabled??!0))},[e,n]);const p=e=>{try{return new URL(e),!0}catch{return!1}},u=r.trim()&&s.trim()&&p(s.trim());return te().createElement(de.Dialog,{open:e,onClose:t,maxWidth:"sm",fullWidth:!0},te().createElement(de.DialogTitle,null,"add"===a?"Add MCP Server":"Edit MCP Server"),te().createElement(de.DialogContent,null,te().createElement(de.Box,{sx:{display:"flex",flexDirection:"column",gap:2,pt:1}},te().createElement(de.TextField,{autoFocus:!0,fullWidth:!0,label:"Server Name",value:r,onChange:e=>i(e.target.value),placeholder:"My MCP Server",helperText:"A friendly name to identify this MCP server"}),te().createElement(de.TextField,{fullWidth:!0,label:"Server URL",value:s,onChange:e=>l(e.target.value),placeholder:"https://example.com/mcp",helperText:"The HTTP/HTTPS URL of the MCP server",error:Boolean(s.trim()&&!p(s.trim()))}),te().createElement(de.FormControlLabel,{control:te().createElement(de.Switch,{checked:c,onChange:e=>d(e.target.checked),color:"primary"}),label:"Enable this server"}))),te().createElement(de.DialogActions,null,te().createElement(de.Button,{onClick:t},"Cancel"),te().createElement(de.Button,{onClick:()=>{r.trim()&&s.trim()&&(o({name:r.trim(),url:s.trim(),enabled:c}),t())},variant:"contained",disabled:!u},"add"===a?"Add":"Save")))};var De;!function(e){let t;e.setToken=function(e){t=e},e.getToken=function(){return t}}(De||(De={}));class Be extends i.MainAreaWidget{constructor(e){super(e),this.title.label=this.content.model.name,this.toolbar.addItem("moveToSide",new i.CommandToolbarButton({commands:e.commands,id:n.moveChat,args:{name:this.content.model.name,area:"side"},icon:h.launchIcon}));const t=new ne({tokenUsageChanged:this.model.tokenUsageChanged,settingsModel:e.settingsModel,initialTokenUsage:this.model.agentManager.tokenUsage});this.toolbar.addItem("token-usage",t),this._approvalButtons=new N({chatPanel:this.content})}dispose(){super.dispose(),this._approvalButtons.dispose()}get model(){return this.content.model}_approvalButtons}const qe={id:"@jupyterlite/ai:provider-registry",description:"AI provider registry",autoStart:!0,provides:w,activate:()=>new $},We={id:"@jupyterlite/ai:anthropic-provider",description:"Register Anthropic provider",autoStart:!0,requires:[w],activate:(e,t)=>{t.registerProvider(K)}},Je={id:"@jupyterlite/ai:google-provider",description:"Register Google Generative AI provider",autoStart:!0,requires:[w],activate:(e,t)=>{t.registerProvider(G)}},Ke={id:"@jupyterlite/ai:mistral-provider",description:"Register Mistral provider",autoStart:!0,requires:[w],activate:(e,t)=>{t.registerProvider(H)}},Ge={id:"@jupyterlite/ai:openai-provider",description:"Register OpenAI provider",autoStart:!0,requires:[w],activate:(e,t)=>{t.registerProvider(V)}},He={id:"@jupyterlite/ai:generic-provider",description:"Register Generic OpenAI-compatible provider",autoStart:!0,requires:[w],activate:(e,t)=>{t.registerProvider(Y)}},Ve={id:"@jupyterlite/ai:chat-model-registry",description:"Registry for the current chat model",autoStart:!0,requires:[x,M,l.IDocumentManager],optional:[w,d.INotebookTracker,C],provides:I,activate:(e,t,o,n,a,i,s)=>{let l;return i&&(l=new r.ActiveCellManager({tracker:i,shell:e.shell})),new L({activeCellManager:l,settingsModel:t,agentManagerFactory:o,docManager:n,providerRegistry:a,toolRegistry:s})}},Ye={id:"@jupyterlite/ai:plugin",description:"AI in JupyterLab",autoStart:!0,requires:[p.IRenderMimeRegistry,r.IInputToolbarRegistryFactory,I,x],optional:[i.IThemeManager,a.ILayoutRestorer,a.ILabShell],activate:(e,t,o,a,s,l,c,d)=>{const p=new r.AttachmentOpenerRegistry;p.set("file",t=>{e.commands.execute("docmanager:open",{path:t.value})}),p.set("notebook",t=>{e.commands.execute("docmanager:open",{path:t.value})});const u=new r.MultiChatPanel({rmRegistry:t,themeManager:l??null,inputToolbarFactory:o,attachmentOpenerRegistry:p,createModel:async e=>({model:a.createModel(e)}),renameChat:async(e,t)=>{const o=a.get(e),n=a.get(t);return!(!o||n||(o.name=t,0))},openInMain:t=>e.commands.execute(n.moveChat,{area:"main",name:t})});u.id="@jupyterlite/ai:chat-panel",u.title.icon=r.chatIcon,u.title.caption="Chat with AI assistant",u.toolbar.addItem("spacer",h.Toolbar.createSpacerItem()),u.toolbar.addItem("settings",new h.ToolbarButton({icon:h.settingsIcon,onClick:()=>{e.commands.execute("@jupyterlite/ai:open-settings")},tooltip:"Open AI Settings"})),u.sectionAdded.connect((e,t)=>{const{widget:o}=t,n=t.model;m.add(o),n.nameChanged.connect(()=>m.save(o)),n.agentManager.activeProviderChanged.connect(()=>m.save(o));const r=new ne({tokenUsageChanged:n.tokenUsageChanged,settingsModel:s,initialTokenUsage:n.agentManager.tokenUsage});t.toolbar.insertBefore("markRead","token-usage",r),n.writersChanged?.connect((e,t)=>{t.some(e=>"ai-assistant"===e.user.username)?(o.inputToolbarRegistry?.hide("send"),o.inputToolbarRegistry?.show("stop")):(o.inputToolbarRegistry?.hide("stop"),o.inputToolbarRegistry?.show("send"))});const i=new N({chatPanel:o});o.disposed.connect(()=>{i.dispose(),a.remove(n.name)})}),e.shell.add(u,"left",{rank:1e3});const m=new i.WidgetTracker({namespace:"ai-chat"});c&&(c.add(u,u.id),c.restore(m,{command:n.openChat,args:e=>({name:e.model.name,area:e instanceof Be?"main":"side",provider:e.model.agentManager.activeProvider}),name:e=>`${e instanceof Be?"main":"side"}:${e.model.name}`})),e.restored.then(()=>{!a.getAll().length&&s.config.defaultProvider&&e.commands.execute(n.openChat)}),function(e,t,o,a,i,s,l,c,d,p){const{commands:u}=e;if(p){u.addCommand(n.reposition,{label:"Reposition Widget",execute:e=>{const{widgetId:t,area:o,mode:n}=e,a=t&&Array.from(p.widgets("main")).find(e=>e.id===t)||p.currentWidget;a&&(o&&"main"!==o?(p.move(a,o),p.activateById(a.id)):n&&p.add(a,"main",{mode:n,activate:!0}))},describedBy:{args:{type:"object",properties:{widgetId:{type:"string",description:"The widget ID to reposition in the application shell"},area:{type:"string",description:"The name of the area to reposition the widget to"},mode:{type:"string",enum:["split-left","split-right","split-top","split-bottom"],description:"The mode to use when repositioning the widget"}}}}});const m=o=>{const n=new r.ChatWidget({model:o,rmRegistry:t,themeManager:d??null,inputToolbarRegistry:i.create(),attachmentOpenerRegistry:a}),p=new Be({content:n,commands:u,settingsModel:s});e.shell.add(p,"main"),l.add(p),o.nameChanged.connect(()=>l.save(p)),o.agentManager.activeProviderChanged.connect(()=>l.save(p)),p.disposed.connect(()=>{c.remove(o.name)})};u.addCommand(n.openChat,{label:"Open a chat",execute:async e=>{const t="main"===e.area?"main":"side",n=e.provider??void 0;if(n&&!s.getProvider(n))return!1;const a=c.createModel(e.name?e.name:void 0,n);return!!a&&("main"===t?m(a):o.addChat({model:a}),!0)},describedBy:{args:{type:"object",properties:{area:{type:"string",enum:["main","side"],description:"The name of the area to open the chat to"},name:{type:"string",description:"The name of the chat"},provider:{type:"string",description:"The provider/model to use with this chat"}}}}}),u.addCommand(n.moveChat,{caption:"Move chat between area",execute:async t=>{const n=t.area;if(!["side","main"].includes(n))return console.error("Error while moving the chat to main area: the area has not been provided or is not correct"),!1;if(!t.name||!t.area)return console.error("Error while moving the chat to main area: the name has not been provided"),!1;const a=c.get(t.name);if(!a)return console.error("Error while moving the chat to main area: there is no reference model"),!1;const r=new f.PromiseDelegate,i=(e,t)=>{t.model===a&&r.resolve(!0)};l.widgetUpdated.connect(i),a.name=f.UUID.uuid4();const s=c.createModel(t.name,a?.agentManager.activeProvider,a?.agentManager.tokenUsage);a?.messages.forEach(e=>s?.messageAdded(e));const d=await Promise.any([r.promise,new Promise(e=>setTimeout(()=>!1,2e3))]);if(l.widgetUpdated.disconnect(i),!d)return!1;if("main"===n)m(s);else{const t=e.shell.currentWidget;t instanceof Be&&t.model.name===a.name&&t.dispose(),o.addChat({model:s})}return!0},describedBy:{args:{type:"object",properties:{area:{type:"string",enum:["main","side"],description:"The name of the area to move the chat to"},name:{type:"string",description:"The name of the chat to move"}},requires:["area","name"]}}})}}(e,t,u,p,o,s,m,a,l,d)}},Xe=v.SecretsManager.sign(k,e=>({id:k,description:"Provide the AI agent manager",autoStart:!0,provides:M,requires:[x,w],optional:[i.ICommandPalette,s.ICompletionProviderManager,a.ILayoutRestorer,v.ISecretsManager,i.IThemeManager],activate:(t,o,a,r,i,s,l,c)=>{const d=new T({settingsModel:o,secretsManager:l,token:e}),p=new Oe({settingsModel:o,agentManagerFactory:d,themeManager:c,providerRegistry:a,secretsManager:l,token:e});if(p.id="jupyterlite-ai-settings",p.title.icon=h.settingsIcon,p.title.iconClass="jp-ai-settings-icon",i){const t=new Z({settingsModel:o,providerRegistry:a,secretsManager:l,token:e});i.registerInlineProvider(t)}else console.info("Completion provider manager not available, skipping AI completion setup");return s&&s.add(p,p.id),t.commands.addCommand(n.openSettings,{label:"AI Settings",caption:"Configure AI providers and behavior",icon:h.settingsIcon,iconClass:"jp-ai-settings-icon",execute:()=>{let e=Array.from(t.shell.widgets("main")).find(e=>"jupyterlite-ai-settings"===e.id);!e&&p&&(e=p,t.shell.add(e,"main")),e&&t.shell.activateById(e.id)},describedBy:{args:{}}}),r&&r.addItem({command:n.openSettings,category:"AI Assistant"}),d}})),Qe={id:"@jupyterlite/ai:settings-model",description:"Provide the AI settings model",autoStart:!0,provides:x,requires:[m.ISettingRegistry],activate:(e,t)=>new he({settingRegistry:t})},Ze={id:"@jupyterlite/ai:diff-manager",description:"Provide the diff manager for notebook cell diffs",autoStart:!0,provides:P,requires:[x],activate:(e,t)=>new ve({commands:e.commands,settingsModel:t})},et={id:"@jupyterlite/ai:tool-registry",description:"Provide the AI tool registry",autoStart:!0,requires:[x,l.IDocumentManager,u.IKernelSpecManager],optional:[d.INotebookTracker,P,c.IEditorTracker],provides:C,activate:(e,t,o,n,a,r,i)=>{const s=new fe,l=function(e,t){return(0,b.tool)({name:"create_notebook",description:"Create a new Jupyter notebook with a kernel for the specified programming language",parameters:_e.z.object({language:_e.z.string().optional().nullable().describe("The programming language for the notebook (e.g., python, r, julia, javascript, etc.). Will use system default if not specified."),name:_e.z.string().optional().nullable().describe("Optional name for the notebook file (without .ipynb extension)")}),execute:async o=>{const n=await async function(e,t){try{await e.ready;const o=e.specs;if(!o||!o.kernelspecs)return"python3";if(!t)return o.default||Object.keys(o.kernelspecs)[0]||"python3";const n=t.toLowerCase().trim();for(const[e,t]of Object.entries(o.kernelspecs))if(t&&(t.language?.toLowerCase()||"")===n)return e;return console.warn(`No kernel found for language '${t}', using default`),o.default||Object.keys(o.kernelspecs)[0]||"python3"}catch(e){return console.warn("Failed to find kernel by language:",e),"python3"}}(t,o.language),{name:a}=o;if(!a)throw new Error("A name must be provided to create a notebook");try{const t=a.endsWith(".ipynb")?a:`${a}.ipynb`,r=await e.newUntitled({type:"notebook"});await e.services.contents.rename(r.path,t);const i=e.createNew(t,"default",{name:n});if(!(i instanceof be.DocumentWidget))throw new Error("Failed to create notebook widget");return await i.context.ready,await i.context.save(),e.openOrReveal(t),{success:!0,message:`Successfully created notebook ${t} with ${n} kernel${o.language?` for ${o.language}`:""}`,notebookPath:t,notebookName:t,kernel:n,language:o.language}}catch(e){return{success:!1,error:`Failed to create notebook: ${e.message}`}}}})}(o,n);s.add("create_notebook",l);const c=function(e,t){return(0,b.tool)({name:"add_cell",description:"Add a cell to the current notebook with optional content",parameters:_e.z.object({notebookPath:_e.z.string().optional().nullable().describe("Path to the notebook file. If not provided, uses the currently active notebook"),content:_e.z.string().optional().nullable().describe("Content to add to the cell"),cellType:_e.z.enum(["code","markdown","raw"]).default("code").describe("Type of cell to add"),position:_e.z.enum(["above","below"]).optional().default("below").describe("Position relative to current cell")}),async execute({notebookPath:o,content:n,cellType:a="code",position:r="below"}){try{const i=await Ce(o,e,t);if(!i)return{success:!1,error:o?`Failed to open notebook at path: ${o}`:"No active notebook and no notebook path provided"};const s=i.content,l=s.model;if(!l)return{success:!1,error:"No notebook model available"};1===l.cells.length&&""===l.cells.get(0).sharedModel.getSource().trim()&&l.sharedModel.deleteCell(0);const c={cell_type:a,source:n||"",metadata:"code"===a?{trusted:!0}:{}};if(l.sharedModel.addCell(c),"markdown"===a&&n){const e=l.cells.length-1,t=s.widgets[e];if(t&&t instanceof ye.MarkdownCell)try{await t.ready,t.rendered=!0}catch(e){console.warn("Failed to render markdown cell:",e)}}return{success:!0,message:`${a} cell added successfully`,content:n||"",cellType:a,position:r}}catch(e){return{success:!1,error:`Failed to add ${a} cell: ${e.message}`}}}})}(o,a),d=function(e,t){return(0,b.tool)({name:"get_notebook_info",description:"Get information about a notebook including number of cells and active cell index",parameters:_e.z.object({notebookPath:_e.z.string().optional().nullable().describe("Path to the notebook file. If not provided, uses the currently active notebook")}),execute:async o=>{const{notebookPath:n}=o;try{const o=await Ce(n,e,t);if(!o)return JSON.stringify({success:!1,error:n?`Failed to open notebook at path: ${n}`:"No active notebook and no notebook path provided"});const a=o.content,r=a.model;if(!r)return JSON.stringify({success:!1,error:"No notebook model available"});const i=r.cells.length,s=a.activeCellIndex,l=a.activeCell,c=l?.model.type||"unknown";return JSON.stringify({success:!0,notebookName:o.title.label,notebookPath:o.context.path,cellCount:i,activeCellIndex:s,activeCellType:c,isDirty:r.dirty})}catch(e){return JSON.stringify({success:!1,error:`Failed to get notebook info: ${e.message}`})}}})}(o,a),p=function(e,t){return(0,b.tool)({name:"get_cell_info",description:"Get information about a specific cell including its type, source content, and outputs",parameters:_e.z.object({notebookPath:_e.z.string().optional().nullable().describe("Path to the notebook file. If not provided, uses the currently active notebook"),cellIndex:_e.z.number().optional().nullable().describe("Index of the cell to get information for (0-based). If not provided, uses the currently active cell")}),execute:async o=>{const{notebookPath:n}=o;let{cellIndex:a}=o;try{const o=await Ce(n,e,t);if(!o)return JSON.stringify({success:!1,error:n?`Failed to open notebook at path: ${n}`:"No active notebook and no notebook path provided"});const r=o.content,i=r.model;if(!i)return JSON.stringify({success:!1,error:"No notebook model available"});if(null==a&&(a=r.activeCellIndex),a<0||a>=i.cells.length)return JSON.stringify({success:!1,error:`Invalid cell index: ${a}. Notebook has ${i.cells.length} cells.`});const s=i.cells.get(a),l=s.type,c=s.sharedModel,d=c.getSource();let p=[];if("code"===l){const e=c.toJSON().outputs;p=Array.isArray(e)?e:[]}return JSON.stringify({success:!0,cellId:s.id,cellIndex:a,cellType:l,source:d,outputs:p,executionCount:"code"===l?s.executionCount:null})}catch(e){return JSON.stringify({success:!1,error:`Failed to get cell info: ${e.message}`})}}})}(o,a),u=function(e,t,o){return(0,b.tool)({name:"set_cell_content",description:"Set the content of a specific cell and return both the previous and new content",parameters:_e.z.object({notebookPath:_e.z.string().optional().nullable().describe("Path to the notebook file. If not provided, uses the currently active notebook"),cellId:_e.z.string().optional().nullable().describe("ID of the cell to modify. If provided, takes precedence over cellIndex"),cellIndex:_e.z.number().optional().nullable().describe("Index of the cell to modify (0-based). Used if cellId is not provided. If neither is provided, targets the active cell"),content:_e.z.string().describe("New content for the cell")}),execute:async n=>{const{notebookPath:a,cellId:r,cellIndex:i,content:s}=n;try{const n=await Ce(a,e,t);if(!n)return JSON.stringify({success:!1,error:a?`Failed to open notebook at path: ${a}`:"No active notebook and no notebook path provided"});const l=n.content,c=n.context.path,d=l.model;if(!d)return JSON.stringify({success:!1,error:"No notebook model available"});let p;if(null!=r){p=-1;for(let e=0;e<d.cells.length;e++)if(d.cells.get(e).id===r){p=e;break}if(-1===p)return JSON.stringify({success:!1,error:`Cell with ID '${r}' not found in notebook`})}else if(null!=i){if(i<0||i>=d.cells.length)return JSON.stringify({success:!1,error:`Invalid cell index: ${i}. Notebook has ${d.cells.length} cells.`});p=i}else if(p=l.activeCellIndex,-1===p||p>=d.cells.length)return JSON.stringify({success:!1,error:"No active cell or invalid active cell index"});const u=d.cells.get(p);if(!u)return JSON.stringify({success:!1,error:`Cell at index ${p} not found`});const m=u.sharedModel,g=m.getSource(),h=u.type,v=u.id;return m.setSource(s),o&&await o.showCellDiff({original:g,modified:s,cellId:v,notebookPath:c}),JSON.stringify({success:!0,message:null!=r?`Cell with ID '${r}' content replaced successfully`:null!=i?`Cell ${p} content replaced successfully`:"Active cell content replaced successfully",notebookPath:c,cellId:v,cellIndex:p,previousContent:g,previousCellType:h,newContent:s,wasActiveCell:void 0===r&&void 0===i})}catch(e){return JSON.stringify({success:!1,error:`Failed to replace cell content: ${e.message}`})}}})}(o,a,r),m=function(e,t){return(0,b.tool)({name:"run_cell",description:"Run a specific cell in the notebook by index",parameters:_e.z.object({notebookPath:_e.z.string().optional().nullable().describe("Path to the notebook file. If not provided, uses the currently active notebook"),cellIndex:_e.z.number().describe("Index of the cell to run (0-based)"),recordTiming:_e.z.boolean().default(!0).describe("Whether to record execution timing")}),needsApproval:!0,execute:async o=>{const{notebookPath:n,cellIndex:a,recordTiming:r=!0}=o;try{const o=await Ce(n,e,t);if(!o)return JSON.stringify({success:!1,error:n?`Failed to open notebook at path: ${n}`:"No active notebook and no notebook path provided"});const i=o.content,s=i.model;if(!s)return JSON.stringify({success:!1,error:"No notebook model available"});if(a<0||a>=s.cells.length)return JSON.stringify({success:!1,error:`Invalid cell index: ${a}. Notebook has ${s.cells.length} cells.`});const l=i.widgets[a];if(!l)return JSON.stringify({success:!1,error:`Cell widget at index ${a} not found`});try{if(l instanceof ye.CodeCell){const e=o.sessionContext;await ye.CodeCell.execute(l,e,{recordTiming:r,deletedCells:s.deletedCells});const t=l.model;return JSON.stringify({success:!0,message:`Cell ${a} executed successfully`,cellIndex:a,executionCount:t.executionCount,hasOutput:t.outputs.length>0})}return JSON.stringify({success:!0,message:`Cell ${a} is not a code cell, no execution needed`,cellIndex:a,cellType:l.model.type})}catch(e){return JSON.stringify({success:!1,error:`Failed to execute cell: ${e.message}`,cellIndex:a})}}catch(e){return JSON.stringify({success:!1,error:`Failed to run cell: ${e.message}`})}}})}(o,a),g=function(e,t){return(0,b.tool)({name:"delete_cell",description:"Delete a specific cell from the notebook by index",parameters:_e.z.object({notebookPath:_e.z.string().optional().nullable().describe("Path to the notebook file. If not provided, uses the currently active notebook"),cellIndex:_e.z.number().describe("Index of the cell to delete (0-based)")}),execute:async o=>{const{notebookPath:n,cellIndex:a}=o;try{const o=await Ce(n,e,t);if(!o)return JSON.stringify({success:!1,error:n?`Failed to open notebook at path: ${n}`:"No active notebook and no notebook path provided"});const r=o.content.model;return r?a<0||a>=r.cells.length?JSON.stringify({success:!1,error:`Invalid cell index: ${a}. Notebook has ${r.cells.length} cells.`}):r.cells.get(a)?(r.sharedModel.deleteCell(a),JSON.stringify({success:!0,message:`Cell ${a} deleted successfully`,cellIndex:a,remainingCells:r.cells.length})):JSON.stringify({success:!1,error:`Cell at index ${a} not found`}):JSON.stringify({success:!1,error:"No notebook model available"})}catch(e){return JSON.stringify({success:!1,error:`Failed to delete cell: ${e.message}`})}}})}(o,a),h=function(e,t){return(0,b.tool)({name:"save_notebook",description:"Save a specific notebook to disk",parameters:_e.z.object({notebookPath:_e.z.string().optional().nullable().describe("Path to the notebook file. If not provided, uses the currently active notebook")}),execute:async o=>{const{notebookPath:n}=o;try{const o=await Ce(n,e,t);return o?(await o.context.save(),JSON.stringify({success:!0,message:"Notebook saved successfully",notebookName:o.title.label,notebookPath:o.context.path})):JSON.stringify({success:!1,error:n?`Failed to open notebook at path: ${n}`:"No active notebook and no notebook path provided"})}catch(e){return JSON.stringify({success:!1,error:`Failed to save notebook: ${e.message}`})}}})}(o,a),v=function(e,t){return(0,b.tool)({name:"execute_active_cell",description:"Execute the currently active cell in the notebook without disrupting user focus",parameters:_e.z.object({notebookPath:_e.z.string().optional().nullable().describe("Path to the notebook file. If not provided, uses the currently active notebook"),code:_e.z.string().optional().nullable().describe("Optional: set cell content before executing"),recordTiming:_e.z.boolean().default(!0).describe("Whether to record execution timing")}),execute:async o=>{const{notebookPath:n,code:a,recordTiming:r=!0}=o;try{const o=await Ce(n,e,t);if(!o)return JSON.stringify({success:!1,error:n?`Failed to open notebook at path: ${n}`:"No active notebook and no notebook path provided"});const i=o.content,s=i.model,l=i.activeCellIndex;if(!s||-1===l)return JSON.stringify({success:!1,error:"No notebook model or active cell available"});const c=s.cells.get(l);if(!c)return JSON.stringify({success:!1,error:"Active cell not found"});a&&c.sharedModel.setSource(a);const d=i.widgets[l];if(!(d&&d instanceof ye.CodeCell))return JSON.stringify({success:!1,error:"Active cell is not a code cell"});const p=o.sessionContext;await ye.CodeCell.execute(d,p,{recordTiming:r,deletedCells:s.deletedCells});const u=d.model;return JSON.stringify({success:!0,message:"Code executed successfully in active cell",cellIndex:l,executionCount:u.executionCount,hasOutput:u.outputs.length>0,code:a||c.sharedModel.getSource()})}catch(e){return JSON.stringify({success:!1,error:`Failed to execute code: ${e.message}`})}}})}(o,a);s.add("add_cell",c),s.add("get_notebook_info",d),s.add("get_cell_info",p),s.add("set_cell_content",u),s.add("run_cell",m),s.add("delete_cell",g),s.add("save_notebook",h),s.add("execute_active_cell",v);const f=function(e){return(0,b.tool)({name:"create_file",description:"Create a new file of specified type (text, python, markdown, json, etc.)",parameters:_e.z.object({fileName:_e.z.string().describe("Name of the file to create"),fileType:_e.z.string().default("text").describe("Type of file to create. Common examples: text, python, markdown, json, javascript, typescript, yaml, julia, r, csv"),content:_e.z.string().optional().nullable().describe("Initial content for the file (optional)"),cwd:_e.z.string().optional().nullable().describe("Directory where to create the file (optional)")}),errorFunction:(e,t)=>JSON.stringify({success:!1,error:`Failed to create file: ${t instanceof Error?t.message:String(t)}`}),execute:async t=>{const{fileName:o,content:n="",cwd:a,fileType:r="text"}=t,i=e.registry.getFileType(r),s=i?.extensions[0]||".txt",l=F.PathExt.extname(o)?o:`${o}${s}`,c=a?`${a}/${l}`:l,d=await e.services.contents.newUntitled({path:a||"",type:"file",ext:s});let p=d.path;d.name!==l&&(p=(await e.services.contents.rename(d.path,c)).path),n&&await e.services.contents.save(p,{type:"file",format:"text",content:n});let u=!1;return e.findWidget(p)||(e.openOrReveal(p),u=!0),{success:!0,message:`${r} file '${l}' created and opened successfully`,fileName:l,filePath:p,fileType:r,hasContent:!!n,opened:u}}})}(o),y=function(e){return(0,b.tool)({name:"open_file",description:"Open a file in the editor",parameters:_e.z.object({filePath:_e.z.string().describe("Path to the file to open")}),errorFunction:(e,t)=>JSON.stringify({success:!1,error:`Failed to open file: ${t instanceof Error?t.message:String(t)}`}),execute:async t=>{const{filePath:o}=t,n=e.openOrReveal(o);if(!n)throw new Error(`Could not open file: ${o}`);return{success:!0,message:`File '${o}' opened successfully`,filePath:o,widgetId:n.id}}})}(o),_=function(e){return(0,b.tool)({name:"delete_file",description:"Delete a file from the file system",parameters:_e.z.object({filePath:_e.z.string().describe("Path to the file to delete")}),errorFunction:(e,t)=>JSON.stringify({success:!1,error:`Failed to delete file: ${t instanceof Error?t.message:String(t)}`}),execute:async t=>{const{filePath:o}=t;return await e.services.contents.delete(o),{success:!0,message:`File '${o}' deleted successfully`,filePath:o}}})}(o),C=function(e){return(0,b.tool)({name:"rename_file",description:"Rename a file or move it to a different location",parameters:_e.z.object({oldPath:_e.z.string().describe("Current path of the file"),newPath:_e.z.string().describe("New path/name for the file")}),errorFunction:(e,t)=>JSON.stringify({success:!1,error:`Failed to rename file: ${t instanceof Error?t.message:String(t)}`}),execute:async t=>{const{oldPath:o,newPath:n}=t;return await e.services.contents.rename(o,n),{success:!0,message:`File renamed from '${o}' to '${n}' successfully`,oldPath:o,newPath:n}}})}(o),w=function(e){return(0,b.tool)({name:"copy_file",description:"Copy a file to a new location",parameters:_e.z.object({sourcePath:_e.z.string().describe("Path of the file to copy"),destinationPath:_e.z.string().describe("Destination path for the copied file")}),errorFunction:(e,t)=>JSON.stringify({success:!1,error:`Failed to copy file: ${t instanceof Error?t.message:String(t)}`}),execute:async t=>{const{sourcePath:o,destinationPath:n}=t;return await e.services.contents.copy(o,n),{success:!0,message:`File copied from '${o}' to '${n}' successfully`,sourcePath:o,destinationPath:n}}})}(o),x=(S=e.commands,(0,b.tool)({name:"navigate_to_directory",description:"Navigate to a specific directory in the file browser",parameters:_e.z.object({directoryPath:_e.z.string().describe("Path to the directory to navigate to")}),errorFunction:(e,t)=>JSON.stringify({success:!1,error:`Failed to navigate to directory: ${t instanceof Error?t.message:String(t)}`}),execute:async e=>{const{directoryPath:t}=e;return await S.execute("filebrowser:go-to-path",{path:t}),{success:!0,message:`Navigated to directory '${t}' successfully`,directoryPath:t}}}));var S;const k=function(e,t){return(0,b.tool)({name:"get_file_info",description:"Get information about a file including its path, name, extension, and content. Works with text-based files like Python files, markdown, JSON, etc. For Jupyter notebooks, use dedicated notebook tools instead. If no file path is provided, returns information about the currently active file in the editor.",parameters:_e.z.object({filePath:_e.z.string().optional().nullable().describe('Path to the file to read (e.g., "script.py", "README.md", "config.json"). If not provided, uses the currently active file in the editor.')}),errorFunction:(e,t)=>JSON.stringify({success:!1,error:`Failed to get file info: ${t instanceof Error?t.message:String(t)}`}),execute:async o=>{const{filePath:n}=o;let a=null;if(n){if(a=e.findWidget(n)??e.openOrReveal(n)??null,!a)throw new Error(`Failed to open file at path: ${n}`)}else if(a=t?.currentWidget??null,!a)throw new Error("No active file in the editor and no file path provided");if(!a.context)throw new Error("Widget is not a document");await a.context.ready;const r=a.context.model;if(!r)throw new Error("File model not available");const i=r.sharedModel.getSource(),s=a.context.path,l=a.title.label,c=F.PathExt.extname(s)||"unknown";return JSON.stringify({success:!0,filePath:s,fileName:l,fileExtension:c,content:i,isDirty:r.dirty,readOnly:r.readOnly,widgetType:a.constructor.name})}})}(o,i),E=function(e,t){return(0,b.tool)({name:"set_file_content",description:"Set or update the content of an existing file. This will replace the entire content of the file. For Jupyter notebooks, use dedicated notebook tools instead.",parameters:_e.z.object({filePath:_e.z.string().describe('Path to the file to update (e.g., "script.py", "README.md", "config.json")'),content:_e.z.string().describe("The new content to set for the file"),save:_e.z.boolean().optional().default(!0).describe("Whether to save the file after updating (default: true)")}),errorFunction:(e,t)=>JSON.stringify({success:!1,error:`Failed to set file content: ${t instanceof Error?t.message:String(t)}`}),execute:async o=>{const{filePath:n,content:a,save:r=!0}=o;let i=e.findWidget(n);if(i||(i=e.openOrReveal(n)),!i)throw new Error(`Failed to open file at path: ${n}`);await i.context.ready;const s=i.context.model;if(!s)throw new Error("File model not available");if(s.readOnly)throw new Error("File is read-only and cannot be modified");const l=s.sharedModel,c=l.getSource();return l.setSource(a),t&&await t.showFileDiff({original:String(c),modified:a,filePath:n}),r&&await i.context.save(),JSON.stringify({success:!0,filePath:n,fileName:i.title.label,contentLength:a.length,saved:r,isDirty:s.dirty})}})}(o,r);s.add("create_file",f),s.add("open_file",y),s.add("delete_file",_),s.add("rename_file",C),s.add("copy_file",w),s.add("navigate_to_directory",x),s.add("get_file_info",k),s.add("set_file_content",E);const M=function(e){return(0,b.tool)({name:"discover_commands",description:"Discover all available JupyterLab commands with their metadata, arguments, and descriptions",parameters:_e.z.object({query:_e.z.string().optional().nullable().describe("Optional search query to filter commands")}),execute:async t=>{const{query:o}=t,n=[],a=e.listCommands();for(const t of a){const a=await e.describedBy(t),r=e.label(t),i=e.caption(t),s=e.usage(t),l={id:t,label:r||void 0,caption:i||void 0,description:s||void 0,args:a?.args||void 0};if(o){const e=o.toLowerCase();(t.toLowerCase().includes(e)||r?.toLowerCase().includes(e)||i?.toLowerCase().includes(e)||s?.toLowerCase().includes(e))&&n.push(l)}else n.push(l)}return{success:!0,commandCount:n.length,commands:n}}})}(e.commands),I=function(e,t){return(0,b.tool)({name:"execute_command",description:"Execute a specific JupyterLab command with optional arguments",parameters:_e.z.object({commandId:_e.z.string().describe("The ID of the command to execute"),args:_e.z.any().optional().describe("Optional arguments to pass to the command")}),needsApproval:async(e,{commandId:o})=>t.config.commandsRequiringApproval.some(e=>o.includes(e)||e.includes(o)),execute:async t=>{const{commandId:o,args:n}=t;if(!e.hasCommand(o))return{success:!1,error:`Command '${o}' does not exist. Use 'discover_commands' to see available commands.`};try{const t=await e.execute(o,n);let a;if(t&&"object"==typeof t&&(t.constructor?.name?.includes("Widget")||t.id))a={type:t.constructor?.name||"Widget",id:t.id,title:t.title?.label||t.title,className:t.className};else try{a=JSON.parse(JSON.stringify(t))}catch{a=t?"[Complex object - cannot serialize]":"Command executed successfully"}return{success:!0,commandId:o,result:a}}catch(e){return{success:!1,error:`Failed to execute command '${o}': ${e instanceof Error?e.message:String(e)}`}}}})}(e.commands,t);return s.add("discover_commands",M),s.add("execute_command",I),s}},tt={id:"@jupyterlite/ai:input-toolbar-factory",description:"The input toolbar registry plugin.",autoStart:!0,provides:r.IInputToolbarRegistryFactory,requires:[x,C],activate:(e,t,o)=>{const n={element:e=>{const{model:t}=e;return function(e){const t="Stop streaming";return te().createElement(r.TooltippedButton,{onClick:e.stopStreaming,tooltip:t,buttonProps:{size:"small",variant:"contained",color:"error",title:t}},te().createElement(ie,null))}({...e,stopStreaming:()=>t.chatContext.stopStreaming()})},position:50,hidden:!0},a={element:e=>{const{model:t}=e;return function(e){const t="Clear chat";return te().createElement(r.TooltippedButton,{onClick:e.clearMessages,tooltip:t,buttonProps:{size:"small",variant:"outlined",color:"secondary",title:t}},te().createElement(se,null))}({...e,clearMessages:()=>t.chatContext.clearMessages()})},position:0,hidden:!1},i=function(e,t=!0){return{element:o=>{const n={...o,toolRegistry:e,onToolSelectionChange:e=>{const t=o.model.chatContext;t.agentManager&&t.agentManager.setSelectedTools(e)},toolsEnabled:t};return te().createElement(pe,{...n})},position:1}}(o,t.config.toolsEnabled),s=function(e){return{element:t=>{if(!t.model.chatContext.agentManager)return;const o={...t,settingsModel:e};return te().createElement(ue,{...o})},position:.5}}(t);return{create(){const e=r.InputToolbarRegistry.defaultToolbarRegistry();return e.addItem("stop",n),e.addItem("clear",a),e.addItem("model",s),e.addItem("tools",i),t.stateChanged.connect(()=>{t.config.toolsEnabled?e.show("tools"):e.hide("tools")}),e}}}},ot={id:"@jupyterlite/ai:completion-status",description:"The completion status displayed in the status bar",autoStart:!0,requires:[x],optional:[g.IStatusBar],activate:(e,t,o)=>{if(!o)return;const n=new ge({settingsModel:t});o?.registerStatusItem("completionState",{item:n,align:"right",rank:10})}},nt=[qe,We,Je,Ke,Ge,He,Qe,Ze,Ve,Ye,et,Xe,tt,ot]},5764:(e,t,o)=>{o.d(t,{A:()=>r});var n=o(709),a=o(4848);const r=(0,n.A)((0,a.jsx)("path",{d:"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6"}),"Settings")}}]);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";(self.webpackChunk_jupyterlite_ai=self.webpackChunk_jupyterlite_ai||[]).push([[92],{8092:(t,e,o)=>{o.d(e,{CallToolResultSchema:()=>vt,GU:()=>Wt,HM:()=>bt,Iu:()=>a,ListToolsResultSchema:()=>_t,Nh:()=>Jt,O$:()=>X,O4:()=>_,OR:()=>C,Rk:()=>H,Sq:()=>P,Yu:()=>zt,_r:()=>$,aE:()=>r,cv:()=>K,lg:()=>j,o$:()=>T,tC:()=>O,tG:()=>f,ve:()=>tt,vo:()=>b,wR:()=>k,wU:()=>N});var n=o(9661);const r="2025-06-18",a=[r,"2025-03-26","2024-11-05","2024-10-07"],i="2.0",s=n.z.union([n.z.string(),n.z.number().int()]),z=n.z.string(),l=n.z.object({progressToken:n.z.optional(s)}).passthrough(),p=n.z.object({_meta:n.z.optional(l)}).passthrough(),c=n.z.object({method:n.z.string(),params:n.z.optional(p)}),u=n.z.object({_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),g=n.z.object({method:n.z.string(),params:n.z.optional(u)}),m=n.z.object({_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),h=n.z.union([n.z.string(),n.z.number().int()]),d=n.z.object({jsonrpc:n.z.literal(i),id:h}).merge(c).strict(),b=t=>d.safeParse(t).success,x=n.z.object({jsonrpc:n.z.literal(i)}).merge(g).strict(),j=t=>x.safeParse(t).success,y=n.z.object({jsonrpc:n.z.literal(i),id:h,result:m}).strict(),f=t=>y.safeParse(t).success;var _;!function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"}(_||(_={}));const v=n.z.object({jsonrpc:n.z.literal(i),id:h,error:n.z.object({code:n.z.number().int(),message:n.z.string(),data:n.z.optional(n.z.unknown())})}).strict(),T=t=>v.safeParse(t).success,C=n.z.union([d,x,y,v]),k=m.strict(),P=g.extend({method:n.z.literal("notifications/cancelled"),params:u.extend({requestId:h,reason:n.z.string().optional()})}),q=n.z.object({src:n.z.string(),mimeType:n.z.optional(n.z.string()),sizes:n.z.optional(n.z.array(n.z.string()))}).passthrough(),w=n.z.object({icons:n.z.array(q).optional()}).passthrough(),I=n.z.object({name:n.z.string(),title:n.z.optional(n.z.string())}).passthrough(),R=I.extend({version:n.z.string(),websiteUrl:n.z.optional(n.z.string())}).merge(w),S=n.z.object({experimental:n.z.optional(n.z.object({}).passthrough()),sampling:n.z.optional(n.z.object({}).passthrough()),elicitation:n.z.optional(n.z.object({}).passthrough()),roots:n.z.optional(n.z.object({listChanged:n.z.optional(n.z.boolean())}).passthrough())}).passthrough(),E=c.extend({method:n.z.literal("initialize"),params:p.extend({protocolVersion:n.z.string(),capabilities:S,clientInfo:R})}),M=n.z.object({experimental:n.z.optional(n.z.object({}).passthrough()),logging:n.z.optional(n.z.object({}).passthrough()),completions:n.z.optional(n.z.object({}).passthrough()),prompts:n.z.optional(n.z.object({listChanged:n.z.optional(n.z.boolean())}).passthrough()),resources:n.z.optional(n.z.object({subscribe:n.z.optional(n.z.boolean()),listChanged:n.z.optional(n.z.boolean())}).passthrough()),tools:n.z.optional(n.z.object({listChanged:n.z.optional(n.z.boolean())}).passthrough())}).passthrough(),H=m.extend({protocolVersion:n.z.string(),capabilities:M,serverInfo:R,instructions:n.z.optional(n.z.string())}),L=g.extend({method:n.z.literal("notifications/initialized")}),N=t=>L.safeParse(t).success,O=c.extend({method:n.z.literal("ping")}),U=n.z.object({progress:n.z.number(),total:n.z.optional(n.z.number()),message:n.z.optional(n.z.string())}).passthrough(),$=g.extend({method:n.z.literal("notifications/progress"),params:u.merge(U).extend({progressToken:s})}),F=c.extend({params:p.extend({cursor:n.z.optional(z)}).optional()}),G=m.extend({nextCursor:n.z.optional(z)}),V=n.z.object({uri:n.z.string(),mimeType:n.z.optional(n.z.string()),_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),W=V.extend({text:n.z.string()}),B=n.z.string().refine(t=>{try{return atob(t),!0}catch(t){return!1}},{message:"Invalid Base64 string"}),Y=V.extend({blob:B}),A=I.extend({uri:n.z.string(),description:n.z.optional(n.z.string()),mimeType:n.z.optional(n.z.string()),_meta:n.z.optional(n.z.object({}).passthrough())}).merge(w),D=I.extend({uriTemplate:n.z.string(),description:n.z.optional(n.z.string()),mimeType:n.z.optional(n.z.string()),_meta:n.z.optional(n.z.object({}).passthrough())}).merge(w),J=F.extend({method:n.z.literal("resources/list")}),K=G.extend({resources:n.z.array(A)}),Q=F.extend({method:n.z.literal("resources/templates/list")}),X=G.extend({resourceTemplates:n.z.array(D)}),Z=c.extend({method:n.z.literal("resources/read"),params:p.extend({uri:n.z.string()})}),tt=m.extend({contents:n.z.array(n.z.union([W,Y]))}),et=g.extend({method:n.z.literal("notifications/resources/list_changed")}),ot=c.extend({method:n.z.literal("resources/subscribe"),params:p.extend({uri:n.z.string()})}),nt=c.extend({method:n.z.literal("resources/unsubscribe"),params:p.extend({uri:n.z.string()})}),rt=g.extend({method:n.z.literal("notifications/resources/updated"),params:u.extend({uri:n.z.string()})}),at=n.z.object({name:n.z.string(),description:n.z.optional(n.z.string()),required:n.z.optional(n.z.boolean())}).passthrough(),it=I.extend({description:n.z.optional(n.z.string()),arguments:n.z.optional(n.z.array(at)),_meta:n.z.optional(n.z.object({}).passthrough())}).merge(w),st=F.extend({method:n.z.literal("prompts/list")}),zt=G.extend({prompts:n.z.array(it)}),lt=c.extend({method:n.z.literal("prompts/get"),params:p.extend({name:n.z.string(),arguments:n.z.optional(n.z.record(n.z.string()))})}),pt=n.z.object({type:n.z.literal("text"),text:n.z.string(),_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),ct=n.z.object({type:n.z.literal("image"),data:B,mimeType:n.z.string(),_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),ut=n.z.object({type:n.z.literal("audio"),data:B,mimeType:n.z.string(),_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),gt=n.z.object({type:n.z.literal("resource"),resource:n.z.union([W,Y]),_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),mt=A.extend({type:n.z.literal("resource_link")}),ht=n.z.union([pt,ct,ut,mt,gt]),dt=n.z.object({role:n.z.enum(["user","assistant"]),content:ht}).passthrough(),bt=m.extend({description:n.z.optional(n.z.string()),messages:n.z.array(dt)}),xt=g.extend({method:n.z.literal("notifications/prompts/list_changed")}),jt=n.z.object({title:n.z.optional(n.z.string()),readOnlyHint:n.z.optional(n.z.boolean()),destructiveHint:n.z.optional(n.z.boolean()),idempotentHint:n.z.optional(n.z.boolean()),openWorldHint:n.z.optional(n.z.boolean())}).passthrough(),yt=I.extend({description:n.z.optional(n.z.string()),inputSchema:n.z.object({type:n.z.literal("object"),properties:n.z.optional(n.z.object({}).passthrough()),required:n.z.optional(n.z.array(n.z.string()))}).passthrough(),outputSchema:n.z.optional(n.z.object({type:n.z.literal("object"),properties:n.z.optional(n.z.object({}).passthrough()),required:n.z.optional(n.z.array(n.z.string()))}).passthrough()),annotations:n.z.optional(jt),_meta:n.z.optional(n.z.object({}).passthrough())}).merge(w),ft=F.extend({method:n.z.literal("tools/list")}),_t=G.extend({tools:n.z.array(yt)}),vt=m.extend({content:n.z.array(ht).default([]),structuredContent:n.z.object({}).passthrough().optional(),isError:n.z.optional(n.z.boolean())}),Tt=(vt.or(m.extend({toolResult:n.z.unknown()})),c.extend({method:n.z.literal("tools/call"),params:p.extend({name:n.z.string(),arguments:n.z.optional(n.z.record(n.z.unknown()))})})),Ct=g.extend({method:n.z.literal("notifications/tools/list_changed")}),kt=n.z.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Pt=c.extend({method:n.z.literal("logging/setLevel"),params:p.extend({level:kt})}),qt=g.extend({method:n.z.literal("notifications/message"),params:u.extend({level:kt,logger:n.z.optional(n.z.string()),data:n.z.unknown()})}),wt=n.z.object({name:n.z.string().optional()}).passthrough(),It=n.z.object({hints:n.z.optional(n.z.array(wt)),costPriority:n.z.optional(n.z.number().min(0).max(1)),speedPriority:n.z.optional(n.z.number().min(0).max(1)),intelligencePriority:n.z.optional(n.z.number().min(0).max(1))}).passthrough(),Rt=n.z.object({role:n.z.enum(["user","assistant"]),content:n.z.union([pt,ct,ut])}).passthrough(),St=c.extend({method:n.z.literal("sampling/createMessage"),params:p.extend({messages:n.z.array(Rt),systemPrompt:n.z.optional(n.z.string()),includeContext:n.z.optional(n.z.enum(["none","thisServer","allServers"])),temperature:n.z.optional(n.z.number()),maxTokens:n.z.number().int(),stopSequences:n.z.optional(n.z.array(n.z.string())),metadata:n.z.optional(n.z.object({}).passthrough()),modelPreferences:n.z.optional(It)})}),Et=m.extend({model:n.z.string(),stopReason:n.z.optional(n.z.enum(["endTurn","stopSequence","maxTokens"]).or(n.z.string())),role:n.z.enum(["user","assistant"]),content:n.z.discriminatedUnion("type",[pt,ct,ut])}),Mt=n.z.object({type:n.z.literal("boolean"),title:n.z.optional(n.z.string()),description:n.z.optional(n.z.string()),default:n.z.optional(n.z.boolean())}).passthrough(),Ht=n.z.object({type:n.z.literal("string"),title:n.z.optional(n.z.string()),description:n.z.optional(n.z.string()),minLength:n.z.optional(n.z.number()),maxLength:n.z.optional(n.z.number()),format:n.z.optional(n.z.enum(["email","uri","date","date-time"]))}).passthrough(),Lt=n.z.object({type:n.z.enum(["number","integer"]),title:n.z.optional(n.z.string()),description:n.z.optional(n.z.string()),minimum:n.z.optional(n.z.number()),maximum:n.z.optional(n.z.number())}).passthrough(),Nt=n.z.object({type:n.z.literal("string"),title:n.z.optional(n.z.string()),description:n.z.optional(n.z.string()),enum:n.z.array(n.z.string()),enumNames:n.z.optional(n.z.array(n.z.string()))}).passthrough(),Ot=n.z.union([Mt,Ht,Lt,Nt]),Ut=c.extend({method:n.z.literal("elicitation/create"),params:p.extend({message:n.z.string(),requestedSchema:n.z.object({type:n.z.literal("object"),properties:n.z.record(n.z.string(),Ot),required:n.z.optional(n.z.array(n.z.string()))}).passthrough()})}),$t=m.extend({action:n.z.enum(["accept","decline","cancel"]),content:n.z.optional(n.z.record(n.z.string(),n.z.unknown()))}),Ft=n.z.object({type:n.z.literal("ref/resource"),uri:n.z.string()}).passthrough(),Gt=n.z.object({type:n.z.literal("ref/prompt"),name:n.z.string()}).passthrough(),Vt=c.extend({method:n.z.literal("completion/complete"),params:p.extend({ref:n.z.union([Gt,Ft]),argument:n.z.object({name:n.z.string(),value:n.z.string()}).passthrough(),context:n.z.optional(n.z.object({arguments:n.z.optional(n.z.record(n.z.string(),n.z.string()))}))})}),Wt=m.extend({completion:n.z.object({values:n.z.array(n.z.string()).max(100),total:n.z.optional(n.z.number().int()),hasMore:n.z.optional(n.z.boolean())}).passthrough()}),Bt=n.z.object({uri:n.z.string().startsWith("file://"),name:n.z.optional(n.z.string()),_meta:n.z.optional(n.z.object({}).passthrough())}).passthrough(),Yt=c.extend({method:n.z.literal("roots/list")}),At=m.extend({roots:n.z.array(Bt)}),Dt=g.extend({method:n.z.literal("notifications/roots/list_changed")});n.z.union([O,E,Vt,Pt,lt,st,J,Q,Z,ot,nt,Tt,ft]),n.z.union([P,$,L,Dt]),n.z.union([k,Et,$t,At]),n.z.union([O,St,Ut,Yt]),n.z.union([P,$,qt,rt,et,Ct,xt]),n.z.union([k,H,Wt,bt,zt,K,X,tt,vt,_t]);class Jt extends Error{constructor(t,e,o){super(`MCP error ${t}: ${e}`),this.code=t,this.data=o,this.name="McpError"}}}}]);
|