iobroker.javascript
Version:
Rules Engine for ioBroker
234 lines (204 loc) • 65.8 kB
JavaScript
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./aiPromptBuilder-Bs27qOHT.js","./rolldown-runtime-C0FnF6B9.js"])))=>i.map(i=>d[i]);
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{t}from"./vite-preload-helper-B7qeedMF.js";import{Ft as n,Hn as r,It as i,Kt as a,Lt as o,Mn as s,Nt as c,Rt as l,Sn as u,Tn as d,Un as f,_t as p,cn as m,cr as h,f as g,fr as _,gn as v,gt as y,hr as b,ln as x,mn as S,mr as C,or as w,qt as T,st as E,ut as D,vn as O,vt as k,wn as ee,xn as A,yr as j,zt as M}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-CxICLr5Z.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 te,r as L}from"./aiPromptBuilder-Bs27qOHT.js";var R=s(r(`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`),z=s(r(`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=s(r(`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`),B=s(r(`path`,{d:`M9.01 14H2v2h7.01v3L13 15l-3.99-4zm5.98-1v-3H22V8h-7.01V5L11 9z`}),`CompareArrows`),V=s(r(`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`),H=s(r(`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`),re=s(r(`path`,{d:`M2.01 21 23 12 2.01 3 2 10l15 2-15 2z`}),`Send`),U=s(r(`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`);j();var W=e(E(),1),G=t(()=>import(`./docs-compact-D7rpMc7r.js`),[],import.meta.url),K={openai:`img/openai.svg`,anthropic:`img/anthropic.svg`,gemini:`img/gemini.svg`,deepseek:`img/deepseek.svg`,custom:`img/custom.svg`},q={width:16,height:16,flexShrink:0,opacity:.7},ie={ru:`Russian`,en:`English`,de:`German`,es:`Spanish`,fr:`French`,it:`Italian`,pl:`Polish`,nl:`Dutch`,pt:`Portuguese`,uk:`Ukrainian`,"zh-cn":`Chinese`},J=null,Y=null,X=null,Z=null;function ae(){J=null,Y=null,X=null,Z=null}async function Q(e,t){if(J)return J;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?(J={providers:i,gptBaseUrl:a==null?void 0:a.baseUrl},J):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 Q(e,t);if(!n)return{models:[],providerMap:{},errors:[`No API keys configured`]};let r=Object.keys(t)[0];if(!r)return{models:[],providerMap:{},errors:[g.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(Z)return Z;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 Z=Object.assign(t,n,r,i,a),Z}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(Y)return Y;let t=g.getLanguage(),n=await ue(e),r=Object.keys(n).sort(),i=new W.default,a=[],o=[`UNREACH_STICKY`],s=[W.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 _;r.name=fe(((_=a.common)==null?void 0:_.name)||r.name,t)}}else{var v;r.name=fe((i==null||(v=i.common)==null?void 0:v.name)||r.name,t)}}}return Y=p,p}async function me(){return X||(X=(await G).default,X)}function he(){return ie[g.getLanguage()]||`English`}function ge(e){return`You write ioBroker JavaScript adapter scripts.
Copy EXACTLY this syntax. Do NOT change the callback signature.
IMPORTANT: Write all code at top level. NEVER use console.log (use log instead). NEVER define functions with the function keyword.
// CORRECT: on() always has ONE callback argument called obj
on('zigbee.0.sensor.state', (obj) => {
// obj.state.val = the new value (boolean or number)
// obj.id = the state ID that changed
setState('zigbee.0.lamp.state', obj.state.val);
log('Changed to ' + obj.state.val);
});
// CORRECT: on() with filter
on({id: /zigbee\\.0\\..*\\.state$/, change: 'ne'}, (obj) => {
if (obj.state.val === true) {
setState('zigbee.0.other.state', true);
}
});
// Other correct examples:
setState('id', true);
setState('id', 50);
const val = getState('id').val;
schedule('0 7 * * *', () => { log('runs daily at 07:00'); });
schedule('0 22 * * *', () => { setState('id', false); });
// CORRECT Telegram: always use sendTo, NEVER setState on telegram
sendTo('telegram.0', 'send', {text: 'Alert: ' + someValue});
// CORRECT httpGet: res.data is a STRING, parse JSON with JSON.parse
httpGet('https://api.example.com/data', (err, res) => {
const data = JSON.parse(res.data);
log('Temperature: ' + data.main.temp);
});
$('state[state.id=*.state](rooms=Room)').each((id) => { setState(id, false); });
createState('name', 0, {type: 'number', name: 'Name'});
// CORRECT: one-time delayed action (turn off after 5 minutes = 300000ms)
setStateDelayed('zigbee.0.lamp.state', false, false, 5 * 60 * 1000);
log(formatDate(new Date(), 'DD.MM.YYYY hh:mm'));
WRONG: on('id', (id, state) => {}) CORRECT: on('id', (obj) => {})
WRONG: set('id', true) CORRECT: setState('id', true)
WRONG: adapter.setState('id', true) CORRECT: setState('id', true)
WRONG: obj.val or newState.val CORRECT: obj.state.val
WRONG: on('change', {id: 'x'}, cb) CORRECT: on({id: 'x', change: 'ne'}, cb)
WRONG: setState('telegram.0', text) CORRECT: sendTo('telegram.0', 'send', {text: text})
WRONG: res.body.main.temp CORRECT: JSON.parse(res.data).main.temp
WRONG: function myFunc() {} CORRECT: write code directly, no function definitions
WRONG: setTimeout(fn, ms) CORRECT: setStateDelayed(id, val, false, ms) for one-time delay
WRONG: schedule('*/5 * * * *', fn) for one-time delay. schedule() is ONLY for recurring tasks
Values are boolean (true/false) or numbers, NEVER strings like 'ON'/'OFF'.
NEVER use: function keyword, require, import, setInterval, setTimeout, console.log, debug().
All available functions (use syntax from examples above):
on(pattern, (obj)=>{}) | once(pattern, (obj)=>{}) | unsubscribe(handler)
setState(id, val) | getState(id).val | setStateChanged(id, val) | setStateDelayed(id, val, ack, ms) | clearStateDelayed(id)
existsState(id) | existsObject(id) | getObject(id) | setObject(id, obj) | extendObject(id, obj) | deleteObject(id)
createState(name, initVal, {type,name,role}) | deleteState(name) | createAlias(name, alias)
schedule(cron, ()=>{}) | clearSchedule(obj) | scheduleById(id, (obj)=>{}) | getSchedules()
sendTo(adapter, cmd, msg) | sendToHost(host, cmd, msg)
$('selector').each((id)=>{}) | $('selector').setState(val) | $('selector').getState()
log(text) | formatDate(date, 'DD.MM.YYYY hh:mm') | formatTimeDiff(ms) | formatValue(val, decimals)
getDateObject(str) | getAstroDate(pattern) | isAstroDay() | compareTime(start, end, op)
exec(cmd, (err,stdout,stderr)=>{}) | httpGet(url, (err,res)=>{}) | httpPost(url, data, (err,res)=>{})
readFile(adapter, name, (err,data)=>{}) | writeFile(adapter, name, data, cb) | delFile(adapter, name, cb)
onFile(id, name, withFile, cb) | offFile(id, name) | onStop(cb, timeout)
getHistory(inst, {id,start,end,aggregate,count}, cb) | getEnums(name) | getIdByName(name)
wait(ms) | toInt(val) | toFloat(val) | toBoolean(val)
messageTo(target, data) | onMessage(name, cb) | onLog(severity, cb)
runScript(name) | startScript(name) | stopScript(name) | isScriptActive(name)
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.
Use EXACT state IDs from the plan. Write text/comments in ${e}.
IMPORTANT RULES:
- Return ONLY the inner blocks (no <xml> wrapper needed)
- Use the exact block types shown below
- State IDs must be full paths like "zigbee2mqtt.0.0x1234.state"
- Values are boolean (true/false) or numbers, NEVER strings like "ON"/"OFF"
- For Telegram use sendto_custom block, NEVER setState on telegram
## Block Templates
### Trigger: on_ext (react to state changes)
<block type="on_ext" x="0" y="0">
<mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
<field name="CONDITION">ne</field>
<field name="ACK_CONDITION"></field>
<value name="OID0">
<shadow type="field_oid"><field name="oid">STATE_ID_HERE</field></shadow>
</value>
<statement name="STATEMENT">
<!-- actions here -->
</statement>
</block>
### Schedule: schedule (cron-based)
<block type="schedule" x="0" y="0">
<field name="SCHEDULE">0 7 * * *</field>
<statement name="STATEMENT">
<!-- actions here -->
</statement>
</block>
### Set State: control
<block type="control">
<mutation xmlns="http://www.w3.org/1999/xhtml" delay_input="false"></mutation>
<field name="OID">STATE_ID_HERE</field>
<field name="WITH_DELAY">FALSE</field>
<value name="VALUE">
<block type="logic_boolean"><field name="BOOL">TRUE</field></block>
</value>
</block>
### Get State Value: get_value
<block type="get_value">
<field name="ATTR">val</field>
<field name="OID">STATE_ID_HERE</field>
</block>
### Log: debug
<block type="debug">
<field name="Severity">log</field>
<value name="TEXT">
<shadow type="text"><field name="TEXT">Message here</field></shadow>
</value>
</block>
### SendTo (Telegram): sendto_custom
<block type="sendto_custom">
<mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
<field name="INSTANCE">telegram.0</field>
<field name="COMMAND">send</field>
<field name="LOG"></field>
<value name="ARG0">
<block type="text"><field name="TEXT">Message text</field></block>
</value>
<value name="ATTR0">
<block type="text"><field name="TEXT">text</field></block>
</value>
</block>
### Timeout: timeouts_settimeout
<block type="timeouts_settimeout">
<field name="NAME">timeout1</field>
<field name="DELAY">5000</field>
<field name="UNIT">ms</field>
<statement name="STATEMENT">
<!-- delayed actions -->
</statement>
</block>
### If/Else: controls_if
<block type="controls_if">
<mutation else="1"></mutation>
<value name="IF0">
<block type="logic_compare">
<field name="OP">EQ</field>
<value name="A"><block type="get_value"><field name="ATTR">val</field><field name="OID">STATE_ID</field></block></value>
<value name="B"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
</block>
</value>
<statement name="DO0"><!-- then --></statement>
<statement name="ELSE"><!-- else --></statement>
</block>
### Number value
<block type="math_number"><field name="NUM">0</field></block>
### Text value
<block type="text"><field name="TEXT">hello</field></block>
### Boolean value
<block type="logic_boolean"><field name="BOOL">TRUE</field></block>
### Comparison: logic_compare
<block type="logic_compare">
<field name="OP">EQ</field>
<!-- OP can be: EQ, NEQ, LT, LTE, GT, GTE -->
<value name="A"><!-- left side --></value>
<value name="B"><!-- right side --></value>
</block>
## Common Patterns
### Turn on light when sensor triggers:
<block type="on_ext" x="0" y="0">
<mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
<field name="CONDITION">ne</field>
<field name="ACK_CONDITION"></field>
<value name="OID0">
<shadow type="field_oid"><field name="oid">zigbee2mqtt.0.0xSENSOR.occupancy</field></shadow>
</value>
<statement name="STATEMENT">
<block type="controls_if">
<value name="IF0">
<block type="logic_compare">
<field name="OP">EQ</field>
<value name="A"><block type="get_value"><field name="ATTR">val</field><field name="OID">zigbee2mqtt.0.0xSENSOR.occupancy</field></block></value>
<value name="B"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
</block>
</value>
<statement name="DO0">
<block type="control">
<mutation xmlns="http://www.w3.org/1999/xhtml" delay_input="false"></mutation>
<field name="OID">zigbee2mqtt.0.0xLAMP.state</field>
<field name="WITH_DELAY">FALSE</field>
<value name="VALUE"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
</block>
</statement>
</block>
</statement>
</block>
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(`
`),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=w((e,t,n)=>e===`none`||!n?null:{range:t,scriptId:c||``,scriptVersion:(i||``).length,kind:e,originalText:n},[c,i]),[u,d]=b(()=>{try{let e=window.localStorage.getItem(`Editor.aiChatMessages`);return e?JSON.parse(e):[]}catch{return[]}}),f=w(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]=b(!1),[_,v]=b(null),[y,x]=b(window.localStorage.getItem(`Editor.aiChatMode`)||`agent`),S=w(e=>{x(e),window.localStorage.setItem(`Editor.aiChatMode`,e)},[]),[T,E]=b(null),[D,O]=b(window.localStorage.getItem(`openai-model`)||``),[k,ee]=b([]),[A,j]=b({}),[M,N]=b(!0),[I,te]=b(null),L=C(null),R=C(null),z=C(null),ne=C(null),B=w(e=>{O(e),window.localStorage.setItem(`openai-model`,e)},[]),V=w(async()=>{N(!0),te(null);try{let e=await ce(n,r);if(ee(e.models),j(e.providerMap),e.models.length>0){let t=window.localStorage.getItem(`openai-model`);t&&e.models.includes(t)?O(t):O(e.models[0])}e.errors.length>0&&te(e.errors.join(`; `))}catch(e){te(String(e))}N(!1)},[n,r]);h(()=>{V()},[V]);let H=w(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]),re=w(async(e,t,s)=>{ne.current||=await me(),L.current||=await Q(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.
ioBroker object hierarchy: adapter.instance.device.channel.state
- A "state" is a single datapoint (e.g. zigbee2mqtt.0.0x1234.temperature)
- A "channel" groups related states (e.g. zigbee2mqtt.0.0x1234 contains temperature, humidity, battery)
- A "device" groups channels (e.g. zigbee2mqtt.0.0x1234)
- The channel/device often has the human-readable name (e.g. "Living Room Sensor")
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.
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.
Available API and syntax rules:
${ne.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]),U=w(async e=>{if(!e.trim()||p)return;let t=A[D];if(!t){E(g.t(`Please select a valid model`));return}let i=L.current||await Q(n,r);if(L.current=i,!i){E(g.t(`No API keys configured`));return}let o=Object.keys(r)[0];if(!o){E(g.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:`⏳ ${g.t(`Generating plan...`)}`,timestamp:Date.now()};f(e=>[...e,c,l]),m(!0),E(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:D,provider:t,baseUrl:s});if(l.error){E(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:`📋 **${g.t(`Plan`)}:**\n${u}`}),t});let d={id:Pe(),role:`assistant`,content:`⏳ ${g.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),y=await le(n,o,{messages:[{role:`system`,content:_},{role:`user`,content:h}],model:D,provider:t,baseUrl:s});if(y.error){E(y.error),f(e=>e.slice(0,-1)),m(!1);return}let b=ve(y.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:b}),t}),v(`${g.t(`devices`)}: ${i.length}`)}catch(e){E(String(e)),f(e=>e.slice(0,-1))}m(!1)},[D,A,p,n,r,a,f]),W=w(async e=>{if(y===`code`)return U(e);if(!e.trim()||p)return;let t=A[D];if(!t){E(g.t(`Please select a valid model`));return}let i=L.current||await Q(n,r);if(L.current=i,!i){E(g.t(`No API keys configured`));return}let a=Object.keys(r)[0];if(!a){E(g.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},_={id:Pe(),role:`assistant`,content:``,timestamp:Date.now(),sourceRange:c};f(e=>[...e,h,_]),m(!0),E(null);let{cleanMessage:b,mentionedScriptIds:x,includeAll:S,includeDevices:C}=H(e),w=[];if(S)w.push(`${g.t(`all scripts`)} (${(o==null?void 0:o.length)||0})`);else if(x.length>0){let e=x.map(e=>e.replace(/^script\.js\./,``));w.push(e.join(`, `))}else w.push(g.t(`current script`));C&&w.push(g.t(`devices`)),v(`${g.t(`Context`)}: ${w.join(` + `)}`);let T=await re(S,C,x),O=t===`custom`&&i.gptBaseUrl||``,k=b||e;if(o&&o.length>0){let e=k.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(`
`)}`)}t.length>0&&(k+=`\n\n[Automatic analysis results]\n${t.join(`
`)}`)}}let ee=[...T,...u.filter(e=>e.role!==`system`).map(e=>({role:e.role,content:e.content})),{role:`user`,content:k}],j=y===`agent`;try{let e=[...ee];for(let r=0;r<5;r++){let i=await le(n,a,{messages:e,model:D,provider:t,baseUrl:O,...j?{tools:ye}:{}});if(i.error){if(j&&r===0&&i.error.toLowerCase().includes(`tool`)){let r=await le(n,a,{messages:e,model:D,provider:t,baseUrl:O});if(r.error)E(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}E(i.error),f(e=>e.slice(0,-1));break}let c=i.tool_calls;if((!c||c.length===0)&&j&&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`🔍 ${g.t(`Searching datapoints`)}: "${String(t.query||``)}"`;case`get_state_value`:return`📊 ${g.t(`Reading value`)}: ${String(t.id||``)}`;case`get_object_info`:return`📋 ${g.t(`Loading object info`)}: ${String(t.id||``)}`;case`search_scripts`:return`🔍 ${g.t(`Searching scripts`)}: "${String(t.query||``)}"`;case`read_script`:return`📖 ${g.t(`Reading script`)}: ${String(t.id||``)}`;case`list_scripts`:return`📂 ${g.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(`
`)}),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){E(String(e)),f(e=>e.slice(0,-1))}m(!1)},[D,A,u,p,n,r,re,H,o,y,U,f,l,s]),G=w(()=>{f([]),E(null),m(!1),v(null),ae(),window.localStorage.removeItem(`Editor.aiChatHistory`)},[f]),K=w(async(e,t)=>{let i=A[D];if(!i)return`Error: ${g.t(`Please select a valid model`)}`;let o=L.current||await Q(n,r);if(L.current=o,!o)return`Error: ${g.t(`No API keys configured`)}`;let s=Object.keys(r)[0];if(!s)return`Error: ${g.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:D,provider:i,baseUrl:c});return e.error?`Error: ${e.error}`:e.content||``}catch(e){return`Error: ${e.message||String(e)}`}},[D,A,r,n,a]);return{messages:u,isLoading:p,error:T,model:D,availableModels:k,modelProviderMap:A,modelsLoading:M,modelsError:I,lastContextInfo:_,mode:y,setMode:S,setModel:B,sendMessage:W,triggerAiAction:w(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?W(n):R.current=null}).catch(()=>{R.current=null,E(g.t(`Failed to build AI action prompt`))})},[W,a,l]),askInline:K,clearChat:G,retryLoadModels:V}}j();var Ie=({code:e,language:t,themeType:i,onInsertCode:a,onShowDiff:s,sourceRange:c})=>{let l=C(null);h(()=>{var n;let r=window.monaco;if(!l.current||!(r!=null&&(n=r.editor)!=null&&n.colorize))return;let a=t===`ts`||t===`typescript`?`typescript`:t||`javascript`;r.editor.colorize(e,a,{theme:i===`dark`?`vs-dark`:`vs`}).then(e=>{l.current&&(l.current.innerHTML=e)})},[e,t,i]);let u=w(()=>{navigator.clipboard.writeText(e)},[e]);return f(o,{sx:{position:`relative`,my:1,borderRadius:1,overflow:`hidden`,border:`1px solid`,borderColor:`divider`},children:[f(o,{sx:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,px:1,py:.5,bgcolor:`action.hover`,borderBottom:`1px solid`,borderColor:`divider`},children:[r(o,{sx:{fontSize:`0.75rem`,color:`text.secondary`,textTransform:`uppercase`},children:t||`javascript`}),f(o,{children:[r(n,{title:g.t(`Copy`),children:r(x,{size:`small`,onClick:u,children:r(y,{sx:{fontSize:16}})})}),a&&r(n,{title:g.t(`Insert into editor`),children:r(x,{size:`small`,onClick:()=>a(e),children:r(R,{sx:{fontSize:16}})})}),s&&r(n,{title:g.t(`Show as diff`),children:r(x,{size:`small`,onClick:()=>s(e,c),children:r(B,{sx:{fontSize:16}})})})]})]}),r(`pre`,{ref:l,style:{margin:0,padding:`8px 12px`,overflow:`auto`,maxHeight:400,fontSize:`13px`,fontFamily:`'Cascadia Code', 'Fira Code', 'Consolas', monospace`,backgroundColor:i===`dark`?`#1e1e1e`:`#f8f8f8`,color:i===`dark`?`#d4d4d4`:`#333`},children:e})]})};j();var Le=({xml:e,themeType:t})=>{let n=C(null),i=C(null),[a,s]=b(60),c=C(!1);return h(()=>{c.current&&(c.current=!1,requestAnimationFrame(()=>{let e=window.Blockly,t=i.current;e&&t&&(e.svgResize(t),t.scrollCenter())}))},[a]),h(()=>{let r=window.Blockly;if(!(!r||!n.current)){i.current&&=(i.current.dispose(),null);try{let a=r.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:t===`dark`?I():`classic`,media:`google-blockly/media/`});i.current=a;let o=e.trim();o.startsWith(`<xml`)||(o=`<xml xmlns="https://developers.google.com/blockly/xml">${o}</xml>`);let l=r.utils.xml.textToDom(o),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;r.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));c.current=!0,s(t)}}catch{}return()=>{i.current&&=(i.current.dispose(),null)}}},[e,t]),r(o,{ref:n,sx:{width:`100%`,height:a,minHeight:60,borderRadius:1,overflow:`hidden`,border:`1px solid`,borderColor:`divider`}})};j();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.