@spfunctions/cli 1.7.28 → 1.7.31

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- (()=>{var e={87783:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cached=async function(e,t,o){const s=n.get(e);if(s&&Date.now()<s.expiry)return s.data;try{const s=await o();return n.set(e,{data:s,expiry:Date.now()+t}),s}catch(e){if(s)return s.data;throw e}},t.invalidate=function(e){n.delete(e)},t.invalidateAll=function(){n.clear()};const n=new Map},19218:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SFClient=void 0,t.kalshiFetchAllSeries=async function(){const e=await o("/series",{include_volume:"true"});return e.series||[]},t.kalshiFetchEvents=async function(e){const t=await o("/events",{series_ticker:e,status:"open",with_nested_markets:"true",limit:"200"});return t.events||[]},t.kalshiFetchMarket=async function(e){const t=await o(`/markets/${e}`);return t.market||t},t.kalshiFetchMarketsBySeries=async function(e){const t=await o("/markets",{series_ticker:e,status:"open",limit:"200"});return t.markets||[]},t.kalshiFetchMarketsByEvent=async function(e){const t=await o("/markets",{event_ticker:e,status:"open",limit:"1000"});return t.markets||[]},t.fetchGlobalContext=i,t.fetchQuery=async function(e){const t=await fetch(`${s}/api/public/query?q=${encodeURIComponent(e)}`);if(!t.ok)throw new Error(`Query API error: ${t.status}`);return t.json()},t.fetchTraditionalMarkets=async function(){const e=await i();return e.traditionalMarkets||[]};const n="https://api.elections.kalshi.com/trade-api/v2";async function o(e,t){const o=new URL(`${n}${e}`);if(t)for(const[e,n]of Object.entries(t))void 0!==n&&""!==n&&o.searchParams.set(e,n);const s=await fetch(o.toString());if(!s.ok)throw new Error(`Kalshi API ${s.status}: ${await s.text()}`);return s.json()}t.SFClient=class{apiKey;baseUrl;constructor(e,t){if(this.apiKey=e||process.env.SF_API_KEY||"",this.baseUrl=(t||process.env.SF_API_URL||"https://simplefunctions.dev").replace(/\/$/,""),!this.apiKey)throw new Error("API key required. Set SF_API_KEY or use --api-key")}async request(e,t,n){const o=`${this.baseUrl}${t}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},i=await fetch(o,{method:e,headers:s,body:n?JSON.stringify(n):void 0});if(!i.ok){let e=null;try{const t=await i.text();e=t?JSON.parse(t):null}catch{}const t=new Error(e?.error||e?.message||`API error ${i.status}`);throw t.status=i.status,t.code=e?.code||`HTTP_${i.status}`,t.details=e,t}return i.json()}async listTheses(){return this.request("GET","/api/thesis")}async getThesis(e){return this.request("GET",`/api/thesis/${e}`)}async getContext(e){return this.request("GET",`/api/thesis/${e}/context`)}async createThesis(e,t=!0){return this.request("POST",`/api/thesis/create?sync=${t}`,{rawThesis:e})}async injectSignal(e,t,n,o="cli"){return this.request("POST",`/api/thesis/${e}/signal`,{type:t,content:n,source:o})}async evaluate(e){return this.request("POST",`/api/thesis/${e}/evaluate`)}async getHeartbeatConfig(e){return this.request("GET",`/api/thesis/${e}/heartbeat`)}async updateHeartbeatConfig(e,t){return this.request("PATCH",`/api/thesis/${e}/heartbeat`,t)}async getFeed(e=24,t=200){return this.request("GET",`/api/feed?hours=${e}&limit=${t}`)}async getChanges(e,t){return this.request("GET",`/api/thesis/${e}/changes?since=${encodeURIComponent(t)}`)}async updateThesis(e,t){return this.request("PATCH",`/api/thesis/${e}`,t)}async publish(e,t,n){return this.request("POST",`/api/thesis/${e}/publish`,{slug:t,description:n})}async unpublish(e){return this.request("DELETE",`/api/thesis/${e}/publish`)}async augmentTree(e,t=!1){const n=t?"?dryRun=true":"";return this.request("POST",`/api/thesis/${e}/augment${n}`)}async getStrategies(e,t){const n=t?`?status=${t}`:"";return this.request("GET",`/api/thesis/${e}/strategies${n}`)}async createStrategyAPI(e,t){return this.request("POST",`/api/thesis/${e}/strategies`,t)}async updateStrategyAPI(e,t,n){return this.request("PATCH",`/api/thesis/${e}/strategies/${t}`,n)}async deleteStrategyAPI(e,t){return this.request("DELETE",`/api/thesis/${e}/strategies/${t}`)}async createIntent(e){return this.request("POST","/api/intents",e)}async listIntents(e){const t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.active&&t.set("active","true");const n=t.toString();return this.request("GET","/api/intents"+(n?"?"+n:""))}async getIntentDetail(e){return this.request("GET",`/api/intents/${e}`)}async cancelIntentAPI(e){return this.request("DELETE",`/api/intents/${e}`)}async searchX(e,t){const n=t?.mode||"summary",o=t?.hours||24,s=t?.limit||20;return this.request("GET",`/api/x/search?q=${encodeURIComponent(e)}&mode=${n}&hours=${o}&limit=${s}`)}async getXVolume(e,t){const n=t?.hours||72,o=t?.granularity||"hour";return this.request("GET",`/api/x/volume?q=${encodeURIComponent(e)}&hours=${n}&granularity=${o}`)}async searchXNews(e,t){const n=t?.limit||10;return this.request("GET",`/api/x/news?q=${encodeURIComponent(e)}&limit=${n}`)}async getXAccount(e,t){const n=e.replace(/^@/,""),o=t?.hours||24,s=t?.limit||20;return this.request("GET",`/api/x/account?username=${n}&hours=${o}&limit=${s}`)}};const s="https://simplefunctions.dev";async function i(){const e=await fetch(`${s}/api/public/context`);if(!e.ok)throw new Error(`Context API error: ${e.status}`);return e.json()}},83969:function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.agentCommand=async function(e,t){const o=t?.modelKey||process.env.OPENROUTER_API_KEY,s=process.env.SF_API_KEY,i=process.env.SF_API_URL||"https://simplefunctions.dev",r=!o&&!!s,h=o||s,m=r?`${i}/api/proxy`:"https://openrouter.ai/api/v1";h||(console.error("Need an API key to power the agent LLM."),console.error(""),console.error(" Option 1 (recommended): sf login"),console.error(" Option 2: Get an OpenRouter key at https://openrouter.ai/keys"),console.error(" export OPENROUTER_API_KEY=sk-or-v1-..."),console.error(" sf agent --model-key sk-or-v1-..."),console.error(" sf setup (saves to ~/.sf/config.json)"),process.exit(1));if(r)console.log(" Using SimpleFunctions LLM proxy (no OpenRouter key needed)");else try{(await fetch("https://openrouter.ai/api/v1/auth/key",{headers:{Authorization:`Bearer ${h}`},signal:AbortSignal.timeout(8e3)})).ok||(console.error("OpenRouter API key is invalid or expired."),console.error("Get a new key at https://openrouter.ai/keys"),process.exit(1))}catch(e){const t=e instanceof Error?e.message:String(e);t.includes("timeout")||console.warn(`Warning: Could not verify OpenRouter key (${t}). Continuing anyway.`)}const y=new a.SFClient;let $,S=e||null,x=!1;if(!S){let e=[];try{const t=await y.listTheses();e=(t.theses||t).filter(e=>"active"===e.status)}catch{e=[]}if(0===e.length)x=!0;else if(1===e.length)S=e[0].id;else if(process.stdin.isTTY&&!t?.noTui){const t=await async function(e,t=!1){return new Promise(n=>{let o=0;const s=[];t&&s.push({id:"_explorer",conf:-1,title:"Explorer mode — no thesis, full market access"});for(const t of e){const e="number"==typeof t.confidence?Math.round(100*t.confidence):0,n=(t.rawThesis||t.thesis||t.title||"").slice(0,55);s.push({id:t.id,conf:e,title:n})}const i=process.stdout.write.bind(process.stdout);function r(){i(""),i("\n Select thesis\n\n");for(let e=0;e<s.length;e++){const t=s[e],n=e===o,r=n?" › ":" ";if("_explorer"===t.id){const e=n?`${t.title}`:`${t.title}`;i(`${r}${e}\n`)}else{const e=n?`${t.id.slice(0,8)}`:`${t.id.slice(0,8)}`,o=`${t.conf}%`,s=n?`${t.title}`:`${t.title}`;i(`${r}${e} ${o} ${s}\n`)}}i("\n ↑↓ navigate · enter select")}i("[?1049h"),i("[?25l"),r(),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");const a=e=>{const t=Buffer.from(e);27===t[0]&&91===t[1]&&65===t[2]?(o=(o-1+s.length)%s.length,r()):27===t[0]&&91===t[1]&&66===t[2]?(o=(o+1)%s.length,r()):"k"===e?(o=(o-1+s.length)%s.length,r()):"j"===e?(o=(o+1)%s.length,r()):"\r"===e||"\n"===e?(c(),n(s[o].id)):3===t[0]&&(c(),process.exit(0))};function c(){process.stdin.removeListener("data",a),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),i("[?25h"),i("[?1049l")}process.stdin.on("data",a)})}(e,!0);"_explorer"===t?x=!0:S=t}else S=e[0].id}if(x){const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));$=await e(),$._explorerMode=!0}else $=await y.getContext(S);if(t?.noTui)return async function(e){const{openrouterKey:t,sfClient:o,resolvedThesisId:s,opts:i,useProxy:r,llmBaseUrl:p,sfApiKey:h,sfApiUrl:m}=e;let y=e.latestContext;const $=await Promise.resolve().then(n.t.bind(n,23785,23)),w=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),k=await Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653)),{getModel:b,streamSimple:v,Type:_}=w,{Agent:S}=k,x=i?.model||"anthropic/claude-sonnet-4.6";let C=x.replace(/^openrouter\//,"");function O(e){let t;try{t=b("openrouter",e)}catch{t={modelId:e,provider:"openrouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",id:e,name:e,inputPrice:0,outputPrice:0,contextWindow:2e5,supportsImages:!0,supportsTools:!0}}return r&&(t.baseUrl=p),t}let I=O(C);const P=_.Object({thesisId:_.String({description:"Thesis ID"})}),T=_.Object({thesisId:_.String({description:"Thesis ID"}),content:_.String({description:"Signal content"}),type:_.Optional(_.String({description:"Signal type: news, user_note, external"}))}),E=_.Object({query:_.Optional(_.String({description:"Keyword search"})),series:_.Optional(_.String({description:"Series ticker"})),market:_.Optional(_.String({description:"Market ticker"}))}),A=_.Object({query:_.String({description:"Search keywords"})}),M=_.Object({}),R=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:P,execute:async(e,t)=>{const n=await o.getContext(t.thesisId);return y=n,{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"global_context",label:"Market Snapshot",description:"Global market snapshot — top movers, expiring contracts, milestones, liquidity, signals. No thesis needed.",parameters:M,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 knowledge search. Returns structured answer with live prices, thesis data, key factors.",parameters:_.Object({q:_.String({description:"Natural language query"})}),execute:async(e,t)=>{const{fetchQuery:o}=await Promise.resolve().then(n.bind(n,19218)),s=await o(t.q);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"get_markets",label:"Traditional Markets",description:"Traditional market prices via Databento: SPY, VIX, Treasury, Gold, Oil. Daily close + change.",parameters:M,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:"Inject Signal",description:"Inject a signal into the thesis",parameters:T,execute:async(e,t)=>{const n=await o.injectSignal(t.thesisId,t.type||"user_note",t.content);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"trigger_evaluation",label:"Evaluate",description:"Trigger a deep evaluation cycle",parameters:P,execute:async(e,t)=>{const n=await o.evaluate(t.thesisId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"scan_markets",label:"Scan Markets",description:"Search Kalshi prediction markets",parameters:E,execute:async(e,t)=>{let n;if(t.market)n=await(0,a.kalshiFetchMarket)(t.market);else if(t.series)n=await(0,a.kalshiFetchMarketsBySeries)(t.series);else if(t.query){const e=await(0,a.kalshiFetchAllSeries)(),o=t.query.toLowerCase().split(/\s+/);n=e.filter(e=>o.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,15)}else n={error:"Provide query, series, or market"};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"list_theses",label:"List Theses",description:"List all theses",parameters:M,execute:async()=>{const e=await o.listTheses();return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}},{name:"get_positions",label:"Get Positions",description:"Get Kalshi positions with live prices",parameters:M,execute:async()=>{const e=await(0,c.getPositions)();if(!e)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};for(const t of e){const e=await(0,c.getMarketPrice)(t.ticker);null!==e&&(t.current_value=e,t.unrealized_pnl=Math.round((e-t.average_price_paid)*t.quantity))}const t=e.map(e=>({ticker:e.ticker,side:e.side,quantity:e.quantity,avg_price:`${e.average_price_paid}¢`,current_price:`${e.current_value}¢`,unrealized_pnl:`$${(e.unrealized_pnl/100).toFixed(2)}`,total_cost:`$${(e.total_cost/100).toFixed(2)}`,realized_pnl:`$${(e.realized_pnl/100).toFixed(2)}`}));return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"web_search",label:"Web Search",description:"Search latest news and information",parameters:A,execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY;if(!n&&!(!n&&h))return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let o;if(o=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:5,search_depth:"basic",include_answer:!0})}):await fetch(`${m}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({query:t.query,max_results:5,search_depth:"basic",include_answer:!0})}),!o.ok)return{content:[{type:"text",text:`Search failed: ${o.status}`}],details:{}};const s=await o.json(),i=(s.results||[]).map(e=>`[${e.title}](${e.url})\n${e.content?.slice(0,200)}`).join("\n\n");return{content:[{type:"text",text:`${s.answer?`Summary: ${s.answer}\n\n---\n\n`:""}${i}`}],details:{}}}},{name:"get_milestones",label:"Milestones",description:"Get upcoming events from Kalshi calendar. Use to check economic releases, political events, or other catalysts.",parameters:_.Object({hours:_.Optional(_.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:_.Optional(_.String({description:"Filter by category (e.g. Economics, Politics, Sports)"}))}),execute:async(e,t)=>{const n=t.hours||168,o=new Date,s=`https://api.elections.kalshi.com/trade-api/v2/milestones?limit=200&minimum_start_date=${o.toISOString()}`+(t.category?`&category=${t.category}`:""),i=await fetch(s,{headers:{Accept:"application/json"}});if(!i.ok)return{content:[{type:"text",text:`Milestones API error: ${i.status}`}],details:{}};const r=await i.json(),a=o.getTime()+36e5*n,c=(r.milestones||[]).filter(e=>new Date(e.start_date).getTime()<=a).slice(0,30).map(e=>({title:e.title,category:e.category,start_date:e.start_date,related_event_tickers:e.related_event_tickers,hours_until:Math.round((new Date(e.start_date).getTime()-o.getTime())/36e5)}));return{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}}},{name:"get_forecast",label:"Forecast",description:"Get market distribution (P50/P75/P90 percentile history) for a Kalshi event.",parameters:_.Object({eventTicker:_.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:_.Optional(_.Number({description:"Days of history (default 7)"}))}),execute:async(e,t)=>{const{getForecastHistory:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=t.days||7,i=await fetch(`https://api.elections.kalshi.com/trade-api/v2/events/${t.eventTicker}`,{headers:{Accept:"application/json"}});if(!i.ok)return{content:[{type:"text",text:`Event not found: ${t.eventTicker}`}],details:{}};const r=await i.json(),a=r.event?.series_ticker;if(!a)return{content:[{type:"text",text:`No series_ticker for ${t.eventTicker}`}],details:{}};const c=await o({seriesTicker:a,eventTicker:t.eventTicker,percentiles:[5e3,7500,9e3],startTs:Math.floor((Date.now()-864e5*s)/1e3),endTs:Math.floor(Date.now()/1e3),periodInterval:1440});return c&&0!==c.length?{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}:{content:[{type:"text",text:"No forecast data available"}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled (resolved) contracts with P&L.",parameters:_.Object({ticker:_.Optional(_.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getSettlements:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await o({limit:100,ticker:t.ticker});return s?{content:[{type:"text",text:JSON.stringify(s.settlements,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance and portfolio value.",parameters:M,execute:async()=>{const{getBalance:e}=await Promise.resolve().then(n.t.bind(n,96139,23)),t=await e();return t?{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_orders",label:"Orders",description:"Get current resting orders on Kalshi.",parameters:_.Object({status:_.Optional(_.String({description:"Filter by status: resting, canceled, executed. Default: resting"}))}),execute:async(e,t)=>{const{getOrders:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await o({status:t.status||"resting",limit:100});return s?{content:[{type:"text",text:JSON.stringify(s.orders,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_fills",label:"Fills",description:"Get recent trade fills (executed trades) on Kalshi.",parameters:_.Object({ticker:_.Optional(_.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getFills:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await o({ticker:t.ticker,limit:50});return s?{content:[{type:"text",text:JSON.stringify(s.fills,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_liquidity",label:"Liquidity Scanner",description:"Scan orderbook liquidity for a topic across Kalshi + Polymarket. Returns spread, depth, liquidity scores. Topics: "+Object.keys(d.TOPIC_SERIES).join(", "),parameters:_.Object({topic:_.String({description:"Topic to scan (e.g. oil, crypto, fed, geopolitics)"})}),execute:async(e,t)=>{const n=t.topic.toLowerCase(),o=d.TOPIC_SERIES[n];if(!o)return{content:[{type:"text",text:`Unknown topic "${t.topic}". Available: ${Object.keys(d.TOPIC_SERIES).join(", ")}`}],details:{}};const s=[];for(const e of o)try{const t=`https://api.elections.kalshi.com/trade-api/v2/markets?series_ticker=${e}&status=open&limit=200`,n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)continue;const o=(await n.json()).markets||[],i=await Promise.allSettled(o.slice(0,20).map(e=>(0,c.getPublicOrderbook)(e.ticker).then(t=>({ticker:e.ticker,title:e.title,ob:t}))));for(const e of i){if("fulfilled"!==e.status||!e.value.ob)continue;const{ticker:t,title:n,ob:o}=e.value,i=(o.yes_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),r=(o.no_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),a=i[0]?.price||0,c=r.length>0?100-r[0].price:100,l=c-a,d=i.slice(0,3).reduce((e,t)=>e+t.qty,0)+r.slice(0,3).reduce((e,t)=>e+t.qty,0),u=l<=2&&d>=500?"high":l<=5&&d>=100?"medium":"low";s.push({venue:"kalshi",ticker:t,title:(n||"").slice(0,50),bestBid:a,bestAsk:c,spread:l,depth:Math.round(d),liquidityScore:u})}}catch{}try{const e=await(0,l.polymarketSearch)(n,5);for(const t of e)for(const e of(t.markets||[]).slice(0,5)){if(!e.active||e.closed||!e.clobTokenIds)continue;const n=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!n)continue;const o=await(0,l.polymarketGetOrderbookWithDepth)(n[0]);o&&s.push({venue:"polymarket",ticker:(e.question||t.title).slice(0,50),bestBid:o.bestBid,bestAsk:o.bestAsk,spread:o.spread,depth:o.bidDepthTop3+o.askDepthTop3,liquidityScore:o.liquidityScore})}}catch{}return s.sort((e,t)=>e.spread-t.spread),{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"inspect_book",label:"Orderbook",description:'Get orderbook depth, spread, and liquidity. Returns a status field per market: "ok", "empty_orderbook", "market_closed", or "api_error". Supports multiple tickers in one call — use tickers array for batch position checks.',parameters:_.Object({ticker:_.Optional(_.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:_.Optional(_.Array(_.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:_.Optional(_.String({description:'Search Polymarket by keyword (e.g. "oil price above 100")'}))}),execute:async(e,t)=>{const n=[],o=[];t.tickers?.length?o.push(...t.tickers):t.ticker&&o.push(t.ticker);for(const e of o)try{const t=await(0,a.kalshiFetchMarket)(e),o=t.status||"unknown";if("open"!==o&&"active"!==o)n.push({venue:"kalshi",ticker:e,title:t.title,status:"market_closed",reason:`Market status: ${o}. Orderbook unavailable for closed/settled markets.`,lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0"))});else{const o=await(0,c.getPublicOrderbook)(e),s=(o?.yes_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),i=(o?.no_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price);if(0===s.length&&0===i.length)n.push({venue:"kalshi",ticker:e,title:t.title,status:"empty_orderbook",reason:"Market open but no resting orders. Normal for illiquid/OTM contracts. Use lastPrice as reference.",lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0")),volume24h:parseFloat(t.volume_24h_fp||"0"),openInterest:parseFloat(t.open_interest_fp||"0"),expiry:t.close_time||null});else{const o=s[0]?.price||0,r=i.length>0?100-i[0].price:s[0]?s[0].price+1:100,a=r-o,c=s.slice(0,3).reduce((e,t)=>e+t.size,0)+i.slice(0,3).reduce((e,t)=>e+t.size,0),l=a<=2&&c>=500?"high":a<=5&&c>=100?"medium":"low";n.push({venue:"kalshi",ticker:e,title:t.title,status:"ok",bestBid:o,bestAsk:r,spread:a,liquidityScore:l,bidLevels:s.slice(0,5),askLevels:i.slice(0,5).map(e=>({price:100-e.price,size:e.size})),totalBidDepth:s.reduce((e,t)=>e+t.size,0),totalAskDepth:i.reduce((e,t)=>e+t.size,0),lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0")),volume24h:parseFloat(t.volume_24h_fp||"0"),openInterest:parseFloat(t.open_interest_fp||"0"),expiry:t.close_time||null})}}}catch(t){n.push({venue:"kalshi",ticker:e,status:"api_error",reason:`Kalshi API error: ${t.message}`})}if(t.polyQuery)try{const e=await(0,l.polymarketSearch)(t.polyQuery,5);for(const t of e)for(const e of(t.markets||[]).slice(0,3)){if(!e.active||e.closed||!e.clobTokenIds)continue;const o=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!o)continue;const s=await(0,l.polymarketGetOrderbookWithDepth)(o[0]);if(!s)continue;const i=(0,l.parseOutcomePrices)(e.outcomePrices);n.push({venue:"polymarket",title:e.question||t.title,bestBid:s.bestBid,bestAsk:s.bestAsk,spread:s.spread,liquidityScore:s.liquidityScore,totalBidDepth:s.totalBidDepth,totalAskDepth:s.totalAskDepth,lastPrice:i[0]?Math.round(100*i[0]):0,volume24h:e.volume24hr||0})}}catch{}return 0===n.length?{content:[{type:"text",text:"No markets found. Provide ticker (Kalshi) or polyQuery (Polymarket search)."}],details:{}}:{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"get_schedule",label:"Schedule",description:"Get exchange status (open/closed) and trading hours. Use to check if low liquidity is due to off-hours.",parameters:M,execute:async()=>{try{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:`Exchange API error: ${e.status}`}],details:{}};const t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}catch(e){return{content:[{type:"text",text:`Failed: ${e.message}`}],details:{}}}}},{name:"create_thesis",label:"Create Thesis",description:"Create a new thesis from a raw thesis statement. Returns the thesis ID, confidence, node count, and edge count.",parameters:_.Object({rawThesis:_.String({description:"The raw thesis statement to create"}),webhookUrl:_.Optional(_.String({description:"Optional webhook URL for notifications"}))}),execute:async(e,t)=>{const n=await o.createThesis(t.rawThesis,!0),s=n.thesis||n,i=s.causalTree?.nodes?.length||0,r=(s.edges||[]).length,a="number"==typeof s.confidence?Math.round(100*s.confidence):0;return{content:[{type:"text",text:`Thesis created.\nID: ${s.id}\nConfidence: ${a}%\nNodes: ${i}\nEdges: ${r}`}],details:{}}}},{name:"get_edges",label:"Get Edges",description:"Get top edges across all active theses. Returns the top 10 edges sorted by absolute edge size with ticker, market name, edge size, direction, and venue.",parameters:M,execute:async()=>{const{theses:e}=await o.listTheses(),t=(e||[]).filter(e=>"active"===e.status||"monitoring"===e.status),n=await Promise.allSettled(t.map(async e=>((await o.getContext(e.id)).edges||[]).map(t=>({...t,thesisId:e.id})))),s=[];for(const e of n)"fulfilled"===e.status&&s.push(...e.value);s.sort((e,t)=>Math.abs(t.edge||t.edgeSize||0)-Math.abs(e.edge||e.edgeSize||0));const i=s.slice(0,10).map(e=>({ticker:e.marketId||e.ticker||"-",market:e.market||e.marketTitle||"-",edge:e.edge||e.edgeSize||0,direction:e.direction||"yes",venue:e.venue||"kalshi"}));return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"get_feed",label:"Get Feed",description:"Get evaluation history with topSignal highlighting. The most important signal is surfaced first.",parameters:_.Object({hours:_.Optional(_.Number({description:"Hours of history to fetch (default 24)"}))}),execute:async(e,t)=>{const n=await o.getFeed(t.hours||24),s=Array.isArray(n)?n:n?.evaluations||n?.items||[];let i=null,r=0;for(const e of s){let t=0;const n=Math.abs(e.confidenceDelta||e.confidence_delta||0);n>0?t=100*n:e.summary?.length>50&&(t=.1),t>r&&(r=t,i=e)}const a={total:s.length};return i&&(a.topSignal={summary:i.summary||i.content||"",confidenceDelta:i.confidenceDelta||i.confidence_delta||0,evaluatedAt:i.evaluatedAt||i.evaluated_at||"",why:r>1?"Largest confidence movement":r>0?"Most substantive (no confidence change)":"Most recent"}),a.items=s,{content:[{type:"text",text:JSON.stringify(a,null,2)}],details:{}}}},{name:"get_changes",label:"Get Changes",description:"Get recent market changes detected server-side. Returns real price moves (>5¢), new contracts, and removed/settled contracts across Kalshi, Polymarket, and traditional markets. Use for situational awareness and discovering new opportunities.",parameters:_.Object({hours:_.Optional(_.Number({description:"Hours of history (default 1)"}))}),execute:async(e,t)=>{const n=t.hours||1,o=new Date(Date.now()-60*n*60*1e3).toISOString(),s=process.env.SF_API_URL||"https://simplefunctions.dev",i=await fetch(`${s}/api/changes?since=${encodeURIComponent(o)}&limit=100`);if(!i.ok)return{content:[{type:"text",text:JSON.stringify({error:`API error ${i.status}`})}],details:{}};const r=await i.json();return{content:[{type:"text",text:JSON.stringify(r,null,2)}],details:{}}}},{name:"explore_public",label:"Explore Public Theses",description:"Browse public theses from other users. No auth required. Pass a slug to get details, or omit to list all.",parameters:_.Object({slug:_.Optional(_.String({description:"Specific thesis slug, or empty to list all"}))}),execute:async(e,t)=>{const n="https://simplefunctions.dev";if(t.slug){const e=await fetch(`${n}/api/public/thesis/${t.slug}`);if(!e.ok)return{content:[{type:"text",text:`Not found: ${t.slug}`}],details:{}};const o=await e.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}const o=await fetch(`${n}/api/public/theses`);if(!o.ok)return{content:[{type:"text",text:"Failed to fetch public theses"}],details:{}};const s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"create_strategy",label:"Create Strategy",description:"Create a trading strategy for a thesis. Extract hard conditions (entryBelow/stopLoss/takeProfit as cents) and soft conditions from conversation. Called when user mentions specific trade ideas.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),marketId:_.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:_.String({description:"Human-readable market name"}),direction:_.String({description:"yes or no"}),horizon:_.Optional(_.String({description:"short, medium, or long. Default: medium"})),entryBelow:_.Optional(_.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:_.Optional(_.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:_.Optional(_.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:_.Optional(_.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:_.Optional(_.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:_.Optional(_.Number({description:"Contracts per order. Default: 50"})),softConditions:_.Optional(_.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:_.Optional(_.String({description:"Full logic description"}))}),execute:async(e,t)=>{const n=await o.createStrategyAPI(t.thesisId,{marketId:t.marketId,market:t.market,direction:t.direction,horizon:t.horizon,entryBelow:t.entryBelow,entryAbove:t.entryAbove,stopLoss:t.stopLoss,takeProfit:t.takeProfit,maxQuantity:t.maxQuantity,perOrderQuantity:t.perOrderQuantity,softConditions:t.softConditions,rationale:t.rationale,createdBy:"agent"});return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"list_strategies",label:"List Strategies",description:"List strategies for a thesis. Filter by status (active/watching/executed/cancelled/review) or omit for all.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),status:_.Optional(_.String({description:"Filter by status. Omit for all."}))}),execute:async(e,t)=>{const n=await o.getStrategies(t.thesisId,t.status);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"update_strategy",label:"Update Strategy",description:"Update a strategy (change stop loss, take profit, status, priority, etc.)",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),strategyId:_.String({description:"Strategy ID (UUID)"}),stopLoss:_.Optional(_.Number({description:"New stop loss (cents)"})),takeProfit:_.Optional(_.Number({description:"New take profit (cents)"})),entryBelow:_.Optional(_.Number({description:"New entry below trigger (cents)"})),entryAbove:_.Optional(_.Number({description:"New entry above trigger (cents)"})),status:_.Optional(_.String({description:"New status: active|watching|executed|cancelled|review"})),priority:_.Optional(_.Number({description:"New priority"})),softConditions:_.Optional(_.String({description:"Updated soft conditions"})),rationale:_.Optional(_.String({description:"Updated rationale"}))}),execute:async(e,t)=>{const{thesisId:n,strategyId:s,...i}=t,r=await o.updateStrategyAPI(n,s,i);return{content:[{type:"text",text:JSON.stringify(r)}],details:{}}}},{name:"what_if",label:"What-If",description:"Run a what-if scenario: override causal tree node probabilities and see how edges and confidence change. Zero LLM cost — pure computation.",parameters:_.Object({overrides:_.Array(_.Object({nodeId:_.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:_.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{const n=y,o=[];function s(e){for(const t of e)o.push(t),t.children?.length&&s(t.children)}const i=n.causalTree?.nodes||[];s(i);const r=i.filter(e=>0===e.depth||void 0===e.depth&&!e.id.includes(".")),a=new Map(t.overrides.map(e=>[e.nodeId,e.newProbability])),c=r.reduce((e,t)=>e+(t.probability||0)*(t.importance||0),0),l=r.reduce((e,t)=>e+(a.get(t.id)??t.probability??0)*(t.importance||0),0),d=new Map;for(const[e,t]of a.entries()){const n=o.find(t=>t.id===e);n&&n.probability>0&&d.set(e,Math.max(0,Math.min(2,t/n.probability)))}const u=(n.edges||[]).map(e=>{const t=e.relatedNodeId;let n=1;if(t){const e=[t,t.split(".").slice(0,-1).join("."),t.split(".")[0]].filter(Boolean);for(const t of e)if(d.has(t)){n=d.get(t);break}}const o=e.marketPrice||0,s=e.thesisPrice||e.thesisImpliedPrice||o,i=e.edge||e.edgeSize||0,r=Math.round(100*(o+(s-o)*n))/100,a=e.direction||"yes",c=Math.round(100*("yes"===a?r-o:o-r))/100;return{market:e.market||e.marketTitle||e.marketId,marketPrice:o,oldEdge:i,newEdge:c,delta:c-i,signal:Math.abs(c-i)<1?"unchanged":i>0&&c<0||i<0&&c>0?"REVERSED":Math.abs(c)<2?"GONE":"reduced"}}).filter(e=>"unchanged"!==e.signal),p={overrides:t.overrides.map(e=>{const t=o.find(t=>t.id===e.nodeId);return{nodeId:e.nodeId,label:t?.label||e.nodeId,oldProb:t?.probability,newProb:e.newProbability}}),confidence:{old:Math.round(100*c),new:Math.round(100*l),delta:Math.round(100*(l-c))},affectedEdges:u};return{content:[{type:"text",text:JSON.stringify(p,null,2)}],details:{}}}}];R.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:_.Object({query:_.String({description:"Search query"}),mode:_.Optional(_.String({description:'"summary" or "raw"'})),hours:_.Optional(_.Number({description:"Hours (default 24)"}))}),execute:async(e,t)=>{const n=await o.searchX(t.query,{mode:t.mode,hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_volume",label:"X Volume",description:"X discussion volume trend — total posts, velocity, peak time, timeseries.",parameters:_.Object({query:_.String({description:"Search query"}),hours:_.Optional(_.Number({description:"Hours (default 72)"}))}),execute:async(e,t)=>{const n=await o.getXVolume(t.query,{hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_news",label:"X News",description:"News stories trending on X — titles, summaries, tickers.",parameters:_.Object({query:_.String({description:"Search query"}),limit:_.Optional(_.Number({description:"Max stories (default 10)"}))}),execute:async(e,t)=>{const n=await o.searchXNews(t.query,{limit:t.limit});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_account",label:"X Account",description:"Recent posts from a specific X account.",parameters:_.Object({username:_.String({description:"X username (with or without @)"}),hours:_.Optional(_.Number({description:"Hours (default 24)"}))}),execute:async(e,t)=>{const n=await o.getXAccount(t.username,{hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,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:_.Object({thesisId:_.String({description:"Thesis ID"}),newsIntervalMin:_.Optional(_.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:_.Optional(_.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:_.Optional(_.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:_.Optional(_.Number({description:"Monthly budget (0 = unlimited)"})),paused:_.Optional(_.Boolean({description:"Pause or resume heartbeat"}))}),execute:async(e,t)=>{if(t.newsIntervalMin||t.xIntervalMin||t.evalModelTier||void 0!==t.monthlyBudgetUsd||void 0!==t.paused){const e={};t.newsIntervalMin&&(e.newsIntervalMin=t.newsIntervalMin),t.xIntervalMin&&(e.xIntervalMin=t.xIntervalMin),t.evalModelTier&&(e.evalModelTier=t.evalModelTier),void 0!==t.monthlyBudgetUsd&&(e.monthlyBudgetUsd=t.monthlyBudgetUsd),void 0!==t.paused&&(e.paused=t.paused),await o.updateHeartbeatConfig(t.thesisId,e)}const n=await o.getHeartbeatConfig(t.thesisId);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}}),R.push({name:"configure_heartbeat",label:"Configure Heartbeat",description:"Adjust the 24/7 monitoring engine: news interval, X interval, model tier, budget, pause/resume.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),newsIntervalMin:_.Optional(_.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:_.Optional(_.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:_.Optional(_.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:_.Optional(_.Number({description:"Monthly budget cap (0=unlimited)"})),paused:_.Optional(_.Boolean({description:"Pause/resume"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t,i=await o.request("PATCH",`/api/thesis/${n}/heartbeat`,s);return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"get_heartbeat_status",label:"Heartbeat Status",description:"Heartbeat config + cost summary for a thesis.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await o.request("GET",`/api/thesis/${t.thesisId}/heartbeat`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"update_thesis",label:"Update Thesis",description:"Update thesis metadata: title, status (active/paused/archived), webhookUrl.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),title:_.Optional(_.String({description:"New title"})),status:_.Optional(_.String({description:"active, paused, or archived"})),webhookUrl:_.Optional(_.String({description:"Webhook URL (HTTPS)"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t,i=await o.request("PATCH",`/api/thesis/${n}`,s);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"add_position",label:"Add Position",description:"Record a new position in a thesis for tracking.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),venue:_.String({description:"kalshi or polymarket"}),externalMarketId:_.String({description:"Market ticker"}),marketTitle:_.String({description:"Market name"}),direction:_.String({description:"yes or no"}),entryPrice:_.Number({description:"Entry price in cents"}),size:_.Optional(_.Number({description:"Contracts"})),rationale:_.Optional(_.String({description:"Why"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t,i=await o.request("POST",`/api/thesis/${n}/positions`,s);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"update_position",label:"Update Position",description:"Update position: currentPrice, edge, status (open→closed).",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),positionId:_.String({description:"Position ID"}),currentPrice:_.Optional(_.Number({description:"Current price (cents)"})),edge:_.Optional(_.Number({description:"Current edge (cents)"})),status:_.Optional(_.String({description:"open or closed"}))}),execute:async(e,t)=>{const{thesisId:n,positionId:s,...i}=t,r=await o.request("PATCH",`/api/thesis/${n}/positions/${s}`,i);return{content:[{type:"text",text:JSON.stringify(r)}],details:{}}}},{name:"get_evaluation_history",label:"Evaluation History",description:"Confidence trajectory over time — daily aggregated. For trend analysis.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await o.request("GET",`/api/thesis/${t.thesisId}/evaluations`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"update_nodes",label:"Update Nodes",description:"Directly update causal tree node probabilities. Zero LLM cost. Use for confirmed facts (lock nodes at 0.99).",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),updates:_.Array(_.Object({nodeId:_.String({description:"Node ID (e.g. n3)"}),probability:_.Number({description:"New probability (0-1)"}),reason:_.Optional(_.String({description:"Why"}))})),lock:_.Optional(_.Array(_.String({description:"Node IDs to lock"})))}),execute:async(e,t)=>{const n=await o.request("POST",`/api/thesis/${t.thesisId}/nodes/update`,{updates:t.updates,lock:t.lock});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}}),R.push({name:"get_trade_ideas",label:"Trade Ideas",description:"S&T-style trade pitches: conviction, catalyst, direction, risk. Synthesized from live market data, edges, and macro context. No auth required.",parameters:_.Object({freshness:_.Optional(_.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:_.Optional(_.String({description:"Filter: macro, geopolitics, crypto, policy, event"}))}),execute:async(e,t)=>{const n=new URLSearchParams;t.freshness&&n.set("freshness",t.freshness),t.category&&n.set("category",t.category);const o=await fetch(`https://simplefunctions.dev/api/public/ideas?${n.toString()}`);if(!o.ok)return{content:[{type:"text",text:`Ideas API error: ${o.status}`}],details:{}};const s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"create_intent",label:"Create Intent",description:"Declare an execution intent with trigger conditions. Runtime daemon evaluates triggers and executes via local keys.",parameters:_.Object({action:_.String({description:"buy or sell"}),venue:_.String({description:"kalshi or polymarket"}),marketId:_.String({description:"Market ticker"}),marketTitle:_.String({description:"Human-readable name"}),direction:_.String({description:"yes or no"}),targetQuantity:_.Number({description:"Number of contracts"}),maxPrice:_.Optional(_.Number({description:"Max price per contract in cents (1-99)"})),triggerType:_.Optional(_.String({description:"immediate, price_below, price_above, time"})),triggerPrice:_.Optional(_.Number({description:"Price trigger threshold in cents"})),rationale:_.Optional(_.String({description:"Why this trade"})),autoExecute:_.Optional(_.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(e,t)=>{const n=await o.createIntent({...t,source:"agent",expireAt:new Date(Date.now()+864e5).toISOString()});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"list_intents",label:"List Intents",description:"List execution intents — pending, armed, triggered, executing, filled.",parameters:_.Object({activeOnly:_.Optional(_.Boolean({description:"Only active intents (default true)"}))}),execute:async(e,t)=>{const n=await o.listIntents({active:!1!==t.activeOnly});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"cancel_intent",label:"Cancel Intent",description:"Cancel an active intent — stops trigger evaluation and prevents execution.",parameters:_.Object({intentId:_.String({description:"Intent ID to cancel"})}),execute:async(e,t)=>{const n=await o.cancelIntentAPI(t.intentId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}});const N=(0,u.loadConfig)();N.tradingEnabled&&R.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Shows preview and asks for confirmation.",parameters:_.Object({ticker:_.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:_.String({description:"yes or no"}),action:_.String({description:"buy or sell"}),type:_.String({description:"limit or market"}),count:_.Number({description:"Number of contracts"}),price_cents:_.Optional(_.Number({description:"Limit price in cents (1-99). Required for limit orders."}))}),execute:async(e,t)=>{const{createOrder:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await Promise.resolve().then(n.t.bind(n,23785,23)),i=t.price_cents?Math.round(Number(t.price_cents)):void 0,r=((i||99)*t.count/100).toFixed(2),a=` Order: ${t.action.toUpperCase()} ${t.count}x ${t.ticker} ${t.side.toUpperCase()} @ ${i?i+"¢":"market"} (max $${r})`;if(process.stderr.write(a+"\n"),!process.stdin.isTTY)return{content:[{type:"text",text:"Order rejected: trading requires interactive terminal (stdin is piped). Use TUI mode for trading."}],details:{}};const c=s.createInterface({input:process.stdin,output:process.stderr}),l=await new Promise(e=>c.question(" Execute? (y/n) ",e));if(c.close(),!l.toLowerCase().startsWith("y"))return{content:[{type:"text",text:"Order cancelled by user."}],details:{}};try{const e=await o({ticker:t.ticker,side:t.side,action:t.action,type:t.type,count:t.count,...i?{yes_price:i}:{}}),n=e.order||e;return{content:[{type:"text",text:`Order placed: ${n.order_id||"OK"}\nStatus: ${n.status||"-"}\nFilled: ${n.fill_count_fp||0}/${n.initial_count_fp||t.count}`}],details:{}}}catch(e){const t=e.message||String(e);return t.includes("403")?{content:[{type:"text",text:"403 Forbidden — your Kalshi key lacks write permission. Get a read+write key at kalshi.com/account/api-keys"}],details:{}}:{content:[{type:"text",text:`Order failed: ${t}`}],details:{}}}}},{name:"cancel_order",label:"Cancel Order",description:"Cancel a resting order by order ID. Executes directly (no confirmation prompt in plain mode).",parameters:_.Object({order_id:_.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{const{cancelOrder:o}=await Promise.resolve().then(n.t.bind(n,96139,23));try{return await o(t.order_id),{content:[{type:"text",text:`Order ${t.order_id} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Cancel failed: ${e.message}`}],details:{}}}}});R.push({name:"close_position",label:"Close Position",description:"Remove a position record from a thesis.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),positionId:_.String({description:"Position ID"})}),execute:async(e,t)=>{const n=await o.request("DELETE",`/api/thesis/${t.thesisId}/positions/${t.positionId}`);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"augment_tree",label:"Augment Tree",description:"Review and merge suggested causal tree nodes from evaluations.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),dryRun:_.Optional(_.Boolean({description:"Preview without applying"}))}),execute:async(e,t)=>{const n=t.dryRun?"?dryRun=true":"",s=await o.request("POST",`/api/thesis/${t.thesisId}/augment${n}`);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}}),R.push({name:"get_world_state",label:"World State",description:"Real-time world model for agents. ~800 tokens of structured state: prediction market index, traditional markets, topic summaries, divergences.",parameters:_.Object({focus:_.Optional(_.String({description:'Comma-separated topics (e.g. "energy,geopolitics")'}))}),execute:async(e,t)=>{const n=t.focus?`?focus=${encodeURIComponent(t.focus)}`:"",o=process.env.SF_API_URL||"https://simplefunctions.dev",s=await fetch(`${o}/api/agent/world${n}`);if(!s.ok)return{content:[{type:"text",text:`World API error: ${s.status}`}],details:{}};return{content:[{type:"text",text:await s.text()}],details:{}}}},{name:"get_world_delta",label:"World Delta",description:"Incremental world state update — only what changed. ~30-50 tokens.",parameters:_.Object({since:_.Optional(_.String({description:'"30m", "1h", "6h", "24h" or ISO timestamp (default "1h")'}))}),execute:async(e,t)=>{const n=t.since||"1h",o=process.env.SF_API_URL||"https://simplefunctions.dev",s=await fetch(`${o}/api/agent/world/delta?since=${encodeURIComponent(n)}`);if(!s.ok)return{content:[{type:"text",text:`Delta API error: ${s.status}`}],details:{}};return{content:[{type:"text",text:await s.text()}],details:{}}}},{name:"monitor_the_situation",label:"Monitor",description:"Universal web intelligence. Scrape any URL (Firecrawl), analyze with any LLM, cross-reference with 9,706 prediction markets.",parameters:_.Object({source:_.Object({action:_.String({description:"scrape, crawl, search, map, extract, batch_scrape"}),url:_.Optional(_.String({description:"Target URL"})),query:_.Optional(_.String({description:"Search query (for search action)"}))}),analysis:_.Optional(_.Object({model:_.Optional(_.String({description:"OpenRouter model"})),prompt:_.Optional(_.String({description:"Analysis prompt"}))})),enrich:_.Optional(_.Object({topics:_.Optional(_.Array(_.String())),includeIndex:_.Optional(_.Boolean())})),webhook:_.Optional(_.Object({url:_.String({description:"Webhook URL"}),format:_.Optional(_.String({description:"full, brief, or tweetable"}))}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",o=await fetch(`${n}/api/monitor-the-situation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)return{content:[{type:"text",text:`Monitor API error: ${o.status}`}],details:{}};const s=await o.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:_.Object({content:_.String({description:"Text to cross-reference"}),topics:_.Optional(_.Array(_.String()))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",o=await fetch(`${n}/api/monitor-the-situation/enrich`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)return{content:[{type:"text",text:`Enrich API error: ${o.status}`}],details:{}};const s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}}),R.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime is running and show active intents.",parameters:_.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=s(i(),".sf","runtime.pid");let a=!1,c="";if(e(r)){c=t(r,"utf-8").trim();try{process.kill(parseInt(c),0),a=!0}catch{a=!1}}const l=await o.listIntents({active:!0});return{content:[{type:"text",text:JSON.stringify({running:a,pid:a?c:null,...l},null,2)}],details:{}}}},{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon. Evaluates intent triggers and executes orders.",parameters:_.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),{spawn:i}=await Promise.resolve().then(n.t.bind(n,35317,23)),r=o(s(),".sf","runtime.pid");if(e(r)){const e=t(r,"utf-8").trim();try{return process.kill(parseInt(e),0),{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{}}if(i(process.execPath,[process.argv[1],"runtime","start"],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env}}).unref(),await new Promise(e=>setTimeout(e,1e3)),e(r)){return{content:[{type:"text",text:`Runtime started (PID ${t(r,"utf-8").trim()}). Polling every 30s.`}],details:{}}}return{content:[{type:"text",text:"Runtime starting... check runtime_status in a moment."}],details:{}}}},{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:_.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:o}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=s(i(),".sf","runtime.pid");if(!e(r))return{content:[{type:"text",text:"No runtime running."}],details:{}};const a=t(r,"utf-8").trim();try{return process.kill(parseInt(a),"SIGTERM"),o(r),{content:[{type:"text",text:`Runtime stopped (PID ${a}).`}],details:{}}}catch{try{o(r)}catch{}return{content:[{type:"text",text:"Runtime was not running (stale PID removed)."}],details:{}}}}});const L=y,D=L._explorerMode||"_explorer"===s;let K;if(D){const e=(L.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.title||"").slice(0,40)} | ${e.venue||"kalshi"} | +${e.edge}`).join("\n")||" (no edges)";K=`You are a prediction market research assistant in EXPLORER MODE — not bound to any thesis.\n\n## What you can do\n- get_world_state: real-time world model (~800 tokens), use ?focus= for deeper topic coverage\n- get_world_delta: incremental changes since last check (~30-50 tokens)\n- query: LLM-enhanced market search\n- scan_markets: search Kalshi + Polymarket\n- get_markets: traditional markets (SPY, VIX, gold, oil)\n- get_trade_ideas: S&T-style trade pitches with conviction + catalyst\n- explore_public: browse public theses\n- search_x, x_volume, x_news: X/Twitter signals\n- monitor_the_situation: scrape any URL, analyze, cross-reference with 9,706 markets\n- enrich_content: cross-reference text with prediction markets\n- get_positions: portfolio positions\n- create_intent / list_intents / cancel_intent: execution intents with triggers\n- runtime_start / runtime_stop / runtime_status: local execution daemon\n- create_thesis: create a thesis when user forms a view\n\n## CRITICAL: When the user expresses a view worth tracking, use create_thesis. After creation, confirm and continue with the new thesis context.\n\n## Rules\n- Be concise. Use tools for fresh data.\n- Use Chinese if user writes Chinese, English if English.\n- Prices in cents (¢). P&L in dollars ($).\n${N.tradingEnabled?"- Trading ENABLED.":"- Trading DISABLED."}\n\n## Market snapshot\nPublic edges:\n${e}`}else{const e=L.edges?.sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.market||"").slice(0,40)} | ${e.venue||"kalshi"} | mkt ${e.marketPrice}¢ | edge ${e.edge>0?"+":""}${e.edge}`).join("\n")||" (no edges)",t=L.causalTree?.nodes?.filter(e=>0===e.depth).map(e=>` ${e.id} ${(e.label||"").slice(0,40)} — ${Math.round(100*e.probability)}%`).join("\n")||" (no causal tree)",n="number"==typeof L.confidence?Math.round(100*L.confidence):0;K=`You are a prediction market trading assistant. Your job is not to please the user — it is to help them see reality clearly and make correct trading decisions.\n\n## Framework\nEdge = thesis price - market price. Positive = market underprices. executableEdge = edge minus spread.\n\nEdge types: "consensus_gap" (depth >= 500, real disagreement), "attention_gap" (depth < 100, illusory pricing), "timing_gap" (market lags), "risk_premium" (settlement/platform risk). Always classify when reporting edges.\nFor edges > 20 cents, state what the market must believe for it to be right.\n\nPrice reliability: depth >= 500 = consensus. depth < 100 = unreliable. spread > 5 cents = noisy. Flag illiquid markets.\n\nKill conditions: each causal node has a falsifier. Check these first when evaluating news. If triggered, override other analysis.\n\nAlways state contract expiry and next catalyst. No catalyst = flag capital lock risk.\n\nFor complex questions, chain: get_context -> inspect_book -> get_liquidity -> web_search -> search_x -> synthesize.\nUse search_x for social sentiment on any topic. Use x_volume to detect discussion spikes. Use x_account to track key people.\nUse heartbeat_config to view/adjust scan intervals, model tier, budget cap, or check cost breakdown.\n\nFlag correlated exposure across positions sharing upstream nodes. If nothing to do, say so.\n\n## Rules\n- Be concise. Use tools for fresh data. Don't guess prices.\n- You do NOT know the user's positions at start. Call get_positions before discussing trades or portfolio.\n- If user mentions news, inject_signal immediately.\n- If user says "evaluate", trigger immediately. Don't confirm.\n- Don't end with "anything else?"\n- If an edge is narrowing or disappearing, say so proactively.\n- Use Chinese if user writes Chinese, English if English.\n- Prices in cents (¢). P&L in dollars ($). Don't re-convert tool output.\n- When a trade idea emerges, create_strategy to record it.\n${N.tradingEnabled?"- Trading ENABLED. You have place_order and cancel_order tools.":"- Trading DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current State\nThesis: ${L.thesis||L.rawThesis||"N/A"}\nID: ${s} | Confidence: ${n}% | Status: ${L.status}\n\nCausal nodes:\n${t}\n\nTop edges:\n${e}\n\n${L.lastEvaluation?.summary?`Latest eval: ${L.lastEvaluation.summary.slice(0,300)}`:""}`}const j=new S({initialState:{systemPrompt:K,model:I,tools:R,thinkingLevel:"off"},streamFn:v,getApiKey:e=>"openrouter"===e?t:void 0});if(!i?.newSession){const e=g(s);if(e?.messages?.length>0)try{j.replaceMessages(e.messages),j.setSystemPrompt(K)}catch{}}let F="";if(j.subscribe(e=>{if("message_update"===e.type){const t=e.assistantMessageEvent;"text_delta"===t.type&&(process.stdout.write(t.delta),F+=t.delta)}if("message_end"===e.type&&F&&(process.stdout.write("\n"),F=""),"tool_execution_start"===e.type&&process.stderr.write(` ▸ ${e.toolName}...\n`),"tool_execution_end"===e.type){const t=e.isError?"✗":"✓";process.stderr.write(` ${t} ${e.toolName}\n`)}}),D)console.log(`SF Agent — Explorer mode | ${C}`),console.log(`Public edges: ${(L.edges||[]).length}`),console.log("Ask anything about prediction markets. Type /help for commands, /exit to quit.\n");else{const e=L.thesis||L.rawThesis||"N/A",t="number"==typeof L.confidence?Math.round(100*L.confidence):0;console.log(`SF Agent — ${s.slice(0,8)} | ${t}% | ${C}`),console.log(`Thesis: ${e.length>100?e.slice(0,100)+"...":e}`),console.log(`Edges: ${(L.edges||[]).length} | Status: ${L.status}`),console.log("Type /help for commands, /exit to quit.\n")}const q=$.createInterface({input:process.stdin,output:process.stdout,prompt:"> "});q.prompt();for await(const t of q){const n=t.trim();if(n){if("/exit"===n||"/quit"===n){try{f(s,C,j.state.messages)}catch{}return void q.close()}if("/help"!==n){if("/tree"===n){y=await o.getContext(s);const e=y.causalTree?.nodes||[];for(const t of e){const e=" ".repeat(t.depth||0);console.log(`${e}${t.id} ${(t.label||"").slice(0,60)} — ${Math.round(100*t.probability)}%`)}q.prompt();continue}if("/edges"===n){y=await o.getContext(s);const e=(y.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,15);for(const t of e){const e=t.edge>0?"+":"";console.log(` ${(t.market||"").slice(0,45).padEnd(45)} ${t.marketPrice}¢ edge ${e}${t.edge} ${t.venue}`)}q.prompt();continue}if("/eval"===n){console.log("Triggering evaluation...");const e=await o.evaluate(s);console.log(`Confidence: ${e.previousConfidence} → ${e.newConfidence}`),e.summary&&console.log(e.summary),q.prompt();continue}if(n.startsWith("/model")){const e=n.slice(6).trim();if(!e){console.log(`Current: ${C}`),q.prompt();continue}C=e.replace(/^openrouter\//,""),I=O(C),j.setModel(I),console.log(`Model: ${C}`),q.prompt();continue}try{await j.prompt(n)}catch(e){console.error(`Error: ${e.message}`)}try{f(s,C,j.state.messages)}catch{}q.prompt()}else console.log("Commands: /help /exit /tree /edges /eval /model <name>"),q.prompt()}else q.prompt()}}({openrouterKey:h,sfClient:y,resolvedThesisId:S||"_explorer",latestContext:$,useProxy:r,llmBaseUrl:m,sfApiKey:s,sfApiUrl:i,opts:t});const C=await n.e(921).then(n.bind(n,93921)),O=await 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(641),n.e(582)]).then(n.bind(n,65653)),{TUI:P,ProcessTerminal:T,Container:E,Text:A,Markdown:M,Editor:R,Loader:N,Spacer:L,CombinedAutocompleteProvider:D,truncateToWidth:K,visibleWidth:j}=C,{getModel:F,streamSimple:q,Type:U}=O,{Agent:z}=I,H=function(e){const{truncateToWidth:t,visibleWidth:n}=e;return class{text;cachedWidth;cachedLines;constructor(e){this.text=e}setText(e){this.text=e,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}render(e){return this.cachedLines&&this.cachedWidth===e||(this.cachedWidth=e,this.cachedLines=[t(this.text,e)]),this.cachedLines}}}(C),B=function(e){const{truncateToWidth:t,visibleWidth:n}=e;return class{thesisId="";confidence=0;confidenceDelta=0;pnlDollars=0;positionCount=0;edgeCount=0;topEdge="";tokens=0;cost=0;toolCount=0;modelName="";tradingEnabled=!1;exchangeOpen=null;cachedWidth;cachedLines;isExplorer=!1;setFromContext(e,t){if(e._explorerMode){this.isExplorer=!0,this.thesisId="Explorer",this.confidence=0,this.confidenceDelta=0,this.edgeCount=(e.edges||[]).length;const t=e.edges||[];if(t.length>0){const e=[...t].sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge))[0];this.topEdge=`${(e.title||"").slice(0,20)} +${Math.round(e.edge)}¢`}}else{this.isExplorer=!1,this.thesisId=(e.thesisId||"").slice(0,8),this.confidence="number"==typeof e.confidence?Math.round(100*e.confidence):"string"==typeof e.confidence?Math.round(100*parseFloat(e.confidence)):0,this.confidenceDelta=e.lastEvaluation?.confidenceDelta?Math.round(100*e.lastEvaluation.confidenceDelta):0,this.edgeCount=(e.edges||[]).length;const t=e.edges||[];if(t.length>0){const e=[...t].sort((e,t)=>Math.abs(t.edge||t.edgeSize||0)-Math.abs(e.edge||e.edgeSize||0))[0],n=(e.market||e.marketTitle||e.marketId||"").slice(0,20),o=e.edge||e.edgeSize||0;this.topEdge=`${n} ${o>0?"+":""}${Math.round(o)}¢`}}t&&t.length>0&&(this.positionCount=t.length,this.pnlDollars=t.reduce((e,t)=>e+(t.unrealized_pnl||0),0)/100),this.cachedWidth=void 0,this.cachedLines=void 0}updateConfidence(e,t){this.confidence=Math.round(100*e),this.confidenceDelta=Math.round(100*t),this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}update(){this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;this.cachedWidth=e;const o=_.zinc600(" │ ");let s;if(this.isExplorer){const e=_.emerald(w("Explorer")),t=_.zinc600(`${this.edgeCount} public edges`),n=this.topEdge?_.zinc400(this.topEdge):"";let o="";if(this.positionCount>0){const e=this.pnlDollars>=0?_.emerald(`+$${this.pnlDollars.toFixed(2)}`):_.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);o=_.zinc600(`${this.positionCount} pos `)+e}s=[e,o,t,n].filter(Boolean)}else{const e=_.emerald(this.thesisId),t=this.confidenceDelta>0?"▲":this.confidenceDelta<0?"▼":"─",n=this.confidenceDelta>0?_.emerald:this.confidenceDelta<0?_.red:_.zinc600,o=0!==this.confidenceDelta?` (${this.confidenceDelta>0?"+":""}${this.confidenceDelta})`:"",i=n(`${t} ${this.confidence}%${o}`);let r="";if(this.positionCount>0){const e=this.pnlDollars>=0?_.emerald(`+$${this.pnlDollars.toFixed(2)}`):_.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);r=_.zinc600(`${this.positionCount} pos `)+e}s=[e,i,r,_.zinc600(`${this.edgeCount} edges`),this.topEdge?_.zinc400(this.topEdge):""].filter(Boolean)}let i=_.bgZinc800(" "+t(s.join(o),e-2,"")+" ");const r=n(i);r<e&&(i+=_.bgZinc800(" ".repeat(e-r)));const a=_.zinc600(this.modelName.split("/").pop()||this.modelName),c=this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:`${this.tokens}`,l=_.zinc600(`${c} tok`),d=!0===this.exchangeOpen?_.emerald("OPEN"):!1===this.exchangeOpen?_.red("CLOSED"):_.zinc600("..."),u=this.tradingEnabled?_.amber("trading"):_.zinc600("read-only"),p=_.zinc600("/help"),h=[a,l,d,u].join(o),m=n(h),g=n(p),f=Math.max(1,e-m-g-2);let y=_.bgZinc900(" "+h+" ".repeat(f)+p+" ");const $=n(y);return $<e&&(y+=_.bgZinc900(" ".repeat(e-$))),this.cachedLines=[i,y],this.cachedLines}}}(C),J=t?.model||"anthropic/claude-sonnet-4.6";let W=J.replace(/^openrouter\//,"");function X(e){let t;try{t=F("openrouter",e)}catch{t={modelId:e,provider:"openrouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",id:e,name:e,inputPrice:0,outputPrice:0,contextWindow:2e5,supportsImages:!0,supportsTools:!0}}return r&&(t.baseUrl=m),t}let G=X(W),Y=0,V=!1,Q=null,Z=(new Date).toISOString(),ee=null,te=null,ne=null;const oe=new T,se=new P(oe),ie={heading:e=>_.zinc200(w(e)),link:e=>_.emerald(e),linkUrl:e=>_.zinc600(e),code:e=>_.zinc200(e),codeBlock:e=>_.zinc400(e),codeBlockBorder:e=>_.zinc600(e),quote:e=>_.zinc400(e),quoteBorder:e=>_.zinc600(e),hr:e=>_.zinc600(e),listBullet:e=>_.emerald(e),bold:e=>w(e),italic:e=>k(e),strikethrough:e=>v(e),underline:e=>b(e)},re={color:e=>_.zinc400(e)},ae={borderColor:e=>`${e}`,selectList:{selectedPrefix:e=>_.emerald(e),selectedText:e=>_.zinc200(e),description:e=>_.zinc600(e),scrollInfo:e=>_.zinc600(e),noMatch:e=>_.zinc600(e)}},ce=new B;ce.modelName=W,ce.tradingEnabled=(0,u.loadConfig)().tradingEnabled||!1;let le=null;try{if(le=await(0,c.getPositions)(),le)for(const e of le){const t=await(0,c.getMarketPrice)(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity))}}catch{}ce.setFromContext($,le||void 0),fetch("https://api.elections.kalshi.com/trade-api/v2/exchange/status",{headers:{Accept:"application/json"}}).then(e=>e.json()).then(e=>{ce.exchangeOpen=!!e.exchange_active,ce.update(),se.requestRender()}).catch(()=>{});const de=new L(1),ue=new L(1),pe=new E,he=new R(se,ae,{paddingX:1}),me=[{name:"help",description:"Show available commands"},{name:"tree",description:"Display causal tree"},{name:"edges",description:"Display edge/spread table"},{name:"pos",description:"Display Kalshi positions"},{name:"eval",description:"Trigger deep evaluation"},{name:"switch",description:"Switch thesis (e.g. /switch f582bf76)"},{name:"compact",description:"Compress conversation history"},{name:"new",description:"Start fresh session"},{name:"model",description:"Switch model (e.g. /model anthropic/claude-sonnet-4)"},{name:"env",description:"Show environment variable status"},{name:"clear",description:"Clear screen (keeps history)"},{name:"exit",description:"Exit agent (auto-saves)"}];(0,u.loadConfig)().tradingEnabled&&me.splice(-2,0,{name:"buy",description:"TICKER QTY PRICE — quick buy"},{name:"sell",description:"TICKER QTY PRICE — quick sell"},{name:"cancel",description:"ORDER_ID — cancel order"});const ge=(0,p.loadSkills)();for(const e of ge){const t=e.trigger.replace(/^\//,"");me.splice(-2,0,{name:t,description:`[skill] ${e.description.slice(0,50)}`})}const fe=new D(me,process.cwd());he.setAutocompleteProvider(fe),se.addChild(de),se.addChild(pe),se.addChild(he),se.addChild(ue),se.setFocus(he);se.showOverlay(ce,{anchor:"bottom-left",width:"100%",nonCapturing:!0});function ye(e){const t=new A(e,1,0);pe.addChild(t),se.requestRender()}function $e(){pe.addChild(new L(1))}function we(e){return new Promise(t=>{ye(_.amber(w("⚠ "))+_.zinc200(e)),$e(),se.requestRender(),ne={resolve:t}})}const ke=U.Object({thesisId:U.String({description:"Thesis ID (short or full UUID)"})}),be=U.Object({thesisId:U.String({description:"Thesis ID"}),content:U.String({description:"Signal content"}),type:U.Optional(U.String({description:"Signal type: news, user_note, external. Default: user_note"}))}),ve=U.Object({query:U.Optional(U.String({description:"Keyword search for Kalshi markets"})),series:U.Optional(U.String({description:"Kalshi series ticker (e.g. KXWTIMAX)"})),market:U.Optional(U.String({description:"Specific market ticker"}))}),_e=U.Object({query:U.String({description:"Search keywords"})}),Se=U.Object({}),xe=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:ke,execute:async(e,t)=>{const n=await y.getContext(t.thesisId);return $=n,ce.setFromContext(n,le||void 0),se.requestRender(),{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"global_context",label:"Market Snapshot",description:"Global market snapshot — top movers, expiring contracts, milestones, liquidity, signals. No thesis needed.",parameters:Se,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 knowledge search. Ask any question about prediction markets, macro, geopolitics. Returns structured answer with live market prices, thesis data, and key factors.",parameters:U.Object({q:U.String({description:'Natural language query (e.g. "iran oil prices", "fed rate cut 2026")'})}),execute:async(e,t)=>{const{fetchQuery:o}=await Promise.resolve().then(n.bind(n,19218)),s=await o(t.q);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"get_markets",label:"Traditional Markets",description:"Get traditional market prices via Databento: S&P 500 (SPY), VIX (VIXY), 20Y Treasury (TLT), Gold (GLD), Oil (USO). Daily close + 1-day change.",parameters:Se,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:"Inject Signal",description:"Inject a signal into the thesis (news, note, external event)",parameters:be,execute:async(e,t)=>{const n=await y.injectSignal(t.thesisId,t.type||"user_note",t.content);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"trigger_evaluation",label:"Evaluate",description:"Trigger a deep evaluation cycle (heavy model, takes longer)",parameters:ke,execute:async(e,t)=>{const n=await y.evaluate(t.thesisId);if(n.evaluation?.confidenceDelta&&Math.abs(n.evaluation.confidenceDelta)>=.01){const e=n.evaluation.confidenceDelta,t=Math.round(100*(n.evaluation.previousConfidence||0)),o=Math.round(100*(n.evaluation.newConfidence||0)),s=e>0?"▲":"▼";ye((e>0?_.emerald:_.red)(` ${s} Confidence ${t}% → ${o}% (${e>0?"+":""}${Math.round(100*e)})`)),$e(),ce.updateConfidence(n.evaluation.newConfidence,e),se.requestRender()}try{$=await y.getContext(t.thesisId),ce.setFromContext($,le||void 0),se.requestRender()}catch{}return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"scan_markets",label:"Scan Markets",description:"Search Kalshi + Polymarket prediction markets. Provide exactly one of: query (keyword search), series (Kalshi series ticker), or market (specific Kalshi ticker). Keyword search returns results from BOTH venues.",parameters:ve,execute:async(e,t)=>{if(t.market){const e=await(0,a.kalshiFetchMarket)(t.market);return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}if(t.series){const e=await(0,a.kalshiFetchMarketsBySeries)(t.series);return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}if(t.query){const e=await(0,a.kalshiFetchAllSeries)(),n=t.query.toLowerCase().split(/\s+/),o=e.filter(e=>n.some(t=>(e.title||"").toLowerCase().includes(t)||(e.ticker||"").toLowerCase().includes(t))).filter(e=>parseFloat(e.volume_24h_fp||e.volume_fp||"0")>0).sort((e,t)=>parseFloat(t.volume_24h_fp||t.volume_fp||"0")-parseFloat(e.volume_24h_fp||e.volume_fp||"0")).slice(0,10).map(e=>({venue:"kalshi",ticker:e.ticker,title:e.title,volume:e.volume_fp}));let s=[];try{const e=await(0,l.polymarketSearch)(t.query,10);for(const t of e)for(const e of(t.markets||[]).slice(0,3)){if(!e.active||e.closed)continue;const n=(0,l.parseOutcomePrices)(e.outcomePrices);s.push({venue:"polymarket",id:e.conditionId||e.id,title:e.groupItemTitle?`${t.title}: ${e.groupItemTitle}`:e.question||t.title,price:n[0]?Math.round(100*n[0]):null,volume24h:e.volume24hr,liquidity:e.liquidityNum})}}catch{}return{content:[{type:"text",text:JSON.stringify({kalshi:o,polymarket:s},null,2)}],details:{}}}return{content:[{type:"text",text:'{"error":"Provide query, series, or market parameter"}'}],details:{}}}},{name:"list_theses",label:"List Theses",description:"List all theses for the current user",parameters:Se,execute:async()=>{const e=await y.listTheses();return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}},{name:"get_positions",label:"Get Positions",description:"Get positions across Kalshi + Polymarket with live prices and PnL",parameters:Se,execute:async()=>{const e={kalshi:[],polymarket:[]},t=await(0,c.getPositions)();if(t){for(const e of t){const t=await(0,c.getMarketPrice)(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity))}Q=t,e.kalshi=t.map(e=>({venue:"kalshi",ticker:e.ticker,side:e.side,quantity:e.quantity,avg_price:`${e.average_price_paid}¢`,current_price:`${e.current_value}¢`,unrealized_pnl:`$${(e.unrealized_pnl/100).toFixed(2)}`,total_cost:`$${(e.total_cost/100).toFixed(2)}`}))}const n=(0,u.loadConfig)();if(n.polymarketWalletAddress)try{const t=await(0,l.polymarketGetPositions)(n.polymarketWalletAddress);e.polymarket=t.map(e=>({venue:"polymarket",market:e.title||e.slug||e.asset,side:e.outcome||"Yes",size:e.size,avg_price:`${Math.round(100*(e.avgPrice||0))}¢`,current_price:`${Math.round(100*(e.curPrice||e.currentPrice||0))}¢`,pnl:`$${(e.cashPnl||0).toFixed(2)}`}))}catch{}return 0===e.kalshi.length&&0===e.polymarket.length?{content:[{type:"text",text:"No positions found. Configure Kalshi (KALSHI_API_KEY_ID) or Polymarket (sf setup --polymarket) to see positions."}],details:{}}:{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}},{name:"web_search",label:"Web Search",description:"Search latest news and information. Use for real-time info not yet covered by the causal tree or heartbeat engine.",parameters:_e,execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY;if(!n&&!(!n&&s))return{content:[{type:"text",text:"Web search not available. Run sf login (proxied search) or set TAVILY_API_KEY."}],details:{}};let o;if(o=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:5,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:5,search_depth:"basic",include_answer:!0})}),!o.ok)return{content:[{type:"text",text:`Search failed: ${o.status}`}],details:{}};const r=await o.json(),a=(r.results||[]).map(e=>`[${e.title}](${e.url})\n${e.content?.slice(0,200)}`).join("\n\n");return{content:[{type:"text",text:`${r.answer?`Summary: ${r.answer}\n\n---\n\n`:""}${a}`}],details:{}}}},{name:"explore_public",label:"Explore Public Theses",description:"Browse public theses from other users. No auth required. Pass a slug to get details, or omit to list all.",parameters:U.Object({slug:U.Optional(U.String({description:"Specific thesis slug, or empty to list all"}))}),execute:async(e,t)=>{const n="https://simplefunctions.dev";if(t.slug){const e=await fetch(`${n}/api/public/thesis/${t.slug}`);if(!e.ok)return{content:[{type:"text",text:`Not found: ${t.slug}`}],details:{}};const o=await e.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}const o=await fetch(`${n}/api/public/theses`);if(!o.ok)return{content:[{type:"text",text:"Failed to fetch public theses"}],details:{}};const s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"create_strategy",label:"Create Strategy",description:"Create a trading strategy for a thesis. Extract hard conditions (entryBelow/stopLoss/takeProfit as cents) and soft conditions from conversation. Called when user mentions specific trade ideas.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),marketId:U.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:U.String({description:"Human-readable market name"}),direction:U.String({description:"yes or no"}),horizon:U.Optional(U.String({description:"short, medium, or long. Default: medium"})),entryBelow:U.Optional(U.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:U.Optional(U.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:U.Optional(U.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:U.Optional(U.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:U.Optional(U.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:U.Optional(U.Number({description:"Contracts per order. Default: 50"})),softConditions:U.Optional(U.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:U.Optional(U.String({description:"Full logic description"}))}),execute:async(e,t)=>{const n=await y.createStrategyAPI(t.thesisId,{marketId:t.marketId,market:t.market,direction:t.direction,horizon:t.horizon,entryBelow:t.entryBelow,entryAbove:t.entryAbove,stopLoss:t.stopLoss,takeProfit:t.takeProfit,maxQuantity:t.maxQuantity,perOrderQuantity:t.perOrderQuantity,softConditions:t.softConditions,rationale:t.rationale,createdBy:"agent"});return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"list_strategies",label:"List Strategies",description:"List strategies for a thesis. Filter by status (active/watching/executed/cancelled/review) or omit for all.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),status:U.Optional(U.String({description:"Filter by status. Omit for all."}))}),execute:async(e,t)=>{const n=await y.getStrategies(t.thesisId,t.status);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"update_strategy",label:"Update Strategy",description:"Update a strategy (change stop loss, take profit, status, priority, etc.)",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),strategyId:U.String({description:"Strategy ID (UUID)"}),stopLoss:U.Optional(U.Number({description:"New stop loss (cents)"})),takeProfit:U.Optional(U.Number({description:"New take profit (cents)"})),entryBelow:U.Optional(U.Number({description:"New entry below trigger (cents)"})),entryAbove:U.Optional(U.Number({description:"New entry above trigger (cents)"})),status:U.Optional(U.String({description:"New status: active|watching|executed|cancelled|review"})),priority:U.Optional(U.Number({description:"New priority"})),softConditions:U.Optional(U.String({description:"Updated soft conditions"})),rationale:U.Optional(U.String({description:"Updated rationale"}))}),execute:async(e,t)=>{const{thesisId:n,strategyId:o,...s}=t,i=await y.updateStrategyAPI(n,o,s);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"get_milestones",label:"Milestones",description:"Get upcoming events from Kalshi calendar. Use to check economic releases, political events, or other catalysts coming up that might affect the thesis.",parameters:U.Object({hours:U.Optional(U.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:U.Optional(U.String({description:"Filter by category (e.g. Economics, Politics, Sports)"}))}),execute:async(e,t)=>{const n=t.hours||168,o=new Date,s=`https://api.elections.kalshi.com/trade-api/v2/milestones?limit=200&minimum_start_date=${o.toISOString()}`+(t.category?`&category=${t.category}`:""),i=await fetch(s,{headers:{Accept:"application/json"}});if(!i.ok)return{content:[{type:"text",text:`Milestones API error: ${i.status}`}],details:{}};const r=await i.json(),a=o.getTime()+36e5*n,c=(r.milestones||[]).filter(e=>new Date(e.start_date).getTime()<=a).slice(0,30).map(e=>({title:e.title,category:e.category,start_date:e.start_date,related_event_tickers:e.related_event_tickers,hours_until:Math.round((new Date(e.start_date).getTime()-o.getTime())/36e5)}));return{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}}},{name:"get_forecast",label:"Forecast",description:"Get market distribution (P50/P75/P90 percentile history) for a Kalshi event. Shows how market consensus has shifted over time.",parameters:U.Object({eventTicker:U.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:U.Optional(U.Number({description:"Days of history (default 7)"}))}),execute:async(e,t)=>{const{getForecastHistory:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=t.days||7,i=await fetch(`https://api.elections.kalshi.com/trade-api/v2/events/${t.eventTicker}`,{headers:{Accept:"application/json"}});if(!i.ok)return{content:[{type:"text",text:`Event not found: ${t.eventTicker}`}],details:{}};const r=await i.json(),a=r.event?.series_ticker;if(!a)return{content:[{type:"text",text:`No series_ticker for ${t.eventTicker}`}],details:{}};const c=await o({seriesTicker:a,eventTicker:t.eventTicker,percentiles:[5e3,7500,9e3],startTs:Math.floor((Date.now()-864e5*s)/1e3),endTs:Math.floor(Date.now()/1e3),periodInterval:1440});return c&&0!==c.length?{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}:{content:[{type:"text",text:"No forecast data available"}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled (resolved) contracts with P&L. Shows which contracts won/lost and realized returns.",parameters:U.Object({ticker:U.Optional(U.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getSettlements:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await o({limit:100,ticker:t.ticker});return s?{content:[{type:"text",text:JSON.stringify(s.settlements,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance and portfolio value.",parameters:Se,execute:async()=>{const{getBalance:e}=await Promise.resolve().then(n.t.bind(n,96139,23)),t=await e();return t?{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_orders",label:"Orders",description:"Get current resting orders on Kalshi. Stale orders (>7 days old AND >10¢ from market) are flagged.",parameters:U.Object({status:U.Optional(U.String({description:"Filter by status: resting, canceled, executed. Default: resting"}))}),execute:async(e,t)=>{const{getOrders:o,getMarketPrice:s}=await Promise.resolve().then(n.t.bind(n,96139,23)),i=await o({status:t.status||"resting",limit:100});if(!i)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};const r=await Promise.all((i.orders||[]).map(async e=>{const t=e.created_time?Math.round((Date.now()-new Date(e.created_time).getTime())/864e5):null;let n=null,o=!1;try{const i=await s(e.ticker);null!=i&&e.yes_price_dollars&&(n=Math.round(100*Math.abs(i-parseFloat(e.yes_price_dollars))),null!=t&&t>7&&n>10&&(o=!0))}catch{}return{...e,daysSinceCreated:t,distanceFromMarket:n,stale:o}}));return{content:[{type:"text",text:JSON.stringify(r,null,2)}],details:{}}}},{name:"get_fills",label:"Fills",description:"Get recent trade fills (executed trades) on Kalshi.",parameters:U.Object({ticker:U.Optional(U.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getFills:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await o({ticker:t.ticker,limit:50});return s?{content:[{type:"text",text:JSON.stringify(s.fills,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_liquidity",label:"Liquidity Scanner",description:"Scan orderbook liquidity for a topic across Kalshi + Polymarket. Returns spread, depth, liquidity scores. Topics: "+Object.keys(d.TOPIC_SERIES).join(", "),parameters:U.Object({topic:U.String({description:"Topic to scan (e.g. oil, crypto, fed, geopolitics)"})}),execute:async(e,t)=>{const n=t.topic.toLowerCase(),o=d.TOPIC_SERIES[n];if(!o)return{content:[{type:"text",text:`Unknown topic "${t.topic}". Available: ${Object.keys(d.TOPIC_SERIES).join(", ")}`}],details:{}};const s=[];for(const e of o)try{const t=`https://api.elections.kalshi.com/trade-api/v2/markets?series_ticker=${e}&status=open&limit=200`,n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)continue;const o=(await n.json()).markets||[],i=await Promise.allSettled(o.slice(0,20).map(e=>(0,c.getPublicOrderbook)(e.ticker).then(t=>({ticker:e.ticker,title:e.title,ob:t}))));for(const e of i){if("fulfilled"!==e.status||!e.value.ob)continue;const{ticker:t,title:n,ob:o}=e.value,i=(o.yes_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),r=(o.no_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),a=i[0]?.price||0,c=r.length>0?100-r[0].price:100,l=c-a,d=i.slice(0,3).reduce((e,t)=>e+t.qty,0)+r.slice(0,3).reduce((e,t)=>e+t.qty,0),u=l<=2&&d>=500?"high":l<=5&&d>=100?"medium":"low";s.push({venue:"kalshi",ticker:t,title:(n||"").slice(0,50),bestBid:a,bestAsk:c,spread:l,depth:Math.round(d),liquidityScore:u})}}catch{}try{const e=await(0,l.polymarketSearch)(n,5);for(const t of e)for(const e of(t.markets||[]).slice(0,5)){if(!e.active||e.closed||!e.clobTokenIds)continue;const n=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!n)continue;const o=await(0,l.polymarketGetOrderbookWithDepth)(n[0]);o&&s.push({venue:"polymarket",ticker:(e.question||t.title).slice(0,50),bestBid:o.bestBid,bestAsk:o.bestAsk,spread:o.spread,depth:o.bidDepthTop3+o.askDepthTop3,liquidityScore:o.liquidityScore})}}catch{}return s.sort((e,t)=>e.spread-t.spread),{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"inspect_book",label:"Orderbook",description:'Get orderbook depth, spread, and liquidity. Returns a status field per market: "ok", "empty_orderbook", "market_closed", or "api_error". Supports multiple tickers in one call — use tickers array for batch position checks.',parameters:U.Object({ticker:U.Optional(U.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:U.Optional(U.Array(U.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:U.Optional(U.String({description:'Search Polymarket by keyword (e.g. "oil price above 100")'}))}),execute:async(e,t)=>{const n=[],o=[];t.tickers?.length?o.push(...t.tickers):t.ticker&&o.push(t.ticker);for(const e of o)try{const t=await(0,a.kalshiFetchMarket)(e),o=t.status||"unknown";if("open"!==o&&"active"!==o)n.push({venue:"kalshi",ticker:e,title:t.title,status:"market_closed",reason:`Market status: ${o}. Orderbook unavailable for closed/settled markets.`,lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0"))});else{const o=await(0,c.getPublicOrderbook)(e),s=(o?.yes_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),i=(o?.no_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price);if(0===s.length&&0===i.length)n.push({venue:"kalshi",ticker:e,title:t.title,status:"empty_orderbook",reason:"Market open but no resting orders. Normal for illiquid/OTM contracts. Use lastPrice as reference.",lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0")),volume24h:parseFloat(t.volume_24h_fp||"0"),openInterest:parseFloat(t.open_interest_fp||"0"),expiry:t.close_time||null});else{const o=s[0]?.price||0,r=i.length>0?100-i[0].price:s[0]?s[0].price+1:100,a=r-o,c=s.slice(0,3).reduce((e,t)=>e+t.size,0)+i.slice(0,3).reduce((e,t)=>e+t.size,0),l=a<=2&&c>=500?"high":a<=5&&c>=100?"medium":"low";n.push({venue:"kalshi",ticker:e,title:t.title,status:"ok",bestBid:o,bestAsk:r,spread:a,liquidityScore:l,bidLevels:s.slice(0,5),askLevels:i.slice(0,5).map(e=>({price:100-e.price,size:e.size})),totalBidDepth:s.reduce((e,t)=>e+t.size,0),totalAskDepth:i.reduce((e,t)=>e+t.size,0),lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0")),volume24h:parseFloat(t.volume_24h_fp||"0"),openInterest:parseFloat(t.open_interest_fp||"0"),expiry:t.close_time||null})}}}catch(t){n.push({venue:"kalshi",ticker:e,status:"api_error",reason:`Kalshi API error: ${t.message}`})}if(t.polyQuery)try{const e=await(0,l.polymarketSearch)(t.polyQuery,5);for(const t of e)for(const e of(t.markets||[]).slice(0,3)){if(!e.active||e.closed||!e.clobTokenIds)continue;const o=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!o)continue;const s=await(0,l.polymarketGetOrderbookWithDepth)(o[0]);if(!s)continue;const i=(0,l.parseOutcomePrices)(e.outcomePrices);n.push({venue:"polymarket",title:e.question||t.title,bestBid:s.bestBid,bestAsk:s.bestAsk,spread:s.spread,liquidityScore:s.liquidityScore,totalBidDepth:s.totalBidDepth,totalAskDepth:s.totalAskDepth,lastPrice:i[0]?Math.round(100*i[0]):0,volume24h:e.volume24hr||0})}}catch{}return 0===n.length?{content:[{type:"text",text:"No markets found. Provide ticker (Kalshi) or polyQuery (Polymarket search)."}],details:{}}:{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"get_schedule",label:"Schedule",description:"Get exchange status (open/closed) and trading hours. Use to check if low liquidity is due to off-hours.",parameters:Se,execute:async()=>{try{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:`Exchange API error: ${e.status}`}],details:{}};const t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}catch(e){return{content:[{type:"text",text:`Failed: ${e.message}`}],details:{}}}}},{name:"create_thesis",label:"Create Thesis",description:"Create a new thesis from a raw thesis statement. Returns the thesis ID, confidence, node count, and edge count. In explorer mode, this automatically transitions to thesis mode.",parameters:U.Object({rawThesis:U.String({description:"The raw thesis statement to create"}),webhookUrl:U.Optional(U.String({description:"Optional webhook URL for notifications"}))}),execute:async(e,t)=>{const n=await y.createThesis(t.rawThesis,!0),o=n.thesis||n,s=o.causalTree?.nodes?.length||0,i=(o.edges||[]).length,r="number"==typeof o.confidence?Math.round(100*o.confidence):0;if(x&&o.id){x=!1,S=o.id;try{$=await y.getContext(o.id);const e=Oe($);Pe.setSystemPrompt(e),ce.setFromContext($,le||void 0),se.requestRender()}catch{}}return{content:[{type:"text",text:`Thesis created.\nID: ${o.id}\nConfidence: ${r}%\nNodes: ${s}\nEdges: ${i}\n\nHeartbeat engine is now monitoring this thesis 24/7. Use /switch ${o.id?.slice(0,8)} to focus on it.`}],details:{}}}},{name:"get_edges",label:"Get Edges",description:"Get top edges across all active theses. Returns the top 10 edges sorted by absolute edge size with ticker, market name, edge size, direction, and venue.",parameters:Se,execute:async()=>{const{theses:e}=await y.listTheses(),t=(e||[]).filter(e=>"active"===e.status||"monitoring"===e.status),n=await Promise.allSettled(t.map(async e=>((await y.getContext(e.id)).edges||[]).map(t=>({...t,thesisId:e.id})))),o=[];for(const e of n)"fulfilled"===e.status&&o.push(...e.value);o.sort((e,t)=>Math.abs(t.edge||t.edgeSize||0)-Math.abs(e.edge||e.edgeSize||0));const s=o.slice(0,10).map(e=>({ticker:e.marketId||e.ticker||"-",market:e.market||e.marketTitle||"-",edge:e.edge||e.edgeSize||0,direction:e.direction||"yes",venue:e.venue||"kalshi"}));return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"get_feed",label:"Get Feed",description:"Get evaluation history with topSignal highlighting. The most important signal (largest confidence change or most actionable) is surfaced first so you don't have to scan all entries.",parameters:U.Object({hours:U.Optional(U.Number({description:"Hours of history to fetch (default 24)"}))}),execute:async(e,t)=>{const n=await y.getFeed(t.hours||24),o=Array.isArray(n)?n:n?.evaluations||n?.items||[];let s=null,i=0;for(const e of o){let t=0;const n=Math.abs(e.confidenceDelta||e.confidence_delta||0);n>0?t=100*n:e.summary?.length>50&&(t=.1),t>i&&(i=t,s=e)}const r={total:o.length};return s&&(r.topSignal={summary:s.summary||s.content||"",confidenceDelta:s.confidenceDelta||s.confidence_delta||0,evaluatedAt:s.evaluatedAt||s.evaluated_at||s.createdAt||"",why:i>1?"Largest confidence movement in this period":i>0?"Most substantive evaluation (no confidence change)":"Most recent evaluation"}),r.items=o,{content:[{type:"text",text:JSON.stringify(r,null,2)}],details:{}}}},{name:"get_changes",label:"Get Changes",description:"Get recent market changes detected server-side. Returns real price moves (>5¢), new contracts, and removed/settled contracts across Kalshi, Polymarket, and traditional markets. Checked every 15 minutes. Use for situational awareness, discovering new opportunities, or checking if anything material happened recently.",parameters:U.Object({hours:U.Optional(U.Number({description:"Hours of history (default 1)"}))}),execute:async(e,t)=>{const n=t.hours||1,o=new Date(Date.now()-60*n*60*1e3).toISOString(),s=process.env.SF_API_URL||"https://simplefunctions.dev",i=await fetch(`${s}/api/changes?since=${encodeURIComponent(o)}&limit=100`);if(!i.ok)return{content:[{type:"text",text:JSON.stringify({error:`API error ${i.status}`})}],details:{}};const r=await i.json();return{content:[{type:"text",text:JSON.stringify(r,null,2)}],details:{}}}}];xe.push({name:"what_if",label:"What-If",description:'Run a what-if scenario: override causal tree node probabilities and see how edges and confidence change. Zero LLM cost — pure computation. Use when user asks "what if X happens?" or "what if this node drops to Y%?".',parameters:U.Object({overrides:U.Array(U.Object({nodeId:U.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:U.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{if(S)try{$=await y.getContext(S)}catch{}const n=$,o=[];const s=n.causalTree?.nodes||[];!function e(t){for(const n of t)o.push(n),n.children?.length&&e(n.children)}(s);const i=s.filter(e=>0===e.depth||void 0===e.depth&&!e.id.includes(".")),r=new Map(t.overrides.map(e=>[e.nodeId,e.newProbability]));function a(e){if(r.has(e.id))return r.get(e.id);if(e.children?.length>0){const t=e.children.map(e=>a(e)),n=e.children.map(e=>e.importance||1),o=n.reduce((e,t)=>e+t,0);return o>0?t.reduce((e,t,o)=>e+t*n[o],0)/o:t.reduce((e,t)=>e+t,0)/t.length}return e.probability??0}const c=i.reduce((e,t)=>e+(t.probability||0)*(t.importance||0),0),l=i.reduce((e,t)=>e+a(t)*(t.importance||0),0),d=new Map;for(const[e,t]of r.entries()){const n=o.find(t=>t.id===e);n&&n.probability>0&&d.set(e,Math.max(0,Math.min(2,t/n.probability)))}const u=(n.edges||[]).map(e=>{const t=e.relatedNodeId;let n=1;if(t){const e=[t,t.split(".").slice(0,-1).join("."),t.split(".")[0]].filter(Boolean);for(const t of e)if(d.has(t)){n=d.get(t);break}}const o=e.marketPrice||0,s=e.thesisPrice||e.thesisImpliedPrice||o,i=e.edge||e.edgeSize||0,r=Math.round(100*(o+(s-o)*n))/100,a=e.direction||"yes",c=Math.round(100*("yes"===a?r-o:o-r))/100;return{market:e.market||e.marketTitle||e.marketId,marketPrice:o,oldEdge:i,newEdge:c,delta:c-i,signal:Math.abs(c-i)<1?"unchanged":i>0&&c<0||i<0&&c>0?"REVERSED":Math.abs(c)<2?"GONE":"reduced"}}).filter(e=>"unchanged"!==e.signal),p=null!=n.confidence?Math.round(100*Number(n.confidence)):null,h={overrides:t.overrides.map(e=>{const t=o.find(t=>t.id===e.nodeId);return{nodeId:e.nodeId,label:t?.label||e.nodeId,oldProb:t?.probability,newProb:e.newProbability}}),serverConfidence:p,treeConfidence:{old:Math.round(100*c),new:Math.round(100*l),delta:Math.round(100*(l-c))},note:null!=p&&Math.abs(p-Math.round(100*c))>5?`serverConfidence (${p}%) differs from treeConfidence (${Math.round(100*c)}%) because the LLM evaluation considers factors beyond the causal tree.`:void 0,affectedEdges:u};return{content:[{type:"text",text:JSON.stringify(h,null,2)}],details:{}}}}),xe.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions on a topic. Returns top posts with engagement metrics, sentiment analysis, and key themes. Use for social signal research on any prediction market topic.",parameters:U.Object({query:U.String({description:'Search query (e.g. "iran oil", "fed rate cut", "$BTC")'}),mode:U.Optional(U.String({description:'"summary" (default, with AI analysis) or "raw" (just posts)'})),hours:U.Optional(U.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await y.searchX(t.query,{mode:t.mode,hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_volume",label:"X Volume",description:"Get X discussion volume trend for a topic — total posts, velocity change vs prior period, peak time, and hourly timeseries. Use to detect social momentum shifts.",parameters:U.Object({query:U.String({description:"Search query"}),hours:U.Optional(U.Number({description:"Hours of history (default 72)"}))}),execute:async(e,t)=>{const n=await y.getXVolume(t.query,{hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_news",label:"X News",description:"Get news stories trending on X — titles, summaries, categories, and ticker mentions. Use for breaking news and narrative tracking.",parameters:U.Object({query:U.String({description:"Search query"}),limit:U.Optional(U.Number({description:"Max stories (default 10)"}))}),execute:async(e,t)=>{const n=await y.searchXNews(t.query,{limit:t.limit});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_account",label:"X Account",description:"Get recent posts from a specific X account. Use to track key opinion leaders, officials, or analysts.",parameters:U.Object({username:U.String({description:"X username (with or without @)"}),hours:U.Optional(U.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await y.getXAccount(t.username,{hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"heartbeat_config",label:"Heartbeat Config",description:"View or update heartbeat settings for a thesis: scan intervals, model tier, budget cap, pause/resume. Also shows this month's cost breakdown.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),newsIntervalMin:U.Optional(U.Number({description:"News scan interval in minutes (15-1440)"})),xIntervalMin:U.Optional(U.Number({description:"X scan interval in minutes (60-1440)"})),evalModelTier:U.Optional(U.String({description:"Eval model: cheap, medium, or heavy"})),monthlyBudgetUsd:U.Optional(U.Number({description:"Monthly budget cap in USD (0 = unlimited)"})),paused:U.Optional(U.Boolean({description:"Pause (true) or resume (false) heartbeat"}))}),execute:async(e,t)=>{if(t.newsIntervalMin||t.xIntervalMin||t.evalModelTier||void 0!==t.monthlyBudgetUsd||void 0!==t.paused){const e={};t.newsIntervalMin&&(e.newsIntervalMin=t.newsIntervalMin),t.xIntervalMin&&(e.xIntervalMin=t.xIntervalMin),t.evalModelTier&&(e.evalModelTier=t.evalModelTier),void 0!==t.monthlyBudgetUsd&&(e.monthlyBudgetUsd=t.monthlyBudgetUsd),void 0!==t.paused&&(e.paused=t.paused),await y.updateHeartbeatConfig(t.thesisId,e)}const n=await y.getHeartbeatConfig(t.thesisId);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}});const Ce=(0,u.loadConfig)();Ce.tradingEnabled&&xe.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Shows a preview and asks for user confirmation before executing. Use for limit or market orders.",parameters:U.Object({ticker:U.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:U.String({description:"yes or no"}),action:U.String({description:"buy or sell"}),type:U.String({description:"limit or market"}),count:U.Number({description:"Number of contracts"}),price_cents:U.Optional(U.Number({description:"Limit price in cents (1-99). Required for limit orders."}))}),execute:async(e,t)=>{const{createOrder:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=t.price_cents?Math.round(Number(t.price_cents)):void 0,i=((s||99)*t.count/100).toFixed(2);ye([_.zinc200(w("ORDER PREVIEW")),` Ticker: ${t.ticker}`,` Side: ${"yes"===t.side?_.emerald("YES"):_.red("NO")}`,` Action: ${t.action.toUpperCase()}`,` Quantity: ${t.count}`,` Type: ${t.type}`,s?` Price: ${s}¢`:"",` Max cost: $${i}`].filter(Boolean).join("\n")),$e(),se.requestRender();if(!(await we("Execute this order? (y/n)")).toLowerCase().startsWith("y"))return{content:[{type:"text",text:"Order cancelled by user."}],details:{}};try{const e=await o({ticker:t.ticker,side:t.side,action:t.action,type:t.type,count:t.count,...s?{yes_price:s}:{}}),n=e.order||e;return{content:[{type:"text",text:`Order placed: ${n.order_id||"OK"}\nStatus: ${n.status||"-"}\nFilled: ${n.fill_count_fp||0}/${n.initial_count_fp||t.count}`}],details:{}}}catch(e){const t=e.message||String(e);return t.includes("403")?{content:[{type:"text",text:"403 Forbidden — your Kalshi key lacks write permission. Get a read+write key at kalshi.com/account/api-keys"}],details:{}}:{content:[{type:"text",text:`Order failed: ${t}`}],details:{}}}}},{name:"cancel_order",label:"Cancel Order",description:"Cancel a resting order by order ID.",parameters:U.Object({order_id:U.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{const{cancelOrder:o}=await Promise.resolve().then(n.t.bind(n,96139,23));if(!(await we(`Cancel order ${t.order_id}? (y/n)`)).toLowerCase().startsWith("y"))return{content:[{type:"text",text:"Cancel aborted by user."}],details:{}};try{return await o(t.order_id),{content:[{type:"text",text:`Order ${t.order_id} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Cancel failed: ${e.message}`}],details:{}}}}});function Oe(e){const t=e.edges?.sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.market||"").slice(0,40)} | ${e.venue||"kalshi"} | mkt ${e.marketPrice}¢ → thesis ${e.thesisPrice}¢ | edge ${e.edge>0?"+":""}${e.edge} | ${e.orderbook?.liquidityScore||"?"}`).join("\n")||" (no edge data)",n=e.causalTree?.nodes?.filter(e=>0===e.depth).map(e=>` ${e.id} ${(e.label||"").slice(0,40)} — ${Math.round(100*e.probability)}%`).join("\n")||" (no causal tree)",o="number"==typeof e.confidence?Math.round(100*e.confidence):"string"==typeof e.confidence?parseInt(e.confidence):0;return`You are a prediction market trading assistant. Your job is not to please the user — it is to help them see reality clearly and make correct trading decisions.\n\n## Your analytical framework\n\nEach thesis has a causal tree. Every node is a causal hypothesis with a probability. Nodes have causal relationships — when upstream nodes change, downstream nodes follow.\n\nEdge = thesis-implied price - actual market price. Positive edge = market underprices. Contracts with large edges AND good liquidity are most tradeable.\n\nexecutableEdge = real edge after subtracting bid-ask spread. Big theoretical edge with wide spread may not be worth entering.\n\n### Edge diagnosis (always classify)\nWhen reporting an edge, classify it:\n- "consensus gap": depth >= 500, market actively disagrees — real edge, real opponents\n- "attention gap": depth < 100, no real pricing — edge may be illusory, needs catalyst\n- "timing gap": market directionally agrees but lags — may close suddenly on news\n- "risk premium": edge reflects settlement ambiguity or platform risk, not alpha\nFor edges > 20 cents, state in one sentence what must be true for the market to be right and the thesis wrong.\n\n### Price reliability\n47 cents with depth 14K = strong consensus. 47 cents with depth 50 = three people's opinion.\n- depth >= 500: reliable, treat as market consensus\n- depth 100-500: moderate confidence, caveat when citing\n- depth < 100: unreliable — do NOT treat as "the market thinks X"\n- spread > 5 cents: wide disagreement, noisy midpoint\n- liquidityScore = low: do NOT recommend entry\n\n### Kill condition awareness\nEach top-level causal node has an implicit falsifier. When scanning news or evaluating events, check: "Does any event here fundamentally break a core assumption?" If yes, flag immediately — this overrides all other analysis.\n\n### Catalyst and time\nWhen discussing an edge, always state contract expiry and next identifiable catalyst. No visible catalyst = flag capital lock risk.\n\n### Research workflow\nFor complex questions, chain multiple tool calls:\n1. get_world_state (broad situational awareness) 2. get_context 3. inspect_book 4. get_liquidity 5. web_search 6. search_x 7. monitor_the_situation (scrape specific URLs) 8. synthesize\nUse get_world_delta for efficient polling (30-50 tokens vs 800 for full state). Use enrich_content to cross-reference any text with 9,706 markets.\nDon't answer a complex question with a single tool call.\n\n### Social signal research\nUse search_x to check X/Twitter sentiment on any topic — especially useful for geopolitical events, macro shifts, and breaking news that moves prediction markets. Use x_volume to detect discussion spikes (velocity > 1 = increasing attention). Use x_account to track specific analysts or officials.\n\n### Heartbeat config\nUse heartbeat_config to view or adjust per-thesis heartbeat settings: news/X scan intervals, evaluation model tier (cheap/medium/heavy), monthly budget cap, pause/resume. Also shows this month's cost breakdown (LLM calls, search calls, tokens, spend). Useful when the user asks about costs, wants to slow down/speed up monitoring, or if you detect budget overrun.\n\n### Conditional rules\n- Portfolio/positions questions: flag correlated exposure — positions sharing upstream causal nodes are not independent bets.\n- No catalyst visible within 30 days + edge not improving: flag "stale capital risk."\n- Edges < 10 cents, thin liquidity, no catalyst near: say "nothing to do right now." Do not manufacture urgency.\n\nShort-term markets settle into hard data that calibrates the thesis. Use them to verify node probabilities, not to bet.\n\n## Your behavioral rules\n\n- IMPORTANT: You do NOT know the user's current positions at conversation start. Before discussing trades, recommending entries/exits, or analyzing portfolio risk, call get_positions FIRST. Never assume the user has no positions — they may have large existing holdings you don't know about.\n- Think before calling tools. If the data is already in context, don't re-fetch.\n- If the user says "note this" or mentions a news event, inject a signal. Don't ask "should I note this?"\n- If the user says "evaluate" or "run it", trigger immediately. Don't confirm.\n- Don't end every response with "anything else?" — the user will ask when they want to.\n- If the user asks about latest news or real-time events, use web_search first, then answer based on results. If you find important information, suggest injecting it as a signal.\n- If you notice an edge narrowing or disappearing, say so proactively. Don't only report good news.\n- If a causal tree node probability seriously contradicts the market price, point it out.\n- Use Chinese if the user writes in Chinese, English if they write in English.\n- For any question about prices, positions, or P&L, ALWAYS call a tool to get fresh data first. Never answer price-related questions using the cached data in this system prompt.\n- Prices are in cents (e.g. 35¢). P&L, cost, and balance are in dollars (e.g. $90.66). Tool outputs are pre-formatted with units — do not re-convert.\n- Align tables. Be precise with numbers to the cent.\n\n## Strategy rules\n\nWhen the conversation produces a concrete trade idea (specific contract, direction, price conditions), use create_strategy to record it immediately. Don't wait for the user to say "record this."\n- Extract hard conditions (specific prices in cents) into entryBelow/stopLoss/takeProfit.\n- Put fuzzy conditions into softConditions (e.g. "only if n3 > 60%", "spread < 3¢").\n- Put the full reasoning into rationale.\n- After creating, confirm the strategy details.\n- If the user says "change the stop loss on T150 to 30", use update_strategy.\n\n## Intent & Execution\n\nUse create_intent to declare execution intents with trigger conditions (price_below, price_above, time, immediate). Use list_intents / cancel_intent to manage. The local runtime daemon (runtime_start/runtime_stop/runtime_status) evaluates triggers and executes orders via local API keys.\n\n## Trading status\n\n${Ce.tradingEnabled?"Trading is ENABLED. You have place_order, cancel_order, create_intent, and runtime tools.":"Trading is DISABLED. You cannot place or cancel orders. Tell the user to run `sf setup --enable-trading` to unlock trading. Intent system still works for declaring plans."}\n\n## Current thesis state\n\nThesis: ${e.thesis||e.rawThesis||"N/A"}\nID: ${e.thesisId||S}\nConfidence: ${o}%\nStatus: ${e.status}\n\nTop-level causal tree nodes:\n${n}\n\nTop 5 edges by magnitude:\n${t}\n\n${e.lastEvaluation?.summary?`Latest evaluation summary: ${e.lastEvaluation.summary.slice(0,300)}`:""}`}xe.push({name:"update_thesis",label:"Update Thesis",description:"Update thesis metadata: title, status (active/paused/archived), webhookUrl.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),title:U.Optional(U.String({description:"New title"})),status:U.Optional(U.String({description:"active, paused, or archived"})),webhookUrl:U.Optional(U.String({description:"Webhook URL (HTTPS)"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,s=await y.request("PATCH",`/api/thesis/${n}`,o);return{content:[{type:"text",text:JSON.stringify(s)}],details:{}}}},{name:"augment_tree",label:"Augment Tree",description:"Review and merge suggested causal tree nodes from evaluations. Evolves the tree structure.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),dryRun:U.Optional(U.Boolean({description:"Preview changes without applying (default false)"}))}),execute:async(e,t)=>{const n=t.dryRun?"?dryRun=true":"",o=await y.request("POST",`/api/thesis/${t.thesisId}/augment${n}`);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"add_position",label:"Add Position",description:"Record a new position in a thesis for tracking.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),venue:U.String({description:"kalshi or polymarket"}),externalMarketId:U.String({description:"Market ticker"}),marketTitle:U.String({description:"Market name"}),direction:U.String({description:"yes or no"}),entryPrice:U.Number({description:"Entry price in cents"}),size:U.Optional(U.Number({description:"Contracts"})),rationale:U.Optional(U.String({description:"Why"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,s=await y.request("POST",`/api/thesis/${n}/positions`,o);return{content:[{type:"text",text:JSON.stringify(s)}],details:{}}}},{name:"update_position",label:"Update Position",description:"Update position: currentPrice, edge, status (open→closed).",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),positionId:U.String({description:"Position ID"}),currentPrice:U.Optional(U.Number({description:"Current price (cents)"})),edge:U.Optional(U.Number({description:"Current edge (cents)"})),status:U.Optional(U.String({description:"open or closed"}))}),execute:async(e,t)=>{const{thesisId:n,positionId:o,...s}=t,i=await y.request("PATCH",`/api/thesis/${n}/positions/${o}`,s);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"close_position",label:"Close Position",description:"Remove a position record from a thesis.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),positionId:U.String({description:"Position ID"})}),execute:async(e,t)=>{const n=await y.request("DELETE",`/api/thesis/${t.thesisId}/positions/${t.positionId}`);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"get_evaluation_history",label:"Evaluation History",description:"Confidence trajectory over time — daily aggregated. For trend analysis.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await y.request("GET",`/api/thesis/${t.thesisId}/evaluations`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"update_nodes",label:"Update Nodes",description:"Directly update causal tree node probabilities. Zero LLM cost. Use for confirmed facts (lock nodes at 0.99).",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),updates:U.Array(U.Object({nodeId:U.String({description:"Node ID (e.g. n3)"}),probability:U.Number({description:"New probability (0-1)"}),reason:U.Optional(U.String({description:"Why"}))})),lock:U.Optional(U.Array(U.String({description:"Node IDs to lock"})))}),execute:async(e,t)=>{const n=await y.request("POST",`/api/thesis/${t.thesisId}/nodes/update`,{updates:t.updates,lock:t.lock});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"configure_heartbeat",label:"Configure Heartbeat",description:"Adjust the 24/7 monitoring engine: news interval, X interval, model tier, budget, pause/resume.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),newsIntervalMin:U.Optional(U.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:U.Optional(U.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:U.Optional(U.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:U.Optional(U.Number({description:"Monthly budget cap (0=unlimited)"})),paused:U.Optional(U.Boolean({description:"Pause/resume"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,s=await y.request("PATCH",`/api/thesis/${n}/heartbeat`,o);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"get_heartbeat_status",label:"Heartbeat Status",description:"Heartbeat config + cost summary for a thesis.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await y.request("GET",`/api/thesis/${t.thesisId}/heartbeat`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}}),xe.push({name:"get_trade_ideas",label:"Trade Ideas",description:"S&T-style trade pitches: conviction, catalyst, direction, risk. No auth required.",parameters:U.Object({freshness:U.Optional(U.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:U.Optional(U.String({description:"Filter: macro, geopolitics, crypto, policy, event"}))}),execute:async(e,t)=>{const n=new URLSearchParams;t.freshness&&n.set("freshness",t.freshness),t.category&&n.set("category",t.category);const o=await fetch(`${i}/api/public/ideas?${n.toString()}`);if(!o.ok)return{content:[{type:"text",text:`Ideas API error: ${o.status}`}],details:{}};const s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"create_intent",label:"Create Intent",description:"Declare an execution intent with trigger conditions. Runtime daemon evaluates triggers and executes via local keys.",parameters:U.Object({action:U.String({description:"buy or sell"}),venue:U.String({description:"kalshi or polymarket"}),marketId:U.String({description:"Market ticker"}),marketTitle:U.String({description:"Human-readable name"}),direction:U.String({description:"yes or no"}),targetQuantity:U.Number({description:"Number of contracts"}),maxPrice:U.Optional(U.Number({description:"Max price per contract in cents (1-99)"})),triggerType:U.Optional(U.String({description:"immediate, price_below, price_above, time"})),triggerPrice:U.Optional(U.Number({description:"Price trigger threshold in cents"})),rationale:U.Optional(U.String({description:"Why this trade"})),autoExecute:U.Optional(U.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(e,t)=>{const n=await y.createIntent({...t,source:"agent",expireAt:new Date(Date.now()+864e5).toISOString()});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"list_intents",label:"List Intents",description:"List execution intents — pending, armed, triggered, executing, filled.",parameters:U.Object({activeOnly:U.Optional(U.Boolean({description:"Only active intents (default true)"}))}),execute:async(e,t)=>{const n=await y.listIntents({active:!1!==t.activeOnly});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"cancel_intent",label:"Cancel Intent",description:"Cancel an active intent — stops trigger evaluation and prevents execution.",parameters:U.Object({intentId:U.String({description:"Intent ID to cancel"})}),execute:async(e,t)=>{const n=await y.cancelIntentAPI(t.intentId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}}),xe.push({name:"get_world_state",label:"World State",description:"Real-time world model for agents. ~800 tokens of structured state: prediction market index, traditional markets, topic summaries, divergences. Use ?focus=energy,geo for deeper coverage on specific topics.",parameters:U.Object({focus:U.Optional(U.String({description:'Comma-separated topics to focus on (e.g. "energy,geopolitics")'}))}),execute:async(e,t)=>{const n=t.focus?`?focus=${encodeURIComponent(t.focus)}`:"",o=await fetch(`${i}/api/agent/world${n}`);if(!o.ok)return{content:[{type:"text",text:`World API error: ${o.status}`}],details:{}};return{content:[{type:"text",text:await o.text()}],details:{}}}},{name:"get_world_delta",label:"World Delta",description:"Incremental world state update — only what changed since a given time. ~30-50 tokens. Much cheaper than full state for polling.",parameters:U.Object({since:U.Optional(U.String({description:'Time window: "30m", "1h", "6h", "24h" or ISO timestamp (default "1h")'}))}),execute:async(e,t)=>{const n=t.since||"1h",o=await fetch(`${i}/api/agent/world/delta?since=${encodeURIComponent(n)}`);if(!o.ok)return{content:[{type:"text",text:`Delta API error: ${o.status}`}],details:{}};return{content:[{type:"text",text:await o.text()}],details:{}}}},{name:"monitor_the_situation",label:"Monitor",description:"Universal web intelligence. Scrape any URL (Firecrawl), analyze with any LLM, cross-reference with 9,706 prediction markets, push to webhook.",parameters:U.Object({source:U.Object({action:U.String({description:"Firecrawl action: scrape, crawl, search, map, extract, batch_scrape"}),url:U.Optional(U.String({description:"Target URL (for scrape/crawl/extract)"})),query:U.Optional(U.String({description:"Search query (for search action)"}))}),analysis:U.Optional(U.Object({model:U.Optional(U.String({description:"OpenRouter model (e.g. google/gemini-flash-1.5)"})),prompt:U.Optional(U.String({description:"Analysis prompt"}))})),enrich:U.Optional(U.Object({topics:U.Optional(U.Array(U.String(),{description:"Topics for market cross-reference"})),includeIndex:U.Optional(U.Boolean({description:"Include SF prediction market index"}))})),webhook:U.Optional(U.Object({url:U.String({description:"Webhook URL"}),format:U.Optional(U.String({description:"full, brief, or tweetable"}))}))}),execute:async(e,t)=>{const n=await fetch(`${i}/api/monitor-the-situation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)return{content:[{type:"text",text:`Monitor API error: ${n.status}`}],details:{}};const o=await n.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"enrich_content",label:"Enrich",description:"Cross-reference any text with 9,706 prediction markets. Returns divergences between your content and market prices. No auth required.",parameters:U.Object({content:U.String({description:"Text to cross-reference with markets"}),topics:U.Optional(U.Array(U.String(),{description:"Topic hints for better matching"}))}),execute:async(e,t)=>{const n=await fetch(`${i}/api/monitor-the-situation/enrich`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)return{content:[{type:"text",text:`Enrich API error: ${n.status}`}],details:{}};const o=await n.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}}),xe.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime daemon is running and show active intents.",parameters:U.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),i=o(s(),".sf","runtime.pid");let r=!1,a="";if(e(i)){a=t(i,"utf-8").trim();try{process.kill(parseInt(a),0),r=!0}catch{r=!1}}const c=await y.listIntents({active:!0});return{content:[{type:"text",text:JSON.stringify({running:r,pid:r?a:null,...c},null,2)}],details:{}}}},{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon. Polls for active intents, evaluates trigger conditions, and executes orders via local API keys.",parameters:U.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),{spawn:i}=await Promise.resolve().then(n.t.bind(n,35317,23)),r=o(s(),".sf","runtime.pid");if(e(r)){const e=t(r,"utf-8").trim();try{return process.kill(parseInt(e),0),{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{}}if(i(process.execPath,[process.argv[1],"runtime","start"],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env}}).unref(),await new Promise(e=>setTimeout(e,1e3)),e(r)){return{content:[{type:"text",text:`Runtime started (PID ${t(r,"utf-8").trim()}). Polling every 30s for active intents.`}],details:{}}}return{content:[{type:"text",text:"Runtime starting... check status in a moment with runtime_status."}],details:{}}}},{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:U.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:o}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=s(i(),".sf","runtime.pid");if(!e(r))return{content:[{type:"text",text:"No runtime running."}],details:{}};const a=t(r,"utf-8").trim();try{return process.kill(parseInt(a),"SIGTERM"),o(r),{content:[{type:"text",text:`Runtime stopped (PID ${a}).`}],details:{}}}catch{try{o(r)}catch{}return{content:[{type:"text",text:"Runtime was not running (stale PID file removed)."}],details:{}}}}});const Ie=x?function(e){const t=(0,u.loadConfig)(),n=e.theses?.length||0,o=(e.edges,(e.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.title||"").slice(0,40)} | ${e.venue||"kalshi"} | mkt ${e.price}¢ | edge +${e.edge}`).join("\n")||" (no edges)");return`You are a prediction market research assistant with access to live data across Kalshi, Polymarket, X/Twitter, and traditional markets.\n\nYou are in EXPLORER MODE — not bound to any specific thesis. Help the user research, compare, and understand prediction market data across all sources.\n\n## What you can do\n- Get real-time world state: prediction index, markets, topics, divergences (get_world_state, get_world_delta)\n- Search and compare markets across Kalshi and Polymarket (scan_markets)\n- Answer questions with live market data + LLM synthesis (query)\n- Check traditional market prices — SPY, VIX, gold, oil, bonds (get_markets)\n- S&T-style trade ideas with conviction and catalysts (get_trade_ideas)\n- Browse public theses and their edges (explore_public)\n- Search X/Twitter for sentiment and breaking news (search_x, x_volume, x_news)\n- Scrape any URL, analyze, cross-reference with 9,706 markets (monitor_the_situation, enrich_content)\n- Check orderbook depth and liquidity (inspect_book, get_liquidity)\n- View user positions across venues (get_positions)\n- Create and manage execution intents with triggers (create_intent, list_intents, cancel_intent)\n- Start/stop/check local execution runtime (runtime_start, runtime_stop, runtime_status)\n- Create a new thesis when the user forms a view (create_thesis)\n\n## CRITICAL: Thesis creation transition\nWhen the user expresses a market view worth tracking — explicitly ("create a thesis") or implicitly ("I think oil stays above $100", "the war won't end soon") — use create_thesis to create it. After creation, tell the user: "Thesis created. The heartbeat engine is now monitoring this 24/7. Use /switch <id> to focus on it."\n\n## Your analytical framework\nEdge = thesis price - market price. Positive = market underprices.\nEdge types: "consensus_gap" (real disagreement), "attention_gap" (no real pricing), "timing_gap" (market lags), "risk_premium" (settlement risk).\nPrice reliability: depth >= 500 = consensus. depth < 100 = unreliable. spread > 5¢ = noisy.\nAlways state contract expiry and next catalyst. No catalyst = capital lock risk.\n\n## Your behavioral rules\n- Be concise. Use tools for fresh data. Don't guess prices.\n- You do NOT know the user's positions at start. Call get_positions before discussing trades.\n- If user mentions news, offer to create a thesis or inject a signal if one exists.\n- Don't end with "anything else?"\n- Use Chinese if user writes Chinese, English if English.\n- Prices in cents (¢). P&L in dollars ($).\n\n## Trading status\n${t.tradingEnabled?"Trading is ENABLED.":"Trading is DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current market snapshot\nPublic theses tracked: ${n}\nTop edges across all public theses:\n${o}\n`}($):Oe($),Pe=new z({initialState:{systemPrompt:Ie,model:G,tools:xe,thinkingLevel:"off"},streamFn:q,getApiKey:e=>{if("openrouter"===e)return h}});let Te=!1;if(!t?.newSession){const e=g(S||"_explorer");if(e?.messages?.length>0)try{const t=e.messages.filter(e=>!!e.role&&((!Array.isArray(e.content)||0!==e.content.length)&&!("assistant"===e.role&&!e.content&&!e.tool_calls?.length))),n=[];for(const e of t){const t=n.length>0?n[n.length-1].role:null;e.role===t&&"tool"!==e.role||n.push(e)}n.length>0&&"user"===n[n.length-1].role&&n.pop(),Pe.replaceMessages(n),Pe.setSystemPrompt(Ie),Te=!0}catch{}}function Ee(){try{const e=Pe.state.messages;e.length>0&&f(S||"_explorer",W,e)}catch{}}let Ae=null,Me="",Re=null;const Ne=new Map,Le=new Map;let De=null;function Ke(){De&&(clearTimeout(De),De=null),se.requestRender()}async function je(e){const t=e.trim().split(/\s+/),o=t[0].toLowerCase();switch(o){case"/help":return $e(),ye(_.zinc200(w("Commands"))+"\n"+_.emerald("/help ")+_.zinc400("Show this help")+"\n"+_.emerald("/tree ")+_.zinc400("Display causal tree")+"\n"+_.emerald("/edges ")+_.zinc400("Display edge/spread table")+"\n"+_.emerald("/pos ")+_.zinc400("Display Kalshi positions")+"\n"+_.emerald("/eval ")+_.zinc400("Trigger deep evaluation")+"\n"+_.emerald("/switch <id>")+_.zinc400(" Switch thesis")+"\n"+_.emerald("/compact ")+_.zinc400("Compress conversation history")+"\n"+_.emerald("/new ")+_.zinc400("Start fresh session")+"\n"+_.emerald("/model <m> ")+_.zinc400("Switch model")+"\n"+_.emerald("/env ")+_.zinc400("Show environment variable status")+"\n"+(Ce.tradingEnabled?_.zinc600("─".repeat(30))+"\n"+_.emerald("/buy ")+_.zinc400("TICKER QTY PRICE — quick buy")+"\n"+_.emerald("/sell ")+_.zinc400("TICKER QTY PRICE — quick sell")+"\n"+_.emerald("/cancel ")+_.zinc400("ORDER_ID — cancel order")+"\n"+_.zinc600("─".repeat(30))+"\n":"")+(ge.length>0?_.zinc600("─".repeat(30))+"\n"+_.zinc200(w("Skills"))+"\n"+ge.map(e=>_.emerald(`/${e.name.padEnd(10)}`)+_.zinc400(e.description.slice(0,45))).join("\n")+"\n"+_.zinc600("─".repeat(30))+"\n":"")+_.emerald("/clear ")+_.zinc400("Clear screen (keeps history)")+"\n"+_.emerald("/exit ")+_.zinc400("Exit (auto-saves)")),$e(),!0;case"/tree":if($e(),x)ye(_.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one."));else try{$=await y.getContext(S),ye(_.zinc200(w("Causal Tree"))+"\n"+function(e){const t=e.causalTree;if(!t?.nodes?.length)return _.zinc600(" No causal tree data");const n=[];for(const e of t.nodes){const t=e.id||"",o=e.label||e.description||"",s="number"==typeof e.probability?Math.round(100*e.probability):"number"==typeof e.impliedProbability?Math.round(100*e.impliedProbability):null,i=(t.match(/\./g)||[]).length,r=" ".repeat(i+1);if(null!==s){const e=Math.round(s/10),i="█".repeat(e)+"░".repeat(10-e),a=s>=70?_.emerald:s>=40?_.amber:_.red,c=`${r}${_.zinc600(t)} ${_.zinc400(o)} `,l=` ${a(`${s}%`)} ${a(i)}`;n.push(c+l)}else n.push(`${r}${_.zinc600(t)} ${_.zinc400(o)}`)}return n.join("\n")}($))}catch(e){ye(_.red(`Error: ${e.message}`))}return $e(),!0;case"/edges":if($e(),x)try{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218)),t=((await e()).edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,10);if(0===t.length)ye(_.zinc400("No public edges available."));else{const e=t.map(e=>{const t=(e.title||"").slice(0,35).padEnd(35),n=(e.venue||"kalshi").padEnd(5),o=String(Math.round(e.price||0)).padStart(3)+"¢",s="+"+Math.round(e.edge||0);return` ${_.zinc400(t)} ${_.zinc600(n)} ${_.zinc400(o)} ${_.emerald(s.padStart(4))}`}).join("\n");ye(_.zinc200(w("Public Edges"))+"\n"+e)}}catch(e){ye(_.red(`Error: ${e.message}`))}else try{$=await y.getContext(S),Q&&($._positions=Q),ye(_.zinc200(w("Edges"))+"\n"+function(e){const t=e.edges;if(!t?.length)return _.zinc600(" No edge data");const n=e._positions||[],o=[];for(const e of t){const t=(e.market||e.marketId||"").slice(0,18).padEnd(18),s="number"==typeof e.marketPrice?`${e.marketPrice}¢`:"?",i="number"==typeof e.thesisPrice?`${e.thesisPrice}¢`:"?",r="number"==typeof e.edge?e.edge>0?`+${e.edge}`:`${e.edge}`:"?",a=e.orderbook||{},c="number"==typeof a.spread?`${a.spread}¢`:"?",l=a.liquidityScore||"low",d="high"===l?"■■■":"medium"===l?"■■ ":"■ ",u="high"===l?_.emerald:"medium"===l?_.amber:_.red,p=n.find(t=>t.ticker===e.marketId||e.marketId&&t.ticker?.includes(e.marketId));let h=_.zinc600("—");if(p){const e=p.side?.toUpperCase()||"YES",t="number"==typeof p.unrealized_pnl?p.unrealized_pnl>=0?_.emerald(`+$${(p.unrealized_pnl/100).toFixed(0)}`):_.red(`-$${(Math.abs(p.unrealized_pnl)/100).toFixed(0)}`):"";h=_.emerald(`${e} (${p.quantity}@${p.average_price_paid}¢ ${t})`)}o.push(` ${_.zinc200(t)} ${_.zinc400(s)} → ${_.zinc400(i)} edge ${r.includes("+")?_.emerald(r):_.red(r)} spread ${_.zinc600(c)} ${u(d)} ${u(l.padEnd(4))} ${h}`)}return o.join("\n")}($))}catch(e){ye(_.red(`Error: ${e.message}`))}return $e(),!0;case"/pos":$e();try{const e=await(0,c.getPositions)();if(!e)return ye(_.zinc600("Kalshi not configured")),!0;for(const t of e){const e=await(0,c.getMarketPrice)(t.ticker);null!==e&&(t.current_value=e,t.unrealized_pnl=Math.round((e-t.average_price_paid)*t.quantity))}Q=e,ye(_.zinc200(w("Positions"))+"\n"+function(e){if(!e?.length)return _.zinc600(" No positions");const t=[];let n=0;for(const o of e){const e=(o.ticker||"").slice(0,18).padEnd(18),s=(o.side||"yes").toUpperCase().padEnd(3),i=String(o.quantity||0),r=`${o.average_price_paid||0}¢`,a="number"==typeof o.current_value&&o.current_value>0?`${o.current_value}¢`:"?¢",c=o.unrealized_pnl||0;n+=c;const l=(c/100).toFixed(2),d=c>=0?_.emerald(`+$${l}`):_.red(`-$${Math.abs(parseFloat(l)).toFixed(2)}`),u=c>=0?_.emerald("▲"):_.red("▼");t.push(` ${_.zinc200(e)} ${_.zinc400(s)} ${_.zinc400(i)} @ ${_.zinc400(r)} now ${_.zinc200(a)} ${d} ${u}`)}const o=(n/100).toFixed(2);return t.push(_.zinc600(" "+"─".repeat(40))),t.push(n>=0?` Total P&L: ${_.emerald(w(`+$${o}`))}`:` Total P&L: ${_.red(w(`-$${Math.abs(parseFloat(o)).toFixed(2)}`))}`),t.join("\n")}(e))}catch(e){ye(_.red(`Error: ${e.message}`))}return $e(),!0;case"/eval":if($e(),x)return ye(_.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one.")),$e(),!0;ye(_.zinc600("Triggering evaluation...")),se.requestRender();try{const e=await y.evaluate(S);ye(_.emerald("Evaluation complete")+"\n"+_.zinc400(JSON.stringify(e,null,2)))}catch(e){ye(_.red(`Error: ${e.message}`))}return $e(),!0;case"/model":{const e=t.slice(1).join(" ").trim();return e?($e(),W=e.replace(/^openrouter\//,""),G=X(W),Pe.setModel(G),ce.modelName=W,ce.update(),ye(_.emerald(`Model switched to ${W}`)),$e(),se.requestRender(),!0):(ye(_.zinc400(`Current model: ${W}`)),!0)}case"/switch":{const n=t[1]?.trim();if(!n)return ye(_.zinc400("Usage: /switch <thesisId>")),!0;$e();try{Ee();const e=await y.getContext(n);S=e.thesisId||n,$=e;const t=Oe(e);"number"==typeof e.confidence&&Math.round(100*e.confidence);Pe.clearMessages();const o=g(S);o?.messages?.length>0?(Pe.replaceMessages(o.messages),Pe.setSystemPrompt(t),ye(_.emerald(`Switched to ${S.slice(0,8)}`)+_.zinc400(` (resumed ${o.messages.length} messages)`))):(Pe.setSystemPrompt(t),ye(_.emerald(`Switched to ${S.slice(0,8)}`)+_.zinc400(" (new session)"))),ce.setFromContext(e,le||void 0),pe.clear(),ye(qe(e,le))}catch(e){ye(_.red(`Switch failed: ${e.message}`))}return $e(),se.setFocus(he),se.requestRender(),!0}case"/compact":$e();try{const t=Pe.state.messages;if(t.length<=10)return ye(_.zinc400("Conversation too short to compact")),$e(),se.setFocus(he),!0;const n=3;let o=0,s=t.length;for(let e=t.length-1;e>=0;e--)if("user"===t[e].role&&(o++,o>=n)){s=e;break}if(s<=2)return ye(_.zinc400("Not enough complete turns to compact")),$e(),se.setFocus(he),!0;const a=t.slice(0,s),c=t.slice(s),l=new N(se,e=>_.emerald(e),e=>_.zinc600(e),"compacting with LLM...");l.start(),pe.addChild(l),se.requestRender();const d=[];let u=0;const p=12e3;for(const e of a){if(u>=p)break;let t="";if("string"==typeof e.content?t=e.content:Array.isArray(e.content)&&(t=e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")),!t)continue;const n=(e.role||"unknown").toUpperCase(),o=`[${n}]: ${t.slice(0,800)}`;d.push(o),u+=o.length}const m=d.join("\n\n"),g="google/gemini-2.0-flash-001",f="You are a conversation compressor. Given a conversation between a user and a prediction-market trading assistant, produce a dense summary that preserves:\n1. All factual conclusions, numbers, prices, and probabilities mentioned\n2. Key trading decisions, positions taken or discussed\n3. Signals injected, evaluations triggered, and their outcomes\n4. Any action items or pending questions\n\nOutput a structured summary. Be concise but preserve every important detail — this summary replaces the original messages for continued conversation. Do NOT add commentary or meta-text. Just the summary.";let y;try{const e=r?`${i}/api/proxy/llm`:"https://openrouter.ai/api/v1/chat/completions",t={model:g,messages:[{role:"system",content:f},{role:"user",content:`Summarize this conversation (${a.length} messages):\n\n${m}`}],max_tokens:2e3,temperature:.2},n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`,"HTTP-Referer":"https://simplefunctions.com","X-Title":"SF Agent Compact"},body:JSON.stringify(t)});if(!n.ok){const e=await n.text().catch(()=>"");throw new Error(`OpenRouter ${n.status}: ${e.slice(0,200)}`)}const o=await n.json();if(y=o.choices?.[0]?.message?.content||"",!y)throw new Error("Empty summary from LLM")}catch(e){const t=[];for(const e of a){const n="string"==typeof e.content?e.content:"";"user"===e.role&&n?t.push(`- User: ${n.slice(0,100)}`):"assistant"===e.role&&n&&t.push(`- Assistant: ${n.slice(0,150)}`)}y=`[LLM summary failed: ${e.message}. Fallback bullet points:]\n\n${t.slice(-20).join("\n")}`}l.stop(),pe.removeChild(l);const $=[{role:"user",content:`[Conversation summary — ${a.length} messages compressed]\n\n${y}`},{role:"assistant",content:"Understood. I have the full conversation context from the summary above. Continuing from where we left off."},...c];Pe.clearMessages(),Pe.replaceMessages($),Pe.setSystemPrompt(Ie),Ee(),ye(_.emerald(`Compacted: ${a.length} messages → summary + ${c.length} recent`)+_.zinc600(` (via ${g.split("/").pop()})`)),$e(),se.setFocus(he),se.requestRender()}catch(e){ye(_.red(`Compact failed: ${e.message||e}`)),$e(),se.setFocus(he),se.requestRender()}return!0;case"/new":return $e(),Ee(),Pe.clearMessages(),Pe.setSystemPrompt(Ie),pe.clear(),ye(_.emerald("Session cleared")+_.zinc400(" — fresh start")),$e(),se.requestRender(),!0;case"/env":{$e();const e=[{name:"SF_API_KEY",key:"SF_API_KEY",required:!0,mask:!0},{name:"SF_API_URL",key:"SF_API_URL",required:!1,mask:!1},{name:"OPENROUTER_KEY",key:"OPENROUTER_API_KEY",required:!0,mask:!0},{name:"KALSHI_KEY_ID",key:"KALSHI_API_KEY_ID",required:!1,mask:!0},{name:"KALSHI_PEM_PATH",key:"KALSHI_PRIVATE_KEY_PATH",required:!1,mask:!1},{name:"TAVILY_API_KEY",key:"TAVILY_API_KEY",required:!1,mask:!0}].map(e=>{const t=process.env[e.key];if(t){const n=e.mask?t.slice(0,Math.min(8,t.length))+"..."+t.slice(-4):t;return` ${e.name.padEnd(18)} ${_.emerald("✓")} ${_.zinc400(n)}`}{const t=e.required?"必须":"可选";return` ${e.name.padEnd(18)} ${_.red("✗")} ${_.zinc600(`未配置(${t})`)}`}});return ye(_.zinc200(w("Environment"))+"\n"+e.join("\n")),$e(),!0}case"/clear":{const e=[...pe.children||[]];for(const t of e)try{pe.removeChild(t)}catch{}return $e(),V=!1,ne=null,se.setFocus(he),se.requestRender(),!0}case"/buy":{const[,o,s,i]=t;if(!o||!s||!i)return ye(_.zinc400("Usage: /buy TICKER QTY PRICE_CENTS (e.g. /buy KXWTIMAX-26DEC31-T135 100 50)")),!0;if(!Ce.tradingEnabled)return ye(_.red("Trading disabled. Run: sf setup --enable-trading")),!0;$e();if((await we(`BUY ${s}x ${o} YES @ ${i}¢ — execute? (y/n)`)).toLowerCase().startsWith("y"))try{const{createOrder:e}=await Promise.resolve().then(n.t.bind(n,96139,23)),t=await e({ticker:o,side:"yes",action:"buy",type:"limit",count:parseInt(s),yes_price:parseInt(i)});ye(_.emerald("✓ Order placed: "+((t.order||t).order_id||"OK")))}catch(e){ye(_.red("✗ "+e.message))}else ye(_.zinc400("Cancelled."));return $e(),!0}case"/sell":{const[,o,s,i]=t;if(!o||!s||!i)return ye(_.zinc400("Usage: /sell TICKER QTY PRICE_CENTS")),!0;if(!Ce.tradingEnabled)return ye(_.red("Trading disabled. Run: sf setup --enable-trading")),!0;$e();if((await we(`SELL ${s}x ${o} YES @ ${i}¢ — execute? (y/n)`)).toLowerCase().startsWith("y"))try{const{createOrder:e}=await Promise.resolve().then(n.t.bind(n,96139,23)),t=await e({ticker:o,side:"yes",action:"sell",type:"limit",count:parseInt(s),yes_price:parseInt(i)});ye(_.emerald("✓ Order placed: "+((t.order||t).order_id||"OK")))}catch(e){ye(_.red("✗ "+e.message))}else ye(_.zinc400("Cancelled."));return $e(),!0}case"/cancel":{const[,o]=t;if(!o)return ye(_.zinc400("Usage: /cancel ORDER_ID")),!0;if(!Ce.tradingEnabled)return ye(_.red("Trading disabled. Run: sf setup --enable-trading")),!0;$e();try{const{cancelOrder:e}=await Promise.resolve().then(n.t.bind(n,96139,23));await e(o),ye(_.emerald(`✓ Order ${o} cancelled.`))}catch(e){ye(_.red("✗ "+e.message))}return $e(),!0}case"/exit":case"/quit":return Fe(),!0;default:{const t=ge.find(e=>e.trigger===o);if(t){$e(),ye(_.zinc200(`Running skill: ${w(t.name)}`)+_.zinc600(` — ${t.description.slice(0,60)}`)),$e(),se.requestRender(),V=!0;try{await Pe.prompt(t.prompt)}catch(e){ye(_.red(`Skill error: ${e.message}`))}finally{V=!1}return!0}return!1}}}function Fe(){te&&clearInterval(te),Re&&Re.stop(),Ee(),se.stop(),process.exit(0)}function qe(e,t){const n=[];if(e._explorerMode){const t=e.edges?.length||0,o=e.theses?.length||0;n.push(_.zinc600("─".repeat(55))),n.push(" "+_.emerald(w("Explorer mode"))+_.zinc600(" — full market access, no thesis")),n.push(" "+_.zinc600(`${o} public theses │ ${t} edges tracked`)),n.push(_.zinc600("─".repeat(55)));const s=e.edges||[];if(s.length>0){const e=[...s].sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5);n.push(" "+_.zinc400(w("TOP PUBLIC EDGES"))+_.zinc600(" mkt edge"));for(const t of e){const e=(t.title||"").slice(0,30).padEnd(30),o=String(Math.round(t.price||0)).padStart(3)+"¢",s=t.edge||0,i="+"+Math.round(s),r=Math.abs(s)>=15?_.emerald:Math.abs(s)>=8?_.amber:_.zinc400;n.push(` ${_.zinc400(e)} ${_.zinc400(o)} ${r(i.padStart(4))}`)}}return n.push(_.zinc600("─".repeat(55))),n.push(" "+_.zinc600("Ask anything, or describe a view to create a thesis.")),n.push(_.zinc600("─".repeat(55))),n.join("\n")}const o=e.thesis||e.rawThesis||"N/A",s=o.length>100?o.slice(0,100)+"...":o,i="number"==typeof e.confidence?Math.round(100*e.confidence):"string"==typeof e.confidence?Math.round(100*parseFloat(e.confidence)):0,r=e.lastEvaluation?.confidenceDelta?Math.round(100*e.lastEvaluation.confidenceDelta):0,a=0!==r?` (${r>0?"+":""}${r})`:"",c=e.lastEvaluation?.evaluatedAt?Math.round((Date.now()-new Date(e.lastEvaluation.evaluatedAt).getTime())/36e5):null;if(n.push(_.zinc600("─".repeat(55))),n.push(" "+_.zinc200(w(s))),n.push(" "+_.zinc600(`${e.status||"active"} ${i}%${a}`)+(null!==c?_.zinc600(` │ last eval: ${c<1?"<1":c}h ago`):"")),n.push(_.zinc600("─".repeat(55))),t&&t.length>0){n.push(" "+_.zinc400(w("POSITIONS")));let e=0;for(const o of t){const t=o.unrealized_pnl||0;e+=t;const s=t>=0?_.emerald(`+$${(t/100).toFixed(2)}`):_.red(`-$${(Math.abs(t)/100).toFixed(2)}`),i=(o.ticker||"").slice(0,28).padEnd(28),r=String(o.quantity||0).padStart(5),a="yes"===o.side?_.emerald("Y"):_.red("N");n.push(` ${_.zinc400(i)} ${r} ${a} ${s}`)}const o=e>=0?_.emerald(w(`+$${(e/100).toFixed(2)}`)):_.red(w(`-$${(Math.abs(e)/100).toFixed(2)}`));n.push(` ${"".padEnd(28)} ${_.zinc600("Total")} ${o}`)}const l=e.edges||[];if(l.length>0){const e=[...l].sort((e,t)=>Math.abs(t.edge||t.edgeSize||0)-Math.abs(e.edge||e.edgeSize||0)).slice(0,5);n.push(_.zinc600("─".repeat(55))),n.push(" "+_.zinc400(w("TOP EDGES"))+_.zinc600(" mkt edge liq"));for(const t of e){const e=(t.market||t.marketTitle||t.marketId||"").slice(0,30).padEnd(30),o=String(Math.round(t.marketPrice||0)).padStart(3)+"¢",s=t.edge||t.edgeSize||0,i=(s>0?"+":"")+Math.round(s),r=t.orderbook?.liquidityScore||("polymarket"===t.venue?"-":"?"),a=Math.abs(s)>=15?_.emerald:Math.abs(s)>=8?_.amber:_.zinc400;n.push(` ${_.zinc400(e)} ${_.zinc400(o)} ${a(i.padStart(4))} ${_.zinc600(r)}`)}}return n.push(_.zinc600("─".repeat(55))),n.join("\n")}Pe.subscribe(e=>{if("message_start"===e.type&&(Me="",Ae=null,Re=new N(se,e=>_.emerald(e),e=>_.zinc600(e),"thinking..."),Re.start(),pe.addChild(Re),se.requestRender()),"message_update"===e.type){const t=e.assistantMessageEvent;"text_delta"===t.type&&(Re&&(Re.stop(),pe.removeChild(Re),Re=null,Ae=new M("",1,0,ie,re),pe.addChild(Ae)),Me+=t.delta,Ae&&Ae.setText(Me),De||(De=setTimeout(()=>{De=null,se.requestRender()},66)))}if("message_end"===e.type&&(Re&&(Re.stop(),pe.removeChild(Re),Re=null),Ae&&Me&&Ae.setText(Me),$e(),Ae=null,Me="",Ke()),"agent_end"===e.type&&(V=!1,Ee(),Ke(),ee)){const e=ee;ee=null,He(e)}if("tool_execution_start"===e.type){const t=new H(_.zinc600(` ▸ ${e.toolName}...`));Ne.set(e.toolCallId||e.toolName,Date.now()),Le.set(e.toolCallId||e.toolName,t),pe.addChild(t),Y++,ce.toolCount=Y,ce.update(),se.requestRender()}if("tool_execution_end"===e.type){const t=e.toolCallId||e.toolName,n=Ne.get(t),o=n?((Date.now()-n)/1e3).toFixed(1):"?",s=Le.get(t);s&&(e.isError?s.setText(_.red(` ✗ ${e.toolName} (${o}s) error`)):s.setText(_.zinc600(` ▸ ${e.toolName} `)+_.emerald("✓")+_.zinc600(` ${o}s`))),Ne.delete(t),Le.delete(t),se.requestRender()}}),he.onSubmit=async e=>{const t=e.trim();if(!t)return;if(ne){const{resolve:e}=ne;ne=null;const n=new A(_.zinc400(" > ")+_.zinc200(t),1,0);return pe.addChild(n),$e(),se.requestRender(),void e(t)}if(V)return;if(he.addToHistory(t),t.startsWith("/")){if(await je(t))return}V=!0;const n=new A(_.emerald(w(">"))+" "+_.white(t),1,0);pe.addChild(n),$e(),se.requestRender();try{await Pe.prompt(t)}catch(e){Re&&(Re.stop(),pe.removeChild(Re),Re=null),ye(_.red(`Error: ${e.message}`)),$e(),V=!1}},se.addInputListener(e=>{if(""===e)return Fe(),{consume:!0}}),process.on("SIGINT",Fe),process.on("SIGTERM",Fe);const Ue=Te?_.zinc600(`resumed (${Pe.state.messages.length} messages)`):_.zinc600("new session");ye(qe($,le)),ye(" "+Ue),$e();const ze=.03;function He(e){const t=Math.abs(e.confidenceDelta||0),n=Math.round(100*(e.confidence||0)),o=Math.round(100*(e.confidenceDelta||0)),s=o>0?"+":"";if(t>=ze){const t=o>0?"▲":"▼";ye((o>0?_.emerald:_.red)(` ${t} Heartbeat: confidence ${s}${o}% → ${n}%`)),e.latestSummary&&ye(_.zinc400(` ${e.latestSummary.slice(0,100)}`)),$e(),ce.setFromContext({...$,confidence:e.confidence,lastEvaluation:{confidenceDelta:e.confidenceDelta}},le||void 0),se.requestRender(),V=!0;const i=`[HEARTBEAT ALERT] Confidence just changed ${s}${o}% to ${n}%. ${e.evaluationCount} evaluation(s) since last check. Latest: "${(e.latestSummary||"").slice(0,150)}". Briefly analyze what happened and whether any action is needed. Be concise.`;Pe.prompt(i).catch(e=>{ye(_.red(`Error: ${e.message}`)),V=!1})}else t>0&&(ye(_.zinc600(` ─ heartbeat: ${n}% (${s}${o}%) — ${e.evaluationCount||0} eval(s)`)),se.requestRender())}x||(te=setInterval(async()=>{try{const e=await y.getChanges(S,Z);if(Z=(new Date).toISOString(),!e.changed)return;V||ne?ee=e:He(e)}catch{}},6e4));se.start()};const s=o(n(79896)),i=o(n(16928)),r=o(n(70857)),a=n(19218),c=n(96139),l=n(34331),d=n(97325),u=n(11627),p=n(40101);function h(){return i.default.join(r.default.homedir(),".sf","sessions")}function m(e){return i.default.join(h(),`${e}.json`)}function g(e){const t=m(e);try{if(s.default.existsSync(t))return JSON.parse(s.default.readFileSync(t,"utf-8"))}catch{}return null}function f(e,t,n){const o=h();s.default.mkdirSync(o,{recursive:!0}),s.default.writeFileSync(m(e),JSON.stringify({thesisId:e,model:t,updatedAt:(new Date).toISOString(),messages:n},null,2))}const y=(e,t,n)=>o=>`[38;2;${e};${t};${n}m${o}`,$=(e,t,n)=>o=>`[48;2;${e};${t};${n}m${o}`,w=e=>`${e}`,k=e=>`${e}`,b=e=>`${e}`,v=e=>`${e}`,_={emerald:y(16,185,129),zinc200:y(228,228,231),zinc400:y(161,161,170),zinc600:y(82,82,91),zinc800:y(39,39,42),red:y(239,68,68),amber:y(245,158,11),white:y(255,255,255),bgZinc900:$(24,24,27),bgZinc800:$(39,39,42)}},72768:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.announcementsCommand=async function(e){const t=await(0,o.getExchangeAnnouncements)();if(e.json)return void console.log(JSON.stringify(t,null,2));if(0===t.length)return void console.log(`${s.c.dim}No announcements.${s.c.reset}`);console.log(`${s.c.bold}${s.c.cyan}Exchange Announcements${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(70)}${s.c.reset}`);for(const e of t.slice(0,20)){const t=e.created_time?new Date(e.created_time).toLocaleDateString():"",n=e.type?`[${e.type}]`:"";if(console.log(` ${s.c.dim}${t}${s.c.reset} ${n} ${e.title||e.message||""}`),e.body){const t=String(e.body).slice(0,120);console.log(` ${s.c.dim}${t}${s.c.reset}`)}}console.log(`\n${s.c.dim}${t.length} announcement(s)${s.c.reset}`)};const o=n(96139),s=n(99236)},71783:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.augmentCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl);console.log(`${t.dryRun?"Previewing":"Running"} tree augmentation for ${e.slice(0,8)}...`);const s=await n.augmentTree(e,t.dryRun);if(t.json)return void console.log(JSON.stringify(s,null,2));console.log(),s.warning&&(console.log(` ⚠ ${s.warning}`),console.log());if(s.suggestedNodes?.length>0){console.log(` Suggested Nodes (${s.suggestedNodes.length} from evaluations)`);for(const e of s.suggestedNodes)console.log(` • ${e.label} (parent: ${e.parentNodeId}, est: ${Math.round(100*e.estimatedProbability)}%, seen ${e.frequency}x)`);console.log()}if(s.acceptedNodes?.length>0){console.log(` Accepted Nodes (${s.acceptedNodes.length})`);for(const e of s.acceptedNodes)console.log(` + ${e.id}: ${e.label} (prob: ${Math.round(100*e.probability)}%, imp: ${e.importance})`);if(console.log(),Object.keys(s.updatedImportanceWeights||{}).length>0){console.log(" Rebalanced Weights");for(const[e,t]of Object.entries(s.updatedImportanceWeights))console.log(` ${e} → ${t}`);console.log()}s.applied?console.log(" ✓ Applied to causal tree"):t.dryRun&&console.log(" Dry run — use without --dry-run to apply")}else console.log(" No nodes accepted.");console.log()};const o=n(19218)},44040:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.balanceCommand=async function(e){const t=await(0,o.getBalance)();if(!t)throw new Error("Kalshi not configured. Run: sf setup --kalshi");if(e.json)return void console.log(JSON.stringify(t,null,2));console.log(`${s.c.bold}${s.c.cyan}Kalshi Account${s.c.reset}`),console.log(` Balance: $${t.balance.toFixed(2)}`),console.log(` Portfolio Value: $${t.portfolioValue.toFixed(2)}`)};const o=n(96139),s=n(99236)},69903:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bookCommand=async function(e,t){const n=[];if(t.poly){console.log(`${r.c.dim}Searching Polymarket for "${t.poly}"...${r.c.reset}`);const e=await(0,i.polymarketSearch)(t.poly,10);for(const o of e)for(const e of(o.markets||[]).slice(0,5)){if(!e.active||e.closed||!e.clobTokenIds)continue;const s=(0,i.parseClobTokenIds)(e.clobTokenIds);if(!s)continue;const r=await(0,i.polymarketGetOrderbookWithDepth)(s[0]);if(!r)continue;const c=(0,i.parseOutcomePrices)(e.outcomePrices),l={venue:"polymarket",ticker:e.conditionId?.slice(0,16)||e.id,title:e.groupItemTitle?`${o.title}: ${e.groupItemTitle}`:e.question||o.title,bestBid:r.bestBid,bestAsk:r.bestAsk,spread:r.spread,bidDepth:r.totalBidDepth,askDepth:r.totalAskDepth,liquidityScore:r.liquidityScore,volume24h:e.volume24hr||0,openInterest:e.liquidityNum||0,lastPrice:c[0]?(0,i.toCents)(c[0]):0,expiry:e.endDateIso||null,bidLevels:r.levels.bids.slice(0,5).map(e=>({price:Math.round(100*parseFloat(e.price)),size:Math.round(parseFloat(e.size))})),askLevels:r.levels.asks.slice(0,5).map(e=>({price:Math.round(100*parseFloat(e.price)),size:Math.round(parseFloat(e.size))}))};if(t.history)try{const e=await(0,i.polymarketGetPriceHistory)({tokenId:s[0],interval:"1w",fidelity:360});e.length>0&&(l.sparkline=a(e.map(e=>100*e.p)))}catch{}n.push(l)}}for(const i of e){console.log(`${r.c.dim}Fetching ${i}...${r.c.reset}`);try{const e=await(0,o.kalshiFetchMarket)(i),c=await(0,s.getPublicOrderbook)(i),l=(c?.yes_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),d=(c?.no_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),u=l[0]?.price||0,p=d.length>0?100-d[0].price:100,h=p-u,m=l.reduce((e,t)=>e+t.size,0),g=d.reduce((e,t)=>e+t.size,0),f=l.slice(0,3).reduce((e,t)=>e+t.size,0)+d.slice(0,3).reduce((e,t)=>e+t.size,0),y=h<=2&&f>=500?"high":h<=5&&f>=100?"medium":"low",$=100*parseFloat(e.last_price_dollars||"0"),w={venue:"kalshi",ticker:e.ticker||i,title:e.title||e.subtitle||i,bestBid:u,bestAsk:p,spread:h,bidDepth:m,askDepth:g,liquidityScore:y,volume24h:parseFloat(e.volume_24h_fp||"0"),openInterest:parseFloat(e.open_interest_fp||"0"),lastPrice:Math.round($),expiry:e.close_time||e.expiration_time||null,bidLevels:l.slice(0,5),askLevels:d.slice(0,5).map(e=>({price:100-e.price,size:e.size}))};if(t.history){if((0,s.isKalshiConfigured)())try{const e=Math.floor(Date.now()/1e3),t=e-604800,n=await(0,s.getBatchCandlesticks)({tickers:[i],startTs:t,endTs:e,periodInterval:1440}),o=n.find(e=>e.market_ticker===i)||n[0],r=o?.candlesticks||[];if(Array.isArray(r)&&r.length>0){const e=r.map(e=>{const t=e.price?.close_dollars??e.yes_ask?.close_dollars??e.yes_bid?.close_dollars??e.close??e.price,n="string"==typeof t?100*parseFloat(t):"number"==typeof t?t:0;return Math.round(n)}).filter(e=>e>0);e.length>=2&&(w.sparkline=a(e))}}catch{}if(!w.sparkline){const t=100*parseFloat(e.previous_price_dollars||"0");if(t>0&&Math.abs(t-w.lastPrice)>0){const e=w.lastPrice-Math.round(t),n=e>=0?r.c.green:r.c.red,o=e>=0?`+${e}`:`${e}`;w.sparkline=`prev ${Math.round(t)}¢ → now ${w.lastPrice}¢ ${n}${o}${r.c.reset}`}}}n.push(w)}catch(e){console.error(`${r.c.red}Failed to fetch ${i}: ${e.message}${r.c.reset}`)}}if(0===n.length)return void console.log(`\n ${r.c.dim}No markets found. Check the ticker and try again.${r.c.reset}\n`);if(t.json)return void console.log(JSON.stringify(n,null,2));for(const e of n){const t="polymarket"===e.venue?`${r.c.blue}POLY${r.c.reset}`:`${r.c.cyan}KLSH${r.c.reset}`;console.log(),console.log(`${r.c.bold}${t} ${e.title}${r.c.reset}`),console.log(`${r.c.dim}${e.ticker}${r.c.reset}`),console.log();const n="high"===e.liquidityScore?r.c.green:"medium"===e.liquidityScore?r.c.yellow:r.c.red;if(console.log(` Last ${r.c.bold}${e.lastPrice}¢${r.c.reset} Bid ${r.c.green}${e.bestBid}¢${r.c.reset} Ask ${r.c.red}${e.bestAsk}¢${r.c.reset} Spread ${n}${e.spread}¢${r.c.reset} Liq ${n}${e.liquidityScore}${r.c.reset}`),console.log(` Vol24h ${(0,r.vol)(e.volume24h)} OI ${(0,r.vol)(e.openInterest)}`+(e.expiry?` Expires ${e.expiry.slice(0,10)}`:"")),e.sparkline&&console.log(` 7d ${e.sparkline}`),e.bidLevels&&e.askLevels){console.log(),console.log(` ${r.c.dim}${(0,r.pad)("BID",18)} ${(0,r.pad)("ASK",18)}${r.c.reset}`),console.log(` ${r.c.dim}${"─".repeat(38)}${r.c.reset}`);const t=Math.max(e.bidLevels.length,e.askLevels.length);for(let n=0;n<Math.min(t,5);n++){const t=e.bidLevels[n],o=e.askLevels[n],s=t?`${r.c.green}${(0,r.rpad)(`${t.price}¢`,5)}${r.c.reset} ${(0,r.rpad)(String(t.size),8)}`:(0,r.pad)("",18),i=o?`${r.c.red}${(0,r.rpad)(`${o.price}¢`,5)}${r.c.reset} ${(0,r.rpad)(String(o.size),8)}`:"";console.log(` ${s} ${i}`)}console.log(` ${r.c.dim}depth: ${e.bidDepth} bid / ${e.askDepth} ask${r.c.reset}`)}console.log()}};const o=n(19218),s=n(96139),i=n(34331),r=n(99236);function a(e){if(e.length<2)return"";const t=Math.min(...e),n=Math.max(...e)-t||1,o=e.map(e=>"▁▂▃▄▅▆▇█"[Math.round((e-t)/n*7)]).join(""),s=Math.round(e[0]),i=Math.round(e[e.length-1]),a=i-s;return`${o} ${s}¢→${i}¢ ${a>=0?r.c.green:r.c.red}${a>=0?`+${a}`:`${a}`}${r.c.reset}`}},80928:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cancelCommand=async function(e,t){if((0,s.requireTrading)(),t.all){const e=await(0,o.getOrders)({status:"resting",limit:200});if(!e)throw new Error("Kalshi not configured.");let n=e.orders;if(t.ticker&&(n=n.filter(e=>(e.ticker||"").startsWith(t.ticker))),0===n.length)return void console.log(`\n ${i.c.dim}No resting orders to cancel.${i.c.reset}\n`);if(console.log(`\n Cancelling ${n.length} order(s)...`),!t.yesIAmSure){for(let e=3;e>0;e--)process.stdout.write(` Executing in ${e}... (Ctrl+C to cancel)\r`),await new Promise(e=>setTimeout(e,1e3));process.stdout.write(" Executing... \n")}for(let e=0;e<n.length;e+=20){const t=n.slice(e,e+20).map(e=>e.order_id);await(0,o.batchCancelOrders)(t)}return void console.log(`\n ${i.c.green}✓${i.c.reset} Cancelled ${n.length} order(s).\n`)}if(!e)throw new Error("Usage: sf cancel <orderId> or sf cancel --all");await(0,o.cancelOrder)(e),console.log(`\n ${i.c.green}✓${i.c.reset} Order ${e} cancelled.\n`)};const o=n(96139),s=n(11627),i=n(99236)},97499:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contextCommand=async function(e,t){if(!e){const e=await fetch(`${t.apiUrl||a}/api/public/context`);if(!e.ok)return void console.error(` Error: ${e.status} ${await e.text()}`);const n=await e.json();if(t.share)return void await(0,r.shareOutput)("context","",n);if(t.json)return void console.log(JSON.stringify(n,null,2));const o=n.scannedAt?(0,i.shortDate)(n.scannedAt):"no scan yet",s=n.meta||{};console.log(),console.log(`${i.c.bold}Markets${i.c.reset} ${i.c.dim}${s.totalMarkets||0} markets (K:${s.kalshiMarkets||0} P:${s.polymarketMarkets||0}) · scan: ${o}${i.c.reset}`),console.log();const l=n.traditional||[];if(l.length>0){const e=l.map(e=>{const t=e.changePct||0,n=t>0?i.c.green:t<0?i.c.red:i.c.dim,o=t>0?"+":"";return`${i.c.bold}${e.symbol}${i.c.reset} ${e.price} ${n}${o}${t.toFixed(1)}%${i.c.reset}`}).join(" ");console.log(` ${e}`),console.log()}const d=n.highlights||[];if(d.length>0){console.log(`${i.c.bold}${i.c.cyan}Highlights${i.c.reset}`);for(const e of d)console.log(` ${i.c.bold}${e.title}${i.c.reset}`),console.log(` ${i.c.dim}${e.detail}${i.c.reset}`),e.relatedTickers?.length>0&&console.log(` ${i.c.dim}tickers: ${e.relatedTickers.join(", ")}${i.c.reset}`),console.log(` ${i.c.cyan}→ ${e.suggestedAction}${i.c.reset}`),console.log()}const u=n.categories||[];if(u.length>0){console.log(`${i.c.bold}Categories${i.c.reset} ${i.c.dim}(${u.length} total)${i.c.reset}`),console.log(`${i.c.dim}${"─".repeat(70)}${i.c.reset}`);for(const e of u){const t=e.description?` ${i.c.dim}${e.description}${i.c.reset}`:"";console.log(`\n ${i.c.bold}${e.name}${i.c.reset} ${i.c.dim}${e.marketCount} mkts · vol ${(0,i.vol)(e.totalVolume24h)}${i.c.reset}${t}`);const n=e.topMovers||[];if(n.length>0)for(const e of n){const t="kalshi"===e.venue?`${i.c.cyan}K${i.c.reset}`:`${i.c.magenta}P${i.c.reset}`,n=e.change24h||0,o=n>0?i.c.green:n<0?i.c.red:i.c.dim,s=0!==n?`${o}${n>0?"+":""}${n}¢${i.c.reset}`:"";console.log(` ${t} ${(0,i.rpad)(`${e.price}¢`,5)} ${(0,i.rpad)(s,14)} ${(0,i.trunc)(e.title,45)} ${i.c.dim}${e.ticker.slice(0,18)}${i.c.reset}`),e.whyInteresting&&console.log(` ${i.c.dim}${e.whyInteresting}${i.c.reset}`)}const o=e.mostLiquid||[];if(o.length>0)for(const e of o){const t="kalshi"===e.venue?`${i.c.cyan}K${i.c.reset}`:`${i.c.magenta}P${i.c.reset}`;console.log(` ${t} ${(0,i.rpad)(`${e.price}¢`,5)} spread ${e.spread}¢ vol ${(0,i.vol)(Math.round(e.volume24h))} ${i.c.dim}${(0,i.trunc)(e.title,35)}${i.c.reset}`)}}console.log()}const p=n.edges||[];if(p.length>0){console.log(`${i.c.bold}Thesis Edges${i.c.reset}`);for(const e of p.slice(0,6)){const t="kalshi"===e.venue?`${i.c.cyan}K${i.c.reset}`:`${i.c.magenta}P${i.c.reset}`,n=e.edge>0?i.c.green:i.c.red;console.log(` ${t} ${(0,i.rpad)(`${e.price}¢`,5)} ${n}edge ${e.edge>0?"+":""}${e.edge}¢${i.c.reset} ${(0,i.trunc)(e.title,40)} ${i.c.dim}${e.thesisSlug||""}${i.c.reset}`)}console.log()}const h=n.signals||[];if(h.length>0){console.log(`${i.c.bold}Recent Evaluations${i.c.reset}`);for(const e of h.slice(0,5)){const t=e.confidenceDelta,n=t>0?`${i.c.green}+${t}%${i.c.reset}`:t<0?`${i.c.red}${t}%${i.c.reset}`:`${i.c.dim}0%${i.c.reset}`,o=c(e.evaluatedAt);console.log(` ${(0,i.rpad)(o,5)} ${(0,i.rpad)(e.thesisSlug||"?",18)} ${(0,i.rpad)(n,14)} ${(0,i.trunc)(e.summary,50)}`)}console.log()}return console.log(`${i.c.dim}${"─".repeat(60)}${i.c.reset}`),console.log(` ${i.c.cyan}sf query${i.c.reset} "topic" ${i.c.dim}ask anything${i.c.reset}`),console.log(` ${i.c.cyan}sf scan${i.c.reset} "keywords" ${i.c.dim}search markets${i.c.reset}`),console.log(` ${i.c.cyan}sf explore${i.c.reset} ${i.c.dim}public theses${i.c.reset}`),console.log(` ${i.c.cyan}sf create${i.c.reset} "thesis" ${i.c.dim}start monitoring${i.c.reset}`),void console.log()}const n=new o.SFClient(t.apiKey,t.apiUrl),l=await n.getContext(e);if(t.json)return void console.log(JSON.stringify(l,null,2));console.log(`\n${i.c.bold}Thesis:${i.c.reset} ${l.thesis||l.rawThesis||"(unknown)"}`);const d=null!==l.confidence&&void 0!==l.confidence?(0,i.pct)(l.confidence):"-",u=l.lastEvaluation?.confidenceDelta,p=u?` (${(0,i.delta)(u)} since last eval)`:"";console.log(`${i.c.bold}Confidence:${i.c.reset} ${d}${p}`),console.log(`${i.c.bold}Status:${i.c.reset} ${l.status}`),console.log(`${i.c.bold}Last Updated:${i.c.reset} ${(0,i.shortDate)(l.updatedAt)}`);const h=l.causalTree?.nodes;if(h&&h.length>0){(0,i.header)("Causal Tree");for(const e of h){const t=" ".repeat((e.depth||0)+1),n=void 0!==e.probability?(0,i.pct)(e.probability):"-",o=e.label||e.id;console.log(`${t}${i.c.cyan}${e.id}${i.c.reset} ${(0,i.pad)(o,40)} ${(0,i.rpad)(n,5)}`)}}let m=null;if((0,s.isKalshiConfigured)())try{m=await(0,s.getPositions)()}catch{}const g=new Map;if(m)for(const e of m)g.set(e.ticker,e);const f=l.edges;if(f&&f.length>0){(0,i.header)("Top Edges");const e=[...f].sort((e,t)=>Math.abs(t.edge??t.edgeSize??0)-Math.abs(e.edge??e.edgeSize??0));for(const t of e.slice(0,10)){const e=t.edge??t.edgeSize??0,n=e>10?i.c.green:e>0?i.c.yellow:i.c.red,o=t.marketPrice??t.currentPrice??0,s=t.market||t.marketTitle||t.marketId||"?",r=t.orderbook,a=r?` ${i.c.dim}spread ${r.spread}¢ ${r.liquidityScore}${i.c.reset}`:"",c=g.get(t.marketId);let l="";if(c){const e=c.unrealized_pnl||0,t=e>0?i.c.green:e<0?i.c.red:i.c.dim,n=e>=0?`+$${(e/100).toFixed(0)}`:`-$${(Math.abs(e)/100).toFixed(0)}`;l=` ${i.c.cyan}← ${c.quantity}@${c.average_price_paid}¢ ${t}${n}${i.c.reset}`}console.log(` ${(0,i.pad)(s,35)} ${(0,i.rpad)(o.toFixed(0)+"¢",5)} ${n}edge ${e>0?"+":""}${e.toFixed(1)}${i.c.reset} ${i.c.dim}${t.venue||""}${i.c.reset}`+a+l)}}if(l.lastEvaluation?.summary&&((0,i.header)("Last Evaluation"),console.log(` ${i.c.dim}${(0,i.shortDate)(l.lastEvaluation.evaluatedAt)} | model: ${l.lastEvaluation.model||""}${i.c.reset}`),console.log(` ${l.lastEvaluation.summary}`),l.lastEvaluation.positionRecommendations?.length>0)){console.log(`\n ${i.c.bold}Position Recommendations:${i.c.reset}`);for(const e of l.lastEvaluation.positionRecommendations){const t="hold"===e.recommendation?i.c.dim:"close"===e.recommendation?i.c.red:i.c.yellow;console.log(` [${(e.positionId||"").slice(0,8)}] ${t}${e.recommendation}${i.c.reset} — ${e.reason}`)}}l.edgeMeta?.lastRescanAt&&console.log(`\n${i.c.dim}Last rescan: ${(0,i.shortDate)(l.edgeMeta.lastRescanAt)}${i.c.reset}`);console.log("")};const o=n(19218),s=n(96139),i=n(99236),r=n(35178),a=process.env.SF_API_URL||"https://simplefunctions.dev";function c(e){const t=Date.now()-new Date(e).getTime(),n=Math.round(t/6e4);if(n<60)return`${n}m`;const o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}},46222:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl),i=!t.async;t.json||(i?console.log(`${s.c.dim}Creating thesis (sync mode — waiting for formation)...${s.c.reset}`):console.log(`${s.c.dim}Creating thesis (async mode)...${s.c.reset}`));const r=await n.createThesis(e,i),a=r.thesis?.id||r.thesisId||r.id||null;if(t.json)return void console.log(JSON.stringify({id:a,status:r.thesis?.status||r.status||"forming",result:r},null,2));a||(console.error(`${s.c.red}✗${s.c.reset} Thesis creation returned no ID.`),console.error(`${s.c.dim}Response: ${JSON.stringify(r).slice(0,200)}${s.c.reset}`),process.exit(1));console.log(`\n${s.c.green}✓${s.c.reset} Thesis created`),console.log(` ${s.c.bold}ID:${s.c.reset} ${a}`),console.log(` ${s.c.bold}Status:${s.c.reset} ${r.thesis?.status||r.status}`),r.thesis?.confidence&&console.log(` ${s.c.bold}Confidence:${s.c.reset} ${Math.round(100*parseFloat(r.thesis.confidence))}%`);r.thesis?.causalTree?.nodes&&console.log(` ${s.c.bold}Nodes:${s.c.reset} ${r.thesis.causalTree.nodes.length}`);r.thesis?.edgeAnalysis?.edges&&console.log(` ${s.c.bold}Edges:${s.c.reset} ${r.thesis.edgeAnalysis.edges.length}`);console.log(`\n${s.c.dim}View: sf get ${(0,s.shortId)(a)}${s.c.reset}`),console.log(`${s.c.dim}Context: sf context ${(0,s.shortId)(a)}${s.c.reset}`)};const o=n(19218),s=n(99236)},60952:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dashboardCommand=async function(e){if(!e?.json&&!e?.once)return void await(0,c.startDashboard)();const t=new o.SFClient(e?.apiKey,e?.apiUrl),[n,a]=await Promise.all([t.listTheses(),(0,s.getPositions)().catch(()=>null)]),u=n.theses||n,p=[];for(const e of u)try{const n=await t.getContext(e.id);p.push(n)}catch{p.push(null)}if(a)for(const e of a){const t=await(0,s.getMarketPrice)(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity))}const h=[];for(const e of p)if(e?.edges)for(const t of e.edges)h.push(t);const m=new Map;for(const e of h){const t=m.get(e.marketId);(!t||Math.abs(e.edge)>Math.abs(t.edge))&&m.set(e.marketId,e)}const g=new Set(a?.map(e=>e.ticker)||[]),f=[...m.values()].filter(e=>!g.has(e.marketId)).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,10),[y,$,w]=await Promise.all([e?.json?(0,s.getOrders)({status:"resting"}).catch(()=>[]):Promise.resolve([]),e?.json?(0,s.getBalance)().catch(()=>null):Promise.resolve(null),e?.json&&(0,r.loadConfig)().polymarketWalletAddress?(0,i.polymarketGetPositions)((0,r.loadConfig)().polymarketWalletAddress).catch(()=>[]):Promise.resolve([])]);let k=[];if(e?.json)try{k=(await t.getFeed(24,20)).evaluations||[]}catch{}if(e?.json)return void console.log(JSON.stringify({theses:u,positions:a||[],polymarketPositions:w,orders:y,balance:$,unpositionedEdges:f,feed:k,kalshiConfigured:(0,s.isKalshiConfigured)(),polymarketConfigured:!!(0,r.loadConfig)().polymarketWalletAddress,timestamp:(new Date).toISOString()},null,2));if(console.log(),console.log(" SimpleFunctions Dashboard"),console.log(" "+"─".repeat(50)),console.log(),console.log(" Theses"),0===u.length)console.log(" (none)");else for(let e=0;e<u.length;e++){const t=u[e],n=p[e],o=t.id.slice(0,8),s=(t.title||"").slice(0,35).padEnd(35),i=null!=t.confidence?`${Math.round(100*t.confidence)}%`:"?%",r=n?.edges?.length||0,a=t.updatedAt?d(t.updatedAt):"?";console.log(` ${o} ${s} ${i.padStart(4)} ${String(r).padStart(2)} edges updated ${a}`)}if(console.log(),console.log(" Positions"),a&&0!==a.length){let e=0,t=0;for(const n of a){const o=(n.ticker||"").padEnd(22),s=String(n.quantity||0).padStart(5),i=`${n.average_price_paid||0}¢`,r="number"==typeof n.current_value?`${n.current_value}¢`:"?¢",a=n.unrealized_pnl||0,c=(a/100).toFixed(2),l=a>=0?`+$${c}`:`-$${Math.abs(parseFloat(c)).toFixed(2)}`;e+=(n.average_price_paid||0)*(n.quantity||0),t+=a,console.log(` ${o} ${s} @ ${i.padEnd(5)} now ${r.padEnd(5)} ${l}`)}console.log(" "+"─".repeat(45));const n=(e/100).toFixed(0),o=(t/100).toFixed(2),s=t>=0?`+$${o}`:`-$${Math.abs(parseFloat(o)).toFixed(2)}`;console.log(` Total cost: $${n} | P&L: ${s}`)}else console.log(" (no Kalshi positions or Kalshi not configured)");if(console.log(),a&&a.length>0){console.log(" Risk Exposure");const e=new Map;for(const t of a){const n=l(t.ticker||""),o=e.get(n)||{cost:0,contracts:0,tickers:[]},s=(t.average_price_paid||0)*(t.quantity||0);o.cost+=s,o.contracts+=t.quantity||0,o.tickers.includes(t.ticker)||o.tickers.push(t.ticker),e.set(n,o)}const t=[...e.entries()].sort((e,t)=>t[1].cost-e[1].cost);for(const[e,n]of t){const t=`$${(n.cost/100).toFixed(0)}`,o=n.tickers.length<=2?` (${n.tickers.join("+")})`:` (${n.tickers.length} markets)`;console.log(` ${(e+o+":").padEnd(35)} ${t.padStart(7)} cost | ${String(n.contracts).padStart(5)} contracts`)}console.log()}if(f.length>0){console.log(" Top Unpositioned Edges");for(const e of f){const t=(e.market||e.marketId||"").slice(0,25).padEnd(25),n=`${e.marketPrice}¢`,o=`${e.thesisPrice}¢`,s=e.edge>0?`+${e.edge}`:`${e.edge}`,i=e.orderbook?.liquidityScore||"?";console.log(` ${t} ${n.padStart(5)} → ${o.padStart(5)} edge ${s.padStart(4)} ${i}`)}console.log()}};const o=n(19218),s=n(96139),i=n(34331),r=n(11627),a=n(97325),c=n(99844);function l(e){const t=Object.keys(a.RISK_CATEGORIES).sort((e,t)=>t.length-e.length);for(const n of t)if(e.startsWith(n))return a.RISK_CATEGORIES[n];return"Other"}function d(e){const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<60)return`${n}m ago`;const o=Math.floor(n/60);if(o<24)return`${o}h ago`;return`${Math.floor(o/24)}d ago`}},81466:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deltaCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl),i=t.since?new Date(t.since):new Date(Date.now()-36e5*parseInt(t.hours||"6"));if(isNaN(i.getTime()))throw new Error(`Invalid timestamp: "${t.since}". Use ISO 8601 format (e.g., 2026-03-28T14:00:00Z)`);const r=async()=>{const o=i.toISOString(),r=await n.getChanges(e,o);if(t.json)return void console.log(JSON.stringify(r,null,2));if(!r.changed)return void console.log(`${s.c.dim}No changes since ${i.toLocaleString()}.${s.c.reset}`);const a=(0,s.shortId)(e);if(console.log(),console.log(`${s.c.bold}${s.c.cyan}Delta: ${a}${s.c.reset}${s.c.dim} — since ${i.toLocaleString()}${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(65)}${s.c.reset}`),void 0!==r.confidence){const e=Math.round(100*r.confidence),t=void 0!==r.previousConfidence?Math.round(100*r.previousConfidence):null,n=null!==t?e-t:null;let o="";null!==n&&(o=n>0?`${s.c.green} (+${n}%)${s.c.reset}`:n<0?`${s.c.red} (${n}%)${s.c.reset}`:`${s.c.dim} (0%)${s.c.reset}`),console.log(` Confidence: ${s.c.bold}${e}%${s.c.reset}${o}`)}r.evaluationCount&&console.log(` Evaluations: ${r.evaluationCount} cycle(s)`);const c=r.updatedNodes||[];if(c.length>0){console.log(),console.log(` ${s.c.bold}Node Changes (${c.length}):${s.c.reset}`);for(const e of c){const t=Math.round(100*(e.newProbability??e.newProb??0)),n=e.previousProbability??e.prevProb;let o="";if(null!=n){const e=t-Math.round(100*n);o=e>0?` ${s.c.green}+${e}%${s.c.reset}`:e<0?` ${s.c.red}${e}%${s.c.reset}`:""}const i=e.label||e.nodeId||"?";console.log(` ${i.slice(0,40).padEnd(40)} ${t}%${o}`)}}const l=r.newSignals||[];if(l.length>0){console.log(),console.log(` ${s.c.bold}New Signals (${l.length}):${s.c.reset}`);for(const e of l){const t=e.type||"signal",n=(e.content||e.title||"").replace(/\n/g," ").slice(0,70);console.log(` ${s.c.dim}[${t}]${s.c.reset} ${n}`)}}const d=r.edgeChanges||r.edges||[];if(d.length>0){console.log(),console.log(` ${s.c.bold}Edge Movements (${d.length}):${s.c.reset}`);for(const e of d.slice(0,15)){const t=(e.market||e.marketId||"").slice(0,35).padEnd(35),n=e.edge??0,o=e.previousEdge??null,i=n>0?`+${n}`:`${n}`;let r="";if(null!==o){const e=n-o;r=e>0?` ${s.c.green}(+${e})${s.c.reset}`:e<0?` ${s.c.red}(${e})${s.c.reset}`:""}const a=n>0?s.c.green:n<0?s.c.red:s.c.dim;console.log(` ${t} ${a}${i}${s.c.reset}${r}`)}}console.log(`${s.c.dim}${"─".repeat(65)}${s.c.reset}`),console.log()};if(t.watch)for(console.log(`${s.c.dim}Watching for changes every 60s... (Ctrl+C to stop)${s.c.reset}`);;)await r(),await new Promise(e=>setTimeout(e,6e4)),console.clear();else await r()};const o=n(19218),s=n(99236)},91262:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.edgesCommand=async function(e){const t=new o.SFClient(e.apiKey,e.apiUrl),n=parseInt(e.limit||"20"),a=e.minEdge?parseInt(e.minEdge):0,c=e.minLiquidity?.toLowerCase()||"",l=e.sort||"edge",d={a:4,high:4,b:3,medium:3,c:2,low:2,d:1};let u;const p=e.json?()=>{}:e=>console.log(e);if(e.thesis)p(`${i.c.dim}Fetching edges for thesis ${e.thesis}...${i.c.reset}`),u=[{id:e.thesis}];else{p(`${i.c.dim}Fetching theses...${i.c.reset}`);const e=await t.listTheses(),n=e.theses||e;u=(Array.isArray(n)?n:[]).filter(e=>"active"===e.status)}if(0===u.length)return e.json?void console.log(JSON.stringify({edges:[],totalEdges:0})):void(0,i.emptyState)("active theses",'Create one: sf create "your market thesis"');p(`${i.c.dim}Fetching edges from ${u.length} ${1===u.length?"thesis":"theses"}...${i.c.reset}`);const h=[],m=u.map(async e=>{try{const n=await t.getContext(e.id);return{thesisId:e.id,edges:n.edges||[]}}catch{return{thesisId:e.id,edges:[]}}}),g=await Promise.all(m);for(const{thesisId:e,edges:t}of g)for(const n of t)h.push({marketId:n.marketId||"",market:n.market||n.marketTitle||n.marketId||"",venue:n.venue||"kalshi",direction:n.direction||"yes",marketPrice:"number"==typeof n.marketPrice?n.marketPrice:0,thesisPrice:"number"==typeof n.thesisPrice?n.thesisPrice:0,edge:"number"==typeof n.edge?n.edge:0,executableEdge:"number"==typeof n.executableEdge?n.executableEdge:null,spread:n.orderbook?.spread??null,liquidityScore:n.orderbook?.liquidityScore??null,thesisId:e,position:null});if(0===h.length)return e.json?void console.log(JSON.stringify({edges:[],totalEdges:0,thesesScanned:u.length})):void(0,i.emptyState)("edges",`Scanned ${u.length} theses. Edges appear when thesis price diverges from market price.`);const f=new Map;for(const e of h){const t=e.marketId;if(!t)continue;const n=f.get(t);(!n||Math.abs(e.edge)>Math.abs(n.edge))&&f.set(t,e)}let y=Array.from(f.values());a>0&&(y=y.filter(e=>Math.abs(e.edge)>=a));c&&d[c]&&(y=y.filter(e=>e.liquidityScore&&(d[e.liquidityScore.toLowerCase()]||0)>=d[c]));let $=null;if((0,s.isKalshiConfigured)()&&(p(`${i.c.dim}Fetching Kalshi positions...${i.c.reset}`),$=await(0,s.getPositions)(),$)){for(const e of $){const t=await(0,s.getMarketPrice)(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity))}for(const e of y){const t=$.find(t=>t.ticker===e.marketId||e.marketId&&t.ticker?.includes(e.marketId));t&&(e.position={side:t.side||"yes",quantity:t.quantity,avgPrice:t.average_price_paid,currentValue:t.current_value,pnl:t.unrealized_pnl||0,totalCost:t.total_cost||Math.round(t.average_price_paid*t.quantity)})}}"spread"===l?y.sort((e,t)=>(e.spread??999)-(t.spread??999)):y.sort((e,t)=>{const n=null!==e.executableEdge?e.executableEdge:e.edge,o=null!==t.executableEdge?t.executableEdge:t.edge;return Math.abs(o)-Math.abs(n)});const w=y.slice(0,n),k={totalEdges:y.length,displayed:w.length,thesesScanned:u.length,edges:w};if(e.share)return void await(0,r.shareOutput)("edges","",k);if(e.json)return void console.log(JSON.stringify(k,null,2));console.log(),(0,i.header)(`Top Edges Across ${u.length} Theses`),console.log();const b=[(0,i.pad)("Market",32),(0,i.rpad)("Mkt",5),(0,i.rpad)("Thesis",7),(0,i.rpad)("Edge",6),(0,i.rpad)("Exec",6),(0,i.rpad)("Sprd",5),(0,i.pad)("Liq",5),(0,i.pad)("Thesis",10),(0,i.pad)("Position",20)].join(" ");console.log(`${i.c.dim}${b}${i.c.reset}`),(0,i.hr)(100);for(const e of w){const t=(0,i.trunc)(e.market,31),n=`${e.marketPrice}¢`,o=`${e.thesisPrice}¢`,s=e.edge>0?`+${e.edge}`:`${e.edge}`,r=null!==e.executableEdge?e.executableEdge>0?`+${e.executableEdge}`:`${e.executableEdge}`:"—",a=null!==e.spread?`${e.spread}¢`:"—",c=e.liquidityScore||"—",l=(0,i.shortId)(e.thesisId),d=e.edge>0?i.c.green:e.edge<0?i.c.red:i.c.dim,u=null!==e.executableEdge?e.executableEdge>0?i.c.green:i.c.red:i.c.dim,p="high"===c?i.c.green:"medium"===c?i.c.yellow:i.c.dim;let h=`${i.c.dim}—${i.c.reset}`;if(e.position){const t=e.position,n=t.pnl>=0?`${i.c.green}+$${(t.pnl/100).toFixed(0)}${i.c.reset}`:`${i.c.red}-$${(Math.abs(t.pnl)/100).toFixed(0)}${i.c.reset}`;h=`${i.c.green}${t.quantity}@${t.avgPrice}¢${i.c.reset} ${n}`}const m=[e.position?`${i.c.green}${(0,i.pad)(t,32)}${i.c.reset}`:(0,i.pad)(t,32),(0,i.rpad)(n,5),(0,i.rpad)(o,7),`${d}${(0,i.rpad)(s,6)}${i.c.reset}`,`${u}${(0,i.rpad)(r,6)}${i.c.reset}`,(0,i.rpad)(a,5),`${p}${(0,i.pad)(c,5)}${i.c.reset}`,`${i.c.dim}${(0,i.pad)(l,10)}${i.c.reset}`,h].join(" ");console.log(m)}(0,i.hr)(100);const v=w.filter(e=>e.position);if(v.length>0){let e=0,t=0;for(const n of v)e+=n.position.totalCost,t+=n.position.pnl;const n=`$${(e/100).toFixed(0)}`,o=`${t>=0?i.c.green:i.c.red}${t>=0?"+":"-"}$${(Math.abs(t)/100).toFixed(0)}${i.c.reset}`;console.log(`${i.c.bold}Total positioned:${i.c.reset} ${n} cost | P&L: ${o}`)}const _=w.filter(e=>!e.position&&e.edge>0);if(_.length>0){const e=_[0],t=null!==e.executableEdge?`exec +${e.executableEdge}`:`edge +${e.edge}`,n=e.liquidityScore?`, ${e.liquidityScore} liq`:"";console.log(`${i.c.bold}Top unpositioned:${i.c.reset} ${(0,i.trunc)(e.market,30)} @ ${e.marketPrice}¢ (${t}${n})`)}console.log()};const o=n(19218),s=n(96139),i=n(99236),r=n(35178)},67509:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl);console.log(`${s.c.dim}Triggering deep evaluation (heavy model)...${s.c.reset}`);const i=await n.evaluate(e);if(console.log(`\n${s.c.green}✓${s.c.reset} Evaluation complete`),i.evaluation){const e=i.evaluation;if(void 0!==e.confidenceDelta){const t=e.confidenceDelta,n=t>0?s.c.green:t<0?s.c.red:s.c.dim;console.log(` ${s.c.bold}Confidence:${s.c.reset} ${(0,s.pct)(e.previousConfidence)} → ${(0,s.pct)(e.newConfidence)} ${n}(${(0,s.delta)(t)})${s.c.reset}`)}if(e.summary&&console.log(`\n ${e.summary}`),e.positionUpdates&&e.positionUpdates.length>0){console.log(`\n ${s.c.bold}Position Recommendations:${s.c.reset}`);for(const t of e.positionUpdates){const e="hold"===t.recommendation?s.c.dim:"close"===t.recommendation?s.c.red:s.c.yellow;console.log(` [${t.positionId.slice(0,8)}] ${e}${t.recommendation}${s.c.reset} — ${t.reason}`)}}}console.log("")};const o=n(19218),s=n(99236)},22835:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exploreCommand=async function(e,t){if(!e){const e=await fetch(`${i}/api/public/theses`);if(!e.ok)return void console.error(` Error: ${e.status} ${await e.text()}`);const{theses:n}=await e.json();if(t?.share)return void await(0,o.shareOutput)("explore","",{theses:n});if(t?.json)return void console.log(JSON.stringify(n,null,2));if(console.log("\n Public Theses\n"),0===n.length)return void console.log(` ${s.c.dim}No public theses yet. Publish yours: sf publish <id>${s.c.reset}\n`);for(const e of n){const t=null!=e.confidence?Math.round(100*e.confidence):"?",n=null!=e.impliedReturn?`${e.impliedReturn>0?"+":""}${e.impliedReturn}%`:"";console.log(` ${(e.slug||"").padEnd(35)} ${String(t).padStart(3)}% ${n.padStart(8)} ${(e.status||"").padEnd(8)} ${(e.title||"").slice(0,45)}`)}return void console.log(`\n ${n.length} public theses. Use: sf explore <slug>\n`)}const n=await fetch(`${i}/api/public/thesis/${e}`);if(!n.ok)return void(404===n.status?console.error(` Not found: ${e}`):console.error(` Error: ${n.status} ${await n.text()}`));const r=await n.json();if(t?.json)return void console.log(JSON.stringify(r,null,2));const a=r.thesis,c=r.impliedReturns;console.log(`\n ${a.title}`),console.log(` ${a.slug} | ${null!=a.confidence?Math.round(100*a.confidence):"?"}% | ${a.status} | published ${a.publishedAt?.slice(0,10)||"?"}`),a.description&&console.log(` ${a.description}`);if(console.log(""),r.causalTree?.nodes?.length){console.log(" Causal Tree");for(const e of r.causalTree.nodes){const t="█".repeat(Math.round(10*(e.probability||0)))+"░".repeat(10-Math.round(10*(e.probability||0)));if(console.log(` ${e.id} ${(e.label||"").slice(0,35).padEnd(35)} ${Math.round(100*(e.probability||0))}% ${t}`),e.children)for(const t of e.children){const e="█".repeat(Math.round(10*(t.probability||0)))+"░".repeat(10-Math.round(10*(t.probability||0)));console.log(` ${t.id} ${(t.label||"").slice(0,33).padEnd(33)} ${Math.round(100*(t.probability||0))}% ${e}`)}}console.log("")}if(c&&c.edges?.length>0){console.log(` Implied Returns (equal-weight, since ${c.trackedSince?.slice(0,10)||"?"})`),console.log(` Avg: ${c.avgReturnPct>0?"+":""}${c.avgReturnPct}% | Win rate: ${c.winRate}% (${c.winners}W ${c.losers}L)`),console.log("");for(const e of c.edges.slice(0,10)){const t=e.returnPct>0?`+${e.returnPct}%`:`${e.returnPct}%`;console.log(` ${(e.market||"").slice(0,35).padEnd(35)} ${e.entryPrice}¢ → ${e.currentPrice}¢ ${t}`)}console.log("")}if(r.confidenceHistory?.length>0){console.log(" Recent Evaluations");for(const e of r.confidenceHistory.slice(-5)){const t=e.delta>0?`+${Math.round(100*e.delta)}`:`${Math.round(100*e.delta)}`;console.log(` ${(e.evaluatedAt||"").slice(0,16)} ${Math.round(100*e.confidence)}% (${t}) ${(e.summary||"").slice(0,60)}`)}console.log("")}if(r.edges?.length>0){console.log(" Top Edges");const e=[...r.edges].sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,10);for(const t of e){const e=t.orderbook?.liquidityScore||"?";console.log(` ${(t.market||"").slice(0,35).padEnd(35)} ${t.marketPrice}¢ → ${t.thesisPrice}¢ edge ${t.edge>0?"+":""}${t.edge} ${e}`)}console.log("")}};const o=n(35178),s=n(99236),i="https://simplefunctions.dev"},44478:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.feedCommand=async function(e){const t=new o.SFClient(e.apiKey,e.apiUrl),n=parseInt(e.hours||"24"),i=await t.getFeed(n,200);let r=i.feed||[];if(0===r.length)return void console.log(`${s.c.dim}No evaluations in the last ${n} hours.${s.c.reset}`);if(e.thesis&&(r=r.filter(t=>t.thesisId.startsWith(e.thesis)||t.thesisShortId===e.thesis),0===r.length))return void console.log(`${s.c.dim}No evaluations for ${e.thesis} in the last ${n} hours.${s.c.reset}`);if(e.json)return void console.log(JSON.stringify(r,null,2));console.log(),console.log(`${s.c.bold}${s.c.cyan}Evaluation Feed${s.c.reset}${s.c.dim} — last ${n}h, ${r.length} cycles${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(75)}${s.c.reset}`);for(const e of r){const t=new Date(e.evaluatedAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n=Math.round(100*e.confidence),o=Math.round(100*e.delta);let i;i=o>0?`${s.c.green}+${o}%${s.c.reset}`:o<0?`${s.c.red}${o}%${s.c.reset}`:`${s.c.dim}0%${s.c.reset}`;const r=e.thesisShortId||e.thesisId?.slice(0,8)||"?",a=(e.summary||"No summary").replace(/\n/g," ").slice(0,80),c=e.updatedNodes||[],l=c.length>0?c.slice(0,3).map(e=>`${e.nodeId}→${Math.round(100*(e.newProb||0))}%`).join(", "):"";console.log(`${s.c.dim}[${t}]${s.c.reset} ${s.c.cyan}${r}${s.c.reset} ${n}% (${i}) ${s.c.dim}${a}${s.c.reset}`),l&&console.log(`${" ".repeat(9)} ${s.c.dim}nodes: ${l}${s.c.reset}`)}console.log(`${s.c.dim}${"─".repeat(75)}${s.c.reset}`),console.log()};const o=n(19218),s=n(99236)},63746:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fillsCommand=async function(e){const t=await(0,o.getFills)({ticker:e.ticker,limit:50});if(!t)throw new Error("Kalshi not configured. Run: sf setup --kalshi");if(e.json)return void console.log(JSON.stringify(t.fills,null,2));if(0===t.fills.length)return void console.log(`${s.c.dim}No fills.${s.c.reset}`);console.log(`${s.c.bold}${s.c.cyan}Recent Fills${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(80)}${s.c.reset}`);for(const e of t.fills){const t=e.yes_price_dollars?100*parseFloat(e.yes_price_dollars)+"¢":`${e.yes_price||"?"}¢`,n="yes"===e.side?`${s.c.green}YES${s.c.reset}`:`${s.c.red}NO${s.c.reset}`,o=e.action||"buy",i=e.count_fp||e.count||"?",r=e.created_time?new Date(e.created_time).toLocaleString():"";console.log(` ${(e.ticker||"").padEnd(35)} ${o.padEnd(5)} ${n} ${t.padEnd(8)} x${i} ${s.c.dim}${r}${s.c.reset}`)}console.log(`\n${s.c.dim}${t.fills.length} fill(s)${s.c.reset}`)};const o=n(96139),s=n(99236)},28423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forecastCommand=async function(e,t){const n=parseInt(t.days||"7"),r=await fetch(`${i}/events/${e}`,{headers:{Accept:"application/json"}});if(!r.ok)throw new Error(`Event not found: ${e}`);const a=await r.json(),c=a.event?.series_ticker;if(!c)throw new Error(`No series_ticker for ${e}`);const l=new Date;l.setUTCHours(0,0,0,0);const d=Math.floor(l.getTime()/1e3),u=d-86400*n,p=await(0,o.getForecastHistory)({seriesTicker:c,eventTicker:e,percentiles:[5e3,7500,9e3],startTs:u,endTs:d,periodInterval:1440});if(!p||0===p.length)return void console.log(`${s.c.dim}No forecast data for ${e}${s.c.reset}`);if(t.json)return void console.log(JSON.stringify(p,null,2));console.log(`${s.c.bold}${s.c.cyan}Forecast: ${a.event?.title||e}${s.c.reset}`),console.log(`${s.c.dim}Series: ${c} | ${n} days${s.c.reset}`),console.log(),console.log(`${s.c.bold}${"Date".padEnd(14)} ${"P50".padEnd(12)} ${"P75".padEnd(12)} P90${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(52)}${s.c.reset}`);for(const e of p){const t=new Date(1e3*e.end_period_ts).toISOString().slice(0,10),n=e.percentile_points||[],o=n.find(e=>5e3===e.percentile)?.formatted_forecast||"-",s=n.find(e=>7500===e.percentile)?.formatted_forecast||"-",i=n.find(e=>9e3===e.percentile)?.formatted_forecast||"-";console.log(` ${t.padEnd(14)} ${o.padEnd(12)} ${s.padEnd(12)} ${i}`)}};const o=n(96139),s=n(99236),i="https://api.elections.kalshi.com/trade-api/v2"},5596:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl),r=await n.getThesis(e);if(t.json)return void console.log(JSON.stringify(r,null,2));const a=r,c=r.positions||[];(0,s.header)(`Thesis: ${(a.id||e).slice(0,8)}`),(0,s.hr)(),console.log(`${s.c.bold}Status:${s.c.reset} ${a.status||"-"}`);const l=a.confidence?(0,s.pct)(parseFloat(a.confidence)):"-";console.log(`${s.c.bold}Confidence:${s.c.reset} ${l}`);const d=a.createdAt instanceof Date?a.createdAt.toISOString():a.createdAt,u=a.updatedAt instanceof Date?a.updatedAt.toISOString():a.updatedAt;console.log(`${s.c.bold}Created:${s.c.reset} ${(0,s.shortDate)(d)}`),console.log(`${s.c.bold}Updated:${s.c.reset} ${(0,s.shortDate)(u)}`),a.title&&console.log(`${s.c.bold}Title:${s.c.reset} ${a.title}`);console.log(`${s.c.bold}Thesis:${s.c.reset} ${a.rawThesis||"-"}`),a.webhookUrl&&console.log(`${s.c.bold}Webhook:${s.c.reset} ${a.webhookUrl}`);const p=a.causalTree;p&&p.nodes&&((0,s.header)("Causal Tree"),i(p.nodes,0));const h=a.edgeAnalysis;if(h&&h.edges){(0,s.header)("Edge Analysis"),console.log(`${s.c.dim}Analyzed: ${(0,s.shortDate)(h.analyzedAt)}${s.c.reset}`),h.lastRescanAt&&console.log(`${s.c.dim}Last rescan: ${(0,s.shortDate)(h.lastRescanAt)}${s.c.reset}`);for(const e of h.edges){const t=e.edgeSize??0,n=t>10?s.c.green:t>0?s.c.yellow:s.c.red;console.log(` ${e.marketTitle||e.marketId} ${s.c.dim}${e.venue}${s.c.reset} price: ${(e.marketPrice??0).toFixed(0)}¢ ${n}edge: ${t>0?"+":""}${t.toFixed(1)}${s.c.reset}`)}}if(c.length>0){(0,s.header)("Positions");for(const e of c){if(!e)continue;const t="open"===e.status?s.c.green+"●":s.c.dim+"○";console.log(` ${t}${s.c.reset} [${(e.id||"?").slice(0,8)}] "${e.marketTitle||"?"}" ${e.direction||"?"}@${e.entryPrice||"?"}→${e.currentPrice||e.entryPrice||"?"} ${s.c.dim}(${e.venue||"?"})${s.c.reset}`)}}const m=a.lastEvaluation;if(m){(0,s.header)("Last Evaluation");const e=m.evaluatedAt instanceof Date?m.evaluatedAt.toISOString():m.evaluatedAt;if(console.log(`${s.c.dim}${(0,s.shortDate)(e)} | model: ${m.model||"-"}${s.c.reset}`),void 0!==m.confidenceDelta){const e=m.confidenceDelta,t=e>0?s.c.green:e<0?s.c.red:s.c.dim;console.log(`Confidence: ${(0,s.pct)(m.previousConfidence)} → ${(0,s.pct)(m.newConfidence)} ${t}(${(0,s.delta)(e)})${s.c.reset}`)}m.summary&&console.log(`\n${m.summary}`)}console.log("")};const o=n(19218),s=n(99236);function i(e,t){for(const n of e){if(!n)continue;const e=" ".repeat(t+1),o=void 0!==n.probability?(0,s.pct)(n.probability):"-",r=void 0!==n.importance?` imp:${n.importance}`:"";console.log(`${e}${s.c.cyan}${n.id}${s.c.reset} ${n.label} ${s.c.dim}(${o}${r})${s.c.reset}`),n.children&&n.children.length>0&&i(n.children,t+1)}}},87604:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heartbeatCommand=async function(e,t,n){const s=n.newsInterval||n.xInterval||n.model||void 0!==n.budget||n.pause||n.resume;if(s){const s={};n.newsInterval&&(s.newsIntervalMin=parseInt(n.newsInterval,10)),n.xInterval&&(s.xIntervalMin=parseInt(n.xInterval,10)),n.model&&(s.evalModelTier=n.model),void 0!==n.budget&&(s.monthlyBudgetUsd=parseFloat(n.budget)),n.pause&&(s.paused=!0),n.resume&&(s.paused=!1);try{const n=await e.updateHeartbeatConfig(t,s);console.log(`\n ${o.c.green}✓${o.c.reset} Updated heartbeat config`),console.log(` ${o.c.dim}Updated fields: ${n.updated.join(", ")}${o.c.reset}\n`)}catch(e){return void console.error(` ${o.c.red}✗ ${e.message}${o.c.reset}`)}}try{const n=await e.getHeartbeatConfig(t),s=n.config,i=n.costs;console.log(`\n ${o.c.bold}Heartbeat Config${o.c.reset} ${o.c.dim}(${t.slice(0,8)})${o.c.reset}`),console.log();const r=s.paused?`${o.c.red}⏸ paused${o.c.reset}`:`${o.c.green}▶ active${o.c.reset}`;if(console.log(` Status ${r}`),console.log(` News interval ${o.c.cyan}${s.newsIntervalMin}${o.c.reset} min ${o.c.dim}(${s.newsIntervalMin===n.defaults.newsIntervalMin?"default":"custom"})${o.c.reset}`),console.log(` X interval ${o.c.cyan}${s.xIntervalMin}${o.c.reset} min ${o.c.dim}(${s.xIntervalMin===n.defaults.xIntervalMin?"default":"custom"})${o.c.reset}`),console.log(` Eval model ${o.c.cyan}${s.evalModelTier}${o.c.reset} ${o.c.dim}(${s.evalModelTier===n.defaults.evalModelTier?"default":"custom"})${o.c.reset}`),console.log(" Monthly budget "+(s.monthlyBudgetUsd>0?`${o.c.cyan}$${s.monthlyBudgetUsd}${o.c.reset}`:`${o.c.dim}unlimited${o.c.reset}`)),console.log(),console.log(` ${o.c.bold}This Month${o.c.reset}`),console.log(` Total cost ${o.c.cyan}$${i.monthlyTotal.toFixed(4)}${o.c.reset}`),console.log(` LLM calls ${i.llmCalls}`),console.log(` Search calls ${i.searchCalls}`),console.log(` Tokens ${o.c.dim}${i.inputTokens.toLocaleString()} in / ${i.outputTokens.toLocaleString()} out${o.c.reset}`),null!==i.budgetRemaining){const e=s.monthlyBudgetUsd>0?Math.round(i.monthlyTotal/s.monthlyBudgetUsd*100):0;console.log(` Budget used ${e}% ${o.c.dim}($${i.budgetRemaining.toFixed(2)} remaining)${o.c.reset}`)}console.log()}catch(e){console.error(` ${o.c.red}✗ ${e.message}${o.c.reset}`)}};const o=n(99236)},9708:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.historyCommand=async function(e,t){const n=await(0,o.getHistoricalMarket)(e);if(!n)return void console.log(`${s.c.dim}No historical data for ${e}${s.c.reset}`);if(t.json)return void console.log(JSON.stringify(n,null,2));console.log(`${s.c.bold}${s.c.cyan}${n.title||e}${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(60)}${s.c.reset}`),console.log(` Ticker: ${n.ticker||e}`),console.log(` Event: ${n.event_ticker||"-"}`),console.log(` Status: ${n.status||"-"}`),console.log(` Result: ${n.result||n.market_result||"-"}`),n.last_price_dollars&&console.log(` Last Price: ${Math.round(100*parseFloat(n.last_price_dollars))}¢`);void 0!==n.settlement_value&&console.log(` Settlement: ${n.settlement_value}`);n.volume&&console.log(` Volume: ${n.volume}`);n.open_interest&&console.log(` Open Int: ${n.open_interest}`);n.expiration_time&&console.log(` Expired: ${n.expiration_time}`);console.log()};const o=n(96139),s=n(99236)},30896:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ideasCommand=async function(e){const t=process.env.SF_API_URL||"https://simplefunctions.dev",n=new URLSearchParams;e.category&&n.set("category",e.category);e.fresh&&n.set("freshness",e.fresh);const s=await fetch(`${t}/api/public/ideas?${n.toString()}`);s.ok||(console.error(`\n ${o.c.red}Error:${o.c.reset} API returned ${s.status}\n`),process.exit(1));const i=await s.json();if(e.json)return void console.log(JSON.stringify(i,null,2));const r=i.ideas||i;if(!Array.isArray(r)||0===r.length)return void console.log(`\n ${o.c.dim}No trade ideas available.${o.c.reset}\n`);console.log(),console.log(` ${o.c.bold}Trade Ideas${o.c.reset} ${o.c.dim}${r.length} ideas${o.c.reset}`),console.log();for(const e of r){const t="long"===e.direction?o.c.green+"▲ LONG"+o.c.reset:o.c.red+"▼ SHORT"+o.c.reset,n="●".repeat(Math.min(e.conviction||3,5));if(console.log(` ${t} ${e.headline}`),console.log(` ${o.c.dim}Conviction: ${n} Category: ${e.category||"-"} Horizon: ${e.timeHorizon||"-"}${o.c.reset}`),console.log(` ${e.pitch||""}`),e.catalyst&&console.log(` ${o.c.dim}Catalyst: ${e.catalyst}${o.c.reset}`),e.risk&&console.log(` ${o.c.dim}Risk: ${e.risk}${o.c.reset}`),e.markets?.length){const t=e.markets.map(e=>`${e.ticker||e.marketId} ${e.currentPrice?e.currentPrice+"¢":""}`).join(", ");console.log(` ${o.c.dim}Markets: ${t}${o.c.reset}`)}console.log()}};const o=n(99236)},15472:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.registerIntents=function(e){const t=e.command("intent").description("Manage execution intents");t.command("list").option("--all","Show all statuses (default: active only)").option("--status <status>","Filter by status").option("--json","JSON output").description("List intents").action(async e=>{try{const t=new o.SFClient,n=e.all?{}:{active:!e.status,status:e.status},{intents:i}=await t.listIntents(n);if(e.json)return void console.log(JSON.stringify(i,null,2));if(!i||0===i.length)return void(0,s.emptyState)("intents","Create one: sf intent buy TICKER QTY --price CENTS");console.log(`\n ${s.c.bold}INTENTS${s.c.reset} (${i.length})\n`);for(const e of i)console.log(r(e)),console.log()}catch(e){console.error(`${s.c.red}Error:${s.c.reset} ${e.message}`),process.exit(1)}}),t.command("buy").argument("<ticker>","Market ticker (e.g. KXFEDDEC-25DEC31-T100)").argument("<quantity>","Number of contracts").option("--price <cents>","Max price per contract in cents").option("--side <side>","Direction: yes or no","yes").option("--trigger <trigger>","Trigger condition: immediate, below:<cents>, above:<cents>","immediate").option("--expire <duration>","Expiry: 1h, 6h, 1d, 3d, 1w","1d").option("--venue <venue>","Venue: kalshi or polymarket","kalshi").option("--rationale <text>","Why this trade").option("--auto","Auto-execute without confirmation").option("--style <style>","Execution style: immediate, twap","immediate").option("--json","JSON output").description("Create a buy intent").action(async(e,t,n)=>{await a("buy",e,t,n)}),t.command("sell").argument("<ticker>","Market ticker").argument("<quantity>","Number of contracts").option("--price <cents>","Max price per contract in cents").option("--side <side>","Direction: yes or no","yes").option("--trigger <trigger>","Trigger condition","immediate").option("--expire <duration>","Expiry","1d").option("--venue <venue>","Venue","kalshi").option("--rationale <text>","Why this trade").option("--auto","Auto-execute without confirmation").option("--json","JSON output").description("Create a sell intent").action(async(e,t,n)=>{await a("sell",e,t,n)}),t.command("status").argument("<id>","Intent ID or prefix").option("--json","JSON output").description("Detailed intent status with fills").action(async(e,t)=>{try{const n=new o.SFClient,{intent:i}=await n.getIntentDetail(e);if(t.json)return void console.log(JSON.stringify(i,null,2));if(console.log(`\n ${s.c.bold}Intent ${i.id.slice(0,8)}${s.c.reset}\n`),console.log(r(i)),console.log(),i.fills&&i.fills.length>0){console.log(` ${s.c.bold}Fills${s.c.reset} (${i.fills.length})\n`);for(const e of i.fills){const t=new Date(e.filledAt).toLocaleTimeString("en-US",{hour12:!1});console.log(` ${t} ${e.fillQuantity} @ ${e.fillPrice}c ($${(e.fillCostCents/100).toFixed(2)}) ${s.c.dim}order: ${e.orderId||"?"}${s.c.reset}`)}console.log();const e=i.fills.reduce((e,t)=>e+t.fillCostCents,0),t=i.fills.reduce((e,t)=>e+t.fillPrice*t.fillQuantity,0)/i.filledQuantity;console.log(` Total: $${(e/100).toFixed(2)} avg ${t.toFixed(1)}c`),console.log()}}catch(e){console.error(`${s.c.red}Error:${s.c.reset} ${e.message}`),process.exit(1)}}),t.command("cancel").argument("<id>","Intent ID or prefix").description("Cancel an intent").action(async e=>{try{const t=new o.SFClient;await t.cancelIntentAPI(e),console.log(`\n ${s.c.green}OK${s.c.reset} Intent ${e} cancelled.\n`)}catch(e){console.error(`${s.c.red}Error:${s.c.reset} ${e.message}`),process.exit(1)}})};const o=n(19218),s=n(99236),i={pending:"",armed:"",triggered:"",executing:"",filled:"",partial:"",expired:"",cancelled:"",rejected:""};function r(e){const t=i[e.status]||"",n=[],o=e.action.toUpperCase(),r=e.direction.toUpperCase(),a=e.maxPrice?` @ ≤${e.maxPrice}c`:" @ market",c="kalshi"===e.venue?"K":"P";if(n.push(` ${t}[${e.status}]${s.c.reset} ${s.c.bold}${o}${s.c.reset} ${e.marketId} ${r} ${e.targetQuantity}${a} ${s.c.dim}${c}${s.c.reset}`),"immediate"!==e.triggerType){const t=function(e){switch(e.triggerType){case"price_below":return`price ≤ ${e.triggerPrice}c`;case"price_above":return`price ≥ ${e.triggerPrice}c`;case"time":return`at ${new Date(e.triggerAt).toLocaleString()}`;case"compound":return"compound (see details)";default:return e.triggerType}}(e);n.push(` Trigger: ${t}`)}if(e.filledQuantity>0){const t=Math.round(e.filledQuantity/e.targetQuantity*100);n.push(` Filled: ${e.filledQuantity}/${e.targetQuantity} (${t}%)`)}const l=new Date(e.expireAt).toLocaleDateString("en-US",{month:"short",day:"numeric"});return n.push(` ${s.c.dim}expires ${l} · source: ${e.source}${e.rationale?` · "${e.rationale.slice(0,60)}"`:""}${s.c.reset}`),n.join("\n")}async function a(e,t,n,i){try{const r=new o.SFClient,a=parseInt(n);if(isNaN(a)||a<1)throw new Error("Quantity must be a positive integer");const c=function(e){if("immediate"===e)return{type:"immediate"};const[t,n]=e.split(":");if("below"===t&&n)return{type:"price_below",price:parseInt(n)};if("above"===t&&n)return{type:"price_above",price:parseInt(n)};throw new Error(`Unknown trigger: "${e}". Use: immediate, below:<cents>, above:<cents>`)}(i.trigger||"immediate"),l=i.price?parseInt(i.price):void 0;if(void 0!==l&&(l<1||l>99))throw new Error("Price must be 1-99 cents");const d={"1h":36e5,"6h":216e5,"1d":864e5,"3d":2592e5,"1w":6048e5},u=d[i.expire]||d["1d"],p={action:e,venue:i.venue||"kalshi",marketId:t.toUpperCase(),marketTitle:t.toUpperCase(),direction:i.side||"yes",targetQuantity:a,maxPrice:l,triggerType:c.type,triggerPrice:c.price,expireAt:new Date(Date.now()+u).toISOString(),source:"manual",rationale:i.rationale,autoExecute:!!i.auto,executionStyle:i.style||"immediate"},h=await r.createIntent(p);if(i.json)return void console.log(JSON.stringify(h,null,2));const m=l?`$${(a*l/100).toFixed(2)}`:"market";console.log(),console.log(` ${s.c.green}OK${s.c.reset} Intent created: ${h.id?.slice(0,8)||"OK"}`),console.log(),console.log(` ${e.toUpperCase()} ${t.toUpperCase()} ${(i.side||"yes").toUpperCase()} x${a}${l?` @ ≤${l}c`:""}`),console.log(` Trigger: ${i.trigger||"immediate"}`),console.log(` Max cost: ${m}`),console.log(` Expires: ${i.expire||"1d"}`),i.auto&&console.log(" Auto-execute: ON"),console.log(),console.log(` ${s.c.dim}Start runtime to execute: sf runtime start${s.c.reset}`),console.log()}catch(e){console.error(`${s.c.red}Error:${s.c.reset} ${e.message}`),process.exit(1)}}},50984:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.liquidityCommand=async function(e){const t=Object.keys(r.TOPIC_SERIES);if(!e.topic&&!e.all){console.log(),console.log(`${a.c.bold}Available Topics${a.c.reset} ${a.c.dim}(${t.length} topics)${a.c.reset}`),console.log(a.c.dim+"─".repeat(50)+a.c.reset),console.log();for(const e of t){const t=r.TOPIC_SERIES[e];console.log(` ${a.c.cyan}${(0,a.pad)(e,14)}${a.c.reset} ${a.c.dim}${t.slice(0,3).join(", ")}${t.length>3?` +${t.length-3} more`:""}${a.c.reset}`)}return console.log(),console.log(`${a.c.dim}Usage: sf liquidity <topic> (e.g. sf liquidity oil)${a.c.reset}`),console.log(`${a.c.dim} sf liquidity --all (scan all topics)${a.c.reset}`),void console.log()}const n=e.topic?t.filter(t=>t.toLowerCase()===e.topic.toLowerCase()):t;if(e.topic&&0===n.length){const n=t.join(", ");console.error(`Unknown topic: ${e.topic}. Valid topics: ${n}`),process.exit(1)}let h=new Set;if((0,s.isKalshiConfigured)())try{const e=await(0,s.getPositions)();e&&(h=new Set(e.map(e=>e.ticker)))}catch{}const m={};for(const e of n){const t=r.TOPIC_SERIES[e],n=[];for(const e of t)try{const t=await(0,o.kalshiFetchMarketsBySeries)(e);n.push(...t)}catch{}n.length>0&&(m[e]=n)}const g="kalshi"!==e.venue;if(g)for(const e of n)try{const t=await(0,i.polymarketSearch)(e,5);for(const n of t)for(const t of n.markets||[])t.active&&!t.closed&&t.enableOrderBook&&(m[e]||(m[e]=[]),m[e].push({ticker:t.conditionId?.slice(0,16)||t.id,close_time:t.endDateIso||"",venue:"polymarket",question:t.question||n.title,clobTokenIds:t.clobTokenIds,bestBid:t.bestBid,bestAsk:t.bestAsk,spread:t.spread,liquidityNum:t.liquidityNum}))}catch{}const f=e.horizon,y=[];for(const[e,t]of Object.entries(m))for(const n of t){const t=n.close_time||n.expiration_time||"";if(!t)continue;const o=c(t);f&&o!==f||y.push({ticker:n.ticker,closeTime:t,topic:e,horizon:o,venue:n.venue||"kalshi",question:n.question,clobTokenIds:n.clobTokenIds})}if(0===y.length)return void console.log("No markets found matching filters.");const $=y.filter(e=>"kalshi"===e.venue),w=y.filter(e=>"polymarket"===e.venue),k=await u($,async e=>({info:e,ob:await(0,s.getPublicOrderbook)(e.ticker)}),5,100),b=await u(w,async e=>{if(!e.clobTokenIds)return{info:e,depth:null};const t=(0,i.parseClobTokenIds)(e.clobTokenIds);if(!t)return{info:e,depth:null};return{info:e,depth:await(0,i.polymarketGetOrderbookWithDepth)(t[0])}},5,100),v=[];for(const t of k){if(!t||!t.ob)continue;const{info:n,ob:o}=t,s=o.yes_dollars.map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0),i=o.no_dollars.map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0);s.sort((e,t)=>t.price-e.price),i.sort((e,t)=>t.price-e.price);const r=s.length>0?s[0].price:0,a=i.length>0?100-i[0].price:100,c=a-r,l=s.reduce((e,t)=>e+t.qty,0),u=i.reduce((e,t)=>e+t.qty,0),p=d(o.no_dollars,100);e.minDepth&&l+u<e.minDepth||v.push({ticker:n.ticker,shortTicker:n.ticker,topic:n.topic.toUpperCase(),horizon:n.horizon,closeTime:n.closeTime,bestBid:r,bestAsk:a,spread:c,bidDepth:l,askDepth:u,slippage100:p,held:h.has(n.ticker),venue:"kalshi"})}for(const t of b){if(!t||!t.depth)continue;const{info:n,depth:o}=t;e.minDepth&&o.bidDepthTop3+o.askDepthTop3<e.minDepth||v.push({ticker:(n.question||n.ticker).slice(0,30),shortTicker:(n.question||n.ticker).slice(0,30),topic:n.topic.toUpperCase(),horizon:n.horizon,closeTime:n.closeTime,bestBid:o.bestBid,bestAsk:o.bestAsk,spread:o.spread,bidDepth:o.totalBidDepth,askDepth:o.totalAskDepth,slippage100:"-",held:!1,venue:"polymarket"})}if(e.json)return void console.log(JSON.stringify(v,null,2));const _=(new Date).toISOString().slice(0,10);console.log(),console.log(`${a.c.bold}Liquidity Scanner${a.c.reset} ${a.c.dim}(${_} UTC)${a.c.reset}`),console.log(a.c.dim+"─".repeat(68)+a.c.reset);const S={};for(const e of v){const t=e.topic||"OTHER";S[t]||(S[t]={}),S[t][e.horizon]||(S[t][e.horizon]=[]),S[t][e.horizon].push(e)}let x=0,C=0,O=0;const I=["weekly","monthly","long-term"];for(const[e,t]of Object.entries(S))for(const n of I){const o=t[n];if(!o||0===o.length)continue;const s=o.filter(e=>"kalshi"===e.venue);if(s.length>1){const e=p(s.map(e=>e.ticker));for(const t of s){const n=e.length>0?t.ticker.slice(e.length).replace(/^-/,""):t.ticker;t.shortTicker=n.length>0?n:t.ticker}}o.sort((e,t)=>e.venue!==t.venue?"kalshi"===e.venue?-1:1:"kalshi"===e.venue?e.ticker.localeCompare(t.ticker):e.spread-t.spread),console.log(),console.log(`${a.c.bold}${a.c.cyan}${e}${a.c.reset} ${a.c.dim}— ${l(n)}${a.c.reset}`),console.log(`${a.c.dim} ${(0,a.pad)("Market",22)} ${(0,a.rpad)("Bid¢",5)} ${(0,a.rpad)("Ask¢",5)} ${(0,a.rpad)("Spread",6)} ${(0,a.rpad)("BidDep",6)} ${(0,a.rpad)("AskDep",6)} ${(0,a.rpad)("Slip100",7)}${a.c.reset}`);for(const e of o){x++,e.held&&O++;const t=e.spread>5;let n;t&&C++,n=e.spread<=2?`${a.c.green}${e.spread}¢${a.c.reset}`:e.spread<=5?`${a.c.yellow}${e.spread}¢${a.c.reset}`:`${a.c.red}${e.spread}¢${a.c.reset}`;const o=t?" ⚠️":"",s=e.held?` ${a.c.magenta}← held${a.c.reset}`:"",i=(0,a.rpad)(`${e.spread}¢`,6),r=e.spread<=2?`${a.c.green}${i}${a.c.reset}`:e.spread<=5?`${a.c.yellow}${i}${a.c.reset}`:`${a.c.red}${i}${a.c.reset}`,c="polymarket"===e.venue?`${a.c.blue}POLY${a.c.reset} `:`${a.c.cyan}KLSH${a.c.reset} `;console.log(`${c}${(0,a.pad)(e.shortTicker,22)} ${(0,a.rpad)(String(e.bestBid),5)} ${(0,a.rpad)(String(e.bestAsk),5)} ${r} ${(0,a.rpad)(String(Math.round(e.bidDepth)),6)} ${(0,a.rpad)(String(Math.round(e.askDepth)),6)} ${(0,a.rpad)(e.slippage100,7)}${o}${s}`)}}console.log(),console.log(`${a.c.dim}Summary: ${x} markets | ${C} thin (spread>5¢) | ${O} held${a.c.reset}`),console.log()};const o=n(19218),s=n(96139),i=n(34331),r=n(97325),a=n(99236);function c(e){const t=Date.now(),n=(new Date(e).getTime()-t)/864e5;return n<7?"weekly":n<=35?"monthly":"long-term"}function l(e){switch(e){case"weekly":return"weekly (<7d)";case"monthly":return"monthly (7-35d)";case"long-term":return"long-term (>35d)"}}function d(e,t){const n=e.map(([e,t])=>({noPrice:parseFloat(e),yesAsk:1-parseFloat(e),qty:parseFloat(t)})).filter(e=>e.noPrice>0&&e.qty>0).sort((e,t)=>t.noPrice-e.noPrice);let o=t,s=0;for(const e of n){if(o<=0)break;const t=Math.min(o,e.qty);s+=t*e.yesAsk,o-=t}if(o>0)return"∞";return(100*(s/t)).toFixed(1)+"¢"}async function u(e,t,n,o){const s=[];for(let i=0;i<e.length;i+=n){const r=e.slice(i,i+n),a=await Promise.allSettled(r.map(t));for(const e of a)s.push("fulfilled"===e.status?e.value:null);i+n<e.length&&await new Promise(e=>setTimeout(e,o))}return s}function p(e){if(0===e.length)return"";if(1===e.length)return"";let t=e[0];for(let n=1;n<e.length;n++)for(;!e[n].startsWith(t);)if(t=t.slice(0,-1),0===t.length)return"";return t}},38706:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.listCommand=async function(e){const t=new o.SFClient(e.apiKey,e.apiUrl),{theses:n}=await t.listTheses();if(e.json)return void console.log(JSON.stringify(n,null,2));if(0===n.length)return void(0,s.emptyState)("theses",'Create one: sf create "your market thesis"');console.log(`\n${s.c.bold}`+(0,s.pad)("ID",12)+(0,s.pad)("Status",10)+(0,s.rpad)("Conf",6)+" "+(0,s.pad)("Updated",14)+" Title"+s.c.reset),(0,s.hr)(90);for(const e of n){const t="active"===e.status?s.c.green:"forming"===e.status?s.c.yellow:s.c.dim,n=e.confidence?(0,s.pct)(parseFloat(e.confidence)):"-";console.log((0,s.pad)((0,s.shortId)(e.id),12)+t+(0,s.pad)(e.status,10)+s.c.reset+(0,s.rpad)(n,6)+" "+s.c.dim+(0,s.pad)((0,s.shortDate)(e.updatedAt),14)+s.c.reset+" "+(0,s.trunc)(e.title||e.rawThesis.slice(0,60),50))}console.log(`\n${s.c.dim}${n.length} thesis(es)${s.c.reset}`)};const o=n(19218),s=n(99236)},50869:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.loginCommand=async function(e){const t=e.apiUrl||(0,s.loadConfig)().apiUrl||r,a=(0,s.loadFileConfig)();if(a.apiKey&&!e.force)return console.log(`\n ${i.c.dim}Already logged in (${a.apiKey.slice(0,12)}...).${i.c.reset}`),void console.log(` ${i.c.dim}Run ${i.c.cyan}sf login --force${i.c.dim} to re-authenticate, or ${i.c.cyan}sf logout${i.c.dim} to clear.${i.c.reset}\n`);const c=(0,o.randomBytes)(32).toString("base64url");console.log(`\n ${i.c.dim}Registering login session...${i.c.reset}`);try{const e=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:c})});if(!e.ok){const t=await e.json().catch(()=>({}));return void console.error(` ${i.c.red}Failed to create session: ${t.error||e.status}${i.c.reset}`)}}catch(e){return void console.error(` ${i.c.red}Could not reach ${t}${i.c.reset}`)}const l=`${t}/auth/cli?token=${c}`;console.log(`\n ${i.c.bold}Opening browser...${i.c.reset}`),console.log(` ${i.c.dim}${l}${i.c.reset}\n`);try{const{exec:e}=await Promise.resolve().then(n.t.bind(n,35317,23)),t=process.platform;e(`${"darwin"===t?"open":"win32"===t?"start":"xdg-open"} "${l}"`)}catch{console.log(` ${i.c.dim}Could not open browser. Visit the URL above manually.${i.c.reset}`)}console.log(` ${i.c.dim}Waiting for login...${i.c.reset}`);const d=Date.now();for(;Date.now()-d<3e5;){await new Promise(e=>setTimeout(e,2e3));try{const e=await fetch(`${t}/api/auth/cli/poll?token=${c}`),n=await e.json();if("ready"===n.status&&n.apiKey)return(0,s.saveConfig)({...a,apiKey:n.apiKey,apiUrl:t!==r?t:void 0}),console.log(`\n ${i.c.green}✓${i.c.reset} ${i.c.bold}Authenticated!${i.c.reset}`),console.log(` ${i.c.dim}API key saved to ~/.sf/config.json${i.c.reset}`),console.log(`\n ${i.c.dim}OpenRouter & Tavily are proxied through ${t}${i.c.reset}`),console.log(` ${i.c.dim}No additional API keys needed.${i.c.reset}`),console.log(`\n ${i.c.cyan}sf context${i.c.reset} ${i.c.dim}market intelligence${i.c.reset}`),console.log(` ${i.c.cyan}sf agent${i.c.reset} ${i.c.dim}<thesis>${i.c.reset} ${i.c.dim}start the agent${i.c.reset}`),console.log(` ${i.c.cyan}sf setup --check${i.c.reset} ${i.c.dim}verify config${i.c.reset}`),void console.log();if("expired"===n.status)return void console.error(`\n ${i.c.red}Session expired. Run ${i.c.cyan}sf login${i.c.red} again.${i.c.reset}\n`);process.stdout.write(".")}catch{process.stdout.write("x")}}console.error(`\n ${i.c.red}Timed out waiting for login. Run ${i.c.cyan}sf login${i.c.red} again.${i.c.reset}\n`)};const o=n(76982),s=n(11627),i=n(99236),r=process.env.SF_API_URL||"https://simplefunctions.dev"},23017:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.marketsCommand=async function(e){const t=await fetch(`${s}/api/public/markets`);if(!t.ok)return void console.error(` Error: ${t.status} ${await t.text()}`);const n=await t.json();if(e?.share)return void await(0,o.shareOutput)("markets","",n);if(e?.json)return void console.log(JSON.stringify(n,null,2));if(console.log(`\n Traditional Markets ${n.snapshotAt?.slice(0,10)||""}\n`),!n.markets?.length)return void console.log(" No data available.\n");for(const e of n.markets){const t=e.changePct>=0?"▲":"▼",n=e.changePct>=0?`+${e.changePct}%`:`${e.changePct}%`,o=`$${e.price.toFixed(2)}`;console.log(` ${t} ${e.symbol.padEnd(5)} ${o.padStart(10)} ${n.padStart(16)} ${e.name}`)}console.log()};const o=n(35178),s="https://simplefunctions.dev"},8045:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.milestonesCommand=async function(e){const t=parseInt(e.hours||"168"),n=new Date,r=new Date(n.getTime()+36e5*t),a=`${i}/milestones?limit=200&minimum_start_date=${n.toISOString()}`+(e.category?`&category=${e.category}`:""),c=await fetch(a,{headers:{Accept:"application/json"}});if(!c.ok)throw new Error(`Kalshi API ${c.status}`);let l=((await c.json()).milestones||[]).filter(e=>new Date(e.start_date).getTime()<=r.getTime());if(e.thesis){const t=new o.SFClient(e.apiKey,e.apiUrl),n=await t.getContext(e.thesis),s=new Set((n.edges||[]).map(e=>e.eventTicker).filter(Boolean)),i=new Set((n.edges||[]).map(e=>e.seriesTicker).filter(Boolean));l=l.filter(e=>(e.related_event_tickers||e.primary_event_tickers||[]).some(e=>s.has(e)||i.has(e.split("-")[0])))}if(e.json)return void console.log(JSON.stringify(l,null,2));if(0===l.length)return void console.log(`${s.c.dim}No milestones in the next ${t} hours.${s.c.reset}`);l.sort((e,t)=>new Date(e.start_date).getTime()-new Date(t.start_date).getTime()),console.log(`${s.c.bold}${s.c.cyan}Upcoming Milestones (next ${t}h)${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(80)}${s.c.reset}`);for(const e of l){const t=new Date(e.start_date),o=Math.round((t.getTime()-n.getTime())/36e5),i=o<=24?`${s.c.bold}${o}h${s.c.reset}`:`${s.c.dim}${Math.round(o/24)}d${s.c.reset}`,r=`${s.c.dim}[${e.category}]${s.c.reset}`,a=(e.related_event_tickers||[]).slice(0,3).join(", ");console.log(` ${i.padEnd(12)} ${r.padEnd(25)} ${e.title}`),a&&console.log(` ${" ".repeat(10)} ${s.c.dim}${a}${s.c.reset}`)}console.log(`\n${s.c.dim}${l.length} milestone(s)${s.c.reset}`)};const o=n(19218),s=n(99236),i="https://api.elections.kalshi.com/trade-api/v2"},45475:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ordersCommand=async function(e){const t=e.status||"resting",n=await(0,o.getOrders)({status:t,limit:100});if(!n)throw new Error("Kalshi not configured. Set KALSHI_API_KEY_ID + KALSHI_PRIVATE_KEY_PATH.");if(e.json)return void console.log(JSON.stringify(n.orders,null,2));if(0===n.orders.length)return void console.log(`${s.c.dim}No ${t} orders.${s.c.reset}`);console.log(`${s.c.bold}${s.c.cyan}Orders (${t})${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(80)}${s.c.reset}`);for(const e of n.orders){const t=e.yes_price_dollars?100*parseFloat(e.yes_price_dollars)+"¢":`${e.yes_price||"?"}¢`,n="yes"===e.side?`${s.c.green}YES${s.c.reset}`:`${s.c.red}NO${s.c.reset}`,o=e.remaining_count_fp||e.remaining_count||"?";console.log(` ${(e.ticker||"").padEnd(35)} ${n} ${t.padEnd(8)} qty ${o}`)}console.log(`\n${s.c.dim}${n.orders.length} order(s)${s.c.reset}`)};const o=n(96139),s=n(99236)},33766:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.performanceCommand=async function(e){if(!(0,s.isKalshiConfigured)())return void console.log(`${r.c.yellow}Kalshi not configured.${r.c.reset} Run ${r.c.cyan}sf setup --kalshi${r.c.reset} first.`);const t=await(0,s.getFills)({limit:500});if(!t||0===t.fills.length)return void console.log(`${r.c.dim}No fills found.${r.c.reset}`);const n=new Map;for(const e of t.fills){const t=e.ticker||e.market_ticker||"";if(!t)continue;const o=e.action||"buy",s=e.side||"yes",i=Math.round(parseFloat(e.count_fp||e.count||"0")),r=Math.round(100*parseFloat(e.yes_price_dollars||"0"));let a=i;"sell"===o&&(a=-a),"no"===s&&(a=-a);const c=n.get(t)||{ticker:t,netQty:0,totalCostCents:0,totalContracts:0,earliestFillTs:1/0};if(c.netQty+=a,a>0){const e="no"===s?100-r:r;c.totalCostCents+=e*i,c.totalContracts+=i}const l=e.created_time||e.ts||e.created_at;if(l){const e=Math.floor(new Date(l).getTime()/1e3);e<c.earliestFillTs&&(c.earliestFillTs=e)}n.set(t,c)}let u=[...n.values()].filter(e=>0!==e.netQty);if(e.ticker){const t=e.ticker.toLowerCase();u=u.filter(e=>e.ticker.toLowerCase().includes(t))}if(0===u.length)return void console.log(`${r.c.dim}No open positions found${e.ticker?` matching "${e.ticker}"`:""}.${r.c.reset}`);const p=e.since?Math.floor(new Date(e.since).getTime()/1e3):Math.min(...u.map(e=>e.earliestFillTs===1/0?Math.floor(Date.now()/1e3)-2592e3:e.earliestFillTs)),h=Math.floor(Date.now()/1e3),m=await(0,s.getBatchCandlesticks)({tickers:u.map(e=>e.ticker),startTs:p,endTs:h,periodInterval:1440}),g=new Map;for(const e of m){const t=[];for(const n of e.candlesticks||[]){const e=parseFloat(n.yes_bid?.close_dollars||"0"),o=parseFloat(n.yes_ask?.close_dollars||"0"),s=e>0&&o>0?(e+o)/2:e||o,i=parseFloat(n.price?.close_dollars||"0")||s,r=Math.round(100*i),a=n.end_period_ts||n.period_end_ts||n.ts;a&&t.push({date:l(new Date(1e3*a)),close:r})}t.sort((e,t)=>e.date.localeCompare(t.date)),g.set(e.market_ticker,t)}const f=new Set;for(const[,e]of g)for(const t of e)f.add(t.date);const y=[...f].sort(),$=new Map;for(const e of u)$.set(e.ticker,e.totalContracts>0?Math.round(e.totalCostCents/e.totalContracts):0);const w=[];try{const e=(0,i.loadConfig)(),t=new o.SFClient(e.apiKey,e.apiUrl),n=await t.getFeed(720),s=n?.feed||n?.items||n||[];if(Array.isArray(s))for(const e of s){const t=e.delta??e.confidenceDelta??0;if(Math.abs(t)>=.02){const n=e.evaluatedAt||e.createdAt||e.timestamp||"";n&&w.push({date:l(new Date(n)),direction:t>0?"up":"down",deltaPct:Math.round(100*t),summary:e.summary||""})}}}catch{}const k=[];for(const e of u){const t=$.get(e.ticker)||0,n=g.get(e.ticker)||[],o=n.length>0?n[n.length-1].close:t,s=(o-t)*e.netQty,i=t*e.netQty,r=0!==i?s/Math.abs(i)*100:0,a=n.map(n=>(n.close-t)*e.netQty);k.push({ticker:e.ticker,qty:e.netQty,entry:t,current:o,pnlCents:s,pnlPct:r,dailyPnl:a})}k.sort((e,t)=>Math.abs(t.pnlCents)-Math.abs(e.pnlCents));const b=y.map(e=>{let t=0;for(const n of u){const o=g.get(n.ticker)||[],s=$.get(n.ticker)||0,i=o.find(t=>t.date===e);i&&(t+=(i.close-s)*n.netQty)}return t}),v=u.reduce((e,t)=>e+t.totalCostCents,0),_=k.reduce((e,t)=>e+t.pnlCents,0),S=v>0?_/v*100:0;if(e.json)return void console.log(JSON.stringify({positions:k.map(e=>({ticker:e.ticker,qty:e.qty,entry:e.entry,current:e.current,pnl:e.pnlCents,pnlPct:Math.round(10*e.pnlPct)/10})),totalDailyPnl:y.map((e,t)=>({date:e,pnl:b[t]})),events:w,summary:{cost:v,pnl:_,pnlPct:Math.round(10*S)/10}},null,2));const x=y.length>0?a(new Date(y[0])):"?",C=a(new Date);console.log(),console.log(` ${r.c.bold}Portfolio Performance${r.c.reset} ${r.c.dim}(${x} → ${C})${r.c.reset}`),console.log(` ${r.c.dim}${"─".repeat(76)}${r.c.reset}`),console.log();const O=Math.max(...k.map(e=>e.ticker.length),5)+2,I=O+50,P=(e,t)=>e.padEnd(t);console.log(` ${r.c.dim}${P("Ticker",O)} Qty Entry Now P&L Trend${r.c.reset}`);for(const e of k){const t=c(e.pnlCents),n=e.pnlCents>0?r.c.green:e.pnlCents<0?r.c.red:r.c.dim,o=d(e.dailyPnl,e=>e>=0?r.c.green:r.c.red);console.log(` ${P(e.ticker,O)} ${(0,r.rpad)(String(e.qty),8)}${(0,r.rpad)(e.entry+"¢",7)}${(0,r.rpad)(e.current+"¢",7)}${n}${(0,r.rpad)(t,13)}${r.c.reset}`+o)}console.log(` ${r.c.dim}${"─".repeat(I)}${r.c.reset}`);const T=c(_),E=`${S>=0?"+":""}${S.toFixed(1)}%`,A=_>=0?r.c.green:r.c.red,M=d(b,e=>e>=0?r.c.green:r.c.red);if(console.log(` ${r.c.bold}${P("TOTAL",O)}${r.c.reset} ${(0,r.rpad)("",22)}${A}${r.c.bold}${(0,r.rpad)(`${T} (${E})`,13)}${r.c.reset}`+M),w.length>0){const e=new Set(y),t=w.filter(t=>e.has(t.date));if(t.length>0){console.log();for(const e of t.slice(0,8)){const t="up"===e.direction?`${r.c.green}▲${r.c.reset}`:`${r.c.red}▼${r.c.reset}`,n=e.summary.length>55?e.summary.slice(0,54)+"…":e.summary;console.log(` ${t} ${r.c.dim}${a(new Date(e.date))}${r.c.reset} ${e.deltaPct>0?"+":""}${e.deltaPct}% → ${n}`)}}}console.log();const R=`$${(v/100).toFixed(0)}`;console.log(` ${r.c.dim}Cost basis:${r.c.reset} ${R} ${r.c.dim}|${r.c.reset} ${A}${r.c.bold}${T} (${E})${r.c.reset}`),console.log()};const o=n(19218),s=n(96139),i=n(11627),r=n(99236);function a(e){return`${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][e.getMonth()]} ${String(e.getDate()).padStart(2,"0")}`}function c(e){const t=Math.abs(e/100),n=t>=1e3?`${(t/1e3).toFixed(1)}k`:t>=100?t.toFixed(0):t.toFixed(2);return e>=0?`+$${n}`:`-$${n}`}function l(e){return e.toISOString().slice(0,10)}function d(e,t){if(0===e.length)return"";const n=Math.min(...e),o=Math.max(...e)-n||1,s=["▁","▂","▃","▄","▅","▆","▇","█"];return e.map(e=>{const i=Math.round((e-n)/o*(s.length-1)),a=s[i];return t?t(e)+a+r.c.reset:a}).join("")}},8784:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.positionsCommand=async function(e){const t=new o.SFClient(e.apiKey,e.apiUrl);let n=null;(0,s.isKalshiConfigured)()&&(console.log(`${a.c.dim}Fetching Kalshi positions...${a.c.reset}`),n=await(0,s.getPositions)());const c=(0,r.loadConfig)();let l=[];if(c.polymarketWalletAddress){console.log(`${a.c.dim}Fetching Polymarket positions...${a.c.reset}`);try{l=await(0,i.polymarketGetPositions)(c.polymarketWalletAddress)}catch{}}console.log(`${a.c.dim}Fetching thesis edges...${a.c.reset}`);let d=[];try{d=(await t.listTheses()).theses||[]}catch(e){console.warn(`${a.c.yellow}Warning: Could not fetch theses: ${e}${a.c.reset}`)}let u=[];if(e.thesis)try{const n=await t.getContext(e.thesis);for(const e of n.edges||[])u.push({thesisId:n.thesisId,thesisTitle:n.thesis||n.title||"",edge:e})}catch(t){console.warn(`${a.c.yellow}Warning: Could not fetch context for ${e.thesis}: ${t}${a.c.reset}`)}else{const e=d.filter(e=>"monitoring"===e.status||"active"===e.status);for(const n of e.slice(0,5))try{const e=await t.getContext(n.id);for(const t of e.edges||[])u.push({thesisId:n.id,thesisTitle:e.thesis||e.title||n.title||"",edge:t})}catch{}}if(n&&n.length>0){console.log(`${a.c.dim}Fetching live prices for ${n.length} positions...${a.c.reset}`);for(const e of n)try{const t=await(0,s.getMarketPrice)(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=(t-e.average_price_paid)*e.quantity),await new Promise(e=>setTimeout(e,100))}catch{}}const p=new Map;for(const e of u){const t=e.edge.marketId;p.has(t)||p.set(t,[]),p.get(t).push(e)}if(e.json)return void console.log(JSON.stringify({kalshiConfigured:(0,s.isKalshiConfigured)(),polymarketConfigured:!!c.polymarketWalletAddress,positions:n||[],polymarketPositions:l,edges:u.map(e=>({...e.edge,thesisId:e.thesisId}))},null,2));if(n&&n.length>0){(0,a.header)("Your Positions (via Kalshi)"),console.log(" "+a.c.bold+(0,a.pad)("Ticker",25)+(0,a.rpad)("Side",5)+(0,a.rpad)("Qty",7)+(0,a.rpad)("Avg",6)+(0,a.rpad)("Now",6)+(0,a.rpad)("P&L",9)+(0,a.rpad)("Edge",7)+" Signal"+a.c.reset),console.log(" "+a.c.dim+"─".repeat(85)+a.c.reset);for(const e of n){const t=e.current_value||null,n=e.average_price_paid||0,o=e.unrealized_pnl||0,s=o>0?a.c.green:o<0?a.c.red:a.c.dim,i=o>=0?`+$${(o/100).toFixed(2)}`:`-$${(Math.abs(o)/100).toFixed(2)}`,r=(p.get(e.ticker)||[])[0],c=r?.edge?.edge??r?.edge?.edgeSize??0,l=Math.abs(c)>10?a.c.green:Math.abs(c)>5?a.c.yellow:a.c.dim;let d="HOLD";if(r){d=e.side===r.edge.direction&&c>3?"HOLD":c<-3?"CLOSE":"HOLD"}else d="—";const u="HOLD"===d?a.c.dim:"CLOSE"===d?a.c.red:a.c.yellow;console.log(" "+(0,a.pad)(e.ticker,25)+(0,a.rpad)(e.side.toUpperCase(),5)+(0,a.rpad)(String(e.quantity),7)+(0,a.rpad)(`${n}¢`,6)+(0,a.rpad)(t?`${t}¢`:"-",6)+`${s}${(0,a.rpad)(i,9)}${a.c.reset}`+`${l}${(0,a.rpad)(c?`${c>0?"+":""}${c.toFixed(0)}`:"-",7)}${a.c.reset}`+` ${u}${d}${a.c.reset}`)}console.log("")}else(0,s.isKalshiConfigured)()?console.log(`\n ${a.c.dim}No open Kalshi positions.${a.c.reset}\n`):console.log(`\n ${a.c.dim}Kalshi not configured. Run: ${a.c.cyan}sf setup --kalshi${a.c.reset}\n`);if(l.length>0){(0,a.header)("Polymarket Positions"),console.log(" "+a.c.bold+(0,a.pad)("Market",35)+(0,a.rpad)("Side",5)+(0,a.rpad)("Size",8)+(0,a.rpad)("Avg",6)+(0,a.rpad)("Now",6)+(0,a.rpad)("P&L",9)+a.c.reset),console.log(" "+a.c.dim+"─".repeat(75)+a.c.reset);for(const e of l){const t=(e.title||e.slug||e.asset||"").slice(0,34),n=e.outcome||"YES",o=e.size||0,s=Math.round(100*(e.avgPrice||0)),i=Math.round(100*(e.curPrice||e.currentPrice||0)),r=e.cashPnl||(i-s)*o/100,c=r>=0?a.c.green:a.c.red,l=r>=0?`+$${r.toFixed(2)}`:`-$${Math.abs(r).toFixed(2)}`;console.log(" "+(0,a.pad)(t,35)+(0,a.rpad)(n.toUpperCase(),5)+(0,a.rpad)(String(Math.round(o)),8)+(0,a.rpad)(`${s}¢`,6)+(0,a.rpad)(`${i}¢`,6)+`${c}${(0,a.rpad)(l,9)}${a.c.reset}`)}console.log("")}else c.polymarketWalletAddress&&console.log(`${a.c.dim}No open positions on Polymarket.${a.c.reset}\n`);const h=new Set((n||[]).map(e=>e.ticker)),m=u.filter(e=>!h.has(e.edge.marketId));if(m.length>0){m.sort((e,t)=>Math.abs(t.edge.edge??t.edge.edgeSize??0)-Math.abs(e.edge.edge??e.edge.edgeSize??0));const t=m.slice(0,10).filter(e=>"kalshi"===e.edge.venue&&!e.edge.orderbook&&Math.abs(e.edge.edge??e.edge.edgeSize??0)>5),n=new Map;if(t.length>0&&(0,s.isKalshiConfigured)()){console.log(`${a.c.dim}Fetching orderbooks for ${t.length} edges...${a.c.reset}`);for(const e of t)try{const t=await(0,s.getOrderbook)(e.edge.marketId);t&&n.set(e.edge.marketId,t),await new Promise(e=>setTimeout(e,150))}catch{}}const o=e.thesis?` (thesis ${(0,a.shortId)(e.thesis)})`:"";(0,a.header)(`Unpositioned Edges${o}`),console.log(" "+a.c.bold+(0,a.pad)("Market",30)+(0,a.rpad)("Mkt",6)+(0,a.rpad)("Thesis",8)+(0,a.rpad)("Edge",7)+(0,a.rpad)("Spread",8)+(0,a.rpad)("Liq",8)+" Signal"+a.c.reset),console.log(" "+a.c.dim+"─".repeat(85)+a.c.reset);for(const e of m.slice(0,20)){const t=e.edge,o=t.edge??t.edgeSize??0,s=o>10?a.c.green:o>5?a.c.yellow:o>0?a.c.dim:a.c.red,i=t.marketPrice??0,r=t.thesisPrice??t.thesisImpliedPrice??0,c=(t.market||t.marketTitle||t.marketId||"?").slice(0,29),l=t.orderbook,d=n.get(t.marketId),u=l||d,p=u?`${u.spread}¢`:"-",h=u?u.liquidityScore:"-",m="high"===u?.liquidityScore?a.c.green:"medium"===u?.liquidityScore?a.c.yellow:a.c.dim;let g="WATCH";(o>10&&"low"!==u?.liquidityScore||o>5&&"high"===u?.liquidityScore)&&(g="CONSIDER");const f="CONSIDER"===g?a.c.green:a.c.dim;console.log(" "+(0,a.pad)(c,30)+(0,a.rpad)(`${i.toFixed(0)}¢`,6)+(0,a.rpad)(`${r.toFixed(0)}¢`,8)+`${s}${(0,a.rpad)(`${o>0?"+":""}${o.toFixed(0)}`,7)}${a.c.reset}`+(0,a.rpad)(p,8)+`${m}${(0,a.rpad)(h,8)}${a.c.reset}`+` ${f}${g}${a.c.reset}`)}console.log("")}else 0===u.length&&console.log(`\n${a.c.dim}No thesis edges found.${a.c.reset}\n`)};const o=n(19218),s=n(96139),i=n(34331),r=n(11627),a=n(99236)},35344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.promptCommand=async function(e,t){const n=(t.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev").replace(/\/$/,""),o=t.apiKey||process.env.SF_API_KEY||"",s=new URLSearchParams;t.sections&&s.set("sections",t.sections);t.maxLength&&s.set("maxLength",t.maxLength);t.json&&s.set("format","json");const i=e?`/api/thesis/${e}/prompt`:"/api/prompt",r=s.toString()?`?${s.toString()}`:"",a=await fetch(`${n}${i}${r}`,{headers:{Authorization:`Bearer ${o}`}});if(!a.ok){const e=await a.text();throw new Error(`API error ${a.status}: ${e}`)}const c=await a.text();process.stdout.write(c),c.endsWith("\n")||process.stdout.write("\n")}},40791:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.publishCommand=async function(e,t){const n=function(e){return e.toLowerCase().trim().replace(/[^a-z0-9\s-]/g,"").replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,60)}(t.slug);n.length<3&&(console.error(`\n Error: slug too short after normalization: "${n}" (need 3+ chars)\n`),process.exit(1));n!==t.slug&&console.log(` Slug normalized: "${t.slug}" → "${n}"`);const s=new o.SFClient(t.apiKey,t.apiUrl);await s.publish(e,n,t.description),console.log(`\n ✓ Published: https://simplefunctions.dev/thesis/${n}\n`)},t.unpublishCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl);await n.unpublish(e),console.log(`\n ✓ Unpublished thesis ${e}\n`)};const o=n(19218)},65240:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryCommand=async function(e,t){const n=t?.limit||"10",a=`${s}/api/public/query?q=${encodeURIComponent(e)}&limit=${n}`,c=await fetch(a);if(!c.ok){const e=await c.text();return void(429===c.status?console.error(" Rate limited. Wait a minute and try again."):console.error(` Error: ${c.status} ${e}`))}const l=await c.json();if(t?.share)return void await(0,o.shareOutput)("query",e,l);if(t?.json)return void console.log(JSON.stringify(l,null,2));console.log(),console.log(` ${l.query}`),console.log(),l.answer&&(console.log(` ${l.answer}`),console.log());if(l.keyFactors?.length>0){console.log(" Key factors:");for(const e of l.keyFactors)console.log(` • ${e}`);console.log()}const d=l.kalshi||[],u=l.polymarket||[];if(d.length>0||u.length>0){console.log(" Markets");for(const e of d.slice(0,8)){const t=i(e.volume),n=e.ticker?` ${e.ticker}`:"";console.log(` K ${String(e.price).padStart(3)}¢ vol ${t.padStart(6)} ${e.title.slice(0,55)}${n}`)}d.length>0&&u.length>0&&console.log();for(const e of u.slice(0,8)){const t=i(e.volume),n=e.slug?` ${e.slug}`:"";console.log(` P ${String(e.price).padStart(3)}¢ vol ${t.padStart(6)} ${e.title.slice(0,55)}${n}`)}console.log()}const p=l.x||[];if(p.length>0){console.log(" X signals");for(const e of p.slice(0,5)){const t=`${r(e.likes)}♥ ${r(e.retweets)}⟲`;console.log(` @${e.author} ${t} ${e.text.slice(0,80)}`)}console.log()}const h=l.traditional||[];if(h.length>0){console.log(" Traditional");for(const e of h){const t=e.change1d>=0?"+":"";console.log(` ${e.symbol.padEnd(5)} $${e.price} ${t}${e.change1d} (${t}${e.changePct}%) ${e.name}`)}console.log()}if(l.theses?.length>0){console.log(" Theses");for(const e of l.theses.slice(0,3))console.log(` ${e.confidence||"?"}% ${String(e.edges||0).padStart(2)} edges ${e.title.slice(0,50)}`);console.log()}if(l.content?.length>0){console.log(" Content");for(const e of l.content.slice(0,5)){const t=e.type.padEnd(9);console.log(` ${t} ${e.title.slice(0,50)} ${e.url}`)}console.log()}const m=l.meta||{},g=m.sources||l.sources||[],f=m.latencyMs?`${(m.latencyMs/1e3).toFixed(1)}s`:"";console.log(` Sources: ${g.join(", ")}${f?` (${f})`:""}`),console.log()};const o=n(35178),s=process.env.SF_API_URL||"https://simplefunctions.dev";function i(e){return e>1e6?`${(e/1e6).toFixed(1)}M`:e>1e3?`${(e/1e3).toFixed(0)}K`:String(Math.round(e))}function r(e){return e>1e6?`${(e/1e6).toFixed(1)}M`:e>1e3?`${(e/1e3).toFixed(1)}K`:String(e)}},43423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rfqCommand=async function(e,t,n){(0,s.requireTrading)();const r=parseInt(t);if(isNaN(r)||r<=0)throw new Error("Quantity must be a positive integer");console.log(),console.log(` ${i.c.bold}${i.c.cyan}Request for Quote${i.c.reset}`),console.log(` ${i.c.dim}${"─".repeat(30)}${i.c.reset}`),console.log(` Market: ${e}`),console.log(` Contracts: ${r}`),n.targetCost&&console.log(` Target cost: ${n.targetCost}¢/contract`);console.log(" Rest remainder: "+(n.restRemainder?"yes":"no")),console.log();try{const t=await(0,o.createRFQ)({market_ticker:e,contracts:r,rest_remainder:n.restRemainder||!1,...n.targetCost?{target_cost_centi_cents:100*parseInt(n.targetCost)}:{}});console.log(` ${i.c.green}✓${i.c.reset} RFQ created: ${t.id||t.rfq_id||"OK"}`),console.log()}catch(e){console.error(`\n ${i.c.red}✗${i.c.reset} ${e.message}\n`),process.exit(1)}};const o=n(96139),s=n(11627),i=n(99236)},52072:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.registerRuntime=function(e){const t=e.command("runtime").description("Execution runtime daemon");t.command("start").option("--daemon","Run as background process").description("Start the execution runtime").action(async e=>{if((0,s.isKalshiConfigured)()||(console.error(`\n ${i.c.red}Error:${i.c.reset} Kalshi credentials not configured.`),console.error(" Run: sf setup --enable-trading\n"),process.exit(1)),(0,r.existsSync)(l)){const e=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(e),0),console.error(`\n ${i.c.yellow}Warning:${i.c.reset} Runtime already running (PID ${e}).`),console.error(" Stop it first: sf runtime stop\n"),process.exit(1)}catch{(0,r.unlinkSync)(l)}}e.daemon&&(console.error(`\n ${i.c.dim}Daemon mode not yet implemented. Run in foreground for now.${i.c.reset}\n`),process.exit(1)),await async function(){const e=(0,a.join)((0,c.homedir)(),".sf");(0,r.existsSync)(e)||(0,r.mkdirSync)(e,{recursive:!0});(0,r.writeFileSync)(l,process.pid.toString()),console.log(),console.log(` ${i.c.bold}SimpleFunctions Runtime${i.c.reset}`),console.log(` ${i.c.dim}PID ${process.pid} · polling every ${d/1e3}s · Ctrl+C to stop${i.c.reset}`),console.log();const t=new o.SFClient;let n=0;const s=()=>{console.log(`\n ${i.c.dim}Runtime stopping...${i.c.reset}`);try{(0,r.unlinkSync)(l)}catch{}process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s);for(;;){n++;Date.now();try{const{intents:e}=await t.listIntents({active:!0});if(!e||0===e.length){n%10==1&&h("No active intents. Waiting..."),await m(d);continue}for(const n of e)await u(t,n)}catch(e){h(`Error in cycle: ${e.message}`)}await m(d)}}()}),t.command("stop").description("Stop the runtime daemon").action(async()=>{if(!(0,r.existsSync)(l))return void console.log(`\n ${i.c.dim}No runtime running.${i.c.reset}\n`);const e=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(e),"SIGTERM"),(0,r.unlinkSync)(l),console.log(`\n ${i.c.green}OK${i.c.reset} Runtime stopped (PID ${e}).\n`)}catch{(0,r.unlinkSync)(l),console.log(`\n ${i.c.dim}Runtime was not running (stale PID file removed).${i.c.reset}\n`)}}),t.command("status").option("--json","JSON output").description("Show runtime status and active intents").action(async e=>{try{let t=!1,n="";if((0,r.existsSync)(l)){n=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(n),0),t=!0}catch{t=!1}}const s=new o.SFClient,{intents:a}=await s.listIntents({active:!0});if(e.json)return void console.log(JSON.stringify({running:t,pid:t?n:null,intents:a},null,2));if(console.log(),console.log(` ${i.c.bold}Runtime${i.c.reset} ${t?`${i.c.green}RUNNING${i.c.reset} (PID ${n})`:`${i.c.dim}STOPPED${i.c.reset}`}`),console.log(),!a||0===a.length)return console.log(` ${i.c.dim}No active intents.${i.c.reset}`),console.log(" Create one: sf intent buy TICKER QTY --price CENTS"),void console.log();const c={};for(const e of a)c[e.status]=(c[e.status]||0)+1;const d=Object.entries(c).map(([e,t])=>`${t} ${e}`).join(", ");console.log(` Active intents: ${d}`),console.log();for(const e of a){const t=e.action.toUpperCase(),n=e.direction.toUpperCase(),o=e.maxPrice?`@ ≤${e.maxPrice}c`:"@ market",s=e.targetQuantity>0?` (${Math.round(e.filledQuantity/e.targetQuantity*100)}%)`:"";if(console.log(` [${e.status}] ${t} ${e.marketId} ${n} ${e.targetQuantity}${o} filled ${e.filledQuantity}/${e.targetQuantity}${s}`),"immediate"!==e.triggerType){const t="price_below"===e.triggerType?`price ≤ ${e.triggerPrice}c`:"price_above"===e.triggerType?`price ≥ ${e.triggerPrice}c`:e.triggerType;console.log(` trigger: ${t}`)}}console.log(),t||(console.log(` ${i.c.dim}Start runtime to execute: sf runtime start${i.c.reset}`),console.log())}catch(e){console.error(`${i.c.red}Error:${i.c.reset} ${e.message}`),process.exit(1)}})};const o=n(19218),s=n(96139),i=n(99236),r=n(79896),a=n(16928),c=n(70857),l=(0,a.join)((0,c.homedir)(),".sf","runtime.pid"),d=((0,a.join)((0,c.homedir)(),".sf","runtime.log"),3e4);async function u(e,t){if(!(t.activateAt&&new Date(t.activateAt)>new Date))if(new Date(t.expireAt)<new Date){h(`Intent ${t.id.slice(0,8)} expired`);try{await e.cancelIntentAPI(t.id)}catch{}}else{if("pending"===t.status&&h(`Arming intent ${t.id.slice(0,8)}: ${t.action.toUpperCase()} ${t.marketId} ${t.direction.toUpperCase()} x${t.targetQuantity}`),"pending"===t.status||"armed"===t.status){const n=await async function(e){switch(e.triggerType){case"immediate":return!0;case"price_below":{if(!e.triggerPrice)return!1;const t=await(0,s.getMarketPrice)(e.marketId);return null!==t&&t<=e.triggerPrice}case"price_above":{if(!e.triggerPrice)return!1;const t=await(0,s.getMarketPrice)(e.marketId);return null!==t&&t>=e.triggerPrice}case"time":return!!e.triggerAt&&new Date>=new Date(e.triggerAt);default:return!1}}(t);if(!n)return;h(`TRIGGERED: ${t.id.slice(0,8)} ${t.marketId} (${t.triggerType})`),t.autoExecute?await p(e,t):h(` Awaiting confirmation. Use: sf intent status ${t.id.slice(0,8)}`)}"triggered"===t.status&&t.autoExecute&&await p(e,t)}}async function p(e,t){if("kalshi"!==t.venue)return void h(` Skipping ${t.id.slice(0,8)}: ${t.venue} execution not yet supported`);const n=t.targetQuantity-t.filledQuantity;if(!(n<=0)){h(` Executing: ${t.action.toUpperCase()} ${t.marketId} ${t.direction.toUpperCase()} x${n}${t.maxPrice?` @ ≤${t.maxPrice}c`:""}`);try{const e=await(0,s.createOrder)({ticker:t.marketId,side:t.direction,action:t.action,type:t.maxPrice?"limit":"market",count:n,...t.maxPrice?{yes_price:t.maxPrice}:{}}),o=e.order||e,l=o.fill_count||o.fill_count_fp||n;h(` ${i.c.green}FILLED${i.c.reset}: ${l} contracts, order ${o.order_id||"OK"}`);try{const e=JSON.stringify({ts:(new Date).toISOString(),intentId:t.id,action:t.action,ticker:t.marketId,side:t.direction,quantity:l,price:t.maxPrice,orderId:o.order_id,source:t.source})+"\n";(0,r.appendFileSync)((0,a.join)((0,c.homedir)(),".sf","trade-journal.jsonl"),e)}catch{}}catch(e){const t=e.message||String(e);t.includes("403")?h(` ${i.c.red}FAILED${i.c.reset}: 403 Forbidden — Kalshi key lacks write permission`):h(` ${i.c.red}FAILED${i.c.reset}: ${t}`)}}}function h(e){const t=(new Date).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});console.log(` ${i.c.dim}${t}${i.c.reset} ${e}`)}function m(e){return new Promise(t=>setTimeout(t,e))}},46183:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scanCommand=async function(e,t){if(t.market)return void await async function(e,t){console.log(`${i.c.dim}Fetching market ${e}...${i.c.reset}`);const n=await(0,o.kalshiFetchMarket)(e);if(t)return void console.log(JSON.stringify(n,null,2));(0,i.header)(`${n.title||n.ticker}`),n.subtitle&&console.log(`${i.c.dim}${n.subtitle}${i.c.reset}`);console.log(`Event: ${n.event_ticker} Status: ${n.status}`),console.log(""),console.log(`Yes Ask: ${(0,i.cents)(n.yes_ask_dollars)} (size: ${n.yes_ask_size_fp||"-"})`),console.log(`Yes Bid: ${(0,i.cents)(n.yes_bid_dollars)} (size: ${n.yes_bid_size_fp||"-"})`),console.log(`No Ask: ${(0,i.cents)(n.no_ask_dollars)}`),console.log(`No Bid: ${(0,i.cents)(n.no_bid_dollars)}`),console.log(`Last: ${(0,i.cents)(n.last_price_dollars)}`),console.log(""),console.log(`Volume: ${(0,i.vol)(n.volume_fp)}`),console.log(`Vol 24h: ${(0,i.vol)(n.volume_24h_fp)}`),console.log(`Open Int: ${(0,i.vol)(n.open_interest_fp)}`),console.log(`Liquidity: ${(0,i.vol)(n.liquidity_dollars)}`),console.log(""),console.log(`Open: ${n.open_time}`),console.log(`Close: ${n.close_time}`),n.rules_primary&&console.log(`\nRules: ${n.rules_primary.slice(0,300)}`)}(t.market.toUpperCase(),t.json);if(t.series)return void await async function(e,t){console.log(`${i.c.dim}Fetching events for series ${e}...${i.c.reset}`);let n=await(0,o.kalshiFetchEvents)(e);if(0===n.length){const n=await(0,o.kalshiFetchMarketsBySeries)(e);return t?void console.log(JSON.stringify(n,null,2)):0===n.length?void console.log(`${i.c.dim}No open markets found for series ${e}.${i.c.reset}`):((0,i.header)(`${e} — ${n.length} markets`),void c(n))}if(t)return void console.log(JSON.stringify(n,null,2));for(const e of n){(0,i.header)(`${e.title||e.event_ticker}`),console.log(`${i.c.dim}${e.event_ticker} | ${e.category||"-"} | strike: ${e.strike_date||"-"}${i.c.reset}`);c(e.markets&&e.markets.length>0?e.markets:await(0,o.kalshiFetchMarketsByEvent)(e.event_ticker))}}(t.series.toUpperCase(),t.json);await async function(e,t,n="all",o){const c="kalshi"===n?Promise.resolve([]):(0,s.polymarketSearch)(e,10).catch(()=>[]);"polymarket"!==n&&console.log(`${i.c.dim}Scanning Kalshi for: "${e}"...${i.c.reset}`);"kalshi"!==n&&console.log(`${i.c.dim}Scanning Polymarket for: "${e}"...${i.c.reset}`);const l=[];if("polymarket"!==n)try{const t=`${a}/api/public/scan?q=${encodeURIComponent(e)}&limit=30`,n=await fetch(t);if(!n.ok)throw new Error(`Proxy ${n.status}`);const o=await n.json(),s=o.matchedSeries||[],r=o.markets||[];console.log(`\n${i.c.bold}Matched ${s.length} series via proxy:${i.c.reset}\n`);for(const e of s.slice(0,15))console.log(` ${(0,i.pad)(e.ticker,25)} score=${e.score} ${e.title||""}`);for(const e of r)l.push({venue:"kalshi",seriesTicker:e.series_ticker,ticker:e.ticker,title:e.title||e.exchange_title||"",yesAsk:parseFloat(e.yes_ask_dollars||"0"),lastPrice:parseFloat(e.last_price_dollars||"0"),volume24h:parseFloat(e.volume_24h_fp||"0"),liquidity:parseFloat(e.open_interest_fp||e.liquidity_dollars||"0")})}catch(e){console.warn(`${i.c.dim}Kalshi scan failed: ${e}${i.c.reset}`)}l.sort((e,t)=>t.liquidity-e.liquidity);const d=await c,u=[];for(const e of d)for(const t of e.markets||[]){if(!t.active||t.closed)continue;const n=(0,s.parseOutcomePrices)(t.outcomePrices)[0]||0;u.push({venue:"polymarket",ticker:t.conditionId?.slice(0,16)||t.id,title:t.groupItemTitle?`${e.title}: ${t.groupItemTitle}`:t.question||e.title,yesAsk:n,lastPrice:t.lastTradePrice||n,volume24h:t.volume24hr||0,liquidity:t.liquidityNum||0})}for(const e of l)e.venue||(e.venue="kalshi");const p=[...l,...u];if(p.sort((e,t)=>t.liquidity-e.liquidity),o)return void await(0,r.shareOutput)("scan",e,p);if(t)return void console.log(JSON.stringify(p,null,2));(0,i.header)(`${p.length} Live Markets (${l.length} Kalshi + ${u.length} Polymarket)`),console.log(i.c.bold+(0,i.pad)("",5)+(0,i.pad)("Ticker",30)+(0,i.rpad)("Yes",6)+(0,i.rpad)("Last",6)+(0,i.rpad)("Vol24h",10)+(0,i.rpad)("Liq",10)+" Title"+i.c.reset),(0,i.hr)(120);for(const e of p.slice(0,60)){const t="polymarket"===e.venue?"POLY ":"KLSH ",n="polymarket"===e.venue?i.c.blue+t+i.c.reset:i.c.cyan+t+i.c.reset,o=(e.venue,(e.ticker||"").slice(0,28));console.log(n+(0,i.pad)(o,30)+(0,i.rpad)(`${Math.round(100*e.yesAsk)}¢`,6)+(0,i.rpad)(`${Math.round(100*e.lastPrice)}¢`,6)+(0,i.rpad)((0,i.vol)(Math.round(e.volume24h)),10)+(0,i.rpad)((0,i.vol)(Math.round(e.liquidity)),10)+` ${(e.title||"").slice(0,55)}`)}console.log(""),t||(console.log(`${i.c.dim}Want 24/7 monitoring + edge detection? ${i.c.reset}${i.c.cyan}sf create${i.c.reset}${i.c.dim} "${e.slice(0,50)}"${i.c.reset}`),console.log(""))}(e,t.json,t.venue||"all",t.share)};const o=n(19218),s=n(34331),i=n(99236),r=n(35178),a=process.env.SF_API_URL||"https://simplefunctions.dev";function c(e){if(0!==e.length){e.sort((e,t)=>{const n=parseFloat(e.yes_ask_dollars||e.last_price_dollars||"0");return parseFloat(t.yes_ask_dollars||t.last_price_dollars||"0")-n}),console.log(" "+i.c.bold+(0,i.pad)("Ticker",35)+(0,i.rpad)("YesAsk",8)+(0,i.rpad)("Last",8)+(0,i.rpad)("Vol24h",10)+(0,i.rpad)("Liq",12)+" Title"+i.c.reset),console.log(" "+i.c.dim+"─".repeat(100)+i.c.reset);for(const t of e)console.log(" "+(0,i.pad)(t.ticker||"",35)+(0,i.rpad)((0,i.cents)(t.yes_ask_dollars),8)+(0,i.rpad)((0,i.cents)(t.last_price_dollars),8)+(0,i.rpad)((0,i.vol)(t.volume_24h_fp),10)+(0,i.rpad)((0,i.vol)(t.liquidity_dollars),12)+` ${(t.title||t.subtitle||"").slice(0,55)}`);console.log("")}else console.log(` ${i.c.dim}(no markets)${i.c.reset}`)}},58211:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleCommand=async function(e){const t=await fetch(`${s}/exchange/status`,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Exchange API ${t.status}`);const n=await t.json();let i=null;try{const e=await fetch(`${s}/exchange/schedule`,{headers:{Accept:"application/json"}});e.ok&&(i=await e.json())}catch{}if(e.json)return void console.log(JSON.stringify({status:n,schedule:i},null,2));const r=n.exchange_active?`${o.c.green}OPEN${o.c.reset}`:`${o.c.red}CLOSED${o.c.reset}`;console.log(),console.log(` ${o.c.bold}${o.c.cyan}Exchange Status${o.c.reset}`),console.log(` ${o.c.dim}${"─".repeat(30)}${o.c.reset}`),console.log(` Trading: ${r}`),void 0!==n.trading_active&&console.log(" Trading Active: "+(n.trading_active?"yes":"no"));i?.schedule&&console.log(` Schedule: ${JSON.stringify(i.schedule).slice(0,100)}`);console.log()};const o=n(99236),s="https://api.elections.kalshi.com/trade-api/v2"},96616:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settlementsCommand=async function(e){const t=[];let n="";do{const e=await(0,o.getSettlements)({limit:200,cursor:n||void 0});if(!e)throw new Error("Kalshi not configured. Set KALSHI_API_KEY_ID + KALSHI_PRIVATE_KEY_PATH.");t.push(...e.settlements),n=e.cursor}while(n);let r=t;if(e.thesis){const n=new s.SFClient(e.apiKey,e.apiUrl),o=await n.getContext(e.thesis),i=new Set((o.edges||[]).map(e=>e.marketId));r=t.filter(e=>i.has(e.ticker))}if(e.json)return void console.log(JSON.stringify(r,null,2));if(0===r.length)return void console.log(`${i.c.dim}No settlements found.${i.c.reset}`);console.log(`${i.c.bold}${i.c.cyan}Settlements${i.c.reset}`),console.log(`${i.c.dim}${"─".repeat(80)}${i.c.reset}`),console.log(`${i.c.bold}${"Ticker".padEnd(35)} ${"Result".padEnd(8)} ${"Revenue".padEnd(10)} ${"Cost".padEnd(10)} P&L${i.c.reset}`);let a=0;for(const e of r.slice(0,50)){const t=parseFloat(e.revenue||e.revenue_dollars||"0"),n=parseFloat(e.yes_total_cost||e.yes_total_cost_dollars||"0")+parseFloat(e.no_total_cost||e.no_total_cost_dollars||"0"),o=t-n;a+=o;const s=o>=0?`${i.c.green}+$${o.toFixed(2)}${i.c.reset}`:`${i.c.red}-$${Math.abs(o).toFixed(2)}${i.c.reset}`,r=e.market_result||"-";console.log(` ${(e.ticker||"").slice(0,33).padEnd(35)} ${r.padEnd(8)} $${t.toFixed(2).padEnd(9)} $${n.toFixed(2).padEnd(9)} ${s}`)}console.log(`${i.c.dim}${"─".repeat(80)}${i.c.reset}`);const c=a>=0?`${i.c.green}+$${a.toFixed(2)}${i.c.reset}`:`${i.c.red}-$${Math.abs(a).toFixed(2)}${i.c.reset}`;console.log(` Total: ${c} (${r.length} settlements)`)};const o=n(96139),s=n(19218),i=n(99236)},85417:function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupCommand=async function(e){if(e.check)return async function(){const e=(0,r.loadConfig)();$(),console.log(` ${h("SimpleFunctions Config Status")}`),console.log(` ${p("─".repeat(35))}`),$(),e.apiKey?g(`SF_API_KEY ${p(v(e.apiKey))}`):f("SF_API_KEY not configured (required)");e.openrouterKey?g(`OPENROUTER ${p(v(e.openrouterKey))} (direct)`):e.apiKey?g(`OPENROUTER ${p("proxied via SimpleFunctions")}`):f("OPENROUTER not configured (run sf login or set key)");e.kalshiKeyId&&e.kalshiPrivateKeyPath?g(`KALSHI ${p(v(e.kalshiKeyId))}`):y(`${p("○")} KALSHI ${p("skipped")}`);e.polymarketWalletAddress?g(`POLYMARKET ${p(v(e.polymarketWalletAddress))}`):y(`${p("○")} POLYMARKET ${p("skipped")}`);e.tavilyKey?g(`TAVILY ${p(v(e.tavilyKey))} (direct)`):e.apiKey?g(`TAVILY ${p("proxied via SimpleFunctions")}`):y(`${p("○")} TAVILY ${p("skipped")}`);e.tradingEnabled?g("TRADING enabled"):y(`${p("○")} TRADING ${p("disabled — sf setup --enable-trading")}`);$(),console.log(` ${p("Config file: "+(0,r.getConfigPath)())}`),$()}();if(e.reset)return(0,r.resetConfig)(),g("Config reset"),$(),y("Run sf setup to reconfigure"),void $();if(e.key){const t=process.env.SF_API_URL||"https://simplefunctions.dev",n=await _(e.key,t);n.valid||(f(n.msg),process.exit(1));const o=(0,r.loadFileConfig)();return(0,r.saveConfig)({...o,apiKey:e.key,apiUrl:t}),g(n.msg),void g(`Saved to ${(0,r.getConfigPath)()}`)}if(e.kalshi){const e=(0,r.loadFileConfig)();return $(),console.log(` ${h("Reconfigure Kalshi Credentials")}`),$(),y("Go to https://kalshi.com/account/api-keys to generate a new API key."),y("If you need trading, make sure to enable read+write permissions."),$(),await P(e),(0,r.saveConfig)(e),e.kalshiKeyId&&(process.env.KALSHI_API_KEY_ID=e.kalshiKeyId,process.env.KALSHI_PRIVATE_KEY_PATH=e.kalshiPrivateKeyPath),void $()}if(e.polymarket){const e=(0,r.loadFileConfig)();return $(),console.log(` ${h("Reconfigure Polymarket Credentials")}`),$(),await E(e),(0,r.saveConfig)(e),void $()}if(e.enableTrading){const e=(0,r.loadFileConfig)();return(0,r.saveConfig)({...e,tradingEnabled:!0}),g("Trading enabled. sf buy / sf sell / sf cancel now available."),void $()}if(e.disableTrading){const e=(0,r.loadFileConfig)();return(0,r.saveConfig)({...e,tradingEnabled:!1}),g("Trading disabled."),void $()}return async function(){$(),console.log(` ${h("SimpleFunctions Setup")}`),console.log(` ${p("─".repeat(25))}`),$();const e=(0,r.loadFileConfig)(),t=e.apiUrl||"https://simplefunctions.dev";console.log(` ${h("Step 1: API Key")}`),$();const n=process.env.SF_API_KEY||e.apiKey;if(n){const o=await _(n,t);o.valid?(g(`Detected SF_API_KEY — ${p(v(n))}`),y(p("Skipping.")),e.apiKey=n,$()):(f(`Existing key invalid: ${o.msg}`),e.apiKey=await O(t))}else e.apiKey=await O(t);e.apiUrl=t,(0,r.saveConfig)(e),process.env.SF_API_KEY=e.apiKey,console.log(` ${h("Step 2: AI Model (for sf agent)")}`),$();const o=process.env.OPENROUTER_API_KEY||e.openrouterKey;if(o){const t=await S(o);t.valid?(g(`Detected OPENROUTER_API_KEY — ${p(v(o))}`),y(p("Skipping.")),e.openrouterKey=o,$()):(f(`Existing key invalid: ${t.msg}`),e.openrouterKey=await I())}else e.openrouterKey=await I();(0,r.saveConfig)(e),e.openrouterKey&&(process.env.OPENROUTER_API_KEY=e.openrouterKey);console.log(` ${h("Step 3: Kalshi Exchange (optional)")}`),$();const s=process.env.KALSHI_API_KEY_ID||e.kalshiKeyId,i=process.env.KALSHI_PRIVATE_KEY_PATH||e.kalshiPrivateKeyPath;if(s&&i){process.env.KALSHI_API_KEY_ID=s,process.env.KALSHI_PRIVATE_KEY_PATH=i;const t=await x();t.valid?(g(`Detected Kalshi — ${p(v(s))} (${t.posCount} position(s))`),y(p("Skipping.")),e.kalshiKeyId=s,e.kalshiPrivateKeyPath=i,$()):(f(`Existing credentials invalid: ${t.msg}`),await P(e))}else await P(e);(0,r.saveConfig)(e),console.log(` ${h("Step 4: Polymarket (optional)")}`),$();const a=process.env.POLYMARKET_WALLET_ADDRESS||e.polymarketWalletAddress;a?(g(`Detected wallet — ${p(v(a))}`),y(p("Skipping.")),e.polymarketWalletAddress=a,$()):await E(e);(0,r.saveConfig)(e),e.polymarketWalletAddress&&(process.env.POLYMARKET_WALLET_ADDRESS=e.polymarketWalletAddress);console.log(` ${h("Step 5: News Search (optional)")}`),$();const c=process.env.TAVILY_API_KEY||e.tavilyKey;if(c){const t=await C(c);t.valid?(g(`Detected TAVILY_API_KEY — ${p(v(c))}`),y(p("Skipping.")),e.tavilyKey=c,$()):(f(`Existing key invalid: ${t.msg}`),e.tavilyKey=await T())}else e.tavilyKey=await T();(0,r.saveConfig)(e),e.tavilyKey&&(process.env.TAVILY_API_KEY=e.tavilyKey);if(e.kalshiKeyId){console.log(` ${h("Step 6: Trading (optional)")}`),$(),y("Warning: enabling this unlocks sf buy / sf sell / sf cancel."),y("Your Kalshi API key must have read+write permissions."),$();const t=await k(" Enable trading? (y/N) ",!1);e.tradingEnabled=t,t?g("Trading enabled"):y(p("Skipped. You can enable later with sf setup --enable-trading.")),$(),(0,r.saveConfig)(e)}console.log(` ${p("─".repeat(25))}`),y(`Config saved to ${p((0,r.getConfigPath)())}`),$(),e.apiKey?g("SF_API_KEY configured"):f("SF_API_KEY not configured");e.openrouterKey?g("OPENROUTER_KEY configured"):f("OPENROUTER_KEY skipped");e.kalshiKeyId?g("KALSHI configured"):y(`${p("○")} KALSHI skipped`);e.tavilyKey?g("TAVILY configured"):y(`${p("○")} TAVILY skipped`);$(),e.apiKey&&await A(e)}()};const s=o(n(23785)),i=n(35317),r=n(11627),a=n(19218),c=n(96139),l=n(83969),d=e=>`${e}`,u=e=>`${e}`,p=e=>`${e}`,h=e=>`${e}`,m=e=>`${e}`;function g(e){console.log(` ${d("✓")} ${e}`)}function f(e){console.log(` ${u("✗")} ${e}`)}function y(e){console.log(` ${e}`)}function $(){console.log()}function w(e){const t=s.default.createInterface({input:process.stdin,output:process.stdout,terminal:!0});return new Promise(n=>{t.question(e,e=>{t.close(),n(e.trim())})})}function k(e,t=!0){return w(e).then(e=>e?e.toLowerCase().startsWith("y"):t)}function b(e){const t="darwin"===process.platform?"open":"win32"===process.platform?"start":"xdg-open";(0,i.exec)(`${t} ${e}`)}function v(e){return!e||e.length<=12?e:e.slice(0,8)+"..."+e.slice(-4)}async function _(e,t){try{const n=await fetch(`${t}/api/thesis`,{headers:{Authorization:`Bearer ${e}`}});return n.ok?{valid:!0,msg:`API key valid — connected to ${t.replace("https://","")}`}:401===n.status?{valid:!1,msg:"Invalid key, please try again"}:{valid:!1,msg:`Server returned ${n.status}`}}catch(e){return{valid:!1,msg:`Connection failed: ${e.message}`}}}async function S(e){try{const t=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${e}`}});return t.ok?{valid:!0,msg:"OpenRouter connected — available model: claude-sonnet-4.6"}:{valid:!1,msg:`OpenRouter returned ${t.status}`}}catch(e){return{valid:!1,msg:`Connection failed: ${e.message}`}}}async function x(){try{const e=await(0,c.getPositions)();return null===e?{valid:!1,msg:"Kalshi authentication failed",posCount:0}:{valid:!0,msg:`Kalshi authenticated — found ${e.length} position(s)`,posCount:e.length}}catch(e){return{valid:!1,msg:`Kalshi connection failed: ${e.message}`,posCount:0}}}async function C(e){try{const t=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:e,query:"test",max_results:1})});return t.ok?{valid:!0,msg:"Tavily connected"}:{valid:!1,msg:`Tavily returned ${t.status}`}}catch(e){return{valid:!1,msg:`Connection failed: ${e.message}`}}}async function O(e){for(y(`Don't have a key? Sign up at ${m("https://simplefunctions.dev/dashboard")}.`),y("Press Enter to open browser, or paste your key:"),$();;){const t=await w(" > ");if(!t){b("https://simplefunctions.dev/dashboard"),y(p("Browser opened. Paste your key here once you have it:"));continue}y(p("Validating..."));const n=await _(t,e);if(n.valid)return g(n.msg),$(),t;f(n.msg)}}async function I(){y(`Requires an OpenRouter API key. Get one at ${m("https://openrouter.ai/settings/keys")}.`),y("Press Enter to skip (agent unavailable), or paste key:"),$();const e=await w(" > ");if(!e)return y(p("Skipped.")),void $();y(p("Validating..."));const t=await S(e);return t.valid?g(t.msg):(f(t.msg),y(p("Saved. You can re-run sf setup later to fix this."))),$(),e}async function P(e){y("Connect Kalshi to view your positions and P&L."),y("Requires an API Key ID and private key file."),y(`Get them at ${m("https://kalshi.com/account/api-keys")}.`),y("Press Enter to skip, or paste Key ID:"),$();const t=await w(" > ");if(!t)return y(p("Skipped.")),void $();y("Private key file path (default ~/.kalshi/private.pem):");const n=await w(" > ")||"~/.kalshi/private.pem";e.kalshiKeyId=t,e.kalshiPrivateKeyPath=n,process.env.KALSHI_API_KEY_ID=t,process.env.KALSHI_PRIVATE_KEY_PATH=n,y(p("Validating..."));const o=await x();o.valid?g(o.msg):(f(o.msg),y(p("Saved. You can re-run sf setup later to fix this."))),$()}async function T(){y("Tavily API powers the agent's web_search tool."),y(`Get a free key at ${m("https://tavily.com")}.`),y("Press Enter to skip:"),$();const e=await w(" > ");if(!e)return y(p("Skipped.")),void $();y(p("Validating..."));const t=await C(e);return t.valid?g(t.msg):(f(t.msg),y(p("Saved. You can re-run sf setup later to fix this."))),$(),e}async function E(e){y("Connect Polymarket to view positions and scan orderbooks."),y("Your Polygon wallet address is needed (starts with 0x...)."),y(`Find it at ${m("https://polymarket.com")} → Settings → Profile.`),y("Press Enter to skip:"),$();const t=await w(" Wallet address > ");if(!t)return y(p("Skipped.")),void $();!t.startsWith("0x")||t.length<40?(f("Invalid wallet address (must start with 0x and be 42 characters)"),y(p("Saved anyway. You can fix it later with sf setup."))):g(`Wallet: ${v(t)}`),e.polymarketWalletAddress=t,y(p("Private key (for future trading) — press Enter to skip:"));const n=await w(" Key path > ");n&&(e.polymarketPrivateKeyPath=n,g(`Private key path: ${p(n)}`)),$()}async function A(e){try{const t=new a.SFClient(e.apiKey,e.apiUrl),n=await t.listTheses(),o=(n.theses||[]).filter(e=>"active"===e.status);if(o.length>0){console.log(` ${h("Step 7: Theses")}`),$(),g(`Found ${o.length} active thesis(es):`);for(const e of o.slice(0,5)){const t="number"==typeof e.confidence?Math.round(100*e.confidence):0,n=(e.rawThesis||e.thesis||e.title||"").slice(0,60);y(` ${p(e.id.slice(0,8))} — ${n} — ${t}%`)}if(y(p("Skipping creation.")),$(),e.openrouterKey){console.log(` ${p("─".repeat(25))}`),console.log(` ${h("All set!")}`),$(),y(` ${m("sf agent")} Chat with your thesis`),y(` ${m("sf context <id>")} View thesis snapshot`),y(` ${m("sf positions")} View positions`),y(` ${m("sf setup --check")} Check config`),$();await k(" Launch agent now? (Y/n) ")&&($(),y("Launching..."),$(),await(0,l.agentCommand)(o[0].id,{model:e.model}))}else $(),console.log(` ${h("All set!")}`),$(),y(` ${m("sf list")} List all theses`),y(` ${m("sf context <id>")} View thesis snapshot`),y(` ${m("sf positions")} View positions`),y(` ${m("sf setup --check")} Check config`),$();return}console.log(` ${h("Step 7: Create Your First Thesis")}`),$(),y("A thesis is your core market conviction. The system builds a causal model"),y("from it, then continuously scans prediction markets for mispriced contracts."),$(),y("Examples:"),y(` ${p('"The Fed won\'t cut rates in 2026 — inflation stays elevated due to oil prices"')}`),y(` ${p('"AI-driven layoffs cause consumer spending to contract, S&P drops 20% by year-end"')}`),y(` ${p('"Trump can\'t exit the Iran conflict — oil stays above $100 for six months"')}`),$();const s=await w(" Enter your thesis (press Enter to skip, use sf create later):\n > ");if(!s)return $(),y(p('Skipped. Use sf create "your thesis" to create one later.')),$(),void M(e);$(),y("Building causal model... (~30s)"),$();try{const n=await t.createThesis(s,!0);if(n.id){const t=n.causalTree?.nodes?.length||0,o=n.edgeAnalysis?.edges?.length||0,s=n.edgeAnalysis?.totalMarketsAnalyzed||0,i=Math.round(100*(parseFloat(n.confidence)||.5));if(g(`Causal tree: ${t} node(s)`),g(`Scanned ${s} markets, found ${o} contract(s) with edge`),g(`Confidence: ${i}%`),g(`Thesis ID: ${n.id.slice(0,8)}`),$(),e.openrouterKey){console.log(` ${p("─".repeat(25))}`),console.log(` ${h("All set!")}`),$();await k(" Launch agent now? (Y/n) ")?($(),y("Launching..."),$(),await(0,l.agentCommand)(n.id,{model:e.model})):($(),M(e))}else M(e)}else f(`Creation failed: ${n.error||"unknown error"}`),y(p('You can retry later with sf create "your thesis"')),$(),M(e)}catch(t){f(`Creation failed: ${t.message}`),y(p('You can retry later with sf create "your thesis"')),$(),M(e)}}catch{$(),M(e)}}function M(e){console.log(` ${p("─".repeat(25))}`),console.log(` ${h("All set!")}`),$(),y(` ${m("sf agent")} Chat with your thesis`),y(` ${m("sf list")} List all theses`),y(` ${m("sf context <id>")} View thesis snapshot`),y(` ${m("sf positions")} View positions`),y(` ${m("sf setup --check")} Check config`),$()}},67378:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.signalCommand=async function(e,t,n){const i=new o.SFClient(n.apiKey,n.apiUrl),r=n.type||"user_note",a=await i.injectSignal(e,r,t,"cli");if(n.json)return void console.log(JSON.stringify({signalId:a.signalId||null,type:r,source:"cli",content:t},null,2));console.log(`${s.c.green}✓${s.c.reset} Signal injected`),console.log(` ${s.c.bold}Type:${s.c.reset} ${r}`),console.log(` ${s.c.bold}Source:${s.c.reset} cli`),console.log(` ${s.c.bold}Content:${s.c.reset} ${t}`),a.signalId&&console.log(` ${s.c.bold}ID:${s.c.reset} ${a.signalId}`);const c=new Date,l=c.getMinutes(),d=15*Math.ceil((l+1)/15),u=d-l,p=new Date(c);p.setMinutes(d%60,0,0),d>=60&&p.setHours(p.getHours()+1);const h=p.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(`\n${s.c.dim}Signal queued. Next monitor cycle in ~${u}min (${h}).${s.c.reset}`),console.log(`${s.c.dim}Or run ${s.c.reset}sf evaluate ${e}${s.c.dim} to consume immediately.${s.c.reset}`)};const o=n(19218),s=n(99236)},72124:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statusCommand=async function(e){const t=[],n=Date.now();try{const e=await fetch(`${r}/api`,{signal:AbortSignal.timeout(5e3)});t.push({name:"API",status:e.ok?"ok":"fail",detail:e.ok?r.replace("https://",""):`HTTP ${e.status}`,ms:Date.now()-n})}catch(e){t.push({name:"API",status:"fail",detail:e.message?.slice(0,40)||"unreachable",ms:Date.now()-n})}const a=(0,i.loadConfig)();if((0,i.isConfigured)()){const n=Date.now();try{const e=await fetch(`${r}/api/thesis`,{headers:{Authorization:`Bearer ${a.apiKey}`},signal:AbortSignal.timeout(5e3)}),o=(a.apiKey||"").slice(0,12)+"...";t.push({name:"Auth",status:e.ok?"ok":"fail",detail:e.ok?o:`HTTP ${e.status}`,ms:Date.now()-n})}catch(e){t.push({name:"Auth",status:"fail",detail:e.message?.slice(0,40)||"failed"})}}else t.push({name:"Auth",status:"skip",detail:"not configured (sf login)"});if((0,s.isKalshiConfigured)()){const n=Date.now();try{const e=await(0,s.getBalance)();t.push({name:"Kalshi",status:e?"ok":"fail",detail:e?`$${e.balance.toFixed(2)} balance`:"auth failed",ms:Date.now()-n})}catch(e){t.push({name:"Kalshi",status:"fail",detail:e.message?.slice(0,40)||"failed"})}}else t.push({name:"Kalshi",status:"skip",detail:"not configured (sf setup --kalshi)"});a.polymarketWalletAddress?t.push({name:"Polymarket",status:"ok",detail:a.polymarketWalletAddress.slice(0,10)+"..."}):t.push({name:"Polymarket",status:"skip",detail:"not configured (sf setup --polymarket)"});if((0,i.isConfigured)())try{const e=await fetch(`${r}/api/thesis`,{headers:{Authorization:`Bearer ${a.apiKey}`},signal:AbortSignal.timeout(5e3)});if(e.ok){const n=(await e.json()).theses||[],o=n.filter(e=>"active"===e.status).length,s=n.length;t.push({name:"Theses",status:"ok",detail:`${o} active, ${s} total`})}}catch{}const c=a.tradingEnabled;if(t.push({name:"Trading",status:c?"ok":"skip",detail:c?"enabled":"disabled (sf setup --enable-trading)"}),e?.json)return void console.log(JSON.stringify({checks:t,timestamp:(new Date).toISOString()},null,2));console.log();for(const e of t){const t="ok"===e.status?`${o.c.green}ok${o.c.reset}`:"fail"===e.status?`${o.c.red}!!${o.c.reset}`:`${o.c.dim}--${o.c.reset}`,n=e.ms?` ${o.c.dim}${e.ms}ms${o.c.reset}`:"";console.log(` ${e.name.padEnd(14)} ${t} ${e.detail}${n}`)}console.log()};const o=n(99236),s=n(96139),i=n(11627),r=process.env.SF_API_URL||"https://simplefunctions.dev"},40239:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.registerStrategies=function(e){e.command("strategies").argument("[thesisId]","thesis ID or prefix (omit for all theses)").option("--status <status>","filter by status (active|watching|executed|cancelled|review)").option("--all","show all statuses (default: active only)").description("List strategies across theses").action(async(e,t)=>{try{const n=new o.SFClient;if(e){const o=(await n.getStrategies(e,t?.all?void 0:t?.status||"active")).strategies||[];if(0===o.length)return console.log(`\n No strategies found for thesis ${e}`),t?.all||t?.status||console.log(` ${r}Try --all to see all statuses${i}`),void console.log();console.log(`\n Strategies for ${e}\n`);for(const e of o)console.log(c(e)),console.log()}else{const{theses:e}=await n.listTheses();let o=0;for(const s of e){const e=t?.all?void 0:t?.status||"active",l=(await n.getStrategies(s.id,e)).strategies||[];if(0!==l.length){o+=l.length,console.log(`\n ${a}${s.title}${i} ${r}(${s.id.slice(0,8)})${i}\n`);for(const e of l)console.log(c(e)),console.log()}}0===o&&(console.log("\n No strategies found"),t?.all||t?.status||console.log(` ${r}Try --all to see all statuses${i}`),console.log())}}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}})};const o=n(19218),s={active:"",watching:"",executed:"",cancelled:"",review:""},i="",r="",a="";function c(e,t=!1){const n=s[e.status]||"",o=[],c=t?`${r}${e.thesisTitle||e.thesisId?.slice(0,8)}${i} `:"";o.push(` ${c}${n}[${e.status}]${i} ${a}${e.marketId}${i} ${e.direction.toUpperCase()} ${r}${e.horizon}${i} priority ${e.priority||0}`);const l=[];null!=e.entryBelow&&l.push(`ask ≤ ${e.entryBelow}¢`),null!=e.entryAbove&&l.push(`ask ≥ ${e.entryAbove}¢`);const d=null!=e.stopLoss?`Stop: ${e.stopLoss}¢`:"",u=null!=e.takeProfit?`TP: ${e.takeProfit}¢`:"",p=`Max: ${e.maxQuantity||500}`,h=`Filled: ${e.executedQuantity||0}/${e.maxQuantity||500}`,m=[l.length>0?`Entry: ${l.join(", ")}`:null,d||null,u||null,p,h].filter(Boolean).join(" | ");if(o.push(` ${m}`),e.softConditions&&o.push(` ${r}Soft: ${e.softConditions}${i}`),"review"===e.status&&o.push(` ⚠️ Needs review${i}`),e.rationale){const t=e.rationale.length>120?e.rationale.slice(0,117)+"...":e.rationale;o.push(` ${r}${t}${i}`)}const g=e.createdBy||"user",f=e.createdAt?new Date(e.createdAt).toLocaleDateString("en-US",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}):"";return o.push(` ${r}created by ${g} · ${f}${i}`),o.join("\n")}},91993:function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.telegramCommand=async function(e){if(e.stop){const e=u();if(e){process.kill(e,"SIGTERM");try{i.default.unlinkSync(l)}catch{}console.log(` Telegram bot stopped (PID ${e})`)}else console.log(" No running Telegram bot found.");return}if(e.status){const e=u();return void(e?(console.log(` Telegram bot running (PID ${e})`),console.log(` Log: ${d}`)):console.log(" Telegram bot not running."))}const t=function(e){const t=(0,c.loadConfig)();if(e){const t=(0,c.loadFileConfig)();return t.telegramBotToken!==e&&(0,c.saveConfig)({...t,telegramBotToken:e}),e}return t.telegramBotToken||null}(e.token);if(!t)return console.log(" No Telegram bot token configured.\n"),console.log(" Setup:"),console.log(" 1. Message @BotFather on Telegram → /newbot"),console.log(" 2. Copy the token"),console.log(" 3. Run: sf telegram --token YOUR_TOKEN\n"),void console.log(" The token will be saved to ~/.sf/config.json for future use.");if(e.daemon){const t=u();if(t)return void console.log(` Bot already running (PID ${t}). Use --stop first.`);const n=["telegram"];e.chatId&&n.push("--chat-id",e.chatId);const o=process.argv[1];i.default.mkdirSync(r.default.dirname(l),{recursive:!0});const a=i.default.openSync(d,"a"),c=(0,s.spawn)(process.execPath,[o,...n],{detached:!0,stdio:["ignore",a,a],env:{...process.env}});return c.unref(),i.default.writeFileSync(l,String(c.pid)),console.log(` Telegram bot started in background (PID ${c.pid})`),console.log(` Log: ${d}`),void console.log(" Stop: sf telegram --stop")}const{startBot:o}=await Promise.all([n.e(830),n.e(278),n.e(12)]).then(n.bind(n,6012));await o({token:t,chatId:e.chatId?parseInt(e.chatId):void 0})};const s=n(35317),i=o(n(79896)),r=o(n(16928)),a=o(n(70857)),c=n(11627),l=r.default.join(a.default.homedir(),".sf","telegram.pid"),d=r.default.join(a.default.homedir(),".sf","telegram.log");function u(){try{const e=parseInt(i.default.readFileSync(l,"utf-8").trim());if(isNaN(e))return null;try{return process.kill(e,0),e}catch{return null}}catch{return null}}},34362:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buyCommand=async function(e,t,n){(0,s.requireTrading)(),await l(e,t,"buy",n)},t.sellCommand=async function(e,t,n){(0,s.requireTrading)(),await l(e,t,"sell",n)};const o=n(96139),s=n(11627),i=n(99236),r=n(79896),a=n(16928),c=n(70857);async function l(e,t,n,s){const l=parseInt(t);if(isNaN(l)||l<=0)throw new Error("Quantity must be a positive integer");const d=s.side||"yes";if(!s.market&&!s.price)throw new Error("Limit order requires --price <cents>. Example: sf buy TICKER 10 --price 45\nFor market orders use: sf buy TICKER 10 --market --price 99");const u=s.market?"market":"limit";let p=s.price?parseInt(s.price):void 0;if(s.market&&!p){console.log(`${i.c.dim}Fetching current market price for ${e}...${i.c.reset}`);const t=await(0,o.getMarketPrice)(e.toUpperCase());if(!t)throw new Error(`Could not fetch market price for ${e}. Use --price <cents> to set manually.`);p=t,console.log(`${i.c.dim}Using market price: ${t}¢${i.c.reset}`)}if(void 0!==p&&(p<1||p>99))throw new Error("Price must be 1-99 cents.");const h=((p||99)*l/100).toFixed(2);if(console.log(),console.log(` ${i.c.bold}${i.c.cyan}${n.toUpperCase()} Order${i.c.reset}`),console.log(` ${i.c.dim}${"─".repeat(35)}${i.c.reset}`),console.log(` Ticker: ${e}`),console.log(" Side: "+("yes"===d?i.c.green+"YES"+i.c.reset:i.c.red+"NO"+i.c.reset)),console.log(` Quantity: ${l}`),console.log(` Type: ${u}`),p&&console.log(` Price: ${p}¢`),console.log(` Max cost: $${h}`),console.log(),!s.yesIAmSure){for(let e=3;e>0;e--)process.stdout.write(` Executing in ${e}... (Ctrl+C to cancel)\r`),await new Promise(e=>setTimeout(e,1e3));process.stdout.write(" Executing... \n")}try{const t=await(0,o.createOrder)({ticker:e,side:d,action:n,type:u,count:l,...p?{yes_price:p}:{}}),s=t.order||t;console.log(),console.log(` ${i.c.green}✓${i.c.reset} Order placed: ${s.order_id||"OK"}`),s.status&&console.log(` Status: ${s.status}`),s.fill_count_fp&&console.log(` Filled: ${s.fill_count_fp}/${s.initial_count_fp||l}`),console.log();try{const t=(0,a.join)((0,c.homedir)(),".sf");(0,r.existsSync)(t)||(0,r.mkdirSync)(t,{recursive:!0});const o=JSON.stringify({ts:(new Date).toISOString(),action:n,ticker:e,side:d,quantity:l,price:p||null,type:u,orderId:s.order_id||null,status:s.status||null,filled:s.fill_count_fp||null})+"\n";(0,r.appendFileSync)((0,a.join)(t,"trade-journal.jsonl"),o),console.log(` ${i.c.dim}Trade logged to ~/.sf/trade-journal.jsonl${i.c.reset}`)}catch{}}catch(e){const t=e.message||String(e);t.includes("403")?(console.error(`\n ${i.c.red}✗${i.c.reset} 403 Forbidden — your Kalshi key lacks write permission.`),console.error(" Get a read+write key at https://kalshi.com/account/api-keys\n")):console.error(`\n ${i.c.red}✗${i.c.reset} ${t}\n`),process.exit(1)}}},96007:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.watchCommand=async function(e,t,n){const s=function(e){if(!e)return"price";const t=e.toLowerCase();return"orderbook"===t||"ob"===t?"orderbook":"flow"===t?"flow":"cross-venue"===t||"xv"===t||"cross"===t?"cross-venue":"all"===t?"all":"price"}(t),i=parseInt(n.interval||("orderbook"===s?"30":"60")),a=1e3*i,h=n.json||!1;if(!h){const t="price"===s?"":` [${s}]`;console.log(),console.log(` ${o.c.bold}sf watch${o.c.reset}${e?` "${e}"`:""}${t}`),console.log(` ${o.c.dim}Polling every ${i}s · Ctrl+C to stop${o.c.reset}`),console.log()}switch(process.on("SIGINT",()=>{h||console.log(`\n ${o.c.dim}Watch stopped.${o.c.reset}\n`),process.exit(0)}),s){case"orderbook":await r(e,a,h);break;case"flow":await async function(e,t,n){let s=new Date(Date.now()-72e5).toISOString();const i=new Map;for(;;){try{const t=await l(s,e);for(const e of t){if("price_move"!==e.changeType)continue;let t=i.get(e.ticker);t||(t={ticker:e.ticker,recentDeltas:[],lastPrice:e.afterPrice||0},i.set(e.ticker,t)),t.recentDeltas.push(e.delta||0),t.recentDeltas.length>10&&t.recentDeltas.shift(),t.lastPrice=e.afterPrice||t.lastPrice;const s=t.recentDeltas.slice(-3);if(s.length>=3){const t=s.every(e=>e>0),i=s.every(e=>e<0);if(t||i){const i=s.reduce((e,t)=>e+Math.abs(t),0),r=t?"UP":"DOWN",a=t?o.c.green:o.c.red;n?console.log(JSON.stringify({type:"momentum",ticker:e.ticker,direction:r,totalDelta:i,moves:s.length})):console.log(` ${u()} ${a}MOMENTUM${o.c.reset} ${e.ticker} ${s.length} consecutive ${r} (${s.map(e=>`${e>0?"+":""}${e}c`).join(", ")}) total ${i}c`)}}if(t.recentDeltas.length>=2){const s=t.recentDeltas[t.recentDeltas.length-2],i=t.recentDeltas[t.recentDeltas.length-1];s&&i&&Math.sign(s)!==Math.sign(i)&&Math.abs(i)>=5&&(n?console.log(JSON.stringify({type:"reversal",ticker:e.ticker,previousDelta:s,currentDelta:i})):console.log(` ${u()} ${o.c.yellow}REVERSAL${o.c.reset} ${e.ticker} was ${s>0?"+":""}${s}c, now ${i>0?"+":""}${i}c`))}}t.length>0?s=t[0].detectedAt:n||process.stdout.write(` ${o.c.dim}${u()} · monitoring flow${o.c.reset}\r`)}catch(e){n||console.error(` ${o.c.dim}${u()} Error: ${e.message}${o.c.reset}`)}await p(t)}}(e,a,h);break;case"cross-venue":await async function(e,t,n){n||console.log(` ${o.c.dim}Fetching cross-venue data from scan...${o.c.reset}`);let s=new Date(Date.now()-72e5).toISOString();const i=new Map;for(;;){try{const t=await l(s,e);for(const e of t){if("price_move"!==e.changeType)continue;const t=e.title.toLowerCase().slice(0,50);let s=i.get(t);if(s||(s={kalshi:0,poly:0}),"kalshi"===e.venue?s.kalshi=e.afterPrice||0:"polymarket"===e.venue&&(s.poly=e.afterPrice||0),i.set(t,s),s.kalshi>0&&s.poly>0){const t=Math.abs(s.kalshi-s.poly),i=s.kalshi>s.poly?"Kalshi":"Poly";if(t>=2)if(n)console.log(JSON.stringify({type:"cross_venue",title:e.title,kalshi:s.kalshi,poly:s.poly,gap:t,higher:i}));else{const n=t>=5?o.c.green:o.c.yellow;console.log(` ${u()} ${n}SPREAD${o.c.reset} ${e.title.slice(0,45)} K:${s.kalshi}c P:${s.poly}c gap ${t}c (${i} higher)`)}}}t.length>0?s=t[0].detectedAt:n||process.stdout.write(` ${o.c.dim}${u()} · tracking cross-venue${o.c.reset}\r`)}catch(e){n||console.error(` ${o.c.dim}${u()} Error: ${e.message}${o.c.reset}`)}await p(t)}}(e,a,h);break;case"all":await async function(e,t,n){let s=new Date(Date.now()-36e5).toISOString();const i=new Map,r=new Map;for(;;){try{const t=await l(s,e);for(const e of t){if(n?console.log(JSON.stringify(e)):d(e),"price_move"!==e.changeType)continue;let t=i.get(e.ticker);t||(t={ticker:e.ticker,recentDeltas:[],lastPrice:e.afterPrice||0},i.set(e.ticker,t)),t.recentDeltas.push(e.delta||0),t.recentDeltas.length>10&&t.recentDeltas.shift();const s=t.recentDeltas.slice(-3);if(s.length>=3&&(s.every(e=>e>0)||s.every(e=>e<0))){const e=s.every(e=>e>0)?"UP":"DOWN",t=s.reduce((e,t)=>e+Math.abs(t),0);if(!n){const n="UP"===e?o.c.green:o.c.red;console.log(` ${n}^^ MOMENTUM${o.c.reset} ${s.length}x ${e} (${t}c total)`)}}const a=e.title.toLowerCase().slice(0,50);let c=r.get(a)||{kalshi:0,poly:0};if("kalshi"===e.venue?c.kalshi=e.afterPrice||0:"polymarket"===e.venue&&(c.poly=e.afterPrice||0),r.set(a,c),c.kalshi>0&&c.poly>0){const e=Math.abs(c.kalshi-c.poly);e>=3&&!n&&console.log(` ${o.c.yellow}^^ CROSS-VENUE${o.c.reset} gap ${e}c K:${c.kalshi}c vs P:${c.poly}c`)}}t.length>0?s=t[0].detectedAt:n||process.stdout.write(` ${o.c.dim}${u()} · watching all${o.c.reset}\r`)}catch(e){n||console.error(` ${o.c.dim}${u()} Error: ${e.message}${o.c.reset}`)}await p(t)}}(e,a,h);break;default:await async function(e,t,n){let s=(new Date).toISOString();try{const t=new Date(Date.now()-36e5).toISOString(),i=await l(t,e);if(i.length>0){n||console.log(` ${o.c.dim}${u()} Recent changes (last hour):${o.c.reset}`);const e=c(i);for(const t of e)n?console.log(JSON.stringify(t)):d(t);s=i[0].detectedAt}else n||console.log(` ${o.c.dim}${u()} No recent changes. Watching...${o.c.reset}`)}catch(e){n||console.error(` ${o.c.dim}${u()} Error: ${e.message}${o.c.reset}`)}for(;;){await p(t);try{const t=await l(s,e),i=n?t:c(t);for(const e of i)n?console.log(JSON.stringify(e)):d(e);t.length>0?s=t[0].detectedAt:n||process.stdout.write(` ${o.c.dim}${u()} · no new changes${o.c.reset}\r`)}catch(e){n||console.error(` ${o.c.dim}${u()} Error: ${e.message}${o.c.reset}`)}}}(e,a,h)}};const o=n(99236),s=n(96139),i=process.env.SF_API_URL||"https://simplefunctions.dev";async function r(e,t,n){e||(console.error(` ${o.c.red}Error:${o.c.reset} orderbook mode requires a query. Example: sf watch "fed" orderbook`),process.exit(1));const i=await a(e);0===i.length&&(console.error(` ${o.c.dim}No Kalshi markets found for "${e}"${o.c.reset}`),process.exit(1)),n||(console.log(` ${o.c.dim}Tracking ${i.length} market(s)${o.c.reset}`),console.log());let r=new Map;for(;;){for(const{ticker:e,title:t}of i)try{const i=await(0,s.getPublicOrderbook)(e,10);if(!i)continue;const a=i.yes_dollars||[],c=i.no_dollars||[],l=a.length>0?Math.round(100*parseFloat(a[0][0])):0,d=c.length>0?100-Math.round(100*parseFloat(c[0][0])):100,p=d-l,h=a.slice(0,3).reduce((e,t)=>e+parseFloat(t[1]),0),m=c.slice(0,3).reduce((e,t)=>e+parseFloat(t[1]),0),g={ticker:e,title:t,bestBid:l,bestAsk:d,spread:p,bidDepth:h,askDepth:m},f=r.get(e);if(n)console.log(JSON.stringify({type:"orderbook",ts:(new Date).toISOString(),...g}));else{const t=p<=2?`${o.c.green}HIGH${o.c.reset}`:p<=5?`${o.c.yellow}MED${o.c.reset}`:`${o.c.red}LOW${o.c.reset}`;let n="";if(f){const e=h-f.bidDepth,t=m-f.askDepth;if(Math.abs(e)>50||Math.abs(t)>50){const s=e>0?"+":"",i=t>0?"+":"";n=` ${o.c.dim}depth: bids ${s}${Math.round(e)}, asks ${i}${Math.round(t)}${o.c.reset}`}}console.log(` ${u()} ${o.c.bold}${e.slice(0,30)}${o.c.reset} bid ${l}c (${Math.round(h)}) | ask ${d}c (${Math.round(m)}) spread ${p}c [${t}]${n}`)}r.set(e,g)}catch{}await p(t)}}async function a(e){try{const t=await fetch(`${i}/api/public/scan?q=${encodeURIComponent(e)}&limit=20`);if(!t.ok)return[];const n=await t.json();return(n.results||n.markets||[]).filter(e=>e.ticker&&"kalshi"===e.venue).slice(0,5).map(e=>({ticker:e.ticker,title:e.title||e.ticker}))}catch{return[]}}function c(e){const t=new Map;for(const n of e){const e=`${n.changeType}:${n.title}`,o=t.get(e);o?o.count++:t.set(e,{count:1,representative:n})}return Array.from(t.values()).map(({count:e,representative:t})=>e>1?{...t,title:`${t.title} (${e} contracts)`}:t)}async function l(e,t){let n=`${i}/api/changes?since=${encodeURIComponent(e)}&limit=50`;t&&(n+=`&q=${encodeURIComponent(t)}`);const o=await fetch(n);if(!o.ok)return[];return(await o.json()).changes||[]}function d(e){const t=u(),n="kalshi"===e.venue?`${o.c.cyan}K${o.c.reset}`:"polymarket"===e.venue?"P":"traditional"===e.venue?`${o.c.dim}$${o.c.reset}`:"·";switch(e.changeType){case"new_contract":console.log(` ${t} ${n} ${o.c.green}+ NEW${o.c.reset} ${e.afterPrice}c ${e.title}`);break;case"removed_contract":console.log(` ${t} ${n} ${o.c.red}- GONE${o.c.reset} ${e.title}`);break;case"price_move":if("traditional"===e.venue){const s=(e.delta||0)>0?"+":"",i=(e.delta||0)>0?o.c.green:o.c.red,r=((e.beforePrice||0)/100).toFixed(0),a=((e.afterPrice||0)/100).toFixed(0);console.log(` ${t} ${n} ${i}${s}${e.delta}c${o.c.reset} $${r}→$${a} ${e.title}`)}else{const s=(e.delta||0)>0?"+":"",i=(e.delta||0)>0?o.c.green:o.c.red;console.log(` ${t} ${n} ${i}${s}${e.delta}c${o.c.reset} ${e.beforePrice}→${e.afterPrice}c ${e.title}`)}}}function u(){return(new Date).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}function p(e){return new Promise(t=>setTimeout(t,e))}},18691:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whatifCommand=async function(e,t){if(!t.set||0===t.set.length)throw new Error('Usage: sf whatif <thesisId> --set "n1=0.1" [--set "n3=0.5"]');const n=t.set.map(e=>{const[t,n]=e.split("=");if(!t||!n)throw new Error(`Invalid override: "${e}". Format: nodeId=probability`);const o=parseFloat(n);if(isNaN(o)||o<0||o>1)throw new Error(`Invalid probability: "${n}". Must be 0-1.`);return{nodeId:t.trim(),newProbability:o}}),r=new o.SFClient(t.apiKey,t.apiUrl),a=await r.getContext(e),c=function(e,t){const n=[];function o(e){for(const t of e)n.push(t),t.children?.length&&o(t.children)}const s=e.causalTree?.nodes||[];o(s);const i=s.filter(e=>0===e.depth||void 0===e.depth&&!e.id.includes(".")),r=new Map(t.map(e=>[e.nodeId,e.newProbability])),a=t.map(e=>{const t=n.find(t=>t.id===e.nodeId);return{nodeId:e.nodeId,oldProb:t?.probability??0,newProb:e.newProbability,label:t?.label||e.nodeId}}),c=i.reduce((e,t)=>e+(t.probability||0)*(t.importance||0),0),l=i.reduce((e,t)=>e+(r.get(t.id)??t.probability??0)*(t.importance||0),0),d=new Map;for(const[e,t]of r.entries()){const o=n.find(t=>t.id===e);o&&o.probability>0&&d.set(e,Math.max(0,Math.min(2,t/o.probability)))}const u=(e.edges||[]).map(e=>{const t=e.relatedNodeId;let n=1;if(t){const e=[t,t.split(".").slice(0,-1).join("."),t.split(".")[0]].filter(Boolean);for(const t of e)if(d.has(t)){n=d.get(t);break}}const o=e.marketPrice||0,s=e.thesisPrice||e.thesisImpliedPrice||o,i=e.edge||e.edgeSize||0,r=s-o,a=Math.round(100*(o+r*n))/100,c=e.direction||"yes",l=Math.round(100*("yes"===c?a-o:o-a))/100,u=Math.round(100*(l-i))/100;let p="unchanged";return Math.abs(u)<1?p="unchanged":i>0&&l<0||i<0&&l>0?p="reversed":Math.abs(l)<2?p="gone":Math.abs(l)<Math.abs(i)&&(p="reduced"),{marketId:e.marketId,market:e.market||e.marketTitle||e.marketId,venue:e.venue,direction:c,marketPrice:o,oldThesisPrice:s,newThesisPrice:a,oldEdge:i,newEdge:l,delta:u,signal:p,relatedNodeId:t}});return u.sort((e,t)=>Math.abs(t.delta)-Math.abs(e.delta)),{overrides:a,oldConfidence:c,newConfidence:l,confidenceDelta:Math.round(100*(l-c))/100,edges:u}}(a,n);if(t.json)return void console.log(JSON.stringify(c,null,2));console.log(),console.log(`${i.c.bold}${i.c.cyan}WHAT-IF Scenario${i.c.reset}`),console.log(`${i.c.dim}${"─".repeat(65)}${i.c.reset}`);for(const e of c.overrides){const t=Math.round(100*e.oldProb),n=Math.round(100*e.newProb),o=n>t?i.c.green+"↑"+i.c.reset:i.c.red+"↓"+i.c.reset;console.log(` ${i.c.cyan}${e.nodeId}${i.c.reset} ${e.label.slice(0,40)}`),console.log(` ${t}% ${o} ${i.c.bold}${n}%${i.c.reset}`)}const l=Math.round(100*c.oldConfidence),d=Math.round(100*c.newConfidence),u=c.confidenceDelta>0?"+":"",p=c.confidenceDelta>=0?i.c.green:i.c.red;console.log(),console.log(` Confidence: ${l}% → ${p}${i.c.bold}${d}%${i.c.reset} (${p}${u}${Math.round(100*c.confidenceDelta)}${i.c.reset})`),console.log();const h=c.edges.filter(e=>"unchanged"!==e.signal);if(0===h.length)console.log(` ${i.c.dim}No edges affected.${i.c.reset}`);else{console.log(` ${i.c.bold}Edges Affected${i.c.reset}`),console.log(` ${"Market".padEnd(35)} ${"Now".padEnd(6)} ${"Edge".padEnd(8)} ${"→".padEnd(3)} ${"New Edge".padEnd(8)} Signal`),console.log(` ${i.c.dim}${"─".repeat(65)}${i.c.reset}`);for(const e of h){const t=(e.market||e.marketId).slice(0,33).padEnd(35),n=`${Math.round(e.marketPrice)}¢`.padEnd(6),o=`${e.oldEdge>0?"+":""}${Math.round(e.oldEdge)}`.padEnd(8),s=`${e.newEdge>0?"+":""}${Math.round(e.newEdge)}`.padEnd(8);let r;switch(e.signal){case"reversed":r=`${i.c.red}${i.c.bold}REVERSED${i.c.reset}`;break;case"gone":r=`${i.c.red}GONE${i.c.reset}`;break;case"reduced":r=`${i.c.dim}reduced${i.c.reset}`;break;default:r=`${i.c.dim}-${i.c.reset}`}console.log(` ${i.c.dim}${t}${i.c.reset} ${n} ${o} → ${s} ${r}`)}}try{const e=await(0,s.getPositions)();if(e&&e.length>0){const t=new Map(c.edges.map(e=>[e.marketId,e])),n=e.filter(e=>{const n=t.get(e.ticker);return n&&("reversed"===n.signal||"gone"===n.signal)});if(n.length>0){console.log(),console.log(` ${i.c.red}${i.c.bold}⚠ Positions at Risk${i.c.reset}`);for(const e of n){const n=t.get(e.ticker),o=await(0,s.getMarketPrice)(e.ticker),r=null!==o?((o-e.average_price_paid)*e.quantity/100).toFixed(2):"?";console.log(` ${i.c.red}${e.ticker}${i.c.reset} ${e.quantity} ${e.side} P&L $${r} edge ${n.oldEdge>0?"+":""}${Math.round(n.oldEdge)} → ${i.c.red}${n.newEdge>0?"+":""}${Math.round(n.newEdge)}${i.c.reset}`)}}}}catch{}console.log()};const o=n(19218),s=n(96139),i=n(99236)},33192:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.worldCommand=async function(e){const t=process.env.SF_API_URL||"https://simplefunctions.dev";if(e.delta){const n=e.since||"1h",s=await fetch(`${t}/api/agent/world/delta?since=${encodeURIComponent(n)}`);s.ok||(console.error(`\n ${o.c.red}Error:${o.c.reset} API returned ${s.status}\n`),process.exit(1));const i=await s.text();if(e.json)try{console.log(JSON.stringify(JSON.parse(i),null,2))}catch{console.log(i)}else console.log(),console.log(i),console.log();return}const n=e.focus?`?focus=${encodeURIComponent(e.focus)}`:"",s=await fetch(`${t}/api/agent/world${n}`);s.ok||(console.error(`\n ${o.c.red}Error:${o.c.reset} API returned ${s.status}\n`),process.exit(1));const i=await s.text();if(e.json)try{console.log(JSON.stringify(JSON.parse(i),null,2))}catch{console.log(i)}else console.log(),console.log(i),console.log()};const o=n(99236)},84436:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.xSearchCommand=async function(e,t){const n=t?.raw?"raw":"summary",o=t?.hours||"24",r=t?.limit||"20",a=await s(`/api/x/search?q=${encodeURIComponent(e)}&mode=${n}&hours=${o}&limit=${r}`);if(t?.json)return void console.log(JSON.stringify(a,null,2));if(a.summary){if(console.log(`\n X: ${e}\n`),console.log(` ${a.summary}\n`),a.sentiment){const e={bullish:"",bearish:"",mixed:"",neutral:""};console.log(` Sentiment: ${e[a.sentiment]||""}${a.sentiment}`)}a.keyThemes?.length&&console.log(` Themes: ${a.keyThemes.join(", ")}`),console.log()}const c=a.posts||[];if(c.length>0){console.log(` Top posts (${c.length})\n`);for(const e of c.slice(0,10)){const t=e.metrics?.likes||0,n=e.metrics?.retweets||0,o=e.authorFollowers?` (${i(e.authorFollowers)})`:"";console.log(` @${e.authorUsername}${o}`),console.log(` ${e.text.slice(0,140)}${e.text.length>140?"...":""}`),console.log(` ♥ ${t} ↻ ${n}\n`)}}if(a.volume){const e=a.volume,t=e.velocityChange>1?`+${Math.round(100*(e.velocityChange-1))}%`:`${Math.round(100*(e.velocityChange-1))}%`;console.log(` Volume: ${i(e.totalCount)} posts (${o}h) | Velocity: ${t} | Peak: ${e.peak?.count}\n`)}const l=a.news||[];if(l.length>0){console.log(` X News (${l.length})\n`);for(const e of l.slice(0,5)){const t=e.tickers?.length?` ${e.tickers.join(" ")}`:"";console.log(` ${e.title}${t}`),console.log(` ${e.summary.slice(0,120)}...\n`)}}},t.xVolumeCommand=async function(e,t){const n=t?.hours||"72",o=t?.granularity||"hour",r=await s(`/api/x/volume?q=${encodeURIComponent(e)}&hours=${n}&granularity=${o}`);if(t?.json)return void console.log(JSON.stringify(r,null,2));console.log(`\n X Volume: ${e}\n`),console.log(` Total: ${i(r.totalCount)} posts (${n}h)`);const a=r.velocityChange>1?`+${Math.round(100*(r.velocityChange-1))}%`:`${Math.round(100*(r.velocityChange-1))}%`;console.log(` Velocity: ${a}`),console.log(` Peak: ${r.peak?.count} at ${r.peak?.time?.slice(11,16)||"?"}\n`);const c=r.timeseries||[];if(c.length>0){const e=Math.max(...c.map(e=>e.count)),t=40;for(const n of c.slice(-24)){const o=(n.time||"").slice(11,16)||"?",s=e>0?Math.round(n.count/e*t):0,i="▓".repeat(s),r=String(n.count).padStart(6);console.log(` ${o} ${r} ${i}`)}}console.log()},t.xNewsCommand=async function(e,t){const n=t?.limit||"10",o=await s(`/api/x/news?q=${encodeURIComponent(e)}&limit=${n}`);if(t?.json)return void console.log(JSON.stringify(o,null,2));const i=o.stories||[];console.log(`\n X News: ${e} (${i.length} stories)\n`);for(const e of i){const t=e.tickers?.length?` ${e.tickers.join(" ")}`:"",n=e.categories?.length?`[${e.categories.join(", ")}]`:"";console.log(` ${e.title}${t} ${n}`),console.log(` ${e.summary.slice(0,200)}${e.summary.length>200?"...":""}`),console.log()}},t.xAccountCommand=async function(e,t){const n=e.replace(/^@/,""),o=t?.hours||"24",i=t?.limit||"20",r=await s(`/api/x/account?username=${n}&hours=${o}&limit=${i}`);if(t?.json)return void console.log(JSON.stringify(r,null,2));const a=r.posts||[];console.log(`\n @${n} (${a.length} posts, last ${o}h)\n`);for(const e of a){const t=e.metrics?.likes||0,n=e.metrics?.retweets||0,o=e.createdAt?.slice(11,16)||"";console.log(` ${o} ${e.text.slice(0,140)}${e.text.length>140?"...":""}`),console.log(` ♥ ${t} ↻ ${n}\n`)}};const n=process.env.SF_API_URL||"https://simplefunctions.dev";function o(){const e=process.env.SF_API_KEY||"";return e||(console.error(" API key required. Run: sf setup"),process.exit(1)),e}async function s(e){const t=await fetch(`${n}${e}`,{headers:{Authorization:`Bearer ${o()}`}});if(!t.ok){const e=await t.text();throw new Error(`${t.status}: ${e}`)}return t.json()}function i(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}},11627:function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.loadFileConfig=u,t.loadConfig=p,t.saveConfig=function(e){s.default.mkdirSync(a,{recursive:!0}),s.default.writeFileSync(c,JSON.stringify({...e,configuredAt:(new Date).toISOString()},null,2))},t.resetConfig=function(){try{s.default.existsSync(c)&&s.default.unlinkSync(c)}catch{}},t.applyConfig=function(){const e=u();!process.env.SF_API_KEY&&e.apiKey&&(process.env.SF_API_KEY=e.apiKey);!process.env.SF_API_URL&&e.apiUrl&&(process.env.SF_API_URL=e.apiUrl);!process.env.OPENROUTER_API_KEY&&e.openrouterKey&&(process.env.OPENROUTER_API_KEY=e.openrouterKey);!process.env.KALSHI_API_KEY_ID&&e.kalshiKeyId&&(process.env.KALSHI_API_KEY_ID=e.kalshiKeyId);!process.env.KALSHI_PRIVATE_KEY_PATH&&e.kalshiPrivateKeyPath&&(process.env.KALSHI_PRIVATE_KEY_PATH=e.kalshiPrivateKeyPath);!process.env.POLYMARKET_WALLET_ADDRESS&&e.polymarketWalletAddress&&(process.env.POLYMARKET_WALLET_ADDRESS=e.polymarketWalletAddress);!process.env.POLYMARKET_PRIVATE_KEY_PATH&&e.polymarketPrivateKeyPath&&(process.env.POLYMARKET_PRIVATE_KEY_PATH=e.polymarketPrivateKeyPath);!process.env.TAVILY_API_KEY&&e.tavilyKey&&(process.env.TAVILY_API_KEY=e.tavilyKey);!process.env.SF_MODEL&&e.model&&(process.env.SF_MODEL=e.model)},t.isConfigured=function(){const e=p();return!!e.apiKey},t.requireTrading=function(){const e=p();e.tradingEnabled||(console.error("\n Trading is disabled. Run: sf setup --enable-trading\n"),process.exit(1));e.kalshiKeyId||process.env.KALSHI_API_KEY_ID||(console.error("\n Kalshi API key not configured. Run: sf setup --kalshi\n"),process.exit(1))},t.getConfigPath=function(){return c};const s=o(n(79896)),i=o(n(16928)),r=o(n(70857)),a=i.default.join(r.default.homedir(),".sf"),c=i.default.join(a,"config.json"),l="https://simplefunctions.dev",d="anthropic/claude-sonnet-4.6";function u(){try{if(s.default.existsSync(c))return JSON.parse(s.default.readFileSync(c,"utf-8"))}catch{}return{}}function p(){const e=u();return{apiKey:process.env.SF_API_KEY||e.apiKey,apiUrl:process.env.SF_API_URL||e.apiUrl||l,openrouterKey:process.env.OPENROUTER_API_KEY||e.openrouterKey,kalshiKeyId:process.env.KALSHI_API_KEY_ID||e.kalshiKeyId,kalshiPrivateKeyPath:process.env.KALSHI_PRIVATE_KEY_PATH||e.kalshiPrivateKeyPath,polymarketWalletAddress:process.env.POLYMARKET_WALLET_ADDRESS||e.polymarketWalletAddress,polymarketPrivateKeyPath:process.env.POLYMARKET_PRIVATE_KEY_PATH||e.polymarketPrivateKeyPath,tavilyKey:process.env.TAVILY_API_KEY||e.tavilyKey,model:process.env.SF_MODEL||e.model||d,tradingEnabled:e.tradingEnabled||!1,telegramBotToken:process.env.TELEGRAM_BOT_TOKEN||e.telegramBotToken}}},96139:function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isKalshiConfigured=c,t.getPositions=async function(){if(!c())return null;try{const e=await u("/portfolio/positions");return(e.market_positions||e.positions||[]).map(e=>{const t=parseFloat(e.position_fp||"0"),n=parseFloat(e.total_traded_dollars||"0"),o=Math.abs(t),s=t>=0?"yes":"no",i=o>0?Math.round(n/o*100):0;return{ticker:e.ticker||e.market_ticker||"",event_ticker:e.event_ticker||"",market_title:e.market_title||e.title||"",side:s,quantity:o,average_price_paid:i,current_value:0,realized_pnl:Math.round(100*parseFloat(e.realized_pnl||"0")),unrealized_pnl:0,total_cost:Math.round(100*n)}})}catch(e){return console.warn("[Kalshi] Failed to fetch positions:",e),null}},t.kalshiPriceCents=h,t.getMarketPrice=async function(e){try{const t=`https://api.elections.kalshi.com/trade-api/v2/markets/${e}`,n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)return null;const o=await n.json(),s=o.market||o,i=h(s);return 50!==i||s.last_price_dollars||s.yes_bid_dollars?i:null}catch{return null}},t.getOrderbook=async function(e){if(!c())return null;try{const t=await u(`/markets/${e}/orderbook`),n=t.orderbook_fp||t.orderbook;if(!n)return null;const o=n.yes_dollars||n.yes||[],s=n.no_dollars||n.no||[],i=!(!n.yes_dollars&&!n.no_dollars),r=o.map(e=>({price:i?Math.round(100*parseFloat(e[0])):Number(e[0]),qty:parseFloat(e[1])})).filter(e=>e.price>0),a=s.map(e=>({price:i?Math.round(100*parseFloat(e[0])):Number(e[0]),qty:parseFloat(e[1])})).filter(e=>e.price>0);r.sort((e,t)=>t.price-e.price),a.sort((e,t)=>t.price-e.price);const c=r.length>0?r[0].price:0,l=a.length>0?100-a[0].price:100,d=l-c,p=r.slice(0,3).reduce((e,t)=>e+t.qty,0),h=a.slice(0,3).reduce((e,t)=>e+t.qty,0),m=Math.min(p,h);let g="low";return d<=2&&m>=500?g="high":d<=5&&m>=100&&(g="medium"),{bestBid:c,bestAsk:l,spread:d,bidDepth:p,askDepth:h,liquidityScore:g}}catch{return null}},t.getPublicOrderbook=async function(e,t=20){try{const n=`${a}/markets/${e}/orderbook?depth=${t}`,o=await fetch(n,{headers:{Accept:"application/json"}});if(!o.ok)return null;const s=await o.json(),i=s.orderbook_fp||s.orderbook||s;return{yes_dollars:i.yes_dollars||i.yes||[],no_dollars:i.no_dollars||i.no||[]}}catch{return null}},t.getSettlements=async function(e){if(!c())return null;try{const t=new URLSearchParams;e?.limit&&t.set("limit",e.limit.toString()),e?.cursor&&t.set("cursor",e.cursor),e?.ticker&&t.set("ticker",e.ticker);const n=await u(`/portfolio/settlements?${t.toString()}`);return{settlements:n.settlements||[],cursor:n.cursor||""}}catch(e){return console.warn("[Kalshi] Failed to fetch settlements:",e),null}},t.getBalance=async function(){if(!c())return null;try{const e=await u("/portfolio/balance"),t=(e.balance||0)/100;return{balance:t,portfolioValue:(e.portfolio_value||0)/100}}catch(e){return console.warn("[Kalshi] Failed to fetch balance:",e),null}},t.getOrders=async function(e){if(!c())return null;try{const t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.ticker&&t.set("ticker",e.ticker),e?.limit&&t.set("limit",e.limit.toString()),e?.cursor&&t.set("cursor",e.cursor);const n=await u(`/portfolio/orders?${t.toString()}`);return{orders:n.orders||[],cursor:n.cursor||""}}catch(e){return console.warn("[Kalshi] Failed to fetch orders:",e),null}},t.getFills=async function(e){if(!c())return null;try{const t=new URLSearchParams;e?.ticker&&t.set("ticker",e.ticker),e?.limit&&t.set("limit",e.limit.toString()),e?.cursor&&t.set("cursor",e.cursor);const n=await u(`/portfolio/fills?${t.toString()}`);return{fills:n.fills||[],cursor:n.cursor||""}}catch(e){return console.warn("[Kalshi] Failed to fetch fills:",e),null}},t.getForecastHistory=async function(e){if(!c())return null;try{const t=new URLSearchParams;for(const n of e.percentiles)t.append("percentiles",n.toString());t.set("start_ts",e.startTs.toString());const n=Math.floor((new Date).setUTCHours(0,0,0,0)/1e3),o=Math.min(e.endTs,n);t.set("end_ts",o.toString()),t.set("period_interval",e.periodInterval.toString());const s=`/series/${e.seriesTicker}/events/${e.eventTicker}/forecast_percentile_history?${t.toString()}`;return(await u(s)).forecast_history||[]}catch(e){return console.warn("[Kalshi] Failed to fetch forecast:",e),null}},t.getExchangeAnnouncements=async function(){try{const e=await fetch(`${a}/exchange/announcements`,{headers:{Accept:"application/json"}});if(!e.ok)return[];return(await e.json()).announcements||[]}catch{return[]}},t.getHistoricalMarket=async function(e){try{const t=await fetch(`${a}/historical/markets/${e}`,{headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return n.market||n||null}catch{return null}},t.createOrder=async function(e){return p("/portfolio/orders",e)},t.cancelOrder=async function(e){await async function(e){const t=l();if(!t)throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.");const n=`${a}${e}`,o=e.split("?")[0],{headers:s}=d("DELETE",`/trade-api/v2${o}`,t),i=await fetch(n,{method:"DELETE",headers:s});if(!i.ok){const e=await i.text();throw new Error(`Kalshi API ${i.status}: ${e}`)}const r=i.headers.get("content-type");if(r?.includes("application/json"))return i.json();return{}}(`/portfolio/orders/${e}`)},t.batchCancelOrders=async function(e){await p("/portfolio/orders/batched",{orders:e.map(e=>({action:"cancel",order_id:e}))})},t.amendOrder=async function(e,t){const n=l();if(!n)throw new Error("Kalshi private key not loaded.");const o=`/portfolio/orders/${e}`,s=`${a}${o}`,{headers:i}=d("PATCH",`/trade-api/v2${o}`,n),r=await fetch(s,{method:"PATCH",headers:i,body:JSON.stringify(t)});if(!r.ok){const e=await r.text();throw new Error(`Kalshi API ${r.status}: ${e}`)}return r.json()},t.getBatchCandlesticks=async function(e){if(!c())return[];try{const t=new URLSearchParams;t.set("market_tickers",e.tickers.join(",")),t.set("start_ts",e.startTs.toString()),t.set("end_ts",e.endTs.toString()),t.set("period_interval",(e.periodInterval??1440).toString());return(await u(`/markets/candlesticks?${t.toString()}`)).markets||[]}catch(e){return console.warn("[Kalshi] Failed to fetch candlesticks:",e),[]}},t.createRFQ=async function(e){return p("/communications/rfqs",e)};const s=o(n(79896)),i=o(n(16928)),r=o(n(76982)),a="https://api.elections.kalshi.com/trade-api/v2";function c(){return!(!process.env.KALSHI_API_KEY_ID||!process.env.KALSHI_PRIVATE_KEY_PATH)}function l(){const e=process.env.KALSHI_PRIVATE_KEY_PATH;if(!e)return null;const t=e.startsWith("~")?i.default.join(process.env.HOME||"",e.slice(1)):i.default.resolve(e);try{const e=s.default.readFileSync(t,"utf-8");return r.default.createPrivateKey(e)}catch(e){return console.warn(`[Kalshi] Failed to load private key from ${t}:`,e),null}}function d(e,t,n){const o=process.env.KALSHI_API_KEY_ID,s=Date.now().toString(),i=s+e.toUpperCase()+t;return{headers:{"KALSHI-ACCESS-KEY":o,"KALSHI-ACCESS-SIGNATURE":r.default.sign("sha256",Buffer.from(i),{key:n,padding:r.default.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.default.constants.RSA_PSS_SALTLEN_DIGEST}).toString("base64"),"KALSHI-ACCESS-TIMESTAMP":s,"Content-Type":"application/json",Accept:"application/json"}}}async function u(e){const t=l();if(!t)throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.");const n=`${a}${e}`,o=e.split("?")[0],{headers:s}=d("GET",`/trade-api/v2${o}`,t),i=await fetch(n,{method:"GET",headers:s});if(!i.ok){const e=await i.text();throw new Error(`Kalshi API ${i.status}: ${e}`)}return i.json()}async function p(e,t){const n=l();if(!n)throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.");const o=`${a}${e}`,s=e.split("?")[0],{headers:i}=d("POST",`/trade-api/v2${s}`,n),r=await fetch(o,{method:"POST",headers:i,body:JSON.stringify(t)});if(!r.ok){const e=await r.text();throw new Error(`Kalshi API ${r.status}: ${e}`)}return r.json()}function h(e){if(e.last_price_dollars){const t=parseFloat(e.last_price_dollars);if(!isNaN(t)&&t>0)return Math.round(100*t)}if(e.yes_bid_dollars){const t=parseFloat(e.yes_bid_dollars);if(!isNaN(t)&&t>0)return Math.round(100*t)}if(e.yes_ask_dollars){const t=parseFloat(e.yes_ask_dollars);if(!isNaN(t)&&t>0)return Math.round(100*t)}return null!=e.last_price&&e.last_price>0?e.last_price:null!=e.yes_bid&&e.yes_bid>0?e.yes_bid:50}},34331:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.polymarketSearch=async function(e,t=20){const o=new URLSearchParams({q:e,limit_per_type:t.toString()}),s=await fetch(`${n}/public-search?${o}`);if(!s.ok)throw new Error(`Polymarket search error: ${s.status}`);const i=await s.json();return i.events||[]},t.polymarketListEvents=async function(e){const t=new URLSearchParams({active:"true",closed:"false",limit:(e?.limit||50).toString(),offset:(e?.offset||0).toString()});e?.order&&t.set("order",e.order);void 0!==e?.ascending&&t.set("ascending",String(e.ascending));e?.tag_id&&t.set("tag_id",e.tag_id);const o=await fetch(`${n}/events?${t}`);if(!o.ok)throw new Error(`Polymarket events error: ${o.status}`);return o.json()},t.polymarketGetEvent=async function(e){const t=await fetch(`${n}/events/${e}`);if(!t.ok)throw new Error(`Polymarket event error: ${t.status}`);return t.json()},t.polymarketGetMarket=async function(e){const t=await fetch(`${n}/markets/${e}`);if(!t.ok)throw new Error(`Polymarket market error: ${t.status}`);return t.json()},t.polymarketListTags=async function(){const e=await fetch(`${n}/tags`);if(!e.ok)throw new Error(`Polymarket tags error: ${e.status}`);return e.json()},t.polymarketGetOrderbook=i,t.computeOrderbookDepth=r,t.polymarketGetOrderbookWithDepth=async function(e){const t=await i(e);return t?r(t):null},t.polymarketGetMidpoint=async function(e){try{const t=await fetch(`${o}/midpoint?token_id=${e}`);if(!t.ok)return null;const n=await t.json();return n.mid?parseFloat(n.mid):null}catch{return null}},t.polymarketGetSpread=async function(e){try{const t=await fetch(`${o}/spread?token_id=${e}`);if(!t.ok)return null;const n=await t.json();return n.spread?parseFloat(n.spread):null}catch{return null}},t.polymarketGetMidpoints=async function(e){if(0===e.length)return{};const t=await fetch(`${o}/midpoints`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Polymarket midpoints error: ${t.status}`);return t.json()},t.polymarketGetOHLC=async function(e){const t=new URLSearchParams({asset_id:e.tokenId,startTs:e.startTs.toString(),fidelity:e.fidelity||"1h"});e.endTs&&t.set("endTs",e.endTs.toString());e.limit&&t.set("limit",e.limit.toString());const n=await fetch(`${o}/ohlc?${t}`);if(!n.ok)return[];const s=await n.json();return Array.isArray(s)?s:s.candles||s.data||[]},t.polymarketGetPriceHistory=async function(e){const t=new URLSearchParams({market:e.tokenId});e.interval&&t.set("interval",e.interval);e.startTs&&t.set("startTs",e.startTs.toString());e.endTs&&t.set("endTs",e.endTs.toString());e.fidelity&&t.set("fidelity",e.fidelity.toString());const n=await fetch(`${o}/prices-history?${t}`);if(!n.ok)return[];const s=await n.json();return s.history||[]},t.polymarketGetPositions=async function(e){const t=await fetch(`${s}/positions?user=${e}`);if(!t.ok)return[];const n=await t.json();return Array.isArray(n)?n:[]},t.polymarketGetClosedPositions=async function(e){const t=await fetch(`${s}/closed-positions?user=${e}`);if(!t.ok)return[];const n=await t.json();return Array.isArray(n)?n:[]},t.scoreLiquidity=a,t.parseClobTokenIds=function(e){try{const t=JSON.parse(e);return Array.isArray(t)&&t.length>=2?[t[0],t[1]]:null}catch{return null}},t.parseOutcomes=function(e){try{return JSON.parse(e)}catch{return[]}},t.parseOutcomePrices=function(e){try{return JSON.parse(e)}catch{return[]}},t.toCents=function(e){return Math.round(100*e)},t.polymarketUrl=function(e){return`https://polymarket.com/event/${e}`};const n="https://gamma-api.polymarket.com",o="https://clob.polymarket.com",s="https://data-api.polymarket.com";async function i(e){try{const t=await fetch(`${o}/book?token_id=${e}`);if(!t.ok)return null;const n=await t.json();return n.error?null:n}catch{return null}}function r(e){const t=(e.bids||[]).map(e=>({price:parseFloat(e.price),size:parseFloat(e.size)})).sort((e,t)=>t.price-e.price),n=(e.asks||[]).map(e=>({price:parseFloat(e.price),size:parseFloat(e.size)})).sort((e,t)=>e.price-t.price),o=t.length>0?Math.round(100*t[0].price):0,s=n.length>0?Math.round(100*n[0].price):100,i=s-o,r=t.slice(0,3).reduce((e,t)=>e+t.size,0),c=n.slice(0,3).reduce((e,t)=>e+t.size,0),l=t.reduce((e,t)=>e+t.size,0),d=n.reduce((e,t)=>e+t.size,0),u=a(i,r+c);return{bestBid:o,bestAsk:s,spread:i,bidDepthTop3:Math.round(r),askDepthTop3:Math.round(c),totalBidDepth:Math.round(l),totalAskDepth:Math.round(d),liquidityScore:u,levels:{bids:e.bids,asks:e.asks}}}function a(e,t){return e<=2&&t>=500?"high":e<=5&&t>=100?"medium":"low"}},35178:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shareOutput=async function(e,t,o){try{const s=await fetch(`${n}/api/share`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,args:t,data:o})});if(!s.ok)return void console.error(`Share failed: ${s.status}`);const{url:i}=await s.json();console.log(),console.log(` ${i}`),console.log()}catch(e){console.error(`Share failed: ${e.message}`)}};const n=process.env.SF_API_URL||"https://simplefunctions.dev"},40101:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.loadSkills=function(){const e=[],t=__dirname,n=t.includes("dist")?(0,s.join)(t,"../../src/skills"):t;let r=[];try{r=(0,o.readdirSync)(n).filter(e=>e.endsWith(".md"))}catch{return e}for(const t of r)try{const r=i((0,o.readFileSync)((0,s.join)(n,t),"utf-8"));r&&e.push(r)}catch{}try{const t=process.env.HOME||process.env.USERPROFILE||"",n=(0,s.join)(t,".sf","skills"),r=(0,o.readdirSync)(n).filter(e=>e.endsWith(".md"));for(const t of r)try{const r=i((0,o.readFileSync)((0,s.join)(n,t),"utf-8"));r&&e.push(r)}catch{}}catch{}return e};const o=n(79896),s=n(16928);function i(e){const t=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!t)return null;const n=t[1],o=t[2].trim(),s={};for(const e of n.split("\n")){const t=e.match(/^(\w[\w_]*)\s*:\s*(.+)$/);t&&(s[t[1]]=t[2].trim())}if(!s.name||!s.trigger)return null;const i=o.match(/## Instructions\n([\s\S]*)$/i),r=i?i[1].trim():o,a=e=>(e||"").replace(/[\[\]]/g,"").split(",").map(e=>e.trim()).filter(Boolean);return{name:s.name,trigger:s.trigger,description:s.description||"",author:s.author||"unknown",version:s.version||"1.0.0",category:s.category||"general",tags:a(s.tags),toolsUsed:a(s.tools_used),estimatedTime:s.estimated_time||"",auto:s.auto,prompt:r,raw:e}}},97325:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RISK_CATEGORIES=t.TOPIC_SERIES=void 0,t.tickerToTopic=function(e){const n=Object.entries(t.TOPIC_SERIES).flatMap(([e,t])=>t.map(t=>({prefix:t,topic:e}))).sort((e,t)=>t.prefix.length-e.prefix.length);for(const{prefix:t,topic:o}of n)if(e.toUpperCase().startsWith(t))return o.toUpperCase();return"OTHER"},t.TOPIC_SERIES={oil:["KXWTIMAX","KXWTIW","KXWTID","KXWTI"],gas:["KXAAAGASM","KXAAAGASW","KXCPIGAS"],fed:["KXFEDDECISION","KXFED","KXRATECUT","KXRATECUTCOUNT"],cpi:["KXCPI","KXCPIYOY"],recession:["KXRECSSNBER"],sp500:["KXINXY","KXINXU","KXINX"],nasdaq:["KXNASDAQ100","KXNASDAQ100U","KXNASDAQ100Y"],crypto:["KXBTCD","KXBTC","KXBTC15M","KXBTCMAXY","KXBTCMINY","KXBTCY","KXETHD","KXETH","KXETH15M","KXETHMAXY","KXETHMINY","KXSOL15M","KXXRP15M"],unemployment:["KXU3","KXPAYROLLS"],gdp:["KXGDP"],treasury:["KXTNOTEW","KXTNOTED"],geopolitics:["KXCLOSEHORMUZ","KXHORMUZTRAFFICW","KXHORMUZTRAFFIC","KXHORMUZNORM","KXLEADERSOUT","KXLEADEROUT","KXMADUROOUT","KXKHAMENEIOUT"],elections:["PRES","KXFEDCHAIRNOM","KXPRESNOMD","KXPRESNOMR","KXPRESPERSON","KXNEXTPOPE","KXTRUMPOUT","KXCANADAPM"],politics:["KXGOVSHUT","KXGOVTSHUTDOWN","KXGOVSHUTLENGTH","KXGOVTCUTS","KXTRUMPMENTION","KXEOWEEK","KXGREENLAND","KXCANCOALITION"],centralbanks:["KXCBDECISIONJAPAN","KXCBDECISIONENGLAND","KXCBDECISIONEU","KXCBDECISIONAUSTRALIA","KXCBDECISIONCANADA","KXCBDECISIONCHINA","KXCBDECISIONMEXICO","KXCBDECISIONKOREA"],forex:["KXUSDJPY"],tariffs:["KXTARIFFRATEPRC","KXTARIFFRATECAN","KXTARIFFRATECA","KXTARIFFRATEINDIA","KXTARIFFRATEBR","KXTARIFFRATEEU","KXTARIFFRATEJP","KXTARIFFRATEKR"],tech:["KXLLM1","KXTOPMODEL","KXALIENS"]},t.RISK_CATEGORIES={KXWTIMAX:"Oil",KXWTIW:"Oil",KXWTID:"Oil",KXWTI:"Oil",KXAAAGASM:"Gas",KXAAAGASW:"Gas",KXCPIGAS:"Gas",KXRECSSNBER:"Recession",KXCPI:"Inflation",KXCPIYOY:"Inflation",KXINXY:"S&P 500",KXINXU:"S&P 500",KXINX:"S&P 500",KXNASDAQ100:"Nasdaq",KXNASDAQ100U:"Nasdaq",KXNASDAQ100Y:"Nasdaq",KXFEDDECISION:"Fed Rate",KXFED:"Fed Rate",KXRATECUT:"Fed Rate",KXRATECUTCOUNT:"Fed Rate",KXBTCD:"Bitcoin",KXBTC:"Bitcoin",KXBTC15M:"Bitcoin",KXETHD:"Ethereum",KXETH:"Ethereum",KXETH15M:"Ethereum",KXU3:"Unemployment",KXPAYROLLS:"Jobs",KXGDP:"GDP",KXTNOTEW:"Treasury",KXTNOTED:"Treasury",KXCLOSEHORMUZ:"Hormuz",KXHORMUZTRAFFICW:"Hormuz",KXHORMUZTRAFFIC:"Hormuz",KXUSDJPY:"USD/JPY",KXGOVSHUT:"Govt Shutdown",KXGOVTSHUTDOWN:"Govt Shutdown",PRES:"Elections",KXFEDCHAIRNOM:"Elections",KXTARIFFRATEPRC:"Tariffs",KXCBDECISIONJAPAN:"Central Banks",KXCBDECISIONENGLAND:"Central Banks",KXCBDECISIONEU:"Central Banks"}},77096:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLR=t.bgRgb=t.rgb=void 0,t.drawBorder=function(e,n,o){const{row:s,col:i,width:r,height:a}=n;if(r<3||a<2)return;e.fill(s,i,r,a," ","",t.CLR.bgPanel);for(let n=i;n<i+r;n++)e.write(s,n,"─",t.CLR.borderDim);o&&e.write(s,i+2,` ${o} `,t.CLR.dim)},t.drawHDivider=function(e,n,o){const s=n.row+o;for(let o=n.col;o<n.col+n.width;o++)e.write(s,o,"─",t.CLR.borderDim)},t.fit=function(e,t,n="left"){return e.length>t?e.slice(0,t-1)+"…":"right"===n?e.padStart(t):e.padEnd(t)},t.sparkline=function(e,n){if(0===e.length)return[];const o=Math.min(...e),s=Math.max(...e),i=s-o||1;return e.map(e=>({text:"▁▂▃▄▅▆▇█"[Math.round((e-o)/i*7)],fg:n?n(e):t.CLR.dim}))},t.compact=function(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1)}M`:Math.abs(e)>=1e4?`${(e/1e3).toFixed(0)}k`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)}k`:String(Math.round(e))};t.rgb=(e,t,n)=>`[38;2;${e};${t};${n}m`;t.bgRgb=(e,t,n)=>`[48;2;${e};${t};${n}m`,t.CLR={border:(0,t.rgb)(50,50,56),borderDim:(0,t.rgb)(35,35,40),title:(0,t.rgb)(180,180,190),white:(0,t.rgb)(240,240,242),text:(0,t.rgb)(180,180,186),dim:(0,t.rgb)(100,100,110),veryDim:(0,t.rgb)(55,55,62),emerald:(0,t.rgb)(16,185,129),green:(0,t.rgb)(74,222,128),red:(0,t.rgb)(248,113,113),yellow:(0,t.rgb)(250,204,21),cyan:(0,t.rgb)(34,211,238),purple:(0,t.rgb)(192,132,252),bg:(0,t.bgRgb)(8,8,12),bgPanel:(0,t.bgRgb)(14,14,18),bgSelected:(0,t.bgRgb)(22,40,35),bgHover:(0,t.bgRgb)(18,18,24)}},14916:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.drawChart=function(e,t,n,s,i,r,a){if(0===r.length||s<10||i<4)return;const c=s-8-1,l=i-2;if(c<4||l<2)return;const d=Math.min(...r),u=Math.max(...r),p=u-d||1,h=[];for(let e=0;e<c;e++){const t=e/(c-1)*(r.length-1),n=Math.floor(t),o=Math.min(n+1,r.length-1),s=t-n;h.push(r[n]*(1-s)+r[o]*s)}const m=n+8+1,g=[{row:0,value:u},{row:l-1,value:d}];let f=-1;d<0&&u>0&&(f=Math.round(u/p*(l-1)),f>0&&f<l-1&&g.push({row:f,value:0}));for(let s=0;s<l;s++)e.write(t+s,n+8,"│",o.CLR.borderDim);for(const s of g){const i=Math.abs(s.value)>=100?"$"+((s.value>=0?"+":"")+s.value.toFixed(0)):"$"+((s.value>=0?"+":"")+s.value.toFixed(1));e.write(t+s.row,n,i.padStart(8),o.CLR.dim)}if(f>=0&&f<l)for(let n=0;n<c;n++)e.write(t+f,m+n,"╌",o.CLR.veryDim);for(let n=0;n<c;n++){const s=h[n],i=(s-d)/p*l*8,r=s>=0?o.CLR.green:o.CLR.red;for(let o=l-1;o>=0;o--){const s=i-8*(l-1-o);if(s>=8)e.write(t+o,m+n,"█",r);else if(s>0){const i=Math.round(Math.max(1,Math.min(s,8)));e.write(t+o,m+n," ▁▂▃▄▅▆▇█"[i],r)}}}const y=t+l;e.write(y,n+8,"└",o.CLR.borderDim);for(let t=0;t<c;t++)e.write(y,m+t,"─",o.CLR.borderDim);if(a&&a.length>0){const i=t+l+1,r=Math.min(a.length,6);for(let t=0;t<r;t++){const l=Math.round(t*(a.length-1)/Math.max(r-1,1)),d=m+Math.round(l*(c-1)/Math.max(a.length-1,1)),u=a[l]||"";d>=m&&d+u.length<n+s&&e.write(i,d,u.slice(0,5),o.CLR.dim)}}};const o=n(77096)},99844:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.loadAllData=R,t.startDashboard=async function(){const e=new o.ScreenBuffer,t=(0,i.initialState)();process.stdout.write("[?1049h"),process.stdout.write("[?25l"),process.stdin.isTTY&&process.stdin.setRawMode(!0);process.stdin.resume();let n=!1;const s=()=>{n||(n=!0,setImmediate(()=>{n=!1,D(e,t)}))},r=[];let c=!1;const l=()=>{if(!c){c=!0;for(const e of r)clearInterval(e);process.stdout.write("[?1049l"),process.stdout.write("[?25h"),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.exit(0)}};process.on("SIGINT",l),process.on("SIGTERM",l);try{await R(t)}catch(e){t.error=e instanceof Error?e.message.slice(0,50):"Failed to load data"}D(e,t),r.push(setInterval(async()=>{try{const e=await(0,a.cached)("positions",C,()=>(0,d.getPositions)());if(e){const n=await Promise.allSettled(e.map(e=>(0,a.cached)(`price:${e.ticker}`,1e4,()=>(0,d.getMarketPrice)(e.ticker))));for(let t=0;t<e.length;t++){const o=n[t];"fulfilled"===o.status&&null!=o.value&&(e[t].current_value=o.value)}t.positions=e,N(t)}s()}catch{}},C)),r.push(setInterval(async()=>{try{const e=await(0,a.cached)("orders",I,()=>(0,d.getOrders)({status:"resting"}));e&&(t.orders=e.orders||[]),s()}catch{}},I)),r.push(setInterval(async()=>{try{const e=await(0,a.cached)("balance",P,()=>(0,d.getBalance)());e&&(t.balance=e.balance??0),s()}catch{}},P)),r.push(setInterval(async()=>{try{await L(t),s()}catch{}},E)),process.stdin.on("data",n=>{!function(e,t,n,o,s){const i=t.toString("utf-8"),r=27===t[0]&&1===t.length,a=27===t[0]&&91===t[1]&&65===t[2],c=27===t[0]&&91===t[1]&&66===t[2],l="\r"===i||"\n"===i,d=3===t[0];if(d||"q"===i&&"trade"!==e.mode)return void s();switch(e.error=null,e.mode){case"overview":j(i,a,c,l,e,n,o,s);break;case"detail":!function(e,t,n,o,s){t?(n.mode="overview",s()):"b"===e?(F(n,"buy"),s()):"s"===e?(F(n,"sell"),s()):"w"===e&&n.theses.length>0&&(n.prevMode="detail",n.mode="whatif",n.whatifThesisId=n.theses[0].id,z(n).then(s))}(i,r,e,0,o);break;case"liquidity":!function(e,t,n,o,s,i,r){if(o)s.mode=s.prevMode,r();else if("j"===e||n)s.liquiditySelectedIndex++,r();else if("k"===e||t)s.liquiditySelectedIndex=Math.max(0,s.liquiditySelectedIndex-1),r();else if("\t"===e){const e=Object.keys(u.TOPIC_SERIES),t=e.indexOf(s.liquidityTopic);s.liquidityTopic=e[(t+1)%e.length],s.liquiditySelectedIndex=0,U(s).then(r)}else"b"===e?(!function(e){const t=e.liquidityData.get(e.liquidityTopic)||[];if(0===t.length)return;const n=t[Math.min(e.liquiditySelectedIndex,t.length-1)];if(!n)return;e.prevMode=e.mode,e.mode="trade",e.tradeParams={ticker:n.ticker||"",side:"yes",action:"buy",qty:10,price:n.bestAsk??n.yes_ask??50},e.tradeCountdown=-1,e.tradeField="qty"}(s),r()):"r"===e&&U(s).then(r)}(i,a,c,r,e,0,o);break;case"whatif":!function(e,t,n,o,s,i,r,a){if(s)i.mode=i.prevMode,a();else if("j"===e||n){const e=(i.whatifResult?.scenarios?.length||1)-1;i.whatifScenarioIndex=Math.min(i.whatifScenarioIndex+1,e),a()}else"k"===e||t?(i.whatifScenarioIndex=Math.max(0,i.whatifScenarioIndex-1),a()):o&&a()}(i,a,c,l,r,e,0,o);break;case"trade":!function(e,t,n,o,s,i,r,a){if(s)return i.mode=i.prevMode,i.tradeParams=null,i.tradeCountdown=-1,void a();if(!i.tradeParams)return;"\t"===e?(i.tradeField="qty"===i.tradeField?"price":"qty",a()):t?("qty"===i.tradeField?i.tradeParams.qty=Math.min(i.tradeParams.qty+1,9999):i.tradeParams.price=Math.min(i.tradeParams.price+1,99),a()):n?("qty"===i.tradeField?i.tradeParams.qty=Math.max(i.tradeParams.qty-1,1):i.tradeParams.price=Math.max(i.tradeParams.price-1,1),a()):o&&i.tradeCountdown<0&&(i.tradeCountdown=3,a(),function(e,t,n){const o=()=>{e.tradeCountdown<=0||"trade"!==e.mode||(e.tradeCountdown--,n(),0===e.tradeCountdown?q(e,n):setTimeout(o,1e3))};setTimeout(o,1e3)}(i,0,a))}(i,a,c,l,r,e,0,o)}}(t,n,e,s,l)}),process.stdout.on("resize",()=>{e.resize(),s()})};const o=n(72222),s=n(42992),i=n(56661),r=n(77096),a=n(87783),c=n(11627),l=n(19218),d=n(96139),u=n(97325),p=n(34331),h=n(3322),m=n(21704),g=n(30012),f=n(75757),y=n(50511),$=n(98573),w=n(12423),k=n(72734),b=n(35301),v=n(82950),_=n(29405),S=n(67748),x=n(87009),C=15e3,O=3e4,I=1e4,P=3e4,T=6e4,E=6e4;let A=null;function M(){if(A)return A;try{const e=(0,c.loadConfig)();return e.apiKey?(A=new l.SFClient(e.apiKey,e.apiUrl),A):null}catch{return null}}async function R(e){const t=M(),[n,o,s,i]=await Promise.allSettled([(0,a.cached)("positions",C,()=>(0,d.getPositions)()),t?(0,a.cached)("theses",O,()=>t.listTheses()):Promise.resolve(null),(0,a.cached)("orders",I,()=>(0,d.getOrders)({status:"resting"})),(0,a.cached)("balance",P,()=>(0,d.getBalance)())]);if("fulfilled"===n.status&&n.value){const t=n.value,o=await Promise.allSettled(t.map(e=>(0,a.cached)(`price:${e.ticker}`,1e4,()=>(0,d.getMarketPrice)(e.ticker))));for(let e=0;e<t.length;e++){const n=o[e];"fulfilled"===n.status&&null!=n.value&&(t[e].current_value=n.value,t[e].unrealized_pnl=Math.round((n.value-t[e].average_price_paid)*t[e].quantity))}e.positions=t}const r=(0,c.loadConfig)();if(r.polymarketWalletAddress)try{const t=await(0,a.cached)("poly-positions",C,()=>(0,p.polymarketGetPositions)(r.polymarketWalletAddress));if(t&&Array.isArray(t)&&t.length>0)for(const n of t)e.positions.push({ticker:(n.title||n.slug||n.asset||"").slice(0,25),quantity:n.size||0,average_price_paid:Math.round(100*(n.avgPrice||0)),current_value:Math.round(100*(n.curPrice||n.currentPrice||0)),unrealized_pnl:Math.round(100*(n.cashPnl||0)),side:(n.outcome||"yes").toLowerCase(),venue:"polymarket"})}catch{}if("fulfilled"===o.status&&o.value){const t=o.value;e.theses=t.theses||t||[]}if("fulfilled"===s.status&&s.value&&(e.orders=s.value.orders||[]),"fulfilled"===i.status&&i.value&&(e.balance=i.value.balance??0),t&&e.theses.length>0){const n=await Promise.allSettled(e.theses.map(e=>(0,a.cached)(`ctx:${e.id}`,O,()=>t.getContext(e.id))));for(let t=0;t<e.theses.length;t++){const o=n[t];"fulfilled"===o.status&&o.value&&e.contexts.set(e.theses[t].id,o.value)}}if(N(e),await L(e),t)try{const n=await(0,a.cached)("feed",T,()=>t.getFeed(48)),o=n.entries||n.feed||n;Array.isArray(o)&&(e.signals=o)}catch{}if(t)try{const n=await(0,a.cached)("intents",I,()=>t.request("GET","/api/intents?active=true"));e.intents=n?.intents||[]}catch{}try{const t=await(0,a.cached)("traditional",O,()=>fetch("https://simplefunctions.dev/api/public/markets").then(e=>e.ok?e.json():null));t&&(Array.isArray(t)?e.traditionalMarkets=t:"object"==typeof t&&(e.traditionalMarkets=Object.entries(t).map(([e,t])=>({symbol:e,price:t.price||t.value||0,changePct:t.changePct||t.pctChange||t.change_pct||0}))))}catch{}!function(e){const t=[];for(const[,n]of e.contexts){if(n?.milestones)for(const e of n.milestones)t.push(e);if(n?.upcomingEvents)for(const e of n.upcomingEvents)t.push(e)}t.sort((e,t)=>new Date(e.timestamp||e.date||e.time||0).getTime()-new Date(t.timestamp||t.date||t.time||0).getTime()),e.events=t.filter(e=>new Date(e.timestamp||e.date||e.time||0).getTime()>Date.now())}(e),function(e){const t=new Date,n=t.getUTCDay();e.exchangeOpen=n>=1&&n<=5}(e),e.lastRefresh.all=Date.now()}function N(e){const t=[];for(const[,n]of e.contexts)if(n?.edges)for(const e of n.edges)t.push(e);const n=new Map;for(const e of t){const t=e.marketId||e.ticker||e.market,o=n.get(t);(!o||Math.abs(e.edge??0)>Math.abs(o.edge??0))&&n.set(t,e)}const o=new Set(e.positions.map(e=>e.ticker_symbol||e.ticker));e.edges=[...n.values()].filter(e=>!o.has(e.marketId||e.ticker)).sort((e,t)=>Math.abs(t.edge??0)-Math.abs(e.edge??0))}async function L(e){const t=e.positions.map(e=>e.ticker).filter(Boolean);if(0!==t.length)try{const n=Math.floor(Date.now()/1e3),o=n-604800,s=await(0,a.cached)("candles",E,()=>(0,d.getBatchCandlesticks)({tickers:t,startTs:o,endTs:n}));for(const t of s)if(t.market_ticker&&t.candlesticks){const n=t.candlesticks.map(e=>{const t=parseFloat(e.yes_bid?.close_dollars||"0"),n=parseFloat(e.yes_ask?.close_dollars||"0"),o=t>0&&n>0?(t+n)/2:t||n,s=parseFloat(e.price?.close_dollars||"0")||o;return{close:Math.round(100*s),date:e.end_period_ts?new Date(1e3*e.end_period_ts).toISOString().slice(0,10):"",end_period_ts:e.end_period_ts}}).filter(e=>e.close>0);e.candleCache.set(t.market_ticker,n)}}catch{}}function D(e,t){switch((0,w.renderMarketBar)(e,0,t),(0,$.renderStatusBar)(e,1,t),(0,k.renderCommandBar)(e,e.rows-1,t),t.mode){case"overview":K(e,t);break;case"detail":(0,b.renderDetail)(e,(0,s.fullLayout)(e.cols,e.rows),t);break;case"liquidity":(0,v.renderLiquidity)(e,(0,s.fullLayout)(e.cols,e.rows),t);break;case"whatif":(0,_.renderWhatif)(e,(0,s.fullLayout)(e.cols,e.rows),t);break;case"trade":"detail"===t.prevMode?(0,b.renderDetail)(e,(0,s.fullLayout)(e.cols,e.rows),t):K(e,t),(0,S.renderTrade)(e,(0,s.fullLayout)(e.cols,e.rows),t)}e.flush()}function K(e,t){const n=e.cols<80,o=n?(0,s.narrowLayout)(e.cols,e.rows):(0,s.overviewLayout)(e.cols,e.rows);if(!n){const t=Math.floor(.55*e.cols);for(let n=2;n<e.rows-1;n++)e.write(n,t,"│",r.CLR.borderDim)}for(const n of o)switch(n.name){case"positions":(0,h.renderPortfolio)(e,n,t);break;case"thesis":(0,m.renderThesis)(e,n,t);break;case"edges":(0,g.renderEdges)(e,n,t);break;case"signals":(0,y.renderSignals)(e,n,t);break;case"intents":(0,x.renderIntents)(e,n,t);break;case"orders":(0,f.renderOrders)(e,n,t)}}function j(e,t,n,o,s,i,r,c){const l="positions"===s.focusArea?s.positions:"edges"===s.focusArea?s.edges:s.intents||[],d=Math.max(0,l.length-1);if("j"===e||n)s.selectedIndex=Math.min(s.selectedIndex+1,d),r();else if("k"===e||t)s.selectedIndex=Math.max(s.selectedIndex-1,0),r();else if(o){if("positions"===s.focusArea&&s.positions.length>0){const e=s.positions[s.selectedIndex];s.detailTicker=e?.ticker||null,s.prevMode="overview",s.mode="detail",r()}}else if("l"===e)s.prevMode="overview",s.mode="liquidity",s.liquiditySelectedIndex=0,U(s).then(r);else if("w"===e)s.theses.length>0&&(s.prevMode="overview",s.mode="whatif",s.whatifThesisId=s.theses[0].id,z(s).then(r));else if("b"===e)F(s,"buy"),r();else if("s"===e)F(s,"sell"),r();else if("e"===e)(async function(e){const t=M();if(!t||0===e.theses.length)return;try{e.error=null;const n=e.theses[0];await t.evaluate(n.id),(0,a.invalidateAll)(),await R(e)}catch(t){e.error=t instanceof Error?t.message.slice(0,40):"Evaluation failed"}})(s).then(r);else if("r"===e)(0,a.invalidateAll)(),R(s).then(r);else if("i"===e){if("edges"===s.focusArea&&s.edges.length>0){const e=s.edges[s.selectedIndex];if(e){const t=e.marketId||e.ticker||"";F(s,"buy"),s.tradeParams&&(s.tradeParams.ticker=t,s.tradeParams.side=e.direction||"yes",s.tradeParams.price=e.marketPrice||50),r()}}}else if("x"===e){if("intents"===s.focusArea&&s.intents.length>0){const e=s.intents[s.selectedIndex];if(e?.id){const t=M();t&&t.request("DELETE",`/api/intents/${e.id}`).then(()=>{(0,a.invalidateAll)(),R(s).then(r)}).catch(()=>{s.error="Failed to cancel intent",r()})}}}else if(e>="1"&&e<="9"){const t=parseInt(e)-1;t<s.theses.length&&(s.activeThesisIndex=t,r())}else"\t"===e&&("positions"===s.focusArea?s.focusArea="edges":"edges"===s.focusArea?s.focusArea="intents":s.focusArea="positions",s.selectedIndex=0,r())}function F(e,t){let n="";if("positions"===e.focusArea&&e.positions.length>0){const t=e.positions[e.selectedIndex];n=t?.ticker_symbol||t?.ticker||""}else if("edges"===e.focusArea&&e.edges.length>0){const t=e.edges[e.selectedIndex];n=t?.ticker||t?.marketId||""}else e.detailTicker&&(n=e.detailTicker);n?(e.prevMode=e.mode,e.mode="trade",e.tradeParams={ticker:n,side:"yes",action:t,qty:10,price:50},e.tradeCountdown=-1,e.tradeField="qty"):e.error="No market selected"}async function q(e,t){if(e.tradeParams){try{if(!(0,c.loadConfig)().tradingEnabled)return e.error="Trading disabled. Run: sf setup --enable-trading",e.tradeCountdown=-1,void t();await(0,d.createOrder)({ticker:e.tradeParams.ticker,side:e.tradeParams.side,action:e.tradeParams.action,type:"limit",count:e.tradeParams.qty,yes_price:e.tradeParams.price}),e.error=null,e.mode=e.prevMode,e.tradeParams=null,e.tradeCountdown=-1,(0,a.invalidateAll)(),await R(e)}catch(t){e.error=t instanceof Error?t.message.slice(0,40):"Trade failed",e.tradeCountdown=-1}t()}}async function U(e){const t=e.liquidityTopic,n=u.TOPIC_SERIES[t];if(n)try{const o=await Promise.allSettled(n.map(e=>(0,a.cached)(`liq:${e}`,3e4,async()=>{const t=`https://api.elections.kalshi.com/trade-api/v2/markets?series_ticker=${e}&status=open&limit=200`,n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)return[];return(await n.json()).markets||[]}))),s=[];for(const e of o)"fulfilled"===e.status&&Array.isArray(e.value)&&s.push(...e.value);e.liquidityData.set(t,[...s]);const i=8;for(let n=0;n<s.length;n+=i){const o=s.slice(n,n+i),r=await Promise.allSettled(o.map(e=>(0,a.cached)(`ob:${e.ticker}`,3e4,()=>(0,d.getPublicOrderbook)(e.ticker)).then(t=>({mkt:e,ob:t}))));for(const e of r){if("fulfilled"!==e.status||!e.value.ob)continue;const{mkt:t,ob:n}=e.value,o=(n.yes_dollars||[]).map(e=>({price:Math.round(100*parseFloat(e[0])),qty:parseFloat(e[1])})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),s=(n.no_dollars||[]).map(e=>({price:Math.round(100*parseFloat(e[0])),qty:parseFloat(e[1])})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price);t.bestBid=o.length>0?o[0].price:0,t.bestAsk=s.length>0?100-s[0].price:100,t.spread=t.bestAsk-t.bestBid,t.totalDepth=o.slice(0,3).reduce((e,t)=>e+t.qty,0)+s.slice(0,3).reduce((e,t)=>e+t.qty,0)}e.liquidityData.set(t,[...s])}}catch(t){e.error="Failed to load liquidity data"}}async function z(e){if(M()&&e.whatifThesisId)try{const t=e.contexts.get(e.whatifThesisId);if(!t)return;const n=(t.causalTree?.nodes||t.nodes||[]).slice(0,10).map(e=>({name:e.name||e.title||e.id,nodeId:e.id,description:`Set ${e.name||e.id} to low probability`}));e.whatifResult={scenarios:n,before:{confidence:e.theses[0]?.confidence,edges:e.edges.slice(0,5)},after:null}}catch{e.error="Failed to load what-if data"}}},42992:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.overviewLayout=function(e,t){const n=t-3,o=Math.floor(.55*e),s=e-o-1,i=o+1,r=Math.max(Math.floor(.4*n),5),a=Math.max(Math.floor(.3*n),4),c=Math.max(n-r-a,3);return[{name:"positions",row:2,col:0,width:o,height:r},{name:"thesis",row:2,col:i,width:s,height:r},{name:"edges",row:2+r,col:0,width:o,height:a},{name:"signals",row:2+r,col:i,width:s,height:a},{name:"intents",row:2+r+a,col:0,width:o,height:c},{name:"orders",row:2+r+a,col:i,width:s,height:c}]},t.fullLayout=function(e,t){return{name:"main",row:2,col:0,width:e,height:t-3}},t.narrowLayout=function(e,t){const n=t-3,o=Math.floor(n/4);return[{name:"positions",row:2,col:0,width:e,height:o},{name:"edges",row:2+o,col:0,width:e,height:o},{name:"intents",row:2+2*o,col:0,width:e,height:o},{name:"thesis",row:2+3*o,col:0,width:e,height:n-3*o}]}},72222:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ScreenBuffer=void 0;t.ScreenBuffer=class{front;back;cols;rows;constructor(){this.cols=process.stdout.columns||120,this.rows=process.stdout.rows||40,this.front=this.createBuffer(),this.back=this.createBuffer()}createBuffer(){return Array.from({length:this.rows},()=>Array.from({length:this.cols},()=>({char:" ",fg:"",bg:""})))}write(e,t,n,o="",s=""){if(e<0||e>=this.rows)return;let i=t;for(let t=0;t<n.length&&i<this.cols;t++)i>=0&&(this.back[e][i]={char:n[t],fg:o,bg:s}),i++}writeStyled(e,t,n){let o=t;for(const t of n)for(let n=0;n<t.text.length&&o<this.cols;n++)e>=0&&e<this.rows&&o>=0&&(this.back[e][o]={char:t.text[n],fg:t.fg||"",bg:t.bg||""}),o++}fill(e,t,n,o,s=" ",i="",r=""){for(let a=e;a<e+o&&a<this.rows;a++)for(let e=t;e<t+n&&e<this.cols;e++)a>=0&&e>=0&&(this.back[a][e]={char:s,fg:i,bg:r})}flush(){let e="",t="",n="";for(let o=0;o<this.rows;o++)for(let s=0;s<this.cols;s++){const i=this.front[o][s],r=this.back[o][s];i.char===r.char&&i.fg===r.fg&&i.bg===r.bg||(e+=`[${o+1};${s+1}H`,r.fg===t&&r.bg===n||(e+="",r.fg&&(e+=r.fg),r.bg&&(e+=r.bg),t=r.fg,n=r.bg),e+=r.char)}e&&(e+="",process.stdout.write(e)),this.front=this.back,this.back=this.createBuffer()}resize(){this.cols=process.stdout.columns||120,this.rows=process.stdout.rows||40,this.front=this.createBuffer(),this.back=this.createBuffer(),process.stdout.write("")}}},56661:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.initialState=function(){return{mode:"overview",prevMode:"overview",selectedIndex:0,focusArea:"positions",detailTicker:null,liquidityTopic:"oil",liquiditySelectedIndex:0,whatifScenarioIndex:0,whatifResult:null,whatifThesisId:null,tradeParams:null,tradeCountdown:-1,tradeField:"qty",activeThesisIndex:0,positions:[],theses:[],contexts:new Map,edges:[],orders:[],signals:[],events:[],intents:[],traditionalMarkets:[],balance:0,candleCache:new Map,liquidityData:new Map,error:null,lastRefresh:{},exchangeOpen:null}}},72734:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderCommandBar=function(e,t,n){const r=e.cols;e.fill(t,0,r,1," ","",s);const a=i[n.mode]||i.overview,c="overview"===n.mode?n.focusArea.toUpperCase():"";let l=1;c&&(e.write(t,l,"●",o.CLR.emerald,s),l+=2,e.write(t,l,c,o.CLR.dim,s),l+=c.length+2);for(const n of a){if(l+n.key.length+n.label.length+3>r-2)break;e.write(t,l,n.key,o.CLR.emerald,s),l+=n.key.length,e.write(t,l," "+n.label,o.CLR.dim,s),l+=n.label.length+3}if(n.error){const i=n.error.slice(0,30),a=r-i.length-2;a>l&&e.write(t,a,i,o.CLR.red,s)}};const o=n(77096),s=(0,o.bgRgb)(12,12,16),i={overview:[{key:"j/k",label:"nav"},{key:"Tab",label:"focus"},{key:"⏎",label:"detail"},{key:"i",label:"intent"},{key:"x",label:"cancel"},{key:"1-9",label:"thesis"},{key:"l",label:"liquidity"},{key:"w",label:"whatif"},{key:"b/s",label:"trade"},{key:"r",label:"refresh"},{key:"q",label:"quit"}],detail:[{key:"b",label:"buy"},{key:"s",label:"sell"},{key:"w",label:"whatif"},{key:"Esc",label:"back"},{key:"q",label:"quit"}],liquidity:[{key:"j/k",label:"nav"},{key:"Tab",label:"topic"},{key:"b",label:"buy"},{key:"r",label:"refresh"},{key:"Esc",label:"back"}],whatif:[{key:"j/k",label:"nav"},{key:"⏎",label:"apply"},{key:"Esc",label:"back"}],trade:[{key:"↑↓",label:"adjust"},{key:"Tab",label:"field"},{key:"⏎",label:"confirm"},{key:"Esc",label:"cancel"}]}},35301:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderDetail=function(e,t,n){(0,o.drawBorder)(e,t,"POSITION DETAIL");const i=t.col+2,r=t.width-4,a=n.positions.find(e=>(e.ticker_symbol||e.ticker)===n.detailTicker)||n.positions[0];if(!a)return void e.write(t.row+2,i,"No position selected",o.CLR.dim);const c=a.ticker_symbol||a.ticker||"???",l=a.quantity??0,d=a.average_price_paid??a.cost_basis??0,u=a.current_value??d,p=(u-d)*l,h=p/100,m=p>=0?o.CLR.green:o.CLR.red,g=a.side||"yes";let f=1;e.writeStyled(t.row+f,i,[{text:(0,o.fit)(c,30),fg:o.CLR.white},{text:` ${g.toUpperCase()} `,fg:o.CLR.emerald},{text:` qty: ${l}`,fg:o.CLR.dim}]),f++,e.writeStyled(t.row+f,i,[{text:`Entry: ${d.toFixed(0)}¢`,fg:o.CLR.dim},{text:` Current: ${u.toFixed(0)}¢`,fg:o.CLR.text},{text:` P&L: ${h>=0?"+":""}$${Math.abs(h).toFixed(2)}`,fg:m}]),f++;const y=a.expiration_time||a.expiry||a.close_time||"";if(y){const n=new Date(y),s=Math.ceil((n.getTime()-Date.now())/864e5);e.write(t.row+f,i,`Expiry: ${n.toISOString().slice(0,10)} (${s}d)`,o.CLR.dim)}f++,(0,o.drawHDivider)(e,t,f),f++;const $=Math.min(8,Math.floor((t.height-f-8)/2)+4),w=n.candleCache.get(c)||[];if(w.length>1){const n=w.map(e=>((e.close??0)-d)*l/100),a=w.map(e=>{const t=e.date?new Date(e.date):new Date(e.end_period_ts?1e3*e.end_period_ts:0);return`${t.getMonth()+1}/${t.getDate()}`});e.write(t.row+f,i,"Daily P&L ($)",o.CLR.title),f++,(0,s.drawChart)(e,t.row+f,i,r,$,n,a),f+=$+1}else e.write(t.row+f,i,"No chart data available",o.CLR.dim),f+=2;f<t.height-5&&((0,o.drawHDivider)(e,t,f),f++);const k=Math.floor(r/2)-1,b=t.row+f,v=t.height-f-1;e.write(b,i,"Causal Tree",o.CLR.title);let _=null;for(const[,e]of n.contexts){if((e?.edges||[]).some(e=>e.marketId===c||e.ticker===c)){_=e;break}}const S=[];!function e(t,n=0){for(const o of t)S.push({...o,depth:n}),o.children&&e(o.children,n+1)}(_?.causalTree?.nodes||[]);const x=S.filter(e=>e.depth<=1).slice(0,v-1);for(let t=0;t<x.length;t++){const n=x[t],s=" ".repeat(n.depth+1),r=n.label||n.claim||n.name||n.id||"?",a=null!=n.probability?`${Math.round(100*n.probability)}%`:"";e.writeStyled(b+1+t,i,[{text:s+(0,o.fit)(r,k-s.length-5),fg:o.CLR.text},{text:(0,o.fit)(a,5,"right"),fg:o.CLR.emerald}])}0===x.length&&e.write(b+1,i," (no context data)",o.CLR.dim);const C=i+k+2;e.write(b,C,"Orderbook",o.CLR.title);const O=_?.edges?.find(e=>e.marketId===c||e.ticker===c),I=O?.orderbook;if(I){const t=I.bidPrice??I.bestBid??0,n=I.askPrice??I.bestAsk??0,s=I.spread??n-t;e.writeStyled(b+1,C,[{text:"Bid: ",fg:o.CLR.dim},{text:`${t}¢`,fg:o.CLR.green},{text:" Ask: ",fg:o.CLR.dim},{text:`${n}¢`,fg:o.CLR.red}]),e.writeStyled(b+2,C,[{text:"Spread: ",fg:o.CLR.dim},{text:`${s}¢`,fg:s<=2?o.CLR.green:s<=5?o.CLR.yellow:o.CLR.red}]),null!=I.bidDepth&&e.writeStyled(b+3,C,[{text:"Depth: ",fg:o.CLR.dim},{text:`bid ${I.bidDepth}`,fg:o.CLR.dim},{text:` / ask ${I.askDepth}`,fg:o.CLR.dim}])}else e.write(b+1,C," (no orderbook data)",o.CLR.dim)};const o=n(77096),s=n(14916)},30012:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderEdges=function(e,t,n){(0,o.drawBorder)(e,t,"TOP EDGES");const i=t.col+2,r=t.width-4,a=t.height-2,c=new Set(n.positions.map(e=>e.ticker)),l=n.edges.filter(e=>!c.has(e.marketId||e.ticker||"")),d=l.slice(0,Math.min(a,8));if(0===d.length)return void e.write(t.row+1,i,"No unpositioned edges",o.CLR.dim);const u=Math.max(...d.map(e=>Math.abs(e.edge??e.edgeSize??0)),1);for(let a=0;a<d.length;a++){const c=d[a],l=t.row+1+a,p="edges"===n.focusArea&&n.selectedIndex===a,h=p?"▸":" ",m=c.market||c.marketTitle||c.marketId||"???",g=c.edge??c.edgeSize??0,f=`${g>0?"+":""}${g.toFixed(0)}¢`,y=`${c.marketPrice??"?"}¢`,$="polymarket"===c.venue?"P":"K",w=c.orderbook?.liquidityScore||"",k="high"===w?"H":"medium"===w?"M":"low"===w?"L":"",b="high"===w?o.CLR.green:"low"===w?o.CLR.yellow:o.CLR.dim,v=6,_=Math.abs(g)/u,S=Math.floor(_*v),x=_*v-S,C=Math.min(Math.floor(8*x),7),O=s[7].repeat(S)+(x>.1?s[C]:""),I=g>0?o.CLR.emerald:o.CLR.red,P=Math.max(r-28,8);e.writeStyled(l,i,[{text:`${h}${$} `,fg:p?o.CLR.white:o.CLR.dim},{text:(0,o.fit)(m,P),fg:p?o.CLR.white:o.CLR.text},{text:(0,o.fit)(y,5,"right"),fg:o.CLR.dim},{text:" "+(0,o.fit)(O,v),fg:I},{text:(0,o.fit)(f,5,"right"),fg:o.CLR.emerald},{text:k?` ${k}`:"",fg:b}])}};const o=n(77096),s="▏▎▍▌▋▊▉█"},87009:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderIntents=function(e,t,n){(0,o.drawBorder)(e,t,"INTENTS");const i=t.col+2,r=t.width-4,a=t.height-2,c=n.intents||[];if(0===c.length)return e.write(t.row+1,i,"No active intents",o.CLR.dim,o.CLR.bgPanel),void e.write(t.row+2,i,"Press i on an edge to create one",o.CLR.veryDim,o.CLR.bgPanel);for(let l=0;l<Math.min(c.length,a);l++){const a=c[l],d=t.row+1+l,u="intents"===n.focusArea&&n.selectedIndex===l,p=u?o.CLR.bgSelected:o.CLR.bgPanel;u&&e.fill(d,t.col+1,t.width-2,1," ","",p);const h=a.status||"pending",m=s[h]||o.CLR.dim,g=(a.action||"buy").toUpperCase(),f=(a.direction||"yes").toUpperCase(),y=(a.marketId||a.market_id||"???").slice(0,16),$=a.targetQuantity||a.target_quantity||0,w=a.filledQuantity||a.filled_quantity||0,k=a.maxPrice||a.max_price,b=k?`≤${k}¢`:"mkt",v=w>0?`${w}/${$}`:`${$}`,_=Math.max(r-26,6);e.writeStyled(d,i,[{text:(0,o.fit)(h,9),fg:m,bg:p},{text:` ${g} `,fg:u?o.CLR.white:o.CLR.text,bg:p},{text:(0,o.fit)(y,_),fg:u?o.CLR.white:o.CLR.text,bg:p},{text:` ${f} ${v} ${b}`,fg:o.CLR.dim,bg:p}])}};const o=n(77096),s={pending:o.CLR.yellow,armed:o.CLR.emerald,triggered:o.CLR.white,executing:o.CLR.cyan,filled:o.CLR.green,partial:o.CLR.yellow,expired:o.CLR.veryDim,cancelled:o.CLR.veryDim,rejected:o.CLR.red}},82950:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderLiquidity=function(e,t,n){(0,o.drawBorder)(e,t,"LIQUIDITY SCANNER");const a=t.col+2,c=t.width-4;let l=1;const d=Object.keys(s.TOPIC_SERIES);let u=a;for(const s of d){const a=s===n.liquidityTopic,c=` ${s.toUpperCase()} `,d=a?o.CLR.emerald:o.CLR.dim,p=a?i:r;e.write(t.row+l,u,c,d,p),u+=c.length+1}l+=2;const p=Math.min(28,Math.floor(.35*c));e.writeStyled(t.row+l,a,[{text:(0,o.fit)("Market",p),fg:o.CLR.title},{text:(0,o.fit)("Bid¢",8,"right"),fg:o.CLR.title},{text:(0,o.fit)("Ask¢",8,"right"),fg:o.CLR.title},{text:(0,o.fit)("Spread",8,"right"),fg:o.CLR.title},{text:(0,o.fit)("Depth",8,"right"),fg:o.CLR.title},{text:" ",fg:o.CLR.dim}]),l++;for(let n=a;n<a+c;n++)e.write(t.row+l,n,"─",o.CLR.borderDim);l++;const h=n.liquidityData.get(n.liquidityTopic)||[],m=new Set(n.positions.map(e=>e.ticker_symbol||e.ticker)),g=(t.height,function(e){const t=new Map;for(const n of e){const e=(n.ticker||"").toUpperCase();let o="Other";if(e.includes("-D")||e.includes("DAILY"))o="Daily";else if(e.includes("-W")||e.includes("WEEKLY"))o="Weekly";else if(e.includes("-M")||e.match(/-\d{2}(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d{2}/))o="Monthly";else{const e=n.expiration_time||n.close_time||"";if(e){const t=Math.ceil((new Date(e).getTime()-Date.now())/864e5);o=t<=7?"Weekly":t<=35?"Monthly":"Long-term"}}t.has(o)||t.set(o,[]),t.get(o).push(n)}const n=["Daily","Weekly","Monthly","Long-term","Other"],o=new Map;for(const e of n)t.has(e)&&o.set(e,t.get(e));return o}(h));let f=0;for(const[s,i]of g){if(l>=t.row+t.height-4)break;e.write(t.row+l,a,` ${s}`,o.CLR.title),l++;for(const s of i){if(l>=t.row+t.height-4)break;const i=n.liquiditySelectedIndex===f,r=i?"▸":" ",c=m.has(s.ticker)?"← held":"",d=s.ticker||"???",u=s.bestBid??s.yes_bid??0,h=s.bestAsk??s.yes_ask??0,g=s.spread??h-u,y=s.totalDepth??s.depth??0,$=g<=2?o.CLR.green:g<=5?o.CLR.yellow:o.CLR.red;e.writeStyled(t.row+l,a,[{text:r+" ",fg:i?o.CLR.emerald:o.CLR.dim},{text:(0,o.fit)(d,p-2),fg:o.CLR.text},{text:(0,o.fit)(String(u),8,"right"),fg:o.CLR.green},{text:(0,o.fit)(String(h),8,"right"),fg:o.CLR.red},{text:(0,o.fit)(String(g),8,"right"),fg:$},{text:(0,o.fit)(String(y),8,"right"),fg:o.CLR.dim},{text:c?` ${c}`:"",fg:o.CLR.emerald}]),l++,f++}}if(h.length>0){const s=Math.min(n.liquiditySelectedIndex,h.length-1),i=Array.from(g.values()).flat(),r=i[s]||i[0];if(r){const n=t.row+t.height-3;e.write(n,a,(0,o.fit)(`▶ ${r.ticker||""}`,c),o.CLR.emerald);const s=null!=r.slippage?`Slippage: ~${r.slippage}¢`:"",i=null!=r.edge?`Edge: ${r.edge>=0?"+":""}${r.edge}¢`:"";e.writeStyled(n+1,a,[{text:s?(0,o.fit)(s,20):"",fg:o.CLR.dim},{text:i?(0,o.fit)(i,20):"",fg:r.edge>=0?o.CLR.green:o.CLR.red}])}}};const o=n(77096),s=n(97325),i=(0,o.bgRgb)(30,30,35),r=(0,o.bgRgb)(16,16,18)},12423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderMarketBar=function(e,t,n){const i=e.cols;e.fill(t,0,i,1," ","",s);const r=n.traditionalMarkets||[];if(0===r.length)return void e.write(t,1,"SimpleFunctions",o.CLR.dim,s);const a=r.slice(0,6),c=Math.floor((i-2)/a.length);for(let n=0;n<a.length;n++){const i=a[n],r=1+n*c,l=(i.symbol||i.name||"???").replace("SPDR ","").replace(" ETF","").slice(0,5),d=i.changePct??i.change_pct??i.pctChange??0,u=i.price??i.value??0,p=u>100?Math.round(u).toLocaleString():u.toFixed(2),h=`${d>=0?"+":""}${d.toFixed(1)}%`,m=d>=0?o.CLR.green:o.CLR.red;e.write(t,r,l,o.CLR.dim,s),e.write(t,r+l.length+1,p,o.CLR.text,s),e.write(t,r+l.length+1+p.length+1,h,m,s)}};const o=n(77096),s=(0,o.bgRgb)(12,12,16)},75757:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderOrders=function(e,t,n){(0,o.drawBorder)(e,t,"ORDERS");const s=t.col+2,i=(t.width,t.height-2);if(0===n.orders.length)return void e.write(t.row+1,s,"No resting orders",o.CLR.dim);for(let r=0;r<Math.min(n.orders.length,i);r++){const i=n.orders[r],a=t.row+1+r,c=(i.ticker||"???").slice(0,10),l=Math.round(parseFloat(i.remaining_count_fp||i.initial_count_fp||"0")),d=parseFloat(i.yes_price_dollars||"0"),u=Math.round(100*d),p=i.status||"resting",h=`${l}@${u}¢`,m=new Date(i.created_time||Date.now()).getTime(),g=Math.floor((Date.now()-m)/864e5),f=0===g?"<1d":`${g}d`,y=g>3,$=y?"⚠ ":" ";e.writeStyled(a,s,[{text:$,fg:y?o.CLR.yellow:o.CLR.dim},{text:(0,o.fit)(c,12),fg:o.CLR.text},{text:(0,o.fit)(h,10),fg:o.CLR.dim},{text:(0,o.fit)(p,10),fg:"filled"===p?o.CLR.green:o.CLR.dim},{text:(0,o.fit)(f,4,"right"),fg:y?o.CLR.yellow:o.CLR.dim}])}};const o=n(77096)},3322:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderPortfolio=function(e,t,n){(0,o.drawBorder)(e,t,"POSITIONS");const s=t.col+2,i=t.width-4,r=t.height-2;let a=0;if(0===n.positions.length)return e.write(t.row+1,s,"No positions",o.CLR.dim,o.CLR.bgPanel),void e.write(t.row+2,s,"sf buy TICKER QTY --price CENTS",o.CLR.veryDim,o.CLR.bgPanel);const c=[...n.positions].sort((e,t)=>{const n=Math.abs(((e.current_value||e.average_price_paid||0)-(e.average_price_paid||0))*(e.quantity||0));return Math.abs(((t.current_value||t.average_price_paid||0)-(t.average_price_paid||0))*(t.quantity||0))-n});for(const l of c){if(a+1>=r)break;const d=t.row+1+a,u=c.indexOf(l),p="positions"===n.focusArea&&n.selectedIndex===u,h=p?o.CLR.bgSelected:o.CLR.bgPanel;p&&e.fill(d,t.col+1,t.width-2,2," ","",h);const m=l.ticker||"???",g="polymarket"===l.venue?"P":"K",f="polymarket"===l.venue?o.CLR.purple:o.CLR.cyan;if(e.writeStyled(d,s,[{text:g+" ",fg:f,bg:h},{text:(0,o.fit)(m,Math.min(i-2,28)),fg:p?o.CLR.white:o.CLR.text,bg:h}]),a+1<r){const t=l.quantity??0,i=l.average_price_paid??0,r=l.current_value??i,a=(r-i)*t/100,c=(a>=0?"+$":"-$")+Math.abs(a).toFixed(2),u=a>=0?o.CLR.green:o.CLR.red,p=[{text:` ${(0,o.compact)(t)} @ ${i}¢`,fg:o.CLR.dim,bg:h},{text:` → ${r}¢ `,fg:o.CLR.dim,bg:h},{text:(0,o.fit)(c,9),fg:u,bg:h}],g=n.candleCache.get(m);if(g&&g.length>1){const e=g.slice(-7).map(e=>((e.close??0)-i)*t),n=(0,o.sparkline)(e,e=>e>=0?o.CLR.green:o.CLR.red);for(const e of n)p.push({...e,bg:h})}e.writeStyled(d+1,s,p)}a+=2}};const o=n(77096)},50511:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderSignals=function(e,t,n){(0,o.drawBorder)(e,t,"FEED");const s=t.col+2,i=t.width-4,r=t.height-2,a=n.signals.sort((e,t)=>{const n=new Date(e.evaluatedAt||e.timestamp||e.time||0).getTime();return new Date(t.evaluatedAt||t.timestamp||t.time||0).getTime()-n});if(0===a.length)return void e.write(t.row+1,s,"No recent signals",o.CLR.dim);for(let n=0;n<Math.min(a.length,r);n++){const r=a[n],c=t.row+1+n,l=r.confidenceDelta??r.delta??r.change??0,d=r.summary||r.title||r.content||"???",u=r.evaluatedAt||r.timestamp||r.time||"";let p=" ";if(u){const e=new Date(u);p=`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}const h="number"!=typeof l||l>=0,m="number"==typeof l&&Math.abs(l)>=.001,g=m?h?"▲":"▼":" ",f=h?o.CLR.green:o.CLR.red,y=m?`${l>0?"+":""}${Math.round(100*l)}%`:"",$=i-14;e.writeStyled(c,s,[{text:p,fg:o.CLR.veryDim},{text:` ${g}`,fg:m?f:o.CLR.dim},{text:(0,o.fit)(y,5,"right"),fg:m?f:o.CLR.dim},{text:" "+(0,o.fit)(d,$),fg:o.CLR.text}])}};const o=n(77096)},98573:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderStatusBar=function(e,t,n){const r=e.cols;e.fill(t,0,r,1," ","",s);let a=0,c=0;for(const e of n.positions){const t=e.average_price_paid??e.cost_basis??0,n=e.current_value??t,o=e.quantity??0;a+=(n-t)*o,c+=t*o}const l=a/100,d=c>0?a/c*100:0,u=l>=0?o.CLR.green:o.CLR.red;let p=1;const h=l>=0?"+":"",m=`${h}$${Math.abs(l).toFixed(2)}`,g=`${h}${d.toFixed(1)}%`;if(e.write(t,p,"P&L ",o.CLR.dim,s),p+=4,e.write(t,p,m,u,s),p+=m.length+1,e.write(t,p,g,u,s),p+=g.length+1,e.write(t,p,i,o.CLR.veryDim,s),p+=2,e.write(t,p,`$${n.balance.toFixed(2)}`,o.CLR.text,s),p+=`$${n.balance.toFixed(2)}`.length+1,n.theses.length>0){e.write(t,p,i,o.CLR.veryDim,s),p+=2;const r=n.theses[n.activeThesisIndex||0]||n.theses[0],a=(r.title||"Thesis").slice(0,18),c=null!=r.confidence?`${Math.round(100*(r.confidence??0))}%`:"?%";if(e.write(t,p,a,o.CLR.dim,s),p+=a.length+1,e.write(t,p,c,o.CLR.emerald,s),p+=c.length+1,n.theses.length>1){const i=`[${(n.activeThesisIndex||0)+1}/${n.theses.length}]`;e.write(t,p,i,o.CLR.veryDim,s),p+=i.length+1}}const f=(n.intents||[]).filter(e=>["pending","armed","triggered","executing"].includes(e.status));if(f.length>0){e.write(t,p,i,o.CLR.veryDim,s),p+=2;const n=`${f.length} intent${f.length>1?"s":""}`;e.write(t,p,n,o.CLR.emerald,s),p+=n.length+1}if(null!==n.exchangeOpen){e.write(t,p,i,o.CLR.veryDim,s),p+=2;const r=n.exchangeOpen?"OPEN":"CLOSED",a=n.exchangeOpen?o.CLR.green:o.CLR.red;e.write(t,p,r,a,s)}const y=(new Date).toISOString().slice(11,19)+" UTC";e.write(t,r-y.length-1,y,o.CLR.veryDim,s)};const o=n(77096),s=(0,o.bgRgb)(16,16,20),i="│"},21704:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderThesis=function(e,t,n){(0,o.drawBorder)(e,t,"THESIS");const s=t.col+2,i=t.width-4,r=t.height-2;let a=0;for(const c of n.theses){if(a>=r-2)break;const n=t.row+1+a,l=c.title||c.short_title||"???",d=c.confidence??c.current_confidence??0,u=`${Math.round(100*d)}%`,p=c.lastEvaluation?.confidenceDelta??c.confidence_delta??0;let h,m,g;p>=.02?(h="▲",m=o.CLR.green,g=`+${Math.round(100*p)}`):p<=-.02?(h="▼",m=o.CLR.red,g=`${Math.round(100*p)}`):(h="─",m=o.CLR.dim,g=p>=0?`+${Math.round(100*p)}`:`${Math.round(100*p)}`);const f=i-10;e.writeStyled(n,s,[{text:(0,o.fit)(l,f),fg:o.CLR.text},{text:(0,o.fit)(u,5,"right"),fg:o.CLR.white},{text:` ${h}`,fg:m},{text:(0,o.fit)(g,3,"right"),fg:m}]),a++}if(n.theses.length>0&&a<r){const a=n.theses[0],c=n.contexts.get(a.id||a.thesis_id),l=c?.lastEvaluation?.summary||a.lastEvaluation?.summary||"";if(l){const n=t.row+1+r-1,d=c?.lastEvaluation?.timestamp||a.lastEvaluation?.timestamp;let u="";if(d){const e=Math.floor((Date.now()-new Date(d).getTime())/36e5);u=e<1?"<1h ago":`${e}h ago`}const p=i-u.length-1;e.writeStyled(n,s,[{text:(0,o.fit)(l,p),fg:o.CLR.dim},{text:" "+u,fg:o.CLR.veryDim}])}}};const o=n(77096)},67748:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderTrade=function(e,t,n){if(!n.tradeParams)return;const a=n.tradeParams,c=Math.min(50,t.width-4),l=Math.min(18,t.height-2),d=t.col+Math.floor((t.width-c)/2),u=t.row+Math.floor((t.height-l)/2),p={name:"trade",row:u,col:d,width:c,height:l};e.fill(u,d,c,l," ","",s),(0,o.drawBorder)(e,p,"TRADE");const h=d+2,m=c-4;let g=1;const f="buy"===a.action?o.CLR.green:o.CLR.red,y="buy"===a.action?"BUY":"SELL";e.writeStyled(u+g,h,[{text:y+" ",fg:f},{text:a.side.toUpperCase()+" ",fg:o.CLR.emerald},{text:a.ticker,fg:o.CLR.white}]),g+=2;const $=n.positions.find(e=>(e.ticker_symbol||e.ticker)===a.ticker),w=$?.bestBid??$?.current_value??0,k=$?.bestAsk??w+2;e.writeStyled(u+g,h,[{text:"Bid: ",fg:o.CLR.dim},{text:`${w}¢`,fg:o.CLR.green},{text:" Ask: ",fg:o.CLR.dim},{text:`${k}¢`,fg:o.CLR.red}]),g+=2;const b="qty"===n.tradeField,v=b?r:i;e.write(u+g,h,"Quantity:",o.CLR.dim,s),e.write(u+g,h+12,(0,o.fit)(String(a.qty),10),b?o.CLR.emerald:o.CLR.text,v),b&&e.write(u+g,h+22," ◀",o.CLR.emerald,s);g++;const _="price"===n.tradeField,S=_?r:i;e.write(u+g,h,"Price (¢):",o.CLR.dim,s),e.write(u+g,h+12,(0,o.fit)(String(a.price),10),_?o.CLR.emerald:o.CLR.text,S),_&&e.write(u+g,h+22," ◀",o.CLR.emerald,s);g+=2;const x=a.qty*a.price/100,C=a.qty,O=C-x;e.write(u+g,h,"Preview:",o.CLR.title,s),g++,e.writeStyled(u+g,h,[{text:`Max cost: $${x.toFixed(2)}`,fg:o.CLR.dim}]),g++,e.writeStyled(u+g,h,[{text:`Max payout: $${C.toFixed(2)}`,fg:o.CLR.dim}]),g++,e.writeStyled(u+g,h,[{text:"Profit: ",fg:o.CLR.dim},{text:`$${O.toFixed(2)}`,fg:O>=0?o.CLR.green:o.CLR.red}]),g++;const I=n.edges.find(e=>(e.ticker||e.marketId)===a.ticker);if(I){const t=I.edge??I.value??0;e.writeStyled(u+g,h,[{text:"Edge: ",fg:o.CLR.dim},{text:`${t>=0?"+":""}${t}¢`,fg:t>=0?o.CLR.green:o.CLR.red}]),g++}const P=Math.max(0,a.price-w);P>0&&(e.writeStyled(u+g,h,[{text:"Slippage: ",fg:o.CLR.dim},{text:`~${P}¢`,fg:o.CLR.yellow}]),g++);if(g++,n.tradeCountdown>0){const t=` Executing in ${n.tradeCountdown}... `,i=h+Math.floor((m-t.length)/2);e.write(u+g,i,t,o.CLR.yellow,s)}else 0===n.tradeCountdown?e.write(u+g,h+Math.floor((m-12)/2)," EXECUTING ",o.CLR.white,(0,o.bgRgb)(16,120,80)):e.write(u+g,h+Math.floor((m-24)/2),"Press Enter to confirm",o.CLR.dim,s)};const o=n(77096),s=(0,o.bgRgb)(18,18,22),i=(0,o.bgRgb)(30,30,35),r=(0,o.bgRgb)(16,50,40)},29405:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderWhatif=function(e,t,n){(0,o.drawBorder)(e,t,"WHAT-IF SCENARIO");const i=t.col+2,r=t.width-4;let a=1;if(!n.whatifResult)return void e.write(t.row+a,i,'No what-if data. Press "w" from overview to start.',o.CLR.dim);const c=n.whatifResult,l=c.scenarios||c.overrides||[],d=Math.floor(r/2)-2;if(e.write(t.row+a,i,"Scenarios:",o.CLR.title),a++,0===l.length)e.write(t.row+a,i," (no scenarios available)",o.CLR.dim),a+=2;else{for(let c=0;c<l.length&&!(a>=t.height-8);c++){const d=l[c],u=n.whatifScenarioIndex===c,p=u?"▸ ":" ",h=d.name||d.description||d.nodeId||`Scenario ${c+1}`,m=u?s:"";e.write(t.row+a,i,(0,o.fit)(`${p}${h}`,r),u?o.CLR.white:o.CLR.text,m),a++}a++}for(let n=i;n<i+r;n++)e.write(t.row+a,n,"─",o.CLR.borderDim);a++;const u=i,p=i+d+3;e.write(t.row+a,u,(0,o.fit)("BEFORE",d),o.CLR.title),e.write(t.row+a,p,(0,o.fit)("AFTER",d),o.CLR.title),a++;const h=c.before||c.current||{},m=c.after||c.proposed||{},g=null!=h.confidence?`${Math.round(100*h.confidence)}%`:"?%",f=null!=m.confidence?`${Math.round(100*m.confidence)}%`:"?%",y=(m.confidence??0)-(h.confidence??0),$=y>=0?`+${Math.round(100*y)}%`:`${Math.round(100*y)}%`;e.writeStyled(t.row+a,u,[{text:"Confidence: ",fg:o.CLR.dim},{text:g,fg:o.CLR.text}]),e.writeStyled(t.row+a,p,[{text:"Confidence: ",fg:o.CLR.dim},{text:f,fg:o.CLR.text},{text:` (${$})`,fg:y>=0?o.CLR.green:o.CLR.red}]),a++;const w=h.edges||[],k=m.edges||[];e.write(t.row+a,u,"Edges:",o.CLR.dim),e.write(t.row+a,p,"Edges:",o.CLR.dim),a++;const b=Math.min(Math.max(w.length,k.length),t.height-a-3);for(let n=0;n<b;n++){const s=w[n],i=k[n];if(s){const n=(s.market||s.ticker||"").slice(0,d-10),i=`${s.edge>=0?"+":""}${s.edge}`;e.writeStyled(t.row+a,u,[{text:(0,o.fit)(n,d-8),fg:o.CLR.text},{text:(0,o.fit)(i,6,"right"),fg:s.edge>=0?o.CLR.green:o.CLR.red}])}if(i){const n=(i.market||i.ticker||"").slice(0,d-10),r=`${i.edge>=0?"+":""}${i.edge}`,c=i.edgeDelta??i.edge-(s?.edge??0),l=c>=0?`+${c}`:`${c}`;e.writeStyled(t.row+a,p,[{text:(0,o.fit)(n,d-14),fg:o.CLR.text},{text:(0,o.fit)(r,6,"right"),fg:i.edge>=0?o.CLR.green:o.CLR.red},{text:(0,o.fit)(l,6,"right"),fg:c>=0?o.CLR.green:o.CLR.red}])}a++}if(a<t.height-2){a++;const n=c.pnlImpact??c.pnl_impact;null!=n&&e.writeStyled(t.row+a,i,[{text:"P&L Impact: ",fg:o.CLR.dim},{text:`${n>=0?"+":""}$${Math.abs(n).toFixed(2)}`,fg:n>=0?o.CLR.green:o.CLR.red}])}};const o=n(77096),s=(0,o.bgRgb)(25,25,30)},99236:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.c=void 0,t.vol=function(e){if(null==e)return"-";const t="string"==typeof e?parseFloat(e):e;return isNaN(t)?"-":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(0)}K`:t.toString()},t.cents=function(e){if(null==e)return"-";const t="string"==typeof e?parseFloat(e):e;return isNaN(t)?"-":`${Math.round(100*t)}¢`},t.pct=function(e){if(null==e)return"-";const t="string"==typeof e?parseFloat(e):e;return isNaN(t)?"-":`${Math.round(100*t)}%`},t.delta=function(e){const t=e>0?"↑":e<0?"↓":"→",n=e>0?"+":"";return`${t} ${n}${Math.round(100*e)}%`},t.shortDate=function(e){if(!e)return"-";try{const t=new Date(e),n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()],o=t.getDate(),s=t.getHours().toString().padStart(2,"0");return`${n} ${o} ${s}:${t.getMinutes().toString().padStart(2,"0")}`}catch{return e.slice(0,16)}},t.pad=function(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)},t.rpad=function(e,t){return e.length>=t?e.slice(0,t):" ".repeat(t-e.length)+e},t.hr=function(e=80){console.log(t.c.dim+"─".repeat(e)+t.c.reset)},t.die=function(e){console.error(`${t.c.red}Error:${t.c.reset} ${e}`),process.exit(1)},t.errorWithHint=function(e,n){console.error(`\n ${t.c.red}Error:${t.c.reset} ${e}`),n&&console.error(` ${t.c.dim}${n}${t.c.reset}`);console.error()},t.emptyState=function(e,n){console.log(`\n ${t.c.dim}No ${e} found.${t.c.reset}`),n&&console.log(` ${t.c.dim}${n}${t.c.reset}`);console.log()},t.header=function(e){console.log(`\n${t.c.bold}${t.c.cyan}${e}${t.c.reset}`)},t.trunc=function(e,t){return e.length<=t?e:e.slice(0,t-1)+"…"},t.shortId=function(e){return e.slice(0,8)},t.c={reset:"",bold:"",dim:"",red:"",green:"",yellow:"",blue:"",magenta:"",cyan:"",white:"",gray:""}},42613:e=>{"use strict";e.exports=require("assert")},20181:e=>{"use strict";e.exports=require("buffer")},35317:e=>{"use strict";e.exports=require("child_process")},76982:e=>{"use strict";e.exports=require("crypto")},24434:e=>{"use strict";e.exports=require("events")},79896:e=>{"use strict";e.exports=require("fs")},91943:e=>{"use strict";e.exports=require("fs/promises")},58611:e=>{"use strict";e.exports=require("http")},65692:e=>{"use strict";e.exports=require("https")},69278:e=>{"use strict";e.exports=require("net")},4573:e=>{"use strict";e.exports=require("buffer")},31421:e=>{"use strict";e.exports=require("child_process")},78474:e=>{"use strict";e.exports=require("events")},73024:e=>{"use strict";e.exports=require("fs")},37067:e=>{"use strict";e.exports=require("http")},44708:e=>{"use strict";e.exports=require("https")},98995:e=>{"use strict";e.exports=require("node:module")},77030:e=>{"use strict";e.exports=require("net")},48161:e=>{"use strict";e.exports=require("os")},76760:e=>{"use strict";e.exports=require("path")},1708:e=>{"use strict";e.exports=require("process")},57075:e=>{"use strict";e.exports=require("stream")},46466:e=>{"use strict";e.exports=require("stream/promises")},37830:e=>{"use strict";e.exports=require("stream/web")},73136:e=>{"use strict";e.exports=require("url")},57975:e=>{"use strict";e.exports=require("util")},38522:e=>{"use strict";e.exports=require("zlib")},70857:e=>{"use strict";e.exports=require("os")},16928:e=>{"use strict";e.exports=require("path")},932:e=>{"use strict";e.exports=require("process")},24876:e=>{"use strict";e.exports=require("punycode")},83480:e=>{"use strict";e.exports=require("querystring")},23785:e=>{"use strict";e.exports=require("readline")},2203:e=>{"use strict";e.exports=require("stream")},64756:e=>{"use strict";e.exports=require("tls")},52018:e=>{"use strict";e.exports=require("tty")},87016:e=>{"use strict";e.exports=require("url")},39023:e=>{"use strict";e.exports=require("util")},28167:e=>{"use strict";e.exports=require("worker_threads")},43106:e=>{"use strict";e.exports=require("zlib")},18909:(e,t,n)=>{const{Argument:o}=n(49154),{Command:s}=n(34348),{CommanderError:i,InvalidArgumentError:r}=n(41135),{Help:a}=n(79754),{Option:c}=n(45240);t.program=new s,t.createCommand=e=>new s(e),t.createOption=(e,t)=>new c(e,t),t.createArgument=(e,t)=>new o(e,t),t.Command=s,t.Option=c,t.Argument=o,t.Help=a,t.CommanderError=i,t.InvalidArgumentError=r,t.InvalidOptionArgumentError=r},49154:(e,t,n)=>{const{InvalidArgumentError:o}=n(41135);t.Argument=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.length>3&&"..."===this._name.slice(-3)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t!==this.defaultValue&&Array.isArray(t)?t.concat(e):[e]}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new o(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(e,t):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}},t.humanReadableArgName=function(e){const t=e.name()+(!0===e.variadic?"...":"");return e.required?"<"+t+">":"["+t+"]"}},34348:(e,t,n)=>{const o=n(78474).EventEmitter,s=n(31421),i=n(76760),r=n(73024),a=n(1708),{Argument:c,humanReadableArgName:l}=n(49154),{CommanderError:d}=n(41135),{Help:u}=n(79754),{Option:p,DualOptions:h}=n(45240),{suggestSimilar:m}=n(65030);class g extends o{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:e=>a.stdout.write(e),writeErr:e=>a.stderr.write(e),getOutHelpWidth:()=>a.stdout.isTTY?a.stdout.columns:void 0,getErrHelpWidth:()=>a.stderr.isTTY?a.stderr.columns:void 0,outputError:(e,t)=>t(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){const e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let o=t,s=n;"object"==typeof o&&null!==o&&(s=o,o=null),s=s||{};const[,i,r]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(i);return o&&(a.description(o),a._executableHandler=!0),s.isDefault&&(this._defaultCommandName=a._name),a._hidden=!(!s.noHelp&&!s.hidden),a._executableFile=s.executableFile||null,r&&a.arguments(r),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),o?this:a}createCommand(e){return new g(e)}createHelp(){return Object.assign(new u,this.configureHelp())}configureHelp(e){return void 0===e?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return void 0===e?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return"string"!=typeof e&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error("Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()");return(t=t||{}).isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new c(e,t)}argument(e,t,n,o){const s=this.createArgument(e,t);return"function"==typeof n?s.default(o).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){const t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&void 0!==e.defaultValue&&void 0===e.parseArg)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if("boolean"==typeof e)return this._addImplicitHelpCommand=e,this;e=e??"help [command]";const[,n,o]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",i=this.createCommand(n);return i.helpOption(!1),o&&i.arguments(o),s&&i.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=i,this}addHelpCommand(e,t){return"object"!=typeof e?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(void 0===this._helpCommand&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){const n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.\nExpecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if("commander.executeSubCommandAsync"!==e.code)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new d(e,t,n)),a.exit(e)}action(e){return this._actionHandler=t=>{const n=this.registeredArguments.length,o=t.slice(0,n);return this._storeOptionsAsProperties?o[n]=this:o[n]=this.opts(),o.push(this),e.apply(this,o)},this}createOption(e,t){return new p(e,t)}_callParseArg(e,t,n,o){try{return e.parseArg(t,n)}catch(e){if("commander.invalidArgument"===e.code){const t=`${o} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){const t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){const n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'\n- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){const t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){const o=t(this._findCommand(n)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${o}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);const t=e.name(),n=e.attributeName();if(e.negate){const t=e.long.replace(/^--no-/,"--");this._findOption(t)||this.setOptionValueWithSource(n,void 0===e.defaultValue||e.defaultValue,"default")}else void 0!==e.defaultValue&&this.setOptionValueWithSource(n,e.defaultValue,"default");const o=(t,o,s)=>{null==t&&void 0!==e.presetArg&&(t=e.presetArg);const i=this.getOptionValue(n);null!==t&&e.parseArg?t=this._callParseArg(e,t,i,o):null!==t&&e.variadic&&(t=e._concatValue(t,i)),null==t&&(t=!e.negate&&(!(!e.isBoolean()&&!e.optional)||"")),this.setOptionValueWithSource(n,t,s)};return this.on("option:"+t,t=>{const n=`error: option '${e.flags}' argument '${t}' is invalid.`;o(t,n,"cli")}),e.envVar&&this.on("optionEnv:"+t,t=>{const n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;o(t,n,"env")}),this}_optionEx(e,t,n,o,s){if("object"==typeof t&&t instanceof p)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const i=this.createOption(t,n);if(i.makeOptionMandatory(!!e.mandatory),"function"==typeof o)i.default(s).argParser(o);else if(o instanceof RegExp){const e=o;o=(t,n)=>{const o=e.exec(t);return o?o[0]:n},i.default(s).argParser(o)}else i.default(o);return this.addOption(i)}option(e,t,n,o){return this._optionEx({},e,t,n,o)}requiredOption(e,t,n,o){return this._optionEx({mandatory:!0},e,t,n,o)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{void 0!==n.getOptionValueSource(e)&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(void 0!==e&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},void 0===e&&void 0===t.from){a.versions?.electron&&(t.from="electron");const e=a.execArgv??[];(e.includes("-e")||e.includes("--eval")||e.includes("-p")||e.includes("--print"))&&(t.from="eval")}let n;switch(void 0===e&&(e=a.argv),this.rawArgs=e.slice(),t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":a.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){const n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){const n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1;const o=[".js",".ts",".tsx",".mjs",".cjs"];function c(e,t){const n=i.resolve(e,t);if(r.existsSync(n))return n;if(o.includes(i.extname(t)))return;const s=o.find(e=>r.existsSync(`${n}${e}`));return s?`${n}${s}`:void 0}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let l,u=e._executableFile||`${this._name}-${e._name}`,p=this._executableDir||"";if(this._scriptPath){let e;try{e=r.realpathSync(this._scriptPath)}catch(t){e=this._scriptPath}p=i.resolve(i.dirname(e),p)}if(p){let t=c(p,u);if(!t&&!e._executableFile&&this._scriptPath){const n=i.basename(this._scriptPath,i.extname(this._scriptPath));n!==this._name&&(t=c(p,`${n}-${e._name}`))}u=t||u}if(n=o.includes(i.extname(u)),"win32"!==a.platform?n?(t.unshift(u),t=f(a.execArgv).concat(t),l=s.spawn(a.argv[0],t,{stdio:"inherit"})):l=s.spawn(u,t,{stdio:"inherit"}):(t.unshift(u),t=f(a.execArgv).concat(t),l=s.spawn(a.execPath,t,{stdio:"inherit"})),!l.killed){["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(e=>{a.on(e,()=>{!1===l.killed&&null===l.exitCode&&l.kill(e)})})}const h=this._exitCallback;l.on("close",e=>{e=e??1,h?h(new d(e,"commander.executeSubCommandAsync","(close)")):a.exit(e)}),l.on("error",t=>{if("ENOENT"===t.code){const t=p?`searched for local subcommand relative to directory '${p}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",n=`'${u}' does not exist\n - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${t}`;throw new Error(n)}if("EACCES"===t.code)throw new Error(`'${u}' not executable`);if(h){const e=new d(1,"commander.executeSubCommandAsync","(error)");e.nestedError=t,h(e)}else a.exit(1)}),this.runningCommand=l}_dispatchSubcommand(e,t,n){const o=this._findCommand(e);let s;return o||this.help({error:!0}),s=this._chainOrCallSubCommandHook(s,o,"preSubcommand"),s=this._chainOrCall(s,()=>{if(!o._executableHandler)return o._parseCommand(t,n);this._executeSubCommand(o,t.concat(n))}),s}_dispatchHelpCommand(e){e||this.help();const t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&null==this.args[t]&&this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic||this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const e=(e,t,n)=>{let o=t;if(null!==t&&e.parseArg){const s=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;o=this._callParseArg(e,t,n,s)}return o};this._checkNumberOfArguments();const t=[];this.registeredArguments.forEach((n,o)=>{let s=n.defaultValue;n.variadic?o<this.args.length?(s=this.args.slice(o),n.parseArg&&(s=s.reduce((t,o)=>e(n,o,t),n.defaultValue))):void 0===s&&(s=[]):o<this.args.length&&(s=this.args[o],n.parseArg&&(s=e(n,s,n.defaultValue))),t[o]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&"function"==typeof e.then?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e;const o=[];return this._getCommandAndAncestors().reverse().filter(e=>void 0!==e._lifeCycleHooks[t]).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{o.push({hookedCommand:e,callback:t})})}),"postAction"===t&&o.reverse(),o.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let o=e;return void 0!==this._lifeCycleHooks[n]&&this._lifeCycleHooks[n].forEach(e=>{o=this._chainOrCall(o,()=>e(this,t))}),o}_parseCommand(e,t){const n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);!this.commands.length||0!==this.args.length||this._actionHandler||this._defaultCommandName||this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const o=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){let n;return o(),this._processArguments(),n=this._chainOrCallHooks(n,"preAction"),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(s,e,t)})),n=this._chainOrCallHooks(n,"postAction"),n}if(this.parent&&this.parent.listenerCount(s))o(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&void 0===e.getOptionValue(t.attributeName())&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){const e=this.options.filter(e=>{const t=e.attributeName();return void 0!==this.getOptionValue(t)&&"default"!==this.getOptionValueSource(t)});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{const n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){const t=[],n=[];let o=t;const s=e.slice();function i(e){return e.length>1&&"-"===e[0]}let r=null;for(;s.length;){const e=s.shift();if("--"===e){o===n&&o.push(e),o.push(...s);break}if(!r||i(e)){if(r=null,i(e)){const t=this._findOption(e);if(t){if(t.required){const e=s.shift();void 0===e&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,e)}else if(t.optional){let e=null;s.length>0&&!i(s[0])&&(e=s.shift()),this.emit(`option:${t.name()}`,e)}else this.emit(`option:${t.name()}`);r=t.variadic?t:null;continue}}if(e.length>2&&"-"===e[0]&&"-"!==e[1]){const t=this._findOption(`-${e[1]}`);if(t){t.required||t.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${t.name()}`,e.slice(2)):(this.emit(`option:${t.name()}`),s.unshift(`-${e.slice(2)}`));continue}}if(/^--[^=]+=/.test(e)){const t=e.indexOf("="),n=this._findOption(e.slice(0,t));if(n&&(n.required||n.optional)){this.emit(`option:${n.name()}`,e.slice(t+1));continue}}if(i(e)&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&0===t.length&&0===n.length){if(this._findCommand(e)){t.push(e),s.length>0&&n.push(...s);break}if(this._getHelpCommand()&&e===this._getHelpCommand().name()){t.push(e),s.length>0&&t.push(...s);break}if(this._defaultCommandName){n.push(e),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){o.push(e),s.length>0&&o.push(...s);break}o.push(e)}else this.emit(`option:${r.name()}`,e)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){const e={},t=this.options.length;for(let n=0;n<t;n++){const t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),"string"==typeof this._showHelpAfterError?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr("\n"),this.outputHelp({error:!0}));const n=t||{},o=n.exitCode||1,s=n.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in a.env){const t=e.attributeName();(void 0===this.getOptionValue(t)||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,a.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){const e=new h(this.options),t=e=>void 0!==this.getOptionValue(e)&&!["default","implied"].includes(this.getOptionValueSource(e));this.options.filter(n=>void 0!==n.implied&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],"implied")})})}missingArgument(e){const t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){const t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){const t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){const n=e=>{const t=e.attributeName(),n=this.getOptionValue(t),o=this.options.find(e=>e.negate&&t===e.attributeName()),s=this.options.find(e=>!e.negate&&t===e.attributeName());return o&&(void 0===o.presetArg&&!1===n||void 0!==o.presetArg&&n===o.presetArg)?o:s||e},o=e=>{const t=n(e),o=t.attributeName();return"env"===this.getOptionValueSource(o)?`environment variable '${t.envVar}'`:`option '${t.flags}'`},s=`error: ${o(e)} cannot be used with ${o(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],o=this;do{const e=o.createHelp().visibleOptions(o).filter(e=>e.long).map(e=>e.long);n=n.concat(e),o=o.parent}while(o&&!o._enablePositionalOptions);t=m(e,n)}const n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;const t=this.registeredArguments.length,n=1===t?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){const e=this.args[0];let t="";if(this._showSuggestionAfterError){const n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=m(e,n)}const n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(void 0===e)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";const o=this.createOption(t,n);return this._versionOptionName=o.attributeName(),this._registerOption(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,"commander.version",e)}),this}description(e,t){return void 0===e&&void 0===t?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return void 0===e?this._summary:(this._summary=e,this)}alias(e){if(void 0===e)return this._aliases[0];let t=this;if(0!==this.commands.length&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");const n=this.parent?._findCommand(e);if(n){const t=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return void 0===e?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(void 0===e){if(this._usage)return this._usage;const e=this.registeredArguments.map(e=>l(e));return[].concat(this.options.length||null!==this._helpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=e,this}name(e){return void 0===e?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=i.basename(e,i.extname(e)),this}executableDir(e){return void 0===e?this._executableDir:(this._executableDir=e,this)}helpInformation(e){const t=this.createHelp();return void 0===t.helpWidth&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){const t={error:!!(e=e||{}).error};let n;return n=t.error?e=>this._outputConfiguration.writeErr(e):e=>this._outputConfiguration.writeOut(e),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;"function"==typeof e&&(t=e,e=void 0);const n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(e=>e.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let o=this.helpInformation(n);if(t&&(o=t(o),"string"!=typeof o&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(e=>e.emit("afterAllHelp",n))}helpOption(e,t){return"boolean"==typeof e?(this._helpOption=e?this._helpOption??void 0:null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return void 0===this._helpOption&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=a.exitCode||0;0===t&&e&&"function"!=typeof e&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){const n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${n.join("', '")}'`);const o=`${e}Help`;return this.on(o,e=>{let n;n="function"==typeof t?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){const t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function f(e){return e.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n,o="127.0.0.1",s="9229";return null!==(n=e.match(/^(--inspect(-brk)?)$/))?t=n[1]:null!==(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))?(t=n[1],/^\d+$/.test(n[3])?s=n[3]:o=n[3]):null!==(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(t=n[1],o=n[3],s=n[4]),t&&"0"!==s?`${t}=${o}:${parseInt(s)+1}`:e})}t.Command=g},41135:(e,t)=>{class n extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}t.CommanderError=n,t.InvalidArgumentError=class extends n{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}},79754:(e,t,n)=>{const{humanReadableArgName:o}=n(49154);t.Help=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){const t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){const n=e=>e.short?e.short.replace(/^-/,""):e.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){const t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){const o=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);o||s?n.long&&!s?t.push(e.createOption(n.long,n.description)):n.short&&!o&&t.push(e.createOption(n.short,n.description)):t.push(n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];const t=[];for(let n=e.parent;n;n=n.parent){const e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){const t=e.registeredArguments.map(e=>o(e)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,t.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,t.argumentTerm(n).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let t=e.parent;t;t=t.parent)n=t.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){const t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(", ")}`),void 0!==e.defaultValue){(e.required||e.optional||e.isBoolean()&&"boolean"==typeof e.defaultValue)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}return void 0!==e.presetArg&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),void 0!==e.envVar&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){const t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(", ")}`),void 0!==e.defaultValue&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){const n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){const n=t.padWidth(e,t),o=t.helpWidth||80;function s(e,s){if(s){const i=`${e.padEnd(n+2)}${s}`;return t.wrap(i,o-2,n+2)}return e}function i(e){return e.join("\n").replace(/^/gm," ".repeat(2))}let r=[`Usage: ${t.commandUsage(e)}`,""];const a=t.commandDescription(e);a.length>0&&(r=r.concat([t.wrap(a,o,0),""]));const c=t.visibleArguments(e).map(e=>s(t.argumentTerm(e),t.argumentDescription(e)));c.length>0&&(r=r.concat(["Arguments:",i(c),""]));const l=t.visibleOptions(e).map(e=>s(t.optionTerm(e),t.optionDescription(e)));if(l.length>0&&(r=r.concat(["Options:",i(l),""])),this.showGlobalOptions){const n=t.visibleGlobalOptions(e).map(e=>s(t.optionTerm(e),t.optionDescription(e)));n.length>0&&(r=r.concat(["Global Options:",i(n),""]))}const d=t.visibleCommands(e).map(e=>s(t.subcommandTerm(e),t.subcommandDescription(e)));return d.length>0&&(r=r.concat(["Commands:",i(d),""])),r.join("\n")}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,o=40){const s=new RegExp("[\\n][ \\f\\t\\v   -    \ufeff]+");if(e.match(s))return e;const i=t-n;if(i<o)return e;const r=e.slice(0,n),a=e.slice(n).replace("\r\n","\n"),c=" ".repeat(n),l="\\s​",d=new RegExp(`\n|.{1,${i-1}}([${l}]|$)|[^${l}]+?([${l}]|$)`,"g");return r+(a.match(d)||[]).map((e,t)=>"\n"===e?"":(t>0?c:"")+e.trimEnd()).join("\n")}}},45240:(e,t,n)=>{const{InvalidArgumentError:o}=n(41135);t.Option=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;const n=function(e){let t,n;const o=e.split(/[ |,]+/);o.length>1&&!/^[[<]/.test(o[1])&&(t=o.shift());n=o.shift(),!t&&/^-[^-]$/.test(n)&&(t=n,n=void 0);return{shortFlag:t,longFlag:n}}(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return"string"==typeof e&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t!==this.defaultValue&&Array.isArray(t)?t.concat(e):[e]}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new o(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(e,t):e},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return function(e){return e.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},t.DualOptions=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){const n=t.attributeName();if(!this.dualOptions.has(n))return!0;const o=this.negativeOptions.get(n).presetArg,s=void 0!==o&&o;return t.negate===(s===e)}}},65030:(e,t)=>{function n(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);const n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let o=1;o<=t.length;o++)for(let s=1;s<=e.length;s++){let i=1;i=e[s-1]===t[o-1]?0:1,n[s][o]=Math.min(n[s-1][o]+1,n[s][o-1]+1,n[s-1][o-1]+i),s>1&&o>1&&e[s-1]===t[o-2]&&e[s-2]===t[o-1]&&(n[s][o]=Math.min(n[s][o],n[s-2][o-2]+1))}return n[e.length][t.length]}t.suggestSimilar=function(e,t){if(!t||0===t.length)return"";t=Array.from(new Set(t));const o=e.startsWith("--");o&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let s=[],i=3;return t.forEach(t=>{if(t.length<=1)return;const o=n(e,t),r=Math.max(e.length,t.length);(r-o)/r>.4&&(o<i?(i=o,s=[t]):o===i&&s.push(t))}),s.sort((e,t)=>e.localeCompare(t)),o&&(s=s.map(e=>`--${e}`)),s.length>1?`\n(Did you mean one of ${s.join(", ")}?)`:1===s.length?`\n(Did you mean ${s[0]}?)`:""}}},t={};function n(o){var s=t[o];if(void 0!==s)return s.exports;var i=t[o]={exports:{}},r=!0;try{e[o].call(i.exports,i,i.exports,n),r=!1}finally{r&&delete t[o]}return i.exports}n.m=e,(()=>{var e,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;n.t=function(o,s){if(1&s&&(o=this(o)),8&s)return o;if("object"==typeof o&&o){if(4&s&&o.__esModule)return o;if(16&s&&"function"==typeof o.then)return o}var i=Object.create(null);n.r(i);var r={};e=e||[null,t({}),t([]),t(t)];for(var a=2&s&&o;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach(e=>r[e]=()=>o[e]);return r.default=()=>o,n.d(i,r),i}})(),n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce((t,o)=>(n.f[o](e,t),t),[])),n.u=e=>e+".index.js",n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},void 0!==n&&(n.ab=__dirname+"/"),(()=>{var e={792:1};n.f.require=(t,o)=>{e[t]||(t=>{var o=t.modules,s=t.ids,i=t.runtime;for(var r in o)n.o(o,r)&&(n.m[r]=o[r]);i&&i(n);for(var a=0;a<s.length;a++)e[s[a]]=1})(require("./"+n.u(t)))}})();var o={};(()=>{"use strict";var e=o;Object.defineProperty(e,"__esModule",{value:!0});const t=n(18909),s=n(11627),i=n(19218),r=n(38706),a=n(5596),c=n(97499),l=n(46222),d=n(67378),u=n(67509),p=n(46183),h=n(96007),m=n(8784),g=n(91262),f=n(83969),y=n(85417),$=n(40791),w=n(22835),k=n(60952),b=n(40239),v=n(8045),_=n(28423),S=n(96616),x=n(44040),C=n(45475),O=n(63746),I=n(44478),P=n(18691),T=n(34362),E=n(80928),A=n(58211),M=n(43423),R=n(72768),N=n(9708),L=n(33766),D=n(50984),K=n(69903),j=n(35344),F=n(71783),q=n(91993),U=n(81466),z=n(50869),H=n(87604),B=n(65240),J=n(23017),W=n(84436),X=n(15472),G=n(52072),Y=n(33192),V=n(30896),Q=n(72124),Z=n(99236);(0,s.applyConfig)();const ee=new t.Command,te='\nSimpleFunctions CLI — prediction market thesis agent\n\nUsage: sf <command> [options]\n sf <command> --help for detailed options\n\nSetup\n login Browser login (recommended)\n logout Clear saved credentials\n setup Interactive config wizard (power users)\n setup --check Show config status\n setup --polymarket Configure Polymarket wallet\n\nThesis\n list List all theses\n get <id> Full thesis details\n context [id] [--json] Market snapshot (no id) or thesis context (with id)\n create "thesis" Create a new thesis\n signal <id> "content" Inject a signal\n evaluate <id> Trigger deep evaluation\n augment <id> Evolve causal tree with new nodes\n publish / unpublish <id> Manage public visibility\n heartbeat <id> View/configure heartbeat settings & costs\n\nWorld Model (no auth)\n world Real-time world state (~800 tokens, prediction index + markets)\n world --delta What changed since last check (~30-50 tokens)\n world --focus energy,geo Deep coverage on specific topics\n ideas S&T-style trade ideas: conviction, catalyst, direction, risk\n\nSearch\n query "question" LLM-enhanced market knowledge search (no auth)\n markets Traditional markets: SPY, VIX, bonds, gold, oil (no auth)\n\nMarkets\n scan "keywords" Search Kalshi + Polymarket\n scan --series TICKER Browse a Kalshi series\n edges [--json] Top edges across all theses\n watch [query] [mode] Watch markets (modes: orderbook, flow, cross-venue, all)\n whatif <id> What-if scenario analysis\n liquidity [topic] Orderbook liquidity scanner\n book <ticker> [ticker2...] Orderbook depth for specific markets\n explore [slug] Browse public theses\n forecast <event> Market distribution (P50/P75/P90)\n\nShare (any command with --share generates a short URL)\n scan "gold" --share Share scan results\n query "fed rate" --share Share query results\n context --share Share global context snapshot\n\nPortfolio\n positions Kalshi + Polymarket positions\n balance Account balance\n orders Resting orders\n fills Recent trade fills\n settlements Settled contracts with P&L\n performance P&L over time\n dashboard Interactive TUI overview\n\nIntents (declarative execution — the single gateway for all orders)\n intent buy <ticker> <qty> Create buy intent with trigger conditions\n intent sell <ticker> <qty> Create sell intent\n intent list Active intents (--all for history)\n intent status <id> Detailed status + fills\n intent cancel <id> Cancel an intent\n\nTrading (requires sf setup --enable-trading)\n buy <ticker> <qty> Buy contracts (direct, no intent)\n sell <ticker> <qty> Sell contracts (direct, no intent)\n cancel [orderId] Cancel order(s)\n rfq <ticker> <qty> Request for quote\n\nRuntime\n runtime start Start execution daemon (evaluates triggers, places orders)\n runtime stop Stop daemon\n runtime status Active intents + runtime state\n\nInteractive\n agent [id] Agent with natural language + tools\n prompt [id] Dynamic system prompt for any agent\n telegram Telegram bot for monitoring\n\nX / Twitter\n x "query" Search X discussions (summary + raw mode)\n x-volume "query" Discussion volume and velocity trend\n x-news "query" X news stories (Grok-aggregated)\n x-account @username Recent posts from a specific account\n\nInfo\n feed Evaluation history stream\n delta <id> Changes since timestamp\n milestones Upcoming Kalshi events\n schedule Exchange status\n announcements Exchange announcements\n history <ticker> Historical market data\n';ee.name("sf").description("SimpleFunctions CLI — prediction market thesis agent").version("1.7.17").option("--api-key <key>","API key (or set SF_API_KEY env var)").option("--api-url <url>","API base URL (or set SF_API_URL env var)").configureHelp({formatHelp:(e,t)=>{if(!e.parent)return te;const{Help:o}=n(18909);return(new o).formatHelp(e,t)}}).action(async()=>{await async function(){if(!process.stdin.isTTY)return void console.log(te);const e=await Promise.resolve().then(n.t.bind(n,23785,23));if((0,s.isConfigured)())try{const e=new i.SFClient,{theses:t}=await e.listTheses(),n=(t||[]).filter(e=>"active"===e.status);if(n.length>0)return void await(0,f.agentCommand)(n[0].id,{})}catch{}console.log(),console.log(" SimpleFunctions — prediction market intelligence"),console.log(),(0,s.isConfigured)()?console.log(" You have no active theses."):console.log(" No login needed to explore.");console.log();const t=e.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),o=await new Promise(e=>{t.question(" What's your market view? (keyword or thesis)\n > ",n=>{t.close(),e(n.trim())})});if(!o)return void console.log(te);let r=o.replace(/[^\w\s]/g," ").split(/\s+/).filter(e=>e.length>2).slice(0,5).join(" ");r||(r=o.trim().slice(0,40));console.log(),console.log(` Scanning Kalshi + Polymarket for: "${r}"...`),console.log();try{const{scanCommand:e}=await Promise.resolve().then(n.bind(n,46183));await e(r,{json:!1})}catch(e){console.error(` Scan failed: ${e.message}`)}console.log(),(0,s.isConfigured)()?(console.log(" Want to monitor this thesis 24/7?"),console.log(` sf create "${o.slice(0,60)}"`)):(console.log(" Want 24/7 monitoring + edge detection?"),console.log(" sf setup to get started (2 min)"));console.log()}()});const ne=new Set(["setup","login","logout","help","status","scan","explore","query","context","markets","watch","milestones","forecast","settlements","balance","orders","fills","schedule","announcements","history","liquidity","book","prompt","sf"]);async function oe(e){try{await e()}catch(e){const t=e instanceof Error?e.message:String(e);process.argv.includes("--json")&&(console.log(JSON.stringify({error:t,code:e.code||"CLI_ERROR",status:e.status||1})),process.exit(1)),(0,Z.die)(t)}}ee.hook("preAction",(e,t)=>{const n=t.name();if(ne.has(n))return;if(!(e.optsWithGlobals?.()||e.opts()).apiKey&&!(0,s.isConfigured)()){process.argv.includes("--json")?console.log(JSON.stringify({error:"API key required.",code:"NOT_CONFIGURED",keyUrl:"https://simplefunctions.dev/dashboard/keys",cli:"sf login"})):(console.log(),console.log(" This command needs an API key. Three options:"),console.log(" 1. sf login Browser login (30 sec, recommended)"),console.log(" 2. sf setup Interactive wizard (2 min)"),console.log(" 3. sf --api-key KEY Pass inline"),console.log(),console.log(" Get a key at: https://simplefunctions.dev/dashboard/keys"),console.log(' No key? Try sf scan "oil" — works without login.')),console.log(),process.exit(1)}}),ee.command("setup").description("Interactive configuration wizard").option("--check","Show current configuration status").option("--reset","Delete config and start over").option("--key <key>","Set SF API key (non-interactive, for CI)").option("--enable-trading","Enable trading (sf buy/sell/cancel)").option("--disable-trading","Disable trading").option("--kalshi","Reconfigure Kalshi API credentials").option("--polymarket","Reconfigure Polymarket wallet address").action(async e=>{await oe(()=>(0,y.setupCommand)({check:e.check,reset:e.reset,key:e.key,enableTrading:e.enableTrading,disableTrading:e.disableTrading,kalshi:e.kalshi,polymarket:e.polymarket}))}),ee.command("login").description("Browser-based login (recommended — no API keys needed)").option("--force","Re-login even if already configured").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,z.loginCommand)({apiUrl:n.apiUrl,force:e.force}))}),ee.command("logout").description("Clear saved credentials").action(async()=>{await oe(async()=>{const{resetConfig:e,loadFileConfig:t}=await Promise.resolve().then(n.t.bind(n,11627,23));t().apiKey?(e(),console.log("\n Logged out. Credentials removed from ~/.sf/config.json"),console.log(` ${Z.c.dim}Run ${Z.c.cyan}sf login${Z.c.dim} to re-authenticate.${Z.c.reset}\n`)):console.log(`\n ${Z.c.dim}Not logged in.${Z.c.reset}\n`)})}),ee.command("status").description("Health check: verify API, auth, Kalshi, Polymarket connections").option("--json","JSON output").action(async e=>{await oe(()=>(0,Q.statusCommand)({json:e.json}))}),ee.command("list").description("List all theses").option("--json","JSON output").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,r.listCommand)({json:e.json,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("get <id>").description("Get full thesis details").option("--json","Output raw JSON").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,a.getCommand)(e,{json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("context [id]").description("Context snapshot. With ID: thesis-specific. Without: global market snapshot (no auth)").option("--json","Output raw JSON").option("--share","Share output via short URL").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,c.contextCommand)(e,{json:t.json,share:t.share,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("create <thesis>").description("Create a new thesis (sync by default — waits for formation)").option("--async","Async mode — return immediately without waiting").option("--json","JSON output").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,l.createCommand)(e,{async:t.async,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("signal <id> <content>").description("Inject a signal into the thesis queue").option("--type <type>","Signal type: news | user_note | external","user_note").option("--json","JSON output").action(async(e,t,n,o)=>{const s=o.optsWithGlobals();await oe(()=>(0,d.signalCommand)(e,t,{type:n.type,json:n.json,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ee.command("evaluate <id>").description("Trigger a deep evaluation (heavy model, force-heavy mode)").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,u.evaluateCommand)(e,{apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("heartbeat <id>").description("View/configure per-thesis heartbeat settings and costs").option("--news-interval <min>","News scan interval in minutes (15-1440)").option("--x-interval <min>","X/social scan interval in minutes (60-1440)").option("--model <tier>","Eval model tier: cheap, medium, heavy").option("--budget <usd>","Monthly budget cap in USD (0 = unlimited)").option("--pause","Pause heartbeat").option("--resume","Resume heartbeat").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>{const n=new i.SFClient(o.apiKey,o.apiUrl);return(0,H.heartbeatCommand)(n,e,{newsInterval:t.newsInterval,xInterval:t.xInterval,model:t.model,budget:t.budget,pause:t.pause,resume:t.resume})})}),ee.command("scan [query]").description("Explore Kalshi + Polymarket markets").option("--series <ticker>","List events + markets for a series (e.g. KXWTIMAX)").option("--market <ticker>","Get single market detail (e.g. KXWTIMAX-26DEC31-T140)").option("--venue <venue>","Filter by venue: kalshi, polymarket, or all (default: all)").option("--json","Output raw JSON").option("--share","Share output via short URL").action(async(e,t,n)=>{const o=n.optsWithGlobals(),s=e||"";s||t.series||t.market||(console.error('Usage: sf scan "keywords" OR sf scan --series TICKER OR sf scan --market TICKER'),process.exit(1)),await oe(()=>(0,p.scanCommand)(s,{series:t.series,market:t.market,venue:t.venue,json:t.json,share:t.share,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("watch [query] [mode]").description("Watch for market changes (modes: price, orderbook, flow, cross-venue, all)").option("--interval <seconds>","Poll interval in seconds (default: 60, 30 for orderbook)").option("--json","JSON change events (for piping)").option("--thesis <id>","Watch markets related to a thesis").option("--smart","LLM-enhanced noise filtering").option("--execute","Auto-create intents from triggers (requires --smart)").action(async(e,t,n)=>{await oe(()=>(0,h.watchCommand)(e,t,{interval:n.interval,json:n.json,thesis:n.thesis,smart:n.smart,execute:n.execute}))}),ee.command("edges").description("Top edges across all theses — what to trade now").option("--json","JSON output for agents").option("--share","Share output via short URL").option("--limit <n>","Max edges to show","20").option("--thesis <id>","Filter to a single thesis").option("--min-edge <cents>","Minimum absolute edge size in cents").option("--min-liquidity <grade>","Minimum liquidity (high/medium/low or A/B/C)").option("--sort <by>","Sort by: edge (default), spread").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,g.edgesCommand)({json:e.json,share:e.share,limit:e.limit,thesis:e.thesis,minEdge:e.minEdge,minLiquidity:e.minLiquidity,sort:e.sort,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("positions").description("Show Kalshi positions with thesis edge overlay (requires KALSHI_API_KEY_ID + KALSHI_PRIVATE_KEY_PATH)").option("--json","JSON output for agents").option("--thesis <id>","Filter by thesis ID").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,m.positionsCommand)({json:e.json,thesis:e.thesis,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("agent [thesisId]").description("Interactive agent mode — natural language interface to SimpleFunctions").option("--model <model>","Model via OpenRouter (default: anthropic/claude-sonnet-4.6)").option("--model-key <key>","OpenRouter API key (or set OPENROUTER_API_KEY)").option("--new","Start a fresh session (default: continue last session)").option("--plain","Plain text mode (no TUI, works in pipes and scripts)").action(async(e,t,n)=>{n.optsWithGlobals();await oe(()=>(0,f.agentCommand)(e,{model:t.model,modelKey:t.modelKey,newSession:t.new,noTui:t.plain}))}),ee.command("publish <thesisId>").description("Publish a thesis for public viewing").requiredOption("--slug <slug>","URL slug (lowercase, hyphens, 3-60 chars)").option("--description <desc>","Short description").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,$.publishCommand)(e,{slug:t.slug,description:t.description,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("unpublish <thesisId>").description("Remove a thesis from public viewing").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,$.unpublishCommand)(e,{apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("explore [slug]").description("Browse public theses (no auth required)").option("--json","JSON output").option("--share","Share output via short URL").action(async(e,t)=>{await oe(()=>(0,w.exploreCommand)(e,{json:t.json,share:t.share}))}),ee.command("dashboard").description("Portfolio overview — interactive TUI (default), or one-shot with --once/--json").option("--json","JSON output").option("--once","One-time print (no interactive mode)").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,k.dashboardCommand)({json:e.json,once:e.once,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("milestones").description("Upcoming events from Kalshi calendar. Use --category to filter (e.g., Economics, Politics, Financials, Climate)").option("--category <cat>","Filter by category (e.g., Economics, Politics, Financials, Climate, Sports)").option("--thesis <id>","Show milestones matching thesis edges").option("--hours <n>","Hours ahead (default 168)","168").option("--json","JSON output").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,v.milestonesCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("forecast <eventTicker>").description("Market distribution forecast (P50/P75/P90). Use EVENT ticker (e.g., KXWTIMAX-26DEC31), not series ticker.").option("--days <n>","Days of history (default 7)","7").option("--json","JSON output").action(async(e,t)=>{await oe(()=>(0,_.forecastCommand)(e,t))}),ee.command("settlements").description("Settled (resolved) contracts with P&L").option("--thesis <id>","Filter to thesis edge tickers").option("--json","JSON output").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,S.settlementsCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("balance").description("Kalshi account balance").option("--json","JSON output").action(async e=>{await oe(()=>(0,x.balanceCommand)(e))}),ee.command("orders").description("Kalshi resting orders").option("--status <status>","Order status filter (default: resting)","resting").option("--json","JSON output").action(async e=>{await oe(()=>(0,C.ordersCommand)(e))}),ee.command("fills").description("Recent trade fills").option("--ticker <ticker>","Filter by market ticker").option("--json","JSON output").action(async e=>{await oe(()=>(0,O.fillsCommand)(e))}),ee.command("feed").description("Evaluation history stream — what the heartbeat engine has been thinking").option("--hours <n>","Hours to look back (default 24)","24").option("--thesis <id>","Filter by thesis").option("--json","JSON output").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,I.feedCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("delta <thesisId>").description("Changes since a timestamp — confidence, nodes, signals, edges").option("--since <timestamp>","ISO 8601 start time (e.g., 2026-03-28T14:00:00Z)").option("--hours <n>","Hours to look back (default 6)","6").option("--watch","Continuously poll every 60s").option("--json","JSON output").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,U.deltaCommand)(e,{...t,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("whatif <thesisId>").description('What-if scenario — "if node X drops to 10%, what happens to my edges?"').option("--set <override>","Node override: nodeId=probability (0-1). Repeatable.",(e,t)=>[...t,e],[]).option("--json","JSON output").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,P.whatifCommand)(e,{set:t.set,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("schedule").description("Exchange status and trading hours").option("--json","JSON output").action(async e=>{await oe(()=>(0,A.scheduleCommand)(e))}),ee.command("buy <ticker> <qty>").description("Buy contracts (requires --enable-trading)").option("--price <cents>","Limit price in cents (required for limit orders)").option("--market","Market order (no price needed)").option("--side <s>","yes or no","yes").option("--yes-i-am-sure","Skip 3-second countdown").action(async(e,t,n)=>{await oe(()=>(0,T.buyCommand)(e,t,n))}),ee.command("sell <ticker> <qty>").description("Sell contracts (requires --enable-trading)").option("--price <cents>","Limit price in cents").option("--market","Market order").option("--side <s>","yes or no","yes").option("--yes-i-am-sure","Skip 3-second countdown").action(async(e,t,n)=>{await oe(()=>(0,T.sellCommand)(e,t,n))}),ee.command("cancel [orderId]").description("Cancel order(s) (requires --enable-trading)").option("--all","Cancel all resting orders").option("--ticker <t>","Cancel orders matching ticker prefix (with --all)").option("--yes-i-am-sure","Skip countdown").action(async(e,t)=>{await oe(()=>(0,E.cancelCommand)(e,t))}),ee.command("rfq <ticker> <qty>").description("Request for quote — large order pricing (requires --enable-trading)").option("--target-cost <cents>","Target cost per contract in cents").option("--rest-remainder","Rest unfilled portion as limit order").option("--json","JSON output").action(async(e,t,n)=>{await oe(()=>(0,M.rfqCommand)(e,t,n))}),ee.command("announcements").description("Exchange announcements (rule changes, maintenance)").option("--json","JSON output").action(async e=>{await oe(()=>(0,R.announcementsCommand)(e))}),ee.command("history <ticker>").description("Historical market data (settled/closed)").option("--json","JSON output").action(async(e,t)=>{await oe(()=>(0,N.historyCommand)(e,t))}),ee.command("performance").description("Portfolio P&L over time with thesis event annotations").option("--ticker <ticker>","Filter by ticker (fuzzy match)").option("--since <date>","Start date (ISO, e.g. 2026-03-01)").option("--json","JSON output").action(async e=>{await oe(()=>(0,L.performanceCommand)(e))}),ee.command("liquidity [topic]").description("Market liquidity scanner — run without args to see topics").option("--all","Scan all topics").option("--venue <venue>","Filter venue: kalshi, polymarket, all (default: all)").option("--horizon <horizon>","Filter horizon (weekly, monthly, long-term)").option("--min-depth <depth>","Minimum bid+ask depth",parseInt).option("--json","JSON output").action(async(e,t)=>{await oe(()=>(0,D.liquidityCommand)({...t,topic:e}))}),ee.command("book [tickers...]").description("Orderbook depth, spread, and liquidity for specific markets").option("--poly <query>","Search Polymarket markets by keyword").option("--history","Include 7-day price history sparkline").option("--json","JSON output").action(async(e,t)=>{0!==e.length||t.poly||(console.error('Usage: sf book <ticker> [ticker2...] OR sf book --poly "oil price"'),process.exit(1)),await oe(()=>(0,K.bookCommand)(e,t))}),ee.command("prompt [thesisId]").description("Get dynamic system prompt with live thesis state (for agent injection)").option("--sections <list>","Include: thesis,tree,edges,evaluation,orderbook (default: all)").option("--max-length <n>","Max character length (default: 3000)").option("--json","JSON format with metadata").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,j.promptCommand)(e,{sections:t.sections,maxLength:t.maxLength,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("augment <thesisId>").description("Review & merge suggested causal tree nodes from evaluations").option("--dry-run","Preview accepted nodes without applying").option("--json","JSON output").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,F.augmentCommand)(e,{dryRun:t.dryRun,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("markets").description("Traditional market snapshot — SPY, VIX, Treasury, Gold, Oil (no auth)").option("--json","JSON output").option("--share","Share output via short URL").action(async e=>{await oe(()=>(0,J.marketsCommand)({json:e.json,share:e.share}))}),ee.command("query <question>").description("LLM-enhanced prediction market knowledge search (no auth required)").option("--json","JSON output").option("--share","Share output via short URL").option("--limit <n>","Max results per category (default 10)","10").action(async(e,t)=>{await oe(()=>(0,B.queryCommand)(e,{json:t.json,share:t.share,limit:t.limit}))}),ee.command("telegram").description("Start Telegram bot for monitoring and trading").option("--token <token>","Telegram bot token (or set TELEGRAM_BOT_TOKEN)").option("--chat-id <id>","Restrict to specific chat ID").option("--daemon","Run in background").option("--stop","Stop background bot").option("--status","Check if bot is running").action(async e=>{await oe(()=>(0,q.telegramCommand)(e))}),ee.command("x <query>").description("Search X/Twitter discussions about a topic").option("--json","JSON output").option("--raw","Raw mode (no LLM summary)").option("--hours <n>","Hours to search back (default 24)","24").option("--limit <n>","Max results (default 20)","20").action(async(e,t)=>{await oe(()=>(0,W.xSearchCommand)(e,t))}),ee.command("x-volume <query>").description("X/Twitter discussion volume and velocity trend").option("--json","JSON output").option("--hours <n>","Hours to look back (default 72)","72").option("--granularity <g>","minute|hour|day (default hour)","hour").action(async(e,t)=>{await oe(()=>(0,W.xVolumeCommand)(e,t))}),ee.command("x-news <query>").description("X/Twitter news stories (Grok-aggregated)").option("--json","JSON output").option("--limit <n>","Max stories (default 10)","10").action(async(e,t)=>{await oe(()=>(0,W.xNewsCommand)(e,t))}),ee.command("x-account <username>").description("Recent posts from a specific X/Twitter account").option("--json","JSON output").option("--hours <n>","Hours to look back (default 24)","24").option("--limit <n>","Max posts (default 20)","20").action(async(e,t)=>{await oe(()=>(0,W.xAccountCommand)(e,t))}),ee.command("world").description("Real-time world state for agents (~800 tokens, no auth)").option("--json","JSON output").option("--delta","Incremental update only (what changed)").option("--since <window>","Time window for delta: 30m, 1h, 6h, 24h (default 1h)").option("--focus <topics>","Focus on topics: energy,geopolitics,crypto,policy,tech,economy").option("--share","Share output via short URL").action(async e=>{await oe(()=>(0,Y.worldCommand)(e))}),ee.command("ideas").description("S&T-style trade ideas: conviction, catalyst, direction, risk (no auth)").option("--json","JSON output").option("--category <cat>","Filter: macro, geopolitics, crypto, policy, event").option("--fresh <window>","Max cache age: 1h, 6h, 12h (default 12h)").option("--share","Share output via short URL").action(async e=>{await oe(()=>(0,V.ideasCommand)(e))}),(0,b.registerStrategies)(ee),(0,X.registerIntents)(ee),(0,G.registerRuntime)(ee),ee.parse()})(),module.exports=o})();
2
+ (()=>{var e={87783:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cached=async function(e,t,o){const s=n.get(e);if(s&&Date.now()<s.expiry)return s.data;try{const s=await o();return n.set(e,{data:s,expiry:Date.now()+t}),s}catch(e){if(s)return s.data;throw e}},t.invalidate=function(e){n.delete(e)},t.invalidateAll=function(){n.clear()};const n=new Map},19218:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SFClient=void 0,t.kalshiFetchAllSeries=async function(){const e=await o("/series",{include_volume:"true"});return e.series||[]},t.kalshiFetchEvents=async function(e){const t=await o("/events",{series_ticker:e,status:"open",with_nested_markets:"true",limit:"200"});return t.events||[]},t.kalshiFetchMarket=async function(e){const t=await o(`/markets/${e}`);return t.market||t},t.kalshiFetchMarketsBySeries=async function(e){const t=await o("/markets",{series_ticker:e,status:"open",limit:"200"});return t.markets||[]},t.kalshiFetchMarketsByEvent=async function(e){const t=await o("/markets",{event_ticker:e,status:"open",limit:"1000"});return t.markets||[]},t.fetchGlobalContext=async function(){const e=await fetch(`${s}/api/public/context`);if(!e.ok)throw new Error(`Context API error: ${e.status}`);return e.json()},t.fetchQuery=async function(e){const t=await fetch(`${s}/api/public/query?q=${encodeURIComponent(e)}`);if(!t.ok)throw new Error(`Query API error: ${t.status}`);return t.json()},t.fetchTraditionalMarkets=async function(){const e=await fetch(`${s}/api/public/markets`);if(!e.ok)throw new Error(`Markets API error: ${e.status}`);return e.json()};const n="https://api.elections.kalshi.com/trade-api/v2";async function o(e,t){const o=new URL(`${n}${e}`);if(t)for(const[e,n]of Object.entries(t))void 0!==n&&""!==n&&o.searchParams.set(e,n);const s=await fetch(o.toString());if(!s.ok)throw new Error(`Kalshi API ${s.status}: ${await s.text()}`);return s.json()}t.SFClient=class{apiKey;baseUrl;constructor(e,t){if(this.apiKey=e||process.env.SF_API_KEY||"",this.baseUrl=(t||process.env.SF_API_URL||"https://simplefunctions.dev").replace(/\/$/,""),!this.apiKey)throw new Error("API key required. Set SF_API_KEY or use --api-key")}async request(e,t,n){const o=`${this.baseUrl}${t}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},i=await fetch(o,{method:e,headers:s,body:n?JSON.stringify(n):void 0});if(!i.ok){let e=null;try{const t=await i.text();e=t?JSON.parse(t):null}catch{}const t=new Error(e?.error||e?.message||`API error ${i.status}`);throw t.status=i.status,t.code=e?.code||`HTTP_${i.status}`,t.details=e,t}return i.json()}async listTheses(){return this.request("GET","/api/thesis")}async getThesis(e){return this.request("GET",`/api/thesis/${e}`)}async getContext(e){return this.request("GET",`/api/thesis/${e}/context`)}async createThesis(e,t=!0){return this.request("POST",`/api/thesis/create?sync=${t}`,{rawThesis:e})}async injectSignal(e,t,n,o="cli"){return this.request("POST",`/api/thesis/${e}/signal`,{type:t,content:n,source:o})}async evaluate(e){return this.request("POST",`/api/thesis/${e}/evaluate`)}async getHeartbeatConfig(e){return this.request("GET",`/api/thesis/${e}/heartbeat`)}async updateHeartbeatConfig(e,t){return this.request("PATCH",`/api/thesis/${e}/heartbeat`,t)}async getFeed(e=24,t=200){return this.request("GET",`/api/feed?hours=${e}&limit=${t}`)}async getChanges(e,t){return this.request("GET",`/api/thesis/${e}/changes?since=${encodeURIComponent(t)}`)}async updateThesis(e,t){return this.request("PATCH",`/api/thesis/${e}`,t)}async publish(e,t,n){return this.request("POST",`/api/thesis/${e}/publish`,{slug:t,description:n})}async unpublish(e){return this.request("DELETE",`/api/thesis/${e}/publish`)}async augmentTree(e,t=!1){const n=t?"?dryRun=true":"";return this.request("POST",`/api/thesis/${e}/augment${n}`)}async getStrategies(e,t){const n=t?`?status=${t}`:"";return this.request("GET",`/api/thesis/${e}/strategies${n}`)}async createStrategyAPI(e,t){return this.request("POST",`/api/thesis/${e}/strategies`,t)}async updateStrategyAPI(e,t,n){return this.request("PATCH",`/api/thesis/${e}/strategies/${t}`,n)}async deleteStrategyAPI(e,t){return this.request("DELETE",`/api/thesis/${e}/strategies/${t}`)}async createIntent(e){return this.request("POST","/api/intents",e)}async listIntents(e){const t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.active&&t.set("active","true");const n=t.toString();return this.request("GET","/api/intents"+(n?"?"+n:""))}async getIntentDetail(e){return this.request("GET",`/api/intents/${e}`)}async cancelIntentAPI(e){return this.request("DELETE",`/api/intents/${e}`)}async searchX(e,t){const n=t?.mode||"summary",o=t?.hours||24,s=t?.limit||20;return this.request("GET",`/api/x/search?q=${encodeURIComponent(e)}&mode=${n}&hours=${o}&limit=${s}`)}async getXVolume(e,t){const n=t?.hours||72,o=t?.granularity||"hour";return this.request("GET",`/api/x/volume?q=${encodeURIComponent(e)}&hours=${n}&granularity=${o}`)}async searchXNews(e,t){const n=t?.limit||10;return this.request("GET",`/api/x/news?q=${encodeURIComponent(e)}&limit=${n}`)}async getXAccount(e,t){const n=e.replace(/^@/,""),o=t?.hours||24,s=t?.limit||20;return this.request("GET",`/api/x/account?username=${n}&hours=${o}&limit=${s}`)}};const s="https://simplefunctions.dev"},83969:function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.agentCommand=async function(e,t){const o=t?.modelKey||process.env.OPENROUTER_API_KEY,s=process.env.SF_API_KEY,i=process.env.SF_API_URL||"https://simplefunctions.dev",r=!o&&!!s,h=o||s,m=r?`${i}/api/proxy`:"https://openrouter.ai/api/v1";h||(console.error("Need an API key to power the agent LLM."),console.error(""),console.error(" Option 1 (recommended): sf login"),console.error(" Option 2: Get an OpenRouter key at https://openrouter.ai/keys"),console.error(" export OPENROUTER_API_KEY=sk-or-v1-..."),console.error(" sf agent --model-key sk-or-v1-..."),console.error(" sf setup (saves to ~/.sf/config.json)"),process.exit(1));if(r)console.log(" Using SimpleFunctions LLM proxy (no OpenRouter key needed)");else try{(await fetch("https://openrouter.ai/api/v1/auth/key",{headers:{Authorization:`Bearer ${h}`},signal:AbortSignal.timeout(8e3)})).ok||(console.error("OpenRouter API key is invalid or expired."),console.error("Get a new key at https://openrouter.ai/keys"),process.exit(1))}catch(e){const t=e instanceof Error?e.message:String(e);t.includes("timeout")||console.warn(`Warning: Could not verify OpenRouter key (${t}). Continuing anyway.`)}const y=new a.SFClient;let $,S=e||null,x=!1;if(!S){let e=[];try{const t=await y.listTheses();e=(t.theses||t).filter(e=>"active"===e.status)}catch{e=[]}if(0===e.length)x=!0;else if(1===e.length)S=e[0].id;else if(process.stdin.isTTY&&!t?.noTui){const t=await async function(e,t=!1){return new Promise(n=>{let o=0;const s=[];t&&s.push({id:"_explorer",conf:-1,title:"Explorer mode — no thesis, full market access"});for(const t of e){const e="number"==typeof t.confidence?Math.round(100*t.confidence):0,n=(t.rawThesis||t.thesis||t.title||"").slice(0,55);s.push({id:t.id,conf:e,title:n})}const i=process.stdout.write.bind(process.stdout);function r(){i(""),i("\n Select thesis\n\n");for(let e=0;e<s.length;e++){const t=s[e],n=e===o,r=n?" › ":" ";if("_explorer"===t.id){const e=n?`${t.title}`:`${t.title}`;i(`${r}${e}\n`)}else{const e=n?`${t.id.slice(0,8)}`:`${t.id.slice(0,8)}`,o=`${t.conf}%`,s=n?`${t.title}`:`${t.title}`;i(`${r}${e} ${o} ${s}\n`)}}i("\n ↑↓ navigate · enter select")}i("[?1049h"),i("[?25l"),r(),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");const a=e=>{const t=Buffer.from(e);27===t[0]&&91===t[1]&&65===t[2]?(o=(o-1+s.length)%s.length,r()):27===t[0]&&91===t[1]&&66===t[2]?(o=(o+1)%s.length,r()):"k"===e?(o=(o-1+s.length)%s.length,r()):"j"===e?(o=(o+1)%s.length,r()):"\r"===e||"\n"===e?(c(),n(s[o].id)):3===t[0]&&(c(),process.exit(0))};function c(){process.stdin.removeListener("data",a),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),i("[?25h"),i("[?1049l")}process.stdin.on("data",a)})}(e,!0);"_explorer"===t?x=!0:S=t}else S=e[0].id}if(x){const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));$=await e(),$._explorerMode=!0}else $=await y.getContext(S);if(t?.noTui)return async function(e){const{openrouterKey:t,sfClient:o,resolvedThesisId:s,opts:i,useProxy:r,llmBaseUrl:p,sfApiKey:h,sfApiUrl:m}=e;let y=e.latestContext;const $=await Promise.resolve().then(n.t.bind(n,23785,23)),w=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),k=await Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653)),{getModel:b,streamSimple:v,Type:_}=w,{Agent:S}=k,x=i?.model||"anthropic/claude-sonnet-4.6";let C=x.replace(/^openrouter\//,"");function O(e){let t;try{t=b("openrouter",e)}catch{t={modelId:e,provider:"openrouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",id:e,name:e,inputPrice:0,outputPrice:0,contextWindow:2e5,supportsImages:!0,supportsTools:!0}}return r&&(t.baseUrl=p),t}let I=O(C);const P=_.Object({thesisId:_.String({description:"Thesis ID"})}),T=_.Object({thesisId:_.String({description:"Thesis ID"}),content:_.String({description:"Signal content"}),type:_.Optional(_.String({description:"Signal type: news, user_note, external"}))}),E=_.Object({query:_.Optional(_.String({description:"Keyword search"})),series:_.Optional(_.String({description:"Series ticker"})),market:_.Optional(_.String({description:"Market ticker"}))}),A=_.Object({query:_.String({description:"Search keywords"})}),M=_.Object({}),R=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:P,execute:async(e,t)=>{const n=await o.getContext(t.thesisId);return y=n,{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"global_context",label:"Market Snapshot",description:"Global market snapshot — top movers, expiring contracts, milestones, liquidity, signals. No thesis needed.",parameters:M,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 knowledge search. Returns structured answer with live prices, thesis data, key factors.",parameters:_.Object({q:_.String({description:"Natural language query"})}),execute:async(e,t)=>{const{fetchQuery:o}=await Promise.resolve().then(n.bind(n,19218)),s=await o(t.q);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"get_markets",label:"Traditional Markets",description:"Traditional market prices via Databento: SPY, VIX, Treasury, Gold, Oil. Daily close + change.",parameters:M,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:"Inject Signal",description:"Inject a signal into the thesis",parameters:T,execute:async(e,t)=>{const n=await o.injectSignal(t.thesisId,t.type||"user_note",t.content);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"trigger_evaluation",label:"Evaluate",description:"Trigger a deep evaluation cycle",parameters:P,execute:async(e,t)=>{const n=await o.evaluate(t.thesisId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"scan_markets",label:"Scan Markets",description:"Search Kalshi prediction markets",parameters:E,execute:async(e,t)=>{let n;if(t.market)n=await(0,a.kalshiFetchMarket)(t.market);else if(t.series)n=await(0,a.kalshiFetchMarketsBySeries)(t.series);else if(t.query){const e=await(0,a.kalshiFetchAllSeries)(),o=t.query.toLowerCase().split(/\s+/);n=e.filter(e=>o.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,15)}else n={error:"Provide query, series, or market"};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"list_theses",label:"List Theses",description:"List all theses",parameters:M,execute:async()=>{const e=await o.listTheses();return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}},{name:"get_positions",label:"Get Positions",description:"Get Kalshi positions with live prices",parameters:M,execute:async()=>{const e=await(0,c.getPositions)();if(!e)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};for(const t of e){const e=await(0,c.getMarketPrice)(t.ticker);null!==e&&(t.current_value=e,t.unrealized_pnl=Math.round((e-t.average_price_paid)*t.quantity))}const t=e.map(e=>({ticker:e.ticker,side:e.side,quantity:e.quantity,avg_price:`${e.average_price_paid}¢`,current_price:`${e.current_value}¢`,unrealized_pnl:`$${(e.unrealized_pnl/100).toFixed(2)}`,total_cost:`$${(e.total_cost/100).toFixed(2)}`,realized_pnl:`$${(e.realized_pnl/100).toFixed(2)}`}));return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"web_search",label:"Web Search",description:"Search latest news and information",parameters:A,execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY;if(!n&&!(!n&&h))return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let o;if(o=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:5,search_depth:"basic",include_answer:!0})}):await fetch(`${m}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({query:t.query,max_results:5,search_depth:"basic",include_answer:!0})}),!o.ok)return{content:[{type:"text",text:`Search failed: ${o.status}`}],details:{}};const s=await o.json(),i=(s.results||[]).map(e=>`[${e.title}](${e.url})\n${e.content?.slice(0,200)}`).join("\n\n");return{content:[{type:"text",text:`${s.answer?`Summary: ${s.answer}\n\n---\n\n`:""}${i}`}],details:{}}}},{name:"get_milestones",label:"Milestones",description:"Get upcoming events from Kalshi calendar. Use to check economic releases, political events, or other catalysts.",parameters:_.Object({hours:_.Optional(_.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:_.Optional(_.String({description:"Filter by category (e.g. Economics, Politics, Sports)"}))}),execute:async(e,t)=>{const n=t.hours||168,o=new Date,s=`https://api.elections.kalshi.com/trade-api/v2/milestones?limit=200&minimum_start_date=${o.toISOString()}`+(t.category?`&category=${t.category}`:""),i=await fetch(s,{headers:{Accept:"application/json"}});if(!i.ok)return{content:[{type:"text",text:`Milestones API error: ${i.status}`}],details:{}};const r=await i.json(),a=o.getTime()+36e5*n,c=(r.milestones||[]).filter(e=>new Date(e.start_date).getTime()<=a).slice(0,30).map(e=>({title:e.title,category:e.category,start_date:e.start_date,related_event_tickers:e.related_event_tickers,hours_until:Math.round((new Date(e.start_date).getTime()-o.getTime())/36e5)}));return{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}}},{name:"get_forecast",label:"Forecast",description:"Get market distribution (P50/P75/P90 percentile history) for a Kalshi event.",parameters:_.Object({eventTicker:_.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:_.Optional(_.Number({description:"Days of history (default 7)"}))}),execute:async(e,t)=>{const{getForecastHistory:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=t.days||7,i=await fetch(`https://api.elections.kalshi.com/trade-api/v2/events/${t.eventTicker}`,{headers:{Accept:"application/json"}});if(!i.ok)return{content:[{type:"text",text:`Event not found: ${t.eventTicker}`}],details:{}};const r=await i.json(),a=r.event?.series_ticker;if(!a)return{content:[{type:"text",text:`No series_ticker for ${t.eventTicker}`}],details:{}};const c=await o({seriesTicker:a,eventTicker:t.eventTicker,percentiles:[5e3,7500,9e3],startTs:Math.floor((Date.now()-864e5*s)/1e3),endTs:Math.floor(Date.now()/1e3),periodInterval:1440});return c&&0!==c.length?{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}:{content:[{type:"text",text:"No forecast data available"}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled (resolved) contracts with P&L.",parameters:_.Object({ticker:_.Optional(_.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getSettlements:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await o({limit:100,ticker:t.ticker});return s?{content:[{type:"text",text:JSON.stringify(s.settlements,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance and portfolio value.",parameters:M,execute:async()=>{const{getBalance:e}=await Promise.resolve().then(n.t.bind(n,96139,23)),t=await e();return t?{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_orders",label:"Orders",description:"Get current resting orders on Kalshi.",parameters:_.Object({status:_.Optional(_.String({description:"Filter by status: resting, canceled, executed. Default: resting"}))}),execute:async(e,t)=>{const{getOrders:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await o({status:t.status||"resting",limit:100});return s?{content:[{type:"text",text:JSON.stringify(s.orders,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_fills",label:"Fills",description:"Get recent trade fills (executed trades) on Kalshi.",parameters:_.Object({ticker:_.Optional(_.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getFills:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await o({ticker:t.ticker,limit:50});return s?{content:[{type:"text",text:JSON.stringify(s.fills,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_liquidity",label:"Liquidity Scanner",description:"Scan orderbook liquidity for a topic across Kalshi + Polymarket. Returns spread, depth, liquidity scores. Topics: "+Object.keys(d.TOPIC_SERIES).join(", "),parameters:_.Object({topic:_.String({description:"Topic to scan (e.g. oil, crypto, fed, geopolitics)"})}),execute:async(e,t)=>{const n=t.topic.toLowerCase(),o=d.TOPIC_SERIES[n];if(!o)return{content:[{type:"text",text:`Unknown topic "${t.topic}". Available: ${Object.keys(d.TOPIC_SERIES).join(", ")}`}],details:{}};const s=[];for(const e of o)try{const t=`https://api.elections.kalshi.com/trade-api/v2/markets?series_ticker=${e}&status=open&limit=200`,n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)continue;const o=(await n.json()).markets||[],i=await Promise.allSettled(o.slice(0,20).map(e=>(0,c.getPublicOrderbook)(e.ticker).then(t=>({ticker:e.ticker,title:e.title,ob:t}))));for(const e of i){if("fulfilled"!==e.status||!e.value.ob)continue;const{ticker:t,title:n,ob:o}=e.value,i=(o.yes_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),r=(o.no_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),a=i[0]?.price||0,c=r.length>0?100-r[0].price:100,l=c-a,d=i.slice(0,3).reduce((e,t)=>e+t.qty,0)+r.slice(0,3).reduce((e,t)=>e+t.qty,0),u=l<=2&&d>=500?"high":l<=5&&d>=100?"medium":"low";s.push({venue:"kalshi",ticker:t,title:(n||"").slice(0,50),bestBid:a,bestAsk:c,spread:l,depth:Math.round(d),liquidityScore:u})}}catch{}try{const e=await(0,l.polymarketSearch)(n,5);for(const t of e)for(const e of(t.markets||[]).slice(0,5)){if(!e.active||e.closed||!e.clobTokenIds)continue;const n=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!n)continue;const o=await(0,l.polymarketGetOrderbookWithDepth)(n[0]);o&&s.push({venue:"polymarket",ticker:(e.question||t.title).slice(0,50),bestBid:o.bestBid,bestAsk:o.bestAsk,spread:o.spread,depth:o.bidDepthTop3+o.askDepthTop3,liquidityScore:o.liquidityScore})}}catch{}return s.sort((e,t)=>e.spread-t.spread),{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"inspect_book",label:"Orderbook",description:'Get orderbook depth, spread, and liquidity. Returns a status field per market: "ok", "empty_orderbook", "market_closed", or "api_error". Supports multiple tickers in one call — use tickers array for batch position checks.',parameters:_.Object({ticker:_.Optional(_.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:_.Optional(_.Array(_.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:_.Optional(_.String({description:'Search Polymarket by keyword (e.g. "oil price above 100")'}))}),execute:async(e,t)=>{const n=[],o=[];t.tickers?.length?o.push(...t.tickers):t.ticker&&o.push(t.ticker);for(const e of o)try{const t=await(0,a.kalshiFetchMarket)(e),o=t.status||"unknown";if("open"!==o&&"active"!==o)n.push({venue:"kalshi",ticker:e,title:t.title,status:"market_closed",reason:`Market status: ${o}. Orderbook unavailable for closed/settled markets.`,lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0"))});else{const o=await(0,c.getPublicOrderbook)(e),s=(o?.yes_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),i=(o?.no_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price);if(0===s.length&&0===i.length)n.push({venue:"kalshi",ticker:e,title:t.title,status:"empty_orderbook",reason:"Market open but no resting orders. Normal for illiquid/OTM contracts. Use lastPrice as reference.",lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0")),volume24h:parseFloat(t.volume_24h_fp||"0"),openInterest:parseFloat(t.open_interest_fp||"0"),expiry:t.close_time||null});else{const o=s[0]?.price||0,r=i.length>0?100-i[0].price:s[0]?s[0].price+1:100,a=r-o,c=s.slice(0,3).reduce((e,t)=>e+t.size,0)+i.slice(0,3).reduce((e,t)=>e+t.size,0),l=a<=2&&c>=500?"high":a<=5&&c>=100?"medium":"low";n.push({venue:"kalshi",ticker:e,title:t.title,status:"ok",bestBid:o,bestAsk:r,spread:a,liquidityScore:l,bidLevels:s.slice(0,5),askLevels:i.slice(0,5).map(e=>({price:100-e.price,size:e.size})),totalBidDepth:s.reduce((e,t)=>e+t.size,0),totalAskDepth:i.reduce((e,t)=>e+t.size,0),lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0")),volume24h:parseFloat(t.volume_24h_fp||"0"),openInterest:parseFloat(t.open_interest_fp||"0"),expiry:t.close_time||null})}}}catch(t){n.push({venue:"kalshi",ticker:e,status:"api_error",reason:`Kalshi API error: ${t.message}`})}if(t.polyQuery)try{const e=await(0,l.polymarketSearch)(t.polyQuery,5);for(const t of e)for(const e of(t.markets||[]).slice(0,3)){if(!e.active||e.closed||!e.clobTokenIds)continue;const o=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!o)continue;const s=await(0,l.polymarketGetOrderbookWithDepth)(o[0]);if(!s)continue;const i=(0,l.parseOutcomePrices)(e.outcomePrices);n.push({venue:"polymarket",title:e.question||t.title,bestBid:s.bestBid,bestAsk:s.bestAsk,spread:s.spread,liquidityScore:s.liquidityScore,totalBidDepth:s.totalBidDepth,totalAskDepth:s.totalAskDepth,lastPrice:i[0]?Math.round(100*i[0]):0,volume24h:e.volume24hr||0})}}catch{}return 0===n.length?{content:[{type:"text",text:"No markets found. Provide ticker (Kalshi) or polyQuery (Polymarket search)."}],details:{}}:{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"get_schedule",label:"Schedule",description:"Get exchange status (open/closed) and trading hours. Use to check if low liquidity is due to off-hours.",parameters:M,execute:async()=>{try{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:`Exchange API error: ${e.status}`}],details:{}};const t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}catch(e){return{content:[{type:"text",text:`Failed: ${e.message}`}],details:{}}}}},{name:"create_thesis",label:"Create Thesis",description:"Create a new thesis from a raw thesis statement. Returns the thesis ID, confidence, node count, and edge count.",parameters:_.Object({rawThesis:_.String({description:"The raw thesis statement to create"}),webhookUrl:_.Optional(_.String({description:"Optional webhook URL for notifications"}))}),execute:async(e,t)=>{const n=await o.createThesis(t.rawThesis,!0),s=n.thesis||n,i=s.causalTree?.nodes?.length||0,r=(s.edges||[]).length,a="number"==typeof s.confidence?Math.round(100*s.confidence):0;return{content:[{type:"text",text:`Thesis created.\nID: ${s.id}\nConfidence: ${a}%\nNodes: ${i}\nEdges: ${r}`}],details:{}}}},{name:"get_edges",label:"Get Edges",description:"Get top edges across all active theses. Returns the top 10 edges sorted by absolute edge size with ticker, market name, edge size, direction, and venue.",parameters:M,execute:async()=>{const{theses:e}=await o.listTheses(),t=(e||[]).filter(e=>"active"===e.status||"monitoring"===e.status),n=await Promise.allSettled(t.map(async e=>((await o.getContext(e.id)).edges||[]).map(t=>({...t,thesisId:e.id})))),s=[];for(const e of n)"fulfilled"===e.status&&s.push(...e.value);s.sort((e,t)=>Math.abs(t.edge||t.edgeSize||0)-Math.abs(e.edge||e.edgeSize||0));const i=s.slice(0,10).map(e=>({ticker:e.marketId||e.ticker||"-",market:e.market||e.marketTitle||"-",edge:e.edge||e.edgeSize||0,direction:e.direction||"yes",venue:e.venue||"kalshi"}));return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"get_feed",label:"Get Feed",description:"Get evaluation history with topSignal highlighting. The most important signal is surfaced first.",parameters:_.Object({hours:_.Optional(_.Number({description:"Hours of history to fetch (default 24)"}))}),execute:async(e,t)=>{const n=await o.getFeed(t.hours||24),s=Array.isArray(n)?n:n?.evaluations||n?.items||[];let i=null,r=0;for(const e of s){let t=0;const n=Math.abs(e.confidenceDelta||e.confidence_delta||0);n>0?t=100*n:e.summary?.length>50&&(t=.1),t>r&&(r=t,i=e)}const a={total:s.length};return i&&(a.topSignal={summary:i.summary||i.content||"",confidenceDelta:i.confidenceDelta||i.confidence_delta||0,evaluatedAt:i.evaluatedAt||i.evaluated_at||"",why:r>1?"Largest confidence movement":r>0?"Most substantive (no confidence change)":"Most recent"}),a.items=s,{content:[{type:"text",text:JSON.stringify(a,null,2)}],details:{}}}},{name:"get_changes",label:"Get Changes",description:"Get recent market changes detected server-side. Returns real price moves (>5¢), new contracts, and removed/settled contracts across Kalshi, Polymarket, and traditional markets. Use for situational awareness and discovering new opportunities.",parameters:_.Object({hours:_.Optional(_.Number({description:"Hours of history (default 1)"}))}),execute:async(e,t)=>{const n=t.hours||1,o=new Date(Date.now()-60*n*60*1e3).toISOString(),s=process.env.SF_API_URL||"https://simplefunctions.dev",i=await fetch(`${s}/api/changes?since=${encodeURIComponent(o)}&limit=100`);if(!i.ok)return{content:[{type:"text",text:JSON.stringify({error:`API error ${i.status}`})}],details:{}};const r=await i.json();return{content:[{type:"text",text:JSON.stringify(r,null,2)}],details:{}}}},{name:"explore_public",label:"Explore Public Theses",description:"Browse public theses from other users. No auth required. Pass a slug to get details, or omit to list all.",parameters:_.Object({slug:_.Optional(_.String({description:"Specific thesis slug, or empty to list all"}))}),execute:async(e,t)=>{const n="https://simplefunctions.dev";if(t.slug){const e=await fetch(`${n}/api/public/thesis/${t.slug}`);if(!e.ok)return{content:[{type:"text",text:`Not found: ${t.slug}`}],details:{}};const o=await e.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}const o=await fetch(`${n}/api/public/theses`);if(!o.ok)return{content:[{type:"text",text:"Failed to fetch public theses"}],details:{}};const s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"create_strategy",label:"Create Strategy",description:"Create a trading strategy for a thesis. Extract hard conditions (entryBelow/stopLoss/takeProfit as cents) and soft conditions from conversation. Called when user mentions specific trade ideas.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),marketId:_.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:_.String({description:"Human-readable market name"}),direction:_.String({description:"yes or no"}),horizon:_.Optional(_.String({description:"short, medium, or long. Default: medium"})),entryBelow:_.Optional(_.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:_.Optional(_.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:_.Optional(_.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:_.Optional(_.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:_.Optional(_.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:_.Optional(_.Number({description:"Contracts per order. Default: 50"})),softConditions:_.Optional(_.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:_.Optional(_.String({description:"Full logic description"}))}),execute:async(e,t)=>{const n=await o.createStrategyAPI(t.thesisId,{marketId:t.marketId,market:t.market,direction:t.direction,horizon:t.horizon,entryBelow:t.entryBelow,entryAbove:t.entryAbove,stopLoss:t.stopLoss,takeProfit:t.takeProfit,maxQuantity:t.maxQuantity,perOrderQuantity:t.perOrderQuantity,softConditions:t.softConditions,rationale:t.rationale,createdBy:"agent"});return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"list_strategies",label:"List Strategies",description:"List strategies for a thesis. Filter by status (active/watching/executed/cancelled/review) or omit for all.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),status:_.Optional(_.String({description:"Filter by status. Omit for all."}))}),execute:async(e,t)=>{const n=await o.getStrategies(t.thesisId,t.status);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"update_strategy",label:"Update Strategy",description:"Update a strategy (change stop loss, take profit, status, priority, etc.)",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),strategyId:_.String({description:"Strategy ID (UUID)"}),stopLoss:_.Optional(_.Number({description:"New stop loss (cents)"})),takeProfit:_.Optional(_.Number({description:"New take profit (cents)"})),entryBelow:_.Optional(_.Number({description:"New entry below trigger (cents)"})),entryAbove:_.Optional(_.Number({description:"New entry above trigger (cents)"})),status:_.Optional(_.String({description:"New status: active|watching|executed|cancelled|review"})),priority:_.Optional(_.Number({description:"New priority"})),softConditions:_.Optional(_.String({description:"Updated soft conditions"})),rationale:_.Optional(_.String({description:"Updated rationale"}))}),execute:async(e,t)=>{const{thesisId:n,strategyId:s,...i}=t,r=await o.updateStrategyAPI(n,s,i);return{content:[{type:"text",text:JSON.stringify(r)}],details:{}}}},{name:"what_if",label:"What-If",description:"Run a what-if scenario: override causal tree node probabilities and see how edges and confidence change. Zero LLM cost — pure computation.",parameters:_.Object({overrides:_.Array(_.Object({nodeId:_.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:_.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{const n=y,o=[];function s(e){for(const t of e)o.push(t),t.children?.length&&s(t.children)}const i=n.causalTree?.nodes||[];s(i);const r=i.filter(e=>0===e.depth||void 0===e.depth&&!e.id.includes(".")),a=new Map(t.overrides.map(e=>[e.nodeId,e.newProbability])),c=r.reduce((e,t)=>e+(t.probability||0)*(t.importance||0),0),l=r.reduce((e,t)=>e+(a.get(t.id)??t.probability??0)*(t.importance||0),0),d=new Map;for(const[e,t]of a.entries()){const n=o.find(t=>t.id===e);n&&n.probability>0&&d.set(e,Math.max(0,Math.min(2,t/n.probability)))}const u=(n.edges||[]).map(e=>{const t=e.relatedNodeId;let n=1;if(t){const e=[t,t.split(".").slice(0,-1).join("."),t.split(".")[0]].filter(Boolean);for(const t of e)if(d.has(t)){n=d.get(t);break}}const o=e.marketPrice||0,s=e.thesisPrice||e.thesisImpliedPrice||o,i=e.edge||e.edgeSize||0,r=Math.round(100*(o+(s-o)*n))/100,a=e.direction||"yes",c=Math.round(100*("yes"===a?r-o:o-r))/100;return{market:e.market||e.marketTitle||e.marketId,marketPrice:o,oldEdge:i,newEdge:c,delta:c-i,signal:Math.abs(c-i)<1?"unchanged":i>0&&c<0||i<0&&c>0?"REVERSED":Math.abs(c)<2?"GONE":"reduced"}}).filter(e=>"unchanged"!==e.signal),p={overrides:t.overrides.map(e=>{const t=o.find(t=>t.id===e.nodeId);return{nodeId:e.nodeId,label:t?.label||e.nodeId,oldProb:t?.probability,newProb:e.newProbability}}),confidence:{old:Math.round(100*c),new:Math.round(100*l),delta:Math.round(100*(l-c))},affectedEdges:u};return{content:[{type:"text",text:JSON.stringify(p,null,2)}],details:{}}}}];R.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:_.Object({query:_.String({description:"Search query"}),mode:_.Optional(_.String({description:'"summary" or "raw"'})),hours:_.Optional(_.Number({description:"Hours (default 24)"}))}),execute:async(e,t)=>{const n=await o.searchX(t.query,{mode:t.mode,hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_volume",label:"X Volume",description:"X discussion volume trend — total posts, velocity, peak time, timeseries.",parameters:_.Object({query:_.String({description:"Search query"}),hours:_.Optional(_.Number({description:"Hours (default 72)"}))}),execute:async(e,t)=>{const n=await o.getXVolume(t.query,{hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_news",label:"X News",description:"News stories trending on X — titles, summaries, tickers.",parameters:_.Object({query:_.String({description:"Search query"}),limit:_.Optional(_.Number({description:"Max stories (default 10)"}))}),execute:async(e,t)=>{const n=await o.searchXNews(t.query,{limit:t.limit});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_account",label:"X Account",description:"Recent posts from a specific X account.",parameters:_.Object({username:_.String({description:"X username (with or without @)"}),hours:_.Optional(_.Number({description:"Hours (default 24)"}))}),execute:async(e,t)=>{const n=await o.getXAccount(t.username,{hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,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:_.Object({thesisId:_.String({description:"Thesis ID"}),newsIntervalMin:_.Optional(_.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:_.Optional(_.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:_.Optional(_.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:_.Optional(_.Number({description:"Monthly budget (0 = unlimited)"})),paused:_.Optional(_.Boolean({description:"Pause or resume heartbeat"}))}),execute:async(e,t)=>{if(t.newsIntervalMin||t.xIntervalMin||t.evalModelTier||void 0!==t.monthlyBudgetUsd||void 0!==t.paused){const e={};t.newsIntervalMin&&(e.newsIntervalMin=t.newsIntervalMin),t.xIntervalMin&&(e.xIntervalMin=t.xIntervalMin),t.evalModelTier&&(e.evalModelTier=t.evalModelTier),void 0!==t.monthlyBudgetUsd&&(e.monthlyBudgetUsd=t.monthlyBudgetUsd),void 0!==t.paused&&(e.paused=t.paused),await o.updateHeartbeatConfig(t.thesisId,e)}const n=await o.getHeartbeatConfig(t.thesisId);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}}),R.push({name:"configure_heartbeat",label:"Configure Heartbeat",description:"Adjust the 24/7 monitoring engine: news interval, X interval, model tier, budget, pause/resume.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),newsIntervalMin:_.Optional(_.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:_.Optional(_.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:_.Optional(_.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:_.Optional(_.Number({description:"Monthly budget cap (0=unlimited)"})),paused:_.Optional(_.Boolean({description:"Pause/resume"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t,i=await o.request("PATCH",`/api/thesis/${n}/heartbeat`,s);return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"get_heartbeat_status",label:"Heartbeat Status",description:"Heartbeat config + cost summary for a thesis.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await o.request("GET",`/api/thesis/${t.thesisId}/heartbeat`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"update_thesis",label:"Update Thesis",description:"Update thesis metadata: title, status (active/paused/archived), webhookUrl.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),title:_.Optional(_.String({description:"New title"})),status:_.Optional(_.String({description:"active, paused, or archived"})),webhookUrl:_.Optional(_.String({description:"Webhook URL (HTTPS)"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t,i=await o.request("PATCH",`/api/thesis/${n}`,s);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"add_position",label:"Add Position",description:"Record a new position in a thesis for tracking.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),venue:_.String({description:"kalshi or polymarket"}),externalMarketId:_.String({description:"Market ticker"}),marketTitle:_.String({description:"Market name"}),direction:_.String({description:"yes or no"}),entryPrice:_.Number({description:"Entry price in cents"}),size:_.Optional(_.Number({description:"Contracts"})),rationale:_.Optional(_.String({description:"Why"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t,i=await o.request("POST",`/api/thesis/${n}/positions`,s);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"update_position",label:"Update Position",description:"Update position: currentPrice, edge, status (open→closed).",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),positionId:_.String({description:"Position ID"}),currentPrice:_.Optional(_.Number({description:"Current price (cents)"})),edge:_.Optional(_.Number({description:"Current edge (cents)"})),status:_.Optional(_.String({description:"open or closed"}))}),execute:async(e,t)=>{const{thesisId:n,positionId:s,...i}=t,r=await o.request("PATCH",`/api/thesis/${n}/positions/${s}`,i);return{content:[{type:"text",text:JSON.stringify(r)}],details:{}}}},{name:"get_evaluation_history",label:"Evaluation History",description:"Confidence trajectory over time — daily aggregated. For trend analysis.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await o.request("GET",`/api/thesis/${t.thesisId}/evaluations`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"update_nodes",label:"Update Nodes",description:"Directly update causal tree node probabilities. Zero LLM cost. Use for confirmed facts (lock nodes at 0.99).",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),updates:_.Array(_.Object({nodeId:_.String({description:"Node ID (e.g. n3)"}),probability:_.Number({description:"New probability (0-1)"}),reason:_.Optional(_.String({description:"Why"}))})),lock:_.Optional(_.Array(_.String({description:"Node IDs to lock"})))}),execute:async(e,t)=>{const n=await o.request("POST",`/api/thesis/${t.thesisId}/nodes/update`,{updates:t.updates,lock:t.lock});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}}),R.push({name:"get_trade_ideas",label:"Trade Ideas",description:"S&T-style trade pitches: conviction, catalyst, direction, risk. Synthesized from live market data, edges, and macro context. No auth required.",parameters:_.Object({freshness:_.Optional(_.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:_.Optional(_.String({description:"Filter: macro, geopolitics, crypto, policy, event"}))}),execute:async(e,t)=>{const n=new URLSearchParams;t.freshness&&n.set("freshness",t.freshness),t.category&&n.set("category",t.category);const o=await fetch(`https://simplefunctions.dev/api/public/ideas?${n.toString()}`);if(!o.ok)return{content:[{type:"text",text:`Ideas API error: ${o.status}`}],details:{}};const s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"create_intent",label:"Create Intent",description:"Declare an execution intent with trigger conditions. Runtime daemon evaluates triggers and executes via local keys.",parameters:_.Object({action:_.String({description:"buy or sell"}),venue:_.String({description:"kalshi or polymarket"}),marketId:_.String({description:"Market ticker"}),marketTitle:_.String({description:"Human-readable name"}),direction:_.String({description:"yes or no"}),targetQuantity:_.Number({description:"Number of contracts"}),maxPrice:_.Optional(_.Number({description:"Max price per contract in cents (1-99)"})),triggerType:_.Optional(_.String({description:"immediate, price_below, price_above, time"})),triggerPrice:_.Optional(_.Number({description:"Price trigger threshold in cents"})),rationale:_.Optional(_.String({description:"Why this trade"})),autoExecute:_.Optional(_.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(e,t)=>{const n=await o.createIntent({...t,source:"agent",expireAt:new Date(Date.now()+864e5).toISOString()});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"list_intents",label:"List Intents",description:"List execution intents — pending, armed, triggered, executing, filled.",parameters:_.Object({activeOnly:_.Optional(_.Boolean({description:"Only active intents (default true)"}))}),execute:async(e,t)=>{const n=await o.listIntents({active:!1!==t.activeOnly});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"cancel_intent",label:"Cancel Intent",description:"Cancel an active intent — stops trigger evaluation and prevents execution.",parameters:_.Object({intentId:_.String({description:"Intent ID to cancel"})}),execute:async(e,t)=>{const n=await o.cancelIntentAPI(t.intentId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}});const N=(0,u.loadConfig)();N.tradingEnabled&&R.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Shows preview and asks for confirmation.",parameters:_.Object({ticker:_.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:_.String({description:"yes or no"}),action:_.String({description:"buy or sell"}),type:_.String({description:"limit or market"}),count:_.Number({description:"Number of contracts"}),price_cents:_.Optional(_.Number({description:"Limit price in cents (1-99). Required for limit orders."}))}),execute:async(e,t)=>{const{createOrder:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await Promise.resolve().then(n.t.bind(n,23785,23)),i=t.price_cents?Math.round(Number(t.price_cents)):void 0,r=((i||99)*t.count/100).toFixed(2),a=` Order: ${t.action.toUpperCase()} ${t.count}x ${t.ticker} ${t.side.toUpperCase()} @ ${i?i+"¢":"market"} (max $${r})`;if(process.stderr.write(a+"\n"),!process.stdin.isTTY)return{content:[{type:"text",text:"Order rejected: trading requires interactive terminal (stdin is piped). Use TUI mode for trading."}],details:{}};const c=s.createInterface({input:process.stdin,output:process.stderr}),l=await new Promise(e=>c.question(" Execute? (y/n) ",e));if(c.close(),!l.toLowerCase().startsWith("y"))return{content:[{type:"text",text:"Order cancelled by user."}],details:{}};try{const e=await o({ticker:t.ticker,side:t.side,action:t.action,type:t.type,count:t.count,...i?{yes_price:i}:{}}),n=e.order||e;return{content:[{type:"text",text:`Order placed: ${n.order_id||"OK"}\nStatus: ${n.status||"-"}\nFilled: ${n.fill_count_fp||0}/${n.initial_count_fp||t.count}`}],details:{}}}catch(e){const t=e.message||String(e);return t.includes("403")?{content:[{type:"text",text:"403 Forbidden — your Kalshi key lacks write permission. Get a read+write key at kalshi.com/account/api-keys"}],details:{}}:{content:[{type:"text",text:`Order failed: ${t}`}],details:{}}}}},{name:"cancel_order",label:"Cancel Order",description:"Cancel a resting order by order ID. Executes directly (no confirmation prompt in plain mode).",parameters:_.Object({order_id:_.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{const{cancelOrder:o}=await Promise.resolve().then(n.t.bind(n,96139,23));try{return await o(t.order_id),{content:[{type:"text",text:`Order ${t.order_id} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Cancel failed: ${e.message}`}],details:{}}}}});R.push({name:"close_position",label:"Close Position",description:"Remove a position record from a thesis.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),positionId:_.String({description:"Position ID"})}),execute:async(e,t)=>{const n=await o.request("DELETE",`/api/thesis/${t.thesisId}/positions/${t.positionId}`);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"augment_tree",label:"Augment Tree",description:"Review and merge suggested causal tree nodes from evaluations.",parameters:_.Object({thesisId:_.String({description:"Thesis ID"}),dryRun:_.Optional(_.Boolean({description:"Preview without applying"}))}),execute:async(e,t)=>{const n=t.dryRun?"?dryRun=true":"",s=await o.request("POST",`/api/thesis/${t.thesisId}/augment${n}`);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}}),R.push({name:"get_world_state",label:"World State",description:"Real-time world model for agents. ~800 tokens of structured state: prediction market index, traditional markets, topic summaries, divergences.",parameters:_.Object({focus:_.Optional(_.String({description:'Comma-separated topics (e.g. "energy,geopolitics")'}))}),execute:async(e,t)=>{const n=t.focus?`?focus=${encodeURIComponent(t.focus)}`:"",o=process.env.SF_API_URL||"https://simplefunctions.dev",s=await fetch(`${o}/api/agent/world${n}`);if(!s.ok)return{content:[{type:"text",text:`World API error: ${s.status}`}],details:{}};return{content:[{type:"text",text:await s.text()}],details:{}}}},{name:"get_world_delta",label:"World Delta",description:"Incremental world state update — only what changed. ~30-50 tokens.",parameters:_.Object({since:_.Optional(_.String({description:'"30m", "1h", "6h", "24h" or ISO timestamp (default "1h")'}))}),execute:async(e,t)=>{const n=t.since||"1h",o=process.env.SF_API_URL||"https://simplefunctions.dev",s=await fetch(`${o}/api/agent/world/delta?since=${encodeURIComponent(n)}`);if(!s.ok)return{content:[{type:"text",text:`Delta API error: ${s.status}`}],details:{}};return{content:[{type:"text",text:await s.text()}],details:{}}}},{name:"monitor_the_situation",label:"Monitor",description:"Universal web intelligence. Scrape any URL (Firecrawl), analyze with any LLM, cross-reference with 9,706 prediction markets.",parameters:_.Object({source:_.Object({action:_.String({description:"scrape, crawl, search, map, extract, batch_scrape"}),url:_.Optional(_.String({description:"Target URL"})),query:_.Optional(_.String({description:"Search query (for search action)"}))}),analysis:_.Optional(_.Object({model:_.Optional(_.String({description:"OpenRouter model"})),prompt:_.Optional(_.String({description:"Analysis prompt"}))})),enrich:_.Optional(_.Object({topics:_.Optional(_.Array(_.String())),includeIndex:_.Optional(_.Boolean())})),webhook:_.Optional(_.Object({url:_.String({description:"Webhook URL"}),format:_.Optional(_.String({description:"full, brief, or tweetable"}))}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",o=await fetch(`${n}/api/monitor-the-situation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)return{content:[{type:"text",text:`Monitor API error: ${o.status}`}],details:{}};const s=await o.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:_.Object({content:_.String({description:"Text to cross-reference"}),topics:_.Optional(_.Array(_.String()))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",o=await fetch(`${n}/api/monitor-the-situation/enrich`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)return{content:[{type:"text",text:`Enrich API error: ${o.status}`}],details:{}};const s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}}),R.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime is running and show active intents.",parameters:_.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=s(i(),".sf","runtime.pid");let a=!1,c="";if(e(r)){c=t(r,"utf-8").trim();try{process.kill(parseInt(c),0),a=!0}catch{a=!1}}const l=await o.listIntents({active:!0});return{content:[{type:"text",text:JSON.stringify({running:a,pid:a?c:null,...l},null,2)}],details:{}}}},{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon. Evaluates intent triggers and executes orders.",parameters:_.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),{spawn:i}=await Promise.resolve().then(n.t.bind(n,35317,23)),r=o(s(),".sf","runtime.pid");if(e(r)){const e=t(r,"utf-8").trim();try{return process.kill(parseInt(e),0),{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{}}if(i(process.execPath,[process.argv[1],"runtime","start"],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env}}).unref(),await new Promise(e=>setTimeout(e,1e3)),e(r)){return{content:[{type:"text",text:`Runtime started (PID ${t(r,"utf-8").trim()}). Polling every 30s.`}],details:{}}}return{content:[{type:"text",text:"Runtime starting... check runtime_status in a moment."}],details:{}}}},{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:_.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:o}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=s(i(),".sf","runtime.pid");if(!e(r))return{content:[{type:"text",text:"No runtime running."}],details:{}};const a=t(r,"utf-8").trim();try{return process.kill(parseInt(a),"SIGTERM"),o(r),{content:[{type:"text",text:`Runtime stopped (PID ${a}).`}],details:{}}}catch{try{o(r)}catch{}return{content:[{type:"text",text:"Runtime was not running (stale PID removed)."}],details:{}}}}});const L=y,D=L._explorerMode||"_explorer"===s;let K;if(D){const e=(L.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.title||"").slice(0,40)} | ${e.venue||"kalshi"} | +${e.edge}`).join("\n")||" (no edges)";K=`You are a prediction market research assistant in EXPLORER MODE — not bound to any thesis.\n\n## What you can do\n- get_world_state: real-time world model (~800 tokens), use ?focus= for deeper topic coverage\n- get_world_delta: incremental changes since last check (~30-50 tokens)\n- query: LLM-enhanced market search\n- scan_markets: search Kalshi + Polymarket\n- get_markets: traditional markets (SPY, VIX, gold, oil)\n- get_trade_ideas: S&T-style trade pitches with conviction + catalyst\n- explore_public: browse public theses\n- search_x, x_volume, x_news: X/Twitter signals\n- monitor_the_situation: scrape any URL, analyze, cross-reference with 9,706 markets\n- enrich_content: cross-reference text with prediction markets\n- get_positions: portfolio positions\n- create_intent / list_intents / cancel_intent: execution intents with triggers\n- runtime_start / runtime_stop / runtime_status: local execution daemon\n- create_thesis: create a thesis when user forms a view\n\n## CRITICAL: When the user expresses a view worth tracking, use create_thesis. After creation, confirm and continue with the new thesis context.\n\n## Rules\n- Be concise. Use tools for fresh data.\n- Use Chinese if user writes Chinese, English if English.\n- Prices in cents (¢). P&L in dollars ($).\n${N.tradingEnabled?"- Trading ENABLED.":"- Trading DISABLED."}\n\n## Market snapshot\nPublic edges:\n${e}`}else{const e=L.edges?.sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.market||"").slice(0,40)} | ${e.venue||"kalshi"} | mkt ${e.marketPrice}¢ | edge ${e.edge>0?"+":""}${e.edge}`).join("\n")||" (no edges)",t=L.causalTree?.nodes?.filter(e=>0===e.depth).map(e=>` ${e.id} ${(e.label||"").slice(0,40)} — ${Math.round(100*e.probability)}%`).join("\n")||" (no causal tree)",n="number"==typeof L.confidence?Math.round(100*L.confidence):0;K=`You are a prediction market trading assistant. Your job is not to please the user — it is to help them see reality clearly and make correct trading decisions.\n\n## Framework\nEdge = thesis price - market price. Positive = market underprices. executableEdge = edge minus spread.\n\nEdge types: "consensus_gap" (depth >= 500, real disagreement), "attention_gap" (depth < 100, illusory pricing), "timing_gap" (market lags), "risk_premium" (settlement/platform risk). Always classify when reporting edges.\nFor edges > 20 cents, state what the market must believe for it to be right.\n\nPrice reliability: depth >= 500 = consensus. depth < 100 = unreliable. spread > 5 cents = noisy. Flag illiquid markets.\n\nKill conditions: each causal node has a falsifier. Check these first when evaluating news. If triggered, override other analysis.\n\nAlways state contract expiry and next catalyst. No catalyst = flag capital lock risk.\n\nFor complex questions, chain: get_context -> inspect_book -> get_liquidity -> web_search -> search_x -> synthesize.\nUse search_x for social sentiment on any topic. Use x_volume to detect discussion spikes. Use x_account to track key people.\nUse heartbeat_config to view/adjust scan intervals, model tier, budget cap, or check cost breakdown.\n\nFlag correlated exposure across positions sharing upstream nodes. If nothing to do, say so.\n\n## Rules\n- Be concise. Use tools for fresh data. Don't guess prices.\n- You do NOT know the user's positions at start. Call get_positions before discussing trades or portfolio.\n- If user mentions news, inject_signal immediately.\n- If user says "evaluate", trigger immediately. Don't confirm.\n- Don't end with "anything else?"\n- If an edge is narrowing or disappearing, say so proactively.\n- Use Chinese if user writes Chinese, English if English.\n- Prices in cents (¢). P&L in dollars ($). Don't re-convert tool output.\n- When a trade idea emerges, create_strategy to record it.\n${N.tradingEnabled?"- Trading ENABLED. You have place_order and cancel_order tools.":"- Trading DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current State\nThesis: ${L.thesis||L.rawThesis||"N/A"}\nID: ${s} | Confidence: ${n}% | Status: ${L.status}\n\nCausal nodes:\n${t}\n\nTop edges:\n${e}\n\n${L.lastEvaluation?.summary?`Latest eval: ${L.lastEvaluation.summary.slice(0,300)}`:""}`}const j=new S({initialState:{systemPrompt:K,model:I,tools:R,thinkingLevel:"off"},streamFn:v,getApiKey:e=>"openrouter"===e?t:void 0});if(!i?.newSession){const e=g(s);if(e?.messages?.length>0)try{j.replaceMessages(e.messages),j.setSystemPrompt(K)}catch{}}let F="";if(j.subscribe(e=>{if("message_update"===e.type){const t=e.assistantMessageEvent;"text_delta"===t.type&&(process.stdout.write(t.delta),F+=t.delta)}if("message_end"===e.type&&F&&(process.stdout.write("\n"),F=""),"tool_execution_start"===e.type&&process.stderr.write(` ▸ ${e.toolName}...\n`),"tool_execution_end"===e.type){const t=e.isError?"✗":"✓";process.stderr.write(` ${t} ${e.toolName}\n`)}}),D)console.log(`SF Agent — Explorer mode | ${C}`),console.log(`Public edges: ${(L.edges||[]).length}`),console.log("Ask anything about prediction markets. Type /help for commands, /exit to quit.\n");else{const e=L.thesis||L.rawThesis||"N/A",t="number"==typeof L.confidence?Math.round(100*L.confidence):0;console.log(`SF Agent — ${s.slice(0,8)} | ${t}% | ${C}`),console.log(`Thesis: ${e.length>100?e.slice(0,100)+"...":e}`),console.log(`Edges: ${(L.edges||[]).length} | Status: ${L.status}`),console.log("Type /help for commands, /exit to quit.\n")}const q=$.createInterface({input:process.stdin,output:process.stdout,prompt:"> "});q.prompt();for await(const t of q){const n=t.trim();if(n){if("/exit"===n||"/quit"===n){try{f(s,C,j.state.messages)}catch{}return void q.close()}if("/help"!==n){if("/tree"===n){y=await o.getContext(s);const e=y.causalTree?.nodes||[];for(const t of e){const e=" ".repeat(t.depth||0);console.log(`${e}${t.id} ${(t.label||"").slice(0,60)} — ${Math.round(100*t.probability)}%`)}q.prompt();continue}if("/edges"===n){y=await o.getContext(s);const e=(y.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,15);for(const t of e){const e=t.edge>0?"+":"";console.log(` ${(t.market||"").slice(0,45).padEnd(45)} ${t.marketPrice}¢ edge ${e}${t.edge} ${t.venue}`)}q.prompt();continue}if("/eval"===n){console.log("Triggering evaluation...");const e=await o.evaluate(s);console.log(`Confidence: ${e.previousConfidence} → ${e.newConfidence}`),e.summary&&console.log(e.summary),q.prompt();continue}if(n.startsWith("/model")){const e=n.slice(6).trim();if(!e){console.log(`Current: ${C}`),q.prompt();continue}C=e.replace(/^openrouter\//,""),I=O(C),j.setModel(I),console.log(`Model: ${C}`),q.prompt();continue}try{await j.prompt(n)}catch(e){console.error(`Error: ${e.message}`)}try{f(s,C,j.state.messages)}catch{}q.prompt()}else console.log("Commands: /help /exit /tree /edges /eval /model <name>"),q.prompt()}else q.prompt()}}({openrouterKey:h,sfClient:y,resolvedThesisId:S||"_explorer",latestContext:$,useProxy:r,llmBaseUrl:m,sfApiKey:s,sfApiUrl:i,opts:t});const C=await n.e(921).then(n.bind(n,93921)),O=await 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(641),n.e(582)]).then(n.bind(n,65653)),{TUI:P,ProcessTerminal:T,Container:E,Text:A,Markdown:M,Editor:R,Loader:N,Spacer:L,CombinedAutocompleteProvider:D,truncateToWidth:K,visibleWidth:j}=C,{getModel:F,streamSimple:q,Type:U}=O,{Agent:z}=I,H=function(e){const{truncateToWidth:t,visibleWidth:n}=e;return class{text;cachedWidth;cachedLines;constructor(e){this.text=e}setText(e){this.text=e,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}render(e){return this.cachedLines&&this.cachedWidth===e||(this.cachedWidth=e,this.cachedLines=[t(this.text,e)]),this.cachedLines}}}(C),B=function(e){const{truncateToWidth:t,visibleWidth:n}=e;return class{thesisId="";confidence=0;confidenceDelta=0;pnlDollars=0;positionCount=0;edgeCount=0;topEdge="";tokens=0;cost=0;toolCount=0;modelName="";tradingEnabled=!1;exchangeOpen=null;cachedWidth;cachedLines;isExplorer=!1;setFromContext(e,t){if(e._explorerMode){this.isExplorer=!0,this.thesisId="Explorer",this.confidence=0,this.confidenceDelta=0,this.edgeCount=(e.edges||[]).length;const t=e.edges||[];if(t.length>0){const e=[...t].sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge))[0];this.topEdge=`${(e.title||"").slice(0,20)} +${Math.round(e.edge)}¢`}}else{this.isExplorer=!1,this.thesisId=(e.thesisId||"").slice(0,8),this.confidence="number"==typeof e.confidence?Math.round(100*e.confidence):"string"==typeof e.confidence?Math.round(100*parseFloat(e.confidence)):0,this.confidenceDelta=e.lastEvaluation?.confidenceDelta?Math.round(100*e.lastEvaluation.confidenceDelta):0,this.edgeCount=(e.edges||[]).length;const t=e.edges||[];if(t.length>0){const e=[...t].sort((e,t)=>Math.abs(t.edge||t.edgeSize||0)-Math.abs(e.edge||e.edgeSize||0))[0],n=(e.market||e.marketTitle||e.marketId||"").slice(0,20),o=e.edge||e.edgeSize||0;this.topEdge=`${n} ${o>0?"+":""}${Math.round(o)}¢`}}t&&t.length>0&&(this.positionCount=t.length,this.pnlDollars=t.reduce((e,t)=>e+(t.unrealized_pnl||0),0)/100),this.cachedWidth=void 0,this.cachedLines=void 0}updateConfidence(e,t){this.confidence=Math.round(100*e),this.confidenceDelta=Math.round(100*t),this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}update(){this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;this.cachedWidth=e;const o=_.zinc600(" │ ");let s;if(this.isExplorer){const e=_.emerald(w("Explorer")),t=_.zinc600(`${this.edgeCount} public edges`),n=this.topEdge?_.zinc400(this.topEdge):"";let o="";if(this.positionCount>0){const e=this.pnlDollars>=0?_.emerald(`+$${this.pnlDollars.toFixed(2)}`):_.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);o=_.zinc600(`${this.positionCount} pos `)+e}s=[e,o,t,n].filter(Boolean)}else{const e=_.emerald(this.thesisId),t=this.confidenceDelta>0?"▲":this.confidenceDelta<0?"▼":"─",n=this.confidenceDelta>0?_.emerald:this.confidenceDelta<0?_.red:_.zinc600,o=0!==this.confidenceDelta?` (${this.confidenceDelta>0?"+":""}${this.confidenceDelta})`:"",i=n(`${t} ${this.confidence}%${o}`);let r="";if(this.positionCount>0){const e=this.pnlDollars>=0?_.emerald(`+$${this.pnlDollars.toFixed(2)}`):_.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);r=_.zinc600(`${this.positionCount} pos `)+e}s=[e,i,r,_.zinc600(`${this.edgeCount} edges`),this.topEdge?_.zinc400(this.topEdge):""].filter(Boolean)}let i=_.bgZinc800(" "+t(s.join(o),e-2,"")+" ");const r=n(i);r<e&&(i+=_.bgZinc800(" ".repeat(e-r)));const a=_.zinc600(this.modelName.split("/").pop()||this.modelName),c=this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:`${this.tokens}`,l=_.zinc600(`${c} tok`),d=!0===this.exchangeOpen?_.emerald("OPEN"):!1===this.exchangeOpen?_.red("CLOSED"):_.zinc600("..."),u=this.tradingEnabled?_.amber("trading"):_.zinc600("read-only"),p=_.zinc600("/help"),h=[a,l,d,u].join(o),m=n(h),g=n(p),f=Math.max(1,e-m-g-2);let y=_.bgZinc900(" "+h+" ".repeat(f)+p+" ");const $=n(y);return $<e&&(y+=_.bgZinc900(" ".repeat(e-$))),this.cachedLines=[i,y],this.cachedLines}}}(C),J=t?.model||"anthropic/claude-sonnet-4.6";let W=J.replace(/^openrouter\//,"");function X(e){let t;try{t=F("openrouter",e)}catch{t={modelId:e,provider:"openrouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",id:e,name:e,inputPrice:0,outputPrice:0,contextWindow:2e5,supportsImages:!0,supportsTools:!0}}return r&&(t.baseUrl=m),t}let G=X(W),Y=0,V=!1,Q=null,Z=(new Date).toISOString(),ee=null,te=null,ne=null;const oe=new T,se=new P(oe),ie={heading:e=>_.zinc200(w(e)),link:e=>_.emerald(e),linkUrl:e=>_.zinc600(e),code:e=>_.zinc200(e),codeBlock:e=>_.zinc400(e),codeBlockBorder:e=>_.zinc600(e),quote:e=>_.zinc400(e),quoteBorder:e=>_.zinc600(e),hr:e=>_.zinc600(e),listBullet:e=>_.emerald(e),bold:e=>w(e),italic:e=>k(e),strikethrough:e=>v(e),underline:e=>b(e)},re={color:e=>_.zinc400(e)},ae={borderColor:e=>`${e}`,selectList:{selectedPrefix:e=>_.emerald(e),selectedText:e=>_.zinc200(e),description:e=>_.zinc600(e),scrollInfo:e=>_.zinc600(e),noMatch:e=>_.zinc600(e)}},ce=new B;ce.modelName=W,ce.tradingEnabled=(0,u.loadConfig)().tradingEnabled||!1;let le=null;try{if(le=await(0,c.getPositions)(),le)for(const e of le){const t=await(0,c.getMarketPrice)(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity))}}catch{}ce.setFromContext($,le||void 0),fetch("https://api.elections.kalshi.com/trade-api/v2/exchange/status",{headers:{Accept:"application/json"}}).then(e=>e.json()).then(e=>{ce.exchangeOpen=!!e.exchange_active,ce.update(),se.requestRender()}).catch(()=>{});const de=new L(1),ue=new L(1),pe=new E,he=new R(se,ae,{paddingX:1}),me=[{name:"help",description:"Show available commands"},{name:"tree",description:"Display causal tree"},{name:"edges",description:"Display edge/spread table"},{name:"pos",description:"Display Kalshi positions"},{name:"eval",description:"Trigger deep evaluation"},{name:"switch",description:"Switch thesis (e.g. /switch f582bf76)"},{name:"compact",description:"Compress conversation history"},{name:"new",description:"Start fresh session"},{name:"model",description:"Switch model (e.g. /model anthropic/claude-sonnet-4)"},{name:"env",description:"Show environment variable status"},{name:"clear",description:"Clear screen (keeps history)"},{name:"exit",description:"Exit agent (auto-saves)"}];(0,u.loadConfig)().tradingEnabled&&me.splice(-2,0,{name:"buy",description:"TICKER QTY PRICE — quick buy"},{name:"sell",description:"TICKER QTY PRICE — quick sell"},{name:"cancel",description:"ORDER_ID — cancel order"});const ge=(0,p.loadSkills)();for(const e of ge){const t=e.trigger.replace(/^\//,"");me.splice(-2,0,{name:t,description:`[skill] ${e.description.slice(0,50)}`})}const fe=new D(me,process.cwd());he.setAutocompleteProvider(fe),se.addChild(de),se.addChild(pe),se.addChild(he),se.addChild(ue),se.setFocus(he);se.showOverlay(ce,{anchor:"bottom-left",width:"100%",nonCapturing:!0});function ye(e){const t=new A(e,1,0);pe.addChild(t),se.requestRender()}function $e(){pe.addChild(new L(1))}function we(e){return new Promise(t=>{ye(_.amber(w("⚠ "))+_.zinc200(e)),$e(),se.requestRender(),ne={resolve:t}})}const ke=U.Object({thesisId:U.String({description:"Thesis ID (short or full UUID)"})}),be=U.Object({thesisId:U.String({description:"Thesis ID"}),content:U.String({description:"Signal content"}),type:U.Optional(U.String({description:"Signal type: news, user_note, external. Default: user_note"}))}),ve=U.Object({query:U.Optional(U.String({description:"Keyword search for Kalshi markets"})),series:U.Optional(U.String({description:"Kalshi series ticker (e.g. KXWTIMAX)"})),market:U.Optional(U.String({description:"Specific market ticker"}))}),_e=U.Object({query:U.String({description:"Search keywords"})}),Se=U.Object({}),xe=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:ke,execute:async(e,t)=>{const n=await y.getContext(t.thesisId);return $=n,ce.setFromContext(n,le||void 0),se.requestRender(),{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"global_context",label:"Market Snapshot",description:"Global market snapshot — top movers, expiring contracts, milestones, liquidity, signals. No thesis needed.",parameters:Se,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 knowledge search. Ask any question about prediction markets, macro, geopolitics. Returns structured answer with live market prices, thesis data, and key factors.",parameters:U.Object({q:U.String({description:'Natural language query (e.g. "iran oil prices", "fed rate cut 2026")'})}),execute:async(e,t)=>{const{fetchQuery:o}=await Promise.resolve().then(n.bind(n,19218)),s=await o(t.q);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"get_markets",label:"Traditional Markets",description:"Get traditional market prices via Databento: S&P 500 (SPY), VIX (VIXY), 20Y Treasury (TLT), Gold (GLD), Oil (USO). Daily close + 1-day change.",parameters:Se,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:"Inject Signal",description:"Inject a signal into the thesis (news, note, external event)",parameters:be,execute:async(e,t)=>{const n=await y.injectSignal(t.thesisId,t.type||"user_note",t.content);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"trigger_evaluation",label:"Evaluate",description:"Trigger a deep evaluation cycle (heavy model, takes longer)",parameters:ke,execute:async(e,t)=>{const n=await y.evaluate(t.thesisId);if(n.evaluation?.confidenceDelta&&Math.abs(n.evaluation.confidenceDelta)>=.01){const e=n.evaluation.confidenceDelta,t=Math.round(100*(n.evaluation.previousConfidence||0)),o=Math.round(100*(n.evaluation.newConfidence||0)),s=e>0?"▲":"▼";ye((e>0?_.emerald:_.red)(` ${s} Confidence ${t}% → ${o}% (${e>0?"+":""}${Math.round(100*e)})`)),$e(),ce.updateConfidence(n.evaluation.newConfidence,e),se.requestRender()}try{$=await y.getContext(t.thesisId),ce.setFromContext($,le||void 0),se.requestRender()}catch{}return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"scan_markets",label:"Scan Markets",description:"Search Kalshi + Polymarket prediction markets. Provide exactly one of: query (keyword search), series (Kalshi series ticker), or market (specific Kalshi ticker). Keyword search returns results from BOTH venues.",parameters:ve,execute:async(e,t)=>{if(t.market){const e=await(0,a.kalshiFetchMarket)(t.market);return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}if(t.series){const e=await(0,a.kalshiFetchMarketsBySeries)(t.series);return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}if(t.query){const e=await(0,a.kalshiFetchAllSeries)(),n=t.query.toLowerCase().split(/\s+/),o=e.filter(e=>n.some(t=>(e.title||"").toLowerCase().includes(t)||(e.ticker||"").toLowerCase().includes(t))).filter(e=>parseFloat(e.volume_24h_fp||e.volume_fp||"0")>0).sort((e,t)=>parseFloat(t.volume_24h_fp||t.volume_fp||"0")-parseFloat(e.volume_24h_fp||e.volume_fp||"0")).slice(0,10).map(e=>({venue:"kalshi",ticker:e.ticker,title:e.title,volume:e.volume_fp}));let s=[];try{const e=await(0,l.polymarketSearch)(t.query,10);for(const t of e)for(const e of(t.markets||[]).slice(0,3)){if(!e.active||e.closed)continue;const n=(0,l.parseOutcomePrices)(e.outcomePrices);s.push({venue:"polymarket",id:e.conditionId||e.id,title:e.groupItemTitle?`${t.title}: ${e.groupItemTitle}`:e.question||t.title,price:n[0]?Math.round(100*n[0]):null,volume24h:e.volume24hr,liquidity:e.liquidityNum})}}catch{}return{content:[{type:"text",text:JSON.stringify({kalshi:o,polymarket:s},null,2)}],details:{}}}return{content:[{type:"text",text:'{"error":"Provide query, series, or market parameter"}'}],details:{}}}},{name:"list_theses",label:"List Theses",description:"List all theses for the current user",parameters:Se,execute:async()=>{const e=await y.listTheses();return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}},{name:"get_positions",label:"Get Positions",description:"Get positions across Kalshi + Polymarket with live prices and PnL",parameters:Se,execute:async()=>{const e={kalshi:[],polymarket:[]},t=await(0,c.getPositions)();if(t){for(const e of t){const t=await(0,c.getMarketPrice)(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity))}Q=t,e.kalshi=t.map(e=>({venue:"kalshi",ticker:e.ticker,side:e.side,quantity:e.quantity,avg_price:`${e.average_price_paid}¢`,current_price:`${e.current_value}¢`,unrealized_pnl:`$${(e.unrealized_pnl/100).toFixed(2)}`,total_cost:`$${(e.total_cost/100).toFixed(2)}`}))}const n=(0,u.loadConfig)();if(n.polymarketWalletAddress)try{const t=await(0,l.polymarketGetPositions)(n.polymarketWalletAddress);e.polymarket=t.map(e=>({venue:"polymarket",market:e.title||e.slug||e.asset,side:e.outcome||"Yes",size:e.size,avg_price:`${Math.round(100*(e.avgPrice||0))}¢`,current_price:`${Math.round(100*(e.curPrice||e.currentPrice||0))}¢`,pnl:`$${(e.cashPnl||0).toFixed(2)}`}))}catch{}return 0===e.kalshi.length&&0===e.polymarket.length?{content:[{type:"text",text:"No positions found. Configure Kalshi (KALSHI_API_KEY_ID) or Polymarket (sf setup --polymarket) to see positions."}],details:{}}:{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}},{name:"web_search",label:"Web Search",description:"Search latest news and information. Use for real-time info not yet covered by the causal tree or heartbeat engine.",parameters:_e,execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY;if(!n&&!(!n&&s))return{content:[{type:"text",text:"Web search not available. Run sf login (proxied search) or set TAVILY_API_KEY."}],details:{}};let o;if(o=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:5,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:5,search_depth:"basic",include_answer:!0})}),!o.ok)return{content:[{type:"text",text:`Search failed: ${o.status}`}],details:{}};const r=await o.json(),a=(r.results||[]).map(e=>`[${e.title}](${e.url})\n${e.content?.slice(0,200)}`).join("\n\n");return{content:[{type:"text",text:`${r.answer?`Summary: ${r.answer}\n\n---\n\n`:""}${a}`}],details:{}}}},{name:"explore_public",label:"Explore Public Theses",description:"Browse public theses from other users. No auth required. Pass a slug to get details, or omit to list all.",parameters:U.Object({slug:U.Optional(U.String({description:"Specific thesis slug, or empty to list all"}))}),execute:async(e,t)=>{const n="https://simplefunctions.dev";if(t.slug){const e=await fetch(`${n}/api/public/thesis/${t.slug}`);if(!e.ok)return{content:[{type:"text",text:`Not found: ${t.slug}`}],details:{}};const o=await e.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}const o=await fetch(`${n}/api/public/theses`);if(!o.ok)return{content:[{type:"text",text:"Failed to fetch public theses"}],details:{}};const s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"create_strategy",label:"Create Strategy",description:"Create a trading strategy for a thesis. Extract hard conditions (entryBelow/stopLoss/takeProfit as cents) and soft conditions from conversation. Called when user mentions specific trade ideas.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),marketId:U.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:U.String({description:"Human-readable market name"}),direction:U.String({description:"yes or no"}),horizon:U.Optional(U.String({description:"short, medium, or long. Default: medium"})),entryBelow:U.Optional(U.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:U.Optional(U.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:U.Optional(U.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:U.Optional(U.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:U.Optional(U.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:U.Optional(U.Number({description:"Contracts per order. Default: 50"})),softConditions:U.Optional(U.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:U.Optional(U.String({description:"Full logic description"}))}),execute:async(e,t)=>{const n=await y.createStrategyAPI(t.thesisId,{marketId:t.marketId,market:t.market,direction:t.direction,horizon:t.horizon,entryBelow:t.entryBelow,entryAbove:t.entryAbove,stopLoss:t.stopLoss,takeProfit:t.takeProfit,maxQuantity:t.maxQuantity,perOrderQuantity:t.perOrderQuantity,softConditions:t.softConditions,rationale:t.rationale,createdBy:"agent"});return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"list_strategies",label:"List Strategies",description:"List strategies for a thesis. Filter by status (active/watching/executed/cancelled/review) or omit for all.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),status:U.Optional(U.String({description:"Filter by status. Omit for all."}))}),execute:async(e,t)=>{const n=await y.getStrategies(t.thesisId,t.status);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"update_strategy",label:"Update Strategy",description:"Update a strategy (change stop loss, take profit, status, priority, etc.)",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),strategyId:U.String({description:"Strategy ID (UUID)"}),stopLoss:U.Optional(U.Number({description:"New stop loss (cents)"})),takeProfit:U.Optional(U.Number({description:"New take profit (cents)"})),entryBelow:U.Optional(U.Number({description:"New entry below trigger (cents)"})),entryAbove:U.Optional(U.Number({description:"New entry above trigger (cents)"})),status:U.Optional(U.String({description:"New status: active|watching|executed|cancelled|review"})),priority:U.Optional(U.Number({description:"New priority"})),softConditions:U.Optional(U.String({description:"Updated soft conditions"})),rationale:U.Optional(U.String({description:"Updated rationale"}))}),execute:async(e,t)=>{const{thesisId:n,strategyId:o,...s}=t,i=await y.updateStrategyAPI(n,o,s);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"get_milestones",label:"Milestones",description:"Get upcoming events from Kalshi calendar. Use to check economic releases, political events, or other catalysts coming up that might affect the thesis.",parameters:U.Object({hours:U.Optional(U.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:U.Optional(U.String({description:"Filter by category (e.g. Economics, Politics, Sports)"}))}),execute:async(e,t)=>{const n=t.hours||168,o=new Date,s=`https://api.elections.kalshi.com/trade-api/v2/milestones?limit=200&minimum_start_date=${o.toISOString()}`+(t.category?`&category=${t.category}`:""),i=await fetch(s,{headers:{Accept:"application/json"}});if(!i.ok)return{content:[{type:"text",text:`Milestones API error: ${i.status}`}],details:{}};const r=await i.json(),a=o.getTime()+36e5*n,c=(r.milestones||[]).filter(e=>new Date(e.start_date).getTime()<=a).slice(0,30).map(e=>({title:e.title,category:e.category,start_date:e.start_date,related_event_tickers:e.related_event_tickers,hours_until:Math.round((new Date(e.start_date).getTime()-o.getTime())/36e5)}));return{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}}},{name:"get_forecast",label:"Forecast",description:"Get market distribution (P50/P75/P90 percentile history) for a Kalshi event. Shows how market consensus has shifted over time.",parameters:U.Object({eventTicker:U.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:U.Optional(U.Number({description:"Days of history (default 7)"}))}),execute:async(e,t)=>{const{getForecastHistory:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=t.days||7,i=await fetch(`https://api.elections.kalshi.com/trade-api/v2/events/${t.eventTicker}`,{headers:{Accept:"application/json"}});if(!i.ok)return{content:[{type:"text",text:`Event not found: ${t.eventTicker}`}],details:{}};const r=await i.json(),a=r.event?.series_ticker;if(!a)return{content:[{type:"text",text:`No series_ticker for ${t.eventTicker}`}],details:{}};const c=await o({seriesTicker:a,eventTicker:t.eventTicker,percentiles:[5e3,7500,9e3],startTs:Math.floor((Date.now()-864e5*s)/1e3),endTs:Math.floor(Date.now()/1e3),periodInterval:1440});return c&&0!==c.length?{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}:{content:[{type:"text",text:"No forecast data available"}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled (resolved) contracts with P&L. Shows which contracts won/lost and realized returns.",parameters:U.Object({ticker:U.Optional(U.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getSettlements:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await o({limit:100,ticker:t.ticker});return s?{content:[{type:"text",text:JSON.stringify(s.settlements,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance and portfolio value.",parameters:Se,execute:async()=>{const{getBalance:e}=await Promise.resolve().then(n.t.bind(n,96139,23)),t=await e();return t?{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_orders",label:"Orders",description:"Get current resting orders on Kalshi. Stale orders (>7 days old AND >10¢ from market) are flagged.",parameters:U.Object({status:U.Optional(U.String({description:"Filter by status: resting, canceled, executed. Default: resting"}))}),execute:async(e,t)=>{const{getOrders:o,getMarketPrice:s}=await Promise.resolve().then(n.t.bind(n,96139,23)),i=await o({status:t.status||"resting",limit:100});if(!i)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};const r=await Promise.all((i.orders||[]).map(async e=>{const t=e.created_time?Math.round((Date.now()-new Date(e.created_time).getTime())/864e5):null;let n=null,o=!1;try{const i=await s(e.ticker);null!=i&&e.yes_price_dollars&&(n=Math.round(100*Math.abs(i-parseFloat(e.yes_price_dollars))),null!=t&&t>7&&n>10&&(o=!0))}catch{}return{...e,daysSinceCreated:t,distanceFromMarket:n,stale:o}}));return{content:[{type:"text",text:JSON.stringify(r,null,2)}],details:{}}}},{name:"get_fills",label:"Fills",description:"Get recent trade fills (executed trades) on Kalshi.",parameters:U.Object({ticker:U.Optional(U.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getFills:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=await o({ticker:t.ticker,limit:50});return s?{content:[{type:"text",text:JSON.stringify(s.fills,null,2)}],details:{}}:{content:[{type:"text",text:"Kalshi not configured."}],details:{}}}},{name:"get_liquidity",label:"Liquidity Scanner",description:"Scan orderbook liquidity for a topic across Kalshi + Polymarket. Returns spread, depth, liquidity scores. Topics: "+Object.keys(d.TOPIC_SERIES).join(", "),parameters:U.Object({topic:U.String({description:"Topic to scan (e.g. oil, crypto, fed, geopolitics)"})}),execute:async(e,t)=>{const n=t.topic.toLowerCase(),o=d.TOPIC_SERIES[n];if(!o)return{content:[{type:"text",text:`Unknown topic "${t.topic}". Available: ${Object.keys(d.TOPIC_SERIES).join(", ")}`}],details:{}};const s=[];for(const e of o)try{const t=`https://api.elections.kalshi.com/trade-api/v2/markets?series_ticker=${e}&status=open&limit=200`,n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)continue;const o=(await n.json()).markets||[],i=await Promise.allSettled(o.slice(0,20).map(e=>(0,c.getPublicOrderbook)(e.ticker).then(t=>({ticker:e.ticker,title:e.title,ob:t}))));for(const e of i){if("fulfilled"!==e.status||!e.value.ob)continue;const{ticker:t,title:n,ob:o}=e.value,i=(o.yes_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),r=(o.no_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),a=i[0]?.price||0,c=r.length>0?100-r[0].price:100,l=c-a,d=i.slice(0,3).reduce((e,t)=>e+t.qty,0)+r.slice(0,3).reduce((e,t)=>e+t.qty,0),u=l<=2&&d>=500?"high":l<=5&&d>=100?"medium":"low";s.push({venue:"kalshi",ticker:t,title:(n||"").slice(0,50),bestBid:a,bestAsk:c,spread:l,depth:Math.round(d),liquidityScore:u})}}catch{}try{const e=await(0,l.polymarketSearch)(n,5);for(const t of e)for(const e of(t.markets||[]).slice(0,5)){if(!e.active||e.closed||!e.clobTokenIds)continue;const n=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!n)continue;const o=await(0,l.polymarketGetOrderbookWithDepth)(n[0]);o&&s.push({venue:"polymarket",ticker:(e.question||t.title).slice(0,50),bestBid:o.bestBid,bestAsk:o.bestAsk,spread:o.spread,depth:o.bidDepthTop3+o.askDepthTop3,liquidityScore:o.liquidityScore})}}catch{}return s.sort((e,t)=>e.spread-t.spread),{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"inspect_book",label:"Orderbook",description:'Get orderbook depth, spread, and liquidity. Returns a status field per market: "ok", "empty_orderbook", "market_closed", or "api_error". Supports multiple tickers in one call — use tickers array for batch position checks.',parameters:U.Object({ticker:U.Optional(U.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:U.Optional(U.Array(U.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:U.Optional(U.String({description:'Search Polymarket by keyword (e.g. "oil price above 100")'}))}),execute:async(e,t)=>{const n=[],o=[];t.tickers?.length?o.push(...t.tickers):t.ticker&&o.push(t.ticker);for(const e of o)try{const t=await(0,a.kalshiFetchMarket)(e),o=t.status||"unknown";if("open"!==o&&"active"!==o)n.push({venue:"kalshi",ticker:e,title:t.title,status:"market_closed",reason:`Market status: ${o}. Orderbook unavailable for closed/settled markets.`,lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0"))});else{const o=await(0,c.getPublicOrderbook)(e),s=(o?.yes_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),i=(o?.no_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price);if(0===s.length&&0===i.length)n.push({venue:"kalshi",ticker:e,title:t.title,status:"empty_orderbook",reason:"Market open but no resting orders. Normal for illiquid/OTM contracts. Use lastPrice as reference.",lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0")),volume24h:parseFloat(t.volume_24h_fp||"0"),openInterest:parseFloat(t.open_interest_fp||"0"),expiry:t.close_time||null});else{const o=s[0]?.price||0,r=i.length>0?100-i[0].price:s[0]?s[0].price+1:100,a=r-o,c=s.slice(0,3).reduce((e,t)=>e+t.size,0)+i.slice(0,3).reduce((e,t)=>e+t.size,0),l=a<=2&&c>=500?"high":a<=5&&c>=100?"medium":"low";n.push({venue:"kalshi",ticker:e,title:t.title,status:"ok",bestBid:o,bestAsk:r,spread:a,liquidityScore:l,bidLevels:s.slice(0,5),askLevels:i.slice(0,5).map(e=>({price:100-e.price,size:e.size})),totalBidDepth:s.reduce((e,t)=>e+t.size,0),totalAskDepth:i.reduce((e,t)=>e+t.size,0),lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0")),volume24h:parseFloat(t.volume_24h_fp||"0"),openInterest:parseFloat(t.open_interest_fp||"0"),expiry:t.close_time||null})}}}catch(t){n.push({venue:"kalshi",ticker:e,status:"api_error",reason:`Kalshi API error: ${t.message}`})}if(t.polyQuery)try{const e=await(0,l.polymarketSearch)(t.polyQuery,5);for(const t of e)for(const e of(t.markets||[]).slice(0,3)){if(!e.active||e.closed||!e.clobTokenIds)continue;const o=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!o)continue;const s=await(0,l.polymarketGetOrderbookWithDepth)(o[0]);if(!s)continue;const i=(0,l.parseOutcomePrices)(e.outcomePrices);n.push({venue:"polymarket",title:e.question||t.title,bestBid:s.bestBid,bestAsk:s.bestAsk,spread:s.spread,liquidityScore:s.liquidityScore,totalBidDepth:s.totalBidDepth,totalAskDepth:s.totalAskDepth,lastPrice:i[0]?Math.round(100*i[0]):0,volume24h:e.volume24hr||0})}}catch{}return 0===n.length?{content:[{type:"text",text:"No markets found. Provide ticker (Kalshi) or polyQuery (Polymarket search)."}],details:{}}:{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"get_schedule",label:"Schedule",description:"Get exchange status (open/closed) and trading hours. Use to check if low liquidity is due to off-hours.",parameters:Se,execute:async()=>{try{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:`Exchange API error: ${e.status}`}],details:{}};const t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}catch(e){return{content:[{type:"text",text:`Failed: ${e.message}`}],details:{}}}}},{name:"create_thesis",label:"Create Thesis",description:"Create a new thesis from a raw thesis statement. Returns the thesis ID, confidence, node count, and edge count. In explorer mode, this automatically transitions to thesis mode.",parameters:U.Object({rawThesis:U.String({description:"The raw thesis statement to create"}),webhookUrl:U.Optional(U.String({description:"Optional webhook URL for notifications"}))}),execute:async(e,t)=>{const n=await y.createThesis(t.rawThesis,!0),o=n.thesis||n,s=o.causalTree?.nodes?.length||0,i=(o.edges||[]).length,r="number"==typeof o.confidence?Math.round(100*o.confidence):0;if(x&&o.id){x=!1,S=o.id;try{$=await y.getContext(o.id);const e=Oe($);Pe.setSystemPrompt(e),ce.setFromContext($,le||void 0),se.requestRender()}catch{}}return{content:[{type:"text",text:`Thesis created.\nID: ${o.id}\nConfidence: ${r}%\nNodes: ${s}\nEdges: ${i}\n\nHeartbeat engine is now monitoring this thesis 24/7. Use /switch ${o.id?.slice(0,8)} to focus on it.`}],details:{}}}},{name:"get_edges",label:"Get Edges",description:"Get top edges across all active theses. Returns the top 10 edges sorted by absolute edge size with ticker, market name, edge size, direction, and venue.",parameters:Se,execute:async()=>{const{theses:e}=await y.listTheses(),t=(e||[]).filter(e=>"active"===e.status||"monitoring"===e.status),n=await Promise.allSettled(t.map(async e=>((await y.getContext(e.id)).edges||[]).map(t=>({...t,thesisId:e.id})))),o=[];for(const e of n)"fulfilled"===e.status&&o.push(...e.value);o.sort((e,t)=>Math.abs(t.edge||t.edgeSize||0)-Math.abs(e.edge||e.edgeSize||0));const s=o.slice(0,10).map(e=>({ticker:e.marketId||e.ticker||"-",market:e.market||e.marketTitle||"-",edge:e.edge||e.edgeSize||0,direction:e.direction||"yes",venue:e.venue||"kalshi"}));return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"get_feed",label:"Get Feed",description:"Get evaluation history with topSignal highlighting. The most important signal (largest confidence change or most actionable) is surfaced first so you don't have to scan all entries.",parameters:U.Object({hours:U.Optional(U.Number({description:"Hours of history to fetch (default 24)"}))}),execute:async(e,t)=>{const n=await y.getFeed(t.hours||24),o=Array.isArray(n)?n:n?.evaluations||n?.items||[];let s=null,i=0;for(const e of o){let t=0;const n=Math.abs(e.confidenceDelta||e.confidence_delta||0);n>0?t=100*n:e.summary?.length>50&&(t=.1),t>i&&(i=t,s=e)}const r={total:o.length};return s&&(r.topSignal={summary:s.summary||s.content||"",confidenceDelta:s.confidenceDelta||s.confidence_delta||0,evaluatedAt:s.evaluatedAt||s.evaluated_at||s.createdAt||"",why:i>1?"Largest confidence movement in this period":i>0?"Most substantive evaluation (no confidence change)":"Most recent evaluation"}),r.items=o,{content:[{type:"text",text:JSON.stringify(r,null,2)}],details:{}}}},{name:"get_changes",label:"Get Changes",description:"Get recent market changes detected server-side. Returns real price moves (>5¢), new contracts, and removed/settled contracts across Kalshi, Polymarket, and traditional markets. Checked every 15 minutes. Use for situational awareness, discovering new opportunities, or checking if anything material happened recently.",parameters:U.Object({hours:U.Optional(U.Number({description:"Hours of history (default 1)"}))}),execute:async(e,t)=>{const n=t.hours||1,o=new Date(Date.now()-60*n*60*1e3).toISOString(),s=process.env.SF_API_URL||"https://simplefunctions.dev",i=await fetch(`${s}/api/changes?since=${encodeURIComponent(o)}&limit=100`);if(!i.ok)return{content:[{type:"text",text:JSON.stringify({error:`API error ${i.status}`})}],details:{}};const r=await i.json();return{content:[{type:"text",text:JSON.stringify(r,null,2)}],details:{}}}}];xe.push({name:"what_if",label:"What-If",description:'Run a what-if scenario: override causal tree node probabilities and see how edges and confidence change. Zero LLM cost — pure computation. Use when user asks "what if X happens?" or "what if this node drops to Y%?".',parameters:U.Object({overrides:U.Array(U.Object({nodeId:U.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:U.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{if(S)try{$=await y.getContext(S)}catch{}const n=$,o=[];const s=n.causalTree?.nodes||[];!function e(t){for(const n of t)o.push(n),n.children?.length&&e(n.children)}(s);const i=s.filter(e=>0===e.depth||void 0===e.depth&&!e.id.includes(".")),r=new Map(t.overrides.map(e=>[e.nodeId,e.newProbability]));function a(e){if(r.has(e.id))return r.get(e.id);if(e.children?.length>0){const t=e.children.map(e=>a(e)),n=e.children.map(e=>e.importance||1),o=n.reduce((e,t)=>e+t,0);return o>0?t.reduce((e,t,o)=>e+t*n[o],0)/o:t.reduce((e,t)=>e+t,0)/t.length}return e.probability??0}const c=i.reduce((e,t)=>e+(t.probability||0)*(t.importance||0),0),l=i.reduce((e,t)=>e+a(t)*(t.importance||0),0),d=new Map;for(const[e,t]of r.entries()){const n=o.find(t=>t.id===e);n&&n.probability>0&&d.set(e,Math.max(0,Math.min(2,t/n.probability)))}const u=(n.edges||[]).map(e=>{const t=e.relatedNodeId;let n=1;if(t){const e=[t,t.split(".").slice(0,-1).join("."),t.split(".")[0]].filter(Boolean);for(const t of e)if(d.has(t)){n=d.get(t);break}}const o=e.marketPrice||0,s=e.thesisPrice||e.thesisImpliedPrice||o,i=e.edge||e.edgeSize||0,r=Math.round(100*(o+(s-o)*n))/100,a=e.direction||"yes",c=Math.round(100*("yes"===a?r-o:o-r))/100;return{market:e.market||e.marketTitle||e.marketId,marketPrice:o,oldEdge:i,newEdge:c,delta:c-i,signal:Math.abs(c-i)<1?"unchanged":i>0&&c<0||i<0&&c>0?"REVERSED":Math.abs(c)<2?"GONE":"reduced"}}).filter(e=>"unchanged"!==e.signal),p=null!=n.confidence?Math.round(100*Number(n.confidence)):null,h={overrides:t.overrides.map(e=>{const t=o.find(t=>t.id===e.nodeId);return{nodeId:e.nodeId,label:t?.label||e.nodeId,oldProb:t?.probability,newProb:e.newProbability}}),serverConfidence:p,treeConfidence:{old:Math.round(100*c),new:Math.round(100*l),delta:Math.round(100*(l-c))},note:null!=p&&Math.abs(p-Math.round(100*c))>5?`serverConfidence (${p}%) differs from treeConfidence (${Math.round(100*c)}%) because the LLM evaluation considers factors beyond the causal tree.`:void 0,affectedEdges:u};return{content:[{type:"text",text:JSON.stringify(h,null,2)}],details:{}}}}),xe.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions on a topic. Returns top posts with engagement metrics, sentiment analysis, and key themes. Use for social signal research on any prediction market topic.",parameters:U.Object({query:U.String({description:'Search query (e.g. "iran oil", "fed rate cut", "$BTC")'}),mode:U.Optional(U.String({description:'"summary" (default, with AI analysis) or "raw" (just posts)'})),hours:U.Optional(U.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await y.searchX(t.query,{mode:t.mode,hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_volume",label:"X Volume",description:"Get X discussion volume trend for a topic — total posts, velocity change vs prior period, peak time, and hourly timeseries. Use to detect social momentum shifts.",parameters:U.Object({query:U.String({description:"Search query"}),hours:U.Optional(U.Number({description:"Hours of history (default 72)"}))}),execute:async(e,t)=>{const n=await y.getXVolume(t.query,{hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_news",label:"X News",description:"Get news stories trending on X — titles, summaries, categories, and ticker mentions. Use for breaking news and narrative tracking.",parameters:U.Object({query:U.String({description:"Search query"}),limit:U.Optional(U.Number({description:"Max stories (default 10)"}))}),execute:async(e,t)=>{const n=await y.searchXNews(t.query,{limit:t.limit});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"x_account",label:"X Account",description:"Get recent posts from a specific X account. Use to track key opinion leaders, officials, or analysts.",parameters:U.Object({username:U.String({description:"X username (with or without @)"}),hours:U.Optional(U.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await y.getXAccount(t.username,{hours:t.hours});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"heartbeat_config",label:"Heartbeat Config",description:"View or update heartbeat settings for a thesis: scan intervals, model tier, budget cap, pause/resume. Also shows this month's cost breakdown.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),newsIntervalMin:U.Optional(U.Number({description:"News scan interval in minutes (15-1440)"})),xIntervalMin:U.Optional(U.Number({description:"X scan interval in minutes (60-1440)"})),evalModelTier:U.Optional(U.String({description:"Eval model: cheap, medium, or heavy"})),monthlyBudgetUsd:U.Optional(U.Number({description:"Monthly budget cap in USD (0 = unlimited)"})),paused:U.Optional(U.Boolean({description:"Pause (true) or resume (false) heartbeat"}))}),execute:async(e,t)=>{if(t.newsIntervalMin||t.xIntervalMin||t.evalModelTier||void 0!==t.monthlyBudgetUsd||void 0!==t.paused){const e={};t.newsIntervalMin&&(e.newsIntervalMin=t.newsIntervalMin),t.xIntervalMin&&(e.xIntervalMin=t.xIntervalMin),t.evalModelTier&&(e.evalModelTier=t.evalModelTier),void 0!==t.monthlyBudgetUsd&&(e.monthlyBudgetUsd=t.monthlyBudgetUsd),void 0!==t.paused&&(e.paused=t.paused),await y.updateHeartbeatConfig(t.thesisId,e)}const n=await y.getHeartbeatConfig(t.thesisId);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}});const Ce=(0,u.loadConfig)();Ce.tradingEnabled&&xe.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Shows a preview and asks for user confirmation before executing. Use for limit or market orders.",parameters:U.Object({ticker:U.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:U.String({description:"yes or no"}),action:U.String({description:"buy or sell"}),type:U.String({description:"limit or market"}),count:U.Number({description:"Number of contracts"}),price_cents:U.Optional(U.Number({description:"Limit price in cents (1-99). Required for limit orders."}))}),execute:async(e,t)=>{const{createOrder:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),s=t.price_cents?Math.round(Number(t.price_cents)):void 0,i=((s||99)*t.count/100).toFixed(2);ye([_.zinc200(w("ORDER PREVIEW")),` Ticker: ${t.ticker}`,` Side: ${"yes"===t.side?_.emerald("YES"):_.red("NO")}`,` Action: ${t.action.toUpperCase()}`,` Quantity: ${t.count}`,` Type: ${t.type}`,s?` Price: ${s}¢`:"",` Max cost: $${i}`].filter(Boolean).join("\n")),$e(),se.requestRender();if(!(await we("Execute this order? (y/n)")).toLowerCase().startsWith("y"))return{content:[{type:"text",text:"Order cancelled by user."}],details:{}};try{const e=await o({ticker:t.ticker,side:t.side,action:t.action,type:t.type,count:t.count,...s?{yes_price:s}:{}}),n=e.order||e;return{content:[{type:"text",text:`Order placed: ${n.order_id||"OK"}\nStatus: ${n.status||"-"}\nFilled: ${n.fill_count_fp||0}/${n.initial_count_fp||t.count}`}],details:{}}}catch(e){const t=e.message||String(e);return t.includes("403")?{content:[{type:"text",text:"403 Forbidden — your Kalshi key lacks write permission. Get a read+write key at kalshi.com/account/api-keys"}],details:{}}:{content:[{type:"text",text:`Order failed: ${t}`}],details:{}}}}},{name:"cancel_order",label:"Cancel Order",description:"Cancel a resting order by order ID.",parameters:U.Object({order_id:U.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{const{cancelOrder:o}=await Promise.resolve().then(n.t.bind(n,96139,23));if(!(await we(`Cancel order ${t.order_id}? (y/n)`)).toLowerCase().startsWith("y"))return{content:[{type:"text",text:"Cancel aborted by user."}],details:{}};try{return await o(t.order_id),{content:[{type:"text",text:`Order ${t.order_id} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Cancel failed: ${e.message}`}],details:{}}}}});function Oe(e){const t=e.edges?.sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.market||"").slice(0,40)} | ${e.venue||"kalshi"} | mkt ${e.marketPrice}¢ → thesis ${e.thesisPrice}¢ | edge ${e.edge>0?"+":""}${e.edge} | ${e.orderbook?.liquidityScore||"?"}`).join("\n")||" (no edge data)",n=e.causalTree?.nodes?.filter(e=>0===e.depth).map(e=>` ${e.id} ${(e.label||"").slice(0,40)} — ${Math.round(100*e.probability)}%`).join("\n")||" (no causal tree)",o="number"==typeof e.confidence?Math.round(100*e.confidence):"string"==typeof e.confidence?parseInt(e.confidence):0;return`You are a prediction market trading assistant. Your job is not to please the user — it is to help them see reality clearly and make correct trading decisions.\n\n## Your analytical framework\n\nEach thesis has a causal tree. Every node is a causal hypothesis with a probability. Nodes have causal relationships — when upstream nodes change, downstream nodes follow.\n\nEdge = thesis-implied price - actual market price. Positive edge = market underprices. Contracts with large edges AND good liquidity are most tradeable.\n\nexecutableEdge = real edge after subtracting bid-ask spread. Big theoretical edge with wide spread may not be worth entering.\n\n### Edge diagnosis (always classify)\nWhen reporting an edge, classify it:\n- "consensus gap": depth >= 500, market actively disagrees — real edge, real opponents\n- "attention gap": depth < 100, no real pricing — edge may be illusory, needs catalyst\n- "timing gap": market directionally agrees but lags — may close suddenly on news\n- "risk premium": edge reflects settlement ambiguity or platform risk, not alpha\nFor edges > 20 cents, state in one sentence what must be true for the market to be right and the thesis wrong.\n\n### Price reliability\n47 cents with depth 14K = strong consensus. 47 cents with depth 50 = three people's opinion.\n- depth >= 500: reliable, treat as market consensus\n- depth 100-500: moderate confidence, caveat when citing\n- depth < 100: unreliable — do NOT treat as "the market thinks X"\n- spread > 5 cents: wide disagreement, noisy midpoint\n- liquidityScore = low: do NOT recommend entry\n\n### Kill condition awareness\nEach top-level causal node has an implicit falsifier. When scanning news or evaluating events, check: "Does any event here fundamentally break a core assumption?" If yes, flag immediately — this overrides all other analysis.\n\n### Catalyst and time\nWhen discussing an edge, always state contract expiry and next identifiable catalyst. No visible catalyst = flag capital lock risk.\n\n### Research workflow\nFor complex questions, chain multiple tool calls:\n1. get_world_state (broad situational awareness) 2. get_context 3. inspect_book 4. get_liquidity 5. web_search 6. search_x 7. monitor_the_situation (scrape specific URLs) 8. synthesize\nUse get_world_delta for efficient polling (30-50 tokens vs 800 for full state). Use enrich_content to cross-reference any text with 9,706 markets.\nDon't answer a complex question with a single tool call.\n\n### Social signal research\nUse search_x to check X/Twitter sentiment on any topic — especially useful for geopolitical events, macro shifts, and breaking news that moves prediction markets. Use x_volume to detect discussion spikes (velocity > 1 = increasing attention). Use x_account to track specific analysts or officials.\n\n### Heartbeat config\nUse heartbeat_config to view or adjust per-thesis heartbeat settings: news/X scan intervals, evaluation model tier (cheap/medium/heavy), monthly budget cap, pause/resume. Also shows this month's cost breakdown (LLM calls, search calls, tokens, spend). Useful when the user asks about costs, wants to slow down/speed up monitoring, or if you detect budget overrun.\n\n### Conditional rules\n- Portfolio/positions questions: flag correlated exposure — positions sharing upstream causal nodes are not independent bets.\n- No catalyst visible within 30 days + edge not improving: flag "stale capital risk."\n- Edges < 10 cents, thin liquidity, no catalyst near: say "nothing to do right now." Do not manufacture urgency.\n\nShort-term markets settle into hard data that calibrates the thesis. Use them to verify node probabilities, not to bet.\n\n## Your behavioral rules\n\n- IMPORTANT: You do NOT know the user's current positions at conversation start. Before discussing trades, recommending entries/exits, or analyzing portfolio risk, call get_positions FIRST. Never assume the user has no positions — they may have large existing holdings you don't know about.\n- Think before calling tools. If the data is already in context, don't re-fetch.\n- If the user says "note this" or mentions a news event, inject a signal. Don't ask "should I note this?"\n- If the user says "evaluate" or "run it", trigger immediately. Don't confirm.\n- Don't end every response with "anything else?" — the user will ask when they want to.\n- If the user asks about latest news or real-time events, use web_search first, then answer based on results. If you find important information, suggest injecting it as a signal.\n- If you notice an edge narrowing or disappearing, say so proactively. Don't only report good news.\n- If a causal tree node probability seriously contradicts the market price, point it out.\n- Use Chinese if the user writes in Chinese, English if they write in English.\n- For any question about prices, positions, or P&L, ALWAYS call a tool to get fresh data first. Never answer price-related questions using the cached data in this system prompt.\n- Prices are in cents (e.g. 35¢). P&L, cost, and balance are in dollars (e.g. $90.66). Tool outputs are pre-formatted with units — do not re-convert.\n- Align tables. Be precise with numbers to the cent.\n\n## Strategy rules\n\nWhen the conversation produces a concrete trade idea (specific contract, direction, price conditions), use create_strategy to record it immediately. Don't wait for the user to say "record this."\n- Extract hard conditions (specific prices in cents) into entryBelow/stopLoss/takeProfit.\n- Put fuzzy conditions into softConditions (e.g. "only if n3 > 60%", "spread < 3¢").\n- Put the full reasoning into rationale.\n- After creating, confirm the strategy details.\n- If the user says "change the stop loss on T150 to 30", use update_strategy.\n\n## Intent & Execution\n\nUse create_intent to declare execution intents with trigger conditions (price_below, price_above, time, immediate). Use list_intents / cancel_intent to manage. The local runtime daemon (runtime_start/runtime_stop/runtime_status) evaluates triggers and executes orders via local API keys.\n\n## Trading status\n\n${Ce.tradingEnabled?"Trading is ENABLED. You have place_order, cancel_order, create_intent, and runtime tools.":"Trading is DISABLED. You cannot place or cancel orders. Tell the user to run `sf setup --enable-trading` to unlock trading. Intent system still works for declaring plans."}\n\n## Current thesis state\n\nThesis: ${e.thesis||e.rawThesis||"N/A"}\nID: ${e.thesisId||S}\nConfidence: ${o}%\nStatus: ${e.status}\n\nTop-level causal tree nodes:\n${n}\n\nTop 5 edges by magnitude:\n${t}\n\n${e.lastEvaluation?.summary?`Latest evaluation summary: ${e.lastEvaluation.summary.slice(0,300)}`:""}`}xe.push({name:"update_thesis",label:"Update Thesis",description:"Update thesis metadata: title, status (active/paused/archived), webhookUrl.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),title:U.Optional(U.String({description:"New title"})),status:U.Optional(U.String({description:"active, paused, or archived"})),webhookUrl:U.Optional(U.String({description:"Webhook URL (HTTPS)"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,s=await y.request("PATCH",`/api/thesis/${n}`,o);return{content:[{type:"text",text:JSON.stringify(s)}],details:{}}}},{name:"augment_tree",label:"Augment Tree",description:"Review and merge suggested causal tree nodes from evaluations. Evolves the tree structure.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),dryRun:U.Optional(U.Boolean({description:"Preview changes without applying (default false)"}))}),execute:async(e,t)=>{const n=t.dryRun?"?dryRun=true":"",o=await y.request("POST",`/api/thesis/${t.thesisId}/augment${n}`);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"add_position",label:"Add Position",description:"Record a new position in a thesis for tracking.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),venue:U.String({description:"kalshi or polymarket"}),externalMarketId:U.String({description:"Market ticker"}),marketTitle:U.String({description:"Market name"}),direction:U.String({description:"yes or no"}),entryPrice:U.Number({description:"Entry price in cents"}),size:U.Optional(U.Number({description:"Contracts"})),rationale:U.Optional(U.String({description:"Why"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,s=await y.request("POST",`/api/thesis/${n}/positions`,o);return{content:[{type:"text",text:JSON.stringify(s)}],details:{}}}},{name:"update_position",label:"Update Position",description:"Update position: currentPrice, edge, status (open→closed).",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),positionId:U.String({description:"Position ID"}),currentPrice:U.Optional(U.Number({description:"Current price (cents)"})),edge:U.Optional(U.Number({description:"Current edge (cents)"})),status:U.Optional(U.String({description:"open or closed"}))}),execute:async(e,t)=>{const{thesisId:n,positionId:o,...s}=t,i=await y.request("PATCH",`/api/thesis/${n}/positions/${o}`,s);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"close_position",label:"Close Position",description:"Remove a position record from a thesis.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),positionId:U.String({description:"Position ID"})}),execute:async(e,t)=>{const n=await y.request("DELETE",`/api/thesis/${t.thesisId}/positions/${t.positionId}`);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"get_evaluation_history",label:"Evaluation History",description:"Confidence trajectory over time — daily aggregated. For trend analysis.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await y.request("GET",`/api/thesis/${t.thesisId}/evaluations`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"update_nodes",label:"Update Nodes",description:"Directly update causal tree node probabilities. Zero LLM cost. Use for confirmed facts (lock nodes at 0.99).",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),updates:U.Array(U.Object({nodeId:U.String({description:"Node ID (e.g. n3)"}),probability:U.Number({description:"New probability (0-1)"}),reason:U.Optional(U.String({description:"Why"}))})),lock:U.Optional(U.Array(U.String({description:"Node IDs to lock"})))}),execute:async(e,t)=>{const n=await y.request("POST",`/api/thesis/${t.thesisId}/nodes/update`,{updates:t.updates,lock:t.lock});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"configure_heartbeat",label:"Configure Heartbeat",description:"Adjust the 24/7 monitoring engine: news interval, X interval, model tier, budget, pause/resume.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"}),newsIntervalMin:U.Optional(U.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:U.Optional(U.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:U.Optional(U.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:U.Optional(U.Number({description:"Monthly budget cap (0=unlimited)"})),paused:U.Optional(U.Boolean({description:"Pause/resume"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,s=await y.request("PATCH",`/api/thesis/${n}/heartbeat`,o);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"get_heartbeat_status",label:"Heartbeat Status",description:"Heartbeat config + cost summary for a thesis.",parameters:U.Object({thesisId:U.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await y.request("GET",`/api/thesis/${t.thesisId}/heartbeat`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}}),xe.push({name:"get_trade_ideas",label:"Trade Ideas",description:"S&T-style trade pitches: conviction, catalyst, direction, risk. No auth required.",parameters:U.Object({freshness:U.Optional(U.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:U.Optional(U.String({description:"Filter: macro, geopolitics, crypto, policy, event"}))}),execute:async(e,t)=>{const n=new URLSearchParams;t.freshness&&n.set("freshness",t.freshness),t.category&&n.set("category",t.category);const o=await fetch(`${i}/api/public/ideas?${n.toString()}`);if(!o.ok)return{content:[{type:"text",text:`Ideas API error: ${o.status}`}],details:{}};const s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"create_intent",label:"Create Intent",description:"Declare an execution intent with trigger conditions. Runtime daemon evaluates triggers and executes via local keys.",parameters:U.Object({action:U.String({description:"buy or sell"}),venue:U.String({description:"kalshi or polymarket"}),marketId:U.String({description:"Market ticker"}),marketTitle:U.String({description:"Human-readable name"}),direction:U.String({description:"yes or no"}),targetQuantity:U.Number({description:"Number of contracts"}),maxPrice:U.Optional(U.Number({description:"Max price per contract in cents (1-99)"})),triggerType:U.Optional(U.String({description:"immediate, price_below, price_above, time"})),triggerPrice:U.Optional(U.Number({description:"Price trigger threshold in cents"})),rationale:U.Optional(U.String({description:"Why this trade"})),autoExecute:U.Optional(U.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(e,t)=>{const n=await y.createIntent({...t,source:"agent",expireAt:new Date(Date.now()+864e5).toISOString()});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"list_intents",label:"List Intents",description:"List execution intents — pending, armed, triggered, executing, filled.",parameters:U.Object({activeOnly:U.Optional(U.Boolean({description:"Only active intents (default true)"}))}),execute:async(e,t)=>{const n=await y.listIntents({active:!1!==t.activeOnly});return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"cancel_intent",label:"Cancel Intent",description:"Cancel an active intent — stops trigger evaluation and prevents execution.",parameters:U.Object({intentId:U.String({description:"Intent ID to cancel"})}),execute:async(e,t)=>{const n=await y.cancelIntentAPI(t.intentId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}}),xe.push({name:"get_world_state",label:"World State",description:"Real-time world model for agents. ~800 tokens of structured state: prediction market index, traditional markets, topic summaries, divergences. Use ?focus=energy,geo for deeper coverage on specific topics.",parameters:U.Object({focus:U.Optional(U.String({description:'Comma-separated topics to focus on (e.g. "energy,geopolitics")'}))}),execute:async(e,t)=>{const n=t.focus?`?focus=${encodeURIComponent(t.focus)}`:"",o=await fetch(`${i}/api/agent/world${n}`);if(!o.ok)return{content:[{type:"text",text:`World API error: ${o.status}`}],details:{}};return{content:[{type:"text",text:await o.text()}],details:{}}}},{name:"get_world_delta",label:"World Delta",description:"Incremental world state update — only what changed since a given time. ~30-50 tokens. Much cheaper than full state for polling.",parameters:U.Object({since:U.Optional(U.String({description:'Time window: "30m", "1h", "6h", "24h" or ISO timestamp (default "1h")'}))}),execute:async(e,t)=>{const n=t.since||"1h",o=await fetch(`${i}/api/agent/world/delta?since=${encodeURIComponent(n)}`);if(!o.ok)return{content:[{type:"text",text:`Delta API error: ${o.status}`}],details:{}};return{content:[{type:"text",text:await o.text()}],details:{}}}},{name:"monitor_the_situation",label:"Monitor",description:"Universal web intelligence. Scrape any URL (Firecrawl), analyze with any LLM, cross-reference with 9,706 prediction markets, push to webhook.",parameters:U.Object({source:U.Object({action:U.String({description:"Firecrawl action: scrape, crawl, search, map, extract, batch_scrape"}),url:U.Optional(U.String({description:"Target URL (for scrape/crawl/extract)"})),query:U.Optional(U.String({description:"Search query (for search action)"}))}),analysis:U.Optional(U.Object({model:U.Optional(U.String({description:"OpenRouter model (e.g. google/gemini-flash-1.5)"})),prompt:U.Optional(U.String({description:"Analysis prompt"}))})),enrich:U.Optional(U.Object({topics:U.Optional(U.Array(U.String(),{description:"Topics for market cross-reference"})),includeIndex:U.Optional(U.Boolean({description:"Include SF prediction market index"}))})),webhook:U.Optional(U.Object({url:U.String({description:"Webhook URL"}),format:U.Optional(U.String({description:"full, brief, or tweetable"}))}))}),execute:async(e,t)=>{const n=await fetch(`${i}/api/monitor-the-situation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)return{content:[{type:"text",text:`Monitor API error: ${n.status}`}],details:{}};const o=await n.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"enrich_content",label:"Enrich",description:"Cross-reference any text with 9,706 prediction markets. Returns divergences between your content and market prices. No auth required.",parameters:U.Object({content:U.String({description:"Text to cross-reference with markets"}),topics:U.Optional(U.Array(U.String(),{description:"Topic hints for better matching"}))}),execute:async(e,t)=>{const n=await fetch(`${i}/api/monitor-the-situation/enrich`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)return{content:[{type:"text",text:`Enrich API error: ${n.status}`}],details:{}};const o=await n.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}}),xe.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime daemon is running and show active intents.",parameters:U.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),i=o(s(),".sf","runtime.pid");let r=!1,a="";if(e(i)){a=t(i,"utf-8").trim();try{process.kill(parseInt(a),0),r=!0}catch{r=!1}}const c=await y.listIntents({active:!0});return{content:[{type:"text",text:JSON.stringify({running:r,pid:r?a:null,...c},null,2)}],details:{}}}},{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon. Polls for active intents, evaluates trigger conditions, and executes orders via local API keys.",parameters:U.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:s}=await Promise.resolve().then(n.t.bind(n,70857,23)),{spawn:i}=await Promise.resolve().then(n.t.bind(n,35317,23)),r=o(s(),".sf","runtime.pid");if(e(r)){const e=t(r,"utf-8").trim();try{return process.kill(parseInt(e),0),{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{}}if(i(process.execPath,[process.argv[1],"runtime","start"],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env}}).unref(),await new Promise(e=>setTimeout(e,1e3)),e(r)){return{content:[{type:"text",text:`Runtime started (PID ${t(r,"utf-8").trim()}). Polling every 30s for active intents.`}],details:{}}}return{content:[{type:"text",text:"Runtime starting... check status in a moment with runtime_status."}],details:{}}}},{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:U.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:o}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=s(i(),".sf","runtime.pid");if(!e(r))return{content:[{type:"text",text:"No runtime running."}],details:{}};const a=t(r,"utf-8").trim();try{return process.kill(parseInt(a),"SIGTERM"),o(r),{content:[{type:"text",text:`Runtime stopped (PID ${a}).`}],details:{}}}catch{try{o(r)}catch{}return{content:[{type:"text",text:"Runtime was not running (stale PID file removed)."}],details:{}}}}});const Ie=x?function(e){const t=(0,u.loadConfig)(),n=e.theses?.length||0,o=(e.edges,(e.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5).map(e=>` ${(e.title||"").slice(0,40)} | ${e.venue||"kalshi"} | mkt ${e.price}¢ | edge +${e.edge}`).join("\n")||" (no edges)");return`You are a prediction market research assistant with access to live data across Kalshi, Polymarket, X/Twitter, and traditional markets.\n\nYou are in EXPLORER MODE — not bound to any specific thesis. Help the user research, compare, and understand prediction market data across all sources.\n\n## What you can do\n- Get real-time world state: prediction index, markets, topics, divergences (get_world_state, get_world_delta)\n- Search and compare markets across Kalshi and Polymarket (scan_markets)\n- Answer questions with live market data + LLM synthesis (query)\n- Check traditional market prices — SPY, VIX, gold, oil, bonds (get_markets)\n- S&T-style trade ideas with conviction and catalysts (get_trade_ideas)\n- Browse public theses and their edges (explore_public)\n- Search X/Twitter for sentiment and breaking news (search_x, x_volume, x_news)\n- Scrape any URL, analyze, cross-reference with 9,706 markets (monitor_the_situation, enrich_content)\n- Check orderbook depth and liquidity (inspect_book, get_liquidity)\n- View user positions across venues (get_positions)\n- Create and manage execution intents with triggers (create_intent, list_intents, cancel_intent)\n- Start/stop/check local execution runtime (runtime_start, runtime_stop, runtime_status)\n- Create a new thesis when the user forms a view (create_thesis)\n\n## CRITICAL: Thesis creation transition\nWhen the user expresses a market view worth tracking — explicitly ("create a thesis") or implicitly ("I think oil stays above $100", "the war won't end soon") — use create_thesis to create it. After creation, tell the user: "Thesis created. The heartbeat engine is now monitoring this 24/7. Use /switch <id> to focus on it."\n\n## Your analytical framework\nEdge = thesis price - market price. Positive = market underprices.\nEdge types: "consensus_gap" (real disagreement), "attention_gap" (no real pricing), "timing_gap" (market lags), "risk_premium" (settlement risk).\nPrice reliability: depth >= 500 = consensus. depth < 100 = unreliable. spread > 5¢ = noisy.\nAlways state contract expiry and next catalyst. No catalyst = capital lock risk.\n\n## Your behavioral rules\n- Be concise. Use tools for fresh data. Don't guess prices.\n- You do NOT know the user's positions at start. Call get_positions before discussing trades.\n- If user mentions news, offer to create a thesis or inject a signal if one exists.\n- Don't end with "anything else?"\n- Use Chinese if user writes Chinese, English if English.\n- Prices in cents (¢). P&L in dollars ($).\n\n## Trading status\n${t.tradingEnabled?"Trading is ENABLED.":"Trading is DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current market snapshot\nPublic theses tracked: ${n}\nTop edges across all public theses:\n${o}\n`}($):Oe($),Pe=new z({initialState:{systemPrompt:Ie,model:G,tools:xe,thinkingLevel:"off"},streamFn:q,getApiKey:e=>{if("openrouter"===e)return h}});let Te=!1;if(!t?.newSession){const e=g(S||"_explorer");if(e?.messages?.length>0)try{const t=e.messages.filter(e=>!!e.role&&((!Array.isArray(e.content)||0!==e.content.length)&&!("assistant"===e.role&&!e.content&&!e.tool_calls?.length))),n=[];for(const e of t){const t=n.length>0?n[n.length-1].role:null;e.role===t&&"tool"!==e.role||n.push(e)}n.length>0&&"user"===n[n.length-1].role&&n.pop(),Pe.replaceMessages(n),Pe.setSystemPrompt(Ie),Te=!0}catch{}}function Ee(){try{const e=Pe.state.messages;e.length>0&&f(S||"_explorer",W,e)}catch{}}let Ae=null,Me="",Re=null;const Ne=new Map,Le=new Map;let De=null;function Ke(){De&&(clearTimeout(De),De=null),se.requestRender()}async function je(e){const t=e.trim().split(/\s+/),o=t[0].toLowerCase();switch(o){case"/help":return $e(),ye(_.zinc200(w("Commands"))+"\n"+_.emerald("/help ")+_.zinc400("Show this help")+"\n"+_.emerald("/tree ")+_.zinc400("Display causal tree")+"\n"+_.emerald("/edges ")+_.zinc400("Display edge/spread table")+"\n"+_.emerald("/pos ")+_.zinc400("Display Kalshi positions")+"\n"+_.emerald("/eval ")+_.zinc400("Trigger deep evaluation")+"\n"+_.emerald("/switch <id>")+_.zinc400(" Switch thesis")+"\n"+_.emerald("/compact ")+_.zinc400("Compress conversation history")+"\n"+_.emerald("/new ")+_.zinc400("Start fresh session")+"\n"+_.emerald("/model <m> ")+_.zinc400("Switch model")+"\n"+_.emerald("/env ")+_.zinc400("Show environment variable status")+"\n"+(Ce.tradingEnabled?_.zinc600("─".repeat(30))+"\n"+_.emerald("/buy ")+_.zinc400("TICKER QTY PRICE — quick buy")+"\n"+_.emerald("/sell ")+_.zinc400("TICKER QTY PRICE — quick sell")+"\n"+_.emerald("/cancel ")+_.zinc400("ORDER_ID — cancel order")+"\n"+_.zinc600("─".repeat(30))+"\n":"")+(ge.length>0?_.zinc600("─".repeat(30))+"\n"+_.zinc200(w("Skills"))+"\n"+ge.map(e=>_.emerald(`/${e.name.padEnd(10)}`)+_.zinc400(e.description.slice(0,45))).join("\n")+"\n"+_.zinc600("─".repeat(30))+"\n":"")+_.emerald("/clear ")+_.zinc400("Clear screen (keeps history)")+"\n"+_.emerald("/exit ")+_.zinc400("Exit (auto-saves)")),$e(),!0;case"/tree":if($e(),x)ye(_.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one."));else try{$=await y.getContext(S),ye(_.zinc200(w("Causal Tree"))+"\n"+function(e){const t=e.causalTree;if(!t?.nodes?.length)return _.zinc600(" No causal tree data");const n=[];for(const e of t.nodes){const t=e.id||"",o=e.label||e.description||"",s="number"==typeof e.probability?Math.round(100*e.probability):"number"==typeof e.impliedProbability?Math.round(100*e.impliedProbability):null,i=(t.match(/\./g)||[]).length,r=" ".repeat(i+1);if(null!==s){const e=Math.round(s/10),i="█".repeat(e)+"░".repeat(10-e),a=s>=70?_.emerald:s>=40?_.amber:_.red,c=`${r}${_.zinc600(t)} ${_.zinc400(o)} `,l=` ${a(`${s}%`)} ${a(i)}`;n.push(c+l)}else n.push(`${r}${_.zinc600(t)} ${_.zinc400(o)}`)}return n.join("\n")}($))}catch(e){ye(_.red(`Error: ${e.message}`))}return $e(),!0;case"/edges":if($e(),x)try{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218)),t=((await e()).edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,10);if(0===t.length)ye(_.zinc400("No public edges available."));else{const e=t.map(e=>{const t=(e.title||"").slice(0,35).padEnd(35),n=(e.venue||"kalshi").padEnd(5),o=String(Math.round(e.price||0)).padStart(3)+"¢",s="+"+Math.round(e.edge||0);return` ${_.zinc400(t)} ${_.zinc600(n)} ${_.zinc400(o)} ${_.emerald(s.padStart(4))}`}).join("\n");ye(_.zinc200(w("Public Edges"))+"\n"+e)}}catch(e){ye(_.red(`Error: ${e.message}`))}else try{$=await y.getContext(S),Q&&($._positions=Q),ye(_.zinc200(w("Edges"))+"\n"+function(e){const t=e.edges;if(!t?.length)return _.zinc600(" No edge data");const n=e._positions||[],o=[];for(const e of t){const t=(e.market||e.marketId||"").slice(0,18).padEnd(18),s="number"==typeof e.marketPrice?`${e.marketPrice}¢`:"?",i="number"==typeof e.thesisPrice?`${e.thesisPrice}¢`:"?",r="number"==typeof e.edge?e.edge>0?`+${e.edge}`:`${e.edge}`:"?",a=e.orderbook||{},c="number"==typeof a.spread?`${a.spread}¢`:"?",l=a.liquidityScore||"low",d="high"===l?"■■■":"medium"===l?"■■ ":"■ ",u="high"===l?_.emerald:"medium"===l?_.amber:_.red,p=n.find(t=>t.ticker===e.marketId||e.marketId&&t.ticker?.includes(e.marketId));let h=_.zinc600("—");if(p){const e=p.side?.toUpperCase()||"YES",t="number"==typeof p.unrealized_pnl?p.unrealized_pnl>=0?_.emerald(`+$${(p.unrealized_pnl/100).toFixed(0)}`):_.red(`-$${(Math.abs(p.unrealized_pnl)/100).toFixed(0)}`):"";h=_.emerald(`${e} (${p.quantity}@${p.average_price_paid}¢ ${t})`)}o.push(` ${_.zinc200(t)} ${_.zinc400(s)} → ${_.zinc400(i)} edge ${r.includes("+")?_.emerald(r):_.red(r)} spread ${_.zinc600(c)} ${u(d)} ${u(l.padEnd(4))} ${h}`)}return o.join("\n")}($))}catch(e){ye(_.red(`Error: ${e.message}`))}return $e(),!0;case"/pos":$e();try{const e=await(0,c.getPositions)();if(!e)return ye(_.zinc600("Kalshi not configured")),!0;for(const t of e){const e=await(0,c.getMarketPrice)(t.ticker);null!==e&&(t.current_value=e,t.unrealized_pnl=Math.round((e-t.average_price_paid)*t.quantity))}Q=e,ye(_.zinc200(w("Positions"))+"\n"+function(e){if(!e?.length)return _.zinc600(" No positions");const t=[];let n=0;for(const o of e){const e=(o.ticker||"").slice(0,18).padEnd(18),s=(o.side||"yes").toUpperCase().padEnd(3),i=String(o.quantity||0),r=`${o.average_price_paid||0}¢`,a="number"==typeof o.current_value&&o.current_value>0?`${o.current_value}¢`:"?¢",c=o.unrealized_pnl||0;n+=c;const l=(c/100).toFixed(2),d=c>=0?_.emerald(`+$${l}`):_.red(`-$${Math.abs(parseFloat(l)).toFixed(2)}`),u=c>=0?_.emerald("▲"):_.red("▼");t.push(` ${_.zinc200(e)} ${_.zinc400(s)} ${_.zinc400(i)} @ ${_.zinc400(r)} now ${_.zinc200(a)} ${d} ${u}`)}const o=(n/100).toFixed(2);return t.push(_.zinc600(" "+"─".repeat(40))),t.push(n>=0?` Total P&L: ${_.emerald(w(`+$${o}`))}`:` Total P&L: ${_.red(w(`-$${Math.abs(parseFloat(o)).toFixed(2)}`))}`),t.join("\n")}(e))}catch(e){ye(_.red(`Error: ${e.message}`))}return $e(),!0;case"/eval":if($e(),x)return ye(_.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one.")),$e(),!0;ye(_.zinc600("Triggering evaluation...")),se.requestRender();try{const e=await y.evaluate(S);ye(_.emerald("Evaluation complete")+"\n"+_.zinc400(JSON.stringify(e,null,2)))}catch(e){ye(_.red(`Error: ${e.message}`))}return $e(),!0;case"/model":{const e=t.slice(1).join(" ").trim();return e?($e(),W=e.replace(/^openrouter\//,""),G=X(W),Pe.setModel(G),ce.modelName=W,ce.update(),ye(_.emerald(`Model switched to ${W}`)),$e(),se.requestRender(),!0):(ye(_.zinc400(`Current model: ${W}`)),!0)}case"/switch":{const n=t[1]?.trim();if(!n)return ye(_.zinc400("Usage: /switch <thesisId>")),!0;$e();try{Ee();const e=await y.getContext(n);S=e.thesisId||n,$=e;const t=Oe(e);"number"==typeof e.confidence&&Math.round(100*e.confidence);Pe.clearMessages();const o=g(S);o?.messages?.length>0?(Pe.replaceMessages(o.messages),Pe.setSystemPrompt(t),ye(_.emerald(`Switched to ${S.slice(0,8)}`)+_.zinc400(` (resumed ${o.messages.length} messages)`))):(Pe.setSystemPrompt(t),ye(_.emerald(`Switched to ${S.slice(0,8)}`)+_.zinc400(" (new session)"))),ce.setFromContext(e,le||void 0),pe.clear(),ye(qe(e,le))}catch(e){ye(_.red(`Switch failed: ${e.message}`))}return $e(),se.setFocus(he),se.requestRender(),!0}case"/compact":$e();try{const t=Pe.state.messages;if(t.length<=10)return ye(_.zinc400("Conversation too short to compact")),$e(),se.setFocus(he),!0;const n=3;let o=0,s=t.length;for(let e=t.length-1;e>=0;e--)if("user"===t[e].role&&(o++,o>=n)){s=e;break}if(s<=2)return ye(_.zinc400("Not enough complete turns to compact")),$e(),se.setFocus(he),!0;const a=t.slice(0,s),c=t.slice(s),l=new N(se,e=>_.emerald(e),e=>_.zinc600(e),"compacting with LLM...");l.start(),pe.addChild(l),se.requestRender();const d=[];let u=0;const p=12e3;for(const e of a){if(u>=p)break;let t="";if("string"==typeof e.content?t=e.content:Array.isArray(e.content)&&(t=e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")),!t)continue;const n=(e.role||"unknown").toUpperCase(),o=`[${n}]: ${t.slice(0,800)}`;d.push(o),u+=o.length}const m=d.join("\n\n"),g="google/gemini-2.0-flash-001",f="You are a conversation compressor. Given a conversation between a user and a prediction-market trading assistant, produce a dense summary that preserves:\n1. All factual conclusions, numbers, prices, and probabilities mentioned\n2. Key trading decisions, positions taken or discussed\n3. Signals injected, evaluations triggered, and their outcomes\n4. Any action items or pending questions\n\nOutput a structured summary. Be concise but preserve every important detail — this summary replaces the original messages for continued conversation. Do NOT add commentary or meta-text. Just the summary.";let y;try{const e=r?`${i}/api/proxy/llm`:"https://openrouter.ai/api/v1/chat/completions",t={model:g,messages:[{role:"system",content:f},{role:"user",content:`Summarize this conversation (${a.length} messages):\n\n${m}`}],max_tokens:2e3,temperature:.2},n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`,"HTTP-Referer":"https://simplefunctions.com","X-Title":"SF Agent Compact"},body:JSON.stringify(t)});if(!n.ok){const e=await n.text().catch(()=>"");throw new Error(`OpenRouter ${n.status}: ${e.slice(0,200)}`)}const o=await n.json();if(y=o.choices?.[0]?.message?.content||"",!y)throw new Error("Empty summary from LLM")}catch(e){const t=[];for(const e of a){const n="string"==typeof e.content?e.content:"";"user"===e.role&&n?t.push(`- User: ${n.slice(0,100)}`):"assistant"===e.role&&n&&t.push(`- Assistant: ${n.slice(0,150)}`)}y=`[LLM summary failed: ${e.message}. Fallback bullet points:]\n\n${t.slice(-20).join("\n")}`}l.stop(),pe.removeChild(l);const $=[{role:"user",content:`[Conversation summary — ${a.length} messages compressed]\n\n${y}`},{role:"assistant",content:"Understood. I have the full conversation context from the summary above. Continuing from where we left off."},...c];Pe.clearMessages(),Pe.replaceMessages($),Pe.setSystemPrompt(Ie),Ee(),ye(_.emerald(`Compacted: ${a.length} messages → summary + ${c.length} recent`)+_.zinc600(` (via ${g.split("/").pop()})`)),$e(),se.setFocus(he),se.requestRender()}catch(e){ye(_.red(`Compact failed: ${e.message||e}`)),$e(),se.setFocus(he),se.requestRender()}return!0;case"/new":return $e(),Ee(),Pe.clearMessages(),Pe.setSystemPrompt(Ie),pe.clear(),ye(_.emerald("Session cleared")+_.zinc400(" — fresh start")),$e(),se.requestRender(),!0;case"/env":{$e();const e=[{name:"SF_API_KEY",key:"SF_API_KEY",required:!0,mask:!0},{name:"SF_API_URL",key:"SF_API_URL",required:!1,mask:!1},{name:"OPENROUTER_KEY",key:"OPENROUTER_API_KEY",required:!0,mask:!0},{name:"KALSHI_KEY_ID",key:"KALSHI_API_KEY_ID",required:!1,mask:!0},{name:"KALSHI_PEM_PATH",key:"KALSHI_PRIVATE_KEY_PATH",required:!1,mask:!1},{name:"TAVILY_API_KEY",key:"TAVILY_API_KEY",required:!1,mask:!0}].map(e=>{const t=process.env[e.key];if(t){const n=e.mask?t.slice(0,Math.min(8,t.length))+"..."+t.slice(-4):t;return` ${e.name.padEnd(18)} ${_.emerald("✓")} ${_.zinc400(n)}`}{const t=e.required?"必须":"可选";return` ${e.name.padEnd(18)} ${_.red("✗")} ${_.zinc600(`未配置(${t})`)}`}});return ye(_.zinc200(w("Environment"))+"\n"+e.join("\n")),$e(),!0}case"/clear":{const e=[...pe.children||[]];for(const t of e)try{pe.removeChild(t)}catch{}return $e(),V=!1,ne=null,se.setFocus(he),se.requestRender(),!0}case"/buy":{const[,o,s,i]=t;if(!o||!s||!i)return ye(_.zinc400("Usage: /buy TICKER QTY PRICE_CENTS (e.g. /buy KXWTIMAX-26DEC31-T135 100 50)")),!0;if(!Ce.tradingEnabled)return ye(_.red("Trading disabled. Run: sf setup --enable-trading")),!0;$e();if((await we(`BUY ${s}x ${o} YES @ ${i}¢ — execute? (y/n)`)).toLowerCase().startsWith("y"))try{const{createOrder:e}=await Promise.resolve().then(n.t.bind(n,96139,23)),t=await e({ticker:o,side:"yes",action:"buy",type:"limit",count:parseInt(s),yes_price:parseInt(i)});ye(_.emerald("✓ Order placed: "+((t.order||t).order_id||"OK")))}catch(e){ye(_.red("✗ "+e.message))}else ye(_.zinc400("Cancelled."));return $e(),!0}case"/sell":{const[,o,s,i]=t;if(!o||!s||!i)return ye(_.zinc400("Usage: /sell TICKER QTY PRICE_CENTS")),!0;if(!Ce.tradingEnabled)return ye(_.red("Trading disabled. Run: sf setup --enable-trading")),!0;$e();if((await we(`SELL ${s}x ${o} YES @ ${i}¢ — execute? (y/n)`)).toLowerCase().startsWith("y"))try{const{createOrder:e}=await Promise.resolve().then(n.t.bind(n,96139,23)),t=await e({ticker:o,side:"yes",action:"sell",type:"limit",count:parseInt(s),yes_price:parseInt(i)});ye(_.emerald("✓ Order placed: "+((t.order||t).order_id||"OK")))}catch(e){ye(_.red("✗ "+e.message))}else ye(_.zinc400("Cancelled."));return $e(),!0}case"/cancel":{const[,o]=t;if(!o)return ye(_.zinc400("Usage: /cancel ORDER_ID")),!0;if(!Ce.tradingEnabled)return ye(_.red("Trading disabled. Run: sf setup --enable-trading")),!0;$e();try{const{cancelOrder:e}=await Promise.resolve().then(n.t.bind(n,96139,23));await e(o),ye(_.emerald(`✓ Order ${o} cancelled.`))}catch(e){ye(_.red("✗ "+e.message))}return $e(),!0}case"/exit":case"/quit":return Fe(),!0;default:{const t=ge.find(e=>e.trigger===o);if(t){$e(),ye(_.zinc200(`Running skill: ${w(t.name)}`)+_.zinc600(` — ${t.description.slice(0,60)}`)),$e(),se.requestRender(),V=!0;try{await Pe.prompt(t.prompt)}catch(e){ye(_.red(`Skill error: ${e.message}`))}finally{V=!1}return!0}return!1}}}function Fe(){te&&clearInterval(te),Re&&Re.stop(),Ee(),se.stop(),process.exit(0)}function qe(e,t){const n=[];if(e._explorerMode){const t=e.edges?.length||0,o=e.theses?.length||0;n.push(_.zinc600("─".repeat(55))),n.push(" "+_.emerald(w("Explorer mode"))+_.zinc600(" — full market access, no thesis")),n.push(" "+_.zinc600(`${o} public theses │ ${t} edges tracked`)),n.push(_.zinc600("─".repeat(55)));const s=e.edges||[];if(s.length>0){const e=[...s].sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5);n.push(" "+_.zinc400(w("TOP PUBLIC EDGES"))+_.zinc600(" mkt edge"));for(const t of e){const e=(t.title||"").slice(0,30).padEnd(30),o=String(Math.round(t.price||0)).padStart(3)+"¢",s=t.edge||0,i="+"+Math.round(s),r=Math.abs(s)>=15?_.emerald:Math.abs(s)>=8?_.amber:_.zinc400;n.push(` ${_.zinc400(e)} ${_.zinc400(o)} ${r(i.padStart(4))}`)}}return n.push(_.zinc600("─".repeat(55))),n.push(" "+_.zinc600("Ask anything, or describe a view to create a thesis.")),n.push(_.zinc600("─".repeat(55))),n.join("\n")}const o=e.thesis||e.rawThesis||"N/A",s=o.length>100?o.slice(0,100)+"...":o,i="number"==typeof e.confidence?Math.round(100*e.confidence):"string"==typeof e.confidence?Math.round(100*parseFloat(e.confidence)):0,r=e.lastEvaluation?.confidenceDelta?Math.round(100*e.lastEvaluation.confidenceDelta):0,a=0!==r?` (${r>0?"+":""}${r})`:"",c=e.lastEvaluation?.evaluatedAt?Math.round((Date.now()-new Date(e.lastEvaluation.evaluatedAt).getTime())/36e5):null;if(n.push(_.zinc600("─".repeat(55))),n.push(" "+_.zinc200(w(s))),n.push(" "+_.zinc600(`${e.status||"active"} ${i}%${a}`)+(null!==c?_.zinc600(` │ last eval: ${c<1?"<1":c}h ago`):"")),n.push(_.zinc600("─".repeat(55))),t&&t.length>0){n.push(" "+_.zinc400(w("POSITIONS")));let e=0;for(const o of t){const t=o.unrealized_pnl||0;e+=t;const s=t>=0?_.emerald(`+$${(t/100).toFixed(2)}`):_.red(`-$${(Math.abs(t)/100).toFixed(2)}`),i=(o.ticker||"").slice(0,28).padEnd(28),r=String(o.quantity||0).padStart(5),a="yes"===o.side?_.emerald("Y"):_.red("N");n.push(` ${_.zinc400(i)} ${r} ${a} ${s}`)}const o=e>=0?_.emerald(w(`+$${(e/100).toFixed(2)}`)):_.red(w(`-$${(Math.abs(e)/100).toFixed(2)}`));n.push(` ${"".padEnd(28)} ${_.zinc600("Total")} ${o}`)}const l=e.edges||[];if(l.length>0){const e=[...l].sort((e,t)=>Math.abs(t.edge||t.edgeSize||0)-Math.abs(e.edge||e.edgeSize||0)).slice(0,5);n.push(_.zinc600("─".repeat(55))),n.push(" "+_.zinc400(w("TOP EDGES"))+_.zinc600(" mkt edge liq"));for(const t of e){const e=(t.market||t.marketTitle||t.marketId||"").slice(0,30).padEnd(30),o=String(Math.round(t.marketPrice||0)).padStart(3)+"¢",s=t.edge||t.edgeSize||0,i=(s>0?"+":"")+Math.round(s),r=t.orderbook?.liquidityScore||("polymarket"===t.venue?"-":"?"),a=Math.abs(s)>=15?_.emerald:Math.abs(s)>=8?_.amber:_.zinc400;n.push(` ${_.zinc400(e)} ${_.zinc400(o)} ${a(i.padStart(4))} ${_.zinc600(r)}`)}}return n.push(_.zinc600("─".repeat(55))),n.join("\n")}Pe.subscribe(e=>{if("message_start"===e.type&&(Me="",Ae=null,Re=new N(se,e=>_.emerald(e),e=>_.zinc600(e),"thinking..."),Re.start(),pe.addChild(Re),se.requestRender()),"message_update"===e.type){const t=e.assistantMessageEvent;"text_delta"===t.type&&(Re&&(Re.stop(),pe.removeChild(Re),Re=null,Ae=new M("",1,0,ie,re),pe.addChild(Ae)),Me+=t.delta,Ae&&Ae.setText(Me),De||(De=setTimeout(()=>{De=null,se.requestRender()},66)))}if("message_end"===e.type&&(Re&&(Re.stop(),pe.removeChild(Re),Re=null),Ae&&Me&&Ae.setText(Me),$e(),Ae=null,Me="",Ke()),"agent_end"===e.type&&(V=!1,Ee(),Ke(),ee)){const e=ee;ee=null,He(e)}if("tool_execution_start"===e.type){const t=new H(_.zinc600(` ▸ ${e.toolName}...`));Ne.set(e.toolCallId||e.toolName,Date.now()),Le.set(e.toolCallId||e.toolName,t),pe.addChild(t),Y++,ce.toolCount=Y,ce.update(),se.requestRender()}if("tool_execution_end"===e.type){const t=e.toolCallId||e.toolName,n=Ne.get(t),o=n?((Date.now()-n)/1e3).toFixed(1):"?",s=Le.get(t);s&&(e.isError?s.setText(_.red(` ✗ ${e.toolName} (${o}s) error`)):s.setText(_.zinc600(` ▸ ${e.toolName} `)+_.emerald("✓")+_.zinc600(` ${o}s`))),Ne.delete(t),Le.delete(t),se.requestRender()}}),he.onSubmit=async e=>{const t=e.trim();if(!t)return;if(ne){const{resolve:e}=ne;ne=null;const n=new A(_.zinc400(" > ")+_.zinc200(t),1,0);return pe.addChild(n),$e(),se.requestRender(),void e(t)}if(V)return;if(he.addToHistory(t),t.startsWith("/")){if(await je(t))return}V=!0;const n=new A(_.emerald(w(">"))+" "+_.white(t),1,0);pe.addChild(n),$e(),se.requestRender();try{await Pe.prompt(t)}catch(e){Re&&(Re.stop(),pe.removeChild(Re),Re=null),ye(_.red(`Error: ${e.message}`)),$e(),V=!1}},se.addInputListener(e=>{if(""===e)return Fe(),{consume:!0}}),process.on("SIGINT",Fe),process.on("SIGTERM",Fe);const Ue=Te?_.zinc600(`resumed (${Pe.state.messages.length} messages)`):_.zinc600("new session");ye(qe($,le)),ye(" "+Ue),$e();const ze=.03;function He(e){const t=Math.abs(e.confidenceDelta||0),n=Math.round(100*(e.confidence||0)),o=Math.round(100*(e.confidenceDelta||0)),s=o>0?"+":"";if(t>=ze){const t=o>0?"▲":"▼";ye((o>0?_.emerald:_.red)(` ${t} Heartbeat: confidence ${s}${o}% → ${n}%`)),e.latestSummary&&ye(_.zinc400(` ${e.latestSummary.slice(0,100)}`)),$e(),ce.setFromContext({...$,confidence:e.confidence,lastEvaluation:{confidenceDelta:e.confidenceDelta}},le||void 0),se.requestRender(),V=!0;const i=`[HEARTBEAT ALERT] Confidence just changed ${s}${o}% to ${n}%. ${e.evaluationCount} evaluation(s) since last check. Latest: "${(e.latestSummary||"").slice(0,150)}". Briefly analyze what happened and whether any action is needed. Be concise.`;Pe.prompt(i).catch(e=>{ye(_.red(`Error: ${e.message}`)),V=!1})}else t>0&&(ye(_.zinc600(` ─ heartbeat: ${n}% (${s}${o}%) — ${e.evaluationCount||0} eval(s)`)),se.requestRender())}x||(te=setInterval(async()=>{try{const e=await y.getChanges(S,Z);if(Z=(new Date).toISOString(),!e.changed)return;V||ne?ee=e:He(e)}catch{}},6e4));se.start()};const s=o(n(79896)),i=o(n(16928)),r=o(n(70857)),a=n(19218),c=n(96139),l=n(34331),d=n(97325),u=n(11627),p=n(40101);function h(){return i.default.join(r.default.homedir(),".sf","sessions")}function m(e){return i.default.join(h(),`${e}.json`)}function g(e){const t=m(e);try{if(s.default.existsSync(t))return JSON.parse(s.default.readFileSync(t,"utf-8"))}catch{}return null}function f(e,t,n){const o=h();s.default.mkdirSync(o,{recursive:!0}),s.default.writeFileSync(m(e),JSON.stringify({thesisId:e,model:t,updatedAt:(new Date).toISOString(),messages:n},null,2))}const y=(e,t,n)=>o=>`[38;2;${e};${t};${n}m${o}`,$=(e,t,n)=>o=>`[48;2;${e};${t};${n}m${o}`,w=e=>`${e}`,k=e=>`${e}`,b=e=>`${e}`,v=e=>`${e}`,_={emerald:y(16,185,129),zinc200:y(228,228,231),zinc400:y(161,161,170),zinc600:y(82,82,91),zinc800:y(39,39,42),red:y(239,68,68),amber:y(245,158,11),white:y(255,255,255),bgZinc900:$(24,24,27),bgZinc800:$(39,39,42)}},72768:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.announcementsCommand=async function(e){const t=await(0,o.getExchangeAnnouncements)();if(e.json)return void console.log(JSON.stringify(t,null,2));if(0===t.length)return void console.log(`${s.c.dim}No announcements.${s.c.reset}`);console.log(`${s.c.bold}${s.c.cyan}Exchange Announcements${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(70)}${s.c.reset}`);for(const e of t.slice(0,20)){const t=e.created_time?new Date(e.created_time).toLocaleDateString():"",n=e.type?`[${e.type}]`:"";if(console.log(` ${s.c.dim}${t}${s.c.reset} ${n} ${e.title||e.message||""}`),e.body){const t=String(e.body).slice(0,120);console.log(` ${s.c.dim}${t}${s.c.reset}`)}}console.log(`\n${s.c.dim}${t.length} announcement(s)${s.c.reset}`)};const o=n(96139),s=n(99236)},71783:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.augmentCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl);console.log(`${t.dryRun?"Previewing":"Running"} tree augmentation for ${e.slice(0,8)}...`);const s=await n.augmentTree(e,t.dryRun);if(t.json)return void console.log(JSON.stringify(s,null,2));console.log(),s.warning&&(console.log(` ⚠ ${s.warning}`),console.log());if(s.suggestedNodes?.length>0){console.log(` Suggested Nodes (${s.suggestedNodes.length} from evaluations)`);for(const e of s.suggestedNodes)console.log(` • ${e.label} (parent: ${e.parentNodeId}, est: ${Math.round(100*e.estimatedProbability)}%, seen ${e.frequency}x)`);console.log()}if(s.acceptedNodes?.length>0){console.log(` Accepted Nodes (${s.acceptedNodes.length})`);for(const e of s.acceptedNodes)console.log(` + ${e.id}: ${e.label} (prob: ${Math.round(100*e.probability)}%, imp: ${e.importance})`);if(console.log(),Object.keys(s.updatedImportanceWeights||{}).length>0){console.log(" Rebalanced Weights");for(const[e,t]of Object.entries(s.updatedImportanceWeights))console.log(` ${e} → ${t}`);console.log()}s.applied?console.log(" ✓ Applied to causal tree"):t.dryRun&&console.log(" Dry run — use without --dry-run to apply")}else console.log(" No nodes accepted.");console.log()};const o=n(19218)},44040:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.balanceCommand=async function(e){const t=await(0,o.getBalance)();if(!t)throw new Error("Kalshi not configured. Run: sf setup --kalshi");if(e.json)return void console.log(JSON.stringify(t,null,2));console.log(`${s.c.bold}${s.c.cyan}Kalshi Account${s.c.reset}`),console.log(` Balance: $${t.balance.toFixed(2)}`),console.log(` Portfolio Value: $${t.portfolioValue.toFixed(2)}`)};const o=n(96139),s=n(99236)},69903:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bookCommand=async function(e,t){const n=[];if(t.poly){console.log(`${r.c.dim}Searching Polymarket for "${t.poly}"...${r.c.reset}`);const e=await(0,i.polymarketSearch)(t.poly,10);for(const o of e)for(const e of(o.markets||[]).slice(0,5)){if(!e.active||e.closed||!e.clobTokenIds)continue;const s=(0,i.parseClobTokenIds)(e.clobTokenIds);if(!s)continue;const r=await(0,i.polymarketGetOrderbookWithDepth)(s[0]);if(!r)continue;const c=(0,i.parseOutcomePrices)(e.outcomePrices),l={venue:"polymarket",ticker:e.conditionId?.slice(0,16)||e.id,title:e.groupItemTitle?`${o.title}: ${e.groupItemTitle}`:e.question||o.title,bestBid:r.bestBid,bestAsk:r.bestAsk,spread:r.spread,bidDepth:r.totalBidDepth,askDepth:r.totalAskDepth,liquidityScore:r.liquidityScore,volume24h:e.volume24hr||0,openInterest:e.liquidityNum||0,lastPrice:c[0]?(0,i.toCents)(c[0]):0,expiry:e.endDateIso||null,bidLevels:r.levels.bids.slice(0,5).map(e=>({price:Math.round(100*parseFloat(e.price)),size:Math.round(parseFloat(e.size))})),askLevels:r.levels.asks.slice(0,5).map(e=>({price:Math.round(100*parseFloat(e.price)),size:Math.round(parseFloat(e.size))}))};if(t.history)try{const e=await(0,i.polymarketGetPriceHistory)({tokenId:s[0],interval:"1w",fidelity:360});e.length>0&&(l.sparkline=a(e.map(e=>100*e.p)))}catch{}n.push(l)}}for(const i of e){console.log(`${r.c.dim}Fetching ${i}...${r.c.reset}`);try{const e=await(0,o.kalshiFetchMarket)(i),c=await(0,s.getPublicOrderbook)(i),l=(c?.yes_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),d=(c?.no_dollars||[]).map(([e,t])=>({price:Math.round(100*parseFloat(e)),size:Math.round(parseFloat(t))})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),u=l[0]?.price||0,p=d.length>0?100-d[0].price:100,h=p-u,m=l.reduce((e,t)=>e+t.size,0),g=d.reduce((e,t)=>e+t.size,0),f=l.slice(0,3).reduce((e,t)=>e+t.size,0)+d.slice(0,3).reduce((e,t)=>e+t.size,0),y=h<=2&&f>=500?"high":h<=5&&f>=100?"medium":"low",$=100*parseFloat(e.last_price_dollars||"0"),w={venue:"kalshi",ticker:e.ticker||i,title:e.title||e.subtitle||i,bestBid:u,bestAsk:p,spread:h,bidDepth:m,askDepth:g,liquidityScore:y,volume24h:parseFloat(e.volume_24h_fp||"0"),openInterest:parseFloat(e.open_interest_fp||"0"),lastPrice:Math.round($),expiry:e.close_time||e.expiration_time||null,bidLevels:l.slice(0,5),askLevels:d.slice(0,5).map(e=>({price:100-e.price,size:e.size}))};if(t.history){if((0,s.isKalshiConfigured)())try{const e=Math.floor(Date.now()/1e3),t=e-604800,n=await(0,s.getBatchCandlesticks)({tickers:[i],startTs:t,endTs:e,periodInterval:1440}),o=n.find(e=>e.market_ticker===i)||n[0],r=o?.candlesticks||[];if(Array.isArray(r)&&r.length>0){const e=r.map(e=>{const t=e.price?.close_dollars??e.yes_ask?.close_dollars??e.yes_bid?.close_dollars??e.close??e.price,n="string"==typeof t?100*parseFloat(t):"number"==typeof t?t:0;return Math.round(n)}).filter(e=>e>0);e.length>=2&&(w.sparkline=a(e))}}catch{}if(!w.sparkline){const t=100*parseFloat(e.previous_price_dollars||"0");if(t>0&&Math.abs(t-w.lastPrice)>0){const e=w.lastPrice-Math.round(t),n=e>=0?r.c.green:r.c.red,o=e>=0?`+${e}`:`${e}`;w.sparkline=`prev ${Math.round(t)}¢ → now ${w.lastPrice}¢ ${n}${o}${r.c.reset}`}}}n.push(w)}catch(e){console.error(`${r.c.red}Failed to fetch ${i}: ${e.message}${r.c.reset}`)}}if(0===n.length)return void console.log(`\n ${r.c.dim}No markets found. Check the ticker and try again.${r.c.reset}\n`);if(t.json)return void console.log(JSON.stringify(n,null,2));for(const e of n){const t="polymarket"===e.venue?`${r.c.blue}POLY${r.c.reset}`:`${r.c.cyan}KLSH${r.c.reset}`;console.log(),console.log(`${r.c.bold}${t} ${e.title}${r.c.reset}`),console.log(`${r.c.dim}${e.ticker}${r.c.reset}`),console.log();const n="high"===e.liquidityScore?r.c.green:"medium"===e.liquidityScore?r.c.yellow:r.c.red;if(console.log(` Last ${r.c.bold}${e.lastPrice}¢${r.c.reset} Bid ${r.c.green}${e.bestBid}¢${r.c.reset} Ask ${r.c.red}${e.bestAsk}¢${r.c.reset} Spread ${n}${e.spread}¢${r.c.reset} Liq ${n}${e.liquidityScore}${r.c.reset}`),console.log(` Vol24h ${(0,r.vol)(e.volume24h)} OI ${(0,r.vol)(e.openInterest)}`+(e.expiry?` Expires ${e.expiry.slice(0,10)}`:"")),e.sparkline&&console.log(` 7d ${e.sparkline}`),e.bidLevels&&e.askLevels){console.log(),console.log(` ${r.c.dim}${(0,r.pad)("BID",18)} ${(0,r.pad)("ASK",18)}${r.c.reset}`),console.log(` ${r.c.dim}${"─".repeat(38)}${r.c.reset}`);const t=Math.max(e.bidLevels.length,e.askLevels.length);for(let n=0;n<Math.min(t,5);n++){const t=e.bidLevels[n],o=e.askLevels[n],s=t?`${r.c.green}${(0,r.rpad)(`${t.price}¢`,5)}${r.c.reset} ${(0,r.rpad)(String(t.size),8)}`:(0,r.pad)("",18),i=o?`${r.c.red}${(0,r.rpad)(`${o.price}¢`,5)}${r.c.reset} ${(0,r.rpad)(String(o.size),8)}`:"";console.log(` ${s} ${i}`)}console.log(` ${r.c.dim}depth: ${e.bidDepth} bid / ${e.askDepth} ask${r.c.reset}`)}console.log()}};const o=n(19218),s=n(96139),i=n(34331),r=n(99236);function a(e){if(e.length<2)return"";const t=Math.min(...e),n=Math.max(...e)-t||1,o=e.map(e=>"▁▂▃▄▅▆▇█"[Math.round((e-t)/n*7)]).join(""),s=Math.round(e[0]),i=Math.round(e[e.length-1]),a=i-s;return`${o} ${s}¢→${i}¢ ${a>=0?r.c.green:r.c.red}${a>=0?`+${a}`:`${a}`}${r.c.reset}`}},80928:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cancelCommand=async function(e,t){if((0,s.requireTrading)(),t.all){const e=await(0,o.getOrders)({status:"resting",limit:200});if(!e)throw new Error("Kalshi not configured.");let n=e.orders;if(t.ticker&&(n=n.filter(e=>(e.ticker||"").startsWith(t.ticker))),0===n.length)return void console.log(`\n ${i.c.dim}No resting orders to cancel.${i.c.reset}\n`);if(console.log(`\n Cancelling ${n.length} order(s)...`),!t.yesIAmSure){for(let e=3;e>0;e--)process.stdout.write(` Executing in ${e}... (Ctrl+C to cancel)\r`),await new Promise(e=>setTimeout(e,1e3));process.stdout.write(" Executing... \n")}for(let e=0;e<n.length;e+=20){const t=n.slice(e,e+20).map(e=>e.order_id);await(0,o.batchCancelOrders)(t)}return void console.log(`\n ${i.c.green}✓${i.c.reset} Cancelled ${n.length} order(s).\n`)}if(!e)throw new Error("Usage: sf cancel <orderId> or sf cancel --all");await(0,o.cancelOrder)(e),console.log(`\n ${i.c.green}✓${i.c.reset} Order ${e} cancelled.\n`)};const o=n(96139),s=n(11627),i=n(99236)},97499:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contextCommand=async function(e,t){if(!e){const e=await fetch(`${t.apiUrl||a}/api/public/context`);if(!e.ok)return void console.error(` Error: ${e.status} ${await e.text()}`);const n=await e.json();if(t.share)return void await(0,r.shareOutput)("context","",n);if(t.json)return void console.log(JSON.stringify(n,null,2));const o=n.scannedAt?(0,i.shortDate)(n.scannedAt):"no scan yet",s=n.meta||{};console.log(),console.log(`${i.c.bold}Markets${i.c.reset} ${i.c.dim}${s.totalMarkets||0} markets (K:${s.kalshiMarkets||0} P:${s.polymarketMarkets||0}) · scan: ${o}${i.c.reset}`),console.log();const l=n.traditional||[];if(l.length>0){const e=l.map(e=>{const t=e.changePct||0,n=t>0?i.c.green:t<0?i.c.red:i.c.dim,o=t>0?"+":"";return`${i.c.bold}${e.symbol}${i.c.reset} ${e.price} ${n}${o}${t.toFixed(1)}%${i.c.reset}`}).join(" ");console.log(` ${e}`),console.log()}const d=n.highlights||[];if(d.length>0){console.log(`${i.c.bold}${i.c.cyan}Highlights${i.c.reset}`);for(const e of d)console.log(` ${i.c.bold}${e.title}${i.c.reset}`),console.log(` ${i.c.dim}${e.detail}${i.c.reset}`),e.relatedTickers?.length>0&&console.log(` ${i.c.dim}tickers: ${e.relatedTickers.join(", ")}${i.c.reset}`),console.log(` ${i.c.cyan}→ ${e.suggestedAction}${i.c.reset}`),console.log()}const u=n.categories||[];if(u.length>0){console.log(`${i.c.bold}Categories${i.c.reset} ${i.c.dim}(${u.length} total)${i.c.reset}`),console.log(`${i.c.dim}${"─".repeat(70)}${i.c.reset}`);for(const e of u){const t=e.description?` ${i.c.dim}${e.description}${i.c.reset}`:"";console.log(`\n ${i.c.bold}${e.name}${i.c.reset} ${i.c.dim}${e.marketCount} mkts · vol ${(0,i.vol)(e.totalVolume24h)}${i.c.reset}${t}`);const n=e.topMovers||[];if(n.length>0)for(const e of n){const t="kalshi"===e.venue?`${i.c.cyan}K${i.c.reset}`:`${i.c.magenta}P${i.c.reset}`,n=e.change24h||0,o=n>0?i.c.green:n<0?i.c.red:i.c.dim,s=0!==n?`${o}${n>0?"+":""}${n}¢${i.c.reset}`:"";console.log(` ${t} ${(0,i.rpad)(`${e.price}¢`,5)} ${(0,i.rpad)(s,14)} ${(0,i.trunc)(e.title,45)} ${i.c.dim}${e.ticker.slice(0,18)}${i.c.reset}`),e.whyInteresting&&console.log(` ${i.c.dim}${e.whyInteresting}${i.c.reset}`)}const o=e.mostLiquid||[];if(o.length>0)for(const e of o){const t="kalshi"===e.venue?`${i.c.cyan}K${i.c.reset}`:`${i.c.magenta}P${i.c.reset}`;console.log(` ${t} ${(0,i.rpad)(`${e.price}¢`,5)} spread ${e.spread}¢ vol ${(0,i.vol)(Math.round(e.volume24h))} ${i.c.dim}${(0,i.trunc)(e.title,35)}${i.c.reset}`)}}console.log()}const p=n.edges||[];if(p.length>0){console.log(`${i.c.bold}Thesis Edges${i.c.reset}`);for(const e of p.slice(0,6)){const t="kalshi"===e.venue?`${i.c.cyan}K${i.c.reset}`:`${i.c.magenta}P${i.c.reset}`,n=e.edge>0?i.c.green:i.c.red;console.log(` ${t} ${(0,i.rpad)(`${e.price}¢`,5)} ${n}edge ${e.edge>0?"+":""}${e.edge}¢${i.c.reset} ${(0,i.trunc)(e.title,40)} ${i.c.dim}${e.thesisSlug||""}${i.c.reset}`)}console.log()}const h=n.signals||[];if(h.length>0){console.log(`${i.c.bold}Recent Evaluations${i.c.reset}`);for(const e of h.slice(0,5)){const t=e.confidenceDelta,n=t>0?`${i.c.green}+${t}%${i.c.reset}`:t<0?`${i.c.red}${t}%${i.c.reset}`:`${i.c.dim}0%${i.c.reset}`,o=c(e.evaluatedAt);console.log(` ${(0,i.rpad)(o,5)} ${(0,i.rpad)(e.thesisSlug||"?",18)} ${(0,i.rpad)(n,14)} ${(0,i.trunc)(e.summary,50)}`)}console.log()}return console.log(`${i.c.dim}${"─".repeat(60)}${i.c.reset}`),console.log(` ${i.c.cyan}sf query${i.c.reset} "topic" ${i.c.dim}ask anything${i.c.reset}`),console.log(` ${i.c.cyan}sf scan${i.c.reset} "keywords" ${i.c.dim}search markets${i.c.reset}`),console.log(` ${i.c.cyan}sf explore${i.c.reset} ${i.c.dim}public theses${i.c.reset}`),console.log(` ${i.c.cyan}sf create${i.c.reset} "thesis" ${i.c.dim}start monitoring${i.c.reset}`),void console.log()}const n=new o.SFClient(t.apiKey,t.apiUrl),l=await n.getContext(e);if(t.json)return void console.log(JSON.stringify(l,null,2));console.log(`\n${i.c.bold}Thesis:${i.c.reset} ${l.thesis||l.rawThesis||"(unknown)"}`);const d=null!==l.confidence&&void 0!==l.confidence?(0,i.pct)(l.confidence):"-",u=l.lastEvaluation?.confidenceDelta,p=u?` (${(0,i.delta)(u)} since last eval)`:"";console.log(`${i.c.bold}Confidence:${i.c.reset} ${d}${p}`),console.log(`${i.c.bold}Status:${i.c.reset} ${l.status}`),console.log(`${i.c.bold}Last Updated:${i.c.reset} ${(0,i.shortDate)(l.updatedAt)}`);const h=l.causalTree?.nodes;if(h&&h.length>0){(0,i.header)("Causal Tree");for(const e of h){const t=" ".repeat((e.depth||0)+1),n=void 0!==e.probability?(0,i.pct)(e.probability):"-",o=e.label||e.id;console.log(`${t}${i.c.cyan}${e.id}${i.c.reset} ${(0,i.pad)(o,40)} ${(0,i.rpad)(n,5)}`)}}let m=null;if((0,s.isKalshiConfigured)())try{m=await(0,s.getPositions)()}catch{}const g=new Map;if(m)for(const e of m)g.set(e.ticker,e);const f=l.edges;if(f&&f.length>0){(0,i.header)("Top Edges");const e=[...f].sort((e,t)=>Math.abs(t.edge??t.edgeSize??0)-Math.abs(e.edge??e.edgeSize??0));for(const t of e.slice(0,10)){const e=t.edge??t.edgeSize??0,n=e>10?i.c.green:e>0?i.c.yellow:i.c.red,o=t.marketPrice??t.currentPrice??0,s=t.market||t.marketTitle||t.marketId||"?",r=t.orderbook,a=r?` ${i.c.dim}spread ${r.spread}¢ ${r.liquidityScore}${i.c.reset}`:"",c=g.get(t.marketId);let l="";if(c){const e=c.unrealized_pnl||0,t=e>0?i.c.green:e<0?i.c.red:i.c.dim,n=e>=0?`+$${(e/100).toFixed(0)}`:`-$${(Math.abs(e)/100).toFixed(0)}`;l=` ${i.c.cyan}← ${c.quantity}@${c.average_price_paid}¢ ${t}${n}${i.c.reset}`}console.log(` ${(0,i.pad)(s,35)} ${(0,i.rpad)(o.toFixed(0)+"¢",5)} ${n}edge ${e>0?"+":""}${e.toFixed(1)}${i.c.reset} ${i.c.dim}${t.venue||""}${i.c.reset}`+a+l)}}if(l.lastEvaluation?.summary&&((0,i.header)("Last Evaluation"),console.log(` ${i.c.dim}${(0,i.shortDate)(l.lastEvaluation.evaluatedAt)} | model: ${l.lastEvaluation.model||""}${i.c.reset}`),console.log(` ${l.lastEvaluation.summary}`),l.lastEvaluation.positionRecommendations?.length>0)){console.log(`\n ${i.c.bold}Position Recommendations:${i.c.reset}`);for(const e of l.lastEvaluation.positionRecommendations){const t="hold"===e.recommendation?i.c.dim:"close"===e.recommendation?i.c.red:i.c.yellow;console.log(` [${(e.positionId||"").slice(0,8)}] ${t}${e.recommendation}${i.c.reset} — ${e.reason}`)}}l.edgeMeta?.lastRescanAt&&console.log(`\n${i.c.dim}Last rescan: ${(0,i.shortDate)(l.edgeMeta.lastRescanAt)}${i.c.reset}`);console.log("")};const o=n(19218),s=n(96139),i=n(99236),r=n(35178),a=process.env.SF_API_URL||"https://simplefunctions.dev";function c(e){const t=Date.now()-new Date(e).getTime(),n=Math.round(t/6e4);if(n<60)return`${n}m`;const o=Math.round(n/60);return o<24?`${o}h`:`${Math.round(o/24)}d`}},46222:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl),i=!t.async;t.json||(i?console.log(`${s.c.dim}Creating thesis (sync mode — waiting for formation)...${s.c.reset}`):console.log(`${s.c.dim}Creating thesis (async mode)...${s.c.reset}`));const r=await n.createThesis(e,i),a=r.thesis?.id||r.thesisId||r.id||null;if(t.json)return void console.log(JSON.stringify({id:a,status:r.thesis?.status||r.status||"forming",result:r},null,2));a||(console.error(`${s.c.red}✗${s.c.reset} Thesis creation returned no ID.`),console.error(`${s.c.dim}Response: ${JSON.stringify(r).slice(0,200)}${s.c.reset}`),process.exit(1));console.log(`\n${s.c.green}✓${s.c.reset} Thesis created`),console.log(` ${s.c.bold}ID:${s.c.reset} ${a}`),console.log(` ${s.c.bold}Status:${s.c.reset} ${r.thesis?.status||r.status}`),r.thesis?.confidence&&console.log(` ${s.c.bold}Confidence:${s.c.reset} ${Math.round(100*parseFloat(r.thesis.confidence))}%`);r.thesis?.causalTree?.nodes&&console.log(` ${s.c.bold}Nodes:${s.c.reset} ${r.thesis.causalTree.nodes.length}`);r.thesis?.edgeAnalysis?.edges&&console.log(` ${s.c.bold}Edges:${s.c.reset} ${r.thesis.edgeAnalysis.edges.length}`);console.log(`\n${s.c.dim}View: sf get ${(0,s.shortId)(a)}${s.c.reset}`),console.log(`${s.c.dim}Context: sf context ${(0,s.shortId)(a)}${s.c.reset}`)};const o=n(19218),s=n(99236)},60952:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dashboardCommand=async function(e){if(!e?.json&&!e?.once)return void await(0,c.startDashboard)();const t=new o.SFClient(e?.apiKey,e?.apiUrl),[n,a]=await Promise.all([t.listTheses(),(0,s.getPositions)().catch(()=>null)]),u=n.theses||n,p=[];for(const e of u)try{const n=await t.getContext(e.id);p.push(n)}catch{p.push(null)}if(a)for(const e of a){const t=await(0,s.getMarketPrice)(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity))}const h=[];for(const e of p)if(e?.edges)for(const t of e.edges)h.push(t);const m=new Map;for(const e of h){const t=m.get(e.marketId);(!t||Math.abs(e.edge)>Math.abs(t.edge))&&m.set(e.marketId,e)}const g=new Set(a?.map(e=>e.ticker)||[]),f=[...m.values()].filter(e=>!g.has(e.marketId)).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,10),[y,$,w]=await Promise.all([e?.json?(0,s.getOrders)({status:"resting"}).catch(()=>[]):Promise.resolve([]),e?.json?(0,s.getBalance)().catch(()=>null):Promise.resolve(null),e?.json&&(0,r.loadConfig)().polymarketWalletAddress?(0,i.polymarketGetPositions)((0,r.loadConfig)().polymarketWalletAddress).catch(()=>[]):Promise.resolve([])]);let k=[];if(e?.json)try{k=(await t.getFeed(24,20)).evaluations||[]}catch{}if(e?.json)return void console.log(JSON.stringify({theses:u,positions:a||[],polymarketPositions:w,orders:y,balance:$,unpositionedEdges:f,feed:k,kalshiConfigured:(0,s.isKalshiConfigured)(),polymarketConfigured:!!(0,r.loadConfig)().polymarketWalletAddress,timestamp:(new Date).toISOString()},null,2));if(console.log(),console.log(" SimpleFunctions Dashboard"),console.log(" "+"─".repeat(50)),console.log(),console.log(" Theses"),0===u.length)console.log(" (none)");else for(let e=0;e<u.length;e++){const t=u[e],n=p[e],o=t.id.slice(0,8),s=(t.title||"").slice(0,35).padEnd(35),i=null!=t.confidence?`${Math.round(100*t.confidence)}%`:"?%",r=n?.edges?.length||0,a=t.updatedAt?d(t.updatedAt):"?";console.log(` ${o} ${s} ${i.padStart(4)} ${String(r).padStart(2)} edges updated ${a}`)}if(console.log(),console.log(" Positions"),a&&0!==a.length){let e=0,t=0;for(const n of a){const o=(n.ticker||"").padEnd(22),s=String(n.quantity||0).padStart(5),i=`${n.average_price_paid||0}¢`,r="number"==typeof n.current_value?`${n.current_value}¢`:"?¢",a=n.unrealized_pnl||0,c=(a/100).toFixed(2),l=a>=0?`+$${c}`:`-$${Math.abs(parseFloat(c)).toFixed(2)}`;e+=(n.average_price_paid||0)*(n.quantity||0),t+=a,console.log(` ${o} ${s} @ ${i.padEnd(5)} now ${r.padEnd(5)} ${l}`)}console.log(" "+"─".repeat(45));const n=(e/100).toFixed(0),o=(t/100).toFixed(2),s=t>=0?`+$${o}`:`-$${Math.abs(parseFloat(o)).toFixed(2)}`;console.log(` Total cost: $${n} | P&L: ${s}`)}else console.log(" (no Kalshi positions or Kalshi not configured)");if(console.log(),a&&a.length>0){console.log(" Risk Exposure");const e=new Map;for(const t of a){const n=l(t.ticker||""),o=e.get(n)||{cost:0,contracts:0,tickers:[]},s=(t.average_price_paid||0)*(t.quantity||0);o.cost+=s,o.contracts+=t.quantity||0,o.tickers.includes(t.ticker)||o.tickers.push(t.ticker),e.set(n,o)}const t=[...e.entries()].sort((e,t)=>t[1].cost-e[1].cost);for(const[e,n]of t){const t=`$${(n.cost/100).toFixed(0)}`,o=n.tickers.length<=2?` (${n.tickers.join("+")})`:` (${n.tickers.length} markets)`;console.log(` ${(e+o+":").padEnd(35)} ${t.padStart(7)} cost | ${String(n.contracts).padStart(5)} contracts`)}console.log()}if(f.length>0){console.log(" Top Unpositioned Edges");for(const e of f){const t=(e.market||e.marketId||"").slice(0,25).padEnd(25),n=`${e.marketPrice}¢`,o=`${e.thesisPrice}¢`,s=e.edge>0?`+${e.edge}`:`${e.edge}`,i=e.orderbook?.liquidityScore||"?";console.log(` ${t} ${n.padStart(5)} → ${o.padStart(5)} edge ${s.padStart(4)} ${i}`)}console.log()}};const o=n(19218),s=n(96139),i=n(34331),r=n(11627),a=n(97325),c=n(99844);function l(e){const t=Object.keys(a.RISK_CATEGORIES).sort((e,t)=>t.length-e.length);for(const n of t)if(e.startsWith(n))return a.RISK_CATEGORIES[n];return"Other"}function d(e){const t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<60)return`${n}m ago`;const o=Math.floor(n/60);if(o<24)return`${o}h ago`;return`${Math.floor(o/24)}d ago`}},81466:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deltaCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl),i=t.since?new Date(t.since):new Date(Date.now()-36e5*parseInt(t.hours||"6"));if(isNaN(i.getTime()))throw new Error(`Invalid timestamp: "${t.since}". Use ISO 8601 format (e.g., 2026-03-28T14:00:00Z)`);const r=async()=>{const o=i.toISOString(),r=await n.getChanges(e,o);if(t.json)return void console.log(JSON.stringify(r,null,2));if(!r.changed)return void console.log(`${s.c.dim}No changes since ${i.toLocaleString()}.${s.c.reset}`);const a=(0,s.shortId)(e);if(console.log(),console.log(`${s.c.bold}${s.c.cyan}Delta: ${a}${s.c.reset}${s.c.dim} — since ${i.toLocaleString()}${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(65)}${s.c.reset}`),void 0!==r.confidence){const e=Math.round(100*r.confidence),t=void 0!==r.previousConfidence?Math.round(100*r.previousConfidence):null,n=null!==t?e-t:null;let o="";null!==n&&(o=n>0?`${s.c.green} (+${n}%)${s.c.reset}`:n<0?`${s.c.red} (${n}%)${s.c.reset}`:`${s.c.dim} (0%)${s.c.reset}`),console.log(` Confidence: ${s.c.bold}${e}%${s.c.reset}${o}`)}r.evaluationCount&&console.log(` Evaluations: ${r.evaluationCount} cycle(s)`);const c=r.updatedNodes||[];if(c.length>0){console.log(),console.log(` ${s.c.bold}Node Changes (${c.length}):${s.c.reset}`);for(const e of c){const t=Math.round(100*(e.newProbability??e.newProb??0)),n=e.previousProbability??e.prevProb;let o="";if(null!=n){const e=t-Math.round(100*n);o=e>0?` ${s.c.green}+${e}%${s.c.reset}`:e<0?` ${s.c.red}${e}%${s.c.reset}`:""}const i=e.label||e.nodeId||"?";console.log(` ${i.slice(0,40).padEnd(40)} ${t}%${o}`)}}const l=r.newSignals||[];if(l.length>0){console.log(),console.log(` ${s.c.bold}New Signals (${l.length}):${s.c.reset}`);for(const e of l){const t=e.type||"signal",n=(e.content||e.title||"").replace(/\n/g," ").slice(0,70);console.log(` ${s.c.dim}[${t}]${s.c.reset} ${n}`)}}const d=r.edgeChanges||r.edges||[];if(d.length>0){console.log(),console.log(` ${s.c.bold}Edge Movements (${d.length}):${s.c.reset}`);for(const e of d.slice(0,15)){const t=(e.market||e.marketId||"").slice(0,35).padEnd(35),n=e.edge??0,o=e.previousEdge??null,i=n>0?`+${n}`:`${n}`;let r="";if(null!==o){const e=n-o;r=e>0?` ${s.c.green}(+${e})${s.c.reset}`:e<0?` ${s.c.red}(${e})${s.c.reset}`:""}const a=n>0?s.c.green:n<0?s.c.red:s.c.dim;console.log(` ${t} ${a}${i}${s.c.reset}${r}`)}}console.log(`${s.c.dim}${"─".repeat(65)}${s.c.reset}`),console.log()};if(t.watch)for(console.log(`${s.c.dim}Watching for changes every 60s... (Ctrl+C to stop)${s.c.reset}`);;)await r(),await new Promise(e=>setTimeout(e,6e4)),console.clear();else await r()};const o=n(19218),s=n(99236)},91262:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.edgesCommand=async function(e){const t=new o.SFClient(e.apiKey,e.apiUrl),n=parseInt(e.limit||"20"),a=e.minEdge?parseInt(e.minEdge):0,c=e.minLiquidity?.toLowerCase()||"",l=e.sort||"edge",d={a:4,high:4,b:3,medium:3,c:2,low:2,d:1};let u;const p=e.json?()=>{}:e=>console.log(e);if(e.thesis)p(`${i.c.dim}Fetching edges for thesis ${e.thesis}...${i.c.reset}`),u=[{id:e.thesis}];else{p(`${i.c.dim}Fetching theses...${i.c.reset}`);const e=await t.listTheses(),n=e.theses||e;u=(Array.isArray(n)?n:[]).filter(e=>"active"===e.status)}if(0===u.length)return e.json?void console.log(JSON.stringify({edges:[],totalEdges:0})):void(0,i.emptyState)("active theses",'Create one: sf create "your market thesis"');p(`${i.c.dim}Fetching edges from ${u.length} ${1===u.length?"thesis":"theses"}...${i.c.reset}`);const h=[],m=u.map(async e=>{try{const n=await t.getContext(e.id);return{thesisId:e.id,edges:n.edges||[]}}catch{return{thesisId:e.id,edges:[]}}}),g=await Promise.all(m);for(const{thesisId:e,edges:t}of g)for(const n of t)h.push({marketId:n.marketId||"",market:n.market||n.marketTitle||n.marketId||"",venue:n.venue||"kalshi",direction:n.direction||"yes",marketPrice:"number"==typeof n.marketPrice?n.marketPrice:0,thesisPrice:"number"==typeof n.thesisPrice?n.thesisPrice:0,edge:"number"==typeof n.edge?n.edge:0,executableEdge:"number"==typeof n.executableEdge?n.executableEdge:null,spread:n.orderbook?.spread??null,liquidityScore:n.orderbook?.liquidityScore??null,thesisId:e,position:null});if(0===h.length)return e.json?void console.log(JSON.stringify({edges:[],totalEdges:0,thesesScanned:u.length})):void(0,i.emptyState)("edges",`Scanned ${u.length} theses. Edges appear when thesis price diverges from market price.`);const f=new Map;for(const e of h){const t=e.marketId;if(!t)continue;const n=f.get(t);(!n||Math.abs(e.edge)>Math.abs(n.edge))&&f.set(t,e)}let y=Array.from(f.values());a>0&&(y=y.filter(e=>Math.abs(e.edge)>=a));c&&d[c]&&(y=y.filter(e=>e.liquidityScore&&(d[e.liquidityScore.toLowerCase()]||0)>=d[c]));let $=null;if((0,s.isKalshiConfigured)()&&(p(`${i.c.dim}Fetching Kalshi positions...${i.c.reset}`),$=await(0,s.getPositions)(),$)){for(const e of $){const t=await(0,s.getMarketPrice)(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity))}for(const e of y){const t=$.find(t=>t.ticker===e.marketId||e.marketId&&t.ticker?.includes(e.marketId));t&&(e.position={side:t.side||"yes",quantity:t.quantity,avgPrice:t.average_price_paid,currentValue:t.current_value,pnl:t.unrealized_pnl||0,totalCost:t.total_cost||Math.round(t.average_price_paid*t.quantity)})}}"spread"===l?y.sort((e,t)=>(e.spread??999)-(t.spread??999)):y.sort((e,t)=>{const n=null!==e.executableEdge?e.executableEdge:e.edge,o=null!==t.executableEdge?t.executableEdge:t.edge;return Math.abs(o)-Math.abs(n)});const w=y.slice(0,n),k={totalEdges:y.length,displayed:w.length,thesesScanned:u.length,edges:w};if(e.share)return void await(0,r.shareOutput)("edges","",k);if(e.json)return void console.log(JSON.stringify(k,null,2));console.log(),(0,i.header)(`Top Edges Across ${u.length} Theses`),console.log();const b=[(0,i.pad)("Market",32),(0,i.rpad)("Mkt",5),(0,i.rpad)("Thesis",7),(0,i.rpad)("Edge",6),(0,i.rpad)("Exec",6),(0,i.rpad)("Sprd",5),(0,i.pad)("Liq",5),(0,i.pad)("Thesis",10),(0,i.pad)("Position",20)].join(" ");console.log(`${i.c.dim}${b}${i.c.reset}`),(0,i.hr)(100);for(const e of w){const t=(0,i.trunc)(e.market,31),n=`${e.marketPrice}¢`,o=`${e.thesisPrice}¢`,s=e.edge>0?`+${e.edge}`:`${e.edge}`,r=null!==e.executableEdge?e.executableEdge>0?`+${e.executableEdge}`:`${e.executableEdge}`:"—",a=null!==e.spread?`${e.spread}¢`:"—",c=e.liquidityScore||"—",l=(0,i.shortId)(e.thesisId),d=e.edge>0?i.c.green:e.edge<0?i.c.red:i.c.dim,u=null!==e.executableEdge?e.executableEdge>0?i.c.green:i.c.red:i.c.dim,p="high"===c?i.c.green:"medium"===c?i.c.yellow:i.c.dim;let h=`${i.c.dim}—${i.c.reset}`;if(e.position){const t=e.position,n=t.pnl>=0?`${i.c.green}+$${(t.pnl/100).toFixed(0)}${i.c.reset}`:`${i.c.red}-$${(Math.abs(t.pnl)/100).toFixed(0)}${i.c.reset}`;h=`${i.c.green}${t.quantity}@${t.avgPrice}¢${i.c.reset} ${n}`}const m=[e.position?`${i.c.green}${(0,i.pad)(t,32)}${i.c.reset}`:(0,i.pad)(t,32),(0,i.rpad)(n,5),(0,i.rpad)(o,7),`${d}${(0,i.rpad)(s,6)}${i.c.reset}`,`${u}${(0,i.rpad)(r,6)}${i.c.reset}`,(0,i.rpad)(a,5),`${p}${(0,i.pad)(c,5)}${i.c.reset}`,`${i.c.dim}${(0,i.pad)(l,10)}${i.c.reset}`,h].join(" ");console.log(m)}(0,i.hr)(100);const v=w.filter(e=>e.position);if(v.length>0){let e=0,t=0;for(const n of v)e+=n.position.totalCost,t+=n.position.pnl;const n=`$${(e/100).toFixed(0)}`,o=`${t>=0?i.c.green:i.c.red}${t>=0?"+":"-"}$${(Math.abs(t)/100).toFixed(0)}${i.c.reset}`;console.log(`${i.c.bold}Total positioned:${i.c.reset} ${n} cost | P&L: ${o}`)}const _=w.filter(e=>!e.position&&e.edge>0);if(_.length>0){const e=_[0],t=null!==e.executableEdge?`exec +${e.executableEdge}`:`edge +${e.edge}`,n=e.liquidityScore?`, ${e.liquidityScore} liq`:"";console.log(`${i.c.bold}Top unpositioned:${i.c.reset} ${(0,i.trunc)(e.market,30)} @ ${e.marketPrice}¢ (${t}${n})`)}console.log()};const o=n(19218),s=n(96139),i=n(99236),r=n(35178)},67509:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl);console.log(`${s.c.dim}Triggering deep evaluation (heavy model)...${s.c.reset}`);const i=await n.evaluate(e);if(console.log(`\n${s.c.green}✓${s.c.reset} Evaluation complete`),i.evaluation){const e=i.evaluation;if(void 0!==e.confidenceDelta){const t=e.confidenceDelta,n=t>0?s.c.green:t<0?s.c.red:s.c.dim;console.log(` ${s.c.bold}Confidence:${s.c.reset} ${(0,s.pct)(e.previousConfidence)} → ${(0,s.pct)(e.newConfidence)} ${n}(${(0,s.delta)(t)})${s.c.reset}`)}if(e.summary&&console.log(`\n ${e.summary}`),e.positionUpdates&&e.positionUpdates.length>0){console.log(`\n ${s.c.bold}Position Recommendations:${s.c.reset}`);for(const t of e.positionUpdates){const e="hold"===t.recommendation?s.c.dim:"close"===t.recommendation?s.c.red:s.c.yellow;console.log(` [${t.positionId.slice(0,8)}] ${e}${t.recommendation}${s.c.reset} — ${t.reason}`)}}}console.log("")};const o=n(19218),s=n(99236)},22835:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exploreCommand=async function(e,t){if(!e){const e=await fetch(`${i}/api/public/theses`);if(!e.ok)return void console.error(` Error: ${e.status} ${await e.text()}`);const{theses:n}=await e.json();if(t?.share)return void await(0,o.shareOutput)("explore","",{theses:n});if(t?.json)return void console.log(JSON.stringify(n,null,2));if(console.log("\n Public Theses\n"),0===n.length)return void console.log(` ${s.c.dim}No public theses yet. Publish yours: sf publish <id>${s.c.reset}\n`);for(const e of n){const t=null!=e.confidence?Math.round(100*e.confidence):"?",n=null!=e.impliedReturn?`${e.impliedReturn>0?"+":""}${e.impliedReturn}%`:"";console.log(` ${(e.slug||"").padEnd(35)} ${String(t).padStart(3)}% ${n.padStart(8)} ${(e.status||"").padEnd(8)} ${(e.title||"").slice(0,45)}`)}return void console.log(`\n ${n.length} public theses. Use: sf explore <slug>\n`)}const n=await fetch(`${i}/api/public/thesis/${e}`);if(!n.ok)return void(404===n.status?console.error(` Not found: ${e}`):console.error(` Error: ${n.status} ${await n.text()}`));const r=await n.json();if(t?.json)return void console.log(JSON.stringify(r,null,2));const a=r.thesis,c=r.impliedReturns;console.log(`\n ${a.title}`),console.log(` ${a.slug} | ${null!=a.confidence?Math.round(100*a.confidence):"?"}% | ${a.status} | published ${a.publishedAt?.slice(0,10)||"?"}`),a.description&&console.log(` ${a.description}`);if(console.log(""),r.causalTree?.nodes?.length){console.log(" Causal Tree");for(const e of r.causalTree.nodes){const t="█".repeat(Math.round(10*(e.probability||0)))+"░".repeat(10-Math.round(10*(e.probability||0)));if(console.log(` ${e.id} ${(e.label||"").slice(0,35).padEnd(35)} ${Math.round(100*(e.probability||0))}% ${t}`),e.children)for(const t of e.children){const e="█".repeat(Math.round(10*(t.probability||0)))+"░".repeat(10-Math.round(10*(t.probability||0)));console.log(` ${t.id} ${(t.label||"").slice(0,33).padEnd(33)} ${Math.round(100*(t.probability||0))}% ${e}`)}}console.log("")}if(c&&c.edges?.length>0){console.log(` Implied Returns (equal-weight, since ${c.trackedSince?.slice(0,10)||"?"})`),console.log(` Avg: ${c.avgReturnPct>0?"+":""}${c.avgReturnPct}% | Win rate: ${c.winRate}% (${c.winners}W ${c.losers}L)`),console.log("");for(const e of c.edges.slice(0,10)){const t=e.returnPct>0?`+${e.returnPct}%`:`${e.returnPct}%`;console.log(` ${(e.market||"").slice(0,35).padEnd(35)} ${e.entryPrice}¢ → ${e.currentPrice}¢ ${t}`)}console.log("")}if(r.confidenceHistory?.length>0){console.log(" Recent Evaluations");for(const e of r.confidenceHistory.slice(-5)){const t=e.delta>0?`+${Math.round(100*e.delta)}`:`${Math.round(100*e.delta)}`;console.log(` ${(e.evaluatedAt||"").slice(0,16)} ${Math.round(100*e.confidence)}% (${t}) ${(e.summary||"").slice(0,60)}`)}console.log("")}if(r.edges?.length>0){console.log(" Top Edges");const e=[...r.edges].sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,10);for(const t of e){const e=t.orderbook?.liquidityScore||"?";console.log(` ${(t.market||"").slice(0,35).padEnd(35)} ${t.marketPrice}¢ → ${t.thesisPrice}¢ edge ${t.edge>0?"+":""}${t.edge} ${e}`)}console.log("")}};const o=n(35178),s=n(99236),i="https://simplefunctions.dev"},44478:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.feedCommand=async function(e){const t=new o.SFClient(e.apiKey,e.apiUrl),n=parseInt(e.hours||"24"),i=await t.getFeed(n,200);let r=i.feed||[];if(0===r.length)return void console.log(`${s.c.dim}No evaluations in the last ${n} hours.${s.c.reset}`);if(e.thesis&&(r=r.filter(t=>t.thesisId.startsWith(e.thesis)||t.thesisShortId===e.thesis),0===r.length))return void console.log(`${s.c.dim}No evaluations for ${e.thesis} in the last ${n} hours.${s.c.reset}`);if(e.json)return void console.log(JSON.stringify(r,null,2));console.log(),console.log(`${s.c.bold}${s.c.cyan}Evaluation Feed${s.c.reset}${s.c.dim} — last ${n}h, ${r.length} cycles${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(75)}${s.c.reset}`);for(const e of r){const t=new Date(e.evaluatedAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n=Math.round(100*e.confidence),o=Math.round(100*e.delta);let i;i=o>0?`${s.c.green}+${o}%${s.c.reset}`:o<0?`${s.c.red}${o}%${s.c.reset}`:`${s.c.dim}0%${s.c.reset}`;const r=e.thesisShortId||e.thesisId?.slice(0,8)||"?",a=(e.summary||"No summary").replace(/\n/g," ").slice(0,80),c=e.updatedNodes||[],l=c.length>0?c.slice(0,3).map(e=>`${e.nodeId}→${Math.round(100*(e.newProb||0))}%`).join(", "):"";console.log(`${s.c.dim}[${t}]${s.c.reset} ${s.c.cyan}${r}${s.c.reset} ${n}% (${i}) ${s.c.dim}${a}${s.c.reset}`),l&&console.log(`${" ".repeat(9)} ${s.c.dim}nodes: ${l}${s.c.reset}`)}console.log(`${s.c.dim}${"─".repeat(75)}${s.c.reset}`),console.log()};const o=n(19218),s=n(99236)},63746:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fillsCommand=async function(e){const t=await(0,o.getFills)({ticker:e.ticker,limit:50});if(!t)throw new Error("Kalshi not configured. Run: sf setup --kalshi");if(e.json)return void console.log(JSON.stringify(t.fills,null,2));if(0===t.fills.length)return void console.log(`${s.c.dim}No fills.${s.c.reset}`);console.log(`${s.c.bold}${s.c.cyan}Recent Fills${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(80)}${s.c.reset}`);for(const e of t.fills){const t=e.yes_price_dollars?100*parseFloat(e.yes_price_dollars)+"¢":`${e.yes_price||"?"}¢`,n="yes"===e.side?`${s.c.green}YES${s.c.reset}`:`${s.c.red}NO${s.c.reset}`,o=e.action||"buy",i=e.count_fp||e.count||"?",r=e.created_time?new Date(e.created_time).toLocaleString():"";console.log(` ${(e.ticker||"").padEnd(35)} ${o.padEnd(5)} ${n} ${t.padEnd(8)} x${i} ${s.c.dim}${r}${s.c.reset}`)}console.log(`\n${s.c.dim}${t.fills.length} fill(s)${s.c.reset}`)};const o=n(96139),s=n(99236)},28423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.forecastCommand=async function(e,t){const n=parseInt(t.days||"7"),r=await fetch(`${i}/events/${e}`,{headers:{Accept:"application/json"}});if(!r.ok)throw new Error(`Event not found: ${e}`);const a=await r.json(),c=a.event?.series_ticker;if(!c)throw new Error(`No series_ticker for ${e}`);const l=new Date;l.setUTCHours(0,0,0,0);const d=Math.floor(l.getTime()/1e3),u=d-86400*n,p=await(0,o.getForecastHistory)({seriesTicker:c,eventTicker:e,percentiles:[5e3,7500,9e3],startTs:u,endTs:d,periodInterval:1440});if(!p||0===p.length)return void console.log(`${s.c.dim}No forecast data for ${e}${s.c.reset}`);if(t.json)return void console.log(JSON.stringify(p,null,2));console.log(`${s.c.bold}${s.c.cyan}Forecast: ${a.event?.title||e}${s.c.reset}`),console.log(`${s.c.dim}Series: ${c} | ${n} days${s.c.reset}`),console.log(),console.log(`${s.c.bold}${"Date".padEnd(14)} ${"P50".padEnd(12)} ${"P75".padEnd(12)} P90${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(52)}${s.c.reset}`);for(const e of p){const t=new Date(1e3*e.end_period_ts).toISOString().slice(0,10),n=e.percentile_points||[],o=n.find(e=>5e3===e.percentile)?.formatted_forecast||"-",s=n.find(e=>7500===e.percentile)?.formatted_forecast||"-",i=n.find(e=>9e3===e.percentile)?.formatted_forecast||"-";console.log(` ${t.padEnd(14)} ${o.padEnd(12)} ${s.padEnd(12)} ${i}`)}};const o=n(96139),s=n(99236),i="https://api.elections.kalshi.com/trade-api/v2"},5596:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl),r=await n.getThesis(e);if(t.json)return void console.log(JSON.stringify(r,null,2));const a=r,c=r.positions||[];(0,s.header)(`Thesis: ${(a.id||e).slice(0,8)}`),(0,s.hr)(),console.log(`${s.c.bold}Status:${s.c.reset} ${a.status||"-"}`);const l=a.confidence?(0,s.pct)(parseFloat(a.confidence)):"-";console.log(`${s.c.bold}Confidence:${s.c.reset} ${l}`);const d=a.createdAt instanceof Date?a.createdAt.toISOString():a.createdAt,u=a.updatedAt instanceof Date?a.updatedAt.toISOString():a.updatedAt;console.log(`${s.c.bold}Created:${s.c.reset} ${(0,s.shortDate)(d)}`),console.log(`${s.c.bold}Updated:${s.c.reset} ${(0,s.shortDate)(u)}`),a.title&&console.log(`${s.c.bold}Title:${s.c.reset} ${a.title}`);console.log(`${s.c.bold}Thesis:${s.c.reset} ${a.rawThesis||"-"}`),a.webhookUrl&&console.log(`${s.c.bold}Webhook:${s.c.reset} ${a.webhookUrl}`);const p=a.causalTree;p&&p.nodes&&((0,s.header)("Causal Tree"),i(p.nodes,0));const h=a.edgeAnalysis;if(h&&h.edges){(0,s.header)("Edge Analysis"),console.log(`${s.c.dim}Analyzed: ${(0,s.shortDate)(h.analyzedAt)}${s.c.reset}`),h.lastRescanAt&&console.log(`${s.c.dim}Last rescan: ${(0,s.shortDate)(h.lastRescanAt)}${s.c.reset}`);for(const e of h.edges){const t=e.edgeSize??0,n=t>10?s.c.green:t>0?s.c.yellow:s.c.red;console.log(` ${e.marketTitle||e.marketId} ${s.c.dim}${e.venue}${s.c.reset} price: ${(e.marketPrice??0).toFixed(0)}¢ ${n}edge: ${t>0?"+":""}${t.toFixed(1)}${s.c.reset}`)}}if(c.length>0){(0,s.header)("Positions");for(const e of c){if(!e)continue;const t="open"===e.status?s.c.green+"●":s.c.dim+"○";console.log(` ${t}${s.c.reset} [${(e.id||"?").slice(0,8)}] "${e.marketTitle||"?"}" ${e.direction||"?"}@${e.entryPrice||"?"}→${e.currentPrice||e.entryPrice||"?"} ${s.c.dim}(${e.venue||"?"})${s.c.reset}`)}}const m=a.lastEvaluation;if(m){(0,s.header)("Last Evaluation");const e=m.evaluatedAt instanceof Date?m.evaluatedAt.toISOString():m.evaluatedAt;if(console.log(`${s.c.dim}${(0,s.shortDate)(e)} | model: ${m.model||"-"}${s.c.reset}`),void 0!==m.confidenceDelta){const e=m.confidenceDelta,t=e>0?s.c.green:e<0?s.c.red:s.c.dim;console.log(`Confidence: ${(0,s.pct)(m.previousConfidence)} → ${(0,s.pct)(m.newConfidence)} ${t}(${(0,s.delta)(e)})${s.c.reset}`)}m.summary&&console.log(`\n${m.summary}`)}console.log("")};const o=n(19218),s=n(99236);function i(e,t){for(const n of e){if(!n)continue;const e=" ".repeat(t+1),o=void 0!==n.probability?(0,s.pct)(n.probability):"-",r=void 0!==n.importance?` imp:${n.importance}`:"";console.log(`${e}${s.c.cyan}${n.id}${s.c.reset} ${n.label} ${s.c.dim}(${o}${r})${s.c.reset}`),n.children&&n.children.length>0&&i(n.children,t+1)}}},87604:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.heartbeatCommand=async function(e,t,n){const s=n.newsInterval||n.xInterval||n.model||void 0!==n.budget||n.pause||n.resume;if(s){const s={};n.newsInterval&&(s.newsIntervalMin=parseInt(n.newsInterval,10)),n.xInterval&&(s.xIntervalMin=parseInt(n.xInterval,10)),n.model&&(s.evalModelTier=n.model),void 0!==n.budget&&(s.monthlyBudgetUsd=parseFloat(n.budget)),n.pause&&(s.paused=!0),n.resume&&(s.paused=!1);try{const n=await e.updateHeartbeatConfig(t,s);console.log(`\n ${o.c.green}✓${o.c.reset} Updated heartbeat config`),console.log(` ${o.c.dim}Updated fields: ${n.updated.join(", ")}${o.c.reset}\n`)}catch(e){return void console.error(` ${o.c.red}✗ ${e.message}${o.c.reset}`)}}try{const n=await e.getHeartbeatConfig(t),s=n.config,i=n.costs;console.log(`\n ${o.c.bold}Heartbeat Config${o.c.reset} ${o.c.dim}(${t.slice(0,8)})${o.c.reset}`),console.log();const r=s.paused?`${o.c.red}⏸ paused${o.c.reset}`:`${o.c.green}▶ active${o.c.reset}`;if(console.log(` Status ${r}`),console.log(` News interval ${o.c.cyan}${s.newsIntervalMin}${o.c.reset} min ${o.c.dim}(${s.newsIntervalMin===n.defaults.newsIntervalMin?"default":"custom"})${o.c.reset}`),console.log(` X interval ${o.c.cyan}${s.xIntervalMin}${o.c.reset} min ${o.c.dim}(${s.xIntervalMin===n.defaults.xIntervalMin?"default":"custom"})${o.c.reset}`),console.log(` Eval model ${o.c.cyan}${s.evalModelTier}${o.c.reset} ${o.c.dim}(${s.evalModelTier===n.defaults.evalModelTier?"default":"custom"})${o.c.reset}`),console.log(" Monthly budget "+(s.monthlyBudgetUsd>0?`${o.c.cyan}$${s.monthlyBudgetUsd}${o.c.reset}`:`${o.c.dim}unlimited${o.c.reset}`)),console.log(),console.log(` ${o.c.bold}This Month${o.c.reset}`),console.log(` Total cost ${o.c.cyan}$${i.monthlyTotal.toFixed(4)}${o.c.reset}`),console.log(` LLM calls ${i.llmCalls}`),console.log(` Search calls ${i.searchCalls}`),console.log(` Tokens ${o.c.dim}${i.inputTokens.toLocaleString()} in / ${i.outputTokens.toLocaleString()} out${o.c.reset}`),null!==i.budgetRemaining){const e=s.monthlyBudgetUsd>0?Math.round(i.monthlyTotal/s.monthlyBudgetUsd*100):0;console.log(` Budget used ${e}% ${o.c.dim}($${i.budgetRemaining.toFixed(2)} remaining)${o.c.reset}`)}console.log()}catch(e){console.error(` ${o.c.red}✗ ${e.message}${o.c.reset}`)}};const o=n(99236)},9708:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.historyCommand=async function(e,t){const n=await(0,o.getHistoricalMarket)(e);if(!n)return void console.log(`${s.c.dim}No historical data for ${e}${s.c.reset}`);if(t.json)return void console.log(JSON.stringify(n,null,2));console.log(`${s.c.bold}${s.c.cyan}${n.title||e}${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(60)}${s.c.reset}`),console.log(` Ticker: ${n.ticker||e}`),console.log(` Event: ${n.event_ticker||"-"}`),console.log(` Status: ${n.status||"-"}`),console.log(` Result: ${n.result||n.market_result||"-"}`),n.last_price_dollars&&console.log(` Last Price: ${Math.round(100*parseFloat(n.last_price_dollars))}¢`);void 0!==n.settlement_value&&console.log(` Settlement: ${n.settlement_value}`);n.volume&&console.log(` Volume: ${n.volume}`);n.open_interest&&console.log(` Open Int: ${n.open_interest}`);n.expiration_time&&console.log(` Expired: ${n.expiration_time}`);console.log()};const o=n(96139),s=n(99236)},30896:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ideasCommand=async function(e){const t=process.env.SF_API_URL||"https://simplefunctions.dev",n=new URLSearchParams;e.category&&n.set("category",e.category);e.fresh&&n.set("freshness",e.fresh);const s=await fetch(`${t}/api/public/ideas?${n.toString()}`);s.ok||(console.error(`\n ${o.c.red}Error:${o.c.reset} API returned ${s.status}\n`),process.exit(1));const i=await s.json();if(e.json)return void console.log(JSON.stringify(i,null,2));const r=i.ideas||i;if(!Array.isArray(r)||0===r.length)return void console.log(`\n ${o.c.dim}No trade ideas available.${o.c.reset}\n`);console.log(),console.log(` ${o.c.bold}Trade Ideas${o.c.reset} ${o.c.dim}${r.length} ideas${o.c.reset}`),console.log();for(const e of r){const t="long"===e.direction?o.c.green+"▲ LONG"+o.c.reset:o.c.red+"▼ SHORT"+o.c.reset,n="●".repeat(Math.min(e.conviction||3,5));if(console.log(` ${t} ${e.headline}`),console.log(` ${o.c.dim}Conviction: ${n} Category: ${e.category||"-"} Horizon: ${e.timeHorizon||"-"}${o.c.reset}`),console.log(` ${e.pitch||""}`),e.catalyst&&console.log(` ${o.c.dim}Catalyst: ${e.catalyst}${o.c.reset}`),e.risk&&console.log(` ${o.c.dim}Risk: ${e.risk}${o.c.reset}`),e.markets?.length){const t=e.markets.map(e=>`${e.ticker||e.marketId} ${e.currentPrice?e.currentPrice+"¢":""}`).join(", ");console.log(` ${o.c.dim}Markets: ${t}${o.c.reset}`)}console.log()}};const o=n(99236)},15472:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.registerIntents=function(e){const t=e.command("intent").description("Manage execution intents");t.command("list").option("--all","Show all statuses (default: active only)").option("--status <status>","Filter by status").option("--json","JSON output").description("List intents").action(async e=>{try{const t=new o.SFClient,n=e.all?{}:{active:!e.status,status:e.status},{intents:i}=await t.listIntents(n);if(e.json)return void console.log(JSON.stringify(i,null,2));if(!i||0===i.length)return void(0,s.emptyState)("intents","Create one: sf intent buy TICKER QTY --price CENTS");console.log(`\n ${s.c.bold}INTENTS${s.c.reset} (${i.length})\n`);for(const e of i)console.log(r(e)),console.log()}catch(e){console.error(`${s.c.red}Error:${s.c.reset} ${e.message}`),process.exit(1)}}),t.command("buy").argument("<ticker>","Market ticker (e.g. KXFEDDEC-25DEC31-T100)").argument("<quantity>","Number of contracts").option("--price <cents>","Max price per contract in cents").option("--side <side>","Direction: yes or no","yes").option("--trigger <trigger>","Trigger condition: immediate, below:<cents>, above:<cents>","immediate").option("--expire <duration>","Expiry: 1h, 6h, 1d, 3d, 1w","1d").option("--venue <venue>","Venue: kalshi or polymarket","kalshi").option("--rationale <text>","Why this trade").option("--auto","Auto-execute without confirmation").option("--style <style>","Execution style: immediate, twap","immediate").option("--json","JSON output").description("Create a buy intent").action(async(e,t,n)=>{await a("buy",e,t,n)}),t.command("sell").argument("<ticker>","Market ticker").argument("<quantity>","Number of contracts").option("--price <cents>","Max price per contract in cents").option("--side <side>","Direction: yes or no","yes").option("--trigger <trigger>","Trigger condition","immediate").option("--expire <duration>","Expiry","1d").option("--venue <venue>","Venue","kalshi").option("--rationale <text>","Why this trade").option("--auto","Auto-execute without confirmation").option("--json","JSON output").description("Create a sell intent").action(async(e,t,n)=>{await a("sell",e,t,n)}),t.command("status").argument("<id>","Intent ID or prefix").option("--json","JSON output").description("Detailed intent status with fills").action(async(e,t)=>{try{const n=new o.SFClient,{intent:i}=await n.getIntentDetail(e);if(t.json)return void console.log(JSON.stringify(i,null,2));if(console.log(`\n ${s.c.bold}Intent ${i.id.slice(0,8)}${s.c.reset}\n`),console.log(r(i)),console.log(),i.fills&&i.fills.length>0){console.log(` ${s.c.bold}Fills${s.c.reset} (${i.fills.length})\n`);for(const e of i.fills){const t=new Date(e.filledAt).toLocaleTimeString("en-US",{hour12:!1});console.log(` ${t} ${e.fillQuantity} @ ${e.fillPrice}c ($${(e.fillCostCents/100).toFixed(2)}) ${s.c.dim}order: ${e.orderId||"?"}${s.c.reset}`)}console.log();const e=i.fills.reduce((e,t)=>e+t.fillCostCents,0),t=i.fills.reduce((e,t)=>e+t.fillPrice*t.fillQuantity,0)/i.filledQuantity;console.log(` Total: $${(e/100).toFixed(2)} avg ${t.toFixed(1)}c`),console.log()}}catch(e){console.error(`${s.c.red}Error:${s.c.reset} ${e.message}`),process.exit(1)}}),t.command("cancel").argument("<id>","Intent ID or prefix").description("Cancel an intent").action(async e=>{try{const t=new o.SFClient;await t.cancelIntentAPI(e),console.log(`\n ${s.c.green}OK${s.c.reset} Intent ${e} cancelled.\n`)}catch(e){console.error(`${s.c.red}Error:${s.c.reset} ${e.message}`),process.exit(1)}})};const o=n(19218),s=n(99236),i={pending:"",armed:"",triggered:"",executing:"",filled:"",partial:"",expired:"",cancelled:"",rejected:""};function r(e){const t=i[e.status]||"",n=[],o=e.action.toUpperCase(),r=e.direction.toUpperCase(),a=e.maxPrice?` @ ≤${e.maxPrice}c`:" @ market",c="kalshi"===e.venue?"K":"P";if(n.push(` ${t}[${e.status}]${s.c.reset} ${s.c.bold}${o}${s.c.reset} ${e.marketId} ${r} ${e.targetQuantity}${a} ${s.c.dim}${c}${s.c.reset}`),"immediate"!==e.triggerType){const t=function(e){switch(e.triggerType){case"price_below":return`price ≤ ${e.triggerPrice}c`;case"price_above":return`price ≥ ${e.triggerPrice}c`;case"time":return`at ${new Date(e.triggerAt).toLocaleString()}`;case"compound":return"compound (see details)";default:return e.triggerType}}(e);n.push(` Trigger: ${t}`)}if(e.filledQuantity>0){const t=Math.round(e.filledQuantity/e.targetQuantity*100);n.push(` Filled: ${e.filledQuantity}/${e.targetQuantity} (${t}%)`)}const l=new Date(e.expireAt).toLocaleDateString("en-US",{month:"short",day:"numeric"});return n.push(` ${s.c.dim}expires ${l} · source: ${e.source}${e.rationale?` · "${e.rationale.slice(0,60)}"`:""}${s.c.reset}`),n.join("\n")}async function a(e,t,n,i){try{const r=new o.SFClient,a=parseInt(n);if(isNaN(a)||a<1)throw new Error("Quantity must be a positive integer");const c=function(e){if("immediate"===e)return{type:"immediate"};const[t,n]=e.split(":");if("below"===t&&n)return{type:"price_below",price:parseInt(n)};if("above"===t&&n)return{type:"price_above",price:parseInt(n)};throw new Error(`Unknown trigger: "${e}". Use: immediate, below:<cents>, above:<cents>`)}(i.trigger||"immediate"),l=i.price?parseInt(i.price):void 0;if(void 0!==l&&(l<1||l>99))throw new Error("Price must be 1-99 cents");const d={"1h":36e5,"6h":216e5,"1d":864e5,"3d":2592e5,"1w":6048e5},u=d[i.expire]||d["1d"],p={action:e,venue:i.venue||"kalshi",marketId:t.toUpperCase(),marketTitle:t.toUpperCase(),direction:i.side||"yes",targetQuantity:a,maxPrice:l,triggerType:c.type,triggerPrice:c.price,expireAt:new Date(Date.now()+u).toISOString(),source:"manual",rationale:i.rationale,autoExecute:!!i.auto,executionStyle:i.style||"immediate"},h=await r.createIntent(p);if(i.json)return void console.log(JSON.stringify(h,null,2));const m=l?`$${(a*l/100).toFixed(2)}`:"market";console.log(),console.log(` ${s.c.green}OK${s.c.reset} Intent created: ${h.id?.slice(0,8)||"OK"}`),console.log(),console.log(` ${e.toUpperCase()} ${t.toUpperCase()} ${(i.side||"yes").toUpperCase()} x${a}${l?` @ ≤${l}c`:""}`),console.log(` Trigger: ${i.trigger||"immediate"}`),console.log(` Max cost: ${m}`),console.log(` Expires: ${i.expire||"1d"}`),i.auto&&console.log(" Auto-execute: ON"),console.log(),console.log(` ${s.c.dim}Start runtime to execute: sf runtime start${s.c.reset}`),console.log()}catch(e){console.error(`${s.c.red}Error:${s.c.reset} ${e.message}`),process.exit(1)}}},50984:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.liquidityCommand=async function(e){const t=Object.keys(r.TOPIC_SERIES);if(!e.topic&&!e.all){console.log(),console.log(`${a.c.bold}Available Topics${a.c.reset} ${a.c.dim}(${t.length} topics)${a.c.reset}`),console.log(a.c.dim+"─".repeat(50)+a.c.reset),console.log();for(const e of t){const t=r.TOPIC_SERIES[e];console.log(` ${a.c.cyan}${(0,a.pad)(e,14)}${a.c.reset} ${a.c.dim}${t.slice(0,3).join(", ")}${t.length>3?` +${t.length-3} more`:""}${a.c.reset}`)}return console.log(),console.log(`${a.c.dim}Usage: sf liquidity <topic> (e.g. sf liquidity oil)${a.c.reset}`),console.log(`${a.c.dim} sf liquidity --all (scan all topics)${a.c.reset}`),void console.log()}const n=e.topic?t.filter(t=>t.toLowerCase()===e.topic.toLowerCase()):t;if(e.topic&&0===n.length){const n=t.join(", ");console.error(`Unknown topic: ${e.topic}. Valid topics: ${n}`),process.exit(1)}let h=new Set;if((0,s.isKalshiConfigured)())try{const e=await(0,s.getPositions)();e&&(h=new Set(e.map(e=>e.ticker)))}catch{}const m={};for(const e of n){const t=r.TOPIC_SERIES[e],n=[];for(const e of t)try{const t=await(0,o.kalshiFetchMarketsBySeries)(e);n.push(...t)}catch{}n.length>0&&(m[e]=n)}const g="kalshi"!==e.venue;if(g)for(const e of n)try{const t=await(0,i.polymarketSearch)(e,5);for(const n of t)for(const t of n.markets||[])t.active&&!t.closed&&t.enableOrderBook&&(m[e]||(m[e]=[]),m[e].push({ticker:t.conditionId?.slice(0,16)||t.id,close_time:t.endDateIso||"",venue:"polymarket",question:t.question||n.title,clobTokenIds:t.clobTokenIds,bestBid:t.bestBid,bestAsk:t.bestAsk,spread:t.spread,liquidityNum:t.liquidityNum}))}catch{}const f=e.horizon,y=[];for(const[e,t]of Object.entries(m))for(const n of t){const t=n.close_time||n.expiration_time||"";if(!t)continue;const o=c(t);f&&o!==f||y.push({ticker:n.ticker,closeTime:t,topic:e,horizon:o,venue:n.venue||"kalshi",question:n.question,clobTokenIds:n.clobTokenIds})}if(0===y.length)return void console.log("No markets found matching filters.");const $=y.filter(e=>"kalshi"===e.venue),w=y.filter(e=>"polymarket"===e.venue),k=await u($,async e=>({info:e,ob:await(0,s.getPublicOrderbook)(e.ticker)}),5,100),b=await u(w,async e=>{if(!e.clobTokenIds)return{info:e,depth:null};const t=(0,i.parseClobTokenIds)(e.clobTokenIds);if(!t)return{info:e,depth:null};return{info:e,depth:await(0,i.polymarketGetOrderbookWithDepth)(t[0])}},5,100),v=[];for(const t of k){if(!t||!t.ob)continue;const{info:n,ob:o}=t,s=o.yes_dollars.map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0),i=o.no_dollars.map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0);s.sort((e,t)=>t.price-e.price),i.sort((e,t)=>t.price-e.price);const r=s.length>0?s[0].price:0,a=i.length>0?100-i[0].price:100,c=a-r,l=s.reduce((e,t)=>e+t.qty,0),u=i.reduce((e,t)=>e+t.qty,0),p=d(o.no_dollars,100);e.minDepth&&l+u<e.minDepth||v.push({ticker:n.ticker,shortTicker:n.ticker,topic:n.topic.toUpperCase(),horizon:n.horizon,closeTime:n.closeTime,bestBid:r,bestAsk:a,spread:c,bidDepth:l,askDepth:u,slippage100:p,held:h.has(n.ticker),venue:"kalshi"})}for(const t of b){if(!t||!t.depth)continue;const{info:n,depth:o}=t;e.minDepth&&o.bidDepthTop3+o.askDepthTop3<e.minDepth||v.push({ticker:(n.question||n.ticker).slice(0,30),shortTicker:(n.question||n.ticker).slice(0,30),topic:n.topic.toUpperCase(),horizon:n.horizon,closeTime:n.closeTime,bestBid:o.bestBid,bestAsk:o.bestAsk,spread:o.spread,bidDepth:o.totalBidDepth,askDepth:o.totalAskDepth,slippage100:"-",held:!1,venue:"polymarket"})}if(e.json)return void console.log(JSON.stringify(v,null,2));const _=(new Date).toISOString().slice(0,10);console.log(),console.log(`${a.c.bold}Liquidity Scanner${a.c.reset} ${a.c.dim}(${_} UTC)${a.c.reset}`),console.log(a.c.dim+"─".repeat(68)+a.c.reset);const S={};for(const e of v){const t=e.topic||"OTHER";S[t]||(S[t]={}),S[t][e.horizon]||(S[t][e.horizon]=[]),S[t][e.horizon].push(e)}let x=0,C=0,O=0;const I=["weekly","monthly","long-term"];for(const[e,t]of Object.entries(S))for(const n of I){const o=t[n];if(!o||0===o.length)continue;const s=o.filter(e=>"kalshi"===e.venue);if(s.length>1){const e=p(s.map(e=>e.ticker));for(const t of s){const n=e.length>0?t.ticker.slice(e.length).replace(/^-/,""):t.ticker;t.shortTicker=n.length>0?n:t.ticker}}o.sort((e,t)=>e.venue!==t.venue?"kalshi"===e.venue?-1:1:"kalshi"===e.venue?e.ticker.localeCompare(t.ticker):e.spread-t.spread),console.log(),console.log(`${a.c.bold}${a.c.cyan}${e}${a.c.reset} ${a.c.dim}— ${l(n)}${a.c.reset}`),console.log(`${a.c.dim} ${(0,a.pad)("Market",22)} ${(0,a.rpad)("Bid¢",5)} ${(0,a.rpad)("Ask¢",5)} ${(0,a.rpad)("Spread",6)} ${(0,a.rpad)("BidDep",6)} ${(0,a.rpad)("AskDep",6)} ${(0,a.rpad)("Slip100",7)}${a.c.reset}`);for(const e of o){x++,e.held&&O++;const t=e.spread>5;let n;t&&C++,n=e.spread<=2?`${a.c.green}${e.spread}¢${a.c.reset}`:e.spread<=5?`${a.c.yellow}${e.spread}¢${a.c.reset}`:`${a.c.red}${e.spread}¢${a.c.reset}`;const o=t?" ⚠️":"",s=e.held?` ${a.c.magenta}← held${a.c.reset}`:"",i=(0,a.rpad)(`${e.spread}¢`,6),r=e.spread<=2?`${a.c.green}${i}${a.c.reset}`:e.spread<=5?`${a.c.yellow}${i}${a.c.reset}`:`${a.c.red}${i}${a.c.reset}`,c="polymarket"===e.venue?`${a.c.blue}POLY${a.c.reset} `:`${a.c.cyan}KLSH${a.c.reset} `;console.log(`${c}${(0,a.pad)(e.shortTicker,22)} ${(0,a.rpad)(String(e.bestBid),5)} ${(0,a.rpad)(String(e.bestAsk),5)} ${r} ${(0,a.rpad)(String(Math.round(e.bidDepth)),6)} ${(0,a.rpad)(String(Math.round(e.askDepth)),6)} ${(0,a.rpad)(e.slippage100,7)}${o}${s}`)}}console.log(),console.log(`${a.c.dim}Summary: ${x} markets | ${C} thin (spread>5¢) | ${O} held${a.c.reset}`),console.log()};const o=n(19218),s=n(96139),i=n(34331),r=n(97325),a=n(99236);function c(e){const t=Date.now(),n=(new Date(e).getTime()-t)/864e5;return n<7?"weekly":n<=35?"monthly":"long-term"}function l(e){switch(e){case"weekly":return"weekly (<7d)";case"monthly":return"monthly (7-35d)";case"long-term":return"long-term (>35d)"}}function d(e,t){const n=e.map(([e,t])=>({noPrice:parseFloat(e),yesAsk:1-parseFloat(e),qty:parseFloat(t)})).filter(e=>e.noPrice>0&&e.qty>0).sort((e,t)=>t.noPrice-e.noPrice);let o=t,s=0;for(const e of n){if(o<=0)break;const t=Math.min(o,e.qty);s+=t*e.yesAsk,o-=t}if(o>0)return"∞";return(100*(s/t)).toFixed(1)+"¢"}async function u(e,t,n,o){const s=[];for(let i=0;i<e.length;i+=n){const r=e.slice(i,i+n),a=await Promise.allSettled(r.map(t));for(const e of a)s.push("fulfilled"===e.status?e.value:null);i+n<e.length&&await new Promise(e=>setTimeout(e,o))}return s}function p(e){if(0===e.length)return"";if(1===e.length)return"";let t=e[0];for(let n=1;n<e.length;n++)for(;!e[n].startsWith(t);)if(t=t.slice(0,-1),0===t.length)return"";return t}},38706:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.listCommand=async function(e){const t=new o.SFClient(e.apiKey,e.apiUrl),{theses:n}=await t.listTheses();if(e.json)return void console.log(JSON.stringify(n,null,2));if(0===n.length)return void(0,s.emptyState)("theses",'Create one: sf create "your market thesis"');console.log(`\n${s.c.bold}`+(0,s.pad)("ID",12)+(0,s.pad)("Status",10)+(0,s.rpad)("Conf",6)+" "+(0,s.pad)("Updated",14)+" Title"+s.c.reset),(0,s.hr)(90);for(const e of n){const t="active"===e.status?s.c.green:"forming"===e.status?s.c.yellow:s.c.dim,n=e.confidence?(0,s.pct)(parseFloat(e.confidence)):"-";console.log((0,s.pad)((0,s.shortId)(e.id),12)+t+(0,s.pad)(e.status,10)+s.c.reset+(0,s.rpad)(n,6)+" "+s.c.dim+(0,s.pad)((0,s.shortDate)(e.updatedAt),14)+s.c.reset+" "+(0,s.trunc)(e.title||e.rawThesis.slice(0,60),50))}console.log(`\n${s.c.dim}${n.length} thesis(es)${s.c.reset}`)};const o=n(19218),s=n(99236)},50869:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.loginCommand=async function(e){const t=e.apiUrl||(0,s.loadConfig)().apiUrl||r,a=(0,s.loadFileConfig)();if(a.apiKey&&!e.force)return console.log(`\n ${i.c.dim}Already logged in (${a.apiKey.slice(0,12)}...).${i.c.reset}`),void console.log(` ${i.c.dim}Run ${i.c.cyan}sf login --force${i.c.dim} to re-authenticate, or ${i.c.cyan}sf logout${i.c.dim} to clear.${i.c.reset}\n`);const c=(0,o.randomBytes)(32).toString("base64url");console.log(`\n ${i.c.dim}Registering login session...${i.c.reset}`);try{const e=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:c})});if(!e.ok){const t=await e.json().catch(()=>({}));return void console.error(` ${i.c.red}Failed to create session: ${t.error||e.status}${i.c.reset}`)}}catch(e){return void console.error(` ${i.c.red}Could not reach ${t}${i.c.reset}`)}const l=`${t}/auth/cli?token=${c}`;console.log(`\n ${i.c.bold}Opening browser...${i.c.reset}`),console.log(` ${i.c.dim}${l}${i.c.reset}\n`);try{const{exec:e}=await Promise.resolve().then(n.t.bind(n,35317,23)),t=process.platform;e(`${"darwin"===t?"open":"win32"===t?"start":"xdg-open"} "${l}"`)}catch{console.log(` ${i.c.dim}Could not open browser. Visit the URL above manually.${i.c.reset}`)}console.log(` ${i.c.dim}Waiting for login...${i.c.reset}`);const d=Date.now();for(;Date.now()-d<3e5;){await new Promise(e=>setTimeout(e,2e3));try{const e=await fetch(`${t}/api/auth/cli/poll?token=${c}`),n=await e.json();if("ready"===n.status&&n.apiKey)return(0,s.saveConfig)({...a,apiKey:n.apiKey,apiUrl:t!==r?t:void 0}),console.log(`\n ${i.c.green}✓${i.c.reset} ${i.c.bold}Authenticated!${i.c.reset}`),console.log(` ${i.c.dim}API key saved to ~/.sf/config.json${i.c.reset}`),console.log(`\n ${i.c.dim}OpenRouter & Tavily are proxied through ${t}${i.c.reset}`),console.log(` ${i.c.dim}No additional API keys needed.${i.c.reset}`),console.log(`\n ${i.c.cyan}sf context${i.c.reset} ${i.c.dim}market intelligence${i.c.reset}`),console.log(` ${i.c.cyan}sf agent${i.c.reset} ${i.c.dim}<thesis>${i.c.reset} ${i.c.dim}start the agent${i.c.reset}`),console.log(` ${i.c.cyan}sf setup --check${i.c.reset} ${i.c.dim}verify config${i.c.reset}`),void console.log();if("expired"===n.status)return void console.error(`\n ${i.c.red}Session expired. Run ${i.c.cyan}sf login${i.c.red} again.${i.c.reset}\n`);process.stdout.write(".")}catch{process.stdout.write("x")}}console.error(`\n ${i.c.red}Timed out waiting for login. Run ${i.c.cyan}sf login${i.c.red} again.${i.c.reset}\n`)};const o=n(76982),s=n(11627),i=n(99236),r=process.env.SF_API_URL||"https://simplefunctions.dev"},23017:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.marketsCommand=async function(e){const t=await fetch(`${s}/api/public/markets`);if(!t.ok)return void console.error(` Error: ${t.status} ${await t.text()}`);const n=await t.json();if(e?.share)return void await(0,o.shareOutput)("markets","",n);if(e?.json)return void console.log(JSON.stringify(n,null,2));if(console.log(`\n Traditional Markets ${n.snapshotAt?.slice(0,10)||""}\n`),!n.markets?.length)return void console.log(" No data available.\n");for(const e of n.markets){const t=e.changePct>=0?"▲":"▼",n=e.changePct>=0?`+${e.changePct}%`:`${e.changePct}%`,o=`$${e.price.toFixed(2)}`;console.log(` ${t} ${e.symbol.padEnd(5)} ${o.padStart(10)} ${n.padStart(16)} ${e.name}`)}console.log()};const o=n(35178),s="https://simplefunctions.dev"},8045:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.milestonesCommand=async function(e){const t=parseInt(e.hours||"168"),n=new Date,r=new Date(n.getTime()+36e5*t),a=`${i}/milestones?limit=200&minimum_start_date=${n.toISOString()}`+(e.category?`&category=${e.category}`:""),c=await fetch(a,{headers:{Accept:"application/json"}});if(!c.ok)throw new Error(`Kalshi API ${c.status}`);let l=((await c.json()).milestones||[]).filter(e=>new Date(e.start_date).getTime()<=r.getTime());if(e.thesis){const t=new o.SFClient(e.apiKey,e.apiUrl),n=await t.getContext(e.thesis),s=new Set((n.edges||[]).map(e=>e.eventTicker).filter(Boolean)),i=new Set((n.edges||[]).map(e=>e.seriesTicker).filter(Boolean));l=l.filter(e=>(e.related_event_tickers||e.primary_event_tickers||[]).some(e=>s.has(e)||i.has(e.split("-")[0])))}if(e.json)return void console.log(JSON.stringify(l,null,2));if(0===l.length)return void console.log(`${s.c.dim}No milestones in the next ${t} hours.${s.c.reset}`);l.sort((e,t)=>new Date(e.start_date).getTime()-new Date(t.start_date).getTime()),console.log(`${s.c.bold}${s.c.cyan}Upcoming Milestones (next ${t}h)${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(80)}${s.c.reset}`);for(const e of l){const t=new Date(e.start_date),o=Math.round((t.getTime()-n.getTime())/36e5),i=o<=24?`${s.c.bold}${o}h${s.c.reset}`:`${s.c.dim}${Math.round(o/24)}d${s.c.reset}`,r=`${s.c.dim}[${e.category}]${s.c.reset}`,a=(e.related_event_tickers||[]).slice(0,3).join(", ");console.log(` ${i.padEnd(12)} ${r.padEnd(25)} ${e.title}`),a&&console.log(` ${" ".repeat(10)} ${s.c.dim}${a}${s.c.reset}`)}console.log(`\n${s.c.dim}${l.length} milestone(s)${s.c.reset}`)};const o=n(19218),s=n(99236),i="https://api.elections.kalshi.com/trade-api/v2"},45475:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ordersCommand=async function(e){const t=e.status||"resting",n=await(0,o.getOrders)({status:t,limit:100});if(!n)throw new Error("Kalshi not configured. Set KALSHI_API_KEY_ID + KALSHI_PRIVATE_KEY_PATH.");if(e.json)return void console.log(JSON.stringify(n.orders,null,2));if(0===n.orders.length)return void console.log(`${s.c.dim}No ${t} orders.${s.c.reset}`);console.log(`${s.c.bold}${s.c.cyan}Orders (${t})${s.c.reset}`),console.log(`${s.c.dim}${"─".repeat(80)}${s.c.reset}`);for(const e of n.orders){const t=e.yes_price_dollars?100*parseFloat(e.yes_price_dollars)+"¢":`${e.yes_price||"?"}¢`,n="yes"===e.side?`${s.c.green}YES${s.c.reset}`:`${s.c.red}NO${s.c.reset}`,o=e.remaining_count_fp||e.remaining_count||"?";console.log(` ${(e.ticker||"").padEnd(35)} ${n} ${t.padEnd(8)} qty ${o}`)}console.log(`\n${s.c.dim}${n.orders.length} order(s)${s.c.reset}`)};const o=n(96139),s=n(99236)},33766:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.performanceCommand=async function(e){if(!(0,s.isKalshiConfigured)())return void console.log(`${r.c.yellow}Kalshi not configured.${r.c.reset} Run ${r.c.cyan}sf setup --kalshi${r.c.reset} first.`);const t=await(0,s.getFills)({limit:500});if(!t||0===t.fills.length)return void console.log(`${r.c.dim}No fills found.${r.c.reset}`);const n=new Map;for(const e of t.fills){const t=e.ticker||e.market_ticker||"";if(!t)continue;const o=e.action||"buy",s=e.side||"yes",i=Math.round(parseFloat(e.count_fp||e.count||"0")),r=Math.round(100*parseFloat(e.yes_price_dollars||"0"));let a=i;"sell"===o&&(a=-a),"no"===s&&(a=-a);const c=n.get(t)||{ticker:t,netQty:0,totalCostCents:0,totalContracts:0,earliestFillTs:1/0};if(c.netQty+=a,a>0){const e="no"===s?100-r:r;c.totalCostCents+=e*i,c.totalContracts+=i}const l=e.created_time||e.ts||e.created_at;if(l){const e=Math.floor(new Date(l).getTime()/1e3);e<c.earliestFillTs&&(c.earliestFillTs=e)}n.set(t,c)}let u=[...n.values()].filter(e=>0!==e.netQty);if(e.ticker){const t=e.ticker.toLowerCase();u=u.filter(e=>e.ticker.toLowerCase().includes(t))}if(0===u.length)return void console.log(`${r.c.dim}No open positions found${e.ticker?` matching "${e.ticker}"`:""}.${r.c.reset}`);const p=e.since?Math.floor(new Date(e.since).getTime()/1e3):Math.min(...u.map(e=>e.earliestFillTs===1/0?Math.floor(Date.now()/1e3)-2592e3:e.earliestFillTs)),h=Math.floor(Date.now()/1e3),m=await(0,s.getBatchCandlesticks)({tickers:u.map(e=>e.ticker),startTs:p,endTs:h,periodInterval:1440}),g=new Map;for(const e of m){const t=[];for(const n of e.candlesticks||[]){const e=parseFloat(n.yes_bid?.close_dollars||"0"),o=parseFloat(n.yes_ask?.close_dollars||"0"),s=e>0&&o>0?(e+o)/2:e||o,i=parseFloat(n.price?.close_dollars||"0")||s,r=Math.round(100*i),a=n.end_period_ts||n.period_end_ts||n.ts;a&&t.push({date:l(new Date(1e3*a)),close:r})}t.sort((e,t)=>e.date.localeCompare(t.date)),g.set(e.market_ticker,t)}const f=new Set;for(const[,e]of g)for(const t of e)f.add(t.date);const y=[...f].sort(),$=new Map;for(const e of u)$.set(e.ticker,e.totalContracts>0?Math.round(e.totalCostCents/e.totalContracts):0);const w=[];try{const e=(0,i.loadConfig)(),t=new o.SFClient(e.apiKey,e.apiUrl),n=await t.getFeed(720),s=n?.feed||n?.items||n||[];if(Array.isArray(s))for(const e of s){const t=e.delta??e.confidenceDelta??0;if(Math.abs(t)>=.02){const n=e.evaluatedAt||e.createdAt||e.timestamp||"";n&&w.push({date:l(new Date(n)),direction:t>0?"up":"down",deltaPct:Math.round(100*t),summary:e.summary||""})}}}catch{}const k=[];for(const e of u){const t=$.get(e.ticker)||0,n=g.get(e.ticker)||[],o=n.length>0?n[n.length-1].close:t,s=(o-t)*e.netQty,i=t*e.netQty,r=0!==i?s/Math.abs(i)*100:0,a=n.map(n=>(n.close-t)*e.netQty);k.push({ticker:e.ticker,qty:e.netQty,entry:t,current:o,pnlCents:s,pnlPct:r,dailyPnl:a})}k.sort((e,t)=>Math.abs(t.pnlCents)-Math.abs(e.pnlCents));const b=y.map(e=>{let t=0;for(const n of u){const o=g.get(n.ticker)||[],s=$.get(n.ticker)||0,i=o.find(t=>t.date===e);i&&(t+=(i.close-s)*n.netQty)}return t}),v=u.reduce((e,t)=>e+t.totalCostCents,0),_=k.reduce((e,t)=>e+t.pnlCents,0),S=v>0?_/v*100:0;if(e.json)return void console.log(JSON.stringify({positions:k.map(e=>({ticker:e.ticker,qty:e.qty,entry:e.entry,current:e.current,pnl:e.pnlCents,pnlPct:Math.round(10*e.pnlPct)/10})),totalDailyPnl:y.map((e,t)=>({date:e,pnl:b[t]})),events:w,summary:{cost:v,pnl:_,pnlPct:Math.round(10*S)/10}},null,2));const x=y.length>0?a(new Date(y[0])):"?",C=a(new Date);console.log(),console.log(` ${r.c.bold}Portfolio Performance${r.c.reset} ${r.c.dim}(${x} → ${C})${r.c.reset}`),console.log(` ${r.c.dim}${"─".repeat(76)}${r.c.reset}`),console.log();const O=Math.max(...k.map(e=>e.ticker.length),5)+2,I=O+50,P=(e,t)=>e.padEnd(t);console.log(` ${r.c.dim}${P("Ticker",O)} Qty Entry Now P&L Trend${r.c.reset}`);for(const e of k){const t=c(e.pnlCents),n=e.pnlCents>0?r.c.green:e.pnlCents<0?r.c.red:r.c.dim,o=d(e.dailyPnl,e=>e>=0?r.c.green:r.c.red);console.log(` ${P(e.ticker,O)} ${(0,r.rpad)(String(e.qty),8)}${(0,r.rpad)(e.entry+"¢",7)}${(0,r.rpad)(e.current+"¢",7)}${n}${(0,r.rpad)(t,13)}${r.c.reset}`+o)}console.log(` ${r.c.dim}${"─".repeat(I)}${r.c.reset}`);const T=c(_),E=`${S>=0?"+":""}${S.toFixed(1)}%`,A=_>=0?r.c.green:r.c.red,M=d(b,e=>e>=0?r.c.green:r.c.red);if(console.log(` ${r.c.bold}${P("TOTAL",O)}${r.c.reset} ${(0,r.rpad)("",22)}${A}${r.c.bold}${(0,r.rpad)(`${T} (${E})`,13)}${r.c.reset}`+M),w.length>0){const e=new Set(y),t=w.filter(t=>e.has(t.date));if(t.length>0){console.log();for(const e of t.slice(0,8)){const t="up"===e.direction?`${r.c.green}▲${r.c.reset}`:`${r.c.red}▼${r.c.reset}`,n=e.summary.length>55?e.summary.slice(0,54)+"…":e.summary;console.log(` ${t} ${r.c.dim}${a(new Date(e.date))}${r.c.reset} ${e.deltaPct>0?"+":""}${e.deltaPct}% → ${n}`)}}}console.log();const R=`$${(v/100).toFixed(0)}`;console.log(` ${r.c.dim}Cost basis:${r.c.reset} ${R} ${r.c.dim}|${r.c.reset} ${A}${r.c.bold}${T} (${E})${r.c.reset}`),console.log()};const o=n(19218),s=n(96139),i=n(11627),r=n(99236);function a(e){return`${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][e.getMonth()]} ${String(e.getDate()).padStart(2,"0")}`}function c(e){const t=Math.abs(e/100),n=t>=1e3?`${(t/1e3).toFixed(1)}k`:t>=100?t.toFixed(0):t.toFixed(2);return e>=0?`+$${n}`:`-$${n}`}function l(e){return e.toISOString().slice(0,10)}function d(e,t){if(0===e.length)return"";const n=Math.min(...e),o=Math.max(...e)-n||1,s=["▁","▂","▃","▄","▅","▆","▇","█"];return e.map(e=>{const i=Math.round((e-n)/o*(s.length-1)),a=s[i];return t?t(e)+a+r.c.reset:a}).join("")}},8784:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.positionsCommand=async function(e){const t=new o.SFClient(e.apiKey,e.apiUrl);let n=null;(0,s.isKalshiConfigured)()&&(console.log(`${a.c.dim}Fetching Kalshi positions...${a.c.reset}`),n=await(0,s.getPositions)());const c=(0,r.loadConfig)();let l=[];if(c.polymarketWalletAddress){console.log(`${a.c.dim}Fetching Polymarket positions...${a.c.reset}`);try{l=await(0,i.polymarketGetPositions)(c.polymarketWalletAddress)}catch{}}console.log(`${a.c.dim}Fetching thesis edges...${a.c.reset}`);let d=[];try{d=(await t.listTheses()).theses||[]}catch(e){console.warn(`${a.c.yellow}Warning: Could not fetch theses: ${e}${a.c.reset}`)}let u=[];if(e.thesis)try{const n=await t.getContext(e.thesis);for(const e of n.edges||[])u.push({thesisId:n.thesisId,thesisTitle:n.thesis||n.title||"",edge:e})}catch(t){console.warn(`${a.c.yellow}Warning: Could not fetch context for ${e.thesis}: ${t}${a.c.reset}`)}else{const e=d.filter(e=>"monitoring"===e.status||"active"===e.status);for(const n of e.slice(0,5))try{const e=await t.getContext(n.id);for(const t of e.edges||[])u.push({thesisId:n.id,thesisTitle:e.thesis||e.title||n.title||"",edge:t})}catch{}}if(n&&n.length>0){console.log(`${a.c.dim}Fetching live prices for ${n.length} positions...${a.c.reset}`);for(const e of n)try{const t=await(0,s.getMarketPrice)(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=(t-e.average_price_paid)*e.quantity),await new Promise(e=>setTimeout(e,100))}catch{}}const p=new Map;for(const e of u){const t=e.edge.marketId;p.has(t)||p.set(t,[]),p.get(t).push(e)}if(e.json)return void console.log(JSON.stringify({kalshiConfigured:(0,s.isKalshiConfigured)(),polymarketConfigured:!!c.polymarketWalletAddress,positions:n||[],polymarketPositions:l,edges:u.map(e=>({...e.edge,thesisId:e.thesisId}))},null,2));if(n&&n.length>0){(0,a.header)("Your Positions (via Kalshi)"),console.log(" "+a.c.bold+(0,a.pad)("Ticker",25)+(0,a.rpad)("Side",5)+(0,a.rpad)("Qty",7)+(0,a.rpad)("Avg",6)+(0,a.rpad)("Now",6)+(0,a.rpad)("P&L",9)+(0,a.rpad)("Edge",7)+" Signal"+a.c.reset),console.log(" "+a.c.dim+"─".repeat(85)+a.c.reset);for(const e of n){const t=e.current_value||null,n=e.average_price_paid||0,o=e.unrealized_pnl||0,s=o>0?a.c.green:o<0?a.c.red:a.c.dim,i=o>=0?`+$${(o/100).toFixed(2)}`:`-$${(Math.abs(o)/100).toFixed(2)}`,r=(p.get(e.ticker)||[])[0],c=r?.edge?.edge??r?.edge?.edgeSize??0,l=Math.abs(c)>10?a.c.green:Math.abs(c)>5?a.c.yellow:a.c.dim;let d="HOLD";if(r){d=e.side===r.edge.direction&&c>3?"HOLD":c<-3?"CLOSE":"HOLD"}else d="—";const u="HOLD"===d?a.c.dim:"CLOSE"===d?a.c.red:a.c.yellow;console.log(" "+(0,a.pad)(e.ticker,25)+(0,a.rpad)(e.side.toUpperCase(),5)+(0,a.rpad)(String(e.quantity),7)+(0,a.rpad)(`${n}¢`,6)+(0,a.rpad)(t?`${t}¢`:"-",6)+`${s}${(0,a.rpad)(i,9)}${a.c.reset}`+`${l}${(0,a.rpad)(c?`${c>0?"+":""}${c.toFixed(0)}`:"-",7)}${a.c.reset}`+` ${u}${d}${a.c.reset}`)}console.log("")}else(0,s.isKalshiConfigured)()?console.log(`\n ${a.c.dim}No open Kalshi positions.${a.c.reset}\n`):console.log(`\n ${a.c.dim}Kalshi not configured. Run: ${a.c.cyan}sf setup --kalshi${a.c.reset}\n`);if(l.length>0){(0,a.header)("Polymarket Positions"),console.log(" "+a.c.bold+(0,a.pad)("Market",35)+(0,a.rpad)("Side",5)+(0,a.rpad)("Size",8)+(0,a.rpad)("Avg",6)+(0,a.rpad)("Now",6)+(0,a.rpad)("P&L",9)+a.c.reset),console.log(" "+a.c.dim+"─".repeat(75)+a.c.reset);for(const e of l){const t=(e.title||e.slug||e.asset||"").slice(0,34),n=e.outcome||"YES",o=e.size||0,s=Math.round(100*(e.avgPrice||0)),i=Math.round(100*(e.curPrice||e.currentPrice||0)),r=e.cashPnl||(i-s)*o/100,c=r>=0?a.c.green:a.c.red,l=r>=0?`+$${r.toFixed(2)}`:`-$${Math.abs(r).toFixed(2)}`;console.log(" "+(0,a.pad)(t,35)+(0,a.rpad)(n.toUpperCase(),5)+(0,a.rpad)(String(Math.round(o)),8)+(0,a.rpad)(`${s}¢`,6)+(0,a.rpad)(`${i}¢`,6)+`${c}${(0,a.rpad)(l,9)}${a.c.reset}`)}console.log("")}else c.polymarketWalletAddress&&console.log(`${a.c.dim}No open positions on Polymarket.${a.c.reset}\n`);const h=new Set((n||[]).map(e=>e.ticker)),m=u.filter(e=>!h.has(e.edge.marketId));if(m.length>0){m.sort((e,t)=>Math.abs(t.edge.edge??t.edge.edgeSize??0)-Math.abs(e.edge.edge??e.edge.edgeSize??0));const t=m.slice(0,10).filter(e=>"kalshi"===e.edge.venue&&!e.edge.orderbook&&Math.abs(e.edge.edge??e.edge.edgeSize??0)>5),n=new Map;if(t.length>0&&(0,s.isKalshiConfigured)()){console.log(`${a.c.dim}Fetching orderbooks for ${t.length} edges...${a.c.reset}`);for(const e of t)try{const t=await(0,s.getOrderbook)(e.edge.marketId);t&&n.set(e.edge.marketId,t),await new Promise(e=>setTimeout(e,150))}catch{}}const o=e.thesis?` (thesis ${(0,a.shortId)(e.thesis)})`:"";(0,a.header)(`Unpositioned Edges${o}`),console.log(" "+a.c.bold+(0,a.pad)("Market",30)+(0,a.rpad)("Mkt",6)+(0,a.rpad)("Thesis",8)+(0,a.rpad)("Edge",7)+(0,a.rpad)("Spread",8)+(0,a.rpad)("Liq",8)+" Signal"+a.c.reset),console.log(" "+a.c.dim+"─".repeat(85)+a.c.reset);for(const e of m.slice(0,20)){const t=e.edge,o=t.edge??t.edgeSize??0,s=o>10?a.c.green:o>5?a.c.yellow:o>0?a.c.dim:a.c.red,i=t.marketPrice??0,r=t.thesisPrice??t.thesisImpliedPrice??0,c=(t.market||t.marketTitle||t.marketId||"?").slice(0,29),l=t.orderbook,d=n.get(t.marketId),u=l||d,p=u?`${u.spread}¢`:"-",h=u?u.liquidityScore:"-",m="high"===u?.liquidityScore?a.c.green:"medium"===u?.liquidityScore?a.c.yellow:a.c.dim;let g="WATCH";(o>10&&"low"!==u?.liquidityScore||o>5&&"high"===u?.liquidityScore)&&(g="CONSIDER");const f="CONSIDER"===g?a.c.green:a.c.dim;console.log(" "+(0,a.pad)(c,30)+(0,a.rpad)(`${i.toFixed(0)}¢`,6)+(0,a.rpad)(`${r.toFixed(0)}¢`,8)+`${s}${(0,a.rpad)(`${o>0?"+":""}${o.toFixed(0)}`,7)}${a.c.reset}`+(0,a.rpad)(p,8)+`${m}${(0,a.rpad)(h,8)}${a.c.reset}`+` ${f}${g}${a.c.reset}`)}console.log("")}else 0===u.length&&console.log(`\n${a.c.dim}No thesis edges found.${a.c.reset}\n`)};const o=n(19218),s=n(96139),i=n(34331),r=n(11627),a=n(99236)},35344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.promptCommand=async function(e,t){const n=(t.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev").replace(/\/$/,""),o=t.apiKey||process.env.SF_API_KEY||"",s=new URLSearchParams;t.sections&&s.set("sections",t.sections);t.maxLength&&s.set("maxLength",t.maxLength);t.json&&s.set("format","json");const i=e?`/api/thesis/${e}/prompt`:"/api/prompt",r=s.toString()?`?${s.toString()}`:"",a=await fetch(`${n}${i}${r}`,{headers:{Authorization:`Bearer ${o}`}});if(!a.ok){const e=await a.text();throw new Error(`API error ${a.status}: ${e}`)}const c=await a.text();process.stdout.write(c),c.endsWith("\n")||process.stdout.write("\n")}},40791:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.publishCommand=async function(e,t){const n=function(e){return e.toLowerCase().trim().replace(/[^a-z0-9\s-]/g,"").replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,60)}(t.slug);n.length<3&&(console.error(`\n Error: slug too short after normalization: "${n}" (need 3+ chars)\n`),process.exit(1));n!==t.slug&&console.log(` Slug normalized: "${t.slug}" → "${n}"`);const s=new o.SFClient(t.apiKey,t.apiUrl);await s.publish(e,n,t.description),console.log(`\n ✓ Published: https://simplefunctions.dev/thesis/${n}\n`)},t.unpublishCommand=async function(e,t){const n=new o.SFClient(t.apiKey,t.apiUrl);await n.unpublish(e),console.log(`\n ✓ Unpublished thesis ${e}\n`)};const o=n(19218)},65240:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.queryCommand=async function(e,t){const n=t?.limit||"10",a=`${s}/api/public/query?q=${encodeURIComponent(e)}&limit=${n}`,c=await fetch(a);if(!c.ok){const e=await c.text();return void(429===c.status?console.error(" Rate limited. Wait a minute and try again."):console.error(` Error: ${c.status} ${e}`))}const l=await c.json();if(t?.share)return void await(0,o.shareOutput)("query",e,l);if(t?.json)return void console.log(JSON.stringify(l,null,2));console.log(),console.log(` ${l.query}`),console.log(),l.answer&&(console.log(` ${l.answer}`),console.log());if(l.keyFactors?.length>0){console.log(" Key factors:");for(const e of l.keyFactors)console.log(` • ${e}`);console.log()}const d=l.kalshi||[],u=l.polymarket||[];if(d.length>0||u.length>0){console.log(" Markets");for(const e of d.slice(0,8)){const t=i(e.volume),n=e.ticker?` ${e.ticker}`:"";console.log(` K ${String(e.price).padStart(3)}¢ vol ${t.padStart(6)} ${e.title.slice(0,55)}${n}`)}d.length>0&&u.length>0&&console.log();for(const e of u.slice(0,8)){const t=i(e.volume),n=e.slug?` ${e.slug}`:"";console.log(` P ${String(e.price).padStart(3)}¢ vol ${t.padStart(6)} ${e.title.slice(0,55)}${n}`)}console.log()}const p=l.x||[];if(p.length>0){console.log(" X signals");for(const e of p.slice(0,5)){const t=`${r(e.likes)}♥ ${r(e.retweets)}⟲`;console.log(` @${e.author} ${t} ${e.text.slice(0,80)}`)}console.log()}const h=l.traditional||[];if(h.length>0){console.log(" Traditional");for(const e of h){const t=e.change1d>=0?"+":"";console.log(` ${e.symbol.padEnd(5)} $${e.price} ${t}${e.change1d} (${t}${e.changePct}%) ${e.name}`)}console.log()}if(l.theses?.length>0){console.log(" Theses");for(const e of l.theses.slice(0,3))console.log(` ${e.confidence||"?"}% ${String(e.edges||0).padStart(2)} edges ${e.title.slice(0,50)}`);console.log()}if(l.content?.length>0){console.log(" Content");for(const e of l.content.slice(0,5)){const t=e.type.padEnd(9);console.log(` ${t} ${e.title.slice(0,50)} ${e.url}`)}console.log()}const m=l.meta||{},g=m.sources||l.sources||[],f=m.latencyMs?`${(m.latencyMs/1e3).toFixed(1)}s`:"";console.log(` Sources: ${g.join(", ")}${f?` (${f})`:""}`),console.log()};const o=n(35178),s=process.env.SF_API_URL||"https://simplefunctions.dev";function i(e){return e>1e6?`${(e/1e6).toFixed(1)}M`:e>1e3?`${(e/1e3).toFixed(0)}K`:String(Math.round(e))}function r(e){return e>1e6?`${(e/1e6).toFixed(1)}M`:e>1e3?`${(e/1e3).toFixed(1)}K`:String(e)}},43423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.rfqCommand=async function(e,t,n){(0,s.requireTrading)();const r=parseInt(t);if(isNaN(r)||r<=0)throw new Error("Quantity must be a positive integer");console.log(),console.log(` ${i.c.bold}${i.c.cyan}Request for Quote${i.c.reset}`),console.log(` ${i.c.dim}${"─".repeat(30)}${i.c.reset}`),console.log(` Market: ${e}`),console.log(` Contracts: ${r}`),n.targetCost&&console.log(` Target cost: ${n.targetCost}¢/contract`);console.log(" Rest remainder: "+(n.restRemainder?"yes":"no")),console.log();try{const t=await(0,o.createRFQ)({market_ticker:e,contracts:r,rest_remainder:n.restRemainder||!1,...n.targetCost?{target_cost_centi_cents:100*parseInt(n.targetCost)}:{}});console.log(` ${i.c.green}✓${i.c.reset} RFQ created: ${t.id||t.rfq_id||"OK"}`),console.log()}catch(e){console.error(`\n ${i.c.red}✗${i.c.reset} ${e.message}\n`),process.exit(1)}};const o=n(96139),s=n(11627),i=n(99236)},52072:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.registerRuntime=function(e){const t=e.command("runtime").description("Execution runtime daemon");t.command("start").option("--daemon","Run as background process").description("Start the execution runtime").action(async e=>{if((0,s.isKalshiConfigured)()||(console.error(`\n ${i.c.red}Error:${i.c.reset} Kalshi credentials not configured.`),console.error(" Run: sf setup --enable-trading\n"),process.exit(1)),(0,r.existsSync)(l)){const e=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(e),0),console.error(`\n ${i.c.yellow}Warning:${i.c.reset} Runtime already running (PID ${e}).`),console.error(" Stop it first: sf runtime stop\n"),process.exit(1)}catch{(0,r.unlinkSync)(l)}}e.daemon&&(console.error(`\n ${i.c.dim}Daemon mode not yet implemented. Run in foreground for now.${i.c.reset}\n`),process.exit(1)),await async function(){const e=(0,a.join)((0,c.homedir)(),".sf");(0,r.existsSync)(e)||(0,r.mkdirSync)(e,{recursive:!0});(0,r.writeFileSync)(l,process.pid.toString()),console.log(),console.log(` ${i.c.bold}SimpleFunctions Runtime${i.c.reset}`),console.log(` ${i.c.dim}PID ${process.pid} · polling every ${d/1e3}s · Ctrl+C to stop${i.c.reset}`),console.log();const t=new o.SFClient;let n=0;const s=()=>{console.log(`\n ${i.c.dim}Runtime stopping...${i.c.reset}`);try{(0,r.unlinkSync)(l)}catch{}process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s);for(;;){n++;Date.now();try{const{intents:e}=await t.listIntents({active:!0});if(!e||0===e.length){n%10==1&&m("No active intents. Waiting..."),await g(d);continue}for(const n of e)await p(t,n)}catch(e){m(`Error in cycle: ${e.message}`)}await g(d)}}()}),t.command("stop").description("Stop the runtime daemon").action(async()=>{if(!(0,r.existsSync)(l))return void console.log(`\n ${i.c.dim}No runtime running.${i.c.reset}\n`);const e=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(e),"SIGTERM"),(0,r.unlinkSync)(l),console.log(`\n ${i.c.green}OK${i.c.reset} Runtime stopped (PID ${e}).\n`)}catch{(0,r.unlinkSync)(l),console.log(`\n ${i.c.dim}Runtime was not running (stale PID file removed).${i.c.reset}\n`)}}),t.command("status").option("--json","JSON output").description("Show runtime status and active intents").action(async e=>{try{let t=!1,n="";if((0,r.existsSync)(l)){n=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(n),0),t=!0}catch{t=!1}}const s=new o.SFClient,{intents:a}=await s.listIntents({active:!0});if(e.json)return void console.log(JSON.stringify({running:t,pid:t?n:null,intents:a},null,2));if(console.log(),console.log(` ${i.c.bold}Runtime${i.c.reset} ${t?`${i.c.green}RUNNING${i.c.reset} (PID ${n})`:`${i.c.dim}STOPPED${i.c.reset}`}`),console.log(),!a||0===a.length)return console.log(` ${i.c.dim}No active intents.${i.c.reset}`),console.log(" Create one: sf intent buy TICKER QTY --price CENTS"),void console.log();const c={};for(const e of a)c[e.status]=(c[e.status]||0)+1;const d=Object.entries(c).map(([e,t])=>`${t} ${e}`).join(", ");console.log(` Active intents: ${d}`),console.log();for(const e of a){const t=e.action.toUpperCase(),n=e.direction.toUpperCase(),o=e.maxPrice?`@ ≤${e.maxPrice}c`:"@ market",s=e.targetQuantity>0?` (${Math.round(e.filledQuantity/e.targetQuantity*100)}%)`:"";if(console.log(` [${e.status}] ${t} ${e.marketId} ${n} ${e.targetQuantity}${o} filled ${e.filledQuantity}/${e.targetQuantity}${s}`),"immediate"!==e.triggerType){const t="price_below"===e.triggerType?`price ≤ ${e.triggerPrice}c`:"price_above"===e.triggerType?`price ≥ ${e.triggerPrice}c`:e.triggerType;console.log(` trigger: ${t}`)}}console.log(),t||(console.log(` ${i.c.dim}Start runtime to execute: sf runtime start${i.c.reset}`),console.log())}catch(e){console.error(`${i.c.red}Error:${i.c.reset} ${e.message}`),process.exit(1)}})};const o=n(19218),s=n(96139),i=n(99236),r=n(79896),a=n(16928),c=n(70857),l=(0,a.join)((0,c.homedir)(),".sf","runtime.pid"),d=((0,a.join)((0,c.homedir)(),".sf","runtime.log"),3e4),u=new Set;async function p(e,t){if(!(t.activateAt&&new Date(t.activateAt)>new Date))if(new Date(t.expireAt)<new Date){m(`Intent ${t.id.slice(0,8)} expired`);try{await e.cancelIntentAPI(t.id)}catch{}}else{if("pending"===t.status&&m(`Arming intent ${t.id.slice(0,8)}: ${t.action.toUpperCase()} ${t.marketId} ${t.direction.toUpperCase()} x${t.targetQuantity}`),"pending"===t.status||"armed"===t.status){const n=await async function(e){switch(e.triggerType){case"immediate":return!0;case"price_below":{if(!e.triggerPrice)return!1;const t=await(0,s.getMarketPrice)(e.marketId);return null!==t&&t<=e.triggerPrice}case"price_above":{if(!e.triggerPrice)return!1;const t=await(0,s.getMarketPrice)(e.marketId);return null!==t&&t>=e.triggerPrice}case"time":return!!e.triggerAt&&new Date>=new Date(e.triggerAt);default:return!1}}(t);if(!n)return;m(`TRIGGERED: ${t.id.slice(0,8)} ${t.marketId} (${t.triggerType})`),t.autoExecute?await h(e,t):m(` Awaiting confirmation. Use: sf intent status ${t.id.slice(0,8)}`)}"triggered"===t.status&&t.autoExecute&&await h(e,t)}}async function h(e,t){if(u.has(t.id))return;if("kalshi"!==t.venue)return void m(` Skipping ${t.id.slice(0,8)}: ${t.venue} execution not yet supported`);const n=t.targetQuantity-t.filledQuantity;if(n<=0)u.add(t.id);else{u.add(t.id),m(` Executing: ${t.action.toUpperCase()} ${t.marketId} ${t.direction.toUpperCase()} x${n}${t.maxPrice?` @ ≤${t.maxPrice}c`:""}`);try{const o=await(0,s.createOrder)({ticker:t.marketId,side:t.direction,action:t.action,type:t.maxPrice?"limit":"market",count:n,...t.maxPrice?{yes_price:t.maxPrice}:{}}),l=o.order||o,d=l.fill_count||l.fill_count_fp||n,u=l.yes_price||l.no_price||t.maxPrice||0;m(` ${i.c.green}FILLED${i.c.reset}: ${d} contracts, order ${l.order_id||"OK"}`);try{const e=JSON.stringify({ts:(new Date).toISOString(),intentId:t.id,action:t.action,ticker:t.marketId,side:t.direction,quantity:d,price:t.maxPrice,orderId:l.order_id,source:t.source})+"\n";(0,r.appendFileSync)((0,a.join)((0,c.homedir)(),".sf","trade-journal.jsonl"),e)}catch{}try{await e.request("PATCH",`/api/intents/${t.id}`,{fill:{orderId:l.order_id||null,fillQuantity:d,fillPrice:u,fillCostCents:Math.round(u*d),venueResponse:{order_id:l.order_id,status:l.status}}}),m(` ${i.c.dim}Fill recorded to API${i.c.reset}`)}catch(e){m(` ${i.c.yellow}Warning:${i.c.reset} Failed to record fill to API: ${e.message}. Intent may re-execute on restart.`)}}catch(e){u.delete(t.id);const n=e.message||String(e);n.includes("403")?(m(` ${i.c.red}FAILED${i.c.reset}: 403 Forbidden — Kalshi key lacks write permission`),u.add(t.id)):m(` ${i.c.red}FAILED${i.c.reset}: ${n}`)}}}function m(e){const t=(new Date).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});console.log(` ${i.c.dim}${t}${i.c.reset} ${e}`)}function g(e){return new Promise(t=>setTimeout(t,e))}},46183:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scanCommand=async function(e,t){if(t.market)return void await async function(e,t){console.log(`${i.c.dim}Fetching market ${e}...${i.c.reset}`);const n=await(0,o.kalshiFetchMarket)(e);if(t)return void console.log(JSON.stringify(n,null,2));(0,i.header)(`${n.title||n.ticker}`),n.subtitle&&console.log(`${i.c.dim}${n.subtitle}${i.c.reset}`);console.log(`Event: ${n.event_ticker} Status: ${n.status}`),console.log(""),console.log(`Yes Ask: ${(0,i.cents)(n.yes_ask_dollars)} (size: ${n.yes_ask_size_fp||"-"})`),console.log(`Yes Bid: ${(0,i.cents)(n.yes_bid_dollars)} (size: ${n.yes_bid_size_fp||"-"})`),console.log(`No Ask: ${(0,i.cents)(n.no_ask_dollars)}`),console.log(`No Bid: ${(0,i.cents)(n.no_bid_dollars)}`),console.log(`Last: ${(0,i.cents)(n.last_price_dollars)}`),console.log(""),console.log(`Volume: ${(0,i.vol)(n.volume_fp)}`),console.log(`Vol 24h: ${(0,i.vol)(n.volume_24h_fp)}`),console.log(`Open Int: ${(0,i.vol)(n.open_interest_fp)}`),console.log(`Liquidity: ${(0,i.vol)(n.liquidity_dollars)}`),console.log(""),console.log(`Open: ${n.open_time}`),console.log(`Close: ${n.close_time}`),n.rules_primary&&console.log(`\nRules: ${n.rules_primary.slice(0,300)}`)}(t.market.toUpperCase(),t.json);if(t.series)return void await async function(e,t){console.log(`${i.c.dim}Fetching events for series ${e}...${i.c.reset}`);let n=await(0,o.kalshiFetchEvents)(e);if(0===n.length){const n=await(0,o.kalshiFetchMarketsBySeries)(e);return t?void console.log(JSON.stringify(n,null,2)):0===n.length?void console.log(`${i.c.dim}No open markets found for series ${e}.${i.c.reset}`):((0,i.header)(`${e} — ${n.length} markets`),void c(n))}if(t)return void console.log(JSON.stringify(n,null,2));for(const e of n){(0,i.header)(`${e.title||e.event_ticker}`),console.log(`${i.c.dim}${e.event_ticker} | ${e.category||"-"} | strike: ${e.strike_date||"-"}${i.c.reset}`);c(e.markets&&e.markets.length>0?e.markets:await(0,o.kalshiFetchMarketsByEvent)(e.event_ticker))}}(t.series.toUpperCase(),t.json);await async function(e,t,n="all",o){const c="kalshi"===n?Promise.resolve([]):(0,s.polymarketSearch)(e,10).catch(()=>[]);"polymarket"!==n&&console.log(`${i.c.dim}Scanning Kalshi for: "${e}"...${i.c.reset}`);"kalshi"!==n&&console.log(`${i.c.dim}Scanning Polymarket for: "${e}"...${i.c.reset}`);const l=[];if("polymarket"!==n)try{const t=`${a}/api/public/scan?q=${encodeURIComponent(e)}&limit=30`,n=await fetch(t);if(!n.ok)throw new Error(`Proxy ${n.status}`);const o=await n.json(),s=o.matchedSeries||[],r=o.markets||[];console.log(`\n${i.c.bold}Matched ${s.length} series via proxy:${i.c.reset}\n`);for(const e of s.slice(0,15))console.log(` ${(0,i.pad)(e.ticker,25)} score=${e.score} ${e.title||""}`);for(const e of r)l.push({venue:"kalshi",seriesTicker:e.series_ticker,ticker:e.ticker,title:e.title||e.exchange_title||"",yesAsk:parseFloat(e.yes_ask_dollars||"0"),lastPrice:parseFloat(e.last_price_dollars||"0"),volume24h:parseFloat(e.volume_24h_fp||"0"),liquidity:parseFloat(e.open_interest_fp||e.liquidity_dollars||"0")})}catch(e){console.warn(`${i.c.dim}Kalshi scan failed: ${e}${i.c.reset}`)}l.sort((e,t)=>t.liquidity-e.liquidity);const d=await c,u=[];for(const e of d)for(const t of e.markets||[]){if(!t.active||t.closed)continue;const n=(0,s.parseOutcomePrices)(t.outcomePrices)[0]||0;u.push({venue:"polymarket",ticker:t.conditionId?.slice(0,16)||t.id,title:t.groupItemTitle?`${e.title}: ${t.groupItemTitle}`:t.question||e.title,yesAsk:n,lastPrice:t.lastTradePrice||n,volume24h:t.volume24hr||0,liquidity:t.liquidityNum||0})}for(const e of l)e.venue||(e.venue="kalshi");const p=[...l,...u];if(p.sort((e,t)=>t.liquidity-e.liquidity),o)return void await(0,r.shareOutput)("scan",e,p);if(t)return void console.log(JSON.stringify(p,null,2));(0,i.header)(`${p.length} Live Markets (${l.length} Kalshi + ${u.length} Polymarket)`),console.log(i.c.bold+(0,i.pad)("",5)+(0,i.pad)("Ticker",30)+(0,i.rpad)("Yes",6)+(0,i.rpad)("Last",6)+(0,i.rpad)("Vol24h",10)+(0,i.rpad)("Liq",10)+" Title"+i.c.reset),(0,i.hr)(120);for(const e of p.slice(0,60)){const t="polymarket"===e.venue?"POLY ":"KLSH ",n="polymarket"===e.venue?i.c.blue+t+i.c.reset:i.c.cyan+t+i.c.reset,o=(e.venue,(e.ticker||"").slice(0,28));console.log(n+(0,i.pad)(o,30)+(0,i.rpad)(`${Math.round(100*e.yesAsk)}¢`,6)+(0,i.rpad)(`${Math.round(100*e.lastPrice)}¢`,6)+(0,i.rpad)((0,i.vol)(Math.round(e.volume24h)),10)+(0,i.rpad)((0,i.vol)(Math.round(e.liquidity)),10)+` ${(e.title||"").slice(0,55)}`)}console.log(""),t||(console.log(`${i.c.dim}Want 24/7 monitoring + edge detection? ${i.c.reset}${i.c.cyan}sf create${i.c.reset}${i.c.dim} "${e.slice(0,50)}"${i.c.reset}`),console.log(""))}(e,t.json,t.venue||"all",t.share)};const o=n(19218),s=n(34331),i=n(99236),r=n(35178),a=process.env.SF_API_URL||"https://simplefunctions.dev";function c(e){if(0!==e.length){e.sort((e,t)=>{const n=parseFloat(e.yes_ask_dollars||e.last_price_dollars||"0");return parseFloat(t.yes_ask_dollars||t.last_price_dollars||"0")-n}),console.log(" "+i.c.bold+(0,i.pad)("Ticker",35)+(0,i.rpad)("YesAsk",8)+(0,i.rpad)("Last",8)+(0,i.rpad)("Vol24h",10)+(0,i.rpad)("Liq",12)+" Title"+i.c.reset),console.log(" "+i.c.dim+"─".repeat(100)+i.c.reset);for(const t of e)console.log(" "+(0,i.pad)(t.ticker||"",35)+(0,i.rpad)((0,i.cents)(t.yes_ask_dollars),8)+(0,i.rpad)((0,i.cents)(t.last_price_dollars),8)+(0,i.rpad)((0,i.vol)(t.volume_24h_fp),10)+(0,i.rpad)((0,i.vol)(t.liquidity_dollars),12)+` ${(t.title||t.subtitle||"").slice(0,55)}`);console.log("")}else console.log(` ${i.c.dim}(no markets)${i.c.reset}`)}},58211:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleCommand=async function(e){const t=await fetch(`${s}/exchange/status`,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Exchange API ${t.status}`);const n=await t.json();let i=null;try{const e=await fetch(`${s}/exchange/schedule`,{headers:{Accept:"application/json"}});e.ok&&(i=await e.json())}catch{}if(e.json)return void console.log(JSON.stringify({status:n,schedule:i},null,2));const r=n.exchange_active?`${o.c.green}OPEN${o.c.reset}`:`${o.c.red}CLOSED${o.c.reset}`;console.log(),console.log(` ${o.c.bold}${o.c.cyan}Exchange Status${o.c.reset}`),console.log(` ${o.c.dim}${"─".repeat(30)}${o.c.reset}`),console.log(` Trading: ${r}`),void 0!==n.trading_active&&console.log(" Trading Active: "+(n.trading_active?"yes":"no"));i?.schedule&&console.log(` Schedule: ${JSON.stringify(i.schedule).slice(0,100)}`);console.log()};const o=n(99236),s="https://api.elections.kalshi.com/trade-api/v2"},96616:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.settlementsCommand=async function(e){const t=[];let n="";do{const e=await(0,o.getSettlements)({limit:200,cursor:n||void 0});if(!e)throw new Error("Kalshi not configured. Set KALSHI_API_KEY_ID + KALSHI_PRIVATE_KEY_PATH.");t.push(...e.settlements),n=e.cursor}while(n);let r=t;if(e.thesis){const n=new s.SFClient(e.apiKey,e.apiUrl),o=await n.getContext(e.thesis),i=new Set((o.edges||[]).map(e=>e.marketId));r=t.filter(e=>i.has(e.ticker))}if(e.json)return void console.log(JSON.stringify(r,null,2));if(0===r.length)return void console.log(`${i.c.dim}No settlements found.${i.c.reset}`);console.log(`${i.c.bold}${i.c.cyan}Settlements${i.c.reset}`),console.log(`${i.c.dim}${"─".repeat(80)}${i.c.reset}`),console.log(`${i.c.bold}${"Ticker".padEnd(35)} ${"Result".padEnd(8)} ${"Revenue".padEnd(10)} ${"Cost".padEnd(10)} P&L${i.c.reset}`);let a=0;for(const e of r.slice(0,50)){const t=parseFloat(e.revenue||e.revenue_dollars||"0"),n=parseFloat(e.yes_total_cost||e.yes_total_cost_dollars||"0")+parseFloat(e.no_total_cost||e.no_total_cost_dollars||"0"),o=t-n;a+=o;const s=o>=0?`${i.c.green}+$${o.toFixed(2)}${i.c.reset}`:`${i.c.red}-$${Math.abs(o).toFixed(2)}${i.c.reset}`,r=e.market_result||"-";console.log(` ${(e.ticker||"").slice(0,33).padEnd(35)} ${r.padEnd(8)} $${t.toFixed(2).padEnd(9)} $${n.toFixed(2).padEnd(9)} ${s}`)}console.log(`${i.c.dim}${"─".repeat(80)}${i.c.reset}`);const c=a>=0?`${i.c.green}+$${a.toFixed(2)}${i.c.reset}`:`${i.c.red}-$${Math.abs(a).toFixed(2)}${i.c.reset}`;console.log(` Total: ${c} (${r.length} settlements)`)};const o=n(96139),s=n(19218),i=n(99236)},85417:function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.setupCommand=async function(e){if(e.check)return async function(){const e=(0,r.loadConfig)();$(),console.log(` ${h("SimpleFunctions Config Status")}`),console.log(` ${p("─".repeat(35))}`),$(),e.apiKey?g(`SF_API_KEY ${p(v(e.apiKey))}`):f("SF_API_KEY not configured (required)");e.openrouterKey?g(`OPENROUTER ${p(v(e.openrouterKey))} (direct)`):e.apiKey?g(`OPENROUTER ${p("proxied via SimpleFunctions")}`):f("OPENROUTER not configured (run sf login or set key)");e.kalshiKeyId&&e.kalshiPrivateKeyPath?g(`KALSHI ${p(v(e.kalshiKeyId))}`):y(`${p("○")} KALSHI ${p("skipped")}`);e.polymarketWalletAddress?g(`POLYMARKET ${p(v(e.polymarketWalletAddress))}`):y(`${p("○")} POLYMARKET ${p("skipped")}`);e.tavilyKey?g(`TAVILY ${p(v(e.tavilyKey))} (direct)`):e.apiKey?g(`TAVILY ${p("proxied via SimpleFunctions")}`):y(`${p("○")} TAVILY ${p("skipped")}`);e.tradingEnabled?g("TRADING enabled"):y(`${p("○")} TRADING ${p("disabled — sf setup --enable-trading")}`);$(),console.log(` ${p("Config file: "+(0,r.getConfigPath)())}`),$()}();if(e.reset)return(0,r.resetConfig)(),g("Config reset"),$(),y("Run sf setup to reconfigure"),void $();if(e.key){const t=process.env.SF_API_URL||"https://simplefunctions.dev",n=await _(e.key,t);n.valid||(f(n.msg),process.exit(1));const o=(0,r.loadFileConfig)();return(0,r.saveConfig)({...o,apiKey:e.key,apiUrl:t}),g(n.msg),void g(`Saved to ${(0,r.getConfigPath)()}`)}if(e.kalshi){const e=(0,r.loadFileConfig)();return $(),console.log(` ${h("Reconfigure Kalshi Credentials")}`),$(),y("Go to https://kalshi.com/account/api-keys to generate a new API key."),y("If you need trading, make sure to enable read+write permissions."),$(),await P(e),(0,r.saveConfig)(e),e.kalshiKeyId&&(process.env.KALSHI_API_KEY_ID=e.kalshiKeyId,process.env.KALSHI_PRIVATE_KEY_PATH=e.kalshiPrivateKeyPath),void $()}if(e.polymarket){const e=(0,r.loadFileConfig)();return $(),console.log(` ${h("Reconfigure Polymarket Credentials")}`),$(),await E(e),(0,r.saveConfig)(e),void $()}if(e.enableTrading){const e=(0,r.loadFileConfig)();return(0,r.saveConfig)({...e,tradingEnabled:!0}),g("Trading enabled. sf buy / sf sell / sf cancel now available."),void $()}if(e.disableTrading){const e=(0,r.loadFileConfig)();return(0,r.saveConfig)({...e,tradingEnabled:!1}),g("Trading disabled."),void $()}return async function(){$(),console.log(` ${h("SimpleFunctions Setup")}`),console.log(` ${p("─".repeat(25))}`),$();const e=(0,r.loadFileConfig)(),t=e.apiUrl||"https://simplefunctions.dev";console.log(` ${h("Step 1: API Key")}`),$();const n=process.env.SF_API_KEY||e.apiKey;if(n){const o=await _(n,t);o.valid?(g(`Detected SF_API_KEY — ${p(v(n))}`),y(p("Skipping.")),e.apiKey=n,$()):(f(`Existing key invalid: ${o.msg}`),e.apiKey=await O(t))}else e.apiKey=await O(t);e.apiUrl=t,(0,r.saveConfig)(e),process.env.SF_API_KEY=e.apiKey,console.log(` ${h("Step 2: AI Model (for sf agent)")}`),$();const o=process.env.OPENROUTER_API_KEY||e.openrouterKey;if(o){const t=await S(o);t.valid?(g(`Detected OPENROUTER_API_KEY — ${p(v(o))}`),y(p("Skipping.")),e.openrouterKey=o,$()):(f(`Existing key invalid: ${t.msg}`),e.openrouterKey=await I())}else e.openrouterKey=await I();(0,r.saveConfig)(e),e.openrouterKey&&(process.env.OPENROUTER_API_KEY=e.openrouterKey);console.log(` ${h("Step 3: Kalshi Exchange (optional)")}`),$();const s=process.env.KALSHI_API_KEY_ID||e.kalshiKeyId,i=process.env.KALSHI_PRIVATE_KEY_PATH||e.kalshiPrivateKeyPath;if(s&&i){process.env.KALSHI_API_KEY_ID=s,process.env.KALSHI_PRIVATE_KEY_PATH=i;const t=await x();t.valid?(g(`Detected Kalshi — ${p(v(s))} (${t.posCount} position(s))`),y(p("Skipping.")),e.kalshiKeyId=s,e.kalshiPrivateKeyPath=i,$()):(f(`Existing credentials invalid: ${t.msg}`),await P(e))}else await P(e);(0,r.saveConfig)(e),console.log(` ${h("Step 4: Polymarket (optional)")}`),$();const a=process.env.POLYMARKET_WALLET_ADDRESS||e.polymarketWalletAddress;a?(g(`Detected wallet — ${p(v(a))}`),y(p("Skipping.")),e.polymarketWalletAddress=a,$()):await E(e);(0,r.saveConfig)(e),e.polymarketWalletAddress&&(process.env.POLYMARKET_WALLET_ADDRESS=e.polymarketWalletAddress);console.log(` ${h("Step 5: News Search (optional)")}`),$();const c=process.env.TAVILY_API_KEY||e.tavilyKey;if(c){const t=await C(c);t.valid?(g(`Detected TAVILY_API_KEY — ${p(v(c))}`),y(p("Skipping.")),e.tavilyKey=c,$()):(f(`Existing key invalid: ${t.msg}`),e.tavilyKey=await T())}else e.tavilyKey=await T();(0,r.saveConfig)(e),e.tavilyKey&&(process.env.TAVILY_API_KEY=e.tavilyKey);if(e.kalshiKeyId){console.log(` ${h("Step 6: Trading (optional)")}`),$(),y("Warning: enabling this unlocks sf buy / sf sell / sf cancel."),y("Your Kalshi API key must have read+write permissions."),$();const t=await k(" Enable trading? (y/N) ",!1);e.tradingEnabled=t,t?g("Trading enabled"):y(p("Skipped. You can enable later with sf setup --enable-trading.")),$(),(0,r.saveConfig)(e)}console.log(` ${p("─".repeat(25))}`),y(`Config saved to ${p((0,r.getConfigPath)())}`),$(),e.apiKey?g("SF_API_KEY configured"):f("SF_API_KEY not configured");e.openrouterKey?g("OPENROUTER_KEY configured"):f("OPENROUTER_KEY skipped");e.kalshiKeyId?g("KALSHI configured"):y(`${p("○")} KALSHI skipped`);e.tavilyKey?g("TAVILY configured"):y(`${p("○")} TAVILY skipped`);$(),e.apiKey&&await A(e)}()};const s=o(n(23785)),i=n(35317),r=n(11627),a=n(19218),c=n(96139),l=n(83969),d=e=>`${e}`,u=e=>`${e}`,p=e=>`${e}`,h=e=>`${e}`,m=e=>`${e}`;function g(e){console.log(` ${d("✓")} ${e}`)}function f(e){console.log(` ${u("✗")} ${e}`)}function y(e){console.log(` ${e}`)}function $(){console.log()}function w(e){const t=s.default.createInterface({input:process.stdin,output:process.stdout,terminal:!0});return new Promise(n=>{t.question(e,e=>{t.close(),n(e.trim())})})}function k(e,t=!0){return w(e).then(e=>e?e.toLowerCase().startsWith("y"):t)}function b(e){const t="darwin"===process.platform?"open":"win32"===process.platform?"start":"xdg-open";(0,i.exec)(`${t} ${e}`)}function v(e){return!e||e.length<=12?e:e.slice(0,8)+"..."+e.slice(-4)}async function _(e,t){try{const n=await fetch(`${t}/api/thesis`,{headers:{Authorization:`Bearer ${e}`}});return n.ok?{valid:!0,msg:`API key valid — connected to ${t.replace("https://","")}`}:401===n.status?{valid:!1,msg:"Invalid key, please try again"}:{valid:!1,msg:`Server returned ${n.status}`}}catch(e){return{valid:!1,msg:`Connection failed: ${e.message}`}}}async function S(e){try{const t=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${e}`}});return t.ok?{valid:!0,msg:"OpenRouter connected — available model: claude-sonnet-4.6"}:{valid:!1,msg:`OpenRouter returned ${t.status}`}}catch(e){return{valid:!1,msg:`Connection failed: ${e.message}`}}}async function x(){try{const e=await(0,c.getPositions)();return null===e?{valid:!1,msg:"Kalshi authentication failed",posCount:0}:{valid:!0,msg:`Kalshi authenticated — found ${e.length} position(s)`,posCount:e.length}}catch(e){return{valid:!1,msg:`Kalshi connection failed: ${e.message}`,posCount:0}}}async function C(e){try{const t=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:e,query:"test",max_results:1})});return t.ok?{valid:!0,msg:"Tavily connected"}:{valid:!1,msg:`Tavily returned ${t.status}`}}catch(e){return{valid:!1,msg:`Connection failed: ${e.message}`}}}async function O(e){for(y(`Don't have a key? Sign up at ${m("https://simplefunctions.dev/dashboard")}.`),y("Press Enter to open browser, or paste your key:"),$();;){const t=await w(" > ");if(!t){b("https://simplefunctions.dev/dashboard"),y(p("Browser opened. Paste your key here once you have it:"));continue}y(p("Validating..."));const n=await _(t,e);if(n.valid)return g(n.msg),$(),t;f(n.msg)}}async function I(){y(`Requires an OpenRouter API key. Get one at ${m("https://openrouter.ai/settings/keys")}.`),y("Press Enter to skip (agent unavailable), or paste key:"),$();const e=await w(" > ");if(!e)return y(p("Skipped.")),void $();y(p("Validating..."));const t=await S(e);return t.valid?g(t.msg):(f(t.msg),y(p("Saved. You can re-run sf setup later to fix this."))),$(),e}async function P(e){y("Connect Kalshi to view your positions and P&L."),y("Requires an API Key ID and private key file."),y(`Get them at ${m("https://kalshi.com/account/api-keys")}.`),y("Press Enter to skip, or paste Key ID:"),$();const t=await w(" > ");if(!t)return y(p("Skipped.")),void $();y("Private key file path (default ~/.kalshi/private.pem):");const n=await w(" > ")||"~/.kalshi/private.pem";e.kalshiKeyId=t,e.kalshiPrivateKeyPath=n,process.env.KALSHI_API_KEY_ID=t,process.env.KALSHI_PRIVATE_KEY_PATH=n,y(p("Validating..."));const o=await x();o.valid?g(o.msg):(f(o.msg),y(p("Saved. You can re-run sf setup later to fix this."))),$()}async function T(){y("Tavily API powers the agent's web_search tool."),y(`Get a free key at ${m("https://tavily.com")}.`),y("Press Enter to skip:"),$();const e=await w(" > ");if(!e)return y(p("Skipped.")),void $();y(p("Validating..."));const t=await C(e);return t.valid?g(t.msg):(f(t.msg),y(p("Saved. You can re-run sf setup later to fix this."))),$(),e}async function E(e){y("Connect Polymarket to view positions and scan orderbooks."),y("Your Polygon wallet address is needed (starts with 0x...)."),y(`Find it at ${m("https://polymarket.com")} → Settings → Profile.`),y("Press Enter to skip:"),$();const t=await w(" Wallet address > ");if(!t)return y(p("Skipped.")),void $();!t.startsWith("0x")||t.length<40?(f("Invalid wallet address (must start with 0x and be 42 characters)"),y(p("Saved anyway. You can fix it later with sf setup."))):g(`Wallet: ${v(t)}`),e.polymarketWalletAddress=t,y(p("Private key (for future trading) — press Enter to skip:"));const n=await w(" Key path > ");n&&(e.polymarketPrivateKeyPath=n,g(`Private key path: ${p(n)}`)),$()}async function A(e){try{const t=new a.SFClient(e.apiKey,e.apiUrl),n=await t.listTheses(),o=(n.theses||[]).filter(e=>"active"===e.status);if(o.length>0){console.log(` ${h("Step 7: Theses")}`),$(),g(`Found ${o.length} active thesis(es):`);for(const e of o.slice(0,5)){const t="number"==typeof e.confidence?Math.round(100*e.confidence):0,n=(e.rawThesis||e.thesis||e.title||"").slice(0,60);y(` ${p(e.id.slice(0,8))} — ${n} — ${t}%`)}if(y(p("Skipping creation.")),$(),e.openrouterKey){console.log(` ${p("─".repeat(25))}`),console.log(` ${h("All set!")}`),$(),y(` ${m("sf agent")} Chat with your thesis`),y(` ${m("sf context <id>")} View thesis snapshot`),y(` ${m("sf positions")} View positions`),y(` ${m("sf setup --check")} Check config`),$();await k(" Launch agent now? (Y/n) ")&&($(),y("Launching..."),$(),await(0,l.agentCommand)(o[0].id,{model:e.model}))}else $(),console.log(` ${h("All set!")}`),$(),y(` ${m("sf list")} List all theses`),y(` ${m("sf context <id>")} View thesis snapshot`),y(` ${m("sf positions")} View positions`),y(` ${m("sf setup --check")} Check config`),$();return}console.log(` ${h("Step 7: Create Your First Thesis")}`),$(),y("A thesis is your core market conviction. The system builds a causal model"),y("from it, then continuously scans prediction markets for mispriced contracts."),$(),y("Examples:"),y(` ${p('"The Fed won\'t cut rates in 2026 — inflation stays elevated due to oil prices"')}`),y(` ${p('"AI-driven layoffs cause consumer spending to contract, S&P drops 20% by year-end"')}`),y(` ${p('"Trump can\'t exit the Iran conflict — oil stays above $100 for six months"')}`),$();const s=await w(" Enter your thesis (press Enter to skip, use sf create later):\n > ");if(!s)return $(),y(p('Skipped. Use sf create "your thesis" to create one later.')),$(),void M(e);$(),y("Building causal model... (~30s)"),$();try{const n=await t.createThesis(s,!0);if(n.id){const t=n.causalTree?.nodes?.length||0,o=n.edgeAnalysis?.edges?.length||0,s=n.edgeAnalysis?.totalMarketsAnalyzed||0,i=Math.round(100*(parseFloat(n.confidence)||.5));if(g(`Causal tree: ${t} node(s)`),g(`Scanned ${s} markets, found ${o} contract(s) with edge`),g(`Confidence: ${i}%`),g(`Thesis ID: ${n.id.slice(0,8)}`),$(),e.openrouterKey){console.log(` ${p("─".repeat(25))}`),console.log(` ${h("All set!")}`),$();await k(" Launch agent now? (Y/n) ")?($(),y("Launching..."),$(),await(0,l.agentCommand)(n.id,{model:e.model})):($(),M(e))}else M(e)}else f(`Creation failed: ${n.error||"unknown error"}`),y(p('You can retry later with sf create "your thesis"')),$(),M(e)}catch(t){f(`Creation failed: ${t.message}`),y(p('You can retry later with sf create "your thesis"')),$(),M(e)}}catch{$(),M(e)}}function M(e){console.log(` ${p("─".repeat(25))}`),console.log(` ${h("All set!")}`),$(),y(` ${m("sf agent")} Chat with your thesis`),y(` ${m("sf list")} List all theses`),y(` ${m("sf context <id>")} View thesis snapshot`),y(` ${m("sf positions")} View positions`),y(` ${m("sf setup --check")} Check config`),$()}},67378:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.signalCommand=async function(e,t,n){const i=new o.SFClient(n.apiKey,n.apiUrl),r=n.type||"user_note",a=await i.injectSignal(e,r,t,"cli");if(n.json)return void console.log(JSON.stringify({signalId:a.signalId||null,type:r,source:"cli",content:t},null,2));console.log(`${s.c.green}✓${s.c.reset} Signal injected`),console.log(` ${s.c.bold}Type:${s.c.reset} ${r}`),console.log(` ${s.c.bold}Source:${s.c.reset} cli`),console.log(` ${s.c.bold}Content:${s.c.reset} ${t}`),a.signalId&&console.log(` ${s.c.bold}ID:${s.c.reset} ${a.signalId}`);const c=new Date,l=c.getMinutes(),d=15*Math.ceil((l+1)/15),u=d-l,p=new Date(c);p.setMinutes(d%60,0,0),d>=60&&p.setHours(p.getHours()+1);const h=p.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(`\n${s.c.dim}Signal queued. Next monitor cycle in ~${u}min (${h}).${s.c.reset}`),console.log(`${s.c.dim}Or run ${s.c.reset}sf evaluate ${e}${s.c.dim} to consume immediately.${s.c.reset}`)};const o=n(19218),s=n(99236)},72124:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statusCommand=async function(e){const t=[],n=Date.now();try{const e=await fetch(`${r}/api`,{signal:AbortSignal.timeout(5e3)});t.push({name:"API",status:e.ok?"ok":"fail",detail:e.ok?r.replace("https://",""):`HTTP ${e.status}`,ms:Date.now()-n})}catch(e){t.push({name:"API",status:"fail",detail:e.message?.slice(0,40)||"unreachable",ms:Date.now()-n})}const a=(0,i.loadConfig)();if((0,i.isConfigured)()){const n=Date.now();try{const e=await fetch(`${r}/api/thesis`,{headers:{Authorization:`Bearer ${a.apiKey}`},signal:AbortSignal.timeout(5e3)}),o=(a.apiKey||"").slice(0,12)+"...";t.push({name:"Auth",status:e.ok?"ok":"fail",detail:e.ok?o:`HTTP ${e.status}`,ms:Date.now()-n})}catch(e){t.push({name:"Auth",status:"fail",detail:e.message?.slice(0,40)||"failed"})}}else t.push({name:"Auth",status:"skip",detail:"not configured (sf login)"});if((0,s.isKalshiConfigured)()){const n=Date.now();try{const e=await(0,s.getBalance)();t.push({name:"Kalshi",status:e?"ok":"fail",detail:e?`$${e.balance.toFixed(2)} balance`:"auth failed",ms:Date.now()-n})}catch(e){t.push({name:"Kalshi",status:"fail",detail:e.message?.slice(0,40)||"failed"})}}else t.push({name:"Kalshi",status:"skip",detail:"not configured (sf setup --kalshi)"});a.polymarketWalletAddress?t.push({name:"Polymarket",status:"ok",detail:a.polymarketWalletAddress.slice(0,10)+"..."}):t.push({name:"Polymarket",status:"skip",detail:"not configured (sf setup --polymarket)"});if((0,i.isConfigured)())try{const e=await fetch(`${r}/api/thesis`,{headers:{Authorization:`Bearer ${a.apiKey}`},signal:AbortSignal.timeout(5e3)});if(e.ok){const n=(await e.json()).theses||[],o=n.filter(e=>"active"===e.status).length,s=n.length;t.push({name:"Theses",status:"ok",detail:`${o} active, ${s} total`})}}catch{}const c=a.tradingEnabled;if(t.push({name:"Trading",status:c?"ok":"skip",detail:c?"enabled":"disabled (sf setup --enable-trading)"}),e?.json)return void console.log(JSON.stringify({checks:t,timestamp:(new Date).toISOString()},null,2));console.log();for(const e of t){const t="ok"===e.status?`${o.c.green}ok${o.c.reset}`:"fail"===e.status?`${o.c.red}!!${o.c.reset}`:`${o.c.dim}--${o.c.reset}`,n=e.ms?` ${o.c.dim}${e.ms}ms${o.c.reset}`:"";console.log(` ${e.name.padEnd(14)} ${t} ${e.detail}${n}`)}console.log()};const o=n(99236),s=n(96139),i=n(11627),r=process.env.SF_API_URL||"https://simplefunctions.dev"},40239:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.registerStrategies=function(e){e.command("strategies").argument("[thesisId]","thesis ID or prefix (omit for all theses)").option("--status <status>","filter by status (active|watching|executed|cancelled|review)").option("--all","show all statuses (default: active only)").description("List strategies across theses").action(async(e,t)=>{try{const n=new o.SFClient;if(e){const o=(await n.getStrategies(e,t?.all?void 0:t?.status||"active")).strategies||[];if(0===o.length)return console.log(`\n No strategies found for thesis ${e}`),t?.all||t?.status||console.log(` ${r}Try --all to see all statuses${i}`),void console.log();console.log(`\n Strategies for ${e}\n`);for(const e of o)console.log(c(e)),console.log()}else{const{theses:e}=await n.listTheses();let o=0;for(const s of e){const e=t?.all?void 0:t?.status||"active",l=(await n.getStrategies(s.id,e)).strategies||[];if(0!==l.length){o+=l.length,console.log(`\n ${a}${s.title}${i} ${r}(${s.id.slice(0,8)})${i}\n`);for(const e of l)console.log(c(e)),console.log()}}0===o&&(console.log("\n No strategies found"),t?.all||t?.status||console.log(` ${r}Try --all to see all statuses${i}`),console.log())}}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}})};const o=n(19218),s={active:"",watching:"",executed:"",cancelled:"",review:""},i="",r="",a="";function c(e,t=!1){const n=s[e.status]||"",o=[],c=t?`${r}${e.thesisTitle||e.thesisId?.slice(0,8)}${i} `:"";o.push(` ${c}${n}[${e.status}]${i} ${a}${e.marketId}${i} ${e.direction.toUpperCase()} ${r}${e.horizon}${i} priority ${e.priority||0}`);const l=[];null!=e.entryBelow&&l.push(`ask ≤ ${e.entryBelow}¢`),null!=e.entryAbove&&l.push(`ask ≥ ${e.entryAbove}¢`);const d=null!=e.stopLoss?`Stop: ${e.stopLoss}¢`:"",u=null!=e.takeProfit?`TP: ${e.takeProfit}¢`:"",p=`Max: ${e.maxQuantity||500}`,h=`Filled: ${e.executedQuantity||0}/${e.maxQuantity||500}`,m=[l.length>0?`Entry: ${l.join(", ")}`:null,d||null,u||null,p,h].filter(Boolean).join(" | ");if(o.push(` ${m}`),e.softConditions&&o.push(` ${r}Soft: ${e.softConditions}${i}`),"review"===e.status&&o.push(` ⚠️ Needs review${i}`),e.rationale){const t=e.rationale.length>120?e.rationale.slice(0,117)+"...":e.rationale;o.push(` ${r}${t}${i}`)}const g=e.createdBy||"user",f=e.createdAt?new Date(e.createdAt).toLocaleDateString("en-US",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}):"";return o.push(` ${r}created by ${g} · ${f}${i}`),o.join("\n")}},91993:function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.telegramCommand=async function(e){if(e.stop){const e=u();if(e){process.kill(e,"SIGTERM");try{i.default.unlinkSync(l)}catch{}console.log(` Telegram bot stopped (PID ${e})`)}else console.log(" No running Telegram bot found.");return}if(e.status){const e=u();return void(e?(console.log(` Telegram bot running (PID ${e})`),console.log(` Log: ${d}`)):console.log(" Telegram bot not running."))}const t=function(e){const t=(0,c.loadConfig)();if(e){const t=(0,c.loadFileConfig)();return t.telegramBotToken!==e&&(0,c.saveConfig)({...t,telegramBotToken:e}),e}return t.telegramBotToken||null}(e.token);if(!t)return console.log(" No Telegram bot token configured.\n"),console.log(" Setup:"),console.log(" 1. Message @BotFather on Telegram → /newbot"),console.log(" 2. Copy the token"),console.log(" 3. Run: sf telegram --token YOUR_TOKEN\n"),void console.log(" The token will be saved to ~/.sf/config.json for future use.");if(e.daemon){const t=u();if(t)return void console.log(` Bot already running (PID ${t}). Use --stop first.`);const n=["telegram"];e.chatId&&n.push("--chat-id",e.chatId);const o=process.argv[1];i.default.mkdirSync(r.default.dirname(l),{recursive:!0});const a=i.default.openSync(d,"a"),c=(0,s.spawn)(process.execPath,[o,...n],{detached:!0,stdio:["ignore",a,a],env:{...process.env}});return c.unref(),i.default.writeFileSync(l,String(c.pid)),console.log(` Telegram bot started in background (PID ${c.pid})`),console.log(` Log: ${d}`),void console.log(" Stop: sf telegram --stop")}const{startBot:o}=await Promise.all([n.e(830),n.e(278),n.e(12)]).then(n.bind(n,6012));await o({token:t,chatId:e.chatId?parseInt(e.chatId):void 0})};const s=n(35317),i=o(n(79896)),r=o(n(16928)),a=o(n(70857)),c=n(11627),l=r.default.join(a.default.homedir(),".sf","telegram.pid"),d=r.default.join(a.default.homedir(),".sf","telegram.log");function u(){try{const e=parseInt(i.default.readFileSync(l,"utf-8").trim());if(isNaN(e))return null;try{return process.kill(e,0),e}catch{return null}}catch{return null}}},34362:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buyCommand=async function(e,t,n){(0,s.requireTrading)(),await l(e,t,"buy",n)},t.sellCommand=async function(e,t,n){(0,s.requireTrading)(),await l(e,t,"sell",n)};const o=n(96139),s=n(11627),i=n(99236),r=n(79896),a=n(16928),c=n(70857);async function l(e,t,n,s){const l=parseInt(t);if(isNaN(l)||l<=0)throw new Error("Quantity must be a positive integer");const d=s.side||"yes";if(!s.market&&!s.price)throw new Error("Limit order requires --price <cents>. Example: sf buy TICKER 10 --price 45\nFor market orders use: sf buy TICKER 10 --market --price 99");const u=s.market?"market":"limit";let p=s.price?parseInt(s.price):void 0;if(s.market&&!p){console.log(`${i.c.dim}Fetching current market price for ${e}...${i.c.reset}`);const t=await(0,o.getMarketPrice)(e.toUpperCase());if(!t)throw new Error(`Could not fetch market price for ${e}. Use --price <cents> to set manually.`);p=t,console.log(`${i.c.dim}Using market price: ${t}¢${i.c.reset}`)}if(void 0!==p&&(p<1||p>99))throw new Error("Price must be 1-99 cents.");const h=((p||99)*l/100).toFixed(2);if(console.log(),console.log(` ${i.c.bold}${i.c.cyan}${n.toUpperCase()} Order${i.c.reset}`),console.log(` ${i.c.dim}${"─".repeat(35)}${i.c.reset}`),console.log(` Ticker: ${e}`),console.log(" Side: "+("yes"===d?i.c.green+"YES"+i.c.reset:i.c.red+"NO"+i.c.reset)),console.log(` Quantity: ${l}`),console.log(` Type: ${u}`),p&&console.log(` Price: ${p}¢`),console.log(` Max cost: $${h}`),console.log(),!s.yesIAmSure){for(let e=3;e>0;e--)process.stdout.write(` Executing in ${e}... (Ctrl+C to cancel)\r`),await new Promise(e=>setTimeout(e,1e3));process.stdout.write(" Executing... \n")}try{const t=await(0,o.createOrder)({ticker:e,side:d,action:n,type:u,count:l,...p?{yes_price:p}:{}}),s=t.order||t;console.log(),console.log(` ${i.c.green}✓${i.c.reset} Order placed: ${s.order_id||"OK"}`),s.status&&console.log(` Status: ${s.status}`),s.fill_count_fp&&console.log(` Filled: ${s.fill_count_fp}/${s.initial_count_fp||l}`),console.log();try{const t=(0,a.join)((0,c.homedir)(),".sf");(0,r.existsSync)(t)||(0,r.mkdirSync)(t,{recursive:!0});const o=JSON.stringify({ts:(new Date).toISOString(),action:n,ticker:e,side:d,quantity:l,price:p||null,type:u,orderId:s.order_id||null,status:s.status||null,filled:s.fill_count_fp||null})+"\n";(0,r.appendFileSync)((0,a.join)(t,"trade-journal.jsonl"),o),console.log(` ${i.c.dim}Trade logged to ~/.sf/trade-journal.jsonl${i.c.reset}`)}catch{}}catch(e){const t=e.message||String(e);t.includes("403")?(console.error(`\n ${i.c.red}✗${i.c.reset} 403 Forbidden — your Kalshi key lacks write permission.`),console.error(" Get a read+write key at https://kalshi.com/account/api-keys\n")):console.error(`\n ${i.c.red}✗${i.c.reset} ${t}\n`),process.exit(1)}}},96007:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.watchCommand=async function(e,t,n){const s=function(e){if(!e)return"price";const t=e.toLowerCase();return"orderbook"===t||"ob"===t?"orderbook":"flow"===t?"flow":"cross-venue"===t||"xv"===t||"cross"===t?"cross-venue":"all"===t?"all":"price"}(t),i=parseInt(n.interval||("orderbook"===s?"30":"60")),a=1e3*i,h=n.json||!1;if(!h){const t="price"===s?"":` [${s}]`;console.log(),console.log(` ${o.c.bold}sf watch${o.c.reset}${e?` "${e}"`:""}${t}`),console.log(` ${o.c.dim}Polling every ${i}s · Ctrl+C to stop${o.c.reset}`),console.log()}switch(process.on("SIGINT",()=>{h||console.log(`\n ${o.c.dim}Watch stopped.${o.c.reset}\n`),process.exit(0)}),s){case"orderbook":await r(e,a,h);break;case"flow":await async function(e,t,n){let s=new Date(Date.now()-72e5).toISOString();const i=new Map;for(;;){try{const t=await l(s,e);for(const e of t){if("price_move"!==e.changeType)continue;let t=i.get(e.ticker);t||(t={ticker:e.ticker,recentDeltas:[],lastPrice:e.afterPrice||0},i.set(e.ticker,t)),t.recentDeltas.push(e.delta||0),t.recentDeltas.length>10&&t.recentDeltas.shift(),t.lastPrice=e.afterPrice||t.lastPrice;const s=t.recentDeltas.slice(-3);if(s.length>=3){const t=s.every(e=>e>0),i=s.every(e=>e<0);if(t||i){const i=s.reduce((e,t)=>e+Math.abs(t),0),r=t?"UP":"DOWN",a=t?o.c.green:o.c.red;n?console.log(JSON.stringify({type:"momentum",ticker:e.ticker,direction:r,totalDelta:i,moves:s.length})):console.log(` ${u()} ${a}MOMENTUM${o.c.reset} ${e.ticker} ${s.length} consecutive ${r} (${s.map(e=>`${e>0?"+":""}${e}c`).join(", ")}) total ${i}c`)}}if(t.recentDeltas.length>=2){const s=t.recentDeltas[t.recentDeltas.length-2],i=t.recentDeltas[t.recentDeltas.length-1];s&&i&&Math.sign(s)!==Math.sign(i)&&Math.abs(i)>=5&&(n?console.log(JSON.stringify({type:"reversal",ticker:e.ticker,previousDelta:s,currentDelta:i})):console.log(` ${u()} ${o.c.yellow}REVERSAL${o.c.reset} ${e.ticker} was ${s>0?"+":""}${s}c, now ${i>0?"+":""}${i}c`))}}t.length>0?s=t[0].detectedAt:n||process.stdout.write(` ${o.c.dim}${u()} · monitoring flow${o.c.reset}\r`)}catch(e){n||console.error(` ${o.c.dim}${u()} Error: ${e.message}${o.c.reset}`)}await p(t)}}(e,a,h);break;case"cross-venue":await async function(e,t,n){n||console.log(` ${o.c.dim}Fetching cross-venue data from scan...${o.c.reset}`);let s=new Date(Date.now()-72e5).toISOString();const i=new Map;for(;;){try{const t=await l(s,e);for(const e of t){if("price_move"!==e.changeType)continue;const t=e.title.toLowerCase().slice(0,50);let s=i.get(t);if(s||(s={kalshi:0,poly:0}),"kalshi"===e.venue?s.kalshi=e.afterPrice||0:"polymarket"===e.venue&&(s.poly=e.afterPrice||0),i.set(t,s),s.kalshi>0&&s.poly>0){const t=Math.abs(s.kalshi-s.poly),i=s.kalshi>s.poly?"Kalshi":"Poly";if(t>=2)if(n)console.log(JSON.stringify({type:"cross_venue",title:e.title,kalshi:s.kalshi,poly:s.poly,gap:t,higher:i}));else{const n=t>=5?o.c.green:o.c.yellow;console.log(` ${u()} ${n}SPREAD${o.c.reset} ${e.title.slice(0,45)} K:${s.kalshi}c P:${s.poly}c gap ${t}c (${i} higher)`)}}}t.length>0?s=t[0].detectedAt:n||process.stdout.write(` ${o.c.dim}${u()} · tracking cross-venue${o.c.reset}\r`)}catch(e){n||console.error(` ${o.c.dim}${u()} Error: ${e.message}${o.c.reset}`)}await p(t)}}(e,a,h);break;case"all":await async function(e,t,n){let s=new Date(Date.now()-36e5).toISOString();const i=new Map,r=new Map;for(;;){try{const t=await l(s,e);for(const e of t){if(n?console.log(JSON.stringify(e)):d(e),"price_move"!==e.changeType)continue;let t=i.get(e.ticker);t||(t={ticker:e.ticker,recentDeltas:[],lastPrice:e.afterPrice||0},i.set(e.ticker,t)),t.recentDeltas.push(e.delta||0),t.recentDeltas.length>10&&t.recentDeltas.shift();const s=t.recentDeltas.slice(-3);if(s.length>=3&&(s.every(e=>e>0)||s.every(e=>e<0))){const e=s.every(e=>e>0)?"UP":"DOWN",t=s.reduce((e,t)=>e+Math.abs(t),0);if(!n){const n="UP"===e?o.c.green:o.c.red;console.log(` ${n}^^ MOMENTUM${o.c.reset} ${s.length}x ${e} (${t}c total)`)}}const a=e.title.toLowerCase().slice(0,50);let c=r.get(a)||{kalshi:0,poly:0};if("kalshi"===e.venue?c.kalshi=e.afterPrice||0:"polymarket"===e.venue&&(c.poly=e.afterPrice||0),r.set(a,c),c.kalshi>0&&c.poly>0){const e=Math.abs(c.kalshi-c.poly);e>=3&&!n&&console.log(` ${o.c.yellow}^^ CROSS-VENUE${o.c.reset} gap ${e}c K:${c.kalshi}c vs P:${c.poly}c`)}}t.length>0?s=t[0].detectedAt:n||process.stdout.write(` ${o.c.dim}${u()} · watching all${o.c.reset}\r`)}catch(e){n||console.error(` ${o.c.dim}${u()} Error: ${e.message}${o.c.reset}`)}await p(t)}}(e,a,h);break;default:await async function(e,t,n){let s=(new Date).toISOString();try{const t=new Date(Date.now()-36e5).toISOString(),i=await l(t,e);if(i.length>0){n||console.log(` ${o.c.dim}${u()} Recent changes (last hour):${o.c.reset}`);const e=c(i);for(const t of e)n?console.log(JSON.stringify(t)):d(t);s=i[0].detectedAt}else n||console.log(` ${o.c.dim}${u()} No recent changes. Watching...${o.c.reset}`)}catch(e){n||console.error(` ${o.c.dim}${u()} Error: ${e.message}${o.c.reset}`)}for(;;){await p(t);try{const t=await l(s,e),i=n?t:c(t);for(const e of i)n?console.log(JSON.stringify(e)):d(e);t.length>0?s=t[0].detectedAt:n||process.stdout.write(` ${o.c.dim}${u()} · no new changes${o.c.reset}\r`)}catch(e){n||console.error(` ${o.c.dim}${u()} Error: ${e.message}${o.c.reset}`)}}}(e,a,h)}};const o=n(99236),s=n(96139),i=process.env.SF_API_URL||"https://simplefunctions.dev";async function r(e,t,n){e||(console.error(` ${o.c.red}Error:${o.c.reset} orderbook mode requires a query. Example: sf watch "fed" orderbook`),process.exit(1));const i=await a(e);0===i.length&&(console.error(` ${o.c.dim}No Kalshi markets found for "${e}"${o.c.reset}`),process.exit(1)),n||(console.log(` ${o.c.dim}Tracking ${i.length} market(s)${o.c.reset}`),console.log());let r=new Map;for(;;){for(const{ticker:e,title:t}of i)try{const i=await(0,s.getPublicOrderbook)(e,10);if(!i)continue;const a=i.yes_dollars||[],c=i.no_dollars||[],l=a.length>0?Math.round(100*parseFloat(a[0][0])):0,d=c.length>0?100-Math.round(100*parseFloat(c[0][0])):100,p=d-l,h=a.slice(0,3).reduce((e,t)=>e+parseFloat(t[1]),0),m=c.slice(0,3).reduce((e,t)=>e+parseFloat(t[1]),0),g={ticker:e,title:t,bestBid:l,bestAsk:d,spread:p,bidDepth:h,askDepth:m},f=r.get(e);if(n)console.log(JSON.stringify({type:"orderbook",ts:(new Date).toISOString(),...g}));else{const t=p<=2?`${o.c.green}HIGH${o.c.reset}`:p<=5?`${o.c.yellow}MED${o.c.reset}`:`${o.c.red}LOW${o.c.reset}`;let n="";if(f){const e=h-f.bidDepth,t=m-f.askDepth;if(Math.abs(e)>50||Math.abs(t)>50){const s=e>0?"+":"",i=t>0?"+":"";n=` ${o.c.dim}depth: bids ${s}${Math.round(e)}, asks ${i}${Math.round(t)}${o.c.reset}`}}console.log(` ${u()} ${o.c.bold}${e.slice(0,30)}${o.c.reset} bid ${l}c (${Math.round(h)}) | ask ${d}c (${Math.round(m)}) spread ${p}c [${t}]${n}`)}r.set(e,g)}catch{}await p(t)}}async function a(e){try{const t=await fetch(`${i}/api/public/scan?q=${encodeURIComponent(e)}&limit=20`);if(!t.ok)return[];const n=await t.json();return(n.results||n.markets||[]).filter(e=>e.ticker&&"kalshi"===e.venue).slice(0,5).map(e=>({ticker:e.ticker,title:e.title||e.ticker}))}catch{return[]}}function c(e){const t=new Map;for(const n of e){const e=`${n.changeType}:${n.title}`,o=t.get(e);o?o.count++:t.set(e,{count:1,representative:n})}return Array.from(t.values()).map(({count:e,representative:t})=>e>1?{...t,title:`${t.title} (${e} contracts)`}:t)}async function l(e,t){let n=`${i}/api/changes?since=${encodeURIComponent(e)}&limit=50`;t&&(n+=`&q=${encodeURIComponent(t)}`);const o=await fetch(n);if(!o.ok)return[];return(await o.json()).changes||[]}function d(e){const t=u(),n="kalshi"===e.venue?`${o.c.cyan}K${o.c.reset}`:"polymarket"===e.venue?"P":"traditional"===e.venue?`${o.c.dim}$${o.c.reset}`:"·";switch(e.changeType){case"new_contract":console.log(` ${t} ${n} ${o.c.green}+ NEW${o.c.reset} ${e.afterPrice}c ${e.title}`);break;case"removed_contract":console.log(` ${t} ${n} ${o.c.red}- GONE${o.c.reset} ${e.title}`);break;case"price_move":if("traditional"===e.venue){const s=(e.delta||0)>0?"+":"",i=(e.delta||0)>0?o.c.green:o.c.red,r=((e.beforePrice||0)/100).toFixed(0),a=((e.afterPrice||0)/100).toFixed(0);console.log(` ${t} ${n} ${i}${s}${e.delta}c${o.c.reset} $${r}→$${a} ${e.title}`)}else{const s=(e.delta||0)>0?"+":"",i=(e.delta||0)>0?o.c.green:o.c.red;console.log(` ${t} ${n} ${i}${s}${e.delta}c${o.c.reset} ${e.beforePrice}→${e.afterPrice}c ${e.title}`)}}}function u(){return(new Date).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}function p(e){return new Promise(t=>setTimeout(t,e))}},18691:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.whatifCommand=async function(e,t){if(!t.set||0===t.set.length)throw new Error('Usage: sf whatif <thesisId> --set "n1=0.1" [--set "n3=0.5"]');const n=t.set.map(e=>{const[t,n]=e.split("=");if(!t||!n)throw new Error(`Invalid override: "${e}". Format: nodeId=probability`);const o=parseFloat(n);if(isNaN(o)||o<0||o>1)throw new Error(`Invalid probability: "${n}". Must be 0-1.`);return{nodeId:t.trim(),newProbability:o}}),r=new o.SFClient(t.apiKey,t.apiUrl),a=await r.getContext(e),c=function(e,t){const n=[];function o(e){for(const t of e)n.push(t),t.children?.length&&o(t.children)}const s=e.causalTree?.nodes||[];o(s);const i=s.filter(e=>0===e.depth||void 0===e.depth&&!e.id.includes(".")),r=new Map(t.map(e=>[e.nodeId,e.newProbability])),a=t.map(e=>{const t=n.find(t=>t.id===e.nodeId);return{nodeId:e.nodeId,oldProb:t?.probability??0,newProb:e.newProbability,label:t?.label||e.nodeId}}),c=i.reduce((e,t)=>e+(t.probability||0)*(t.importance||0),0),l=i.reduce((e,t)=>e+(r.get(t.id)??t.probability??0)*(t.importance||0),0),d=new Map;for(const[e,t]of r.entries()){const o=n.find(t=>t.id===e);o&&o.probability>0&&d.set(e,Math.max(0,Math.min(2,t/o.probability)))}const u=(e.edges||[]).map(e=>{const t=e.relatedNodeId;let n=1;if(t){const e=[t,t.split(".").slice(0,-1).join("."),t.split(".")[0]].filter(Boolean);for(const t of e)if(d.has(t)){n=d.get(t);break}}const o=e.marketPrice||0,s=e.thesisPrice||e.thesisImpliedPrice||o,i=e.edge||e.edgeSize||0,r=s-o,a=Math.round(100*(o+r*n))/100,c=e.direction||"yes",l=Math.round(100*("yes"===c?a-o:o-a))/100,u=Math.round(100*(l-i))/100;let p="unchanged";return Math.abs(u)<1?p="unchanged":i>0&&l<0||i<0&&l>0?p="reversed":Math.abs(l)<2?p="gone":Math.abs(l)<Math.abs(i)&&(p="reduced"),{marketId:e.marketId,market:e.market||e.marketTitle||e.marketId,venue:e.venue,direction:c,marketPrice:o,oldThesisPrice:s,newThesisPrice:a,oldEdge:i,newEdge:l,delta:u,signal:p,relatedNodeId:t}});return u.sort((e,t)=>Math.abs(t.delta)-Math.abs(e.delta)),{overrides:a,oldConfidence:c,newConfidence:l,confidenceDelta:Math.round(100*(l-c))/100,edges:u}}(a,n);if(t.json)return void console.log(JSON.stringify(c,null,2));console.log(),console.log(`${i.c.bold}${i.c.cyan}WHAT-IF Scenario${i.c.reset}`),console.log(`${i.c.dim}${"─".repeat(65)}${i.c.reset}`);for(const e of c.overrides){const t=Math.round(100*e.oldProb),n=Math.round(100*e.newProb),o=n>t?i.c.green+"↑"+i.c.reset:i.c.red+"↓"+i.c.reset;console.log(` ${i.c.cyan}${e.nodeId}${i.c.reset} ${e.label.slice(0,40)}`),console.log(` ${t}% ${o} ${i.c.bold}${n}%${i.c.reset}`)}const l=Math.round(100*c.oldConfidence),d=Math.round(100*c.newConfidence),u=c.confidenceDelta>0?"+":"",p=c.confidenceDelta>=0?i.c.green:i.c.red;console.log(),console.log(` Confidence: ${l}% → ${p}${i.c.bold}${d}%${i.c.reset} (${p}${u}${Math.round(100*c.confidenceDelta)}${i.c.reset})`),console.log();const h=c.edges.filter(e=>"unchanged"!==e.signal);if(0===h.length)console.log(` ${i.c.dim}No edges affected.${i.c.reset}`);else{console.log(` ${i.c.bold}Edges Affected${i.c.reset}`),console.log(` ${"Market".padEnd(35)} ${"Now".padEnd(6)} ${"Edge".padEnd(8)} ${"→".padEnd(3)} ${"New Edge".padEnd(8)} Signal`),console.log(` ${i.c.dim}${"─".repeat(65)}${i.c.reset}`);for(const e of h){const t=(e.market||e.marketId).slice(0,33).padEnd(35),n=`${Math.round(e.marketPrice)}¢`.padEnd(6),o=`${e.oldEdge>0?"+":""}${Math.round(e.oldEdge)}`.padEnd(8),s=`${e.newEdge>0?"+":""}${Math.round(e.newEdge)}`.padEnd(8);let r;switch(e.signal){case"reversed":r=`${i.c.red}${i.c.bold}REVERSED${i.c.reset}`;break;case"gone":r=`${i.c.red}GONE${i.c.reset}`;break;case"reduced":r=`${i.c.dim}reduced${i.c.reset}`;break;default:r=`${i.c.dim}-${i.c.reset}`}console.log(` ${i.c.dim}${t}${i.c.reset} ${n} ${o} → ${s} ${r}`)}}try{const e=await(0,s.getPositions)();if(e&&e.length>0){const t=new Map(c.edges.map(e=>[e.marketId,e])),n=e.filter(e=>{const n=t.get(e.ticker);return n&&("reversed"===n.signal||"gone"===n.signal)});if(n.length>0){console.log(),console.log(` ${i.c.red}${i.c.bold}⚠ Positions at Risk${i.c.reset}`);for(const e of n){const n=t.get(e.ticker),o=await(0,s.getMarketPrice)(e.ticker),r=null!==o?((o-e.average_price_paid)*e.quantity/100).toFixed(2):"?";console.log(` ${i.c.red}${e.ticker}${i.c.reset} ${e.quantity} ${e.side} P&L $${r} edge ${n.oldEdge>0?"+":""}${Math.round(n.oldEdge)} → ${i.c.red}${n.newEdge>0?"+":""}${Math.round(n.newEdge)}${i.c.reset}`)}}}}catch{}console.log()};const o=n(19218),s=n(96139),i=n(99236)},33192:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.worldCommand=async function(e){const t=process.env.SF_API_URL||"https://simplefunctions.dev";if(e.delta){const n=e.since||"1h",s=await fetch(`${t}/api/agent/world/delta?since=${encodeURIComponent(n)}`);s.ok||(console.error(`\n ${o.c.red}Error:${o.c.reset} API returned ${s.status}\n`),process.exit(1));const i=await s.text();if(e.json)try{console.log(JSON.stringify(JSON.parse(i),null,2))}catch{console.log(i)}else console.log(),console.log(i),console.log();return}const n=e.focus?`?focus=${encodeURIComponent(e.focus)}`:"",s=await fetch(`${t}/api/agent/world${n}`);s.ok||(console.error(`\n ${o.c.red}Error:${o.c.reset} API returned ${s.status}\n`),process.exit(1));const i=await s.text();if(e.json)try{console.log(JSON.stringify(JSON.parse(i),null,2))}catch{console.log(i)}else console.log(),console.log(i),console.log()};const o=n(99236)},84436:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.xSearchCommand=async function(e,t){const n=t?.raw?"raw":"summary",o=t?.hours||"24",r=t?.limit||"20",a=await s(`/api/x/search?q=${encodeURIComponent(e)}&mode=${n}&hours=${o}&limit=${r}`);if(t?.json)return void console.log(JSON.stringify(a,null,2));if(a.summary){if(console.log(`\n X: ${e}\n`),console.log(` ${a.summary}\n`),a.sentiment){const e={bullish:"",bearish:"",mixed:"",neutral:""};console.log(` Sentiment: ${e[a.sentiment]||""}${a.sentiment}`)}a.keyThemes?.length&&console.log(` Themes: ${a.keyThemes.join(", ")}`),console.log()}const c=a.posts||[];if(c.length>0){console.log(` Top posts (${c.length})\n`);for(const e of c.slice(0,10)){const t=e.metrics?.likes||0,n=e.metrics?.retweets||0,o=e.authorFollowers?` (${i(e.authorFollowers)})`:"";console.log(` @${e.authorUsername}${o}`),console.log(` ${e.text.slice(0,140)}${e.text.length>140?"...":""}`),console.log(` ♥ ${t} ↻ ${n}\n`)}}if(a.volume){const e=a.volume,t=e.velocityChange>1?`+${Math.round(100*(e.velocityChange-1))}%`:`${Math.round(100*(e.velocityChange-1))}%`;console.log(` Volume: ${i(e.totalCount)} posts (${o}h) | Velocity: ${t} | Peak: ${e.peak?.count}\n`)}const l=a.news||[];if(l.length>0){console.log(` X News (${l.length})\n`);for(const e of l.slice(0,5)){const t=e.tickers?.length?` ${e.tickers.join(" ")}`:"";console.log(` ${e.title}${t}`),console.log(` ${e.summary.slice(0,120)}...\n`)}}},t.xVolumeCommand=async function(e,t){const n=t?.hours||"72",o=t?.granularity||"hour",r=await s(`/api/x/volume?q=${encodeURIComponent(e)}&hours=${n}&granularity=${o}`);if(t?.json)return void console.log(JSON.stringify(r,null,2));console.log(`\n X Volume: ${e}\n`),console.log(` Total: ${i(r.totalCount)} posts (${n}h)`);const a=r.velocityChange>1?`+${Math.round(100*(r.velocityChange-1))}%`:`${Math.round(100*(r.velocityChange-1))}%`;console.log(` Velocity: ${a}`),console.log(` Peak: ${r.peak?.count} at ${r.peak?.time?.slice(11,16)||"?"}\n`);const c=r.timeseries||[];if(c.length>0){const e=Math.max(...c.map(e=>e.count)),t=40;for(const n of c.slice(-24)){const o=(n.time||"").slice(11,16)||"?",s=e>0?Math.round(n.count/e*t):0,i="▓".repeat(s),r=String(n.count).padStart(6);console.log(` ${o} ${r} ${i}`)}}console.log()},t.xNewsCommand=async function(e,t){const n=t?.limit||"10",o=await s(`/api/x/news?q=${encodeURIComponent(e)}&limit=${n}`);if(t?.json)return void console.log(JSON.stringify(o,null,2));const i=o.stories||[];console.log(`\n X News: ${e} (${i.length} stories)\n`);for(const e of i){const t=e.tickers?.length?` ${e.tickers.join(" ")}`:"",n=e.categories?.length?`[${e.categories.join(", ")}]`:"";console.log(` ${e.title}${t} ${n}`),console.log(` ${e.summary.slice(0,200)}${e.summary.length>200?"...":""}`),console.log()}},t.xAccountCommand=async function(e,t){const n=e.replace(/^@/,""),o=t?.hours||"24",i=t?.limit||"20",r=await s(`/api/x/account?username=${n}&hours=${o}&limit=${i}`);if(t?.json)return void console.log(JSON.stringify(r,null,2));const a=r.posts||[];console.log(`\n @${n} (${a.length} posts, last ${o}h)\n`);for(const e of a){const t=e.metrics?.likes||0,n=e.metrics?.retweets||0,o=e.createdAt?.slice(11,16)||"";console.log(` ${o} ${e.text.slice(0,140)}${e.text.length>140?"...":""}`),console.log(` ♥ ${t} ↻ ${n}\n`)}};const n=process.env.SF_API_URL||"https://simplefunctions.dev";function o(){const e=process.env.SF_API_KEY||"";return e||(console.error(" API key required. Run: sf setup"),process.exit(1)),e}async function s(e){const t=await fetch(`${n}${e}`,{headers:{Authorization:`Bearer ${o()}`}});if(!t.ok){const e=await t.text();throw new Error(`${t.status}: ${e}`)}return t.json()}function i(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}},11627:function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.loadFileConfig=u,t.loadConfig=p,t.saveConfig=function(e){s.default.mkdirSync(a,{recursive:!0}),s.default.writeFileSync(c,JSON.stringify({...e,configuredAt:(new Date).toISOString()},null,2))},t.resetConfig=function(){try{s.default.existsSync(c)&&s.default.unlinkSync(c)}catch{}},t.applyConfig=function(){const e=u();!process.env.SF_API_KEY&&e.apiKey&&(process.env.SF_API_KEY=e.apiKey);!process.env.SF_API_URL&&e.apiUrl&&(process.env.SF_API_URL=e.apiUrl);!process.env.OPENROUTER_API_KEY&&e.openrouterKey&&(process.env.OPENROUTER_API_KEY=e.openrouterKey);!process.env.KALSHI_API_KEY_ID&&e.kalshiKeyId&&(process.env.KALSHI_API_KEY_ID=e.kalshiKeyId);!process.env.KALSHI_PRIVATE_KEY_PATH&&e.kalshiPrivateKeyPath&&(process.env.KALSHI_PRIVATE_KEY_PATH=e.kalshiPrivateKeyPath);!process.env.POLYMARKET_WALLET_ADDRESS&&e.polymarketWalletAddress&&(process.env.POLYMARKET_WALLET_ADDRESS=e.polymarketWalletAddress);!process.env.POLYMARKET_PRIVATE_KEY_PATH&&e.polymarketPrivateKeyPath&&(process.env.POLYMARKET_PRIVATE_KEY_PATH=e.polymarketPrivateKeyPath);!process.env.TAVILY_API_KEY&&e.tavilyKey&&(process.env.TAVILY_API_KEY=e.tavilyKey);!process.env.SF_MODEL&&e.model&&(process.env.SF_MODEL=e.model)},t.isConfigured=function(){const e=p();return!!e.apiKey},t.requireTrading=function(){const e=p();e.tradingEnabled||(console.error("\n Trading is disabled. Run: sf setup --enable-trading\n"),process.exit(1));e.kalshiKeyId||process.env.KALSHI_API_KEY_ID||(console.error("\n Kalshi API key not configured. Run: sf setup --kalshi\n"),process.exit(1))},t.getConfigPath=function(){return c};const s=o(n(79896)),i=o(n(16928)),r=o(n(70857)),a=i.default.join(r.default.homedir(),".sf"),c=i.default.join(a,"config.json"),l="https://simplefunctions.dev",d="anthropic/claude-sonnet-4.6";function u(){try{if(s.default.existsSync(c))return JSON.parse(s.default.readFileSync(c,"utf-8"))}catch{}return{}}function p(){const e=u();return{apiKey:process.env.SF_API_KEY||e.apiKey,apiUrl:process.env.SF_API_URL||e.apiUrl||l,openrouterKey:process.env.OPENROUTER_API_KEY||e.openrouterKey,kalshiKeyId:process.env.KALSHI_API_KEY_ID||e.kalshiKeyId,kalshiPrivateKeyPath:process.env.KALSHI_PRIVATE_KEY_PATH||e.kalshiPrivateKeyPath,polymarketWalletAddress:process.env.POLYMARKET_WALLET_ADDRESS||e.polymarketWalletAddress,polymarketPrivateKeyPath:process.env.POLYMARKET_PRIVATE_KEY_PATH||e.polymarketPrivateKeyPath,tavilyKey:process.env.TAVILY_API_KEY||e.tavilyKey,model:process.env.SF_MODEL||e.model||d,tradingEnabled:e.tradingEnabled||!1,telegramBotToken:process.env.TELEGRAM_BOT_TOKEN||e.telegramBotToken}}},96139:function(e,t,n){"use strict";var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isKalshiConfigured=c,t.getPositions=async function(){if(!c())return null;try{const e=await u("/portfolio/positions");return(e.market_positions||e.positions||[]).map(e=>{const t=parseFloat(e.position_fp||"0"),n=parseFloat(e.total_traded_dollars||"0"),o=Math.abs(t),s=t>=0?"yes":"no",i=o>0?Math.round(n/o*100):0;return{ticker:e.ticker||e.market_ticker||"",event_ticker:e.event_ticker||"",market_title:e.market_title||e.title||"",side:s,quantity:o,average_price_paid:i,current_value:0,realized_pnl:Math.round(100*parseFloat(e.realized_pnl||"0")),unrealized_pnl:0,total_cost:Math.round(100*n)}})}catch(e){return console.warn("[Kalshi] Failed to fetch positions:",e),null}},t.kalshiPriceCents=h,t.getMarketPrice=async function(e){try{const t=`https://api.elections.kalshi.com/trade-api/v2/markets/${e}`,n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)return null;const o=await n.json(),s=o.market||o,i=h(s);return 50!==i||s.last_price_dollars||s.yes_bid_dollars?i:null}catch{return null}},t.getOrderbook=async function(e){if(!c())return null;try{const t=await u(`/markets/${e}/orderbook`),n=t.orderbook_fp||t.orderbook;if(!n)return null;const o=n.yes_dollars||n.yes||[],s=n.no_dollars||n.no||[],i=!(!n.yes_dollars&&!n.no_dollars),r=o.map(e=>({price:i?Math.round(100*parseFloat(e[0])):Number(e[0]),qty:parseFloat(e[1])})).filter(e=>e.price>0),a=s.map(e=>({price:i?Math.round(100*parseFloat(e[0])):Number(e[0]),qty:parseFloat(e[1])})).filter(e=>e.price>0);r.sort((e,t)=>t.price-e.price),a.sort((e,t)=>t.price-e.price);const c=r.length>0?r[0].price:0,l=a.length>0?100-a[0].price:100,d=l-c,p=r.slice(0,3).reduce((e,t)=>e+t.qty,0),h=a.slice(0,3).reduce((e,t)=>e+t.qty,0),m=Math.min(p,h);let g="low";return d<=2&&m>=500?g="high":d<=5&&m>=100&&(g="medium"),{bestBid:c,bestAsk:l,spread:d,bidDepth:p,askDepth:h,liquidityScore:g}}catch{return null}},t.getPublicOrderbook=async function(e,t=20){try{const n=`${a}/markets/${e}/orderbook?depth=${t}`,o=await fetch(n,{headers:{Accept:"application/json"}});if(!o.ok)return null;const s=await o.json(),i=s.orderbook_fp||s.orderbook||s;return{yes_dollars:i.yes_dollars||i.yes||[],no_dollars:i.no_dollars||i.no||[]}}catch{return null}},t.getSettlements=async function(e){if(!c())return null;try{const t=new URLSearchParams;e?.limit&&t.set("limit",e.limit.toString()),e?.cursor&&t.set("cursor",e.cursor),e?.ticker&&t.set("ticker",e.ticker);const n=await u(`/portfolio/settlements?${t.toString()}`);return{settlements:n.settlements||[],cursor:n.cursor||""}}catch(e){return console.warn("[Kalshi] Failed to fetch settlements:",e),null}},t.getBalance=async function(){if(!c())return null;try{const e=await u("/portfolio/balance"),t=(e.balance||0)/100;return{balance:t,portfolioValue:(e.portfolio_value||0)/100}}catch(e){return console.warn("[Kalshi] Failed to fetch balance:",e),null}},t.getOrders=async function(e){if(!c())return null;try{const t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.ticker&&t.set("ticker",e.ticker),e?.limit&&t.set("limit",e.limit.toString()),e?.cursor&&t.set("cursor",e.cursor);const n=await u(`/portfolio/orders?${t.toString()}`);return{orders:n.orders||[],cursor:n.cursor||""}}catch(e){return console.warn("[Kalshi] Failed to fetch orders:",e),null}},t.getFills=async function(e){if(!c())return null;try{const t=new URLSearchParams;e?.ticker&&t.set("ticker",e.ticker),e?.limit&&t.set("limit",e.limit.toString()),e?.cursor&&t.set("cursor",e.cursor);const n=await u(`/portfolio/fills?${t.toString()}`);return{fills:n.fills||[],cursor:n.cursor||""}}catch(e){return console.warn("[Kalshi] Failed to fetch fills:",e),null}},t.getForecastHistory=async function(e){if(!c())return null;try{const t=new URLSearchParams;for(const n of e.percentiles)t.append("percentiles",n.toString());t.set("start_ts",e.startTs.toString());const n=Math.floor((new Date).setUTCHours(0,0,0,0)/1e3),o=Math.min(e.endTs,n);t.set("end_ts",o.toString()),t.set("period_interval",e.periodInterval.toString());const s=`/series/${e.seriesTicker}/events/${e.eventTicker}/forecast_percentile_history?${t.toString()}`;return(await u(s)).forecast_history||[]}catch(e){return console.warn("[Kalshi] Failed to fetch forecast:",e),null}},t.getExchangeAnnouncements=async function(){try{const e=await fetch(`${a}/exchange/announcements`,{headers:{Accept:"application/json"}});if(!e.ok)return[];return(await e.json()).announcements||[]}catch{return[]}},t.getHistoricalMarket=async function(e){try{const t=await fetch(`${a}/historical/markets/${e}`,{headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return n.market||n||null}catch{return null}},t.createOrder=async function(e){return p("/portfolio/orders",e)},t.cancelOrder=async function(e){await async function(e){const t=l();if(!t)throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.");const n=`${a}${e}`,o=e.split("?")[0],{headers:s}=d("DELETE",`/trade-api/v2${o}`,t),i=await fetch(n,{method:"DELETE",headers:s});if(!i.ok){const e=await i.text();throw new Error(`Kalshi API ${i.status}: ${e}`)}const r=i.headers.get("content-type");if(r?.includes("application/json"))return i.json();return{}}(`/portfolio/orders/${e}`)},t.batchCancelOrders=async function(e){await p("/portfolio/orders/batched",{orders:e.map(e=>({action:"cancel",order_id:e}))})},t.amendOrder=async function(e,t){const n=l();if(!n)throw new Error("Kalshi private key not loaded.");const o=`/portfolio/orders/${e}`,s=`${a}${o}`,{headers:i}=d("PATCH",`/trade-api/v2${o}`,n),r=await fetch(s,{method:"PATCH",headers:i,body:JSON.stringify(t)});if(!r.ok){const e=await r.text();throw new Error(`Kalshi API ${r.status}: ${e}`)}return r.json()},t.getBatchCandlesticks=async function(e){if(!c())return[];try{const t=new URLSearchParams;t.set("market_tickers",e.tickers.join(",")),t.set("start_ts",e.startTs.toString()),t.set("end_ts",e.endTs.toString()),t.set("period_interval",(e.periodInterval??1440).toString());return(await u(`/markets/candlesticks?${t.toString()}`)).markets||[]}catch(e){return console.warn("[Kalshi] Failed to fetch candlesticks:",e),[]}},t.createRFQ=async function(e){return p("/communications/rfqs",e)};const s=o(n(79896)),i=o(n(16928)),r=o(n(76982)),a="https://api.elections.kalshi.com/trade-api/v2";function c(){return!(!process.env.KALSHI_API_KEY_ID||!process.env.KALSHI_PRIVATE_KEY_PATH)}function l(){const e=process.env.KALSHI_PRIVATE_KEY_PATH;if(!e)return null;const t=e.startsWith("~")?i.default.join(process.env.HOME||"",e.slice(1)):i.default.resolve(e);try{const e=s.default.readFileSync(t,"utf-8");return r.default.createPrivateKey(e)}catch(e){return console.warn(`[Kalshi] Failed to load private key from ${t}:`,e),null}}function d(e,t,n){const o=process.env.KALSHI_API_KEY_ID,s=Date.now().toString(),i=s+e.toUpperCase()+t;return{headers:{"KALSHI-ACCESS-KEY":o,"KALSHI-ACCESS-SIGNATURE":r.default.sign("sha256",Buffer.from(i),{key:n,padding:r.default.constants.RSA_PKCS1_PSS_PADDING,saltLength:r.default.constants.RSA_PSS_SALTLEN_DIGEST}).toString("base64"),"KALSHI-ACCESS-TIMESTAMP":s,"Content-Type":"application/json",Accept:"application/json"}}}async function u(e){const t=l();if(!t)throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.");const n=`${a}${e}`,o=e.split("?")[0],{headers:s}=d("GET",`/trade-api/v2${o}`,t),i=await fetch(n,{method:"GET",headers:s});if(!i.ok){const e=await i.text();throw new Error(`Kalshi API ${i.status}: ${e}`)}return i.json()}async function p(e,t){const n=l();if(!n)throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.");const o=`${a}${e}`,s=e.split("?")[0],{headers:i}=d("POST",`/trade-api/v2${s}`,n),r=await fetch(o,{method:"POST",headers:i,body:JSON.stringify(t)});if(!r.ok){const e=await r.text();throw new Error(`Kalshi API ${r.status}: ${e}`)}return r.json()}function h(e){if(e.last_price_dollars){const t=parseFloat(e.last_price_dollars);if(!isNaN(t)&&t>0)return Math.round(100*t)}if(e.yes_bid_dollars){const t=parseFloat(e.yes_bid_dollars);if(!isNaN(t)&&t>0)return Math.round(100*t)}if(e.yes_ask_dollars){const t=parseFloat(e.yes_ask_dollars);if(!isNaN(t)&&t>0)return Math.round(100*t)}return null!=e.last_price&&e.last_price>0?e.last_price:null!=e.yes_bid&&e.yes_bid>0?e.yes_bid:50}},34331:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.polymarketSearch=async function(e,t=20){const o=new URLSearchParams({q:e,limit_per_type:t.toString()}),s=await fetch(`${n}/public-search?${o}`);if(!s.ok)throw new Error(`Polymarket search error: ${s.status}`);const i=await s.json();return i.events||[]},t.polymarketListEvents=async function(e){const t=new URLSearchParams({active:"true",closed:"false",limit:(e?.limit||50).toString(),offset:(e?.offset||0).toString()});e?.order&&t.set("order",e.order);void 0!==e?.ascending&&t.set("ascending",String(e.ascending));e?.tag_id&&t.set("tag_id",e.tag_id);const o=await fetch(`${n}/events?${t}`);if(!o.ok)throw new Error(`Polymarket events error: ${o.status}`);return o.json()},t.polymarketGetEvent=async function(e){const t=await fetch(`${n}/events/${e}`);if(!t.ok)throw new Error(`Polymarket event error: ${t.status}`);return t.json()},t.polymarketGetMarket=async function(e){const t=await fetch(`${n}/markets/${e}`);if(!t.ok)throw new Error(`Polymarket market error: ${t.status}`);return t.json()},t.polymarketListTags=async function(){const e=await fetch(`${n}/tags`);if(!e.ok)throw new Error(`Polymarket tags error: ${e.status}`);return e.json()},t.polymarketGetOrderbook=i,t.computeOrderbookDepth=r,t.polymarketGetOrderbookWithDepth=async function(e){const t=await i(e);return t?r(t):null},t.polymarketGetMidpoint=async function(e){try{const t=await fetch(`${o}/midpoint?token_id=${e}`);if(!t.ok)return null;const n=await t.json();return n.mid?parseFloat(n.mid):null}catch{return null}},t.polymarketGetSpread=async function(e){try{const t=await fetch(`${o}/spread?token_id=${e}`);if(!t.ok)return null;const n=await t.json();return n.spread?parseFloat(n.spread):null}catch{return null}},t.polymarketGetMidpoints=async function(e){if(0===e.length)return{};const t=await fetch(`${o}/midpoints`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Polymarket midpoints error: ${t.status}`);return t.json()},t.polymarketGetOHLC=async function(e){const t=new URLSearchParams({asset_id:e.tokenId,startTs:e.startTs.toString(),fidelity:e.fidelity||"1h"});e.endTs&&t.set("endTs",e.endTs.toString());e.limit&&t.set("limit",e.limit.toString());const n=await fetch(`${o}/ohlc?${t}`);if(!n.ok)return[];const s=await n.json();return Array.isArray(s)?s:s.candles||s.data||[]},t.polymarketGetPriceHistory=async function(e){const t=new URLSearchParams({market:e.tokenId});e.interval&&t.set("interval",e.interval);e.startTs&&t.set("startTs",e.startTs.toString());e.endTs&&t.set("endTs",e.endTs.toString());e.fidelity&&t.set("fidelity",e.fidelity.toString());const n=await fetch(`${o}/prices-history?${t}`);if(!n.ok)return[];const s=await n.json();return s.history||[]},t.polymarketGetPositions=async function(e){const t=await fetch(`${s}/positions?user=${e}`);if(!t.ok)return[];const n=await t.json();return Array.isArray(n)?n:[]},t.polymarketGetClosedPositions=async function(e){const t=await fetch(`${s}/closed-positions?user=${e}`);if(!t.ok)return[];const n=await t.json();return Array.isArray(n)?n:[]},t.scoreLiquidity=a,t.parseClobTokenIds=function(e){try{const t=JSON.parse(e);return Array.isArray(t)&&t.length>=2?[t[0],t[1]]:null}catch{return null}},t.parseOutcomes=function(e){try{return JSON.parse(e)}catch{return[]}},t.parseOutcomePrices=function(e){try{return JSON.parse(e)}catch{return[]}},t.toCents=function(e){return Math.round(100*e)},t.polymarketUrl=function(e){return`https://polymarket.com/event/${e}`};const n="https://gamma-api.polymarket.com",o="https://clob.polymarket.com",s="https://data-api.polymarket.com";async function i(e){try{const t=await fetch(`${o}/book?token_id=${e}`);if(!t.ok)return null;const n=await t.json();return n.error?null:n}catch{return null}}function r(e){const t=(e.bids||[]).map(e=>({price:parseFloat(e.price),size:parseFloat(e.size)})).sort((e,t)=>t.price-e.price),n=(e.asks||[]).map(e=>({price:parseFloat(e.price),size:parseFloat(e.size)})).sort((e,t)=>e.price-t.price),o=t.length>0?Math.round(100*t[0].price):0,s=n.length>0?Math.round(100*n[0].price):100,i=s-o,r=t.slice(0,3).reduce((e,t)=>e+t.size,0),c=n.slice(0,3).reduce((e,t)=>e+t.size,0),l=t.reduce((e,t)=>e+t.size,0),d=n.reduce((e,t)=>e+t.size,0),u=a(i,r+c);return{bestBid:o,bestAsk:s,spread:i,bidDepthTop3:Math.round(r),askDepthTop3:Math.round(c),totalBidDepth:Math.round(l),totalAskDepth:Math.round(d),liquidityScore:u,levels:{bids:e.bids,asks:e.asks}}}function a(e,t){return e<=2&&t>=500?"high":e<=5&&t>=100?"medium":"low"}},35178:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shareOutput=async function(e,t,o){try{const s=await fetch(`${n}/api/share`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,args:t,data:o})});if(!s.ok)return void console.error(`Share failed: ${s.status}`);const{url:i}=await s.json();console.log(),console.log(` ${i}`),console.log()}catch(e){console.error(`Share failed: ${e.message}`)}};const n=process.env.SF_API_URL||"https://simplefunctions.dev"},40101:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.loadSkills=function(){const e=[],t=__dirname,n=t.includes("dist")?(0,s.join)(t,"../../src/skills"):t;let r=[];try{r=(0,o.readdirSync)(n).filter(e=>e.endsWith(".md"))}catch{return e}for(const t of r)try{const r=i((0,o.readFileSync)((0,s.join)(n,t),"utf-8"));r&&e.push(r)}catch{}try{const t=process.env.HOME||process.env.USERPROFILE||"",n=(0,s.join)(t,".sf","skills"),r=(0,o.readdirSync)(n).filter(e=>e.endsWith(".md"));for(const t of r)try{const r=i((0,o.readFileSync)((0,s.join)(n,t),"utf-8"));r&&e.push(r)}catch{}}catch{}return e};const o=n(79896),s=n(16928);function i(e){const t=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!t)return null;const n=t[1],o=t[2].trim(),s={};for(const e of n.split("\n")){const t=e.match(/^(\w[\w_]*)\s*:\s*(.+)$/);t&&(s[t[1]]=t[2].trim())}if(!s.name||!s.trigger)return null;const i=o.match(/## Instructions\n([\s\S]*)$/i),r=i?i[1].trim():o,a=e=>(e||"").replace(/[\[\]]/g,"").split(",").map(e=>e.trim()).filter(Boolean);return{name:s.name,trigger:s.trigger,description:s.description||"",author:s.author||"unknown",version:s.version||"1.0.0",category:s.category||"general",tags:a(s.tags),toolsUsed:a(s.tools_used),estimatedTime:s.estimated_time||"",auto:s.auto,prompt:r,raw:e}}},97325:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RISK_CATEGORIES=t.TOPIC_SERIES=void 0,t.tickerToTopic=function(e){const n=Object.entries(t.TOPIC_SERIES).flatMap(([e,t])=>t.map(t=>({prefix:t,topic:e}))).sort((e,t)=>t.prefix.length-e.prefix.length);for(const{prefix:t,topic:o}of n)if(e.toUpperCase().startsWith(t))return o.toUpperCase();return"OTHER"},t.TOPIC_SERIES={oil:["KXWTIMAX","KXWTIW","KXWTID","KXWTI"],gas:["KXAAAGASM","KXAAAGASW","KXCPIGAS"],fed:["KXFEDDECISION","KXFED","KXRATECUT","KXRATECUTCOUNT"],cpi:["KXCPI","KXCPIYOY"],recession:["KXRECSSNBER"],sp500:["KXINXY","KXINXU","KXINX"],nasdaq:["KXNASDAQ100","KXNASDAQ100U","KXNASDAQ100Y"],crypto:["KXBTCD","KXBTC","KXBTC15M","KXBTCMAXY","KXBTCMINY","KXBTCY","KXETHD","KXETH","KXETH15M","KXETHMAXY","KXETHMINY","KXSOL15M","KXXRP15M"],unemployment:["KXU3","KXPAYROLLS"],gdp:["KXGDP"],treasury:["KXTNOTEW","KXTNOTED"],geopolitics:["KXCLOSEHORMUZ","KXHORMUZTRAFFICW","KXHORMUZTRAFFIC","KXHORMUZNORM","KXLEADERSOUT","KXLEADEROUT","KXMADUROOUT","KXKHAMENEIOUT"],elections:["PRES","KXFEDCHAIRNOM","KXPRESNOMD","KXPRESNOMR","KXPRESPERSON","KXNEXTPOPE","KXTRUMPOUT","KXCANADAPM"],politics:["KXGOVSHUT","KXGOVTSHUTDOWN","KXGOVSHUTLENGTH","KXGOVTCUTS","KXTRUMPMENTION","KXEOWEEK","KXGREENLAND","KXCANCOALITION"],centralbanks:["KXCBDECISIONJAPAN","KXCBDECISIONENGLAND","KXCBDECISIONEU","KXCBDECISIONAUSTRALIA","KXCBDECISIONCANADA","KXCBDECISIONCHINA","KXCBDECISIONMEXICO","KXCBDECISIONKOREA"],forex:["KXUSDJPY"],tariffs:["KXTARIFFRATEPRC","KXTARIFFRATECAN","KXTARIFFRATECA","KXTARIFFRATEINDIA","KXTARIFFRATEBR","KXTARIFFRATEEU","KXTARIFFRATEJP","KXTARIFFRATEKR"],tech:["KXLLM1","KXTOPMODEL","KXALIENS"]},t.RISK_CATEGORIES={KXWTIMAX:"Oil",KXWTIW:"Oil",KXWTID:"Oil",KXWTI:"Oil",KXAAAGASM:"Gas",KXAAAGASW:"Gas",KXCPIGAS:"Gas",KXRECSSNBER:"Recession",KXCPI:"Inflation",KXCPIYOY:"Inflation",KXINXY:"S&P 500",KXINXU:"S&P 500",KXINX:"S&P 500",KXNASDAQ100:"Nasdaq",KXNASDAQ100U:"Nasdaq",KXNASDAQ100Y:"Nasdaq",KXFEDDECISION:"Fed Rate",KXFED:"Fed Rate",KXRATECUT:"Fed Rate",KXRATECUTCOUNT:"Fed Rate",KXBTCD:"Bitcoin",KXBTC:"Bitcoin",KXBTC15M:"Bitcoin",KXETHD:"Ethereum",KXETH:"Ethereum",KXETH15M:"Ethereum",KXU3:"Unemployment",KXPAYROLLS:"Jobs",KXGDP:"GDP",KXTNOTEW:"Treasury",KXTNOTED:"Treasury",KXCLOSEHORMUZ:"Hormuz",KXHORMUZTRAFFICW:"Hormuz",KXHORMUZTRAFFIC:"Hormuz",KXUSDJPY:"USD/JPY",KXGOVSHUT:"Govt Shutdown",KXGOVTSHUTDOWN:"Govt Shutdown",PRES:"Elections",KXFEDCHAIRNOM:"Elections",KXTARIFFRATEPRC:"Tariffs",KXCBDECISIONJAPAN:"Central Banks",KXCBDECISIONENGLAND:"Central Banks",KXCBDECISIONEU:"Central Banks"}},77096:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLR=t.bgRgb=t.rgb=void 0,t.drawBorder=function(e,n,o){const{row:s,col:i,width:r,height:a}=n;if(r<3||a<2)return;e.fill(s,i,r,a," ","",t.CLR.bgPanel);for(let n=i;n<i+r;n++)e.write(s,n,"─",t.CLR.borderDim);o&&e.write(s,i+2,` ${o} `,t.CLR.dim)},t.drawHDivider=function(e,n,o){const s=n.row+o;for(let o=n.col;o<n.col+n.width;o++)e.write(s,o,"─",t.CLR.borderDim)},t.fit=function(e,t,n="left"){return e.length>t?e.slice(0,t-1)+"…":"right"===n?e.padStart(t):e.padEnd(t)},t.sparkline=function(e,n){if(0===e.length)return[];const o=Math.min(...e),s=Math.max(...e),i=s-o||1;return e.map(e=>({text:"▁▂▃▄▅▆▇█"[Math.round((e-o)/i*7)],fg:n?n(e):t.CLR.dim}))},t.compact=function(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1)}M`:Math.abs(e)>=1e4?`${(e/1e3).toFixed(0)}k`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)}k`:String(Math.round(e))};t.rgb=(e,t,n)=>`[38;2;${e};${t};${n}m`;t.bgRgb=(e,t,n)=>`[48;2;${e};${t};${n}m`,t.CLR={border:(0,t.rgb)(50,50,56),borderDim:(0,t.rgb)(35,35,40),title:(0,t.rgb)(180,180,190),white:(0,t.rgb)(240,240,242),text:(0,t.rgb)(180,180,186),dim:(0,t.rgb)(100,100,110),veryDim:(0,t.rgb)(55,55,62),emerald:(0,t.rgb)(16,185,129),green:(0,t.rgb)(74,222,128),red:(0,t.rgb)(248,113,113),yellow:(0,t.rgb)(250,204,21),cyan:(0,t.rgb)(34,211,238),purple:(0,t.rgb)(192,132,252),bg:(0,t.bgRgb)(8,8,12),bgPanel:(0,t.bgRgb)(14,14,18),bgSelected:(0,t.bgRgb)(22,40,35),bgHover:(0,t.bgRgb)(18,18,24)}},14916:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.drawChart=function(e,t,n,s,i,r,a){if(0===r.length||s<10||i<4)return;const c=s-8-1,l=i-2;if(c<4||l<2)return;const d=Math.min(...r),u=Math.max(...r),p=u-d||1,h=[];for(let e=0;e<c;e++){const t=e/(c-1)*(r.length-1),n=Math.floor(t),o=Math.min(n+1,r.length-1),s=t-n;h.push(r[n]*(1-s)+r[o]*s)}const m=n+8+1,g=[{row:0,value:u},{row:l-1,value:d}];let f=-1;d<0&&u>0&&(f=Math.round(u/p*(l-1)),f>0&&f<l-1&&g.push({row:f,value:0}));for(let s=0;s<l;s++)e.write(t+s,n+8,"│",o.CLR.borderDim);for(const s of g){const i=Math.abs(s.value)>=100?"$"+((s.value>=0?"+":"")+s.value.toFixed(0)):"$"+((s.value>=0?"+":"")+s.value.toFixed(1));e.write(t+s.row,n,i.padStart(8),o.CLR.dim)}if(f>=0&&f<l)for(let n=0;n<c;n++)e.write(t+f,m+n,"╌",o.CLR.veryDim);for(let n=0;n<c;n++){const s=h[n],i=(s-d)/p*l*8,r=s>=0?o.CLR.green:o.CLR.red;for(let o=l-1;o>=0;o--){const s=i-8*(l-1-o);if(s>=8)e.write(t+o,m+n,"█",r);else if(s>0){const i=Math.round(Math.max(1,Math.min(s,8)));e.write(t+o,m+n," ▁▂▃▄▅▆▇█"[i],r)}}}const y=t+l;e.write(y,n+8,"└",o.CLR.borderDim);for(let t=0;t<c;t++)e.write(y,m+t,"─",o.CLR.borderDim);if(a&&a.length>0){const i=t+l+1,r=Math.min(a.length,6);for(let t=0;t<r;t++){const l=Math.round(t*(a.length-1)/Math.max(r-1,1)),d=m+Math.round(l*(c-1)/Math.max(a.length-1,1)),u=a[l]||"";d>=m&&d+u.length<n+s&&e.write(i,d,u.slice(0,5),o.CLR.dim)}}};const o=n(77096)},99844:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.loadAllData=R,t.startDashboard=async function(){const e=new o.ScreenBuffer,t=(0,i.initialState)();process.stdout.write("[?1049h"),process.stdout.write("[?25l"),process.stdin.isTTY&&process.stdin.setRawMode(!0);process.stdin.resume();let n=!1;const s=()=>{n||(n=!0,setImmediate(()=>{n=!1,D(e,t)}))},r=[];let c=!1;const l=()=>{if(!c){c=!0;for(const e of r)clearInterval(e);process.stdout.write("[?1049l"),process.stdout.write("[?25h"),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.exit(0)}};process.on("SIGINT",l),process.on("SIGTERM",l);try{await R(t)}catch(e){t.error=e instanceof Error?e.message.slice(0,50):"Failed to load data"}D(e,t),r.push(setInterval(async()=>{try{const e=await(0,a.cached)("positions",C,()=>(0,d.getPositions)());if(e){const n=await Promise.allSettled(e.map(e=>(0,a.cached)(`price:${e.ticker}`,1e4,()=>(0,d.getMarketPrice)(e.ticker))));for(let t=0;t<e.length;t++){const o=n[t];"fulfilled"===o.status&&null!=o.value&&(e[t].current_value=o.value)}t.positions=e,N(t)}s()}catch{}},C)),r.push(setInterval(async()=>{try{const e=await(0,a.cached)("orders",I,()=>(0,d.getOrders)({status:"resting"}));e&&(t.orders=e.orders||[]),s()}catch{}},I)),r.push(setInterval(async()=>{try{const e=await(0,a.cached)("balance",P,()=>(0,d.getBalance)());e&&(t.balance=e.balance??0),s()}catch{}},P)),r.push(setInterval(async()=>{try{await L(t),s()}catch{}},E)),process.stdin.on("data",n=>{!function(e,t,n,o,s){const i=t.toString("utf-8"),r=27===t[0]&&1===t.length,a=27===t[0]&&91===t[1]&&65===t[2],c=27===t[0]&&91===t[1]&&66===t[2],l="\r"===i||"\n"===i,d=3===t[0];if(d||"q"===i&&"trade"!==e.mode)return void s();switch(e.error=null,e.mode){case"overview":j(i,a,c,l,e,n,o,s);break;case"detail":!function(e,t,n,o,s){t?(n.mode="overview",s()):"b"===e?(F(n,"buy"),s()):"s"===e?(F(n,"sell"),s()):"w"===e&&n.theses.length>0&&(n.prevMode="detail",n.mode="whatif",n.whatifThesisId=n.theses[0].id,z(n).then(s))}(i,r,e,0,o);break;case"liquidity":!function(e,t,n,o,s,i,r){if(o)s.mode=s.prevMode,r();else if("j"===e||n)s.liquiditySelectedIndex++,r();else if("k"===e||t)s.liquiditySelectedIndex=Math.max(0,s.liquiditySelectedIndex-1),r();else if("\t"===e){const e=Object.keys(u.TOPIC_SERIES),t=e.indexOf(s.liquidityTopic);s.liquidityTopic=e[(t+1)%e.length],s.liquiditySelectedIndex=0,U(s).then(r)}else"b"===e?(!function(e){const t=e.liquidityData.get(e.liquidityTopic)||[];if(0===t.length)return;const n=t[Math.min(e.liquiditySelectedIndex,t.length-1)];if(!n)return;e.prevMode=e.mode,e.mode="trade",e.tradeParams={ticker:n.ticker||"",side:"yes",action:"buy",qty:10,price:n.bestAsk??n.yes_ask??50},e.tradeCountdown=-1,e.tradeField="qty"}(s),r()):"r"===e&&U(s).then(r)}(i,a,c,r,e,0,o);break;case"whatif":!function(e,t,n,o,s,i,r,a){if(s)i.mode=i.prevMode,a();else if("j"===e||n){const e=(i.whatifResult?.scenarios?.length||1)-1;i.whatifScenarioIndex=Math.min(i.whatifScenarioIndex+1,e),a()}else"k"===e||t?(i.whatifScenarioIndex=Math.max(0,i.whatifScenarioIndex-1),a()):o&&a()}(i,a,c,l,r,e,0,o);break;case"trade":!function(e,t,n,o,s,i,r,a){if(s)return i.mode=i.prevMode,i.tradeParams=null,i.tradeCountdown=-1,void a();if(!i.tradeParams)return;"\t"===e?(i.tradeField="qty"===i.tradeField?"price":"qty",a()):t?("qty"===i.tradeField?i.tradeParams.qty=Math.min(i.tradeParams.qty+1,9999):i.tradeParams.price=Math.min(i.tradeParams.price+1,99),a()):n?("qty"===i.tradeField?i.tradeParams.qty=Math.max(i.tradeParams.qty-1,1):i.tradeParams.price=Math.max(i.tradeParams.price-1,1),a()):o&&i.tradeCountdown<0&&(i.tradeCountdown=3,a(),function(e,t,n){const o=()=>{e.tradeCountdown<=0||"trade"!==e.mode||(e.tradeCountdown--,n(),0===e.tradeCountdown?q(e,n):setTimeout(o,1e3))};setTimeout(o,1e3)}(i,0,a))}(i,a,c,l,r,e,0,o)}}(t,n,e,s,l)}),process.stdout.on("resize",()=>{e.resize(),s()})};const o=n(72222),s=n(42992),i=n(56661),r=n(77096),a=n(87783),c=n(11627),l=n(19218),d=n(96139),u=n(97325),p=n(34331),h=n(3322),m=n(21704),g=n(30012),f=n(75757),y=n(50511),$=n(98573),w=n(12423),k=n(72734),b=n(35301),v=n(82950),_=n(29405),S=n(67748),x=n(87009),C=15e3,O=3e4,I=1e4,P=3e4,T=6e4,E=6e4;let A=null;function M(){if(A)return A;try{const e=(0,c.loadConfig)();return e.apiKey?(A=new l.SFClient(e.apiKey,e.apiUrl),A):null}catch{return null}}async function R(e){const t=M(),[n,o,s,i]=await Promise.allSettled([(0,a.cached)("positions",C,()=>(0,d.getPositions)()),t?(0,a.cached)("theses",O,()=>t.listTheses()):Promise.resolve(null),(0,a.cached)("orders",I,()=>(0,d.getOrders)({status:"resting"})),(0,a.cached)("balance",P,()=>(0,d.getBalance)())]);if("fulfilled"===n.status&&n.value){const t=n.value,o=await Promise.allSettled(t.map(e=>(0,a.cached)(`price:${e.ticker}`,1e4,()=>(0,d.getMarketPrice)(e.ticker))));for(let e=0;e<t.length;e++){const n=o[e];"fulfilled"===n.status&&null!=n.value&&(t[e].current_value=n.value,t[e].unrealized_pnl=Math.round((n.value-t[e].average_price_paid)*t[e].quantity))}e.positions=t}const r=(0,c.loadConfig)();if(r.polymarketWalletAddress)try{const t=await(0,a.cached)("poly-positions",C,()=>(0,p.polymarketGetPositions)(r.polymarketWalletAddress));if(t&&Array.isArray(t)&&t.length>0)for(const n of t)e.positions.push({ticker:(n.title||n.slug||n.asset||"").slice(0,25),quantity:n.size||0,average_price_paid:Math.round(100*(n.avgPrice||0)),current_value:Math.round(100*(n.curPrice||n.currentPrice||0)),unrealized_pnl:Math.round(100*(n.cashPnl||0)),side:(n.outcome||"yes").toLowerCase(),venue:"polymarket"})}catch{}if("fulfilled"===o.status&&o.value){const t=o.value;e.theses=t.theses||t||[]}if("fulfilled"===s.status&&s.value&&(e.orders=s.value.orders||[]),"fulfilled"===i.status&&i.value&&(e.balance=i.value.balance??0),t&&e.theses.length>0){const n=await Promise.allSettled(e.theses.map(e=>(0,a.cached)(`ctx:${e.id}`,O,()=>t.getContext(e.id))));for(let t=0;t<e.theses.length;t++){const o=n[t];"fulfilled"===o.status&&o.value&&e.contexts.set(e.theses[t].id,o.value)}}if(N(e),await L(e),t)try{const n=await(0,a.cached)("feed",T,()=>t.getFeed(48)),o=n.entries||n.feed||n;Array.isArray(o)&&(e.signals=o)}catch{}if(t)try{const n=await(0,a.cached)("intents",I,()=>t.request("GET","/api/intents?active=true"));e.intents=n?.intents||[]}catch{}try{const t=await(0,a.cached)("traditional",O,()=>fetch("https://simplefunctions.dev/api/public/markets").then(e=>e.ok?e.json():null));t&&(Array.isArray(t)?e.traditionalMarkets=t:"object"==typeof t&&(e.traditionalMarkets=Object.entries(t).map(([e,t])=>({symbol:e,price:t.price||t.value||0,changePct:t.changePct||t.pctChange||t.change_pct||0}))))}catch{}!function(e){const t=[];for(const[,n]of e.contexts){if(n?.milestones)for(const e of n.milestones)t.push(e);if(n?.upcomingEvents)for(const e of n.upcomingEvents)t.push(e)}t.sort((e,t)=>new Date(e.timestamp||e.date||e.time||0).getTime()-new Date(t.timestamp||t.date||t.time||0).getTime()),e.events=t.filter(e=>new Date(e.timestamp||e.date||e.time||0).getTime()>Date.now())}(e),function(e){const t=new Date,n=t.getUTCDay();e.exchangeOpen=n>=1&&n<=5}(e),e.lastRefresh.all=Date.now()}function N(e){const t=[];for(const[,n]of e.contexts)if(n?.edges)for(const e of n.edges)t.push(e);const n=new Map;for(const e of t){const t=e.marketId||e.ticker||e.market,o=n.get(t);(!o||Math.abs(e.edge??0)>Math.abs(o.edge??0))&&n.set(t,e)}const o=new Set(e.positions.map(e=>e.ticker_symbol||e.ticker));e.edges=[...n.values()].filter(e=>!o.has(e.marketId||e.ticker)).sort((e,t)=>Math.abs(t.edge??0)-Math.abs(e.edge??0))}async function L(e){const t=e.positions.map(e=>e.ticker).filter(Boolean);if(0!==t.length)try{const n=Math.floor(Date.now()/1e3),o=n-604800,s=await(0,a.cached)("candles",E,()=>(0,d.getBatchCandlesticks)({tickers:t,startTs:o,endTs:n}));for(const t of s)if(t.market_ticker&&t.candlesticks){const n=t.candlesticks.map(e=>{const t=parseFloat(e.yes_bid?.close_dollars||"0"),n=parseFloat(e.yes_ask?.close_dollars||"0"),o=t>0&&n>0?(t+n)/2:t||n,s=parseFloat(e.price?.close_dollars||"0")||o;return{close:Math.round(100*s),date:e.end_period_ts?new Date(1e3*e.end_period_ts).toISOString().slice(0,10):"",end_period_ts:e.end_period_ts}}).filter(e=>e.close>0);e.candleCache.set(t.market_ticker,n)}}catch{}}function D(e,t){switch((0,w.renderMarketBar)(e,0,t),(0,$.renderStatusBar)(e,1,t),(0,k.renderCommandBar)(e,e.rows-1,t),t.mode){case"overview":K(e,t);break;case"detail":(0,b.renderDetail)(e,(0,s.fullLayout)(e.cols,e.rows),t);break;case"liquidity":(0,v.renderLiquidity)(e,(0,s.fullLayout)(e.cols,e.rows),t);break;case"whatif":(0,_.renderWhatif)(e,(0,s.fullLayout)(e.cols,e.rows),t);break;case"trade":"detail"===t.prevMode?(0,b.renderDetail)(e,(0,s.fullLayout)(e.cols,e.rows),t):K(e,t),(0,S.renderTrade)(e,(0,s.fullLayout)(e.cols,e.rows),t)}e.flush()}function K(e,t){const n=e.cols<80,o=n?(0,s.narrowLayout)(e.cols,e.rows):(0,s.overviewLayout)(e.cols,e.rows);if(!n){const t=Math.floor(.55*e.cols);for(let n=2;n<e.rows-1;n++)e.write(n,t,"│",r.CLR.borderDim)}for(const n of o)switch(n.name){case"positions":(0,h.renderPortfolio)(e,n,t);break;case"thesis":(0,m.renderThesis)(e,n,t);break;case"edges":(0,g.renderEdges)(e,n,t);break;case"signals":(0,y.renderSignals)(e,n,t);break;case"intents":(0,x.renderIntents)(e,n,t);break;case"orders":(0,f.renderOrders)(e,n,t)}}function j(e,t,n,o,s,i,r,c){const l="positions"===s.focusArea?s.positions:"edges"===s.focusArea?s.edges:s.intents||[],d=Math.max(0,l.length-1);if("j"===e||n)s.selectedIndex=Math.min(s.selectedIndex+1,d),r();else if("k"===e||t)s.selectedIndex=Math.max(s.selectedIndex-1,0),r();else if(o){if("positions"===s.focusArea&&s.positions.length>0){const e=s.positions[s.selectedIndex];s.detailTicker=e?.ticker||null,s.prevMode="overview",s.mode="detail",r()}}else if("l"===e)s.prevMode="overview",s.mode="liquidity",s.liquiditySelectedIndex=0,U(s).then(r);else if("w"===e)s.theses.length>0&&(s.prevMode="overview",s.mode="whatif",s.whatifThesisId=s.theses[0].id,z(s).then(r));else if("b"===e)F(s,"buy"),r();else if("s"===e)F(s,"sell"),r();else if("e"===e)(async function(e){const t=M();if(!t||0===e.theses.length)return;try{e.error=null;const n=e.theses[0];await t.evaluate(n.id),(0,a.invalidateAll)(),await R(e)}catch(t){e.error=t instanceof Error?t.message.slice(0,40):"Evaluation failed"}})(s).then(r);else if("r"===e)(0,a.invalidateAll)(),R(s).then(r);else if("i"===e){if("edges"===s.focusArea&&s.edges.length>0){const e=s.edges[s.selectedIndex];if(e){const t=e.marketId||e.ticker||"";F(s,"buy"),s.tradeParams&&(s.tradeParams.ticker=t,s.tradeParams.side=e.direction||"yes",s.tradeParams.price=e.marketPrice||50),r()}}}else if("x"===e){if("intents"===s.focusArea&&s.intents.length>0){const e=s.intents[s.selectedIndex];if(e?.id){const t=M();t&&t.request("DELETE",`/api/intents/${e.id}`).then(()=>{(0,a.invalidateAll)(),R(s).then(r)}).catch(()=>{s.error="Failed to cancel intent",r()})}}}else if(e>="1"&&e<="9"){const t=parseInt(e)-1;t<s.theses.length&&(s.activeThesisIndex=t,r())}else"\t"===e&&("positions"===s.focusArea?s.focusArea="edges":"edges"===s.focusArea?s.focusArea="intents":s.focusArea="positions",s.selectedIndex=0,r())}function F(e,t){let n="";if("positions"===e.focusArea&&e.positions.length>0){const t=e.positions[e.selectedIndex];n=t?.ticker_symbol||t?.ticker||""}else if("edges"===e.focusArea&&e.edges.length>0){const t=e.edges[e.selectedIndex];n=t?.ticker||t?.marketId||""}else e.detailTicker&&(n=e.detailTicker);n?(e.prevMode=e.mode,e.mode="trade",e.tradeParams={ticker:n,side:"yes",action:t,qty:10,price:50},e.tradeCountdown=-1,e.tradeField="qty"):e.error="No market selected"}async function q(e,t){if(e.tradeParams){try{if(!(0,c.loadConfig)().tradingEnabled)return e.error="Trading disabled. Run: sf setup --enable-trading",e.tradeCountdown=-1,void t();await(0,d.createOrder)({ticker:e.tradeParams.ticker,side:e.tradeParams.side,action:e.tradeParams.action,type:"limit",count:e.tradeParams.qty,yes_price:e.tradeParams.price}),e.error=null,e.mode=e.prevMode,e.tradeParams=null,e.tradeCountdown=-1,(0,a.invalidateAll)(),await R(e)}catch(t){e.error=t instanceof Error?t.message.slice(0,40):"Trade failed",e.tradeCountdown=-1}t()}}async function U(e){const t=e.liquidityTopic,n=u.TOPIC_SERIES[t];if(n)try{const o=await Promise.allSettled(n.map(e=>(0,a.cached)(`liq:${e}`,3e4,async()=>{const t=`https://api.elections.kalshi.com/trade-api/v2/markets?series_ticker=${e}&status=open&limit=200`,n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)return[];return(await n.json()).markets||[]}))),s=[];for(const e of o)"fulfilled"===e.status&&Array.isArray(e.value)&&s.push(...e.value);e.liquidityData.set(t,[...s]);const i=8;for(let n=0;n<s.length;n+=i){const o=s.slice(n,n+i),r=await Promise.allSettled(o.map(e=>(0,a.cached)(`ob:${e.ticker}`,3e4,()=>(0,d.getPublicOrderbook)(e.ticker)).then(t=>({mkt:e,ob:t}))));for(const e of r){if("fulfilled"!==e.status||!e.value.ob)continue;const{mkt:t,ob:n}=e.value,o=(n.yes_dollars||[]).map(e=>({price:Math.round(100*parseFloat(e[0])),qty:parseFloat(e[1])})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price),s=(n.no_dollars||[]).map(e=>({price:Math.round(100*parseFloat(e[0])),qty:parseFloat(e[1])})).filter(e=>e.price>0).sort((e,t)=>t.price-e.price);t.bestBid=o.length>0?o[0].price:0,t.bestAsk=s.length>0?100-s[0].price:100,t.spread=t.bestAsk-t.bestBid,t.totalDepth=o.slice(0,3).reduce((e,t)=>e+t.qty,0)+s.slice(0,3).reduce((e,t)=>e+t.qty,0)}e.liquidityData.set(t,[...s])}}catch(t){e.error="Failed to load liquidity data"}}async function z(e){if(M()&&e.whatifThesisId)try{const t=e.contexts.get(e.whatifThesisId);if(!t)return;const n=(t.causalTree?.nodes||t.nodes||[]).slice(0,10).map(e=>({name:e.name||e.title||e.id,nodeId:e.id,description:`Set ${e.name||e.id} to low probability`}));e.whatifResult={scenarios:n,before:{confidence:e.theses[0]?.confidence,edges:e.edges.slice(0,5)},after:null}}catch{e.error="Failed to load what-if data"}}},42992:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.overviewLayout=function(e,t){const n=t-3,o=Math.floor(.55*e),s=e-o-1,i=o+1,r=Math.max(Math.floor(.4*n),5),a=Math.max(Math.floor(.3*n),4),c=Math.max(n-r-a,3);return[{name:"positions",row:2,col:0,width:o,height:r},{name:"thesis",row:2,col:i,width:s,height:r},{name:"edges",row:2+r,col:0,width:o,height:a},{name:"signals",row:2+r,col:i,width:s,height:a},{name:"intents",row:2+r+a,col:0,width:o,height:c},{name:"orders",row:2+r+a,col:i,width:s,height:c}]},t.fullLayout=function(e,t){return{name:"main",row:2,col:0,width:e,height:t-3}},t.narrowLayout=function(e,t){const n=t-3,o=Math.floor(n/4);return[{name:"positions",row:2,col:0,width:e,height:o},{name:"edges",row:2+o,col:0,width:e,height:o},{name:"intents",row:2+2*o,col:0,width:e,height:o},{name:"thesis",row:2+3*o,col:0,width:e,height:n-3*o}]}},72222:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ScreenBuffer=void 0;t.ScreenBuffer=class{front;back;cols;rows;constructor(){this.cols=process.stdout.columns||120,this.rows=process.stdout.rows||40,this.front=this.createBuffer(),this.back=this.createBuffer()}createBuffer(){return Array.from({length:this.rows},()=>Array.from({length:this.cols},()=>({char:" ",fg:"",bg:""})))}write(e,t,n,o="",s=""){if(e<0||e>=this.rows)return;let i=t;for(let t=0;t<n.length&&i<this.cols;t++)i>=0&&(this.back[e][i]={char:n[t],fg:o,bg:s}),i++}writeStyled(e,t,n){let o=t;for(const t of n)for(let n=0;n<t.text.length&&o<this.cols;n++)e>=0&&e<this.rows&&o>=0&&(this.back[e][o]={char:t.text[n],fg:t.fg||"",bg:t.bg||""}),o++}fill(e,t,n,o,s=" ",i="",r=""){for(let a=e;a<e+o&&a<this.rows;a++)for(let e=t;e<t+n&&e<this.cols;e++)a>=0&&e>=0&&(this.back[a][e]={char:s,fg:i,bg:r})}flush(){let e="",t="",n="";for(let o=0;o<this.rows;o++)for(let s=0;s<this.cols;s++){const i=this.front[o][s],r=this.back[o][s];i.char===r.char&&i.fg===r.fg&&i.bg===r.bg||(e+=`[${o+1};${s+1}H`,r.fg===t&&r.bg===n||(e+="",r.fg&&(e+=r.fg),r.bg&&(e+=r.bg),t=r.fg,n=r.bg),e+=r.char)}e&&(e+="",process.stdout.write(e)),this.front=this.back,this.back=this.createBuffer()}resize(){this.cols=process.stdout.columns||120,this.rows=process.stdout.rows||40,this.front=this.createBuffer(),this.back=this.createBuffer(),process.stdout.write("")}}},56661:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.initialState=function(){return{mode:"overview",prevMode:"overview",selectedIndex:0,focusArea:"positions",detailTicker:null,liquidityTopic:"oil",liquiditySelectedIndex:0,whatifScenarioIndex:0,whatifResult:null,whatifThesisId:null,tradeParams:null,tradeCountdown:-1,tradeField:"qty",activeThesisIndex:0,positions:[],theses:[],contexts:new Map,edges:[],orders:[],signals:[],events:[],intents:[],traditionalMarkets:[],balance:0,candleCache:new Map,liquidityData:new Map,error:null,lastRefresh:{},exchangeOpen:null}}},72734:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderCommandBar=function(e,t,n){const r=e.cols;e.fill(t,0,r,1," ","",s);const a=i[n.mode]||i.overview,c="overview"===n.mode?n.focusArea.toUpperCase():"";let l=1;c&&(e.write(t,l,"●",o.CLR.emerald,s),l+=2,e.write(t,l,c,o.CLR.dim,s),l+=c.length+2);for(const n of a){if(l+n.key.length+n.label.length+3>r-2)break;e.write(t,l,n.key,o.CLR.emerald,s),l+=n.key.length,e.write(t,l," "+n.label,o.CLR.dim,s),l+=n.label.length+3}if(n.error){const i=n.error.slice(0,30),a=r-i.length-2;a>l&&e.write(t,a,i,o.CLR.red,s)}};const o=n(77096),s=(0,o.bgRgb)(12,12,16),i={overview:[{key:"j/k",label:"nav"},{key:"Tab",label:"focus"},{key:"⏎",label:"detail"},{key:"i",label:"intent"},{key:"x",label:"cancel"},{key:"1-9",label:"thesis"},{key:"l",label:"liquidity"},{key:"w",label:"whatif"},{key:"b/s",label:"trade"},{key:"r",label:"refresh"},{key:"q",label:"quit"}],detail:[{key:"b",label:"buy"},{key:"s",label:"sell"},{key:"w",label:"whatif"},{key:"Esc",label:"back"},{key:"q",label:"quit"}],liquidity:[{key:"j/k",label:"nav"},{key:"Tab",label:"topic"},{key:"b",label:"buy"},{key:"r",label:"refresh"},{key:"Esc",label:"back"}],whatif:[{key:"j/k",label:"nav"},{key:"⏎",label:"apply"},{key:"Esc",label:"back"}],trade:[{key:"↑↓",label:"adjust"},{key:"Tab",label:"field"},{key:"⏎",label:"confirm"},{key:"Esc",label:"cancel"}]}},35301:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderDetail=function(e,t,n){(0,o.drawBorder)(e,t,"POSITION DETAIL");const i=t.col+2,r=t.width-4,a=n.positions.find(e=>(e.ticker_symbol||e.ticker)===n.detailTicker)||n.positions[0];if(!a)return void e.write(t.row+2,i,"No position selected",o.CLR.dim);const c=a.ticker_symbol||a.ticker||"???",l=a.quantity??0,d=a.average_price_paid??a.cost_basis??0,u=a.current_value??d,p=(u-d)*l,h=p/100,m=p>=0?o.CLR.green:o.CLR.red,g=a.side||"yes";let f=1;e.writeStyled(t.row+f,i,[{text:(0,o.fit)(c,30),fg:o.CLR.white},{text:` ${g.toUpperCase()} `,fg:o.CLR.emerald},{text:` qty: ${l}`,fg:o.CLR.dim}]),f++,e.writeStyled(t.row+f,i,[{text:`Entry: ${d.toFixed(0)}¢`,fg:o.CLR.dim},{text:` Current: ${u.toFixed(0)}¢`,fg:o.CLR.text},{text:` P&L: ${h>=0?"+":""}$${Math.abs(h).toFixed(2)}`,fg:m}]),f++;const y=a.expiration_time||a.expiry||a.close_time||"";if(y){const n=new Date(y),s=Math.ceil((n.getTime()-Date.now())/864e5);e.write(t.row+f,i,`Expiry: ${n.toISOString().slice(0,10)} (${s}d)`,o.CLR.dim)}f++,(0,o.drawHDivider)(e,t,f),f++;const $=Math.min(8,Math.floor((t.height-f-8)/2)+4),w=n.candleCache.get(c)||[];if(w.length>1){const n=w.map(e=>((e.close??0)-d)*l/100),a=w.map(e=>{const t=e.date?new Date(e.date):new Date(e.end_period_ts?1e3*e.end_period_ts:0);return`${t.getMonth()+1}/${t.getDate()}`});e.write(t.row+f,i,"Daily P&L ($)",o.CLR.title),f++,(0,s.drawChart)(e,t.row+f,i,r,$,n,a),f+=$+1}else e.write(t.row+f,i,"No chart data available",o.CLR.dim),f+=2;f<t.height-5&&((0,o.drawHDivider)(e,t,f),f++);const k=Math.floor(r/2)-1,b=t.row+f,v=t.height-f-1;e.write(b,i,"Causal Tree",o.CLR.title);let _=null;for(const[,e]of n.contexts){if((e?.edges||[]).some(e=>e.marketId===c||e.ticker===c)){_=e;break}}const S=[];!function e(t,n=0){for(const o of t)S.push({...o,depth:n}),o.children&&e(o.children,n+1)}(_?.causalTree?.nodes||[]);const x=S.filter(e=>e.depth<=1).slice(0,v-1);for(let t=0;t<x.length;t++){const n=x[t],s=" ".repeat(n.depth+1),r=n.label||n.claim||n.name||n.id||"?",a=null!=n.probability?`${Math.round(100*n.probability)}%`:"";e.writeStyled(b+1+t,i,[{text:s+(0,o.fit)(r,k-s.length-5),fg:o.CLR.text},{text:(0,o.fit)(a,5,"right"),fg:o.CLR.emerald}])}0===x.length&&e.write(b+1,i," (no context data)",o.CLR.dim);const C=i+k+2;e.write(b,C,"Orderbook",o.CLR.title);const O=_?.edges?.find(e=>e.marketId===c||e.ticker===c),I=O?.orderbook;if(I){const t=I.bidPrice??I.bestBid??0,n=I.askPrice??I.bestAsk??0,s=I.spread??n-t;e.writeStyled(b+1,C,[{text:"Bid: ",fg:o.CLR.dim},{text:`${t}¢`,fg:o.CLR.green},{text:" Ask: ",fg:o.CLR.dim},{text:`${n}¢`,fg:o.CLR.red}]),e.writeStyled(b+2,C,[{text:"Spread: ",fg:o.CLR.dim},{text:`${s}¢`,fg:s<=2?o.CLR.green:s<=5?o.CLR.yellow:o.CLR.red}]),null!=I.bidDepth&&e.writeStyled(b+3,C,[{text:"Depth: ",fg:o.CLR.dim},{text:`bid ${I.bidDepth}`,fg:o.CLR.dim},{text:` / ask ${I.askDepth}`,fg:o.CLR.dim}])}else e.write(b+1,C," (no orderbook data)",o.CLR.dim)};const o=n(77096),s=n(14916)},30012:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderEdges=function(e,t,n){(0,o.drawBorder)(e,t,"TOP EDGES");const i=t.col+2,r=t.width-4,a=t.height-2,c=new Set(n.positions.map(e=>e.ticker)),l=n.edges.filter(e=>!c.has(e.marketId||e.ticker||"")),d=l.slice(0,Math.min(a,8));if(0===d.length)return void e.write(t.row+1,i,"No unpositioned edges",o.CLR.dim);const u=Math.max(...d.map(e=>Math.abs(e.edge??e.edgeSize??0)),1);for(let a=0;a<d.length;a++){const c=d[a],l=t.row+1+a,p="edges"===n.focusArea&&n.selectedIndex===a,h=p?"▸":" ",m=c.market||c.marketTitle||c.marketId||"???",g=c.edge??c.edgeSize??0,f=`${g>0?"+":""}${g.toFixed(0)}¢`,y=`${c.marketPrice??"?"}¢`,$="polymarket"===c.venue?"P":"K",w=c.orderbook?.liquidityScore||"",k="high"===w?"H":"medium"===w?"M":"low"===w?"L":"",b="high"===w?o.CLR.green:"low"===w?o.CLR.yellow:o.CLR.dim,v=6,_=Math.abs(g)/u,S=Math.floor(_*v),x=_*v-S,C=Math.min(Math.floor(8*x),7),O=s[7].repeat(S)+(x>.1?s[C]:""),I=g>0?o.CLR.emerald:o.CLR.red,P=Math.max(r-28,8);e.writeStyled(l,i,[{text:`${h}${$} `,fg:p?o.CLR.white:o.CLR.dim},{text:(0,o.fit)(m,P),fg:p?o.CLR.white:o.CLR.text},{text:(0,o.fit)(y,5,"right"),fg:o.CLR.dim},{text:" "+(0,o.fit)(O,v),fg:I},{text:(0,o.fit)(f,5,"right"),fg:o.CLR.emerald},{text:k?` ${k}`:"",fg:b}])}};const o=n(77096),s="▏▎▍▌▋▊▉█"},87009:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderIntents=function(e,t,n){(0,o.drawBorder)(e,t,"INTENTS");const i=t.col+2,r=t.width-4,a=t.height-2,c=n.intents||[];if(0===c.length)return e.write(t.row+1,i,"No active intents",o.CLR.dim,o.CLR.bgPanel),void e.write(t.row+2,i,"Press i on an edge to create one",o.CLR.veryDim,o.CLR.bgPanel);for(let l=0;l<Math.min(c.length,a);l++){const a=c[l],d=t.row+1+l,u="intents"===n.focusArea&&n.selectedIndex===l,p=u?o.CLR.bgSelected:o.CLR.bgPanel;u&&e.fill(d,t.col+1,t.width-2,1," ","",p);const h=a.status||"pending",m=s[h]||o.CLR.dim,g=(a.action||"buy").toUpperCase(),f=(a.direction||"yes").toUpperCase(),y=(a.marketId||a.market_id||"???").slice(0,16),$=a.targetQuantity||a.target_quantity||0,w=a.filledQuantity||a.filled_quantity||0,k=a.maxPrice||a.max_price,b=k?`≤${k}¢`:"mkt",v=w>0?`${w}/${$}`:`${$}`,_=Math.max(r-26,6);e.writeStyled(d,i,[{text:(0,o.fit)(h,9),fg:m,bg:p},{text:` ${g} `,fg:u?o.CLR.white:o.CLR.text,bg:p},{text:(0,o.fit)(y,_),fg:u?o.CLR.white:o.CLR.text,bg:p},{text:` ${f} ${v} ${b}`,fg:o.CLR.dim,bg:p}])}};const o=n(77096),s={pending:o.CLR.yellow,armed:o.CLR.emerald,triggered:o.CLR.white,executing:o.CLR.cyan,filled:o.CLR.green,partial:o.CLR.yellow,expired:o.CLR.veryDim,cancelled:o.CLR.veryDim,rejected:o.CLR.red}},82950:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderLiquidity=function(e,t,n){(0,o.drawBorder)(e,t,"LIQUIDITY SCANNER");const a=t.col+2,c=t.width-4;let l=1;const d=Object.keys(s.TOPIC_SERIES);let u=a;for(const s of d){const a=s===n.liquidityTopic,c=` ${s.toUpperCase()} `,d=a?o.CLR.emerald:o.CLR.dim,p=a?i:r;e.write(t.row+l,u,c,d,p),u+=c.length+1}l+=2;const p=Math.min(28,Math.floor(.35*c));e.writeStyled(t.row+l,a,[{text:(0,o.fit)("Market",p),fg:o.CLR.title},{text:(0,o.fit)("Bid¢",8,"right"),fg:o.CLR.title},{text:(0,o.fit)("Ask¢",8,"right"),fg:o.CLR.title},{text:(0,o.fit)("Spread",8,"right"),fg:o.CLR.title},{text:(0,o.fit)("Depth",8,"right"),fg:o.CLR.title},{text:" ",fg:o.CLR.dim}]),l++;for(let n=a;n<a+c;n++)e.write(t.row+l,n,"─",o.CLR.borderDim);l++;const h=n.liquidityData.get(n.liquidityTopic)||[],m=new Set(n.positions.map(e=>e.ticker_symbol||e.ticker)),g=(t.height,function(e){const t=new Map;for(const n of e){const e=(n.ticker||"").toUpperCase();let o="Other";if(e.includes("-D")||e.includes("DAILY"))o="Daily";else if(e.includes("-W")||e.includes("WEEKLY"))o="Weekly";else if(e.includes("-M")||e.match(/-\d{2}(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d{2}/))o="Monthly";else{const e=n.expiration_time||n.close_time||"";if(e){const t=Math.ceil((new Date(e).getTime()-Date.now())/864e5);o=t<=7?"Weekly":t<=35?"Monthly":"Long-term"}}t.has(o)||t.set(o,[]),t.get(o).push(n)}const n=["Daily","Weekly","Monthly","Long-term","Other"],o=new Map;for(const e of n)t.has(e)&&o.set(e,t.get(e));return o}(h));let f=0;for(const[s,i]of g){if(l>=t.row+t.height-4)break;e.write(t.row+l,a,` ${s}`,o.CLR.title),l++;for(const s of i){if(l>=t.row+t.height-4)break;const i=n.liquiditySelectedIndex===f,r=i?"▸":" ",c=m.has(s.ticker)?"← held":"",d=s.ticker||"???",u=s.bestBid??s.yes_bid??0,h=s.bestAsk??s.yes_ask??0,g=s.spread??h-u,y=s.totalDepth??s.depth??0,$=g<=2?o.CLR.green:g<=5?o.CLR.yellow:o.CLR.red;e.writeStyled(t.row+l,a,[{text:r+" ",fg:i?o.CLR.emerald:o.CLR.dim},{text:(0,o.fit)(d,p-2),fg:o.CLR.text},{text:(0,o.fit)(String(u),8,"right"),fg:o.CLR.green},{text:(0,o.fit)(String(h),8,"right"),fg:o.CLR.red},{text:(0,o.fit)(String(g),8,"right"),fg:$},{text:(0,o.fit)(String(y),8,"right"),fg:o.CLR.dim},{text:c?` ${c}`:"",fg:o.CLR.emerald}]),l++,f++}}if(h.length>0){const s=Math.min(n.liquiditySelectedIndex,h.length-1),i=Array.from(g.values()).flat(),r=i[s]||i[0];if(r){const n=t.row+t.height-3;e.write(n,a,(0,o.fit)(`▶ ${r.ticker||""}`,c),o.CLR.emerald);const s=null!=r.slippage?`Slippage: ~${r.slippage}¢`:"",i=null!=r.edge?`Edge: ${r.edge>=0?"+":""}${r.edge}¢`:"";e.writeStyled(n+1,a,[{text:s?(0,o.fit)(s,20):"",fg:o.CLR.dim},{text:i?(0,o.fit)(i,20):"",fg:r.edge>=0?o.CLR.green:o.CLR.red}])}}};const o=n(77096),s=n(97325),i=(0,o.bgRgb)(30,30,35),r=(0,o.bgRgb)(16,16,18)},12423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderMarketBar=function(e,t,n){const i=e.cols;e.fill(t,0,i,1," ","",s);const r=n.traditionalMarkets||[];if(0===r.length)return void e.write(t,1,"SimpleFunctions",o.CLR.dim,s);const a=r.slice(0,6),c=Math.floor((i-2)/a.length);for(let n=0;n<a.length;n++){const i=a[n],r=1+n*c,l=(i.symbol||i.name||"???").replace("SPDR ","").replace(" ETF","").slice(0,5),d=i.changePct??i.change_pct??i.pctChange??0,u=i.price??i.value??0,p=u>100?Math.round(u).toLocaleString():u.toFixed(2),h=`${d>=0?"+":""}${d.toFixed(1)}%`,m=d>=0?o.CLR.green:o.CLR.red;e.write(t,r,l,o.CLR.dim,s),e.write(t,r+l.length+1,p,o.CLR.text,s),e.write(t,r+l.length+1+p.length+1,h,m,s)}};const o=n(77096),s=(0,o.bgRgb)(12,12,16)},75757:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderOrders=function(e,t,n){(0,o.drawBorder)(e,t,"ORDERS");const s=t.col+2,i=(t.width,t.height-2);if(0===n.orders.length)return void e.write(t.row+1,s,"No resting orders",o.CLR.dim);for(let r=0;r<Math.min(n.orders.length,i);r++){const i=n.orders[r],a=t.row+1+r,c=(i.ticker||"???").slice(0,10),l=Math.round(parseFloat(i.remaining_count_fp||i.initial_count_fp||"0")),d=parseFloat(i.yes_price_dollars||"0"),u=Math.round(100*d),p=i.status||"resting",h=`${l}@${u}¢`,m=new Date(i.created_time||Date.now()).getTime(),g=Math.floor((Date.now()-m)/864e5),f=0===g?"<1d":`${g}d`,y=g>3,$=y?"⚠ ":" ";e.writeStyled(a,s,[{text:$,fg:y?o.CLR.yellow:o.CLR.dim},{text:(0,o.fit)(c,12),fg:o.CLR.text},{text:(0,o.fit)(h,10),fg:o.CLR.dim},{text:(0,o.fit)(p,10),fg:"filled"===p?o.CLR.green:o.CLR.dim},{text:(0,o.fit)(f,4,"right"),fg:y?o.CLR.yellow:o.CLR.dim}])}};const o=n(77096)},3322:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderPortfolio=function(e,t,n){(0,o.drawBorder)(e,t,"POSITIONS");const s=t.col+2,i=t.width-4,r=t.height-2;let a=0;if(0===n.positions.length)return e.write(t.row+1,s,"No positions",o.CLR.dim,o.CLR.bgPanel),void e.write(t.row+2,s,"sf buy TICKER QTY --price CENTS",o.CLR.veryDim,o.CLR.bgPanel);const c=[...n.positions].sort((e,t)=>{const n=Math.abs(((e.current_value||e.average_price_paid||0)-(e.average_price_paid||0))*(e.quantity||0));return Math.abs(((t.current_value||t.average_price_paid||0)-(t.average_price_paid||0))*(t.quantity||0))-n});for(const l of c){if(a+1>=r)break;const d=t.row+1+a,u=c.indexOf(l),p="positions"===n.focusArea&&n.selectedIndex===u,h=p?o.CLR.bgSelected:o.CLR.bgPanel;p&&e.fill(d,t.col+1,t.width-2,2," ","",h);const m=l.ticker||"???",g="polymarket"===l.venue?"P":"K",f="polymarket"===l.venue?o.CLR.purple:o.CLR.cyan;if(e.writeStyled(d,s,[{text:g+" ",fg:f,bg:h},{text:(0,o.fit)(m,Math.min(i-2,28)),fg:p?o.CLR.white:o.CLR.text,bg:h}]),a+1<r){const t=l.quantity??0,i=l.average_price_paid??0,r=l.current_value??i,a=(r-i)*t/100,c=(a>=0?"+$":"-$")+Math.abs(a).toFixed(2),u=a>=0?o.CLR.green:o.CLR.red,p=[{text:` ${(0,o.compact)(t)} @ ${i}¢`,fg:o.CLR.dim,bg:h},{text:` → ${r}¢ `,fg:o.CLR.dim,bg:h},{text:(0,o.fit)(c,9),fg:u,bg:h}],g=n.candleCache.get(m);if(g&&g.length>1){const e=g.slice(-7).map(e=>((e.close??0)-i)*t),n=(0,o.sparkline)(e,e=>e>=0?o.CLR.green:o.CLR.red);for(const e of n)p.push({...e,bg:h})}e.writeStyled(d+1,s,p)}a+=2}};const o=n(77096)},50511:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderSignals=function(e,t,n){(0,o.drawBorder)(e,t,"FEED");const s=t.col+2,i=t.width-4,r=t.height-2,a=n.signals.sort((e,t)=>{const n=new Date(e.evaluatedAt||e.timestamp||e.time||0).getTime();return new Date(t.evaluatedAt||t.timestamp||t.time||0).getTime()-n});if(0===a.length)return void e.write(t.row+1,s,"No recent signals",o.CLR.dim);for(let n=0;n<Math.min(a.length,r);n++){const r=a[n],c=t.row+1+n,l=r.confidenceDelta??r.delta??r.change??0,d=r.summary||r.title||r.content||"???",u=r.evaluatedAt||r.timestamp||r.time||"";let p=" ";if(u){const e=new Date(u);p=`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}const h="number"!=typeof l||l>=0,m="number"==typeof l&&Math.abs(l)>=.001,g=m?h?"▲":"▼":" ",f=h?o.CLR.green:o.CLR.red,y=m?`${l>0?"+":""}${Math.round(100*l)}%`:"",$=i-14;e.writeStyled(c,s,[{text:p,fg:o.CLR.veryDim},{text:` ${g}`,fg:m?f:o.CLR.dim},{text:(0,o.fit)(y,5,"right"),fg:m?f:o.CLR.dim},{text:" "+(0,o.fit)(d,$),fg:o.CLR.text}])}};const o=n(77096)},98573:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderStatusBar=function(e,t,n){const r=e.cols;e.fill(t,0,r,1," ","",s);let a=0,c=0;for(const e of n.positions){const t=e.average_price_paid??e.cost_basis??0,n=e.current_value??t,o=e.quantity??0;a+=(n-t)*o,c+=t*o}const l=a/100,d=c>0?a/c*100:0,u=l>=0?o.CLR.green:o.CLR.red;let p=1;const h=l>=0?"+":"",m=`${h}$${Math.abs(l).toFixed(2)}`,g=`${h}${d.toFixed(1)}%`;if(e.write(t,p,"P&L ",o.CLR.dim,s),p+=4,e.write(t,p,m,u,s),p+=m.length+1,e.write(t,p,g,u,s),p+=g.length+1,e.write(t,p,i,o.CLR.veryDim,s),p+=2,e.write(t,p,`$${n.balance.toFixed(2)}`,o.CLR.text,s),p+=`$${n.balance.toFixed(2)}`.length+1,n.theses.length>0){e.write(t,p,i,o.CLR.veryDim,s),p+=2;const r=n.theses[n.activeThesisIndex||0]||n.theses[0],a=(r.title||"Thesis").slice(0,18),c=null!=r.confidence?`${Math.round(100*(r.confidence??0))}%`:"?%";if(e.write(t,p,a,o.CLR.dim,s),p+=a.length+1,e.write(t,p,c,o.CLR.emerald,s),p+=c.length+1,n.theses.length>1){const i=`[${(n.activeThesisIndex||0)+1}/${n.theses.length}]`;e.write(t,p,i,o.CLR.veryDim,s),p+=i.length+1}}const f=(n.intents||[]).filter(e=>["pending","armed","triggered","executing"].includes(e.status));if(f.length>0){e.write(t,p,i,o.CLR.veryDim,s),p+=2;const n=`${f.length} intent${f.length>1?"s":""}`;e.write(t,p,n,o.CLR.emerald,s),p+=n.length+1}if(null!==n.exchangeOpen){e.write(t,p,i,o.CLR.veryDim,s),p+=2;const r=n.exchangeOpen?"OPEN":"CLOSED",a=n.exchangeOpen?o.CLR.green:o.CLR.red;e.write(t,p,r,a,s)}const y=(new Date).toISOString().slice(11,19)+" UTC";e.write(t,r-y.length-1,y,o.CLR.veryDim,s)};const o=n(77096),s=(0,o.bgRgb)(16,16,20),i="│"},21704:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderThesis=function(e,t,n){(0,o.drawBorder)(e,t,"THESIS");const s=t.col+2,i=t.width-4,r=t.height-2;let a=0;for(const c of n.theses){if(a>=r-2)break;const n=t.row+1+a,l=c.title||c.short_title||"???",d=c.confidence??c.current_confidence??0,u=`${Math.round(100*d)}%`,p=c.lastEvaluation?.confidenceDelta??c.confidence_delta??0;let h,m,g;p>=.02?(h="▲",m=o.CLR.green,g=`+${Math.round(100*p)}`):p<=-.02?(h="▼",m=o.CLR.red,g=`${Math.round(100*p)}`):(h="─",m=o.CLR.dim,g=p>=0?`+${Math.round(100*p)}`:`${Math.round(100*p)}`);const f=i-10;e.writeStyled(n,s,[{text:(0,o.fit)(l,f),fg:o.CLR.text},{text:(0,o.fit)(u,5,"right"),fg:o.CLR.white},{text:` ${h}`,fg:m},{text:(0,o.fit)(g,3,"right"),fg:m}]),a++}if(n.theses.length>0&&a<r){const a=n.theses[0],c=n.contexts.get(a.id||a.thesis_id),l=c?.lastEvaluation?.summary||a.lastEvaluation?.summary||"";if(l){const n=t.row+1+r-1,d=c?.lastEvaluation?.timestamp||a.lastEvaluation?.timestamp;let u="";if(d){const e=Math.floor((Date.now()-new Date(d).getTime())/36e5);u=e<1?"<1h ago":`${e}h ago`}const p=i-u.length-1;e.writeStyled(n,s,[{text:(0,o.fit)(l,p),fg:o.CLR.dim},{text:" "+u,fg:o.CLR.veryDim}])}}};const o=n(77096)},67748:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderTrade=function(e,t,n){if(!n.tradeParams)return;const a=n.tradeParams,c=Math.min(50,t.width-4),l=Math.min(18,t.height-2),d=t.col+Math.floor((t.width-c)/2),u=t.row+Math.floor((t.height-l)/2),p={name:"trade",row:u,col:d,width:c,height:l};e.fill(u,d,c,l," ","",s),(0,o.drawBorder)(e,p,"TRADE");const h=d+2,m=c-4;let g=1;const f="buy"===a.action?o.CLR.green:o.CLR.red,y="buy"===a.action?"BUY":"SELL";e.writeStyled(u+g,h,[{text:y+" ",fg:f},{text:a.side.toUpperCase()+" ",fg:o.CLR.emerald},{text:a.ticker,fg:o.CLR.white}]),g+=2;const $=n.positions.find(e=>(e.ticker_symbol||e.ticker)===a.ticker),w=$?.bestBid??$?.current_value??0,k=$?.bestAsk??w+2;e.writeStyled(u+g,h,[{text:"Bid: ",fg:o.CLR.dim},{text:`${w}¢`,fg:o.CLR.green},{text:" Ask: ",fg:o.CLR.dim},{text:`${k}¢`,fg:o.CLR.red}]),g+=2;const b="qty"===n.tradeField,v=b?r:i;e.write(u+g,h,"Quantity:",o.CLR.dim,s),e.write(u+g,h+12,(0,o.fit)(String(a.qty),10),b?o.CLR.emerald:o.CLR.text,v),b&&e.write(u+g,h+22," ◀",o.CLR.emerald,s);g++;const _="price"===n.tradeField,S=_?r:i;e.write(u+g,h,"Price (¢):",o.CLR.dim,s),e.write(u+g,h+12,(0,o.fit)(String(a.price),10),_?o.CLR.emerald:o.CLR.text,S),_&&e.write(u+g,h+22," ◀",o.CLR.emerald,s);g+=2;const x=a.qty*a.price/100,C=a.qty,O=C-x;e.write(u+g,h,"Preview:",o.CLR.title,s),g++,e.writeStyled(u+g,h,[{text:`Max cost: $${x.toFixed(2)}`,fg:o.CLR.dim}]),g++,e.writeStyled(u+g,h,[{text:`Max payout: $${C.toFixed(2)}`,fg:o.CLR.dim}]),g++,e.writeStyled(u+g,h,[{text:"Profit: ",fg:o.CLR.dim},{text:`$${O.toFixed(2)}`,fg:O>=0?o.CLR.green:o.CLR.red}]),g++;const I=n.edges.find(e=>(e.ticker||e.marketId)===a.ticker);if(I){const t=I.edge??I.value??0;e.writeStyled(u+g,h,[{text:"Edge: ",fg:o.CLR.dim},{text:`${t>=0?"+":""}${t}¢`,fg:t>=0?o.CLR.green:o.CLR.red}]),g++}const P=Math.max(0,a.price-w);P>0&&(e.writeStyled(u+g,h,[{text:"Slippage: ",fg:o.CLR.dim},{text:`~${P}¢`,fg:o.CLR.yellow}]),g++);if(g++,n.tradeCountdown>0){const t=` Executing in ${n.tradeCountdown}... `,i=h+Math.floor((m-t.length)/2);e.write(u+g,i,t,o.CLR.yellow,s)}else 0===n.tradeCountdown?e.write(u+g,h+Math.floor((m-12)/2)," EXECUTING ",o.CLR.white,(0,o.bgRgb)(16,120,80)):e.write(u+g,h+Math.floor((m-24)/2),"Press Enter to confirm",o.CLR.dim,s)};const o=n(77096),s=(0,o.bgRgb)(18,18,22),i=(0,o.bgRgb)(30,30,35),r=(0,o.bgRgb)(16,50,40)},29405:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderWhatif=function(e,t,n){(0,o.drawBorder)(e,t,"WHAT-IF SCENARIO");const i=t.col+2,r=t.width-4;let a=1;if(!n.whatifResult)return void e.write(t.row+a,i,'No what-if data. Press "w" from overview to start.',o.CLR.dim);const c=n.whatifResult,l=c.scenarios||c.overrides||[],d=Math.floor(r/2)-2;if(e.write(t.row+a,i,"Scenarios:",o.CLR.title),a++,0===l.length)e.write(t.row+a,i," (no scenarios available)",o.CLR.dim),a+=2;else{for(let c=0;c<l.length&&!(a>=t.height-8);c++){const d=l[c],u=n.whatifScenarioIndex===c,p=u?"▸ ":" ",h=d.name||d.description||d.nodeId||`Scenario ${c+1}`,m=u?s:"";e.write(t.row+a,i,(0,o.fit)(`${p}${h}`,r),u?o.CLR.white:o.CLR.text,m),a++}a++}for(let n=i;n<i+r;n++)e.write(t.row+a,n,"─",o.CLR.borderDim);a++;const u=i,p=i+d+3;e.write(t.row+a,u,(0,o.fit)("BEFORE",d),o.CLR.title),e.write(t.row+a,p,(0,o.fit)("AFTER",d),o.CLR.title),a++;const h=c.before||c.current||{},m=c.after||c.proposed||{},g=null!=h.confidence?`${Math.round(100*h.confidence)}%`:"?%",f=null!=m.confidence?`${Math.round(100*m.confidence)}%`:"?%",y=(m.confidence??0)-(h.confidence??0),$=y>=0?`+${Math.round(100*y)}%`:`${Math.round(100*y)}%`;e.writeStyled(t.row+a,u,[{text:"Confidence: ",fg:o.CLR.dim},{text:g,fg:o.CLR.text}]),e.writeStyled(t.row+a,p,[{text:"Confidence: ",fg:o.CLR.dim},{text:f,fg:o.CLR.text},{text:` (${$})`,fg:y>=0?o.CLR.green:o.CLR.red}]),a++;const w=h.edges||[],k=m.edges||[];e.write(t.row+a,u,"Edges:",o.CLR.dim),e.write(t.row+a,p,"Edges:",o.CLR.dim),a++;const b=Math.min(Math.max(w.length,k.length),t.height-a-3);for(let n=0;n<b;n++){const s=w[n],i=k[n];if(s){const n=(s.market||s.ticker||"").slice(0,d-10),i=`${s.edge>=0?"+":""}${s.edge}`;e.writeStyled(t.row+a,u,[{text:(0,o.fit)(n,d-8),fg:o.CLR.text},{text:(0,o.fit)(i,6,"right"),fg:s.edge>=0?o.CLR.green:o.CLR.red}])}if(i){const n=(i.market||i.ticker||"").slice(0,d-10),r=`${i.edge>=0?"+":""}${i.edge}`,c=i.edgeDelta??i.edge-(s?.edge??0),l=c>=0?`+${c}`:`${c}`;e.writeStyled(t.row+a,p,[{text:(0,o.fit)(n,d-14),fg:o.CLR.text},{text:(0,o.fit)(r,6,"right"),fg:i.edge>=0?o.CLR.green:o.CLR.red},{text:(0,o.fit)(l,6,"right"),fg:c>=0?o.CLR.green:o.CLR.red}])}a++}if(a<t.height-2){a++;const n=c.pnlImpact??c.pnl_impact;null!=n&&e.writeStyled(t.row+a,i,[{text:"P&L Impact: ",fg:o.CLR.dim},{text:`${n>=0?"+":""}$${Math.abs(n).toFixed(2)}`,fg:n>=0?o.CLR.green:o.CLR.red}])}};const o=n(77096),s=(0,o.bgRgb)(25,25,30)},99236:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.c=void 0,t.vol=function(e){if(null==e)return"-";const t="string"==typeof e?parseFloat(e):e;return isNaN(t)?"-":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(0)}K`:t.toString()},t.cents=function(e){if(null==e)return"-";const t="string"==typeof e?parseFloat(e):e;return isNaN(t)?"-":`${Math.round(100*t)}¢`},t.pct=function(e){if(null==e)return"-";const t="string"==typeof e?parseFloat(e):e;return isNaN(t)?"-":`${Math.round(100*t)}%`},t.delta=function(e){const t=e>0?"↑":e<0?"↓":"→",n=e>0?"+":"";return`${t} ${n}${Math.round(100*e)}%`},t.shortDate=function(e){if(!e)return"-";try{const t=new Date(e),n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()],o=t.getDate(),s=t.getHours().toString().padStart(2,"0");return`${n} ${o} ${s}:${t.getMinutes().toString().padStart(2,"0")}`}catch{return e.slice(0,16)}},t.pad=function(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)},t.rpad=function(e,t){return e.length>=t?e.slice(0,t):" ".repeat(t-e.length)+e},t.hr=function(e=80){console.log(t.c.dim+"─".repeat(e)+t.c.reset)},t.die=function(e){console.error(`${t.c.red}Error:${t.c.reset} ${e}`),process.exit(1)},t.errorWithHint=function(e,n){console.error(`\n ${t.c.red}Error:${t.c.reset} ${e}`),n&&console.error(` ${t.c.dim}${n}${t.c.reset}`);console.error()},t.emptyState=function(e,n){console.log(`\n ${t.c.dim}No ${e} found.${t.c.reset}`),n&&console.log(` ${t.c.dim}${n}${t.c.reset}`);console.log()},t.header=function(e){console.log(`\n${t.c.bold}${t.c.cyan}${e}${t.c.reset}`)},t.trunc=function(e,t){return e.length<=t?e:e.slice(0,t-1)+"…"},t.shortId=function(e){return e.slice(0,8)},t.c={reset:"",bold:"",dim:"",red:"",green:"",yellow:"",blue:"",magenta:"",cyan:"",white:"",gray:""}},42613:e=>{"use strict";e.exports=require("assert")},20181:e=>{"use strict";e.exports=require("buffer")},35317:e=>{"use strict";e.exports=require("child_process")},76982:e=>{"use strict";e.exports=require("crypto")},24434:e=>{"use strict";e.exports=require("events")},79896:e=>{"use strict";e.exports=require("fs")},91943:e=>{"use strict";e.exports=require("fs/promises")},58611:e=>{"use strict";e.exports=require("http")},65692:e=>{"use strict";e.exports=require("https")},69278:e=>{"use strict";e.exports=require("net")},4573:e=>{"use strict";e.exports=require("buffer")},31421:e=>{"use strict";e.exports=require("child_process")},78474:e=>{"use strict";e.exports=require("events")},73024:e=>{"use strict";e.exports=require("fs")},37067:e=>{"use strict";e.exports=require("http")},44708:e=>{"use strict";e.exports=require("https")},98995:e=>{"use strict";e.exports=require("node:module")},77030:e=>{"use strict";e.exports=require("net")},48161:e=>{"use strict";e.exports=require("os")},76760:e=>{"use strict";e.exports=require("path")},1708:e=>{"use strict";e.exports=require("process")},57075:e=>{"use strict";e.exports=require("stream")},46466:e=>{"use strict";e.exports=require("stream/promises")},37830:e=>{"use strict";e.exports=require("stream/web")},73136:e=>{"use strict";e.exports=require("url")},57975:e=>{"use strict";e.exports=require("util")},38522:e=>{"use strict";e.exports=require("zlib")},70857:e=>{"use strict";e.exports=require("os")},16928:e=>{"use strict";e.exports=require("path")},932:e=>{"use strict";e.exports=require("process")},24876:e=>{"use strict";e.exports=require("punycode")},83480:e=>{"use strict";e.exports=require("querystring")},23785:e=>{"use strict";e.exports=require("readline")},2203:e=>{"use strict";e.exports=require("stream")},64756:e=>{"use strict";e.exports=require("tls")},52018:e=>{"use strict";e.exports=require("tty")},87016:e=>{"use strict";e.exports=require("url")},39023:e=>{"use strict";e.exports=require("util")},28167:e=>{"use strict";e.exports=require("worker_threads")},43106:e=>{"use strict";e.exports=require("zlib")},18909:(e,t,n)=>{const{Argument:o}=n(49154),{Command:s}=n(34348),{CommanderError:i,InvalidArgumentError:r}=n(41135),{Help:a}=n(79754),{Option:c}=n(45240);t.program=new s,t.createCommand=e=>new s(e),t.createOption=(e,t)=>new c(e,t),t.createArgument=(e,t)=>new o(e,t),t.Command=s,t.Option=c,t.Argument=o,t.Help=a,t.CommanderError=i,t.InvalidArgumentError=r,t.InvalidOptionArgumentError=r},49154:(e,t,n)=>{const{InvalidArgumentError:o}=n(41135);t.Argument=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.length>3&&"..."===this._name.slice(-3)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t!==this.defaultValue&&Array.isArray(t)?t.concat(e):[e]}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new o(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(e,t):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}},t.humanReadableArgName=function(e){const t=e.name()+(!0===e.variadic?"...":"");return e.required?"<"+t+">":"["+t+"]"}},34348:(e,t,n)=>{const o=n(78474).EventEmitter,s=n(31421),i=n(76760),r=n(73024),a=n(1708),{Argument:c,humanReadableArgName:l}=n(49154),{CommanderError:d}=n(41135),{Help:u}=n(79754),{Option:p,DualOptions:h}=n(45240),{suggestSimilar:m}=n(65030);class g extends o{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:e=>a.stdout.write(e),writeErr:e=>a.stderr.write(e),getOutHelpWidth:()=>a.stdout.isTTY?a.stdout.columns:void 0,getErrHelpWidth:()=>a.stderr.isTTY?a.stderr.columns:void 0,outputError:(e,t)=>t(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){const e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let o=t,s=n;"object"==typeof o&&null!==o&&(s=o,o=null),s=s||{};const[,i,r]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(i);return o&&(a.description(o),a._executableHandler=!0),s.isDefault&&(this._defaultCommandName=a._name),a._hidden=!(!s.noHelp&&!s.hidden),a._executableFile=s.executableFile||null,r&&a.arguments(r),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),o?this:a}createCommand(e){return new g(e)}createHelp(){return Object.assign(new u,this.configureHelp())}configureHelp(e){return void 0===e?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return void 0===e?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return"string"!=typeof e&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error("Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()");return(t=t||{}).isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new c(e,t)}argument(e,t,n,o){const s=this.createArgument(e,t);return"function"==typeof n?s.default(o).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){const t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&void 0!==e.defaultValue&&void 0===e.parseArg)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if("boolean"==typeof e)return this._addImplicitHelpCommand=e,this;e=e??"help [command]";const[,n,o]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",i=this.createCommand(n);return i.helpOption(!1),o&&i.arguments(o),s&&i.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=i,this}addHelpCommand(e,t){return"object"!=typeof e?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(void 0===this._helpCommand&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){const n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.\nExpecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if("commander.executeSubCommandAsync"!==e.code)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new d(e,t,n)),a.exit(e)}action(e){return this._actionHandler=t=>{const n=this.registeredArguments.length,o=t.slice(0,n);return this._storeOptionsAsProperties?o[n]=this:o[n]=this.opts(),o.push(this),e.apply(this,o)},this}createOption(e,t){return new p(e,t)}_callParseArg(e,t,n,o){try{return e.parseArg(t,n)}catch(e){if("commander.invalidArgument"===e.code){const t=`${o} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){const t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){const n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'\n- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){const t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){const o=t(this._findCommand(n)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${o}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);const t=e.name(),n=e.attributeName();if(e.negate){const t=e.long.replace(/^--no-/,"--");this._findOption(t)||this.setOptionValueWithSource(n,void 0===e.defaultValue||e.defaultValue,"default")}else void 0!==e.defaultValue&&this.setOptionValueWithSource(n,e.defaultValue,"default");const o=(t,o,s)=>{null==t&&void 0!==e.presetArg&&(t=e.presetArg);const i=this.getOptionValue(n);null!==t&&e.parseArg?t=this._callParseArg(e,t,i,o):null!==t&&e.variadic&&(t=e._concatValue(t,i)),null==t&&(t=!e.negate&&(!(!e.isBoolean()&&!e.optional)||"")),this.setOptionValueWithSource(n,t,s)};return this.on("option:"+t,t=>{const n=`error: option '${e.flags}' argument '${t}' is invalid.`;o(t,n,"cli")}),e.envVar&&this.on("optionEnv:"+t,t=>{const n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;o(t,n,"env")}),this}_optionEx(e,t,n,o,s){if("object"==typeof t&&t instanceof p)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const i=this.createOption(t,n);if(i.makeOptionMandatory(!!e.mandatory),"function"==typeof o)i.default(s).argParser(o);else if(o instanceof RegExp){const e=o;o=(t,n)=>{const o=e.exec(t);return o?o[0]:n},i.default(s).argParser(o)}else i.default(o);return this.addOption(i)}option(e,t,n,o){return this._optionEx({},e,t,n,o)}requiredOption(e,t,n,o){return this._optionEx({mandatory:!0},e,t,n,o)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{void 0!==n.getOptionValueSource(e)&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(void 0!==e&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},void 0===e&&void 0===t.from){a.versions?.electron&&(t.from="electron");const e=a.execArgv??[];(e.includes("-e")||e.includes("--eval")||e.includes("-p")||e.includes("--print"))&&(t.from="eval")}let n;switch(void 0===e&&(e=a.argv),this.rawArgs=e.slice(),t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":a.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){const n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){const n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1;const o=[".js",".ts",".tsx",".mjs",".cjs"];function c(e,t){const n=i.resolve(e,t);if(r.existsSync(n))return n;if(o.includes(i.extname(t)))return;const s=o.find(e=>r.existsSync(`${n}${e}`));return s?`${n}${s}`:void 0}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let l,u=e._executableFile||`${this._name}-${e._name}`,p=this._executableDir||"";if(this._scriptPath){let e;try{e=r.realpathSync(this._scriptPath)}catch(t){e=this._scriptPath}p=i.resolve(i.dirname(e),p)}if(p){let t=c(p,u);if(!t&&!e._executableFile&&this._scriptPath){const n=i.basename(this._scriptPath,i.extname(this._scriptPath));n!==this._name&&(t=c(p,`${n}-${e._name}`))}u=t||u}if(n=o.includes(i.extname(u)),"win32"!==a.platform?n?(t.unshift(u),t=f(a.execArgv).concat(t),l=s.spawn(a.argv[0],t,{stdio:"inherit"})):l=s.spawn(u,t,{stdio:"inherit"}):(t.unshift(u),t=f(a.execArgv).concat(t),l=s.spawn(a.execPath,t,{stdio:"inherit"})),!l.killed){["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(e=>{a.on(e,()=>{!1===l.killed&&null===l.exitCode&&l.kill(e)})})}const h=this._exitCallback;l.on("close",e=>{e=e??1,h?h(new d(e,"commander.executeSubCommandAsync","(close)")):a.exit(e)}),l.on("error",t=>{if("ENOENT"===t.code){const t=p?`searched for local subcommand relative to directory '${p}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",n=`'${u}' does not exist\n - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${t}`;throw new Error(n)}if("EACCES"===t.code)throw new Error(`'${u}' not executable`);if(h){const e=new d(1,"commander.executeSubCommandAsync","(error)");e.nestedError=t,h(e)}else a.exit(1)}),this.runningCommand=l}_dispatchSubcommand(e,t,n){const o=this._findCommand(e);let s;return o||this.help({error:!0}),s=this._chainOrCallSubCommandHook(s,o,"preSubcommand"),s=this._chainOrCall(s,()=>{if(!o._executableHandler)return o._parseCommand(t,n);this._executeSubCommand(o,t.concat(n))}),s}_dispatchHelpCommand(e){e||this.help();const t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&null==this.args[t]&&this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic||this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const e=(e,t,n)=>{let o=t;if(null!==t&&e.parseArg){const s=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;o=this._callParseArg(e,t,n,s)}return o};this._checkNumberOfArguments();const t=[];this.registeredArguments.forEach((n,o)=>{let s=n.defaultValue;n.variadic?o<this.args.length?(s=this.args.slice(o),n.parseArg&&(s=s.reduce((t,o)=>e(n,o,t),n.defaultValue))):void 0===s&&(s=[]):o<this.args.length&&(s=this.args[o],n.parseArg&&(s=e(n,s,n.defaultValue))),t[o]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&"function"==typeof e.then?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e;const o=[];return this._getCommandAndAncestors().reverse().filter(e=>void 0!==e._lifeCycleHooks[t]).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{o.push({hookedCommand:e,callback:t})})}),"postAction"===t&&o.reverse(),o.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let o=e;return void 0!==this._lifeCycleHooks[n]&&this._lifeCycleHooks[n].forEach(e=>{o=this._chainOrCall(o,()=>e(this,t))}),o}_parseCommand(e,t){const n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);!this.commands.length||0!==this.args.length||this._actionHandler||this._defaultCommandName||this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const o=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){let n;return o(),this._processArguments(),n=this._chainOrCallHooks(n,"preAction"),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(s,e,t)})),n=this._chainOrCallHooks(n,"postAction"),n}if(this.parent&&this.parent.listenerCount(s))o(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&void 0===e.getOptionValue(t.attributeName())&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){const e=this.options.filter(e=>{const t=e.attributeName();return void 0!==this.getOptionValue(t)&&"default"!==this.getOptionValueSource(t)});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{const n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){const t=[],n=[];let o=t;const s=e.slice();function i(e){return e.length>1&&"-"===e[0]}let r=null;for(;s.length;){const e=s.shift();if("--"===e){o===n&&o.push(e),o.push(...s);break}if(!r||i(e)){if(r=null,i(e)){const t=this._findOption(e);if(t){if(t.required){const e=s.shift();void 0===e&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,e)}else if(t.optional){let e=null;s.length>0&&!i(s[0])&&(e=s.shift()),this.emit(`option:${t.name()}`,e)}else this.emit(`option:${t.name()}`);r=t.variadic?t:null;continue}}if(e.length>2&&"-"===e[0]&&"-"!==e[1]){const t=this._findOption(`-${e[1]}`);if(t){t.required||t.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${t.name()}`,e.slice(2)):(this.emit(`option:${t.name()}`),s.unshift(`-${e.slice(2)}`));continue}}if(/^--[^=]+=/.test(e)){const t=e.indexOf("="),n=this._findOption(e.slice(0,t));if(n&&(n.required||n.optional)){this.emit(`option:${n.name()}`,e.slice(t+1));continue}}if(i(e)&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&0===t.length&&0===n.length){if(this._findCommand(e)){t.push(e),s.length>0&&n.push(...s);break}if(this._getHelpCommand()&&e===this._getHelpCommand().name()){t.push(e),s.length>0&&t.push(...s);break}if(this._defaultCommandName){n.push(e),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){o.push(e),s.length>0&&o.push(...s);break}o.push(e)}else this.emit(`option:${r.name()}`,e)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){const e={},t=this.options.length;for(let n=0;n<t;n++){const t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),"string"==typeof this._showHelpAfterError?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr("\n"),this.outputHelp({error:!0}));const n=t||{},o=n.exitCode||1,s=n.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in a.env){const t=e.attributeName();(void 0===this.getOptionValue(t)||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,a.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){const e=new h(this.options),t=e=>void 0!==this.getOptionValue(e)&&!["default","implied"].includes(this.getOptionValueSource(e));this.options.filter(n=>void 0!==n.implied&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],"implied")})})}missingArgument(e){const t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){const t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){const t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){const n=e=>{const t=e.attributeName(),n=this.getOptionValue(t),o=this.options.find(e=>e.negate&&t===e.attributeName()),s=this.options.find(e=>!e.negate&&t===e.attributeName());return o&&(void 0===o.presetArg&&!1===n||void 0!==o.presetArg&&n===o.presetArg)?o:s||e},o=e=>{const t=n(e),o=t.attributeName();return"env"===this.getOptionValueSource(o)?`environment variable '${t.envVar}'`:`option '${t.flags}'`},s=`error: ${o(e)} cannot be used with ${o(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],o=this;do{const e=o.createHelp().visibleOptions(o).filter(e=>e.long).map(e=>e.long);n=n.concat(e),o=o.parent}while(o&&!o._enablePositionalOptions);t=m(e,n)}const n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;const t=this.registeredArguments.length,n=1===t?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){const e=this.args[0];let t="";if(this._showSuggestionAfterError){const n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=m(e,n)}const n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(void 0===e)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";const o=this.createOption(t,n);return this._versionOptionName=o.attributeName(),this._registerOption(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,"commander.version",e)}),this}description(e,t){return void 0===e&&void 0===t?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return void 0===e?this._summary:(this._summary=e,this)}alias(e){if(void 0===e)return this._aliases[0];let t=this;if(0!==this.commands.length&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");const n=this.parent?._findCommand(e);if(n){const t=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return void 0===e?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(void 0===e){if(this._usage)return this._usage;const e=this.registeredArguments.map(e=>l(e));return[].concat(this.options.length||null!==this._helpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=e,this}name(e){return void 0===e?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=i.basename(e,i.extname(e)),this}executableDir(e){return void 0===e?this._executableDir:(this._executableDir=e,this)}helpInformation(e){const t=this.createHelp();return void 0===t.helpWidth&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){const t={error:!!(e=e||{}).error};let n;return n=t.error?e=>this._outputConfiguration.writeErr(e):e=>this._outputConfiguration.writeOut(e),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;"function"==typeof e&&(t=e,e=void 0);const n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(e=>e.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let o=this.helpInformation(n);if(t&&(o=t(o),"string"!=typeof o&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(e=>e.emit("afterAllHelp",n))}helpOption(e,t){return"boolean"==typeof e?(this._helpOption=e?this._helpOption??void 0:null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return void 0===this._helpOption&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=a.exitCode||0;0===t&&e&&"function"!=typeof e&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){const n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${n.join("', '")}'`);const o=`${e}Help`;return this.on(o,e=>{let n;n="function"==typeof t?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){const t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function f(e){return e.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n,o="127.0.0.1",s="9229";return null!==(n=e.match(/^(--inspect(-brk)?)$/))?t=n[1]:null!==(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))?(t=n[1],/^\d+$/.test(n[3])?s=n[3]:o=n[3]):null!==(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(t=n[1],o=n[3],s=n[4]),t&&"0"!==s?`${t}=${o}:${parseInt(s)+1}`:e})}t.Command=g},41135:(e,t)=>{class n extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}t.CommanderError=n,t.InvalidArgumentError=class extends n{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}},79754:(e,t,n)=>{const{humanReadableArgName:o}=n(49154);t.Help=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){const t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){const n=e=>e.short?e.short.replace(/^-/,""):e.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){const t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){const o=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);o||s?n.long&&!s?t.push(e.createOption(n.long,n.description)):n.short&&!o&&t.push(e.createOption(n.short,n.description)):t.push(n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];const t=[];for(let n=e.parent;n;n=n.parent){const e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){const t=e.registeredArguments.map(e=>o(e)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,t.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,t.argumentTerm(n).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let t=e.parent;t;t=t.parent)n=t.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){const t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(", ")}`),void 0!==e.defaultValue){(e.required||e.optional||e.isBoolean()&&"boolean"==typeof e.defaultValue)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}return void 0!==e.presetArg&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),void 0!==e.envVar&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){const t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(", ")}`),void 0!==e.defaultValue&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){const n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){const n=t.padWidth(e,t),o=t.helpWidth||80;function s(e,s){if(s){const i=`${e.padEnd(n+2)}${s}`;return t.wrap(i,o-2,n+2)}return e}function i(e){return e.join("\n").replace(/^/gm," ".repeat(2))}let r=[`Usage: ${t.commandUsage(e)}`,""];const a=t.commandDescription(e);a.length>0&&(r=r.concat([t.wrap(a,o,0),""]));const c=t.visibleArguments(e).map(e=>s(t.argumentTerm(e),t.argumentDescription(e)));c.length>0&&(r=r.concat(["Arguments:",i(c),""]));const l=t.visibleOptions(e).map(e=>s(t.optionTerm(e),t.optionDescription(e)));if(l.length>0&&(r=r.concat(["Options:",i(l),""])),this.showGlobalOptions){const n=t.visibleGlobalOptions(e).map(e=>s(t.optionTerm(e),t.optionDescription(e)));n.length>0&&(r=r.concat(["Global Options:",i(n),""]))}const d=t.visibleCommands(e).map(e=>s(t.subcommandTerm(e),t.subcommandDescription(e)));return d.length>0&&(r=r.concat(["Commands:",i(d),""])),r.join("\n")}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,o=40){const s=new RegExp("[\\n][ \\f\\t\\v   -    \ufeff]+");if(e.match(s))return e;const i=t-n;if(i<o)return e;const r=e.slice(0,n),a=e.slice(n).replace("\r\n","\n"),c=" ".repeat(n),l="\\s​",d=new RegExp(`\n|.{1,${i-1}}([${l}]|$)|[^${l}]+?([${l}]|$)`,"g");return r+(a.match(d)||[]).map((e,t)=>"\n"===e?"":(t>0?c:"")+e.trimEnd()).join("\n")}}},45240:(e,t,n)=>{const{InvalidArgumentError:o}=n(41135);t.Option=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;const n=function(e){let t,n;const o=e.split(/[ |,]+/);o.length>1&&!/^[[<]/.test(o[1])&&(t=o.shift());n=o.shift(),!t&&/^-[^-]$/.test(n)&&(t=n,n=void 0);return{shortFlag:t,longFlag:n}}(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return"string"==typeof e&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t!==this.defaultValue&&Array.isArray(t)?t.concat(e):[e]}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new o(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(e,t):e},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return function(e){return e.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},t.DualOptions=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){const n=t.attributeName();if(!this.dualOptions.has(n))return!0;const o=this.negativeOptions.get(n).presetArg,s=void 0!==o&&o;return t.negate===(s===e)}}},65030:(e,t)=>{function n(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);const n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let o=1;o<=t.length;o++)for(let s=1;s<=e.length;s++){let i=1;i=e[s-1]===t[o-1]?0:1,n[s][o]=Math.min(n[s-1][o]+1,n[s][o-1]+1,n[s-1][o-1]+i),s>1&&o>1&&e[s-1]===t[o-2]&&e[s-2]===t[o-1]&&(n[s][o]=Math.min(n[s][o],n[s-2][o-2]+1))}return n[e.length][t.length]}t.suggestSimilar=function(e,t){if(!t||0===t.length)return"";t=Array.from(new Set(t));const o=e.startsWith("--");o&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let s=[],i=3;return t.forEach(t=>{if(t.length<=1)return;const o=n(e,t),r=Math.max(e.length,t.length);(r-o)/r>.4&&(o<i?(i=o,s=[t]):o===i&&s.push(t))}),s.sort((e,t)=>e.localeCompare(t)),o&&(s=s.map(e=>`--${e}`)),s.length>1?`\n(Did you mean one of ${s.join(", ")}?)`:1===s.length?`\n(Did you mean ${s[0]}?)`:""}}},t={};function n(o){var s=t[o];if(void 0!==s)return s.exports;var i=t[o]={exports:{}},r=!0;try{e[o].call(i.exports,i,i.exports,n),r=!1}finally{r&&delete t[o]}return i.exports}n.m=e,(()=>{var e,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;n.t=function(o,s){if(1&s&&(o=this(o)),8&s)return o;if("object"==typeof o&&o){if(4&s&&o.__esModule)return o;if(16&s&&"function"==typeof o.then)return o}var i=Object.create(null);n.r(i);var r={};e=e||[null,t({}),t([]),t(t)];for(var a=2&s&&o;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach(e=>r[e]=()=>o[e]);return r.default=()=>o,n.d(i,r),i}})(),n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce((t,o)=>(n.f[o](e,t),t),[])),n.u=e=>e+".index.js",n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},void 0!==n&&(n.ab=__dirname+"/"),(()=>{var e={792:1};n.f.require=(t,o)=>{e[t]||(t=>{var o=t.modules,s=t.ids,i=t.runtime;for(var r in o)n.o(o,r)&&(n.m[r]=o[r]);i&&i(n);for(var a=0;a<s.length;a++)e[s[a]]=1})(require("./"+n.u(t)))}})();var o={};(()=>{"use strict";var e=o;Object.defineProperty(e,"__esModule",{value:!0});const t=n(18909),s=n(11627),i=n(19218),r=n(38706),a=n(5596),c=n(97499),l=n(46222),d=n(67378),u=n(67509),p=n(46183),h=n(96007),m=n(8784),g=n(91262),f=n(83969),y=n(85417),$=n(40791),w=n(22835),k=n(60952),b=n(40239),v=n(8045),_=n(28423),S=n(96616),x=n(44040),C=n(45475),O=n(63746),I=n(44478),P=n(18691),T=n(34362),E=n(80928),A=n(58211),M=n(43423),R=n(72768),N=n(9708),L=n(33766),D=n(50984),K=n(69903),j=n(35344),F=n(71783),q=n(91993),U=n(81466),z=n(50869),H=n(87604),B=n(65240),J=n(23017),W=n(84436),X=n(15472),G=n(52072),Y=n(33192),V=n(30896),Q=n(72124),Z=n(99236);(0,s.applyConfig)();const ee=new t.Command,te='\nSimpleFunctions CLI — prediction market thesis agent\n\nUsage: sf <command> [options]\n sf <command> --help for detailed options\n\nSetup\n login Browser login (recommended)\n logout Clear saved credentials\n setup Interactive config wizard (power users)\n setup --check Show config status\n setup --polymarket Configure Polymarket wallet\n\nThesis\n list List all theses\n get <id> Full thesis details\n context [id] [--json] Market snapshot (no id) or thesis context (with id)\n create "thesis" Create a new thesis\n signal <id> "content" Inject a signal\n evaluate <id> Trigger deep evaluation\n augment <id> Evolve causal tree with new nodes\n publish / unpublish <id> Manage public visibility\n heartbeat <id> View/configure heartbeat settings & costs\n\nWorld Model (no auth)\n world Real-time world state (~800 tokens, prediction index + markets)\n world --delta What changed since last check (~30-50 tokens)\n world --focus energy,geo Deep coverage on specific topics\n ideas S&T-style trade ideas: conviction, catalyst, direction, risk\n\nSearch\n query "question" LLM-enhanced market knowledge search (no auth)\n markets Traditional markets: SPY, VIX, bonds, gold, oil (no auth)\n\nMarkets\n scan "keywords" Search Kalshi + Polymarket\n scan --series TICKER Browse a Kalshi series\n edges [--json] Top edges across all theses\n watch [query] [mode] Watch markets (modes: orderbook, flow, cross-venue, all)\n whatif <id> What-if scenario analysis\n liquidity [topic] Orderbook liquidity scanner\n book <ticker> [ticker2...] Orderbook depth for specific markets\n explore [slug] Browse public theses\n forecast <event> Market distribution (P50/P75/P90)\n\nShare (any command with --share generates a short URL)\n scan "gold" --share Share scan results\n query "fed rate" --share Share query results\n context --share Share global context snapshot\n\nPortfolio\n positions Kalshi + Polymarket positions\n balance Account balance\n orders Resting orders\n fills Recent trade fills\n settlements Settled contracts with P&L\n performance P&L over time\n dashboard Interactive TUI overview\n\nIntents (declarative execution — the single gateway for all orders)\n intent buy <ticker> <qty> Create buy intent with trigger conditions\n intent sell <ticker> <qty> Create sell intent\n intent list Active intents (--all for history)\n intent status <id> Detailed status + fills\n intent cancel <id> Cancel an intent\n\nTrading (requires sf setup --enable-trading)\n buy <ticker> <qty> Buy contracts (direct, no intent)\n sell <ticker> <qty> Sell contracts (direct, no intent)\n cancel [orderId] Cancel order(s)\n rfq <ticker> <qty> Request for quote\n\nRuntime\n runtime start Start execution daemon (evaluates triggers, places orders)\n runtime stop Stop daemon\n runtime status Active intents + runtime state\n\nInteractive\n agent [id] Agent with natural language + tools\n prompt [id] Dynamic system prompt for any agent\n telegram Telegram bot for monitoring\n\nX / Twitter\n x "query" Search X discussions (summary + raw mode)\n x-volume "query" Discussion volume and velocity trend\n x-news "query" X news stories (Grok-aggregated)\n x-account @username Recent posts from a specific account\n\nInfo\n feed Evaluation history stream\n delta <id> Changes since timestamp\n milestones Upcoming Kalshi events\n schedule Exchange status\n announcements Exchange announcements\n history <ticker> Historical market data\n';ee.name("sf").description("SimpleFunctions CLI — prediction market thesis agent").version("1.7.17").option("--api-key <key>","API key (or set SF_API_KEY env var)").option("--api-url <url>","API base URL (or set SF_API_URL env var)").configureHelp({formatHelp:(e,t)=>{if(!e.parent)return te;const{Help:o}=n(18909);return(new o).formatHelp(e,t)}}).action(async()=>{await async function(){if(!process.stdin.isTTY)return void console.log(te);const e=await Promise.resolve().then(n.t.bind(n,23785,23));if((0,s.isConfigured)())try{const e=new i.SFClient,{theses:t}=await e.listTheses(),n=(t||[]).filter(e=>"active"===e.status);if(n.length>0)return void await(0,f.agentCommand)(n[0].id,{})}catch{}console.log(),console.log(" SimpleFunctions — prediction market intelligence"),console.log(),(0,s.isConfigured)()?console.log(" You have no active theses."):console.log(" No login needed to explore.");console.log();const t=e.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),o=await new Promise(e=>{t.question(" What's your market view? (keyword or thesis)\n > ",n=>{t.close(),e(n.trim())})});if(!o)return void console.log(te);let r=o.replace(/[^\w\s]/g," ").split(/\s+/).filter(e=>e.length>2).slice(0,5).join(" ");r||(r=o.trim().slice(0,40));console.log(),console.log(` Scanning Kalshi + Polymarket for: "${r}"...`),console.log();try{const{scanCommand:e}=await Promise.resolve().then(n.bind(n,46183));await e(r,{json:!1})}catch(e){console.error(` Scan failed: ${e.message}`)}console.log(),(0,s.isConfigured)()?(console.log(" Want to monitor this thesis 24/7?"),console.log(` sf create "${o.slice(0,60)}"`)):(console.log(" Want 24/7 monitoring + edge detection?"),console.log(" sf setup to get started (2 min)"));console.log()}()});const ne=new Set(["setup","login","logout","help","status","scan","explore","query","context","markets","watch","milestones","forecast","settlements","balance","orders","fills","schedule","announcements","history","liquidity","book","prompt","sf"]);async function oe(e){try{await e()}catch(e){const t=e instanceof Error?e.message:String(e);process.argv.includes("--json")&&(console.log(JSON.stringify({error:t,code:e.code||"CLI_ERROR",status:e.status||1})),process.exit(1)),(0,Z.die)(t)}}ee.hook("preAction",(e,t)=>{const n=t.name();if(ne.has(n))return;if(!(e.optsWithGlobals?.()||e.opts()).apiKey&&!(0,s.isConfigured)()){process.argv.includes("--json")?console.log(JSON.stringify({error:"API key required.",code:"NOT_CONFIGURED",keyUrl:"https://simplefunctions.dev/dashboard/keys",cli:"sf login"})):(console.log(),console.log(" This command needs an API key. Three options:"),console.log(" 1. sf login Browser login (30 sec, recommended)"),console.log(" 2. sf setup Interactive wizard (2 min)"),console.log(" 3. sf --api-key KEY Pass inline"),console.log(),console.log(" Get a key at: https://simplefunctions.dev/dashboard/keys"),console.log(' No key? Try sf scan "oil" — works without login.')),console.log(),process.exit(1)}}),ee.command("setup").description("Interactive configuration wizard").option("--check","Show current configuration status").option("--reset","Delete config and start over").option("--key <key>","Set SF API key (non-interactive, for CI)").option("--enable-trading","Enable trading (sf buy/sell/cancel)").option("--disable-trading","Disable trading").option("--kalshi","Reconfigure Kalshi API credentials").option("--polymarket","Reconfigure Polymarket wallet address").action(async e=>{await oe(()=>(0,y.setupCommand)({check:e.check,reset:e.reset,key:e.key,enableTrading:e.enableTrading,disableTrading:e.disableTrading,kalshi:e.kalshi,polymarket:e.polymarket}))}),ee.command("login").description("Browser-based login (recommended — no API keys needed)").option("--force","Re-login even if already configured").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,z.loginCommand)({apiUrl:n.apiUrl,force:e.force}))}),ee.command("logout").description("Clear saved credentials").action(async()=>{await oe(async()=>{const{resetConfig:e,loadFileConfig:t}=await Promise.resolve().then(n.t.bind(n,11627,23));t().apiKey?(e(),console.log("\n Logged out. Credentials removed from ~/.sf/config.json"),console.log(` ${Z.c.dim}Run ${Z.c.cyan}sf login${Z.c.dim} to re-authenticate.${Z.c.reset}\n`)):console.log(`\n ${Z.c.dim}Not logged in.${Z.c.reset}\n`)})}),ee.command("status").description("Health check: verify API, auth, Kalshi, Polymarket connections").option("--json","JSON output").action(async e=>{await oe(()=>(0,Q.statusCommand)({json:e.json}))}),ee.command("list").description("List all theses").option("--json","JSON output").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,r.listCommand)({json:e.json,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("get <id>").description("Get full thesis details").option("--json","Output raw JSON").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,a.getCommand)(e,{json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("context [id]").description("Context snapshot. With ID: thesis-specific. Without: global market snapshot (no auth)").option("--json","Output raw JSON").option("--share","Share output via short URL").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,c.contextCommand)(e,{json:t.json,share:t.share,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("create <thesis>").description("Create a new thesis (sync by default — waits for formation)").option("--async","Async mode — return immediately without waiting").option("--json","JSON output").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,l.createCommand)(e,{async:t.async,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("signal <id> <content>").description("Inject a signal into the thesis queue").option("--type <type>","Signal type: news | user_note | external","user_note").option("--json","JSON output").action(async(e,t,n,o)=>{const s=o.optsWithGlobals();await oe(()=>(0,d.signalCommand)(e,t,{type:n.type,json:n.json,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ee.command("evaluate <id>").description("Trigger a deep evaluation (heavy model, force-heavy mode)").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,u.evaluateCommand)(e,{apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("heartbeat <id>").description("View/configure per-thesis heartbeat settings and costs").option("--news-interval <min>","News scan interval in minutes (15-1440)").option("--x-interval <min>","X/social scan interval in minutes (60-1440)").option("--model <tier>","Eval model tier: cheap, medium, heavy").option("--budget <usd>","Monthly budget cap in USD (0 = unlimited)").option("--pause","Pause heartbeat").option("--resume","Resume heartbeat").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>{const n=new i.SFClient(o.apiKey,o.apiUrl);return(0,H.heartbeatCommand)(n,e,{newsInterval:t.newsInterval,xInterval:t.xInterval,model:t.model,budget:t.budget,pause:t.pause,resume:t.resume})})}),ee.command("scan [query]").description("Explore Kalshi + Polymarket markets").option("--series <ticker>","List events + markets for a series (e.g. KXWTIMAX)").option("--market <ticker>","Get single market detail (e.g. KXWTIMAX-26DEC31-T140)").option("--venue <venue>","Filter by venue: kalshi, polymarket, or all (default: all)").option("--json","Output raw JSON").option("--share","Share output via short URL").action(async(e,t,n)=>{const o=n.optsWithGlobals(),s=e||"";s||t.series||t.market||(console.error('Usage: sf scan "keywords" OR sf scan --series TICKER OR sf scan --market TICKER'),process.exit(1)),await oe(()=>(0,p.scanCommand)(s,{series:t.series,market:t.market,venue:t.venue,json:t.json,share:t.share,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("watch [query] [mode]").description("Watch for market changes (modes: price, orderbook, flow, cross-venue, all)").option("--interval <seconds>","Poll interval in seconds (default: 60, 30 for orderbook)").option("--json","JSON change events (for piping)").option("--thesis <id>","Watch markets related to a thesis").option("--smart","LLM-enhanced noise filtering").option("--execute","Auto-create intents from triggers (requires --smart)").action(async(e,t,n)=>{await oe(()=>(0,h.watchCommand)(e,t,{interval:n.interval,json:n.json,thesis:n.thesis,smart:n.smart,execute:n.execute}))}),ee.command("edges").description("Top edges across all theses — what to trade now").option("--json","JSON output for agents").option("--share","Share output via short URL").option("--limit <n>","Max edges to show","20").option("--thesis <id>","Filter to a single thesis").option("--min-edge <cents>","Minimum absolute edge size in cents").option("--min-liquidity <grade>","Minimum liquidity (high/medium/low or A/B/C)").option("--sort <by>","Sort by: edge (default), spread").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,g.edgesCommand)({json:e.json,share:e.share,limit:e.limit,thesis:e.thesis,minEdge:e.minEdge,minLiquidity:e.minLiquidity,sort:e.sort,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("positions").description("Show Kalshi positions with thesis edge overlay (requires KALSHI_API_KEY_ID + KALSHI_PRIVATE_KEY_PATH)").option("--json","JSON output for agents").option("--thesis <id>","Filter by thesis ID").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,m.positionsCommand)({json:e.json,thesis:e.thesis,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("agent [thesisId]").description("Interactive agent mode — natural language interface to SimpleFunctions").option("--model <model>","Model via OpenRouter (default: anthropic/claude-sonnet-4.6)").option("--model-key <key>","OpenRouter API key (or set OPENROUTER_API_KEY)").option("--new","Start a fresh session (default: continue last session)").option("--plain","Plain text mode (no TUI, works in pipes and scripts)").action(async(e,t,n)=>{n.optsWithGlobals();await oe(()=>(0,f.agentCommand)(e,{model:t.model,modelKey:t.modelKey,newSession:t.new,noTui:t.plain}))}),ee.command("publish <thesisId>").description("Publish a thesis for public viewing").requiredOption("--slug <slug>","URL slug (lowercase, hyphens, 3-60 chars)").option("--description <desc>","Short description").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,$.publishCommand)(e,{slug:t.slug,description:t.description,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("unpublish <thesisId>").description("Remove a thesis from public viewing").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,$.unpublishCommand)(e,{apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("explore [slug]").description("Browse public theses (no auth required)").option("--json","JSON output").option("--share","Share output via short URL").action(async(e,t)=>{await oe(()=>(0,w.exploreCommand)(e,{json:t.json,share:t.share}))}),ee.command("dashboard").description("Portfolio overview — interactive TUI (default), or one-shot with --once/--json").option("--json","JSON output").option("--once","One-time print (no interactive mode)").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,k.dashboardCommand)({json:e.json,once:e.once,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("milestones").description("Upcoming events from Kalshi calendar. Use --category to filter (e.g., Economics, Politics, Financials, Climate)").option("--category <cat>","Filter by category (e.g., Economics, Politics, Financials, Climate, Sports)").option("--thesis <id>","Show milestones matching thesis edges").option("--hours <n>","Hours ahead (default 168)","168").option("--json","JSON output").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,v.milestonesCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("forecast <eventTicker>").description("Market distribution forecast (P50/P75/P90). Use EVENT ticker (e.g., KXWTIMAX-26DEC31), not series ticker.").option("--days <n>","Days of history (default 7)","7").option("--json","JSON output").action(async(e,t)=>{await oe(()=>(0,_.forecastCommand)(e,t))}),ee.command("settlements").description("Settled (resolved) contracts with P&L").option("--thesis <id>","Filter to thesis edge tickers").option("--json","JSON output").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,S.settlementsCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("balance").description("Kalshi account balance").option("--json","JSON output").action(async e=>{await oe(()=>(0,x.balanceCommand)(e))}),ee.command("orders").description("Kalshi resting orders").option("--status <status>","Order status filter (default: resting)","resting").option("--json","JSON output").action(async e=>{await oe(()=>(0,C.ordersCommand)(e))}),ee.command("fills").description("Recent trade fills").option("--ticker <ticker>","Filter by market ticker").option("--json","JSON output").action(async e=>{await oe(()=>(0,O.fillsCommand)(e))}),ee.command("feed").description("Evaluation history stream — what the heartbeat engine has been thinking").option("--hours <n>","Hours to look back (default 24)","24").option("--thesis <id>","Filter by thesis").option("--json","JSON output").action(async(e,t)=>{const n=t.optsWithGlobals();await oe(()=>(0,I.feedCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ee.command("delta <thesisId>").description("Changes since a timestamp — confidence, nodes, signals, edges").option("--since <timestamp>","ISO 8601 start time (e.g., 2026-03-28T14:00:00Z)").option("--hours <n>","Hours to look back (default 6)","6").option("--watch","Continuously poll every 60s").option("--json","JSON output").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,U.deltaCommand)(e,{...t,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("whatif <thesisId>").description('What-if scenario — "if node X drops to 10%, what happens to my edges?"').option("--set <override>","Node override: nodeId=probability (0-1). Repeatable.",(e,t)=>[...t,e],[]).option("--json","JSON output").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,P.whatifCommand)(e,{set:t.set,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("schedule").description("Exchange status and trading hours").option("--json","JSON output").action(async e=>{await oe(()=>(0,A.scheduleCommand)(e))}),ee.command("buy <ticker> <qty>").description("Buy contracts (requires --enable-trading)").option("--price <cents>","Limit price in cents (required for limit orders)").option("--market","Market order (no price needed)").option("--side <s>","yes or no","yes").option("--yes-i-am-sure","Skip 3-second countdown").action(async(e,t,n)=>{await oe(()=>(0,T.buyCommand)(e,t,n))}),ee.command("sell <ticker> <qty>").description("Sell contracts (requires --enable-trading)").option("--price <cents>","Limit price in cents").option("--market","Market order").option("--side <s>","yes or no","yes").option("--yes-i-am-sure","Skip 3-second countdown").action(async(e,t,n)=>{await oe(()=>(0,T.sellCommand)(e,t,n))}),ee.command("cancel [orderId]").description("Cancel order(s) (requires --enable-trading)").option("--all","Cancel all resting orders").option("--ticker <t>","Cancel orders matching ticker prefix (with --all)").option("--yes-i-am-sure","Skip countdown").action(async(e,t)=>{await oe(()=>(0,E.cancelCommand)(e,t))}),ee.command("rfq <ticker> <qty>").description("Request for quote — large order pricing (requires --enable-trading)").option("--target-cost <cents>","Target cost per contract in cents").option("--rest-remainder","Rest unfilled portion as limit order").option("--json","JSON output").action(async(e,t,n)=>{await oe(()=>(0,M.rfqCommand)(e,t,n))}),ee.command("announcements").description("Exchange announcements (rule changes, maintenance)").option("--json","JSON output").action(async e=>{await oe(()=>(0,R.announcementsCommand)(e))}),ee.command("history <ticker>").description("Historical market data (settled/closed)").option("--json","JSON output").action(async(e,t)=>{await oe(()=>(0,N.historyCommand)(e,t))}),ee.command("performance").description("Portfolio P&L over time with thesis event annotations").option("--ticker <ticker>","Filter by ticker (fuzzy match)").option("--since <date>","Start date (ISO, e.g. 2026-03-01)").option("--json","JSON output").action(async e=>{await oe(()=>(0,L.performanceCommand)(e))}),ee.command("liquidity [topic]").description("Market liquidity scanner — run without args to see topics").option("--all","Scan all topics").option("--venue <venue>","Filter venue: kalshi, polymarket, all (default: all)").option("--horizon <horizon>","Filter horizon (weekly, monthly, long-term)").option("--min-depth <depth>","Minimum bid+ask depth",parseInt).option("--json","JSON output").action(async(e,t)=>{await oe(()=>(0,D.liquidityCommand)({...t,topic:e}))}),ee.command("book [tickers...]").description("Orderbook depth, spread, and liquidity for specific markets").option("--poly <query>","Search Polymarket markets by keyword").option("--history","Include 7-day price history sparkline").option("--json","JSON output").action(async(e,t)=>{0!==e.length||t.poly||(console.error('Usage: sf book <ticker> [ticker2...] OR sf book --poly "oil price"'),process.exit(1)),await oe(()=>(0,K.bookCommand)(e,t))}),ee.command("prompt [thesisId]").description("Get dynamic system prompt with live thesis state (for agent injection)").option("--sections <list>","Include: thesis,tree,edges,evaluation,orderbook (default: all)").option("--max-length <n>","Max character length (default: 3000)").option("--json","JSON format with metadata").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,j.promptCommand)(e,{sections:t.sections,maxLength:t.maxLength,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("augment <thesisId>").description("Review & merge suggested causal tree nodes from evaluations").option("--dry-run","Preview accepted nodes without applying").option("--json","JSON output").action(async(e,t,n)=>{const o=n.optsWithGlobals();await oe(()=>(0,F.augmentCommand)(e,{dryRun:t.dryRun,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ee.command("markets").description("Traditional market snapshot — SPY, VIX, Treasury, Gold, Oil (no auth)").option("--json","JSON output").option("--share","Share output via short URL").action(async e=>{await oe(()=>(0,J.marketsCommand)({json:e.json,share:e.share}))}),ee.command("query <question>").description("LLM-enhanced prediction market knowledge search (no auth required)").option("--json","JSON output").option("--share","Share output via short URL").option("--limit <n>","Max results per category (default 10)","10").action(async(e,t)=>{await oe(()=>(0,B.queryCommand)(e,{json:t.json,share:t.share,limit:t.limit}))}),ee.command("telegram").description("Start Telegram bot for monitoring and trading").option("--token <token>","Telegram bot token (or set TELEGRAM_BOT_TOKEN)").option("--chat-id <id>","Restrict to specific chat ID").option("--daemon","Run in background").option("--stop","Stop background bot").option("--status","Check if bot is running").action(async e=>{await oe(()=>(0,q.telegramCommand)(e))}),ee.command("x <query>").description("Search X/Twitter discussions about a topic").option("--json","JSON output").option("--raw","Raw mode (no LLM summary)").option("--hours <n>","Hours to search back (default 24)","24").option("--limit <n>","Max results (default 20)","20").action(async(e,t)=>{await oe(()=>(0,W.xSearchCommand)(e,t))}),ee.command("x-volume <query>").description("X/Twitter discussion volume and velocity trend").option("--json","JSON output").option("--hours <n>","Hours to look back (default 72)","72").option("--granularity <g>","minute|hour|day (default hour)","hour").action(async(e,t)=>{await oe(()=>(0,W.xVolumeCommand)(e,t))}),ee.command("x-news <query>").description("X/Twitter news stories (Grok-aggregated)").option("--json","JSON output").option("--limit <n>","Max stories (default 10)","10").action(async(e,t)=>{await oe(()=>(0,W.xNewsCommand)(e,t))}),ee.command("x-account <username>").description("Recent posts from a specific X/Twitter account").option("--json","JSON output").option("--hours <n>","Hours to look back (default 24)","24").option("--limit <n>","Max posts (default 20)","20").action(async(e,t)=>{await oe(()=>(0,W.xAccountCommand)(e,t))}),ee.command("world").description("Real-time world state for agents (~800 tokens, no auth)").option("--json","JSON output").option("--delta","Incremental update only (what changed)").option("--since <window>","Time window for delta: 30m, 1h, 6h, 24h (default 1h)").option("--focus <topics>","Focus on topics: energy,geopolitics,crypto,policy,tech,economy").option("--share","Share output via short URL").action(async e=>{await oe(()=>(0,Y.worldCommand)(e))}),ee.command("ideas").description("S&T-style trade ideas: conviction, catalyst, direction, risk (no auth)").option("--json","JSON output").option("--category <cat>","Filter: macro, geopolitics, crypto, policy, event").option("--fresh <window>","Max cache age: 1h, 6h, 12h (default 12h)").option("--share","Share output via short URL").action(async e=>{await oe(()=>(0,V.ideasCommand)(e))}),(0,b.registerStrategies)(ee),(0,X.registerIntents)(ee),(0,G.registerRuntime)(ee),ee.parse()})(),module.exports=o})();