@madh-io/alfred-ai 0.10.62 → 0.10.64
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 +6 -4
- package/package.json +1 -1
package/bundle/index.js
CHANGED
|
@@ -755,7 +755,7 @@ ${t.join(`
|
|
|
755
755
|
|
|
756
756
|
Pendler-Check (Mo\u2013Fr): ${s?r?"\u2705 konfiguriert (Config)":"\u23F3 Adressen werden aus Memories gelesen (oder ALFRED_BRIEFING_HOME/OFFICE_ADDRESS setzen)":"\u274C Routing-Skill nicht verf\xFCgbar"}`}}async runBriefing(e,t){let{home:s}=this.resolveAddresses(t),n=(s?np(s):void 0)??this.alfredConfig.briefing?.location??e.location??"Vienna",o=e.modules,i=this.getAvailableModules();o?.length&&(i=i.filter(h=>o.includes(h.name)));let a=this.resolveHaPreferences(t),c=i.map(h=>{let y={...h.input};if(h.name==="calendar"){let{start:E,end:$}=rp();y.start=E,y.end=$}return h.name==="weather"&&(y.location=n),h.name==="home"&&(a.entities?.length&&(y.entities=a.entities),a.domains?.length&&(y.domains=a.domains)),{module:h,input:y}}),d=await Promise.all(c.map(h=>this.executeModule(h.module,h.input,t))),u=await this.runCommuteCheck(d,t);u&&d.push(u);let p=new Date().toLocaleDateString("de-AT",{weekday:"long",year:"numeric",month:"long",day:"numeric"}),g=[];g.push(`**\u2600\uFE0F Morgenbriefing \u2013 ${p}**
|
|
757
757
|
`);for(let h of d)h.success&&h.display?g.push(`**${h.label}**
|
|
758
|
-
${h.display}`):h.success&&h.data?g.push(`**${h.label}**
|
|
758
|
+
${this.cleanDisplay(h.module,h.display)}`):h.success&&h.data?g.push(`**${h.label}**
|
|
759
759
|
${typeof h.data=="string"?h.data:JSON.stringify(h.data,null,2)}`):!h.success&&h.error&&g.push(`**${h.label}**
|
|
760
760
|
\u26A0\uFE0F ${h.error}`);let f=this.buildHighlights(d);return f.length>0&&(g.push("---"),g.push("**Highlights:**"),g.push(f.join(`
|
|
761
761
|
`))),{success:!0,data:d,display:g.join(`
|
|
@@ -764,7 +764,9 @@ ${typeof h.data=="string"?h.data:JSON.stringify(h.data,null,2)}`):!h.success&&h.
|
|
|
764
764
|
${a.display}`):a.error&&d.push(`**Route:** \u26A0\uFE0F ${a.error}`),c?.success&&c.data){let u=this.extractBatteryLevel(c.data);u!=null&&u<30?d.push(`
|
|
765
765
|
\u26A0\uFE0F **BMW Akku niedrig (${u}%)** \u2014 Laden vor der Fahrt empfohlen!`):u!=null&&d.push(`
|
|
766
766
|
\u{1F50B} BMW Akku: ${u}% \u2014 ausreichend f\xFCr den Arbeitsweg`)}return d.length===0?null:{module:"commute",label:"Arbeitsweg (Mo\u2013Fr)",success:!0,data:{route:a.data,bmwBattery:this.extractBatteryLevel(c?.data)},display:d.join(`
|
|
767
|
-
`)}}resolveAddresses(e){let t=this.alfredConfig.briefing?.homeAddress,s=this.alfredConfig.briefing?.officeAddress;if(!this.memoryRepo)return{home:t,office:s};let r=t,n=s;for(let o of G(e)){let i=this.memoryRepo.search(o,"adresse");for(let a of i){let c=a.key.toLowerCase(),d=a.value;!r&&/heim|home|wohn|zuhause|privat/.test(c)&&(r=d),!n&&/büro|office|arbeit|firma|work/.test(c)&&(n=d)}if(r&&n)break}return{home:r,office:n}}resolveHaPreferences(e){let t=this.alfredConfig.briefing?.homeAssistant?.entities,s=this.alfredConfig.briefing?.homeAssistant?.domains;if(t?.length||s?.length)return{entities:t,domains:s};if(!this.memoryRepo)return{};for(let r of G(e)){let n=this.memoryRepo.search(r,"briefing");for(let o of n){let i=o.key.toLowerCase();if(/ha_entit|home.?assistant.*entit|briefing.*entit/.test(i)){let a=o.value.split(/[,;]\s*/).map(c=>c.trim()).filter(Boolean);if(a.length)return{entities:a}}if(/ha_domain|home.?assistant.*domain|briefing.*domain/.test(i)){let a=o.value.split(/[,;]\s*/).map(c=>c.trim()).filter(Boolean);if(a.length)return{domains:a}}}}return{}}detectExternalAppointment(e){return Array.isArray(e)?e.some(t=>{let s=t.location??t.loc??"";return!s||typeof s!="string"||/teams|zoom|meet\.google|webex|skype/i.test(s)?!1:s.trim().length>0}):!1}
|
|
767
|
+
`)}}resolveAddresses(e){let t=this.alfredConfig.briefing?.homeAddress,s=this.alfredConfig.briefing?.officeAddress;if(!this.memoryRepo)return{home:t,office:s};let r=t,n=s;for(let o of G(e)){let i=this.memoryRepo.search(o,"adresse");for(let a of i){let c=a.key.toLowerCase(),d=a.value;!r&&/heim|home|wohn|zuhause|privat/.test(c)&&(r=d),!n&&/büro|office|arbeit|firma|work/.test(c)&&(n=d)}if(r&&n)break}return{home:r,office:n}}resolveHaPreferences(e){let t=this.alfredConfig.briefing?.homeAssistant?.entities,s=this.alfredConfig.briefing?.homeAssistant?.domains;if(t?.length||s?.length)return{entities:t,domains:s};if(!this.memoryRepo)return{};for(let r of G(e)){let n=this.memoryRepo.search(r,"briefing");for(let o of n){let i=o.key.toLowerCase();if(/ha_entit|home.?assistant.*entit|briefing.*entit/.test(i)){let a=o.value.split(/[,;]\s*/).map(c=>c.trim()).filter(Boolean);if(a.length)return{entities:a}}if(/ha_domain|home.?assistant.*domain|briefing.*domain/.test(i)){let a=o.value.split(/[,;]\s*/).map(c=>c.trim()).filter(Boolean);if(a.length)return{domains:a}}}}return{}}detectExternalAppointment(e){return Array.isArray(e)?e.some(t=>{let s=t.location??t.loc??"";return!s||typeof s!="string"||/teams|zoom|meet\.google|webex|skype/i.test(s)?!1:s.trim().length>0}):!1}cleanDisplay(e,t){let s=t;return s=s.replace(/\s*\[(?:id:)?[A-Za-z0-9+/=]{20,}\]/g,""),e==="email"&&(s=s.replace(/^\d+\.\s*/gm,"- ").replace(/\[UNREAD\]/g,"\u{1F4E9}").replace(/\[ATT\]/g,"\u{1F4CE}").replace(/\n\s+Date:\s+\S+/g,"")),e==="calendar"&&(s=s.replace(/^\d+\s+event\(s\):\n?/i,"")),s=s.replace(/^\[[\w-]+\]\s*/gm,""),s=s.replace(/\n{3,}/g,`
|
|
768
|
+
|
|
769
|
+
`),s.trim()}buildHighlights(e){let t=[],s=e.find(i=>i.module==="bmw")?.data;if(s){let i=this.extractBatteryLevel(s);i!=null&&i<30&&t.push(`\u{1F697} BMW Akku bei ${i}% \u2014 laden empfohlen`)}let r=e.find(i=>i.module==="infra");r&&(!r.success||r.display?.includes("\u26A0\uFE0F"))&&t.push("\u{1F534} Infrastruktur-Warnung vorhanden");let n=e.find(i=>i.module==="energy")?.data;if(n){let i=n.currentCt,a=n.avgCt;i!=null&&a!=null&&i<a&&t.push(`\u26A1 Aktuell g\xFCnstiger Strom (${i} ct/kWh)`)}let o=e.find(i=>i.module==="calendar")?.data;return Array.isArray(o)&&o.length>0&&t.push(`\u{1F4C5} ${o.length} Termin(e) heute`),t}extractBatteryLevel(e){if(!e||typeof e!="object")return null;let t=e,s=t.chargingLevelPercent??t.batterySoc??t.soc??t.chargingState?.chargingLevelPercent;if(typeof s=="number")return s;if(typeof s=="string"){let r=parseFloat(s);return isNaN(r)?null:r}return null}}});import{spawn as ip}from"node:child_process";import Hl from"node:fs";import Wl from"node:path";function dp(l){let e={};for(let[t,s]of Object.entries(l))e[t]=s.replace(/\$\{(\w+)\}/g,(r,n)=>process.env[n]??"");return e}function up(l,e){return l.map(t=>t.replace(/\{\{prompt\}\}/g,e))}function Rn(l){return l.length<=ql?l:`[...truncated...]
|
|
768
770
|
`+l.slice(-ql)}function zl(l){let e=new Map;function t(s){let r;try{r=Hl.readdirSync(s,{withFileTypes:!0})}catch{return}for(let n of r){if(lp.has(n.name))continue;let o=Wl.join(s,n.name);if(n.isDirectory())t(o);else if(n.isFile())try{let i=Hl.statSync(o);e.set(o,i.mtimeMs)}catch{}}}return m(t,"walk"),t(l),e}function mp(l,e,t){let s=[];for(let[r,n]of e){let o=l.get(r);(o===void 0||n>o)&&s.push(Wl.relative(t,r))}return s.sort()}async function gr(l,e,t={}){let s=t.cwd??l.cwd??process.cwd(),r=t.timeoutMs??l.timeoutMs??ap,n=Math.min(r,cp),o=up(l.argsTemplate,e),i={...process.env,...l.env?dp(l.env):{}},a=process.platform==="win32",c=zl(s),d=Date.now();return new Promise(u=>{let p=ip(l.command,o,{cwd:s,env:i,shell:a,stdio:l.promptVia==="stdin"?["pipe","pipe","pipe"]:["ignore","pipe","pipe"]}),g="",f="",h=!1,y=setTimeout(()=>{h=!0,p.kill("SIGTERM"),setTimeout(()=>p.kill("SIGKILL"),5e3)},n);p.stdout?.on("data",E=>{g+=E.toString()}),p.stderr?.on("data",E=>{let $=E.toString();if(f+=$,t.onProgress){let v=$.trim().split(`
|
|
769
771
|
`).pop();v&&t.onProgress(`[${l.name}] ${v}`)}}),l.promptVia==="stdin"&&p.stdin&&(p.stdin.write(e),p.stdin.end()),p.on("close",E=>{clearTimeout(y);let $=Date.now()-d,v=zl(s),P=mp(c,v,s);u({stdout:Rn(g),stderr:Rn(f),exitCode:h?124:E??1,durationMs:$,modifiedFiles:P})}),p.on("error",E=>{clearTimeout(y);let $=Date.now()-d;u({stdout:Rn(g),stderr:Rn(f+`
|
|
770
772
|
`+E.message),exitCode:127,durationMs:$,modifiedFiles:[]})})})}var ap,cp,ql,lp,Cn=_(()=>{"use strict";ap=3e5,cp=9e5,ql=1e5,lp=new Set([".git","node_modules",".next","dist",".cache"]);m(dp,"resolveEnv");m(up,"buildArgs");m(Rn,"truncateOutput");m(zl,"snapshotMtimes");m(mp,"detectModifiedFiles");m(gr,"executeAgent")});import{execFile as pp}from"node:child_process";function Fe(l,e){return new Promise((t,s)=>{pp("git",l,{cwd:e.cwd,maxBuffer:10*1024*1024},(r,n,o)=>{if(r){let i=o?.trim()||r.message;s(new Error(`git ${l[0]} failed: ${i}`));return}t(n.trim())})})}async function Dn(l){try{let e=await Fe(["rev-parse","--abbrev-ref","HEAD"],l),t=await Fe(["status","--porcelain"],l);return{isRepo:!0,branch:e,dirty:t.length>0}}catch{return{isRepo:!1,branch:"",dirty:!1}}}async function Ti(l,e){await Fe(["checkout","-b",l],e)}async function _i(l){await Fe(["add","-A"],l)}async function bi(l,e){await Fe(["commit","-m",l],e);let t=await Fe(["rev-parse","--short","HEAD"],e),r=(await Fe(["diff","--stat","HEAD~1","HEAD"],e)).split(`
|
|
@@ -838,7 +840,7 @@ ${e.allModifiedFiles.map(r=>`- ${r}`).join(`
|
|
|
838
840
|
|
|
839
841
|
**Git:**
|
|
840
842
|
${s.join(`
|
|
841
|
-
`)}`:"";return{...t,data:{...t.data,git:{branch:r.branch,commit:r.commit,pullRequest:r.pullRequest,warnings:r.warnings}},display:(t.display??"")+n}}}});var Xl=_(()=>{"use strict";Kl();Cn();xi();ki();Ai()});var ee={};me(ee,{ActivityTracker:()=>Tt,BMWSkill:()=>$n,BackgroundTaskSkill:()=>es,BriefingSkill:()=>xn,BrowserSkill:()=>Jt,CalculatorSkill:()=>Pt,CalendarProvider:()=>Me,CalendarSkill:()=>_t,ClipboardSkill:()=>Xt,CodeAgentSkill:()=>_r,CodeExecutionSkill:()=>lr,CodeExecutor:()=>$t,ConfigureSkill:()=>ls,ContactsProvider:()=>Ue,ContactsSkill:()=>mr,CrossPlatformSkill:()=>Qt,DelegateSkill:()=>Wt,DockerSkill:()=>_n,DocumentSkill:()=>ss,EmailProvider:()=>Ve,EmailSkill:()=>et,EnergyPriceSkill:()=>vn,FileSkill:()=>Vt,ForgeClient:()=>St,HomeAssistantSkill:()=>fn,HttpSkill:()=>Gt,ImageGenerateSkill:()=>ns,MCPClient:()=>bt,MCPManager:()=>cr,MCPSkillAdapter:()=>Et,MarketplaceSkill:()=>fr,MemorySkill:()=>zt,MicrosoftTodoSkill:()=>An,MonitorSkill:()=>Sn,NoteSkill:()=>Bt,PluginLoader:()=>nn,ProfileSkill:()=>Zt,ProxmoxSkill:()=>pn,ReminderSkill:()=>jt,RoutingSkill:()=>kn,ScheduledTaskSkill:()=>ts,ScreenshotSkill:()=>Yt,ShellSkill:()=>qt,Skill:()=>R,SkillRegistry:()=>Mt,SkillSandbox:()=>Ot,SystemInfoSkill:()=>Ut,TTSSkill:()=>rs,TodoSkill:()=>os,TransitSkill:()=>as,UniFiSkill:()=>hn,WatchSkill:()=>ds,WeatherSkill:()=>Ht,WebSearchSkill:()=>Ft,allUserIds:()=>G,createCalendarProvider:()=>ar,createContactsProvider:()=>ci,createEmailProvider:()=>nr,createForgeClient:()=>ps,effectiveUserId:()=>ae,gitAddRemote:()=>wr,gitGetRemoteUrl:()=>us,gitInitRepo:()=>yr,orchestrate:()=>At,orchestrateWithGit:()=>Tr,parseRemoteUrl:()=>ms});var Z=_(()=>{"use strict";U();Ne();lc();dc();Vo();uc();mc();pc();hc();fc();gc();yc();_c();bc();Ec();Sc();Ic();Rc();Cc();Lc();Mc();Oc();Hc();qc();zc();Wc();Vc();Xc();Yc();Jc();Zc();Qc();el();tl();al();cl();pl();_l();bl();Il();xl();Dl();Ll();Nl();Ol();jl();Bl();Xl()});var br,Ri=_(()=>{"use strict";br=class{static{m(this,"ConversationManager")}conversations;constructor(e){this.conversations=e}getOrCreateConversation(e,t,s){let r=this.conversations.findByPlatformChat(e,t);return r?(this.conversations.updateTimestamp(r.id),r):this.conversations.create(e,t,s)}addMessage(e,t,s,r){return this.conversations.addMessage(e,t,s,r)}getHistory(e,t=20){return this.conversations.getMessages(e,t)}pruneMessages(e,t){return this.conversations.pruneMessages(e,t)}}});function Ke(l,e){let t;if(e.platformUserId)t=l.findOrCreate(e.platform,e.platformUserId,e.userName,e.displayName);else if(e.userId)t=l.findById(e.userId)??l.findOrCreate(e.platform,e.userId);else throw new Error("ContextSource must provide either platformUserId or userId");let s="getMasterUserId"in l?l.getMasterUserId(t.id):t.id,r=[];"getLinkedUsers"in l&&(r=l.getLinkedUsers(s).map(a=>a.platformUserId));let n;try{"getProfile"in l?n=l.getProfile(s)?.timezone||Intl.DateTimeFormat().resolvedOptions().timeZone:n=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n=Intl.DateTimeFormat().resolvedOptions().timeZone}return{context:{userId:t.platformUserId,masterUserId:s,linkedPlatformUserIds:r,chatId:e.chatId,chatType:e.chatType,platform:e.platform,conversationId:e.conversationId??"",timezone:n},user:t,masterUserId:s,linkedPlatformUserIds:r}}var hs=_(()=>{"use strict";m(Ke,"buildSkillContext")});function Yl(l,e){let t=new Set(["core"]),s=!1;for(let[r,n]of Object.entries(kp))e.has(r)&&n.test(l)&&(t.add(r),s=!0);if(!s){let r=["productivity","information","media"];for(let n of r)e.has(n)&&t.add(n)}return t}function Jl(l,e){return l.filter(t=>e.has(t.category??"core"))}var kp,Zl=_(()=>{"use strict";kp={productivity:/\b(todo|note|remind|calendar|termin|event|email|e-mail|mail|contact|kontakt|briefing|morgenbriefing|tagesbriefing)\b/i,information:/\b(search|such|weather|wetter|calculat|rechn|time|date|zeit|datum|uhrzeit|system.?info|transit|bahn|zug|bus|tram|u.?bahn|s.?bahn|abfahrt|verbindung|haltestelle|öffi|fahrplan|strom|energy|preis|price|kwh|awattar|marktpreis|spot|günstig|cheapest|netzentgelt)\b/i,media:/\b(voice|stimme|tts|speak|sprech|sprich|screenshot|clipboard|zwischenablage|brows)\b/i,automation:/\b(background|hintergrund|shell|bash|cron|schedul|code.?agent|sandbox|automat|watch|alert|benachrichtig|bescheid|meld|überwach|monitor|tägliche?r?s?|stündliche?r?s?|wöchentliche?r?s?|monatliche?r?s?|jeden\s+(tag|morgen|abend|montag|dienstag|mittwoch|donnerstag|freitag|samstag|sonntag)|um\s+\d{1,2}\s*(uhr|:|h)|alle\s+\d+\s*(min|stund|sekund)|in\s+\d+\s*(minuten?|stunden?|sekunden?|hours?|minutes?|seconds?|min)|daily|hourly|weekly|every\s+(day|hour|morning|evening|night|\d+\s*min)|führ.{0,5}aus|execut|ausführ)\b/i,files:/\b(file|datei|document|dokument|pdf|http|download|upload)\b/i,infrastructure:/\b(proxmox|vm|container|docker|unifi|wifi|wlan|homeassistant|home.?assistant|smarthome|smart.?home|licht|light|schalter|switch|solar|photovoltaik|pv|wechselrichter|inverter|batterie.?speicher|wallbox|energieverbrauch|stromverbrauch|verbrauch.{0,5}kwh|einspeis|netzeinspeis|autarkie|eigenverbrauch)\b/i,identity:/\b(link|verknüpf|cross.?platform|identity|identität)\b/i,mcp:/\bmcp\b/i};m(Yl,"selectCategories");m(Jl,"filterSkills")});import Ci from"node:fs";import Ql from"node:path";var vp,ed,Sp,td,Ap,Ip,xp,sd,Er,Di=_(()=>{"use strict";Wo();hs();Zl();vp=15*60*1e3,ed=50,Sp=2,td=.85,Ap=1e5,Ip=2e3,xp=.1,sd=3,Er=class{static{m(this,"MessagePipeline")}promptBuilder;llm;conversationManager;users;logger;skillRegistry;skillSandbox;securityManager;memoryRepo;speechTranscriber;inboxPath;embeddingService;activeLearning;memoryRetriever;maxHistoryMessages;documentProcessor;activeAgents=new Map;agentIdCounter=0;constructor(e){this.llm=e.llm,this.conversationManager=e.conversationManager,this.users=e.users,this.logger=e.logger,this.skillRegistry=e.skillRegistry,this.skillSandbox=e.skillSandbox,this.securityManager=e.securityManager,this.memoryRepo=e.memoryRepo,this.speechTranscriber=e.speechTranscriber,this.inboxPath=e.inboxPath,this.embeddingService=e.embeddingService,this.activeLearning=e.activeLearning,this.memoryRetriever=e.memoryRetriever,this.maxHistoryMessages=e.maxHistoryMessages??30,this.documentProcessor=e.documentProcessor,this.promptBuilder=new Qs}async process(e,t){let s=Date.now();this.logger.info({platform:e.platform,userId:e.userId,chatId:e.chatId},"Processing message");try{let{user:r,masterUserId:n,linkedPlatformUserIds:o,context:i}=Ke(this.users,{platformUserId:e.userId,platform:e.platform,chatId:e.chatId,chatType:e.chatType,userName:e.userName,displayName:e.displayName}),a=this.conversationManager.getOrCreateConversation(e.platform,e.chatId,r.id),c=e.metadata?.skipHistory?[]:this.conversationManager.getHistory(a.id,this.maxHistoryMessages);this.conversationManager.addMessage(a.id,"user",e.text);let d,u=this.isSyntheticLabel(e.text),p=e.attachments?.some(H=>H.type==="audio")??!1,g=u&&!p;if(this.memoryRetriever&&e.text&&!g)try{d=await this.memoryRetriever.retrieve(n,e.text,15,o)}catch(H){this.logger.debug({err:H},"Hybrid memory retrieval failed")}if(!d&&this.memoryRepo&&!g)try{let H=[n,...(o??[]).filter(se=>se!==n)];if(this.embeddingService&&e.text&&this.llm.supportsEmbeddings()){let se=new Set;d=[];for(let ce of H)for(let ie of await this.embeddingService.semanticSearch(ce,e.text,10))se.has(ie.key)||(se.add(ie.key),d.push(ie));for(let ce of H)for(let ie of this.memoryRepo.getRecentForPrompt(ce,5))se.has(ie.key)||(se.add(ie.key),d.push(ie))}else{let se=new Set;d=[];for(let ce of H)for(let ie of this.memoryRepo.getRecentForPrompt(ce,20))se.has(ie.key)||(se.add(ie.key),d.push(ie))}}catch(H){this.logger.debug({err:H},"Memory loading failed")}d&&d.length>0&&(d=this.applyMemoryBudget(d));let f;try{"getProfile"in this.users&&(f=this.users.getProfile(n),f&&!f.displayName&&(f.displayName=r.displayName??r.username))}catch(H){this.logger.debug({err:H},"Profile loading failed")}let h=i.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,y=this.skillRegistry?this.skillRegistry.getAll().map(H=>H.metadata):void 0,E=y;if(y&&e.text){let H=new Set(y.map(ce=>ce.category??"core")),se=Yl(e.text,H);E=Jl(y,se)}let $=E?this.promptBuilder.buildTools(E):void 0,v=this.promptBuilder.buildSystemPrompt({memories:d,skills:E,userProfile:f}),P=this.buildActiveAgentStatus();P&&(v+=`
|
|
843
|
+
`)}`:"";return{...t,data:{...t.data,git:{branch:r.branch,commit:r.commit,pullRequest:r.pullRequest,warnings:r.warnings}},display:(t.display??"")+n}}}});var Xl=_(()=>{"use strict";Kl();Cn();xi();ki();Ai()});var ee={};me(ee,{ActivityTracker:()=>Tt,BMWSkill:()=>$n,BackgroundTaskSkill:()=>es,BriefingSkill:()=>xn,BrowserSkill:()=>Jt,CalculatorSkill:()=>Pt,CalendarProvider:()=>Me,CalendarSkill:()=>_t,ClipboardSkill:()=>Xt,CodeAgentSkill:()=>_r,CodeExecutionSkill:()=>lr,CodeExecutor:()=>$t,ConfigureSkill:()=>ls,ContactsProvider:()=>Ue,ContactsSkill:()=>mr,CrossPlatformSkill:()=>Qt,DelegateSkill:()=>Wt,DockerSkill:()=>_n,DocumentSkill:()=>ss,EmailProvider:()=>Ve,EmailSkill:()=>et,EnergyPriceSkill:()=>vn,FileSkill:()=>Vt,ForgeClient:()=>St,HomeAssistantSkill:()=>fn,HttpSkill:()=>Gt,ImageGenerateSkill:()=>ns,MCPClient:()=>bt,MCPManager:()=>cr,MCPSkillAdapter:()=>Et,MarketplaceSkill:()=>fr,MemorySkill:()=>zt,MicrosoftTodoSkill:()=>An,MonitorSkill:()=>Sn,NoteSkill:()=>Bt,PluginLoader:()=>nn,ProfileSkill:()=>Zt,ProxmoxSkill:()=>pn,ReminderSkill:()=>jt,RoutingSkill:()=>kn,ScheduledTaskSkill:()=>ts,ScreenshotSkill:()=>Yt,ShellSkill:()=>qt,Skill:()=>R,SkillRegistry:()=>Mt,SkillSandbox:()=>Ot,SystemInfoSkill:()=>Ut,TTSSkill:()=>rs,TodoSkill:()=>os,TransitSkill:()=>as,UniFiSkill:()=>hn,WatchSkill:()=>ds,WeatherSkill:()=>Ht,WebSearchSkill:()=>Ft,allUserIds:()=>G,createCalendarProvider:()=>ar,createContactsProvider:()=>ci,createEmailProvider:()=>nr,createForgeClient:()=>ps,effectiveUserId:()=>ae,gitAddRemote:()=>wr,gitGetRemoteUrl:()=>us,gitInitRepo:()=>yr,orchestrate:()=>At,orchestrateWithGit:()=>Tr,parseRemoteUrl:()=>ms});var Z=_(()=>{"use strict";U();Ne();lc();dc();Vo();uc();mc();pc();hc();fc();gc();yc();_c();bc();Ec();Sc();Ic();Rc();Cc();Lc();Mc();Oc();Hc();qc();zc();Wc();Vc();Xc();Yc();Jc();Zc();Qc();el();tl();al();cl();pl();_l();bl();Il();xl();Dl();Ll();Nl();Ol();jl();Bl();Xl()});var br,Ri=_(()=>{"use strict";br=class{static{m(this,"ConversationManager")}conversations;constructor(e){this.conversations=e}getOrCreateConversation(e,t,s){let r=this.conversations.findByPlatformChat(e,t);return r?(this.conversations.updateTimestamp(r.id),r):this.conversations.create(e,t,s)}addMessage(e,t,s,r){return this.conversations.addMessage(e,t,s,r)}getHistory(e,t=20){return this.conversations.getMessages(e,t)}pruneMessages(e,t){return this.conversations.pruneMessages(e,t)}}});function Ke(l,e){let t;if(e.platformUserId)t=l.findOrCreate(e.platform,e.platformUserId,e.userName,e.displayName);else if(e.userId)t=l.findById(e.userId)??l.findOrCreate(e.platform,e.userId);else throw new Error("ContextSource must provide either platformUserId or userId");let s="getMasterUserId"in l?l.getMasterUserId(t.id):t.id,r=[];"getLinkedUsers"in l&&(r=l.getLinkedUsers(s).map(a=>a.platformUserId));let n;try{"getProfile"in l?n=l.getProfile(s)?.timezone||Intl.DateTimeFormat().resolvedOptions().timeZone:n=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n=Intl.DateTimeFormat().resolvedOptions().timeZone}return{context:{userId:t.platformUserId,masterUserId:s,linkedPlatformUserIds:r,chatId:e.chatId,chatType:e.chatType,platform:e.platform,conversationId:e.conversationId??"",timezone:n},user:t,masterUserId:s,linkedPlatformUserIds:r}}var hs=_(()=>{"use strict";m(Ke,"buildSkillContext")});function Yl(l,e){let t=new Set(["core"]),s=!1;for(let[r,n]of Object.entries(kp))e.has(r)&&n.test(l)&&(t.add(r),s=!0);if(!s){let r=["productivity","information","media","automation"];for(let n of r)e.has(n)&&t.add(n)}return t}function Jl(l,e){return l.filter(t=>e.has(t.category??"core"))}var kp,Zl=_(()=>{"use strict";kp={productivity:/\b(todo|note|remind|calendar|termin|event|email|e-mail|mail|contact|kontakt|briefing|morgenbriefing|tagesbriefing)\b/i,information:/\b(search|such|weather|wetter|calculat|rechn|time|date|zeit|datum|uhrzeit|system.?info|transit|bahn|zug|bus|tram|u.?bahn|s.?bahn|abfahrt|verbindung|haltestelle|öffi|fahrplan|strom|energy|preis|price|kwh|awattar|marktpreis|spot|günstig|cheapest|netzentgelt)\b/i,media:/\b(voice|stimme|tts|speak|sprech|sprich|screenshot|clipboard|zwischenablage|brows)\b/i,automation:/\b(background|hintergrund|shell|bash|cron|schedul|code.?agent|sandbox|automat|watch|alert|benachrichtig|bescheid|meld|überwach|monitor|tägliche?r?s?|stündliche?r?s?|wöchentliche?r?s?|monatliche?r?s?|jeden\s+(tag|morgen|abend|montag|dienstag|mittwoch|donnerstag|freitag|samstag|sonntag)|um\s+\d{1,2}\s*(uhr|:|h)|alle\s+\d+\s*(min|stund|sekund)|in\s+\d+\s*(minuten?|stunden?|sekunden?|hours?|minutes?|seconds?|min)|daily|hourly|weekly|every\s+(day|hour|morning|evening|night|\d+\s*min)|führ.{0,5}aus|execut|ausführ)\b/i,files:/\b(file|datei|document|dokument|pdf|http|download|upload)\b/i,infrastructure:/\b(proxmox|vm|container|docker|unifi|wifi|wlan|homeassistant|home.?assistant|smarthome|smart.?home|licht|light|schalter|switch|solar|photovoltaik|pv|wechselrichter|inverter|batterie.?speicher|wallbox|energieverbrauch|stromverbrauch|verbrauch.{0,5}kwh|einspeis|netzeinspeis|autarkie|eigenverbrauch|bmw|auto|fahrzeug|ladestand|reichweite|laden(?!e)|charging|vehicle|soc)\b/i,identity:/\b(link|verknüpf|cross.?platform|identity|identität)\b/i,mcp:/\bmcp\b/i};m(Yl,"selectCategories");m(Jl,"filterSkills")});import Ci from"node:fs";import Ql from"node:path";var vp,ed,Sp,td,Ap,Ip,xp,sd,Er,Di=_(()=>{"use strict";Wo();hs();Zl();vp=15*60*1e3,ed=50,Sp=2,td=.85,Ap=1e5,Ip=2e3,xp=.1,sd=3,Er=class{static{m(this,"MessagePipeline")}promptBuilder;llm;conversationManager;users;logger;skillRegistry;skillSandbox;securityManager;memoryRepo;speechTranscriber;inboxPath;embeddingService;activeLearning;memoryRetriever;maxHistoryMessages;documentProcessor;activeAgents=new Map;agentIdCounter=0;constructor(e){this.llm=e.llm,this.conversationManager=e.conversationManager,this.users=e.users,this.logger=e.logger,this.skillRegistry=e.skillRegistry,this.skillSandbox=e.skillSandbox,this.securityManager=e.securityManager,this.memoryRepo=e.memoryRepo,this.speechTranscriber=e.speechTranscriber,this.inboxPath=e.inboxPath,this.embeddingService=e.embeddingService,this.activeLearning=e.activeLearning,this.memoryRetriever=e.memoryRetriever,this.maxHistoryMessages=e.maxHistoryMessages??30,this.documentProcessor=e.documentProcessor,this.promptBuilder=new Qs}async process(e,t){let s=Date.now();this.logger.info({platform:e.platform,userId:e.userId,chatId:e.chatId},"Processing message");try{let{user:r,masterUserId:n,linkedPlatformUserIds:o,context:i}=Ke(this.users,{platformUserId:e.userId,platform:e.platform,chatId:e.chatId,chatType:e.chatType,userName:e.userName,displayName:e.displayName}),a=this.conversationManager.getOrCreateConversation(e.platform,e.chatId,r.id),c=e.metadata?.skipHistory?[]:this.conversationManager.getHistory(a.id,this.maxHistoryMessages);this.conversationManager.addMessage(a.id,"user",e.text);let d,u=this.isSyntheticLabel(e.text),p=e.attachments?.some(H=>H.type==="audio")??!1,g=u&&!p;if(this.memoryRetriever&&e.text&&!g)try{d=await this.memoryRetriever.retrieve(n,e.text,15,o)}catch(H){this.logger.debug({err:H},"Hybrid memory retrieval failed")}if(!d&&this.memoryRepo&&!g)try{let H=[n,...(o??[]).filter(se=>se!==n)];if(this.embeddingService&&e.text&&this.llm.supportsEmbeddings()){let se=new Set;d=[];for(let ce of H)for(let ie of await this.embeddingService.semanticSearch(ce,e.text,10))se.has(ie.key)||(se.add(ie.key),d.push(ie));for(let ce of H)for(let ie of this.memoryRepo.getRecentForPrompt(ce,5))se.has(ie.key)||(se.add(ie.key),d.push(ie))}else{let se=new Set;d=[];for(let ce of H)for(let ie of this.memoryRepo.getRecentForPrompt(ce,20))se.has(ie.key)||(se.add(ie.key),d.push(ie))}}catch(H){this.logger.debug({err:H},"Memory loading failed")}d&&d.length>0&&(d=this.applyMemoryBudget(d));let f;try{"getProfile"in this.users&&(f=this.users.getProfile(n),f&&!f.displayName&&(f.displayName=r.displayName??r.username))}catch(H){this.logger.debug({err:H},"Profile loading failed")}let h=i.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,y=this.skillRegistry?this.skillRegistry.getAll().map(H=>H.metadata):void 0,E=y;if(y&&e.text){let H=new Set(y.map(ce=>ce.category??"core")),se=Yl(e.text,H);E=Jl(y,se)}let $=E?this.promptBuilder.buildTools(E):void 0,v=this.promptBuilder.buildSystemPrompt({memories:d,skills:E,userProfile:f}),P=this.buildActiveAgentStatus();P&&(v+=`
|
|
842
844
|
|
|
843
845
|
`+P);let x=this.promptBuilder.buildMessages(c),B=this.collapseRepeatedToolErrors(x),te=await this.buildUserContent(e,t);B.push({role:"user",content:te});let re=$?Le(JSON.stringify($)):0,N=1,K=this.trimToContextWindow(v,B,re,N),z,le=0,de=Date.now(),ne="",oe=0,D=0,W=0,Te=[];for(t?.("Thinking...");;){le>0&&this.compressToolLoop(K,v,re);try{z=await this.llm.complete({messages:K,system:v,tools:$&&$.length>0?$:void 0,tier:e.metadata?.tier}),D+=z.usage?.inputTokens??0,W+=z.usage?.outputTokens??0}catch(ke){if((ke instanceof Error?ke.message:String(ke)).includes("prompt is too long")&&N>.3){N*=.5,this.logger.warn({budgetMultiplier:N},"Prompt too long, retrimming with reduced budget"),K=this.trimToContextWindow(v,B,re,N);continue}throw ke}if(!z.toolCalls||z.toolCalls.length===0)break;let H=Date.now()-de;if(H>=vp){let ke=Math.round(H/6e4);this.logger.warn({iteration:le,elapsedMin:ke,pendingToolCalls:z.toolCalls.length},"Tool loop timeout reached"),z=await this.abortToolLoop(K,z,a.id,v,`Das Zeitlimit von ${ke} Minuten f\xFCr Tool-Aufrufe wurde erreicht.`,!1,e.metadata?.tier);break}if(le>=ed){this.logger.warn({iteration:le,pendingToolCalls:z.toolCalls.length},"Tool loop iteration cap reached"),z=await this.abortToolLoop(K,z,a.id,v,`Das Iterationslimit von ${ed} Tool-Aufrufen wurde erreicht.`,!1,e.metadata?.tier);break}le++,this.logger.info({iteration:le,toolCalls:z.toolCalls.length},"Processing tool calls");let se=[];z.content&&se.push({type:"text",text:z.content});for(let ke of z.toolCalls)se.push({type:"tool_use",id:ke.id,name:ke.name,input:ke.input});K.push({role:"assistant",content:se});let ce=await this.executeToolCallsParallel(z.toolCalls,{...i,conversationId:a.id,timezone:h},t),ie=ce.blocks;ce.attachments.length>0&&Te.push(...ce.attachments),this.conversationManager.addMessage(a.id,"assistant",z.content??"",JSON.stringify(z.toolCalls)),this.conversationManager.addMessage(a.id,"user","",JSON.stringify(ie));let Rt=this.buildErrorSignature(ie);if(Rt){if(Rt===ne?oe++:(oe=1,ne=Rt),oe>=Sp){this.logger.warn({iteration:le,consecutiveErrors:oe,errorSignature:Rt},"Tool loop aborted: same error repeated consecutively"),z=await this.abortToolLoop(K,z,a.id,v,`Der gleiche Tool-Fehler ist ${oe}x hintereinander aufgetreten: "${ne.slice(0,200)}". Erkl\xE4re dem User kurz was nicht funktioniert hat und schlage eine Alternative vor.`,!0,e.metadata?.tier);break}}else oe=0,ne="";K.push({role:"user",content:ie}),t?.("Thinking...")}let Q=z.content;if(!Q)for(let H=K.length-1;H>=0;H--){let se=K[H];if(se.role==="assistant"&&Array.isArray(se.content)){let ce=se.content.find(ie=>ie.type==="text");if(ce&&"text"in ce&&ce.text){Q=ce.text;break}}}Q||(Q="(no response)"),this.conversationManager.addMessage(a.id,"assistant",Q),this.activeLearning&&this.activeLearning.onMessageProcessed(n,e.text,Q);let Je=Date.now()-s;return this.logger.info({duration:Je,tokens:z.usage,totalTokens:{inputTokens:D,outputTokens:W},stopReason:z.stopReason,toolIterations:le},"Message processed"),{text:Q,attachments:Te.length>0?Te:void 0}}catch(r){throw this.logger.error({err:r},"Failed to process message"),r}}async abortToolLoop(e,t,s,r,n,o=!1,i){if(!o){let d=[];t.content&&d.push({type:"text",text:t.content});for(let u of t.toolCalls)d.push({type:"tool_use",id:u.id,name:u.name,input:u.input});e.push({role:"assistant",content:d})}let a=t.toolCalls.map(d=>({type:"tool_result",tool_use_id:d.id,content:`Error: tool loop aborted \u2014 ${n}`,is_error:!0}));e.push({role:"user",content:a}),o||this.conversationManager.addMessage(s,"assistant",t.content??"",JSON.stringify(t.toolCalls)),this.conversationManager.addMessage(s,"user","",JSON.stringify(a));let c=e[e.length-1];return c&&c.role==="user"&&Array.isArray(c.content)?c.content.push({type:"text",text:`[System: ${n} Fasse dem User kurz zusammen was du bisher geschafft hast und was noch offen ist.]`}):e.push({role:"user",content:`[System: ${n} Fasse dem User kurz zusammen was du bisher geschafft hast und was noch offen ist.]`}),await this.llm.complete({messages:e,system:r,tier:i})}buildErrorSignature(e){let t=[];for(let s of e)s.type==="tool_result"&&s.is_error&&t.push(s.content);return t.length>0?t.join("|"):""}collapseRepeatedToolErrors(e){let t=[],s=0;for(;s<e.length;){let r=e[s];if(r.role==="assistant"&&Array.isArray(r.content)&&r.content.some(n=>n.type==="tool_use")){let n=s+1<e.length?e[s+1]:null;if(n&&n.role==="user"&&Array.isArray(n.content)&&n.content.every(o=>o.type==="tool_result"&&o.is_error)){let o=this.toolPairSignature(r,n),i=1,a=s+2;for(;a+1<e.length;){let c=e[a],d=e[a+1];if(c.role==="assistant"&&d?.role==="user"&&this.toolPairSignature(c,d)===o)i++,a+=2;else break}if(i>1){t.push(r),t.push(n),t.push({role:"user",content:`[System: The above tool error repeated ${i} times with identical input. The loop was aborted.]`}),s=a;continue}}}t.push(r),s++}return t}toolPairSignature(e,t){let s=Array.isArray(e.content)?e.content.filter(n=>n.type==="tool_use").map(n=>`${n.name}:${JSON.stringify(n.input)}`).join(","):"",r=Array.isArray(t.content)?t.content.filter(n=>n.type==="tool_result").map(n=>n.content).join(","):"";return`${s}|${r}`}async executeToolCallsParallel(e,t,s){let r=[],n=m((u,p)=>{let g=p.content;if(p.attachments&&p.attachments.length>0){r.push(...p.attachments);let f=p.attachments.map(h=>h.fileName).join(", ");g+=`
|
|
844
846
|
|
|
@@ -868,7 +870,7 @@ Result: ${o.display??JSON.stringify(o.data)}`:`\u274C Background task failed: ${
|
|
|
868
870
|
|
|
869
871
|
Error: ${o.error}`;await a.sendMessage(e.chatId,c)}}catch(t){let s=t instanceof Error?t.message:String(t);this.taskRepo.updateStatus(e.id,"failed",void 0,s),this.logger.error({taskId:e.id,err:t},"Background task failed");let r=this.adapters.get(e.platform);r&&await r.sendMessage(e.chatId,`\u274C Background task failed: ${e.description}
|
|
870
872
|
|
|
871
|
-
Error: ${s}`)}}}});import Cp from"node:crypto";var Dr,Hi=_(()=>{"use strict";hs();Dr=class{static{m(this,"ProactiveScheduler")}actionRepo;skillRegistry;skillSandbox;llm;adapters;users;logger;pipeline;formatter;conversationManager;tickTimer;tickIntervalMs=6e4;constructor(e,t,s,r,n,o,i,a,c,d){this.actionRepo=e,this.skillRegistry=t,this.skillSandbox=s,this.llm=r,this.adapters=n,this.users=o,this.logger=i,this.pipeline=a,this.formatter=c,this.conversationManager=d}start(){this.tickTimer=setInterval(()=>this.tick(),this.tickIntervalMs),this.logger.info("Proactive scheduler started")}stop(){this.tickTimer&&(clearInterval(this.tickTimer),this.tickTimer=void 0),this.logger.info("Proactive scheduler stopped")}async tick(){try{let e=this.actionRepo.getDue();for(let t of e)try{await this.executeAction(t)}catch(s){this.logger.error({err:s,actionId:t.id},"Failed to execute scheduled action")}}catch(e){this.logger.error({err:e},"Error during proactive scheduler tick")}}async executeAction(e){let t=new Date().toISOString();this.logger.info({actionId:e.id,name:e.name},"Executing scheduled action");let s,r="text";if(e.promptTemplate&&this.pipeline)try{let u=`scheduled-${e.id}`,p=this.users.findById(e.userId),g=p?.platformUserId??e.userId,f={id:`scheduled-${Cp.randomUUID()}`,platform:e.platform,chatId:u,chatType:"dm",userId:g,userName:p?.username??g,text:e.promptTemplate+"\n\n[Format: Use only Markdown (**, *, ~~, `, ```). Do NOT use HTML tags like <b>, <i>, <code>. The system converts Markdown to platform-specific formatting automatically.]",timestamp:new Date,metadata:{scheduled:!0,skipHistory:!0,tier:"fast"}},h=await this.pipeline.process(f),y=this.formatter?this.formatter.format(h.text,e.platform):{text:h.text,parseMode:"text"};s=y.text,r=y.parseMode;let E=this.adapters.get(e.platform);if(E&&h.attachments)for(let $ of h.attachments)try{let v=$.mimeType.startsWith("image/"),P=$.mimeType==="audio/ogg"||$.mimeType==="audio/opus";v?await E.sendPhoto(e.chatId,$.data,$.fileName):P?await E.sendVoice(e.chatId,$.data):await E.sendFile(e.chatId,$.data,$.fileName)}catch(v){this.logger.warn({err:v,fileName:$.fileName,actionId:e.id},"Failed to send scheduled action attachment")}}catch(u){let p=u instanceof Error?u.message:String(u);this.logger.error({actionId:e.id,err:u},"Pipeline execution failed for scheduled action"),s=`Scheduled action "${e.name}" failed: ${p}`}else if(e.promptTemplate)try{s=(await this.llm.complete({messages:[{role:"user",content:e.promptTemplate}],maxTokens:1024,tier:"fast"})).content}catch(u){let p=u instanceof Error?u.message:String(u);this.logger.error({actionId:e.id,err:u},"LLM call failed for scheduled action"),s=`Scheduled action "${e.name}" failed: ${p}`}else
|
|
873
|
+
Error: ${s}`)}}}});import Cp from"node:crypto";var Dr,Hi=_(()=>{"use strict";hs();Dr=class{static{m(this,"ProactiveScheduler")}actionRepo;skillRegistry;skillSandbox;llm;adapters;users;logger;pipeline;formatter;conversationManager;tickTimer;tickIntervalMs=6e4;constructor(e,t,s,r,n,o,i,a,c,d){this.actionRepo=e,this.skillRegistry=t,this.skillSandbox=s,this.llm=r,this.adapters=n,this.users=o,this.logger=i,this.pipeline=a,this.formatter=c,this.conversationManager=d}start(){this.tickTimer=setInterval(()=>this.tick(),this.tickIntervalMs),this.logger.info("Proactive scheduler started")}stop(){this.tickTimer&&(clearInterval(this.tickTimer),this.tickTimer=void 0),this.logger.info("Proactive scheduler stopped")}async tick(){try{let e=this.actionRepo.getDue();for(let t of e)try{await this.executeAction(t)}catch(s){this.logger.error({err:s,actionId:t.id},"Failed to execute scheduled action")}}catch(e){this.logger.error({err:e},"Error during proactive scheduler tick")}}async executeAction(e){let t=new Date().toISOString();this.logger.info({actionId:e.id,name:e.name},"Executing scheduled action");let s,r="text";if(e.skillName&&this.skillRegistry.has(e.skillName)){let u=this.skillRegistry.get(e.skillName);try{let p;try{p=JSON.parse(e.skillInput)}catch{p={},this.logger.warn({actionId:e.id},"Invalid skillInput JSON, using empty input")}let{context:g}=Ke(this.users,{userId:e.userId,platform:e.platform,chatId:e.chatId,chatType:"dm"}),f=await this.skillSandbox.execute(u,p,g);if(f.success){let h=f.display??JSON.stringify(f.data);if(this.formatter){let y=this.formatter.format(h,e.platform);s=y.text,r=y.parseMode}else s=h}else s=`\u274C Scheduled action "${e.name}" failed: ${f.error}`}catch(p){let g=p instanceof Error?p.message:String(p);s=`\u274C Scheduled action "${e.name}" failed: ${g}`}}else if(e.promptTemplate&&this.pipeline)try{let u=`scheduled-${e.id}`,p=this.users.findById(e.userId),g=p?.platformUserId??e.userId,f={id:`scheduled-${Cp.randomUUID()}`,platform:e.platform,chatId:u,chatType:"dm",userId:g,userName:p?.username??g,text:e.promptTemplate+"\n\n[Format: Use only Markdown (**, *, ~~, `, ```). Do NOT use HTML tags like <b>, <i>, <code>. The system converts Markdown to platform-specific formatting automatically.]",timestamp:new Date,metadata:{scheduled:!0,skipHistory:!0,tier:"fast"}},h=await this.pipeline.process(f),y=this.formatter?this.formatter.format(h.text,e.platform):{text:h.text,parseMode:"text"};s=y.text,r=y.parseMode;let E=this.adapters.get(e.platform);if(E&&h.attachments)for(let $ of h.attachments)try{let v=$.mimeType.startsWith("image/"),P=$.mimeType==="audio/ogg"||$.mimeType==="audio/opus";v?await E.sendPhoto(e.chatId,$.data,$.fileName):P?await E.sendVoice(e.chatId,$.data):await E.sendFile(e.chatId,$.data,$.fileName)}catch(v){this.logger.warn({err:v,fileName:$.fileName,actionId:e.id},"Failed to send scheduled action attachment")}}catch(u){let p=u instanceof Error?u.message:String(u);this.logger.error({actionId:e.id,err:u},"Pipeline execution failed for scheduled action"),s=`Scheduled action "${e.name}" failed: ${p}`}else if(e.promptTemplate)try{s=(await this.llm.complete({messages:[{role:"user",content:e.promptTemplate}],maxTokens:1024,tier:"fast"})).content}catch(u){let p=u instanceof Error?u.message:String(u);this.logger.error({actionId:e.id,err:u},"LLM call failed for scheduled action"),s=`Scheduled action "${e.name}" failed: ${p}`}else this.logger.warn({actionId:e.id,skillName:e.skillName},"Unknown skill for scheduled action"),s=`Scheduled action "${e.name}" failed: unknown skill "${e.skillName}"`;let n=s.trim(),o=(e.promptTemplate??"").toLowerCase(),i=/nichts|silent|no\s*output|don't\s*respond|do\s*not\s*respond/i.test(o),a=/offline|down|fehler|error|warn|critical|alert|fail|nicht\s+(erreichbar|verf[uü]gbar|gefunden|online)|ausgefallen|stopped|unreachable|unavailable|⚠|❌|🚨|🔴/i.test(n)&&!/keine\s+(probleme|fehler|auff[aä]lligkeiten)/i.test(n);if(!n||n.length<3||i&&!a)this.logger.info({actionId:e.id,name:e.name},"Scheduled action produced no actionable output \u2014 skipping notification");else{let u=this.adapters.get(e.platform);if(u)try{if(await u.sendMessage(e.chatId,s,{parseMode:r!=="text"?r:void 0}),e.promptTemplate&&this.conversationManager){let p=this.conversationManager.getOrCreateConversation(e.platform,e.chatId,e.userId),g=`[Automated Scheduled Alert: ${e.name}]
|
|
872
874
|
${s}`;this.conversationManager.addMessage(p.id,"assistant",g)}}catch(p){this.logger.error({err:p,actionId:e.id},"Failed to send scheduled action result")}}if(e.promptTemplate&&this.conversationManager)try{let u=`scheduled-${e.id}`,p=this.conversationManager.getOrCreateConversation(e.platform,u,e.userId);this.conversationManager.pruneMessages(p.id,20)}catch{}let d=this.calculateNextRun(e);d?this.actionRepo.updateLastRun(e.id,t,d):(this.actionRepo.updateLastRun(e.id,t,null),this.actionRepo.setEnabled(e.id,!1))}calculateNextRun(e){let t=new Date;switch(e.scheduleType){case"interval":{let s=parseInt(e.scheduleValue,10);return isNaN(s)||s<=0?null:new Date(t.getTime()+s*6e4).toISOString()}case"once":return null;case"cron":return this.getNextCronDate(e.scheduleValue,t)?.toISOString()??null;default:return null}}getNextCronDate(e,t){let s=e.trim().split(/\s+/);if(s.length!==5)return null;let r=new Date(t.getTime()+6e4);r.setSeconds(0,0);for(let n=0;n<1440;n++){if(this.matchesCron(s,r))return r;r.setTime(r.getTime()+6e4)}return null}matchesCron(e,t){let s=t.getMinutes(),r=t.getHours(),n=t.getDate(),o=t.getMonth()+1,i=t.getDay();return this.matchCronField(e[0],s)&&this.matchCronField(e[1],r)&&this.matchCronField(e[2],n)&&this.matchCronField(e[3],o)&&this.matchCronField(e[4],i)}matchCronField(e,t){if(e==="*")return!0;let s=/^\*\/(\d+)$/.exec(e);if(s){let n=parseInt(s[1],10);return t%n===0}let r=parseInt(e,10);return isNaN(r)?!1:t===r}}});function rd(l,e){let t=e.split("."),s=l;for(let r of t){if(s==null)return;if(typeof s=="object"){if(r==="length"&&Array.isArray(s)){s=s.length;continue}s=s[r]}else return}return s}function nd(l,e,t,s){let r=Dp(l);if(s===null)return{triggered:!1,displayValue:r};switch(e){case"lt":case"gt":case"lte":case"gte":{let n=fs(l),o=fs(t);return n===null||o===null?{triggered:!1,displayValue:r}:{triggered:e==="lt"?n<o:e==="gt"?n>o:e==="lte"?n<=o:n>=o,displayValue:r}}case"eq":return{triggered:String(l)===String(t),displayValue:r};case"neq":return{triggered:String(l)!==String(t),displayValue:r};case"contains":return{triggered:String(l).includes(String(t??"")),displayValue:r};case"not_contains":return{triggered:!String(l).includes(String(t??"")),displayValue:r};case"changed":return{triggered:JSON.stringify(l)!==JSON.stringify(s),displayValue:r};case"increased":{let n=fs(l),o=fs(s);return n===null||o===null?{triggered:!1,displayValue:r}:{triggered:n>o,displayValue:r}}case"decreased":{let n=fs(l),o=fs(s);return n===null||o===null?{triggered:!1,displayValue:r}:{triggered:n<o,displayValue:r}}default:return{triggered:!1,displayValue:r}}}function fs(l){if(typeof l=="number")return l;let e=parseFloat(String(l));return isNaN(e)?null:e}function Dp(l){return l==null?"null":typeof l=="object"?JSON.stringify(l):String(l)}var od=_(()=>{"use strict";m(rd,"extractField");m(nd,"evaluateCondition");m(fs,"toNumber");m(Dp,"formatValue")});var Lp,Ln,id=_(()=>{"use strict";od();hs();Lp={lt:"<",gt:">",lte:"<=",gte:">=",eq:"=",neq:"!=",contains:"contains",not_contains:"not contains",changed:"changed",increased:"increased",decreased:"decreased"},Ln=class{static{m(this,"WatchEngine")}watchRepo;skillRegistry;skillSandbox;adapters;users;logger;timer=null;tickIntervalMs=6e4;constructor(e,t,s,r,n,o){this.watchRepo=e,this.skillRegistry=t,this.skillSandbox=s,this.adapters=r,this.users=n,this.logger=o}start(){this.timer=setInterval(()=>this.tick(),this.tickIntervalMs),this.logger.info("Watch engine started")}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.logger.info("Watch engine stopped")}async tick(){try{let e=this.watchRepo.getDue();for(let t of e)try{await this.checkWatch(t)}catch(s){this.logger.error({err:s,watchId:t.id},"Failed to check watch")}}catch(e){this.logger.error({err:e},"Error during watch engine tick")}}async checkWatch(e){let t=new Date().toISOString();this.logger.debug({watchId:e.id,name:e.name,skill:e.skillName},"Checking watch");let s=this.skillRegistry.get(e.skillName);if(!s){this.logger.warn({watchId:e.id,skillName:e.skillName},"Unknown skill for watch"),this.watchRepo.updateAfterCheck(e.id,{lastCheckedAt:t,lastValue:e.lastValue});return}let{context:r}=Ke(this.users,{platform:e.platform,chatId:e.chatId,chatType:"dm"}),n=await this.skillSandbox.execute(s,e.skillParams,r);if(!n.success){this.logger.warn({watchId:e.id,error:n.error},"Watch skill execution failed"),this.watchRepo.updateAfterCheck(e.id,{lastCheckedAt:t,lastValue:e.lastValue});return}let o=rd(n.data,e.condition.field),i=e.lastValue!==null?JSON.parse(e.lastValue):null,{triggered:a,displayValue:c}=nd(o,e.condition.operator,e.condition.value,i),d=JSON.stringify(o);if(a&&this.isCooldownExpired(e)){let u=e.messageTemplate??this.formatAlert(e,c),p=this.adapters.get(e.platform);if(p)try{await p.sendMessage(e.chatId,u),this.logger.info({watchId:e.id,name:e.name,value:c},"Watch alert sent")}catch(g){this.logger.error({err:g,watchId:e.id},"Failed to send watch alert")}this.watchRepo.updateAfterCheck(e.id,{lastCheckedAt:t,lastValue:d,lastTriggeredAt:t})}else this.watchRepo.updateAfterCheck(e.id,{lastCheckedAt:t,lastValue:d})}isCooldownExpired(e){if(!e.lastTriggeredAt)return!0;let t=e.cooldownMinutes*6e4;return Date.now()-new Date(e.lastTriggeredAt).getTime()>=t}formatAlert(e,t){let s=Lp[e.condition.operator]??e.condition.operator,r=e.condition.value!=null?` ${s} ${e.condition.value}`:` ${s}`;return`\u26A1 Watch Alert: ${e.name}
|
|
873
875
|
Bedingung erf\xFCllt: ${e.condition.field}${r}
|
|
874
876
|
Aktueller Wert: ${t}`}}});function qi(l){let e=l.trim();if(e.length<10)return{level:"low",matchedPatterns:[]};for(let s of Np)if(s.test(e))return{level:"low",matchedPatterns:[]};let t=[];for(let s of Mp)for(let r of s.patterns)if(r.test(e)){t.push(s.name);break}return t.length>0?{level:"high",matchedPatterns:t}:{level:"low",matchedPatterns:[]}}var Np,Mp,zi=_(()=>{"use strict";Np=[/^(what|where|when|who|why|how|which|can you|could you|do you|is there|are there|was |wer |wo |wann |warum |wie |welch|kannst du|könntest du|gibt es)/i,/^(hi|hey|hello|hallo|guten (morgen|tag|abend)|moin|servus|grüß|na\b|yo\b|sup\b|good (morning|evening|night))\b/i,/^(tell me|show me|find|search|help|explain|describe|translate|summarize|zeig|such|hilf|erklär|beschreib|übersetze|fass zusammen)/i,/^(ok|okay|yes|no|ja|nein|danke|thanks|thank you|sure|alright|klar|gut|cool|nice|great|perfect|genau|stimmt|richtig)\b/i],Mp=[{name:"fact:name",patterns:[/\b(my name is|i'm called|i am called|ich heiße|ich bin der|ich bin die|mein name ist)\b/i]},{name:"fact:location",patterns:[/\b(i live in|i'm from|i am from|ich wohne|ich lebe in|ich komme aus|ich bin aus)\b/i]},{name:"fact:work",patterns:[/\b(i work at|i work as|i work for|ich arbeite|mein job|mein beruf|ich bin .{0,20}(entwickler|ingenieur|lehrer|arzt|designer))\b/i]},{name:"fact:birthday",patterns:[/\b(my birthday|i was born|ich bin geboren|mein geburtstag|ich habe am .{1,15} geburtstag)\b/i]},{name:"fact:age",patterns:[/\b(i'm \d+ years|i am \d+ years|ich bin \d+ (jahre|jahr))\b/i]},{name:"preference:like",patterns:[/\b(i love|i really like|i enjoy|ich liebe|ich mag|mir gefällt|mir gefallen)\b/i]},{name:"preference:dislike",patterns:[/\b(i hate|i dislike|i can't stand|ich hasse|ich mag .{0,5} nicht|ich kann .{0,10} nicht leiden)\b/i]},{name:"preference:prefer",patterns:[/\b(i prefer|i'd rather|ich bevorzuge|ich nehme lieber|mir ist .{0,10} lieber)\b/i]},{name:"preference:favorite",patterns:[/\b(my fav|my favorite|my favourite|mein lieblings|meine lieblings|am liebsten)\b/i]},{name:"correction",patterns:[/\b(actually|actually,? (i|my|it)|eigentlich|das stimmt nicht|nein,? ich|that's not right|that's wrong|nicht ganz)\b/i]},{name:"relationship:family",patterns:[/\b(my wife|my husband|my partner|meine frau|mein mann|mein partner|meine partnerin|my daughter|my son|mein sohn|meine tochter|my kids|meine kinder|my mother|my father|meine mutter|mein vater)\b/i]},{name:"relationship:professional",patterns:[/\b(my boss|my manager|my colleague|mein chef|mein vorgesetzter|mein kollege|meine kollegin)\b/i]},{name:"relationship:social",patterns:[/\b(my friend|my best friend|mein freund|meine freundin|mein bester freund)\b/i]},{name:"fact:language",patterns:[/\b(i speak|ich spreche|my native|meine muttersprache)\b/i]},{name:"fact:education",patterns:[/\b(i studied|i went to|ich habe .{0,10} studiert|ich war auf der|mein studium)\b/i]},{name:"fact:hobby",patterns:[/\b(my hobby|i play .{0,10}(guitar|piano|football|tennis|chess)|mein hobby|ich spiele|in my free time|in meiner freizeit)\b/i]},{name:"decision",patterns:[/\b(i've decided|i decided|i will always|ich habe (mich )?entschieden|ich werde immer)\b/i]},{name:"commitment",patterns:[/\b(i always|i never|ich mache immer|ich mache nie|i'm trying to|ich versuche)\b/i]}];m(qi,"scanSignal")});var Op,Pp,Lr,Wi=_(()=>{"use strict";Op=["fact","preference","correction","entity","decision","relationship","principle","commitment","moment","skill"],Pp=`You are a memory extraction system. Analyze the user message and extract personal facts about the USER (not about what they're asking).
|