@spfunctions/cli 1.7.29 → 1.7.30
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/160.index.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/160.index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.id=160,exports.ids=[160],exports.modules={28160:(e,t,n)=>{t.runAgentMessage=async function(e,t,n){const s=await r(e,t);return new Promise((e,i)=>{let a="",r="";const o=setTimeout(()=>{e(a||r||"Response timeout (45s). Try a simpler question.")},45e3),l=s.subscribe(n=>{if("message_update"===n.type){const e=n.assistantMessageEvent;"text_delta"===e.type&&(a+=e.delta)}"tool_execution_start"===n.type&&(r+=`⚡ ${n.toolName}\n`),"agent_end"===n.type&&(clearTimeout(o),l?.(),t.agentMessages=s.state.messages||[],e(a||r||"(no response)"))});s.prompt(n).catch(e=>{clearTimeout(o),l?.(),i(e)})})};const s=n(11627);let i=null;async function a(){if(i)return i;const[e,t]=await Promise.all([Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653)),Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641))]),s=await Promise.all([n.e(788),n.e(722)]).then(n.bind(n,85722));return i={Agent:e.Agent,streamSimple:t.streamSimple,Type:s.Type},i}async function r(e,t){if(t.agent)return t.agent;const{Agent:i,streamSimple:r}=await a(),o=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),{getModel:l}=o,c=(0,s.loadConfig)(),d=c.openrouterKey||process.env.OPENROUTER_API_KEY,u=c.apiKey||process.env.SF_API_KEY,p=c.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev",m=!d&&!!u,g=d||u;if(!g)throw new Error("Need API key. Run sf login or sf setup.");const h=await e.getContext(t.thesisId),y="number"==typeof h.confidence?Math.round(100*h.confidence):50,x=await async function(e,t,i){const{Type:r}=await a(),o=(0,s.loadConfig)(),l=r.Object({}),c=await Promise.resolve().then(n.t.bind(n,96139,23)),{kalshiFetchAllSeries:d,kalshiFetchMarketsBySeries:u,kalshiFetchMarket:p}=await Promise.resolve().then(n.bind(n,19218)),m=[{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:r.Object({q:r.String({description:"Question"})}),execute:async(e,t)=>{const{fetchQuery:s}=await Promise.resolve().then(n.bind(n,19218)),i=await s(t.q);return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"get_markets",label:"Markets",description:"Traditional market prices: SPY, VIX, Treasury, Gold, Oil.",parameters:l,execute:async()=>{const{fetchTraditionalMarkets:e}=await Promise.resolve().then(n.bind(n,19218)),t=await e();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"inject_signal",label:"Signal",description:"Inject a signal (news, note, observation) into the thesis",parameters:r.Object({content:r.String({description:"Signal content"}),type:r.Optional(r.String({description:"news | user_note | external"}))}),execute:async(n,s)=>(await e.injectSignal(t,s.type||"user_note",s.content,"telegram"),{content:[{type:"text",text:"Signal injected."}],details:{}})},{name:"trigger_evaluation",label:"Evaluate",description:"Trigger a deep evaluation cycle",parameters:l,execute:async()=>(await e.evaluate(t),{content:[{type:"text",text:"Evaluation triggered. Results in ~2 minutes."}],details:{}})},{name:"scan_markets",label:"Scan",description:"Search Kalshi markets by keyword, series, or ticker",parameters:r.Object({query:r.Optional(r.String({description:"Keyword search"})),series:r.Optional(r.String({description:"Series ticker"})),market:r.Optional(r.String({description:"Market ticker"}))}),execute:async(e,t)=>{let n;if(t.market)n=await p(t.market);else if(t.series)n=await u(t.series);else if(t.query){const e=await d(),s=t.query.toLowerCase().split(/\s+/);n=e.filter(e=>s.every(t=>((e.title||"")+(e.ticker||"")).toLowerCase().includes(t))).filter(e=>parseFloat(e.volume_fp||"0")>1e3).sort((e,t)=>parseFloat(t.volume_fp||"0")-parseFloat(e.volume_fp||"0")).slice(0,10)}else n={error:"Provide query, series, or market"};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"list_theses",label:"List",description:"List all theses",parameters:l,execute:async()=>{const t=await e.listTheses();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_positions",label:"Positions",description:"Get Kalshi positions with live prices and P&L",parameters:l,execute:async()=>{const e=await c.getPositions();if(!e)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};for(const t of e){const e=await c.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 c.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 c.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:r.Object({ticker:r.Optional(r.String())}),execute:async(e,t)=>{const n=await c.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 c.getSettlements({limit:50});return e?{content:[{type:"text",text:JSON.stringify(e.settlements,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_edges",label:"Edges",description:"Top 10 edges across all active theses",parameters:l,execute:async()=>{const{theses:t}=await e.listTheses(),n=(t||[]).filter(e=>"active"===e.status),s=await Promise.allSettled(n.map(async t=>((await e.getContext(t.id)).edges||[]).map(e=>({...e,thesisId:t.id})))),i=[];for(const e of s)"fulfilled"===e.status&&i.push(...e.value);return i.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0)),{content:[{type:"text",text:JSON.stringify(i.slice(0,10),null,2)}],details:{}}}},{name:"get_schedule",label:"Schedule",description:"Exchange status (open/closed) and trading hours",parameters:l,execute:async()=>{const e=await fetch("https://api.elections.kalshi.com/trade-api/v2/exchange/status",{headers:{Accept:"application/json"}});if(!e.ok)return{content:[{type:"text",text:`API error: ${e.status}`}],details:{}};const t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_feed",label:"Feed",description:"Recent evaluation history",parameters:r.Object({hours:r.Optional(r.Number({description:"Hours of history (default 24)"}))}),execute:async(t,n)=>{const s=await e.getFeed(n.hours||24);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"web_search",label:"Search",description:"Search the web for latest news",parameters:r.Object({query:r.String({description:"Search query"})}),execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY||o.tavilyKey,s=o.apiKey||process.env.SF_API_KEY,i=o.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev";if(!n&&(n||!s))return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let a;if(a=n?await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}):await fetch(`${i}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}),!a.ok)return{content:[{type:"text",text:`Search failed: ${a.status}`}],details:{}};const r=await a.json();return{content:[{type:"text",text:`${r.answer?`Summary: ${r.answer}\n\n`:""}${(r.results||[]).map(e=>`${e.title}: ${(e.content||"").slice(0,150)}`).join("\n\n")}`}],details:{}}}},{name:"create_thesis",label:"Create",description:"Create a new thesis",parameters:r.Object({rawThesis:r.String({description:"Thesis statement"})}),execute:async(t,n)=>{const s=await e.createThesis(n.rawThesis,!0);return{content:[{type:"text",text:`Created: ${s.id}\nConfidence: ${Math.round(100*(s.confidence||.5))}%`}],details:{}}}},{name:"what_if",label:"What-If",description:"Override causal tree node probabilities and see how edges change. Zero LLM cost.",parameters:r.Object({overrides:r.Array(r.Object({nodeId:r.String({description:"Node ID (e.g. n1, n3.1)"}),newProbability:r.Number({description:"New probability 0-1"})}))}),execute:async(e,t)=>{const n=i,s=[];!function e(t){for(const n of t)s.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 s)a.has(e.id)&&(e.probability=a.get(e.id));const l=r.reduce((e,t)=>e+(t.probability||.5),0)/Math.max(r.length,1),c=(n?.edges||[]).slice(0,10).map(e=>{const t=s.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),i=Math.round(e.thesisPrice*n)-e.marketPrice;return{market:e.market,oldEdge:e.edge,newEdge:i,signal:Math.abs(i-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*l)},edges:c},null,2)}],details:{}}}}];return m.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:r.Object({query:r.String({description:"Search query"}),mode:r.Optional(r.String({description:'"summary" or "raw"'})),hours:r.Optional(r.Number({description:"Hours (default 24)"}))}),execute:async(t,n)=>{const s=await e.searchX(n.query,{mode:n.mode,hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_volume",label:"X Volume",description:"X discussion volume trend — total posts, velocity, peak time.",parameters:r.Object({query:r.String({description:"Search query"}),hours:r.Optional(r.Number({description:"Hours (default 72)"}))}),execute:async(t,n)=>{const s=await e.getXVolume(n.query,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_news",label:"X News",description:"News stories trending on X — titles, summaries, tickers.",parameters:r.Object({query:r.String({description:"Search query"}),limit:r.Optional(r.Number({description:"Max stories (default 10)"}))}),execute:async(t,n)=>{const s=await e.searchXNews(n.query,{limit:n.limit});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_account",label:"X Account",description:"Recent posts from a specific X account.",parameters:r.Object({username:r.String({description:"X username (with or without @)"}),hours:r.Optional(r.Number({description:"Hours (default 24)"}))}),execute:async(t,n)=>{const s=await e.getXAccount(n.username,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"heartbeat_config",label:"Heartbeat Config",description:"View or update heartbeat settings: scan intervals, model tier, budget cap, pause/resume. Shows cost breakdown.",parameters:r.Object({thesisId:r.String({description:"Thesis ID"}),newsIntervalMin:r.Optional(r.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:r.Optional(r.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:r.Optional(r.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:r.Optional(r.Number({description:"Monthly budget (0 = unlimited)"})),paused:r.Optional(r.Boolean({description:"Pause or resume heartbeat"}))}),execute:async(t,n)=>{if(n.newsIntervalMin||n.xIntervalMin||n.evalModelTier||void 0!==n.monthlyBudgetUsd||void 0!==n.paused){const t={};n.newsIntervalMin&&(t.newsIntervalMin=n.newsIntervalMin),n.xIntervalMin&&(t.xIntervalMin=n.xIntervalMin),n.evalModelTier&&(t.evalModelTier=n.evalModelTier),void 0!==n.monthlyBudgetUsd&&(t.monthlyBudgetUsd=n.monthlyBudgetUsd),void 0!==n.paused&&(t.paused=n.paused),await e.updateHeartbeatConfig(n.thesisId,t)}const s=await e.getHeartbeatConfig(n.thesisId);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}}),o.tradingEnabled&&m.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:r.Object({ticker:r.String({description:"Market ticker (e.g. KXWTIMAX-26DEC31-T135)"}),side:r.String({description:"yes or no"}),action:r.String({description:"buy or sell"}),count:r.Number({description:"Number of contracts"}),yes_price:r.Number({description:"Price in cents (1-99)"})}),execute:async(e,t)=>{try{const e=await c.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:r.Object({orderId:r.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{try{return await c.cancelOrder(t.orderId),{content:[{type:"text",text:`✓ Order ${t.orderId} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`✗ Cancel failed: ${e.message}`}],details:{}}}}}),m}(e,t.thesisId,h),f=c.model||"anthropic/claude-sonnet-4.6";let b;try{b=l("openrouter",f)}catch{b={modelId:f,provider:"openrouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",id:f,name:f,inputPrice:0,outputPrice:0,contextWindow:2e5,supportsImages:!0,supportsTools:!0}}m&&(b.baseUrl=`${p}/api/proxy`);const w=(h.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)",v=(h.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)",S=new i({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- You don't know user's positions. Call get_positions before discussing trades.\n- If user mentions news, inject_signal immediately. Don't ask "should I?"\n- If user says "evaluate" or "run it", trigger immediately.\n- Don't end with "anything else?" — user will ask.\n- Use Chinese if user writes Chinese, English if English.\n${c.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: ${(h.thesis||h.rawThesis||"N/A").slice(0,200)}\nID: ${t.thesisId.slice(0,8)} | Confidence: ${y}%\n\nCausal nodes:\n${v}\n\nTop edges:\n${w}\n\n${h.lastEvaluation?.summary?`Latest eval: ${h.lastEvaluation.summary.slice(0,200)}`:""}`,model:b,tools:x,thinkingLevel:"off"},streamFn:r,getApiKey:e=>"openrouter"===e?g:void 0});if(t.agentMessages.length>0)try{S.replaceMessages(t.agentMessages)}catch{}return t.agent=S,S}}};
|
|
1
|
+
"use strict";exports.id=160,exports.ids=[160],exports.modules={28160:(e,t,n)=>{t.runAgentMessage=async function(e,t,n){const i=await r(e,t);return new Promise((e,s)=>{let a="",r="";const o=setTimeout(()=>{e(a||r||"Response timeout (45s). Try a simpler question.")},45e3),c=i.subscribe(n=>{if("message_update"===n.type){const e=n.assistantMessageEvent;"text_delta"===e.type&&(a+=e.delta)}"tool_execution_start"===n.type&&(r+=`⚡ ${n.toolName}\n`),"agent_end"===n.type&&(clearTimeout(o),c?.(),t.agentMessages=i.state.messages||[],e(a||r||"(no response)"))});i.prompt(n).catch(e=>{clearTimeout(o),c?.(),s(e)})})};const i=n(11627);let s=null;async function a(){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 r(e,t){if(t.agent)return t.agent;const{Agent:s,streamSimple:r}=await a(),o=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),{getModel:c}=o,l=(0,i.loadConfig)(),d=l.openrouterKey||process.env.OPENROUTER_API_KEY,p=l.apiKey||process.env.SF_API_KEY,u=l.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev",m=!d&&!!p,h=d||p;if(!h)throw new Error("Need API key. Run sf login or sf setup.");const g=await e.getContext(t.thesisId),y="number"==typeof g.confidence?Math.round(100*g.confidence):50,f=await async function(e,t,s){const{Type:r}=await a(),o=(0,i.loadConfig)(),c=r.Object({}),l=await Promise.resolve().then(n.t.bind(n,96139,23)),{kalshiFetchAllSeries:d,kalshiFetchMarketsBySeries:p,kalshiFetchMarket:u}=await Promise.resolve().then(n.bind(n,19218)),m=[{name:"get_context",label:"Context",description:"Get thesis snapshot with causal tree, edges, evaluation",parameters:c,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:c,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:r.Object({q:r.String({description:"Question"})}),execute:async(e,t)=>{const{fetchQuery:i}=await Promise.resolve().then(n.bind(n,19218)),s=await i(t.q);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"get_markets",label:"Markets",description:"Traditional market prices: SPY, VIX, Treasury, Gold, Oil.",parameters:c,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:r.Object({content:r.String({description:"Signal content"}),type:r.Optional(r.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:c,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:r.Object({query:r.Optional(r.String({description:"Keyword search"})),series:r.Optional(r.String({description:"Series ticker"})),market:r.Optional(r.String({description:"Market ticker"}))}),execute:async(e,t)=>{let n;if(t.market)n=await u(t.market);else if(t.series)n=await p(t.series);else if(t.query){const e=await d(),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:c,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:c,execute:async()=>{const e=await l.getPositions();if(!e)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};for(const t of e){const e=await l.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:c,execute:async()=>{const e=await l.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:c,execute:async()=>{const e=await l.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:r.Object({ticker:r.Optional(r.String())}),execute:async(e,t)=>{const n=await l.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:c,execute:async()=>{const e=await l.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:c,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})))),s=[];for(const e of i)"fulfilled"===e.status&&s.push(...e.value);return s.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0)),{content:[{type:"text",text:JSON.stringify(s.slice(0,10),null,2)}],details:{}}}},{name:"get_schedule",label:"Schedule",description:"Exchange status (open/closed) and trading hours",parameters:c,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:r.Object({hours:r.Optional(r.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:r.Object({query:r.String({description:"Search query"})}),execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY||o.tavilyKey,i=o.apiKey||process.env.SF_API_KEY,s=o.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 a;if(a=n?await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}):await fetch(`${s}/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})}),!a.ok)return{content:[{type:"text",text:`Search failed: ${a.status}`}],details:{}};const r=await a.json();return{content:[{type:"text",text:`${r.answer?`Summary: ${r.answer}\n\n`:""}${(r.results||[]).map(e=>`${e.title}: ${(e.content||"").slice(0,150)}`).join("\n\n")}`}],details:{}}}},{name:"create_thesis",label:"Create",description:"Create a new thesis",parameters:r.Object({rawThesis:r.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:r.Object({overrides:r.Array(r.Object({nodeId:r.String({description:"Node ID (e.g. n1, n3.1)"}),newProbability:r.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:{}}}}];m.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:r.Object({query:r.String({description:"Search query"}),mode:r.Optional(r.String({description:'"summary" or "raw"'})),hours:r.Optional(r.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:r.Object({query:r.String({description:"Search query"}),hours:r.Optional(r.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:r.Object({query:r.String({description:"Search query"}),limit:r.Optional(r.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:r.Object({username:r.String({description:"X username (with or without @)"}),hours:r.Optional(r.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:r.Object({thesisId:r.String({description:"Thesis ID"}),newsIntervalMin:r.Optional(r.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:r.Optional(r.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:r.Optional(r.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:r.Optional(r.Number({description:"Monthly budget (0 = unlimited)"})),paused:r.Optional(r.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||o.apiUrl||"https://simplefunctions.dev";return m.push({name:"get_world_state",label:"World",description:"Real-time world model (~800 tokens). Geopolitics, economy, energy, elections, crypto, tech.",parameters:r.Object({focus:r.Optional(r.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:r.Object({sourceAction:r.String({description:"scrape|crawl|search|map|extract"}),url:r.Optional(r.String()),query:r.Optional(r.String()),topics:r.Optional(r.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)}),s=await i.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"enrich_content",label:"Enrich",description:"Cross-reference any text with 9,706 prediction markets. Returns divergences.",parameters:r.Object({content:r.String({description:"Text to cross-reference"}),topics:r.Optional(r.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)}),s=await i.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"create_skill",label:"Create Skill",description:"Create a custom agent skill.",parameters:r.Object({name:r.String(),trigger:r.String(),description:r.String(),prompt:r.String(),category:r.Optional(r.String())}),execute:async(e,t)=>{const n=await fetch(`${h}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.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:c,execute:async()=>{const e=await fetch(`${h}/api/skill`,{headers:{Authorization:`Bearer ${o.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:r.Object({q:r.Optional(r.String()),sort:r.Optional(r.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}`),s=await i.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"fork_skill",label:"Fork Skill",description:"Fork a public skill into your collection.",parameters:r.Object({skillId:r.String()}),execute:async(e,t)=>{const n=await fetch(`${h}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${o.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:r.Object({slug:r.String()}),execute:async(e,t)=>{const n=await fetch(`${h}/api/thesis/${t.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${o.apiKey}`}}),i=await n.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}}),o.tradingEnabled&&m.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:r.Object({ticker:r.String({description:"Market ticker (e.g. KXWTIMAX-26DEC31-T135)"}),side:r.String({description:"yes or no"}),action:r.String({description:"buy or sell"}),count:r.Number({description:"Number of contracts"}),yes_price:r.Number({description:"Price in cents (1-99)"})}),execute:async(e,t)=>{try{const e=await l.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:r.Object({orderId:r.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{try{return await l.cancelOrder(t.orderId),{content:[{type:"text",text:`✓ Order ${t.orderId} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`✗ Cancel failed: ${e.message}`}],details:{}}}}}),m}(e,t.thesisId,g),x=l.model||"anthropic/claude-sonnet-4.6";let b;try{b=c("openrouter",x)}catch{b={modelId:x,provider:"openrouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",id:x,name:x,inputPrice:0,outputPrice:0,contextWindow:2e5,supportsImages:!0,supportsTools:!0}}m&&(b.baseUrl=`${u}/api/proxy`);const w=(g.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)",S=(g.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)",k=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- You don't know user's positions. Call get_positions before discussing trades.\n- If user mentions news, inject_signal immediately. Don't ask "should I?"\n- If user says "evaluate" or "run it", trigger immediately.\n- Don't end with "anything else?" — user will ask.\n- Use Chinese if user writes Chinese, English if English.\n${l.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: ${(g.thesis||g.rawThesis||"N/A").slice(0,200)}\nID: ${t.thesisId.slice(0,8)} | Confidence: ${y}%\n\nCausal nodes:\n${S}\n\nTop edges:\n${w}\n\n${g.lastEvaluation?.summary?`Latest eval: ${g.lastEvaluation.summary.slice(0,200)}`:""}`,model:b,tools:f,thinkingLevel:"off"},streamFn:r,getApiKey:e=>"openrouter"===e?h:void 0});if(t.agentMessages.length>0)try{k.replaceMessages(t.agentMessages)}catch{}return t.agent=k,k}}};
|