iobroker.javascript 9.2.4 → 9.3.1

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.
Files changed (37) hide show
  1. package/README.md +6 -15
  2. package/admin/assets/AiChatPanel-C3bIw_D5.js +317 -0
  3. package/admin/assets/{ScriptEditor-CmEeMfC2.js → ScriptEditor-8UU88tT5.js} +1 -1
  4. package/admin/assets/{ScriptEditorVanillaMonaco-C22Gpet7.js → ScriptEditorVanillaMonaco-Bn8xJ3LV.js} +2 -2
  5. package/admin/assets/index-C0ZnUCQf.js +990 -0
  6. package/admin/assets/{index-BTQOdA7v.js → index-CO9RA-Wq.js} +4 -4
  7. package/admin/assets/{index-7mrTpzQy.js → index-CRGWWpGb.js} +1 -1
  8. package/admin/assets/{index-Dggem6AX.js → index-CsyuIWlD.js} +1 -1
  9. package/admin/assets/localSharedImportMap-Db5DxDmY.js +1 -0
  10. package/admin/assets/{stateHoverProvider-DxTNxyYN.js → stateHoverProvider-C82xsI7Q.js} +1 -1
  11. package/admin/assets/{virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-CeYV4czE.js → virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-Bw22wl4W.js} +2 -2
  12. package/admin/custom/assets/index-CMsuyEZj.js +964 -0
  13. package/admin/custom/assets/{index-B6NrrORQ.js → index-CuAhFQ4L.js} +147 -147
  14. package/admin/custom/assets/{index-DTbSiEk2.js → index-mkhHeJ3Q.js} +1 -1
  15. package/admin/custom/assets/localSharedImportMap-BsMINYMr.js +1 -0
  16. package/admin/custom/assets/{virtual_mf-REMOTE_ENTRY_ID_ConfigCustomJavascriptSet__customComponents_js-ClQrb2n1.js → virtual_mf-REMOTE_ENTRY_ID_ConfigCustomJavascriptSet__customComponents_js-BzLNCazi.js} +2 -2
  17. package/admin/custom/customComponents.js +1 -1
  18. package/admin/i18n/de.json +8 -0
  19. package/admin/i18n/en.json +8 -0
  20. package/admin/jsonConfig.json +70 -9
  21. package/admin/mf-manifest.json +1 -1
  22. package/admin/remoteEntry.js +1 -1
  23. package/admin/tab.html +2 -2
  24. package/build/lib/aiProviderResolver.js +32 -5
  25. package/build/lib/aiProviderResolver.js.map +1 -1
  26. package/build/lib/sandbox.js +20 -12
  27. package/build/lib/sandbox.js.map +1 -1
  28. package/build/main.js +336 -41
  29. package/build/main.js.map +1 -1
  30. package/build/types.d.ts +10 -4
  31. package/io-package.json +34 -28
  32. package/package.json +9 -9
  33. package/admin/assets/AiChatPanel-B4vPXgLz.js +0 -315
  34. package/admin/assets/index-qoSy77Bg.js +0 -990
  35. package/admin/assets/localSharedImportMap-CVlAGiIu.js +0 -1
  36. package/admin/custom/assets/index-CT5PwRfY.js +0 -964
  37. package/admin/custom/assets/localSharedImportMap-ChjFDKsq.js +0 -1
package/README.md CHANGED
@@ -27,6 +27,12 @@ Executes Javascript, Typescript Scripts.
27
27
  -->
28
28
 
29
29
  ## Changelog
30
+ ### 9.3.1 (2026-06-18)
31
+ * (@GermanBluefox) Added the possibility to execute one-way scripts without saving it
32
+
33
+ ### 9.3.0 (2026-06-17)
34
+ * (@GermanBluefox) Implemented the support for credentials manager in the configuration
35
+
30
36
  ### 9.2.4 (2026-06-08)
31
37
  * (arteck) Performance optimizations part 2
32
38
  * (arteck) fix filter in tab scripts
@@ -42,21 +48,6 @@ Executes Javascript, Typescript Scripts.
42
48
  * (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
43
49
  * (@GermanBluefox) Added the "is state exists" block to blockly
44
50
 
45
- ### 9.2.1 (2026-04-30)
46
- * (@GermanBluefox) See previous changelog entries
47
-
48
- ### 9.2.0 (2026-04-30)
49
- * (@GermanBluefox) Agent keys are encrypted now. You must enter your keys anew!
50
- * (Eistee82) AI API keys are now stored encrypted and only used server-side (`encryptedNative` + `protectedNative`); the frontend never sees them
51
- * (Eistee82) Code Lens above every top-level function/class/arrow with `💡 Explain | 🔧 Refactor | ✅ Tests` actions
52
- * (Eistee82) Inline Chat Widget (Ctrl+Alt+I) directly in the editor with response preview and Apply button
53
- * (Eistee82) Inline diff for AI "Show diff": only the targeted lines change as red/green, the rest of the script stays untouched; Accept replaces just those lines
54
- * (Eistee82) Six VS-Code-like AI actions in the Monaco editor (right-click menu, Ctrl+Alt+I/E/R/C/F shortcuts, and `/explain`, `/refactor`, `/comment`, `/fix`, `/tests`, `/ask` slash commands with German aliases)
55
- * (Eistee82) Hover over an ioBroker object ID in any string literal to see a rich tooltip with object metadata and the current live state — works without AI
56
- * (Eistee82) Anthropic agent mode (native `tool_use`/`tool_result` blocks) and 10 new Monaco editor tools so the AI agent can read/navigate/edit the live editor
57
- * (Eistee82) `search_datapoints` covers every object type (channels, devices, folders, enums, …) and matches on role; `get_object_info` lists children for containers — fixes finding aliases/motion-sensors modeled as channels
58
- * (Eistee82) Non-chat model filter expanded (embeddings, image/audio/video/TTS, transcription, moderation, web-search, Ollama single-task models, …)
59
-
60
51
  ## License
61
52
  The MIT License (MIT)
62
53
 
@@ -0,0 +1,317 @@
1
+ import{c as Se,j as o}from"./createSvgIcon-DYs_tNrE.js";import{k as J,j as te,b as ne,c as xe,l as Ae}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{z as L,P as ve,o as we,a0 as ct,a1 as lt,i as We,J as dt,r as ut,s as pt,u as mt,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-45IwpC7_.js";import{i as vt,k as qe,l as wt,n as St}from"./index-CO9RA-Wq.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-Bw22wl4W.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(o.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(o.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"),Tt=Se(o.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"),Ct=Se(o.jsx("path",{d:"M9.01 14H2v2h7.01v3L13 15l-3.99-4zm5.98-1v-3H22V8h-7.01V5L11 9z"}),"CompareArrows"),It=Se(o.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(o.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(o.jsx("path",{d:"M2.01 21 23 12 2.01 3 2 10l15 2-15 2z"}),"Send"),Nt=Se(o.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"),Rt=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,Je=null,Le=null,Me=null;function Dt(){$e=null,Je=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",{}),i=((t==null?void 0:t.providers)||[]).map(a=>a.provider),s=((t==null?void 0:t.providers)||[]).find(a=>a.provider==="custom");return i.length?($e={providers:i,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 i=[],s={},a=[],p=(c,y)=>{for(const d of c)zt(d)&&(s[d]||(i.push(d),s[d]=y))},l=[],m=(c,y)=>{l.push(r.sendTo(t,"testApiConnection",{provider:c==="custom"?"openai":c}).then(d=>{d.models?p(d.models,c):d.error&&a.push(`${y||c}: ${d.error}`)}).catch(d=>{a.push(`${y||c}: ${String(d)}`)}))},g={openai:"OpenAI",anthropic:"Anthropic",gemini:"Gemini",deepseek:"DeepSeek",custom:"Custom"};for(const c of n.providers)m(c,g[c]);return await Promise.all(l),i.sort(),{models:i,providerMap:s,errors:a}}async function Ne(r,e,n){var i;return await r.sendTo(e,"chatCompletion",{timeout:n.timeout||6e5,model:n.model,provider:n.provider,messages:n.messages,...n.baseUrl?{baseUrl:n.baseUrl}:{},...(i=n.tools)!=null&&i.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","","香"),i=await r.getObjectViewSystem("folder","","香"),s=await r.getObjectViewSystem("enum","","香");return Me=Object.assign(e,n,t,i,s),Me}async function nt(r){return tt(r)}function Ce(r,e){return r&&typeof r=="object"?r[e]||r.en:r||""}async function Ge(r){var S,b,v,H;if(Je)return Je;const e=u.I18n.getLanguage(),n=await tt(r),t=Object.keys(n).sort(),i=new gt,s=[],a=["UNREACH_STICKY"],p=[yt.Types.info],l=[],m=[],g=[],c=[];t.forEach(E=>{var C,x,w;((C=n[E])==null?void 0:C.type)==="enum"?l.push(E):(w=(x=n[E])==null?void 0:x.common)!=null&&w.smartName&&c.push(E)}),l.forEach(E=>{E.startsWith("enum.rooms.")?m.push(E):E.startsWith("enum.functions.")&&g.push(E);const C=n[E].common.members;C!=null&&C.length&&C.forEach(x=>{n[x]&&!c.includes(x)&&c.push(x)})});const y={id:"",objects:n,_keysOptional:t,_usedIdsOptional:s,ignoreIndicators:a,excludedTypes:p},d=[];c.forEach(E=>{y.id=E;const C=i.detect(y);C&&C.forEach(x=>{var de;const w=(de=x.states.find(I=>I.id))==null?void 0:de.id;if(!w||d.find(I=>I.id===w))return;const M=n[w],re={id:w,name:Ce(M.common.name,e),type:M.type,deviceType:x.type,states:x.states.filter(I=>I.id).map(I=>({id:I.id,name:I.name,role:I.defaultRole,type:n[I.id].common.type,unit:n[I.id].common.unit,read:n[I.id].common.read??!0,write:n[I.id].common.write??!0}))},G=w.split(".");let _,Y;(M.type==="channel"||M.type==="state")&&(G.pop(),_=G.join("."),n[_]&&(n[_].type==="channel"||n[_].type==="folder")?(G.pop(),Y=G.join("."),(!n[Y]||n[Y].type!=="device"&&n[_].type!=="folder")&&(Y=void 0)):_=void 0);const le=m.find(I=>{var A,X,Q;return(A=n[I].common.members)!=null&&A.includes(w)||_&&((X=n[I].common.members)!=null&&X.includes(_))?!0:Y&&((Q=n[I].common.members)==null?void 0:Q.includes(Y))});le&&(re.room=Ce(n[le].common.name,e));const K=g.find(I=>{var A,X,Q;return(A=n[I].common.members)!=null&&A.includes(w)||_&&((X=n[I].common.members)!=null&&X.includes(_))?!0:Y&&((Q=n[I].common.members)==null?void 0:Q.includes(Y))});K&&(re.function=Ce(n[K].common.name,e)),d.push(re)})});for(let E=0;E<d.length;E++){const C=d[E];if(C.type==="state"||C.type==="channel"){const x=C.id.split(".");x.pop();const w=n[x.join(".")];if(w&&(w.type==="channel"||w.type==="device"||w.type==="folder")){C.name=Ce(((S=w.common)==null?void 0:S.name)||C.name,e),x.pop();const M=n[x.join(".")];(M==null?void 0:M.type)==="device"&&((b=M.common)!=null&&b.icon)&&(C.name=Ce(((v=M.common)==null?void 0:v.name)||C.name,e))}else C.name=Ce(((H=w==null?void 0:w.common)==null?void 0:H.name)||C.name,e)}}return Je=d,d}async function Jt(){return Le||(Le=(await Rt).default,Le)}function Ye(){return Mt[u.I18n.getLanguage()]||"English"}function At(r){return`You write ioBroker JavaScript adapter scripts.
2
+ Copy EXACTLY this syntax. Do NOT change the callback signature.
3
+ IMPORTANT: Write all code at top level. NEVER use console.log (use log instead). NEVER define functions with the function keyword.
4
+
5
+ // CORRECT: on() always has ONE callback argument called obj
6
+ on('zigbee.0.sensor.state', (obj) => {
7
+ // obj.state.val = the new value (boolean or number)
8
+ // obj.id = the state ID that changed
9
+ setState('zigbee.0.lamp.state', obj.state.val);
10
+ log('Changed to ' + obj.state.val);
11
+ });
12
+
13
+ // CORRECT: on() with filter
14
+ on({id: /zigbee\\.0\\..*\\.state$/, change: 'ne'}, (obj) => {
15
+ if (obj.state.val === true) {
16
+ setState('zigbee.0.other.state', true);
17
+ }
18
+ });
19
+
20
+ // Other correct examples:
21
+ setState('id', true);
22
+ setState('id', 50);
23
+ const val = getState('id').val;
24
+ schedule('0 7 * * *', () => { log('runs daily at 07:00'); });
25
+ schedule('0 22 * * *', () => { setState('id', false); });
26
+
27
+ // CORRECT Telegram: always use sendTo, NEVER setState on telegram
28
+ sendTo('telegram.0', 'send', {text: 'Alert: ' + someValue});
29
+
30
+ // CORRECT httpGet: res.data is a STRING, parse JSON with JSON.parse
31
+ httpGet('https://api.example.com/data', (err, res) => {
32
+ const data = JSON.parse(res.data);
33
+ log('Temperature: ' + data.main.temp);
34
+ });
35
+
36
+ $('state[state.id=*.state](rooms=Room)').each((id) => { setState(id, false); });
37
+ createState('name', 0, {type: 'number', name: 'Name'});
38
+ // CORRECT: one-time delayed action (turn off after 5 minutes = 300000ms)
39
+ setStateDelayed('zigbee.0.lamp.state', false, false, 5 * 60 * 1000);
40
+ log(formatDate(new Date(), 'DD.MM.YYYY hh:mm'));
41
+
42
+ WRONG: on('id', (id, state) => {}) CORRECT: on('id', (obj) => {})
43
+ WRONG: set('id', true) CORRECT: setState('id', true)
44
+ WRONG: adapter.setState('id', true) CORRECT: setState('id', true)
45
+ WRONG: obj.val or newState.val CORRECT: obj.state.val
46
+ WRONG: on('change', {id: 'x'}, cb) CORRECT: on({id: 'x', change: 'ne'}, cb)
47
+ WRONG: setState('telegram.0', text) CORRECT: sendTo('telegram.0', 'send', {text: text})
48
+ WRONG: res.body.main.temp CORRECT: JSON.parse(res.data).main.temp
49
+ WRONG: function myFunc() {} CORRECT: write code directly, no function definitions
50
+ WRONG: setTimeout(fn, ms) CORRECT: setStateDelayed(id, val, false, ms) for one-time delay
51
+ WRONG: schedule('*/5 * * * *', fn) for one-time delay. schedule() is ONLY for recurring tasks
52
+ Values are boolean (true/false) or numbers, NEVER strings like 'ON'/'OFF'.
53
+ NEVER use: function keyword, require, import, setInterval, setTimeout, console.log, debug().
54
+
55
+ All available functions (use syntax from examples above):
56
+ on(pattern, (obj)=>{}) | once(pattern, (obj)=>{}) | unsubscribe(handler)
57
+ setState(id, val) | getState(id).val | setStateChanged(id, val) | setStateDelayed(id, val, ack, ms) | clearStateDelayed(id)
58
+ existsState(id) | existsObject(id) | getObject(id) | setObject(id, obj) | extendObject(id, obj) | deleteObject(id)
59
+ createState(name, initVal, {type,name,role}) | deleteState(name) | createAlias(name, alias)
60
+ schedule(cron, ()=>{}) | clearSchedule(obj) | scheduleById(id, (obj)=>{}) | getSchedules()
61
+ sendTo(adapter, cmd, msg) | sendToHost(host, cmd, msg)
62
+ $('selector').each((id)=>{}) | $('selector').setState(val) | $('selector').getState()
63
+ log(text) | formatDate(date, 'DD.MM.YYYY hh:mm') | formatTimeDiff(ms) | formatValue(val, decimals)
64
+ getDateObject(str) | getAstroDate(pattern) | isAstroDay() | compareTime(start, end, op)
65
+ exec(cmd, (err,stdout,stderr)=>{}) | httpGet(url, (err,res)=>{}) | httpPost(url, data, (err,res)=>{})
66
+ readFile(adapter, name, (err,data)=>{}) | writeFile(adapter, name, data, cb) | delFile(adapter, name, cb)
67
+ onFile(id, name, withFile, cb) | offFile(id, name) | onStop(cb, timeout)
68
+ getHistory(inst, {id,start,end,aggregate,count}, cb) | getEnums(name) | getIdByName(name)
69
+ wait(ms) | toInt(val) | toFloat(val) | toBoolean(val)
70
+ messageTo(target, data) | onMessage(name, cb) | onLog(severity, cb)
71
+ runScript(name) | startScript(name) | stopScript(name) | isScriptActive(name)
72
+
73
+ Write comments in ${r}. Put code in a \`\`\`javascript code block.`}function Xe(r){return`You generate ioBroker Blockly XML blocks. Return Blockly XML in a \`\`\`xml code block.
74
+ Use EXACT state IDs from the plan. Write text/comments in ${r}.
75
+
76
+ IMPORTANT RULES:
77
+ - Return ONLY the inner blocks (no <xml> wrapper needed)
78
+ - Use the exact block types shown below
79
+ - State IDs must be full paths like "zigbee2mqtt.0.0x1234.state"
80
+ - Values are boolean (true/false) or numbers, NEVER strings like "ON"/"OFF"
81
+ - For Telegram use sendto_custom block, NEVER setState on telegram
82
+
83
+ ## Block Templates
84
+
85
+ ### Trigger: on_ext (react to state changes)
86
+ <block type="on_ext" x="0" y="0">
87
+ <mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
88
+ <field name="CONDITION">ne</field>
89
+ <field name="ACK_CONDITION"></field>
90
+ <value name="OID0">
91
+ <shadow type="field_oid"><field name="oid">STATE_ID_HERE</field></shadow>
92
+ </value>
93
+ <statement name="STATEMENT">
94
+ <!-- actions here -->
95
+ </statement>
96
+ </block>
97
+
98
+ ### Schedule: schedule (cron-based)
99
+ <block type="schedule" x="0" y="0">
100
+ <field name="SCHEDULE">0 7 * * *</field>
101
+ <statement name="STATEMENT">
102
+ <!-- actions here -->
103
+ </statement>
104
+ </block>
105
+
106
+ ### Set State: control
107
+ <block type="control">
108
+ <mutation xmlns="http://www.w3.org/1999/xhtml" delay_input="false"></mutation>
109
+ <field name="OID">STATE_ID_HERE</field>
110
+ <field name="WITH_DELAY">FALSE</field>
111
+ <value name="VALUE">
112
+ <block type="logic_boolean"><field name="BOOL">TRUE</field></block>
113
+ </value>
114
+ </block>
115
+
116
+ ### Get State Value: get_value
117
+ <block type="get_value">
118
+ <field name="ATTR">val</field>
119
+ <field name="OID">STATE_ID_HERE</field>
120
+ </block>
121
+
122
+ ### Log: debug
123
+ <block type="debug">
124
+ <field name="Severity">log</field>
125
+ <value name="TEXT">
126
+ <shadow type="text"><field name="TEXT">Message here</field></shadow>
127
+ </value>
128
+ </block>
129
+
130
+ ### SendTo (Telegram): sendto_custom
131
+ <block type="sendto_custom">
132
+ <mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
133
+ <field name="INSTANCE">telegram.0</field>
134
+ <field name="COMMAND">send</field>
135
+ <field name="LOG"></field>
136
+ <value name="ARG0">
137
+ <block type="text"><field name="TEXT">Message text</field></block>
138
+ </value>
139
+ <value name="ATTR0">
140
+ <block type="text"><field name="TEXT">text</field></block>
141
+ </value>
142
+ </block>
143
+
144
+ ### Timeout: timeouts_settimeout
145
+ <block type="timeouts_settimeout">
146
+ <field name="NAME">timeout1</field>
147
+ <field name="DELAY">5000</field>
148
+ <field name="UNIT">ms</field>
149
+ <statement name="STATEMENT">
150
+ <!-- delayed actions -->
151
+ </statement>
152
+ </block>
153
+
154
+ ### If/Else: controls_if
155
+ <block type="controls_if">
156
+ <mutation else="1"></mutation>
157
+ <value name="IF0">
158
+ <block type="logic_compare">
159
+ <field name="OP">EQ</field>
160
+ <value name="A"><block type="get_value"><field name="ATTR">val</field><field name="OID">STATE_ID</field></block></value>
161
+ <value name="B"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
162
+ </block>
163
+ </value>
164
+ <statement name="DO0"><!-- then --></statement>
165
+ <statement name="ELSE"><!-- else --></statement>
166
+ </block>
167
+
168
+ ### Number value
169
+ <block type="math_number"><field name="NUM">0</field></block>
170
+
171
+ ### Text value
172
+ <block type="text"><field name="TEXT">hello</field></block>
173
+
174
+ ### Boolean value
175
+ <block type="logic_boolean"><field name="BOOL">TRUE</field></block>
176
+
177
+ ### Comparison: logic_compare
178
+ <block type="logic_compare">
179
+ <field name="OP">EQ</field>
180
+ <!-- OP can be: EQ, NEQ, LT, LTE, GT, GTE -->
181
+ <value name="A"><!-- left side --></value>
182
+ <value name="B"><!-- right side --></value>
183
+ </block>
184
+
185
+ ## Common Patterns
186
+
187
+ ### Turn on light when sensor triggers:
188
+ <block type="on_ext" x="0" y="0">
189
+ <mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
190
+ <field name="CONDITION">ne</field>
191
+ <field name="ACK_CONDITION"></field>
192
+ <value name="OID0">
193
+ <shadow type="field_oid"><field name="oid">zigbee2mqtt.0.0xSENSOR.occupancy</field></shadow>
194
+ </value>
195
+ <statement name="STATEMENT">
196
+ <block type="controls_if">
197
+ <value name="IF0">
198
+ <block type="logic_compare">
199
+ <field name="OP">EQ</field>
200
+ <value name="A"><block type="get_value"><field name="ATTR">val</field><field name="OID">zigbee2mqtt.0.0xSENSOR.occupancy</field></block></value>
201
+ <value name="B"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
202
+ </block>
203
+ </value>
204
+ <statement name="DO0">
205
+ <block type="control">
206
+ <mutation xmlns="http://www.w3.org/1999/xhtml" delay_input="false"></mutation>
207
+ <field name="OID">zigbee2mqtt.0.0xLAMP.state</field>
208
+ <field name="WITH_DELAY">FALSE</field>
209
+ <value name="VALUE"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
210
+ </block>
211
+ </statement>
212
+ </block>
213
+ </statement>
214
+ </block>
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 Ut=[{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:"run_script",description:"Execute a JavaScript or TypeScript snippet in the live ioBroker javascript engine and get back everything it logged. The code runs with the full script API (log, console.*, setState, getState, on, schedule, $, exec, httpGet, …) in VERBOSE mode, so internal operations (setState/getState/subscribe/…) are logged too — ideal for diagnosing behaviour or inspecting values. The snippet runs for a short window and is then automatically STOPPED and fully cleaned up (timers, subscriptions, schedules removed); it does NOT create a persistent script. Use `log(...)` or `console.log(...)` in the code to surface the values you want to inspect. WARNING: side effects are real (e.g. setState changes actual devices) — prefer read-only diagnostics unless the user explicitly asked to change something.",parameters:{type:"object",properties:{source:{type:"string",description:"The JavaScript (or TypeScript) source to execute. Log the values you want to inspect via log(...) / console.log(...). Top-level await is supported."},engineType:{type:"string",description:'Optional. "TypeScript/ts" to run the code as TypeScript. Defaults to JavaScript.'},timeout:{type:"number",description:"Optional. Milliseconds to keep the script alive to collect asynchronous logs before it is stopped (default 5000, max 60000). Increase when waiting for timers, subscriptions or HTTP responses."},logLevel:{type:"string",description:"Optional minimum severity to return: silly, debug, info, warn, error. Default silly (everything)."}},required:["source"]}}},{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 Ue(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 i=e==null?void 0:e.common;if(!i)return!1;const s=Ue(i.name).toLowerCase();if(s&&s.includes(t))return!0;const a=(i.role||"").toLowerCase();return!!(a&&a.includes(t))}async function Ft(r,e,n=20,t){const i=await nt(r),s=t==null?void 0:t.toLowerCase(),a=[],p=Object.keys(i),l=new Set;for(const m of p){const g=m.lastIndexOf(".");g>0&&l.add(m.substring(0,g))}for(const m of p){const g=i[m],c=g==null?void 0:g.type;if(!c||s&&c!==s||!Wt(m,g,e))continue;const y=g.common,d={id:m,type:c,name:Ue(y==null?void 0:y.name)};if(y!=null&&y.role&&(d.role=y.role),c==="state"?(d.stateType=(y==null?void 0:y.type)||"",y!=null&&y.unit&&(d.unit=y.unit)):l.has(m)&&(d.hasChildren=!0),a.push(d),a.length>=n)break}return a.length===0?JSON.stringify({message:`No objects found matching "${e}". Hint: try a role like "sensor.motion" or a partial path.`}):JSON.stringify(a)}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 i={id:t._id,type:t.type,common:t.common},s=e.split("."),a=[];for(let p=s.length-1;p>=2;p--){const l=s.slice(0,p).join(".");try{const m=await r.getObject(l);m&&m.type!=="state"&&a.push({id:m._id,type:m.type,name:Ue((n=m.common)==null?void 0:n.name),common:m.common})}catch{}}if(a.length>0&&(i.parents=a),Vt.has(t.type)){const p=await nt(r),l=[],m=`${e}.`;let g=!1;for(const c of Object.keys(p))if(c.startsWith(m)&&!c.substring(m.length).includes(".")){const y=p[c],d=y==null?void 0:y.common,S={id:c,name:Ue(d==null?void 0:d.name),type:(y==null?void 0:y.type)||""};if(d!=null&&d.role&&(S.role=d.role),(y==null?void 0:y.type)==="state"&&(d!=null&&d.unit)&&(S.unit=d.unit),l.push(S),l.length>=Ke){g=!0;break}}l.length>0&&(i.children=l,g&&(i.childrenTruncated=!0,i.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(i)}catch{return JSON.stringify({error:`Failed to read object '${e}'`})}}function st(r){return vt(r)||r}function Gt(r,e,n=10){const t=e.toLowerCase(),i=[];for(const s of r){const a=s.id.toLowerCase(),p=s.name.toLowerCase(),l=s.id.replace(/^script\.js\./,"").replace(/\./g,"/"),m=s.engineType==="Blockly"||s.engineType==="Rules",g=a.includes(t)||p.includes(t),c=m?st(s.source):s.source,y=c.toLowerCase().includes(t);if(g||y){const d={id:s.id,path:l,name:s.name,type:m?"Blockly":s.engineType.includes("TypeScript")?"TypeScript":"JavaScript",enabled:s.enabled};if(y){const S=c.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&&(d.matchingLines=b)}if(i.push(d),i.length>=n)break}}return i.length===0?JSON.stringify({message:`No scripts found matching "${e}"`}):JSON.stringify(i)}function Yt(r,e){const n=e.replace(/\//g,".").toLowerCase(),t=r.find(p=>{const l=p.id.toLowerCase();return l===n||l===`script.js.${n}`||l.endsWith(`.${n}`)});if(!t)return JSON.stringify({error:`Script '${e}' not found. Use search_scripts to find available scripts.`});const i=t.engineType==="Blockly"||t.engineType==="Rules",s=i?st(t.source):t.source,a=t.id.replace(/^script\.js\./,"").replace(/\./g,"/");return JSON.stringify({id:t.id,path:a,name:t.name,type:i?"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){var i;if(!e)return JSON.stringify({error:"No running javascript instance found to execute the script."});const t=n.source;if(!t||typeof t!="string")return JSON.stringify({error:"No source code provided."});try{const s=await r.sendTo(e,"execute",{source:t,engineType:n.engineType,timeout:n.timeout,logLevel:n.logLevel});return!s||s.ok===!1?JSON.stringify({error:(s==null?void 0:s.error)||"Execution failed",logs:(s==null?void 0:s.logs)||[]}):JSON.stringify({engineType:s.engineType,runtime:s.runtime,truncated:s.truncated||!1,logCount:((i=s.logs)==null?void 0:i.length)||0,logs:s.logs||[],output:s.output||""})}catch(s){return JSON.stringify({error:`Failed to execute script: ${s instanceof Error?s.message:String(s)}`})}}async function Qt(r,e,n,t,i){let s;try{s=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,s.query,s.max_results||20,s.object_type);case"get_state_value":return Ht(r,s.id);case"get_object_info":return qt(r,s.id);case"search_scripts":return Gt(n||[],s.query,s.max_results||10);case"read_script":return Yt(n||[],s.id);case"list_scripts":return Xt(n||[]);case"run_script":return Kt(r,i,s);case"get_editor_selection":{if(!(t!=null&&t.getSelection))return he();const a=t.getSelection();return JSON.stringify(a||{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 a=t.getCursorPosition();return JSON.stringify(a||{message:"Editor has no cursor position (not focused)."})}case"highlight_text_in_editor":{if(!(t!=null&&t.highlightText))return he();const a=t.highlightText(s.text);return JSON.stringify({matches:a,message:a===0?`Text "${s.text}" was not found in the editor.`:`Highlighted ${a} occurrence(s) of "${s.text}".`})}case"highlight_line_range":{if(!(t!=null&&t.highlightLineRange))return he();const a=t.highlightLineRange(s.start_line,s.end_line);return JSON.stringify({success:a,message:a?`Selected lines ${s.start_line}-${s.end_line}.`:"Could not select the requested line range."})}case"go_to_line":{if(!(t!=null&&t.goToLine))return he();const a=t.goToLine(s.line,s.column);return JSON.stringify({success:a,message:a?`Cursor moved to line ${s.line}.`:"Could not move the cursor."})}case"insert_text_at_cursor":{if(!(t!=null&&t.insertTextAtCursor))return he();const a=t.insertTextAtCursor(s.text);return JSON.stringify({success:a,message:a?"Text inserted at cursor.":"Editor rejected the insertion."})}case"replace_selection":{if(!(t!=null&&t.replaceSelection))return he();const a=t.replaceSelection(s.text);return JSON.stringify({success:a,message:a?"Selection replaced.":"No text was selected to replace."})}case"get_diagnostics":{if(!(t!=null&&t.getDiagnostics))return he();const a=t.getDiagnostics();return JSON.stringify({count:a.length,diagnostics:a})}case"get_document_symbols":{if(!(t!=null&&t.getSymbols))return he();const a=await t.getSymbols();return JSON.stringify({count:a.length,symbols:a})}default:return JSON.stringify({error:`Unknown tool: ${e.function.name}`})}}let Zt=0;function Re(){return`msg_${Date.now()}_${++Zt}`}function en(r){const{socket:e,runningInstances:n,currentCode:t,currentLanguage:i,allScripts:s,editorApi:a,currentScriptId:p}=r,l=J((f,O,N)=>f==="none"||!N?null:{range:O,scriptId:p||"",scriptVersion:(t||"").length,kind:f,originalText:N},[p,t]),[m,g]=te(()=>{try{const f=window.localStorage.getItem("Editor.aiChatMessages");return f?JSON.parse(f):[]}catch{return[]}}),c=J(f=>{g(O=>{const N=typeof f=="function"?f(O):f,R=N.length>100?N.slice(-100):N;try{window.localStorage.setItem("Editor.aiChatMessages",JSON.stringify(R))}catch{try{const W=R.slice(-20);window.localStorage.setItem("Editor.aiChatMessages",JSON.stringify(W))}catch{}}return R})},[]),[y,d]=te(!1),[S,b]=te(null),[v,H]=te(window.localStorage.getItem("Editor.aiChatMode")||"agent"),E=J(f=>{H(f),window.localStorage.setItem("Editor.aiChatMode",f)},[]),[C,x]=te(null),[w,M]=te(window.localStorage.getItem("openai-model")||""),[re,G]=te([]),[_,Y]=te({}),[le,K]=te(!0),[de,I]=te(null),A=ne(null),X=ne(null),Q=ne(null),h=ne(null),T=J(f=>{M(f),window.localStorage.setItem("openai-model",f)},[]),k=J(async()=>{K(!0),I(null);try{const f=await Pt(e,n);if(G(f.models),Y(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&&I(f.errors.join("; "))}catch(f){I(String(f))}K(!1)},[e,n]);xe(()=>{k()},[k]);const z=J(f=>{let O=!1,N=!1;const R=[];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")N=!0;else if(W=!0,s&&s.length>0){const V=D[1].replace(/\//g,".").toLowerCase(),oe=V.split("."),ie=s.find(ye=>{const pe=ye.id.toLowerCase(),Z=pe.replace(/^script\.js\./,"");if(Z===V||Z.endsWith(`.${V}`)||pe===`script.js.${V}`)return!0;let _e=0;for(const me of oe){const Te=Z.indexOf(me,_e);if(Te===-1)return!1;_e=Te+me.length}return!0});if(ie)R.push(ie.id);else for(const ye of oe){if(ye.length<3)continue;const pe=s.filter(Z=>Z.id.toLowerCase().includes(`.${ye}`)||Z.name.toLowerCase().includes(ye));for(const Z of pe)R.includes(Z.id)||R.push(Z.id)}}}return W&&R.length===0&&(O=!0),{cleanMessage:f.replace(/@[\w/äöüÄÖÜß]+\s*/g,"").trim(),mentionedScriptIds:R,includeAll:O,includeDevices:N}},[s]),se=J(async(f,O,N)=>{h.current||(h.current=await Jt()),A.current||(A.current=await De(e,n));const R=Ye(),W=i==="blockly",ge=f||N.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 ${R}. Use the ioBroker JavaScript API correctly.
218
+
219
+ ioBroker object hierarchy: adapter.instance.device.channel.state
220
+ - A "state" is a single datapoint (e.g. zigbee2mqtt.0.0x1234.temperature)
221
+ - A "channel" groups related states (e.g. zigbee2mqtt.0.0x1234 contains temperature, humidity, battery)
222
+ - A "device" groups channels (e.g. zigbee2mqtt.0.0x1234)
223
+ - The channel/device often has the human-readable name (e.g. "Living Room Sensor")
224
+ When looking up info about a datapoint, ALWAYS also check its parent channel/device for the device name and context. Use get_object_info which returns the full parent hierarchy automatically.
225
+
226
+ To verify code or diagnose runtime behaviour, you can use the run_script tool: it executes a JavaScript/TypeScript snippet in the live engine (verbose mode) and returns everything it logged, then auto-stops it. Log the values you want to inspect via log(...) / console.log(...). It runs against the live system, so prefer read-only diagnostics (getState, $, getObject) and only call setState when the user explicitly asked to change something.
227
+
228
+ Available API and syntax rules:
229
+ ${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 Ge(e)),D+=`
230
+
231
+ Available smart home devices:
232
+ ${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+=`
233
+
234
+ The user is working on this Blockly script (currently open in the editor).
235
+
236
+ Generated JavaScript (shows the logic):
237
+ \`\`\`javascript
238
+ ${V}
239
+ \`\`\``,oe&&(D+=`
240
+
241
+ Blockly XML (use for modifications):
242
+ \`\`\`xml
243
+ ${oe}
244
+ \`\`\``)}else D+=`
245
+
246
+ The user's question is about this script (currently open in the editor, ${i||"javascript"}):
247
+ \`\`\`${i||"javascript"}
248
+ ${t}
249
+ \`\`\``;if(f&&s&&s.length>0)D+=`
250
+
251
+ 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.
252
+
253
+ ${qe(s,!0)}`;else if(N.length>0&&s){const F=s.filter(B=>N.includes(B.id));F.length>0&&(D+=`
254
+
255
+ 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:
256
+
257
+ ${qe(F,!0)}`)}return W&&(D+=`
258
+
259
+ ${Xe(R)}`),[{role:"system",content:D}]},[e,n,t,i,s]),ke=J(async f=>{if(!f.trim()||y)return;const O=_[w];if(!O){x(u.I18n.t("Please select a valid model"));return}const N=A.current||await De(e,n);if(A.current=N,!N){x(u.I18n.t("No API keys configured"));return}const R=Object.keys(n)[0];if(!R){x(u.I18n.t("No running javascript instance found"));return}const W=O==="custom"&&N.gptBaseUrl||"",ge={id:Re(),role:"user",content:f,timestamp:Date.now()},D={id:Re(),role:"assistant",content:`⏳ ${u.I18n.t("Generating plan...")}`,timestamp:Date.now()};c(F=>[...F,ge,D]),d(!0),x(null);try{const F=Ye();Q.current||(Q.current=await Ge(e));const B=Q.current||[],V=`Devices in my smart home:
260
+ ${JSON.stringify(B)}
261
+
262
+ I need a plan for this task: ${f}
263
+
264
+ Answer with max 6 lines. Use FULL device IDs from the list above (e.g. zigbee2mqtt.0.0xa4c1383f5ef5fb07.state). No explanation. No reasoning.
265
+ 1. IDs: <full IDs from the device list. If a device is not in the list, use TODO_DEVICE_ID as placeholder>
266
+ 2. Trigger: <on(id) for state changes OR schedule('min hour * * *') for time-based tasks>
267
+ 3. Condition: <when to act>
268
+ 4. Actions: <what to set, with full IDs and values. For Telegram use sendTo('telegram.0', 'send', {text: msg})>
269
+ 5. Else: <alternative actions or nothing>
270
+ 6. Extra: <logging, formatting, etc.>
271
+ Values are boolean (true/false) or numbers, not strings. Use .state not .state_toggle.`,oe=await Ne(e,R,{messages:[{role:"user",content:V}],model:w,provider:O,baseUrl:W});if(oe.error){x(oe.error),c(ae=>ae.slice(0,-2)),d(!1);return}const ie=Pe(oe.content||"");c(ae=>{const j=[...ae],P=j[j.length-1];return(P==null?void 0:P.role)==="assistant"&&(j[j.length-1]={...P,content:`📋 **${u.I18n.t("Plan")}:**
272
+ ${ie}`}),j});const ye={id:Re(),role:"assistant",content:`⏳ ${u.I18n.t("Generating code...")}`,timestamp:Date.now()};c(ae=>[...ae,ye]);const pe=i==="blockly",Z=pe?`TASK: ${f}
273
+
274
+ PLAN:
275
+ ${ie}
276
+
277
+ 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}
278
+
279
+ PLAN:
280
+ ${ie}
281
+
282
+ 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=pe?Xe(F):At(F),me=await Ne(e,R,{messages:[{role:"system",content:_e},{role:"user",content:Z}],model:w,provider:O,baseUrl:W});if(me.error){x(me.error),c(ae=>ae.slice(0,-1)),d(!1);return}const Te=Pe(me.content||"");c(ae=>{const j=[...ae],P=j[j.length-1];return(P==null?void 0:P.role)==="assistant"&&(j[j.length-1]={...P,content:Te}),j}),b(`${u.I18n.t("devices")}: ${B.length}`)}catch(F){x(String(F)),c(B=>B.slice(0,-1))}d(!1)},[w,_,y,e,n,i,c]),U=J(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 N=A.current||await De(e,n);if(A.current=N,!N){x(u.I18n.t("No API keys configured"));return}const R=Object.keys(n)[0];if(!R){x(u.I18n.t("No running javascript instance found"));return}let W=X.current;if(X.current=null,!W)try{const j=(ae=a==null?void 0:a.getSelection)==null?void 0:ae.call(a);j&&j.text&&(W=l("selection",j.range,j.text))}catch{}const ge={id:Re(),role:"user",content:f,timestamp:Date.now(),sourceRange:W},D={id:Re(),role:"assistant",content:"",timestamp:Date.now(),sourceRange:W};c(j=>[...j,ge,D]),d(!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),pe=O==="custom"&&N.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:
283
+ ${be.map(je=>` - ${je.scriptName} (${je.scriptId}) line ${je.lineNumber}: ${je.usageType} → ${je.line}`).join(`
284
+ `)}`)}P.length>0&&(Z+=`
285
+
286
+ [Automatic analysis results]
287
+ ${P.join(`
288
+
289
+ `)}`)}}const _e=[...ye,...m.filter(j=>j.role!=="system").map(j=>({role:j.role,content:j.content})),{role:"user",content:Z}],me=v==="agent",Te=5;try{const j=[..._e];for(let P=0;P<Te;P++){const ee=await Ne(e,R,{messages:j,model:w,provider:O,baseUrl:pe,...me?{tools:Ut}:{}});if(ee.error){if(me&&P===0&&ee.error.toLowerCase().includes("tool")){const q=await Ne(e,R,{messages:j,model:w,provider:O,baseUrl:pe});if(q.error)x(q.error),c($=>$.slice(0,-1));else{const $=Pe(q.content||"");c(ce=>{const fe=[...ce],Be=fe[fe.length-1];return(Be==null?void 0:Be.role)==="assistant"&&(fe[fe.length-1]={...Be,content:$}),fe})}break}x(ee.error),c(q=>q.slice(0,-1));break}let be=ee.tool_calls;if((!be||be.length===0)&&me&&ee.content){const q=ee.content.trim();try{const $=JSON.parse(q);$.name&&$.arguments&&(be=[{id:`text_tool_${Date.now()}`,type:"function",function:{name:$.name,arguments:JSON.stringify($.arguments)}}])}catch{}}if(!be||be.length===0){const q=Pe(ee.content||"");c($=>{const ce=[...$],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 $={};try{$=JSON.parse(q.function.arguments)}catch{}switch(q.function.name){case"search_datapoints":return`🔍 ${u.I18n.t("Searching datapoints")}: "${String($.query||"")}"`;case"get_state_value":return`📊 ${u.I18n.t("Reading value")}: ${String($.id||"")}`;case"get_object_info":return`📋 ${u.I18n.t("Loading object info")}: ${String($.id||"")}`;case"search_scripts":return`🔍 ${u.I18n.t("Searching scripts")}: "${String($.query||"")}"`;case"read_script":return`📖 ${u.I18n.t("Reading script")}: ${String($.id||"")}`;case"list_scripts":return`📂 ${u.I18n.t("Loading script list")}`;default:return`⚙️ ${q.function.name}`}});c(q=>{const $=[...q],ce=$[$.length-1];return(ce==null?void 0:ce.role)==="assistant"&&($[$.length-1]={...ce,content:je.join(`
290
+ `)}),$}),j.push({role:"assistant",content:ee.content||"",tool_calls:ee.tool_calls});for(const q of ee.tool_calls){const $=await Qt(e,q,s,a,R);j.push({role:"tool",tool_call_id:q.id,content:$})}}}catch(j){x(String(j)),c(P=>P.slice(0,-1))}d(!1)},[w,_,m,y,e,n,se,z,s,v,ke,c,l,a]),ue=J(()=>{c([]),x(null),d(!1),b(null),Dt(),window.localStorage.removeItem("Editor.aiChatHistory")},[c]),it=J(async(f,O)=>{const N=_[w];if(!N)return`Error: ${u.I18n.t("Please select a valid model")}`;const R=A.current||await De(e,n);if(A.current=R,!R)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=N==="custom"&&R.gptBaseUrl||"",D=i||"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:
291
+ - 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.
292
+ - 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.
293
+ - If they ask something ambiguous or meta (e.g. "is this correct?"), reply in prose first and only include code if proposing a change.
294
+ ioBroker globals available in scripts: on, setState, getState, schedule, sendTo, log, createState, setStateDelayed, existsState, httpGet, httpPost.`,B=O?`Code from my editor:
295
+
296
+ \`\`\`${D==="blockly"?"xml":D}
297
+ ${O}
298
+ \`\`\`
299
+
300
+ ${f}`:f;try{const V=await Ne(e,W,{messages:[{role:"system",content:F},{role:"user",content:B}],model:w,provider:N,baseUrl:ge});return V.error?`Error: ${V.error}`:V.content||""}catch(V){return`Error: ${V.message||String(V)}`}},[w,_,n,e,i]),at=J(f=>{f.range&&f.code?X.current=l(f.kind||"codelens",f.range,f.code):X.current=null,Ze(async()=>{const{buildActionPrompt:O}=await Promise.resolve().then(()=>dn);return{buildActionPrompt:O}},void 0,import.meta.url).then(({buildActionPrompt:O})=>{const N=O({action:f.action,code:f.code,language:i||"javascript",diagnostic:f.diagnostic,question:f.question,rangeLabel:f.rangeLabel});N?U(N):X.current=null}).catch(()=>{X.current=null,x(u.I18n.t("Failed to build AI action prompt"))})},[U,i,l]);return{messages:m,isLoading:y,error:C,model:w,availableModels:re,modelProviderMap:_,modelsLoading:le,modelsError:de,lastContextInfo:S,mode:v,setMode:E,setModel:T,sendMessage:U,triggerAiAction:at,askInline:it,clearChat:ue,retryLoadModels:k}}const tn=({code:r,language:e,themeType:n,onInsertCode:t,onShowDiff:i,sourceRange:s})=>{const a=ne(null);xe(()=>{var g;const l=window.monaco;if(!a.current||!((g=l==null?void 0:l.editor)!=null&&g.colorize))return;const m=e==="ts"||e==="typescript"?"typescript":e||"javascript";l.editor.colorize(r,m,{theme:n==="dark"?"vs-dark":"vs"}).then(c=>{a.current&&(a.current.innerHTML=c)})},[r,e,n]);const p=J(()=>{navigator.clipboard.writeText(r)},[r]);return o.jsxs(L,{sx:{position:"relative",my:1,borderRadius:1,overflow:"hidden",border:"1px solid",borderColor:"divider"},children:[o.jsxs(L,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",px:1,py:.5,bgcolor:"action.hover",borderBottom:"1px solid",borderColor:"divider"},children:[o.jsx(L,{sx:{fontSize:"0.75rem",color:"text.secondary",textTransform:"uppercase"},children:e||"javascript"}),o.jsxs(L,{children:[o.jsx(ve,{title:u.I18n.t("Copy"),children:o.jsx(we,{size:"small",onClick:p,children:o.jsx(kt,{sx:{fontSize:16}})})}),t&&o.jsx(ve,{title:u.I18n.t("Insert into editor"),children:o.jsx(we,{size:"small",onClick:()=>t(r),children:o.jsx(et,{sx:{fontSize:16}})})}),i&&o.jsx(ve,{title:u.I18n.t("Show as diff"),children:o.jsx(we,{size:"small",onClick:()=>i(r,s),children:o.jsx(Ct,{sx:{fontSize:16}})})})]})]}),o.jsx("pre",{ref:a,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})]})},nn=({xml:r,themeType:e})=>{const n=ne(null),t=ne(null),[i,s]=te(60),a=ne(!1);return xe(()=>{a.current&&(a.current=!1,requestAnimationFrame(()=>{const p=window.Blockly,l=t.current;p&&l&&(p.svgResize(l),l.scrollCenter())}))},[i]),xe(()=>{const p=window.Blockly;if(!(!p||!n.current)){t.current&&(t.current.dispose(),t.current=null);try{const l=p.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=l;let m=r.trim();m.startsWith("<xml")||(m=`<xml xmlns="https://developers.google.com/blockly/xml">${m}</xml>`);const g=p.utils.xml.textToDom(m);let c=10;const y=Array.from(g.querySelectorAll(":scope > block"));for(const b of y)b.setAttribute("x","10"),b.setAttribute("y",String(c)),c+=200;p.Xml.domToWorkspace(g,l);const d=l.getTopBlocks(!1);if(d.length>1){let b=10;for(const v of d){const H=v.getRelativeToSurfaceXY();v.moveBy(10-H.x,b-H.y),b+=v.getHeightWidth().height+20}}const S=l.getBlocksBoundingBox();if(S){const b=S.bottom-S.top+20,v=Math.max(60,Math.ceil(b));a.current=!0,s(v)}}catch{}return()=>{t.current&&(t.current.dispose(),t.current=null)}}},[r,e]),o.jsx(L,{ref:n,sx:{width:"100%",height:i,minHeight:60,borderRadius:1,overflow:"hidden",border:"1px solid",borderColor:"divider"}})};function sn(r){const e=[],n=/```(\w*)\n?([\s\S]*?)```/g;let t=0,i;for(;(i=n.exec(r))!==null;){if(i.index>t){const s=r.substring(t,i.index).trim();s&&e.push({type:"text",content:s})}e.push({type:"code",content:i[2].trim(),language:i[1]||"javascript"}),t=i.index+i[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,i,s=0;for(;(i=n.exec(r))!==null;)i.index>t&&e.push(r.substring(t,i.index)),i[2]?e.push(o.jsx("strong",{children:i[2]},s++)):i[3]?e.push(o.jsx("em",{children:i[3]},s++)):i[4]&&e.push(o.jsx("code",{className:"ai-chat-inline-code",style:{padding:"2px 6px",borderRadius:4,fontSize:"0.85em",fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace"},children:i[4]},s++)),t=i.index+i[0].length;return t<r.length&&e.push(r.substring(t)),e}function Qe(r){return r.trim().startsWith("|")&&r.trim().endsWith("|")}function rn(r){return/^\|[\s:]*-+[\s:|-]*\|$/.test(r.trim())}function on(r,e,n){const t=e.palette.mode==="dark",i=p=>p.trim().replace(/^\||\|$/g,"").split("|").map(l=>l.trim()),s=i(r[0]),a=r.slice(2).map(i);return o.jsx(L,{sx:{overflowX:"auto",my:1},children:o.jsxs("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"0.8rem",color:e.palette.text.primary},children:[o.jsx("thead",{children:o.jsx("tr",{children:s.map((p,l)=>o.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(p)},l))})}),o.jsx("tbody",{children:a.map((p,l)=>o.jsx("tr",{style:{backgroundColor:l%2===1?t?e.palette.grey[900]:e.palette.grey[50]:void 0},children:p.map((m,g)=>o.jsx("td",{style:{border:`1px solid ${e.palette.divider}`,padding:"6px 10px",color:e.palette.text.primary},children:Ee(m)},g))},l))})]})},n)}function an(r,e){const n=r.split(`
301
+ `),t=[];let i=0,s=0;for(;s<n.length;){const p=n[s].trim();if(p===""){s++;continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(p)){t.push(o.jsx("hr",{style:{border:"none",borderTop:`1px solid ${e.palette.divider}`,margin:"8px 0"}},i++)),s++;continue}const l=p.match(/^(#{1,4})\s+(.+)$/);if(l){const m=l[1].length,g=["1.2em","1.1em","1em","0.95em"];t.push(o.jsx("div",{style:{fontWeight:600,fontSize:g[m-1],margin:"8px 0 4px"},children:Ee(l[2])},i++)),s++;continue}if(Qe(p)&&s+1<n.length&&rn(n[s+1].trim())&&s+2<n.length){const m=[n[s],n[s+1]];let g=s+2;for(;g<n.length&&Qe(n[g]);)m.push(n[g]),g++;t.push(on(m,e,i++)),s=g;continue}if(/^[-*+]\s/.test(p)){const m=[];for(;s<n.length&&/^\s*[-*+]\s/.test(n[s]);)m.push(n[s].replace(/^\s*[-*+]\s/,"").trim()),s++;t.push(o.jsx("ul",{style:{margin:"4px 0",paddingLeft:20},children:m.map((g,c)=>o.jsx("li",{children:Ee(g)},c))},i++));continue}if(/^\d+[.)]\s/.test(p)){const m=[];for(;s<n.length&&/^\s*\d+[.)]\s/.test(n[s]);)m.push(n[s].replace(/^\s*\d+[.)]\s/,"").trim()),s++;t.push(o.jsx("ol",{style:{margin:"4px 0",paddingLeft:20},children:m.map((g,c)=>o.jsx("li",{children:Ee(g)},c))},i++));continue}t.push(o.jsx("div",{children:Ee(p)},i++)),s++}return t}const cn=({message:r,themeType:e,currentLanguage:n,onInsertCode:t,onShowDiff:i,onApplyCode:s})=>{const a=r.role==="user",p=ct(),l=a?e==="dark"?p.palette.primary.dark:p.palette.primary.main:e==="dark"?p.palette.secondary.dark:p.palette.secondary.main,m=p.palette.getContrastText(l),g=Ae(()=>sn(r.content),[r.content]),c=(b,v)=>!!(b==="xml"||b==="blockly"||n==="blockly"&&v&&/<block\s+type=/.test(v)),y=l,d=a?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=a?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 o.jsxs(L,{sx:{display:"flex",gap:1,px:1.5,py:1,mx:.75,my:.5,bgcolor:d,borderRadius:1.5,borderLeft:"3px solid",borderLeftColor:y,transition:"background-color 120ms","&:hover":{bgcolor:S}},children:[o.jsx(lt,{sx:{width:28,height:28,bgcolor:l,color:m,flexShrink:0,mt:.5},children:a?o.jsx(It,{sx:{fontSize:18}}):o.jsx(Nt,{sx:{fontSize:18}})}),o.jsx(L,{sx:{flex:1,minWidth:0,fontSize:"0.875rem",lineHeight:1.6},children:g.map((b,v)=>b.type==="code"?c(b.language,b.content)?o.jsxs(L,{sx:{my:1},children:[o.jsx(nn,{xml:b.content,themeType:e}),o.jsxs(L,{sx:{display:"flex",gap:.5,mt:.5},children:[s&&o.jsx(We,{size:"small",variant:"contained",color:"primary",startIcon:o.jsx(Ot,{sx:{fontSize:14}}),onClick:()=>s(b.content),sx:{textTransform:"none",fontSize:"0.75rem"},children:u.I18n.t("Apply blocks")}),t&&o.jsx(We,{size:"small",variant:"outlined",startIcon:o.jsx(et,{sx:{fontSize:14}}),onClick:()=>t(b.content),sx:{textTransform:"none",fontSize:"0.75rem"},children:u.I18n.t("Insert blocks")})]})]},v):o.jsx(tn,{code:b.content,language:b.language||"javascript",themeType:e,onInsertCode:t,onShowDiff:i,sourceRange:r.sourceRange||null},v):o.jsx(L,{sx:{wordBreak:"break-word",color:p.palette.text.primary},children:an(b.content,p)},v))})]})};function ln(r){const e=(r||"").toLowerCase();return e.includes("blockly")||e.includes("rules")?"blockly":e.includes("typescript")?"typescript":"javascript"}function Ie(r,e){return`\`\`\`${e==="blockly"?"xml":e}
302
+ ${r}
303
+ \`\`\``}function rt(r){const e=(r.code||"").trim(),n=ln(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.","",Ie(e,n)].join(`
304
+ `):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.`,"",Ie(e,n)].join(`
305
+ `):null;case"comment":return e?[`Add clear, concise inline comments to this ioBroker ${n} code${t}.`,"Only add comments where they add real value (non-obvious logic, tricky edge cases, business rules).","Do not over-comment trivial lines. Return the commented version in a code block.","",Ie(e,n)].join(`
306
+ `):null;case"fix":{if(!e)return null;const i=(r.diagnostic||"").trim(),s=i?`
307
+ Reported problem: ${i}`:"";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.","",Ie(e,n)].join(`
308
+ `)}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.","",Ie(e,n)].join(`
309
+ `):null;case"ask":{const i=(r.question||"").trim();return i?e?[`Regarding this ioBroker ${n} code${t}:`,"",Ie(e,n),"",i].join(`
310
+ `):i: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(),i=(n[2]||"").trim(),a={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 a?{action:a,rest:i}:null}const dn=Object.freeze(Object.defineProperty({__proto__:null,buildActionPrompt:rt,parseSlashCommand:ot},Symbol.toStringTag,{value:"Module"}));function un(){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 pn({provider:r,isDark:e}){return $t[r]?o.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 fn=({onSend:r,disabled:e,themeType:n,hasSelection:t,selectionText:i,allScripts:s,model:a,availableModels:p,modelProviderMap:l,modelsLoading:m,onModelChange:g,mode:c,onModeChange:y,currentLanguage:d})=>{const[S,b]=te(""),[v,H]=te(!1),[E,C]=te(""),[x,w]=te(0),M=ne(null),re=ne(-1),G=ne(mn()),_=ne(-1),Y=ne(""),le=Ae(()=>{const T=un().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,"/");T.push({id:`@${z}`,label:`@${z}`,description:`${k.name} [${k.enabled?"active":"inactive"}]`})}return T},[s]),K=Ae(()=>{if(!E)return le;const h=E.toLowerCase();return le.filter(T=>T.id.toLowerCase().includes(h)||T.description.toLowerCase().includes(h))},[le,E]);xe(()=>{w(0)},[E]);const de=J(()=>{const h=S.trim();if(!h||e)return;let T=h;const k=ot(h);if(k){const z=t&&i?i:"",se=rt({action:k.action,code:z,language:d||"javascript",question:k.action==="ask"?k.rest:void 0,diagnostic:k.action==="fix"&&k.rest||void 0});se&&(T=se)}else t&&i&&(T=`[Selected code in editor]
311
+ \`\`\`
312
+ ${i}
313
+ \`\`\`
314
+
315
+ ${h}`);G.current.push(h),_.current=-1,Y.current="";try{const z=G.current.slice(-50);window.localStorage.setItem("Editor.aiChatHistory",JSON.stringify(z))}catch{}r(T),b(""),H(!1),requestAnimationFrame(()=>{var z;return(z=M.current)==null?void 0:z.focus()})},[S,e,r,t,i,d]),I=J(h=>{const T=re.current,k=M.current;if(T<0){const ue=S?`${S}${h} `:`${h} `;b(ue),H(!1),C(""),setTimeout(()=>{k&&(k.focus(),k.setSelectionRange(ue.length,ue.length))},0);return}const z=S.substring(0,T),se=(k==null?void 0:k.selectionStart)??S.length,ke=S.substring(se),U=`${z}${h} ${ke}`;b(U),H(!1),C(""),re.current=-1,setTimeout(()=>{if(k){const ue=z.length+h.length+1;k.focus(),k.setSelectionRange(ue,ue)}},0)},[S]),A=J(()=>{re.current=-1,C(""),H(h=>!h)},[]),X=J(h=>{const T=h.target.value;b(T);const k=h.target.selectionStart??T.length,se=T.substring(0,k).match(/@([\w/äöüÄÖÜß]*)$/);se?(re.current=k-se[0].length,C(se[1]),H(!0)):(H(!1),C(""))},[]),Q=J(h=>{if(v&&K.length>0){if(h.key==="ArrowDown"){h.preventDefault(),w(T=>(T+1)%K.length);return}if(h.key==="ArrowUp"){h.preventDefault(),w(T=>(T-1+K.length)%K.length);return}if(h.key==="Enter"||h.key==="Tab"){h.preventDefault(),I(K[x].id);return}if(h.key==="Escape"){h.preventDefault(),H(!1);return}}if(h.key==="ArrowUp"&&!v&&G.current.length>0){const T=M.current,k=!T||T.selectionStart===0,z=!S.includes(`
316
+ `);if(k&&z){h.preventDefault(),_.current===-1?(Y.current=S,_.current=G.current.length-1):_.current>0&&_.current--,b(G.current[_.current]);return}}if(h.key==="ArrowDown"&&!v&&_.current>=0){const T=M.current,k=!T||T.selectionStart===S.length,z=!S.includes(`
317
+ `);if(k&&z){h.preventDefault(),_.current<G.current.length-1?(_.current++,b(G.current[_.current])):(_.current=-1,b(Y.current));return}}h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),de())},[de,v,K,x,I,S]);return o.jsxs(L,{sx:{borderTop:"1px solid",borderColor:"divider",position:"relative"},children:[v&&K.length>0&&o.jsx(dt,{elevation:4,sx:{position:"absolute",bottom:"100%",left:8,right:8,maxHeight:200,overflow:"auto",zIndex:10,mb:.5},children:o.jsx(ut,{dense:!0,disablePadding:!0,children:K.slice(0,15).map((h,T)=>o.jsx(pt,{selected:T===x,onClick:()=>I(h.id),sx:{py:.25,minHeight:32},children:o.jsx(mt,{primary:h.label,secondary:h.description,primaryTypographyProps:{fontSize:"0.8rem",fontWeight:500},secondaryTypographyProps:{fontSize:"0.7rem"}})},h.id))})}),c==="code"&&o.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&&i&&o.jsx(Fe,{icon:o.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)"}}),o.jsxs(L,{sx:{mx:1,mt:.5,mb:.5,border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden","&:focus-within":{borderColor:"primary.main"}},children:[o.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"}}}),o.jsxs(L,{sx:{display:"flex",alignItems:"center",gap:.75,px:1,pb:.5},children:[o.jsx(ve,{title:o.jsxs(L,{sx:{fontSize:"0.8rem",lineHeight:1.5,maxWidth:360},children:[o.jsx(L,{sx:{fontWeight:600,mb:.75},children:u.I18n.t("AI chat mode")}),o.jsxs(L,{sx:{mb:.75},children:[o.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.")]}),o.jsxs(L,{sx:{mb:.75},children:[o.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".')]}),o.jsxs(L,{children:[o.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:o.jsxs(He,{value:c,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:[o.jsx(ze,{value:"chat",sx:{fontSize:"0.75rem"},title:u.I18n.t("Plain conversation. Best for: general questions, syntax help, concept explanations."),children:"💬 Chat"}),o.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"}),o.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"})]})}),o.jsx(He,{value:a,onChange:h=>g(h.target.value),size:"small",disabled:m||p.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:p.map(h=>o.jsxs(ze,{value:h,sx:{fontSize:"0.75rem",display:"flex",gap:.5},children:[o.jsx(pn,{provider:l[h],isDark:n==="dark"}),h]},h))}),o.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:o.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:o.jsx(Tt,{sx:{fontSize:16}})})}),o.jsx(L,{sx:{flex:1}}),o.jsxs(Oe,{variant:"caption",sx:{color:"text.disabled",fontSize:"0.65rem",mr:.5,whiteSpace:"nowrap"},children:["Enter ",u.I18n.t("to send")]}),o.jsx(ve,{title:`${u.I18n.t("Send")} (Enter)`,children:o.jsx("span",{children:o.jsx(we,{color:"primary",onClick:de,disabled:e||!S.trim(),size:"small",sx:{p:.25},children:o.jsx(Et,{sx:{fontSize:18}})})})})]})]})]})},On=({socket:r,runningInstances:e,themeType:n,currentCode:t,currentLanguage:i,selectedCode:s,allScripts:a,editorApi:p,aiActionRequest:l,onAiActionConsumed:m,onRegisterInlineAsk:g,onInsertCode:c,onShowDiff:y,onApplyCode:d,currentScriptId:S,onClose:b})=>{var ke;const v=ne(null),H=Ae(()=>({socket:r,runningInstances:e,currentCode:t,currentLanguage:i,allScripts:a,editorApi:p,currentScriptId:S}),[r,e,t,i,a,p,S]),{messages:E,isLoading:C,error:x,model:w,availableModels:M,modelProviderMap:re,modelsLoading:G,modelsError:_,lastContextInfo:Y,mode:le,setMode:K,setModel:de,sendMessage:I,triggerAiAction:A,askInline:X,clearChat:Q,retryLoadModels:h}=en(H);xe(()=>(g==null||g(X),()=>g==null?void 0:g(null)),[X,g]);const T=ne(null);xe(()=>{!l||T.current===l||(T.current=l,A(l),m==null||m())},[l,A,m]),xe(()=>{var U;(U=v.current)==null||U.scrollIntoView({behavior:"smooth"})},[E]);const k=J(U=>{c==null||c(U)},[c]),z=J((U,ue)=>{y==null||y(U,ue)},[y]),se=J(U=>{d==null||d(U)},[d]);return o.jsxs(L,{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:[o.jsxs(L,{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:[o.jsx(Oe,{variant:"subtitle2",sx:{fontWeight:600,flex:1,color:"text.primary"},children:u.I18n.t("AI Chat")}),G&&o.jsx(Ve,{size:16}),o.jsx(ve,{title:u.I18n.t("New chat"),children:o.jsx(we,{size:"small",onClick:Q,children:o.jsx(_t,{sx:{fontSize:18}})})}),o.jsx(ve,{title:u.I18n.t("Close"),children:o.jsx(we,{size:"small",onClick:b,children:o.jsx(jt,{sx:{fontSize:18}})})})]}),(x||_)&&o.jsx(ht,{severity:"error",sx:{m:1,py:0},action:_?o.jsx(we,{size:"small",onClick:h,children:o.jsx(xt,{sx:{fontSize:16}})}):void 0,children:x||_}),Y&&o.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:Y}),o.jsxs(L,{sx:{flex:1,overflow:"auto",py:1},children:[E.length===0&&!C&&o.jsxs(L,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",color:"text.secondary",px:3,textAlign:"center"},children:[o.jsx(Oe,{variant:"body2",sx:{mb:1},children:u.I18n.t("Ask questions about your script, request changes, or generate new code.")}),o.jsxs(Oe,{variant:"caption",color:"text.disabled",children:["Enter ",u.I18n.t("to send"),", Shift+Enter ",u.I18n.t("for new line")]})]}),E.filter(U=>U.role!=="system").map(U=>o.jsx(cn,{message:U,themeType:n,currentLanguage:i,onInsertCode:k,onShowDiff:z,onApplyCode:se},U.id)),C&&((ke=E[E.length-1])==null?void 0:ke.content)===""&&o.jsxs(L,{sx:{display:"flex",alignItems:"center",gap:1,px:2,py:1},children:[o.jsx(Ve,{size:16}),o.jsx(Oe,{variant:"caption",color:"text.secondary",children:u.I18n.t("Thinking...")})]}),o.jsx("div",{ref:v})]}),o.jsx(fn,{onSend:I,disabled:C||M.length===0,themeType:n,hasSelection:!!s,selectionText:s,allScripts:a,model:w,availableModels:M,modelProviderMap:re,modelsLoading:G,onModelChange:de,mode:le,onModeChange:K,currentLanguage:i})]})};export{On 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-C22Gpet7.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-BTQOdA7v.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-CeYV4czE.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-Bn8xJ3LV.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-CO9RA-Wq.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-Bw22wl4W.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};