@spfunctions/cli 1.7.36 → 1.7.37
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/101.index.js +451 -1
- package/dist/12.index.js +536 -1
- package/dist/160.index.js +709 -1
- package/dist/174.index.js +44 -1
- package/dist/278.index.js +15129 -2
- package/dist/582.index.js +1066 -1
- package/dist/641.index.js +122145 -66
- package/dist/669.index.js +556 -1
- package/dist/722.index.js +843 -1
- package/dist/788.index.js +6677 -1
- package/dist/816.index.js +7496 -4
- package/dist/830.index.js +1199 -1
- package/dist/921.index.js +10683 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/160.index.js
CHANGED
|
@@ -1 +1,709 @@
|
|
|
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}}};
|
|
1
|
+
"use strict";
|
|
2
|
+
exports.id = 160;
|
|
3
|
+
exports.ids = [160];
|
|
4
|
+
exports.modules = {
|
|
5
|
+
|
|
6
|
+
/***/ 28160:
|
|
7
|
+
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
|
|
8
|
+
|
|
9
|
+
var __webpack_unused_export__;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Agent bridge — connects Telegram to pi-agent-core
|
|
13
|
+
*
|
|
14
|
+
* Uses the SAME tools as sf agent --plain. Multi-turn tool calling
|
|
15
|
+
* is handled by pi-agent-core's Agent class (not manual OpenRouter calls).
|
|
16
|
+
*/
|
|
17
|
+
__webpack_unused_export__ = ({ value: true });
|
|
18
|
+
__webpack_unused_export__ = getOrCreateAgent;
|
|
19
|
+
exports.runAgentMessage = runAgentMessage;
|
|
20
|
+
const config_js_1 = __webpack_require__(11627);
|
|
21
|
+
let piModules = null;
|
|
22
|
+
async function loadPiModules() {
|
|
23
|
+
if (piModules)
|
|
24
|
+
return piModules;
|
|
25
|
+
const [piAgent, piAi] = await Promise.all([
|
|
26
|
+
Promise.all(/* import() */[__webpack_require__.e(788), __webpack_require__.e(641), __webpack_require__.e(582)]).then(__webpack_require__.bind(__webpack_require__, 65653)),
|
|
27
|
+
Promise.all(/* import() */[__webpack_require__.e(788), __webpack_require__.e(641), __webpack_require__.e(174)]).then(__webpack_require__.bind(__webpack_require__, 99641)),
|
|
28
|
+
]);
|
|
29
|
+
const typebox = await Promise.all(/* import() */[__webpack_require__.e(788), __webpack_require__.e(722)]).then(__webpack_require__.bind(__webpack_require__, 85722));
|
|
30
|
+
piModules = { Agent: piAgent.Agent, streamSimple: piAi.streamSimple, Type: typebox.Type };
|
|
31
|
+
return piModules;
|
|
32
|
+
}
|
|
33
|
+
async function buildTools(sfClient, thesisId, latestContext) {
|
|
34
|
+
const { Type } = await loadPiModules();
|
|
35
|
+
const config = (0, config_js_1.loadConfig)();
|
|
36
|
+
const emptyParams = Type.Object({});
|
|
37
|
+
// Import Kalshi functions
|
|
38
|
+
const kalshi = await Promise.resolve(/* import() */).then(__webpack_require__.t.bind(__webpack_require__, 96139, 23));
|
|
39
|
+
const { kalshiFetchAllSeries, kalshiFetchMarketsBySeries, kalshiFetchMarket } = await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 19218));
|
|
40
|
+
const tools = [
|
|
41
|
+
{
|
|
42
|
+
name: 'get_context', label: 'Context',
|
|
43
|
+
description: 'Get thesis snapshot with causal tree, edges, evaluation',
|
|
44
|
+
parameters: emptyParams,
|
|
45
|
+
execute: async () => {
|
|
46
|
+
const ctx = await sfClient.getContext(thesisId);
|
|
47
|
+
return { content: [{ type: 'text', text: JSON.stringify(ctx, null, 2) }], details: {} };
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
name: 'global_context', label: 'Snapshot',
|
|
52
|
+
description: 'Global market snapshot — movers, expiring, milestones, liquidity, signals. No thesis needed.',
|
|
53
|
+
parameters: emptyParams,
|
|
54
|
+
execute: async () => {
|
|
55
|
+
const { fetchGlobalContext } = await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 19218));
|
|
56
|
+
const data = await fetchGlobalContext();
|
|
57
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
name: 'query', label: 'Query',
|
|
62
|
+
description: 'LLM-enhanced prediction market search. Returns answer, live prices, key factors.',
|
|
63
|
+
parameters: Type.Object({ q: Type.String({ description: 'Question' }) }),
|
|
64
|
+
execute: async (_id, p) => {
|
|
65
|
+
const { fetchQuery } = await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 19218));
|
|
66
|
+
const data = await fetchQuery(p.q);
|
|
67
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
name: 'get_markets', label: 'Markets',
|
|
72
|
+
description: 'Traditional market prices: SPY, VIX, Treasury, Gold, Oil.',
|
|
73
|
+
parameters: emptyParams,
|
|
74
|
+
execute: async () => {
|
|
75
|
+
const { fetchTraditionalMarkets } = await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 19218));
|
|
76
|
+
const data = await fetchTraditionalMarkets();
|
|
77
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
name: 'inject_signal', label: 'Signal',
|
|
82
|
+
description: 'Inject a signal (news, note, observation) into the thesis',
|
|
83
|
+
parameters: Type.Object({
|
|
84
|
+
content: Type.String({ description: 'Signal content' }),
|
|
85
|
+
type: Type.Optional(Type.String({ description: 'news | user_note | external' })),
|
|
86
|
+
}),
|
|
87
|
+
execute: async (_id, p) => {
|
|
88
|
+
await sfClient.injectSignal(thesisId, p.type || 'user_note', p.content, 'telegram');
|
|
89
|
+
return { content: [{ type: 'text', text: 'Signal injected.' }], details: {} };
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
name: 'trigger_evaluation', label: 'Evaluate',
|
|
94
|
+
description: 'Trigger a deep evaluation cycle',
|
|
95
|
+
parameters: emptyParams,
|
|
96
|
+
execute: async () => {
|
|
97
|
+
await sfClient.evaluate(thesisId);
|
|
98
|
+
return { content: [{ type: 'text', text: 'Evaluation triggered. Results in ~2 minutes.' }], details: {} };
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
name: 'scan_markets', label: 'Scan',
|
|
103
|
+
description: 'Search Kalshi markets by keyword, series, or ticker',
|
|
104
|
+
parameters: Type.Object({
|
|
105
|
+
query: Type.Optional(Type.String({ description: 'Keyword search' })),
|
|
106
|
+
series: Type.Optional(Type.String({ description: 'Series ticker' })),
|
|
107
|
+
market: Type.Optional(Type.String({ description: 'Market ticker' })),
|
|
108
|
+
}),
|
|
109
|
+
execute: async (_id, p) => {
|
|
110
|
+
let result;
|
|
111
|
+
if (p.market) {
|
|
112
|
+
result = await kalshiFetchMarket(p.market);
|
|
113
|
+
}
|
|
114
|
+
else if (p.series) {
|
|
115
|
+
result = await kalshiFetchMarketsBySeries(p.series);
|
|
116
|
+
}
|
|
117
|
+
else if (p.query) {
|
|
118
|
+
const series = await kalshiFetchAllSeries();
|
|
119
|
+
const kws = p.query.toLowerCase().split(/\s+/);
|
|
120
|
+
result = series.filter((s) => kws.every((k) => ((s.title || '') + (s.ticker || '')).toLowerCase().includes(k)))
|
|
121
|
+
.filter((s) => parseFloat(s.volume_fp || '0') > 1000)
|
|
122
|
+
.sort((a, b) => parseFloat(b.volume_fp || '0') - parseFloat(a.volume_fp || '0'))
|
|
123
|
+
.slice(0, 10);
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
result = { error: 'Provide query, series, or market' };
|
|
127
|
+
}
|
|
128
|
+
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], details: {} };
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
name: 'list_theses', label: 'List',
|
|
133
|
+
description: 'List all theses',
|
|
134
|
+
parameters: emptyParams,
|
|
135
|
+
execute: async () => {
|
|
136
|
+
const theses = await sfClient.listTheses();
|
|
137
|
+
return { content: [{ type: 'text', text: JSON.stringify(theses, null, 2) }], details: {} };
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
{
|
|
141
|
+
name: 'get_positions', label: 'Positions',
|
|
142
|
+
description: 'Get Kalshi positions with live prices and P&L',
|
|
143
|
+
parameters: emptyParams,
|
|
144
|
+
execute: async () => {
|
|
145
|
+
const positions = await kalshi.getPositions();
|
|
146
|
+
if (!positions)
|
|
147
|
+
return { content: [{ type: 'text', text: 'Kalshi not configured.' }], details: {} };
|
|
148
|
+
for (const pos of positions) {
|
|
149
|
+
const price = await kalshi.getMarketPrice(pos.ticker);
|
|
150
|
+
if (price != null) {
|
|
151
|
+
pos.current_value = price;
|
|
152
|
+
pos.unrealized_pnl = Math.round((price - pos.average_price_paid) * pos.quantity);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const formatted = positions.map((p) => ({
|
|
156
|
+
ticker: p.ticker, qty: p.quantity,
|
|
157
|
+
avg_price: `${p.average_price_paid}¢`, current: `${p.current_value}¢`,
|
|
158
|
+
pnl: `$${((p.unrealized_pnl || 0) / 100).toFixed(2)}`,
|
|
159
|
+
}));
|
|
160
|
+
return { content: [{ type: 'text', text: JSON.stringify(formatted, null, 2) }], details: {} };
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
name: 'get_balance', label: 'Balance',
|
|
165
|
+
description: 'Get Kalshi account balance',
|
|
166
|
+
parameters: emptyParams,
|
|
167
|
+
execute: async () => {
|
|
168
|
+
const bal = await kalshi.getBalance();
|
|
169
|
+
if (!bal)
|
|
170
|
+
return { content: [{ type: 'text', text: 'Kalshi not configured.' }], details: {} };
|
|
171
|
+
return { content: [{ type: 'text', text: JSON.stringify(bal, null, 2) }], details: {} };
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
name: 'get_orders', label: 'Orders',
|
|
176
|
+
description: 'Get resting orders on Kalshi',
|
|
177
|
+
parameters: emptyParams,
|
|
178
|
+
execute: async () => {
|
|
179
|
+
const result = await kalshi.getOrders({ status: 'resting', limit: 50 });
|
|
180
|
+
if (!result)
|
|
181
|
+
return { content: [{ type: 'text', text: 'Kalshi not configured.' }], details: {} };
|
|
182
|
+
return { content: [{ type: 'text', text: JSON.stringify(result.orders, null, 2) }], details: {} };
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
{
|
|
186
|
+
name: 'get_fills', label: 'Fills',
|
|
187
|
+
description: 'Get recent trade fills',
|
|
188
|
+
parameters: Type.Object({ ticker: Type.Optional(Type.String()) }),
|
|
189
|
+
execute: async (_id, p) => {
|
|
190
|
+
const result = await kalshi.getFills({ ticker: p.ticker, limit: 20 });
|
|
191
|
+
if (!result)
|
|
192
|
+
return { content: [{ type: 'text', text: 'Kalshi not configured.' }], details: {} };
|
|
193
|
+
return { content: [{ type: 'text', text: JSON.stringify(result.fills, null, 2) }], details: {} };
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
{
|
|
197
|
+
name: 'get_settlements', label: 'Settlements',
|
|
198
|
+
description: 'Get settled contracts with P&L',
|
|
199
|
+
parameters: emptyParams,
|
|
200
|
+
execute: async () => {
|
|
201
|
+
const result = await kalshi.getSettlements({ limit: 50 });
|
|
202
|
+
if (!result)
|
|
203
|
+
return { content: [{ type: 'text', text: 'Kalshi not configured.' }], details: {} };
|
|
204
|
+
return { content: [{ type: 'text', text: JSON.stringify(result.settlements, null, 2) }], details: {} };
|
|
205
|
+
},
|
|
206
|
+
},
|
|
207
|
+
{
|
|
208
|
+
name: 'get_edges', label: 'Edges',
|
|
209
|
+
description: 'Top 10 edges across all active theses',
|
|
210
|
+
parameters: emptyParams,
|
|
211
|
+
execute: async () => {
|
|
212
|
+
const { theses } = await sfClient.listTheses();
|
|
213
|
+
const active = (theses || []).filter((t) => t.status === 'active');
|
|
214
|
+
const results = await Promise.allSettled(active.map(async (t) => {
|
|
215
|
+
const ctx = await sfClient.getContext(t.id);
|
|
216
|
+
return (ctx.edges || []).map((e) => ({ ...e, thesisId: t.id }));
|
|
217
|
+
}));
|
|
218
|
+
const allEdges = [];
|
|
219
|
+
for (const r of results) {
|
|
220
|
+
if (r.status === 'fulfilled')
|
|
221
|
+
allEdges.push(...r.value);
|
|
222
|
+
}
|
|
223
|
+
allEdges.sort((a, b) => Math.abs(b.edge || 0) - Math.abs(a.edge || 0));
|
|
224
|
+
return { content: [{ type: 'text', text: JSON.stringify(allEdges.slice(0, 10), null, 2) }], details: {} };
|
|
225
|
+
},
|
|
226
|
+
},
|
|
227
|
+
{
|
|
228
|
+
name: 'get_schedule', label: 'Schedule',
|
|
229
|
+
description: 'Exchange status (open/closed) and trading hours',
|
|
230
|
+
parameters: emptyParams,
|
|
231
|
+
execute: async () => {
|
|
232
|
+
const res = await fetch('https://api.elections.kalshi.com/trade-api/v2/exchange/status', { headers: { 'Accept': 'application/json' } });
|
|
233
|
+
if (!res.ok)
|
|
234
|
+
return { content: [{ type: 'text', text: `API error: ${res.status}` }], details: {} };
|
|
235
|
+
const data = await res.json();
|
|
236
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
name: 'get_feed', label: 'Feed',
|
|
241
|
+
description: 'Recent evaluation history',
|
|
242
|
+
parameters: Type.Object({ hours: Type.Optional(Type.Number({ description: 'Hours of history (default 24)' })) }),
|
|
243
|
+
execute: async (_id, p) => {
|
|
244
|
+
const data = await sfClient.getFeed(p.hours || 24);
|
|
245
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
246
|
+
},
|
|
247
|
+
},
|
|
248
|
+
{
|
|
249
|
+
name: 'web_search', label: 'Search',
|
|
250
|
+
description: 'Search the web for latest news',
|
|
251
|
+
parameters: Type.Object({ query: Type.String({ description: 'Search query' }) }),
|
|
252
|
+
execute: async (_id, p) => {
|
|
253
|
+
const tavilyKey = process.env.TAVILY_API_KEY || config.tavilyKey;
|
|
254
|
+
const tgSfKey = config.apiKey || process.env.SF_API_KEY;
|
|
255
|
+
const tgSfUrl = config.apiUrl || process.env.SF_API_URL || 'https://simplefunctions.dev';
|
|
256
|
+
const canProxySearch = !tavilyKey && tgSfKey;
|
|
257
|
+
if (!tavilyKey && !canProxySearch)
|
|
258
|
+
return { content: [{ type: 'text', text: 'Web search not available. Run sf login or set TAVILY_API_KEY.' }], details: {} };
|
|
259
|
+
let res;
|
|
260
|
+
if (tavilyKey) {
|
|
261
|
+
res = await fetch('https://api.tavily.com/search', {
|
|
262
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
263
|
+
body: JSON.stringify({ api_key: tavilyKey, query: p.query, max_results: 3, search_depth: 'basic', include_answer: true }),
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
else {
|
|
267
|
+
res = await fetch(`${tgSfUrl}/api/proxy/search`, {
|
|
268
|
+
method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${tgSfKey}` },
|
|
269
|
+
body: JSON.stringify({ query: p.query, max_results: 3, search_depth: 'basic', include_answer: true }),
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
if (!res.ok)
|
|
273
|
+
return { content: [{ type: 'text', text: `Search failed: ${res.status}` }], details: {} };
|
|
274
|
+
const data = await res.json();
|
|
275
|
+
const answer = data.answer ? `Summary: ${data.answer}\n\n` : '';
|
|
276
|
+
const results = (data.results || []).map((r) => `${r.title}: ${(r.content || '').slice(0, 150)}`).join('\n\n');
|
|
277
|
+
return { content: [{ type: 'text', text: `${answer}${results}` }], details: {} };
|
|
278
|
+
},
|
|
279
|
+
},
|
|
280
|
+
{
|
|
281
|
+
name: 'create_thesis', label: 'Create',
|
|
282
|
+
description: 'Create a new thesis',
|
|
283
|
+
parameters: Type.Object({ rawThesis: Type.String({ description: 'Thesis statement' }) }),
|
|
284
|
+
execute: async (_id, p) => {
|
|
285
|
+
const result = await sfClient.createThesis(p.rawThesis, true);
|
|
286
|
+
return { content: [{ type: 'text', text: `Created: ${result.id}\nConfidence: ${Math.round((result.confidence || 0.5) * 100)}%` }], details: {} };
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
{
|
|
290
|
+
name: 'what_if', label: 'What-If',
|
|
291
|
+
description: 'Override causal tree node probabilities and see how edges change. Zero LLM cost.',
|
|
292
|
+
parameters: Type.Object({
|
|
293
|
+
overrides: Type.Array(Type.Object({
|
|
294
|
+
nodeId: Type.String({ description: 'Node ID (e.g. n1, n3.1)' }),
|
|
295
|
+
newProbability: Type.Number({ description: 'New probability 0-1' }),
|
|
296
|
+
})),
|
|
297
|
+
}),
|
|
298
|
+
execute: async (_id, p) => {
|
|
299
|
+
const ctx = latestContext;
|
|
300
|
+
const allNodes = [];
|
|
301
|
+
function flatten(nodes) { for (const n of nodes) {
|
|
302
|
+
allNodes.push(n);
|
|
303
|
+
if (n.children?.length)
|
|
304
|
+
flatten(n.children);
|
|
305
|
+
} }
|
|
306
|
+
flatten(ctx?.causalTree?.nodes || []);
|
|
307
|
+
const overrideMap = new Map(p.overrides.map((o) => [o.nodeId, o.newProbability]));
|
|
308
|
+
const topNodes = (ctx?.causalTree?.nodes || []).filter((n) => !n.parentId || n.depth === 0);
|
|
309
|
+
const oldConf = topNodes.reduce((s, n) => s + (n.probability || 0.5), 0) / Math.max(topNodes.length, 1);
|
|
310
|
+
for (const n of allNodes) {
|
|
311
|
+
if (overrideMap.has(n.id))
|
|
312
|
+
n.probability = overrideMap.get(n.id);
|
|
313
|
+
}
|
|
314
|
+
const newConf = topNodes.reduce((s, n) => s + (n.probability || 0.5), 0) / Math.max(topNodes.length, 1);
|
|
315
|
+
const edges = (ctx?.edges || []).slice(0, 10).map((e) => {
|
|
316
|
+
const node = allNodes.find((n) => n.id === e.relatedNodeId);
|
|
317
|
+
if (!node || !overrideMap.has(node.id))
|
|
318
|
+
return { market: e.market, oldEdge: e.edge, newEdge: e.edge, signal: 'unchanged' };
|
|
319
|
+
const scale = node.probability / (e.confidence || 0.5);
|
|
320
|
+
const newThesis = Math.round(e.thesisPrice * scale);
|
|
321
|
+
const newEdge = newThesis - e.marketPrice;
|
|
322
|
+
return { market: e.market, oldEdge: e.edge, newEdge, signal: Math.abs(newEdge - e.edge) < 1 ? 'unchanged' : 'changed' };
|
|
323
|
+
}).filter((e) => e.signal !== 'unchanged');
|
|
324
|
+
return { content: [{ type: 'text', text: JSON.stringify({ confidence: { old: Math.round(oldConf * 100), new: Math.round(newConf * 100) }, edges }, null, 2) }], details: {} };
|
|
325
|
+
},
|
|
326
|
+
},
|
|
327
|
+
];
|
|
328
|
+
// ── X (Twitter) tools ──
|
|
329
|
+
tools.push({
|
|
330
|
+
name: 'search_x', label: 'X Search',
|
|
331
|
+
description: 'Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.',
|
|
332
|
+
parameters: Type.Object({
|
|
333
|
+
query: Type.String({ description: 'Search query' }),
|
|
334
|
+
mode: Type.Optional(Type.String({ description: '"summary" or "raw"' })),
|
|
335
|
+
hours: Type.Optional(Type.Number({ description: 'Hours (default 24)' })),
|
|
336
|
+
}),
|
|
337
|
+
execute: async (_id, p) => {
|
|
338
|
+
const data = await sfClient.searchX(p.query, { mode: p.mode, hours: p.hours });
|
|
339
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
340
|
+
},
|
|
341
|
+
}, {
|
|
342
|
+
name: 'x_volume', label: 'X Volume',
|
|
343
|
+
description: 'X discussion volume trend — total posts, velocity, peak time.',
|
|
344
|
+
parameters: Type.Object({
|
|
345
|
+
query: Type.String({ description: 'Search query' }),
|
|
346
|
+
hours: Type.Optional(Type.Number({ description: 'Hours (default 72)' })),
|
|
347
|
+
}),
|
|
348
|
+
execute: async (_id, p) => {
|
|
349
|
+
const data = await sfClient.getXVolume(p.query, { hours: p.hours });
|
|
350
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
351
|
+
},
|
|
352
|
+
}, {
|
|
353
|
+
name: 'x_news', label: 'X News',
|
|
354
|
+
description: 'News stories trending on X — titles, summaries, tickers.',
|
|
355
|
+
parameters: Type.Object({
|
|
356
|
+
query: Type.String({ description: 'Search query' }),
|
|
357
|
+
limit: Type.Optional(Type.Number({ description: 'Max stories (default 10)' })),
|
|
358
|
+
}),
|
|
359
|
+
execute: async (_id, p) => {
|
|
360
|
+
const data = await sfClient.searchXNews(p.query, { limit: p.limit });
|
|
361
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
362
|
+
},
|
|
363
|
+
}, {
|
|
364
|
+
name: 'x_account', label: 'X Account',
|
|
365
|
+
description: 'Recent posts from a specific X account.',
|
|
366
|
+
parameters: Type.Object({
|
|
367
|
+
username: Type.String({ description: 'X username (with or without @)' }),
|
|
368
|
+
hours: Type.Optional(Type.Number({ description: 'Hours (default 24)' })),
|
|
369
|
+
}),
|
|
370
|
+
execute: async (_id, p) => {
|
|
371
|
+
const data = await sfClient.getXAccount(p.username, { hours: p.hours });
|
|
372
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
373
|
+
},
|
|
374
|
+
}, {
|
|
375
|
+
name: 'heartbeat_config', label: 'Heartbeat Config',
|
|
376
|
+
description: 'View or update heartbeat settings: scan intervals, model tier, budget cap, pause/resume. Shows cost breakdown.',
|
|
377
|
+
parameters: Type.Object({
|
|
378
|
+
thesisId: Type.String({ description: 'Thesis ID' }),
|
|
379
|
+
newsIntervalMin: Type.Optional(Type.Number({ description: 'News scan interval (15-1440 min)' })),
|
|
380
|
+
xIntervalMin: Type.Optional(Type.Number({ description: 'X scan interval (60-1440 min)' })),
|
|
381
|
+
evalModelTier: Type.Optional(Type.String({ description: 'cheap, medium, or heavy' })),
|
|
382
|
+
monthlyBudgetUsd: Type.Optional(Type.Number({ description: 'Monthly budget (0 = unlimited)' })),
|
|
383
|
+
paused: Type.Optional(Type.Boolean({ description: 'Pause or resume heartbeat' })),
|
|
384
|
+
}),
|
|
385
|
+
execute: async (_id, p) => {
|
|
386
|
+
const hasUp = p.newsIntervalMin || p.xIntervalMin || p.evalModelTier || p.monthlyBudgetUsd !== undefined || p.paused !== undefined;
|
|
387
|
+
if (hasUp) {
|
|
388
|
+
const u = {};
|
|
389
|
+
if (p.newsIntervalMin)
|
|
390
|
+
u.newsIntervalMin = p.newsIntervalMin;
|
|
391
|
+
if (p.xIntervalMin)
|
|
392
|
+
u.xIntervalMin = p.xIntervalMin;
|
|
393
|
+
if (p.evalModelTier)
|
|
394
|
+
u.evalModelTier = p.evalModelTier;
|
|
395
|
+
if (p.monthlyBudgetUsd !== undefined)
|
|
396
|
+
u.monthlyBudgetUsd = p.monthlyBudgetUsd;
|
|
397
|
+
if (p.paused !== undefined)
|
|
398
|
+
u.paused = p.paused;
|
|
399
|
+
await sfClient.updateHeartbeatConfig(p.thesisId, u);
|
|
400
|
+
}
|
|
401
|
+
const data = await sfClient.getHeartbeatConfig(p.thesisId);
|
|
402
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
403
|
+
},
|
|
404
|
+
});
|
|
405
|
+
// ── Monitor + Skill + Fork tools ──
|
|
406
|
+
const apiUrl = process.env.SF_API_URL || config.apiUrl || 'https://simplefunctions.dev';
|
|
407
|
+
tools.push({
|
|
408
|
+
name: 'get_world_state', label: 'World',
|
|
409
|
+
description: 'Real-time world model (~800 tokens). Geopolitics, economy, energy, elections, crypto, tech.',
|
|
410
|
+
parameters: Type.Object({ focus: Type.Optional(Type.String({ description: 'Comma-separated topics' })) }),
|
|
411
|
+
execute: async (_id, p) => {
|
|
412
|
+
const params = new URLSearchParams();
|
|
413
|
+
if (p.focus)
|
|
414
|
+
params.set('focus', p.focus);
|
|
415
|
+
const res = await fetch(`${apiUrl}/api/agent/world?${params}`);
|
|
416
|
+
const text = await res.text();
|
|
417
|
+
return { content: [{ type: 'text', text }], details: {} };
|
|
418
|
+
},
|
|
419
|
+
}, {
|
|
420
|
+
name: 'monitor_the_situation', label: 'Monitor',
|
|
421
|
+
description: 'Scrape any URL (Firecrawl), analyze with any LLM, cross-reference with 9,706 markets, push to webhook.',
|
|
422
|
+
parameters: Type.Object({
|
|
423
|
+
sourceAction: Type.String({ description: 'scrape|crawl|search|map|extract' }),
|
|
424
|
+
url: Type.Optional(Type.String()),
|
|
425
|
+
query: Type.Optional(Type.String()),
|
|
426
|
+
topics: Type.Optional(Type.String({ description: 'Comma-separated topics for market enrichment' })),
|
|
427
|
+
}),
|
|
428
|
+
execute: async (_id, p) => {
|
|
429
|
+
const body = { source: { action: p.sourceAction } };
|
|
430
|
+
if (p.url)
|
|
431
|
+
body.source.url = p.url;
|
|
432
|
+
if (p.query)
|
|
433
|
+
body.source.query = p.query;
|
|
434
|
+
if (p.topics)
|
|
435
|
+
body.enrich = { enabled: true, topics: p.topics.split(',').map((t) => t.trim()), includeIndex: true };
|
|
436
|
+
const res = await fetch(`${apiUrl}/api/monitor-the-situation`, {
|
|
437
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
|
|
438
|
+
});
|
|
439
|
+
const data = await res.json();
|
|
440
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
441
|
+
},
|
|
442
|
+
}, {
|
|
443
|
+
name: 'enrich_content', label: 'Enrich',
|
|
444
|
+
description: 'Cross-reference any text with 9,706 prediction markets. Returns divergences.',
|
|
445
|
+
parameters: Type.Object({
|
|
446
|
+
content: Type.String({ description: 'Text to cross-reference' }),
|
|
447
|
+
topics: Type.Optional(Type.String({ description: 'Comma-separated topics' })),
|
|
448
|
+
}),
|
|
449
|
+
execute: async (_id, p) => {
|
|
450
|
+
const body = { content: p.content };
|
|
451
|
+
if (p.topics)
|
|
452
|
+
body.topics = p.topics.split(',').map((t) => t.trim());
|
|
453
|
+
else
|
|
454
|
+
body.topics = ['general'];
|
|
455
|
+
const res = await fetch(`${apiUrl}/api/monitor-the-situation/enrich`, {
|
|
456
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
|
|
457
|
+
});
|
|
458
|
+
const data = await res.json();
|
|
459
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
460
|
+
},
|
|
461
|
+
}, {
|
|
462
|
+
name: 'create_skill', label: 'Create Skill',
|
|
463
|
+
description: 'Create a custom agent skill.',
|
|
464
|
+
parameters: Type.Object({
|
|
465
|
+
name: Type.String(), trigger: Type.String(), description: Type.String(), prompt: Type.String(),
|
|
466
|
+
category: Type.Optional(Type.String()),
|
|
467
|
+
}),
|
|
468
|
+
execute: async (_id, p) => {
|
|
469
|
+
const res = await fetch(`${apiUrl}/api/skill`, {
|
|
470
|
+
method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${config.apiKey}` },
|
|
471
|
+
body: JSON.stringify(p),
|
|
472
|
+
});
|
|
473
|
+
const data = await res.json();
|
|
474
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
475
|
+
},
|
|
476
|
+
}, {
|
|
477
|
+
name: 'list_skills', label: 'Skills',
|
|
478
|
+
description: 'List built-in + custom skills.',
|
|
479
|
+
parameters: emptyParams,
|
|
480
|
+
execute: async () => {
|
|
481
|
+
const res = await fetch(`${apiUrl}/api/skill`, { headers: { 'Authorization': `Bearer ${config.apiKey}` } });
|
|
482
|
+
const data = await res.json();
|
|
483
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
484
|
+
},
|
|
485
|
+
}, {
|
|
486
|
+
name: 'browse_public_skills', label: 'Public Skills',
|
|
487
|
+
description: 'Browse community skills.',
|
|
488
|
+
parameters: Type.Object({ q: Type.Optional(Type.String()), sort: Type.Optional(Type.String()) }),
|
|
489
|
+
execute: async (_id, p) => {
|
|
490
|
+
const params = new URLSearchParams();
|
|
491
|
+
if (p.q)
|
|
492
|
+
params.set('q', p.q);
|
|
493
|
+
if (p.sort)
|
|
494
|
+
params.set('sort', p.sort);
|
|
495
|
+
const res = await fetch(`${apiUrl}/api/public/skills?${params}`);
|
|
496
|
+
const data = await res.json();
|
|
497
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
498
|
+
},
|
|
499
|
+
}, {
|
|
500
|
+
name: 'fork_skill', label: 'Fork Skill',
|
|
501
|
+
description: 'Fork a public skill into your collection.',
|
|
502
|
+
parameters: Type.Object({ skillId: Type.String() }),
|
|
503
|
+
execute: async (_id, p) => {
|
|
504
|
+
const res = await fetch(`${apiUrl}/api/skill/${p.skillId}/fork`, {
|
|
505
|
+
method: 'POST', headers: { 'Authorization': `Bearer ${config.apiKey}` },
|
|
506
|
+
});
|
|
507
|
+
const data = await res.json();
|
|
508
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
509
|
+
},
|
|
510
|
+
}, {
|
|
511
|
+
name: 'fork_thesis', label: 'Fork Thesis',
|
|
512
|
+
description: 'Fork a public thesis. Copies thesis + causal tree.',
|
|
513
|
+
parameters: Type.Object({ slug: Type.String() }),
|
|
514
|
+
execute: async (_id, p) => {
|
|
515
|
+
const res = await fetch(`${apiUrl}/api/thesis/${p.slug}/fork`, {
|
|
516
|
+
method: 'POST', headers: { 'Authorization': `Bearer ${config.apiKey}` },
|
|
517
|
+
});
|
|
518
|
+
const data = await res.json();
|
|
519
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], details: {} };
|
|
520
|
+
},
|
|
521
|
+
});
|
|
522
|
+
// Trading tools (only if enabled)
|
|
523
|
+
if (config.tradingEnabled) {
|
|
524
|
+
tools.push({
|
|
525
|
+
name: 'place_order',
|
|
526
|
+
label: 'Place Order',
|
|
527
|
+
description: 'Place a buy or sell order on Kalshi. Requires trading to be enabled. Always confirm with user before placing.',
|
|
528
|
+
parameters: Type.Object({
|
|
529
|
+
ticker: Type.String({ description: 'Market ticker (e.g. KXWTIMAX-26DEC31-T135)' }),
|
|
530
|
+
side: Type.String({ description: 'yes or no' }),
|
|
531
|
+
action: Type.String({ description: 'buy or sell' }),
|
|
532
|
+
count: Type.Number({ description: 'Number of contracts' }),
|
|
533
|
+
yes_price: Type.Number({ description: 'Price in cents (1-99)' }),
|
|
534
|
+
}),
|
|
535
|
+
execute: async (_id, p) => {
|
|
536
|
+
try {
|
|
537
|
+
const result = await kalshi.createOrder({
|
|
538
|
+
ticker: p.ticker,
|
|
539
|
+
side: p.side,
|
|
540
|
+
action: p.action,
|
|
541
|
+
type: 'limit',
|
|
542
|
+
count: p.count,
|
|
543
|
+
yes_price: p.yes_price,
|
|
544
|
+
});
|
|
545
|
+
return { content: [{ type: 'text', text: `✓ Order placed: ${(result.order || result).order_id || 'OK'}\n${p.action.toUpperCase()} ${p.count}x ${p.ticker} ${p.side.toUpperCase()} @ ${p.yes_price}¢` }], details: {} };
|
|
546
|
+
}
|
|
547
|
+
catch (err) {
|
|
548
|
+
return { content: [{ type: 'text', text: `✗ Order failed: ${err.message}` }], details: {} };
|
|
549
|
+
}
|
|
550
|
+
},
|
|
551
|
+
}, {
|
|
552
|
+
name: 'cancel_order',
|
|
553
|
+
label: 'Cancel Order',
|
|
554
|
+
description: 'Cancel a resting order on Kalshi.',
|
|
555
|
+
parameters: Type.Object({
|
|
556
|
+
orderId: Type.String({ description: 'Order ID to cancel' }),
|
|
557
|
+
}),
|
|
558
|
+
execute: async (_id, p) => {
|
|
559
|
+
try {
|
|
560
|
+
await kalshi.cancelOrder(p.orderId);
|
|
561
|
+
return { content: [{ type: 'text', text: `✓ Order ${p.orderId} cancelled.` }], details: {} };
|
|
562
|
+
}
|
|
563
|
+
catch (err) {
|
|
564
|
+
return { content: [{ type: 'text', text: `✗ Cancel failed: ${err.message}` }], details: {} };
|
|
565
|
+
}
|
|
566
|
+
},
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
return tools;
|
|
570
|
+
}
|
|
571
|
+
async function getOrCreateAgent(sfClient, session) {
|
|
572
|
+
if (session.agent)
|
|
573
|
+
return session.agent;
|
|
574
|
+
const { Agent, streamSimple } = await loadPiModules();
|
|
575
|
+
const piAi = await Promise.all(/* import() */[__webpack_require__.e(788), __webpack_require__.e(641), __webpack_require__.e(174)]).then(__webpack_require__.bind(__webpack_require__, 99641));
|
|
576
|
+
const { getModel } = piAi;
|
|
577
|
+
const config = (0, config_js_1.loadConfig)();
|
|
578
|
+
const directOrKey = config.openrouterKey || process.env.OPENROUTER_API_KEY;
|
|
579
|
+
const sfApiKey = config.apiKey || process.env.SF_API_KEY;
|
|
580
|
+
const sfApiUrl = config.apiUrl || process.env.SF_API_URL || 'https://simplefunctions.dev';
|
|
581
|
+
const tgUseProxy = !directOrKey && !!sfApiKey;
|
|
582
|
+
const openrouterKey = directOrKey || sfApiKey;
|
|
583
|
+
if (!openrouterKey)
|
|
584
|
+
throw new Error('Need API key. Run sf login or sf setup.');
|
|
585
|
+
const ctx = await sfClient.getContext(session.thesisId);
|
|
586
|
+
const conf = typeof ctx.confidence === 'number' ? Math.round(ctx.confidence * 100) : 50;
|
|
587
|
+
const tools = await buildTools(sfClient, session.thesisId, ctx);
|
|
588
|
+
// Resolve model object (not just a string — pi-ai needs api/provider/baseUrl)
|
|
589
|
+
const modelName = config.model || 'anthropic/claude-sonnet-4.6';
|
|
590
|
+
let model;
|
|
591
|
+
try {
|
|
592
|
+
model = getModel('openrouter', modelName);
|
|
593
|
+
}
|
|
594
|
+
catch {
|
|
595
|
+
model = {
|
|
596
|
+
modelId: modelName, provider: 'openrouter', api: 'openai-completions',
|
|
597
|
+
baseUrl: 'https://openrouter.ai/api/v1', id: modelName, name: modelName,
|
|
598
|
+
inputPrice: 0, outputPrice: 0, contextWindow: 200000,
|
|
599
|
+
supportsImages: true, supportsTools: true,
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
if (tgUseProxy)
|
|
603
|
+
model.baseUrl = `${sfApiUrl}/api/proxy`;
|
|
604
|
+
const edgesSummary = (ctx.edges || [])
|
|
605
|
+
.sort((a, b) => Math.abs(b.edge) - Math.abs(a.edge))
|
|
606
|
+
.slice(0, 5)
|
|
607
|
+
.map((e) => ` ${(e.market || '').slice(0, 35)} | ${e.venue || 'kalshi'} | mkt ${e.marketPrice}¢ → thesis ${e.thesisPrice}¢ | edge ${e.edge > 0 ? '+' : ''}${e.edge}`)
|
|
608
|
+
.join('\n') || ' (no edges)';
|
|
609
|
+
const nodesSummary = (ctx.causalTree?.nodes || [])
|
|
610
|
+
.filter((n) => n.depth === 0 || !n.depth)
|
|
611
|
+
.slice(0, 5)
|
|
612
|
+
.map((n) => ` ${n.id} ${(n.label || '').slice(0, 35)} — ${Math.round((n.probability || 0.5) * 100)}%`)
|
|
613
|
+
.join('\n') || ' (no causal tree)';
|
|
614
|
+
const 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.
|
|
615
|
+
|
|
616
|
+
## Framework
|
|
617
|
+
Edge = thesis price - market price. Positive = market underprices.
|
|
618
|
+
Edge types: [consensus] depth>=500 real opponents, [attention] depth<100 illusory, [timing] market lags, [risk_premium] platform risk. Tag when reporting.
|
|
619
|
+
Price: depth >= 500 = consensus, < 100 = unreliable, spread > 5 = noisy.
|
|
620
|
+
|
|
621
|
+
## Rules
|
|
622
|
+
- When reporting an edge, tag it: [consensus] [attention] [timing] [risk_premium].
|
|
623
|
+
- If any kill condition is triggered or approaching, lead with that.
|
|
624
|
+
- If nothing material to do, say "quiet — no action needed." Don't pad.
|
|
625
|
+
- Keep Telegram messages SHORT — bullet points, no walls of text.
|
|
626
|
+
- Prices in cents (¢). P&L in dollars ($). Don't re-convert tool output units.
|
|
627
|
+
- Call tools for fresh data. Never guess prices or P&L from this prompt.
|
|
628
|
+
- Use search_x for X/Twitter sentiment. Use x_volume for discussion spikes. Use x_account to track key people.
|
|
629
|
+
- Use heartbeat_config to view/adjust scan intervals, model tier, budget cap, or check cost breakdown.
|
|
630
|
+
- Use monitor_the_situation to scrape URLs and cross-reference with markets. Use enrich_content for text-only analysis.
|
|
631
|
+
- Use get_world_state for broad situational awareness (~800 tokens).
|
|
632
|
+
- Use create_skill / list_skills / browse_public_skills / fork_skill to manage agent skills.
|
|
633
|
+
- Use fork_thesis to fork a public thesis (copies thesis + causal tree).
|
|
634
|
+
- You don't know user's positions. Call get_positions before discussing trades.
|
|
635
|
+
- If user mentions news, inject_signal immediately. Don't ask "should I?"
|
|
636
|
+
- If user says "evaluate" or "run it", trigger immediately.
|
|
637
|
+
- Don't end with "anything else?" — user will ask.
|
|
638
|
+
- Use Chinese if user writes Chinese, English if English.
|
|
639
|
+
${config.tradingEnabled ? '- Trading ENABLED. You have place_order and cancel_order. ALWAYS confirm before placing.' : '- Trading DISABLED. Tell user: sf setup --enable-trading'}
|
|
640
|
+
|
|
641
|
+
## Current State
|
|
642
|
+
Thesis: ${(ctx.thesis || ctx.rawThesis || 'N/A').slice(0, 200)}
|
|
643
|
+
ID: ${session.thesisId.slice(0, 8)} | Confidence: ${conf}%
|
|
644
|
+
|
|
645
|
+
Causal nodes:
|
|
646
|
+
${nodesSummary}
|
|
647
|
+
|
|
648
|
+
Top edges:
|
|
649
|
+
${edgesSummary}
|
|
650
|
+
|
|
651
|
+
${ctx.lastEvaluation?.summary ? `Latest eval: ${ctx.lastEvaluation.summary.slice(0, 200)}` : ''}`;
|
|
652
|
+
const agent = new Agent({
|
|
653
|
+
initialState: {
|
|
654
|
+
systemPrompt,
|
|
655
|
+
model,
|
|
656
|
+
tools,
|
|
657
|
+
thinkingLevel: 'off',
|
|
658
|
+
},
|
|
659
|
+
streamFn: streamSimple,
|
|
660
|
+
getApiKey: (provider) => provider === 'openrouter' ? openrouterKey : undefined,
|
|
661
|
+
});
|
|
662
|
+
// Restore session messages if available
|
|
663
|
+
if (session.agentMessages.length > 0) {
|
|
664
|
+
try {
|
|
665
|
+
agent.replaceMessages(session.agentMessages);
|
|
666
|
+
}
|
|
667
|
+
catch { /* start fresh */ }
|
|
668
|
+
}
|
|
669
|
+
session.agent = agent;
|
|
670
|
+
return agent;
|
|
671
|
+
}
|
|
672
|
+
async function runAgentMessage(client, session, userMessage) {
|
|
673
|
+
const agent = await getOrCreateAgent(client, session);
|
|
674
|
+
return new Promise((resolve, reject) => {
|
|
675
|
+
let response = '';
|
|
676
|
+
let toolLog = '';
|
|
677
|
+
const timeout = setTimeout(() => {
|
|
678
|
+
resolve(response || toolLog || 'Response timeout (45s). Try a simpler question.');
|
|
679
|
+
}, 45_000);
|
|
680
|
+
const unsub = agent.subscribe((event) => {
|
|
681
|
+
if (event.type === 'message_update') {
|
|
682
|
+
const e = event.assistantMessageEvent;
|
|
683
|
+
if (e.type === 'text_delta')
|
|
684
|
+
response += e.delta;
|
|
685
|
+
}
|
|
686
|
+
if (event.type === 'tool_execution_start') {
|
|
687
|
+
toolLog += `⚡ ${event.toolName}\n`;
|
|
688
|
+
}
|
|
689
|
+
if (event.type === 'agent_end') {
|
|
690
|
+
clearTimeout(timeout);
|
|
691
|
+
unsub?.();
|
|
692
|
+
// Save messages for session continuity
|
|
693
|
+
session.agentMessages = agent.state.messages || [];
|
|
694
|
+
resolve(response || toolLog || '(no response)');
|
|
695
|
+
}
|
|
696
|
+
});
|
|
697
|
+
agent.prompt(userMessage).catch((err) => {
|
|
698
|
+
clearTimeout(timeout);
|
|
699
|
+
unsub?.();
|
|
700
|
+
reject(err);
|
|
701
|
+
});
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
/***/ })
|
|
707
|
+
|
|
708
|
+
};
|
|
709
|
+
;
|