@madh-io/alfred-ai 0.9.8 → 0.9.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bundle/index.js +56 -54
  2. package/package.json +1 -1
package/bundle/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Ar=Object.defineProperty;var d=(c,e)=>Ar(c,"name",{value:e,configurable:!0});var f=(c,e)=>()=>(c&&(e=c(c=0)),e);var G=(c,e)=>{for(var t in e)Ar(c,t,{get:e[t],enumerable:!0})};import{z as g}from"zod";var Rr,Lr,Mr,Nr,Dr,Or,Cr,Ur,de,Xo,zo,qo,Ko,Vo,Go,Yo,Jo,Zo,Qo,ei,ti,si,xs,$s=f(()=>{"use strict";Rr=g.object({token:g.string().optional(),enabled:g.boolean()}),Lr=g.object({token:g.string().optional(),enabled:g.boolean()}),Mr=g.object({enabled:g.boolean(),dataPath:g.string()}),Nr=g.object({homeserverUrl:g.string(),accessToken:g.string().optional(),userId:g.string().optional(),enabled:g.boolean()}),Dr=g.object({apiUrl:g.string(),phoneNumber:g.string().optional(),enabled:g.boolean()}),Or=g.object({path:g.string()}),Cr=g.object({level:g.enum(["trace","debug","info","warn","error","fatal"]),pretty:g.boolean(),auditLogPath:g.string().optional()}),Ur=g.object({rulesPath:g.string(),defaultEffect:g.enum(["allow","deny"]),ownerUserId:g.string().optional()}),de=g.object({provider:g.enum(["anthropic","openai","openrouter","ollama","openwebui"]),apiKey:g.string().optional(),baseUrl:g.string().optional(),model:g.string(),temperature:g.number().optional(),maxTokens:g.number().optional()}),Xo=g.object({default:de,strong:de.optional(),fast:de.optional(),embeddings:de.optional(),local:de.optional()}),zo=g.union([de,Xo]),qo=g.object({provider:g.enum(["brave","searxng","tavily","duckduckgo"]),apiKey:g.string().optional(),baseUrl:g.string().optional()}),Ko=g.object({imap:g.object({host:g.string(),port:g.number(),secure:g.boolean()}),smtp:g.object({host:g.string(),port:g.number(),secure:g.boolean()}),auth:g.object({user:g.string(),pass:g.string()})}),Vo=g.object({provider:g.enum(["openai","groq"]),apiKey:g.string(),baseUrl:g.string().optional()}),Go=g.object({serverUrl:g.string(),username:g.string(),password:g.string()}),Yo=g.object({clientId:g.string(),clientSecret:g.string(),refreshToken:g.string()}),Jo=g.object({clientId:g.string(),clientSecret:g.string(),tenantId:g.string(),refreshToken:g.string()}),Zo=g.object({provider:g.enum(["caldav","google","microsoft"]),caldav:Go.optional(),google:Yo.optional(),microsoft:Jo.optional()}),Qo=g.object({name:g.string(),command:g.string().optional(),args:g.array(g.string()).optional(),env:g.record(g.string()).optional(),url:g.string().optional()}),ei=g.object({servers:g.array(Qo)}),ti=g.object({enabled:g.boolean(),allowedLanguages:g.array(g.enum(["javascript","python"])).optional(),maxTimeoutMs:g.number().optional(),allowNetwork:g.boolean().optional()}),si=g.object({enabled:g.boolean().optional(),minMessageLength:g.number().optional(),minConfidence:g.number().min(0).max(1).optional(),maxExtractionsPerMinute:g.number().optional()}),xs=g.object({name:g.string(),telegram:Rr,discord:Lr.optional(),whatsapp:Mr.optional(),matrix:Nr.optional(),signal:Dr.optional(),llm:zo,storage:Or,logger:Cr,security:Ur,search:qo.optional(),email:Ko.optional(),speech:Vo.optional(),calendar:Zo.optional(),mcp:ei.optional(),codeSandbox:ti.optional(),activeLearning:si.optional()})});var Is,As=f(()=>{"use strict";Is={name:"Alfred",telegram:{token:"",enabled:!1},discord:{token:"",enabled:!1},whatsapp:{enabled:!1,dataPath:"./data/whatsapp"},matrix:{homeserverUrl:"https://matrix.org",accessToken:"",userId:"",enabled:!1},signal:{apiUrl:"http://localhost:8080",phoneNumber:"",enabled:!1},llm:{provider:"anthropic",model:"claude-sonnet-4-20250514",temperature:.7,maxTokens:4096},storage:{path:"./data/alfred.db"},logger:{level:"info",pretty:!0},security:{rulesPath:"./config/rules",defaultEffect:"deny"}}});import Pr from"node:fs";import ri from"node:path";import{config as ni}from"dotenv";import oi from"js-yaml";function Fr(c,e){let t={...c};for(let s of Object.keys(e)){let r=e[s],n=t[s];r!=null&&typeof r=="object"&&!Array.isArray(r)&&n!==null&&n!==void 0&&typeof n=="object"&&!Array.isArray(n)?t[s]=Fr(n,r):t[s]=r}return t}function ai(c){let e={...c};for(let[t,s]of Object.entries(ii)){let r=process.env[t];if(r===void 0)continue;let n=e;for(let o=0;o<s.length-1;o++){let i=s[o];(n[i]===void 0||n[i]===null||typeof n[i]!="object")&&(n[i]={}),n[i]={...n[i]},n=n[i]}n[s[s.length-1]]=r}return e}var ii,q,jr=f(()=>{"use strict";$s();As();d(Fr,"deepMerge");ii={ALFRED_TELEGRAM_TOKEN:["telegram","token"],ALFRED_DISCORD_TOKEN:["discord","token"],ALFRED_MATRIX_HOMESERVER_URL:["matrix","homeserverUrl"],ALFRED_MATRIX_ACCESS_TOKEN:["matrix","accessToken"],ALFRED_MATRIX_USER_ID:["matrix","userId"],ALFRED_SIGNAL_API_URL:["signal","apiUrl"],ALFRED_SIGNAL_PHONE_NUMBER:["signal","phoneNumber"],ALFRED_ANTHROPIC_API_KEY:["llm","apiKey"],ALFRED_OPENAI_API_KEY:["llm","apiKey"],ALFRED_OPENROUTER_API_KEY:["llm","apiKey"],ALFRED_OPENWEBUI_API_KEY:["llm","apiKey"],ALFRED_LLM_PROVIDER:["llm","provider"],ALFRED_LLM_MODEL:["llm","model"],ALFRED_LLM_BASE_URL:["llm","baseUrl"],ALFRED_LLM_STRONG_PROVIDER:["llm","strong","provider"],ALFRED_LLM_STRONG_MODEL:["llm","strong","model"],ALFRED_LLM_STRONG_API_KEY:["llm","strong","apiKey"],ALFRED_LLM_FAST_PROVIDER:["llm","fast","provider"],ALFRED_LLM_FAST_MODEL:["llm","fast","model"],ALFRED_LLM_FAST_API_KEY:["llm","fast","apiKey"],ALFRED_LLM_EMBEDDINGS_PROVIDER:["llm","embeddings","provider"],ALFRED_LLM_EMBEDDINGS_MODEL:["llm","embeddings","model"],ALFRED_LLM_EMBEDDINGS_API_KEY:["llm","embeddings","apiKey"],ALFRED_LLM_LOCAL_PROVIDER:["llm","local","provider"],ALFRED_LLM_LOCAL_MODEL:["llm","local","model"],ALFRED_LLM_LOCAL_BASE_URL:["llm","local","baseUrl"],ALFRED_STORAGE_PATH:["storage","path"],ALFRED_LOG_LEVEL:["logger","level"],ALFRED_OWNER_USER_ID:["security","ownerUserId"],ALFRED_SEARCH_PROVIDER:["search","provider"],ALFRED_SEARCH_API_KEY:["search","apiKey"],ALFRED_SEARCH_BASE_URL:["search","baseUrl"],ALFRED_EMAIL_USER:["email","auth","user"],ALFRED_EMAIL_PASS:["email","auth","pass"],ALFRED_SPEECH_PROVIDER:["speech","provider"],ALFRED_SPEECH_API_KEY:["speech","apiKey"],ALFRED_SPEECH_BASE_URL:["speech","baseUrl"],ALFRED_CALENDAR_PROVIDER:["calendar","provider"],ALFRED_CALDAV_SERVER_URL:["calendar","caldav","serverUrl"],ALFRED_CALDAV_USERNAME:["calendar","caldav","username"],ALFRED_CALDAV_PASSWORD:["calendar","caldav","password"],ALFRED_GOOGLE_CALENDAR_CLIENT_ID:["calendar","google","clientId"],ALFRED_GOOGLE_CALENDAR_CLIENT_SECRET:["calendar","google","clientSecret"],ALFRED_GOOGLE_CALENDAR_REFRESH_TOKEN:["calendar","google","refreshToken"],ALFRED_MICROSOFT_CALENDAR_CLIENT_ID:["calendar","microsoft","clientId"],ALFRED_MICROSOFT_CALENDAR_CLIENT_SECRET:["calendar","microsoft","clientSecret"],ALFRED_MICROSOFT_CALENDAR_TENANT_ID:["calendar","microsoft","tenantId"],ALFRED_MICROSOFT_CALENDAR_REFRESH_TOKEN:["calendar","microsoft","refreshToken"]};d(ai,"applyEnvOverrides");q=class{static{d(this,"ConfigLoader")}loadConfig(e){ni();let t=e??process.env.ALFRED_CONFIG_PATH??"./config/default.yml",s={},r=ri.resolve(t);if(Pr.existsSync(r)){let l=Pr.readFileSync(r,"utf-8"),u=oi.load(l);u&&typeof u=="object"&&(s=u)}let n=Fr(Is,s),o=ai(n),i=xs.parse(o),a=i.llm;return a&&"provider"in a&&(i.llm={default:a}),i}}});var ue=f(()=>{"use strict";$s();As();jr()});import Rs from"pino";function ot(c,e){let t=e??process.env.LOG_LEVEL??"info";if(t==="debug"||t==="trace"||process.env.NODE_ENV!=="production"){let r=Rs.transport({target:"pino-pretty",options:{colorize:!0}});return Rs({name:c,level:t},r)}return Rs({name:c,level:t})}var Br=f(()=>{"use strict";d(ot,"createLogger")});import Ja from"pino";var Wr=f(()=>{"use strict"});var Ls=f(()=>{"use strict";Br();Wr()});var $e,Qt=f(()=>{"use strict";$e=class{static{d(this,"Migrator")}db;constructor(e){this.db=e,this.ensureMigrationsTable()}ensureMigrationsTable(){this.db.exec(`
2
+ var Ar=Object.defineProperty;var d=(c,e)=>Ar(c,"name",{value:e,configurable:!0});var f=(c,e)=>()=>(c&&(e=c(c=0)),e);var G=(c,e)=>{for(var t in e)Ar(c,t,{get:e[t],enumerable:!0})};import{z as g}from"zod";var Rr,Lr,Mr,Nr,Dr,Or,Cr,Ur,de,Xo,zo,qo,Ko,Vo,Go,Yo,Jo,Zo,Qo,ei,ti,si,xs,$s=f(()=>{"use strict";Rr=g.object({token:g.string().optional(),enabled:g.boolean()}),Lr=g.object({token:g.string().optional(),enabled:g.boolean()}),Mr=g.object({enabled:g.boolean(),dataPath:g.string()}),Nr=g.object({homeserverUrl:g.string(),accessToken:g.string().optional(),userId:g.string().optional(),enabled:g.boolean()}),Dr=g.object({apiUrl:g.string(),phoneNumber:g.string().optional(),enabled:g.boolean()}),Or=g.object({path:g.string()}),Cr=g.object({level:g.enum(["trace","debug","info","warn","error","fatal"]),pretty:g.boolean(),auditLogPath:g.string().optional()}),Ur=g.object({rulesPath:g.string(),defaultEffect:g.enum(["allow","deny"]),ownerUserId:g.string().optional()}),de=g.object({provider:g.enum(["anthropic","openai","openrouter","ollama","openwebui"]),apiKey:g.string().optional(),baseUrl:g.string().optional(),model:g.string(),temperature:g.number().optional(),maxTokens:g.number().optional()}),Xo=g.object({default:de,strong:de.optional(),fast:de.optional(),embeddings:de.optional(),local:de.optional()}),zo=g.union([de,Xo]),qo=g.object({provider:g.enum(["brave","searxng","tavily","duckduckgo"]),apiKey:g.string().optional(),baseUrl:g.string().optional()}),Ko=g.object({imap:g.object({host:g.string(),port:g.number(),secure:g.boolean()}),smtp:g.object({host:g.string(),port:g.number(),secure:g.boolean()}),auth:g.object({user:g.string(),pass:g.string()})}),Vo=g.object({provider:g.enum(["openai","groq"]),apiKey:g.string(),baseUrl:g.string().optional()}),Go=g.object({serverUrl:g.string(),username:g.string(),password:g.string()}),Yo=g.object({clientId:g.string(),clientSecret:g.string(),refreshToken:g.string()}),Jo=g.object({clientId:g.string(),clientSecret:g.string(),tenantId:g.string(),refreshToken:g.string()}),Zo=g.object({provider:g.enum(["caldav","google","microsoft"]),caldav:Go.optional(),google:Yo.optional(),microsoft:Jo.optional()}),Qo=g.object({name:g.string(),command:g.string().optional(),args:g.array(g.string()).optional(),env:g.record(g.string()).optional(),url:g.string().optional()}),ei=g.object({servers:g.array(Qo)}),ti=g.object({enabled:g.boolean(),allowedLanguages:g.array(g.enum(["javascript","python"])).optional(),maxTimeoutMs:g.number().optional(),allowNetwork:g.boolean().optional()}),si=g.object({enabled:g.boolean().optional(),minMessageLength:g.number().optional(),minConfidence:g.number().min(0).max(1).optional(),maxExtractionsPerMinute:g.number().optional()}),xs=g.object({name:g.string(),telegram:Rr,discord:Lr.optional(),whatsapp:Mr.optional(),matrix:Nr.optional(),signal:Dr.optional(),llm:zo,storage:Or,logger:Cr,security:Ur,search:qo.optional(),email:Ko.optional(),speech:Vo.optional(),calendar:Zo.optional(),mcp:ei.optional(),codeSandbox:ti.optional(),activeLearning:si.optional()})});var Is,As=f(()=>{"use strict";Is={name:"Alfred",telegram:{token:"",enabled:!1},discord:{token:"",enabled:!1},whatsapp:{enabled:!1,dataPath:"./data/whatsapp"},matrix:{homeserverUrl:"https://matrix.org",accessToken:"",userId:"",enabled:!1},signal:{apiUrl:"http://localhost:8080",phoneNumber:"",enabled:!1},llm:{provider:"anthropic",model:"claude-sonnet-4-20250514",temperature:.7,maxTokens:4096},storage:{path:"./data/alfred.db"},logger:{level:"info",pretty:!0},security:{rulesPath:"./config/rules",defaultEffect:"deny"}}});import Pr from"node:fs";import ri from"node:path";import{config as ni}from"dotenv";import oi from"js-yaml";function Fr(c,e){let t={...c};for(let s of Object.keys(e)){let r=e[s],n=t[s];r!=null&&typeof r=="object"&&!Array.isArray(r)&&n!==null&&n!==void 0&&typeof n=="object"&&!Array.isArray(n)?t[s]=Fr(n,r):t[s]=r}return t}function ai(c){let e={...c};for(let[t,s]of Object.entries(ii)){let r=process.env[t];if(r===void 0)continue;let n=e;for(let o=0;o<s.length-1;o++){let i=s[o];(n[i]===void 0||n[i]===null||typeof n[i]!="object")&&(n[i]={}),n[i]={...n[i]},n=n[i]}n[s[s.length-1]]=r}return e}var ii,z,jr=f(()=>{"use strict";$s();As();d(Fr,"deepMerge");ii={ALFRED_TELEGRAM_TOKEN:["telegram","token"],ALFRED_DISCORD_TOKEN:["discord","token"],ALFRED_MATRIX_HOMESERVER_URL:["matrix","homeserverUrl"],ALFRED_MATRIX_ACCESS_TOKEN:["matrix","accessToken"],ALFRED_MATRIX_USER_ID:["matrix","userId"],ALFRED_SIGNAL_API_URL:["signal","apiUrl"],ALFRED_SIGNAL_PHONE_NUMBER:["signal","phoneNumber"],ALFRED_ANTHROPIC_API_KEY:["llm","apiKey"],ALFRED_OPENAI_API_KEY:["llm","apiKey"],ALFRED_OPENROUTER_API_KEY:["llm","apiKey"],ALFRED_OPENWEBUI_API_KEY:["llm","apiKey"],ALFRED_LLM_PROVIDER:["llm","provider"],ALFRED_LLM_MODEL:["llm","model"],ALFRED_LLM_BASE_URL:["llm","baseUrl"],ALFRED_LLM_STRONG_PROVIDER:["llm","strong","provider"],ALFRED_LLM_STRONG_MODEL:["llm","strong","model"],ALFRED_LLM_STRONG_API_KEY:["llm","strong","apiKey"],ALFRED_LLM_FAST_PROVIDER:["llm","fast","provider"],ALFRED_LLM_FAST_MODEL:["llm","fast","model"],ALFRED_LLM_FAST_API_KEY:["llm","fast","apiKey"],ALFRED_LLM_EMBEDDINGS_PROVIDER:["llm","embeddings","provider"],ALFRED_LLM_EMBEDDINGS_MODEL:["llm","embeddings","model"],ALFRED_LLM_EMBEDDINGS_API_KEY:["llm","embeddings","apiKey"],ALFRED_LLM_LOCAL_PROVIDER:["llm","local","provider"],ALFRED_LLM_LOCAL_MODEL:["llm","local","model"],ALFRED_LLM_LOCAL_BASE_URL:["llm","local","baseUrl"],ALFRED_STORAGE_PATH:["storage","path"],ALFRED_LOG_LEVEL:["logger","level"],ALFRED_OWNER_USER_ID:["security","ownerUserId"],ALFRED_SEARCH_PROVIDER:["search","provider"],ALFRED_SEARCH_API_KEY:["search","apiKey"],ALFRED_SEARCH_BASE_URL:["search","baseUrl"],ALFRED_EMAIL_USER:["email","auth","user"],ALFRED_EMAIL_PASS:["email","auth","pass"],ALFRED_SPEECH_PROVIDER:["speech","provider"],ALFRED_SPEECH_API_KEY:["speech","apiKey"],ALFRED_SPEECH_BASE_URL:["speech","baseUrl"],ALFRED_CALENDAR_PROVIDER:["calendar","provider"],ALFRED_CALDAV_SERVER_URL:["calendar","caldav","serverUrl"],ALFRED_CALDAV_USERNAME:["calendar","caldav","username"],ALFRED_CALDAV_PASSWORD:["calendar","caldav","password"],ALFRED_GOOGLE_CALENDAR_CLIENT_ID:["calendar","google","clientId"],ALFRED_GOOGLE_CALENDAR_CLIENT_SECRET:["calendar","google","clientSecret"],ALFRED_GOOGLE_CALENDAR_REFRESH_TOKEN:["calendar","google","refreshToken"],ALFRED_MICROSOFT_CALENDAR_CLIENT_ID:["calendar","microsoft","clientId"],ALFRED_MICROSOFT_CALENDAR_CLIENT_SECRET:["calendar","microsoft","clientSecret"],ALFRED_MICROSOFT_CALENDAR_TENANT_ID:["calendar","microsoft","tenantId"],ALFRED_MICROSOFT_CALENDAR_REFRESH_TOKEN:["calendar","microsoft","refreshToken"]};d(ai,"applyEnvOverrides");z=class{static{d(this,"ConfigLoader")}loadConfig(e){ni();let t=e??process.env.ALFRED_CONFIG_PATH??"./config/default.yml",s={},r=ri.resolve(t);if(Pr.existsSync(r)){let l=Pr.readFileSync(r,"utf-8"),u=oi.load(l);u&&typeof u=="object"&&(s=u)}let n=Fr(Is,s),o=ai(n),i=xs.parse(o),a=i.llm;return a&&"provider"in a&&(i.llm={default:a}),i}}});var ue=f(()=>{"use strict";$s();As();jr()});import Rs from"pino";function ot(c,e){let t=e??process.env.LOG_LEVEL??"info";if(t==="debug"||t==="trace"||process.env.NODE_ENV!=="production"){let r=Rs.transport({target:"pino-pretty",options:{colorize:!0}});return Rs({name:c,level:t},r)}return Rs({name:c,level:t})}var Br=f(()=>{"use strict";d(ot,"createLogger")});import Ja from"pino";var Wr=f(()=>{"use strict"});var Ls=f(()=>{"use strict";Br();Wr()});var $e,Qt=f(()=>{"use strict";$e=class{static{d(this,"Migrator")}db;constructor(e){this.db=e,this.ensureMigrationsTable()}ensureMigrationsTable(){this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS _migrations (
4
4
  version INTEGER PRIMARY KEY,
5
5
  description TEXT,
@@ -252,16 +252,18 @@ var Ar=Object.defineProperty;var d=(c,e)=>Ar(c,"name",{value:e,configurable:!0})
252
252
  SET last_run_at = ?, next_run_at = ?
253
253
  WHERE id = ?
254
254
  `).run(t,s,e)}setEnabled(e,t){return this.db.prepare("UPDATE scheduled_actions SET enabled = ? WHERE id = ?").run(t?1:0,e).changes>0}delete(e){return this.db.prepare("DELETE FROM scheduled_actions WHERE id = ?").run(e).changes>0}calculateInitialNextRun(e,t){let s=new Date;switch(e){case"interval":{let r=parseInt(t,10);return isNaN(r)||r<=0?null:new Date(s.getTime()+r*6e4).toISOString()}case"once":return new Date(t).toISOString();case"cron":return this.getNextCronDate(t,s)?.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}mapRow(e){return{id:e.id,userId:e.user_id,platform:e.platform,chatId:e.chat_id,name:e.name,description:e.description,scheduleType:e.schedule_type,scheduleValue:e.schedule_value,skillName:e.skill_name,skillInput:e.skill_input,promptTemplate:e.prompt_template,enabled:e.enabled===1,lastRunAt:e.last_run_at,nextRunAt:e.next_run_at,createdAt:e.created_at}}}});import{randomUUID as tn}from"node:crypto";var ft,sn=f(()=>{"use strict";ft=class{static{d(this,"DocumentRepository")}db;constructor(e){this.db=e}createDocument(e,t,s,r){let n=tn(),o=new Date().toISOString();return this.db.prepare("INSERT INTO documents (id, user_id, filename, mime_type, size_bytes, chunk_count, created_at) VALUES (?, ?, ?, ?, ?, 0, ?)").run(n,e,t,s,r,o),{id:n,userId:e,filename:t,mimeType:s,sizeBytes:r,chunkCount:0,createdAt:o}}updateChunkCount(e,t){this.db.prepare("UPDATE documents SET chunk_count = ? WHERE id = ?").run(t,e)}addChunk(e,t,s,r){let n=tn(),o=new Date().toISOString();return this.db.prepare("INSERT INTO document_chunks (id, document_id, chunk_index, content, embedding_id, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(n,e,t,s,r??null,o),{id:n,documentId:e,chunkIndex:t,content:s,embeddingId:r,createdAt:o}}getDocument(e){let t=this.db.prepare("SELECT * FROM documents WHERE id = ?").get(e);return t?this.mapDocumentRow(t):void 0}getChunks(e){return this.db.prepare("SELECT * FROM document_chunks WHERE document_id = ? ORDER BY chunk_index ASC").all(e).map(s=>this.mapChunkRow(s))}listByUser(e){return this.db.prepare("SELECT * FROM documents WHERE user_id = ? ORDER BY created_at DESC").all(e).map(s=>this.mapDocumentRow(s))}deleteDocument(e){this.db.transaction(()=>{let s=this.db.prepare("SELECT embedding_id FROM document_chunks WHERE document_id = ? AND embedding_id IS NOT NULL").all(e);if(s.length>0){let r=s.map(o=>o.embedding_id),n=r.map(()=>"?").join(", ");this.db.prepare(`DELETE FROM embeddings WHERE key IN (${n})`).run(...r)}this.db.prepare("DELETE FROM document_chunks WHERE document_id = ?").run(e),this.db.prepare("DELETE FROM documents WHERE id = ?").run(e)})()}getChunksByEmbeddingIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(", ");return this.db.prepare(`SELECT * FROM document_chunks WHERE embedding_id IN (${t}) ORDER BY chunk_index ASC`).all(...e).map(r=>this.mapChunkRow(r))}mapDocumentRow(e){return{id:e.id,userId:e.user_id,filename:e.filename,mimeType:e.mime_type,sizeBytes:e.size_bytes,chunkCount:e.chunk_count,createdAt:e.created_at}}mapChunkRow(e){return{id:e.id,documentId:e.document_id,chunkIndex:e.chunk_index,content:e.content,embeddingId:e.embedding_id||void 0,createdAt:e.created_at}}}});var Ds=f(()=>{"use strict";Hr();zr();qr();Kr();Vr();Qt();Ns();Gr();Yr();Jr();Zr();Qr();en();sn()});function he(c){if(Os[c])return Os[c];for(let[e,t]of Object.entries(Os))if(c.startsWith(e))return t}var Os,Ei,Y,Ie=f(()=>{"use strict";Os={"claude-opus-4-20250514":{maxInputTokens:2e5,maxOutputTokens:32e3},"claude-sonnet-4-20250514":{maxInputTokens:2e5,maxOutputTokens:16e3},"claude-haiku-3-5-20241022":{maxInputTokens:2e5,maxOutputTokens:8192},"gpt-4o":{maxInputTokens:128e3,maxOutputTokens:16384},"gpt-4o-mini":{maxInputTokens:128e3,maxOutputTokens:16384},"gpt-4-turbo":{maxInputTokens:128e3,maxOutputTokens:4096},"gpt-4":{maxInputTokens:8192,maxOutputTokens:4096},"gpt-3.5-turbo":{maxInputTokens:16384,maxOutputTokens:4096},o1:{maxInputTokens:2e5,maxOutputTokens:1e5},"o1-mini":{maxInputTokens:128e3,maxOutputTokens:65536},"o3-mini":{maxInputTokens:2e5,maxOutputTokens:1e5},"llama3.2":{maxInputTokens:128e3,maxOutputTokens:4096},"llama3.1":{maxInputTokens:128e3,maxOutputTokens:4096},llama3:{maxInputTokens:8192,maxOutputTokens:4096},mistral:{maxInputTokens:32e3,maxOutputTokens:4096},"mistral-small":{maxInputTokens:32e3,maxOutputTokens:4096},mixtral:{maxInputTokens:32e3,maxOutputTokens:4096},gemma2:{maxInputTokens:8192,maxOutputTokens:4096},"qwen2.5":{maxInputTokens:128e3,maxOutputTokens:4096},phi3:{maxInputTokens:128e3,maxOutputTokens:4096},"deepseek-r1":{maxInputTokens:128e3,maxOutputTokens:8192},"command-r":{maxInputTokens:128e3,maxOutputTokens:4096}},Ei={maxInputTokens:8192,maxOutputTokens:4096};d(he,"lookupContextWindow");Y=class{static{d(this,"LLMProvider")}config;contextWindow=Ei;constructor(e){this.config=e}getContextWindow(){return this.contextWindow}async embed(e){}supportsEmbeddings(){return!1}}});import Ti from"@anthropic-ai/sdk";var gt,Cs=f(()=>{"use strict";Ie();gt=class extends Y{static{d(this,"AnthropicProvider")}client;constructor(e){super(e)}async initialize(){this.client=new Ti({apiKey:this.config.apiKey});let e=he(this.config.model);e&&(this.contextWindow=e)}async complete(e){let t=this.mapMessages(e.messages),s=e.tools?this.mapTools(e.tools):void 0,r={model:this.config.model,max_tokens:e.maxTokens??this.config.maxTokens??4096,temperature:e.temperature??this.config.temperature,system:e.system,messages:t,tools:s},n=await this.client.messages.create(r);return this.mapResponse(n)}async*stream(e){let t=this.mapMessages(e.messages),s=e.tools?this.mapTools(e.tools):void 0,r=this.client.messages.stream({model:this.config.model,max_tokens:e.maxTokens??this.config.maxTokens??4096,temperature:e.temperature??this.config.temperature,system:e.system,messages:t,tools:s});for await(let n of r)if(n.type==="content_block_delta")n.delta.type==="text_delta"?yield{type:"text_delta",text:n.delta.text}:n.delta.type==="input_json_delta"&&(yield{type:"tool_use_delta",toolCall:{input:n.delta.partial_json}});else if(n.type==="content_block_start")n.content_block.type==="tool_use"&&(yield{type:"tool_use_start",toolCall:{id:n.content_block.id,name:n.content_block.name}});else if(n.type==="message_stop"){let o=await r.finalMessage();yield{type:"message_complete",response:this.mapResponse(o)}}}isAvailable(){return!!this.config.apiKey}mapMessages(e){return e.map(t=>{if(typeof t.content=="string")return{role:t.role,content:t.content};let s=t.content.map(r=>{switch(r.type){case"text":return{type:"text",text:r.text};case"image":return{type:"image",source:{type:"base64",media_type:r.source.media_type,data:r.source.data}};case"tool_use":return{type:"tool_use",id:r.id,name:r.name,input:r.input};case"tool_result":return{type:"tool_result",tool_use_id:r.tool_use_id,content:r.content,is_error:r.is_error}}});return{role:t.role,content:s}})}mapTools(e){return e.map(t=>({name:t.name,description:t.description,input_schema:t.inputSchema}))}mapResponse(e){let t="",s=[];for(let r of e.content)r.type==="text"?t+=r.text:r.type==="tool_use"&&s.push({id:r.id,name:r.name,input:r.input});return{content:t,toolCalls:s.length>0?s:void 0,usage:{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens},stopReason:e.stop_reason}}}});import bi from"openai";var se,yt=f(()=>{"use strict";Ie();se=class extends Y{static{d(this,"OpenAIProvider")}client;constructor(e){super(e)}async initialize(){this.client=new bi({apiKey:this.config.apiKey,baseURL:this.config.baseUrl});let e=he(this.config.model);e&&(this.contextWindow=e)}async complete(e){let t=this.mapMessages(e.messages,e.system),s=e.tools?this.mapTools(e.tools):void 0,r={model:this.config.model,max_tokens:e.maxTokens??this.config.maxTokens??4096,temperature:e.temperature??this.config.temperature,messages:t,...s?{tools:s}:{}},n=await this.client.chat.completions.create(r);return this.mapResponse(n)}async*stream(e){let t=this.mapMessages(e.messages,e.system),s=e.tools?this.mapTools(e.tools):void 0,r=await this.client.chat.completions.create({model:this.config.model,max_tokens:e.maxTokens??this.config.maxTokens??4096,temperature:e.temperature??this.config.temperature,messages:t,...s?{tools:s}:{},stream:!0}),n,o,i="",a="",l=[],u=null,p=0,m=0;for await(let h of r){let w=h.choices[0];if(!w)continue;let E=w.delta;if(E?.content&&(a+=E.content,yield{type:"text_delta",text:E.content}),E?.tool_calls)for(let T of E.tool_calls)T.id?(n&&l.push({id:n,name:o,input:JSON.parse(i||"{}")}),n=T.id,o=T.function?.name,i=T.function?.arguments??"",yield{type:"tool_use_start",toolCall:{id:n,name:o}}):T.function?.arguments&&(i+=T.function.arguments,yield{type:"tool_use_delta",toolCall:{input:T.function.arguments}});w.finish_reason&&(u=w.finish_reason),h.usage&&(p=h.usage.prompt_tokens,m=h.usage.completion_tokens)}n&&l.push({id:n,name:o,input:JSON.parse(i||"{}")}),yield{type:"message_complete",response:{content:a,toolCalls:l.length>0?l:void 0,usage:{inputTokens:p,outputTokens:m},stopReason:this.mapStopReason(u)}}}isAvailable(){return!!this.config.apiKey}async embed(e){try{let s=(await this.client.embeddings.create({model:"text-embedding-3-small",input:e})).data[0];return{embedding:s.embedding,model:"text-embedding-3-small",dimensions:s.embedding.length}}catch{return}}supportsEmbeddings(){return!0}mapMessages(e,t){let s=[];t&&s.push({role:"system",content:t});for(let r of e){if(typeof r.content=="string"){s.push({role:r.role,content:r.content});continue}let n=[],o=[],i=[];for(let a of r.content)switch(a.type){case"text":n.push({type:"text",text:a.text});break;case"image":n.push({type:"image_url",image_url:{url:`data:${a.source.media_type};base64,${a.source.data}`}});break;case"tool_use":o.push({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}});break;case"tool_result":i.push({tool_call_id:a.tool_use_id,content:a.content});break}if(r.role==="assistant"&&o.length>0){let a=n.map(l=>l.text).join("");s.push({role:"assistant",content:a||null,tool_calls:o})}else if(i.length>0)for(let a of i)s.push({role:"tool",tool_call_id:a.tool_call_id,content:a.content});else n.length>0&&(r.role==="user"?s.push({role:"user",content:n}):s.push({role:r.role,content:n.map(a=>a.text).join("")}))}return s}mapTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}))}mapResponse(e){let t=e.choices[0],s=t?.message,r=s?.content??"",n=s?.tool_calls?.map(o=>({id:o.id,name:o.function.name,input:(()=>{try{return JSON.parse(o.function.arguments)}catch{return{}}})()}));return{content:r,toolCalls:n&&n.length>0?n:void 0,usage:{inputTokens:e.usage?.prompt_tokens??0,outputTokens:e.usage?.completion_tokens??0},stopReason:this.mapStopReason(t?.finish_reason??null)}}mapStopReason(e){switch(e){case"stop":return"end_turn";case"tool_calls":return"tool_use";case"length":return"max_tokens";default:return"end_turn"}}}});var wt,Us=f(()=>{"use strict";yt();wt=class extends se{static{d(this,"OpenRouterProvider")}constructor(e){super({...e,baseUrl:e.baseUrl??"https://openrouter.ai/api/v1"})}isAvailable(){return!!this.config.apiKey}supportsEmbeddings(){return!1}}});var Et,Ps=f(()=>{"use strict";Ie();Et=class extends Y{static{d(this,"OllamaProvider")}baseUrl="";constructor(e){super(e)}apiKey="";async initialize(){let e=this.config.baseUrl??"http://localhost:11434";this.baseUrl=e.replace(/\/v1\/?$/,"").replace(/\/+$/,""),this.apiKey=this.config.apiKey??"";let t=he(this.config.model);t?this.contextWindow=t:await this.fetchModelContextWindow()}async fetchModelContextWindow(){try{let e=await fetch(`${this.baseUrl}/api/show`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:this.config.model})});if(!e.ok)return;let s=(await e.json()).model_info??{},r=Object.keys(s).find(o=>o.includes("context_length")||o==="num_ctx"),n=r?Number(s[r]):0;n>0&&(this.contextWindow={maxInputTokens:n,maxOutputTokens:Math.min(n,4096)})}catch{}}getHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}async complete(e){let t=this.buildMessages(e.messages,e.system),s=e.tools?this.mapTools(e.tools):void 0,r={model:this.config.model,messages:t,stream:!1,options:this.buildOptions(e)};s&&s.length>0&&(r.tools=s);let n=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(r)});if(!n.ok){let i=await n.text();throw new Error(`Ollama API error (${n.status}): ${i}`)}let o=await n.json();return this.mapResponse(o)}async*stream(e){let t=this.buildMessages(e.messages,e.system),s=e.tools?this.mapTools(e.tools):void 0,r={model:this.config.model,messages:t,stream:!0,options:this.buildOptions(e)};s&&s.length>0&&(r.tools=s);let n=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(r)});if(!n.ok){let h=await n.text();throw new Error(`Ollama API error (${n.status}): ${h}`)}if(!n.body)throw new Error("Ollama streaming response has no body");let o=n.body.getReader(),i=new TextDecoder,a="",l="",u=0,p=0,m=[];try{for(;;){let{done:h,value:w}=await o.read();if(h)break;a+=i.decode(w,{stream:!0});let E=a.split(`
255
- `);a=E.pop()??"";for(let T of E){let k=T.trim();if(!k)continue;let _;try{_=JSON.parse(k)}catch{continue}if(_.message?.content&&(l+=_.message.content,yield{type:"text_delta",text:_.message.content}),_.message?.tool_calls)for(let v of _.message.tool_calls){let M={id:`ollama_tool_${m.length}`,name:v.function.name,input:v.function.arguments};m.push(M),yield{type:"tool_use_start",toolCall:{id:M.id,name:M.name}},yield{type:"tool_use_delta",toolCall:{input:M.input}}}_.done&&(u=_.prompt_eval_count??0,p=_.eval_count??0,yield{type:"message_complete",response:{content:l,toolCalls:m.length>0?m:void 0,usage:{inputTokens:u,outputTokens:p},stopReason:m.length>0?"tool_use":"end_turn"}})}}if(a.trim()){let h;try{h=JSON.parse(a.trim())}catch{return}if(h.message?.content&&(l+=h.message.content,yield{type:"text_delta",text:h.message.content}),h.message?.tool_calls)for(let w of h.message.tool_calls){let E={id:`ollama_tool_${m.length}`,name:w.function.name,input:w.function.arguments};m.push(E),yield{type:"tool_use_start",toolCall:{id:E.id,name:E.name}},yield{type:"tool_use_delta",toolCall:{input:E.input}}}h.done&&(u=h.prompt_eval_count??0,p=h.eval_count??0,yield{type:"message_complete",response:{content:l,toolCalls:m.length>0?m:void 0,usage:{inputTokens:u,outputTokens:p},stopReason:m.length>0?"tool_use":"end_turn"}})}}finally{o.releaseLock()}}isAvailable(){try{return this.baseUrl.length>0}catch{return!1}}async embed(e){try{let t=await fetch(`${this.baseUrl}/api/embed`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:"nomic-embed-text",input:e})});if(!t.ok)return;let s=await t.json();if(!s.embeddings||s.embeddings.length===0)return;let r=s.embeddings[0];return{embedding:r,model:"nomic-embed-text",dimensions:r.length}}catch{return}}supportsEmbeddings(){return!0}buildOptions(e){let t={},s=e.temperature??this.config.temperature;s!==void 0&&(t.temperature=s);let r=e.maxTokens??this.config.maxTokens;return r!==void 0&&(t.num_predict=r),t}buildMessages(e,t){let s=[];t&&s.push({role:"system",content:t});for(let r of e)typeof r.content=="string"?s.push({role:r.role,content:r.content}):s.push(this.mapContentBlocks(r.role,r.content));return s}mapContentBlocks(e,t){let s=[],r=[];for(let o of t)switch(o.type){case"text":s.push(o.text);break;case"image":r.push(o.source.data);break;case"tool_use":s.push(`[Tool call: ${o.name}(${JSON.stringify(o.input)})]`);break;case"tool_result":s.push(`[Tool result for ${o.tool_use_id}]: ${o.content}`);break}let n={role:e,content:s.join(`
255
+ `);a=E.pop()??"";for(let T of E){let k=T.trim();if(!k)continue;let v;try{v=JSON.parse(k)}catch{continue}if(v.message?.content&&(l+=v.message.content,yield{type:"text_delta",text:v.message.content}),v.message?.tool_calls)for(let b of v.message.tool_calls){let A={id:`ollama_tool_${m.length}`,name:b.function.name,input:b.function.arguments};m.push(A),yield{type:"tool_use_start",toolCall:{id:A.id,name:A.name}},yield{type:"tool_use_delta",toolCall:{input:A.input}}}v.done&&(u=v.prompt_eval_count??0,p=v.eval_count??0,yield{type:"message_complete",response:{content:l,toolCalls:m.length>0?m:void 0,usage:{inputTokens:u,outputTokens:p},stopReason:m.length>0?"tool_use":"end_turn"}})}}if(a.trim()){let h;try{h=JSON.parse(a.trim())}catch{return}if(h.message?.content&&(l+=h.message.content,yield{type:"text_delta",text:h.message.content}),h.message?.tool_calls)for(let w of h.message.tool_calls){let E={id:`ollama_tool_${m.length}`,name:w.function.name,input:w.function.arguments};m.push(E),yield{type:"tool_use_start",toolCall:{id:E.id,name:E.name}},yield{type:"tool_use_delta",toolCall:{input:E.input}}}h.done&&(u=h.prompt_eval_count??0,p=h.eval_count??0,yield{type:"message_complete",response:{content:l,toolCalls:m.length>0?m:void 0,usage:{inputTokens:u,outputTokens:p},stopReason:m.length>0?"tool_use":"end_turn"}})}}finally{o.releaseLock()}}isAvailable(){try{return this.baseUrl.length>0}catch{return!1}}async embed(e){try{let t=await fetch(`${this.baseUrl}/api/embed`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:"nomic-embed-text",input:e})});if(!t.ok)return;let s=await t.json();if(!s.embeddings||s.embeddings.length===0)return;let r=s.embeddings[0];return{embedding:r,model:"nomic-embed-text",dimensions:r.length}}catch{return}}supportsEmbeddings(){return!0}buildOptions(e){let t={},s=e.temperature??this.config.temperature;s!==void 0&&(t.temperature=s);let r=e.maxTokens??this.config.maxTokens;return r!==void 0&&(t.num_predict=r),t}buildMessages(e,t){let s=[];t&&s.push({role:"system",content:t});for(let r of e)typeof r.content=="string"?s.push({role:r.role,content:r.content}):s.push(this.mapContentBlocks(r.role,r.content));return s}mapContentBlocks(e,t){let s=[],r=[];for(let o of t)switch(o.type){case"text":s.push(o.text);break;case"image":r.push(o.source.data);break;case"tool_use":s.push(`[Tool call: ${o.name}(${JSON.stringify(o.input)})]`);break;case"tool_result":s.push(`[Tool result for ${o.tool_use_id}]: ${o.content}`);break}let n={role:e,content:s.join(`
256
256
  `)};return r.length>0&&(n.images=r),n}mapTools(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}))}mapResponse(e){let t=[];if(e.message.tool_calls)for(let s of e.message.tool_calls)t.push({id:`ollama_tool_${t.length}`,name:s.function.name,input:s.function.arguments});return{content:e.message.content,toolCalls:t.length>0?t:void 0,usage:{inputTokens:e.prompt_eval_count??0,outputTokens:e.eval_count??0},stopReason:t.length>0?"tool_use":"end_turn"}}}});var Tt,Fs=f(()=>{"use strict";yt();Tt=class extends se{static{d(this,"OpenWebUIProvider")}constructor(e){super({...e,apiKey:e.apiKey||"openwebui",baseUrl:e.baseUrl??"http://localhost:3000/api/v1"})}isAvailable(){return!0}supportsEmbeddings(){return!1}}});function js(c){switch(c.provider){case"anthropic":return new gt(c);case"openai":return new se(c);case"openrouter":return new wt(c);case"ollama":return new Et(c);case"openwebui":return new Tt(c);default:throw new Error(`Unknown LLM provider: ${c.provider}`)}}var Bs=f(()=>{"use strict";Cs();yt();Us();Ps();Fs();d(js,"createLLMProvider")});function Ws(c){return new es(c)}var _i,es,rn=f(()=>{"use strict";Ie();Bs();_i=["default","strong","fast","embeddings","local"],es=class extends Y{static{d(this,"ModelRouter")}providers=new Map;multiConfig;constructor(e){super(e.default),this.multiConfig=e}async initialize(){for(let e of _i){let t=this.multiConfig[e];if(t){let s=js(t);await s.initialize(),this.providers.set(e,s)}}}resolve(e){return e&&this.providers.has(e)?this.providers.get(e):this.providers.get("default")}async complete(e){return this.resolve(e.tier).complete(e)}async*stream(e){yield*this.resolve(e.tier).stream(e)}async embed(e){return(this.providers.get("embeddings")??this.resolve()).embed(e)}supportsEmbeddings(){return(this.providers.get("embeddings")??this.resolve()).supportsEmbeddings()}isAvailable(){return this.resolve().isAvailable()}getContextWindow(){return this.resolve().getContextWindow()}};d(Ws,"createModelRouter")});function ie(c){return Math.ceil(c.length/3.5)}function ts(c){if(typeof c.content=="string")return ie(c.content)+4;let e=4;for(let t of c.content)switch(t.type){case"text":e+=ie(t.text);break;case"image":e+=1e3;break;case"tool_use":e+=ie(t.name)+ie(JSON.stringify(t.input));break;case"tool_result":e+=ie(t.content);break}return e}var bt,nn=f(()=>{"use strict";d(ie,"estimateTokens");d(ts,"estimateMessageTokens");bt=class{static{d(this,"PromptBuilder")}buildSystemPrompt(e={}){let{memories:t,skills:s,userProfile:r,todayEvents:n}=e,o=process.platform==="darwin"?"macOS":process.platform==="win32"?"Windows":"Linux",i=process.env.HOME||process.env.USERPROFILE||"~",a=`You are Alfred, a personal AI assistant. You run on ${o} (home: ${i}).
257
257
 
258
258
  ## Core principles
259
- - ACT, don't just talk. For simple, safe tasks (searches, calculations, reminders, reading files), USE YOUR TOOLS immediately.
259
+ - **When the user's intent is clear**, ACT immediately using your tools. Don't explain what you'll do \u2014 just do it.
260
+ - **When the user's intent is unclear or ambiguous**, ASK before doing anything. This includes: files sent without instructions, vague requests, or anything where you'd have to guess what the user wants.
260
261
  - **Ask before acting** on anything that changes the system: installing software, deleting files, writing to disk, running commands with side effects. Briefly confirm what you'll do and wait for the user's OK.
261
262
  - Do exactly what the user asks. If the user asks for X, don't install Y instead. If you think an alternative is better, **recommend it first** and let the user decide.
262
263
  - Respond in the same language the user writes in.
263
264
  - Be concise. No filler text, no unnecessary explanations.
264
265
  - If a tool fails or is denied, explain why and try an alternative approach.
266
+ - **If a tool call fails with the same error twice, STOP.** Tell the user what went wrong and ask how to proceed. Do NOT retry the same call.
265
267
 
266
268
  ## Follow-ups and corrections
267
269
  - When the user refers back to a previous request or corrects you, **reconnect to the original task**. Don't start fresh \u2014 continue where you left off.
@@ -298,46 +300,46 @@ For complex tasks, work through multiple steps:
298
300
  - Language: ${r.language}`),r.bio&&(a+=`
299
301
  - Bio: ${r.bio}`)),n&&n.length>0){a+=`
300
302
 
301
- ## Today's events`;for(let E of n){let T=E.allDay?"All day":E.start.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",...r?.timezone?{timeZone:r.timezone}:{}}),k=E.allDay?"":`-${E.end.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",...r?.timezone?{timeZone:r.timezone}:{}})}`,_=E.location?` @ ${E.location}`:"";a+=`
302
- - ${T}${k}: ${E.title}${_}`}}if(t&&t.length>0){if(a+=`
303
+ ## Today's events`;for(let E of n){let T=E.allDay?"All day":E.start.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",...r?.timezone?{timeZone:r.timezone}:{}}),k=E.allDay?"":`-${E.end.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",...r?.timezone?{timeZone:r.timezone}:{}})}`,v=E.location?` @ ${E.location}`:"";a+=`
304
+ - ${T}${k}: ${E.title}${v}`}}if(t&&t.length>0){if(a+=`
303
305
 
304
306
  ## Memories about this user
305
- `,t.some(T=>T.type&&T.type!=="general")){let T=new Map;for(let _ of t){let v=_.type||"general",M=T.get(v);M||(M=[],T.set(v,M)),M.push(_)}let k={fact:"Facts",preference:"Preferences",correction:"Corrections",entity:"Entities",decision:"Decisions",relationship:"Relationships",principle:"Principles",commitment:"Commitments",moment:"Moments",skill:"Skills",general:"General"};for(let[_,v]of T){a+=`
306
- ### ${k[_]||_}
307
- `;for(let M of v)a+=`- ${M.key}: ${M.value}
307
+ `,t.some(T=>T.type&&T.type!=="general")){let T=new Map;for(let v of t){let b=v.type||"general",A=T.get(b);A||(A=[],T.set(b,A)),A.push(v)}let k={fact:"Facts",preference:"Preferences",correction:"Corrections",entity:"Entities",decision:"Decisions",relationship:"Relationships",principle:"Principles",commitment:"Commitments",moment:"Moments",skill:"Skills",general:"General"};for(let[v,b]of T){a+=`
308
+ ### ${k[v]||v}
309
+ `;for(let A of b)a+=`- ${A.key}: ${A.value}
308
310
  `}}else for(let T of t)a+=`- [${T.category}] ${T.key}: ${T.value}
309
311
  `;a+=`
310
312
  Use these memories to personalize your responses. When the user tells you new facts or preferences, use the memory tool to save them.`}else a+=`
311
313
 
312
- When the user tells you facts about themselves or preferences, use the memory tool to save them for future reference.`;return a}buildMessages(e){let t=e.filter(s=>s.role==="user"||s.role==="assistant").map(s=>{if(s.toolCalls){let r;try{r=JSON.parse(s.toolCalls)}catch{r=[]}if(s.role==="assistant"){let i=r,a=[];s.content&&a.push({type:"text",text:s.content});for(let l of i)a.push({type:"tool_use",id:l.id,name:l.name,input:l.input});return{role:"assistant",content:a}}let n=r,o=[];for(let i of n)i.type==="tool_result"&&o.push(i);return o.length>0?{role:"user",content:o}:{role:"user",content:s.content||""}}return{role:s.role,content:s.content}});return this.sanitizeToolMessages(t)}sanitizeToolMessages(e){let t=new Set;for(let n of e)if(n.role==="assistant"&&Array.isArray(n.content))for(let o of n.content)o.type==="tool_use"&&t.add(o.id);let s=new Set;for(let n of e)if(n.role==="user"&&Array.isArray(n.content))for(let o of n.content)o.type==="tool_result"&&s.add(o.tool_use_id);let r=[];for(let n of e){if(!Array.isArray(n.content)){r.push(n);continue}let o=n.content.filter(i=>i.type==="tool_use"?s.has(i.id):i.type==="tool_result"?t.has(i.tool_use_id):!0);o.length!==0&&r.push({...n,content:o})}return r}buildTools(e){return e.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}}});var Hs=f(()=>{"use strict";Ie();Cs();yt();Us();Ps();Fs();Bs();rn();nn()});var _t,Xs=f(()=>{"use strict";_t=class{static{d(this,"RateLimiter")}buckets=new Map;check(e,t){let s=Date.now(),r=t.windowSeconds*1e3,n=this.buckets.get(e);if(!n)return{allowed:!0,remaining:t.maxInvocations,resetsAt:s+r};if(s>n.windowStart+r)return{allowed:!0,remaining:t.maxInvocations,resetsAt:s+r};let o=Math.max(0,t.maxInvocations-n.count);return{allowed:n.count<t.maxInvocations,remaining:o,resetsAt:n.windowStart+r}}increment(e,t){let s=Date.now(),r=t.windowSeconds*1e3,n=this.buckets.get(e);!n||s>n.windowStart+r?this.buckets.set(e,{count:1,windowStart:s}):n.count+=1}reset(){this.buckets.clear()}}});var St,on=f(()=>{"use strict";Xs();St=class{static{d(this,"RuleEngine")}rules=[];rateLimiter=new _t;loadRules(e){this.rules=[...e].sort((t,s)=>t.priority-s.priority)}getRules(){return this.rules}evaluate(e){for(let t of this.rules)if(this.ruleMatches(t,e))return t.rateLimit&&t.effect==="allow"&&!this.checkRateLimit(t,e)?{allowed:!1,matchedRule:t,reason:`Rate limit exceeded for rule: ${t.id}`,timestamp:new Date}:{allowed:t.effect==="allow",matchedRule:t,reason:`Matched rule: ${t.id}`,timestamp:new Date};return{allowed:!1,matchedRule:void 0,reason:"No matching rule found \u2014 default deny",timestamp:new Date}}checkRateLimit(e,t){if(!e.rateLimit)return!0;let s=this.getScopeKey(e.scope,t),r=`${e.id}:${s}`;return this.rateLimiter.check(r,e.rateLimit).allowed?(this.rateLimiter.increment(r,e.rateLimit),!0):!1}resetRateLimits(){this.rateLimiter.reset()}getScopeKey(e,t){switch(e){case"global":return"global";case"user":return t.userId;case"conversation":return t.chatId??"unknown";case"platform":return t.platform}}ruleMatches(e,t){return!(!e.actions.includes("*")&&!e.actions.includes(t.action)||!e.riskLevels.includes(t.riskLevel)||e.conditions&&(e.conditions.users&&e.conditions.users.length>0&&!e.conditions.users.includes(t.userId)||e.conditions.platforms&&e.conditions.platforms.length>0&&!e.conditions.platforms.includes(t.platform)||e.conditions.chatType&&t.chatType&&e.conditions.chatType!==t.chatType||e.conditions.timeWindow&&!this.matchesTimeWindow(e.conditions.timeWindow)))}matchesTimeWindow(e){if(!e)return!0;let t=new Date;if(e.daysOfWeek&&e.daysOfWeek.length>0&&!e.daysOfWeek.includes(t.getDay()))return!1;let s=t.getHours();if(e.startHour!==void 0&&e.endHour!==void 0){if(e.startHour<=e.endHour){if(s<e.startHour||s>=e.endHour)return!1}else if(s>=e.endHour&&s<e.startHour)return!1}else if(e.startHour!==void 0){if(s<e.startHour)return!1}else if(e.endHour!==void 0&&s>=e.endHour)return!1;return!0}}});var an,cn,ln,fe,dn=f(()=>{"use strict";an=["allow","deny"],cn=["global","user","conversation","platform"],ln=["read","write","destructive","admin"],fe=class{static{d(this,"RuleLoader")}loadFromObject(e){if(!e||!Array.isArray(e.rules))throw new Error('Invalid data: expected an object with a "rules" array');return e.rules.map((t,s)=>this.validateRule(t,s))}validateRule(e,t){if(typeof e!="object"||e===null)throw new Error(`Rule at index ${t} is not an object`);let s=e;if(typeof s.id!="string"||s.id.length===0)throw new Error(`Rule at index ${t} is missing a valid "id" string`);if(typeof s.effect!="string"||!an.includes(s.effect))throw new Error(`Rule "${s.id}" has invalid "effect": expected one of ${an.join(", ")}`);if(typeof s.priority!="number"||!Number.isFinite(s.priority))throw new Error(`Rule "${s.id}" is missing a valid "priority" number`);if(typeof s.scope!="string"||!cn.includes(s.scope))throw new Error(`Rule "${s.id}" has invalid "scope": expected one of ${cn.join(", ")}`);if(!Array.isArray(s.actions)||s.actions.length===0)throw new Error(`Rule "${s.id}" is missing a valid "actions" array`);for(let n of s.actions)if(typeof n!="string")throw new Error(`Rule "${s.id}" has a non-string entry in "actions"`);if(!Array.isArray(s.riskLevels)||s.riskLevels.length===0)throw new Error(`Rule "${s.id}" is missing a valid "riskLevels" array`);for(let n of s.riskLevels)if(!ln.includes(n))throw new Error(`Rule "${s.id}" has invalid risk level "${n}": expected one of ${ln.join(", ")}`);let r={id:s.id,effect:s.effect,priority:s.priority,scope:s.scope,actions:s.actions,riskLevels:s.riskLevels};if(s.conditions!==void 0){if(typeof s.conditions!="object"||s.conditions===null)throw new Error(`Rule "${s.id}" has invalid "conditions": expected an object`);r.conditions=s.conditions}if(s.rateLimit!==void 0){if(typeof s.rateLimit!="object"||s.rateLimit===null)throw new Error(`Rule "${s.id}" has invalid "rateLimit": expected an object`);let n=s.rateLimit;if(typeof n.maxInvocations!="number"||typeof n.windowSeconds!="number")throw new Error(`Rule "${s.id}" has invalid "rateLimit": expected maxInvocations and windowSeconds numbers`);r.rateLimit=s.rateLimit}return r}}});import Si from"node:crypto";var kt,un=f(()=>{"use strict";kt=class{static{d(this,"SecurityManager")}ruleEngine;auditRepository;logger;constructor(e,t,s){this.ruleEngine=e,this.auditRepository=t,this.logger=s}evaluate(e){let t=this.ruleEngine.evaluate(e),s={id:Si.randomUUID(),timestamp:t.timestamp,userId:e.userId,action:e.action,riskLevel:e.riskLevel,ruleId:t.matchedRule?.id,effect:t.allowed?"allow":"deny",platform:e.platform,chatId:e.chatId,context:{chatType:e.chatType,reason:t.reason}};try{this.auditRepository.log(s)}catch(r){this.logger.error({err:r,auditEntry:s},"Failed to write audit log entry")}return this.logger.debug({userId:e.userId,action:e.action,allowed:t.allowed,ruleId:t.matchedRule?.id,reason:t.reason},"Security evaluation completed"),t}}});var ss=f(()=>{"use strict";on();Xs();dn();un()});var b,D=f(()=>{"use strict";b=class{static{d(this,"Skill")}}});var Ae,mn=f(()=>{"use strict";Ae=class{static{d(this,"SkillRegistry")}skills=new Map;register(e){let{name:t}=e.metadata;if(this.skills.has(t))throw new Error(`Skill "${t}" is already registered`);this.skills.set(t,e)}get(e){return this.skills.get(e)}getAll(){return[...this.skills.values()]}has(e){return this.skills.has(e)}toToolDefinitions(){return this.getAll().map(e=>({name:e.metadata.name,description:e.metadata.description,inputSchema:e.metadata.inputSchema}))}}});var Re,pn=f(()=>{"use strict";Re=class{static{d(this,"SkillSandbox")}logger;constructor(e){this.logger=e}async execute(e,t,s,r,n){r=r??e.metadata.timeoutMs??3e4;let{name:o}=e.metadata;return this.logger.info({skill:o,input:t},"Skill execution started"),n?this.executeWithTracker(e,t,s,o,r,n):this.executeWithHardTimeout(e,t,s,o,r)}async executeWithTracker(e,t,s,r,n,o){return new Promise(i=>{let a=!1,l,u,p,m=d(()=>{l&&clearInterval(l),u&&clearTimeout(u),p&&clearTimeout(p)},"cleanup"),h=d(w=>{a||(a=!0,m(),i(w))},"finish");e.execute(t,s).then(w=>{this.logger.info({skill:r,success:w.success},"Skill execution completed"),h(w)},w=>{let E=w instanceof Error?w.message:String(w);this.logger.error({skill:r,error:E},"Skill execution failed"),h({success:!1,error:E})}),p=setTimeout(()=>{if(a)return;let w=o.getIdleMs();if(w>=12e4){let T=o.getSnapshot();this.logger.warn({skill:r,idleMs:w,state:T.state,iteration:T.iteration},"Agent inactive after initial timeout \u2014 aborting"),h({success:!1,error:`Skill "${r}" timed out \u2014 inactive for ${Math.round(w/1e3)}s (last state: ${T.state})`});return}let E=o.getSnapshot();this.logger.info({skill:r,idleMs:w,state:E.state,iteration:E.iteration,totalMs:E.totalElapsedMs},"Initial timeout reached but agent is active \u2014 extending"),l=setInterval(()=>{if(a){m();return}let T=o.getIdleMs(),k=o.getSnapshot();T>=12e4?(this.logger.warn({skill:r,idleMs:T,state:k.state,iteration:k.iteration,totalMs:k.totalElapsedMs},"Agent went inactive \u2014 aborting"),h({success:!1,error:`Skill "${r}" killed \u2014 inactive for ${Math.round(T/1e3)}s (last state: ${k.state})`})):this.logger.debug({skill:r,idleMs:T,state:k.state,iteration:k.iteration},"Agent still active, continuing...")},1e4)},n),u=setTimeout(()=>{if(a)return;let w=o.getSnapshot();this.logger.error({skill:r,totalMs:w.totalElapsedMs,state:w.state,iteration:w.iteration},"Absolute time limit reached \u2014 force killing agent"),h({success:!1,error:`Skill "${r}" force-killed after ${Math.round(12e5/6e4)} minutes (safety limit)`})},12e5)})}async executeWithHardTimeout(e,t,s,r,n){try{let o=await Promise.race([e.execute(t,s),new Promise((i,a)=>{setTimeout(()=>a(new Error(`Skill "${r}" timed out after ${n}ms`)),n)})]);return this.logger.info({skill:r,success:o.success},"Skill execution completed"),o}catch(o){let i=o instanceof Error?o.message:String(o);return this.logger.error({skill:r,error:i},"Skill execution failed"),{success:!1,error:i}}}}});var ge,zs=f(()=>{"use strict";ge=class{static{d(this,"ActivityTracker")}state="starting";iteration=0;maxIterations=0;currentTool;lastPingAt;startedAt;history=[];onProgress;constructor(e){this.startedAt=Date.now(),this.lastPingAt=Date.now(),this.onProgress=e}ping(e,t){this.state=e,this.lastPingAt=Date.now(),t?.iteration!==void 0&&(this.iteration=t.iteration),t?.maxIterations!==void 0&&(this.maxIterations=t.maxIterations),this.currentTool=t?.tool,this.history.push({state:e,tool:t?.tool,iteration:this.iteration,timestamp:this.lastPingAt}),this.onProgress&&this.onProgress(this.formatStatus())}getIdleMs(){return Date.now()-this.lastPingAt}getTotalElapsedMs(){return Date.now()-this.startedAt}formatStatus(){let e=this.maxIterations>0?` (${this.iteration}/${this.maxIterations})`:"";switch(this.state){case"starting":return"Sub-agent starting...";case"llm_call":return`Sub-agent thinking...${e}`;case"tool_call":return this.currentTool?`Sub-agent using ${this.currentTool}${e}`:`Sub-agent using tool...${e}`;case"processing":return`Sub-agent processing...${e}`;case"done":return`Sub-agent done${e}`;default:return`Sub-agent working...${e}`}}getSnapshot(){return{state:this.state,iteration:this.iteration,maxIterations:this.maxIterations,lastPingAt:this.lastPingAt,idleMs:this.getIdleMs(),currentTool:this.currentTool,totalElapsedMs:this.getTotalElapsedMs(),history:[...this.history]}}}});import ki from"node:fs";import qs from"node:path";var rs,hn=f(()=>{"use strict";D();rs=class{static{d(this,"PluginLoader")}async loadFromDirectory(e){let t=qs.resolve(e),s;try{s=await ki.promises.readdir(t)}catch(o){let i=o instanceof Error?o.message:String(o);return console.warn(`PluginLoader: failed to read directory "${t}": ${i}`),[]}let r=s.filter(o=>o.endsWith(".js")),n=[];for(let o of r){let i=qs.join(t,o);try{let a=await this.loadFromFile(i);n.push(a)}catch(a){let l=a instanceof Error?a.message:String(a);console.warn(`PluginLoader: skipping "${i}": ${l}`)}}return n}async loadFromFile(e){let t=qs.resolve(e),n=(await import(`file:///${t.replace(/\\/g,"/")}`)).default;if(typeof n!="function")throw new Error(`Module "${t}" does not have a default export that is a class`);let o=new n;if(!(o instanceof b))throw new Error(`Default export of "${t}" does not extend Skill`);return this.validateMetadata(o,t),o}validateMetadata(e,t){let{metadata:s}=e;if(!s)throw new Error(`Plugin "${t}" is missing metadata`);if(!s.name||typeof s.name!="string")throw new Error(`Plugin "${t}" has invalid or missing metadata.name`);if(!s.description||typeof s.description!="string")throw new Error(`Plugin "${t}" has invalid or missing metadata.description`);if(!["read","write","destructive","admin"].includes(s.riskLevel))throw new Error(`Plugin "${t}" has invalid metadata.riskLevel: "${String(s.riskLevel)}"`);if(!s.version||typeof s.version!="string")throw new Error(`Plugin "${t}" has invalid or missing metadata.version`)}}});var vi,xi,Le,fn=f(()=>{"use strict";D();vi=/^[\d+\-*/().,%\s]|Math\.(sin|cos|tan|sqrt|pow|abs|floor|ceil|round|log|log2|log10|PI|E)/,xi=/^[0-9+\-*/().,\s%]*(Math\.(sin|cos|tan|sqrt|pow|abs|floor|ceil|round|log|log2|log10|PI|E)[(0-9+\-*/().,\s%]*)*$/,Le=class extends b{static{d(this,"CalculatorSkill")}metadata={name:"calculator",description:"Evaluate mathematical expressions. Use for any calculation, unit conversion, or math question the user asks.",riskLevel:"read",version:"1.0.0",inputSchema:{type:"object",properties:{expression:{type:"string",description:"The mathematical expression to evaluate"}},required:["expression"]}};async execute(e,t){let s=e.expression;if(!s||typeof s!="string")return{success:!1,error:"Invalid expression: input must be a non-empty string"};let r=s.trim();if(!vi.test(r))return{success:!1,error:`Invalid expression: "${r}" contains disallowed characters`};if(!xi.test(r))return{success:!1,error:`Invalid expression: "${r}" contains disallowed constructs`};try{let o=new Function("Math",`"use strict"; return (${r});`)(Math);return typeof o!="number"||!isFinite(o)?{success:!1,error:`Invalid expression: "${r}" did not produce a finite number`}:{success:!0,data:o,display:`${r} = ${o}`}}catch{return{success:!1,error:`Invalid expression: "${r}"`}}}}});var Me,gn=f(()=>{"use strict";D();Me=class extends b{static{d(this,"SystemInfoSkill")}metadata={name:"system_info",description:'Get system information: current date/time (datetime), system stats (general), memory usage (memory), or uptime (uptime). Use "datetime" when the user asks what day/time it is.',riskLevel:"read",version:"1.0.0",inputSchema:{type:"object",properties:{category:{type:"string",enum:["general","memory","uptime","datetime"],description:"Category of system info (use datetime for current date/time)"}},required:["category"]}};async execute(e,t){let s=e.category;switch(s){case"general":return this.getGeneralInfo();case"memory":return this.getMemoryInfo();case"uptime":return this.getUptimeInfo();case"datetime":return this.getDateTimeInfo();default:return{success:!1,error:`Unknown category: "${String(s)}". Valid categories: general, memory, uptime`}}}getGeneralInfo(){let e={nodeVersion:process.version,platform:process.platform,arch:process.arch};return{success:!0,data:e,display:`Node.js ${e.nodeVersion} on ${e.platform} (${e.arch})`}}getMemoryInfo(){let e=process.memoryUsage(),t=d(r=>(r/1024/1024).toFixed(2),"toMB"),s={rss:`${t(e.rss)} MB`,heapTotal:`${t(e.heapTotal)} MB`,heapUsed:`${t(e.heapUsed)} MB`,external:`${t(e.external)} MB`};return{success:!0,data:s,display:`Memory \u2014 RSS: ${s.rss}, Heap: ${s.heapUsed} / ${s.heapTotal}, External: ${s.external}`}}getUptimeInfo(){let e=process.uptime(),t=Math.floor(e/3600),s=Math.floor(e%3600/60),r=Math.floor(e%60),n={uptimeSeconds:e,formatted:`${t}h ${s}m ${r}s`};return{success:!0,data:n,display:`Uptime: ${n.formatted}`}}getDateTimeInfo(){let e=new Date,t={iso:e.toISOString(),date:e.toLocaleDateString("de-DE",{weekday:"long",year:"numeric",month:"long",day:"numeric"}),time:e.toLocaleTimeString("de-DE"),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timestamp:e.getTime()};return{success:!0,data:t,display:`${t.date}, ${t.time} (${t.timezone})`}}}});var Ne,yn=f(()=>{"use strict";D();Ne=class extends b{static{d(this,"WebSearchSkill")}config;metadata={name:"web_search",description:"Search the internet for current information, news, facts, or anything the user asks about that you don't know. Use this whenever you need up-to-date information.",riskLevel:"read",version:"1.1.0",inputSchema:{type:"object",properties:{query:{type:"string",description:"The search query"},count:{type:"number",description:"Number of results to return (default: 5, max: 10)"}},required:["query"]}};constructor(e){super(),this.config=e}async execute(e,t){let s=e.query,r=Math.min(Math.max(1,e.count||5),10);if(!s||typeof s!="string")return{success:!1,error:'Invalid input: "query" must be a non-empty string'};if(!this.config)return{success:!1,error:"Web search is not configured. Run `alfred setup` to configure a search provider."};if((this.config.provider==="brave"||this.config.provider==="tavily")&&!this.config.apiKey)return{success:!1,error:`Web search requires an API key for ${this.config.provider}. Run \`alfred setup\` to configure it.`};try{let o;switch(this.config.provider){case"brave":o=await this.searchBrave(s,r);break;case"searxng":o=await this.searchSearXNG(s,r);break;case"tavily":o=await this.searchTavily(s,r);break;case"duckduckgo":o=await this.searchDuckDuckGo(s,r);break;default:return{success:!1,error:`Unknown search provider: ${this.config.provider}`}}if(o.length===0)return{success:!0,data:{results:[]},display:`No results found for "${s}".`};let i=o.map((a,l)=>`${l+1}. **${a.title}**
314
+ When the user tells you facts about themselves or preferences, use the memory tool to save them for future reference.`;return a}buildMessages(e){let t=e.filter(s=>s.role==="user"||s.role==="assistant").map(s=>{if(s.toolCalls){let r;try{r=JSON.parse(s.toolCalls)}catch{r=[]}if(s.role==="assistant"){let i=r,a=[];s.content&&a.push({type:"text",text:s.content});for(let l of i)a.push({type:"tool_use",id:l.id,name:l.name,input:l.input});return{role:"assistant",content:a}}let n=r,o=[];for(let i of n)i.type==="tool_result"&&o.push(i);return o.length>0?{role:"user",content:o}:{role:"user",content:s.content||""}}return{role:s.role,content:s.content}});return this.sanitizeToolMessages(t)}sanitizeToolMessages(e){let t=new Set;for(let n of e)if(n.role==="assistant"&&Array.isArray(n.content))for(let o of n.content)o.type==="tool_use"&&t.add(o.id);let s=new Set;for(let n of e)if(n.role==="user"&&Array.isArray(n.content))for(let o of n.content)o.type==="tool_result"&&s.add(o.tool_use_id);let r=[];for(let n of e){if(!Array.isArray(n.content)){r.push(n);continue}let o=n.content.filter(i=>i.type==="tool_use"?s.has(i.id):i.type==="tool_result"?t.has(i.tool_use_id):!0);o.length!==0&&r.push({...n,content:o})}return r}buildTools(e){return e.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}}});var Hs=f(()=>{"use strict";Ie();Cs();yt();Us();Ps();Fs();Bs();rn();nn()});var _t,Xs=f(()=>{"use strict";_t=class{static{d(this,"RateLimiter")}buckets=new Map;check(e,t){let s=Date.now(),r=t.windowSeconds*1e3,n=this.buckets.get(e);if(!n)return{allowed:!0,remaining:t.maxInvocations,resetsAt:s+r};if(s>n.windowStart+r)return{allowed:!0,remaining:t.maxInvocations,resetsAt:s+r};let o=Math.max(0,t.maxInvocations-n.count);return{allowed:n.count<t.maxInvocations,remaining:o,resetsAt:n.windowStart+r}}increment(e,t){let s=Date.now(),r=t.windowSeconds*1e3,n=this.buckets.get(e);!n||s>n.windowStart+r?this.buckets.set(e,{count:1,windowStart:s}):n.count+=1}reset(){this.buckets.clear()}}});var St,on=f(()=>{"use strict";Xs();St=class{static{d(this,"RuleEngine")}rules=[];rateLimiter=new _t;loadRules(e){this.rules=[...e].sort((t,s)=>t.priority-s.priority)}getRules(){return this.rules}evaluate(e){for(let t of this.rules)if(this.ruleMatches(t,e))return t.rateLimit&&t.effect==="allow"&&!this.checkRateLimit(t,e)?{allowed:!1,matchedRule:t,reason:`Rate limit exceeded for rule: ${t.id}`,timestamp:new Date}:{allowed:t.effect==="allow",matchedRule:t,reason:`Matched rule: ${t.id}`,timestamp:new Date};return{allowed:!1,matchedRule:void 0,reason:"No matching rule found \u2014 default deny",timestamp:new Date}}checkRateLimit(e,t){if(!e.rateLimit)return!0;let s=this.getScopeKey(e.scope,t),r=`${e.id}:${s}`;return this.rateLimiter.check(r,e.rateLimit).allowed?(this.rateLimiter.increment(r,e.rateLimit),!0):!1}resetRateLimits(){this.rateLimiter.reset()}getScopeKey(e,t){switch(e){case"global":return"global";case"user":return t.userId;case"conversation":return t.chatId??"unknown";case"platform":return t.platform}}ruleMatches(e,t){return!(!e.actions.includes("*")&&!e.actions.includes(t.action)||!e.riskLevels.includes(t.riskLevel)||e.conditions&&(e.conditions.users&&e.conditions.users.length>0&&!e.conditions.users.includes(t.userId)||e.conditions.platforms&&e.conditions.platforms.length>0&&!e.conditions.platforms.includes(t.platform)||e.conditions.chatType&&t.chatType&&e.conditions.chatType!==t.chatType||e.conditions.timeWindow&&!this.matchesTimeWindow(e.conditions.timeWindow)))}matchesTimeWindow(e){if(!e)return!0;let t=new Date;if(e.daysOfWeek&&e.daysOfWeek.length>0&&!e.daysOfWeek.includes(t.getDay()))return!1;let s=t.getHours();if(e.startHour!==void 0&&e.endHour!==void 0){if(e.startHour<=e.endHour){if(s<e.startHour||s>=e.endHour)return!1}else if(s>=e.endHour&&s<e.startHour)return!1}else if(e.startHour!==void 0){if(s<e.startHour)return!1}else if(e.endHour!==void 0&&s>=e.endHour)return!1;return!0}}});var an,cn,ln,fe,dn=f(()=>{"use strict";an=["allow","deny"],cn=["global","user","conversation","platform"],ln=["read","write","destructive","admin"],fe=class{static{d(this,"RuleLoader")}loadFromObject(e){if(!e||!Array.isArray(e.rules))throw new Error('Invalid data: expected an object with a "rules" array');return e.rules.map((t,s)=>this.validateRule(t,s))}validateRule(e,t){if(typeof e!="object"||e===null)throw new Error(`Rule at index ${t} is not an object`);let s=e;if(typeof s.id!="string"||s.id.length===0)throw new Error(`Rule at index ${t} is missing a valid "id" string`);if(typeof s.effect!="string"||!an.includes(s.effect))throw new Error(`Rule "${s.id}" has invalid "effect": expected one of ${an.join(", ")}`);if(typeof s.priority!="number"||!Number.isFinite(s.priority))throw new Error(`Rule "${s.id}" is missing a valid "priority" number`);if(typeof s.scope!="string"||!cn.includes(s.scope))throw new Error(`Rule "${s.id}" has invalid "scope": expected one of ${cn.join(", ")}`);if(!Array.isArray(s.actions)||s.actions.length===0)throw new Error(`Rule "${s.id}" is missing a valid "actions" array`);for(let n of s.actions)if(typeof n!="string")throw new Error(`Rule "${s.id}" has a non-string entry in "actions"`);if(!Array.isArray(s.riskLevels)||s.riskLevels.length===0)throw new Error(`Rule "${s.id}" is missing a valid "riskLevels" array`);for(let n of s.riskLevels)if(!ln.includes(n))throw new Error(`Rule "${s.id}" has invalid risk level "${n}": expected one of ${ln.join(", ")}`);let r={id:s.id,effect:s.effect,priority:s.priority,scope:s.scope,actions:s.actions,riskLevels:s.riskLevels};if(s.conditions!==void 0){if(typeof s.conditions!="object"||s.conditions===null)throw new Error(`Rule "${s.id}" has invalid "conditions": expected an object`);r.conditions=s.conditions}if(s.rateLimit!==void 0){if(typeof s.rateLimit!="object"||s.rateLimit===null)throw new Error(`Rule "${s.id}" has invalid "rateLimit": expected an object`);let n=s.rateLimit;if(typeof n.maxInvocations!="number"||typeof n.windowSeconds!="number")throw new Error(`Rule "${s.id}" has invalid "rateLimit": expected maxInvocations and windowSeconds numbers`);r.rateLimit=s.rateLimit}return r}}});import Si from"node:crypto";var kt,un=f(()=>{"use strict";kt=class{static{d(this,"SecurityManager")}ruleEngine;auditRepository;logger;constructor(e,t,s){this.ruleEngine=e,this.auditRepository=t,this.logger=s}evaluate(e){let t=this.ruleEngine.evaluate(e),s={id:Si.randomUUID(),timestamp:t.timestamp,userId:e.userId,action:e.action,riskLevel:e.riskLevel,ruleId:t.matchedRule?.id,effect:t.allowed?"allow":"deny",platform:e.platform,chatId:e.chatId,context:{chatType:e.chatType,reason:t.reason}};try{this.auditRepository.log(s)}catch(r){this.logger.error({err:r,auditEntry:s},"Failed to write audit log entry")}return this.logger.debug({userId:e.userId,action:e.action,allowed:t.allowed,ruleId:t.matchedRule?.id,reason:t.reason},"Security evaluation completed"),t}}});var ss=f(()=>{"use strict";on();Xs();dn();un()});var _,D=f(()=>{"use strict";_=class{static{d(this,"Skill")}}});var Ae,mn=f(()=>{"use strict";Ae=class{static{d(this,"SkillRegistry")}skills=new Map;register(e){let{name:t}=e.metadata;if(this.skills.has(t))throw new Error(`Skill "${t}" is already registered`);this.skills.set(t,e)}get(e){return this.skills.get(e)}getAll(){return[...this.skills.values()]}has(e){return this.skills.has(e)}toToolDefinitions(){return this.getAll().map(e=>({name:e.metadata.name,description:e.metadata.description,inputSchema:e.metadata.inputSchema}))}}});var Re,pn=f(()=>{"use strict";Re=class{static{d(this,"SkillSandbox")}logger;constructor(e){this.logger=e}async execute(e,t,s,r,n){r=r??e.metadata.timeoutMs??3e4;let{name:o}=e.metadata;return this.logger.info({skill:o,input:t},"Skill execution started"),n?this.executeWithTracker(e,t,s,o,r,n):this.executeWithHardTimeout(e,t,s,o,r)}async executeWithTracker(e,t,s,r,n,o){return new Promise(i=>{let a=!1,l,u,p,m=d(()=>{l&&clearInterval(l),u&&clearTimeout(u),p&&clearTimeout(p)},"cleanup"),h=d(w=>{a||(a=!0,m(),i(w))},"finish");e.execute(t,s).then(w=>{this.logger.info({skill:r,success:w.success},"Skill execution completed"),h(w)},w=>{let E=w instanceof Error?w.message:String(w);this.logger.error({skill:r,error:E},"Skill execution failed"),h({success:!1,error:E})}),p=setTimeout(()=>{if(a)return;let w=o.getIdleMs();if(w>=12e4){let T=o.getSnapshot();this.logger.warn({skill:r,idleMs:w,state:T.state,iteration:T.iteration},"Agent inactive after initial timeout \u2014 aborting"),h({success:!1,error:`Skill "${r}" timed out \u2014 inactive for ${Math.round(w/1e3)}s (last state: ${T.state})`});return}let E=o.getSnapshot();this.logger.info({skill:r,idleMs:w,state:E.state,iteration:E.iteration,totalMs:E.totalElapsedMs},"Initial timeout reached but agent is active \u2014 extending"),l=setInterval(()=>{if(a){m();return}let T=o.getIdleMs(),k=o.getSnapshot();T>=12e4?(this.logger.warn({skill:r,idleMs:T,state:k.state,iteration:k.iteration,totalMs:k.totalElapsedMs},"Agent went inactive \u2014 aborting"),h({success:!1,error:`Skill "${r}" killed \u2014 inactive for ${Math.round(T/1e3)}s (last state: ${k.state})`})):this.logger.debug({skill:r,idleMs:T,state:k.state,iteration:k.iteration},"Agent still active, continuing...")},1e4)},n),u=setTimeout(()=>{if(a)return;let w=o.getSnapshot();this.logger.error({skill:r,totalMs:w.totalElapsedMs,state:w.state,iteration:w.iteration},"Absolute time limit reached \u2014 force killing agent"),h({success:!1,error:`Skill "${r}" force-killed after ${Math.round(12e5/6e4)} minutes (safety limit)`})},12e5)})}async executeWithHardTimeout(e,t,s,r,n){try{let o=await Promise.race([e.execute(t,s),new Promise((i,a)=>{setTimeout(()=>a(new Error(`Skill "${r}" timed out after ${n}ms`)),n)})]);return this.logger.info({skill:r,success:o.success},"Skill execution completed"),o}catch(o){let i=o instanceof Error?o.message:String(o);return this.logger.error({skill:r,error:i},"Skill execution failed"),{success:!1,error:i}}}}});var ge,zs=f(()=>{"use strict";ge=class{static{d(this,"ActivityTracker")}state="starting";iteration=0;maxIterations=0;currentTool;lastPingAt;startedAt;history=[];onProgress;constructor(e){this.startedAt=Date.now(),this.lastPingAt=Date.now(),this.onProgress=e}ping(e,t){this.state=e,this.lastPingAt=Date.now(),t?.iteration!==void 0&&(this.iteration=t.iteration),t?.maxIterations!==void 0&&(this.maxIterations=t.maxIterations),this.currentTool=t?.tool,this.history.push({state:e,tool:t?.tool,iteration:this.iteration,timestamp:this.lastPingAt}),this.onProgress&&this.onProgress(this.formatStatus())}getIdleMs(){return Date.now()-this.lastPingAt}getTotalElapsedMs(){return Date.now()-this.startedAt}formatStatus(){let e=this.maxIterations>0?` (${this.iteration}/${this.maxIterations})`:"";switch(this.state){case"starting":return"Sub-agent starting...";case"llm_call":return`Sub-agent thinking...${e}`;case"tool_call":return this.currentTool?`Sub-agent using ${this.currentTool}${e}`:`Sub-agent using tool...${e}`;case"processing":return`Sub-agent processing...${e}`;case"done":return`Sub-agent done${e}`;default:return`Sub-agent working...${e}`}}getSnapshot(){return{state:this.state,iteration:this.iteration,maxIterations:this.maxIterations,lastPingAt:this.lastPingAt,idleMs:this.getIdleMs(),currentTool:this.currentTool,totalElapsedMs:this.getTotalElapsedMs(),history:[...this.history]}}}});import ki from"node:fs";import qs from"node:path";var rs,hn=f(()=>{"use strict";D();rs=class{static{d(this,"PluginLoader")}async loadFromDirectory(e){let t=qs.resolve(e),s;try{s=await ki.promises.readdir(t)}catch(o){let i=o instanceof Error?o.message:String(o);return console.warn(`PluginLoader: failed to read directory "${t}": ${i}`),[]}let r=s.filter(o=>o.endsWith(".js")),n=[];for(let o of r){let i=qs.join(t,o);try{let a=await this.loadFromFile(i);n.push(a)}catch(a){let l=a instanceof Error?a.message:String(a);console.warn(`PluginLoader: skipping "${i}": ${l}`)}}return n}async loadFromFile(e){let t=qs.resolve(e),n=(await import(`file:///${t.replace(/\\/g,"/")}`)).default;if(typeof n!="function")throw new Error(`Module "${t}" does not have a default export that is a class`);let o=new n;if(!(o instanceof _))throw new Error(`Default export of "${t}" does not extend Skill`);return this.validateMetadata(o,t),o}validateMetadata(e,t){let{metadata:s}=e;if(!s)throw new Error(`Plugin "${t}" is missing metadata`);if(!s.name||typeof s.name!="string")throw new Error(`Plugin "${t}" has invalid or missing metadata.name`);if(!s.description||typeof s.description!="string")throw new Error(`Plugin "${t}" has invalid or missing metadata.description`);if(!["read","write","destructive","admin"].includes(s.riskLevel))throw new Error(`Plugin "${t}" has invalid metadata.riskLevel: "${String(s.riskLevel)}"`);if(!s.version||typeof s.version!="string")throw new Error(`Plugin "${t}" has invalid or missing metadata.version`)}}});var vi,xi,Le,fn=f(()=>{"use strict";D();vi=/^[\d+\-*/().,%\s]|Math\.(sin|cos|tan|sqrt|pow|abs|floor|ceil|round|log|log2|log10|PI|E)/,xi=/^[0-9+\-*/().,\s%]*(Math\.(sin|cos|tan|sqrt|pow|abs|floor|ceil|round|log|log2|log10|PI|E)[(0-9+\-*/().,\s%]*)*$/,Le=class extends _{static{d(this,"CalculatorSkill")}metadata={name:"calculator",description:"Evaluate mathematical expressions. Use for any calculation, unit conversion, or math question the user asks.",riskLevel:"read",version:"1.0.0",inputSchema:{type:"object",properties:{expression:{type:"string",description:"The mathematical expression to evaluate"}},required:["expression"]}};async execute(e,t){let s=e.expression;if(!s||typeof s!="string")return{success:!1,error:"Invalid expression: input must be a non-empty string"};let r=s.trim();if(!vi.test(r))return{success:!1,error:`Invalid expression: "${r}" contains disallowed characters`};if(!xi.test(r))return{success:!1,error:`Invalid expression: "${r}" contains disallowed constructs`};try{let o=new Function("Math",`"use strict"; return (${r});`)(Math);return typeof o!="number"||!isFinite(o)?{success:!1,error:`Invalid expression: "${r}" did not produce a finite number`}:{success:!0,data:o,display:`${r} = ${o}`}}catch{return{success:!1,error:`Invalid expression: "${r}"`}}}}});var Me,gn=f(()=>{"use strict";D();Me=class extends _{static{d(this,"SystemInfoSkill")}metadata={name:"system_info",description:'Get system information: current date/time (datetime), system stats (general), memory usage (memory), or uptime (uptime). Use "datetime" when the user asks what day/time it is.',riskLevel:"read",version:"1.0.0",inputSchema:{type:"object",properties:{category:{type:"string",enum:["general","memory","uptime","datetime"],description:"Category of system info (use datetime for current date/time)"}},required:["category"]}};async execute(e,t){let s=e.category;switch(s){case"general":return this.getGeneralInfo();case"memory":return this.getMemoryInfo();case"uptime":return this.getUptimeInfo();case"datetime":return this.getDateTimeInfo();default:return{success:!1,error:`Unknown category: "${String(s)}". Valid categories: general, memory, uptime`}}}getGeneralInfo(){let e={nodeVersion:process.version,platform:process.platform,arch:process.arch};return{success:!0,data:e,display:`Node.js ${e.nodeVersion} on ${e.platform} (${e.arch})`}}getMemoryInfo(){let e=process.memoryUsage(),t=d(r=>(r/1024/1024).toFixed(2),"toMB"),s={rss:`${t(e.rss)} MB`,heapTotal:`${t(e.heapTotal)} MB`,heapUsed:`${t(e.heapUsed)} MB`,external:`${t(e.external)} MB`};return{success:!0,data:s,display:`Memory \u2014 RSS: ${s.rss}, Heap: ${s.heapUsed} / ${s.heapTotal}, External: ${s.external}`}}getUptimeInfo(){let e=process.uptime(),t=Math.floor(e/3600),s=Math.floor(e%3600/60),r=Math.floor(e%60),n={uptimeSeconds:e,formatted:`${t}h ${s}m ${r}s`};return{success:!0,data:n,display:`Uptime: ${n.formatted}`}}getDateTimeInfo(){let e=new Date,t={iso:e.toISOString(),date:e.toLocaleDateString("de-DE",{weekday:"long",year:"numeric",month:"long",day:"numeric"}),time:e.toLocaleTimeString("de-DE"),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timestamp:e.getTime()};return{success:!0,data:t,display:`${t.date}, ${t.time} (${t.timezone})`}}}});var Ne,yn=f(()=>{"use strict";D();Ne=class extends _{static{d(this,"WebSearchSkill")}config;metadata={name:"web_search",description:"Search the internet for current information, news, facts, or anything the user asks about that you don't know. Use this whenever you need up-to-date information.",riskLevel:"read",version:"1.1.0",inputSchema:{type:"object",properties:{query:{type:"string",description:"The search query"},count:{type:"number",description:"Number of results to return (default: 5, max: 10)"}},required:["query"]}};constructor(e){super(),this.config=e}async execute(e,t){let s=e.query,r=Math.min(Math.max(1,e.count||5),10);if(!s||typeof s!="string")return{success:!1,error:'Invalid input: "query" must be a non-empty string'};if(!this.config)return{success:!1,error:"Web search is not configured. Run `alfred setup` to configure a search provider."};if((this.config.provider==="brave"||this.config.provider==="tavily")&&!this.config.apiKey)return{success:!1,error:`Web search requires an API key for ${this.config.provider}. Run \`alfred setup\` to configure it.`};try{let o;switch(this.config.provider){case"brave":o=await this.searchBrave(s,r);break;case"searxng":o=await this.searchSearXNG(s,r);break;case"tavily":o=await this.searchTavily(s,r);break;case"duckduckgo":o=await this.searchDuckDuckGo(s,r);break;default:return{success:!1,error:`Unknown search provider: ${this.config.provider}`}}if(o.length===0)return{success:!0,data:{results:[]},display:`No results found for "${s}".`};let i=o.map((a,l)=>`${l+1}. **${a.title}**
313
315
  ${a.url}
314
316
  ${a.snippet}`).join(`
315
317
 
316
318
  `);return{success:!0,data:{query:s,results:o},display:`Search results for "${s}":
317
319
 
318
- ${i}`}}catch(o){return{success:!1,error:`Search failed: ${o instanceof Error?o.message:String(o)}`}}}async searchBrave(e,t){let s=new URL("https://api.search.brave.com/res/v1/web/search");s.searchParams.set("q",e),s.searchParams.set("count",String(t));let r=await fetch(s.toString(),{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":this.config.apiKey}});if(!r.ok)throw new Error(`Brave Search API returned ${r.status}: ${r.statusText}`);return((await r.json()).web?.results??[]).slice(0,t).map(o=>({title:o.title,url:o.url,snippet:o.description}))}async searchSearXNG(e,t){let s=(this.config.baseUrl??"http://localhost:8080").replace(/\/+$/,""),r=new URL(`${s}/search`);r.searchParams.set("q",e),r.searchParams.set("format","json"),r.searchParams.set("pageno","1");let n=await fetch(r.toString(),{headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`SearXNG returned ${n.status}: ${n.statusText}`);return((await n.json()).results??[]).slice(0,t).map(i=>({title:i.title,url:i.url,snippet:i.content}))}async searchTavily(e,t){let s=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:this.config.apiKey,query:e,max_results:t,include_answer:!1})});if(!s.ok)throw new Error(`Tavily API returned ${s.status}: ${s.statusText}`);return((await s.json()).results??[]).slice(0,t).map(n=>({title:n.title,url:n.url,snippet:n.content}))}async searchDuckDuckGo(e,t){let s=new URL("https://html.duckduckgo.com/html/");s.searchParams.set("q",e);let r=await fetch(s.toString(),{headers:{"User-Agent":"Mozilla/5.0 (compatible; Alfred/1.0)"}});if(!r.ok)throw new Error(`DuckDuckGo returned ${r.status}: ${r.statusText}`);let n=await r.text();return this.parseDuckDuckGoHtml(n,t)}parseDuckDuckGoHtml(e,t){let s=[],r=/<a[^>]+class="result__a"[^>]+href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/g,n=/<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/g,o=[],i;for(;(i=r.exec(e))!==null;){let l=i[1],u=this.stripHtml(i[2]).trim(),p=this.extractDdgUrl(l);u&&p&&o.push({url:p,title:u})}let a=[];for(;(i=n.exec(e))!==null;)a.push(this.stripHtml(i[1]).trim());for(let l=0;l<Math.min(o.length,t);l++)s.push({title:o[l].title,url:o[l].url,snippet:a[l]??""});return s}extractDdgUrl(e){try{if(e.includes("uddg=")){let s=new URL(e,"https://duckduckgo.com").searchParams.get("uddg");if(s)return decodeURIComponent(s)}}catch{}return e.startsWith("http")?e:""}stripHtml(e){return e.replace(/<[^>]*>/g,"").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#x27;/g,"'").replace(/&nbsp;/g," ").replace(/\s+/g," ")}}});var De,wn=f(()=>{"use strict";D();De=class extends b{static{d(this,"ReminderSkill")}reminderRepo;metadata={name:"reminder",description:'Set timed reminders that notify the user later. Use when the user says "remind me", "erinnere mich", or asks to be notified about something at a specific time. Prefer triggerAt (absolute time like "14:30" or "2026-02-28 09:00") over delayMinutes \u2014 it is more precise and avoids calculation errors.',riskLevel:"write",version:"3.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["set","list","cancel"],description:"The reminder action to perform"},message:{type:"string",description:"The reminder message (required for set)"},triggerAt:{type:"string",description:'Absolute time for the reminder. Accepts "HH:MM" for today or "YYYY-MM-DD HH:MM" for a specific date. Preferred over delayMinutes for time-specific reminders.'},delayMinutes:{type:"number",description:"Minutes until the reminder triggers. Use triggerAt instead when the user specifies a clock time."},reminderId:{type:"string",description:"The ID of the reminder to cancel (required for cancel)"}},required:["action"]}};constructor(e){super(),this.reminderRepo=e}async execute(e,t){let s=e.action;switch(s){case"set":return this.setReminder(e,t);case"list":return this.listReminders(t);case"cancel":return this.cancelReminder(e);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: set, list, cancel`}}}setReminder(e,t){let s=e.message,r=e.triggerAt,n=e.delayMinutes;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "message" for set action'};let o;if(r&&typeof r=="string"){let p=this.parseTriggerAt(r,t.timezone);if(!p)return{success:!1,error:`Could not parse triggerAt "${r}". Use "HH:MM" for today or "YYYY-MM-DD HH:MM" for a specific date.`};if(p.getTime()<=Date.now())return{success:!1,error:`The time "${r}" is in the past. Please specify a future time.`};o=p}else if(n!==void 0&&typeof n=="number"&&n>0)o=new Date(Date.now()+n*60*1e3);else return{success:!1,error:'Provide either "triggerAt" (e.g. "14:30") or "delayMinutes" (positive number) for set action.'};let i=this.reminderRepo.create(t.userId,t.platform,t.chatId,s,o),a=o.getTime()-Date.now(),l=Math.round(a/6e4),u=o.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",...t.timezone?{timeZone:t.timezone}:{}});return{success:!0,data:{reminderId:i.id,message:s,triggerAt:i.triggerAt},display:`Reminder set (${i.id}): "${s}" at ${u} (in ${l} min)`}}parseTriggerAt(e,t){let s=e.trim(),r=/^(\d{1,2}):(\d{2})$/.exec(s);if(r){let o=parseInt(r[1],10),i=parseInt(r[2],10);return o>23||i>59?void 0:this.buildDateInTimezone(o,i,void 0,t)}let n=/^(\d{4})-(\d{2})-(\d{2})\s+(\d{1,2}):(\d{2})$/.exec(s);if(n){let o=parseInt(n[1],10),i=parseInt(n[2],10)-1,a=parseInt(n[3],10),l=parseInt(n[4],10),u=parseInt(n[5],10);return l>23||u>59||i>11||a>31?void 0:this.buildDateInTimezone(l,u,{year:o,month:i,day:a},t)}}buildDateInTimezone(e,t,s,r){if(!r){let h=s?new Date(s.year,s.month,s.day,e,t,0,0):new Date;return s||h.setHours(e,t,0,0),h}let n=new Date,o=s?new Date(Date.UTC(s.year,s.month,s.day,e,t,0)):new Date(Date.UTC(n.getFullYear(),n.getMonth(),n.getDate(),e,t,0)),i=new Intl.DateTimeFormat("en-CA",{timeZone:r,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});if(!s){let h=i.formatToParts(n),w=parseInt(h.find(A=>A.type==="year").value,10),E=parseInt(h.find(A=>A.type==="month").value,10)-1,T=parseInt(h.find(A=>A.type==="day").value,10),k=new Date(Date.UTC(w,E,T,e,t,0)),_=i.formatToParts(k),v=parseInt(_.find(A=>A.type==="hour").value,10),M=parseInt(_.find(A=>A.type==="minute").value,10),x=(e-v)*60+(t-M);return k=new Date(k.getTime()+x*6e4),k}let a=o,l=i.formatToParts(a),u=parseInt(l.find(h=>h.type==="hour").value,10),p=parseInt(l.find(h=>h.type==="minute").value,10),m=(e-u)*60+(t-p);return a=new Date(a.getTime()+m*6e4),a}listReminders(e){let s=this.reminderRepo.getByUser(e.userId).map(r=>({reminderId:r.id,message:r.message,triggerAt:r.triggerAt}));return{success:!0,data:s,display:s.length===0?"No active reminders.":`Active reminders:
320
+ ${i}`}}catch(o){return{success:!1,error:`Search failed: ${o instanceof Error?o.message:String(o)}`}}}async searchBrave(e,t){let s=new URL("https://api.search.brave.com/res/v1/web/search");s.searchParams.set("q",e),s.searchParams.set("count",String(t));let r=await fetch(s.toString(),{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":this.config.apiKey}});if(!r.ok)throw new Error(`Brave Search API returned ${r.status}: ${r.statusText}`);return((await r.json()).web?.results??[]).slice(0,t).map(o=>({title:o.title,url:o.url,snippet:o.description}))}async searchSearXNG(e,t){let s=(this.config.baseUrl??"http://localhost:8080").replace(/\/+$/,""),r=new URL(`${s}/search`);r.searchParams.set("q",e),r.searchParams.set("format","json"),r.searchParams.set("pageno","1");let n=await fetch(r.toString(),{headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`SearXNG returned ${n.status}: ${n.statusText}`);return((await n.json()).results??[]).slice(0,t).map(i=>({title:i.title,url:i.url,snippet:i.content}))}async searchTavily(e,t){let s=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:this.config.apiKey,query:e,max_results:t,include_answer:!1})});if(!s.ok)throw new Error(`Tavily API returned ${s.status}: ${s.statusText}`);return((await s.json()).results??[]).slice(0,t).map(n=>({title:n.title,url:n.url,snippet:n.content}))}async searchDuckDuckGo(e,t){let s=new URL("https://html.duckduckgo.com/html/");s.searchParams.set("q",e);let r=await fetch(s.toString(),{headers:{"User-Agent":"Mozilla/5.0 (compatible; Alfred/1.0)"}});if(!r.ok)throw new Error(`DuckDuckGo returned ${r.status}: ${r.statusText}`);let n=await r.text();return this.parseDuckDuckGoHtml(n,t)}parseDuckDuckGoHtml(e,t){let s=[],r=/<a[^>]+class="result__a"[^>]+href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/g,n=/<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/g,o=[],i;for(;(i=r.exec(e))!==null;){let l=i[1],u=this.stripHtml(i[2]).trim(),p=this.extractDdgUrl(l);u&&p&&o.push({url:p,title:u})}let a=[];for(;(i=n.exec(e))!==null;)a.push(this.stripHtml(i[1]).trim());for(let l=0;l<Math.min(o.length,t);l++)s.push({title:o[l].title,url:o[l].url,snippet:a[l]??""});return s}extractDdgUrl(e){try{if(e.includes("uddg=")){let s=new URL(e,"https://duckduckgo.com").searchParams.get("uddg");if(s)return decodeURIComponent(s)}}catch{}return e.startsWith("http")?e:""}stripHtml(e){return e.replace(/<[^>]*>/g,"").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#x27;/g,"'").replace(/&nbsp;/g," ").replace(/\s+/g," ")}}});var De,wn=f(()=>{"use strict";D();De=class extends _{static{d(this,"ReminderSkill")}reminderRepo;metadata={name:"reminder",description:'Set timed reminders that notify the user later. Use when the user says "remind me", "erinnere mich", or asks to be notified about something at a specific time. Prefer triggerAt (absolute time like "14:30" or "2026-02-28 09:00") over delayMinutes \u2014 it is more precise and avoids calculation errors.',riskLevel:"write",version:"3.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["set","list","cancel"],description:"The reminder action to perform"},message:{type:"string",description:"The reminder message (required for set)"},triggerAt:{type:"string",description:'Absolute time for the reminder. Accepts "HH:MM" for today or "YYYY-MM-DD HH:MM" for a specific date. Preferred over delayMinutes for time-specific reminders.'},delayMinutes:{type:"number",description:"Minutes until the reminder triggers. Use triggerAt instead when the user specifies a clock time."},reminderId:{type:"string",description:"The ID of the reminder to cancel (required for cancel)"}},required:["action"]}};constructor(e){super(),this.reminderRepo=e}async execute(e,t){let s=e.action;switch(s){case"set":return this.setReminder(e,t);case"list":return this.listReminders(t);case"cancel":return this.cancelReminder(e);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: set, list, cancel`}}}setReminder(e,t){let s=e.message,r=e.triggerAt,n=e.delayMinutes;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "message" for set action'};let o;if(r&&typeof r=="string"){let p=this.parseTriggerAt(r,t.timezone);if(!p)return{success:!1,error:`Could not parse triggerAt "${r}". Use "HH:MM" for today or "YYYY-MM-DD HH:MM" for a specific date.`};if(p.getTime()<=Date.now())return{success:!1,error:`The time "${r}" is in the past. Please specify a future time.`};o=p}else if(n!==void 0&&typeof n=="number"&&n>0)o=new Date(Date.now()+n*60*1e3);else return{success:!1,error:'Provide either "triggerAt" (e.g. "14:30") or "delayMinutes" (positive number) for set action.'};let i=this.reminderRepo.create(t.userId,t.platform,t.chatId,s,o),a=o.getTime()-Date.now(),l=Math.round(a/6e4),u=o.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",...t.timezone?{timeZone:t.timezone}:{}});return{success:!0,data:{reminderId:i.id,message:s,triggerAt:i.triggerAt},display:`Reminder set (${i.id}): "${s}" at ${u} (in ${l} min)`}}parseTriggerAt(e,t){let s=e.trim(),r=/^(\d{1,2}):(\d{2})$/.exec(s);if(r){let o=parseInt(r[1],10),i=parseInt(r[2],10);return o>23||i>59?void 0:this.buildDateInTimezone(o,i,void 0,t)}let n=/^(\d{4})-(\d{2})-(\d{2})\s+(\d{1,2}):(\d{2})$/.exec(s);if(n){let o=parseInt(n[1],10),i=parseInt(n[2],10)-1,a=parseInt(n[3],10),l=parseInt(n[4],10),u=parseInt(n[5],10);return l>23||u>59||i>11||a>31?void 0:this.buildDateInTimezone(l,u,{year:o,month:i,day:a},t)}}buildDateInTimezone(e,t,s,r){if(!r){let h=s?new Date(s.year,s.month,s.day,e,t,0,0):new Date;return s||h.setHours(e,t,0,0),h}let n=new Date,o=s?new Date(Date.UTC(s.year,s.month,s.day,e,t,0)):new Date(Date.UTC(n.getFullYear(),n.getMonth(),n.getDate(),e,t,0)),i=new Intl.DateTimeFormat("en-CA",{timeZone:r,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});if(!s){let h=i.formatToParts(n),w=parseInt(h.find(L=>L.type==="year").value,10),E=parseInt(h.find(L=>L.type==="month").value,10)-1,T=parseInt(h.find(L=>L.type==="day").value,10),k=new Date(Date.UTC(w,E,T,e,t,0)),v=i.formatToParts(k),b=parseInt(v.find(L=>L.type==="hour").value,10),A=parseInt(v.find(L=>L.type==="minute").value,10),x=(e-b)*60+(t-A);return k=new Date(k.getTime()+x*6e4),k}let a=o,l=i.formatToParts(a),u=parseInt(l.find(h=>h.type==="hour").value,10),p=parseInt(l.find(h=>h.type==="minute").value,10),m=(e-u)*60+(t-p);return a=new Date(a.getTime()+m*6e4),a}listReminders(e){let s=this.reminderRepo.getByUser(e.userId).map(r=>({reminderId:r.id,message:r.message,triggerAt:r.triggerAt}));return{success:!0,data:s,display:s.length===0?"No active reminders.":`Active reminders:
319
321
  ${s.map(r=>`- ${r.reminderId}: "${r.message}" (triggers at ${r.triggerAt})`).join(`
320
- `)}`}}cancelReminder(e){let t=e.reminderId;return!t||typeof t!="string"?{success:!1,error:'Missing required field "reminderId" for cancel action'}:this.reminderRepo.cancel(t)?{success:!0,data:{reminderId:t},display:`Reminder "${t}" cancelled.`}:{success:!1,error:`Reminder "${t}" not found`}}}});var Oe,En=f(()=>{"use strict";D();Oe=class extends b{static{d(this,"NoteSkill")}noteRepo;metadata={name:"note",description:"Save, list, search, or delete persistent notes (stored in SQLite). Use when the user wants to write down or retrieve text notes, lists, or ideas.",riskLevel:"write",version:"2.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["save","list","search","delete"],description:"The note action to perform"},title:{type:"string",description:"The note title (required for save)"},content:{type:"string",description:"The note content (required for save)"},noteId:{type:"string",description:"The ID of the note to delete (required for delete)"},query:{type:"string",description:"Search query to filter notes (required for search)"}},required:["action"]}};constructor(e){super(),this.noteRepo=e}async execute(e,t){let s=e.action;switch(s){case"save":return this.saveNote(e,t);case"list":return this.listNotes(t);case"search":return this.searchNotes(e,t);case"delete":return this.deleteNote(e);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: save, list, search, delete`}}}saveNote(e,t){let s=e.title,r=e.content;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "title" for save action'};if(!r||typeof r!="string")return{success:!1,error:'Missing required field "content" for save action'};let n=this.noteRepo.save(t.userId,s,r);return{success:!0,data:{noteId:n.id,title:n.title},display:`Note saved: "${s}"`}}listNotes(e){let t=this.noteRepo.list(e.userId);if(t.length===0)return{success:!0,data:[],display:"No notes found."};let s=t.map(r=>`- **${r.title}** (${r.id.slice(0,8)}\u2026)
322
+ `)}`}}cancelReminder(e){let t=e.reminderId;return!t||typeof t!="string"?{success:!1,error:'Missing required field "reminderId" for cancel action'}:this.reminderRepo.cancel(t)?{success:!0,data:{reminderId:t},display:`Reminder "${t}" cancelled.`}:{success:!1,error:`Reminder "${t}" not found`}}}});var Oe,En=f(()=>{"use strict";D();Oe=class extends _{static{d(this,"NoteSkill")}noteRepo;metadata={name:"note",description:"Save, list, search, or delete persistent notes (stored in SQLite). Use when the user wants to write down or retrieve text notes, lists, or ideas.",riskLevel:"write",version:"2.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["save","list","search","delete"],description:"The note action to perform"},title:{type:"string",description:"The note title (required for save)"},content:{type:"string",description:"The note content (required for save)"},noteId:{type:"string",description:"The ID of the note to delete (required for delete)"},query:{type:"string",description:"Search query to filter notes (required for search)"}},required:["action"]}};constructor(e){super(),this.noteRepo=e}async execute(e,t){let s=e.action;switch(s){case"save":return this.saveNote(e,t);case"list":return this.listNotes(t);case"search":return this.searchNotes(e,t);case"delete":return this.deleteNote(e);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: save, list, search, delete`}}}saveNote(e,t){let s=e.title,r=e.content;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "title" for save action'};if(!r||typeof r!="string")return{success:!1,error:'Missing required field "content" for save action'};let n=this.noteRepo.save(t.userId,s,r);return{success:!0,data:{noteId:n.id,title:n.title},display:`Note saved: "${s}"`}}listNotes(e){let t=this.noteRepo.list(e.userId);if(t.length===0)return{success:!0,data:[],display:"No notes found."};let s=t.map(r=>`- **${r.title}** (${r.id.slice(0,8)}\u2026)
321
323
  ${r.content.slice(0,100)}${r.content.length>100?"\u2026":""}`).join(`
322
324
  `);return{success:!0,data:t,display:`${t.length} note(s):
323
325
  ${s}`}}searchNotes(e,t){let s=e.query;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "query" for search action'};let r=this.noteRepo.search(t.userId,s);if(r.length===0)return{success:!0,data:[],display:`No notes matching "${s}".`};let n=r.map(o=>`- **${o.title}** (${o.id.slice(0,8)}\u2026)
324
326
  ${o.content.slice(0,100)}${o.content.length>100?"\u2026":""}`).join(`
325
327
  `);return{success:!0,data:r,display:`Found ${r.length} note(s):
326
- ${n}`}}deleteNote(e){let t=e.noteId;return!t||typeof t!="string"?{success:!1,error:'Missing required field "noteId" for delete action'}:this.noteRepo.delete(t)?{success:!0,data:{noteId:t},display:"Note deleted."}:{success:!1,error:`Note "${t}" not found`}}}});var $i,Ce,Tn=f(()=>{"use strict";D();$i={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Foggy",48:"Depositing rime fog",51:"Light drizzle",53:"Moderate drizzle",55:"Dense drizzle",61:"Slight rain",63:"Moderate rain",65:"Heavy rain",71:"Slight snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Slight rain showers",81:"Moderate rain showers",82:"Violent rain showers",85:"Slight snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with slight hail",99:"Thunderstorm with heavy hail"},Ce=class extends b{static{d(this,"WeatherSkill")}metadata={name:"weather",description:"Get current weather for any location. Uses Open-Meteo (free, no API key). Use when the user asks about weather, temperature, or conditions somewhere.",riskLevel:"read",version:"2.0.0",inputSchema:{type:"object",properties:{location:{type:"string",description:'City or place name (e.g. "Vienna", "New York", "Tokyo")'}},required:["location"]}};async execute(e,t){let s=e.location;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "location"'};try{let r=await this.geocode(s);if(!r)return{success:!1,error:`Location "${s}" not found`};let n=await this.fetchWeather(r.latitude,r.longitude),o=$i[n.weathercode]??`Code ${n.weathercode}`,i=r.admin1?`${r.name}, ${r.admin1}, ${r.country}`:`${r.name}, ${r.country}`,a={location:i,temperature:n.temperature,unit:"\xB0C",condition:o,windSpeed:n.windspeed,windDirection:n.winddirection,isDay:n.is_day===1},l=`${i}: ${n.temperature}\xB0C, ${o}
328
+ ${n}`}}deleteNote(e){let t=e.noteId;return!t||typeof t!="string"?{success:!1,error:'Missing required field "noteId" for delete action'}:this.noteRepo.delete(t)?{success:!0,data:{noteId:t},display:"Note deleted."}:{success:!1,error:`Note "${t}" not found`}}}});var $i,Ce,Tn=f(()=>{"use strict";D();$i={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Foggy",48:"Depositing rime fog",51:"Light drizzle",53:"Moderate drizzle",55:"Dense drizzle",61:"Slight rain",63:"Moderate rain",65:"Heavy rain",71:"Slight snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Slight rain showers",81:"Moderate rain showers",82:"Violent rain showers",85:"Slight snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with slight hail",99:"Thunderstorm with heavy hail"},Ce=class extends _{static{d(this,"WeatherSkill")}metadata={name:"weather",description:"Get current weather for any location. Uses Open-Meteo (free, no API key). Use when the user asks about weather, temperature, or conditions somewhere.",riskLevel:"read",version:"2.0.0",inputSchema:{type:"object",properties:{location:{type:"string",description:'City or place name (e.g. "Vienna", "New York", "Tokyo")'}},required:["location"]}};async execute(e,t){let s=e.location;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "location"'};try{let r=await this.geocode(s);if(!r)return{success:!1,error:`Location "${s}" not found`};let n=await this.fetchWeather(r.latitude,r.longitude),o=$i[n.weathercode]??`Code ${n.weathercode}`,i=r.admin1?`${r.name}, ${r.admin1}, ${r.country}`:`${r.name}, ${r.country}`,a={location:i,temperature:n.temperature,unit:"\xB0C",condition:o,windSpeed:n.windspeed,windDirection:n.winddirection,isDay:n.is_day===1},l=`${i}: ${n.temperature}\xB0C, ${o}
327
329
  Wind: ${n.windspeed} km/h`;return{success:!0,data:a,display:l}}catch(r){return{success:!1,error:`Weather fetch failed: ${r instanceof Error?r.message:String(r)}`}}}async geocode(e){let t=`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(e)}&count=1&language=en&format=json`,s=await fetch(t);if(!s.ok)throw new Error(`Geocoding API returned ${s.status}`);return(await s.json()).results?.[0]}async fetchWeather(e,t){let s=`https://api.open-meteo.com/v1/forecast?latitude=${e}&longitude=${t}&current_weather=true&timezone=auto`,r=await fetch(s);if(!r.ok)throw new Error(`Weather API returned ${r.status}`);return(await r.json()).current_weather}}});import{exec as Ii}from"node:child_process";function _n(c){return c.length>bn?c.slice(0,bn)+`
328
- [output truncated]`:c}var Ai,bn,Ue,Sn=f(()=>{"use strict";D();Ai=3e4,bn=1e4;d(_n,"truncate");Ue=class extends b{static{d(this,"ShellSkill")}metadata={name:"shell",description:"Execute shell commands on the host system. Use this for ANY task involving files, folders, system operations, or running programs: ls, cat, find, file, du, mkdir, cp, mv, grep, etc. When the user asks about their documents, files, or anything on disk \u2014 use this tool.",riskLevel:"admin",version:"1.0.0",inputSchema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},timeout:{type:"number",description:"Timeout in milliseconds (default: 30000)"},cwd:{type:"string",description:"Working directory for the command"}},required:["command"]}};async execute(e,t){let s=e.command;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "command"'};let r=[/\brm\s+-rf\s+\/(?:\s|$)/,/:(){ :|:& };:/,/>\s*\/dev\/sd[a-z]/,/\bmkfs\b/,/\bdd\s+.*of=\/dev/];for(let i of r)if(i.test(s))return{success:!1,error:"Command blocked: potentially destructive system operation"};let n=typeof e.timeout=="number"&&e.timeout>0?e.timeout:Ai,o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:void 0;try{let{stdout:i,stderr:a,exitCode:l}=await this.run(s,n,o),u=[];return i&&u.push(`stdout:
330
+ [output truncated]`:c}var Ai,bn,Ue,Sn=f(()=>{"use strict";D();Ai=3e4,bn=1e4;d(_n,"truncate");Ue=class extends _{static{d(this,"ShellSkill")}metadata={name:"shell",description:"Execute shell commands on the host system. Use this for ANY task involving files, folders, system operations, or running programs: ls, cat, find, file, du, mkdir, cp, mv, grep, etc. When the user asks about their documents, files, or anything on disk \u2014 use this tool.",riskLevel:"admin",version:"1.0.0",inputSchema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},timeout:{type:"number",description:"Timeout in milliseconds (default: 30000)"},cwd:{type:"string",description:"Working directory for the command"}},required:["command"]}};async execute(e,t){let s=e.command;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "command"'};let r=[/\brm\s+-rf\s+\/(?:\s|$)/,/:(){ :|:& };:/,/>\s*\/dev\/sd[a-z]/,/\bmkfs\b/,/\bdd\s+.*of=\/dev/];for(let i of r)if(i.test(s))return{success:!1,error:"Command blocked: potentially destructive system operation"};let n=typeof e.timeout=="number"&&e.timeout>0?e.timeout:Ai,o=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:void 0;try{let{stdout:i,stderr:a,exitCode:l}=await this.run(s,n,o),u=[];return i&&u.push(`stdout:
329
331
  ${_n(i)}`),a&&u.push(`stderr:
330
332
  ${_n(a)}`),u.length===0&&u.push("(no output)"),u.push(`exit code: ${l}`),{success:l===0,data:{stdout:i,stderr:a,exitCode:l},display:u.join(`
331
333
 
332
- `),...l!==0&&{error:`Command exited with code ${l}`}}}catch(i){return{success:!1,error:`Shell execution failed: ${i instanceof Error?i.message:String(i)}`}}}run(e,t,s){return new Promise(r=>{Ii(e,{timeout:t,cwd:s},(n,o,i)=>{let a=n&&"code"in n&&typeof n.code=="number"?n.code:n?1:0;r({stdout:typeof o=="string"?o:"",stderr:typeof i=="string"?i:"",exitCode:a})})})}}});var Pe,kn=f(()=>{"use strict";D();Pe=class extends b{static{d(this,"MemorySkill")}memoryRepo;embeddingService;metadata={name:"memory",description:"Store and retrieve persistent memories. Use this to remember user preferences, facts, and important information across conversations.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["save","recall","search","list","delete","semantic_search"],description:"The memory action to perform"},key:{type:"string",description:"The memory key/label"},value:{type:"string",description:"The value to remember (for save)"},category:{type:"string",description:"Optional category (for save/list)"},query:{type:"string",description:"Search query (for search)"}},required:["action"]}};constructor(e,t){super(),this.memoryRepo=e,this.embeddingService=t}async execute(e,t){let s=e.action;switch(s){case"save":return this.saveMemory(e,t);case"recall":return this.recallMemory(e,t);case"search":return this.searchMemories(e,t);case"list":return this.listMemories(e,t);case"delete":return this.deleteMemory(e,t);case"semantic_search":return this.semanticSearchMemories(e,t);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: save, recall, search, list, delete, semantic_search`}}}saveMemory(e,t){let s=e.key,r=e.value,n=e.category;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "key" for save action'};if(!r||typeof r!="string")return{success:!1,error:'Missing required field "value" for save action'};let o=this.memoryRepo.save(t.userId,s,r,n??"general");return this.embeddingService&&this.embeddingService.embedAndStore(t.userId,`${s}: ${r}`,"memory",s).catch(()=>{}),{success:!0,data:o,display:`Remembered "${s}" = "${r}" (category: ${o.category})`}}recallMemory(e,t){let s=e.key;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "key" for recall action'};let r=this.memoryRepo.recall(t.userId,s);return r?{success:!0,data:r,display:`${s} = "${r.value}" (category: ${r.category}, updated: ${r.updatedAt})`}:{success:!0,data:null,display:`No memory found for key "${s}".`}}searchMemories(e,t){let s=e.query;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "query" for search action'};let r=this.memoryRepo.search(t.userId,s);return{success:!0,data:r,display:r.length===0?`No memories matching "${s}".`:`Found ${r.length} memory(ies):
334
+ `),...l!==0&&{error:`Command exited with code ${l}`}}}catch(i){return{success:!1,error:`Shell execution failed: ${i instanceof Error?i.message:String(i)}`}}}run(e,t,s){return new Promise(r=>{Ii(e,{timeout:t,cwd:s},(n,o,i)=>{let a=n&&"code"in n&&typeof n.code=="number"?n.code:n?1:0;r({stdout:typeof o=="string"?o:"",stderr:typeof i=="string"?i:"",exitCode:a})})})}}});var Pe,kn=f(()=>{"use strict";D();Pe=class extends _{static{d(this,"MemorySkill")}memoryRepo;embeddingService;metadata={name:"memory",description:"Store and retrieve persistent memories. Use this to remember user preferences, facts, and important information across conversations.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["save","recall","search","list","delete","semantic_search"],description:"The memory action to perform"},key:{type:"string",description:"The memory key/label"},value:{type:"string",description:"The value to remember (for save)"},category:{type:"string",description:"Optional category (for save/list)"},query:{type:"string",description:"Search query (for search)"}},required:["action"]}};constructor(e,t){super(),this.memoryRepo=e,this.embeddingService=t}async execute(e,t){let s=e.action;switch(s){case"save":return this.saveMemory(e,t);case"recall":return this.recallMemory(e,t);case"search":return this.searchMemories(e,t);case"list":return this.listMemories(e,t);case"delete":return this.deleteMemory(e,t);case"semantic_search":return this.semanticSearchMemories(e,t);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: save, recall, search, list, delete, semantic_search`}}}saveMemory(e,t){let s=e.key,r=e.value,n=e.category;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "key" for save action'};if(!r||typeof r!="string")return{success:!1,error:'Missing required field "value" for save action'};let o=this.memoryRepo.save(t.userId,s,r,n??"general");return this.embeddingService&&this.embeddingService.embedAndStore(t.userId,`${s}: ${r}`,"memory",s).catch(()=>{}),{success:!0,data:o,display:`Remembered "${s}" = "${r}" (category: ${o.category})`}}recallMemory(e,t){let s=e.key;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "key" for recall action'};let r=this.memoryRepo.recall(t.userId,s);return r?{success:!0,data:r,display:`${s} = "${r.value}" (category: ${r.category}, updated: ${r.updatedAt})`}:{success:!0,data:null,display:`No memory found for key "${s}".`}}searchMemories(e,t){let s=e.query;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "query" for search action'};let r=this.memoryRepo.search(t.userId,s);return{success:!0,data:r,display:r.length===0?`No memories matching "${s}".`:`Found ${r.length} memory(ies):
333
335
  ${r.map(n=>`- ${n.key}: "${n.value}"`).join(`
334
336
  `)}`}}listMemories(e,t){let s=e.category,r=s&&typeof s=="string"?this.memoryRepo.listByCategory(t.userId,s):this.memoryRepo.listAll(t.userId),n=s?`in category "${s}"`:"total";return{success:!0,data:r,display:r.length===0?`No memories found${s?` in category "${s}"`:""}.`:`${r.length} memory(ies) ${n}:
335
337
  ${r.map(o=>`- [${o.category}] ${o.key}: "${o.value}"`).join(`
336
338
  `)}`}}deleteMemory(e,t){let s=e.key;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "key" for delete action'};let r=this.memoryRepo.delete(t.userId,s);return{success:!0,data:{key:s,deleted:r},display:r?`Memory "${s}" deleted.`:`No memory found for key "${s}".`}}async semanticSearchMemories(e,t){let s=e.query;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "query" for semantic_search action'};if(!this.embeddingService)return this.searchMemories(e,t);let r=await this.embeddingService.semanticSearch(t.userId,s,10);return r.length===0?this.searchMemories(e,t):{success:!0,data:r,display:`Found ${r.length} semantically related memory(ies):
337
339
  ${r.map(n=>`- ${n.key}: "${n.value}" (score: ${n.score.toFixed(2)})`).join(`
338
- `)}`}}}});var Ri,Li,Mi,Fe,vn=f(()=>{"use strict";D();zs();Ri=5,Li=15,Mi=12e4,Fe=class extends b{static{d(this,"DelegateSkill")}llm;skillRegistry;skillSandbox;securityManager;metadata={name:"delegate",description:'Delegate a complex sub-task to an autonomous sub-agent that has full tool access. The sub-agent can use shell, web search, calculator, memory, email, and all other tools. Use when a task is independent enough to run in parallel or when it requires a focused, multi-step workflow (e.g. "research X and summarize", "find all TODO files and list them", "check the weather and draft a packing list"). Control depth with max_iterations (default 5, max 15).',riskLevel:"write",version:"3.0.0",timeoutMs:Mi,inputSchema:{type:"object",properties:{task:{type:"string",description:"The task to delegate to the sub-agent. Be specific about what you want."},context:{type:"string",description:"Additional context the sub-agent needs (optional)"},max_iterations:{type:"number",description:"Max tool iterations (1-15). Use higher values for complex multi-step tasks. Default: 5."}},required:["task"]}};onProgress;constructor(e,t,s,r){super(),this.llm=e,this.skillRegistry=t,this.skillSandbox=s,this.securityManager=r}setProgressCallback(e){this.onProgress=e}createTracker(){return new ge(this.onProgress)}async execute(e,t){let s=e.task,r=e.context;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "task"'};let n=e.max_iterations,o=n?Math.max(1,Math.min(Li,Math.round(n))):Ri,i=t.onProgress??this.onProgress,a=t.tracker?t.tracker:new ge(i);a.ping("starting",{maxIterations:o});let l=this.buildSubAgentTools(),u="You are a sub-agent of Alfred, a personal AI assistant. Complete the assigned task using the tools available to you. Work step by step: use tools to gather information, then synthesize a clear result. Be concise and return only the final answer when done.",p=s;r&&typeof r=="string"&&(p=`${s}
340
+ `)}`}}}});var Ri,Li,Mi,Fe,vn=f(()=>{"use strict";D();zs();Ri=5,Li=15,Mi=12e4,Fe=class extends _{static{d(this,"DelegateSkill")}llm;skillRegistry;skillSandbox;securityManager;metadata={name:"delegate",description:'Delegate a complex sub-task to an autonomous sub-agent that has full tool access. The sub-agent can use shell, web search, calculator, memory, email, and all other tools. Use when a task is independent enough to run in parallel or when it requires a focused, multi-step workflow (e.g. "research X and summarize", "find all TODO files and list them", "check the weather and draft a packing list"). Control depth with max_iterations (default 5, max 15).',riskLevel:"write",version:"3.0.0",timeoutMs:Mi,inputSchema:{type:"object",properties:{task:{type:"string",description:"The task to delegate to the sub-agent. Be specific about what you want."},context:{type:"string",description:"Additional context the sub-agent needs (optional)"},max_iterations:{type:"number",description:"Max tool iterations (1-15). Use higher values for complex multi-step tasks. Default: 5."}},required:["task"]}};onProgress;constructor(e,t,s,r){super(),this.llm=e,this.skillRegistry=t,this.skillSandbox=s,this.securityManager=r}setProgressCallback(e){this.onProgress=e}createTracker(){return new ge(this.onProgress)}async execute(e,t){let s=e.task,r=e.context;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "task"'};let n=e.max_iterations,o=n?Math.max(1,Math.min(Li,Math.round(n))):Ri,i=t.onProgress??this.onProgress,a=t.tracker?t.tracker:new ge(i);a.ping("starting",{maxIterations:o});let l=this.buildSubAgentTools(),u="You are a sub-agent of Alfred, a personal AI assistant. Complete the assigned task using the tools available to you. Work step by step: use tools to gather information, then synthesize a clear result. Be concise and return only the final answer when done.",p=s;r&&typeof r=="string"&&(p=`${s}
339
341
 
340
- Additional context: ${r}`);let m=[{role:"user",content:p}];try{let h=0,w=0,E=0;for(;;){a.ping("llm_call",{iteration:h,maxIterations:o});let T=await this.llm.complete({messages:m,system:u,tools:l.length>0?l:void 0,maxTokens:2048,tier:"strong"});if(w+=T.usage.inputTokens,E+=T.usage.outputTokens,a.ping("processing",{iteration:h,maxIterations:o}),!T.toolCalls||T.toolCalls.length===0||h>=o)return a.ping("done",{iteration:h,maxIterations:o}),{success:!0,data:{response:T.content,iterations:h,usage:{inputTokens:w,outputTokens:E}},display:T.content};h++;let k=[];T.content&&k.push({type:"text",text:T.content});for(let v of T.toolCalls)k.push({type:"tool_use",id:v.id,name:v.name,input:v.input});m.push({role:"assistant",content:k});let _=[];for(let v of T.toolCalls){a.ping("tool_call",{iteration:h,maxIterations:o,tool:v.name});let M=await this.executeSubAgentTool(v,t);_.push({type:"tool_result",tool_use_id:v.id,content:M.content,is_error:M.isError})}m.push({role:"user",content:_})}}catch(h){return{success:!1,error:`Sub-agent failed: ${h instanceof Error?h.message:String(h)}`}}}buildSubAgentTools(){return this.skillRegistry?this.skillRegistry.getAll().filter(e=>e.metadata.name!=="delegate").map(e=>({name:e.metadata.name,description:e.metadata.description,inputSchema:e.metadata.inputSchema})):[]}async executeSubAgentTool(e,t){let s=this.skillRegistry?.get(e.name);if(!s)return{content:`Error: Unknown tool "${e.name}"`,isError:!0};if(this.securityManager){let r=this.securityManager.evaluate({userId:t.userId,action:e.name,riskLevel:s.metadata.riskLevel,platform:t.platform,chatId:t.chatId,chatType:t.chatType});if(!r.allowed)return{content:`Access denied: ${r.reason}`,isError:!0}}if(this.skillSandbox){let r=await this.skillSandbox.execute(s,e.input,t);return{content:r.display??(r.success?JSON.stringify(r.data):r.error??"Unknown error"),isError:!r.success}}try{let r=await s.execute(e.input,t);return{content:r.display??(r.success?JSON.stringify(r.data):r.error??"Unknown error"),isError:!r.success}}catch(r){return{content:`Skill execution failed: ${r instanceof Error?r.message:String(r)}`,isError:!0}}}}});var je,xn=f(()=>{"use strict";D();je=class extends b{static{d(this,"EmailSkill")}config;metadata={name:"email",description:"Access the user's email: check inbox, read messages, search emails, or send new emails. Use when the user asks about their emails or wants to send one.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["inbox","read","search","send"],description:"The email action to perform"},count:{type:"number",description:"Number of emails to fetch (for inbox, default: 10)"},messageId:{type:"string",description:"Message sequence number to read (for read action)"},query:{type:"string",description:"Search query (for search action)"},to:{type:"string",description:"Recipient email address (for send action)"},subject:{type:"string",description:"Email subject (for send action)"},body:{type:"string",description:"Email body text (for send action)"}},required:["action"]}};constructor(e){super(),this.config=e}async execute(e,t){if(!this.config)return{success:!1,error:"Email is not configured. Run `alfred setup` to configure email access."};let s=e.action;try{switch(s){case"inbox":return await this.fetchInbox(e.count);case"read":return await this.readMessage(e.messageId);case"search":return await this.searchMessages(e.query,e.count);case"send":return await this.sendMessage(e.to,e.subject,e.body);default:return{success:!1,error:`Unknown action: ${s}. Use: inbox, read, search, send`}}}catch(r){return{success:!1,error:`Email error: ${r instanceof Error?r.message:String(r)}`}}}async fetchInbox(e){let t=Math.min(Math.max(1,e??10),50),{ImapFlow:s}=await import("imapflow"),r=new s({host:this.config.imap.host,port:this.config.imap.port,secure:this.config.imap.secure,auth:this.config.auth,logger:!1});try{await r.connect();let n=await r.getMailboxLock("INBOX");try{let o=[],i=r.mailbox,a=i&&typeof i=="object"?i.exists??0:0;if(a===0)return{success:!0,data:{messages:[]},display:"Inbox is empty."};let u=`${Math.max(1,a-t+1)}:*`;for await(let h of r.fetch(u,{envelope:!0,flags:!0})){let w=h.envelope?.from?.[0],E=w?w.name?`${w.name} <${w.address}>`:w.address??"unknown":"unknown";o.push({seq:h.seq,from:E,subject:h.envelope?.subject??"(no subject)",date:h.envelope?.date?.toISOString()??"",seen:h.flags?.has("\\Seen")??!1})}o.reverse();let p=o.length===0?"No messages found.":o.map((h,w)=>{let E=h.seen?"":" [UNREAD]";return`${w+1}. [#${h.seq}]${E} ${h.subject}
342
+ Additional context: ${r}`);let m=[{role:"user",content:p}];try{let h=0,w=0,E=0;for(;;){a.ping("llm_call",{iteration:h,maxIterations:o});let T=await this.llm.complete({messages:m,system:u,tools:l.length>0?l:void 0,maxTokens:2048,tier:"strong"});if(w+=T.usage.inputTokens,E+=T.usage.outputTokens,a.ping("processing",{iteration:h,maxIterations:o}),!T.toolCalls||T.toolCalls.length===0||h>=o)return a.ping("done",{iteration:h,maxIterations:o}),{success:!0,data:{response:T.content,iterations:h,usage:{inputTokens:w,outputTokens:E}},display:T.content};h++;let k=[];T.content&&k.push({type:"text",text:T.content});for(let b of T.toolCalls)k.push({type:"tool_use",id:b.id,name:b.name,input:b.input});m.push({role:"assistant",content:k});let v=[];for(let b of T.toolCalls){a.ping("tool_call",{iteration:h,maxIterations:o,tool:b.name});let A=await this.executeSubAgentTool(b,t);v.push({type:"tool_result",tool_use_id:b.id,content:A.content,is_error:A.isError})}m.push({role:"user",content:v})}}catch(h){return{success:!1,error:`Sub-agent failed: ${h instanceof Error?h.message:String(h)}`}}}buildSubAgentTools(){return this.skillRegistry?this.skillRegistry.getAll().filter(e=>e.metadata.name!=="delegate").map(e=>({name:e.metadata.name,description:e.metadata.description,inputSchema:e.metadata.inputSchema})):[]}async executeSubAgentTool(e,t){let s=this.skillRegistry?.get(e.name);if(!s)return{content:`Error: Unknown tool "${e.name}"`,isError:!0};if(this.securityManager){let r=this.securityManager.evaluate({userId:t.userId,action:e.name,riskLevel:s.metadata.riskLevel,platform:t.platform,chatId:t.chatId,chatType:t.chatType});if(!r.allowed)return{content:`Access denied: ${r.reason}`,isError:!0}}if(this.skillSandbox){let r=await this.skillSandbox.execute(s,e.input,t);return{content:r.display??(r.success?JSON.stringify(r.data):r.error??"Unknown error"),isError:!r.success}}try{let r=await s.execute(e.input,t);return{content:r.display??(r.success?JSON.stringify(r.data):r.error??"Unknown error"),isError:!r.success}}catch(r){return{content:`Skill execution failed: ${r instanceof Error?r.message:String(r)}`,isError:!0}}}}});var je,xn=f(()=>{"use strict";D();je=class extends _{static{d(this,"EmailSkill")}config;metadata={name:"email",description:"Access the user's email: check inbox, read messages, search emails, or send new emails. Use when the user asks about their emails or wants to send one.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["inbox","read","search","send"],description:"The email action to perform"},count:{type:"number",description:"Number of emails to fetch (for inbox, default: 10)"},messageId:{type:"string",description:"Message sequence number to read (for read action)"},query:{type:"string",description:"Search query (for search action)"},to:{type:"string",description:"Recipient email address (for send action)"},subject:{type:"string",description:"Email subject (for send action)"},body:{type:"string",description:"Email body text (for send action)"}},required:["action"]}};constructor(e){super(),this.config=e}async execute(e,t){if(!this.config)return{success:!1,error:"Email is not configured. Run `alfred setup` to configure email access."};let s=e.action;try{switch(s){case"inbox":return await this.fetchInbox(e.count);case"read":return await this.readMessage(e.messageId);case"search":return await this.searchMessages(e.query,e.count);case"send":return await this.sendMessage(e.to,e.subject,e.body);default:return{success:!1,error:`Unknown action: ${s}. Use: inbox, read, search, send`}}}catch(r){return{success:!1,error:`Email error: ${r instanceof Error?r.message:String(r)}`}}}async fetchInbox(e){let t=Math.min(Math.max(1,e??10),50),{ImapFlow:s}=await import("imapflow"),r=new s({host:this.config.imap.host,port:this.config.imap.port,secure:this.config.imap.secure,auth:this.config.auth,logger:!1});try{await r.connect();let n=await r.getMailboxLock("INBOX");try{let o=[],i=r.mailbox,a=i&&typeof i=="object"?i.exists??0:0;if(a===0)return{success:!0,data:{messages:[]},display:"Inbox is empty."};let u=`${Math.max(1,a-t+1)}:*`;for await(let h of r.fetch(u,{envelope:!0,flags:!0})){let w=h.envelope?.from?.[0],E=w?w.name?`${w.name} <${w.address}>`:w.address??"unknown":"unknown";o.push({seq:h.seq,from:E,subject:h.envelope?.subject??"(no subject)",date:h.envelope?.date?.toISOString()??"",seen:h.flags?.has("\\Seen")??!1})}o.reverse();let p=o.length===0?"No messages found.":o.map((h,w)=>{let E=h.seen?"":" [UNREAD]";return`${w+1}. [#${h.seq}]${E} ${h.subject}
341
343
  From: ${h.from}
342
344
  Date: ${h.date}`}).join(`
343
345
 
@@ -364,20 +366,20 @@ Message ID: ${o.messageId}`}}extractTextBody(e){let t=e.split(/\r?\n\r?\n/);if(t
364
366
  \r
365
367
  `);if(u>=0)return this.decodeBody(i.slice(u+4))}}return this.decodeBody(t.slice(1).join(`
366
368
 
367
- `).slice(0,5e3))}decodeBody(e){return e.replace(/=\r?\n/g,"").replace(/=([0-9A-Fa-f]{2})/g,(t,s)=>String.fromCharCode(parseInt(s,16))).trim()}}});var $n,Be,In=f(()=>{"use strict";D();$n=1e5,Be=class extends b{static{d(this,"HttpSkill")}metadata={name:"http",description:"Make HTTP requests to fetch web pages or call REST APIs. Use when you need to read a URL, call an API endpoint, or fetch data from the web. Supports GET, POST, PUT, PATCH, DELETE methods.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{url:{type:"string",description:"The URL to request"},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method (default: GET)"},headers:{type:"object",description:"Request headers as key-value pairs (optional)"},body:{type:"string",description:"Request body for POST/PUT/PATCH (optional)"}},required:["url"]}};async execute(e,t){let s=e.url,r=(e.method??"GET").toUpperCase(),n=e.headers,o=e.body;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "url"'};let i;try{i=new URL(s)}catch{return{success:!1,error:`Invalid URL: "${s}"`}}if(i.protocol!=="http:"&&i.protocol!=="https:")return{success:!1,error:`Unsupported URL scheme "${i.protocol}". Only http: and https: are allowed.`};try{let a={method:r,headers:{"User-Agent":"Alfred/1.0",...n??{}},signal:AbortSignal.timeout(15e3)};o&&["POST","PUT","PATCH"].includes(r)&&(a.body=o,!n?.["Content-Type"]&&!n?.["content-type"]&&(a.headers["Content-Type"]="application/json"));let l=await fetch(s,a),u=l.headers.get("content-type")??"",p=await l.text(),m=p.length>$n,h=m?p.slice(0,$n)+`
369
+ `).slice(0,5e3))}decodeBody(e){return e.replace(/=\r?\n/g,"").replace(/=([0-9A-Fa-f]{2})/g,(t,s)=>String.fromCharCode(parseInt(s,16))).trim()}}});var $n,Be,In=f(()=>{"use strict";D();$n=1e5,Be=class extends _{static{d(this,"HttpSkill")}metadata={name:"http",description:"Make HTTP requests to fetch web pages or call REST APIs. Use when you need to read a URL, call an API endpoint, or fetch data from the web. Supports GET, POST, PUT, PATCH, DELETE methods.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{url:{type:"string",description:"The URL to request"},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method (default: GET)"},headers:{type:"object",description:"Request headers as key-value pairs (optional)"},body:{type:"string",description:"Request body for POST/PUT/PATCH (optional)"}},required:["url"]}};async execute(e,t){let s=e.url,r=(e.method??"GET").toUpperCase(),n=e.headers,o=e.body;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "url"'};let i;try{i=new URL(s)}catch{return{success:!1,error:`Invalid URL: "${s}"`}}if(i.protocol!=="http:"&&i.protocol!=="https:")return{success:!1,error:`Unsupported URL scheme "${i.protocol}". Only http: and https: are allowed.`};try{let a={method:r,headers:{"User-Agent":"Alfred/1.0",...n??{}},signal:AbortSignal.timeout(15e3)};o&&["POST","PUT","PATCH"].includes(r)&&(a.body=o,!n?.["Content-Type"]&&!n?.["content-type"]&&(a.headers["Content-Type"]="application/json"));let l=await fetch(s,a),u=l.headers.get("content-type")??"",p=await l.text(),m=p.length>$n,h=m?p.slice(0,$n)+`
368
370
 
369
371
  [... truncated]`:p,w=h;u.includes("text/html")&&(w=this.stripHtml(h).slice(0,1e4));let E={status:l.status,statusText:l.statusText,contentType:u,bodyLength:p.length,truncated:m,body:h};return l.ok?{success:!0,data:E,display:`HTTP ${l.status} OK (${p.length} bytes)
370
372
 
371
373
  ${w.slice(0,5e3)}`}:{success:!0,data:E,display:`HTTP ${l.status} ${l.statusText}
372
374
 
373
- ${w.slice(0,2e3)}`}}catch(a){return{success:!1,error:`HTTP request failed: ${a instanceof Error?a.message:String(a)}`}}}stripHtml(e){return e.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#x27;/g,"'").replace(/&nbsp;/g," ").replace(/\s+/g," ").trim()}}});import P from"node:fs";import vt from"node:path";var Ks,We,An=f(()=>{"use strict";D();Ks=5e5,We=class extends b{static{d(this,"FileSkill")}metadata={name:"file",description:'Read, write, move, or copy files. Use for reading file contents, writing text to files, saving binary data, listing directory contents, moving/copying files, or getting file info. Prefer this over shell for file operations. When a user sends a file attachment, it is saved to the inbox \u2014 use "move" to relocate it.',riskLevel:"write",version:"2.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","write","write_binary","append","list","info","exists","move","copy","delete"],description:"The file operation to perform"},path:{type:"string",description:"Absolute or relative file/directory path (~ expands to home)"},destination:{type:"string",description:"Destination path for move/copy actions (~ expands to home)"},content:{type:"string",description:"Content to write (required for write/append; base64-encoded for write_binary)"}},required:["action","path"]}};async execute(e,t){let s=e.action,r=e.path,n=e.content,o=e.destination;if(!s||!r)return{success:!1,error:'Missing required fields "action" and "path"'};if((s==="write"||s==="write_binary"||s==="append")&&!n)return{success:!1,error:`Missing "content" field for "${s}" action. You must provide the file content.`};let i=this.resolvePath(r),a=i.toLowerCase();if(["/etc/shadow","/etc/passwd","/proc/","/sys/","/dev/","c:\\windows\\system32","c:\\windows\\syswow64"].some(u=>a.startsWith(u)||a===u.replace(/\/$/,"")))return{success:!1,error:"Access to system directories/files is blocked for security"};switch(s){case"read":return this.readFile(i);case"write":return this.writeFile(i,n);case"write_binary":return this.writeBinaryFile(i,n);case"append":return this.appendFile(i,n);case"list":return this.listDir(i);case"info":return this.fileInfo(i);case"exists":return this.fileExists(i);case"move":return this.moveFile(i,o);case"copy":return this.copyFile(i,o);case"delete":return this.deleteFile(i);default:return{success:!1,error:`Unknown action "${s}". Valid: read, write, write_binary, append, list, info, exists, move, copy, delete`}}}resolvePath(e){let t=process.env.HOME||process.env.USERPROFILE||"",s=e.startsWith("~")?e.replace("~",t):e;return vt.resolve(s)}readFile(e){try{let t=P.statSync(e);if(t.isDirectory())return{success:!1,error:`"${e}" is a directory, not a file. Use action "list" instead.`};if(t.size>Ks){let r=P.readFileSync(e,"utf-8").slice(0,Ks);return{success:!0,data:{path:e,size:t.size,truncated:!0},display:`${e} (${t.size} bytes, truncated to ${Ks}):
375
+ ${w.slice(0,2e3)}`}}catch(a){return{success:!1,error:`HTTP request failed: ${a instanceof Error?a.message:String(a)}`}}}stripHtml(e){return e.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#x27;/g,"'").replace(/&nbsp;/g," ").replace(/\s+/g," ").trim()}}});import j from"node:fs";import vt from"node:path";var Ks,We,An=f(()=>{"use strict";D();Ks=5e5,We=class extends _{static{d(this,"FileSkill")}metadata={name:"file",description:'Read, write, move, or copy files. Use for reading file contents, writing text to files, saving binary data, listing directory contents, moving/copying files, or getting file info. Prefer this over shell for file operations. When a user sends a file attachment, it is saved to the inbox \u2014 use "move" to relocate it.',riskLevel:"write",version:"2.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","write","write_binary","append","list","info","exists","move","copy","delete"],description:"The file operation to perform"},path:{type:"string",description:"Absolute or relative file/directory path (~ expands to home)"},destination:{type:"string",description:"Destination path for move/copy actions (~ expands to home)"},content:{type:"string",description:"Content to write (required for write/append; base64-encoded for write_binary)"}},required:["action","path"]}};async execute(e,t){let s=e.action,r=e.path,n=e.content,o=e.destination;if(!s||!r)return{success:!1,error:'Missing required fields "action" and "path"'};if((s==="write"||s==="write_binary"||s==="append")&&!n)return{success:!1,error:`Missing "content" field for "${s}" action. You must provide the file content.`};let i=this.resolvePath(r),a=i.toLowerCase();if(["/etc/shadow","/etc/passwd","/proc/","/sys/","/dev/","c:\\windows\\system32","c:\\windows\\syswow64"].some(u=>a.startsWith(u)||a===u.replace(/\/$/,"")))return{success:!1,error:"Access to system directories/files is blocked for security"};switch(s){case"read":return this.readFile(i);case"write":return this.writeFile(i,n);case"write_binary":return this.writeBinaryFile(i,n);case"append":return this.appendFile(i,n);case"list":return this.listDir(i);case"info":return this.fileInfo(i);case"exists":return this.fileExists(i);case"move":return this.moveFile(i,o);case"copy":return this.copyFile(i,o);case"delete":return this.deleteFile(i);default:return{success:!1,error:`Unknown action "${s}". Valid: read, write, write_binary, append, list, info, exists, move, copy, delete`}}}resolvePath(e){let t=process.env.HOME||process.env.USERPROFILE||"",s=e.startsWith("~")?e.replace("~",t):e;return vt.resolve(s)}readFile(e){try{let t=j.statSync(e);if(t.isDirectory())return{success:!1,error:`"${e}" is a directory, not a file. Use action "list" instead.`};if(t.size>Ks){let r=j.readFileSync(e,"utf-8").slice(0,Ks);return{success:!0,data:{path:e,size:t.size,truncated:!0},display:`${e} (${t.size} bytes, truncated to ${Ks}):
374
376
 
375
- ${r}`}}let s=P.readFileSync(e,"utf-8");return{success:!0,data:{path:e,size:t.size,content:s},display:s}}catch(t){return{success:!1,error:`Cannot read "${e}": ${t.message}`}}}writeFile(e,t){if(t==null)return{success:!1,error:'Missing "content" for write action'};try{let s=vt.dirname(e);return P.mkdirSync(s,{recursive:!0}),P.writeFileSync(e,t,"utf-8"),{success:!0,data:{path:e,bytes:Buffer.byteLength(t)},display:`Written ${Buffer.byteLength(t)} bytes to ${e}`}}catch(s){return{success:!1,error:`Cannot write "${e}": ${s.message}`}}}appendFile(e,t){if(t==null)return{success:!1,error:'Missing "content" for append action'};try{return P.appendFileSync(e,t,"utf-8"),{success:!0,data:{path:e,appendedBytes:Buffer.byteLength(t)},display:`Appended ${Buffer.byteLength(t)} bytes to ${e}`}}catch(s){return{success:!1,error:`Cannot append to "${e}": ${s.message}`}}}listDir(e){try{let s=P.readdirSync(e,{withFileTypes:!0}).map(n=>({name:n.name,type:n.isDirectory()?"dir":n.isSymbolicLink()?"symlink":"file"})),r=s.length===0?`${e}: (empty)`:s.map(n=>`${n.type==="dir"?"\u{1F4C1}":"\u{1F4C4}"} ${n.name}`).join(`
376
- `);return{success:!0,data:{path:e,entries:s},display:r}}catch(t){return{success:!1,error:`Cannot list "${e}": ${t.message}`}}}fileInfo(e){try{let t=P.statSync(e),s={path:e,type:t.isDirectory()?"directory":t.isFile()?"file":"other",size:t.size,created:t.birthtime.toISOString(),modified:t.mtime.toISOString(),permissions:t.mode.toString(8)};return{success:!0,data:s,display:`${s.type}: ${e}
377
+ ${r}`}}let s=j.readFileSync(e,"utf-8");return{success:!0,data:{path:e,size:t.size,content:s},display:s}}catch(t){return{success:!1,error:`Cannot read "${e}": ${t.message}`}}}writeFile(e,t){if(t==null)return{success:!1,error:'Missing "content" for write action'};try{let s=vt.dirname(e);return j.mkdirSync(s,{recursive:!0}),j.writeFileSync(e,t,"utf-8"),{success:!0,data:{path:e,bytes:Buffer.byteLength(t)},display:`Written ${Buffer.byteLength(t)} bytes to ${e}`}}catch(s){return{success:!1,error:`Cannot write "${e}": ${s.message}`}}}appendFile(e,t){if(t==null)return{success:!1,error:'Missing "content" for append action'};try{return j.appendFileSync(e,t,"utf-8"),{success:!0,data:{path:e,appendedBytes:Buffer.byteLength(t)},display:`Appended ${Buffer.byteLength(t)} bytes to ${e}`}}catch(s){return{success:!1,error:`Cannot append to "${e}": ${s.message}`}}}listDir(e){try{let s=j.readdirSync(e,{withFileTypes:!0}).map(n=>({name:n.name,type:n.isDirectory()?"dir":n.isSymbolicLink()?"symlink":"file"})),r=s.length===0?`${e}: (empty)`:s.map(n=>`${n.type==="dir"?"\u{1F4C1}":"\u{1F4C4}"} ${n.name}`).join(`
378
+ `);return{success:!0,data:{path:e,entries:s},display:r}}catch(t){return{success:!1,error:`Cannot list "${e}": ${t.message}`}}}fileInfo(e){try{let t=j.statSync(e),s={path:e,type:t.isDirectory()?"directory":t.isFile()?"file":"other",size:t.size,created:t.birthtime.toISOString(),modified:t.mtime.toISOString(),permissions:t.mode.toString(8)};return{success:!0,data:s,display:`${s.type}: ${e}
377
379
  Size: ${t.size} bytes
378
- Modified: ${s.modified}`}}catch(t){return{success:!1,error:`Cannot stat "${e}": ${t.message}`}}}fileExists(e){let t=P.existsSync(e);return{success:!0,data:{path:e,exists:t},display:t?`Yes, "${e}" exists`:`No, "${e}" does not exist`}}writeBinaryFile(e,t){if(!t)return{success:!1,error:'Missing "content" (base64-encoded) for write_binary action'};try{let s=vt.dirname(e);P.mkdirSync(s,{recursive:!0});let r=Buffer.from(t,"base64");return P.writeFileSync(e,r),{success:!0,data:{path:e,bytes:r.length},display:`Written ${r.length} bytes (binary) to ${e}`}}catch(s){return{success:!1,error:`Cannot write "${e}": ${s.message}`}}}moveFile(e,t){if(!t)return{success:!1,error:'Missing "destination" for move action'};let s=this.resolvePath(t);try{let r=vt.dirname(s);return P.mkdirSync(r,{recursive:!0}),P.renameSync(e,s),{success:!0,data:{from:e,to:s},display:`Moved ${e} \u2192 ${s}`}}catch{try{return P.copyFileSync(e,s),P.unlinkSync(e),{success:!0,data:{from:e,to:s},display:`Moved ${e} \u2192 ${s}`}}catch(n){return{success:!1,error:`Cannot move "${e}" to "${s}": ${n.message}`}}}}copyFile(e,t){if(!t)return{success:!1,error:'Missing "destination" for copy action'};let s=this.resolvePath(t);try{let r=vt.dirname(s);return P.mkdirSync(r,{recursive:!0}),P.copyFileSync(e,s),{success:!0,data:{from:e,to:s},display:`Copied ${e} \u2192 ${s}`}}catch(r){return{success:!1,error:`Cannot copy "${e}" to "${s}": ${r.message}`}}}deleteFile(e){try{return P.existsSync(e)?P.statSync(e).isDirectory()?{success:!1,error:`"${e}" is a directory. Use shell for directory deletion.`}:(P.unlinkSync(e),{success:!0,data:{path:e},display:`Deleted ${e}`}):{success:!1,error:`"${e}" does not exist`}}catch(t){return{success:!1,error:`Cannot delete "${e}": ${t.message}`}}}}});import{execSync as He}from"node:child_process";var Xe,Rn=f(()=>{"use strict";D();Xe=class extends b{static{d(this,"ClipboardSkill")}metadata={name:"clipboard",description:"Read or write the system clipboard. Use when the user asks to copy something, paste from clipboard, or check what is in their clipboard.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","write"],description:'"read" to get clipboard contents, "write" to set clipboard contents'},text:{type:"string",description:"Text to copy to clipboard (required for write)"}},required:["action"]}};async execute(e,t){let s=e.action;switch(s){case"read":return this.readClipboard();case"write":return this.writeClipboard(e.text);default:return{success:!1,error:`Unknown action "${s}". Valid: read, write`}}}readClipboard(){try{let e;switch(process.platform){case"darwin":e=He("pbpaste",{encoding:"utf-8",timeout:5e3});break;case"win32":e=He("powershell -NoProfile -Command Get-Clipboard",{encoding:"utf-8",timeout:5e3}).replace(/\r\n$/,"");break;default:e=He("xclip -selection clipboard -o 2>/dev/null || xsel --clipboard --output",{encoding:"utf-8",timeout:5e3});break}return!e||e.trim().length===0?{success:!0,data:{content:""},display:"Clipboard is empty."}:{success:!0,data:{content:e},display:e.length>2e3?e.slice(0,2e3)+`
380
+ Modified: ${s.modified}`}}catch(t){return{success:!1,error:`Cannot stat "${e}": ${t.message}`}}}fileExists(e){let t=j.existsSync(e);return{success:!0,data:{path:e,exists:t},display:t?`Yes, "${e}" exists`:`No, "${e}" does not exist`}}writeBinaryFile(e,t){if(!t)return{success:!1,error:'Missing "content" (base64-encoded) for write_binary action'};try{let s=vt.dirname(e);j.mkdirSync(s,{recursive:!0});let r=Buffer.from(t,"base64");return j.writeFileSync(e,r),{success:!0,data:{path:e,bytes:r.length},display:`Written ${r.length} bytes (binary) to ${e}`}}catch(s){return{success:!1,error:`Cannot write "${e}": ${s.message}`}}}moveFile(e,t){if(!t)return{success:!1,error:'Missing "destination" for move action'};let s=this.resolvePath(t);try{let r=vt.dirname(s);return j.mkdirSync(r,{recursive:!0}),j.renameSync(e,s),{success:!0,data:{from:e,to:s},display:`Moved ${e} \u2192 ${s}`}}catch{try{return j.copyFileSync(e,s),j.unlinkSync(e),{success:!0,data:{from:e,to:s},display:`Moved ${e} \u2192 ${s}`}}catch(n){return{success:!1,error:`Cannot move "${e}" to "${s}": ${n.message}`}}}}copyFile(e,t){if(!t)return{success:!1,error:'Missing "destination" for copy action'};let s=this.resolvePath(t);try{let r=vt.dirname(s);return j.mkdirSync(r,{recursive:!0}),j.copyFileSync(e,s),{success:!0,data:{from:e,to:s},display:`Copied ${e} \u2192 ${s}`}}catch(r){return{success:!1,error:`Cannot copy "${e}" to "${s}": ${r.message}`}}}deleteFile(e){try{return j.existsSync(e)?j.statSync(e).isDirectory()?{success:!1,error:`"${e}" is a directory. Use shell for directory deletion.`}:(j.unlinkSync(e),{success:!0,data:{path:e},display:`Deleted ${e}`}):{success:!1,error:`"${e}" does not exist`}}catch(t){return{success:!1,error:`Cannot delete "${e}": ${t.message}`}}}}});import{execSync as He}from"node:child_process";var Xe,Rn=f(()=>{"use strict";D();Xe=class extends _{static{d(this,"ClipboardSkill")}metadata={name:"clipboard",description:"Read or write the system clipboard. Use when the user asks to copy something, paste from clipboard, or check what is in their clipboard.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","write"],description:'"read" to get clipboard contents, "write" to set clipboard contents'},text:{type:"string",description:"Text to copy to clipboard (required for write)"}},required:["action"]}};async execute(e,t){let s=e.action;switch(s){case"read":return this.readClipboard();case"write":return this.writeClipboard(e.text);default:return{success:!1,error:`Unknown action "${s}". Valid: read, write`}}}readClipboard(){try{let e;switch(process.platform){case"darwin":e=He("pbpaste",{encoding:"utf-8",timeout:5e3});break;case"win32":e=He("powershell -NoProfile -Command Get-Clipboard",{encoding:"utf-8",timeout:5e3}).replace(/\r\n$/,"");break;default:e=He("xclip -selection clipboard -o 2>/dev/null || xsel --clipboard --output",{encoding:"utf-8",timeout:5e3});break}return!e||e.trim().length===0?{success:!0,data:{content:""},display:"Clipboard is empty."}:{success:!0,data:{content:e},display:e.length>2e3?e.slice(0,2e3)+`
379
381
 
380
- [... truncated]`:e}}catch(e){return{success:!1,error:`Failed to read clipboard: ${e.message}`}}}writeClipboard(e){if(!e||typeof e!="string")return{success:!1,error:'Missing "text" for write action'};try{switch(process.platform){case"darwin":He("pbcopy",{input:e,timeout:5e3});break;case"win32":He('powershell -NoProfile -Command "$input | Set-Clipboard"',{input:e,timeout:5e3});break;default:He("xclip -selection clipboard 2>/dev/null || xsel --clipboard --input",{input:e,timeout:5e3});break}return{success:!0,data:{copiedLength:e.length},display:`Copied ${e.length} characters to clipboard.`}}catch(t){return{success:!1,error:`Failed to write clipboard: ${t.message}`}}}}});import{execSync as xt}from"node:child_process";import Ln from"node:path";import Ni from"node:os";var ze,Mn=f(()=>{"use strict";D();ze=class extends b{static{d(this,"ScreenshotSkill")}metadata={name:"screenshot",description:"Take a screenshot of the current screen and save it to a file. Use when the user asks to capture their screen or take a screenshot.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{path:{type:"string",description:"Output file path (optional, defaults to ~/Desktop/screenshot-<timestamp>.png)"}}}};async execute(e,t){let s=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),r=Ln.join(Ni.homedir(),"Desktop"),n=e.path||Ln.join(r,`screenshot-${s}.png`);try{switch(process.platform){case"darwin":xt(`screencapture -x "${n}"`,{timeout:1e4});break;case"win32":xt(`powershell -NoProfile -Command "Add-Type -AssemblyName System.Windows.Forms; $screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds; $bitmap = New-Object System.Drawing.Bitmap($screen.Width, $screen.Height); $graphics = [System.Drawing.Graphics]::FromImage($bitmap); $graphics.CopyFromScreen($screen.Location, [System.Drawing.Point]::Empty, $screen.Size); $bitmap.Save('${n.replace(/'/g,"''")}'); $graphics.Dispose(); $bitmap.Dispose()"`,{timeout:1e4});break;default:try{xt(`scrot "${n}"`,{timeout:1e4})}catch{try{xt(`import -window root "${n}"`,{timeout:1e4})}catch{xt(`gnome-screenshot -f "${n}"`,{timeout:1e4})}}break}return{success:!0,data:{path:n},display:`Screenshot saved to ${n}`}}catch(o){return{success:!1,error:`Screenshot failed: ${o.message}`}}}}});import Di from"node:path";import Oi from"node:os";var Nn,qe,Dn=f(()=>{"use strict";D();Nn=5e4,qe=class extends b{static{d(this,"BrowserSkill")}browser=null;page=null;metadata={name:"browser",description:"Open web pages in a real browser (Puppeteer/Chromium). Renders JavaScript, so it works with SPAs and dynamic sites. Can also interact with pages: click buttons, fill forms, take screenshots. Use when http skill returns empty/broken content, or when you need to interact with a web page.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["open","screenshot","click","type","evaluate","close"],description:"open = navigate to URL and return page text. screenshot = save screenshot of current page. click = click element by CSS selector. type = type text into input by CSS selector. evaluate = run JavaScript on the page. close = close the browser."},url:{type:"string",description:'URL to open (required for "open", optional for "screenshot")'},selector:{type:"string",description:'CSS selector for the element (required for "click" and "type")'},text:{type:"string",description:'Text to type (required for "type")'},script:{type:"string",description:'JavaScript code to evaluate (required for "evaluate")'},path:{type:"string",description:"File path to save screenshot (optional, defaults to Desktop)"}},required:["action"]}};async execute(e,t){let s=e.action;if(s==="close")return this.closeBrowser();let r=await this.loadPuppeteer();if(!r)return{success:!1,error:`Puppeteer is not installed. Run: npm install -g puppeteer
382
+ [... truncated]`:e}}catch(e){return{success:!1,error:`Failed to read clipboard: ${e.message}`}}}writeClipboard(e){if(!e||typeof e!="string")return{success:!1,error:'Missing "text" for write action'};try{switch(process.platform){case"darwin":He("pbcopy",{input:e,timeout:5e3});break;case"win32":He('powershell -NoProfile -Command "$input | Set-Clipboard"',{input:e,timeout:5e3});break;default:He("xclip -selection clipboard 2>/dev/null || xsel --clipboard --input",{input:e,timeout:5e3});break}return{success:!0,data:{copiedLength:e.length},display:`Copied ${e.length} characters to clipboard.`}}catch(t){return{success:!1,error:`Failed to write clipboard: ${t.message}`}}}}});import{execSync as xt}from"node:child_process";import Ln from"node:path";import Ni from"node:os";var ze,Mn=f(()=>{"use strict";D();ze=class extends _{static{d(this,"ScreenshotSkill")}metadata={name:"screenshot",description:"Take a screenshot of the current screen and save it to a file. Use when the user asks to capture their screen or take a screenshot.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{path:{type:"string",description:"Output file path (optional, defaults to ~/Desktop/screenshot-<timestamp>.png)"}}}};async execute(e,t){let s=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),r=Ln.join(Ni.homedir(),"Desktop"),n=e.path||Ln.join(r,`screenshot-${s}.png`);try{switch(process.platform){case"darwin":xt(`screencapture -x "${n}"`,{timeout:1e4});break;case"win32":xt(`powershell -NoProfile -Command "Add-Type -AssemblyName System.Windows.Forms; $screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds; $bitmap = New-Object System.Drawing.Bitmap($screen.Width, $screen.Height); $graphics = [System.Drawing.Graphics]::FromImage($bitmap); $graphics.CopyFromScreen($screen.Location, [System.Drawing.Point]::Empty, $screen.Size); $bitmap.Save('${n.replace(/'/g,"''")}'); $graphics.Dispose(); $bitmap.Dispose()"`,{timeout:1e4});break;default:try{xt(`scrot "${n}"`,{timeout:1e4})}catch{try{xt(`import -window root "${n}"`,{timeout:1e4})}catch{xt(`gnome-screenshot -f "${n}"`,{timeout:1e4})}}break}return{success:!0,data:{path:n},display:`Screenshot saved to ${n}`}}catch(o){return{success:!1,error:`Screenshot failed: ${o.message}`}}}}});import Di from"node:path";import Oi from"node:os";var Nn,qe,Dn=f(()=>{"use strict";D();Nn=5e4,qe=class extends _{static{d(this,"BrowserSkill")}browser=null;page=null;metadata={name:"browser",description:"Open web pages in a real browser (Puppeteer/Chromium). Renders JavaScript, so it works with SPAs and dynamic sites. Can also interact with pages: click buttons, fill forms, take screenshots. Use when http skill returns empty/broken content, or when you need to interact with a web page.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["open","screenshot","click","type","evaluate","close"],description:"open = navigate to URL and return page text. screenshot = save screenshot of current page. click = click element by CSS selector. type = type text into input by CSS selector. evaluate = run JavaScript on the page. close = close the browser."},url:{type:"string",description:'URL to open (required for "open", optional for "screenshot")'},selector:{type:"string",description:'CSS selector for the element (required for "click" and "type")'},text:{type:"string",description:'Text to type (required for "type")'},script:{type:"string",description:'JavaScript code to evaluate (required for "evaluate")'},path:{type:"string",description:"File path to save screenshot (optional, defaults to Desktop)"}},required:["action"]}};async execute(e,t){let s=e.action;if(s==="close")return this.closeBrowser();let r=await this.loadPuppeteer();if(!r)return{success:!1,error:`Puppeteer is not installed. Run: npm install -g puppeteer
381
383
  Or add it to Alfred: npm install puppeteer`};switch(s){case"open":return this.openPage(r,e);case"screenshot":return this.screenshotPage(r,e);case"click":return this.clickElement(e);case"type":return this.typeText(e);case"evaluate":return this.evaluateScript(e);default:return{success:!1,error:`Unknown action "${s}". Valid: open, screenshot, click, type, evaluate, close`}}}async loadPuppeteer(){try{let e=await Function('return import("puppeteer")')();return this.resolvePuppeteerModule(e)}catch{try{let e=await Function('return import("puppeteer-core")')();return this.resolvePuppeteerModule(e)}catch{return null}}}resolvePuppeteerModule(e){let t=e;return typeof t.launch=="function"?t:t.default}async ensureBrowser(e){return this.browser&&this.browser.connected?this.browser:(this.browser=await e.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"]}),this.browser)}async ensurePage(e){let t=await this.ensureBrowser(e);return this.page||(this.page=await t.newPage(),await this.page.setViewport({width:1280,height:900})),this.page}async openPage(e,t){let s=t.url;if(!s)return{success:!1,error:'Missing "url" for open action'};try{let r=await this.ensurePage(e);await r.goto(s,{waitUntil:"networkidle2",timeout:3e4});let n=await r.title(),o=await r.evaluate(`
382
384
  (() => {
383
385
  document.querySelectorAll('script, style, noscript').forEach(el => el.remove());
@@ -389,7 +391,7 @@ Or add it to Alfred: npm install puppeteer`};switch(s){case"open":return this.op
389
391
 
390
392
  `).trim();return{success:!0,data:{url:r.url(),title:n,length:o.length},display:`**${n}** (${r.url()})
391
393
 
392
- ${a}`}}catch(r){return{success:!1,error:`Failed to open "${s}": ${r.message}`}}}async screenshotPage(e,t){try{let s=await this.ensurePage(e),r=t.url;r&&await s.goto(r,{waitUntil:"networkidle2",timeout:3e4});let n=s.url();if(n==="about:blank")return{success:!1,error:'No page is open. Use action "open" with a URL first, or provide a URL.'};let o=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),i=t.path||Di.join(Oi.homedir(),"Desktop",`browser-${o}.png`);return await s.screenshot({path:i,fullPage:!1}),{success:!0,data:{path:i,url:n},display:`Screenshot saved to ${i}`}}catch(s){return{success:!1,error:`Screenshot failed: ${s.message}`}}}async clickElement(e){let t=e.selector;if(!t)return{success:!1,error:'Missing "selector" for click action'};if(!this.page)return{success:!1,error:'No page is open. Use action "open" first.'};try{await this.page.waitForSelector(t,{timeout:5e3}),await this.page.click(t);try{await this.page.waitForNavigation({timeout:3e3})}catch{}let s=await this.page.title();return{success:!0,data:{selector:t,url:this.page.url(),title:s},display:`Clicked "${t}" \u2014 now on: ${s} (${this.page.url()})`}}catch(s){return{success:!1,error:`Click failed on "${t}": ${s.message}`}}}async typeText(e){let t=e.selector,s=e.text;if(!t)return{success:!1,error:'Missing "selector" for type action'};if(!s)return{success:!1,error:'Missing "text" for type action'};if(!this.page)return{success:!1,error:'No page is open. Use action "open" first.'};try{return await this.page.waitForSelector(t,{timeout:5e3}),await this.page.click(t),await this.page.type(t,s,{delay:50}),{success:!0,data:{selector:t,textLength:s.length},display:`Typed ${s.length} characters into "${t}"`}}catch(r){return{success:!1,error:`Type failed on "${t}": ${r.message}`}}}async evaluateScript(e){let t=e.script;if(!t)return{success:!1,error:'Missing "script" for evaluate action'};if(!this.page)return{success:!1,error:'No page is open. Use action "open" first.'};try{let s=await this.page.evaluate(t),r=typeof s=="string"?s:JSON.stringify(s,null,2);return{success:!0,data:{result:s},display:r?.slice(0,1e4)??"(no output)"}}catch(s){return{success:!1,error:`Evaluate failed: ${s.message}`}}}async closeBrowser(){try{return this.page=null,this.browser&&(await this.browser.close(),this.browser=null),{success:!0,display:"Browser closed."}}catch(e){return this.browser=null,this.page=null,{success:!1,error:`Close failed: ${e.message}`}}}}});var Ke,On=f(()=>{"use strict";D();Ke=class extends b{static{d(this,"ProfileSkill")}userRepo;metadata={name:"profile",description:"Manage user profile settings including timezone, language, and bio. Use this to personalize Alfred for each user.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","set_timezone","set_language","set_bio","set_preference"],description:"The profile action to perform"},value:{type:"string",description:"The value to set (for set_* actions)"},preference_key:{type:"string",description:"The preference key (for set_preference)"},preference_value:{type:"string",description:"The preference value (for set_preference)"}},required:["action"]}};constructor(e){super(),this.userRepo=e}async execute(e,t){let s=e.action,r=this.userRepo.findOrCreate(t.platform,t.userId);switch(s){case"get":return this.getProfile(r.id);case"set_timezone":return this.setField(r.id,"timezone",e.value);case"set_language":return this.setField(r.id,"language",e.value);case"set_bio":return this.setField(r.id,"bio",e.value);case"set_preference":return this.setPreference(r.id,e.preference_key,e.preference_value);default:return{success:!1,error:`Unknown action: "${String(s)}"`}}}getProfile(e){let t=this.userRepo.getProfile(e);if(!t)return{success:!0,data:null,display:"No profile found. Set your timezone, language, or bio to create one."};let s=[];if(t.displayName&&s.push(`Name: ${t.displayName}`),t.timezone&&s.push(`Timezone: ${t.timezone}`),t.language&&s.push(`Language: ${t.language}`),t.bio&&s.push(`Bio: ${t.bio}`),t.preferences)for(let[r,n]of Object.entries(t.preferences))s.push(`${r}: ${String(n)}`);return{success:!0,data:t,display:s.length>0?`Profile:
394
+ ${a}`}}catch(r){return{success:!1,error:`Failed to open "${s}": ${r.message}`}}}async screenshotPage(e,t){try{let s=await this.ensurePage(e),r=t.url;r&&await s.goto(r,{waitUntil:"networkidle2",timeout:3e4});let n=s.url();if(n==="about:blank")return{success:!1,error:'No page is open. Use action "open" with a URL first, or provide a URL.'};let o=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),i=t.path||Di.join(Oi.homedir(),"Desktop",`browser-${o}.png`);return await s.screenshot({path:i,fullPage:!1}),{success:!0,data:{path:i,url:n},display:`Screenshot saved to ${i}`}}catch(s){return{success:!1,error:`Screenshot failed: ${s.message}`}}}async clickElement(e){let t=e.selector;if(!t)return{success:!1,error:'Missing "selector" for click action'};if(!this.page)return{success:!1,error:'No page is open. Use action "open" first.'};try{await this.page.waitForSelector(t,{timeout:5e3}),await this.page.click(t);try{await this.page.waitForNavigation({timeout:3e3})}catch{}let s=await this.page.title();return{success:!0,data:{selector:t,url:this.page.url(),title:s},display:`Clicked "${t}" \u2014 now on: ${s} (${this.page.url()})`}}catch(s){return{success:!1,error:`Click failed on "${t}": ${s.message}`}}}async typeText(e){let t=e.selector,s=e.text;if(!t)return{success:!1,error:'Missing "selector" for type action'};if(!s)return{success:!1,error:'Missing "text" for type action'};if(!this.page)return{success:!1,error:'No page is open. Use action "open" first.'};try{return await this.page.waitForSelector(t,{timeout:5e3}),await this.page.click(t),await this.page.type(t,s,{delay:50}),{success:!0,data:{selector:t,textLength:s.length},display:`Typed ${s.length} characters into "${t}"`}}catch(r){return{success:!1,error:`Type failed on "${t}": ${r.message}`}}}async evaluateScript(e){let t=e.script;if(!t)return{success:!1,error:'Missing "script" for evaluate action'};if(!this.page)return{success:!1,error:'No page is open. Use action "open" first.'};try{let s=await this.page.evaluate(t),r=typeof s=="string"?s:JSON.stringify(s,null,2);return{success:!0,data:{result:s},display:r?.slice(0,1e4)??"(no output)"}}catch(s){return{success:!1,error:`Evaluate failed: ${s.message}`}}}async closeBrowser(){try{return this.page=null,this.browser&&(await this.browser.close(),this.browser=null),{success:!0,display:"Browser closed."}}catch(e){return this.browser=null,this.page=null,{success:!1,error:`Close failed: ${e.message}`}}}}});var Ke,On=f(()=>{"use strict";D();Ke=class extends _{static{d(this,"ProfileSkill")}userRepo;metadata={name:"profile",description:"Manage user profile settings including timezone, language, and bio. Use this to personalize Alfred for each user.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","set_timezone","set_language","set_bio","set_preference"],description:"The profile action to perform"},value:{type:"string",description:"The value to set (for set_* actions)"},preference_key:{type:"string",description:"The preference key (for set_preference)"},preference_value:{type:"string",description:"The preference value (for set_preference)"}},required:["action"]}};constructor(e){super(),this.userRepo=e}async execute(e,t){let s=e.action,r=this.userRepo.findOrCreate(t.platform,t.userId);switch(s){case"get":return this.getProfile(r.id);case"set_timezone":return this.setField(r.id,"timezone",e.value);case"set_language":return this.setField(r.id,"language",e.value);case"set_bio":return this.setField(r.id,"bio",e.value);case"set_preference":return this.setPreference(r.id,e.preference_key,e.preference_value);default:return{success:!1,error:`Unknown action: "${String(s)}"`}}}getProfile(e){let t=this.userRepo.getProfile(e);if(!t)return{success:!0,data:null,display:"No profile found. Set your timezone, language, or bio to create one."};let s=[];if(t.displayName&&s.push(`Name: ${t.displayName}`),t.timezone&&s.push(`Timezone: ${t.timezone}`),t.language&&s.push(`Language: ${t.language}`),t.bio&&s.push(`Bio: ${t.bio}`),t.preferences)for(let[r,n]of Object.entries(t.preferences))s.push(`${r}: ${String(n)}`);return{success:!0,data:t,display:s.length>0?`Profile:
393
395
  ${s.map(r=>`- ${r}`).join(`
394
396
  `)}`:"Profile is empty."}}setField(e,t,s){return!s||typeof s!="string"?{success:!1,error:`Missing required "value" for ${t}`}:(this.userRepo.updateProfile(e,{[t]:s}),{success:!0,data:{[t]:s},display:`${t} set to "${s}"`})}setPreference(e,t,s){if(!t||typeof t!="string")return{success:!1,error:'Missing required "preference_key"'};let n=this.userRepo.getProfile(e)?.preferences??{};return n[t]=s,this.userRepo.updateProfile(e,{preferences:n}),{success:!0,data:{key:t,value:s},display:`Preference "${t}" set to "${s}"`}}}});var J,$t=f(()=>{"use strict";J=class{static{d(this,"CalendarProvider")}}});var Cn={};G(Cn,{CalDAVProvider:()=>ns});var ns,Vs=f(()=>{"use strict";$t();ns=class extends J{static{d(this,"CalDAVProvider")}config;client;constructor(e){super(),this.config=e}async initialize(){try{let e=await import("tsdav"),{createDAVClient:t}=e;this.client=await t({serverUrl:this.config.serverUrl,credentials:{username:this.config.username,password:this.config.password},authMethod:"Basic",defaultAccountType:"caldav"})}catch(e){throw new Error(`CalDAV initialization failed: ${e instanceof Error?e.message:String(e)}`)}}async listEvents(e,t){let s=await this.client.fetchCalendars();if(!s||s.length===0)return[];let r=[];for(let n of s){let o=await this.client.fetchCalendarObjects({calendar:n,timeRange:{start:e.toISOString(),end:t.toISOString()}});for(let i of o){let a=this.parseICalEvent(i.data,i.url);a&&r.push(a)}}return r.sort((n,o)=>n.start.getTime()-o.start.getTime())}async createEvent(e){let t=await this.client.fetchCalendars();if(!t||t.length===0)throw new Error("No calendars found");let s=`alfred-${Date.now()}@alfred`,r=this.buildICalEvent(s,e);return await this.client.createCalendarObject({calendar:t[0],filename:`${s}.ics`,iCalString:r}),{id:s,title:e.title,start:e.start,end:e.end,location:e.location,description:e.description,allDay:e.allDay}}async updateEvent(e,t){let s=await this.client.fetchCalendars();for(let r of s){let n=await this.client.fetchCalendarObjects({calendar:r});for(let o of n)if(o.url?.includes(e)||o.data?.includes(e)){let i=this.parseICalEvent(o.data,o.url);if(!i)continue;let a={title:t.title??i.title,start:t.start??i.start,end:t.end??i.end,location:t.location??i.location,description:t.description??i.description,allDay:t.allDay??i.allDay},l=this.buildICalEvent(e,a);return await this.client.updateCalendarObject({calendarObject:{...o,data:l}}),{id:e,...a}}}throw new Error(`Event ${e} not found`)}async deleteEvent(e){let t=await this.client.fetchCalendars();for(let s of t){let r=await this.client.fetchCalendarObjects({calendar:s});for(let n of r)if(n.url?.includes(e)||n.data?.includes(e)){await this.client.deleteCalendarObject({calendarObject:n});return}}throw new Error(`Event ${e} not found`)}async checkAvailability(e,t){let r=(await this.listEvents(e,t)).filter(n=>!n.allDay&&n.start<t&&n.end>e);return{available:r.length===0,conflicts:r}}parseICalEvent(e,t){try{let s=e.split(`
395
397
  `).map(m=>m.trim()),r=d(m=>s.find(h=>h.startsWith(m+":"))?.slice(m.length+1),"get"),n=r("SUMMARY"),o=r("DTSTART")??r("DTSTART;VALUE=DATE"),i=r("DTEND")??r("DTEND;VALUE=DATE"),a=r("LOCATION"),l=r("DESCRIPTION"),u=r("UID")??t;if(!n||!o)return;let p=o.length===8;return{id:u,title:n,start:this.parseICalDate(o),end:i?this.parseICalDate(i):this.parseICalDate(o),location:a||void 0,description:l||void 0,allDay:p}}catch(s){console.error("[caldav] Failed to parse iCal event",s);return}}parseICalDate(e){if(e.length===8)return new Date(`${e.slice(0,4)}-${e.slice(4,6)}-${e.slice(6,8)}`);let t=e.replace(/[^0-9TZ]/g,"");return t.length>=15?new Date(`${t.slice(0,4)}-${t.slice(4,6)}-${t.slice(6,8)}T${t.slice(9,11)}:${t.slice(11,13)}:${t.slice(13,15)}Z`):new Date(e)}buildICalEvent(e,t){let s=d((n,o)=>o?n.toISOString().slice(0,10).replace(/-/g,""):n.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),"formatDate"),r=`BEGIN:VCALENDAR\r
@@ -407,11 +409,11 @@ BEGIN:VEVENT\r
407
409
  `),r+=`DTSTAMP:${s(new Date)}\r
408
410
  `,r+=`END:VEVENT\r
409
411
  END:VCALENDAR\r
410
- `,r}}});var Un={};G(Un,{GoogleCalendarProvider:()=>os});var os,Gs=f(()=>{"use strict";$t();os=class extends J{static{d(this,"GoogleCalendarProvider")}config;calendar;constructor(e){super(),this.config=e}async initialize(){try{let{google:e}=await import("googleapis"),t=new e.auth.OAuth2(this.config.clientId,this.config.clientSecret);t.setCredentials({refresh_token:this.config.refreshToken}),this.calendar=e.calendar({version:"v3",auth:t})}catch(e){throw new Error(`Google Calendar initialization failed: ${e instanceof Error?e.message:String(e)}`)}}async listEvents(e,t){return((await this.calendar.events.list({calendarId:"primary",timeMin:e.toISOString(),timeMax:t.toISOString(),singleEvents:!0,orderBy:"startTime"})).data.items??[]).map(r=>this.mapEvent(r))}async createEvent(e){let t={summary:e.title,location:e.location,description:e.description};e.allDay?(t.start={date:e.start.toISOString().slice(0,10)},t.end={date:e.end.toISOString().slice(0,10)}):(t.start={dateTime:e.start.toISOString()},t.end={dateTime:e.end.toISOString()});let s=await this.calendar.events.insert({calendarId:"primary",requestBody:t});return this.mapEvent(s.data)}async updateEvent(e,t){let s={};t.title&&(s.summary=t.title),t.location&&(s.location=t.location),t.description&&(s.description=t.description),t.start&&(s.start=t.allDay?{date:t.start.toISOString().slice(0,10)}:{dateTime:t.start.toISOString()}),t.end&&(s.end=t.allDay?{date:t.end.toISOString().slice(0,10)}:{dateTime:t.end.toISOString()});let r=await this.calendar.events.patch({calendarId:"primary",eventId:e,requestBody:s});return this.mapEvent(r.data)}async deleteEvent(e){await this.calendar.events.delete({calendarId:"primary",eventId:e})}async checkAvailability(e,t){let r=(await this.listEvents(e,t)).filter(n=>!n.allDay&&n.start<t&&n.end>e);return{available:r.length===0,conflicts:r}}mapEvent(e){let t=!!e.start?.date;return{id:e.id,title:e.summary??"(No title)",start:new Date(e.start?.dateTime??e.start?.date),end:new Date(e.end?.dateTime??e.end?.date),location:e.location??void 0,description:e.description??void 0,allDay:t}}}});var Pn={};G(Pn,{MicrosoftCalendarProvider:()=>is});var is,Ys=f(()=>{"use strict";$t();is=class extends J{static{d(this,"MicrosoftCalendarProvider")}config;client;accessToken="";constructor(e){super(),this.config=e}async initialize(){await this.refreshAccessToken()}async refreshAccessToken(){let e=`https://login.microsoftonline.com/${this.config.tenantId}/oauth2/v2.0/token`,t=new URLSearchParams({client_id:this.config.clientId,client_secret:this.config.clientSecret,refresh_token:this.config.refreshToken,grant_type:"refresh_token",scope:"https://graph.microsoft.com/Calendars.ReadWrite offline_access"}),s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!s.ok)throw new Error(`Microsoft token refresh failed: ${s.status}`);let r=await s.json();this.accessToken=r.access_token}async graphRequest(e,t={}){let s=await fetch(`https://graph.microsoft.com/v1.0${e}`,{...t,headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json",...t.headers}});if(s.status===401){await this.refreshAccessToken();let r=await fetch(`https://graph.microsoft.com/v1.0${e}`,{...t,headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json",...t.headers}});if(!r.ok)throw new Error(`Graph API error: ${r.status}`);return r.json()}if(!s.ok)throw new Error(`Graph API error: ${s.status}`);if(s.status!==204)return s.json()}async listEvents(e,t){let s=new URLSearchParams({startDateTime:e.toISOString(),endDateTime:t.toISOString(),$orderby:"start/dateTime",$top:"50"});return((await this.graphRequest(`/me/calendarView?${s}`)).value??[]).map(n=>this.mapEvent(n))}async createEvent(e){let t={subject:e.title,body:e.description?{contentType:"text",content:e.description}:void 0,location:e.location?{displayName:e.location}:void 0,isAllDay:e.allDay??!1};e.allDay?(t.start={dateTime:e.start.toISOString().slice(0,10)+"T00:00:00",timeZone:"UTC"},t.end={dateTime:e.end.toISOString().slice(0,10)+"T00:00:00",timeZone:"UTC"}):(t.start={dateTime:e.start.toISOString(),timeZone:"UTC"},t.end={dateTime:e.end.toISOString(),timeZone:"UTC"});let s=await this.graphRequest("/me/events",{method:"POST",body:JSON.stringify(t)});return this.mapEvent(s)}async updateEvent(e,t){let s={};t.title&&(s.subject=t.title),t.description&&(s.body={contentType:"text",content:t.description}),t.location&&(s.location={displayName:t.location}),t.start&&(s.start={dateTime:t.start.toISOString(),timeZone:"UTC"}),t.end&&(s.end={dateTime:t.end.toISOString(),timeZone:"UTC"});let r=await this.graphRequest(`/me/events/${e}`,{method:"PATCH",body:JSON.stringify(s)});return this.mapEvent(r)}async deleteEvent(e){await this.graphRequest(`/me/events/${e}`,{method:"DELETE"})}async checkAvailability(e,t){let r=(await this.listEvents(e,t)).filter(n=>!n.allDay&&n.start<t&&n.end>e);return{available:r.length===0,conflicts:r}}mapEvent(e){return{id:e.id,title:e.subject??"(No title)",start:new Date(e.start?.dateTime),end:new Date(e.end?.dateTime),location:e.location?.displayName??void 0,description:e.body?.content??void 0,allDay:e.isAllDay??!1}}}});async function It(c){switch(c.provider){case"caldav":{if(!c.caldav)throw new Error("CalDAV config missing");let{CalDAVProvider:e}=await Promise.resolve().then(()=>(Vs(),Cn)),t=new e(c.caldav);return await t.initialize(),t}case"google":{if(!c.google)throw new Error("Google Calendar config missing");let{GoogleCalendarProvider:e}=await Promise.resolve().then(()=>(Gs(),Un)),t=new e(c.google);return await t.initialize(),t}case"microsoft":{if(!c.microsoft)throw new Error("Microsoft Calendar config missing");let{MicrosoftCalendarProvider:e}=await Promise.resolve().then(()=>(Ys(),Pn)),t=new e(c.microsoft);return await t.initialize(),t}default:throw new Error(`Unknown calendar provider: ${c.provider}`)}}var Fn=f(()=>{"use strict";d(It,"createCalendarProvider")});var ye,jn=f(()=>{"use strict";D();ye=class extends b{static{d(this,"CalendarSkill")}calendarProvider;timezone;metadata={name:"calendar",description:"Manage calendar events. List upcoming events, create new events, update or delete existing ones, and check availability.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list_events","create_event","update_event","delete_event","check_availability"],description:"The calendar action to perform"},start:{type:"string",description:"Start date/time in ISO 8601 format"},end:{type:"string",description:"End date/time in ISO 8601 format"},title:{type:"string",description:"Event title (for create/update)"},location:{type:"string",description:"Event location (for create/update)"},description:{type:"string",description:"Event description (for create/update)"},event_id:{type:"string",description:"Event ID (for update/delete)"},all_day:{type:"boolean",description:"Whether this is an all-day event"}},required:["action"]}};constructor(e,t){super(),this.calendarProvider=e,this.timezone=t}async execute(e,t){let s=e.action;switch(s){case"list_events":return this.listEvents(e);case"create_event":return this.createEvent(e);case"update_event":return this.updateEvent(e);case"delete_event":return this.deleteEvent(e);case"check_availability":return this.checkAvailability(e);default:return{success:!1,error:`Unknown action: "${String(s)}"`}}}async getTodayEvents(){let e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()),s=new Date(e.getFullYear(),e.getMonth(),e.getDate()+1);try{return await this.calendarProvider.listEvents(t,s)}catch(r){return console.error("[calendar] Failed to fetch today events",r),[]}}async listEvents(e){let t=e.start?new Date(e.start):new Date,s=e.end?new Date(e.end):new Date(t.getTime()+7*24*60*60*1e3);try{let r=await this.calendarProvider.listEvents(t,s);if(r.length===0)return{success:!0,data:[],display:"No events found in this time range."};let n=r.map(o=>this.formatEvent(o)).join(`
412
+ `,r}}});var Un={};G(Un,{GoogleCalendarProvider:()=>os});var os,Gs=f(()=>{"use strict";$t();os=class extends J{static{d(this,"GoogleCalendarProvider")}config;calendar;constructor(e){super(),this.config=e}async initialize(){try{let{google:e}=await import("googleapis"),t=new e.auth.OAuth2(this.config.clientId,this.config.clientSecret);t.setCredentials({refresh_token:this.config.refreshToken}),this.calendar=e.calendar({version:"v3",auth:t})}catch(e){throw new Error(`Google Calendar initialization failed: ${e instanceof Error?e.message:String(e)}`)}}async listEvents(e,t){return((await this.calendar.events.list({calendarId:"primary",timeMin:e.toISOString(),timeMax:t.toISOString(),singleEvents:!0,orderBy:"startTime"})).data.items??[]).map(r=>this.mapEvent(r))}async createEvent(e){let t={summary:e.title,location:e.location,description:e.description};e.allDay?(t.start={date:e.start.toISOString().slice(0,10)},t.end={date:e.end.toISOString().slice(0,10)}):(t.start={dateTime:e.start.toISOString()},t.end={dateTime:e.end.toISOString()});let s=await this.calendar.events.insert({calendarId:"primary",requestBody:t});return this.mapEvent(s.data)}async updateEvent(e,t){let s={};t.title&&(s.summary=t.title),t.location&&(s.location=t.location),t.description&&(s.description=t.description),t.start&&(s.start=t.allDay?{date:t.start.toISOString().slice(0,10)}:{dateTime:t.start.toISOString()}),t.end&&(s.end=t.allDay?{date:t.end.toISOString().slice(0,10)}:{dateTime:t.end.toISOString()});let r=await this.calendar.events.patch({calendarId:"primary",eventId:e,requestBody:s});return this.mapEvent(r.data)}async deleteEvent(e){await this.calendar.events.delete({calendarId:"primary",eventId:e})}async checkAvailability(e,t){let r=(await this.listEvents(e,t)).filter(n=>!n.allDay&&n.start<t&&n.end>e);return{available:r.length===0,conflicts:r}}mapEvent(e){let t=!!e.start?.date;return{id:e.id,title:e.summary??"(No title)",start:new Date(e.start?.dateTime??e.start?.date),end:new Date(e.end?.dateTime??e.end?.date),location:e.location??void 0,description:e.description??void 0,allDay:t}}}});var Pn={};G(Pn,{MicrosoftCalendarProvider:()=>is});var is,Ys=f(()=>{"use strict";$t();is=class extends J{static{d(this,"MicrosoftCalendarProvider")}config;client;accessToken="";constructor(e){super(),this.config=e}async initialize(){await this.refreshAccessToken()}async refreshAccessToken(){let e=`https://login.microsoftonline.com/${this.config.tenantId}/oauth2/v2.0/token`,t=new URLSearchParams({client_id:this.config.clientId,client_secret:this.config.clientSecret,refresh_token:this.config.refreshToken,grant_type:"refresh_token",scope:"https://graph.microsoft.com/Calendars.ReadWrite offline_access"}),s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!s.ok)throw new Error(`Microsoft token refresh failed: ${s.status}`);let r=await s.json();this.accessToken=r.access_token}async graphRequest(e,t={}){let s=await fetch(`https://graph.microsoft.com/v1.0${e}`,{...t,headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json",...t.headers}});if(s.status===401){await this.refreshAccessToken();let r=await fetch(`https://graph.microsoft.com/v1.0${e}`,{...t,headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json",...t.headers}});if(!r.ok)throw new Error(`Graph API error: ${r.status}`);return r.json()}if(!s.ok)throw new Error(`Graph API error: ${s.status}`);if(s.status!==204)return s.json()}async listEvents(e,t){let s=new URLSearchParams({startDateTime:e.toISOString(),endDateTime:t.toISOString(),$orderby:"start/dateTime",$top:"50"});return((await this.graphRequest(`/me/calendarView?${s}`)).value??[]).map(n=>this.mapEvent(n))}async createEvent(e){let t={subject:e.title,body:e.description?{contentType:"text",content:e.description}:void 0,location:e.location?{displayName:e.location}:void 0,isAllDay:e.allDay??!1};e.allDay?(t.start={dateTime:e.start.toISOString().slice(0,10)+"T00:00:00",timeZone:"UTC"},t.end={dateTime:e.end.toISOString().slice(0,10)+"T00:00:00",timeZone:"UTC"}):(t.start={dateTime:e.start.toISOString(),timeZone:"UTC"},t.end={dateTime:e.end.toISOString(),timeZone:"UTC"});let s=await this.graphRequest("/me/events",{method:"POST",body:JSON.stringify(t)});return this.mapEvent(s)}async updateEvent(e,t){let s={};t.title&&(s.subject=t.title),t.description&&(s.body={contentType:"text",content:t.description}),t.location&&(s.location={displayName:t.location}),t.start&&(s.start={dateTime:t.start.toISOString(),timeZone:"UTC"}),t.end&&(s.end={dateTime:t.end.toISOString(),timeZone:"UTC"});let r=await this.graphRequest(`/me/events/${e}`,{method:"PATCH",body:JSON.stringify(s)});return this.mapEvent(r)}async deleteEvent(e){await this.graphRequest(`/me/events/${e}`,{method:"DELETE"})}async checkAvailability(e,t){let r=(await this.listEvents(e,t)).filter(n=>!n.allDay&&n.start<t&&n.end>e);return{available:r.length===0,conflicts:r}}mapEvent(e){return{id:e.id,title:e.subject??"(No title)",start:new Date(e.start?.dateTime),end:new Date(e.end?.dateTime),location:e.location?.displayName??void 0,description:e.body?.content??void 0,allDay:e.isAllDay??!1}}}});async function It(c){switch(c.provider){case"caldav":{if(!c.caldav)throw new Error("CalDAV config missing");let{CalDAVProvider:e}=await Promise.resolve().then(()=>(Vs(),Cn)),t=new e(c.caldav);return await t.initialize(),t}case"google":{if(!c.google)throw new Error("Google Calendar config missing");let{GoogleCalendarProvider:e}=await Promise.resolve().then(()=>(Gs(),Un)),t=new e(c.google);return await t.initialize(),t}case"microsoft":{if(!c.microsoft)throw new Error("Microsoft Calendar config missing");let{MicrosoftCalendarProvider:e}=await Promise.resolve().then(()=>(Ys(),Pn)),t=new e(c.microsoft);return await t.initialize(),t}default:throw new Error(`Unknown calendar provider: ${c.provider}`)}}var Fn=f(()=>{"use strict";d(It,"createCalendarProvider")});var ye,jn=f(()=>{"use strict";D();ye=class extends _{static{d(this,"CalendarSkill")}calendarProvider;timezone;metadata={name:"calendar",description:"Manage calendar events. List upcoming events, create new events, update or delete existing ones, and check availability.",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list_events","create_event","update_event","delete_event","check_availability"],description:"The calendar action to perform"},start:{type:"string",description:"Start date/time in ISO 8601 format"},end:{type:"string",description:"End date/time in ISO 8601 format"},title:{type:"string",description:"Event title (for create/update)"},location:{type:"string",description:"Event location (for create/update)"},description:{type:"string",description:"Event description (for create/update)"},event_id:{type:"string",description:"Event ID (for update/delete)"},all_day:{type:"boolean",description:"Whether this is an all-day event"}},required:["action"]}};constructor(e,t){super(),this.calendarProvider=e,this.timezone=t}async execute(e,t){let s=e.action;switch(s){case"list_events":return this.listEvents(e);case"create_event":return this.createEvent(e);case"update_event":return this.updateEvent(e);case"delete_event":return this.deleteEvent(e);case"check_availability":return this.checkAvailability(e);default:return{success:!1,error:`Unknown action: "${String(s)}"`}}}async getTodayEvents(){let e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()),s=new Date(e.getFullYear(),e.getMonth(),e.getDate()+1);try{return await this.calendarProvider.listEvents(t,s)}catch(r){return console.error("[calendar] Failed to fetch today events",r),[]}}async listEvents(e){let t=e.start?new Date(e.start):new Date,s=e.end?new Date(e.end):new Date(t.getTime()+7*24*60*60*1e3);try{let r=await this.calendarProvider.listEvents(t,s);if(r.length===0)return{success:!0,data:[],display:"No events found in this time range."};let n=r.map(o=>this.formatEvent(o)).join(`
411
413
  `);return{success:!0,data:r,display:`${r.length} event(s):
412
414
  ${n}`}}catch(r){return{success:!1,error:`Failed to list events: ${r instanceof Error?r.message:String(r)}`}}}async createEvent(e){let t=e.title,s=e.start,r=e.end;if(!t)return{success:!1,error:'Missing required field "title"'};if(!s)return{success:!1,error:'Missing required field "start"'};if(!r)return{success:!1,error:'Missing required field "end"'};try{let n=await this.calendarProvider.createEvent({title:t,start:new Date(s),end:new Date(r),location:e.location,description:e.description,allDay:e.all_day});return{success:!0,data:n,display:`Event created: ${this.formatEvent(n)}`}}catch(n){return{success:!1,error:`Failed to create event: ${n instanceof Error?n.message:String(n)}`}}}async updateEvent(e){let t=e.event_id;if(!t)return{success:!1,error:'Missing required field "event_id"'};try{let s=await this.calendarProvider.updateEvent(t,{title:e.title,start:e.start?new Date(e.start):void 0,end:e.end?new Date(e.end):void 0,location:e.location,description:e.description,allDay:e.all_day});return{success:!0,data:s,display:`Event updated: ${this.formatEvent(s)}`}}catch(s){return{success:!1,error:`Failed to update event: ${s instanceof Error?s.message:String(s)}`}}}async deleteEvent(e){let t=e.event_id;if(!t)return{success:!1,error:'Missing required field "event_id"'};try{return await this.calendarProvider.deleteEvent(t),{success:!0,data:{deleted:t},display:`Event "${t}" deleted.`}}catch(s){return{success:!1,error:`Failed to delete event: ${s instanceof Error?s.message:String(s)}`}}}async checkAvailability(e){let t=e.start,s=e.end;if(!t||!s)return{success:!1,error:'Missing required fields "start" and "end"'};try{let r=await this.calendarProvider.checkAvailability(new Date(t),new Date(s)),n=r.available?"Time slot is available.":`Time slot has ${r.conflicts.length} conflict(s):
413
415
  ${r.conflicts.map(o=>this.formatEvent(o)).join(`
414
- `)}`;return{success:!0,data:r,display:n}}catch(r){return{success:!1,error:`Failed to check availability: ${r instanceof Error?r.message:String(r)}`}}}formatEvent(e){let t={hour:"2-digit",minute:"2-digit",...this.timezone?{timeZone:this.timezone}:{}};if(e.allDay)return`- All day: ${e.title}${e.location?` @ ${e.location}`:""}`;let s=e.start.toLocaleTimeString("en-GB",t),r=e.end.toLocaleTimeString("en-GB",t);return`- ${s}-${r}: ${e.title}${e.location?` @ ${e.location}`:""}`}}});var Bn=f(()=>{"use strict";$t();Vs();Gs();Ys();Fn();jn()});var Ve,Wn=f(()=>{"use strict";D();Ve=class extends b{static{d(this,"CrossPlatformSkill")}users;linkTokens;adapters;metadata={name:"cross_platform",description:"Manage cross-platform identity linking and messaging. Actions: link_start (generate a linking code on current platform), link_confirm (enter a code from another platform to link accounts), send_message (send a message to a linked platform), list_identities (show all linked platforms), unlink (remove a platform link).",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["link_start","link_confirm","send_message","list_identities","unlink"],description:"The action to perform"},code:{type:"string",description:"The 6-digit linking code (for link_confirm)"},platform:{type:"string",description:"Target platform (for send_message or unlink)"},chat_id:{type:"string",description:"Target chat ID (for send_message)"},message:{type:"string",description:"Message text to send (for send_message)"}},required:["action"]}};constructor(e,t,s){super(),this.users=e,this.linkTokens=t,this.adapters=s}async execute(e,t){let s=e.action;switch(s){case"link_start":return this.linkStart(t);case"link_confirm":return this.linkConfirm(e,t);case"send_message":return this.sendMessage(e);case"list_identities":return this.listIdentities(t);case"unlink":return this.unlink(e,t);default:return{success:!1,error:`Unknown action: ${s}`}}}failedConfirmAttempts=new Map;checkConfirmRateLimit(e){let t=Date.now(),s=this.failedConfirmAttempts.get(e);return s&&t<s.resetAt&&s.count>=5?`Too many failed attempts. Please wait ${Math.ceil((s.resetAt-t)/1e3)}s before trying again.`:null}recordFailedConfirm(e){let t=Date.now(),s=this.failedConfirmAttempts.get(e);s&&t<s.resetAt?s.count++:this.failedConfirmAttempts.set(e,{count:1,resetAt:t+5*6e4})}async linkStart(e){if(this.linkTokens.cleanup(),this.linkTokens.countRecentByUser(e.userId,10)>=5)return{success:!1,error:"Too many linking codes generated recently. Please wait a few minutes."};let s=this.linkTokens.create(e.userId,e.platform);return{success:!0,data:{code:s.code,expiresAt:s.expiresAt},display:`Your linking code is: **${s.code}**
416
+ `)}`;return{success:!0,data:r,display:n}}catch(r){return{success:!1,error:`Failed to check availability: ${r instanceof Error?r.message:String(r)}`}}}formatEvent(e){let t={hour:"2-digit",minute:"2-digit",...this.timezone?{timeZone:this.timezone}:{}};if(e.allDay)return`- All day: ${e.title}${e.location?` @ ${e.location}`:""}`;let s=e.start.toLocaleTimeString("en-GB",t),r=e.end.toLocaleTimeString("en-GB",t);return`- ${s}-${r}: ${e.title}${e.location?` @ ${e.location}`:""}`}}});var Bn=f(()=>{"use strict";$t();Vs();Gs();Ys();Fn();jn()});var Ve,Wn=f(()=>{"use strict";D();Ve=class extends _{static{d(this,"CrossPlatformSkill")}users;linkTokens;adapters;metadata={name:"cross_platform",description:"Manage cross-platform identity linking and messaging. Actions: link_start (generate a linking code on current platform), link_confirm (enter a code from another platform to link accounts), send_message (send a message to a linked platform), list_identities (show all linked platforms), unlink (remove a platform link).",riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["link_start","link_confirm","send_message","list_identities","unlink"],description:"The action to perform"},code:{type:"string",description:"The 6-digit linking code (for link_confirm)"},platform:{type:"string",description:"Target platform (for send_message or unlink)"},chat_id:{type:"string",description:"Target chat ID (for send_message)"},message:{type:"string",description:"Message text to send (for send_message)"}},required:["action"]}};constructor(e,t,s){super(),this.users=e,this.linkTokens=t,this.adapters=s}async execute(e,t){let s=e.action;switch(s){case"link_start":return this.linkStart(t);case"link_confirm":return this.linkConfirm(e,t);case"send_message":return this.sendMessage(e);case"list_identities":return this.listIdentities(t);case"unlink":return this.unlink(e,t);default:return{success:!1,error:`Unknown action: ${s}`}}}failedConfirmAttempts=new Map;checkConfirmRateLimit(e){let t=Date.now(),s=this.failedConfirmAttempts.get(e);return s&&t<s.resetAt&&s.count>=5?`Too many failed attempts. Please wait ${Math.ceil((s.resetAt-t)/1e3)}s before trying again.`:null}recordFailedConfirm(e){let t=Date.now(),s=this.failedConfirmAttempts.get(e);s&&t<s.resetAt?s.count++:this.failedConfirmAttempts.set(e,{count:1,resetAt:t+5*6e4})}async linkStart(e){if(this.linkTokens.cleanup(),this.linkTokens.countRecentByUser(e.userId,10)>=5)return{success:!1,error:"Too many linking codes generated recently. Please wait a few minutes."};let s=this.linkTokens.create(e.userId,e.platform);return{success:!0,data:{code:s.code,expiresAt:s.expiresAt},display:`Your linking code is: **${s.code}**
415
417
 
416
418
  Enter this code on your other platform within 10 minutes using:
417
419
  "Link my account with code ${s.code}"`}}async linkConfirm(e,t){let s=e.code;if(!s)return{success:!1,error:'Missing required field "code"'};let r=this.checkConfirmRateLimit(t.userId);if(r)return{success:!1,error:r};let n=this.linkTokens.findByCode(s.trim());if(!n)return this.recordFailedConfirm(t.userId),{success:!1,error:"Invalid or expired linking code. Please generate a new one."};if(n.userId===t.userId)return{success:!1,error:"Cannot link an account to itself. Use the code on a different platform."};let o=this.users.getMasterUserId(n.userId),i=this.users.getMasterUserId(t.userId),a;if(o!==n.userId?a=o:i!==t.userId?a=i:a=n.userId,o!==n.userId&&i!==t.userId&&o!==i){let p=this.users.getLinkedUsers(i);for(let m of p)this.users.setMasterUser(m.id,a)}n.userId!==a&&this.users.setMasterUser(n.userId,a),t.userId!==a&&this.users.setMasterUser(t.userId,a),this.linkTokens.consume(n.id);let l=this.users.findById(n.userId),u=n.platform;return{success:!0,data:{masterUserId:a,linkedPlatform:u},display:`Account linked successfully! Your ${u} account (${l?.displayName??l?.username??"unknown"}) is now linked to this ${t.platform} account.
@@ -419,18 +421,18 @@ Enter this code on your other platform within 10 minutes using:
419
421
  Your memories, preferences, and context are now shared across platforms.`}}async sendMessage(e){let t=e.platform,s=e.chat_id,r=e.message;if(!t)return{success:!1,error:'Missing required field "platform"'};if(!s)return{success:!1,error:'Missing required field "chat_id"'};if(!r)return{success:!1,error:'Missing required field "message"'};let n=this.adapters.get(t);if(!n)return{success:!1,error:`Platform "${t}" is not connected. Available: ${[...this.adapters.keys()].join(", ")}`};try{return{success:!0,data:{messageId:await n.sendMessage(s,r),platform:t,chatId:s},display:`Message sent to ${t} (chat ${s}).`}}catch(o){return{success:!1,error:`Failed to send message: ${o instanceof Error?o.message:String(o)}`}}}async listIdentities(e){let t=this.users.getMasterUserId(e.userId),s=this.users.getLinkedUsers(t);if(s.length<=1)return{success:!0,data:{identities:s},display:`No linked accounts found. To link another platform, use:
420
422
  "Start linking my account" on the platform you want to link from, then enter the code on the other platform.`};let r=s.map(n=>{let o=n.id===e.userId?" (current)":"",i=n.displayName??n.username??n.platformUserId;return`- **${n.platform}**: ${i}${o}`});return{success:!0,data:{identities:s.map(n=>({platform:n.platform,username:n.username,displayName:n.displayName}))},display:`Linked accounts:
421
423
  ${r.join(`
422
- `)}`}}async unlink(e,t){let s=e.platform;if(!s)return{success:!1,error:'Missing required field "platform"'};let r=this.users.getMasterUserId(t.userId),o=this.users.getLinkedUsers(r).find(i=>i.platform===s&&i.id!==t.userId);return o?(this.users.setMasterUser(o.id,o.id),{success:!0,data:{unlinkedPlatform:s,unlinkedUserId:o.id},display:`Unlinked ${s} account (${o.displayName??o.username??o.platformUserId}).`}):{success:!1,error:`No linked account found on platform "${s}".`}}}});var Ge,Hn=f(()=>{"use strict";D();Ge=class extends b{static{d(this,"BackgroundTaskSkill")}taskRepo;metadata={name:"background_task",description:'Schedule, list, or cancel background tasks that run independently. Use "schedule" to queue a skill to execute in the background (user will be notified when done). Use "list" to see active/recent tasks. Use "cancel" to stop a pending or running task.',riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["schedule","list","cancel"],description:"The background task action to perform"},description:{type:"string",description:"Human-readable description of what the task does (for schedule)"},skill_name:{type:"string",description:"The skill to run in the background (for schedule)"},skill_input:{type:"object",description:"Input to pass to the skill (for schedule)"},task_id:{type:"string",description:"Task ID (for cancel)"}},required:["action"]}};constructor(e){super(),this.taskRepo=e}async execute(e,t){let s=e.action;switch(s){case"schedule":return this.scheduleTask(e,t);case"list":return this.listTasks(t);case"cancel":return this.cancelTask(e);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: schedule, list, cancel`}}}scheduleTask(e,t){let s=e.description,r=e.skill_name,n=e.skill_input;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "description" for schedule action'};if(!r||typeof r!="string")return{success:!1,error:'Missing required field "skill_name" for schedule action'};let o=this.taskRepo.create(t.userId,t.platform,t.chatId,s,r,JSON.stringify(n??{}));return{success:!0,data:{taskId:o.id,description:s,skillName:r,status:o.status},display:`Background task scheduled (${o.id}): "${s}" using skill "${r}". You'll be notified when it completes.`}}listTasks(e){let t=this.taskRepo.getByUser(e.userId);if(t.length===0)return{success:!0,data:[],display:"No active or recent background tasks."};let s={pending:"\u23F3",running:"\u25B6\uFE0F",completed:"\u2705",failed:"\u274C"},r=t.map(n=>`- ${s[n.status]??"?"} ${n.id}: "${n.description}" [${n.status}] (${n.skillName})`);return{success:!0,data:t.map(n=>({taskId:n.id,description:n.description,status:n.status,skillName:n.skillName,createdAt:n.createdAt,completedAt:n.completedAt})),display:`Background tasks:
424
+ `)}`}}async unlink(e,t){let s=e.platform;if(!s)return{success:!1,error:'Missing required field "platform"'};let r=this.users.getMasterUserId(t.userId),o=this.users.getLinkedUsers(r).find(i=>i.platform===s&&i.id!==t.userId);return o?(this.users.setMasterUser(o.id,o.id),{success:!0,data:{unlinkedPlatform:s,unlinkedUserId:o.id},display:`Unlinked ${s} account (${o.displayName??o.username??o.platformUserId}).`}):{success:!1,error:`No linked account found on platform "${s}".`}}}});var Ge,Hn=f(()=>{"use strict";D();Ge=class extends _{static{d(this,"BackgroundTaskSkill")}taskRepo;metadata={name:"background_task",description:'Schedule, list, or cancel background tasks that run independently. Use "schedule" to queue a skill to execute in the background (user will be notified when done). Use "list" to see active/recent tasks. Use "cancel" to stop a pending or running task.',riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["schedule","list","cancel"],description:"The background task action to perform"},description:{type:"string",description:"Human-readable description of what the task does (for schedule)"},skill_name:{type:"string",description:"The skill to run in the background (for schedule)"},skill_input:{type:"object",description:"Input to pass to the skill (for schedule)"},task_id:{type:"string",description:"Task ID (for cancel)"}},required:["action"]}};constructor(e){super(),this.taskRepo=e}async execute(e,t){let s=e.action;switch(s){case"schedule":return this.scheduleTask(e,t);case"list":return this.listTasks(t);case"cancel":return this.cancelTask(e);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: schedule, list, cancel`}}}scheduleTask(e,t){let s=e.description,r=e.skill_name,n=e.skill_input;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "description" for schedule action'};if(!r||typeof r!="string")return{success:!1,error:'Missing required field "skill_name" for schedule action'};let o=this.taskRepo.create(t.userId,t.platform,t.chatId,s,r,JSON.stringify(n??{}));return{success:!0,data:{taskId:o.id,description:s,skillName:r,status:o.status},display:`Background task scheduled (${o.id}): "${s}" using skill "${r}". You'll be notified when it completes.`}}listTasks(e){let t=this.taskRepo.getByUser(e.userId);if(t.length===0)return{success:!0,data:[],display:"No active or recent background tasks."};let s={pending:"\u23F3",running:"\u25B6\uFE0F",completed:"\u2705",failed:"\u274C"},r=t.map(n=>`- ${s[n.status]??"?"} ${n.id}: "${n.description}" [${n.status}] (${n.skillName})`);return{success:!0,data:t.map(n=>({taskId:n.id,description:n.description,status:n.status,skillName:n.skillName,createdAt:n.createdAt,completedAt:n.completedAt})),display:`Background tasks:
423
425
  ${r.join(`
424
- `)}`}}cancelTask(e){let t=e.task_id;return!t||typeof t!="string"?{success:!1,error:'Missing required field "task_id" for cancel action'}:this.taskRepo.cancel(t)?{success:!0,data:{taskId:t},display:`Background task "${t}" cancelled.`}:{success:!1,error:`Task "${t}" not found or already completed`}}}});var Ye,Xn=f(()=>{"use strict";D();Ye=class extends b{static{d(this,"ScheduledTaskSkill")}actionRepo;metadata={name:"scheduled_task",description:'Create, list, enable, disable, or delete scheduled actions that run automatically on a recurring basis. Supports cron expressions (e.g. "0 9 * * *" for daily at 9 AM), intervals (in minutes), and one-time schedules. Each scheduled action executes a skill or sends a prompt to the LLM at the configured time.',riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","list","enable","disable","delete"],description:"The scheduled task action to perform"},name:{type:"string",description:"Name for the scheduled action (for create)"},description:{type:"string",description:"What the scheduled action does (for create)"},schedule_type:{type:"string",enum:["cron","interval","once"],description:"Type of schedule: cron expression, interval in minutes, or one-time ISO date (for create)"},schedule_value:{type:"string",description:"Schedule value: cron expression, minutes as string, or ISO date (for create)"},skill_name:{type:"string",description:"The skill to execute on schedule (for create)"},skill_input:{type:"object",description:"Input to pass to the skill (for create)"},prompt_template:{type:"string",description:"Optional LLM prompt to run instead of a skill (for create)"},action_id:{type:"string",description:"Scheduled action ID (for enable, disable, delete)"}},required:["action"]}};constructor(e){super(),this.actionRepo=e}async execute(e,t){let s=e.action;switch(s){case"create":return this.createAction(e,t);case"list":return this.listActions(t);case"enable":return this.toggleAction(e,!0);case"disable":return this.toggleAction(e,!1);case"delete":return this.deleteAction(e);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: create, list, enable, disable, delete`}}}createAction(e,t){let s=e.name,r=e.description,n=e.schedule_type,o=e.schedule_value,i=e.skill_name,a=e.skill_input,l=e.prompt_template;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "name" for create action'};if(!r||typeof r!="string")return{success:!1,error:'Missing required field "description" for create action'};if(!n||!["cron","interval","once"].includes(n))return{success:!1,error:'Missing or invalid "schedule_type". Must be "cron", "interval", or "once"'};if(!o||typeof o!="string")return{success:!1,error:'Missing required field "schedule_value" for create action'};if(!i||typeof i!="string")return{success:!1,error:'Missing required field "skill_name" for create action'};if(n==="interval"){let m=parseInt(o,10);if(isNaN(m)||m<=0)return{success:!1,error:"For interval schedule, value must be a positive number of minutes"}}if(n==="cron"&&o.trim().split(/\s+/).length!==5)return{success:!1,error:"Cron expression must have 5 fields: minute hour dayOfMonth month dayOfWeek"};if(n==="once"){let m=new Date(o);if(isNaN(m.getTime()))return{success:!1,error:"For once schedule, value must be a valid ISO date string"};if(m.getTime()<=Date.now())return{success:!1,error:"The scheduled time is in the past. Please specify a future time."}}let u=this.actionRepo.create({userId:t.userId,platform:t.platform,chatId:t.chatId,name:s,description:r,scheduleType:n,scheduleValue:o,skillName:i,skillInput:JSON.stringify(a??{}),promptTemplate:l}),p=n==="cron"?`cron: ${o}`:n==="interval"?`every ${o} minutes`:`once at ${o}`;return{success:!0,data:{actionId:u.id,name:s,scheduleType:n,scheduleValue:o,skillName:i},display:`Scheduled action created (${u.id}): "${s}" \u2014 ${p}, running "${i}"${u.nextRunAt?`. Next run: ${u.nextRunAt}`:""}`}}listActions(e){let t=this.actionRepo.getByUser(e.userId);if(t.length===0)return{success:!0,data:[],display:"No scheduled actions."};let s=t.map(r=>{let n=r.enabled?"\u2705":"\u23F8\uFE0F",o=r.scheduleType==="cron"?`cron: ${r.scheduleValue}`:r.scheduleType==="interval"?`every ${r.scheduleValue} min`:`once: ${r.scheduleValue}`,i=r.nextRunAt?` | next: ${r.nextRunAt}`:"";return`- ${n} ${r.id}: "${r.name}" [${o}] \u2192 ${r.skillName}${i}`});return{success:!0,data:t.map(r=>({actionId:r.id,name:r.name,scheduleType:r.scheduleType,scheduleValue:r.scheduleValue,skillName:r.skillName,enabled:r.enabled,nextRunAt:r.nextRunAt,lastRunAt:r.lastRunAt})),display:`Scheduled actions:
426
+ `)}`}}cancelTask(e){let t=e.task_id;return!t||typeof t!="string"?{success:!1,error:'Missing required field "task_id" for cancel action'}:this.taskRepo.cancel(t)?{success:!0,data:{taskId:t},display:`Background task "${t}" cancelled.`}:{success:!1,error:`Task "${t}" not found or already completed`}}}});var Ye,Xn=f(()=>{"use strict";D();Ye=class extends _{static{d(this,"ScheduledTaskSkill")}actionRepo;metadata={name:"scheduled_task",description:'Create, list, enable, disable, or delete scheduled actions that run automatically on a recurring basis. Supports cron expressions (e.g. "0 9 * * *" for daily at 9 AM), intervals (in minutes), and one-time schedules. Each scheduled action executes a skill or sends a prompt to the LLM at the configured time.',riskLevel:"write",version:"1.0.0",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","list","enable","disable","delete"],description:"The scheduled task action to perform"},name:{type:"string",description:"Name for the scheduled action (for create)"},description:{type:"string",description:"What the scheduled action does (for create)"},schedule_type:{type:"string",enum:["cron","interval","once"],description:"Type of schedule: cron expression, interval in minutes, or one-time ISO date (for create)"},schedule_value:{type:"string",description:"Schedule value: cron expression, minutes as string, or ISO date (for create)"},skill_name:{type:"string",description:"The skill to execute on schedule (for create)"},skill_input:{type:"object",description:"Input to pass to the skill (for create)"},prompt_template:{type:"string",description:"Optional LLM prompt to run instead of a skill (for create)"},action_id:{type:"string",description:"Scheduled action ID (for enable, disable, delete)"}},required:["action"]}};constructor(e){super(),this.actionRepo=e}async execute(e,t){let s=e.action;switch(s){case"create":return this.createAction(e,t);case"list":return this.listActions(t);case"enable":return this.toggleAction(e,!0);case"disable":return this.toggleAction(e,!1);case"delete":return this.deleteAction(e);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: create, list, enable, disable, delete`}}}createAction(e,t){let s=e.name,r=e.description,n=e.schedule_type,o=e.schedule_value,i=e.skill_name,a=e.skill_input,l=e.prompt_template;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "name" for create action'};if(!r||typeof r!="string")return{success:!1,error:'Missing required field "description" for create action'};if(!n||!["cron","interval","once"].includes(n))return{success:!1,error:'Missing or invalid "schedule_type". Must be "cron", "interval", or "once"'};if(!o||typeof o!="string")return{success:!1,error:'Missing required field "schedule_value" for create action'};if(!i||typeof i!="string")return{success:!1,error:'Missing required field "skill_name" for create action'};if(n==="interval"){let m=parseInt(o,10);if(isNaN(m)||m<=0)return{success:!1,error:"For interval schedule, value must be a positive number of minutes"}}if(n==="cron"&&o.trim().split(/\s+/).length!==5)return{success:!1,error:"Cron expression must have 5 fields: minute hour dayOfMonth month dayOfWeek"};if(n==="once"){let m=new Date(o);if(isNaN(m.getTime()))return{success:!1,error:"For once schedule, value must be a valid ISO date string"};if(m.getTime()<=Date.now())return{success:!1,error:"The scheduled time is in the past. Please specify a future time."}}let u=this.actionRepo.create({userId:t.userId,platform:t.platform,chatId:t.chatId,name:s,description:r,scheduleType:n,scheduleValue:o,skillName:i,skillInput:JSON.stringify(a??{}),promptTemplate:l}),p=n==="cron"?`cron: ${o}`:n==="interval"?`every ${o} minutes`:`once at ${o}`;return{success:!0,data:{actionId:u.id,name:s,scheduleType:n,scheduleValue:o,skillName:i},display:`Scheduled action created (${u.id}): "${s}" \u2014 ${p}, running "${i}"${u.nextRunAt?`. Next run: ${u.nextRunAt}`:""}`}}listActions(e){let t=this.actionRepo.getByUser(e.userId);if(t.length===0)return{success:!0,data:[],display:"No scheduled actions."};let s=t.map(r=>{let n=r.enabled?"\u2705":"\u23F8\uFE0F",o=r.scheduleType==="cron"?`cron: ${r.scheduleValue}`:r.scheduleType==="interval"?`every ${r.scheduleValue} min`:`once: ${r.scheduleValue}`,i=r.nextRunAt?` | next: ${r.nextRunAt}`:"";return`- ${n} ${r.id}: "${r.name}" [${o}] \u2192 ${r.skillName}${i}`});return{success:!0,data:t.map(r=>({actionId:r.id,name:r.name,scheduleType:r.scheduleType,scheduleValue:r.scheduleValue,skillName:r.skillName,enabled:r.enabled,nextRunAt:r.nextRunAt,lastRunAt:r.lastRunAt})),display:`Scheduled actions:
425
427
  ${s.join(`
426
428
  `)}`}}toggleAction(e,t){let s=e.action_id;return!s||typeof s!="string"?{success:!1,error:`Missing required field "action_id" for ${t?"enable":"disable"} action`}:this.actionRepo.setEnabled(s,t)?{success:!0,data:{actionId:s,enabled:t},display:`Scheduled action "${s}" ${t?"enabled":"disabled"}.`}:{success:!1,error:`Scheduled action "${s}" not found`}}deleteAction(e){let t=e.action_id;return!t||typeof t!="string"?{success:!1,error:'Missing required field "action_id" for delete action'}:this.actionRepo.delete(t)?{success:!0,data:{actionId:t},display:`Scheduled action "${t}" deleted.`}:{success:!1,error:`Scheduled action "${t}" not found`}}}});var we,Js=f(()=>{"use strict";we=class{static{d(this,"MCPClient")}serverName;config;logger;client;transport;connected=!1;constructor(e,t,s){this.serverName=e,this.config=t,this.logger=s}async connect(){try{let{Client:e}=await import("@modelcontextprotocol/sdk/client/index.js");if(this.client=new e({name:`alfred-${this.serverName}`,version:"1.0.0"},{capabilities:{}}),this.config.command){let{StdioClientTransport:t}=await import("@modelcontextprotocol/sdk/client/stdio.js"),s={PATH:process.env.PATH??"",HOME:process.env.HOME??process.env.USERPROFILE??"",LANG:process.env.LANG??"en_US.UTF-8",NODE_ENV:process.env.NODE_ENV??"",SYSTEMROOT:process.env.SYSTEMROOT??""};if(this.config.env)for(let[r,n]of Object.entries(this.config.env))s[r]=n.replace(/\$\{(\w+)\}/g,(o,i)=>process.env[i]??"");this.transport=new t({command:this.config.command,args:this.config.args??[],env:s})}else if(this.config.url){let{SSEClientTransport:t}=await import("@modelcontextprotocol/sdk/client/sse.js");this.transport=new t(new URL(this.config.url))}else throw new Error(`MCP server "${this.serverName}": must specify either command or url`);await this.client.connect(this.transport),this.connected=!0,this.logger.info({server:this.serverName},"MCP server connected")}catch(e){throw this.logger.error({server:this.serverName,err:e},"Failed to connect MCP server"),e}}async listTools(){if(!this.connected||!this.client)return[];try{return((await this.client.listTools()).tools??[]).map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema??{type:"object",properties:{}}}))}catch(e){return this.logger.error({server:this.serverName,err:e},"Failed to list MCP tools"),[]}}async callTool(e,t){if(!this.connected||!this.client)return{content:"MCP server not connected",isError:!0};try{let s=await this.client.callTool({name:e,arguments:t});return{content:(s.content??[]).map(n=>n.text??JSON.stringify(n)).join(`
427
- `),isError:s.isError}}catch(s){return{content:`MCP tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}}async disconnect(){if(this.transport)try{await this.transport.close?.()}catch{}this.connected=!1,this.logger.info({server:this.serverName},"MCP server disconnected")}}});var Ee,Zs=f(()=>{"use strict";D();Ee=class extends b{static{d(this,"MCPSkillAdapter")}client;serverName;toolName;metadata;constructor(e,t,s,r,n){super(),this.client=e,this.serverName=t,this.toolName=s,this.metadata={name:`mcp__${t}__${s}`,description:`[MCP/${t}] ${r||s}`,riskLevel:"write",version:"1.0.0",inputSchema:n}}async execute(e,t){let s=await this.client.callTool(this.toolName,e);return{success:s.isError!==!0,data:s.content,display:s.content,error:s.isError===!0?s.content:void 0}}}});var At,zn=f(()=>{"use strict";Js();Zs();At=class{static{d(this,"MCPManager")}logger;clients=[];skills=[];constructor(e){this.logger=e}async initialize(e){for(let t of e.servers)try{let s=new we(t.name,t,this.logger.child({mcp:t.name}));await s.connect(),this.clients.push(s);let r=await s.listTools();for(let n of r){let o=new Ee(s,t.name,n.name,n.description??"",n.inputSchema);this.skills.push(o)}this.logger.info({server:t.name,tools:r.length},"MCP server initialized")}catch(s){this.logger.error({server:t.name,err:s},"Failed to initialize MCP server")}}getSkills(){return this.skills}async shutdown(){for(let e of this.clients)await e.disconnect();this.clients.length=0,this.skills.length=0}}});var qn=f(()=>{"use strict";Js();Zs();zn()});import{spawn as Ci}from"node:child_process";import Je from"node:fs";import Qs from"node:path";import Ui from"node:os";import Pi from"node:crypto";var Te,er=f(()=>{"use strict";Te=class{static{d(this,"CodeExecutor")}async execute(e,t,s){let r=Math.min(s?.timeout??3e4,12e4),n=Qs.join(Ui.tmpdir(),`alfred-sandbox-${Pi.randomUUID()}`);Je.mkdirSync(n,{recursive:!0});try{let o=t==="javascript"?"js":"py",i=Qs.join(n,`script.${o}`);Je.writeFileSync(i,e);let a=t==="javascript"?"node":process.platform==="win32"?"python":"python3",l=[i],u=Date.now();return await new Promise(p=>{let m=Ci(a,l,{cwd:n,timeout:r,env:{PATH:process.env.PATH??"",HOME:process.env.HOME??process.env.USERPROFILE??"",LANG:process.env.LANG??"en_US.UTF-8",NODE_ENV:"sandbox",PYTHONDONTWRITEBYTECODE:"1",...s?.env,TMPDIR:n,TEMP:n,TMP:n},stdio:["pipe","pipe","pipe"]}),h="",w="";m.stdout.on("data",E=>{h+=E.toString()}),m.stderr.on("data",E=>{w+=E.toString()}),m.on("close",E=>{let T=Date.now()-u,k=[];try{let _=Je.readdirSync(n).filter(v=>!v.startsWith("script."));for(let v of _){let M=Qs.join(n,v),x=Je.statSync(M);if(x.isFile()&&x.size<1e7){let A=Je.readFileSync(M),C=v.endsWith(".png")?"image/png":v.endsWith(".jpg")||v.endsWith(".jpeg")?"image/jpeg":v.endsWith(".svg")?"image/svg+xml":v.endsWith(".csv")?"text/csv":v.endsWith(".json")?"application/json":"application/octet-stream";k.push({name:v,data:A,mimeType:C})}}}catch{}p({stdout:h.slice(0,5e4),stderr:w.slice(0,1e4),exitCode:E??1,files:k.length>0?k:void 0,durationMs:T})}),m.on("error",E=>{p({stdout:"",stderr:E.message,exitCode:1,durationMs:Date.now()-u})}),m.stdin.end()})}finally{try{Je.rmSync(n,{recursive:!0,force:!0})}catch{}}}}});var Rt,Kn=f(()=>{"use strict";D();er();Rt=class extends b{static{d(this,"CodeExecutionSkill")}metadata={name:"code_sandbox",description:"Execute code in a sandboxed environment. Supports JavaScript (Node.js) and Python. Use for calculations, data processing, generating charts, or testing code snippets. Code runs in an isolated temp directory with a timeout.",riskLevel:"destructive",version:"1.0.0",timeoutMs:12e4,inputSchema:{type:"object",properties:{action:{type:"string",enum:["run","run_with_data"],description:"Action to perform"},code:{type:"string",description:"Code to execute"},language:{type:"string",enum:["javascript","python"],description:"Programming language"},data:{type:"string",description:"Input data to pass (available as DATA env var or stdin)"},timeout:{type:"number",description:"Timeout in ms (max 120000)"}},required:["action","code","language"]}};executor=new Te;allowedLanguages;maxTimeout;constructor(e){super(),this.allowedLanguages=new Set(e?.allowedLanguages??["javascript","python"]),this.maxTimeout=e?.maxTimeoutMs??12e4}async execute(e,t){let s=e.action,r=e.code,n=e.language,o=e.data,i=Math.min(e.timeout??3e4,this.maxTimeout);if(!r)return{success:!1,error:'Missing required field "code"'};if(!n)return{success:!1,error:'Missing required field "language"'};if(!this.allowedLanguages.has(n))return{success:!1,error:`Language "${n}" is not allowed. Allowed: ${[...this.allowedLanguages].join(", ")}`};let a=r;s==="run_with_data"&&o&&(n==="javascript"?a=`const INPUT_DATA = ${JSON.stringify(o)};
429
+ `),isError:s.isError}}catch(s){return{content:`MCP tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}}async disconnect(){if(this.transport)try{await this.transport.close?.()}catch{}this.connected=!1,this.logger.info({server:this.serverName},"MCP server disconnected")}}});var Ee,Zs=f(()=>{"use strict";D();Ee=class extends _{static{d(this,"MCPSkillAdapter")}client;serverName;toolName;metadata;constructor(e,t,s,r,n){super(),this.client=e,this.serverName=t,this.toolName=s,this.metadata={name:`mcp__${t}__${s}`,description:`[MCP/${t}] ${r||s}`,riskLevel:"write",version:"1.0.0",inputSchema:n}}async execute(e,t){let s=await this.client.callTool(this.toolName,e);return{success:s.isError!==!0,data:s.content,display:s.content,error:s.isError===!0?s.content:void 0}}}});var At,zn=f(()=>{"use strict";Js();Zs();At=class{static{d(this,"MCPManager")}logger;clients=[];skills=[];constructor(e){this.logger=e}async initialize(e){for(let t of e.servers)try{let s=new we(t.name,t,this.logger.child({mcp:t.name}));await s.connect(),this.clients.push(s);let r=await s.listTools();for(let n of r){let o=new Ee(s,t.name,n.name,n.description??"",n.inputSchema);this.skills.push(o)}this.logger.info({server:t.name,tools:r.length},"MCP server initialized")}catch(s){this.logger.error({server:t.name,err:s},"Failed to initialize MCP server")}}getSkills(){return this.skills}async shutdown(){for(let e of this.clients)await e.disconnect();this.clients.length=0,this.skills.length=0}}});var qn=f(()=>{"use strict";Js();Zs();zn()});import{spawn as Ci}from"node:child_process";import Je from"node:fs";import Qs from"node:path";import Ui from"node:os";import Pi from"node:crypto";var Te,er=f(()=>{"use strict";Te=class{static{d(this,"CodeExecutor")}async execute(e,t,s){let r=Math.min(s?.timeout??3e4,12e4),n=Qs.join(Ui.tmpdir(),`alfred-sandbox-${Pi.randomUUID()}`);Je.mkdirSync(n,{recursive:!0});try{let o=t==="javascript"?"js":"py",i=Qs.join(n,`script.${o}`);Je.writeFileSync(i,e);let a=t==="javascript"?"node":process.platform==="win32"?"python":"python3",l=[i],u=Date.now();return await new Promise(p=>{let m=Ci(a,l,{cwd:n,timeout:r,env:{PATH:process.env.PATH??"",HOME:process.env.HOME??process.env.USERPROFILE??"",LANG:process.env.LANG??"en_US.UTF-8",NODE_ENV:"sandbox",PYTHONDONTWRITEBYTECODE:"1",...s?.env,TMPDIR:n,TEMP:n,TMP:n},stdio:["pipe","pipe","pipe"]}),h="",w="";m.stdout.on("data",E=>{h+=E.toString()}),m.stderr.on("data",E=>{w+=E.toString()}),m.on("close",E=>{let T=Date.now()-u,k=[];try{let v=Je.readdirSync(n).filter(b=>!b.startsWith("script."));for(let b of v){let A=Qs.join(n,b),x=Je.statSync(A);if(x.isFile()&&x.size<1e7){let L=Je.readFileSync(A),P=b.endsWith(".png")?"image/png":b.endsWith(".jpg")||b.endsWith(".jpeg")?"image/jpeg":b.endsWith(".svg")?"image/svg+xml":b.endsWith(".csv")?"text/csv":b.endsWith(".json")?"application/json":"application/octet-stream";k.push({name:b,data:L,mimeType:P})}}}catch{}p({stdout:h.slice(0,5e4),stderr:w.slice(0,1e4),exitCode:E??1,files:k.length>0?k:void 0,durationMs:T})}),m.on("error",E=>{p({stdout:"",stderr:E.message,exitCode:1,durationMs:Date.now()-u})}),m.stdin.end()})}finally{try{Je.rmSync(n,{recursive:!0,force:!0})}catch{}}}}});var Rt,Kn=f(()=>{"use strict";D();er();Rt=class extends _{static{d(this,"CodeExecutionSkill")}metadata={name:"code_sandbox",description:"Execute code in a sandboxed environment. Supports JavaScript (Node.js) and Python. Use for calculations, data processing, generating charts, or testing code snippets. Code runs in an isolated temp directory with a timeout.",riskLevel:"destructive",version:"1.0.0",timeoutMs:12e4,inputSchema:{type:"object",properties:{action:{type:"string",enum:["run","run_with_data"],description:"Action to perform"},code:{type:"string",description:"Code to execute"},language:{type:"string",enum:["javascript","python"],description:"Programming language"},data:{type:"string",description:"Input data to pass (available as DATA env var or stdin)"},timeout:{type:"number",description:"Timeout in ms (max 120000)"}},required:["action","code","language"]}};executor=new Te;allowedLanguages;maxTimeout;constructor(e){super(),this.allowedLanguages=new Set(e?.allowedLanguages??["javascript","python"]),this.maxTimeout=e?.maxTimeoutMs??12e4}async execute(e,t){let s=e.action,r=e.code,n=e.language,o=e.data,i=Math.min(e.timeout??3e4,this.maxTimeout);if(!r)return{success:!1,error:'Missing required field "code"'};if(!n)return{success:!1,error:'Missing required field "language"'};if(!this.allowedLanguages.has(n))return{success:!1,error:`Language "${n}" is not allowed. Allowed: ${[...this.allowedLanguages].join(", ")}`};let a=r;s==="run_with_data"&&o&&(n==="javascript"?a=`const INPUT_DATA = ${JSON.stringify(o)};
428
430
  ${r}`:a=`INPUT_DATA = ${JSON.stringify(o)}
429
431
  ${r}`);let l=await this.executor.execute(a,n,{timeout:i}),u=[l.stdout?`Output:
430
432
  ${l.stdout}`:"",l.stderr?`Errors:
431
433
  ${l.stderr}`:"",`Exit code: ${l.exitCode}`,`Duration: ${l.durationMs}ms`].filter(Boolean).join(`
432
434
 
433
- `);return{success:l.exitCode===0,data:{stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode,durationMs:l.durationMs,fileCount:l.files?.length??0},display:u,error:l.exitCode!==0?`Code execution failed with exit code ${l.exitCode}`:void 0}}}});var Vn=f(()=>{"use strict";er();Kn()});var Ze,Gn=f(()=>{"use strict";D();Ze=class extends b{static{d(this,"DocumentSkill")}docRepo;processor;embeddingService;metadata={name:"document",description:"Ingest, search, summarize, list, or delete documents. Supports PDF, DOCX, TXT, CSV, and Markdown files. Documents are chunked and embedded for semantic search.",riskLevel:"write",version:"1.0.0",timeoutMs:12e4,inputSchema:{type:"object",properties:{action:{type:"string",enum:["ingest","search","summarize","list","delete"],description:"Action to perform"},file_path:{type:"string",description:"Path to the file (for ingest)"},filename:{type:"string",description:"Original filename (for ingest)"},mime_type:{type:"string",description:"MIME type of the file (for ingest)"},query:{type:"string",description:"Search query (for search)"},document_id:{type:"string",description:"Document ID (for summarize, delete)"},limit:{type:"number",description:"Max results (for search, list)"}},required:["action"]}};constructor(e,t,s){super(),this.docRepo=e,this.processor=t,this.embeddingService=s}async execute(e,t){let s=e.action;switch(s){case"ingest":return this.ingest(e,t);case"search":return this.search(e,t);case"summarize":return this.summarize(e);case"list":return this.list(e,t);case"delete":return this.deleteDoc(e);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: ingest, search, summarize, list, delete`}}}async ingest(e,t){let s=e.file_path,r=e.filename,n=e.mime_type;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "file_path" for ingest action'};if(!r||typeof r!="string")return{success:!1,error:'Missing required field "filename" for ingest action'};if(!n||typeof n!="string")return{success:!1,error:'Missing required field "mime_type" for ingest action'};let o=await import("node:path"),i=o.resolve(s);if(i!==o.normalize(s)&&s.includes(".."))return{success:!1,error:"Invalid file path: path traversal not allowed"};let a=i.toLowerCase();if(a.startsWith("/etc/")||a.startsWith("/proc/")||a.startsWith("/sys/")||a.startsWith("c:\\windows\\")||a.startsWith("/root/"))return{success:!1,error:"Access to system directories is not allowed"};try{let l=await this.processor.ingest(t.userId,s,r,n);return{success:!0,data:l,display:`Document "${r}" ingested successfully (${l.chunkCount} chunks). ID: ${l.documentId.slice(0,8)}...`}}catch(l){return{success:!1,error:`Failed to ingest document: ${l instanceof Error?l.message:String(l)}`}}}async search(e,t){let s=e.query,r=e.limit||5;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "query" for search action'};if(!this.embeddingService)return{success:!1,error:"Embedding service not available for document search"};let o=(await this.embeddingService.semanticSearch(t.userId,s,r)).filter(a=>a.category==="document");if(o.length===0)return{success:!0,data:[],display:`No document matches found for "${s}".`};let i=o.map((a,l)=>`${l+1}. (score: ${a.score.toFixed(3)}) ${a.value.slice(0,200)}${a.value.length>200?"...":""}`).join(`
435
+ `);return{success:l.exitCode===0,data:{stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode,durationMs:l.durationMs,fileCount:l.files?.length??0},display:u,error:l.exitCode!==0?`Code execution failed with exit code ${l.exitCode}`:void 0}}}});var Vn=f(()=>{"use strict";er();Kn()});var Ze,Gn=f(()=>{"use strict";D();Ze=class extends _{static{d(this,"DocumentSkill")}docRepo;processor;embeddingService;metadata={name:"document",description:"Ingest, search, summarize, list, or delete documents. Supports PDF, DOCX, TXT, CSV, and Markdown files. Documents are chunked and embedded for semantic search.",riskLevel:"write",version:"1.0.0",timeoutMs:12e4,inputSchema:{type:"object",properties:{action:{type:"string",enum:["ingest","search","summarize","list","delete"],description:"Action to perform"},file_path:{type:"string",description:"Path to the file (for ingest)"},filename:{type:"string",description:"Original filename (for ingest)"},mime_type:{type:"string",description:"MIME type of the file (for ingest)"},query:{type:"string",description:"Search query (for search)"},document_id:{type:"string",description:"Document ID (for summarize, delete)"},limit:{type:"number",description:"Max results (for search, list)"}},required:["action"]}};constructor(e,t,s){super(),this.docRepo=e,this.processor=t,this.embeddingService=s}async execute(e,t){let s=e.action;switch(s){case"ingest":return this.ingest(e,t);case"search":return this.search(e,t);case"summarize":return this.summarize(e);case"list":return this.list(e,t);case"delete":return this.deleteDoc(e);default:return{success:!1,error:`Unknown action: "${String(s)}". Valid actions: ingest, search, summarize, list, delete`}}}async ingest(e,t){let s=e.file_path,r=e.filename,n=e.mime_type;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "file_path" for ingest action'};if(!r||typeof r!="string")return{success:!1,error:'Missing required field "filename" for ingest action'};if(!n||typeof n!="string")return{success:!1,error:'Missing required field "mime_type" for ingest action'};let o=await import("node:path"),i=o.resolve(s);if(i!==o.normalize(s)&&s.includes(".."))return{success:!1,error:"Invalid file path: path traversal not allowed"};let a=i.toLowerCase();if(a.startsWith("/etc/")||a.startsWith("/proc/")||a.startsWith("/sys/")||a.startsWith("c:\\windows\\")||a.startsWith("/root/"))return{success:!1,error:"Access to system directories is not allowed"};try{let l=await this.processor.ingest(t.userId,s,r,n);return{success:!0,data:l,display:`Document "${r}" ingested successfully (${l.chunkCount} chunks). ID: ${l.documentId.slice(0,8)}...`}}catch(l){return{success:!1,error:`Failed to ingest document: ${l instanceof Error?l.message:String(l)}`}}}async search(e,t){let s=e.query,r=e.limit||5;if(!s||typeof s!="string")return{success:!1,error:'Missing required field "query" for search action'};if(!this.embeddingService)return{success:!1,error:"Embedding service not available for document search"};let o=(await this.embeddingService.semanticSearch(t.userId,s,r)).filter(a=>a.category==="document");if(o.length===0)return{success:!0,data:[],display:`No document matches found for "${s}".`};let i=o.map((a,l)=>`${l+1}. (score: ${a.score.toFixed(3)}) ${a.value.slice(0,200)}${a.value.length>200?"...":""}`).join(`
434
436
 
435
437
  `);return{success:!0,data:o,display:`Found ${o.length} relevant chunk(s):
436
438
 
@@ -442,10 +444,10 @@ ${i}`}}summarize(e){let t=e.document_id;if(!t||typeof t!="string")return{success
442
444
 
443
445
  ${a}`}}list(e,t){let s=e.limit||50,n=this.docRepo.listByUser(t.userId).slice(0,s);if(n.length===0)return{success:!0,data:[],display:"No documents found."};let o=n.map(i=>`- **${i.filename}** (${i.id.slice(0,8)}...) \u2014 ${i.mimeType}, ${i.chunkCount} chunks, ${i.sizeBytes} bytes`).join(`
444
446
  `);return{success:!0,data:n,display:`${n.length} document(s):
445
- ${o}`}}deleteDoc(e){let t=e.document_id;if(!t||typeof t!="string")return{success:!1,error:'Missing required field "document_id" for delete action'};let s=this.docRepo.getDocument(t);return s?(this.docRepo.deleteDocument(t),{success:!0,data:{documentId:t},display:`Document "${s.filename}" deleted.`}):{success:!1,error:`Document "${t}" not found`}}}});var as={};G(as,{ActivityTracker:()=>ge,BackgroundTaskSkill:()=>Ge,BrowserSkill:()=>qe,CalculatorSkill:()=>Le,CalendarProvider:()=>J,CalendarSkill:()=>ye,ClipboardSkill:()=>Xe,CodeExecutionSkill:()=>Rt,CodeExecutor:()=>Te,CrossPlatformSkill:()=>Ve,DelegateSkill:()=>Fe,DocumentSkill:()=>Ze,EmailSkill:()=>je,FileSkill:()=>We,HttpSkill:()=>Be,MCPClient:()=>we,MCPManager:()=>At,MCPSkillAdapter:()=>Ee,MemorySkill:()=>Pe,NoteSkill:()=>Oe,PluginLoader:()=>rs,ProfileSkill:()=>Ke,ReminderSkill:()=>De,ScheduledTaskSkill:()=>Ye,ScreenshotSkill:()=>ze,ShellSkill:()=>Ue,Skill:()=>b,SkillRegistry:()=>Ae,SkillSandbox:()=>Re,SystemInfoSkill:()=>Me,WeatherSkill:()=>Ce,WebSearchSkill:()=>Ne,createCalendarProvider:()=>It});var Lt=f(()=>{"use strict";D();mn();pn();zs();hn();fn();gn();yn();wn();En();Tn();Sn();kn();vn();xn();In();An();Rn();Mn();Dn();On();Bn();Wn();Hn();Xn();qn();Vn();Gn()});var Mt,tr=f(()=>{"use strict";Mt=class{static{d(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)}}});import Yn from"node:fs";import Jn from"node:path";var Fi,ji,Bi,Wi,Nt,sr=f(()=>{"use strict";Hs();Fi=15*60*1e3,ji=2,Bi=.85,Wi=1e5,Nt=class{static{d(this,"MessagePipeline")}promptBuilder;llm;conversationManager;users;logger;skillRegistry;skillSandbox;securityManager;memoryRepo;speechTranscriber;inboxPath;embeddingService;activeLearning;memoryRetriever;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.promptBuilder=new bt}async process(e,t){let s=Date.now();this.logger.info({platform:e.platform,userId:e.userId,chatId:e.chatId},"Processing message");try{let r=this.users.findOrCreate(e.platform,e.userId,e.userName,e.displayName),n="getMasterUserId"in this.users?this.users.getMasterUserId(r.id):r.id,o=this.conversationManager.getOrCreateConversation(e.platform,e.chatId,r.id),i=this.conversationManager.getHistory(o.id,50);this.conversationManager.addMessage(o.id,"user",e.text);let a;if(this.memoryRetriever&&e.text)try{a=await this.memoryRetriever.retrieve(n,e.text,15)}catch(O){this.logger.debug({err:O},"Hybrid memory retrieval failed")}if(!a&&this.memoryRepo)try{if(this.embeddingService&&e.text&&this.llm.supportsEmbeddings()){let O=await this.embeddingService.semanticSearch(n,e.text,10),X=this.memoryRepo.getRecentForPrompt(n,5),B=new Set;a=[];for(let $ of O)B.has($.key)||(B.add($.key),a.push($));for(let $ of X)B.has($.key)||(B.add($.key),a.push($))}else a=this.memoryRepo.getRecentForPrompt(n,20)}catch(O){this.logger.debug({err:O},"Memory loading failed")}let l;try{"getProfile"in this.users&&(l=this.users.getProfile(r.id),l&&!l.displayName&&(l.displayName=r.displayName??r.username))}catch(O){this.logger.debug({err:O},"Profile loading failed")}let u=l?.timezone||Intl.DateTimeFormat().resolvedOptions().timeZone,p=this.skillRegistry?this.skillRegistry.getAll().map(O=>O.metadata):void 0,m=p?this.promptBuilder.buildTools(p):void 0,h=this.promptBuilder.buildSystemPrompt({memories:a,skills:p,userProfile:l}),w=this.buildActiveAgentStatus();w&&(h+=`
447
+ ${o}`}}deleteDoc(e){let t=e.document_id;if(!t||typeof t!="string")return{success:!1,error:'Missing required field "document_id" for delete action'};let s=this.docRepo.getDocument(t);return s?(this.docRepo.deleteDocument(t),{success:!0,data:{documentId:t},display:`Document "${s.filename}" deleted.`}):{success:!1,error:`Document "${t}" not found`}}}});var as={};G(as,{ActivityTracker:()=>ge,BackgroundTaskSkill:()=>Ge,BrowserSkill:()=>qe,CalculatorSkill:()=>Le,CalendarProvider:()=>J,CalendarSkill:()=>ye,ClipboardSkill:()=>Xe,CodeExecutionSkill:()=>Rt,CodeExecutor:()=>Te,CrossPlatformSkill:()=>Ve,DelegateSkill:()=>Fe,DocumentSkill:()=>Ze,EmailSkill:()=>je,FileSkill:()=>We,HttpSkill:()=>Be,MCPClient:()=>we,MCPManager:()=>At,MCPSkillAdapter:()=>Ee,MemorySkill:()=>Pe,NoteSkill:()=>Oe,PluginLoader:()=>rs,ProfileSkill:()=>Ke,ReminderSkill:()=>De,ScheduledTaskSkill:()=>Ye,ScreenshotSkill:()=>ze,ShellSkill:()=>Ue,Skill:()=>_,SkillRegistry:()=>Ae,SkillSandbox:()=>Re,SystemInfoSkill:()=>Me,WeatherSkill:()=>Ce,WebSearchSkill:()=>Ne,createCalendarProvider:()=>It});var Lt=f(()=>{"use strict";D();mn();pn();zs();hn();fn();gn();yn();wn();En();Tn();Sn();kn();vn();xn();In();An();Rn();Mn();Dn();On();Bn();Wn();Hn();Xn();qn();Vn();Gn()});var Mt,tr=f(()=>{"use strict";Mt=class{static{d(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)}}});import Yn from"node:fs";import Jn from"node:path";var Fi,ji,Bi,Wi,Nt,sr=f(()=>{"use strict";Hs();Fi=15*60*1e3,ji=2,Bi=.85,Wi=1e5,Nt=class{static{d(this,"MessagePipeline")}promptBuilder;llm;conversationManager;users;logger;skillRegistry;skillSandbox;securityManager;memoryRepo;speechTranscriber;inboxPath;embeddingService;activeLearning;memoryRetriever;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.promptBuilder=new bt}async process(e,t){let s=Date.now();this.logger.info({platform:e.platform,userId:e.userId,chatId:e.chatId},"Processing message");try{let r=this.users.findOrCreate(e.platform,e.userId,e.userName,e.displayName),n="getMasterUserId"in this.users?this.users.getMasterUserId(r.id):r.id,o=this.conversationManager.getOrCreateConversation(e.platform,e.chatId,r.id),i=this.conversationManager.getHistory(o.id,200);this.conversationManager.addMessage(o.id,"user",e.text);let a;if(this.memoryRetriever&&e.text)try{a=await this.memoryRetriever.retrieve(n,e.text,15)}catch(C){this.logger.debug({err:C},"Hybrid memory retrieval failed")}if(!a&&this.memoryRepo)try{if(this.embeddingService&&e.text&&this.llm.supportsEmbeddings()){let C=await this.embeddingService.semanticSearch(n,e.text,10),K=this.memoryRepo.getRecentForPrompt(n,5),$=new Set;a=[];for(let O of C)$.has(O.key)||($.add(O.key),a.push(O));for(let O of K)$.has(O.key)||($.add(O.key),a.push(O))}else a=this.memoryRepo.getRecentForPrompt(n,20)}catch(C){this.logger.debug({err:C},"Memory loading failed")}let l;try{"getProfile"in this.users&&(l=this.users.getProfile(r.id),l&&!l.displayName&&(l.displayName=r.displayName??r.username))}catch(C){this.logger.debug({err:C},"Profile loading failed")}let u=l?.timezone||Intl.DateTimeFormat().resolvedOptions().timeZone,p=this.skillRegistry?this.skillRegistry.getAll().map(C=>C.metadata):void 0,m=p?this.promptBuilder.buildTools(p):void 0,h=this.promptBuilder.buildSystemPrompt({memories:a,skills:p,userProfile:l}),w=this.buildActiveAgentStatus();w&&(h+=`
446
448
 
447
- `+w);let E=this.promptBuilder.buildMessages(i),T=await this.buildUserContent(e,t);E.push({role:"user",content:T});let k=this.trimToContextWindow(h,E),_,v=0,M=Date.now(),x="",A=0;for(t?.("Thinking...");_=await this.llm.complete({messages:k,system:h,tools:m&&m.length>0?m:void 0}),!(!_.toolCalls||_.toolCalls.length===0);){let O=Date.now()-M;if(O>=Fi){let z=Math.round(O/6e4);this.logger.warn({iteration:v,elapsedMin:z,pendingToolCalls:_.toolCalls.length},"Tool loop timeout reached"),_=await this.abortToolLoop(k,_,o.id,h,`Das Zeitlimit von ${z} Minuten f\xFCr Tool-Aufrufe wurde erreicht.`);break}v++,this.logger.info({iteration:v,toolCalls:_.toolCalls.length},"Processing tool calls");let X=[];_.content&&X.push({type:"text",text:_.content});for(let z of _.toolCalls)X.push({type:"tool_use",id:z.id,name:z.name,input:z.input});k.push({role:"assistant",content:X});let B=await this.executeToolCallsParallel(_.toolCalls,{userId:e.userId,chatId:e.chatId,chatType:e.chatType,platform:e.platform,conversationId:o.id,timezone:u},t);this.conversationManager.addMessage(o.id,"assistant",_.content??"",JSON.stringify(_.toolCalls)),this.conversationManager.addMessage(o.id,"user","",JSON.stringify(B));let $=this.buildErrorSignature(B);if($){if($===x?A++:(A=1,x=$),A>=ji){this.logger.warn({iteration:v,consecutiveErrors:A,errorSignature:$},"Tool loop aborted: same error repeated consecutively"),_=await this.abortToolLoop(k,_,o.id,h,`Der gleiche Tool-Fehler ist ${A}x hintereinander aufgetreten: "${x.slice(0,200)}". Erkl\xE4re dem User kurz was nicht funktioniert hat und schlage eine Alternative vor.`);break}}else A=0,x="";k.push({role:"user",content:B}),t?.("Thinking...")}let C=_.content;if(!C)for(let O=k.length-1;O>=0;O--){let X=k[O];if(X.role==="assistant"&&Array.isArray(X.content)){let B=X.content.find($=>$.type==="text");if(B&&"text"in B&&B.text){C=B.text;break}}}C||(C="(no response)"),this.conversationManager.addMessage(o.id,"assistant",C),this.activeLearning&&this.activeLearning.onMessageProcessed(n,e.text,C);let H=Date.now()-s;return this.logger.info({duration:H,tokens:_.usage,stopReason:_.stopReason,toolIterations:v},"Message processed"),C}catch(r){throw this.logger.error({err:r},"Failed to process message"),r}}async abortToolLoop(e,t,s,r,n){let o=[];t.content&&o.push({type:"text",text:t.content});for(let a of t.toolCalls)o.push({type:"tool_use",id:a.id,name:a.name,input:a.input});e.push({role:"assistant",content:o});let i=t.toolCalls.map(a=>({type:"tool_result",tool_use_id:a.id,content:`Error: tool loop aborted \u2014 ${n}`,is_error:!0}));return e.push({role:"user",content:i}),this.conversationManager.addMessage(s,"assistant",t.content??"",JSON.stringify(t.toolCalls)),this.conversationManager.addMessage(s,"user","",JSON.stringify(i)),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})}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("|"):""}async executeToolCallsParallel(e,t,s){if(e.length===1){let n=e[0],o=this.getToolLabel(n.name,n.input);s?.(o);let i=await this.executeToolCall(n,t,s);return[{type:"tool_result",tool_use_id:n.id,content:i.content,is_error:i.isError}]}s?.(`Running ${e.length} tools in parallel...`);let r=await Promise.allSettled(e.map(n=>this.executeToolCall(n,t,s)));return e.map((n,o)=>{let i=r[o];return i.status==="fulfilled"?{type:"tool_result",tool_use_id:n.id,content:i.value.content,is_error:i.value.isError}:{type:"tool_result",tool_use_id:n.id,content:`Tool execution failed: ${i.reason}`,is_error:!0}})}async executeToolCall(e,t,s){let r=this.skillRegistry?.get(e.name);if(!r)return this.logger.warn({tool:e.name},"Unknown skill requested"),{content:`Error: Unknown tool "${e.name}"`,isError:!0};if(this.securityManager){let n=this.securityManager.evaluate({userId:t.userId,action:e.name,riskLevel:r.metadata.riskLevel,platform:t.platform,chatId:t.chatId,chatType:t.chatType});if(!n.allowed)return this.logger.warn({tool:e.name,reason:n.reason,rule:n.matchedRule?.id},"Skill execution denied by security rules"),{content:`Access denied: ${n.reason}`,isError:!0}}if(this.skillSandbox){let n,o;if(e.name==="delegate"){let{ActivityTracker:a}=await Promise.resolve().then(()=>(Lt(),as));n=new a(s),o=`agent-${++this.agentIdCounter}`,this.activeAgents.set(o,{chatId:t.chatId,task:String(e.input.task??"").slice(0,200),tracker:n,startedAt:Date.now()})}let i=e.name==="delegate"?{...t,tracker:n,onProgress:s}:t;try{let a=await this.skillSandbox.execute(r,e.input,i,void 0,n);return{content:a.display??(a.success?JSON.stringify(a.data):a.error??"Unknown error"),isError:!a.success}}finally{o&&this.activeAgents.delete(o)}}try{let n=await r.execute(e.input,t);return{content:n.display??(n.success?JSON.stringify(n.data):n.error??"Unknown error"),isError:!n.success}}catch(n){return{content:`Skill execution failed: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}getToolLabel(e,t){switch(e){case"shell":return`Running: ${String(t.command??"").slice(0,60)}`;case"web_search":return`Searching: ${String(t.query??"")}`;case"email":return`Email: ${String(t.action??"")}`;case"memory":return`Memory: ${String(t.action??"")}`;case"reminder":return`Reminder: ${String(t.action??"")}`;case"calculator":return"Calculating...";case"system_info":return"Getting system info...";case"delegate":return"Delegating sub-task...";case"http":return`Fetching: ${String(t.url??"").slice(0,60)}`;case"file":return`File: ${String(t.action??"")} ${String(t.path??"").slice(0,50)}`;case"clipboard":return`Clipboard: ${String(t.action??"")}`;case"screenshot":return"Taking screenshot...";case"browser":return`Browser: ${String(t.action??"")} ${String(t.url??"").slice(0,50)}`;case"weather":return`Weather: ${String(t.location??"")}`;case"note":return`Note: ${String(t.action??"")}`;case"profile":return`Profile: ${String(t.action??"")}`;case"calendar":return`Calendar: ${String(t.action??"")}`;case"background_task":return`Background task: ${String(t.action??"")}`;case"scheduled_task":return`Scheduled task: ${String(t.action??"")}`;case"cross_platform":return`Cross-platform: ${String(t.action??"")}`;case"code_sandbox":return"Running code...";case"document":return`Document: ${String(t.action??"")}`;default:return`Using ${e}...`}}buildActiveAgentStatus(){if(this.activeAgents.size===0)return;let e=["## Currently running sub-agents"];for(let[t,s]of this.activeAgents){let r=s.tracker.getSnapshot(),n=Math.round(r.totalElapsedMs/1e3);e.push(`- **${t}**: "${s.task}"`,` Status: ${s.tracker.formatStatus()}`,` Running for ${n}s | Last activity ${Math.round(r.idleMs/1e3)}s ago`)}return e.push(""),e.push("If the user asks what you or the agent is doing, describe the above status in natural language."),e.join(`
448
- `)}trimToContextWindow(e,t){let s=this.llm.getContextWindow(),r=Math.floor(s.maxInputTokens*Bi),n=ie(e),o=t[t.length-1],i=ts(o),l=n+i+200+500,u=r-l;if(u<=0)return this.logger.warn({maxInputTokens:r,systemTokens:n,latestTokens:i},"Context window very tight, sending only latest message"),[o];let p=t.slice(0,-1),m=this.groupToolPairs(p),h=[];for(let T=m.length-1;T>=0;T--){let k=m[T].reduce((_,v)=>_+ts(v),0);if(k>u)break;u-=k,h.unshift(m[T])}let w=h.flat(),E=p.length-w.length;if(E>0){this.logger.info({trimmedCount:E,totalMessages:t.length,maxInputTokens:r},"Trimmed conversation history to fit context window");let T=p.slice(0,p.length-w.length),k=this.summarizeTrimmedMessages(T);w.unshift({role:"user",content:`[Earlier conversation summary \u2014 ${E} messages were trimmed to fit the context window:
449
+ `+w);let E=this.promptBuilder.buildMessages(i),T=this.collapseRepeatedToolErrors(E),k=await this.buildUserContent(e,t);T.push({role:"user",content:k});let v=this.trimToContextWindow(h,T),b,A=0,x=Date.now(),L="",P=0;for(t?.("Thinking...");b=await this.llm.complete({messages:v,system:h,tools:m&&m.length>0?m:void 0}),!(!b.toolCalls||b.toolCalls.length===0);){let C=Date.now()-x;if(C>=Fi){let H=Math.round(C/6e4);this.logger.warn({iteration:A,elapsedMin:H,pendingToolCalls:b.toolCalls.length},"Tool loop timeout reached"),b=await this.abortToolLoop(v,b,o.id,h,`Das Zeitlimit von ${H} Minuten f\xFCr Tool-Aufrufe wurde erreicht.`);break}A++,this.logger.info({iteration:A,toolCalls:b.toolCalls.length},"Processing tool calls");let K=[];b.content&&K.push({type:"text",text:b.content});for(let H of b.toolCalls)K.push({type:"tool_use",id:H.id,name:H.name,input:H.input});v.push({role:"assistant",content:K});let $=await this.executeToolCallsParallel(b.toolCalls,{userId:e.userId,chatId:e.chatId,chatType:e.chatType,platform:e.platform,conversationId:o.id,timezone:u},t);this.conversationManager.addMessage(o.id,"assistant",b.content??"",JSON.stringify(b.toolCalls)),this.conversationManager.addMessage(o.id,"user","",JSON.stringify($));let O=this.buildErrorSignature($);if(O){if(O===L?P++:(P=1,L=O),P>=ji){this.logger.warn({iteration:A,consecutiveErrors:P,errorSignature:O},"Tool loop aborted: same error repeated consecutively"),b=await this.abortToolLoop(v,b,o.id,h,`Der gleiche Tool-Fehler ist ${P}x hintereinander aufgetreten: "${L.slice(0,200)}". Erkl\xE4re dem User kurz was nicht funktioniert hat und schlage eine Alternative vor.`);break}}else P=0,L="";v.push({role:"user",content:$}),t?.("Thinking...")}let F=b.content;if(!F)for(let C=v.length-1;C>=0;C--){let K=v[C];if(K.role==="assistant"&&Array.isArray(K.content)){let $=K.content.find(O=>O.type==="text");if($&&"text"in $&&$.text){F=$.text;break}}}F||(F="(no response)"),this.conversationManager.addMessage(o.id,"assistant",F),this.activeLearning&&this.activeLearning.onMessageProcessed(n,e.text,F);let ee=Date.now()-s;return this.logger.info({duration:ee,tokens:b.usage,stopReason:b.stopReason,toolIterations:A},"Message processed"),F}catch(r){throw this.logger.error({err:r},"Failed to process message"),r}}async abortToolLoop(e,t,s,r,n){let o=[];t.content&&o.push({type:"text",text:t.content});for(let a of t.toolCalls)o.push({type:"tool_use",id:a.id,name:a.name,input:a.input});e.push({role:"assistant",content:o});let i=t.toolCalls.map(a=>({type:"tool_result",tool_use_id:a.id,content:`Error: tool loop aborted \u2014 ${n}`,is_error:!0}));return e.push({role:"user",content:i}),this.conversationManager.addMessage(s,"assistant",t.content??"",JSON.stringify(t.toolCalls)),this.conversationManager.addMessage(s,"user","",JSON.stringify(i)),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})}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 l=e[a],u=e[a+1];if(l.role==="assistant"&&u?.role==="user"&&this.toolPairSignature(l,u)===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){if(e.length===1){let n=e[0],o=this.getToolLabel(n.name,n.input);s?.(o);let i=await this.executeToolCall(n,t,s);return[{type:"tool_result",tool_use_id:n.id,content:i.content,is_error:i.isError}]}s?.(`Running ${e.length} tools in parallel...`);let r=await Promise.allSettled(e.map(n=>this.executeToolCall(n,t,s)));return e.map((n,o)=>{let i=r[o];return i.status==="fulfilled"?{type:"tool_result",tool_use_id:n.id,content:i.value.content,is_error:i.value.isError}:{type:"tool_result",tool_use_id:n.id,content:`Tool execution failed: ${i.reason}`,is_error:!0}})}async executeToolCall(e,t,s){let r=this.skillRegistry?.get(e.name);if(!r)return this.logger.warn({tool:e.name},"Unknown skill requested"),{content:`Error: Unknown tool "${e.name}"`,isError:!0};if(this.securityManager){let n=this.securityManager.evaluate({userId:t.userId,action:e.name,riskLevel:r.metadata.riskLevel,platform:t.platform,chatId:t.chatId,chatType:t.chatType});if(!n.allowed)return this.logger.warn({tool:e.name,reason:n.reason,rule:n.matchedRule?.id},"Skill execution denied by security rules"),{content:`Access denied: ${n.reason}`,isError:!0}}if(this.skillSandbox){let n,o;if(e.name==="delegate"){let{ActivityTracker:a}=await Promise.resolve().then(()=>(Lt(),as));n=new a(s),o=`agent-${++this.agentIdCounter}`,this.activeAgents.set(o,{chatId:t.chatId,task:String(e.input.task??"").slice(0,200),tracker:n,startedAt:Date.now()})}let i=e.name==="delegate"?{...t,tracker:n,onProgress:s}:t;try{let a=await this.skillSandbox.execute(r,e.input,i,void 0,n);return{content:a.display??(a.success?JSON.stringify(a.data):a.error??"Unknown error"),isError:!a.success}}finally{o&&this.activeAgents.delete(o)}}try{let n=await r.execute(e.input,t);return{content:n.display??(n.success?JSON.stringify(n.data):n.error??"Unknown error"),isError:!n.success}}catch(n){return{content:`Skill execution failed: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}getToolLabel(e,t){switch(e){case"shell":return`Running: ${String(t.command??"").slice(0,60)}`;case"web_search":return`Searching: ${String(t.query??"")}`;case"email":return`Email: ${String(t.action??"")}`;case"memory":return`Memory: ${String(t.action??"")}`;case"reminder":return`Reminder: ${String(t.action??"")}`;case"calculator":return"Calculating...";case"system_info":return"Getting system info...";case"delegate":return"Delegating sub-task...";case"http":return`Fetching: ${String(t.url??"").slice(0,60)}`;case"file":return`File: ${String(t.action??"")} ${String(t.path??"").slice(0,50)}`;case"clipboard":return`Clipboard: ${String(t.action??"")}`;case"screenshot":return"Taking screenshot...";case"browser":return`Browser: ${String(t.action??"")} ${String(t.url??"").slice(0,50)}`;case"weather":return`Weather: ${String(t.location??"")}`;case"note":return`Note: ${String(t.action??"")}`;case"profile":return`Profile: ${String(t.action??"")}`;case"calendar":return`Calendar: ${String(t.action??"")}`;case"background_task":return`Background task: ${String(t.action??"")}`;case"scheduled_task":return`Scheduled task: ${String(t.action??"")}`;case"cross_platform":return`Cross-platform: ${String(t.action??"")}`;case"code_sandbox":return"Running code...";case"document":return`Document: ${String(t.action??"")}`;default:return`Using ${e}...`}}buildActiveAgentStatus(){if(this.activeAgents.size===0)return;let e=["## Currently running sub-agents"];for(let[t,s]of this.activeAgents){let r=s.tracker.getSnapshot(),n=Math.round(r.totalElapsedMs/1e3);e.push(`- **${t}**: "${s.task}"`,` Status: ${s.tracker.formatStatus()}`,` Running for ${n}s | Last activity ${Math.round(r.idleMs/1e3)}s ago`)}return e.push(""),e.push("If the user asks what you or the agent is doing, describe the above status in natural language."),e.join(`
450
+ `)}trimToContextWindow(e,t){let s=this.llm.getContextWindow(),r=Math.floor(s.maxInputTokens*Bi),n=ie(e),o=t[t.length-1],i=ts(o),l=n+i+200+500,u=r-l;if(u<=0)return this.logger.warn({maxInputTokens:r,systemTokens:n,latestTokens:i},"Context window very tight, sending only latest message"),[o];let p=t.slice(0,-1),m=this.groupToolPairs(p),h=[];for(let T=m.length-1;T>=0;T--){let k=m[T].reduce((v,b)=>v+ts(b),0);if(k>u)break;u-=k,h.unshift(m[T])}let w=h.flat(),E=p.length-w.length;if(E>0){this.logger.info({trimmedCount:E,totalMessages:t.length,maxInputTokens:r},"Trimmed conversation history to fit context window");let T=p.slice(0,p.length-w.length),k=this.summarizeTrimmedMessages(T);w.unshift({role:"user",content:`[Earlier conversation summary \u2014 ${E} messages were trimmed to fit the context window:
449
451
  ${k}
450
452
 
451
453
  The conversation continues below with the most recent messages.]`})}return w.push(o),w}summarizeTrimmedMessages(e){let t=[];for(let r of e){let n=this.extractMessageText(r);if(!n)continue;let o=n.length>150?n.slice(0,150)+"...":n,i=r.role==="user"?"User":"Assistant";if(t.push(`- ${i}: ${o}`),r.role==="assistant"&&Array.isArray(r.content)){for(let a of r.content)if(a.type==="tool_use"){let l=JSON.stringify(a.input).slice(0,80);t.push(` \u2192 Tool: ${a.name}(${l})`)}}}let s=40;if(t.length>s){let r=t.slice(0,s);return r.push(` ... and ${t.length-s} more interactions`),r.join(`
@@ -455,7 +457,7 @@ The conversation continues below with the most recent messages.]`})}return w.pus
455
457
  `;return r.push({type:"text",text:`${a}[Voice transcript]: ${i}`}),this.logger.info({transcriptLength:i.length},"Voice message transcribed"),r.length===1&&r[0].type==="text"?r[0].text:r}catch(i){this.logger.error({err:i},"Voice transcription failed"),r.push({type:"text",text:"[Voice message could not be transcribed]"})}}else r.push({type:"text",text:"[Voice message received but speech-to-text is not configured. Add speech config to enable transcription.]"});else if((o.type==="document"||o.type==="video"||o.type==="other")&&o.data){let i=this.saveToInbox(o);if(i){let a=this.isTextMimeType(o.mimeType),l=`[File received: "${o.fileName??"unknown"}" (${this.formatBytes(o.data.length)}, ${o.mimeType??"unknown type"})]
456
458
  [Saved to: ${i}]`;if(a&&o.data.length<=Wi){let u=o.data.toString("utf-8");l+=`
457
459
  [File content]:
458
- ${u}`}r.push({type:"text",text:l}),this.logger.info({fileName:o.fileName,savedPath:i,size:o.data.length},"File saved to inbox")}}let n=["[Photo]","[Voice message]","[Video]","[Video note]","[Document]","[File]"];return e.text&&!n.includes(e.text)?r.push({type:"text",text:e.text}):r.some(o=>o.type==="image")&&!r.some(o=>o.type==="text")?r.push({type:"text",text:"What do you see in this image?"}):r.length===0&&r.push({type:"text",text:e.text||"(empty message)"}),r}saveToInbox(e){if(!e.data)return;let t=this.inboxPath??Jn.resolve("./data/inbox");try{Yn.mkdirSync(t,{recursive:!0})}catch{this.logger.error({inboxDir:t},"Cannot create inbox directory");return}let s=new Date().toISOString().replace(/[:.]/g,"-"),n=(e.fileName??`file_${s}`).replace(/[<>:"/\\|?*]/g,"_"),o=`${s}_${n}`,i=Jn.join(t,o);try{return Yn.writeFileSync(i,e.data),i}catch(a){this.logger.error({err:a,filePath:i},"Failed to save file to inbox");return}}isTextMimeType(e){return e?["text/","application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/sql","application/csv","application/x-csv"].some(s=>e.startsWith(s)):!1}formatBytes(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}}});var Dt,rr=f(()=>{"use strict";Dt=class{static{d(this,"ReminderScheduler")}reminderRepo;sendMessage;logger;intervalId;checkIntervalMs;constructor(e,t,s,r=15e3){this.reminderRepo=e,this.sendMessage=t,this.logger=s,this.checkIntervalMs=r}start(){this.logger.info("Reminder scheduler started"),this.intervalId=setInterval(()=>this.checkDueReminders(),this.checkIntervalMs),this.checkDueReminders()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0),this.logger.info("Reminder scheduler stopped")}async checkDueReminders(){try{let e=this.reminderRepo.getDue();for(let t of e)try{await this.sendMessage(t.platform,t.chatId,`\u23F0 Reminder: ${t.message}`),this.reminderRepo.markFired(t.id),this.logger.info({reminderId:t.id},"Reminder fired")}catch(s){this.logger.error({err:s,reminderId:t.id},"Failed to send reminder")}}catch(e){this.logger.error({err:e},"Error checking due reminders")}}}});var Ot,nr=f(()=>{"use strict";Ot=class{static{d(this,"SpeechTranscriber")}logger;apiKey;baseUrl;constructor(e,t){this.logger=t,this.apiKey=e.apiKey,e.provider==="groq"?this.baseUrl=e.baseUrl??"https://api.groq.com/openai/v1":this.baseUrl=e.baseUrl??"https://api.openai.com/v1"}async transcribe(e,t){let s=this.mimeToExtension(t),r=new FormData;r.append("file",new Blob([e],{type:t}),`audio.${s}`),r.append("model","whisper-1");try{let n=await fetch(`${this.baseUrl}/audio/transcriptions`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:r});if(!n.ok){let i=await n.text();throw new Error(`Whisper API ${n.status}: ${i}`)}let o=await n.json();return this.logger.info({textLength:o.text.length},"Voice transcribed"),o.text}catch(n){throw this.logger.error({err:n},"Voice transcription failed"),n}}mimeToExtension(e){return{"audio/ogg":"ogg","audio/mpeg":"mp3","audio/mp4":"m4a","audio/wav":"wav","audio/webm":"webm","audio/x-m4a":"m4a"}[e]??"ogg"}}});var Ct,or=f(()=>{"use strict";Ct=class{static{d(this,"ResponseFormatter")}format(e,t){switch(t){case"telegram":return{text:this.toTelegramHTML(e),parseMode:"html"};case"discord":return{text:e,parseMode:"markdown"};case"matrix":return{text:this.toMatrixHTML(e),parseMode:"html"};case"whatsapp":return{text:this.toWhatsApp(e),parseMode:"text"};case"signal":return{text:this.stripFormatting(e),parseMode:"text"};default:return{text:e,parseMode:"text"}}}toTelegramHTML(e){let t=e;return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(s,r,n)=>`<pre>${this.escapeHTML(n.trimEnd())}</pre>`),t=t.replace(/`([^`]+)`/g,(s,r)=>`<code>${this.escapeHTML(r)}</code>`),t=t.replace(/\*\*(.+?)\*\*/g,"<b>$1</b>"),t=t.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"<i>$1</i>"),t=t.replace(/~~(.+?)~~/g,"<s>$1</s>"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2">$1</a>'),t}toMatrixHTML(e){return this.toTelegramHTML(e)}toWhatsApp(e){let t=e;return t=t.replace(/\*\*(.+?)\*\*/g,"*$1*"),t=t.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"_$1_"),t=t.replace(/~~(.+?)~~/g,"~$1~"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1 ($2)"),t}stripFormatting(e){let t=e;return t=t.replace(/```\w*\n?/g,""),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/\*\*(.+?)\*\*/g,"$1"),t=t.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"$1"),t=t.replace(/~~(.+?)~~/g,"$1"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1 ($2)"),t}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}}});var Ut,ir=f(()=>{"use strict";Ut=class{static{d(this,"EmbeddingService")}llm;embeddingRepo;logger;constructor(e,t,s){this.llm=e,this.embeddingRepo=t,this.logger=s}async embedAndStore(e,t,s,r){if(this.llm.supportsEmbeddings())try{let n=await this.llm.embed(t);if(!n)return;this.embeddingRepo.store({userId:e,sourceType:s,sourceId:r,content:t,embedding:n.embedding,model:n.model,dimensions:n.dimensions}),this.logger.debug({userId:e,sourceType:s,sourceId:r},"Embedding stored")}catch(n){this.logger.error({err:n,userId:e,sourceType:s,sourceId:r},"Failed to embed content")}}async semanticSearch(e,t,s=10){if(!this.llm.supportsEmbeddings())return[];try{let r=await this.llm.embed(t);if(!r)return[];let n=this.embeddingRepo.findByUser(e);if(n.length===0)return[];let o=n.map(a=>{let l=this.cosineSimilarity(r.embedding,a.embedding);return{...a,score:l}});return o.sort((a,l)=>l.score-a.score),o.slice(0,s).map(a=>({key:a.sourceId,value:a.content,category:a.sourceType,score:a.score}))}catch(r){return this.logger.error({err:r},"Semantic search failed"),[]}}cosineSimilarity(e,t){if(e.length!==t.length)return 0;let s=0,r=0,n=0;for(let i=0;i<e.length;i++)s+=e[i]*t[i],r+=e[i]*e[i],n+=t[i]*t[i];let o=Math.sqrt(r)*Math.sqrt(n);return o===0?0:s/o}}});var Pt,ar=f(()=>{"use strict";Pt=class{static{d(this,"DocumentProcessor")}docRepo;embeddingService;logger;constructor(e,t,s){this.docRepo=e,this.embeddingService=t,this.logger=s}async ingest(e,t,s,r){let n=await this.extractText(t,r),i=(await import("node:fs")).statSync(t),a=this.docRepo.createDocument(e,s,r,i.size),l=this.chunkText(n,500,50);for(let u=0;u<l.length;u++){let p;try{await this.embeddingService.embedAndStore(e,l[u],"document",`${a.id}:${u}`),p=`${a.id}:${u}`}catch(m){this.logger.warn({documentId:a.id,chunkIndex:u,err:m},"Embedding failed for chunk, continuing")}this.docRepo.addChunk(a.id,u,l[u],p)}return this.docRepo.updateChunkCount(a.id,l.length),this.logger.info({documentId:a.id,filename:s,chunkCount:l.length},"Document ingested"),{documentId:a.id,chunkCount:l.length}}async extractText(e,t){let s=await import("node:fs");if(t==="application/pdf")try{let r=(await import("pdf-parse")).default,n=s.readFileSync(e);return(await r(n)).text}catch(r){throw this.logger.error({err:r},"PDF parsing failed"),new Error("Failed to parse PDF")}if(t==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||t==="application/msword")try{return(await(await import("mammoth")).extractRawText({path:e})).value}catch(r){throw this.logger.error({err:r},"DOCX parsing failed"),new Error("Failed to parse DOCX")}return s.readFileSync(e,"utf-8")}chunkText(e,t,s){let n=Math.round(t*3.5),o=Math.round(s*3.5),i=[],a=0;for(;a<e.length;){let l=a+n;if(l>=e.length){i.push(e.slice(a).trim());break}let u=Math.max(l-200,a),p=e.slice(u,l+200),m=p.lastIndexOf(`
460
+ ${u}`}r.push({type:"text",text:l}),this.logger.info({fileName:o.fileName,savedPath:i,size:o.data.length},"File saved to inbox")}}let n=["[Photo]","[Voice message]","[Video]","[Video note]","[Document]","[File]"];return e.text&&!n.includes(e.text)?r.push({type:"text",text:e.text}):r.some(o=>o.type==="image")&&!r.some(o=>o.type==="text")?r.push({type:"text",text:"What do you see in this image?"}):r.some(o=>o.type==="text"&&o.text.startsWith("[File received:"))?r.push({type:"text",text:"The user sent this file without any instructions. Ask them what they would like you to do with it."}):r.length===0&&r.push({type:"text",text:e.text||"(empty message)"}),r}saveToInbox(e){if(!e.data)return;let t=this.inboxPath??Jn.resolve("./data/inbox");try{Yn.mkdirSync(t,{recursive:!0})}catch{this.logger.error({inboxDir:t},"Cannot create inbox directory");return}let s=new Date().toISOString().replace(/[:.]/g,"-"),n=(e.fileName??`file_${s}`).replace(/[<>:"/\\|?*]/g,"_"),o=`${s}_${n}`,i=Jn.join(t,o);try{return Yn.writeFileSync(i,e.data),i}catch(a){this.logger.error({err:a,filePath:i},"Failed to save file to inbox");return}}isTextMimeType(e){return e?["text/","application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/sql","application/csv","application/x-csv"].some(s=>e.startsWith(s)):!1}formatBytes(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}}});var Dt,rr=f(()=>{"use strict";Dt=class{static{d(this,"ReminderScheduler")}reminderRepo;sendMessage;logger;intervalId;checkIntervalMs;constructor(e,t,s,r=15e3){this.reminderRepo=e,this.sendMessage=t,this.logger=s,this.checkIntervalMs=r}start(){this.logger.info("Reminder scheduler started"),this.intervalId=setInterval(()=>this.checkDueReminders(),this.checkIntervalMs),this.checkDueReminders()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0),this.logger.info("Reminder scheduler stopped")}async checkDueReminders(){try{let e=this.reminderRepo.getDue();for(let t of e)try{await this.sendMessage(t.platform,t.chatId,`\u23F0 Reminder: ${t.message}`),this.reminderRepo.markFired(t.id),this.logger.info({reminderId:t.id},"Reminder fired")}catch(s){this.logger.error({err:s,reminderId:t.id},"Failed to send reminder")}}catch(e){this.logger.error({err:e},"Error checking due reminders")}}}});var Ot,nr=f(()=>{"use strict";Ot=class{static{d(this,"SpeechTranscriber")}logger;apiKey;baseUrl;constructor(e,t){this.logger=t,this.apiKey=e.apiKey,e.provider==="groq"?this.baseUrl=e.baseUrl??"https://api.groq.com/openai/v1":this.baseUrl=e.baseUrl??"https://api.openai.com/v1"}async transcribe(e,t){let s=this.mimeToExtension(t),r=new FormData;r.append("file",new Blob([e],{type:t}),`audio.${s}`),r.append("model","whisper-1");try{let n=await fetch(`${this.baseUrl}/audio/transcriptions`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:r});if(!n.ok){let i=await n.text();throw new Error(`Whisper API ${n.status}: ${i}`)}let o=await n.json();return this.logger.info({textLength:o.text.length},"Voice transcribed"),o.text}catch(n){throw this.logger.error({err:n},"Voice transcription failed"),n}}mimeToExtension(e){return{"audio/ogg":"ogg","audio/mpeg":"mp3","audio/mp4":"m4a","audio/wav":"wav","audio/webm":"webm","audio/x-m4a":"m4a"}[e]??"ogg"}}});var Ct,or=f(()=>{"use strict";Ct=class{static{d(this,"ResponseFormatter")}format(e,t){switch(t){case"telegram":return{text:this.toTelegramHTML(e),parseMode:"html"};case"discord":return{text:e,parseMode:"markdown"};case"matrix":return{text:this.toMatrixHTML(e),parseMode:"html"};case"whatsapp":return{text:this.toWhatsApp(e),parseMode:"text"};case"signal":return{text:this.stripFormatting(e),parseMode:"text"};default:return{text:e,parseMode:"text"}}}toTelegramHTML(e){let t=e;return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(s,r,n)=>`<pre>${this.escapeHTML(n.trimEnd())}</pre>`),t=t.replace(/`([^`]+)`/g,(s,r)=>`<code>${this.escapeHTML(r)}</code>`),t=t.replace(/\*\*(.+?)\*\*/g,"<b>$1</b>"),t=t.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"<i>$1</i>"),t=t.replace(/~~(.+?)~~/g,"<s>$1</s>"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2">$1</a>'),t}toMatrixHTML(e){return this.toTelegramHTML(e)}toWhatsApp(e){let t=e;return t=t.replace(/\*\*(.+?)\*\*/g,"*$1*"),t=t.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"_$1_"),t=t.replace(/~~(.+?)~~/g,"~$1~"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1 ($2)"),t}stripFormatting(e){let t=e;return t=t.replace(/```\w*\n?/g,""),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/\*\*(.+?)\*\*/g,"$1"),t=t.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"$1"),t=t.replace(/~~(.+?)~~/g,"$1"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,"$1 ($2)"),t}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}}});var Ut,ir=f(()=>{"use strict";Ut=class{static{d(this,"EmbeddingService")}llm;embeddingRepo;logger;constructor(e,t,s){this.llm=e,this.embeddingRepo=t,this.logger=s}async embedAndStore(e,t,s,r){if(this.llm.supportsEmbeddings())try{let n=await this.llm.embed(t);if(!n)return;this.embeddingRepo.store({userId:e,sourceType:s,sourceId:r,content:t,embedding:n.embedding,model:n.model,dimensions:n.dimensions}),this.logger.debug({userId:e,sourceType:s,sourceId:r},"Embedding stored")}catch(n){this.logger.error({err:n,userId:e,sourceType:s,sourceId:r},"Failed to embed content")}}async semanticSearch(e,t,s=10){if(!this.llm.supportsEmbeddings())return[];try{let r=await this.llm.embed(t);if(!r)return[];let n=this.embeddingRepo.findByUser(e);if(n.length===0)return[];let o=n.map(a=>{let l=this.cosineSimilarity(r.embedding,a.embedding);return{...a,score:l}});return o.sort((a,l)=>l.score-a.score),o.slice(0,s).map(a=>({key:a.sourceId,value:a.content,category:a.sourceType,score:a.score}))}catch(r){return this.logger.error({err:r},"Semantic search failed"),[]}}cosineSimilarity(e,t){if(e.length!==t.length)return 0;let s=0,r=0,n=0;for(let i=0;i<e.length;i++)s+=e[i]*t[i],r+=e[i]*e[i],n+=t[i]*t[i];let o=Math.sqrt(r)*Math.sqrt(n);return o===0?0:s/o}}});var Pt,ar=f(()=>{"use strict";Pt=class{static{d(this,"DocumentProcessor")}docRepo;embeddingService;logger;constructor(e,t,s){this.docRepo=e,this.embeddingService=t,this.logger=s}async ingest(e,t,s,r){let n=await this.extractText(t,r),i=(await import("node:fs")).statSync(t),a=this.docRepo.createDocument(e,s,r,i.size),l=this.chunkText(n,500,50);for(let u=0;u<l.length;u++){let p;try{await this.embeddingService.embedAndStore(e,l[u],"document",`${a.id}:${u}`),p=`${a.id}:${u}`}catch(m){this.logger.warn({documentId:a.id,chunkIndex:u,err:m},"Embedding failed for chunk, continuing")}this.docRepo.addChunk(a.id,u,l[u],p)}return this.docRepo.updateChunkCount(a.id,l.length),this.logger.info({documentId:a.id,filename:s,chunkCount:l.length},"Document ingested"),{documentId:a.id,chunkCount:l.length}}async extractText(e,t){let s=await import("node:fs");if(t==="application/pdf")try{let r=(await import("pdf-parse")).default,n=s.readFileSync(e);return(await r(n)).text}catch(r){throw this.logger.error({err:r},"PDF parsing failed"),new Error("Failed to parse PDF")}if(t==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||t==="application/msword")try{return(await(await import("mammoth")).extractRawText({path:e})).value}catch(r){throw this.logger.error({err:r},"DOCX parsing failed"),new Error("Failed to parse DOCX")}return s.readFileSync(e,"utf-8")}chunkText(e,t,s){let n=Math.round(t*3.5),o=Math.round(s*3.5),i=[],a=0;for(;a<e.length;){let l=a+n;if(l>=e.length){i.push(e.slice(a).trim());break}let u=Math.max(l-200,a),p=e.slice(u,l+200),m=p.lastIndexOf(`
459
461
 
460
462
  `);if(m>0)l=u+m;else{let w=p.lastIndexOf(". ");w>0&&(l=u+w+1)}let h=e.slice(a,l).trim();h&&i.push(h),a=l-o}return i.filter(l=>l.length>0)}}});var Ft,cr=f(()=>{"use strict";Ft=class{static{d(this,"BackgroundTaskRunner")}skillRegistry;skillSandbox;taskRepo;adapters;logger;pollTimer;running=0;maxConcurrent=3;pollIntervalMs=5e3;taskTimeoutMs=5*6e4;constructor(e,t,s,r,n){this.skillRegistry=e,this.skillSandbox=t,this.taskRepo=s,this.adapters=r,this.logger=n}start(){this.pollTimer=setInterval(()=>this.poll(),this.pollIntervalMs),this.logger.info("Background task runner started")}stop(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.logger.info("Background task runner stopped")}async poll(){if(!(this.running>=this.maxConcurrent))try{let e=this.maxConcurrent-this.running,t=this.taskRepo.getPending(e);for(let s of t)this.running++,this.runTask(s).finally(()=>{this.running--})}catch(e){this.logger.error({err:e},"Error polling for background tasks")}}async runTask(e){this.taskRepo.updateStatus(e.id,"running");try{let t=this.skillRegistry.get(e.skillName);if(!t){this.taskRepo.updateStatus(e.id,"failed",void 0,`Unknown skill: ${e.skillName}`);return}let s;try{s=JSON.parse(e.skillInput)}catch(l){this.logger.warn({taskId:e.id,err:l},"Malformed skill input JSON"),this.taskRepo.updateStatus(e.id,"failed",void 0,"Malformed skill input JSON");return}let r={userId:e.userId,chatId:e.chatId,platform:e.platform,conversationId:"",chatType:"dm"},n=new Promise((l,u)=>setTimeout(()=>u(new Error("Background task timed out")),this.taskTimeoutMs)),o=await Promise.race([this.skillSandbox.execute(t,s,r),n]),i=JSON.stringify(o.data??o.display??o.error);this.taskRepo.updateStatus(e.id,o.success?"completed":"failed",i,o.error);let a=this.adapters.get(e.platform);if(a){let l=o.success?`\u2705 Background task completed: ${e.description}
461
463
 
@@ -485,29 +487,29 @@ Extract memories from this conversation:
485
487
  User: {USER_MESSAGE}
486
488
  Assistant: {ASSISTANT_RESPONSE}
487
489
 
488
- Return ONLY a valid JSON array, no explanation:`,Bt=class{static{d(this,"MemoryExtractor")}llm;memoryRepo;logger;embeddingService;minConfidence;constructor(e,t,s,r,n=.4){this.llm=e,this.memoryRepo=t,this.logger=s,this.embeddingService=r,this.minConfidence=n}async extract(e,t,s){try{let r=qi.replace("{USER_MESSAGE}",t).replace("{ASSISTANT_RESPONSE}",s),n=await this.llm.complete({messages:[{role:"user",content:r}],temperature:.1,tier:"fast",maxTokens:1024}),o=this.parseResponse(n.content);if(o.length===0)return 0;let i=0;for(let a of o)if(!(a.confidence<this.minConfidence))try{let l=this.memoryRepo.saveWithMetadata(e,a.key,a.value,a.category,a.type,a.confidence,"auto");this.embeddingService&&this.embeddingService.embedAndStore(e,`${a.key}: ${a.value}`,"memory",l.id).catch(u=>this.logger.debug({err:u},"Auto-embed failed")),i++,this.logger.info({key:a.key,type:a.type,confidence:a.confidence},"Auto-extracted memory saved")}catch(l){this.logger.warn({err:l,key:a.key},"Failed to save extracted memory")}return i}catch(r){return this.logger.error({err:r},"Memory extraction failed"),0}}parseResponse(e){try{let t=e.match(/\[[\s\S]*\]/);if(!t)return[];let s=JSON.parse(t[0]);return Array.isArray(s)?s.filter(r=>typeof r=="object"&&r!==null).map(r=>({key:String(r.key||""),value:String(r.value||""),type:this.validateType(String(r.type||"fact")),confidence:this.clampConfidence(Number(r.confidence)||.5),category:String(r.category||"general")})).filter(r=>r.key&&r.value):[]}catch{return this.logger.debug({content:e.slice(0,200)},"Failed to parse extraction response"),[]}}validateType(e){return zi.includes(e)?e:"fact"}clampConfidence(e){return Math.max(0,Math.min(1,e))}}});var Wt,pr=f(()=>{"use strict";ur();mr();Wt=class{static{d(this,"ActiveLearningService")}extractor;logger;minMessageLength;maxExtractionsPerMinute;extractionTimestamps=new Map;constructor(e){this.logger=e.logger,this.minMessageLength=e.minMessageLength??15,this.maxExtractionsPerMinute=e.maxExtractionsPerMinute??5,this.extractor=new Bt(e.llm,e.memoryRepo,this.logger,e.embeddingService,e.minConfidence??.4)}onMessageProcessed(e,t,s){if(!t||t.length<this.minMessageLength)return;let r=dr(t);if(r.level==="low"){this.logger.debug({signal:"low"},"Skipping extraction \u2014 low signal");return}if(!this.checkRateLimit(e)){this.logger.debug({userId:e},"Skipping extraction \u2014 rate limit reached");return}this.logger.info({signal:r.level,patterns:r.matchedPatterns},"High signal detected, triggering extraction"),this.extractor.extract(e,t,s).then(n=>{n>0&&this.logger.info({userId:e,extractedCount:n},"Auto-extraction complete")}).catch(n=>{this.logger.error({err:n},"Auto-extraction failed")})}checkRateLimit(e){let t=Date.now(),s=t-6e4,r=this.extractionTimestamps.get(e);r||(r=[],this.extractionTimestamps.set(e,r));let n=r.filter(o=>o>s);return this.extractionTimestamps.set(e,n),n.length>=this.maxExtractionsPerMinute?!1:(n.push(t),!0)}}});var Ki,Vi,Gi,Yi,Ht,hr=f(()=>{"use strict";Ki=Math.LN2,Vi=.3,Gi=.7,Yi=3,Ht=class{static{d(this,"MemoryRetriever")}memoryRepo;logger;embeddingService;constructor(e,t,s){this.memoryRepo=e,this.logger=t,this.embeddingService=s}async retrieve(e,t,s=15){try{let r=this.memoryRepo.keywordSearch(e,t,30),n=[],o=!1;if(this.embeddingService)try{n=await this.embeddingService.semanticSearch(e,t,30),o=n.length>0}catch(m){this.logger.debug({err:m},"Semantic search failed, falling back to keyword-only")}let i=new Map,a=r.length;for(let m=0;m<r.length;m++){let h=r[m],w=a>0?1-m/a:0,E=o?Vi:1,T=this.applyBoosts(w*E,h);i.set(h.id,{memory:{key:h.key,value:h.value,category:h.category,type:h.type,score:T},score:T}),this.memoryRepo.recordAccess(h.id)}if(o)for(let m of n){let h=m.score*Gi,w=i.get(m.key);if(w)w.score+=h,w.memory.score=w.score;else{let E=this.memoryRepo.recall(e,m.key),T=this.applyBoosts(h,E||void 0);i.set(m.key,{memory:{key:m.key,value:m.value,category:m.category,type:E?.type||"general",score:T},score:T}),E&&this.memoryRepo.recordAccess(E.id)}}let l=Array.from(i.values()).sort((m,h)=>h.score-m.score),u=new Map,p=[];for(let{memory:m}of l){let h=u.get(m.type)||0;if(!(h>=Yi)&&(u.set(m.type,h+1),p.push(m),p.length>=s))break}return this.logger.debug({keywordCount:r.length,semanticCount:n.length,resultCount:p.length,hasSemanticSearch:o},"Hybrid memory retrieval complete"),p}catch(r){return this.logger.error({err:r},"Memory retrieval failed"),this.memoryRepo.getRecentForPrompt(e,s).map(n=>({key:n.key,value:n.value,category:n.category,type:n.type,score:0}))}}applyBoosts(e,t){let s=e;if(t){s*=.5+.5*t.confidence;let r=new Date(t.updatedAt).getTime(),n=Date.now()-r,o=Math.exp(-Ki*n/2592e6);s*=o}return s}}});import{EventEmitter as Ji}from"node:events";var W,ae=f(()=>{"use strict";W=class extends Ji{static{d(this,"MessagingAdapter")}status="disconnected";async sendPhoto(e,t,s){}async sendFile(e,t,s,r){}getStatus(){return this.status}}});import{Bot as Zi,InputFile as Zn}from"grammy";function Qn(c){if(c==="markdown")return"MarkdownV2";if(c==="html")return"HTML"}var cs,eo=f(()=>{"use strict";ae();d(Qn,"mapParseMode");cs=class extends W{static{d(this,"TelegramAdapter")}platform="telegram";bot;constructor(e){super(),this.bot=new Zi(e)}async connect(){this.status="connecting",this.bot.on("message:text",e=>{this.emit("message",this.normalizeMessage(e.message,e.message.text))}),this.bot.on("message:photo",async e=>{let t=e.message,r=(t.caption??"")||"[Photo]",n=t.photo[t.photo.length-1],o=await this.downloadAttachment(n.file_id,"image","image/jpeg"),i=this.normalizeMessage(t,r);i.attachments=o?[o]:void 0,this.emit("message",i)}),this.bot.on("message:voice",async e=>{let t=e.message,s=await this.downloadAttachment(t.voice.file_id,"audio",t.voice.mime_type??"audio/ogg"),r=this.normalizeMessage(t,"[Voice message]");r.attachments=s?[s]:void 0,this.emit("message",r)}),this.bot.on("message:audio",async e=>{let t=e.message,r=(t.caption??"")||`[Audio: ${t.audio.file_name??"audio"}]`,n=await this.downloadAttachment(t.audio.file_id,"audio",t.audio.mime_type??"audio/mpeg"),o=this.normalizeMessage(t,r);o.attachments=n?[n]:void 0,this.emit("message",o)}),this.bot.on("message:video",async e=>{let t=e.message,r=(t.caption??"")||"[Video]",n=await this.downloadAttachment(t.video.file_id,"video",t.video.mime_type??"video/mp4"),o=this.normalizeMessage(t,r);o.attachments=n?[n]:void 0,this.emit("message",o)}),this.bot.on("message:document",async e=>{let t=e.message,s=t.document,n=(t.caption??"")||`[Document: ${s.file_name??"file"}]`,o=await this.downloadAttachment(s.file_id,"document",s.mime_type??"application/octet-stream",s.file_name),i=this.normalizeMessage(t,n);i.attachments=o?[o]:void 0,this.emit("message",i)}),this.bot.on("message:video_note",async e=>{let t=e.message,s=await this.downloadAttachment(t.video_note.file_id,"video","video/mp4"),r=this.normalizeMessage(t,"[Video note]");r.attachments=s?[s]:void 0,this.emit("message",r)}),this.bot.on("message:sticker",e=>{let t=e.message,s=t.sticker.emoji??"\u{1F3F7}\uFE0F";this.emit("message",this.normalizeMessage(t,`[Sticker: ${s}]`))}),this.bot.catch(e=>{this.emit("error",e.error)}),this.bot.start({onStart:d(()=>{this.status="connected",this.emit("connected")},"onStart")})}async disconnect(){await this.bot.stop(),this.status="disconnected",this.emit("disconnected")}async sendMessage(e,t,s){let r=await this.bot.api.sendMessage(Number(e),t,{reply_to_message_id:s?.replyToMessageId?Number(s.replyToMessageId):void 0,parse_mode:Qn(s?.parseMode)});return String(r.message_id)}async editMessage(e,t,s,r){await this.bot.api.editMessageText(Number(e),Number(t),s,{parse_mode:Qn(r?.parseMode)})}async deleteMessage(e,t){await this.bot.api.deleteMessage(Number(e),Number(t))}async sendPhoto(e,t,s){let r=await this.bot.api.sendPhoto(Number(e),new Zn(t,"image.png"),{caption:s});return String(r.message_id)}async sendFile(e,t,s,r){let n=await this.bot.api.sendDocument(Number(e),new Zn(t,s),{caption:r});return String(n.message_id)}normalizeMessage(e,t){return{id:String(e.message_id),platform:"telegram",chatId:String(e.chat.id),chatType:e.chat.type==="private"?"dm":"group",userId:String(e.from.id),userName:e.from.username??String(e.from.id),displayName:[e.from.first_name,e.from.last_name].filter(Boolean).join(" "),text:t,timestamp:new Date(e.date*1e3),replyToMessageId:e.reply_to_message?String(e.reply_to_message.message_id):void 0}}async downloadAttachment(e,t,s,r){try{let o=(await this.bot.api.getFile(e)).file_path;if(!o)return;let i=`https://api.telegram.org/file/bot${this.bot.token}/${o}`,a=await fetch(i);if(!a.ok)return;let l=Buffer.from(await a.arrayBuffer());return{type:t,mimeType:s,fileName:r??o.split("/").pop(),size:l.length,data:l}}catch(n){console.error("[telegram] Failed to download file",e,n);return}}}});import{Client as Qi,GatewayIntentBits as ls,Events as fr}from"discord.js";var ds,to=f(()=>{"use strict";ae();ds=class extends W{static{d(this,"DiscordAdapter")}platform="discord";client=null;token;constructor(e){super(),this.token=e}async connect(){this.status="connecting",this.client=new Qi({intents:[ls.Guilds,ls.GuildMessages,ls.MessageContent,ls.DirectMessages]}),this.client.on(fr.MessageCreate,async e=>{if(!e.author.bot)try{let t=await this.downloadAttachments(e),s=e.content||this.inferTextFromAttachments(t),r={id:e.id,platform:"discord",chatId:e.channelId,chatType:e.channel.isDMBased()?"dm":"group",userId:e.author.id,userName:e.author.username,displayName:e.author.displayName,text:s,timestamp:e.createdAt,replyToMessageId:e.reference?.messageId??void 0,attachments:t.length>0?t:void 0};this.emit("message",r)}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t)))}}),this.client.on(fr.ClientReady,()=>{this.status="connected",this.emit("connected")}),this.client.on(fr.Error,e=>{this.emit("error",e)}),await this.client.login(this.token)}async disconnect(){this.client?.destroy(),this.client=null,this.status="disconnected",this.emit("disconnected")}async sendMessage(e,t,s){if(!this.client)throw new Error("Client is not connected");let r=await this.client.channels.fetch(e);if(!r?.isTextBased()||!("send"in r))throw new Error(`Channel ${e} is not a text channel`);return s?.replyToMessageId?(await(await r.messages.fetch(s.replyToMessageId)).reply(t)).id:(await r.send(t)).id}async editMessage(e,t,s,r){if(!this.client)throw new Error("Client is not connected");let n=await this.client.channels.fetch(e);if(!n?.isTextBased()||!("messages"in n))throw new Error(`Channel ${e} is not a text channel`);await(await n.messages.fetch(t)).edit(s)}async deleteMessage(e,t){if(!this.client)throw new Error("Client is not connected");let s=await this.client.channels.fetch(e);if(!s?.isTextBased()||!("messages"in s))throw new Error(`Channel ${e} is not a text channel`);await(await s.messages.fetch(t)).delete()}async sendPhoto(e,t,s){if(!this.client)return;let r=await this.client.channels.fetch(e);return!r?.isTextBased()||!("send"in r)?void 0:(await r.send({content:s,files:[{attachment:t,name:"image.png"}]})).id}async sendFile(e,t,s,r){if(!this.client)return;let n=await this.client.channels.fetch(e);return!n?.isTextBased()||!("send"in n)?void 0:(await n.send({content:r,files:[{attachment:t,name:s}]})).id}async downloadAttachments(e){let t=[],s=e.attachments;if(!s||s.size===0)return t;for(let[,r]of s)try{let n=await fetch(r.url);if(!n.ok)continue;let o=await n.arrayBuffer(),i=Buffer.from(o),a=this.classifyContentType(r.contentType);t.push({type:a,url:r.url,mimeType:r.contentType??void 0,fileName:r.name??void 0,size:r.size??i.length,data:i})}catch(n){console.error("[discord] Failed to download attachment",r.url,n)}return t}classifyContentType(e){return e?e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"document":"other"}inferTextFromAttachments(e){if(e.length===0)return"";let t=e.map(s=>s.type);return t.includes("image")?"[Photo]":t.includes("audio")?"[Voice message]":t.includes("video")?"[Video]":t.includes("document")?"[Document]":"[File]"}}});var us,so=f(()=>{"use strict";ae();us=class extends W{static{d(this,"MatrixAdapter")}platform="matrix";client;homeserverUrl;accessToken;botUserId;constructor(e,t,s){super(),this.homeserverUrl=e.replace(/\/+$/,""),this.accessToken=t,this.botUserId=s}async connect(){this.status="connecting";let{MatrixClient:e,SimpleFsStorageProvider:t,AutojoinRoomsMixin:s}=await import("matrix-bot-sdk"),r=new t("./data/matrix-storage");this.client=new e(this.homeserverUrl,this.accessToken,r),s.setupOnClient(this.client),this.client.on("room.message",async(n,o)=>{if(o.sender===this.botUserId)return;let i=o.content?.msgtype;if(i)try{let a=await this.normalizeEvent(n,o,i);a&&this.emit("message",a)}catch(a){this.emit("error",a instanceof Error?a:new Error(String(a)))}}),await this.client.start(),this.status="connected",this.emit("connected")}async disconnect(){this.client.stop(),this.status="disconnected",this.emit("disconnected")}async sendMessage(e,t,s){return s?.parseMode==="html"?await this.client.sendEvent(e,"m.room.message",{msgtype:"m.text",body:t.replace(/<[^>]*>/g,""),format:"org.matrix.custom.html",formatted_body:t}):await this.client.sendText(e,t)}async editMessage(e,t,s,r){let n=r?.parseMode==="html",o={msgtype:"m.text",body:"* "+(n?s.replace(/<[^>]*>/g,""):s),"m.new_content":{msgtype:"m.text",body:n?s.replace(/<[^>]*>/g,""):s,...n?{format:"org.matrix.custom.html",formatted_body:s}:{}},"m.relates_to":{rel_type:"m.replace",event_id:t}};await this.client.sendEvent(e,"m.room.message",o)}async deleteMessage(e,t){await this.client.redactEvent(e,t)}async sendPhoto(e,t,s){let r=await this.client.uploadContent(t,"image/png","image.png"),n={msgtype:"m.image",body:s??"image.png",url:r,info:{mimetype:"image/png",size:t.length}};return await this.client.sendEvent(e,"m.room.message",n)}async sendFile(e,t,s,r){let n=this.guessMimeType(s),o=await this.client.uploadContent(t,n,s),i={msgtype:"m.file",body:r??s,filename:s,url:o,info:{mimetype:n,size:t.length}};return await this.client.sendEvent(e,"m.room.message",i)}async normalizeEvent(e,t,s){let r={id:t.event_id,platform:"matrix",chatId:e,chatType:"group",userId:t.sender,userName:t.sender.split(":")[0].slice(1),timestamp:new Date(t.origin_server_ts),replyToMessageId:t.content["m.relates_to"]?.["m.in_reply_to"]?.event_id};switch(s){case"m.text":return{...r,text:t.content.body};case"m.image":{let n=await this.downloadAttachment(t.content,"image");return{...r,text:t.content.body??"[Photo]",attachments:n?[n]:void 0}}case"m.audio":{let n=await this.downloadAttachment(t.content,"audio");return{...r,text:t.content.body??"[Voice message]",attachments:n?[n]:void 0}}case"m.video":{let n=await this.downloadAttachment(t.content,"video");return{...r,text:t.content.body??"[Video]",attachments:n?[n]:void 0}}case"m.file":{let n=await this.downloadAttachment(t.content,"document");return{...r,text:t.content.body??"[Document]",attachments:n?[n]:void 0}}default:return t.content.body?{...r,text:t.content.body}:void 0}}async downloadAttachment(e,t){let s=e.url;if(!s||!s.startsWith("mxc://"))return;let r=e.info??{},n=r.mimetype,o=r.size,i=e.filename??e.body??"file";try{let a=s.slice(6),l=`${this.homeserverUrl}/_matrix/media/v3/download/${a}`,u=await fetch(l,{headers:{Authorization:`Bearer ${this.accessToken}`}});if(!u.ok)return;let p=await u.arrayBuffer(),m=Buffer.from(p);return{type:t,mimeType:n,fileName:i,size:o??m.length,data:m}}catch(a){console.error("[matrix] Failed to download attachment",s,a);return}}guessMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{pdf:"application/pdf",txt:"text/plain",json:"application/json",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",mp3:"audio/mpeg",ogg:"audio/ogg",mp4:"video/mp4",zip:"application/zip",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}[t??""]??"application/octet-stream"}}});var ms,ro=f(()=>{"use strict";ae();ms=class extends W{static{d(this,"WhatsAppAdapter")}platform="whatsapp";socket;downloadMedia;dataPath;reconnectAttempts=0;reconnectTimer;constructor(e){super(),this.dataPath=e}async connect(){this.status="connecting";let e=await import("@whiskeysockets/baileys"),t=e.default??e,{makeWASocket:s,useMultiFileAuthState:r,DisconnectReason:n,downloadMediaMessage:o}=t;this.downloadMedia=o;let{state:i,saveCreds:a}=await r(this.dataPath);this.socket=s({auth:i,printQRInTerminal:!0}),this.socket.ev.on("creds.update",a),this.socket.ev.on("connection.update",l=>{if(l.connection==="open"&&(this.status="connected",this.reconnectAttempts=0,this.emit("connected")),l.connection==="close"){let p=l.lastDisconnect?.error?.output?.statusCode!==n.loggedOut;if(this.status="disconnected",this.emit("disconnected"),p){let m=Math.min(1e3*Math.pow(2,this.reconnectAttempts),6e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>this.connect(),m)}}}),this.socket.ev.on("messages.upsert",({messages:l,type:u})=>{if(u==="notify")for(let p of l)p.message&&(p.key.fromMe||this.processMessage(p).catch(m=>{this.emit("error",m instanceof Error?m:new Error(String(m)))}))})}async disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.reconnectAttempts=0,this.socket?.end(void 0),this.socket=void 0,this.status="disconnected",this.emit("disconnected")}async sendMessage(e,t,s){return(await this.socket.sendMessage(e,{text:t},s?.replyToMessageId?{quoted:{key:{remoteJid:e,id:s.replyToMessageId},message:{}}}:void 0))?.key?.id??""}async editMessage(e,t,s,r){await this.socket.sendMessage(e,{text:s,edit:{remoteJid:e,id:t,fromMe:!0}})}async deleteMessage(e,t){await this.socket.sendMessage(e,{delete:{remoteJid:e,id:t,fromMe:!0}})}async sendPhoto(e,t,s){return(await this.socket.sendMessage(e,{image:t,caption:s}))?.key?.id}async sendFile(e,t,s,r){return(await this.socket.sendMessage(e,{document:t,fileName:s,caption:r,mimetype:this.guessMimeType(s)}))?.key?.id}async processMessage(e){let t=e.message,s=t.conversation??t.extendedTextMessage?.text??t.imageMessage?.caption??t.videoMessage?.caption??t.documentMessage?.caption??"",r=[],n=s;if(t.imageMessage){let i=await this.downloadMediaSafe(e);i&&r.push({type:"image",mimeType:t.imageMessage.mimetype??"image/jpeg",size:t.imageMessage.fileLength??i.length,data:i}),n||(n="[Photo]")}else if(t.audioMessage){let i=await this.downloadMediaSafe(e);i&&r.push({type:"audio",mimeType:t.audioMessage.mimetype??"audio/ogg",size:t.audioMessage.fileLength??i.length,data:i}),n||(n="[Voice message]")}else if(t.videoMessage){let i=await this.downloadMediaSafe(e);i&&r.push({type:"video",mimeType:t.videoMessage.mimetype??"video/mp4",size:t.videoMessage.fileLength??i.length,data:i}),n||(n="[Video]")}else if(t.documentMessage){let i=await this.downloadMediaSafe(e);i&&r.push({type:"document",mimeType:t.documentMessage.mimetype??"application/octet-stream",fileName:t.documentMessage.fileName??"document",size:t.documentMessage.fileLength??i.length,data:i}),n||(n="[Document]")}else if(t.stickerMessage&&!s)return;if(!n&&r.length===0)return;let o={id:e.key.id??"",platform:"whatsapp",chatId:e.key.remoteJid??"",chatType:e.key.remoteJid?.endsWith("@g.us")?"group":"dm",userId:e.key.participant??e.key.remoteJid??"",userName:e.pushName??e.key.participant??e.key.remoteJid??"",text:n,timestamp:new Date(e.messageTimestamp*1e3),replyToMessageId:t.extendedTextMessage?.contextInfo?.stanzaId??void 0,attachments:r.length>0?r:void 0};this.emit("message",o)}async downloadMediaSafe(e){try{if(!this.downloadMedia)return;let t=await this.downloadMedia(e,"buffer",{});return Buffer.isBuffer(t)?t:Buffer.from(t)}catch(t){console.error("[whatsapp] Failed to download media",t);return}}guessMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{pdf:"application/pdf",txt:"text/plain",json:"application/json",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",mp3:"audio/mpeg",ogg:"audio/ogg",mp4:"video/mp4",zip:"application/zip",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}[t??""]??"application/octet-stream"}}});var ps,no=f(()=>{"use strict";ae();ps=class extends W{static{d(this,"SignalAdapter")}apiUrl;phoneNumber;platform="signal";pollingInterval;constructor(e,t){super(),this.apiUrl=e,this.phoneNumber=t}async connect(){this.status="connecting";try{let e=await fetch(`${this.apiUrl}/v1/about`);if(!e.ok)throw new Error(`Signal API not reachable: ${e.status}`);this.pollingInterval=setInterval(()=>{this.pollMessages().catch(t=>{this.emit("error",t instanceof Error?t:new Error(String(t)))})},2e3),this.status="connected",this.emit("connected")}catch(e){this.status="error",this.emit("error",e instanceof Error?e:new Error(String(e)))}}async disconnect(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0),this.status="disconnected",this.emit("disconnected")}async sendMessage(e,t,s){let r=e.startsWith("group."),n={message:t,number:this.phoneNumber};r?n.recipients=[e.replace("group.","")]:n.recipients=[e];let o=await fetch(`${this.apiUrl}/v2/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Signal send failed: ${o.status} ${await o.text()}`);let i=await o.json();return String(i.timestamp??Date.now())}async editMessage(e,t,s,r){throw new Error("Signal does not support message editing")}async deleteMessage(e,t){let s={number:this.phoneNumber,recipients:[e],timestamp:Number(t)},r=await fetch(`${this.apiUrl}/v1/deleteMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok)throw new Error(`Signal delete failed: ${r.status} ${await r.text()}`)}async pollMessages(){let e=await fetch(`${this.apiUrl}/v1/receive/${this.phoneNumber}`);if(!e.ok)return;let t=await e.json();for(let s of t){let r=s.envelope?.dataMessage;if(!r||!r.message&&(!r.attachments||r.attachments.length===0))continue;let n=s.envelope,o=r.groupInfo?.groupId?`group.${r.groupInfo.groupId}`:n.sourceNumber??n.source??"",i=[];if(r.attachments)for(let u of r.attachments){let p=await this.downloadAttachment(u);p&&i.push(p)}let a=r.message||this.inferTextFromAttachments(i)||"";if(!a&&i.length===0)continue;let l={id:String(r.timestamp??Date.now()),platform:"signal",chatId:o,chatType:r.groupInfo?"group":"dm",userId:n.sourceNumber??n.source??"",userName:n.sourceName??n.sourceNumber??n.source??"",displayName:n.sourceName,text:a,timestamp:new Date(r.timestamp??Date.now()),attachments:i.length>0?i:void 0};this.emit("message",l)}}async downloadAttachment(e){if(e.id)try{let t=await fetch(`${this.apiUrl}/v1/attachments/${e.id}`);if(!t.ok)return;let s=await t.arrayBuffer(),r=Buffer.from(s);return{type:this.classifyContentType(e.contentType),mimeType:e.contentType??void 0,fileName:e.filename??void 0,size:e.size??r.length,data:r}}catch(t){console.error("[signal] Failed to download attachment",e.id,t);return}}classifyContentType(e){return e?e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"document":"other"}inferTextFromAttachments(e){if(e.length===0)return"";let t=e.map(s=>s.type);return t.includes("image")?"[Photo]":t.includes("audio")?"[Voice message]":t.includes("video")?"[Video]":t.includes("document")?"[Document]":"[File]"}}});import gr from"node:readline";var hs,oo=f(()=>{"use strict";ae();hs=class extends W{static{d(this,"CLIAdapter")}platform="cli";rl;messageCounter=0;async connect(){this.status="connecting",this.rl=gr.createInterface({input:process.stdin,output:process.stdout,prompt:"You: "}),console.log(`
490
+ Return ONLY a valid JSON array, no explanation:`,Bt=class{static{d(this,"MemoryExtractor")}llm;memoryRepo;logger;embeddingService;minConfidence;constructor(e,t,s,r,n=.4){this.llm=e,this.memoryRepo=t,this.logger=s,this.embeddingService=r,this.minConfidence=n}async extract(e,t,s){try{let r=qi.replace("{USER_MESSAGE}",t).replace("{ASSISTANT_RESPONSE}",s),n=await this.llm.complete({messages:[{role:"user",content:r}],temperature:.1,tier:"fast",maxTokens:1024}),o=this.parseResponse(n.content);if(o.length===0)return 0;let i=0;for(let a of o)if(!(a.confidence<this.minConfidence))try{let l=this.memoryRepo.saveWithMetadata(e,a.key,a.value,a.category,a.type,a.confidence,"auto");this.embeddingService&&this.embeddingService.embedAndStore(e,`${a.key}: ${a.value}`,"memory",l.id).catch(u=>this.logger.debug({err:u},"Auto-embed failed")),i++,this.logger.info({key:a.key,type:a.type,confidence:a.confidence},"Auto-extracted memory saved")}catch(l){this.logger.warn({err:l,key:a.key},"Failed to save extracted memory")}return i}catch(r){return this.logger.error({err:r},"Memory extraction failed"),0}}parseResponse(e){try{let t=e.match(/\[[\s\S]*\]/);if(!t)return[];let s=JSON.parse(t[0]);return Array.isArray(s)?s.filter(r=>typeof r=="object"&&r!==null).map(r=>({key:String(r.key||""),value:String(r.value||""),type:this.validateType(String(r.type||"fact")),confidence:this.clampConfidence(Number(r.confidence)||.5),category:String(r.category||"general")})).filter(r=>r.key&&r.value):[]}catch{return this.logger.debug({content:e.slice(0,200)},"Failed to parse extraction response"),[]}}validateType(e){return zi.includes(e)?e:"fact"}clampConfidence(e){return Math.max(0,Math.min(1,e))}}});var Wt,pr=f(()=>{"use strict";ur();mr();Wt=class{static{d(this,"ActiveLearningService")}extractor;logger;minMessageLength;maxExtractionsPerMinute;extractionTimestamps=new Map;constructor(e){this.logger=e.logger,this.minMessageLength=e.minMessageLength??15,this.maxExtractionsPerMinute=e.maxExtractionsPerMinute??5,this.extractor=new Bt(e.llm,e.memoryRepo,this.logger,e.embeddingService,e.minConfidence??.4)}onMessageProcessed(e,t,s){if(!t||t.length<this.minMessageLength)return;let r=dr(t);if(r.level==="low"){this.logger.debug({signal:"low"},"Skipping extraction \u2014 low signal");return}if(!this.checkRateLimit(e)){this.logger.debug({userId:e},"Skipping extraction \u2014 rate limit reached");return}this.logger.info({signal:r.level,patterns:r.matchedPatterns},"High signal detected, triggering extraction"),this.extractor.extract(e,t,s).then(n=>{n>0&&this.logger.info({userId:e,extractedCount:n},"Auto-extraction complete")}).catch(n=>{this.logger.error({err:n},"Auto-extraction failed")})}checkRateLimit(e){let t=Date.now(),s=t-6e4,r=this.extractionTimestamps.get(e);r||(r=[],this.extractionTimestamps.set(e,r));let n=r.filter(o=>o>s);return this.extractionTimestamps.set(e,n),n.length>=this.maxExtractionsPerMinute?!1:(n.push(t),!0)}}});var Ki,Vi,Gi,Yi,Ht,hr=f(()=>{"use strict";Ki=Math.LN2,Vi=.3,Gi=.7,Yi=3,Ht=class{static{d(this,"MemoryRetriever")}memoryRepo;logger;embeddingService;constructor(e,t,s){this.memoryRepo=e,this.logger=t,this.embeddingService=s}async retrieve(e,t,s=15){try{let r=this.memoryRepo.keywordSearch(e,t,30),n=[],o=!1;if(this.embeddingService)try{n=await this.embeddingService.semanticSearch(e,t,30),o=n.length>0}catch(m){this.logger.debug({err:m},"Semantic search failed, falling back to keyword-only")}let i=new Map,a=r.length;for(let m=0;m<r.length;m++){let h=r[m],w=a>0?1-m/a:0,E=o?Vi:1,T=this.applyBoosts(w*E,h);i.set(h.id,{memory:{key:h.key,value:h.value,category:h.category,type:h.type,score:T},score:T}),this.memoryRepo.recordAccess(h.id)}if(o)for(let m of n){let h=m.score*Gi,w=i.get(m.key);if(w)w.score+=h,w.memory.score=w.score;else{let E=this.memoryRepo.recall(e,m.key),T=this.applyBoosts(h,E||void 0);i.set(m.key,{memory:{key:m.key,value:m.value,category:m.category,type:E?.type||"general",score:T},score:T}),E&&this.memoryRepo.recordAccess(E.id)}}let l=Array.from(i.values()).sort((m,h)=>h.score-m.score),u=new Map,p=[];for(let{memory:m}of l){let h=u.get(m.type)||0;if(!(h>=Yi)&&(u.set(m.type,h+1),p.push(m),p.length>=s))break}return this.logger.debug({keywordCount:r.length,semanticCount:n.length,resultCount:p.length,hasSemanticSearch:o},"Hybrid memory retrieval complete"),p}catch(r){return this.logger.error({err:r},"Memory retrieval failed"),this.memoryRepo.getRecentForPrompt(e,s).map(n=>({key:n.key,value:n.value,category:n.category,type:n.type,score:0}))}}applyBoosts(e,t){let s=e;if(t){s*=.5+.5*t.confidence;let r=new Date(t.updatedAt).getTime(),n=Date.now()-r,o=Math.exp(-Ki*n/2592e6);s*=o}return s}}});import{EventEmitter as Ji}from"node:events";var X,ae=f(()=>{"use strict";X=class extends Ji{static{d(this,"MessagingAdapter")}status="disconnected";async sendPhoto(e,t,s){}async sendFile(e,t,s,r){}getStatus(){return this.status}}});import{Bot as Zi,InputFile as Zn}from"grammy";function Qn(c){if(c==="markdown")return"MarkdownV2";if(c==="html")return"HTML"}var cs,eo=f(()=>{"use strict";ae();d(Qn,"mapParseMode");cs=class extends X{static{d(this,"TelegramAdapter")}platform="telegram";bot;constructor(e){super(),this.bot=new Zi(e)}async connect(){this.status="connecting",this.bot.on("message:text",e=>{this.emit("message",this.normalizeMessage(e.message,e.message.text))}),this.bot.on("message:photo",async e=>{let t=e.message,r=(t.caption??"")||"[Photo]",n=t.photo[t.photo.length-1],o=await this.downloadAttachment(n.file_id,"image","image/jpeg"),i=this.normalizeMessage(t,r);i.attachments=o?[o]:void 0,this.emit("message",i)}),this.bot.on("message:voice",async e=>{let t=e.message,s=await this.downloadAttachment(t.voice.file_id,"audio",t.voice.mime_type??"audio/ogg"),r=this.normalizeMessage(t,"[Voice message]");r.attachments=s?[s]:void 0,this.emit("message",r)}),this.bot.on("message:audio",async e=>{let t=e.message,r=(t.caption??"")||`[Audio: ${t.audio.file_name??"audio"}]`,n=await this.downloadAttachment(t.audio.file_id,"audio",t.audio.mime_type??"audio/mpeg"),o=this.normalizeMessage(t,r);o.attachments=n?[n]:void 0,this.emit("message",o)}),this.bot.on("message:video",async e=>{let t=e.message,r=(t.caption??"")||"[Video]",n=await this.downloadAttachment(t.video.file_id,"video",t.video.mime_type??"video/mp4"),o=this.normalizeMessage(t,r);o.attachments=n?[n]:void 0,this.emit("message",o)}),this.bot.on("message:document",async e=>{let t=e.message,s=t.document,n=(t.caption??"")||`[Document: ${s.file_name??"file"}]`,o=await this.downloadAttachment(s.file_id,"document",s.mime_type??"application/octet-stream",s.file_name),i=this.normalizeMessage(t,n);i.attachments=o?[o]:void 0,this.emit("message",i)}),this.bot.on("message:video_note",async e=>{let t=e.message,s=await this.downloadAttachment(t.video_note.file_id,"video","video/mp4"),r=this.normalizeMessage(t,"[Video note]");r.attachments=s?[s]:void 0,this.emit("message",r)}),this.bot.on("message:sticker",e=>{let t=e.message,s=t.sticker.emoji??"\u{1F3F7}\uFE0F";this.emit("message",this.normalizeMessage(t,`[Sticker: ${s}]`))}),this.bot.catch(e=>{this.emit("error",e.error)}),this.bot.start({onStart:d(()=>{this.status="connected",this.emit("connected")},"onStart")})}async disconnect(){await this.bot.stop(),this.status="disconnected",this.emit("disconnected")}async sendMessage(e,t,s){let r=await this.bot.api.sendMessage(Number(e),t,{reply_to_message_id:s?.replyToMessageId?Number(s.replyToMessageId):void 0,parse_mode:Qn(s?.parseMode)});return String(r.message_id)}async editMessage(e,t,s,r){await this.bot.api.editMessageText(Number(e),Number(t),s,{parse_mode:Qn(r?.parseMode)})}async deleteMessage(e,t){await this.bot.api.deleteMessage(Number(e),Number(t))}async sendPhoto(e,t,s){let r=await this.bot.api.sendPhoto(Number(e),new Zn(t,"image.png"),{caption:s});return String(r.message_id)}async sendFile(e,t,s,r){let n=await this.bot.api.sendDocument(Number(e),new Zn(t,s),{caption:r});return String(n.message_id)}normalizeMessage(e,t){return{id:String(e.message_id),platform:"telegram",chatId:String(e.chat.id),chatType:e.chat.type==="private"?"dm":"group",userId:String(e.from.id),userName:e.from.username??String(e.from.id),displayName:[e.from.first_name,e.from.last_name].filter(Boolean).join(" "),text:t,timestamp:new Date(e.date*1e3),replyToMessageId:e.reply_to_message?String(e.reply_to_message.message_id):void 0}}async downloadAttachment(e,t,s,r){try{let o=(await this.bot.api.getFile(e)).file_path;if(!o)return;let i=`https://api.telegram.org/file/bot${this.bot.token}/${o}`,a=await fetch(i);if(!a.ok)return;let l=Buffer.from(await a.arrayBuffer());return{type:t,mimeType:s,fileName:r??o.split("/").pop(),size:l.length,data:l}}catch(n){console.error("[telegram] Failed to download file",e,n);return}}}});import{Client as Qi,GatewayIntentBits as ls,Events as fr}from"discord.js";var ds,to=f(()=>{"use strict";ae();ds=class extends X{static{d(this,"DiscordAdapter")}platform="discord";client=null;token;constructor(e){super(),this.token=e}async connect(){this.status="connecting",this.client=new Qi({intents:[ls.Guilds,ls.GuildMessages,ls.MessageContent,ls.DirectMessages]}),this.client.on(fr.MessageCreate,async e=>{if(!e.author.bot)try{let t=await this.downloadAttachments(e),s=e.content||this.inferTextFromAttachments(t),r={id:e.id,platform:"discord",chatId:e.channelId,chatType:e.channel.isDMBased()?"dm":"group",userId:e.author.id,userName:e.author.username,displayName:e.author.displayName,text:s,timestamp:e.createdAt,replyToMessageId:e.reference?.messageId??void 0,attachments:t.length>0?t:void 0};this.emit("message",r)}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t)))}}),this.client.on(fr.ClientReady,()=>{this.status="connected",this.emit("connected")}),this.client.on(fr.Error,e=>{this.emit("error",e)}),await this.client.login(this.token)}async disconnect(){this.client?.destroy(),this.client=null,this.status="disconnected",this.emit("disconnected")}async sendMessage(e,t,s){if(!this.client)throw new Error("Client is not connected");let r=await this.client.channels.fetch(e);if(!r?.isTextBased()||!("send"in r))throw new Error(`Channel ${e} is not a text channel`);return s?.replyToMessageId?(await(await r.messages.fetch(s.replyToMessageId)).reply(t)).id:(await r.send(t)).id}async editMessage(e,t,s,r){if(!this.client)throw new Error("Client is not connected");let n=await this.client.channels.fetch(e);if(!n?.isTextBased()||!("messages"in n))throw new Error(`Channel ${e} is not a text channel`);await(await n.messages.fetch(t)).edit(s)}async deleteMessage(e,t){if(!this.client)throw new Error("Client is not connected");let s=await this.client.channels.fetch(e);if(!s?.isTextBased()||!("messages"in s))throw new Error(`Channel ${e} is not a text channel`);await(await s.messages.fetch(t)).delete()}async sendPhoto(e,t,s){if(!this.client)return;let r=await this.client.channels.fetch(e);return!r?.isTextBased()||!("send"in r)?void 0:(await r.send({content:s,files:[{attachment:t,name:"image.png"}]})).id}async sendFile(e,t,s,r){if(!this.client)return;let n=await this.client.channels.fetch(e);return!n?.isTextBased()||!("send"in n)?void 0:(await n.send({content:r,files:[{attachment:t,name:s}]})).id}async downloadAttachments(e){let t=[],s=e.attachments;if(!s||s.size===0)return t;for(let[,r]of s)try{let n=await fetch(r.url);if(!n.ok)continue;let o=await n.arrayBuffer(),i=Buffer.from(o),a=this.classifyContentType(r.contentType);t.push({type:a,url:r.url,mimeType:r.contentType??void 0,fileName:r.name??void 0,size:r.size??i.length,data:i})}catch(n){console.error("[discord] Failed to download attachment",r.url,n)}return t}classifyContentType(e){return e?e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"document":"other"}inferTextFromAttachments(e){if(e.length===0)return"";let t=e.map(s=>s.type);return t.includes("image")?"[Photo]":t.includes("audio")?"[Voice message]":t.includes("video")?"[Video]":t.includes("document")?"[Document]":"[File]"}}});var us,so=f(()=>{"use strict";ae();us=class extends X{static{d(this,"MatrixAdapter")}platform="matrix";client;homeserverUrl;accessToken;botUserId;constructor(e,t,s){super(),this.homeserverUrl=e.replace(/\/+$/,""),this.accessToken=t,this.botUserId=s}async connect(){this.status="connecting";let{MatrixClient:e,SimpleFsStorageProvider:t,AutojoinRoomsMixin:s}=await import("matrix-bot-sdk"),r=new t("./data/matrix-storage");this.client=new e(this.homeserverUrl,this.accessToken,r),s.setupOnClient(this.client),this.client.on("room.message",async(n,o)=>{if(o.sender===this.botUserId)return;let i=o.content?.msgtype;if(i)try{let a=await this.normalizeEvent(n,o,i);a&&this.emit("message",a)}catch(a){this.emit("error",a instanceof Error?a:new Error(String(a)))}}),await this.client.start(),this.status="connected",this.emit("connected")}async disconnect(){this.client.stop(),this.status="disconnected",this.emit("disconnected")}async sendMessage(e,t,s){return s?.parseMode==="html"?await this.client.sendEvent(e,"m.room.message",{msgtype:"m.text",body:t.replace(/<[^>]*>/g,""),format:"org.matrix.custom.html",formatted_body:t}):await this.client.sendText(e,t)}async editMessage(e,t,s,r){let n=r?.parseMode==="html",o={msgtype:"m.text",body:"* "+(n?s.replace(/<[^>]*>/g,""):s),"m.new_content":{msgtype:"m.text",body:n?s.replace(/<[^>]*>/g,""):s,...n?{format:"org.matrix.custom.html",formatted_body:s}:{}},"m.relates_to":{rel_type:"m.replace",event_id:t}};await this.client.sendEvent(e,"m.room.message",o)}async deleteMessage(e,t){await this.client.redactEvent(e,t)}async sendPhoto(e,t,s){let r=await this.client.uploadContent(t,"image/png","image.png"),n={msgtype:"m.image",body:s??"image.png",url:r,info:{mimetype:"image/png",size:t.length}};return await this.client.sendEvent(e,"m.room.message",n)}async sendFile(e,t,s,r){let n=this.guessMimeType(s),o=await this.client.uploadContent(t,n,s),i={msgtype:"m.file",body:r??s,filename:s,url:o,info:{mimetype:n,size:t.length}};return await this.client.sendEvent(e,"m.room.message",i)}async normalizeEvent(e,t,s){let r={id:t.event_id,platform:"matrix",chatId:e,chatType:"group",userId:t.sender,userName:t.sender.split(":")[0].slice(1),timestamp:new Date(t.origin_server_ts),replyToMessageId:t.content["m.relates_to"]?.["m.in_reply_to"]?.event_id};switch(s){case"m.text":return{...r,text:t.content.body};case"m.image":{let n=await this.downloadAttachment(t.content,"image");return{...r,text:t.content.body??"[Photo]",attachments:n?[n]:void 0}}case"m.audio":{let n=await this.downloadAttachment(t.content,"audio");return{...r,text:t.content.body??"[Voice message]",attachments:n?[n]:void 0}}case"m.video":{let n=await this.downloadAttachment(t.content,"video");return{...r,text:t.content.body??"[Video]",attachments:n?[n]:void 0}}case"m.file":{let n=await this.downloadAttachment(t.content,"document");return{...r,text:t.content.body??"[Document]",attachments:n?[n]:void 0}}default:return t.content.body?{...r,text:t.content.body}:void 0}}async downloadAttachment(e,t){let s=e.url;if(!s||!s.startsWith("mxc://"))return;let r=e.info??{},n=r.mimetype,o=r.size,i=e.filename??e.body??"file";try{let a=s.slice(6),l=`${this.homeserverUrl}/_matrix/media/v3/download/${a}`,u=await fetch(l,{headers:{Authorization:`Bearer ${this.accessToken}`}});if(!u.ok)return;let p=await u.arrayBuffer(),m=Buffer.from(p);return{type:t,mimeType:n,fileName:i,size:o??m.length,data:m}}catch(a){console.error("[matrix] Failed to download attachment",s,a);return}}guessMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{pdf:"application/pdf",txt:"text/plain",json:"application/json",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",mp3:"audio/mpeg",ogg:"audio/ogg",mp4:"video/mp4",zip:"application/zip",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}[t??""]??"application/octet-stream"}}});var ms,ro=f(()=>{"use strict";ae();ms=class extends X{static{d(this,"WhatsAppAdapter")}platform="whatsapp";socket;downloadMedia;dataPath;reconnectAttempts=0;reconnectTimer;constructor(e){super(),this.dataPath=e}async connect(){this.status="connecting";let e=await import("@whiskeysockets/baileys"),t=e.default??e,{makeWASocket:s,useMultiFileAuthState:r,DisconnectReason:n,downloadMediaMessage:o}=t;this.downloadMedia=o;let{state:i,saveCreds:a}=await r(this.dataPath);this.socket=s({auth:i,printQRInTerminal:!0}),this.socket.ev.on("creds.update",a),this.socket.ev.on("connection.update",l=>{if(l.connection==="open"&&(this.status="connected",this.reconnectAttempts=0,this.emit("connected")),l.connection==="close"){let p=l.lastDisconnect?.error?.output?.statusCode!==n.loggedOut;if(this.status="disconnected",this.emit("disconnected"),p){let m=Math.min(1e3*Math.pow(2,this.reconnectAttempts),6e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>this.connect(),m)}}}),this.socket.ev.on("messages.upsert",({messages:l,type:u})=>{if(u==="notify")for(let p of l)p.message&&(p.key.fromMe||this.processMessage(p).catch(m=>{this.emit("error",m instanceof Error?m:new Error(String(m)))}))})}async disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.reconnectAttempts=0,this.socket?.end(void 0),this.socket=void 0,this.status="disconnected",this.emit("disconnected")}async sendMessage(e,t,s){return(await this.socket.sendMessage(e,{text:t},s?.replyToMessageId?{quoted:{key:{remoteJid:e,id:s.replyToMessageId},message:{}}}:void 0))?.key?.id??""}async editMessage(e,t,s,r){await this.socket.sendMessage(e,{text:s,edit:{remoteJid:e,id:t,fromMe:!0}})}async deleteMessage(e,t){await this.socket.sendMessage(e,{delete:{remoteJid:e,id:t,fromMe:!0}})}async sendPhoto(e,t,s){return(await this.socket.sendMessage(e,{image:t,caption:s}))?.key?.id}async sendFile(e,t,s,r){return(await this.socket.sendMessage(e,{document:t,fileName:s,caption:r,mimetype:this.guessMimeType(s)}))?.key?.id}async processMessage(e){let t=e.message,s=t.conversation??t.extendedTextMessage?.text??t.imageMessage?.caption??t.videoMessage?.caption??t.documentMessage?.caption??"",r=[],n=s;if(t.imageMessage){let i=await this.downloadMediaSafe(e);i&&r.push({type:"image",mimeType:t.imageMessage.mimetype??"image/jpeg",size:t.imageMessage.fileLength??i.length,data:i}),n||(n="[Photo]")}else if(t.audioMessage){let i=await this.downloadMediaSafe(e);i&&r.push({type:"audio",mimeType:t.audioMessage.mimetype??"audio/ogg",size:t.audioMessage.fileLength??i.length,data:i}),n||(n="[Voice message]")}else if(t.videoMessage){let i=await this.downloadMediaSafe(e);i&&r.push({type:"video",mimeType:t.videoMessage.mimetype??"video/mp4",size:t.videoMessage.fileLength??i.length,data:i}),n||(n="[Video]")}else if(t.documentMessage){let i=await this.downloadMediaSafe(e);i&&r.push({type:"document",mimeType:t.documentMessage.mimetype??"application/octet-stream",fileName:t.documentMessage.fileName??"document",size:t.documentMessage.fileLength??i.length,data:i}),n||(n="[Document]")}else if(t.stickerMessage&&!s)return;if(!n&&r.length===0)return;let o={id:e.key.id??"",platform:"whatsapp",chatId:e.key.remoteJid??"",chatType:e.key.remoteJid?.endsWith("@g.us")?"group":"dm",userId:e.key.participant??e.key.remoteJid??"",userName:e.pushName??e.key.participant??e.key.remoteJid??"",text:n,timestamp:new Date(e.messageTimestamp*1e3),replyToMessageId:t.extendedTextMessage?.contextInfo?.stanzaId??void 0,attachments:r.length>0?r:void 0};this.emit("message",o)}async downloadMediaSafe(e){try{if(!this.downloadMedia)return;let t=await this.downloadMedia(e,"buffer",{});return Buffer.isBuffer(t)?t:Buffer.from(t)}catch(t){console.error("[whatsapp] Failed to download media",t);return}}guessMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{pdf:"application/pdf",txt:"text/plain",json:"application/json",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",mp3:"audio/mpeg",ogg:"audio/ogg",mp4:"video/mp4",zip:"application/zip",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}[t??""]??"application/octet-stream"}}});var ps,no=f(()=>{"use strict";ae();ps=class extends X{static{d(this,"SignalAdapter")}apiUrl;phoneNumber;platform="signal";pollingInterval;constructor(e,t){super(),this.apiUrl=e,this.phoneNumber=t}async connect(){this.status="connecting";try{let e=await fetch(`${this.apiUrl}/v1/about`);if(!e.ok)throw new Error(`Signal API not reachable: ${e.status}`);this.pollingInterval=setInterval(()=>{this.pollMessages().catch(t=>{this.emit("error",t instanceof Error?t:new Error(String(t)))})},2e3),this.status="connected",this.emit("connected")}catch(e){this.status="error",this.emit("error",e instanceof Error?e:new Error(String(e)))}}async disconnect(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0),this.status="disconnected",this.emit("disconnected")}async sendMessage(e,t,s){let r=e.startsWith("group."),n={message:t,number:this.phoneNumber};r?n.recipients=[e.replace("group.","")]:n.recipients=[e];let o=await fetch(`${this.apiUrl}/v2/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Signal send failed: ${o.status} ${await o.text()}`);let i=await o.json();return String(i.timestamp??Date.now())}async editMessage(e,t,s,r){throw new Error("Signal does not support message editing")}async deleteMessage(e,t){let s={number:this.phoneNumber,recipients:[e],timestamp:Number(t)},r=await fetch(`${this.apiUrl}/v1/deleteMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok)throw new Error(`Signal delete failed: ${r.status} ${await r.text()}`)}async pollMessages(){let e=await fetch(`${this.apiUrl}/v1/receive/${this.phoneNumber}`);if(!e.ok)return;let t=await e.json();for(let s of t){let r=s.envelope?.dataMessage;if(!r||!r.message&&(!r.attachments||r.attachments.length===0))continue;let n=s.envelope,o=r.groupInfo?.groupId?`group.${r.groupInfo.groupId}`:n.sourceNumber??n.source??"",i=[];if(r.attachments)for(let u of r.attachments){let p=await this.downloadAttachment(u);p&&i.push(p)}let a=r.message||this.inferTextFromAttachments(i)||"";if(!a&&i.length===0)continue;let l={id:String(r.timestamp??Date.now()),platform:"signal",chatId:o,chatType:r.groupInfo?"group":"dm",userId:n.sourceNumber??n.source??"",userName:n.sourceName??n.sourceNumber??n.source??"",displayName:n.sourceName,text:a,timestamp:new Date(r.timestamp??Date.now()),attachments:i.length>0?i:void 0};this.emit("message",l)}}async downloadAttachment(e){if(e.id)try{let t=await fetch(`${this.apiUrl}/v1/attachments/${e.id}`);if(!t.ok)return;let s=await t.arrayBuffer(),r=Buffer.from(s);return{type:this.classifyContentType(e.contentType),mimeType:e.contentType??void 0,fileName:e.filename??void 0,size:e.size??r.length,data:r}}catch(t){console.error("[signal] Failed to download attachment",e.id,t);return}}classifyContentType(e){return e?e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"document":"other"}inferTextFromAttachments(e){if(e.length===0)return"";let t=e.map(s=>s.type);return t.includes("image")?"[Photo]":t.includes("audio")?"[Voice message]":t.includes("video")?"[Video]":t.includes("document")?"[Document]":"[File]"}}});import gr from"node:readline";var hs,oo=f(()=>{"use strict";ae();hs=class extends X{static{d(this,"CLIAdapter")}platform="cli";rl;messageCounter=0;async connect(){this.status="connecting",this.rl=gr.createInterface({input:process.stdin,output:process.stdout,prompt:"You: "}),console.log(`
489
491
  Alfred Chat \u2014 type your message and press Enter. Use /quit or /exit to leave.
490
492
  `),this.rl.on("line",e=>{let t=e.trim();if(!t){this.prompt();return}if(t==="/quit"||t==="/exit"){console.log(`
491
493
  Goodbye!
492
494
  `),this.emit("disconnected");return}this.messageCounter++;let s={id:`cli-${this.messageCounter}`,platform:"cli",chatId:"cli-chat",chatType:"dm",userId:"cli-user",userName:"cli-user",displayName:"You",text:t,timestamp:new Date};this.emit("message",s)}),this.rl.on("close",()=>{this.emit("disconnected")}),this.status="connected",this.emit("connected"),this.prompt()}async disconnect(){this.rl?.close(),this.rl=void 0,this.status="disconnected"}async sendMessage(e,t,s){let r=`cli-resp-${++this.messageCounter}`;return process.stdout.write(`
493
495
  Alfred: ${t}
494
- `),this.prompt(),r}async editMessage(e,t,s,r){gr.clearLine(process.stdout,0),gr.cursorTo(process.stdout,0),process.stdout.write(`Alfred: ${s}`)}async deleteMessage(e,t){}prompt(){this.rl?.prompt()}}});var be={};G(be,{CLIAdapter:()=>hs,DiscordAdapter:()=>ds,MatrixAdapter:()=>us,MessagingAdapter:()=>W,SignalAdapter:()=>ps,TelegramAdapter:()=>cs,WhatsAppAdapter:()=>ms});var _e=f(()=>{"use strict";ae();eo();to();so();ro();no();oo()});import fs from"node:fs";import gs from"node:path";import ea from"js-yaml";var Se,io=f(()=>{"use strict";Ls();Ds();Hs();ss();Lt();tr();sr();rr();nr();or();ir();ar();cr();lr();pr();hr();Se=class{static{d(this,"Alfred")}config;logger;database;pipeline;reminderScheduler;backgroundTaskRunner;proactiveScheduler;adapters=new Map;formatter=new Ct;mcpManager;calendarSkill;constructor(e){this.config=e,this.logger=ot("alfred",e.logger.level)}async initialize(){this.logger.info("Initializing Alfred..."),this.database=new me(this.config.storage.path);let e=this.database.getDb(),t=new it(e),s=new at(e),r=new pe(e),n=new ct(e),o=new lt(e),i=new dt(e),a=new ut(e),l=new mt(e),u=new pt(e),p=new ht(e);this.logger.info("Storage initialized");let m=new St,h=this.loadSecurityRules();m.loadRules(h);let w=new kt(m,r,this.logger.child({component:"security"}));this.logger.info({ruleCount:h.length},"Security engine initialized");let E=Ws(this.config.llm);await E.initialize(),this.logger.info({provider:this.config.llm.default.provider,model:this.config.llm.default.model},"LLM provider initialized");let T=new Ut(E,a,this.logger.child({component:"embeddings"})),k=this.config.activeLearning?.enabled!==!1,_,v;k&&(_=new Wt({llm:E,memoryRepo:n,logger:this.logger.child({component:"active-learning"}),embeddingService:T,minMessageLength:this.config.activeLearning?.minMessageLength,minConfidence:this.config.activeLearning?.minConfidence,maxExtractionsPerMinute:this.config.activeLearning?.maxExtractionsPerMinute}),v=new Ht(n,this.logger.child({component:"memory-retriever"}),T),this.logger.info("Active learning & memory retriever initialized"));let M=new Re(this.logger.child({component:"sandbox"})),x=new Ae;x.register(new Le),x.register(new Me),x.register(new Ne(this.config.search?{provider:this.config.search.provider,apiKey:this.config.search.apiKey,baseUrl:this.config.search.baseUrl}:void 0)),x.register(new De(o)),x.register(new Oe(i)),x.register(new Ce),x.register(new Ue),x.register(new Pe(n,T)),x.register(new Fe(E,x,M,w)),x.register(new je(this.config.email?{imap:this.config.email.imap,smtp:this.config.email.smtp,auth:this.config.email.auth}:void 0)),x.register(new Be),x.register(new We),x.register(new Xe),x.register(new ze),x.register(new qe),x.register(new Ke(s)),x.register(new Ve(s,l,this.adapters)),x.register(new Ge(u)),x.register(new Ye(p));let A=new ft(e),C=new Pt(A,T,this.logger.child({component:"documents"}));x.register(new Ze(A,C,T));let H;if(this.config.calendar)try{let $=await It(this.config.calendar);H=new ye($),x.register(H),this.logger.info({provider:this.config.calendar.provider},"Calendar initialized")}catch($){this.logger.warn({err:$},"Calendar initialization failed, continuing without calendar")}if(this.calendarSkill=H,this.config.mcp?.servers?.length){let{MCPManager:$}=await Promise.resolve().then(()=>(Lt(),as));this.mcpManager=new $(this.logger.child({component:"mcp"})),await this.mcpManager.initialize(this.config.mcp);for(let z of this.mcpManager.getSkills())x.register(z);this.logger.info({mcpSkills:this.mcpManager.getSkills().length},"MCP skills registered")}if(this.config.codeSandbox?.enabled){let{CodeExecutionSkill:$}=await Promise.resolve().then(()=>(Lt(),as));x.register(new $({allowedLanguages:this.config.codeSandbox.allowedLanguages,maxTimeoutMs:this.config.codeSandbox.maxTimeoutMs})),this.logger.info("Code sandbox enabled")}this.logger.info({skills:x.getAll().map($=>$.metadata.name)},"Skills registered");let O;this.config.speech?.apiKey&&(O=new Ot(this.config.speech,this.logger.child({component:"speech"})),this.logger.info({provider:this.config.speech.provider},"Speech-to-text initialized"));let X=new Mt(t),B=gs.resolve(gs.dirname(this.config.storage.path),"inbox");this.pipeline=new Nt({llm:E,conversationManager:X,users:s,logger:this.logger.child({component:"pipeline"}),skillRegistry:x,skillSandbox:M,securityManager:w,memoryRepo:n,speechTranscriber:O,inboxPath:B,embeddingService:T,activeLearning:_,memoryRetriever:v}),this.reminderScheduler=new Dt(o,async($,z,Z)=>{let tt=this.adapters.get($);tt?await tt.sendMessage(z,Z):this.logger.warn({platform:$,chatId:z},"No adapter for reminder platform")},this.logger.child({component:"reminders"})),this.backgroundTaskRunner=new Ft(x,M,u,this.adapters,this.logger.child({component:"background-tasks"})),this.proactiveScheduler=new jt(p,x,M,E,this.adapters,this.logger.child({component:"proactive-scheduler"})),await this.initializeAdapters(),this.logger.info("Alfred initialized")}async initializeAdapters(){let{config:e}=this;if(e.telegram.enabled&&e.telegram.token){let{TelegramAdapter:t}=await Promise.resolve().then(()=>(_e(),be));this.adapters.set("telegram",new t(e.telegram.token)),this.logger.info("Telegram adapter registered")}if(e.discord?.enabled&&e.discord.token){let{DiscordAdapter:t}=await Promise.resolve().then(()=>(_e(),be));this.adapters.set("discord",new t(e.discord.token)),this.logger.info("Discord adapter registered")}if(e.whatsapp?.enabled){let{WhatsAppAdapter:t}=await Promise.resolve().then(()=>(_e(),be));this.adapters.set("whatsapp",new t(e.whatsapp.dataPath)),this.logger.info("WhatsApp adapter registered")}if(e.matrix?.enabled&&e.matrix.accessToken){let{MatrixAdapter:t}=await Promise.resolve().then(()=>(_e(),be));this.adapters.set("matrix",new t(e.matrix.homeserverUrl,e.matrix.accessToken,e.matrix.userId)),this.logger.info("Matrix adapter registered")}if(e.signal?.enabled&&e.signal.phoneNumber){let{SignalAdapter:t}=await Promise.resolve().then(()=>(_e(),be));this.adapters.set("signal",new t(e.signal.apiUrl,e.signal.phoneNumber)),this.logger.info("Signal adapter registered")}}async start(){this.logger.info("Starting Alfred...");for(let[e,t]of this.adapters)this.setupAdapterHandlers(e,t),await t.connect(),this.logger.info({platform:e},"Adapter connected");this.reminderScheduler?.start(),this.backgroundTaskRunner?.start(),this.proactiveScheduler?.start(),this.adapters.size===0&&this.logger.warn("No messaging adapters enabled. Configure at least one platform."),this.logger.info(`Alfred is running with ${this.adapters.size} adapter(s)`)}async startWithCLI(){this.adapters.clear();let{CLIAdapter:e}=await Promise.resolve().then(()=>(_e(),be)),t=new e;this.adapters.set("cli",t),this.setupAdapterHandlers("cli",t),t.on("disconnected",()=>{this.stop().then(()=>process.exit(0))}),await this.start()}async stop(){this.logger.info("Stopping Alfred..."),this.reminderScheduler?.stop(),this.backgroundTaskRunner?.stop(),this.proactiveScheduler?.stop(),this.mcpManager&&await this.mcpManager.shutdown();for(let[e,t]of this.adapters)try{await t.disconnect(),this.logger.info({platform:e},"Adapter disconnected")}catch(s){this.logger.error({platform:e,err:s},"Failed to disconnect adapter")}this.database.close(),this.logger.info("Alfred stopped")}setupAdapterHandlers(e,t){t.on("message",async s=>{try{let r,n="",o=d(async u=>{if(u!==n){n=u;try{r?await t.editMessage(s.chatId,r,u):r=await t.sendMessage(s.chatId,u)}catch(p){this.logger.debug({err:p,chatId:s.chatId},"Status message edit failed")}}},"onProgress"),i=await this.pipeline.process(s,o),a=this.formatter.format(i,s.platform),l=a.parseMode!=="text"?{parseMode:a.parseMode}:void 0;if(r)try{await t.editMessage(s.chatId,r,a.text,l)}catch(u){this.logger.debug({err:u,chatId:s.chatId},"Final response edit failed, sending as new message"),await t.sendMessage(s.chatId,a.text,l)}else await t.sendMessage(s.chatId,a.text,l)}catch(r){this.logger.error({platform:e,err:r,chatId:s.chatId},"Failed to handle message");try{await t.sendMessage(s.chatId,"Sorry, I encountered an error processing your message. Please try again.")}catch(n){this.logger.error({err:n},"Failed to send error message")}}}),t.on("error",s=>{this.logger.error({platform:e,err:s},"Adapter error")}),t.on("connected",()=>{this.logger.info({platform:e},"Adapter connected")}),t.on("disconnected",()=>{this.logger.warn({platform:e},"Adapter disconnected")})}loadSecurityRules(){let e=gs.resolve(this.config.security.rulesPath),t=[];if(!fs.existsSync(e))return this.logger.warn({rulesPath:e},"Security rules directory not found, using default deny"),t;if(!fs.statSync(e).isDirectory())return this.logger.warn({rulesPath:e},"Security rules path is not a directory"),t;let r=fs.readdirSync(e).filter(n=>n.endsWith(".yml")||n.endsWith(".yaml"));for(let n of r)try{let o=gs.join(e,n),i=fs.readFileSync(o,"utf-8"),a=ea.load(i);a?.rules&&Array.isArray(a.rules)&&(t.push(...a.rules),this.logger.info({file:n,count:a.rules.length},"Loaded security rules"))}catch(o){this.logger.error({err:o,file:n},"Failed to load security rules file")}return t}}});var ao=f(()=>{"use strict"});var yr=f(()=>{"use strict";io();sr();tr();rr();nr();or();ir();cr();lr();ar();pr();hr();mr();ao();ur()});var co={};G(co,{startCommand:()=>ta});async function ta(){let c=new q,e;try{e=c.loadConfig()}catch(o){console.error("Failed to load configuration:",o.message),process.exit(1)}let t=ot("cli",e.logger.level);t.info({name:e.name},"Configuration loaded");let s=new Se(e),r=!1,n=d(async o=>{if(!r){r=!0,t.info({signal:o},"Received shutdown signal");try{await s.stop(),t.info("Graceful shutdown complete"),process.exit(0)}catch(i){t.error({error:i},"Error during shutdown"),process.exit(1)}}},"shutdown");process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM")),process.on("uncaughtException",o=>{t.fatal({error:o},"Uncaught exception"),n("uncaughtException")}),process.on("unhandledRejection",o=>{t.fatal({reason:o},"Unhandled rejection"),n("unhandledRejection")});try{await s.initialize(),await s.start(),t.info("Alfred is ready")}catch(o){t.fatal({error:o},"Failed to start Alfred"),process.exit(1)}}var lo=f(()=>{"use strict";ue();Ls();yr();d(ta,"startCommand")});var uo={};G(uo,{chatCommand:()=>sa});async function sa(c){let e=new q,t;try{t=e.loadConfig()}catch(r){console.error("Failed to load configuration:",r.message),process.exit(1)}if(t.logger.level="warn",c.model&&(t.llm.default.model=c.model),c.tier){let r=t.llm[c.tier];r?t.llm.default=r:(console.error(`Unknown tier: ${c.tier}. Available tiers: default, strong, fast, embeddings, local`),process.exit(1))}let s=new Se(t);try{await s.initialize(),await s.startWithCLI()}catch(r){console.error("Failed to start chat:",r.message),process.exit(1)}}var mo=f(()=>{"use strict";ue();yr();d(sa,"chatCommand")});var ho={};G(ho,{setupCommand:()=>da});import{createInterface as ra}from"node:readline/promises";import{stdin as na,stdout as oa}from"node:process";import K from"node:fs";import re from"node:path";import Er from"js-yaml";function U(c){return`${ys}${c}${L}`}function ca(c){return`${ee}${c}${L}`}function ke(c){return`${ws}${c}${L}`}function po(c){return`${ia}${c}${L}`}function I(c){return`${et}${c}${L}`}function S(c){return`${le}${c}${L}`}function ve(c){return c.length<=4?"****":"*".repeat(c.length-4)+c.slice(-4)}function la(c){let e={},t={},s=!1,r=!1,n=30,o=re.join(c,"config","default.yml");if(K.existsSync(o))try{let l=Er.load(K.readFileSync(o,"utf-8"));l&&typeof l=="object"&&Object.assign(e,l)}catch{}let i=re.join(c,".env");if(K.existsSync(i))try{let l=K.readFileSync(i,"utf-8").split(`
495
- `);for(let u of l){let p=u.trim();if(!p||p.startsWith("#"))continue;let m=p.indexOf("=");m>0&&(t[p.slice(0,m)]=p.slice(m+1))}}catch{}let a=re.join(c,"config","rules","default-rules.yml");if(K.existsSync(a))try{let l=Er.load(K.readFileSync(a,"utf-8"));if(l?.rules){s=l.rules.some(m=>m.id==="allow-owner-admin"&&m.effect==="allow"),l.rules.find(m=>m.id==="allow-write-for-dm"||m.id==="allow-write-all")?.id==="allow-write-all"&&(r=!0);let p=l.rules.find(m=>m.id==="rate-limit-write");p?.rateLimit?.maxInvocations&&(n=p.rateLimit.maxInvocations)}}catch{}return{config:e,env:t,shellEnabled:s,writeInGroups:r,rateLimit:n}}async function da(){let c=ra({input:na,output:oa}),e=process.cwd(),t=la(e),s=Object.keys(t.config).length>0;try{ua(),console.log(s?`${ws}Existing configuration found \u2014 press Enter to keep current values.${L}
496
- ${le}Only change what you need to update.${L}
497
- `:`${ws}Welcome to the Alfred setup wizard!${L}
498
- ${le}This will walk you through configuring your AI assistant.${L}
499
- ${le}Press Enter to accept defaults shown in [brackets].${L}
500
- `);let r=await F(c,"What should your bot be called?",t.config.name??"Alfred"),n=t.config.llm?.provider?Xt.findIndex(y=>y.name===t.config.llm?.provider):-1,o=n>=0?n+1:1;console.log(`
501
- ${I("Which LLM provider would you like to use?")}`);for(let y=0;y<Xt.length;y++){let R=y===n?` ${S("(current)")}`:"";console.log(` ${ke(String(y+1)+")")} ${Xt[y].label}${R}`)}let i=await wr(c,"> ",1,Xt.length,o),a=Xt[i-1];console.log(` ${U(">")} Selected: ${I(a.label)}`);let l="",u=t.env[a.envKeyName]??"";a.needsApiKey&&(console.log(""),u?l=await F(c,`${a.name.charAt(0).toUpperCase()+a.name.slice(1)} API key`,u):l=await ce(c,`Enter your ${a.name.charAt(0).toUpperCase()+a.name.slice(1)} API key`),console.log(` ${U(">")} API key set: ${S(ve(l))}`));let p=a.baseUrl??"";if(["ollama","openwebui","openai","openrouter"].includes(a.name)){let R=(t.config.llm?.baseUrl??t.env.ALFRED_LLM_BASE_URL??"")||a.baseUrl||"";if(R){let j={ollama:"Ollama URL (use a remote address if Ollama runs on another machine)",openwebui:"OpenWebUI URL",openai:"OpenAI-compatible API URL (leave default for official API)",openrouter:"OpenRouter API URL"};console.log(""),p=await F(c,j[a.name]??"API Base URL",R.replace(/\/+$/,"")),p=p.replace(/\/+$/,""),console.log(` ${U(">")} URL: ${S(p)}`)}}let h=t.config.llm?.model??a.defaultModel;console.log("");let w=await F(c,"Which model?",h),E=["brave","tavily","duckduckgo","searxng"],T=t.config.search?.provider??t.env.ALFRED_SEARCH_PROVIDER??"",k=E.indexOf(T),_=k>=0?k+1:0;console.log(`
502
- ${I("Web Search provider (for searching the internet):")}`);let v=["Brave Search \u2014 recommended, free tier (2,000/month)","Tavily \u2014 built for AI agents, free tier (1,000/month)","DuckDuckGo \u2014 free, no API key needed","SearXNG \u2014 self-hosted, no API key needed"],M=d(y=>k===y?` ${S("(current)")}`:"","mark");console.log(` ${ke("0)")} None (disable web search)${k===-1&&T===""?` ${S("(current)")}`:""}`);for(let y=0;y<v.length;y++)console.log(` ${ke(String(y+1)+")")} ${v[y]}${M(y)}`);let x=await wr(c,"> ",0,E.length,_),A,C="",H="";if(x>=1&&x<=E.length&&(A=E[x-1]),A==="brave"){let y=t.env.ALFRED_SEARCH_API_KEY??"";y?C=await F(c," Brave Search API key",y):(console.log(` ${S("Get your free API key at: https://brave.com/search/api/")}`),C=await ce(c," Brave Search API key")),console.log(` ${U(">")} Brave Search: ${S(ve(C))}`)}else if(A==="tavily"){let y=t.env.ALFRED_SEARCH_API_KEY??"";y?C=await F(c," Tavily API key",y):(console.log(` ${S("Get your free API key at: https://tavily.com/")}`),C=await ce(c," Tavily API key")),console.log(` ${U(">")} Tavily: ${S(ve(C))}`)}else if(A==="duckduckgo")console.log(` ${U(">")} DuckDuckGo: ${S("no API key needed")}`);else if(A==="searxng"){let y=t.config.search?.baseUrl??t.env.ALFRED_SEARCH_BASE_URL??"http://localhost:8080";H=await F(c," SearXNG URL",y),H=H.replace(/\/+$/,""),console.log(` ${U(">")} SearXNG: ${S(H)}`)}else console.log(` ${S("Web search disabled \u2014 you can configure it later.")}`);let O=[];for(let y=0;y<Qe.length;y++){let R=Qe[y];t.config[R.configKey]?.enabled&&O.push(y+1)}let X=O.length>0?O.join(","):"";console.log(`
503
- ${I("Which messaging platforms do you want to enable?")}`),console.log(`${S("(Enter comma-separated numbers, e.g. 1,3)")}`);for(let y=0;y<Qe.length;y++){let R=O.includes(y+1)?` ${S("(enabled)")}`:"";console.log(` ${ke(String(y+1)+")")} ${Qe[y].label}${R}`)}console.log(` ${ke("0)")} None (configure later)`);let B=(await c.question(`${ee}> ${L}${X?S(`[${X}] `):""}`)).trim(),$=[],z=B||X;if(z&&z!=="0"){let y=z.split(",").map(R=>parseInt(R.trim(),10));for(let R of y)if(R>=1&&R<=Qe.length){let j=Qe[R-1];$.includes(j)||$.push(j)}}$.length>0?console.log(` ${U(">")} Enabling: ${$.map(y=>I(y.label)).join(", ")}`):console.log(` ${S("No platforms selected \u2014 you can configure them later.")}`);let Z={},tt={};for(let y of $){if(y.credentials.length===0){y.name==="whatsapp"&&console.log(`
496
+ `),this.prompt(),r}async editMessage(e,t,s,r){gr.clearLine(process.stdout,0),gr.cursorTo(process.stdout,0),process.stdout.write(`Alfred: ${s}`)}async deleteMessage(e,t){}prompt(){this.rl?.prompt()}}});var be={};G(be,{CLIAdapter:()=>hs,DiscordAdapter:()=>ds,MatrixAdapter:()=>us,MessagingAdapter:()=>X,SignalAdapter:()=>ps,TelegramAdapter:()=>cs,WhatsAppAdapter:()=>ms});var _e=f(()=>{"use strict";ae();eo();to();so();ro();no();oo()});import fs from"node:fs";import gs from"node:path";import ea from"js-yaml";var Se,io=f(()=>{"use strict";Ls();Ds();Hs();ss();Lt();tr();sr();rr();nr();or();ir();ar();cr();lr();pr();hr();Se=class{static{d(this,"Alfred")}config;logger;database;pipeline;reminderScheduler;backgroundTaskRunner;proactiveScheduler;adapters=new Map;formatter=new Ct;mcpManager;calendarSkill;constructor(e){this.config=e,this.logger=ot("alfred",e.logger.level)}async initialize(){this.logger.info("Initializing Alfred..."),this.database=new me(this.config.storage.path);let e=this.database.getDb(),t=new it(e),s=new at(e),r=new pe(e),n=new ct(e),o=new lt(e),i=new dt(e),a=new ut(e),l=new mt(e),u=new pt(e),p=new ht(e);this.logger.info("Storage initialized");let m=new St,h=this.loadSecurityRules();m.loadRules(h);let w=new kt(m,r,this.logger.child({component:"security"}));this.logger.info({ruleCount:h.length},"Security engine initialized");let E=Ws(this.config.llm);await E.initialize(),this.logger.info({provider:this.config.llm.default.provider,model:this.config.llm.default.model},"LLM provider initialized");let T=new Ut(E,a,this.logger.child({component:"embeddings"})),k=this.config.activeLearning?.enabled!==!1,v,b;k&&(v=new Wt({llm:E,memoryRepo:n,logger:this.logger.child({component:"active-learning"}),embeddingService:T,minMessageLength:this.config.activeLearning?.minMessageLength,minConfidence:this.config.activeLearning?.minConfidence,maxExtractionsPerMinute:this.config.activeLearning?.maxExtractionsPerMinute}),b=new Ht(n,this.logger.child({component:"memory-retriever"}),T),this.logger.info("Active learning & memory retriever initialized"));let A=new Re(this.logger.child({component:"sandbox"})),x=new Ae;x.register(new Le),x.register(new Me),x.register(new Ne(this.config.search?{provider:this.config.search.provider,apiKey:this.config.search.apiKey,baseUrl:this.config.search.baseUrl}:void 0)),x.register(new De(o)),x.register(new Oe(i)),x.register(new Ce),x.register(new Ue),x.register(new Pe(n,T)),x.register(new Fe(E,x,A,w)),x.register(new je(this.config.email?{imap:this.config.email.imap,smtp:this.config.email.smtp,auth:this.config.email.auth}:void 0)),x.register(new Be),x.register(new We),x.register(new Xe),x.register(new ze),x.register(new qe),x.register(new Ke(s)),x.register(new Ve(s,l,this.adapters)),x.register(new Ge(u)),x.register(new Ye(p));let L=new ft(e),P=new Pt(L,T,this.logger.child({component:"documents"}));x.register(new Ze(L,P,T));let F;if(this.config.calendar)try{let $=await It(this.config.calendar);F=new ye($),x.register(F),this.logger.info({provider:this.config.calendar.provider},"Calendar initialized")}catch($){this.logger.warn({err:$},"Calendar initialization failed, continuing without calendar")}if(this.calendarSkill=F,this.config.mcp?.servers?.length){let{MCPManager:$}=await Promise.resolve().then(()=>(Lt(),as));this.mcpManager=new $(this.logger.child({component:"mcp"})),await this.mcpManager.initialize(this.config.mcp);for(let O of this.mcpManager.getSkills())x.register(O);this.logger.info({mcpSkills:this.mcpManager.getSkills().length},"MCP skills registered")}if(this.config.codeSandbox?.enabled){let{CodeExecutionSkill:$}=await Promise.resolve().then(()=>(Lt(),as));x.register(new $({allowedLanguages:this.config.codeSandbox.allowedLanguages,maxTimeoutMs:this.config.codeSandbox.maxTimeoutMs})),this.logger.info("Code sandbox enabled")}this.logger.info({skills:x.getAll().map($=>$.metadata.name)},"Skills registered");let ee;this.config.speech?.apiKey&&(ee=new Ot(this.config.speech,this.logger.child({component:"speech"})),this.logger.info({provider:this.config.speech.provider},"Speech-to-text initialized"));let C=new Mt(t),K=gs.resolve(gs.dirname(this.config.storage.path),"inbox");this.pipeline=new Nt({llm:E,conversationManager:C,users:s,logger:this.logger.child({component:"pipeline"}),skillRegistry:x,skillSandbox:A,securityManager:w,memoryRepo:n,speechTranscriber:ee,inboxPath:K,embeddingService:T,activeLearning:v,memoryRetriever:b}),this.reminderScheduler=new Dt(o,async($,O,H)=>{let tt=this.adapters.get($);tt?await tt.sendMessage(O,H):this.logger.warn({platform:$,chatId:O},"No adapter for reminder platform")},this.logger.child({component:"reminders"})),this.backgroundTaskRunner=new Ft(x,A,u,this.adapters,this.logger.child({component:"background-tasks"})),this.proactiveScheduler=new jt(p,x,A,E,this.adapters,this.logger.child({component:"proactive-scheduler"})),await this.initializeAdapters(),this.logger.info("Alfred initialized")}async initializeAdapters(){let{config:e}=this;if(e.telegram.enabled&&e.telegram.token){let{TelegramAdapter:t}=await Promise.resolve().then(()=>(_e(),be));this.adapters.set("telegram",new t(e.telegram.token)),this.logger.info("Telegram adapter registered")}if(e.discord?.enabled&&e.discord.token){let{DiscordAdapter:t}=await Promise.resolve().then(()=>(_e(),be));this.adapters.set("discord",new t(e.discord.token)),this.logger.info("Discord adapter registered")}if(e.whatsapp?.enabled){let{WhatsAppAdapter:t}=await Promise.resolve().then(()=>(_e(),be));this.adapters.set("whatsapp",new t(e.whatsapp.dataPath)),this.logger.info("WhatsApp adapter registered")}if(e.matrix?.enabled&&e.matrix.accessToken){let{MatrixAdapter:t}=await Promise.resolve().then(()=>(_e(),be));this.adapters.set("matrix",new t(e.matrix.homeserverUrl,e.matrix.accessToken,e.matrix.userId)),this.logger.info("Matrix adapter registered")}if(e.signal?.enabled&&e.signal.phoneNumber){let{SignalAdapter:t}=await Promise.resolve().then(()=>(_e(),be));this.adapters.set("signal",new t(e.signal.apiUrl,e.signal.phoneNumber)),this.logger.info("Signal adapter registered")}}async start(){this.logger.info("Starting Alfred...");for(let[e,t]of this.adapters)this.setupAdapterHandlers(e,t),await t.connect(),this.logger.info({platform:e},"Adapter connected");this.reminderScheduler?.start(),this.backgroundTaskRunner?.start(),this.proactiveScheduler?.start(),this.adapters.size===0&&this.logger.warn("No messaging adapters enabled. Configure at least one platform."),this.logger.info(`Alfred is running with ${this.adapters.size} adapter(s)`)}async startWithCLI(){this.adapters.clear();let{CLIAdapter:e}=await Promise.resolve().then(()=>(_e(),be)),t=new e;this.adapters.set("cli",t),this.setupAdapterHandlers("cli",t),t.on("disconnected",()=>{this.stop().then(()=>process.exit(0))}),await this.start()}async stop(){this.logger.info("Stopping Alfred..."),this.reminderScheduler?.stop(),this.backgroundTaskRunner?.stop(),this.proactiveScheduler?.stop(),this.mcpManager&&await this.mcpManager.shutdown();for(let[e,t]of this.adapters)try{await t.disconnect(),this.logger.info({platform:e},"Adapter disconnected")}catch(s){this.logger.error({platform:e,err:s},"Failed to disconnect adapter")}this.database.close(),this.logger.info("Alfred stopped")}setupAdapterHandlers(e,t){t.on("message",async s=>{try{let r,n="",o=d(async u=>{if(u!==n){n=u;try{r?await t.editMessage(s.chatId,r,u):r=await t.sendMessage(s.chatId,u)}catch(p){this.logger.debug({err:p,chatId:s.chatId},"Status message edit failed")}}},"onProgress"),i=await this.pipeline.process(s,o),a=this.formatter.format(i,s.platform),l=a.parseMode!=="text"?{parseMode:a.parseMode}:void 0;if(r)try{await t.editMessage(s.chatId,r,a.text,l)}catch(u){this.logger.debug({err:u,chatId:s.chatId},"Final response edit failed, sending as new message"),await t.sendMessage(s.chatId,a.text,l)}else await t.sendMessage(s.chatId,a.text,l)}catch(r){this.logger.error({platform:e,err:r,chatId:s.chatId},"Failed to handle message");try{await t.sendMessage(s.chatId,"Sorry, I encountered an error processing your message. Please try again.")}catch(n){this.logger.error({err:n},"Failed to send error message")}}}),t.on("error",s=>{this.logger.error({platform:e,err:s},"Adapter error")}),t.on("connected",()=>{this.logger.info({platform:e},"Adapter connected")}),t.on("disconnected",()=>{this.logger.warn({platform:e},"Adapter disconnected")})}loadSecurityRules(){let e=gs.resolve(this.config.security.rulesPath),t=[];if(!fs.existsSync(e))return this.logger.warn({rulesPath:e},"Security rules directory not found, using default deny"),t;if(!fs.statSync(e).isDirectory())return this.logger.warn({rulesPath:e},"Security rules path is not a directory"),t;let r=fs.readdirSync(e).filter(n=>n.endsWith(".yml")||n.endsWith(".yaml"));for(let n of r)try{let o=gs.join(e,n),i=fs.readFileSync(o,"utf-8"),a=ea.load(i);a?.rules&&Array.isArray(a.rules)&&(t.push(...a.rules),this.logger.info({file:n,count:a.rules.length},"Loaded security rules"))}catch(o){this.logger.error({err:o,file:n},"Failed to load security rules file")}return t}}});var ao=f(()=>{"use strict"});var yr=f(()=>{"use strict";io();sr();tr();rr();nr();or();ir();cr();lr();ar();pr();hr();mr();ao();ur()});var co={};G(co,{startCommand:()=>ta});async function ta(){let c=new z,e;try{e=c.loadConfig()}catch(o){console.error("Failed to load configuration:",o.message),process.exit(1)}let t=ot("cli",e.logger.level);t.info({name:e.name},"Configuration loaded");let s=new Se(e),r=!1,n=d(async o=>{if(!r){r=!0,t.info({signal:o},"Received shutdown signal");try{await s.stop(),t.info("Graceful shutdown complete"),process.exit(0)}catch(i){t.error({error:i},"Error during shutdown"),process.exit(1)}}},"shutdown");process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM")),process.on("uncaughtException",o=>{t.fatal({error:o},"Uncaught exception"),n("uncaughtException")}),process.on("unhandledRejection",o=>{t.fatal({reason:o},"Unhandled rejection"),n("unhandledRejection")});try{await s.initialize(),await s.start(),t.info("Alfred is ready")}catch(o){t.fatal({error:o},"Failed to start Alfred"),process.exit(1)}}var lo=f(()=>{"use strict";ue();Ls();yr();d(ta,"startCommand")});var uo={};G(uo,{chatCommand:()=>sa});async function sa(c){let e=new z,t;try{t=e.loadConfig()}catch(r){console.error("Failed to load configuration:",r.message),process.exit(1)}if(t.logger.level="warn",c.model&&(t.llm.default.model=c.model),c.tier){let r=t.llm[c.tier];r?t.llm.default=r:(console.error(`Unknown tier: ${c.tier}. Available tiers: default, strong, fast, embeddings, local`),process.exit(1))}let s=new Se(t);try{await s.initialize(),await s.startWithCLI()}catch(r){console.error("Failed to start chat:",r.message),process.exit(1)}}var mo=f(()=>{"use strict";ue();yr();d(sa,"chatCommand")});var ho={};G(ho,{setupCommand:()=>da});import{createInterface as ra}from"node:readline/promises";import{stdin as na,stdout as oa}from"node:process";import q from"node:fs";import re from"node:path";import Er from"js-yaml";function U(c){return`${ys}${c}${M}`}function ca(c){return`${Q}${c}${M}`}function ke(c){return`${ws}${c}${M}`}function po(c){return`${ia}${c}${M}`}function I(c){return`${et}${c}${M}`}function S(c){return`${le}${c}${M}`}function ve(c){return c.length<=4?"****":"*".repeat(c.length-4)+c.slice(-4)}function la(c){let e={},t={},s=!1,r=!1,n=30,o=re.join(c,"config","default.yml");if(q.existsSync(o))try{let l=Er.load(q.readFileSync(o,"utf-8"));l&&typeof l=="object"&&Object.assign(e,l)}catch{}let i=re.join(c,".env");if(q.existsSync(i))try{let l=q.readFileSync(i,"utf-8").split(`
497
+ `);for(let u of l){let p=u.trim();if(!p||p.startsWith("#"))continue;let m=p.indexOf("=");m>0&&(t[p.slice(0,m)]=p.slice(m+1))}}catch{}let a=re.join(c,"config","rules","default-rules.yml");if(q.existsSync(a))try{let l=Er.load(q.readFileSync(a,"utf-8"));if(l?.rules){s=l.rules.some(m=>m.id==="allow-owner-admin"&&m.effect==="allow"),l.rules.find(m=>m.id==="allow-write-for-dm"||m.id==="allow-write-all")?.id==="allow-write-all"&&(r=!0);let p=l.rules.find(m=>m.id==="rate-limit-write");p?.rateLimit?.maxInvocations&&(n=p.rateLimit.maxInvocations)}}catch{}return{config:e,env:t,shellEnabled:s,writeInGroups:r,rateLimit:n}}async function da(){let c=ra({input:na,output:oa}),e=process.cwd(),t=la(e),s=Object.keys(t.config).length>0;try{ua(),console.log(s?`${ws}Existing configuration found \u2014 press Enter to keep current values.${M}
498
+ ${le}Only change what you need to update.${M}
499
+ `:`${ws}Welcome to the Alfred setup wizard!${M}
500
+ ${le}This will walk you through configuring your AI assistant.${M}
501
+ ${le}Press Enter to accept defaults shown in [brackets].${M}
502
+ `);let r=await B(c,"What should your bot be called?",t.config.name??"Alfred"),n=t.config.llm?.provider?Xt.findIndex(y=>y.name===t.config.llm?.provider):-1,o=n>=0?n+1:1;console.log(`
503
+ ${I("Which LLM provider would you like to use?")}`);for(let y=0;y<Xt.length;y++){let R=y===n?` ${S("(current)")}`:"";console.log(` ${ke(String(y+1)+")")} ${Xt[y].label}${R}`)}let i=await wr(c,"> ",1,Xt.length,o),a=Xt[i-1];console.log(` ${U(">")} Selected: ${I(a.label)}`);let l="",u=t.env[a.envKeyName]??"";a.needsApiKey&&(console.log(""),u?l=await B(c,`${a.name.charAt(0).toUpperCase()+a.name.slice(1)} API key`,u):l=await ce(c,`Enter your ${a.name.charAt(0).toUpperCase()+a.name.slice(1)} API key`),console.log(` ${U(">")} API key set: ${S(ve(l))}`));let p=a.baseUrl??"";if(["ollama","openwebui","openai","openrouter"].includes(a.name)){let R=(t.config.llm?.baseUrl??t.env.ALFRED_LLM_BASE_URL??"")||a.baseUrl||"";if(R){let W={ollama:"Ollama URL (use a remote address if Ollama runs on another machine)",openwebui:"OpenWebUI URL",openai:"OpenAI-compatible API URL (leave default for official API)",openrouter:"OpenRouter API URL"};console.log(""),p=await B(c,W[a.name]??"API Base URL",R.replace(/\/+$/,"")),p=p.replace(/\/+$/,""),console.log(` ${U(">")} URL: ${S(p)}`)}}let h=t.config.llm?.model??a.defaultModel;console.log("");let w=await B(c,"Which model?",h),E=["brave","tavily","duckduckgo","searxng"],T=t.config.search?.provider??t.env.ALFRED_SEARCH_PROVIDER??"",k=E.indexOf(T),v=k>=0?k+1:0;console.log(`
504
+ ${I("Web Search provider (for searching the internet):")}`);let b=["Brave Search \u2014 recommended, free tier (2,000/month)","Tavily \u2014 built for AI agents, free tier (1,000/month)","DuckDuckGo \u2014 free, no API key needed","SearXNG \u2014 self-hosted, no API key needed"],A=d(y=>k===y?` ${S("(current)")}`:"","mark");console.log(` ${ke("0)")} None (disable web search)${k===-1&&T===""?` ${S("(current)")}`:""}`);for(let y=0;y<b.length;y++)console.log(` ${ke(String(y+1)+")")} ${b[y]}${A(y)}`);let x=await wr(c,"> ",0,E.length,v),L,P="",F="";if(x>=1&&x<=E.length&&(L=E[x-1]),L==="brave"){let y=t.env.ALFRED_SEARCH_API_KEY??"";y?P=await B(c," Brave Search API key",y):(console.log(` ${S("Get your free API key at: https://brave.com/search/api/")}`),P=await ce(c," Brave Search API key")),console.log(` ${U(">")} Brave Search: ${S(ve(P))}`)}else if(L==="tavily"){let y=t.env.ALFRED_SEARCH_API_KEY??"";y?P=await B(c," Tavily API key",y):(console.log(` ${S("Get your free API key at: https://tavily.com/")}`),P=await ce(c," Tavily API key")),console.log(` ${U(">")} Tavily: ${S(ve(P))}`)}else if(L==="duckduckgo")console.log(` ${U(">")} DuckDuckGo: ${S("no API key needed")}`);else if(L==="searxng"){let y=t.config.search?.baseUrl??t.env.ALFRED_SEARCH_BASE_URL??"http://localhost:8080";F=await B(c," SearXNG URL",y),F=F.replace(/\/+$/,""),console.log(` ${U(">")} SearXNG: ${S(F)}`)}else console.log(` ${S("Web search disabled \u2014 you can configure it later.")}`);let ee=[];for(let y=0;y<Qe.length;y++){let R=Qe[y];t.config[R.configKey]?.enabled&&ee.push(y+1)}let C=ee.length>0?ee.join(","):"";console.log(`
505
+ ${I("Which messaging platforms do you want to enable?")}`),console.log(`${S("(Enter comma-separated numbers, e.g. 1,3)")}`);for(let y=0;y<Qe.length;y++){let R=ee.includes(y+1)?` ${S("(enabled)")}`:"";console.log(` ${ke(String(y+1)+")")} ${Qe[y].label}${R}`)}console.log(` ${ke("0)")} None (configure later)`);let K=(await c.question(`${Q}> ${M}${C?S(`[${C}] `):""}`)).trim(),$=[],O=K||C;if(O&&O!=="0"){let y=O.split(",").map(R=>parseInt(R.trim(),10));for(let R of y)if(R>=1&&R<=Qe.length){let W=Qe[R-1];$.includes(W)||$.push(W)}}$.length>0?console.log(` ${U(">")} Enabling: ${$.map(y=>I(y.label)).join(", ")}`):console.log(` ${S("No platforms selected \u2014 you can configure them later.")}`);let H={},tt={};for(let y of $){if(y.credentials.length===0){y.name==="whatsapp"&&console.log(`
504
506
  ${ca("i")} WhatsApp: a QR code will be displayed on first start.`);continue}console.log(`
505
- ${I(y.label+" configuration:")}`);let R={};for(let j of y.credentials){let xe=t.env[j.envKey]??"",Q;xe?Q=await F(c,` ${j.prompt}`,xe):j.defaultValue?Q=await F(c,` ${j.prompt}`,j.defaultValue):j.required?Q=await ce(c,` ${j.prompt}`):(Q=(await c.question(` ${j.prompt}: ${ee}`)).trim(),process.stdout.write(L)),R[j.configField]=Q,tt[j.envKey]=Q,j.configField==="token"||j.configField==="accessToken"?console.log(` ${U(">")} Set: ${S(ve(Q))}`):console.log(` ${U(">")} Set: ${S(Q)}`)}Z[y.configKey]=R}let _r=t.config.email?.auth?.user??t.env.ALFRED_EMAIL_USER??"",Sr=!!_r,$o=Sr?"Y/n":"y/N";console.log(`
506
- ${I("Email access (read & send emails via IMAP/SMTP)?")}`),console.log(`${S("Works with Gmail, Outlook, or any IMAP/SMTP provider.")}`);let Ts=(await c.question(`${ee}> ${L}${S(`[${$o}] `)}`)).trim().toLowerCase(),qt=Ts===""?Sr:Ts==="y"||Ts==="yes",ne="",Kt="",Vt="",bs=993,kr="",_s=587;if(qt){console.log(""),ne=await F(c," Email address",_r||""),ne||(ne=await ce(c," Email address"));let y=t.env.ALFRED_EMAIL_PASS??"";y?Kt=await F(c," Password / App password",y):(console.log(` ${S("For Gmail: use an App Password (not your regular password)")}`),console.log(` ${S(" \u2192 Google Account \u2192 Security \u2192 2-Step \u2192 App passwords")}`),Kt=await ce(c," Password / App password"));let R=ne.split("@")[1]?.toLowerCase()??"",xe={"gmail.com":{imap:"imap.gmail.com",smtp:"smtp.gmail.com"},"googlemail.com":{imap:"imap.gmail.com",smtp:"smtp.gmail.com"},"outlook.com":{imap:"outlook.office365.com",smtp:"smtp.office365.com"},"hotmail.com":{imap:"outlook.office365.com",smtp:"smtp.office365.com"},"live.com":{imap:"outlook.office365.com",smtp:"smtp.office365.com"},"yahoo.com":{imap:"imap.mail.yahoo.com",smtp:"smtp.mail.yahoo.com"},"icloud.com":{imap:"imap.mail.me.com",smtp:"smtp.mail.me.com"},"me.com":{imap:"imap.mail.me.com",smtp:"smtp.mail.me.com"},"gmx.de":{imap:"imap.gmx.net",smtp:"mail.gmx.net"},"gmx.net":{imap:"imap.gmx.net",smtp:"mail.gmx.net"},"web.de":{imap:"imap.web.de",smtp:"smtp.web.de"},"posteo.de":{imap:"posteo.de",smtp:"posteo.de"},"mailbox.org":{imap:"imap.mailbox.org",smtp:"smtp.mailbox.org"},"protonmail.com":{imap:"127.0.0.1",smtp:"127.0.0.1"},"proton.me":{imap:"127.0.0.1",smtp:"127.0.0.1"}}[R],Q=t.config.email?.imap?.host??xe?.imap??`imap.${R}`,Fo=t.config.email?.smtp?.host??xe?.smtp??`smtp.${R}`,jo=t.config.email?.imap?.port??993,Bo=t.config.email?.smtp?.port??587;xe&&console.log(` ${U(">")} Detected ${R} \u2014 using preset server settings`),Vt=await F(c," IMAP server",Q);let Wo=await F(c," IMAP port",String(jo));bs=parseInt(Wo,10)||993,kr=await F(c," SMTP server",Fo);let Ho=await F(c," SMTP port",String(Bo));_s=parseInt(Ho,10)||587,console.log(` ${U(">")} Email: ${S(ne)} via ${S(Vt)}`)}else console.log(` ${S("Email disabled \u2014 you can configure it later.")}`);let Gt=["openai","groq"],Io=t.config.speech?.provider??t.env.ALFRED_SPEECH_PROVIDER??"",Yt=Gt.indexOf(Io),Ao=Yt>=0?Yt+1:0;console.log(`
507
- ${I("Voice message transcription (Speech-to-Text via Whisper)?")}`),console.log(`${S("Transcribes voice messages from Telegram, Discord, etc.")}`);let vr=["OpenAI Whisper \u2014 best quality","Groq Whisper \u2014 fast & free"];console.log(` ${ke("0)")} None (disable voice transcription)${Yt===-1?` ${S("(current)")}`:""}`);for(let y=0;y<vr.length;y++){let R=Yt===y?` ${S("(current)")}`:"";console.log(` ${ke(String(y+1)+")")} ${vr[y]}${R}`)}let Ss=await wr(c,"> ",0,Gt.length,Ao),te,oe="",st="";if(Ss>=1&&Ss<=Gt.length&&(te=Gt[Ss-1]),te==="openai"){let y=t.env.ALFRED_SPEECH_API_KEY??"";y?oe=await F(c," OpenAI API key (for Whisper)",y):(console.log(` ${S("Uses your OpenAI API key for Whisper transcription.")}`),oe=await ce(c," OpenAI API key")),console.log(` ${U(">")} OpenAI Whisper: ${S(ve(oe))}`)}else if(te==="groq"){let y=t.env.ALFRED_SPEECH_API_KEY??"";y?oe=await F(c," Groq API key",y):(console.log(` ${S("Get your free API key at: https://console.groq.com/")}`),oe=await ce(c," Groq API key"));let R=t.env.ALFRED_SPEECH_BASE_URL??"";R&&(st=await F(c," Groq API URL",R)),console.log(` ${U(">")} Groq Whisper: ${S(ve(oe))}`)}else console.log(` ${S("Voice transcription disabled \u2014 you can configure it later.")}`);console.log(`
508
- ${I("Security configuration:")}`);let xr=t.config.security?.ownerUserId??t.env.ALFRED_OWNER_USER_ID??"",V;if(xr)V=await F(c,"Owner user ID (for elevated permissions)",xr);else{let y=(await c.question(`${et}Owner user ID${L} ${S("(optional, for elevated permissions)")}: ${ee}`)).trim();process.stdout.write(L),V=y}let rt=!1;if(V){let y=t.shellEnabled?"Y/n":"y/N";console.log(""),console.log(` ${I("Enable shell access (admin commands) for the owner?")}`),console.log(` ${S("Allows Alfred to execute shell commands. Only for the owner.")}`);let R=(await c.question(` ${ee}> ${L}${S(`[${y}] `)}`)).trim().toLowerCase();R===""?rt=t.shellEnabled:rt=R==="y"||R==="yes",console.log(rt?` ${U(">")} Shell access ${I("enabled")} for owner ${S(V)}`:` ${S("Shell access disabled.")}`)}let Ro=t.writeInGroups?"Y/n":"y/N";console.log(""),console.log(` ${I("Allow write actions (notes, reminders, memory) in group chats?")}`),console.log(` ${S("By default, write actions are only allowed in DMs.")}`);let ks=(await c.question(` ${ee}> ${L}${S(`[${Ro}] `)}`)).trim().toLowerCase(),nt;ks===""?nt=t.writeInGroups:nt=ks==="y"||ks==="yes",console.log(nt?` ${U(">")} Write actions ${I("enabled")} in groups`:` ${S("Write actions only in DMs (default).")}`);let Lo=t.rateLimit??30;console.log("");let Mo=await F(c," Rate limit (max write actions per hour per user)",String(Lo)),Jt=Math.max(1,parseInt(Mo,10)||30);console.log(` ${U(">")} Rate limit: ${I(String(Jt))} per hour`),console.log(`
509
- ${I("Writing configuration files...")}`);let N=["# Alfred Environment Variables","# Generated by `alfred setup`","","# === LLM ===","",`ALFRED_LLM_PROVIDER=${a.name}`];if(l){let y=a.envKeyName||"ALFRED_OLLAMA_API_KEY";N.push(`${y}=${l}`)}w!==a.defaultModel&&N.push(`ALFRED_LLM_MODEL=${w}`),p&&N.push(`ALFRED_LLM_BASE_URL=${p}`),N.push("","# === Messaging Platforms ===","");for(let[y,R]of Object.entries(tt))N.push(`${y}=${R}`);N.push("","# === Web Search ===",""),A?(N.push(`ALFRED_SEARCH_PROVIDER=${A}`),C&&N.push(`ALFRED_SEARCH_API_KEY=${C}`),H&&N.push(`ALFRED_SEARCH_BASE_URL=${H}`)):(N.push("# ALFRED_SEARCH_PROVIDER=brave"),N.push("# ALFRED_SEARCH_API_KEY=")),N.push("","# === Email ===",""),qt?(N.push(`ALFRED_EMAIL_USER=${ne}`),N.push(`ALFRED_EMAIL_PASS=${Kt}`)):(N.push("# ALFRED_EMAIL_USER="),N.push("# ALFRED_EMAIL_PASS=")),N.push("","# === Speech-to-Text ===",""),te?(N.push(`ALFRED_SPEECH_PROVIDER=${te}`),N.push(`ALFRED_SPEECH_API_KEY=${oe}`),st&&N.push(`ALFRED_SPEECH_BASE_URL=${st}`)):(N.push("# ALFRED_SPEECH_PROVIDER=groq"),N.push("# ALFRED_SPEECH_API_KEY=")),N.push("","# === Security ===",""),V?N.push(`ALFRED_OWNER_USER_ID=${V}`):N.push("# ALFRED_OWNER_USER_ID="),N.push("");let No=re.join(e,".env");K.writeFileSync(No,N.join(`
510
- `),"utf-8"),console.log(` ${U("+")} ${S(".env")} written`);let Zt=re.join(e,"config");K.existsSync(Zt)||K.mkdirSync(Zt,{recursive:!0});let $r={name:r,telegram:{token:Z.telegram?.token??"",enabled:$.some(y=>y.name==="telegram")},discord:{token:Z.discord?.token??"",enabled:$.some(y=>y.name==="discord")},whatsapp:{enabled:$.some(y=>y.name==="whatsapp"),dataPath:"./data/whatsapp"},matrix:{homeserverUrl:Z.matrix?.homeserverUrl??"https://matrix.org",accessToken:Z.matrix?.accessToken??"",userId:Z.matrix?.userId??"",enabled:$.some(y=>y.name==="matrix")},signal:{apiUrl:Z.signal?.apiUrl??"http://localhost:8080",phoneNumber:Z.signal?.phoneNumber??"",enabled:$.some(y=>y.name==="signal")},llm:{provider:a.name,model:w,...p?{baseUrl:p}:{},temperature:.7,maxTokens:4096},...A?{search:{provider:A,...C?{apiKey:C}:{},...H?{baseUrl:H}:{}}}:{},...qt?{email:{imap:{host:Vt,port:bs,secure:bs===993},smtp:{host:kr,port:_s,secure:_s===465},auth:{user:ne,pass:Kt}}}:{},...te?{speech:{provider:te,apiKey:oe,...st?{baseUrl:st}:{}}}:{},storage:{path:"./data/alfred.db"},logger:{level:"info",pretty:!0,auditLogPath:"./data/audit.log"},security:{rulesPath:"./config/rules",defaultEffect:"deny"}};V&&($r.security.ownerUserId=V);let Do="# Alfred \u2014 Configuration\n# Generated by `alfred setup`\n# Edit manually or re-run `alfred setup` to reconfigure.\n\n"+Er.dump($r,{lineWidth:120,noRefs:!0,sortKeys:!1}),Oo=re.join(Zt,"default.yml");K.writeFileSync(Oo,Do,"utf-8"),console.log(` ${U("+")} ${S("config/default.yml")} written`);let vs=re.join(Zt,"rules");K.existsSync(vs)||K.mkdirSync(vs,{recursive:!0});let Co=rt&&V?`
507
+ ${I(y.label+" configuration:")}`);let R={};for(let W of y.credentials){let xe=t.env[W.envKey]??"",Z;xe?Z=await B(c,` ${W.prompt}`,xe):W.defaultValue?Z=await B(c,` ${W.prompt}`,W.defaultValue):W.required?Z=await ce(c,` ${W.prompt}`):(Z=(await c.question(` ${W.prompt}: ${Q}`)).trim(),process.stdout.write(M)),R[W.configField]=Z,tt[W.envKey]=Z,W.configField==="token"||W.configField==="accessToken"?console.log(` ${U(">")} Set: ${S(ve(Z))}`):console.log(` ${U(">")} Set: ${S(Z)}`)}H[y.configKey]=R}let _r=t.config.email?.auth?.user??t.env.ALFRED_EMAIL_USER??"",Sr=!!_r,$o=Sr?"Y/n":"y/N";console.log(`
508
+ ${I("Email access (read & send emails via IMAP/SMTP)?")}`),console.log(`${S("Works with Gmail, Outlook, or any IMAP/SMTP provider.")}`);let Ts=(await c.question(`${Q}> ${M}${S(`[${$o}] `)}`)).trim().toLowerCase(),qt=Ts===""?Sr:Ts==="y"||Ts==="yes",ne="",Kt="",Vt="",bs=993,kr="",_s=587;if(qt){console.log(""),ne=await B(c," Email address",_r||""),ne||(ne=await ce(c," Email address"));let y=t.env.ALFRED_EMAIL_PASS??"";y?Kt=await B(c," Password / App password",y):(console.log(` ${S("For Gmail: use an App Password (not your regular password)")}`),console.log(` ${S(" \u2192 Google Account \u2192 Security \u2192 2-Step \u2192 App passwords")}`),Kt=await ce(c," Password / App password"));let R=ne.split("@")[1]?.toLowerCase()??"",xe={"gmail.com":{imap:"imap.gmail.com",smtp:"smtp.gmail.com"},"googlemail.com":{imap:"imap.gmail.com",smtp:"smtp.gmail.com"},"outlook.com":{imap:"outlook.office365.com",smtp:"smtp.office365.com"},"hotmail.com":{imap:"outlook.office365.com",smtp:"smtp.office365.com"},"live.com":{imap:"outlook.office365.com",smtp:"smtp.office365.com"},"yahoo.com":{imap:"imap.mail.yahoo.com",smtp:"smtp.mail.yahoo.com"},"icloud.com":{imap:"imap.mail.me.com",smtp:"smtp.mail.me.com"},"me.com":{imap:"imap.mail.me.com",smtp:"smtp.mail.me.com"},"gmx.de":{imap:"imap.gmx.net",smtp:"mail.gmx.net"},"gmx.net":{imap:"imap.gmx.net",smtp:"mail.gmx.net"},"web.de":{imap:"imap.web.de",smtp:"smtp.web.de"},"posteo.de":{imap:"posteo.de",smtp:"posteo.de"},"mailbox.org":{imap:"imap.mailbox.org",smtp:"smtp.mailbox.org"},"protonmail.com":{imap:"127.0.0.1",smtp:"127.0.0.1"},"proton.me":{imap:"127.0.0.1",smtp:"127.0.0.1"}}[R],Z=t.config.email?.imap?.host??xe?.imap??`imap.${R}`,Fo=t.config.email?.smtp?.host??xe?.smtp??`smtp.${R}`,jo=t.config.email?.imap?.port??993,Bo=t.config.email?.smtp?.port??587;xe&&console.log(` ${U(">")} Detected ${R} \u2014 using preset server settings`),Vt=await B(c," IMAP server",Z);let Wo=await B(c," IMAP port",String(jo));bs=parseInt(Wo,10)||993,kr=await B(c," SMTP server",Fo);let Ho=await B(c," SMTP port",String(Bo));_s=parseInt(Ho,10)||587,console.log(` ${U(">")} Email: ${S(ne)} via ${S(Vt)}`)}else console.log(` ${S("Email disabled \u2014 you can configure it later.")}`);let Gt=["openai","groq"],Io=t.config.speech?.provider??t.env.ALFRED_SPEECH_PROVIDER??"",Yt=Gt.indexOf(Io),Ao=Yt>=0?Yt+1:0;console.log(`
509
+ ${I("Voice message transcription (Speech-to-Text via Whisper)?")}`),console.log(`${S("Transcribes voice messages from Telegram, Discord, etc.")}`);let vr=["OpenAI Whisper \u2014 best quality","Groq Whisper \u2014 fast & free"];console.log(` ${ke("0)")} None (disable voice transcription)${Yt===-1?` ${S("(current)")}`:""}`);for(let y=0;y<vr.length;y++){let R=Yt===y?` ${S("(current)")}`:"";console.log(` ${ke(String(y+1)+")")} ${vr[y]}${R}`)}let Ss=await wr(c,"> ",0,Gt.length,Ao),te,oe="",st="";if(Ss>=1&&Ss<=Gt.length&&(te=Gt[Ss-1]),te==="openai"){let y=t.env.ALFRED_SPEECH_API_KEY??"";y?oe=await B(c," OpenAI API key (for Whisper)",y):(console.log(` ${S("Uses your OpenAI API key for Whisper transcription.")}`),oe=await ce(c," OpenAI API key")),console.log(` ${U(">")} OpenAI Whisper: ${S(ve(oe))}`)}else if(te==="groq"){let y=t.env.ALFRED_SPEECH_API_KEY??"";y?oe=await B(c," Groq API key",y):(console.log(` ${S("Get your free API key at: https://console.groq.com/")}`),oe=await ce(c," Groq API key"));let R=t.env.ALFRED_SPEECH_BASE_URL??"";R&&(st=await B(c," Groq API URL",R)),console.log(` ${U(">")} Groq Whisper: ${S(ve(oe))}`)}else console.log(` ${S("Voice transcription disabled \u2014 you can configure it later.")}`);console.log(`
510
+ ${I("Security configuration:")}`);let xr=t.config.security?.ownerUserId??t.env.ALFRED_OWNER_USER_ID??"",V;if(xr)V=await B(c,"Owner user ID (for elevated permissions)",xr);else{let y=(await c.question(`${et}Owner user ID${M} ${S("(optional, for elevated permissions)")}: ${Q}`)).trim();process.stdout.write(M),V=y}let rt=!1;if(V){let y=t.shellEnabled?"Y/n":"y/N";console.log(""),console.log(` ${I("Enable shell access (admin commands) for the owner?")}`),console.log(` ${S("Allows Alfred to execute shell commands. Only for the owner.")}`);let R=(await c.question(` ${Q}> ${M}${S(`[${y}] `)}`)).trim().toLowerCase();R===""?rt=t.shellEnabled:rt=R==="y"||R==="yes",console.log(rt?` ${U(">")} Shell access ${I("enabled")} for owner ${S(V)}`:` ${S("Shell access disabled.")}`)}let Ro=t.writeInGroups?"Y/n":"y/N";console.log(""),console.log(` ${I("Allow write actions (notes, reminders, memory) in group chats?")}`),console.log(` ${S("By default, write actions are only allowed in DMs.")}`);let ks=(await c.question(` ${Q}> ${M}${S(`[${Ro}] `)}`)).trim().toLowerCase(),nt;ks===""?nt=t.writeInGroups:nt=ks==="y"||ks==="yes",console.log(nt?` ${U(">")} Write actions ${I("enabled")} in groups`:` ${S("Write actions only in DMs (default).")}`);let Lo=t.rateLimit??30;console.log("");let Mo=await B(c," Rate limit (max write actions per hour per user)",String(Lo)),Jt=Math.max(1,parseInt(Mo,10)||30);console.log(` ${U(">")} Rate limit: ${I(String(Jt))} per hour`),console.log(`
511
+ ${I("Writing configuration files...")}`);let N=["# Alfred Environment Variables","# Generated by `alfred setup`","","# === LLM ===","",`ALFRED_LLM_PROVIDER=${a.name}`];if(l){let y=a.envKeyName||"ALFRED_OLLAMA_API_KEY";N.push(`${y}=${l}`)}w!==a.defaultModel&&N.push(`ALFRED_LLM_MODEL=${w}`),p&&N.push(`ALFRED_LLM_BASE_URL=${p}`),N.push("","# === Messaging Platforms ===","");for(let[y,R]of Object.entries(tt))N.push(`${y}=${R}`);N.push("","# === Web Search ===",""),L?(N.push(`ALFRED_SEARCH_PROVIDER=${L}`),P&&N.push(`ALFRED_SEARCH_API_KEY=${P}`),F&&N.push(`ALFRED_SEARCH_BASE_URL=${F}`)):(N.push("# ALFRED_SEARCH_PROVIDER=brave"),N.push("# ALFRED_SEARCH_API_KEY=")),N.push("","# === Email ===",""),qt?(N.push(`ALFRED_EMAIL_USER=${ne}`),N.push(`ALFRED_EMAIL_PASS=${Kt}`)):(N.push("# ALFRED_EMAIL_USER="),N.push("# ALFRED_EMAIL_PASS=")),N.push("","# === Speech-to-Text ===",""),te?(N.push(`ALFRED_SPEECH_PROVIDER=${te}`),N.push(`ALFRED_SPEECH_API_KEY=${oe}`),st&&N.push(`ALFRED_SPEECH_BASE_URL=${st}`)):(N.push("# ALFRED_SPEECH_PROVIDER=groq"),N.push("# ALFRED_SPEECH_API_KEY=")),N.push("","# === Security ===",""),V?N.push(`ALFRED_OWNER_USER_ID=${V}`):N.push("# ALFRED_OWNER_USER_ID="),N.push("");let No=re.join(e,".env");q.writeFileSync(No,N.join(`
512
+ `),"utf-8"),console.log(` ${U("+")} ${S(".env")} written`);let Zt=re.join(e,"config");q.existsSync(Zt)||q.mkdirSync(Zt,{recursive:!0});let $r={name:r,telegram:{token:H.telegram?.token??"",enabled:$.some(y=>y.name==="telegram")},discord:{token:H.discord?.token??"",enabled:$.some(y=>y.name==="discord")},whatsapp:{enabled:$.some(y=>y.name==="whatsapp"),dataPath:"./data/whatsapp"},matrix:{homeserverUrl:H.matrix?.homeserverUrl??"https://matrix.org",accessToken:H.matrix?.accessToken??"",userId:H.matrix?.userId??"",enabled:$.some(y=>y.name==="matrix")},signal:{apiUrl:H.signal?.apiUrl??"http://localhost:8080",phoneNumber:H.signal?.phoneNumber??"",enabled:$.some(y=>y.name==="signal")},llm:{provider:a.name,model:w,...p?{baseUrl:p}:{},temperature:.7,maxTokens:4096},...L?{search:{provider:L,...P?{apiKey:P}:{},...F?{baseUrl:F}:{}}}:{},...qt?{email:{imap:{host:Vt,port:bs,secure:bs===993},smtp:{host:kr,port:_s,secure:_s===465},auth:{user:ne,pass:Kt}}}:{},...te?{speech:{provider:te,apiKey:oe,...st?{baseUrl:st}:{}}}:{},storage:{path:"./data/alfred.db"},logger:{level:"info",pretty:!0,auditLogPath:"./data/audit.log"},security:{rulesPath:"./config/rules",defaultEffect:"deny"}};V&&($r.security.ownerUserId=V);let Do="# Alfred \u2014 Configuration\n# Generated by `alfred setup`\n# Edit manually or re-run `alfred setup` to reconfigure.\n\n"+Er.dump($r,{lineWidth:120,noRefs:!0,sortKeys:!1}),Oo=re.join(Zt,"default.yml");q.writeFileSync(Oo,Do,"utf-8"),console.log(` ${U("+")} ${S("config/default.yml")} written`);let vs=re.join(Zt,"rules");q.existsSync(vs)||q.mkdirSync(vs,{recursive:!0});let Co=rt&&V?`
511
513
  # Allow admin actions (shell, etc.) for the owner only
512
514
  - id: allow-owner-admin
513
515
  effect: allow
@@ -583,14 +585,14 @@ ${Co}
583
585
  scope: global
584
586
  actions: ["*"]
585
587
  riskLevels: [read, write, destructive, admin]
586
- `,Po=re.join(vs,"default-rules.yml");K.writeFileSync(Po,Uo,"utf-8"),console.log(` ${U("+")} ${S("config/rules/default-rules.yml")} written`);let Ir=re.join(e,"data");if(K.existsSync(Ir)||(K.mkdirSync(Ir,{recursive:!0}),console.log(` ${U("+")} ${S("data/")} directory created`)),console.log(""),console.log(`${ys}${"=".repeat(52)}${L}`),console.log(`${ys}${et} Setup complete!${L}`),console.log(`${ys}${"=".repeat(52)}${L}`),console.log(""),console.log(` ${I("Bot name:")} ${r}`),console.log(` ${I("LLM provider:")} ${a.name} (${w})`),l&&console.log(` ${I("API key:")} ${ve(l)}`),$.length>0?console.log(` ${I("Platforms:")} ${$.map(y=>y.label).join(", ")}`):console.log(` ${I("Platforms:")} none (configure later)`),A){let y={brave:"Brave Search",tavily:"Tavily",duckduckgo:"DuckDuckGo",searxng:`SearXNG (${H})`};console.log(` ${I("Web search:")} ${y[A]}`)}else console.log(` ${I("Web search:")} ${S("disabled")}`);if(console.log(qt?` ${I("Email:")} ${ne} (${Vt})`:` ${I("Email:")} ${S("disabled")}`),te){let y={openai:"OpenAI Whisper",groq:"Groq Whisper"};console.log(` ${I("Voice:")} ${y[te]}`)}else console.log(` ${I("Voice:")} ${S("disabled")}`);V&&(console.log(` ${I("Owner ID:")} ${V}`),console.log(` ${I("Shell access:")} ${rt?U("enabled"):S("disabled")}`)),console.log(` ${I("Write scope:")} ${nt?"DMs + Groups":"DMs only"}`),console.log(` ${I("Rate limit:")} ${Jt}/hour per user`),console.log(""),console.log(`${ws}Next steps:${L}`),console.log(` ${I("alfred start")} Start Alfred`),console.log(` ${I("alfred status")} Check configuration`),console.log(` ${I("alfred --help")} Show all commands`),console.log(""),console.log(`${le}Edit ${I(".env")}${le} or ${I("config/default.yml")}${le} for manual configuration.${L}`),console.log("")}finally{c.close()}}async function F(c,e,t){let s=(await c.question(`${et}${e}${L} ${S(`[${t}]`)}: ${ee}`)).trim();return process.stdout.write(L),s||t}async function ce(c,e){for(;;){let t=(await c.question(`${et}${e}${L}: ${ee}`)).trim();if(process.stdout.write(L),t)return t;console.log(` ${po("!")} This field is required. Please enter a value.`)}}async function wr(c,e,t,s,r){for(;;){let n=(await c.question(`${ee}${e}${L}`)).trim();if(!n)return r;let o=parseInt(n,10);if(!Number.isNaN(o)&&o>=t&&o<=s)return o;console.log(` ${po("!")} Please enter a number between ${t} and ${s}.`)}}function ua(){console.log(`
588
+ `,Po=re.join(vs,"default-rules.yml");q.writeFileSync(Po,Uo,"utf-8"),console.log(` ${U("+")} ${S("config/rules/default-rules.yml")} written`);let Ir=re.join(e,"data");if(q.existsSync(Ir)||(q.mkdirSync(Ir,{recursive:!0}),console.log(` ${U("+")} ${S("data/")} directory created`)),console.log(""),console.log(`${ys}${"=".repeat(52)}${M}`),console.log(`${ys}${et} Setup complete!${M}`),console.log(`${ys}${"=".repeat(52)}${M}`),console.log(""),console.log(` ${I("Bot name:")} ${r}`),console.log(` ${I("LLM provider:")} ${a.name} (${w})`),l&&console.log(` ${I("API key:")} ${ve(l)}`),$.length>0?console.log(` ${I("Platforms:")} ${$.map(y=>y.label).join(", ")}`):console.log(` ${I("Platforms:")} none (configure later)`),L){let y={brave:"Brave Search",tavily:"Tavily",duckduckgo:"DuckDuckGo",searxng:`SearXNG (${F})`};console.log(` ${I("Web search:")} ${y[L]}`)}else console.log(` ${I("Web search:")} ${S("disabled")}`);if(console.log(qt?` ${I("Email:")} ${ne} (${Vt})`:` ${I("Email:")} ${S("disabled")}`),te){let y={openai:"OpenAI Whisper",groq:"Groq Whisper"};console.log(` ${I("Voice:")} ${y[te]}`)}else console.log(` ${I("Voice:")} ${S("disabled")}`);V&&(console.log(` ${I("Owner ID:")} ${V}`),console.log(` ${I("Shell access:")} ${rt?U("enabled"):S("disabled")}`)),console.log(` ${I("Write scope:")} ${nt?"DMs + Groups":"DMs only"}`),console.log(` ${I("Rate limit:")} ${Jt}/hour per user`),console.log(""),console.log(`${ws}Next steps:${M}`),console.log(` ${I("alfred start")} Start Alfred`),console.log(` ${I("alfred status")} Check configuration`),console.log(` ${I("alfred --help")} Show all commands`),console.log(""),console.log(`${le}Edit ${I(".env")}${le} or ${I("config/default.yml")}${le} for manual configuration.${M}`),console.log("")}finally{c.close()}}async function B(c,e,t){let s=(await c.question(`${et}${e}${M} ${S(`[${t}]`)}: ${Q}`)).trim();return process.stdout.write(M),s||t}async function ce(c,e){for(;;){let t=(await c.question(`${et}${e}${M}: ${Q}`)).trim();if(process.stdout.write(M),t)return t;console.log(` ${po("!")} This field is required. Please enter a value.`)}}async function wr(c,e,t,s,r){for(;;){let n=(await c.question(`${Q}${e}${M}`)).trim();if(!n)return r;let o=parseInt(n,10);if(!Number.isNaN(o)&&o>=t&&o<=s)return o;console.log(` ${po("!")} Please enter a number between ${t} and ${s}.`)}}function ua(){console.log(`
587
589
  ${aa}${et} _ _ _____ ____ _____ ____
588
590
  / \\ | | | ___| _ \\| ____| _ \\
589
591
  / _ \\ | | | |_ | |_) | _| | | | |
590
592
  / ___ \\| |___| _| | _ <| |___| |_| |
591
- /_/ \\_\\_____|_| |_| \\_\\_____|____/ ${L}
592
- ${le} Personal AI Assistant \u2014 Setup Wizard${L}
593
- `)}var L,et,le,ys,ee,ws,ia,aa,Xt,Qe,fo=f(()=>{"use strict";L="\x1B[0m",et="\x1B[1m",le="\x1B[2m",ys="\x1B[32m",ee="\x1B[33m",ws="\x1B[36m",ia="\x1B[31m",aa="\x1B[35m";d(U,"green");d(ca,"yellow");d(ke,"cyan");d(po,"red");d(I,"bold");d(S,"dim");d(ve,"maskKey");Xt=[{name:"anthropic",label:"Anthropic (Claude) \u2014 recommended",defaultModel:"claude-sonnet-4-20250514",envKeyName:"ALFRED_ANTHROPIC_API_KEY",needsApiKey:!0},{name:"openai",label:"OpenAI (GPT)",defaultModel:"gpt-4o",envKeyName:"ALFRED_OPENAI_API_KEY",needsApiKey:!0},{name:"openrouter",label:"OpenRouter (multiple providers)",defaultModel:"anthropic/claude-sonnet-4-20250514",envKeyName:"ALFRED_OPENROUTER_API_KEY",needsApiKey:!0,baseUrl:"https://openrouter.ai/api/v1"},{name:"ollama",label:"Ollama (local, no API key needed)",defaultModel:"llama3.2",envKeyName:"",needsApiKey:!1,baseUrl:"http://localhost:11434"},{name:"openwebui",label:"OpenWebUI (local OpenAI-compatible UI)",defaultModel:"llama3.2",envKeyName:"ALFRED_OPENWEBUI_API_KEY",needsApiKey:!0,baseUrl:"http://localhost:3000/api/v1"}],Qe=[{name:"telegram",label:"Telegram",configKey:"telegram",credentials:[{envKey:"ALFRED_TELEGRAM_TOKEN",configField:"token",prompt:"Enter your Telegram Bot token (from @BotFather)",required:!0}]},{name:"discord",label:"Discord",configKey:"discord",credentials:[{envKey:"ALFRED_DISCORD_TOKEN",configField:"token",prompt:"Enter your Discord Bot token",required:!0}]},{name:"whatsapp",label:"WhatsApp",configKey:"whatsapp",credentials:[]},{name:"matrix",label:"Matrix",configKey:"matrix",credentials:[{envKey:"ALFRED_MATRIX_HOMESERVER_URL",configField:"homeserverUrl",prompt:"Enter your Matrix homeserver URL",defaultValue:"https://matrix.org",required:!0},{envKey:"ALFRED_MATRIX_ACCESS_TOKEN",configField:"accessToken",prompt:"Enter your Matrix access token",required:!0},{envKey:"ALFRED_MATRIX_USER_ID",configField:"userId",prompt:"Enter your Matrix user ID (e.g. @bot:matrix.org)",required:!0}]},{name:"signal",label:"Signal",configKey:"signal",credentials:[{envKey:"ALFRED_SIGNAL_API_URL",configField:"apiUrl",prompt:"Enter the Signal REST API URL",defaultValue:"http://localhost:8080",required:!0},{envKey:"ALFRED_SIGNAL_PHONE_NUMBER",configField:"phoneNumber",prompt:"Enter the Signal phone number (e.g. +15551234567)",required:!0}]}];d(la,"loadExistingConfig");d(da,"setupCommand");d(F,"askWithDefault");d(ce,"askRequired");d(wr,"askNumber");d(ua,"printBanner")});var yo={};G(yo,{configCommand:()=>fa});function pa(c){let e=c.toLowerCase();return ma.some(t=>e.includes(t))}function ha(c){return typeof c!="string"||c.length===0?"(empty)":c.length<=8?"***":c.slice(0,4)+"..."+c.slice(-4)}function go(c){let e={};for(let[t,s]of Object.entries(c))pa(t)?e[t]=ha(s):s!=null&&typeof s=="object"&&!Array.isArray(s)?e[t]=go(s):e[t]=s;return e}async function fa(){let c=new q,e;try{e=c.loadConfig()}catch(s){console.error("Failed to load configuration:",s.message),process.exit(1)}let t=go(e);console.log("Alfred \u2014 Resolved Configuration"),console.log("================================"),console.log(JSON.stringify(t,null,2))}var ma,wo=f(()=>{"use strict";ue();ma=["token","apikey","api_key","accesstoken","secret","password"];d(pa,"isSensitiveKey");d(ha,"redactValue");d(go,"redactObject");d(fa,"configCommand")});var To={};G(To,{rulesCommand:()=>ya});import Es from"node:fs";import Eo from"node:path";import ga from"js-yaml";async function ya(){let c=new q,e;try{e=c.loadConfig()}catch(a){console.error("Failed to load configuration:",a.message),process.exit(1)}let t=Eo.resolve(e.security.rulesPath);if(!Es.existsSync(t)){console.log(`Rules directory not found: ${t}`),console.log("No security rules loaded.");return}Es.statSync(t).isDirectory()||(console.error(`Rules path is not a directory: ${t}`),process.exit(1));let r=Es.readdirSync(t).filter(a=>a.endsWith(".yml")||a.endsWith(".yaml"));if(r.length===0){console.log(`No YAML rule files found in: ${t}`);return}let n=new fe,o=[],i=[];for(let a of r){let l=Eo.join(t,a);try{let u=Es.readFileSync(l,"utf-8"),p=ga.load(u),m=n.loadFromObject(p);o.push(...m)}catch(u){i.push(` ${a}: ${u.message}`)}}if(console.log("Alfred \u2014 Security Rules"),console.log("======================="),console.log(`Rules directory: ${t}`),console.log(`Rule files found: ${r.length}`),console.log(`Total rules loaded: ${o.length}`),console.log(""),i.length>0){console.log("Errors:");for(let a of i)console.log(a);console.log("")}if(o.length!==0){o.sort((a,l)=>a.priority-l.priority),console.log("Loaded rules (sorted by priority):"),console.log("");for(let a of o){let l=a.rateLimit?` | rate-limit: ${a.rateLimit.maxInvocations}/${a.rateLimit.windowSeconds}s`:"";console.log(` [${a.priority}] ${a.id}`),console.log(` effect: ${a.effect} | scope: ${a.scope}`),console.log(` actions: ${a.actions.join(", ")}`),console.log(` risk levels: ${a.riskLevels.join(", ")}${l}`),a.conditions&&console.log(` conditions: ${JSON.stringify(a.conditions)}`),console.log("")}}}var bo=f(()=>{"use strict";ue();ss();d(ya,"rulesCommand")});var _o={};G(_o,{statusCommand:()=>Ea});import zt from"node:fs";import Tr from"node:path";import wa from"js-yaml";async function Ea(){let c=new q,e;try{e=c.loadConfig()}catch(l){console.error("Failed to load configuration:",l.message),process.exit(1)}console.log("Alfred \u2014 Status"),console.log("================"),console.log("");let t=[{name:"Telegram",enabled:e.telegram.enabled,configured:!!e.telegram.token},{name:"Discord",enabled:!!e.discord?.enabled,configured:!!e.discord?.token},{name:"WhatsApp",enabled:!!e.whatsapp?.enabled,configured:!!e.whatsapp?.dataPath},{name:"Matrix",enabled:!!e.matrix?.enabled,configured:!!e.matrix?.accessToken},{name:"Signal",enabled:!!e.signal?.enabled,configured:!!e.signal?.phoneNumber}];console.log("Messaging Adapters:");for(let l of t){let u=l.enabled?"enabled":l.configured?"configured (disabled)":"not configured",p=l.enabled?"+":"-";console.log(` [${p}] ${l.name}: ${u}`)}console.log(""),console.log("LLM Provider:");let s=e.llm.default;console.log(` Provider: ${s.provider}`),console.log(` Model: ${s.model}`),console.log(` API Key: ${s.apiKey?"set":"not set"}`),s.baseUrl&&console.log(` Base URL: ${s.baseUrl}`);for(let l of["strong","fast","embeddings","local"]){let u=e.llm[l];u&&console.log(` ${l}: ${u.provider}/${u.model}`)}console.log(""),console.log("Storage:");let r=Tr.resolve(e.storage.path),n=zt.existsSync(r);console.log(` Database: ${r}`),console.log(` Status: ${n?"exists":"not yet created"}`),console.log("");let o=Tr.resolve(e.security.rulesPath),i=0,a=0;if(zt.existsSync(o)&&zt.statSync(o).isDirectory()){let l=zt.readdirSync(o).filter(p=>p.endsWith(".yml")||p.endsWith(".yaml"));a=l.length;let u=new fe;for(let p of l){let m=Tr.join(o,p);try{let h=zt.readFileSync(m,"utf-8"),w=wa.load(h),E=u.loadFromObject(w);i+=E.length}catch{}}}console.log("Security:"),console.log(` Rules path: ${o}`),console.log(` Rule files: ${a}`),console.log(` Rules loaded: ${i}`),console.log(` Default effect: ${e.security.defaultEffect}`),e.security.ownerUserId&&console.log(` Owner user ID: ${e.security.ownerUserId}`),console.log(""),console.log("Logger:"),console.log(` Level: ${e.logger.level}`),console.log(` Pretty: ${e.logger.pretty}`)}var So=f(()=>{"use strict";ue();ss();d(Ea,"statusCommand")});var ko={};G(ko,{logsCommand:()=>_a});import Ta from"node:fs";import ba from"node:path";async function _a(c){let e=new q,t;try{t=e.loadConfig()}catch(n){console.error("Failed to load configuration:",n.message),process.exit(1)}let s=ba.resolve(t.storage.path);if(!Ta.existsSync(s)){console.log(`Database not found at: ${s}`),console.log("No audit log entries. Alfred has not been run yet, or the database path is incorrect.");return}let r;try{r=new me(s);let n=new pe(r.getDb()),o=n.count({}),i=n.query({limit:c});if(console.log("Alfred \u2014 Audit Log"),console.log("==================="),console.log(`Total entries: ${o}`),console.log(`Showing last ${Math.min(c,o)} entries:`),console.log(""),i.length===0){console.log("No audit log entries found.");return}for(let a of i){let l=a.timestamp.toISOString(),u=a.effect==="allow"?"ALLOW":"DENY ";console.log(` ${l} [${u}] ${a.action}`),console.log(` user: ${a.userId} | platform: ${a.platform} | risk: ${a.riskLevel}`),a.ruleId&&console.log(` rule: ${a.ruleId}`),a.chatId&&console.log(` chat: ${a.chatId}`),a.context&&console.log(` context: ${JSON.stringify(a.context)}`),console.log("")}}catch(n){console.error("Failed to read audit log:",n.message),process.exit(1)}finally{r&&r.close()}}var vo=f(()=>{"use strict";ue();Ds();d(_a,"logsCommand")});import{readFileSync as Sa}from"node:fs";import{fileURLToPath as ka}from"node:url";import{dirname as va,join as xa}from"node:path";function $a(){try{let c=va(ka(import.meta.url));for(let e of["../package.json","../../package.json"])try{let t=JSON.parse(Sa(xa(c,e),"utf-8"));if(t.version)return t.version}catch{}}catch{}return"0.0.0"}d($a,"getVersion");var xo=$a(),br=`
593
+ /_/ \\_\\_____|_| |_| \\_\\_____|____/ ${M}
594
+ ${le} Personal AI Assistant \u2014 Setup Wizard${M}
595
+ `)}var M,et,le,ys,Q,ws,ia,aa,Xt,Qe,fo=f(()=>{"use strict";M="\x1B[0m",et="\x1B[1m",le="\x1B[2m",ys="\x1B[32m",Q="\x1B[33m",ws="\x1B[36m",ia="\x1B[31m",aa="\x1B[35m";d(U,"green");d(ca,"yellow");d(ke,"cyan");d(po,"red");d(I,"bold");d(S,"dim");d(ve,"maskKey");Xt=[{name:"anthropic",label:"Anthropic (Claude) \u2014 recommended",defaultModel:"claude-sonnet-4-20250514",envKeyName:"ALFRED_ANTHROPIC_API_KEY",needsApiKey:!0},{name:"openai",label:"OpenAI (GPT)",defaultModel:"gpt-4o",envKeyName:"ALFRED_OPENAI_API_KEY",needsApiKey:!0},{name:"openrouter",label:"OpenRouter (multiple providers)",defaultModel:"anthropic/claude-sonnet-4-20250514",envKeyName:"ALFRED_OPENROUTER_API_KEY",needsApiKey:!0,baseUrl:"https://openrouter.ai/api/v1"},{name:"ollama",label:"Ollama (local, no API key needed)",defaultModel:"llama3.2",envKeyName:"",needsApiKey:!1,baseUrl:"http://localhost:11434"},{name:"openwebui",label:"OpenWebUI (local OpenAI-compatible UI)",defaultModel:"llama3.2",envKeyName:"ALFRED_OPENWEBUI_API_KEY",needsApiKey:!0,baseUrl:"http://localhost:3000/api/v1"}],Qe=[{name:"telegram",label:"Telegram",configKey:"telegram",credentials:[{envKey:"ALFRED_TELEGRAM_TOKEN",configField:"token",prompt:"Enter your Telegram Bot token (from @BotFather)",required:!0}]},{name:"discord",label:"Discord",configKey:"discord",credentials:[{envKey:"ALFRED_DISCORD_TOKEN",configField:"token",prompt:"Enter your Discord Bot token",required:!0}]},{name:"whatsapp",label:"WhatsApp",configKey:"whatsapp",credentials:[]},{name:"matrix",label:"Matrix",configKey:"matrix",credentials:[{envKey:"ALFRED_MATRIX_HOMESERVER_URL",configField:"homeserverUrl",prompt:"Enter your Matrix homeserver URL",defaultValue:"https://matrix.org",required:!0},{envKey:"ALFRED_MATRIX_ACCESS_TOKEN",configField:"accessToken",prompt:"Enter your Matrix access token",required:!0},{envKey:"ALFRED_MATRIX_USER_ID",configField:"userId",prompt:"Enter your Matrix user ID (e.g. @bot:matrix.org)",required:!0}]},{name:"signal",label:"Signal",configKey:"signal",credentials:[{envKey:"ALFRED_SIGNAL_API_URL",configField:"apiUrl",prompt:"Enter the Signal REST API URL",defaultValue:"http://localhost:8080",required:!0},{envKey:"ALFRED_SIGNAL_PHONE_NUMBER",configField:"phoneNumber",prompt:"Enter the Signal phone number (e.g. +15551234567)",required:!0}]}];d(la,"loadExistingConfig");d(da,"setupCommand");d(B,"askWithDefault");d(ce,"askRequired");d(wr,"askNumber");d(ua,"printBanner")});var yo={};G(yo,{configCommand:()=>fa});function pa(c){let e=c.toLowerCase();return ma.some(t=>e.includes(t))}function ha(c){return typeof c!="string"||c.length===0?"(empty)":c.length<=8?"***":c.slice(0,4)+"..."+c.slice(-4)}function go(c){let e={};for(let[t,s]of Object.entries(c))pa(t)?e[t]=ha(s):s!=null&&typeof s=="object"&&!Array.isArray(s)?e[t]=go(s):e[t]=s;return e}async function fa(){let c=new z,e;try{e=c.loadConfig()}catch(s){console.error("Failed to load configuration:",s.message),process.exit(1)}let t=go(e);console.log("Alfred \u2014 Resolved Configuration"),console.log("================================"),console.log(JSON.stringify(t,null,2))}var ma,wo=f(()=>{"use strict";ue();ma=["token","apikey","api_key","accesstoken","secret","password"];d(pa,"isSensitiveKey");d(ha,"redactValue");d(go,"redactObject");d(fa,"configCommand")});var To={};G(To,{rulesCommand:()=>ya});import Es from"node:fs";import Eo from"node:path";import ga from"js-yaml";async function ya(){let c=new z,e;try{e=c.loadConfig()}catch(a){console.error("Failed to load configuration:",a.message),process.exit(1)}let t=Eo.resolve(e.security.rulesPath);if(!Es.existsSync(t)){console.log(`Rules directory not found: ${t}`),console.log("No security rules loaded.");return}Es.statSync(t).isDirectory()||(console.error(`Rules path is not a directory: ${t}`),process.exit(1));let r=Es.readdirSync(t).filter(a=>a.endsWith(".yml")||a.endsWith(".yaml"));if(r.length===0){console.log(`No YAML rule files found in: ${t}`);return}let n=new fe,o=[],i=[];for(let a of r){let l=Eo.join(t,a);try{let u=Es.readFileSync(l,"utf-8"),p=ga.load(u),m=n.loadFromObject(p);o.push(...m)}catch(u){i.push(` ${a}: ${u.message}`)}}if(console.log("Alfred \u2014 Security Rules"),console.log("======================="),console.log(`Rules directory: ${t}`),console.log(`Rule files found: ${r.length}`),console.log(`Total rules loaded: ${o.length}`),console.log(""),i.length>0){console.log("Errors:");for(let a of i)console.log(a);console.log("")}if(o.length!==0){o.sort((a,l)=>a.priority-l.priority),console.log("Loaded rules (sorted by priority):"),console.log("");for(let a of o){let l=a.rateLimit?` | rate-limit: ${a.rateLimit.maxInvocations}/${a.rateLimit.windowSeconds}s`:"";console.log(` [${a.priority}] ${a.id}`),console.log(` effect: ${a.effect} | scope: ${a.scope}`),console.log(` actions: ${a.actions.join(", ")}`),console.log(` risk levels: ${a.riskLevels.join(", ")}${l}`),a.conditions&&console.log(` conditions: ${JSON.stringify(a.conditions)}`),console.log("")}}}var bo=f(()=>{"use strict";ue();ss();d(ya,"rulesCommand")});var _o={};G(_o,{statusCommand:()=>Ea});import zt from"node:fs";import Tr from"node:path";import wa from"js-yaml";async function Ea(){let c=new z,e;try{e=c.loadConfig()}catch(l){console.error("Failed to load configuration:",l.message),process.exit(1)}console.log("Alfred \u2014 Status"),console.log("================"),console.log("");let t=[{name:"Telegram",enabled:e.telegram.enabled,configured:!!e.telegram.token},{name:"Discord",enabled:!!e.discord?.enabled,configured:!!e.discord?.token},{name:"WhatsApp",enabled:!!e.whatsapp?.enabled,configured:!!e.whatsapp?.dataPath},{name:"Matrix",enabled:!!e.matrix?.enabled,configured:!!e.matrix?.accessToken},{name:"Signal",enabled:!!e.signal?.enabled,configured:!!e.signal?.phoneNumber}];console.log("Messaging Adapters:");for(let l of t){let u=l.enabled?"enabled":l.configured?"configured (disabled)":"not configured",p=l.enabled?"+":"-";console.log(` [${p}] ${l.name}: ${u}`)}console.log(""),console.log("LLM Provider:");let s=e.llm.default;console.log(` Provider: ${s.provider}`),console.log(` Model: ${s.model}`),console.log(` API Key: ${s.apiKey?"set":"not set"}`),s.baseUrl&&console.log(` Base URL: ${s.baseUrl}`);for(let l of["strong","fast","embeddings","local"]){let u=e.llm[l];u&&console.log(` ${l}: ${u.provider}/${u.model}`)}console.log(""),console.log("Storage:");let r=Tr.resolve(e.storage.path),n=zt.existsSync(r);console.log(` Database: ${r}`),console.log(` Status: ${n?"exists":"not yet created"}`),console.log("");let o=Tr.resolve(e.security.rulesPath),i=0,a=0;if(zt.existsSync(o)&&zt.statSync(o).isDirectory()){let l=zt.readdirSync(o).filter(p=>p.endsWith(".yml")||p.endsWith(".yaml"));a=l.length;let u=new fe;for(let p of l){let m=Tr.join(o,p);try{let h=zt.readFileSync(m,"utf-8"),w=wa.load(h),E=u.loadFromObject(w);i+=E.length}catch{}}}console.log("Security:"),console.log(` Rules path: ${o}`),console.log(` Rule files: ${a}`),console.log(` Rules loaded: ${i}`),console.log(` Default effect: ${e.security.defaultEffect}`),e.security.ownerUserId&&console.log(` Owner user ID: ${e.security.ownerUserId}`),console.log(""),console.log("Logger:"),console.log(` Level: ${e.logger.level}`),console.log(` Pretty: ${e.logger.pretty}`)}var So=f(()=>{"use strict";ue();ss();d(Ea,"statusCommand")});var ko={};G(ko,{logsCommand:()=>_a});import Ta from"node:fs";import ba from"node:path";async function _a(c){let e=new z,t;try{t=e.loadConfig()}catch(n){console.error("Failed to load configuration:",n.message),process.exit(1)}let s=ba.resolve(t.storage.path);if(!Ta.existsSync(s)){console.log(`Database not found at: ${s}`),console.log("No audit log entries. Alfred has not been run yet, or the database path is incorrect.");return}let r;try{r=new me(s);let n=new pe(r.getDb()),o=n.count({}),i=n.query({limit:c});if(console.log("Alfred \u2014 Audit Log"),console.log("==================="),console.log(`Total entries: ${o}`),console.log(`Showing last ${Math.min(c,o)} entries:`),console.log(""),i.length===0){console.log("No audit log entries found.");return}for(let a of i){let l=a.timestamp.toISOString(),u=a.effect==="allow"?"ALLOW":"DENY ";console.log(` ${l} [${u}] ${a.action}`),console.log(` user: ${a.userId} | platform: ${a.platform} | risk: ${a.riskLevel}`),a.ruleId&&console.log(` rule: ${a.ruleId}`),a.chatId&&console.log(` chat: ${a.chatId}`),a.context&&console.log(` context: ${JSON.stringify(a.context)}`),console.log("")}}catch(n){console.error("Failed to read audit log:",n.message),process.exit(1)}finally{r&&r.close()}}var vo=f(()=>{"use strict";ue();Ds();d(_a,"logsCommand")});import{readFileSync as Sa}from"node:fs";import{fileURLToPath as ka}from"node:url";import{dirname as va,join as xa}from"node:path";function $a(){try{let c=va(ka(import.meta.url));for(let e of["../package.json","../../package.json"])try{let t=JSON.parse(Sa(xa(c,e),"utf-8"));if(t.version)return t.version}catch{}}catch{}return"0.0.0"}d($a,"getVersion");var xo=$a(),br=`
594
596
  Alfred CLI v${xo}
595
597
  Personal AI Assistant
596
598