@madh-io/alfred-ai 0.11.2 → 0.11.3
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/bundle/index.js +4 -4
- package/package.json +1 -1
package/bundle/index.js
CHANGED
|
@@ -772,10 +772,10 @@ ${o}`}}async clientInfo(e){if(!e)return{success:!1,error:"mac is required for cl
|
|
|
772
772
|
Use "list_vouchers" to see the codes.`}}async enableWlan(e){return e?(await this.request("PUT",`rest/wlanconf/${e}`,{enabled:!0}),{success:!0,data:{id:e,enabled:!0},display:`WLAN ${e} enabled.`}):{success:!1,error:"id is required for enable_wlan."}}async disableWlan(e){return e?(await this.request("PUT",`rest/wlanconf/${e}`,{enabled:!1}),{success:!0,data:{id:e,enabled:!1},display:`WLAN ${e} disabled.`}):{success:!1,error:"id is required for disable_wlan."}}async archiveAlerts(){return await this.request("POST","cmd/evtmgr",{cmd:"archive-all-alarms"}),{success:!0,data:{},display:"All alerts archived."}}async blockClient(e){return e?(await this.request("POST","cmd/stamgr",{cmd:"block-sta",mac:e}),{success:!0,data:{mac:e},display:`Client ${e} blocked.`}):{success:!1,error:"mac is required for block_client."}}async unblockClient(e){return e?(await this.request("POST","cmd/stamgr",{cmd:"unblock-sta",mac:e}),{success:!0,data:{mac:e},display:`Client ${e} unblocked.`}):{success:!1,error:"mac is required for unblock_client."}}async forgetClient(e){return e?(await this.request("POST","cmd/stamgr",{cmd:"forget-sta",macs:[e]}),{success:!0,data:{mac:e},display:`Client ${e} forgotten (removed from known clients).`}):{success:!1,error:"mac is required for forget_client."}}async adoptDevice(e){return e?(await this.request("POST","cmd/devmgr",{cmd:"adopt",mac:e}),{success:!0,data:{mac:e},display:`Adopt command sent to device ${e}.`}):{success:!1,error:"mac is required for adopt_device."}}formatBytes(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],s=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/Math.pow(1024,s)).toFixed(s===0?0:1)} ${t[s]}`}formatUptime(e){let t=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),n=[];return t>0&&n.push(`${t}d`),s>0&&n.push(`${s}h`),n.push(`${r}m`),n.join(" ")}}});function Si(l){let e=l.match(/^(\d+)\s*(h|d|m|w)$/i);if(!e)return new Date(Date.now()-36e5).toISOString();let t=parseInt(e[1],10),s=e[2].toLowerCase(),r={m:6e4,h:36e5,d:864e5,w:6048e5}[s]??36e5;return new Date(Date.now()-t*r).toISOString()}function hp(l){let e=l.indexOf(".");if(e<1)throw new Error(`Invalid entity_id "${l}" \u2014 expected format "domain.name"`);return l.slice(0,e)}var Nn,Ul=w(()=>{"use strict";j();m(Si,"parsePeriod");m(hp,"extractDomain");Nn=class extends R{static{m(this,"HomeAssistantSkill")}metadata={name:"homeassistant",category:"infrastructure",description:'Control Home Assistant smart home devices. Use "states" to list entities, "turn_on"/"turn_off"/"toggle" to control devices, "call_service" for advanced service calls, "history" for entity state history. Also: "areas" for rooms/zones, "presence" for who is home, "activate_scene"/"trigger_automation"/"run_script" for automations, "notify" for notifications, "calendar_events" for calendars, "template" for Jinja2 queries, "error_log" for HA logs. Config API: "create_automation"/"delete_automation", "create_script"/"delete_script", "create_scene"/"delete_scene" \u2014 create persistent automations, scripts, and scenes in HA. Use configData (JSON) with the HA automation/script/scene schema. "briefing_summary" for a compact smart home overview (open contacts, lights on, battery/SoC, energy, climate, presence). Optionally pass entities[] or domains[] to filter. "energy_stats" for energy consumption statistics over a period (today, yesterday, last_week, etc.) \u2014 auto-discovers all energy sensors and calculates kWh consumed.',riskLevel:"write",version:"2.1.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["states","state","turn_on","turn_off","toggle","call_service","services","history","logbook","config","areas","template","presence","notify","activate_scene","trigger_automation","run_script","calendar_events","error_log","create_automation","delete_automation","create_script","delete_script","create_scene","delete_scene","briefing_summary","energy_stats"],description:"The Home Assistant action to perform"},entityId:{type:"string",description:"Entity ID, e.g. light.wohnzimmer, switch.garage, sensor.temperature"},domain:{type:"string",description:'Domain filter for "states" (e.g. light, sensor, switch) or domain for "call_service"'},service:{type:"string",description:'Service name for "call_service", e.g. set_temperature, set_hvac_mode'},serviceData:{type:"string",description:'JSON string with service parameters, e.g. {"brightness": 200, "color_name": "red"}'},period:{type:"string",description:'Time period for history/logbook/energy_stats. Formats: "1h", "24h", "7d" or friendly names "today", "yesterday", "this_week", "last_week", "this_month", "last_month" (default for energy_stats: "today")'},area:{type:"string",description:"Area name or ID (for areas action)"},template:{type:"string",description:"Jinja2 template string (for template action)"},target:{type:"string",description:"Notification target (for notify action, e.g. mobile_app_pixel)"},message:{type:"string",description:"Notification message (for notify action)"},title:{type:"string",description:"Optional title (for notify action)"},startTime:{type:"string",description:"ISO datetime start (for calendar_events, default: now)"},endTime:{type:"string",description:"ISO datetime end (for calendar_events, default: +24h)"},subAction:{type:"string",enum:["trigger","enable","disable"],description:"Sub-action for trigger_automation"},variables:{type:"string",description:"JSON string with script variables (for run_script)"},configId:{type:"string",description:'Unique ID for create/delete automation, script, or scene (e.g. "notify_garage_light"). Used as the HA config entry ID.'},configData:{type:"string",description:"JSON string with the HA config object for create actions. For automations: {alias, description, trigger[], condition[], action[], mode}. For scripts: {alias, sequence[], mode}. For scenes: {name, entities: {entity_id: state}}."},entities:{type:"array",items:{type:"string"},description:'Specific entity IDs for briefing_summary (e.g. ["sensor.victron_soc", "sensor.power_consumption"])'},domains:{type:"array",items:{type:"string"},description:'Domain filters for briefing_summary (e.g. ["binary_sensor", "light", "climate"])'}},required:["action"]}};config;constructor(e){super(),this.config=e}async execute(e,t){let s=e.action;if(!s)return{success:!1,error:'Missing required field "action"'};try{switch(s){case"states":return await this.getStates(e.domain);case"state":return await this.getState(e.entityId);case"turn_on":return await this.switchAction("turn_on",e.entityId,e.serviceData);case"turn_off":return await this.switchAction("turn_off",e.entityId,e.serviceData);case"toggle":return await this.switchAction("toggle",e.entityId,e.serviceData);case"call_service":return await this.callService(e.domain,e.service,e.entityId,e.serviceData);case"services":return await this.getServices();case"history":return await this.getHistory(e.entityId,e.period);case"logbook":return await this.getLogbook(e.entityId,e.period);case"config":return await this.getConfig();case"areas":return await this.getAreas(e.area);case"template":return await this.renderTemplate(e.template);case"presence":return await this.getPresence();case"notify":return await this.sendNotification(e.message,e.title,e.target);case"activate_scene":return await this.activateScene(e.entityId);case"trigger_automation":return await this.triggerAutomation(e.entityId,e.subAction);case"run_script":return await this.runScript(e.entityId,e.variables);case"calendar_events":return await this.getCalendarEvents(e.entityId,e.startTime,e.endTime);case"error_log":return await this.getErrorLog();case"create_automation":return await this.createConfig("automation",e.configId,e.configData);case"delete_automation":return await this.deleteConfig("automation",e.configId);case"create_script":return await this.createConfig("script",e.configId,e.configData);case"delete_script":return await this.deleteConfig("script",e.configId);case"create_scene":return await this.createConfig("scene",e.configId,e.configData);case"delete_scene":return await this.deleteConfig("scene",e.configId);case"briefing_summary":return await this.getBriefingSummary(e.entities,e.domains);case"energy_stats":return await this.getEnergyStats(e.period,e.entityId);default:return{success:!1,error:`Unknown action "${s}"`}}}catch(r){return{success:!1,error:`Home Assistant API error: ${r instanceof Error?r.message:String(r)}. Check baseUrl and connectivity.`}}}async api(e,t,s){let r=`${this.config.baseUrl.replace(/\/+$/,"")}${t}`,n={Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":"application/json"},o={method:e,headers:n,signal:AbortSignal.timeout(15e3)};s&&e!=="GET"&&(o.body=JSON.stringify(s));let i=this.config.verifyTls===!1,a=process.env.NODE_TLS_REJECT_UNAUTHORIZED;i&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");let c;try{c=await fetch(r,o)}finally{i&&(a===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=a)}if(!c.ok){let d="";try{d=(await c.text()).slice(0,500)}catch{}throw new Error(`HTTP ${c.status} ${c.statusText} \u2014 ${d}`)}return await c.json()}async apiText(e,t,s){let r=`${this.config.baseUrl.replace(/\/+$/,"")}${t}`,n={Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":"application/json"},o={method:e,headers:n,signal:AbortSignal.timeout(15e3)};s&&e!=="GET"&&(o.body=JSON.stringify(s));let i=this.config.verifyTls===!1,a=process.env.NODE_TLS_REJECT_UNAUTHORIZED;i&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");let c;try{c=await fetch(r,o)}finally{i&&(a===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=a)}if(!c.ok){let d="";try{d=(await c.text()).slice(0,500)}catch{}throw new Error(`HTTP ${c.status} ${c.statusText} \u2014 ${d}`)}return await c.text()}async getStates(e){let t=await this.api("GET","/api/states");e&&(t=t.filter(r=>r.entity_id.startsWith(`${e}.`)));let s=[`## Entities${e?` (${e})`:""}`,"","| Entity ID | State | Name | Unit |","|-----------|-------|------|------|"];for(let r of t){let n=r.attributes?.friendly_name??"-",o=r.attributes?.unit_of_measurement??"-";s.push(`| ${r.entity_id} | ${r.state} | ${n} | ${o} |`)}return t.length===0&&s.push(`| - | No entities found${e?` for domain "${e}"`:""} | - | - |`),{success:!0,data:t,display:s.join(`
|
|
773
773
|
`)}}async getState(e){if(!e)return{success:!1,error:'Missing required "entityId" parameter'};let t=await this.api("GET",`/api/states/${e}`),s=t.attributes??{},r=[`## ${s.friendly_name??e}`,"",`**Entity ID:** ${t.entity_id}`,`**State:** ${t.state}`,`**Last Changed:** ${t.last_changed??"-"}`,`**Last Updated:** ${t.last_updated??"-"}`,"","### Attributes"];for(let[n,o]of Object.entries(s)){let i=typeof o=="object"?JSON.stringify(o):String(o);r.push(`- **${n}:** ${i}`)}return{success:!0,data:t,display:r.join(`
|
|
774
774
|
`)}}async getServices(){let e=await this.api("GET","/api/services"),t=["## Available Services",""];for(let s of e){let r=s.domain??"unknown",n=Object.keys(s.services??{});if(n.length!==0){t.push(`### ${r}`);for(let o of n){let i=s.services[o]?.description??"";t.push(`- **${o}**${i?`: ${i}`:""}`)}t.push("")}}return{success:!0,data:e,display:t.join(`
|
|
775
|
-
`)}}async getHistory(e,t){let s=Si(t??"1h"),r=e?`?filter_entity_id=${e}
|
|
776
|
-
`)};for(let
|
|
777
|
-
`)}}async getLogbook(e,t){let s=Si(t??"1h"),r=e?`?entity=${e}
|
|
778
|
-
`)};
|
|
775
|
+
`)}}async getHistory(e,t){let s=Si(t??"1h"),r=new Date().toISOString(),n=e?`?filter_entity_id=${e}&end_time=${r}`:`?end_time=${r}`,o=await this.api("GET",`/api/history/period/${s}${n}`),i=["## History",""];if(!o||o.length===0||o.every(a=>a.length===0))return i.push("No history entries found for the given period."),{success:!0,data:[],display:i.join(`
|
|
776
|
+
`)};for(let a of o){if(a.length===0)continue;let c=a[0]?.entity_id??"unknown",d=a[0]?.attributes?.friendly_name??c;i.push(`### ${d} (\`${c}\`)`),i.push(""),i.push("| Time | State |"),i.push("|------|-------|");for(let u of a){let p=u.last_changed?new Date(u.last_changed).toLocaleString():"-";i.push(`| ${p} | ${u.state} |`)}i.push("")}return{success:!0,data:o,display:i.join(`
|
|
777
|
+
`)}}async getLogbook(e,t){let s=Si(t??"1h"),r=new Date().toISOString(),n=e?`?entity=${e}&end_time=${r}`:`?end_time=${r}`,o=await this.api("GET",`/api/logbook/${s}${n}`),i=["## Logbook",""];if(!o||o.length===0)return i.push("No logbook entries found for the given period."),{success:!0,data:[],display:i.join(`
|
|
778
|
+
`)};i.push("| Time | Entity | Message |"),i.push("|------|--------|---------|");for(let a of o){let c=a.when?new Date(a.when).toLocaleString():"-",d=a.name??a.entity_id??"-",u=a.message??a.state??"-";i.push(`| ${c} | ${d} | ${u} |`)}return{success:!0,data:o,display:i.join(`
|
|
779
779
|
`)}}async getConfig(){let e=await this.api("GET","/api/config"),t=["## Home Assistant Configuration","",`**Name:** ${e.location_name??"-"}`,`**Version:** ${e.version??"-"}`,`**Time Zone:** ${e.time_zone??"-"}`,`**Latitude:** ${e.latitude??"-"}`,`**Longitude:** ${e.longitude??"-"}`,`**Elevation:** ${e.elevation??"-"} m`,`**Unit System:** ${e.unit_system?.length?JSON.stringify(e.unit_system):"-"}`,`**Currency:** ${e.currency??"-"}`,`**Internal URL:** ${e.internal_url??"-"}`,`**External URL:** ${e.external_url??"-"}`];return e.components&&Array.isArray(e.components)&&t.push("",`**Components:** ${e.components.length} loaded`),{success:!0,data:e,display:t.join(`
|
|
780
780
|
`)}}async switchAction(e,t,s){if(!t)return{success:!1,error:'Missing required "entityId" parameter'};let r=hp(t),n={entity_id:t};if(s)try{let c=JSON.parse(s);Object.assign(n,c)}catch{return{success:!1,error:'Invalid "serviceData" \u2014 must be valid JSON'}}let o=await this.api("POST",`/api/services/${r}/${e}`,n),i=o?.[0]?.state??"unknown",a=o?.[0]?.attributes?.friendly_name??t;return{success:!0,data:o,display:[`**${e.replace("_"," ")}** \u2192 **${a}**`,"",`New state: **${i}**`].join(`
|
|
781
781
|
`)}}async callService(e,t,s,r){if(!e)return{success:!1,error:'Missing required "domain" parameter for call_service'};if(!t)return{success:!1,error:'Missing required "service" parameter for call_service'};let n={};if(s&&(n.entity_id=s),r)try{let c=JSON.parse(r);Object.assign(n,c)}catch{return{success:!1,error:'Invalid "serviceData" \u2014 must be valid JSON'}}let o=await this.api("POST",`/api/services/${e}/${t}`,n),i=o?.length??0,a=[`**Service called:** \`${e}.${t}\``,s?`**Entity:** ${s}`:"",`**Affected entities:** ${i}`].filter(Boolean);if(o&&o.length>0){a.push("");for(let c of o){let d=c.attributes?.friendly_name??c.entity_id??"unknown";a.push(`- **${d}**: ${c.state}`)}}return{success:!0,data:o,display:a.join(`
|