@madh-io/alfred-ai 0.8.4 → 0.8.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/index.js +51 -54
- package/package.json +1 -1
package/bundle/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Sr=Object.defineProperty;var d=(c,e)=>Sr(c,"name",{value:e,configurable:!0});var h=(c,e)=>()=>(c&&(e=c(c=0)),e);var
|
|
2
|
+
var Sr=Object.defineProperty;var d=(c,e)=>Sr(c,"name",{value:e,configurable:!0});var h=(c,e)=>()=>(c&&(e=c(c=0)),e);var q=(c,e)=>{for(var t in e)Sr(c,t,{get:e[t],enumerable:!0})};import{z as g}from"zod";var br,kr,vr,xr,$r,Ir,Rr,Ar,ce,Oo,Uo,Po,Fo,jo,Bo,Wo,Ho,Xo,zo,qo,Ko,Ss,bs=h(()=>{"use strict";br=g.object({token:g.string().optional(),enabled:g.boolean()}),kr=g.object({token:g.string().optional(),enabled:g.boolean()}),vr=g.object({enabled:g.boolean(),dataPath:g.string()}),xr=g.object({homeserverUrl:g.string(),accessToken:g.string().optional(),userId:g.string().optional(),enabled:g.boolean()}),$r=g.object({apiUrl:g.string(),phoneNumber:g.string().optional(),enabled:g.boolean()}),Ir=g.object({path:g.string()}),Rr=g.object({level:g.enum(["trace","debug","info","warn","error","fatal"]),pretty:g.boolean(),auditLogPath:g.string().optional()}),Ar=g.object({rulesPath:g.string(),defaultEffect:g.enum(["allow","deny"]),ownerUserId:g.string().optional()}),ce=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()}),Oo=g.object({default:ce,strong:ce.optional(),fast:ce.optional(),embeddings:ce.optional(),local:ce.optional()}),Uo=g.union([ce,Oo]),Po=g.object({provider:g.enum(["brave","searxng","tavily","duckduckgo"]),apiKey:g.string().optional(),baseUrl:g.string().optional()}),Fo=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()})}),jo=g.object({provider:g.enum(["openai","groq"]),apiKey:g.string(),baseUrl:g.string().optional()}),Bo=g.object({serverUrl:g.string(),username:g.string(),password:g.string()}),Wo=g.object({clientId:g.string(),clientSecret:g.string(),refreshToken:g.string()}),Ho=g.object({clientId:g.string(),clientSecret:g.string(),tenantId:g.string(),refreshToken:g.string()}),Xo=g.object({provider:g.enum(["caldav","google","microsoft"]),caldav:Bo.optional(),google:Wo.optional(),microsoft:Ho.optional()}),zo=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()}),qo=g.object({servers:g.array(zo)}),Ko=g.object({enabled:g.boolean(),allowedLanguages:g.array(g.enum(["javascript","python"])).optional(),maxTimeoutMs:g.number().optional(),allowNetwork:g.boolean().optional()}),Ss=g.object({name:g.string(),telegram:br,discord:kr.optional(),whatsapp:vr.optional(),matrix:xr.optional(),signal:$r.optional(),llm:Uo,storage:Ir,logger:Rr,security:Ar,search:Po.optional(),email:Fo.optional(),speech:jo.optional(),calendar:Xo.optional(),mcp:qo.optional(),codeSandbox:Ko.optional()})});var ks,vs=h(()=>{"use strict";ks={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 Lr from"node:fs";import Vo from"node:path";import{config as Go}from"dotenv";import Yo from"js-yaml";function Mr(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]=Mr(n,r):t[s]=r}return t}function Zo(c){let e={...c};for(let[t,s]of Object.entries(Jo)){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 Jo,W,Nr=h(()=>{"use strict";bs();vs();d(Mr,"deepMerge");Jo={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(Zo,"applyEnvOverrides");W=class{static{d(this,"ConfigLoader")}loadConfig(e){Go();let t=e??process.env.ALFRED_CONFIG_PATH??"./config/default.yml",s={},r=Vo.resolve(t);if(Lr.existsSync(r)){let l=Lr.readFileSync(r,"utf-8"),u=Yo.load(l);u&&typeof u=="object"&&(s=u)}let n=Mr(ks,s),o=Zo(n),i=Ss.parse(o),a=i.llm;return a&&"provider"in a&&(i.llm={default:a}),i}}});var le=h(()=>{"use strict";bs();vs();Nr()});import xs from"pino";function st(c,e){let t=e??process.env.LOG_LEVEL??"info";if(t==="debug"||t==="trace"||process.env.NODE_ENV!=="production"){let r=xs.transport({target:"pino-pretty",options:{colorize:!0}});return xs({name:c,level:t},r)}return xs({name:c,level:t})}var Dr=h(()=>{"use strict";d(st,"createLogger")});import Ma from"pino";var Cr=h(()=>{"use strict"});var $s=h(()=>{"use strict";Dr();Cr()});var ve,Kt=h(()=>{"use strict";ve=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,
|
|
6
6
|
applied_at TEXT NOT NULL
|
|
7
7
|
)
|
|
8
|
-
`)}getCurrentVersion(){return this.db.prepare("SELECT MAX(version) as version FROM _migrations").get()?.version??0}migrate(e){let t=[...e].sort((r,n)=>r.version-n.version),s=this.getCurrentVersion();for(let r of t){if(r.version<=s)continue;this.db.transaction(()=>{r.up(this.db),this.db.prepare("INSERT INTO _migrations (version, description, applied_at) VALUES (?, ?, ?)").run(r.version,r.description,new Date().toISOString())})()}}getAppliedMigrations(){return this.db.prepare("SELECT version, applied_at FROM _migrations ORDER BY version ASC").all().map(t=>({version:t.version,appliedAt:t.applied_at}))}}});var Is,Rs=h(()=>{"use strict";
|
|
8
|
+
`)}getCurrentVersion(){return this.db.prepare("SELECT MAX(version) as version FROM _migrations").get()?.version??0}migrate(e){let t=[...e].sort((r,n)=>r.version-n.version),s=this.getCurrentVersion();for(let r of t){if(r.version<=s)continue;this.db.transaction(()=>{r.up(this.db),this.db.prepare("INSERT INTO _migrations (version, description, applied_at) VALUES (?, ?, ?)").run(r.version,r.description,new Date().toISOString())})()}}getAppliedMigrations(){return this.db.prepare("SELECT version, applied_at FROM _migrations ORDER BY version ASC").all().map(t=>({version:t.version,appliedAt:t.applied_at}))}}});var Is,Rs=h(()=>{"use strict";Kt();Is=[{version:1,description:"Initial schema \u2014 conversations, messages, users, audit_log",up(c){}},{version:2,description:"Add plugin_skills table for tracking loaded external plugins",up(c){c.exec(`
|
|
9
9
|
CREATE TABLE IF NOT EXISTS plugin_skills (
|
|
10
10
|
name TEXT PRIMARY KEY,
|
|
11
11
|
file_path TEXT NOT NULL,
|
|
@@ -148,7 +148,7 @@ var Sr=Object.defineProperty;var d=(c,e)=>Sr(c,"name",{value:e,configurable:!0})
|
|
|
148
148
|
created_at TEXT NOT NULL
|
|
149
149
|
);
|
|
150
150
|
CREATE INDEX IF NOT EXISTS idx_doc_chunks_doc ON document_chunks(document_id);
|
|
151
|
-
`)}}]});import Qo from"better-sqlite3";import ei from"node:fs";import ti from"node:path";var de,Or=h(()=>{"use strict";
|
|
151
|
+
`)}}]});import Qo from"better-sqlite3";import ei from"node:fs";import ti from"node:path";var de,Or=h(()=>{"use strict";Kt();Rs();de=class{static{d(this,"Database")}db;constructor(e){let t=ti.dirname(e);ei.mkdirSync(t,{recursive:!0}),this.db=new Qo(e),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.initTables(),this.runMigrations()}initTables(){this.db.exec(`
|
|
152
152
|
CREATE TABLE IF NOT EXISTS conversations (
|
|
153
153
|
id TEXT PRIMARY KEY,
|
|
154
154
|
platform TEXT NOT NULL,
|
|
@@ -243,9 +243,9 @@ var Sr=Object.defineProperty;var d=(c,e)=>Sr(c,"name",{value:e,configurable:!0})
|
|
|
243
243
|
UPDATE scheduled_actions
|
|
244
244
|
SET last_run_at = ?, next_run_at = ?
|
|
245
245
|
WHERE id = ?
|
|
246
|
-
`).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 Vr}from"node:crypto";var pt,Gr=h(()=>{"use strict";pt=class{static{d(this,"DocumentRepository")}db;constructor(e){this.db=e}createDocument(e,t,s,r){let n=Vr(),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=Vr(),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 As=h(()=>{"use strict";Or();Pr();Fr();jr();Br();Vt();Rs();Wr();Hr();Xr();zr();qr();Kr();Gr()});function pe(c){if(Ls[c])return Ls[c];for(let[e,t]of Object.entries(Ls))if(c.startsWith(e))return t}var Ls,di,V,xe=h(()=>{"use strict";Ls={"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}},di={maxInputTokens:8192,maxOutputTokens:4096};d(pe,"lookupContextWindow");V=class{static{d(this,"LLMProvider")}config;contextWindow=di;constructor(e){this.config=e}getContextWindow(){return this.contextWindow}async embed(e){}supportsEmbeddings(){return!1}}});import ui from"@anthropic-ai/sdk";var mt,Ms=h(()=>{"use strict";xe();mt=class extends V{static{d(this,"AnthropicProvider")}client;constructor(e){super(e)}async initialize(){this.client=new ui({apiKey:this.config.apiKey});let e=pe(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 pi from"openai";var Q,ht=h(()=>{"use strict";xe();Q=class extends V{static{d(this,"OpenAIProvider")}client;constructor(e){super(e)}async initialize(){this.client=new pi({apiKey:this.config.apiKey,baseURL:this.config.baseUrl});let e=pe(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,m=0,p=0;for await(let f of r){let E=f.choices[0];if(!E)continue;let w=E.delta;if(w?.content&&(a+=w.content,yield{type:"text_delta",text:w.content}),w?.tool_calls)for(let b of w.tool_calls)b.id?(n&&l.push({id:n,name:o,input:JSON.parse(i||"{}")}),n=b.id,o=b.function?.name,i=b.function?.arguments??"",yield{type:"tool_use_start",toolCall:{id:n,name:o}}):b.function?.arguments&&(i+=b.function.arguments,yield{type:"tool_use_delta",toolCall:{input:b.function.arguments}});E.finish_reason&&(u=E.finish_reason),f.usage&&(m=f.usage.prompt_tokens,p=f.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:m,outputTokens:p},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 ft,Ns=h(()=>{"use strict";ht();ft=class extends Q{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 gt,Ds=h(()=>{"use strict";xe();gt=class extends V{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=pe(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 f=await n.text();throw new Error(`Ollama API error (${n.status}): ${f}`)}if(!n.body)throw new Error("Ollama streaming response has no body");let o=n.body.getReader(),i=new TextDecoder,a="",l="",u=0,m=0,p=[];try{for(;;){let{done:f,value:E}=await o.read();if(f)break;a+=i.decode(E,{stream:!0});let w=a.split(`
|
|
247
|
-
`);a=w.pop()??"";for(let b of w){let k=b.trim();if(!k)continue;let T;try{T=JSON.parse(k)}catch{continue}if(T.message?.content&&(l+=T.message.content,yield{type:"text_delta",text:T.message.content}),T.message?.tool_calls)for(let x of T.message.tool_calls){let
|
|
248
|
-
`)};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 yt,Cs=h(()=>{"use strict";ht();yt=class extends
|
|
246
|
+
`).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 Vr}from"node:crypto";var pt,Gr=h(()=>{"use strict";pt=class{static{d(this,"DocumentRepository")}db;constructor(e){this.db=e}createDocument(e,t,s,r){let n=Vr(),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=Vr(),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 As=h(()=>{"use strict";Or();Pr();Fr();jr();Br();Kt();Rs();Wr();Hr();Xr();zr();qr();Kr();Gr()});function pe(c){if(Ls[c])return Ls[c];for(let[e,t]of Object.entries(Ls))if(c.startsWith(e))return t}var Ls,di,K,xe=h(()=>{"use strict";Ls={"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}},di={maxInputTokens:8192,maxOutputTokens:4096};d(pe,"lookupContextWindow");K=class{static{d(this,"LLMProvider")}config;contextWindow=di;constructor(e){this.config=e}getContextWindow(){return this.contextWindow}async embed(e){}supportsEmbeddings(){return!1}}});import ui from"@anthropic-ai/sdk";var mt,Ms=h(()=>{"use strict";xe();mt=class extends K{static{d(this,"AnthropicProvider")}client;constructor(e){super(e)}async initialize(){this.client=new ui({apiKey:this.config.apiKey});let e=pe(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 pi from"openai";var Z,ht=h(()=>{"use strict";xe();Z=class extends K{static{d(this,"OpenAIProvider")}client;constructor(e){super(e)}async initialize(){this.client=new pi({apiKey:this.config.apiKey,baseURL:this.config.baseUrl});let e=pe(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,m=0,p=0;for await(let f of r){let E=f.choices[0];if(!E)continue;let w=E.delta;if(w?.content&&(a+=w.content,yield{type:"text_delta",text:w.content}),w?.tool_calls)for(let b of w.tool_calls)b.id?(n&&l.push({id:n,name:o,input:JSON.parse(i||"{}")}),n=b.id,o=b.function?.name,i=b.function?.arguments??"",yield{type:"tool_use_start",toolCall:{id:n,name:o}}):b.function?.arguments&&(i+=b.function.arguments,yield{type:"tool_use_delta",toolCall:{input:b.function.arguments}});E.finish_reason&&(u=E.finish_reason),f.usage&&(m=f.usage.prompt_tokens,p=f.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:m,outputTokens:p},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 ft,Ns=h(()=>{"use strict";ht();ft=class extends Z{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 gt,Ds=h(()=>{"use strict";xe();gt=class extends K{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=pe(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 f=await n.text();throw new Error(`Ollama API error (${n.status}): ${f}`)}if(!n.body)throw new Error("Ollama streaming response has no body");let o=n.body.getReader(),i=new TextDecoder,a="",l="",u=0,m=0,p=[];try{for(;;){let{done:f,value:E}=await o.read();if(f)break;a+=i.decode(E,{stream:!0});let w=a.split(`
|
|
247
|
+
`);a=w.pop()??"";for(let b of w){let k=b.trim();if(!k)continue;let T;try{T=JSON.parse(k)}catch{continue}if(T.message?.content&&(l+=T.message.content,yield{type:"text_delta",text:T.message.content}),T.message?.tool_calls)for(let x of T.message.tool_calls){let U={id:`ollama_tool_${p.length}`,name:x.function.name,input:x.function.arguments};p.push(U),yield{type:"tool_use_start",toolCall:{id:U.id,name:U.name}},yield{type:"tool_use_delta",toolCall:{input:U.input}}}T.done&&(u=T.prompt_eval_count??0,m=T.eval_count??0,yield{type:"message_complete",response:{content:l,toolCalls:p.length>0?p:void 0,usage:{inputTokens:u,outputTokens:m},stopReason:p.length>0?"tool_use":"end_turn"}})}}if(a.trim()){let f;try{f=JSON.parse(a.trim())}catch{return}if(f.message?.content&&(l+=f.message.content,yield{type:"text_delta",text:f.message.content}),f.message?.tool_calls)for(let E of f.message.tool_calls){let w={id:`ollama_tool_${p.length}`,name:E.function.name,input:E.function.arguments};p.push(w),yield{type:"tool_use_start",toolCall:{id:w.id,name:w.name}},yield{type:"tool_use_delta",toolCall:{input:w.input}}}f.done&&(u=f.prompt_eval_count??0,m=f.eval_count??0,yield{type:"message_complete",response:{content:l,toolCalls:p.length>0?p:void 0,usage:{inputTokens:u,outputTokens:m},stopReason:p.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(`
|
|
248
|
+
`)};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 yt,Cs=h(()=>{"use strict";ht();yt=class extends Z{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 Os(c){switch(c.provider){case"anthropic":return new mt(c);case"openai":return new Z(c);case"openrouter":return new ft(c);case"ollama":return new gt(c);case"openwebui":return new yt(c);default:throw new Error(`Unknown LLM provider: ${c.provider}`)}}var Us=h(()=>{"use strict";Ms();ht();Ns();Ds();Cs();d(Os,"createLLMProvider")});function Ps(c){return new Vt(c)}var mi,Vt,Yr=h(()=>{"use strict";xe();Us();mi=["default","strong","fast","embeddings","local"],Vt=class extends K{static{d(this,"ModelRouter")}providers=new Map;multiConfig;constructor(e){super(e.default),this.multiConfig=e}async initialize(){for(let e of mi){let t=this.multiConfig[e];if(t){let s=Os(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(Ps,"createModelRouter")});function ne(c){return Math.ceil(c.length/3.5)}function Gt(c){if(typeof c.content=="string")return ne(c.content)+4;let e=4;for(let t of c.content)switch(t.type){case"text":e+=ne(t.text);break;case"image":e+=1e3;break;case"tool_use":e+=ne(t.name)+ne(JSON.stringify(t.input));break;case"tool_result":e+=ne(t.content);break}return e}var wt,Jr=h(()=>{"use strict";d(ne,"estimateTokens");d(Gt,"estimateMessageTokens");wt=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}).
|
|
249
249
|
|
|
250
250
|
## Core principles
|
|
251
251
|
- ACT, don't just talk. When the user asks you to do something, USE YOUR TOOLS immediately. Never say "I could do X" \u2014 just do X.
|
|
@@ -291,35 +291,35 @@ For complex tasks, work through multiple steps:
|
|
|
291
291
|
`;a+=`
|
|
292
292
|
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+=`
|
|
293
293
|
|
|
294
|
-
When the user tells you facts about themselves or preferences, use the memory tool to save them for future reference.`;return a}buildMessages(e){return e.filter(t=>t.role==="user"||t.role==="assistant").map(t=>{if(t.toolCalls){let s;try{s=JSON.parse(t.toolCalls)}catch{s=[]}let r=[];t.content&&r.push({type:"text",text:t.content});for(let n of s)r.push({type:"tool_use",id:n.id,name:n.name,input:n.input});return{role:t.role,content:r}}return{role:t.role,content:t.content}})}buildTools(e){return e.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}}});var Fs=h(()=>{"use strict";xe();Ms();ht();Ns();Ds();Cs();Us();Yr();Jr()});var Et,js=h(()=>{"use strict";Et=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 Tt,Zr=h(()=>{"use strict";js();Tt=class{static{d(this,"RuleEngine")}rules=[];rateLimiter=new Et;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 Qr,en,tn,me,sn=h(()=>{"use strict";Qr=["allow","deny"],en=["global","user","conversation","platform"],tn=["read","write","destructive","admin"],me=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"||!Qr.includes(s.effect))throw new Error(`Rule "${s.id}" has invalid "effect": expected one of ${Qr.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"||!en.includes(s.scope))throw new Error(`Rule "${s.id}" has invalid "scope": expected one of ${en.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(!tn.includes(n))throw new Error(`Rule "${s.id}" has invalid risk level "${n}": expected one of ${tn.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 hi from"node:crypto";var _t,rn=h(()=>{"use strict";_t=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:hi.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 Jt=h(()=>{"use strict";Zr();js();sn();rn()});var _,M=h(()=>{"use strict";_=class{static{d(this,"Skill")}}});var $e,nn=h(()=>{"use strict";$e=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 Ie,on=h(()=>{"use strict";Ie=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,m,p=d(()=>{l&&clearInterval(l),u&&clearTimeout(u),m&&clearTimeout(m)},"cleanup"),f=d(E=>{a||(a=!0,p(),i(E))},"finish");e.execute(t,s).then(E=>{this.logger.info({skill:r,success:E.success},"Skill execution completed"),f(E)},E=>{let w=E instanceof Error?E.message:String(E);this.logger.error({skill:r,error:w},"Skill execution failed"),f({success:!1,error:w})}),m=setTimeout(()=>{if(a)return;let E=o.getIdleMs();if(E>=12e4){let b=o.getSnapshot();this.logger.warn({skill:r,idleMs:E,state:b.state,iteration:b.iteration},"Agent inactive after initial timeout \u2014 aborting"),f({success:!1,error:`Skill "${r}" timed out \u2014 inactive for ${Math.round(E/1e3)}s (last state: ${b.state})`});return}let w=o.getSnapshot();this.logger.info({skill:r,idleMs:E,state:w.state,iteration:w.iteration,totalMs:w.totalElapsedMs},"Initial timeout reached but agent is active \u2014 extending"),l=setInterval(()=>{if(a){p();return}let b=o.getIdleMs(),k=o.getSnapshot();b>=12e4?(this.logger.warn({skill:r,idleMs:b,state:k.state,iteration:k.iteration,totalMs:k.totalElapsedMs},"Agent went inactive \u2014 aborting"),f({success:!1,error:`Skill "${r}" killed \u2014 inactive for ${Math.round(b/1e3)}s (last state: ${k.state})`})):this.logger.debug({skill:r,idleMs:b,state:k.state,iteration:k.iteration},"Agent still active, continuing...")},1e4)},n),u=setTimeout(()=>{if(a)return;let E=o.getSnapshot();this.logger.error({skill:r,totalMs:E.totalElapsedMs,state:E.state,iteration:E.iteration},"Absolute time limit reached \u2014 force killing agent"),f({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 he,Bs=h(()=>{"use strict";he=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 fi from"node:fs";import Ws from"node:path";var Zt,an=h(()=>{"use strict";M();Zt=class{static{d(this,"PluginLoader")}async loadFromDirectory(e){let t=Ws.resolve(e),s;try{s=await fi.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=Ws.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=Ws.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 gi,yi,Re,cn=h(()=>{"use strict";M();gi=/^[\d+\-*/().,%\s]|Math\.(sin|cos|tan|sqrt|pow|abs|floor|ceil|round|log|log2|log10|PI|E)/,yi=/^[0-9+\-*/().,\s%]*(Math\.(sin|cos|tan|sqrt|pow|abs|floor|ceil|round|log|log2|log10|PI|E)[(0-9+\-*/().,\s%]*)*$/,Re=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(!gi.test(r))return{success:!1,error:`Invalid expression: "${r}" contains disallowed characters`};if(!yi.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 Ae,ln=h(()=>{"use strict";M();Ae=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 Le,dn=h(()=>{"use strict";M();Le=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}**
|
|
294
|
+
When the user tells you facts about themselves or preferences, use the memory tool to save them for future reference.`;return a}buildMessages(e){return e.filter(t=>t.role==="user"||t.role==="assistant").map(t=>{if(t.toolCalls){let s;try{s=JSON.parse(t.toolCalls)}catch{s=[]}if(t.role==="assistant"){let o=s,i=[];t.content&&i.push({type:"text",text:t.content});for(let a of o)i.push({type:"tool_use",id:a.id,name:a.name,input:a.input});return{role:"assistant",content:i}}let r=s,n=[];for(let o of r)o.type==="tool_result"&&n.push(o);return n.length>0?{role:"user",content:n}:{role:"user",content:t.content||""}}return{role:t.role,content:t.content}})}buildTools(e){return e.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}}});var Fs=h(()=>{"use strict";xe();Ms();ht();Ns();Ds();Cs();Us();Yr();Jr()});var Et,js=h(()=>{"use strict";Et=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 Tt,Zr=h(()=>{"use strict";js();Tt=class{static{d(this,"RuleEngine")}rules=[];rateLimiter=new Et;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 Qr,en,tn,me,sn=h(()=>{"use strict";Qr=["allow","deny"],en=["global","user","conversation","platform"],tn=["read","write","destructive","admin"],me=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"||!Qr.includes(s.effect))throw new Error(`Rule "${s.id}" has invalid "effect": expected one of ${Qr.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"||!en.includes(s.scope))throw new Error(`Rule "${s.id}" has invalid "scope": expected one of ${en.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(!tn.includes(n))throw new Error(`Rule "${s.id}" has invalid risk level "${n}": expected one of ${tn.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 hi from"node:crypto";var _t,rn=h(()=>{"use strict";_t=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:hi.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 Yt=h(()=>{"use strict";Zr();js();sn();rn()});var _,L=h(()=>{"use strict";_=class{static{d(this,"Skill")}}});var $e,nn=h(()=>{"use strict";$e=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 Ie,on=h(()=>{"use strict";Ie=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,m,p=d(()=>{l&&clearInterval(l),u&&clearTimeout(u),m&&clearTimeout(m)},"cleanup"),f=d(E=>{a||(a=!0,p(),i(E))},"finish");e.execute(t,s).then(E=>{this.logger.info({skill:r,success:E.success},"Skill execution completed"),f(E)},E=>{let w=E instanceof Error?E.message:String(E);this.logger.error({skill:r,error:w},"Skill execution failed"),f({success:!1,error:w})}),m=setTimeout(()=>{if(a)return;let E=o.getIdleMs();if(E>=12e4){let b=o.getSnapshot();this.logger.warn({skill:r,idleMs:E,state:b.state,iteration:b.iteration},"Agent inactive after initial timeout \u2014 aborting"),f({success:!1,error:`Skill "${r}" timed out \u2014 inactive for ${Math.round(E/1e3)}s (last state: ${b.state})`});return}let w=o.getSnapshot();this.logger.info({skill:r,idleMs:E,state:w.state,iteration:w.iteration,totalMs:w.totalElapsedMs},"Initial timeout reached but agent is active \u2014 extending"),l=setInterval(()=>{if(a){p();return}let b=o.getIdleMs(),k=o.getSnapshot();b>=12e4?(this.logger.warn({skill:r,idleMs:b,state:k.state,iteration:k.iteration,totalMs:k.totalElapsedMs},"Agent went inactive \u2014 aborting"),f({success:!1,error:`Skill "${r}" killed \u2014 inactive for ${Math.round(b/1e3)}s (last state: ${k.state})`})):this.logger.debug({skill:r,idleMs:b,state:k.state,iteration:k.iteration},"Agent still active, continuing...")},1e4)},n),u=setTimeout(()=>{if(a)return;let E=o.getSnapshot();this.logger.error({skill:r,totalMs:E.totalElapsedMs,state:E.state,iteration:E.iteration},"Absolute time limit reached \u2014 force killing agent"),f({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 he,Bs=h(()=>{"use strict";he=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 fi from"node:fs";import Ws from"node:path";var Jt,an=h(()=>{"use strict";L();Jt=class{static{d(this,"PluginLoader")}async loadFromDirectory(e){let t=Ws.resolve(e),s;try{s=await fi.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=Ws.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=Ws.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 gi,yi,Re,cn=h(()=>{"use strict";L();gi=/^[\d+\-*/().,%\s]|Math\.(sin|cos|tan|sqrt|pow|abs|floor|ceil|round|log|log2|log10|PI|E)/,yi=/^[0-9+\-*/().,\s%]*(Math\.(sin|cos|tan|sqrt|pow|abs|floor|ceil|round|log|log2|log10|PI|E)[(0-9+\-*/().,\s%]*)*$/,Re=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(!gi.test(r))return{success:!1,error:`Invalid expression: "${r}" contains disallowed characters`};if(!yi.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 Ae,ln=h(()=>{"use strict";L();Ae=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 Le,dn=h(()=>{"use strict";L();Le=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}**
|
|
295
295
|
${a.url}
|
|
296
296
|
${a.snippet}`).join(`
|
|
297
297
|
|
|
298
298
|
`);return{success:!0,data:{query:s,results:o},display:`Search results for "${s}":
|
|
299
299
|
|
|
300
|
-
${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(),m=this.extractDdgUrl(l);u&&m&&o.push({url:m,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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/\s+/g," ")}}});var Me,un=h(()=>{"use strict";
|
|
300
|
+
${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(),m=this.extractDdgUrl(l);u&&m&&o.push({url:m,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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/\s+/g," ")}}});var Me,un=h(()=>{"use strict";L();Me=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 m=this.parseTriggerAt(r,t.timezone);if(!m)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(m.getTime()<=Date.now())return{success:!1,error:`The time "${r}" is in the past. Please specify a future time.`};o=m}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 f=s?new Date(s.year,s.month,s.day,e,t,0,0):new Date;return s||f.setHours(e,t,0,0),f}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 f=i.formatToParts(n),E=parseInt(f.find(v=>v.type==="year").value,10),w=parseInt(f.find(v=>v.type==="month").value,10)-1,b=parseInt(f.find(v=>v.type==="day").value,10),k=new Date(Date.UTC(E,w,b,e,t,0)),T=i.formatToParts(k),x=parseInt(T.find(v=>v.type==="hour").value,10),U=parseInt(T.find(v=>v.type==="minute").value,10),X=(e-x)*60+(t-U);return k=new Date(k.getTime()+X*6e4),k}let a=o,l=i.formatToParts(a),u=parseInt(l.find(f=>f.type==="hour").value,10),m=parseInt(l.find(f=>f.type==="minute").value,10),p=(e-u)*60+(t-m);return a=new Date(a.getTime()+p*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:
|
|
301
301
|
${s.map(r=>`- ${r.reminderId}: "${r.message}" (triggers at ${r.triggerAt})`).join(`
|
|
302
|
-
`)}`}}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 Ne,pn=h(()=>{"use strict";
|
|
302
|
+
`)}`}}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 Ne,pn=h(()=>{"use strict";L();Ne=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)
|
|
303
303
|
${r.content.slice(0,100)}${r.content.length>100?"\u2026":""}`).join(`
|
|
304
304
|
`);return{success:!0,data:t,display:`${t.length} note(s):
|
|
305
305
|
${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)
|
|
306
306
|
${o.content.slice(0,100)}${o.content.length>100?"\u2026":""}`).join(`
|
|
307
307
|
`);return{success:!0,data:r,display:`Found ${r.length} note(s):
|
|
308
|
-
${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 wi,De,mn=h(()=>{"use strict";
|
|
308
|
+
${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 wi,De,mn=h(()=>{"use strict";L();wi={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"},De=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=wi[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}
|
|
309
309
|
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}¤t_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 Ei}from"node:child_process";function fn(c){return c.length>hn?c.slice(0,hn)+`
|
|
310
|
-
[output truncated]`:c}var Ti,hn,Ce,gn=h(()=>{"use strict";
|
|
310
|
+
[output truncated]`:c}var Ti,hn,Ce,gn=h(()=>{"use strict";L();Ti=3e4,hn=1e4;d(fn,"truncate");Ce=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:Ti,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:
|
|
311
311
|
${fn(i)}`),a&&u.push(`stderr:
|
|
312
312
|
${fn(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(`
|
|
313
313
|
|
|
314
|
-
`),...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=>{Ei(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 Oe,yn=h(()=>{"use strict";
|
|
314
|
+
`),...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=>{Ei(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 Oe,yn=h(()=>{"use strict";L();Oe=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):
|
|
315
315
|
${r.map(n=>`- ${n.key}: "${n.value}"`).join(`
|
|
316
316
|
`)}`}}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}:
|
|
317
317
|
${r.map(o=>`- [${o.category}] ${o.key}: "${o.value}"`).join(`
|
|
318
318
|
`)}`}}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):
|
|
319
319
|
${r.map(n=>`- ${n.key}: "${n.value}" (score: ${n.score.toFixed(2)})`).join(`
|
|
320
|
-
`)}`}}}});var _i,Si,bi,Ue,wn=h(()=>{"use strict";
|
|
320
|
+
`)}`}}}});var _i,Si,bi,Ue,wn=h(()=>{"use strict";L();Bs();_i=5,Si=15,bi=12e4,Ue=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:bi,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 he(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(Si,Math.round(n))):_i,i=t.onProgress??this.onProgress,a=t.tracker?t.tracker:new he(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.",m=s;r&&typeof r=="string"&&(m=`${s}
|
|
321
321
|
|
|
322
|
-
Additional context: ${r}`);let p=[{role:"user",content:m}];try{let f=0,E=0,w=0;for(;;){a.ping("llm_call",{iteration:f,maxIterations:o});let b=await this.llm.complete({messages:p,system:u,tools:l.length>0?l:void 0,maxTokens:2048,tier:"strong"});if(E+=b.usage.inputTokens,w+=b.usage.outputTokens,a.ping("processing",{iteration:f,maxIterations:o}),!b.toolCalls||b.toolCalls.length===0||f>=o)return a.ping("done",{iteration:f,maxIterations:o}),{success:!0,data:{response:b.content,iterations:f,usage:{inputTokens:E,outputTokens:w}},display:b.content};f++;let k=[];b.content&&k.push({type:"text",text:b.content});for(let x of b.toolCalls)k.push({type:"tool_use",id:x.id,name:x.name,input:x.input});p.push({role:"assistant",content:k});let T=[];for(let x of b.toolCalls){a.ping("tool_call",{iteration:f,maxIterations:o,tool:x.name});let
|
|
322
|
+
Additional context: ${r}`);let p=[{role:"user",content:m}];try{let f=0,E=0,w=0;for(;;){a.ping("llm_call",{iteration:f,maxIterations:o});let b=await this.llm.complete({messages:p,system:u,tools:l.length>0?l:void 0,maxTokens:2048,tier:"strong"});if(E+=b.usage.inputTokens,w+=b.usage.outputTokens,a.ping("processing",{iteration:f,maxIterations:o}),!b.toolCalls||b.toolCalls.length===0||f>=o)return a.ping("done",{iteration:f,maxIterations:o}),{success:!0,data:{response:b.content,iterations:f,usage:{inputTokens:E,outputTokens:w}},display:b.content};f++;let k=[];b.content&&k.push({type:"text",text:b.content});for(let x of b.toolCalls)k.push({type:"tool_use",id:x.id,name:x.name,input:x.input});p.push({role:"assistant",content:k});let T=[];for(let x of b.toolCalls){a.ping("tool_call",{iteration:f,maxIterations:o,tool:x.name});let U=await this.executeSubAgentTool(x,t);T.push({type:"tool_result",tool_use_id:x.id,content:U.content,is_error:U.isError})}p.push({role:"user",content:T})}}catch(f){return{success:!1,error:`Sub-agent failed: ${f instanceof Error?f.message:String(f)}`}}}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 Pe,En=h(()=>{"use strict";L();Pe=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 f of r.fetch(u,{envelope:!0,flags:!0})){let E=f.envelope?.from?.[0],w=E?E.name?`${E.name} <${E.address}>`:E.address??"unknown":"unknown";o.push({seq:f.seq,from:w,subject:f.envelope?.subject??"(no subject)",date:f.envelope?.date?.toISOString()??"",seen:f.flags?.has("\\Seen")??!1})}o.reverse();let m=o.length===0?"No messages found.":o.map((f,E)=>{let w=f.seen?"":" [UNREAD]";return`${E+1}. [#${f.seq}]${w} ${f.subject}
|
|
323
323
|
From: ${f.from}
|
|
324
324
|
Date: ${f.date}`}).join(`
|
|
325
325
|
|
|
@@ -346,20 +346,20 @@ Message ID: ${o.messageId}`}}extractTextBody(e){let t=e.split(/\r?\n\r?\n/);if(t
|
|
|
346
346
|
\r
|
|
347
347
|
`);if(u>=0)return this.decodeBody(i.slice(u+4))}}return this.decodeBody(t.slice(1).join(`
|
|
348
348
|
|
|
349
|
-
`).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 Tn,Fe,_n=h(()=>{"use strict";
|
|
349
|
+
`).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 Tn,Fe,_n=h(()=>{"use strict";L();Tn=1e5,Fe=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")??"",m=await l.text(),p=m.length>Tn,f=p?m.slice(0,Tn)+`
|
|
350
350
|
|
|
351
351
|
[... truncated]`:m,E=f;u.includes("text/html")&&(E=this.stripHtml(f).slice(0,1e4));let w={status:l.status,statusText:l.statusText,contentType:u,bodyLength:m.length,truncated:p,body:f};return l.ok?{success:!0,data:w,display:`HTTP ${l.status} OK (${m.length} bytes)
|
|
352
352
|
|
|
353
353
|
${E.slice(0,5e3)}`}:{success:!0,data:w,display:`HTTP ${l.status} ${l.statusText}
|
|
354
354
|
|
|
355
|
-
${E.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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/\s+/g," ").trim()}}});import
|
|
355
|
+
${E.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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/\s+/g," ").trim()}}});import C from"node:fs";import St from"node:path";var Hs,je,Sn=h(()=>{"use strict";L();Hs=5e5,je=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"'};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 St.resolve(s)}readFile(e){try{let t=C.statSync(e);if(t.isDirectory())return{success:!1,error:`"${e}" is a directory, not a file. Use action "list" instead.`};if(t.size>Hs){let r=C.readFileSync(e,"utf-8").slice(0,Hs);return{success:!0,data:{path:e,size:t.size,truncated:!0},display:`${e} (${t.size} bytes, truncated to ${Hs}):
|
|
356
356
|
|
|
357
|
-
${r}`}}let s=
|
|
358
|
-
`);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=
|
|
357
|
+
${r}`}}let s=C.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=St.dirname(e);return C.mkdirSync(s,{recursive:!0}),C.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 C.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=C.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(`
|
|
358
|
+
`);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=C.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}
|
|
359
359
|
Size: ${t.size} bytes
|
|
360
|
-
Modified: ${s.modified}`}}catch(t){return{success:!1,error:`Cannot stat "${e}": ${t.message}`}}}fileExists(e){let t=
|
|
360
|
+
Modified: ${s.modified}`}}catch(t){return{success:!1,error:`Cannot stat "${e}": ${t.message}`}}}fileExists(e){let t=C.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=St.dirname(e);C.mkdirSync(s,{recursive:!0});let r=Buffer.from(t,"base64");return C.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=St.dirname(s);return C.mkdirSync(r,{recursive:!0}),C.renameSync(e,s),{success:!0,data:{from:e,to:s},display:`Moved ${e} \u2192 ${s}`}}catch{try{return C.copyFileSync(e,s),C.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=St.dirname(s);return C.mkdirSync(r,{recursive:!0}),C.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 C.existsSync(e)?C.statSync(e).isDirectory()?{success:!1,error:`"${e}" is a directory. Use shell for directory deletion.`}:(C.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 Be}from"node:child_process";var We,bn=h(()=>{"use strict";L();We=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=Be("pbpaste",{encoding:"utf-8",timeout:5e3});break;case"win32":e=Be("powershell -NoProfile -Command Get-Clipboard",{encoding:"utf-8",timeout:5e3}).replace(/\r\n$/,"");break;default:e=Be("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)+`
|
|
361
361
|
|
|
362
|
-
[... 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":Be("pbcopy",{input:e,timeout:5e3});break;case"win32":Be('powershell -NoProfile -Command "$input | Set-Clipboard"',{input:e,timeout:5e3});break;default:Be("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 bt}from"node:child_process";import kn from"node:path";import ki from"node:os";var He,vn=h(()=>{"use strict";
|
|
362
|
+
[... 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":Be("pbcopy",{input:e,timeout:5e3});break;case"win32":Be('powershell -NoProfile -Command "$input | Set-Clipboard"',{input:e,timeout:5e3});break;default:Be("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 bt}from"node:child_process";import kn from"node:path";import ki from"node:os";var He,vn=h(()=>{"use strict";L();He=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=kn.join(ki.homedir(),"Desktop"),n=e.path||kn.join(r,`screenshot-${s}.png`);try{switch(process.platform){case"darwin":bt(`screencapture -x "${n}"`,{timeout:1e4});break;case"win32":bt(`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{bt(`scrot "${n}"`,{timeout:1e4})}catch{try{bt(`import -window root "${n}"`,{timeout:1e4})}catch{bt(`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 vi from"node:path";import xi from"node:os";var xn,Xe,$n=h(()=>{"use strict";L();xn=5e4,Xe=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
|
|
363
363
|
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(`
|
|
364
364
|
(() => {
|
|
365
365
|
document.querySelectorAll('script, style, noscript').forEach(el => el.remove());
|
|
@@ -371,9 +371,9 @@ Or add it to Alfred: npm install puppeteer`};switch(s){case"open":return this.op
|
|
|
371
371
|
|
|
372
372
|
`).trim();return{success:!0,data:{url:r.url(),title:n,length:o.length},display:`**${n}** (${r.url()})
|
|
373
373
|
|
|
374
|
-
${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||vi.join(xi.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 ze,In=h(()=>{"use strict";
|
|
374
|
+
${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||vi.join(xi.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 ze,In=h(()=>{"use strict";L();ze=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:
|
|
375
375
|
${s.map(r=>`- ${r}`).join(`
|
|
376
|
-
`)}`:"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
|
|
376
|
+
`)}`:"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 V,kt=h(()=>{"use strict";V=class{static{d(this,"CalendarProvider")}}});var Rn={};q(Rn,{CalDAVProvider:()=>Zt});var Zt,Xs=h(()=>{"use strict";kt();Zt=class extends V{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(`
|
|
377
377
|
`).map(p=>p.trim()),r=d(p=>s.find(f=>f.startsWith(p+":"))?.slice(p.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 m=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:m}}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
|
|
378
378
|
VERSION:2.0\r
|
|
379
379
|
PRODID:-//Alfred//EN\r
|
|
@@ -389,11 +389,11 @@ BEGIN:VEVENT\r
|
|
|
389
389
|
`),r+=`DTSTAMP:${s(new Date)}\r
|
|
390
390
|
`,r+=`END:VEVENT\r
|
|
391
391
|
END:VCALENDAR\r
|
|
392
|
-
`,r}}});var An={};
|
|
392
|
+
`,r}}});var An={};q(An,{GoogleCalendarProvider:()=>Qt});var Qt,zs=h(()=>{"use strict";kt();Qt=class extends V{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 Ln={};q(Ln,{MicrosoftCalendarProvider:()=>es});var es,qs=h(()=>{"use strict";kt();es=class extends V{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 vt(c){switch(c.provider){case"caldav":{if(!c.caldav)throw new Error("CalDAV config missing");let{CalDAVProvider:e}=await Promise.resolve().then(()=>(Xs(),Rn)),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(()=>(zs(),An)),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(()=>(qs(),Ln)),t=new e(c.microsoft);return await t.initialize(),t}default:throw new Error(`Unknown calendar provider: ${c.provider}`)}}var Mn=h(()=>{"use strict";d(vt,"createCalendarProvider")});var fe,Nn=h(()=>{"use strict";L();fe=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(`
|
|
393
393
|
`);return{success:!0,data:r,display:`${r.length} event(s):
|
|
394
394
|
${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):
|
|
395
395
|
${r.conflicts.map(o=>this.formatEvent(o)).join(`
|
|
396
|
-
`)}`;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 Dn=h(()=>{"use strict";kt();Xs();zs();qs();Mn();Nn()});var qe,Cn=h(()=>{"use strict";
|
|
396
|
+
`)}`;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 Dn=h(()=>{"use strict";kt();Xs();zs();qs();Mn();Nn()});var qe,Cn=h(()=>{"use strict";L();qe=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}**
|
|
397
397
|
|
|
398
398
|
Enter this code on your other platform within 10 minutes using:
|
|
399
399
|
"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 m=this.users.getLinkedUsers(i);for(let p of m)this.users.setMasterUser(p.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.
|
|
@@ -401,18 +401,18 @@ Enter this code on your other platform within 10 minutes using:
|
|
|
401
401
|
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:
|
|
402
402
|
"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:
|
|
403
403
|
${r.join(`
|
|
404
|
-
`)}`}}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 Ke,On=h(()=>{"use strict";
|
|
404
|
+
`)}`}}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 Ke,On=h(()=>{"use strict";L();Ke=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:
|
|
405
405
|
${r.join(`
|
|
406
|
-
`)}`}}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 Ve,Un=h(()=>{"use strict";
|
|
406
|
+
`)}`}}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 Ve,Un=h(()=>{"use strict";L();Ve=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 p=parseInt(o,10);if(isNaN(p)||p<=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 p=new Date(o);if(isNaN(p.getTime()))return{success:!1,error:"For once schedule, value must be a valid ISO date string"};if(p.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}),m=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 ${m}, 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:
|
|
407
407
|
${s.join(`
|
|
408
408
|
`)}`}}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 ge,Ks=h(()=>{"use strict";ge=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(`
|
|
409
|
-
`),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 ye,Vs=h(()=>{"use strict";
|
|
409
|
+
`),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 ye,Vs=h(()=>{"use strict";L();ye=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 xt,Pn=h(()=>{"use strict";Ks();Vs();xt=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 ge(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 ye(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 Fn=h(()=>{"use strict";Ks();Vs();Pn()});import{spawn as $i}from"node:child_process";import Ge from"node:fs";import Gs from"node:path";import Ii from"node:os";import Ri from"node:crypto";var we,Ys=h(()=>{"use strict";we=class{static{d(this,"CodeExecutor")}async execute(e,t,s){let r=Math.min(s?.timeout??3e4,12e4),n=Gs.join(Ii.tmpdir(),`alfred-sandbox-${Ri.randomUUID()}`);Ge.mkdirSync(n,{recursive:!0});try{let o=t==="javascript"?"js":"py",i=Gs.join(n,`script.${o}`);Ge.writeFileSync(i,e);let a=t==="javascript"?"node":process.platform==="win32"?"python":"python3",l=[i],u=Date.now();return await new Promise(m=>{let p=$i(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"]}),f="",E="";p.stdout.on("data",w=>{f+=w.toString()}),p.stderr.on("data",w=>{E+=w.toString()}),p.on("close",w=>{let b=Date.now()-u,k=[];try{let T=Ge.readdirSync(n).filter(x=>!x.startsWith("script."));for(let x of T){let U=Gs.join(n,x),X=Ge.statSync(U);if(X.isFile()&&X.size<1e7){let v=Ge.readFileSync(U),P=x.endsWith(".png")?"image/png":x.endsWith(".jpg")||x.endsWith(".jpeg")?"image/jpeg":x.endsWith(".svg")?"image/svg+xml":x.endsWith(".csv")?"text/csv":x.endsWith(".json")?"application/json":"application/octet-stream";k.push({name:x,data:v,mimeType:P})}}}catch{}m({stdout:f.slice(0,5e4),stderr:E.slice(0,1e4),exitCode:w??1,files:k.length>0?k:void 0,durationMs:b})}),p.on("error",w=>{m({stdout:"",stderr:w.message,exitCode:1,durationMs:Date.now()-u})}),p.stdin.end()})}finally{try{Ge.rmSync(n,{recursive:!0,force:!0})}catch{}}}}});var $t,jn=h(()=>{"use strict";L();Ys();$t=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 we;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)};
|
|
410
410
|
${r}`:a=`INPUT_DATA = ${JSON.stringify(o)}
|
|
411
411
|
${r}`);let l=await this.executor.execute(a,n,{timeout:i}),u=[l.stdout?`Output:
|
|
412
412
|
${l.stdout}`:"",l.stderr?`Errors:
|
|
413
413
|
${l.stderr}`:"",`Exit code: ${l.exitCode}`,`Duration: ${l.durationMs}ms`].filter(Boolean).join(`
|
|
414
414
|
|
|
415
|
-
`);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 Bn=h(()=>{"use strict";Ys();jn()});var Ye,Wn=h(()=>{"use strict";
|
|
415
|
+
`);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 Bn=h(()=>{"use strict";Ys();jn()});var Ye,Wn=h(()=>{"use strict";L();Ye=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(`
|
|
416
416
|
|
|
417
417
|
`);return{success:!0,data:o,display:`Found ${o.length} relevant chunk(s):
|
|
418
418
|
|
|
@@ -424,13 +424,10 @@ ${i}`}}summarize(e){let t=e.document_id;if(!t||typeof t!="string")return{success
|
|
|
424
424
|
|
|
425
425
|
${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(`
|
|
426
426
|
`);return{success:!0,data:n,display:`${n.length} document(s):
|
|
427
|
-
${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
|
|
427
|
+
${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 ts={};q(ts,{ActivityTracker:()=>he,BackgroundTaskSkill:()=>Ke,BrowserSkill:()=>Xe,CalculatorSkill:()=>Re,CalendarProvider:()=>V,CalendarSkill:()=>fe,ClipboardSkill:()=>We,CodeExecutionSkill:()=>$t,CodeExecutor:()=>we,CrossPlatformSkill:()=>qe,DelegateSkill:()=>Ue,DocumentSkill:()=>Ye,EmailSkill:()=>Pe,FileSkill:()=>je,HttpSkill:()=>Fe,MCPClient:()=>ge,MCPManager:()=>xt,MCPSkillAdapter:()=>ye,MemorySkill:()=>Oe,NoteSkill:()=>Ne,PluginLoader:()=>Jt,ProfileSkill:()=>ze,ReminderSkill:()=>Me,ScheduledTaskSkill:()=>Ve,ScreenshotSkill:()=>He,ShellSkill:()=>Ce,Skill:()=>_,SkillRegistry:()=>$e,SkillSandbox:()=>Ie,SystemInfoSkill:()=>Ae,WeatherSkill:()=>De,WebSearchSkill:()=>Le,createCalendarProvider:()=>vt});var It=h(()=>{"use strict";L();nn();on();Bs();an();cn();ln();dn();un();pn();mn();gn();yn();wn();En();_n();Sn();bn();vn();$n();In();Dn();Cn();On();Un();Fn();Bn();Wn()});var Rt,Js=h(()=>{"use strict";Rt=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 Hn from"node:fs";import Xn from"node:path";var Zs,Ai,Li,At,Qs=h(()=>{"use strict";Fs();Zs=10,Ai=.85,Li=1e5,At=class{static{d(this,"MessagePipeline")}promptBuilder;llm;conversationManager;users;logger;skillRegistry;skillSandbox;securityManager;memoryRepo;speechTranscriber;inboxPath;embeddingService;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.promptBuilder=new wt}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.memoryRepo)try{if(this.embeddingService&&e.text&&this.llm.supportsEmbeddings()){let v=await this.embeddingService.semanticSearch(n,e.text,10),P=this.memoryRepo.getRecentForPrompt(n,5),D=new Set;a=[];for(let M of v)D.has(M.key)||(D.add(M.key),a.push(M));for(let M of P)D.has(M.key)||(D.add(M.key),a.push(M))}else a=this.memoryRepo.getRecentForPrompt(n,20)}catch(v){this.logger.debug({err:v},"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(v){this.logger.debug({err:v},"Profile loading failed")}let u=l?.timezone||Intl.DateTimeFormat().resolvedOptions().timeZone,m=this.skillRegistry?this.skillRegistry.getAll().map(v=>v.metadata):void 0,p=m?this.promptBuilder.buildTools(m):void 0,f=this.promptBuilder.buildSystemPrompt({memories:a,skills:m,userProfile:l}),E=this.buildActiveAgentStatus();E&&(f+=`
|
|
428
428
|
|
|
429
|
-
`+E);let w=this.promptBuilder.buildMessages(i),b=await this.buildUserContent(e,t);w.push({role:"user",content:b});let k=this.trimToContextWindow(f,w),T,x=0;for(t?.("Thinking...");;){if(T=await this.llm.complete({messages:k,system:f,tools:p&&p.length>0?p:void 0}),!T.toolCalls||T.toolCalls.length===0||x>=Zs){x>=Zs&&T.toolCalls?.length&&this.logger.warn({iteration:x},"Max tool iterations reached, stopping loop");break}x++,this.logger.info({iteration:x,toolCalls:T.toolCalls.length},"Processing tool calls");let v=[];T.content&&v.push({type:"text",text:T.content});for(let
|
|
430
|
-
`),
|
|
431
|
-
`);this.conversationManager.addMessage(o.id,"assistant",`${T.content?T.content+`
|
|
432
|
-
`:""}${F}`,JSON.stringify(T.toolCalls)),this.conversationManager.addMessage(o.id,"user",A),k.push({role:"user",content:U}),x<Zs&&t?.("Thinking...")}let O=T.content||"(no response)";this.conversationManager.addMessage(o.id,"assistant",O);let z=Date.now()-s;return this.logger.info({duration:z,tokens:T.usage,stopReason:T.stopReason,toolIterations:x},"Message processed"),O}catch(r){throw this.logger.error({err:r},"Failed to process message"),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(()=>(It(),ss));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(`
|
|
433
|
-
`)}trimToContextWindow(e,t){let s=this.llm.getContextWindow(),r=Math.floor(s.maxInputTokens*Ai),n=ne(e),o=t[t.length-1],i=Yt(o),a=n+i+200,l=r-a;if(l<=0)return this.logger.warn({maxInputTokens:r,systemTokens:n,latestTokens:i},"Context window very tight, sending only latest message"),[o];let u=[];for(let p=t.length-2;p>=0;p--){let f=Yt(t[p]);if(f>l)break;l-=f,u.unshift(t[p])}let m=t.length-1-u.length;return m>0&&(this.logger.info({trimmedCount:m,totalMessages:t.length,maxInputTokens:r},"Trimmed conversation history to fit context window"),u.unshift({role:"user",content:`[System note: ${m} older message(s) were omitted to fit the context window. The conversation continues from the most recent messages.]`})),u.push(o),u}async buildUserContent(e,t){let s=e.attachments?.filter(o=>o.data)??[];if(s.length===0)return e.text;let r=[];for(let o of s)if(o.type==="image"&&o.data)r.push({type:"image",source:{type:"base64",media_type:o.mimeType??"image/jpeg",data:o.data.toString("base64")}}),this.logger.info({mimeType:o.mimeType,size:o.size},"Image attached to LLM request");else if(o.type==="audio"&&o.data)if(this.speechTranscriber){t?.("Transcribing voice...");try{let i=await this.speechTranscriber.transcribe(o.data,o.mimeType??"audio/ogg"),a=e.text==="[Voice message]"?"":`${e.text}
|
|
429
|
+
`+E);let w=this.promptBuilder.buildMessages(i),b=await this.buildUserContent(e,t);w.push({role:"user",content:b});let k=this.trimToContextWindow(f,w),T,x=0;for(t?.("Thinking...");;){if(T=await this.llm.complete({messages:k,system:f,tools:p&&p.length>0?p:void 0}),!T.toolCalls||T.toolCalls.length===0||x>=Zs){x>=Zs&&T.toolCalls?.length&&this.logger.warn({iteration:x},"Max tool iterations reached, stopping loop");break}x++,this.logger.info({iteration:x,toolCalls:T.toolCalls.length},"Processing tool calls");let v=[];T.content&&v.push({type:"text",text:T.content});for(let D of T.toolCalls)v.push({type:"tool_use",id:D.id,name:D.name,input:D.input});k.push({role:"assistant",content:v});let P=await this.executeToolCallsParallel(T.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",T.content??"",JSON.stringify(T.toolCalls)),this.conversationManager.addMessage(o.id,"user","",JSON.stringify(P)),k.push({role:"user",content:P}),x<Zs&&t?.("Thinking...")}let U=T.content||"(no response)";this.conversationManager.addMessage(o.id,"assistant",U);let X=Date.now()-s;return this.logger.info({duration:X,tokens:T.usage,stopReason:T.stopReason,toolIterations:x},"Message processed"),U}catch(r){throw this.logger.error({err:r},"Failed to process message"),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(()=>(It(),ts));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(`
|
|
430
|
+
`)}trimToContextWindow(e,t){let s=this.llm.getContextWindow(),r=Math.floor(s.maxInputTokens*Ai),n=ne(e),o=t[t.length-1],i=Gt(o),a=n+i+200,l=r-a;if(l<=0)return this.logger.warn({maxInputTokens:r,systemTokens:n,latestTokens:i},"Context window very tight, sending only latest message"),[o];let u=[];for(let p=t.length-2;p>=0;p--){let f=Gt(t[p]);if(f>l)break;l-=f,u.unshift(t[p])}let m=t.length-1-u.length;return m>0&&(this.logger.info({trimmedCount:m,totalMessages:t.length,maxInputTokens:r},"Trimmed conversation history to fit context window"),u.unshift({role:"user",content:`[System note: ${m} older message(s) were omitted to fit the context window. The conversation continues from the most recent messages.]`})),u.push(o),u}async buildUserContent(e,t){let s=e.attachments?.filter(o=>o.data)??[];if(s.length===0)return e.text;let r=[];for(let o of s)if(o.type==="image"&&o.data)r.push({type:"image",source:{type:"base64",media_type:o.mimeType??"image/jpeg",data:o.data.toString("base64")}}),this.logger.info({mimeType:o.mimeType,size:o.size},"Image attached to LLM request");else if(o.type==="audio"&&o.data)if(this.speechTranscriber){t?.("Transcribing voice...");try{let i=await this.speechTranscriber.transcribe(o.data,o.mimeType??"audio/ogg"),a=e.text==="[Voice message]"?"":`${e.text}
|
|
434
431
|
|
|
435
432
|
`;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"})]
|
|
436
433
|
[Saved to: ${i}]`;if(a&&o.data.length<=Li){let u=o.data.toString("utf-8");l+=`
|
|
@@ -445,29 +442,29 @@ Error: ${o.error}`;await a.sendMessage(e.chatId,l)}}catch(t){let s=t instanceof
|
|
|
445
442
|
|
|
446
443
|
Error: ${s}`)}}}});var Ut,ir=h(()=>{"use strict";Ut=class{static{d(this,"ProactiveScheduler")}actionRepo;skillRegistry;skillSandbox;llm;adapters;logger;tickTimer;tickIntervalMs=6e4;constructor(e,t,s,r,n,o){this.actionRepo=e,this.skillRegistry=t,this.skillSandbox=s,this.llm=r,this.adapters=n,this.logger=o}start(){this.tickTimer=setInterval(()=>this.tick(),this.tickIntervalMs),this.logger.info("Proactive scheduler started")}stop(){this.tickTimer&&(clearInterval(this.tickTimer),this.tickTimer=void 0),this.logger.info("Proactive scheduler stopped")}async tick(){try{let e=this.actionRepo.getDue();for(let t of e)try{await this.executeAction(t)}catch(s){this.logger.error({err:s,actionId:t.id},"Failed to execute scheduled action")}}catch(e){this.logger.error({err:e},"Error during proactive scheduler tick")}}async executeAction(e){let t=new Date().toISOString();this.logger.info({actionId:e.id,name:e.name},"Executing scheduled action");let s;if(e.promptTemplate)try{s=(await this.llm.complete({messages:[{role:"user",content:e.promptTemplate}],maxTokens:1024,tier:"fast"})).content}catch(o){let i=o instanceof Error?o.message:String(o);this.logger.error({actionId:e.id,err:o},"LLM call failed for scheduled action"),s=`Scheduled action "${e.name}" failed: ${i}`}else{let o=this.skillRegistry.get(e.skillName);if(!o)this.logger.warn({actionId:e.id,skillName:e.skillName},"Unknown skill for scheduled action"),s=`Scheduled action "${e.name}" failed: unknown skill "${e.skillName}"`;else try{let i;try{i=JSON.parse(e.skillInput)}catch{i={},this.logger.warn({actionId:e.id},"Invalid skillInput JSON, using empty input")}let a={userId:e.userId,chatId:e.chatId,platform:e.platform,conversationId:"",chatType:"dm"},l=await this.skillSandbox.execute(o,i,a);s=l.success?`\u{1F514} Scheduled: ${e.name}
|
|
447
444
|
|
|
448
|
-
${l.display??JSON.stringify(l.data)}`:`\u274C Scheduled action "${e.name}" failed: ${l.error}`}catch(i){let a=i instanceof Error?i.message:String(i);s=`\u274C Scheduled action "${e.name}" failed: ${a}`}}let r=this.adapters.get(e.platform);if(r)try{await r.sendMessage(e.chatId,s)}catch(o){this.logger.error({err:o,actionId:e.id},"Failed to send scheduled action result")}let n=this.calculateNextRun(e);n?this.actionRepo.updateLastRun(e.id,t,n):(this.actionRepo.updateLastRun(e.id,t,null),this.actionRepo.setEnabled(e.id,!1))}calculateNextRun(e){let t=new Date;switch(e.scheduleType){case"interval":{let s=parseInt(e.scheduleValue,10);return isNaN(s)||s<=0?null:new Date(t.getTime()+s*6e4).toISOString()}case"once":return null;case"cron":return this.getNextCronDate(e.scheduleValue,t)?.toISOString()??null;default:return null}}getNextCronDate(e,t){let s=e.trim().split(/\s+/);if(s.length!==5)return null;let r=new Date(t.getTime()+6e4);r.setSeconds(0,0);for(let n=0;n<1440;n++){if(this.matchesCron(s,r))return r;r.setTime(r.getTime()+6e4)}return null}matchesCron(e,t){let s=t.getMinutes(),r=t.getHours(),n=t.getDate(),o=t.getMonth()+1,i=t.getDay();return this.matchCronField(e[0],s)&&this.matchCronField(e[1],r)&&this.matchCronField(e[2],n)&&this.matchCronField(e[3],o)&&this.matchCronField(e[4],i)}matchCronField(e,t){if(e==="*")return!0;let s=/^\*\/(\d+)$/.exec(e);if(s){let n=parseInt(s[1],10);return t%n===0}let r=parseInt(e,10);return isNaN(r)?!1:t===r}}});import{EventEmitter as Mi}from"node:events";var B,oe=h(()=>{"use strict";B=class extends Mi{static{d(this,"MessagingAdapter")}status="disconnected";async sendPhoto(e,t,s){}async sendFile(e,t,s,r){}getStatus(){return this.status}}});import{Bot as Ni,InputFile as zn}from"grammy";function qn(c){if(c==="markdown")return"MarkdownV2";if(c==="html")return"HTML"}var rs,Kn=h(()=>{"use strict";oe();d(qn,"mapParseMode");rs=class extends B{static{d(this,"TelegramAdapter")}platform="telegram";bot;constructor(e){super(),this.bot=new Ni(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 Di,GatewayIntentBits as ns,Events as ar}from"discord.js";var os,Vn=h(()=>{"use strict";oe();os=class extends B{static{d(this,"DiscordAdapter")}platform="discord";client=null;token;constructor(e){super(),this.token=e}async connect(){this.status="connecting",this.client=new Di({intents:[ns.Guilds,ns.GuildMessages,ns.MessageContent,ns.DirectMessages]}),this.client.on(ar.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(ar.ClientReady,()=>{this.status="connected",this.emit("connected")}),this.client.on(ar.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 is,Gn=h(()=>{"use strict";oe();is=class extends B{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 m=await u.arrayBuffer(),p=Buffer.from(m);return{type:t,mimeType:n,fileName:i,size:o??p.length,data:p}}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 as,Yn=h(()=>{"use strict";oe();as=class extends B{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 m=l.lastDisconnect?.error?.output?.statusCode!==n.loggedOut;if(this.status="disconnected",this.emit("disconnected"),m){let p=Math.min(1e3*Math.pow(2,this.reconnectAttempts),6e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>this.connect(),p)}}}),this.socket.ev.on("messages.upsert",({messages:l,type:u})=>{if(u==="notify")for(let m of l)m.message&&(m.key.fromMe||this.processMessage(m).catch(p=>{this.emit("error",p instanceof Error?p:new Error(String(p)))}))})}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 cs,Jn=h(()=>{"use strict";oe();cs=class extends B{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 m=await this.downloadAttachment(u);m&&i.push(m)}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 cr from"node:readline";var ls,Zn=h(()=>{"use strict";oe();ls=class extends B{static{d(this,"CLIAdapter")}platform="cli";rl;messageCounter=0;async connect(){this.status="connecting",this.rl=cr.createInterface({input:process.stdin,output:process.stdout,prompt:"You: "}),console.log(`
|
|
445
|
+
${l.display??JSON.stringify(l.data)}`:`\u274C Scheduled action "${e.name}" failed: ${l.error}`}catch(i){let a=i instanceof Error?i.message:String(i);s=`\u274C Scheduled action "${e.name}" failed: ${a}`}}let r=this.adapters.get(e.platform);if(r)try{await r.sendMessage(e.chatId,s)}catch(o){this.logger.error({err:o,actionId:e.id},"Failed to send scheduled action result")}let n=this.calculateNextRun(e);n?this.actionRepo.updateLastRun(e.id,t,n):(this.actionRepo.updateLastRun(e.id,t,null),this.actionRepo.setEnabled(e.id,!1))}calculateNextRun(e){let t=new Date;switch(e.scheduleType){case"interval":{let s=parseInt(e.scheduleValue,10);return isNaN(s)||s<=0?null:new Date(t.getTime()+s*6e4).toISOString()}case"once":return null;case"cron":return this.getNextCronDate(e.scheduleValue,t)?.toISOString()??null;default:return null}}getNextCronDate(e,t){let s=e.trim().split(/\s+/);if(s.length!==5)return null;let r=new Date(t.getTime()+6e4);r.setSeconds(0,0);for(let n=0;n<1440;n++){if(this.matchesCron(s,r))return r;r.setTime(r.getTime()+6e4)}return null}matchesCron(e,t){let s=t.getMinutes(),r=t.getHours(),n=t.getDate(),o=t.getMonth()+1,i=t.getDay();return this.matchCronField(e[0],s)&&this.matchCronField(e[1],r)&&this.matchCronField(e[2],n)&&this.matchCronField(e[3],o)&&this.matchCronField(e[4],i)}matchCronField(e,t){if(e==="*")return!0;let s=/^\*\/(\d+)$/.exec(e);if(s){let n=parseInt(s[1],10);return t%n===0}let r=parseInt(e,10);return isNaN(r)?!1:t===r}}});import{EventEmitter as Mi}from"node:events";var j,oe=h(()=>{"use strict";j=class extends Mi{static{d(this,"MessagingAdapter")}status="disconnected";async sendPhoto(e,t,s){}async sendFile(e,t,s,r){}getStatus(){return this.status}}});import{Bot as Ni,InputFile as zn}from"grammy";function qn(c){if(c==="markdown")return"MarkdownV2";if(c==="html")return"HTML"}var ss,Kn=h(()=>{"use strict";oe();d(qn,"mapParseMode");ss=class extends j{static{d(this,"TelegramAdapter")}platform="telegram";bot;constructor(e){super(),this.bot=new Ni(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 Di,GatewayIntentBits as rs,Events as ar}from"discord.js";var ns,Vn=h(()=>{"use strict";oe();ns=class extends j{static{d(this,"DiscordAdapter")}platform="discord";client=null;token;constructor(e){super(),this.token=e}async connect(){this.status="connecting",this.client=new Di({intents:[rs.Guilds,rs.GuildMessages,rs.MessageContent,rs.DirectMessages]}),this.client.on(ar.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(ar.ClientReady,()=>{this.status="connected",this.emit("connected")}),this.client.on(ar.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 os,Gn=h(()=>{"use strict";oe();os=class extends j{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 m=await u.arrayBuffer(),p=Buffer.from(m);return{type:t,mimeType:n,fileName:i,size:o??p.length,data:p}}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 is,Yn=h(()=>{"use strict";oe();is=class extends j{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 m=l.lastDisconnect?.error?.output?.statusCode!==n.loggedOut;if(this.status="disconnected",this.emit("disconnected"),m){let p=Math.min(1e3*Math.pow(2,this.reconnectAttempts),6e4);this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>this.connect(),p)}}}),this.socket.ev.on("messages.upsert",({messages:l,type:u})=>{if(u==="notify")for(let m of l)m.message&&(m.key.fromMe||this.processMessage(m).catch(p=>{this.emit("error",p instanceof Error?p:new Error(String(p)))}))})}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 as,Jn=h(()=>{"use strict";oe();as=class extends j{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 m=await this.downloadAttachment(u);m&&i.push(m)}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 cr from"node:readline";var cs,Zn=h(()=>{"use strict";oe();cs=class extends j{static{d(this,"CLIAdapter")}platform="cli";rl;messageCounter=0;async connect(){this.status="connecting",this.rl=cr.createInterface({input:process.stdin,output:process.stdout,prompt:"You: "}),console.log(`
|
|
449
446
|
Alfred Chat \u2014 type your message and press Enter. Use /quit or /exit to leave.
|
|
450
447
|
`),this.rl.on("line",e=>{let t=e.trim();if(!t){this.prompt();return}if(t==="/quit"||t==="/exit"){console.log(`
|
|
451
448
|
Goodbye!
|
|
452
449
|
`),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(`
|
|
453
450
|
Alfred: ${t}
|
|
454
|
-
`),this.prompt(),r}async editMessage(e,t,s,r){cr.clearLine(process.stdout,0),cr.cursorTo(process.stdout,0),process.stdout.write(`Alfred: ${s}`)}async deleteMessage(e,t){}prompt(){this.rl?.prompt()}}});var Ee={};K(Ee,{CLIAdapter:()=>ls,DiscordAdapter:()=>os,MatrixAdapter:()=>is,MessagingAdapter:()=>B,SignalAdapter:()=>cs,TelegramAdapter:()=>rs,WhatsAppAdapter:()=>as});var Te=h(()=>{"use strict";oe();Kn();Vn();Gn();Yn();Jn();Zn()});import ds from"node:fs";import us from"node:path";import Ci from"js-yaml";var _e,Qn=h(()=>{"use strict";$s();As();Fs();Jt();It();Js();Qs();er();tr();sr();rr();nr();or();ir();_e=class{static{d(this,"Alfred")}config;logger;database;pipeline;reminderScheduler;backgroundTaskRunner;proactiveScheduler;adapters=new Map;formatter=new Nt;mcpManager;calendarSkill;constructor(e){this.config=e,this.logger=st("alfred",e.logger.level)}async initialize(){this.logger.info("Initializing Alfred..."),this.database=new de(this.config.storage.path);let e=this.database.getDb(),t=new rt(e),s=new nt(e),r=new ue(e),n=new ot(e),o=new it(e),i=new at(e),a=new ct(e),l=new lt(e),u=new dt(e),m=new ut(e);this.logger.info("Storage initialized");let p=new Tt,f=this.loadSecurityRules();p.loadRules(f);let E=new _t(p,r,this.logger.child({component:"security"}));this.logger.info({ruleCount:f.length},"Security engine initialized");let w=Ps(this.config.llm);await w.initialize(),this.logger.info({provider:this.config.llm.default.provider,model:this.config.llm.default.model},"LLM provider initialized");let b=new Dt(w,a,this.logger.child({component:"embeddings"})),k=new Ie(this.logger.child({component:"sandbox"})),T=new $e;T.register(new Re),T.register(new Ae),T.register(new Le(this.config.search?{provider:this.config.search.provider,apiKey:this.config.search.apiKey,baseUrl:this.config.search.baseUrl}:void 0)),T.register(new Me(o)),T.register(new Ne(i)),T.register(new De),T.register(new Ce),T.register(new Oe(n,b)),T.register(new Ue(w,T,k,E)),T.register(new Pe(this.config.email?{imap:this.config.email.imap,smtp:this.config.email.smtp,auth:this.config.email.auth}:void 0)),T.register(new Fe),T.register(new je),T.register(new We),T.register(new He),T.register(new Xe),T.register(new ze(s)),T.register(new qe(s,l,this.adapters)),T.register(new Ke(u)),T.register(new Ve(m));let x=new pt(e),O=new Ct(x,b,this.logger.child({component:"documents"}));T.register(new Ye(x,O,b));let z;if(this.config.calendar)try{let A=await vt(this.config.calendar);z=new fe(A),T.register(z),this.logger.info({provider:this.config.calendar.provider},"Calendar initialized")}catch(A){this.logger.warn({err:A},"Calendar initialization failed, continuing without calendar")}if(this.calendarSkill=z,this.config.mcp?.servers?.length){let{MCPManager:A}=await Promise.resolve().then(()=>(It(),ss));this.mcpManager=new A(this.logger.child({component:"mcp"})),await this.mcpManager.initialize(this.config.mcp);for(let j of this.mcpManager.getSkills())T.register(j);this.logger.info({mcpSkills:this.mcpManager.getSkills().length},"MCP skills registered")}if(this.config.codeSandbox?.enabled){let{CodeExecutionSkill:A}=await Promise.resolve().then(()=>(It(),ss));T.register(new A({allowedLanguages:this.config.codeSandbox.allowedLanguages,maxTimeoutMs:this.config.codeSandbox.maxTimeoutMs})),this.logger.info("Code sandbox enabled")}this.logger.info({skills:T.getAll().map(A=>A.metadata.name)},"Skills registered");let v;this.config.speech?.apiKey&&(v=new Mt(this.config.speech,this.logger.child({component:"speech"})),this.logger.info({provider:this.config.speech.provider},"Speech-to-text initialized"));let U=new Rt(t),F=us.resolve(us.dirname(this.config.storage.path),"inbox");this.pipeline=new At({llm:w,conversationManager:U,users:s,logger:this.logger.child({component:"pipeline"}),skillRegistry:T,skillSandbox:k,securityManager:E,memoryRepo:n,speechTranscriber:v,inboxPath:F,embeddingService:b}),this.reminderScheduler=new Lt(o,async(A,j,jt)=>{let W=this.adapters.get(A);W?await W.sendMessage(j,jt):this.logger.warn({platform:A,chatId:j},"No adapter for reminder platform")},this.logger.child({component:"reminders"})),this.backgroundTaskRunner=new Ot(T,k,u,this.adapters,this.logger.child({component:"background-tasks"})),this.proactiveScheduler=new Ut(m,T,k,w,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(()=>(Te(),Ee));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(()=>(Te(),Ee));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(()=>(Te(),Ee));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(()=>(Te(),Ee));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(()=>(Te(),Ee));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(){let{CLIAdapter:e}=await Promise.resolve().then(()=>(Te(),Ee)),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(m){this.logger.debug({err:m,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=us.resolve(this.config.security.rulesPath),t=[];if(!ds.existsSync(e))return this.logger.warn({rulesPath:e},"Security rules directory not found, using default deny"),t;if(!ds.statSync(e).isDirectory())return this.logger.warn({rulesPath:e},"Security rules path is not a directory"),t;let r=ds.readdirSync(e).filter(n=>n.endsWith(".yml")||n.endsWith(".yaml"));for(let n of r)try{let o=us.join(e,n),i=ds.readFileSync(o,"utf-8"),a=Ci.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 lr=h(()=>{"use strict";Qn();Qs();Js();er();tr();sr();rr();or();ir();nr()});var eo={};K(eo,{startCommand:()=>Oi});async function Oi(){let c=new H,e;try{e=c.loadConfig()}catch(o){console.error("Failed to load configuration:",o.message),process.exit(1)}let t=st("cli",e.logger.level);t.info({name:e.name},"Configuration loaded");let s=new _e(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 to=h(()=>{"use strict";le();$s();lr();d(Oi,"startCommand")});var so={};K(so,{chatCommand:()=>Ui});async function Ui(c){let e=new H,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 _e(t);try{await s.initialize(),await s.startWithCLI()}catch(r){console.error("Failed to start chat:",r.message),process.exit(1)}}var ro=h(()=>{"use strict";le();lr();d(Ui,"chatCommand")});var oo={};K(oo,{setupCommand:()=>zi});import{createInterface as Pi}from"node:readline/promises";import{stdin as Fi,stdout as ji}from"node:process";import X from"node:fs";import ee from"node:path";import ur from"js-yaml";function N(c){return`${ps}${c}${R}`}function Hi(c){return`${J}${c}${R}`}function Se(c){return`${ms}${c}${R}`}function no(c){return`${Bi}${c}${R}`}function $(c){return`${Ze}${c}${R}`}function S(c){return`${ae}${c}${R}`}function be(c){return c.length<=4?"****":"*".repeat(c.length-4)+c.slice(-4)}function Xi(c){let e={},t={},s=!1,r=!1,n=30,o=ee.join(c,"config","default.yml");if(X.existsSync(o))try{let l=ur.load(X.readFileSync(o,"utf-8"));l&&typeof l=="object"&&Object.assign(e,l)}catch{}let i=ee.join(c,".env");if(X.existsSync(i))try{let l=X.readFileSync(i,"utf-8").split(`
|
|
455
|
-
`);for(let u of l){let m=u.trim();if(!m||m.startsWith("#"))continue;let p=m.indexOf("=");p>0&&(t[m.slice(0,p)]=m.slice(p+1))}}catch{}let a=
|
|
451
|
+
`),this.prompt(),r}async editMessage(e,t,s,r){cr.clearLine(process.stdout,0),cr.cursorTo(process.stdout,0),process.stdout.write(`Alfred: ${s}`)}async deleteMessage(e,t){}prompt(){this.rl?.prompt()}}});var Ee={};q(Ee,{CLIAdapter:()=>cs,DiscordAdapter:()=>ns,MatrixAdapter:()=>os,MessagingAdapter:()=>j,SignalAdapter:()=>as,TelegramAdapter:()=>ss,WhatsAppAdapter:()=>is});var Te=h(()=>{"use strict";oe();Kn();Vn();Gn();Yn();Jn();Zn()});import ls from"node:fs";import ds from"node:path";import Ci from"js-yaml";var _e,Qn=h(()=>{"use strict";$s();As();Fs();Yt();It();Js();Qs();er();tr();sr();rr();nr();or();ir();_e=class{static{d(this,"Alfred")}config;logger;database;pipeline;reminderScheduler;backgroundTaskRunner;proactiveScheduler;adapters=new Map;formatter=new Nt;mcpManager;calendarSkill;constructor(e){this.config=e,this.logger=st("alfred",e.logger.level)}async initialize(){this.logger.info("Initializing Alfred..."),this.database=new de(this.config.storage.path);let e=this.database.getDb(),t=new rt(e),s=new nt(e),r=new ue(e),n=new ot(e),o=new it(e),i=new at(e),a=new ct(e),l=new lt(e),u=new dt(e),m=new ut(e);this.logger.info("Storage initialized");let p=new Tt,f=this.loadSecurityRules();p.loadRules(f);let E=new _t(p,r,this.logger.child({component:"security"}));this.logger.info({ruleCount:f.length},"Security engine initialized");let w=Ps(this.config.llm);await w.initialize(),this.logger.info({provider:this.config.llm.default.provider,model:this.config.llm.default.model},"LLM provider initialized");let b=new Dt(w,a,this.logger.child({component:"embeddings"})),k=new Ie(this.logger.child({component:"sandbox"})),T=new $e;T.register(new Re),T.register(new Ae),T.register(new Le(this.config.search?{provider:this.config.search.provider,apiKey:this.config.search.apiKey,baseUrl:this.config.search.baseUrl}:void 0)),T.register(new Me(o)),T.register(new Ne(i)),T.register(new De),T.register(new Ce),T.register(new Oe(n,b)),T.register(new Ue(w,T,k,E)),T.register(new Pe(this.config.email?{imap:this.config.email.imap,smtp:this.config.email.smtp,auth:this.config.email.auth}:void 0)),T.register(new Fe),T.register(new je),T.register(new We),T.register(new He),T.register(new Xe),T.register(new ze(s)),T.register(new qe(s,l,this.adapters)),T.register(new Ke(u)),T.register(new Ve(m));let x=new pt(e),U=new Ct(x,b,this.logger.child({component:"documents"}));T.register(new Ye(x,U,b));let X;if(this.config.calendar)try{let M=await vt(this.config.calendar);X=new fe(M),T.register(X),this.logger.info({provider:this.config.calendar.provider},"Calendar initialized")}catch(M){this.logger.warn({err:M},"Calendar initialization failed, continuing without calendar")}if(this.calendarSkill=X,this.config.mcp?.servers?.length){let{MCPManager:M}=await Promise.resolve().then(()=>(It(),ts));this.mcpManager=new M(this.logger.child({component:"mcp"})),await this.mcpManager.initialize(this.config.mcp);for(let ee of this.mcpManager.getSkills())T.register(ee);this.logger.info({mcpSkills:this.mcpManager.getSkills().length},"MCP skills registered")}if(this.config.codeSandbox?.enabled){let{CodeExecutionSkill:M}=await Promise.resolve().then(()=>(It(),ts));T.register(new M({allowedLanguages:this.config.codeSandbox.allowedLanguages,maxTimeoutMs:this.config.codeSandbox.maxTimeoutMs})),this.logger.info("Code sandbox enabled")}this.logger.info({skills:T.getAll().map(M=>M.metadata.name)},"Skills registered");let v;this.config.speech?.apiKey&&(v=new Mt(this.config.speech,this.logger.child({component:"speech"})),this.logger.info({provider:this.config.speech.provider},"Speech-to-text initialized"));let P=new Rt(t),D=ds.resolve(ds.dirname(this.config.storage.path),"inbox");this.pipeline=new At({llm:w,conversationManager:P,users:s,logger:this.logger.child({component:"pipeline"}),skillRegistry:T,skillSandbox:k,securityManager:E,memoryRepo:n,speechTranscriber:v,inboxPath:D,embeddingService:b}),this.reminderScheduler=new Lt(o,async(M,ee,hs)=>{let B=this.adapters.get(M);B?await B.sendMessage(ee,hs):this.logger.warn({platform:M,chatId:ee},"No adapter for reminder platform")},this.logger.child({component:"reminders"})),this.backgroundTaskRunner=new Ot(T,k,u,this.adapters,this.logger.child({component:"background-tasks"})),this.proactiveScheduler=new Ut(m,T,k,w,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(()=>(Te(),Ee));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(()=>(Te(),Ee));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(()=>(Te(),Ee));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(()=>(Te(),Ee));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(()=>(Te(),Ee));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(()=>(Te(),Ee)),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(m){this.logger.debug({err:m,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=ds.resolve(this.config.security.rulesPath),t=[];if(!ls.existsSync(e))return this.logger.warn({rulesPath:e},"Security rules directory not found, using default deny"),t;if(!ls.statSync(e).isDirectory())return this.logger.warn({rulesPath:e},"Security rules path is not a directory"),t;let r=ls.readdirSync(e).filter(n=>n.endsWith(".yml")||n.endsWith(".yaml"));for(let n of r)try{let o=ds.join(e,n),i=ls.readFileSync(o,"utf-8"),a=Ci.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 lr=h(()=>{"use strict";Qn();Qs();Js();er();tr();sr();rr();or();ir();nr()});var eo={};q(eo,{startCommand:()=>Oi});async function Oi(){let c=new W,e;try{e=c.loadConfig()}catch(o){console.error("Failed to load configuration:",o.message),process.exit(1)}let t=st("cli",e.logger.level);t.info({name:e.name},"Configuration loaded");let s=new _e(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 to=h(()=>{"use strict";le();$s();lr();d(Oi,"startCommand")});var so={};q(so,{chatCommand:()=>Ui});async function Ui(c){let e=new W,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 _e(t);try{await s.initialize(),await s.startWithCLI()}catch(r){console.error("Failed to start chat:",r.message),process.exit(1)}}var ro=h(()=>{"use strict";le();lr();d(Ui,"chatCommand")});var oo={};q(oo,{setupCommand:()=>zi});import{createInterface as Pi}from"node:readline/promises";import{stdin as Fi,stdout as ji}from"node:process";import H from"node:fs";import Q from"node:path";import ur from"js-yaml";function N(c){return`${us}${c}${R}`}function Hi(c){return`${Y}${c}${R}`}function Se(c){return`${ps}${c}${R}`}function no(c){return`${Bi}${c}${R}`}function $(c){return`${Ze}${c}${R}`}function S(c){return`${ae}${c}${R}`}function be(c){return c.length<=4?"****":"*".repeat(c.length-4)+c.slice(-4)}function Xi(c){let e={},t={},s=!1,r=!1,n=30,o=Q.join(c,"config","default.yml");if(H.existsSync(o))try{let l=ur.load(H.readFileSync(o,"utf-8"));l&&typeof l=="object"&&Object.assign(e,l)}catch{}let i=Q.join(c,".env");if(H.existsSync(i))try{let l=H.readFileSync(i,"utf-8").split(`
|
|
452
|
+
`);for(let u of l){let m=u.trim();if(!m||m.startsWith("#"))continue;let p=m.indexOf("=");p>0&&(t[m.slice(0,p)]=m.slice(p+1))}}catch{}let a=Q.join(c,"config","rules","default-rules.yml");if(H.existsSync(a))try{let l=ur.load(H.readFileSync(a,"utf-8"));if(l?.rules){s=l.rules.some(p=>p.id==="allow-owner-admin"&&p.effect==="allow"),l.rules.find(p=>p.id==="allow-write-for-dm"||p.id==="allow-write-all")?.id==="allow-write-all"&&(r=!0);let m=l.rules.find(p=>p.id==="rate-limit-write");m?.rateLimit?.maxInvocations&&(n=m.rateLimit.maxInvocations)}}catch{}return{config:e,env:t,shellEnabled:s,writeInGroups:r,rateLimit:n}}async function zi(){let c=Pi({input:Fi,output:ji}),e=process.cwd(),t=Xi(e),s=Object.keys(t.config).length>0;try{qi(),console.log(s?`${ps}Existing configuration found \u2014 press Enter to keep current values.${R}
|
|
456
453
|
${ae}Only change what you need to update.${R}
|
|
457
|
-
`:`${
|
|
454
|
+
`:`${ps}Welcome to the Alfred setup wizard!${R}
|
|
458
455
|
${ae}This will walk you through configuring your AI assistant.${R}
|
|
459
456
|
${ae}Press Enter to accept defaults shown in [brackets].${R}
|
|
460
|
-
`);let r=await
|
|
461
|
-
${$("Which LLM provider would you like to use?")}`);for(let y=0;y<Pt.length;y++){let I=y===n?` ${S("(current)")}`:"";console.log(` ${Se(String(y+1)+")")} ${Pt[y].label}${I}`)}let i=await dr(c,"> ",1,Pt.length,o),a=Pt[i-1];console.log(` ${N(">")} Selected: ${$(a.label)}`);let l="",u=t.env[a.envKeyName]??"";a.needsApiKey&&(console.log(""),u?l=await
|
|
462
|
-
${$("Web Search provider (for searching the internet):")}`);let x=["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"],
|
|
463
|
-
${$("Which messaging platforms do you want to enable?")}`),console.log(`${S("(Enter comma-separated numbers, e.g. 1,3)")}`);for(let y=0;y<Je.length;y++){let I=
|
|
457
|
+
`);let r=await O(c,"What should your bot be called?",t.config.name??"Alfred"),n=t.config.llm?.provider?Pt.findIndex(y=>y.name===t.config.llm?.provider):-1,o=n>=0?n+1:1;console.log(`
|
|
458
|
+
${$("Which LLM provider would you like to use?")}`);for(let y=0;y<Pt.length;y++){let I=y===n?` ${S("(current)")}`:"";console.log(` ${Se(String(y+1)+")")} ${Pt[y].label}${I}`)}let i=await dr(c,"> ",1,Pt.length,o),a=Pt[i-1];console.log(` ${N(">")} Selected: ${$(a.label)}`);let l="",u=t.env[a.envKeyName]??"";a.needsApiKey&&(console.log(""),u?l=await O(c,`${a.name.charAt(0).toUpperCase()+a.name.slice(1)} API key`,u):l=await ie(c,`Enter your ${a.name.charAt(0).toUpperCase()+a.name.slice(1)} API key`),console.log(` ${N(">")} API key set: ${S(be(l))}`));let m=a.baseUrl??"";if(["ollama","openwebui","openai","openrouter"].includes(a.name)){let I=(t.config.llm?.baseUrl??t.env.ALFRED_LLM_BASE_URL??"")||a.baseUrl||"";if(I){let F={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(""),m=await O(c,F[a.name]??"API Base URL",I.replace(/\/+$/,"")),m=m.replace(/\/+$/,""),console.log(` ${N(">")} URL: ${S(m)}`)}}let f=t.config.llm?.model??a.defaultModel;console.log("");let E=await O(c,"Which model?",f),w=["brave","tavily","duckduckgo","searxng"],b=t.config.search?.provider??t.env.ALFRED_SEARCH_PROVIDER??"",k=w.indexOf(b),T=k>=0?k+1:0;console.log(`
|
|
459
|
+
${$("Web Search provider (for searching the internet):")}`);let x=["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"],U=d(y=>k===y?` ${S("(current)")}`:"","mark");console.log(` ${Se("0)")} None (disable web search)${k===-1&&b===""?` ${S("(current)")}`:""}`);for(let y=0;y<x.length;y++)console.log(` ${Se(String(y+1)+")")} ${x[y]}${U(y)}`);let X=await dr(c,"> ",0,w.length,T),v,P="",D="";if(X>=1&&X<=w.length&&(v=w[X-1]),v==="brave"){let y=t.env.ALFRED_SEARCH_API_KEY??"";y?P=await O(c," Brave Search API key",y):(console.log(` ${S("Get your free API key at: https://brave.com/search/api/")}`),P=await ie(c," Brave Search API key")),console.log(` ${N(">")} Brave Search: ${S(be(P))}`)}else if(v==="tavily"){let y=t.env.ALFRED_SEARCH_API_KEY??"";y?P=await O(c," Tavily API key",y):(console.log(` ${S("Get your free API key at: https://tavily.com/")}`),P=await ie(c," Tavily API key")),console.log(` ${N(">")} Tavily: ${S(be(P))}`)}else if(v==="duckduckgo")console.log(` ${N(">")} DuckDuckGo: ${S("no API key needed")}`);else if(v==="searxng"){let y=t.config.search?.baseUrl??t.env.ALFRED_SEARCH_BASE_URL??"http://localhost:8080";D=await O(c," SearXNG URL",y),D=D.replace(/\/+$/,""),console.log(` ${N(">")} SearXNG: ${S(D)}`)}else console.log(` ${S("Web search disabled \u2014 you can configure it later.")}`);let M=[];for(let y=0;y<Je.length;y++){let I=Je[y];t.config[I.configKey]?.enabled&&M.push(y+1)}let ee=M.length>0?M.join(","):"";console.log(`
|
|
460
|
+
${$("Which messaging platforms do you want to enable?")}`),console.log(`${S("(Enter comma-separated numbers, e.g. 1,3)")}`);for(let y=0;y<Je.length;y++){let I=M.includes(y+1)?` ${S("(enabled)")}`:"";console.log(` ${Se(String(y+1)+")")} ${Je[y].label}${I}`)}console.log(` ${Se("0)")} None (configure later)`);let hs=(await c.question(`${Y}> ${R}${ee?S(`[${ee}] `):""}`)).trim(),B=[],fs=hs||ee;if(fs&&fs!=="0"){let y=fs.split(",").map(I=>parseInt(I.trim(),10));for(let I of y)if(I>=1&&I<=Je.length){let F=Je[I-1];B.includes(F)||B.push(F)}}B.length>0?console.log(` ${N(">")} Enabling: ${B.map(y=>$(y.label)).join(", ")}`):console.log(` ${S("No platforms selected \u2014 you can configure them later.")}`);let te={},hr={};for(let y of B){if(y.credentials.length===0){y.name==="whatsapp"&&console.log(`
|
|
464
461
|
${Hi("i")} WhatsApp: a QR code will be displayed on first start.`);continue}console.log(`
|
|
465
|
-
${$(y.label+" configuration:")}`);let I={};for(let
|
|
466
|
-
${$("Email access (read & send emails via IMAP/SMTP)?")}`),console.log(`${S("Works with Gmail, Outlook, or any IMAP/SMTP provider.")}`);let gs=(await c.question(`${
|
|
467
|
-
${$("Voice message transcription (Speech-to-Text via Whisper)?")}`),console.log(`${S("Transcribes voice messages from Telegram, Discord, etc.")}`);let wr=["OpenAI Whisper \u2014 best quality","Groq Whisper \u2014 fast & free"];console.log(` ${Se("0)")} None (disable voice transcription)${
|
|
468
|
-
${$("Security configuration:")}`);let Er=t.config.security?.ownerUserId??t.env.ALFRED_OWNER_USER_ID??"",
|
|
469
|
-
${$("Writing configuration files...")}`);let
|
|
470
|
-
`),"utf-8"),console.log(` ${N("+")} ${S(".env")} written`);let
|
|
462
|
+
${$(y.label+" configuration:")}`);let I={};for(let F of y.credentials){let ke=t.env[F.envKey]??"",G;ke?G=await O(c,` ${F.prompt}`,ke):F.defaultValue?G=await O(c,` ${F.prompt}`,F.defaultValue):F.required?G=await ie(c,` ${F.prompt}`):(G=(await c.question(` ${F.prompt}: ${Y}`)).trim(),process.stdout.write(R)),I[F.configField]=G,hr[F.envKey]=G,F.configField==="token"||F.configField==="accessToken"?console.log(` ${N(">")} Set: ${S(be(G))}`):console.log(` ${N(">")} Set: ${S(G)}`)}te[y.configKey]=I}let fr=t.config.email?.auth?.user??t.env.ALFRED_EMAIL_USER??"",gr=!!fr,Eo=gr?"Y/n":"y/N";console.log(`
|
|
463
|
+
${$("Email access (read & send emails via IMAP/SMTP)?")}`),console.log(`${S("Works with Gmail, Outlook, or any IMAP/SMTP provider.")}`);let gs=(await c.question(`${Y}> ${R}${S(`[${Eo}] `)}`)).trim().toLowerCase(),jt=gs===""?gr:gs==="y"||gs==="yes",se="",Bt="",Wt="",ys=993,yr="",ws=587;if(jt){console.log(""),se=await O(c," Email address",fr||""),se||(se=await ie(c," Email address"));let y=t.env.ALFRED_EMAIL_PASS??"";y?Bt=await O(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")}`),Bt=await ie(c," Password / App password"));let I=se.split("@")[1]?.toLowerCase()??"",ke={"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"}}[I],G=t.config.email?.imap?.host??ke?.imap??`imap.${I}`,Lo=t.config.email?.smtp?.host??ke?.smtp??`smtp.${I}`,Mo=t.config.email?.imap?.port??993,No=t.config.email?.smtp?.port??587;ke&&console.log(` ${N(">")} Detected ${I} \u2014 using preset server settings`),Wt=await O(c," IMAP server",G);let Do=await O(c," IMAP port",String(Mo));ys=parseInt(Do,10)||993,yr=await O(c," SMTP server",Lo);let Co=await O(c," SMTP port",String(No));ws=parseInt(Co,10)||587,console.log(` ${N(">")} Email: ${S(se)} via ${S(Wt)}`)}else console.log(` ${S("Email disabled \u2014 you can configure it later.")}`);let Ht=["openai","groq"],To=t.config.speech?.provider??t.env.ALFRED_SPEECH_PROVIDER??"",Xt=Ht.indexOf(To),_o=Xt>=0?Xt+1:0;console.log(`
|
|
464
|
+
${$("Voice message transcription (Speech-to-Text via Whisper)?")}`),console.log(`${S("Transcribes voice messages from Telegram, Discord, etc.")}`);let wr=["OpenAI Whisper \u2014 best quality","Groq Whisper \u2014 fast & free"];console.log(` ${Se("0)")} None (disable voice transcription)${Xt===-1?` ${S("(current)")}`:""}`);for(let y=0;y<wr.length;y++){let I=Xt===y?` ${S("(current)")}`:"";console.log(` ${Se(String(y+1)+")")} ${wr[y]}${I}`)}let Es=await dr(c,"> ",0,Ht.length,_o),J,re="",Qe="";if(Es>=1&&Es<=Ht.length&&(J=Ht[Es-1]),J==="openai"){let y=t.env.ALFRED_SPEECH_API_KEY??"";y?re=await O(c," OpenAI API key (for Whisper)",y):(console.log(` ${S("Uses your OpenAI API key for Whisper transcription.")}`),re=await ie(c," OpenAI API key")),console.log(` ${N(">")} OpenAI Whisper: ${S(be(re))}`)}else if(J==="groq"){let y=t.env.ALFRED_SPEECH_API_KEY??"";y?re=await O(c," Groq API key",y):(console.log(` ${S("Get your free API key at: https://console.groq.com/")}`),re=await ie(c," Groq API key"));let I=t.env.ALFRED_SPEECH_BASE_URL??"";I&&(Qe=await O(c," Groq API URL",I)),console.log(` ${N(">")} Groq Whisper: ${S(be(re))}`)}else console.log(` ${S("Voice transcription disabled \u2014 you can configure it later.")}`);console.log(`
|
|
465
|
+
${$("Security configuration:")}`);let Er=t.config.security?.ownerUserId??t.env.ALFRED_OWNER_USER_ID??"",z;if(Er)z=await O(c,"Owner user ID (for elevated permissions)",Er);else{let y=(await c.question(`${Ze}Owner user ID${R} ${S("(optional, for elevated permissions)")}: ${Y}`)).trim();process.stdout.write(R),z=y}let et=!1;if(z){let y=t.shellEnabled?"Y/n":"y/N";console.log(""),console.log(` ${$("Enable shell access (admin commands) for the owner?")}`),console.log(` ${S("Allows Alfred to execute shell commands. Only for the owner.")}`);let I=(await c.question(` ${Y}> ${R}${S(`[${y}] `)}`)).trim().toLowerCase();I===""?et=t.shellEnabled:et=I==="y"||I==="yes",console.log(et?` ${N(">")} Shell access ${$("enabled")} for owner ${S(z)}`:` ${S("Shell access disabled.")}`)}let So=t.writeInGroups?"Y/n":"y/N";console.log(""),console.log(` ${$("Allow write actions (notes, reminders, memory) in group chats?")}`),console.log(` ${S("By default, write actions are only allowed in DMs.")}`);let Ts=(await c.question(` ${Y}> ${R}${S(`[${So}] `)}`)).trim().toLowerCase(),tt;Ts===""?tt=t.writeInGroups:tt=Ts==="y"||Ts==="yes",console.log(tt?` ${N(">")} Write actions ${$("enabled")} in groups`:` ${S("Write actions only in DMs (default).")}`);let bo=t.rateLimit??30;console.log("");let ko=await O(c," Rate limit (max write actions per hour per user)",String(bo)),zt=Math.max(1,parseInt(ko,10)||30);console.log(` ${N(">")} Rate limit: ${$(String(zt))} per hour`),console.log(`
|
|
466
|
+
${$("Writing configuration files...")}`);let A=["# Alfred Environment Variables","# Generated by `alfred setup`","","# === LLM ===","",`ALFRED_LLM_PROVIDER=${a.name}`];if(l){let y=a.envKeyName||"ALFRED_OLLAMA_API_KEY";A.push(`${y}=${l}`)}E!==a.defaultModel&&A.push(`ALFRED_LLM_MODEL=${E}`),m&&A.push(`ALFRED_LLM_BASE_URL=${m}`),A.push("","# === Messaging Platforms ===","");for(let[y,I]of Object.entries(hr))A.push(`${y}=${I}`);A.push("","# === Web Search ===",""),v?(A.push(`ALFRED_SEARCH_PROVIDER=${v}`),P&&A.push(`ALFRED_SEARCH_API_KEY=${P}`),D&&A.push(`ALFRED_SEARCH_BASE_URL=${D}`)):(A.push("# ALFRED_SEARCH_PROVIDER=brave"),A.push("# ALFRED_SEARCH_API_KEY=")),A.push("","# === Email ===",""),jt?(A.push(`ALFRED_EMAIL_USER=${se}`),A.push(`ALFRED_EMAIL_PASS=${Bt}`)):(A.push("# ALFRED_EMAIL_USER="),A.push("# ALFRED_EMAIL_PASS=")),A.push("","# === Speech-to-Text ===",""),J?(A.push(`ALFRED_SPEECH_PROVIDER=${J}`),A.push(`ALFRED_SPEECH_API_KEY=${re}`),Qe&&A.push(`ALFRED_SPEECH_BASE_URL=${Qe}`)):(A.push("# ALFRED_SPEECH_PROVIDER=groq"),A.push("# ALFRED_SPEECH_API_KEY=")),A.push("","# === Security ===",""),z?A.push(`ALFRED_OWNER_USER_ID=${z}`):A.push("# ALFRED_OWNER_USER_ID="),A.push("");let vo=Q.join(e,".env");H.writeFileSync(vo,A.join(`
|
|
467
|
+
`),"utf-8"),console.log(` ${N("+")} ${S(".env")} written`);let qt=Q.join(e,"config");H.existsSync(qt)||H.mkdirSync(qt,{recursive:!0});let Tr={name:r,telegram:{token:te.telegram?.token??"",enabled:B.some(y=>y.name==="telegram")},discord:{token:te.discord?.token??"",enabled:B.some(y=>y.name==="discord")},whatsapp:{enabled:B.some(y=>y.name==="whatsapp"),dataPath:"./data/whatsapp"},matrix:{homeserverUrl:te.matrix?.homeserverUrl??"https://matrix.org",accessToken:te.matrix?.accessToken??"",userId:te.matrix?.userId??"",enabled:B.some(y=>y.name==="matrix")},signal:{apiUrl:te.signal?.apiUrl??"http://localhost:8080",phoneNumber:te.signal?.phoneNumber??"",enabled:B.some(y=>y.name==="signal")},llm:{provider:a.name,model:E,...m?{baseUrl:m}:{},temperature:.7,maxTokens:4096},...v?{search:{provider:v,...P?{apiKey:P}:{},...D?{baseUrl:D}:{}}}:{},...jt?{email:{imap:{host:Wt,port:ys,secure:ys===993},smtp:{host:yr,port:ws,secure:ws===465},auth:{user:se,pass:Bt}}}:{},...J?{speech:{provider:J,apiKey:re,...Qe?{baseUrl:Qe}:{}}}:{},storage:{path:"./data/alfred.db"},logger:{level:"info",pretty:!0,auditLogPath:"./data/audit.log"},security:{rulesPath:"./config/rules",defaultEffect:"deny"}};z&&(Tr.security.ownerUserId=z);let xo="# Alfred \u2014 Configuration\n# Generated by `alfred setup`\n# Edit manually or re-run `alfred setup` to reconfigure.\n\n"+ur.dump(Tr,{lineWidth:120,noRefs:!0,sortKeys:!1}),$o=Q.join(qt,"default.yml");H.writeFileSync($o,xo,"utf-8"),console.log(` ${N("+")} ${S("config/default.yml")} written`);let _s=Q.join(qt,"rules");H.existsSync(_s)||H.mkdirSync(_s,{recursive:!0});let Io=et&&z?`
|
|
471
468
|
# Allow admin actions (shell, etc.) for the owner only
|
|
472
469
|
- id: allow-owner-admin
|
|
473
470
|
effect: allow
|
|
@@ -476,7 +473,7 @@ ${$("Writing configuration files...")}`);let L=["# Alfred Environment Variables"
|
|
|
476
473
|
actions: ["*"]
|
|
477
474
|
riskLevels: [admin, destructive]
|
|
478
475
|
conditions:
|
|
479
|
-
users: ["${
|
|
476
|
+
users: ["${z}"]
|
|
480
477
|
`:`
|
|
481
478
|
# Allow admin actions (shell, etc.) for the owner only
|
|
482
479
|
# Uncomment and set your user ID to enable:
|
|
@@ -487,7 +484,7 @@ ${$("Writing configuration files...")}`);let L=["# Alfred Environment Variables"
|
|
|
487
484
|
# actions: ["*"]
|
|
488
485
|
# riskLevels: [admin, destructive]
|
|
489
486
|
# conditions:
|
|
490
|
-
# users: ["${
|
|
487
|
+
# users: ["${z||"YOUR_USER_ID_HERE"}"]
|
|
491
488
|
`,Ro=`# Alfred \u2014 Default Security Rules
|
|
492
489
|
# Rules are evaluated in priority order (lower number = higher priority).
|
|
493
490
|
# First matching rule wins.
|
|
@@ -517,7 +514,7 @@ ${tt?` # Allow write-level skills everywhere (DMs and groups)
|
|
|
517
514
|
conditions:
|
|
518
515
|
chatType: dm`}
|
|
519
516
|
|
|
520
|
-
# Rate-limit write actions: max ${
|
|
517
|
+
# Rate-limit write actions: max ${zt} per hour per user
|
|
521
518
|
- id: rate-limit-write
|
|
522
519
|
effect: allow
|
|
523
520
|
priority: 250
|
|
@@ -525,7 +522,7 @@ ${tt?` # Allow write-level skills everywhere (DMs and groups)
|
|
|
525
522
|
actions: ["*"]
|
|
526
523
|
riskLevels: [write]
|
|
527
524
|
rateLimit:
|
|
528
|
-
maxInvocations: ${
|
|
525
|
+
maxInvocations: ${zt}
|
|
529
526
|
windowSeconds: 3600
|
|
530
527
|
${Io}
|
|
531
528
|
# Deny destructive and admin actions by default
|
|
@@ -543,14 +540,14 @@ ${Io}
|
|
|
543
540
|
scope: global
|
|
544
541
|
actions: ["*"]
|
|
545
542
|
riskLevels: [read, write, destructive, admin]
|
|
546
|
-
`,Ao=
|
|
543
|
+
`,Ao=Q.join(_s,"default-rules.yml");H.writeFileSync(Ao,Ro,"utf-8"),console.log(` ${N("+")} ${S("config/rules/default-rules.yml")} written`);let _r=Q.join(e,"data");if(H.existsSync(_r)||(H.mkdirSync(_r,{recursive:!0}),console.log(` ${N("+")} ${S("data/")} directory created`)),console.log(""),console.log(`${us}${"=".repeat(52)}${R}`),console.log(`${us}${Ze} Setup complete!${R}`),console.log(`${us}${"=".repeat(52)}${R}`),console.log(""),console.log(` ${$("Bot name:")} ${r}`),console.log(` ${$("LLM provider:")} ${a.name} (${E})`),l&&console.log(` ${$("API key:")} ${be(l)}`),B.length>0?console.log(` ${$("Platforms:")} ${B.map(y=>y.label).join(", ")}`):console.log(` ${$("Platforms:")} none (configure later)`),v){let y={brave:"Brave Search",tavily:"Tavily",duckduckgo:"DuckDuckGo",searxng:`SearXNG (${D})`};console.log(` ${$("Web search:")} ${y[v]}`)}else console.log(` ${$("Web search:")} ${S("disabled")}`);if(console.log(jt?` ${$("Email:")} ${se} (${Wt})`:` ${$("Email:")} ${S("disabled")}`),J){let y={openai:"OpenAI Whisper",groq:"Groq Whisper"};console.log(` ${$("Voice:")} ${y[J]}`)}else console.log(` ${$("Voice:")} ${S("disabled")}`);z&&(console.log(` ${$("Owner ID:")} ${z}`),console.log(` ${$("Shell access:")} ${et?N("enabled"):S("disabled")}`)),console.log(` ${$("Write scope:")} ${tt?"DMs + Groups":"DMs only"}`),console.log(` ${$("Rate limit:")} ${zt}/hour per user`),console.log(""),console.log(`${ps}Next steps:${R}`),console.log(` ${$("alfred start")} Start Alfred`),console.log(` ${$("alfred status")} Check configuration`),console.log(` ${$("alfred --help")} Show all commands`),console.log(""),console.log(`${ae}Edit ${$(".env")}${ae} or ${$("config/default.yml")}${ae} for manual configuration.${R}`),console.log("")}finally{c.close()}}async function O(c,e,t){let s=(await c.question(`${Ze}${e}${R} ${S(`[${t}]`)}: ${Y}`)).trim();return process.stdout.write(R),s||t}async function ie(c,e){for(;;){let t=(await c.question(`${Ze}${e}${R}: ${Y}`)).trim();if(process.stdout.write(R),t)return t;console.log(` ${no("!")} This field is required. Please enter a value.`)}}async function dr(c,e,t,s,r){for(;;){let n=(await c.question(`${Y}${e}${R}`)).trim();if(!n)return r;let o=parseInt(n,10);if(!Number.isNaN(o)&&o>=t&&o<=s)return o;console.log(` ${no("!")} Please enter a number between ${t} and ${s}.`)}}function qi(){console.log(`
|
|
547
544
|
${Wi}${Ze} _ _ _____ ____ _____ ____
|
|
548
545
|
/ \\ | | | ___| _ \\| ____| _ \\
|
|
549
546
|
/ _ \\ | | | |_ | |_) | _| | | | |
|
|
550
547
|
/ ___ \\| |___| _| | _ <| |___| |_| |
|
|
551
548
|
/_/ \\_\\_____|_| |_| \\_\\_____|____/ ${R}
|
|
552
549
|
${ae} Personal AI Assistant \u2014 Setup Wizard${R}
|
|
553
|
-
`)}var R,Ze,ae,
|
|
550
|
+
`)}var R,Ze,ae,us,Y,ps,Bi,Wi,Pt,Je,io=h(()=>{"use strict";R="\x1B[0m",Ze="\x1B[1m",ae="\x1B[2m",us="\x1B[32m",Y="\x1B[33m",ps="\x1B[36m",Bi="\x1B[31m",Wi="\x1B[35m";d(N,"green");d(Hi,"yellow");d(Se,"cyan");d(no,"red");d($,"bold");d(S,"dim");d(be,"maskKey");Pt=[{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"}],Je=[{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(Xi,"loadExistingConfig");d(zi,"setupCommand");d(O,"askWithDefault");d(ie,"askRequired");d(dr,"askNumber");d(qi,"printBanner")});var co={};q(co,{configCommand:()=>Yi});function Vi(c){let e=c.toLowerCase();return Ki.some(t=>e.includes(t))}function Gi(c){return typeof c!="string"||c.length===0?"(empty)":c.length<=8?"***":c.slice(0,4)+"..."+c.slice(-4)}function ao(c){let e={};for(let[t,s]of Object.entries(c))Vi(t)?e[t]=Gi(s):s!=null&&typeof s=="object"&&!Array.isArray(s)?e[t]=ao(s):e[t]=s;return e}async function Yi(){let c=new W,e;try{e=c.loadConfig()}catch(s){console.error("Failed to load configuration:",s.message),process.exit(1)}let t=ao(e);console.log("Alfred \u2014 Resolved Configuration"),console.log("================================"),console.log(JSON.stringify(t,null,2))}var Ki,lo=h(()=>{"use strict";le();Ki=["token","apikey","api_key","accesstoken","secret","password"];d(Vi,"isSensitiveKey");d(Gi,"redactValue");d(ao,"redactObject");d(Yi,"configCommand")});var po={};q(po,{rulesCommand:()=>Zi});import ms from"node:fs";import uo from"node:path";import Ji from"js-yaml";async function Zi(){let c=new W,e;try{e=c.loadConfig()}catch(a){console.error("Failed to load configuration:",a.message),process.exit(1)}let t=uo.resolve(e.security.rulesPath);if(!ms.existsSync(t)){console.log(`Rules directory not found: ${t}`),console.log("No security rules loaded.");return}ms.statSync(t).isDirectory()||(console.error(`Rules path is not a directory: ${t}`),process.exit(1));let r=ms.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 me,o=[],i=[];for(let a of r){let l=uo.join(t,a);try{let u=ms.readFileSync(l,"utf-8"),m=Ji.load(u),p=n.loadFromObject(m);o.push(...p)}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 mo=h(()=>{"use strict";le();Yt();d(Zi,"rulesCommand")});var ho={};q(ho,{statusCommand:()=>ea});import Ft from"node:fs";import pr from"node:path";import Qi from"js-yaml";async function ea(){let c=new W,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",m=l.enabled?"+":"-";console.log(` [${m}] ${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=pr.resolve(e.storage.path),n=Ft.existsSync(r);console.log(` Database: ${r}`),console.log(` Status: ${n?"exists":"not yet created"}`),console.log("");let o=pr.resolve(e.security.rulesPath),i=0,a=0;if(Ft.existsSync(o)&&Ft.statSync(o).isDirectory()){let l=Ft.readdirSync(o).filter(m=>m.endsWith(".yml")||m.endsWith(".yaml"));a=l.length;let u=new me;for(let m of l){let p=pr.join(o,m);try{let f=Ft.readFileSync(p,"utf-8"),E=Qi.load(f),w=u.loadFromObject(E);i+=w.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 fo=h(()=>{"use strict";le();Yt();d(ea,"statusCommand")});var go={};q(go,{logsCommand:()=>ra});import ta from"node:fs";import sa from"node:path";async function ra(c){let e=new W,t;try{t=e.loadConfig()}catch(n){console.error("Failed to load configuration:",n.message),process.exit(1)}let s=sa.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 de(s);let n=new ue(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 yo=h(()=>{"use strict";le();As();d(ra,"logsCommand")});import{readFileSync as na}from"node:fs";import{fileURLToPath as oa}from"node:url";import{dirname as ia,join as aa}from"node:path";function ca(){try{let c=ia(oa(import.meta.url));for(let e of["../package.json","../../package.json"])try{let t=JSON.parse(na(aa(c,e),"utf-8"));if(t.version)return t.version}catch{}}catch{}return"0.0.0"}d(ca,"getVersion");var wo=ca(),mr=`
|
|
554
551
|
Alfred CLI v${wo}
|
|
555
552
|
Personal AI Assistant
|
|
556
553
|
|