iobroker.javascript 10.0.0 → 10.1.0
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 +41 -6
- package/admin/assets/AiChatPanel-C4kuqP2U.js +237 -0
- package/admin/assets/AiDiffView-zJTEnv05.js +1 -0
- package/admin/assets/BlocklyEditor-BB77aFJI.js +84 -0
- package/admin/assets/ContextWrapper-C2yvd2Tn.css +1 -0
- package/admin/assets/ContextWrapper-W2H0z6zD.js +136 -0
- package/admin/assets/Debugger-DCMWjeGm.js +15 -0
- package/admin/assets/Error-CBC2oZzb.js +1 -0
- package/admin/assets/Import-B-F9IhZ-.js +1 -0
- package/admin/assets/RulesEditor-ByjgEaVo.js +1 -0
- package/admin/assets/RulesEditor-k-DMHotH.css +1 -0
- package/admin/assets/{ScriptEditor-BGIuoNei.js → ScriptEditor-CMYUt5S4.js} +2 -2
- package/admin/assets/{ScriptEditorVanillaMonaco-DyMQtoTQ.js → ScriptEditorVanillaMonaco-v12-gORS.js} +3 -3
- package/admin/assets/Send-CChqR5Oy.js +1 -0
- package/admin/assets/_virtual_mf-localSharedImportMap___mfe_internal__iobroker_javascript__mf_owner__1-7EPUlgCk.js +1 -0
- package/admin/assets/_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-DuplUOZN.js +1243 -0
- package/admin/assets/{_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-BBAXJaqI.js → _virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-JkwfVf8d.js} +1 -1
- package/admin/assets/{aiCodeLensProvider-hyAmut0e.js → aiCodeLensProvider-BGvIu6hH.js} +1 -1
- package/admin/assets/blockly-C4zJerWL.js +1047 -0
- package/admin/assets/blocks_action-CvnOHXwt.js +1 -0
- package/admin/assets/blocks_convert-BZlKcd02.js +3 -0
- package/admin/assets/blocks_logic-B33Pypxr.js +1 -0
- package/admin/assets/blocks_number-k2IjE7OH.js +1 -0
- package/admin/assets/blocks_object-B64vSfel.js +1 -0
- package/admin/assets/blocks_procedures-BpvNI5dO.js +3 -0
- package/admin/assets/blocks_sendto-pwZchfe0.js +5 -0
- package/admin/assets/blocks_switch-DViYCmQd.js +2 -0
- package/admin/assets/blocks_system-BZZcGqTJ.js +1 -0
- package/admin/assets/blocks_text-BOvtHN2r.js +1 -0
- package/admin/assets/blocks_time-BH2F-ylT.js +1 -0
- package/admin/assets/blocks_timeout-C3BoW4XJ.js +1 -0
- package/admin/assets/blocks_trigger-gwXvuAHV.js +2 -0
- package/admin/assets/blocks_words-D8PL_nSE.js +1 -0
- package/admin/assets/{cronHoverProvider-pKJkSevo.js → cronHoverProvider-DjY3jLvQ.js} +1 -1
- package/admin/assets/dist-D6o4h8Pd.js +4 -0
- package/admin/assets/field_cron-BMQWPb61.js +1 -0
- package/admin/assets/field_oid-BGIMv9gw.js +1 -0
- package/admin/assets/field_script-CdzYBCe6.js +1 -0
- package/admin/assets/helpers-Crmcgphg.js +1 -0
- package/admin/assets/hostInit-DBlZi_Kt.js +1 -0
- package/admin/assets/index-BvPVHv3P.js +192 -0
- package/admin/assets/{inlineChatWidget-ZaisTOLh.js → inlineChatWidget-SDoyVtOR.js} +2 -2
- package/admin/assets/{inlineDiffController-hTwHHqcc.js → inlineDiffController-CnHE3Rwd.js} +2 -2
- package/admin/assets/javascript-DVIhlTDr.js +218 -0
- package/admin/assets/{mf-entry-bootstrap-0-d6052b31.js → mf-entry-bootstrap-0-a03ecebd.js} +6 -2
- package/admin/assets/{mjs-DWqivHEk.js → mjs-Bh7xFIpd.js} +2 -2
- package/admin/assets/{stateHoverProvider-C7DawIs-.js → stateHoverProvider-D0iXo6YF.js} +3 -3
- package/admin/assets/{virtualExposes-Ed0lGq7k.js → virtualExposes-DgGB-18P.js} +1 -1
- package/admin/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__iobroker_javascript__remoteEntry_js-DYEYnOkt.js +1 -0
- package/admin/assets/virtual_mf-exposes___mfe_internal__iobroker_javascript__remoteEntry_js-ChiJXsfH.js +1 -0
- package/admin/custom/assets/Components-CuFt9lAY.js +1 -0
- package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1-DljJyQQg.js +1 -0
- package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_react__loadShare__.js-D0M1SjIE.js +1 -0
- package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_styled__loadShare__.js-CGb5Cofy.js → _virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_styled__loadShare__.js-BD2OkSge.js} +1 -1
- package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BVCIAgbo.js → _virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-pM642JFd.js} +91 -91
- package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_json_mf_2_config__loadShare__.js-BkB0anQX.js → _virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_json_mf_2_config__loadShare__.js-BLelmJ7Y.js} +74 -74
- package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-BotqDuw-.js → _virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-BGiB1l5e.js} +1 -1
- package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__prebuild__date_mf_2_fns__prebuild__-Cb5TR7FB.js → _virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__prebuild__date_mf_2_fns__prebuild__-D5hqXJXI.js} +1 -1
- package/admin/custom/assets/hostInit-0DGPuZTB.js +1 -0
- package/admin/custom/assets/{index-uEKAoVT7.js → index-DcFI5r-g.js} +1 -1
- package/admin/custom/assets/{lib-Yj8cfN0A.js → lib-BlUjuGH7.js} +1 -1
- package/admin/custom/assets/{mf-entry-bootstrap-0-77793feb.js → mf-entry-bootstrap-0-efd847a6.js} +6 -2
- package/admin/custom/assets/{setYear-DJ9FbdkO.js → setYear-BaCcPbbI.js} +1 -1
- package/admin/custom/assets/virtualExposes-DGxNcyb6.js +1 -0
- package/admin/custom/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-DVNwFcUr.js +1 -0
- package/admin/custom/assets/virtual_mf-exposes___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-DPck7zEs.js +2 -0
- package/admin/custom/customComponents.js +1 -1
- package/admin/google-blockly/VERSION +1 -0
- package/admin/google-blockly/media/drop.mp3 +0 -0
- package/admin/google-blockly/msg/js/de.js +332 -56
- package/admin/google-blockly/msg/js/en.js +319 -43
- package/admin/google-blockly/msg/js/es.js +319 -42
- package/admin/google-blockly/msg/js/fr.js +315 -39
- package/admin/google-blockly/msg/js/it.js +327 -51
- package/admin/google-blockly/msg/js/nl.js +376 -100
- package/admin/google-blockly/msg/js/pl.js +318 -42
- package/admin/google-blockly/msg/js/pt.js +318 -42
- package/admin/google-blockly/msg/js/ru.js +320 -44
- package/admin/google-blockly/msg/js/uk.js +326 -50
- package/admin/google-blockly/msg/js/zh-cn.js +322 -46
- package/admin/i18n/de.json +48 -26
- package/admin/i18n/en.json +47 -25
- package/admin/i18n/es.json +48 -18
- package/admin/i18n/fr.json +47 -17
- package/admin/i18n/it.json +47 -17
- package/admin/i18n/nl.json +47 -17
- package/admin/i18n/pl.json +48 -18
- package/admin/i18n/pt.json +47 -17
- package/admin/i18n/ru.json +47 -17
- package/admin/i18n/uk.json +47 -17
- package/admin/i18n/zh-cn.json +47 -17
- package/admin/jsonConfig.json +367 -0
- package/admin/mf-manifest.json +1 -1
- package/admin/mf-stats.json +1 -1
- package/admin/remoteEntry.js +1 -1
- package/admin/tab.html +12 -95
- package/build/lib/mirror.js +9 -0
- package/build/lib/mirror.js.map +1 -1
- package/build/lib/sandbox.js +35 -0
- package/build/lib/sandbox.js.map +1 -1
- package/build/lib/typescriptSettings.js +112 -2
- package/build/lib/typescriptSettings.js.map +1 -1
- package/build/lib/typescriptTools.js +168 -43
- package/build/lib/typescriptTools.js.map +1 -1
- package/build/main.js +10 -5
- package/build/main.js.map +1 -1
- package/build/types.d.ts +41 -0
- package/docs/en/javascript.md +16 -0
- package/docs/en/upgrade-guide.md +3 -0
- package/io-package.json +45 -15
- package/package.json +8 -3
- package/admin/assets/AiChatPanel-p0KAg6Cs.js +0 -237
- package/admin/assets/AiDiffView-BPTLnNx1.js +0 -1
- package/admin/assets/BlocklyEditor-CAjVMhYT.js +0 -81
- package/admin/assets/ContextWrapper-BVc8wTK_.css +0 -1
- package/admin/assets/ContextWrapper-D9CrnNKs.js +0 -127
- package/admin/assets/Debugger-SjROokFI.js +0 -15
- package/admin/assets/Error-DDfrxAt2.js +0 -1
- package/admin/assets/Import-DpTg1Jow.js +0 -1
- package/admin/assets/RulesEditor-BSRFWpEm.css +0 -1
- package/admin/assets/RulesEditor-D0hgrcBc.js +0 -1
- package/admin/assets/_virtual_mf-localSharedImportMap___mfe_internal__iobroker_javascript__mf_owner__1-DWJotR1B.js +0 -1
- package/admin/assets/_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-CxICLr5Z.js +0 -1243
- package/admin/assets/dist-uw5orDgd.js +0 -4
- package/admin/assets/hostInit-BFg5u9hY.js +0 -1
- package/admin/assets/index-B1gICjdq.js +0 -192
- package/admin/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__iobroker_javascript__remoteEntry_js-BYs71IQF.js +0 -1
- package/admin/assets/virtual_mf-exposes___mfe_internal__iobroker_javascript__remoteEntry_js-DnnXQRkG.js +0 -1
- package/admin/custom/assets/Components-BrDyDHXh.js +0 -1
- package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1-CyYJM2-v.js +0 -1
- package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_react__loadShare__.js-BdzCssLn.js +0 -1
- package/admin/custom/assets/hostInit-DJx2uXXy.js +0 -1
- package/admin/custom/assets/virtualExposes-CxDjLoYu.js +0 -1
- package/admin/custom/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-BU-ugy_7.js +0 -1
- package/admin/custom/assets/virtual_mf-exposes-ssr___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-BEfZbrf7.js +0 -2
- package/admin/custom/assets/virtual_mf-exposes___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-CTeZ0Jpm.js +0 -2
- package/admin/google-blockly/blockly_compressed.js +0 -1679
- package/admin/google-blockly/blocks_compressed.js +0 -193
- package/admin/google-blockly/javascript_compressed.js +0 -264
- package/admin/google-blockly/msg/messages.js +0 -1630
- package/admin/google-blockly/own/blocks_action.js +0 -765
- package/admin/google-blockly/own/blocks_convert.js +0 -480
- package/admin/google-blockly/own/blocks_logic.js +0 -459
- package/admin/google-blockly/own/blocks_number.js +0 -30
- package/admin/google-blockly/own/blocks_object.js +0 -402
- package/admin/google-blockly/own/blocks_procedures.js +0 -688
- package/admin/google-blockly/own/blocks_sendto.js +0 -702
- package/admin/google-blockly/own/blocks_switch.js +0 -257
- package/admin/google-blockly/own/blocks_system.js +0 -1409
- package/admin/google-blockly/own/blocks_text.js +0 -104
- package/admin/google-blockly/own/blocks_time.js +0 -639
- package/admin/google-blockly/own/blocks_timeout.js +0 -551
- package/admin/google-blockly/own/blocks_trigger.js +0 -1791
- package/admin/google-blockly/own/blocks_words.js +0 -708
- package/admin/google-blockly/own/field_cron.js +0 -158
- package/admin/google-blockly/own/field_oid.js +0 -642
- package/admin/google-blockly/own/field_script.js +0 -159
package/README.md
CHANGED
|
@@ -27,10 +27,49 @@ Executes Javascript, Typescript Scripts.
|
|
|
27
27
|
-->
|
|
28
28
|
|
|
29
29
|
## Changelog
|
|
30
|
+
### 10.1.0 (2026-08-16)
|
|
31
|
+
* (@GermanBluefox) Turned `strict` off again for the scripts, as TypeScript 6 enables it by default
|
|
32
|
+
* (@GermanBluefox) Added the tab "TypeScript" to the settings, where the compiler options for the scripts can be configured
|
|
33
|
+
* (@GermanBluefox) Added snapshot tests for the Blockly code generation (`npm run test:blockly`)
|
|
34
|
+
* (@GermanBluefox) Removed two leftover `.only` markers that had disabled almost the whole test suite
|
|
35
|
+
* (@GermanBluefox) Pinned the line endings of transformed TypeScript sources to LF, so a compiler update cannot rewrite every script
|
|
36
|
+
* (@GermanBluefox) Moved the micro benchmarks into `npm run test:performance`, as they measure relative speed against timeouts and cannot block a build
|
|
37
|
+
* (@GermanBluefox) Updated Blockly from 11.1.1 to 13.2.1. The generated code is unchanged
|
|
38
|
+
* (@GermanBluefox) `updateBlockly.js` now copies from the installed npm package instead of cloning the git master branch, so the shipped Blockly version is reproducible
|
|
39
|
+
* (@GermanBluefox) Blockly is now bundled from the npm package instead of being loaded as vendored script tags. Custom blocks of other adapters keep working unchanged
|
|
40
|
+
* (@GermanBluefox) Removed 828 kB of vendored Blockly code from the repository
|
|
41
|
+
* (@GermanBluefox) Converted all block definitions from JavaScript to TypeScript. The generated code is unchanged
|
|
42
|
+
* (@GermanBluefox) Fixed the object blocks under Blockly 13: the attribute rows were no longer right-aligned, and editing the attributes of an "object" block threw
|
|
43
|
+
* (@GermanBluefox) Dropped the dead field editor code of the CRON and script fields, which had been written against Blockly 1.x
|
|
44
|
+
* (@GermanBluefox) Fixed the multi-and/multi-or blocks under Blockly 13, which threw when their conditions were edited
|
|
45
|
+
* (@GermanBluefox) Removed a phantom block type "Convert" that a stray assignment in the conversion blocks had registered
|
|
46
|
+
* (@GermanBluefox) Added `BLOCKLY_TS.md` for adapter developers: what Blockly 13 changed for custom blocks and how to write them in TypeScript
|
|
47
|
+
* (@GermanBluefox) Moved the Blockly translations into `words.json` and typed the lookup helpers
|
|
48
|
+
* (@GermanBluefox) Redesign of Rules
|
|
49
|
+
* (@GermanBluefox) Added a wizard to the rule editor that builds a rule step by step - trigger, condition and action are configured in place, and the last step shows the finished rule
|
|
50
|
+
* (@GermanBluefox) The wizard opens by itself for a newly created rule - once, and not for a duplicated one. Afterwards it stays available in the block palette
|
|
51
|
+
* (@GermanBluefox) Fixed the type declarations of 3rd party libraries: they were placed under the name the library has on disk while their `package.json` went to the name the scripts import, so TypeScript never connected the two and everything imported from such a library was `any` (#2341)
|
|
52
|
+
* (@GermanBluefox) Stopped wrapping a library's declarations in `declare module`, which cut a barrel file off from what it re-exports. Declarations that are not a module themselves are still wrapped
|
|
53
|
+
* (@GermanBluefox) Fixed following the imports inside a declaration file: only the first import of a file was followed, and only if it was on the first line. For rxjs 6 that loaded 6 of its ~800 declaration files
|
|
54
|
+
* (@GermanBluefox) Side effect imports (`import "./x";`) inside a declaration file are now followed as well. `@iobroker/types` consists of nothing else, so the `ioBroker.*` types were missing in scripts and in the editor
|
|
55
|
+
* (@GermanBluefox) A definition file that cannot be read no longer discards all type declarations of its package
|
|
56
|
+
* (@GermanBluefox) Added regression tests for the type declarations of 3rd party libraries, which compile against them and insist that wrong code is rejected
|
|
57
|
+
* (@GermanBluefox) `createState` now stringifies `common.def` of an object, json or array state, as js-controller expects it and as `setState` already does with the value. Creating such a state with an initial value no longer warns "Default value has to be stringified" (#2307)
|
|
58
|
+
* (@GermanBluefox) Documented that an object in the second position of `createState` is always the `common`, and how to give a state a non-primitive initial value
|
|
59
|
+
* (@GermanBluefox) Restored the check of the mirror path in the instance configuration. It was lost when the admin configuration moved to `jsonConfig.json`, so a forbidden path was accepted without a word and only refused later in the log (#2296)
|
|
60
|
+
* (@GermanBluefox) The mirror path field now explains what the directory has to be, and suggests one
|
|
61
|
+
* (@GermanBluefox) Scripts are no longer deleted from the database when the mirror directory as a whole becomes unreachable, e.g. because a share is not mounted
|
|
62
|
+
* (@GermanBluefox) Libraries that name their declarations through an `exports` map are typed now. Their legacy `types` field is often a stub pointing at a file that does not exist - rxjs 7 is one - which left everything imported from them as `any` (#928)
|
|
63
|
+
* (@GermanBluefox) The declarations of a library are laid out around its entry point, so `moduleResolution: node10` finds it even when they live in a subdirectory
|
|
64
|
+
* (@GermanBluefox) The manifest handed to TypeScript describes that layout instead of the one on disk. An `exports` map pointing at paths that do not exist there made TypeScript refuse the library altogether
|
|
65
|
+
* (@GermanBluefox) The package.json of a library is read from disk instead of through Node, which refuses it when the library does not export it
|
|
66
|
+
* (@GermanBluefox) Fixed the mirror tests on macOS. They asserted on the first event a watcher reported, while `fs.watch` there works at directory granularity and sends an event for the watched directory before the one for the file. They now wait for the change they are about, and say what arrived instead if it never comes
|
|
67
|
+
* (@GermanBluefox) Made the mirror tests independent of how long a watch takes to arm. The change under test is repeated while waiting, so it cannot be made before the watcher is listening - the same commit produced a green and a red macOS job over that
|
|
68
|
+
|
|
30
69
|
### 10.0.0 (2026-08-04)
|
|
31
|
-
* (@GermanBluefox)
|
|
70
|
+
* (@GermanBluefox) TypeScript 6 support
|
|
32
71
|
* (@GermanBluefox) GUI was migrated to React 19 and MUI 9
|
|
33
|
-
* (@GermanBluefox) Showed host name in the instance selection dialog
|
|
72
|
+
* (@GermanBluefox) Showed the host name in the instance selection dialog
|
|
34
73
|
|
|
35
74
|
### 9.3.1 (2026-06-18)
|
|
36
75
|
* (@GermanBluefox) Added the possibility to execute one-way scripts without saving it
|
|
@@ -44,10 +83,6 @@ Executes Javascript, Typescript Scripts.
|
|
|
44
83
|
* (@GermanBluefox) Fixed a subscription leak on script stop for RegExp-notation string ids (dispatch index)
|
|
45
84
|
* (@GermanBluefox) `extendObject` no longer throws into the script when the object contains non-clonable values (e.g. functions)
|
|
46
85
|
|
|
47
|
-
### 9.2.3 (2026-05-27)
|
|
48
|
-
* (arteck) Performance optimizations done
|
|
49
|
-
* (@GermanBluefox) Added on mouse over the value of the state
|
|
50
|
-
|
|
51
86
|
## License
|
|
52
87
|
The MIT License (MIT)
|
|
53
88
|
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./aiPromptBuilder-Bs27qOHT.js","./rolldown-runtime-C0FnF6B9.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{t}from"./vite-preload-helper-B7qeedMF.js";import{Bt as n,Cr as r,En as i,Ht as a,It as o,Jn as s,Ln as c,On as l,Rt as u,Sn as d,Tn as f,Vt as p,Xt as m,Yt as h,_t as g,bn as _,dr as v,f as y,fn as ee,gr as b,kn as x,pn as S,pr as C,qn as w,st as T,ut as te,vn as E,vr as D,vt as O,yr as k,yt as A,zt as j}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-DuplUOZN.js";import{t as M}from"./Send-CChqR5Oy.js";import{n as N,r as P,t as F}from"./AiScriptAnalyzer--BHML2rN.js";import{t as I}from"./blocklyDarkTheme-DEiAX5DT.js";import{n as L,r as R}from"./aiPromptBuilder-Bs27qOHT.js";var z=c(w(`path`,{d:`M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m5 11h-4v4h-2v-4H7v-2h4V7h2v4h4z`}),`AddCircleOutlined`),B=c(w(`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`),ne=c(w(`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`),V=c(w(`path`,{d:`M9.01 14H2v2h7.01v3L13 15l-3.99-4zm5.98-1v-3H22V8h-7.01V5L11 9z`}),`CompareArrows`),H=c(w(`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`),U=c(w(`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`),W=c(w(`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`);r();var G=e(T(),1),K=t(()=>import(`./docs-compact-D7rpMc7r.js`),[],import.meta.url),q={openai:`img/openai.svg`,anthropic:`img/anthropic.svg`,gemini:`img/gemini.svg`,deepseek:`img/deepseek.svg`,custom:`img/custom.svg`},J={width:16,height:16,flexShrink:0,opacity:.7},re={ru:`Russian`,en:`English`,de:`German`,es:`Spanish`,fr:`French`,it:`Italian`,pl:`Polish`,nl:`Dutch`,pt:`Portuguese`,uk:`Ukrainian`,"zh-cn":`Chinese`},Y=null,X=null,Z=null,Q=null;function ie(){Y=null,X=null,Z=null,Q=null}async function ae(e,t){if(Y)return Y;let n=Object.keys(t)[0];if(!n)return null;let r=await e.sendTo(n,`getAvailableAiProviders`,{}),i=((r==null?void 0:r.providers)||[]).map(e=>e.provider),a=((r==null?void 0:r.providers)||[]).find(e=>e.provider===`custom`);return i.length?(Y={providers:i,gptBaseUrl:a==null?void 0:a.baseUrl},Y):null}var oe=`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`.split(`.`);function se(e){let t=e.toLowerCase();return!(oe.some(e=>t.includes(e))||t.startsWith(`claude-1`)||t.startsWith(`claude-instant`))}async function ce(e,t){let n=await ae(e,t);if(!n)return{models:[],providerMap:{},errors:[`No API keys configured`]};let r=Object.keys(t)[0];if(!r)return{models:[],providerMap:{},errors:[y.t(`No running javascript instance found`)]};let i=[],a={},o=[],s=(e,t)=>{for(let n of e)se(n)&&(a[n]||(i.push(n),a[n]=t))},c=[],l=(t,n)=>{c.push(e.sendTo(r,`testApiConnection`,{provider:t===`custom`?`openai`:t}).then(e=>{e.models?s(e.models,t):e.error&&o.push(`${n||t}: ${e.error}`)}).catch(e=>{o.push(`${n||t}: ${String(e)}`)}))},u={openai:`OpenAI`,anthropic:`Anthropic`,gemini:`Gemini`,deepseek:`DeepSeek`,custom:`Custom`};for(let e of n.providers)l(e,u[e]);return await Promise.all(c),i.sort(),{models:i,providerMap:a,errors:o}}async function le(e,t,n){var r;return await e.sendTo(t,`chatCompletion`,{timeout:n.timeout||6e5,model:n.model,provider:n.provider,messages:n.messages,...n.baseUrl?{baseUrl:n.baseUrl}:{},...(r=n.tools)!=null&&r.length?{tools:n.tools}:{}})}async function ue(e){if(Q)return Q;let t=await e.getObjectViewSystem(`state`,``,`香`),n=await e.getObjectViewSystem(`channel`,``,`香`),r=await e.getObjectViewSystem(`device`,``,`香`),i=await e.getObjectViewSystem(`folder`,``,`香`),a=await e.getObjectViewSystem(`enum`,``,`香`);return Q=Object.assign(t,n,r,i,a),Q}async function de(e){return ue(e)}function fe(e,t){return e&&typeof e==`object`?e[t]||e.en:e||``}async function pe(e){if(X)return X;let t=y.getLanguage(),n=await ue(e),r=Object.keys(n).sort(),i=new G.default,a=[],o=[`UNREACH_STICKY`],s=[G.Types.info],c=[],l=[],u=[],d=[];r.forEach(e=>{var t,r;((t=n[e])==null?void 0:t.type)===`enum`?c.push(e):(r=n[e])!=null&&(r=r.common)!=null&&r.smartName&&d.push(e)}),c.forEach(e=>{e.startsWith(`enum.rooms.`)?l.push(e):e.startsWith(`enum.functions.`)&&u.push(e);let t=n[e].common.members;t!=null&&t.length&&t.forEach(e=>{n[e]&&!d.includes(e)&&d.push(e)})});let f={id:``,objects:n,_keysOptional:r,_usedIdsOptional:a,ignoreIndicators:o,excludedTypes:s},p=[];d.forEach(e=>{f.id=e;let r=i.detect(f);r&&r.forEach(e=>{var r;let i=(r=e.states.find(e=>e.id))==null?void 0:r.id;if(!i||p.find(e=>e.id===i))return;let a=n[i],o={id:i,name:fe(a.common.name,t),type:a.type,deviceType:e.type,states:e.states.filter(e=>e.id).map(e=>({id:e.id,name:e.name,role:e.defaultRole,type:n[e.id].common.type,unit:n[e.id].common.unit,read:n[e.id].common.read??!0,write:n[e.id].common.write??!0}))},s=i.split(`.`),c,d;(a.type===`channel`||a.type===`state`)&&(s.pop(),c=s.join(`.`),n[c]&&(n[c].type===`channel`||n[c].type===`folder`)?(s.pop(),d=s.join(`.`),(!n[d]||n[d].type!==`device`&&n[c].type!==`folder`)&&(d=void 0)):c=void 0);let f=l.find(e=>{var t,r,a;return(t=n[e].common.members)!=null&&t.includes(i)||c&&(r=n[e].common.members)!=null&&r.includes(c)?!0:d&&((a=n[e].common.members)==null?void 0:a.includes(d))});f&&(o.room=fe(n[f].common.name,t));let m=u.find(e=>{var t,r,a;return(t=n[e].common.members)!=null&&t.includes(i)||c&&(r=n[e].common.members)!=null&&r.includes(c)?!0:d&&((a=n[e].common.members)==null?void 0:a.includes(d))});m&&(o.function=fe(n[m].common.name,t)),p.push(o)})});for(let e=0;e<p.length;e++){let r=p[e];if(r.type===`state`||r.type===`channel`){let e=r.id.split(`.`);e.pop();let i=n[e.join(`.`)];if(i&&(i.type===`channel`||i.type===`device`||i.type===`folder`)){var m,h;r.name=fe(((m=i.common)==null?void 0:m.name)||r.name,t),e.pop();let a=n[e.join(`.`)];if((a==null?void 0:a.type)===`device`&&(h=a.common)!=null&&h.icon){var g;r.name=fe(((g=a.common)==null?void 0:g.name)||r.name,t)}}else{var _;r.name=fe((i==null||(_=i.common)==null?void 0:_.name)||r.name,t)}}}return X=p,p}async function me(){return Z||(Z=(await K).default,Z)}function he(){return re[y.getLanguage()]||`English`}function ge(e){return`You write ioBroker JavaScript adapter scripts.
|
|
3
|
+
Copy EXACTLY this syntax. Do NOT change the callback signature.
|
|
4
|
+
IMPORTANT: Write all code at top level. NEVER use console.log (use log instead). NEVER define functions with the function keyword.
|
|
5
|
+
|
|
6
|
+
// CORRECT: on() always has ONE callback argument called obj
|
|
7
|
+
on('zigbee.0.sensor.state', (obj) => {
|
|
8
|
+
// obj.state.val = the new value (boolean or number)
|
|
9
|
+
// obj.id = the state ID that changed
|
|
10
|
+
setState('zigbee.0.lamp.state', obj.state.val);
|
|
11
|
+
log('Changed to ' + obj.state.val);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
// CORRECT: on() with filter
|
|
15
|
+
on({id: /zigbee\\.0\\..*\\.state$/, change: 'ne'}, (obj) => {
|
|
16
|
+
if (obj.state.val === true) {
|
|
17
|
+
setState('zigbee.0.other.state', true);
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
// Other correct examples:
|
|
22
|
+
setState('id', true);
|
|
23
|
+
setState('id', 50);
|
|
24
|
+
const val = getState('id').val;
|
|
25
|
+
schedule('0 7 * * *', () => { log('runs daily at 07:00'); });
|
|
26
|
+
schedule('0 22 * * *', () => { setState('id', false); });
|
|
27
|
+
|
|
28
|
+
// CORRECT Telegram: always use sendTo, NEVER setState on telegram
|
|
29
|
+
sendTo('telegram.0', 'send', {text: 'Alert: ' + someValue});
|
|
30
|
+
|
|
31
|
+
// CORRECT httpGet: res.data is a STRING, parse JSON with JSON.parse
|
|
32
|
+
httpGet('https://api.example.com/data', (err, res) => {
|
|
33
|
+
const data = JSON.parse(res.data);
|
|
34
|
+
log('Temperature: ' + data.main.temp);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
$('state[state.id=*.state](rooms=Room)').each((id) => { setState(id, false); });
|
|
38
|
+
createState('name', 0, {type: 'number', name: 'Name'});
|
|
39
|
+
// CORRECT: one-time delayed action (turn off after 5 minutes = 300000ms)
|
|
40
|
+
setStateDelayed('zigbee.0.lamp.state', false, false, 5 * 60 * 1000);
|
|
41
|
+
log(formatDate(new Date(), 'DD.MM.YYYY hh:mm'));
|
|
42
|
+
|
|
43
|
+
WRONG: on('id', (id, state) => {}) CORRECT: on('id', (obj) => {})
|
|
44
|
+
WRONG: set('id', true) CORRECT: setState('id', true)
|
|
45
|
+
WRONG: adapter.setState('id', true) CORRECT: setState('id', true)
|
|
46
|
+
WRONG: obj.val or newState.val CORRECT: obj.state.val
|
|
47
|
+
WRONG: on('change', {id: 'x'}, cb) CORRECT: on({id: 'x', change: 'ne'}, cb)
|
|
48
|
+
WRONG: setState('telegram.0', text) CORRECT: sendTo('telegram.0', 'send', {text: text})
|
|
49
|
+
WRONG: res.body.main.temp CORRECT: JSON.parse(res.data).main.temp
|
|
50
|
+
WRONG: function myFunc() {} CORRECT: write code directly, no function definitions
|
|
51
|
+
WRONG: setTimeout(fn, ms) CORRECT: setStateDelayed(id, val, false, ms) for one-time delay
|
|
52
|
+
WRONG: schedule('*/5 * * * *', fn) for one-time delay. schedule() is ONLY for recurring tasks
|
|
53
|
+
Values are boolean (true/false) or numbers, NEVER strings like 'ON'/'OFF'.
|
|
54
|
+
NEVER use: function keyword, require, import, setInterval, setTimeout, console.log, debug().
|
|
55
|
+
|
|
56
|
+
All available functions (use syntax from examples above):
|
|
57
|
+
on(pattern, (obj)=>{}) | once(pattern, (obj)=>{}) | unsubscribe(handler)
|
|
58
|
+
setState(id, val) | getState(id).val | setStateChanged(id, val) | setStateDelayed(id, val, ack, ms) | clearStateDelayed(id)
|
|
59
|
+
existsState(id) | existsObject(id) | getObject(id) | setObject(id, obj) | extendObject(id, obj) | deleteObject(id)
|
|
60
|
+
createState(name, initVal, {type,name,role}) | deleteState(name) | createAlias(name, alias)
|
|
61
|
+
schedule(cron, ()=>{}) | clearSchedule(obj) | scheduleById(id, (obj)=>{}) | getSchedules()
|
|
62
|
+
sendTo(adapter, cmd, msg) | sendToHost(host, cmd, msg)
|
|
63
|
+
$('selector').each((id)=>{}) | $('selector').setState(val) | $('selector').getState()
|
|
64
|
+
log(text) | formatDate(date, 'DD.MM.YYYY hh:mm') | formatTimeDiff(ms) | formatValue(val, decimals)
|
|
65
|
+
getDateObject(str) | getAstroDate(pattern) | isAstroDay() | compareTime(start, end, op)
|
|
66
|
+
exec(cmd, (err,stdout,stderr)=>{}) | httpGet(url, (err,res)=>{}) | httpPost(url, data, (err,res)=>{})
|
|
67
|
+
readFile(adapter, name, (err,data)=>{}) | writeFile(adapter, name, data, cb) | delFile(adapter, name, cb)
|
|
68
|
+
onFile(id, name, withFile, cb) | offFile(id, name) | onStop(cb, timeout)
|
|
69
|
+
getHistory(inst, {id,start,end,aggregate,count}, cb) | getEnums(name) | getIdByName(name)
|
|
70
|
+
wait(ms) | toInt(val) | toFloat(val) | toBoolean(val)
|
|
71
|
+
messageTo(target, data) | onMessage(name, cb) | onLog(severity, cb)
|
|
72
|
+
runScript(name) | startScript(name) | stopScript(name) | isScriptActive(name)
|
|
73
|
+
|
|
74
|
+
Write comments in ${e}. Put code in a \`\`\`javascript code block.`}function _e(e){return`You generate ioBroker Blockly XML blocks. Return Blockly XML in a \`\`\`xml code block.
|
|
75
|
+
Use EXACT state IDs from the plan. Write text/comments in ${e}.
|
|
76
|
+
|
|
77
|
+
IMPORTANT RULES:
|
|
78
|
+
- Return ONLY the inner blocks (no <xml> wrapper needed)
|
|
79
|
+
- Use the exact block types shown below
|
|
80
|
+
- State IDs must be full paths like "zigbee2mqtt.0.0x1234.state"
|
|
81
|
+
- Values are boolean (true/false) or numbers, NEVER strings like "ON"/"OFF"
|
|
82
|
+
- For Telegram use sendto_custom block, NEVER setState on telegram
|
|
83
|
+
|
|
84
|
+
## Block Templates
|
|
85
|
+
|
|
86
|
+
### Trigger: on_ext (react to state changes)
|
|
87
|
+
<block type="on_ext" x="0" y="0">
|
|
88
|
+
<mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
|
|
89
|
+
<field name="CONDITION">ne</field>
|
|
90
|
+
<field name="ACK_CONDITION"></field>
|
|
91
|
+
<value name="OID0">
|
|
92
|
+
<shadow type="field_oid"><field name="oid">STATE_ID_HERE</field></shadow>
|
|
93
|
+
</value>
|
|
94
|
+
<statement name="STATEMENT">
|
|
95
|
+
<!-- actions here -->
|
|
96
|
+
</statement>
|
|
97
|
+
</block>
|
|
98
|
+
|
|
99
|
+
### Schedule: schedule (cron-based)
|
|
100
|
+
<block type="schedule" x="0" y="0">
|
|
101
|
+
<field name="SCHEDULE">0 7 * * *</field>
|
|
102
|
+
<statement name="STATEMENT">
|
|
103
|
+
<!-- actions here -->
|
|
104
|
+
</statement>
|
|
105
|
+
</block>
|
|
106
|
+
|
|
107
|
+
### Set State: control
|
|
108
|
+
<block type="control">
|
|
109
|
+
<mutation xmlns="http://www.w3.org/1999/xhtml" delay_input="false"></mutation>
|
|
110
|
+
<field name="OID">STATE_ID_HERE</field>
|
|
111
|
+
<field name="WITH_DELAY">FALSE</field>
|
|
112
|
+
<value name="VALUE">
|
|
113
|
+
<block type="logic_boolean"><field name="BOOL">TRUE</field></block>
|
|
114
|
+
</value>
|
|
115
|
+
</block>
|
|
116
|
+
|
|
117
|
+
### Get State Value: get_value
|
|
118
|
+
<block type="get_value">
|
|
119
|
+
<field name="ATTR">val</field>
|
|
120
|
+
<field name="OID">STATE_ID_HERE</field>
|
|
121
|
+
</block>
|
|
122
|
+
|
|
123
|
+
### Log: debug
|
|
124
|
+
<block type="debug">
|
|
125
|
+
<field name="Severity">log</field>
|
|
126
|
+
<value name="TEXT">
|
|
127
|
+
<shadow type="text"><field name="TEXT">Message here</field></shadow>
|
|
128
|
+
</value>
|
|
129
|
+
</block>
|
|
130
|
+
|
|
131
|
+
### SendTo (Telegram): sendto_custom
|
|
132
|
+
<block type="sendto_custom">
|
|
133
|
+
<mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
|
|
134
|
+
<field name="INSTANCE">telegram.0</field>
|
|
135
|
+
<field name="COMMAND">send</field>
|
|
136
|
+
<field name="LOG"></field>
|
|
137
|
+
<value name="ARG0">
|
|
138
|
+
<block type="text"><field name="TEXT">Message text</field></block>
|
|
139
|
+
</value>
|
|
140
|
+
<value name="ATTR0">
|
|
141
|
+
<block type="text"><field name="TEXT">text</field></block>
|
|
142
|
+
</value>
|
|
143
|
+
</block>
|
|
144
|
+
|
|
145
|
+
### Timeout: timeouts_settimeout
|
|
146
|
+
<block type="timeouts_settimeout">
|
|
147
|
+
<field name="NAME">timeout1</field>
|
|
148
|
+
<field name="DELAY">5000</field>
|
|
149
|
+
<field name="UNIT">ms</field>
|
|
150
|
+
<statement name="STATEMENT">
|
|
151
|
+
<!-- delayed actions -->
|
|
152
|
+
</statement>
|
|
153
|
+
</block>
|
|
154
|
+
|
|
155
|
+
### If/Else: controls_if
|
|
156
|
+
<block type="controls_if">
|
|
157
|
+
<mutation else="1"></mutation>
|
|
158
|
+
<value name="IF0">
|
|
159
|
+
<block type="logic_compare">
|
|
160
|
+
<field name="OP">EQ</field>
|
|
161
|
+
<value name="A"><block type="get_value"><field name="ATTR">val</field><field name="OID">STATE_ID</field></block></value>
|
|
162
|
+
<value name="B"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
|
|
163
|
+
</block>
|
|
164
|
+
</value>
|
|
165
|
+
<statement name="DO0"><!-- then --></statement>
|
|
166
|
+
<statement name="ELSE"><!-- else --></statement>
|
|
167
|
+
</block>
|
|
168
|
+
|
|
169
|
+
### Number value
|
|
170
|
+
<block type="math_number"><field name="NUM">0</field></block>
|
|
171
|
+
|
|
172
|
+
### Text value
|
|
173
|
+
<block type="text"><field name="TEXT">hello</field></block>
|
|
174
|
+
|
|
175
|
+
### Boolean value
|
|
176
|
+
<block type="logic_boolean"><field name="BOOL">TRUE</field></block>
|
|
177
|
+
|
|
178
|
+
### Comparison: logic_compare
|
|
179
|
+
<block type="logic_compare">
|
|
180
|
+
<field name="OP">EQ</field>
|
|
181
|
+
<!-- OP can be: EQ, NEQ, LT, LTE, GT, GTE -->
|
|
182
|
+
<value name="A"><!-- left side --></value>
|
|
183
|
+
<value name="B"><!-- right side --></value>
|
|
184
|
+
</block>
|
|
185
|
+
|
|
186
|
+
## Common Patterns
|
|
187
|
+
|
|
188
|
+
### Turn on light when sensor triggers:
|
|
189
|
+
<block type="on_ext" x="0" y="0">
|
|
190
|
+
<mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
|
|
191
|
+
<field name="CONDITION">ne</field>
|
|
192
|
+
<field name="ACK_CONDITION"></field>
|
|
193
|
+
<value name="OID0">
|
|
194
|
+
<shadow type="field_oid"><field name="oid">zigbee2mqtt.0.0xSENSOR.occupancy</field></shadow>
|
|
195
|
+
</value>
|
|
196
|
+
<statement name="STATEMENT">
|
|
197
|
+
<block type="controls_if">
|
|
198
|
+
<value name="IF0">
|
|
199
|
+
<block type="logic_compare">
|
|
200
|
+
<field name="OP">EQ</field>
|
|
201
|
+
<value name="A"><block type="get_value"><field name="ATTR">val</field><field name="OID">zigbee2mqtt.0.0xSENSOR.occupancy</field></block></value>
|
|
202
|
+
<value name="B"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
|
|
203
|
+
</block>
|
|
204
|
+
</value>
|
|
205
|
+
<statement name="DO0">
|
|
206
|
+
<block type="control">
|
|
207
|
+
<mutation xmlns="http://www.w3.org/1999/xhtml" delay_input="false"></mutation>
|
|
208
|
+
<field name="OID">zigbee2mqtt.0.0xLAMP.state</field>
|
|
209
|
+
<field name="WITH_DELAY">FALSE</field>
|
|
210
|
+
<value name="VALUE"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
|
|
211
|
+
</block>
|
|
212
|
+
</statement>
|
|
213
|
+
</block>
|
|
214
|
+
</statement>
|
|
215
|
+
</block>
|
|
216
|
+
|
|
217
|
+
Write comments in ${e}. Put blocks in a \`\`\`xml code block.`}function ve(e){let t=e;return t=t.replace(/<think>[\s\S]*?<\/think>/gi,``),t=t.replace(/<\|endoftext\|>/g,``),t=t.replace(/<\|im_start\|>[\s\S]*?<\|im_end\|>/g,``),t=t.replace(/<\|im_start\|>[\s\S]*/g,``),t.trim()}var ye=[{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 be(e){return e&&typeof e==`object`?e.en||e.de||``:e||``}function xe(e,t,n){let r=(n||``).toLowerCase();if(!r)return!1;if(e.toLowerCase().includes(r))return!0;let i=t==null?void 0:t.common;if(!i)return!1;let a=be(i.name).toLowerCase();if(a&&a.includes(r))return!0;let o=(i.role||``).toLowerCase();return!!(o&&o.includes(r))}async function Se(e,t,n=20,r){let i=await de(e),a=r==null?void 0:r.toLowerCase(),o=[],s=Object.keys(i),c=new Set;for(let e of s){let t=e.lastIndexOf(`.`);t>0&&c.add(e.substring(0,t))}for(let e of s){let r=i[e],s=r==null?void 0:r.type;if(!s||a&&s!==a||!xe(e,r,t))continue;let l=r.common,u={id:e,type:s,name:be(l==null?void 0:l.name)};if(l!=null&&l.role&&(u.role=l.role),s===`state`?(u.stateType=(l==null?void 0:l.type)||``,l!=null&&l.unit&&(u.unit=l.unit)):c.has(e)&&(u.hasChildren=!0),o.push(u),o.length>=n)break}return o.length===0?JSON.stringify({message:`No objects found matching "${t}". Hint: try a role like "sensor.motion" or a partial path.`}):JSON.stringify(o)}async function Ce(e,t){try{let n=await e.getState(t);return JSON.stringify(n?{val:n.val,ts:n.ts?new Date(n.ts).toISOString():null,ack:n.ack,from:n.from}:{error:`State '${t}' not found`})}catch{return JSON.stringify({error:`Failed to read state '${t}'`})}}var we=new Set([`channel`,`device`,`folder`,`adapter`,`instance`,`enum`,`meta`]),Te=50;async function Ee(e,t){try{let r=await e.getObject(t);if(!r)return JSON.stringify({error:`Object '${t}' not found`});let i={id:r._id,type:r.type,common:r.common},a=t.split(`.`),o=[];for(let t=a.length-1;t>=2;t--){let r=a.slice(0,t).join(`.`);try{let t=await e.getObject(r);if(t&&t.type!==`state`){var n;o.push({id:t._id,type:t.type,name:be((n=t.common)==null?void 0:n.name),common:t.common})}}catch{}}if(o.length>0&&(i.parents=o),we.has(r.type)){let n=await de(e),r=[],a=`${t}.`,o=!1;for(let e of Object.keys(n))if(e.startsWith(a)&&!e.substring(a.length).includes(`.`)){let t=n[e],i=t==null?void 0:t.common,a={id:e,name:be(i==null?void 0:i.name),type:(t==null?void 0:t.type)||``};if(i!=null&&i.role&&(a.role=i.role),(t==null?void 0:t.type)===`state`&&i!=null&&i.unit&&(a.unit=i.unit),r.push(a),r.length>=Te){o=!0;break}}r.length>0&&(i.children=r,o&&(i.childrenTruncated=!0,i.childrenHint=`Only the first ${Te} 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 '${t}'`})}}function De(e){return N(e)||e}function Oe(e,t,n=10){let r=t.toLowerCase(),i=[];for(let t of e){let e=t.id.toLowerCase(),a=t.name.toLowerCase(),o=t.id.replace(/^script\.js\./,``).replace(/\./g,`/`),s=t.engineType===`Blockly`||t.engineType===`Rules`,c=e.includes(r)||a.includes(r),l=s?De(t.source):t.source,u=l.toLowerCase().includes(r);if(c||u){let e={id:t.id,path:o,name:t.name,type:s?`Blockly`:t.engineType.includes(`TypeScript`)?`TypeScript`:`JavaScript`,enabled:t.enabled};if(u){let t=l.split(`
|
|
218
|
+
`),n=[];for(let e=0;e<t.length&&!(t[e].toLowerCase().includes(r)&&(n.push({line:e+1,text:t[e].trim()}),n.length>=5));e++);n.length>0&&(e.matchingLines=n)}if(i.push(e),i.length>=n)break}}return i.length===0?JSON.stringify({message:`No scripts found matching "${t}"`}):JSON.stringify(i)}function ke(e,t){let n=t.replace(/\//g,`.`).toLowerCase(),r=e.find(e=>{let t=e.id.toLowerCase();return t===n||t===`script.js.${n}`||t.endsWith(`.${n}`)});if(!r)return JSON.stringify({error:`Script '${t}' not found. Use search_scripts to find available scripts.`});let i=r.engineType===`Blockly`||r.engineType===`Rules`,a=i?De(r.source):r.source,o=r.id.replace(/^script\.js\./,``).replace(/\./g,`/`);return JSON.stringify({id:r.id,path:o,name:r.name,type:i?`Blockly`:r.engineType.includes(`TypeScript`)?`TypeScript`:`JavaScript`,enabled:r.enabled,source:a})}function Ae(e){let t=e.map(e=>({id:e.id,path:e.id.replace(/^script\.js\./,``).replace(/\./g,`/`),name:e.name,type:e.engineType===`Blockly`||e.engineType===`Rules`?`Blockly`:e.engineType.includes(`TypeScript`)?`TypeScript`:`JavaScript`,enabled:e.enabled}));return JSON.stringify(t)}function $(){return JSON.stringify({error:`Editor is not available. This tool requires the script editor to be open.`})}async function je(e,t,n){if(!t)return JSON.stringify({error:`No running javascript instance found to execute the script.`});let r=n.source;if(!r||typeof r!=`string`)return JSON.stringify({error:`No source code provided.`});try{var i;let a=await e.sendTo(t,`execute`,{source:r,engineType:n.engineType,timeout:n.timeout,logLevel:n.logLevel});return!a||a.ok===!1?JSON.stringify({error:(a==null?void 0:a.error)||`Execution failed`,logs:(a==null?void 0:a.logs)||[]}):JSON.stringify({engineType:a.engineType,runtime:a.runtime,truncated:a.truncated||!1,logCount:((i=a.logs)==null?void 0:i.length)||0,logs:a.logs||[],output:a.output||``})}catch(e){return JSON.stringify({error:`Failed to execute script: ${e instanceof Error?e.message:String(e)}`})}}async function Me(e,t,n,r,i){let a;try{a=JSON.parse(t.function.arguments)}catch{return JSON.stringify({error:`Invalid arguments: ${t.function.arguments}`})}switch(t.function.name){case`search_datapoints`:return Se(e,a.query,a.max_results||20,a.object_type);case`get_state_value`:return Ce(e,a.id);case`get_object_info`:return Ee(e,a.id);case`search_scripts`:return Oe(n||[],a.query,a.max_results||10);case`read_script`:return ke(n||[],a.id);case`list_scripts`:return Ae(n||[]);case`run_script`:return je(e,i,a);case`get_editor_selection`:{if(!(r!=null&&r.getSelection))return $();let e=r.getSelection();return JSON.stringify(e||{message:`No text is currently selected in the editor.`})}case`get_editor_content`:return r!=null&&r.getContent?JSON.stringify({content:r.getContent()}):$();case`get_cursor_position`:{if(!(r!=null&&r.getCursorPosition))return $();let e=r.getCursorPosition();return JSON.stringify(e||{message:`Editor has no cursor position (not focused).`})}case`highlight_text_in_editor`:{if(!(r!=null&&r.highlightText))return $();let e=r.highlightText(a.text);return JSON.stringify({matches:e,message:e===0?`Text "${a.text}" was not found in the editor.`:`Highlighted ${e} occurrence(s) of "${a.text}".`})}case`highlight_line_range`:{if(!(r!=null&&r.highlightLineRange))return $();let e=r.highlightLineRange(a.start_line,a.end_line);return JSON.stringify({success:e,message:e?`Selected lines ${a.start_line}-${a.end_line}.`:`Could not select the requested line range.`})}case`go_to_line`:{if(!(r!=null&&r.goToLine))return $();let e=r.goToLine(a.line,a.column);return JSON.stringify({success:e,message:e?`Cursor moved to line ${a.line}.`:`Could not move the cursor.`})}case`insert_text_at_cursor`:{if(!(r!=null&&r.insertTextAtCursor))return $();let e=r.insertTextAtCursor(a.text);return JSON.stringify({success:e,message:e?`Text inserted at cursor.`:`Editor rejected the insertion.`})}case`replace_selection`:{if(!(r!=null&&r.replaceSelection))return $();let e=r.replaceSelection(a.text);return JSON.stringify({success:e,message:e?`Selection replaced.`:`No text was selected to replace.`})}case`get_diagnostics`:{if(!(r!=null&&r.getDiagnostics))return $();let e=r.getDiagnostics();return JSON.stringify({count:e.length,diagnostics:e})}case`get_document_symbols`:{if(!(r!=null&&r.getSymbols))return $();let e=await r.getSymbols();return JSON.stringify({count:e.length,symbols:e})}default:return JSON.stringify({error:`Unknown tool: ${t.function.name}`})}}var Ne=0;function Pe(){return`msg_${Date.now()}_${++Ne}`}function Fe(e){let{socket:n,runningInstances:r,currentCode:i,currentLanguage:a,allScripts:o,editorApi:s,currentScriptId:c}=e,l=v((e,t,n)=>e===`none`||!n?null:{range:t,scriptId:c||``,scriptVersion:(i||``).length,kind:e,originalText:n},[c,i]),[u,d]=k(()=>{try{let e=window.localStorage.getItem(`Editor.aiChatMessages`);return e?JSON.parse(e):[]}catch{return[]}}),f=v(e=>{d(t=>{let n=typeof e==`function`?e(t):e,r=n.length>100?n.slice(-100):n;try{window.localStorage.setItem(`Editor.aiChatMessages`,JSON.stringify(r))}catch{try{let e=r.slice(-20);window.localStorage.setItem(`Editor.aiChatMessages`,JSON.stringify(e))}catch{}}return r})},[]),[p,m]=k(!1),[h,g]=k(null),[_,ee]=k(window.localStorage.getItem(`Editor.aiChatMode`)||`agent`),b=v(e=>{ee(e),window.localStorage.setItem(`Editor.aiChatMode`,e)},[]),[x,S]=k(null),[w,T]=k(window.localStorage.getItem(`openai-model`)||``),[te,E]=k([]),[O,A]=k({}),[j,M]=k(!0),[N,I]=k(null),L=D(null),R=D(null),z=D(null),B=D(null),ne=v(e=>{T(e),window.localStorage.setItem(`openai-model`,e)},[]),V=v(async()=>{M(!0),I(null);try{let e=await ce(n,r);if(E(e.models),A(e.providerMap),e.models.length>0){let t=window.localStorage.getItem(`openai-model`);t&&e.models.includes(t)?T(t):T(e.models[0])}e.errors.length>0&&I(e.errors.join(`; `))}catch(e){I(String(e))}M(!1)},[n,r]);C(()=>{V()},[V]);let H=v(e=>{let t=!1,n=!1,r=[],i=!1,a=/@([\w/äöüÄÖÜß-]+)/g,s;for(;(s=a.exec(e))!==null;){let e=s[1].toLowerCase();if(e===`alle`||e===`all`)t=!0;else if(e===`geräte`||e===`devices`||e===`geraete`)n=!0;else if(i=!0,o&&o.length>0){let e=s[1].replace(/\//g,`.`).toLowerCase(),t=e.split(`.`),n=o.find(n=>{let r=n.id.toLowerCase(),i=r.replace(/^script\.js\./,``);if(i===e||i.endsWith(`.${e}`)||r===`script.js.${e}`)return!0;let a=0;for(let e of t){let t=i.indexOf(e,a);if(t===-1)return!1;a=t+e.length}return!0});if(n)r.push(n.id);else for(let e of t){if(e.length<3)continue;let t=o.filter(t=>t.id.toLowerCase().includes(`.${e}`)||t.name.toLowerCase().includes(e));for(let e of t)r.includes(e.id)||r.push(e.id)}}}return i&&r.length===0&&(t=!0),{cleanMessage:e.replace(/@[\w/äöüÄÖÜß]+\s*/g,``).trim(),mentionedScriptIds:r,includeAll:t,includeDevices:n}},[o]),U=v(async(e,t,s)=>{B.current||=await me(),L.current||=await ae(n,r);let c=he(),l=a===`blockly`,u=e||s.length>0,d=`You are an AI assistant for ioBroker JavaScript adapter scripting. Help the user write, debug, and understand ioBroker scripts. Write comments in ${c}. Use the ioBroker JavaScript API correctly.
|
|
219
|
+
|
|
220
|
+
ioBroker object hierarchy: adapter.instance.device.channel.state
|
|
221
|
+
- A "state" is a single datapoint (e.g. zigbee2mqtt.0.0x1234.temperature)
|
|
222
|
+
- A "channel" groups related states (e.g. zigbee2mqtt.0.0x1234 contains temperature, humidity, battery)
|
|
223
|
+
- A "device" groups channels (e.g. zigbee2mqtt.0.0x1234)
|
|
224
|
+
- The channel/device often has the human-readable name (e.g. "Living Room Sensor")
|
|
225
|
+
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.
|
|
226
|
+
|
|
227
|
+
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.
|
|
228
|
+
|
|
229
|
+
Available API and syntax rules:
|
|
230
|
+
${B.current}`;if(l&&(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."),(t||e)&&(z.current||=await pe(n),d+=`\n\nAvailable smart home devices:\n${JSON.stringify(z.current,null,0)}`),!u&&i)if(l){let e=i.indexOf(`%%BLOCKLY_XML%%`),t=e===-1?i:i.substring(0,e).trim(),n=e===-1?``:i.substring(e+15).trim();d+=`\n\nThe user is working on this Blockly script (currently open in the editor).\n\nGenerated JavaScript (shows the logic):\n\`\`\`javascript\n${t}\n\`\`\``,n&&(d+=`\n\nBlockly XML (use for modifications):\n\`\`\`xml\n${n}\n\`\`\``)}else d+=`\n\nThe user's question is about this script (currently open in the editor, ${a||`javascript`}):\n\`\`\`${a||`javascript`}\n${i}\n\`\`\``;if(e&&o&&o.length>0)d+=`\n\nThe 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.\n\n${F(o,!0)}`;else if(s.length>0&&o){let e=o.filter(e=>s.includes(e.id));e.length>0&&(d+=`\n\nIMPORTANT: 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:\n\n${F(e,!0)}`)}return l&&(d+=`\n\n${_e(c)}`),[{role:`system`,content:d}]},[n,r,i,a,o]),W=v(async e=>{if(!e.trim()||p)return;let t=O[w];if(!t){S(y.t(`Please select a valid model`));return}let i=L.current||await ae(n,r);if(L.current=i,!i){S(y.t(`No API keys configured`));return}let o=Object.keys(r)[0];if(!o){S(y.t(`No running javascript instance found`));return}let s=t===`custom`&&i.gptBaseUrl||``,c={id:Pe(),role:`user`,content:e,timestamp:Date.now()},l={id:Pe(),role:`assistant`,content:`⏳ ${y.t(`Generating plan...`)}`,timestamp:Date.now()};f(e=>[...e,c,l]),m(!0),S(null);try{let r=he();z.current||=await pe(n);let i=z.current||[],c=`Devices in my smart home:\n${JSON.stringify(i)}\n\nI need a plan for this task: ${e}\n\nAnswer with max 6 lines. Use FULL device IDs from the list above (e.g. zigbee2mqtt.0.0xa4c1383f5ef5fb07.state). No explanation. No reasoning.\n1. IDs: <full IDs from the device list. If a device is not in the list, use TODO_DEVICE_ID as placeholder>\n2. Trigger: <on(id) for state changes OR schedule('min hour * * *') for time-based tasks>\n3. Condition: <when to act>\n4. Actions: <what to set, with full IDs and values. For Telegram use sendTo('telegram.0', 'send', {text: msg})>\n5. Else: <alternative actions or nothing>\n6. Extra: <logging, formatting, etc.>\nValues are boolean (true/false) or numbers, not strings. Use .state not .state_toggle.`,l=await le(n,o,{messages:[{role:`user`,content:c}],model:w,provider:t,baseUrl:s});if(l.error){S(l.error),f(e=>e.slice(0,-2)),m(!1);return}let u=ve(l.content||``);f(e=>{let t=[...e],n=t[t.length-1];return(n==null?void 0:n.role)===`assistant`&&(t[t.length-1]={...n,content:`📋 **${y.t(`Plan`)}:**\n${u}`}),t});let d={id:Pe(),role:`assistant`,content:`⏳ ${y.t(`Generating code...`)}`,timestamp:Date.now()};f(e=>[...e,d]);let p=a===`blockly`,h=p?`TASK: ${e}\n\nPLAN:\n${u}\n\nGenerate 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 ${r}. Put the blocks in a \`\`\`xml code block. You may add a short explanation before or after the XML.`:`TASK: ${e}\n\nPLAN:\n${u}\n\nWrite 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 ${r}. Put the code in a \`\`\`javascript code block. You may add a short explanation before or after the code.`,_=p?_e(r):ge(r),v=await le(n,o,{messages:[{role:`system`,content:_},{role:`user`,content:h}],model:w,provider:t,baseUrl:s});if(v.error){S(v.error),f(e=>e.slice(0,-1)),m(!1);return}let ee=ve(v.content||``);f(e=>{let t=[...e],n=t[t.length-1];return(n==null?void 0:n.role)===`assistant`&&(t[t.length-1]={...n,content:ee}),t}),g(`${y.t(`devices`)}: ${i.length}`)}catch(e){S(String(e)),f(e=>e.slice(0,-1))}m(!1)},[w,O,p,n,r,a,f]),G=v(async e=>{if(_===`code`)return W(e);if(!e.trim()||p)return;let t=O[w];if(!t){S(y.t(`Please select a valid model`));return}let i=L.current||await ae(n,r);if(L.current=i,!i){S(y.t(`No API keys configured`));return}let a=Object.keys(r)[0];if(!a){S(y.t(`No running javascript instance found`));return}let c=R.current;if(R.current=null,!c)try{var d;let e=s==null||(d=s.getSelection)==null?void 0:d.call(s);e&&e.text&&(c=l(`selection`,e.range,e.text))}catch{}let h={id:Pe(),role:`user`,content:e,timestamp:Date.now(),sourceRange:c},v={id:Pe(),role:`assistant`,content:``,timestamp:Date.now(),sourceRange:c};f(e=>[...e,h,v]),m(!0),S(null);let{cleanMessage:ee,mentionedScriptIds:b,includeAll:x,includeDevices:C}=H(e),T=[];if(x)T.push(`${y.t(`all scripts`)} (${(o==null?void 0:o.length)||0})`);else if(b.length>0){let e=b.map(e=>e.replace(/^script\.js\./,``));T.push(e.join(`, `))}else T.push(y.t(`current script`));C&&T.push(y.t(`devices`)),g(`${y.t(`Context`)}: ${T.join(` + `)}`);let te=await U(x,C,b),E=t===`custom`&&i.gptBaseUrl||``,D=ee||e;if(o&&o.length>0){let e=D.match(/\b[\w-]+\.\d+\.[\w.-]+/g);if(e){let t=[];for(let n of new Set(e)){let e=P(o,n);e.length>0&&t.push(`Datapoint "${n}" is used in:\n${e.map(e=>` - ${e.scriptName} (${e.scriptId}) line ${e.lineNumber}: ${e.usageType} → ${e.line}`).join(`
|
|
231
|
+
`)}`)}t.length>0&&(D+=`\n\n[Automatic analysis results]\n${t.join(`
|
|
232
|
+
|
|
233
|
+
`)}`)}}let k=[...te,...u.filter(e=>e.role!==`system`).map(e=>({role:e.role,content:e.content})),{role:`user`,content:D}],A=_===`agent`;try{let e=[...k];for(let r=0;r<5;r++){let i=await le(n,a,{messages:e,model:w,provider:t,baseUrl:E,...A?{tools:ye}:{}});if(i.error){if(A&&r===0&&i.error.toLowerCase().includes(`tool`)){let r=await le(n,a,{messages:e,model:w,provider:t,baseUrl:E});if(r.error)S(r.error),f(e=>e.slice(0,-1));else{let e=ve(r.content||``);f(t=>{let n=[...t],r=n[n.length-1];return(r==null?void 0:r.role)===`assistant`&&(n[n.length-1]={...r,content:e}),n})}break}S(i.error),f(e=>e.slice(0,-1));break}let c=i.tool_calls;if((!c||c.length===0)&&A&&i.content){let e=i.content.trim();try{let t=JSON.parse(e);t.name&&t.arguments&&(c=[{id:`text_tool_${Date.now()}`,type:`function`,function:{name:t.name,arguments:JSON.stringify(t.arguments)}}])}catch{}}if(!c||c.length===0){let e=ve(i.content||``);f(t=>{let n=[...t],r=n[n.length-1];return(r==null?void 0:r.role)===`assistant`&&(n[n.length-1]={...r,content:e}),n});break}i.tool_calls=c;let l=i.tool_calls.map(e=>{let t={};try{t=JSON.parse(e.function.arguments)}catch{}switch(e.function.name){case`search_datapoints`:return`🔍 ${y.t(`Searching datapoints`)}: "${String(t.query||``)}"`;case`get_state_value`:return`📊 ${y.t(`Reading value`)}: ${String(t.id||``)}`;case`get_object_info`:return`📋 ${y.t(`Loading object info`)}: ${String(t.id||``)}`;case`search_scripts`:return`🔍 ${y.t(`Searching scripts`)}: "${String(t.query||``)}"`;case`read_script`:return`📖 ${y.t(`Reading script`)}: ${String(t.id||``)}`;case`list_scripts`:return`📂 ${y.t(`Loading script list`)}`;default:return`⚙️ ${e.function.name}`}});f(e=>{let t=[...e],n=t[t.length-1];return(n==null?void 0:n.role)===`assistant`&&(t[t.length-1]={...n,content:l.join(`
|
|
234
|
+
`)}),t}),e.push({role:`assistant`,content:i.content||``,tool_calls:i.tool_calls});for(let t of i.tool_calls){let r=await Me(n,t,o,s,a);e.push({role:`tool`,tool_call_id:t.id,content:r})}}}catch(e){S(String(e)),f(e=>e.slice(0,-1))}m(!1)},[w,O,u,p,n,r,U,H,o,_,W,f,l,s]),K=v(()=>{f([]),S(null),m(!1),g(null),ie(),window.localStorage.removeItem(`Editor.aiChatHistory`)},[f]),q=v(async(e,t)=>{let i=O[w];if(!i)return`Error: ${y.t(`Please select a valid model`)}`;let o=L.current||await ae(n,r);if(L.current=o,!o)return`Error: ${y.t(`No API keys configured`)}`;let s=Object.keys(r)[0];if(!s)return`Error: ${y.t(`No running javascript instance found`)}`;let c=i===`custom`&&o.gptBaseUrl||``,l=a||`javascript`,u=`You are an assistant for writing ioBroker ${l} scripts. The user will ask a question about a snippet of their code. Match your answer to the question: \n- 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. \n- If they explicitly ask for a change, refactor, fix, or rewrite, reply with a single fenced \`\`\`${l===`blockly`?`xml`:l}\`\`\` code block containing the full replacement for the selection. You may add one short sentence before or after the block. \n- If they ask something ambiguous or meta (e.g. "is this correct?"), reply in prose first and only include code if proposing a change. \nioBroker globals available in scripts: on, setState, getState, schedule, sendTo, log, createState, setStateDelayed, existsState, httpGet, httpPost.`,d=t?`Code from my editor:\n\n\`\`\`${l===`blockly`?`xml`:l}\n${t}\n\`\`\`\n\n${e}`:e;try{let e=await le(n,s,{messages:[{role:`system`,content:u},{role:`user`,content:d}],model:w,provider:i,baseUrl:c});return e.error?`Error: ${e.error}`:e.content||``}catch(e){return`Error: ${e.message||String(e)}`}},[w,O,r,n,a]);return{messages:u,isLoading:p,error:x,model:w,availableModels:te,modelProviderMap:O,modelsLoading:j,modelsError:N,lastContextInfo:h,mode:_,setMode:b,setModel:ne,sendMessage:G,triggerAiAction:v(e=>{e.range&&e.code?R.current=l(e.kind||`codelens`,e.range,e.code):R.current=null,t(async()=>{let{buildActionPrompt:e}=await import(`./aiPromptBuilder-Bs27qOHT.js`).then(e=>e.t);return{buildActionPrompt:e}},__vite__mapDeps([0,1]),import.meta.url).then(({buildActionPrompt:t})=>{let n=t({action:e.action,code:e.code,language:a||`javascript`,diagnostic:e.diagnostic,question:e.question,rangeLabel:e.rangeLabel});n?G(n):R.current=null}).catch(()=>{R.current=null,S(y.t(`Failed to build AI action prompt`))})},[G,a,l]),askInline:q,clearChat:K,retryLoadModels:V}}r();var Ie=({code:e,language:t,themeType:r,onInsertCode:i,onShowDiff:a,sourceRange:o})=>{let c=D(null);C(()=>{var n;let i=window.monaco;if(!c.current||!(i!=null&&(n=i.editor)!=null&&n.colorize))return;let a=t===`ts`||t===`typescript`?`typescript`:t||`javascript`;i.editor.colorize(e,a,{theme:r===`dark`?`vs-dark`:`vs`}).then(e=>{c.current&&(c.current.innerHTML=e)})},[e,t,r]);let l=v(()=>{navigator.clipboard.writeText(e)},[e]);return s(n,{sx:{position:`relative`,my:1,borderRadius:1,overflow:`hidden`,border:`1px solid`,borderColor:`divider`},children:[s(n,{sx:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,px:1,py:.5,bgcolor:`action.hover`,borderBottom:`1px solid`,borderColor:`divider`},children:[w(n,{sx:{fontSize:`0.75rem`,color:`text.secondary`,textTransform:`uppercase`},children:t||`javascript`}),s(n,{children:[w(u,{title:y.t(`Copy`),children:w(S,{size:`small`,onClick:l,children:w(g,{sx:{fontSize:16}})})}),i&&w(u,{title:y.t(`Insert into editor`),children:w(S,{size:`small`,onClick:()=>i(e),children:w(z,{sx:{fontSize:16}})})}),a&&w(u,{title:y.t(`Show as diff`),children:w(S,{size:`small`,onClick:()=>a(e,o),children:w(V,{sx:{fontSize:16}})})})]})]}),w(`pre`,{ref:c,style:{margin:0,padding:`8px 12px`,overflow:`auto`,maxHeight:400,fontSize:`13px`,fontFamily:`'Cascadia Code', 'Fira Code', 'Consolas', monospace`,backgroundColor:r===`dark`?`#1e1e1e`:`#f8f8f8`,color:r===`dark`?`#d4d4d4`:`#333`},children:e})]})};r();var Le=({xml:e,themeType:t})=>{let r=D(null),i=D(null),[a,o]=k(60),s=D(!1);return C(()=>{s.current&&(s.current=!1,requestAnimationFrame(()=>{let e=window.Blockly,t=i.current;e&&t&&(e.svgResize(t),t.scrollCenter())}))},[a]),C(()=>{let n=window.Blockly;if(!(!n||!r.current)){i.current&&=(i.current.dispose(),null);try{let a=n.inject(r.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:t===`dark`?I():`classic`,media:`google-blockly/media/`});i.current=a;let c=e.trim();c.startsWith(`<xml`)||(c=`<xml xmlns="https://developers.google.com/blockly/xml">${c}</xml>`);let l=n.utils.xml.textToDom(c),u=10,d=Array.from(l.querySelectorAll(`:scope > block`));for(let e of d)e.setAttribute(`x`,`10`),e.setAttribute(`y`,String(u)),u+=200;n.Xml.domToWorkspace(l,a);let f=a.getTopBlocks(!1);if(f.length>1){let e=10;for(let t of f){let n=t.getRelativeToSurfaceXY();t.moveBy(10-n.x,e-n.y),e+=t.getHeightWidth().height+20}}let p=a.getBlocksBoundingBox();if(p){let e=p.bottom-p.top+20,t=Math.max(60,Math.ceil(e));s.current=!0,o(t)}}catch{}return()=>{i.current&&=(i.current.dispose(),null)}}},[e,t]),w(n,{ref:r,sx:{width:`100%`,height:a,minHeight:60,borderRadius:1,overflow:`hidden`,border:`1px solid`,borderColor:`divider`}})};r();function Re(e){let t=[],n=/```(\w*)\n?([\s\S]*?)```/g,r=0,i;for(;(i=n.exec(e))!==null;){if(i.index>r){let n=e.substring(r,i.index).trim();n&&t.push({type:`text`,content:n})}t.push({type:`code`,content:i[2].trim(),language:i[1]||`javascript`}),r=i.index+i[0].length}if(r<e.length){let n=e.substring(r).trim();n&&t.push({type:`text`,content:n})}return t.length===0&&t.push({type:`text`,content:e}),t}function ze(e){let t=[],n=/(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`)/g,r=0,i,a=0;for(;(i=n.exec(e))!==null;)i.index>r&&t.push(e.substring(r,i.index)),i[2]?t.push(w(`strong`,{children:i[2]},a++)):i[3]?t.push(w(`em`,{children:i[3]},a++)):i[4]&&t.push(w(`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]},a++)),r=i.index+i[0].length;return r<e.length&&t.push(e.substring(r)),t}function Be(e){return e.trim().startsWith(`|`)&&e.trim().endsWith(`|`)}function Ve(e){return/^\|[\s:]*-+[\s:|-]*\|$/.test(e.trim())}function He(e,t,r){let i=t.palette.mode===`dark`,a=e=>e.trim().replace(/^\||\|$/g,``).split(`|`).map(e=>e.trim()),o=a(e[0]),c=e.slice(2).map(a);return w(n,{sx:{overflowX:`auto`,my:1},children:s(`table`,{style:{borderCollapse:`collapse`,width:`100%`,fontSize:`0.8rem`,color:t.palette.text.primary},children:[w(`thead`,{children:w(`tr`,{children:o.map((e,n)=>w(`th`,{style:{border:`1px solid ${t.palette.divider}`,padding:`6px 10px`,backgroundColor:i?t.palette.grey[800]:t.palette.grey[100],color:t.palette.text.primary,fontWeight:600,textAlign:`left`},children:ze(e)},n))})}),w(`tbody`,{children:c.map((e,n)=>w(`tr`,{style:{backgroundColor:n%2==1?i?t.palette.grey[900]:t.palette.grey[50]:void 0},children:e.map((e,n)=>w(`td`,{style:{border:`1px solid ${t.palette.divider}`,padding:`6px 10px`,color:t.palette.text.primary},children:ze(e)},n))},n))})]})},r)}function Ue(e,t){let n=e.split(`
|
|
235
|
+
`),r=[],i=0,a=0;for(;a<n.length;){let e=n[a].trim();if(e===``){a++;continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(e)){r.push(w(`hr`,{style:{border:`none`,borderTop:`1px solid ${t.palette.divider}`,margin:`8px 0`}},i++)),a++;continue}let o=e.match(/^(#{1,4})\s+(.+)$/);if(o){let e=o[1].length;r.push(w(`div`,{style:{fontWeight:600,fontSize:[`1.2em`,`1.1em`,`1em`,`0.95em`][e-1],margin:`8px 0 4px`},children:ze(o[2])},i++)),a++;continue}if(Be(e)&&a+1<n.length&&Ve(n[a+1].trim())&&a+2<n.length){let e=[n[a],n[a+1]],o=a+2;for(;o<n.length&&Be(n[o]);)e.push(n[o]),o++;r.push(He(e,t,i++)),a=o;continue}if(/^[-*+]\s/.test(e)){let e=[];for(;a<n.length&&/^\s*[-*+]\s/.test(n[a]);)e.push(n[a].replace(/^\s*[-*+]\s/,``).trim()),a++;r.push(w(`ul`,{style:{margin:`4px 0`,paddingLeft:20},children:e.map((e,t)=>w(`li`,{children:ze(e)},t))},i++));continue}if(/^\d+[.)]\s/.test(e)){let e=[];for(;a<n.length&&/^\s*\d+[.)]\s/.test(n[a]);)e.push(n[a].replace(/^\s*\d+[.)]\s/,``).trim()),a++;r.push(w(`ol`,{style:{margin:`4px 0`,paddingLeft:20},children:e.map((e,t)=>w(`li`,{children:ze(e)},t))},i++));continue}r.push(w(`div`,{children:ze(e)},i++)),a++}return r}var We=({message:e,themeType:t,currentLanguage:r,onInsertCode:i,onShowDiff:o,onApplyCode:c})=>{let l=e.role===`user`,u=p(),d=l?t===`dark`?u.palette.primary.dark:u.palette.primary.main:t===`dark`?u.palette.secondary.dark:u.palette.secondary.main,f=u.palette.getContrastText(d),m=b(()=>Re(e.content),[e.content]),h=(e,t)=>!!(e===`xml`||e===`blockly`||r===`blockly`&&t&&/<block\s+type=/.test(t));return s(n,{sx:{display:`flex`,gap:1,px:1.5,py:1,mx:.75,my:.5,bgcolor:l?t===`dark`?`rgba(144, 202, 249, 0.10)`:`rgba(25, 118, 210, 0.07)`:t===`dark`?`rgba(206, 147, 216, 0.10)`:`rgba(156, 39, 176, 0.06)`,borderRadius:1.5,borderLeft:`3px solid`,borderLeftColor:d,transition:`background-color 120ms`,"&:hover":{bgcolor:l?t===`dark`?`rgba(144, 202, 249, 0.16)`:`rgba(25, 118, 210, 0.12)`:t===`dark`?`rgba(206, 147, 216, 0.16)`:`rgba(156, 39, 176, 0.10)`}},children:[w(x,{sx:{width:28,height:28,bgcolor:d,color:f,flexShrink:0,mt:.5},children:w(l?H:W,{sx:{fontSize:18}})}),w(n,{sx:{flex:1,minWidth:0,fontSize:`0.875rem`,lineHeight:1.6},children:m.map((r,l)=>r.type===`code`?h(r.language,r.content)?s(n,{sx:{my:1},children:[w(Le,{xml:r.content,themeType:t}),s(n,{sx:{display:`flex`,gap:.5,mt:.5},children:[c&&w(a,{size:`small`,variant:`contained`,color:`primary`,startIcon:w(U,{sx:{fontSize:14}}),onClick:()=>c(r.content),sx:{textTransform:`none`,fontSize:`0.75rem`},children:y.t(`Apply blocks`)}),i&&w(a,{size:`small`,variant:`outlined`,startIcon:w(z,{sx:{fontSize:14}}),onClick:()=>i(r.content),sx:{textTransform:`none`,fontSize:`0.75rem`},children:y.t(`Insert blocks`)})]})]},l):w(Ie,{code:r.content,language:r.language||`javascript`,themeType:t,onInsertCode:i,onShowDiff:o,sourceRange:e.sourceRange||null},l):w(n,{sx:{wordBreak:`break-word`,color:u.palette.text.primary},children:Ue(r.content,u)},l))})]})};r();function Ge(){return[{id:`@all`,label:y.t(`mention @all`),descriptionKey:`All scripts`},{id:`@devices`,label:y.t(`mention @devices`),descriptionKey:`Smart home devices`}]}function Ke({provider:e,isDark:t}){return q[e]?w(`img`,{src:`./img/${e}.svg`,alt:e,style:{...J,...t?{filter:`invert(0.85)`}:{}},onError:e=>{e.target.style.display=`none`}}):null}function qe(){try{let e=window.localStorage.getItem(`Editor.aiChatHistory`);return e?JSON.parse(e):[]}catch{return[]}}var Je=({onSend:e,disabled:t,themeType:r,hasSelection:a,selectionText:c,allScripts:p,model:m,availableModels:g,modelProviderMap:ee,modelsLoading:x,onModelChange:T,mode:te,onModeChange:A,currentLanguage:N})=>{let[P,F]=k(``),[I,z]=k(!1),[B,V]=k(``),[H,U]=k(0),W=D(null),G=D(-1),K=D(qe()),q=D(-1),J=D(``),re=b(()=>{let e=Ge().map(e=>({...e,description:y.t(e.descriptionKey)}));if(p)for(let t of p){let n=t.id.replace(/^script\.js\./,``).replace(/\./g,`/`);e.push({id:`@${n}`,label:`@${n}`,description:`${t.name} [${t.enabled?`active`:`inactive`}]`})}return e},[p]),Y=b(()=>{if(!B)return re;let e=B.toLowerCase();return re.filter(t=>t.id.toLowerCase().includes(e)||t.description.toLowerCase().includes(e))},[re,B]);C(()=>{U(0)},[B]);let X=v(()=>{let n=P.trim();if(!n||t)return;let r=n,i=R(n);if(i){let e=a&&c?c:``,t=L({action:i.action,code:e,language:N||`javascript`,question:i.action===`ask`?i.rest:void 0,diagnostic:i.action===`fix`&&i.rest||void 0});t&&(r=t)}else a&&c&&(r=`[Selected code in editor]\n\`\`\`\n${c}\n\`\`\`\n\n${n}`);K.current.push(n),q.current=-1,J.current=``;try{let e=K.current.slice(-50);window.localStorage.setItem(`Editor.aiChatHistory`,JSON.stringify(e))}catch{}e(r),F(``),z(!1),requestAnimationFrame(()=>{var e;return(e=W.current)==null?void 0:e.focus()})},[P,t,e,a,c,N]),Z=v(e=>{let t=G.current,n=W.current;if(t<0){let t=P?`${P}${e} `:`${e} `;F(t),z(!1),V(``),setTimeout(()=>{n&&(n.focus(),n.setSelectionRange(t.length,t.length))},0);return}let r=P.substring(0,t),i=(n==null?void 0:n.selectionStart)??P.length,a=`${r}${e} ${P.substring(i)}`;F(a),z(!1),V(``),G.current=-1,setTimeout(()=>{if(n){let t=r.length+e.length+1;n.focus(),n.setSelectionRange(t,t)}},0)},[P]),Q=v(()=>{G.current=-1,V(``),z(e=>!e)},[]),ie=v(e=>{let t=e.target.value;F(t);let n=e.target.selectionStart??t.length,r=t.substring(0,n).match(/@([\w/äöüÄÖÜß]*)$/);r?(G.current=n-r[0].length,V(r[1]),z(!0)):(z(!1),V(``))},[]),ae=v(e=>{if(I&&Y.length>0){if(e.key===`ArrowDown`){e.preventDefault(),U(e=>(e+1)%Y.length);return}if(e.key===`ArrowUp`){e.preventDefault(),U(e=>(e-1+Y.length)%Y.length);return}if(e.key===`Enter`||e.key===`Tab`){e.preventDefault(),Z(Y[H].id);return}if(e.key===`Escape`){e.preventDefault(),z(!1);return}}if(e.key===`ArrowUp`&&!I&&K.current.length>0){let t=W.current,n=!t||t.selectionStart===0,r=!P.includes(`
|
|
236
|
+
`);if(n&&r){e.preventDefault(),q.current===-1?(J.current=P,q.current=K.current.length-1):q.current>0&&q.current--,F(K.current[q.current]);return}}if(e.key===`ArrowDown`&&!I&&q.current>=0){let t=W.current,n=!t||t.selectionStart===P.length,r=!P.includes(`
|
|
237
|
+
`);if(n&&r){e.preventDefault(),q.current<K.current.length-1?(q.current++,F(K.current[q.current])):(q.current=-1,F(J.current));return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),X())},[X,I,Y,H,Z,P]);return s(n,{sx:{borderTop:`1px solid`,borderColor:`divider`,position:`relative`},children:[I&&Y.length>0&&w(i,{elevation:4,sx:{position:`absolute`,bottom:`100%`,left:8,right:8,maxHeight:200,overflow:`auto`,zIndex:10,mb:.5},children:w(E,{dense:!0,disablePadding:!0,children:Y.slice(0,15).map((e,t)=>w(_,{selected:t===H,onClick:()=>Z(e.id),sx:{py:.25,minHeight:32},children:w(d,{primary:e.label,secondary:e.description,slotProps:{primary:{sx:{fontSize:`0.8rem`,fontWeight:500}},secondary:{sx:{fontSize:`0.7rem`}}}})},e.id))})}),te===`code`&&w(h,{label:`${y.t(`mention @devices`)} — ${y.t(`Smart home devices`)}`,size:`small`,variant:`outlined`,sx:{mx:1,mt:.5,maxWidth:`calc(100% - 16px)`}}),a&&c&&w(h,{icon:w(O,{sx:{fontSize:14}}),label:y.t(`Selected code as context`),size:`small`,variant:`outlined`,sx:{mx:1,mt:.5,maxWidth:`calc(100% - 16px)`}}),s(n,{sx:{mx:1,mt:.5,mb:.5,border:`1px solid`,borderColor:`divider`,borderRadius:1.5,overflow:`hidden`,"&:focus-within":{borderColor:`primary.main`}},children:[w(o,{inputRef:W,fullWidth:!0,multiline:!0,maxRows:6,placeholder:y.t(`Ask about your script...`),value:P,onChange:ie,onKeyDown:ae,disabled:t,onBlur:()=>{setTimeout(()=>z(!1),200)},variant:`standard`,slotProps:{input:{disableUnderline:!0}},sx:{px:1.5,pt:1,pb:.5,"& .MuiInputBase-root":{fontSize:`0.875rem`}}}),s(n,{sx:{display:`flex`,alignItems:`center`,gap:.75,px:1,pb:.5},children:[w(u,{title:s(n,{sx:{fontSize:`0.8rem`,lineHeight:1.5,maxWidth:360},children:[w(n,{sx:{fontWeight:600,mb:.75},children:y.t(`AI chat mode`)}),s(n,{sx:{mb:.75},children:[s(`strong`,{children:[`💬 `,y.t(`Chat`)]}),` —`,` `,y.t(`Plain conversation. Use for questions, explanations, syntax help. Does not read or modify your scripts.`)]}),s(n,{sx:{mb:.75},children:[s(`strong`,{children:[`🤖 `,y.t(`Agent`)]}),` —`,` `,y.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".`)]}),s(n,{children:[s(`strong`,{children:[`💻 `,y.t(`Code`)]}),` —`,` `,y.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:s(l,{value:te,onChange:e=>A(e.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:[w(f,{value:`chat`,sx:{fontSize:`0.75rem`},title:y.t(`Plain conversation. Best for: general questions, syntax help, concept explanations.`),children:`💬 Chat`}),w(f,{value:`agent`,sx:{fontSize:`0.75rem`},title:y.t(`For larger models with tool support. Best for: creating, editing, or analyzing scripts; finding datapoint usages; inspecting the object tree.`),children:`🤖 Agent`}),w(f,{value:`code`,sx:{fontSize:`0.75rem`},title:y.t(`For smaller models without tool support. Best for: creating new JavaScript/TypeScript or Blockly scripts from a description.`),children:`💻 Code`})]})}),w(l,{value:m,onChange:e=>T(e.target.value),size:`small`,disabled:x||g.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:g.map(e=>s(f,{value:e,sx:{fontSize:`0.75rem`,display:`flex`,gap:.5},children:[w(Ke,{provider:ee[e],isDark:r===`dark`}),e]},e))}),w(u,{title:y.t(`Mention scripts as context for the AI. Use @all for all scripts or @scriptName for a specific one.`),enterDelay:500,children:w(S,{size:`small`,onClick:Q,sx:{p:`3px`,color:I?`primary.main`:`text.secondary`,border:`1px solid`,borderColor:I?`primary.main`:`text.secondary`,bgcolor:I?void 0:`action.hover`,borderRadius:3,"&:hover":{borderColor:`text.disabled`,bgcolor:`action.hover`}},children:w(ne,{sx:{fontSize:16}})})}),w(n,{sx:{flex:1}}),s(j,{variant:`caption`,sx:{color:`text.disabled`,fontSize:`0.65rem`,mr:.5,whiteSpace:`nowrap`},children:[`Enter `,y.t(`to send`)]}),w(u,{title:`${y.t(`Send`)} (Enter)`,children:w(`span`,{children:w(S,{color:`primary`,onClick:X,disabled:t||!P.trim(),size:`small`,sx:{p:.25},children:w(M,{sx:{fontSize:18}})})})})]})]})]})};r();var Ye=({socket:e,runningInstances:t,themeType:r,currentCode:i,currentLanguage:a,selectedCode:o,allScripts:c,editorApi:l,aiActionRequest:d,onAiActionConsumed:f,onRegisterInlineAsk:p,onInsertCode:h,onShowDiff:g,onApplyCode:_,currentScriptId:x,onClose:T})=>{var E;let O=D(null),{messages:k,isLoading:M,error:N,model:P,availableModels:F,modelProviderMap:I,modelsLoading:L,modelsError:R,lastContextInfo:z,mode:ne,setMode:V,setModel:H,sendMessage:U,triggerAiAction:W,askInline:G,clearChat:K,retryLoadModels:q}=Fe(b(()=>({socket:e,runningInstances:t,currentCode:i,currentLanguage:a,allScripts:c,editorApi:l,currentScriptId:x}),[e,t,i,a,c,l,x]));C(()=>(p==null||p(G),()=>p==null?void 0:p(null)),[G,p]);let J=D(null);C(()=>{!d||J.current===d||(J.current=d,W(d),f==null||f())},[d,W,f]),C(()=>{var e;(e=O.current)==null||e.scrollIntoView({behavior:`smooth`})},[k]);let re=v(e=>{h==null||h(e)},[h]),Y=v((e,t)=>{g==null||g(e,t)},[g]),X=v(e=>{_==null||_(e)},[_]);return s(n,{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:[s(n,{sx:{display:`flex`,alignItems:`center`,gap:1,px:1,py:.5,borderBottom:`1px solid`,borderColor:`divider`,bgcolor:r===`dark`?`grey.900`:`grey.100`,flexShrink:0},children:[w(j,{variant:`subtitle2`,sx:{fontWeight:600,flex:1,color:`text.primary`},children:y.t(`AI Chat`)}),L&&w(m,{size:16}),w(u,{title:y.t(`New chat`),children:w(S,{size:`small`,onClick:K,children:w(B,{sx:{fontSize:18}})})}),w(u,{title:y.t(`Close`),children:w(S,{size:`small`,onClick:T,children:w(A,{sx:{fontSize:18}})})})]}),(N||R)&&w(ee,{severity:`error`,sx:{m:1,py:0},action:R?w(S,{size:`small`,onClick:q,children:w(te,{sx:{fontSize:16}})}):void 0,children:N||R}),z&&w(j,{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:z}),s(n,{sx:{flex:1,overflow:`auto`,py:1},children:[k.length===0&&!M&&s(n,{sx:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,height:`100%`,color:`text.secondary`,px:3,textAlign:`center`},children:[w(j,{variant:`body2`,sx:{mb:1},children:y.t(`Ask questions about your script, request changes, or generate new code.`)}),s(j,{variant:`caption`,color:`text.disabled`,children:[`Enter `,y.t(`to send`),`, Shift+Enter `,y.t(`for new line`)]})]}),k.filter(e=>e.role!==`system`).map(e=>w(We,{message:e,themeType:r,currentLanguage:a,onInsertCode:re,onShowDiff:Y,onApplyCode:X},e.id)),M&&((E=k[k.length-1])==null?void 0:E.content)===``&&s(n,{sx:{display:`flex`,alignItems:`center`,gap:1,px:2,py:1},children:[w(m,{size:16}),w(j,{variant:`caption`,color:`text.secondary`,children:y.t(`Thinking...`)})]}),w(`div`,{ref:O})]}),w(Je,{onSend:U,disabled:M||F.length===0,themeType:r,hasSelection:!!o,selectionText:o,allScripts:c,model:P,availableModels:F,modelProviderMap:I,modelsLoading:L,onModelChange:H,mode:ne,onModeChange:V,currentLanguage:a})]})};export{Ye as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Bt as e,Cr as t,Ht as n,Jn as r,Lt as i,dr as a,f as o,pr as s,qn as c,vr as l,xt as u,yt as d,zt as f}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-DuplUOZN.js";t();var p=({originalCode:t,modifiedCode:p,language:m,themeType:h,onAccept:g,onReject:_})=>{let v=l(null),y=l(null),b=l(null);s(()=>{let e=window.monaco;if(!e||!v.current)return;let n=e.editor.createDiffEditor(v.current,{readOnly:!1,originalEditable:!1,renderSideBySide:!0,automaticLayout:!0,theme:h===`dark`?`vs-dark`:`vs`,scrollBeyondLastLine:!1,minimap:{enabled:!1}}),r=e.editor.createModel(t,m),i=e.editor.createModel(p,m);return b.current=i,n.setModel({original:r,modified:i}),y.current=n,()=>{n.dispose(),r.dispose(),i.dispose(),y.current=null,b.current=null}},[t,p,m,h]);let x=a(()=>{var e;g(((e=b.current)==null?void 0:e.getValue())||p)},[p,g]);return r(e,{sx:{display:`flex`,flexDirection:`column`,height:`100%`,width:`100%`},children:[r(i,{variant:`dense`,sx:{minHeight:36,bgcolor:`background.paper`,borderBottom:`1px solid`,borderColor:`divider`,gap:1,flexShrink:0},children:[c(f,{variant:`subtitle2`,sx:{flex:1},children:o.t(`AI suggested changes`)}),c(n,{variant:`contained`,color:`success`,size:`small`,startIcon:c(u,{}),onClick:x,children:o.t(`Accept`)}),c(n,{variant:`outlined`,color:`error`,size:`small`,startIcon:c(d,{}),onClick:_,children:o.t(`Reject`)})]}),c(e,{ref:v,sx:{flex:1,overflow:`hidden`}})]})};export{p as default};
|