iobroker.javascript 9.2.1 → 9.2.2

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/README.md CHANGED
@@ -27,10 +27,15 @@ Executes Javascript, Typescript Scripts.
27
27
  -->
28
28
 
29
29
  ## Changelog
30
+ ### 9.2.2 (2026-05-07)
31
+ * (Eistee82) Fix: AI chat mode tooltip no longer covers the dropdown options (issue #2201) — moved tooltip to the left of the selector
32
+ * (Eistee82) Clarified the AI chat mode descriptions in the tooltip: Agent is for larger models with tool support and handles both analysis and script creation, Code is for smaller models without tool support (uses two-step plan-then-code) — translations updated in all 11 languages
33
+ * (@GermanBluefox) Added the "is state exists" block to blockly
34
+
30
35
  ### 9.2.1 (2026-04-30)
31
36
  * (@GermanBluefox) See previous changelog entries
32
37
 
33
- ### 9.2.0 (2026-04-3)
38
+ ### 9.2.0 (2026-04-30)
34
39
  * (@GermanBluefox) Agent keys are encrypted now. You must enter your keys anew!
35
40
  * (Eistee82) AI API keys are now stored encrypted and only used server-side (`encryptedNative` + `protectedNative`); the frontend never sees them
36
41
  * (Eistee82) Code Lens above every top-level function/class/arrow with `💡 Explain | 🔧 Refactor | ✅ Tests` actions
@@ -67,10 +72,6 @@ Executes Javascript, Typescript Scripts.
67
72
  * All API calls (models + chat) are proxied server-side to avoid CORS issues with local providers
68
73
  * Strip LLM thinking artifacts from responses (for local models like Ollama)
69
74
 
70
- ### 9.0.18 (2026-01-11)
71
- * (@GermanBluefox) Corrected an error message with `lastSync`
72
- * (@klein0r) Corrected JavaScript filter
73
-
74
75
  ## License
75
76
  The MIT License (MIT)
76
77
 
@@ -1,4 +1,4 @@
1
- import{c as Se,j as i}from"./createSvgIcon-DYs_tNrE.js";import{k as U,j as te,b as ne,c as xe,l as Ae}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{z as $,P as ve,o as we,a0 as ct,a1 as lt,i as We,J as dt,r as ut,s as mt,u as pt,a2 as He,c as ft,f as Fe,g as ze,a3 as Oe,a4 as Ve,a5 as ht}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-CV1_X-Lf.js";import{_ as u}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{_ as Ze}from"./preload-helper-BDBacUwf.js";import{C as gt,b as yt,I as bt,R as xt}from"./index-SHs7_wDh.js";import{i as vt,k as qe,l as wt,n as St}from"./index-CYbVtccs.js";import{g as kt,c as jt}from"./index-wHNMOf-c.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-DNrEsMrg.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-CIXm_zPk.js";const et=Se(i.jsx("path",{d:"M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4zm-1-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8"}),"AddCircleOutline"),_t=Se(i.jsx("path",{d:"M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4zM17 11h-4v4h-2v-4H7V9h4V5h2v4h4z"}),"AddComment"),Ct=Se(i.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10h5v-2h-5c-4.34 0-8-3.66-8-8s3.66-8 8-8 8 3.66 8 8v1.43c0 .79-.71 1.57-1.5 1.57s-1.5-.78-1.5-1.57V12c0-2.76-2.24-5-5-5s-5 2.24-5 5 2.24 5 5 5c1.38 0 2.64-.56 3.54-1.47.65.89 1.77 1.47 2.96 1.47 1.97 0 3.5-1.6 3.5-3.57V12c0-5.52-4.48-10-10-10m0 13c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3"}),"AlternateEmail"),It=Se(i.jsx("path",{d:"M9.01 14H2v2h7.01v3L13 15l-3.99-4zm5.98-1v-3H22V8h-7.01V5L11 9z"}),"CompareArrows"),Tt=Se(i.jsx("path",{d:"M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4m0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4"}),"Person"),Ot=Se(i.jsx("path",{d:"M3 10h11v2H3zm0-4h11v2H3zm0 8h7v2H3zm17.59-2.07-4.25 4.24-2.12-2.12-1.41 1.41L16.34 19 22 13.34z"}),"PlaylistAddCheck"),Et=Se(i.jsx("path",{d:"M2.01 21 23 12 2.01 3 2 10l15 2-15 2z"}),"Send"),Rt=Se(i.jsx("path",{d:"M20 9V7c0-1.1-.9-2-2-2h-3c0-1.66-1.34-3-3-3S9 3.34 9 5H6c-1.1 0-2 .9-2 2v2c-1.66 0-3 1.34-3 3s1.34 3 3 3v4c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-4c1.66 0 3-1.34 3-3s-1.34-3-3-3M7.5 11.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5S9.83 13 9 13s-1.5-.67-1.5-1.5M16 17H8v-2h8zm-1-4c-.83 0-1.5-.67-1.5-1.5S14.17 10 15 10s1.5.67 1.5 1.5S15.83 13 15 13"}),"SmartToy"),Nt=Ze(()=>import("./docs-compact-CKNGiYh2.js"),[],import.meta.url),$t={openai:"img/openai.svg",anthropic:"img/anthropic.svg",gemini:"img/gemini.svg",deepseek:"img/deepseek.svg",custom:"img/custom.svg"},Lt={width:16,height:16,flexShrink:0,opacity:.7},Mt={ru:"Russian",en:"English",de:"German",es:"Spanish",fr:"French",it:"Italian",pl:"Polish",nl:"Dutch",pt:"Portuguese",uk:"Ukrainian","zh-cn":"Chinese"};let $e=null,Ue=null,Le=null,Me=null;function Dt(){$e=null,Ue=null,Le=null,Me=null}async function De(r,e){if($e)return $e;const n=Object.keys(e)[0];if(!n)return null;const t=await r.sendTo(n,"getAvailableAiProviders",{}),o=((t==null?void 0:t.providers)||[]).map(d=>d.provider),s=((t==null?void 0:t.providers)||[]).find(d=>d.provider==="custom");return o.length?($e={providers:o,gptBaseUrl:s==null?void 0:s.baseUrl},$e):null}const Bt=["embedding","text-embedding","textembedding","embeddinggemma","embed-","-embed","bge-","mxbai-embed","nomic-embed","arctic-embed","snowflake-arctic-embed","all-minilm","multilingual-e5","jina-embed","voyage-","gecko","paraphrase-multilingual","dall-e","gpt-image","image-edit","-image-preview","-image-latest","flash-image","nano-banana","stable-diffusion","sdxl","midjourney","flux-","imagen","sora","veo-","cogvideo","runway-","lumiere","lyria","whisper","tts-","-tts","speech-","audio-preview","mini-tts","mini-transcribe","-transcribe","native-audio","flash-live","gpt-audio","realtime","bark-","xtts","voicebox","moderation","omni-moderation","llama-guard","shieldgemma","prompt-guard","-guardian","safeguard","rerank","reranker","babbage-","davinci-","curie-","text-ada-","text-davinci","text-curie","text-babbage","instructgpt","code-davinci","code-cushman","-turbo-instruct","-search-preview","-search-api","code-search","text-search","similarity-","computer-use-preview","deep-research","robotics","aqa","reader-lm","-nsql","minicheck"];function zt(r){const e=r.toLowerCase();return!(Bt.some(n=>e.includes(n))||e.startsWith("claude-1")||e.startsWith("claude-instant"))}async function Pt(r,e){const n=await De(r,e);if(!n)return{models:[],providerMap:{},errors:["No API keys configured"]};const t=Object.keys(e)[0];if(!t)return{models:[],providerMap:{},errors:[u.I18n.t("No running javascript instance found")]};const o=[],s={},d=[],m=(a,y)=>{for(const l of a)zt(l)&&(s[l]||(o.push(l),s[l]=y))},c=[],p=(a,y)=>{c.push(r.sendTo(t,"testApiConnection",{provider:a==="custom"?"openai":a}).then(l=>{l.models?m(l.models,a):l.error&&d.push(`${y||a}: ${l.error}`)}).catch(l=>{d.push(`${y||a}: ${String(l)}`)}))},g={openai:"OpenAI",anthropic:"Anthropic",gemini:"Gemini",deepseek:"DeepSeek",custom:"Custom"};for(const a of n.providers)p(a,g[a]);return await Promise.all(c),o.sort(),{models:o,providerMap:s,errors:d}}async function Re(r,e,n){var o;return await r.sendTo(e,"chatCompletion",{timeout:n.timeout||6e5,model:n.model,provider:n.provider,messages:n.messages,...n.baseUrl?{baseUrl:n.baseUrl}:{},...(o=n.tools)!=null&&o.length?{tools:n.tools}:{}})}async function tt(r){if(Me)return Me;const e=await r.getObjectViewSystem("state","","香"),n=await r.getObjectViewSystem("channel","","香"),t=await r.getObjectViewSystem("device","","香"),o=await r.getObjectViewSystem("folder","","香"),s=await r.getObjectViewSystem("enum","","香");return Me=Object.assign(e,n,t,o,s),Me}async function nt(r){return tt(r)}function Ie(r,e){return r&&typeof r=="object"?r[e]||r.en:r||""}async function Ye(r){var S,b,v,F;if(Ue)return Ue;const e=u.I18n.getLanguage(),n=await tt(r),t=Object.keys(n).sort(),o=new gt,s=[],d=["UNREACH_STICKY"],m=[yt.Types.info],c=[],p=[],g=[],a=[];t.forEach(E=>{var I,x,w;((I=n[E])==null?void 0:I.type)==="enum"?c.push(E):(w=(x=n[E])==null?void 0:x.common)!=null&&w.smartName&&a.push(E)}),c.forEach(E=>{E.startsWith("enum.rooms.")?p.push(E):E.startsWith("enum.functions.")&&g.push(E);const I=n[E].common.members;I!=null&&I.length&&I.forEach(x=>{n[x]&&!a.includes(x)&&a.push(x)})});const y={id:"",objects:n,_keysOptional:t,_usedIdsOptional:s,ignoreIndicators:d,excludedTypes:m},l=[];a.forEach(E=>{y.id=E;const I=o.detect(y);I&&I.forEach(x=>{var de;const w=(de=x.states.find(T=>T.id))==null?void 0:de.id;if(!w||l.find(T=>T.id===w))return;const M=n[w],re={id:w,name:Ie(M.common.name,e),type:M.type,deviceType:x.type,states:x.states.filter(T=>T.id).map(T=>({id:T.id,name:T.name,role:T.defaultRole,type:n[T.id].common.type,unit:n[T.id].common.unit,read:n[T.id].common.read??!0,write:n[T.id].common.write??!0}))},Y=w.split(".");let _,G;(M.type==="channel"||M.type==="state")&&(Y.pop(),_=Y.join("."),n[_]&&(n[_].type==="channel"||n[_].type==="folder")?(Y.pop(),G=Y.join("."),(!n[G]||n[G].type!=="device"&&n[_].type!=="folder")&&(G=void 0)):_=void 0);const le=p.find(T=>{var A,X,Q;return(A=n[T].common.members)!=null&&A.includes(w)||_&&((X=n[T].common.members)!=null&&X.includes(_))?!0:G&&((Q=n[T].common.members)==null?void 0:Q.includes(G))});le&&(re.room=Ie(n[le].common.name,e));const K=g.find(T=>{var A,X,Q;return(A=n[T].common.members)!=null&&A.includes(w)||_&&((X=n[T].common.members)!=null&&X.includes(_))?!0:G&&((Q=n[T].common.members)==null?void 0:Q.includes(G))});K&&(re.function=Ie(n[K].common.name,e)),l.push(re)})});for(let E=0;E<l.length;E++){const I=l[E];if(I.type==="state"||I.type==="channel"){const x=I.id.split(".");x.pop();const w=n[x.join(".")];if(w&&(w.type==="channel"||w.type==="device"||w.type==="folder")){I.name=Ie(((S=w.common)==null?void 0:S.name)||I.name,e),x.pop();const M=n[x.join(".")];(M==null?void 0:M.type)==="device"&&((b=M.common)!=null&&b.icon)&&(I.name=Ie(((v=M.common)==null?void 0:v.name)||I.name,e))}else I.name=Ie(((F=w==null?void 0:w.common)==null?void 0:F.name)||I.name,e)}}return Ue=l,l}async function Ut(){return Le||(Le=(await Nt).default,Le)}function Ge(){return Mt[u.I18n.getLanguage()]||"English"}function At(r){return`You write ioBroker JavaScript adapter scripts.
1
+ import{c as Se,j as i}from"./createSvgIcon-DYs_tNrE.js";import{k as A,j as te,b as ne,c as xe,l as Ue}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{z as $,P as ve,o as we,a0 as ct,a1 as lt,i as We,J as dt,r as ut,s as mt,u as pt,a2 as Fe,c as ft,f as He,g as ze,a3 as Oe,a4 as Ve,a5 as ht}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-CV1_X-Lf.js";import{_ as u}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{_ as Ze}from"./preload-helper-BDBacUwf.js";import{C as gt,b as yt,I as bt,R as xt}from"./index-SHs7_wDh.js";import{i as vt,k as qe,l as wt,n as St}from"./index-DSvAO584.js";import{g as kt,c as jt}from"./index-wHNMOf-c.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-DNrEsMrg.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-CIXm_zPk.js";const et=Se(i.jsx("path",{d:"M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4zm-1-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8"}),"AddCircleOutline"),_t=Se(i.jsx("path",{d:"M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4zM17 11h-4v4h-2v-4H7V9h4V5h2v4h4z"}),"AddComment"),Ct=Se(i.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10h5v-2h-5c-4.34 0-8-3.66-8-8s3.66-8 8-8 8 3.66 8 8v1.43c0 .79-.71 1.57-1.5 1.57s-1.5-.78-1.5-1.57V12c0-2.76-2.24-5-5-5s-5 2.24-5 5 2.24 5 5 5c1.38 0 2.64-.56 3.54-1.47.65.89 1.77 1.47 2.96 1.47 1.97 0 3.5-1.6 3.5-3.57V12c0-5.52-4.48-10-10-10m0 13c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3"}),"AlternateEmail"),It=Se(i.jsx("path",{d:"M9.01 14H2v2h7.01v3L13 15l-3.99-4zm5.98-1v-3H22V8h-7.01V5L11 9z"}),"CompareArrows"),Tt=Se(i.jsx("path",{d:"M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4m0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4"}),"Person"),Ot=Se(i.jsx("path",{d:"M3 10h11v2H3zm0-4h11v2H3zm0 8h7v2H3zm17.59-2.07-4.25 4.24-2.12-2.12-1.41 1.41L16.34 19 22 13.34z"}),"PlaylistAddCheck"),Et=Se(i.jsx("path",{d:"M2.01 21 23 12 2.01 3 2 10l15 2-15 2z"}),"Send"),Rt=Se(i.jsx("path",{d:"M20 9V7c0-1.1-.9-2-2-2h-3c0-1.66-1.34-3-3-3S9 3.34 9 5H6c-1.1 0-2 .9-2 2v2c-1.66 0-3 1.34-3 3s1.34 3 3 3v4c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-4c1.66 0 3-1.34 3-3s-1.34-3-3-3M7.5 11.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5S9.83 13 9 13s-1.5-.67-1.5-1.5M16 17H8v-2h8zm-1-4c-.83 0-1.5-.67-1.5-1.5S14.17 10 15 10s1.5.67 1.5 1.5S15.83 13 15 13"}),"SmartToy"),Nt=Ze(()=>import("./docs-compact-CKNGiYh2.js"),[],import.meta.url),$t={openai:"img/openai.svg",anthropic:"img/anthropic.svg",gemini:"img/gemini.svg",deepseek:"img/deepseek.svg",custom:"img/custom.svg"},Lt={width:16,height:16,flexShrink:0,opacity:.7},Mt={ru:"Russian",en:"English",de:"German",es:"Spanish",fr:"French",it:"Italian",pl:"Polish",nl:"Dutch",pt:"Portuguese",uk:"Ukrainian","zh-cn":"Chinese"};let $e=null,Ae=null,Le=null,Me=null;function Dt(){$e=null,Ae=null,Le=null,Me=null}async function De(r,e){if($e)return $e;const n=Object.keys(e)[0];if(!n)return null;const t=await r.sendTo(n,"getAvailableAiProviders",{}),o=((t==null?void 0:t.providers)||[]).map(d=>d.provider),s=((t==null?void 0:t.providers)||[]).find(d=>d.provider==="custom");return o.length?($e={providers:o,gptBaseUrl:s==null?void 0:s.baseUrl},$e):null}const Bt=["embedding","text-embedding","textembedding","embeddinggemma","embed-","-embed","bge-","mxbai-embed","nomic-embed","arctic-embed","snowflake-arctic-embed","all-minilm","multilingual-e5","jina-embed","voyage-","gecko","paraphrase-multilingual","dall-e","gpt-image","image-edit","-image-preview","-image-latest","flash-image","nano-banana","stable-diffusion","sdxl","midjourney","flux-","imagen","sora","veo-","cogvideo","runway-","lumiere","lyria","whisper","tts-","-tts","speech-","audio-preview","mini-tts","mini-transcribe","-transcribe","native-audio","flash-live","gpt-audio","realtime","bark-","xtts","voicebox","moderation","omni-moderation","llama-guard","shieldgemma","prompt-guard","-guardian","safeguard","rerank","reranker","babbage-","davinci-","curie-","text-ada-","text-davinci","text-curie","text-babbage","instructgpt","code-davinci","code-cushman","-turbo-instruct","-search-preview","-search-api","code-search","text-search","similarity-","computer-use-preview","deep-research","robotics","aqa","reader-lm","-nsql","minicheck"];function zt(r){const e=r.toLowerCase();return!(Bt.some(n=>e.includes(n))||e.startsWith("claude-1")||e.startsWith("claude-instant"))}async function Pt(r,e){const n=await De(r,e);if(!n)return{models:[],providerMap:{},errors:["No API keys configured"]};const t=Object.keys(e)[0];if(!t)return{models:[],providerMap:{},errors:[u.I18n.t("No running javascript instance found")]};const o=[],s={},d=[],m=(a,y)=>{for(const l of a)zt(l)&&(s[l]||(o.push(l),s[l]=y))},c=[],p=(a,y)=>{c.push(r.sendTo(t,"testApiConnection",{provider:a==="custom"?"openai":a}).then(l=>{l.models?m(l.models,a):l.error&&d.push(`${y||a}: ${l.error}`)}).catch(l=>{d.push(`${y||a}: ${String(l)}`)}))},g={openai:"OpenAI",anthropic:"Anthropic",gemini:"Gemini",deepseek:"DeepSeek",custom:"Custom"};for(const a of n.providers)p(a,g[a]);return await Promise.all(c),o.sort(),{models:o,providerMap:s,errors:d}}async function Re(r,e,n){var o;return await r.sendTo(e,"chatCompletion",{timeout:n.timeout||6e5,model:n.model,provider:n.provider,messages:n.messages,...n.baseUrl?{baseUrl:n.baseUrl}:{},...(o=n.tools)!=null&&o.length?{tools:n.tools}:{}})}async function tt(r){if(Me)return Me;const e=await r.getObjectViewSystem("state","","香"),n=await r.getObjectViewSystem("channel","","香"),t=await r.getObjectViewSystem("device","","香"),o=await r.getObjectViewSystem("folder","","香"),s=await r.getObjectViewSystem("enum","","香");return Me=Object.assign(e,n,t,o,s),Me}async function nt(r){return tt(r)}function Ie(r,e){return r&&typeof r=="object"?r[e]||r.en:r||""}async function Ye(r){var S,b,v,H;if(Ae)return Ae;const e=u.I18n.getLanguage(),n=await tt(r),t=Object.keys(n).sort(),o=new gt,s=[],d=["UNREACH_STICKY"],m=[yt.Types.info],c=[],p=[],g=[],a=[];t.forEach(E=>{var I,x,w;((I=n[E])==null?void 0:I.type)==="enum"?c.push(E):(w=(x=n[E])==null?void 0:x.common)!=null&&w.smartName&&a.push(E)}),c.forEach(E=>{E.startsWith("enum.rooms.")?p.push(E):E.startsWith("enum.functions.")&&g.push(E);const I=n[E].common.members;I!=null&&I.length&&I.forEach(x=>{n[x]&&!a.includes(x)&&a.push(x)})});const y={id:"",objects:n,_keysOptional:t,_usedIdsOptional:s,ignoreIndicators:d,excludedTypes:m},l=[];a.forEach(E=>{y.id=E;const I=o.detect(y);I&&I.forEach(x=>{var de;const w=(de=x.states.find(T=>T.id))==null?void 0:de.id;if(!w||l.find(T=>T.id===w))return;const M=n[w],re={id:w,name:Ie(M.common.name,e),type:M.type,deviceType:x.type,states:x.states.filter(T=>T.id).map(T=>({id:T.id,name:T.name,role:T.defaultRole,type:n[T.id].common.type,unit:n[T.id].common.unit,read:n[T.id].common.read??!0,write:n[T.id].common.write??!0}))},Y=w.split(".");let _,G;(M.type==="channel"||M.type==="state")&&(Y.pop(),_=Y.join("."),n[_]&&(n[_].type==="channel"||n[_].type==="folder")?(Y.pop(),G=Y.join("."),(!n[G]||n[G].type!=="device"&&n[_].type!=="folder")&&(G=void 0)):_=void 0);const le=p.find(T=>{var U,X,Q;return(U=n[T].common.members)!=null&&U.includes(w)||_&&((X=n[T].common.members)!=null&&X.includes(_))?!0:G&&((Q=n[T].common.members)==null?void 0:Q.includes(G))});le&&(re.room=Ie(n[le].common.name,e));const K=g.find(T=>{var U,X,Q;return(U=n[T].common.members)!=null&&U.includes(w)||_&&((X=n[T].common.members)!=null&&X.includes(_))?!0:G&&((Q=n[T].common.members)==null?void 0:Q.includes(G))});K&&(re.function=Ie(n[K].common.name,e)),l.push(re)})});for(let E=0;E<l.length;E++){const I=l[E];if(I.type==="state"||I.type==="channel"){const x=I.id.split(".");x.pop();const w=n[x.join(".")];if(w&&(w.type==="channel"||w.type==="device"||w.type==="folder")){I.name=Ie(((S=w.common)==null?void 0:S.name)||I.name,e),x.pop();const M=n[x.join(".")];(M==null?void 0:M.type)==="device"&&((b=M.common)!=null&&b.icon)&&(I.name=Ie(((v=M.common)==null?void 0:v.name)||I.name,e))}else I.name=Ie(((H=w==null?void 0:w.common)==null?void 0:H.name)||I.name,e)}}return Ae=l,l}async function At(){return Le||(Le=(await Nt).default,Le)}function Ge(){return Mt[u.I18n.getLanguage()]||"English"}function Ut(r){return`You write ioBroker JavaScript adapter scripts.
2
2
  Copy EXACTLY this syntax. Do NOT change the callback signature.
3
3
  IMPORTANT: Write all code at top level. NEVER use console.log (use log instead). NEVER define functions with the function keyword.
4
4
 
@@ -213,8 +213,8 @@ IMPORTANT RULES:
213
213
  </statement>
214
214
  </block>
215
215
 
216
- Write comments in ${r}. Put blocks in a \`\`\`xml code block.`}function Pe(r){let e=r;return e=e.replace(/<think>[\s\S]*?<\/think>/gi,""),e=e.replace(/<\|endoftext\|>/g,""),e=e.replace(/<\|im_start\|>[\s\S]*?<\|im_end\|>/g,""),e=e.replace(/<\|im_start\|>[\s\S]*/g,""),e.trim()}const Jt=[{type:"function",function:{name:"search_datapoints",description:'Search ALL ioBroker objects by ID, name, or role — includes states, channels, devices, folders, enums (rooms/functions), adapters, instances, scripts, meta, etc. Returns matching IDs with object type, name, role, unit, and a hasChildren hint for containers. IMPORTANT: Aliases and physical device groupings are usually CHANNELS containing multiple state children (e.g. a motion sensor is often a channel alias.0.Floor.Room.MotionSensor with states ACTUAL, BATTERY, STATE under it). If a channel/device/folder matches your query, call get_object_info on its ID to list its state children. Role-based queries work too: "sensor.motion", "switch.light", "value.temperature".',parameters:{type:"object",properties:{query:{type:"string",description:'Search pattern (case-insensitive substring) - matches against object ID, name, and role. Examples: "bewegungsmelder", "temperature", "sensor.motion", "alias.0", "küche", "zigbee2mqtt.0.lamp".'},max_results:{type:"number",description:"Maximum number of results to return (default: 20)."},object_type:{type:"string",description:'Optional filter by object type: "state", "channel", "device", "folder", "enum", "adapter", "instance", "script", "meta", etc. Omit to search every type.'}},required:["query"]}}},{type:"function",function:{name:"get_state_value",description:"Get the current value of an ioBroker state/datapoint. Returns value, timestamp, and acknowledgment flag.",parameters:{type:"object",properties:{id:{type:"string",description:'The full state ID, e.g. "zigbee2mqtt.0.sensor.temperature"'}},required:["id"]}}},{type:"function",function:{name:"get_object_info",description:"Get detailed info about ANY ioBroker object + its full parent hierarchy + direct children. Works for every object type: state, channel, device, folder, adapter, instance, enum, meta, script. Returns: the object itself, parent chain (all non-state ancestors up to the adapter), and — if the object is a container (channel/device/folder/enum/instance/adapter/meta) — the list of direct children with their types, names, roles and units. Use this to navigate the object tree: start from a channel found by search_datapoints, read its children to see the actual state IDs underneath.",parameters:{type:"object",properties:{id:{type:"string",description:'The full object ID, e.g. "zigbee2mqtt.0.0x1234.state", "alias.0.Room.MotionSensor", or "enum.rooms.kitchen".'}},required:["id"]}}},{type:"function",function:{name:"search_scripts",description:"Search through all ioBroker JavaScript/Blockly/Rules scripts. Can search by script name/path OR by content (e.g. find all scripts that use a specific datapoint ID). Returns matching script names, paths, and matching lines.",parameters:{type:"object",properties:{query:{type:"string",description:'Search term - matches against script name, path, AND source code content. Examples: "carport", "zigbee2mqtt.0.lamp.state", "telegram"'},max_results:{type:"number",description:"Maximum number of scripts to return (default: 10)"}},required:["query"]}}},{type:"function",function:{name:"read_script",description:"Read the full source code of a specific ioBroker script by its ID or path. Use search_scripts first to find the script ID, then read_script to see its complete code.",parameters:{type:"object",properties:{id:{type:"string",description:'The script ID (e.g. "script.js.common.Licht.Carport") or path (e.g. "common/Licht/Carport")'}},required:["id"]}}},{type:"function",function:{name:"list_scripts",description:"List ALL available ioBroker scripts with their names, paths, types (JavaScript/Blockly/TypeScript), and enabled status. Use this to get an overview of all scripts before searching or reading specific ones.",parameters:{type:"object",properties:{}}}},{type:"function",function:{name:"get_editor_selection",description:'Read what the user has currently selected in the script editor. Returns the selected text and its line/column range, or a message if nothing is selected. Use this when the user refers to "this", "das hier", "the selection", or asks about a specific piece of code they highlighted.',parameters:{type:"object",properties:{}}}},{type:"function",function:{name:"get_editor_content",description:"Read the full current content of the script editor (may differ from the initial script version if the user has made edits). Use this when you need the live editor state rather than the saved script.",parameters:{type:"object",properties:{}}}},{type:"function",function:{name:"get_cursor_position",description:"Read the current cursor position (line and column, 1-based) in the script editor.",parameters:{type:"object",properties:{}}}},{type:"function",function:{name:"highlight_text_in_editor",description:"Search for a literal text in the script editor and select + scroll to it. Returns how many occurrences were found. Use this to draw the user's attention to a specific snippet you are discussing.",parameters:{type:"object",properties:{text:{type:"string",description:"Exact substring to search for (case-sensitive)."}},required:["text"]}}},{type:"function",function:{name:"highlight_line_range",description:"Select and scroll to a range of lines in the editor. Both line numbers are 1-based and inclusive. Use this to show the user which block of code you are referring to.",parameters:{type:"object",properties:{start_line:{type:"number",description:"First line (1-based, inclusive)."},end_line:{type:"number",description:"Last line (1-based, inclusive)."}},required:["start_line","end_line"]}}},{type:"function",function:{name:"go_to_line",description:"Move the cursor to a specific line (and optional column) and scroll that line into view. Use this to navigate the user to a relevant spot.",parameters:{type:"object",properties:{line:{type:"number",description:"1-based line number."},column:{type:"number",description:"1-based column (optional, default 1)."}},required:["line"]}}},{type:"function",function:{name:"insert_text_at_cursor",description:"Insert text at the current cursor position in the editor (or replace the current selection if one exists). Use sparingly — prefer returning code in a fenced markdown block so the user can review and smart-apply it. Only use direct insertion when the user explicitly asked you to write something into the editor.",parameters:{type:"object",properties:{text:{type:"string",description:"Text to insert."}},required:["text"]}}},{type:"function",function:{name:"replace_selection",description:"Replace the currently selected text in the editor with new text. Fails if nothing is selected. Use this to refactor or rewrite a specific highlighted snippet.",parameters:{type:"object",properties:{text:{type:"string",description:"Replacement text."}},required:["text"]}}},{type:"function",function:{name:"get_diagnostics",description:"Read all active Monaco diagnostics (errors, warnings, info, hints) from the current editor model — this is what shows up as red/yellow squiggles. Use this to find syntax errors, unused variables, missing types, or other editor-reported issues the user might be asking about.",parameters:{type:"object",properties:{}}}},{type:"function",function:{name:"get_document_symbols",description:"Get the document outline of the current script: all top-level functions, classes, constants, and variables with their line numbers. Use this to understand the structure of a long script or to find where a specific function is defined.",parameters:{type:"object",properties:{}}}}];function Je(r){return r&&typeof r=="object"?r.en||r.de||"":r||""}function Wt(r,e,n){const t=(n||"").toLowerCase();if(!t)return!1;if(r.toLowerCase().includes(t))return!0;const o=e==null?void 0:e.common;if(!o)return!1;const s=Je(o.name).toLowerCase();if(s&&s.includes(t))return!0;const d=(o.role||"").toLowerCase();return!!(d&&d.includes(t))}async function Ht(r,e,n=20,t){const o=await nt(r),s=t==null?void 0:t.toLowerCase(),d=[],m=Object.keys(o),c=new Set;for(const p of m){const g=p.lastIndexOf(".");g>0&&c.add(p.substring(0,g))}for(const p of m){const g=o[p],a=g==null?void 0:g.type;if(!a||s&&a!==s||!Wt(p,g,e))continue;const y=g.common,l={id:p,type:a,name:Je(y==null?void 0:y.name)};if(y!=null&&y.role&&(l.role=y.role),a==="state"?(l.stateType=(y==null?void 0:y.type)||"",y!=null&&y.unit&&(l.unit=y.unit)):c.has(p)&&(l.hasChildren=!0),d.push(l),d.length>=n)break}return d.length===0?JSON.stringify({message:`No objects found matching "${e}". Hint: try a role like "sensor.motion" or a partial path.`}):JSON.stringify(d)}async function Ft(r,e){try{const n=await r.getState(e);return JSON.stringify(n?{val:n.val,ts:n.ts?new Date(n.ts).toISOString():null,ack:n.ack,from:n.from}:{error:`State '${e}' not found`})}catch{return JSON.stringify({error:`Failed to read state '${e}'`})}}const Vt=new Set(["channel","device","folder","adapter","instance","enum","meta"]),Ke=50;async function qt(r,e){var n;try{const t=await r.getObject(e);if(!t)return JSON.stringify({error:`Object '${e}' not found`});const o={id:t._id,type:t.type,common:t.common},s=e.split("."),d=[];for(let m=s.length-1;m>=2;m--){const c=s.slice(0,m).join(".");try{const p=await r.getObject(c);p&&p.type!=="state"&&d.push({id:p._id,type:p.type,name:Je((n=p.common)==null?void 0:n.name),common:p.common})}catch{}}if(d.length>0&&(o.parents=d),Vt.has(t.type)){const m=await nt(r),c=[],p=`${e}.`;let g=!1;for(const a of Object.keys(m))if(a.startsWith(p)&&!a.substring(p.length).includes(".")){const y=m[a],l=y==null?void 0:y.common,S={id:a,name:Je(l==null?void 0:l.name),type:(y==null?void 0:y.type)||""};if(l!=null&&l.role&&(S.role=l.role),(y==null?void 0:y.type)==="state"&&(l!=null&&l.unit)&&(S.unit=l.unit),c.push(S),c.length>=Ke){g=!0;break}}c.length>0&&(o.children=c,g&&(o.childrenTruncated=!0,o.childrenHint=`Only the first ${Ke} children are shown. Use search_datapoints with a more specific query or the object_type filter to narrow down.`))}return JSON.stringify(o)}catch{return JSON.stringify({error:`Failed to read object '${e}'`})}}function st(r){return vt(r)||r}function Yt(r,e,n=10){const t=e.toLowerCase(),o=[];for(const s of r){const d=s.id.toLowerCase(),m=s.name.toLowerCase(),c=s.id.replace(/^script\.js\./,"").replace(/\./g,"/"),p=s.engineType==="Blockly"||s.engineType==="Rules",g=d.includes(t)||m.includes(t),a=p?st(s.source):s.source,y=a.toLowerCase().includes(t);if(g||y){const l={id:s.id,path:c,name:s.name,type:p?"Blockly":s.engineType.includes("TypeScript")?"TypeScript":"JavaScript",enabled:s.enabled};if(y){const S=a.split(`
217
- `),b=[];for(let v=0;v<S.length&&!(S[v].toLowerCase().includes(t)&&(b.push({line:v+1,text:S[v].trim()}),b.length>=5));v++);b.length>0&&(l.matchingLines=b)}if(o.push(l),o.length>=n)break}}return o.length===0?JSON.stringify({message:`No scripts found matching "${e}"`}):JSON.stringify(o)}function Gt(r,e){const n=e.replace(/\//g,".").toLowerCase(),t=r.find(m=>{const c=m.id.toLowerCase();return c===n||c===`script.js.${n}`||c.endsWith(`.${n}`)});if(!t)return JSON.stringify({error:`Script '${e}' not found. Use search_scripts to find available scripts.`});const o=t.engineType==="Blockly"||t.engineType==="Rules",s=o?st(t.source):t.source,d=t.id.replace(/^script\.js\./,"").replace(/\./g,"/");return JSON.stringify({id:t.id,path:d,name:t.name,type:o?"Blockly":t.engineType.includes("TypeScript")?"TypeScript":"JavaScript",enabled:t.enabled,source:s})}function Xt(r){const e=r.map(n=>({id:n.id,path:n.id.replace(/^script\.js\./,"").replace(/\./g,"/"),name:n.name,type:n.engineType==="Blockly"||n.engineType==="Rules"?"Blockly":n.engineType.includes("TypeScript")?"TypeScript":"JavaScript",enabled:n.enabled}));return JSON.stringify(e)}function he(){return JSON.stringify({error:"Editor is not available. This tool requires the script editor to be open."})}async function Kt(r,e,n,t){let o;try{o=JSON.parse(e.function.arguments)}catch{return JSON.stringify({error:`Invalid arguments: ${e.function.arguments}`})}switch(e.function.name){case"search_datapoints":return Ht(r,o.query,o.max_results||20,o.object_type);case"get_state_value":return Ft(r,o.id);case"get_object_info":return qt(r,o.id);case"search_scripts":return Yt(n||[],o.query,o.max_results||10);case"read_script":return Gt(n||[],o.id);case"list_scripts":return Xt(n||[]);case"get_editor_selection":{if(!(t!=null&&t.getSelection))return he();const s=t.getSelection();return JSON.stringify(s||{message:"No text is currently selected in the editor."})}case"get_editor_content":return t!=null&&t.getContent?JSON.stringify({content:t.getContent()}):he();case"get_cursor_position":{if(!(t!=null&&t.getCursorPosition))return he();const s=t.getCursorPosition();return JSON.stringify(s||{message:"Editor has no cursor position (not focused)."})}case"highlight_text_in_editor":{if(!(t!=null&&t.highlightText))return he();const s=t.highlightText(o.text);return JSON.stringify({matches:s,message:s===0?`Text "${o.text}" was not found in the editor.`:`Highlighted ${s} occurrence(s) of "${o.text}".`})}case"highlight_line_range":{if(!(t!=null&&t.highlightLineRange))return he();const s=t.highlightLineRange(o.start_line,o.end_line);return JSON.stringify({success:s,message:s?`Selected lines ${o.start_line}-${o.end_line}.`:"Could not select the requested line range."})}case"go_to_line":{if(!(t!=null&&t.goToLine))return he();const s=t.goToLine(o.line,o.column);return JSON.stringify({success:s,message:s?`Cursor moved to line ${o.line}.`:"Could not move the cursor."})}case"insert_text_at_cursor":{if(!(t!=null&&t.insertTextAtCursor))return he();const s=t.insertTextAtCursor(o.text);return JSON.stringify({success:s,message:s?"Text inserted at cursor.":"Editor rejected the insertion."})}case"replace_selection":{if(!(t!=null&&t.replaceSelection))return he();const s=t.replaceSelection(o.text);return JSON.stringify({success:s,message:s?"Selection replaced.":"No text was selected to replace."})}case"get_diagnostics":{if(!(t!=null&&t.getDiagnostics))return he();const s=t.getDiagnostics();return JSON.stringify({count:s.length,diagnostics:s})}case"get_document_symbols":{if(!(t!=null&&t.getSymbols))return he();const s=await t.getSymbols();return JSON.stringify({count:s.length,symbols:s})}default:return JSON.stringify({error:`Unknown tool: ${e.function.name}`})}}let Qt=0;function Ne(){return`msg_${Date.now()}_${++Qt}`}function Zt(r){const{socket:e,runningInstances:n,currentCode:t,currentLanguage:o,allScripts:s,editorApi:d,currentScriptId:m}=r,c=U((f,O,R)=>f==="none"||!R?null:{range:O,scriptId:m||"",scriptVersion:(t||"").length,kind:f,originalText:R},[m,t]),[p,g]=te(()=>{try{const f=window.localStorage.getItem("Editor.aiChatMessages");return f?JSON.parse(f):[]}catch{return[]}}),a=U(f=>{g(O=>{const R=typeof f=="function"?f(O):f,L=R.length>100?R.slice(-100):R;try{window.localStorage.setItem("Editor.aiChatMessages",JSON.stringify(L))}catch{try{const W=L.slice(-20);window.localStorage.setItem("Editor.aiChatMessages",JSON.stringify(W))}catch{}}return L})},[]),[y,l]=te(!1),[S,b]=te(null),[v,F]=te(window.localStorage.getItem("Editor.aiChatMode")||"agent"),E=U(f=>{F(f),window.localStorage.setItem("Editor.aiChatMode",f)},[]),[I,x]=te(null),[w,M]=te(window.localStorage.getItem("openai-model")||""),[re,Y]=te([]),[_,G]=te({}),[le,K]=te(!0),[de,T]=te(null),A=ne(null),X=ne(null),Q=ne(null),h=ne(null),C=U(f=>{M(f),window.localStorage.setItem("openai-model",f)},[]),k=U(async()=>{K(!0),T(null);try{const f=await Pt(e,n);if(Y(f.models),G(f.providerMap),f.models.length>0){const O=window.localStorage.getItem("openai-model");O&&f.models.includes(O)?M(O):M(f.models[0])}f.errors.length>0&&T(f.errors.join("; "))}catch(f){T(String(f))}K(!1)},[e,n]);xe(()=>{k()},[k]);const z=U(f=>{let O=!1,R=!1;const L=[];let W=!1;const ge=/@([\w/äöüÄÖÜß-]+)/g;let D;for(;(D=ge.exec(f))!==null;){const B=D[1].toLowerCase();if(B==="alle"||B==="all")O=!0;else if(B==="geräte"||B==="devices"||B==="geraete")R=!0;else if(W=!0,s&&s.length>0){const V=D[1].replace(/\//g,".").toLowerCase(),oe=V.split("."),ie=s.find(ye=>{const me=ye.id.toLowerCase(),Z=me.replace(/^script\.js\./,"");if(Z===V||Z.endsWith(`.${V}`)||me===`script.js.${V}`)return!0;let _e=0;for(const pe of oe){const Ce=Z.indexOf(pe,_e);if(Ce===-1)return!1;_e=Ce+pe.length}return!0});if(ie)L.push(ie.id);else for(const ye of oe){if(ye.length<3)continue;const me=s.filter(Z=>Z.id.toLowerCase().includes(`.${ye}`)||Z.name.toLowerCase().includes(ye));for(const Z of me)L.includes(Z.id)||L.push(Z.id)}}}return W&&L.length===0&&(O=!0),{cleanMessage:f.replace(/@[\w/äöüÄÖÜß]+\s*/g,"").trim(),mentionedScriptIds:L,includeAll:O,includeDevices:R}},[s]),se=U(async(f,O,R)=>{h.current||(h.current=await Ut()),A.current||(A.current=await De(e,n));const L=Ge(),W=o==="blockly",ge=f||R.length>0;let D=`You are an AI assistant for ioBroker JavaScript adapter scripting. Help the user write, debug, and understand ioBroker scripts. Write comments in ${L}. Use the ioBroker JavaScript API correctly.
216
+ Write comments in ${r}. Put blocks in a \`\`\`xml code block.`}function Pe(r){let e=r;return e=e.replace(/<think>[\s\S]*?<\/think>/gi,""),e=e.replace(/<\|endoftext\|>/g,""),e=e.replace(/<\|im_start\|>[\s\S]*?<\|im_end\|>/g,""),e=e.replace(/<\|im_start\|>[\s\S]*/g,""),e.trim()}const Jt=[{type:"function",function:{name:"search_datapoints",description:'Search ALL ioBroker objects by ID, name, or role — includes states, channels, devices, folders, enums (rooms/functions), adapters, instances, scripts, meta, etc. Returns matching IDs with object type, name, role, unit, and a hasChildren hint for containers. IMPORTANT: Aliases and physical device groupings are usually CHANNELS containing multiple state children (e.g. a motion sensor is often a channel alias.0.Floor.Room.MotionSensor with states ACTUAL, BATTERY, STATE under it). If a channel/device/folder matches your query, call get_object_info on its ID to list its state children. Role-based queries work too: "sensor.motion", "switch.light", "value.temperature".',parameters:{type:"object",properties:{query:{type:"string",description:'Search pattern (case-insensitive substring) - matches against object ID, name, and role. Examples: "bewegungsmelder", "temperature", "sensor.motion", "alias.0", "küche", "zigbee2mqtt.0.lamp".'},max_results:{type:"number",description:"Maximum number of results to return (default: 20)."},object_type:{type:"string",description:'Optional filter by object type: "state", "channel", "device", "folder", "enum", "adapter", "instance", "script", "meta", etc. Omit to search every type.'}},required:["query"]}}},{type:"function",function:{name:"get_state_value",description:"Get the current value of an ioBroker state/datapoint. Returns value, timestamp, and acknowledgment flag.",parameters:{type:"object",properties:{id:{type:"string",description:'The full state ID, e.g. "zigbee2mqtt.0.sensor.temperature"'}},required:["id"]}}},{type:"function",function:{name:"get_object_info",description:"Get detailed info about ANY ioBroker object + its full parent hierarchy + direct children. Works for every object type: state, channel, device, folder, adapter, instance, enum, meta, script. Returns: the object itself, parent chain (all non-state ancestors up to the adapter), and — if the object is a container (channel/device/folder/enum/instance/adapter/meta) — the list of direct children with their types, names, roles and units. Use this to navigate the object tree: start from a channel found by search_datapoints, read its children to see the actual state IDs underneath.",parameters:{type:"object",properties:{id:{type:"string",description:'The full object ID, e.g. "zigbee2mqtt.0.0x1234.state", "alias.0.Room.MotionSensor", or "enum.rooms.kitchen".'}},required:["id"]}}},{type:"function",function:{name:"search_scripts",description:"Search through all ioBroker JavaScript/Blockly/Rules scripts. Can search by script name/path OR by content (e.g. find all scripts that use a specific datapoint ID). Returns matching script names, paths, and matching lines.",parameters:{type:"object",properties:{query:{type:"string",description:'Search term - matches against script name, path, AND source code content. Examples: "carport", "zigbee2mqtt.0.lamp.state", "telegram"'},max_results:{type:"number",description:"Maximum number of scripts to return (default: 10)"}},required:["query"]}}},{type:"function",function:{name:"read_script",description:"Read the full source code of a specific ioBroker script by its ID or path. Use search_scripts first to find the script ID, then read_script to see its complete code.",parameters:{type:"object",properties:{id:{type:"string",description:'The script ID (e.g. "script.js.common.Licht.Carport") or path (e.g. "common/Licht/Carport")'}},required:["id"]}}},{type:"function",function:{name:"list_scripts",description:"List ALL available ioBroker scripts with their names, paths, types (JavaScript/Blockly/TypeScript), and enabled status. Use this to get an overview of all scripts before searching or reading specific ones.",parameters:{type:"object",properties:{}}}},{type:"function",function:{name:"get_editor_selection",description:'Read what the user has currently selected in the script editor. Returns the selected text and its line/column range, or a message if nothing is selected. Use this when the user refers to "this", "das hier", "the selection", or asks about a specific piece of code they highlighted.',parameters:{type:"object",properties:{}}}},{type:"function",function:{name:"get_editor_content",description:"Read the full current content of the script editor (may differ from the initial script version if the user has made edits). Use this when you need the live editor state rather than the saved script.",parameters:{type:"object",properties:{}}}},{type:"function",function:{name:"get_cursor_position",description:"Read the current cursor position (line and column, 1-based) in the script editor.",parameters:{type:"object",properties:{}}}},{type:"function",function:{name:"highlight_text_in_editor",description:"Search for a literal text in the script editor and select + scroll to it. Returns how many occurrences were found. Use this to draw the user's attention to a specific snippet you are discussing.",parameters:{type:"object",properties:{text:{type:"string",description:"Exact substring to search for (case-sensitive)."}},required:["text"]}}},{type:"function",function:{name:"highlight_line_range",description:"Select and scroll to a range of lines in the editor. Both line numbers are 1-based and inclusive. Use this to show the user which block of code you are referring to.",parameters:{type:"object",properties:{start_line:{type:"number",description:"First line (1-based, inclusive)."},end_line:{type:"number",description:"Last line (1-based, inclusive)."}},required:["start_line","end_line"]}}},{type:"function",function:{name:"go_to_line",description:"Move the cursor to a specific line (and optional column) and scroll that line into view. Use this to navigate the user to a relevant spot.",parameters:{type:"object",properties:{line:{type:"number",description:"1-based line number."},column:{type:"number",description:"1-based column (optional, default 1)."}},required:["line"]}}},{type:"function",function:{name:"insert_text_at_cursor",description:"Insert text at the current cursor position in the editor (or replace the current selection if one exists). Use sparingly — prefer returning code in a fenced markdown block so the user can review and smart-apply it. Only use direct insertion when the user explicitly asked you to write something into the editor.",parameters:{type:"object",properties:{text:{type:"string",description:"Text to insert."}},required:["text"]}}},{type:"function",function:{name:"replace_selection",description:"Replace the currently selected text in the editor with new text. Fails if nothing is selected. Use this to refactor or rewrite a specific highlighted snippet.",parameters:{type:"object",properties:{text:{type:"string",description:"Replacement text."}},required:["text"]}}},{type:"function",function:{name:"get_diagnostics",description:"Read all active Monaco diagnostics (errors, warnings, info, hints) from the current editor model — this is what shows up as red/yellow squiggles. Use this to find syntax errors, unused variables, missing types, or other editor-reported issues the user might be asking about.",parameters:{type:"object",properties:{}}}},{type:"function",function:{name:"get_document_symbols",description:"Get the document outline of the current script: all top-level functions, classes, constants, and variables with their line numbers. Use this to understand the structure of a long script or to find where a specific function is defined.",parameters:{type:"object",properties:{}}}}];function Je(r){return r&&typeof r=="object"?r.en||r.de||"":r||""}function Wt(r,e,n){const t=(n||"").toLowerCase();if(!t)return!1;if(r.toLowerCase().includes(t))return!0;const o=e==null?void 0:e.common;if(!o)return!1;const s=Je(o.name).toLowerCase();if(s&&s.includes(t))return!0;const d=(o.role||"").toLowerCase();return!!(d&&d.includes(t))}async function Ft(r,e,n=20,t){const o=await nt(r),s=t==null?void 0:t.toLowerCase(),d=[],m=Object.keys(o),c=new Set;for(const p of m){const g=p.lastIndexOf(".");g>0&&c.add(p.substring(0,g))}for(const p of m){const g=o[p],a=g==null?void 0:g.type;if(!a||s&&a!==s||!Wt(p,g,e))continue;const y=g.common,l={id:p,type:a,name:Je(y==null?void 0:y.name)};if(y!=null&&y.role&&(l.role=y.role),a==="state"?(l.stateType=(y==null?void 0:y.type)||"",y!=null&&y.unit&&(l.unit=y.unit)):c.has(p)&&(l.hasChildren=!0),d.push(l),d.length>=n)break}return d.length===0?JSON.stringify({message:`No objects found matching "${e}". Hint: try a role like "sensor.motion" or a partial path.`}):JSON.stringify(d)}async function Ht(r,e){try{const n=await r.getState(e);return JSON.stringify(n?{val:n.val,ts:n.ts?new Date(n.ts).toISOString():null,ack:n.ack,from:n.from}:{error:`State '${e}' not found`})}catch{return JSON.stringify({error:`Failed to read state '${e}'`})}}const Vt=new Set(["channel","device","folder","adapter","instance","enum","meta"]),Ke=50;async function qt(r,e){var n;try{const t=await r.getObject(e);if(!t)return JSON.stringify({error:`Object '${e}' not found`});const o={id:t._id,type:t.type,common:t.common},s=e.split("."),d=[];for(let m=s.length-1;m>=2;m--){const c=s.slice(0,m).join(".");try{const p=await r.getObject(c);p&&p.type!=="state"&&d.push({id:p._id,type:p.type,name:Je((n=p.common)==null?void 0:n.name),common:p.common})}catch{}}if(d.length>0&&(o.parents=d),Vt.has(t.type)){const m=await nt(r),c=[],p=`${e}.`;let g=!1;for(const a of Object.keys(m))if(a.startsWith(p)&&!a.substring(p.length).includes(".")){const y=m[a],l=y==null?void 0:y.common,S={id:a,name:Je(l==null?void 0:l.name),type:(y==null?void 0:y.type)||""};if(l!=null&&l.role&&(S.role=l.role),(y==null?void 0:y.type)==="state"&&(l!=null&&l.unit)&&(S.unit=l.unit),c.push(S),c.length>=Ke){g=!0;break}}c.length>0&&(o.children=c,g&&(o.childrenTruncated=!0,o.childrenHint=`Only the first ${Ke} children are shown. Use search_datapoints with a more specific query or the object_type filter to narrow down.`))}return JSON.stringify(o)}catch{return JSON.stringify({error:`Failed to read object '${e}'`})}}function st(r){return vt(r)||r}function Yt(r,e,n=10){const t=e.toLowerCase(),o=[];for(const s of r){const d=s.id.toLowerCase(),m=s.name.toLowerCase(),c=s.id.replace(/^script\.js\./,"").replace(/\./g,"/"),p=s.engineType==="Blockly"||s.engineType==="Rules",g=d.includes(t)||m.includes(t),a=p?st(s.source):s.source,y=a.toLowerCase().includes(t);if(g||y){const l={id:s.id,path:c,name:s.name,type:p?"Blockly":s.engineType.includes("TypeScript")?"TypeScript":"JavaScript",enabled:s.enabled};if(y){const S=a.split(`
217
+ `),b=[];for(let v=0;v<S.length&&!(S[v].toLowerCase().includes(t)&&(b.push({line:v+1,text:S[v].trim()}),b.length>=5));v++);b.length>0&&(l.matchingLines=b)}if(o.push(l),o.length>=n)break}}return o.length===0?JSON.stringify({message:`No scripts found matching "${e}"`}):JSON.stringify(o)}function Gt(r,e){const n=e.replace(/\//g,".").toLowerCase(),t=r.find(m=>{const c=m.id.toLowerCase();return c===n||c===`script.js.${n}`||c.endsWith(`.${n}`)});if(!t)return JSON.stringify({error:`Script '${e}' not found. Use search_scripts to find available scripts.`});const o=t.engineType==="Blockly"||t.engineType==="Rules",s=o?st(t.source):t.source,d=t.id.replace(/^script\.js\./,"").replace(/\./g,"/");return JSON.stringify({id:t.id,path:d,name:t.name,type:o?"Blockly":t.engineType.includes("TypeScript")?"TypeScript":"JavaScript",enabled:t.enabled,source:s})}function Xt(r){const e=r.map(n=>({id:n.id,path:n.id.replace(/^script\.js\./,"").replace(/\./g,"/"),name:n.name,type:n.engineType==="Blockly"||n.engineType==="Rules"?"Blockly":n.engineType.includes("TypeScript")?"TypeScript":"JavaScript",enabled:n.enabled}));return JSON.stringify(e)}function he(){return JSON.stringify({error:"Editor is not available. This tool requires the script editor to be open."})}async function Kt(r,e,n,t){let o;try{o=JSON.parse(e.function.arguments)}catch{return JSON.stringify({error:`Invalid arguments: ${e.function.arguments}`})}switch(e.function.name){case"search_datapoints":return Ft(r,o.query,o.max_results||20,o.object_type);case"get_state_value":return Ht(r,o.id);case"get_object_info":return qt(r,o.id);case"search_scripts":return Yt(n||[],o.query,o.max_results||10);case"read_script":return Gt(n||[],o.id);case"list_scripts":return Xt(n||[]);case"get_editor_selection":{if(!(t!=null&&t.getSelection))return he();const s=t.getSelection();return JSON.stringify(s||{message:"No text is currently selected in the editor."})}case"get_editor_content":return t!=null&&t.getContent?JSON.stringify({content:t.getContent()}):he();case"get_cursor_position":{if(!(t!=null&&t.getCursorPosition))return he();const s=t.getCursorPosition();return JSON.stringify(s||{message:"Editor has no cursor position (not focused)."})}case"highlight_text_in_editor":{if(!(t!=null&&t.highlightText))return he();const s=t.highlightText(o.text);return JSON.stringify({matches:s,message:s===0?`Text "${o.text}" was not found in the editor.`:`Highlighted ${s} occurrence(s) of "${o.text}".`})}case"highlight_line_range":{if(!(t!=null&&t.highlightLineRange))return he();const s=t.highlightLineRange(o.start_line,o.end_line);return JSON.stringify({success:s,message:s?`Selected lines ${o.start_line}-${o.end_line}.`:"Could not select the requested line range."})}case"go_to_line":{if(!(t!=null&&t.goToLine))return he();const s=t.goToLine(o.line,o.column);return JSON.stringify({success:s,message:s?`Cursor moved to line ${o.line}.`:"Could not move the cursor."})}case"insert_text_at_cursor":{if(!(t!=null&&t.insertTextAtCursor))return he();const s=t.insertTextAtCursor(o.text);return JSON.stringify({success:s,message:s?"Text inserted at cursor.":"Editor rejected the insertion."})}case"replace_selection":{if(!(t!=null&&t.replaceSelection))return he();const s=t.replaceSelection(o.text);return JSON.stringify({success:s,message:s?"Selection replaced.":"No text was selected to replace."})}case"get_diagnostics":{if(!(t!=null&&t.getDiagnostics))return he();const s=t.getDiagnostics();return JSON.stringify({count:s.length,diagnostics:s})}case"get_document_symbols":{if(!(t!=null&&t.getSymbols))return he();const s=await t.getSymbols();return JSON.stringify({count:s.length,symbols:s})}default:return JSON.stringify({error:`Unknown tool: ${e.function.name}`})}}let Qt=0;function Ne(){return`msg_${Date.now()}_${++Qt}`}function Zt(r){const{socket:e,runningInstances:n,currentCode:t,currentLanguage:o,allScripts:s,editorApi:d,currentScriptId:m}=r,c=A((f,O,R)=>f==="none"||!R?null:{range:O,scriptId:m||"",scriptVersion:(t||"").length,kind:f,originalText:R},[m,t]),[p,g]=te(()=>{try{const f=window.localStorage.getItem("Editor.aiChatMessages");return f?JSON.parse(f):[]}catch{return[]}}),a=A(f=>{g(O=>{const R=typeof f=="function"?f(O):f,L=R.length>100?R.slice(-100):R;try{window.localStorage.setItem("Editor.aiChatMessages",JSON.stringify(L))}catch{try{const W=L.slice(-20);window.localStorage.setItem("Editor.aiChatMessages",JSON.stringify(W))}catch{}}return L})},[]),[y,l]=te(!1),[S,b]=te(null),[v,H]=te(window.localStorage.getItem("Editor.aiChatMode")||"agent"),E=A(f=>{H(f),window.localStorage.setItem("Editor.aiChatMode",f)},[]),[I,x]=te(null),[w,M]=te(window.localStorage.getItem("openai-model")||""),[re,Y]=te([]),[_,G]=te({}),[le,K]=te(!0),[de,T]=te(null),U=ne(null),X=ne(null),Q=ne(null),h=ne(null),C=A(f=>{M(f),window.localStorage.setItem("openai-model",f)},[]),k=A(async()=>{K(!0),T(null);try{const f=await Pt(e,n);if(Y(f.models),G(f.providerMap),f.models.length>0){const O=window.localStorage.getItem("openai-model");O&&f.models.includes(O)?M(O):M(f.models[0])}f.errors.length>0&&T(f.errors.join("; "))}catch(f){T(String(f))}K(!1)},[e,n]);xe(()=>{k()},[k]);const z=A(f=>{let O=!1,R=!1;const L=[];let W=!1;const ge=/@([\w/äöüÄÖÜß-]+)/g;let D;for(;(D=ge.exec(f))!==null;){const B=D[1].toLowerCase();if(B==="alle"||B==="all")O=!0;else if(B==="geräte"||B==="devices"||B==="geraete")R=!0;else if(W=!0,s&&s.length>0){const V=D[1].replace(/\//g,".").toLowerCase(),oe=V.split("."),ie=s.find(ye=>{const me=ye.id.toLowerCase(),Z=me.replace(/^script\.js\./,"");if(Z===V||Z.endsWith(`.${V}`)||me===`script.js.${V}`)return!0;let _e=0;for(const pe of oe){const Ce=Z.indexOf(pe,_e);if(Ce===-1)return!1;_e=Ce+pe.length}return!0});if(ie)L.push(ie.id);else for(const ye of oe){if(ye.length<3)continue;const me=s.filter(Z=>Z.id.toLowerCase().includes(`.${ye}`)||Z.name.toLowerCase().includes(ye));for(const Z of me)L.includes(Z.id)||L.push(Z.id)}}}return W&&L.length===0&&(O=!0),{cleanMessage:f.replace(/@[\w/äöüÄÖÜß]+\s*/g,"").trim(),mentionedScriptIds:L,includeAll:O,includeDevices:R}},[s]),se=A(async(f,O,R)=>{h.current||(h.current=await At()),U.current||(U.current=await De(e,n));const L=Ge(),W=o==="blockly",ge=f||R.length>0;let D=`You are an AI assistant for ioBroker JavaScript adapter scripting. Help the user write, debug, and understand ioBroker scripts. Write comments in ${L}. Use the ioBroker JavaScript API correctly.
218
218
 
219
219
  ioBroker object hierarchy: adapter.instance.device.channel.state
220
220
  - A "state" is a single datapoint (e.g. zigbee2mqtt.0.0x1234.temperature)
@@ -227,7 +227,7 @@ Available API and syntax rules:
227
227
  ${h.current}`;if(W&&(D+="\n\nThe user is working in the Blockly visual editor. When asked to create or modify code, respond with Blockly XML in a ```xml code block instead of JavaScript."),(O||f)&&(Q.current||(Q.current=await Ye(e)),D+=`
228
228
 
229
229
  Available smart home devices:
230
- ${JSON.stringify(Q.current,null,0)}`),!ge&&t)if(W){const H="%%BLOCKLY_XML%%",B=t.indexOf(H),V=B!==-1?t.substring(0,B).trim():t,oe=B!==-1?t.substring(B+H.length).trim():"";D+=`
230
+ ${JSON.stringify(Q.current,null,0)}`),!ge&&t)if(W){const F="%%BLOCKLY_XML%%",B=t.indexOf(F),V=B!==-1?t.substring(0,B).trim():t,oe=B!==-1?t.substring(B+F.length).trim():"";D+=`
231
231
 
232
232
  The user is working on this Blockly script (currently open in the editor).
233
233
 
@@ -248,13 +248,13 @@ ${t}
248
248
 
249
249
  The user requested ALL scripts. Search through all of them to answer the question. Always identify WHICH script you describe by its full ID. Scripts may reference datapoint IDs via variables.
250
250
 
251
- ${qe(s,!0)}`;else if(R.length>0&&s){const H=s.filter(B=>R.includes(B.id));H.length>0&&(D+=`
251
+ ${qe(s,!0)}`;else if(R.length>0&&s){const F=s.filter(B=>R.includes(B.id));F.length>0&&(D+=`
252
252
 
253
253
  IMPORTANT: The user is asking about the following script(s). Answer ONLY about these scripts, NOT about the currently open editor tab. Analyze the source code below carefully:
254
254
 
255
- ${qe(H,!0)}`)}return W&&(D+=`
255
+ ${qe(F,!0)}`)}return W&&(D+=`
256
256
 
257
- ${Xe(L)}`),[{role:"system",content:D}]},[e,n,t,o,s]),ke=U(async f=>{if(!f.trim()||y)return;const O=_[w];if(!O){x(u.I18n.t("Please select a valid model"));return}const R=A.current||await De(e,n);if(A.current=R,!R){x(u.I18n.t("No API keys configured"));return}const L=Object.keys(n)[0];if(!L){x(u.I18n.t("No running javascript instance found"));return}const W=O==="custom"&&R.gptBaseUrl||"",ge={id:Ne(),role:"user",content:f,timestamp:Date.now()},D={id:Ne(),role:"assistant",content:`⏳ ${u.I18n.t("Generating plan...")}`,timestamp:Date.now()};a(H=>[...H,ge,D]),l(!0),x(null);try{const H=Ge();Q.current||(Q.current=await Ye(e));const B=Q.current||[],V=`Devices in my smart home:
257
+ ${Xe(L)}`),[{role:"system",content:D}]},[e,n,t,o,s]),ke=A(async f=>{if(!f.trim()||y)return;const O=_[w];if(!O){x(u.I18n.t("Please select a valid model"));return}const R=U.current||await De(e,n);if(U.current=R,!R){x(u.I18n.t("No API keys configured"));return}const L=Object.keys(n)[0];if(!L){x(u.I18n.t("No running javascript instance found"));return}const W=O==="custom"&&R.gptBaseUrl||"",ge={id:Ne(),role:"user",content:f,timestamp:Date.now()},D={id:Ne(),role:"assistant",content:`⏳ ${u.I18n.t("Generating plan...")}`,timestamp:Date.now()};a(F=>[...F,ge,D]),l(!0),x(null);try{const F=Ge();Q.current||(Q.current=await Ye(e));const B=Q.current||[],V=`Devices in my smart home:
258
258
  ${JSON.stringify(B)}
259
259
 
260
260
  I need a plan for this task: ${f}
@@ -272,12 +272,12 @@ ${ie}`}),j});const ye={id:Ne(),role:"assistant",content:`⏳ ${u.I18n.t("Generat
272
272
  PLAN:
273
273
  ${ie}
274
274
 
275
- Generate Blockly XML blocks for this ioBroker automation. Use the exact state IDs from the plan. If the plan contains TODO_DEVICE_ID, keep it as a placeholder. Write comments in ${H}. Put the blocks in a \`\`\`xml code block. You may add a short explanation before or after the XML.`:`TASK: ${f}
275
+ Generate Blockly XML blocks for this ioBroker automation. Use the exact state IDs from the plan. If the plan contains TODO_DEVICE_ID, keep it as a placeholder. Write comments in ${F}. Put the blocks in a \`\`\`xml code block. You may add a short explanation before or after the XML.`:`TASK: ${f}
276
276
 
277
277
  PLAN:
278
278
  ${ie}
279
279
 
280
- Write the ioBroker script. Use the exact state IDs from the plan. If the plan contains TODO_DEVICE_ID, keep it as a placeholder with a comment so the user can fill in the correct ID. Write comments in ${H}. Put the code in a \`\`\`javascript code block. You may add a short explanation before or after the code.`,_e=me?Xe(H):At(H),pe=await Re(e,L,{messages:[{role:"system",content:_e},{role:"user",content:Z}],model:w,provider:O,baseUrl:W});if(pe.error){x(pe.error),a(ae=>ae.slice(0,-1)),l(!1);return}const Ce=Pe(pe.content||"");a(ae=>{const j=[...ae],P=j[j.length-1];return(P==null?void 0:P.role)==="assistant"&&(j[j.length-1]={...P,content:Ce}),j}),b(`${u.I18n.t("devices")}: ${B.length}`)}catch(H){x(String(H)),a(B=>B.slice(0,-1))}l(!1)},[w,_,y,e,n,o,a]),J=U(async f=>{var ae;if(v==="code")return ke(f);if(!f.trim()||y)return;const O=_[w];if(!O){x(u.I18n.t("Please select a valid model"));return}const R=A.current||await De(e,n);if(A.current=R,!R){x(u.I18n.t("No API keys configured"));return}const L=Object.keys(n)[0];if(!L){x(u.I18n.t("No running javascript instance found"));return}let W=X.current;if(X.current=null,!W)try{const j=(ae=d==null?void 0:d.getSelection)==null?void 0:ae.call(d);j&&j.text&&(W=c("selection",j.range,j.text))}catch{}const ge={id:Ne(),role:"user",content:f,timestamp:Date.now(),sourceRange:W},D={id:Ne(),role:"assistant",content:"",timestamp:Date.now(),sourceRange:W};a(j=>[...j,ge,D]),l(!0),x(null);const{cleanMessage:H,mentionedScriptIds:B,includeAll:V,includeDevices:oe}=z(f),ie=[];if(V)ie.push(`${u.I18n.t("all scripts")} (${(s==null?void 0:s.length)||0})`);else if(B.length>0){const j=B.map(P=>P.replace(/^script\.js\./,""));ie.push(j.join(", "))}else ie.push(u.I18n.t("current script"));oe&&ie.push(u.I18n.t("devices")),b(`${u.I18n.t("Context")}: ${ie.join(" + ")}`);const ye=await se(V,oe,B),me=O==="custom"&&R.gptBaseUrl||"";let Z=H||f;if(s&&s.length>0){const j=Z.match(/\b[\w-]+\.\d+\.[\w.-]+/g);if(j){const P=[];for(const ee of new Set(j)){const be=wt(s,ee);be.length>0&&P.push(`Datapoint "${ee}" is used in:
280
+ Write the ioBroker script. Use the exact state IDs from the plan. If the plan contains TODO_DEVICE_ID, keep it as a placeholder with a comment so the user can fill in the correct ID. Write comments in ${F}. Put the code in a \`\`\`javascript code block. You may add a short explanation before or after the code.`,_e=me?Xe(F):Ut(F),pe=await Re(e,L,{messages:[{role:"system",content:_e},{role:"user",content:Z}],model:w,provider:O,baseUrl:W});if(pe.error){x(pe.error),a(ae=>ae.slice(0,-1)),l(!1);return}const Ce=Pe(pe.content||"");a(ae=>{const j=[...ae],P=j[j.length-1];return(P==null?void 0:P.role)==="assistant"&&(j[j.length-1]={...P,content:Ce}),j}),b(`${u.I18n.t("devices")}: ${B.length}`)}catch(F){x(String(F)),a(B=>B.slice(0,-1))}l(!1)},[w,_,y,e,n,o,a]),J=A(async f=>{var ae;if(v==="code")return ke(f);if(!f.trim()||y)return;const O=_[w];if(!O){x(u.I18n.t("Please select a valid model"));return}const R=U.current||await De(e,n);if(U.current=R,!R){x(u.I18n.t("No API keys configured"));return}const L=Object.keys(n)[0];if(!L){x(u.I18n.t("No running javascript instance found"));return}let W=X.current;if(X.current=null,!W)try{const j=(ae=d==null?void 0:d.getSelection)==null?void 0:ae.call(d);j&&j.text&&(W=c("selection",j.range,j.text))}catch{}const ge={id:Ne(),role:"user",content:f,timestamp:Date.now(),sourceRange:W},D={id:Ne(),role:"assistant",content:"",timestamp:Date.now(),sourceRange:W};a(j=>[...j,ge,D]),l(!0),x(null);const{cleanMessage:F,mentionedScriptIds:B,includeAll:V,includeDevices:oe}=z(f),ie=[];if(V)ie.push(`${u.I18n.t("all scripts")} (${(s==null?void 0:s.length)||0})`);else if(B.length>0){const j=B.map(P=>P.replace(/^script\.js\./,""));ie.push(j.join(", "))}else ie.push(u.I18n.t("current script"));oe&&ie.push(u.I18n.t("devices")),b(`${u.I18n.t("Context")}: ${ie.join(" + ")}`);const ye=await se(V,oe,B),me=O==="custom"&&R.gptBaseUrl||"";let Z=F||f;if(s&&s.length>0){const j=Z.match(/\b[\w-]+\.\d+\.[\w.-]+/g);if(j){const P=[];for(const ee of new Set(j)){const be=wt(s,ee);be.length>0&&P.push(`Datapoint "${ee}" is used in:
281
281
  ${be.map(je=>` - ${je.scriptName} (${je.scriptId}) line ${je.lineNumber}: ${je.usageType} → ${je.line}`).join(`
282
282
  `)}`)}P.length>0&&(Z+=`
283
283
 
@@ -285,7 +285,7 @@ ${be.map(je=>` - ${je.scriptName} (${je.scriptId}) line ${je.lineNumber}: ${je.
285
285
  ${P.join(`
286
286
 
287
287
  `)}`)}}const _e=[...ye,...p.filter(j=>j.role!=="system").map(j=>({role:j.role,content:j.content})),{role:"user",content:Z}],pe=v==="agent",Ce=5;try{const j=[..._e];for(let P=0;P<Ce;P++){const ee=await Re(e,L,{messages:j,model:w,provider:O,baseUrl:me,...pe?{tools:Jt}:{}});if(ee.error){if(pe&&P===0&&ee.error.toLowerCase().includes("tool")){const q=await Re(e,L,{messages:j,model:w,provider:O,baseUrl:me});if(q.error)x(q.error),a(N=>N.slice(0,-1));else{const N=Pe(q.content||"");a(ce=>{const fe=[...ce],Be=fe[fe.length-1];return(Be==null?void 0:Be.role)==="assistant"&&(fe[fe.length-1]={...Be,content:N}),fe})}break}x(ee.error),a(q=>q.slice(0,-1));break}let be=ee.tool_calls;if((!be||be.length===0)&&pe&&ee.content){const q=ee.content.trim();try{const N=JSON.parse(q);N.name&&N.arguments&&(be=[{id:`text_tool_${Date.now()}`,type:"function",function:{name:N.name,arguments:JSON.stringify(N.arguments)}}])}catch{}}if(!be||be.length===0){const q=Pe(ee.content||"");a(N=>{const ce=[...N],fe=ce[ce.length-1];return(fe==null?void 0:fe.role)==="assistant"&&(ce[ce.length-1]={...fe,content:q}),ce});break}ee.tool_calls=be;const je=ee.tool_calls.map(q=>{let N={};try{N=JSON.parse(q.function.arguments)}catch{}switch(q.function.name){case"search_datapoints":return`🔍 ${u.I18n.t("Searching datapoints")}: "${String(N.query||"")}"`;case"get_state_value":return`📊 ${u.I18n.t("Reading value")}: ${String(N.id||"")}`;case"get_object_info":return`📋 ${u.I18n.t("Loading object info")}: ${String(N.id||"")}`;case"search_scripts":return`🔍 ${u.I18n.t("Searching scripts")}: "${String(N.query||"")}"`;case"read_script":return`📖 ${u.I18n.t("Reading script")}: ${String(N.id||"")}`;case"list_scripts":return`📂 ${u.I18n.t("Loading script list")}`;default:return`⚙️ ${q.function.name}`}});a(q=>{const N=[...q],ce=N[N.length-1];return(ce==null?void 0:ce.role)==="assistant"&&(N[N.length-1]={...ce,content:je.join(`
288
- `)}),N}),j.push({role:"assistant",content:ee.content||"",tool_calls:ee.tool_calls});for(const q of ee.tool_calls){const N=await Kt(e,q,s,d);j.push({role:"tool",tool_call_id:q.id,content:N})}}}catch(j){x(String(j)),a(P=>P.slice(0,-1))}l(!1)},[w,_,p,y,e,n,se,z,s,v,ke,a,c,d]),ue=U(()=>{a([]),x(null),l(!1),b(null),Dt(),window.localStorage.removeItem("Editor.aiChatHistory")},[a]),it=U(async(f,O)=>{const R=_[w];if(!R)return`Error: ${u.I18n.t("Please select a valid model")}`;const L=A.current||await De(e,n);if(A.current=L,!L)return`Error: ${u.I18n.t("No API keys configured")}`;const W=Object.keys(n)[0];if(!W)return`Error: ${u.I18n.t("No running javascript instance found")}`;const ge=R==="custom"&&L.gptBaseUrl||"",D=o||"javascript",H=`You are an assistant for writing ioBroker ${D} scripts. The user will ask a question about a snippet of their code. Match your answer to the question:
288
+ `)}),N}),j.push({role:"assistant",content:ee.content||"",tool_calls:ee.tool_calls});for(const q of ee.tool_calls){const N=await Kt(e,q,s,d);j.push({role:"tool",tool_call_id:q.id,content:N})}}}catch(j){x(String(j)),a(P=>P.slice(0,-1))}l(!1)},[w,_,p,y,e,n,se,z,s,v,ke,a,c,d]),ue=A(()=>{a([]),x(null),l(!1),b(null),Dt(),window.localStorage.removeItem("Editor.aiChatHistory")},[a]),it=A(async(f,O)=>{const R=_[w];if(!R)return`Error: ${u.I18n.t("Please select a valid model")}`;const L=U.current||await De(e,n);if(U.current=L,!L)return`Error: ${u.I18n.t("No API keys configured")}`;const W=Object.keys(n)[0];if(!W)return`Error: ${u.I18n.t("No running javascript instance found")}`;const ge=R==="custom"&&L.gptBaseUrl||"",D=o||"javascript",F=`You are an assistant for writing ioBroker ${D} scripts. The user will ask a question about a snippet of their code. Match your answer to the question:
289
289
  - If they ask for an explanation, description, or "what does this do?", reply with clear prose (a few sentences). Do NOT repeat the code unchanged.
290
290
  - If they explicitly ask for a change, refactor, fix, or rewrite, reply with a single fenced \`\`\`${D==="blockly"?"xml":D}\`\`\` code block containing the full replacement for the selection. You may add one short sentence before or after the block.
291
291
  - If they ask something ambiguous or meta (e.g. "is this correct?"), reply in prose first and only include code if proposing a change.
@@ -295,8 +295,8 @@ ioBroker globals available in scripts: on, setState, getState, schedule, sendTo,
295
295
  ${O}
296
296
  \`\`\`
297
297
 
298
- ${f}`:f;try{const V=await Re(e,W,{messages:[{role:"system",content:H},{role:"user",content:B}],model:w,provider:R,baseUrl:ge});return V.error?`Error: ${V.error}`:V.content||""}catch(V){return`Error: ${V.message||String(V)}`}},[w,_,n,e,o]),at=U(f=>{f.range&&f.code?X.current=c(f.kind||"codelens",f.range,f.code):X.current=null,Ze(async()=>{const{buildActionPrompt:O}=await Promise.resolve().then(()=>ln);return{buildActionPrompt:O}},void 0,import.meta.url).then(({buildActionPrompt:O})=>{const R=O({action:f.action,code:f.code,language:o||"javascript",diagnostic:f.diagnostic,question:f.question,rangeLabel:f.rangeLabel});R?J(R):X.current=null}).catch(()=>{X.current=null,x(u.I18n.t("Failed to build AI action prompt"))})},[J,o,c]);return{messages:p,isLoading:y,error:I,model:w,availableModels:re,modelProviderMap:_,modelsLoading:le,modelsError:de,lastContextInfo:S,mode:v,setMode:E,setModel:C,sendMessage:J,triggerAiAction:at,askInline:it,clearChat:ue,retryLoadModels:k}}const en=({code:r,language:e,themeType:n,onInsertCode:t,onShowDiff:o,sourceRange:s})=>{const d=ne(null);xe(()=>{var g;const c=window.monaco;if(!d.current||!((g=c==null?void 0:c.editor)!=null&&g.colorize))return;const p=e==="ts"||e==="typescript"?"typescript":e||"javascript";c.editor.colorize(r,p,{theme:n==="dark"?"vs-dark":"vs"}).then(a=>{d.current&&(d.current.innerHTML=a)})},[r,e,n]);const m=U(()=>{navigator.clipboard.writeText(r)},[r]);return i.jsxs($,{sx:{position:"relative",my:1,borderRadius:1,overflow:"hidden",border:"1px solid",borderColor:"divider"},children:[i.jsxs($,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",px:1,py:.5,bgcolor:"action.hover",borderBottom:"1px solid",borderColor:"divider"},children:[i.jsx($,{sx:{fontSize:"0.75rem",color:"text.secondary",textTransform:"uppercase"},children:e||"javascript"}),i.jsxs($,{children:[i.jsx(ve,{title:u.I18n.t("Copy"),children:i.jsx(we,{size:"small",onClick:m,children:i.jsx(kt,{sx:{fontSize:16}})})}),t&&i.jsx(ve,{title:u.I18n.t("Insert into editor"),children:i.jsx(we,{size:"small",onClick:()=>t(r),children:i.jsx(et,{sx:{fontSize:16}})})}),o&&i.jsx(ve,{title:u.I18n.t("Show as diff"),children:i.jsx(we,{size:"small",onClick:()=>o(r,s),children:i.jsx(It,{sx:{fontSize:16}})})})]})]}),i.jsx("pre",{ref:d,style:{margin:0,padding:"8px 12px",overflow:"auto",maxHeight:400,fontSize:"13px",fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace",backgroundColor:n==="dark"?"#1e1e1e":"#f8f8f8",color:n==="dark"?"#d4d4d4":"#333"},children:r})]})},tn=({xml:r,themeType:e})=>{const n=ne(null),t=ne(null),[o,s]=te(60),d=ne(!1);return xe(()=>{d.current&&(d.current=!1,requestAnimationFrame(()=>{const m=window.Blockly,c=t.current;m&&c&&(m.svgResize(c),c.scrollCenter())}))},[o]),xe(()=>{const m=window.Blockly;if(!(!m||!n.current)){t.current&&(t.current.dispose(),t.current=null);try{const c=m.inject(n.current,{readOnly:!0,toolbox:null,trashcan:!1,zoom:{controls:!1,wheel:!1,startScale:1},move:{scrollbars:!1,drag:!1,wheel:!1},sounds:!1,renderer:"thrasos",theme:e==="dark"?St:"classic",media:"google-blockly/media/"});t.current=c;let p=r.trim();p.startsWith("<xml")||(p=`<xml xmlns="https://developers.google.com/blockly/xml">${p}</xml>`);const g=m.utils.xml.textToDom(p);let a=10;const y=Array.from(g.querySelectorAll(":scope > block"));for(const b of y)b.setAttribute("x","10"),b.setAttribute("y",String(a)),a+=200;m.Xml.domToWorkspace(g,c);const l=c.getTopBlocks(!1);if(l.length>1){let b=10;for(const v of l){const F=v.getRelativeToSurfaceXY();v.moveBy(10-F.x,b-F.y),b+=v.getHeightWidth().height+20}}const S=c.getBlocksBoundingBox();if(S){const b=S.bottom-S.top+20,v=Math.max(60,Math.ceil(b));d.current=!0,s(v)}}catch{}return()=>{t.current&&(t.current.dispose(),t.current=null)}}},[r,e]),i.jsx($,{ref:n,sx:{width:"100%",height:o,minHeight:60,borderRadius:1,overflow:"hidden",border:"1px solid",borderColor:"divider"}})};function nn(r){const e=[],n=/```(\w*)\n?([\s\S]*?)```/g;let t=0,o;for(;(o=n.exec(r))!==null;){if(o.index>t){const s=r.substring(t,o.index).trim();s&&e.push({type:"text",content:s})}e.push({type:"code",content:o[2].trim(),language:o[1]||"javascript"}),t=o.index+o[0].length}if(t<r.length){const s=r.substring(t).trim();s&&e.push({type:"text",content:s})}return e.length===0&&e.push({type:"text",content:r}),e}function Ee(r){const e=[],n=/(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`)/g;let t=0,o,s=0;for(;(o=n.exec(r))!==null;)o.index>t&&e.push(r.substring(t,o.index)),o[2]?e.push(i.jsx("strong",{children:o[2]},s++)):o[3]?e.push(i.jsx("em",{children:o[3]},s++)):o[4]&&e.push(i.jsx("code",{className:"ai-chat-inline-code",style:{padding:"2px 6px",borderRadius:4,fontSize:"0.85em",fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace"},children:o[4]},s++)),t=o.index+o[0].length;return t<r.length&&e.push(r.substring(t)),e}function Qe(r){return r.trim().startsWith("|")&&r.trim().endsWith("|")}function sn(r){return/^\|[\s:]*-+[\s:|-]*\|$/.test(r.trim())}function rn(r,e,n){const t=e.palette.mode==="dark",o=m=>m.trim().replace(/^\||\|$/g,"").split("|").map(c=>c.trim()),s=o(r[0]),d=r.slice(2).map(o);return i.jsx($,{sx:{overflowX:"auto",my:1},children:i.jsxs("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"0.8rem",color:e.palette.text.primary},children:[i.jsx("thead",{children:i.jsx("tr",{children:s.map((m,c)=>i.jsx("th",{style:{border:`1px solid ${e.palette.divider}`,padding:"6px 10px",backgroundColor:t?e.palette.grey[800]:e.palette.grey[100],color:e.palette.text.primary,fontWeight:600,textAlign:"left"},children:Ee(m)},c))})}),i.jsx("tbody",{children:d.map((m,c)=>i.jsx("tr",{style:{backgroundColor:c%2===1?t?e.palette.grey[900]:e.palette.grey[50]:void 0},children:m.map((p,g)=>i.jsx("td",{style:{border:`1px solid ${e.palette.divider}`,padding:"6px 10px",color:e.palette.text.primary},children:Ee(p)},g))},c))})]})},n)}function on(r,e){const n=r.split(`
299
- `),t=[];let o=0,s=0;for(;s<n.length;){const m=n[s].trim();if(m===""){s++;continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(m)){t.push(i.jsx("hr",{style:{border:"none",borderTop:`1px solid ${e.palette.divider}`,margin:"8px 0"}},o++)),s++;continue}const c=m.match(/^(#{1,4})\s+(.+)$/);if(c){const p=c[1].length,g=["1.2em","1.1em","1em","0.95em"];t.push(i.jsx("div",{style:{fontWeight:600,fontSize:g[p-1],margin:"8px 0 4px"},children:Ee(c[2])},o++)),s++;continue}if(Qe(m)&&s+1<n.length&&sn(n[s+1].trim())&&s+2<n.length){const p=[n[s],n[s+1]];let g=s+2;for(;g<n.length&&Qe(n[g]);)p.push(n[g]),g++;t.push(rn(p,e,o++)),s=g;continue}if(/^[-*+]\s/.test(m)){const p=[];for(;s<n.length&&/^\s*[-*+]\s/.test(n[s]);)p.push(n[s].replace(/^\s*[-*+]\s/,"").trim()),s++;t.push(i.jsx("ul",{style:{margin:"4px 0",paddingLeft:20},children:p.map((g,a)=>i.jsx("li",{children:Ee(g)},a))},o++));continue}if(/^\d+[.)]\s/.test(m)){const p=[];for(;s<n.length&&/^\s*\d+[.)]\s/.test(n[s]);)p.push(n[s].replace(/^\s*\d+[.)]\s/,"").trim()),s++;t.push(i.jsx("ol",{style:{margin:"4px 0",paddingLeft:20},children:p.map((g,a)=>i.jsx("li",{children:Ee(g)},a))},o++));continue}t.push(i.jsx("div",{children:Ee(m)},o++)),s++}return t}const an=({message:r,themeType:e,currentLanguage:n,onInsertCode:t,onShowDiff:o,onApplyCode:s})=>{const d=r.role==="user",m=ct(),c=d?e==="dark"?m.palette.primary.dark:m.palette.primary.main:e==="dark"?m.palette.secondary.dark:m.palette.secondary.main,p=m.palette.getContrastText(c),g=Ae(()=>nn(r.content),[r.content]),a=(b,v)=>!!(b==="xml"||b==="blockly"||n==="blockly"&&v&&/<block\s+type=/.test(v)),y=c,l=d?e==="dark"?"rgba(144, 202, 249, 0.10)":"rgba(25, 118, 210, 0.07)":e==="dark"?"rgba(206, 147, 216, 0.10)":"rgba(156, 39, 176, 0.06)",S=d?e==="dark"?"rgba(144, 202, 249, 0.16)":"rgba(25, 118, 210, 0.12)":e==="dark"?"rgba(206, 147, 216, 0.16)":"rgba(156, 39, 176, 0.10)";return i.jsxs($,{sx:{display:"flex",gap:1,px:1.5,py:1,mx:.75,my:.5,bgcolor:l,borderRadius:1.5,borderLeft:"3px solid",borderLeftColor:y,transition:"background-color 120ms","&:hover":{bgcolor:S}},children:[i.jsx(lt,{sx:{width:28,height:28,bgcolor:c,color:p,flexShrink:0,mt:.5},children:d?i.jsx(Tt,{sx:{fontSize:18}}):i.jsx(Rt,{sx:{fontSize:18}})}),i.jsx($,{sx:{flex:1,minWidth:0,fontSize:"0.875rem",lineHeight:1.6},children:g.map((b,v)=>b.type==="code"?a(b.language,b.content)?i.jsxs($,{sx:{my:1},children:[i.jsx(tn,{xml:b.content,themeType:e}),i.jsxs($,{sx:{display:"flex",gap:.5,mt:.5},children:[s&&i.jsx(We,{size:"small",variant:"contained",color:"primary",startIcon:i.jsx(Ot,{sx:{fontSize:14}}),onClick:()=>s(b.content),sx:{textTransform:"none",fontSize:"0.75rem"},children:u.I18n.t("Apply blocks")}),t&&i.jsx(We,{size:"small",variant:"outlined",startIcon:i.jsx(et,{sx:{fontSize:14}}),onClick:()=>t(b.content),sx:{textTransform:"none",fontSize:"0.75rem"},children:u.I18n.t("Insert blocks")})]})]},v):i.jsx(en,{code:b.content,language:b.language||"javascript",themeType:e,onInsertCode:t,onShowDiff:o,sourceRange:r.sourceRange||null},v):i.jsx($,{sx:{wordBreak:"break-word",color:m.palette.text.primary},children:on(b.content,m)},v))})]})};function cn(r){const e=(r||"").toLowerCase();return e.includes("blockly")||e.includes("rules")?"blockly":e.includes("typescript")?"typescript":"javascript"}function Te(r,e){return`\`\`\`${e==="blockly"?"xml":e}
298
+ ${f}`:f;try{const V=await Re(e,W,{messages:[{role:"system",content:F},{role:"user",content:B}],model:w,provider:R,baseUrl:ge});return V.error?`Error: ${V.error}`:V.content||""}catch(V){return`Error: ${V.message||String(V)}`}},[w,_,n,e,o]),at=A(f=>{f.range&&f.code?X.current=c(f.kind||"codelens",f.range,f.code):X.current=null,Ze(async()=>{const{buildActionPrompt:O}=await Promise.resolve().then(()=>ln);return{buildActionPrompt:O}},void 0,import.meta.url).then(({buildActionPrompt:O})=>{const R=O({action:f.action,code:f.code,language:o||"javascript",diagnostic:f.diagnostic,question:f.question,rangeLabel:f.rangeLabel});R?J(R):X.current=null}).catch(()=>{X.current=null,x(u.I18n.t("Failed to build AI action prompt"))})},[J,o,c]);return{messages:p,isLoading:y,error:I,model:w,availableModels:re,modelProviderMap:_,modelsLoading:le,modelsError:de,lastContextInfo:S,mode:v,setMode:E,setModel:C,sendMessage:J,triggerAiAction:at,askInline:it,clearChat:ue,retryLoadModels:k}}const en=({code:r,language:e,themeType:n,onInsertCode:t,onShowDiff:o,sourceRange:s})=>{const d=ne(null);xe(()=>{var g;const c=window.monaco;if(!d.current||!((g=c==null?void 0:c.editor)!=null&&g.colorize))return;const p=e==="ts"||e==="typescript"?"typescript":e||"javascript";c.editor.colorize(r,p,{theme:n==="dark"?"vs-dark":"vs"}).then(a=>{d.current&&(d.current.innerHTML=a)})},[r,e,n]);const m=A(()=>{navigator.clipboard.writeText(r)},[r]);return i.jsxs($,{sx:{position:"relative",my:1,borderRadius:1,overflow:"hidden",border:"1px solid",borderColor:"divider"},children:[i.jsxs($,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",px:1,py:.5,bgcolor:"action.hover",borderBottom:"1px solid",borderColor:"divider"},children:[i.jsx($,{sx:{fontSize:"0.75rem",color:"text.secondary",textTransform:"uppercase"},children:e||"javascript"}),i.jsxs($,{children:[i.jsx(ve,{title:u.I18n.t("Copy"),children:i.jsx(we,{size:"small",onClick:m,children:i.jsx(kt,{sx:{fontSize:16}})})}),t&&i.jsx(ve,{title:u.I18n.t("Insert into editor"),children:i.jsx(we,{size:"small",onClick:()=>t(r),children:i.jsx(et,{sx:{fontSize:16}})})}),o&&i.jsx(ve,{title:u.I18n.t("Show as diff"),children:i.jsx(we,{size:"small",onClick:()=>o(r,s),children:i.jsx(It,{sx:{fontSize:16}})})})]})]}),i.jsx("pre",{ref:d,style:{margin:0,padding:"8px 12px",overflow:"auto",maxHeight:400,fontSize:"13px",fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace",backgroundColor:n==="dark"?"#1e1e1e":"#f8f8f8",color:n==="dark"?"#d4d4d4":"#333"},children:r})]})},tn=({xml:r,themeType:e})=>{const n=ne(null),t=ne(null),[o,s]=te(60),d=ne(!1);return xe(()=>{d.current&&(d.current=!1,requestAnimationFrame(()=>{const m=window.Blockly,c=t.current;m&&c&&(m.svgResize(c),c.scrollCenter())}))},[o]),xe(()=>{const m=window.Blockly;if(!(!m||!n.current)){t.current&&(t.current.dispose(),t.current=null);try{const c=m.inject(n.current,{readOnly:!0,toolbox:null,trashcan:!1,zoom:{controls:!1,wheel:!1,startScale:1},move:{scrollbars:!1,drag:!1,wheel:!1},sounds:!1,renderer:"thrasos",theme:e==="dark"?St:"classic",media:"google-blockly/media/"});t.current=c;let p=r.trim();p.startsWith("<xml")||(p=`<xml xmlns="https://developers.google.com/blockly/xml">${p}</xml>`);const g=m.utils.xml.textToDom(p);let a=10;const y=Array.from(g.querySelectorAll(":scope > block"));for(const b of y)b.setAttribute("x","10"),b.setAttribute("y",String(a)),a+=200;m.Xml.domToWorkspace(g,c);const l=c.getTopBlocks(!1);if(l.length>1){let b=10;for(const v of l){const H=v.getRelativeToSurfaceXY();v.moveBy(10-H.x,b-H.y),b+=v.getHeightWidth().height+20}}const S=c.getBlocksBoundingBox();if(S){const b=S.bottom-S.top+20,v=Math.max(60,Math.ceil(b));d.current=!0,s(v)}}catch{}return()=>{t.current&&(t.current.dispose(),t.current=null)}}},[r,e]),i.jsx($,{ref:n,sx:{width:"100%",height:o,minHeight:60,borderRadius:1,overflow:"hidden",border:"1px solid",borderColor:"divider"}})};function nn(r){const e=[],n=/```(\w*)\n?([\s\S]*?)```/g;let t=0,o;for(;(o=n.exec(r))!==null;){if(o.index>t){const s=r.substring(t,o.index).trim();s&&e.push({type:"text",content:s})}e.push({type:"code",content:o[2].trim(),language:o[1]||"javascript"}),t=o.index+o[0].length}if(t<r.length){const s=r.substring(t).trim();s&&e.push({type:"text",content:s})}return e.length===0&&e.push({type:"text",content:r}),e}function Ee(r){const e=[],n=/(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`)/g;let t=0,o,s=0;for(;(o=n.exec(r))!==null;)o.index>t&&e.push(r.substring(t,o.index)),o[2]?e.push(i.jsx("strong",{children:o[2]},s++)):o[3]?e.push(i.jsx("em",{children:o[3]},s++)):o[4]&&e.push(i.jsx("code",{className:"ai-chat-inline-code",style:{padding:"2px 6px",borderRadius:4,fontSize:"0.85em",fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace"},children:o[4]},s++)),t=o.index+o[0].length;return t<r.length&&e.push(r.substring(t)),e}function Qe(r){return r.trim().startsWith("|")&&r.trim().endsWith("|")}function sn(r){return/^\|[\s:]*-+[\s:|-]*\|$/.test(r.trim())}function rn(r,e,n){const t=e.palette.mode==="dark",o=m=>m.trim().replace(/^\||\|$/g,"").split("|").map(c=>c.trim()),s=o(r[0]),d=r.slice(2).map(o);return i.jsx($,{sx:{overflowX:"auto",my:1},children:i.jsxs("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"0.8rem",color:e.palette.text.primary},children:[i.jsx("thead",{children:i.jsx("tr",{children:s.map((m,c)=>i.jsx("th",{style:{border:`1px solid ${e.palette.divider}`,padding:"6px 10px",backgroundColor:t?e.palette.grey[800]:e.palette.grey[100],color:e.palette.text.primary,fontWeight:600,textAlign:"left"},children:Ee(m)},c))})}),i.jsx("tbody",{children:d.map((m,c)=>i.jsx("tr",{style:{backgroundColor:c%2===1?t?e.palette.grey[900]:e.palette.grey[50]:void 0},children:m.map((p,g)=>i.jsx("td",{style:{border:`1px solid ${e.palette.divider}`,padding:"6px 10px",color:e.palette.text.primary},children:Ee(p)},g))},c))})]})},n)}function on(r,e){const n=r.split(`
299
+ `),t=[];let o=0,s=0;for(;s<n.length;){const m=n[s].trim();if(m===""){s++;continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(m)){t.push(i.jsx("hr",{style:{border:"none",borderTop:`1px solid ${e.palette.divider}`,margin:"8px 0"}},o++)),s++;continue}const c=m.match(/^(#{1,4})\s+(.+)$/);if(c){const p=c[1].length,g=["1.2em","1.1em","1em","0.95em"];t.push(i.jsx("div",{style:{fontWeight:600,fontSize:g[p-1],margin:"8px 0 4px"},children:Ee(c[2])},o++)),s++;continue}if(Qe(m)&&s+1<n.length&&sn(n[s+1].trim())&&s+2<n.length){const p=[n[s],n[s+1]];let g=s+2;for(;g<n.length&&Qe(n[g]);)p.push(n[g]),g++;t.push(rn(p,e,o++)),s=g;continue}if(/^[-*+]\s/.test(m)){const p=[];for(;s<n.length&&/^\s*[-*+]\s/.test(n[s]);)p.push(n[s].replace(/^\s*[-*+]\s/,"").trim()),s++;t.push(i.jsx("ul",{style:{margin:"4px 0",paddingLeft:20},children:p.map((g,a)=>i.jsx("li",{children:Ee(g)},a))},o++));continue}if(/^\d+[.)]\s/.test(m)){const p=[];for(;s<n.length&&/^\s*\d+[.)]\s/.test(n[s]);)p.push(n[s].replace(/^\s*\d+[.)]\s/,"").trim()),s++;t.push(i.jsx("ol",{style:{margin:"4px 0",paddingLeft:20},children:p.map((g,a)=>i.jsx("li",{children:Ee(g)},a))},o++));continue}t.push(i.jsx("div",{children:Ee(m)},o++)),s++}return t}const an=({message:r,themeType:e,currentLanguage:n,onInsertCode:t,onShowDiff:o,onApplyCode:s})=>{const d=r.role==="user",m=ct(),c=d?e==="dark"?m.palette.primary.dark:m.palette.primary.main:e==="dark"?m.palette.secondary.dark:m.palette.secondary.main,p=m.palette.getContrastText(c),g=Ue(()=>nn(r.content),[r.content]),a=(b,v)=>!!(b==="xml"||b==="blockly"||n==="blockly"&&v&&/<block\s+type=/.test(v)),y=c,l=d?e==="dark"?"rgba(144, 202, 249, 0.10)":"rgba(25, 118, 210, 0.07)":e==="dark"?"rgba(206, 147, 216, 0.10)":"rgba(156, 39, 176, 0.06)",S=d?e==="dark"?"rgba(144, 202, 249, 0.16)":"rgba(25, 118, 210, 0.12)":e==="dark"?"rgba(206, 147, 216, 0.16)":"rgba(156, 39, 176, 0.10)";return i.jsxs($,{sx:{display:"flex",gap:1,px:1.5,py:1,mx:.75,my:.5,bgcolor:l,borderRadius:1.5,borderLeft:"3px solid",borderLeftColor:y,transition:"background-color 120ms","&:hover":{bgcolor:S}},children:[i.jsx(lt,{sx:{width:28,height:28,bgcolor:c,color:p,flexShrink:0,mt:.5},children:d?i.jsx(Tt,{sx:{fontSize:18}}):i.jsx(Rt,{sx:{fontSize:18}})}),i.jsx($,{sx:{flex:1,minWidth:0,fontSize:"0.875rem",lineHeight:1.6},children:g.map((b,v)=>b.type==="code"?a(b.language,b.content)?i.jsxs($,{sx:{my:1},children:[i.jsx(tn,{xml:b.content,themeType:e}),i.jsxs($,{sx:{display:"flex",gap:.5,mt:.5},children:[s&&i.jsx(We,{size:"small",variant:"contained",color:"primary",startIcon:i.jsx(Ot,{sx:{fontSize:14}}),onClick:()=>s(b.content),sx:{textTransform:"none",fontSize:"0.75rem"},children:u.I18n.t("Apply blocks")}),t&&i.jsx(We,{size:"small",variant:"outlined",startIcon:i.jsx(et,{sx:{fontSize:14}}),onClick:()=>t(b.content),sx:{textTransform:"none",fontSize:"0.75rem"},children:u.I18n.t("Insert blocks")})]})]},v):i.jsx(en,{code:b.content,language:b.language||"javascript",themeType:e,onInsertCode:t,onShowDiff:o,sourceRange:r.sourceRange||null},v):i.jsx($,{sx:{wordBreak:"break-word",color:m.palette.text.primary},children:on(b.content,m)},v))})]})};function cn(r){const e=(r||"").toLowerCase();return e.includes("blockly")||e.includes("rules")?"blockly":e.includes("typescript")?"typescript":"javascript"}function Te(r,e){return`\`\`\`${e==="blockly"?"xml":e}
300
300
  ${r}
301
301
  \`\`\``}function rt(r){const e=(r.code||"").trim(),n=cn(r.language),t=r.rangeLabel?` (${r.rangeLabel})`:"";switch(r.action){case"explain":return e?[`Please explain what this ioBroker ${n} code does${t}.`,"Focus on: which datapoints it reads/writes, which triggers fire it, and any side-effects.","",Te(e,n)].join(`
302
302
  `):null;case"refactor":return e?[`Refactor this ioBroker ${n} code${t} to be cleaner and more idiomatic.`,"Preserve behavior exactly. Keep ioBroker APIs (on, setState, getState, schedule, sendTo, log).",`Return the full refactored block inside a \`\`\`${n==="blockly"?"xml":n}\`\`\` code block so it can be smart-applied.`,"",Te(e,n)].join(`
@@ -305,11 +305,11 @@ ${r}
305
305
  Reported problem: ${o}`:"";return[`This ioBroker ${n} code has an issue${t}. Please fix it and return the corrected code.${s}`,"Keep the fix minimal — do not rewrite unrelated parts.","",Te(e,n)].join(`
306
306
  `)}case"tests":return e?[`Suggest how to test this ioBroker ${n} script manually inside the ioBroker admin UI${t}.`,"","ioBroker scripts run inside the adapter sandbox and CANNOT be unit-tested with Jest, Mocha, or any external test framework. Do NOT propose Jest/Mocha tests, do NOT propose extracting the code into a separate Node.js project, do NOT write `describe` / `test` blocks.","","Instead, propose a short list of manual test cases. For each case describe:",' • Setup — which ioBroker datapoints to prepare and to which values (via the objects tree "Values" tab)'," • Action — what to trigger: set a state with setState, wait for a schedule, change a sensor value, etc."," • Expected — what should happen afterwards: which states should change, what should appear in the adapter log (javascript.0), which side effects are visible","","Keep it concise: 3-6 cases covering the happy path, typical edge cases, and any guard conditions the script has.","",Te(e,n)].join(`
307
307
  `):null;case"ask":{const o=(r.question||"").trim();return o?e?[`Regarding this ioBroker ${n} code${t}:`,"",Te(e,n),"",o].join(`
308
- `):o:null}default:return null}}function ot(r){const e=(r||"").trimStart();if(!e.startsWith("/"))return null;const n=e.match(/^\/(\w+)(?:\s+([\s\S]*))?$/);if(!n)return null;const t=n[1].toLowerCase(),o=(n[2]||"").trim(),d={explain:"explain",erklaere:"explain",erklaeren:"explain",refactor:"refactor",refaktor:"refactor",refaktoriere:"refactor",comment:"comment",comments:"comment",kommentar:"comment",kommentiere:"comment",fix:"fix",fixme:"fix",tests:"tests",test:"tests",ask:"ask",frag:"ask",frage:"ask"}[t];return d?{action:d,rest:o}:null}const ln=Object.freeze(Object.defineProperty({__proto__:null,buildActionPrompt:rt,parseSlashCommand:ot},Symbol.toStringTag,{value:"Module"}));function dn(){return[{id:"@all",label:u.I18n.t("mention @all"),descriptionKey:"All scripts"},{id:"@devices",label:u.I18n.t("mention @devices"),descriptionKey:"Smart home devices"}]}function un({provider:r,isDark:e}){return $t[r]?i.jsx("img",{src:`./img/${r}.svg`,alt:r,style:{...Lt,...e?{filter:"invert(0.85)"}:{}},onError:t=>{t.target.style.display="none"}}):null}function mn(){try{const r=window.localStorage.getItem("Editor.aiChatHistory");return r?JSON.parse(r):[]}catch{return[]}}const pn=({onSend:r,disabled:e,themeType:n,hasSelection:t,selectionText:o,allScripts:s,model:d,availableModels:m,modelProviderMap:c,modelsLoading:p,onModelChange:g,mode:a,onModeChange:y,currentLanguage:l})=>{const[S,b]=te(""),[v,F]=te(!1),[E,I]=te(""),[x,w]=te(0),M=ne(null),re=ne(-1),Y=ne(mn()),_=ne(-1),G=ne(""),le=Ae(()=>{const C=dn().map(k=>({...k,description:u.I18n.t(k.descriptionKey)}));if(s)for(const k of s){const z=k.id.replace(/^script\.js\./,"").replace(/\./g,"/");C.push({id:`@${z}`,label:`@${z}`,description:`${k.name} [${k.enabled?"active":"inactive"}]`})}return C},[s]),K=Ae(()=>{if(!E)return le;const h=E.toLowerCase();return le.filter(C=>C.id.toLowerCase().includes(h)||C.description.toLowerCase().includes(h))},[le,E]);xe(()=>{w(0)},[E]);const de=U(()=>{const h=S.trim();if(!h||e)return;let C=h;const k=ot(h);if(k){const z=t&&o?o:"",se=rt({action:k.action,code:z,language:l||"javascript",question:k.action==="ask"?k.rest:void 0,diagnostic:k.action==="fix"&&k.rest||void 0});se&&(C=se)}else t&&o&&(C=`[Selected code in editor]
308
+ `):o:null}default:return null}}function ot(r){const e=(r||"").trimStart();if(!e.startsWith("/"))return null;const n=e.match(/^\/(\w+)(?:\s+([\s\S]*))?$/);if(!n)return null;const t=n[1].toLowerCase(),o=(n[2]||"").trim(),d={explain:"explain",erklaere:"explain",erklaeren:"explain",refactor:"refactor",refaktor:"refactor",refaktoriere:"refactor",comment:"comment",comments:"comment",kommentar:"comment",kommentiere:"comment",fix:"fix",fixme:"fix",tests:"tests",test:"tests",ask:"ask",frag:"ask",frage:"ask"}[t];return d?{action:d,rest:o}:null}const ln=Object.freeze(Object.defineProperty({__proto__:null,buildActionPrompt:rt,parseSlashCommand:ot},Symbol.toStringTag,{value:"Module"}));function dn(){return[{id:"@all",label:u.I18n.t("mention @all"),descriptionKey:"All scripts"},{id:"@devices",label:u.I18n.t("mention @devices"),descriptionKey:"Smart home devices"}]}function un({provider:r,isDark:e}){return $t[r]?i.jsx("img",{src:`./img/${r}.svg`,alt:r,style:{...Lt,...e?{filter:"invert(0.85)"}:{}},onError:t=>{t.target.style.display="none"}}):null}function mn(){try{const r=window.localStorage.getItem("Editor.aiChatHistory");return r?JSON.parse(r):[]}catch{return[]}}const pn=({onSend:r,disabled:e,themeType:n,hasSelection:t,selectionText:o,allScripts:s,model:d,availableModels:m,modelProviderMap:c,modelsLoading:p,onModelChange:g,mode:a,onModeChange:y,currentLanguage:l})=>{const[S,b]=te(""),[v,H]=te(!1),[E,I]=te(""),[x,w]=te(0),M=ne(null),re=ne(-1),Y=ne(mn()),_=ne(-1),G=ne(""),le=Ue(()=>{const C=dn().map(k=>({...k,description:u.I18n.t(k.descriptionKey)}));if(s)for(const k of s){const z=k.id.replace(/^script\.js\./,"").replace(/\./g,"/");C.push({id:`@${z}`,label:`@${z}`,description:`${k.name} [${k.enabled?"active":"inactive"}]`})}return C},[s]),K=Ue(()=>{if(!E)return le;const h=E.toLowerCase();return le.filter(C=>C.id.toLowerCase().includes(h)||C.description.toLowerCase().includes(h))},[le,E]);xe(()=>{w(0)},[E]);const de=A(()=>{const h=S.trim();if(!h||e)return;let C=h;const k=ot(h);if(k){const z=t&&o?o:"",se=rt({action:k.action,code:z,language:l||"javascript",question:k.action==="ask"?k.rest:void 0,diagnostic:k.action==="fix"&&k.rest||void 0});se&&(C=se)}else t&&o&&(C=`[Selected code in editor]
309
309
  \`\`\`
310
310
  ${o}
311
311
  \`\`\`
312
312
 
313
- ${h}`);Y.current.push(h),_.current=-1,G.current="";try{const z=Y.current.slice(-50);window.localStorage.setItem("Editor.aiChatHistory",JSON.stringify(z))}catch{}r(C),b(""),F(!1),requestAnimationFrame(()=>{var z;return(z=M.current)==null?void 0:z.focus()})},[S,e,r,t,o,l]),T=U(h=>{const C=re.current,k=M.current;if(C<0){const ue=S?`${S}${h} `:`${h} `;b(ue),F(!1),I(""),setTimeout(()=>{k&&(k.focus(),k.setSelectionRange(ue.length,ue.length))},0);return}const z=S.substring(0,C),se=(k==null?void 0:k.selectionStart)??S.length,ke=S.substring(se),J=`${z}${h} ${ke}`;b(J),F(!1),I(""),re.current=-1,setTimeout(()=>{if(k){const ue=z.length+h.length+1;k.focus(),k.setSelectionRange(ue,ue)}},0)},[S]),A=U(()=>{re.current=-1,I(""),F(h=>!h)},[]),X=U(h=>{const C=h.target.value;b(C);const k=h.target.selectionStart??C.length,se=C.substring(0,k).match(/@([\w/äöüÄÖÜß]*)$/);se?(re.current=k-se[0].length,I(se[1]),F(!0)):(F(!1),I(""))},[]),Q=U(h=>{if(v&&K.length>0){if(h.key==="ArrowDown"){h.preventDefault(),w(C=>(C+1)%K.length);return}if(h.key==="ArrowUp"){h.preventDefault(),w(C=>(C-1+K.length)%K.length);return}if(h.key==="Enter"||h.key==="Tab"){h.preventDefault(),T(K[x].id);return}if(h.key==="Escape"){h.preventDefault(),F(!1);return}}if(h.key==="ArrowUp"&&!v&&Y.current.length>0){const C=M.current,k=!C||C.selectionStart===0,z=!S.includes(`
313
+ ${h}`);Y.current.push(h),_.current=-1,G.current="";try{const z=Y.current.slice(-50);window.localStorage.setItem("Editor.aiChatHistory",JSON.stringify(z))}catch{}r(C),b(""),H(!1),requestAnimationFrame(()=>{var z;return(z=M.current)==null?void 0:z.focus()})},[S,e,r,t,o,l]),T=A(h=>{const C=re.current,k=M.current;if(C<0){const ue=S?`${S}${h} `:`${h} `;b(ue),H(!1),I(""),setTimeout(()=>{k&&(k.focus(),k.setSelectionRange(ue.length,ue.length))},0);return}const z=S.substring(0,C),se=(k==null?void 0:k.selectionStart)??S.length,ke=S.substring(se),J=`${z}${h} ${ke}`;b(J),H(!1),I(""),re.current=-1,setTimeout(()=>{if(k){const ue=z.length+h.length+1;k.focus(),k.setSelectionRange(ue,ue)}},0)},[S]),U=A(()=>{re.current=-1,I(""),H(h=>!h)},[]),X=A(h=>{const C=h.target.value;b(C);const k=h.target.selectionStart??C.length,se=C.substring(0,k).match(/@([\w/äöüÄÖÜß]*)$/);se?(re.current=k-se[0].length,I(se[1]),H(!0)):(H(!1),I(""))},[]),Q=A(h=>{if(v&&K.length>0){if(h.key==="ArrowDown"){h.preventDefault(),w(C=>(C+1)%K.length);return}if(h.key==="ArrowUp"){h.preventDefault(),w(C=>(C-1+K.length)%K.length);return}if(h.key==="Enter"||h.key==="Tab"){h.preventDefault(),T(K[x].id);return}if(h.key==="Escape"){h.preventDefault(),H(!1);return}}if(h.key==="ArrowUp"&&!v&&Y.current.length>0){const C=M.current,k=!C||C.selectionStart===0,z=!S.includes(`
314
314
  `);if(k&&z){h.preventDefault(),_.current===-1?(G.current=S,_.current=Y.current.length-1):_.current>0&&_.current--,b(Y.current[_.current]);return}}if(h.key==="ArrowDown"&&!v&&_.current>=0){const C=M.current,k=!C||C.selectionStart===S.length,z=!S.includes(`
315
- `);if(k&&z){h.preventDefault(),_.current<Y.current.length-1?(_.current++,b(Y.current[_.current])):(_.current=-1,b(G.current));return}}h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),de())},[de,v,K,x,T,S]);return i.jsxs($,{sx:{borderTop:"1px solid",borderColor:"divider",position:"relative"},children:[v&&K.length>0&&i.jsx(dt,{elevation:4,sx:{position:"absolute",bottom:"100%",left:8,right:8,maxHeight:200,overflow:"auto",zIndex:10,mb:.5},children:i.jsx(ut,{dense:!0,disablePadding:!0,children:K.slice(0,15).map((h,C)=>i.jsx(mt,{selected:C===x,onClick:()=>T(h.id),sx:{py:.25,minHeight:32},children:i.jsx(pt,{primary:h.label,secondary:h.description,primaryTypographyProps:{fontSize:"0.8rem",fontWeight:500},secondaryTypographyProps:{fontSize:"0.7rem"}})},h.id))})}),a==="code"&&i.jsx(He,{label:`${u.I18n.t("mention @devices")} — ${u.I18n.t("Smart home devices")}`,size:"small",variant:"outlined",sx:{mx:1,mt:.5,maxWidth:"calc(100% - 16px)"}}),t&&o&&i.jsx(He,{icon:i.jsx(bt,{sx:{fontSize:14}}),label:u.I18n.t("Selected code as context"),size:"small",variant:"outlined",sx:{mx:1,mt:.5,maxWidth:"calc(100% - 16px)"}}),i.jsxs($,{sx:{mx:1,mt:.5,mb:.5,border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden","&:focus-within":{borderColor:"primary.main"}},children:[i.jsx(ft,{inputRef:M,fullWidth:!0,multiline:!0,maxRows:6,placeholder:u.I18n.t("Ask about your script..."),value:S,onChange:X,onKeyDown:Q,disabled:e,onBlur:()=>{setTimeout(()=>F(!1),200)},variant:"standard",slotProps:{input:{disableUnderline:!0}},sx:{px:1.5,pt:1,pb:.5,"& .MuiInputBase-root":{fontSize:"0.875rem"}}}),i.jsxs($,{sx:{display:"flex",alignItems:"center",gap:.75,px:1,pb:.5},children:[i.jsx(ve,{title:i.jsxs($,{sx:{fontSize:"0.8rem",lineHeight:1.5,maxWidth:360},children:[i.jsx($,{sx:{fontWeight:600,mb:.75},children:u.I18n.t("AI chat mode")}),i.jsxs($,{sx:{mb:.75},children:[i.jsxs("strong",{children:["💬 ",u.I18n.t("Chat")]})," —"," ",u.I18n.t("Plain conversation. Use for questions, explanations, syntax help. Does not read or modify your scripts.")]}),i.jsxs($,{sx:{mb:.75},children:[i.jsxs("strong",{children:["🤖 ",u.I18n.t("Agent")]})," —"," ",u.I18n.t('AI can call tools to inspect your system: read scripts, look up datapoints, browse the object tree. Use for "which scripts use this state?", "analyze my light script".')]}),i.jsxs($,{children:[i.jsxs("strong",{children:["💻 ",u.I18n.t("Code")]})," —"," ",u.I18n.t('Two-step script generator (plan then code). Use for "create a script that...", "write a Blockly rule for...". Output goes into the editor for smart-apply.')]})]}),enterDelay:400,placement:"top",children:i.jsxs(Fe,{value:a,onChange:h=>y(h.target.value),size:"small",variant:"standard",disableUnderline:!0,sx:{fontSize:"0.7rem",color:"text.secondary",border:"1px solid",borderColor:"text.secondary",borderRadius:3,bgcolor:"action.hover",px:.75,"&:hover":{borderColor:"text.disabled",bgcolor:"action.hover"},"& .MuiSelect-select":{py:"2px",pr:"18px !important",display:"flex",alignItems:"center",gap:.5}},children:[i.jsx(ze,{value:"chat",sx:{fontSize:"0.75rem"},title:u.I18n.t("Plain conversation. Best for: general questions, syntax help, concept explanations."),children:"💬 Chat"}),i.jsx(ze,{value:"agent",sx:{fontSize:"0.75rem"},title:u.I18n.t("Tool-using assistant. Best for: analyzing existing scripts, finding datapoint usages, inspecting the object tree."),children:"🤖 Agent"}),i.jsx(ze,{value:"code",sx:{fontSize:"0.75rem"},title:u.I18n.t("Script generator. Best for: creating new JavaScript/TypeScript or Blockly scripts from a description."),children:"💻 Code"})]})}),i.jsx(Fe,{value:d,onChange:h=>g(h.target.value),size:"small",disabled:p||m.length===0,variant:"standard",disableUnderline:!0,sx:{fontSize:"0.7rem",color:"text.secondary",border:"1px solid",borderColor:"text.secondary",borderRadius:3,bgcolor:"action.hover",px:.75,"&:hover":{borderColor:"text.disabled",bgcolor:"action.hover"},"& .MuiSelect-select":{py:"2px",pr:"18px !important",display:"flex",alignItems:"center",gap:.5}},children:m.map(h=>i.jsxs(ze,{value:h,sx:{fontSize:"0.75rem",display:"flex",gap:.5},children:[i.jsx(un,{provider:c[h],isDark:n==="dark"}),h]},h))}),i.jsx(ve,{title:u.I18n.t("Mention scripts as context for the AI. Use @all for all scripts or @scriptName for a specific one."),enterDelay:500,children:i.jsx(we,{size:"small",onClick:A,sx:{p:"3px",color:v?"primary.main":"text.secondary",border:"1px solid",borderColor:v?"primary.main":"text.secondary",bgcolor:v?void 0:"action.hover",borderRadius:3,"&:hover":{borderColor:"text.disabled",bgcolor:"action.hover"}},children:i.jsx(Ct,{sx:{fontSize:16}})})}),i.jsx($,{sx:{flex:1}}),i.jsxs(Oe,{variant:"caption",sx:{color:"text.disabled",fontSize:"0.65rem",mr:.5,whiteSpace:"nowrap"},children:["Enter ",u.I18n.t("to send")]}),i.jsx(ve,{title:`${u.I18n.t("Send")} (Enter)`,children:i.jsx("span",{children:i.jsx(we,{color:"primary",onClick:de,disabled:e||!S.trim(),size:"small",sx:{p:.25},children:i.jsx(Et,{sx:{fontSize:18}})})})})]})]})]})},Tn=({socket:r,runningInstances:e,themeType:n,currentCode:t,currentLanguage:o,selectedCode:s,allScripts:d,editorApi:m,aiActionRequest:c,onAiActionConsumed:p,onRegisterInlineAsk:g,onInsertCode:a,onShowDiff:y,onApplyCode:l,currentScriptId:S,onClose:b})=>{var ke;const v=ne(null),F=Ae(()=>({socket:r,runningInstances:e,currentCode:t,currentLanguage:o,allScripts:d,editorApi:m,currentScriptId:S}),[r,e,t,o,d,m,S]),{messages:E,isLoading:I,error:x,model:w,availableModels:M,modelProviderMap:re,modelsLoading:Y,modelsError:_,lastContextInfo:G,mode:le,setMode:K,setModel:de,sendMessage:T,triggerAiAction:A,askInline:X,clearChat:Q,retryLoadModels:h}=Zt(F);xe(()=>(g==null||g(X),()=>g==null?void 0:g(null)),[X,g]);const C=ne(null);xe(()=>{!c||C.current===c||(C.current=c,A(c),p==null||p())},[c,A,p]),xe(()=>{var J;(J=v.current)==null||J.scrollIntoView({behavior:"smooth"})},[E]);const k=U(J=>{a==null||a(J)},[a]),z=U((J,ue)=>{y==null||y(J,ue)},[y]),se=U(J=>{l==null||l(J)},[l]);return i.jsxs($,{sx:{display:"flex",flexDirection:"column",height:"100%",bgcolor:"background.default","& .ai-chat-inline-code":{backgroundColor:"action.selected",color:"text.primary",border:"1px solid",borderColor:"divider"}},children:[i.jsxs($,{sx:{display:"flex",alignItems:"center",gap:1,px:1,py:.5,borderBottom:"1px solid",borderColor:"divider",bgcolor:n==="dark"?"grey.900":"grey.100",flexShrink:0},children:[i.jsx(Oe,{variant:"subtitle2",sx:{fontWeight:600,flex:1,color:"text.primary"},children:u.I18n.t("AI Chat")}),Y&&i.jsx(Ve,{size:16}),i.jsx(ve,{title:u.I18n.t("New chat"),children:i.jsx(we,{size:"small",onClick:Q,children:i.jsx(_t,{sx:{fontSize:18}})})}),i.jsx(ve,{title:u.I18n.t("Close"),children:i.jsx(we,{size:"small",onClick:b,children:i.jsx(jt,{sx:{fontSize:18}})})})]}),(x||_)&&i.jsx(ht,{severity:"error",sx:{m:1,py:0},action:_?i.jsx(we,{size:"small",onClick:h,children:i.jsx(xt,{sx:{fontSize:16}})}):void 0,children:x||_}),G&&i.jsx(Oe,{variant:"caption",sx:{px:1.5,py:.25,color:"text.secondary",fontSize:"0.7rem",bgcolor:"action.hover",borderBottom:"1px solid",borderColor:"divider",flexShrink:0},children:G}),i.jsxs($,{sx:{flex:1,overflow:"auto",py:1},children:[E.length===0&&!I&&i.jsxs($,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",color:"text.secondary",px:3,textAlign:"center"},children:[i.jsx(Oe,{variant:"body2",sx:{mb:1},children:u.I18n.t("Ask questions about your script, request changes, or generate new code.")}),i.jsxs(Oe,{variant:"caption",color:"text.disabled",children:["Enter ",u.I18n.t("to send"),", Shift+Enter ",u.I18n.t("for new line")]})]}),E.filter(J=>J.role!=="system").map(J=>i.jsx(an,{message:J,themeType:n,currentLanguage:o,onInsertCode:k,onShowDiff:z,onApplyCode:se},J.id)),I&&((ke=E[E.length-1])==null?void 0:ke.content)===""&&i.jsxs($,{sx:{display:"flex",alignItems:"center",gap:1,px:2,py:1},children:[i.jsx(Ve,{size:16}),i.jsx(Oe,{variant:"caption",color:"text.secondary",children:u.I18n.t("Thinking...")})]}),i.jsx("div",{ref:v})]}),i.jsx(pn,{onSend:T,disabled:I||M.length===0,themeType:n,hasSelection:!!s,selectionText:s,allScripts:d,model:w,availableModels:M,modelProviderMap:re,modelsLoading:Y,onModelChange:de,mode:le,onModeChange:K,currentLanguage:o})]})};export{Tn as default};
315
+ `);if(k&&z){h.preventDefault(),_.current<Y.current.length-1?(_.current++,b(Y.current[_.current])):(_.current=-1,b(G.current));return}}h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),de())},[de,v,K,x,T,S]);return i.jsxs($,{sx:{borderTop:"1px solid",borderColor:"divider",position:"relative"},children:[v&&K.length>0&&i.jsx(dt,{elevation:4,sx:{position:"absolute",bottom:"100%",left:8,right:8,maxHeight:200,overflow:"auto",zIndex:10,mb:.5},children:i.jsx(ut,{dense:!0,disablePadding:!0,children:K.slice(0,15).map((h,C)=>i.jsx(mt,{selected:C===x,onClick:()=>T(h.id),sx:{py:.25,minHeight:32},children:i.jsx(pt,{primary:h.label,secondary:h.description,primaryTypographyProps:{fontSize:"0.8rem",fontWeight:500},secondaryTypographyProps:{fontSize:"0.7rem"}})},h.id))})}),a==="code"&&i.jsx(Fe,{label:`${u.I18n.t("mention @devices")} — ${u.I18n.t("Smart home devices")}`,size:"small",variant:"outlined",sx:{mx:1,mt:.5,maxWidth:"calc(100% - 16px)"}}),t&&o&&i.jsx(Fe,{icon:i.jsx(bt,{sx:{fontSize:14}}),label:u.I18n.t("Selected code as context"),size:"small",variant:"outlined",sx:{mx:1,mt:.5,maxWidth:"calc(100% - 16px)"}}),i.jsxs($,{sx:{mx:1,mt:.5,mb:.5,border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden","&:focus-within":{borderColor:"primary.main"}},children:[i.jsx(ft,{inputRef:M,fullWidth:!0,multiline:!0,maxRows:6,placeholder:u.I18n.t("Ask about your script..."),value:S,onChange:X,onKeyDown:Q,disabled:e,onBlur:()=>{setTimeout(()=>H(!1),200)},variant:"standard",slotProps:{input:{disableUnderline:!0}},sx:{px:1.5,pt:1,pb:.5,"& .MuiInputBase-root":{fontSize:"0.875rem"}}}),i.jsxs($,{sx:{display:"flex",alignItems:"center",gap:.75,px:1,pb:.5},children:[i.jsx(ve,{title:i.jsxs($,{sx:{fontSize:"0.8rem",lineHeight:1.5,maxWidth:360},children:[i.jsx($,{sx:{fontWeight:600,mb:.75},children:u.I18n.t("AI chat mode")}),i.jsxs($,{sx:{mb:.75},children:[i.jsxs("strong",{children:["💬 ",u.I18n.t("Chat")]})," —"," ",u.I18n.t("Plain conversation. Use for questions, explanations, syntax help. Does not read or modify your scripts.")]}),i.jsxs($,{sx:{mb:.75},children:[i.jsxs("strong",{children:["🤖 ",u.I18n.t("Agent")]})," —"," ",u.I18n.t('For larger models with tool support. The AI can read, create, and edit scripts, look up datapoints, and browse the object tree useful for "create a script that...", "which scripts use this state?" or "analyze my light script".')]}),i.jsxs($,{children:[i.jsxs("strong",{children:["💻 ",u.I18n.t("Code")]})," —"," ",u.I18n.t('For smaller models without tool support. Two-step script generator (plan then code) useful for "create a script that..." or "write a Blockly rule for...". Output goes into the editor for smart-apply.')]})]}),enterDelay:400,placement:"left",children:i.jsxs(He,{value:a,onChange:h=>y(h.target.value),size:"small",variant:"standard",disableUnderline:!0,sx:{fontSize:"0.7rem",color:"text.secondary",border:"1px solid",borderColor:"text.secondary",borderRadius:3,bgcolor:"action.hover",px:.75,"&:hover":{borderColor:"text.disabled",bgcolor:"action.hover"},"& .MuiSelect-select":{py:"2px",pr:"18px !important",display:"flex",alignItems:"center",gap:.5}},children:[i.jsx(ze,{value:"chat",sx:{fontSize:"0.75rem"},title:u.I18n.t("Plain conversation. Best for: general questions, syntax help, concept explanations."),children:"💬 Chat"}),i.jsx(ze,{value:"agent",sx:{fontSize:"0.75rem"},title:u.I18n.t("For larger models with tool support. Best for: creating, editing, or analyzing scripts; finding datapoint usages; inspecting the object tree."),children:"🤖 Agent"}),i.jsx(ze,{value:"code",sx:{fontSize:"0.75rem"},title:u.I18n.t("For smaller models without tool support. Best for: creating new JavaScript/TypeScript or Blockly scripts from a description."),children:"💻 Code"})]})}),i.jsx(He,{value:d,onChange:h=>g(h.target.value),size:"small",disabled:p||m.length===0,variant:"standard",disableUnderline:!0,sx:{fontSize:"0.7rem",color:"text.secondary",border:"1px solid",borderColor:"text.secondary",borderRadius:3,bgcolor:"action.hover",px:.75,"&:hover":{borderColor:"text.disabled",bgcolor:"action.hover"},"& .MuiSelect-select":{py:"2px",pr:"18px !important",display:"flex",alignItems:"center",gap:.5}},children:m.map(h=>i.jsxs(ze,{value:h,sx:{fontSize:"0.75rem",display:"flex",gap:.5},children:[i.jsx(un,{provider:c[h],isDark:n==="dark"}),h]},h))}),i.jsx(ve,{title:u.I18n.t("Mention scripts as context for the AI. Use @all for all scripts or @scriptName for a specific one."),enterDelay:500,children:i.jsx(we,{size:"small",onClick:U,sx:{p:"3px",color:v?"primary.main":"text.secondary",border:"1px solid",borderColor:v?"primary.main":"text.secondary",bgcolor:v?void 0:"action.hover",borderRadius:3,"&:hover":{borderColor:"text.disabled",bgcolor:"action.hover"}},children:i.jsx(Ct,{sx:{fontSize:16}})})}),i.jsx($,{sx:{flex:1}}),i.jsxs(Oe,{variant:"caption",sx:{color:"text.disabled",fontSize:"0.65rem",mr:.5,whiteSpace:"nowrap"},children:["Enter ",u.I18n.t("to send")]}),i.jsx(ve,{title:`${u.I18n.t("Send")} (Enter)`,children:i.jsx("span",{children:i.jsx(we,{color:"primary",onClick:de,disabled:e||!S.trim(),size:"small",sx:{p:.25},children:i.jsx(Et,{sx:{fontSize:18}})})})})]})]})]})},Tn=({socket:r,runningInstances:e,themeType:n,currentCode:t,currentLanguage:o,selectedCode:s,allScripts:d,editorApi:m,aiActionRequest:c,onAiActionConsumed:p,onRegisterInlineAsk:g,onInsertCode:a,onShowDiff:y,onApplyCode:l,currentScriptId:S,onClose:b})=>{var ke;const v=ne(null),H=Ue(()=>({socket:r,runningInstances:e,currentCode:t,currentLanguage:o,allScripts:d,editorApi:m,currentScriptId:S}),[r,e,t,o,d,m,S]),{messages:E,isLoading:I,error:x,model:w,availableModels:M,modelProviderMap:re,modelsLoading:Y,modelsError:_,lastContextInfo:G,mode:le,setMode:K,setModel:de,sendMessage:T,triggerAiAction:U,askInline:X,clearChat:Q,retryLoadModels:h}=Zt(H);xe(()=>(g==null||g(X),()=>g==null?void 0:g(null)),[X,g]);const C=ne(null);xe(()=>{!c||C.current===c||(C.current=c,U(c),p==null||p())},[c,U,p]),xe(()=>{var J;(J=v.current)==null||J.scrollIntoView({behavior:"smooth"})},[E]);const k=A(J=>{a==null||a(J)},[a]),z=A((J,ue)=>{y==null||y(J,ue)},[y]),se=A(J=>{l==null||l(J)},[l]);return i.jsxs($,{sx:{display:"flex",flexDirection:"column",height:"100%",bgcolor:"background.default","& .ai-chat-inline-code":{backgroundColor:"action.selected",color:"text.primary",border:"1px solid",borderColor:"divider"}},children:[i.jsxs($,{sx:{display:"flex",alignItems:"center",gap:1,px:1,py:.5,borderBottom:"1px solid",borderColor:"divider",bgcolor:n==="dark"?"grey.900":"grey.100",flexShrink:0},children:[i.jsx(Oe,{variant:"subtitle2",sx:{fontWeight:600,flex:1,color:"text.primary"},children:u.I18n.t("AI Chat")}),Y&&i.jsx(Ve,{size:16}),i.jsx(ve,{title:u.I18n.t("New chat"),children:i.jsx(we,{size:"small",onClick:Q,children:i.jsx(_t,{sx:{fontSize:18}})})}),i.jsx(ve,{title:u.I18n.t("Close"),children:i.jsx(we,{size:"small",onClick:b,children:i.jsx(jt,{sx:{fontSize:18}})})})]}),(x||_)&&i.jsx(ht,{severity:"error",sx:{m:1,py:0},action:_?i.jsx(we,{size:"small",onClick:h,children:i.jsx(xt,{sx:{fontSize:16}})}):void 0,children:x||_}),G&&i.jsx(Oe,{variant:"caption",sx:{px:1.5,py:.25,color:"text.secondary",fontSize:"0.7rem",bgcolor:"action.hover",borderBottom:"1px solid",borderColor:"divider",flexShrink:0},children:G}),i.jsxs($,{sx:{flex:1,overflow:"auto",py:1},children:[E.length===0&&!I&&i.jsxs($,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",color:"text.secondary",px:3,textAlign:"center"},children:[i.jsx(Oe,{variant:"body2",sx:{mb:1},children:u.I18n.t("Ask questions about your script, request changes, or generate new code.")}),i.jsxs(Oe,{variant:"caption",color:"text.disabled",children:["Enter ",u.I18n.t("to send"),", Shift+Enter ",u.I18n.t("for new line")]})]}),E.filter(J=>J.role!=="system").map(J=>i.jsx(an,{message:J,themeType:n,currentLanguage:o,onInsertCode:k,onShowDiff:z,onApplyCode:se},J.id)),I&&((ke=E[E.length-1])==null?void 0:ke.content)===""&&i.jsxs($,{sx:{display:"flex",alignItems:"center",gap:1,px:2,py:1},children:[i.jsx(Ve,{size:16}),i.jsx(Oe,{variant:"caption",color:"text.secondary",children:u.I18n.t("Thinking...")})]}),i.jsx("div",{ref:v})]}),i.jsx(pn,{onSend:T,disabled:I||M.length===0,themeType:n,hasSelection:!!s,selectionText:s,allScripts:d,model:w,availableModels:M,modelProviderMap:re,modelsLoading:Y,onModelChange:de,mode:le,onModeChange:K,currentLanguage:o})]})};export{Tn as default};
@@ -1,2 +1,2 @@
1
- import{j as t}from"./createSvgIcon-DYs_tNrE.js";import{a as n}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as l,a as c,b as h,z as a,h as d,i}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-CV1_X-Lf.js";import{_ as o}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import p from"./ScriptEditorVanillaMonaco-bJua4sm1.js";import{S as m}from"./Save-CkuNSiWL.js";import{a as g}from"./index-wHNMOf-c.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./preload-helper-BDBacUwf.js";import"./index-CYbVtccs.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-DNrEsMrg.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-CIXm_zPk.js";const s={textArea:{width:"calc(100% - 10px)",resize:"none"},dialog:{height:"95%"},fullHeight:{height:"100%",overflow:"hidden"},args:r=>({color:r.palette.mode==="dark"?"white":"black",height:30,width:"100%",fontSize:16}),argsTitle:r=>({color:r.palette.mode==="dark"?"white":"black",fontWeight:"bold"})};class D extends n.Component{constructor(e){super(e),this.state={changed:!1,source:!e.source&&e.isReturn?`
1
+ import{j as t}from"./createSvgIcon-DYs_tNrE.js";import{a as n}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as l,a as c,b as h,z as a,h as d,i}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-CV1_X-Lf.js";import{_ as o}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import p from"./ScriptEditorVanillaMonaco-CaFyKuJ2.js";import{S as m}from"./Save-CkuNSiWL.js";import{a as g}from"./index-wHNMOf-c.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./preload-helper-BDBacUwf.js";import"./index-DSvAO584.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-DNrEsMrg.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-CIXm_zPk.js";const s={textArea:{width:"calc(100% - 10px)",resize:"none"},dialog:{height:"95%"},fullHeight:{height:"100%",overflow:"hidden"},args:r=>({color:r.palette.mode==="dark"?"white":"black",height:30,width:"100%",fontSize:16}),argsTitle:r=>({color:r.palette.mode==="dark"?"white":"black",fontWeight:"bold"})};class D extends n.Component{constructor(e){super(e),this.state={changed:!1,source:!e.source&&e.isReturn?`
2
2
  return false`:e.source}}componentDidMount(){setTimeout(()=>{var e;try{(e=window.document.getElementById("source-text-area"))==null||e.focus()}catch{}},100)}handleCancel(){this.props.onClose(!1)}handleOk(){(!this.props.isReturn||this.state.source.includes("return "))&&this.props.onClose(this.state.source)}onChange(e){this.setState({changed:!0,source:e})}render(){return t.jsxs(l,{onClose:()=>!1,maxWidth:"lg",sx:{"& .MuiDialog-paper":s.dialog},fullWidth:!0,open:!0,"aria-labelledby":"source-dialog-title",children:[t.jsx(c,{id:"source-dialog-title",children:o.I18n.t("Function editor")}),t.jsxs(h,{style:s.fullHeight,children:[this.props.args&&t.jsxs(a,{sx:s.args,children:[t.jsx(a,{component:"span",sx:s.argsTitle,children:o.I18n.t("function (")}),this.props.args,t.jsx(a,{component:"span",sx:s.argsTitle,children:")"})]},"arguments"),t.jsx(p,{triggerPrettier:1,adapterName:this.props.adapterName,runningInstances:this.props.runningInstances,style:{...s.textArea,height:this.props.args?"calc(100% - 30px)":"100%"},name:"blockly",socket:this.props.socket,readOnly:!1,checkJs:!1,changed:this.state.changed,code:this.state.source,isDark:this.props.themeType==="dark",onChange:e=>this.onChange(e),language:"javascript"},"scriptEditor")]}),t.jsxs(d,{children:[t.jsx(i,{variant:"contained",onClick:()=>this.handleOk(),color:"primary",startIcon:t.jsx(m,{}),children:o.I18n.t("Save")}),t.jsx(i,{color:"grey",variant:"contained",onClick:()=>this.handleCancel(),startIcon:t.jsx(g,{}),children:o.I18n.t("Cancel")})]})]})}}export{D as default};
@@ -1,3 +1,3 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-CYbVtccs.js","./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-DNrEsMrg.js","./preload-helper-BDBacUwf.js","./createSvgIcon-DYs_tNrE.js","./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js","./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js","./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js","./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js","./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js","./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-CV1_X-Lf.js","./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js","./index-wHNMOf-c.js","./inheritsLoose-CIXm_zPk.js","./index-BTsjunTt.css","./inlineDiffController-DBLpPOe2.js","./applyCodeEdit-BdRnbz2g.js","./inlineChatWidget-Cu6rb4Ar.js"])))=>i.map(i=>d[i]);
2
- import{_ as g}from"./preload-helper-BDBacUwf.js";import{j as m}from"./createSvgIcon-DYs_tNrE.js";import{a as v}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as T,a as N,b as M,h as A,i as w,Q as O,o as x,$ as j}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-CV1_X-Lf.js";import{n as E,Z as R}from"./index-wHNMOf-c.js";import{_ as p}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{h as V}from"./index-CYbVtccs.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-DNrEsMrg.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-CIXm_zPk.js";function K(k){return/^script\.js\.global\./.test(k)}let P=0;function $(k){const t=/\x1b\[[0-9;]*m/g;return k.replace(t,"")}class tt extends v.Component{monacoDiv=null;editor=null;monaco=window.monaco;get monacoTS(){var t,e;return(e=(t=this.monaco)==null?void 0:t.languages)==null?void 0:e.typescript}insert="";originalCode;runningInstancesStr;monacoCounter=0;location;breakpoints;lastSearch="";typings={};decorations=[];datapointProviderDisposable=null;inlineProviderDisposable=null;stateHoverDisposable=null;codeLensDisposable=null;inlineChatWidgetInstance=null;inlineDiffInstance=null;inlineDiffCssInjected=!1;triggerPrettier;contentChangeDisposable=null;mouseDownDisposable=null;constructor(t){super(t),this.state={name:"current",isDark:t.isDark||!1,language:t.language||"javascript",readOnly:t.readOnly||!1,alive:!0,check:!1,searchText:this.props.searchText||"",typingsLoaded:!1,showError:null},this.triggerPrettier=t.triggerPrettier,this.runningInstancesStr=JSON.stringify(this.props.runningInstances),this.originalCode=t.code||"",this.monacoDiv=v.createRef()}waitForMonaco(t){var i,o,n,r;let e=!!((o=(i=this.monacoTS)==null?void 0:i.typescriptDefaults)!=null&&o.getCompilerOptions);if(!e||!this.props.runningInstances){if(this.monaco=window.monaco,e=!!((r=(n=this.monacoTS)==null?void 0:n.typescriptDefaults)!=null&&r.getCompilerOptions),this.monacoCounter++,!e&&this.monacoCounter<20){console.log("wait for monaco loaded"),setTimeout(()=>this.waitForMonaco(t),200);return}this.monacoCounter>=20&&console.error("Cannot load monaco!")}else t&&t()}loadTypings(t){if(!this.editor)return;t||=this.props.runningInstances;const e=t&&Object.keys(t).find(i=>t==null?void 0:t[i]);e&&this.props.socket.sendTo(e.replace("system.adapter.",""),"loadTypings",null).then(i=>{this.setState({alive:!0,check:!0,typingsLoaded:!0}),this.setTypeCheck(!0),i.typings?(this.typings=i.typings,this.setEditorTypings(this.state.name)):console.error(`failed to load typings: ${i.error}`)})}componentDidMount(){var i,o,n,r,s,d,c,a;this.undo,this.redo,this.showInlineDiff,this.getEditorSelection,this.getEditorContent,this.getCursorPosition,this.highlightLineRange,this.goToLine,this.replaceSelection,this.getDiagnostics,this.getDocumentSymbols;let t=!!((o=(i=this.monacoTS)==null?void 0:i.typescriptDefaults)!=null&&o.getCompilerOptions);if((!t||!this.props.runningInstances)&&(this.monaco=window.monaco,t=!!((r=(n=this.monacoTS)==null?void 0:n.typescriptDefaults)!=null&&r.getCompilerOptions),!t)){console.log("wait for monaco loaded..."),this.waitForMonaco(()=>this.componentDidMount());return}if(!this.editor&&t&&this.monaco){console.log("Init editor"),(d=(s=this.props).onRegisterSelect)==null||d.call(s,()=>{var l;if(this.editor){const u=this.editor.getSelection();if(u)return(l=this.editor.getModel())==null?void 0:l.getValueInRange(u)}});const h=this.monacoTS.typescriptDefaults.getCompilerOptions();h.allowJs=!0,h.checkJs=this.props.checkJs!==!1,h.noLib=!0,h.lib=[],h.useUnknownInCatchVariables=!1,h.moduleResolution=this.monacoTS.ModuleResolutionKind.NodeJs,h.target=this.monacoTS.ScriptTarget.ESNext,h.module=this.monacoTS.ModuleKind.ESNext,h.allowNonTsExtensions=!0,this.monacoTS.typescriptDefaults.setCompilerOptions(h),this.setTypeCheck(!1),(c=this.monacoDiv)!=null&&c.current&&(this.editor=this.monaco.editor.create((a=this.monacoDiv)==null?void 0:a.current,{lineNumbers:"on",scrollBeyondLastLine:!1,automaticLayout:!0,glyphMargin:!!this.props.breakpoints,colorDecorators:!0}),this.contentChangeDisposable=this.editor.onDidChangeModelContent(()=>this.onChange()),this.monaco&&!this.datapointProviderDisposable&&g(async()=>{const{registerDatapointProvider:l}=await import("./AiDatapointProvider-B0i3I5Fm.js");return{registerDatapointProvider:l}},[],import.meta.url).then(({registerDatapointProvider:l})=>{this.monaco&&(this.datapointProviderDisposable=l(this.monaco,this.props.socket))}).catch(()=>{}),this.monaco&&!this.stateHoverDisposable&&g(async()=>{const{registerStateHoverProvider:l}=await import("./stateHoverProvider-CGChzV5W.js");return{registerStateHoverProvider:l}},[],import.meta.url).then(({registerStateHoverProvider:l})=>{this.monaco&&(this.stateHoverDisposable=l(this.monaco,this.props.socket))}).catch(()=>{}),this.props.aiCompletionsEnabled&&this.monaco&&!this.inlineProviderDisposable&&g(async()=>{const{registerAiInlineProvider:l}=await import("./AiInlineProvider-DkgjVSFQ.js");return{registerAiInlineProvider:l}},[],import.meta.url).then(({registerAiInlineProvider:l})=>{this.monaco&&(this.inlineProviderDisposable=l(this.monaco,this.props.socket,this.props.runningInstances))}).catch(()=>{}),this.loadTypings(),this.props.onForceSave&&this.editor.addCommand(this.monaco.KeyMod.CtrlCmd|this.monaco.KeyCode.KeyS,()=>this.props.onForceSave&&this.props.onForceSave()),this.registerAiActions(),this.monaco&&this.editor&&this.props.onAiAction&&!this.codeLensDisposable&&g(async()=>{const{registerAiCodeLensProvider:l}=await import("./index-CYbVtccs.js").then(u=>u.o);return{registerAiCodeLensProvider:l}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url).then(({registerAiCodeLensProvider:l})=>{this.monaco&&this.editor&&this.props.onAiAction&&(this.codeLensDisposable=l(this.monaco,this.editor,(u,y,f,b,C)=>{var L,I,S;const D=(L=this.editor)==null?void 0:L.getModel(),_=D?D.getLineMaxColumn(Math.min(C,D.getLineCount())):1;(S=(I=this.props).onAiAction)==null||S.call(I,{action:u,code:y,rangeLabel:f,range:{startLine:b,startColumn:1,endLine:C,endColumn:_},kind:"codelens"})}))}).catch(()=>{}),setTimeout(()=>{this.highlightText(this.state.searchText),this.location=this.props.location||void 0,this.breakpoints=this.props.breakpoints,this.showDecorators()}))}const e={selectOnLineNumbers:!0,scrollBeyondLastLine:!1,automaticLayout:!0,readOnly:this.state.readOnly,language:this.state.language,isDark:this.state.isDark};this.setEditorOptions(e),this.editor&&(this.editor.focus(),this.editor.setValue(this.originalCode),this.props.onToggleBreakpoint&&(this.mouseDownDisposable=this.editor.onMouseDown(h=>{var u;const l=h.target;this.props.onToggleBreakpoint&&((u=l.detail)==null?void 0:u.glyphMarginLeft)!==void 0&&l.position&&this.props.onToggleBreakpoint(l.position.lineNumber-1)})))}setEditorOptions(t){var e;t&&(t.language&&this.setEditorLanguage(t.language),this.editor&&(t.readOnly!==void 0&&this.editor.updateOptions({readOnly:t.readOnly}),t.lineWrap!==void 0&&this.editor.updateOptions({wordWrap:t.lineWrap?"on":"off"})),t.typeCheck!==void 0&&this.setTypeCheck(t.typeCheck),t.isDark!==void 0&&((e=this.monaco)==null||e.editor.setTheme(t.isDark?"vs-dark":"vs")))}componentWillUnmount(){var t,e,i,o,n,r,s,d,c;(t=this.contentChangeDisposable)==null||t.dispose(),this.contentChangeDisposable=null,(e=this.mouseDownDisposable)==null||e.dispose(),this.mouseDownDisposable=null,(i=this.datapointProviderDisposable)==null||i.dispose(),this.datapointProviderDisposable=null,g(async()=>{const{clearDatapointCache:a}=await import("./AiDatapointProvider-B0i3I5Fm.js");return{clearDatapointCache:a}},[],import.meta.url).then(({clearDatapointCache:a})=>a()).catch(()=>{}),(o=this.inlineProviderDisposable)==null||o.dispose(),this.inlineProviderDisposable=null,(n=this.stateHoverDisposable)==null||n.dispose(),this.stateHoverDisposable=null,g(async()=>{const{clearStateHoverCache:a}=await import("./stateHoverProvider-CGChzV5W.js");return{clearStateHoverCache:a}},[],import.meta.url).then(({clearStateHoverCache:a})=>a()).catch(()=>{}),(r=this.codeLensDisposable)==null||r.dispose(),this.codeLensDisposable=null,(s=this.inlineChatWidgetInstance)==null||s.dispose(),this.inlineChatWidgetInstance=null,this.hideInlineDiff(),this.editor&&((c=(d=this.props).onRegisterSelect)==null||c.call(d,null),this.editor.dispose(),this.editor=null)}async doPrettier(){var i,o,n,r;const t=this.props.runningInstances&&Object.keys(this.props.runningInstances).find(s=>{var d;return(d=this.props.runningInstances)==null?void 0:d[s]});if(!t){window.alert(p.I18n.t("No script adapter instance found to format the code"));return}const e=await this.props.socket.sendTo(t.replace("system.adapter.",""),"prettier",{code:(i=this.editor)==null?void 0:i.getValue(),type:this.state.language});e.error?this.setState({showError:{title:p.I18n.t("Error formatting code"),message:$(e.error)}}):e.code&&((o=this.editor)==null||o.setValue(e.code),(r=(n=this.props).onChange)==null||r.call(n,e.code),this.showDecorators())}setEditorLanguage(t){var i,o;if(!this.editor)return;const e=this.editor.getModel();if(e){const n=e.getValue(),r=e.uri.path,s=typeof r=="string"&&r.includes(".")?r.substring(0,r.lastIndexOf(".")):"index",d=t==="javascript"?"js":t==="typescript"?"ts":t;e.dispose();const c=t==="javascript"||t==="typescript"?"typescript":t,a=(i=this.monaco)==null?void 0:i.editor.createModel(n,c,this.monaco.Uri.from({scheme:window.location.protocol.replace(":",""),path:`${s}${P++}.${d}`}));a&&(this.editor.setModel(a),(o=this.contentChangeDisposable)==null||o.dispose(),this.contentChangeDisposable=this.editor.onDidChangeModelContent(()=>this.onChange()))}}setTypeCheck(t){var i,o;const e={noSemanticValidation:!this.state.alive||!t,noSyntaxValidation:!this.state.alive};(i=this.monacoTS)==null||i.typescriptDefaults.setDiagnosticsOptions(e),(o=this.monacoTS)==null||o.javascriptDefaults.setDiagnosticsOptions({noSemanticValidation:!this.state.alive||!t,noSyntaxValidation:!this.state.alive})}setEditorTypings(t=""){var n,r,s,d;const e=K(t),i=`${t}.d.ts`,o=[];for(const c of Object.keys(this.typings))e&&(c==="global.d.ts"||c.startsWith("script.js.global")&&c!==i)||o.push({filePath:c,content:this.typings[c]});if((r=(n=this.monacoTS)==null?void 0:n.typescriptDefaults)!=null&&r.setExtraLibs)this.monacoTS.typescriptDefaults.setExtraLibs(o);else if((d=(s=this.monacoTS)==null?void 0:s.typescriptDefaults)!=null&&d.addExtraLib){const c=this.monacoTS.typescriptDefaults.getExtraLibs();o.forEach(a=>{!c[a.filePath]&&this.monaco&&this.monacoTS.typescriptDefaults.addExtraLib(a.content,a.filePath)})}}undo(){var t;(t=this.editor)==null||t.trigger("toolbar","undo",null)}redo(){var t;(t=this.editor)==null||t.trigger("toolbar","redo",null)}insertTextIntoEditor(t){if(!this.editor||!this.monaco)return;const e=this.editor.getSelection();if(e){const i=new this.monaco.Range(e.startLineNumber,e.startColumn,e.endLineNumber,e.endColumn);this.editor.executeEdits("",[{range:i,text:t,forceMoveMarkers:!0}])}this.editor.focus()}highlightText(t){var o;if(!this.editor||!this.monaco)return 0;const e=t?(o=this.editor.getModel())==null?void 0:o.findMatches(t,!0,!1,!1,null,!0):void 0;if(e!=null&&e.length)return e.forEach(n=>{var r;return(r=this.editor)==null?void 0:r.setSelection(n.range)}),this.editor.revealLine(e[0].range.startLineNumber),e.length;const i=this.editor.getPosition();if(i){const n=i.lineNumber,r=i.column;this.editor.setSelection(new this.monaco.Range(n,r,n,r))}return 0}showInlineDiff(t){if(!this.editor||!this.monaco)return;const e=this.editor,i=this.monaco;this.hideInlineDiff(),g(async()=>{const{InlineDiffController:o,INLINE_DIFF_CSS:n}=await import("./inlineDiffController-DBLpPOe2.js");return{InlineDiffController:o,INLINE_DIFF_CSS:n}},__vite__mapDeps([14,10,15]),import.meta.url).then(({InlineDiffController:o,INLINE_DIFF_CSS:n})=>{if(!this.inlineDiffCssInjected){const s=document.createElement("style");s.textContent=n,s.setAttribute("data-iob-aichat","inline-diff"),document.head.appendChild(s),this.inlineDiffCssInjected=!0}const r=new o(e,i,{range:t.range,originalText:t.originalText,modifiedText:t.modifiedText,onAccepted:()=>{var s;this.inlineDiffInstance=null,(s=t.onAccepted)==null||s.call(t)},onRejected:()=>{var s;this.inlineDiffInstance=null,(s=t.onRejected)==null||s.call(t)}});this.inlineDiffInstance=r,r.show()}).catch(()=>{})}hideInlineDiff(){if(this.inlineDiffInstance){try{this.inlineDiffInstance.dispose()}catch{}this.inlineDiffInstance=null}}showInlineChatWidget(){if(!this.editor||!this.monaco||!this.props.onInlineAsk)return;if(this.inlineChatWidgetInstance){this.inlineChatWidgetInstance.show();return}const t=this.editor,e=this.monaco,i=this.props.onInlineAsk,o=this.props.onAiAction;g(async()=>{const{InlineChatWidget:n}=await import("./inlineChatWidget-Cu6rb4Ar.js");return{InlineChatWidget:n}},__vite__mapDeps([16,10,15]),import.meta.url).then(({InlineChatWidget:n})=>{const r=new n(t,e,{onSubmit:async s=>i({question:s.question,selectedCode:s.selectedCode}),onEscalateToChat:s=>{o&&o({action:"ask",code:s.selectedCode,question:s.question,rangeLabel:s.range?`lines ${s.range.startLineNumber}-${s.range.endLineNumber}`:"whole file"})}});this.inlineChatWidgetInstance=r,r.show()}).catch(()=>{})}registerAiActions(){if(!this.editor||!this.monaco||!this.props.onAiAction)return;const t=this.monaco,e=(o,n={})=>{if(!this.editor||!this.props.onAiAction)return;const r=this.editor.getModel();if(!r)return;const s=this.editor.getSelection(),d=s&&!s.isEmpty();let c,a,h,l="selection";if(d)c=r.getValueInRange(s),a=s.startLineNumber===s.endLineNumber?`line ${s.startLineNumber}`:`lines ${s.startLineNumber}-${s.endLineNumber}`,h={startLine:s.startLineNumber,startColumn:s.startColumn,endLine:s.endLineNumber,endColumn:s.endColumn},l="selection";else{const u=this.editor.getPosition();let y=null;if(u)try{y=V(r.getValue(),u.lineNumber)}catch{}if(y){const f=y.startLine,b=y.endLine,C=r.getLineMaxColumn(b),D=new t.Range(f,1,b,C);c=r.getValueInRange(D),a=f===b?`line ${f}`:`lines ${f}-${b}`,h={startLine:f,startColumn:1,endLine:b,endColumn:C},l="codelens"}else c=r.getValue(),a="whole file",l="none"}this.props.onAiAction({action:o,code:c,rangeLabel:a,range:h,kind:l,...n})},i=[{id:"iobroker.ai.inline",label:`🤖 ${p.I18n.t("AI: Inline chat…")}`,keybindings:[t.KeyMod.CtrlCmd|t.KeyMod.Alt|t.KeyCode.KeyI],order:1,run:()=>{if(this.props.onInlineAsk)this.showInlineChatWidget();else{const o=window.prompt(p.I18n.t("Ask the AI about the selected code:"));o&&o.trim()&&e("ask",{question:o.trim()})}}},{id:"iobroker.ai.explain",label:`💡 ${p.I18n.t("AI: Explain")}`,keybindings:[t.KeyMod.CtrlCmd|t.KeyMod.Alt|t.KeyCode.KeyE],order:2,run:()=>e("explain")},{id:"iobroker.ai.refactor",label:`🔧 ${p.I18n.t("AI: Refactor")}`,keybindings:[t.KeyMod.CtrlCmd|t.KeyMod.Alt|t.KeyCode.KeyR],order:3,run:()=>e("refactor")},{id:"iobroker.ai.comment",label:`💬 ${p.I18n.t("AI: Add comments")}`,keybindings:[t.KeyMod.CtrlCmd|t.KeyMod.Alt|t.KeyCode.KeyC],order:4,run:()=>e("comment")},{id:"iobroker.ai.fix",label:`🛠️ ${p.I18n.t("AI: Fix problem")}`,keybindings:[t.KeyMod.CtrlCmd|t.KeyMod.Alt|t.KeyCode.KeyF],order:5,run:()=>{var n,r;let o;try{const s=(n=this.editor)==null?void 0:n.getModel(),d=(r=this.editor)==null?void 0:r.getPosition();if(s&&d){const a=t.editor.getModelMarkers({resource:s.uri}).find(h=>d.lineNumber>=h.startLineNumber&&d.lineNumber<=h.endLineNumber);a&&(o=a.message)}}catch{}e("fix",{diagnostic:o})}},{id:"iobroker.ai.tests",label:`✅ ${p.I18n.t("AI: Suggest tests")}`,order:6,run:()=>e("tests")}];for(const o of i)try{this.editor.addAction({id:o.id,label:o.label,contextMenuGroupId:"aichat",contextMenuOrder:o.order,keybindings:o.keybindings,run:()=>o.run()})}catch{}}getEditorSelection(){if(!this.editor)return null;const t=this.editor.getSelection();if(!t||t.isEmpty())return null;const e=this.editor.getModel();return e?{text:e.getValueInRange(t),range:{startLine:t.startLineNumber,startColumn:t.startColumn,endLine:t.endLineNumber,endColumn:t.endColumn}}:null}getEditorContent(){var t,e;return((e=(t=this.editor)==null?void 0:t.getModel())==null?void 0:e.getValue())??""}getCursorPosition(){var e;const t=(e=this.editor)==null?void 0:e.getPosition();return t?{line:t.lineNumber,column:t.column}:null}highlightLineRange(t,e){if(!this.editor||!this.monaco)return!1;const i=this.editor.getModel();if(!i)return!1;const o=i.getLineCount(),n=Math.max(1,Math.min(t,o)),r=Math.max(n,Math.min(e,o)),s=i.getLineMaxColumn(r);return this.editor.setSelection(new this.monaco.Range(n,1,r,s)),this.editor.revealLineInCenter(n),!0}goToLine(t,e=1){if(!this.editor||!this.monaco)return!1;const i=this.editor.getModel();if(!i)return!1;const o=i.getLineCount(),n=Math.max(1,Math.min(t,o));return this.editor.setPosition({lineNumber:n,column:e}),this.editor.revealLineInCenter(n),this.editor.focus(),!0}replaceSelection(t){if(!this.editor||!this.monaco)return!1;const e=this.editor.getSelection();if(!e)return!1;const i=new this.monaco.Range(e.startLineNumber,e.startColumn,e.endLineNumber,e.endColumn);return this.editor.executeEdits("",[{range:i,text:t,forceMoveMarkers:!0}]),this.editor.focus(),!0}getDiagnostics(){if(!this.editor||!this.monaco)return[];const t=this.editor.getModel();if(!t)return[];const e=this.monaco.editor.getModelMarkers({resource:t.uri}),i={8:"error",4:"warning",2:"info",1:"hint"};return e.map(o=>({line:o.startLineNumber,column:o.startColumn,endLine:o.endLineNumber,endColumn:o.endColumn,severity:i[o.severity]||"info",message:o.message,...o.source?{source:o.source}:{}}))}async getDocumentSymbols(){var i;if(!this.editor||!this.monaco)return[];const t=this.editor.getModel();if(!t)return[];const e=[];try{const o=this.monaco.languages,n=(i=o.getDocumentSymbolProviders)==null?void 0:i.call(o,t);if(n!=null&&n.length){const r={0:"file",1:"module",2:"namespace",3:"package",4:"class",5:"method",6:"property",7:"field",8:"constructor",9:"enum",10:"interface",11:"function",12:"variable",13:"constant",14:"string",15:"number",16:"boolean",17:"array",18:"object",19:"key",20:"null",21:"enum-member",22:"struct",23:"event",24:"operator",25:"type-parameter"};for(const s of n){const d={isCancellationRequested:!1},c=await s.provideDocumentSymbols(t,d);if(!c)continue;const a=h=>{var l;for(const u of h)e.push({name:u.name,kind:r[u.kind]||String(u.kind),line:u.range.startLineNumber,endLine:u.range.endLineNumber,...u.detail?{detail:u.detail}:{}}),(l=u.children)!=null&&l.length&&a(u.children)};if(a(c),e.length)break}}}catch{}if(e.length===0){const n=t.getValue().split(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DSvAO584.js","./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-DNrEsMrg.js","./preload-helper-BDBacUwf.js","./createSvgIcon-DYs_tNrE.js","./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js","./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js","./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js","./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js","./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js","./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-CV1_X-Lf.js","./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js","./index-wHNMOf-c.js","./inheritsLoose-CIXm_zPk.js","./index-BTsjunTt.css","./inlineDiffController-DBLpPOe2.js","./applyCodeEdit-BdRnbz2g.js","./inlineChatWidget-Cu6rb4Ar.js"])))=>i.map(i=>d[i]);
2
+ import{_ as g}from"./preload-helper-BDBacUwf.js";import{j as m}from"./createSvgIcon-DYs_tNrE.js";import{a as v}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as T,a as N,b as M,h as A,i as w,Q as O,o as x,$ as j}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-CV1_X-Lf.js";import{n as E,Z as R}from"./index-wHNMOf-c.js";import{_ as p}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{h as V}from"./index-DSvAO584.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-DNrEsMrg.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-CIXm_zPk.js";function K(k){return/^script\.js\.global\./.test(k)}let P=0;function $(k){const t=/\x1b\[[0-9;]*m/g;return k.replace(t,"")}class tt extends v.Component{monacoDiv=null;editor=null;monaco=window.monaco;get monacoTS(){var t,e;return(e=(t=this.monaco)==null?void 0:t.languages)==null?void 0:e.typescript}insert="";originalCode;runningInstancesStr;monacoCounter=0;location;breakpoints;lastSearch="";typings={};decorations=[];datapointProviderDisposable=null;inlineProviderDisposable=null;stateHoverDisposable=null;codeLensDisposable=null;inlineChatWidgetInstance=null;inlineDiffInstance=null;inlineDiffCssInjected=!1;triggerPrettier;contentChangeDisposable=null;mouseDownDisposable=null;constructor(t){super(t),this.state={name:"current",isDark:t.isDark||!1,language:t.language||"javascript",readOnly:t.readOnly||!1,alive:!0,check:!1,searchText:this.props.searchText||"",typingsLoaded:!1,showError:null},this.triggerPrettier=t.triggerPrettier,this.runningInstancesStr=JSON.stringify(this.props.runningInstances),this.originalCode=t.code||"",this.monacoDiv=v.createRef()}waitForMonaco(t){var i,o,n,r;let e=!!((o=(i=this.monacoTS)==null?void 0:i.typescriptDefaults)!=null&&o.getCompilerOptions);if(!e||!this.props.runningInstances){if(this.monaco=window.monaco,e=!!((r=(n=this.monacoTS)==null?void 0:n.typescriptDefaults)!=null&&r.getCompilerOptions),this.monacoCounter++,!e&&this.monacoCounter<20){console.log("wait for monaco loaded"),setTimeout(()=>this.waitForMonaco(t),200);return}this.monacoCounter>=20&&console.error("Cannot load monaco!")}else t&&t()}loadTypings(t){if(!this.editor)return;t||=this.props.runningInstances;const e=t&&Object.keys(t).find(i=>t==null?void 0:t[i]);e&&this.props.socket.sendTo(e.replace("system.adapter.",""),"loadTypings",null).then(i=>{this.setState({alive:!0,check:!0,typingsLoaded:!0}),this.setTypeCheck(!0),i.typings?(this.typings=i.typings,this.setEditorTypings(this.state.name)):console.error(`failed to load typings: ${i.error}`)})}componentDidMount(){var i,o,n,r,s,d,c,a;this.undo,this.redo,this.showInlineDiff,this.getEditorSelection,this.getEditorContent,this.getCursorPosition,this.highlightLineRange,this.goToLine,this.replaceSelection,this.getDiagnostics,this.getDocumentSymbols;let t=!!((o=(i=this.monacoTS)==null?void 0:i.typescriptDefaults)!=null&&o.getCompilerOptions);if((!t||!this.props.runningInstances)&&(this.monaco=window.monaco,t=!!((r=(n=this.monacoTS)==null?void 0:n.typescriptDefaults)!=null&&r.getCompilerOptions),!t)){console.log("wait for monaco loaded..."),this.waitForMonaco(()=>this.componentDidMount());return}if(!this.editor&&t&&this.monaco){console.log("Init editor"),(d=(s=this.props).onRegisterSelect)==null||d.call(s,()=>{var l;if(this.editor){const u=this.editor.getSelection();if(u)return(l=this.editor.getModel())==null?void 0:l.getValueInRange(u)}});const h=this.monacoTS.typescriptDefaults.getCompilerOptions();h.allowJs=!0,h.checkJs=this.props.checkJs!==!1,h.noLib=!0,h.lib=[],h.useUnknownInCatchVariables=!1,h.moduleResolution=this.monacoTS.ModuleResolutionKind.NodeJs,h.target=this.monacoTS.ScriptTarget.ESNext,h.module=this.monacoTS.ModuleKind.ESNext,h.allowNonTsExtensions=!0,this.monacoTS.typescriptDefaults.setCompilerOptions(h),this.setTypeCheck(!1),(c=this.monacoDiv)!=null&&c.current&&(this.editor=this.monaco.editor.create((a=this.monacoDiv)==null?void 0:a.current,{lineNumbers:"on",scrollBeyondLastLine:!1,automaticLayout:!0,glyphMargin:!!this.props.breakpoints,colorDecorators:!0}),this.contentChangeDisposable=this.editor.onDidChangeModelContent(()=>this.onChange()),this.monaco&&!this.datapointProviderDisposable&&g(async()=>{const{registerDatapointProvider:l}=await import("./AiDatapointProvider-B0i3I5Fm.js");return{registerDatapointProvider:l}},[],import.meta.url).then(({registerDatapointProvider:l})=>{this.monaco&&(this.datapointProviderDisposable=l(this.monaco,this.props.socket))}).catch(()=>{}),this.monaco&&!this.stateHoverDisposable&&g(async()=>{const{registerStateHoverProvider:l}=await import("./stateHoverProvider-CGChzV5W.js");return{registerStateHoverProvider:l}},[],import.meta.url).then(({registerStateHoverProvider:l})=>{this.monaco&&(this.stateHoverDisposable=l(this.monaco,this.props.socket))}).catch(()=>{}),this.props.aiCompletionsEnabled&&this.monaco&&!this.inlineProviderDisposable&&g(async()=>{const{registerAiInlineProvider:l}=await import("./AiInlineProvider-DkgjVSFQ.js");return{registerAiInlineProvider:l}},[],import.meta.url).then(({registerAiInlineProvider:l})=>{this.monaco&&(this.inlineProviderDisposable=l(this.monaco,this.props.socket,this.props.runningInstances))}).catch(()=>{}),this.loadTypings(),this.props.onForceSave&&this.editor.addCommand(this.monaco.KeyMod.CtrlCmd|this.monaco.KeyCode.KeyS,()=>this.props.onForceSave&&this.props.onForceSave()),this.registerAiActions(),this.monaco&&this.editor&&this.props.onAiAction&&!this.codeLensDisposable&&g(async()=>{const{registerAiCodeLensProvider:l}=await import("./index-DSvAO584.js").then(u=>u.o);return{registerAiCodeLensProvider:l}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url).then(({registerAiCodeLensProvider:l})=>{this.monaco&&this.editor&&this.props.onAiAction&&(this.codeLensDisposable=l(this.monaco,this.editor,(u,y,f,b,C)=>{var L,I,S;const D=(L=this.editor)==null?void 0:L.getModel(),_=D?D.getLineMaxColumn(Math.min(C,D.getLineCount())):1;(S=(I=this.props).onAiAction)==null||S.call(I,{action:u,code:y,rangeLabel:f,range:{startLine:b,startColumn:1,endLine:C,endColumn:_},kind:"codelens"})}))}).catch(()=>{}),setTimeout(()=>{this.highlightText(this.state.searchText),this.location=this.props.location||void 0,this.breakpoints=this.props.breakpoints,this.showDecorators()}))}const e={selectOnLineNumbers:!0,scrollBeyondLastLine:!1,automaticLayout:!0,readOnly:this.state.readOnly,language:this.state.language,isDark:this.state.isDark};this.setEditorOptions(e),this.editor&&(this.editor.focus(),this.editor.setValue(this.originalCode),this.props.onToggleBreakpoint&&(this.mouseDownDisposable=this.editor.onMouseDown(h=>{var u;const l=h.target;this.props.onToggleBreakpoint&&((u=l.detail)==null?void 0:u.glyphMarginLeft)!==void 0&&l.position&&this.props.onToggleBreakpoint(l.position.lineNumber-1)})))}setEditorOptions(t){var e;t&&(t.language&&this.setEditorLanguage(t.language),this.editor&&(t.readOnly!==void 0&&this.editor.updateOptions({readOnly:t.readOnly}),t.lineWrap!==void 0&&this.editor.updateOptions({wordWrap:t.lineWrap?"on":"off"})),t.typeCheck!==void 0&&this.setTypeCheck(t.typeCheck),t.isDark!==void 0&&((e=this.monaco)==null||e.editor.setTheme(t.isDark?"vs-dark":"vs")))}componentWillUnmount(){var t,e,i,o,n,r,s,d,c;(t=this.contentChangeDisposable)==null||t.dispose(),this.contentChangeDisposable=null,(e=this.mouseDownDisposable)==null||e.dispose(),this.mouseDownDisposable=null,(i=this.datapointProviderDisposable)==null||i.dispose(),this.datapointProviderDisposable=null,g(async()=>{const{clearDatapointCache:a}=await import("./AiDatapointProvider-B0i3I5Fm.js");return{clearDatapointCache:a}},[],import.meta.url).then(({clearDatapointCache:a})=>a()).catch(()=>{}),(o=this.inlineProviderDisposable)==null||o.dispose(),this.inlineProviderDisposable=null,(n=this.stateHoverDisposable)==null||n.dispose(),this.stateHoverDisposable=null,g(async()=>{const{clearStateHoverCache:a}=await import("./stateHoverProvider-CGChzV5W.js");return{clearStateHoverCache:a}},[],import.meta.url).then(({clearStateHoverCache:a})=>a()).catch(()=>{}),(r=this.codeLensDisposable)==null||r.dispose(),this.codeLensDisposable=null,(s=this.inlineChatWidgetInstance)==null||s.dispose(),this.inlineChatWidgetInstance=null,this.hideInlineDiff(),this.editor&&((c=(d=this.props).onRegisterSelect)==null||c.call(d,null),this.editor.dispose(),this.editor=null)}async doPrettier(){var i,o,n,r;const t=this.props.runningInstances&&Object.keys(this.props.runningInstances).find(s=>{var d;return(d=this.props.runningInstances)==null?void 0:d[s]});if(!t){window.alert(p.I18n.t("No script adapter instance found to format the code"));return}const e=await this.props.socket.sendTo(t.replace("system.adapter.",""),"prettier",{code:(i=this.editor)==null?void 0:i.getValue(),type:this.state.language});e.error?this.setState({showError:{title:p.I18n.t("Error formatting code"),message:$(e.error)}}):e.code&&((o=this.editor)==null||o.setValue(e.code),(r=(n=this.props).onChange)==null||r.call(n,e.code),this.showDecorators())}setEditorLanguage(t){var i,o;if(!this.editor)return;const e=this.editor.getModel();if(e){const n=e.getValue(),r=e.uri.path,s=typeof r=="string"&&r.includes(".")?r.substring(0,r.lastIndexOf(".")):"index",d=t==="javascript"?"js":t==="typescript"?"ts":t;e.dispose();const c=t==="javascript"||t==="typescript"?"typescript":t,a=(i=this.monaco)==null?void 0:i.editor.createModel(n,c,this.monaco.Uri.from({scheme:window.location.protocol.replace(":",""),path:`${s}${P++}.${d}`}));a&&(this.editor.setModel(a),(o=this.contentChangeDisposable)==null||o.dispose(),this.contentChangeDisposable=this.editor.onDidChangeModelContent(()=>this.onChange()))}}setTypeCheck(t){var i,o;const e={noSemanticValidation:!this.state.alive||!t,noSyntaxValidation:!this.state.alive};(i=this.monacoTS)==null||i.typescriptDefaults.setDiagnosticsOptions(e),(o=this.monacoTS)==null||o.javascriptDefaults.setDiagnosticsOptions({noSemanticValidation:!this.state.alive||!t,noSyntaxValidation:!this.state.alive})}setEditorTypings(t=""){var n,r,s,d;const e=K(t),i=`${t}.d.ts`,o=[];for(const c of Object.keys(this.typings))e&&(c==="global.d.ts"||c.startsWith("script.js.global")&&c!==i)||o.push({filePath:c,content:this.typings[c]});if((r=(n=this.monacoTS)==null?void 0:n.typescriptDefaults)!=null&&r.setExtraLibs)this.monacoTS.typescriptDefaults.setExtraLibs(o);else if((d=(s=this.monacoTS)==null?void 0:s.typescriptDefaults)!=null&&d.addExtraLib){const c=this.monacoTS.typescriptDefaults.getExtraLibs();o.forEach(a=>{!c[a.filePath]&&this.monaco&&this.monacoTS.typescriptDefaults.addExtraLib(a.content,a.filePath)})}}undo(){var t;(t=this.editor)==null||t.trigger("toolbar","undo",null)}redo(){var t;(t=this.editor)==null||t.trigger("toolbar","redo",null)}insertTextIntoEditor(t){if(!this.editor||!this.monaco)return;const e=this.editor.getSelection();if(e){const i=new this.monaco.Range(e.startLineNumber,e.startColumn,e.endLineNumber,e.endColumn);this.editor.executeEdits("",[{range:i,text:t,forceMoveMarkers:!0}])}this.editor.focus()}highlightText(t){var o;if(!this.editor||!this.monaco)return 0;const e=t?(o=this.editor.getModel())==null?void 0:o.findMatches(t,!0,!1,!1,null,!0):void 0;if(e!=null&&e.length)return e.forEach(n=>{var r;return(r=this.editor)==null?void 0:r.setSelection(n.range)}),this.editor.revealLine(e[0].range.startLineNumber),e.length;const i=this.editor.getPosition();if(i){const n=i.lineNumber,r=i.column;this.editor.setSelection(new this.monaco.Range(n,r,n,r))}return 0}showInlineDiff(t){if(!this.editor||!this.monaco)return;const e=this.editor,i=this.monaco;this.hideInlineDiff(),g(async()=>{const{InlineDiffController:o,INLINE_DIFF_CSS:n}=await import("./inlineDiffController-DBLpPOe2.js");return{InlineDiffController:o,INLINE_DIFF_CSS:n}},__vite__mapDeps([14,10,15]),import.meta.url).then(({InlineDiffController:o,INLINE_DIFF_CSS:n})=>{if(!this.inlineDiffCssInjected){const s=document.createElement("style");s.textContent=n,s.setAttribute("data-iob-aichat","inline-diff"),document.head.appendChild(s),this.inlineDiffCssInjected=!0}const r=new o(e,i,{range:t.range,originalText:t.originalText,modifiedText:t.modifiedText,onAccepted:()=>{var s;this.inlineDiffInstance=null,(s=t.onAccepted)==null||s.call(t)},onRejected:()=>{var s;this.inlineDiffInstance=null,(s=t.onRejected)==null||s.call(t)}});this.inlineDiffInstance=r,r.show()}).catch(()=>{})}hideInlineDiff(){if(this.inlineDiffInstance){try{this.inlineDiffInstance.dispose()}catch{}this.inlineDiffInstance=null}}showInlineChatWidget(){if(!this.editor||!this.monaco||!this.props.onInlineAsk)return;if(this.inlineChatWidgetInstance){this.inlineChatWidgetInstance.show();return}const t=this.editor,e=this.monaco,i=this.props.onInlineAsk,o=this.props.onAiAction;g(async()=>{const{InlineChatWidget:n}=await import("./inlineChatWidget-Cu6rb4Ar.js");return{InlineChatWidget:n}},__vite__mapDeps([16,10,15]),import.meta.url).then(({InlineChatWidget:n})=>{const r=new n(t,e,{onSubmit:async s=>i({question:s.question,selectedCode:s.selectedCode}),onEscalateToChat:s=>{o&&o({action:"ask",code:s.selectedCode,question:s.question,rangeLabel:s.range?`lines ${s.range.startLineNumber}-${s.range.endLineNumber}`:"whole file"})}});this.inlineChatWidgetInstance=r,r.show()}).catch(()=>{})}registerAiActions(){if(!this.editor||!this.monaco||!this.props.onAiAction)return;const t=this.monaco,e=(o,n={})=>{if(!this.editor||!this.props.onAiAction)return;const r=this.editor.getModel();if(!r)return;const s=this.editor.getSelection(),d=s&&!s.isEmpty();let c,a,h,l="selection";if(d)c=r.getValueInRange(s),a=s.startLineNumber===s.endLineNumber?`line ${s.startLineNumber}`:`lines ${s.startLineNumber}-${s.endLineNumber}`,h={startLine:s.startLineNumber,startColumn:s.startColumn,endLine:s.endLineNumber,endColumn:s.endColumn},l="selection";else{const u=this.editor.getPosition();let y=null;if(u)try{y=V(r.getValue(),u.lineNumber)}catch{}if(y){const f=y.startLine,b=y.endLine,C=r.getLineMaxColumn(b),D=new t.Range(f,1,b,C);c=r.getValueInRange(D),a=f===b?`line ${f}`:`lines ${f}-${b}`,h={startLine:f,startColumn:1,endLine:b,endColumn:C},l="codelens"}else c=r.getValue(),a="whole file",l="none"}this.props.onAiAction({action:o,code:c,rangeLabel:a,range:h,kind:l,...n})},i=[{id:"iobroker.ai.inline",label:`🤖 ${p.I18n.t("AI: Inline chat…")}`,keybindings:[t.KeyMod.CtrlCmd|t.KeyMod.Alt|t.KeyCode.KeyI],order:1,run:()=>{if(this.props.onInlineAsk)this.showInlineChatWidget();else{const o=window.prompt(p.I18n.t("Ask the AI about the selected code:"));o&&o.trim()&&e("ask",{question:o.trim()})}}},{id:"iobroker.ai.explain",label:`💡 ${p.I18n.t("AI: Explain")}`,keybindings:[t.KeyMod.CtrlCmd|t.KeyMod.Alt|t.KeyCode.KeyE],order:2,run:()=>e("explain")},{id:"iobroker.ai.refactor",label:`🔧 ${p.I18n.t("AI: Refactor")}`,keybindings:[t.KeyMod.CtrlCmd|t.KeyMod.Alt|t.KeyCode.KeyR],order:3,run:()=>e("refactor")},{id:"iobroker.ai.comment",label:`💬 ${p.I18n.t("AI: Add comments")}`,keybindings:[t.KeyMod.CtrlCmd|t.KeyMod.Alt|t.KeyCode.KeyC],order:4,run:()=>e("comment")},{id:"iobroker.ai.fix",label:`🛠️ ${p.I18n.t("AI: Fix problem")}`,keybindings:[t.KeyMod.CtrlCmd|t.KeyMod.Alt|t.KeyCode.KeyF],order:5,run:()=>{var n,r;let o;try{const s=(n=this.editor)==null?void 0:n.getModel(),d=(r=this.editor)==null?void 0:r.getPosition();if(s&&d){const a=t.editor.getModelMarkers({resource:s.uri}).find(h=>d.lineNumber>=h.startLineNumber&&d.lineNumber<=h.endLineNumber);a&&(o=a.message)}}catch{}e("fix",{diagnostic:o})}},{id:"iobroker.ai.tests",label:`✅ ${p.I18n.t("AI: Suggest tests")}`,order:6,run:()=>e("tests")}];for(const o of i)try{this.editor.addAction({id:o.id,label:o.label,contextMenuGroupId:"aichat",contextMenuOrder:o.order,keybindings:o.keybindings,run:()=>o.run()})}catch{}}getEditorSelection(){if(!this.editor)return null;const t=this.editor.getSelection();if(!t||t.isEmpty())return null;const e=this.editor.getModel();return e?{text:e.getValueInRange(t),range:{startLine:t.startLineNumber,startColumn:t.startColumn,endLine:t.endLineNumber,endColumn:t.endColumn}}:null}getEditorContent(){var t,e;return((e=(t=this.editor)==null?void 0:t.getModel())==null?void 0:e.getValue())??""}getCursorPosition(){var e;const t=(e=this.editor)==null?void 0:e.getPosition();return t?{line:t.lineNumber,column:t.column}:null}highlightLineRange(t,e){if(!this.editor||!this.monaco)return!1;const i=this.editor.getModel();if(!i)return!1;const o=i.getLineCount(),n=Math.max(1,Math.min(t,o)),r=Math.max(n,Math.min(e,o)),s=i.getLineMaxColumn(r);return this.editor.setSelection(new this.monaco.Range(n,1,r,s)),this.editor.revealLineInCenter(n),!0}goToLine(t,e=1){if(!this.editor||!this.monaco)return!1;const i=this.editor.getModel();if(!i)return!1;const o=i.getLineCount(),n=Math.max(1,Math.min(t,o));return this.editor.setPosition({lineNumber:n,column:e}),this.editor.revealLineInCenter(n),this.editor.focus(),!0}replaceSelection(t){if(!this.editor||!this.monaco)return!1;const e=this.editor.getSelection();if(!e)return!1;const i=new this.monaco.Range(e.startLineNumber,e.startColumn,e.endLineNumber,e.endColumn);return this.editor.executeEdits("",[{range:i,text:t,forceMoveMarkers:!0}]),this.editor.focus(),!0}getDiagnostics(){if(!this.editor||!this.monaco)return[];const t=this.editor.getModel();if(!t)return[];const e=this.monaco.editor.getModelMarkers({resource:t.uri}),i={8:"error",4:"warning",2:"info",1:"hint"};return e.map(o=>({line:o.startLineNumber,column:o.startColumn,endLine:o.endLineNumber,endColumn:o.endColumn,severity:i[o.severity]||"info",message:o.message,...o.source?{source:o.source}:{}}))}async getDocumentSymbols(){var i;if(!this.editor||!this.monaco)return[];const t=this.editor.getModel();if(!t)return[];const e=[];try{const o=this.monaco.languages,n=(i=o.getDocumentSymbolProviders)==null?void 0:i.call(o,t);if(n!=null&&n.length){const r={0:"file",1:"module",2:"namespace",3:"package",4:"class",5:"method",6:"property",7:"field",8:"constructor",9:"enum",10:"interface",11:"function",12:"variable",13:"constant",14:"string",15:"number",16:"boolean",17:"array",18:"object",19:"key",20:"null",21:"enum-member",22:"struct",23:"event",24:"operator",25:"type-parameter"};for(const s of n){const d={isCancellationRequested:!1},c=await s.provideDocumentSymbols(t,d);if(!c)continue;const a=h=>{var l;for(const u of h)e.push({name:u.name,kind:r[u.kind]||String(u.kind),line:u.range.startLineNumber,endLine:u.range.endLineNumber,...u.detail?{detail:u.detail}:{}}),(l=u.children)!=null&&l.length&&a(u.children)};if(a(c),e.length)break}}}catch{}if(e.length===0){const n=t.getValue().split(`
3
3
  `),r=[{re:/^(?:export\s+)?(?:async\s+)?function\s+(\w+)/,kind:"function"},{re:/^(?:export\s+)?class\s+(\w+)/,kind:"class"},{re:/^(?:export\s+)?(?:const|let|var)\s+(\w+)/,kind:"variable"}];for(let s=0;s<n.length;s++){const d=n[s].trim();for(const{re:c,kind:a}of r){const h=c.exec(d);if(h!=null&&h[1]){e.push({name:h[1],kind:a,line:s+1,endLine:s+1});break}}}}return e}showDecorators(){var e;const t=[];if(this.location&&this.monaco&&(t.push({range:new this.monaco.Range(this.location.lineNumber+1,(this.location.columnNumber||0)+1,this.location.lineNumber+1,1e3),options:{isWholeLine:!1,className:this.props.isDark?"monacoCurrentLineDark":"monacoCurrentLine"}}),t.push({range:new this.monaco.Range(this.location.lineNumber+1,0,this.location.lineNumber+1,0),options:{isWholeLine:!0,className:this.props.isDark?"monacoCurrentFullLineDark":"monacoCurrentFullLine"}})),(e=this.breakpoints)==null||e.forEach(i=>{this.monaco&&t.push({range:new this.monaco.Range(i.location.lineNumber+1,0,i.location.lineNumber+1,100),options:{isWholeLine:!0,glyphMarginClassName:this.props.isDark?"monacoBreakPointDark":"monacoBreakPoint"}})}),this.editor){const i=this.editor.getModel();i&&(this.decorations=i.deltaDecorations(this.decorations,t))}}initNewScript(t,e){var i;this.setState({name:t}),this.originalCode=e||"",(i=this.editor)==null||i.setValue(e||""),this.highlightText(this.lastSearch),this.showDecorators(),this.setEditorTypings(t)}scrollToLineIfNeeded(t){if(this.editor){const e=this.editor.getVisibleRanges();(!e||!e[0]||e[0].startLineNumber>t||t>e[0].endLineNumber)&&this.editor.revealLineInCenter(t)}}UNSAFE_componentWillReceiveProps(t){const e={};this.state.name!==t.name&&this.initNewScript(t.name,t.code),JSON.stringify(t.runningInstances)!==this.runningInstancesStr&&(this.runningInstancesStr=JSON.stringify(t.runningInstances),this.state.typingsLoaded||this.loadTypings(t.runningInstances)),this.editor&&!t.changed&&(t.code!==this.originalCode||t.code!==this.editor.getValue())&&(this.originalCode=t.code||"",this.editor.setValue(this.originalCode),this.showDecorators(),this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)),t.searchText!==this.lastSearch&&(this.lastSearch=t.searchText||"",this.highlightText(this.lastSearch)),JSON.stringify(t.location)!==JSON.stringify(this.location)&&JSON.stringify(t.breakpoints)!==JSON.stringify(this.breakpoints)?(this.location=t.location||void 0,this.breakpoints=t.breakpoints,this.showDecorators(),this.editor&&this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)):JSON.stringify(t.breakpoints)!==JSON.stringify(this.breakpoints)?(this.breakpoints=t.breakpoints,this.showDecorators()):JSON.stringify(t.location)!==JSON.stringify(this.location)&&(this.location=t.location||void 0,this.showDecorators(),this.editor&&this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)),this.state.language!==(t.language||"javascript")?(this.setState({language:t.language||"javascript"}),e.language=t.language||"javascript"):this.state.readOnly!==(t.readOnly||!1)?(this.setState({readOnly:t.readOnly||!1}),e.readOnly=t.readOnly):this.state.isDark!==(t.isDark||!1)&&(this.setState({isDark:t.isDark||!1}),e.isDark=t.isDark),this.setEditorOptions(e),t.aiCompletionsEnabled!==this.props.aiCompletionsEnabled&&(t.aiCompletionsEnabled&&this.monaco&&!this.inlineProviderDisposable?g(async()=>{const{registerAiInlineProvider:i}=await import("./AiInlineProvider-DkgjVSFQ.js");return{registerAiInlineProvider:i}},[],import.meta.url).then(({registerAiInlineProvider:i})=>{this.monaco&&(this.inlineProviderDisposable=i(this.monaco,this.props.socket,this.props.runningInstances))}).catch(()=>{}):!t.aiCompletionsEnabled&&this.inlineProviderDisposable&&(this.inlineProviderDisposable.dispose(),this.inlineProviderDisposable=null)),this.insert!==t.insert&&(this.insert=t.insert||"",this.insert&&(console.log(`Insert text: ${this.insert}`),setTimeout(i=>{this.insertTextIntoEditor(i),setTimeout(()=>this.props.onInserted&&this.props.onInserted(),100)},100,this.insert)))}onChange(){var t,e;!this.props.readOnly&&this.editor&&((e=(t=this.props).onChange)==null||e.call(t,this.editor.getValue()))}renderErrorDialog(){return this.state.showError?this.state.showError.full?m.jsxs(T,{open:!0,maxWidth:"md",onClose:()=>this.setState({showError:null}),children:[m.jsx(N,{children:this.state.showError.title||p.I18n.t("Error")}),m.jsx(M,{children:m.jsx("pre",{children:m.jsx("code",{children:this.state.showError.message})})}),m.jsx(A,{children:m.jsxs(w,{variant:"contained",startIcon:m.jsx(E,{}),onClick:()=>this.setState({showError:null}),children:[p.I18n.t("Close")," "]})})]}):m.jsx(O,{open:!0,autoHideDuration:5e3,onClose:()=>this.setState({showError:null}),message:this.state.showError.title,action:m.jsxs(v.Fragment,{children:[m.jsx(w,{color:"secondary",size:"small",onClick:()=>this.setState({showError:{...this.state.showError,full:!0}}),children:p.I18n.t("More")}),m.jsx(x,{size:"small","aria-label":"close",color:"inherit",onClick:()=>this.setState({showError:null}),children:m.jsx(E,{fontSize:"small"})})]})}):null}render(){var t;return!((t=this.monacoTS)!=null&&t.typescriptDefaults)||!this.props.runningInstances?(setTimeout(()=>{this.monaco=window.monaco,this.forceUpdate()},200),null):(this.props.triggerPrettier!==this.triggerPrettier&&(this.triggerPrettier=this.props.triggerPrettier,setTimeout(()=>this.doPrettier().catch(e=>console.error("Error formatting code:",e)),50)),m.jsxs("div",{ref:this.monacoDiv,style:{...this.props.style,width:"100%",height:"100%",overflow:"hidden",position:"relative"},children:[this.renderErrorDialog(),!this.state.check&&m.jsx(j,{size:"small",title:p.I18n.t("Check is not active, because javascript adapter is disabled"),style:{bottom:10,right:10,opacity:.5,position:"absolute",zIndex:1,background:"red",color:"white"},color:"secondary",children:m.jsx(R,{})})]}))}}export{tt as default};