@spfunctions/cli 2.0.6 → 2.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +266 -144
- 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,s){const a=await o(e,t);if(t.thesisId)try{const n=await Promise.race([e.getContext(t.thesisId),new Promise((e,t)=>setTimeout(t,3e3))]);if(n){const e="number"==typeof n.confidence?Math.round(100*n.confidence):"?",t=(n.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,3),s=`\n\n## Live State\nConfidence: ${e}%\nTop edges: ${t.map(e=>`${(e.market||"").slice(0,20)} ${e.edge>0?"+":""}${e.edge}¢`).join(" | ")||"none"}`,i=a.state?.systemPrompt||"";i.includes("## Live State")?a.setSystemPrompt(i.replace(/\n\n## Live State[\s\S]*$/,s)):a.setSystemPrompt(i+s)}}catch{}return new Promise((e,r)=>{let o="",c="";const l=setTimeout(()=>{e(o||c||"Response timeout (45s). Try a simpler question.")},45e3),p=a.subscribe(r=>{if("message_update"===r.type){const e=r.assistantMessageEvent;"text_delta"===e.type&&(o+=e.delta)}if("tool_execution_start"===r.type&&(c+=`⚡ ${r.toolName}\n`,s&&s(r.toolName)),"agent_end"===r.type){clearTimeout(l),p?.(),t.agentMessages=a.state.messages||[];try{t.thesisId&&((0,i.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"user",content:n,source:"telegram"}),o&&(0,i.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"assistant",content:o.slice(0,5e3),source:"telegram"}))}catch{}e(o||c||"(no response)")}});a.prompt(n).catch(e=>{clearTimeout(l),p?.(),r(e)})})};const s=n(11627),i=n(73600);let a=null;async function r(){if(a)return a;const[e,t]=await Promise.all([Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653)),Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641))]),s=await Promise.all([n.e(788),n.e(722)]).then(n.bind(n,85722));return a={Agent:e.Agent,streamSimple:t.streamSimple,Type:s.Type},a}async function o(e,t){if(t.agent)return t.agent;const{Agent:a,streamSimple:o}=await r(),c=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),{getModel:l}=c,p=(0,s.loadConfig)(),d=p.openrouterKey||process.env.OPENROUTER_API_KEY,u=p.apiKey||process.env.SF_API_KEY,m=p.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev",h=!d&&!!u,g=d||u;if(!g)throw new Error("Need API key. Run sf login or sf setup.");const y=await e.getContext(t.thesisId),f="number"==typeof y.confidence?Math.round(100*y.confidence):50,x=await async function(e,t,a){const{Type:o}=await r(),c=(0,s.loadConfig)(),l=o.Object({}),p=await Promise.resolve().then(n.t.bind(n,96139,23)),{kalshiFetchAllSeries:d,kalshiFetchMarketsBySeries:u,kalshiFetchMarket:m}=await Promise.resolve().then(n.bind(n,19218)),h=[{name:"get_context",label:"Context",description:"Get thesis snapshot with causal tree, edges, evaluation",parameters:l,execute:async()=>{const n=await e.getContext(t);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"global_context",label:"Snapshot",description:"Global market snapshot — movers, expiring, milestones, liquidity, signals. No thesis needed.",parameters:l,execute:async()=>{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218)),t=await e();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"query",label:"Query",description:"LLM-enhanced prediction market search. Returns answer, live prices, key factors.",parameters:o.Object({q:o.String({description:"Question"})}),execute:async(e,t)=>{const{fetchQuery:s}=await Promise.resolve().then(n.bind(n,19218)),i=await s(t.q);return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"get_markets",label:"Markets",description:"Traditional market prices: SPY, VIX, Treasury, Gold, Oil.",parameters:l,execute:async()=>{const{fetchTraditionalMarkets:e}=await Promise.resolve().then(n.bind(n,19218)),t=await e();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"inject_signal",label:"Signal",description:"Inject a signal (news, note, observation) into the thesis",parameters:o.Object({content:o.String({description:"Signal content"}),type:o.Optional(o.String({description:"news | user_note | external"}))}),execute:async(n,s)=>(await e.injectSignal(t,s.type||"user_note",s.content,"telegram"),{content:[{type:"text",text:"Signal injected."}],details:{}})},{name:"trigger_evaluation",label:"Evaluate",description:"Trigger a deep evaluation cycle",parameters:l,execute:async()=>(await e.evaluate(t),{content:[{type:"text",text:"Evaluation triggered. Results in ~2 minutes."}],details:{}})},{name:"scan_markets",label:"Scan",description:"Search Kalshi markets by keyword, series, or ticker",parameters:o.Object({query:o.Optional(o.String({description:"Keyword search"})),series:o.Optional(o.String({description:"Series ticker"})),market:o.Optional(o.String({description:"Market ticker"}))}),execute:async(e,t)=>{let n;if(t.market)n=await m(t.market);else if(t.series)n=await u(t.series);else if(t.query){const e=await d(),s=t.query.toLowerCase().split(/\s+/);n=e.filter(e=>s.every(t=>((e.title||"")+(e.ticker||"")).toLowerCase().includes(t))).filter(e=>parseFloat(e.volume_fp||"0")>1e3).sort((e,t)=>parseFloat(t.volume_fp||"0")-parseFloat(e.volume_fp||"0")).slice(0,10)}else n={error:"Provide query, series, or market"};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"list_theses",label:"List",description:"List all theses",parameters:l,execute:async()=>{const t=await e.listTheses();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_positions",label:"Positions",description:"Get Kalshi positions with live prices and P&L",parameters:l,execute:async()=>{const e=await p.getPositions();if(!e)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};for(const t of e){const e=await p.getMarketPrice(t.ticker);null!=e&&(t.current_value=e,t.unrealized_pnl=Math.round((e-t.average_price_paid)*t.quantity))}const t=e.map(e=>({ticker:e.ticker,qty:e.quantity,avg_price:`${e.average_price_paid}¢`,current:`${e.current_value}¢`,pnl:`$${((e.unrealized_pnl||0)/100).toFixed(2)}`}));return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance",parameters:l,execute:async()=>{const e=await p.getBalance();return e?{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_orders",label:"Orders",description:"Get resting orders on Kalshi",parameters:l,execute:async()=>{const e=await p.getOrders({status:"resting",limit:50});return e?{content:[{type:"text",text:JSON.stringify(e.orders,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_fills",label:"Fills",description:"Get recent trade fills",parameters:o.Object({ticker:o.Optional(o.String())}),execute:async(e,t)=>{const n=await p.getFills({ticker:t.ticker,limit:20});return n?{content:[{type:"text",text:JSON.stringify(n.fills,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled contracts with P&L",parameters:l,execute:async()=>{const e=await p.getSettlements({limit:50});return e?{content:[{type:"text",text:JSON.stringify(e.settlements,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_edges",label:"Edges",description:"Top 10 edges across all active theses",parameters:l,execute:async()=>{const{theses:t}=await e.listTheses(),n=(t||[]).filter(e=>"active"===e.status),s=await Promise.allSettled(n.map(async t=>((await e.getContext(t.id)).edges||[]).map(e=>({...e,thesisId:t.id})))),i=[];for(const e of s)"fulfilled"===e.status&&i.push(...e.value);return i.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0)),{content:[{type:"text",text:JSON.stringify(i.slice(0,10),null,2)}],details:{}}}},{name:"get_schedule",label:"Schedule",description:"Exchange status (open/closed) and trading hours",parameters:l,execute:async()=>{const e=await fetch("https://api.elections.kalshi.com/trade-api/v2/exchange/status",{headers:{Accept:"application/json"}});if(!e.ok)return{content:[{type:"text",text:`API error: ${e.status}`}],details:{}};const t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_feed",label:"Feed",description:"Recent evaluation history",parameters:o.Object({hours:o.Optional(o.Number({description:"Hours of history (default 24)"}))}),execute:async(t,n)=>{const s=await e.getFeed(n.hours||24);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"web_search",label:"Search",description:"Search the web for latest news",parameters:o.Object({query:o.String({description:"Search query"})}),execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY||c.tavilyKey,s=c.apiKey||process.env.SF_API_KEY,i=c.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev";if(!n&&(n||!s))return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let a;if(a=n?await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}):await fetch(`${i}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}),!a.ok)return{content:[{type:"text",text:`Search failed: ${a.status}`}],details:{}};const r=await a.json();return{content:[{type:"text",text:`${r.answer?`Summary: ${r.answer}\n\n`:""}${(r.results||[]).map(e=>`${e.title}: ${(e.content||"").slice(0,150)}`).join("\n\n")}`}],details:{}}}},{name:"create_thesis",label:"Create",description:"Create a new thesis",parameters:o.Object({rawThesis:o.String({description:"Thesis statement"})}),execute:async(t,n)=>{const s=await e.createThesis(n.rawThesis,!0);return{content:[{type:"text",text:`Created: ${s.id}\nConfidence: ${Math.round(100*(s.confidence||.5))}%`}],details:{}}}},{name:"what_if",label:"What-If",description:"Override causal tree node probabilities and see how edges change. Zero LLM cost.",parameters:o.Object({overrides:o.Array(o.Object({nodeId:o.String({description:"Node ID (e.g. n1, n3.1)"}),newProbability:o.Number({description:"New probability 0-1"})}))}),execute:async(e,t)=>{const n=a,s=[];!function e(t){for(const n of t)s.push(n),n.children?.length&&e(n.children)}(n?.causalTree?.nodes||[]);const i=new Map(t.overrides.map(e=>[e.nodeId,e.newProbability])),r=(n?.causalTree?.nodes||[]).filter(e=>!e.parentId||0===e.depth),o=r.reduce((e,t)=>e+(t.probability||.5),0)/Math.max(r.length,1);for(const e of s)i.has(e.id)&&(e.probability=i.get(e.id));const c=r.reduce((e,t)=>e+(t.probability||.5),0)/Math.max(r.length,1),l=(n?.edges||[]).slice(0,10).map(e=>{const t=s.find(t=>t.id===e.relatedNodeId);if(!t||!i.has(t.id))return{market:e.market,oldEdge:e.edge,newEdge:e.edge,signal:"unchanged"};const n=t.probability/(e.confidence||.5),a=Math.round(e.thesisPrice*n)-e.marketPrice;return{market:e.market,oldEdge:e.edge,newEdge:a,signal:Math.abs(a-e.edge)<1?"unchanged":"changed"}}).filter(e=>"unchanged"!==e.signal);return{content:[{type:"text",text:JSON.stringify({confidence:{old:Math.round(100*o),new:Math.round(100*c)},edges:l},null,2)}],details:{}}}}];h.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:o.Object({query:o.String({description:"Search query"}),mode:o.Optional(o.String({description:'"summary" or "raw"'})),hours:o.Optional(o.Number({description:"Hours (default 24)"}))}),execute:async(t,n)=>{const s=await e.searchX(n.query,{mode:n.mode,hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_volume",label:"X Volume",description:"X discussion volume trend — total posts, velocity, peak time.",parameters:o.Object({query:o.String({description:"Search query"}),hours:o.Optional(o.Number({description:"Hours (default 72)"}))}),execute:async(t,n)=>{const s=await e.getXVolume(n.query,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_news",label:"X News",description:"News stories trending on X — titles, summaries, tickers.",parameters:o.Object({query:o.String({description:"Search query"}),limit:o.Optional(o.Number({description:"Max stories (default 10)"}))}),execute:async(t,n)=>{const s=await e.searchXNews(n.query,{limit:n.limit});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"x_account",label:"X Account",description:"Recent posts from a specific X account.",parameters:o.Object({username:o.String({description:"X username (with or without @)"}),hours:o.Optional(o.Number({description:"Hours (default 24)"}))}),execute:async(t,n)=>{const s=await e.getXAccount(n.username,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"heartbeat_config",label:"Heartbeat Config",description:"View or update heartbeat settings: scan intervals, model tier, budget cap, pause/resume. Shows cost breakdown.",parameters:o.Object({thesisId:o.String({description:"Thesis ID"}),newsIntervalMin:o.Optional(o.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:o.Optional(o.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:o.Optional(o.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:o.Optional(o.Number({description:"Monthly budget (0 = unlimited)"})),paused:o.Optional(o.Boolean({description:"Pause or resume heartbeat"}))}),execute:async(t,n)=>{if(n.newsIntervalMin||n.xIntervalMin||n.evalModelTier||void 0!==n.monthlyBudgetUsd||void 0!==n.paused){const t={};n.newsIntervalMin&&(t.newsIntervalMin=n.newsIntervalMin),n.xIntervalMin&&(t.xIntervalMin=n.xIntervalMin),n.evalModelTier&&(t.evalModelTier=n.evalModelTier),void 0!==n.monthlyBudgetUsd&&(t.monthlyBudgetUsd=n.monthlyBudgetUsd),void 0!==n.paused&&(t.paused=n.paused),await e.updateHeartbeatConfig(n.thesisId,t)}const s=await e.getHeartbeatConfig(n.thesisId);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}});const g=process.env.SF_API_URL||c.apiUrl||"https://simplefunctions.dev";return h.push({name:"get_world_state",label:"World",description:"Real-time world model (~800 tokens). Geopolitics, economy, energy, elections, crypto, tech.",parameters:o.Object({focus:o.Optional(o.String({description:"Comma-separated topics"}))}),execute:async(e,t)=>{const n=new URLSearchParams;t.focus&&n.set("focus",t.focus);const s=await fetch(`${g}/api/agent/world?${n}`);return{content:[{type:"text",text:await s.text()}],details:{}}}},{name:"monitor_the_situation",label:"Monitor",description:"Scrape any URL (Firecrawl), analyze with any LLM, cross-reference with 9,706 markets, push to webhook.",parameters:o.Object({sourceAction:o.String({description:"scrape|crawl|search|map|extract"}),url:o.Optional(o.String()),query:o.Optional(o.String()),topics:o.Optional(o.String({description:"Comma-separated topics for market enrichment"}))}),execute:async(e,t)=>{const n={source:{action:t.sourceAction}};t.url&&(n.source.url=t.url),t.query&&(n.source.query=t.query),t.topics&&(n.enrich={enabled:!0,topics:t.topics.split(",").map(e=>e.trim()),includeIndex:!0});const s=await fetch(`${g}/api/monitor-the-situation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"enrich_content",label:"Enrich",description:"Cross-reference any text with 9,706 prediction markets. Returns divergences.",parameters:o.Object({content:o.String({description:"Text to cross-reference"}),topics:o.Optional(o.String({description:"Comma-separated topics"}))}),execute:async(e,t)=>{const n={content:t.content};t.topics?n.topics=t.topics.split(",").map(e=>e.trim()):n.topics=["general"];const s=await fetch(`${g}/api/monitor-the-situation/enrich`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"create_skill",label:"Create Skill",description:"Create a custom agent skill.",parameters:o.Object({name:o.String(),trigger:o.String(),description:o.String(),prompt:o.String(),category:o.Optional(o.String())}),execute:async(e,t)=>{const n=await fetch(`${g}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c.apiKey}`},body:JSON.stringify(t)}),s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"list_skills",label:"Skills",description:"List built-in + custom skills.",parameters:l,execute:async()=>{const e=await fetch(`${g}/api/skill`,{headers:{Authorization:`Bearer ${c.apiKey}`}}),t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"browse_public_skills",label:"Public Skills",description:"Browse community skills.",parameters:o.Object({q:o.Optional(o.String()),sort:o.Optional(o.String())}),execute:async(e,t)=>{const n=new URLSearchParams;t.q&&n.set("q",t.q),t.sort&&n.set("sort",t.sort);const s=await fetch(`${g}/api/public/skills?${n}`),i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"fork_skill",label:"Fork Skill",description:"Fork a public skill into your collection.",parameters:o.Object({skillId:o.String()}),execute:async(e,t)=>{const n=await fetch(`${g}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${c.apiKey}`}}),s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"fork_thesis",label:"Fork Thesis",description:"Fork a public thesis. Copies thesis + causal tree.",parameters:o.Object({slug:o.String()}),execute:async(e,t)=>{const n=await fetch(`${g}/api/thesis/${t.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${c.apiKey}`}}),s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}}),c.tradingEnabled&&h.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Requires trading to be enabled. Always confirm with user before placing.",parameters:o.Object({ticker:o.String({description:"Market ticker (e.g. KXWTIMAX-26DEC31-T135)"}),side:o.String({description:"yes or no"}),action:o.String({description:"buy or sell"}),count:o.Number({description:"Number of contracts"}),yes_price:o.Number({description:"Price in cents (1-99)"})}),execute:async(e,t)=>{try{const e=await p.createOrder({ticker:t.ticker,side:t.side,action:t.action,type:"limit",count:t.count,yes_price:t.yes_price});return{content:[{type:"text",text:`✓ Order placed: ${(e.order||e).order_id||"OK"}\n${t.action.toUpperCase()} ${t.count}x ${t.ticker} ${t.side.toUpperCase()} @ ${t.yes_price}¢`}],details:{}}}catch(e){return{content:[{type:"text",text:`✗ Order failed: ${e.message}`}],details:{}}}}},{name:"cancel_order",label:"Cancel Order",description:"Cancel a resting order on Kalshi.",parameters:o.Object({orderId:o.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{try{return await p.cancelOrder(t.orderId),{content:[{type:"text",text:`✓ Order ${t.orderId} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`✗ Cancel failed: ${e.message}`}],details:{}}}}}),h.push({name:"fs_read",label:"Read File",description:"Read a file from workspace (~/.sf/workspace/).",parameters:o.Object({path:o.String({description:"Relative file path"})}),execute:async(e,t)=>{const n=(0,i.wsRead)(t.path);return{content:[{type:"text",text:n.ok?n.content:`Error: ${n.content}`}],details:{}}}},{name:"fs_write",label:"Write File",description:"Write or append to a file in workspace.",parameters:o.Object({path:o.String({description:"Relative file path"}),content:o.String({description:"Content"}),append:o.Optional(o.Boolean({description:"Append mode"}))}),execute:async(e,t)=>({content:[{type:"text",text:(0,i.wsWrite)(t.path,t.content,t.append).message}],details:{}})},{name:"fs_list",label:"List Files",description:"List files in workspace.",parameters:o.Object({path:o.Optional(o.String({description:"Directory"})),glob:o.Optional(o.String({description:"Filter pattern"}))}),execute:async(e,t)=>{const n=(0,i.wsList)(t.path,t.glob);return n.ok?{content:[{type:"text",text:n.entries.length>0?n.entries.join("\n"):"(empty)"}],details:{}}:{content:[{type:"text",text:`Error: ${n.message}`}],details:{}}}},{name:"fs_search",label:"Search Files",description:"Search file contents in workspace using regex.",parameters:o.Object({pattern:o.String({description:"Regex pattern"}),path:o.Optional(o.String({description:"Directory scope"}))}),execute:async(e,t)=>{const n=(0,i.wsSearch)(t.pattern,t.path);return n.ok?0===n.matches.length?{content:[{type:"text",text:"No matches."}],details:{}}:{content:[{type:"text",text:n.matches.map(e=>`${e.file}:${e.line}: ${e.text}`).join("\n")}],details:{}}:{content:[{type:"text",text:`Error: ${n.message}`}],details:{}}}},{name:"fs_delete",label:"Delete File",description:"Delete a file from workspace.",parameters:o.Object({path:o.String({description:"File to delete"})}),execute:async(e,t)=>({content:[{type:"text",text:(0,i.wsDelete)(t.path).message}],details:{}})}),h.push({name:"calculate",label:"Calculate",description:"Evaluate a math expression precisely.",parameters:o.Object({expression:o.String({description:"Math expression"})}),execute:async(e,t)=>{try{const e=t.expression.trim();return/^[\d\s+\-*/.%(),eE]+$/.test(e.replace(/Math\.\w+/g,"").replace(/\*\*/g,""))?{content:[{type:"text",text:`${e} = ${new Function(`"use strict"; return (${e})`)()}`}],details:{}}:{content:[{type:"text",text:"Unsafe expression."}],details:{}}}catch(e){return{content:[{type:"text",text:`Calc error: ${e.message}`}],details:{}}}}},{name:"cancel_all_intents",label:"Cancel All",description:"Cancel all active intents. Emergency use.",parameters:o.Object({confirm:o.Boolean({description:"Must be true"})}),execute:async(t,n)=>{if(!n.confirm)return{content:[{type:"text",text:"Set confirm=true."}],details:{}};try{const t=((await e.listIntents({active:!0})).intents||[]).filter(e=>["pending","armed"].includes(e.status));if(0===t.length)return{content:[{type:"text",text:"No active intents."}],details:{}};let n=0;for(const s of t)try{await e.cancelIntentAPI(s.id),n++}catch{}return{content:[{type:"text",text:`Cancelled ${n}/${t.length} intents.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}}),h}(e,t.thesisId,y),b=p.model||"anthropic/claude-sonnet-4.6";let w;try{w=l("openrouter",b)}catch{w={modelId:b,provider:"openrouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",id:b,name:b,inputPrice:0,outputPrice:0,contextWindow:2e5,supportsImages:!0,supportsTools:!0}}h&&(w.baseUrl=`${m}/api/proxy`);const S=(y.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.market||"").slice(0,35)} | ${e.venue||"kalshi"} | mkt ${e.marketPrice}¢ → thesis ${e.thesisPrice}¢ | edge ${e.edge>0?"+":""}${e.edge}`).join("\n")||" (no edges)",k=(y.causalTree?.nodes||[]).filter(e=>0===e.depth||!e.depth).slice(0,5).map(e=>` ${e.id} ${(e.label||"").slice(0,35)} — ${Math.round(100*(e.probability||.5))}%`).join("\n")||" (no causal tree)",_=new a({initialState:{systemPrompt:`You are a prediction market trading assistant on Telegram. Your job is to help the user see reality clearly and make correct trading decisions.\n\n## Framework\nEdge = thesis price - market price. Positive = market underprices.\nEdge types: [consensus] depth>=500 real opponents, [attention] depth<100 illusory, [timing] market lags, [risk_premium] platform risk. Tag when reporting.\nPrice: depth >= 500 = consensus, < 100 = unreliable, spread > 5 = noisy.\n\n## Rules\n- When reporting an edge, tag it: [consensus] [attention] [timing] [risk_premium].\n- If any kill condition is triggered or approaching, lead with that.\n- If nothing material to do, say "quiet — no action needed." Don't pad.\n- Keep Telegram messages SHORT — bullet points, no walls of text.\n- Prices in cents (¢). P&L in dollars ($). Don't re-convert tool output units.\n- Call tools for fresh data. Never guess prices or P&L from this prompt.\n- Use search_x for X/Twitter sentiment. Use x_volume for discussion spikes. Use x_account to track key people.\n- Use heartbeat_config to view/adjust scan intervals, model tier, budget cap, or check cost breakdown.\n- Use monitor_the_situation to scrape URLs and cross-reference with markets. Use enrich_content for text-only analysis.\n- Use get_world_state for broad situational awareness (~800 tokens).\n- Use create_skill / list_skills / browse_public_skills / fork_skill to manage agent skills.\n- Use fork_thesis to fork a public thesis (copies thesis + causal tree).\n- fs_read/fs_write/fs_list/fs_search/fs_delete: workspace. Write notes proactively. Shared with TUI.\n- calculate: precise math. send_alert: push to Telegram. schedule_wake: self-scheduling.\n- Live State shows positions/edges each turn — use it directly, don't re-fetch.\n- If user mentions news, inject_signal immediately. Don't ask "should I?"\n- If user says "evaluate" or "run it", trigger immediately.\n- Don't end with "anything else?" — user will ask.\n- Use Chinese if user writes Chinese, English if English.\n${p.tradingEnabled?"- Trading ENABLED. You have place_order and cancel_order. ALWAYS confirm before placing.":"- Trading DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current State\nThesis: ${(y.thesis||y.rawThesis||"N/A").slice(0,200)}\nID: ${t.thesisId.slice(0,8)} | Confidence: ${f}%\n\nCausal nodes:\n${k}\n\nTop edges:\n${S}\n\n${y.lastEvaluation?.summary?`Latest eval: ${y.lastEvaluation.summary.slice(0,200)}`:""}`,model:w,tools:x,thinkingLevel:"off"},streamFn:o,getApiKey:e=>"openrouter"===e?g:void 0});if(t.agentMessages.length>0)try{_.replaceMessages(t.agentMessages)}catch{}else if(t.thesisId)try{const e=(0,i.readRecentContext)(t.thesisId,30);if(e.length>0){const t=[];for(const n of e)"user"===n.role?t.push({role:"user",content:n.content}):"assistant"===n.role&&t.push({role:"assistant",content:n.content});const n=[];for(const e of t)0!==n.length&&n[n.length-1].role===e.role||n.push(e);if(n.length>0)try{_.replaceMessages(n)}catch{}}}catch{}return t.agent=_,_}}};
|
|
1
|
+
"use strict";exports.id=160,exports.ids=[160],exports.modules={28160:(e,t,n)=>{t.runAgentMessage=async function(e,t,n,i){const s=await o(e,t);if(t.thesisId)try{const n=await Promise.race([e.getContext(t.thesisId),new Promise((e,t)=>setTimeout(t,3e3))]);if(n){const e="number"==typeof n.confidence?Math.round(100*n.confidence):"?",t=(n.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,3),i=`\n\n## Live State\nConfidence: ${e}%\nTop edges: ${t.map(e=>`${(e.market||"").slice(0,20)} ${e.edge>0?"+":""}${e.edge}¢`).join(" | ")||"none"}`,a=s.state?.systemPrompt||"";a.includes("## Live State")?s.setSystemPrompt(a.replace(/\n\n## Live State[\s\S]*$/,i)):s.setSystemPrompt(a+i)}}catch{}return new Promise((e,r)=>{let o="",c="";const l=setTimeout(()=>{e(o||c||"Response timeout (45s). Try a simpler question.")},45e3),d=s.subscribe(r=>{if("message_update"===r.type){const e=r.assistantMessageEvent;"text_delta"===e.type&&(o+=e.delta)}if("tool_execution_start"===r.type&&(c+=`⚡ ${r.toolName}\n`,i&&i(r.toolName)),"agent_end"===r.type){clearTimeout(l),d?.(),t.agentMessages=s.state.messages||[];try{t.thesisId&&((0,a.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"user",content:n,source:"telegram"}),o&&(0,a.appendContext)(t.thesisId,{ts:(new Date).toISOString(),role:"assistant",content:o.slice(0,5e3),source:"telegram"}))}catch{}e(o||c||"(no response)")}});s.prompt(n).catch(e=>{clearTimeout(l),d?.(),r(e)})})};const i=n(11627),a=n(73600);let s=null;async function r(){if(s)return s;const[e,t]=await Promise.all([Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653)),Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641))]),i=await Promise.all([n.e(788),n.e(722)]).then(n.bind(n,85722));return s={Agent:e.Agent,streamSimple:t.streamSimple,Type:i.Type},s}async function o(e,t){if(t.agent)return t.agent;const{Agent:s,streamSimple:o}=await r(),c=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),{getModel:l}=c,d=(0,i.loadConfig)(),p=d.openrouterKey||process.env.OPENROUTER_API_KEY,u=d.apiKey||process.env.SF_API_KEY,m=d.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev",h=!p&&!!u,g=p||u;if(!g)throw new Error("Need API key. Run sf login or sf setup.");const y=await e.getContext(t.thesisId),x="number"==typeof y.confidence?Math.round(100*y.confidence):50,f=await async function(e,t,s){const{Type:o}=await r(),c=(0,i.loadConfig)(),l=o.Object({}),d=await Promise.resolve().then(n.t.bind(n,96139,23)),{kalshiFetchAllSeries:p,kalshiFetchMarketsBySeries:u,kalshiFetchMarket:m}=await Promise.resolve().then(n.bind(n,19218)),h=[{name:"get_context",label:"Context",description:"Get thesis snapshot with causal tree, edges, evaluation",parameters:l,execute:async()=>{const n=await e.getContext(t);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"global_context",label:"Snapshot",description:"Global market snapshot — movers, expiring, milestones, liquidity, signals. No thesis needed.",parameters:l,execute:async()=>{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218)),t=await e();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"query",label:"Query",description:"LLM-enhanced prediction market search. Returns answer, live prices, key factors.",parameters:o.Object({q:o.String({description:"Question"})}),execute:async(e,t)=>{const{fetchQuery:i}=await Promise.resolve().then(n.bind(n,19218)),a=await i(t.q);return{content:[{type:"text",text:JSON.stringify(a,null,2)}],details:{}}}},{name:"get_markets",label:"Markets",description:"Traditional market prices: SPY, VIX, Treasury, Gold, Oil.",parameters:l,execute:async()=>{const{fetchTraditionalMarkets:e}=await Promise.resolve().then(n.bind(n,19218)),t=await e();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"inject_signal",label:"Signal",description:"Inject a signal (news, note, observation) into the thesis",parameters:o.Object({content:o.String({description:"Signal content"}),type:o.Optional(o.String({description:"news | user_note | external"}))}),execute:async(n,i)=>(await e.injectSignal(t,i.type||"user_note",i.content,"telegram"),{content:[{type:"text",text:"Signal injected."}],details:{}})},{name:"trigger_evaluation",label:"Evaluate",description:"Trigger a deep evaluation cycle",parameters:l,execute:async()=>(await e.evaluate(t),{content:[{type:"text",text:"Evaluation triggered. Results in ~2 minutes."}],details:{}})},{name:"scan_markets",label:"Scan",description:"Search Kalshi markets by keyword, series, or ticker",parameters:o.Object({query:o.Optional(o.String({description:"Keyword search"})),series:o.Optional(o.String({description:"Series ticker"})),market:o.Optional(o.String({description:"Market ticker"}))}),execute:async(e,t)=>{let n;if(t.market)n=await m(t.market);else if(t.series)n=await u(t.series);else if(t.query){const e=await p(),i=t.query.toLowerCase().split(/\s+/);n=e.filter(e=>i.every(t=>((e.title||"")+(e.ticker||"")).toLowerCase().includes(t))).filter(e=>parseFloat(e.volume_fp||"0")>1e3).sort((e,t)=>parseFloat(t.volume_fp||"0")-parseFloat(e.volume_fp||"0")).slice(0,10)}else n={error:"Provide query, series, or market"};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"list_theses",label:"List",description:"List all theses",parameters:l,execute:async()=>{const t=await e.listTheses();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_positions",label:"Positions",description:"Get Kalshi positions with live prices and P&L",parameters:l,execute:async()=>{const e=await d.getPositions();if(!e)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};for(const t of e){const e=await d.getMarketPrice(t.ticker);null!=e&&(t.current_value=e,t.unrealized_pnl=Math.round((e-t.average_price_paid)*t.quantity))}const t=e.map(e=>({ticker:e.ticker,qty:e.quantity,avg_price:`${e.average_price_paid}¢`,current:`${e.current_value}¢`,pnl:`$${((e.unrealized_pnl||0)/100).toFixed(2)}`}));return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance",parameters:l,execute:async()=>{const e=await d.getBalance();return e?{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_orders",label:"Orders",description:"Get resting orders on Kalshi",parameters:l,execute:async()=>{const e=await d.getOrders({status:"resting",limit:50});return e?{content:[{type:"text",text:JSON.stringify(e.orders,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_fills",label:"Fills",description:"Get recent trade fills",parameters:o.Object({ticker:o.Optional(o.String())}),execute:async(e,t)=>{const n=await d.getFills({ticker:t.ticker,limit:20});return n?{content:[{type:"text",text:JSON.stringify(n.fills,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled contracts with P&L",parameters:l,execute:async()=>{const e=await d.getSettlements({limit:50});return e?{content:[{type:"text",text:JSON.stringify(e.settlements,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_edges",label:"Edges",description:"Top 10 edges across all active theses",parameters:l,execute:async()=>{const{theses:t}=await e.listTheses(),n=(t||[]).filter(e=>"active"===e.status),i=await Promise.allSettled(n.map(async t=>((await e.getContext(t.id)).edges||[]).map(e=>({...e,thesisId:t.id})))),a=[];for(const e of i)"fulfilled"===e.status&&a.push(...e.value);return a.sort((e,t)=>Math.abs(t.edge||0)-Math.abs(e.edge||0)),{content:[{type:"text",text:JSON.stringify(a.slice(0,10),null,2)}],details:{}}}},{name:"get_schedule",label:"Schedule",description:"Exchange status (open/closed) and trading hours",parameters:l,execute:async()=>{const e=await fetch("https://api.elections.kalshi.com/trade-api/v2/exchange/status",{headers:{Accept:"application/json"}});if(!e.ok)return{content:[{type:"text",text:`API error: ${e.status}`}],details:{}};const t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_feed",label:"Feed",description:"Recent evaluation history",parameters:o.Object({hours:o.Optional(o.Number({description:"Hours of history (default 24)"}))}),execute:async(t,n)=>{const i=await e.getFeed(n.hours||24);return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"web_search",label:"Search",description:"Search the web for latest news",parameters:o.Object({query:o.String({description:"Search query"})}),execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY||c.tavilyKey,i=c.apiKey||process.env.SF_API_KEY,a=c.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev";if(!n&&(n||!i))return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let s;if(s=n?await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}):await fetch(`${a}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({query:t.query,max_results:3,search_depth:"basic",include_answer:!0})}),!s.ok)return{content:[{type:"text",text:`Search failed: ${s.status}`}],details:{}};const r=await s.json();return{content:[{type:"text",text:`${r.answer?`Summary: ${r.answer}\n\n`:""}${(r.results||[]).map(e=>`${e.title}: ${(e.content||"").slice(0,150)}`).join("\n\n")}`}],details:{}}}},{name:"create_thesis",label:"Create",description:"Create a new thesis",parameters:o.Object({rawThesis:o.String({description:"Thesis statement"})}),execute:async(t,n)=>{const i=await e.createThesis(n.rawThesis,!0);return{content:[{type:"text",text:`Created: ${i.id}\nConfidence: ${Math.round(100*(i.confidence||.5))}%`}],details:{}}}},{name:"what_if",label:"What-If",description:"Override causal tree node probabilities and see how edges change. Zero LLM cost.",parameters:o.Object({overrides:o.Array(o.Object({nodeId:o.String({description:"Node ID (e.g. n1, n3.1)"}),newProbability:o.Number({description:"New probability 0-1"})}))}),execute:async(e,t)=>{const n=s,i=[];!function e(t){for(const n of t)i.push(n),n.children?.length&&e(n.children)}(n?.causalTree?.nodes||[]);const a=new Map(t.overrides.map(e=>[e.nodeId,e.newProbability])),r=(n?.causalTree?.nodes||[]).filter(e=>!e.parentId||0===e.depth),o=r.reduce((e,t)=>e+(t.probability||.5),0)/Math.max(r.length,1);for(const e of i)a.has(e.id)&&(e.probability=a.get(e.id));const c=r.reduce((e,t)=>e+(t.probability||.5),0)/Math.max(r.length,1),l=(n?.edges||[]).slice(0,10).map(e=>{const t=i.find(t=>t.id===e.relatedNodeId);if(!t||!a.has(t.id))return{market:e.market,oldEdge:e.edge,newEdge:e.edge,signal:"unchanged"};const n=t.probability/(e.confidence||.5),s=Math.round(e.thesisPrice*n)-e.marketPrice;return{market:e.market,oldEdge:e.edge,newEdge:s,signal:Math.abs(s-e.edge)<1?"unchanged":"changed"}}).filter(e=>"unchanged"!==e.signal);return{content:[{type:"text",text:JSON.stringify({confidence:{old:Math.round(100*o),new:Math.round(100*c)},edges:l},null,2)}],details:{}}}}];h.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:o.Object({query:o.String({description:"Search query"}),mode:o.Optional(o.String({description:'"summary" or "raw"'})),hours:o.Optional(o.Number({description:"Hours (default 24)"}))}),execute:async(t,n)=>{const i=await e.searchX(n.query,{mode:n.mode,hours:n.hours});return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"x_volume",label:"X Volume",description:"X discussion volume trend — total posts, velocity, peak time.",parameters:o.Object({query:o.String({description:"Search query"}),hours:o.Optional(o.Number({description:"Hours (default 72)"}))}),execute:async(t,n)=>{const i=await e.getXVolume(n.query,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"x_news",label:"X News",description:"News stories trending on X — titles, summaries, tickers.",parameters:o.Object({query:o.String({description:"Search query"}),limit:o.Optional(o.Number({description:"Max stories (default 10)"}))}),execute:async(t,n)=>{const i=await e.searchXNews(n.query,{limit:n.limit});return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"x_account",label:"X Account",description:"Recent posts from a specific X account.",parameters:o.Object({username:o.String({description:"X username (with or without @)"}),hours:o.Optional(o.Number({description:"Hours (default 24)"}))}),execute:async(t,n)=>{const i=await e.getXAccount(n.username,{hours:n.hours});return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"heartbeat_config",label:"Heartbeat Config",description:"View or update heartbeat settings: scan intervals, model tier, budget cap, pause/resume. Shows cost breakdown.",parameters:o.Object({thesisId:o.String({description:"Thesis ID"}),newsIntervalMin:o.Optional(o.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:o.Optional(o.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:o.Optional(o.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:o.Optional(o.Number({description:"Monthly budget (0 = unlimited)"})),paused:o.Optional(o.Boolean({description:"Pause or resume heartbeat"}))}),execute:async(t,n)=>{if(n.newsIntervalMin||n.xIntervalMin||n.evalModelTier||void 0!==n.monthlyBudgetUsd||void 0!==n.paused){const t={};n.newsIntervalMin&&(t.newsIntervalMin=n.newsIntervalMin),n.xIntervalMin&&(t.xIntervalMin=n.xIntervalMin),n.evalModelTier&&(t.evalModelTier=n.evalModelTier),void 0!==n.monthlyBudgetUsd&&(t.monthlyBudgetUsd=n.monthlyBudgetUsd),void 0!==n.paused&&(t.paused=n.paused),await e.updateHeartbeatConfig(n.thesisId,t)}const i=await e.getHeartbeatConfig(n.thesisId);return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}});const g=process.env.SF_API_URL||c.apiUrl||"https://simplefunctions.dev";return h.push({name:"get_world_state",label:"World",description:"Real-time world model (~800 tokens). Geopolitics, economy, energy, elections, crypto, tech.",parameters:o.Object({focus:o.Optional(o.String({description:"Comma-separated topics"}))}),execute:async(e,t)=>{const n=new URLSearchParams;t.focus&&n.set("focus",t.focus);const i=await fetch(`${g}/api/agent/world?${n}`);return{content:[{type:"text",text:await i.text()}],details:{}}}},{name:"monitor_the_situation",label:"Monitor",description:"Scrape any URL (Firecrawl), analyze with any LLM, cross-reference with 9,706 markets, push to webhook.",parameters:o.Object({sourceAction:o.String({description:"scrape|crawl|search|map|extract"}),url:o.Optional(o.String()),query:o.Optional(o.String()),topics:o.Optional(o.String({description:"Comma-separated topics for market enrichment"}))}),execute:async(e,t)=>{const n={source:{action:t.sourceAction}};t.url&&(n.source.url=t.url),t.query&&(n.source.query=t.query),t.topics&&(n.enrich={enabled:!0,topics:t.topics.split(",").map(e=>e.trim()),includeIndex:!0});const i=await fetch(`${g}/api/monitor-the-situation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a=await i.json();return{content:[{type:"text",text:JSON.stringify(a,null,2)}],details:{}}}},{name:"enrich_content",label:"Enrich",description:"Cross-reference any text with 9,706 prediction markets. Returns divergences.",parameters:o.Object({content:o.String({description:"Text to cross-reference"}),topics:o.Optional(o.String({description:"Comma-separated topics"}))}),execute:async(e,t)=>{const n={content:t.content};t.topics?n.topics=t.topics.split(",").map(e=>e.trim()):n.topics=["general"];const i=await fetch(`${g}/api/monitor-the-situation/enrich`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a=await i.json();return{content:[{type:"text",text:JSON.stringify(a,null,2)}],details:{}}}},{name:"create_skill",label:"Create Skill",description:"Create a custom agent skill.",parameters:o.Object({name:o.String(),trigger:o.String(),description:o.String(),prompt:o.String(),category:o.Optional(o.String())}),execute:async(e,t)=>{const n=await fetch(`${g}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c.apiKey}`},body:JSON.stringify(t)}),i=await n.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"list_skills",label:"Skills",description:"List built-in + custom skills.",parameters:l,execute:async()=>{const e=await fetch(`${g}/api/skill`,{headers:{Authorization:`Bearer ${c.apiKey}`}}),t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"browse_public_skills",label:"Public Skills",description:"Browse community skills.",parameters:o.Object({q:o.Optional(o.String()),sort:o.Optional(o.String())}),execute:async(e,t)=>{const n=new URLSearchParams;t.q&&n.set("q",t.q),t.sort&&n.set("sort",t.sort);const i=await fetch(`${g}/api/public/skills?${n}`),a=await i.json();return{content:[{type:"text",text:JSON.stringify(a,null,2)}],details:{}}}},{name:"fork_skill",label:"Fork Skill",description:"Fork a public skill into your collection.",parameters:o.Object({skillId:o.String()}),execute:async(e,t)=>{const n=await fetch(`${g}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${c.apiKey}`}}),i=await n.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"fork_thesis",label:"Fork Thesis",description:"Fork a public thesis. Copies thesis + causal tree.",parameters:o.Object({slug:o.String()}),execute:async(e,t)=>{const n=await fetch(`${g}/api/thesis/${t.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${c.apiKey}`}}),i=await n.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}}),c.tradingEnabled&&h.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Requires trading to be enabled. Always confirm with user before placing.",parameters:o.Object({ticker:o.String({description:"Market ticker (e.g. KXWTIMAX-26DEC31-T135)"}),side:o.String({description:"yes or no"}),action:o.String({description:"buy or sell"}),count:o.Number({description:"Number of contracts"}),yes_price:o.Number({description:"Price in cents (1-99)"})}),execute:async(e,t)=>{try{const e=await d.createOrder({ticker:t.ticker,side:t.side,action:t.action,type:"limit",count:t.count,yes_price:t.yes_price});return{content:[{type:"text",text:`✓ Order placed: ${(e.order||e).order_id||"OK"}\n${t.action.toUpperCase()} ${t.count}x ${t.ticker} ${t.side.toUpperCase()} @ ${t.yes_price}¢`}],details:{}}}catch(e){return{content:[{type:"text",text:`✗ Order failed: ${e.message}`}],details:{}}}}},{name:"cancel_order",label:"Cancel Order",description:"Cancel a resting order on Kalshi.",parameters:o.Object({orderId:o.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{try{return await d.cancelOrder(t.orderId),{content:[{type:"text",text:`✓ Order ${t.orderId} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`✗ Cancel failed: ${e.message}`}],details:{}}}}}),h.push({name:"fs_read",label:"Read File",description:"Read a file from workspace (~/.sf/workspace/).",parameters:o.Object({path:o.String({description:"Relative file path"})}),execute:async(e,t)=>{const n=(0,a.wsRead)(t.path);return{content:[{type:"text",text:n.ok?n.content:`Error: ${n.content}`}],details:{}}}},{name:"fs_write",label:"Write File",description:"Write or append to a file in workspace.",parameters:o.Object({path:o.String({description:"Relative file path"}),content:o.String({description:"Content"}),append:o.Optional(o.Boolean({description:"Append mode"}))}),execute:async(e,t)=>({content:[{type:"text",text:(0,a.wsWrite)(t.path,t.content,t.append).message}],details:{}})},{name:"fs_list",label:"List Files",description:"List files in workspace.",parameters:o.Object({path:o.Optional(o.String({description:"Directory"})),glob:o.Optional(o.String({description:"Filter pattern"}))}),execute:async(e,t)=>{const n=(0,a.wsList)(t.path,t.glob);return n.ok?{content:[{type:"text",text:n.entries.length>0?n.entries.join("\n"):"(empty)"}],details:{}}:{content:[{type:"text",text:`Error: ${n.message}`}],details:{}}}},{name:"fs_search",label:"Search Files",description:"Search file contents in workspace using regex.",parameters:o.Object({pattern:o.String({description:"Regex pattern"}),path:o.Optional(o.String({description:"Directory scope"}))}),execute:async(e,t)=>{const n=(0,a.wsSearch)(t.pattern,t.path);return n.ok?0===n.matches.length?{content:[{type:"text",text:"No matches."}],details:{}}:{content:[{type:"text",text:n.matches.map(e=>`${e.file}:${e.line}: ${e.text}`).join("\n")}],details:{}}:{content:[{type:"text",text:`Error: ${n.message}`}],details:{}}}},{name:"fs_delete",label:"Delete File",description:"Delete a file from workspace.",parameters:o.Object({path:o.String({description:"File to delete"})}),execute:async(e,t)=>({content:[{type:"text",text:(0,a.wsDelete)(t.path).message}],details:{}})}),h.push({name:"calculate",label:"Calculate",description:"Evaluate a math expression precisely.",parameters:o.Object({expression:o.String({description:"Math expression"})}),execute:async(e,t)=>{try{const e=t.expression.trim();return/^[\d\s+\-*/.%(),eE]+$/.test(e.replace(/Math\.\w+/g,"").replace(/\*\*/g,""))?{content:[{type:"text",text:`${e} = ${new Function(`"use strict"; return (${e})`)()}`}],details:{}}:{content:[{type:"text",text:"Unsafe expression."}],details:{}}}catch(e){return{content:[{type:"text",text:`Calc error: ${e.message}`}],details:{}}}}},{name:"cancel_all_intents",label:"Cancel All",description:"Cancel all active intents. Emergency use.",parameters:o.Object({confirm:o.Boolean({description:"Must be true"})}),execute:async(t,n)=>{if(!n.confirm)return{content:[{type:"text",text:"Set confirm=true."}],details:{}};try{const t=((await e.listIntents({active:!0})).intents||[]).filter(e=>["pending","armed"].includes(e.status));if(0===t.length)return{content:[{type:"text",text:"No active intents."}],details:{}};let n=0;for(const i of t)try{await e.cancelIntentAPI(i.id),n++}catch{}return{content:[{type:"text",text:`Cancelled ${n}/${t.length} intents.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}}),c.apiUrl||process.env.SF_API_URL,c.apiKey||process.env.SF_API_KEY,h.push({name:"create_intent",label:"Create Intent",description:"Declare an execution intent with trigger conditions. Runtime daemon evaluates triggers and executes via local keys.",parameters:o.Object({action:o.String({description:"buy or sell"}),venue:o.String({description:"kalshi or polymarket"}),marketId:o.String({description:"Market ticker"}),marketTitle:o.String({description:"Human-readable name"}),direction:o.String({description:"yes or no"}),targetQuantity:o.Number({description:"Number of contracts"}),maxPrice:o.Optional(o.Number({description:"Max price in cents (1-99)"})),triggerType:o.Optional(o.String({description:"immediate, price_below, price_above, time"})),triggerPrice:o.Optional(o.Number({description:"Price trigger threshold in cents"})),triggerAt:o.Optional(o.String({description:"ISO timestamp for time trigger"})),softCondition:o.Optional(o.String({description:"Natural language condition evaluated by LLM before execution"})),rationale:o.Optional(o.String({description:"Why this trade"})),autoExecute:o.Optional(o.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(t,n)=>{const i=await e.createIntent({...n,source:"telegram",expireAt:new Date(Date.now()+864e5).toISOString()});return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"list_intents",label:"List Intents",description:"List execution intents — pending, armed, triggered, filled.",parameters:o.Object({activeOnly:o.Optional(o.Boolean({description:"Only active (default true)"}))}),execute:async(t,n)=>{const i=await e.listIntents({active:!1!==n.activeOnly});return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"cancel_intent",label:"Cancel Intent",description:"Cancel an active intent.",parameters:o.Object({intentId:o.String({description:"Intent ID"})}),execute:async(t,n)=>{const i=await e.cancelIntentAPI(n.intentId);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime is running.",parameters:l,execute:async()=>{const{existsSync:t,readFileSync:i}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:a}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=a(s(),".sf","runtime.pid");let o=!1,c="";if(t(r)){c=i(r,"utf-8").trim();try{process.kill(parseInt(c),0),o=!0}catch{}}const l=await e.listIntents({active:!0});return{content:[{type:"text",text:JSON.stringify({running:o,pid:o?c:null,...l},null,2)}],details:{}}}},{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon.",parameters:l,execute:async()=>{const{existsSync:e,readFileSync:t,mkdirSync:i,openSync:a}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:r}=await Promise.resolve().then(n.t.bind(n,70857,23)),{spawn:o}=await Promise.resolve().then(n.t.bind(n,35317,23)),c=s(r(),".sf","runtime.pid"),l=s(r(),".sf","runtime.log");if(e(c)){const e=t(c,"utf-8").trim();try{return process.kill(parseInt(e),0),{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{}}i(s(r(),".sf"),{recursive:!0});const d=a(l,"a");return o(process.execPath,[process.argv[1],"runtime","start"],{detached:!0,stdio:["ignore",d,d],env:{...process.env}}).unref(),await new Promise(e=>setTimeout(e,1e3)),{content:[{type:"text",text:`Runtime started. Log: ${l}`}],details:{}}}},{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:l,execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:i}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:a}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=a(s(),".sf","runtime.pid");if(!e(r))return{content:[{type:"text",text:"No runtime running."}],details:{}};const o=t(r,"utf-8").trim();try{return process.kill(parseInt(o),"SIGTERM"),i(r),{content:[{type:"text",text:`Runtime stopped (PID ${o}).`}],details:{}}}catch{try{i(r)}catch{}return{content:[{type:"text",text:"Runtime was not running (stale PID removed)."}],details:{}}}}},{name:"daemon_command",label:"Daemon Command",description:"Send command to a running daemon. Actions: pause, resume, scan_now.",parameters:o.Object({target:o.String({description:"Target: runtime, telegram, watch"}),action:o.String({description:"Command: pause, resume, scan_now"})}),execute:async(e,t)=>{const{writeMessage:i}=await n.e(563).then(n.bind(n,9563)),a=i({from:"agent",to:t.target,type:"command",priority:"normal",payload:{action:t.action},ttl:3600});return{content:[{type:"text",text:`Command sent to ${t.target}: ${t.action} (msg ${a})`}],details:{}}}},{name:"set_wake_condition",label:"Set Wake Condition",description:"Set a condition for daemons to alert you. Types: price, time, llm.",parameters:o.Object({description:o.String({description:"Human-readable description"}),type:o.String({description:"price, time, or llm"}),condition:o.Any({description:"Condition config"}),priority:o.Optional(o.String())}),execute:async(e,t)=>{const{saveWakeCondition:i}=await n.e(563).then(n.bind(n,9563)),{randomBytes:a}=await Promise.resolve().then(n.t.bind(n,76982,23)),s={id:a(8).toString("hex"),createdAt:(new Date).toISOString(),description:t.description,type:t.type,[`${t.type}Condition`]:t.condition,alertChannels:["bus","telegram"],priority:t.priority||"normal",maxFires:-1,firedCount:0,lastFiredAt:null,expiresAt:null,active:!0};return i(s),{content:[{type:"text",text:`Wake condition set: "${t.description}" (${s.id})`}],details:{}}}},{name:"check_daemon_alerts",label:"Check Alerts",description:"Read alerts from running daemons.",parameters:l,execute:async()=>{const{readMessages:e,deleteMessage:t}=await n.e(563).then(n.bind(n,9563)),i=e("agent","outbox");return 0===i.length?{content:[{type:"text",text:"No new daemon alerts."}],details:{}}:{content:[{type:"text",text:i.map(e=>(t(e.id,"outbox"),`[${e.priority}] ${e.from}: ${e.payload.summary||JSON.stringify(e.payload)}`)).join("\n")}],details:{}}}},{name:"schedule_wake",label:"Schedule Wake",description:"Schedule a self-wake: after N minutes, perform an action. Can repeat.",parameters:o.Object({delayMinutes:o.Number({description:"Minutes from now"}),action:o.String({description:"prompt, tool, or check"}),prompt:o.Optional(o.String({description:"Prompt text (for action=prompt)"})),repeatMinutes:o.Optional(o.Number({description:"Repeat interval in minutes"})),context:o.Optional(o.String({description:"Why this wake"}))}),execute:async(e,i)=>{const{scheduleWake:a}=await n.e(563).then(n.bind(n,9563)),s=a({...i,thesisId:t});return{content:[{type:"text",text:`Wake scheduled: ${s.id} fires at ${s.fireAt}${i.repeatMinutes?` (repeats every ${i.repeatMinutes}m)`:""}`}],details:{}}}},{name:"list_wakes",label:"List Wakes",description:"List all scheduled self-wakes.",parameters:l,execute:async()=>{const{listWakes:e}=await n.e(563).then(n.bind(n,9563)),t=e();return 0===t.length?{content:[{type:"text",text:"No scheduled wakes."}],details:{}}:{content:[{type:"text",text:t.map(e=>`${e.id.slice(0,8)} ${e.firedAt?"FIRED":"PENDING"} at ${e.fireAt} — ${e.context||e.action}`).join("\n")}],details:{}}}},{name:"cancel_wake",label:"Cancel Wake",description:"Cancel a scheduled wake.",parameters:o.Object({wakeId:o.String({description:"Wake ID"})}),execute:async(e,t)=>{const{cancelWake:i}=await n.e(563).then(n.bind(n,9563));return{content:[{type:"text",text:i(t.wakeId)?"Cancelled.":"Not found."}],details:{}}}},{name:"send_alert",label:"Send Alert",description:"Push an alert to Telegram and/or daemon bus.",parameters:o.Object({message:o.String({description:"Alert message"}),priority:o.Optional(o.String({description:"low | normal | high | critical"}))}),execute:async(e,t)=>{try{const{writeMessage:e}=await n.e(563).then(n.bind(n,9563));return e({from:"agent",to:"all",type:"alert",priority:t.priority||"high",payload:{summary:t.message},ttl:7200}),{content:[{type:"text",text:`Alert sent: "${t.message}"`}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}}),h}(e,t.thesisId,y),b=d.model||"anthropic/claude-sonnet-4.6";let w;try{w=l("openrouter",b)}catch{w={modelId:b,provider:"openrouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",id:b,name:b,inputPrice:0,outputPrice:0,contextWindow:2e5,supportsImages:!0,supportsTools:!0,headers:{"HTTP-Referer":"https://simplefunctions.dev","X-Title":"SimpleFunctions"}}}h&&(w.baseUrl=`${m}/api/proxy`);const S=(y.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.market||"").slice(0,35)} | ${e.venue||"kalshi"} | mkt ${e.marketPrice}¢ → thesis ${e.thesisPrice}¢ | edge ${e.edge>0?"+":""}${e.edge}`).join("\n")||" (no edges)",k=(y.causalTree?.nodes||[]).filter(e=>0===e.depth||!e.depth).slice(0,5).map(e=>` ${e.id} ${(e.label||"").slice(0,35)} — ${Math.round(100*(e.probability||.5))}%`).join("\n")||" (no causal tree)",_=new s({initialState:{systemPrompt:`You are a prediction market trading assistant on Telegram. Your job is to help the user see reality clearly and make correct trading decisions.\n\n## Framework\nEdge = thesis price - market price. Positive = market underprices.\nEdge types: [consensus] depth>=500 real opponents, [attention] depth<100 illusory, [timing] market lags, [risk_premium] platform risk. Tag when reporting.\nPrice: depth >= 500 = consensus, < 100 = unreliable, spread > 5 = noisy.\n\n## Rules\n- When reporting an edge, tag it: [consensus] [attention] [timing] [risk_premium].\n- If any kill condition is triggered or approaching, lead with that.\n- If nothing material to do, say "quiet — no action needed." Don't pad.\n- Keep Telegram messages SHORT — bullet points, no walls of text.\n- Prices in cents (¢). P&L in dollars ($). Don't re-convert tool output units.\n- Call tools for fresh data. Never guess prices or P&L from this prompt.\n- Use search_x for X/Twitter sentiment. Use x_volume for discussion spikes. Use x_account to track key people.\n- Use heartbeat_config to view/adjust scan intervals, model tier, budget cap, or check cost breakdown.\n- Use monitor_the_situation to scrape URLs and cross-reference with markets. Use enrich_content for text-only analysis.\n- Use get_world_state for broad situational awareness (~800 tokens).\n- Use create_skill / list_skills / browse_public_skills / fork_skill to manage agent skills.\n- Use fork_thesis to fork a public thesis (copies thesis + causal tree).\n- fs_read/fs_write/fs_list/fs_search/fs_delete: workspace. Write notes proactively. Shared with TUI.\n- calculate: precise math. send_alert: push to Telegram/bus. schedule_wake / list_wakes / cancel_wake: self-scheduling.\n- create_intent / list_intents / cancel_intent: execution intents with triggers.\n- runtime_start / runtime_stop / runtime_status: local execution daemon.\n- daemon_command / set_wake_condition / check_daemon_alerts: smart daemon control.\n- Live State shows positions/edges each turn — use it directly, don't re-fetch.\n- If user mentions news, inject_signal immediately. Don't ask "should I?"\n- If user says "evaluate" or "run it", trigger immediately.\n- Don't end with "anything else?" — user will ask.\n- Use Chinese if user writes Chinese, English if English.\n${d.tradingEnabled?"- Trading ENABLED. You have place_order and cancel_order. ALWAYS confirm before placing.":"- Trading DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current State\nThesis: ${(y.thesis||y.rawThesis||"N/A").slice(0,200)}\nID: ${t.thesisId.slice(0,8)} | Confidence: ${x}%\n\nCausal nodes:\n${k}\n\nTop edges:\n${S}\n\n${y.lastEvaluation?.summary?`Latest eval: ${y.lastEvaluation.summary.slice(0,200)}`:""}`,model:w,tools:f,thinkingLevel:"off"},streamFn:o,getApiKey:e=>"openrouter"===e?g:void 0});if(t.agentMessages.length>0)try{_.replaceMessages(t.agentMessages)}catch{}else if(t.thesisId)try{const e=(0,a.readRecentContext)(t.thesisId,30);if(e.length>0){const t=[];for(const n of e)"user"===n.role?t.push({role:"user",content:n.content}):"assistant"===n.role&&t.push({role:"assistant",content:n.content});const n=[];for(const e of t)0!==n.length&&n[n.length-1].role===e.role||n.push(e);if(n.length>0)try{_.replaceMessages(n)}catch{}}}catch{}return t.agent=_,_}}};
|