@spfunctions/cli 2.0.5 → 2.0.6
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/dist/12.index.js +1 -1
- package/dist/160.index.js +1 -1
- package/dist/482.index.js +1 -0
- package/dist/563.index.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/12.index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.id=12,exports.ids=[12],exports.modules={6012:function(e,t,s){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.startBot=async function(e){const t=(0,l.loadConfig)(),a=e.token||t.telegramBotToken||process.env.TELEGRAM_BOT_TOKEN;a||(console.error("No Telegram bot token. Use --token, set TELEGRAM_BOT_TOKEN, or add to ~/.sf/config.json"),process.exit(1));const o=new c.SFClient(t.apiKey,t.apiUrl),f=new n.Bot(a),m=e.chatId||null,y=new Map;function w(e){return!m||e===m}f.command("start",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id);try{const{theses:s}=await o.listTheses(),a=(s||[]).filter(e=>"active"===e.status);a.length>0?(t.thesisId=a[0].id,await e.reply(`✅ Connected to SimpleFunctions\n\nActive thesis: <b>${(a[0].rawThesis||"").slice(0,60)}</b>\nID: <code>${a[0].id.slice(0,8)}</code>\n\nCommands:\n/context — thesis snapshot\n/positions — Kalshi positions\n/edges — top edges\n/balance — account balance\n/orders — resting orders\n/eval — trigger evaluation\n/list — all theses\n/switch — switch thesis\n\nOr just type naturally.`,{parse_mode:"HTML"}),y.has(e.chat.id)&&clearInterval(y.get(e.chat.id)),y.set(e.chat.id,(0,u.startPoller)(f,e.chat.id,o,t.thesisId))):await e.reply('No active theses found. Create one with `sf create "your thesis"`')}catch(t){await e.reply(`❌ Connection failed: ${t.message}\nCheck SF_API_KEY in ~/.sf/config.json`)}}),f.command("context",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id);if(t.thesisId)try{const s=await(0,h.handleContext)(o,t.thesisId);for(const t of(0,d.splitMessage)(s))await e.reply(t,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("No thesis selected. Use /start or /switch <id>")}),f.command("positions",async e=>{if(w(e.chat.id))try{const t=await(0,h.handlePositions)();for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("edges",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleEdges)(o);for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("balance",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleBalance)();await e.reply(t,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("orders",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleOrders)();for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("eval",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id);if(t.thesisId)try{const s=await(0,h.handleEval)(o,t.thesisId);await e.reply(s)}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("No thesis selected.")}),f.command("list",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleList)(o);for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("switch",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id),s=e.match?.trim();if(s)try{const{theses:a}=await o.listTheses(),n=(a||[]).find(e=>e.id.startsWith(s));n?(t.thesisId=n.id,t.agentMessages=[],y.has(e.chat.id)&&clearInterval(y.get(e.chat.id)),y.set(e.chat.id,(0,u.startPoller)(f,e.chat.id,o,t.thesisId)),await e.reply(`Switched to: <code>${n.id.slice(0,8)}</code> — ${(n.rawThesis||"").slice(0,60)}`,{parse_mode:"HTML"})):await e.reply(`No thesis found matching "${s}". Use /list to see all.`)}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("Usage: /switch <thesis_id>")}),f.on("message:text",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id),a=e.message.text;if(!a.startsWith("/")){if(!t.thesisId)try{const{theses:s}=await o.listTheses(),a=(s||[]).filter(e=>"active"===e.status);if(!(a.length>0))return void await e.reply('No active theses. Create one with `sf create "your thesis"` then /start');t.thesisId=a[0].id}catch{return void await e.reply("Could not connect. Use /start first.")}try{const n=setInterval(()=>{e.replyWithChatAction("typing").catch(()=>{})},4e3);await e.replyWithChatAction("typing");const{runAgentMessage:r}=await s.e(160).then(s.bind(s,28160)),i=new Promise((e,t)=>setTimeout(()=>t(new Error("Response timeout (30s)")),3e4));let c;try{c=await Promise.race([r(o,t,a),i])}finally{clearInterval(n)}if(c&&0!==c.trim().length)for(const t of(0,d.splitMessage)(c))try{await e.reply(t,{parse_mode:"HTML"})}catch{await e.reply(t)}else await e.reply("No response generated. Try rephrasing or use a slash command.")}catch(t){console.error("[Telegram] Agent error:",t.message),await e.reply(`❌ ${t.message}`)}}}),f.on("callback_query:data",async e=>{const t=e.callbackQuery.data;t.startsWith("order_confirm:")?await e.answerCallbackQuery({text:"Order execution coming soon"}):"order_cancel"===t&&(await e.answerCallbackQuery({text:"Order cancelled"}),await e.editMessageText("❌ Order cancelled."))}),console.log("🤖 SimpleFunctions Telegram bot starting..."),console.log(" SF API: "+(t.apiKey?"✓":"✗")),console.log(" Kalshi: "+(process.env.KALSHI_API_KEY_ID?"✓":"✗")),console.log(" OpenRouter: "+(t.openrouterKey?"✓":"✗")),m&&console.log(` Restricted to chat: ${m}`);function $(){for(const e of y.values())clearInterval(e);f.stop();try{r.default.unlinkSync(p)}catch{}}console.log(" Press Ctrl+C to stop.\n"),r.default.mkdirSync(i.default.dirname(p),{recursive:!0}),r.default.writeFileSync(p,String(process.pid)),process.on("uncaughtException",e=>{console.error("[Telegram] Uncaught exception:",e.message)}),process.on("unhandledRejection",e=>{console.error("[Telegram] Unhandled rejection:",e?.message||e)}),process.on("SIGINT",()=>{$(),process.exit(0)}),process.on("SIGTERM",()=>{$(),process.exit(0)}),process.on("exit",()=>{try{r.default.unlinkSync(p)}catch{}});for(let e=0;e<=5;e++)try{await f.start({onStart:()=>console.log("[Telegram] Polling started successfully")});break}catch(t){if((t?.message?.includes("409")||409===t?.error_code)&&e<5){const t=5*(e+1);console.error(`[Telegram] 409 conflict — retrying in ${t}s (${e+1}/5)`),await new Promise(e=>setTimeout(e,1e3*t));continue}console.error(`[Telegram] Fatal: ${t.message}`),$(),process.exit(1)}};const n=s(53278),r=a(s(79896)),i=a(s(16928)),o=a(s(70857)),c=s(19218),l=s(11627),d=s(76342),h=s(77499),u=s(55875),p=i.default.join(o.default.homedir(),".sf","telegram.pid"),f=new Map;function g(e){return f.has(e)||f.set(e,{thesisId:null,agentMessages:[]}),f.get(e)}},77499:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.handleContext=async function(e,t){const s=await e.getContext(t),a="number"==typeof s.confidence?Math.round(100*s.confidence):"?",r=s.thesis||s.rawThesis||"N/A";let i=`📋 <b>${(0,n.escapeHtml)(r.slice(0,80))}</b>\n`;i+=`Confidence: <b>${a}%</b> | Status: ${s.status}\n\n`;const o=(s.edges||[]).slice(0,8);if(o.length>0){i+="<b>Top Edges:</b>\n<pre>";for(const e of o){i+=`${(e.market||e.marketTitle||"???").slice(0,35).padEnd(36)} ${String(e.edge||0).padStart(3)}¢ ${e.direction||"yes"}\n`}i+="</pre>"}return i},t.handlePositions=async function(){if(!(0,a.isKalshiConfigured)())return"⚠️ Kalshi not configured. Run <code>sf setup --kalshi</code>";const e=await(0,a.getPositions)();if(!e||0===e.length)return"No open positions.";let t=0;const s=[];for(const r of e){const e=await(0,a.getMarketPrice)(r.ticker)??r.average_price_paid,i=(e-r.average_price_paid)*r.quantity;t+=i;const o=(0,n.fmtDollar)(i);s.push(`${r.ticker.slice(0,28).padEnd(29)} ${String(r.quantity).padStart(5)} ${String(r.average_price_paid).padStart(3)}¢→${String(e).padStart(3)}¢ ${o}`)}let r="📊 <b>Positions</b>\n<pre>";return r+=s.join("\n"),r+=`\n${"─".repeat(50)}\nTotal P&L: ${(0,n.fmtDollar)(t)}`,r+="</pre>",r},t.handleEdges=async function(e){const{theses:t}=await e.listTheses(),s=(t||[]).filter(e=>"active"===e.status),a=await Promise.allSettled(s.map(async t=>((await e.getContext(t.id)).edges||[]).map(e=>({...e,thesisId:t.id})))),n=[];for(const e of a)"fulfilled"===e.status&&n.push(...e.value);n.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0));const r=n.slice(0,10);if(0===r.length)return"No edges found.";let i="📈 <b>Top Edges</b>\n<pre>";for(const e of r){const t=(e.market||"???").slice(0,35),s=e.orderbook?.liquidityScore||"?";i+=`${t.padEnd(36)} +${String(e.edge||0).padStart(2)}¢ ${s}\n`}return i+="</pre>",i},t.handleBalance=async function(){if(!(0,a.isKalshiConfigured)())return"⚠️ Kalshi not configured.";const e=await(0,a.getBalance)();return e?`💰 Balance: <b>$${e.balance.toFixed(2)}</b> | Portfolio: <b>$${e.portfolioValue.toFixed(2)}</b>`:"⚠️ Failed to fetch balance."},t.handleOrders=async function(){if(!(0,a.isKalshiConfigured)())return"⚠️ Kalshi not configured.";const e=await(0,a.getOrders)({status:"resting",limit:20});if(!e||!e.orders||0===e.orders.length)return"No resting orders.";let t="📋 <b>Resting Orders</b>\n<pre>";for(const s of e.orders){const e=Math.round(parseFloat(s.remaining_count_fp||"0")),a=Math.round(100*parseFloat(s.yes_price_dollars||"0")),n=(s.ticker||"???").slice(0,25);t+=`${s.action} ${e}x ${n} @ ${a}¢\n`}return t+="</pre>",t},t.handleEval=async function(e,t){return await e.evaluate(t),"⚡ Evaluation triggered. Results in ~2 minutes."},t.handleList=async function(e){const{theses:t}=await e.listTheses();if(!t||0===t.length)return"No theses.";let s="📝 <b>Theses</b>\n<pre>";for(const e of t){const t="number"==typeof e.confidence?Math.round(100*e.confidence):0,a=(e.rawThesis||e.thesis||"").slice(0,50);s+=`${e.id.slice(0,8)} ${String(t).padStart(3)}% ${e.status.padEnd(8)} ${a}\n`}return s+="</pre>",s};const a=s(96139),n=s(76342)},76342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitMessage=function(e,t=4e3){if(e.length<=t)return[e];const s=[];let a=e;for(;a.length>0;){if(a.length<=t){s.push(a);break}let e=a.lastIndexOf("\n",t);e<.5*t&&(e=t),s.push(a.slice(0,e)),a=a.slice(e)}return s},t.fmtDollar=function(e){const t=e/100;return t>=0?`+$${t.toFixed(2)}`:`-$${Math.abs(t).toFixed(2)}`},t.sparkline=function(e){if(0===e.length)return"";const t=Math.min(...e),s=Math.max(...e)-t||1;return e.map(e=>"▁▂▃▄▅▆▇█"[Math.round((e-t)/s*7)]).join("")},t.escapeHtml=function(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}},55875:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.startPoller=function(e,t,s,n){let r=(new Date).toISOString();return setInterval(async()=>{try{const i=await s.getChanges(n,r);if(r=(new Date).toISOString(),!i||!i.changed)return;const o=i.confidenceDelta??i.delta??0;if(Math.abs(o)<.02)return;const c="number"==typeof i.confidence?Math.round(100*i.confidence):"?",l=o>0?"📈":"📉",d=o>0?"+":"",h=i.summary||i.latestSummary||"";let u=`${l} <b>Confidence ${d}${Math.round(100*o)}% → ${c}%</b>\n`;h&&(u+=`${(0,a.escapeHtml)(h.slice(0,200))}`),await e.api.sendMessage(t,u,{parse_mode:"HTML"})}catch{}},6e4)};const a=s(76342)}};
|
|
1
|
+
"use strict";exports.id=12,exports.ids=[12],exports.modules={6012:function(e,t,a){var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.startBot=async function(e){const t=(0,l.loadConfig)(),s=e.token||t.telegramBotToken||process.env.TELEGRAM_BOT_TOKEN;s||(console.error("No Telegram bot token. Use --token, set TELEGRAM_BOT_TOKEN, or add to ~/.sf/config.json"),process.exit(1));const o=new c.SFClient(t.apiKey,t.apiUrl),f=new i.Bot(s),y=e.chatId||null,m=new Map;function w(e){return!y||e===y}async function $(e,t){const a=g(e);a.thesisId=t.id,a.agentMessages=[],a.agent=void 0,m.has(e)&&clearInterval(m.get(e)),m.set(e,(0,p.startPoller)(f,e,o,a.thesisId))}f.command("start",async e=>{if(!w(e.chat.id))return;g(e.chat.id);try{const{theses:t}=await o.listTheses(),a=(t||[]).filter(e=>"active"===e.status);if(0===a.length)return void await e.reply('No active theses found. Create one with `sf create "your thesis"`');if(1===a.length)await $(e.chat.id,a[0]),await e.reply(`✅ Connected\n\nThesis: <b>${(a[0].rawThesis||"").slice(0,80)}</b>\nID: <code>${a[0].id.slice(0,8)}</code>\n\nType naturally, send voice, or use /help`,{parse_mode:"HTML"});else{const t=new i.InlineKeyboard;for(const e of a.slice(0,8)){const a=`${(e.rawThesis||e.id).slice(0,40)}`;t.text(a,`pick_thesis:${e.id}`).row()}await e.reply(`✅ Connected — ${a.length} active theses\n\nPick one:`,{parse_mode:"HTML",reply_markup:t})}}catch(t){await e.reply(`❌ Connection failed: ${t.message}\nCheck SF_API_KEY in ~/.sf/config.json`)}}),f.on("callback_query:data",async e=>{const n=e.callbackQuery.data;if(n.startsWith("pick_thesis:")){const t=n.slice(12);try{const{theses:a}=await o.listTheses(),s=(a||[]).find(e=>e.id===t);if(!s)return void await e.answerCallbackQuery({text:"Thesis not found"});await $(e.chat.id,s),await e.answerCallbackQuery({text:`Selected: ${(s.rawThesis||"").slice(0,30)}`}),await e.editMessageText(`✅ Active: <b>${(s.rawThesis||"").slice(0,80)}</b>\nID: <code>${s.id.slice(0,8)}</code>\n\nType naturally, send voice, or use /help`,{parse_mode:"HTML"})}catch(t){await e.answerCallbackQuery({text:`Error: ${t.message}`})}return}f.command("context",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id);if(t.thesisId)try{const a=await(0,h.handleContext)(o,t.thesisId);for(const t of(0,d.splitMessage)(a))await e.reply(t,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("No thesis selected. Use /start or /switch <id>")}),f.command("positions",async e=>{if(w(e.chat.id))try{const t=await(0,h.handlePositions)();for(const a of(0,d.splitMessage)(t))await e.reply(a,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("edges",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleEdges)(o);for(const a of(0,d.splitMessage)(t))await e.reply(a,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("balance",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleBalance)();await e.reply(t,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("orders",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleOrders)();for(const a of(0,d.splitMessage)(t))await e.reply(a,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("eval",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id);if(t.thesisId)try{const a=await(0,h.handleEval)(o,t.thesisId);await e.reply(a)}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("No thesis selected.")}),f.command("help",async e=>{w(e.chat.id)&&await e.reply("<b>Commands</b>\n/context — thesis snapshot\n/positions — Kalshi positions\n/edges — top edges\n/balance — account balance\n/orders — resting orders\n/eval — trigger evaluation\n/list — all theses\n/switch <id> — switch thesis\n\n🎤 Send a voice message to talk\n💬 Or just type naturally",{parse_mode:"HTML"})}),f.command("list",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleList)(o);for(const a of(0,d.splitMessage)(t))await e.reply(a,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("switch",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id),a=e.match?.trim();if(a)try{const{theses:s}=await o.listTheses(),i=(s||[]).find(e=>e.id.startsWith(a));i?(t.thesisId=i.id,t.agentMessages=[],t.agent=void 0,m.has(e.chat.id)&&clearInterval(m.get(e.chat.id)),m.set(e.chat.id,(0,p.startPoller)(f,e.chat.id,o,t.thesisId)),await e.reply(`Switched to: <code>${i.id.slice(0,8)}</code> — ${(i.rawThesis||"").slice(0,60)}`,{parse_mode:"HTML"})):await e.reply(`No thesis found matching "${a}". Use /list to see all.`)}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("Usage: /switch <thesis_id>")}),f.on("message:text",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id),s=e.message.text;if(!s.startsWith("/")){if(!t.thesisId)try{const{theses:a}=await o.listTheses(),s=(a||[]).filter(e=>"active"===e.status);if(!(s.length>0))return void await e.reply('No active theses. Create one with `sf create "your thesis"` then /start');t.thesisId=s[0].id}catch{return void await e.reply("Could not connect. Use /start first.")}try{const i=await e.reply("⏳ Thinking..."),n=[];let r=0;const c=setInterval(()=>{e.replyWithChatAction("typing").catch(()=>{})},4e3);await e.replyWithChatAction("typing");const{runAgentMessage:l}=await a.e(160).then(a.bind(a,28160)),h=new Promise((e,t)=>setTimeout(()=>t(new Error("Response timeout (30s)")),3e4)),p=t=>{n.push(t);const a=Date.now();if(a-r>1e3){r=a;const t=n.map(e=>`⚡ ${e}`).join(" → ");e.api.editMessageText(e.chat.id,i.message_id,`⏳ ${t}...`).catch(()=>{})}};let u;try{u=await Promise.race([l(o,t,s,p),h])}finally{clearInterval(c)}try{await e.api.deleteMessage(e.chat.id,i.message_id)}catch{}if(u&&0!==u.trim().length)for(const t of(0,d.splitMessage)(u))try{await e.reply(t,{parse_mode:"HTML"})}catch{await e.reply(t)}else await e.reply("No response generated. Try rephrasing or use a slash command.")}catch(t){console.error("[Telegram] Agent error:",t.message),await e.reply(`❌ ${t.message}`)}}}),f.on(["message:voice","message:audio"],async e=>{if(!w(e.chat.id))return;const n=g(e.chat.id);if(!n.thesisId)try{const{theses:t}=await o.listTheses(),a=(t||[]).filter(e=>"active"===e.status);if(!(a.length>0))return void await e.reply("No active theses. Create one first.");n.thesisId=a[0].id}catch{return void await e.reply("Could not connect. Use /start first.")}try{await e.replyWithChatAction("typing");const r=e.message.voice||e.message.audio;if(!r)return void await e.reply("Could not read audio.");const c=await e.api.getFile(r.file_id);if(!c.file_path)return void await e.reply("Could not download audio.");const l=`https://api.telegram.org/file/bot${s}/${c.file_path}`,h=await fetch(l);if(!h.ok)return void await e.reply("Failed to download voice message.");const p=Buffer.from(await h.arrayBuffer()),u=t.apiKey||process.env.SF_API_KEY,f=t.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev";if(!u)return void await e.reply("SF API key required for voice transcription.");const g=new Blob([p],{type:"audio/ogg"}),y=new FormData;y.append("audio",g,"voice.ogg");const m=await fetch(`${f}/api/proxy/stt`,{method:"POST",headers:{Authorization:`Bearer ${u}`},body:y,signal:AbortSignal.timeout(3e4)});if(!m.ok)return void await e.reply("Transcription failed.");const w=(await m.json()).text;if(!w||0===w.trim().length)return void await e.reply("Could not transcribe voice message.");const $=await e.reply(`🎤 "${w}"\n⏳ Thinking...`),T=[];let b=0;const _=setInterval(()=>{e.replyWithChatAction("typing").catch(()=>{})},4e3);await e.replyWithChatAction("typing");const{runAgentMessage:v}=await a.e(160).then(a.bind(a,28160)),M=t=>{T.push(t);const a=Date.now();if(a-b>1e3){b=a;const t=T.map(e=>`⚡ ${e}`).join(" → ");e.api.editMessageText(e.chat.id,$.message_id,`🎤 "${w}"\n⏳ ${t}...`).catch(()=>{})}};let S;try{S=await Promise.race([v(o,n,w,M),new Promise((e,t)=>setTimeout(()=>t(new Error("Timeout")),3e4))])}finally{clearInterval(_)}try{await e.api.editMessageText(e.chat.id,$.message_id,`🎤 "${w}"`)}catch{}if(S&&S.trim().length>0){for(const t of(0,d.splitMessage)(S))try{await e.reply(t,{parse_mode:"HTML"})}catch{await e.reply(t)}const t=S.replace(/<[^>]*>/g,"").trim();if(t.length>0&&t.length<500)try{const a=await fetch(`${f}/api/proxy/tts`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},body:JSON.stringify({text:t.slice(0,500)}),signal:AbortSignal.timeout(15e3)});if(a.ok){const t=Buffer.from(await a.arrayBuffer());await e.replyWithVoice(new i.InputFile(t,"reply.mp3"))}}catch{}}}catch(t){console.error("[Telegram] Voice error:",t.message),await e.reply(`❌ Voice: ${t.message}`)}}),n.startsWith("order_confirm:")?await e.answerCallbackQuery({text:"Order execution coming soon"}):"order_cancel"===n&&(await e.answerCallbackQuery({text:"Order cancelled"}),await e.editMessageText("❌ Order cancelled."))}),console.log("🤖 SimpleFunctions Telegram bot starting..."),console.log(" SF API: "+(t.apiKey?"✓":"✗")),console.log(" Kalshi: "+(process.env.KALSHI_API_KEY_ID?"✓":"✗")),console.log(" OpenRouter: "+(t.openrouterKey?"✓":"✗")),y&&console.log(` Restricted to chat: ${y}`);function T(){for(const e of m.values())clearInterval(e);f.stop();try{n.default.unlinkSync(u)}catch{}}console.log(" Press Ctrl+C to stop.\n"),n.default.mkdirSync(r.default.dirname(u),{recursive:!0}),n.default.writeFileSync(u,String(process.pid)),process.on("uncaughtException",e=>{console.error("[Telegram] Uncaught exception:",e.message)}),process.on("unhandledRejection",e=>{console.error("[Telegram] Unhandled rejection:",e?.message||e)}),process.on("SIGINT",()=>{T(),process.exit(0)}),process.on("SIGTERM",()=>{T(),process.exit(0)}),process.on("exit",()=>{try{n.default.unlinkSync(u)}catch{}});for(let e=0;e<=5;e++)try{await f.start({onStart:()=>console.log("[Telegram] Polling started successfully")});break}catch(t){if((t?.message?.includes("409")||409===t?.error_code)&&e<5){const t=5*(e+1);console.error(`[Telegram] 409 conflict — retrying in ${t}s (${e+1}/5)`),await new Promise(e=>setTimeout(e,1e3*t));continue}console.error(`[Telegram] Fatal: ${t.message}`),T(),process.exit(1)}};const i=a(53278),n=s(a(79896)),r=s(a(16928)),o=s(a(70857)),c=a(19218),l=a(11627),d=a(76342),h=a(77499),p=a(55875),u=r.default.join(o.default.homedir(),".sf","telegram.pid"),f=new Map;function g(e){return f.has(e)||f.set(e,{thesisId:null,agentMessages:[]}),f.get(e)}},77499:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.handleContext=async function(e,t){const a=await e.getContext(t),s="number"==typeof a.confidence?Math.round(100*a.confidence):"?",n=a.thesis||a.rawThesis||"N/A";let r=`📋 <b>${(0,i.escapeHtml)(n.slice(0,80))}</b>\n`;r+=`Confidence: <b>${s}%</b> | Status: ${a.status}\n\n`;const o=(a.edges||[]).slice(0,8);if(o.length>0){r+="<b>Top Edges:</b>\n<pre>";for(const e of o){r+=`${(e.market||e.marketTitle||"???").slice(0,35).padEnd(36)} ${String(e.edge||0).padStart(3)}¢ ${e.direction||"yes"}\n`}r+="</pre>"}return r},t.handlePositions=async function(){if(!(0,s.isKalshiConfigured)())return"⚠️ Kalshi not configured. Run <code>sf setup --kalshi</code>";const e=await(0,s.getPositions)();if(!e||0===e.length)return"No open positions.";let t=0;const a=[];for(const n of e){const e=await(0,s.getMarketPrice)(n.ticker)??n.average_price_paid,r=(e-n.average_price_paid)*n.quantity;t+=r;const o=(0,i.fmtDollar)(r);a.push(`${n.ticker.slice(0,28).padEnd(29)} ${String(n.quantity).padStart(5)} ${String(n.average_price_paid).padStart(3)}¢→${String(e).padStart(3)}¢ ${o}`)}let n="📊 <b>Positions</b>\n<pre>";return n+=a.join("\n"),n+=`\n${"─".repeat(50)}\nTotal P&L: ${(0,i.fmtDollar)(t)}`,n+="</pre>",n},t.handleEdges=async function(e){const{theses:t}=await e.listTheses(),a=(t||[]).filter(e=>"active"===e.status),s=await Promise.allSettled(a.map(async t=>((await e.getContext(t.id)).edges||[]).map(e=>({...e,thesisId:t.id})))),i=[];for(const e of s)"fulfilled"===e.status&&i.push(...e.value);i.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0));const n=i.slice(0,10);if(0===n.length)return"No edges found.";let r="📈 <b>Top Edges</b>\n<pre>";for(const e of n){const t=(e.market||"???").slice(0,35),a=e.orderbook?.liquidityScore||"?";r+=`${t.padEnd(36)} +${String(e.edge||0).padStart(2)}¢ ${a}\n`}return r+="</pre>",r},t.handleBalance=async function(){if(!(0,s.isKalshiConfigured)())return"⚠️ Kalshi not configured.";const e=await(0,s.getBalance)();return e?`💰 Balance: <b>$${e.balance.toFixed(2)}</b> | Portfolio: <b>$${e.portfolioValue.toFixed(2)}</b>`:"⚠️ Failed to fetch balance."},t.handleOrders=async function(){if(!(0,s.isKalshiConfigured)())return"⚠️ Kalshi not configured.";const e=await(0,s.getOrders)({status:"resting",limit:20});if(!e||!e.orders||0===e.orders.length)return"No resting orders.";let t="📋 <b>Resting Orders</b>\n<pre>";for(const a of e.orders){const e=Math.round(parseFloat(a.remaining_count_fp||"0")),s=Math.round(100*parseFloat(a.yes_price_dollars||"0")),i=(a.ticker||"???").slice(0,25);t+=`${a.action} ${e}x ${i} @ ${s}¢\n`}return t+="</pre>",t},t.handleEval=async function(e,t){return await e.evaluate(t),"⚡ Evaluation triggered. Results in ~2 minutes."},t.handleList=async function(e){const{theses:t}=await e.listTheses();if(!t||0===t.length)return"No theses.";let a="📝 <b>Theses</b>\n<pre>";for(const e of t){const t="number"==typeof e.confidence?Math.round(100*e.confidence):0,s=(e.rawThesis||e.thesis||"").slice(0,50);a+=`${e.id.slice(0,8)} ${String(t).padStart(3)}% ${e.status.padEnd(8)} ${s}\n`}return a+="</pre>",a};const s=a(96139),i=a(76342)},76342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitMessage=function(e,t=4e3){if(e.length<=t)return[e];const a=[];let s=e;for(;s.length>0;){if(s.length<=t){a.push(s);break}let e=s.lastIndexOf("\n",t);e<.5*t&&(e=t),a.push(s.slice(0,e)),s=s.slice(e)}return a},t.fmtDollar=function(e){const t=e/100;return t>=0?`+$${t.toFixed(2)}`:`-$${Math.abs(t).toFixed(2)}`},t.sparkline=function(e){if(0===e.length)return"";const t=Math.min(...e),a=Math.max(...e)-t||1;return e.map(e=>"▁▂▃▄▅▆▇█"[Math.round((e-t)/a*7)]).join("")},t.escapeHtml=function(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}},55875:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.startPoller=function(e,t,a,i){let n=(new Date).toISOString();return setInterval(async()=>{try{const r=await a.getChanges(i,n);if(n=(new Date).toISOString(),!r||!r.changed)return;const o=r.confidenceDelta??r.delta??0;if(Math.abs(o)<.02)return;const c="number"==typeof r.confidence?Math.round(100*r.confidence):"?",l=o>0?"📈":"📉",d=o>0?"+":"",h=r.summary||r.latestSummary||"";let p=`${l} <b>Confidence ${d}${Math.round(100*o)}% → ${c}%</b>\n`;h&&(p+=`${(0,s.escapeHtml)(h.slice(0,200))}`),await e.api.sendMessage(t,p,{parse_mode:"HTML"})}catch{}},6e4)};const s=a(76342)}};
|
package/dist/160.index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.id=160,exports.ids=[160],exports.modules={28160:(e,t,n)=>{t.runAgentMessage=async function(e,t,n){const s=await o(e,t);return new Promise((e,a)=>{let r="",o="";const c=setTimeout(()=>{e(r||o||"Response timeout (45s). Try a simpler question.")},45e3),l=s.subscribe(a=>{if("message_update"===a.type){const e=a.assistantMessageEvent;"text_delta"===e.type&&(r+=e.delta)}if("tool_execution_start"===a.type&&(o+=`⚡ ${a.toolName}\n`),"agent_end"===a.type){clearTimeout(c),l?.(),t.agentMessages=s.state.messages||[];try{t.thesisId&&((0,i.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"user",content:n,source:"telegram"}),r&&(0,i.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"assistant",content:r.slice(0,5e3),source:"telegram"}))}catch{}e(r||o||"(no response)")}});s.prompt(n).catch(e=>{clearTimeout(c),l?.(),a(e)})})};const s=n(11627),i=n(73600);let a=null;async function r(){if(a)return a;const[e,t]=await Promise.all([Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653)),Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641))]),s=await Promise.all([n.e(788),n.e(722)]).then(n.bind(n,85722));return a={Agent:e.Agent,streamSimple:t.streamSimple,Type:s.Type},a}async function o(e,t){if(t.agent)return t.agent;const{Agent:a,streamSimple:o}=await r(),c=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),{getModel:l}=c,p=(0,s.loadConfig)(),d=p.openrouterKey||process.env.OPENROUTER_API_KEY,u=p.apiKey||process.env.SF_API_KEY,m=p.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev",h=!d&&!!u,g=d||u;if(!g)throw new Error("Need API key. Run sf login or sf setup.");const y=await e.getContext(t.thesisId),f="number"==typeof y.confidence?Math.round(100*y.confidence):50,x=await async function(e,t,a){const{Type:o}=await r(),c=(0,s.loadConfig)(),l=o.Object({}),p=await Promise.resolve().then(n.t.bind(n,96139,23)),{kalshiFetchAllSeries:d,kalshiFetchMarketsBySeries:u,kalshiFetchMarket:m}=await Promise.resolve().then(n.bind(n,19218)),h=[{name:"get_context",label:"Context",description:"Get thesis snapshot with causal tree, edges, evaluation",parameters:l,execute:async()=>{const n=await e.getContext(t);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"global_context",label:"Snapshot",description:"Global market snapshot — movers, expiring, milestones, liquidity, signals. No thesis needed.",parameters:l,execute:async()=>{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218)),t=await e();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"query",label:"Query",description:"LLM-enhanced prediction market search. Returns answer, live prices, key factors.",parameters:o.Object({q:o.String({description:"Question"})}),execute:async(e,t)=>{const{fetchQuery:s}=await Promise.resolve().then(n.bind(n,19218)),i=await s(t.q);return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"get_markets",label:"Markets",description:"Traditional market prices: SPY, VIX, Treasury, Gold, Oil.",parameters:l,execute:async()=>{const{fetchTraditionalMarkets:e}=await Promise.resolve().then(n.bind(n,19218)),t=await e();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"inject_signal",label:"Signal",description:"Inject a signal (news, note, observation) into the thesis",parameters:o.Object({content:o.String({description:"Signal content"}),type:o.Optional(o.String({description:"news | user_note | external"}))}),execute:async(n,s)=>(await e.injectSignal(t,s.type||"user_note",s.content,"telegram"),{content:[{type:"text",text:"Signal injected."}],details:{}})},{name:"trigger_evaluation",label:"Evaluate",description:"Trigger a deep evaluation cycle",parameters:l,execute:async()=>(await e.evaluate(t),{content:[{type:"text",text:"Evaluation triggered. Results in ~2 minutes."}],details:{}})},{name:"scan_markets",label:"Scan",description:"Search Kalshi markets by keyword, series, or ticker",parameters:o.Object({query:o.Optional(o.String({description:"Keyword search"})),series:o.Optional(o.String({description:"Series ticker"})),market:o.Optional(o.String({description:"Market ticker"}))}),execute:async(e,t)=>{let n;if(t.market)n=await m(t.market);else if(t.series)n=await u(t.series);else if(t.query){const e=await d(),s=t.query.toLowerCase().split(/\s+/);n=e.filter(e=>s.every(t=>((e.title||"")+(e.ticker||"")).toLowerCase().includes(t))).filter(e=>parseFloat(e.volume_fp||"0")>1e3).sort((e,t)=>parseFloat(t.volume_fp||"0")-parseFloat(e.volume_fp||"0")).slice(0,10)}else n={error:"Provide query, series, or market"};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"list_theses",label:"List",description:"List all theses",parameters:l,execute:async()=>{const t=await e.listTheses();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_positions",label:"Positions",description:"Get Kalshi positions with live prices and P&L",parameters:l,execute:async()=>{const e=await p.getPositions();if(!e)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};for(const t of e){const e=await p.getMarketPrice(t.ticker);null!=e&&(t.current_value=e,t.unrealized_pnl=Math.round((e-t.average_price_paid)*t.quantity))}const t=e.map(e=>({ticker:e.ticker,qty:e.quantity,avg_price:`${e.average_price_paid}¢`,current:`${e.current_value}¢`,pnl:`$${((e.unrealized_pnl||0)/100).toFixed(2)}`}));return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance",parameters:l,execute:async()=>{const e=await p.getBalance();return e?{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_orders",label:"Orders",description:"Get resting orders on Kalshi",parameters:l,execute:async()=>{const e=await p.getOrders({status:"resting",limit:50});return e?{content:[{type:"text",text:JSON.stringify(e.orders,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_fills",label:"Fills",description:"Get recent trade fills",parameters:o.Object({ticker:o.Optional(o.String())}),execute:async(e,t)=>{const n=await p.getFills({ticker:t.ticker,limit:20});return n?{content:[{type:"text",text:JSON.stringify(n.fills,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled contracts with P&L",parameters:l,execute:async()=>{const e=await p.getSettlements({limit:50});return e?{content:[{type:"text",text:JSON.stringify(e.settlements,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_edges",label:"Edges",description:"Top 10 edges across all active theses",parameters:l,execute:async()=>{const{theses:t}=await e.listTheses(),n=(t||[]).filter(e=>"active"===e.status),s=await Promise.allSettled(n.map(async t=>((await e.getContext(t.id)).edges||[]).map(e=>({...e,thesisId:t.id})))),i=[];for(const e of s)"fulfilled"===e.status&&i.push(...e.value);return i.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0)),{content:[{type:"text",text:JSON.stringify(i.slice(0,10),null,2)}],details:{}}}},{name:"get_schedule",label:"Schedule",description:"Exchange status (open/closed) and trading hours",parameters:l,execute:async()=>{const e=await fetch("https://api.elections.kalshi.com/trade-api/v2/exchange/status",{headers:{Accept:"application/json"}});if(!e.ok)return{content:[{type:"text",text:`API error: ${e.status}`}],details:{}};const t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_feed",label:"Feed",description:"Recent evaluation history",parameters:o.Object({hours:o.Optional(o.Number({description:"Hours of history (default 24)"}))}),execute:async(t,n)=>{const s=await e.getFeed(n.hours||24);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"web_search",label:"Search",description:"Search the web for latest news",parameters:o.Object({query:o.String({description:"Search query"})}),execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY||c.tavilyKey,s=c.apiKey||process.env.SF_API_KEY,i=c.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev";if(!n&&(n||!s))return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let a;if(a=n?await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}):await fetch(`${i}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}),!a.ok)return{content:[{type:"text",text:`Search failed: ${a.status}`}],details:{}};const r=await a.json();return{content:[{type:"text",text:`${r.answer?`Summary: ${r.answer}\n\n`:""}${(r.results||[]).map(e=>`${e.title}: ${(e.content||"").slice(0,150)}`).join("\n\n")}`}],details:{}}}},{name:"create_thesis",label:"Create",description:"Create a new thesis",parameters:o.Object({rawThesis:o.String({description:"Thesis statement"})}),execute:async(t,n)=>{const s=await e.createThesis(n.rawThesis,!0);return{content:[{type:"text",text:`Created: ${s.id}\nConfidence: ${Math.round(100*(s.confidence||.5))}%`}],details:{}}}},{name:"what_if",label:"What-If",description:"Override causal tree node probabilities and see how edges change. Zero LLM cost.",parameters:o.Object({overrides:o.Array(o.Object({nodeId:o.String({description:"Node ID (e.g. n1, n3.1)"}),newProbability:o.Number({description:"New probability 0-1"})}))}),execute:async(e,t)=>{const n=a,s=[];!function e(t){for(const n of t)s.push(n),n.children?.length&&e(n.children)}(n?.causalTree?.nodes||[]);const i=new Map(t.overrides.map(e=>[e.nodeId,e.newProbability])),r=(n?.causalTree?.nodes||[]).filter(e=>!e.parentId||0===e.depth),o=r.reduce((e,t)=>e+(t.probability||.5),0)/Math.max(r.length,1);for(const e of s)i.has(e.id)&&(e.probability=i.get(e.id));const c=r.reduce((e,t)=>e+(t.probability||.5),0)/Math.max(r.length,1),l=(n?.edges||[]).slice(0,10).map(e=>{const t=s.find(t=>t.id===e.relatedNodeId);if(!t||!i.has(t.id))return{market:e.market,oldEdge:e.edge,newEdge:e.edge,signal:"unchanged"};const n=t.probability/(e.confidence||.5),a=Math.round(e.thesisPrice*n)-e.marketPrice;return{market:e.market,oldEdge:e.edge,newEdge:a,signal:Math.abs(a-e.edge)<1?"unchanged":"changed"}}).filter(e=>"unchanged"!==e.signal);return{content:[{type:"text",text:JSON.stringify({confidence:{old:Math.round(100*o),new:Math.round(100*c)},edges:l},null,2)}],details:{}}}}];h.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:o.Object({query:o.String({description:"Search query"}),mode:o.Optional(o.String({description:'"summary" or "raw"'})),hours:o.Optional(o.Number({description:"Hours (default 24)"}))}),execute:async(t,n)=>{const s=await e.searchX(n.query,{mode:n.mode,hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_volume",label:"X Volume",description:"X discussion volume trend — total posts, velocity, peak time.",parameters:o.Object({query:o.String({description:"Search query"}),hours:o.Optional(o.Number({description:"Hours (default 72)"}))}),execute:async(t,n)=>{const s=await e.getXVolume(n.query,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_news",label:"X News",description:"News stories trending on X — titles, summaries, tickers.",parameters:o.Object({query:o.String({description:"Search query"}),limit:o.Optional(o.Number({description:"Max stories (default 10)"}))}),execute:async(t,n)=>{const s=await e.searchXNews(n.query,{limit:n.limit});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_account",label:"X Account",description:"Recent posts from a specific X account.",parameters:o.Object({username:o.String({description:"X username (with or without @)"}),hours:o.Optional(o.Number({description:"Hours (default 24)"}))}),execute:async(t,n)=>{const s=await e.getXAccount(n.username,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"heartbeat_config",label:"Heartbeat Config",description:"View or update heartbeat settings: scan intervals, model tier, budget cap, pause/resume. Shows cost breakdown.",parameters:o.Object({thesisId:o.String({description:"Thesis ID"}),newsIntervalMin:o.Optional(o.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:o.Optional(o.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:o.Optional(o.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:o.Optional(o.Number({description:"Monthly budget (0 = unlimited)"})),paused:o.Optional(o.Boolean({description:"Pause or resume heartbeat"}))}),execute:async(t,n)=>{if(n.newsIntervalMin||n.xIntervalMin||n.evalModelTier||void 0!==n.monthlyBudgetUsd||void 0!==n.paused){const t={};n.newsIntervalMin&&(t.newsIntervalMin=n.newsIntervalMin),n.xIntervalMin&&(t.xIntervalMin=n.xIntervalMin),n.evalModelTier&&(t.evalModelTier=n.evalModelTier),void 0!==n.monthlyBudgetUsd&&(t.monthlyBudgetUsd=n.monthlyBudgetUsd),void 0!==n.paused&&(t.paused=n.paused),await e.updateHeartbeatConfig(n.thesisId,t)}const s=await e.getHeartbeatConfig(n.thesisId);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}});const g=process.env.SF_API_URL||c.apiUrl||"https://simplefunctions.dev";return h.push({name:"get_world_state",label:"World",description:"Real-time world model (~800 tokens). Geopolitics, economy, energy, elections, crypto, tech.",parameters:o.Object({focus:o.Optional(o.String({description:"Comma-separated topics"}))}),execute:async(e,t)=>{const n=new URLSearchParams;t.focus&&n.set("focus",t.focus);const s=await fetch(`${g}/api/agent/world?${n}`);return{content:[{type:"text",text:await s.text()}],details:{}}}},{name:"monitor_the_situation",label:"Monitor",description:"Scrape any URL (Firecrawl), analyze with any LLM, cross-reference with 9,706 markets, push to webhook.",parameters:o.Object({sourceAction:o.String({description:"scrape|crawl|search|map|extract"}),url:o.Optional(o.String()),query:o.Optional(o.String()),topics:o.Optional(o.String({description:"Comma-separated topics for market enrichment"}))}),execute:async(e,t)=>{const n={source:{action:t.sourceAction}};t.url&&(n.source.url=t.url),t.query&&(n.source.query=t.query),t.topics&&(n.enrich={enabled:!0,topics:t.topics.split(",").map(e=>e.trim()),includeIndex:!0});const s=await fetch(`${g}/api/monitor-the-situation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"enrich_content",label:"Enrich",description:"Cross-reference any text with 9,706 prediction markets. Returns divergences.",parameters:o.Object({content:o.String({description:"Text to cross-reference"}),topics:o.Optional(o.String({description:"Comma-separated topics"}))}),execute:async(e,t)=>{const n={content:t.content};t.topics?n.topics=t.topics.split(",").map(e=>e.trim()):n.topics=["general"];const s=await fetch(`${g}/api/monitor-the-situation/enrich`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"create_skill",label:"Create Skill",description:"Create a custom agent skill.",parameters:o.Object({name:o.String(),trigger:o.String(),description:o.String(),prompt:o.String(),category:o.Optional(o.String())}),execute:async(e,t)=>{const n=await fetch(`${g}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c.apiKey}`},body:JSON.stringify(t)}),s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"list_skills",label:"Skills",description:"List built-in + custom skills.",parameters:l,execute:async()=>{const e=await fetch(`${g}/api/skill`,{headers:{Authorization:`Bearer ${c.apiKey}`}}),t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"browse_public_skills",label:"Public Skills",description:"Browse community skills.",parameters:o.Object({q:o.Optional(o.String()),sort:o.Optional(o.String())}),execute:async(e,t)=>{const n=new URLSearchParams;t.q&&n.set("q",t.q),t.sort&&n.set("sort",t.sort);const s=await fetch(`${g}/api/public/skills?${n}`),i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"fork_skill",label:"Fork Skill",description:"Fork a public skill into your collection.",parameters:o.Object({skillId:o.String()}),execute:async(e,t)=>{const n=await fetch(`${g}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${c.apiKey}`}}),s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"fork_thesis",label:"Fork Thesis",description:"Fork a public thesis. Copies thesis + causal tree.",parameters:o.Object({slug:o.String()}),execute:async(e,t)=>{const n=await fetch(`${g}/api/thesis/${t.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${c.apiKey}`}}),s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}}),c.tradingEnabled&&h.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Requires trading to be enabled. Always confirm with user before placing.",parameters:o.Object({ticker:o.String({description:"Market ticker (e.g. KXWTIMAX-26DEC31-T135)"}),side:o.String({description:"yes or no"}),action:o.String({description:"buy or sell"}),count:o.Number({description:"Number of contracts"}),yes_price:o.Number({description:"Price in cents (1-99)"})}),execute:async(e,t)=>{try{const e=await p.createOrder({ticker:t.ticker,side:t.side,action:t.action,type:"limit",count:t.count,yes_price:t.yes_price});return{content:[{type:"text",text:`✓ Order placed: ${(e.order||e).order_id||"OK"}\n${t.action.toUpperCase()} ${t.count}x ${t.ticker} ${t.side.toUpperCase()} @ ${t.yes_price}¢`}],details:{}}}catch(e){return{content:[{type:"text",text:`✗ Order failed: ${e.message}`}],details:{}}}}},{name:"cancel_order",label:"Cancel Order",description:"Cancel a resting order on Kalshi.",parameters:o.Object({orderId:o.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{try{return await p.cancelOrder(t.orderId),{content:[{type:"text",text:`✓ Order ${t.orderId} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`✗ Cancel failed: ${e.message}`}],details:{}}}}}),h.push({name:"fs_read",label:"Read File",description:"Read a file from workspace (~/.sf/workspace/).",parameters:o.Object({path:o.String({description:"Relative file path"})}),execute:async(e,t)=>{const n=(0,i.wsRead)(t.path);return{content:[{type:"text",text:n.ok?n.content:`Error: ${n.content}`}],details:{}}}},{name:"fs_write",label:"Write File",description:"Write or append to a file in workspace.",parameters:o.Object({path:o.String({description:"Relative file path"}),content:o.String({description:"Content"}),append:o.Optional(o.Boolean({description:"Append mode"}))}),execute:async(e,t)=>({content:[{type:"text",text:(0,i.wsWrite)(t.path,t.content,t.append).message}],details:{}})},{name:"fs_list",label:"List Files",description:"List files in workspace.",parameters:o.Object({path:o.Optional(o.String({description:"Directory"})),glob:o.Optional(o.String({description:"Filter pattern"}))}),execute:async(e,t)=>{const n=(0,i.wsList)(t.path,t.glob);return n.ok?{content:[{type:"text",text:n.entries.length>0?n.entries.join("\n"):"(empty)"}],details:{}}:{content:[{type:"text",text:`Error: ${n.message}`}],details:{}}}},{name:"fs_search",label:"Search Files",description:"Search file contents in workspace using regex.",parameters:o.Object({pattern:o.String({description:"Regex pattern"}),path:o.Optional(o.String({description:"Directory scope"}))}),execute:async(e,t)=>{const n=(0,i.wsSearch)(t.pattern,t.path);return n.ok?0===n.matches.length?{content:[{type:"text",text:"No matches."}],details:{}}:{content:[{type:"text",text:n.matches.map(e=>`${e.file}:${e.line}: ${e.text}`).join("\n")}],details:{}}:{content:[{type:"text",text:`Error: ${n.message}`}],details:{}}}},{name:"fs_delete",label:"Delete File",description:"Delete a file from workspace.",parameters:o.Object({path:o.String({description:"File to delete"})}),execute:async(e,t)=>({content:[{type:"text",text:(0,i.wsDelete)(t.path).message}],details:{}})}),h}(e,t.thesisId,y),b=p.model||"anthropic/claude-sonnet-4.6";let w;try{w=l("openrouter",b)}catch{w={modelId:b,provider:"openrouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",id:b,name:b,inputPrice:0,outputPrice:0,contextWindow:2e5,supportsImages:!0,supportsTools:!0}}h&&(w.baseUrl=`${m}/api/proxy`);const S=(y.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.market||"").slice(0,35)} | ${e.venue||"kalshi"} | mkt ${e.marketPrice}¢ → thesis ${e.thesisPrice}¢ | edge ${e.edge>0?"+":""}${e.edge}`).join("\n")||" (no edges)",k=(y.causalTree?.nodes||[]).filter(e=>0===e.depth||!e.depth).slice(0,5).map(e=>` ${e.id} ${(e.label||"").slice(0,35)} — ${Math.round(100*(e.probability||.5))}%`).join("\n")||" (no causal tree)",O=new a({initialState:{systemPrompt:`You are a prediction market trading assistant on Telegram. Your job is to help the user see reality clearly and make correct trading decisions.\n\n## Framework\nEdge = thesis price - market price. Positive = market underprices.\nEdge types: [consensus] depth>=500 real opponents, [attention] depth<100 illusory, [timing] market lags, [risk_premium] platform risk. Tag when reporting.\nPrice: depth >= 500 = consensus, < 100 = unreliable, spread > 5 = noisy.\n\n## Rules\n- When reporting an edge, tag it: [consensus] [attention] [timing] [risk_premium].\n- If any kill condition is triggered or approaching, lead with that.\n- If nothing material to do, say "quiet — no action needed." Don't pad.\n- Keep Telegram messages SHORT — bullet points, no walls of text.\n- Prices in cents (¢). P&L in dollars ($). Don't re-convert tool output units.\n- Call tools for fresh data. Never guess prices or P&L from this prompt.\n- Use search_x for X/Twitter sentiment. Use x_volume for discussion spikes. Use x_account to track key people.\n- Use heartbeat_config to view/adjust scan intervals, model tier, budget cap, or check cost breakdown.\n- Use monitor_the_situation to scrape URLs and cross-reference with markets. Use enrich_content for text-only analysis.\n- Use get_world_state for broad situational awareness (~800 tokens).\n- Use create_skill / list_skills / browse_public_skills / fork_skill to manage agent skills.\n- Use fork_thesis to fork a public thesis (copies thesis + causal tree).\n- fs_read / fs_write / fs_list / fs_search / fs_delete: workspace filesystem (~/.sf/workspace/) for notes, analysis, data. Shared with TUI.\n- You don't know user's positions. Call get_positions before discussing trades.\n- If user mentions news, inject_signal immediately. Don't ask "should I?"\n- If user says "evaluate" or "run it", trigger immediately.\n- Don't end with "anything else?" — user will ask.\n- Use Chinese if user writes Chinese, English if English.\n${p.tradingEnabled?"- Trading ENABLED. You have place_order and cancel_order. ALWAYS confirm before placing.":"- Trading DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current State\nThesis: ${(y.thesis||y.rawThesis||"N/A").slice(0,200)}\nID: ${t.thesisId.slice(0,8)} | Confidence: ${f}%\n\nCausal nodes:\n${k}\n\nTop edges:\n${S}\n\n${y.lastEvaluation?.summary?`Latest eval: ${y.lastEvaluation.summary.slice(0,200)}`:""}`,model:w,tools:x,thinkingLevel:"off"},streamFn:o,getApiKey:e=>"openrouter"===e?g:void 0});if(t.agentMessages.length>0)try{O.replaceMessages(t.agentMessages)}catch{}return t.agent=O,O}}};
|
|
1
|
+
"use strict";exports.id=160,exports.ids=[160],exports.modules={28160:(e,t,n)=>{t.runAgentMessage=async function(e,t,n,s){const a=await o(e,t);if(t.thesisId)try{const n=await Promise.race([e.getContext(t.thesisId),new Promise((e,t)=>setTimeout(t,3e3))]);if(n){const e="number"==typeof n.confidence?Math.round(100*n.confidence):"?",t=(n.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,3),s=`\n\n## Live State\nConfidence: ${e}%\nTop edges: ${t.map(e=>`${(e.market||"").slice(0,20)} ${e.edge>0?"+":""}${e.edge}¢`).join(" | ")||"none"}`,i=a.state?.systemPrompt||"";i.includes("## Live State")?a.setSystemPrompt(i.replace(/\n\n## Live State[\s\S]*$/,s)):a.setSystemPrompt(i+s)}}catch{}return new Promise((e,r)=>{let o="",c="";const l=setTimeout(()=>{e(o||c||"Response timeout (45s). Try a simpler question.")},45e3),p=a.subscribe(r=>{if("message_update"===r.type){const e=r.assistantMessageEvent;"text_delta"===e.type&&(o+=e.delta)}if("tool_execution_start"===r.type&&(c+=`⚡ ${r.toolName}\n`,s&&s(r.toolName)),"agent_end"===r.type){clearTimeout(l),p?.(),t.agentMessages=a.state.messages||[];try{t.thesisId&&((0,i.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"user",content:n,source:"telegram"}),o&&(0,i.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"assistant",content:o.slice(0,5e3),source:"telegram"}))}catch{}e(o||c||"(no response)")}});a.prompt(n).catch(e=>{clearTimeout(l),p?.(),r(e)})})};const s=n(11627),i=n(73600);let a=null;async function r(){if(a)return a;const[e,t]=await Promise.all([Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653)),Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641))]),s=await Promise.all([n.e(788),n.e(722)]).then(n.bind(n,85722));return a={Agent:e.Agent,streamSimple:t.streamSimple,Type:s.Type},a}async function o(e,t){if(t.agent)return t.agent;const{Agent:a,streamSimple:o}=await r(),c=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),{getModel:l}=c,p=(0,s.loadConfig)(),d=p.openrouterKey||process.env.OPENROUTER_API_KEY,u=p.apiKey||process.env.SF_API_KEY,m=p.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev",h=!d&&!!u,g=d||u;if(!g)throw new Error("Need API key. Run sf login or sf setup.");const y=await e.getContext(t.thesisId),f="number"==typeof y.confidence?Math.round(100*y.confidence):50,x=await async function(e,t,a){const{Type:o}=await r(),c=(0,s.loadConfig)(),l=o.Object({}),p=await Promise.resolve().then(n.t.bind(n,96139,23)),{kalshiFetchAllSeries:d,kalshiFetchMarketsBySeries:u,kalshiFetchMarket:m}=await Promise.resolve().then(n.bind(n,19218)),h=[{name:"get_context",label:"Context",description:"Get thesis snapshot with causal tree, edges, evaluation",parameters:l,execute:async()=>{const n=await e.getContext(t);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"global_context",label:"Snapshot",description:"Global market snapshot — movers, expiring, milestones, liquidity, signals. No thesis needed.",parameters:l,execute:async()=>{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218)),t=await e();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"query",label:"Query",description:"LLM-enhanced prediction market search. Returns answer, live prices, key factors.",parameters:o.Object({q:o.String({description:"Question"})}),execute:async(e,t)=>{const{fetchQuery:s}=await Promise.resolve().then(n.bind(n,19218)),i=await s(t.q);return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"get_markets",label:"Markets",description:"Traditional market prices: SPY, VIX, Treasury, Gold, Oil.",parameters:l,execute:async()=>{const{fetchTraditionalMarkets:e}=await Promise.resolve().then(n.bind(n,19218)),t=await e();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"inject_signal",label:"Signal",description:"Inject a signal (news, note, observation) into the thesis",parameters:o.Object({content:o.String({description:"Signal content"}),type:o.Optional(o.String({description:"news | user_note | external"}))}),execute:async(n,s)=>(await e.injectSignal(t,s.type||"user_note",s.content,"telegram"),{content:[{type:"text",text:"Signal injected."}],details:{}})},{name:"trigger_evaluation",label:"Evaluate",description:"Trigger a deep evaluation cycle",parameters:l,execute:async()=>(await e.evaluate(t),{content:[{type:"text",text:"Evaluation triggered. Results in ~2 minutes."}],details:{}})},{name:"scan_markets",label:"Scan",description:"Search Kalshi markets by keyword, series, or ticker",parameters:o.Object({query:o.Optional(o.String({description:"Keyword search"})),series:o.Optional(o.String({description:"Series ticker"})),market:o.Optional(o.String({description:"Market ticker"}))}),execute:async(e,t)=>{let n;if(t.market)n=await m(t.market);else if(t.series)n=await u(t.series);else if(t.query){const e=await d(),s=t.query.toLowerCase().split(/\s+/);n=e.filter(e=>s.every(t=>((e.title||"")+(e.ticker||"")).toLowerCase().includes(t))).filter(e=>parseFloat(e.volume_fp||"0")>1e3).sort((e,t)=>parseFloat(t.volume_fp||"0")-parseFloat(e.volume_fp||"0")).slice(0,10)}else n={error:"Provide query, series, or market"};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"list_theses",label:"List",description:"List all theses",parameters:l,execute:async()=>{const t=await e.listTheses();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_positions",label:"Positions",description:"Get Kalshi positions with live prices and P&L",parameters:l,execute:async()=>{const e=await p.getPositions();if(!e)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};for(const t of e){const e=await p.getMarketPrice(t.ticker);null!=e&&(t.current_value=e,t.unrealized_pnl=Math.round((e-t.average_price_paid)*t.quantity))}const t=e.map(e=>({ticker:e.ticker,qty:e.quantity,avg_price:`${e.average_price_paid}¢`,current:`${e.current_value}¢`,pnl:`$${((e.unrealized_pnl||0)/100).toFixed(2)}`}));return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance",parameters:l,execute:async()=>{const e=await p.getBalance();return e?{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_orders",label:"Orders",description:"Get resting orders on Kalshi",parameters:l,execute:async()=>{const e=await p.getOrders({status:"resting",limit:50});return e?{content:[{type:"text",text:JSON.stringify(e.orders,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_fills",label:"Fills",description:"Get recent trade fills",parameters:o.Object({ticker:o.Optional(o.String())}),execute:async(e,t)=>{const n=await p.getFills({ticker:t.ticker,limit:20});return n?{content:[{type:"text",text:JSON.stringify(n.fills,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled contracts with P&L",parameters:l,execute:async()=>{const e=await p.getSettlements({limit:50});return e?{content:[{type:"text",text:JSON.stringify(e.settlements,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_edges",label:"Edges",description:"Top 10 edges across all active theses",parameters:l,execute:async()=>{const{theses:t}=await e.listTheses(),n=(t||[]).filter(e=>"active"===e.status),s=await Promise.allSettled(n.map(async t=>((await e.getContext(t.id)).edges||[]).map(e=>({...e,thesisId:t.id})))),i=[];for(const e of s)"fulfilled"===e.status&&i.push(...e.value);return i.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0)),{content:[{type:"text",text:JSON.stringify(i.slice(0,10),null,2)}],details:{}}}},{name:"get_schedule",label:"Schedule",description:"Exchange status (open/closed) and trading hours",parameters:l,execute:async()=>{const e=await fetch("https://api.elections.kalshi.com/trade-api/v2/exchange/status",{headers:{Accept:"application/json"}});if(!e.ok)return{content:[{type:"text",text:`API error: ${e.status}`}],details:{}};const t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_feed",label:"Feed",description:"Recent evaluation history",parameters:o.Object({hours:o.Optional(o.Number({description:"Hours of history (default 24)"}))}),execute:async(t,n)=>{const s=await e.getFeed(n.hours||24);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"web_search",label:"Search",description:"Search the web for latest news",parameters:o.Object({query:o.String({description:"Search query"})}),execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY||c.tavilyKey,s=c.apiKey||process.env.SF_API_KEY,i=c.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev";if(!n&&(n||!s))return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let a;if(a=n?await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}):await fetch(`${i}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}),!a.ok)return{content:[{type:"text",text:`Search failed: ${a.status}`}],details:{}};const r=await a.json();return{content:[{type:"text",text:`${r.answer?`Summary: ${r.answer}\n\n`:""}${(r.results||[]).map(e=>`${e.title}: ${(e.content||"").slice(0,150)}`).join("\n\n")}`}],details:{}}}},{name:"create_thesis",label:"Create",description:"Create a new thesis",parameters:o.Object({rawThesis:o.String({description:"Thesis statement"})}),execute:async(t,n)=>{const s=await e.createThesis(n.rawThesis,!0);return{content:[{type:"text",text:`Created: ${s.id}\nConfidence: ${Math.round(100*(s.confidence||.5))}%`}],details:{}}}},{name:"what_if",label:"What-If",description:"Override causal tree node probabilities and see how edges change. Zero LLM cost.",parameters:o.Object({overrides:o.Array(o.Object({nodeId:o.String({description:"Node ID (e.g. n1, n3.1)"}),newProbability:o.Number({description:"New probability 0-1"})}))}),execute:async(e,t)=>{const n=a,s=[];!function e(t){for(const n of t)s.push(n),n.children?.length&&e(n.children)}(n?.causalTree?.nodes||[]);const i=new Map(t.overrides.map(e=>[e.nodeId,e.newProbability])),r=(n?.causalTree?.nodes||[]).filter(e=>!e.parentId||0===e.depth),o=r.reduce((e,t)=>e+(t.probability||.5),0)/Math.max(r.length,1);for(const e of s)i.has(e.id)&&(e.probability=i.get(e.id));const c=r.reduce((e,t)=>e+(t.probability||.5),0)/Math.max(r.length,1),l=(n?.edges||[]).slice(0,10).map(e=>{const t=s.find(t=>t.id===e.relatedNodeId);if(!t||!i.has(t.id))return{market:e.market,oldEdge:e.edge,newEdge:e.edge,signal:"unchanged"};const n=t.probability/(e.confidence||.5),a=Math.round(e.thesisPrice*n)-e.marketPrice;return{market:e.market,oldEdge:e.edge,newEdge:a,signal:Math.abs(a-e.edge)<1?"unchanged":"changed"}}).filter(e=>"unchanged"!==e.signal);return{content:[{type:"text",text:JSON.stringify({confidence:{old:Math.round(100*o),new:Math.round(100*c)},edges:l},null,2)}],details:{}}}}];h.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:o.Object({query:o.String({description:"Search query"}),mode:o.Optional(o.String({description:'"summary" or "raw"'})),hours:o.Optional(o.Number({description:"Hours (default 24)"}))}),execute:async(t,n)=>{const s=await e.searchX(n.query,{mode:n.mode,hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_volume",label:"X Volume",description:"X discussion volume trend — total posts, velocity, peak time.",parameters:o.Object({query:o.String({description:"Search query"}),hours:o.Optional(o.Number({description:"Hours (default 72)"}))}),execute:async(t,n)=>{const s=await e.getXVolume(n.query,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_news",label:"X News",description:"News stories trending on X — titles, summaries, tickers.",parameters:o.Object({query:o.String({description:"Search query"}),limit:o.Optional(o.Number({description:"Max stories (default 10)"}))}),execute:async(t,n)=>{const s=await e.searchXNews(n.query,{limit:n.limit});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_account",label:"X Account",description:"Recent posts from a specific X account.",parameters:o.Object({username:o.String({description:"X username (with or without @)"}),hours:o.Optional(o.Number({description:"Hours (default 24)"}))}),execute:async(t,n)=>{const s=await e.getXAccount(n.username,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"heartbeat_config",label:"Heartbeat Config",description:"View or update heartbeat settings: scan intervals, model tier, budget cap, pause/resume. Shows cost breakdown.",parameters:o.Object({thesisId:o.String({description:"Thesis ID"}),newsIntervalMin:o.Optional(o.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:o.Optional(o.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:o.Optional(o.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:o.Optional(o.Number({description:"Monthly budget (0 = unlimited)"})),paused:o.Optional(o.Boolean({description:"Pause or resume heartbeat"}))}),execute:async(t,n)=>{if(n.newsIntervalMin||n.xIntervalMin||n.evalModelTier||void 0!==n.monthlyBudgetUsd||void 0!==n.paused){const t={};n.newsIntervalMin&&(t.newsIntervalMin=n.newsIntervalMin),n.xIntervalMin&&(t.xIntervalMin=n.xIntervalMin),n.evalModelTier&&(t.evalModelTier=n.evalModelTier),void 0!==n.monthlyBudgetUsd&&(t.monthlyBudgetUsd=n.monthlyBudgetUsd),void 0!==n.paused&&(t.paused=n.paused),await e.updateHeartbeatConfig(n.thesisId,t)}const s=await e.getHeartbeatConfig(n.thesisId);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}});const g=process.env.SF_API_URL||c.apiUrl||"https://simplefunctions.dev";return h.push({name:"get_world_state",label:"World",description:"Real-time world model (~800 tokens). Geopolitics, economy, energy, elections, crypto, tech.",parameters:o.Object({focus:o.Optional(o.String({description:"Comma-separated topics"}))}),execute:async(e,t)=>{const n=new URLSearchParams;t.focus&&n.set("focus",t.focus);const s=await fetch(`${g}/api/agent/world?${n}`);return{content:[{type:"text",text:await s.text()}],details:{}}}},{name:"monitor_the_situation",label:"Monitor",description:"Scrape any URL (Firecrawl), analyze with any LLM, cross-reference with 9,706 markets, push to webhook.",parameters:o.Object({sourceAction:o.String({description:"scrape|crawl|search|map|extract"}),url:o.Optional(o.String()),query:o.Optional(o.String()),topics:o.Optional(o.String({description:"Comma-separated topics for market enrichment"}))}),execute:async(e,t)=>{const n={source:{action:t.sourceAction}};t.url&&(n.source.url=t.url),t.query&&(n.source.query=t.query),t.topics&&(n.enrich={enabled:!0,topics:t.topics.split(",").map(e=>e.trim()),includeIndex:!0});const s=await fetch(`${g}/api/monitor-the-situation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"enrich_content",label:"Enrich",description:"Cross-reference any text with 9,706 prediction markets. Returns divergences.",parameters:o.Object({content:o.String({description:"Text to cross-reference"}),topics:o.Optional(o.String({description:"Comma-separated topics"}))}),execute:async(e,t)=>{const n={content:t.content};t.topics?n.topics=t.topics.split(",").map(e=>e.trim()):n.topics=["general"];const s=await fetch(`${g}/api/monitor-the-situation/enrich`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"create_skill",label:"Create Skill",description:"Create a custom agent skill.",parameters:o.Object({name:o.String(),trigger:o.String(),description:o.String(),prompt:o.String(),category:o.Optional(o.String())}),execute:async(e,t)=>{const n=await fetch(`${g}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c.apiKey}`},body:JSON.stringify(t)}),s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"list_skills",label:"Skills",description:"List built-in + custom skills.",parameters:l,execute:async()=>{const e=await fetch(`${g}/api/skill`,{headers:{Authorization:`Bearer ${c.apiKey}`}}),t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"browse_public_skills",label:"Public Skills",description:"Browse community skills.",parameters:o.Object({q:o.Optional(o.String()),sort:o.Optional(o.String())}),execute:async(e,t)=>{const n=new URLSearchParams;t.q&&n.set("q",t.q),t.sort&&n.set("sort",t.sort);const s=await fetch(`${g}/api/public/skills?${n}`),i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"fork_skill",label:"Fork Skill",description:"Fork a public skill into your collection.",parameters:o.Object({skillId:o.String()}),execute:async(e,t)=>{const n=await fetch(`${g}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${c.apiKey}`}}),s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"fork_thesis",label:"Fork Thesis",description:"Fork a public thesis. Copies thesis + causal tree.",parameters:o.Object({slug:o.String()}),execute:async(e,t)=>{const n=await fetch(`${g}/api/thesis/${t.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${c.apiKey}`}}),s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}}),c.tradingEnabled&&h.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Requires trading to be enabled. Always confirm with user before placing.",parameters:o.Object({ticker:o.String({description:"Market ticker (e.g. KXWTIMAX-26DEC31-T135)"}),side:o.String({description:"yes or no"}),action:o.String({description:"buy or sell"}),count:o.Number({description:"Number of contracts"}),yes_price:o.Number({description:"Price in cents (1-99)"})}),execute:async(e,t)=>{try{const e=await p.createOrder({ticker:t.ticker,side:t.side,action:t.action,type:"limit",count:t.count,yes_price:t.yes_price});return{content:[{type:"text",text:`✓ Order placed: ${(e.order||e).order_id||"OK"}\n${t.action.toUpperCase()} ${t.count}x ${t.ticker} ${t.side.toUpperCase()} @ ${t.yes_price}¢`}],details:{}}}catch(e){return{content:[{type:"text",text:`✗ Order failed: ${e.message}`}],details:{}}}}},{name:"cancel_order",label:"Cancel Order",description:"Cancel a resting order on Kalshi.",parameters:o.Object({orderId:o.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{try{return await p.cancelOrder(t.orderId),{content:[{type:"text",text:`✓ Order ${t.orderId} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`✗ Cancel failed: ${e.message}`}],details:{}}}}}),h.push({name:"fs_read",label:"Read File",description:"Read a file from workspace (~/.sf/workspace/).",parameters:o.Object({path:o.String({description:"Relative file path"})}),execute:async(e,t)=>{const n=(0,i.wsRead)(t.path);return{content:[{type:"text",text:n.ok?n.content:`Error: ${n.content}`}],details:{}}}},{name:"fs_write",label:"Write File",description:"Write or append to a file in workspace.",parameters:o.Object({path:o.String({description:"Relative file path"}),content:o.String({description:"Content"}),append:o.Optional(o.Boolean({description:"Append mode"}))}),execute:async(e,t)=>({content:[{type:"text",text:(0,i.wsWrite)(t.path,t.content,t.append).message}],details:{}})},{name:"fs_list",label:"List Files",description:"List files in workspace.",parameters:o.Object({path:o.Optional(o.String({description:"Directory"})),glob:o.Optional(o.String({description:"Filter pattern"}))}),execute:async(e,t)=>{const n=(0,i.wsList)(t.path,t.glob);return n.ok?{content:[{type:"text",text:n.entries.length>0?n.entries.join("\n"):"(empty)"}],details:{}}:{content:[{type:"text",text:`Error: ${n.message}`}],details:{}}}},{name:"fs_search",label:"Search Files",description:"Search file contents in workspace using regex.",parameters:o.Object({pattern:o.String({description:"Regex pattern"}),path:o.Optional(o.String({description:"Directory scope"}))}),execute:async(e,t)=>{const n=(0,i.wsSearch)(t.pattern,t.path);return n.ok?0===n.matches.length?{content:[{type:"text",text:"No matches."}],details:{}}:{content:[{type:"text",text:n.matches.map(e=>`${e.file}:${e.line}: ${e.text}`).join("\n")}],details:{}}:{content:[{type:"text",text:`Error: ${n.message}`}],details:{}}}},{name:"fs_delete",label:"Delete File",description:"Delete a file from workspace.",parameters:o.Object({path:o.String({description:"File to delete"})}),execute:async(e,t)=>({content:[{type:"text",text:(0,i.wsDelete)(t.path).message}],details:{}})}),h.push({name:"calculate",label:"Calculate",description:"Evaluate a math expression precisely.",parameters:o.Object({expression:o.String({description:"Math expression"})}),execute:async(e,t)=>{try{const e=t.expression.trim();return/^[\d\s+\-*/.%(),eE]+$/.test(e.replace(/Math\.\w+/g,"").replace(/\*\*/g,""))?{content:[{type:"text",text:`${e} = ${new Function(`"use strict"; return (${e})`)()}`}],details:{}}:{content:[{type:"text",text:"Unsafe expression."}],details:{}}}catch(e){return{content:[{type:"text",text:`Calc error: ${e.message}`}],details:{}}}}},{name:"cancel_all_intents",label:"Cancel All",description:"Cancel all active intents. Emergency use.",parameters:o.Object({confirm:o.Boolean({description:"Must be true"})}),execute:async(t,n)=>{if(!n.confirm)return{content:[{type:"text",text:"Set confirm=true."}],details:{}};try{const t=((await e.listIntents({active:!0})).intents||[]).filter(e=>["pending","armed"].includes(e.status));if(0===t.length)return{content:[{type:"text",text:"No active intents."}],details:{}};let n=0;for(const s of t)try{await e.cancelIntentAPI(s.id),n++}catch{}return{content:[{type:"text",text:`Cancelled ${n}/${t.length} intents.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}}),h}(e,t.thesisId,y),b=p.model||"anthropic/claude-sonnet-4.6";let w;try{w=l("openrouter",b)}catch{w={modelId:b,provider:"openrouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",id:b,name:b,inputPrice:0,outputPrice:0,contextWindow:2e5,supportsImages:!0,supportsTools:!0}}h&&(w.baseUrl=`${m}/api/proxy`);const S=(y.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.market||"").slice(0,35)} | ${e.venue||"kalshi"} | mkt ${e.marketPrice}¢ → thesis ${e.thesisPrice}¢ | edge ${e.edge>0?"+":""}${e.edge}`).join("\n")||" (no edges)",k=(y.causalTree?.nodes||[]).filter(e=>0===e.depth||!e.depth).slice(0,5).map(e=>` ${e.id} ${(e.label||"").slice(0,35)} — ${Math.round(100*(e.probability||.5))}%`).join("\n")||" (no causal tree)",_=new a({initialState:{systemPrompt:`You are a prediction market trading assistant on Telegram. Your job is to help the user see reality clearly and make correct trading decisions.\n\n## Framework\nEdge = thesis price - market price. Positive = market underprices.\nEdge types: [consensus] depth>=500 real opponents, [attention] depth<100 illusory, [timing] market lags, [risk_premium] platform risk. Tag when reporting.\nPrice: depth >= 500 = consensus, < 100 = unreliable, spread > 5 = noisy.\n\n## Rules\n- When reporting an edge, tag it: [consensus] [attention] [timing] [risk_premium].\n- If any kill condition is triggered or approaching, lead with that.\n- If nothing material to do, say "quiet — no action needed." Don't pad.\n- Keep Telegram messages SHORT — bullet points, no walls of text.\n- Prices in cents (¢). P&L in dollars ($). Don't re-convert tool output units.\n- Call tools for fresh data. Never guess prices or P&L from this prompt.\n- Use search_x for X/Twitter sentiment. Use x_volume for discussion spikes. Use x_account to track key people.\n- Use heartbeat_config to view/adjust scan intervals, model tier, budget cap, or check cost breakdown.\n- Use monitor_the_situation to scrape URLs and cross-reference with markets. Use enrich_content for text-only analysis.\n- Use get_world_state for broad situational awareness (~800 tokens).\n- Use create_skill / list_skills / browse_public_skills / fork_skill to manage agent skills.\n- Use fork_thesis to fork a public thesis (copies thesis + causal tree).\n- fs_read/fs_write/fs_list/fs_search/fs_delete: workspace. Write notes proactively. Shared with TUI.\n- calculate: precise math. send_alert: push to Telegram. schedule_wake: self-scheduling.\n- Live State shows positions/edges each turn — use it directly, don't re-fetch.\n- If user mentions news, inject_signal immediately. Don't ask "should I?"\n- If user says "evaluate" or "run it", trigger immediately.\n- Don't end with "anything else?" — user will ask.\n- Use Chinese if user writes Chinese, English if English.\n${p.tradingEnabled?"- Trading ENABLED. You have place_order and cancel_order. ALWAYS confirm before placing.":"- Trading DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current State\nThesis: ${(y.thesis||y.rawThesis||"N/A").slice(0,200)}\nID: ${t.thesisId.slice(0,8)} | Confidence: ${f}%\n\nCausal nodes:\n${k}\n\nTop edges:\n${S}\n\n${y.lastEvaluation?.summary?`Latest eval: ${y.lastEvaluation.summary.slice(0,200)}`:""}`,model:w,tools:x,thinkingLevel:"off"},streamFn:o,getApiKey:e=>"openrouter"===e?g:void 0});if(t.agentMessages.length>0)try{_.replaceMessages(t.agentMessages)}catch{}else if(t.thesisId)try{const e=(0,i.readRecentContext)(t.thesisId,30);if(e.length>0){const t=[];for(const n of e)"user"===n.role?t.push({role:"user",content:n.content}):"assistant"===n.role&&t.push({role:"assistant",content:n.content});const n=[];for(const e of t)0!==n.length&&n[n.length-1].role===e.role||n.push(e);if(n.length>0)try{_.replaceMessages(n)}catch{}}}catch{}return t.agent=_,_}}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.id=482,exports.ids=[482],exports.modules={40101:(t,e,r)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.loadSkills=function(){const t=[],e=__dirname,r=e.includes("dist")?(0,n.join)(e,"../../src/skills"):e;let i=[];try{i=(0,s.readdirSync)(r).filter(t=>t.endsWith(".md"))}catch{return t}for(const e of i)try{const i=o((0,s.readFileSync)((0,n.join)(r,e),"utf-8"));i&&t.push(i)}catch{}try{const e=process.env.HOME||process.env.USERPROFILE||"",r=(0,n.join)(e,".sf","skills"),i=(0,s.readdirSync)(r).filter(t=>t.endsWith(".md"));for(const e of i)try{const i=o((0,s.readFileSync)((0,n.join)(r,e),"utf-8"));i&&t.push(i)}catch{}}catch{}return t};const s=r(79896),n=r(16928);function o(t){const e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;const r=e[1],s=e[2].trim(),n={};for(const t of r.split("\n")){const e=t.match(/^(\w[\w_]*)\s*:\s*(.+)$/);e&&(n[e[1]]=e[2].trim())}if(!n.name||!n.trigger)return null;const o=s.match(/## Instructions\n([\s\S]*)$/i),i=o?o[1].trim():s,c=t=>(t||"").replace(/[\[\]]/g,"").split(",").map(t=>t.trim()).filter(Boolean);return{name:n.name,trigger:n.trigger,description:n.description||"",author:n.author||"unknown",version:n.version||"1.0.0",category:n.category||"general",tags:c(n.tags),toolsUsed:c(n.tools_used),estimatedTime:n.estimated_time||"",auto:n.auto,prompt:i,raw:t}}}};
|
package/dist/563.index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.id=563,exports.ids=[563],exports.modules={83003:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleWake=d,t.getPendingWakes=l,t.getDueWakes=function(){const e=(new Date).toISOString();return l().filter(t=>t.fireAt<=e)},t.markFired=function(e){const t=i.default.join(c,`${e.id}.json`);e.firedAt=(new Date).toISOString();try{o.default.writeFileSync(t,JSON.stringify(e,null,2))}catch{}if(e.repeatMinutes&&e.repeatMinutes>0)return d({delayMinutes:e.repeatMinutes,action:e.action,prompt:e.prompt,toolCall:e.toolCall,repeatMinutes:e.repeatMinutes,context:e.context,thesisId:e.thesisId});return null},t.cancelWake=function(e){const t=i.default.join(c,`${e}.json`);if(o.default.existsSync(t))return o.default.unlinkSync(t),!0;return!1},t.listWakes=function(){u();const e=o.default.readdirSync(c).filter(e=>e.endsWith(".json")),t=[];for(const n of e)try{t.push(JSON.parse(o.default.readFileSync(i.default.join(c,n),"utf-8")))}catch{}return t.sort((e,t)=>e.fireAt.localeCompare(t.fireAt))},t.cleanOldWakes=function(){u();const e=new Date(Date.now()-864e5).toISOString(),t=o.default.readdirSync(c).filter(e=>e.endsWith(".json"));let n=0;for(const r of t)try{const t=JSON.parse(o.default.readFileSync(i.default.join(c,r),"utf-8"));t.firedAt&&t.firedAt<e&&(o.default.unlinkSync(i.default.join(c,r)),n++)}catch{}return n};const o=r(n(79896)),i=r(n(16928)),a=r(n(70857)),s=r(n(76982)),c=i.default.join(a.default.homedir(),".sf","wake","agent");function u(){o.default.mkdirSync(c,{recursive:!0})}function d(e){u();const t={id:s.default.randomBytes(8).toString("hex"),createdAt:(new Date).toISOString(),fireAt:new Date(Date.now()+6e4*e.delayMinutes).toISOString(),action:e.action,prompt:e.prompt,toolCall:e.toolCall,repeatMinutes:e.repeatMinutes,context:e.context,thesisId:e.thesisId};return o.default.writeFileSync(i.default.join(c,`${t.id}.json`),JSON.stringify(t,null,2)),t}function l(){u();const e=o.default.readdirSync(c).filter(e=>e.endsWith(".json")),t=[];for(const n of e)try{const e=JSON.parse(o.default.readFileSync(i.default.join(c,n),"utf-8"));e.firedAt||t.push(e)}catch{}return t}},32849:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeMessage=function(e){const t=`${Date.now()}-${(0,a.randomBytes)(4).toString("hex")}`,n={id:t,ts:(new Date).toISOString(),...e},i="agent"===e.from?c:u;d(i);const s=(0,o.join)(i,`.${t}.tmp`),l=(0,o.join)(i,`${t}.json`);return(0,r.writeFileSync)(s,JSON.stringify(n)),(0,r.renameSync)(s,l),t},t.readMessages=function(e,t){const n="inbox"===t?c:u;d(n);const i=[],a=Date.now();for(const t of(0,r.readdirSync)(n))if(t.endsWith(".json"))try{const s=JSON.parse((0,r.readFileSync)((0,o.join)(n,t),"utf-8"));if((a-new Date(s.ts).getTime())/1e3>s.ttl){try{(0,r.unlinkSync)((0,o.join)(n,t))}catch{}continue}s.to!==e&&"all"!==s.to||i.push(s)}catch{try{(0,r.unlinkSync)((0,o.join)(n,t))}catch{}}return i.sort((e,t)=>e.ts.localeCompare(t.ts))},t.markRead=function(e,t){const n="inbox"===t?c:u,i=(0,o.join)(n,`${e}.json`);try{const e=JSON.parse((0,r.readFileSync)(i,"utf-8"));e.read=!0,(0,r.writeFileSync)(i,JSON.stringify(e))}catch{}},t.deleteMessage=function(e,t){const n="inbox"===t?c:u;try{(0,r.unlinkSync)((0,o.join)(n,`${e}.json`))}catch{}},t.cleanExpired=function(){let e=0;for(const t of[c,u]){d(t);const n=Date.now();for(const i of(0,r.readdirSync)(t))if(i.endsWith(".json"))try{const a=JSON.parse((0,r.readFileSync)((0,o.join)(t,i),"utf-8"));(n-new Date(a.ts).getTime())/1e3>a.ttl&&((0,r.unlinkSync)((0,o.join)(t,i)),e++)}catch{try{(0,r.unlinkSync)((0,o.join)(t,i))}catch{}e++}}return e};const r=n(79896),o=n(16928),i=n(70857),a=n(76982),s=(0,o.join)((0,i.homedir)(),".sf","bus"),c=(0,o.join)(s,"inbox"),u=(0,o.join)(s,"outbox");function d(e){(0,r.mkdirSync)(e,{recursive:!0})}},9563:(e,t,n)=>{t.cleanOldWakes=t.listWakes=t.cancelWake=t.markFired=t.getDueWakes=t.scheduleWake=t.evaluateWakeConditions=t.saveWakeCondition=t.periodicScan=t.evaluateSoftCondition=t.writeAgentHeartbeat=t.deleteMessage=t.readMessages=t.writeMessage=void 0;var r=n(32849);Object.defineProperty(t,"writeMessage",{enumerable:!0,get:function(){return r.writeMessage}}),Object.defineProperty(t,"readMessages",{enumerable:!0,get:function(){return r.readMessages}}),Object.defineProperty(t,"deleteMessage",{enumerable:!0,get:function(){return r.deleteMessage}});var o=n(42340);var i=n(44934);Object.defineProperty(t,"writeAgentHeartbeat",{enumerable:!0,get:function(){return i.writeAgentHeartbeat}});var a=n(44258);Object.defineProperty(t,"evaluateSoftCondition",{enumerable:!0,get:function(){return a.evaluateSoftCondition}}),Object.defineProperty(t,"periodicScan",{enumerable:!0,get:function(){return a.periodicScan}});var s=n(8695);Object.defineProperty(t,"saveWakeCondition",{enumerable:!0,get:function(){return s.saveWakeCondition}}),Object.defineProperty(t,"evaluateWakeConditions",{enumerable:!0,get:function(){return s.evaluateWakeConditions}});var c=n(83003);Object.defineProperty(t,"scheduleWake",{enumerable:!0,get:function(){return c.scheduleWake}}),Object.defineProperty(t,"getDueWakes",{enumerable:!0,get:function(){return c.getDueWakes}}),Object.defineProperty(t,"markFired",{enumerable:!0,get:function(){return c.markFired}}),Object.defineProperty(t,"cancelWake",{enumerable:!0,get:function(){return c.cancelWake}}),Object.defineProperty(t,"listWakes",{enumerable:!0,get:function(){return c.listWakes}}),Object.defineProperty(t,"cleanOldWakes",{enumerable:!0,get:function(){return c.cleanOldWakes}})},42340:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.smartLLMCall=async function(e){const t=(0,a.loadConfig)(),n=t.apiKey;if(!n)return null;const f=t.apiUrl||"https://simplefunctions.dev",p=e.model||t.smartModel||c,y=e.maxTokens||d,m=e.timeoutMs||u;if(!function(e){const t=e??1;if(t<=0)return!1;try{const e=(0,r.readFileSync)(s,"utf-8").trim().split("\n"),n=Date.now()-2592e6;let o=0;for(const t of e)try{const e=JSON.parse(t);new Date(e.ts).getTime()>n&&(o+=e.costUsd)}catch{}return o<t}catch{return!0}}(t.smartBudgetUsd))return null;try{const t=new AbortController,a=setTimeout(()=>t.abort(),m),c=await fetch(`${f}/api/proxy/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({model:p,messages:[{role:"system",content:e.systemPrompt},{role:"user",content:e.userContent}],max_tokens:y,temperature:e.temperature??.3}),signal:t.signal});if(clearTimeout(a),!c.ok)return null;const u=await c.json(),d=u.choices?.[0]?.message?.content||"",g=u.usage?.prompt_tokens||0,S=u.usage?.completion_tokens||0,h=l[p]||{input:1,output:3},k=(g*h.input+S*h.output)/1e6;return function(e){try{(0,r.mkdirSync)((0,o.join)((0,i.homedir)(),".sf","bus","cost"),{recursive:!0}),(0,r.appendFileSync)(s,JSON.stringify(e)+"\n")}catch{}}({ts:(new Date).toISOString(),daemon:e.daemon,type:e.callType,model:p,inputTokens:g,outputTokens:S,costUsd:k,intentId:e.intentId}),{text:d,usage:{input:g,output:S,costUsd:k}}}catch{return null}},t.getMonthlySpend=function(){try{const e=(0,r.readFileSync)(s,"utf-8").trim().split("\n"),t=Date.now()-2592e6;let n=0;for(const r of e)try{const e=JSON.parse(r);new Date(e.ts).getTime()>t&&(n+=e.costUsd)}catch{}return n}catch{return 0}};const r=n(79896),o=n(16928),i=n(70857),a=n(11627),s=(0,o.join)((0,i.homedir)(),".sf","bus","cost","smart-usage.jsonl"),c="anthropic/claude-haiku-4.5",u=1e4,d=500,l={"anthropic/claude-haiku-4.5":{input:.8,output:4},"anthropic/claude-haiku-4-5-20251001":{input:.8,output:4}}},44934:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeAgentHeartbeat=function(e){try{(0,r.mkdirSync)((0,o.dirname)(a),{recursive:!0});const t={pid:process.pid,ts:(new Date).toISOString(),thesisId:e};(0,r.writeFileSync)(a,JSON.stringify(t))}catch{}},t.isAgentActive=function(e=120){try{const t=JSON.parse((0,r.readFileSync)(a,"utf-8"));if(Date.now()-new Date(t.ts).getTime()>1e3*e)return!1;try{return process.kill(t.pid,0),!0}catch{return!1}}catch{return!1}},t.getAgentHeartbeat=function(){try{return JSON.parse((0,r.readFileSync)(a,"utf-8"))}catch{return null}};const r=n(79896),o=n(16928),i=n(70857),a=(0,o.join)((0,i.homedir)(),".sf","bus","presence","agent.heartbeat")},44258:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateSoftCondition=async function(e){if(!e.softCondition)return!0;const t=await(0,r.getMarketPrice)(e.marketId);let n="";try{const t=await(0,r.getPublicOrderbook)(e.marketId,5);if(t){const e=t.yes_dollars||[],r=t.no_dollars||[],o=e.length>0?Math.round(100*parseFloat(e[0][0])):0,i=r.length>0?100-Math.round(100*parseFloat(r[0][0])):100,a=i-o,s=e.slice(0,3).reduce((e,t)=>e+parseFloat(t[1]),0),c=r.slice(0,3).reduce((e,t)=>e+parseFloat(t[1]),0);n=`Orderbook: bid ${o}c ($${Math.round(s)}), ask ${i}c ($${Math.round(c)}), spread ${a}c`}}catch{}const i=await(0,o.smartLLMCall)({systemPrompt:"You are a trade execution gate. Answer PASS or HOLD with a one-sentence reason. Nothing else.",userContent:`Intent: ${e.action.toUpperCase()} ${e.marketId} ${e.direction.toUpperCase()} x${e.targetQuantity}${e.maxPrice?` @ <=${e.maxPrice}c`:""}\nHard trigger: ${e.triggerType}${e.triggerPrice?` ${e.triggerPrice}c`:""} — FIRED\nSoft condition: "${e.softCondition}"\n\nCurrent state:\n- Last price: ${t??"unknown"}c\n${n?`- ${n}`:""}\n\nDoes the current market state satisfy the soft condition?`,daemon:"runtime",callType:"soft_condition",maxTokens:50,intentId:e.id});return!!i&&i.text.toUpperCase().includes("PASS")},t.periodicScan=async function(e,t,n){if(0===t.length)return null;const r=t.map(e=>{const t=n.get(e.marketId),r=null!=t?`${t}c`:"?";return`- ${e.id.slice(0,8)}: ${e.action} ${e.marketId} ${e.direction} x${e.targetQuantity} @ <=${e.maxPrice??"mkt"}c | status: ${e.status} | trigger: ${e.triggerType}${e.triggerPrice?` ${e.triggerPrice}c`:""} | filled: ${e.filledQuantity}/${e.targetQuantity} | market: ${r}${e.softCondition?` | soft: "${e.softCondition}"`:""}`}).join("\n"),a=await(0,o.smartLLMCall)({systemPrompt:'You are a trading daemon monitor. Analyze intent state and report concisely.\nFormat exactly:\nALERTS: (urgent items, or "none")\nOBSERVATIONS: (patterns, risks, opportunities)\nRECOMMENDATIONS: (action suggestions, or "hold steady")\nOne sentence per item. If nothing notable, say "All clear."',userContent:`Active intents:\n${r}`,daemon:e,callType:"periodic_scan",maxTokens:300});if(!a)return null;!a.text.includes("ALERTS:")||a.text.includes("ALERTS: none")||a.text.includes("ALERTS: None")||a.text.toLowerCase().includes("alerts: none")||(0,i.writeMessage)({from:e,to:"agent",type:"observation",priority:"normal",payload:{summary:a.text},ttl:3600});return a.text};const r=n(96139),o=n(42340),i=n(32849)},8695:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.loadWakeConditions=d,t.saveWakeCondition=l,t.evaluateWakeConditions=async function(e,t,n){const r=d();for(const o of r){if(await f(o,e,t,n)){o.firedCount++,o.lastFiredAt=(new Date).toISOString(),l(o);for(const t of o.alertChannels)"bus"===t&&(0,c.writeMessage)({from:e,to:"agent",type:"alert",priority:o.priority,payload:{summary:`Wake condition fired: ${o.description}`,wakeConditionId:o.id},ttl:7200})}}};const r=n(79896),o=n(16928),i=n(70857),a=n(96139),s=n(42340),c=n(32849),u=(0,o.join)((0,i.homedir)(),".sf","bus","wake");function d(){try{(0,r.mkdirSync)(u,{recursive:!0});const e=[];for(const t of(0,r.readdirSync)(u))if(t.endsWith(".json"))try{const n=JSON.parse((0,r.readFileSync)((0,o.join)(u,t),"utf-8"));if(!n.active)continue;if(n.expiresAt&&new Date(n.expiresAt)<new Date)continue;if(-1!==n.maxFires&&n.firedCount>=n.maxFires)continue;e.push(n)}catch{}return e}catch{return[]}}function l(e){(0,r.mkdirSync)(u,{recursive:!0}),(0,r.writeFileSync)((0,o.join)(u,`${e.id}.json`),JSON.stringify(e,null,2))}async function f(e,t,n,r){switch(e.type){case"price":{if(!e.priceCondition)return!1;const t=r?.get(e.priceCondition.ticker)??await(0,a.getMarketPrice)(e.priceCondition.ticker);return null!==t&&("above"===e.priceCondition.operator?t>=e.priceCondition.threshold:t<=e.priceCondition.threshold)}case"time":return!!e.timeCondition&&new Date>=new Date(e.timeCondition.at);case"llm":{if(!e.llmCondition)return!1;const o=e.llmCondition.checkIntervalCycles||10;if(n%o!==0)return!1;const i=[];if(e.llmCondition.dataNeeded.includes("prices")&&r)for(const[e,t]of r)i.push(`${e}: ${t}c`);const a=await(0,s.smartLLMCall)({systemPrompt:"You are a market condition evaluator. Answer FIRED or NOT_FIRED with a one-sentence reason. Nothing else.",userContent:`Condition: "${e.llmCondition.prompt}"\n\nCurrent data:\n${i.join("\n")||"(no data)"}`,daemon:t,callType:"wake_condition",maxTokens:50});return!!a&&a.text.toUpperCase().includes("FIRED")}case"compound":{if(!e.compoundCondition?.conditions)return!1;const o=await Promise.all(e.compoundCondition.conditions.map(e=>f(e,t,n,r)));return"and"===e.compoundCondition.operator?o.every(Boolean):o.some(Boolean)}default:return!1}}}};
|
|
1
|
+
"use strict";exports.id=563,exports.ids=[563],exports.modules={83003:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleWake=d,t.getPendingWakes=l,t.getDueWakes=function(){const e=(new Date).toISOString();return l().filter(t=>t.fireAt<=e)},t.markFired=function(e){const t=i.default.join(c,`${e.id}.json`);e.firedAt=(new Date).toISOString();try{o.default.writeFileSync(t,JSON.stringify(e,null,2))}catch{}if(e.repeatMinutes&&e.repeatMinutes>0)return d({delayMinutes:e.repeatMinutes,action:e.action,prompt:e.prompt,toolCall:e.toolCall,repeatMinutes:e.repeatMinutes,context:e.context,thesisId:e.thesisId});return null},t.cancelWake=function(e){const t=i.default.join(c,`${e}.json`);if(o.default.existsSync(t))return o.default.unlinkSync(t),!0;return!1},t.listWakes=function(){u();const e=o.default.readdirSync(c).filter(e=>e.endsWith(".json")),t=[];for(const n of e)try{t.push(JSON.parse(o.default.readFileSync(i.default.join(c,n),"utf-8")))}catch{}return t.sort((e,t)=>e.fireAt.localeCompare(t.fireAt))},t.cleanOldWakes=function(){u();const e=new Date(Date.now()-864e5).toISOString(),t=o.default.readdirSync(c).filter(e=>e.endsWith(".json"));let n=0;for(const r of t)try{const t=JSON.parse(o.default.readFileSync(i.default.join(c,r),"utf-8"));t.firedAt&&t.firedAt<e&&(o.default.unlinkSync(i.default.join(c,r)),n++)}catch{}return n};const o=r(n(79896)),i=r(n(16928)),a=r(n(70857)),s=r(n(76982)),c=i.default.join(a.default.homedir(),".sf","wake","agent");function u(){o.default.mkdirSync(c,{recursive:!0})}function d(e){u();const t={id:s.default.randomBytes(8).toString("hex"),createdAt:(new Date).toISOString(),fireAt:new Date(Date.now()+6e4*e.delayMinutes).toISOString(),action:e.action,prompt:e.prompt,toolCall:e.toolCall,repeatMinutes:e.repeatMinutes,context:e.context,thesisId:e.thesisId};return o.default.writeFileSync(i.default.join(c,`${t.id}.json`),JSON.stringify(t,null,2)),t}function l(){u();const e=o.default.readdirSync(c).filter(e=>e.endsWith(".json")),t=[];for(const n of e)try{const e=JSON.parse(o.default.readFileSync(i.default.join(c,n),"utf-8"));e.firedAt||t.push(e)}catch{}return t}},32849:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeMessage=function(e){const t=`${Date.now()}-${(0,a.randomBytes)(4).toString("hex")}`,n={id:t,ts:(new Date).toISOString(),...e},i="agent"===e.from?c:u;d(i);const s=(0,o.join)(i,`.${t}.tmp`),l=(0,o.join)(i,`${t}.json`);return(0,r.writeFileSync)(s,JSON.stringify(n)),(0,r.renameSync)(s,l),t},t.readMessages=function(e,t){const n="inbox"===t?c:u;d(n);const i=[],a=Date.now();for(const t of(0,r.readdirSync)(n))if(t.endsWith(".json"))try{const s=JSON.parse((0,r.readFileSync)((0,o.join)(n,t),"utf-8"));if((a-new Date(s.ts).getTime())/1e3>s.ttl){try{(0,r.unlinkSync)((0,o.join)(n,t))}catch{}continue}s.to!==e&&"all"!==s.to||i.push(s)}catch{try{(0,r.unlinkSync)((0,o.join)(n,t))}catch{}}return i.sort((e,t)=>e.ts.localeCompare(t.ts))},t.markRead=function(e,t){const n="inbox"===t?c:u,i=(0,o.join)(n,`${e}.json`);try{const e=JSON.parse((0,r.readFileSync)(i,"utf-8"));e.read=!0,(0,r.writeFileSync)(i,JSON.stringify(e))}catch{}},t.deleteMessage=function(e,t){const n="inbox"===t?c:u;try{(0,r.unlinkSync)((0,o.join)(n,`${e}.json`))}catch{}},t.cleanExpired=function(){let e=0;for(const t of[c,u]){d(t);const n=Date.now();for(const i of(0,r.readdirSync)(t))if(i.endsWith(".json"))try{const a=JSON.parse((0,r.readFileSync)((0,o.join)(t,i),"utf-8"));(n-new Date(a.ts).getTime())/1e3>a.ttl&&((0,r.unlinkSync)((0,o.join)(t,i)),e++)}catch{try{(0,r.unlinkSync)((0,o.join)(t,i))}catch{}e++}}return e};const r=n(79896),o=n(16928),i=n(70857),a=n(76982),s=(0,o.join)((0,i.homedir)(),".sf","bus"),c=(0,o.join)(s,"inbox"),u=(0,o.join)(s,"outbox");function d(e){(0,r.mkdirSync)(e,{recursive:!0})}},9563:(e,t,n)=>{t.cleanOldWakes=t.listWakes=t.cancelWake=t.markFired=t.getPendingWakes=t.getDueWakes=t.scheduleWake=t.evaluateWakeConditions=t.saveWakeCondition=t.periodicScan=t.evaluateSoftCondition=t.writeAgentHeartbeat=t.deleteMessage=t.readMessages=t.writeMessage=void 0;var r=n(32849);Object.defineProperty(t,"writeMessage",{enumerable:!0,get:function(){return r.writeMessage}}),Object.defineProperty(t,"readMessages",{enumerable:!0,get:function(){return r.readMessages}}),Object.defineProperty(t,"deleteMessage",{enumerable:!0,get:function(){return r.deleteMessage}});var o=n(42340);var i=n(44934);Object.defineProperty(t,"writeAgentHeartbeat",{enumerable:!0,get:function(){return i.writeAgentHeartbeat}});var a=n(44258);Object.defineProperty(t,"evaluateSoftCondition",{enumerable:!0,get:function(){return a.evaluateSoftCondition}}),Object.defineProperty(t,"periodicScan",{enumerable:!0,get:function(){return a.periodicScan}});var s=n(8695);Object.defineProperty(t,"saveWakeCondition",{enumerable:!0,get:function(){return s.saveWakeCondition}}),Object.defineProperty(t,"evaluateWakeConditions",{enumerable:!0,get:function(){return s.evaluateWakeConditions}});var c=n(83003);Object.defineProperty(t,"scheduleWake",{enumerable:!0,get:function(){return c.scheduleWake}}),Object.defineProperty(t,"getDueWakes",{enumerable:!0,get:function(){return c.getDueWakes}}),Object.defineProperty(t,"getPendingWakes",{enumerable:!0,get:function(){return c.getPendingWakes}}),Object.defineProperty(t,"markFired",{enumerable:!0,get:function(){return c.markFired}}),Object.defineProperty(t,"cancelWake",{enumerable:!0,get:function(){return c.cancelWake}}),Object.defineProperty(t,"listWakes",{enumerable:!0,get:function(){return c.listWakes}}),Object.defineProperty(t,"cleanOldWakes",{enumerable:!0,get:function(){return c.cleanOldWakes}})},42340:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.smartLLMCall=async function(e){const t=(0,a.loadConfig)(),n=t.apiKey;if(!n)return null;const f=t.apiUrl||"https://simplefunctions.dev",p=e.model||t.smartModel||c,y=e.maxTokens||d,m=e.timeoutMs||u;if(!function(e){const t=e??1;if(t<=0)return!1;try{const e=(0,r.readFileSync)(s,"utf-8").trim().split("\n"),n=Date.now()-2592e6;let o=0;for(const t of e)try{const e=JSON.parse(t);new Date(e.ts).getTime()>n&&(o+=e.costUsd)}catch{}return o<t}catch{return!0}}(t.smartBudgetUsd))return null;try{const t=new AbortController,a=setTimeout(()=>t.abort(),m),c=await fetch(`${f}/api/proxy/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({model:p,messages:[{role:"system",content:e.systemPrompt},{role:"user",content:e.userContent}],max_tokens:y,temperature:e.temperature??.3}),signal:t.signal});if(clearTimeout(a),!c.ok)return null;const u=await c.json(),d=u.choices?.[0]?.message?.content||"",g=u.usage?.prompt_tokens||0,S=u.usage?.completion_tokens||0,h=l[p]||{input:1,output:3},k=(g*h.input+S*h.output)/1e6;return function(e){try{(0,r.mkdirSync)((0,o.join)((0,i.homedir)(),".sf","bus","cost"),{recursive:!0}),(0,r.appendFileSync)(s,JSON.stringify(e)+"\n")}catch{}}({ts:(new Date).toISOString(),daemon:e.daemon,type:e.callType,model:p,inputTokens:g,outputTokens:S,costUsd:k,intentId:e.intentId}),{text:d,usage:{input:g,output:S,costUsd:k}}}catch{return null}},t.getMonthlySpend=function(){try{const e=(0,r.readFileSync)(s,"utf-8").trim().split("\n"),t=Date.now()-2592e6;let n=0;for(const r of e)try{const e=JSON.parse(r);new Date(e.ts).getTime()>t&&(n+=e.costUsd)}catch{}return n}catch{return 0}};const r=n(79896),o=n(16928),i=n(70857),a=n(11627),s=(0,o.join)((0,i.homedir)(),".sf","bus","cost","smart-usage.jsonl"),c="anthropic/claude-haiku-4.5",u=1e4,d=500,l={"anthropic/claude-haiku-4.5":{input:.8,output:4},"anthropic/claude-haiku-4-5-20251001":{input:.8,output:4}}},44934:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.writeAgentHeartbeat=function(e){try{(0,r.mkdirSync)((0,o.dirname)(a),{recursive:!0});const t={pid:process.pid,ts:(new Date).toISOString(),thesisId:e};(0,r.writeFileSync)(a,JSON.stringify(t))}catch{}},t.isAgentActive=function(e=120){try{const t=JSON.parse((0,r.readFileSync)(a,"utf-8"));if(Date.now()-new Date(t.ts).getTime()>1e3*e)return!1;try{return process.kill(t.pid,0),!0}catch{return!1}}catch{return!1}},t.getAgentHeartbeat=function(){try{return JSON.parse((0,r.readFileSync)(a,"utf-8"))}catch{return null}};const r=n(79896),o=n(16928),i=n(70857),a=(0,o.join)((0,i.homedir)(),".sf","bus","presence","agent.heartbeat")},44258:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateSoftCondition=async function(e){if(!e.softCondition)return!0;const t=await(0,r.getMarketPrice)(e.marketId);let n="";try{const t=await(0,r.getPublicOrderbook)(e.marketId,5);if(t){const e=t.yes_dollars||[],r=t.no_dollars||[],o=e.length>0?Math.round(100*parseFloat(e[0][0])):0,i=r.length>0?100-Math.round(100*parseFloat(r[0][0])):100,a=i-o,s=e.slice(0,3).reduce((e,t)=>e+parseFloat(t[1]),0),c=r.slice(0,3).reduce((e,t)=>e+parseFloat(t[1]),0);n=`Orderbook: bid ${o}c ($${Math.round(s)}), ask ${i}c ($${Math.round(c)}), spread ${a}c`}}catch{}const i=await(0,o.smartLLMCall)({systemPrompt:"You are a trade execution gate. Answer PASS or HOLD with a one-sentence reason. Nothing else.",userContent:`Intent: ${e.action.toUpperCase()} ${e.marketId} ${e.direction.toUpperCase()} x${e.targetQuantity}${e.maxPrice?` @ <=${e.maxPrice}c`:""}\nHard trigger: ${e.triggerType}${e.triggerPrice?` ${e.triggerPrice}c`:""} — FIRED\nSoft condition: "${e.softCondition}"\n\nCurrent state:\n- Last price: ${t??"unknown"}c\n${n?`- ${n}`:""}\n\nDoes the current market state satisfy the soft condition?`,daemon:"runtime",callType:"soft_condition",maxTokens:50,intentId:e.id});return!!i&&i.text.toUpperCase().includes("PASS")},t.periodicScan=async function(e,t,n){if(0===t.length)return null;const r=t.map(e=>{const t=n.get(e.marketId),r=null!=t?`${t}c`:"?";return`- ${e.id.slice(0,8)}: ${e.action} ${e.marketId} ${e.direction} x${e.targetQuantity} @ <=${e.maxPrice??"mkt"}c | status: ${e.status} | trigger: ${e.triggerType}${e.triggerPrice?` ${e.triggerPrice}c`:""} | filled: ${e.filledQuantity}/${e.targetQuantity} | market: ${r}${e.softCondition?` | soft: "${e.softCondition}"`:""}`}).join("\n"),a=await(0,o.smartLLMCall)({systemPrompt:'You are a trading daemon monitor. Analyze intent state and report concisely.\nFormat exactly:\nALERTS: (urgent items, or "none")\nOBSERVATIONS: (patterns, risks, opportunities)\nRECOMMENDATIONS: (action suggestions, or "hold steady")\nOne sentence per item. If nothing notable, say "All clear."',userContent:`Active intents:\n${r}`,daemon:e,callType:"periodic_scan",maxTokens:300});if(!a)return null;!a.text.includes("ALERTS:")||a.text.includes("ALERTS: none")||a.text.includes("ALERTS: None")||a.text.toLowerCase().includes("alerts: none")||(0,i.writeMessage)({from:e,to:"agent",type:"observation",priority:"normal",payload:{summary:a.text},ttl:3600});return a.text};const r=n(96139),o=n(42340),i=n(32849)},8695:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.loadWakeConditions=d,t.saveWakeCondition=l,t.evaluateWakeConditions=async function(e,t,n){const r=d();for(const o of r){if(await f(o,e,t,n)){o.firedCount++,o.lastFiredAt=(new Date).toISOString(),l(o);for(const t of o.alertChannels)"bus"===t&&(0,c.writeMessage)({from:e,to:"agent",type:"alert",priority:o.priority,payload:{summary:`Wake condition fired: ${o.description}`,wakeConditionId:o.id},ttl:7200})}}};const r=n(79896),o=n(16928),i=n(70857),a=n(96139),s=n(42340),c=n(32849),u=(0,o.join)((0,i.homedir)(),".sf","bus","wake");function d(){try{(0,r.mkdirSync)(u,{recursive:!0});const e=[];for(const t of(0,r.readdirSync)(u))if(t.endsWith(".json"))try{const n=JSON.parse((0,r.readFileSync)((0,o.join)(u,t),"utf-8"));if(!n.active)continue;if(n.expiresAt&&new Date(n.expiresAt)<new Date)continue;if(-1!==n.maxFires&&n.firedCount>=n.maxFires)continue;e.push(n)}catch{}return e}catch{return[]}}function l(e){(0,r.mkdirSync)(u,{recursive:!0}),(0,r.writeFileSync)((0,o.join)(u,`${e.id}.json`),JSON.stringify(e,null,2))}async function f(e,t,n,r){switch(e.type){case"price":{if(!e.priceCondition)return!1;const t=r?.get(e.priceCondition.ticker)??await(0,a.getMarketPrice)(e.priceCondition.ticker);return null!==t&&("above"===e.priceCondition.operator?t>=e.priceCondition.threshold:t<=e.priceCondition.threshold)}case"time":return!!e.timeCondition&&new Date>=new Date(e.timeCondition.at);case"llm":{if(!e.llmCondition)return!1;const o=e.llmCondition.checkIntervalCycles||10;if(n%o!==0)return!1;const i=[];if(e.llmCondition.dataNeeded.includes("prices")&&r)for(const[e,t]of r)i.push(`${e}: ${t}c`);const a=await(0,s.smartLLMCall)({systemPrompt:"You are a market condition evaluator. Answer FIRED or NOT_FIRED with a one-sentence reason. Nothing else.",userContent:`Condition: "${e.llmCondition.prompt}"\n\nCurrent data:\n${i.join("\n")||"(no data)"}`,daemon:t,callType:"wake_condition",maxTokens:50});return!!a&&a.text.toUpperCase().includes("FIRED")}case"compound":{if(!e.compoundCondition?.conditions)return!1;const o=await Promise.all(e.compoundCondition.conditions.map(e=>f(e,t,n,r)));return"and"===e.compoundCondition.operator?o.every(Boolean):o.some(Boolean)}default:return!1}}}};
|