@spfunctions/cli 2.0.4 → 2.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/12.index.js +1 -1
- package/dist/160.index.js +1 -1
- package/dist/324.index.js +1 -0
- package/dist/482.index.js +1 -0
- package/dist/563.index.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
(()=>{var e={93402:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkForUpdates=function(){const e=u(),t=d();t.latestVersion&&function(e,t){const n=e.replace(/^v/,"").split(".").map(Number),o=t.replace(/^v/,"").split(".").map(Number);for(let e=0;e<3;e++){if((n[e]||0)<(o[e]||0))return!0;if((n[e]||0)>(o[e]||0))return!1}return!1}(e,t.latestVersion)&&console.log(` [33m↑ Update available: ${e} → ${t.latestVersion}. Run [1msf update[22;33m to install.[39m`);if(Date.now()-t.lastCheck<l)return;const n=`\n const fs = require('fs');\n const path = require('path');\n const f = ${JSON.stringify(c)};\n fetch('https://registry.npmjs.org/${a}/latest', {signal: AbortSignal.timeout(5000)})\n .then(r => r.json())\n .then(d => {\n fs.mkdirSync(path.dirname(f), {recursive: true});\n fs.writeFileSync(f, JSON.stringify({lastCheck: Date.now(), latestVersion: d.version}));\n }).catch(() => {});\n `,o=(0,r.spawn)(process.execPath,["-e",n],{detached:!0,stdio:"ignore"});o.unref()};const o=n(79896),s=n(16928),i=n(70857),r=n(35317),a="@spfunctions/cli",c=(0,s.join)((0,i.homedir)(),".sf","update-check.json"),l=36e5;function d(){try{if((0,o.existsSync)(c))return JSON.parse((0,o.readFileSync)(c,"utf-8"))}catch{}return{lastCheck:0,latestVersion:null}}function u(){try{const e=(0,s.join)(__dirname,"..","package.json");if((0,o.existsSync)(e))return JSON.parse((0,o.readFileSync)(e,"utf-8")).version;const t=(0,s.join)(__dirname,"package.json");if((0,o.existsSync)(t))return JSON.parse((0,o.readFileSync)(t,"utf-8")).version}catch{}return"0.0.0"}},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(e){const t=e?`?topic=${encodeURIComponent(e)}`:"",n=await fetch(`${s}/api/public/markets${t}`);if(!n.ok)throw new Error(`Markets API error: ${n.status}`);return n.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,g=o||s,f=r?`${i}/api/proxy`:"https://openrouter.ai/api/v1";g||(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(" [2mUsing SimpleFunctions LLM proxy (no OpenRouter key needed)[22m");else try{(await fetch("https://openrouter.ai/api/v1/auth/key",{headers:{Authorization:`Bearer ${g}`},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 w=new a.SFClient;let k,O=e||null,C=!1;if(!O){let e=[];try{const t=await w.listTheses();e=(t.theses||t).filter(e=>"active"===e.status)}catch{e=[]}if(0===e.length)C=!0;else if(1===e.length)O=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("[H[2J"),i("\n [2mSelect thesis[22m\n\n");for(let e=0;e<s.length;e++){const t=s[e],n=e===o,r=n?"[38;2;16;185;129m › [39m":" ";if("_explorer"===t.id){const e=n?`[38;2;16;185;129m${t.title}[39m`:`[38;2;80;80;88m${t.title}[39m`;i(`${r}${e}\n`)}else{const e=n?`[38;2;16;185;129m${t.id.slice(0,8)}[39m`:`[38;2;55;55;60m${t.id.slice(0,8)}[39m`,o=`[38;2;55;55;60m${t.conf}%[39m`,s=n?`[38;2;160;160;165m${t.title}[39m`:`[38;2;80;80;88m${t.title}[39m`;i(`${r}${e} ${o} ${s}\n`)}}i("\n [38;2;55;55;60m↑↓ navigate · enter select[39m")}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?C=!0:O=t}else O=e[0].id}if(C){try{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));k=await e()}catch{k={edges:[],theses:[]}}k._explorerMode=!0}else try{k=await w.getContext(O)}catch(e){console.error(`Warning: Could not fetch thesis context (${e.message}). Starting with limited context.`),k={thesisId:O,edges:[],causalTree:{nodes:[]}}}if(t?.noTui)return async function(e){const{openrouterKey:t,sfClient:o,resolvedThesisId:s,opts:i,useProxy:r,llmBaseUrl:p,sfApiKey:g,sfApiUrl:f}=e;let w=e.latestContext;const k=await Promise.resolve().then(n.t.bind(n,23785,23)),b=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),v=await Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653)),{getModel:S,streamSimple:_,Type:x}=b,{Agent:O}=v,C=i?.model||"anthropic/claude-sonnet-4.6";let I=C.replace(/^openrouter\//,"");function P(e){let t;try{t=S("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 T=P(I);const E=x.Object({thesisId:x.String({description:"Thesis ID"})}),A=x.Object({thesisId:x.String({description:"Thesis ID"}),content:x.String({description:"Signal content"}),type:x.Optional(x.String({description:"Signal type: news, user_note, external"}))}),M=x.Object({query:x.Optional(x.String({description:"Keyword search"})),series:x.Optional(x.String({description:"Series ticker"})),market:x.Optional(x.String({description:"Market ticker"}))}),R=x.Object({query:x.String({description:"Search keywords"})}),N=x.Object({}),L=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:E,execute:async(e,t)=>{const n=await o.getContext(t.thesisId);return w=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:N,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:x.Object({q:x.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. Use topic for deep dives: energy, rates, fx, equities, crypto, volatility.",parameters:x.Object({topic:x.Optional(x.String({description:"Deep dive: energy, rates, fx, equities, crypto, volatility"}))}),execute:async(e,t)=>{const{fetchTraditionalMarkets:o}=await Promise.resolve().then(n.bind(n,19218)),s=await o(t.topic);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"query_databento",label:"Databento Query",description:"Free-form historical data: stocks, ETFs, CME futures, options. OHLCV, trades, BBO. Max 30 days.",parameters:x.Object({symbols:x.String({description:"Comma-separated. Futures: ROOT.c.0. E.g. SPY, CL.c.0"}),dataset:x.Optional(x.String({description:"DBEQ.BASIC, GLBX.MDP3, OPRA.PILLAR"})),schema:x.Optional(x.String({description:"ohlcv-1d, ohlcv-1h, ohlcv-1m, trades"})),stype:x.Optional(x.String({description:"raw_symbol or continuous"})),days:x.Optional(x.Number({description:"Lookback (max 30)"}))}),execute:async(e,t)=>{const n=new URLSearchParams({symbols:t.symbols});t.dataset&&n.set("dataset",t.dataset),t.schema&&n.set("schema",t.schema),t.stype&&n.set("stype",t.stype),t.days&&n.set("days",String(t.days));const o=process.env.SF_API_URL||"https://simplefunctions.dev",s=await fetch(`${o}/api/public/databento?${n.toString()}`);if(!s.ok)return{content:[{type:"text",text:`Databento error: ${s.status}`}],details:{}};const i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"inject_signal",label:"Inject Signal",description:"Inject a signal into the thesis",parameters:A,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:E,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:M,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:N,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:N,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:R,execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY;if(!n&&!(!n&&g))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(`${f}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g}`},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:x.Object({hours:x.Optional(x.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:x.Optional(x.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:x.Object({eventTicker:x.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:x.Optional(x.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:x.Object({ticker:x.Optional(x.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:N,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:x.Object({status:x.Optional(x.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:x.Object({ticker:x.Optional(x.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:x.Object({topic:x.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:x.Object({ticker:x.Optional(x.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:x.Optional(x.Array(x.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:x.Optional(x.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:N,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:x.Object({rawThesis:x.String({description:"The raw thesis statement to create"}),webhookUrl:x.Optional(x.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:N,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:x.Object({hours:x.Optional(x.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:x.Object({hours:x.Optional(x.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:x.Object({slug:x.Optional(x.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:x.Object({thesisId:x.String({description:"Thesis ID"}),marketId:x.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:x.String({description:"Human-readable market name"}),direction:x.String({description:"yes or no"}),horizon:x.Optional(x.String({description:"short, medium, or long. Default: medium"})),entryBelow:x.Optional(x.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:x.Optional(x.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:x.Optional(x.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:x.Optional(x.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:x.Optional(x.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:x.Optional(x.Number({description:"Contracts per order. Default: 50"})),softConditions:x.Optional(x.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:x.Optional(x.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:x.Object({thesisId:x.String({description:"Thesis ID"}),status:x.Optional(x.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:x.Object({thesisId:x.String({description:"Thesis ID"}),strategyId:x.String({description:"Strategy ID (UUID)"}),stopLoss:x.Optional(x.Number({description:"New stop loss (cents)"})),takeProfit:x.Optional(x.Number({description:"New take profit (cents)"})),entryBelow:x.Optional(x.Number({description:"New entry below trigger (cents)"})),entryAbove:x.Optional(x.Number({description:"New entry above trigger (cents)"})),status:x.Optional(x.String({description:"New status: active|watching|executed|cancelled|review"})),priority:x.Optional(x.Number({description:"New priority"})),softConditions:x.Optional(x.String({description:"Updated soft conditions"})),rationale:x.Optional(x.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:x.Object({overrides:x.Array(x.Object({nodeId:x.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:x.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{const n=w,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:{}}}}];L.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:x.Object({query:x.String({description:"Search query"}),mode:x.Optional(x.String({description:'"summary" or "raw"'})),hours:x.Optional(x.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:x.Object({query:x.String({description:"Search query"}),hours:x.Optional(x.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:x.Object({query:x.String({description:"Search query"}),limit:x.Optional(x.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:x.Object({username:x.String({description:"X username (with or without @)"}),hours:x.Optional(x.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:x.Object({thesisId:x.String({description:"Thesis ID"}),newsIntervalMin:x.Optional(x.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:x.Optional(x.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:x.Optional(x.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:x.Optional(x.Number({description:"Monthly budget (0 = unlimited)"})),paused:x.Optional(x.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:{}}}}),L.push({name:"configure_heartbeat",label:"Configure Heartbeat",description:"Adjust the 24/7 monitoring engine: news interval, X interval, model tier, budget, pause/resume.",parameters:x.Object({thesisId:x.String({description:"Thesis ID"}),newsIntervalMin:x.Optional(x.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:x.Optional(x.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:x.Optional(x.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:x.Optional(x.Number({description:"Monthly budget cap (0=unlimited)"})),paused:x.Optional(x.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:x.Object({thesisId:x.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:x.Object({thesisId:x.String({description:"Thesis ID"}),title:x.Optional(x.String({description:"New title"})),status:x.Optional(x.String({description:"active, paused, or archived"})),webhookUrl:x.Optional(x.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:x.Object({thesisId:x.String({description:"Thesis ID"}),venue:x.String({description:"kalshi or polymarket"}),externalMarketId:x.String({description:"Market ticker"}),marketTitle:x.String({description:"Market name"}),direction:x.String({description:"yes or no"}),entryPrice:x.Number({description:"Entry price in cents"}),size:x.Optional(x.Number({description:"Contracts"})),rationale:x.Optional(x.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:x.Object({thesisId:x.String({description:"Thesis ID"}),positionId:x.String({description:"Position ID"}),currentPrice:x.Optional(x.Number({description:"Current price (cents)"})),edge:x.Optional(x.Number({description:"Current edge (cents)"})),status:x.Optional(x.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:x.Object({thesisId:x.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:x.Object({thesisId:x.String({description:"Thesis ID"}),updates:x.Array(x.Object({nodeId:x.String({description:"Node ID (e.g. n3)"}),probability:x.Number({description:"New probability (0-1)"}),reason:x.Optional(x.String({description:"Why"}))})),lock:x.Optional(x.Array(x.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:{}}}}),L.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:x.Object({freshness:x.Optional(x.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:x.Optional(x.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:x.Object({action:x.String({description:"buy or sell"}),venue:x.String({description:"kalshi or polymarket"}),marketId:x.String({description:"Market ticker"}),marketTitle:x.String({description:"Human-readable name"}),direction:x.String({description:"yes or no"}),targetQuantity:x.Number({description:"Number of contracts"}),maxPrice:x.Optional(x.Number({description:"Max price per contract in cents (1-99)"})),triggerType:x.Optional(x.String({description:"immediate, price_below, price_above, time"})),triggerPrice:x.Optional(x.Number({description:"Price trigger threshold in cents"})),rationale:x.Optional(x.String({description:"Why this trade"})),autoExecute:x.Optional(x.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:x.Object({activeOnly:x.Optional(x.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:x.Object({intentId:x.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 D=(0,u.loadConfig)();D.tradingEnabled&&L.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Shows preview and asks for confirmation.",parameters:x.Object({ticker:x.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:x.String({description:"yes or no"}),action:x.String({description:"buy or sell"}),type:x.String({description:"limit or market"}),count:x.Number({description:"Number of contracts"}),price_cents:x.Optional(x.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:x.Object({order_id:x.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:{}}}}});L.push({name:"close_position",label:"Close Position",description:"Remove a position record from a thesis.",parameters:x.Object({thesisId:x.String({description:"Thesis ID"}),positionId:x.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:x.Object({thesisId:x.String({description:"Thesis ID"}),dryRun:x.Optional(x.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:{}}}}),L.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:x.Object({focus:x.Optional(x.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:x.Object({since:x.Optional(x.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:x.Object({source:x.Object({action:x.String({description:"scrape, crawl, search, map, extract, batch_scrape"}),url:x.Optional(x.String({description:"Target URL"})),query:x.Optional(x.String({description:"Search query (for search action)"}))}),analysis:x.Optional(x.Object({model:x.Optional(x.String({description:"OpenRouter model"})),prompt:x.Optional(x.String({description:"Analysis prompt"}))})),enrich:x.Optional(x.Object({topics:x.Optional(x.Array(x.String())),includeIndex:x.Optional(x.Boolean())})),webhook:x.Optional(x.Object({url:x.String({description:"Webhook URL"}),format:x.Optional(x.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:x.Object({content:x.String({description:"Text to cross-reference"}),topics:x.Optional(x.Array(x.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:{}}}}),L.push({name:"create_skill",label:"Create Skill",description:"Create a custom agent skill — a reusable prompt/workflow triggered via slash command.",parameters:x.Object({name:x.String(),trigger:x.String({description:"Slash command trigger, e.g. /my-skill"}),description:x.String(),prompt:x.String({description:"The instruction text the agent executes"}),category:x.Optional(x.String()),tags:x.Optional(x.String({description:"Comma-separated tags"})),toolsUsed:x.Optional(x.String({description:"Comma-separated tool names"}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",o={name:t.name,trigger:t.trigger,description:t.description,prompt:t.prompt};t.category&&(o.category=t.category),t.tags&&(o.tags=t.tags.split(",").map(e=>e.trim())),t.toolsUsed&&(o.toolsUsed=t.toolsUsed.split(",").map(e=>e.trim()));const s=await fetch(`${n}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g}`},body:JSON.stringify(o)}),i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"list_skills",label:"List Skills",description:"List all skills: built-in defaults + user-created custom skills.",parameters:x.Object({}),execute:async()=>{const e=process.env.SF_API_URL||"https://simplefunctions.dev",t=await fetch(`${e}/api/skill`,{headers:{Authorization:`Bearer ${g}`}}),n=await t.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"browse_public_skills",label:"Browse Public Skills",description:"Browse community-created skills. Filter by category, search, or sort by popularity. No auth needed.",parameters:x.Object({category:x.Optional(x.String()),q:x.Optional(x.String()),sort:x.Optional(x.String({description:"popular or new"}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",o=new URLSearchParams;t.category&&o.set("category",t.category),t.q&&o.set("q",t.q),t.sort&&o.set("sort",t.sort);const s=await fetch(`${n}/api/public/skills?${o}`),i=await s.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"publish_skill",label:"Publish Skill",description:"Publish a skill to make it publicly browsable and forkable.",parameters:x.Object({skillId:x.String(),slug:x.String({description:"URL-safe slug, e.g. my-precheck"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",o=await fetch(`${n}/api/skill/${t.skillId}/publish`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g}`},body:JSON.stringify({slug:t.slug})}),s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"fork_skill",label:"Fork Skill",description:"Fork a public skill into your collection. Creates a copy you can customize.",parameters:x.Object({skillId:x.String({description:"ID of the public skill to fork"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",o=await fetch(`${n}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${g}`}}),s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"fork_thesis",label:"Fork Thesis",description:"Fork a public thesis. Copies thesis + causal tree, resets edges. Run formation after forking.",parameters:x.Object({slug:x.String({description:"Public thesis slug, e.g. iran-war"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",o=await fetch(`${n}/api/thesis/${t.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${g}`}}),s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}}),L.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime is running and show active intents.",parameters:x.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:{}}}},{...h(o)},{...m()},{name:"daemon_command",label:"Daemon Command",description:"Send a command to a running daemon (runtime, telegram). Actions: pause, resume, scan_now.",parameters:x.Object({target:x.String({description:"Target daemon: runtime, telegram, watch"}),action:x.String({description:"Command action"}),data:x.Optional(x.Any())}),execute:async(e,t)=>{const{writeMessage:o}=await n.e(563).then(n.bind(n,9563)),s=o({from:"agent",to:t.target,type:"command",priority:"normal",payload:{action:t.action,data:t.data},ttl:3600});return{content:[{type:"text",text:`Command sent: ${t.action} → ${t.target} (${s})`}],details:{}}}},{name:"set_wake_condition",label:"Set Wake Condition",description:"Set a condition for daemons to alert you. Types: price, time, llm.",parameters:x.Object({description:x.String({description:"Human-readable condition"}),type:x.String({description:"price, time, or llm"}),condition:x.Any({description:"Condition config"}),priority:x.Optional(x.String())}),execute:async(e,t)=>{const{saveWakeCondition:o}=await n.e(563).then(n.bind(n,9563)),{randomBytes:s}=await Promise.resolve().then(n.t.bind(n,76982,23)),i={id:s(8).toString("hex"),createdAt:(new Date).toISOString(),description:t.description,type:t.type,[`${t.type}Condition`]:t.condition,alertChannels:["bus"],priority:t.priority||"normal",maxFires:-1,firedCount:0,lastFiredAt:null,expiresAt:null,active:!0};return o(i),{content:[{type:"text",text:`Wake condition set: "${t.description}" (${i.id})`}],details:{}}}},{name:"check_daemon_alerts",label:"Check Daemon Alerts",description:"Read alerts and observations from running daemons.",parameters:x.Object({}),execute:async()=>{const{readMessages:e,deleteMessage:t}=await n.e(563).then(n.bind(n,9563)),o=e("agent","outbox");if(0===o.length)return{content:[{type:"text",text:"No new daemon alerts."}],details:{}};const s=o.map(e=>(t(e.id,"outbox"),`[${e.priority}] ${e.from} (${e.ts.slice(11,19)}): ${e.payload.summary||JSON.stringify(e.payload)}`));return{content:[{type:"text",text:s.join("\n")}],details:{}}}});const j=w,F=j._explorerMode||"_explorer"===s;let K;if(F){const e=(j.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- daemon_command / set_wake_condition / check_daemon_alerts: smart daemon control\n- create_skill / list_skills / publish_skill / fork_skill / browse_public_skills: manage agent skills\n- fork_thesis: fork a public thesis (copies thesis + causal tree)\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${D.tradingEnabled?"- Trading ENABLED.":"- Trading DISABLED."}\n\n## Market snapshot\nPublic edges:\n${e}`}else{const e=j.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=j.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 j.confidence?Math.round(100*j.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${D.tradingEnabled?"- Trading ENABLED. You have place_order and cancel_order tools.":"- Trading DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current State\nThesis: ${j.thesis||j.rawThesis||"N/A"}\nID: ${s} | Confidence: ${n}% | Status: ${j.status}\n\nCausal nodes:\n${t}\n\nTop edges:\n${e}\n\n${j.lastEvaluation?.summary?`Latest eval: ${j.lastEvaluation.summary.slice(0,300)}`:""}`}const q=new O({initialState:{systemPrompt:K,model:T,tools:L,thinkingLevel:"off"},streamFn:_,getApiKey:e=>"openrouter"===e?t:void 0});if(!i?.newSession){const e=y(s);if(e?.messages?.length>0)try{q.replaceMessages(e.messages),q.setSystemPrompt(K)}catch{}}let U="";if(q.subscribe(e=>{if("message_update"===e.type){const t=e.assistantMessageEvent;"text_delta"===t.type&&(process.stdout.write(t.delta),U+=t.delta)}if("message_end"===e.type&&U&&(process.stdout.write("\n"),U=""),"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`)}}),F)console.log(`SF Agent — Explorer mode | ${I}`),console.log(`Public edges: ${(j.edges||[]).length}`),console.log("Ask anything about prediction markets. Type /help for commands, /exit to quit.\n");else{const e=j.thesis||j.rawThesis||"N/A",t="number"==typeof j.confidence?Math.round(100*j.confidence):0;console.log(`SF Agent — ${s.slice(0,8)} | ${t}% | ${I}`),console.log(`Thesis: ${e.length>100?e.slice(0,100)+"...":e}`),console.log(`Edges: ${(j.edges||[]).length} | Status: ${j.status}`),console.log("Type /help for commands, /exit to quit.\n")}const z=k.createInterface({input:process.stdin,output:process.stdout,prompt:"> "});z.prompt();for await(const t of z){const n=t.trim();if(n){if("/exit"===n||"/quit"===n){try{$(s,I,q.state.messages)}catch{}return void z.close()}if("/help"!==n){if("/tree"===n){w=await o.getContext(s);const e=w.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)}%`)}z.prompt();continue}if("/edges"===n){w=await o.getContext(s);const e=(w.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}`)}z.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),z.prompt();continue}if(n.startsWith("/model")){const e=n.slice(6).trim();if(!e){console.log(`Current: ${I}`),z.prompt();continue}I=e.replace(/^openrouter\//,""),T=P(I),q.setModel(T),console.log(`Model: ${I}`),z.prompt();continue}try{await q.prompt(n)}catch(e){console.error(`Error: ${e.message}`)}try{$(s,I,q.state.messages)}catch{}z.prompt()}else console.log("Commands: /help /exit /tree /edges /eval /model <name>"),z.prompt()}else z.prompt()}}({openrouterKey:g,sfClient:w,resolvedThesisId:O||"_explorer",latestContext:k,useProxy:r,llmBaseUrl:f,sfApiKey:s,sfApiUrl:i,opts:t});const I=await n.e(921).then(n.bind(n,93921)),P=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),T=await Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653)),{TUI:E,ProcessTerminal:A,Container:M,Text:R,Markdown:N,Editor:L,Loader:D,Spacer:j,CombinedAutocompleteProvider:F,truncateToWidth:K,visibleWidth:q}=I,{getModel:U,streamSimple:z,Type:H}=P,{Agent:B}=T,J=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}}}(I),W=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=x.zinc600(" │ ");let s;if(this.isExplorer){const e=x.emerald(b("Explorer")),t=x.zinc600(`${this.edgeCount} public edges`),n=this.topEdge?x.zinc400(this.topEdge):"";let o="";if(this.positionCount>0){const e=this.pnlDollars>=0?x.emerald(`+$${this.pnlDollars.toFixed(2)}`):x.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);o=x.zinc600(`${this.positionCount} pos `)+e}s=[e,o,t,n].filter(Boolean)}else{const e=x.emerald(this.thesisId),t=this.confidenceDelta>0?"▲":this.confidenceDelta<0?"▼":"─",n=this.confidenceDelta>0?x.emerald:this.confidenceDelta<0?x.red:x.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?x.emerald(`+$${this.pnlDollars.toFixed(2)}`):x.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);r=x.zinc600(`${this.positionCount} pos `)+e}s=[e,i,r,x.zinc600(`${this.edgeCount} edges`),this.topEdge?x.zinc400(this.topEdge):""].filter(Boolean)}let i=x.bgZinc800(" "+t(s.join(o),e-2,"")+" ");const r=n(i);r<e&&(i+=x.bgZinc800(" ".repeat(e-r)));const a=x.zinc600(this.modelName.split("/").pop()||this.modelName),c=this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:`${this.tokens}`,l=x.zinc600(`${c} tok`),d=!0===this.exchangeOpen?x.emerald("OPEN"):!1===this.exchangeOpen?x.red("CLOSED"):x.zinc600("..."),u=this.tradingEnabled?x.amber("trading"):x.zinc600("read-only"),p=x.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=x.bgZinc900(" "+h+" ".repeat(f)+p+" ");const $=n(y);return $<e&&(y+=x.bgZinc900(" ".repeat(e-$))),this.cachedLines=[i,y],this.cachedLines}}}(I),X=t?.model||"anthropic/claude-sonnet-4.6";let G=X.replace(/^openrouter\//,"");function Y(e){let t;try{t=U("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=f),t}let V=Y(G),Q=0,Z=!1,ee=null,te=(new Date).toISOString(),ne=null,oe=null,se=null;const ie=new A,re=new E(ie),ae={heading:e=>x.zinc200(b(e)),link:e=>x.emerald(e),linkUrl:e=>x.zinc600(e),code:e=>x.zinc200(e),codeBlock:e=>x.zinc400(e),codeBlockBorder:e=>x.zinc600(e),quote:e=>x.zinc400(e),quoteBorder:e=>x.zinc600(e),hr:e=>x.zinc600(e),listBullet:e=>x.emerald(e),bold:e=>b(e),italic:e=>v(e),strikethrough:e=>_(e),underline:e=>S(e)},ce={color:e=>x.zinc400(e)},le={borderColor:e=>`[38;2;50;50;55m${e}[39m`,selectList:{selectedPrefix:e=>x.emerald(e),selectedText:e=>x.zinc200(e),description:e=>x.zinc600(e),scrollInfo:e=>x.zinc600(e),noMatch:e=>x.zinc600(e)}},de=new W;de.modelName=G,de.tradingEnabled=(0,u.loadConfig)().tradingEnabled||!1;let ue=null;try{if(ue=await(0,c.getPositions)(),ue)for(const e of ue){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{}de.setFromContext(k,ue||void 0),fetch("https://api.elections.kalshi.com/trade-api/v2/exchange/status",{headers:{Accept:"application/json"}}).then(e=>e.json()).then(e=>{de.exchangeOpen=!!e.exchange_active,de.update(),re.requestRender()}).catch(()=>{});const pe=new j(1),he=new j(1),me=new M,ge=new L(re,le,{paddingX:1}),fe=[{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&&fe.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 ye=(0,p.loadSkills)();for(const e of ye){const t=e.trigger.replace(/^\//,"");fe.splice(-2,0,{name:t,description:`[skill] ${e.description.slice(0,50)}`})}const $e=new F(fe,process.cwd());ge.setAutocompleteProvider($e),re.addChild(pe),re.addChild(me),re.addChild(ge),re.addChild(he),re.setFocus(ge);re.showOverlay(de,{anchor:"bottom-left",width:"100%",nonCapturing:!0});function we(e){const t=new R(e,1,0);me.addChild(t),re.requestRender()}function ke(){me.addChild(new j(1))}function be(e){return new Promise(t=>{we(x.amber(b("⚠ "))+x.zinc200(e)),ke(),re.requestRender(),se={resolve:t}})}const ve=H.Object({thesisId:H.String({description:"Thesis ID (short or full UUID)"})}),Se=H.Object({thesisId:H.String({description:"Thesis ID"}),content:H.String({description:"Signal content"}),type:H.Optional(H.String({description:"Signal type: news, user_note, external. Default: user_note"}))}),_e=H.Object({query:H.Optional(H.String({description:"Keyword search for Kalshi markets"})),series:H.Optional(H.String({description:"Kalshi series ticker (e.g. KXWTIMAX)"})),market:H.Optional(H.String({description:"Specific market ticker"}))}),xe=H.Object({query:H.String({description:"Search keywords"})}),Oe=H.Object({}),Ce=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:ve,execute:async(e,t)=>{const n=await w.getContext(t.thesisId);return k=n,de.setFromContext(n,ue||void 0),re.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:Oe,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:H.Object({q:H.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. Default: SPY, VIX, TLT, GLD, USO. Use topic for deep dives: energy (WTI, Brent, NG, Heating Oil), rates (yield curve: SHY, IEF, TLT, ZN, ZB, HYG, LQD), fx (DXY, JPY, EUR, GBP), equities (QQQ, IWM, EEM, XLF, XLK), crypto (BTC/ETH ETFs + futures), volatility (VIX suite).",parameters:H.Object({topic:H.Optional(H.String({description:"Deep dive topic: energy, rates, fx, equities, crypto, volatility. Omit for core 5."}))}),execute:async(e,t)=>{const{fetchTraditionalMarkets:o}=await Promise.resolve().then(n.bind(n,19218)),s=await o(t.topic);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"query_databento",label:"Databento Query",description:"Free-form historical market data via Databento. Stocks, ETFs, CME futures, options. OHLCV daily/hourly/minute, trades, BBO. Max 30 days, 5 symbols. Examples: SPY 7d OHLCV, CL.c.0 hourly, ES.c.0 + NQ.c.0 comparison. Continuous futures format: ROOT.c.0 (front month).",parameters:H.Object({symbols:H.String({description:"Comma-separated (max 5). Continuous futures: ROOT.c.0. E.g. SPY, CL.c.0, ES.c.0"}),dataset:H.Optional(H.String({description:"DBEQ.BASIC (stocks), GLBX.MDP3 (CME futures), OPRA.PILLAR (options)"})),schema:H.Optional(H.String({description:"ohlcv-1d, ohlcv-1h, ohlcv-1m, trades, bbo-1s, bbo-1m, statistics"})),stype:H.Optional(H.String({description:"raw_symbol (default) or continuous (for .FUT)"})),days:H.Optional(H.Number({description:"Lookback days (default 7, max 30)"}))}),execute:async(e,t)=>{const n=new URLSearchParams({symbols:t.symbols});t.dataset&&n.set("dataset",t.dataset),t.schema&&n.set("schema",t.schema),t.stype&&n.set("stype",t.stype),t.days&&n.set("days",String(t.days));const o=await fetch(`${i}/api/public/databento?${n.toString()}`);if(!o.ok)return{content:[{type:"text",text:`Databento error: ${o.status}`}],details:{}};const s=await o.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"inject_signal",label:"Inject Signal",description:"Inject a signal into the thesis (news, note, external event)",parameters:Se,execute:async(e,t)=>{const n=await w.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:ve,execute:async(e,t)=>{const n=await w.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?"▲":"▼";we((e>0?x.emerald:x.red)(` ${s} Confidence ${t}% → ${o}% (${e>0?"+":""}${Math.round(100*e)})`)),ke(),de.updateConfidence(n.evaluation.newConfidence,e),re.requestRender()}try{k=await w.getContext(t.thesisId),de.setFromContext(k,ue||void 0),re.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:_e,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:Oe,execute:async()=>{const e=await w.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:Oe,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))}ee=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:xe,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:H.Object({slug:H.Optional(H.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:H.Object({thesisId:H.String({description:"Thesis ID"}),marketId:H.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:H.String({description:"Human-readable market name"}),direction:H.String({description:"yes or no"}),horizon:H.Optional(H.String({description:"short, medium, or long. Default: medium"})),entryBelow:H.Optional(H.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:H.Optional(H.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:H.Optional(H.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:H.Optional(H.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:H.Optional(H.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:H.Optional(H.Number({description:"Contracts per order. Default: 50"})),softConditions:H.Optional(H.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:H.Optional(H.String({description:"Full logic description"}))}),execute:async(e,t)=>{const n=await w.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:H.Object({thesisId:H.String({description:"Thesis ID"}),status:H.Optional(H.String({description:"Filter by status. Omit for all."}))}),execute:async(e,t)=>{const n=await w.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:H.Object({thesisId:H.String({description:"Thesis ID"}),strategyId:H.String({description:"Strategy ID (UUID)"}),stopLoss:H.Optional(H.Number({description:"New stop loss (cents)"})),takeProfit:H.Optional(H.Number({description:"New take profit (cents)"})),entryBelow:H.Optional(H.Number({description:"New entry below trigger (cents)"})),entryAbove:H.Optional(H.Number({description:"New entry above trigger (cents)"})),status:H.Optional(H.String({description:"New status: active|watching|executed|cancelled|review"})),priority:H.Optional(H.Number({description:"New priority"})),softConditions:H.Optional(H.String({description:"Updated soft conditions"})),rationale:H.Optional(H.String({description:"Updated rationale"}))}),execute:async(e,t)=>{const{thesisId:n,strategyId:o,...s}=t,i=await w.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:H.Object({hours:H.Optional(H.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:H.Optional(H.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:H.Object({eventTicker:H.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:H.Optional(H.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:H.Object({ticker:H.Optional(H.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:Oe,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:H.Object({status:H.Optional(H.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:H.Object({ticker:H.Optional(H.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:H.Object({topic:H.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:H.Object({ticker:H.Optional(H.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:H.Optional(H.Array(H.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:H.Optional(H.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:Oe,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:H.Object({rawThesis:H.String({description:"The raw thesis statement to create"}),webhookUrl:H.Optional(H.String({description:"Optional webhook URL for notifications"}))}),execute:async(e,t)=>{const n=await w.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(C&&o.id){C=!1,O=o.id;try{k=await w.getContext(o.id);const e=Pe(k);Ee.setSystemPrompt(e),de.setFromContext(k,ue||void 0),re.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:Oe,execute:async()=>{const{theses:e}=await w.listTheses(),t=(e||[]).filter(e=>"active"===e.status||"monitoring"===e.status),n=await Promise.allSettled(t.map(async e=>((await w.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:H.Object({hours:H.Optional(H.Number({description:"Hours of history to fetch (default 24)"}))}),execute:async(e,t)=>{const n=await w.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:H.Object({hours:H.Optional(H.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:{}}}}];Ce.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:H.Object({overrides:H.Array(H.Object({nodeId:H.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:H.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{if(O)try{k=await w.getContext(O)}catch{}const n=k,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:{}}}}),Ce.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:H.Object({query:H.String({description:'Search query (e.g. "iran oil", "fed rate cut", "$BTC")'}),mode:H.Optional(H.String({description:'"summary" (default, with AI analysis) or "raw" (just posts)'})),hours:H.Optional(H.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await w.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:H.Object({query:H.String({description:"Search query"}),hours:H.Optional(H.Number({description:"Hours of history (default 72)"}))}),execute:async(e,t)=>{const n=await w.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:H.Object({query:H.String({description:"Search query"}),limit:H.Optional(H.Number({description:"Max stories (default 10)"}))}),execute:async(e,t)=>{const n=await w.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:H.Object({username:H.String({description:"X username (with or without @)"}),hours:H.Optional(H.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await w.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:H.Object({thesisId:H.String({description:"Thesis ID"}),newsIntervalMin:H.Optional(H.Number({description:"News scan interval in minutes (15-1440)"})),xIntervalMin:H.Optional(H.Number({description:"X scan interval in minutes (60-1440)"})),evalModelTier:H.Optional(H.String({description:"Eval model: cheap, medium, or heavy"})),monthlyBudgetUsd:H.Optional(H.Number({description:"Monthly budget cap in USD (0 = unlimited)"})),paused:H.Optional(H.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 w.updateHeartbeatConfig(t.thesisId,e)}const n=await w.getHeartbeatConfig(t.thesisId);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}});const Ie=(0,u.loadConfig)();Ie.tradingEnabled&&Ce.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:H.Object({ticker:H.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:H.String({description:"yes or no"}),action:H.String({description:"buy or sell"}),type:H.String({description:"limit or market"}),count:H.Number({description:"Number of contracts"}),price_cents:H.Optional(H.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);we([x.zinc200(b("ORDER PREVIEW")),` Ticker: ${t.ticker}`,` Side: ${"yes"===t.side?x.emerald("YES"):x.red("NO")}`,` Action: ${t.action.toUpperCase()}`,` Quantity: ${t.count}`,` Type: ${t.type}`,s?` Price: ${s}¢`:"",` Max cost: $${i}`].filter(Boolean).join("\n")),ke(),re.requestRender();if(!(await be("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:H.Object({order_id:H.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 be(`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 Pe(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). Intents can have a softCondition (natural language) that the smart runtime evaluates via LLM before executing. 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.\nUse daemon_command to send commands to running daemons (pause, resume, scan_now). Use set_wake_condition to create alerts: price thresholds, time triggers, or natural language conditions evaluated by LLM. Use check_daemon_alerts to read daemon observations.\n\n## Skills & Fork\n\n- create_skill: create reusable agent workflows triggered via slash command\n- list_skills / browse_public_skills: discover built-in, custom, and community skills\n- publish_skill / fork_skill: share skills publicly, fork others' skills\n- fork_thesis: copy a public thesis + causal tree into user's account, then run formation for fresh edges\n\n## Trading status\n\n${Ie.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||O}\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)}`:""}`}Ce.push({name:"update_thesis",label:"Update Thesis",description:"Update thesis metadata: title, status (active/paused/archived), webhookUrl.",parameters:H.Object({thesisId:H.String({description:"Thesis ID"}),title:H.Optional(H.String({description:"New title"})),status:H.Optional(H.String({description:"active, paused, or archived"})),webhookUrl:H.Optional(H.String({description:"Webhook URL (HTTPS)"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,s=await w.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:H.Object({thesisId:H.String({description:"Thesis ID"}),dryRun:H.Optional(H.Boolean({description:"Preview changes without applying (default false)"}))}),execute:async(e,t)=>{const n=t.dryRun?"?dryRun=true":"",o=await w.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:H.Object({thesisId:H.String({description:"Thesis ID"}),venue:H.String({description:"kalshi or polymarket"}),externalMarketId:H.String({description:"Market ticker"}),marketTitle:H.String({description:"Market name"}),direction:H.String({description:"yes or no"}),entryPrice:H.Number({description:"Entry price in cents"}),size:H.Optional(H.Number({description:"Contracts"})),rationale:H.Optional(H.String({description:"Why"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,s=await w.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:H.Object({thesisId:H.String({description:"Thesis ID"}),positionId:H.String({description:"Position ID"}),currentPrice:H.Optional(H.Number({description:"Current price (cents)"})),edge:H.Optional(H.Number({description:"Current edge (cents)"})),status:H.Optional(H.String({description:"open or closed"}))}),execute:async(e,t)=>{const{thesisId:n,positionId:o,...s}=t,i=await w.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:H.Object({thesisId:H.String({description:"Thesis ID"}),positionId:H.String({description:"Position ID"})}),execute:async(e,t)=>{const n=await w.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:H.Object({thesisId:H.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await w.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:H.Object({thesisId:H.String({description:"Thesis ID"}),updates:H.Array(H.Object({nodeId:H.String({description:"Node ID (e.g. n3)"}),probability:H.Number({description:"New probability (0-1)"}),reason:H.Optional(H.String({description:"Why"}))})),lock:H.Optional(H.Array(H.String({description:"Node IDs to lock"})))}),execute:async(e,t)=>{const n=await w.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:H.Object({thesisId:H.String({description:"Thesis ID"}),newsIntervalMin:H.Optional(H.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:H.Optional(H.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:H.Optional(H.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:H.Optional(H.Number({description:"Monthly budget cap (0=unlimited)"})),paused:H.Optional(H.Boolean({description:"Pause/resume"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,s=await w.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:H.Object({thesisId:H.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await w.request("GET",`/api/thesis/${t.thesisId}/heartbeat`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}}),Ce.push({name:"get_trade_ideas",label:"Trade Ideas",description:"S&T-style trade pitches: conviction, catalyst, direction, risk. No auth required.",parameters:H.Object({freshness:H.Optional(H.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:H.Optional(H.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:H.Object({action:H.String({description:"buy or sell"}),venue:H.String({description:"kalshi or polymarket"}),marketId:H.String({description:"Market ticker"}),marketTitle:H.String({description:"Human-readable name"}),direction:H.String({description:"yes or no"}),targetQuantity:H.Number({description:"Number of contracts"}),maxPrice:H.Optional(H.Number({description:"Max price per contract in cents (1-99)"})),triggerType:H.Optional(H.String({description:"immediate, price_below, price_above, time"})),triggerPrice:H.Optional(H.Number({description:"Price trigger threshold in cents"})),rationale:H.Optional(H.String({description:"Why this trade"})),autoExecute:H.Optional(H.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(e,t)=>{const n=await w.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:H.Object({activeOnly:H.Optional(H.Boolean({description:"Only active intents (default true)"}))}),execute:async(e,t)=>{const n=await w.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:H.Object({intentId:H.String({description:"Intent ID to cancel"})}),execute:async(e,t)=>{const n=await w.cancelIntentAPI(t.intentId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}}),Ce.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:H.Object({focus:H.Optional(H.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:H.Object({since:H.Optional(H.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:H.Object({source:H.Object({action:H.String({description:"Firecrawl action: scrape, crawl, search, map, extract, batch_scrape"}),url:H.Optional(H.String({description:"Target URL (for scrape/crawl/extract)"})),query:H.Optional(H.String({description:"Search query (for search action)"}))}),analysis:H.Optional(H.Object({model:H.Optional(H.String({description:"OpenRouter model (e.g. google/gemini-flash-1.5)"})),prompt:H.Optional(H.String({description:"Analysis prompt"}))})),enrich:H.Optional(H.Object({topics:H.Optional(H.Array(H.String(),{description:"Topics for market cross-reference"})),includeIndex:H.Optional(H.Boolean({description:"Include SF prediction market index"}))})),webhook:H.Optional(H.Object({url:H.String({description:"Webhook URL"}),format:H.Optional(H.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:H.Object({content:H.String({description:"Text to cross-reference with markets"}),topics:H.Optional(H.Array(H.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:{}}}}),Ce.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime daemon is running and show active intents.",parameters:H.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 w.listIntents({active:!0});return{content:[{type:"text",text:JSON.stringify({running:r,pid:r?a:null,...c},null,2)}],details:{}}}},{...h(w)},{...m()}),Ce.push({name:"daemon_command",label:"Daemon Command",description:"Send a command to a running daemon (runtime, telegram). Actions: pause, resume, scan_now.",parameters:H.Object({target:H.String({description:"Target daemon: runtime, telegram, watch"}),action:H.String({description:"Command action: pause, resume, scan_now, adjust_trigger"}),data:H.Optional(H.Any({description:"Optional data for the command"}))}),execute:async(e,t)=>{const{writeMessage:o}=await n.e(563).then(n.bind(n,9563)),s=o({from:"agent",to:t.target,type:"command",priority:"normal",payload:{action:t.action,data:t.data},ttl:3600});return{content:[{type:"text",text:`Command sent to ${t.target}: ${t.action} (msg ${s})`}],details:{}}}},{name:"set_wake_condition",label:"Set Wake Condition",description:"Set a condition for daemons to alert you. Types: price (ticker crosses threshold), time (at a specific time), llm (natural language condition evaluated by LLM).",parameters:H.Object({description:H.String({description:"Human-readable description of the condition"}),type:H.String({description:"Condition type: price, time, llm"}),condition:H.Any({description:"Condition config: { ticker, operator, threshold } for price, { at } for time, { prompt, dataNeeded } for llm"}),priority:H.Optional(H.String({description:"Alert priority: low, normal, high, critical"}))}),execute:async(e,t)=>{const{saveWakeCondition:o}=await n.e(563).then(n.bind(n,9563)),{randomBytes:s}=await Promise.resolve().then(n.t.bind(n,76982,23)),i={id:s(8).toString("hex"),createdAt:(new Date).toISOString(),description:t.description,type:t.type,[`${t.type}Condition`]:t.condition,alertChannels:["bus"],priority:t.priority||"normal",maxFires:-1,firedCount:0,lastFiredAt:null,expiresAt:null,active:!0};return o(i),{content:[{type:"text",text:`Wake condition set: "${t.description}" (id: ${i.id})`}],details:{}}}},{name:"check_daemon_alerts",label:"Check Daemon Alerts",description:"Read alerts and observations from running daemons.",parameters:Oe,execute:async()=>{const{readMessages:e,deleteMessage:t}=await n.e(563).then(n.bind(n,9563)),o=e("agent","outbox");if(0===o.length)return{content:[{type:"text",text:"No new daemon alerts."}],details:{}};const s=o.map(e=>(t(e.id,"outbox"),`[${e.priority}] ${e.from} (${e.ts.slice(11,19)}): ${e.payload.summary||JSON.stringify(e.payload)}`));return{content:[{type:"text",text:s.join("\n")}],details:{}}}}),Ce.push({name:"create_skill",label:"Create Skill",description:"Create a custom agent skill — a reusable prompt/workflow triggered via slash command.",parameters:H.Object({name:H.String({description:'Skill name (e.g. "precheck", "wti_arb")'}),trigger:H.String({description:'Slash command trigger (e.g. "/precheck")'}),description:H.String({description:"What this skill does"}),prompt:H.String({description:"The full prompt/instructions for the skill"}),category:H.Optional(H.String({description:"Category: custom, trading, research, monitoring"})),tags:H.Optional(H.String({description:"Comma-separated tags"})),toolsUsed:H.Optional(H.String({description:"Comma-separated tool names used by this skill"}))}),execute:async(e,t)=>{const n={name:t.name,trigger:t.trigger,description:t.description,prompt:t.prompt};t.category&&(n.category=t.category),t.tags&&(n.tags=t.tags.split(",").map(e=>e.trim())),t.toolsUsed&&(n.toolsUsed=t.toolsUsed.split(",").map(e=>e.trim()));try{const e=await fetch(`${i}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(n)});if(!e.ok)return{content:[{type:"text",text:`Skill 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:`Error: ${e.message}`}],details:{}}}}},{name:"list_skills",label:"List Skills",description:"List all skills: built-in defaults + user-created custom skills.",parameters:H.Object({}),execute:async()=>{try{const e=await fetch(`${i}/api/skill`,{headers:{Authorization:`Bearer ${s}`}});if(!e.ok)return{content:[{type:"text",text:`Skill 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:`Error: ${e.message}`}],details:{}}}}},{name:"browse_public_skills",label:"Browse Skills",description:"Browse community-created skills. No auth needed.",parameters:H.Object({category:H.Optional(H.String({description:"Filter: custom, trading, research, monitoring"})),q:H.Optional(H.String({description:"Search by name/description"})),sort:H.Optional(H.String({description:"popular or new (default: new)"}))}),execute:async(e,t)=>{const n=new URLSearchParams;t.category&&n.set("category",t.category),t.q&&n.set("q",t.q),t.sort&&n.set("sort",t.sort);try{const e=await fetch(`${i}/api/public/skills?${n}`);if(!e.ok)return{content:[{type:"text",text:`Skills 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:`Error: ${e.message}`}],details:{}}}}},{name:"publish_skill",label:"Publish Skill",description:"Publish a skill to make it publicly browsable and forkable.",parameters:H.Object({skillId:H.String({description:"Skill ID to publish"}),slug:H.String({description:"Public URL slug (lowercase, hyphens, 3-60 chars)"})}),execute:async(e,t)=>{try{const e=await fetch(`${i}/api/skill/${t.skillId}/publish`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({slug:t.slug})});if(!e.ok)return{content:[{type:"text",text:`Publish error: ${e.status}`}],details:{}};const n=await e.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}},{name:"fork_skill",label:"Fork Skill",description:"Fork a public skill into your collection.",parameters:H.Object({skillId:H.String({description:"ID of the public skill to fork"})}),execute:async(e,t)=>{try{const e=await fetch(`${i}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${s}`}});if(!e.ok)return{content:[{type:"text",text:`Fork error: ${e.status}`}],details:{}};const n=await e.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}},{name:"fork_thesis",label:"Fork Thesis",description:"Fork a public thesis. Copies thesis + causal tree. Accepts ID or slug.",parameters:H.Object({idOrSlug:H.String({description:"Public thesis ID or slug"})}),execute:async(e,t)=>{try{const e=await fetch(`${i}/api/thesis/${t.idOrSlug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${s}`}});if(!e.ok)return{content:[{type:"text",text:`Fork error: ${e.status}`}],details:{}};const n=await e.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}});const Te=C?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, publish, fork skills — reusable agent workflows (create_skill, list_skills, publish_skill, fork_skill, browse_public_skills)\n- Fork public theses — copy thesis + causal tree, then run formation (fork_thesis)\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`}(k):Pe(k),Ee=new B({initialState:{systemPrompt:Te,model:V,tools:Ce,thinkingLevel:"off"},streamFn:z,getApiKey:e=>{if("openrouter"===e)return g}});let Ae=!1;if(!t?.newSession){const e=y(O||"_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(),Ee.replaceMessages(n),Ee.setSystemPrompt(Te),Ae=!0}catch{}}function Me(){try{const e=Ee.state.messages;e.length>0&&$(O||"_explorer",G,e)}catch{}}let Re=null,Ne="",Le=null;const De=new Map,je=new Map;let Fe=null;function Ke(){Fe&&(clearTimeout(Fe),Fe=null),re.requestRender()}async function qe(e){const t=e.trim().split(/\s+/),o=t[0].toLowerCase();switch(o){case"/help":return ke(),we(x.zinc200(b("Commands"))+"\n"+x.emerald("/help ")+x.zinc400("Show this help")+"\n"+x.emerald("/tree ")+x.zinc400("Display causal tree")+"\n"+x.emerald("/edges ")+x.zinc400("Display edge/spread table")+"\n"+x.emerald("/pos ")+x.zinc400("Display Kalshi positions")+"\n"+x.emerald("/eval ")+x.zinc400("Trigger deep evaluation")+"\n"+x.emerald("/switch <id>")+x.zinc400(" Switch thesis")+"\n"+x.emerald("/compact ")+x.zinc400("Compress conversation history")+"\n"+x.emerald("/new ")+x.zinc400("Start fresh session")+"\n"+x.emerald("/model <m> ")+x.zinc400("Switch model")+"\n"+x.emerald("/env ")+x.zinc400("Show environment variable status")+"\n"+(Ie.tradingEnabled?x.zinc600("─".repeat(30))+"\n"+x.emerald("/buy ")+x.zinc400("TICKER QTY PRICE — quick buy")+"\n"+x.emerald("/sell ")+x.zinc400("TICKER QTY PRICE — quick sell")+"\n"+x.emerald("/cancel ")+x.zinc400("ORDER_ID — cancel order")+"\n"+x.zinc600("─".repeat(30))+"\n":"")+(ye.length>0?x.zinc600("─".repeat(30))+"\n"+x.zinc200(b("Skills"))+"\n"+ye.map(e=>x.emerald(`/${e.name.padEnd(10)}`)+x.zinc400(e.description.slice(0,45))).join("\n")+"\n"+x.zinc600("─".repeat(30))+"\n":"")+x.emerald("/clear ")+x.zinc400("Clear screen (keeps history)")+"\n"+x.emerald("/exit ")+x.zinc400("Exit (auto-saves)")),ke(),!0;case"/tree":if(ke(),C)we(x.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one."));else try{k=await w.getContext(O),we(x.zinc200(b("Causal Tree"))+"\n"+function(e){const t=e.causalTree;if(!t?.nodes?.length)return x.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?x.emerald:s>=40?x.amber:x.red,c=`${r}${x.zinc600(t)} ${x.zinc400(o)} `,l=` ${a(`${s}%`)} ${a(i)}`;n.push(c+l)}else n.push(`${r}${x.zinc600(t)} ${x.zinc400(o)}`)}return n.join("\n")}(k))}catch(e){we(x.red(`Error: ${e.message}`))}return ke(),!0;case"/edges":if(ke(),C)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)we(x.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` ${x.zinc400(t)} ${x.zinc600(n)} ${x.zinc400(o)} ${x.emerald(s.padStart(4))}`}).join("\n");we(x.zinc200(b("Public Edges"))+"\n"+e)}}catch(e){we(x.red(`Error: ${e.message}`))}else try{k=await w.getContext(O),ee&&(k._positions=ee),we(x.zinc200(b("Edges"))+"\n"+function(e){const t=e.edges;if(!t?.length)return x.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?x.emerald:"medium"===l?x.amber:x.red,p=n.find(t=>t.ticker===e.marketId||e.marketId&&t.ticker?.includes(e.marketId));let h=x.zinc600("—");if(p){const e=p.side?.toUpperCase()||"YES",t="number"==typeof p.unrealized_pnl?p.unrealized_pnl>=0?x.emerald(`+$${(p.unrealized_pnl/100).toFixed(0)}`):x.red(`-$${(Math.abs(p.unrealized_pnl)/100).toFixed(0)}`):"";h=x.emerald(`${e} (${p.quantity}@${p.average_price_paid}¢ ${t})`)}o.push(` ${x.zinc200(t)} ${x.zinc400(s)} → ${x.zinc400(i)} edge ${r.includes("+")?x.emerald(r):x.red(r)} spread ${x.zinc600(c)} ${u(d)} ${u(l.padEnd(4))} ${h}`)}return o.join("\n")}(k))}catch(e){we(x.red(`Error: ${e.message}`))}return ke(),!0;case"/pos":ke();try{const e=await(0,c.getPositions)();if(!e)return we(x.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))}ee=e,we(x.zinc200(b("Positions"))+"\n"+function(e){if(!e?.length)return x.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?x.emerald(`+$${l}`):x.red(`-$${Math.abs(parseFloat(l)).toFixed(2)}`),u=c>=0?x.emerald("▲"):x.red("▼");t.push(` ${x.zinc200(e)} ${x.zinc400(s)} ${x.zinc400(i)} @ ${x.zinc400(r)} now ${x.zinc200(a)} ${d} ${u}`)}const o=(n/100).toFixed(2);return t.push(x.zinc600(" "+"─".repeat(40))),t.push(n>=0?` Total P&L: ${x.emerald(b(`+$${o}`))}`:` Total P&L: ${x.red(b(`-$${Math.abs(parseFloat(o)).toFixed(2)}`))}`),t.join("\n")}(e))}catch(e){we(x.red(`Error: ${e.message}`))}return ke(),!0;case"/eval":if(ke(),C)return we(x.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one.")),ke(),!0;we(x.zinc600("Triggering evaluation...")),re.requestRender();try{const e=await w.evaluate(O);we(x.emerald("Evaluation complete")+"\n"+x.zinc400(JSON.stringify(e,null,2)))}catch(e){we(x.red(`Error: ${e.message}`))}return ke(),!0;case"/model":{const e=t.slice(1).join(" ").trim();return e?(ke(),G=e.replace(/^openrouter\//,""),V=Y(G),Ee.setModel(V),de.modelName=G,de.update(),we(x.emerald(`Model switched to ${G}`)),ke(),re.requestRender(),!0):(we(x.zinc400(`Current model: ${G}`)),!0)}case"/switch":{const n=t[1]?.trim();if(!n)return we(x.zinc400("Usage: /switch <thesisId>")),!0;ke();try{Me();const e=await w.getContext(n);O=e.thesisId||n,k=e;const t=Pe(e);"number"==typeof e.confidence&&Math.round(100*e.confidence);Ee.clearMessages();const o=y(O);o?.messages?.length>0?(Ee.replaceMessages(o.messages),Ee.setSystemPrompt(t),we(x.emerald(`Switched to ${O.slice(0,8)}`)+x.zinc400(` (resumed ${o.messages.length} messages)`))):(Ee.setSystemPrompt(t),we(x.emerald(`Switched to ${O.slice(0,8)}`)+x.zinc400(" (new session)"))),de.setFromContext(e,ue||void 0),me.clear(),we(ze(e,ue))}catch(e){we(x.red(`Switch failed: ${e.message}`))}return ke(),re.setFocus(ge),re.requestRender(),!0}case"/compact":ke();try{const t=Ee.state.messages;if(t.length<=10)return we(x.zinc400("Conversation too short to compact")),ke(),re.setFocus(ge),!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 we(x.zinc400("Not enough complete turns to compact")),ke(),re.setFocus(ge),!0;const a=t.slice(0,s),c=t.slice(s),l=new D(re,e=>x.emerald(e),e=>x.zinc600(e),"compacting with LLM...");l.start(),me.addChild(l),re.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 h=d.join("\n\n"),m="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:m,messages:[{role:"system",content:f},{role:"user",content:`Summarize this conversation (${a.length} messages):\n\n${h}`}],max_tokens:2e3,temperature:.2},n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g}`,"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(),me.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];Ee.clearMessages(),Ee.replaceMessages($),Ee.setSystemPrompt(Te),Me(),we(x.emerald(`Compacted: ${a.length} messages → summary + ${c.length} recent`)+x.zinc600(` (via ${m.split("/").pop()})`)),ke(),re.setFocus(ge),re.requestRender()}catch(e){we(x.red(`Compact failed: ${e.message||e}`)),ke(),re.setFocus(ge),re.requestRender()}return!0;case"/new":return ke(),Me(),Ee.clearMessages(),Ee.setSystemPrompt(Te),me.clear(),we(x.emerald("Session cleared")+x.zinc400(" — fresh start")),ke(),re.requestRender(),!0;case"/env":{ke();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)} ${x.emerald("✓")} ${x.zinc400(n)}`}{const t=e.required?"必须":"可选";return` ${e.name.padEnd(18)} ${x.red("✗")} ${x.zinc600(`未配置(${t})`)}`}});return we(x.zinc200(b("Environment"))+"\n"+e.join("\n")),ke(),!0}case"/clear":{const e=[...me.children||[]];for(const t of e)try{me.removeChild(t)}catch{}return ke(),Z=!1,se=null,re.setFocus(ge),re.requestRender(),!0}case"/buy":{const[,o,s,i]=t;if(!o||!s||!i)return we(x.zinc400("Usage: /buy TICKER QTY PRICE_CENTS (e.g. /buy KXWTIMAX-26DEC31-T135 100 50)")),!0;if(!Ie.tradingEnabled)return we(x.red("Trading disabled. Run: sf setup --enable-trading")),!0;ke();if((await be(`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)});we(x.emerald("✓ Order placed: "+((t.order||t).order_id||"OK")))}catch(e){we(x.red("✗ "+e.message))}else we(x.zinc400("Cancelled."));return ke(),!0}case"/sell":{const[,o,s,i]=t;if(!o||!s||!i)return we(x.zinc400("Usage: /sell TICKER QTY PRICE_CENTS")),!0;if(!Ie.tradingEnabled)return we(x.red("Trading disabled. Run: sf setup --enable-trading")),!0;ke();if((await be(`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)});we(x.emerald("✓ Order placed: "+((t.order||t).order_id||"OK")))}catch(e){we(x.red("✗ "+e.message))}else we(x.zinc400("Cancelled."));return ke(),!0}case"/cancel":{const[,o]=t;if(!o)return we(x.zinc400("Usage: /cancel ORDER_ID")),!0;if(!Ie.tradingEnabled)return we(x.red("Trading disabled. Run: sf setup --enable-trading")),!0;ke();try{const{cancelOrder:e}=await Promise.resolve().then(n.t.bind(n,96139,23));await e(o),we(x.emerald(`✓ Order ${o} cancelled.`))}catch(e){we(x.red("✗ "+e.message))}return ke(),!0}case"/exit":case"/quit":return Ue(),!0;default:{const t=ye.find(e=>e.trigger===o);if(t){ke(),we(x.zinc200(`Running skill: ${b(t.name)}`)+x.zinc600(` — ${t.description.slice(0,60)}`)),ke(),re.requestRender(),Z=!0;try{await Ee.prompt(t.prompt)}catch(e){we(x.red(`Skill error: ${e.message}`))}finally{Z=!1}return!0}return!1}}}function Ue(){oe&&clearInterval(oe),We&&clearInterval(We),Le&&Le.stop(),Me(),re.stop(),process.exit(0)}function ze(e,t){const n=[];if(e._explorerMode){const t=e.edges?.length||0,o=e.theses?.length||0;n.push(x.zinc600("─".repeat(55))),n.push(" "+x.emerald(b("Explorer mode"))+x.zinc600(" — full market access, no thesis")),n.push(" "+x.zinc600(`${o} public theses │ ${t} edges tracked`)),n.push(x.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(" "+x.zinc400(b("TOP PUBLIC EDGES"))+x.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?x.emerald:Math.abs(s)>=8?x.amber:x.zinc400;n.push(` ${x.zinc400(e)} ${x.zinc400(o)} ${r(i.padStart(4))}`)}}return n.push(x.zinc600("─".repeat(55))),n.push(" "+x.zinc600("Ask anything, or describe a view to create a thesis.")),n.push(x.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(x.zinc600("─".repeat(55))),n.push(" "+x.zinc200(b(s))),n.push(" "+x.zinc600(`${e.status||"active"} ${i}%${a}`)+(null!==c?x.zinc600(` │ last eval: ${c<1?"<1":c}h ago`):"")),n.push(x.zinc600("─".repeat(55))),t&&t.length>0){n.push(" "+x.zinc400(b("POSITIONS")));let e=0;for(const o of t){const t=o.unrealized_pnl||0;e+=t;const s=t>=0?x.emerald(`+$${(t/100).toFixed(2)}`):x.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?x.emerald("Y"):x.red("N");n.push(` ${x.zinc400(i)} ${r} ${a} ${s}`)}const o=e>=0?x.emerald(b(`+$${(e/100).toFixed(2)}`)):x.red(b(`-$${(Math.abs(e)/100).toFixed(2)}`));n.push(` ${"".padEnd(28)} ${x.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(x.zinc600("─".repeat(55))),n.push(" "+x.zinc400(b("TOP EDGES"))+x.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?x.emerald:Math.abs(s)>=8?x.amber:x.zinc400;n.push(` ${x.zinc400(e)} ${x.zinc400(o)} ${a(i.padStart(4))} ${x.zinc600(r)}`)}}return n.push(x.zinc600("─".repeat(55))),n.join("\n")}Ee.subscribe(e=>{if("message_start"===e.type&&(Ne="",Re=null,Le=new D(re,e=>x.emerald(e),e=>x.zinc600(e),"thinking..."),Le.start(),me.addChild(Le),re.requestRender()),"message_update"===e.type){const t=e.assistantMessageEvent;"text_delta"===t.type&&(Le&&(Le.stop(),me.removeChild(Le),Le=null,Re=new N("",1,0,ae,ce),me.addChild(Re)),Ne+=t.delta,Re&&Re.setText(Ne),Fe||(Fe=setTimeout(()=>{Fe=null,re.requestRender()},66)))}if("message_end"===e.type&&(Le&&(Le.stop(),me.removeChild(Le),Le=null),Re&&Ne&&Re.setText(Ne),ke(),Re=null,Ne="",Ke()),"agent_end"===e.type&&(Z=!1,Me(),Ke(),ne)){const e=ne;ne=null,Je(e)}if("tool_execution_start"===e.type){const t=new J(x.zinc600(` ▸ ${e.toolName}...`));De.set(e.toolCallId||e.toolName,Date.now()),je.set(e.toolCallId||e.toolName,t),me.addChild(t),Q++,de.toolCount=Q,de.update(),re.requestRender()}if("tool_execution_end"===e.type){const t=e.toolCallId||e.toolName,n=De.get(t),o=n?((Date.now()-n)/1e3).toFixed(1):"?",s=je.get(t);s&&(e.isError?s.setText(x.red(` ✗ ${e.toolName} (${o}s) error`)):s.setText(x.zinc600(` ▸ ${e.toolName} `)+x.emerald("✓")+x.zinc600(` ${o}s`))),De.delete(t),je.delete(t),re.requestRender()}}),ge.onSubmit=async e=>{const t=e.trim();if(!t)return;if(se){const{resolve:e}=se;se=null;const n=new R(x.zinc400(" > ")+x.zinc200(t),1,0);return me.addChild(n),ke(),re.requestRender(),void e(t)}if(Z)return;if(ge.addToHistory(t),t.startsWith("/")){if(await qe(t))return}Z=!0;const n=new R(x.emerald(b(">"))+" "+x.white(t),1,0);me.addChild(n),ke(),re.requestRender();try{await Ee.prompt(t)}catch(e){Le&&(Le.stop(),me.removeChild(Le),Le=null),we(x.red(`Error: ${e.message}`)),ke(),Z=!1}},re.addInputListener(e=>{if(""===e)return Ue(),{consume:!0}}),process.on("SIGINT",Ue),process.on("SIGTERM",Ue);const He=Ae?x.zinc600(`resumed (${Ee.state.messages.length} messages)`):x.zinc600("new session");we(ze(k,ue)),we(" "+He),ke();const Be=.03;function Je(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>=Be){const t=o>0?"▲":"▼";we((o>0?x.emerald:x.red)(` ${t} Heartbeat: confidence ${s}${o}% → ${n}%`)),e.latestSummary&&we(x.zinc400(` ${e.latestSummary.slice(0,100)}`)),ke(),de.setFromContext({...k,confidence:e.confidence,lastEvaluation:{confidenceDelta:e.confidenceDelta}},ue||void 0),re.requestRender(),Z=!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.`;Ee.prompt(i).catch(e=>{we(x.red(`Error: ${e.message}`)),Z=!1})}else t>0&&(we(x.zinc600(` ─ heartbeat: ${n}% (${s}${o}%) — ${e.evaluationCount||0} eval(s)`)),re.requestRender())}C||(oe=setInterval(async()=>{try{const e=await w.getChanges(O,te);if(te=(new Date).toISOString(),!e.changed)return;Z||se?ne=e:Je(e)}catch{}},6e4));const We=setInterval(async()=>{try{const{writeAgentHeartbeat:e,readMessages:t}=await n.e(563).then(n.bind(n,9563));e(O||void 0);const o=t("agent","outbox").filter(e=>!e.read);for(const e of o)if(!Z&&!se){const{deleteMessage:t}=await n.e(563).then(n.bind(n,9563));we(("critical"===e.priority||"high"===e.priority?x.red:x.zinc400)(` [${e.from}] ${e.payload.summary||JSON.stringify(e.payload)}`)),t(e.id,"outbox"),re.requestRender()}}catch{}},3e4);re.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(e){return{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon. Evaluates intent triggers and executes orders via local keys.",parameters:{type:"object",properties:{}},execute:async()=>{const{existsSync:e,readFileSync:t,openSync:o,mkdirSync:s}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:i}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:r}=await Promise.resolve().then(n.t.bind(n,70857,23)),{spawn:a}=await Promise.resolve().then(n.t.bind(n,35317,23)),c=i(r(),".sf","runtime.pid"),l=i(r(),".sf","runtime.log");if(e(c)){const e=t(c,"utf-8").trim();try{return process.kill(parseInt(e),0),{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{try{(await Promise.resolve().then(n.t.bind(n,79896,23))).unlinkSync(c)}catch{}}}s(i(r(),".sf"),{recursive:!0});const d=o(l,"a");if(a(process.execPath,[process.argv[1],"runtime","start"],{detached:!0,stdio:["ignore",d,d],env:{...process.env}}).unref(),await new Promise(e=>setTimeout(e,1e3)),e(c)){return{content:[{type:"text",text:`Runtime started (PID ${t(c,"utf-8").trim()}). Log: ${l}`}],details:{}}}return{content:[{type:"text",text:"Runtime starting... check runtime_status in a moment."}],details:{}}}}}function m(){return{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:{type:"object",properties:{}},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:{}}}}}}function g(){return i.default.join(r.default.homedir(),".sf","sessions")}function f(e){return i.default.join(g(),`${e}.json`)}function y(e){const t=f(e);try{if(s.default.existsSync(t))return JSON.parse(s.default.readFileSync(t,"utf-8"))}catch{}return null}function $(e,t,n){const o=g();s.default.mkdirSync(o,{recursive:!0}),s.default.writeFileSync(f(e),JSON.stringify({thesisId:e,model:t,updatedAt:(new Date).toISOString(),messages:n},null,2))}const w=(e,t,n)=>o=>`[38;2;${e};${t};${n}m${o}[39m`,k=(e,t,n)=>o=>`[48;2;${e};${t};${n}m${o}[49m`,b=e=>`[1m${e}[22m`,v=e=>`[3m${e}[23m`,S=e=>`[4m${e}[24m`,_=e=>`[9m${e}[29m`,x={emerald:w(16,185,129),zinc200:w(228,228,231),zinc400:w(161,161,170),zinc600:w(82,82,91),zinc800:w(39,39,42),red:w(239,68,68),amber:w(245,158,11),white:w(255,255,255),bgZinc900:k(24,24,27),bgZinc800:k(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(`[2m${t.dryRun?"Previewing":"Running"} tree augmentation for ${e.slice(0,8)}...[22m`);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(` [33m⚠ ${s.warning}[39m`),console.log());if(s.suggestedNodes?.length>0){console.log(` [1mSuggested Nodes[22m (${s.suggestedNodes.length} from evaluations)`);for(const e of s.suggestedNodes)console.log(` • ${e.label} [2m(parent: ${e.parentNodeId}, est: ${Math.round(100*e.estimatedProbability)}%, seen ${e.frequency}x)[22m`);console.log()}if(s.acceptedNodes?.length>0){console.log(` [1m[32mAccepted Nodes[39m[22m (${s.acceptedNodes.length})`);for(const e of s.acceptedNodes)console.log(` [32m+[39m ${e.id}: ${e.label} [2m(prob: ${Math.round(100*e.probability)}%, imp: ${e.importance})[22m`);if(console.log(),Object.keys(s.updatedImportanceWeights||{}).length>0){console.log(" [1mRebalanced Weights[22m");for(const[e,t]of Object.entries(s.updatedImportanceWeights))console.log(` ${e} → ${t}`);console.log()}s.applied?console.log(" [32m✓ Applied to causal tree[39m"):t.dryRun&&console.log(" [2mDry run — use without --dry-run to apply[22m")}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 S=w.filter(e=>!e.position&&e.edge>0);if(S.length>0){const e=S[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:"[33m",armed:"[36m",triggered:"[35m",executing:"[34m",filled:"[32m",partial:"[33m",expired:"[90m",cancelled:"[90m",rejected:"[31m"};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 S=(new Date).toISOString().slice(0,10);console.log(),console.log(`${a.c.bold}Liquidity Scanner${a.c.reset} ${a.c.dim}(${S} UTC)${a.c.reset}`),console.log(a.c.dim+"─".repeat(68)+a.c.reset);const _={};for(const e of v){const t=e.topic||"OTHER";_[t]||(_[t]={}),_[t][e.horizon]||(_[t][e.horizon]=[]),_[t][e.horizon].push(e)}let x=0,O=0,C=0;const I=["weekly","monthly","long-term"];for(const[e,t]of Object.entries(_))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&&C++;const t=e.spread>5;let n;t&&O++,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 | ${O} thin (spread>5¢) | ${C} 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 [1mTraditional Markets[22m [2m${n.snapshotAt?.slice(0,10)||""}[22m\n`),!n.markets?.length)return void console.log(" No data available.\n");for(const e of n.markets){const t=e.changePct>=0?"[32m▲[39m":"[31m▼[39m",n=e.changePct>=0?`[32m+${e.changePct}%[39m`:`[31m${e.changePct}%[39m`,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),S=k.reduce((e,t)=>e+t.pnlCents,0),_=v>0?S/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:S,pnlPct:Math.round(10*_)/10}},null,2));const x=y.length>0?a(new Date(y[0])):"?",O=a(new Date);console.log(),console.log(` ${r.c.bold}Portfolio Performance${r.c.reset} ${r.c.dim}(${x} → ${O})${r.c.reset}`),console.log(` ${r.c.dim}${"─".repeat(76)}${r.c.reset}`),console.log();const C=Math.max(...k.map(e=>e.ticker.length),5)+2,I=C+50,P=(e,t)=>e.padEnd(t);console.log(` ${r.c.dim}${P("Ticker",C)} 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,C)} ${(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(S),E=`${_>=0?"+":""}${_.toFixed(1)}%`,A=S>=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",C)}${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(` [1m${l.query}[22m`),console.log(),l.answer&&(console.log(` ${l.answer}`),console.log());if(l.keyFactors?.length>0){console.log(" [2mKey factors:[22m");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(" [1mMarkets[22m");for(const e of d.slice(0,8)){const t=i(e.volume),n=e.ticker?` [2m${e.ticker}[22m`:"";console.log(` [36mK[39m ${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?` [2m${e.slug}[22m`:"";console.log(` [35mP[39m ${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(" [1mX signals[22m");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(" [1mTraditional[22m");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(" [1mTheses[22m");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(" [1mContent[22m");for(const e of l.content.slice(0,5)){const t=e.type.padEnd(9);console.log(` [2m${t}[22m ${e.title.slice(0,50)} [2m${e.url}[22m`)}console.log()}const m=l.meta||{},g=m.sources||l.sources||[],f=m.latencyMs?`${(m.latencyMs/1e3).toFixed(1)}s`:"";console.log(` [2mSources: ${g.join(", ")}${f?` (${f})`:""}[22m`),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").option("--smart","Enable LLM intelligence layer").description("Start the execution runtime").action(async e=>{if((0,i.isKalshiConfigured)()||(console.error(`\n ${a.c.red}Error:${a.c.reset} Kalshi credentials not configured.`),console.error(" Run: sf setup --enable-trading\n"),process.exit(1)),(0,c.existsSync)(u)){const e=(0,c.readFileSync)(u,"utf-8").trim();try{process.kill(parseInt(e),0),console.error(`\n ${a.c.yellow}Warning:${a.c.reset} Runtime already running (PID ${e}).`),console.error(" Stop it first: sf runtime stop\n"),process.exit(1)}catch{(0,c.unlinkSync)(u)}}if(e.daemon){const t=process.argv[1];(0,c.mkdirSync)((0,l.join)((0,d.homedir)(),".sf"),{recursive:!0});const n=(0,c.openSync)(p,"a"),s=["runtime","start"];e.smart&&s.push("--smart");const i=(0,o.spawn)(process.execPath,[t,...s],{detached:!0,stdio:["ignore",n,n],env:{...process.env}});i.unref();const r=e.smart?` ${a.c.cyan}[smart]${a.c.reset}`:"";return console.log(`\n ${a.c.green}OK${a.c.reset} Runtime started in background${r} (PID ${i.pid})`),console.log(` ${a.c.dim}Log: ${p}${a.c.reset}`),void console.log(` ${a.c.dim}Stop: sf runtime stop${a.c.reset}\n`)}const t=e.smart||(0,r.loadConfig)().smartDaemons||!1;await async function(e=!1){const t=(0,l.join)((0,d.homedir)(),".sf");(0,c.existsSync)(t)||(0,c.mkdirSync)(t,{recursive:!0});f(),(0,c.writeFileSync)(u,process.pid.toString()),console.log(),console.log(` ${a.c.bold}SimpleFunctions Runtime${a.c.reset}${e?` ${a.c.cyan}[smart]${a.c.reset}`:""}`),console.log(` ${a.c.dim}PID ${process.pid} · polling every ${m/1e3}s · Ctrl+C to stop${a.c.reset}`),g.size>0&&console.log(` ${a.c.dim}Loaded ${g.size} previously executed intent(s)${a.c.reset}`);console.log();const o=new s.SFClient;let p=0;process.on("uncaughtException",e=>{b(`Uncaught exception: ${e.message}`)}),process.on("unhandledRejection",e=>{b(`Unhandled rejection: ${e?.message||e}`)});const h=()=>{console.log(`\n ${a.c.dim}Runtime stopping...${a.c.reset}`),y();try{(0,c.unlinkSync)(u)}catch{}process.exit(0)};process.on("SIGINT",h),process.on("SIGTERM",h),process.on("exit",()=>{try{(0,c.unlinkSync)(u)}catch{}});const w=(0,r.loadConfig)().smartScanInterval||10;for(;;){p++;try{const{intents:t}=await o.listIntents({active:!0});if(!t||0===t.length){p%10==1&&b("No active intents. Waiting..."),await v(m);continue}const s=new Map;for(const e of t)if(!s.has(e.marketId)){const t=await(0,i.getMarketPrice)(e.marketId);null!==t&&s.set(e.marketId,t)}for(const n of t)await $(o,n,e);if(e&&p%w===0)try{const{periodicScan:e,evaluateWakeConditions:o}=await n.e(563).then(n.bind(n,9563)),i=await e("runtime",t,s);i&&b(`Smart scan:\n${i}`),await o("runtime",p,s)}catch(e){b(`Smart scan error (non-fatal): ${e.message}`)}if(e&&p%5==0)try{const{readMessages:e,deleteMessage:t}=await n.e(563).then(n.bind(n,9563)),o=e("runtime","inbox");for(const e of o)b(`Agent command: ${e.payload.action||e.payload.summary||"unknown"}`),t(e.id,"inbox")}catch{}}catch(e){b(`Error in cycle: ${e.message}`)}await v(m)}}(t)}),t.command("stop").description("Stop the runtime daemon").action(async()=>{if(!(0,c.existsSync)(u)){const e=k("runtime");if(e.length>0){for(const t of e)try{process.kill(t,"SIGTERM")}catch{}console.log(`\n ${a.c.green}OK${a.c.reset} Stopped ${e.length} orphan runtime process(es): ${e.join(", ")}\n`)}else console.log(`\n ${a.c.dim}No runtime running.${a.c.reset}\n`);return}const e=(0,c.readFileSync)(u,"utf-8").trim();try{process.kill(parseInt(e),"SIGTERM"),(0,c.unlinkSync)(u),console.log(`\n ${a.c.green}OK${a.c.reset} Runtime stopped (PID ${e}).\n`)}catch{(0,c.unlinkSync)(u),console.log(`\n ${a.c.dim}Runtime was not running (stale PID file removed).${a.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="",o=!1;if((0,c.existsSync)(u)){n=(0,c.readFileSync)(u,"utf-8").trim();try{process.kill(parseInt(n),0),t=!0}catch{t=!1}}if(!t){const e=k("runtime");e.length>0&&(t=!0,o=!0,n=e.join(", "))}const i=new s.SFClient,{intents:r}=await i.listIntents({active:!0});if(e.json)return void console.log(JSON.stringify({running:t,pid:t?n:null,intents:r},null,2));console.log();const l=t?o?`${a.c.yellow}RUNNING (orphan)${a.c.reset} PID ${n} — no PID file, use ${a.c.bold}sf runtime stop${a.c.reset} to fix`:`${a.c.green}RUNNING${a.c.reset} (PID ${n})`:`${a.c.dim}STOPPED${a.c.reset}`;if(console.log(` ${a.c.bold}Runtime${a.c.reset} ${l}`),t&&(0,c.existsSync)(p)&&console.log(` ${a.c.dim}Log: ${p}${a.c.reset}`),console.log(),!r||0===r.length)return console.log(` ${a.c.dim}No active intents.${a.c.reset}`),console.log(" Create one: sf intent buy TICKER QTY --price CENTS"),void console.log();const d={};for(const e of r)d[e.status]=(d[e.status]||0)+1;const h=Object.entries(d).map(([e,t])=>`${t} ${e}`).join(", ");console.log(` Active intents: ${h}`),console.log();for(const e of r){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(` ${a.c.dim}Start runtime to execute: sf runtime start${a.c.reset}`),console.log())}catch(e){console.error(`${a.c.red}Error:${a.c.reset} ${e.message}`),process.exit(1)}})};const o=n(35317),s=n(19218),i=n(96139),r=n(11627),a=n(99236),c=n(79896),l=n(16928),d=n(70857),u=(0,l.join)((0,d.homedir)(),".sf","runtime.pid"),p=(0,l.join)((0,d.homedir)(),".sf","runtime.log"),h=(0,l.join)((0,d.homedir)(),".sf","runtime-executed.json"),m=3e4,g=new Set;function f(){try{const e=JSON.parse((0,c.readFileSync)(h,"utf-8"));for(const t of e)g.add(t)}catch{}}function y(){try{(0,c.mkdirSync)((0,l.join)((0,d.homedir)(),".sf"),{recursive:!0}),(0,c.writeFileSync)(h,JSON.stringify([...g]))}catch{}}async function $(e,t,o=!1){if(!(t.activateAt&&new Date(t.activateAt)>new Date))if(new Date(t.expireAt)<new Date){b(`Intent ${t.id.slice(0,8)} expired`);try{await e.cancelIntentAPI(t.id)}catch{}}else{if("pending"===t.status&&b(`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 s=await async function(e){switch(e.triggerType){case"immediate":return!0;case"price_below":{if(!e.triggerPrice)return!1;const t=await(0,i.getMarketPrice)(e.marketId);return null!==t&&t<=e.triggerPrice}case"price_above":{if(!e.triggerPrice)return!1;const t=await(0,i.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(!s)return;if(b(`TRIGGERED: ${t.id.slice(0,8)} ${t.marketId} (${t.triggerType})`),o&&t.softCondition)try{const{evaluateSoftCondition:e}=await n.e(563).then(n.bind(n,9563));if(!await e(t))return void b(` Soft condition HOLD: "${t.softCondition.slice(0,60)}"`);b(` Soft condition PASS: "${t.softCondition.slice(0,60)}"`)}catch(e){return void b(` Soft condition error (defaulting to HOLD): ${e.message}`)}t.autoExecute?await w(e,t):b(` Awaiting confirmation. Use: sf intent status ${t.id.slice(0,8)}`)}"triggered"===t.status&&t.autoExecute&&await w(e,t)}}async function w(e,t){if(g.has(t.id))return;if("kalshi"!==t.venue)return void b(` Skipping ${t.id.slice(0,8)}: ${t.venue} execution not yet supported`);const n=t.targetQuantity-t.filledQuantity;if(n<=0)g.add(t.id);else{g.add(t.id),y(),b(` Executing: ${t.action.toUpperCase()} ${t.marketId} ${t.direction.toUpperCase()} x${n}${t.maxPrice?` @ ≤${t.maxPrice}c`:""}`);try{const o=await(0,i.createOrder)({ticker:t.marketId,side:t.direction,action:t.action,type:t.maxPrice?"limit":"market",count:n,...t.maxPrice?{yes_price:t.maxPrice}:{}}),s=o.order||o,r=Math.round(parseFloat(s.fill_count||s.fill_count_fp||n)),u=Math.round(parseFloat(s.yes_price||s.no_price||t.maxPrice||0));b(` ${a.c.green}FILLED${a.c.reset}: ${r} contracts, order ${s.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:r,price:t.maxPrice,orderId:s.order_id,source:t.source})+"\n";(0,c.appendFileSync)((0,l.join)((0,d.homedir)(),".sf","trade-journal.jsonl"),e)}catch{}try{await e.request("PATCH",`/api/intents/${t.id}`,{fill:{orderId:s.order_id||null,fillQuantity:r,fillPrice:u,fillCostCents:Math.round(u*r),venueResponse:{order_id:s.order_id,status:s.status}}}),b(` ${a.c.dim}Fill recorded to API${a.c.reset}`)}catch(e){b(` ${a.c.yellow}Warning:${a.c.reset} Failed to record fill to API: ${e.message}. Intent may re-execute on restart.`)}}catch(e){g.delete(t.id);const n=e.message||String(e);n.includes("403")?(b(` ${a.c.red}FAILED${a.c.reset}: 403 Forbidden — Kalshi key lacks write permission`),g.add(t.id)):b(` ${a.c.red}FAILED${a.c.reset}: ${n}`)}}}function k(e){try{const{execSync:t}=n(35317),o=t("ps ax -o pid,command",{encoding:"utf-8"}),s=[];for(const t of o.split("\n"))if(t.includes("sf")&&t.includes(e)&&!t.includes("--stop")&&!t.includes("status")){const e=parseInt(t.trim());isNaN(e)||e===process.pid||s.push(e)}return s}catch{return[]}}function b(e){const t=(new Date).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});console.log(` ${a.c.dim}${t}${a.c.reset} ${e}`)}function v(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 S(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 S(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 C(t))}else e.apiKey=await C(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 _(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 O(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=>`[32m${e}[39m`,u=e=>`[31m${e}[39m`,p=e=>`[2m${e}[22m`,h=e=>`[1m${e}[22m`,m=e=>`[36m${e}[39m`;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 S(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 _(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 O(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 C(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 S(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 _(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 O(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/health`,{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(`[31mError:[0m ${e.message}`),process.exit(1)}})};const o=n(19218),s={active:"[32m",watching:"[33m",executed:"[36m",cancelled:"[90m",review:"[31m"},i="[0m",r="[2m",a="[1m";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(` [31m⚠️ 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{const e=p();if(e.length>0){for(const t of e)try{process.kill(t,"SIGTERM")}catch{}console.log(` Stopped ${e.length} orphan bot process(es): ${e.join(", ")}`)}else console.log(" No running Telegram bot found.")}return}if(e.status){const e=u();if(e)console.log(` Telegram bot running (PID ${e})`),console.log(` Log: ${d}`);else{const e=p();e.length>0?(console.log(` Telegram bot running (orphan PID ${e.join(", ")} — no PID file)`),console.log(" Use --stop to terminate.")):console.log(" Telegram bot not running.")}return}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.t.bind(n,6012,23));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}}function p(){try{const{execSync:e}=n(35317),t=e("ps ax -o pid,command",{encoding:"utf-8"}),o=[];for(const e of t.split("\n"))if(/\bsf\b.*\btelegram\b/.test(e)&&!e.includes("--stop")&&!e.includes("--status")){const t=parseInt(e.trim());isNaN(t)||t===process.pid||o.push(t)}return o}catch{return[]}}},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)}}},64115:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateCommand=async function(){console.log(" Checking for updates...");try{const e=await fetch(`https://registry.npmjs.org/${s}/latest`);if(!e.ok)return void console.error(" Failed to check npm registry.");const t=(await e.json()).version,{join:i}=await Promise.resolve().then(n.t.bind(n,16928,23)),{readFileSync:r,existsSync:a}=await Promise.resolve().then(n.t.bind(n,79896,23));let c="0.0.0";try{const e=i(__dirname,"..","package.json");a(e)&&(c=JSON.parse(r(e,"utf-8")).version)}catch{}if(c===t)return void console.log(` Already on latest version (${c}).`);const l=function(){try{const e=(0,o.execSync)("which sf",{encoding:"utf-8"}).trim();if(e.includes("pnpm"))return"pnpm";if(e.includes("yarn"))return"yarn"}catch{}try{if((0,o.execSync)("pnpm list -g --depth=0 2>/dev/null",{encoding:"utf-8"}).includes(s))return"pnpm"}catch{}try{if((0,o.execSync)("yarn global list --depth=0 2>/dev/null",{encoding:"utf-8"}).includes(s))return"yarn"}catch{}return"npm"}(),d="pnpm"===l?`pnpm add -g ${s}@latest`:"yarn"===l?`yarn global add ${s}@latest`:`npm install -g ${s}@latest`;console.log(` ${c} → ${t}`),console.log(` Running: ${d}\n`),(0,o.execSync)(d,{stdio:"inherit"}),console.log(`\n [32m✓ Updated to ${t}[39m`)}catch(e){console.error(` Update failed: ${e.message}`),console.error(` Try manually: npm install -g ${s}@latest`)}};const o=n(35317),s="@spfunctions/cli"},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()}const m=()=>{h||console.log(`\n ${o.c.dim}Watch stopped.${o.c.reset}\n`),process.exit(0)};switch(process.on("SIGINT",m),process.on("SIGTERM",m),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?"[35mP[39m":"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 [1m[36mX: ${e}[0m\n`),console.log(` ${a.summary}\n`),a.sentiment){const e={bullish:"[32m",bearish:"[31m",mixed:"[33m",neutral:"[2m"};console.log(` Sentiment: ${e[a.sentiment]||""}${a.sentiment}[0m`)}a.keyThemes?.length&&console.log(` Themes: ${a.keyThemes.join(", ")}`),console.log()}const c=a.posts||[];if(c.length>0){console.log(` [1mTop posts[22m (${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(` [36m@${e.authorUsername}[0m${o}`),console.log(` ${e.text.slice(0,140)}${e.text.length>140?"...":""}`),console.log(` [2m♥ ${t} ↻ ${n}[0m\n`)}}if(a.volume){const e=a.volume,t=e.velocityChange>1?`[32m+${Math.round(100*(e.velocityChange-1))}%[0m`:`[31m${Math.round(100*(e.velocityChange-1))}%[0m`;console.log(` [2mVolume: ${i(e.totalCount)} posts (${o}h) | Velocity: ${t} | Peak: ${e.peak?.count}[0m\n`)}const l=a.news||[];if(l.length>0){console.log(` [1mX News[22m (${l.length})\n`);for(const e of l.slice(0,5)){const t=e.tickers?.length?` [33m${e.tickers.join(" ")}[0m`:"";console.log(` ${e.title}${t}`),console.log(` [2m${e.summary.slice(0,120)}...[0m\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 [1m[36mX Volume: ${e}[0m\n`),console.log(` Total: ${i(r.totalCount)} posts (${n}h)`);const a=r.velocityChange>1?`[32m+${Math.round(100*(r.velocityChange-1))}%[0m`:`[31m${Math.round(100*(r.velocityChange-1))}%[0m`;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 [1m[36mX News: ${e}[0m (${i.length} stories)\n`);for(const e of i){const t=e.tickers?.length?` [33m${e.tickers.join(" ")}[0m`:"",n=e.categories?.length?`[2m[${e.categories.join(", ")}][0m`:"";console.log(` [1m${e.title}[22m${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 [1m[36m@${n}[0m (${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(` [2m${o}[0m ${e.text.slice(0,140)}${e.text.length>140?"...":""}`),console.log(` [2m♥ ${t} ↻ ${n}[0m\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(` [36m${i}[39m`),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),process.on("uncaughtException",e=>{l(),console.error("Dashboard crashed:",e.message),process.exit(1)}),process.on("unhandledRejection",e=>{t&&(t.error=`${e?.message||e}`.slice(0,50))});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",O,()=>(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{}},O)),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":F(i,a,c,l,e,n,o,s);break;case"detail":!function(e,t,n,o,s){t?(n.mode="overview",s()):"b"===e?(K(n,"buy"),s()):"s"===e?(K(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),S=n(29405),_=n(67748),x=n(87009),O=15e3,C=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",O,()=>(0,d.getPositions)()),t?(0,a.cached)("theses",C,()=>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",O,()=>(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}`,C,()=>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",C,()=>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":j(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,S.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):j(e,t),(0,_.renderTrade)(e,(0,s.fullLayout)(e.cols,e.rows),t)}e.flush()}function j(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 F(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)K(s,"buy"),r();else if("s"===e)K(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||"";K(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 K(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+="[0m",r.fg&&(e+=r.fg),r.bg&&(e+=r.bg),t=r.fg,n=r.bg),e+=r.char)}e&&(e+="[0m",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("[2J")}}},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 S=null;for(const[,e]of n.contexts){if((e?.edges||[]).some(e=>e.marketId===c||e.ticker===c)){S=e;break}}const _=[];!function e(t,n=0){for(const o of t)_.push({...o,depth:n}),o.children&&e(o.children,n+1)}(S?.causalTree?.nodes||[]);const x=_.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 O=i+k+2;e.write(b,O,"Orderbook",o.CLR.title);const C=S?.edges?.find(e=>e.marketId===c||e.ticker===c),I=C?.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,O,[{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,O,[{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,O,[{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,O," (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,S=Math.abs(g)/u,_=Math.floor(S*v),x=S*v-_,O=Math.min(Math.floor(8*x),7),C=s[7].repeat(_)+(x>.1?s[O]:""),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)(C,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}/${$}`:`${$}`,S=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,S),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 S="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),S?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,O=a.qty,C=O-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: $${O.toFixed(2)}`,fg:o.CLR.dim}]),g++,e.writeStyled(u+g,h,[{text:"Profit: ",fg:o.CLR.dim},{text:`$${C.toFixed(2)}`,fg:C>=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:"[0m",bold:"[1m",dim:"[2m",red:"[31m",green:"[32m",yellow:"[33m",blue:"[34m",magenta:"[35m",cyan:"[36m",white:"[37m",gray:"[90m"}},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),S=n(28423),_=n(96616),x=n(44040),O=n(45475),C=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),j=n(69903),F=n(35344),K=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(64115),Z=n(93402),ee=n(72124),te=n(99236);(0,s.applyConfig)(),(0,Z.checkForUpdates)();const ne=new t.Command,oe='\n[1mSimpleFunctions CLI[22m — prediction market thesis agent\n\n[1mUsage:[22m sf <command> [options]\n sf <command> --help for detailed options\n\n[1mSetup[22m\n [36mlogin[39m Browser login (recommended)\n [36mlogout[39m Clear saved credentials\n [36msetup[39m Interactive config wizard (power users)\n [36msetup --check[39m Show config status\n [36msetup --polymarket[39m Configure Polymarket wallet\n [36mupdate[39m Update CLI to latest version\n\n[1mThesis[22m\n [36mlist[39m List all theses\n [36mget[39m <id> Full thesis details\n [36mcontext[39m [id] [--json] Market snapshot (no id) or thesis context (with id)\n [36mcreate[39m "thesis" Create a new thesis\n [36msignal[39m <id> "content" Inject a signal\n [36mevaluate[39m <id> Trigger deep evaluation\n [36maugment[39m <id> Evolve causal tree with new nodes\n [36mpublish[39m / [36munpublish[39m <id> Manage public visibility\n [36mheartbeat[39m <id> View/configure heartbeat settings & costs\n\n[1mWorld Model[22m [2m(no auth)[22m\n [36mworld[39m Real-time world state (~800 tokens, prediction index + markets)\n [36mworld --delta[39m What changed since last check (~30-50 tokens)\n [36mworld --focus[39m energy,geo Deep coverage on specific topics\n [36mideas[39m S&T-style trade ideas: conviction, catalyst, direction, risk\n\n[1mSearch[22m\n [36mquery[39m "question" LLM-enhanced market knowledge search [2m(no auth)[22m\n [36mmarkets[39m Traditional markets: SPY, VIX, bonds, gold, oil [2m(no auth)[22m\n\n[1mMarkets[22m\n [36mscan[39m "keywords" Search Kalshi + Polymarket\n [36mscan[39m --series TICKER Browse a Kalshi series\n [36medges[39m [--json] Top edges across all theses\n [36mwatch[39m [query] [mode] Watch markets (modes: orderbook, flow, cross-venue, all)\n [36mwhatif[39m <id> What-if scenario analysis\n [36mliquidity[39m [topic] Orderbook liquidity scanner\n [36mbook[39m <ticker> [ticker2...] Orderbook depth for specific markets\n [36mexplore[39m [slug] Browse public theses\n [36mforecast[39m <event> Market distribution (P50/P75/P90)\n\n[1mShare[22m [2m(any command with --share generates a short URL)[22m\n [36mscan[39m "gold" --share Share scan results\n [36mquery[39m "fed rate" --share Share query results\n [36mcontext[39m --share Share global context snapshot\n\n[1mPortfolio[22m\n [36mpositions[39m Kalshi + Polymarket positions\n [36mbalance[39m Account balance\n [36morders[39m Resting orders\n [36mfills[39m Recent trade fills\n [36msettlements[39m Settled contracts with P&L\n [36mperformance[39m P&L over time\n [36mdashboard[39m Interactive TUI overview\n\n[1mIntents[22m [2m(declarative execution — the single gateway for all orders)[22m\n [36mintent buy[39m <ticker> <qty> Create buy intent with trigger conditions\n [36mintent sell[39m <ticker> <qty> Create sell intent\n [36mintent list[39m Active intents (--all for history)\n [36mintent status[39m <id> Detailed status + fills\n [36mintent cancel[39m <id> Cancel an intent\n\n[1mTrading[22m [2m(requires sf setup --enable-trading)[22m\n [36mbuy[39m <ticker> <qty> Buy contracts (direct, no intent)\n [36msell[39m <ticker> <qty> Sell contracts (direct, no intent)\n [36mcancel[39m [orderId] Cancel order(s)\n [36mrfq[39m <ticker> <qty> Request for quote\n\n[1mRuntime[22m\n [36mruntime start[39m Start execution daemon (evaluates triggers, places orders)\n [36mruntime stop[39m Stop daemon\n [36mruntime status[39m Active intents + runtime state\n\n[1mInteractive[22m\n [36magent[39m [id] Agent with natural language + tools\n [36mprompt[39m [id] Dynamic system prompt for any agent\n [36mtelegram[39m Telegram bot for monitoring\n\n[1mX / Twitter[22m\n [36mx[39m "query" Search X discussions (summary + raw mode)\n [36mx-volume[39m "query" Discussion volume and velocity trend\n [36mx-news[39m "query" X news stories (Grok-aggregated)\n [36mx-account[39m @username Recent posts from a specific account\n\n[1mInfo[22m\n [36mfeed[39m Evaluation history stream\n [36mdelta[39m <id> Changes since timestamp\n [36mmilestones[39m Upcoming Kalshi events\n [36mschedule[39m Exchange status\n [36mannouncements[39m Exchange announcements\n [36mhistory[39m <ticker> Historical market data\n';ne.name("sf").description("SimpleFunctions CLI — prediction market thesis agent").version("1.7.28").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 oe;const{Help:o}=n(18909);return(new o).formatHelp(e,t)}}).action(async()=>{await async function(){if(!process.stdin.isTTY)return void console.log(oe);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{return void await(0,f.agentCommand)(void 0,{})}console.log(),console.log(" [1mSimpleFunctions[22m — prediction market intelligence"),console.log(),(0,s.isConfigured)()?console.log(" [2mYou have no active theses.[22m"):console.log(" [2mNo login needed to explore.[22m");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 [36m>[39m ",n=>{t.close(),e(n.trim())})});if(!o)return void console.log(oe);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(` [2mScanning Kalshi + Polymarket for: "${r}"...[22m`),console.log();try{const{scanCommand:e}=await Promise.resolve().then(n.bind(n,46183));await e(r,{json:!1})}catch(e){console.error(` [31mScan failed: ${e.message}[39m`)}console.log(),(0,s.isConfigured)()?(console.log(" [2mWant to monitor this thesis 24/7?[22m"),console.log(` [36msf create[39m "${o.slice(0,60)}"`)):(console.log(" [2mWant 24/7 monitoring + edge detection?[22m"),console.log(" [36msf setup[39m to get started (2 min)"));console.log()}()});const se=new Set(["setup","login","logout","help","status","update","scan","explore","query","context","markets","watch","milestones","forecast","settlements","balance","orders","fills","schedule","announcements","history","liquidity","book","prompt","agent","world","ideas","sf"]);async function ie(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,te.die)(t)}}ne.hook("preAction",(e,t)=>{const n=t.name();if(se.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. [36msf login[39m Browser login (30 sec, recommended)"),console.log(" 2. [36msf setup[39m Interactive wizard (2 min)"),console.log(" 3. [36msf --api-key KEY[39m Pass inline"),console.log(),console.log(" [2mGet a key at: [36mhttps://simplefunctions.dev/dashboard/keys[22m"),console.log(' [2mNo key? Try [36msf scan "oil"[22m[2m — works without login.[22m')),console.log(),process.exit(1)}}),ne.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 ie(()=>(0,y.setupCommand)({check:e.check,reset:e.reset,key:e.key,enableTrading:e.enableTrading,disableTrading:e.disableTrading,kalshi:e.kalshi,polymarket:e.polymarket}))}),ne.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 ie(()=>(0,z.loginCommand)({apiUrl:n.apiUrl,force:e.force}))}),ne.command("logout").description("Clear saved credentials").action(async()=>{await ie(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(` ${te.c.dim}Run ${te.c.cyan}sf login${te.c.dim} to re-authenticate.${te.c.reset}\n`)):console.log(`\n ${te.c.dim}Not logged in.${te.c.reset}\n`)})}),ne.command("update").description("Update CLI to latest version").action(async()=>{await ie(()=>(0,Q.updateCommand)())}),ne.command("status").description("Health check: verify API, auth, Kalshi, Polymarket connections").option("--json","JSON output").action(async e=>{await ie(()=>(0,ee.statusCommand)({json:e.json}))}),ne.command("list").description("List all theses").option("--json","JSON output").action(async(e,t)=>{const n=t.optsWithGlobals();await ie(()=>(0,r.listCommand)({json:e.json,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.command("get <id>").description("Get full thesis details").option("--json","Output raw JSON").action(async(e,t,n)=>{const o=n.optsWithGlobals();await ie(()=>(0,a.getCommand)(e,{json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ne.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 ie(()=>(0,c.contextCommand)(e,{json:t.json,share:t.share,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ne.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 ie(()=>(0,l.createCommand)(e,{async:t.async,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ne.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 ie(()=>(0,d.signalCommand)(e,t,{type:n.type,json:n.json,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.command("evaluate <id>").description("Trigger a deep evaluation (heavy model, force-heavy mode)").action(async(e,t,n)=>{const o=n.optsWithGlobals();await ie(()=>(0,u.evaluateCommand)(e,{apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ne.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 ie(()=>{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})})}),ne.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 ie(()=>(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}))}),ne.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 ie(()=>(0,h.watchCommand)(e,t,{interval:n.interval,json:n.json,thesis:n.thesis,smart:n.smart,execute:n.execute}))}),ne.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 ie(()=>(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}))}),ne.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 ie(()=>(0,m.positionsCommand)({json:e.json,thesis:e.thesis,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.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 ie(()=>(0,f.agentCommand)(e,{model:t.model,modelKey:t.modelKey,newSession:t.new,noTui:t.plain}))}),ne.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 ie(()=>(0,$.publishCommand)(e,{slug:t.slug,description:t.description,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ne.command("unpublish <thesisId>").description("Remove a thesis from public viewing").action(async(e,t,n)=>{const o=n.optsWithGlobals();await ie(()=>(0,$.unpublishCommand)(e,{apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ne.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 ie(()=>(0,w.exploreCommand)(e,{json:t.json,share:t.share}))}),ne.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 ie(()=>(0,k.dashboardCommand)({json:e.json,once:e.once,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.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 ie(()=>(0,v.milestonesCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.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 ie(()=>(0,S.forecastCommand)(e,t))}),ne.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 ie(()=>(0,_.settlementsCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.command("balance").description("Kalshi account balance").option("--json","JSON output").action(async e=>{await ie(()=>(0,x.balanceCommand)(e))}),ne.command("orders").description("Kalshi resting orders").option("--status <status>","Order status filter (default: resting)","resting").option("--json","JSON output").action(async e=>{await ie(()=>(0,O.ordersCommand)(e))}),ne.command("fills").description("Recent trade fills").option("--ticker <ticker>","Filter by market ticker").option("--json","JSON output").action(async e=>{await ie(()=>(0,C.fillsCommand)(e))}),ne.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 ie(()=>(0,I.feedCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.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 ie(()=>(0,U.deltaCommand)(e,{...t,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ne.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 ie(()=>(0,P.whatifCommand)(e,{set:t.set,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ne.command("schedule").description("Exchange status and trading hours").option("--json","JSON output").action(async e=>{await ie(()=>(0,A.scheduleCommand)(e))}),ne.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 ie(()=>(0,T.buyCommand)(e,t,n))}),ne.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 ie(()=>(0,T.sellCommand)(e,t,n))}),ne.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 ie(()=>(0,E.cancelCommand)(e,t))}),ne.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 ie(()=>(0,M.rfqCommand)(e,t,n))}),ne.command("announcements").description("Exchange announcements (rule changes, maintenance)").option("--json","JSON output").action(async e=>{await ie(()=>(0,R.announcementsCommand)(e))}),ne.command("history <ticker>").description("Historical market data (settled/closed)").option("--json","JSON output").action(async(e,t)=>{await ie(()=>(0,N.historyCommand)(e,t))}),ne.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 ie(()=>(0,L.performanceCommand)(e))}),ne.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 ie(()=>(0,D.liquidityCommand)({...t,topic:e}))}),ne.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 ie(()=>(0,j.bookCommand)(e,t))}),ne.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 ie(()=>(0,F.promptCommand)(e,{sections:t.sections,maxLength:t.maxLength,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ne.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 ie(()=>(0,K.augmentCommand)(e,{dryRun:t.dryRun,json:t.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ne.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 ie(()=>(0,J.marketsCommand)({json:e.json,share:e.share}))}),ne.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 ie(()=>(0,B.queryCommand)(e,{json:t.json,share:t.share,limit:t.limit}))}),ne.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 ie(()=>(0,q.telegramCommand)(e))}),ne.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 ie(()=>(0,W.xSearchCommand)(e,t))}),ne.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 ie(()=>(0,W.xVolumeCommand)(e,t))}),ne.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 ie(()=>(0,W.xNewsCommand)(e,t))}),ne.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 ie(()=>(0,W.xAccountCommand)(e,t))}),ne.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 ie(()=>(0,Y.worldCommand)(e))}),ne.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 ie(()=>(0,V.ideasCommand)(e))}),(0,b.registerStrategies)(ne),(0,X.registerIntents)(ne),(0,G.registerRuntime)(ne);const re=new Set(["agent","watch","telegram","dashboard"]);ne.hook("postAction",(e,t)=>{re.has(t.name())||setTimeout(()=>process.exit(0),100)}),ne.parse()})(),module.exports=o})();
|
|
2
|
+
(()=>{var e={93402:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.checkForUpdates=function(){const e=u(),t=d();t.latestVersion&&function(e,t){const n=e.replace(/^v/,"").split(".").map(Number),s=t.replace(/^v/,"").split(".").map(Number);for(let e=0;e<3;e++){if((n[e]||0)<(s[e]||0))return!0;if((n[e]||0)>(s[e]||0))return!1}return!1}(e,t.latestVersion)&&console.log(` [33m↑ Update available: ${e} → ${t.latestVersion}. Run [1msf update[22;33m to install.[39m`);if(Date.now()-t.lastCheck<l)return;const n=`\n const fs = require('fs');\n const path = require('path');\n const f = ${JSON.stringify(c)};\n fetch('https://registry.npmjs.org/${a}/latest', {signal: AbortSignal.timeout(5000)})\n .then(r => r.json())\n .then(d => {\n fs.mkdirSync(path.dirname(f), {recursive: true});\n fs.writeFileSync(f, JSON.stringify({lastCheck: Date.now(), latestVersion: d.version}));\n }).catch(() => {});\n `,s=(0,r.spawn)(process.execPath,["-e",n],{detached:!0,stdio:"ignore"});s.unref()};const s=n(79896),o=n(16928),i=n(70857),r=n(35317),a="@spfunctions/cli",c=(0,o.join)((0,i.homedir)(),".sf","update-check.json"),l=36e5;function d(){try{if((0,s.existsSync)(c))return JSON.parse((0,s.readFileSync)(c,"utf-8"))}catch{}return{lastCheck:0,latestVersion:null}}function u(){try{const e=(0,o.join)(__dirname,"..","package.json");if((0,s.existsSync)(e))return JSON.parse((0,s.readFileSync)(e,"utf-8")).version;const t=(0,o.join)(__dirname,"package.json");if((0,s.existsSync)(t))return JSON.parse((0,s.readFileSync)(t,"utf-8")).version}catch{}return"0.0.0"}},87783:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.cached=async function(e,t,s){const o=n.get(e);if(o&&Date.now()<o.expiry)return o.data;try{const o=await s();return n.set(e,{data:o,expiry:Date.now()+t}),o}catch(e){if(o)return o.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 s("/series",{include_volume:"true"});return e.series||[]},t.kalshiFetchEvents=async function(e){const t=await s("/events",{series_ticker:e,status:"open",with_nested_markets:"true",limit:"200"});return t.events||[]},t.kalshiFetchMarket=async function(e){const t=await s(`/markets/${e}`);return t.market||t},t.kalshiFetchMarketsBySeries=async function(e){const t=await s("/markets",{series_ticker:e,status:"open",limit:"200"});return t.markets||[]},t.kalshiFetchMarketsByEvent=async function(e){const t=await s("/markets",{event_ticker:e,status:"open",limit:"1000"});return t.markets||[]},t.fetchGlobalContext=async function(){const e=await fetch(`${o}/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(`${o}/api/public/query?q=${encodeURIComponent(e)}`);if(!t.ok)throw new Error(`Query API error: ${t.status}`);return t.json()},t.fetchTraditionalMarkets=async function(e){const t=e?`?topic=${encodeURIComponent(e)}`:"",n=await fetch(`${o}/api/public/markets${t}`);if(!n.ok)throw new Error(`Markets API error: ${n.status}`);return n.json()};const n="https://api.elections.kalshi.com/trade-api/v2";async function s(e,t){const s=new URL(`${n}${e}`);if(t)for(const[e,n]of Object.entries(t))void 0!==n&&""!==n&&s.searchParams.set(e,n);const o=await fetch(s.toString());if(!o.ok)throw new Error(`Kalshi API ${o.status}: ${await o.text()}`);return o.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 s=`${this.baseUrl}${t}`,o={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},i=await fetch(s,{method:e,headers:o,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,s="cli"){return this.request("POST",`/api/thesis/${e}/signal`,{type:t,content:n,source:s})}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",s=t?.hours||24,o=t?.limit||20;return this.request("GET",`/api/x/search?q=${encodeURIComponent(e)}&mode=${n}&hours=${s}&limit=${o}`)}async getXVolume(e,t){const n=t?.hours||72,s=t?.granularity||"hour";return this.request("GET",`/api/x/volume?q=${encodeURIComponent(e)}&hours=${n}&granularity=${s}`)}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(/^@/,""),s=t?.hours||24,o=t?.limit||20;return this.request("GET",`/api/x/account?username=${n}&hours=${s}&limit=${o}`)}};const o="https://simplefunctions.dev"},83969:function(e,t,n){"use strict";var s=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 s=t?.modelKey||process.env.OPENROUTER_API_KEY,o=process.env.SF_API_KEY,i=process.env.SF_API_URL||"https://simplefunctions.dev",r=!s&&!!o,l=s||o,d=r?`${i}/api/proxy`:"https://openrouter.ai/api/v1";l||(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(" [2mUsing SimpleFunctions LLM proxy (no OpenRouter key needed)[22m");else try{(await fetch("https://openrouter.ai/api/v1/auth/key",{headers:{Authorization:`Bearer ${l}`},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 b=new a.SFClient;let v,x=e||null,I=!1;if(!x){let e=[];try{const t=await b.listTheses();e=(t.theses||t).filter(e=>"active"===e.status)}catch{e=[]}if(0===e.length)I=!0;else if(1===e.length)x=e[0].id;else if(process.stdin.isTTY&&!t?.noTui){const t=await async function(e,t=!1){return new Promise(n=>{let s=0;const o=[];t&&o.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);o.push({id:t.id,conf:e,title:n})}const i=process.stdout.write.bind(process.stdout);function r(){i("[H[2J"),i("\n [2mSelect thesis[22m\n\n");for(let e=0;e<o.length;e++){const t=o[e],n=e===s,r=n?"[38;2;16;185;129m › [39m":" ";if("_explorer"===t.id){const e=n?`[38;2;16;185;129m${t.title}[39m`:`[38;2;80;80;88m${t.title}[39m`;i(`${r}${e}\n`)}else{const e=n?`[38;2;16;185;129m${t.id.slice(0,8)}[39m`:`[38;2;55;55;60m${t.id.slice(0,8)}[39m`,s=`[38;2;55;55;60m${t.conf}%[39m`,o=n?`[38;2;160;160;165m${t.title}[39m`:`[38;2;80;80;88m${t.title}[39m`;i(`${r}${e} ${s} ${o}\n`)}}i("\n [38;2;55;55;60m↑↓ navigate · enter select[39m")}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]?(s=(s-1+o.length)%o.length,r()):27===t[0]&&91===t[1]&&66===t[2]?(s=(s+1)%o.length,r()):"k"===e?(s=(s-1+o.length)%o.length,r()):"j"===e?(s=(s+1)%o.length,r()):"\r"===e||"\n"===e?(c(),n(o[s].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?I=!0:x=t}else x=e[0].id}if(I){try{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));v=await e()}catch{v={edges:[],theses:[]}}v._explorerMode=!0}else try{v=await b.getContext(x)}catch(e){console.error(`Warning: Could not fetch thesis context (${e.message}). Starting with limited context.`),v={thesisId:x,edges:[],causalTree:{nodes:[]}}}if(t?.noTui)return async function(e){const{openrouterKey:t,sfClient:s,resolvedThesisId:o,opts:i,useProxy:r,llmBaseUrl:a,sfApiKey:l,sfApiUrl:d}=e;let g=e.latestContext;const b=await Promise.resolve().then(n.t.bind(n,23785,23)),v=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),x=await Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653)),{getModel:I,streamSimple:P,Type:T}=v,{Agent:E}=x,A=i?.model||"anthropic/claude-sonnet-4.6";let M=A.replace(/^openrouter\//,"");function R(e){let t;try{t=I("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=a),t}let N=R(M);const L=T.Object({thesisId:T.String({description:"Thesis ID"})}),D=T.Object({thesisId:T.String({description:"Thesis ID"}),content:T.String({description:"Signal content"}),type:T.Optional(T.String({description:"Signal type: news, user_note, external"}))}),j=T.Object({query:T.Optional(T.String({description:"Keyword search"})),series:T.Optional(T.String({description:"Series ticker"})),market:T.Optional(T.String({description:"Market ticker"}))}),F=T.Object({query:T.String({description:"Search keywords"})}),K=T.Object({}),q=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:L,execute:async(e,t)=>{const n=await s.getContext(t.thesisId);return g=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:K,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:T.Object({q:T.String({description:"Natural language query"})}),execute:async(e,t)=>{const{fetchQuery:s}=await Promise.resolve().then(n.bind(n,19218)),o=await s(t.q);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"get_markets",label:"Traditional Markets",description:"Traditional market prices via Databento. Use topic for deep dives: energy, rates, fx, equities, crypto, volatility.",parameters:T.Object({topic:T.Optional(T.String({description:"Deep dive: energy, rates, fx, equities, crypto, volatility"}))}),execute:async(e,t)=>{const{fetchTraditionalMarkets:s}=await Promise.resolve().then(n.bind(n,19218)),o=await s(t.topic);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"query_databento",label:"Databento Query",description:"Free-form historical data: stocks, ETFs, CME futures, options. OHLCV, trades, BBO. Max 30 days.",parameters:T.Object({symbols:T.String({description:"Comma-separated. Futures: ROOT.c.0. E.g. SPY, CL.c.0"}),dataset:T.Optional(T.String({description:"DBEQ.BASIC, GLBX.MDP3, OPRA.PILLAR"})),schema:T.Optional(T.String({description:"ohlcv-1d, ohlcv-1h, ohlcv-1m, trades"})),stype:T.Optional(T.String({description:"raw_symbol or continuous"})),days:T.Optional(T.Number({description:"Lookback (max 30)"}))}),execute:async(e,t)=>{const n=new URLSearchParams({symbols:t.symbols});t.dataset&&n.set("dataset",t.dataset),t.schema&&n.set("schema",t.schema),t.stype&&n.set("stype",t.stype),t.days&&n.set("days",String(t.days));const s=process.env.SF_API_URL||"https://simplefunctions.dev",o=await fetch(`${s}/api/public/databento?${n.toString()}`);if(!o.ok)return{content:[{type:"text",text:`Databento error: ${o.status}`}],details:{}};const i=await o.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"inject_signal",label:"Inject Signal",description:"Inject a signal into the thesis",parameters:D,execute:async(e,t)=>{const n=await s.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:L,execute:async(e,t)=>{const n=await s.evaluate(t.thesisId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}},{name:"scan_markets",label:"Scan Markets",description:"Search Kalshi prediction markets",parameters:j,execute:async(e,t)=>{let n;if(t.market)n=await(await f()).kalshiFetchMarket(t.market);else if(t.series)n=await(await f()).kalshiFetchMarketsBySeries(t.series);else if(t.query){const e=await(await f()).kalshiFetchAllSeries(),s=t.query.toLowerCase().split(/\s+/);n=e.filter(e=>s.every(t=>((e.title||"")+(e.ticker||"")).toLowerCase().includes(t))).filter(e=>parseFloat(e.volume_fp||"0")>1e3).sort((e,t)=>parseFloat(t.volume_fp||"0")-parseFloat(e.volume_fp||"0")).slice(0,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:K,execute:async()=>{const e=await s.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:K,execute:async()=>{const e=await(await u()).getPositions();if(!e)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};for(const t of e){const e=await(await u()).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:F,execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY;if(!n&&!(!n&&l))return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let s;if(s=n?await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,query:t.query,max_results:5,search_depth:"basic",include_answer:!0})}):await fetch(`${d}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({query:t.query,max_results:5,search_depth:"basic",include_answer:!0})}),!s.ok)return{content:[{type:"text",text:`Search failed: ${s.status}`}],details:{}};const o=await s.json(),i=(o.results||[]).map(e=>`[${e.title}](${e.url})\n${e.content?.slice(0,200)}`).join("\n\n");return{content:[{type:"text",text:`${o.answer?`Summary: ${o.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:T.Object({hours:T.Optional(T.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:T.Optional(T.String({description:"Filter by category (e.g. Economics, Politics, Sports)"}))}),execute:async(e,t)=>{const n=t.hours||168,s=new Date,o=`https://api.elections.kalshi.com/trade-api/v2/milestones?limit=200&minimum_start_date=${s.toISOString()}`+(t.category?`&category=${t.category}`:""),i=await fetch(o,{headers:{Accept:"application/json"}});if(!i.ok)return{content:[{type:"text",text:`Milestones API error: ${i.status}`}],details:{}};const r=await i.json(),a=s.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()-s.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:T.Object({eventTicker:T.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:T.Optional(T.Number({description:"Days of history (default 7)"}))}),execute:async(e,t)=>{const{getForecastHistory:s}=await Promise.resolve().then(n.t.bind(n,96139,23)),o=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 s({seriesTicker:a,eventTicker:t.eventTicker,percentiles:[5e3,7500,9e3],startTs:Math.floor((Date.now()-864e5*o)/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:T.Object({ticker:T.Optional(T.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getSettlements:s}=await Promise.resolve().then(n.t.bind(n,96139,23)),o=await s({limit:100,ticker:t.ticker});return o?{content:[{type:"text",text:JSON.stringify(o.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:K,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:T.Object({status:T.Optional(T.String({description:"Filter by status: resting, canceled, executed. Default: resting"}))}),execute:async(e,t)=>{const{getOrders:s}=await Promise.resolve().then(n.t.bind(n,96139,23)),o=await s({status:t.status||"resting",limit:100});return o?{content:[{type:"text",text:JSON.stringify(o.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:T.Object({ticker:T.Optional(T.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getFills:s}=await Promise.resolve().then(n.t.bind(n,96139,23)),o=await s({ticker:t.ticker,limit:50});return o?{content:[{type:"text",text:JSON.stringify(o.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((await m()).TOPIC_SERIES).join(", "),parameters:T.Object({topic:T.String({description:"Topic to scan (e.g. oil, crypto, fed, geopolitics)"})}),execute:async(e,t)=>{const n=t.topic.toLowerCase(),s=(await m()).TOPIC_SERIES[n];if(!s)return{content:[{type:"text",text:`Unknown topic "${t.topic}". Available: ${Object.keys((await m()).TOPIC_SERIES).join(", ")}`}],details:{}};const o=[];for(const e of s)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 s=(await n.json()).markets||[],i=await u(),r=await Promise.allSettled(s.slice(0,20).map(e=>i.getPublicOrderbook(e.ticker).then(t=>({ticker:e.ticker,title:e.title,ob:t}))));for(const e of r){if("fulfilled"!==e.status||!e.value.ob)continue;const{ticker:t,title:n,ob:s}=e.value,i=(s.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=(s.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";o.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(await h()).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=(await h()).parseClobTokenIds(e.clobTokenIds);if(!n)continue;const s=await(await h()).polymarketGetOrderbookWithDepth(n[0]);s&&o.push({venue:"polymarket",ticker:(e.question||t.title).slice(0,50),bestBid:s.bestBid,bestAsk:s.bestAsk,spread:s.spread,depth:s.bidDepthTop3+s.askDepthTop3,liquidityScore:s.liquidityScore})}}catch{}return o.sort((e,t)=>e.spread-t.spread),{content:[{type:"text",text:JSON.stringify(o,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:T.Object({ticker:T.Optional(T.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:T.Optional(T.Array(T.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:T.Optional(T.String({description:'Search Polymarket by keyword (e.g. "oil price above 100")'}))}),execute:async(e,t)=>{const n=[],s=[];t.tickers?.length?s.push(...t.tickers):t.ticker&&s.push(t.ticker);for(const e of s)try{const t=await(await f()).kalshiFetchMarket(e),s=t.status||"unknown";if("open"!==s&&"active"!==s)n.push({venue:"kalshi",ticker:e,title:t.title,status:"market_closed",reason:`Market status: ${s}. Orderbook unavailable for closed/settled markets.`,lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0"))});else{const s=await(await u()).getPublicOrderbook(e),o=(s?.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=(s?.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===o.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 s=o[0]?.price||0,r=i.length>0?100-i[0].price:o[0]?o[0].price+1:100,a=r-s,c=o.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:s,bestAsk:r,spread:a,liquidityScore:l,bidLevels:o.slice(0,5),askLevels:i.slice(0,5).map(e=>({price:100-e.price,size:e.size})),totalBidDepth:o.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(await h()).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 s=(await h()).parseClobTokenIds(e.clobTokenIds);if(!s)continue;const o=await(await h()).polymarketGetOrderbookWithDepth(s[0]);if(!o)continue;const i=(await h()).parseOutcomePrices(e.outcomePrices);n.push({venue:"polymarket",title:e.question||t.title,bestBid:o.bestBid,bestAsk:o.bestAsk,spread:o.spread,liquidityScore:o.liquidityScore,totalBidDepth:o.totalBidDepth,totalAskDepth:o.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:K,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:T.Object({rawThesis:T.String({description:"The raw thesis statement to create"}),webhookUrl:T.Optional(T.String({description:"Optional webhook URL for notifications"}))}),execute:async(e,t)=>{const n=await s.createThesis(t.rawThesis,!0),o=n.thesis||n,i=o.causalTree?.nodes?.length||0,r=(o.edges||[]).length,a="number"==typeof o.confidence?Math.round(100*o.confidence):0;return{content:[{type:"text",text:`Thesis created.\nID: ${o.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:K,execute:async()=>{const{theses:e}=await s.listTheses(),t=(e||[]).filter(e=>"active"===e.status||"monitoring"===e.status),n=await Promise.allSettled(t.map(async e=>((await s.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 i=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(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:T.Object({hours:T.Optional(T.Number({description:"Hours of history to fetch (default 24)"}))}),execute:async(e,t)=>{const n=await s.getFeed(t.hours||24),o=Array.isArray(n)?n:n?.evaluations||n?.items||[];let i=null,r=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>r&&(r=t,i=e)}const a={total:o.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=o,{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:T.Object({hours:T.Optional(T.Number({description:"Hours of history (default 1)"}))}),execute:async(e,t)=>{const n=t.hours||1,s=new Date(Date.now()-60*n*60*1e3).toISOString(),o=process.env.SF_API_URL||"https://simplefunctions.dev",i=await fetch(`${o}/api/changes?since=${encodeURIComponent(s)}&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:T.Object({slug:T.Optional(T.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 s=await e.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}const s=await fetch(`${n}/api/public/theses`);if(!s.ok)return{content:[{type:"text",text:"Failed to fetch public theses"}],details:{}};const o=await s.json();return{content:[{type:"text",text:JSON.stringify(o,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:T.Object({thesisId:T.String({description:"Thesis ID"}),marketId:T.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:T.String({description:"Human-readable market name"}),direction:T.String({description:"yes or no"}),horizon:T.Optional(T.String({description:"short, medium, or long. Default: medium"})),entryBelow:T.Optional(T.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:T.Optional(T.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:T.Optional(T.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:T.Optional(T.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:T.Optional(T.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:T.Optional(T.Number({description:"Contracts per order. Default: 50"})),softConditions:T.Optional(T.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:T.Optional(T.String({description:"Full logic description"}))}),execute:async(e,t)=>{const n=await s.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:T.Object({thesisId:T.String({description:"Thesis ID"}),status:T.Optional(T.String({description:"Filter by status. Omit for all."}))}),execute:async(e,t)=>{const n=await s.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:T.Object({thesisId:T.String({description:"Thesis ID"}),strategyId:T.String({description:"Strategy ID (UUID)"}),stopLoss:T.Optional(T.Number({description:"New stop loss (cents)"})),takeProfit:T.Optional(T.Number({description:"New take profit (cents)"})),entryBelow:T.Optional(T.Number({description:"New entry below trigger (cents)"})),entryAbove:T.Optional(T.Number({description:"New entry above trigger (cents)"})),status:T.Optional(T.String({description:"New status: active|watching|executed|cancelled|review"})),priority:T.Optional(T.Number({description:"New priority"})),softConditions:T.Optional(T.String({description:"Updated soft conditions"})),rationale:T.Optional(T.String({description:"Updated rationale"}))}),execute:async(e,t)=>{const{thesisId:n,strategyId:o,...i}=t,r=await s.updateStrategyAPI(n,o,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:T.Object({overrides:T.Array(T.Object({nodeId:T.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:T.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{const n=g,s=[];function o(e){for(const t of e)s.push(t),t.children?.length&&o(t.children)}const i=n.causalTree?.nodes||[];o(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=s.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 s=e.marketPrice||0,o=e.thesisPrice||e.thesisImpliedPrice||s,i=e.edge||e.edgeSize||0,r=Math.round(100*(s+(o-s)*n))/100,a=e.direction||"yes",c=Math.round(100*("yes"===a?r-s:s-r))/100;return{market:e.market||e.marketTitle||e.marketId,marketPrice:s,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=s.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:{}}}}];q.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:T.Object({query:T.String({description:"Search query"}),mode:T.Optional(T.String({description:'"summary" or "raw"'})),hours:T.Optional(T.Number({description:"Hours (default 24)"}))}),execute:async(e,t)=>{const n=await s.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:T.Object({query:T.String({description:"Search query"}),hours:T.Optional(T.Number({description:"Hours (default 72)"}))}),execute:async(e,t)=>{const n=await s.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:T.Object({query:T.String({description:"Search query"}),limit:T.Optional(T.Number({description:"Max stories (default 10)"}))}),execute:async(e,t)=>{const n=await s.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:T.Object({username:T.String({description:"X username (with or without @)"}),hours:T.Optional(T.Number({description:"Hours (default 24)"}))}),execute:async(e,t)=>{const n=await s.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:T.Object({thesisId:T.String({description:"Thesis ID"}),newsIntervalMin:T.Optional(T.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:T.Optional(T.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:T.Optional(T.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:T.Optional(T.Number({description:"Monthly budget (0 = unlimited)"})),paused:T.Optional(T.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 s.updateHeartbeatConfig(t.thesisId,e)}const n=await s.getHeartbeatConfig(t.thesisId);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}}),q.push({name:"configure_heartbeat",label:"Configure Heartbeat",description:"Adjust the 24/7 monitoring engine: news interval, X interval, model tier, budget, pause/resume.",parameters:T.Object({thesisId:T.String({description:"Thesis ID"}),newsIntervalMin:T.Optional(T.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:T.Optional(T.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:T.Optional(T.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:T.Optional(T.Number({description:"Monthly budget cap (0=unlimited)"})),paused:T.Optional(T.Boolean({description:"Pause/resume"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,i=await s.request("PATCH",`/api/thesis/${n}/heartbeat`,o);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:T.Object({thesisId:T.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await s.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:T.Object({thesisId:T.String({description:"Thesis ID"}),title:T.Optional(T.String({description:"New title"})),status:T.Optional(T.String({description:"active, paused, or archived"})),webhookUrl:T.Optional(T.String({description:"Webhook URL (HTTPS)"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,i=await s.request("PATCH",`/api/thesis/${n}`,o);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:T.Object({thesisId:T.String({description:"Thesis ID"}),venue:T.String({description:"kalshi or polymarket"}),externalMarketId:T.String({description:"Market ticker"}),marketTitle:T.String({description:"Market name"}),direction:T.String({description:"yes or no"}),entryPrice:T.Number({description:"Entry price in cents"}),size:T.Optional(T.Number({description:"Contracts"})),rationale:T.Optional(T.String({description:"Why"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t,i=await s.request("POST",`/api/thesis/${n}/positions`,o);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"update_position",label:"Update Position",description:"Update position: currentPrice, edge, status (open→closed).",parameters:T.Object({thesisId:T.String({description:"Thesis ID"}),positionId:T.String({description:"Position ID"}),currentPrice:T.Optional(T.Number({description:"Current price (cents)"})),edge:T.Optional(T.Number({description:"Current edge (cents)"})),status:T.Optional(T.String({description:"open or closed"}))}),execute:async(e,t)=>{const{thesisId:n,positionId:o,...i}=t,r=await s.request("PATCH",`/api/thesis/${n}/positions/${o}`,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:T.Object({thesisId:T.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await s.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:T.Object({thesisId:T.String({description:"Thesis ID"}),updates:T.Array(T.Object({nodeId:T.String({description:"Node ID (e.g. n3)"}),probability:T.Number({description:"New probability (0-1)"}),reason:T.Optional(T.String({description:"Why"}))})),lock:T.Optional(T.Array(T.String({description:"Node IDs to lock"})))}),execute:async(e,t)=>{const n=await s.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:{}}}}),q.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:T.Object({freshness:T.Optional(T.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:T.Optional(T.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 s=await fetch(`https://simplefunctions.dev/api/public/ideas?${n.toString()}`);if(!s.ok)return{content:[{type:"text",text:`Ideas API error: ${s.status}`}],details:{}};const o=await s.json();return{content:[{type:"text",text:JSON.stringify(o,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:T.Object({action:T.String({description:"buy or sell"}),venue:T.String({description:"kalshi or polymarket"}),marketId:T.String({description:"Market ticker"}),marketTitle:T.String({description:"Human-readable name"}),direction:T.String({description:"yes or no"}),targetQuantity:T.Number({description:"Number of contracts"}),maxPrice:T.Optional(T.Number({description:"Max price per contract in cents (1-99)"})),triggerType:T.Optional(T.String({description:"immediate, price_below, price_above, time"})),triggerPrice:T.Optional(T.Number({description:"Price trigger threshold in cents"})),rationale:T.Optional(T.String({description:"Why this trade"})),autoExecute:T.Optional(T.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(e,t)=>{const n=await s.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:T.Object({activeOnly:T.Optional(T.Boolean({description:"Only active intents (default true)"}))}),execute:async(e,t)=>{const n=await s.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:T.Object({intentId:T.String({description:"Intent ID to cancel"})}),execute:async(e,t)=>{const n=await s.cancelIntentAPI(t.intentId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}});const U=(0,c.loadConfig)();U.tradingEnabled&&q.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Shows preview and asks for confirmation.",parameters:T.Object({ticker:T.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:T.String({description:"yes or no"}),action:T.String({description:"buy or sell"}),type:T.String({description:"limit or market"}),count:T.Number({description:"Number of contracts"}),price_cents:T.Optional(T.Number({description:"Limit price in cents (1-99). Required for limit orders."}))}),execute:async(e,t)=>{const{createOrder:s}=await Promise.resolve().then(n.t.bind(n,96139,23)),o=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=o.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 s({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:T.Object({order_id:T.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{const{cancelOrder:s}=await Promise.resolve().then(n.t.bind(n,96139,23));try{return await s(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:{}}}}});q.push({name:"close_position",label:"Close Position",description:"Remove a position record from a thesis.",parameters:T.Object({thesisId:T.String({description:"Thesis ID"}),positionId:T.String({description:"Position ID"})}),execute:async(e,t)=>{const n=await s.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:T.Object({thesisId:T.String({description:"Thesis ID"}),dryRun:T.Optional(T.Boolean({description:"Preview without applying"}))}),execute:async(e,t)=>{const n=t.dryRun?"?dryRun=true":"",o=await s.request("POST",`/api/thesis/${t.thesisId}/augment${n}`);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}}),q.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:T.Object({focus:T.Optional(T.String({description:'Comma-separated topics (e.g. "energy,geopolitics")'}))}),execute:async(e,t)=>{const n=t.focus?`?focus=${encodeURIComponent(t.focus)}`:"",s=process.env.SF_API_URL||"https://simplefunctions.dev",o=await fetch(`${s}/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. ~30-50 tokens.",parameters:T.Object({since:T.Optional(T.String({description:'"30m", "1h", "6h", "24h" or ISO timestamp (default "1h")'}))}),execute:async(e,t)=>{const n=t.since||"1h",s=process.env.SF_API_URL||"https://simplefunctions.dev",o=await fetch(`${s}/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.",parameters:T.Object({source:T.Object({action:T.String({description:"scrape, crawl, search, map, extract, batch_scrape"}),url:T.Optional(T.String({description:"Target URL"})),query:T.Optional(T.String({description:"Search query (for search action)"}))}),analysis:T.Optional(T.Object({model:T.Optional(T.String({description:"OpenRouter model"})),prompt:T.Optional(T.String({description:"Analysis prompt"}))})),enrich:T.Optional(T.Object({topics:T.Optional(T.Array(T.String())),includeIndex:T.Optional(T.Boolean())})),webhook:T.Optional(T.Object({url:T.String({description:"Webhook URL"}),format:T.Optional(T.String({description:"full, brief, or tweetable"}))}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",s=await fetch(`${n}/api/monitor-the-situation`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok)return{content:[{type:"text",text:`Monitor API error: ${s.status}`}],details:{}};const o=await s.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.",parameters:T.Object({content:T.String({description:"Text to cross-reference"}),topics:T.Optional(T.Array(T.String()))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",s=await fetch(`${n}/api/monitor-the-situation/enrich`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok)return{content:[{type:"text",text:`Enrich API error: ${s.status}`}],details:{}};const o=await s.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}}),q.push({name:"create_skill",label:"Create Skill",description:"Create a custom agent skill — a reusable prompt/workflow triggered via slash command.",parameters:T.Object({name:T.String(),trigger:T.String({description:"Slash command trigger, e.g. /my-skill"}),description:T.String(),prompt:T.String({description:"The instruction text the agent executes"}),category:T.Optional(T.String()),tags:T.Optional(T.String({description:"Comma-separated tags"})),toolsUsed:T.Optional(T.String({description:"Comma-separated tool names"}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",s={name:t.name,trigger:t.trigger,description:t.description,prompt:t.prompt};t.category&&(s.category=t.category),t.tags&&(s.tags=t.tags.split(",").map(e=>e.trim())),t.toolsUsed&&(s.toolsUsed=t.toolsUsed.split(",").map(e=>e.trim()));const o=await fetch(`${n}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify(s)}),i=await o.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"list_skills",label:"List Skills",description:"List all skills: built-in defaults + user-created custom skills.",parameters:T.Object({}),execute:async()=>{const e=process.env.SF_API_URL||"https://simplefunctions.dev",t=await fetch(`${e}/api/skill`,{headers:{Authorization:`Bearer ${l}`}}),n=await t.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"browse_public_skills",label:"Browse Public Skills",description:"Browse community-created skills. Filter by category, search, or sort by popularity. No auth needed.",parameters:T.Object({category:T.Optional(T.String()),q:T.Optional(T.String()),sort:T.Optional(T.String({description:"popular or new"}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",s=new URLSearchParams;t.category&&s.set("category",t.category),t.q&&s.set("q",t.q),t.sort&&s.set("sort",t.sort);const o=await fetch(`${n}/api/public/skills?${s}`),i=await o.json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}],details:{}}}},{name:"publish_skill",label:"Publish Skill",description:"Publish a skill to make it publicly browsable and forkable.",parameters:T.Object({skillId:T.String(),slug:T.String({description:"URL-safe slug, e.g. my-precheck"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",s=await fetch(`${n}/api/skill/${t.skillId}/publish`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({slug:t.slug})}),o=await s.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"fork_skill",label:"Fork Skill",description:"Fork a public skill into your collection. Creates a copy you can customize.",parameters:T.Object({skillId:T.String({description:"ID of the public skill to fork"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",s=await fetch(`${n}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${l}`}}),o=await s.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"fork_thesis",label:"Fork Thesis",description:"Fork a public thesis. Copies thesis + causal tree, resets edges. Run formation after forking.",parameters:T.Object({slug:T.String({description:"Public thesis slug, e.g. iran-war"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev",s=await fetch(`${n}/api/thesis/${t.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${l}`}}),o=await s.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}}),q.push(...$(T)),q.push(...y(T,s,d,l)),q.push({name:"speak",label:"Speak",description:"Convert text to speech and play it.",parameters:T.Object({text:T.String({description:"Text to speak"})}),execute:async(e,t)=>{try{const{speak:e}=await n.e(324).then(n.bind(n,99324));return await e(t.text),{content:[{type:"text",text:`🔊 Spoke: "${t.text.slice(0,80)}..."`}],details:{}}}catch(e){return{content:[{type:"text",text:`Voice error: ${e.message}`}],details:{}}}}}),q.push({name:"schedule_wake",label:"Schedule Wake",description:"Schedule a self-wake: after N minutes, wake up to perform an action. Can repeat.",parameters:T.Object({delayMinutes:T.Number({description:"Minutes from now"}),action:T.String({description:"prompt | tool | check"}),prompt:T.Optional(T.String({description:"For prompt action"})),toolName:T.Optional(T.String({description:"For tool action"})),toolParams:T.Optional(T.Any()),repeatMinutes:T.Optional(T.Number({description:"Repeat interval"})),context:T.Optional(T.String({description:"Reason"}))}),execute:async(e,t)=>{const{scheduleWake:s}=await n.e(563).then(n.bind(n,9563)),i=s({delayMinutes:t.delayMinutes,action:t.action,prompt:t.prompt,toolCall:t.toolName?{name:t.toolName,params:t.toolParams||{}}:void 0,repeatMinutes:t.repeatMinutes,context:t.context,thesisId:o});return{content:[{type:"text",text:`Wake scheduled: fires at ${i.fireAt}${t.repeatMinutes?` (every ${t.repeatMinutes}m)`:""} [${i.id}]`}],details:{}}}},{name:"list_wakes",label:"List Wakes",description:"List all scheduled self-wakes.",parameters:T.Object({}),execute:async()=>{const{listWakes:e}=await n.e(563).then(n.bind(n,9563)),t=e();if(0===t.length)return{content:[{type:"text",text:"No wakes."}],details:{}};const s=t.map(e=>`${e.firedAt?"✓":"⏰"} ${e.id.slice(0,8)} | ${e.action} | ${e.fireAt.slice(11,16)} | ${e.context||""}`);return{content:[{type:"text",text:s.join("\n")}],details:{}}}},{name:"cancel_wake",label:"Cancel Wake",description:"Cancel a scheduled self-wake.",parameters:T.Object({id:T.String({description:"Wake ID"})}),execute:async(e,t)=>{const{cancelWake:s}=await n.e(563).then(n.bind(n,9563));return{content:[{type:"text",text:s(t.id)?"Cancelled.":"Not found."}],details:{}}}}),q.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime is running and show active intents.",parameters:T.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:i}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=o(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 s.listIntents({active:!0});return{content:[{type:"text",text:JSON.stringify({running:a,pid:a?c:null,...l},null,2)}],details:{}}}},{...w(s)},{...k()},{name:"daemon_command",label:"Daemon Command",description:"Send a command to a running daemon (runtime, telegram). Actions: pause, resume, scan_now.",parameters:T.Object({target:T.String({description:"Target daemon: runtime, telegram, watch"}),action:T.String({description:"Command action"}),data:T.Optional(T.Any())}),execute:async(e,t)=>{const{writeMessage:s}=await n.e(563).then(n.bind(n,9563)),o=s({from:"agent",to:t.target,type:"command",priority:"normal",payload:{action:t.action,data:t.data},ttl:3600});return{content:[{type:"text",text:`Command sent: ${t.action} → ${t.target} (${o})`}],details:{}}}},{name:"set_wake_condition",label:"Set Wake Condition",description:"Set a condition for daemons to alert you. Types: price, time, llm.",parameters:T.Object({description:T.String({description:"Human-readable condition"}),type:T.String({description:"price, time, or llm"}),condition:T.Any({description:"Condition config"}),priority:T.Optional(T.String())}),execute:async(e,t)=>{const{saveWakeCondition:s}=await n.e(563).then(n.bind(n,9563)),{randomBytes:o}=await Promise.resolve().then(n.t.bind(n,76982,23)),i={id:o(8).toString("hex"),createdAt:(new Date).toISOString(),description:t.description,type:t.type,[`${t.type}Condition`]:t.condition,alertChannels:["bus"],priority:t.priority||"normal",maxFires:-1,firedCount:0,lastFiredAt:null,expiresAt:null,active:!0};return s(i),{content:[{type:"text",text:`Wake condition set: "${t.description}" (${i.id})`}],details:{}}}},{name:"check_daemon_alerts",label:"Check Daemon Alerts",description:"Read alerts and observations from running daemons.",parameters:T.Object({}),execute:async()=>{const{readMessages:e,deleteMessage:t}=await n.e(563).then(n.bind(n,9563)),s=e("agent","outbox");if(0===s.length)return{content:[{type:"text",text:"No new daemon alerts."}],details:{}};const o=s.map(e=>(t(e.id,"outbox"),`[${e.priority}] ${e.from} (${e.ts.slice(11,19)}): ${e.payload.summary||JSON.stringify(e.payload)}`));return{content:[{type:"text",text:o.join("\n")}],details:{}}}});const z=g,H=z._explorerMode||"_explorer"===o;let B;if(H){const e=(z.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)";B=`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- daemon_command / set_wake_condition / check_daemon_alerts: smart daemon control\n- create_skill / list_skills / publish_skill / fork_skill / browse_public_skills: manage agent skills\n- fork_thesis: fork a public thesis (copies thesis + causal tree)\n- create_thesis: create a thesis when user forms a view\n- fs_read / fs_write / fs_list / fs_search / fs_delete: workspace (~/.sf/workspace/). Write notes proactively.\n- calculate: precise math. send_alert: push to Telegram. schedule_wake: self-scheduling.\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${U.tradingEnabled?"- Trading ENABLED.":"- Trading DISABLED."}\n\n## Market snapshot\nPublic edges:\n${e}`}else{const e=z.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=z.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 z.confidence?Math.round(100*z.confidence):0;B=`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## Workspace & Tools\n- fs_read/fs_write/fs_list/fs_search/fs_delete: persistent workspace at ~/.sf/workspace/. Write notes proactively.\n- calculate: precise math (never calculate in your head)\n- send_alert: push to Telegram + bus\n- cancel_all_intents: emergency batch cancel\n- schedule_wake / set_wake_condition(type:'price'): continuous monitoring\n- Live State is auto-refreshed each turn — use it, don't re-fetch what's already shown.\n\n## Rules\n- Be concise. Use tools for fresh data. Don't guess prices.\n- Live State shows positions/balance/edges each turn. Use it directly — only call get_positions for detail.\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${U.tradingEnabled?"- Trading ENABLED. You have place_order and cancel_order tools.":"- Trading DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current State\nThesis: ${z.thesis||z.rawThesis||"N/A"}\nID: ${o} | Confidence: ${n}% | Status: ${z.status}\n\nCausal nodes:\n${t}\n\nTop edges:\n${e}\n\n${z.lastEvaluation?.summary?`Latest eval: ${z.lastEvaluation.summary.slice(0,300)}`:""}`}const W=new E({initialState:{systemPrompt:B,model:N,tools:q,thinkingLevel:"off"},streamFn:P,getApiKey:e=>"openrouter"===e?t:void 0});if(!i?.newSession){const e=S(o);if(e?.messages?.length>0)try{W.replaceMessages(e.messages),W.setSystemPrompt(B)}catch{}}let J="";if(W.subscribe(e=>{if("message_update"===e.type){const t=e.assistantMessageEvent;"text_delta"===t.type&&(process.stdout.write(t.delta),J+=t.delta)}if("message_end"===e.type&&J&&(process.stdout.write("\n"),J=""),"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`)}}),H)console.log(`SF Agent — Explorer mode | ${M}`),console.log(`Public edges: ${(z.edges||[]).length}`),console.log("Ask anything about prediction markets. Type /help for commands, /exit to quit.\n");else{const e=z.thesis||z.rawThesis||"N/A",t="number"==typeof z.confidence?Math.round(100*z.confidence):0;console.log(`SF Agent — ${o.slice(0,8)} | ${t}% | ${M}`),console.log(`Thesis: ${e.length>100?e.slice(0,100)+"...":e}`),console.log(`Edges: ${(z.edges||[]).length} | Status: ${z.status}`),console.log("Type /help for commands, /exit to quit.\n")}if(i?.once){if(!H)try{const e=await C(s,o);W.setSystemPrompt(B+e)}catch{}try{await W.prompt(i.once)}catch(e){console.error(`Error: ${p(e)}`)}try{_(o,M,W.state.messages),O(o,W.state.messages,"plain")}catch{}return}function X(){if(H)return"explorer> ";const e="number"==typeof g?.confidence?Math.round(100*g.confidence):"?";return`[${o.slice(0,8)} ${e}%] > `}const G=b.createInterface({input:process.stdin,output:process.stdout,prompt:X()});G.prompt();for await(const t of G){const i=t.trim();if(i){if("/exit"===i||"/quit"===i){try{_(o,M,W.state.messages),O(o,W.state.messages,"plain")}catch{}return void G.close()}if("/help"!==i){if("/tree"===i){g=await s.getContext(o);const e=g.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)}%`)}G.prompt();continue}if("/edges"===i){g=await s.getContext(o);const e=(g.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}`)}G.prompt();continue}if("/eval"===i){console.log("Triggering evaluation...");const e=await s.evaluate(o);console.log(`Confidence: ${e.previousConfidence} → ${e.newConfidence}`),e.summary&&console.log(e.summary),G.prompt();continue}if(i.startsWith("/model")){const e=i.slice(6).trim();if(!e){console.log(`Current: ${M}`),G.prompt();continue}M=e.replace(/^openrouter\//,""),N=R(M),W.setModel(N),console.log(`Model: ${M}`),G.prompt();continue}if("/voice"!==i){if(!H)try{const e=await C(s,o);W.setSystemPrompt(B+e)}catch{}try{await W.prompt(i)}catch(e){console.error(`Error: ${p(e)}`)}try{_(o,M,W.state.messages),O(o,W.state.messages,"plain")}catch{}G.setPrompt(X()),G.prompt()}else{try{const e=await n.e(324).then(n.bind(n,99324));if(e.isRecording()){console.log("Stopping recording...");const t=e.stopRecording();if(!t){console.log("No audio captured."),G.prompt();continue}console.log("Transcribing...");const n=await e.transcribe(t);if(!n.text){console.log("Transcription empty."),G.prompt();continue}console.log(`🎤 "${n.text}"`),await W.prompt(n.text);try{_(o,M,W.state.messages),O(o,W.state.messages,"plain")}catch{}}else{if(!e.isRecordingAvailable()){console.log("Voice requires sox. Install: brew install sox"),G.prompt();continue}e.startRecording(),console.log("🎙 Recording... type /voice again to stop and send")}}catch(e){console.error(`Voice error: ${e.message}`)}G.prompt()}}else console.log("Commands: /help /exit /tree /edges /eval /balance /intents /wakes /alerts /model <name> /voice"),G.prompt()}else G.prompt()}}({openrouterKey:l,sfClient:b,resolvedThesisId:x||"_explorer",latestContext:v,useProxy:r,llmBaseUrl:d,sfApiKey:o,sfApiUrl:i,opts:t});const P=await n.e(921).then(n.bind(n,93921)),N=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641)),L=await Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653)),{TUI:D,ProcessTerminal:j,Container:F,Text:K,Markdown:q,Editor:U,Loader:z,Spacer:H,CombinedAutocompleteProvider:B,truncateToWidth:W,visibleWidth:J}=P,{getModel:X,streamSimple:G,Type:Y}=N,{Agent:V}=L,Q=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}}}(P),Z=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),s=e.edge||e.edgeSize||0;this.topEdge=`${n} ${s>0?"+":""}${Math.round(s)}¢`}}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 s=R.zinc600(" │ ");let o;if(this.isExplorer){const e=R.emerald(T("Explorer")),t=R.zinc600(`${this.edgeCount} public edges`),n=this.topEdge?R.zinc400(this.topEdge):"";let s="";if(this.positionCount>0){const e=this.pnlDollars>=0?R.emerald(`+$${this.pnlDollars.toFixed(2)}`):R.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);s=R.zinc600(`${this.positionCount} pos `)+e}o=[e,s,t,n].filter(Boolean)}else{const e=R.emerald(this.thesisId),t=this.confidenceDelta>0?"▲":this.confidenceDelta<0?"▼":"─",n=this.confidenceDelta>0?R.emerald:this.confidenceDelta<0?R.red:R.zinc600,s=0!==this.confidenceDelta?` (${this.confidenceDelta>0?"+":""}${this.confidenceDelta})`:"",i=n(`${t} ${this.confidence}%${s}`);let r="";if(this.positionCount>0){const e=this.pnlDollars>=0?R.emerald(`+$${this.pnlDollars.toFixed(2)}`):R.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);r=R.zinc600(`${this.positionCount} pos `)+e}o=[e,i,r,R.zinc600(`${this.edgeCount} edges`),this.topEdge?R.zinc400(this.topEdge):""].filter(Boolean)}let i=R.bgZinc800(" "+t(o.join(s),e-2,"")+" ");const r=n(i);r<e&&(i+=R.bgZinc800(" ".repeat(e-r)));const a=R.zinc600(this.modelName.split("/").pop()||this.modelName),c=this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:`${this.tokens}`,l=R.zinc600(`${c} tok`),d=!0===this.exchangeOpen?R.emerald("OPEN"):!1===this.exchangeOpen?R.red("CLOSED"):R.zinc600("..."),u=this.tradingEnabled?R.amber("trading"):R.zinc600("read-only"),p=R.zinc600("/help"),h=[a,l,d,u].join(s),m=n(h),g=n(p),f=Math.max(1,e-m-g-2);let y=R.bgZinc900(" "+h+" ".repeat(f)+p+" ");const $=n(y);return $<e&&(y+=R.bgZinc900(" ".repeat(e-$))),this.cachedLines=[i,y],this.cachedLines}}}(P),ee=t?.model||"anthropic/claude-sonnet-4.6";let te=ee.replace(/^openrouter\//,"");function ne(e){let t;try{t=X("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=d),t}let se=ne(te),oe=0,ie=!1,re=null,ae=(new Date).toISOString(),ce=null,le=null,de=null;const ue=new j,pe=new D(ue),he={heading:e=>R.zinc200(T(e)),link:e=>R.emerald(e),linkUrl:e=>R.zinc600(e),code:e=>R.zinc200(e),codeBlock:e=>R.zinc400(e),codeBlockBorder:e=>R.zinc600(e),quote:e=>R.zinc400(e),quoteBorder:e=>R.zinc600(e),hr:e=>R.zinc600(e),listBullet:e=>R.emerald(e),bold:e=>T(e),italic:e=>E(e),strikethrough:e=>M(e),underline:e=>A(e)},me={color:e=>R.zinc400(e)},ge={borderColor:e=>`[38;2;50;50;55m${e}[39m`,selectList:{selectedPrefix:e=>R.emerald(e),selectedText:e=>R.zinc200(e),description:e=>R.zinc600(e),scrollInfo:e=>R.zinc600(e),noMatch:e=>R.zinc600(e)}},fe=new Z;fe.modelName=te,fe.tradingEnabled=(0,c.loadConfig)().tradingEnabled||!1;let ye=null;try{if(ye=await(await u()).getPositions(),ye)for(const e of ye){const t=await(await u()).getMarketPrice(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity))}}catch{}fe.setFromContext(v,ye||void 0),fetch("https://api.elections.kalshi.com/trade-api/v2/exchange/status",{headers:{Accept:"application/json"}}).then(e=>e.json()).then(e=>{fe.exchangeOpen=!!e.exchange_active,fe.update(),pe.requestRender()}).catch(()=>{});const $e=new H(1),we=new H(1),ke=new F,be=new U(pe,ge,{paddingX:1}),ve=[{name:"help",description:"Show available commands"},{name:"balance",description:"Quick balance check"},{name:"intents",description:"List active intents"},{name:"wakes",description:"List scheduled wakes"},{name:"alerts",description:"Check daemon alerts"},{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:"voice",description:"Toggle voice recording (record → transcribe → send)"},{name:"clear",description:"Clear screen (keeps history)"},{name:"exit",description:"Exit agent (auto-saves)"}];(0,c.loadConfig)().tradingEnabled&&ve.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 Se=(await g()).loadSkills();for(const e of Se){const t=e.trigger.replace(/^\//,"");ve.splice(-2,0,{name:t,description:`[skill] ${e.description.slice(0,50)}`})}const _e=new B(ve,process.cwd());be.setAutocompleteProvider(_e),pe.addChild($e),pe.addChild(ke),pe.addChild(be),pe.addChild(we),pe.setFocus(be);pe.showOverlay(fe,{anchor:"bottom-left",width:"100%",nonCapturing:!0});function xe(e){const t=new K(e,1,0);ke.addChild(t),pe.requestRender()}function Oe(){ke.addChild(new H(1))}function Ce(e){return new Promise(t=>{xe(R.amber(T("⚠ "))+R.zinc200(e)),Oe(),pe.requestRender(),de={resolve:t}})}const Ie=Y.Object({thesisId:Y.String({description:"Thesis ID (short or full UUID)"})}),Pe=Y.Object({thesisId:Y.String({description:"Thesis ID"}),content:Y.String({description:"Signal content"}),type:Y.Optional(Y.String({description:"Signal type: news, user_note, external. Default: user_note"}))}),Te=Y.Object({query:Y.Optional(Y.String({description:"Keyword search for Kalshi markets"})),series:Y.Optional(Y.String({description:"Kalshi series ticker (e.g. KXWTIMAX)"})),market:Y.Optional(Y.String({description:"Specific market ticker"}))}),Ee=Y.Object({query:Y.String({description:"Search keywords"})}),Ae=Y.Object({}),Me=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:Ie,execute:async(e,t)=>{const n=await b.getContext(t.thesisId);return v=n,fe.setFromContext(n,ye||void 0),pe.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:Ae,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:Y.Object({q:Y.String({description:'Natural language query (e.g. "iran oil prices", "fed rate cut 2026")'})}),execute:async(e,t)=>{const{fetchQuery:s}=await Promise.resolve().then(n.bind(n,19218)),o=await s(t.q);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"get_markets",label:"Traditional Markets",description:"Get traditional market prices via Databento. Default: SPY, VIX, TLT, GLD, USO. Use topic for deep dives: energy (WTI, Brent, NG, Heating Oil), rates (yield curve: SHY, IEF, TLT, ZN, ZB, HYG, LQD), fx (DXY, JPY, EUR, GBP), equities (QQQ, IWM, EEM, XLF, XLK), crypto (BTC/ETH ETFs + futures), volatility (VIX suite).",parameters:Y.Object({topic:Y.Optional(Y.String({description:"Deep dive topic: energy, rates, fx, equities, crypto, volatility. Omit for core 5."}))}),execute:async(e,t)=>{const{fetchTraditionalMarkets:s}=await Promise.resolve().then(n.bind(n,19218)),o=await s(t.topic);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"query_databento",label:"Databento Query",description:"Free-form historical market data via Databento. Stocks, ETFs, CME futures, options. OHLCV daily/hourly/minute, trades, BBO. Max 30 days, 5 symbols. Examples: SPY 7d OHLCV, CL.c.0 hourly, ES.c.0 + NQ.c.0 comparison. Continuous futures format: ROOT.c.0 (front month).",parameters:Y.Object({symbols:Y.String({description:"Comma-separated (max 5). Continuous futures: ROOT.c.0. E.g. SPY, CL.c.0, ES.c.0"}),dataset:Y.Optional(Y.String({description:"DBEQ.BASIC (stocks), GLBX.MDP3 (CME futures), OPRA.PILLAR (options)"})),schema:Y.Optional(Y.String({description:"ohlcv-1d, ohlcv-1h, ohlcv-1m, trades, bbo-1s, bbo-1m, statistics"})),stype:Y.Optional(Y.String({description:"raw_symbol (default) or continuous (for .FUT)"})),days:Y.Optional(Y.Number({description:"Lookback days (default 7, max 30)"}))}),execute:async(e,t)=>{const n=new URLSearchParams({symbols:t.symbols});t.dataset&&n.set("dataset",t.dataset),t.schema&&n.set("schema",t.schema),t.stype&&n.set("stype",t.stype),t.days&&n.set("days",String(t.days));const s=await fetch(`${i}/api/public/databento?${n.toString()}`);if(!s.ok)return{content:[{type:"text",text:`Databento error: ${s.status}`}],details:{}};const o=await s.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"inject_signal",label:"Inject Signal",description:"Inject a signal into the thesis (news, note, external event)",parameters:Pe,execute:async(e,t)=>{const n=await b.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:Ie,execute:async(e,t)=>{const n=await b.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)),s=Math.round(100*(n.evaluation.newConfidence||0)),o=e>0?"▲":"▼";xe((e>0?R.emerald:R.red)(` ${o} Confidence ${t}% → ${s}% (${e>0?"+":""}${Math.round(100*e)})`)),Oe(),fe.updateConfidence(n.evaluation.newConfidence,e),pe.requestRender()}try{v=await b.getContext(t.thesisId),fe.setFromContext(v,ye||void 0),pe.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:Te,execute:async(e,t)=>{if(t.market){const e=await(await f()).kalshiFetchMarket(t.market);return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}if(t.series){const e=await(await f()).kalshiFetchMarketsBySeries(t.series);return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:{}}}if(t.query){const e=await(await f()).kalshiFetchAllSeries(),n=t.query.toLowerCase().split(/\s+/),s=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 o=[];try{const e=await(await h()).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=(await h()).parseOutcomePrices(e.outcomePrices);o.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:s,polymarket:o},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:Ae,execute:async()=>{const e=await b.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:Ae,execute:async()=>{const e={kalshi:[],polymarket:[]},t=await(await u()).getPositions();if(t){for(const e of t){const t=await(await u()).getMarketPrice(e.ticker);null!==t&&(e.current_value=t,e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity))}re=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,c.loadConfig)();if(n.polymarketWalletAddress)try{const t=await(await h()).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:Ee,execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY;if(!n&&!(!n&&o))return{content:[{type:"text",text:"Web search not available. Run sf login (proxied search) or set TAVILY_API_KEY."}],details:{}};let s;if(s=n?await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,query:t.query,max_results:5,search_depth:"basic",include_answer:!0})}):await fetch(`${i}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({query:t.query,max_results:5,search_depth:"basic",include_answer:!0})}),!s.ok)return{content:[{type:"text",text:`Search failed: ${s.status}`}],details:{}};const r=await s.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:Y.Object({slug:Y.Optional(Y.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 s=await e.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}const s=await fetch(`${n}/api/public/theses`);if(!s.ok)return{content:[{type:"text",text:"Failed to fetch public theses"}],details:{}};const o=await s.json();return{content:[{type:"text",text:JSON.stringify(o,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:Y.Object({thesisId:Y.String({description:"Thesis ID"}),marketId:Y.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:Y.String({description:"Human-readable market name"}),direction:Y.String({description:"yes or no"}),horizon:Y.Optional(Y.String({description:"short, medium, or long. Default: medium"})),entryBelow:Y.Optional(Y.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:Y.Optional(Y.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:Y.Optional(Y.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:Y.Optional(Y.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:Y.Optional(Y.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:Y.Optional(Y.Number({description:"Contracts per order. Default: 50"})),softConditions:Y.Optional(Y.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:Y.Optional(Y.String({description:"Full logic description"}))}),execute:async(e,t)=>{const n=await b.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:Y.Object({thesisId:Y.String({description:"Thesis ID"}),status:Y.Optional(Y.String({description:"Filter by status. Omit for all."}))}),execute:async(e,t)=>{const n=await b.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:Y.Object({thesisId:Y.String({description:"Thesis ID"}),strategyId:Y.String({description:"Strategy ID (UUID)"}),stopLoss:Y.Optional(Y.Number({description:"New stop loss (cents)"})),takeProfit:Y.Optional(Y.Number({description:"New take profit (cents)"})),entryBelow:Y.Optional(Y.Number({description:"New entry below trigger (cents)"})),entryAbove:Y.Optional(Y.Number({description:"New entry above trigger (cents)"})),status:Y.Optional(Y.String({description:"New status: active|watching|executed|cancelled|review"})),priority:Y.Optional(Y.Number({description:"New priority"})),softConditions:Y.Optional(Y.String({description:"Updated soft conditions"})),rationale:Y.Optional(Y.String({description:"Updated rationale"}))}),execute:async(e,t)=>{const{thesisId:n,strategyId:s,...o}=t,i=await b.updateStrategyAPI(n,s,o);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:Y.Object({hours:Y.Optional(Y.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:Y.Optional(Y.String({description:"Filter by category (e.g. Economics, Politics, Sports)"}))}),execute:async(e,t)=>{const n=t.hours||168,s=new Date,o=`https://api.elections.kalshi.com/trade-api/v2/milestones?limit=200&minimum_start_date=${s.toISOString()}`+(t.category?`&category=${t.category}`:""),i=await fetch(o,{headers:{Accept:"application/json"}});if(!i.ok)return{content:[{type:"text",text:`Milestones API error: ${i.status}`}],details:{}};const r=await i.json(),a=s.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()-s.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:Y.Object({eventTicker:Y.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:Y.Optional(Y.Number({description:"Days of history (default 7)"}))}),execute:async(e,t)=>{const{getForecastHistory:s}=await Promise.resolve().then(n.t.bind(n,96139,23)),o=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 s({seriesTicker:a,eventTicker:t.eventTicker,percentiles:[5e3,7500,9e3],startTs:Math.floor((Date.now()-864e5*o)/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:Y.Object({ticker:Y.Optional(Y.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getSettlements:s}=await Promise.resolve().then(n.t.bind(n,96139,23)),o=await s({limit:100,ticker:t.ticker});return o?{content:[{type:"text",text:JSON.stringify(o.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:Ae,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:Y.Object({status:Y.Optional(Y.String({description:"Filter by status: resting, canceled, executed. Default: resting"}))}),execute:async(e,t)=>{const{getOrders:s,getMarketPrice:o}=await Promise.resolve().then(n.t.bind(n,96139,23)),i=await s({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,s=!1;try{const o=await(await u()).getMarketPrice(e.ticker);null!=o&&e.yes_price_dollars&&(n=Math.round(100*Math.abs(o-parseFloat(e.yes_price_dollars))),null!=t&&t>7&&n>10&&(s=!0))}catch{}return{...e,daysSinceCreated:t,distanceFromMarket:n,stale:s}}));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:Y.Object({ticker:Y.Optional(Y.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getFills:s}=await Promise.resolve().then(n.t.bind(n,96139,23)),o=await s({ticker:t.ticker,limit:50});return o?{content:[{type:"text",text:JSON.stringify(o.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((await m()).TOPIC_SERIES).join(", "),parameters:Y.Object({topic:Y.String({description:"Topic to scan (e.g. oil, crypto, fed, geopolitics)"})}),execute:async(e,t)=>{const n=t.topic.toLowerCase(),s=(await m()).TOPIC_SERIES[n];if(!s)return{content:[{type:"text",text:`Unknown topic "${t.topic}". Available: ${Object.keys((await m()).TOPIC_SERIES).join(", ")}`}],details:{}};const o=[];for(const e of s)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 s=(await n.json()).markets||[],i=await u(),r=await Promise.allSettled(s.slice(0,20).map(e=>i.getPublicOrderbook(e.ticker).then(t=>({ticker:e.ticker,title:e.title,ob:t}))));for(const e of r){if("fulfilled"!==e.status||!e.value.ob)continue;const{ticker:t,title:n,ob:s}=e.value,i=(s.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=(s.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";o.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(await h()).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=(await h()).parseClobTokenIds(e.clobTokenIds);if(!n)continue;const s=await(await h()).polymarketGetOrderbookWithDepth(n[0]);s&&o.push({venue:"polymarket",ticker:(e.question||t.title).slice(0,50),bestBid:s.bestBid,bestAsk:s.bestAsk,spread:s.spread,depth:s.bidDepthTop3+s.askDepthTop3,liquidityScore:s.liquidityScore})}}catch{}return o.sort((e,t)=>e.spread-t.spread),{content:[{type:"text",text:JSON.stringify(o,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:Y.Object({ticker:Y.Optional(Y.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:Y.Optional(Y.Array(Y.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:Y.Optional(Y.String({description:'Search Polymarket by keyword (e.g. "oil price above 100")'}))}),execute:async(e,t)=>{const n=[],s=[];t.tickers?.length?s.push(...t.tickers):t.ticker&&s.push(t.ticker);for(const e of s)try{const t=await(await f()).kalshiFetchMarket(e),s=t.status||"unknown";if("open"!==s&&"active"!==s)n.push({venue:"kalshi",ticker:e,title:t.title,status:"market_closed",reason:`Market status: ${s}. Orderbook unavailable for closed/settled markets.`,lastPrice:Math.round(100*parseFloat(t.last_price_dollars||"0"))});else{const s=await(await u()).getPublicOrderbook(e),o=(s?.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=(s?.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===o.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 s=o[0]?.price||0,r=i.length>0?100-i[0].price:o[0]?o[0].price+1:100,a=r-s,c=o.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:s,bestAsk:r,spread:a,liquidityScore:l,bidLevels:o.slice(0,5),askLevels:i.slice(0,5).map(e=>({price:100-e.price,size:e.size})),totalBidDepth:o.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(await h()).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 s=(await h()).parseClobTokenIds(e.clobTokenIds);if(!s)continue;const o=await(await h()).polymarketGetOrderbookWithDepth(s[0]);if(!o)continue;const i=(await h()).parseOutcomePrices(e.outcomePrices);n.push({venue:"polymarket",title:e.question||t.title,bestBid:o.bestBid,bestAsk:o.bestAsk,spread:o.spread,liquidityScore:o.liquidityScore,totalBidDepth:o.totalBidDepth,totalAskDepth:o.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:Ae,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:Y.Object({rawThesis:Y.String({description:"The raw thesis statement to create"}),webhookUrl:Y.Optional(Y.String({description:"Optional webhook URL for notifications"}))}),execute:async(e,t)=>{const n=await b.createThesis(t.rawThesis,!0),s=n.thesis||n,o=s.causalTree?.nodes?.length||0,i=(s.edges||[]).length,r="number"==typeof s.confidence?Math.round(100*s.confidence):0;if(I&&s.id){I=!1,x=s.id;try{v=await b.getContext(s.id);const e=Ne(v);je.setSystemPrompt(e),fe.setFromContext(v,ye||void 0),pe.requestRender()}catch{}}return{content:[{type:"text",text:`Thesis created.\nID: ${s.id}\nConfidence: ${r}%\nNodes: ${o}\nEdges: ${i}\n\nHeartbeat engine is now monitoring this thesis 24/7. Use /switch ${s.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:Ae,execute:async()=>{const{theses:e}=await b.listTheses(),t=(e||[]).filter(e=>"active"===e.status||"monitoring"===e.status),n=await Promise.allSettled(t.map(async e=>((await b.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 o=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(o,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:Y.Object({hours:Y.Optional(Y.Number({description:"Hours of history to fetch (default 24)"}))}),execute:async(e,t)=>{const n=await b.getFeed(t.hours||24),s=Array.isArray(n)?n:n?.evaluations||n?.items||[];let o=null,i=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>i&&(i=t,o=e)}const r={total:s.length};return o&&(r.topSignal={summary:o.summary||o.content||"",confidenceDelta:o.confidenceDelta||o.confidence_delta||0,evaluatedAt:o.evaluatedAt||o.evaluated_at||o.createdAt||"",why:i>1?"Largest confidence movement in this period":i>0?"Most substantive evaluation (no confidence change)":"Most recent evaluation"}),r.items=s,{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:Y.Object({hours:Y.Optional(Y.Number({description:"Hours of history (default 1)"}))}),execute:async(e,t)=>{const n=t.hours||1,s=new Date(Date.now()-60*n*60*1e3).toISOString(),o=process.env.SF_API_URL||"https://simplefunctions.dev",i=await fetch(`${o}/api/changes?since=${encodeURIComponent(s)}&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:{}}}}];Me.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:Y.Object({overrides:Y.Array(Y.Object({nodeId:Y.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:Y.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{if(x)try{v=await b.getContext(x)}catch{}const n=v,s=[];const o=n.causalTree?.nodes||[];!function e(t){for(const n of t)s.push(n),n.children?.length&&e(n.children)}(o);const i=o.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),s=n.reduce((e,t)=>e+t,0);return s>0?t.reduce((e,t,s)=>e+t*n[s],0)/s: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=s.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 s=e.marketPrice||0,o=e.thesisPrice||e.thesisImpliedPrice||s,i=e.edge||e.edgeSize||0,r=Math.round(100*(s+(o-s)*n))/100,a=e.direction||"yes",c=Math.round(100*("yes"===a?r-s:s-r))/100;return{market:e.market||e.marketTitle||e.marketId,marketPrice:s,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=s.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:{}}}}),Me.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:Y.Object({query:Y.String({description:'Search query (e.g. "iran oil", "fed rate cut", "$BTC")'}),mode:Y.Optional(Y.String({description:'"summary" (default, with AI analysis) or "raw" (just posts)'})),hours:Y.Optional(Y.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await b.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:Y.Object({query:Y.String({description:"Search query"}),hours:Y.Optional(Y.Number({description:"Hours of history (default 72)"}))}),execute:async(e,t)=>{const n=await b.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:Y.Object({query:Y.String({description:"Search query"}),limit:Y.Optional(Y.Number({description:"Max stories (default 10)"}))}),execute:async(e,t)=>{const n=await b.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:Y.Object({username:Y.String({description:"X username (with or without @)"}),hours:Y.Optional(Y.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await b.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:Y.Object({thesisId:Y.String({description:"Thesis ID"}),newsIntervalMin:Y.Optional(Y.Number({description:"News scan interval in minutes (15-1440)"})),xIntervalMin:Y.Optional(Y.Number({description:"X scan interval in minutes (60-1440)"})),evalModelTier:Y.Optional(Y.String({description:"Eval model: cheap, medium, or heavy"})),monthlyBudgetUsd:Y.Optional(Y.Number({description:"Monthly budget cap in USD (0 = unlimited)"})),paused:Y.Optional(Y.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 b.updateHeartbeatConfig(t.thesisId,e)}const n=await b.getHeartbeatConfig(t.thesisId);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}});const Re=(0,c.loadConfig)();Re.tradingEnabled&&Me.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:Y.Object({ticker:Y.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:Y.String({description:"yes or no"}),action:Y.String({description:"buy or sell"}),type:Y.String({description:"limit or market"}),count:Y.Number({description:"Number of contracts"}),price_cents:Y.Optional(Y.Number({description:"Limit price in cents (1-99). Required for limit orders."}))}),execute:async(e,t)=>{const{createOrder:s}=await Promise.resolve().then(n.t.bind(n,96139,23)),o=t.price_cents?Math.round(Number(t.price_cents)):void 0,i=((o||99)*t.count/100).toFixed(2);xe([R.zinc200(T("ORDER PREVIEW")),` Ticker: ${t.ticker}`,` Side: ${"yes"===t.side?R.emerald("YES"):R.red("NO")}`,` Action: ${t.action.toUpperCase()}`,` Quantity: ${t.count}`,` Type: ${t.type}`,o?` Price: ${o}¢`:"",` Max cost: $${i}`].filter(Boolean).join("\n")),Oe(),pe.requestRender();if(!(await Ce("Execute this order? (y/n)")).toLowerCase().startsWith("y"))return{content:[{type:"text",text:"Order cancelled by user."}],details:{}};try{const e=await s({ticker:t.ticker,side:t.side,action:t.action,type:t.type,count:t.count,...o?{yes_price:o}:{}}),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:Y.Object({order_id:Y.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{const{cancelOrder:s}=await Promise.resolve().then(n.t.bind(n,96139,23));if(!(await Ce(`Cancel order ${t.order_id}? (y/n)`)).toLowerCase().startsWith("y"))return{content:[{type:"text",text:"Cancel aborted by user."}],details:{}};try{return await s(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 Ne(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)",s="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: The ## Live State section (auto-refreshed each turn) shows current positions, balance, edges, and intents. Use this data directly — don't call get_positions or get_context unless you need more detail than what's shown. If Live State shows positions, you already know them.\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). Intents can have a softCondition (natural language) that the smart runtime evaluates via LLM before executing. 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.\nUse daemon_command to send commands to running daemons (pause, resume, scan_now). Use set_wake_condition to create alerts: price thresholds, time triggers, or natural language conditions evaluated by LLM. Use check_daemon_alerts to read daemon observations.\n\n## Workspace (filesystem)\n\nYou have a persistent local filesystem at ~/.sf/workspace/. Use it proactively:\n- fs_write notes after any significant analysis, trade decision, or observation\n- fs_write a daily log summarizing what happened and what to watch\n- fs_search your own history when user asks "what did we discuss about X"\n- Workspace is shared across TUI and Telegram — anything you write is visible from both\n- Context directory has conversation JSONL — you can grep your own past conversations\n\n## Self-Wake & Price Monitoring\n\nYou can schedule yourself to wake up and take action. Use this proactively:\n- schedule_wake: timer (N minutes) + action (prompt/tool/check) + optional repeat\n- Use for: "check oil prices in 30m", "review positions every 2 hours", "watch for Iran news"\n- When a wake fires, you'll be prompted with your scheduled context automatically\n\n**Price monitoring**: set_wake_condition(type: 'price') IS the watch_price tool. Use it to continuously monitor prices:\n set_wake_condition({ type: 'price', description: 'alert if KXBTC drops below 60¢', priceCondition: { ticker: 'KXBTC...', operator: 'below', threshold: 60 } })\n This checks every runtime cycle (~30s). Combine with send_alert for Telegram push.\n\n## Utility tools\n\n- calculate: precise math — use for edge sizing, P&L calculation, probability math. Never calculate in your head.\n- send_alert: push important alerts to Telegram + daemon bus. Use when you discover something urgent.\n- cancel_all_intents: emergency batch cancel. Requires confirm=true.\n\n## Skills & Fork\n\n- create_skill: create reusable agent workflows triggered via slash command\n- list_skills / browse_public_skills: discover built-in, custom, and community skills\n- publish_skill / fork_skill: share skills publicly, fork others' skills\n- fork_thesis: copy a public thesis + causal tree into user's account, then run formation for fresh edges\n\n## Trading status\n\n${Re.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||x}\nConfidence: ${s}%\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)}`:""}`}Me.push({name:"update_thesis",label:"Update Thesis",description:"Update thesis metadata: title, status (active/paused/archived), webhookUrl.",parameters:Y.Object({thesisId:Y.String({description:"Thesis ID"}),title:Y.Optional(Y.String({description:"New title"})),status:Y.Optional(Y.String({description:"active, paused, or archived"})),webhookUrl:Y.Optional(Y.String({description:"Webhook URL (HTTPS)"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t,o=await b.request("PATCH",`/api/thesis/${n}`,s);return{content:[{type:"text",text:JSON.stringify(o)}],details:{}}}},{name:"augment_tree",label:"Augment Tree",description:"Review and merge suggested causal tree nodes from evaluations. Evolves the tree structure.",parameters:Y.Object({thesisId:Y.String({description:"Thesis ID"}),dryRun:Y.Optional(Y.Boolean({description:"Preview changes without applying (default false)"}))}),execute:async(e,t)=>{const n=t.dryRun?"?dryRun=true":"",s=await b.request("POST",`/api/thesis/${t.thesisId}/augment${n}`);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"add_position",label:"Add Position",description:"Record a new position in a thesis for tracking.",parameters:Y.Object({thesisId:Y.String({description:"Thesis ID"}),venue:Y.String({description:"kalshi or polymarket"}),externalMarketId:Y.String({description:"Market ticker"}),marketTitle:Y.String({description:"Market name"}),direction:Y.String({description:"yes or no"}),entryPrice:Y.Number({description:"Entry price in cents"}),size:Y.Optional(Y.Number({description:"Contracts"})),rationale:Y.Optional(Y.String({description:"Why"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t,o=await b.request("POST",`/api/thesis/${n}/positions`,s);return{content:[{type:"text",text:JSON.stringify(o)}],details:{}}}},{name:"update_position",label:"Update Position",description:"Update position: currentPrice, edge, status (open→closed).",parameters:Y.Object({thesisId:Y.String({description:"Thesis ID"}),positionId:Y.String({description:"Position ID"}),currentPrice:Y.Optional(Y.Number({description:"Current price (cents)"})),edge:Y.Optional(Y.Number({description:"Current edge (cents)"})),status:Y.Optional(Y.String({description:"open or closed"}))}),execute:async(e,t)=>{const{thesisId:n,positionId:s,...o}=t,i=await b.request("PATCH",`/api/thesis/${n}/positions/${s}`,o);return{content:[{type:"text",text:JSON.stringify(i)}],details:{}}}},{name:"close_position",label:"Close Position",description:"Remove a position record from a thesis.",parameters:Y.Object({thesisId:Y.String({description:"Thesis ID"}),positionId:Y.String({description:"Position ID"})}),execute:async(e,t)=>{const n=await b.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:Y.Object({thesisId:Y.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await b.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:Y.Object({thesisId:Y.String({description:"Thesis ID"}),updates:Y.Array(Y.Object({nodeId:Y.String({description:"Node ID (e.g. n3)"}),probability:Y.Number({description:"New probability (0-1)"}),reason:Y.Optional(Y.String({description:"Why"}))})),lock:Y.Optional(Y.Array(Y.String({description:"Node IDs to lock"})))}),execute:async(e,t)=>{const n=await b.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:Y.Object({thesisId:Y.String({description:"Thesis ID"}),newsIntervalMin:Y.Optional(Y.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:Y.Optional(Y.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:Y.Optional(Y.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:Y.Optional(Y.Number({description:"Monthly budget cap (0=unlimited)"})),paused:Y.Optional(Y.Boolean({description:"Pause/resume"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t,o=await b.request("PATCH",`/api/thesis/${n}/heartbeat`,s);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}},{name:"get_heartbeat_status",label:"Heartbeat Status",description:"Heartbeat config + cost summary for a thesis.",parameters:Y.Object({thesisId:Y.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await b.request("GET",`/api/thesis/${t.thesisId}/heartbeat`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}}),Me.push({name:"get_trade_ideas",label:"Trade Ideas",description:"S&T-style trade pitches: conviction, catalyst, direction, risk. No auth required.",parameters:Y.Object({freshness:Y.Optional(Y.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:Y.Optional(Y.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 s=await fetch(`${i}/api/public/ideas?${n.toString()}`);if(!s.ok)return{content:[{type:"text",text:`Ideas API error: ${s.status}`}],details:{}};const o=await s.json();return{content:[{type:"text",text:JSON.stringify(o,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:Y.Object({action:Y.String({description:"buy or sell"}),venue:Y.String({description:"kalshi or polymarket"}),marketId:Y.String({description:"Market ticker"}),marketTitle:Y.String({description:"Human-readable name"}),direction:Y.String({description:"yes or no"}),targetQuantity:Y.Number({description:"Number of contracts"}),maxPrice:Y.Optional(Y.Number({description:"Max price per contract in cents (1-99)"})),triggerType:Y.Optional(Y.String({description:"immediate, price_below, price_above, time"})),triggerPrice:Y.Optional(Y.Number({description:"Price trigger threshold in cents"})),rationale:Y.Optional(Y.String({description:"Why this trade"})),autoExecute:Y.Optional(Y.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(e,t)=>{const n=await b.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:Y.Object({activeOnly:Y.Optional(Y.Boolean({description:"Only active intents (default true)"}))}),execute:async(e,t)=>{const n=await b.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:Y.Object({intentId:Y.String({description:"Intent ID to cancel"})}),execute:async(e,t)=>{const n=await b.cancelIntentAPI(t.intentId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}}),Me.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:Y.Object({focus:Y.Optional(Y.String({description:'Comma-separated topics to focus on (e.g. "energy,geopolitics")'}))}),execute:async(e,t)=>{const n=t.focus?`?focus=${encodeURIComponent(t.focus)}`:"",s=await fetch(`${i}/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 since a given time. ~30-50 tokens. Much cheaper than full state for polling.",parameters:Y.Object({since:Y.Optional(Y.String({description:'Time window: "30m", "1h", "6h", "24h" or ISO timestamp (default "1h")'}))}),execute:async(e,t)=>{const n=t.since||"1h",s=await fetch(`${i}/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, push to webhook.",parameters:Y.Object({source:Y.Object({action:Y.String({description:"Firecrawl action: scrape, crawl, search, map, extract, batch_scrape"}),url:Y.Optional(Y.String({description:"Target URL (for scrape/crawl/extract)"})),query:Y.Optional(Y.String({description:"Search query (for search action)"}))}),analysis:Y.Optional(Y.Object({model:Y.Optional(Y.String({description:"OpenRouter model (e.g. google/gemini-flash-1.5)"})),prompt:Y.Optional(Y.String({description:"Analysis prompt"}))})),enrich:Y.Optional(Y.Object({topics:Y.Optional(Y.Array(Y.String(),{description:"Topics for market cross-reference"})),includeIndex:Y.Optional(Y.Boolean({description:"Include SF prediction market index"}))})),webhook:Y.Optional(Y.Object({url:Y.String({description:"Webhook URL"}),format:Y.Optional(Y.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 s=await n.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 between your content and market prices. No auth required.",parameters:Y.Object({content:Y.String({description:"Text to cross-reference with markets"}),topics:Y.Optional(Y.Array(Y.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 s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}}),Me.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime daemon is running and show active intents.",parameters:Y.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:o}=await Promise.resolve().then(n.t.bind(n,70857,23)),i=s(o(),".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 b.listIntents({active:!0});return{content:[{type:"text",text:JSON.stringify({running:r,pid:r?a:null,...c},null,2)}],details:{}}}},{...w(b)},{...k()}),Me.push({name:"daemon_command",label:"Daemon Command",description:"Send a command to a running daemon (runtime, telegram). Actions: pause, resume, scan_now.",parameters:Y.Object({target:Y.String({description:"Target daemon: runtime, telegram, watch"}),action:Y.String({description:"Command action: pause, resume, scan_now, adjust_trigger"}),data:Y.Optional(Y.Any({description:"Optional data for the command"}))}),execute:async(e,t)=>{const{writeMessage:s}=await n.e(563).then(n.bind(n,9563)),o=s({from:"agent",to:t.target,type:"command",priority:"normal",payload:{action:t.action,data:t.data},ttl:3600});return{content:[{type:"text",text:`Command sent to ${t.target}: ${t.action} (msg ${o})`}],details:{}}}},{name:"set_wake_condition",label:"Set Wake Condition",description:"Set a condition for daemons to alert you. Types: price (ticker crosses threshold), time (at a specific time), llm (natural language condition evaluated by LLM).",parameters:Y.Object({description:Y.String({description:"Human-readable description of the condition"}),type:Y.String({description:"Condition type: price, time, llm"}),condition:Y.Any({description:"Condition config: { ticker, operator, threshold } for price, { at } for time, { prompt, dataNeeded } for llm"}),priority:Y.Optional(Y.String({description:"Alert priority: low, normal, high, critical"}))}),execute:async(e,t)=>{const{saveWakeCondition:s}=await n.e(563).then(n.bind(n,9563)),{randomBytes:o}=await Promise.resolve().then(n.t.bind(n,76982,23)),i={id:o(8).toString("hex"),createdAt:(new Date).toISOString(),description:t.description,type:t.type,[`${t.type}Condition`]:t.condition,alertChannels:["bus"],priority:t.priority||"normal",maxFires:-1,firedCount:0,lastFiredAt:null,expiresAt:null,active:!0};return s(i),{content:[{type:"text",text:`Wake condition set: "${t.description}" (id: ${i.id})`}],details:{}}}},{name:"check_daemon_alerts",label:"Check Daemon Alerts",description:"Read alerts and observations from running daemons.",parameters:Ae,execute:async()=>{const{readMessages:e,deleteMessage:t}=await n.e(563).then(n.bind(n,9563)),s=e("agent","outbox");if(0===s.length)return{content:[{type:"text",text:"No new daemon alerts."}],details:{}};const o=s.map(e=>(t(e.id,"outbox"),`[${e.priority}] ${e.from} (${e.ts.slice(11,19)}): ${e.payload.summary||JSON.stringify(e.payload)}`));return{content:[{type:"text",text:o.join("\n")}],details:{}}}}),Me.push({name:"create_skill",label:"Create Skill",description:"Create a custom agent skill — a reusable prompt/workflow triggered via slash command.",parameters:Y.Object({name:Y.String({description:'Skill name (e.g. "precheck", "wti_arb")'}),trigger:Y.String({description:'Slash command trigger (e.g. "/precheck")'}),description:Y.String({description:"What this skill does"}),prompt:Y.String({description:"The full prompt/instructions for the skill"}),category:Y.Optional(Y.String({description:"Category: custom, trading, research, monitoring"})),tags:Y.Optional(Y.String({description:"Comma-separated tags"})),toolsUsed:Y.Optional(Y.String({description:"Comma-separated tool names used by this skill"}))}),execute:async(e,t)=>{const n={name:t.name,trigger:t.trigger,description:t.description,prompt:t.prompt};t.category&&(n.category=t.category),t.tags&&(n.tags=t.tags.split(",").map(e=>e.trim())),t.toolsUsed&&(n.toolsUsed=t.toolsUsed.split(",").map(e=>e.trim()));try{const e=await fetch(`${i}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(n)});if(!e.ok)return{content:[{type:"text",text:`Skill 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:`Error: ${e.message}`}],details:{}}}}},{name:"list_skills",label:"List Skills",description:"List all skills: built-in defaults + user-created custom skills.",parameters:Y.Object({}),execute:async()=>{try{const e=await fetch(`${i}/api/skill`,{headers:{Authorization:`Bearer ${o}`}});if(!e.ok)return{content:[{type:"text",text:`Skill 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:`Error: ${e.message}`}],details:{}}}}},{name:"browse_public_skills",label:"Browse Skills",description:"Browse community-created skills. No auth needed.",parameters:Y.Object({category:Y.Optional(Y.String({description:"Filter: custom, trading, research, monitoring"})),q:Y.Optional(Y.String({description:"Search by name/description"})),sort:Y.Optional(Y.String({description:"popular or new (default: new)"}))}),execute:async(e,t)=>{const n=new URLSearchParams;t.category&&n.set("category",t.category),t.q&&n.set("q",t.q),t.sort&&n.set("sort",t.sort);try{const e=await fetch(`${i}/api/public/skills?${n}`);if(!e.ok)return{content:[{type:"text",text:`Skills 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:`Error: ${e.message}`}],details:{}}}}},{name:"publish_skill",label:"Publish Skill",description:"Publish a skill to make it publicly browsable and forkable.",parameters:Y.Object({skillId:Y.String({description:"Skill ID to publish"}),slug:Y.String({description:"Public URL slug (lowercase, hyphens, 3-60 chars)"})}),execute:async(e,t)=>{try{const e=await fetch(`${i}/api/skill/${t.skillId}/publish`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({slug:t.slug})});if(!e.ok)return{content:[{type:"text",text:`Publish error: ${e.status}`}],details:{}};const n=await e.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}},{name:"fork_skill",label:"Fork Skill",description:"Fork a public skill into your collection.",parameters:Y.Object({skillId:Y.String({description:"ID of the public skill to fork"})}),execute:async(e,t)=>{try{const e=await fetch(`${i}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${o}`}});if(!e.ok)return{content:[{type:"text",text:`Fork error: ${e.status}`}],details:{}};const n=await e.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}},{name:"fork_thesis",label:"Fork Thesis",description:"Fork a public thesis. Copies thesis + causal tree. Accepts ID or slug.",parameters:Y.Object({idOrSlug:Y.String({description:"Public thesis ID or slug"})}),execute:async(e,t)=>{try{const e=await fetch(`${i}/api/thesis/${t.idOrSlug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${o}`}});if(!e.ok)return{content:[{type:"text",text:`Fork error: ${e.status}`}],details:{}};const n=await e.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}}),Me.push(...$(Y)),Me.push(...y(Y,b,i,o)),Me.push({name:"speak",label:"Speak",description:"Convert text to speech and play it through the speakers. Use for alerts, summaries, or when the user prefers audio.",parameters:Y.Object({text:Y.String({description:"Text to speak (max 5000 chars)"})}),execute:async(e,t)=>{try{const{speak:e}=await n.e(324).then(n.bind(n,99324));return await e(t.text),{content:[{type:"text",text:`🔊 Spoke: "${t.text.slice(0,80)}..."`}],details:{}}}catch(e){return{content:[{type:"text",text:`Voice error: ${e.message}`}],details:{}}}}}),Me.push({name:"schedule_wake",label:"Schedule Wake",description:"Schedule a self-wake: after N minutes of idle, you wake up to perform an action (prompt the LLM, run a tool, or just notify). Can repeat.",parameters:Y.Object({delayMinutes:Y.Number({description:"Minutes from now to fire"}),action:Y.String({description:"prompt | tool | check"}),prompt:Y.Optional(Y.String({description:"For action=prompt: what to ask yourself when you wake"})),toolName:Y.Optional(Y.String({description:"For action=tool: tool to call"})),toolParams:Y.Optional(Y.Any({description:"For action=tool: tool parameters"})),repeatMinutes:Y.Optional(Y.Number({description:"Auto-reschedule every N minutes"})),context:Y.Optional(Y.String({description:"Human-readable reason for this wake"}))}),execute:async(e,t)=>{const{scheduleWake:s}=await n.e(563).then(n.bind(n,9563)),o=s({delayMinutes:t.delayMinutes,action:t.action,prompt:t.prompt,toolCall:t.toolName?{name:t.toolName,params:t.toolParams||{}}:void 0,repeatMinutes:t.repeatMinutes,context:t.context,thesisId:x||void 0});return{content:[{type:"text",text:`Wake scheduled: "${t.context||t.action}" fires at ${o.fireAt}${t.repeatMinutes?` (repeats every ${t.repeatMinutes}m)`:""} [${o.id}]`}],details:{}}}},{name:"list_wakes",label:"List Wakes",description:"List all scheduled self-wakes (pending and fired).",parameters:Y.Object({}),execute:async()=>{const{listWakes:e}=await n.e(563).then(n.bind(n,9563)),t=e();if(0===t.length)return{content:[{type:"text",text:"No scheduled wakes."}],details:{}};const s=t.map(e=>`${e.firedAt?"✓":"⏰"} ${e.id.slice(0,8)} | ${e.action} | fires: ${e.fireAt.slice(11,16)} | ${e.context||""}${e.repeatMinutes?` (every ${e.repeatMinutes}m)`:""}`);return{content:[{type:"text",text:s.join("\n")}],details:{}}}},{name:"cancel_wake",label:"Cancel Wake",description:"Cancel a scheduled self-wake by ID.",parameters:Y.Object({id:Y.String({description:"Wake ID to cancel"})}),execute:async(e,t)=>{const{cancelWake:s}=await n.e(563).then(n.bind(n,9563));return{content:[{type:"text",text:s(t.id)?`Wake ${t.id} cancelled.`:`Wake ${t.id} not found.`}],details:{}}}});const Le=I?function(e){const t=(0,c.loadConfig)(),n=e.theses?.length||0,s=(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, publish, fork skills — reusable agent workflows (create_skill, list_skills, publish_skill, fork_skill, browse_public_skills)\n- Fork public theses — copy thesis + causal tree, then run formation (fork_thesis)\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- Live State shows positions/edges. Use it directly — only call get_positions for detail.\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${s}\n`}(v):Ne(v);let De=Le;const je=new V({initialState:{systemPrompt:De,model:se,tools:Me,thinkingLevel:"off"},streamFn:G,getApiKey:e=>{if("openrouter"===e)return l}});let Fe=!1;if(!t?.newSession){const e=S(x||"_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(),je.replaceMessages(n),je.setSystemPrompt(De),Fe=!0}catch{}}function Ke(){try{const e=je.state.messages;e.length>0&&(_(x||"_explorer",te,e),O(x||"_explorer",e,"tui"))}catch{}}let qe=null,Ue="",ze=null;const He=new Map,Be=new Map;let We=null;function Je(){We&&(clearTimeout(We),We=null),pe.requestRender()}async function Xe(e){const t=e.trim().split(/\s+/),s=t[0].toLowerCase();switch(s){case"/help":return Oe(),xe(R.zinc200(T("Commands"))+"\n"+R.emerald("/help ")+R.zinc400("Show this help")+"\n"+R.emerald("/tree ")+R.zinc400("Display causal tree")+"\n"+R.emerald("/edges ")+R.zinc400("Display edge/spread table")+"\n"+R.emerald("/pos ")+R.zinc400("Display Kalshi positions")+"\n"+R.emerald("/balance ")+R.zinc400("Quick balance check")+"\n"+R.emerald("/intents ")+R.zinc400("List active intents")+"\n"+R.emerald("/wakes ")+R.zinc400("List scheduled wakes")+"\n"+R.emerald("/alerts ")+R.zinc400("Check daemon alerts")+"\n"+R.emerald("/eval ")+R.zinc400("Trigger deep evaluation")+"\n"+R.emerald("/switch <id>")+R.zinc400(" Switch thesis")+"\n"+R.emerald("/compact ")+R.zinc400("Compress conversation history")+"\n"+R.emerald("/new ")+R.zinc400("Start fresh session")+"\n"+R.emerald("/model <m> ")+R.zinc400("Switch model")+"\n"+R.emerald("/voice ")+R.zinc400("Toggle voice recording (STT → send)")+"\n"+R.emerald("/env ")+R.zinc400("Show environment variable status")+"\n"+(Re.tradingEnabled?R.zinc600("─".repeat(30))+"\n"+R.emerald("/buy ")+R.zinc400("TICKER QTY PRICE — quick buy")+"\n"+R.emerald("/sell ")+R.zinc400("TICKER QTY PRICE — quick sell")+"\n"+R.emerald("/cancel ")+R.zinc400("ORDER_ID — cancel order")+"\n"+R.zinc600("─".repeat(30))+"\n":"")+(Se.length>0?R.zinc600("─".repeat(30))+"\n"+R.zinc200(T("Skills"))+"\n"+Se.map(e=>R.emerald(`/${e.name.padEnd(10)}`)+R.zinc400(e.description.slice(0,45))).join("\n")+"\n"+R.zinc600("─".repeat(30))+"\n":"")+R.emerald("/clear ")+R.zinc400("Clear screen (keeps history)")+"\n"+R.emerald("/exit ")+R.zinc400("Exit (auto-saves)")),Oe(),!0;case"/tree":if(Oe(),I)xe(R.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one."));else try{v=await b.getContext(x),xe(R.zinc200(T("Causal Tree"))+"\n"+function(e){const t=e.causalTree;if(!t?.nodes?.length)return R.zinc600(" No causal tree data");const n=[];for(const e of t.nodes){const t=e.id||"",s=e.label||e.description||"",o="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!==o){const e=Math.round(o/10),i="█".repeat(e)+"░".repeat(10-e),a=o>=70?R.emerald:o>=40?R.amber:R.red,c=`${r}${R.zinc600(t)} ${R.zinc400(s)} `,l=` ${a(`${o}%`)} ${a(i)}`;n.push(c+l)}else n.push(`${r}${R.zinc600(t)} ${R.zinc400(s)}`)}return n.join("\n")}(v))}catch(e){xe(R.red(`Error: ${p(e)}`))}return Oe(),!0;case"/edges":if(Oe(),I)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)xe(R.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),s=String(Math.round(e.price||0)).padStart(3)+"¢",o="+"+Math.round(e.edge||0);return` ${R.zinc400(t)} ${R.zinc600(n)} ${R.zinc400(s)} ${R.emerald(o.padStart(4))}`}).join("\n");xe(R.zinc200(T("Public Edges"))+"\n"+e)}}catch(e){xe(R.red(`Error: ${p(e)}`))}else try{v=await b.getContext(x),re&&(v._positions=re),xe(R.zinc200(T("Edges"))+"\n"+function(e){const t=e.edges;if(!t?.length)return R.zinc600(" No edge data");const n=e._positions||[],s=[];for(const e of t){const t=(e.market||e.marketId||"").slice(0,18).padEnd(18),o="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?R.emerald:"medium"===l?R.amber:R.red,p=n.find(t=>t.ticker===e.marketId||e.marketId&&t.ticker?.includes(e.marketId));let h=R.zinc600("—");if(p){const e=p.side?.toUpperCase()||"YES",t="number"==typeof p.unrealized_pnl?p.unrealized_pnl>=0?R.emerald(`+$${(p.unrealized_pnl/100).toFixed(0)}`):R.red(`-$${(Math.abs(p.unrealized_pnl)/100).toFixed(0)}`):"";h=R.emerald(`${e} (${p.quantity}@${p.average_price_paid}¢ ${t})`)}s.push(` ${R.zinc200(t)} ${R.zinc400(o)} → ${R.zinc400(i)} edge ${r.includes("+")?R.emerald(r):R.red(r)} spread ${R.zinc600(c)} ${u(d)} ${u(l.padEnd(4))} ${h}`)}return s.join("\n")}(v))}catch(e){xe(R.red(`Error: ${p(e)}`))}return Oe(),!0;case"/pos":Oe();try{const e=await(await u()).getPositions();if(!e)return xe(R.zinc600("Kalshi not configured")),!0;for(const t of e){const e=await(await u()).getMarketPrice(t.ticker);null!==e&&(t.current_value=e,t.unrealized_pnl=Math.round((e-t.average_price_paid)*t.quantity))}re=e,xe(R.zinc200(T("Positions"))+"\n"+function(e){if(!e?.length)return R.zinc600(" No positions");const t=[];let n=0;for(const s of e){const e=(s.ticker||"").slice(0,18).padEnd(18),o=(s.side||"yes").toUpperCase().padEnd(3),i=String(s.quantity||0),r=`${s.average_price_paid||0}¢`,a="number"==typeof s.current_value&&s.current_value>0?`${s.current_value}¢`:"?¢",c=s.unrealized_pnl||0;n+=c;const l=(c/100).toFixed(2),d=c>=0?R.emerald(`+$${l}`):R.red(`-$${Math.abs(parseFloat(l)).toFixed(2)}`),u=c>=0?R.emerald("▲"):R.red("▼");t.push(` ${R.zinc200(e)} ${R.zinc400(o)} ${R.zinc400(i)} @ ${R.zinc400(r)} now ${R.zinc200(a)} ${d} ${u}`)}const s=(n/100).toFixed(2);return t.push(R.zinc600(" "+"─".repeat(40))),t.push(n>=0?` Total P&L: ${R.emerald(T(`+$${s}`))}`:` Total P&L: ${R.red(T(`-$${Math.abs(parseFloat(s)).toFixed(2)}`))}`),t.join("\n")}(e))}catch(e){xe(R.red(`Error: ${p(e)}`))}return Oe(),!0;case"/eval":if(Oe(),I)return xe(R.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one.")),Oe(),!0;xe(R.zinc600("Triggering evaluation...")),pe.requestRender();try{const e=await b.evaluate(x);xe(R.emerald("Evaluation complete")+"\n"+R.zinc400(JSON.stringify(e,null,2)))}catch(e){xe(R.red(`Error: ${p(e)}`))}return Oe(),!0;case"/model":{const e=t.slice(1).join(" ").trim();return e?(Oe(),te=e.replace(/^openrouter\//,""),se=ne(te),je.setModel(se),fe.modelName=te,fe.update(),xe(R.emerald(`Model switched to ${te}`)),Oe(),pe.requestRender(),!0):(xe(R.zinc400(`Current model: ${te}`)),!0)}case"/switch":{const n=t[1]?.trim();if(!n)return xe(R.zinc400("Usage: /switch <thesisId>")),!0;Oe();try{Ke();const e=await b.getContext(n);x=e.thesisId||n,v=e;const t=Ne(e);"number"==typeof e.confidence&&Math.round(100*e.confidence);je.clearMessages();const s=S(x);s?.messages?.length>0?(je.replaceMessages(s.messages),je.setSystemPrompt(t),xe(R.emerald(`Switched to ${x.slice(0,8)}`)+R.zinc400(` (resumed ${s.messages.length} messages)`))):(je.setSystemPrompt(t),xe(R.emerald(`Switched to ${x.slice(0,8)}`)+R.zinc400(" (new session)"))),fe.setFromContext(e,ye||void 0),ke.clear(),xe(Ye(e,ye))}catch(e){xe(R.red(`Switch failed: ${e.message}`))}return Oe(),pe.setFocus(be),pe.requestRender(),!0}case"/compact":Oe();try{const t=je.state.messages;if(t.length<=10)return xe(R.zinc400("Conversation too short to compact")),Oe(),pe.setFocus(be),!0;const n=3;let s=0,o=t.length;for(let e=t.length-1;e>=0;e--)if("user"===t[e].role&&(s++,s>=n)){o=e;break}if(o<=2)return xe(R.zinc400("Not enough complete turns to compact")),Oe(),pe.setFocus(be),!0;const a=t.slice(0,o),c=t.slice(o),d=new z(pe,e=>R.emerald(e),e=>R.zinc600(e),"compacting with LLM...");d.start(),ke.addChild(d),pe.requestRender();const u=[];let p=0;const h=12e3;for(const e of a){if(p>=h)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(),s=`[${n}]: ${t.slice(0,800)}`;u.push(s),p+=s.length}const m=u.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 ${l}`,"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 s=await n.json();if(y=s.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")}`}d.stop(),ke.removeChild(d);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];je.clearMessages(),je.replaceMessages($),je.setSystemPrompt(De),Ke(),xe(R.emerald(`Compacted: ${a.length} messages → summary + ${c.length} recent`)+R.zinc600(` (via ${g.split("/").pop()})`)),Oe(),pe.setFocus(be),pe.requestRender()}catch(e){xe(R.red(`Compact failed: ${e.message||e}`)),Oe(),pe.setFocus(be),pe.requestRender()}return!0;case"/new":return Oe(),Ke(),je.clearMessages(),je.setSystemPrompt(De),ke.clear(),xe(R.emerald("Session cleared")+R.zinc400(" — fresh start")),Oe(),pe.requestRender(),!0;case"/env":{Oe();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)} ${R.emerald("✓")} ${R.zinc400(n)}`}{const t=e.required?"必须":"可选";return` ${e.name.padEnd(18)} ${R.red("✗")} ${R.zinc600(`未配置(${t})`)}`}});return xe(R.zinc200(T("Environment"))+"\n"+e.join("\n")),Oe(),!0}case"/clear":{const e=[...ke.children||[]];for(const t of e)try{ke.removeChild(t)}catch{}return Oe(),ie=!1,de=null,pe.setFocus(be),pe.requestRender(),!0}case"/buy":{const[,s,o,i]=t;if(!s||!o||!i)return xe(R.zinc400("Usage: /buy TICKER QTY PRICE_CENTS (e.g. /buy KXWTIMAX-26DEC31-T135 100 50)")),!0;if(!Re.tradingEnabled)return xe(R.red("Trading disabled. Run: sf setup --enable-trading")),!0;Oe();if((await Ce(`BUY ${o}x ${s} 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:s,side:"yes",action:"buy",type:"limit",count:parseInt(o),yes_price:parseInt(i)});xe(R.emerald("✓ Order placed: "+((t.order||t).order_id||"OK")))}catch(e){xe(R.red("✗ "+e.message))}else xe(R.zinc400("Cancelled."));return Oe(),!0}case"/sell":{const[,s,o,i]=t;if(!s||!o||!i)return xe(R.zinc400("Usage: /sell TICKER QTY PRICE_CENTS")),!0;if(!Re.tradingEnabled)return xe(R.red("Trading disabled. Run: sf setup --enable-trading")),!0;Oe();if((await Ce(`SELL ${o}x ${s} 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:s,side:"yes",action:"sell",type:"limit",count:parseInt(o),yes_price:parseInt(i)});xe(R.emerald("✓ Order placed: "+((t.order||t).order_id||"OK")))}catch(e){xe(R.red("✗ "+e.message))}else xe(R.zinc400("Cancelled."));return Oe(),!0}case"/cancel":{const[,s]=t;if(!s)return xe(R.zinc400("Usage: /cancel ORDER_ID")),!0;if(!Re.tradingEnabled)return xe(R.red("Trading disabled. Run: sf setup --enable-trading")),!0;Oe();try{const{cancelOrder:e}=await Promise.resolve().then(n.t.bind(n,96139,23));await e(s),xe(R.emerald(`✓ Order ${s} cancelled.`))}catch(e){xe(R.red("✗ "+e.message))}return Oe(),!0}case"/balance":Oe();try{const e=await Promise.resolve().then(n.t.bind(n,96139,23)),t=await e.getBalance();if(!t)return xe(R.zinc400(" Kalshi not configured.")),!0;xe(R.zinc200(` Balance: $${((t.balance||0)/100).toFixed(2)} Portfolio: $${((t.portfolioValue||0)/100).toFixed(2)}`))}catch(e){xe(R.red(` ${e.message}`))}return Oe(),!0;case"/intents":Oe();try{const e=((await b.listIntents({active:!0})).intents||[]).filter(e=>["pending","armed","triggered"].includes(e.status));if(0===e.length)return xe(R.zinc400(" No active intents.")),!0;for(const t of e){xe(` ${"armed"===t.status?R.amber(t.status):R.zinc400(t.status)} ${R.zinc200(t.action)} ${R.zinc400((t.marketId||"").slice(0,20))} qty:${t.targetQuantity} ${t.triggerType}:${t.triggerPrice||"-"}`)}}catch(e){xe(R.red(` ${e.message}`))}return Oe(),!0;case"/wakes":Oe();try{const{listWakes:e}=await n.e(563).then(n.bind(n,9563)),t=e().filter(e=>!e.firedAt);if(0===t.length)return xe(R.zinc400(" No pending wakes.")),!0;for(const e of t)xe(` ${R.amber("⏰")} ${e.fireAt.slice(11,16)} ${R.zinc200(e.action)} ${R.zinc400(e.context||"")}${e.repeatMinutes?R.zinc600(` (every ${e.repeatMinutes}m)`):""}`)}catch(e){xe(R.red(` ${e.message}`))}return Oe(),!0;case"/alerts":Oe();try{const{readMessages:e}=await n.e(563).then(n.bind(n,9563)),t=e("agent","outbox").filter(e=>!e.read);if(0===t.length)return xe(R.zinc400(" No new alerts.")),!0;for(const e of t){xe(("critical"===e.priority||"high"===e.priority?R.red:R.zinc400)(` [${e.from}] ${e.payload.summary||JSON.stringify(e.payload)}`))}}catch(e){xe(R.red(` ${e.message}`))}return Oe(),!0;case"/voice":try{const e=await n.e(324).then(n.bind(n,99324));if(e.isRecording()){xe(R.amber(" ⏹ Stopping recording...")),pe.requestRender();const t=e.stopRecording();if(!t)return xe(R.red(" No audio captured.")),!0;xe(R.zinc400(" Transcribing...")),pe.requestRender();const n=await e.transcribe(t);if(!n.text)return xe(R.red(" Transcription empty.")),!0;xe(R.emerald(` 🎤 "${n.text}"`)),Oe(),pe.requestRender(),ie=!0;const s=new K(R.emerald(T(">"))+" "+R.white(`🎤 ${n.text}`),1,0);ke.addChild(s),Oe(),pe.requestRender(),je.prompt(n.text).catch(e=>{xe(R.red(`Error: ${p(e)}`)),ie=!1})}else{if(!e.isRecordingAvailable())return xe(R.red(" Voice recording requires sox. Install: brew install sox")),!0;e.startRecording(),xe(R.amber(" 🎙 Recording... type /voice again to stop and send")),pe.requestRender()}}catch(e){xe(R.red(` Voice error: ${e.message}`))}return!0;case"/exit":case"/quit":return Ge(),!0;default:{const t=Se.find(e=>e.trigger===s);if(t){Oe(),xe(R.zinc200(`Running skill: ${T(t.name)}`)+R.zinc600(` — ${t.description.slice(0,60)}`)),Oe(),pe.requestRender(),ie=!0;try{await je.prompt(t.prompt)}catch(e){xe(R.red(`Skill error: ${e.message}`))}finally{ie=!1}return!0}return!1}}}function Ge(){le&&clearInterval(le),et&&clearInterval(et),ze&&ze.stop(),Ke(),pe.stop(),process.exit(0)}function Ye(e,t){const n=[];if(e._explorerMode){const t=e.edges?.length||0,s=e.theses?.length||0;n.push(R.zinc600("─".repeat(55))),n.push(" "+R.emerald(T("Explorer mode"))+R.zinc600(" — full market access, no thesis")),n.push(" "+R.zinc600(`${s} public theses │ ${t} edges tracked`)),n.push(R.zinc600("─".repeat(55)));const o=e.edges||[];if(o.length>0){const e=[...o].sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,5);n.push(" "+R.zinc400(T("TOP PUBLIC EDGES"))+R.zinc600(" mkt edge"));for(const t of e){const e=(t.title||"").slice(0,30).padEnd(30),s=String(Math.round(t.price||0)).padStart(3)+"¢",o=t.edge||0,i="+"+Math.round(o),r=Math.abs(o)>=15?R.emerald:Math.abs(o)>=8?R.amber:R.zinc400;n.push(` ${R.zinc400(e)} ${R.zinc400(s)} ${r(i.padStart(4))}`)}}return n.push(R.zinc600("─".repeat(55))),n.push(" "+R.zinc600("Ask anything, or describe a view to create a thesis.")),n.push(R.zinc600("─".repeat(55))),n.join("\n")}const s=e.thesis||e.rawThesis||"N/A",o=s.length>100?s.slice(0,100)+"...":s,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(R.zinc600("─".repeat(55))),n.push(" "+R.zinc200(T(o))),n.push(" "+R.zinc600(`${e.status||"active"} ${i}%${a}`)+(null!==c?R.zinc600(` │ last eval: ${c<1?"<1":c}h ago`):"")),n.push(R.zinc600("─".repeat(55))),t&&t.length>0){n.push(" "+R.zinc400(T("POSITIONS")));let e=0;for(const s of t){const t=s.unrealized_pnl||0;e+=t;const o=t>=0?R.emerald(`+$${(t/100).toFixed(2)}`):R.red(`-$${(Math.abs(t)/100).toFixed(2)}`),i=(s.ticker||"").slice(0,28).padEnd(28),r=String(s.quantity||0).padStart(5),a="yes"===s.side?R.emerald("Y"):R.red("N");n.push(` ${R.zinc400(i)} ${r} ${a} ${o}`)}const s=e>=0?R.emerald(T(`+$${(e/100).toFixed(2)}`)):R.red(T(`-$${(Math.abs(e)/100).toFixed(2)}`));n.push(` ${"".padEnd(28)} ${R.zinc600("Total")} ${s}`)}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(R.zinc600("─".repeat(55))),n.push(" "+R.zinc400(T("TOP EDGES"))+R.zinc600(" mkt edge liq"));for(const t of e){const e=(t.market||t.marketTitle||t.marketId||"").slice(0,30).padEnd(30),s=String(Math.round(t.marketPrice||0)).padStart(3)+"¢",o=t.edge||t.edgeSize||0,i=(o>0?"+":"")+Math.round(o),r=t.orderbook?.liquidityScore||("polymarket"===t.venue?"-":"?"),a=Math.abs(o)>=15?R.emerald:Math.abs(o)>=8?R.amber:R.zinc400;n.push(` ${R.zinc400(e)} ${R.zinc400(s)} ${a(i.padStart(4))} ${R.zinc600(r)}`)}}return n.push(R.zinc600("─".repeat(55))),n.join("\n")}je.subscribe(e=>{if("message_start"===e.type&&(Ue="",qe=null,ze=new z(pe,e=>R.emerald(e),e=>R.zinc600(e),"thinking..."),ze.start(),ke.addChild(ze),pe.requestRender()),"message_update"===e.type){const t=e.assistantMessageEvent;"text_delta"===t.type&&(ze&&(ze.stop(),ke.removeChild(ze),ze=null,qe=new q("",1,0,he,me),ke.addChild(qe)),Ue+=t.delta,qe&&qe.setText(Ue),We||(We=setTimeout(()=>{We=null,pe.requestRender()},66)))}if("message_end"===e.type&&(ze&&(ze.stop(),ke.removeChild(ze),ze=null),qe&&Ue&&qe.setText(Ue),Oe(),qe=null,Ue="",Je()),"agent_end"===e.type&&(ie=!1,Ke(),Je(),ce)){const e=ce;ce=null,Ze(e)}if("tool_execution_start"===e.type){const t=new Q(R.zinc600(` ▸ ${e.toolName}...`));He.set(e.toolCallId||e.toolName,Date.now()),Be.set(e.toolCallId||e.toolName,t),ke.addChild(t),oe++,fe.toolCount=oe,fe.update(),pe.requestRender()}if("tool_execution_end"===e.type){const t=e.toolCallId||e.toolName,n=He.get(t),s=n?((Date.now()-n)/1e3).toFixed(1):"?",o=Be.get(t);o&&(e.isError?o.setText(R.red(` ✗ ${e.toolName} (${s}s) error`)):o.setText(R.zinc600(` ▸ ${e.toolName} `)+R.emerald("✓")+R.zinc600(` ${s}s`))),He.delete(t),Be.delete(t),pe.requestRender()}}),be.onSubmit=async e=>{const t=e.trim();if(!t)return;if(de){const{resolve:e}=de;de=null;const n=new K(R.zinc400(" > ")+R.zinc200(t),1,0);return ke.addChild(n),Oe(),pe.requestRender(),void e(t)}if(ie)return;if(be.addToHistory(t),t.startsWith("/")){if(await Xe(t))return}ie=!0;const n=new K(R.emerald(T(">"))+" "+R.white(t),1,0);ke.addChild(n),Oe(),pe.requestRender(),await async function(){if(!I)try{const e=await C(b,x);De=Le+e,je.setSystemPrompt(De)}catch{}}();try{await je.prompt(t)}catch(e){ze&&(ze.stop(),ke.removeChild(ze),ze=null),xe(R.red(`Error: ${p(e)}`)),Oe(),ie=!1}},pe.addInputListener(e=>{if(""===e)return Ge(),{consume:!0}}),process.on("SIGINT",Ge),process.on("SIGTERM",Ge);const Ve=Fe?R.zinc600(`resumed (${je.state.messages.length} messages)`):R.zinc600("new session");xe(Ye(v,ye)),xe(" "+Ve),Oe();const Qe=.03;function Ze(e){const t=Math.abs(e.confidenceDelta||0),n=Math.round(100*(e.confidence||0)),s=Math.round(100*(e.confidenceDelta||0)),o=s>0?"+":"";if(t>=Qe){const t=s>0?"▲":"▼";xe((s>0?R.emerald:R.red)(` ${t} Heartbeat: confidence ${o}${s}% → ${n}%`)),e.latestSummary&&xe(R.zinc400(` ${e.latestSummary.slice(0,100)}`)),Oe(),fe.setFromContext({...v,confidence:e.confidence,lastEvaluation:{confidenceDelta:e.confidenceDelta}},ye||void 0),pe.requestRender(),ie=!0;const i=`[HEARTBEAT ALERT] Confidence just changed ${o}${s}% 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.`;je.prompt(i).catch(e=>{xe(R.red(`Error: ${p(e)}`)),ie=!1})}else t>0&&(xe(R.zinc600(` ─ heartbeat: ${n}% (${o}${s}%) — ${e.evaluationCount||0} eval(s)`)),pe.requestRender())}I||(le=setInterval(async()=>{try{const e=await b.getChanges(x,ae);if(ae=(new Date).toISOString(),!e.changed)return;ie||de?ce=e:Ze(e)}catch{}},6e4));const et=setInterval(async()=>{try{const{writeAgentHeartbeat:e,readMessages:t,getDueWakes:s,markFired:o,cleanOldWakes:i}=await n.e(563).then(n.bind(n,9563));e(x||void 0);const r=t("agent","outbox").filter(e=>!e.read);for(const e of r)if(!ie&&!de){const{deleteMessage:t}=await n.e(563).then(n.bind(n,9563));xe(("critical"===e.priority||"high"===e.priority?R.red:R.zinc400)(` [${e.from}] ${e.payload.summary||JSON.stringify(e.payload)}`)),t(e.id,"outbox"),pe.requestRender()}if(!ie&&!de){const e=s();for(const t of e){if(ie)break;o(t);xe(R.amber(` ⏰ [wake] ${t.context||t.action}`)),pe.requestRender(),"prompt"===t.action&&t.prompt?(ie=!0,je.prompt(`[SELF-WAKE: ${t.context||"scheduled check"}] ${t.prompt}`).catch(e=>{xe(R.red(`Wake error: ${e.message}`)),ie=!1})):"tool"===t.action&&t.toolCall&&(xe(R.zinc400(` → tool: ${t.toolCall.name}`)),pe.requestRender())}i()}}catch{}},3e4);pe.start()};const o=s(n(79896)),i=s(n(16928)),r=s(n(70857)),a=n(19218),c=n(11627),l=n(73600),d={kalshi:null,polymarket:null,topics:null,skills:null,client:null};async function u(){return d.kalshi??=await Promise.resolve().then(n.t.bind(n,96139,23))}function p(e){const t=e?.message||String(e);return/401|unauthorized|Unauthorized/i.test(t)?`${t}\n → Run \`sf login\` to refresh credentials`:/403|forbidden/i.test(t)?`${t}\n → API key may lack permissions. Check \`sf status\``:/ECONNREFUSED|ENOTFOUND|fetch failed/i.test(t)?`${t}\n → Server unreachable. Check your internet or SF_API_URL`:/timeout|timed out|ETIMEDOUT/i.test(t)?`${t}\n → Request timed out. Try again or check \`sf status\``:/kalshi.*not configured|Kalshi not configured/i.test(t)?`${t}\n → Run \`sf setup\` to configure Kalshi API keys`:/no.*thesis|thesis.*not found/i.test(t)?`${t}\n → Create one: \`sf create "your thesis"\``:/openrouter|model.*not found/i.test(t)?`${t}\n → Check OPENROUTER_API_KEY or use \`sf setup\``:t}async function h(){return d.polymarket??=await Promise.resolve().then(n.bind(n,34331))}async function m(){return d.topics??=await Promise.resolve().then(n.bind(n,97325))}async function g(){return d.skills??=await n.e(482).then(n.bind(n,40101))}async function f(){return d.client??=await Promise.resolve().then(n.bind(n,19218))}function y(e,t,s,o){return[{name:"calculate",label:"Calculate",description:"Evaluate a math expression precisely. Use for edge sizing, P&L calculation, probability math. Supports +,-,*,/,**,%,Math functions.",parameters:e.Object({expression:e.String({description:'Math expression, e.g. "0.64 * 0.75 + 0.36 * 0.2" or "Math.round(35.7 * 500 / 100)"'})}),execute:async(e,t)=>{try{const e=t.expression.trim();if(!/^[\d\s+\-*/.%(),eE]+$/.test(e.replace(/Math\.\w+/g,"").replace(/\*\*/g,"")))return{content:[{type:"text",text:"Unsafe expression. Only numbers, operators, and Math.* allowed."}],details:{}};return{content:[{type:"text",text:`${e} = ${new Function(`"use strict"; return (${e})`)()}`}],details:{}}}catch(e){return{content:[{type:"text",text:`Calc error: ${e.message}`}],details:{}}}}},{name:"send_alert",label:"Send Alert",description:"Push an alert to the user via Telegram and/or the daemon message bus. Use when you discover something important that needs immediate attention.",parameters:e.Object({message:e.String({description:"Alert message"}),priority:e.Optional(e.String({description:"low | normal | high | critical (default: high)"}))}),execute:async(e,t)=>{const s=[];try{const{writeMessage:e}=await n.e(563).then(n.bind(n,9563));e({from:"agent",to:"all",type:"alert",priority:t.priority||"high",payload:{summary:t.message},ttl:7200}),s.push("bus: ✓")}catch{s.push("bus: ✗")}try{const{loadConfig:e}=await Promise.resolve().then(n.t.bind(n,11627,23)),o=e().telegramBotToken||process.env.TELEGRAM_BOT_TOKEN;if(o){const e=await fetch(`https://api.telegram.org/bot${o}/getUpdates?limit=1&offset=-1`,{signal:AbortSignal.timeout(5e3)});if(e.ok){const n=await e.json(),i=n.result?.[0]?.message?.chat?.id;if(i){const e="critical"===t.priority?"🚨":"high"===t.priority?"⚠️":"ℹ️";await fetch(`https://api.telegram.org/bot${o}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:i,text:`${e} ${t.message}`}),signal:AbortSignal.timeout(5e3)}),s.push("telegram: ✓")}}}}catch{}return{content:[{type:"text",text:`Alert sent (${s.join(", ")}): "${t.message}"`}],details:{}}}},{name:"cancel_all_intents",label:"Cancel All Intents",description:"Cancel all active intents. Use in emergency or when strategy changes fundamentally.",parameters:e.Object({confirm:e.Boolean({description:"Must be true to proceed"})}),execute:async(e,n)=>{if(!n.confirm)return{content:[{type:"text",text:"Set confirm=true to cancel all intents."}],details:{}};try{const e=((await t.listIntents({active:!0})).intents||[]).filter(e=>["pending","armed"].includes(e.status));if(0===e.length)return{content:[{type:"text",text:"No active intents to cancel."}],details:{}};let n=0;for(const s of e)try{await t.cancelIntentAPI(s.id),n++}catch{}return{content:[{type:"text",text:`Cancelled ${n}/${e.length} intents.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Error: ${e.message}`}],details:{}}}}}]}function $(e){return[{name:"fs_read",label:"Read File",description:"Read a file from your workspace (~/.sf/workspace/). Use relative paths.",parameters:e.Object({path:e.String({description:"File path relative to workspace root"})}),execute:async(e,t)=>{const n=(0,l.wsRead)(t.path);return{content:[{type:"text",text:n.ok?n.content:`Error: ${n.content}`}],details:{}}}},{name:"fs_write",label:"Write File",description:"Write or append to a file in your workspace. Creates parent directories automatically.",parameters:e.Object({path:e.String({description:"File path relative to workspace root"}),content:e.String({description:"Content to write"}),append:e.Optional(e.Boolean({description:"Append instead of overwrite (default: false)"}))}),execute:async(e,t)=>({content:[{type:"text",text:(0,l.wsWrite)(t.path,t.content,t.append).message}],details:{}})},{name:"fs_list",label:"List Files",description:"List files and directories in your workspace. Omit path to list root.",parameters:e.Object({path:e.Optional(e.String({description:"Directory path (default: root)"})),glob:e.Optional(e.String({description:'Filter pattern (e.g. "*.md", "analysis*")'}))}),execute:async(e,t)=>{const n=(0,l.wsList)(t.path,t.glob);return n.ok?{content:[{type:"text",text:n.entries.length>0?n.entries.join("\n"):"(empty)"}],details:{}}:{content:[{type:"text",text:`Error: ${n.message}`}],details:{}}}},{name:"fs_search",label:"Search Files",description:"Search file contents in your workspace using regex. Returns matching lines with file paths.",parameters:e.Object({pattern:e.String({description:"Regex pattern to search for"}),path:e.Optional(e.String({description:"Directory to search in (default: all)"}))}),execute:async(e,t)=>{const n=(0,l.wsSearch)(t.pattern,t.path);if(!n.ok)return{content:[{type:"text",text:`Error: ${n.message}`}],details:{}};if(0===n.matches.length)return{content:[{type:"text",text:"No matches."}],details:{}};const s=n.matches.map(e=>`${e.file}:${e.line}: ${e.text}`);return{content:[{type:"text",text:s.join("\n")}],details:{}}}},{name:"fs_delete",label:"Delete File",description:"Delete a file from your workspace.",parameters:e.Object({path:e.String({description:"File path to delete"})}),execute:async(e,t)=>({content:[{type:"text",text:(0,l.wsDelete)(t.path).message}],details:{}})}]}function w(e){return{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon. Evaluates intent triggers and executes orders via local keys.",parameters:{type:"object",properties:{}},execute:async()=>{const{existsSync:e,readFileSync:t,openSync:s,mkdirSync:o}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:i}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:r}=await Promise.resolve().then(n.t.bind(n,70857,23)),{spawn:a}=await Promise.resolve().then(n.t.bind(n,35317,23)),c=i(r(),".sf","runtime.pid"),l=i(r(),".sf","runtime.log");if(e(c)){const e=t(c,"utf-8").trim();try{return process.kill(parseInt(e),0),{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{try{(await Promise.resolve().then(n.t.bind(n,79896,23))).unlinkSync(c)}catch{}}}o(i(r(),".sf"),{recursive:!0});const d=s(l,"a");if(a(process.execPath,[process.argv[1],"runtime","start"],{detached:!0,stdio:["ignore",d,d],env:{...process.env}}).unref(),await new Promise(e=>setTimeout(e,1e3)),e(c)){return{content:[{type:"text",text:`Runtime started (PID ${t(c,"utf-8").trim()}). Log: ${l}`}],details:{}}}return{content:[{type:"text",text:"Runtime starting... check runtime_status in a moment."}],details:{}}}}}function k(){return{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:{type:"object",properties:{}},execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:s}=await Promise.resolve().then(n.t.bind(n,79896,23)),{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23)),{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23)),r=o(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"),s(r),{content:[{type:"text",text:`Runtime stopped (PID ${a}).`}],details:{}}}catch{try{s(r)}catch{}return{content:[{type:"text",text:"Runtime was not running (stale PID file removed)."}],details:{}}}}}}function b(){return i.default.join(r.default.homedir(),".sf","sessions")}function v(e){return i.default.join(b(),`${e}.json`)}function S(e){const t=v(e);try{if(o.default.existsSync(t))return JSON.parse(o.default.readFileSync(t,"utf-8"))}catch{}return null}function _(e,t,n){const s=b();o.default.mkdirSync(s,{recursive:!0}),o.default.writeFileSync(v(e),JSON.stringify({thesisId:e,model:t,updatedAt:(new Date).toISOString(),messages:n},null,2))}let x=0;function O(e,t,s="tui"){try{const{appendContext:o}=n(73600),i=t.slice(x);for(const t of i){if(!t||!t.role)continue;const n="string"==typeof t.content?t.content:Array.isArray(t.content)?t.content.map(e=>e.text||"").join(""):JSON.stringify(t.content||"");n&&0!==n.length&&o(e,{ts:(new Date).toISOString(),role:t.role,content:n.slice(0,5e3),source:s,toolName:t.name,toolCallId:t.tool_call_id})}x=t.length}catch{}}async function C(e,t){const s=[];try{const[o,i,r,a,c]=await Promise.allSettled([Promise.race([e.getContext(t),new Promise((e,t)=>setTimeout(t,3e3))]),Promise.race([e.listIntents({active:!0}),new Promise((e,t)=>setTimeout(t,3e3))]),(async()=>(await Promise.resolve().then(n.t.bind(n,96139,23))).getPositions())().catch(()=>null),(async()=>(await Promise.resolve().then(n.t.bind(n,96139,23))).getBalance())().catch(()=>null),(async()=>{const{getPendingWakes:e}=await n.e(563).then(n.bind(n,9563));return e()})().catch(()=>[])]);if("fulfilled"===o.status&&o.value){const e=o.value,t="number"==typeof e.confidence?Math.round(100*e.confidence):"?";s.push(`Confidence: ${t}%`);const n=(e.edges||[]).sort((e,t)=>Math.abs(t.edge)-Math.abs(e.edge)).slice(0,3);n.length>0&&s.push("Top edges: "+n.map(e=>`${(e.market||"").slice(0,25)} ${e.edge>0?"+":""}${e.edge}¢`).join(" | "))}if("fulfilled"===r.status&&r.value&&r.value.length>0){const e=r.value,t=e.slice(0,5).map(e=>{const t=null!=e.unrealized_pnl?` ${e.unrealized_pnl>0?"+":""}$${(e.unrealized_pnl/100).toFixed(2)}`:"";return`${e.ticker} ${e.quantity}qty${t}`}).join(" | ");s.push(`Positions (${e.length}): ${t}`)}else s.push("Positions: none or Kalshi not configured");if("fulfilled"===a.status&&a.value){const e=a.value;s.push(`Balance: $${((e.balance||0)/100).toFixed(2)}`)}if("fulfilled"===i.status&&i.value){const e=(i.value.intents||[]).filter(e=>["pending","armed"].includes(e.status));e.length>0&&s.push(`Active intents: ${e.length} (${e.map(e=>`${e.action} ${e.marketId?.slice(0,15)} ${e.status}`).join(", ")})`)}if("fulfilled"===c.status&&c.value){const e=c.value;e.length>0&&s.push(`Pending wakes: ${e.length} (${e.map(e=>e.context||e.action).join(", ")})`)}try{const{wsList:e}=await Promise.resolve().then(n.t.bind(n,73600,23)),{entries:t}=e();t.length>0&&s.push(`Workspace: ${t.slice(0,5).join(", ")}`)}catch{}}catch{return""}return 0===s.length?"":`\n\n## Live State (auto-refreshed)\n${s.join("\n")}`}const I=(e,t,n)=>s=>`[38;2;${e};${t};${n}m${s}[39m`,P=(e,t,n)=>s=>`[48;2;${e};${t};${n}m${s}[49m`,T=e=>`[1m${e}[22m`,E=e=>`[3m${e}[23m`,A=e=>`[4m${e}[24m`,M=e=>`[9m${e}[29m`,R={emerald:I(16,185,129),zinc200:I(228,228,231),zinc400:I(161,161,170),zinc600:I(82,82,91),zinc800:I(39,39,42),red:I(239,68,68),amber:I(245,158,11),white:I(255,255,255),bgZinc900:P(24,24,27),bgZinc800:P(39,39,42)}},72768:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.announcementsCommand=async function(e){const t=await(0,s.getExchangeAnnouncements)();if(e.json)return void console.log(JSON.stringify(t,null,2));if(0===t.length)return void console.log(`${o.c.dim}No announcements.${o.c.reset}`);console.log(`${o.c.bold}${o.c.cyan}Exchange Announcements${o.c.reset}`),console.log(`${o.c.dim}${"─".repeat(70)}${o.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(` ${o.c.dim}${t}${o.c.reset} ${n} ${e.title||e.message||""}`),e.body){const t=String(e.body).slice(0,120);console.log(` ${o.c.dim}${t}${o.c.reset}`)}}console.log(`\n${o.c.dim}${t.length} announcement(s)${o.c.reset}`)};const s=n(96139),o=n(99236)},71783:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.augmentCommand=async function(e,t){const n=new s.SFClient(t.apiKey,t.apiUrl);console.log(`[2m${t.dryRun?"Previewing":"Running"} tree augmentation for ${e.slice(0,8)}...[22m`);const o=await n.augmentTree(e,t.dryRun);if(t.json)return void console.log(JSON.stringify(o,null,2));console.log(),o.warning&&(console.log(` [33m⚠ ${o.warning}[39m`),console.log());if(o.suggestedNodes?.length>0){console.log(` [1mSuggested Nodes[22m (${o.suggestedNodes.length} from evaluations)`);for(const e of o.suggestedNodes)console.log(` • ${e.label} [2m(parent: ${e.parentNodeId}, est: ${Math.round(100*e.estimatedProbability)}%, seen ${e.frequency}x)[22m`);console.log()}if(o.acceptedNodes?.length>0){console.log(` [1m[32mAccepted Nodes[39m[22m (${o.acceptedNodes.length})`);for(const e of o.acceptedNodes)console.log(` [32m+[39m ${e.id}: ${e.label} [2m(prob: ${Math.round(100*e.probability)}%, imp: ${e.importance})[22m`);if(console.log(),Object.keys(o.updatedImportanceWeights||{}).length>0){console.log(" [1mRebalanced Weights[22m");for(const[e,t]of Object.entries(o.updatedImportanceWeights))console.log(` ${e} → ${t}`);console.log()}o.applied?console.log(" [32m✓ Applied to causal tree[39m"):t.dryRun&&console.log(" [2mDry run — use without --dry-run to apply[22m")}else console.log(" No nodes accepted.");console.log()};const s=n(19218)},44040:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.balanceCommand=async function(e){const t=await(0,s.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(`${o.c.bold}${o.c.cyan}Kalshi Account${o.c.reset}`),console.log(` Balance: $${t.balance.toFixed(2)}`),console.log(` Portfolio Value: $${t.portfolioValue.toFixed(2)}`)};const s=n(96139),o=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 s of e)for(const e of(s.markets||[]).slice(0,5)){if(!e.active||e.closed||!e.clobTokenIds)continue;const o=(0,i.parseClobTokenIds)(e.clobTokenIds);if(!o)continue;const r=await(0,i.polymarketGetOrderbookWithDepth)(o[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?`${s.title}: ${e.groupItemTitle}`:e.question||s.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:o[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,s.kalshiFetchMarket)(i),c=await(0,o.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,o.isKalshiConfigured)())try{const e=Math.floor(Date.now()/1e3),t=e-604800,n=await(0,o.getBatchCandlesticks)({tickers:[i],startTs:t,endTs:e,periodInterval:1440}),s=n.find(e=>e.market_ticker===i)||n[0],r=s?.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,s=e>=0?`+${e}`:`${e}`;w.sparkline=`prev ${Math.round(t)}¢ → now ${w.lastPrice}¢ ${n}${s}${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],s=e.askLevels[n],o=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=s?`${r.c.red}${(0,r.rpad)(`${s.price}¢`,5)}${r.c.reset} ${(0,r.rpad)(String(s.size),8)}`:"";console.log(` ${o} ${i}`)}console.log(` ${r.c.dim}depth: ${e.bidDepth} bid / ${e.askDepth} ask${r.c.reset}`)}console.log()}};const s=n(19218),o=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,s=e.map(e=>"▁▂▃▄▅▆▇█"[Math.round((e-t)/n*7)]).join(""),o=Math.round(e[0]),i=Math.round(e[e.length-1]),a=i-o;return`${s} ${o}¢→${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,o.requireTrading)(),t.all){const e=await(0,s.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,s.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,s.cancelOrder)(e),console.log(`\n ${i.c.green}✓${i.c.reset} Order ${e} cancelled.\n`)};const s=n(96139),o=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 s=n.scannedAt?(0,i.shortDate)(n.scannedAt):"no scan yet",o=n.meta||{};console.log(),console.log(`${i.c.bold}Markets${i.c.reset} ${i.c.dim}${o.totalMarkets||0} markets (K:${o.kalshiMarkets||0} P:${o.polymarketMarkets||0}) · scan: ${s}${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,s=t>0?"+":"";return`${i.c.bold}${e.symbol}${i.c.reset} ${e.price} ${n}${s}${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,s=n>0?i.c.green:n<0?i.c.red:i.c.dim,o=0!==n?`${s}${n>0?"+":""}${n}¢${i.c.reset}`:"";console.log(` ${t} ${(0,i.rpad)(`${e.price}¢`,5)} ${(0,i.rpad)(o,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 s=e.mostLiquid||[];if(s.length>0)for(const e of s){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}`,s=c(e.evaluatedAt);console.log(` ${(0,i.rpad)(s,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 s.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):"-",s=e.label||e.id;console.log(`${t}${i.c.cyan}${e.id}${i.c.reset} ${(0,i.pad)(s,40)} ${(0,i.rpad)(n,5)}`)}}let m=null;if((0,o.isKalshiConfigured)())try{m=await(0,o.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,s=t.marketPrice??t.currentPrice??0,o=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)(o,35)} ${(0,i.rpad)(s.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 s=n(19218),o=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 s=Math.round(n/60);return s<24?`${s}h`:`${Math.round(s/24)}d`}},46222:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createCommand=async function(e,t){const n=new s.SFClient(t.apiKey,t.apiUrl),i=!t.async;t.json||(i?console.log(`${o.c.dim}Creating thesis (sync mode — waiting for formation)...${o.c.reset}`):console.log(`${o.c.dim}Creating thesis (async mode)...${o.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(`${o.c.red}✗${o.c.reset} Thesis creation returned no ID.`),console.error(`${o.c.dim}Response: ${JSON.stringify(r).slice(0,200)}${o.c.reset}`),process.exit(1));console.log(`\n${o.c.green}✓${o.c.reset} Thesis created`),console.log(` ${o.c.bold}ID:${o.c.reset} ${a}`),console.log(` ${o.c.bold}Status:${o.c.reset} ${r.thesis?.status||r.status}`),r.thesis?.confidence&&console.log(` ${o.c.bold}Confidence:${o.c.reset} ${Math.round(100*parseFloat(r.thesis.confidence))}%`);r.thesis?.causalTree?.nodes&&console.log(` ${o.c.bold}Nodes:${o.c.reset} ${r.thesis.causalTree.nodes.length}`);r.thesis?.edgeAnalysis?.edges&&console.log(` ${o.c.bold}Edges:${o.c.reset} ${r.thesis.edgeAnalysis.edges.length}`);console.log(`\n${o.c.dim}View: sf get ${(0,o.shortId)(a)}${o.c.reset}`),console.log(`${o.c.dim}Context: sf context ${(0,o.shortId)(a)}${o.c.reset}`)};const s=n(19218),o=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 s.SFClient(e?.apiKey,e?.apiUrl),[n,a]=await Promise.all([t.listTheses(),(0,o.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,o.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,o.getOrders)({status:"resting"}).catch(()=>[]):Promise.resolve([]),e?.json?(0,o.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,o.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],s=t.id.slice(0,8),o=(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(` ${s} ${o} ${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 s=(n.ticker||"").padEnd(22),o=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(` ${s} ${o} @ ${i.padEnd(5)} now ${r.padEnd(5)} ${l}`)}console.log(" "+"─".repeat(45));const n=(e/100).toFixed(0),s=(t/100).toFixed(2),o=t>=0?`+$${s}`:`-$${Math.abs(parseFloat(s)).toFixed(2)}`;console.log(` Total cost: $${n} | P&L: ${o}`)}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||""),s=e.get(n)||{cost:0,contracts:0,tickers:[]},o=(t.average_price_paid||0)*(t.quantity||0);s.cost+=o,s.contracts+=t.quantity||0,s.tickers.includes(t.ticker)||s.tickers.push(t.ticker),e.set(n,s)}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)}`,s=n.tickers.length<=2?` (${n.tickers.join("+")})`:` (${n.tickers.length} markets)`;console.log(` ${(e+s+":").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}¢`,s=`${e.thesisPrice}¢`,o=e.edge>0?`+${e.edge}`:`${e.edge}`,i=e.orderbook?.liquidityScore||"?";console.log(` ${t} ${n.padStart(5)} → ${s.padStart(5)} edge ${o.padStart(4)} ${i}`)}console.log()}};const s=n(19218),o=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 s=Math.floor(n/60);if(s<24)return`${s}h ago`;return`${Math.floor(s/24)}d ago`}},81466:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deltaCommand=async function(e,t){const n=new s.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 s=i.toISOString(),r=await n.getChanges(e,s);if(t.json)return void console.log(JSON.stringify(r,null,2));if(!r.changed)return void console.log(`${o.c.dim}No changes since ${i.toLocaleString()}.${o.c.reset}`);const a=(0,o.shortId)(e);if(console.log(),console.log(`${o.c.bold}${o.c.cyan}Delta: ${a}${o.c.reset}${o.c.dim} — since ${i.toLocaleString()}${o.c.reset}`),console.log(`${o.c.dim}${"─".repeat(65)}${o.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 s="";null!==n&&(s=n>0?`${o.c.green} (+${n}%)${o.c.reset}`:n<0?`${o.c.red} (${n}%)${o.c.reset}`:`${o.c.dim} (0%)${o.c.reset}`),console.log(` Confidence: ${o.c.bold}${e}%${o.c.reset}${s}`)}r.evaluationCount&&console.log(` Evaluations: ${r.evaluationCount} cycle(s)`);const c=r.updatedNodes||[];if(c.length>0){console.log(),console.log(` ${o.c.bold}Node Changes (${c.length}):${o.c.reset}`);for(const e of c){const t=Math.round(100*(e.newProbability??e.newProb??0)),n=e.previousProbability??e.prevProb;let s="";if(null!=n){const e=t-Math.round(100*n);s=e>0?` ${o.c.green}+${e}%${o.c.reset}`:e<0?` ${o.c.red}${e}%${o.c.reset}`:""}const i=e.label||e.nodeId||"?";console.log(` ${i.slice(0,40).padEnd(40)} ${t}%${s}`)}}const l=r.newSignals||[];if(l.length>0){console.log(),console.log(` ${o.c.bold}New Signals (${l.length}):${o.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(` ${o.c.dim}[${t}]${o.c.reset} ${n}`)}}const d=r.edgeChanges||r.edges||[];if(d.length>0){console.log(),console.log(` ${o.c.bold}Edge Movements (${d.length}):${o.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,s=e.previousEdge??null,i=n>0?`+${n}`:`${n}`;let r="";if(null!==s){const e=n-s;r=e>0?` ${o.c.green}(+${e})${o.c.reset}`:e<0?` ${o.c.red}(${e})${o.c.reset}`:""}const a=n>0?o.c.green:n<0?o.c.red:o.c.dim;console.log(` ${t} ${a}${i}${o.c.reset}${r}`)}}console.log(`${o.c.dim}${"─".repeat(65)}${o.c.reset}`),console.log()};if(t.watch)for(console.log(`${o.c.dim}Watching for changes every 60s... (Ctrl+C to stop)${o.c.reset}`);;)await r(),await new Promise(e=>setTimeout(e,6e4)),console.clear();else await r()};const s=n(19218),o=n(99236)},91262:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.edgesCommand=async function(e){const t=new s.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,o.isKalshiConfigured)()&&(p(`${i.c.dim}Fetching Kalshi positions...${i.c.reset}`),$=await(0,o.getPositions)(),$)){for(const e of $){const t=await(0,o.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,s=null!==t.executableEdge?t.executableEdge:t.edge;return Math.abs(s)-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}¢`,s=`${e.thesisPrice}¢`,o=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)(s,7),`${d}${(0,i.rpad)(o,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)}`,s=`${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: ${s}`)}const S=w.filter(e=>!e.position&&e.edge>0);if(S.length>0){const e=S[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 s=n(19218),o=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 s.SFClient(t.apiKey,t.apiUrl);console.log(`${o.c.dim}Triggering deep evaluation (heavy model)...${o.c.reset}`);const i=await n.evaluate(e);if(console.log(`\n${o.c.green}✓${o.c.reset} Evaluation complete`),i.evaluation){const e=i.evaluation;if(void 0!==e.confidenceDelta){const t=e.confidenceDelta,n=t>0?o.c.green:t<0?o.c.red:o.c.dim;console.log(` ${o.c.bold}Confidence:${o.c.reset} ${(0,o.pct)(e.previousConfidence)} → ${(0,o.pct)(e.newConfidence)} ${n}(${(0,o.delta)(t)})${o.c.reset}`)}if(e.summary&&console.log(`\n ${e.summary}`),e.positionUpdates&&e.positionUpdates.length>0){console.log(`\n ${o.c.bold}Position Recommendations:${o.c.reset}`);for(const t of e.positionUpdates){const e="hold"===t.recommendation?o.c.dim:"close"===t.recommendation?o.c.red:o.c.yellow;console.log(` [${t.positionId.slice(0,8)}] ${e}${t.recommendation}${o.c.reset} — ${t.reason}`)}}}console.log("")};const s=n(19218),o=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,s.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(` ${o.c.dim}No public theses yet. Publish yours: sf publish <id>${o.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 s=n(35178),o=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 s.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(`${o.c.dim}No evaluations in the last ${n} hours.${o.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(`${o.c.dim}No evaluations for ${e.thesis} in the last ${n} hours.${o.c.reset}`);if(e.json)return void console.log(JSON.stringify(r,null,2));console.log(),console.log(`${o.c.bold}${o.c.cyan}Evaluation Feed${o.c.reset}${o.c.dim} — last ${n}h, ${r.length} cycles${o.c.reset}`),console.log(`${o.c.dim}${"─".repeat(75)}${o.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),s=Math.round(100*e.delta);let i;i=s>0?`${o.c.green}+${s}%${o.c.reset}`:s<0?`${o.c.red}${s}%${o.c.reset}`:`${o.c.dim}0%${o.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(`${o.c.dim}[${t}]${o.c.reset} ${o.c.cyan}${r}${o.c.reset} ${n}% (${i}) ${o.c.dim}${a}${o.c.reset}`),l&&console.log(`${" ".repeat(9)} ${o.c.dim}nodes: ${l}${o.c.reset}`)}console.log(`${o.c.dim}${"─".repeat(75)}${o.c.reset}`),console.log()};const s=n(19218),o=n(99236)},63746:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fillsCommand=async function(e){const t=await(0,s.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(`${o.c.dim}No fills.${o.c.reset}`);console.log(`${o.c.bold}${o.c.cyan}Recent Fills${o.c.reset}`),console.log(`${o.c.dim}${"─".repeat(80)}${o.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?`${o.c.green}YES${o.c.reset}`:`${o.c.red}NO${o.c.reset}`,s=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)} ${s.padEnd(5)} ${n} ${t.padEnd(8)} x${i} ${o.c.dim}${r}${o.c.reset}`)}console.log(`\n${o.c.dim}${t.fills.length} fill(s)${o.c.reset}`)};const s=n(96139),o=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,s.getForecastHistory)({seriesTicker:c,eventTicker:e,percentiles:[5e3,7500,9e3],startTs:u,endTs:d,periodInterval:1440});if(!p||0===p.length)return void console.log(`${o.c.dim}No forecast data for ${e}${o.c.reset}`);if(t.json)return void console.log(JSON.stringify(p,null,2));console.log(`${o.c.bold}${o.c.cyan}Forecast: ${a.event?.title||e}${o.c.reset}`),console.log(`${o.c.dim}Series: ${c} | ${n} days${o.c.reset}`),console.log(),console.log(`${o.c.bold}${"Date".padEnd(14)} ${"P50".padEnd(12)} ${"P75".padEnd(12)} P90${o.c.reset}`),console.log(`${o.c.dim}${"─".repeat(52)}${o.c.reset}`);for(const e of p){const t=new Date(1e3*e.end_period_ts).toISOString().slice(0,10),n=e.percentile_points||[],s=n.find(e=>5e3===e.percentile)?.formatted_forecast||"-",o=n.find(e=>7500===e.percentile)?.formatted_forecast||"-",i=n.find(e=>9e3===e.percentile)?.formatted_forecast||"-";console.log(` ${t.padEnd(14)} ${s.padEnd(12)} ${o.padEnd(12)} ${i}`)}};const s=n(96139),o=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 s.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,o.header)(`Thesis: ${(a.id||e).slice(0,8)}`),(0,o.hr)(),console.log(`${o.c.bold}Status:${o.c.reset} ${a.status||"-"}`);const l=a.confidence?(0,o.pct)(parseFloat(a.confidence)):"-";console.log(`${o.c.bold}Confidence:${o.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(`${o.c.bold}Created:${o.c.reset} ${(0,o.shortDate)(d)}`),console.log(`${o.c.bold}Updated:${o.c.reset} ${(0,o.shortDate)(u)}`),a.title&&console.log(`${o.c.bold}Title:${o.c.reset} ${a.title}`);console.log(`${o.c.bold}Thesis:${o.c.reset} ${a.rawThesis||"-"}`),a.webhookUrl&&console.log(`${o.c.bold}Webhook:${o.c.reset} ${a.webhookUrl}`);const p=a.causalTree;p&&p.nodes&&((0,o.header)("Causal Tree"),i(p.nodes,0));const h=a.edgeAnalysis;if(h&&h.edges){(0,o.header)("Edge Analysis"),console.log(`${o.c.dim}Analyzed: ${(0,o.shortDate)(h.analyzedAt)}${o.c.reset}`),h.lastRescanAt&&console.log(`${o.c.dim}Last rescan: ${(0,o.shortDate)(h.lastRescanAt)}${o.c.reset}`);for(const e of h.edges){const t=e.edgeSize??0,n=t>10?o.c.green:t>0?o.c.yellow:o.c.red;console.log(` ${e.marketTitle||e.marketId} ${o.c.dim}${e.venue}${o.c.reset} price: ${(e.marketPrice??0).toFixed(0)}¢ ${n}edge: ${t>0?"+":""}${t.toFixed(1)}${o.c.reset}`)}}if(c.length>0){(0,o.header)("Positions");for(const e of c){if(!e)continue;const t="open"===e.status?o.c.green+"●":o.c.dim+"○";console.log(` ${t}${o.c.reset} [${(e.id||"?").slice(0,8)}] "${e.marketTitle||"?"}" ${e.direction||"?"}@${e.entryPrice||"?"}→${e.currentPrice||e.entryPrice||"?"} ${o.c.dim}(${e.venue||"?"})${o.c.reset}`)}}const m=a.lastEvaluation;if(m){(0,o.header)("Last Evaluation");const e=m.evaluatedAt instanceof Date?m.evaluatedAt.toISOString():m.evaluatedAt;if(console.log(`${o.c.dim}${(0,o.shortDate)(e)} | model: ${m.model||"-"}${o.c.reset}`),void 0!==m.confidenceDelta){const e=m.confidenceDelta,t=e>0?o.c.green:e<0?o.c.red:o.c.dim;console.log(`Confidence: ${(0,o.pct)(m.previousConfidence)} → ${(0,o.pct)(m.newConfidence)} ${t}(${(0,o.delta)(e)})${o.c.reset}`)}m.summary&&console.log(`\n${m.summary}`)}console.log("")};const s=n(19218),o=n(99236);function i(e,t){for(const n of e){if(!n)continue;const e=" ".repeat(t+1),s=void 0!==n.probability?(0,o.pct)(n.probability):"-",r=void 0!==n.importance?` imp:${n.importance}`:"";console.log(`${e}${o.c.cyan}${n.id}${o.c.reset} ${n.label} ${o.c.dim}(${s}${r})${o.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 o=n.newsInterval||n.xInterval||n.model||void 0!==n.budget||n.pause||n.resume;if(o){const o={};n.newsInterval&&(o.newsIntervalMin=parseInt(n.newsInterval,10)),n.xInterval&&(o.xIntervalMin=parseInt(n.xInterval,10)),n.model&&(o.evalModelTier=n.model),void 0!==n.budget&&(o.monthlyBudgetUsd=parseFloat(n.budget)),n.pause&&(o.paused=!0),n.resume&&(o.paused=!1);try{const n=await e.updateHeartbeatConfig(t,o);console.log(`\n ${s.c.green}✓${s.c.reset} Updated heartbeat config`),console.log(` ${s.c.dim}Updated fields: ${n.updated.join(", ")}${s.c.reset}\n`)}catch(e){return void console.error(` ${s.c.red}✗ ${e.message}${s.c.reset}`)}}try{const n=await e.getHeartbeatConfig(t),o=n.config,i=n.costs;console.log(`\n ${s.c.bold}Heartbeat Config${s.c.reset} ${s.c.dim}(${t.slice(0,8)})${s.c.reset}`),console.log();const r=o.paused?`${s.c.red}⏸ paused${s.c.reset}`:`${s.c.green}▶ active${s.c.reset}`;if(console.log(` Status ${r}`),console.log(` News interval ${s.c.cyan}${o.newsIntervalMin}${s.c.reset} min ${s.c.dim}(${o.newsIntervalMin===n.defaults.newsIntervalMin?"default":"custom"})${s.c.reset}`),console.log(` X interval ${s.c.cyan}${o.xIntervalMin}${s.c.reset} min ${s.c.dim}(${o.xIntervalMin===n.defaults.xIntervalMin?"default":"custom"})${s.c.reset}`),console.log(` Eval model ${s.c.cyan}${o.evalModelTier}${s.c.reset} ${s.c.dim}(${o.evalModelTier===n.defaults.evalModelTier?"default":"custom"})${s.c.reset}`),console.log(" Monthly budget "+(o.monthlyBudgetUsd>0?`${s.c.cyan}$${o.monthlyBudgetUsd}${s.c.reset}`:`${s.c.dim}unlimited${s.c.reset}`)),console.log(),console.log(` ${s.c.bold}This Month${s.c.reset}`),console.log(` Total cost ${s.c.cyan}$${i.monthlyTotal.toFixed(4)}${s.c.reset}`),console.log(` LLM calls ${i.llmCalls}`),console.log(` Search calls ${i.searchCalls}`),console.log(` Tokens ${s.c.dim}${i.inputTokens.toLocaleString()} in / ${i.outputTokens.toLocaleString()} out${s.c.reset}`),null!==i.budgetRemaining){const e=o.monthlyBudgetUsd>0?Math.round(i.monthlyTotal/o.monthlyBudgetUsd*100):0;console.log(` Budget used ${e}% ${s.c.dim}($${i.budgetRemaining.toFixed(2)} remaining)${s.c.reset}`)}console.log()}catch(e){console.error(` ${s.c.red}✗ ${e.message}${s.c.reset}`)}};const s=n(99236)},9708:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.historyCommand=async function(e,t){const n=await(0,s.getHistoricalMarket)(e);if(!n)return void console.log(`${o.c.dim}No historical data for ${e}${o.c.reset}`);if(t.json)return void console.log(JSON.stringify(n,null,2));console.log(`${o.c.bold}${o.c.cyan}${n.title||e}${o.c.reset}`),console.log(`${o.c.dim}${"─".repeat(60)}${o.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 s=n(96139),o=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 o=await fetch(`${t}/api/public/ideas?${n.toString()}`);o.ok||(console.error(`\n ${s.c.red}Error:${s.c.reset} API returned ${o.status}\n`),process.exit(1));const i=await o.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 ${s.c.dim}No trade ideas available.${s.c.reset}\n`);console.log(),console.log(` ${s.c.bold}Trade Ideas${s.c.reset} ${s.c.dim}${r.length} ideas${s.c.reset}`),console.log();for(const e of r){const t="long"===e.direction?s.c.green+"▲ LONG"+s.c.reset:s.c.red+"▼ SHORT"+s.c.reset,n="●".repeat(Math.min(e.conviction||3,5));if(console.log(` ${t} ${e.headline}`),console.log(` ${s.c.dim}Conviction: ${n} Category: ${e.category||"-"} Horizon: ${e.timeHorizon||"-"}${s.c.reset}`),console.log(` ${e.pitch||""}`),e.catalyst&&console.log(` ${s.c.dim}Catalyst: ${e.catalyst}${s.c.reset}`),e.risk&&console.log(` ${s.c.dim}Risk: ${e.risk}${s.c.reset}`),e.markets?.length){const t=e.markets.map(e=>`${e.ticker||e.marketId} ${e.currentPrice?e.currentPrice+"¢":""}`).join(", ");console.log(` ${s.c.dim}Markets: ${t}${s.c.reset}`)}console.log()}};const s=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 s.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,o.emptyState)("intents","Create one: sf intent buy TICKER QTY --price CENTS");console.log(`\n ${o.c.bold}INTENTS${o.c.reset} (${i.length})\n`);for(const e of i)console.log(r(e)),console.log()}catch(e){console.error(`${o.c.red}Error:${o.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 s.SFClient,{intent:i}=await n.getIntentDetail(e);if(t.json)return void console.log(JSON.stringify(i,null,2));if(console.log(`\n ${o.c.bold}Intent ${i.id.slice(0,8)}${o.c.reset}\n`),console.log(r(i)),console.log(),i.fills&&i.fills.length>0){console.log(` ${o.c.bold}Fills${o.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)}) ${o.c.dim}order: ${e.orderId||"?"}${o.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(`${o.c.red}Error:${o.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 s.SFClient;await t.cancelIntentAPI(e),console.log(`\n ${o.c.green}OK${o.c.reset} Intent ${e} cancelled.\n`)}catch(e){console.error(`${o.c.red}Error:${o.c.reset} ${e.message}`),process.exit(1)}})};const s=n(19218),o=n(99236),i={pending:"[33m",armed:"[36m",triggered:"[35m",executing:"[34m",filled:"[32m",partial:"[33m",expired:"[90m",cancelled:"[90m",rejected:"[31m"};function r(e){const t=i[e.status]||"",n=[],s=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}]${o.c.reset} ${o.c.bold}${s}${o.c.reset} ${e.marketId} ${r} ${e.targetQuantity}${a} ${o.c.dim}${c}${o.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(` ${o.c.dim}expires ${l} · source: ${e.source}${e.rationale?` · "${e.rationale.slice(0,60)}"`:""}${o.c.reset}`),n.join("\n")}async function a(e,t,n,i){try{const r=new s.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(` ${o.c.green}OK${o.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(` ${o.c.dim}Start runtime to execute: sf runtime start${o.c.reset}`),console.log()}catch(e){console.error(`${o.c.red}Error:${o.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,o.isKalshiConfigured)())try{const e=await(0,o.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,s.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 s=c(t);f&&s!==f||y.push({ticker:n.ticker,closeTime:t,topic:e,horizon:s,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,o.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:s}=t,o=s.yes_dollars.map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0),i=s.no_dollars.map(([e,t])=>({price:Math.round(100*parseFloat(e)),qty:parseFloat(t)})).filter(e=>e.price>0);o.sort((e,t)=>t.price-e.price),i.sort((e,t)=>t.price-e.price);const r=o.length>0?o[0].price:0,a=i.length>0?100-i[0].price:100,c=a-r,l=o.reduce((e,t)=>e+t.qty,0),u=i.reduce((e,t)=>e+t.qty,0),p=d(s.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:s}=t;e.minDepth&&s.bidDepthTop3+s.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:s.bestBid,bestAsk:s.bestAsk,spread:s.spread,bidDepth:s.totalBidDepth,askDepth:s.totalAskDepth,slippage100:"-",held:!1,venue:"polymarket"})}if(e.json)return void console.log(JSON.stringify(v,null,2));const S=(new Date).toISOString().slice(0,10);console.log(),console.log(`${a.c.bold}Liquidity Scanner${a.c.reset} ${a.c.dim}(${S} UTC)${a.c.reset}`),console.log(a.c.dim+"─".repeat(68)+a.c.reset);const _={};for(const e of v){const t=e.topic||"OTHER";_[t]||(_[t]={}),_[t][e.horizon]||(_[t][e.horizon]=[]),_[t][e.horizon].push(e)}let x=0,O=0,C=0;const I=["weekly","monthly","long-term"];for(const[e,t]of Object.entries(_))for(const n of I){const s=t[n];if(!s||0===s.length)continue;const o=s.filter(e=>"kalshi"===e.venue);if(o.length>1){const e=p(o.map(e=>e.ticker));for(const t of o){const n=e.length>0?t.ticker.slice(e.length).replace(/^-/,""):t.ticker;t.shortTicker=n.length>0?n:t.ticker}}s.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 s){x++,e.held&&C++;const t=e.spread>5;let n;t&&O++,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 s=t?" ⚠️":"",o=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)}${s}${o}`)}}console.log(),console.log(`${a.c.dim}Summary: ${x} markets | ${O} thin (spread>5¢) | ${C} held${a.c.reset}`),console.log()};const s=n(19218),o=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 s=t,o=0;for(const e of n){if(s<=0)break;const t=Math.min(s,e.qty);o+=t*e.yesAsk,s-=t}if(s>0)return"∞";return(100*(o/t)).toFixed(1)+"¢"}async function u(e,t,n,s){const o=[];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)o.push("fulfilled"===e.status?e.value:null);i+n<e.length&&await new Promise(e=>setTimeout(e,s))}return o}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 s.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,o.emptyState)("theses",'Create one: sf create "your market thesis"');console.log(`\n${o.c.bold}`+(0,o.pad)("ID",12)+(0,o.pad)("Status",10)+(0,o.rpad)("Conf",6)+" "+(0,o.pad)("Updated",14)+" Title"+o.c.reset),(0,o.hr)(90);for(const e of n){const t="active"===e.status?o.c.green:"forming"===e.status?o.c.yellow:o.c.dim,n=e.confidence?(0,o.pct)(parseFloat(e.confidence)):"-";console.log((0,o.pad)((0,o.shortId)(e.id),12)+t+(0,o.pad)(e.status,10)+o.c.reset+(0,o.rpad)(n,6)+" "+o.c.dim+(0,o.pad)((0,o.shortDate)(e.updatedAt),14)+o.c.reset+" "+(0,o.trunc)(e.title||e.rawThesis.slice(0,60),50))}console.log(`\n${o.c.dim}${n.length} thesis(es)${o.c.reset}`)};const s=n(19218),o=n(99236)},50869:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.loginCommand=async function(e){const t=e.apiUrl||(0,o.loadConfig)().apiUrl||r,a=(0,o.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,s.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,o.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 s=n(76982),o=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(`${o}/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,s.shareOutput)("markets","",n);if(e?.json)return void console.log(JSON.stringify(n,null,2));if(console.log(`\n [1mTraditional Markets[22m [2m${n.snapshotAt?.slice(0,10)||""}[22m\n`),!n.markets?.length)return void console.log(" No data available.\n");for(const e of n.markets){const t=e.changePct>=0?"[32m▲[39m":"[31m▼[39m",n=e.changePct>=0?`[32m+${e.changePct}%[39m`:`[31m${e.changePct}%[39m`,s=`$${e.price.toFixed(2)}`;console.log(` ${t} ${e.symbol.padEnd(5)} ${s.padStart(10)} ${n.padStart(16)} ${e.name}`)}console.log()};const s=n(35178),o="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 s.SFClient(e.apiKey,e.apiUrl),n=await t.getContext(e.thesis),o=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=>o.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(`${o.c.dim}No milestones in the next ${t} hours.${o.c.reset}`);l.sort((e,t)=>new Date(e.start_date).getTime()-new Date(t.start_date).getTime()),console.log(`${o.c.bold}${o.c.cyan}Upcoming Milestones (next ${t}h)${o.c.reset}`),console.log(`${o.c.dim}${"─".repeat(80)}${o.c.reset}`);for(const e of l){const t=new Date(e.start_date),s=Math.round((t.getTime()-n.getTime())/36e5),i=s<=24?`${o.c.bold}${s}h${o.c.reset}`:`${o.c.dim}${Math.round(s/24)}d${o.c.reset}`,r=`${o.c.dim}[${e.category}]${o.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)} ${o.c.dim}${a}${o.c.reset}`)}console.log(`\n${o.c.dim}${l.length} milestone(s)${o.c.reset}`)};const s=n(19218),o=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,s.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(`${o.c.dim}No ${t} orders.${o.c.reset}`);console.log(`${o.c.bold}${o.c.cyan}Orders (${t})${o.c.reset}`),console.log(`${o.c.dim}${"─".repeat(80)}${o.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?`${o.c.green}YES${o.c.reset}`:`${o.c.red}NO${o.c.reset}`,s=e.remaining_count_fp||e.remaining_count||"?";console.log(` ${(e.ticker||"").padEnd(35)} ${n} ${t.padEnd(8)} qty ${s}`)}console.log(`\n${o.c.dim}${n.orders.length} order(s)${o.c.reset}`)};const s=n(96139),o=n(99236)},33766:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.performanceCommand=async function(e){if(!(0,o.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,o.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 s=e.action||"buy",o=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"===s&&(a=-a),"no"===o&&(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"===o?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,o.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"),s=parseFloat(n.yes_ask?.close_dollars||"0"),o=e>0&&s>0?(e+s)/2:e||s,i=parseFloat(n.price?.close_dollars||"0")||o,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 s.SFClient(e.apiKey,e.apiUrl),n=await t.getFeed(720),o=n?.feed||n?.items||n||[];if(Array.isArray(o))for(const e of o){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)||[],s=n.length>0?n[n.length-1].close:t,o=(s-t)*e.netQty,i=t*e.netQty,r=0!==i?o/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:s,pnlCents:o,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 s=g.get(n.ticker)||[],o=$.get(n.ticker)||0,i=s.find(t=>t.date===e);i&&(t+=(i.close-o)*n.netQty)}return t}),v=u.reduce((e,t)=>e+t.totalCostCents,0),S=k.reduce((e,t)=>e+t.pnlCents,0),_=v>0?S/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:S,pnlPct:Math.round(10*_)/10}},null,2));const x=y.length>0?a(new Date(y[0])):"?",O=a(new Date);console.log(),console.log(` ${r.c.bold}Portfolio Performance${r.c.reset} ${r.c.dim}(${x} → ${O})${r.c.reset}`),console.log(` ${r.c.dim}${"─".repeat(76)}${r.c.reset}`),console.log();const C=Math.max(...k.map(e=>e.ticker.length),5)+2,I=C+50,P=(e,t)=>e.padEnd(t);console.log(` ${r.c.dim}${P("Ticker",C)} 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,s=d(e.dailyPnl,e=>e>=0?r.c.green:r.c.red);console.log(` ${P(e.ticker,C)} ${(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}`+s)}console.log(` ${r.c.dim}${"─".repeat(I)}${r.c.reset}`);const T=c(S),E=`${_>=0?"+":""}${_.toFixed(1)}%`,A=S>=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",C)}${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 s=n(19218),o=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),s=Math.max(...e)-n||1,o=["▁","▂","▃","▄","▅","▆","▇","█"];return e.map(e=>{const i=Math.round((e-n)/s*(o.length-1)),a=o[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 s.SFClient(e.apiKey,e.apiUrl);let n=null;(0,o.isKalshiConfigured)()&&(console.log(`${a.c.dim}Fetching Kalshi positions...${a.c.reset}`),n=await(0,o.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,o.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,o.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,s=e.unrealized_pnl||0,o=s>0?a.c.green:s<0?a.c.red:a.c.dim,i=s>=0?`+$${(s/100).toFixed(2)}`:`-$${(Math.abs(s)/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)+`${o}${(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,o.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",s=e.size||0,o=Math.round(100*(e.avgPrice||0)),i=Math.round(100*(e.curPrice||e.currentPrice||0)),r=e.cashPnl||(i-o)*s/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(s)),8)+(0,a.rpad)(`${o}¢`,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,o.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,o.getOrderbook)(e.edge.marketId);t&&n.set(e.edge.marketId,t),await new Promise(e=>setTimeout(e,150))}catch{}}const s=e.thesis?` (thesis ${(0,a.shortId)(e.thesis)})`:"";(0,a.header)(`Unpositioned Edges${s}`),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,s=t.edge??t.edgeSize??0,o=s>10?a.c.green:s>5?a.c.yellow:s>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";(s>10&&"low"!==u?.liquidityScore||s>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)+`${o}${(0,a.rpad)(`${s>0?"+":""}${s.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 s=n(19218),o=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(/\/$/,""),s=t.apiKey||process.env.SF_API_KEY||"",o=new URLSearchParams;t.sections&&o.set("sections",t.sections);t.maxLength&&o.set("maxLength",t.maxLength);t.json&&o.set("format","json");const i=e?`/api/thesis/${e}/prompt`:"/api/prompt",r=o.toString()?`?${o.toString()}`:"",a=await fetch(`${n}${i}${r}`,{headers:{Authorization:`Bearer ${s}`}});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 o=new s.SFClient(t.apiKey,t.apiUrl);await o.publish(e,n,t.description),console.log(`\n ✓ Published: https://simplefunctions.dev/thesis/${n}\n`)},t.unpublishCommand=async function(e,t){const n=new s.SFClient(t.apiKey,t.apiUrl);await n.unpublish(e),console.log(`\n ✓ Unpublished thesis ${e}\n`)};const s=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=`${o}/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,s.shareOutput)("query",e,l);if(t?.json)return void console.log(JSON.stringify(l,null,2));console.log(),console.log(` [1m${l.query}[22m`),console.log(),l.answer&&(console.log(` ${l.answer}`),console.log());if(l.keyFactors?.length>0){console.log(" [2mKey factors:[22m");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(" [1mMarkets[22m");for(const e of d.slice(0,8)){const t=i(e.volume),n=e.ticker?` [2m${e.ticker}[22m`:"";console.log(` [36mK[39m ${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?` [2m${e.slug}[22m`:"";console.log(` [35mP[39m ${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(" [1mX signals[22m");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(" [1mTraditional[22m");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(" [1mTheses[22m");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(" [1mContent[22m");for(const e of l.content.slice(0,5)){const t=e.type.padEnd(9);console.log(` [2m${t}[22m ${e.title.slice(0,50)} [2m${e.url}[22m`)}console.log()}const m=l.meta||{},g=m.sources||l.sources||[],f=m.latencyMs?`${(m.latencyMs/1e3).toFixed(1)}s`:"";console.log(` [2mSources: ${g.join(", ")}${f?` (${f})`:""}[22m`),console.log()};const s=n(35178),o=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,o.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,s.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 s=n(96139),o=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").option("--smart","Enable LLM intelligence layer").description("Start the execution runtime").action(async e=>{if((0,i.isKalshiConfigured)()||(console.error(`\n ${a.c.red}Error:${a.c.reset} Kalshi credentials not configured.`),console.error(" Run: sf setup --enable-trading\n"),process.exit(1)),(0,c.existsSync)(u)){const e=(0,c.readFileSync)(u,"utf-8").trim();try{process.kill(parseInt(e),0),console.error(`\n ${a.c.yellow}Warning:${a.c.reset} Runtime already running (PID ${e}).`),console.error(" Stop it first: sf runtime stop\n"),process.exit(1)}catch{(0,c.unlinkSync)(u)}}if(e.daemon){const t=process.argv[1];(0,c.mkdirSync)((0,l.join)((0,d.homedir)(),".sf"),{recursive:!0});const n=(0,c.openSync)(p,"a"),o=["runtime","start"];e.smart&&o.push("--smart");const i=(0,s.spawn)(process.execPath,[t,...o],{detached:!0,stdio:["ignore",n,n],env:{...process.env}});i.unref();const r=e.smart?` ${a.c.cyan}[smart]${a.c.reset}`:"";return console.log(`\n ${a.c.green}OK${a.c.reset} Runtime started in background${r} (PID ${i.pid})`),console.log(` ${a.c.dim}Log: ${p}${a.c.reset}`),void console.log(` ${a.c.dim}Stop: sf runtime stop${a.c.reset}\n`)}const t=e.smart||(0,r.loadConfig)().smartDaemons||!1;await async function(e=!1){const t=(0,l.join)((0,d.homedir)(),".sf");(0,c.existsSync)(t)||(0,c.mkdirSync)(t,{recursive:!0});f(),(0,c.writeFileSync)(u,process.pid.toString()),console.log(),console.log(` ${a.c.bold}SimpleFunctions Runtime${a.c.reset}${e?` ${a.c.cyan}[smart]${a.c.reset}`:""}`),console.log(` ${a.c.dim}PID ${process.pid} · polling every ${m/1e3}s · Ctrl+C to stop${a.c.reset}`),g.size>0&&console.log(` ${a.c.dim}Loaded ${g.size} previously executed intent(s)${a.c.reset}`);console.log();const s=new o.SFClient;let p=0;process.on("uncaughtException",e=>{b(`Uncaught exception: ${e.message}`)}),process.on("unhandledRejection",e=>{b(`Unhandled rejection: ${e?.message||e}`)});const h=()=>{console.log(`\n ${a.c.dim}Runtime stopping...${a.c.reset}`),y();try{(0,c.unlinkSync)(u)}catch{}process.exit(0)};process.on("SIGINT",h),process.on("SIGTERM",h),process.on("exit",()=>{try{(0,c.unlinkSync)(u)}catch{}});const w=(0,r.loadConfig)().smartScanInterval||10;for(;;){p++;try{const{intents:t}=await s.listIntents({active:!0});if(!t||0===t.length){p%10==1&&b("No active intents. Waiting..."),await v(m);continue}const o=new Map;for(const e of t)if(!o.has(e.marketId)){const t=await(0,i.getMarketPrice)(e.marketId);null!==t&&o.set(e.marketId,t)}for(const n of t)await $(s,n,e);if(e&&p%w===0)try{const{periodicScan:e,evaluateWakeConditions:s}=await n.e(563).then(n.bind(n,9563)),i=await e("runtime",t,o);i&&b(`Smart scan:\n${i}`),await s("runtime",p,o)}catch(e){b(`Smart scan error (non-fatal): ${e.message}`)}if(e&&p%5==0)try{const{readMessages:e,deleteMessage:t}=await n.e(563).then(n.bind(n,9563)),s=e("runtime","inbox");for(const e of s)b(`Agent command: ${e.payload.action||e.payload.summary||"unknown"}`),t(e.id,"inbox")}catch{}}catch(e){b(`Error in cycle: ${e.message}`)}await v(m)}}(t)}),t.command("stop").description("Stop the runtime daemon").action(async()=>{if(!(0,c.existsSync)(u)){const e=k("runtime");if(e.length>0){for(const t of e)try{process.kill(t,"SIGTERM")}catch{}console.log(`\n ${a.c.green}OK${a.c.reset} Stopped ${e.length} orphan runtime process(es): ${e.join(", ")}\n`)}else console.log(`\n ${a.c.dim}No runtime running.${a.c.reset}\n`);return}const e=(0,c.readFileSync)(u,"utf-8").trim();try{process.kill(parseInt(e),"SIGTERM"),(0,c.unlinkSync)(u),console.log(`\n ${a.c.green}OK${a.c.reset} Runtime stopped (PID ${e}).\n`)}catch{(0,c.unlinkSync)(u),console.log(`\n ${a.c.dim}Runtime was not running (stale PID file removed).${a.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="",s=!1;if((0,c.existsSync)(u)){n=(0,c.readFileSync)(u,"utf-8").trim();try{process.kill(parseInt(n),0),t=!0}catch{t=!1}}if(!t){const e=k("runtime");e.length>0&&(t=!0,s=!0,n=e.join(", "))}const i=new o.SFClient,{intents:r}=await i.listIntents({active:!0});if(e.json)return void console.log(JSON.stringify({running:t,pid:t?n:null,intents:r},null,2));console.log();const l=t?s?`${a.c.yellow}RUNNING (orphan)${a.c.reset} PID ${n} — no PID file, use ${a.c.bold}sf runtime stop${a.c.reset} to fix`:`${a.c.green}RUNNING${a.c.reset} (PID ${n})`:`${a.c.dim}STOPPED${a.c.reset}`;if(console.log(` ${a.c.bold}Runtime${a.c.reset} ${l}`),t&&(0,c.existsSync)(p)&&console.log(` ${a.c.dim}Log: ${p}${a.c.reset}`),console.log(),!r||0===r.length)return console.log(` ${a.c.dim}No active intents.${a.c.reset}`),console.log(" Create one: sf intent buy TICKER QTY --price CENTS"),void console.log();const d={};for(const e of r)d[e.status]=(d[e.status]||0)+1;const h=Object.entries(d).map(([e,t])=>`${t} ${e}`).join(", ");console.log(` Active intents: ${h}`),console.log();for(const e of r){const t=e.action.toUpperCase(),n=e.direction.toUpperCase(),s=e.maxPrice?`@ ≤${e.maxPrice}c`:"@ market",o=e.targetQuantity>0?` (${Math.round(e.filledQuantity/e.targetQuantity*100)}%)`:"";if(console.log(` [${e.status}] ${t} ${e.marketId} ${n} ${e.targetQuantity}${s} filled ${e.filledQuantity}/${e.targetQuantity}${o}`),"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(` ${a.c.dim}Start runtime to execute: sf runtime start${a.c.reset}`),console.log())}catch(e){console.error(`${a.c.red}Error:${a.c.reset} ${e.message}`),process.exit(1)}})};const s=n(35317),o=n(19218),i=n(96139),r=n(11627),a=n(99236),c=n(79896),l=n(16928),d=n(70857),u=(0,l.join)((0,d.homedir)(),".sf","runtime.pid"),p=(0,l.join)((0,d.homedir)(),".sf","runtime.log"),h=(0,l.join)((0,d.homedir)(),".sf","runtime-executed.json"),m=3e4,g=new Set;function f(){try{const e=JSON.parse((0,c.readFileSync)(h,"utf-8"));for(const t of e)g.add(t)}catch{}}function y(){try{(0,c.mkdirSync)((0,l.join)((0,d.homedir)(),".sf"),{recursive:!0}),(0,c.writeFileSync)(h,JSON.stringify([...g]))}catch{}}async function $(e,t,s=!1){if(!(t.activateAt&&new Date(t.activateAt)>new Date))if(new Date(t.expireAt)<new Date){b(`Intent ${t.id.slice(0,8)} expired`);try{await e.cancelIntentAPI(t.id)}catch{}}else{if("pending"===t.status&&b(`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 o=await async function(e){switch(e.triggerType){case"immediate":return!0;case"price_below":{if(!e.triggerPrice)return!1;const t=await(0,i.getMarketPrice)(e.marketId);return null!==t&&t<=e.triggerPrice}case"price_above":{if(!e.triggerPrice)return!1;const t=await(0,i.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(!o)return;if(b(`TRIGGERED: ${t.id.slice(0,8)} ${t.marketId} (${t.triggerType})`),s&&t.softCondition)try{const{evaluateSoftCondition:e}=await n.e(563).then(n.bind(n,9563));if(!await e(t))return void b(` Soft condition HOLD: "${t.softCondition.slice(0,60)}"`);b(` Soft condition PASS: "${t.softCondition.slice(0,60)}"`)}catch(e){return void b(` Soft condition error (defaulting to HOLD): ${e.message}`)}t.autoExecute?await w(e,t):b(` Awaiting confirmation. Use: sf intent status ${t.id.slice(0,8)}`)}"triggered"===t.status&&t.autoExecute&&await w(e,t)}}async function w(e,t){if(g.has(t.id))return;if("kalshi"!==t.venue)return void b(` Skipping ${t.id.slice(0,8)}: ${t.venue} execution not yet supported`);const n=t.targetQuantity-t.filledQuantity;if(n<=0)g.add(t.id);else{g.add(t.id),y(),b(` Executing: ${t.action.toUpperCase()} ${t.marketId} ${t.direction.toUpperCase()} x${n}${t.maxPrice?` @ ≤${t.maxPrice}c`:""}`);try{const s=await(0,i.createOrder)({ticker:t.marketId,side:t.direction,action:t.action,type:t.maxPrice?"limit":"market",count:n,...t.maxPrice?{yes_price:t.maxPrice}:{}}),o=s.order||s,r=Math.round(parseFloat(o.fill_count||o.fill_count_fp||n)),u=Math.round(parseFloat(o.yes_price||o.no_price||t.maxPrice||0));b(` ${a.c.green}FILLED${a.c.reset}: ${r} 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:r,price:t.maxPrice,orderId:o.order_id,source:t.source})+"\n";(0,c.appendFileSync)((0,l.join)((0,d.homedir)(),".sf","trade-journal.jsonl"),e)}catch{}try{await e.request("PATCH",`/api/intents/${t.id}`,{fill:{orderId:o.order_id||null,fillQuantity:r,fillPrice:u,fillCostCents:Math.round(u*r),venueResponse:{order_id:o.order_id,status:o.status}}}),b(` ${a.c.dim}Fill recorded to API${a.c.reset}`)}catch(e){b(` ${a.c.yellow}Warning:${a.c.reset} Failed to record fill to API: ${e.message}. Intent may re-execute on restart.`)}}catch(e){g.delete(t.id);const n=e.message||String(e);n.includes("403")?(b(` ${a.c.red}FAILED${a.c.reset}: 403 Forbidden — Kalshi key lacks write permission`),g.add(t.id)):b(` ${a.c.red}FAILED${a.c.reset}: ${n}`)}}}function k(e){try{const{execSync:t}=n(35317),s=t("ps ax -o pid,command",{encoding:"utf-8"}),o=[];for(const t of s.split("\n"))if(t.includes("sf")&&t.includes(e)&&!t.includes("--stop")&&!t.includes("status")){const e=parseInt(t.trim());isNaN(e)||e===process.pid||o.push(e)}return o}catch{return[]}}function b(e){const t=(new Date).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});console.log(` ${a.c.dim}${t}${a.c.reset} ${e}`)}function v(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,s.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,s.kalshiFetchEvents)(e);if(0===n.length){const n=await(0,s.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,s.kalshiFetchMarketsByEvent)(e.event_ticker))}}(t.series.toUpperCase(),t.json);await async function(e,t,n="all",s){const c="kalshi"===n?Promise.resolve([]):(0,o.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 s=await n.json(),o=s.matchedSeries||[],r=s.markets||[];console.log(`\n${i.c.bold}Matched ${o.length} series via proxy:${i.c.reset}\n`);for(const e of o.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,o.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),s)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,s=(e.venue,(e.ticker||"").slice(0,28));console.log(n+(0,i.pad)(s,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 s=n(19218),o=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(`${o}/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(`${o}/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?`${s.c.green}OPEN${s.c.reset}`:`${s.c.red}CLOSED${s.c.reset}`;console.log(),console.log(` ${s.c.bold}${s.c.cyan}Exchange Status${s.c.reset}`),console.log(` ${s.c.dim}${"─".repeat(30)}${s.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 s=n(99236),o="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,s.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 o.SFClient(e.apiKey,e.apiUrl),s=await n.getContext(e.thesis),i=new Set((s.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"),s=t-n;a+=s;const o=s>=0?`${i.c.green}+$${s.toFixed(2)}${i.c.reset}`:`${i.c.red}-$${Math.abs(s).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)} ${o}`)}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 s=n(96139),o=n(19218),i=n(99236)},85417:function(e,t,n){"use strict";var s=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 S(e.key,t);n.valid||(f(n.msg),process.exit(1));const s=(0,r.loadFileConfig)();return(0,r.saveConfig)({...s,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 s=await S(n,t);s.valid?(g(`Detected SF_API_KEY — ${p(v(n))}`),y(p("Skipping.")),e.apiKey=n,$()):(f(`Existing key invalid: ${s.msg}`),e.apiKey=await C(t))}else e.apiKey=await C(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 s=process.env.OPENROUTER_API_KEY||e.openrouterKey;if(s){const t=await _(s);t.valid?(g(`Detected OPENROUTER_API_KEY — ${p(v(s))}`),y(p("Skipping.")),e.openrouterKey=s,$()):(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 o=process.env.KALSHI_API_KEY_ID||e.kalshiKeyId,i=process.env.KALSHI_PRIVATE_KEY_PATH||e.kalshiPrivateKeyPath;if(o&&i){process.env.KALSHI_API_KEY_ID=o,process.env.KALSHI_PRIVATE_KEY_PATH=i;const t=await x();t.valid?(g(`Detected Kalshi — ${p(v(o))} (${t.posCount} position(s))`),y(p("Skipping.")),e.kalshiKeyId=o,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 O(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 o=s(n(23785)),i=n(35317),r=n(11627),a=n(19218),c=n(96139),l=n(83969),d=e=>`[32m${e}[39m`,u=e=>`[31m${e}[39m`,p=e=>`[2m${e}[22m`,h=e=>`[1m${e}[22m`,m=e=>`[36m${e}[39m`;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=o.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 S(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 _(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 O(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 C(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 S(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 _(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 s=await x();s.valid?g(s.msg):(f(s.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 O(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(),s=(n.theses||[]).filter(e=>"active"===e.status);if(s.length>0){console.log(` ${h("Step 7: Theses")}`),$(),g(`Found ${s.length} active thesis(es):`);for(const e of s.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)(s[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 o=await w(" Enter your thesis (press Enter to skip, use sf create later):\n > ");if(!o)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(o,!0);if(n.id){const t=n.causalTree?.nodes?.length||0,s=n.edgeAnalysis?.edges?.length||0,o=n.edgeAnalysis?.totalMarketsAnalyzed||0,i=Math.round(100*(parseFloat(n.confidence)||.5));if(g(`Causal tree: ${t} node(s)`),g(`Scanned ${o} markets, found ${s} 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 s.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(`${o.c.green}✓${o.c.reset} Signal injected`),console.log(` ${o.c.bold}Type:${o.c.reset} ${r}`),console.log(` ${o.c.bold}Source:${o.c.reset} cli`),console.log(` ${o.c.bold}Content:${o.c.reset} ${t}`),a.signalId&&console.log(` ${o.c.bold}ID:${o.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${o.c.dim}Signal queued. Next monitor cycle in ~${u}min (${h}).${o.c.reset}`),console.log(`${o.c.dim}Or run ${o.c.reset}sf evaluate ${e}${o.c.dim} to consume immediately.${o.c.reset}`)};const s=n(19218),o=n(99236)},72124:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.statusCommand=async function(e){const t=[],a=Date.now();try{const e=await fetch(`${r}/api/health`,{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()-a})}catch(e){t.push({name:"API",status:"fail",detail:e.message?.slice(0,40)||"unreachable",ms:Date.now()-a})}const c=(0,i.loadConfig)();if((0,i.isConfigured)()){const n=Date.now();try{const e=await fetch(`${r}/api/thesis`,{headers:{Authorization:`Bearer ${c.apiKey}`},signal:AbortSignal.timeout(5e3)}),s=(c.apiKey||"").slice(0,12)+"...";t.push({name:"Auth",status:e.ok?"ok":"fail",detail:e.ok?s:`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,o.isKalshiConfigured)()){const n=Date.now();try{const e=await(0,o.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)"});c.polymarketWalletAddress?t.push({name:"Polymarket",status:"ok",detail:c.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 ${c.apiKey}`},signal:AbortSignal.timeout(5e3)});if(e.ok){const n=(await e.json()).theses||[],s=n.filter(e=>"active"===e.status).length,o=n.length;t.push({name:"Theses",status:"ok",detail:`${s} active, ${o} total`})}}catch{}const l=c.tradingEnabled;t.push({name:"Trading",status:l?"ok":"skip",detail:l?"enabled":"disabled (sf setup --enable-trading)"});try{const e=await Promise.resolve().then(n.t.bind(n,79896,23)),s=await Promise.resolve().then(n.t.bind(n,16928,23)),o=await Promise.resolve().then(n.t.bind(n,70857,23)),i=s.join(o.homedir(),".sf","runtime.pid");if(e.existsSync(i)){const n=e.readFileSync(i,"utf-8").trim();let s=!1;try{process.kill(parseInt(n),0),s=!0}catch{}t.push({name:"Runtime",status:s?"ok":"fail",detail:s?`PID ${n}`:`stale PID ${n}`})}else t.push({name:"Runtime",status:"skip",detail:"not running (sf runtime start)"});const r=s.join(o.homedir(),".sf","telegram.pid");if(e.existsSync(r)){const n=e.readFileSync(r,"utf-8").trim();let s=!1;try{process.kill(parseInt(n),0),s=!0}catch{}t.push({name:"Telegram",status:s?"ok":"fail",detail:s?`PID ${n}`:`stale PID ${n}`})}else t.push({name:"Telegram",status:"skip",detail:"not running (sf telegram --daemon)"})}catch{}if((0,i.isConfigured)())try{const e=await fetch(`${r}/api/intents?active=true`,{headers:{Authorization:`Bearer ${c.apiKey}`},signal:AbortSignal.timeout(5e3)});if(e.ok){const n=((await e.json()).intents||[]).filter(e=>["pending","armed","triggered"].includes(e.status)),s=n.filter(e=>"armed"===e.status).length;t.push({name:"Intents",status:n.length>0?"ok":"skip",detail:n.length>0?`${n.length} active (${s} armed)`:"none"})}}catch{}try{const{getPendingWakes:e}=await n.e(563).then(n.bind(n,9563)),s=e();t.push({name:"Wakes",status:s.length>0?"ok":"skip",detail:s.length>0?`${s.length} pending`:"none"})}catch{}try{const e=await Promise.resolve().then(n.t.bind(n,79896,23)),s=await Promise.resolve().then(n.t.bind(n,16928,23)),o=await Promise.resolve().then(n.t.bind(n,70857,23)),i=s.join(o.homedir(),".sf","workspace");if(e.existsSync(i)){const n=s.join(i,"context"),o=e.existsSync(n)?e.readdirSync(n).filter(e=>e.endsWith(".jsonl")).length:0,r=e.readdirSync(i).length;t.push({name:"Workspace",status:"ok",detail:`${r} items, ${o} context logs`})}else t.push({name:"Workspace",status:"skip",detail:"empty"})}catch{}if(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?`${s.c.green}ok${s.c.reset}`:"fail"===e.status?`${s.c.red}!!${s.c.reset}`:`${s.c.dim}--${s.c.reset}`,n=e.ms?` ${s.c.dim}${e.ms}ms${s.c.reset}`:"";console.log(` ${e.name.padEnd(14)} ${t} ${e.detail}${n}`)}console.log()};const s=n(99236),o=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 s.SFClient;if(e){const s=(await n.getStrategies(e,t?.all?void 0:t?.status||"active")).strategies||[];if(0===s.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 s)console.log(c(e)),console.log()}else{const{theses:e}=await n.listTheses();let s=0;for(const o of e){const e=t?.all?void 0:t?.status||"active",l=(await n.getStrategies(o.id,e)).strategies||[];if(0!==l.length){s+=l.length,console.log(`\n ${a}${o.title}${i} ${r}(${o.id.slice(0,8)})${i}\n`);for(const e of l)console.log(c(e)),console.log()}}0===s&&(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(`[31mError:[0m ${e.message}`),process.exit(1)}})};const s=n(19218),o={active:"[32m",watching:"[33m",executed:"[36m",cancelled:"[90m",review:"[31m"},i="[0m",r="[2m",a="[1m";function c(e,t=!1){const n=o[e.status]||"",s=[],c=t?`${r}${e.thesisTitle||e.thesisId?.slice(0,8)}${i} `:"";s.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(s.push(` ${m}`),e.softConditions&&s.push(` ${r}Soft: ${e.softConditions}${i}`),"review"===e.status&&s.push(` [31m⚠️ Needs review${i}`),e.rationale){const t=e.rationale.length>120?e.rationale.slice(0,117)+"...":e.rationale;s.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 s.push(` ${r}created by ${g} · ${f}${i}`),s.join("\n")}},91993:function(e,t,n){"use strict";var s=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{const e=p();if(e.length>0){for(const t of e)try{process.kill(t,"SIGTERM")}catch{}console.log(` Stopped ${e.length} orphan bot process(es): ${e.join(", ")}`)}else console.log(" No running Telegram bot found.")}return}if(e.status){const e=u();if(e)console.log(` Telegram bot running (PID ${e})`),console.log(` Log: ${d}`);else{const e=p();e.length>0?(console.log(` Telegram bot running (orphan PID ${e.join(", ")} — no PID file)`),console.log(" Use --stop to terminate.")):console.log(" Telegram bot not running.")}return}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 s=process.argv[1];i.default.mkdirSync(r.default.dirname(l),{recursive:!0});const a=i.default.openSync(d,"a"),c=(0,o.spawn)(process.execPath,[s,...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:s}=await Promise.all([n.e(830),n.e(278),n.e(12)]).then(n.t.bind(n,6012,23));await s({token:t,chatId:e.chatId?parseInt(e.chatId):void 0})};const o=n(35317),i=s(n(79896)),r=s(n(16928)),a=s(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}}function p(){try{const{execSync:e}=n(35317),t=e("ps ax -o pid,command",{encoding:"utf-8"}),s=[];for(const e of t.split("\n"))if(/\bsf\b.*\btelegram\b/.test(e)&&!e.includes("--stop")&&!e.includes("--status")){const t=parseInt(e.trim());isNaN(t)||t===process.pid||s.push(t)}return s}catch{return[]}}},34362:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buyCommand=async function(e,t,n){(0,o.requireTrading)(),await l(e,t,"buy",n)},t.sellCommand=async function(e,t,n){(0,o.requireTrading)(),await l(e,t,"sell",n)};const s=n(96139),o=n(11627),i=n(99236),r=n(79896),a=n(16928),c=n(70857);async function l(e,t,n,o){const l=parseInt(t);if(isNaN(l)||l<=0)throw new Error("Quantity must be a positive integer");const d=o.side||"yes";if(!o.market&&!o.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=o.market?"market":"limit";let p=o.price?parseInt(o.price):void 0;if(o.market&&!p){console.log(`${i.c.dim}Fetching current market price for ${e}...${i.c.reset}`);const t=await(0,s.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(),!o.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,s.createOrder)({ticker:e,side:d,action:n,type:u,count:l,...p?{yes_price:p}:{}}),o=t.order||t;console.log(),console.log(` ${i.c.green}✓${i.c.reset} Order placed: ${o.order_id||"OK"}`),o.status&&console.log(` Status: ${o.status}`),o.fill_count_fp&&console.log(` Filled: ${o.fill_count_fp}/${o.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 s=JSON.stringify({ts:(new Date).toISOString(),action:n,ticker:e,side:d,quantity:l,price:p||null,type:u,orderId:o.order_id||null,status:o.status||null,filled:o.fill_count_fp||null})+"\n";(0,r.appendFileSync)((0,a.join)(t,"trade-journal.jsonl"),s),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)}}},64115:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateCommand=async function(){console.log(" Checking for updates...");try{const e=await fetch(`https://registry.npmjs.org/${o}/latest`);if(!e.ok)return void console.error(" Failed to check npm registry.");const t=(await e.json()).version,{join:i}=await Promise.resolve().then(n.t.bind(n,16928,23)),{readFileSync:r,existsSync:a}=await Promise.resolve().then(n.t.bind(n,79896,23));let c="0.0.0";try{const e=i(__dirname,"..","package.json");a(e)&&(c=JSON.parse(r(e,"utf-8")).version)}catch{}if(c===t)return void console.log(` Already on latest version (${c}).`);const l=function(){try{const e=(0,s.execSync)("which sf",{encoding:"utf-8"}).trim();if(e.includes("pnpm"))return"pnpm";if(e.includes("yarn"))return"yarn"}catch{}try{if((0,s.execSync)("pnpm list -g --depth=0 2>/dev/null",{encoding:"utf-8"}).includes(o))return"pnpm"}catch{}try{if((0,s.execSync)("yarn global list --depth=0 2>/dev/null",{encoding:"utf-8"}).includes(o))return"yarn"}catch{}return"npm"}(),d="pnpm"===l?`pnpm add -g ${o}@latest`:"yarn"===l?`yarn global add ${o}@latest`:`npm install -g ${o}@latest`;console.log(` ${c} → ${t}`),console.log(` Running: ${d}\n`),(0,s.execSync)(d,{stdio:"inherit"}),console.log(`\n [32m✓ Updated to ${t}[39m`)}catch(e){console.error(` Update failed: ${e.message}`),console.error(` Try manually: npm install -g ${o}@latest`)}};const s=n(35317),o="@spfunctions/cli"},96007:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.watchCommand=async function(e,t,n){const o=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"===o?"30":"60")),a=1e3*i,h=n.json||!1;if(!h){const t="price"===o?"":` [${o}]`;console.log(),console.log(` ${s.c.bold}sf watch${s.c.reset}${e?` "${e}"`:""}${t}`),console.log(` ${s.c.dim}Polling every ${i}s · Ctrl+C to stop${s.c.reset}`),console.log()}const m=()=>{h||console.log(`\n ${s.c.dim}Watch stopped.${s.c.reset}\n`),process.exit(0)};switch(process.on("SIGINT",m),process.on("SIGTERM",m),o){case"orderbook":await r(e,a,h);break;case"flow":await async function(e,t,n){let o=new Date(Date.now()-72e5).toISOString();const i=new Map;for(;;){try{const t=await l(o,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 o=t.recentDeltas.slice(-3);if(o.length>=3){const t=o.every(e=>e>0),i=o.every(e=>e<0);if(t||i){const i=o.reduce((e,t)=>e+Math.abs(t),0),r=t?"UP":"DOWN",a=t?s.c.green:s.c.red;n?console.log(JSON.stringify({type:"momentum",ticker:e.ticker,direction:r,totalDelta:i,moves:o.length})):console.log(` ${u()} ${a}MOMENTUM${s.c.reset} ${e.ticker} ${o.length} consecutive ${r} (${o.map(e=>`${e>0?"+":""}${e}c`).join(", ")}) total ${i}c`)}}if(t.recentDeltas.length>=2){const o=t.recentDeltas[t.recentDeltas.length-2],i=t.recentDeltas[t.recentDeltas.length-1];o&&i&&Math.sign(o)!==Math.sign(i)&&Math.abs(i)>=5&&(n?console.log(JSON.stringify({type:"reversal",ticker:e.ticker,previousDelta:o,currentDelta:i})):console.log(` ${u()} ${s.c.yellow}REVERSAL${s.c.reset} ${e.ticker} was ${o>0?"+":""}${o}c, now ${i>0?"+":""}${i}c`))}}t.length>0?o=t[0].detectedAt:n||process.stdout.write(` ${s.c.dim}${u()} · monitoring flow${s.c.reset}\r`)}catch(e){n||console.error(` ${s.c.dim}${u()} Error: ${e.message}${s.c.reset}`)}await p(t)}}(e,a,h);break;case"cross-venue":await async function(e,t,n){n||console.log(` ${s.c.dim}Fetching cross-venue data from scan...${s.c.reset}`);let o=new Date(Date.now()-72e5).toISOString();const i=new Map;for(;;){try{const t=await l(o,e);for(const e of t){if("price_move"!==e.changeType)continue;const t=e.title.toLowerCase().slice(0,50);let o=i.get(t);if(o||(o={kalshi:0,poly:0}),"kalshi"===e.venue?o.kalshi=e.afterPrice||0:"polymarket"===e.venue&&(o.poly=e.afterPrice||0),i.set(t,o),o.kalshi>0&&o.poly>0){const t=Math.abs(o.kalshi-o.poly),i=o.kalshi>o.poly?"Kalshi":"Poly";if(t>=2)if(n)console.log(JSON.stringify({type:"cross_venue",title:e.title,kalshi:o.kalshi,poly:o.poly,gap:t,higher:i}));else{const n=t>=5?s.c.green:s.c.yellow;console.log(` ${u()} ${n}SPREAD${s.c.reset} ${e.title.slice(0,45)} K:${o.kalshi}c P:${o.poly}c gap ${t}c (${i} higher)`)}}}t.length>0?o=t[0].detectedAt:n||process.stdout.write(` ${s.c.dim}${u()} · tracking cross-venue${s.c.reset}\r`)}catch(e){n||console.error(` ${s.c.dim}${u()} Error: ${e.message}${s.c.reset}`)}await p(t)}}(e,a,h);break;case"all":await async function(e,t,n){let o=new Date(Date.now()-36e5).toISOString();const i=new Map,r=new Map;for(;;){try{const t=await l(o,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 o=t.recentDeltas.slice(-3);if(o.length>=3&&(o.every(e=>e>0)||o.every(e=>e<0))){const e=o.every(e=>e>0)?"UP":"DOWN",t=o.reduce((e,t)=>e+Math.abs(t),0);if(!n){const n="UP"===e?s.c.green:s.c.red;console.log(` ${n}^^ MOMENTUM${s.c.reset} ${o.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(` ${s.c.yellow}^^ CROSS-VENUE${s.c.reset} gap ${e}c K:${c.kalshi}c vs P:${c.poly}c`)}}t.length>0?o=t[0].detectedAt:n||process.stdout.write(` ${s.c.dim}${u()} · watching all${s.c.reset}\r`)}catch(e){n||console.error(` ${s.c.dim}${u()} Error: ${e.message}${s.c.reset}`)}await p(t)}}(e,a,h);break;default:await async function(e,t,n){let o=(new Date).toISOString();try{const t=new Date(Date.now()-36e5).toISOString(),i=await l(t,e);if(i.length>0){n||console.log(` ${s.c.dim}${u()} Recent changes (last hour):${s.c.reset}`);const e=c(i);for(const t of e)n?console.log(JSON.stringify(t)):d(t);o=i[0].detectedAt}else n||console.log(` ${s.c.dim}${u()} No recent changes. Watching...${s.c.reset}`)}catch(e){n||console.error(` ${s.c.dim}${u()} Error: ${e.message}${s.c.reset}`)}for(;;){await p(t);try{const t=await l(o,e),i=n?t:c(t);for(const e of i)n?console.log(JSON.stringify(e)):d(e);t.length>0?o=t[0].detectedAt:n||process.stdout.write(` ${s.c.dim}${u()} · no new changes${s.c.reset}\r`)}catch(e){n||console.error(` ${s.c.dim}${u()} Error: ${e.message}${s.c.reset}`)}}}(e,a,h)}};const s=n(99236),o=n(96139),i=process.env.SF_API_URL||"https://simplefunctions.dev";async function r(e,t,n){e||(console.error(` ${s.c.red}Error:${s.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(` ${s.c.dim}No Kalshi markets found for "${e}"${s.c.reset}`),process.exit(1)),n||(console.log(` ${s.c.dim}Tracking ${i.length} market(s)${s.c.reset}`),console.log());let r=new Map;for(;;){for(const{ticker:e,title:t}of i)try{const i=await(0,o.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?`${s.c.green}HIGH${s.c.reset}`:p<=5?`${s.c.yellow}MED${s.c.reset}`:`${s.c.red}LOW${s.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 o=e>0?"+":"",i=t>0?"+":"";n=` ${s.c.dim}depth: bids ${o}${Math.round(e)}, asks ${i}${Math.round(t)}${s.c.reset}`}}console.log(` ${u()} ${s.c.bold}${e.slice(0,30)}${s.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}`,s=t.get(e);s?s.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 s=await fetch(n);if(!s.ok)return[];return(await s.json()).changes||[]}function d(e){const t=u(),n="kalshi"===e.venue?`${s.c.cyan}K${s.c.reset}`:"polymarket"===e.venue?"[35mP[39m":"traditional"===e.venue?`${s.c.dim}$${s.c.reset}`:"·";switch(e.changeType){case"new_contract":console.log(` ${t} ${n} ${s.c.green}+ NEW${s.c.reset} ${e.afterPrice}c ${e.title}`);break;case"removed_contract":console.log(` ${t} ${n} ${s.c.red}- GONE${s.c.reset} ${e.title}`);break;case"price_move":if("traditional"===e.venue){const o=(e.delta||0)>0?"+":"",i=(e.delta||0)>0?s.c.green:s.c.red,r=((e.beforePrice||0)/100).toFixed(0),a=((e.afterPrice||0)/100).toFixed(0);console.log(` ${t} ${n} ${i}${o}${e.delta}c${s.c.reset} $${r}→$${a} ${e.title}`)}else{const o=(e.delta||0)>0?"+":"",i=(e.delta||0)>0?s.c.green:s.c.red;console.log(` ${t} ${n} ${i}${o}${e.delta}c${s.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 s=parseFloat(n);if(isNaN(s)||s<0||s>1)throw new Error(`Invalid probability: "${n}". Must be 0-1.`);return{nodeId:t.trim(),newProbability:s}}),r=new s.SFClient(t.apiKey,t.apiUrl),a=await r.getContext(e),c=function(e,t){const n=[];function s(e){for(const t of e)n.push(t),t.children?.length&&s(t.children)}const o=e.causalTree?.nodes||[];s(o);const i=o.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 s=n.find(t=>t.id===e);s&&s.probability>0&&d.set(e,Math.max(0,Math.min(2,t/s.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 s=e.marketPrice||0,o=e.thesisPrice||e.thesisImpliedPrice||s,i=e.edge||e.edgeSize||0,r=o-s,a=Math.round(100*(s+r*n))/100,c=e.direction||"yes",l=Math.round(100*("yes"===c?a-s:s-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:s,oldThesisPrice:o,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),s=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}% ${s} ${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),s=`${e.oldEdge>0?"+":""}${Math.round(e.oldEdge)}`.padEnd(8),o=`${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} ${s} → ${o} ${r}`)}}try{const e=await(0,o.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),s=await(0,o.getMarketPrice)(e.ticker),r=null!==s?((s-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 s=n(19218),o=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",o=await fetch(`${t}/api/agent/world/delta?since=${encodeURIComponent(n)}`);o.ok||(console.error(`\n ${s.c.red}Error:${s.c.reset} API returned ${o.status}\n`),process.exit(1));const i=await o.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)}`:"",o=await fetch(`${t}/api/agent/world${n}`);o.ok||(console.error(`\n ${s.c.red}Error:${s.c.reset} API returned ${o.status}\n`),process.exit(1));const i=await o.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 s=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",s=t?.hours||"24",r=t?.limit||"20",a=await o(`/api/x/search?q=${encodeURIComponent(e)}&mode=${n}&hours=${s}&limit=${r}`);if(t?.json)return void console.log(JSON.stringify(a,null,2));if(a.summary){if(console.log(`\n [1m[36mX: ${e}[0m\n`),console.log(` ${a.summary}\n`),a.sentiment){const e={bullish:"[32m",bearish:"[31m",mixed:"[33m",neutral:"[2m"};console.log(` Sentiment: ${e[a.sentiment]||""}${a.sentiment}[0m`)}a.keyThemes?.length&&console.log(` Themes: ${a.keyThemes.join(", ")}`),console.log()}const c=a.posts||[];if(c.length>0){console.log(` [1mTop posts[22m (${c.length})\n`);for(const e of c.slice(0,10)){const t=e.metrics?.likes||0,n=e.metrics?.retweets||0,s=e.authorFollowers?` (${i(e.authorFollowers)})`:"";console.log(` [36m@${e.authorUsername}[0m${s}`),console.log(` ${e.text.slice(0,140)}${e.text.length>140?"...":""}`),console.log(` [2m♥ ${t} ↻ ${n}[0m\n`)}}if(a.volume){const e=a.volume,t=e.velocityChange>1?`[32m+${Math.round(100*(e.velocityChange-1))}%[0m`:`[31m${Math.round(100*(e.velocityChange-1))}%[0m`;console.log(` [2mVolume: ${i(e.totalCount)} posts (${s}h) | Velocity: ${t} | Peak: ${e.peak?.count}[0m\n`)}const l=a.news||[];if(l.length>0){console.log(` [1mX News[22m (${l.length})\n`);for(const e of l.slice(0,5)){const t=e.tickers?.length?` [33m${e.tickers.join(" ")}[0m`:"";console.log(` ${e.title}${t}`),console.log(` [2m${e.summary.slice(0,120)}...[0m\n`)}}},t.xVolumeCommand=async function(e,t){const n=t?.hours||"72",s=t?.granularity||"hour",r=await o(`/api/x/volume?q=${encodeURIComponent(e)}&hours=${n}&granularity=${s}`);if(t?.json)return void console.log(JSON.stringify(r,null,2));console.log(`\n [1m[36mX Volume: ${e}[0m\n`),console.log(` Total: ${i(r.totalCount)} posts (${n}h)`);const a=r.velocityChange>1?`[32m+${Math.round(100*(r.velocityChange-1))}%[0m`:`[31m${Math.round(100*(r.velocityChange-1))}%[0m`;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 s=(n.time||"").slice(11,16)||"?",o=e>0?Math.round(n.count/e*t):0,i="▓".repeat(o),r=String(n.count).padStart(6);console.log(` ${s} ${r} ${i}`)}}console.log()},t.xNewsCommand=async function(e,t){const n=t?.limit||"10",s=await o(`/api/x/news?q=${encodeURIComponent(e)}&limit=${n}`);if(t?.json)return void console.log(JSON.stringify(s,null,2));const i=s.stories||[];console.log(`\n [1m[36mX News: ${e}[0m (${i.length} stories)\n`);for(const e of i){const t=e.tickers?.length?` [33m${e.tickers.join(" ")}[0m`:"",n=e.categories?.length?`[2m[${e.categories.join(", ")}][0m`:"";console.log(` [1m${e.title}[22m${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(/^@/,""),s=t?.hours||"24",i=t?.limit||"20",r=await o(`/api/x/account?username=${n}&hours=${s}&limit=${i}`);if(t?.json)return void console.log(JSON.stringify(r,null,2));const a=r.posts||[];console.log(`\n [1m[36m@${n}[0m (${a.length} posts, last ${s}h)\n`);for(const e of a){const t=e.metrics?.likes||0,n=e.metrics?.retweets||0,s=e.createdAt?.slice(11,16)||"";console.log(` [2m${s}[0m ${e.text.slice(0,140)}${e.text.length>140?"...":""}`),console.log(` [2m♥ ${t} ↻ ${n}[0m\n`)}};const n=process.env.SF_API_URL||"https://simplefunctions.dev";function s(){const e=process.env.SF_API_KEY||"";return e||(console.error(" API key required. Run: sf setup"),process.exit(1)),e}async function o(e){const t=await fetch(`${n}${e}`,{headers:{Authorization:`Bearer ${s()}`}});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 s=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){o.default.mkdirSync(a,{recursive:!0}),o.default.writeFileSync(c,JSON.stringify({...e,configuredAt:(new Date).toISOString()},null,2))},t.resetConfig=function(){try{o.default.existsSync(c)&&o.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 o=s(n(79896)),i=s(n(16928)),r=s(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(o.default.existsSync(c))return JSON.parse(o.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 s=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"),s=Math.abs(t),o=t>=0?"yes":"no",i=s>0?Math.round(n/s*100):0;return{ticker:e.ticker||e.market_ticker||"",event_ticker:e.event_ticker||"",market_title:e.market_title||e.title||"",side:o,quantity:s,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 s=await n.json(),o=s.market||s,i=h(o);return 50!==i||o.last_price_dollars||o.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 s=n.yes_dollars||n.yes||[],o=n.no_dollars||n.no||[],i=!(!n.yes_dollars&&!n.no_dollars),r=s.map(e=>({price:i?Math.round(100*parseFloat(e[0])):Number(e[0]),qty:parseFloat(e[1])})).filter(e=>e.price>0),a=o.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}`,s=await fetch(n,{headers:{Accept:"application/json"}});if(!s.ok)return null;const o=await s.json(),i=o.orderbook_fp||o.orderbook||o;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),s=Math.min(e.endTs,n);t.set("end_ts",s.toString()),t.set("period_interval",e.periodInterval.toString());const o=`/series/${e.seriesTicker}/events/${e.eventTicker}/forecast_percentile_history?${t.toString()}`;return(await u(o)).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}`,s=e.split("?")[0],{headers:o}=d("DELETE",`/trade-api/v2${s}`,t),i=await fetch(n,{method:"DELETE",headers:o});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 s=`/portfolio/orders/${e}`,o=`${a}${s}`,{headers:i}=d("PATCH",`/trade-api/v2${s}`,n),r=await fetch(o,{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 o=s(n(79896)),i=s(n(16928)),r=s(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=o.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 s=process.env.KALSHI_API_KEY_ID,o=Date.now().toString(),i=o+e.toUpperCase()+t;return{headers:{"KALSHI-ACCESS-KEY":s,"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":o,"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}`,s=e.split("?")[0],{headers:o}=d("GET",`/trade-api/v2${s}`,t),i=await fetch(n,{method:"GET",headers:o});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 s=`${a}${e}`,o=e.split("?")[0],{headers:i}=d("POST",`/trade-api/v2${o}`,n),r=await fetch(s,{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 s=new URLSearchParams({q:e,limit_per_type:t.toString()}),o=await fetch(`${n}/public-search?${s}`);if(!o.ok)throw new Error(`Polymarket search error: ${o.status}`);const i=await o.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 s=await fetch(`${n}/events?${t}`);if(!s.ok)throw new Error(`Polymarket events error: ${s.status}`);return s.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(`${s}/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(`${s}/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(`${s}/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(`${s}/ohlc?${t}`);if(!n.ok)return[];const o=await n.json();return Array.isArray(o)?o:o.candles||o.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(`${s}/prices-history?${t}`);if(!n.ok)return[];const o=await n.json();return o.history||[]},t.polymarketGetPositions=async function(e){const t=await fetch(`${o}/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(`${o}/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",s="https://clob.polymarket.com",o="https://data-api.polymarket.com";async function i(e){try{const t=await fetch(`${s}/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),s=t.length>0?Math.round(100*t[0].price):0,o=n.length>0?Math.round(100*n[0].price):100,i=o-s,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:s,bestAsk:o,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,s){try{const o=await fetch(`${n}/api/share`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,args:t,data:s})});if(!o.ok)return void console.error(`Share failed: ${o.status}`);const{url:i}=await o.json();console.log(),console.log(` [36m${i}[39m`),console.log()}catch(e){console.error(`Share failed: ${e.message}`)}};const n=process.env.SF_API_URL||"https://simplefunctions.dev"},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:s}of n)if(e.toUpperCase().startsWith(t))return s.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,s){const{row:o,col:i,width:r,height:a}=n;if(r<3||a<2)return;e.fill(o,i,r,a," ","",t.CLR.bgPanel);for(let n=i;n<i+r;n++)e.write(o,n,"─",t.CLR.borderDim);s&&e.write(o,i+2,` ${s} `,t.CLR.dim)},t.drawHDivider=function(e,n,s){const o=n.row+s;for(let s=n.col;s<n.col+n.width;s++)e.write(o,s,"─",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 s=Math.min(...e),o=Math.max(...e),i=o-s||1;return e.map(e=>({text:"▁▂▃▄▅▆▇█"[Math.round((e-s)/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,o,i,r,a){if(0===r.length||o<10||i<4)return;const c=o-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),s=Math.min(n+1,r.length-1),o=t-n;h.push(r[n]*(1-o)+r[s]*o)}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 o=0;o<l;o++)e.write(t+o,n+8,"│",s.CLR.borderDim);for(const o of g){const i=Math.abs(o.value)>=100?"$"+((o.value>=0?"+":"")+o.value.toFixed(0)):"$"+((o.value>=0?"+":"")+o.value.toFixed(1));e.write(t+o.row,n,i.padStart(8),s.CLR.dim)}if(f>=0&&f<l)for(let n=0;n<c;n++)e.write(t+f,m+n,"╌",s.CLR.veryDim);for(let n=0;n<c;n++){const o=h[n],i=(o-d)/p*l*8,r=o>=0?s.CLR.green:s.CLR.red;for(let s=l-1;s>=0;s--){const o=i-8*(l-1-s);if(o>=8)e.write(t+s,m+n,"█",r);else if(o>0){const i=Math.round(Math.max(1,Math.min(o,8)));e.write(t+s,m+n," ▁▂▃▄▅▆▇█"[i],r)}}}const y=t+l;e.write(y,n+8,"└",s.CLR.borderDim);for(let t=0;t<c;t++)e.write(y,m+t,"─",s.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+o&&e.write(i,d,u.slice(0,5),s.CLR.dim)}}};const s=n(77096)},99844:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.loadAllData=R,t.startDashboard=async function(){const e=new s.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 o=()=>{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),process.on("uncaughtException",e=>{l(),console.error("Dashboard crashed:",e.message),process.exit(1)}),process.on("unhandledRejection",e=>{t&&(t.error=`${e?.message||e}`.slice(0,50))});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",O,()=>(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 s=n[t];"fulfilled"===s.status&&null!=s.value&&(e[t].current_value=s.value)}t.positions=e,N(t)}o()}catch{}},O)),r.push(setInterval(async()=>{try{const e=await(0,a.cached)("orders",I,()=>(0,d.getOrders)({status:"resting"}));e&&(t.orders=e.orders||[]),o()}catch{}},I)),r.push(setInterval(async()=>{try{const e=await(0,a.cached)("balance",P,()=>(0,d.getBalance)());e&&(t.balance=e.balance??0),o()}catch{}},P)),r.push(setInterval(async()=>{try{await L(t),o()}catch{}},E)),process.stdin.on("data",n=>{!function(e,t,n,s,o){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 o();switch(e.error=null,e.mode){case"overview":F(i,a,c,l,e,n,s,o);break;case"detail":!function(e,t,n,s,o){t?(n.mode="overview",o()):"b"===e?(K(n,"buy"),o()):"s"===e?(K(n,"sell"),o()):"w"===e&&n.theses.length>0&&(n.prevMode="detail",n.mode="whatif",n.whatifThesisId=n.theses[0].id,z(n).then(o))}(i,r,e,0,s);break;case"liquidity":!function(e,t,n,s,o,i,r){if(s)o.mode=o.prevMode,r();else if("j"===e||n)o.liquiditySelectedIndex++,r();else if("k"===e||t)o.liquiditySelectedIndex=Math.max(0,o.liquiditySelectedIndex-1),r();else if("\t"===e){const e=Object.keys(u.TOPIC_SERIES),t=e.indexOf(o.liquidityTopic);o.liquidityTopic=e[(t+1)%e.length],o.liquiditySelectedIndex=0,U(o).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"}(o),r()):"r"===e&&U(o).then(r)}(i,a,c,r,e,0,s);break;case"whatif":!function(e,t,n,s,o,i,r,a){if(o)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()):s&&a()}(i,a,c,l,r,e,0,s);break;case"trade":!function(e,t,n,s,o,i,r,a){if(o)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()):s&&i.tradeCountdown<0&&(i.tradeCountdown=3,a(),function(e,t,n){const s=()=>{e.tradeCountdown<=0||"trade"!==e.mode||(e.tradeCountdown--,n(),0===e.tradeCountdown?q(e,n):setTimeout(s,1e3))};setTimeout(s,1e3)}(i,0,a))}(i,a,c,l,r,e,0,s)}}(t,n,e,o,l)}),process.stdout.on("resize",()=>{e.resize(),o()})};const s=n(72222),o=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),S=n(29405),_=n(67748),x=n(87009),O=15e3,C=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,s,o,i]=await Promise.allSettled([(0,a.cached)("positions",O,()=>(0,d.getPositions)()),t?(0,a.cached)("theses",C,()=>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,s=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=s[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",O,()=>(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"===s.status&&s.value){const t=s.value;e.theses=t.theses||t||[]}if("fulfilled"===o.status&&o.value&&(e.orders=o.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}`,C,()=>t.getContext(e.id))));for(let t=0;t<e.theses.length;t++){const s=n[t];"fulfilled"===s.status&&s.value&&e.contexts.set(e.theses[t].id,s.value)}}if(N(e),await L(e),t)try{const n=await(0,a.cached)("feed",T,()=>t.getFeed(48)),s=n.entries||n.feed||n;Array.isArray(s)&&(e.signals=s)}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",C,()=>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,s=n.get(t);(!s||Math.abs(e.edge??0)>Math.abs(s.edge??0))&&n.set(t,e)}const s=new Set(e.positions.map(e=>e.ticker_symbol||e.ticker));e.edges=[...n.values()].filter(e=>!s.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),s=n-604800,o=await(0,a.cached)("candles",E,()=>(0,d.getBatchCandlesticks)({tickers:t,startTs:s,endTs:n}));for(const t of o)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"),s=t>0&&n>0?(t+n)/2:t||n,o=parseFloat(e.price?.close_dollars||"0")||s;return{close:Math.round(100*o),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":j(e,t);break;case"detail":(0,b.renderDetail)(e,(0,o.fullLayout)(e.cols,e.rows),t);break;case"liquidity":(0,v.renderLiquidity)(e,(0,o.fullLayout)(e.cols,e.rows),t);break;case"whatif":(0,S.renderWhatif)(e,(0,o.fullLayout)(e.cols,e.rows),t);break;case"trade":"detail"===t.prevMode?(0,b.renderDetail)(e,(0,o.fullLayout)(e.cols,e.rows),t):j(e,t),(0,_.renderTrade)(e,(0,o.fullLayout)(e.cols,e.rows),t)}e.flush()}function j(e,t){const n=e.cols<80,s=n?(0,o.narrowLayout)(e.cols,e.rows):(0,o.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 s)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 F(e,t,n,s,o,i,r,c){const l="positions"===o.focusArea?o.positions:"edges"===o.focusArea?o.edges:o.intents||[],d=Math.max(0,l.length-1);if("j"===e||n)o.selectedIndex=Math.min(o.selectedIndex+1,d),r();else if("k"===e||t)o.selectedIndex=Math.max(o.selectedIndex-1,0),r();else if(s){if("positions"===o.focusArea&&o.positions.length>0){const e=o.positions[o.selectedIndex];o.detailTicker=e?.ticker||null,o.prevMode="overview",o.mode="detail",r()}}else if("l"===e)o.prevMode="overview",o.mode="liquidity",o.liquiditySelectedIndex=0,U(o).then(r);else if("w"===e)o.theses.length>0&&(o.prevMode="overview",o.mode="whatif",o.whatifThesisId=o.theses[0].id,z(o).then(r));else if("b"===e)K(o,"buy"),r();else if("s"===e)K(o,"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"}})(o).then(r);else if("r"===e)(0,a.invalidateAll)(),R(o).then(r);else if("i"===e){if("edges"===o.focusArea&&o.edges.length>0){const e=o.edges[o.selectedIndex];if(e){const t=e.marketId||e.ticker||"";K(o,"buy"),o.tradeParams&&(o.tradeParams.ticker=t,o.tradeParams.side=e.direction||"yes",o.tradeParams.price=e.marketPrice||50),r()}}}else if("x"===e){if("intents"===o.focusArea&&o.intents.length>0){const e=o.intents[o.selectedIndex];if(e?.id){const t=M();t&&t.request("DELETE",`/api/intents/${e.id}`).then(()=>{(0,a.invalidateAll)(),R(o).then(r)}).catch(()=>{o.error="Failed to cancel intent",r()})}}}else if(e>="1"&&e<="9"){const t=parseInt(e)-1;t<o.theses.length&&(o.activeThesisIndex=t,r())}else"\t"===e&&("positions"===o.focusArea?o.focusArea="edges":"edges"===o.focusArea?o.focusArea="intents":o.focusArea="positions",o.selectedIndex=0,r())}function K(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 s=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||[]}))),o=[];for(const e of s)"fulfilled"===e.status&&Array.isArray(e.value)&&o.push(...e.value);e.liquidityData.set(t,[...o]);const i=8;for(let n=0;n<o.length;n+=i){const s=o.slice(n,n+i),r=await Promise.allSettled(s.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,s=(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),o=(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=s.length>0?s[0].price:0,t.bestAsk=o.length>0?100-o[0].price:100,t.spread=t.bestAsk-t.bestBid,t.totalDepth=s.slice(0,3).reduce((e,t)=>e+t.qty,0)+o.slice(0,3).reduce((e,t)=>e+t.qty,0)}e.liquidityData.set(t,[...o])}}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,s=Math.floor(.55*e),o=e-s-1,i=s+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:s,height:r},{name:"thesis",row:2,col:i,width:o,height:r},{name:"edges",row:2+r,col:0,width:s,height:a},{name:"signals",row:2+r,col:i,width:o,height:a},{name:"intents",row:2+r+a,col:0,width:s,height:c},{name:"orders",row:2+r+a,col:i,width:o,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,s=Math.floor(n/4);return[{name:"positions",row:2,col:0,width:e,height:s},{name:"edges",row:2+s,col:0,width:e,height:s},{name:"intents",row:2+2*s,col:0,width:e,height:s},{name:"thesis",row:2+3*s,col:0,width:e,height:n-3*s}]}},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,s="",o=""){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:s,bg:o}),i++}writeStyled(e,t,n){let s=t;for(const t of n)for(let n=0;n<t.text.length&&s<this.cols;n++)e>=0&&e<this.rows&&s>=0&&(this.back[e][s]={char:t.text[n],fg:t.fg||"",bg:t.bg||""}),s++}fill(e,t,n,s,o=" ",i="",r=""){for(let a=e;a<e+s&&a<this.rows;a++)for(let e=t;e<t+n&&e<this.cols;e++)a>=0&&e>=0&&(this.back[a][e]={char:o,fg:i,bg:r})}flush(){let e="",t="",n="";for(let s=0;s<this.rows;s++)for(let o=0;o<this.cols;o++){const i=this.front[s][o],r=this.back[s][o];i.char===r.char&&i.fg===r.fg&&i.bg===r.bg||(e+=`[${s+1};${o+1}H`,r.fg===t&&r.bg===n||(e+="[0m",r.fg&&(e+=r.fg),r.bg&&(e+=r.bg),t=r.fg,n=r.bg),e+=r.char)}e&&(e+="[0m",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("[2J")}}},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," ","",o);const a=i[n.mode]||i.overview,c="overview"===n.mode?n.focusArea.toUpperCase():"";let l=1;c&&(e.write(t,l,"●",s.CLR.emerald,o),l+=2,e.write(t,l,c,s.CLR.dim,o),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,s.CLR.emerald,o),l+=n.key.length,e.write(t,l," "+n.label,s.CLR.dim,o),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,s.CLR.red,o)}};const s=n(77096),o=(0,s.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,s.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",s.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?s.CLR.green:s.CLR.red,g=a.side||"yes";let f=1;e.writeStyled(t.row+f,i,[{text:(0,s.fit)(c,30),fg:s.CLR.white},{text:` ${g.toUpperCase()} `,fg:s.CLR.emerald},{text:` qty: ${l}`,fg:s.CLR.dim}]),f++,e.writeStyled(t.row+f,i,[{text:`Entry: ${d.toFixed(0)}¢`,fg:s.CLR.dim},{text:` Current: ${u.toFixed(0)}¢`,fg:s.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),o=Math.ceil((n.getTime()-Date.now())/864e5);e.write(t.row+f,i,`Expiry: ${n.toISOString().slice(0,10)} (${o}d)`,s.CLR.dim)}f++,(0,s.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 ($)",s.CLR.title),f++,(0,o.drawChart)(e,t.row+f,i,r,$,n,a),f+=$+1}else e.write(t.row+f,i,"No chart data available",s.CLR.dim),f+=2;f<t.height-5&&((0,s.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",s.CLR.title);let S=null;for(const[,e]of n.contexts){if((e?.edges||[]).some(e=>e.marketId===c||e.ticker===c)){S=e;break}}const _=[];!function e(t,n=0){for(const s of t)_.push({...s,depth:n}),s.children&&e(s.children,n+1)}(S?.causalTree?.nodes||[]);const x=_.filter(e=>e.depth<=1).slice(0,v-1);for(let t=0;t<x.length;t++){const n=x[t],o=" ".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:o+(0,s.fit)(r,k-o.length-5),fg:s.CLR.text},{text:(0,s.fit)(a,5,"right"),fg:s.CLR.emerald}])}0===x.length&&e.write(b+1,i," (no context data)",s.CLR.dim);const O=i+k+2;e.write(b,O,"Orderbook",s.CLR.title);const C=S?.edges?.find(e=>e.marketId===c||e.ticker===c),I=C?.orderbook;if(I){const t=I.bidPrice??I.bestBid??0,n=I.askPrice??I.bestAsk??0,o=I.spread??n-t;e.writeStyled(b+1,O,[{text:"Bid: ",fg:s.CLR.dim},{text:`${t}¢`,fg:s.CLR.green},{text:" Ask: ",fg:s.CLR.dim},{text:`${n}¢`,fg:s.CLR.red}]),e.writeStyled(b+2,O,[{text:"Spread: ",fg:s.CLR.dim},{text:`${o}¢`,fg:o<=2?s.CLR.green:o<=5?s.CLR.yellow:s.CLR.red}]),null!=I.bidDepth&&e.writeStyled(b+3,O,[{text:"Depth: ",fg:s.CLR.dim},{text:`bid ${I.bidDepth}`,fg:s.CLR.dim},{text:` / ask ${I.askDepth}`,fg:s.CLR.dim}])}else e.write(b+1,O," (no orderbook data)",s.CLR.dim)};const s=n(77096),o=n(14916)},30012:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderEdges=function(e,t,n){(0,s.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",s.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?s.CLR.green:"low"===w?s.CLR.yellow:s.CLR.dim,v=6,S=Math.abs(g)/u,_=Math.floor(S*v),x=S*v-_,O=Math.min(Math.floor(8*x),7),C=o[7].repeat(_)+(x>.1?o[O]:""),I=g>0?s.CLR.emerald:s.CLR.red,P=Math.max(r-28,8);e.writeStyled(l,i,[{text:`${h}${$} `,fg:p?s.CLR.white:s.CLR.dim},{text:(0,s.fit)(m,P),fg:p?s.CLR.white:s.CLR.text},{text:(0,s.fit)(y,5,"right"),fg:s.CLR.dim},{text:" "+(0,s.fit)(C,v),fg:I},{text:(0,s.fit)(f,5,"right"),fg:s.CLR.emerald},{text:k?` ${k}`:"",fg:b}])}};const s=n(77096),o="▏▎▍▌▋▊▉█"},87009:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderIntents=function(e,t,n){(0,s.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",s.CLR.dim,s.CLR.bgPanel),void e.write(t.row+2,i,"Press i on an edge to create one",s.CLR.veryDim,s.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?s.CLR.bgSelected:s.CLR.bgPanel;u&&e.fill(d,t.col+1,t.width-2,1," ","",p);const h=a.status||"pending",m=o[h]||s.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}/${$}`:`${$}`,S=Math.max(r-26,6);e.writeStyled(d,i,[{text:(0,s.fit)(h,9),fg:m,bg:p},{text:` ${g} `,fg:u?s.CLR.white:s.CLR.text,bg:p},{text:(0,s.fit)(y,S),fg:u?s.CLR.white:s.CLR.text,bg:p},{text:` ${f} ${v} ${b}`,fg:s.CLR.dim,bg:p}])}};const s=n(77096),o={pending:s.CLR.yellow,armed:s.CLR.emerald,triggered:s.CLR.white,executing:s.CLR.cyan,filled:s.CLR.green,partial:s.CLR.yellow,expired:s.CLR.veryDim,cancelled:s.CLR.veryDim,rejected:s.CLR.red}},82950:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderLiquidity=function(e,t,n){(0,s.drawBorder)(e,t,"LIQUIDITY SCANNER");const a=t.col+2,c=t.width-4;let l=1;const d=Object.keys(o.TOPIC_SERIES);let u=a;for(const o of d){const a=o===n.liquidityTopic,c=` ${o.toUpperCase()} `,d=a?s.CLR.emerald:s.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,s.fit)("Market",p),fg:s.CLR.title},{text:(0,s.fit)("Bid¢",8,"right"),fg:s.CLR.title},{text:(0,s.fit)("Ask¢",8,"right"),fg:s.CLR.title},{text:(0,s.fit)("Spread",8,"right"),fg:s.CLR.title},{text:(0,s.fit)("Depth",8,"right"),fg:s.CLR.title},{text:" ",fg:s.CLR.dim}]),l++;for(let n=a;n<a+c;n++)e.write(t.row+l,n,"─",s.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 s="Other";if(e.includes("-D")||e.includes("DAILY"))s="Daily";else if(e.includes("-W")||e.includes("WEEKLY"))s="Weekly";else if(e.includes("-M")||e.match(/-\d{2}(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d{2}/))s="Monthly";else{const e=n.expiration_time||n.close_time||"";if(e){const t=Math.ceil((new Date(e).getTime()-Date.now())/864e5);s=t<=7?"Weekly":t<=35?"Monthly":"Long-term"}}t.has(s)||t.set(s,[]),t.get(s).push(n)}const n=["Daily","Weekly","Monthly","Long-term","Other"],s=new Map;for(const e of n)t.has(e)&&s.set(e,t.get(e));return s}(h));let f=0;for(const[o,i]of g){if(l>=t.row+t.height-4)break;e.write(t.row+l,a,` ${o}`,s.CLR.title),l++;for(const o of i){if(l>=t.row+t.height-4)break;const i=n.liquiditySelectedIndex===f,r=i?"▸":" ",c=m.has(o.ticker)?"← held":"",d=o.ticker||"???",u=o.bestBid??o.yes_bid??0,h=o.bestAsk??o.yes_ask??0,g=o.spread??h-u,y=o.totalDepth??o.depth??0,$=g<=2?s.CLR.green:g<=5?s.CLR.yellow:s.CLR.red;e.writeStyled(t.row+l,a,[{text:r+" ",fg:i?s.CLR.emerald:s.CLR.dim},{text:(0,s.fit)(d,p-2),fg:s.CLR.text},{text:(0,s.fit)(String(u),8,"right"),fg:s.CLR.green},{text:(0,s.fit)(String(h),8,"right"),fg:s.CLR.red},{text:(0,s.fit)(String(g),8,"right"),fg:$},{text:(0,s.fit)(String(y),8,"right"),fg:s.CLR.dim},{text:c?` ${c}`:"",fg:s.CLR.emerald}]),l++,f++}}if(h.length>0){const o=Math.min(n.liquiditySelectedIndex,h.length-1),i=Array.from(g.values()).flat(),r=i[o]||i[0];if(r){const n=t.row+t.height-3;e.write(n,a,(0,s.fit)(`▶ ${r.ticker||""}`,c),s.CLR.emerald);const o=null!=r.slippage?`Slippage: ~${r.slippage}¢`:"",i=null!=r.edge?`Edge: ${r.edge>=0?"+":""}${r.edge}¢`:"";e.writeStyled(n+1,a,[{text:o?(0,s.fit)(o,20):"",fg:s.CLR.dim},{text:i?(0,s.fit)(i,20):"",fg:r.edge>=0?s.CLR.green:s.CLR.red}])}}};const s=n(77096),o=n(97325),i=(0,s.bgRgb)(30,30,35),r=(0,s.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," ","",o);const r=n.traditionalMarkets||[];if(0===r.length)return void e.write(t,1,"SimpleFunctions",s.CLR.dim,o);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?s.CLR.green:s.CLR.red;e.write(t,r,l,s.CLR.dim,o),e.write(t,r+l.length+1,p,s.CLR.text,o),e.write(t,r+l.length+1+p.length+1,h,m,o)}};const s=n(77096),o=(0,s.bgRgb)(12,12,16)},75757:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderOrders=function(e,t,n){(0,s.drawBorder)(e,t,"ORDERS");const o=t.col+2,i=(t.width,t.height-2);if(0===n.orders.length)return void e.write(t.row+1,o,"No resting orders",s.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,o,[{text:$,fg:y?s.CLR.yellow:s.CLR.dim},{text:(0,s.fit)(c,12),fg:s.CLR.text},{text:(0,s.fit)(h,10),fg:s.CLR.dim},{text:(0,s.fit)(p,10),fg:"filled"===p?s.CLR.green:s.CLR.dim},{text:(0,s.fit)(f,4,"right"),fg:y?s.CLR.yellow:s.CLR.dim}])}};const s=n(77096)},3322:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderPortfolio=function(e,t,n){(0,s.drawBorder)(e,t,"POSITIONS");const o=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,o,"No positions",s.CLR.dim,s.CLR.bgPanel),void e.write(t.row+2,o,"sf buy TICKER QTY --price CENTS",s.CLR.veryDim,s.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?s.CLR.bgSelected:s.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?s.CLR.purple:s.CLR.cyan;if(e.writeStyled(d,o,[{text:g+" ",fg:f,bg:h},{text:(0,s.fit)(m,Math.min(i-2,28)),fg:p?s.CLR.white:s.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?s.CLR.green:s.CLR.red,p=[{text:` ${(0,s.compact)(t)} @ ${i}¢`,fg:s.CLR.dim,bg:h},{text:` → ${r}¢ `,fg:s.CLR.dim,bg:h},{text:(0,s.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,s.sparkline)(e,e=>e>=0?s.CLR.green:s.CLR.red);for(const e of n)p.push({...e,bg:h})}e.writeStyled(d+1,o,p)}a+=2}};const s=n(77096)},50511:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderSignals=function(e,t,n){(0,s.drawBorder)(e,t,"FEED");const o=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,o,"No recent signals",s.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?s.CLR.green:s.CLR.red,y=m?`${l>0?"+":""}${Math.round(100*l)}%`:"",$=i-14;e.writeStyled(c,o,[{text:p,fg:s.CLR.veryDim},{text:` ${g}`,fg:m?f:s.CLR.dim},{text:(0,s.fit)(y,5,"right"),fg:m?f:s.CLR.dim},{text:" "+(0,s.fit)(d,$),fg:s.CLR.text}])}};const s=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," ","",o);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,s=e.quantity??0;a+=(n-t)*s,c+=t*s}const l=a/100,d=c>0?a/c*100:0,u=l>=0?s.CLR.green:s.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 ",s.CLR.dim,o),p+=4,e.write(t,p,m,u,o),p+=m.length+1,e.write(t,p,g,u,o),p+=g.length+1,e.write(t,p,i,s.CLR.veryDim,o),p+=2,e.write(t,p,`$${n.balance.toFixed(2)}`,s.CLR.text,o),p+=`$${n.balance.toFixed(2)}`.length+1,n.theses.length>0){e.write(t,p,i,s.CLR.veryDim,o),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,s.CLR.dim,o),p+=a.length+1,e.write(t,p,c,s.CLR.emerald,o),p+=c.length+1,n.theses.length>1){const i=`[${(n.activeThesisIndex||0)+1}/${n.theses.length}]`;e.write(t,p,i,s.CLR.veryDim,o),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,s.CLR.veryDim,o),p+=2;const n=`${f.length} intent${f.length>1?"s":""}`;e.write(t,p,n,s.CLR.emerald,o),p+=n.length+1}if(null!==n.exchangeOpen){e.write(t,p,i,s.CLR.veryDim,o),p+=2;const r=n.exchangeOpen?"OPEN":"CLOSED",a=n.exchangeOpen?s.CLR.green:s.CLR.red;e.write(t,p,r,a,o)}const y=(new Date).toISOString().slice(11,19)+" UTC";e.write(t,r-y.length-1,y,s.CLR.veryDim,o)};const s=n(77096),o=(0,s.bgRgb)(16,16,20),i="│"},21704:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderThesis=function(e,t,n){(0,s.drawBorder)(e,t,"THESIS");const o=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=s.CLR.green,g=`+${Math.round(100*p)}`):p<=-.02?(h="▼",m=s.CLR.red,g=`${Math.round(100*p)}`):(h="─",m=s.CLR.dim,g=p>=0?`+${Math.round(100*p)}`:`${Math.round(100*p)}`);const f=i-10;e.writeStyled(n,o,[{text:(0,s.fit)(l,f),fg:s.CLR.text},{text:(0,s.fit)(u,5,"right"),fg:s.CLR.white},{text:` ${h}`,fg:m},{text:(0,s.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,o,[{text:(0,s.fit)(l,p),fg:s.CLR.dim},{text:" "+u,fg:s.CLR.veryDim}])}}};const s=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," ","",o),(0,s.drawBorder)(e,p,"TRADE");const h=d+2,m=c-4;let g=1;const f="buy"===a.action?s.CLR.green:s.CLR.red,y="buy"===a.action?"BUY":"SELL";e.writeStyled(u+g,h,[{text:y+" ",fg:f},{text:a.side.toUpperCase()+" ",fg:s.CLR.emerald},{text:a.ticker,fg:s.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:s.CLR.dim},{text:`${w}¢`,fg:s.CLR.green},{text:" Ask: ",fg:s.CLR.dim},{text:`${k}¢`,fg:s.CLR.red}]),g+=2;const b="qty"===n.tradeField,v=b?r:i;e.write(u+g,h,"Quantity:",s.CLR.dim,o),e.write(u+g,h+12,(0,s.fit)(String(a.qty),10),b?s.CLR.emerald:s.CLR.text,v),b&&e.write(u+g,h+22," ◀",s.CLR.emerald,o);g++;const S="price"===n.tradeField,_=S?r:i;e.write(u+g,h,"Price (¢):",s.CLR.dim,o),e.write(u+g,h+12,(0,s.fit)(String(a.price),10),S?s.CLR.emerald:s.CLR.text,_),S&&e.write(u+g,h+22," ◀",s.CLR.emerald,o);g+=2;const x=a.qty*a.price/100,O=a.qty,C=O-x;e.write(u+g,h,"Preview:",s.CLR.title,o),g++,e.writeStyled(u+g,h,[{text:`Max cost: $${x.toFixed(2)}`,fg:s.CLR.dim}]),g++,e.writeStyled(u+g,h,[{text:`Max payout: $${O.toFixed(2)}`,fg:s.CLR.dim}]),g++,e.writeStyled(u+g,h,[{text:"Profit: ",fg:s.CLR.dim},{text:`$${C.toFixed(2)}`,fg:C>=0?s.CLR.green:s.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:s.CLR.dim},{text:`${t>=0?"+":""}${t}¢`,fg:t>=0?s.CLR.green:s.CLR.red}]),g++}const P=Math.max(0,a.price-w);P>0&&(e.writeStyled(u+g,h,[{text:"Slippage: ",fg:s.CLR.dim},{text:`~${P}¢`,fg:s.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,s.CLR.yellow,o)}else 0===n.tradeCountdown?e.write(u+g,h+Math.floor((m-12)/2)," EXECUTING ",s.CLR.white,(0,s.bgRgb)(16,120,80)):e.write(u+g,h+Math.floor((m-24)/2),"Press Enter to confirm",s.CLR.dim,o)};const s=n(77096),o=(0,s.bgRgb)(18,18,22),i=(0,s.bgRgb)(30,30,35),r=(0,s.bgRgb)(16,50,40)},29405:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderWhatif=function(e,t,n){(0,s.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.',s.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:",s.CLR.title),a++,0===l.length)e.write(t.row+a,i," (no scenarios available)",s.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?o:"";e.write(t.row+a,i,(0,s.fit)(`${p}${h}`,r),u?s.CLR.white:s.CLR.text,m),a++}a++}for(let n=i;n<i+r;n++)e.write(t.row+a,n,"─",s.CLR.borderDim);a++;const u=i,p=i+d+3;e.write(t.row+a,u,(0,s.fit)("BEFORE",d),s.CLR.title),e.write(t.row+a,p,(0,s.fit)("AFTER",d),s.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:s.CLR.dim},{text:g,fg:s.CLR.text}]),e.writeStyled(t.row+a,p,[{text:"Confidence: ",fg:s.CLR.dim},{text:f,fg:s.CLR.text},{text:` (${$})`,fg:y>=0?s.CLR.green:s.CLR.red}]),a++;const w=h.edges||[],k=m.edges||[];e.write(t.row+a,u,"Edges:",s.CLR.dim),e.write(t.row+a,p,"Edges:",s.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 o=w[n],i=k[n];if(o){const n=(o.market||o.ticker||"").slice(0,d-10),i=`${o.edge>=0?"+":""}${o.edge}`;e.writeStyled(t.row+a,u,[{text:(0,s.fit)(n,d-8),fg:s.CLR.text},{text:(0,s.fit)(i,6,"right"),fg:o.edge>=0?s.CLR.green:s.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-(o?.edge??0),l=c>=0?`+${c}`:`${c}`;e.writeStyled(t.row+a,p,[{text:(0,s.fit)(n,d-14),fg:s.CLR.text},{text:(0,s.fit)(r,6,"right"),fg:i.edge>=0?s.CLR.green:s.CLR.red},{text:(0,s.fit)(l,6,"right"),fg:c>=0?s.CLR.green:s.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:s.CLR.dim},{text:`${n>=0?"+":""}$${Math.abs(n).toFixed(2)}`,fg:n>=0?s.CLR.green:s.CLR.red}])}};const s=n(77096),o=(0,s.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()],s=t.getDate(),o=t.getHours().toString().padStart(2,"0");return`${n} ${s} ${o}:${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:"[0m",bold:"[1m",dim:"[2m",red:"[31m",green:"[32m",yellow:"[33m",blue:"[34m",magenta:"[35m",cyan:"[36m",white:"[37m",gray:"[90m"}},73600:function(e,t,n){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.resolvePath=l,t.wsRead=function(e){try{const t=l(e);if(!o.default.existsSync(t))return{ok:!1,content:`File not found: ${e}`};const n=o.default.statSync(t);if(n.isDirectory())return{ok:!1,content:`${e} is a directory, use fs_list`};if(n.size>524288){const e=o.default.openSync(t,"r"),n=Buffer.alloc(524288),s=o.default.readSync(e,n,0,n.length,0);return o.default.closeSync(e),{ok:!0,content:n.slice(0,s).toString("utf-8")+"\n... [truncated at 512KB]"}}return{ok:!0,content:o.default.readFileSync(t,"utf-8")}}catch(e){return{ok:!1,content:e.message}}},t.wsWrite=function(e,t,n){try{c();const s=l(e);return o.default.mkdirSync(i.default.dirname(s),{recursive:!0}),n?o.default.appendFileSync(s,t,"utf-8"):o.default.writeFileSync(s,t,"utf-8"),{ok:!0,message:`${n?"Appended to":"Wrote"} ${e}`}}catch(e){return{ok:!1,message:e.message}}},t.wsList=function(e,t){try{c();const n=l(e||"");if(!o.default.existsSync(n))return{ok:!1,entries:[],message:`Directory not found: ${e||"/"}`};if(!o.default.statSync(n).isDirectory())return{ok:!1,entries:[],message:`${e} is not a directory`};const s=o.default.readdirSync(n).map(e=>{const t=i.default.join(n,e);return o.default.statSync(t).isDirectory()?`${e}/`:e});if(t){const e=function(e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${t}$`,"i")}(t);return{ok:!0,entries:s.filter(t=>e.test(t.replace(/\/$/,"")))}}return{ok:!0,entries:s}}catch(e){return{ok:!1,entries:[],message:e.message}}},t.wsSearch=function(e,t,n=50){try{c();const s=l(t||"");if(!o.default.existsSync(s))return{ok:!1,matches:[],message:`Path not found: ${t||"/"}`};const r=new RegExp(e,"gi"),d=[];function u(e){if(d.length>=n)return;const t=o.default.readdirSync(e);for(const s of t){if(d.length>=n)return;const t=i.default.join(e,s),c=o.default.statSync(t);if(c.isDirectory())u(t);else if(c.size<1048576){const e=o.default.readFileSync(t,"utf-8").split("\n");for(let s=0;s<e.length;s++){if(r.test(e[s])){const o=i.default.relative(a,t);if(d.push({file:o,line:s+1,text:e[s].trim().slice(0,200)}),d.length>=n)return}r.lastIndex=0}}}}if(o.default.statSync(s).isDirectory())u(s);else{const p=o.default.readFileSync(s,"utf-8").split("\n"),h=i.default.relative(a,s);for(let m=0;m<p.length&&!(r.test(p[m])&&(d.push({file:h,line:m+1,text:p[m].trim().slice(0,200)}),d.length>=n));m++)r.lastIndex=0}return{ok:!0,matches:d}}catch(g){return{ok:!1,matches:[],message:g.message}}},t.wsDelete=function(e){try{const t=l(e);if(!o.default.existsSync(t))return{ok:!1,message:`Not found: ${e}`};if(o.default.statSync(t).isDirectory()){if(o.default.readdirSync(t).length>0)return{ok:!1,message:`Directory not empty: ${e}`};o.default.rmdirSync(t)}else o.default.unlinkSync(t);return{ok:!0,message:`Deleted ${e}`}}catch(e){return{ok:!1,message:e.message}}},t.getWorkspaceRoot=function(){return c(),a},t.appendContext=function(e,t){o.default.mkdirSync(d,{recursive:!0});const n=i.default.join(d,`${e}.jsonl`);o.default.appendFileSync(n,JSON.stringify(t)+"\n","utf-8")},t.readRecentContext=function(e,t=50){const n=i.default.join(d,`${e}.jsonl`);if(!o.default.existsSync(n))return[];const s=o.default.readFileSync(n,"utf-8"),r=s.trim().split("\n").filter(e=>e.length>0),a=r.slice(-t),c=[];for(const e of a)try{c.push(JSON.parse(e))}catch{}return c},t.listContextSessions=function(){return o.default.existsSync(d)?o.default.readdirSync(d).filter(e=>e.endsWith(".jsonl")).map(e=>e.replace(".jsonl","")):[]};const o=s(n(79896)),i=s(n(16928)),r=s(n(70857)),a=i.default.join(r.default.homedir(),".sf","workspace");function c(){o.default.mkdirSync(a,{recursive:!0})}function l(e){const t=e.replace(/\\/g,"/").replace(/^\/+/,""),n=i.default.resolve(a,t);if(!n.startsWith(a))throw new Error(`Path escapes workspace: ${e}`);return n}const d=i.default.join(a,"context")},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:s}=n(49154),{Command:o}=n(34348),{CommanderError:i,InvalidArgumentError:r}=n(41135),{Help:a}=n(79754),{Option:c}=n(45240);t.program=new o,t.createCommand=e=>new o(e),t.createOption=(e,t)=>new c(e,t),t.createArgument=(e,t)=>new s(e,t),t.Command=o,t.Option=c,t.Argument=s,t.Help=a,t.CommanderError=i,t.InvalidArgumentError=r,t.InvalidOptionArgumentError=r},49154:(e,t,n)=>{const{InvalidArgumentError:s}=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 s(`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 s=n(78474).EventEmitter,o=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 s{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 s=t,o=n;"object"==typeof s&&null!==s&&(o=s,s=null),o=o||{};const[,i,r]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(i);return s&&(a.description(s),a._executableHandler=!0),o.isDefault&&(this._defaultCommandName=a._name),a._hidden=!(!o.noHelp&&!o.hidden),a._executableFile=o.executableFile||null,r&&a.arguments(r),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),s?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,s){const o=this.createArgument(e,t);return"function"==typeof n?o.default(s).argParser(n):o.default(n),this.addArgument(o),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,s]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",i=this.createCommand(n);return i.helpOption(!1),s&&i.arguments(s),o&&i.description(o),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,s=t.slice(0,n);return this._storeOptionsAsProperties?s[n]=this:s[n]=this.opts(),s.push(this),e.apply(this,s)},this}createOption(e,t){return new p(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(e){if("commander.invalidArgument"===e.code){const t=`${s} ${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 s=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}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 s=(t,s,o)=>{null==t&&void 0!==e.presetArg&&(t=e.presetArg);const i=this.getOptionValue(n);null!==t&&e.parseArg?t=this._callParseArg(e,t,i,s):null!==t&&e.variadic&&(t=e._concatValue(t,i)),null==t&&(t=!e.negate&&(!(!e.isBoolean()&&!e.optional)||"")),this.setOptionValueWithSource(n,t,o)};return this.on("option:"+t,t=>{const n=`error: option '${e.flags}' argument '${t}' is invalid.`;s(t,n,"cli")}),e.envVar&&this.on("optionEnv:"+t,t=>{const n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;s(t,n,"env")}),this}_optionEx(e,t,n,s,o){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 s)i.default(o).argParser(s);else if(s instanceof RegExp){const e=s;s=(t,n)=>{const s=e.exec(t);return s?s[0]:n},i.default(o).argParser(s)}else i.default(s);return this.addOption(i)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}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 s=[".js",".ts",".tsx",".mjs",".cjs"];function c(e,t){const n=i.resolve(e,t);if(r.existsSync(n))return n;if(s.includes(i.extname(t)))return;const o=s.find(e=>r.existsSync(`${n}${e}`));return o?`${n}${o}`: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=s.includes(i.extname(u)),"win32"!==a.platform?n?(t.unshift(u),t=f(a.execArgv).concat(t),l=o.spawn(a.argv[0],t,{stdio:"inherit"})):l=o.spawn(u,t,{stdio:"inherit"}):(t.unshift(u),t=f(a.execArgv).concat(t),l=o.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 s=this._findCommand(e);let o;return s||this.help({error:!0}),o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(!s._executableHandler)return s._parseCommand(t,n);this._executeSubCommand(s,t.concat(n))}),o}_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 s=t;if(null!==t&&e.parseArg){const o=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;s=this._callParseArg(e,t,n,o)}return s};this._checkNumberOfArguments();const t=[];this.registeredArguments.forEach((n,s)=>{let o=n.defaultValue;n.variadic?s<this.args.length?(o=this.args.slice(s),n.parseArg&&(o=o.reduce((t,s)=>e(n,s,t),n.defaultValue))):void 0===o&&(o=[]):s<this.args.length&&(o=this.args[s],n.parseArg&&(o=e(n,o,n.defaultValue))),t[s]=o}),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 s=[];return this._getCommandAndAncestors().reverse().filter(e=>void 0!==e._lifeCycleHooks[t]).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{s.push({hookedCommand:e,callback:t})})}),"postAction"===t&&s.reverse(),s.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return void 0!==this._lifeCycleHooks[n]&&this._lifeCycleHooks[n].forEach(e=>{s=this._chainOrCall(s,()=>e(this,t))}),s}_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 s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){let n;return s(),this._processArguments(),n=this._chainOrCallHooks(n,"preAction"),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(o,e,t)})),n=this._chainOrCallHooks(n,"postAction"),n}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,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():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),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 s=t;const o=e.slice();function i(e){return e.length>1&&"-"===e[0]}let r=null;for(;o.length;){const e=o.shift();if("--"===e){s===n&&s.push(e),s.push(...o);break}if(!r||i(e)){if(r=null,i(e)){const t=this._findOption(e);if(t){if(t.required){const e=o.shift();void 0===e&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,e)}else if(t.optional){let e=null;o.length>0&&!i(o[0])&&(e=o.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()}`),o.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)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&0===t.length&&0===n.length){if(this._findCommand(e)){t.push(e),o.length>0&&n.push(...o);break}if(this._getHelpCommand()&&e===this._getHelpCommand().name()){t.push(e),o.length>0&&t.push(...o);break}if(this._defaultCommandName){n.push(e),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){s.push(e),o.length>0&&s.push(...o);break}s.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||{},s=n.exitCode||1,o=n.code||"commander.error";this._exit(s,o,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),s=this.options.find(e=>e.negate&&t===e.attributeName()),o=this.options.find(e=>!e.negate&&t===e.attributeName());return s&&(void 0===s.presetArg&&!1===n||void 0!==s.presetArg&&n===s.presetArg)?s:o||e},s=e=>{const t=n(e),s=t.attributeName();return"env"===this.getOptionValueSource(s)?`environment variable '${t.envVar}'`:`option '${t.flags}'`},o=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{const e=s.createHelp().visibleOptions(s).filter(e=>e.long).map(e=>e.long);n=n.concat(e),s=s.parent}while(s&&!s._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",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(s,{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 s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.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 s=this.helpInformation(n);if(t&&(s=t(s),"string"!=typeof s&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),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 s=`${e}Help`;return this.on(s,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,s="127.0.0.1",o="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])?o=n[3]:s=n[3]):null!==(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(t=n[1],s=n[3],o=n[4]),t&&"0"!==o?`${t}=${s}:${parseInt(o)+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:s}=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 s=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);s||o?n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!s&&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=>s(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),s=t.helpWidth||80;function o(e,o){if(o){const i=`${e.padEnd(n+2)}${o}`;return t.wrap(i,s-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,s,0),""]));const c=t.visibleArguments(e).map(e=>o(t.argumentTerm(e),t.argumentDescription(e)));c.length>0&&(r=r.concat(["Arguments:",i(c),""]));const l=t.visibleOptions(e).map(e=>o(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=>o(t.optionTerm(e),t.optionDescription(e)));n.length>0&&(r=r.concat(["Global Options:",i(n),""]))}const d=t.visibleCommands(e).map(e=>o(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,s=40){const o=new RegExp("[\\n][ \\f\\t\\v - \ufeff]+");if(e.match(o))return e;const i=t-n;if(i<s)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:s}=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 s=e.split(/[ |,]+/);s.length>1&&!/^[[<]/.test(s[1])&&(t=s.shift());n=s.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 s(`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 s=this.negativeOptions.get(n).presetArg,o=void 0!==s&&s;return t.negate===(o===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 s=1;s<=t.length;s++)for(let o=1;o<=e.length;o++){let i=1;i=e[o-1]===t[s-1]?0:1,n[o][s]=Math.min(n[o-1][s]+1,n[o][s-1]+1,n[o-1][s-1]+i),o>1&&s>1&&e[o-1]===t[s-2]&&e[o-2]===t[s-1]&&(n[o][s]=Math.min(n[o][s],n[o-2][s-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 s=e.startsWith("--");s&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let o=[],i=3;return t.forEach(t=>{if(t.length<=1)return;const s=n(e,t),r=Math.max(e.length,t.length);(r-s)/r>.4&&(s<i?(i=s,o=[t]):s===i&&o.push(t))}),o.sort((e,t)=>e.localeCompare(t)),s&&(o=o.map(e=>`--${e}`)),o.length>1?`\n(Did you mean one of ${o.join(", ")}?)`:1===o.length?`\n(Did you mean ${o[0]}?)`:""}}},t={};function n(s){var o=t[s];if(void 0!==o)return o.exports;var i=t[s]={exports:{}},r=!0;try{e[s].call(i.exports,i,i.exports,n),r=!1}finally{r&&delete t[s]}return i.exports}n.m=e,(()=>{var e,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;n.t=function(s,o){if(1&o&&(s=this(s)),8&o)return s;if("object"==typeof s&&s){if(4&o&&s.__esModule)return s;if(16&o&&"function"==typeof s.then)return s}var i=Object.create(null);n.r(i);var r={};e=e||[null,t({}),t([]),t(t)];for(var a=2&o&&s;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach(e=>r[e]=()=>s[e]);return r.default=()=>s,n.d(i,r),i}})(),n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce((t,s)=>(n.f[s](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,s)=>{e[t]||(t=>{var s=t.modules,o=t.ids,i=t.runtime;for(var r in s)n.o(s,r)&&(n.m[r]=s[r]);i&&i(n);for(var a=0;a<o.length;a++)e[o[a]]=1})(require("./"+n.u(t)))}})();var s={};(()=>{"use strict";var e=s;Object.defineProperty(e,"__esModule",{value:!0});const t=n(18909),o=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),S=n(28423),_=n(96616),x=n(44040),O=n(45475),C=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),j=n(69903),F=n(35344),K=n(71783),q=n(91993),U=n(81466),z=n(50869),H=n(87604),B=n(65240),W=n(23017),J=n(84436),X=n(15472),G=n(52072),Y=n(33192),V=n(30896),Q=n(64115),Z=n(93402),ee=n(72124),te=n(99236);(0,o.applyConfig)(),(0,Z.checkForUpdates)();const ne=new t.Command,se='\n[1mSimpleFunctions CLI[22m — prediction market thesis agent\n\n[1mUsage:[22m sf <command> [options]\n sf <command> --help for detailed options\n\n[1mSetup[22m\n [36mlogin[39m Browser login (recommended)\n [36mlogout[39m Clear saved credentials\n [36msetup[39m Interactive config wizard (power users)\n [36msetup --check[39m Show config status\n [36msetup --polymarket[39m Configure Polymarket wallet\n [36mupdate[39m Update CLI to latest version\n\n[1mThesis[22m\n [36mlist[39m List all theses\n [36mget[39m <id> Full thesis details\n [36mcontext[39m [id] [--json] Market snapshot (no id) or thesis context (with id)\n [36mcreate[39m "thesis" Create a new thesis\n [36msignal[39m <id> "content" Inject a signal\n [36mevaluate[39m <id> Trigger deep evaluation\n [36maugment[39m <id> Evolve causal tree with new nodes\n [36mpublish[39m / [36munpublish[39m <id> Manage public visibility\n [36mheartbeat[39m <id> View/configure heartbeat settings & costs\n\n[1mWorld Model[22m [2m(no auth)[22m\n [36mworld[39m Real-time world state (~800 tokens, prediction index + markets)\n [36mworld --delta[39m What changed since last check (~30-50 tokens)\n [36mworld --focus[39m energy,geo Deep coverage on specific topics\n [36mideas[39m S&T-style trade ideas: conviction, catalyst, direction, risk\n\n[1mSearch[22m\n [36mquery[39m "question" LLM-enhanced market knowledge search [2m(no auth)[22m\n [36mmarkets[39m Traditional markets: SPY, VIX, bonds, gold, oil [2m(no auth)[22m\n\n[1mMarkets[22m\n [36mscan[39m "keywords" Search Kalshi + Polymarket\n [36mscan[39m --series TICKER Browse a Kalshi series\n [36medges[39m [--json] Top edges across all theses\n [36mwatch[39m [query] [mode] Watch markets (modes: orderbook, flow, cross-venue, all)\n [36mwhatif[39m <id> What-if scenario analysis\n [36mliquidity[39m [topic] Orderbook liquidity scanner\n [36mbook[39m <ticker> [ticker2...] Orderbook depth for specific markets\n [36mexplore[39m [slug] Browse public theses\n [36mforecast[39m <event> Market distribution (P50/P75/P90)\n\n[1mShare[22m [2m(any command with --share generates a short URL)[22m\n [36mscan[39m "gold" --share Share scan results\n [36mquery[39m "fed rate" --share Share query results\n [36mcontext[39m --share Share global context snapshot\n\n[1mPortfolio[22m\n [36mpositions[39m Kalshi + Polymarket positions\n [36mbalance[39m Account balance\n [36morders[39m Resting orders\n [36mfills[39m Recent trade fills\n [36msettlements[39m Settled contracts with P&L\n [36mperformance[39m P&L over time\n [36mdashboard[39m Interactive TUI overview\n\n[1mIntents[22m [2m(declarative execution — the single gateway for all orders)[22m\n [36mintent buy[39m <ticker> <qty> Create buy intent with trigger conditions\n [36mintent sell[39m <ticker> <qty> Create sell intent\n [36mintent list[39m Active intents (--all for history)\n [36mintent status[39m <id> Detailed status + fills\n [36mintent cancel[39m <id> Cancel an intent\n\n[1mTrading[22m [2m(requires sf setup --enable-trading)[22m\n [36mbuy[39m <ticker> <qty> Buy contracts (direct, no intent)\n [36msell[39m <ticker> <qty> Sell contracts (direct, no intent)\n [36mcancel[39m [orderId] Cancel order(s)\n [36mrfq[39m <ticker> <qty> Request for quote\n\n[1mRuntime[22m\n [36mruntime start[39m Start execution daemon (evaluates triggers, places orders)\n [36mruntime stop[39m Stop daemon\n [36mruntime status[39m Active intents + runtime state\n\n[1mInteractive[22m\n [36magent[39m [id] Agent with natural language + tools (workspace, voice, self-wake)\n [36mprompt[39m [id] Dynamic system prompt for any agent\n [36mtelegram[39m Telegram bot (text + voice messages)\n\n Agent slash commands: /voice /tree /edges /pos /eval /switch /model /help /exit\n\n[1mX / Twitter[22m\n [36mx[39m "query" Search X discussions (summary + raw mode)\n [36mx-volume[39m "query" Discussion volume and velocity trend\n [36mx-news[39m "query" X news stories (Grok-aggregated)\n [36mx-account[39m @username Recent posts from a specific account\n\n[1mInfo[22m\n [36mfeed[39m Evaluation history stream\n [36mdelta[39m <id> Changes since timestamp\n [36mmilestones[39m Upcoming Kalshi events\n [36mschedule[39m Exchange status\n [36mannouncements[39m Exchange announcements\n [36mhistory[39m <ticker> Historical market data\n';ne.name("sf").description("SimpleFunctions CLI — prediction market thesis agent").version("1.7.28").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 se;const{Help:s}=n(18909);return(new s).formatHelp(e,t)}}).action(async()=>{await async function(){if(!process.stdin.isTTY)return void console.log(se);const e=await Promise.resolve().then(n.t.bind(n,23785,23));if((0,o.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{return void await(0,f.agentCommand)(void 0,{})}console.log(),console.log(" [1mSimpleFunctions[22m — prediction market intelligence"),console.log(),(0,o.isConfigured)()?console.log(" [2mYou have no active theses.[22m"):console.log(" [2mNo login needed to explore.[22m");console.log();const t=e.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),s=await new Promise(e=>{t.question(" What's your market view? (keyword or thesis)\n [36m>[39m ",n=>{t.close(),e(n.trim())})});if(!s)return void console.log(se);let r=s.replace(/[^\w\s]/g," ").split(/\s+/).filter(e=>e.length>2).slice(0,5).join(" ");r||(r=s.trim().slice(0,40));console.log(),console.log(` [2mScanning Kalshi + Polymarket for: "${r}"...[22m`),console.log();try{const{scanCommand:e}=await Promise.resolve().then(n.bind(n,46183));await e(r,{json:!1})}catch(e){console.error(` [31mScan failed: ${e.message}[39m`)}console.log(),(0,o.isConfigured)()?(console.log(" [2mWant to monitor this thesis 24/7?[22m"),console.log(` [36msf create[39m "${s.slice(0,60)}"`)):(console.log(" [2mWant 24/7 monitoring + edge detection?[22m"),console.log(" [36msf setup[39m to get started (2 min)"));console.log()}()});const oe=new Set(["setup","login","logout","help","status","update","scan","explore","query","context","markets","watch","milestones","forecast","settlements","balance","orders","fills","schedule","announcements","history","liquidity","book","prompt","agent","world","ideas","sf"]);async function ie(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,te.die)(t)}}ne.hook("preAction",(e,t)=>{const n=t.name();if(oe.has(n))return;if(!(e.optsWithGlobals?.()||e.opts()).apiKey&&!(0,o.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. [36msf login[39m Browser login (30 sec, recommended)"),console.log(" 2. [36msf setup[39m Interactive wizard (2 min)"),console.log(" 3. [36msf --api-key KEY[39m Pass inline"),console.log(),console.log(" [2mGet a key at: [36mhttps://simplefunctions.dev/dashboard/keys[22m"),console.log(' [2mNo key? Try [36msf scan "oil"[22m[2m — works without login.[22m')),console.log(),process.exit(1)}}),ne.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 ie(()=>(0,y.setupCommand)({check:e.check,reset:e.reset,key:e.key,enableTrading:e.enableTrading,disableTrading:e.disableTrading,kalshi:e.kalshi,polymarket:e.polymarket}))}),ne.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 ie(()=>(0,z.loginCommand)({apiUrl:n.apiUrl,force:e.force}))}),ne.command("logout").description("Clear saved credentials").action(async()=>{await ie(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(` ${te.c.dim}Run ${te.c.cyan}sf login${te.c.dim} to re-authenticate.${te.c.reset}\n`)):console.log(`\n ${te.c.dim}Not logged in.${te.c.reset}\n`)})}),ne.command("update").description("Update CLI to latest version").action(async()=>{await ie(()=>(0,Q.updateCommand)())}),ne.command("status").description("Health check: verify API, auth, Kalshi, Polymarket connections").option("--json","JSON output").action(async e=>{await ie(()=>(0,ee.statusCommand)({json:e.json}))}),ne.command("list").description("List all theses").option("--json","JSON output").action(async(e,t)=>{const n=t.optsWithGlobals();await ie(()=>(0,r.listCommand)({json:e.json,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.command("get <id>").description("Get full thesis details").option("--json","Output raw JSON").action(async(e,t,n)=>{const s=n.optsWithGlobals();await ie(()=>(0,a.getCommand)(e,{json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.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 s=n.optsWithGlobals();await ie(()=>(0,c.contextCommand)(e,{json:t.json,share:t.share,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.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 s=n.optsWithGlobals();await ie(()=>(0,l.createCommand)(e,{async:t.async,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.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,s)=>{const o=s.optsWithGlobals();await ie(()=>(0,d.signalCommand)(e,t,{type:n.type,json:n.json,apiKey:o.apiKey,apiUrl:o.apiUrl}))}),ne.command("evaluate <id>").description("Trigger a deep evaluation (heavy model, force-heavy mode)").action(async(e,t,n)=>{const s=n.optsWithGlobals();await ie(()=>(0,u.evaluateCommand)(e,{apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.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 s=n.optsWithGlobals();await ie(()=>{const n=new i.SFClient(s.apiKey,s.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})})}),ne.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 s=n.optsWithGlobals(),o=e||"";o||t.series||t.market||(console.error('Usage: sf scan "keywords" OR sf scan --series TICKER OR sf scan --market TICKER'),process.exit(1)),await ie(()=>(0,p.scanCommand)(o,{series:t.series,market:t.market,venue:t.venue,json:t.json,share:t.share,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.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 ie(()=>(0,h.watchCommand)(e,t,{interval:n.interval,json:n.json,thesis:n.thesis,smart:n.smart,execute:n.execute}))}),ne.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 ie(()=>(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}))}),ne.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 ie(()=>(0,m.positionsCommand)({json:e.json,thesis:e.thesis,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.command("agent [thesisId]").description("Interactive agent with 50+ tools, workspace filesystem, voice I/O, and self-wake").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)").option("--once <prompt>","Single-shot: ask one question, print response, exit").action(async(e,t,n)=>{n.optsWithGlobals();await ie(()=>(0,f.agentCommand)(e,{model:t.model,modelKey:t.modelKey,newSession:t.new,noTui:t.plain||!!t.once,once:t.once}))}),ne.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 s=n.optsWithGlobals();await ie(()=>(0,$.publishCommand)(e,{slug:t.slug,description:t.description,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.command("unpublish <thesisId>").description("Remove a thesis from public viewing").action(async(e,t,n)=>{const s=n.optsWithGlobals();await ie(()=>(0,$.unpublishCommand)(e,{apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.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 ie(()=>(0,w.exploreCommand)(e,{json:t.json,share:t.share}))}),ne.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 ie(()=>(0,k.dashboardCommand)({json:e.json,once:e.once,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.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 ie(()=>(0,v.milestonesCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.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 ie(()=>(0,S.forecastCommand)(e,t))}),ne.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 ie(()=>(0,_.settlementsCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.command("balance").description("Kalshi account balance").option("--json","JSON output").action(async e=>{await ie(()=>(0,x.balanceCommand)(e))}),ne.command("orders").description("Kalshi resting orders").option("--status <status>","Order status filter (default: resting)","resting").option("--json","JSON output").action(async e=>{await ie(()=>(0,O.ordersCommand)(e))}),ne.command("fills").description("Recent trade fills").option("--ticker <ticker>","Filter by market ticker").option("--json","JSON output").action(async e=>{await ie(()=>(0,C.fillsCommand)(e))}),ne.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 ie(()=>(0,I.feedCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl}))}),ne.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 s=n.optsWithGlobals();await ie(()=>(0,U.deltaCommand)(e,{...t,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.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 s=n.optsWithGlobals();await ie(()=>(0,P.whatifCommand)(e,{set:t.set,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.command("schedule").description("Exchange status and trading hours").option("--json","JSON output").action(async e=>{await ie(()=>(0,A.scheduleCommand)(e))}),ne.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 ie(()=>(0,T.buyCommand)(e,t,n))}),ne.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 ie(()=>(0,T.sellCommand)(e,t,n))}),ne.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 ie(()=>(0,E.cancelCommand)(e,t))}),ne.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 ie(()=>(0,M.rfqCommand)(e,t,n))}),ne.command("announcements").description("Exchange announcements (rule changes, maintenance)").option("--json","JSON output").action(async e=>{await ie(()=>(0,R.announcementsCommand)(e))}),ne.command("history <ticker>").description("Historical market data (settled/closed)").option("--json","JSON output").action(async(e,t)=>{await ie(()=>(0,N.historyCommand)(e,t))}),ne.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 ie(()=>(0,L.performanceCommand)(e))}),ne.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 ie(()=>(0,D.liquidityCommand)({...t,topic:e}))}),ne.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 ie(()=>(0,j.bookCommand)(e,t))}),ne.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 s=n.optsWithGlobals();await ie(()=>(0,F.promptCommand)(e,{sections:t.sections,maxLength:t.maxLength,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.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 s=n.optsWithGlobals();await ie(()=>(0,K.augmentCommand)(e,{dryRun:t.dryRun,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl}))}),ne.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 ie(()=>(0,W.marketsCommand)({json:e.json,share:e.share}))}),ne.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 ie(()=>(0,B.queryCommand)(e,{json:t.json,share:t.share,limit:t.limit}))}),ne.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 ie(()=>(0,q.telegramCommand)(e))}),ne.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 ie(()=>(0,J.xSearchCommand)(e,t))}),ne.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 ie(()=>(0,J.xVolumeCommand)(e,t))}),ne.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 ie(()=>(0,J.xNewsCommand)(e,t))}),ne.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 ie(()=>(0,J.xAccountCommand)(e,t))}),ne.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 ie(()=>(0,Y.worldCommand)(e))}),ne.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 ie(()=>(0,V.ideasCommand)(e))}),(0,b.registerStrategies)(ne),(0,X.registerIntents)(ne),(0,G.registerRuntime)(ne);const re=new Set(["agent","watch","telegram","dashboard"]);ne.hook("postAction",(e,t)=>{re.has(t.name())||setTimeout(()=>process.exit(0),100)}),ne.parse()})(),module.exports=s})();
|