@spfunctions/cli 2.0.3 → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/12.index.js +1 -1
- package/dist/563.index.js +1 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/12.index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.id=12,exports.ids=[12],exports.modules={6012:function(e,t,s){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.startBot=async function(e){const t=(0,l.loadConfig)(),a=e.token||t.telegramBotToken||process.env.TELEGRAM_BOT_TOKEN;a||(console.error("No Telegram bot token. Use --token, set TELEGRAM_BOT_TOKEN, or add to ~/.sf/config.json"),process.exit(1));const o=new c.SFClient(t.apiKey,t.apiUrl),f=new n.Bot(a),m=e.chatId||null,y=new Map;function w(e){return!m||e===m}f.command("start",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id);try{const{theses:s}=await o.listTheses(),a=(s||[]).filter(e=>"active"===e.status);a.length>0?(t.thesisId=a[0].id,await e.reply(`✅ Connected to SimpleFunctions\n\nActive thesis: <b>${(a[0].rawThesis||"").slice(0,60)}</b>\nID: <code>${a[0].id.slice(0,8)}</code>\n\nCommands:\n/context — thesis snapshot\n/positions — Kalshi positions\n/edges — top edges\n/balance — account balance\n/orders — resting orders\n/eval — trigger evaluation\n/list — all theses\n/switch — switch thesis\n\nOr just type naturally.`,{parse_mode:"HTML"}),y.has(e.chat.id)&&clearInterval(y.get(e.chat.id)),y.set(e.chat.id,(0,p.startPoller)(f,e.chat.id,o,t.thesisId))):await e.reply('No active theses found. Create one with `sf create "your thesis"`')}catch(t){await e.reply(`❌ Connection failed: ${t.message}\nCheck SF_API_KEY in ~/.sf/config.json`)}}),f.command("context",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id);if(t.thesisId)try{const s=await(0,h.handleContext)(o,t.thesisId);for(const t of(0,d.splitMessage)(s))await e.reply(t,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("No thesis selected. Use /start or /switch <id>")}),f.command("positions",async e=>{if(w(e.chat.id))try{const t=await(0,h.handlePositions)();for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("edges",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleEdges)(o);for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("balance",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleBalance)();await e.reply(t,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("orders",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleOrders)();for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("eval",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id);if(t.thesisId)try{const s=await(0,h.handleEval)(o,t.thesisId);await e.reply(s)}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("No thesis selected.")}),f.command("list",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleList)(o);for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("switch",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id),s=e.match?.trim();if(s)try{const{theses:a}=await o.listTheses(),n=(a||[]).find(e=>e.id.startsWith(s));n?(t.thesisId=n.id,t.agentMessages=[],y.has(e.chat.id)&&clearInterval(y.get(e.chat.id)),y.set(e.chat.id,(0,p.startPoller)(f,e.chat.id,o,t.thesisId)),await e.reply(`Switched to: <code>${n.id.slice(0,8)}</code> — ${(n.rawThesis||"").slice(0,60)}`,{parse_mode:"HTML"})):await e.reply(`No thesis found matching "${s}". Use /list to see all.`)}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("Usage: /switch <thesis_id>")}),f.on("message:text",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id),a=e.message.text;if(!a.startsWith("/")){if(!t.thesisId)try{const{theses:s}=await o.listTheses(),a=(s||[]).filter(e=>"active"===e.status);if(!(a.length>0))return void await e.reply('No active theses. Create one with `sf create "your thesis"` then /start');t.thesisId=a[0].id}catch{return void await e.reply("Could not connect. Use /start first.")}try{await e.replyWithChatAction("typing");const{runAgentMessage:n}=await s.e(160).then(s.bind(s,28160)),i=new Promise((e,t)=>setTimeout(()=>t(new Error("Response timeout (30s)")),3e4)),r=await Promise.race([n(o,t,a),i]);if(r&&0!==r.trim().length)for(const t of(0,d.splitMessage)(r))try{await e.reply(t,{parse_mode:"HTML"})}catch{await e.reply(t)}else await e.reply("No response generated. Try rephrasing or use a slash command.")}catch(t){console.error("[Telegram] Agent error:",t.message),await e.reply(`❌ ${t.message}`)}}}),f.on("callback_query:data",async e=>{const t=e.callbackQuery.data;t.startsWith("order_confirm:")?await e.answerCallbackQuery({text:"Order execution coming soon"}):"order_cancel"===t&&(await e.answerCallbackQuery({text:"Order cancelled"}),await e.editMessageText("❌ Order cancelled."))}),console.log("🤖 SimpleFunctions Telegram bot starting..."),console.log(" SF API: "+(t.apiKey?"✓":"✗")),console.log(" Kalshi: "+(process.env.KALSHI_API_KEY_ID?"✓":"✗")),console.log(" OpenRouter: "+(t.openrouterKey?"✓":"✗")),m&&console.log(` Restricted to chat: ${m}`);function $(){for(const e of y.values())clearInterval(e);f.stop();try{i.default.unlinkSync(u)}catch{}}console.log(" Press Ctrl+C to stop.\n"),i.default.mkdirSync(r.default.dirname(u),{recursive:!0}),i.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",()=>{$(),process.exit(0)}),process.on("SIGTERM",()=>{$(),process.exit(0)}),process.on("exit",()=>{try{i.default.unlinkSync(u)}catch{}}),await f.start()};const n=s(53278),i=a(s(79896)),r=a(s(16928)),o=a(s(70857)),c=s(19218),l=s(11627),d=s(76342),h=s(77499),p=s(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,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.handleContext=async function(e,t){const s=await e.getContext(t),a="number"==typeof s.confidence?Math.round(100*s.confidence):"?",i=s.thesis||s.rawThesis||"N/A";let r=`📋 <b>${(0,n.escapeHtml)(i.slice(0,80))}</b>\n`;r+=`Confidence: <b>${a}%</b> | Status: ${s.status}\n\n`;const o=(s.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,a.isKalshiConfigured)())return"⚠️ Kalshi not configured. Run <code>sf setup --kalshi</code>";const e=await(0,a.getPositions)();if(!e||0===e.length)return"No open positions.";let t=0;const s=[];for(const i of e){const e=await(0,a.getMarketPrice)(i.ticker)??i.average_price_paid,r=(e-i.average_price_paid)*i.quantity;t+=r;const o=(0,n.fmtDollar)(r);s.push(`${i.ticker.slice(0,28).padEnd(29)} ${String(i.quantity).padStart(5)} ${String(i.average_price_paid).padStart(3)}¢→${String(e).padStart(3)}¢ ${o}`)}let i="📊 <b>Positions</b>\n<pre>";return i+=s.join("\n"),i+=`\n${"─".repeat(50)}\nTotal P&L: ${(0,n.fmtDollar)(t)}`,i+="</pre>",i},t.handleEdges=async function(e){const{theses:t}=await e.listTheses(),s=(t||[]).filter(e=>"active"===e.status),a=await Promise.allSettled(s.map(async t=>((await e.getContext(t.id)).edges||[]).map(e=>({...e,thesisId:t.id})))),n=[];for(const e of a)"fulfilled"===e.status&&n.push(...e.value);n.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0));const i=n.slice(0,10);if(0===i.length)return"No edges found.";let r="📈 <b>Top Edges</b>\n<pre>";for(const e of i){const t=(e.market||"???").slice(0,35),s=e.orderbook?.liquidityScore||"?";r+=`${t.padEnd(36)} +${String(e.edge||0).padStart(2)}¢ ${s}\n`}return r+="</pre>",r},t.handleBalance=async function(){if(!(0,a.isKalshiConfigured)())return"⚠️ Kalshi not configured.";const e=await(0,a.getBalance)();return e?`💰 Balance: <b>$${e.balance.toFixed(2)}</b> | Portfolio: <b>$${e.portfolioValue.toFixed(2)}</b>`:"⚠️ Failed to fetch balance."},t.handleOrders=async function(){if(!(0,a.isKalshiConfigured)())return"⚠️ Kalshi not configured.";const e=await(0,a.getOrders)({status:"resting",limit:20});if(!e||!e.orders||0===e.orders.length)return"No resting orders.";let t="📋 <b>Resting Orders</b>\n<pre>";for(const s of e.orders){const e=Math.round(parseFloat(s.remaining_count_fp||"0")),a=Math.round(100*parseFloat(s.yes_price_dollars||"0")),n=(s.ticker||"???").slice(0,25);t+=`${s.action} ${e}x ${n} @ ${a}¢\n`}return t+="</pre>",t},t.handleEval=async function(e,t){return await e.evaluate(t),"⚡ Evaluation triggered. Results in ~2 minutes."},t.handleList=async function(e){const{theses:t}=await e.listTheses();if(!t||0===t.length)return"No theses.";let s="📝 <b>Theses</b>\n<pre>";for(const e of t){const t="number"==typeof e.confidence?Math.round(100*e.confidence):0,a=(e.rawThesis||e.thesis||"").slice(0,50);s+=`${e.id.slice(0,8)} ${String(t).padStart(3)}% ${e.status.padEnd(8)} ${a}\n`}return s+="</pre>",s};const a=s(96139),n=s(76342)},76342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitMessage=function(e,t=4e3){if(e.length<=t)return[e];const s=[];let a=e;for(;a.length>0;){if(a.length<=t){s.push(a);break}let e=a.lastIndexOf("\n",t);e<.5*t&&(e=t),s.push(a.slice(0,e)),a=a.slice(e)}return s},t.fmtDollar=function(e){const t=e/100;return t>=0?`+$${t.toFixed(2)}`:`-$${Math.abs(t).toFixed(2)}`},t.sparkline=function(e){if(0===e.length)return"";const t=Math.min(...e),s=Math.max(...e)-t||1;return e.map(e=>"▁▂▃▄▅▆▇█"[Math.round((e-t)/s*7)]).join("")},t.escapeHtml=function(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}},55875:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.startPoller=function(e,t,s,n){let i=(new Date).toISOString();return setInterval(async()=>{try{const r=await s.getChanges(n,i);if(i=(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,a.escapeHtml)(h.slice(0,200))}`),await e.api.sendMessage(t,p,{parse_mode:"HTML"})}catch{}},6e4)};const a=s(76342)}};
|
|
1
|
+
"use strict";exports.id=12,exports.ids=[12],exports.modules={6012:function(e,t,s){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.startBot=async function(e){const t=(0,l.loadConfig)(),a=e.token||t.telegramBotToken||process.env.TELEGRAM_BOT_TOKEN;a||(console.error("No Telegram bot token. Use --token, set TELEGRAM_BOT_TOKEN, or add to ~/.sf/config.json"),process.exit(1));const o=new c.SFClient(t.apiKey,t.apiUrl),f=new n.Bot(a),m=e.chatId||null,y=new Map;function w(e){return!m||e===m}f.command("start",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id);try{const{theses:s}=await o.listTheses(),a=(s||[]).filter(e=>"active"===e.status);a.length>0?(t.thesisId=a[0].id,await e.reply(`✅ Connected to SimpleFunctions\n\nActive thesis: <b>${(a[0].rawThesis||"").slice(0,60)}</b>\nID: <code>${a[0].id.slice(0,8)}</code>\n\nCommands:\n/context — thesis snapshot\n/positions — Kalshi positions\n/edges — top edges\n/balance — account balance\n/orders — resting orders\n/eval — trigger evaluation\n/list — all theses\n/switch — switch thesis\n\nOr just type naturally.`,{parse_mode:"HTML"}),y.has(e.chat.id)&&clearInterval(y.get(e.chat.id)),y.set(e.chat.id,(0,u.startPoller)(f,e.chat.id,o,t.thesisId))):await e.reply('No active theses found. Create one with `sf create "your thesis"`')}catch(t){await e.reply(`❌ Connection failed: ${t.message}\nCheck SF_API_KEY in ~/.sf/config.json`)}}),f.command("context",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id);if(t.thesisId)try{const s=await(0,h.handleContext)(o,t.thesisId);for(const t of(0,d.splitMessage)(s))await e.reply(t,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("No thesis selected. Use /start or /switch <id>")}),f.command("positions",async e=>{if(w(e.chat.id))try{const t=await(0,h.handlePositions)();for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("edges",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleEdges)(o);for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("balance",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleBalance)();await e.reply(t,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("orders",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleOrders)();for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("eval",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id);if(t.thesisId)try{const s=await(0,h.handleEval)(o,t.thesisId);await e.reply(s)}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("No thesis selected.")}),f.command("list",async e=>{if(w(e.chat.id))try{const t=await(0,h.handleList)(o);for(const s of(0,d.splitMessage)(t))await e.reply(s,{parse_mode:"HTML"})}catch(t){await e.reply(`❌ ${t.message}`)}}),f.command("switch",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id),s=e.match?.trim();if(s)try{const{theses:a}=await o.listTheses(),n=(a||[]).find(e=>e.id.startsWith(s));n?(t.thesisId=n.id,t.agentMessages=[],y.has(e.chat.id)&&clearInterval(y.get(e.chat.id)),y.set(e.chat.id,(0,u.startPoller)(f,e.chat.id,o,t.thesisId)),await e.reply(`Switched to: <code>${n.id.slice(0,8)}</code> — ${(n.rawThesis||"").slice(0,60)}`,{parse_mode:"HTML"})):await e.reply(`No thesis found matching "${s}". Use /list to see all.`)}catch(t){await e.reply(`❌ ${t.message}`)}else await e.reply("Usage: /switch <thesis_id>")}),f.on("message:text",async e=>{if(!w(e.chat.id))return;const t=g(e.chat.id),a=e.message.text;if(!a.startsWith("/")){if(!t.thesisId)try{const{theses:s}=await o.listTheses(),a=(s||[]).filter(e=>"active"===e.status);if(!(a.length>0))return void await e.reply('No active theses. Create one with `sf create "your thesis"` then /start');t.thesisId=a[0].id}catch{return void await e.reply("Could not connect. Use /start first.")}try{const n=setInterval(()=>{e.replyWithChatAction("typing").catch(()=>{})},4e3);await e.replyWithChatAction("typing");const{runAgentMessage:r}=await s.e(160).then(s.bind(s,28160)),i=new Promise((e,t)=>setTimeout(()=>t(new Error("Response timeout (30s)")),3e4));let c;try{c=await Promise.race([r(o,t,a),i])}finally{clearInterval(n)}if(c&&0!==c.trim().length)for(const t of(0,d.splitMessage)(c))try{await e.reply(t,{parse_mode:"HTML"})}catch{await e.reply(t)}else await e.reply("No response generated. Try rephrasing or use a slash command.")}catch(t){console.error("[Telegram] Agent error:",t.message),await e.reply(`❌ ${t.message}`)}}}),f.on("callback_query:data",async e=>{const t=e.callbackQuery.data;t.startsWith("order_confirm:")?await e.answerCallbackQuery({text:"Order execution coming soon"}):"order_cancel"===t&&(await e.answerCallbackQuery({text:"Order cancelled"}),await e.editMessageText("❌ Order cancelled."))}),console.log("🤖 SimpleFunctions Telegram bot starting..."),console.log(" SF API: "+(t.apiKey?"✓":"✗")),console.log(" Kalshi: "+(process.env.KALSHI_API_KEY_ID?"✓":"✗")),console.log(" OpenRouter: "+(t.openrouterKey?"✓":"✗")),m&&console.log(` Restricted to chat: ${m}`);function $(){for(const e of y.values())clearInterval(e);f.stop();try{r.default.unlinkSync(p)}catch{}}console.log(" Press Ctrl+C to stop.\n"),r.default.mkdirSync(i.default.dirname(p),{recursive:!0}),r.default.writeFileSync(p,String(process.pid)),process.on("uncaughtException",e=>{console.error("[Telegram] Uncaught exception:",e.message)}),process.on("unhandledRejection",e=>{console.error("[Telegram] Unhandled rejection:",e?.message||e)}),process.on("SIGINT",()=>{$(),process.exit(0)}),process.on("SIGTERM",()=>{$(),process.exit(0)}),process.on("exit",()=>{try{r.default.unlinkSync(p)}catch{}});for(let e=0;e<=5;e++)try{await f.start({onStart:()=>console.log("[Telegram] Polling started successfully")});break}catch(t){if((t?.message?.includes("409")||409===t?.error_code)&&e<5){const t=5*(e+1);console.error(`[Telegram] 409 conflict — retrying in ${t}s (${e+1}/5)`),await new Promise(e=>setTimeout(e,1e3*t));continue}console.error(`[Telegram] Fatal: ${t.message}`),$(),process.exit(1)}};const n=s(53278),r=a(s(79896)),i=a(s(16928)),o=a(s(70857)),c=s(19218),l=s(11627),d=s(76342),h=s(77499),u=s(55875),p=i.default.join(o.default.homedir(),".sf","telegram.pid"),f=new Map;function g(e){return f.has(e)||f.set(e,{thesisId:null,agentMessages:[]}),f.get(e)}},77499:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.handleContext=async function(e,t){const s=await e.getContext(t),a="number"==typeof s.confidence?Math.round(100*s.confidence):"?",r=s.thesis||s.rawThesis||"N/A";let i=`📋 <b>${(0,n.escapeHtml)(r.slice(0,80))}</b>\n`;i+=`Confidence: <b>${a}%</b> | Status: ${s.status}\n\n`;const o=(s.edges||[]).slice(0,8);if(o.length>0){i+="<b>Top Edges:</b>\n<pre>";for(const e of o){i+=`${(e.market||e.marketTitle||"???").slice(0,35).padEnd(36)} ${String(e.edge||0).padStart(3)}¢ ${e.direction||"yes"}\n`}i+="</pre>"}return i},t.handlePositions=async function(){if(!(0,a.isKalshiConfigured)())return"⚠️ Kalshi not configured. Run <code>sf setup --kalshi</code>";const e=await(0,a.getPositions)();if(!e||0===e.length)return"No open positions.";let t=0;const s=[];for(const r of e){const e=await(0,a.getMarketPrice)(r.ticker)??r.average_price_paid,i=(e-r.average_price_paid)*r.quantity;t+=i;const o=(0,n.fmtDollar)(i);s.push(`${r.ticker.slice(0,28).padEnd(29)} ${String(r.quantity).padStart(5)} ${String(r.average_price_paid).padStart(3)}¢→${String(e).padStart(3)}¢ ${o}`)}let r="📊 <b>Positions</b>\n<pre>";return r+=s.join("\n"),r+=`\n${"─".repeat(50)}\nTotal P&L: ${(0,n.fmtDollar)(t)}`,r+="</pre>",r},t.handleEdges=async function(e){const{theses:t}=await e.listTheses(),s=(t||[]).filter(e=>"active"===e.status),a=await Promise.allSettled(s.map(async t=>((await e.getContext(t.id)).edges||[]).map(e=>({...e,thesisId:t.id})))),n=[];for(const e of a)"fulfilled"===e.status&&n.push(...e.value);n.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0));const r=n.slice(0,10);if(0===r.length)return"No edges found.";let i="📈 <b>Top Edges</b>\n<pre>";for(const e of r){const t=(e.market||"???").slice(0,35),s=e.orderbook?.liquidityScore||"?";i+=`${t.padEnd(36)} +${String(e.edge||0).padStart(2)}¢ ${s}\n`}return i+="</pre>",i},t.handleBalance=async function(){if(!(0,a.isKalshiConfigured)())return"⚠️ Kalshi not configured.";const e=await(0,a.getBalance)();return e?`💰 Balance: <b>$${e.balance.toFixed(2)}</b> | Portfolio: <b>$${e.portfolioValue.toFixed(2)}</b>`:"⚠️ Failed to fetch balance."},t.handleOrders=async function(){if(!(0,a.isKalshiConfigured)())return"⚠️ Kalshi not configured.";const e=await(0,a.getOrders)({status:"resting",limit:20});if(!e||!e.orders||0===e.orders.length)return"No resting orders.";let t="📋 <b>Resting Orders</b>\n<pre>";for(const s of e.orders){const e=Math.round(parseFloat(s.remaining_count_fp||"0")),a=Math.round(100*parseFloat(s.yes_price_dollars||"0")),n=(s.ticker||"???").slice(0,25);t+=`${s.action} ${e}x ${n} @ ${a}¢\n`}return t+="</pre>",t},t.handleEval=async function(e,t){return await e.evaluate(t),"⚡ Evaluation triggered. Results in ~2 minutes."},t.handleList=async function(e){const{theses:t}=await e.listTheses();if(!t||0===t.length)return"No theses.";let s="📝 <b>Theses</b>\n<pre>";for(const e of t){const t="number"==typeof e.confidence?Math.round(100*e.confidence):0,a=(e.rawThesis||e.thesis||"").slice(0,50);s+=`${e.id.slice(0,8)} ${String(t).padStart(3)}% ${e.status.padEnd(8)} ${a}\n`}return s+="</pre>",s};const a=s(96139),n=s(76342)},76342:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.splitMessage=function(e,t=4e3){if(e.length<=t)return[e];const s=[];let a=e;for(;a.length>0;){if(a.length<=t){s.push(a);break}let e=a.lastIndexOf("\n",t);e<.5*t&&(e=t),s.push(a.slice(0,e)),a=a.slice(e)}return s},t.fmtDollar=function(e){const t=e/100;return t>=0?`+$${t.toFixed(2)}`:`-$${Math.abs(t).toFixed(2)}`},t.sparkline=function(e){if(0===e.length)return"";const t=Math.min(...e),s=Math.max(...e)-t||1;return e.map(e=>"▁▂▃▄▅▆▇█"[Math.round((e-t)/s*7)]).join("")},t.escapeHtml=function(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}},55875:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.startPoller=function(e,t,s,n){let r=(new Date).toISOString();return setInterval(async()=>{try{const i=await s.getChanges(n,r);if(r=(new Date).toISOString(),!i||!i.changed)return;const o=i.confidenceDelta??i.delta??0;if(Math.abs(o)<.02)return;const c="number"==typeof i.confidence?Math.round(100*i.confidence):"?",l=o>0?"📈":"📉",d=o>0?"+":"",h=i.summary||i.latestSummary||"";let u=`${l} <b>Confidence ${d}${Math.round(100*o)}% → ${c}%</b>\n`;h&&(u+=`${(0,a.escapeHtml)(h.slice(0,200))}`),await e.api.sendMessage(t,u,{parse_mode:"HTML"})}catch{}},6e4)};const a=s(76342)}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.id=563,exports.ids=[563],exports.modules={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,r.join)(i,`.${t}.tmp`),l=(0,r.join)(i,`${t}.json`);return(0,o.writeFileSync)(s,JSON.stringify(n)),(0,o.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,o.readdirSync)(n))if(t.endsWith(".json"))try{const s=JSON.parse((0,o.readFileSync)((0,r.join)(n,t),"utf-8"));if((a-new Date(s.ts).getTime())/1e3>s.ttl){try{(0,o.unlinkSync)((0,r.join)(n,t))}catch{}continue}s.to!==e&&"all"!==s.to||i.push(s)}catch{try{(0,o.unlinkSync)((0,r.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,r.join)(n,`${e}.json`);try{const e=JSON.parse((0,o.readFileSync)(i,"utf-8"));e.read=!0,(0,o.writeFileSync)(i,JSON.stringify(e))}catch{}},t.deleteMessage=function(e,t){const n="inbox"===t?c:u;try{(0,o.unlinkSync)((0,r.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,o.readdirSync)(t))if(i.endsWith(".json"))try{const a=JSON.parse((0,o.readFileSync)((0,r.join)(t,i),"utf-8"));(n-new Date(a.ts).getTime())/1e3>a.ttl&&((0,o.unlinkSync)((0,r.join)(t,i)),e++)}catch{try{(0,o.unlinkSync)((0,r.join)(t,i))}catch{}e++}}return e};const o=n(79896),r=n(16928),i=n(70857),a=n(76982),s=(0,r.join)((0,i.homedir)(),".sf","bus"),c=(0,r.join)(s,"inbox"),u=(0,r.join)(s,"outbox");function d(e){(0,o.mkdirSync)(e,{recursive:!0})}},9563:(e,t,n)=>{t.evaluateWakeConditions=t.saveWakeCondition=t.periodicScan=t.evaluateSoftCondition=t.writeAgentHeartbeat=t.deleteMessage=t.readMessages=t.writeMessage=void 0;var o=n(32849);Object.defineProperty(t,"writeMessage",{enumerable:!0,get:function(){return o.writeMessage}}),Object.defineProperty(t,"readMessages",{enumerable:!0,get:function(){return o.readMessages}}),Object.defineProperty(t,"deleteMessage",{enumerable:!0,get:function(){return o.deleteMessage}});var r=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}})},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 p=t.apiUrl||"https://simplefunctions.dev",f=e.model||t.smartModel||c,m=e.maxTokens||d,y=e.timeoutMs||u;if(!function(e){const t=e??1;if(t<=0)return!1;try{const e=(0,o.readFileSync)(s,"utf-8").trim().split("\n"),n=Date.now()-2592e6;let r=0;for(const t of e)try{const e=JSON.parse(t);new Date(e.ts).getTime()>n&&(r+=e.costUsd)}catch{}return r<t}catch{return!0}}(t.smartBudgetUsd))return null;try{const t=new AbortController,a=setTimeout(()=>t.abort(),y),c=await fetch(`${p}/api/proxy/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({model:f,messages:[{role:"system",content:e.systemPrompt},{role:"user",content:e.userContent}],max_tokens:m,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[f]||{input:1,output:3},C=(g*h.input+S*h.output)/1e6;return function(e){try{(0,o.mkdirSync)((0,r.join)((0,i.homedir)(),".sf","bus","cost"),{recursive:!0}),(0,o.appendFileSync)(s,JSON.stringify(e)+"\n")}catch{}}({ts:(new Date).toISOString(),daemon:e.daemon,type:e.callType,model:f,inputTokens:g,outputTokens:S,costUsd:C,intentId:e.intentId}),{text:d,usage:{input:g,output:S,costUsd:C}}}catch{return null}},t.getMonthlySpend=function(){try{const e=(0,o.readFileSync)(s,"utf-8").trim().split("\n"),t=Date.now()-2592e6;let n=0;for(const o of e)try{const e=JSON.parse(o);new Date(e.ts).getTime()>t&&(n+=e.costUsd)}catch{}return n}catch{return 0}};const o=n(79896),r=n(16928),i=n(70857),a=n(11627),s=(0,r.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,o.mkdirSync)((0,r.dirname)(a),{recursive:!0});const t={pid:process.pid,ts:(new Date).toISOString(),thesisId:e};(0,o.writeFileSync)(a,JSON.stringify(t))}catch{}},t.isAgentActive=function(e=120){try{const t=JSON.parse((0,o.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,o.readFileSync)(a,"utf-8"))}catch{return null}};const o=n(79896),r=n(16928),i=n(70857),a=(0,r.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,o.getMarketPrice)(e.marketId);let n="";try{const t=await(0,o.getPublicOrderbook)(e.marketId,5);if(t){const e=t.yes_dollars||[],o=t.no_dollars||[],r=e.length>0?Math.round(100*parseFloat(e[0][0])):0,i=o.length>0?100-Math.round(100*parseFloat(o[0][0])):100,a=i-r,s=e.slice(0,3).reduce((e,t)=>e+parseFloat(t[1]),0),c=o.slice(0,3).reduce((e,t)=>e+parseFloat(t[1]),0);n=`Orderbook: bid ${r}c ($${Math.round(s)}), ask ${i}c ($${Math.round(c)}), spread ${a}c`}}catch{}const i=await(0,r.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 o=t.map(e=>{const t=n.get(e.marketId),o=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: ${o}${e.softCondition?` | soft: "${e.softCondition}"`:""}`}).join("\n"),a=await(0,r.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${o}`,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 o=n(96139),r=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 o=d();for(const r of o){if(await p(r,e,t,n)){r.firedCount++,r.lastFiredAt=(new Date).toISOString(),l(r);for(const t of r.alertChannels)"bus"===t&&(0,c.writeMessage)({from:e,to:"agent",type:"alert",priority:r.priority,payload:{summary:`Wake condition fired: ${r.description}`,wakeConditionId:r.id},ttl:7200})}}};const o=n(79896),r=n(16928),i=n(70857),a=n(96139),s=n(42340),c=n(32849),u=(0,r.join)((0,i.homedir)(),".sf","bus","wake");function d(){try{(0,o.mkdirSync)(u,{recursive:!0});const e=[];for(const t of(0,o.readdirSync)(u))if(t.endsWith(".json"))try{const n=JSON.parse((0,o.readFileSync)((0,r.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,o.mkdirSync)(u,{recursive:!0}),(0,o.writeFileSync)((0,r.join)(u,`${e.id}.json`),JSON.stringify(e,null,2))}async function p(e,t,n,o){switch(e.type){case"price":{if(!e.priceCondition)return!1;const t=o?.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 r=e.llmCondition.checkIntervalCycles||10;if(n%r!==0)return!1;const i=[];if(e.llmCondition.dataNeeded.includes("prices")&&o)for(const[e,t]of o)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 r=await Promise.all(e.compoundCondition.conditions.map(e=>p(e,t,n,o)));return"and"===e.compoundCondition.operator?r.every(Boolean):r.some(Boolean)}default:return!1}}}};
|