@spfunctions/cli 2.0.7 → 2.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -180,14 +180,16 @@ Intents are declarative execution orders. You define the trade and trigger condi
180
180
 
181
181
  | Command | Description |
182
182
  |---------|-------------|
183
- | `sf intent buy <ticker> <qty>` | Create buy intent (`--trigger below:28`, `--auto`, `--expire 1d`) |
183
+ | `sf intent buy <ticker> <qty>` | Create buy intent (`--trigger below:28`, `--trigger time:<ISO>`, `--soft "condition"`, `--auto`) |
184
184
  | `sf intent sell <ticker> <qty>` | Create sell intent |
185
185
  | `sf intent list` | Active intents (`--all` for history) |
186
186
  | `sf intent status <id>` | Detailed status + fills |
187
187
  | `sf intent cancel <id>` | Cancel an intent |
188
- | `sf runtime start` | Start execution daemon |
188
+ | `sf runtime start` | Start execution daemon (Kalshi + Polymarket) |
189
189
  | `sf runtime stop` | Stop daemon |
190
190
  | `sf runtime status` | Active intents + runtime state |
191
+ | `sf backtest <ticker>` | Strategy backtest (`--entry-below 35 --stop 20 --tp 60 --days 30`) |
192
+ | `sf heartbeat <id>` | View/configure heartbeat + closed-loop (`--closed-loop-entry`, `--closed-loop-exit`) |
191
193
 
192
194
  ### Trading (requires `--enable-trading`)
193
195
 
package/dist/12.index.js CHANGED
@@ -1 +1 @@
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 &lt;id&gt; — 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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}},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)}};
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 &lt;id&gt; — 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 (90s)")),9e4)),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")),9e4))])}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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}},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)}};
@@ -0,0 +1 @@
1
+ "use strict";exports.id=122,exports.ids=[122],exports.modules={93122:(t,e,i)=>{e.syncPositionsIfEnabled=async function(){const t=(0,s.loadConfig)();if(!t.syncPositions)return null;if(!t.apiKey)return null;const e=[];try{const{getPositions:t,isKalshiConfigured:s}=await Promise.resolve().then(i.t.bind(i,96139,23));if(s()){const i=await t();if(i)for(const t of i)t.quantity>0&&e.push({ticker:t.ticker,venue:"kalshi",side:t.side||"yes",quantity:t.quantity,avgPrice:t.average_price_paid||0,title:t.market_title||t.ticker})}}catch{}try{const{polymarketGetPositions:s}=await Promise.resolve().then(i.bind(i,34331)),n=t.polymarketWalletAddress||process.env.POLYMARKET_WALLET_ADDRESS;if(n){const t=await s(n);for(const i of t){const t=parseFloat(String(i.size||"0"));t>0&&e.push({ticker:i.asset||i.conditionId||"",venue:"polymarket",side:"Yes"===i.outcome?"yes":"no",quantity:Math.round(t),avgPrice:100*parseFloat(String(i.avgPrice||"0")),title:i.title||i.asset||""})}}}catch{}if(0===e.length)return{synced:0,matched:0};try{const t=new n.SFClient,i=await t.syncPositions(e);return{synced:i.synced||0,matched:i.matched||0}}catch{return null}};const s=i(11627),n=i(19218)}};
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,i){const s=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),i=`\n\n## Live State\nConfidence: ${e}%\nTop edges: ${t.map(e=>`${(e.market||"").slice(0,20)} ${e.edge>0?"+":""}${e.edge}¢`).join(" | ")||"none"}`,a=s.state?.systemPrompt||"";a.includes("## Live State")?s.setSystemPrompt(a.replace(/\n\n## Live State[\s\S]*$/,i)):s.setSystemPrompt(a+i)}}catch{}return new Promise((e,r)=>{let o="",c="";const l=setTimeout(()=>{e(o||c||"Response timeout (45s). Try a simpler question.")},45e3),d=s.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`,i&&i(r.toolName)),"agent_end"===r.type){clearTimeout(l),d?.(),t.agentMessages=s.state.messages||[];try{t.thesisId&&((0,a.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"user",content:n,source:"telegram"}),o&&(0,a.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"assistant",content:o.slice(0,5e3),source:"telegram"}))}catch{}e(o||c||"(no response)")}});s.prompt(n).catch(e=>{clearTimeout(l),d?.(),r(e)})})};const i=n(11627),a=n(73600);let s=null;async function r(){if(s)return s;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))]),i=await Promise.all([n.e(788),n.e(722)]).then(n.bind(n,85722));return s={Agent:e.Agent,streamSimple:t.streamSimple,Type:i.Type},s}async function o(e,t){if(t.agent)return t.agent;const{Agent:s,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,d=(0,i.loadConfig)(),p=d.openrouterKey||process.env.OPENROUTER_API_KEY,u=d.apiKey||process.env.SF_API_KEY,m=d.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev",h=!p&&!!u,g=p||u;if(!g)throw new Error("Need API key. Run sf login or sf setup.");const y=await e.getContext(t.thesisId),x="number"==typeof y.confidence?Math.round(100*y.confidence):50,f=await async function(e,t,s){const{Type:o}=await r(),c=(0,i.loadConfig)(),l=o.Object({}),d=await Promise.resolve().then(n.t.bind(n,96139,23)),{kalshiFetchAllSeries:p,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:i}=await Promise.resolve().then(n.bind(n,19218)),a=await i(t.q);return{content:[{type:"text",text:JSON.stringify(a,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,i)=>(await e.injectSignal(t,i.type||"user_note",i.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 p(),i=t.query.toLowerCase().split(/\s+/);n=e.filter(e=>i.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 d.getPositions();if(!e)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};for(const t of e){const e=await d.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 d.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 d.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 d.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 d.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),i=await Promise.allSettled(n.map(async t=>((await e.getContext(t.id)).edges||[]).map(e=>({...e,thesisId:t.id})))),a=[];for(const e of i)"fulfilled"===e.status&&a.push(...e.value);return a.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0)),{content:[{type:"text",text:JSON.stringify(a.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 i=await e.getFeed(n.hours||24);return{content:[{type:"text",text:JSON.stringify(i,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,i=c.apiKey||process.env.SF_API_KEY,a=c.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev";if(!n&&(n||!i))return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let s;if(s=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(`${a}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}),!s.ok)return{content:[{type:"text",text:`Search failed: ${s.status}`}],details:{}};const r=await s.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 i=await e.createThesis(n.rawThesis,!0);return{content:[{type:"text",text:`Created: ${i.id}\nConfidence: ${Math.round(100*(i.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=s,i=[];!function e(t){for(const n of t)i.push(n),n.children?.length&&e(n.children)}(n?.causalTree?.nodes||[]);const a=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 i)a.has(e.id)&&(e.probability=a.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=i.find(t=>t.id===e.relatedNodeId);if(!t||!a.has(t.id))return{market:e.market,oldEdge:e.edge,newEdge:e.edge,signal:"unchanged"};const n=t.probability/(e.confidence||.5),s=Math.round(e.thesisPrice*n)-e.marketPrice;return{market:e.market,oldEdge:e.edge,newEdge:s,signal:Math.abs(s-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 i=await e.searchX(n.query,{mode:n.mode,hours:n.hours});return{content:[{type:"text",text:JSON.stringify(i,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 i=await e.getXVolume(n.query,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(i,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 i=await e.searchXNews(n.query,{limit:n.limit});return{content:[{type:"text",text:JSON.stringify(i,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 i=await e.getXAccount(n.username,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(i,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 i=await e.getHeartbeatConfig(n.thesisId);return{content:[{type:"text",text:JSON.stringify(i,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 i=await fetch(`${g}/api/agent/world?${n}`);return{content:[{type:"text",text:await i.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 i=await fetch(`${g}/api/monitor-the-situation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a=await i.json();return{content:[{type:"text",text:JSON.stringify(a,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 i=await fetch(`${g}/api/monitor-the-situation/enrich`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a=await i.json();return{content:[{type:"text",text:JSON.stringify(a,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)}),i=await n.json();return{content:[{type:"text",text:JSON.stringify(i,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 i=await fetch(`${g}/api/public/skills?${n}`),a=await i.json();return{content:[{type:"text",text:JSON.stringify(a,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}`}}),i=await n.json();return{content:[{type:"text",text:JSON.stringify(i,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}`}}),i=await n.json();return{content:[{type:"text",text:JSON.stringify(i,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 d.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 d.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,a.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,a.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,a.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,a.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,a.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 i of t)try{await e.cancelIntentAPI(i.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:{}}}}}),c.apiUrl||process.env.SF_API_URL,c.apiKey||process.env.SF_API_KEY,h.push({name:"create_intent",label:"Create Intent",description:"Declare an execution intent with trigger conditions. Runtime daemon evaluates triggers and executes via local keys.",parameters:o.Object({action:o.String({description:"buy or sell"}),venue:o.String({description:"kalshi or polymarket"}),marketId:o.String({description:"Market ticker"}),marketTitle:o.String({description:"Human-readable name"}),direction:o.String({description:"yes or no"}),targetQuantity:o.Number({description:"Number of contracts"}),maxPrice:o.Optional(o.Number({description:"Max price in cents (1-99)"})),triggerType:o.Optional(o.String({description:"immediate, price_below, price_above, time"})),triggerPrice:o.Optional(o.Number({description:"Price trigger threshold in cents"})),triggerAt:o.Optional(o.String({description:"ISO timestamp for time trigger"})),softCondition:o.Optional(o.String({description:"Natural language condition evaluated by LLM before execution"})),rationale:o.Optional(o.String({description:"Why this trade"})),autoExecute:o.Optional(o.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(t,n)=>{const i=await e.createIntent({...n,source:"telegram",expireAt:new Date(Date.now()+864e5).toISOString()});return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"list_intents",label:"List Intents",description:"List execution intents — pending, armed, triggered, filled.",parameters:o.Object({activeOnly:o.Optional(o.Boolean({description:"Only active (default true)"}))}),execute:async(t,n)=>{const i=await e.listIntents({active:!1!==n.activeOnly});return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"cancel_intent",label:"Cancel Intent",description:"Cancel an active intent.",parameters:o.Object({intentId:o.String({description:"Intent ID"})}),execute:async(t,n)=>{const i=await e.cancelIntentAPI(n.intentId);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime is running.",parameters:l,execute:async()=>{const{existsSync:t,readFileSync:i}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:a}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=a(s(),".sf","runtime.pid");let o=!1,c="";if(t(r)){c=i(r,"utf-8").trim();try{process.kill(parseInt(c),0),o=!0}catch{}}const l=await e.listIntents({active:!0});return{content:[{type:"text",text:JSON.stringify({running:o,pid:o?c:null,...l},null,2)}],details:{}}}},{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon.",parameters:l,execute:async()=>{const{existsSync:e,readFileSync:t,mkdirSync:i,openSync:a}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:r}=await Promise.resolve().then(n.t.bind(n,70857,23)),{spawn:o}=await Promise.resolve().then(n.t.bind(n,35317,23)),c=s(r(),".sf","runtime.pid"),l=s(r(),".sf","runtime.log");if(e(c)){const e=t(c,"utf-8").trim();try{return process.kill(parseInt(e),0),{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{}}i(s(r(),".sf"),{recursive:!0});const d=a(l,"a");return o(process.execPath,[process.argv[1],"runtime","start"],{detached:!0,stdio:["ignore",d,d],env:{...process.env}}).unref(),await new Promise(e=>setTimeout(e,1e3)),{content:[{type:"text",text:`Runtime started. Log: ${l}`}],details:{}}}},{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:l,execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:i}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:a}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=a(s(),".sf","runtime.pid");if(!e(r))return{content:[{type:"text",text:"No runtime running."}],details:{}};const o=t(r,"utf-8").trim();try{return process.kill(parseInt(o),"SIGTERM"),i(r),{content:[{type:"text",text:`Runtime stopped (PID ${o}).`}],details:{}}}catch{try{i(r)}catch{}return{content:[{type:"text",text:"Runtime was not running (stale PID removed)."}],details:{}}}}},{name:"daemon_command",label:"Daemon Command",description:"Send command to a running daemon. Actions: pause, resume, scan_now.",parameters:o.Object({target:o.String({description:"Target: runtime, telegram, watch"}),action:o.String({description:"Command: pause, resume, scan_now"})}),execute:async(e,t)=>{const{writeMessage:i}=await n.e(563).then(n.bind(n,9563)),a=i({from:"agent",to:t.target,type:"command",priority:"normal",payload:{action:t.action},ttl:3600});return{content:[{type:"text",text:`Command sent to ${t.target}: ${t.action} (msg ${a})`}],details:{}}}},{name:"set_wake_condition",label:"Set Wake Condition",description:"Set a condition for daemons to alert you. Types: price, time, llm.",parameters:o.Object({description:o.String({description:"Human-readable description"}),type:o.String({description:"price, time, or llm"}),condition:o.Any({description:"Condition config"}),priority:o.Optional(o.String())}),execute:async(e,t)=>{const{saveWakeCondition:i}=await n.e(563).then(n.bind(n,9563)),{randomBytes:a}=await Promise.resolve().then(n.t.bind(n,76982,23)),s={id:a(8).toString("hex"),createdAt:(new Date).toISOString(),description:t.description,type:t.type,[`${t.type}Condition`]:t.condition,alertChannels:["bus","telegram"],priority:t.priority||"normal",maxFires:-1,firedCount:0,lastFiredAt:null,expiresAt:null,active:!0};return i(s),{content:[{type:"text",text:`Wake condition set: "${t.description}" (${s.id})`}],details:{}}}},{name:"check_daemon_alerts",label:"Check Alerts",description:"Read alerts from running daemons.",parameters:l,execute:async()=>{const{readMessages:e,deleteMessage:t}=await n.e(563).then(n.bind(n,9563)),i=e("agent","outbox");return 0===i.length?{content:[{type:"text",text:"No new daemon alerts."}],details:{}}:{content:[{type:"text",text:i.map(e=>(t(e.id,"outbox"),`[${e.priority}] ${e.from}: ${e.payload.summary||JSON.stringify(e.payload)}`)).join("\n")}],details:{}}}},{name:"schedule_wake",label:"Schedule Wake",description:"Schedule a self-wake: after N minutes, perform an action. Can repeat.",parameters:o.Object({delayMinutes:o.Number({description:"Minutes from now"}),action:o.String({description:"prompt, tool, or check"}),prompt:o.Optional(o.String({description:"Prompt text (for action=prompt)"})),repeatMinutes:o.Optional(o.Number({description:"Repeat interval in minutes"})),context:o.Optional(o.String({description:"Why this wake"}))}),execute:async(e,i)=>{const{scheduleWake:a}=await n.e(563).then(n.bind(n,9563)),s=a({...i,thesisId:t});return{content:[{type:"text",text:`Wake scheduled: ${s.id} fires at ${s.fireAt}${i.repeatMinutes?` (repeats every ${i.repeatMinutes}m)`:""}`}],details:{}}}},{name:"list_wakes",label:"List Wakes",description:"List all scheduled self-wakes.",parameters:l,execute:async()=>{const{listWakes:e}=await n.e(563).then(n.bind(n,9563)),t=e();return 0===t.length?{content:[{type:"text",text:"No scheduled wakes."}],details:{}}:{content:[{type:"text",text:t.map(e=>`${e.id.slice(0,8)} ${e.firedAt?"FIRED":"PENDING"} at ${e.fireAt} — ${e.context||e.action}`).join("\n")}],details:{}}}},{name:"cancel_wake",label:"Cancel Wake",description:"Cancel a scheduled wake.",parameters:o.Object({wakeId:o.String({description:"Wake ID"})}),execute:async(e,t)=>{const{cancelWake:i}=await n.e(563).then(n.bind(n,9563));return{content:[{type:"text",text:i(t.wakeId)?"Cancelled.":"Not found."}],details:{}}}},{name:"send_alert",label:"Send Alert",description:"Push an alert to Telegram and/or daemon bus.",parameters:o.Object({message:o.String({description:"Alert message"}),priority:o.Optional(o.String({description:"low | normal | high | critical"}))}),execute:async(e,t)=>{try{const{writeMessage:e}=await n.e(563).then(n.bind(n,9563));return e({from:"agent",to:"all",type:"alert",priority:t.priority||"high",payload:{summary:t.message},ttl:7200}),{content:[{type:"text",text:`Alert sent: "${t.message}"`}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}}),h}(e,t.thesisId,y),b=d.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,headers:{"HTTP-Referer":"https://simplefunctions.dev","X-Title":"SimpleFunctions"}}}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 s({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/bus. schedule_wake / list_wakes / cancel_wake: self-scheduling.\n- create_intent / list_intents / cancel_intent: execution intents with triggers.\n- runtime_start / runtime_stop / runtime_status: local execution daemon.\n- daemon_command / set_wake_condition / check_daemon_alerts: smart daemon control.\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${d.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: ${x}%\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:f,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,a.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=_,_}}};
1
+ "use strict";exports.id=160,exports.ids=[160],exports.modules={28160:(e,t,n)=>{t.runAgentMessage=async function(e,t,n,i){const s=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),i=`\n\n## Live State\nConfidence: ${e}%\nTop edges: ${t.map(e=>`${(e.market||"").slice(0,20)} ${e.edge>0?"+":""}${e.edge}¢`).join(" | ")||"none"}`,a=s.state?.systemPrompt||"";a.includes("## Live State")?s.setSystemPrompt(a.replace(/\n\n## Live State[\s\S]*$/,i)):s.setSystemPrompt(a+i)}}catch{}return new Promise((e,r)=>{let o="",c="",l=!1;function d(i){if(!l){l=!0,t.agentMessages=s.state.messages||[];try{t.thesisId&&((0,a.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"user",content:n,source:"telegram"}),i&&(0,a.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"assistant",content:i.slice(0,5e3),source:"telegram"}))}catch{}e(i||"(no response)")}}const p=setTimeout(()=>{d(o||c||"Response timeout. Try a simpler question or follow up.")},12e4),u=s.subscribe(e=>{if("message_update"===e.type){const t=e.assistantMessageEvent;"text_delta"===t.type&&(o+=t.delta)}"tool_execution_start"===e.type&&(c+=`⚡ ${e.toolName}\n`,i&&i(e.toolName)),"agent_end"===e.type&&(clearTimeout(p),u?.(),d(o||c))});s.prompt(n).catch(e=>{clearTimeout(p),u?.(),l||r(e)})})};const i=n(11627),a=n(73600);let s=null;async function r(){if(s)return s;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))]),i=await Promise.all([n.e(788),n.e(722)]).then(n.bind(n,85722));return s={Agent:e.Agent,streamSimple:t.streamSimple,Type:i.Type},s}async function o(e,t){if(t.agent)return t.agent;const{Agent:s,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,d=(0,i.loadConfig)(),p=d.openrouterKey||process.env.OPENROUTER_API_KEY,u=d.apiKey||process.env.SF_API_KEY,m=d.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev",g=!p&&!!u,h=p||u;if(!h)throw new Error("Need API key. Run sf login or sf setup.");const y=await e.getContext(t.thesisId),x="number"==typeof y.confidence?Math.round(100*y.confidence):50,f=await async function(e,t,s){const{Type:o}=await r(),c=(0,i.loadConfig)(),l=o.Object({}),d=await Promise.resolve().then(n.t.bind(n,96139,23)),{kalshiFetchAllSeries:p,kalshiFetchMarketsBySeries:u,kalshiFetchMarket:m}=await Promise.resolve().then(n.bind(n,19218)),g=[{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:i}=await Promise.resolve().then(n.bind(n,19218)),a=await i(t.q);return{content:[{type:"text",text:JSON.stringify(a,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,i)=>(await e.injectSignal(t,i.type||"user_note",i.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 p(),i=t.query.toLowerCase().split(/\s+/);n=e.filter(e=>i.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 d.getPositions();if(!e)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};for(const t of e){const e=await d.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 d.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 d.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 d.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 d.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),i=await Promise.allSettled(n.map(async t=>((await e.getContext(t.id)).edges||[]).map(e=>({...e,thesisId:t.id})))),a=[];for(const e of i)"fulfilled"===e.status&&a.push(...e.value);return a.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0)),{content:[{type:"text",text:JSON.stringify(a.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 i=await e.getFeed(n.hours||24);return{content:[{type:"text",text:JSON.stringify(i,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,i=c.apiKey||process.env.SF_API_KEY,a=c.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev";if(!n&&(n||!i))return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let s;if(s=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(`${a}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}),!s.ok)return{content:[{type:"text",text:`Search failed: ${s.status}`}],details:{}};const r=await s.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 i=await e.createThesis(n.rawThesis,!0);return{content:[{type:"text",text:`Created: ${i.id}\nConfidence: ${Math.round(100*(i.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=s,i=[];!function e(t){for(const n of t)i.push(n),n.children?.length&&e(n.children)}(n?.causalTree?.nodes||[]);const a=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 i)a.has(e.id)&&(e.probability=a.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=i.find(t=>t.id===e.relatedNodeId);if(!t||!a.has(t.id))return{market:e.market,oldEdge:e.edge,newEdge:e.edge,signal:"unchanged"};const n=t.probability/(e.confidence||.5),s=Math.round(e.thesisPrice*n)-e.marketPrice;return{market:e.market,oldEdge:e.edge,newEdge:s,signal:Math.abs(s-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:{}}}}];g.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 i=await e.searchX(n.query,{mode:n.mode,hours:n.hours});return{content:[{type:"text",text:JSON.stringify(i,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 i=await e.getXVolume(n.query,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(i,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 i=await e.searchXNews(n.query,{limit:n.limit});return{content:[{type:"text",text:JSON.stringify(i,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 i=await e.getXAccount(n.username,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(i,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 i=await e.getHeartbeatConfig(n.thesisId);return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}});const h=process.env.SF_API_URL||c.apiUrl||"https://simplefunctions.dev";g.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 i=await fetch(`${h}/api/agent/world?${n}`);return{content:[{type:"text",text:await i.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 i=await fetch(`${h}/api/monitor-the-situation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a=await i.json();return{content:[{type:"text",text:JSON.stringify(a,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 i=await fetch(`${h}/api/monitor-the-situation/enrich`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a=await i.json();return{content:[{type:"text",text:JSON.stringify(a,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(`${h}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c.apiKey}`},body:JSON.stringify(t)}),i=await n.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"list_skills",label:"Skills",description:"List built-in + custom skills.",parameters:l,execute:async()=>{const e=await fetch(`${h}/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 i=await fetch(`${h}/api/public/skills?${n}`),a=await i.json();return{content:[{type:"text",text:JSON.stringify(a,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(`${h}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${c.apiKey}`}}),i=await n.json();return{content:[{type:"text",text:JSON.stringify(i,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(`${h}/api/thesis/${t.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${c.apiKey}`}}),i=await n.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}}),c.tradingEnabled&&g.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 d.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 d.cancelOrder(t.orderId),{content:[{type:"text",text:`✓ Order ${t.orderId} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`✗ Cancel failed: ${e.message}`}],details:{}}}}}),g.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,a.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,a.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,a.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,a.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,a.wsDelete)(t.path).message}],details:{}})}),g.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 i of t)try{await e.cancelIntentAPI(i.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:{}}}}});const y=c.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev";return c.apiKey||process.env.SF_API_KEY,g.push({name:"create_intent",label:"Create Intent",description:"Declare an execution intent with trigger conditions. Runtime daemon evaluates triggers and executes via local keys.",parameters:o.Object({action:o.String({description:"buy or sell"}),venue:o.String({description:"kalshi or polymarket"}),marketId:o.String({description:"Market ticker"}),marketTitle:o.String({description:"Human-readable name"}),direction:o.String({description:"yes or no"}),targetQuantity:o.Number({description:"Number of contracts"}),maxPrice:o.Optional(o.Number({description:"Max price in cents (1-99)"})),triggerType:o.Optional(o.String({description:"immediate, price_below, price_above, time"})),triggerPrice:o.Optional(o.Number({description:"Price trigger threshold in cents"})),triggerAt:o.Optional(o.String({description:"ISO timestamp for time trigger"})),softCondition:o.Optional(o.String({description:"Natural language condition evaluated by LLM before execution"})),rationale:o.Optional(o.String({description:"Why this trade"})),autoExecute:o.Optional(o.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(t,n)=>{const i=await e.createIntent({...n,source:"telegram",expireAt:new Date(Date.now()+864e5).toISOString()});return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"list_intents",label:"List Intents",description:"List execution intents — pending, armed, triggered, filled.",parameters:o.Object({activeOnly:o.Optional(o.Boolean({description:"Only active (default true)"}))}),execute:async(t,n)=>{const i=await e.listIntents({active:!1!==n.activeOnly});return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"cancel_intent",label:"Cancel Intent",description:"Cancel an active intent.",parameters:o.Object({intentId:o.String({description:"Intent ID"})}),execute:async(t,n)=>{const i=await e.cancelIntentAPI(n.intentId);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime is running.",parameters:l,execute:async()=>{const{existsSync:t,readFileSync:i}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:a}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=a(s(),".sf","runtime.pid");let o=!1,c="";if(t(r)){c=i(r,"utf-8").trim();try{process.kill(parseInt(c),0),o=!0}catch{}}const l=await e.listIntents({active:!0});return{content:[{type:"text",text:JSON.stringify({running:o,pid:o?c:null,...l},null,2)}],details:{}}}},{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon.",parameters:l,execute:async()=>{const{existsSync:e,readFileSync:t,mkdirSync:i,openSync:a}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:r}=await Promise.resolve().then(n.t.bind(n,70857,23)),{spawn:o}=await Promise.resolve().then(n.t.bind(n,35317,23)),c=s(r(),".sf","runtime.pid"),l=s(r(),".sf","runtime.log");if(e(c)){const e=t(c,"utf-8").trim();try{return process.kill(parseInt(e),0),{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{}}i(s(r(),".sf"),{recursive:!0});const d=a(l,"a");return o(process.execPath,[process.argv[1],"runtime","start"],{detached:!0,stdio:["ignore",d,d],env:{...process.env}}).unref(),await new Promise(e=>setTimeout(e,1e3)),{content:[{type:"text",text:`Runtime started. Log: ${l}`}],details:{}}}},{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:l,execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:i}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:a}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=a(s(),".sf","runtime.pid");if(!e(r))return{content:[{type:"text",text:"No runtime running."}],details:{}};const o=t(r,"utf-8").trim();try{return process.kill(parseInt(o),"SIGTERM"),i(r),{content:[{type:"text",text:`Runtime stopped (PID ${o}).`}],details:{}}}catch{try{i(r)}catch{}return{content:[{type:"text",text:"Runtime was not running (stale PID removed)."}],details:{}}}}},{name:"daemon_command",label:"Daemon Command",description:"Send command to a running daemon. Actions: pause, resume, scan_now.",parameters:o.Object({target:o.String({description:"Target: runtime, telegram, watch"}),action:o.String({description:"Command: pause, resume, scan_now"})}),execute:async(e,t)=>{const{writeMessage:i}=await n.e(563).then(n.bind(n,9563)),a=i({from:"agent",to:t.target,type:"command",priority:"normal",payload:{action:t.action},ttl:3600});return{content:[{type:"text",text:`Command sent to ${t.target}: ${t.action} (msg ${a})`}],details:{}}}},{name:"set_wake_condition",label:"Set Wake Condition",description:"Set a condition for daemons to alert you. Types: price, time, llm.",parameters:o.Object({description:o.String({description:"Human-readable description"}),type:o.String({description:"price, time, or llm"}),condition:o.Any({description:"Condition config"}),priority:o.Optional(o.String())}),execute:async(e,t)=>{const{saveWakeCondition:i}=await n.e(563).then(n.bind(n,9563)),{randomBytes:a}=await Promise.resolve().then(n.t.bind(n,76982,23)),s={id:a(8).toString("hex"),createdAt:(new Date).toISOString(),description:t.description,type:t.type,[`${t.type}Condition`]:t.condition,alertChannels:["bus","telegram"],priority:t.priority||"normal",maxFires:-1,firedCount:0,lastFiredAt:null,expiresAt:null,active:!0};return i(s),{content:[{type:"text",text:`Wake condition set: "${t.description}" (${s.id})`}],details:{}}}},{name:"check_daemon_alerts",label:"Check Alerts",description:"Read alerts from running daemons.",parameters:l,execute:async()=>{const{readMessages:e,deleteMessage:t}=await n.e(563).then(n.bind(n,9563)),i=e("agent","outbox");return 0===i.length?{content:[{type:"text",text:"No new daemon alerts."}],details:{}}:{content:[{type:"text",text:i.map(e=>(t(e.id,"outbox"),`[${e.priority}] ${e.from}: ${e.payload.summary||JSON.stringify(e.payload)}`)).join("\n")}],details:{}}}},{name:"schedule_wake",label:"Schedule Wake",description:"Schedule a self-wake: after N minutes, perform an action. Can repeat.",parameters:o.Object({delayMinutes:o.Number({description:"Minutes from now"}),action:o.String({description:"prompt, tool, or check"}),prompt:o.Optional(o.String({description:"Prompt text (for action=prompt)"})),repeatMinutes:o.Optional(o.Number({description:"Repeat interval in minutes"})),context:o.Optional(o.String({description:"Why this wake"}))}),execute:async(e,i)=>{const{scheduleWake:a}=await n.e(563).then(n.bind(n,9563)),s=a({...i,thesisId:t});return{content:[{type:"text",text:`Wake scheduled: ${s.id} fires at ${s.fireAt}${i.repeatMinutes?` (repeats every ${i.repeatMinutes}m)`:""}`}],details:{}}}},{name:"list_wakes",label:"List Wakes",description:"List all scheduled self-wakes.",parameters:l,execute:async()=>{const{listWakes:e}=await n.e(563).then(n.bind(n,9563)),t=e();return 0===t.length?{content:[{type:"text",text:"No scheduled wakes."}],details:{}}:{content:[{type:"text",text:t.map(e=>`${e.id.slice(0,8)} ${e.firedAt?"FIRED":"PENDING"} at ${e.fireAt} — ${e.context||e.action}`).join("\n")}],details:{}}}},{name:"cancel_wake",label:"Cancel Wake",description:"Cancel a scheduled wake.",parameters:o.Object({wakeId:o.String({description:"Wake ID"})}),execute:async(e,t)=>{const{cancelWake:i}=await n.e(563).then(n.bind(n,9563));return{content:[{type:"text",text:i(t.wakeId)?"Cancelled.":"Not found."}],details:{}}}},{name:"send_alert",label:"Send Alert",description:"Push an alert to Telegram and/or daemon bus.",parameters:o.Object({message:o.String({description:"Alert message"}),priority:o.Optional(o.String({description:"low | normal | high | critical"}))}),execute:async(e,t)=>{try{const{writeMessage:e}=await n.e(563).then(n.bind(n,9563));return e({from:"agent",to:"all",type:"alert",priority:t.priority||"high",payload:{summary:t.message},ttl:7200}),{content:[{type:"text",text:`Alert sent: "${t.message}"`}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}}),g.push({name:"get_world_delta",label:"World Delta",description:"Incremental world state update — only what changed. ~30-50 tokens. Much cheaper than full state for polling.",parameters:o.Object({since:o.Optional(o.String({description:'"30m", "1h", "6h", "24h" or ISO timestamp (default "1h")'}))}),execute:async(e,t)=>{const n=t.since||"1h",i=await fetch(`${y}/api/agent/world/delta?since=${encodeURIComponent(n)}`);return i.ok?{content:[{type:"text",text:await i.text()}],details:{}}:{content:[{type:"text",text:`Delta API error: ${i.status}`}],details:{}}}},{name:"get_trade_ideas",label:"Trade Ideas",description:"S&T-style trade ideas with conviction levels and catalysts.",parameters:o.Object({freshness:o.Optional(o.String({description:"today, week, or all"})),category:o.Optional(o.String({description:"macro, geopolitics, crypto, policy, event"}))}),execute:async(e,t)=>{const n=new URLSearchParams;t.freshness&&n.set("freshness",t.freshness),t.category&&n.set("category",t.category);const i=await fetch(`${y}/api/public/ideas?${n.toString()}`);return i.ok?{content:[{type:"text",text:JSON.stringify(await i.json(),null,2)}],details:{}}:{content:[{type:"text",text:`Ideas API error: ${i.status}`}],details:{}}}},{name:"get_milestones",label:"Milestones",description:"Upcoming events from Kalshi calendar: economic releases, political events, catalysts.",parameters:o.Object({hours:o.Optional(o.Number({description:"Hours ahead (default 168 = 1 week)"})),category:o.Optional(o.String({description:"Economics, Politics, Sports"}))}),execute:async(e,t)=>{const i=await Promise.resolve().then(n.t.bind(n,96139,23)),a=await i.getExchangeAnnouncements();if(!a||0===a.length)return{content:[{type:"text",text:"No upcoming milestones."}],details:{}};const s=t.category?a.filter(e=>e.category?.toLowerCase().includes(t.category.toLowerCase())):a;return{content:[{type:"text",text:JSON.stringify(s.slice(0,20),null,2)}],details:{}}}},{name:"get_liquidity",label:"Liquidity",description:"Orderbook liquidity analysis for markets matching a query. Returns bid/ask depth, spread, liquidity score.",parameters:o.Object({query:o.String({description:"Search query"})}),execute:async(e,t)=>{const i=await fetch(`${y}/api/public/scan?q=${encodeURIComponent(t.query)}&limit=10`);if(!i.ok)return{content:[{type:"text",text:`Scan error: ${i.status}`}],details:{}};const a=await i.json(),s=(a.results||a.markets||[]).slice(0,5),r=[];for(const e of s)if("kalshi"===e.venue&&e.ticker){const t=await(await Promise.resolve().then(n.t.bind(n,96139,23))).getPublicOrderbook(e.ticker,5);if(t){const n=t.yes_dollars||[],i=t.no_dollars||[],a=n.length>0?Math.round(100*parseFloat(n[0][0])):0,s=i.length>0?100-Math.round(100*parseFloat(i[0][0])):100;r.push({ticker:e.ticker,title:(e.title||"").slice(0,50),bestBid:a,bestAsk:s,spread:s-a,venue:"kalshi"})}}return{content:[{type:"text",text:r.length>0?JSON.stringify(r,null,2):"No orderbook data found."}],details:{}}}},{name:"explore_public",label:"Explore Public",description:"Browse public theses with edges. Discover what other users are tracking.",parameters:o.Object({limit:o.Optional(o.Number({description:"Max results (default 10)"}))}),execute:async(e,t)=>{const n=await fetch(`${y}/api/public/theses?limit=${t.limit||10}`);return n.ok?{content:[{type:"text",text:JSON.stringify(await n.json(),null,2)}],details:{}}:{content:[{type:"text",text:`Public theses error: ${n.status}`}],details:{}}}},{name:"create_strategy",label:"Create Strategy",description:"Create a trading strategy for a thesis with entry/exit conditions.",parameters:o.Object({marketId:o.String({description:"Market ticker"}),market:o.String({description:"Human-readable name"}),direction:o.String({description:"yes or no"}),entryBelow:o.Optional(o.Number({description:"Entry: ask <= cents"})),stopLoss:o.Optional(o.Number({description:"Stop loss: bid <= cents"})),takeProfit:o.Optional(o.Number({description:"Take profit: bid >= cents"})),maxQuantity:o.Optional(o.Number({description:"Max contracts (default 500)"})),softConditions:o.Optional(o.String({description:"LLM-evaluated conditions"})),rationale:o.Optional(o.String({description:"Reasoning"}))}),execute:async(n,i)=>{const a=await e.createStrategyAPI(t,{...i,createdBy:"telegram"});return{content:[{type:"text",text:JSON.stringify(a)}],details:{}}}},{name:"list_strategies",label:"List Strategies",description:"List strategies for the current thesis.",parameters:o.Object({status:o.Optional(o.String({description:"Filter: active, watching, executed, cancelled"}))}),execute:async(n,i)=>{const a=await e.getStrategies(t,i.status);return{content:[{type:"text",text:JSON.stringify(a,null,2)}],details:{}}}}),g}(e,t.thesisId,y),b=d.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,headers:{"HTTP-Referer":"https://simplefunctions.dev","X-Title":"SimpleFunctions"}}}g&&(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 s({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). Use get_world_delta for cheap incremental updates.\n- Use get_trade_ideas for S&T-style pitches. Use get_milestones for upcoming catalysts.\n- Use get_liquidity / explore_public for discovery. Use create_strategy / list_strategies for trade planning.\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/bus. schedule_wake / list_wakes / cancel_wake: self-scheduling.\n- create_intent / list_intents / cancel_intent: execution intents with triggers.\n- runtime_start / runtime_stop / runtime_status: local execution daemon.\n- daemon_command / set_wake_condition / check_daemon_alerts: smart daemon control.\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${d.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: ${x}%\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:f,thinkingLevel:"off"},streamFn:o,getApiKey:e=>"openrouter"===e?h:void 0});if(t.agentMessages.length>0)try{O.replaceMessages(t.agentMessages)}catch{}else if(t.thesisId)try{const e=(0,a.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{O.replaceMessages(n)}catch{}}}catch{}return t.agent=O,O}}};
@@ -0,0 +1 @@
1
+ "use strict";exports.id=340,exports.ids=[340],exports.modules={42340:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.smartLLMCall=async function(t){const e=(0,i.loadConfig)(),n=e.apiKey;if(!n)return null;const d=e.apiUrl||"https://simplefunctions.dev",m=t.model||e.smartModel||a,y=t.maxTokens||l,f=t.timeoutMs||c;if(!function(t){const e=t??1;if(e<=0)return!1;try{const t=(0,o.readFileSync)(u,"utf-8").trim().split("\n"),n=Date.now()-2592e6;let s=0;for(const e of t)try{const t=JSON.parse(e);new Date(t.ts).getTime()>n&&(s+=t.costUsd)}catch{}return s<e}catch{return!0}}(e.smartBudgetUsd))return null;try{const e=new AbortController,i=setTimeout(()=>e.abort(),f),a=await fetch(`${d}/api/proxy/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({model:m,messages:[{role:"system",content:t.systemPrompt},{role:"user",content:t.userContent}],max_tokens:y,temperature:t.temperature??.3}),signal:e.signal});if(clearTimeout(i),!a.ok)return null;const c=await a.json(),l=c.choices?.[0]?.message?.content||"",h=c.usage?.prompt_tokens||0,g=c.usage?.completion_tokens||0,S=p[m]||{input:1,output:3},k=(h*S.input+g*S.output)/1e6;return function(t){try{(0,o.mkdirSync)((0,s.join)((0,r.homedir)(),".sf","bus","cost"),{recursive:!0}),(0,o.appendFileSync)(u,JSON.stringify(t)+"\n")}catch{}}({ts:(new Date).toISOString(),daemon:t.daemon,type:t.callType,model:m,inputTokens:h,outputTokens:g,costUsd:k,intentId:t.intentId}),{text:l,usage:{input:h,output:g,costUsd:k}}}catch{return null}},e.getMonthlySpend=function(){try{const t=(0,o.readFileSync)(u,"utf-8").trim().split("\n"),e=Date.now()-2592e6;let n=0;for(const o of t)try{const t=JSON.parse(o);new Date(t.ts).getTime()>e&&(n+=t.costUsd)}catch{}return n}catch{return 0}};const o=n(79896),s=n(16928),r=n(70857),i=n(11627),u=(0,s.join)((0,r.homedir)(),".sf","bus","cost","smart-usage.jsonl"),a="anthropic/claude-haiku-4.5",c=1e4,l=500,p={"anthropic/claude-haiku-4.5":{input:.8,output:4},"anthropic/claude-haiku-4-5-20251001":{input:.8,output:4}}}};
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.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}}}};
1
+ "use strict";exports.id=563,exports.ids=[563,340],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}}}};