@spfunctions/cli 1.7.38 → 1.7.39
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/index.js +1 -1
- package/dist/package.json +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:true});t.checkForUpdates=checkForUpdates;const s=n(79896);const o=n(16928);const i=n(70857);const r="@spfunctions/cli";const a=(0,o.join)((0,i.homedir)(),".sf","update-check.json");const c=60*60*1e3;function readCache(){try{if((0,s.existsSync)(a))return JSON.parse((0,s.readFileSync)(a,"utf-8"))}catch{}return{lastCheck:0,latestVersion:null}}function writeCache(e){try{(0,s.mkdirSync)((0,o.dirname)(a),{recursive:true});(0,s.writeFileSync)(a,JSON.stringify(e))}catch{}}function semverLt(e,t){const n=e.replace(/^v/,"").split(".").map(Number);const s=t.replace(/^v/,"").split(".").map(Number);for(let e=0;e<3;e++){if((n[e]||0)<(s[e]||0))return true;if((n[e]||0)>(s[e]||0))return false}return false}function getCurrentVersion(){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"}function checkForUpdates(){const e=getCurrentVersion();const t=readCache();if(Date.now()-t.lastCheck<c){if(t.latestVersion&&semverLt(e,t.latestVersion)){console.log(` [33m↑ Update available: ${e} → ${t.latestVersion}. Run [1msf update[22;33m to install.[39m`)}return}(async()=>{try{const t=await fetch(`https://registry.npmjs.org/${r}/latest`,{signal:AbortSignal.timeout(5e3)});if(!t.ok)return;const n=await t.json();const s=n.version;writeCache({lastCheck:Date.now(),latestVersion:s});if(semverLt(e,s)){console.log(` [33m↑ Update available: ${e} → ${s}. Run [1msf update[22;33m to install.[39m`)}}catch{}})()}},87783:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.cached=cached;t.invalidate=invalidate;t.invalidateAll=invalidateAll;const n=new Map;async function cached(e,t,s){const o=n.get(e);if(o&&Date.now()<o.expiry)return o.data;try{const o=await s();n.set(e,{data:o,expiry:Date.now()+t});return o}catch(e){if(o)return o.data;throw e}}function invalidate(e){n.delete(e)}function invalidateAll(){n.clear()}},19218:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.SFClient=void 0;t.kalshiFetchAllSeries=kalshiFetchAllSeries;t.kalshiFetchEvents=kalshiFetchEvents;t.kalshiFetchMarket=kalshiFetchMarket;t.kalshiFetchMarketsBySeries=kalshiFetchMarketsBySeries;t.kalshiFetchMarketsByEvent=kalshiFetchMarketsByEvent;t.fetchGlobalContext=fetchGlobalContext;t.fetchQuery=fetchQuery;t.fetchTraditionalMarkets=fetchTraditionalMarkets;const n="https://simplefunctions.dev";const s="https://api.elections.kalshi.com/trade-api/v2";class SFClient{apiKey;baseUrl;constructor(e,t){this.apiKey=e||process.env.SF_API_KEY||"";this.baseUrl=(t||process.env.SF_API_URL||n).replace(/\/$/,"");if(!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}`;const o={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"};const i=await fetch(s,{method:e,headers:o,body:n?JSON.stringify(n):undefined});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}`);t.status=i.status;t.code=e?.code||`HTTP_${i.status}`;t.details=e;throw 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=true){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=false){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;if(e?.status)t.set("status",e.status);if(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";const s=t?.hours||24;const 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;const 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(/^@/,"");const s=t?.hours||24;const o=t?.limit||20;return this.request("GET",`/api/x/account?username=${n}&hours=${s}&limit=${o}`)}}t.SFClient=SFClient;async function kalshiGet(e,t){const n=new URL(`${s}${e}`);if(t){for(const[e,s]of Object.entries(t)){if(s!==undefined&&s!=="")n.searchParams.set(e,s)}}const o=await fetch(n.toString());if(!o.ok){throw new Error(`Kalshi API ${o.status}: ${await o.text()}`)}return o.json()}async function kalshiFetchAllSeries(){const e=await kalshiGet("/series",{include_volume:"true"});return e.series||[]}async function kalshiFetchEvents(e){const t=await kalshiGet("/events",{series_ticker:e,status:"open",with_nested_markets:"true",limit:"200"});return t.events||[]}async function kalshiFetchMarket(e){const t=await kalshiGet(`/markets/${e}`);return t.market||t}async function kalshiFetchMarketsBySeries(e){const t=await kalshiGet("/markets",{series_ticker:e,status:"open",limit:"200"});return t.markets||[]}async function kalshiFetchMarketsByEvent(e){const t=await kalshiGet("/markets",{event_ticker:e,status:"open",limit:"1000"});return t.markets||[]}const o="https://simplefunctions.dev";async function fetchGlobalContext(){const e=await fetch(`${o}/api/public/context`);if(!e.ok)throw new Error(`Context API error: ${e.status}`);return e.json()}async function fetchQuery(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()}async function fetchTraditionalMarkets(e){const t=e?`?topic=${encodeURIComponent(e)}`:"";const n=await fetch(`${o}/api/public/markets${t}`);if(!n.ok)throw new Error(`Markets API error: ${n.status}`);return n.json()}},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:true});t.agentCommand=agentCommand;const o=s(n(79896));const i=s(n(16928));const r=s(n(70857));const a=n(19218);const c=n(96139);const l=n(34331);const d=n(97325);const u=n(11627);const p=n(40101);function getSessionDir(){return i.default.join(r.default.homedir(),".sf","sessions")}function getSessionPath(e){return i.default.join(getSessionDir(),`${e}.json`)}function loadSession(e){const t=getSessionPath(e);try{if(o.default.existsSync(t)){return JSON.parse(o.default.readFileSync(t,"utf-8"))}}catch{}return null}function saveSession(e,t,n){const s=getSessionDir();o.default.mkdirSync(s,{recursive:true});o.default.writeFileSync(getSessionPath(e),JSON.stringify({thesisId:e,model:t,updatedAt:(new Date).toISOString(),messages:n},null,2))}const rgb=(e,t,n)=>s=>`[38;2;${e};${t};${n}m${s}[39m`;const bgRgb=(e,t,n)=>s=>`[48;2;${e};${t};${n}m${s}[49m`;const bold=e=>`[1m${e}[22m`;const dim=e=>`[2m${e}[22m`;const italic=e=>`[3m${e}[23m`;const underline=e=>`[4m${e}[24m`;const strikethrough=e=>`[9m${e}[29m`;const h={emerald:rgb(16,185,129),zinc200:rgb(228,228,231),zinc400:rgb(161,161,170),zinc600:rgb(82,82,91),zinc800:rgb(39,39,42),red:rgb(239,68,68),amber:rgb(245,158,11),white:rgb(255,255,255),bgZinc900:bgRgb(24,24,27),bgZinc800:bgRgb(39,39,42)};function createMutableLine(e){const{truncateToWidth:t,visibleWidth:n}=e;return class MutableLine{text;cachedWidth;cachedLines;constructor(e){this.text=e}setText(e){this.text=e;this.cachedWidth=undefined;this.cachedLines=undefined}invalidate(){this.cachedWidth=undefined;this.cachedLines=undefined}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;this.cachedWidth=e;this.cachedLines=[t(this.text,e)];return this.cachedLines}}}function createHeaderBar(e){const{truncateToWidth:t,visibleWidth:n}=e;return class HeaderBar{thesisId="";confidence=0;confidenceDelta=0;pnlDollars=0;positionCount=0;edgeCount=0;topEdge="";cachedWidth;cachedLines;setFromContext(e,t){this.thesisId=(e.thesisId||"").slice(0,8);this.confidence=typeof e.confidence==="number"?Math.round(e.confidence*100):typeof e.confidence==="string"?Math.round(parseFloat(e.confidence)*100):0;this.confidenceDelta=e.lastEvaluation?.confidenceDelta?Math.round(e.lastEvaluation.confidenceDelta*100):0;this.edgeCount=(e.edges||[]).length;const n=e.edges||[];if(n.length>0){const e=[...n].sort(((e,t)=>Math.abs(t.edge||t.edgeSize||0)-Math.abs(e.edge||e.edgeSize||0)))[0];const t=(e.market||e.marketTitle||e.marketId||"").slice(0,20);const s=e.edge||e.edgeSize||0;this.topEdge=`${t} ${s>0?"+":""}${Math.round(s)}¢`}if(t&&t.length>0){this.positionCount=t.length;this.pnlDollars=t.reduce(((e,t)=>{const n=t.unrealized_pnl||0;return e+n}),0)/100}this.cachedWidth=undefined;this.cachedLines=undefined}updateConfidence(e,t){this.confidence=Math.round(e*100);this.confidenceDelta=Math.round(t*100);this.cachedWidth=undefined;this.cachedLines=undefined}invalidate(){this.cachedWidth=undefined;this.cachedLines=undefined}update(e,t,n){this.cachedWidth=undefined;this.cachedLines=undefined}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;this.cachedWidth=e;const s=h.emerald(bold(this.thesisId));const o=this.confidenceDelta>0?"▲":this.confidenceDelta<0?"▼":"─";const i=this.confidenceDelta>0?h.emerald:this.confidenceDelta<0?h.red:h.zinc600;const r=this.confidenceDelta!==0?` (${this.confidenceDelta>0?"+":""}${this.confidenceDelta})`:"";const a=i(`${o} ${this.confidence}%${r}`);let c="";if(this.positionCount>0){const e=this.pnlDollars>=0?h.emerald(`+$${this.pnlDollars.toFixed(2)}`):h.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);c=h.zinc600(`${this.positionCount} pos `)+e}const l=h.zinc600(`${this.edgeCount} edges`);const d=this.topEdge?h.zinc400(this.topEdge):"";const u=h.zinc600(" │ ");const p=[s,a,c,l,d].filter(Boolean);const m=p.join(u);let f=h.bgZinc900(" "+t(m,e-2,"")+" ");const g=n(f);if(g<e){f=f+h.bgZinc900(" ".repeat(e-g))}this.cachedLines=[f];return this.cachedLines}}}function createFooterBar(e){const{truncateToWidth:t,visibleWidth:n}=e;return class FooterBar{thesisId="";confidence=0;confidenceDelta=0;pnlDollars=0;positionCount=0;edgeCount=0;topEdge="";tokens=0;cost=0;toolCount=0;modelName="";tradingEnabled=false;exchangeOpen=null;cachedWidth;cachedLines;isExplorer=false;setFromContext(e,t){if(e._explorerMode){this.isExplorer=true;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=false;this.thesisId=(e.thesisId||"").slice(0,8);this.confidence=typeof e.confidence==="number"?Math.round(e.confidence*100):typeof e.confidence==="string"?Math.round(parseFloat(e.confidence)*100):0;this.confidenceDelta=e.lastEvaluation?.confidenceDelta?Math.round(e.lastEvaluation.confidenceDelta*100):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];const n=(e.market||e.marketTitle||e.marketId||"").slice(0,20);const s=e.edge||e.edgeSize||0;this.topEdge=`${n} ${s>0?"+":""}${Math.round(s)}¢`}}if(t&&t.length>0){this.positionCount=t.length;this.pnlDollars=t.reduce(((e,t)=>e+(t.unrealized_pnl||0)),0)/100}this.cachedWidth=undefined;this.cachedLines=undefined}updateConfidence(e,t){this.confidence=Math.round(e*100);this.confidenceDelta=Math.round(t*100);this.cachedWidth=undefined;this.cachedLines=undefined}invalidate(){this.cachedWidth=undefined;this.cachedLines=undefined}update(){this.cachedWidth=undefined;this.cachedLines=undefined}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;this.cachedWidth=e;const s=h.zinc600(" │ ");let o;if(this.isExplorer){const e=h.emerald(bold("Explorer"));const t=h.zinc600(`${this.edgeCount} public edges`);const n=this.topEdge?h.zinc400(this.topEdge):"";let s="";if(this.positionCount>0){const e=this.pnlDollars>=0?h.emerald(`+$${this.pnlDollars.toFixed(2)}`):h.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);s=h.zinc600(`${this.positionCount} pos `)+e}o=[e,s,t,n].filter(Boolean)}else{const e=h.emerald(this.thesisId);const t=this.confidenceDelta>0?"▲":this.confidenceDelta<0?"▼":"─";const n=this.confidenceDelta>0?h.emerald:this.confidenceDelta<0?h.red:h.zinc600;const s=this.confidenceDelta!==0?` (${this.confidenceDelta>0?"+":""}${this.confidenceDelta})`:"";const i=n(`${t} ${this.confidence}%${s}`);let r="";if(this.positionCount>0){const e=this.pnlDollars>=0?h.emerald(`+$${this.pnlDollars.toFixed(2)}`):h.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);r=h.zinc600(`${this.positionCount} pos `)+e}const a=h.zinc600(`${this.edgeCount} edges`);const c=this.topEdge?h.zinc400(this.topEdge):"";o=[e,i,r,a,c].filter(Boolean)}let i=h.bgZinc800(" "+t(o.join(s),e-2,"")+" ");const r=n(i);if(r<e)i+=h.bgZinc800(" ".repeat(e-r));const a=h.zinc600(this.modelName.split("/").pop()||this.modelName);const c=this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:`${this.tokens}`;const l=h.zinc600(`${c} tok`);const d=this.exchangeOpen===true?h.emerald("OPEN"):this.exchangeOpen===false?h.red("CLOSED"):h.zinc600("...");const u=this.tradingEnabled?h.amber("trading"):h.zinc600("read-only");const p=h.zinc600("/help");const m=[a,l,d,u].join(s);const f=n(m);const g=n(p);const y=Math.max(1,e-f-g-2);let $=h.bgZinc900(" "+m+" ".repeat(y)+p+" ");const k=n($);if(k<e)$+=h.bgZinc900(" ".repeat(e-k));this.cachedLines=[i,$];return this.cachedLines}}}function renderCausalTree(e,t){const n=e.causalTree;if(!n?.nodes?.length)return h.zinc600(" No causal tree data");const s=[];for(const e of n.nodes){const t=e.id||"";const n=e.label||e.description||"";const o=typeof e.probability==="number"?Math.round(e.probability*100):typeof e.impliedProbability==="number"?Math.round(e.impliedProbability*100):null;const i=(t.match(/\./g)||[]).length;const r=" ".repeat(i+1);if(o!==null){const e=Math.round(o/10);const i="█".repeat(e)+"░".repeat(10-e);const a=o>=70?h.emerald:o>=40?h.amber:h.red;const c=`${r}${h.zinc600(t)} ${h.zinc400(n)} `;const l=` ${a(`${o}%`)} ${a(i)}`;s.push(c+l)}else{s.push(`${r}${h.zinc600(t)} ${h.zinc400(n)}`)}}return s.join("\n")}function renderEdges(e,t){const n=e.edges;if(!n?.length)return h.zinc600(" No edge data");const s=e._positions||[];const o=[];for(const e of n){const t=(e.market||e.marketId||"").slice(0,18).padEnd(18);const n=typeof e.marketPrice==="number"?`${e.marketPrice}¢`:"?";const i=typeof e.thesisPrice==="number"?`${e.thesisPrice}¢`:"?";const r=typeof e.edge==="number"?e.edge>0?`+${e.edge}`:`${e.edge}`:"?";const a=e.orderbook||{};const c=typeof a.spread==="number"?`${a.spread}¢`:"?";const l=a.liquidityScore||"low";const d=l==="high"?"■■■":l==="medium"?"■■ ":"■ ";const u=l==="high"?h.emerald:l==="medium"?h.amber:h.red;const p=s.find((t=>t.ticker===e.marketId||e.marketId&&t.ticker?.includes(e.marketId)));let m=h.zinc600("—");if(p){const e=p.side?.toUpperCase()||"YES";const t=typeof p.unrealized_pnl==="number"?p.unrealized_pnl>=0?h.emerald(`+$${(p.unrealized_pnl/100).toFixed(0)}`):h.red(`-$${(Math.abs(p.unrealized_pnl)/100).toFixed(0)}`):"";m=h.emerald(`${e} (${p.quantity}@${p.average_price_paid}¢ ${t})`)}o.push(` ${h.zinc200(t)} ${h.zinc400(n)} → ${h.zinc400(i)} edge ${r.includes("+")?h.emerald(r):h.red(r)} spread ${h.zinc600(c)} ${u(d)} ${u(l.padEnd(4))} ${m}`)}return o.join("\n")}function renderPositions(e){if(!e?.length)return h.zinc600(" No positions");const t=[];let n=0;for(const s of e){const e=(s.ticker||"").slice(0,18).padEnd(18);const o=(s.side||"yes").toUpperCase().padEnd(3);const i=String(s.quantity||0);const r=`${s.average_price_paid||0}¢`;const a=typeof s.current_value==="number"&&s.current_value>0?`${s.current_value}¢`:"?¢";const c=s.unrealized_pnl||0;n+=c;const l=(c/100).toFixed(2);const d=c>=0?h.emerald(`+$${l}`):h.red(`-$${Math.abs(parseFloat(l)).toFixed(2)}`);const u=c>=0?h.emerald("▲"):h.red("▼");t.push(` ${h.zinc200(e)} ${h.zinc400(o)} ${h.zinc400(i)} @ ${h.zinc400(r)} now ${h.zinc200(a)} ${d} ${u}`)}const s=(n/100).toFixed(2);t.push(h.zinc600(" "+"─".repeat(40)));t.push(n>=0?` Total P&L: ${h.emerald(bold(`+$${s}`))}`:` Total P&L: ${h.red(bold(`-$${Math.abs(parseFloat(s)).toFixed(2)}`))}`);return t.join("\n")}async function selectThesis(e,t=false){return new Promise((n=>{let s=0;const o=[];if(t){o.push({id:"_explorer",conf:-1,title:"Explorer mode — no thesis, full market access"})}for(const t of e){const e=typeof t.confidence==="number"?Math.round(t.confidence*100):0;const 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);i("[?1049h");i("[?25l");function render(){i("[H[2J");i("\n [2mSelect thesis[22m\n\n");for(let e=0;e<o.length;e++){const t=o[e];const n=e===s;const r=n?"[38;2;16;185;129m › [39m":" ";if(t.id==="_explorer"){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`;const s=`[38;2;55;55;60m${t.conf}%[39m`;const 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`)}render();if(process.stdin.isTTY)process.stdin.setRawMode(true);process.stdin.resume();process.stdin.setEncoding("utf8");const onKey=e=>{const t=Buffer.from(e);if(t[0]===27&&t[1]===91&&t[2]===65){s=(s-1+o.length)%o.length;render()}else if(t[0]===27&&t[1]===91&&t[2]===66){s=(s+1)%o.length;render()}else if(e==="k"){s=(s-1+o.length)%o.length;render()}else if(e==="j"){s=(s+1)%o.length;render()}else if(e==="\r"||e==="\n"){cleanup();n(o[s].id)}else if(t[0]===3){cleanup();process.exit(0)}};function cleanup(){process.stdin.removeListener("data",onKey);if(process.stdin.isTTY)process.stdin.setRawMode(false);process.stdin.pause();i("[?25h");i("[?1049l")}process.stdin.on("data",onKey)}))}async function agentCommand(e,t){const s=t?.modelKey||process.env.OPENROUTER_API_KEY;const o=process.env.SF_API_KEY;const i=process.env.SF_API_URL||"https://simplefunctions.dev";const r=!s&&!!o;const m=s||o;const f=r?`${i}/api/proxy`:"https://openrouter.ai/api/v1";if(!m){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){try{const e=await fetch("https://openrouter.ai/api/v1/auth/key",{headers:{Authorization:`Bearer ${m}`},signal:AbortSignal.timeout(8e3)});if(!e.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);if(!t.includes("timeout")){console.warn(`Warning: Could not verify OpenRouter key (${t}). Continuing anyway.`)}}}else{console.log(" [2mUsing SimpleFunctions LLM proxy (no OpenRouter key needed)[22m")}const g=new a.SFClient;let y=e||null;let $=false;if(!y){let e=[];try{const t=await g.listTheses();const n=t.theses||t;e=n.filter((e=>e.status==="active"))}catch{e=[]}if(e.length===0){$=true}else if(e.length===1){y=e[0].id}else if(process.stdin.isTTY&&!t?.noTui){const t=await selectThesis(e,true);if(t==="_explorer"){$=true}else{y=t}}else{y=e[0].id}}let k;if($){try{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));k=await e()}catch{k={edges:[],theses:[]}}k._explorerMode=true}else{try{k=await g.getContext(y)}catch(e){console.error(`Warning: Could not fetch thesis context (${e.message}). Starting with limited context.`);k={thesisId:y,edges:[],causalTree:{nodes:[]}}}}if(t?.noTui){return runPlainTextAgent({openrouterKey:m,sfClient:g,resolvedThesisId:y||"_explorer",latestContext:k,useProxy:r,llmBaseUrl:f,sfApiKey:o,sfApiUrl:i,opts:t})}const b=await n.e(921).then(n.bind(n,93921));const w=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641));const _=await Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653));const{TUI:S,ProcessTerminal:v,Container:x,Text:C,Markdown:O,Editor:I,Loader:P,Spacer:T,CombinedAutocompleteProvider:E,truncateToWidth:A,visibleWidth:M}=b;const{getModel:R,streamSimple:L,Type:N}=w;const{Agent:D}=_;const F=createMutableLine(b);const q=createFooterBar(b);const K=t?.model||"anthropic/claude-sonnet-4.6";let j=K.replace(/^openrouter\//,"");function resolveModel(e){let t;try{t=R("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:true,supportsTools:true}}if(r)t.baseUrl=f;return t}let U=resolveModel(j);let z=0;let H=0;let B=0;let J=false;let W=null;let G=(new Date).toISOString();let X=null;let Y=null;let V=null;const Q=new v;const Z=new S(Q);const ee={heading:e=>h.zinc200(bold(e)),link:e=>h.emerald(e),linkUrl:e=>h.zinc600(e),code:e=>h.zinc200(e),codeBlock:e=>h.zinc400(e),codeBlockBorder:e=>h.zinc600(e),quote:e=>h.zinc400(e),quoteBorder:e=>h.zinc600(e),hr:e=>h.zinc600(e),listBullet:e=>h.emerald(e),bold:e=>bold(e),italic:e=>italic(e),strikethrough:e=>strikethrough(e),underline:e=>underline(e)};const te={color:e=>h.zinc400(e)};const ne={borderColor:e=>`[38;2;50;50;55m${e}[39m`,selectList:{selectedPrefix:e=>h.emerald(e),selectedText:e=>h.zinc200(e),description:e=>h.zinc600(e),scrollInfo:e=>h.zinc600(e),noMatch:e=>h.zinc600(e)}};const se=new q;se.modelName=j;se.tradingEnabled=(0,u.loadConfig)().tradingEnabled||false;let oe=null;try{oe=await(0,c.getPositions)();if(oe){for(const e of oe){const t=await(0,c.getMarketPrice)(e.ticker);if(t!==null){e.current_value=t;e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity)}}}}catch{}se.setFromContext(k,oe||undefined);fetch("https://api.elections.kalshi.com/trade-api/v2/exchange/status",{headers:{Accept:"application/json"}}).then((e=>e.json())).then((e=>{se.exchangeOpen=!!e.exchange_active;se.update();Z.requestRender()})).catch((()=>{}));const ie=new T(1);const re=new T(1);const ae=new x;const ce=new I(Z,ne,{paddingX:1});const le=[{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)"}];if((0,u.loadConfig)().tradingEnabled){le.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 de=(0,p.loadSkills)();for(const e of de){const t=e.trigger.replace(/^\//,"");le.splice(-2,0,{name:t,description:`[skill] ${e.description.slice(0,50)}`})}const ue=new E(le,process.cwd());ce.setAutocompleteProvider(ue);Z.addChild(ie);Z.addChild(ae);Z.addChild(ce);Z.addChild(re);Z.setFocus(ce);const pe=Z.showOverlay(se,{anchor:"bottom-left",width:"100%",nonCapturing:true});function addSystemText(e){const t=new C(e,1,0);ae.addChild(t);Z.requestRender()}function addSpacer(){ae.addChild(new T(1))}function promptUser(e){return new Promise((t=>{addSystemText(h.amber(bold("⚠ "))+h.zinc200(e));addSpacer();Z.requestRender();V={resolve:t}}))}const he=N.Object({thesisId:N.String({description:"Thesis ID (short or full UUID)"})});const me=N.Object({thesisId:N.String({description:"Thesis ID"}),content:N.String({description:"Signal content"}),type:N.Optional(N.String({description:"Signal type: news, user_note, external. Default: user_note"}))});const fe=N.Object({query:N.Optional(N.String({description:"Keyword search for Kalshi markets"})),series:N.Optional(N.String({description:"Kalshi series ticker (e.g. KXWTIMAX)"})),market:N.Optional(N.String({description:"Specific market ticker"}))});const ge=N.Object({query:N.String({description:"Search keywords"})});const ye=N.Object({});const $e=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:he,execute:async(e,t)=>{const n=await g.getContext(t.thesisId);k=n;se.setFromContext(n,oe||undefined);Z.requestRender();return{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:ye,execute:async()=>{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));const 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:N.Object({q:N.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));const 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:N.Object({topic:N.Optional(N.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));const 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:N.Object({symbols:N.String({description:"Comma-separated (max 5). Continuous futures: ROOT.c.0. E.g. SPY, CL.c.0, ES.c.0"}),dataset:N.Optional(N.String({description:"DBEQ.BASIC (stocks), GLBX.MDP3 (CME futures), OPRA.PILLAR (options)"})),schema:N.Optional(N.String({description:"ohlcv-1d, ohlcv-1h, ohlcv-1m, trades, bbo-1s, bbo-1m, statistics"})),stype:N.Optional(N.String({description:"raw_symbol (default) or continuous (for .FUT)"})),days:N.Optional(N.Number({description:"Lookback days (default 7, max 30)"}))}),execute:async(e,t)=>{const n=new URLSearchParams({symbols:t.symbols});if(t.dataset)n.set("dataset",t.dataset);if(t.schema)n.set("schema",t.schema);if(t.stype)n.set("stype",t.stype);if(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:me,execute:async(e,t)=>{const n=await g.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:he,execute:async(e,t)=>{const n=await g.evaluate(t.thesisId);if(n.evaluation?.confidenceDelta&&Math.abs(n.evaluation.confidenceDelta)>=.01){const e=n.evaluation.confidenceDelta;const t=Math.round((n.evaluation.previousConfidence||0)*100);const s=Math.round((n.evaluation.newConfidence||0)*100);const o=e>0?"▲":"▼";const i=e>0?h.emerald:h.red;addSystemText(i(` ${o} Confidence ${t}% → ${s}% (${e>0?"+":""}${Math.round(e*100)})`));addSpacer();se.updateConfidence(n.evaluation.newConfidence,e);Z.requestRender()}try{k=await g.getContext(t.thesisId);se.setFromContext(k,oe||undefined);Z.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:fe,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)();const n=t.query.toLowerCase().split(/\s+/);const 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(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);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(n[0]*100):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:ye,execute:async()=>{const e=await g.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:ye,execute:async()=>{const e={kalshi:[],polymarket:[]};const t=await(0,c.getPositions)();if(t){for(const e of t){const t=await(0,c.getMarketPrice)(e.ticker);if(t!==null){e.current_value=t;e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity)}}W=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((e.avgPrice||0)*100)}¢`,current_price:`${Math.round((e.curPrice||e.currentPrice||0)*100)}¢`,pnl:`$${(e.cashPnl||0).toFixed(2)}`})))}catch{}}if(e.kalshi.length===0&&e.polymarket.length===0){return{content:[{type:"text",text:"No positions found. Configure Kalshi (KALSHI_API_KEY_ID) or Polymarket (sf setup --polymarket) to see positions."}],details:{}}}return{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:ge,execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY;const s=!n&&o;if(!n&&!s){return{content:[{type:"text",text:"Web search not available. Run sf login (proxied search) or set TAVILY_API_KEY."}],details:{}}}let r;if(n){r=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:true})})}else{r=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:true})})}if(!r.ok){return{content:[{type:"text",text:`Search failed: ${r.status}`}],details:{}}}const a=await r.json();const c=(a.results||[]).map((e=>`[${e.title}](${e.url})\n${e.content?.slice(0,200)}`)).join("\n\n");const l=a.answer?`Summary: ${a.answer}\n\n---\n\n`:"";return{content:[{type:"text",text:`${l}${c}`}],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:N.Object({slug:N.Optional(N.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:N.Object({thesisId:N.String({description:"Thesis ID"}),marketId:N.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:N.String({description:"Human-readable market name"}),direction:N.String({description:"yes or no"}),horizon:N.Optional(N.String({description:"short, medium, or long. Default: medium"})),entryBelow:N.Optional(N.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:N.Optional(N.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:N.Optional(N.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:N.Optional(N.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:N.Optional(N.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:N.Optional(N.Number({description:"Contracts per order. Default: 50"})),softConditions:N.Optional(N.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:N.Optional(N.String({description:"Full logic description"}))}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),status:N.Optional(N.String({description:"Filter by status. Omit for all."}))}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),strategyId:N.String({description:"Strategy ID (UUID)"}),stopLoss:N.Optional(N.Number({description:"New stop loss (cents)"})),takeProfit:N.Optional(N.Number({description:"New take profit (cents)"})),entryBelow:N.Optional(N.Number({description:"New entry below trigger (cents)"})),entryAbove:N.Optional(N.Number({description:"New entry above trigger (cents)"})),status:N.Optional(N.String({description:"New status: active|watching|executed|cancelled|review"})),priority:N.Optional(N.Number({description:"New priority"})),softConditions:N.Optional(N.String({description:"Updated soft conditions"})),rationale:N.Optional(N.String({description:"Updated rationale"}))}),execute:async(e,t)=>{const{thesisId:n,strategyId:s,...o}=t;const i=await g.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:N.Object({hours:N.Optional(N.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:N.Optional(N.String({description:"Filter by category (e.g. Economics, Politics, Sports)"}))}),execute:async(e,t)=>{const n=t.hours||168;const s=new Date;const o=`https://api.elections.kalshi.com/trade-api/v2/milestones?limit=200&minimum_start_date=${s.toISOString()}`+(t.category?`&category=${t.category}`:"");const 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();const a=s.getTime()+n*36e5;const 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:N.Object({eventTicker:N.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:N.Optional(N.Number({description:"Days of history (default 7)"}))}),execute:async(e,t)=>{const{getForecastHistory:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=t.days||7;const 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();const 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()-o*864e5)/1e3),endTs:Math.floor(Date.now()/1e3),periodInterval:1440});if(!c||c.length===0)return{content:[{type:"text",text:"No forecast data available"}],details:{}};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled (resolved) contracts with P&L. Shows which contracts won/lost and realized returns.",parameters:N.Object({ticker:N.Optional(N.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getSettlements:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=await s({limit:100,ticker:t.ticker});if(!o)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(o.settlements,null,2)}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance and portfolio value.",parameters:ye,execute:async()=>{const{getBalance:e}=await Promise.resolve().then(n.t.bind(n,96139,23));const t=await e();if(!t)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],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:N.Object({status:N.Optional(N.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));const 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;let s=false;try{const i=await o(e.ticker);if(i!=null&&e.yes_price_dollars){n=Math.round(Math.abs(i-parseFloat(e.yes_price_dollars))*100);if(t!=null&&t>7&&n>10)s=true}}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:N.Object({ticker:N.Optional(N.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getFills:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=await s({ticker:t.ticker,limit:50});if(!o)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(o.fills,null,2)}],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:N.Object({topic:N.String({description:"Topic to scan (e.g. oil, crypto, fed, geopolitics)"})}),execute:async(e,t)=>{const n=t.topic.toLowerCase();const s=d.TOPIC_SERIES[n];if(!s){return{content:[{type:"text",text:`Unknown topic "${t.topic}". Available: ${Object.keys(d.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`;const n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)continue;const s=(await n.json()).markets||[];const i=await Promise.allSettled(s.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(e.status!=="fulfilled"||!e.value.ob)continue;const{ticker:t,title:n,ob:s}=e.value;const i=(s.yes_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),qty:parseFloat(t)}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const r=(s.no_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),qty:parseFloat(t)}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const a=i[0]?.price||0;const c=r.length>0?100-r[0].price:100;const l=c-a;const d=i.slice(0,3).reduce(((e,t)=>e+t.qty),0)+r.slice(0,3).reduce(((e,t)=>e+t.qty),0);const 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(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 s=await(0,l.polymarketGetOrderbookWithDepth)(n[0]);if(!s)continue;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{}o.sort(((e,t)=>e.spread-t.spread));return{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:N.Object({ticker:N.Optional(N.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:N.Optional(N.Array(N.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:N.Optional(N.String({description:'Search Polymarket by keyword (e.g. "oil price above 100")'}))}),execute:async(e,t)=>{const n=[];const s=[];if(t.tickers?.length)s.push(...t.tickers);else if(t.ticker)s.push(t.ticker);for(const e of s){try{const t=await(0,a.kalshiFetchMarket)(e);const s=t.status||"unknown";if(s!=="open"&&s!=="active"){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(parseFloat(t.last_price_dollars||"0")*100)})}else{const s=await(0,c.getPublicOrderbook)(e);const o=(s?.yes_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const i=(s?.no_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));if(o.length===0&&i.length===0){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(parseFloat(t.last_price_dollars||"0")*100),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;const r=i.length>0?100-i[0].price:o[0]?o[0].price+1:100;const a=r-s;const c=o.slice(0,3).reduce(((e,t)=>e+t.size),0)+i.slice(0,3).reduce(((e,t)=>e+t.size),0);const 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(parseFloat(t.last_price_dollars||"0")*100),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 s=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!s)continue;const o=await(0,l.polymarketGetOrderbookWithDepth)(s[0]);if(!o)continue;const i=(0,l.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(i[0]*100):0,volume24h:e.volume24hr||0})}}}catch{}}if(n.length===0){return{content:[{type:"text",text:"No markets found. Provide ticker (Kalshi) or polyQuery (Polymarket search)."}],details:{}}}return{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:ye,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:N.Object({rawThesis:N.String({description:"The raw thesis statement to create"}),webhookUrl:N.Optional(N.String({description:"Optional webhook URL for notifications"}))}),execute:async(e,t)=>{const n=await g.createThesis(t.rawThesis,true);const s=n.thesis||n;const o=s.causalTree?.nodes?.length||0;const i=(s.edges||[]).length;const r=typeof s.confidence==="number"?Math.round(s.confidence*100):0;if($&&s.id){$=false;y=s.id;try{k=await g.getContext(s.id);const e=buildSystemPrompt(k);we.setSystemPrompt(e);se.setFromContext(k,oe||undefined);Z.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:ye,execute:async()=>{const{theses:e}=await g.listTheses();const t=(e||[]).filter((e=>e.status==="active"||e.status==="monitoring"));const n=await Promise.allSettled(t.map((async e=>{const t=await g.getContext(e.id);return(t.edges||[]).map((t=>({...t,thesisId:e.id})))})));const s=[];for(const e of n){if(e.status==="fulfilled")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:N.Object({hours:N.Optional(N.Number({description:"Hours of history to fetch (default 24)"}))}),execute:async(e,t)=>{const n=await g.getFeed(t.hours||24);const s=Array.isArray(n)?n:n?.evaluations||n?.items||[];let o=null;let i=0;for(const e of s){let t=0;const n=Math.abs(e.confidenceDelta||e.confidence_delta||0);if(n>0)t=n*100;else if(e.summary?.length>50)t=.1;if(t>i){i=t;o=e}}const r={total:s.length};if(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;return{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:N.Object({hours:N.Optional(N.Number({description:"Hours of history (default 1)"}))}),execute:async(e,t)=>{const n=t.hours||1;const s=new Date(Date.now()-n*60*60*1e3).toISOString();const o=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:{}}}}];$e.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:N.Object({overrides:N.Array(N.Object({nodeId:N.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:N.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{if(y){try{k=await g.getContext(y)}catch{}}const n=k;const s=[];function flatten(e){for(const t of e){s.push(t);if(t.children?.length)flatten(t.children)}}const o=n.causalTree?.nodes||[];flatten(o);const i=o.filter((e=>e.depth===0||e.depth===undefined&&!e.id.includes(".")));const r=new Map(t.overrides.map((e=>[e.nodeId,e.newProbability])));function effectiveProb(e){if(r.has(e.id))return r.get(e.id);if(e.children?.length>0){const t=e.children.map((e=>effectiveProb(e)));const n=e.children.map((e=>e.importance||1));const s=n.reduce(((e,t)=>e+t),0);if(s>0){return t.reduce(((e,t,s)=>e+t*n[s]),0)/s}return t.reduce(((e,t)=>e+t),0)/t.length}return e.probability??0}const a=i.reduce(((e,t)=>e+(t.probability||0)*(t.importance||0)),0);const c=i.reduce(((e,t)=>e+effectiveProb(t)*(t.importance||0)),0);const l=new Map;for(const[e,t]of r.entries()){const n=s.find((t=>t.id===e));if(n&&n.probability>0)l.set(e,Math.max(0,Math.min(2,t/n.probability)))}const d=(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(l.has(t)){n=l.get(t);break}}}const s=e.marketPrice||0;const o=e.thesisPrice||e.thesisImpliedPrice||s;const i=e.edge||e.edgeSize||0;const r=Math.round((s+(o-s)*n)*100)/100;const a=e.direction||"yes";const c=Math.round((a==="yes"?r-s:s-r)*100)/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=>e.signal!=="unchanged"));const u=n.confidence!=null?Math.round(Number(n.confidence)*100):null;const 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}})),serverConfidence:u,treeConfidence:{old:Math.round(a*100),new:Math.round(c*100),delta:Math.round((c-a)*100)},note:u!=null&&Math.abs(u-Math.round(a*100))>5?`serverConfidence (${u}%) differs from treeConfidence (${Math.round(a*100)}%) because the LLM evaluation considers factors beyond the causal tree.`:undefined,affectedEdges:d};return{content:[{type:"text",text:JSON.stringify(p,null,2)}],details:{}}}});$e.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:N.Object({query:N.String({description:'Search query (e.g. "iran oil", "fed rate cut", "$BTC")'}),mode:N.Optional(N.String({description:'"summary" (default, with AI analysis) or "raw" (just posts)'})),hours:N.Optional(N.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await g.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:N.Object({query:N.String({description:"Search query"}),hours:N.Optional(N.Number({description:"Hours of history (default 72)"}))}),execute:async(e,t)=>{const n=await g.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:N.Object({query:N.String({description:"Search query"}),limit:N.Optional(N.Number({description:"Max stories (default 10)"}))}),execute:async(e,t)=>{const n=await g.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:N.Object({username:N.String({description:"X username (with or without @)"}),hours:N.Optional(N.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),newsIntervalMin:N.Optional(N.Number({description:"News scan interval in minutes (15-1440)"})),xIntervalMin:N.Optional(N.Number({description:"X scan interval in minutes (60-1440)"})),evalModelTier:N.Optional(N.String({description:"Eval model: cheap, medium, or heavy"})),monthlyBudgetUsd:N.Optional(N.Number({description:"Monthly budget cap in USD (0 = unlimited)"})),paused:N.Optional(N.Boolean({description:"Pause (true) or resume (false) heartbeat"}))}),execute:async(e,t)=>{const n=t.newsIntervalMin||t.xIntervalMin||t.evalModelTier||t.monthlyBudgetUsd!==undefined||t.paused!==undefined;if(n){const e={};if(t.newsIntervalMin)e.newsIntervalMin=t.newsIntervalMin;if(t.xIntervalMin)e.xIntervalMin=t.xIntervalMin;if(t.evalModelTier)e.evalModelTier=t.evalModelTier;if(t.monthlyBudgetUsd!==undefined)e.monthlyBudgetUsd=t.monthlyBudgetUsd;if(t.paused!==undefined)e.paused=t.paused;await g.updateHeartbeatConfig(t.thesisId,e)}const s=await g.getHeartbeatConfig(t.thesisId);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}});const ke=(0,u.loadConfig)();if(ke.tradingEnabled){$e.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:N.Object({ticker:N.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:N.String({description:"yes or no"}),action:N.String({description:"buy or sell"}),type:N.String({description:"limit or market"}),count:N.Number({description:"Number of contracts"}),price_cents:N.Optional(N.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));const o=t.price_cents?Math.round(Number(t.price_cents)):undefined;const i=((o||99)*t.count/100).toFixed(2);const r=[h.zinc200(bold("ORDER PREVIEW")),` Ticker: ${t.ticker}`,` Side: ${t.side==="yes"?h.emerald("YES"):h.red("NO")}`,` Action: ${t.action.toUpperCase()}`,` Quantity: ${t.count}`,` Type: ${t.type}`,o?` Price: ${o}¢`:"",` Max cost: $${i}`].filter(Boolean).join("\n");addSystemText(r);addSpacer();Z.requestRender();const a=await promptUser("Execute this order? (y/n)");if(!a.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}:{}});const 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);if(t.includes("403")){return{content:[{type:"text",text:"403 Forbidden — your Kalshi key lacks write permission. Get a read+write key at kalshi.com/account/api-keys"}],details:{}}}return{content:[{type:"text",text:`Order failed: ${t}`}],details:{}}}}},{name:"cancel_order",label:"Cancel Order",description:"Cancel a resting order by order ID.",parameters:N.Object({order_id:N.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{const{cancelOrder:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=await promptUser(`Cancel order ${t.order_id}? (y/n)`);if(!o.toLowerCase().startsWith("y")){return{content:[{type:"text",text:"Cancel aborted by user."}],details:{}}}try{await s(t.order_id);return{content:[{type:"text",text:`Order ${t.order_id} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Cancel failed: ${e.message}`}],details:{}}}}})}$e.push({name:"update_thesis",label:"Update Thesis",description:"Update thesis metadata: title, status (active/paused/archived), webhookUrl.",parameters:N.Object({thesisId:N.String({description:"Thesis ID"}),title:N.Optional(N.String({description:"New title"})),status:N.Optional(N.String({description:"active, paused, or archived"})),webhookUrl:N.Optional(N.String({description:"Webhook URL (HTTPS)"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t;const o=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),dryRun:N.Optional(N.Boolean({description:"Preview changes without applying (default false)"}))}),execute:async(e,t)=>{const n=t.dryRun?"?dryRun=true":"";const s=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),venue:N.String({description:"kalshi or polymarket"}),externalMarketId:N.String({description:"Market ticker"}),marketTitle:N.String({description:"Market name"}),direction:N.String({description:"yes or no"}),entryPrice:N.Number({description:"Entry price in cents"}),size:N.Optional(N.Number({description:"Contracts"})),rationale:N.Optional(N.String({description:"Why"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t;const o=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),positionId:N.String({description:"Position ID"}),currentPrice:N.Optional(N.Number({description:"Current price (cents)"})),edge:N.Optional(N.Number({description:"Current edge (cents)"})),status:N.Optional(N.String({description:"open or closed"}))}),execute:async(e,t)=>{const{thesisId:n,positionId:s,...o}=t;const i=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),positionId:N.String({description:"Position ID"})}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),updates:N.Array(N.Object({nodeId:N.String({description:"Node ID (e.g. n3)"}),probability:N.Number({description:"New probability (0-1)"}),reason:N.Optional(N.String({description:"Why"}))})),lock:N.Optional(N.Array(N.String({description:"Node IDs to lock"})))}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),newsIntervalMin:N.Optional(N.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:N.Optional(N.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:N.Optional(N.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:N.Optional(N.Number({description:"Monthly budget cap (0=unlimited)"})),paused:N.Optional(N.Boolean({description:"Pause/resume"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t;const o=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await g.request("GET",`/api/thesis/${t.thesisId}/heartbeat`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}});$e.push({name:"get_trade_ideas",label:"Trade Ideas",description:"S&T-style trade pitches: conviction, catalyst, direction, risk. No auth required.",parameters:N.Object({freshness:N.Optional(N.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:N.Optional(N.String({description:"Filter: macro, geopolitics, crypto, policy, event"}))}),execute:async(e,t)=>{const n=new URLSearchParams;if(t.freshness)n.set("freshness",t.freshness);if(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:N.Object({action:N.String({description:"buy or sell"}),venue:N.String({description:"kalshi or polymarket"}),marketId:N.String({description:"Market ticker"}),marketTitle:N.String({description:"Human-readable name"}),direction:N.String({description:"yes or no"}),targetQuantity:N.Number({description:"Number of contracts"}),maxPrice:N.Optional(N.Number({description:"Max price per contract in cents (1-99)"})),triggerType:N.Optional(N.String({description:"immediate, price_below, price_above, time"})),triggerPrice:N.Optional(N.Number({description:"Price trigger threshold in cents"})),rationale:N.Optional(N.String({description:"Why this trade"})),autoExecute:N.Optional(N.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(e,t)=>{const n=await g.createIntent({...t,source:"agent",expireAt:new Date(Date.now()+24*60*60*1e3).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:N.Object({activeOnly:N.Optional(N.Boolean({description:"Only active intents (default true)"}))}),execute:async(e,t)=>{const n=await g.listIntents({active:t.activeOnly!==false});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:N.Object({intentId:N.String({description:"Intent ID to cancel"})}),execute:async(e,t)=>{const n=await g.cancelIntentAPI(t.intentId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}});$e.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:N.Object({focus:N.Optional(N.String({description:'Comma-separated topics to focus on (e.g. "energy,geopolitics")'}))}),execute:async(e,t)=>{const n=t.focus?`?focus=${encodeURIComponent(t.focus)}`:"";const s=await fetch(`${i}/api/agent/world${n}`);if(!s.ok)return{content:[{type:"text",text:`World API error: ${s.status}`}],details:{}};const o=await s.text();return{content:[{type:"text",text:o}],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:N.Object({since:N.Optional(N.String({description:'Time window: "30m", "1h", "6h", "24h" or ISO timestamp (default "1h")'}))}),execute:async(e,t)=>{const n=t.since||"1h";const 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:{}};const o=await s.text();return{content:[{type:"text",text:o}],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:N.Object({source:N.Object({action:N.String({description:"Firecrawl action: scrape, crawl, search, map, extract, batch_scrape"}),url:N.Optional(N.String({description:"Target URL (for scrape/crawl/extract)"})),query:N.Optional(N.String({description:"Search query (for search action)"}))}),analysis:N.Optional(N.Object({model:N.Optional(N.String({description:"OpenRouter model (e.g. google/gemini-flash-1.5)"})),prompt:N.Optional(N.String({description:"Analysis prompt"}))})),enrich:N.Optional(N.Object({topics:N.Optional(N.Array(N.String(),{description:"Topics for market cross-reference"})),includeIndex:N.Optional(N.Boolean({description:"Include SF prediction market index"}))})),webhook:N.Optional(N.Object({url:N.String({description:"Webhook URL"}),format:N.Optional(N.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:N.Object({content:N.String({description:"Text to cross-reference with markets"}),topics:N.Optional(N.Array(N.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:{}}}});$e.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime daemon is running and show active intents.",parameters:N.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:o}=await Promise.resolve().then(n.t.bind(n,70857,23));const i=s(o(),".sf","runtime.pid");let r=false;let a="";if(e(i)){a=t(i,"utf-8").trim();try{process.kill(parseInt(a),0);r=true}catch{r=false}}const c=await g.listIntents({active:true});return{content:[{type:"text",text:JSON.stringify({running:r,pid:r?a:null,...c},null,2)}],details:{}}}},{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon. Polls for active intents, evaluates trigger conditions, and executes orders via local API keys.",parameters:N.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:o}=await Promise.resolve().then(n.t.bind(n,70857,23));const{spawn:i}=await Promise.resolve().then(n.t.bind(n,35317,23));const r=s(o(),".sf","runtime.pid");if(e(r)){const e=t(r,"utf-8").trim();try{process.kill(parseInt(e),0);return{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{}}const a=i(process.execPath,[process.argv[1],"runtime","start"],{detached:true,stdio:["ignore","ignore","ignore"],env:{...process.env}});a.unref();await new Promise((e=>setTimeout(e,1e3)));if(e(r)){const e=t(r,"utf-8").trim();return{content:[{type:"text",text:`Runtime started (PID ${e}). Polling every 30s for active intents.`}],details:{}}}return{content:[{type:"text",text:"Runtime starting... check status in a moment with runtime_status."}],details:{}}}},{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:N.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:s}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23));const 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{process.kill(parseInt(a),"SIGTERM");s(r);return{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:{}}}}});$e.push({name:"create_skill",description:"Create a custom agent skill — a reusable prompt/workflow triggered via slash command. Returns the new skill ID.",parameters:{name:{type:"string"},trigger:{type:"string"},description:{type:"string"},prompt:{type:"string"},category:{type:"string",optional:true},tags:{type:"string",optional:true,description:"Comma-separated tags"},toolsUsed:{type:"string",optional:true,description:"Comma-separated tool names"}},execute:async e=>{const t={name:e.name,trigger:e.trigger,description:e.description,prompt:e.prompt};if(e.category)t.category=e.category;if(e.tags)t.tags=e.tags.split(",").map((e=>e.trim()));if(e.toolsUsed)t.toolsUsed=e.toolsUsed.split(",").map((e=>e.trim()));const n=await fetch(`${i}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(t)});const s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"list_skills",description:"List all skills: built-in defaults + user-created custom skills.",parameters:{},execute:async()=>{const e=await fetch(`${i}/api/skill`,{headers:{Authorization:`Bearer ${o}`}});const t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"browse_public_skills",description:"Browse community-created skills. Filter by category, search, or sort by popularity. No auth needed.",parameters:{category:{type:"string",optional:true},q:{type:"string",optional:true},sort:{type:"string",optional:true,description:"popular or new"}},execute:async e=>{const t=new URLSearchParams;if(e.category)t.set("category",e.category);if(e.q)t.set("q",e.q);if(e.sort)t.set("sort",e.sort);const n=await fetch(`${i}/api/public/skills?${t}`);const s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"publish_skill",description:"Publish a skill to make it publicly browsable and forkable by other users.",parameters:{skillId:{type:"string"},slug:{type:"string"}},execute:async e=>{const t=await fetch(`${i}/api/skill/${e.skillId}/publish`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({slug:e.slug})});const n=await t.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"fork_skill",description:"Fork a public skill into your collection. Creates a copy you can customize.",parameters:{skillId:{type:"string",description:"ID of the public skill to fork"}},execute:async e=>{const t=await fetch(`${i}/api/skill/${e.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${o}`}});const n=await t.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"fork_thesis",description:"Fork a public thesis. Copies thesis statement + causal tree. Run formation after forking for fresh edges.",parameters:{slug:{type:"string",description:"Public thesis slug (from /thesis/:slug URL)"}},execute:async e=>{const t=await fetch(`${i}/api/thesis/${e.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${o}`}});const n=await t.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}});function buildSystemPrompt(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)";const n=e.causalTree?.nodes?.filter((e=>e.depth===0)).map((e=>` ${e.id} ${(e.label||"").slice(0,40)} — ${Math.round(e.probability*100)}%`)).join("\n")||" (no causal tree)";const s=typeof e.confidence==="number"?Math.round(e.confidence*100):typeof e.confidence==="string"?parseInt(e.confidence):0;return`You are a prediction market trading assistant. Your job is not to please the user — it is to help them see reality clearly and make correct trading decisions.\n\n## Your analytical framework\n\nEach thesis has a causal tree. Every node is a causal hypothesis with a probability. Nodes have causal relationships — when upstream nodes change, downstream nodes follow.\n\nEdge = thesis-implied price - actual market price. Positive edge = market underprices. Contracts with large edges AND good liquidity are most tradeable.\n\nexecutableEdge = real edge after subtracting bid-ask spread. Big theoretical edge with wide spread may not be worth entering.\n\n### Edge diagnosis (always classify)\nWhen reporting an edge, classify it:\n- "consensus gap": depth >= 500, market actively disagrees — real edge, real opponents\n- "attention gap": depth < 100, no real pricing — edge may be illusory, needs catalyst\n- "timing gap": market directionally agrees but lags — may close suddenly on news\n- "risk premium": edge reflects settlement ambiguity or platform risk, not alpha\nFor edges > 20 cents, state in one sentence what must be true for the market to be right and the thesis wrong.\n\n### Price reliability\n47 cents with depth 14K = strong consensus. 47 cents with depth 50 = three people's opinion.\n- depth >= 500: reliable, treat as market consensus\n- depth 100-500: moderate confidence, caveat when citing\n- depth < 100: unreliable — do NOT treat as "the market thinks X"\n- spread > 5 cents: wide disagreement, noisy midpoint\n- liquidityScore = low: do NOT recommend entry\n\n### Kill condition awareness\nEach top-level causal node has an implicit falsifier. When scanning news or evaluating events, check: "Does any event here fundamentally break a core assumption?" If yes, flag immediately — this overrides all other analysis.\n\n### Catalyst and time\nWhen discussing an edge, always state contract expiry and next identifiable catalyst. No visible catalyst = flag capital lock risk.\n\n### Research workflow\nFor complex questions, chain multiple tool calls:\n1. get_world_state (broad situational awareness) 2. get_context 3. inspect_book 4. get_liquidity 5. web_search 6. search_x 7. monitor_the_situation (scrape specific URLs) 8. synthesize\nUse get_world_delta for efficient polling (30-50 tokens vs 800 for full state). Use enrich_content to cross-reference any text with 9,706 markets.\nDon't answer a complex question with a single tool call.\n\n### Social signal research\nUse search_x to check X/Twitter sentiment on any topic — especially useful for geopolitical events, macro shifts, and breaking news that moves prediction markets. Use x_volume to detect discussion spikes (velocity > 1 = increasing attention). Use x_account to track specific analysts or officials.\n\n### Heartbeat config\nUse heartbeat_config to view or adjust per-thesis heartbeat settings: news/X scan intervals, evaluation model tier (cheap/medium/heavy), monthly budget cap, pause/resume. Also shows this month's cost breakdown (LLM calls, search calls, tokens, spend). Useful when the user asks about costs, wants to slow down/speed up monitoring, or if you detect budget overrun.\n\n### Conditional rules\n- Portfolio/positions questions: flag correlated exposure — positions sharing upstream causal nodes are not independent bets.\n- No catalyst visible within 30 days + edge not improving: flag "stale capital risk."\n- Edges < 10 cents, thin liquidity, no catalyst near: say "nothing to do right now." Do not manufacture urgency.\n\nShort-term markets settle into hard data that calibrates the thesis. Use them to verify node probabilities, not to bet.\n\n## Your behavioral rules\n\n- IMPORTANT: You do NOT know the user's current positions at conversation start. Before discussing trades, recommending entries/exits, or analyzing portfolio risk, call get_positions FIRST. Never assume the user has no positions — they may have large existing holdings you don't know about.\n- Think before calling tools. If the data is already in context, don't re-fetch.\n- If the user says "note this" or mentions a news event, inject a signal. Don't ask "should I note this?"\n- If the user says "evaluate" or "run it", trigger immediately. Don't confirm.\n- Don't end every response with "anything else?" — the user will ask when they want to.\n- If the user asks about latest news or real-time events, use web_search first, then answer based on results. If you find important information, suggest injecting it as a signal.\n- If you notice an edge narrowing or disappearing, say so proactively. Don't only report good news.\n- If a causal tree node probability seriously contradicts the market price, point it out.\n- Use Chinese if the user writes in Chinese, English if they write in English.\n- For any question about prices, positions, or P&L, ALWAYS call a tool to get fresh data first. Never answer price-related questions using the cached data in this system prompt.\n- Prices are in cents (e.g. 35¢). P&L, cost, and balance are in dollars (e.g. $90.66). Tool outputs are pre-formatted with units — do not re-convert.\n- Align tables. Be precise with numbers to the cent.\n\n## Strategy rules\n\nWhen the conversation produces a concrete trade idea (specific contract, direction, price conditions), use create_strategy to record it immediately. Don't wait for the user to say "record this."\n- Extract hard conditions (specific prices in cents) into entryBelow/stopLoss/takeProfit.\n- Put fuzzy conditions into softConditions (e.g. "only if n3 > 60%", "spread < 3¢").\n- Put the full reasoning into rationale.\n- After creating, confirm the strategy details.\n- If the user says "change the stop loss on T150 to 30", use update_strategy.\n\n## Intent & Execution\n\nUse create_intent to declare execution intents with trigger conditions (price_below, price_above, time, immediate). Use list_intents / cancel_intent to manage. The local runtime daemon (runtime_start/runtime_stop/runtime_status) evaluates triggers and executes orders via local API keys.\n\n## 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${ke.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||y}\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)}`:""}`}function buildExplorerPrompt(e){const t=(0,u.loadConfig)();const n=e.theses?.length||0;const s=e.edges?.length||0;const o=(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`}const be=$?buildExplorerPrompt(k):buildSystemPrompt(k);const we=new D({initialState:{systemPrompt:be,model:U,tools:$e,thinkingLevel:"off"},streamFn:L,getApiKey:e=>{if(e==="openrouter")return m;return undefined}});let _e=false;if(!t?.newSession){const e=loadSession(y||"_explorer");if(e?.messages?.length>0){try{const t=e.messages.filter((e=>{if(!e.role)return false;if(Array.isArray(e.content)&&e.content.length===0)return false;if(e.role==="assistant"&&!e.content&&!e.tool_calls?.length)return false;return true}));const n=[];for(const e of t){const t=n.length>0?n[n.length-1].role:null;if(e.role===t&&e.role!=="tool"){continue}n.push(e)}if(n.length>0&&n[n.length-1].role==="user"){n.pop()}we.replaceMessages(n);we.setSystemPrompt(be);_e=true}catch{}}}function persistSession(){try{const e=we.state.messages;if(e.length>0){saveSession(y||"_explorer",j,e)}}catch{}}let Se=null;let ve="";let xe=null;const Ce=new Map;const Oe=new Map;let Ie=null;function throttledRender(){if(Ie)return;Ie=setTimeout((()=>{Ie=null;Z.requestRender()}),66)}function flushRender(){if(Ie){clearTimeout(Ie);Ie=null}Z.requestRender()}we.subscribe((e=>{if(e.type==="message_start"){ve="";Se=null;xe=new P(Z,(e=>h.emerald(e)),(e=>h.zinc600(e)),"thinking...");xe.start();ae.addChild(xe);Z.requestRender()}if(e.type==="message_update"){const t=e.assistantMessageEvent;if(t.type==="text_delta"){if(xe){xe.stop();ae.removeChild(xe);xe=null;Se=new O("",1,0,ee,te);ae.addChild(Se)}ve+=t.delta;if(Se){Se.setText(ve)}throttledRender()}}if(e.type==="message_end"){if(xe){xe.stop();ae.removeChild(xe);xe=null}if(Se&&ve){Se.setText(ve)}addSpacer();Se=null;ve="";flushRender()}if(e.type==="agent_end"){J=false;persistSession();flushRender();if(X){const e=X;X=null;handleHeartbeatDelta(e)}}if(e.type==="tool_execution_start"){const t=new F(h.zinc600(` ▸ ${e.toolName}...`));Ce.set(e.toolCallId||e.toolName,Date.now());Oe.set(e.toolCallId||e.toolName,t);ae.addChild(t);B++;se.toolCount=B;se.update();Z.requestRender()}if(e.type==="tool_execution_end"){const t=e.toolCallId||e.toolName;const n=Ce.get(t);const s=n?((Date.now()-n)/1e3).toFixed(1):"?";const o=Oe.get(t);if(o){if(e.isError){o.setText(h.red(` ✗ ${e.toolName} (${s}s) error`))}else{o.setText(h.zinc600(` ▸ ${e.toolName} `)+h.emerald(`✓`)+h.zinc600(` ${s}s`))}}Ce.delete(t);Oe.delete(t);Z.requestRender()}}));async function handleSlashCommand(e){const t=e.trim().split(/\s+/);const s=t[0].toLowerCase();switch(s){case"/help":{addSpacer();addSystemText(h.zinc200(bold("Commands"))+"\n"+h.emerald("/help ")+h.zinc400("Show this help")+"\n"+h.emerald("/tree ")+h.zinc400("Display causal tree")+"\n"+h.emerald("/edges ")+h.zinc400("Display edge/spread table")+"\n"+h.emerald("/pos ")+h.zinc400("Display Kalshi positions")+"\n"+h.emerald("/eval ")+h.zinc400("Trigger deep evaluation")+"\n"+h.emerald("/switch <id>")+h.zinc400(" Switch thesis")+"\n"+h.emerald("/compact ")+h.zinc400("Compress conversation history")+"\n"+h.emerald("/new ")+h.zinc400("Start fresh session")+"\n"+h.emerald("/model <m> ")+h.zinc400("Switch model")+"\n"+h.emerald("/env ")+h.zinc400("Show environment variable status")+"\n"+(ke.tradingEnabled?h.zinc600("─".repeat(30))+"\n"+h.emerald("/buy ")+h.zinc400("TICKER QTY PRICE — quick buy")+"\n"+h.emerald("/sell ")+h.zinc400("TICKER QTY PRICE — quick sell")+"\n"+h.emerald("/cancel ")+h.zinc400("ORDER_ID — cancel order")+"\n"+h.zinc600("─".repeat(30))+"\n":"")+(de.length>0?h.zinc600("─".repeat(30))+"\n"+h.zinc200(bold("Skills"))+"\n"+de.map((e=>h.emerald(`/${e.name.padEnd(10)}`)+h.zinc400(e.description.slice(0,45)))).join("\n")+"\n"+h.zinc600("─".repeat(30))+"\n":"")+h.emerald("/clear ")+h.zinc400("Clear screen (keeps history)")+"\n"+h.emerald("/exit ")+h.zinc400("Exit (auto-saves)"));addSpacer();return true}case"/tree":{addSpacer();if($){addSystemText(h.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one."))}else{try{k=await g.getContext(y);addSystemText(h.zinc200(bold("Causal Tree"))+"\n"+renderCausalTree(k,b))}catch(e){addSystemText(h.red(`Error: ${e.message}`))}}addSpacer();return true}case"/edges":{addSpacer();if($){try{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));const t=await e();const s=(t.edges||[]).sort(((e,t)=>Math.abs(t.edge)-Math.abs(e.edge))).slice(0,10);if(s.length===0){addSystemText(h.zinc400("No public edges available."))}else{const e=s.map((e=>{const t=(e.title||"").slice(0,35).padEnd(35);const n=(e.venue||"kalshi").padEnd(5);const s=String(Math.round(e.price||0)).padStart(3)+"¢";const o="+"+Math.round(e.edge||0);return` ${h.zinc400(t)} ${h.zinc600(n)} ${h.zinc400(s)} ${h.emerald(o.padStart(4))}`})).join("\n");addSystemText(h.zinc200(bold("Public Edges"))+"\n"+e)}}catch(e){addSystemText(h.red(`Error: ${e.message}`))}}else{try{k=await g.getContext(y);if(W){k._positions=W}addSystemText(h.zinc200(bold("Edges"))+"\n"+renderEdges(k,b))}catch(e){addSystemText(h.red(`Error: ${e.message}`))}}addSpacer();return true}case"/pos":{addSpacer();try{const e=await(0,c.getPositions)();if(!e){addSystemText(h.zinc600("Kalshi not configured"));return true}for(const t of e){const e=await(0,c.getMarketPrice)(t.ticker);if(e!==null){t.current_value=e;t.unrealized_pnl=Math.round((e-t.average_price_paid)*t.quantity)}}W=e;addSystemText(h.zinc200(bold("Positions"))+"\n"+renderPositions(e))}catch(e){addSystemText(h.red(`Error: ${e.message}`))}addSpacer();return true}case"/eval":{addSpacer();if($){addSystemText(h.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one."));addSpacer();return true}addSystemText(h.zinc600("Triggering evaluation..."));Z.requestRender();try{const e=await g.evaluate(y);addSystemText(h.emerald("Evaluation complete")+"\n"+h.zinc400(JSON.stringify(e,null,2)))}catch(e){addSystemText(h.red(`Error: ${e.message}`))}addSpacer();return true}case"/model":{const e=t.slice(1).join(" ").trim();if(!e){addSystemText(h.zinc400(`Current model: ${j}`));return true}addSpacer();j=e.replace(/^openrouter\//,"");U=resolveModel(j);we.setModel(U);se.modelName=j;se.update();addSystemText(h.emerald(`Model switched to ${j}`));addSpacer();Z.requestRender();return true}case"/switch":{const e=t[1]?.trim();if(!e){addSystemText(h.zinc400("Usage: /switch <thesisId>"));return true}addSpacer();try{persistSession();const t=await g.getContext(e);y=t.thesisId||e;k=t;const n=buildSystemPrompt(t);const s=typeof t.confidence==="number"?Math.round(t.confidence*100):0;we.clearMessages();const o=loadSession(y);if(o?.messages?.length>0){we.replaceMessages(o.messages);we.setSystemPrompt(n);addSystemText(h.emerald(`Switched to ${y.slice(0,8)}`)+h.zinc400(` (resumed ${o.messages.length} messages)`))}else{we.setSystemPrompt(n);addSystemText(h.emerald(`Switched to ${y.slice(0,8)}`)+h.zinc400(" (new session)"))}se.setFromContext(t,oe||undefined);ae.clear();addSystemText(buildWelcomeDashboard(t,oe))}catch(e){addSystemText(h.red(`Switch failed: ${e.message}`))}addSpacer();Z.setFocus(ce);Z.requestRender();return true}case"/compact":{addSpacer();try{const e=we.state.messages;if(e.length<=10){addSystemText(h.zinc400("Conversation too short to compact"));addSpacer();Z.setFocus(ce);return true}const t=3;let n=0;let s=e.length;for(let o=e.length-1;o>=0;o--){if(e[o].role==="user"){n++;if(n>=t){s=o;break}}}if(s<=2){addSystemText(h.zinc400("Not enough complete turns to compact"));addSpacer();Z.setFocus(ce);return true}const o=e.slice(0,s);const a=e.slice(s);const c=new P(Z,(e=>h.emerald(e)),(e=>h.zinc600(e)),"compacting with LLM...");c.start();ae.addChild(c);Z.requestRender();const l=[];let d=0;const u=12e3;for(const e of o){if(d>=u)break;let t="";if(typeof e.content==="string"){t=e.content}else if(Array.isArray(e.content)){t=e.content.filter((e=>e.type==="text")).map((e=>e.text)).join("\n")}if(!t)continue;const n=(e.role||"unknown").toUpperCase();const s=t.slice(0,800);const o=`[${n}]: ${s}`;l.push(o);d+=o.length}const p=l.join("\n\n");const f="google/gemini-2.0-flash-001";const g=`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";const t={model:f,messages:[{role:"system",content:g},{role:"user",content:`Summarize this conversation (${o.length} messages):\n\n${p}`}],max_tokens:2e3,temperature:.2};const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m}`,"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();y=s.choices?.[0]?.message?.content||"";if(!y){throw new Error("Empty summary from LLM")}}catch(e){const t=[];for(const e of o){const n=typeof e.content==="string"?e.content:"";if(e.role==="user"&&n){t.push(`- User: ${n.slice(0,100)}`)}else if(e.role==="assistant"&&n){t.push(`- Assistant: ${n.slice(0,150)}`)}}y=`[LLM summary failed: ${e.message}. Fallback bullet points:]\n\n${t.slice(-20).join("\n")}`}c.stop();ae.removeChild(c);const $=[{role:"user",content:`[Conversation summary — ${o.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."},...a];we.clearMessages();we.replaceMessages($);we.setSystemPrompt(be);persistSession();addSystemText(h.emerald(`Compacted: ${o.length} messages → summary + ${a.length} recent`)+h.zinc600(` (via ${f.split("/").pop()})`));addSpacer();Z.setFocus(ce);Z.requestRender()}catch(e){addSystemText(h.red(`Compact failed: ${e.message||e}`));addSpacer();Z.setFocus(ce);Z.requestRender()}return true}case"/new":{addSpacer();persistSession();we.clearMessages();we.setSystemPrompt(be);ae.clear();addSystemText(h.emerald("Session cleared")+h.zinc400(" — fresh start"));addSpacer();Z.requestRender();return true}case"/env":{addSpacer();const e=[{name:"SF_API_KEY",key:"SF_API_KEY",required:true,mask:true},{name:"SF_API_URL",key:"SF_API_URL",required:false,mask:false},{name:"OPENROUTER_KEY",key:"OPENROUTER_API_KEY",required:true,mask:true},{name:"KALSHI_KEY_ID",key:"KALSHI_API_KEY_ID",required:false,mask:true},{name:"KALSHI_PEM_PATH",key:"KALSHI_PRIVATE_KEY_PATH",required:false,mask:false},{name:"TAVILY_API_KEY",key:"TAVILY_API_KEY",required:false,mask:true}];const t=e.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)} ${h.emerald("✓")} ${h.zinc400(n)}`}else{const t=e.required?"必须":"可选";return` ${e.name.padEnd(18)} ${h.red("✗")} ${h.zinc600(`未配置(${t})`)}`}}));addSystemText(h.zinc200(bold("Environment"))+"\n"+t.join("\n"));addSpacer();return true}case"/clear":{const e=[...ae.children||[]];for(const t of e){try{ae.removeChild(t)}catch{}}addSpacer();J=false;V=null;Z.setFocus(ce);Z.requestRender();return true}case"/buy":{const[,e,s,o]=t;if(!e||!s||!o){addSystemText(h.zinc400("Usage: /buy TICKER QTY PRICE_CENTS (e.g. /buy KXWTIMAX-26DEC31-T135 100 50)"));return true}if(!ke.tradingEnabled){addSystemText(h.red("Trading disabled. Run: sf setup --enable-trading"));return true}addSpacer();const i=await promptUser(`BUY ${s}x ${e} YES @ ${o}¢ — execute? (y/n)`);if(i.toLowerCase().startsWith("y")){try{const{createOrder:t}=await Promise.resolve().then(n.t.bind(n,96139,23));const i=await t({ticker:e,side:"yes",action:"buy",type:"limit",count:parseInt(s),yes_price:parseInt(o)});addSystemText(h.emerald("✓ Order placed: "+((i.order||i).order_id||"OK")))}catch(e){addSystemText(h.red("✗ "+e.message))}}else{addSystemText(h.zinc400("Cancelled."))}addSpacer();return true}case"/sell":{const[,e,s,o]=t;if(!e||!s||!o){addSystemText(h.zinc400("Usage: /sell TICKER QTY PRICE_CENTS"));return true}if(!ke.tradingEnabled){addSystemText(h.red("Trading disabled. Run: sf setup --enable-trading"));return true}addSpacer();const i=await promptUser(`SELL ${s}x ${e} YES @ ${o}¢ — execute? (y/n)`);if(i.toLowerCase().startsWith("y")){try{const{createOrder:t}=await Promise.resolve().then(n.t.bind(n,96139,23));const i=await t({ticker:e,side:"yes",action:"sell",type:"limit",count:parseInt(s),yes_price:parseInt(o)});addSystemText(h.emerald("✓ Order placed: "+((i.order||i).order_id||"OK")))}catch(e){addSystemText(h.red("✗ "+e.message))}}else{addSystemText(h.zinc400("Cancelled."))}addSpacer();return true}case"/cancel":{const[,e]=t;if(!e){addSystemText(h.zinc400("Usage: /cancel ORDER_ID"));return true}if(!ke.tradingEnabled){addSystemText(h.red("Trading disabled. Run: sf setup --enable-trading"));return true}addSpacer();try{const{cancelOrder:t}=await Promise.resolve().then(n.t.bind(n,96139,23));await t(e);addSystemText(h.emerald(`✓ Order ${e} cancelled.`))}catch(e){addSystemText(h.red("✗ "+e.message))}addSpacer();return true}case"/exit":case"/quit":{cleanup();return true}default:{const e=de.find((e=>e.trigger===s));if(e){addSpacer();addSystemText(h.zinc200(`Running skill: ${bold(e.name)}`)+h.zinc600(` — ${e.description.slice(0,60)}`));addSpacer();Z.requestRender();J=true;try{await we.prompt(e.prompt)}catch(e){addSystemText(h.red(`Skill error: ${e.message}`))}finally{J=false}return true}return false}}}ce.onSubmit=async e=>{const t=e.trim();if(!t)return;if(V){const{resolve:e}=V;V=null;const n=new C(h.zinc400(" > ")+h.zinc200(t),1,0);ae.addChild(n);addSpacer();Z.requestRender();e(t);return}if(J)return;ce.addToHistory(t);if(t.startsWith("/")){const e=await handleSlashCommand(t);if(e)return}J=true;const n=new C(h.emerald(bold(">"))+" "+h.white(t),1,0);ae.addChild(n);addSpacer();Z.requestRender();try{await we.prompt(t)}catch(e){if(xe){xe.stop();ae.removeChild(xe);xe=null}addSystemText(h.red(`Error: ${e.message}`));addSpacer();J=false}};function cleanup(){if(Y)clearInterval(Y);if(xe)xe.stop();persistSession();Z.stop();process.exit(0)}Z.addInputListener((e=>{if(e===""){cleanup();return{consume:true}}return undefined}));process.on("SIGINT",cleanup);process.on("SIGTERM",cleanup);function buildWelcomeDashboard(e,t){const n=[];if(e._explorerMode){const t=e.edges?.length||0;const s=e.theses?.length||0;n.push(h.zinc600("─".repeat(55)));n.push(" "+h.emerald(bold("Explorer mode"))+h.zinc600(" — full market access, no thesis"));n.push(" "+h.zinc600(`${s} public theses │ ${t} edges tracked`));n.push(h.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(" "+h.zinc400(bold("TOP PUBLIC EDGES"))+h.zinc600(" mkt edge"));for(const t of e){const e=(t.title||"").slice(0,30).padEnd(30);const s=String(Math.round(t.price||0)).padStart(3)+"¢";const o=t.edge||0;const i="+"+Math.round(o);const r=Math.abs(o)>=15?h.emerald:Math.abs(o)>=8?h.amber:h.zinc400;n.push(` ${h.zinc400(e)} ${h.zinc400(s)} ${r(i.padStart(4))}`)}}n.push(h.zinc600("─".repeat(55)));n.push(" "+h.zinc600("Ask anything, or describe a view to create a thesis."));n.push(h.zinc600("─".repeat(55)));return n.join("\n")}const s=e.thesis||e.rawThesis||"N/A";const o=s.length>100?s.slice(0,100)+"...":s;const i=typeof e.confidence==="number"?Math.round(e.confidence*100):typeof e.confidence==="string"?Math.round(parseFloat(e.confidence)*100):0;const r=e.lastEvaluation?.confidenceDelta?Math.round(e.lastEvaluation.confidenceDelta*100):0;const a=r!==0?` (${r>0?"+":""}${r})`:"";const c=e.lastEvaluation?.evaluatedAt?Math.round((Date.now()-new Date(e.lastEvaluation.evaluatedAt).getTime())/36e5):null;n.push(h.zinc600("─".repeat(55)));n.push(" "+h.zinc200(bold(o)));n.push(" "+h.zinc600(`${e.status||"active"} ${i}%${a}`)+(c!==null?h.zinc600(` │ last eval: ${c<1?"<1":c}h ago`):""));n.push(h.zinc600("─".repeat(55)));if(t&&t.length>0){n.push(" "+h.zinc400(bold("POSITIONS")));let e=0;for(const s of t){const t=s.unrealized_pnl||0;e+=t;const o=t>=0?h.emerald(`+$${(t/100).toFixed(2)}`):h.red(`-$${(Math.abs(t)/100).toFixed(2)}`);const i=(s.ticker||"").slice(0,28).padEnd(28);const r=String(s.quantity||0).padStart(5);const a=s.side==="yes"?h.emerald("Y"):h.red("N");n.push(` ${h.zinc400(i)} ${r} ${a} ${o}`)}const s=e>=0?h.emerald(bold(`+$${(e/100).toFixed(2)}`)):h.red(bold(`-$${(Math.abs(e)/100).toFixed(2)}`));n.push(` ${"".padEnd(28)} ${h.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(h.zinc600("─".repeat(55)));n.push(" "+h.zinc400(bold("TOP EDGES"))+h.zinc600(" mkt edge liq"));for(const t of e){const e=(t.market||t.marketTitle||t.marketId||"").slice(0,30).padEnd(30);const s=String(Math.round(t.marketPrice||0)).padStart(3)+"¢";const o=t.edge||t.edgeSize||0;const i=(o>0?"+":"")+Math.round(o);const r=t.orderbook?.liquidityScore||(t.venue==="polymarket"?"-":"?");const a=Math.abs(o)>=15?h.emerald:Math.abs(o)>=8?h.amber:h.zinc400;n.push(` ${h.zinc400(e)} ${h.zinc400(s)} ${a(i.padStart(4))} ${h.zinc600(r)}`)}}n.push(h.zinc600("─".repeat(55)));return n.join("\n")}const Pe=_e?h.zinc600(`resumed (${we.state.messages.length} messages)`):h.zinc600("new session");addSystemText(buildWelcomeDashboard(k,oe));addSystemText(" "+Pe);addSpacer();const Te=.03;function handleHeartbeatDelta(e){const t=Math.abs(e.confidenceDelta||0);const n=Math.round((e.confidence||0)*100);const s=Math.round((e.confidenceDelta||0)*100);const o=s>0?"+":"";if(t>=Te){const t=s>0?"▲":"▼";const i=s>0?h.emerald:h.red;addSystemText(i(` ${t} Heartbeat: confidence ${o}${s}% → ${n}%`));if(e.latestSummary){addSystemText(h.zinc400(` ${e.latestSummary.slice(0,100)}`))}addSpacer();se.setFromContext({...k,confidence:e.confidence,lastEvaluation:{confidenceDelta:e.confidenceDelta}},oe||undefined);Z.requestRender();J=true;const r=`[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.`;we.prompt(r).catch((e=>{addSystemText(h.red(`Error: ${e.message}`));J=false}))}else if(t>0){addSystemText(h.zinc600(` ─ heartbeat: ${n}% (${o}${s}%) — ${e.evaluationCount||0} eval(s)`));Z.requestRender()}}if(!$)Y=setInterval((async()=>{try{const e=await g.getChanges(y,G);G=(new Date).toISOString();if(!e.changed)return;if(J||V){X=e}else{handleHeartbeatDelta(e)}}catch{}}),6e4);Z.start()}async function runPlainTextAgent(e){const{openrouterKey:t,sfClient:s,resolvedThesisId:o,opts:i,useProxy:r,llmBaseUrl:p,sfApiKey:h,sfApiUrl:m}=e;let f=e.latestContext;const g=await Promise.resolve().then(n.t.bind(n,23785,23));const y=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641));const $=await Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653));const{getModel:k,streamSimple:b,Type:w}=y;const{Agent:_}=$;const S=i?.model||"anthropic/claude-sonnet-4.6";let v=S.replace(/^openrouter\//,"");function resolveModel(e){let t;try{t=k("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:true,supportsTools:true}}if(r)t.baseUrl=p;return t}let x=resolveModel(v);const C=w.Object({thesisId:w.String({description:"Thesis ID"})});const O=w.Object({thesisId:w.String({description:"Thesis ID"}),content:w.String({description:"Signal content"}),type:w.Optional(w.String({description:"Signal type: news, user_note, external"}))});const I=w.Object({query:w.Optional(w.String({description:"Keyword search"})),series:w.Optional(w.String({description:"Series ticker"})),market:w.Optional(w.String({description:"Market ticker"}))});const P=w.Object({query:w.String({description:"Search keywords"})});const T=w.Object({});const E=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:C,execute:async(e,t)=>{const n=await s.getContext(t.thesisId);f=n;return{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:T,execute:async()=>{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));const 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:w.Object({q:w.String({description:"Natural language query"})}),execute:async(e,t)=>{const{fetchQuery:s}=await Promise.resolve().then(n.bind(n,19218));const 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:w.Object({topic:w.Optional(w.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));const 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:w.Object({symbols:w.String({description:"Comma-separated. Futures: ROOT.c.0. E.g. SPY, CL.c.0"}),dataset:w.Optional(w.String({description:"DBEQ.BASIC, GLBX.MDP3, OPRA.PILLAR"})),schema:w.Optional(w.String({description:"ohlcv-1d, ohlcv-1h, ohlcv-1m, trades"})),stype:w.Optional(w.String({description:"raw_symbol or continuous"})),days:w.Optional(w.Number({description:"Lookback (max 30)"}))}),execute:async(e,t)=>{const n=new URLSearchParams({symbols:t.symbols});if(t.dataset)n.set("dataset",t.dataset);if(t.schema)n.set("schema",t.schema);if(t.stype)n.set("stype",t.stype);if(t.days)n.set("days",String(t.days));const s=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:O,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:C,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:I,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)();const 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:T,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:T,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);if(e!==null){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:P,execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY;const s=!n&&h;if(!n&&!s)return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let o;if(n){o=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:true})})}else{o=await fetch(`${m}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({query:t.query,max_results:5,search_depth:"basic",include_answer:true})})}if(!o.ok)return{content:[{type:"text",text:`Search failed: ${o.status}`}],details:{}};const i=await o.json();const r=(i.results||[]).map((e=>`[${e.title}](${e.url})\n${e.content?.slice(0,200)}`)).join("\n\n");const a=i.answer?`Summary: ${i.answer}\n\n---\n\n`:"";return{content:[{type:"text",text:`${a}${r}`}],details:{}}}},{name:"get_milestones",label:"Milestones",description:"Get upcoming events from Kalshi calendar. Use to check economic releases, political events, or other catalysts.",parameters:w.Object({hours:w.Optional(w.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:w.Optional(w.String({description:"Filter by category (e.g. Economics, Politics, Sports)"}))}),execute:async(e,t)=>{const n=t.hours||168;const s=new Date;const o=`https://api.elections.kalshi.com/trade-api/v2/milestones?limit=200&minimum_start_date=${s.toISOString()}`+(t.category?`&category=${t.category}`:"");const 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();const a=s.getTime()+n*36e5;const 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:w.Object({eventTicker:w.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:w.Optional(w.Number({description:"Days of history (default 7)"}))}),execute:async(e,t)=>{const{getForecastHistory:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=t.days||7;const 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();const 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()-o*864e5)/1e3),endTs:Math.floor(Date.now()/1e3),periodInterval:1440});if(!c||c.length===0)return{content:[{type:"text",text:"No forecast data available"}],details:{}};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled (resolved) contracts with P&L.",parameters:w.Object({ticker:w.Optional(w.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getSettlements:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=await s({limit:100,ticker:t.ticker});if(!o)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(o.settlements,null,2)}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance and portfolio value.",parameters:T,execute:async()=>{const{getBalance:e}=await Promise.resolve().then(n.t.bind(n,96139,23));const t=await e();if(!t)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_orders",label:"Orders",description:"Get current resting orders on Kalshi.",parameters:w.Object({status:w.Optional(w.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));const o=await s({status:t.status||"resting",limit:100});if(!o)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(o.orders,null,2)}],details:{}}}},{name:"get_fills",label:"Fills",description:"Get recent trade fills (executed trades) on Kalshi.",parameters:w.Object({ticker:w.Optional(w.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getFills:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=await s({ticker:t.ticker,limit:50});if(!o)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(o.fills,null,2)}],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:w.Object({topic:w.String({description:"Topic to scan (e.g. oil, crypto, fed, geopolitics)"})}),execute:async(e,t)=>{const n=t.topic.toLowerCase();const s=d.TOPIC_SERIES[n];if(!s){return{content:[{type:"text",text:`Unknown topic "${t.topic}". Available: ${Object.keys(d.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`;const n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)continue;const s=(await n.json()).markets||[];const i=await Promise.allSettled(s.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(e.status!=="fulfilled"||!e.value.ob)continue;const{ticker:t,title:n,ob:s}=e.value;const i=(s.yes_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),qty:parseFloat(t)}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const r=(s.no_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),qty:parseFloat(t)}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const a=i[0]?.price||0;const c=r.length>0?100-r[0].price:100;const l=c-a;const d=i.slice(0,3).reduce(((e,t)=>e+t.qty),0)+r.slice(0,3).reduce(((e,t)=>e+t.qty),0);const 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(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 s=await(0,l.polymarketGetOrderbookWithDepth)(n[0]);if(!s)continue;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{}o.sort(((e,t)=>e.spread-t.spread));return{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:w.Object({ticker:w.Optional(w.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:w.Optional(w.Array(w.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:w.Optional(w.String({description:'Search Polymarket by keyword (e.g. "oil price above 100")'}))}),execute:async(e,t)=>{const n=[];const s=[];if(t.tickers?.length)s.push(...t.tickers);else if(t.ticker)s.push(t.ticker);for(const e of s){try{const t=await(0,a.kalshiFetchMarket)(e);const s=t.status||"unknown";if(s!=="open"&&s!=="active"){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(parseFloat(t.last_price_dollars||"0")*100)})}else{const s=await(0,c.getPublicOrderbook)(e);const o=(s?.yes_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const i=(s?.no_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));if(o.length===0&&i.length===0){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(parseFloat(t.last_price_dollars||"0")*100),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;const r=i.length>0?100-i[0].price:o[0]?o[0].price+1:100;const a=r-s;const c=o.slice(0,3).reduce(((e,t)=>e+t.size),0)+i.slice(0,3).reduce(((e,t)=>e+t.size),0);const 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(parseFloat(t.last_price_dollars||"0")*100),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 s=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!s)continue;const o=await(0,l.polymarketGetOrderbookWithDepth)(s[0]);if(!o)continue;const i=(0,l.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(i[0]*100):0,volume24h:e.volume24hr||0})}}}catch{}}if(n.length===0){return{content:[{type:"text",text:"No markets found. Provide ticker (Kalshi) or polyQuery (Polymarket search)."}],details:{}}}return{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:T,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:w.Object({rawThesis:w.String({description:"The raw thesis statement to create"}),webhookUrl:w.Optional(w.String({description:"Optional webhook URL for notifications"}))}),execute:async(e,t)=>{const n=await s.createThesis(t.rawThesis,true);const o=n.thesis||n;const i=o.causalTree?.nodes?.length||0;const r=(o.edges||[]).length;const a=typeof o.confidence==="number"?Math.round(o.confidence*100):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:T,execute:async()=>{const{theses:e}=await s.listTheses();const t=(e||[]).filter((e=>e.status==="active"||e.status==="monitoring"));const n=await Promise.allSettled(t.map((async e=>{const t=await s.getContext(e.id);return(t.edges||[]).map((t=>({...t,thesisId:e.id})))})));const o=[];for(const e of n){if(e.status==="fulfilled")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:w.Object({hours:w.Optional(w.Number({description:"Hours of history to fetch (default 24)"}))}),execute:async(e,t)=>{const n=await s.getFeed(t.hours||24);const o=Array.isArray(n)?n:n?.evaluations||n?.items||[];let i=null;let r=0;for(const e of o){let t=0;const n=Math.abs(e.confidenceDelta||e.confidence_delta||0);if(n>0)t=n*100;else if(e.summary?.length>50)t=.1;if(t>r){r=t;i=e}}const a={total:o.length};if(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;return{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:w.Object({hours:w.Optional(w.Number({description:"Hours of history (default 1)"}))}),execute:async(e,t)=>{const n=t.hours||1;const s=new Date(Date.now()-n*60*60*1e3).toISOString();const o=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:w.Object({slug:w.Optional(w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),marketId:w.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:w.String({description:"Human-readable market name"}),direction:w.String({description:"yes or no"}),horizon:w.Optional(w.String({description:"short, medium, or long. Default: medium"})),entryBelow:w.Optional(w.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:w.Optional(w.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:w.Optional(w.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:w.Optional(w.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:w.Optional(w.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:w.Optional(w.Number({description:"Contracts per order. Default: 50"})),softConditions:w.Optional(w.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:w.Optional(w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),status:w.Optional(w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),strategyId:w.String({description:"Strategy ID (UUID)"}),stopLoss:w.Optional(w.Number({description:"New stop loss (cents)"})),takeProfit:w.Optional(w.Number({description:"New take profit (cents)"})),entryBelow:w.Optional(w.Number({description:"New entry below trigger (cents)"})),entryAbove:w.Optional(w.Number({description:"New entry above trigger (cents)"})),status:w.Optional(w.String({description:"New status: active|watching|executed|cancelled|review"})),priority:w.Optional(w.Number({description:"New priority"})),softConditions:w.Optional(w.String({description:"Updated soft conditions"})),rationale:w.Optional(w.String({description:"Updated rationale"}))}),execute:async(e,t)=>{const{thesisId:n,strategyId:o,...i}=t;const 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:w.Object({overrides:w.Array(w.Object({nodeId:w.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:w.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{const n=f;const s=[];function flatten(e){for(const t of e){s.push(t);if(t.children?.length)flatten(t.children)}}const o=n.causalTree?.nodes||[];flatten(o);const i=o.filter((e=>e.depth===0||e.depth===undefined&&!e.id.includes(".")));const r=new Map(t.overrides.map((e=>[e.nodeId,e.newProbability])));const a=i.reduce(((e,t)=>e+(t.probability||0)*(t.importance||0)),0);const c=i.reduce(((e,t)=>{const n=r.get(t.id)??t.probability??0;return e+n*(t.importance||0)}),0);const l=new Map;for(const[e,t]of r.entries()){const n=s.find((t=>t.id===e));if(n&&n.probability>0)l.set(e,Math.max(0,Math.min(2,t/n.probability)))}const d=(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(l.has(t)){n=l.get(t);break}}}const s=e.marketPrice||0;const o=e.thesisPrice||e.thesisImpliedPrice||s;const i=e.edge||e.edgeSize||0;const r=Math.round((s+(o-s)*n)*100)/100;const a=e.direction||"yes";const c=Math.round((a==="yes"?r-s:s-r)*100)/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=>e.signal!=="unchanged"));const u={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(a*100),new:Math.round(c*100),delta:Math.round((c-a)*100)},affectedEdges:d};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],details:{}}}}];E.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:w.Object({query:w.String({description:"Search query"}),mode:w.Optional(w.String({description:'"summary" or "raw"'})),hours:w.Optional(w.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:w.Object({query:w.String({description:"Search query"}),hours:w.Optional(w.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:w.Object({query:w.String({description:"Search query"}),limit:w.Optional(w.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:w.Object({username:w.String({description:"X username (with or without @)"}),hours:w.Optional(w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),newsIntervalMin:w.Optional(w.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:w.Optional(w.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:w.Optional(w.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:w.Optional(w.Number({description:"Monthly budget (0 = unlimited)"})),paused:w.Optional(w.Boolean({description:"Pause or resume heartbeat"}))}),execute:async(e,t)=>{const n=t.newsIntervalMin||t.xIntervalMin||t.evalModelTier||t.monthlyBudgetUsd!==undefined||t.paused!==undefined;if(n){const e={};if(t.newsIntervalMin)e.newsIntervalMin=t.newsIntervalMin;if(t.xIntervalMin)e.xIntervalMin=t.xIntervalMin;if(t.evalModelTier)e.evalModelTier=t.evalModelTier;if(t.monthlyBudgetUsd!==undefined)e.monthlyBudgetUsd=t.monthlyBudgetUsd;if(t.paused!==undefined)e.paused=t.paused;await s.updateHeartbeatConfig(t.thesisId,e)}const o=await s.getHeartbeatConfig(t.thesisId);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}});E.push({name:"configure_heartbeat",label:"Configure Heartbeat",description:"Adjust the 24/7 monitoring engine: news interval, X interval, model tier, budget, pause/resume.",parameters:w.Object({thesisId:w.String({description:"Thesis ID"}),newsIntervalMin:w.Optional(w.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:w.Optional(w.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:w.Optional(w.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:w.Optional(w.Number({description:"Monthly budget cap (0=unlimited)"})),paused:w.Optional(w.Boolean({description:"Pause/resume"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t;const 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:w.Object({thesisId:w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),title:w.Optional(w.String({description:"New title"})),status:w.Optional(w.String({description:"active, paused, or archived"})),webhookUrl:w.Optional(w.String({description:"Webhook URL (HTTPS)"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t;const 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:w.Object({thesisId:w.String({description:"Thesis ID"}),venue:w.String({description:"kalshi or polymarket"}),externalMarketId:w.String({description:"Market ticker"}),marketTitle:w.String({description:"Market name"}),direction:w.String({description:"yes or no"}),entryPrice:w.Number({description:"Entry price in cents"}),size:w.Optional(w.Number({description:"Contracts"})),rationale:w.Optional(w.String({description:"Why"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t;const 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:w.Object({thesisId:w.String({description:"Thesis ID"}),positionId:w.String({description:"Position ID"}),currentPrice:w.Optional(w.Number({description:"Current price (cents)"})),edge:w.Optional(w.Number({description:"Current edge (cents)"})),status:w.Optional(w.String({description:"open or closed"}))}),execute:async(e,t)=>{const{thesisId:n,positionId:o,...i}=t;const 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:w.Object({thesisId:w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),updates:w.Array(w.Object({nodeId:w.String({description:"Node ID (e.g. n3)"}),probability:w.Number({description:"New probability (0-1)"}),reason:w.Optional(w.String({description:"Why"}))})),lock:w.Optional(w.Array(w.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:{}}}});E.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:w.Object({freshness:w.Optional(w.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:w.Optional(w.String({description:"Filter: macro, geopolitics, crypto, policy, event"}))}),execute:async(e,t)=>{const n=new URLSearchParams;if(t.freshness)n.set("freshness",t.freshness);if(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:w.Object({action:w.String({description:"buy or sell"}),venue:w.String({description:"kalshi or polymarket"}),marketId:w.String({description:"Market ticker"}),marketTitle:w.String({description:"Human-readable name"}),direction:w.String({description:"yes or no"}),targetQuantity:w.Number({description:"Number of contracts"}),maxPrice:w.Optional(w.Number({description:"Max price per contract in cents (1-99)"})),triggerType:w.Optional(w.String({description:"immediate, price_below, price_above, time"})),triggerPrice:w.Optional(w.Number({description:"Price trigger threshold in cents"})),rationale:w.Optional(w.String({description:"Why this trade"})),autoExecute:w.Optional(w.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(e,t)=>{const n=await s.createIntent({...t,source:"agent",expireAt:new Date(Date.now()+24*60*60*1e3).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:w.Object({activeOnly:w.Optional(w.Boolean({description:"Only active intents (default true)"}))}),execute:async(e,t)=>{const n=await s.listIntents({active:t.activeOnly!==false});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:w.Object({intentId:w.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 A=(0,u.loadConfig)();if(A.tradingEnabled){E.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Shows preview and asks for confirmation.",parameters:w.Object({ticker:w.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:w.String({description:"yes or no"}),action:w.String({description:"buy or sell"}),type:w.String({description:"limit or market"}),count:w.Number({description:"Number of contracts"}),price_cents:w.Optional(w.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));const o=await Promise.resolve().then(n.t.bind(n,23785,23));const i=t.price_cents?Math.round(Number(t.price_cents)):undefined;const r=((i||99)*t.count/100).toFixed(2);const a=` Order: ${t.action.toUpperCase()} ${t.count}x ${t.ticker} ${t.side.toUpperCase()} @ ${i?i+"¢":"market"} (max $${r})`;process.stderr.write(a+"\n");if(!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});const l=await new Promise((e=>c.question(" Execute? (y/n) ",e)));c.close();if(!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}:{}});const 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);if(t.includes("403")){return{content:[{type:"text",text:"403 Forbidden — your Kalshi key lacks write permission. Get a read+write key at kalshi.com/account/api-keys"}],details:{}}}return{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:w.Object({order_id:w.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{const{cancelOrder:s}=await Promise.resolve().then(n.t.bind(n,96139,23));try{await s(t.order_id);return{content:[{type:"text",text:`Order ${t.order_id} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Cancel failed: ${e.message}`}],details:{}}}}})}E.push({name:"close_position",label:"Close Position",description:"Remove a position record from a thesis.",parameters:w.Object({thesisId:w.String({description:"Thesis ID"}),positionId:w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),dryRun:w.Optional(w.Boolean({description:"Preview without applying"}))}),execute:async(e,t)=>{const n=t.dryRun?"?dryRun=true":"";const o=await s.request("POST",`/api/thesis/${t.thesisId}/augment${n}`);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}});E.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:w.Object({focus:w.Optional(w.String({description:'Comma-separated topics (e.g. "energy,geopolitics")'}))}),execute:async(e,t)=>{const n=t.focus?`?focus=${encodeURIComponent(t.focus)}`:"";const s=process.env.SF_API_URL||"https://simplefunctions.dev";const o=await fetch(`${s}/api/agent/world${n}`);if(!o.ok)return{content:[{type:"text",text:`World API error: ${o.status}`}],details:{}};const i=await o.text();return{content:[{type:"text",text:i}],details:{}}}},{name:"get_world_delta",label:"World Delta",description:"Incremental world state update — only what changed. ~30-50 tokens.",parameters:w.Object({since:w.Optional(w.String({description:'"30m", "1h", "6h", "24h" or ISO timestamp (default "1h")'}))}),execute:async(e,t)=>{const n=t.since||"1h";const s=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:{}};const i=await o.text();return{content:[{type:"text",text:i}],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:w.Object({source:w.Object({action:w.String({description:"scrape, crawl, search, map, extract, batch_scrape"}),url:w.Optional(w.String({description:"Target URL"})),query:w.Optional(w.String({description:"Search query (for search action)"}))}),analysis:w.Optional(w.Object({model:w.Optional(w.String({description:"OpenRouter model"})),prompt:w.Optional(w.String({description:"Analysis prompt"}))})),enrich:w.Optional(w.Object({topics:w.Optional(w.Array(w.String())),includeIndex:w.Optional(w.Boolean())})),webhook:w.Optional(w.Object({url:w.String({description:"Webhook URL"}),format:w.Optional(w.String({description:"full, brief, or tweetable"}))}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:w.Object({content:w.String({description:"Text to cross-reference"}),topics:w.Optional(w.Array(w.String()))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:{}}}});E.push({name:"create_skill",label:"Create Skill",description:"Create a custom agent skill — a reusable prompt/workflow triggered via slash command.",parameters:w.Object({name:w.String(),trigger:w.String({description:"Slash command trigger, e.g. /my-skill"}),description:w.String(),prompt:w.String({description:"The instruction text the agent executes"}),category:w.Optional(w.String()),tags:w.Optional(w.String({description:"Comma-separated tags"})),toolsUsed:w.Optional(w.String({description:"Comma-separated tool names"}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const s={name:t.name,trigger:t.trigger,description:t.description,prompt:t.prompt};if(t.category)s.category=t.category;if(t.tags)s.tags=t.tags.split(",").map((e=>e.trim()));if(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 ${h}`},body:JSON.stringify(s)});const 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:w.Object({}),execute:async()=>{const e=process.env.SF_API_URL||"https://simplefunctions.dev";const t=await fetch(`${e}/api/skill`,{headers:{Authorization:`Bearer ${h}`}});const 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:w.Object({category:w.Optional(w.String()),q:w.Optional(w.String()),sort:w.Optional(w.String({description:"popular or new"}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const s=new URLSearchParams;if(t.category)s.set("category",t.category);if(t.q)s.set("q",t.q);if(t.sort)s.set("sort",t.sort);const o=await fetch(`${n}/api/public/skills?${s}`);const 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:w.Object({skillId:w.String(),slug:w.String({description:"URL-safe slug, e.g. my-precheck"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const s=await fetch(`${n}/api/skill/${t.skillId}/publish`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({slug:t.slug})});const 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:w.Object({skillId:w.String({description:"ID of the public skill to fork"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const s=await fetch(`${n}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${h}`}});const 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:w.Object({slug:w.String({description:"Public thesis slug, e.g. iran-war"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const s=await fetch(`${n}/api/thesis/${t.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${h}`}});const o=await s.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}});E.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime is running and show active intents.",parameters:w.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23));const r=o(i(),".sf","runtime.pid");let a=false;let c="";if(e(r)){c=t(r,"utf-8").trim();try{process.kill(parseInt(c),0);a=true}catch{a=false}}const l=await s.listIntents({active:true});return{content:[{type:"text",text:JSON.stringify({running:a,pid:a?c:null,...l},null,2)}],details:{}}}},{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon. Evaluates intent triggers and executes orders.",parameters:w.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:o}=await Promise.resolve().then(n.t.bind(n,70857,23));const{spawn:i}=await Promise.resolve().then(n.t.bind(n,35317,23));const r=s(o(),".sf","runtime.pid");if(e(r)){const e=t(r,"utf-8").trim();try{process.kill(parseInt(e),0);return{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{}}const a=i(process.execPath,[process.argv[1],"runtime","start"],{detached:true,stdio:["ignore","ignore","ignore"],env:{...process.env}});a.unref();await new Promise((e=>setTimeout(e,1e3)));if(e(r)){const e=t(r,"utf-8").trim();return{content:[{type:"text",text:`Runtime started (PID ${e}). Polling every 30s.`}],details:{}}}return{content:[{type:"text",text:"Runtime starting... check runtime_status in a moment."}],details:{}}}},{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:w.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:s}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23));const 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{process.kill(parseInt(a),"SIGTERM");s(r);return{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 removed)."}],details:{}}}}});const M=f;const R=M._explorerMode||o==="_explorer";let L;if(R){const e=(M.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)";L=`You are a prediction market research assistant in EXPLORER MODE — not bound to any thesis.\n\n## What you can do\n- get_world_state: real-time world model (~800 tokens), use ?focus= for deeper topic coverage\n- get_world_delta: incremental changes since last check (~30-50 tokens)\n- query: LLM-enhanced market search\n- scan_markets: search Kalshi + Polymarket\n- get_markets: traditional markets (SPY, VIX, gold, oil)\n- get_trade_ideas: S&T-style trade pitches with conviction + catalyst\n- explore_public: browse public theses\n- search_x, x_volume, x_news: X/Twitter signals\n- monitor_the_situation: scrape any URL, analyze, cross-reference with 9,706 markets\n- enrich_content: cross-reference text with prediction markets\n- get_positions: portfolio positions\n- create_intent / list_intents / cancel_intent: execution intents with triggers\n- runtime_start / runtime_stop / runtime_status: local execution daemon\n- create_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${A.tradingEnabled?"- Trading ENABLED.":"- Trading DISABLED."}\n\n## Market snapshot\nPublic edges:\n${e}`}else{const e=M.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)";const t=M.causalTree?.nodes?.filter((e=>e.depth===0)).map((e=>` ${e.id} ${(e.label||"").slice(0,40)} — ${Math.round(e.probability*100)}%`)).join("\n")||" (no causal tree)";const n=typeof M.confidence==="number"?Math.round(M.confidence*100):0;L=`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${A.tradingEnabled?"- Trading ENABLED. You have place_order and cancel_order tools.":"- Trading DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current State\nThesis: ${M.thesis||M.rawThesis||"N/A"}\nID: ${o} | Confidence: ${n}% | Status: ${M.status}\n\nCausal nodes:\n${t}\n\nTop edges:\n${e}\n\n${M.lastEvaluation?.summary?`Latest eval: ${M.lastEvaluation.summary.slice(0,300)}`:""}`}const N=new _({initialState:{systemPrompt:L,model:x,tools:E,thinkingLevel:"off"},streamFn:b,getApiKey:e=>e==="openrouter"?t:undefined});if(!i?.newSession){const e=loadSession(o);if(e?.messages?.length>0){try{N.replaceMessages(e.messages);N.setSystemPrompt(L)}catch{}}}let D="";N.subscribe((e=>{if(e.type==="message_update"){const t=e.assistantMessageEvent;if(t.type==="text_delta"){process.stdout.write(t.delta);D+=t.delta}}if(e.type==="message_end"){if(D){process.stdout.write("\n");D=""}}if(e.type==="tool_execution_start"){process.stderr.write(` ▸ ${e.toolName}...\n`)}if(e.type==="tool_execution_end"){const t=e.isError?"✗":"✓";process.stderr.write(` ${t} ${e.toolName}\n`)}}));if(R){console.log(`SF Agent — Explorer mode | ${v}`);console.log(`Public edges: ${(M.edges||[]).length}`);console.log("Ask anything about prediction markets. Type /help for commands, /exit to quit.\n")}else{const e=M.thesis||M.rawThesis||"N/A";const t=typeof M.confidence==="number"?Math.round(M.confidence*100):0;console.log(`SF Agent — ${o.slice(0,8)} | ${t}% | ${v}`);console.log(`Thesis: ${e.length>100?e.slice(0,100)+"...":e}`);console.log(`Edges: ${(M.edges||[]).length} | Status: ${M.status}`);console.log("Type /help for commands, /exit to quit.\n")}const F=g.createInterface({input:process.stdin,output:process.stdout,prompt:"> "});F.prompt();for await(const e of F){const t=e.trim();if(!t){F.prompt();continue}if(t==="/exit"||t==="/quit"){try{saveSession(o,v,N.state.messages)}catch{}F.close();return}if(t==="/help"){console.log("Commands: /help /exit /tree /edges /eval /model <name>");F.prompt();continue}if(t==="/tree"){f=await s.getContext(o);const e=f.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(t.probability*100)}%`)}F.prompt();continue}if(t==="/edges"){f=await s.getContext(o);const e=(f.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}`)}F.prompt();continue}if(t==="/eval"){console.log("Triggering evaluation...");const e=await s.evaluate(o);console.log(`Confidence: ${e.previousConfidence} → ${e.newConfidence}`);if(e.summary)console.log(e.summary);F.prompt();continue}if(t.startsWith("/model")){const e=t.slice(6).trim();if(!e){console.log(`Current: ${v}`);F.prompt();continue}v=e.replace(/^openrouter\//,"");x=resolveModel(v);N.setModel(x);console.log(`Model: ${v}`);F.prompt();continue}try{await N.prompt(t)}catch(e){console.error(`Error: ${e.message}`)}try{saveSession(o,v,N.state.messages)}catch{}F.prompt()}}},72768:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.announcementsCommand=announcementsCommand;const s=n(96139);const o=n(99236);async function announcementsCommand(e){const t=await(0,s.getExchangeAnnouncements)();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(`${o.c.dim}No announcements.${o.c.reset}`);return}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():"";const n=e.type?`[${e.type}]`:"";console.log(` ${o.c.dim}${t}${o.c.reset} ${n} ${e.title||e.message||""}`);if(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}`)}},71783:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.augmentCommand=augmentCommand;const s=n(19218);async function augmentCommand(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){console.log(JSON.stringify(o,null,2));return}console.log();if(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(e.estimatedProbability*100)}%, 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(e.probability*100)}%, imp: ${e.importance})[22m`)}console.log();if(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()}if(o.applied){console.log(` [32m✓ Applied to causal tree[39m`)}else if(t.dryRun){console.log(` [2mDry run — use without --dry-run to apply[22m`)}}else{console.log(" No nodes accepted.")}console.log()}},44040:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.balanceCommand=balanceCommand;const s=n(96139);const o=n(99236);async function balanceCommand(e){const t=await(0,s.getBalance)();if(!t)throw new Error("Kalshi not configured. Run: sf setup --kalshi");if(e.json){console.log(JSON.stringify(t,null,2));return}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)}`)}},69903:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.bookCommand=bookCommand;const s=n(19218);const o=n(96139);const i=n(34331);const r=n(99236);async function bookCommand(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 a=(0,i.parseOutcomePrices)(e.outcomePrices);const c={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:a[0]?(0,i.toCents)(a[0]):0,expiry:e.endDateIso||null,bidLevels:r.levels.bids.slice(0,5).map((e=>({price:Math.round(parseFloat(e.price)*100),size:Math.round(parseFloat(e.size))}))),askLevels:r.levels.asks.slice(0,5).map((e=>({price:Math.round(parseFloat(e.price)*100),size:Math.round(parseFloat(e.size))})))};if(t.history){try{const e=await(0,i.polymarketGetPriceHistory)({tokenId:o[0],interval:"1w",fidelity:360});if(e.length>0){c.sparkline=makeSparkline(e.map((e=>e.p*100)))}}catch{}}n.push(c)}}}for(const i of e){console.log(`${r.c.dim}Fetching ${i}...${r.c.reset}`);try{const e=await(0,s.kalshiFetchMarket)(i);const a=await(0,o.getPublicOrderbook)(i);const c=(a?.yes_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const l=(a?.no_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const d=c[0]?.price||0;const u=l.length>0?100-l[0].price:100;const p=u-d;const h=c.reduce(((e,t)=>e+t.size),0);const m=l.reduce(((e,t)=>e+t.size),0);const f=c.slice(0,3).reduce(((e,t)=>e+t.size),0)+l.slice(0,3).reduce(((e,t)=>e+t.size),0);const g=p<=2&&f>=500?"high":p<=5&&f>=100?"medium":"low";const y=parseFloat(e.last_price_dollars||"0")*100;const $={venue:"kalshi",ticker:e.ticker||i,title:e.title||e.subtitle||i,bestBid:d,bestAsk:u,spread:p,bidDepth:h,askDepth:m,liquidityScore:g,volume24h:parseFloat(e.volume_24h_fp||"0"),openInterest:parseFloat(e.open_interest_fp||"0"),lastPrice:Math.round(y),expiry:e.close_time||e.expiration_time||null,bidLevels:c.slice(0,5),askLevels:l.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);const t=e-7*86400;const n=await(0,o.getBatchCandlesticks)({tickers:[i],startTs:t,endTs:e,periodInterval:1440});const s=n.find((e=>e.market_ticker===i))||n[0];const 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;const n=typeof t==="string"?parseFloat(t)*100:typeof t==="number"?t:0;return Math.round(n)})).filter((e=>e>0));if(e.length>=2){$.sparkline=makeSparkline(e)}}}catch{}}if(!$.sparkline){const t=parseFloat(e.previous_price_dollars||"0")*100;if(t>0&&Math.abs(t-$.lastPrice)>0){const e=$.lastPrice-Math.round(t);const n=e>=0?r.c.green:r.c.red;const s=e>=0?`+${e}`:`${e}`;$.sparkline=`prev ${Math.round(t)}¢ → now ${$.lastPrice}¢ ${n}${s}${r.c.reset}`}}}n.push($)}catch(e){console.error(`${r.c.red}Failed to fetch ${i}: ${e.message}${r.c.reset}`)}}if(n.length===0){console.log(`\n ${r.c.dim}No markets found. Check the ticker and try again.${r.c.reset}\n`);return}if(t.json){console.log(JSON.stringify(n,null,2));return}for(const e of n){const t=e.venue==="polymarket"?`${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=e.liquidityScore==="high"?r.c.green:e.liquidityScore==="medium"?r.c.yellow:r.c.red;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)}`:""));if(e.sparkline){console.log(` 7d ${e.sparkline}`)}if(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];const s=e.askLevels[n];const 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);const 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()}}function makeSparkline(e){if(e.length<2)return"";const t=Math.min(...e);const n=Math.max(...e);const s=n-t||1;const o="▁▂▃▄▅▆▇█";const i=e.map((e=>{const n=Math.round((e-t)/s*7);return o[n]})).join("");const a=Math.round(e[0]);const c=Math.round(e[e.length-1]);const l=c-a;const d=l>=0?r.c.green:r.c.red;const u=l>=0?`+${l}`:`${l}`;return`${i} ${a}¢→${c}¢ ${d}${u}${r.c.reset}`}},80928:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.cancelCommand=cancelCommand;const s=n(96139);const o=n(11627);const i=n(99236);async function cancelCommand(e,t){(0,o.requireTrading)();if(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)))}if(n.length===0){console.log(`\n ${i.c.dim}No resting orders to cancel.${i.c.reset}\n`);return}console.log(`\n Cancelling ${n.length} order(s)...`);if(!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)}console.log(`\n ${i.c.green}✓${i.c.reset} Cancelled ${n.length} order(s).\n`);return}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`)}},97499:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.contextCommand=contextCommand;const s=n(19218);const o=n(96139);const i=n(99236);const r=n(35178);const a=process.env.SF_API_URL||"https://simplefunctions.dev";async function contextCommand(e,t){if(!e){const e=await fetch(`${t.apiUrl||a}/api/public/context`);if(!e.ok){console.error(` Error: ${e.status} ${await e.text()}`);return}const n=await e.json();if(t.share){await(0,r.shareOutput)("context","",n);return}if(t.json){console.log(JSON.stringify(n,null,2));return}const s=n.scannedAt?(0,i.shortDate)(n.scannedAt):"no scan yet";const 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 c=n.traditional||[];if(c.length>0){const e=c.map((e=>{const t=e.changePct||0;const n=t>0?i.c.green:t<0?i.c.red:i.c.dim;const 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 l=n.highlights||[];if(l.length>0){console.log(`${i.c.bold}${i.c.cyan}Highlights${i.c.reset}`);for(const e of l){console.log(` ${i.c.bold}${e.title}${i.c.reset}`);console.log(` ${i.c.dim}${e.detail}${i.c.reset}`);if(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 d=n.categories||[];if(d.length>0){console.log(`${i.c.bold}Categories${i.c.reset} ${i.c.dim}(${d.length} total)${i.c.reset}`);console.log(`${i.c.dim}${"─".repeat(70)}${i.c.reset}`);for(const e of d){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=e.venue==="kalshi"?`${i.c.cyan}K${i.c.reset}`:`${i.c.magenta}P${i.c.reset}`;const n=e.change24h||0;const s=n>0?i.c.green:n<0?i.c.red:i.c.dim;const o=n!==0?`${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}`);if(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=e.venue==="kalshi"?`${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 u=n.edges||[];if(u.length>0){console.log(`${i.c.bold}Thesis Edges${i.c.reset}`);for(const e of u.slice(0,6)){const t=e.venue==="kalshi"?`${i.c.cyan}K${i.c.reset}`:`${i.c.magenta}P${i.c.reset}`;const 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 p=n.signals||[];if(p.length>0){console.log(`${i.c.bold}Recent Evaluations${i.c.reset}`);for(const e of p.slice(0,5)){const t=e.confidenceDelta;const 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}`;const s=timeAgo(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()}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}`);console.log();return}const n=new s.SFClient(t.apiKey,t.apiUrl);const c=await n.getContext(e);if(t.json){console.log(JSON.stringify(c,null,2));return}console.log(`\n${i.c.bold}Thesis:${i.c.reset} ${c.thesis||c.rawThesis||"(unknown)"}`);const l=c.confidence!==null&&c.confidence!==undefined?(0,i.pct)(c.confidence):"-";const d=c.lastEvaluation?.confidenceDelta;const u=d?` (${(0,i.delta)(d)} since last eval)`:"";console.log(`${i.c.bold}Confidence:${i.c.reset} ${l}${u}`);console.log(`${i.c.bold}Status:${i.c.reset} ${c.status}`);console.log(`${i.c.bold}Last Updated:${i.c.reset} ${(0,i.shortDate)(c.updatedAt)}`);const p=c.causalTree?.nodes;if(p&&p.length>0){(0,i.header)("Causal Tree");for(const e of p){const t=" ".repeat((e.depth||0)+1);const n=e.probability!==undefined?(0,i.pct)(e.probability):"-";const 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 h=null;if((0,o.isKalshiConfigured)()){try{h=await(0,o.getPositions)()}catch{}}const m=new Map;if(h){for(const e of h)m.set(e.ticker,e)}const f=c.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;const n=e>10?i.c.green:e>0?i.c.yellow:i.c.red;const s=t.marketPrice??t.currentPrice??0;const o=t.market||t.marketTitle||t.marketId||"?";const r=t.orderbook;const a=r?` ${i.c.dim}spread ${r.spread}¢ ${r.liquidityScore}${i.c.reset}`:"";const c=m.get(t.marketId);let l="";if(c){const e=c.unrealized_pnl||0;const t=e>0?i.c.green:e<0?i.c.red:i.c.dim;const 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(c.lastEvaluation?.summary){(0,i.header)("Last Evaluation");console.log(` ${i.c.dim}${(0,i.shortDate)(c.lastEvaluation.evaluatedAt)} | model: ${c.lastEvaluation.model||""}${i.c.reset}`);console.log(` ${c.lastEvaluation.summary}`);if(c.lastEvaluation.positionRecommendations?.length>0){console.log(`\n ${i.c.bold}Position Recommendations:${i.c.reset}`);for(const e of c.lastEvaluation.positionRecommendations){const t=e.recommendation==="hold"?i.c.dim:e.recommendation==="close"?i.c.red:i.c.yellow;console.log(` [${(e.positionId||"").slice(0,8)}] ${t}${e.recommendation}${i.c.reset} — ${e.reason}`)}}}if(c.edgeMeta?.lastRescanAt){console.log(`\n${i.c.dim}Last rescan: ${(0,i.shortDate)(c.edgeMeta.lastRescanAt)}${i.c.reset}`)}console.log("")}function timeAgo(e){const t=Date.now()-new Date(e).getTime();const n=Math.round(t/6e4);if(n<60)return`${n}m`;const s=Math.round(n/60);if(s<24)return`${s}h`;return`${Math.round(s/24)}d`}},46222:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.createCommand=createCommand;const s=n(19218);const o=n(99236);async function createCommand(e,t){const n=new s.SFClient(t.apiKey,t.apiUrl);const i=!t.async;if(!t.json){if(i){console.log(`${o.c.dim}Creating thesis (sync mode — waiting for formation)...${o.c.reset}`)}else{console.log(`${o.c.dim}Creating thesis (async mode)...${o.c.reset}`)}}const r=await n.createThesis(e,i);const a=r.thesis?.id||r.thesisId||r.id||null;if(t.json){console.log(JSON.stringify({id:a,status:r.thesis?.status||r.status||"forming",result:r},null,2));return}if(!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}`);if(r.thesis?.confidence){console.log(` ${o.c.bold}Confidence:${o.c.reset} ${Math.round(parseFloat(r.thesis.confidence)*100)}%`)}if(r.thesis?.causalTree?.nodes){console.log(` ${o.c.bold}Nodes:${o.c.reset} ${r.thesis.causalTree.nodes.length}`)}if(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}`)}},60952:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.dashboardCommand=dashboardCommand;const s=n(19218);const o=n(96139);const i=n(34331);const r=n(11627);const a=n(97325);const c=n(99844);function categorize(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 timeAgo(e){const t=Date.now()-new Date(e).getTime();const 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`;const o=Math.floor(s/24);return`${o}d ago`}async function dashboardCommand(e){if(!e?.json&&!e?.once){await(0,c.startDashboard)();return}const t=new s.SFClient(e?.apiKey,e?.apiUrl);const[n,a]=await Promise.all([t.listTheses(),(0,o.getPositions)().catch((()=>null))]);const l=n.theses||n;const d=[];for(const e of l){try{const n=await t.getContext(e.id);d.push(n)}catch{d.push(null)}}if(a){for(const e of a){const t=await(0,o.getMarketPrice)(e.ticker);if(t!==null){e.current_value=t;e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity)}}}const u=[];for(const e of d){if(!e?.edges)continue;for(const t of e.edges){u.push(t)}}const p=new Map;for(const e of u){const t=p.get(e.marketId);if(!t||Math.abs(e.edge)>Math.abs(t.edge)){p.set(e.marketId,e)}}const h=new Set(a?.map((e=>e.ticker))||[]);const m=[...p.values()].filter((e=>!h.has(e.marketId))).sort(((e,t)=>Math.abs(t.edge)-Math.abs(e.edge))).slice(0,10);const[f,g,y]=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 $=[];if(e?.json){try{$=(await t.getFeed(24,20)).evaluations||[]}catch{}}if(e?.json){console.log(JSON.stringify({theses:l,positions:a||[],polymarketPositions:y,orders:f,balance:g,unpositionedEdges:m,feed:$,kalshiConfigured:(0,o.isKalshiConfigured)(),polymarketConfigured:!!(0,r.loadConfig)().polymarketWalletAddress,timestamp:(new Date).toISOString()},null,2));return}console.log();console.log(" SimpleFunctions Dashboard");console.log(" "+"─".repeat(50));console.log();console.log(" Theses");if(l.length===0){console.log(" (none)")}else{for(let e=0;e<l.length;e++){const t=l[e];const n=d[e];const s=t.id.slice(0,8);const o=(t.title||"").slice(0,35).padEnd(35);const i=t.confidence!=null?`${Math.round(t.confidence*100)}%`:"?%";const r=n?.edges?.length||0;const a=t.updatedAt?timeAgo(t.updatedAt):"?";console.log(` ${s} ${o} ${i.padStart(4)} ${String(r).padStart(2)} edges updated ${a}`)}}console.log();console.log(" Positions");if(!a||a.length===0){console.log(" (no Kalshi positions or Kalshi not configured)")}else{let e=0;let t=0;for(const n of a){const s=(n.ticker||"").padEnd(22);const o=String(n.quantity||0).padStart(5);const i=`${n.average_price_paid||0}¢`;const r=typeof n.current_value==="number"?`${n.current_value}¢`:"?¢";const a=n.unrealized_pnl||0;const c=(a/100).toFixed(2);const l=a>=0?`+$${c}`:`-$${Math.abs(parseFloat(c)).toFixed(2)}`;const d=(n.average_price_paid||0)*(n.quantity||0);e+=d;t+=a;console.log(` ${s} ${o} @ ${i.padEnd(5)} now ${r.padEnd(5)} ${l}`)}console.log(" "+"─".repeat(45));const n=(e/100).toFixed(0);const s=(t/100).toFixed(2);const o=t>=0?`+$${s}`:`-$${Math.abs(parseFloat(s)).toFixed(2)}`;console.log(` Total cost: $${n} | P&L: ${o}`)}console.log();if(a&&a.length>0){console.log(" Risk Exposure");const e=new Map;for(const t of a){const n=categorize(t.ticker||"");const s=e.get(n)||{cost:0,contracts:0,tickers:[]};const o=(t.average_price_paid||0)*(t.quantity||0);s.cost+=o;s.contracts+=t.quantity||0;if(!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)}`;const 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(m.length>0){console.log(" Top Unpositioned Edges");for(const e of m){const t=(e.market||e.marketId||"").slice(0,25).padEnd(25);const n=`${e.marketPrice}¢`;const s=`${e.thesisPrice}¢`;const o=e.edge>0?`+${e.edge}`:`${e.edge}`;const i=e.orderbook?.liquidityScore||"?";console.log(` ${t} ${n.padStart(5)} → ${s.padStart(5)} edge ${o.padStart(4)} ${i}`)}console.log()}}},81466:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.deltaCommand=deltaCommand;const s=n(19218);const o=n(99236);async function deltaCommand(e,t){const n=new s.SFClient(t.apiKey,t.apiUrl);const i=t.since?new Date(t.since):new Date(Date.now()-parseInt(t.hours||"6")*36e5);if(isNaN(i.getTime())){throw new Error(`Invalid timestamp: "${t.since}". Use ISO 8601 format (e.g., 2026-03-28T14:00:00Z)`)}const run=async()=>{const s=i.toISOString();const r=await n.getChanges(e,s);if(t.json){console.log(JSON.stringify(r,null,2));return}if(!r.changed){console.log(`${o.c.dim}No changes since ${i.toLocaleString()}.${o.c.reset}`);return}const a=(0,o.shortId)(e);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}`);if(r.confidence!==undefined){const e=Math.round(r.confidence*100);const t=r.previousConfidence!==undefined?Math.round(r.previousConfidence*100):null;const n=t!==null?e-t:null;let s="";if(n!==null){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}`)}if(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((e.newProbability??e.newProb??0)*100);const n=e.previousProbability??e.prevProb;let s="";if(n!==undefined&&n!==null){const e=Math.round(n*100);const i=t-e;s=i>0?` ${o.c.green}+${i}%${o.c.reset}`:i<0?` ${o.c.red}${i}%${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";const 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);const n=e.edge??0;const s=e.previousEdge??null;const i=n>0?`+${n}`:`${n}`;let r="";if(s!==null){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){console.log(`${o.c.dim}Watching for changes every 60s... (Ctrl+C to stop)${o.c.reset}`);while(true){await run();await new Promise((e=>setTimeout(e,6e4)));console.clear()}}else{await run()}}},91262:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.edgesCommand=edgesCommand;const s=n(19218);const o=n(96139);const i=n(99236);const r=n(35178);async function edgesCommand(e){const t=new s.SFClient(e.apiKey,e.apiUrl);const n=parseInt(e.limit||"20");const a=e.minEdge?parseInt(e.minEdge):0;const c=e.minLiquidity?.toLowerCase()||"";const l=e.sort||"edge";const 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();const n=e.theses||e;u=(Array.isArray(n)?n:[]).filter((e=>e.status==="active"))}if(u.length===0){if(e.json){console.log(JSON.stringify({edges:[],totalEdges:0}));return}(0,i.emptyState)("active theses",'Create one: sf create "your market thesis"');return}p(`${i.c.dim}Fetching edges from ${u.length} ${u.length===1?"thesis":"theses"}...${i.c.reset}`);const h=[];const 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:[]}}}));const f=await Promise.all(m);for(const{thesisId:e,edges:t}of f){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:typeof n.marketPrice==="number"?n.marketPrice:0,thesisPrice:typeof n.thesisPrice==="number"?n.thesisPrice:0,edge:typeof n.edge==="number"?n.edge:0,executableEdge:typeof n.executableEdge==="number"?n.executableEdge:null,spread:n.orderbook?.spread??null,liquidityScore:n.orderbook?.liquidityScore??null,thesisId:e,position:null})}}if(h.length===0){if(e.json){console.log(JSON.stringify({edges:[],totalEdges:0,thesesScanned:u.length}));return}(0,i.emptyState)("edges",`Scanned ${u.length} theses. Edges appear when thesis price diverges from market price.`);return}const g=new Map;for(const e of h){const t=e.marketId;if(!t)continue;const n=g.get(t);if(!n||Math.abs(e.edge)>Math.abs(n.edge)){g.set(t,e)}}let y=Array.from(g.values());if(a>0){y=y.filter((e=>Math.abs(e.edge)>=a))}if(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)();if($){for(const e of $){const t=await(0,o.getMarketPrice)(e.ticker);if(t!==null){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)));if(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)}}}}}if(l==="spread"){y.sort(((e,t)=>(e.spread??999)-(t.spread??999)))}else{y.sort(((e,t)=>{const n=e.executableEdge!==null?e.executableEdge:e.edge;const s=t.executableEdge!==null?t.executableEdge:t.edge;return Math.abs(s)-Math.abs(n)}))}const k=y.slice(0,n);const b={totalEdges:y.length,displayed:k.length,thesesScanned:u.length,edges:k};if(e.share){await(0,r.shareOutput)("edges","",b);return}if(e.json){console.log(JSON.stringify(b,null,2));return}console.log();(0,i.header)(`Top Edges Across ${u.length} Theses`);console.log();const w=[(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}${w}${i.c.reset}`);(0,i.hr)(100);for(const e of k){const t=(0,i.trunc)(e.market,31);const n=`${e.marketPrice}¢`;const s=`${e.thesisPrice}¢`;const o=e.edge>0?`+${e.edge}`:`${e.edge}`;const r=e.executableEdge!==null?e.executableEdge>0?`+${e.executableEdge}`:`${e.executableEdge}`:"—";const a=e.spread!==null?`${e.spread}¢`:"—";const c=e.liquidityScore||"—";const l=(0,i.shortId)(e.thesisId);const d=e.edge>0?i.c.green:e.edge<0?i.c.red:i.c.dim;const u=e.executableEdge!==null?e.executableEdge>0?i.c.green:i.c.red:i.c.dim;const p=c==="high"?i.c.green:c==="medium"?i.c.yellow:i.c.dim;let h=`${i.c.dim}—${i.c.reset}`;if(e.position){const t=e.position;const 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 _=k.filter((e=>e.position));if(_.length>0){let e=0;let t=0;for(const n of _){e+=n.position.totalCost;t+=n.position.pnl}const n=`$${(e/100).toFixed(0)}`;const s=t>=0?i.c.green:i.c.red;const o=t>=0?"+":"-";const r=`${s}${o}$${(Math.abs(t)/100).toFixed(0)}${i.c.reset}`;console.log(`${i.c.bold}Total positioned:${i.c.reset} ${n} cost | P&L: ${r}`)}const S=k.filter((e=>!e.position&&e.edge>0));if(S.length>0){const e=S[0];const t=e.executableEdge!==null?`exec +${e.executableEdge}`:`edge +${e.edge}`;const 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()}},67509:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.evaluateCommand=evaluateCommand;const s=n(19218);const o=n(99236);async function evaluateCommand(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);console.log(`\n${o.c.green}✓${o.c.reset} Evaluation complete`);if(i.evaluation){const e=i.evaluation;if(e.confidenceDelta!==undefined){const t=e.confidenceDelta;const 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}`)}if(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=t.recommendation==="hold"?o.c.dim:t.recommendation==="close"?o.c.red:o.c.yellow;console.log(` [${t.positionId.slice(0,8)}] ${e}${t.recommendation}${o.c.reset} — ${t.reason}`)}}}console.log("")}},22835:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.exploreCommand=exploreCommand;const s=n(35178);const o=n(99236);const i="https://simplefunctions.dev";async function exploreCommand(e,t){if(!e){const e=await fetch(`${i}/api/public/theses`);if(!e.ok){console.error(` Error: ${e.status} ${await e.text()}`);return}const{theses:n}=await e.json();if(t?.share){await(0,s.shareOutput)("explore","",{theses:n});return}if(t?.json){console.log(JSON.stringify(n,null,2));return}console.log("\n Public Theses\n");if(n.length===0){console.log(` ${o.c.dim}No public theses yet. Publish yours: sf publish <id>${o.c.reset}\n`);return}for(const e of n){const t=e.confidence!=null?Math.round(e.confidence*100):"?";const n=e.impliedReturn!=null?`${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)}`)}console.log(`\n ${n.length} public theses. Use: sf explore <slug>\n`);return}const n=await fetch(`${i}/api/public/thesis/${e}`);if(!n.ok){if(n.status===404){console.error(` Not found: ${e}`)}else{console.error(` Error: ${n.status} ${await n.text()}`)}return}const r=await n.json();if(t?.json){console.log(JSON.stringify(r,null,2));return}const a=r.thesis;const c=r.impliedReturns;console.log(`\n ${a.title}`);console.log(` ${a.slug} | ${a.confidence!=null?Math.round(a.confidence*100):"?"}% | ${a.status} | published ${a.publishedAt?.slice(0,10)||"?"}`);if(a.description)console.log(` ${a.description}`);console.log("");if(r.causalTree?.nodes?.length){console.log(" Causal Tree");for(const e of r.causalTree.nodes){const t="█".repeat(Math.round((e.probability||0)*10))+"░".repeat(10-Math.round((e.probability||0)*10));console.log(` ${e.id} ${(e.label||"").slice(0,35).padEnd(35)} ${Math.round((e.probability||0)*100)}% ${t}`);if(e.children){for(const t of e.children){const e="█".repeat(Math.round((t.probability||0)*10))+"░".repeat(10-Math.round((t.probability||0)*10));console.log(` ${t.id} ${(t.label||"").slice(0,33).padEnd(33)} ${Math.round((t.probability||0)*100)}% ${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(e.delta*100)}`:`${Math.round(e.delta*100)}`;console.log(` ${(e.evaluatedAt||"").slice(0,16)} ${Math.round(e.confidence*100)}% (${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("")}}},44478:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.feedCommand=feedCommand;const s=n(19218);const o=n(99236);async function feedCommand(e){const t=new s.SFClient(e.apiKey,e.apiUrl);const n=parseInt(e.hours||"24");const i=await t.getFeed(n,200);let r=i.feed||[];if(r.length===0){console.log(`${o.c.dim}No evaluations in the last ${n} hours.${o.c.reset}`);return}if(e.thesis){r=r.filter((t=>t.thesisId.startsWith(e.thesis)||t.thesisShortId===e.thesis));if(r.length===0){console.log(`${o.c.dim}No evaluations for ${e.thesis} in the last ${n} hours.${o.c.reset}`);return}}if(e.json){console.log(JSON.stringify(r,null,2));return}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);const n=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});const s=Math.round(e.confidence*100);const i=Math.round(e.delta*100);let r;if(i>0){r=`${o.c.green}+${i}%${o.c.reset}`}else if(i<0){r=`${o.c.red}${i}%${o.c.reset}`}else{r=`${o.c.dim}0%${o.c.reset}`}const a=e.thesisShortId||e.thesisId?.slice(0,8)||"?";const c=(e.summary||"No summary").replace(/\n/g," ").slice(0,80);const l=e.updatedNodes||[];const d=l.length>0?l.slice(0,3).map((e=>`${e.nodeId}→${Math.round((e.newProb||0)*100)}%`)).join(", "):"";console.log(`${o.c.dim}[${n}]${o.c.reset} `+`${o.c.cyan}${a}${o.c.reset} `+`${s}% (${r}) `+`${o.c.dim}${c}${o.c.reset}`);if(d){console.log(`${" ".repeat(9)} ${o.c.dim}nodes: ${d}${o.c.reset}`)}}console.log(`${o.c.dim}${"─".repeat(75)}${o.c.reset}`);console.log()}},63746:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.fillsCommand=fillsCommand;const s=n(96139);const o=n(99236);async function fillsCommand(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){console.log(JSON.stringify(t.fills,null,2));return}if(t.fills.length===0){console.log(`${o.c.dim}No fills.${o.c.reset}`);return}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?`${parseFloat(e.yes_price_dollars)*100}¢`:`${e.yes_price||"?"}¢`;const n=e.side==="yes"?`${o.c.green}YES${o.c.reset}`:`${o.c.red}NO${o.c.reset}`;const s=e.action||"buy";const i=e.count_fp||e.count||"?";const 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}`)}},28423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.forecastCommand=forecastCommand;const s=n(96139);const o=n(99236);const i="https://api.elections.kalshi.com/trade-api/v2";async function forecastCommand(e,t){const n=parseInt(t.days||"7");const 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();const 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);const u=d-n*86400;const p=await(0,s.getForecastHistory)({seriesTicker:c,eventTicker:e,percentiles:[5e3,7500,9e3],startTs:u,endTs:d,periodInterval:1440});if(!p||p.length===0){console.log(`${o.c.dim}No forecast data for ${e}${o.c.reset}`);return}if(t.json){console.log(JSON.stringify(p,null,2));return}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(e.end_period_ts*1e3).toISOString().slice(0,10);const n=e.percentile_points||[];const s=n.find((e=>e.percentile===5e3))?.formatted_forecast||"-";const o=n.find((e=>e.percentile===7500))?.formatted_forecast||"-";const i=n.find((e=>e.percentile===9e3))?.formatted_forecast||"-";console.log(` ${t.padEnd(14)} ${s.padEnd(12)} ${o.padEnd(12)} ${i}`)}}},5596:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.getCommand=getCommand;const s=n(19218);const o=n(99236);async function getCommand(e,t){const n=new s.SFClient(t.apiKey,t.apiUrl);const i=await n.getThesis(e);if(t.json){console.log(JSON.stringify(i,null,2));return}const r=i;const a=i.positions||[];(0,o.header)(`Thesis: ${(r.id||e).slice(0,8)}`);(0,o.hr)();console.log(`${o.c.bold}Status:${o.c.reset} ${r.status||"-"}`);const c=r.confidence?(0,o.pct)(parseFloat(r.confidence)):"-";console.log(`${o.c.bold}Confidence:${o.c.reset} ${c}`);const l=r.createdAt instanceof Date?r.createdAt.toISOString():r.createdAt;const d=r.updatedAt instanceof Date?r.updatedAt.toISOString():r.updatedAt;console.log(`${o.c.bold}Created:${o.c.reset} ${(0,o.shortDate)(l)}`);console.log(`${o.c.bold}Updated:${o.c.reset} ${(0,o.shortDate)(d)}`);if(r.title){console.log(`${o.c.bold}Title:${o.c.reset} ${r.title}`)}console.log(`${o.c.bold}Thesis:${o.c.reset} ${r.rawThesis||"-"}`);if(r.webhookUrl){console.log(`${o.c.bold}Webhook:${o.c.reset} ${r.webhookUrl}`)}const u=r.causalTree;if(u&&u.nodes){(0,o.header)("Causal Tree");printNodes(u.nodes,0)}const p=r.edgeAnalysis;if(p&&p.edges){(0,o.header)("Edge Analysis");console.log(`${o.c.dim}Analyzed: ${(0,o.shortDate)(p.analyzedAt)}${o.c.reset}`);if(p.lastRescanAt){console.log(`${o.c.dim}Last rescan: ${(0,o.shortDate)(p.lastRescanAt)}${o.c.reset}`)}for(const e of p.edges){const t=e.edgeSize??0;const 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(a.length>0){(0,o.header)("Positions");for(const e of a){if(!e)continue;const t=e.status==="open"?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 h=r.lastEvaluation;if(h){(0,o.header)("Last Evaluation");const e=h.evaluatedAt instanceof Date?h.evaluatedAt.toISOString():h.evaluatedAt;console.log(`${o.c.dim}${(0,o.shortDate)(e)} | model: ${h.model||"-"}${o.c.reset}`);if(h.confidenceDelta!==undefined){const e=h.confidenceDelta;const t=e>0?o.c.green:e<0?o.c.red:o.c.dim;console.log(`Confidence: ${(0,o.pct)(h.previousConfidence)} → ${(0,o.pct)(h.newConfidence)} ${t}(${(0,o.delta)(e)})${o.c.reset}`)}if(h.summary){console.log(`\n${h.summary}`)}}console.log("")}function printNodes(e,t){for(const n of e){if(!n)continue;const e=" ".repeat(t+1);const s=n.probability!==undefined?(0,o.pct)(n.probability):"-";const i=n.importance!==undefined?` imp:${n.importance}`:"";console.log(`${e}${o.c.cyan}${n.id}${o.c.reset} ${n.label} ${o.c.dim}(${s}${i})${o.c.reset}`);if(n.children&&n.children.length>0){printNodes(n.children,t+1)}}}},87604:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.heartbeatCommand=heartbeatCommand;const s=n(99236);async function heartbeatCommand(e,t,n){const o=n.newsInterval||n.xInterval||n.model||n.budget!==undefined||n.pause||n.resume;if(o){const o={};if(n.newsInterval)o.newsIntervalMin=parseInt(n.newsInterval,10);if(n.xInterval)o.xIntervalMin=parseInt(n.xInterval,10);if(n.model)o.evalModelTier=n.model;if(n.budget!==undefined)o.monthlyBudgetUsd=parseFloat(n.budget);if(n.pause)o.paused=true;if(n.resume)o.paused=false;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){console.error(` ${s.c.red}✗ ${e.message}${s.c.reset}`);return}}try{const n=await e.getHeartbeatConfig(t);const o=n.config;const 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}`;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}`);if(i.budgetRemaining!==null){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}`)}}},9708:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.historyCommand=historyCommand;const s=n(96139);const o=n(99236);async function historyCommand(e,t){const n=await(0,s.getHistoricalMarket)(e);if(!n){console.log(`${o.c.dim}No historical data for ${e}${o.c.reset}`);return}if(t.json){console.log(JSON.stringify(n,null,2));return}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||"-"}`);if(n.last_price_dollars){console.log(` Last Price: ${Math.round(parseFloat(n.last_price_dollars)*100)}¢`)}if(n.settlement_value!==undefined){console.log(` Settlement: ${n.settlement_value}`)}if(n.volume){console.log(` Volume: ${n.volume}`)}if(n.open_interest){console.log(` Open Int: ${n.open_interest}`)}if(n.expiration_time){console.log(` Expired: ${n.expiration_time}`)}console.log()}},30896:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.ideasCommand=ideasCommand;const s=n(99236);async function ideasCommand(e){const t=process.env.SF_API_URL||"https://simplefunctions.dev";const n=new URLSearchParams;if(e.category)n.set("category",e.category);if(e.fresh)n.set("freshness",e.fresh);const o=await fetch(`${t}/api/public/ideas?${n.toString()}`);if(!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){console.log(JSON.stringify(i,null,2));return}const r=i.ideas||i;if(!Array.isArray(r)||r.length===0){console.log(`\n ${s.c.dim}No trade ideas available.${s.c.reset}\n`);return}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=e.direction==="long"?s.c.green+"▲ LONG"+s.c.reset:s.c.red+"▼ SHORT"+s.c.reset;const n="●".repeat(Math.min(e.conviction||3,5));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||""}`);if(e.catalyst)console.log(` ${s.c.dim}Catalyst: ${e.catalyst}${s.c.reset}`);if(e.risk)console.log(` ${s.c.dim}Risk: ${e.risk}${s.c.reset}`);if(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()}}},15472:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.registerIntents=registerIntents;const s=n(19218);const o=n(99236);const i={pending:"[33m",armed:"[36m",triggered:"[35m",executing:"[34m",filled:"[32m",partial:"[33m",expired:"[90m",cancelled:"[90m",rejected:"[31m"};function formatIntent(e){const t=i[e.status]||"";const n=[];const s=e.action.toUpperCase();const r=e.direction.toUpperCase();const a=e.maxPrice?` @ ≤${e.maxPrice}c`:" @ market";const c=e.venue==="kalshi"?"K":"P";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}`);if(e.triggerType!=="immediate"){const t=describeTrigger(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);const d=l.toLocaleDateString("en-US",{month:"short",day:"numeric"});n.push(` ${o.c.dim}expires ${d} · source: ${e.source}${e.rationale?` · "${e.rationale.slice(0,60)}"`:""}${o.c.reset}`);return n.join("\n")}function describeTrigger(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}}function parseTrigger(e){if(e==="immediate")return{type:"immediate"};const[t,n]=e.split(":");if(t==="below"&&n)return{type:"price_below",price:parseInt(n)};if(t==="above"&&n)return{type:"price_above",price:parseInt(n)};throw new Error(`Unknown trigger: "${e}". Use: immediate, below:<cents>, above:<cents>`)}function registerIntents(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;const n=e.all?{}:{active:!e.status,status:e.status};const{intents:i}=await t.listIntents(n);if(e.json){console.log(JSON.stringify(i,null,2));return}if(!i||i.length===0){(0,o.emptyState)("intents","Create one: sf intent buy TICKER QTY --price CENTS");return}console.log(`\n ${o.c.bold}INTENTS${o.c.reset} (${i.length})\n`);for(const e of i){console.log(formatIntent(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 createIntentCommand("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 createIntentCommand("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;const{intent:i}=await n.getIntentDetail(e);if(t.json){console.log(JSON.stringify(i,null,2));return}console.log(`\n ${o.c.bold}Intent ${i.id.slice(0,8)}${o.c.reset}\n`);console.log(formatIntent(i));console.log();if(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:false});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);const 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)}}))}async function createIntentCommand(e,t,n,i){try{const r=new s.SFClient;const a=parseInt(n);if(isNaN(a)||a<1){throw new Error("Quantity must be a positive integer")}const c=parseTrigger(i.trigger||"immediate");const l=i.price?parseInt(i.price):undefined;if(l!==undefined&&(l<1||l>99)){throw new Error("Price must be 1-99 cents")}const d={"1h":60*60*1e3,"6h":6*60*60*1e3,"1d":24*60*60*1e3,"3d":3*24*60*60*1e3,"1w":7*24*60*60*1e3};const u=d[i.expire]||d["1d"];const 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"};const h=await r.createIntent(p);if(i.json){console.log(JSON.stringify(h,null,2));return}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"}`);if(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:true});t.liquidityCommand=liquidityCommand;const s=n(19218);const o=n(96139);const i=n(34331);const r=n(97325);const a=n(99236);function classifyHorizon(e){const t=Date.now();const n=new Date(e).getTime();const s=(n-t)/(1e3*60*60*24);if(s<7)return"weekly";if(s<=35)return"monthly";return"long-term"}function horizonLabel(e){switch(e){case"weekly":return"weekly (<7d)";case"monthly":return"monthly (7-35d)";case"long-term":return"long-term (>35d)"}}function calcSlippage100(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;let 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"∞";const i=o/t;return(i*100).toFixed(1)+"¢"}async function batchProcess(e,t,n,s){const o=[];for(let i=0;i<e.length;i+=n){const r=e.slice(i,i+n);const a=await Promise.allSettled(r.map(t));for(const e of a){o.push(e.status==="fulfilled"?e.value:null)}if(i+n<e.length){await new Promise((e=>setTimeout(e,s)))}}return o}async function liquidityCommand(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}`)}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}`);console.log();return}const n=e.topic?t.filter((t=>t.toLowerCase()===e.topic.toLowerCase())):t;if(e.topic&&n.length===0){const n=t.join(", ");console.error(`Unknown topic: ${e.topic}. Valid topics: ${n}`);process.exit(1)}let c=new Set;if((0,o.isKalshiConfigured)()){try{const e=await(0,o.getPositions)();if(e){c=new Set(e.map((e=>e.ticker)))}}catch{}}const l={};for(const e of n){const t=r.TOPIC_SERIES[e];const n=[];for(const e of t){try{const t=await(0,s.kalshiFetchMarketsBySeries)(e);n.push(...t)}catch{}}if(n.length>0){l[e]=n}}const d=e.venue!=="kalshi";if(d){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||[]){if(!t.active||t.closed||!t.enableOrderBook)continue;if(!l[e])l[e]=[];l[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 u=e.horizon;const p=[];for(const[e,t]of Object.entries(l)){for(const n of t){const t=n.close_time||n.expiration_time||"";if(!t)continue;const s=classifyHorizon(t);if(u&&s!==u)continue;p.push({ticker:n.ticker,closeTime:t,topic:e,horizon:s,venue:n.venue||"kalshi",question:n.question,clobTokenIds:n.clobTokenIds})}}if(p.length===0){console.log("No markets found matching filters.");return}const h=p.filter((e=>e.venue==="kalshi"));const m=p.filter((e=>e.venue==="polymarket"));const f=await batchProcess(h,(async e=>{const t=await(0,o.getPublicOrderbook)(e.ticker);return{info:e,ob:t}}),5,100);const g=await batchProcess(m,(async e=>{if(!e.clobTokenIds)return{info:e,depth:null};const t=(0,i.parseClobTokenIds)(e.clobTokenIds);if(!t)return{info:e,depth:null};const n=await(0,i.polymarketGetOrderbookWithDepth)(t[0]);return{info:e,depth:n}}),5,100);const y=[];for(const t of f){if(!t||!t.ob)continue;const{info:n,ob:s}=t;const o=s.yes_dollars.map((([e,t])=>({price:Math.round(parseFloat(e)*100),qty:parseFloat(t)}))).filter((e=>e.price>0));const i=s.no_dollars.map((([e,t])=>({price:Math.round(parseFloat(e)*100),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;const a=i.length>0?100-i[0].price:100;const l=a-r;const d=o.reduce(((e,t)=>e+t.qty),0);const u=i.reduce(((e,t)=>e+t.qty),0);const p=calcSlippage100(s.no_dollars,100);if(e.minDepth&&d+u<e.minDepth)continue;y.push({ticker:n.ticker,shortTicker:n.ticker,topic:n.topic.toUpperCase(),horizon:n.horizon,closeTime:n.closeTime,bestBid:r,bestAsk:a,spread:l,bidDepth:d,askDepth:u,slippage100:p,held:c.has(n.ticker),venue:"kalshi"})}for(const t of g){if(!t||!t.depth)continue;const{info:n,depth:s}=t;if(e.minDepth&&s.bidDepthTop3+s.askDepthTop3<e.minDepth)continue;y.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:false,venue:"polymarket"})}if(e.json){console.log(JSON.stringify(y,null,2));return}const $=(new Date).toISOString().slice(0,10);console.log();console.log(`${a.c.bold}Liquidity Scanner${a.c.reset} ${a.c.dim}(${$} UTC)${a.c.reset}`);console.log(a.c.dim+"─".repeat(68)+a.c.reset);const k={};for(const e of y){const t=e.topic||"OTHER";if(!k[t])k[t]={};if(!k[t][e.horizon])k[t][e.horizon]=[];k[t][e.horizon].push(e)}let b=0;let w=0;let _=0;const S=["weekly","monthly","long-term"];for(const[e,t]of Object.entries(k)){for(const n of S){const s=t[n];if(!s||s.length===0)continue;const o=s.filter((e=>e.venue==="kalshi"));if(o.length>1){const e=findCommonPrefix(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)=>{if(e.venue!==t.venue)return e.venue==="kalshi"?-1:1;return e.venue==="kalshi"?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}— ${horizonLabel(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){b++;if(e.held)_++;const t=e.spread>5;if(t)w++;let n;if(e.spread<=2){n=`${a.c.green}${e.spread}¢${a.c.reset}`}else if(e.spread<=5){n=`${a.c.yellow}${e.spread}¢${a.c.reset}`}else{n=`${a.c.red}${e.spread}¢${a.c.reset}`}const s=t?" ⚠️":"";const o=e.held?` ${a.c.magenta}← held${a.c.reset}`:"";const i=(0,a.rpad)(`${e.spread}¢`,6);const 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}`;const c=e.venue==="polymarket"?`${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: ${b} markets | ${w} thin (spread>5¢) | ${_} held${a.c.reset}`);console.log()}function findCommonPrefix(e){if(e.length===0)return"";if(e.length===1)return"";let t=e[0];for(let n=1;n<e.length;n++){while(!e[n].startsWith(t)){t=t.slice(0,-1);if(t.length===0)return""}}return t}},38706:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.listCommand=listCommand;const s=n(19218);const o=n(99236);async function listCommand(e){const t=new s.SFClient(e.apiKey,e.apiUrl);const{theses:n}=await t.listTheses();if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){(0,o.emptyState)("theses",'Create one: sf create "your market thesis"');return}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=e.status==="active"?o.c.green:e.status==="forming"?o.c.yellow:o.c.dim;const 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}`)}},50869:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.loginCommand=loginCommand;const s=n(76982);const o=n(11627);const i=n(99236);const r=process.env.SF_API_URL||"https://simplefunctions.dev";async function loginCommand(e){const t=e.apiUrl||(0,o.loadConfig)().apiUrl||r;const a=(0,o.loadFileConfig)();if(a.apiKey&&!e.force){console.log(`\n ${i.c.dim}Already logged in (${a.apiKey.slice(0,12)}...).${i.c.reset}`);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`);return}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((()=>({})));console.error(` ${i.c.red}Failed to create session: ${t.error||e.status}${i.c.reset}`);return}}catch(e){console.error(` ${i.c.red}Could not reach ${t}${i.c.reset}`);return}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));const t=process.platform;const s=t==="darwin"?"open":t==="win32"?"start":"xdg-open";e(`${s} "${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=5*60*1e3;const u=2e3;const p=Date.now();while(Date.now()-p<d){await new Promise((e=>setTimeout(e,u)));try{const e=await fetch(`${t}/api/auth/cli/poll?token=${c}`);const n=await e.json();if(n.status==="ready"&&n.apiKey){(0,o.saveConfig)({...a,apiKey:n.apiKey,apiUrl:t!==r?t:undefined});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}`);console.log();return}if(n.status==="expired"){console.error(`\n ${i.c.red}Session expired. Run ${i.c.cyan}sf login${i.c.red} again.${i.c.reset}\n`);return}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`)}},23017:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.marketsCommand=marketsCommand;const s=n(35178);const o="https://simplefunctions.dev";async function marketsCommand(e){const t=await fetch(`${o}/api/public/markets`);if(!t.ok){console.error(` Error: ${t.status} ${await t.text()}`);return}const n=await t.json();if(e?.share){await(0,s.shareOutput)("markets","",n);return}if(e?.json){console.log(JSON.stringify(n,null,2));return}console.log(`\n [1mTraditional Markets[22m [2m${n.snapshotAt?.slice(0,10)||""}[22m\n`);if(!n.markets?.length){console.log(" No data available.\n");return}for(const e of n.markets){const t=e.changePct>=0?"[32m▲[39m":"[31m▼[39m";const n=e.changePct>=0?`[32m+${e.changePct}%[39m`:`[31m${e.changePct}%[39m`;const s=`$${e.price.toFixed(2)}`;console.log(` ${t} ${e.symbol.padEnd(5)} ${s.padStart(10)} ${n.padStart(16)} ${e.name}`)}console.log()}},8045:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.milestonesCommand=milestonesCommand;const s=n(19218);const o=n(99236);const i="https://api.elections.kalshi.com/trade-api/v2";async function milestonesCommand(e){const t=parseInt(e.hours||"168");const n=new Date;const r=new Date(n.getTime()+t*36e5);const a=`${i}/milestones?limit=200&minimum_start_date=${n.toISOString()}`+(e.category?`&category=${e.category}`:"");const c=await fetch(a,{headers:{Accept:"application/json"}});if(!c.ok)throw new Error(`Kalshi API ${c.status}`);const l=await c.json();let d=(l.milestones||[]).filter((e=>new Date(e.start_date).getTime()<=r.getTime()));if(e.thesis){const t=new s.SFClient(e.apiKey,e.apiUrl);const n=await t.getContext(e.thesis);const o=new Set((n.edges||[]).map((e=>e.eventTicker)).filter(Boolean));const i=new Set((n.edges||[]).map((e=>e.seriesTicker)).filter(Boolean));d=d.filter((e=>{const t=e.related_event_tickers||e.primary_event_tickers||[];return t.some((e=>o.has(e)||i.has(e.split("-")[0])))}))}if(e.json){console.log(JSON.stringify(d,null,2));return}if(d.length===0){console.log(`${o.c.dim}No milestones in the next ${t} hours.${o.c.reset}`);return}d.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 d){const t=new Date(e.start_date);const s=Math.round((t.getTime()-n.getTime())/36e5);const i=s<=24?`${o.c.bold}${s}h${o.c.reset}`:`${o.c.dim}${Math.round(s/24)}d${o.c.reset}`;const r=`${o.c.dim}[${e.category}]${o.c.reset}`;const a=(e.related_event_tickers||[]).slice(0,3).join(", ");console.log(` ${i.padEnd(12)} ${r.padEnd(25)} ${e.title}`);if(a)console.log(` ${" ".repeat(10)} ${o.c.dim}${a}${o.c.reset}`)}console.log(`\n${o.c.dim}${d.length} milestone(s)${o.c.reset}`)}},45475:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.ordersCommand=ordersCommand;const s=n(96139);const o=n(99236);async function ordersCommand(e){const t=e.status||"resting";const 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){console.log(JSON.stringify(n.orders,null,2));return}if(n.orders.length===0){console.log(`${o.c.dim}No ${t} orders.${o.c.reset}`);return}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?`${parseFloat(e.yes_price_dollars)*100}¢`:`${e.yes_price||"?"}¢`;const n=e.side==="yes"?`${o.c.green}YES${o.c.reset}`:`${o.c.red}NO${o.c.reset}`;const 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}`)}},33766:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.performanceCommand=performanceCommand;const s=n(19218);const o=n(96139);const i=n(11627);const r=n(99236);function fmtDate(e){const t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return`${t[e.getMonth()]} ${String(e.getDate()).padStart(2,"0")}`}function fmtDollar(e){const t=Math.abs(e/100);const n=t>=1e3?`${(t/1e3).toFixed(1)}k`:t>=100?t.toFixed(0):t.toFixed(2);return e>=0?`+$${n}`:`-$${n}`}function dateKey(e){return e.toISOString().slice(0,10)}function sparkline(e,t){if(e.length===0)return"";const n=Math.min(...e);const s=Math.max(...e);const o=s-n||1;const i=["▁","▂","▃","▄","▅","▆","▇","█"];return e.map((e=>{const s=Math.round((e-n)/o*(i.length-1));const a=i[s];if(t)return t(e)+a+r.c.reset;return a})).join("")}async function performanceCommand(e){if(!(0,o.isKalshiConfigured)()){console.log(`${r.c.yellow}Kalshi not configured.${r.c.reset} Run ${r.c.cyan}sf setup --kalshi${r.c.reset} first.`);return}const t=await(0,o.getFills)({limit:500});if(!t||t.fills.length===0){console.log(`${r.c.dim}No fills found.${r.c.reset}`);return}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";const o=e.side||"yes";const i=Math.round(parseFloat(e.count_fp||e.count||"0"));const r=Math.round(parseFloat(e.yes_price_dollars||"0")*100);let a=i;if(s==="sell")a=-a;if(o==="no")a=-a;const c=n.get(t)||{ticker:t,netQty:0,totalCostCents:0,totalContracts:0,earliestFillTs:Infinity};c.netQty+=a;if(a>0){const e=o==="no"?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);if(e<c.earliestFillTs)c.earliestFillTs=e}n.set(t,c)}let a=[...n.values()].filter((e=>e.netQty!==0));if(e.ticker){const t=e.ticker.toLowerCase();a=a.filter((e=>e.ticker.toLowerCase().includes(t)))}if(a.length===0){console.log(`${r.c.dim}No open positions found${e.ticker?` matching "${e.ticker}"`:""}.${r.c.reset}`);return}const c=e.since?Math.floor(new Date(e.since).getTime()/1e3):Math.min(...a.map((e=>e.earliestFillTs===Infinity?Math.floor(Date.now()/1e3)-30*86400:e.earliestFillTs)));const l=Math.floor(Date.now()/1e3);const d=await(0,o.getBatchCandlesticks)({tickers:a.map((e=>e.ticker)),startTs:c,endTs:l,periodInterval:1440});const u=new Map;for(const e of d){const t=[];for(const n of e.candlesticks||[]){const e=parseFloat(n.yes_bid?.close_dollars||"0");const s=parseFloat(n.yes_ask?.close_dollars||"0");const o=e>0&&s>0?(e+s)/2:e||s;const i=parseFloat(n.price?.close_dollars||"0")||o;const r=Math.round(i*100);const a=n.end_period_ts||n.period_end_ts||n.ts;if(a)t.push({date:dateKey(new Date(a*1e3)),close:r})}t.sort(((e,t)=>e.date.localeCompare(t.date)));u.set(e.market_ticker,t)}const p=new Set;for(const[,e]of u)for(const t of e)p.add(t.date);const h=[...p].sort();const m=new Map;for(const e of a){m.set(e.ticker,e.totalContracts>0?Math.round(e.totalCostCents/e.totalContracts):0)}const f=[];try{const e=(0,i.loadConfig)();const t=new s.SFClient(e.apiKey,e.apiUrl);const n=await t.getFeed(720);const 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||"";if(n){f.push({date:dateKey(new Date(n)),direction:t>0?"up":"down",deltaPct:Math.round(t*100),summary:e.summary||""})}}}}}catch{}const g=[];for(const e of a){const t=m.get(e.ticker)||0;const n=u.get(e.ticker)||[];const s=n.length>0?n[n.length-1].close:t;const o=(s-t)*e.netQty;const i=t*e.netQty;const r=i!==0?o/Math.abs(i)*100:0;const a=n.map((n=>(n.close-t)*e.netQty));g.push({ticker:e.ticker,qty:e.netQty,entry:t,current:s,pnlCents:o,pnlPct:r,dailyPnl:a})}g.sort(((e,t)=>Math.abs(t.pnlCents)-Math.abs(e.pnlCents)));const y=h.map((e=>{let t=0;for(const n of a){const s=u.get(n.ticker)||[];const o=m.get(n.ticker)||0;const i=s.find((t=>t.date===e));if(i)t+=(i.close-o)*n.netQty}return t}));const $=a.reduce(((e,t)=>e+t.totalCostCents),0);const k=g.reduce(((e,t)=>e+t.pnlCents),0);const b=$>0?k/$*100:0;if(e.json){console.log(JSON.stringify({positions:g.map((e=>({ticker:e.ticker,qty:e.qty,entry:e.entry,current:e.current,pnl:e.pnlCents,pnlPct:Math.round(e.pnlPct*10)/10}))),totalDailyPnl:h.map(((e,t)=>({date:e,pnl:y[t]}))),events:f,summary:{cost:$,pnl:k,pnlPct:Math.round(b*10)/10}},null,2));return}const w=h.length>0?fmtDate(new Date(h[0])):"?";const _=fmtDate(new Date);console.log();console.log(` ${r.c.bold}Portfolio Performance${r.c.reset} ${r.c.dim}(${w} → ${_})${r.c.reset}`);console.log(` ${r.c.dim}${"─".repeat(76)}${r.c.reset}`);console.log();const S=Math.max(...g.map((e=>e.ticker.length)),5)+2;const v=S+50;const pad2=(e,t)=>e.padEnd(t);console.log(` ${r.c.dim}${pad2("Ticker",S)} Qty Entry Now P&L Trend${r.c.reset}`);for(const e of g){const t=fmtDollar(e.pnlCents);const n=e.pnlCents>0?r.c.green:e.pnlCents<0?r.c.red:r.c.dim;const s=sparkline(e.dailyPnl,(e=>e>=0?r.c.green:r.c.red));console.log(` ${pad2(e.ticker,S)} `+`${(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(v)}${r.c.reset}`);const x=fmtDollar(k);const C=`${b>=0?"+":""}${b.toFixed(1)}%`;const O=k>=0?r.c.green:r.c.red;const I=sparkline(y,(e=>e>=0?r.c.green:r.c.red));console.log(` ${r.c.bold}${pad2("TOTAL",S)}${r.c.reset} `+`${(0,r.rpad)("",22)}`+`${O}${r.c.bold}${(0,r.rpad)(`${x} (${C})`,13)}${r.c.reset}`+I);if(f.length>0){const e=new Set(h);const t=f.filter((t=>e.has(t.date)));if(t.length>0){console.log();for(const e of t.slice(0,8)){const t=e.direction==="up"?`${r.c.green}▲${r.c.reset}`:`${r.c.red}▼${r.c.reset}`;const n=e.summary.length>55?e.summary.slice(0,54)+"…":e.summary;console.log(` ${t} ${r.c.dim}${fmtDate(new Date(e.date))}${r.c.reset} ${e.deltaPct>0?"+":""}${e.deltaPct}% → ${n}`)}}}console.log();const P=`$${($/100).toFixed(0)}`;console.log(` ${r.c.dim}Cost basis:${r.c.reset} ${P} ${r.c.dim}|${r.c.reset} ${O}${r.c.bold}${x} (${C})${r.c.reset}`);console.log()}},8784:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.positionsCommand=positionsCommand;const s=n(19218);const o=n(96139);const i=n(34331);const r=n(11627);const a=n(99236);async function positionsCommand(e){const t=new s.SFClient(e.apiKey,e.apiUrl);let n=null;if((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{const e=await t.listTheses();d=e.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=>e.status==="monitoring"||e.status==="active"));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);if(t!==null){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;if(!p.has(t))p.set(t,[]);p.get(t).push(e)}if(e.json){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));return}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;const n=e.average_price_paid||0;const s=e.unrealized_pnl||0;const o=s>0?a.c.green:s<0?a.c.red:a.c.dim;const i=s>=0?`+$${(s/100).toFixed(2)}`:`-$${(Math.abs(s)/100).toFixed(2)}`;const r=p.get(e.ticker)||[];const c=r[0];const l=c?.edge?.edge??c?.edge?.edgeSize??0;const d=Math.abs(l)>10?a.c.green:Math.abs(l)>5?a.c.yellow:a.c.dim;let u="HOLD";if(c){const t=e.side;const n=c.edge.direction;if(t===n&&l>3){u="HOLD"}else if(l<-3){u="CLOSE"}else{u="HOLD"}}else{u="—"}const h=u==="HOLD"?a.c.dim:u==="CLOSE"?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}`+`${d}${(0,a.rpad)(l?`${l>0?"+":""}${l.toFixed(0)}`:"-",7)}${a.c.reset}`+` ${h}${u}${a.c.reset}`)}console.log("")}else if((0,o.isKalshiConfigured)()){console.log(`\n ${a.c.dim}No open Kalshi positions.${a.c.reset}\n`)}else{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);const n=e.outcome||"YES";const s=e.size||0;const o=Math.round((e.avgPrice||0)*100);const i=Math.round((e.curPrice||e.currentPrice||0)*100);const r=e.cashPnl||(i-o)*s/100;const c=r>=0?a.c.green:a.c.red;const 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 if(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)));const 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=>e.edge.venue==="kalshi"&&!e.edge.orderbook&&Math.abs(e.edge.edge??e.edge.edgeSize??0)>5));const 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);if(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;const s=t.edge??t.edgeSize??0;const o=s>10?a.c.green:s>5?a.c.yellow:s>0?a.c.dim:a.c.red;const i=t.marketPrice??0;const r=t.thesisPrice??t.thesisImpliedPrice??0;const c=(t.market||t.marketTitle||t.marketId||"?").slice(0,29);const l=t.orderbook;const d=n.get(t.marketId);const u=l||d;const p=u?`${u.spread}¢`:"-";const h=u?u.liquidityScore:"-";const m=u?.liquidityScore==="high"?a.c.green:u?.liquidityScore==="medium"?a.c.yellow:a.c.dim;let f="WATCH";if(s>10&&u?.liquidityScore!=="low"){f="CONSIDER"}else if(s>5&&u?.liquidityScore==="high"){f="CONSIDER"}const g=f==="CONSIDER"?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}`+` ${g}${f}${a.c.reset}`)}console.log("")}else if(u.length===0){console.log(`\n${a.c.dim}No thesis edges found.${a.c.reset}\n`)}}},35344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.promptCommand=promptCommand;async function promptCommand(e,t){const n=(t.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev").replace(/\/$/,"");const s=t.apiKey||process.env.SF_API_KEY||"";const o=new URLSearchParams;if(t.sections)o.set("sections",t.sections);if(t.maxLength)o.set("maxLength",t.maxLength);if(t.json)o.set("format","json");const i=e?`/api/thesis/${e}/prompt`:"/api/prompt";const r=o.toString()?`?${o.toString()}`:"";const 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);if(!c.endsWith("\n"))process.stdout.write("\n")}},40791:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.publishCommand=publishCommand;t.unpublishCommand=unpublishCommand;const s=n(19218);function slugify(e){return e.toLowerCase().trim().replace(/[^a-z0-9\s-]/g,"").replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,60)}async function publishCommand(e,t){const n=slugify(t.slug);if(n.length<3){console.error(`\n Error: slug too short after normalization: "${n}" (need 3+ chars)\n`);process.exit(1)}if(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`)}async function unpublishCommand(e,t){const n=new s.SFClient(t.apiKey,t.apiUrl);await n.unpublish(e);console.log(`\n ✓ Unpublished thesis ${e}\n`)}},65240:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.queryCommand=queryCommand;const s=n(35178);const o=process.env.SF_API_URL||"https://simplefunctions.dev";async function queryCommand(e,t){const n=t?.limit||"10";const i=`${o}/api/public/query?q=${encodeURIComponent(e)}&limit=${n}`;const r=await fetch(i);if(!r.ok){const e=await r.text();if(r.status===429){console.error(" Rate limited. Wait a minute and try again.")}else{console.error(` Error: ${r.status} ${e}`)}return}const a=await r.json();if(t?.share){await(0,s.shareOutput)("query",e,a);return}if(t?.json){console.log(JSON.stringify(a,null,2));return}console.log();console.log(` [1m${a.query}[22m`);console.log();if(a.answer){console.log(` ${a.answer}`);console.log()}if(a.keyFactors?.length>0){console.log(" [2mKey factors:[22m");for(const e of a.keyFactors){console.log(` • ${e}`)}console.log()}const c=a.kalshi||[];const l=a.polymarket||[];if(c.length>0||l.length>0){console.log(" [1mMarkets[22m");for(const e of c.slice(0,8)){const t=fmtVol(e.volume);const 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}`)}if(c.length>0&&l.length>0)console.log();for(const e of l.slice(0,8)){const t=fmtVol(e.volume);const 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 d=a.x||[];if(d.length>0){console.log(" [1mX signals[22m");for(const e of d.slice(0,5)){const t=`${fmtNum(e.likes)}♥ ${fmtNum(e.retweets)}⟲`;console.log(` @${e.author} ${t} ${e.text.slice(0,80)}`)}console.log()}const u=a.traditional||[];if(u.length>0){console.log(" [1mTraditional[22m");for(const e of u){const t=e.change1d>=0?"+":"";console.log(` ${e.symbol.padEnd(5)} $${e.price} ${t}${e.change1d} (${t}${e.changePct}%) ${e.name}`)}console.log()}if(a.theses?.length>0){console.log(" [1mTheses[22m");for(const e of a.theses.slice(0,3)){console.log(` ${e.confidence||"?"}% ${String(e.edges||0).padStart(2)} edges ${e.title.slice(0,50)}`)}console.log()}if(a.content?.length>0){console.log(" [1mContent[22m");for(const e of a.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 p=a.meta||{};const h=p.sources||a.sources||[];const m=p.latencyMs?`${(p.latencyMs/1e3).toFixed(1)}s`:"";console.log(` [2mSources: ${h.join(", ")}${m?` (${m})`:""}[22m`);console.log()}function fmtVol(e){if(e>1e6)return`${(e/1e6).toFixed(1)}M`;if(e>1e3)return`${(e/1e3).toFixed(0)}K`;return String(Math.round(e))}function fmtNum(e){if(e>1e6)return`${(e/1e6).toFixed(1)}M`;if(e>1e3)return`${(e/1e3).toFixed(1)}K`;return String(e)}},43423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.rfqCommand=rfqCommand;const s=n(96139);const o=n(11627);const i=n(99236);async function rfqCommand(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}`);if(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||false,...n.targetCost?{target_cost_centi_cents:parseInt(n.targetCost)*100}:{}});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)}}},52072:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.registerRuntime=registerRuntime;const s=n(19218);const o=n(96139);const i=n(99236);const r=n(79896);const a=n(16928);const c=n(70857);const l=(0,a.join)((0,c.homedir)(),".sf","runtime.pid");const d=(0,a.join)((0,c.homedir)(),".sf","runtime.log");const u=3e4;const p=3e5;const h=new Set;function registerRuntime(e){const t=e.command("runtime").description("Execution runtime daemon");t.command("start").option("--daemon","Run as background process").description("Start the execution runtime").action((async e=>{if(!(0,o.isKalshiConfigured)()){console.error(`\n ${i.c.red}Error:${i.c.reset} Kalshi credentials not configured.`);console.error(` Run: sf setup --enable-trading\n`);process.exit(1)}if((0,r.existsSync)(l)){const e=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(e),0);console.error(`\n ${i.c.yellow}Warning:${i.c.reset} Runtime already running (PID ${e}).`);console.error(` Stop it first: sf runtime stop\n`);process.exit(1)}catch{(0,r.unlinkSync)(l)}}if(e.daemon){console.error(`\n ${i.c.dim}Daemon mode not yet implemented. Run in foreground for now.${i.c.reset}\n`);process.exit(1)}await startRuntime()}));t.command("stop").description("Stop the runtime daemon").action((async()=>{if(!(0,r.existsSync)(l)){console.log(`\n ${i.c.dim}No runtime running.${i.c.reset}\n`);return}const e=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(e),"SIGTERM");(0,r.unlinkSync)(l);console.log(`\n ${i.c.green}OK${i.c.reset} Runtime stopped (PID ${e}).\n`)}catch{(0,r.unlinkSync)(l);console.log(`\n ${i.c.dim}Runtime was not running (stale PID file removed).${i.c.reset}\n`)}}));t.command("status").option("--json","JSON output").description("Show runtime status and active intents").action((async e=>{try{let t=false;let n="";if((0,r.existsSync)(l)){n=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(n),0);t=true}catch{t=false}}const o=new s.SFClient;const{intents:a}=await o.listIntents({active:true});if(e.json){console.log(JSON.stringify({running:t,pid:t?n:null,intents:a},null,2));return}console.log();console.log(` ${i.c.bold}Runtime${i.c.reset} ${t?`${i.c.green}RUNNING${i.c.reset} (PID ${n})`:`${i.c.dim}STOPPED${i.c.reset}`}`);console.log();if(!a||a.length===0){console.log(` ${i.c.dim}No active intents.${i.c.reset}`);console.log(` Create one: sf intent buy TICKER QTY --price CENTS`);console.log();return}const c={};for(const e of a){c[e.status]=(c[e.status]||0)+1}const d=Object.entries(c).map((([e,t])=>`${t} ${e}`)).join(", ");console.log(` Active intents: ${d}`);console.log();for(const e of a){const t=e.action.toUpperCase();const n=e.direction.toUpperCase();const s=e.maxPrice?`@ ≤${e.maxPrice}c`:"@ market";const o=e.targetQuantity>0?` (${Math.round(e.filledQuantity/e.targetQuantity*100)}%)`:"";console.log(` [${e.status}] ${t} ${e.marketId} ${n} ${e.targetQuantity}${s} filled ${e.filledQuantity}/${e.targetQuantity}${o}`);if(e.triggerType!=="immediate"){const t=e.triggerType==="price_below"?`price ≤ ${e.triggerPrice}c`:e.triggerType==="price_above"?`price ≥ ${e.triggerPrice}c`:e.triggerType;console.log(` trigger: ${t}`)}}console.log();if(!t){console.log(` ${i.c.dim}Start runtime to execute: sf runtime start${i.c.reset}`);console.log()}}catch(e){console.error(`${i.c.red}Error:${i.c.reset} ${e.message}`);process.exit(1)}}))}async function startRuntime(){const e=(0,a.join)((0,c.homedir)(),".sf");if(!(0,r.existsSync)(e))(0,r.mkdirSync)(e,{recursive:true});(0,r.writeFileSync)(l,process.pid.toString());console.log();console.log(` ${i.c.bold}SimpleFunctions Runtime${i.c.reset}`);console.log(` ${i.c.dim}PID ${process.pid} · polling every ${u/1e3}s · Ctrl+C to stop${i.c.reset}`);console.log();const t=new s.SFClient;let n=0;let o=0;const shutdown=()=>{console.log(`\n ${i.c.dim}Runtime stopping...${i.c.reset}`);try{(0,r.unlinkSync)(l)}catch{}process.exit(0)};process.on("SIGINT",shutdown);process.on("SIGTERM",shutdown);while(true){o++;const e=Date.now();try{const{intents:e}=await t.listIntents({active:true});if(!e||e.length===0){if(o%10===1){log("No active intents. Waiting...")}await sleep(u);continue}for(const n of e){await processIntent(t,n)}}catch(e){log(`Error in cycle: ${e.message}`)}await sleep(u)}}async function processIntent(e,t){if(t.activateAt&&new Date(t.activateAt)>new Date)return;if(new Date(t.expireAt)<new Date){log(`Intent ${t.id.slice(0,8)} expired`);try{await e.cancelIntentAPI(t.id)}catch{}return}if(t.status==="pending"){log(`Arming intent ${t.id.slice(0,8)}: ${t.action.toUpperCase()} ${t.marketId} ${t.direction.toUpperCase()} x${t.targetQuantity}`)}if(t.status==="pending"||t.status==="armed"){const n=await evaluateTrigger(t);if(!n)return;log(`TRIGGERED: ${t.id.slice(0,8)} ${t.marketId} (${t.triggerType})`);if(t.autoExecute){await executeIntent(e,t)}else{log(` Awaiting confirmation. Use: sf intent status ${t.id.slice(0,8)}`)}}if(t.status==="triggered"&&t.autoExecute){await executeIntent(e,t)}}async function evaluateTrigger(e){switch(e.triggerType){case"immediate":return true;case"price_below":{if(!e.triggerPrice)return false;const t=await(0,o.getMarketPrice)(e.marketId);if(t===null)return false;return t<=e.triggerPrice}case"price_above":{if(!e.triggerPrice)return false;const t=await(0,o.getMarketPrice)(e.marketId);if(t===null)return false;return t>=e.triggerPrice}case"time":{if(!e.triggerAt)return false;return new Date>=new Date(e.triggerAt)}default:return false}}async function executeIntent(e,t){if(h.has(t.id)){return}if(t.venue!=="kalshi"){log(` Skipping ${t.id.slice(0,8)}: ${t.venue} execution not yet supported`);return}const n=t.targetQuantity-t.filledQuantity;if(n<=0){h.add(t.id);return}h.add(t.id);log(` Executing: ${t.action.toUpperCase()} ${t.marketId} ${t.direction.toUpperCase()} x${n}${t.maxPrice?` @ ≤${t.maxPrice}c`:""}`);try{const s=await(0,o.createOrder)({ticker:t.marketId,side:t.direction,action:t.action,type:t.maxPrice?"limit":"market",count:n,...t.maxPrice?{yes_price:t.maxPrice}:{}});const l=s.order||s;const d=l.fill_count||l.fill_count_fp||n;const u=l.yes_price||l.no_price||t.maxPrice||0;log(` ${i.c.green}FILLED${i.c.reset}: ${d} contracts, order ${l.order_id||"OK"}`);try{const e=JSON.stringify({ts:(new Date).toISOString(),intentId:t.id,action:t.action,ticker:t.marketId,side:t.direction,quantity:d,price:t.maxPrice,orderId:l.order_id,source:t.source})+"\n";(0,r.appendFileSync)((0,a.join)((0,c.homedir)(),".sf","trade-journal.jsonl"),e)}catch{}try{await e.request("PATCH",`/api/intents/${t.id}`,{fill:{orderId:l.order_id||null,fillQuantity:d,fillPrice:u,fillCostCents:Math.round(u*d),venueResponse:{order_id:l.order_id,status:l.status}}});log(` ${i.c.dim}Fill recorded to API${i.c.reset}`)}catch(e){log(` ${i.c.yellow}Warning:${i.c.reset} Failed to record fill to API: ${e.message}. Intent may re-execute on restart.`)}}catch(e){h.delete(t.id);const n=e.message||String(e);if(n.includes("403")){log(` ${i.c.red}FAILED${i.c.reset}: 403 Forbidden — Kalshi key lacks write permission`);h.add(t.id)}else{log(` ${i.c.red}FAILED${i.c.reset}: ${n}`)}}}function log(e){const t=(new Date).toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"});console.log(` ${i.c.dim}${t}${i.c.reset} ${e}`)}function sleep(e){return new Promise((t=>setTimeout(t,e)))}},46183:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.scanCommand=scanCommand;const s=n(19218);const o=n(34331);const i=n(99236);const r=n(35178);const a=process.env.SF_API_URL||"https://simplefunctions.dev";async function scanCommand(e,t){if(t.market){await showMarket(t.market.toUpperCase(),t.json);return}if(t.series){await showSeries(t.series.toUpperCase(),t.json);return}await keywordScan(e,t.json,t.venue||"all",t.share)}async function showMarket(e,t){console.log(`${i.c.dim}Fetching market ${e}...${i.c.reset}`);const n=await(0,s.kalshiFetchMarket)(e);if(t){console.log(JSON.stringify(n,null,2));return}(0,i.header)(`${n.title||n.ticker}`);if(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}`);if(n.rules_primary){console.log(`\nRules: ${n.rules_primary.slice(0,300)}`)}}async function showSeries(e,t){console.log(`${i.c.dim}Fetching events for series ${e}...${i.c.reset}`);let n=await(0,s.kalshiFetchEvents)(e);if(n.length===0){const n=await(0,s.kalshiFetchMarketsBySeries)(e);if(t){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(`${i.c.dim}No open markets found for series ${e}.${i.c.reset}`);return}(0,i.header)(`${e} — ${n.length} markets`);printMarketsTable(n);return}if(t){console.log(JSON.stringify(n,null,2));return}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}`);const t=e.markets&&e.markets.length>0?e.markets:await(0,s.kalshiFetchMarketsByEvent)(e.event_ticker);printMarketsTable(t)}}async function keywordScan(e,t,n="all",s){const c=n==="kalshi"?Promise.resolve([]):(0,o.polymarketSearch)(e,10).catch((()=>[]));if(n!=="polymarket"){console.log(`${i.c.dim}Scanning Kalshi for: "${e}"...${i.c.reset}`)}if(n!=="kalshi"){console.log(`${i.c.dim}Scanning Polymarket for: "${e}"...${i.c.reset}`)}const l=[];if(n!=="polymarket"){try{const t=`${a}/api/public/scan?q=${encodeURIComponent(e)}&limit=30`;const n=await fetch(t);if(!n.ok)throw new Error(`Proxy ${n.status}`);const s=await n.json();const o=s.matchedSeries||[];const 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;const 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);const s=n[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:s,lastPrice:t.lastTradePrice||s,volume24h:t.volume24hr||0,liquidity:t.liquidityNum||0})}}for(const e of l){if(!e.venue)e.venue="kalshi"}const p=[...l,...u];p.sort(((e,t)=>t.liquidity-e.liquidity));if(s){await(0,r.shareOutput)("scan",e,p);return}if(t){console.log(JSON.stringify(p,null,2));return}(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=e.venue==="polymarket"?"POLY ":"KLSH ";const n=e.venue==="polymarket"?i.c.blue+t+i.c.reset:i.c.cyan+t+i.c.reset;const s=e.venue==="polymarket"?(e.ticker||"").slice(0,28):(e.ticker||"").slice(0,28);console.log(n+(0,i.pad)(s,30)+(0,i.rpad)(`${Math.round(e.yesAsk*100)}¢`,6)+(0,i.rpad)(`${Math.round(e.lastPrice*100)}¢`,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("");if(!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("")}}function printMarketsTable(e){if(e.length===0){console.log(` ${i.c.dim}(no markets)${i.c.reset}`);return}e.sort(((e,t)=>{const n=parseFloat(e.yes_ask_dollars||e.last_price_dollars||"0");const s=parseFloat(t.yes_ask_dollars||t.last_price_dollars||"0");return s-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("")}},58211:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.scheduleCommand=scheduleCommand;const s=n(99236);const o="https://api.elections.kalshi.com/trade-api/v2";async function scheduleCommand(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"}});if(e.ok)i=await e.json()}catch{}if(e.json){console.log(JSON.stringify({status:n,schedule:i},null,2));return}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}`);if(n.trading_active!==undefined){console.log(` Trading Active: ${n.trading_active?"yes":"no"}`)}if(i?.schedule){console.log(` Schedule: ${JSON.stringify(i.schedule).slice(0,100)}`)}console.log()}},96616:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.settlementsCommand=settlementsCommand;const s=n(96139);const o=n(19218);const i=n(99236);async function settlementsCommand(e){const t=[];let n="";do{const e=await(0,s.getSettlements)({limit:200,cursor:n||undefined});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);const s=await n.getContext(e.thesis);const i=new Set((s.edges||[]).map((e=>e.marketId)));r=t.filter((e=>i.has(e.ticker)))}if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(`${i.c.dim}No settlements found.${i.c.reset}`);return}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");const n=parseFloat(e.yes_total_cost||e.yes_total_cost_dollars||"0")+parseFloat(e.no_total_cost||e.no_total_cost_dollars||"0");const 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}`;const 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)`)}},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:true});t.setupCommand=setupCommand;const o=s(n(23785));const i=n(35317);const r=n(11627);const a=n(19218);const c=n(96139);const l=n(83969);const green=e=>`[32m${e}[39m`;const red=e=>`[31m${e}[39m`;const dim=e=>`[2m${e}[22m`;const bold=e=>`[1m${e}[22m`;const cyan=e=>`[36m${e}[39m`;function ok(e){console.log(` ${green("✓")} ${e}`)}function fail(e){console.log(` ${red("✗")} ${e}`)}function info(e){console.log(` ${e}`)}function blank(){console.log()}function prompt(e){const t=o.default.createInterface({input:process.stdin,output:process.stdout,terminal:true});return new Promise((n=>{t.question(e,(e=>{t.close();n(e.trim())}))}))}function promptYN(e,t=true){return prompt(e).then((e=>{if(!e)return t;return e.toLowerCase().startsWith("y")}))}function openBrowser(e){const t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,i.exec)(`${t} ${e}`)}function mask(e){if(!e||e.length<=12)return e;return e.slice(0,8)+"..."+e.slice(-4)}async function validateSFKey(e,t){try{const n=await fetch(`${t}/api/thesis`,{headers:{Authorization:`Bearer ${e}`}});if(n.ok)return{valid:true,msg:`API key valid — connected to ${t.replace("https://","")}`};if(n.status===401)return{valid:false,msg:"Invalid key, please try again"};return{valid:false,msg:`Server returned ${n.status}`}}catch(e){return{valid:false,msg:`Connection failed: ${e.message}`}}}async function validateOpenRouterKey(e){try{const t=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${e}`}});if(t.ok)return{valid:true,msg:"OpenRouter connected — available model: claude-sonnet-4.6"};return{valid:false,msg:`OpenRouter returned ${t.status}`}}catch(e){return{valid:false,msg:`Connection failed: ${e.message}`}}}async function validateKalshi(){try{const e=await(0,c.getPositions)();if(e===null)return{valid:false,msg:"Kalshi authentication failed",posCount:0};return{valid:true,msg:`Kalshi authenticated — found ${e.length} position(s)`,posCount:e.length}}catch(e){return{valid:false,msg:`Kalshi connection failed: ${e.message}`,posCount:0}}}async function validateTavily(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})});if(t.ok)return{valid:true,msg:"Tavily connected"};return{valid:false,msg:`Tavily returned ${t.status}`}}catch(e){return{valid:false,msg:`Connection failed: ${e.message}`}}}async function setupCommand(e){if(e.check){return showCheck()}if(e.reset){(0,r.resetConfig)();ok("Config reset");blank();info("Run sf setup to reconfigure");blank();return}if(e.key){const t=process.env.SF_API_URL||"https://simplefunctions.dev";const n=await validateSFKey(e.key,t);if(!n.valid){fail(n.msg);process.exit(1)}const s=(0,r.loadFileConfig)();(0,r.saveConfig)({...s,apiKey:e.key,apiUrl:t});ok(n.msg);ok(`Saved to ${(0,r.getConfigPath)()}`);return}if(e.kalshi){const e=(0,r.loadFileConfig)();blank();console.log(` ${bold("Reconfigure Kalshi Credentials")}`);blank();info("Go to https://kalshi.com/account/api-keys to generate a new API key.");info("If you need trading, make sure to enable read+write permissions.");blank();await promptForKalshi(e);(0,r.saveConfig)(e);if(e.kalshiKeyId){process.env.KALSHI_API_KEY_ID=e.kalshiKeyId;process.env.KALSHI_PRIVATE_KEY_PATH=e.kalshiPrivateKeyPath}blank();return}if(e.polymarket){const e=(0,r.loadFileConfig)();blank();console.log(` ${bold("Reconfigure Polymarket Credentials")}`);blank();await promptForPolymarket(e);(0,r.saveConfig)(e);blank();return}if(e.enableTrading){const e=(0,r.loadFileConfig)();(0,r.saveConfig)({...e,tradingEnabled:true});ok("Trading enabled. sf buy / sf sell / sf cancel now available.");blank();return}if(e.disableTrading){const e=(0,r.loadFileConfig)();(0,r.saveConfig)({...e,tradingEnabled:false});ok("Trading disabled.");blank();return}return runWizard()}async function showCheck(){const e=(0,r.loadConfig)();blank();console.log(` ${bold("SimpleFunctions Config Status")}`);console.log(` ${dim("─".repeat(35))}`);blank();if(e.apiKey){ok(`SF_API_KEY ${dim(mask(e.apiKey))}`)}else{fail("SF_API_KEY not configured (required)")}if(e.openrouterKey){ok(`OPENROUTER ${dim(mask(e.openrouterKey))} (direct)`)}else if(e.apiKey){ok(`OPENROUTER ${dim("proxied via SimpleFunctions")}`)}else{fail(`OPENROUTER not configured (run sf login or set key)`)}if(e.kalshiKeyId&&e.kalshiPrivateKeyPath){ok(`KALSHI ${dim(mask(e.kalshiKeyId))}`)}else{info(`${dim("○")} KALSHI ${dim("skipped")}`)}if(e.polymarketWalletAddress){ok(`POLYMARKET ${dim(mask(e.polymarketWalletAddress))}`)}else{info(`${dim("○")} POLYMARKET ${dim("skipped")}`)}if(e.tavilyKey){ok(`TAVILY ${dim(mask(e.tavilyKey))} (direct)`)}else if(e.apiKey){ok(`TAVILY ${dim("proxied via SimpleFunctions")}`)}else{info(`${dim("○")} TAVILY ${dim("skipped")}`)}if(e.tradingEnabled){ok("TRADING enabled")}else{info(`${dim("○")} TRADING ${dim("disabled — sf setup --enable-trading")}`)}blank();console.log(` ${dim("Config file: "+(0,r.getConfigPath)())}`);blank()}async function runWizard(){blank();console.log(` ${bold("SimpleFunctions Setup")}`);console.log(` ${dim("─".repeat(25))}`);blank();const e=(0,r.loadFileConfig)();const t=e.apiUrl||"https://simplefunctions.dev";console.log(` ${bold("Step 1: API Key")}`);blank();const n=process.env.SF_API_KEY||e.apiKey;if(n){const s=await validateSFKey(n,t);if(s.valid){ok(`Detected SF_API_KEY — ${dim(mask(n))}`);info(dim("Skipping."));e.apiKey=n;blank()}else{fail(`Existing key invalid: ${s.msg}`);e.apiKey=await promptForSFKey(t)}}else{e.apiKey=await promptForSFKey(t)}e.apiUrl=t;(0,r.saveConfig)(e);process.env.SF_API_KEY=e.apiKey;console.log(` ${bold("Step 2: AI Model (for sf agent)")}`);blank();const s=process.env.OPENROUTER_API_KEY||e.openrouterKey;if(s){const t=await validateOpenRouterKey(s);if(t.valid){ok(`Detected OPENROUTER_API_KEY — ${dim(mask(s))}`);info(dim("Skipping."));e.openrouterKey=s;blank()}else{fail(`Existing key invalid: ${t.msg}`);e.openrouterKey=await promptForOpenRouterKey()}}else{e.openrouterKey=await promptForOpenRouterKey()}(0,r.saveConfig)(e);if(e.openrouterKey)process.env.OPENROUTER_API_KEY=e.openrouterKey;console.log(` ${bold("Step 3: Kalshi Exchange (optional)")}`);blank();const o=process.env.KALSHI_API_KEY_ID||e.kalshiKeyId;const 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 validateKalshi();if(t.valid){ok(`Detected Kalshi — ${dim(mask(o))} (${t.posCount} position(s))`);info(dim("Skipping."));e.kalshiKeyId=o;e.kalshiPrivateKeyPath=i;blank()}else{fail(`Existing credentials invalid: ${t.msg}`);await promptForKalshi(e)}}else{await promptForKalshi(e)}(0,r.saveConfig)(e);console.log(` ${bold("Step 4: Polymarket (optional)")}`);blank();const a=process.env.POLYMARKET_WALLET_ADDRESS||e.polymarketWalletAddress;if(a){ok(`Detected wallet — ${dim(mask(a))}`);info(dim("Skipping."));e.polymarketWalletAddress=a;blank()}else{await promptForPolymarket(e)}(0,r.saveConfig)(e);if(e.polymarketWalletAddress)process.env.POLYMARKET_WALLET_ADDRESS=e.polymarketWalletAddress;console.log(` ${bold("Step 5: News Search (optional)")}`);blank();const c=process.env.TAVILY_API_KEY||e.tavilyKey;if(c){const t=await validateTavily(c);if(t.valid){ok(`Detected TAVILY_API_KEY — ${dim(mask(c))}`);info(dim("Skipping."));e.tavilyKey=c;blank()}else{fail(`Existing key invalid: ${t.msg}`);e.tavilyKey=await promptForTavily()}}else{e.tavilyKey=await promptForTavily()}(0,r.saveConfig)(e);if(e.tavilyKey)process.env.TAVILY_API_KEY=e.tavilyKey;if(e.kalshiKeyId){console.log(` ${bold("Step 6: Trading (optional)")}`);blank();info("Warning: enabling this unlocks sf buy / sf sell / sf cancel.");info("Your Kalshi API key must have read+write permissions.");blank();const t=await promptYN(" Enable trading? (y/N) ",false);e.tradingEnabled=t;if(t){ok("Trading enabled")}else{info(dim("Skipped. You can enable later with sf setup --enable-trading."))}blank();(0,r.saveConfig)(e)}console.log(` ${dim("─".repeat(25))}`);info(`Config saved to ${dim((0,r.getConfigPath)())}`);blank();if(e.apiKey)ok("SF_API_KEY configured");else fail("SF_API_KEY not configured");if(e.openrouterKey)ok("OPENROUTER_KEY configured");else fail("OPENROUTER_KEY skipped");if(e.kalshiKeyId)ok("KALSHI configured");else info(`${dim("○")} KALSHI skipped`);if(e.tavilyKey)ok("TAVILY configured");else info(`${dim("○")} TAVILY skipped`);blank();if(e.apiKey){await handleThesisStep(e)}}async function promptForSFKey(e){info(`Don't have a key? Sign up at ${cyan("https://simplefunctions.dev/dashboard")}.`);info("Press Enter to open browser, or paste your key:");blank();while(true){const t=await prompt(" > ");if(!t){openBrowser("https://simplefunctions.dev/dashboard");info(dim("Browser opened. Paste your key here once you have it:"));continue}info(dim("Validating..."));const n=await validateSFKey(t,e);if(n.valid){ok(n.msg);blank();return t}else{fail(n.msg)}}}async function promptForOpenRouterKey(){info(`Requires an OpenRouter API key. Get one at ${cyan("https://openrouter.ai/settings/keys")}.`);info("Press Enter to skip (agent unavailable), or paste key:");blank();const e=await prompt(" > ");if(!e){info(dim("Skipped."));blank();return undefined}info(dim("Validating..."));const t=await validateOpenRouterKey(e);if(t.valid){ok(t.msg)}else{fail(t.msg);info(dim("Saved. You can re-run sf setup later to fix this."))}blank();return e}async function promptForKalshi(e){info(`Connect Kalshi to view your positions and P&L.`);info(`Requires an API Key ID and private key file.`);info(`Get them at ${cyan("https://kalshi.com/account/api-keys")}.`);info("Press Enter to skip, or paste Key ID:");blank();const t=await prompt(" > ");if(!t){info(dim("Skipped."));blank();return}info("Private key file path (default ~/.kalshi/private.pem):");const n=await prompt(" > ");const s=n||"~/.kalshi/private.pem";e.kalshiKeyId=t;e.kalshiPrivateKeyPath=s;process.env.KALSHI_API_KEY_ID=t;process.env.KALSHI_PRIVATE_KEY_PATH=s;info(dim("Validating..."));const o=await validateKalshi();if(o.valid){ok(o.msg)}else{fail(o.msg);info(dim("Saved. You can re-run sf setup later to fix this."))}blank()}async function promptForTavily(){info(`Tavily API powers the agent's web_search tool.`);info(`Get a free key at ${cyan("https://tavily.com")}.`);info("Press Enter to skip:");blank();const e=await prompt(" > ");if(!e){info(dim("Skipped."));blank();return undefined}info(dim("Validating..."));const t=await validateTavily(e);if(t.valid){ok(t.msg)}else{fail(t.msg);info(dim("Saved. You can re-run sf setup later to fix this."))}blank();return e}async function promptForPolymarket(e){info("Connect Polymarket to view positions and scan orderbooks.");info("Your Polygon wallet address is needed (starts with 0x...).");info(`Find it at ${cyan("https://polymarket.com")} → Settings → Profile.`);info("Press Enter to skip:");blank();const t=await prompt(" Wallet address > ");if(!t){info(dim("Skipped."));blank();return}if(!t.startsWith("0x")||t.length<40){fail("Invalid wallet address (must start with 0x and be 42 characters)");info(dim("Saved anyway. You can fix it later with sf setup."))}else{ok(`Wallet: ${mask(t)}`)}e.polymarketWalletAddress=t;info(dim("Private key (for future trading) — press Enter to skip:"));const n=await prompt(" Key path > ");if(n){e.polymarketPrivateKeyPath=n;ok(`Private key path: ${dim(n)}`)}blank()}async function handleThesisStep(e){try{const t=new a.SFClient(e.apiKey,e.apiUrl);const n=await t.listTheses();const s=n.theses||[];const o=s.filter((e=>e.status==="active"));if(o.length>0){console.log(` ${bold("Step 7: Theses")}`);blank();ok(`Found ${o.length} active thesis(es):`);for(const e of o.slice(0,5)){const t=typeof e.confidence==="number"?Math.round(e.confidence*100):0;const n=(e.rawThesis||e.thesis||e.title||"").slice(0,60);info(` ${dim(e.id.slice(0,8))} — ${n} — ${t}%`)}info(dim("Skipping creation."));blank();if(e.openrouterKey){console.log(` ${dim("─".repeat(25))}`);console.log(` ${bold("All set!")}`);blank();info(` ${cyan("sf agent")} Chat with your thesis`);info(` ${cyan("sf context <id>")} View thesis snapshot`);info(` ${cyan("sf positions")} View positions`);info(` ${cyan("sf setup --check")} Check config`);blank();const t=await promptYN(` Launch agent now? (Y/n) `);if(t){blank();info("Launching...");blank();await(0,l.agentCommand)(o[0].id,{model:e.model})}}else{blank();console.log(` ${bold("All set!")}`);blank();info(` ${cyan("sf list")} List all theses`);info(` ${cyan("sf context <id>")} View thesis snapshot`);info(` ${cyan("sf positions")} View positions`);info(` ${cyan("sf setup --check")} Check config`);blank()}return}console.log(` ${bold("Step 7: Create Your First Thesis")}`);blank();info("A thesis is your core market conviction. The system builds a causal model");info("from it, then continuously scans prediction markets for mispriced contracts.");blank();info("Examples:");info(` ${dim('"The Fed won\'t cut rates in 2026 — inflation stays elevated due to oil prices"')}`);info(` ${dim('"AI-driven layoffs cause consumer spending to contract, S&P drops 20% by year-end"')}`);info(` ${dim('"Trump can\'t exit the Iran conflict — oil stays above $100 for six months"')}`);blank();const i=await prompt(" Enter your thesis (press Enter to skip, use sf create later):\n > ");if(!i){blank();info(dim('Skipped. Use sf create "your thesis" to create one later.'));blank();showFinalHints(e);return}blank();info("Building causal model... (~30s)");blank();try{const n=await t.createThesis(i,true);if(n.id){const t=n.causalTree?.nodes?.length||0;const s=n.edgeAnalysis?.edges?.length||0;const o=n.edgeAnalysis?.totalMarketsAnalyzed||0;const i=Math.round((parseFloat(n.confidence)||.5)*100);ok(`Causal tree: ${t} node(s)`);ok(`Scanned ${o} markets, found ${s} contract(s) with edge`);ok(`Confidence: ${i}%`);ok(`Thesis ID: ${n.id.slice(0,8)}`);blank();if(e.openrouterKey){console.log(` ${dim("─".repeat(25))}`);console.log(` ${bold("All set!")}`);blank();const t=await promptYN(` Launch agent now? (Y/n) `);if(t){blank();info("Launching...");blank();await(0,l.agentCommand)(n.id,{model:e.model})}else{blank();showFinalHints(e)}}else{showFinalHints(e)}}else{fail(`Creation failed: ${n.error||"unknown error"}`);info(dim('You can retry later with sf create "your thesis"'));blank();showFinalHints(e)}}catch(t){fail(`Creation failed: ${t.message}`);info(dim('You can retry later with sf create "your thesis"'));blank();showFinalHints(e)}}catch{blank();showFinalHints(e)}}function showFinalHints(e){console.log(` ${dim("─".repeat(25))}`);console.log(` ${bold("All set!")}`);blank();info(` ${cyan("sf agent")} Chat with your thesis`);info(` ${cyan("sf list")} List all theses`);info(` ${cyan("sf context <id>")} View thesis snapshot`);info(` ${cyan("sf positions")} View positions`);info(` ${cyan("sf setup --check")} Check config`);blank()}},67378:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.signalCommand=signalCommand;const s=n(19218);const o=n(99236);async function signalCommand(e,t,n){const i=new s.SFClient(n.apiKey,n.apiUrl);const r=n.type||"user_note";const a=await i.injectSignal(e,r,t,"cli");if(n.json){console.log(JSON.stringify({signalId:a.signalId||null,type:r,source:"cli",content:t},null,2));return}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}`);if(a.signalId){console.log(` ${o.c.bold}ID:${o.c.reset} ${a.signalId}`)}const c=new Date;const l=c.getMinutes();const d=Math.ceil((l+1)/15)*15;const u=d-l;const p=new Date(c);p.setMinutes(d%60,0,0);if(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}`)}},72124:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.statusCommand=statusCommand;const s=n(99236);const o=n(96139);const i=n(11627);const r=process.env.SF_API_URL||"https://simplefunctions.dev";async function statusCommand(e){const t=[];const n=Date.now();try{const e=await fetch(`${r}/api`,{signal:AbortSignal.timeout(5e3)});t.push({name:"API",status:e.ok?"ok":"fail",detail:e.ok?r.replace("https://",""):`HTTP ${e.status}`,ms:Date.now()-n})}catch(e){t.push({name:"API",status:"fail",detail:e.message?.slice(0,40)||"unreachable",ms:Date.now()-n})}const a=(0,i.loadConfig)();if((0,i.isConfigured)()){const e=Date.now();try{const n=await fetch(`${r}/api/thesis`,{headers:{Authorization:`Bearer ${a.apiKey}`},signal:AbortSignal.timeout(5e3)});const s=(a.apiKey||"").slice(0,12)+"...";t.push({name:"Auth",status:n.ok?"ok":"fail",detail:n.ok?s:`HTTP ${n.status}`,ms:Date.now()-e})}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 e=Date.now();try{const n=await(0,o.getBalance)();t.push({name:"Kalshi",status:n?"ok":"fail",detail:n?`$${n.balance.toFixed(2)} balance`:"auth failed",ms:Date.now()-e})}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)"})}if(a.polymarketWalletAddress){t.push({name:"Polymarket",status:"ok",detail:a.polymarketWalletAddress.slice(0,10)+"..."})}else{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();const s=n.theses||[];const o=s.filter((e=>e.status==="active")).length;const i=s.length;t.push({name:"Theses",status:"ok",detail:`${o} active, ${i} total`})}}catch{}}const c=a.tradingEnabled;t.push({name:"Trading",status:c?"ok":"skip",detail:c?"enabled":"disabled (sf setup --enable-trading)"});if(e?.json){console.log(JSON.stringify({checks:t,timestamp:(new Date).toISOString()},null,2));return}console.log();for(const e of t){const t=e.status==="ok"?`${s.c.green}ok${s.c.reset}`:e.status==="fail"?`${s.c.red}!!${s.c.reset}`:`${s.c.dim}--${s.c.reset}`;const n=e.ms?` ${s.c.dim}${e.ms}ms${s.c.reset}`:"";console.log(` ${e.name.padEnd(14)} ${t} ${e.detail}${n}`)}console.log()}},40239:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.registerStrategies=registerStrategies;const s=n(19218);const o={active:"[32m",watching:"[33m",executed:"[36m",cancelled:"[90m",review:"[31m"};const i="[0m";const r="[2m";const a="[1m";function formatStrategy(e,t=false){const n=o[e.status]||"";const s=[];const 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=[];if(e.entryBelow!=null)l.push(`ask ≤ ${e.entryBelow}¢`);if(e.entryAbove!=null)l.push(`ask ≥ ${e.entryAbove}¢`);const d=e.stopLoss!=null?`Stop: ${e.stopLoss}¢`:"";const u=e.takeProfit!=null?`TP: ${e.takeProfit}¢`:"";const p=`Max: ${e.maxQuantity||500}`;const h=`Filled: ${e.executedQuantity||0}/${e.maxQuantity||500}`;const m=[l.length>0?`Entry: ${l.join(", ")}`:null,d||null,u||null,p,h].filter(Boolean).join(" | ");s.push(` ${m}`);if(e.softConditions){s.push(` ${r}Soft: ${e.softConditions}${i}`)}if(e.status==="review"){s.push(` [31m⚠️ Needs review${i}`)}if(e.rationale){const t=e.rationale.length>120?e.rationale.slice(0,117)+"...":e.rationale;s.push(` ${r}${t}${i}`)}const f=e.createdBy||"user";const g=e.createdAt?new Date(e.createdAt).toLocaleDateString("en-US",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}):"";s.push(` ${r}created by ${f} · ${g}${i}`);return s.join("\n")}function registerStrategies(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=t?.all?"":t?.status||"active";const o=s?`/api/thesis/${e}/strategies?status=${s}`:`/api/thesis/${e}/strategies`;const a=await n.getStrategies(e,t?.all?undefined:t?.status||"active");const c=a.strategies||[];if(c.length===0){console.log(`\n No strategies found for thesis ${e}`);if(!t?.all&&!t?.status){console.log(` ${r}Try --all to see all statuses${i}`)}console.log();return}console.log(`\n Strategies for ${e}\n`);for(const e of c){console.log(formatStrategy(e));console.log()}}else{const{theses:e}=await n.listTheses();let s=0;for(const o of e){const e=t?.all?undefined:t?.status||"active";const c=await n.getStrategies(o.id,e);const l=c.strategies||[];if(l.length===0)continue;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(formatStrategy(e));console.log()}}if(s===0){console.log(`\n No strategies found`);if(!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)}}))}},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:true});t.telegramCommand=telegramCommand;const o=n(35317);const i=s(n(79896));const r=s(n(16928));const a=s(n(70857));const c=n(11627);const l=r.default.join(a.default.homedir(),".sf","telegram.pid");const d=r.default.join(a.default.homedir(),".sf","telegram.log");function readPid(){try{const e=parseInt(i.default.readFileSync(l,"utf-8").trim());if(isNaN(e))return null;try{process.kill(e,0);return e}catch{return null}}catch{return null}}function resolveToken(e){const t=(0,c.loadConfig)();if(e){const t=(0,c.loadFileConfig)();if(t.telegramBotToken!==e){(0,c.saveConfig)({...t,telegramBotToken:e})}return e}return t.telegramBotToken||null}async function telegramCommand(e){if(e.stop){const e=readPid();if(e){process.kill(e,"SIGTERM");try{i.default.unlinkSync(l)}catch{}console.log(` Telegram bot stopped (PID ${e})`)}else{console.log(" No running Telegram bot found.")}return}if(e.status){const e=readPid();if(e){console.log(` Telegram bot running (PID ${e})`);console.log(` Log: ${d}`)}else{console.log(" Telegram bot not running.")}return}const t=resolveToken(e.token);if(!t){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");console.log(" The token will be saved to ~/.sf/config.json for future use.");return}if(e.daemon){const t=readPid();if(t){console.log(` Bot already running (PID ${t}). Use --stop first.`);return}const n=["telegram"];if(e.chatId)n.push("--chat-id",e.chatId);const s=process.argv[1];i.default.mkdirSync(r.default.dirname(l),{recursive:true});const a=i.default.openSync(d,"a");const c=(0,o.spawn)(process.execPath,[s,...n],{detached:true,stdio:["ignore",a,a],env:{...process.env}});c.unref();i.default.writeFileSync(l,String(c.pid));console.log(` Telegram bot started in background (PID ${c.pid})`);console.log(` Log: ${d}`);console.log(` Stop: sf telegram --stop`);return}const{startBot:s}=await Promise.all([n.e(830),n.e(278),n.e(12)]).then(n.bind(n,6012));await s({token:t,chatId:e.chatId?parseInt(e.chatId):undefined})}},34362:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.buyCommand=buyCommand;t.sellCommand=sellCommand;const s=n(96139);const o=n(11627);const i=n(99236);const r=n(79896);const a=n(16928);const c=n(70857);async function buyCommand(e,t,n){(0,o.requireTrading)();await executeOrder(e,t,"buy",n)}async function sellCommand(e,t,n){(0,o.requireTrading)();await executeOrder(e,t,"sell",n)}async function executeOrder(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):undefined;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(p!==undefined&&(p<1||p>99)){throw new Error("Price must be 1-99 cents.")}const h=((p||99)*l/100).toFixed(2);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: ${d==="yes"?i.c.green+"YES"+i.c.reset:i.c.red+"NO"+i.c.reset}`);console.log(` Quantity: ${l}`);console.log(` Type: ${u}`);if(p)console.log(` Price: ${p}¢`);console.log(` Max cost: $${h}`);console.log();if(!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}:{}});const o=t.order||t;console.log();console.log(` ${i.c.green}✓${i.c.reset} Order placed: ${o.order_id||"OK"}`);if(o.status)console.log(` Status: ${o.status}`);if(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");if(!(0,r.existsSync)(t))(0,r.mkdirSync)(t,{recursive:true});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);if(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`)}else{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:true});t.updateCommand=updateCommand;const s=n(35317);const o="@spfunctions/cli";function detectPackageManager(){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{const e=(0,s.execSync)("pnpm list -g --depth=0 2>/dev/null",{encoding:"utf-8"});if(e.includes(o))return"pnpm"}catch{}try{const e=(0,s.execSync)("yarn global list --depth=0 2>/dev/null",{encoding:"utf-8"});if(e.includes(o))return"yarn"}catch{}return"npm"}async function updateCommand(){console.log(" Checking for updates...");try{const e=await fetch(`https://registry.npmjs.org/${o}/latest`);if(!e.ok){console.error(" Failed to check npm registry.");return}const t=await e.json();const i=t.version;const{join:r}=await Promise.resolve().then(n.t.bind(n,16928,23));const{readFileSync:a,existsSync:c}=await Promise.resolve().then(n.t.bind(n,79896,23));let l="0.0.0";try{const e=r(__dirname,"..","package.json");if(c(e))l=JSON.parse(a(e,"utf-8")).version}catch{}if(l===i){console.log(` Already on latest version (${l}).`);return}const d=detectPackageManager();const u=d==="pnpm"?`pnpm add -g ${o}@latest`:d==="yarn"?`yarn global add ${o}@latest`:`npm install -g ${o}@latest`;console.log(` ${l} → ${i}`);console.log(` Running: ${u}\n`);(0,s.execSync)(u,{stdio:"inherit"});console.log(`\n [32m✓ Updated to ${i}[39m`)}catch(e){console.error(` Update failed: ${e.message}`);console.error(` Try manually: npm install -g ${o}@latest`)}}},96007:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.watchCommand=watchCommand;const s=n(99236);const o=n(96139);const i=process.env.SF_API_URL||"https://simplefunctions.dev";async function watchCommand(e,t,n){const o=parseMode(t);const i=parseInt(n.interval||(o==="orderbook"?"30":"60"));const r=i*1e3;const a=n.json||false;if(!a){const t=o==="price"?"":` [${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()}process.on("SIGINT",(()=>{if(!a)console.log(`\n ${s.c.dim}Watch stopped.${s.c.reset}\n`);process.exit(0)}));switch(o){case"orderbook":await watchOrderbook(e,r,a);break;case"flow":await watchFlow(e,r,a);break;case"cross-venue":await watchCrossVenue(e,r,a);break;case"all":await watchAll(e,r,a);break;default:await watchPrice(e,r,a)}}function parseMode(e){if(!e)return"price";const t=e.toLowerCase();if(t==="orderbook"||t==="ob")return"orderbook";if(t==="flow")return"flow";if(t==="cross-venue"||t==="xv"||t==="cross")return"cross-venue";if(t==="all")return"all";return"price"}async function watchPrice(e,t,n){let o=(new Date).toISOString();try{const t=new Date(Date.now()-60*60*1e3).toISOString();const i=await fetchChanges(t,e);if(i.length>0){if(!n)console.log(` ${s.c.dim}${ts()} Recent changes (last hour):${s.c.reset}`);const e=dedupeByTitle(i);for(const t of e){if(n)console.log(JSON.stringify(t));else printChange(t)}o=i[0].detectedAt}else if(!n){console.log(` ${s.c.dim}${ts()} No recent changes. Watching...${s.c.reset}`)}}catch(e){if(!n)console.error(` ${s.c.dim}${ts()} Error: ${e.message}${s.c.reset}`)}while(true){await sleep(t);try{const t=await fetchChanges(o,e);const i=n?t:dedupeByTitle(t);for(const e of i){if(n)console.log(JSON.stringify(e));else printChange(e)}if(t.length>0){o=t[0].detectedAt}else if(!n){process.stdout.write(` ${s.c.dim}${ts()} · no new changes${s.c.reset}\r`)}}catch(e){if(!n)console.error(` ${s.c.dim}${ts()} Error: ${e.message}${s.c.reset}`)}}}async function watchOrderbook(e,t,n){if(!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 discoverTickers(e);if(i.length===0){console.error(` ${s.c.dim}No Kalshi markets found for "${e}"${s.c.reset}`);process.exit(1)}if(!n){console.log(` ${s.c.dim}Tracking ${i.length} market(s)${s.c.reset}`);console.log()}let r=new Map;while(true){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||[];const c=i.no_dollars||[];const l=a.length>0?Math.round(parseFloat(a[0][0])*100):0;const d=c.length>0?100-Math.round(parseFloat(c[0][0])*100):100;const u=d-l;const p=a.slice(0,3).reduce(((e,t)=>e+parseFloat(t[1])),0);const h=c.slice(0,3).reduce(((e,t)=>e+parseFloat(t[1])),0);const m={ticker:e,title:t,bestBid:l,bestAsk:d,spread:u,bidDepth:p,askDepth:h};const f=r.get(e);if(n){console.log(JSON.stringify({type:"orderbook",ts:(new Date).toISOString(),...m}))}else{const t=u<=2?`${s.c.green}HIGH${s.c.reset}`:u<=5?`${s.c.yellow}MED${s.c.reset}`:`${s.c.red}LOW${s.c.reset}`;let n="";if(f){const e=p-f.bidDepth;const t=h-f.askDepth;if(Math.abs(e)>50||Math.abs(t)>50){const o=e>0?"+":"";const i=t>0?"+":"";n=` ${s.c.dim}depth: bids ${o}${Math.round(e)}, asks ${i}${Math.round(t)}${s.c.reset}`}}console.log(` ${ts()} ${s.c.bold}${e.slice(0,30)}${s.c.reset} bid ${l}c (${Math.round(p)}) | ask ${d}c (${Math.round(h)}) spread ${u}c [${t}]${n}`)}r.set(e,m)}catch{}}await sleep(t)}}async function watchFlow(e,t,n){let o=new Date(Date.now()-2*60*60*1e3).toISOString();const i=new Map;while(true){try{const t=await fetchChanges(o,e);for(const e of t){if(e.changeType!=="price_move")continue;let t=i.get(e.ticker);if(!t){t={ticker:e.ticker,recentDeltas:[],lastPrice:e.afterPrice||0};i.set(e.ticker,t)}t.recentDeltas.push(e.delta||0);if(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));const i=o.every((e=>e<0));if(t||i){const i=o.reduce(((e,t)=>e+Math.abs(t)),0);const r=t?"UP":"DOWN";const a=t?s.c.green:s.c.red;if(n){console.log(JSON.stringify({type:"momentum",ticker:e.ticker,direction:r,totalDelta:i,moves:o.length}))}else{console.log(` ${ts()} ${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];const i=t.recentDeltas[t.recentDeltas.length-1];if(o&&i&&Math.sign(o)!==Math.sign(i)&&Math.abs(i)>=5){if(n){console.log(JSON.stringify({type:"reversal",ticker:e.ticker,previousDelta:o,currentDelta:i}))}else{console.log(` ${ts()} ${s.c.yellow}REVERSAL${s.c.reset} ${e.ticker} was ${o>0?"+":""}${o}c, now ${i>0?"+":""}${i}c`)}}}}if(t.length>0)o=t[0].detectedAt;else if(!n)process.stdout.write(` ${s.c.dim}${ts()} · monitoring flow${s.c.reset}\r`)}catch(e){if(!n)console.error(` ${s.c.dim}${ts()} Error: ${e.message}${s.c.reset}`)}await sleep(t)}}async function watchCrossVenue(e,t,n){if(!n){console.log(` ${s.c.dim}Fetching cross-venue data from scan...${s.c.reset}`)}let o=new Date(Date.now()-2*60*60*1e3).toISOString();const i=new Map;while(true){try{const t=await fetchChanges(o,e);for(const e of t){if(e.changeType!=="price_move")continue;const t=e.title.toLowerCase().slice(0,50);let o=i.get(t);if(!o)o={kalshi:0,poly:0};if(e.venue==="kalshi")o.kalshi=e.afterPrice||0;else if(e.venue==="polymarket")o.poly=e.afterPrice||0;i.set(t,o);if(o.kalshi>0&&o.poly>0){const t=Math.abs(o.kalshi-o.poly);const 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(` ${ts()} ${n}SPREAD${s.c.reset} ${e.title.slice(0,45)} K:${o.kalshi}c P:${o.poly}c gap ${t}c (${i} higher)`)}}}}if(t.length>0)o=t[0].detectedAt;else if(!n)process.stdout.write(` ${s.c.dim}${ts()} · tracking cross-venue${s.c.reset}\r`)}catch(e){if(!n)console.error(` ${s.c.dim}${ts()} Error: ${e.message}${s.c.reset}`)}await sleep(t)}}async function watchAll(e,t,n){let o=new Date(Date.now()-60*60*1e3).toISOString();const i=new Map;const r=new Map;while(true){try{const t=await fetchChanges(o,e);for(const e of t){if(n){console.log(JSON.stringify(e))}else{printChange(e)}if(e.changeType!=="price_move")continue;let t=i.get(e.ticker);if(!t){t={ticker:e.ticker,recentDeltas:[],lastPrice:e.afterPrice||0};i.set(e.ticker,t)}t.recentDeltas.push(e.delta||0);if(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";const t=o.reduce(((e,t)=>e+Math.abs(t)),0);if(!n){const n=e==="UP"?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(e.venue==="kalshi")c.kalshi=e.afterPrice||0;else if(e.venue==="polymarket")c.poly=e.afterPrice||0;r.set(a,c);if(c.kalshi>0&&c.poly>0){const e=Math.abs(c.kalshi-c.poly);if(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`)}}}if(t.length>0)o=t[0].detectedAt;else if(!n)process.stdout.write(` ${s.c.dim}${ts()} · watching all${s.c.reset}\r`)}catch(e){if(!n)console.error(` ${s.c.dim}${ts()} Error: ${e.message}${s.c.reset}`)}await sleep(t)}}async function discoverTickers(e){try{const t=await fetch(`${i}/api/public/scan?q=${encodeURIComponent(e)}&limit=20`);if(!t.ok)return[];const n=await t.json();const s=n.results||n.markets||[];return s.filter((e=>e.ticker&&e.venue==="kalshi")).slice(0,5).map((e=>({ticker:e.ticker,title:e.title||e.ticker})))}catch{return[]}}function dedupeByTitle(e){const t=new Map;for(const n of e){const e=`${n.changeType}:${n.title}`;const s=t.get(e);if(s)s.count++;else t.set(e,{count:1,representative:n})}return Array.from(t.values()).map((({count:e,representative:t})=>{if(e>1)return{...t,title:`${t.title} (${e} contracts)`};return t}))}async function fetchChanges(e,t){let n=`${i}/api/changes?since=${encodeURIComponent(e)}&limit=50`;if(t)n+=`&q=${encodeURIComponent(t)}`;const s=await fetch(n);if(!s.ok)return[];const o=await s.json();return o.changes||[]}function printChange(e){const t=ts();const n=e.venue==="kalshi"?`${s.c.cyan}K${s.c.reset}`:e.venue==="polymarket"?`[35mP[39m`:e.venue==="traditional"?`${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(e.venue==="traditional"){const o=(e.delta||0)>0?"+":"";const i=(e.delta||0)>0?s.c.green:s.c.red;const r=((e.beforePrice||0)/100).toFixed(0);const 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?"+":"";const 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}`)}break}}}function ts(){return(new Date).toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"})}function sleep(e){return new Promise((t=>setTimeout(t,e)))}},18691:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.whatifCommand=whatifCommand;const s=n(19218);const o=n(96139);const i=n(99236);function simulateWhatIf(e,t){const n=[];function flatten(e){for(const t of e){n.push(t);if(t.children?.length)flatten(t.children)}}const s=e.causalTree?.nodes||[];flatten(s);const o=s.filter((e=>e.depth===0||e.depth===undefined&&!e.id.includes(".")));const i=new Map(t.map((e=>[e.nodeId,e.newProbability])));const r=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}}));const a=o.reduce(((e,t)=>e+(t.probability||0)*(t.importance||0)),0);const c=o.reduce(((e,t)=>{const n=i.get(t.id)??t.probability??0;return e+n*(t.importance||0)}),0);const l=new Map;for(const[e,t]of i.entries()){const s=n.find((t=>t.id===e));if(s&&s.probability>0){l.set(e,Math.max(0,Math.min(2,t/s.probability)))}}const d=(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(l.has(t)){n=l.get(t);break}}}const s=e.marketPrice||0;const o=e.thesisPrice||e.thesisImpliedPrice||s;const i=e.edge||e.edgeSize||0;const r=o-s;const a=Math.round((s+r*n)*100)/100;const c=e.direction||"yes";const d=Math.round((c==="yes"?a-s:s-a)*100)/100;const u=Math.round((d-i)*100)/100;let p="unchanged";if(Math.abs(u)<1)p="unchanged";else if(i>0&&d<0||i<0&&d>0)p="reversed";else if(Math.abs(d)<2)p="gone";else if(Math.abs(d)<Math.abs(i))p="reduced";return{marketId:e.marketId,market:e.market||e.marketTitle||e.marketId,venue:e.venue,direction:c,marketPrice:s,oldThesisPrice:o,newThesisPrice:a,oldEdge:i,newEdge:d,delta:u,signal:p,relatedNodeId:t}}));d.sort(((e,t)=>Math.abs(t.delta)-Math.abs(e.delta)));return{overrides:r,oldConfidence:a,newConfidence:c,confidenceDelta:Math.round((c-a)*100)/100,edges:d}}async function whatifCommand(e,t){if(!t.set||t.set.length===0){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}}));const r=new s.SFClient(t.apiKey,t.apiUrl);const a=await r.getContext(e);const c=simulateWhatIf(a,n);if(t.json){console.log(JSON.stringify(c,null,2));return}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(e.oldProb*100);const n=Math.round(e.newProb*100);const 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(c.oldConfidence*100);const d=Math.round(c.newConfidence*100);const u=c.confidenceDelta>0?"+":"";const 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(c.confidenceDelta*100)}${i.c.reset})`);console.log();const h=c.edges.filter((e=>e.signal!=="unchanged"));if(h.length===0){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);const n=`${Math.round(e.marketPrice)}¢`.padEnd(6);const s=`${e.oldEdge>0?"+":""}${Math.round(e.oldEdge)}`.padEnd(8);const 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])));const n=e.filter((e=>{const n=t.get(e.ticker);return n&&(n.signal==="reversed"||n.signal==="gone")}));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);const s=await(0,o.getMarketPrice)(e.ticker);const r=s!==null?((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()}},33192:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.worldCommand=worldCommand;const s=n(99236);async function worldCommand(e){const t=process.env.SF_API_URL||"https://simplefunctions.dev";if(e.delta){const n=e.since||"1h";const o=await fetch(`${t}/api/agent/world/delta?since=${encodeURIComponent(n)}`);if(!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)}`:"";const o=await fetch(`${t}/api/agent/world${n}`);if(!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()}}},84436:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.xSearchCommand=xSearchCommand;t.xVolumeCommand=xVolumeCommand;t.xNewsCommand=xNewsCommand;t.xAccountCommand=xAccountCommand;const n=process.env.SF_API_URL||"https://simplefunctions.dev";function getApiKey(){const e=process.env.SF_API_KEY||"";if(!e){console.error(" API key required. Run: sf setup");process.exit(1)}return e}async function apiFetch(e){const t=await fetch(`${n}${e}`,{headers:{Authorization:`Bearer ${getApiKey()}`}});if(!t.ok){const e=await t.text();throw new Error(`${t.status}: ${e}`)}return t.json()}async function xSearchCommand(e,t){const n=t?.raw?"raw":"summary";const s=t?.hours||"24";const o=t?.limit||"20";const i=await apiFetch(`/api/x/search?q=${encodeURIComponent(e)}&mode=${n}&hours=${s}&limit=${o}`);if(t?.json){console.log(JSON.stringify(i,null,2));return}if(i.summary){console.log(`\n [1m[36mX: ${e}[0m\n`);console.log(` ${i.summary}\n`);if(i.sentiment){const e={bullish:"[32m",bearish:"[31m",mixed:"[33m",neutral:"[2m"};console.log(` Sentiment: ${e[i.sentiment]||""}${i.sentiment}[0m`)}if(i.keyThemes?.length){console.log(` Themes: ${i.keyThemes.join(", ")}`)}console.log()}const r=i.posts||[];if(r.length>0){console.log(` [1mTop posts[22m (${r.length})\n`);for(const e of r.slice(0,10)){const t=e.metrics?.likes||0;const n=e.metrics?.retweets||0;const s=e.authorFollowers?` (${formatNum(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(i.volume){const e=i.volume;const t=e.velocityChange>1?`[32m+${Math.round((e.velocityChange-1)*100)}%[0m`:`[31m${Math.round((e.velocityChange-1)*100)}%[0m`;console.log(` [2mVolume: ${formatNum(e.totalCount)} posts (${s}h) | Velocity: ${t} | Peak: ${e.peak?.count}[0m\n`)}const a=i.news||[];if(a.length>0){console.log(` [1mX News[22m (${a.length})\n`);for(const e of a.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`)}}}async function xVolumeCommand(e,t){const n=t?.hours||"72";const s=t?.granularity||"hour";const o=await apiFetch(`/api/x/volume?q=${encodeURIComponent(e)}&hours=${n}&granularity=${s}`);if(t?.json){console.log(JSON.stringify(o,null,2));return}console.log(`\n [1m[36mX Volume: ${e}[0m\n`);console.log(` Total: ${formatNum(o.totalCount)} posts (${n}h)`);const i=o.velocityChange>1?`[32m+${Math.round((o.velocityChange-1)*100)}%[0m`:`[31m${Math.round((o.velocityChange-1)*100)}%[0m`;console.log(` Velocity: ${i}`);console.log(` Peak: ${o.peak?.count} at ${o.peak?.time?.slice(11,16)||"?"}\n`);const r=o.timeseries||[];if(r.length>0){const e=Math.max(...r.map((e=>e.count)));const t=40;for(const n of r.slice(-24)){const s=(n.time||"").slice(11,16)||"?";const o=e>0?Math.round(n.count/e*t):0;const i="▓".repeat(o);const r=String(n.count).padStart(6);console.log(` ${s} ${r} ${i}`)}}console.log()}async function xNewsCommand(e,t){const n=t?.limit||"10";const s=await apiFetch(`/api/x/news?q=${encodeURIComponent(e)}&limit=${n}`);if(t?.json){console.log(JSON.stringify(s,null,2));return}const o=s.stories||[];console.log(`\n [1m[36mX News: ${e}[0m (${o.length} stories)\n`);for(const e of o){const t=e.tickers?.length?` [33m${e.tickers.join(" ")}[0m`:"";const 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()}}async function xAccountCommand(e,t){const n=e.replace(/^@/,"");const s=t?.hours||"24";const o=t?.limit||"20";const i=await apiFetch(`/api/x/account?username=${n}&hours=${s}&limit=${o}`);if(t?.json){console.log(JSON.stringify(i,null,2));return}const r=i.posts||[];console.log(`\n [1m[36m@${n}[0m (${r.length} posts, last ${s}h)\n`);for(const e of r){const t=e.metrics?.likes||0;const n=e.metrics?.retweets||0;const 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`)}}function formatNum(e){if(e>=1e6)return`${(e/1e6).toFixed(1)}M`;if(e>=1e3)return`${(e/1e3).toFixed(1)}K`;return 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:true});t.loadFileConfig=loadFileConfig;t.loadConfig=loadConfig;t.saveConfig=saveConfig;t.resetConfig=resetConfig;t.applyConfig=applyConfig;t.isConfigured=isConfigured;t.requireTrading=requireTrading;t.getConfigPath=getConfigPath;const o=s(n(79896));const i=s(n(16928));const r=s(n(70857));const a=i.default.join(r.default.homedir(),".sf");const c=i.default.join(a,"config.json");const l="https://simplefunctions.dev";const d="anthropic/claude-sonnet-4.6";function loadFileConfig(){try{if(o.default.existsSync(c)){return JSON.parse(o.default.readFileSync(c,"utf-8"))}}catch{}return{}}function loadConfig(){const e=loadFileConfig();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||false,telegramBotToken:process.env.TELEGRAM_BOT_TOKEN||e.telegramBotToken}}function saveConfig(e){o.default.mkdirSync(a,{recursive:true});o.default.writeFileSync(c,JSON.stringify({...e,configuredAt:(new Date).toISOString()},null,2))}function resetConfig(){try{if(o.default.existsSync(c)){o.default.unlinkSync(c)}}catch{}}function applyConfig(){const e=loadFileConfig();if(!process.env.SF_API_KEY&&e.apiKey){process.env.SF_API_KEY=e.apiKey}if(!process.env.SF_API_URL&&e.apiUrl){process.env.SF_API_URL=e.apiUrl}if(!process.env.OPENROUTER_API_KEY&&e.openrouterKey){process.env.OPENROUTER_API_KEY=e.openrouterKey}if(!process.env.KALSHI_API_KEY_ID&&e.kalshiKeyId){process.env.KALSHI_API_KEY_ID=e.kalshiKeyId}if(!process.env.KALSHI_PRIVATE_KEY_PATH&&e.kalshiPrivateKeyPath){process.env.KALSHI_PRIVATE_KEY_PATH=e.kalshiPrivateKeyPath}if(!process.env.POLYMARKET_WALLET_ADDRESS&&e.polymarketWalletAddress){process.env.POLYMARKET_WALLET_ADDRESS=e.polymarketWalletAddress}if(!process.env.POLYMARKET_PRIVATE_KEY_PATH&&e.polymarketPrivateKeyPath){process.env.POLYMARKET_PRIVATE_KEY_PATH=e.polymarketPrivateKeyPath}if(!process.env.TAVILY_API_KEY&&e.tavilyKey){process.env.TAVILY_API_KEY=e.tavilyKey}if(!process.env.SF_MODEL&&e.model){process.env.SF_MODEL=e.model}}function isConfigured(){const e=loadConfig();return!!e.apiKey}function requireTrading(){const e=loadConfig();if(!e.tradingEnabled){console.error("\n Trading is disabled. Run: sf setup --enable-trading\n");process.exit(1)}if(!e.kalshiKeyId&&!process.env.KALSHI_API_KEY_ID){console.error("\n Kalshi API key not configured. Run: sf setup --kalshi\n");process.exit(1)}}function getConfigPath(){return c}},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:true});t.isKalshiConfigured=isKalshiConfigured;t.getPositions=getPositions;t.kalshiPriceCents=kalshiPriceCents;t.getMarketPrice=getMarketPrice;t.getOrderbook=getOrderbook;t.getPublicOrderbook=getPublicOrderbook;t.getSettlements=getSettlements;t.getBalance=getBalance;t.getOrders=getOrders;t.getFills=getFills;t.getForecastHistory=getForecastHistory;t.getExchangeAnnouncements=getExchangeAnnouncements;t.getHistoricalMarket=getHistoricalMarket;t.createOrder=createOrder;t.cancelOrder=cancelOrder;t.batchCancelOrders=batchCancelOrders;t.amendOrder=amendOrder;t.getBatchCandlesticks=getBatchCandlesticks;t.createRFQ=createRFQ;const o=s(n(79896));const i=s(n(16928));const r=s(n(76982));const a="https://api.elections.kalshi.com/trade-api/v2";function isKalshiConfigured(){return!!(process.env.KALSHI_API_KEY_ID&&process.env.KALSHI_PRIVATE_KEY_PATH)}function loadPrivateKey(){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){console.warn(`[Kalshi] Failed to load private key from ${t}:`,e);return null}}function signRequest(e,t,n){const s=process.env.KALSHI_API_KEY_ID;const o=Date.now().toString();const i=o+e.toUpperCase()+t;const a=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});return{headers:{"KALSHI-ACCESS-KEY":s,"KALSHI-ACCESS-SIGNATURE":a.toString("base64"),"KALSHI-ACCESS-TIMESTAMP":o,"Content-Type":"application/json",Accept:"application/json"}}}async function kalshiAuthGet(e){const t=loadPrivateKey();if(!t){throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.")}const n=`${a}${e}`;const s=e.split("?")[0];const{headers:o}=signRequest("GET",`/trade-api/v2${s}`,t);const 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 kalshiAuthPost(e,t){const n=loadPrivateKey();if(!n){throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.")}const s=`${a}${e}`;const o=e.split("?")[0];const{headers:i}=signRequest("POST",`/trade-api/v2${o}`,n);const 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()}async function kalshiAuthDelete(e){const t=loadPrivateKey();if(!t){throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.")}const n=`${a}${e}`;const s=e.split("?")[0];const{headers:o}=signRequest("DELETE",`/trade-api/v2${s}`,t);const 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{}}async function getPositions(){if(!isKalshiConfigured())return null;try{const e=await kalshiAuthGet("/portfolio/positions");const t=e.market_positions||e.positions||[];return t.map((e=>{const t=parseFloat(e.position_fp||"0");const n=parseFloat(e.total_traded_dollars||"0");const s=Math.abs(t);const o=t>=0?"yes":"no";const 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(parseFloat(e.realized_pnl||"0")*100),unrealized_pnl:0,total_cost:Math.round(n*100)}}))}catch(e){console.warn(`[Kalshi] Failed to fetch positions:`,e);return null}}function kalshiPriceCents(e){if(e.last_price_dollars){const t=parseFloat(e.last_price_dollars);if(!isNaN(t)&&t>0)return Math.round(t*100)}if(e.yes_bid_dollars){const t=parseFloat(e.yes_bid_dollars);if(!isNaN(t)&&t>0)return Math.round(t*100)}if(e.yes_ask_dollars){const t=parseFloat(e.yes_ask_dollars);if(!isNaN(t)&&t>0)return Math.round(t*100)}if(e.last_price!=null&&e.last_price>0)return e.last_price;if(e.yes_bid!=null&&e.yes_bid>0)return e.yes_bid;return 50}async function getMarketPrice(e){try{const t=`https://api.elections.kalshi.com/trade-api/v2/markets/${e}`;const n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)return null;const s=await n.json();const o=s.market||s;const i=kalshiPriceCents(o);return i===50&&!o.last_price_dollars&&!o.yes_bid_dollars?null:i}catch{return null}}async function getOrderbook(e){if(!isKalshiConfigured())return null;try{const t=await kalshiAuthGet(`/markets/${e}/orderbook`);const n=t.orderbook_fp||t.orderbook;if(!n)return null;const s=n.yes_dollars||n.yes||[];const o=n.no_dollars||n.no||[];const i=!!(n.yes_dollars||n.no_dollars);const r=s.map((e=>({price:i?Math.round(parseFloat(e[0])*100):Number(e[0]),qty:parseFloat(e[1])}))).filter((e=>e.price>0));const a=o.map((e=>({price:i?Math.round(parseFloat(e[0])*100):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;const l=a.length>0?100-a[0].price:100;const d=l-c;const u=r.slice(0,3).reduce(((e,t)=>e+t.qty),0);const p=a.slice(0,3).reduce(((e,t)=>e+t.qty),0);const h=Math.min(u,p);let m="low";if(d<=2&&h>=500)m="high";else if(d<=5&&h>=100)m="medium";return{bestBid:c,bestAsk:l,spread:d,bidDepth:u,askDepth:p,liquidityScore:m}}catch{return null}}async function getPublicOrderbook(e,t=20){try{const n=`${a}/markets/${e}/orderbook?depth=${t}`;const s=await fetch(n,{headers:{Accept:"application/json"}});if(!s.ok)return null;const o=await s.json();const 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}}async function getSettlements(e){if(!isKalshiConfigured())return null;try{const t=new URLSearchParams;if(e?.limit)t.set("limit",e.limit.toString());if(e?.cursor)t.set("cursor",e.cursor);if(e?.ticker)t.set("ticker",e.ticker);const n=await kalshiAuthGet(`/portfolio/settlements?${t.toString()}`);return{settlements:n.settlements||[],cursor:n.cursor||""}}catch(e){console.warn("[Kalshi] Failed to fetch settlements:",e);return null}}async function getBalance(){if(!isKalshiConfigured())return null;try{const e=await kalshiAuthGet("/portfolio/balance");const t=(e.balance||0)/100;const n=(e.portfolio_value||0)/100;return{balance:t,portfolioValue:n}}catch(e){console.warn("[Kalshi] Failed to fetch balance:",e);return null}}async function getOrders(e){if(!isKalshiConfigured())return null;try{const t=new URLSearchParams;if(e?.status)t.set("status",e.status);if(e?.ticker)t.set("ticker",e.ticker);if(e?.limit)t.set("limit",e.limit.toString());if(e?.cursor)t.set("cursor",e.cursor);const n=await kalshiAuthGet(`/portfolio/orders?${t.toString()}`);return{orders:n.orders||[],cursor:n.cursor||""}}catch(e){console.warn("[Kalshi] Failed to fetch orders:",e);return null}}async function getFills(e){if(!isKalshiConfigured())return null;try{const t=new URLSearchParams;if(e?.ticker)t.set("ticker",e.ticker);if(e?.limit)t.set("limit",e.limit.toString());if(e?.cursor)t.set("cursor",e.cursor);const n=await kalshiAuthGet(`/portfolio/fills?${t.toString()}`);return{fills:n.fills||[],cursor:n.cursor||""}}catch(e){console.warn("[Kalshi] Failed to fetch fills:",e);return null}}async function getForecastHistory(e){if(!isKalshiConfigured())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);const 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()}`;const i=await kalshiAuthGet(o);return i.forecast_history||[]}catch(e){console.warn("[Kalshi] Failed to fetch forecast:",e);return null}}async function getExchangeAnnouncements(){try{const e=await fetch(`${a}/exchange/announcements`,{headers:{Accept:"application/json"}});if(!e.ok)return[];const t=await e.json();return t.announcements||[]}catch{return[]}}async function getHistoricalMarket(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}}async function createOrder(e){return kalshiAuthPost("/portfolio/orders",e)}async function cancelOrder(e){await kalshiAuthDelete(`/portfolio/orders/${e}`)}async function batchCancelOrders(e){await kalshiAuthPost("/portfolio/orders/batched",{orders:e.map((e=>({action:"cancel",order_id:e})))})}async function amendOrder(e,t){const n=loadPrivateKey();if(!n)throw new Error("Kalshi private key not loaded.");const s=`/portfolio/orders/${e}`;const o=`${a}${s}`;const{headers:i}=signRequest("PATCH",`/trade-api/v2${s}`,n);const 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()}async function getBatchCandlesticks(e){if(!isKalshiConfigured())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());const n=await kalshiAuthGet(`/markets/candlesticks?${t.toString()}`);return n.markets||[]}catch(e){console.warn("[Kalshi] Failed to fetch candlesticks:",e);return[]}}async function createRFQ(e){return kalshiAuthPost("/communications/rfqs",e)}},34331:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.polymarketSearch=polymarketSearch;t.polymarketListEvents=polymarketListEvents;t.polymarketGetEvent=polymarketGetEvent;t.polymarketGetMarket=polymarketGetMarket;t.polymarketListTags=polymarketListTags;t.polymarketGetOrderbook=polymarketGetOrderbook;t.computeOrderbookDepth=computeOrderbookDepth;t.polymarketGetOrderbookWithDepth=polymarketGetOrderbookWithDepth;t.polymarketGetMidpoint=polymarketGetMidpoint;t.polymarketGetSpread=polymarketGetSpread;t.polymarketGetMidpoints=polymarketGetMidpoints;t.polymarketGetOHLC=polymarketGetOHLC;t.polymarketGetPriceHistory=polymarketGetPriceHistory;t.polymarketGetPositions=polymarketGetPositions;t.polymarketGetClosedPositions=polymarketGetClosedPositions;t.scoreLiquidity=scoreLiquidity;t.parseClobTokenIds=parseClobTokenIds;t.parseOutcomes=parseOutcomes;t.parseOutcomePrices=parseOutcomePrices;t.toCents=toCents;t.polymarketUrl=polymarketUrl;const n="https://gamma-api.polymarket.com";const s="https://clob.polymarket.com";const o="https://data-api.polymarket.com";async function polymarketSearch(e,t=20){const s=new URLSearchParams({q:e,limit_per_type:t.toString()});const 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||[]}async function polymarketListEvents(e){const t=new URLSearchParams({active:"true",closed:"false",limit:(e?.limit||50).toString(),offset:(e?.offset||0).toString()});if(e?.order)t.set("order",e.order);if(e?.ascending!==undefined)t.set("ascending",String(e.ascending));if(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()}async function polymarketGetEvent(e){const t=await fetch(`${n}/events/${e}`);if(!t.ok)throw new Error(`Polymarket event error: ${t.status}`);return t.json()}async function polymarketGetMarket(e){const t=await fetch(`${n}/markets/${e}`);if(!t.ok)throw new Error(`Polymarket market error: ${t.status}`);return t.json()}async function polymarketListTags(){const e=await fetch(`${n}/tags`);if(!e.ok)throw new Error(`Polymarket tags error: ${e.status}`);return e.json()}async function polymarketGetOrderbook(e){try{const t=await fetch(`${s}/book?token_id=${e}`);if(!t.ok)return null;const n=await t.json();if(n.error)return null;return n}catch{return null}}function computeOrderbookDepth(e){const t=(e.bids||[]).map((e=>({price:parseFloat(e.price),size:parseFloat(e.size)}))).sort(((e,t)=>t.price-e.price));const n=(e.asks||[]).map((e=>({price:parseFloat(e.price),size:parseFloat(e.size)}))).sort(((e,t)=>e.price-t.price));const s=t.length>0?Math.round(t[0].price*100):0;const o=n.length>0?Math.round(n[0].price*100):100;const i=o-s;const r=t.slice(0,3).reduce(((e,t)=>e+t.size),0);const a=n.slice(0,3).reduce(((e,t)=>e+t.size),0);const c=t.reduce(((e,t)=>e+t.size),0);const l=n.reduce(((e,t)=>e+t.size),0);const d=scoreLiquidity(i,r+a);return{bestBid:s,bestAsk:o,spread:i,bidDepthTop3:Math.round(r),askDepthTop3:Math.round(a),totalBidDepth:Math.round(c),totalAskDepth:Math.round(l),liquidityScore:d,levels:{bids:e.bids,asks:e.asks}}}async function polymarketGetOrderbookWithDepth(e){const t=await polymarketGetOrderbook(e);if(!t)return null;return computeOrderbookDepth(t)}async function polymarketGetMidpoint(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}}async function polymarketGetSpread(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}}async function polymarketGetMidpoints(e){if(e.length===0)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()}async function polymarketGetOHLC(e){const t=new URLSearchParams({asset_id:e.tokenId,startTs:e.startTs.toString(),fidelity:e.fidelity||"1h"});if(e.endTs)t.set("endTs",e.endTs.toString());if(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||[]}async function polymarketGetPriceHistory(e){const t=new URLSearchParams({market:e.tokenId});if(e.interval)t.set("interval",e.interval);if(e.startTs)t.set("startTs",e.startTs.toString());if(e.endTs)t.set("endTs",e.endTs.toString());if(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||[]}async function polymarketGetPositions(e){const t=await fetch(`${o}/positions?user=${e}`);if(!t.ok)return[];const n=await t.json();return Array.isArray(n)?n:[]}async function polymarketGetClosedPositions(e){const t=await fetch(`${o}/closed-positions?user=${e}`);if(!t.ok)return[];const n=await t.json();return Array.isArray(n)?n:[]}function scoreLiquidity(e,t){if(e<=2&&t>=500)return"high";if(e<=5&&t>=100)return"medium";return"low"}function parseClobTokenIds(e){try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length>=2)return[t[0],t[1]];return null}catch{return null}}function parseOutcomes(e){try{return JSON.parse(e)}catch{return[]}}function parseOutcomePrices(e){try{return JSON.parse(e)}catch{return[]}}function toCents(e){return Math.round(e*100)}function polymarketUrl(e){return`https://polymarket.com/event/${e}`}},35178:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.shareOutput=shareOutput;const n=process.env.SF_API_URL||"https://simplefunctions.dev";async function shareOutput(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){console.error(`Share failed: ${o.status}`);return}const{url:i}=await o.json();console.log();console.log(` [36m${i}[39m`);console.log()}catch(e){console.error(`Share failed: ${e.message}`)}}},40101:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.loadSkills=loadSkills;const s=n(79896);const o=n(16928);function loadSkills(){const e=[];const t=__dirname;const n=t.includes("dist")?(0,o.join)(t,"../../src/skills"):t;let i=[];try{i=(0,s.readdirSync)(n).filter((e=>e.endsWith(".md")))}catch{return e}for(const t of i){try{const i=(0,s.readFileSync)((0,o.join)(n,t),"utf-8");const r=parseSkillFile(i);if(r)e.push(r)}catch{}}try{const t=process.env.HOME||process.env.USERPROFILE||"";const n=(0,o.join)(t,".sf","skills");const i=(0,s.readdirSync)(n).filter((e=>e.endsWith(".md")));for(const t of i){try{const i=(0,s.readFileSync)((0,o.join)(n,t),"utf-8");const r=parseSkillFile(i);if(r)e.push(r)}catch{}}}catch{}return e}function parseSkillFile(e){const t=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!t)return null;const n=t[1];const s=t[2].trim();const o={};for(const e of n.split("\n")){const t=e.match(/^(\w[\w_]*)\s*:\s*(.+)$/);if(t)o[t[1]]=t[2].trim()}if(!o.name||!o.trigger)return null;const i=s.match(/## Instructions\n([\s\S]*)$/i);const r=i?i[1].trim():s;const parseArray=e=>(e||"").replace(/[\[\]]/g,"").split(",").map((e=>e.trim())).filter(Boolean);return{name:o.name,trigger:o.trigger,description:o.description||"",author:o.author||"unknown",version:o.version||"1.0.0",category:o.category||"general",tags:parseArray(o.tags),toolsUsed:parseArray(o.tools_used),estimatedTime:o.estimated_time||"",auto:o.auto,prompt:r,raw:e}}},97325:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.RISK_CATEGORIES=t.TOPIC_SERIES=void 0;t.tickerToTopic=tickerToTopic;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"};function tickerToTopic(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"}},77096:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.CLR=t.bgRgb=t.rgb=void 0;t.drawBorder=drawBorder;t.drawHDivider=drawHDivider;t.fit=fit;t.sparkline=sparkline;t.compact=compact;const rgb=(e,t,n)=>`[38;2;${e};${t};${n}m`;t.rgb=rgb;const bgRgb=(e,t,n)=>`[48;2;${e};${t};${n}m`;t.bgRgb=bgRgb;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)};function drawBorder(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)}if(s){e.write(o,i+2,` ${s} `,t.CLR.dim)}}function drawHDivider(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)}}function fit(e,t,n="left"){if(e.length>t)return e.slice(0,t-1)+"…";if(n==="right")return e.padStart(t);return e.padEnd(t)}function sparkline(e,n){if(e.length===0)return[];const s=Math.min(...e);const o=Math.max(...e);const i=o-s||1;const r="▁▂▃▄▅▆▇█";return e.map((e=>{const o=Math.round((e-s)/i*7);return{text:r[o],fg:n?n(e):t.CLR.dim}}))}function compact(e){if(Math.abs(e)>=1e6)return`${(e/1e6).toFixed(1)}M`;if(Math.abs(e)>=1e4)return`${(e/1e3).toFixed(0)}k`;if(Math.abs(e)>=1e3)return`${(e/1e3).toFixed(1)}k`;return String(Math.round(e))}},14916:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.drawChart=drawChart;const s=n(77096);function drawChart(e,t,n,o,i,r,a){if(r.length===0||o<10||i<4)return;const c=8;const l=o-c-1;const d=i-2;if(l<4||d<2)return;const u=Math.min(...r);const p=Math.max(...r);const h=p-u||1;const m=[];for(let e=0;e<l;e++){const t=e/(l-1)*(r.length-1);const n=Math.floor(t);const s=Math.min(n+1,r.length-1);const o=t-n;m.push(r[n]*(1-o)+r[s]*o)}const f=n+c+1;const g=[{row:0,value:p},{row:d-1,value:u}];let y=-1;if(u<0&&p>0){y=Math.round(p/h*(d-1));if(y>0&&y<d-1){g.push({row:y,value:0})}}for(let o=0;o<d;o++){e.write(t+o,n+c,"│",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(c),s.CLR.dim)}if(y>=0&&y<d){for(let n=0;n<l;n++){e.write(t+y,f+n,"╌",s.CLR.veryDim)}}const $=" ▁▂▃▄▅▆▇█";for(let n=0;n<l;n++){const o=m[n];const i=(o-u)/h;const r=i*d*8;const a=o>=0?s.CLR.green:s.CLR.red;for(let s=d-1;s>=0;s--){const o=d-1-s;const i=r-o*8;if(i>=8){e.write(t+s,f+n,"█",a)}else if(i>0){const o=Math.round(Math.max(1,Math.min(i,8)));e.write(t+s,f+n,$[o],a)}}}const k=t+d;e.write(k,n+c,"└",s.CLR.borderDim);for(let t=0;t<l;t++){e.write(k,f+t,"─",s.CLR.borderDim)}if(a&&a.length>0){const i=t+d+1;const r=Math.min(a.length,6);for(let t=0;t<r;t++){const c=Math.round(t*(a.length-1)/Math.max(r-1,1));const d=f+Math.round(c*(l-1)/Math.max(a.length-1,1));const u=a[c]||"";if(d>=f&&d+u.length<n+o){e.write(i,d,u.slice(0,5),s.CLR.dim)}}}}},99844:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.loadAllData=loadAllData;t.startDashboard=startDashboard;const s=n(72222);const o=n(42992);const i=n(56661);const r=n(77096);const a=n(87783);const c=n(11627);const l=n(19218);const d=n(96139);const u=n(97325);const p=n(34331);const h=n(3322);const m=n(21704);const f=n(30012);const g=n(75757);const y=n(50511);const $=n(98573);const k=n(12423);const b=n(72734);const w=n(35301);const _=n(82950);const S=n(29405);const v=n(67748);const x=n(87009);const C=15e3;const O=3e4;const I=1e4;const P=3e4;const T=6e4;const E=6e4;let A=null;function getClient(){if(A)return A;try{const e=(0,c.loadConfig)();if(!e.apiKey)return null;A=new l.SFClient(e.apiKey,e.apiUrl);return A}catch{return null}}async function loadAllData(e){const t=getClient();const[n,s,o,i]=await Promise.allSettled([(0,a.cached)("positions",C,(()=>(0,d.getPositions)())),t?(0,a.cached)("theses",O,(()=>t.listTheses())):Promise.resolve(null),(0,a.cached)("orders",I,(()=>(0,d.getOrders)({status:"resting"}))),(0,a.cached)("balance",P,(()=>(0,d.getBalance)()))]);if(n.status==="fulfilled"&&n.value){const t=n.value;const 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];if(n.status==="fulfilled"&&n.value!=null){t[e].current_value=n.value;t[e].unrealized_pnl=Math.round((n.value-t[e].average_price_paid)*t[e].quantity)}}e.positions=t}const r=(0,c.loadConfig)();if(r.polymarketWalletAddress){try{const t=await(0,a.cached)("poly-positions",C,(()=>(0,p.polymarketGetPositions)(r.polymarketWalletAddress)));if(t&&Array.isArray(t)&&t.length>0){for(const n of t){e.positions.push({ticker:(n.title||n.slug||n.asset||"").slice(0,25),quantity:n.size||0,average_price_paid:Math.round((n.avgPrice||0)*100),current_value:Math.round((n.curPrice||n.currentPrice||0)*100),unrealized_pnl:Math.round((n.cashPnl||0)*100),side:(n.outcome||"yes").toLowerCase(),venue:"polymarket"})}}}catch{}}if(s.status==="fulfilled"&&s.value){const t=s.value;e.theses=t.theses||t||[]}if(o.status==="fulfilled"&&o.value){e.orders=o.value.orders||[]}if(i.status==="fulfilled"&&i.value){e.balance=i.value.balance??0}if(t&&e.theses.length>0){const n=await Promise.allSettled(e.theses.map((e=>(0,a.cached)(`ctx:${e.id}`,O,(()=>t.getContext(e.id))))));for(let t=0;t<e.theses.length;t++){const s=n[t];if(s.status==="fulfilled"&&s.value){e.contexts.set(e.theses[t].id,s.value)}}}computeEdges(e);await loadCandles(e);if(t){try{const n=await(0,a.cached)("feed",T,(()=>t.getFeed(48)));const s=n.entries||n.feed||n;if(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",O,(()=>fetch("https://simplefunctions.dev/api/public/markets").then((e=>e.ok?e.json():null))));if(t){if(Array.isArray(t)){e.traditionalMarkets=t}else if(typeof t==="object"){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{}collectEvents(e);checkExchangeStatus(e);e.lastRefresh.all=Date.now()}function computeEdges(e){const t=[];for(const[,n]of e.contexts){if(!n?.edges)continue;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;const s=n.get(t);if(!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 loadCandles(e){const t=e.positions.map((e=>e.ticker)).filter(Boolean);if(t.length===0)return;try{const n=Math.floor(Date.now()/1e3);const s=n-7*86400;const 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");const n=parseFloat(e.yes_ask?.close_dollars||"0");const s=t>0&&n>0?(t+n)/2:t||n;const o=parseFloat(e.price?.close_dollars||"0")||s;return{close:Math.round(o*100),date:e.end_period_ts?new Date(e.end_period_ts*1e3).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 collectEvents(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)=>{const n=new Date(e.timestamp||e.date||e.time||0).getTime();const s=new Date(t.timestamp||t.date||t.time||0).getTime();return n-s}));e.events=t.filter((e=>{const t=new Date(e.timestamp||e.date||e.time||0).getTime();return t>Date.now()}))}function checkExchangeStatus(e){const t=new Date;const n=t.getUTCDay();e.exchangeOpen=n>=1&&n<=5}function renderFrame(e,t){(0,k.renderMarketBar)(e,0,t);(0,$.renderStatusBar)(e,1,t);(0,b.renderCommandBar)(e,e.rows-1,t);switch(t.mode){case"overview":renderOverview(e,t);break;case"detail":(0,w.renderDetail)(e,(0,o.fullLayout)(e.cols,e.rows),t);break;case"liquidity":(0,_.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":if(t.prevMode==="detail"){(0,w.renderDetail)(e,(0,o.fullLayout)(e.cols,e.rows),t)}else{renderOverview(e,t)}(0,v.renderTrade)(e,(0,o.fullLayout)(e.cols,e.rows),t);break}e.flush()}function renderOverview(e,t){const n=e.cols<80;const s=n?(0,o.narrowLayout)(e.cols,e.rows):(0,o.overviewLayout)(e.cols,e.rows);if(!n){const t=Math.floor(e.cols*.55);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,f.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,g.renderOrders)(e,n,t);break}}}function handleKeypress(e,t,n,s,o){const i=t.toString("utf-8");const r=t[0]===27&&t.length===1;const a=t[0]===27&&t[1]===91&&t[2]===65;const c=t[0]===27&&t[1]===91&&t[2]===66;const l=i==="\r"||i==="\n";const d=t[0]===3;if(d||i==="q"&&e.mode!=="trade"){o();return}e.error=null;switch(e.mode){case"overview":handleOverviewKey(i,a,c,l,e,n,s,o);break;case"detail":handleDetailKey(i,r,e,n,s);break;case"liquidity":handleLiquidityKey(i,a,c,r,e,n,s);break;case"whatif":handleWhatifKey(i,a,c,l,r,e,n,s);break;case"trade":handleTradeKey(i,a,c,l,r,e,n,s);break}}function handleOverviewKey(e,t,n,s,o,i,r,c){const l=o.focusArea==="positions"?o.positions:o.focusArea==="edges"?o.edges:o.intents||[];const d=Math.max(0,l.length-1);if(e==="j"||n){o.selectedIndex=Math.min(o.selectedIndex+1,d);r()}else if(e==="k"||t){o.selectedIndex=Math.max(o.selectedIndex-1,0);r()}else if(s){if(o.focusArea==="positions"&&o.positions.length>0){const e=o.positions[o.selectedIndex];o.detailTicker=e?.ticker||null;o.prevMode="overview";o.mode="detail";r()}}else if(e==="l"){o.prevMode="overview";o.mode="liquidity";o.liquiditySelectedIndex=0;loadLiquidityData(o).then(r)}else if(e==="w"){if(o.theses.length>0){o.prevMode="overview";o.mode="whatif";o.whatifThesisId=o.theses[0].id;loadWhatifData(o).then(r)}}else if(e==="b"){openTrade(o,"buy");r()}else if(e==="s"){openTrade(o,"sell");r()}else if(e==="e"){triggerEvaluate(o).then(r)}else if(e==="r"){(0,a.invalidateAll)();loadAllData(o).then(r)}else if(e==="i"){if(o.focusArea==="edges"&&o.edges.length>0){const e=o.edges[o.selectedIndex];if(e){const t=e.marketId||e.ticker||"";openTrade(o,"buy");if(o.tradeParams){o.tradeParams.ticker=t;o.tradeParams.side=e.direction||"yes";o.tradeParams.price=e.marketPrice||50}r()}}}else if(e==="x"){if(o.focusArea==="intents"&&o.intents.length>0){const e=o.intents[o.selectedIndex];if(e?.id){const t=getClient();if(t){t.request("DELETE",`/api/intents/${e.id}`).then((()=>{(0,a.invalidateAll)();loadAllData(o).then(r)})).catch((()=>{o.error="Failed to cancel intent";r()}))}}}}else if(e>="1"&&e<="9"){const t=parseInt(e)-1;if(t<o.theses.length){o.activeThesisIndex=t;r()}}else if(e==="\t"){if(o.focusArea==="positions")o.focusArea="edges";else if(o.focusArea==="edges")o.focusArea="intents";else o.focusArea="positions";o.selectedIndex=0;r()}}function handleDetailKey(e,t,n,s,o){if(t){n.mode="overview";o()}else if(e==="b"){openTrade(n,"buy");o()}else if(e==="s"){openTrade(n,"sell");o()}else if(e==="w"){if(n.theses.length>0){n.prevMode="detail";n.mode="whatif";n.whatifThesisId=n.theses[0].id;loadWhatifData(n).then(o)}}}function handleLiquidityKey(e,t,n,s,o,i,r){if(s){o.mode=o.prevMode;r()}else if(e==="j"||n){o.liquiditySelectedIndex++;r()}else if(e==="k"||t){o.liquiditySelectedIndex=Math.max(0,o.liquiditySelectedIndex-1);r()}else if(e==="\t"){const e=Object.keys(u.TOPIC_SERIES);const t=e.indexOf(o.liquidityTopic);o.liquidityTopic=e[(t+1)%e.length];o.liquiditySelectedIndex=0;loadLiquidityData(o).then(r)}else if(e==="b"){openTradeFromLiquidity(o);r()}else if(e==="r"){loadLiquidityData(o).then(r)}}function handleWhatifKey(e,t,n,s,o,i,r,a){if(o){i.mode=i.prevMode;a()}else if(e==="j"||n){const e=(i.whatifResult?.scenarios?.length||1)-1;i.whatifScenarioIndex=Math.min(i.whatifScenarioIndex+1,e);a()}else if(e==="k"||t){i.whatifScenarioIndex=Math.max(0,i.whatifScenarioIndex-1);a()}else if(s){a()}}function handleTradeKey(e,t,n,s,o,i,r,a){if(o){i.mode=i.prevMode;i.tradeParams=null;i.tradeCountdown=-1;a();return}if(!i.tradeParams)return;if(e==="\t"){i.tradeField=i.tradeField==="qty"?"price":"qty";a()}else if(t){if(i.tradeField==="qty"){i.tradeParams.qty=Math.min(i.tradeParams.qty+1,9999)}else{i.tradeParams.price=Math.min(i.tradeParams.price+1,99)}a()}else if(n){if(i.tradeField==="qty"){i.tradeParams.qty=Math.max(i.tradeParams.qty-1,1)}else{i.tradeParams.price=Math.max(i.tradeParams.price-1,1)}a()}else if(s){if(i.tradeCountdown<0){i.tradeCountdown=3;a();startCountdown(i,r,a)}}}function startCountdown(e,t,n){const tick=()=>{if(e.tradeCountdown<=0||e.mode!=="trade")return;e.tradeCountdown--;n();if(e.tradeCountdown===0){executeTrade(e,n)}else{setTimeout(tick,1e3)}};setTimeout(tick,1e3)}function openTrade(e,t){let n="";if(e.focusArea==="positions"&&e.positions.length>0){const t=e.positions[e.selectedIndex];n=t?.ticker_symbol||t?.ticker||""}else if(e.focusArea==="edges"&&e.edges.length>0){const t=e.edges[e.selectedIndex];n=t?.ticker||t?.marketId||""}else if(e.detailTicker){n=e.detailTicker}if(!n){e.error="No market selected";return}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"}function openTradeFromLiquidity(e){const t=e.liquidityData.get(e.liquidityTopic)||[];if(t.length===0)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"}async function executeTrade(e,t){if(!e.tradeParams)return;try{const n=(0,c.loadConfig)();if(!n.tradingEnabled){e.error="Trading disabled. Run: sf setup --enable-trading";e.tradeCountdown=-1;t();return}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 loadAllData(e)}catch(t){e.error=t instanceof Error?t.message.slice(0,40):"Trade failed";e.tradeCountdown=-1}t()}async function loadLiquidityData(e){const t=e.liquidityTopic;const n=u.TOPIC_SERIES[t];if(!n)return;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`;const n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)return[];const s=await n.json();return s.markets||[]})))));const o=[];for(const e of s){if(e.status==="fulfilled"&&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);const 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(e.status!=="fulfilled"||!e.value.ob)continue;const{mkt:t,ob:n}=e.value;const s=(n.yes_dollars||[]).map((e=>({price:Math.round(parseFloat(e[0])*100),qty:parseFloat(e[1])}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const o=(n.no_dollars||[]).map((e=>({price:Math.round(parseFloat(e[0])*100),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 loadWhatifData(e){const t=getClient();if(!t||!e.whatifThesisId)return;try{const t=e.contexts.get(e.whatifThesisId);if(!t)return;const n=t.causalTree?.nodes||t.nodes||[];const s=n.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:s,before:{confidence:e.theses[0]?.confidence,edges:e.edges.slice(0,5)},after:null}}catch{e.error="Failed to load what-if data"}}async function triggerEvaluate(e){const t=getClient();if(!t||e.theses.length===0)return;try{e.error=null;const n=e.theses[0];await t.evaluate(n.id);(0,a.invalidateAll)();await loadAllData(e)}catch(t){e.error=t instanceof Error?t.message.slice(0,40):"Evaluation failed"}}async function startDashboard(){const e=new s.ScreenBuffer;const t=(0,i.initialState)();process.stdout.write("[?1049h");process.stdout.write("[?25l");if(process.stdin.isTTY){process.stdin.setRawMode(true)}process.stdin.resume();let n=false;const scheduleRender=()=>{if(n)return;n=true;setImmediate((()=>{n=false;renderFrame(e,t)}))};const o=[];let r=false;const cleanup=()=>{if(r)return;r=true;for(const e of o)clearInterval(e);process.stdout.write("[?1049l");process.stdout.write("[?25h");if(process.stdin.isTTY){process.stdin.setRawMode(false)}process.stdin.pause();process.exit(0)};process.on("SIGINT",cleanup);process.on("SIGTERM",cleanup);try{await loadAllData(t)}catch(e){t.error=e instanceof Error?e.message.slice(0,50):"Failed to load data"}renderFrame(e,t);o.push(setInterval((async()=>{try{const e=await(0,a.cached)("positions",C,(()=>(0,d.getPositions)()));if(e){const n=await Promise.allSettled(e.map((e=>(0,a.cached)(`price:${e.ticker}`,1e4,(()=>(0,d.getMarketPrice)(e.ticker))))));for(let t=0;t<e.length;t++){const s=n[t];if(s.status==="fulfilled"&&s.value!=null){e[t].current_value=s.value}}t.positions=e;computeEdges(t)}scheduleRender()}catch{}}),C));o.push(setInterval((async()=>{try{const e=await(0,a.cached)("orders",I,(()=>(0,d.getOrders)({status:"resting"})));if(e){t.orders=e.orders||[]}scheduleRender()}catch{}}),I));o.push(setInterval((async()=>{try{const e=await(0,a.cached)("balance",P,(()=>(0,d.getBalance)()));if(e){t.balance=e.balance??0}scheduleRender()}catch{}}),P));o.push(setInterval((async()=>{try{await loadCandles(t);scheduleRender()}catch{}}),E));process.stdin.on("data",(n=>{handleKeypress(t,n,e,scheduleRender,cleanup)}));process.stdout.on("resize",(()=>{e.resize();scheduleRender()}))}},42992:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.overviewLayout=overviewLayout;t.fullLayout=fullLayout;t.narrowLayout=narrowLayout;function overviewLayout(e,t){const n=t-3;const s=Math.floor(e*.55);const o=e-s-1;const i=s+1;const r=Math.max(Math.floor(n*.4),5);const a=Math.max(Math.floor(n*.3),4);const 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}]}function fullLayout(e,t){return{name:"main",row:2,col:0,width:e,height:t-3}}function narrowLayout(e,t){const n=t-3;const 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:true});t.ScreenBuffer=void 0;class ScreenBuffer{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++){if(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++){if(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++){if(a>=0&&e>=0){this.back[a][e]={char:o,fg:i,bg:r}}}}}flush(){let e="";let t="";let n="";for(let s=0;s<this.rows;s++){for(let o=0;o<this.cols;o++){const i=this.front[s][o];const r=this.back[s][o];if(i.char!==r.char||i.fg!==r.fg||i.bg!==r.bg){e+=`[${s+1};${o+1}H`;if(r.fg!==t||r.bg!==n){e+="[0m";if(r.fg)e+=r.fg;if(r.bg)e+=r.bg;t=r.fg;n=r.bg}e+=r.char}}}if(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")}}t.ScreenBuffer=ScreenBuffer},56661:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.initialState=initialState;function initialState(){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:true});t.renderCommandBar=renderCommandBar;const s=n(77096);const o=(0,s.bgRgb)(12,12,16);const 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"}]};function renderCommandBar(e,t,n){const r=e.cols;e.fill(t,0,r,1," ","",o);const a=i[n.mode]||i.overview;const c=n.mode==="overview"?n.focusArea.toUpperCase():"";let l=1;if(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);const a=r-i.length-2;if(a>l)e.write(t,a,i,s.CLR.red,o)}}},35301:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderDetail=renderDetail;const s=n(77096);const o=n(14916);function renderDetail(e,t,n){(0,s.drawBorder)(e,t,"POSITION DETAIL");const i=t.col+2;const r=t.width-4;const a=n.positions.find((e=>(e.ticker_symbol||e.ticker)===n.detailTicker))||n.positions[0];if(!a){e.write(t.row+2,i,"No position selected",s.CLR.dim);return}const c=a.ticker_symbol||a.ticker||"???";const l=a.quantity??0;const d=a.average_price_paid??a.cost_basis??0;const u=a.current_value??d;const p=(u-d)*l;const h=p/100;const m=p>=0?s.CLR.green:s.CLR.red;const f=a.side||"yes";let g=1;e.writeStyled(t.row+g,i,[{text:(0,s.fit)(c,30),fg:s.CLR.white},{text:` ${f.toUpperCase()} `,fg:s.CLR.emerald},{text:` qty: ${l}`,fg:s.CLR.dim}]);g++;e.writeStyled(t.row+g,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}]);g++;const y=a.expiration_time||a.expiry||a.close_time||"";if(y){const n=new Date(y);const o=Math.ceil((n.getTime()-Date.now())/864e5);e.write(t.row+g,i,`Expiry: ${n.toISOString().slice(0,10)} (${o}d)`,s.CLR.dim)}g++;(0,s.drawHDivider)(e,t,g);g++;const $=Math.min(8,Math.floor((t.height-g-8)/2)+4);const k=n.candleCache.get(c)||[];if(k.length>1){const n=k.map((e=>{const t=e.close??0;return(t-d)*l/100}));const a=k.map((e=>{const t=e.date?new Date(e.date):new Date(e.end_period_ts?e.end_period_ts*1e3:0);return`${t.getMonth()+1}/${t.getDate()}`}));e.write(t.row+g,i,"Daily P&L ($)",s.CLR.title);g++;(0,o.drawChart)(e,t.row+g,i,r,$,n,a);g+=$+1}else{e.write(t.row+g,i,"No chart data available",s.CLR.dim);g+=2}if(g<t.height-5){(0,s.drawHDivider)(e,t,g);g++}const b=Math.floor(r/2)-1;const w=t.row+g;const _=t.height-g-1;e.write(w,i,"Causal Tree",s.CLR.title);let S=null;for(const[,e]of n.contexts){const t=e?.edges||[];if(t.some((e=>e.marketId===c||e.ticker===c))){S=e;break}}const v=S?.causalTree?.nodes||[];const x=[];function walk(e,t=0){for(const n of e){x.push({...n,depth:t});if(n.children)walk(n.children,t+1)}}walk(v);const C=x.filter((e=>e.depth<=1)).slice(0,_-1);for(let t=0;t<C.length;t++){const n=C[t];const o=" ".repeat(n.depth+1);const r=n.label||n.claim||n.name||n.id||"?";const a=n.probability!=null?`${Math.round(n.probability*100)}%`:"";e.writeStyled(w+1+t,i,[{text:o+(0,s.fit)(r,b-o.length-5),fg:s.CLR.text},{text:(0,s.fit)(a,5,"right"),fg:s.CLR.emerald}])}if(C.length===0){e.write(w+1,i," (no context data)",s.CLR.dim)}const O=i+b+2;e.write(w,O,"Orderbook",s.CLR.title);const I=S?.edges?.find((e=>e.marketId===c||e.ticker===c));const P=I?.orderbook;if(P){const t=P.bidPrice??P.bestBid??0;const n=P.askPrice??P.bestAsk??0;const o=P.spread??n-t;e.writeStyled(w+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(w+2,O,[{text:"Spread: ",fg:s.CLR.dim},{text:`${o}¢`,fg:o<=2?s.CLR.green:o<=5?s.CLR.yellow:s.CLR.red}]);if(P.bidDepth!=null){e.writeStyled(w+3,O,[{text:"Depth: ",fg:s.CLR.dim},{text:`bid ${P.bidDepth}`,fg:s.CLR.dim},{text:` / ask ${P.askDepth}`,fg:s.CLR.dim}])}}else{e.write(w+1,O," (no orderbook data)",s.CLR.dim)}}},30012:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderEdges=renderEdges;const s=n(77096);const o="▏▎▍▌▋▊▉█";function renderEdges(e,t,n){(0,s.drawBorder)(e,t,"TOP EDGES");const i=t.col+2;const r=t.width-4;const a=t.height-2;const c=new Set(n.positions.map((e=>e.ticker)));const l=n.edges.filter((e=>!c.has(e.marketId||e.ticker||"")));const d=l.slice(0,Math.min(a,8));if(d.length===0){e.write(t.row+1,i,"No unpositioned edges",s.CLR.dim);return}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];const l=t.row+1+a;const p=n.focusArea==="edges"&&n.selectedIndex===a;const h=p?"▸":" ";const m=c.market||c.marketTitle||c.marketId||"???";const f=c.edge??c.edgeSize??0;const g=`${f>0?"+":""}${f.toFixed(0)}¢`;const y=`${c.marketPrice??"?"}¢`;const $=c.venue==="polymarket"?"P":"K";const k=c.orderbook?.liquidityScore||"";const b=k==="high"?"H":k==="medium"?"M":k==="low"?"L":"";const w=k==="high"?s.CLR.green:k==="low"?s.CLR.yellow:s.CLR.dim;const _=6;const S=Math.abs(f)/u;const v=Math.floor(S*_);const x=S*_-v;const C=Math.min(Math.floor(x*8),7);const O=o[7].repeat(v)+(x>.1?o[C]:"");const I=f>0?s.CLR.emerald:s.CLR.red;const 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)(O,_),fg:I},{text:(0,s.fit)(g,5,"right"),fg:s.CLR.emerald},{text:b?` ${b}`:"",fg:w}])}}},87009:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderIntents=renderIntents;const s=n(77096);const 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};function renderIntents(e,t,n){(0,s.drawBorder)(e,t,"INTENTS");const i=t.col+2;const r=t.width-4;const a=t.height-2;const c=n.intents||[];if(c.length===0){e.write(t.row+1,i,"No active intents",s.CLR.dim,s.CLR.bgPanel);e.write(t.row+2,i,"Press i on an edge to create one",s.CLR.veryDim,s.CLR.bgPanel);return}for(let l=0;l<Math.min(c.length,a);l++){const a=c[l];const d=t.row+1+l;const u=n.focusArea==="intents"&&n.selectedIndex===l;const p=u?s.CLR.bgSelected:s.CLR.bgPanel;if(u)e.fill(d,t.col+1,t.width-2,1," ","",p);const h=a.status||"pending";const m=o[h]||s.CLR.dim;const f=(a.action||"buy").toUpperCase();const g=(a.direction||"yes").toUpperCase();const y=(a.marketId||a.market_id||"???").slice(0,16);const $=a.targetQuantity||a.target_quantity||0;const k=a.filledQuantity||a.filled_quantity||0;const b=a.maxPrice||a.max_price;const w=b?`≤${b}¢`:"mkt";const _=k>0?`${k}/${$}`:`${$}`;const S=Math.max(r-26,6);e.writeStyled(d,i,[{text:(0,s.fit)(h,9),fg:m,bg:p},{text:` ${f} `,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:` ${g} ${_} ${w}`,fg:s.CLR.dim,bg:p}])}}},82950:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderLiquidity=renderLiquidity;const s=n(77096);const o=n(97325);const i=(0,s.bgRgb)(30,30,35);const r=(0,s.bgRgb)(16,16,18);function renderLiquidity(e,t,n){(0,s.drawBorder)(e,t,"LIQUIDITY SCANNER");const a=t.col+2;const 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;const c=` ${o.toUpperCase()} `;const d=a?s.CLR.emerald:s.CLR.dim;const 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(c*.35));const h=8;e.writeStyled(t.row+l,a,[{text:(0,s.fit)("Market",p),fg:s.CLR.title},{text:(0,s.fit)("Bid¢",h,"right"),fg:s.CLR.title},{text:(0,s.fit)("Ask¢",h,"right"),fg:s.CLR.title},{text:(0,s.fit)("Spread",h,"right"),fg:s.CLR.title},{text:(0,s.fit)("Depth",h,"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 m=n.liquidityData.get(n.liquidityTopic)||[];const f=new Set(n.positions.map((e=>e.ticker_symbol||e.ticker)));const g=t.height-l-3;const y=groupByHorizon(m);let $=0;for(const[o,i]of y){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===$;const r=i?"▸":" ";const c=f.has(o.ticker)?"← held":"";const d=o.ticker||"???";const u=o.bestBid??o.yes_bid??0;const m=o.bestAsk??o.yes_ask??0;const g=o.spread??m-u;const y=o.totalDepth??o.depth??0;const k=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),h,"right"),fg:s.CLR.green},{text:(0,s.fit)(String(m),h,"right"),fg:s.CLR.red},{text:(0,s.fit)(String(g),h,"right"),fg:k},{text:(0,s.fit)(String(y),h,"right"),fg:s.CLR.dim},{text:c?` ${c}`:"",fg:s.CLR.emerald}]);l++;$++}}if(m.length>0){const o=Math.min(n.liquiditySelectedIndex,m.length-1);const i=Array.from(y.values()).flat();const 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=r.slippage!=null?`Slippage: ~${r.slippage}¢`:"";const i=r.edge!=null?`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}])}}}function groupByHorizon(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);if(t<=7)s="Weekly";else if(t<=35)s="Monthly";else s="Long-term"}}if(!t.has(s))t.set(s,[]);t.get(s).push(n)}const n=["Daily","Weekly","Monthly","Long-term","Other"];const s=new Map;for(const e of n){if(t.has(e))s.set(e,t.get(e))}return s}},12423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderMarketBar=renderMarketBar;const s=n(77096);const o=(0,s.bgRgb)(12,12,16);function renderMarketBar(e,t,n){const i=e.cols;e.fill(t,0,i,1," ","",o);const r=n.traditionalMarkets||[];if(r.length===0){e.write(t,1,"SimpleFunctions",s.CLR.dim,o);return}const a=r.slice(0,6);const c=Math.floor((i-2)/a.length);for(let n=0;n<a.length;n++){const i=a[n];const r=1+n*c;const l=(i.symbol||i.name||"???").replace("SPDR ","").replace(" ETF","").slice(0,5);const d=i.changePct??i.change_pct??i.pctChange??0;const u=i.price??i.value??0;const p=u>100?Math.round(u).toLocaleString():u.toFixed(2);const h=d>=0?"+":"";const m=`${h}${d.toFixed(1)}%`;const f=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,m,f,o)}}},75757:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderOrders=renderOrders;const s=n(77096);function renderOrders(e,t,n){(0,s.drawBorder)(e,t,"ORDERS");const o=t.col+2;const i=t.width-4;const r=t.height-2;if(n.orders.length===0){e.write(t.row+1,o,"No resting orders",s.CLR.dim);return}for(let i=0;i<Math.min(n.orders.length,r);i++){const r=n.orders[i];const a=t.row+1+i;const c=(r.ticker||"???").slice(0,10);const l=Math.round(parseFloat(r.remaining_count_fp||r.initial_count_fp||"0"));const d=parseFloat(r.yes_price_dollars||"0");const u=Math.round(d*100);const p=r.status||"resting";const h=`${l}@${u}¢`;const m=new Date(r.created_time||Date.now()).getTime();const f=Math.floor((Date.now()-m)/864e5);const g=f===0?"<1d":`${f}d`;const y=f>3;const $=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:p==="filled"?s.CLR.green:s.CLR.dim},{text:(0,s.fit)(g,4,"right"),fg:y?s.CLR.yellow:s.CLR.dim}])}}},3322:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderPortfolio=renderPortfolio;const s=n(77096);function renderPortfolio(e,t,n){(0,s.drawBorder)(e,t,"POSITIONS");const o=t.col+2;const i=t.width-4;const r=t.height-2;let a=0;if(n.positions.length===0){e.write(t.row+1,o,"No positions",s.CLR.dim,s.CLR.bgPanel);e.write(t.row+2,o,"sf buy TICKER QTY --price CENTS",s.CLR.veryDim,s.CLR.bgPanel);return}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));const s=Math.abs(((t.current_value||t.average_price_paid||0)-(t.average_price_paid||0))*(t.quantity||0));return s-n}));for(const l of c){if(a+1>=r)break;const d=t.row+1+a;const u=c.indexOf(l);const p=n.focusArea==="positions"&&n.selectedIndex===u;const h=p?s.CLR.bgSelected:s.CLR.bgPanel;if(p){e.fill(d,t.col+1,t.width-2,2," ","",h)}const m=l.ticker||"???";const f=l.venue==="polymarket"?"P":"K";const g=l.venue==="polymarket"?s.CLR.purple:s.CLR.cyan;e.writeStyled(d,o,[{text:f+" ",fg:g,bg:h},{text:(0,s.fit)(m,Math.min(i-2,28)),fg:p?s.CLR.white:s.CLR.text,bg:h}]);if(a+1<r){const t=l.quantity??0;const i=l.average_price_paid??0;const r=l.current_value??i;const a=(r-i)*t;const c=a/100;const u=(c>=0?"+$":"-$")+Math.abs(c).toFixed(2);const p=c>=0?s.CLR.green:s.CLR.red;const f=[{text:` ${(0,s.compact)(t)} @ ${i}¢`,fg:s.CLR.dim,bg:h},{text:` → ${r}¢ `,fg:s.CLR.dim,bg:h},{text:(0,s.fit)(u,9),fg:p,bg:h}];const g=n.candleCache.get(m);if(g&&g.length>1){const e=g.slice(-7).map((e=>{const n=e.close??0;return(n-i)*t}));const n=(0,s.sparkline)(e,(e=>e>=0?s.CLR.green:s.CLR.red));for(const e of n)f.push({...e,bg:h})}e.writeStyled(d+1,o,f)}a+=2}}},50511:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderSignals=renderSignals;const s=n(77096);function renderSignals(e,t,n){(0,s.drawBorder)(e,t,"FEED");const o=t.col+2;const i=t.width-4;const r=t.height-2;const a=n.signals.sort(((e,t)=>{const n=new Date(e.evaluatedAt||e.timestamp||e.time||0).getTime();const s=new Date(t.evaluatedAt||t.timestamp||t.time||0).getTime();return s-n}));if(a.length===0){e.write(t.row+1,o,"No recent signals",s.CLR.dim);return}for(let n=0;n<Math.min(a.length,r);n++){const r=a[n];const c=t.row+1+n;const l=r.confidenceDelta??r.delta??r.change??0;const d=r.summary||r.title||r.content||"???";const 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=typeof l==="number"?l>=0:true;const m=typeof l==="number"&&Math.abs(l)>=.001;const f=m?h?"▲":"▼":" ";const g=h?s.CLR.green:s.CLR.red;const y=m?`${l>0?"+":""}${Math.round(l*100)}%`:"";const $=i-14;e.writeStyled(c,o,[{text:p,fg:s.CLR.veryDim},{text:` ${f}`,fg:m?g:s.CLR.dim},{text:(0,s.fit)(y,5,"right"),fg:m?g:s.CLR.dim},{text:" "+(0,s.fit)(d,$),fg:s.CLR.text}])}}},98573:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderStatusBar=renderStatusBar;const s=n(77096);const o=(0,s.bgRgb)(16,16,20);const i="│";function renderStatusBar(e,t,n){const r=e.cols;e.fill(t,0,r,1," ","",o);let a=0;let c=0;for(const e of n.positions){const t=e.average_price_paid??e.cost_basis??0;const n=e.current_value??t;const s=e.quantity??0;a+=(n-t)*s;c+=t*s}const l=a/100;const d=c>0?a/c*100:0;const u=l>=0?s.CLR.green:s.CLR.red;let p=1;const h=l>=0?"+":"";const m=`${h}$${Math.abs(l).toFixed(2)}`;const f=`${h}${d.toFixed(1)}%`;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,f,u,o);p+=f.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;if(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];const a=(r.title||"Thesis").slice(0,18);const c=r.confidence!=null?`${Math.round((r.confidence??0)*100)}%`:"?%";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;if(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 g=(n.intents||[]).filter((e=>["pending","armed","triggered","executing"].includes(e.status)));if(g.length>0){e.write(t,p,i,s.CLR.veryDim,o);p+=2;const n=`${g.length} intent${g.length>1?"s":""}`;e.write(t,p,n,s.CLR.emerald,o);p+=n.length+1}if(n.exchangeOpen!==null){e.write(t,p,i,s.CLR.veryDim,o);p+=2;const r=n.exchangeOpen?"OPEN":"CLOSED";const a=n.exchangeOpen?s.CLR.green:s.CLR.red;e.write(t,p,r,a,o)}const y=new Date;const $=y.toISOString().slice(11,19)+" UTC";e.write(t,r-$.length-1,$,s.CLR.veryDim,o)}},21704:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderThesis=renderThesis;const s=n(77096);function renderThesis(e,t,n){(0,s.drawBorder)(e,t,"THESIS");const o=t.col+2;const i=t.width-4;const r=t.height-2;let a=0;for(const c of n.theses){if(a>=r-2)break;const n=t.row+1+a;const l=c.title||c.short_title||"???";const d=c.confidence??c.current_confidence??0;const u=`${Math.round(d*100)}%`;const p=c.lastEvaluation?.confidenceDelta??c.confidence_delta??0;let h,m,f;if(p>=.02){h="▲";m=s.CLR.green;f=`+${Math.round(p*100)}`}else if(p<=-.02){h="▼";m=s.CLR.red;f=`${Math.round(p*100)}`}else{h="─";m=s.CLR.dim;f=p>=0?`+${Math.round(p*100)}`:`${Math.round(p*100)}`}const g=i-10;e.writeStyled(n,o,[{text:(0,s.fit)(l,g),fg:s.CLR.text},{text:(0,s.fit)(u,5,"right"),fg:s.CLR.white},{text:` ${h}`,fg:m},{text:(0,s.fit)(f,3,"right"),fg:m}]);a++}if(n.theses.length>0&&a<r){const a=n.theses[0];const c=n.contexts.get(a.id||a.thesis_id);const l=c?.lastEvaluation?.summary||a.lastEvaluation?.summary||"";if(l){const n=t.row+1+r-1;const 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}])}}}},67748:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderTrade=renderTrade;const s=n(77096);const o=(0,s.bgRgb)(18,18,22);const i=(0,s.bgRgb)(30,30,35);const r=(0,s.bgRgb)(16,50,40);function renderTrade(e,t,n){if(!n.tradeParams)return;const a=n.tradeParams;const c=Math.min(50,t.width-4);const l=Math.min(18,t.height-2);const d=t.col+Math.floor((t.width-c)/2);const u=t.row+Math.floor((t.height-l)/2);const 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;const m=c-4;let f=1;const g=a.action==="buy"?s.CLR.green:s.CLR.red;const y=a.action==="buy"?"BUY":"SELL";e.writeStyled(u+f,h,[{text:y+" ",fg:g},{text:a.side.toUpperCase()+" ",fg:s.CLR.emerald},{text:a.ticker,fg:s.CLR.white}]);f+=2;const $=n.positions.find((e=>(e.ticker_symbol||e.ticker)===a.ticker));const k=$?.bestBid??$?.current_value??0;const b=$?.bestAsk??k+2;e.writeStyled(u+f,h,[{text:"Bid: ",fg:s.CLR.dim},{text:`${k}¢`,fg:s.CLR.green},{text:" Ask: ",fg:s.CLR.dim},{text:`${b}¢`,fg:s.CLR.red}]);f+=2;const w=n.tradeField==="qty";const _=w?r:i;e.write(u+f,h,"Quantity:",s.CLR.dim,o);e.write(u+f,h+12,(0,s.fit)(String(a.qty),10),w?s.CLR.emerald:s.CLR.text,_);if(w)e.write(u+f,h+22," ◀",s.CLR.emerald,o);f++;const S=n.tradeField==="price";const v=S?r:i;e.write(u+f,h,"Price (¢):",s.CLR.dim,o);e.write(u+f,h+12,(0,s.fit)(String(a.price),10),S?s.CLR.emerald:s.CLR.text,v);if(S)e.write(u+f,h+22," ◀",s.CLR.emerald,o);f+=2;const x=a.qty*a.price/100;const C=a.qty;const O=C-x;e.write(u+f,h,"Preview:",s.CLR.title,o);f++;e.writeStyled(u+f,h,[{text:`Max cost: $${x.toFixed(2)}`,fg:s.CLR.dim}]);f++;e.writeStyled(u+f,h,[{text:`Max payout: $${C.toFixed(2)}`,fg:s.CLR.dim}]);f++;e.writeStyled(u+f,h,[{text:"Profit: ",fg:s.CLR.dim},{text:`$${O.toFixed(2)}`,fg:O>=0?s.CLR.green:s.CLR.red}]);f++;const I=n.edges.find((e=>(e.ticker||e.marketId)===a.ticker));if(I){const t=I.edge??I.value??0;e.writeStyled(u+f,h,[{text:"Edge: ",fg:s.CLR.dim},{text:`${t>=0?"+":""}${t}¢`,fg:t>=0?s.CLR.green:s.CLR.red}]);f++}const P=Math.max(0,a.price-k);if(P>0){e.writeStyled(u+f,h,[{text:"Slippage: ",fg:s.CLR.dim},{text:`~${P}¢`,fg:s.CLR.yellow}]);f++}f++;if(n.tradeCountdown>0){const t=` Executing in ${n.tradeCountdown}... `;const i=h+Math.floor((m-t.length)/2);e.write(u+f,i,t,s.CLR.yellow,o)}else if(n.tradeCountdown===0){e.write(u+f,h+Math.floor((m-12)/2)," EXECUTING ",s.CLR.white,(0,s.bgRgb)(16,120,80))}else{e.write(u+f,h+Math.floor((m-24)/2),"Press Enter to confirm",s.CLR.dim,o)}}},29405:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderWhatif=renderWhatif;const s=n(77096);const o=(0,s.bgRgb)(25,25,30);function renderWhatif(e,t,n){(0,s.drawBorder)(e,t,"WHAT-IF SCENARIO");const i=t.col+2;const r=t.width-4;let a=1;if(!n.whatifResult){e.write(t.row+a,i,'No what-if data. Press "w" from overview to start.',s.CLR.dim);return}const c=n.whatifResult;const l=c.scenarios||c.overrides||[];const d=Math.floor(r/2)-2;e.write(t.row+a,i,"Scenarios:",s.CLR.title);a++;if(l.length===0){e.write(t.row+a,i," (no scenarios available)",s.CLR.dim);a+=2}else{for(let c=0;c<l.length;c++){if(a>=t.height-8)break;const d=l[c];const u=n.whatifScenarioIndex===c;const p=u?"▸ ":" ";const h=d.name||d.description||d.nodeId||`Scenario ${c+1}`;const 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;const 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||{};const m=c.after||c.proposed||{};const f=h.confidence!=null?`${Math.round(h.confidence*100)}%`:"?%";const g=m.confidence!=null?`${Math.round(m.confidence*100)}%`:"?%";const y=(m.confidence??0)-(h.confidence??0);const $=y>=0?`+${Math.round(y*100)}%`:`${Math.round(y*100)}%`;e.writeStyled(t.row+a,u,[{text:"Confidence: ",fg:s.CLR.dim},{text:f,fg:s.CLR.text}]);e.writeStyled(t.row+a,p,[{text:"Confidence: ",fg:s.CLR.dim},{text:g,fg:s.CLR.text},{text:` (${$})`,fg:y>=0?s.CLR.green:s.CLR.red}]);a++;const k=h.edges||[];const b=m.edges||[];e.write(t.row+a,u,"Edges:",s.CLR.dim);e.write(t.row+a,p,"Edges:",s.CLR.dim);a++;const w=Math.min(Math.max(k.length,b.length),t.height-a-3);for(let n=0;n<w;n++){const o=k[n];const i=b[n];if(o){const n=(o.market||o.ticker||"").slice(0,d-10);const 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);const r=`${i.edge>=0?"+":""}${i.edge}`;const c=i.edgeDelta??i.edge-(o?.edge??0);const 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;if(n!=null){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}])}}}},99236:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.c=void 0;t.vol=vol;t.cents=cents;t.pct=pct;t.delta=delta;t.shortDate=shortDate;t.pad=pad;t.rpad=rpad;t.hr=hr;t.die=die;t.errorWithHint=errorWithHint;t.emptyState=emptyState;t.header=header;t.trunc=trunc;t.shortId=shortId;t.c={reset:"[0m",bold:"[1m",dim:"[2m",red:"[31m",green:"[32m",yellow:"[33m",blue:"[34m",magenta:"[35m",cyan:"[36m",white:"[37m",gray:"[90m"};function vol(e){if(e===null||e===undefined)return"-";const t=typeof e==="string"?parseFloat(e):e;if(isNaN(t))return"-";if(t>=1e6)return`${(t/1e6).toFixed(1)}M`;if(t>=1e3)return`${(t/1e3).toFixed(0)}K`;return t.toString()}function cents(e){if(e===null||e===undefined)return"-";const t=typeof e==="string"?parseFloat(e):e;if(isNaN(t))return"-";return`${Math.round(t*100)}¢`}function pct(e){if(e===null||e===undefined)return"-";const t=typeof e==="string"?parseFloat(e):e;if(isNaN(t))return"-";return`${Math.round(t*100)}%`}function delta(e){const t=e>0?"↑":e<0?"↓":"→";const n=e>0?"+":"";return`${t} ${n}${Math.round(e*100)}%`}function shortDate(e){if(!e)return"-";try{const t=new Date(e);const n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];const s=n[t.getMonth()];const o=t.getDate();const i=t.getHours().toString().padStart(2,"0");const r=t.getMinutes().toString().padStart(2,"0");return`${s} ${o} ${i}:${r}`}catch{return e.slice(0,16)}}function pad(e,t){if(e.length>=t)return e.slice(0,t);return e+" ".repeat(t-e.length)}function rpad(e,t){if(e.length>=t)return e.slice(0,t);return" ".repeat(t-e.length)+e}function hr(e=80){console.log(t.c.dim+"─".repeat(e)+t.c.reset)}function die(e){console.error(`${t.c.red}Error:${t.c.reset} ${e}`);process.exit(1)}function errorWithHint(e,n){console.error(`\n ${t.c.red}Error:${t.c.reset} ${e}`);if(n)console.error(` ${t.c.dim}${n}${t.c.reset}`);console.error()}function emptyState(e,n){console.log(`\n ${t.c.dim}No ${e} found.${t.c.reset}`);if(n)console.log(` ${t.c.dim}${n}${t.c.reset}`);console.log()}function header(e){console.log(`\n${t.c.bold}${t.c.cyan}${e}${t.c.reset}`)}function trunc(e,t){if(e.length<=t)return e;return e.slice(0,t-1)+"…"}function shortId(e){return e.slice(0,8)}},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);const{Command:o}=n(34348);const{CommanderError:i,InvalidArgumentError:r}=n(41135);const{Help:a}=n(79754);const{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);class Argument{constructor(e,t){this.description=t||"";this.variadic=false;this.parseArg=undefined;this.defaultValue=undefined;this.defaultValueDescription=undefined;this.argChoices=undefined;switch(e[0]){case"<":this.required=true;this._name=e.slice(1,-1);break;case"[":this.required=false;this._name=e.slice(1,-1);break;default:this.required=true;this._name=e;break}if(this._name.length>3&&this._name.slice(-3)==="..."){this.variadic=true;this._name=this._name.slice(0,-3)}}name(){return this._name}_concatValue(e,t){if(t===this.defaultValue||!Array.isArray(t)){return[e]}return t.concat(e)}default(e,t){this.defaultValue=e;this.defaultValueDescription=t;return this}argParser(e){this.parseArg=e;return this}choices(e){this.argChoices=e.slice();this.parseArg=(e,t)=>{if(!this.argChoices.includes(e)){throw new s(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(e,t)}return e};return this}argRequired(){this.required=true;return this}argOptional(){this.required=false;return this}}function humanReadableArgName(e){const t=e.name()+(e.variadic===true?"...":"");return e.required?"<"+t+">":"["+t+"]"}t.Argument=Argument;t.humanReadableArgName=humanReadableArgName},34348:(e,t,n)=>{const s=n(78474).EventEmitter;const o=n(31421);const i=n(76760);const r=n(73024);const a=n(1708);const{Argument:c,humanReadableArgName:l}=n(49154);const{CommanderError:d}=n(41135);const{Help:u}=n(79754);const{Option:p,DualOptions:h}=n(45240);const{suggestSimilar:m}=n(65030);class Command extends s{constructor(e){super();this.commands=[];this.options=[];this.parent=null;this._allowUnknownOption=false;this._allowExcessArguments=true;this.registeredArguments=[];this._args=this.registeredArguments;this.args=[];this.rawArgs=[];this.processedArgs=[];this._scriptPath=null;this._name=e||"";this._optionValues={};this._optionValueSources={};this._storeOptionsAsProperties=false;this._actionHandler=null;this._executableHandler=false;this._executableFile=null;this._executableDir=null;this._defaultCommandName=null;this._exitCallback=null;this._aliases=[];this._combineFlagAndOptionalValue=true;this._description="";this._summary="";this._argsDescription=undefined;this._enablePositionalOptions=false;this._passThroughOptions=false;this._lifeCycleHooks={};this._showHelpAfterError=false;this._showSuggestionAfterError=true;this._outputConfiguration={writeOut:e=>a.stdout.write(e),writeErr:e=>a.stderr.write(e),getOutHelpWidth:()=>a.stdout.isTTY?a.stdout.columns:undefined,getErrHelpWidth:()=>a.stderr.isTTY?a.stderr.columns:undefined,outputError:(e,t)=>t(e)};this._hidden=false;this._helpOption=undefined;this._addImplicitHelpCommand=undefined;this._helpCommand=undefined;this._helpConfiguration={}}copyInheritedSettings(e){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;return this}_getCommandAndAncestors(){const e=[];for(let t=this;t;t=t.parent){e.push(t)}return e}command(e,t,n){let s=t;let o=n;if(typeof s==="object"&&s!==null){o=s;s=null}o=o||{};const[,i,r]=e.match(/([^ ]+) *(.*)/);const a=this.createCommand(i);if(s){a.description(s);a._executableHandler=true}if(o.isDefault)this._defaultCommandName=a._name;a._hidden=!!(o.noHelp||o.hidden);a._executableFile=o.executableFile||null;if(r)a.arguments(r);this._registerCommand(a);a.parent=this;a.copyInheritedSettings(this);if(s)return this;return a}createCommand(e){return new Command(e)}createHelp(){return Object.assign(new u,this.configureHelp())}configureHelp(e){if(e===undefined)return this._helpConfiguration;this._helpConfiguration=e;return this}configureOutput(e){if(e===undefined)return this._outputConfiguration;Object.assign(this._outputConfiguration,e);return this}showHelpAfterError(e=true){if(typeof e!=="string")e=!!e;this._showHelpAfterError=e;return this}showSuggestionAfterError(e=true){this._showSuggestionAfterError=!!e;return 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()`)}t=t||{};if(t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=true;this._registerCommand(e);e.parent=this;e._checkForBrokenPassThrough();return this}createArgument(e,t){return new c(e,t)}argument(e,t,n,s){const o=this.createArgument(e,t);if(typeof n==="function"){o.default(s).argParser(n)}else{o.default(n)}this.addArgument(o);return this}arguments(e){e.trim().split(/ +/).forEach((e=>{this.argument(e)}));return 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&&e.defaultValue!==undefined&&e.parseArg===undefined){throw new Error(`a default value for a required argument is never used: '${e.name()}'`)}this.registeredArguments.push(e);return this}helpCommand(e,t){if(typeof e==="boolean"){this._addImplicitHelpCommand=e;return this}e=e??"help [command]";const[,n,s]=e.match(/([^ ]+) *(.*)/);const o=t??"display help for command";const i=this.createCommand(n);i.helpOption(false);if(s)i.arguments(s);if(o)i.description(o);this._addImplicitHelpCommand=true;this._helpCommand=i;return this}addHelpCommand(e,t){if(typeof e!=="object"){this.helpCommand(e,t);return this}this._addImplicitHelpCommand=true;this._helpCommand=e;return this}_getHelpCommand(){const e=this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"));if(e){if(this._helpCommand===undefined){this.helpCommand(undefined,undefined)}return this._helpCommand}return 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("', '")}'`)}if(this._lifeCycleHooks[e]){this._lifeCycleHooks[e].push(t)}else{this._lifeCycleHooks[e]=[t]}return this}exitOverride(e){if(e){this._exitCallback=e}else{this._exitCallback=e=>{if(e.code!=="commander.executeSubCommandAsync"){throw e}else{}}}return this}_exit(e,t,n){if(this._exitCallback){this._exitCallback(new d(e,t,n))}a.exit(e)}action(e){const listener=t=>{const n=this.registeredArguments.length;const s=t.slice(0,n);if(this._storeOptionsAsProperties){s[n]=this}else{s[n]=this.opts()}s.push(this);return e.apply(this,s)};this._actionHandler=listener;return this}createOption(e,t){return new p(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(e){if(e.code==="commander.invalidArgument"){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 knownBy=e=>[e.name()].concat(e.aliases());const t=knownBy(e).find((e=>this._findCommand(e)));if(t){const n=knownBy(this._findCommand(t)).join("|");const s=knownBy(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);const t=e.name();const n=e.attributeName();if(e.negate){const t=e.long.replace(/^--no-/,"--");if(!this._findOption(t)){this.setOptionValueWithSource(n,e.defaultValue===undefined?true:e.defaultValue,"default")}}else if(e.defaultValue!==undefined){this.setOptionValueWithSource(n,e.defaultValue,"default")}const handleOptionValue=(t,s,o)=>{if(t==null&&e.presetArg!==undefined){t=e.presetArg}const i=this.getOptionValue(n);if(t!==null&&e.parseArg){t=this._callParseArg(e,t,i,s)}else if(t!==null&&e.variadic){t=e._concatValue(t,i)}if(t==null){if(e.negate){t=false}else if(e.isBoolean()||e.optional){t=true}else{t=""}}this.setOptionValueWithSource(n,t,o)};this.on("option:"+t,(t=>{const n=`error: option '${e.flags}' argument '${t}' is invalid.`;handleOptionValue(t,n,"cli")}));if(e.envVar){this.on("optionEnv:"+t,(t=>{const n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;handleOptionValue(t,n,"env")}))}return this}_optionEx(e,t,n,s,o){if(typeof t==="object"&&t instanceof p){throw new Error("To add an Option object use addOption() instead of option() or requiredOption()")}const i=this.createOption(t,n);i.makeOptionMandatory(!!e.mandatory);if(typeof s==="function"){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:true},e,t,n,s)}combineFlagAndOptionalValue(e=true){this._combineFlagAndOptionalValue=!!e;return this}allowUnknownOption(e=true){this._allowUnknownOption=!!e;return this}allowExcessArguments(e=true){this._allowExcessArguments=!!e;return this}enablePositionalOptions(e=true){this._enablePositionalOptions=!!e;return this}passThroughOptions(e=true){this._passThroughOptions=!!e;this._checkForBrokenPassThrough();return 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=true){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")}this._storeOptionsAsProperties=!!e;return this}getOptionValue(e){if(this._storeOptionsAsProperties){return this[e]}return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,undefined)}setOptionValueWithSource(e,t,n){if(this._storeOptionsAsProperties){this[e]=t}else{this._optionValues[e]=t}this._optionValueSources[e]=n;return this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;this._getCommandAndAncestors().forEach((n=>{if(n.getOptionValueSource(e)!==undefined){t=n.getOptionValueSource(e)}}));return t}_prepareUserArgs(e,t){if(e!==undefined&&!Array.isArray(e)){throw new Error("first parameter to parse must be array or undefined")}t=t||{};if(e===undefined&&t.from===undefined){if(a.versions?.electron){t.from="electron"}const e=a.execArgv??[];if(e.includes("-e")||e.includes("--eval")||e.includes("-p")||e.includes("--print")){t.from="eval"}}if(e===undefined){e=a.argv}this.rawArgs=e.slice();let n;switch(t.from){case undefined:case"node":this._scriptPath=e[1];n=e.slice(2);break;case"electron":if(a.defaultApp){this._scriptPath=e[1];n=e.slice(2)}else{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}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);this._name=this._name||"program";return n}parse(e,t){const n=this._prepareUserArgs(e,t);this._parseCommand([],n);return this}async parseAsync(e,t){const n=this._prepareUserArgs(e,t);await this._parseCommand([],n);return this}_executeSubCommand(e,t){t=t.slice();let n=false;const s=[".js",".ts",".tsx",".mjs",".cjs"];function findFile(e,t){const n=i.resolve(e,t);if(r.existsSync(n))return n;if(s.includes(i.extname(t)))return undefined;const o=s.find((e=>r.existsSync(`${n}${e}`)));if(o)return`${n}${o}`;return undefined}this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();let c=e._executableFile||`${this._name}-${e._name}`;let l=this._executableDir||"";if(this._scriptPath){let e;try{e=r.realpathSync(this._scriptPath)}catch(t){e=this._scriptPath}l=i.resolve(i.dirname(e),l)}if(l){let t=findFile(l,c);if(!t&&!e._executableFile&&this._scriptPath){const n=i.basename(this._scriptPath,i.extname(this._scriptPath));if(n!==this._name){t=findFile(l,`${n}-${e._name}`)}}c=t||c}n=s.includes(i.extname(c));let u;if(a.platform!=="win32"){if(n){t.unshift(c);t=incrementNodeInspectorPort(a.execArgv).concat(t);u=o.spawn(a.argv[0],t,{stdio:"inherit"})}else{u=o.spawn(c,t,{stdio:"inherit"})}}else{t.unshift(c);t=incrementNodeInspectorPort(a.execArgv).concat(t);u=o.spawn(a.execPath,t,{stdio:"inherit"})}if(!u.killed){const e=["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"];e.forEach((e=>{a.on(e,(()=>{if(u.killed===false&&u.exitCode===null){u.kill(e)}}))}))}const p=this._exitCallback;u.on("close",(e=>{e=e??1;if(!p){a.exit(e)}else{p(new d(e,"commander.executeSubCommandAsync","(close)"))}}));u.on("error",(t=>{if(t.code==="ENOENT"){const t=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory";const n=`'${c}' 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)}else if(t.code==="EACCES"){throw new Error(`'${c}' not executable`)}if(!p){a.exit(1)}else{const e=new d(1,"commander.executeSubCommandAsync","(error)");e.nestedError=t;p(e)}}));this.runningCommand=u}_dispatchSubcommand(e,t,n){const s=this._findCommand(e);if(!s)this.help({error:true});let o;o=this._chainOrCallSubCommandHook(o,s,"preSubcommand");o=this._chainOrCall(o,(()=>{if(s._executableHandler){this._executeSubCommand(s,t.concat(n))}else{return s._parseCommand(t,n)}}));return o}_dispatchHelpCommand(e){if(!e){this.help()}const t=this._findCommand(e);if(t&&!t._executableHandler){t.help()}return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach(((e,t)=>{if(e.required&&this.args[t]==null){this.missingArgument(e.name())}}));if(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic){return}if(this.args.length>this.registeredArguments.length){this._excessArguments(this.args)}}_processArguments(){const myParseArg=(e,t,n)=>{let s=t;if(t!==null&&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 e=[];this.registeredArguments.forEach(((t,n)=>{let s=t.defaultValue;if(t.variadic){if(n<this.args.length){s=this.args.slice(n);if(t.parseArg){s=s.reduce(((e,n)=>myParseArg(t,n,e)),t.defaultValue)}}else if(s===undefined){s=[]}}else if(n<this.args.length){s=this.args[n];if(t.parseArg){s=myParseArg(t,s,t.defaultValue)}}e[n]=s}));this.processedArgs=e}_chainOrCall(e,t){if(e&&e.then&&typeof e.then==="function"){return e.then((()=>t()))}return t()}_chainOrCallHooks(e,t){let n=e;const s=[];this._getCommandAndAncestors().reverse().filter((e=>e._lifeCycleHooks[t]!==undefined)).forEach((e=>{e._lifeCycleHooks[t].forEach((t=>{s.push({hookedCommand:e,callback:t})}))}));if(t==="postAction"){s.reverse()}s.forEach((e=>{n=this._chainOrCall(n,(()=>e.callback(e.hookedCommand,this)))}));return n}_chainOrCallSubCommandHook(e,t,n){let s=e;if(this._lifeCycleHooks[n]!==undefined){this._lifeCycleHooks[n].forEach((e=>{s=this._chainOrCall(s,(()=>e(this,t)))}))}return s}_parseCommand(e,t){const n=this.parseOptions(t);this._parseOptionsEnv();this._parseOptionsImplied();e=e.concat(n.operands);t=n.unknown;this.args=e.concat(t);if(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){this._outputHelpIfRequested(t);return this._dispatchSubcommand(this._defaultCommandName,e,t)}if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName){this.help({error:true})}this._outputHelpIfRequested(n.unknown);this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();const checkForUnknownOptions=()=>{if(n.unknown.length>0){this.unknownOption(n.unknown[0])}};const s=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions();this._processArguments();let n;n=this._chainOrCallHooks(n,"preAction");n=this._chainOrCall(n,(()=>this._actionHandler(this.processedArgs)));if(this.parent){n=this._chainOrCall(n,(()=>{this.parent.emit(s,e,t)}))}n=this._chainOrCallHooks(n,"postAction");return n}if(this.parent&&this.parent.listenerCount(s)){checkForUnknownOptions();this._processArguments();this.parent.emit(s,e,t)}else if(e.length){if(this._findCommand("*")){return this._dispatchSubcommand("*",e,t)}if(this.listenerCount("command:*")){this.emit("command:*",e,t)}else if(this.commands.length){this.unknownCommand()}else{checkForUnknownOptions();this._processArguments()}}else if(this.commands.length){checkForUnknownOptions();this.help({error:true})}else{checkForUnknownOptions();this._processArguments()}}_findCommand(e){if(!e)return undefined;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=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===undefined){e.missingMandatoryOptionValue(t)}}))}))}_checkForConflictingLocalOptions(){const e=this.options.filter((e=>{const t=e.attributeName();if(this.getOptionValue(t)===undefined){return false}return this.getOptionValueSource(t)!=="default"}));const t=e.filter((e=>e.conflictsWith.length>0));t.forEach((t=>{const n=e.find((e=>t.conflictsWith.includes(e.attributeName())));if(n){this._conflictingOption(t,n)}}))}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e=>{e._checkForConflictingLocalOptions()}))}parseOptions(e){const t=[];const n=[];let s=t;const o=e.slice();function maybeOption(e){return e.length>1&&e[0]==="-"}let i=null;while(o.length){const e=o.shift();if(e==="--"){if(s===n)s.push(e);s.push(...o);break}if(i&&!maybeOption(e)){this.emit(`option:${i.name()}`,e);continue}i=null;if(maybeOption(e)){const t=this._findOption(e);if(t){if(t.required){const e=o.shift();if(e===undefined)this.optionMissingArgument(t);this.emit(`option:${t.name()}`,e)}else if(t.optional){let e=null;if(o.length>0&&!maybeOption(o[0])){e=o.shift()}this.emit(`option:${t.name()}`,e)}else{this.emit(`option:${t.name()}`)}i=t.variadic?t:null;continue}}if(e.length>2&&e[0]==="-"&&e[1]!=="-"){const t=this._findOption(`-${e[1]}`);if(t){if(t.required||t.optional&&this._combineFlagAndOptionalValue){this.emit(`option:${t.name()}`,e.slice(2))}else{this.emit(`option:${t.name()}`);o.unshift(`-${e.slice(2)}`)}continue}}if(/^--[^=]+=/.test(e)){const t=e.indexOf("=");const n=this._findOption(e.slice(0,t));if(n&&(n.required||n.optional)){this.emit(`option:${n.name()}`,e.slice(t+1));continue}}if(maybeOption(e)){s=n}if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(e)){t.push(e);if(o.length>0)n.push(...o);break}else if(this._getHelpCommand()&&e===this._getHelpCommand().name()){t.push(e);if(o.length>0)t.push(...o);break}else if(this._defaultCommandName){n.push(e);if(o.length>0)n.push(...o);break}}if(this._passThroughOptions){s.push(e);if(o.length>0)s.push(...o);break}s.push(e)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){const e={};const 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);if(typeof this._showHelpAfterError==="string"){this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`)}else if(this._showHelpAfterError){this._outputConfiguration.writeErr("\n");this.outputHelp({error:true})}const n=t||{};const s=n.exitCode||1;const 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();if(this.getOptionValue(t)===undefined||["default","config","env"].includes(this.getOptionValueSource(t))){if(e.required||e.optional){this.emit(`optionEnv:${e.name()}`,a.env[e.envVar])}else{this.emit(`optionEnv:${e.name()}`)}}}}))}_parseOptionsImplied(){const e=new h(this.options);const hasCustomOptionValue=e=>this.getOptionValue(e)!==undefined&&!["default","implied"].includes(this.getOptionValueSource(e));this.options.filter((t=>t.implied!==undefined&&hasCustomOptionValue(t.attributeName())&&e.valueFromOption(this.getOptionValue(t.attributeName()),t))).forEach((e=>{Object.keys(e.implied).filter((e=>!hasCustomOptionValue(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 findBestOptionFromValue=e=>{const t=e.attributeName();const n=this.getOptionValue(t);const s=this.options.find((e=>e.negate&&t===e.attributeName()));const o=this.options.find((e=>!e.negate&&t===e.attributeName()));if(s&&(s.presetArg===undefined&&n===false||s.presetArg!==undefined&&n===s.presetArg)){return s}return o||e};const getErrorMessage=e=>{const t=findBestOptionFromValue(e);const n=t.attributeName();const s=this.getOptionValueSource(n);if(s==="env"){return`environment variable '${t.envVar}'`}return`option '${t.flags}'`};const n=`error: ${getErrorMessage(e)} cannot be used with ${getErrorMessage(t)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[];let 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;const n=t===1?"":"s";const s=this.parent?` for '${this.name()}'`:"";const o=`error: too many arguments${s}. 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());if(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(e===undefined)return this._version;this._version=e;t=t||"-V, --version";n=n||"output the version number";const s=this.createOption(t,n);this._versionOptionName=s.attributeName();this._registerOption(s);this.on("option:"+s.name(),(()=>{this._outputConfiguration.writeOut(`${e}\n`);this._exit(0,"commander.version",e)}));return this}description(e,t){if(e===undefined&&t===undefined)return this._description;this._description=e;if(t){this._argsDescription=t}return this}summary(e){if(e===undefined)return this._summary;this._summary=e;return this}alias(e){if(e===undefined)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler){t=this.commands[this.commands.length-1]}if(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}'`)}t._aliases.push(e);return this}aliases(e){if(e===undefined)return this._aliases;e.forEach((e=>this.alias(e)));return this}usage(e){if(e===undefined){if(this._usage)return this._usage;const e=this.registeredArguments.map((e=>l(e)));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}this._usage=e;return this}name(e){if(e===undefined)return this._name;this._name=e;return this}nameFromFilename(e){this._name=i.basename(e,i.extname(e));return this}executableDir(e){if(e===undefined)return this._executableDir;this._executableDir=e;return this}helpInformation(e){const t=this.createHelp();if(t.helpWidth===undefined){t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()}return t.formatHelp(this,t)}_getHelpContext(e){e=e||{};const t={error:!!e.error};let n;if(t.error){n=e=>this._outputConfiguration.writeErr(e)}else{n=e=>this._outputConfiguration.writeOut(e)}t.write=e.write||n;t.command=this;return t}outputHelp(e){let t;if(typeof e==="function"){t=e;e=undefined}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);if(typeof s!=="string"&&!Buffer.isBuffer(s)){throw new Error("outputHelp callback must return a string or a Buffer")}}n.write(s);if(this._getHelpOption()?.long){this.emit(this._getHelpOption().long)}this.emit("afterHelp",n);this._getCommandAndAncestors().forEach((e=>e.emit("afterAllHelp",n)))}helpOption(e,t){if(typeof e==="boolean"){if(e){this._helpOption=this._helpOption??undefined}else{this._helpOption=null}return this}e=e??"-h, --help";t=t??"display help for command";this._helpOption=this.createOption(e,t);return this}_getHelpOption(){if(this._helpOption===undefined){this.helpOption(undefined,undefined)}return this._helpOption}addHelpOption(e){this._helpOption=e;return this}help(e){this.outputHelp(e);let t=a.exitCode||0;if(t===0&&e&&typeof e!=="function"&&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`;this.on(s,(e=>{let n;if(typeof t==="function"){n=t({error:e.error,command:e.command})}else{n=t}if(n){e.write(`${n}\n`)}}));return this}_outputHelpIfRequested(e){const t=this._getHelpOption();const n=t&&e.find((e=>t.is(e)));if(n){this.outputHelp();this._exit(0,"commander.helpDisplayed","(outputHelp)")}}}function incrementNodeInspectorPort(e){return e.map((e=>{if(!e.startsWith("--inspect")){return e}let t;let n="127.0.0.1";let s="9229";let o;if((o=e.match(/^(--inspect(-brk)?)$/))!==null){t=o[1]}else if((o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null){t=o[1];if(/^\d+$/.test(o[3])){s=o[3]}else{n=o[3]}}else if((o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null){t=o[1];n=o[3];s=o[4]}if(t&&s!=="0"){return`${t}=${n}:${parseInt(s)+1}`}return e}))}t.Command=Command},41135:(e,t)=>{class CommanderError 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=undefined}}class InvalidArgumentError extends CommanderError{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name}}t.CommanderError=CommanderError;t.InvalidArgumentError=InvalidArgumentError},79754:(e,t,n)=>{const{humanReadableArgName:s}=n(49154);class Help{constructor(){this.helpWidth=undefined;this.sortSubcommands=false;this.sortOptions=false;this.showGlobalOptions=false}visibleCommands(e){const t=e.commands.filter((e=>!e._hidden));const n=e._getHelpCommand();if(n&&!n._hidden){t.push(n)}if(this.sortSubcommands){t.sort(((e,t)=>e.name().localeCompare(t.name())))}return t}compareOptions(e,t){const getSortKey=e=>e.short?e.short.replace(/^-/,""):e.long.replace(/^--/,"");return getSortKey(e).localeCompare(getSortKey(t))}visibleOptions(e){const t=e.options.filter((e=>!e.hidden));const n=e._getHelpOption();if(n&&!n.hidden){const s=n.short&&e._findOption(n.short);const o=n.long&&e._findOption(n.long);if(!s&&!o){t.push(n)}else if(n.long&&!o){t.push(e.createOption(n.long,n.description))}else if(n.short&&!s){t.push(e.createOption(n.short,n.description))}}if(this.sortOptions){t.sort(this.compareOptions)}return 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)}if(this.sortOptions){t.sort(this.compareOptions)}return t}visibleArguments(e){if(e._argsDescription){e.registeredArguments.forEach((t=>{t.description=t.description||e._argsDescription[t.name()]||""}))}if(e.registeredArguments.find((e=>e.description))){return e.registeredArguments}return[]}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;if(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(", ")}`)}if(e.defaultValue!==undefined){const n=e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean";if(n){t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}}if(e.presetArg!==undefined&&e.optional){t.push(`preset: ${JSON.stringify(e.presetArg)}`)}if(e.envVar!==undefined){t.push(`env: ${e.envVar}`)}if(t.length>0){return`${e.description} (${t.join(", ")})`}return e.description}argumentDescription(e){const t=[];if(e.argChoices){t.push(`choices: ${e.argChoices.map((e=>JSON.stringify(e))).join(", ")}`)}if(e.defaultValue!==undefined){t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(t.length>0){const n=`(${t.join(", ")})`;if(e.description){return`${e.description} ${n}`}return n}return e.description}formatHelp(e,t){const n=t.padWidth(e,t);const s=t.helpWidth||80;const o=2;const i=2;function formatItem(e,r){if(r){const a=`${e.padEnd(n+i)}${r}`;return t.wrap(a,s-o,n+i)}return e}function formatList(e){return e.join("\n").replace(/^/gm," ".repeat(o))}let r=[`Usage: ${t.commandUsage(e)}`,""];const a=t.commandDescription(e);if(a.length>0){r=r.concat([t.wrap(a,s,0),""])}const c=t.visibleArguments(e).map((e=>formatItem(t.argumentTerm(e),t.argumentDescription(e))));if(c.length>0){r=r.concat(["Arguments:",formatList(c),""])}const l=t.visibleOptions(e).map((e=>formatItem(t.optionTerm(e),t.optionDescription(e))));if(l.length>0){r=r.concat(["Options:",formatList(l),""])}if(this.showGlobalOptions){const n=t.visibleGlobalOptions(e).map((e=>formatItem(t.optionTerm(e),t.optionDescription(e))));if(n.length>0){r=r.concat(["Global Options:",formatList(n),""])}}const d=t.visibleCommands(e).map((e=>formatItem(t.subcommandTerm(e),t.subcommandDescription(e))));if(d.length>0){r=r.concat(["Commands:",formatList(d),""])}return 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=" \\f\\t\\v - \ufeff";const i=new RegExp(`[\\n][${o}]+`);if(e.match(i))return e;const r=t-n;if(r<s)return e;const a=e.slice(0,n);const c=e.slice(n).replace("\r\n","\n");const l=" ".repeat(n);const d="";const u=`\\s${d}`;const p=new RegExp(`\n|.{1,${r-1}}([${u}]|$)|[^${u}]+?([${u}]|$)`,"g");const h=c.match(p)||[];return a+h.map(((e,t)=>{if(e==="\n")return"";return(t>0?l:"")+e.trimEnd()})).join("\n")}}t.Help=Help},45240:(e,t,n)=>{const{InvalidArgumentError:s}=n(41135);class Option{constructor(e,t){this.flags=e;this.description=t||"";this.required=e.includes("<");this.optional=e.includes("[");this.variadic=/\w\.\.\.[>\]]$/.test(e);this.mandatory=false;const n=splitOptionFlags(e);this.short=n.shortFlag;this.long=n.longFlag;this.negate=false;if(this.long){this.negate=this.long.startsWith("--no-")}this.defaultValue=undefined;this.defaultValueDescription=undefined;this.presetArg=undefined;this.envVar=undefined;this.parseArg=undefined;this.hidden=false;this.argChoices=undefined;this.conflictsWith=[];this.implied=undefined}default(e,t){this.defaultValue=e;this.defaultValueDescription=t;return this}preset(e){this.presetArg=e;return this}conflicts(e){this.conflictsWith=this.conflictsWith.concat(e);return this}implies(e){let t=e;if(typeof e==="string"){t={[e]:true}}this.implied=Object.assign(this.implied||{},t);return this}env(e){this.envVar=e;return this}argParser(e){this.parseArg=e;return this}makeOptionMandatory(e=true){this.mandatory=!!e;return this}hideHelp(e=true){this.hidden=!!e;return this}_concatValue(e,t){if(t===this.defaultValue||!Array.isArray(t)){return[e]}return t.concat(e)}choices(e){this.argChoices=e.slice();this.parseArg=(e,t)=>{if(!this.argChoices.includes(e)){throw new s(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(e,t)}return e};return this}name(){if(this.long){return this.long.replace(/^--/,"")}return this.short.replace(/^-/,"")}attributeName(){return camelcase(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class DualOptions{constructor(e){this.positiveOptions=new Map;this.negativeOptions=new Map;this.dualOptions=new Set;e.forEach((e=>{if(e.negate){this.negativeOptions.set(e.attributeName(),e)}else{this.positiveOptions.set(e.attributeName(),e)}}));this.negativeOptions.forEach(((e,t)=>{if(this.positiveOptions.has(t)){this.dualOptions.add(t)}}))}valueFromOption(e,t){const n=t.attributeName();if(!this.dualOptions.has(n))return true;const s=this.negativeOptions.get(n).presetArg;const o=s!==undefined?s:false;return t.negate===(o===e)}}function camelcase(e){return e.split("-").reduce(((e,t)=>e+t[0].toUpperCase()+t.slice(1)))}function splitOptionFlags(e){let t;let n;const s=e.split(/[ |,]+/);if(s.length>1&&!/^[[<]/.test(s[1]))t=s.shift();n=s.shift();if(!t&&/^-[^-]$/.test(n)){t=n;n=undefined}return{shortFlag:t,longFlag:n}}t.Option=Option;t.DualOptions=DualOptions},65030:(e,t)=>{const n=3;function editDistance(e,t){if(Math.abs(e.length-t.length)>n)return Math.max(e.length,t.length);const s=[];for(let t=0;t<=e.length;t++){s[t]=[t]}for(let e=0;e<=t.length;e++){s[0][e]=e}for(let n=1;n<=t.length;n++){for(let o=1;o<=e.length;o++){let i=1;if(e[o-1]===t[n-1]){i=0}else{i=1}s[o][n]=Math.min(s[o-1][n]+1,s[o][n-1]+1,s[o-1][n-1]+i);if(o>1&&n>1&&e[o-1]===t[n-2]&&e[o-2]===t[n-1]){s[o][n]=Math.min(s[o][n],s[o-2][n-2]+1)}}}return s[e.length][t.length]}function suggestSimilar(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));const s=e.startsWith("--");if(s){e=e.slice(2);t=t.map((e=>e.slice(2)))}let o=[];let i=n;const r=.4;t.forEach((t=>{if(t.length<=1)return;const n=editDistance(e,t);const s=Math.max(e.length,t.length);const a=(s-n)/s;if(a>r){if(n<i){i=n;o=[t]}else if(n===i){o.push(t)}}}));o.sort(((e,t)=>e.localeCompare(t)));if(s){o=o.map((e=>`--${e}`))}if(o.length>1){return`\n(Did you mean one of ${o.join(", ")}?)`}if(o.length===1){return`\n(Did you mean ${o[0]}?)`}return""}t.suggestSimilar=suggestSimilar}};var t={};function __nccwpck_require__(n){var s=t[n];if(s!==undefined){return s.exports}var o=t[n]={exports:{}};var i=true;try{e[n].call(o.exports,o,o.exports,__nccwpck_require__);i=false}finally{if(i)delete t[n]}return o.exports}__nccwpck_require__.m=e;(()=>{var e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;var t;__nccwpck_require__.t=function(n,s){if(s&1)n=this(n);if(s&8)return n;if(typeof n==="object"&&n){if(s&4&&n.__esModule)return n;if(s&16&&typeof n.then==="function")return n}var o=Object.create(null);__nccwpck_require__.r(o);var i={};t=t||[null,e({}),e([]),e(e)];for(var r=s&2&&n;typeof r=="object"&&!~t.indexOf(r);r=e(r)){Object.getOwnPropertyNames(r).forEach((e=>i[e]=()=>n[e]))}i["default"]=()=>n;__nccwpck_require__.d(o,i);return o}})();(()=>{__nccwpck_require__.d=(e,t)=>{for(var n in t){if(__nccwpck_require__.o(t,n)&&!__nccwpck_require__.o(e,n)){Object.defineProperty(e,n,{enumerable:true,get:t[n]})}}}})();(()=>{__nccwpck_require__.f={};__nccwpck_require__.e=e=>Promise.all(Object.keys(__nccwpck_require__.f).reduce(((t,n)=>{__nccwpck_require__.f[n](e,t);return t}),[]))})();(()=>{__nccwpck_require__.u=e=>""+e+".index.js"})();(()=>{__nccwpck_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)})();(()=>{__nccwpck_require__.r=e=>{if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(e,"__esModule",{value:true})}})();if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";(()=>{var e={792:1};var installChunk=t=>{var n=t.modules,s=t.ids,o=t.runtime;for(var i in n){if(__nccwpck_require__.o(n,i)){__nccwpck_require__.m[i]=n[i]}}if(o)o(__nccwpck_require__);for(var r=0;r<s.length;r++)e[s[r]]=1};__nccwpck_require__.f.require=(t,n)=>{if(!e[t]){if(true){installChunk(require("./"+__nccwpck_require__.u(t)))}else e[t]=1}}})();var n={};(()=>{"use strict";var e=n;Object.defineProperty(e,"__esModule",{value:true});const t=__nccwpck_require__(18909);const s=__nccwpck_require__(11627);const o=__nccwpck_require__(19218);const i=__nccwpck_require__(38706);const r=__nccwpck_require__(5596);const a=__nccwpck_require__(97499);const c=__nccwpck_require__(46222);const l=__nccwpck_require__(67378);const d=__nccwpck_require__(67509);const u=__nccwpck_require__(46183);const p=__nccwpck_require__(96007);const h=__nccwpck_require__(8784);const m=__nccwpck_require__(91262);const f=__nccwpck_require__(83969);const g=__nccwpck_require__(85417);const y=__nccwpck_require__(40791);const $=__nccwpck_require__(22835);const k=__nccwpck_require__(60952);const b=__nccwpck_require__(40239);const w=__nccwpck_require__(8045);const _=__nccwpck_require__(28423);const S=__nccwpck_require__(96616);const v=__nccwpck_require__(44040);const x=__nccwpck_require__(45475);const C=__nccwpck_require__(63746);const O=__nccwpck_require__(44478);const I=__nccwpck_require__(18691);const P=__nccwpck_require__(34362);const T=__nccwpck_require__(80928);const E=__nccwpck_require__(58211);const A=__nccwpck_require__(43423);const M=__nccwpck_require__(72768);const R=__nccwpck_require__(9708);const L=__nccwpck_require__(33766);const N=__nccwpck_require__(50984);const D=__nccwpck_require__(69903);const F=__nccwpck_require__(35344);const q=__nccwpck_require__(71783);const K=__nccwpck_require__(91993);const j=__nccwpck_require__(81466);const U=__nccwpck_require__(50869);const z=__nccwpck_require__(87604);const H=__nccwpck_require__(65240);const B=__nccwpck_require__(23017);const J=__nccwpck_require__(84436);const W=__nccwpck_require__(15472);const G=__nccwpck_require__(52072);const X=__nccwpck_require__(33192);const Y=__nccwpck_require__(30896);const V=__nccwpck_require__(72124);const Q=__nccwpck_require__(99236);const Z=__nccwpck_require__(93402);const ee=__nccwpck_require__(64115);(0,s.applyConfig)();(0,Z.checkForUpdates)();const te=new t.Command;const ne=`\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`;te.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 ne;const{Help:n}=__nccwpck_require__(18909);const s=new n;return s.formatHelp(e,t)}}).action((async()=>{await interactiveEntry()}));async function interactiveEntry(){if(!process.stdin.isTTY){console.log(ne);return}const e=await Promise.resolve().then(__nccwpck_require__.t.bind(__nccwpck_require__,23785,23));if((0,s.isConfigured)()){try{const e=new o.SFClient;const{theses:t}=await e.listTheses();const n=(t||[]).filter((e=>e.status==="active"));if(n.length>0){await(0,f.agentCommand)(n[0].id,{});return}}catch{await(0,f.agentCommand)(undefined,{});return}}console.log();console.log(" [1mSimpleFunctions[22m — prediction market intelligence");console.log();if((0,s.isConfigured)()){console.log(" [2mYou have no active theses.[22m")}else{console.log(" [2mNo login needed to explore.[22m")}console.log();const t=e.createInterface({input:process.stdin,output:process.stdout,terminal:true});const n=await new Promise((e=>{t.question(" What's your market view? (keyword or thesis)\n [36m>[39m ",(n=>{t.close();e(n.trim())}))}));if(!n){console.log(ne);return}let i=n.replace(/[^\w\s]/g," ").split(/\s+/).filter((e=>e.length>2)).slice(0,5).join(" ");if(!i)i=n.trim().slice(0,40);console.log();console.log(` [2mScanning Kalshi + Polymarket for: "${i}"...[22m`);console.log();try{const{scanCommand:e}=await Promise.resolve().then(__nccwpck_require__.bind(__nccwpck_require__,46183));await e(i,{json:false})}catch(e){console.error(` [31mScan failed: ${e.message}[39m`)}console.log();if((0,s.isConfigured)()){console.log(" [2mWant to monitor this thesis 24/7?[22m");console.log(` [36msf create[39m "${n.slice(0,60)}"`)}else{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"]);te.hook("preAction",((e,t)=>{const n=t.name();if(se.has(n))return;const o=e.optsWithGlobals?.()||e.opts();if(o.apiKey)return;if(!(0,s.isConfigured)()){const e=process.argv.includes("--json");if(e){console.log(JSON.stringify({error:"API key required.",code:"NOT_CONFIGURED",keyUrl:"https://simplefunctions.dev/dashboard/keys",cli:"sf login"}))}else{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)}}));te.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 run((()=>(0,g.setupCommand)({check:e.check,reset:e.reset,key:e.key,enableTrading:e.enableTrading,disableTrading:e.disableTrading,kalshi:e.kalshi,polymarket:e.polymarket})))}));te.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 run((()=>(0,U.loginCommand)({apiUrl:n.apiUrl,force:e.force})))}));te.command("logout").description("Clear saved credentials").action((async()=>{await run((async()=>{const{resetConfig:e,loadFileConfig:t}=await Promise.resolve().then(__nccwpck_require__.t.bind(__nccwpck_require__,11627,23));const n=t();if(!n.apiKey){console.log(`\n ${Q.c.dim}Not logged in.${Q.c.reset}\n`);return}e();console.log(`\n Logged out. Credentials removed from ~/.sf/config.json`);console.log(` ${Q.c.dim}Run ${Q.c.cyan}sf login${Q.c.dim} to re-authenticate.${Q.c.reset}\n`)}))}));te.command("update").description("Update CLI to latest version").action((async()=>{await run((()=>(0,ee.updateCommand)()))}));te.command("status").description("Health check: verify API, auth, Kalshi, Polymarket connections").option("--json","JSON output").action((async e=>{await run((()=>(0,V.statusCommand)({json:e.json})))}));te.command("list").description("List all theses").option("--json","JSON output").action((async(e,t)=>{const n=t.optsWithGlobals();await run((()=>(0,i.listCommand)({json:e.json,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.command("get <id>").description("Get full thesis details").option("--json","Output raw JSON").action((async(e,t,n)=>{const s=n.optsWithGlobals();await run((()=>(0,r.getCommand)(e,{json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,a.contextCommand)(e,{json:t.json,share:t.share,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,c.createCommand)(e,{async:t.async,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,l.signalCommand)(e,t,{type:n.type,json:n.json,apiKey:o.apiKey,apiUrl:o.apiUrl})))}));te.command("evaluate <id>").description("Trigger a deep evaluation (heavy model, force-heavy mode)").action((async(e,t,n)=>{const s=n.optsWithGlobals();await run((()=>(0,d.evaluateCommand)(e,{apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>{const n=new o.SFClient(s.apiKey,s.apiUrl);return(0,z.heartbeatCommand)(n,e,{newsInterval:t.newsInterval,xInterval:t.xInterval,model:t.model,budget:t.budget,pause:t.pause,resume:t.resume})}))}));te.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();const o=e||"";if(!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 run((()=>(0,u.scanCommand)(o,{series:t.series,market:t.market,venue:t.venue,json:t.json,share:t.share,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,p.watchCommand)(e,t,{interval:n.interval,json:n.json,thesis:n.thesis,smart:n.smart,execute:n.execute})))}));te.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 run((()=>(0,m.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})))}));te.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 run((()=>(0,h.positionsCommand)({json:e.json,thesis:e.thesis,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.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)=>{const s=n.optsWithGlobals();await run((()=>(0,f.agentCommand)(e,{model:t.model,modelKey:t.modelKey,newSession:t.new,noTui:t.plain})))}));te.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 run((()=>(0,y.publishCommand)(e,{slug:t.slug,description:t.description,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.command("unpublish <thesisId>").description("Remove a thesis from public viewing").action((async(e,t,n)=>{const s=n.optsWithGlobals();await run((()=>(0,y.unpublishCommand)(e,{apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,$.exploreCommand)(e,{json:t.json,share:t.share})))}));te.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 run((()=>(0,k.dashboardCommand)({json:e.json,once:e.once,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.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 run((()=>(0,w.milestonesCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.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 run((()=>(0,_.forecastCommand)(e,t)))}));te.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 run((()=>(0,S.settlementsCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.command("balance").description("Kalshi account balance").option("--json","JSON output").action((async e=>{await run((()=>(0,v.balanceCommand)(e)))}));te.command("orders").description("Kalshi resting orders").option("--status <status>","Order status filter (default: resting)","resting").option("--json","JSON output").action((async e=>{await run((()=>(0,x.ordersCommand)(e)))}));te.command("fills").description("Recent trade fills").option("--ticker <ticker>","Filter by market ticker").option("--json","JSON output").action((async e=>{await run((()=>(0,C.fillsCommand)(e)))}));te.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 run((()=>(0,O.feedCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.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 run((()=>(0,j.deltaCommand)(e,{...t,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,I.whatifCommand)(e,{set:t.set,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.command("schedule").description("Exchange status and trading hours").option("--json","JSON output").action((async e=>{await run((()=>(0,E.scheduleCommand)(e)))}));te.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 run((()=>(0,P.buyCommand)(e,t,n)))}));te.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 run((()=>(0,P.sellCommand)(e,t,n)))}));te.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 run((()=>(0,T.cancelCommand)(e,t)))}));te.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 run((()=>(0,A.rfqCommand)(e,t,n)))}));te.command("announcements").description("Exchange announcements (rule changes, maintenance)").option("--json","JSON output").action((async e=>{await run((()=>(0,M.announcementsCommand)(e)))}));te.command("history <ticker>").description("Historical market data (settled/closed)").option("--json","JSON output").action((async(e,t)=>{await run((()=>(0,R.historyCommand)(e,t)))}));te.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 run((()=>(0,L.performanceCommand)(e)))}));te.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 run((()=>(0,N.liquidityCommand)({...t,topic:e})))}));te.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)=>{if(e.length===0&&!t.poly){console.error('Usage: sf book <ticker> [ticker2...] OR sf book --poly "oil price"');process.exit(1)}await run((()=>(0,D.bookCommand)(e,t)))}));te.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 run((()=>(0,F.promptCommand)(e,{sections:t.sections,maxLength:t.maxLength,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,q.augmentCommand)(e,{dryRun:t.dryRun,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,B.marketsCommand)({json:e.json,share:e.share})))}));te.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 run((()=>(0,H.queryCommand)(e,{json:t.json,share:t.share,limit:t.limit})))}));te.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 run((()=>(0,K.telegramCommand)(e)))}));te.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 run((()=>(0,J.xSearchCommand)(e,t)))}));te.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 run((()=>(0,J.xVolumeCommand)(e,t)))}));te.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 run((()=>(0,J.xNewsCommand)(e,t)))}));te.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 run((()=>(0,J.xAccountCommand)(e,t)))}));te.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 run((()=>(0,X.worldCommand)(e)))}));te.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 run((()=>(0,Y.ideasCommand)(e)))}));(0,b.registerStrategies)(te);(0,W.registerIntents)(te);(0,G.registerRuntime)(te);async function run(e){try{await e()}catch(e){const t=e instanceof Error?e.message:String(e);if(process.argv.includes("--json")){console.log(JSON.stringify({error:t,code:e.code||"CLI_ERROR",status:e.status||1}));process.exit(1)}(0,Q.die)(t)}}te.parse()})();module.exports=n})();
|
|
2
|
+
(()=>{var e={93402:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.checkForUpdates=checkForUpdates;const s=n(79896);const o=n(16928);const i=n(70857);const r=n(35317);const a="@spfunctions/cli";const c=(0,o.join)((0,i.homedir)(),".sf","update-check.json");const l=60*60*1e3;function readCache(){try{if((0,s.existsSync)(c))return JSON.parse((0,s.readFileSync)(c,"utf-8"))}catch{}return{lastCheck:0,latestVersion:null}}function semverLt(e,t){const n=e.replace(/^v/,"").split(".").map(Number);const s=t.replace(/^v/,"").split(".").map(Number);for(let e=0;e<3;e++){if((n[e]||0)<(s[e]||0))return true;if((n[e]||0)>(s[e]||0))return false}return false}function getCurrentVersion(){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"}function checkForUpdates(){const e=getCurrentVersion();const t=readCache();if(t.latestVersion&&semverLt(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 `;const s=(0,r.spawn)(process.execPath,["-e",n],{detached:true,stdio:"ignore"});s.unref()}},87783:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.cached=cached;t.invalidate=invalidate;t.invalidateAll=invalidateAll;const n=new Map;async function cached(e,t,s){const o=n.get(e);if(o&&Date.now()<o.expiry)return o.data;try{const o=await s();n.set(e,{data:o,expiry:Date.now()+t});return o}catch(e){if(o)return o.data;throw e}}function invalidate(e){n.delete(e)}function invalidateAll(){n.clear()}},19218:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.SFClient=void 0;t.kalshiFetchAllSeries=kalshiFetchAllSeries;t.kalshiFetchEvents=kalshiFetchEvents;t.kalshiFetchMarket=kalshiFetchMarket;t.kalshiFetchMarketsBySeries=kalshiFetchMarketsBySeries;t.kalshiFetchMarketsByEvent=kalshiFetchMarketsByEvent;t.fetchGlobalContext=fetchGlobalContext;t.fetchQuery=fetchQuery;t.fetchTraditionalMarkets=fetchTraditionalMarkets;const n="https://simplefunctions.dev";const s="https://api.elections.kalshi.com/trade-api/v2";class SFClient{apiKey;baseUrl;constructor(e,t){this.apiKey=e||process.env.SF_API_KEY||"";this.baseUrl=(t||process.env.SF_API_URL||n).replace(/\/$/,"");if(!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}`;const o={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"};const i=await fetch(s,{method:e,headers:o,body:n?JSON.stringify(n):undefined});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}`);t.status=i.status;t.code=e?.code||`HTTP_${i.status}`;t.details=e;throw 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=true){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=false){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;if(e?.status)t.set("status",e.status);if(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";const s=t?.hours||24;const 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;const 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(/^@/,"");const s=t?.hours||24;const o=t?.limit||20;return this.request("GET",`/api/x/account?username=${n}&hours=${s}&limit=${o}`)}}t.SFClient=SFClient;async function kalshiGet(e,t){const n=new URL(`${s}${e}`);if(t){for(const[e,s]of Object.entries(t)){if(s!==undefined&&s!=="")n.searchParams.set(e,s)}}const o=await fetch(n.toString());if(!o.ok){throw new Error(`Kalshi API ${o.status}: ${await o.text()}`)}return o.json()}async function kalshiFetchAllSeries(){const e=await kalshiGet("/series",{include_volume:"true"});return e.series||[]}async function kalshiFetchEvents(e){const t=await kalshiGet("/events",{series_ticker:e,status:"open",with_nested_markets:"true",limit:"200"});return t.events||[]}async function kalshiFetchMarket(e){const t=await kalshiGet(`/markets/${e}`);return t.market||t}async function kalshiFetchMarketsBySeries(e){const t=await kalshiGet("/markets",{series_ticker:e,status:"open",limit:"200"});return t.markets||[]}async function kalshiFetchMarketsByEvent(e){const t=await kalshiGet("/markets",{event_ticker:e,status:"open",limit:"1000"});return t.markets||[]}const o="https://simplefunctions.dev";async function fetchGlobalContext(){const e=await fetch(`${o}/api/public/context`);if(!e.ok)throw new Error(`Context API error: ${e.status}`);return e.json()}async function fetchQuery(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()}async function fetchTraditionalMarkets(e){const t=e?`?topic=${encodeURIComponent(e)}`:"";const n=await fetch(`${o}/api/public/markets${t}`);if(!n.ok)throw new Error(`Markets API error: ${n.status}`);return n.json()}},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:true});t.agentCommand=agentCommand;const o=s(n(79896));const i=s(n(16928));const r=s(n(70857));const a=n(19218);const c=n(96139);const l=n(34331);const d=n(97325);const u=n(11627);const p=n(40101);function getSessionDir(){return i.default.join(r.default.homedir(),".sf","sessions")}function getSessionPath(e){return i.default.join(getSessionDir(),`${e}.json`)}function loadSession(e){const t=getSessionPath(e);try{if(o.default.existsSync(t)){return JSON.parse(o.default.readFileSync(t,"utf-8"))}}catch{}return null}function saveSession(e,t,n){const s=getSessionDir();o.default.mkdirSync(s,{recursive:true});o.default.writeFileSync(getSessionPath(e),JSON.stringify({thesisId:e,model:t,updatedAt:(new Date).toISOString(),messages:n},null,2))}const rgb=(e,t,n)=>s=>`[38;2;${e};${t};${n}m${s}[39m`;const bgRgb=(e,t,n)=>s=>`[48;2;${e};${t};${n}m${s}[49m`;const bold=e=>`[1m${e}[22m`;const dim=e=>`[2m${e}[22m`;const italic=e=>`[3m${e}[23m`;const underline=e=>`[4m${e}[24m`;const strikethrough=e=>`[9m${e}[29m`;const h={emerald:rgb(16,185,129),zinc200:rgb(228,228,231),zinc400:rgb(161,161,170),zinc600:rgb(82,82,91),zinc800:rgb(39,39,42),red:rgb(239,68,68),amber:rgb(245,158,11),white:rgb(255,255,255),bgZinc900:bgRgb(24,24,27),bgZinc800:bgRgb(39,39,42)};function createMutableLine(e){const{truncateToWidth:t,visibleWidth:n}=e;return class MutableLine{text;cachedWidth;cachedLines;constructor(e){this.text=e}setText(e){this.text=e;this.cachedWidth=undefined;this.cachedLines=undefined}invalidate(){this.cachedWidth=undefined;this.cachedLines=undefined}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;this.cachedWidth=e;this.cachedLines=[t(this.text,e)];return this.cachedLines}}}function createHeaderBar(e){const{truncateToWidth:t,visibleWidth:n}=e;return class HeaderBar{thesisId="";confidence=0;confidenceDelta=0;pnlDollars=0;positionCount=0;edgeCount=0;topEdge="";cachedWidth;cachedLines;setFromContext(e,t){this.thesisId=(e.thesisId||"").slice(0,8);this.confidence=typeof e.confidence==="number"?Math.round(e.confidence*100):typeof e.confidence==="string"?Math.round(parseFloat(e.confidence)*100):0;this.confidenceDelta=e.lastEvaluation?.confidenceDelta?Math.round(e.lastEvaluation.confidenceDelta*100):0;this.edgeCount=(e.edges||[]).length;const n=e.edges||[];if(n.length>0){const e=[...n].sort(((e,t)=>Math.abs(t.edge||t.edgeSize||0)-Math.abs(e.edge||e.edgeSize||0)))[0];const t=(e.market||e.marketTitle||e.marketId||"").slice(0,20);const s=e.edge||e.edgeSize||0;this.topEdge=`${t} ${s>0?"+":""}${Math.round(s)}¢`}if(t&&t.length>0){this.positionCount=t.length;this.pnlDollars=t.reduce(((e,t)=>{const n=t.unrealized_pnl||0;return e+n}),0)/100}this.cachedWidth=undefined;this.cachedLines=undefined}updateConfidence(e,t){this.confidence=Math.round(e*100);this.confidenceDelta=Math.round(t*100);this.cachedWidth=undefined;this.cachedLines=undefined}invalidate(){this.cachedWidth=undefined;this.cachedLines=undefined}update(e,t,n){this.cachedWidth=undefined;this.cachedLines=undefined}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;this.cachedWidth=e;const s=h.emerald(bold(this.thesisId));const o=this.confidenceDelta>0?"▲":this.confidenceDelta<0?"▼":"─";const i=this.confidenceDelta>0?h.emerald:this.confidenceDelta<0?h.red:h.zinc600;const r=this.confidenceDelta!==0?` (${this.confidenceDelta>0?"+":""}${this.confidenceDelta})`:"";const a=i(`${o} ${this.confidence}%${r}`);let c="";if(this.positionCount>0){const e=this.pnlDollars>=0?h.emerald(`+$${this.pnlDollars.toFixed(2)}`):h.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);c=h.zinc600(`${this.positionCount} pos `)+e}const l=h.zinc600(`${this.edgeCount} edges`);const d=this.topEdge?h.zinc400(this.topEdge):"";const u=h.zinc600(" │ ");const p=[s,a,c,l,d].filter(Boolean);const m=p.join(u);let f=h.bgZinc900(" "+t(m,e-2,"")+" ");const g=n(f);if(g<e){f=f+h.bgZinc900(" ".repeat(e-g))}this.cachedLines=[f];return this.cachedLines}}}function createFooterBar(e){const{truncateToWidth:t,visibleWidth:n}=e;return class FooterBar{thesisId="";confidence=0;confidenceDelta=0;pnlDollars=0;positionCount=0;edgeCount=0;topEdge="";tokens=0;cost=0;toolCount=0;modelName="";tradingEnabled=false;exchangeOpen=null;cachedWidth;cachedLines;isExplorer=false;setFromContext(e,t){if(e._explorerMode){this.isExplorer=true;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=false;this.thesisId=(e.thesisId||"").slice(0,8);this.confidence=typeof e.confidence==="number"?Math.round(e.confidence*100):typeof e.confidence==="string"?Math.round(parseFloat(e.confidence)*100):0;this.confidenceDelta=e.lastEvaluation?.confidenceDelta?Math.round(e.lastEvaluation.confidenceDelta*100):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];const n=(e.market||e.marketTitle||e.marketId||"").slice(0,20);const s=e.edge||e.edgeSize||0;this.topEdge=`${n} ${s>0?"+":""}${Math.round(s)}¢`}}if(t&&t.length>0){this.positionCount=t.length;this.pnlDollars=t.reduce(((e,t)=>e+(t.unrealized_pnl||0)),0)/100}this.cachedWidth=undefined;this.cachedLines=undefined}updateConfidence(e,t){this.confidence=Math.round(e*100);this.confidenceDelta=Math.round(t*100);this.cachedWidth=undefined;this.cachedLines=undefined}invalidate(){this.cachedWidth=undefined;this.cachedLines=undefined}update(){this.cachedWidth=undefined;this.cachedLines=undefined}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;this.cachedWidth=e;const s=h.zinc600(" │ ");let o;if(this.isExplorer){const e=h.emerald(bold("Explorer"));const t=h.zinc600(`${this.edgeCount} public edges`);const n=this.topEdge?h.zinc400(this.topEdge):"";let s="";if(this.positionCount>0){const e=this.pnlDollars>=0?h.emerald(`+$${this.pnlDollars.toFixed(2)}`):h.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);s=h.zinc600(`${this.positionCount} pos `)+e}o=[e,s,t,n].filter(Boolean)}else{const e=h.emerald(this.thesisId);const t=this.confidenceDelta>0?"▲":this.confidenceDelta<0?"▼":"─";const n=this.confidenceDelta>0?h.emerald:this.confidenceDelta<0?h.red:h.zinc600;const s=this.confidenceDelta!==0?` (${this.confidenceDelta>0?"+":""}${this.confidenceDelta})`:"";const i=n(`${t} ${this.confidence}%${s}`);let r="";if(this.positionCount>0){const e=this.pnlDollars>=0?h.emerald(`+$${this.pnlDollars.toFixed(2)}`):h.red(`-$${Math.abs(this.pnlDollars).toFixed(2)}`);r=h.zinc600(`${this.positionCount} pos `)+e}const a=h.zinc600(`${this.edgeCount} edges`);const c=this.topEdge?h.zinc400(this.topEdge):"";o=[e,i,r,a,c].filter(Boolean)}let i=h.bgZinc800(" "+t(o.join(s),e-2,"")+" ");const r=n(i);if(r<e)i+=h.bgZinc800(" ".repeat(e-r));const a=h.zinc600(this.modelName.split("/").pop()||this.modelName);const c=this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:`${this.tokens}`;const l=h.zinc600(`${c} tok`);const d=this.exchangeOpen===true?h.emerald("OPEN"):this.exchangeOpen===false?h.red("CLOSED"):h.zinc600("...");const u=this.tradingEnabled?h.amber("trading"):h.zinc600("read-only");const p=h.zinc600("/help");const m=[a,l,d,u].join(s);const f=n(m);const g=n(p);const y=Math.max(1,e-f-g-2);let $=h.bgZinc900(" "+m+" ".repeat(y)+p+" ");const k=n($);if(k<e)$+=h.bgZinc900(" ".repeat(e-k));this.cachedLines=[i,$];return this.cachedLines}}}function renderCausalTree(e,t){const n=e.causalTree;if(!n?.nodes?.length)return h.zinc600(" No causal tree data");const s=[];for(const e of n.nodes){const t=e.id||"";const n=e.label||e.description||"";const o=typeof e.probability==="number"?Math.round(e.probability*100):typeof e.impliedProbability==="number"?Math.round(e.impliedProbability*100):null;const i=(t.match(/\./g)||[]).length;const r=" ".repeat(i+1);if(o!==null){const e=Math.round(o/10);const i="█".repeat(e)+"░".repeat(10-e);const a=o>=70?h.emerald:o>=40?h.amber:h.red;const c=`${r}${h.zinc600(t)} ${h.zinc400(n)} `;const l=` ${a(`${o}%`)} ${a(i)}`;s.push(c+l)}else{s.push(`${r}${h.zinc600(t)} ${h.zinc400(n)}`)}}return s.join("\n")}function renderEdges(e,t){const n=e.edges;if(!n?.length)return h.zinc600(" No edge data");const s=e._positions||[];const o=[];for(const e of n){const t=(e.market||e.marketId||"").slice(0,18).padEnd(18);const n=typeof e.marketPrice==="number"?`${e.marketPrice}¢`:"?";const i=typeof e.thesisPrice==="number"?`${e.thesisPrice}¢`:"?";const r=typeof e.edge==="number"?e.edge>0?`+${e.edge}`:`${e.edge}`:"?";const a=e.orderbook||{};const c=typeof a.spread==="number"?`${a.spread}¢`:"?";const l=a.liquidityScore||"low";const d=l==="high"?"■■■":l==="medium"?"■■ ":"■ ";const u=l==="high"?h.emerald:l==="medium"?h.amber:h.red;const p=s.find((t=>t.ticker===e.marketId||e.marketId&&t.ticker?.includes(e.marketId)));let m=h.zinc600("—");if(p){const e=p.side?.toUpperCase()||"YES";const t=typeof p.unrealized_pnl==="number"?p.unrealized_pnl>=0?h.emerald(`+$${(p.unrealized_pnl/100).toFixed(0)}`):h.red(`-$${(Math.abs(p.unrealized_pnl)/100).toFixed(0)}`):"";m=h.emerald(`${e} (${p.quantity}@${p.average_price_paid}¢ ${t})`)}o.push(` ${h.zinc200(t)} ${h.zinc400(n)} → ${h.zinc400(i)} edge ${r.includes("+")?h.emerald(r):h.red(r)} spread ${h.zinc600(c)} ${u(d)} ${u(l.padEnd(4))} ${m}`)}return o.join("\n")}function renderPositions(e){if(!e?.length)return h.zinc600(" No positions");const t=[];let n=0;for(const s of e){const e=(s.ticker||"").slice(0,18).padEnd(18);const o=(s.side||"yes").toUpperCase().padEnd(3);const i=String(s.quantity||0);const r=`${s.average_price_paid||0}¢`;const a=typeof s.current_value==="number"&&s.current_value>0?`${s.current_value}¢`:"?¢";const c=s.unrealized_pnl||0;n+=c;const l=(c/100).toFixed(2);const d=c>=0?h.emerald(`+$${l}`):h.red(`-$${Math.abs(parseFloat(l)).toFixed(2)}`);const u=c>=0?h.emerald("▲"):h.red("▼");t.push(` ${h.zinc200(e)} ${h.zinc400(o)} ${h.zinc400(i)} @ ${h.zinc400(r)} now ${h.zinc200(a)} ${d} ${u}`)}const s=(n/100).toFixed(2);t.push(h.zinc600(" "+"─".repeat(40)));t.push(n>=0?` Total P&L: ${h.emerald(bold(`+$${s}`))}`:` Total P&L: ${h.red(bold(`-$${Math.abs(parseFloat(s)).toFixed(2)}`))}`);return t.join("\n")}async function selectThesis(e,t=false){return new Promise((n=>{let s=0;const o=[];if(t){o.push({id:"_explorer",conf:-1,title:"Explorer mode — no thesis, full market access"})}for(const t of e){const e=typeof t.confidence==="number"?Math.round(t.confidence*100):0;const 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);i("[?1049h");i("[?25l");function render(){i("[H[2J");i("\n [2mSelect thesis[22m\n\n");for(let e=0;e<o.length;e++){const t=o[e];const n=e===s;const r=n?"[38;2;16;185;129m › [39m":" ";if(t.id==="_explorer"){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`;const s=`[38;2;55;55;60m${t.conf}%[39m`;const 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`)}render();if(process.stdin.isTTY)process.stdin.setRawMode(true);process.stdin.resume();process.stdin.setEncoding("utf8");const onKey=e=>{const t=Buffer.from(e);if(t[0]===27&&t[1]===91&&t[2]===65){s=(s-1+o.length)%o.length;render()}else if(t[0]===27&&t[1]===91&&t[2]===66){s=(s+1)%o.length;render()}else if(e==="k"){s=(s-1+o.length)%o.length;render()}else if(e==="j"){s=(s+1)%o.length;render()}else if(e==="\r"||e==="\n"){cleanup();n(o[s].id)}else if(t[0]===3){cleanup();process.exit(0)}};function cleanup(){process.stdin.removeListener("data",onKey);if(process.stdin.isTTY)process.stdin.setRawMode(false);process.stdin.pause();i("[?25h");i("[?1049l")}process.stdin.on("data",onKey)}))}async function agentCommand(e,t){const s=t?.modelKey||process.env.OPENROUTER_API_KEY;const o=process.env.SF_API_KEY;const i=process.env.SF_API_URL||"https://simplefunctions.dev";const r=!s&&!!o;const m=s||o;const f=r?`${i}/api/proxy`:"https://openrouter.ai/api/v1";if(!m){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){try{const e=await fetch("https://openrouter.ai/api/v1/auth/key",{headers:{Authorization:`Bearer ${m}`},signal:AbortSignal.timeout(8e3)});if(!e.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);if(!t.includes("timeout")){console.warn(`Warning: Could not verify OpenRouter key (${t}). Continuing anyway.`)}}}else{console.log(" [2mUsing SimpleFunctions LLM proxy (no OpenRouter key needed)[22m")}const g=new a.SFClient;let y=e||null;let $=false;if(!y){let e=[];try{const t=await g.listTheses();const n=t.theses||t;e=n.filter((e=>e.status==="active"))}catch{e=[]}if(e.length===0){$=true}else if(e.length===1){y=e[0].id}else if(process.stdin.isTTY&&!t?.noTui){const t=await selectThesis(e,true);if(t==="_explorer"){$=true}else{y=t}}else{y=e[0].id}}let k;if($){try{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));k=await e()}catch{k={edges:[],theses:[]}}k._explorerMode=true}else{try{k=await g.getContext(y)}catch(e){console.error(`Warning: Could not fetch thesis context (${e.message}). Starting with limited context.`);k={thesisId:y,edges:[],causalTree:{nodes:[]}}}}if(t?.noTui){return runPlainTextAgent({openrouterKey:m,sfClient:g,resolvedThesisId:y||"_explorer",latestContext:k,useProxy:r,llmBaseUrl:f,sfApiKey:o,sfApiUrl:i,opts:t})}const b=await n.e(921).then(n.bind(n,93921));const w=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641));const _=await Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653));const{TUI:S,ProcessTerminal:v,Container:x,Text:C,Markdown:O,Editor:I,Loader:P,Spacer:T,CombinedAutocompleteProvider:E,truncateToWidth:A,visibleWidth:M}=b;const{getModel:R,streamSimple:L,Type:N}=w;const{Agent:D}=_;const F=createMutableLine(b);const q=createFooterBar(b);const K=t?.model||"anthropic/claude-sonnet-4.6";let j=K.replace(/^openrouter\//,"");function resolveModel(e){let t;try{t=R("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:true,supportsTools:true}}if(r)t.baseUrl=f;return t}let U=resolveModel(j);let z=0;let H=0;let B=0;let J=false;let W=null;let G=(new Date).toISOString();let X=null;let Y=null;let V=null;const Q=new v;const Z=new S(Q);const ee={heading:e=>h.zinc200(bold(e)),link:e=>h.emerald(e),linkUrl:e=>h.zinc600(e),code:e=>h.zinc200(e),codeBlock:e=>h.zinc400(e),codeBlockBorder:e=>h.zinc600(e),quote:e=>h.zinc400(e),quoteBorder:e=>h.zinc600(e),hr:e=>h.zinc600(e),listBullet:e=>h.emerald(e),bold:e=>bold(e),italic:e=>italic(e),strikethrough:e=>strikethrough(e),underline:e=>underline(e)};const te={color:e=>h.zinc400(e)};const ne={borderColor:e=>`[38;2;50;50;55m${e}[39m`,selectList:{selectedPrefix:e=>h.emerald(e),selectedText:e=>h.zinc200(e),description:e=>h.zinc600(e),scrollInfo:e=>h.zinc600(e),noMatch:e=>h.zinc600(e)}};const se=new q;se.modelName=j;se.tradingEnabled=(0,u.loadConfig)().tradingEnabled||false;let oe=null;try{oe=await(0,c.getPositions)();if(oe){for(const e of oe){const t=await(0,c.getMarketPrice)(e.ticker);if(t!==null){e.current_value=t;e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity)}}}}catch{}se.setFromContext(k,oe||undefined);fetch("https://api.elections.kalshi.com/trade-api/v2/exchange/status",{headers:{Accept:"application/json"}}).then((e=>e.json())).then((e=>{se.exchangeOpen=!!e.exchange_active;se.update();Z.requestRender()})).catch((()=>{}));const ie=new T(1);const re=new T(1);const ae=new x;const ce=new I(Z,ne,{paddingX:1});const le=[{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)"}];if((0,u.loadConfig)().tradingEnabled){le.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 de=(0,p.loadSkills)();for(const e of de){const t=e.trigger.replace(/^\//,"");le.splice(-2,0,{name:t,description:`[skill] ${e.description.slice(0,50)}`})}const ue=new E(le,process.cwd());ce.setAutocompleteProvider(ue);Z.addChild(ie);Z.addChild(ae);Z.addChild(ce);Z.addChild(re);Z.setFocus(ce);const pe=Z.showOverlay(se,{anchor:"bottom-left",width:"100%",nonCapturing:true});function addSystemText(e){const t=new C(e,1,0);ae.addChild(t);Z.requestRender()}function addSpacer(){ae.addChild(new T(1))}function promptUser(e){return new Promise((t=>{addSystemText(h.amber(bold("⚠ "))+h.zinc200(e));addSpacer();Z.requestRender();V={resolve:t}}))}const he=N.Object({thesisId:N.String({description:"Thesis ID (short or full UUID)"})});const me=N.Object({thesisId:N.String({description:"Thesis ID"}),content:N.String({description:"Signal content"}),type:N.Optional(N.String({description:"Signal type: news, user_note, external. Default: user_note"}))});const fe=N.Object({query:N.Optional(N.String({description:"Keyword search for Kalshi markets"})),series:N.Optional(N.String({description:"Kalshi series ticker (e.g. KXWTIMAX)"})),market:N.Optional(N.String({description:"Specific market ticker"}))});const ge=N.Object({query:N.String({description:"Search keywords"})});const ye=N.Object({});const $e=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:he,execute:async(e,t)=>{const n=await g.getContext(t.thesisId);k=n;se.setFromContext(n,oe||undefined);Z.requestRender();return{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:ye,execute:async()=>{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));const 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:N.Object({q:N.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));const 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:N.Object({topic:N.Optional(N.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));const 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:N.Object({symbols:N.String({description:"Comma-separated (max 5). Continuous futures: ROOT.c.0. E.g. SPY, CL.c.0, ES.c.0"}),dataset:N.Optional(N.String({description:"DBEQ.BASIC (stocks), GLBX.MDP3 (CME futures), OPRA.PILLAR (options)"})),schema:N.Optional(N.String({description:"ohlcv-1d, ohlcv-1h, ohlcv-1m, trades, bbo-1s, bbo-1m, statistics"})),stype:N.Optional(N.String({description:"raw_symbol (default) or continuous (for .FUT)"})),days:N.Optional(N.Number({description:"Lookback days (default 7, max 30)"}))}),execute:async(e,t)=>{const n=new URLSearchParams({symbols:t.symbols});if(t.dataset)n.set("dataset",t.dataset);if(t.schema)n.set("schema",t.schema);if(t.stype)n.set("stype",t.stype);if(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:me,execute:async(e,t)=>{const n=await g.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:he,execute:async(e,t)=>{const n=await g.evaluate(t.thesisId);if(n.evaluation?.confidenceDelta&&Math.abs(n.evaluation.confidenceDelta)>=.01){const e=n.evaluation.confidenceDelta;const t=Math.round((n.evaluation.previousConfidence||0)*100);const s=Math.round((n.evaluation.newConfidence||0)*100);const o=e>0?"▲":"▼";const i=e>0?h.emerald:h.red;addSystemText(i(` ${o} Confidence ${t}% → ${s}% (${e>0?"+":""}${Math.round(e*100)})`));addSpacer();se.updateConfidence(n.evaluation.newConfidence,e);Z.requestRender()}try{k=await g.getContext(t.thesisId);se.setFromContext(k,oe||undefined);Z.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:fe,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)();const n=t.query.toLowerCase().split(/\s+/);const 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(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);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(n[0]*100):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:ye,execute:async()=>{const e=await g.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:ye,execute:async()=>{const e={kalshi:[],polymarket:[]};const t=await(0,c.getPositions)();if(t){for(const e of t){const t=await(0,c.getMarketPrice)(e.ticker);if(t!==null){e.current_value=t;e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity)}}W=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((e.avgPrice||0)*100)}¢`,current_price:`${Math.round((e.curPrice||e.currentPrice||0)*100)}¢`,pnl:`$${(e.cashPnl||0).toFixed(2)}`})))}catch{}}if(e.kalshi.length===0&&e.polymarket.length===0){return{content:[{type:"text",text:"No positions found. Configure Kalshi (KALSHI_API_KEY_ID) or Polymarket (sf setup --polymarket) to see positions."}],details:{}}}return{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:ge,execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY;const s=!n&&o;if(!n&&!s){return{content:[{type:"text",text:"Web search not available. Run sf login (proxied search) or set TAVILY_API_KEY."}],details:{}}}let r;if(n){r=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:true})})}else{r=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:true})})}if(!r.ok){return{content:[{type:"text",text:`Search failed: ${r.status}`}],details:{}}}const a=await r.json();const c=(a.results||[]).map((e=>`[${e.title}](${e.url})\n${e.content?.slice(0,200)}`)).join("\n\n");const l=a.answer?`Summary: ${a.answer}\n\n---\n\n`:"";return{content:[{type:"text",text:`${l}${c}`}],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:N.Object({slug:N.Optional(N.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:N.Object({thesisId:N.String({description:"Thesis ID"}),marketId:N.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:N.String({description:"Human-readable market name"}),direction:N.String({description:"yes or no"}),horizon:N.Optional(N.String({description:"short, medium, or long. Default: medium"})),entryBelow:N.Optional(N.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:N.Optional(N.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:N.Optional(N.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:N.Optional(N.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:N.Optional(N.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:N.Optional(N.Number({description:"Contracts per order. Default: 50"})),softConditions:N.Optional(N.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:N.Optional(N.String({description:"Full logic description"}))}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),status:N.Optional(N.String({description:"Filter by status. Omit for all."}))}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),strategyId:N.String({description:"Strategy ID (UUID)"}),stopLoss:N.Optional(N.Number({description:"New stop loss (cents)"})),takeProfit:N.Optional(N.Number({description:"New take profit (cents)"})),entryBelow:N.Optional(N.Number({description:"New entry below trigger (cents)"})),entryAbove:N.Optional(N.Number({description:"New entry above trigger (cents)"})),status:N.Optional(N.String({description:"New status: active|watching|executed|cancelled|review"})),priority:N.Optional(N.Number({description:"New priority"})),softConditions:N.Optional(N.String({description:"Updated soft conditions"})),rationale:N.Optional(N.String({description:"Updated rationale"}))}),execute:async(e,t)=>{const{thesisId:n,strategyId:s,...o}=t;const i=await g.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:N.Object({hours:N.Optional(N.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:N.Optional(N.String({description:"Filter by category (e.g. Economics, Politics, Sports)"}))}),execute:async(e,t)=>{const n=t.hours||168;const s=new Date;const o=`https://api.elections.kalshi.com/trade-api/v2/milestones?limit=200&minimum_start_date=${s.toISOString()}`+(t.category?`&category=${t.category}`:"");const 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();const a=s.getTime()+n*36e5;const 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:N.Object({eventTicker:N.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:N.Optional(N.Number({description:"Days of history (default 7)"}))}),execute:async(e,t)=>{const{getForecastHistory:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=t.days||7;const 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();const 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()-o*864e5)/1e3),endTs:Math.floor(Date.now()/1e3),periodInterval:1440});if(!c||c.length===0)return{content:[{type:"text",text:"No forecast data available"}],details:{}};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled (resolved) contracts with P&L. Shows which contracts won/lost and realized returns.",parameters:N.Object({ticker:N.Optional(N.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getSettlements:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=await s({limit:100,ticker:t.ticker});if(!o)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(o.settlements,null,2)}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance and portfolio value.",parameters:ye,execute:async()=>{const{getBalance:e}=await Promise.resolve().then(n.t.bind(n,96139,23));const t=await e();if(!t)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],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:N.Object({status:N.Optional(N.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));const 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;let s=false;try{const i=await o(e.ticker);if(i!=null&&e.yes_price_dollars){n=Math.round(Math.abs(i-parseFloat(e.yes_price_dollars))*100);if(t!=null&&t>7&&n>10)s=true}}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:N.Object({ticker:N.Optional(N.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getFills:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=await s({ticker:t.ticker,limit:50});if(!o)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(o.fills,null,2)}],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:N.Object({topic:N.String({description:"Topic to scan (e.g. oil, crypto, fed, geopolitics)"})}),execute:async(e,t)=>{const n=t.topic.toLowerCase();const s=d.TOPIC_SERIES[n];if(!s){return{content:[{type:"text",text:`Unknown topic "${t.topic}". Available: ${Object.keys(d.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`;const n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)continue;const s=(await n.json()).markets||[];const i=await Promise.allSettled(s.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(e.status!=="fulfilled"||!e.value.ob)continue;const{ticker:t,title:n,ob:s}=e.value;const i=(s.yes_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),qty:parseFloat(t)}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const r=(s.no_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),qty:parseFloat(t)}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const a=i[0]?.price||0;const c=r.length>0?100-r[0].price:100;const l=c-a;const d=i.slice(0,3).reduce(((e,t)=>e+t.qty),0)+r.slice(0,3).reduce(((e,t)=>e+t.qty),0);const 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(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 s=await(0,l.polymarketGetOrderbookWithDepth)(n[0]);if(!s)continue;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{}o.sort(((e,t)=>e.spread-t.spread));return{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:N.Object({ticker:N.Optional(N.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:N.Optional(N.Array(N.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:N.Optional(N.String({description:'Search Polymarket by keyword (e.g. "oil price above 100")'}))}),execute:async(e,t)=>{const n=[];const s=[];if(t.tickers?.length)s.push(...t.tickers);else if(t.ticker)s.push(t.ticker);for(const e of s){try{const t=await(0,a.kalshiFetchMarket)(e);const s=t.status||"unknown";if(s!=="open"&&s!=="active"){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(parseFloat(t.last_price_dollars||"0")*100)})}else{const s=await(0,c.getPublicOrderbook)(e);const o=(s?.yes_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const i=(s?.no_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));if(o.length===0&&i.length===0){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(parseFloat(t.last_price_dollars||"0")*100),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;const r=i.length>0?100-i[0].price:o[0]?o[0].price+1:100;const a=r-s;const c=o.slice(0,3).reduce(((e,t)=>e+t.size),0)+i.slice(0,3).reduce(((e,t)=>e+t.size),0);const 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(parseFloat(t.last_price_dollars||"0")*100),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 s=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!s)continue;const o=await(0,l.polymarketGetOrderbookWithDepth)(s[0]);if(!o)continue;const i=(0,l.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(i[0]*100):0,volume24h:e.volume24hr||0})}}}catch{}}if(n.length===0){return{content:[{type:"text",text:"No markets found. Provide ticker (Kalshi) or polyQuery (Polymarket search)."}],details:{}}}return{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:ye,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:N.Object({rawThesis:N.String({description:"The raw thesis statement to create"}),webhookUrl:N.Optional(N.String({description:"Optional webhook URL for notifications"}))}),execute:async(e,t)=>{const n=await g.createThesis(t.rawThesis,true);const s=n.thesis||n;const o=s.causalTree?.nodes?.length||0;const i=(s.edges||[]).length;const r=typeof s.confidence==="number"?Math.round(s.confidence*100):0;if($&&s.id){$=false;y=s.id;try{k=await g.getContext(s.id);const e=buildSystemPrompt(k);we.setSystemPrompt(e);se.setFromContext(k,oe||undefined);Z.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:ye,execute:async()=>{const{theses:e}=await g.listTheses();const t=(e||[]).filter((e=>e.status==="active"||e.status==="monitoring"));const n=await Promise.allSettled(t.map((async e=>{const t=await g.getContext(e.id);return(t.edges||[]).map((t=>({...t,thesisId:e.id})))})));const s=[];for(const e of n){if(e.status==="fulfilled")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:N.Object({hours:N.Optional(N.Number({description:"Hours of history to fetch (default 24)"}))}),execute:async(e,t)=>{const n=await g.getFeed(t.hours||24);const s=Array.isArray(n)?n:n?.evaluations||n?.items||[];let o=null;let i=0;for(const e of s){let t=0;const n=Math.abs(e.confidenceDelta||e.confidence_delta||0);if(n>0)t=n*100;else if(e.summary?.length>50)t=.1;if(t>i){i=t;o=e}}const r={total:s.length};if(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;return{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:N.Object({hours:N.Optional(N.Number({description:"Hours of history (default 1)"}))}),execute:async(e,t)=>{const n=t.hours||1;const s=new Date(Date.now()-n*60*60*1e3).toISOString();const o=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:{}}}}];$e.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:N.Object({overrides:N.Array(N.Object({nodeId:N.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:N.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{if(y){try{k=await g.getContext(y)}catch{}}const n=k;const s=[];function flatten(e){for(const t of e){s.push(t);if(t.children?.length)flatten(t.children)}}const o=n.causalTree?.nodes||[];flatten(o);const i=o.filter((e=>e.depth===0||e.depth===undefined&&!e.id.includes(".")));const r=new Map(t.overrides.map((e=>[e.nodeId,e.newProbability])));function effectiveProb(e){if(r.has(e.id))return r.get(e.id);if(e.children?.length>0){const t=e.children.map((e=>effectiveProb(e)));const n=e.children.map((e=>e.importance||1));const s=n.reduce(((e,t)=>e+t),0);if(s>0){return t.reduce(((e,t,s)=>e+t*n[s]),0)/s}return t.reduce(((e,t)=>e+t),0)/t.length}return e.probability??0}const a=i.reduce(((e,t)=>e+(t.probability||0)*(t.importance||0)),0);const c=i.reduce(((e,t)=>e+effectiveProb(t)*(t.importance||0)),0);const l=new Map;for(const[e,t]of r.entries()){const n=s.find((t=>t.id===e));if(n&&n.probability>0)l.set(e,Math.max(0,Math.min(2,t/n.probability)))}const d=(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(l.has(t)){n=l.get(t);break}}}const s=e.marketPrice||0;const o=e.thesisPrice||e.thesisImpliedPrice||s;const i=e.edge||e.edgeSize||0;const r=Math.round((s+(o-s)*n)*100)/100;const a=e.direction||"yes";const c=Math.round((a==="yes"?r-s:s-r)*100)/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=>e.signal!=="unchanged"));const u=n.confidence!=null?Math.round(Number(n.confidence)*100):null;const 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}})),serverConfidence:u,treeConfidence:{old:Math.round(a*100),new:Math.round(c*100),delta:Math.round((c-a)*100)},note:u!=null&&Math.abs(u-Math.round(a*100))>5?`serverConfidence (${u}%) differs from treeConfidence (${Math.round(a*100)}%) because the LLM evaluation considers factors beyond the causal tree.`:undefined,affectedEdges:d};return{content:[{type:"text",text:JSON.stringify(p,null,2)}],details:{}}}});$e.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:N.Object({query:N.String({description:'Search query (e.g. "iran oil", "fed rate cut", "$BTC")'}),mode:N.Optional(N.String({description:'"summary" (default, with AI analysis) or "raw" (just posts)'})),hours:N.Optional(N.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await g.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:N.Object({query:N.String({description:"Search query"}),hours:N.Optional(N.Number({description:"Hours of history (default 72)"}))}),execute:async(e,t)=>{const n=await g.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:N.Object({query:N.String({description:"Search query"}),limit:N.Optional(N.Number({description:"Max stories (default 10)"}))}),execute:async(e,t)=>{const n=await g.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:N.Object({username:N.String({description:"X username (with or without @)"}),hours:N.Optional(N.Number({description:"Hours of history (default 24)"}))}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),newsIntervalMin:N.Optional(N.Number({description:"News scan interval in minutes (15-1440)"})),xIntervalMin:N.Optional(N.Number({description:"X scan interval in minutes (60-1440)"})),evalModelTier:N.Optional(N.String({description:"Eval model: cheap, medium, or heavy"})),monthlyBudgetUsd:N.Optional(N.Number({description:"Monthly budget cap in USD (0 = unlimited)"})),paused:N.Optional(N.Boolean({description:"Pause (true) or resume (false) heartbeat"}))}),execute:async(e,t)=>{const n=t.newsIntervalMin||t.xIntervalMin||t.evalModelTier||t.monthlyBudgetUsd!==undefined||t.paused!==undefined;if(n){const e={};if(t.newsIntervalMin)e.newsIntervalMin=t.newsIntervalMin;if(t.xIntervalMin)e.xIntervalMin=t.xIntervalMin;if(t.evalModelTier)e.evalModelTier=t.evalModelTier;if(t.monthlyBudgetUsd!==undefined)e.monthlyBudgetUsd=t.monthlyBudgetUsd;if(t.paused!==undefined)e.paused=t.paused;await g.updateHeartbeatConfig(t.thesisId,e)}const s=await g.getHeartbeatConfig(t.thesisId);return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}});const ke=(0,u.loadConfig)();if(ke.tradingEnabled){$e.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:N.Object({ticker:N.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:N.String({description:"yes or no"}),action:N.String({description:"buy or sell"}),type:N.String({description:"limit or market"}),count:N.Number({description:"Number of contracts"}),price_cents:N.Optional(N.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));const o=t.price_cents?Math.round(Number(t.price_cents)):undefined;const i=((o||99)*t.count/100).toFixed(2);const r=[h.zinc200(bold("ORDER PREVIEW")),` Ticker: ${t.ticker}`,` Side: ${t.side==="yes"?h.emerald("YES"):h.red("NO")}`,` Action: ${t.action.toUpperCase()}`,` Quantity: ${t.count}`,` Type: ${t.type}`,o?` Price: ${o}¢`:"",` Max cost: $${i}`].filter(Boolean).join("\n");addSystemText(r);addSpacer();Z.requestRender();const a=await promptUser("Execute this order? (y/n)");if(!a.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}:{}});const 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);if(t.includes("403")){return{content:[{type:"text",text:"403 Forbidden — your Kalshi key lacks write permission. Get a read+write key at kalshi.com/account/api-keys"}],details:{}}}return{content:[{type:"text",text:`Order failed: ${t}`}],details:{}}}}},{name:"cancel_order",label:"Cancel Order",description:"Cancel a resting order by order ID.",parameters:N.Object({order_id:N.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{const{cancelOrder:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=await promptUser(`Cancel order ${t.order_id}? (y/n)`);if(!o.toLowerCase().startsWith("y")){return{content:[{type:"text",text:"Cancel aborted by user."}],details:{}}}try{await s(t.order_id);return{content:[{type:"text",text:`Order ${t.order_id} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Cancel failed: ${e.message}`}],details:{}}}}})}$e.push({name:"update_thesis",label:"Update Thesis",description:"Update thesis metadata: title, status (active/paused/archived), webhookUrl.",parameters:N.Object({thesisId:N.String({description:"Thesis ID"}),title:N.Optional(N.String({description:"New title"})),status:N.Optional(N.String({description:"active, paused, or archived"})),webhookUrl:N.Optional(N.String({description:"Webhook URL (HTTPS)"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t;const o=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),dryRun:N.Optional(N.Boolean({description:"Preview changes without applying (default false)"}))}),execute:async(e,t)=>{const n=t.dryRun?"?dryRun=true":"";const s=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),venue:N.String({description:"kalshi or polymarket"}),externalMarketId:N.String({description:"Market ticker"}),marketTitle:N.String({description:"Market name"}),direction:N.String({description:"yes or no"}),entryPrice:N.Number({description:"Entry price in cents"}),size:N.Optional(N.Number({description:"Contracts"})),rationale:N.Optional(N.String({description:"Why"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t;const o=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),positionId:N.String({description:"Position ID"}),currentPrice:N.Optional(N.Number({description:"Current price (cents)"})),edge:N.Optional(N.Number({description:"Current edge (cents)"})),status:N.Optional(N.String({description:"open or closed"}))}),execute:async(e,t)=>{const{thesisId:n,positionId:s,...o}=t;const i=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),positionId:N.String({description:"Position ID"})}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),updates:N.Array(N.Object({nodeId:N.String({description:"Node ID (e.g. n3)"}),probability:N.Number({description:"New probability (0-1)"}),reason:N.Optional(N.String({description:"Why"}))})),lock:N.Optional(N.Array(N.String({description:"Node IDs to lock"})))}),execute:async(e,t)=>{const n=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"}),newsIntervalMin:N.Optional(N.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:N.Optional(N.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:N.Optional(N.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:N.Optional(N.Number({description:"Monthly budget cap (0=unlimited)"})),paused:N.Optional(N.Boolean({description:"Pause/resume"}))}),execute:async(e,t)=>{const{thesisId:n,...s}=t;const o=await g.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:N.Object({thesisId:N.String({description:"Thesis ID"})}),execute:async(e,t)=>{const n=await g.request("GET",`/api/thesis/${t.thesisId}/heartbeat`);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}});$e.push({name:"get_trade_ideas",label:"Trade Ideas",description:"S&T-style trade pitches: conviction, catalyst, direction, risk. No auth required.",parameters:N.Object({freshness:N.Optional(N.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:N.Optional(N.String({description:"Filter: macro, geopolitics, crypto, policy, event"}))}),execute:async(e,t)=>{const n=new URLSearchParams;if(t.freshness)n.set("freshness",t.freshness);if(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:N.Object({action:N.String({description:"buy or sell"}),venue:N.String({description:"kalshi or polymarket"}),marketId:N.String({description:"Market ticker"}),marketTitle:N.String({description:"Human-readable name"}),direction:N.String({description:"yes or no"}),targetQuantity:N.Number({description:"Number of contracts"}),maxPrice:N.Optional(N.Number({description:"Max price per contract in cents (1-99)"})),triggerType:N.Optional(N.String({description:"immediate, price_below, price_above, time"})),triggerPrice:N.Optional(N.Number({description:"Price trigger threshold in cents"})),rationale:N.Optional(N.String({description:"Why this trade"})),autoExecute:N.Optional(N.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(e,t)=>{const n=await g.createIntent({...t,source:"agent",expireAt:new Date(Date.now()+24*60*60*1e3).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:N.Object({activeOnly:N.Optional(N.Boolean({description:"Only active intents (default true)"}))}),execute:async(e,t)=>{const n=await g.listIntents({active:t.activeOnly!==false});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:N.Object({intentId:N.String({description:"Intent ID to cancel"})}),execute:async(e,t)=>{const n=await g.cancelIntentAPI(t.intentId);return{content:[{type:"text",text:JSON.stringify(n)}],details:{}}}});$e.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:N.Object({focus:N.Optional(N.String({description:'Comma-separated topics to focus on (e.g. "energy,geopolitics")'}))}),execute:async(e,t)=>{const n=t.focus?`?focus=${encodeURIComponent(t.focus)}`:"";const s=await fetch(`${i}/api/agent/world${n}`);if(!s.ok)return{content:[{type:"text",text:`World API error: ${s.status}`}],details:{}};const o=await s.text();return{content:[{type:"text",text:o}],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:N.Object({since:N.Optional(N.String({description:'Time window: "30m", "1h", "6h", "24h" or ISO timestamp (default "1h")'}))}),execute:async(e,t)=>{const n=t.since||"1h";const 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:{}};const o=await s.text();return{content:[{type:"text",text:o}],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:N.Object({source:N.Object({action:N.String({description:"Firecrawl action: scrape, crawl, search, map, extract, batch_scrape"}),url:N.Optional(N.String({description:"Target URL (for scrape/crawl/extract)"})),query:N.Optional(N.String({description:"Search query (for search action)"}))}),analysis:N.Optional(N.Object({model:N.Optional(N.String({description:"OpenRouter model (e.g. google/gemini-flash-1.5)"})),prompt:N.Optional(N.String({description:"Analysis prompt"}))})),enrich:N.Optional(N.Object({topics:N.Optional(N.Array(N.String(),{description:"Topics for market cross-reference"})),includeIndex:N.Optional(N.Boolean({description:"Include SF prediction market index"}))})),webhook:N.Optional(N.Object({url:N.String({description:"Webhook URL"}),format:N.Optional(N.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:N.Object({content:N.String({description:"Text to cross-reference with markets"}),topics:N.Optional(N.Array(N.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:{}}}});$e.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime daemon is running and show active intents.",parameters:N.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:o}=await Promise.resolve().then(n.t.bind(n,70857,23));const i=s(o(),".sf","runtime.pid");let r=false;let a="";if(e(i)){a=t(i,"utf-8").trim();try{process.kill(parseInt(a),0);r=true}catch{r=false}}const c=await g.listIntents({active:true});return{content:[{type:"text",text:JSON.stringify({running:r,pid:r?a:null,...c},null,2)}],details:{}}}},{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon. Polls for active intents, evaluates trigger conditions, and executes orders via local API keys.",parameters:N.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:o}=await Promise.resolve().then(n.t.bind(n,70857,23));const{spawn:i}=await Promise.resolve().then(n.t.bind(n,35317,23));const r=s(o(),".sf","runtime.pid");if(e(r)){const e=t(r,"utf-8").trim();try{process.kill(parseInt(e),0);return{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{}}const a=i(process.execPath,[process.argv[1],"runtime","start"],{detached:true,stdio:["ignore","ignore","ignore"],env:{...process.env}});a.unref();await new Promise((e=>setTimeout(e,1e3)));if(e(r)){const e=t(r,"utf-8").trim();return{content:[{type:"text",text:`Runtime started (PID ${e}). Polling every 30s for active intents.`}],details:{}}}return{content:[{type:"text",text:"Runtime starting... check status in a moment with runtime_status."}],details:{}}}},{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:N.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:s}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23));const 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{process.kill(parseInt(a),"SIGTERM");s(r);return{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:{}}}}});$e.push({name:"create_skill",description:"Create a custom agent skill — a reusable prompt/workflow triggered via slash command. Returns the new skill ID.",parameters:{name:{type:"string"},trigger:{type:"string"},description:{type:"string"},prompt:{type:"string"},category:{type:"string",optional:true},tags:{type:"string",optional:true,description:"Comma-separated tags"},toolsUsed:{type:"string",optional:true,description:"Comma-separated tool names"}},execute:async e=>{const t={name:e.name,trigger:e.trigger,description:e.description,prompt:e.prompt};if(e.category)t.category=e.category;if(e.tags)t.tags=e.tags.split(",").map((e=>e.trim()));if(e.toolsUsed)t.toolsUsed=e.toolsUsed.split(",").map((e=>e.trim()));const n=await fetch(`${i}/api/skill`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(t)});const s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"list_skills",description:"List all skills: built-in defaults + user-created custom skills.",parameters:{},execute:async()=>{const e=await fetch(`${i}/api/skill`,{headers:{Authorization:`Bearer ${o}`}});const t=await e.json();return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"browse_public_skills",description:"Browse community-created skills. Filter by category, search, or sort by popularity. No auth needed.",parameters:{category:{type:"string",optional:true},q:{type:"string",optional:true},sort:{type:"string",optional:true,description:"popular or new"}},execute:async e=>{const t=new URLSearchParams;if(e.category)t.set("category",e.category);if(e.q)t.set("q",e.q);if(e.sort)t.set("sort",e.sort);const n=await fetch(`${i}/api/public/skills?${t}`);const s=await n.json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}],details:{}}}},{name:"publish_skill",description:"Publish a skill to make it publicly browsable and forkable by other users.",parameters:{skillId:{type:"string"},slug:{type:"string"}},execute:async e=>{const t=await fetch(`${i}/api/skill/${e.skillId}/publish`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({slug:e.slug})});const n=await t.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"fork_skill",description:"Fork a public skill into your collection. Creates a copy you can customize.",parameters:{skillId:{type:"string",description:"ID of the public skill to fork"}},execute:async e=>{const t=await fetch(`${i}/api/skill/${e.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${o}`}});const n=await t.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}},{name:"fork_thesis",description:"Fork a public thesis. Copies thesis statement + causal tree. Run formation after forking for fresh edges.",parameters:{slug:{type:"string",description:"Public thesis slug (from /thesis/:slug URL)"}},execute:async e=>{const t=await fetch(`${i}/api/thesis/${e.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${o}`}});const n=await t.json();return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{}}}});function buildSystemPrompt(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)";const n=e.causalTree?.nodes?.filter((e=>e.depth===0)).map((e=>` ${e.id} ${(e.label||"").slice(0,40)} — ${Math.round(e.probability*100)}%`)).join("\n")||" (no causal tree)";const s=typeof e.confidence==="number"?Math.round(e.confidence*100):typeof e.confidence==="string"?parseInt(e.confidence):0;return`You are a prediction market trading assistant. Your job is not to please the user — it is to help them see reality clearly and make correct trading decisions.\n\n## Your analytical framework\n\nEach thesis has a causal tree. Every node is a causal hypothesis with a probability. Nodes have causal relationships — when upstream nodes change, downstream nodes follow.\n\nEdge = thesis-implied price - actual market price. Positive edge = market underprices. Contracts with large edges AND good liquidity are most tradeable.\n\nexecutableEdge = real edge after subtracting bid-ask spread. Big theoretical edge with wide spread may not be worth entering.\n\n### Edge diagnosis (always classify)\nWhen reporting an edge, classify it:\n- "consensus gap": depth >= 500, market actively disagrees — real edge, real opponents\n- "attention gap": depth < 100, no real pricing — edge may be illusory, needs catalyst\n- "timing gap": market directionally agrees but lags — may close suddenly on news\n- "risk premium": edge reflects settlement ambiguity or platform risk, not alpha\nFor edges > 20 cents, state in one sentence what must be true for the market to be right and the thesis wrong.\n\n### Price reliability\n47 cents with depth 14K = strong consensus. 47 cents with depth 50 = three people's opinion.\n- depth >= 500: reliable, treat as market consensus\n- depth 100-500: moderate confidence, caveat when citing\n- depth < 100: unreliable — do NOT treat as "the market thinks X"\n- spread > 5 cents: wide disagreement, noisy midpoint\n- liquidityScore = low: do NOT recommend entry\n\n### Kill condition awareness\nEach top-level causal node has an implicit falsifier. When scanning news or evaluating events, check: "Does any event here fundamentally break a core assumption?" If yes, flag immediately — this overrides all other analysis.\n\n### Catalyst and time\nWhen discussing an edge, always state contract expiry and next identifiable catalyst. No visible catalyst = flag capital lock risk.\n\n### Research workflow\nFor complex questions, chain multiple tool calls:\n1. get_world_state (broad situational awareness) 2. get_context 3. inspect_book 4. get_liquidity 5. web_search 6. search_x 7. monitor_the_situation (scrape specific URLs) 8. synthesize\nUse get_world_delta for efficient polling (30-50 tokens vs 800 for full state). Use enrich_content to cross-reference any text with 9,706 markets.\nDon't answer a complex question with a single tool call.\n\n### Social signal research\nUse search_x to check X/Twitter sentiment on any topic — especially useful for geopolitical events, macro shifts, and breaking news that moves prediction markets. Use x_volume to detect discussion spikes (velocity > 1 = increasing attention). Use x_account to track specific analysts or officials.\n\n### Heartbeat config\nUse heartbeat_config to view or adjust per-thesis heartbeat settings: news/X scan intervals, evaluation model tier (cheap/medium/heavy), monthly budget cap, pause/resume. Also shows this month's cost breakdown (LLM calls, search calls, tokens, spend). Useful when the user asks about costs, wants to slow down/speed up monitoring, or if you detect budget overrun.\n\n### Conditional rules\n- Portfolio/positions questions: flag correlated exposure — positions sharing upstream causal nodes are not independent bets.\n- No catalyst visible within 30 days + edge not improving: flag "stale capital risk."\n- Edges < 10 cents, thin liquidity, no catalyst near: say "nothing to do right now." Do not manufacture urgency.\n\nShort-term markets settle into hard data that calibrates the thesis. Use them to verify node probabilities, not to bet.\n\n## Your behavioral rules\n\n- IMPORTANT: You do NOT know the user's current positions at conversation start. Before discussing trades, recommending entries/exits, or analyzing portfolio risk, call get_positions FIRST. Never assume the user has no positions — they may have large existing holdings you don't know about.\n- Think before calling tools. If the data is already in context, don't re-fetch.\n- If the user says "note this" or mentions a news event, inject a signal. Don't ask "should I note this?"\n- If the user says "evaluate" or "run it", trigger immediately. Don't confirm.\n- Don't end every response with "anything else?" — the user will ask when they want to.\n- If the user asks about latest news or real-time events, use web_search first, then answer based on results. If you find important information, suggest injecting it as a signal.\n- If you notice an edge narrowing or disappearing, say so proactively. Don't only report good news.\n- If a causal tree node probability seriously contradicts the market price, point it out.\n- Use Chinese if the user writes in Chinese, English if they write in English.\n- For any question about prices, positions, or P&L, ALWAYS call a tool to get fresh data first. Never answer price-related questions using the cached data in this system prompt.\n- Prices are in cents (e.g. 35¢). P&L, cost, and balance are in dollars (e.g. $90.66). Tool outputs are pre-formatted with units — do not re-convert.\n- Align tables. Be precise with numbers to the cent.\n\n## Strategy rules\n\nWhen the conversation produces a concrete trade idea (specific contract, direction, price conditions), use create_strategy to record it immediately. Don't wait for the user to say "record this."\n- Extract hard conditions (specific prices in cents) into entryBelow/stopLoss/takeProfit.\n- Put fuzzy conditions into softConditions (e.g. "only if n3 > 60%", "spread < 3¢").\n- Put the full reasoning into rationale.\n- After creating, confirm the strategy details.\n- If the user says "change the stop loss on T150 to 30", use update_strategy.\n\n## Intent & Execution\n\nUse create_intent to declare execution intents with trigger conditions (price_below, price_above, time, immediate). Use list_intents / cancel_intent to manage. The local runtime daemon (runtime_start/runtime_stop/runtime_status) evaluates triggers and executes orders via local API keys.\n\n## 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${ke.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||y}\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)}`:""}`}function buildExplorerPrompt(e){const t=(0,u.loadConfig)();const n=e.theses?.length||0;const s=e.edges?.length||0;const o=(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`}const be=$?buildExplorerPrompt(k):buildSystemPrompt(k);const we=new D({initialState:{systemPrompt:be,model:U,tools:$e,thinkingLevel:"off"},streamFn:L,getApiKey:e=>{if(e==="openrouter")return m;return undefined}});let _e=false;if(!t?.newSession){const e=loadSession(y||"_explorer");if(e?.messages?.length>0){try{const t=e.messages.filter((e=>{if(!e.role)return false;if(Array.isArray(e.content)&&e.content.length===0)return false;if(e.role==="assistant"&&!e.content&&!e.tool_calls?.length)return false;return true}));const n=[];for(const e of t){const t=n.length>0?n[n.length-1].role:null;if(e.role===t&&e.role!=="tool"){continue}n.push(e)}if(n.length>0&&n[n.length-1].role==="user"){n.pop()}we.replaceMessages(n);we.setSystemPrompt(be);_e=true}catch{}}}function persistSession(){try{const e=we.state.messages;if(e.length>0){saveSession(y||"_explorer",j,e)}}catch{}}let Se=null;let ve="";let xe=null;const Ce=new Map;const Oe=new Map;let Ie=null;function throttledRender(){if(Ie)return;Ie=setTimeout((()=>{Ie=null;Z.requestRender()}),66)}function flushRender(){if(Ie){clearTimeout(Ie);Ie=null}Z.requestRender()}we.subscribe((e=>{if(e.type==="message_start"){ve="";Se=null;xe=new P(Z,(e=>h.emerald(e)),(e=>h.zinc600(e)),"thinking...");xe.start();ae.addChild(xe);Z.requestRender()}if(e.type==="message_update"){const t=e.assistantMessageEvent;if(t.type==="text_delta"){if(xe){xe.stop();ae.removeChild(xe);xe=null;Se=new O("",1,0,ee,te);ae.addChild(Se)}ve+=t.delta;if(Se){Se.setText(ve)}throttledRender()}}if(e.type==="message_end"){if(xe){xe.stop();ae.removeChild(xe);xe=null}if(Se&&ve){Se.setText(ve)}addSpacer();Se=null;ve="";flushRender()}if(e.type==="agent_end"){J=false;persistSession();flushRender();if(X){const e=X;X=null;handleHeartbeatDelta(e)}}if(e.type==="tool_execution_start"){const t=new F(h.zinc600(` ▸ ${e.toolName}...`));Ce.set(e.toolCallId||e.toolName,Date.now());Oe.set(e.toolCallId||e.toolName,t);ae.addChild(t);B++;se.toolCount=B;se.update();Z.requestRender()}if(e.type==="tool_execution_end"){const t=e.toolCallId||e.toolName;const n=Ce.get(t);const s=n?((Date.now()-n)/1e3).toFixed(1):"?";const o=Oe.get(t);if(o){if(e.isError){o.setText(h.red(` ✗ ${e.toolName} (${s}s) error`))}else{o.setText(h.zinc600(` ▸ ${e.toolName} `)+h.emerald(`✓`)+h.zinc600(` ${s}s`))}}Ce.delete(t);Oe.delete(t);Z.requestRender()}}));async function handleSlashCommand(e){const t=e.trim().split(/\s+/);const s=t[0].toLowerCase();switch(s){case"/help":{addSpacer();addSystemText(h.zinc200(bold("Commands"))+"\n"+h.emerald("/help ")+h.zinc400("Show this help")+"\n"+h.emerald("/tree ")+h.zinc400("Display causal tree")+"\n"+h.emerald("/edges ")+h.zinc400("Display edge/spread table")+"\n"+h.emerald("/pos ")+h.zinc400("Display Kalshi positions")+"\n"+h.emerald("/eval ")+h.zinc400("Trigger deep evaluation")+"\n"+h.emerald("/switch <id>")+h.zinc400(" Switch thesis")+"\n"+h.emerald("/compact ")+h.zinc400("Compress conversation history")+"\n"+h.emerald("/new ")+h.zinc400("Start fresh session")+"\n"+h.emerald("/model <m> ")+h.zinc400("Switch model")+"\n"+h.emerald("/env ")+h.zinc400("Show environment variable status")+"\n"+(ke.tradingEnabled?h.zinc600("─".repeat(30))+"\n"+h.emerald("/buy ")+h.zinc400("TICKER QTY PRICE — quick buy")+"\n"+h.emerald("/sell ")+h.zinc400("TICKER QTY PRICE — quick sell")+"\n"+h.emerald("/cancel ")+h.zinc400("ORDER_ID — cancel order")+"\n"+h.zinc600("─".repeat(30))+"\n":"")+(de.length>0?h.zinc600("─".repeat(30))+"\n"+h.zinc200(bold("Skills"))+"\n"+de.map((e=>h.emerald(`/${e.name.padEnd(10)}`)+h.zinc400(e.description.slice(0,45)))).join("\n")+"\n"+h.zinc600("─".repeat(30))+"\n":"")+h.emerald("/clear ")+h.zinc400("Clear screen (keeps history)")+"\n"+h.emerald("/exit ")+h.zinc400("Exit (auto-saves)"));addSpacer();return true}case"/tree":{addSpacer();if($){addSystemText(h.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one."))}else{try{k=await g.getContext(y);addSystemText(h.zinc200(bold("Causal Tree"))+"\n"+renderCausalTree(k,b))}catch(e){addSystemText(h.red(`Error: ${e.message}`))}}addSpacer();return true}case"/edges":{addSpacer();if($){try{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));const t=await e();const s=(t.edges||[]).sort(((e,t)=>Math.abs(t.edge)-Math.abs(e.edge))).slice(0,10);if(s.length===0){addSystemText(h.zinc400("No public edges available."))}else{const e=s.map((e=>{const t=(e.title||"").slice(0,35).padEnd(35);const n=(e.venue||"kalshi").padEnd(5);const s=String(Math.round(e.price||0)).padStart(3)+"¢";const o="+"+Math.round(e.edge||0);return` ${h.zinc400(t)} ${h.zinc600(n)} ${h.zinc400(s)} ${h.emerald(o.padStart(4))}`})).join("\n");addSystemText(h.zinc200(bold("Public Edges"))+"\n"+e)}}catch(e){addSystemText(h.red(`Error: ${e.message}`))}}else{try{k=await g.getContext(y);if(W){k._positions=W}addSystemText(h.zinc200(bold("Edges"))+"\n"+renderEdges(k,b))}catch(e){addSystemText(h.red(`Error: ${e.message}`))}}addSpacer();return true}case"/pos":{addSpacer();try{const e=await(0,c.getPositions)();if(!e){addSystemText(h.zinc600("Kalshi not configured"));return true}for(const t of e){const e=await(0,c.getMarketPrice)(t.ticker);if(e!==null){t.current_value=e;t.unrealized_pnl=Math.round((e-t.average_price_paid)*t.quantity)}}W=e;addSystemText(h.zinc200(bold("Positions"))+"\n"+renderPositions(e))}catch(e){addSystemText(h.red(`Error: ${e.message}`))}addSpacer();return true}case"/eval":{addSpacer();if($){addSystemText(h.zinc400("No thesis selected. Use /switch <id> to pick one, or ask me to create one."));addSpacer();return true}addSystemText(h.zinc600("Triggering evaluation..."));Z.requestRender();try{const e=await g.evaluate(y);addSystemText(h.emerald("Evaluation complete")+"\n"+h.zinc400(JSON.stringify(e,null,2)))}catch(e){addSystemText(h.red(`Error: ${e.message}`))}addSpacer();return true}case"/model":{const e=t.slice(1).join(" ").trim();if(!e){addSystemText(h.zinc400(`Current model: ${j}`));return true}addSpacer();j=e.replace(/^openrouter\//,"");U=resolveModel(j);we.setModel(U);se.modelName=j;se.update();addSystemText(h.emerald(`Model switched to ${j}`));addSpacer();Z.requestRender();return true}case"/switch":{const e=t[1]?.trim();if(!e){addSystemText(h.zinc400("Usage: /switch <thesisId>"));return true}addSpacer();try{persistSession();const t=await g.getContext(e);y=t.thesisId||e;k=t;const n=buildSystemPrompt(t);const s=typeof t.confidence==="number"?Math.round(t.confidence*100):0;we.clearMessages();const o=loadSession(y);if(o?.messages?.length>0){we.replaceMessages(o.messages);we.setSystemPrompt(n);addSystemText(h.emerald(`Switched to ${y.slice(0,8)}`)+h.zinc400(` (resumed ${o.messages.length} messages)`))}else{we.setSystemPrompt(n);addSystemText(h.emerald(`Switched to ${y.slice(0,8)}`)+h.zinc400(" (new session)"))}se.setFromContext(t,oe||undefined);ae.clear();addSystemText(buildWelcomeDashboard(t,oe))}catch(e){addSystemText(h.red(`Switch failed: ${e.message}`))}addSpacer();Z.setFocus(ce);Z.requestRender();return true}case"/compact":{addSpacer();try{const e=we.state.messages;if(e.length<=10){addSystemText(h.zinc400("Conversation too short to compact"));addSpacer();Z.setFocus(ce);return true}const t=3;let n=0;let s=e.length;for(let o=e.length-1;o>=0;o--){if(e[o].role==="user"){n++;if(n>=t){s=o;break}}}if(s<=2){addSystemText(h.zinc400("Not enough complete turns to compact"));addSpacer();Z.setFocus(ce);return true}const o=e.slice(0,s);const a=e.slice(s);const c=new P(Z,(e=>h.emerald(e)),(e=>h.zinc600(e)),"compacting with LLM...");c.start();ae.addChild(c);Z.requestRender();const l=[];let d=0;const u=12e3;for(const e of o){if(d>=u)break;let t="";if(typeof e.content==="string"){t=e.content}else if(Array.isArray(e.content)){t=e.content.filter((e=>e.type==="text")).map((e=>e.text)).join("\n")}if(!t)continue;const n=(e.role||"unknown").toUpperCase();const s=t.slice(0,800);const o=`[${n}]: ${s}`;l.push(o);d+=o.length}const p=l.join("\n\n");const f="google/gemini-2.0-flash-001";const g=`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";const t={model:f,messages:[{role:"system",content:g},{role:"user",content:`Summarize this conversation (${o.length} messages):\n\n${p}`}],max_tokens:2e3,temperature:.2};const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m}`,"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();y=s.choices?.[0]?.message?.content||"";if(!y){throw new Error("Empty summary from LLM")}}catch(e){const t=[];for(const e of o){const n=typeof e.content==="string"?e.content:"";if(e.role==="user"&&n){t.push(`- User: ${n.slice(0,100)}`)}else if(e.role==="assistant"&&n){t.push(`- Assistant: ${n.slice(0,150)}`)}}y=`[LLM summary failed: ${e.message}. Fallback bullet points:]\n\n${t.slice(-20).join("\n")}`}c.stop();ae.removeChild(c);const $=[{role:"user",content:`[Conversation summary — ${o.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."},...a];we.clearMessages();we.replaceMessages($);we.setSystemPrompt(be);persistSession();addSystemText(h.emerald(`Compacted: ${o.length} messages → summary + ${a.length} recent`)+h.zinc600(` (via ${f.split("/").pop()})`));addSpacer();Z.setFocus(ce);Z.requestRender()}catch(e){addSystemText(h.red(`Compact failed: ${e.message||e}`));addSpacer();Z.setFocus(ce);Z.requestRender()}return true}case"/new":{addSpacer();persistSession();we.clearMessages();we.setSystemPrompt(be);ae.clear();addSystemText(h.emerald("Session cleared")+h.zinc400(" — fresh start"));addSpacer();Z.requestRender();return true}case"/env":{addSpacer();const e=[{name:"SF_API_KEY",key:"SF_API_KEY",required:true,mask:true},{name:"SF_API_URL",key:"SF_API_URL",required:false,mask:false},{name:"OPENROUTER_KEY",key:"OPENROUTER_API_KEY",required:true,mask:true},{name:"KALSHI_KEY_ID",key:"KALSHI_API_KEY_ID",required:false,mask:true},{name:"KALSHI_PEM_PATH",key:"KALSHI_PRIVATE_KEY_PATH",required:false,mask:false},{name:"TAVILY_API_KEY",key:"TAVILY_API_KEY",required:false,mask:true}];const t=e.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)} ${h.emerald("✓")} ${h.zinc400(n)}`}else{const t=e.required?"必须":"可选";return` ${e.name.padEnd(18)} ${h.red("✗")} ${h.zinc600(`未配置(${t})`)}`}}));addSystemText(h.zinc200(bold("Environment"))+"\n"+t.join("\n"));addSpacer();return true}case"/clear":{const e=[...ae.children||[]];for(const t of e){try{ae.removeChild(t)}catch{}}addSpacer();J=false;V=null;Z.setFocus(ce);Z.requestRender();return true}case"/buy":{const[,e,s,o]=t;if(!e||!s||!o){addSystemText(h.zinc400("Usage: /buy TICKER QTY PRICE_CENTS (e.g. /buy KXWTIMAX-26DEC31-T135 100 50)"));return true}if(!ke.tradingEnabled){addSystemText(h.red("Trading disabled. Run: sf setup --enable-trading"));return true}addSpacer();const i=await promptUser(`BUY ${s}x ${e} YES @ ${o}¢ — execute? (y/n)`);if(i.toLowerCase().startsWith("y")){try{const{createOrder:t}=await Promise.resolve().then(n.t.bind(n,96139,23));const i=await t({ticker:e,side:"yes",action:"buy",type:"limit",count:parseInt(s),yes_price:parseInt(o)});addSystemText(h.emerald("✓ Order placed: "+((i.order||i).order_id||"OK")))}catch(e){addSystemText(h.red("✗ "+e.message))}}else{addSystemText(h.zinc400("Cancelled."))}addSpacer();return true}case"/sell":{const[,e,s,o]=t;if(!e||!s||!o){addSystemText(h.zinc400("Usage: /sell TICKER QTY PRICE_CENTS"));return true}if(!ke.tradingEnabled){addSystemText(h.red("Trading disabled. Run: sf setup --enable-trading"));return true}addSpacer();const i=await promptUser(`SELL ${s}x ${e} YES @ ${o}¢ — execute? (y/n)`);if(i.toLowerCase().startsWith("y")){try{const{createOrder:t}=await Promise.resolve().then(n.t.bind(n,96139,23));const i=await t({ticker:e,side:"yes",action:"sell",type:"limit",count:parseInt(s),yes_price:parseInt(o)});addSystemText(h.emerald("✓ Order placed: "+((i.order||i).order_id||"OK")))}catch(e){addSystemText(h.red("✗ "+e.message))}}else{addSystemText(h.zinc400("Cancelled."))}addSpacer();return true}case"/cancel":{const[,e]=t;if(!e){addSystemText(h.zinc400("Usage: /cancel ORDER_ID"));return true}if(!ke.tradingEnabled){addSystemText(h.red("Trading disabled. Run: sf setup --enable-trading"));return true}addSpacer();try{const{cancelOrder:t}=await Promise.resolve().then(n.t.bind(n,96139,23));await t(e);addSystemText(h.emerald(`✓ Order ${e} cancelled.`))}catch(e){addSystemText(h.red("✗ "+e.message))}addSpacer();return true}case"/exit":case"/quit":{cleanup();return true}default:{const e=de.find((e=>e.trigger===s));if(e){addSpacer();addSystemText(h.zinc200(`Running skill: ${bold(e.name)}`)+h.zinc600(` — ${e.description.slice(0,60)}`));addSpacer();Z.requestRender();J=true;try{await we.prompt(e.prompt)}catch(e){addSystemText(h.red(`Skill error: ${e.message}`))}finally{J=false}return true}return false}}}ce.onSubmit=async e=>{const t=e.trim();if(!t)return;if(V){const{resolve:e}=V;V=null;const n=new C(h.zinc400(" > ")+h.zinc200(t),1,0);ae.addChild(n);addSpacer();Z.requestRender();e(t);return}if(J)return;ce.addToHistory(t);if(t.startsWith("/")){const e=await handleSlashCommand(t);if(e)return}J=true;const n=new C(h.emerald(bold(">"))+" "+h.white(t),1,0);ae.addChild(n);addSpacer();Z.requestRender();try{await we.prompt(t)}catch(e){if(xe){xe.stop();ae.removeChild(xe);xe=null}addSystemText(h.red(`Error: ${e.message}`));addSpacer();J=false}};function cleanup(){if(Y)clearInterval(Y);if(xe)xe.stop();persistSession();Z.stop();process.exit(0)}Z.addInputListener((e=>{if(e===""){cleanup();return{consume:true}}return undefined}));process.on("SIGINT",cleanup);process.on("SIGTERM",cleanup);function buildWelcomeDashboard(e,t){const n=[];if(e._explorerMode){const t=e.edges?.length||0;const s=e.theses?.length||0;n.push(h.zinc600("─".repeat(55)));n.push(" "+h.emerald(bold("Explorer mode"))+h.zinc600(" — full market access, no thesis"));n.push(" "+h.zinc600(`${s} public theses │ ${t} edges tracked`));n.push(h.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(" "+h.zinc400(bold("TOP PUBLIC EDGES"))+h.zinc600(" mkt edge"));for(const t of e){const e=(t.title||"").slice(0,30).padEnd(30);const s=String(Math.round(t.price||0)).padStart(3)+"¢";const o=t.edge||0;const i="+"+Math.round(o);const r=Math.abs(o)>=15?h.emerald:Math.abs(o)>=8?h.amber:h.zinc400;n.push(` ${h.zinc400(e)} ${h.zinc400(s)} ${r(i.padStart(4))}`)}}n.push(h.zinc600("─".repeat(55)));n.push(" "+h.zinc600("Ask anything, or describe a view to create a thesis."));n.push(h.zinc600("─".repeat(55)));return n.join("\n")}const s=e.thesis||e.rawThesis||"N/A";const o=s.length>100?s.slice(0,100)+"...":s;const i=typeof e.confidence==="number"?Math.round(e.confidence*100):typeof e.confidence==="string"?Math.round(parseFloat(e.confidence)*100):0;const r=e.lastEvaluation?.confidenceDelta?Math.round(e.lastEvaluation.confidenceDelta*100):0;const a=r!==0?` (${r>0?"+":""}${r})`:"";const c=e.lastEvaluation?.evaluatedAt?Math.round((Date.now()-new Date(e.lastEvaluation.evaluatedAt).getTime())/36e5):null;n.push(h.zinc600("─".repeat(55)));n.push(" "+h.zinc200(bold(o)));n.push(" "+h.zinc600(`${e.status||"active"} ${i}%${a}`)+(c!==null?h.zinc600(` │ last eval: ${c<1?"<1":c}h ago`):""));n.push(h.zinc600("─".repeat(55)));if(t&&t.length>0){n.push(" "+h.zinc400(bold("POSITIONS")));let e=0;for(const s of t){const t=s.unrealized_pnl||0;e+=t;const o=t>=0?h.emerald(`+$${(t/100).toFixed(2)}`):h.red(`-$${(Math.abs(t)/100).toFixed(2)}`);const i=(s.ticker||"").slice(0,28).padEnd(28);const r=String(s.quantity||0).padStart(5);const a=s.side==="yes"?h.emerald("Y"):h.red("N");n.push(` ${h.zinc400(i)} ${r} ${a} ${o}`)}const s=e>=0?h.emerald(bold(`+$${(e/100).toFixed(2)}`)):h.red(bold(`-$${(Math.abs(e)/100).toFixed(2)}`));n.push(` ${"".padEnd(28)} ${h.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(h.zinc600("─".repeat(55)));n.push(" "+h.zinc400(bold("TOP EDGES"))+h.zinc600(" mkt edge liq"));for(const t of e){const e=(t.market||t.marketTitle||t.marketId||"").slice(0,30).padEnd(30);const s=String(Math.round(t.marketPrice||0)).padStart(3)+"¢";const o=t.edge||t.edgeSize||0;const i=(o>0?"+":"")+Math.round(o);const r=t.orderbook?.liquidityScore||(t.venue==="polymarket"?"-":"?");const a=Math.abs(o)>=15?h.emerald:Math.abs(o)>=8?h.amber:h.zinc400;n.push(` ${h.zinc400(e)} ${h.zinc400(s)} ${a(i.padStart(4))} ${h.zinc600(r)}`)}}n.push(h.zinc600("─".repeat(55)));return n.join("\n")}const Pe=_e?h.zinc600(`resumed (${we.state.messages.length} messages)`):h.zinc600("new session");addSystemText(buildWelcomeDashboard(k,oe));addSystemText(" "+Pe);addSpacer();const Te=.03;function handleHeartbeatDelta(e){const t=Math.abs(e.confidenceDelta||0);const n=Math.round((e.confidence||0)*100);const s=Math.round((e.confidenceDelta||0)*100);const o=s>0?"+":"";if(t>=Te){const t=s>0?"▲":"▼";const i=s>0?h.emerald:h.red;addSystemText(i(` ${t} Heartbeat: confidence ${o}${s}% → ${n}%`));if(e.latestSummary){addSystemText(h.zinc400(` ${e.latestSummary.slice(0,100)}`))}addSpacer();se.setFromContext({...k,confidence:e.confidence,lastEvaluation:{confidenceDelta:e.confidenceDelta}},oe||undefined);Z.requestRender();J=true;const r=`[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.`;we.prompt(r).catch((e=>{addSystemText(h.red(`Error: ${e.message}`));J=false}))}else if(t>0){addSystemText(h.zinc600(` ─ heartbeat: ${n}% (${o}${s}%) — ${e.evaluationCount||0} eval(s)`));Z.requestRender()}}if(!$)Y=setInterval((async()=>{try{const e=await g.getChanges(y,G);G=(new Date).toISOString();if(!e.changed)return;if(J||V){X=e}else{handleHeartbeatDelta(e)}}catch{}}),6e4);Z.start()}async function runPlainTextAgent(e){const{openrouterKey:t,sfClient:s,resolvedThesisId:o,opts:i,useProxy:r,llmBaseUrl:p,sfApiKey:h,sfApiUrl:m}=e;let f=e.latestContext;const g=await Promise.resolve().then(n.t.bind(n,23785,23));const y=await Promise.all([n.e(788),n.e(641),n.e(174)]).then(n.bind(n,99641));const $=await Promise.all([n.e(788),n.e(641),n.e(582)]).then(n.bind(n,65653));const{getModel:k,streamSimple:b,Type:w}=y;const{Agent:_}=$;const S=i?.model||"anthropic/claude-sonnet-4.6";let v=S.replace(/^openrouter\//,"");function resolveModel(e){let t;try{t=k("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:true,supportsTools:true}}if(r)t.baseUrl=p;return t}let x=resolveModel(v);const C=w.Object({thesisId:w.String({description:"Thesis ID"})});const O=w.Object({thesisId:w.String({description:"Thesis ID"}),content:w.String({description:"Signal content"}),type:w.Optional(w.String({description:"Signal type: news, user_note, external"}))});const I=w.Object({query:w.Optional(w.String({description:"Keyword search"})),series:w.Optional(w.String({description:"Series ticker"})),market:w.Optional(w.String({description:"Market ticker"}))});const P=w.Object({query:w.String({description:"Search keywords"})});const T=w.Object({});const E=[{name:"get_context",label:"Get Context",description:"Get thesis snapshot: causal tree, edge prices, last evaluation, confidence",parameters:C,execute:async(e,t)=>{const n=await s.getContext(t.thesisId);f=n;return{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:T,execute:async()=>{const{fetchGlobalContext:e}=await Promise.resolve().then(n.bind(n,19218));const 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:w.Object({q:w.String({description:"Natural language query"})}),execute:async(e,t)=>{const{fetchQuery:s}=await Promise.resolve().then(n.bind(n,19218));const 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:w.Object({topic:w.Optional(w.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));const 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:w.Object({symbols:w.String({description:"Comma-separated. Futures: ROOT.c.0. E.g. SPY, CL.c.0"}),dataset:w.Optional(w.String({description:"DBEQ.BASIC, GLBX.MDP3, OPRA.PILLAR"})),schema:w.Optional(w.String({description:"ohlcv-1d, ohlcv-1h, ohlcv-1m, trades"})),stype:w.Optional(w.String({description:"raw_symbol or continuous"})),days:w.Optional(w.Number({description:"Lookback (max 30)"}))}),execute:async(e,t)=>{const n=new URLSearchParams({symbols:t.symbols});if(t.dataset)n.set("dataset",t.dataset);if(t.schema)n.set("schema",t.schema);if(t.stype)n.set("stype",t.stype);if(t.days)n.set("days",String(t.days));const s=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:O,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:C,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:I,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)();const 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:T,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:T,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);if(e!==null){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:P,execute:async(e,t)=>{const n=process.env.TAVILY_API_KEY;const s=!n&&h;if(!n&&!s)return{content:[{type:"text",text:"Web search not available. Run sf login or set TAVILY_API_KEY."}],details:{}};let o;if(n){o=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:true})})}else{o=await fetch(`${m}/api/proxy/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({query:t.query,max_results:5,search_depth:"basic",include_answer:true})})}if(!o.ok)return{content:[{type:"text",text:`Search failed: ${o.status}`}],details:{}};const i=await o.json();const r=(i.results||[]).map((e=>`[${e.title}](${e.url})\n${e.content?.slice(0,200)}`)).join("\n\n");const a=i.answer?`Summary: ${i.answer}\n\n---\n\n`:"";return{content:[{type:"text",text:`${a}${r}`}],details:{}}}},{name:"get_milestones",label:"Milestones",description:"Get upcoming events from Kalshi calendar. Use to check economic releases, political events, or other catalysts.",parameters:w.Object({hours:w.Optional(w.Number({description:"Hours ahead to look (default 168 = 1 week)"})),category:w.Optional(w.String({description:"Filter by category (e.g. Economics, Politics, Sports)"}))}),execute:async(e,t)=>{const n=t.hours||168;const s=new Date;const o=`https://api.elections.kalshi.com/trade-api/v2/milestones?limit=200&minimum_start_date=${s.toISOString()}`+(t.category?`&category=${t.category}`:"");const 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();const a=s.getTime()+n*36e5;const 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:w.Object({eventTicker:w.String({description:"Kalshi event ticker (e.g. KXWTIMAX-26DEC31)"}),days:w.Optional(w.Number({description:"Days of history (default 7)"}))}),execute:async(e,t)=>{const{getForecastHistory:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=t.days||7;const 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();const 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()-o*864e5)/1e3),endTs:Math.floor(Date.now()/1e3),periodInterval:1440});if(!c||c.length===0)return{content:[{type:"text",text:"No forecast data available"}],details:{}};return{content:[{type:"text",text:JSON.stringify(c,null,2)}],details:{}}}},{name:"get_settlements",label:"Settlements",description:"Get settled (resolved) contracts with P&L.",parameters:w.Object({ticker:w.Optional(w.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getSettlements:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=await s({limit:100,ticker:t.ticker});if(!o)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(o.settlements,null,2)}],details:{}}}},{name:"get_balance",label:"Balance",description:"Get Kalshi account balance and portfolio value.",parameters:T,execute:async()=>{const{getBalance:e}=await Promise.resolve().then(n.t.bind(n,96139,23));const t=await e();if(!t)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],details:{}}}},{name:"get_orders",label:"Orders",description:"Get current resting orders on Kalshi.",parameters:w.Object({status:w.Optional(w.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));const o=await s({status:t.status||"resting",limit:100});if(!o)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(o.orders,null,2)}],details:{}}}},{name:"get_fills",label:"Fills",description:"Get recent trade fills (executed trades) on Kalshi.",parameters:w.Object({ticker:w.Optional(w.String({description:"Filter by market ticker"}))}),execute:async(e,t)=>{const{getFills:s}=await Promise.resolve().then(n.t.bind(n,96139,23));const o=await s({ticker:t.ticker,limit:50});if(!o)return{content:[{type:"text",text:"Kalshi not configured."}],details:{}};return{content:[{type:"text",text:JSON.stringify(o.fills,null,2)}],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:w.Object({topic:w.String({description:"Topic to scan (e.g. oil, crypto, fed, geopolitics)"})}),execute:async(e,t)=>{const n=t.topic.toLowerCase();const s=d.TOPIC_SERIES[n];if(!s){return{content:[{type:"text",text:`Unknown topic "${t.topic}". Available: ${Object.keys(d.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`;const n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)continue;const s=(await n.json()).markets||[];const i=await Promise.allSettled(s.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(e.status!=="fulfilled"||!e.value.ob)continue;const{ticker:t,title:n,ob:s}=e.value;const i=(s.yes_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),qty:parseFloat(t)}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const r=(s.no_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),qty:parseFloat(t)}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const a=i[0]?.price||0;const c=r.length>0?100-r[0].price:100;const l=c-a;const d=i.slice(0,3).reduce(((e,t)=>e+t.qty),0)+r.slice(0,3).reduce(((e,t)=>e+t.qty),0);const 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(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 s=await(0,l.polymarketGetOrderbookWithDepth)(n[0]);if(!s)continue;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{}o.sort(((e,t)=>e.spread-t.spread));return{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:w.Object({ticker:w.Optional(w.String({description:"Single Kalshi market ticker (e.g. KXWTIMAX-26DEC31-T135)"})),tickers:w.Optional(w.Array(w.String(),{description:'Multiple Kalshi tickers for batch check (e.g. ["T$135", "T$140", "T$150"])'})),polyQuery:w.Optional(w.String({description:'Search Polymarket by keyword (e.g. "oil price above 100")'}))}),execute:async(e,t)=>{const n=[];const s=[];if(t.tickers?.length)s.push(...t.tickers);else if(t.ticker)s.push(t.ticker);for(const e of s){try{const t=await(0,a.kalshiFetchMarket)(e);const s=t.status||"unknown";if(s!=="open"&&s!=="active"){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(parseFloat(t.last_price_dollars||"0")*100)})}else{const s=await(0,c.getPublicOrderbook)(e);const o=(s?.yes_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const i=(s?.no_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));if(o.length===0&&i.length===0){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(parseFloat(t.last_price_dollars||"0")*100),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;const r=i.length>0?100-i[0].price:o[0]?o[0].price+1:100;const a=r-s;const c=o.slice(0,3).reduce(((e,t)=>e+t.size),0)+i.slice(0,3).reduce(((e,t)=>e+t.size),0);const 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(parseFloat(t.last_price_dollars||"0")*100),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 s=(0,l.parseClobTokenIds)(e.clobTokenIds);if(!s)continue;const o=await(0,l.polymarketGetOrderbookWithDepth)(s[0]);if(!o)continue;const i=(0,l.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(i[0]*100):0,volume24h:e.volume24hr||0})}}}catch{}}if(n.length===0){return{content:[{type:"text",text:"No markets found. Provide ticker (Kalshi) or polyQuery (Polymarket search)."}],details:{}}}return{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:T,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:w.Object({rawThesis:w.String({description:"The raw thesis statement to create"}),webhookUrl:w.Optional(w.String({description:"Optional webhook URL for notifications"}))}),execute:async(e,t)=>{const n=await s.createThesis(t.rawThesis,true);const o=n.thesis||n;const i=o.causalTree?.nodes?.length||0;const r=(o.edges||[]).length;const a=typeof o.confidence==="number"?Math.round(o.confidence*100):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:T,execute:async()=>{const{theses:e}=await s.listTheses();const t=(e||[]).filter((e=>e.status==="active"||e.status==="monitoring"));const n=await Promise.allSettled(t.map((async e=>{const t=await s.getContext(e.id);return(t.edges||[]).map((t=>({...t,thesisId:e.id})))})));const o=[];for(const e of n){if(e.status==="fulfilled")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:w.Object({hours:w.Optional(w.Number({description:"Hours of history to fetch (default 24)"}))}),execute:async(e,t)=>{const n=await s.getFeed(t.hours||24);const o=Array.isArray(n)?n:n?.evaluations||n?.items||[];let i=null;let r=0;for(const e of o){let t=0;const n=Math.abs(e.confidenceDelta||e.confidence_delta||0);if(n>0)t=n*100;else if(e.summary?.length>50)t=.1;if(t>r){r=t;i=e}}const a={total:o.length};if(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;return{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:w.Object({hours:w.Optional(w.Number({description:"Hours of history (default 1)"}))}),execute:async(e,t)=>{const n=t.hours||1;const s=new Date(Date.now()-n*60*60*1e3).toISOString();const o=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:w.Object({slug:w.Optional(w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),marketId:w.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T150"}),market:w.String({description:"Human-readable market name"}),direction:w.String({description:"yes or no"}),horizon:w.Optional(w.String({description:"short, medium, or long. Default: medium"})),entryBelow:w.Optional(w.Number({description:"Entry trigger: ask <= this value (cents)"})),entryAbove:w.Optional(w.Number({description:"Entry trigger: ask >= this value (cents, for NO direction)"})),stopLoss:w.Optional(w.Number({description:"Stop loss: bid <= this value (cents)"})),takeProfit:w.Optional(w.Number({description:"Take profit: bid >= this value (cents)"})),maxQuantity:w.Optional(w.Number({description:"Max total contracts. Default: 500"})),perOrderQuantity:w.Optional(w.Number({description:"Contracts per order. Default: 50"})),softConditions:w.Optional(w.String({description:'LLM-evaluated conditions e.g. "only enter when n3 > 60%"'})),rationale:w.Optional(w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),status:w.Optional(w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),strategyId:w.String({description:"Strategy ID (UUID)"}),stopLoss:w.Optional(w.Number({description:"New stop loss (cents)"})),takeProfit:w.Optional(w.Number({description:"New take profit (cents)"})),entryBelow:w.Optional(w.Number({description:"New entry below trigger (cents)"})),entryAbove:w.Optional(w.Number({description:"New entry above trigger (cents)"})),status:w.Optional(w.String({description:"New status: active|watching|executed|cancelled|review"})),priority:w.Optional(w.Number({description:"New priority"})),softConditions:w.Optional(w.String({description:"Updated soft conditions"})),rationale:w.Optional(w.String({description:"Updated rationale"}))}),execute:async(e,t)=>{const{thesisId:n,strategyId:o,...i}=t;const 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:w.Object({overrides:w.Array(w.Object({nodeId:w.String({description:"Causal tree node ID (e.g. n1, n3.1)"}),newProbability:w.Number({description:"New probability 0-1"})}),{description:"Node probability overrides"})}),execute:async(e,t)=>{const n=f;const s=[];function flatten(e){for(const t of e){s.push(t);if(t.children?.length)flatten(t.children)}}const o=n.causalTree?.nodes||[];flatten(o);const i=o.filter((e=>e.depth===0||e.depth===undefined&&!e.id.includes(".")));const r=new Map(t.overrides.map((e=>[e.nodeId,e.newProbability])));const a=i.reduce(((e,t)=>e+(t.probability||0)*(t.importance||0)),0);const c=i.reduce(((e,t)=>{const n=r.get(t.id)??t.probability??0;return e+n*(t.importance||0)}),0);const l=new Map;for(const[e,t]of r.entries()){const n=s.find((t=>t.id===e));if(n&&n.probability>0)l.set(e,Math.max(0,Math.min(2,t/n.probability)))}const d=(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(l.has(t)){n=l.get(t);break}}}const s=e.marketPrice||0;const o=e.thesisPrice||e.thesisImpliedPrice||s;const i=e.edge||e.edgeSize||0;const r=Math.round((s+(o-s)*n)*100)/100;const a=e.direction||"yes";const c=Math.round((a==="yes"?r-s:s-r)*100)/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=>e.signal!=="unchanged"));const u={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(a*100),new:Math.round(c*100),delta:Math.round((c-a)*100)},affectedEdges:d};return{content:[{type:"text",text:JSON.stringify(u,null,2)}],details:{}}}}];E.push({name:"search_x",label:"X Search",description:"Search X (Twitter) for recent discussions. Returns posts, sentiment, themes.",parameters:w.Object({query:w.String({description:"Search query"}),mode:w.Optional(w.String({description:'"summary" or "raw"'})),hours:w.Optional(w.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:w.Object({query:w.String({description:"Search query"}),hours:w.Optional(w.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:w.Object({query:w.String({description:"Search query"}),limit:w.Optional(w.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:w.Object({username:w.String({description:"X username (with or without @)"}),hours:w.Optional(w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),newsIntervalMin:w.Optional(w.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:w.Optional(w.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:w.Optional(w.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:w.Optional(w.Number({description:"Monthly budget (0 = unlimited)"})),paused:w.Optional(w.Boolean({description:"Pause or resume heartbeat"}))}),execute:async(e,t)=>{const n=t.newsIntervalMin||t.xIntervalMin||t.evalModelTier||t.monthlyBudgetUsd!==undefined||t.paused!==undefined;if(n){const e={};if(t.newsIntervalMin)e.newsIntervalMin=t.newsIntervalMin;if(t.xIntervalMin)e.xIntervalMin=t.xIntervalMin;if(t.evalModelTier)e.evalModelTier=t.evalModelTier;if(t.monthlyBudgetUsd!==undefined)e.monthlyBudgetUsd=t.monthlyBudgetUsd;if(t.paused!==undefined)e.paused=t.paused;await s.updateHeartbeatConfig(t.thesisId,e)}const o=await s.getHeartbeatConfig(t.thesisId);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}});E.push({name:"configure_heartbeat",label:"Configure Heartbeat",description:"Adjust the 24/7 monitoring engine: news interval, X interval, model tier, budget, pause/resume.",parameters:w.Object({thesisId:w.String({description:"Thesis ID"}),newsIntervalMin:w.Optional(w.Number({description:"News scan interval (15-1440 min)"})),xIntervalMin:w.Optional(w.Number({description:"X scan interval (60-1440 min)"})),evalModelTier:w.Optional(w.String({description:"cheap, medium, or heavy"})),monthlyBudgetUsd:w.Optional(w.Number({description:"Monthly budget cap (0=unlimited)"})),paused:w.Optional(w.Boolean({description:"Pause/resume"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t;const 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:w.Object({thesisId:w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),title:w.Optional(w.String({description:"New title"})),status:w.Optional(w.String({description:"active, paused, or archived"})),webhookUrl:w.Optional(w.String({description:"Webhook URL (HTTPS)"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t;const 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:w.Object({thesisId:w.String({description:"Thesis ID"}),venue:w.String({description:"kalshi or polymarket"}),externalMarketId:w.String({description:"Market ticker"}),marketTitle:w.String({description:"Market name"}),direction:w.String({description:"yes or no"}),entryPrice:w.Number({description:"Entry price in cents"}),size:w.Optional(w.Number({description:"Contracts"})),rationale:w.Optional(w.String({description:"Why"}))}),execute:async(e,t)=>{const{thesisId:n,...o}=t;const 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:w.Object({thesisId:w.String({description:"Thesis ID"}),positionId:w.String({description:"Position ID"}),currentPrice:w.Optional(w.Number({description:"Current price (cents)"})),edge:w.Optional(w.Number({description:"Current edge (cents)"})),status:w.Optional(w.String({description:"open or closed"}))}),execute:async(e,t)=>{const{thesisId:n,positionId:o,...i}=t;const 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:w.Object({thesisId:w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),updates:w.Array(w.Object({nodeId:w.String({description:"Node ID (e.g. n3)"}),probability:w.Number({description:"New probability (0-1)"}),reason:w.Optional(w.String({description:"Why"}))})),lock:w.Optional(w.Array(w.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:{}}}});E.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:w.Object({freshness:w.Optional(w.String({description:"Max cache age: 1h, 6h, 12h (default 12h)"})),category:w.Optional(w.String({description:"Filter: macro, geopolitics, crypto, policy, event"}))}),execute:async(e,t)=>{const n=new URLSearchParams;if(t.freshness)n.set("freshness",t.freshness);if(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:w.Object({action:w.String({description:"buy or sell"}),venue:w.String({description:"kalshi or polymarket"}),marketId:w.String({description:"Market ticker"}),marketTitle:w.String({description:"Human-readable name"}),direction:w.String({description:"yes or no"}),targetQuantity:w.Number({description:"Number of contracts"}),maxPrice:w.Optional(w.Number({description:"Max price per contract in cents (1-99)"})),triggerType:w.Optional(w.String({description:"immediate, price_below, price_above, time"})),triggerPrice:w.Optional(w.Number({description:"Price trigger threshold in cents"})),rationale:w.Optional(w.String({description:"Why this trade"})),autoExecute:w.Optional(w.Boolean({description:"Auto-execute without confirmation"}))}),execute:async(e,t)=>{const n=await s.createIntent({...t,source:"agent",expireAt:new Date(Date.now()+24*60*60*1e3).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:w.Object({activeOnly:w.Optional(w.Boolean({description:"Only active intents (default true)"}))}),execute:async(e,t)=>{const n=await s.listIntents({active:t.activeOnly!==false});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:w.Object({intentId:w.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 A=(0,u.loadConfig)();if(A.tradingEnabled){E.push({name:"place_order",label:"Place Order",description:"Place a buy or sell order on Kalshi. Shows preview and asks for confirmation.",parameters:w.Object({ticker:w.String({description:"Market ticker e.g. KXWTIMAX-26DEC31-T135"}),side:w.String({description:"yes or no"}),action:w.String({description:"buy or sell"}),type:w.String({description:"limit or market"}),count:w.Number({description:"Number of contracts"}),price_cents:w.Optional(w.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));const o=await Promise.resolve().then(n.t.bind(n,23785,23));const i=t.price_cents?Math.round(Number(t.price_cents)):undefined;const r=((i||99)*t.count/100).toFixed(2);const a=` Order: ${t.action.toUpperCase()} ${t.count}x ${t.ticker} ${t.side.toUpperCase()} @ ${i?i+"¢":"market"} (max $${r})`;process.stderr.write(a+"\n");if(!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});const l=await new Promise((e=>c.question(" Execute? (y/n) ",e)));c.close();if(!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}:{}});const 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);if(t.includes("403")){return{content:[{type:"text",text:"403 Forbidden — your Kalshi key lacks write permission. Get a read+write key at kalshi.com/account/api-keys"}],details:{}}}return{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:w.Object({order_id:w.String({description:"Order ID to cancel"})}),execute:async(e,t)=>{const{cancelOrder:s}=await Promise.resolve().then(n.t.bind(n,96139,23));try{await s(t.order_id);return{content:[{type:"text",text:`Order ${t.order_id} cancelled.`}],details:{}}}catch(e){return{content:[{type:"text",text:`Cancel failed: ${e.message}`}],details:{}}}}})}E.push({name:"close_position",label:"Close Position",description:"Remove a position record from a thesis.",parameters:w.Object({thesisId:w.String({description:"Thesis ID"}),positionId:w.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:w.Object({thesisId:w.String({description:"Thesis ID"}),dryRun:w.Optional(w.Boolean({description:"Preview without applying"}))}),execute:async(e,t)=>{const n=t.dryRun?"?dryRun=true":"";const o=await s.request("POST",`/api/thesis/${t.thesisId}/augment${n}`);return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}});E.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:w.Object({focus:w.Optional(w.String({description:'Comma-separated topics (e.g. "energy,geopolitics")'}))}),execute:async(e,t)=>{const n=t.focus?`?focus=${encodeURIComponent(t.focus)}`:"";const s=process.env.SF_API_URL||"https://simplefunctions.dev";const o=await fetch(`${s}/api/agent/world${n}`);if(!o.ok)return{content:[{type:"text",text:`World API error: ${o.status}`}],details:{}};const i=await o.text();return{content:[{type:"text",text:i}],details:{}}}},{name:"get_world_delta",label:"World Delta",description:"Incremental world state update — only what changed. ~30-50 tokens.",parameters:w.Object({since:w.Optional(w.String({description:'"30m", "1h", "6h", "24h" or ISO timestamp (default "1h")'}))}),execute:async(e,t)=>{const n=t.since||"1h";const s=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:{}};const i=await o.text();return{content:[{type:"text",text:i}],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:w.Object({source:w.Object({action:w.String({description:"scrape, crawl, search, map, extract, batch_scrape"}),url:w.Optional(w.String({description:"Target URL"})),query:w.Optional(w.String({description:"Search query (for search action)"}))}),analysis:w.Optional(w.Object({model:w.Optional(w.String({description:"OpenRouter model"})),prompt:w.Optional(w.String({description:"Analysis prompt"}))})),enrich:w.Optional(w.Object({topics:w.Optional(w.Array(w.String())),includeIndex:w.Optional(w.Boolean())})),webhook:w.Optional(w.Object({url:w.String({description:"Webhook URL"}),format:w.Optional(w.String({description:"full, brief, or tweetable"}))}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:w.Object({content:w.String({description:"Text to cross-reference"}),topics:w.Optional(w.Array(w.String()))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const 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:{}}}});E.push({name:"create_skill",label:"Create Skill",description:"Create a custom agent skill — a reusable prompt/workflow triggered via slash command.",parameters:w.Object({name:w.String(),trigger:w.String({description:"Slash command trigger, e.g. /my-skill"}),description:w.String(),prompt:w.String({description:"The instruction text the agent executes"}),category:w.Optional(w.String()),tags:w.Optional(w.String({description:"Comma-separated tags"})),toolsUsed:w.Optional(w.String({description:"Comma-separated tool names"}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const s={name:t.name,trigger:t.trigger,description:t.description,prompt:t.prompt};if(t.category)s.category=t.category;if(t.tags)s.tags=t.tags.split(",").map((e=>e.trim()));if(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 ${h}`},body:JSON.stringify(s)});const 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:w.Object({}),execute:async()=>{const e=process.env.SF_API_URL||"https://simplefunctions.dev";const t=await fetch(`${e}/api/skill`,{headers:{Authorization:`Bearer ${h}`}});const 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:w.Object({category:w.Optional(w.String()),q:w.Optional(w.String()),sort:w.Optional(w.String({description:"popular or new"}))}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const s=new URLSearchParams;if(t.category)s.set("category",t.category);if(t.q)s.set("q",t.q);if(t.sort)s.set("sort",t.sort);const o=await fetch(`${n}/api/public/skills?${s}`);const 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:w.Object({skillId:w.String(),slug:w.String({description:"URL-safe slug, e.g. my-precheck"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const s=await fetch(`${n}/api/skill/${t.skillId}/publish`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({slug:t.slug})});const 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:w.Object({skillId:w.String({description:"ID of the public skill to fork"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const s=await fetch(`${n}/api/skill/${t.skillId}/fork`,{method:"POST",headers:{Authorization:`Bearer ${h}`}});const 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:w.Object({slug:w.String({description:"Public thesis slug, e.g. iran-war"})}),execute:async(e,t)=>{const n=process.env.SF_API_URL||"https://simplefunctions.dev";const s=await fetch(`${n}/api/thesis/${t.slug}/fork`,{method:"POST",headers:{Authorization:`Bearer ${h}`}});const o=await s.json();return{content:[{type:"text",text:JSON.stringify(o,null,2)}],details:{}}}});E.push({name:"runtime_status",label:"Runtime Status",description:"Check if the local execution runtime is running and show active intents.",parameters:w.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23));const r=o(i(),".sf","runtime.pid");let a=false;let c="";if(e(r)){c=t(r,"utf-8").trim();try{process.kill(parseInt(c),0);a=true}catch{a=false}}const l=await s.listIntents({active:true});return{content:[{type:"text",text:JSON.stringify({running:a,pid:a?c:null,...l},null,2)}],details:{}}}},{name:"runtime_start",label:"Start Runtime",description:"Start the local execution runtime daemon. Evaluates intent triggers and executes orders.",parameters:w.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:s}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:o}=await Promise.resolve().then(n.t.bind(n,70857,23));const{spawn:i}=await Promise.resolve().then(n.t.bind(n,35317,23));const r=s(o(),".sf","runtime.pid");if(e(r)){const e=t(r,"utf-8").trim();try{process.kill(parseInt(e),0);return{content:[{type:"text",text:`Runtime already running (PID ${e}).`}],details:{}}}catch{}}const a=i(process.execPath,[process.argv[1],"runtime","start"],{detached:true,stdio:["ignore","ignore","ignore"],env:{...process.env}});a.unref();await new Promise((e=>setTimeout(e,1e3)));if(e(r)){const e=t(r,"utf-8").trim();return{content:[{type:"text",text:`Runtime started (PID ${e}). Polling every 30s.`}],details:{}}}return{content:[{type:"text",text:"Runtime starting... check runtime_status in a moment."}],details:{}}}},{name:"runtime_stop",label:"Stop Runtime",description:"Stop the local execution runtime daemon.",parameters:w.Object({}),execute:async()=>{const{existsSync:e,readFileSync:t,unlinkSync:s}=await Promise.resolve().then(n.t.bind(n,79896,23));const{join:o}=await Promise.resolve().then(n.t.bind(n,16928,23));const{homedir:i}=await Promise.resolve().then(n.t.bind(n,70857,23));const 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{process.kill(parseInt(a),"SIGTERM");s(r);return{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 removed)."}],details:{}}}}});const M=f;const R=M._explorerMode||o==="_explorer";let L;if(R){const e=(M.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)";L=`You are a prediction market research assistant in EXPLORER MODE — not bound to any thesis.\n\n## What you can do\n- get_world_state: real-time world model (~800 tokens), use ?focus= for deeper topic coverage\n- get_world_delta: incremental changes since last check (~30-50 tokens)\n- query: LLM-enhanced market search\n- scan_markets: search Kalshi + Polymarket\n- get_markets: traditional markets (SPY, VIX, gold, oil)\n- get_trade_ideas: S&T-style trade pitches with conviction + catalyst\n- explore_public: browse public theses\n- search_x, x_volume, x_news: X/Twitter signals\n- monitor_the_situation: scrape any URL, analyze, cross-reference with 9,706 markets\n- enrich_content: cross-reference text with prediction markets\n- get_positions: portfolio positions\n- create_intent / list_intents / cancel_intent: execution intents with triggers\n- runtime_start / runtime_stop / runtime_status: local execution daemon\n- create_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${A.tradingEnabled?"- Trading ENABLED.":"- Trading DISABLED."}\n\n## Market snapshot\nPublic edges:\n${e}`}else{const e=M.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)";const t=M.causalTree?.nodes?.filter((e=>e.depth===0)).map((e=>` ${e.id} ${(e.label||"").slice(0,40)} — ${Math.round(e.probability*100)}%`)).join("\n")||" (no causal tree)";const n=typeof M.confidence==="number"?Math.round(M.confidence*100):0;L=`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${A.tradingEnabled?"- Trading ENABLED. You have place_order and cancel_order tools.":"- Trading DISABLED. Tell user: sf setup --enable-trading"}\n\n## Current State\nThesis: ${M.thesis||M.rawThesis||"N/A"}\nID: ${o} | Confidence: ${n}% | Status: ${M.status}\n\nCausal nodes:\n${t}\n\nTop edges:\n${e}\n\n${M.lastEvaluation?.summary?`Latest eval: ${M.lastEvaluation.summary.slice(0,300)}`:""}`}const N=new _({initialState:{systemPrompt:L,model:x,tools:E,thinkingLevel:"off"},streamFn:b,getApiKey:e=>e==="openrouter"?t:undefined});if(!i?.newSession){const e=loadSession(o);if(e?.messages?.length>0){try{N.replaceMessages(e.messages);N.setSystemPrompt(L)}catch{}}}let D="";N.subscribe((e=>{if(e.type==="message_update"){const t=e.assistantMessageEvent;if(t.type==="text_delta"){process.stdout.write(t.delta);D+=t.delta}}if(e.type==="message_end"){if(D){process.stdout.write("\n");D=""}}if(e.type==="tool_execution_start"){process.stderr.write(` ▸ ${e.toolName}...\n`)}if(e.type==="tool_execution_end"){const t=e.isError?"✗":"✓";process.stderr.write(` ${t} ${e.toolName}\n`)}}));if(R){console.log(`SF Agent — Explorer mode | ${v}`);console.log(`Public edges: ${(M.edges||[]).length}`);console.log("Ask anything about prediction markets. Type /help for commands, /exit to quit.\n")}else{const e=M.thesis||M.rawThesis||"N/A";const t=typeof M.confidence==="number"?Math.round(M.confidence*100):0;console.log(`SF Agent — ${o.slice(0,8)} | ${t}% | ${v}`);console.log(`Thesis: ${e.length>100?e.slice(0,100)+"...":e}`);console.log(`Edges: ${(M.edges||[]).length} | Status: ${M.status}`);console.log("Type /help for commands, /exit to quit.\n")}const F=g.createInterface({input:process.stdin,output:process.stdout,prompt:"> "});F.prompt();for await(const e of F){const t=e.trim();if(!t){F.prompt();continue}if(t==="/exit"||t==="/quit"){try{saveSession(o,v,N.state.messages)}catch{}F.close();return}if(t==="/help"){console.log("Commands: /help /exit /tree /edges /eval /model <name>");F.prompt();continue}if(t==="/tree"){f=await s.getContext(o);const e=f.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(t.probability*100)}%`)}F.prompt();continue}if(t==="/edges"){f=await s.getContext(o);const e=(f.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}`)}F.prompt();continue}if(t==="/eval"){console.log("Triggering evaluation...");const e=await s.evaluate(o);console.log(`Confidence: ${e.previousConfidence} → ${e.newConfidence}`);if(e.summary)console.log(e.summary);F.prompt();continue}if(t.startsWith("/model")){const e=t.slice(6).trim();if(!e){console.log(`Current: ${v}`);F.prompt();continue}v=e.replace(/^openrouter\//,"");x=resolveModel(v);N.setModel(x);console.log(`Model: ${v}`);F.prompt();continue}try{await N.prompt(t)}catch(e){console.error(`Error: ${e.message}`)}try{saveSession(o,v,N.state.messages)}catch{}F.prompt()}}},72768:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.announcementsCommand=announcementsCommand;const s=n(96139);const o=n(99236);async function announcementsCommand(e){const t=await(0,s.getExchangeAnnouncements)();if(e.json){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(`${o.c.dim}No announcements.${o.c.reset}`);return}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():"";const n=e.type?`[${e.type}]`:"";console.log(` ${o.c.dim}${t}${o.c.reset} ${n} ${e.title||e.message||""}`);if(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}`)}},71783:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.augmentCommand=augmentCommand;const s=n(19218);async function augmentCommand(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){console.log(JSON.stringify(o,null,2));return}console.log();if(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(e.estimatedProbability*100)}%, 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(e.probability*100)}%, imp: ${e.importance})[22m`)}console.log();if(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()}if(o.applied){console.log(` [32m✓ Applied to causal tree[39m`)}else if(t.dryRun){console.log(` [2mDry run — use without --dry-run to apply[22m`)}}else{console.log(" No nodes accepted.")}console.log()}},44040:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.balanceCommand=balanceCommand;const s=n(96139);const o=n(99236);async function balanceCommand(e){const t=await(0,s.getBalance)();if(!t)throw new Error("Kalshi not configured. Run: sf setup --kalshi");if(e.json){console.log(JSON.stringify(t,null,2));return}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)}`)}},69903:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.bookCommand=bookCommand;const s=n(19218);const o=n(96139);const i=n(34331);const r=n(99236);async function bookCommand(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 a=(0,i.parseOutcomePrices)(e.outcomePrices);const c={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:a[0]?(0,i.toCents)(a[0]):0,expiry:e.endDateIso||null,bidLevels:r.levels.bids.slice(0,5).map((e=>({price:Math.round(parseFloat(e.price)*100),size:Math.round(parseFloat(e.size))}))),askLevels:r.levels.asks.slice(0,5).map((e=>({price:Math.round(parseFloat(e.price)*100),size:Math.round(parseFloat(e.size))})))};if(t.history){try{const e=await(0,i.polymarketGetPriceHistory)({tokenId:o[0],interval:"1w",fidelity:360});if(e.length>0){c.sparkline=makeSparkline(e.map((e=>e.p*100)))}}catch{}}n.push(c)}}}for(const i of e){console.log(`${r.c.dim}Fetching ${i}...${r.c.reset}`);try{const e=await(0,s.kalshiFetchMarket)(i);const a=await(0,o.getPublicOrderbook)(i);const c=(a?.yes_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const l=(a?.no_dollars||[]).map((([e,t])=>({price:Math.round(parseFloat(e)*100),size:Math.round(parseFloat(t))}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const d=c[0]?.price||0;const u=l.length>0?100-l[0].price:100;const p=u-d;const h=c.reduce(((e,t)=>e+t.size),0);const m=l.reduce(((e,t)=>e+t.size),0);const f=c.slice(0,3).reduce(((e,t)=>e+t.size),0)+l.slice(0,3).reduce(((e,t)=>e+t.size),0);const g=p<=2&&f>=500?"high":p<=5&&f>=100?"medium":"low";const y=parseFloat(e.last_price_dollars||"0")*100;const $={venue:"kalshi",ticker:e.ticker||i,title:e.title||e.subtitle||i,bestBid:d,bestAsk:u,spread:p,bidDepth:h,askDepth:m,liquidityScore:g,volume24h:parseFloat(e.volume_24h_fp||"0"),openInterest:parseFloat(e.open_interest_fp||"0"),lastPrice:Math.round(y),expiry:e.close_time||e.expiration_time||null,bidLevels:c.slice(0,5),askLevels:l.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);const t=e-7*86400;const n=await(0,o.getBatchCandlesticks)({tickers:[i],startTs:t,endTs:e,periodInterval:1440});const s=n.find((e=>e.market_ticker===i))||n[0];const 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;const n=typeof t==="string"?parseFloat(t)*100:typeof t==="number"?t:0;return Math.round(n)})).filter((e=>e>0));if(e.length>=2){$.sparkline=makeSparkline(e)}}}catch{}}if(!$.sparkline){const t=parseFloat(e.previous_price_dollars||"0")*100;if(t>0&&Math.abs(t-$.lastPrice)>0){const e=$.lastPrice-Math.round(t);const n=e>=0?r.c.green:r.c.red;const s=e>=0?`+${e}`:`${e}`;$.sparkline=`prev ${Math.round(t)}¢ → now ${$.lastPrice}¢ ${n}${s}${r.c.reset}`}}}n.push($)}catch(e){console.error(`${r.c.red}Failed to fetch ${i}: ${e.message}${r.c.reset}`)}}if(n.length===0){console.log(`\n ${r.c.dim}No markets found. Check the ticker and try again.${r.c.reset}\n`);return}if(t.json){console.log(JSON.stringify(n,null,2));return}for(const e of n){const t=e.venue==="polymarket"?`${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=e.liquidityScore==="high"?r.c.green:e.liquidityScore==="medium"?r.c.yellow:r.c.red;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)}`:""));if(e.sparkline){console.log(` 7d ${e.sparkline}`)}if(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];const s=e.askLevels[n];const 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);const 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()}}function makeSparkline(e){if(e.length<2)return"";const t=Math.min(...e);const n=Math.max(...e);const s=n-t||1;const o="▁▂▃▄▅▆▇█";const i=e.map((e=>{const n=Math.round((e-t)/s*7);return o[n]})).join("");const a=Math.round(e[0]);const c=Math.round(e[e.length-1]);const l=c-a;const d=l>=0?r.c.green:r.c.red;const u=l>=0?`+${l}`:`${l}`;return`${i} ${a}¢→${c}¢ ${d}${u}${r.c.reset}`}},80928:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.cancelCommand=cancelCommand;const s=n(96139);const o=n(11627);const i=n(99236);async function cancelCommand(e,t){(0,o.requireTrading)();if(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)))}if(n.length===0){console.log(`\n ${i.c.dim}No resting orders to cancel.${i.c.reset}\n`);return}console.log(`\n Cancelling ${n.length} order(s)...`);if(!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)}console.log(`\n ${i.c.green}✓${i.c.reset} Cancelled ${n.length} order(s).\n`);return}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`)}},97499:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.contextCommand=contextCommand;const s=n(19218);const o=n(96139);const i=n(99236);const r=n(35178);const a=process.env.SF_API_URL||"https://simplefunctions.dev";async function contextCommand(e,t){if(!e){const e=await fetch(`${t.apiUrl||a}/api/public/context`);if(!e.ok){console.error(` Error: ${e.status} ${await e.text()}`);return}const n=await e.json();if(t.share){await(0,r.shareOutput)("context","",n);return}if(t.json){console.log(JSON.stringify(n,null,2));return}const s=n.scannedAt?(0,i.shortDate)(n.scannedAt):"no scan yet";const 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 c=n.traditional||[];if(c.length>0){const e=c.map((e=>{const t=e.changePct||0;const n=t>0?i.c.green:t<0?i.c.red:i.c.dim;const 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 l=n.highlights||[];if(l.length>0){console.log(`${i.c.bold}${i.c.cyan}Highlights${i.c.reset}`);for(const e of l){console.log(` ${i.c.bold}${e.title}${i.c.reset}`);console.log(` ${i.c.dim}${e.detail}${i.c.reset}`);if(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 d=n.categories||[];if(d.length>0){console.log(`${i.c.bold}Categories${i.c.reset} ${i.c.dim}(${d.length} total)${i.c.reset}`);console.log(`${i.c.dim}${"─".repeat(70)}${i.c.reset}`);for(const e of d){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=e.venue==="kalshi"?`${i.c.cyan}K${i.c.reset}`:`${i.c.magenta}P${i.c.reset}`;const n=e.change24h||0;const s=n>0?i.c.green:n<0?i.c.red:i.c.dim;const o=n!==0?`${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}`);if(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=e.venue==="kalshi"?`${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 u=n.edges||[];if(u.length>0){console.log(`${i.c.bold}Thesis Edges${i.c.reset}`);for(const e of u.slice(0,6)){const t=e.venue==="kalshi"?`${i.c.cyan}K${i.c.reset}`:`${i.c.magenta}P${i.c.reset}`;const 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 p=n.signals||[];if(p.length>0){console.log(`${i.c.bold}Recent Evaluations${i.c.reset}`);for(const e of p.slice(0,5)){const t=e.confidenceDelta;const 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}`;const s=timeAgo(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()}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}`);console.log();return}const n=new s.SFClient(t.apiKey,t.apiUrl);const c=await n.getContext(e);if(t.json){console.log(JSON.stringify(c,null,2));return}console.log(`\n${i.c.bold}Thesis:${i.c.reset} ${c.thesis||c.rawThesis||"(unknown)"}`);const l=c.confidence!==null&&c.confidence!==undefined?(0,i.pct)(c.confidence):"-";const d=c.lastEvaluation?.confidenceDelta;const u=d?` (${(0,i.delta)(d)} since last eval)`:"";console.log(`${i.c.bold}Confidence:${i.c.reset} ${l}${u}`);console.log(`${i.c.bold}Status:${i.c.reset} ${c.status}`);console.log(`${i.c.bold}Last Updated:${i.c.reset} ${(0,i.shortDate)(c.updatedAt)}`);const p=c.causalTree?.nodes;if(p&&p.length>0){(0,i.header)("Causal Tree");for(const e of p){const t=" ".repeat((e.depth||0)+1);const n=e.probability!==undefined?(0,i.pct)(e.probability):"-";const 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 h=null;if((0,o.isKalshiConfigured)()){try{h=await(0,o.getPositions)()}catch{}}const m=new Map;if(h){for(const e of h)m.set(e.ticker,e)}const f=c.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;const n=e>10?i.c.green:e>0?i.c.yellow:i.c.red;const s=t.marketPrice??t.currentPrice??0;const o=t.market||t.marketTitle||t.marketId||"?";const r=t.orderbook;const a=r?` ${i.c.dim}spread ${r.spread}¢ ${r.liquidityScore}${i.c.reset}`:"";const c=m.get(t.marketId);let l="";if(c){const e=c.unrealized_pnl||0;const t=e>0?i.c.green:e<0?i.c.red:i.c.dim;const 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(c.lastEvaluation?.summary){(0,i.header)("Last Evaluation");console.log(` ${i.c.dim}${(0,i.shortDate)(c.lastEvaluation.evaluatedAt)} | model: ${c.lastEvaluation.model||""}${i.c.reset}`);console.log(` ${c.lastEvaluation.summary}`);if(c.lastEvaluation.positionRecommendations?.length>0){console.log(`\n ${i.c.bold}Position Recommendations:${i.c.reset}`);for(const e of c.lastEvaluation.positionRecommendations){const t=e.recommendation==="hold"?i.c.dim:e.recommendation==="close"?i.c.red:i.c.yellow;console.log(` [${(e.positionId||"").slice(0,8)}] ${t}${e.recommendation}${i.c.reset} — ${e.reason}`)}}}if(c.edgeMeta?.lastRescanAt){console.log(`\n${i.c.dim}Last rescan: ${(0,i.shortDate)(c.edgeMeta.lastRescanAt)}${i.c.reset}`)}console.log("")}function timeAgo(e){const t=Date.now()-new Date(e).getTime();const n=Math.round(t/6e4);if(n<60)return`${n}m`;const s=Math.round(n/60);if(s<24)return`${s}h`;return`${Math.round(s/24)}d`}},46222:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.createCommand=createCommand;const s=n(19218);const o=n(99236);async function createCommand(e,t){const n=new s.SFClient(t.apiKey,t.apiUrl);const i=!t.async;if(!t.json){if(i){console.log(`${o.c.dim}Creating thesis (sync mode — waiting for formation)...${o.c.reset}`)}else{console.log(`${o.c.dim}Creating thesis (async mode)...${o.c.reset}`)}}const r=await n.createThesis(e,i);const a=r.thesis?.id||r.thesisId||r.id||null;if(t.json){console.log(JSON.stringify({id:a,status:r.thesis?.status||r.status||"forming",result:r},null,2));return}if(!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}`);if(r.thesis?.confidence){console.log(` ${o.c.bold}Confidence:${o.c.reset} ${Math.round(parseFloat(r.thesis.confidence)*100)}%`)}if(r.thesis?.causalTree?.nodes){console.log(` ${o.c.bold}Nodes:${o.c.reset} ${r.thesis.causalTree.nodes.length}`)}if(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}`)}},60952:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.dashboardCommand=dashboardCommand;const s=n(19218);const o=n(96139);const i=n(34331);const r=n(11627);const a=n(97325);const c=n(99844);function categorize(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 timeAgo(e){const t=Date.now()-new Date(e).getTime();const 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`;const o=Math.floor(s/24);return`${o}d ago`}async function dashboardCommand(e){if(!e?.json&&!e?.once){await(0,c.startDashboard)();return}const t=new s.SFClient(e?.apiKey,e?.apiUrl);const[n,a]=await Promise.all([t.listTheses(),(0,o.getPositions)().catch((()=>null))]);const l=n.theses||n;const d=[];for(const e of l){try{const n=await t.getContext(e.id);d.push(n)}catch{d.push(null)}}if(a){for(const e of a){const t=await(0,o.getMarketPrice)(e.ticker);if(t!==null){e.current_value=t;e.unrealized_pnl=Math.round((t-e.average_price_paid)*e.quantity)}}}const u=[];for(const e of d){if(!e?.edges)continue;for(const t of e.edges){u.push(t)}}const p=new Map;for(const e of u){const t=p.get(e.marketId);if(!t||Math.abs(e.edge)>Math.abs(t.edge)){p.set(e.marketId,e)}}const h=new Set(a?.map((e=>e.ticker))||[]);const m=[...p.values()].filter((e=>!h.has(e.marketId))).sort(((e,t)=>Math.abs(t.edge)-Math.abs(e.edge))).slice(0,10);const[f,g,y]=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 $=[];if(e?.json){try{$=(await t.getFeed(24,20)).evaluations||[]}catch{}}if(e?.json){console.log(JSON.stringify({theses:l,positions:a||[],polymarketPositions:y,orders:f,balance:g,unpositionedEdges:m,feed:$,kalshiConfigured:(0,o.isKalshiConfigured)(),polymarketConfigured:!!(0,r.loadConfig)().polymarketWalletAddress,timestamp:(new Date).toISOString()},null,2));return}console.log();console.log(" SimpleFunctions Dashboard");console.log(" "+"─".repeat(50));console.log();console.log(" Theses");if(l.length===0){console.log(" (none)")}else{for(let e=0;e<l.length;e++){const t=l[e];const n=d[e];const s=t.id.slice(0,8);const o=(t.title||"").slice(0,35).padEnd(35);const i=t.confidence!=null?`${Math.round(t.confidence*100)}%`:"?%";const r=n?.edges?.length||0;const a=t.updatedAt?timeAgo(t.updatedAt):"?";console.log(` ${s} ${o} ${i.padStart(4)} ${String(r).padStart(2)} edges updated ${a}`)}}console.log();console.log(" Positions");if(!a||a.length===0){console.log(" (no Kalshi positions or Kalshi not configured)")}else{let e=0;let t=0;for(const n of a){const s=(n.ticker||"").padEnd(22);const o=String(n.quantity||0).padStart(5);const i=`${n.average_price_paid||0}¢`;const r=typeof n.current_value==="number"?`${n.current_value}¢`:"?¢";const a=n.unrealized_pnl||0;const c=(a/100).toFixed(2);const l=a>=0?`+$${c}`:`-$${Math.abs(parseFloat(c)).toFixed(2)}`;const d=(n.average_price_paid||0)*(n.quantity||0);e+=d;t+=a;console.log(` ${s} ${o} @ ${i.padEnd(5)} now ${r.padEnd(5)} ${l}`)}console.log(" "+"─".repeat(45));const n=(e/100).toFixed(0);const s=(t/100).toFixed(2);const o=t>=0?`+$${s}`:`-$${Math.abs(parseFloat(s)).toFixed(2)}`;console.log(` Total cost: $${n} | P&L: ${o}`)}console.log();if(a&&a.length>0){console.log(" Risk Exposure");const e=new Map;for(const t of a){const n=categorize(t.ticker||"");const s=e.get(n)||{cost:0,contracts:0,tickers:[]};const o=(t.average_price_paid||0)*(t.quantity||0);s.cost+=o;s.contracts+=t.quantity||0;if(!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)}`;const 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(m.length>0){console.log(" Top Unpositioned Edges");for(const e of m){const t=(e.market||e.marketId||"").slice(0,25).padEnd(25);const n=`${e.marketPrice}¢`;const s=`${e.thesisPrice}¢`;const o=e.edge>0?`+${e.edge}`:`${e.edge}`;const i=e.orderbook?.liquidityScore||"?";console.log(` ${t} ${n.padStart(5)} → ${s.padStart(5)} edge ${o.padStart(4)} ${i}`)}console.log()}}},81466:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.deltaCommand=deltaCommand;const s=n(19218);const o=n(99236);async function deltaCommand(e,t){const n=new s.SFClient(t.apiKey,t.apiUrl);const i=t.since?new Date(t.since):new Date(Date.now()-parseInt(t.hours||"6")*36e5);if(isNaN(i.getTime())){throw new Error(`Invalid timestamp: "${t.since}". Use ISO 8601 format (e.g., 2026-03-28T14:00:00Z)`)}const run=async()=>{const s=i.toISOString();const r=await n.getChanges(e,s);if(t.json){console.log(JSON.stringify(r,null,2));return}if(!r.changed){console.log(`${o.c.dim}No changes since ${i.toLocaleString()}.${o.c.reset}`);return}const a=(0,o.shortId)(e);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}`);if(r.confidence!==undefined){const e=Math.round(r.confidence*100);const t=r.previousConfidence!==undefined?Math.round(r.previousConfidence*100):null;const n=t!==null?e-t:null;let s="";if(n!==null){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}`)}if(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((e.newProbability??e.newProb??0)*100);const n=e.previousProbability??e.prevProb;let s="";if(n!==undefined&&n!==null){const e=Math.round(n*100);const i=t-e;s=i>0?` ${o.c.green}+${i}%${o.c.reset}`:i<0?` ${o.c.red}${i}%${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";const 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);const n=e.edge??0;const s=e.previousEdge??null;const i=n>0?`+${n}`:`${n}`;let r="";if(s!==null){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){console.log(`${o.c.dim}Watching for changes every 60s... (Ctrl+C to stop)${o.c.reset}`);while(true){await run();await new Promise((e=>setTimeout(e,6e4)));console.clear()}}else{await run()}}},91262:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.edgesCommand=edgesCommand;const s=n(19218);const o=n(96139);const i=n(99236);const r=n(35178);async function edgesCommand(e){const t=new s.SFClient(e.apiKey,e.apiUrl);const n=parseInt(e.limit||"20");const a=e.minEdge?parseInt(e.minEdge):0;const c=e.minLiquidity?.toLowerCase()||"";const l=e.sort||"edge";const 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();const n=e.theses||e;u=(Array.isArray(n)?n:[]).filter((e=>e.status==="active"))}if(u.length===0){if(e.json){console.log(JSON.stringify({edges:[],totalEdges:0}));return}(0,i.emptyState)("active theses",'Create one: sf create "your market thesis"');return}p(`${i.c.dim}Fetching edges from ${u.length} ${u.length===1?"thesis":"theses"}...${i.c.reset}`);const h=[];const 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:[]}}}));const f=await Promise.all(m);for(const{thesisId:e,edges:t}of f){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:typeof n.marketPrice==="number"?n.marketPrice:0,thesisPrice:typeof n.thesisPrice==="number"?n.thesisPrice:0,edge:typeof n.edge==="number"?n.edge:0,executableEdge:typeof n.executableEdge==="number"?n.executableEdge:null,spread:n.orderbook?.spread??null,liquidityScore:n.orderbook?.liquidityScore??null,thesisId:e,position:null})}}if(h.length===0){if(e.json){console.log(JSON.stringify({edges:[],totalEdges:0,thesesScanned:u.length}));return}(0,i.emptyState)("edges",`Scanned ${u.length} theses. Edges appear when thesis price diverges from market price.`);return}const g=new Map;for(const e of h){const t=e.marketId;if(!t)continue;const n=g.get(t);if(!n||Math.abs(e.edge)>Math.abs(n.edge)){g.set(t,e)}}let y=Array.from(g.values());if(a>0){y=y.filter((e=>Math.abs(e.edge)>=a))}if(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)();if($){for(const e of $){const t=await(0,o.getMarketPrice)(e.ticker);if(t!==null){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)));if(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)}}}}}if(l==="spread"){y.sort(((e,t)=>(e.spread??999)-(t.spread??999)))}else{y.sort(((e,t)=>{const n=e.executableEdge!==null?e.executableEdge:e.edge;const s=t.executableEdge!==null?t.executableEdge:t.edge;return Math.abs(s)-Math.abs(n)}))}const k=y.slice(0,n);const b={totalEdges:y.length,displayed:k.length,thesesScanned:u.length,edges:k};if(e.share){await(0,r.shareOutput)("edges","",b);return}if(e.json){console.log(JSON.stringify(b,null,2));return}console.log();(0,i.header)(`Top Edges Across ${u.length} Theses`);console.log();const w=[(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}${w}${i.c.reset}`);(0,i.hr)(100);for(const e of k){const t=(0,i.trunc)(e.market,31);const n=`${e.marketPrice}¢`;const s=`${e.thesisPrice}¢`;const o=e.edge>0?`+${e.edge}`:`${e.edge}`;const r=e.executableEdge!==null?e.executableEdge>0?`+${e.executableEdge}`:`${e.executableEdge}`:"—";const a=e.spread!==null?`${e.spread}¢`:"—";const c=e.liquidityScore||"—";const l=(0,i.shortId)(e.thesisId);const d=e.edge>0?i.c.green:e.edge<0?i.c.red:i.c.dim;const u=e.executableEdge!==null?e.executableEdge>0?i.c.green:i.c.red:i.c.dim;const p=c==="high"?i.c.green:c==="medium"?i.c.yellow:i.c.dim;let h=`${i.c.dim}—${i.c.reset}`;if(e.position){const t=e.position;const 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 _=k.filter((e=>e.position));if(_.length>0){let e=0;let t=0;for(const n of _){e+=n.position.totalCost;t+=n.position.pnl}const n=`$${(e/100).toFixed(0)}`;const s=t>=0?i.c.green:i.c.red;const o=t>=0?"+":"-";const r=`${s}${o}$${(Math.abs(t)/100).toFixed(0)}${i.c.reset}`;console.log(`${i.c.bold}Total positioned:${i.c.reset} ${n} cost | P&L: ${r}`)}const S=k.filter((e=>!e.position&&e.edge>0));if(S.length>0){const e=S[0];const t=e.executableEdge!==null?`exec +${e.executableEdge}`:`edge +${e.edge}`;const 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()}},67509:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.evaluateCommand=evaluateCommand;const s=n(19218);const o=n(99236);async function evaluateCommand(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);console.log(`\n${o.c.green}✓${o.c.reset} Evaluation complete`);if(i.evaluation){const e=i.evaluation;if(e.confidenceDelta!==undefined){const t=e.confidenceDelta;const 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}`)}if(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=t.recommendation==="hold"?o.c.dim:t.recommendation==="close"?o.c.red:o.c.yellow;console.log(` [${t.positionId.slice(0,8)}] ${e}${t.recommendation}${o.c.reset} — ${t.reason}`)}}}console.log("")}},22835:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.exploreCommand=exploreCommand;const s=n(35178);const o=n(99236);const i="https://simplefunctions.dev";async function exploreCommand(e,t){if(!e){const e=await fetch(`${i}/api/public/theses`);if(!e.ok){console.error(` Error: ${e.status} ${await e.text()}`);return}const{theses:n}=await e.json();if(t?.share){await(0,s.shareOutput)("explore","",{theses:n});return}if(t?.json){console.log(JSON.stringify(n,null,2));return}console.log("\n Public Theses\n");if(n.length===0){console.log(` ${o.c.dim}No public theses yet. Publish yours: sf publish <id>${o.c.reset}\n`);return}for(const e of n){const t=e.confidence!=null?Math.round(e.confidence*100):"?";const n=e.impliedReturn!=null?`${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)}`)}console.log(`\n ${n.length} public theses. Use: sf explore <slug>\n`);return}const n=await fetch(`${i}/api/public/thesis/${e}`);if(!n.ok){if(n.status===404){console.error(` Not found: ${e}`)}else{console.error(` Error: ${n.status} ${await n.text()}`)}return}const r=await n.json();if(t?.json){console.log(JSON.stringify(r,null,2));return}const a=r.thesis;const c=r.impliedReturns;console.log(`\n ${a.title}`);console.log(` ${a.slug} | ${a.confidence!=null?Math.round(a.confidence*100):"?"}% | ${a.status} | published ${a.publishedAt?.slice(0,10)||"?"}`);if(a.description)console.log(` ${a.description}`);console.log("");if(r.causalTree?.nodes?.length){console.log(" Causal Tree");for(const e of r.causalTree.nodes){const t="█".repeat(Math.round((e.probability||0)*10))+"░".repeat(10-Math.round((e.probability||0)*10));console.log(` ${e.id} ${(e.label||"").slice(0,35).padEnd(35)} ${Math.round((e.probability||0)*100)}% ${t}`);if(e.children){for(const t of e.children){const e="█".repeat(Math.round((t.probability||0)*10))+"░".repeat(10-Math.round((t.probability||0)*10));console.log(` ${t.id} ${(t.label||"").slice(0,33).padEnd(33)} ${Math.round((t.probability||0)*100)}% ${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(e.delta*100)}`:`${Math.round(e.delta*100)}`;console.log(` ${(e.evaluatedAt||"").slice(0,16)} ${Math.round(e.confidence*100)}% (${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("")}}},44478:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.feedCommand=feedCommand;const s=n(19218);const o=n(99236);async function feedCommand(e){const t=new s.SFClient(e.apiKey,e.apiUrl);const n=parseInt(e.hours||"24");const i=await t.getFeed(n,200);let r=i.feed||[];if(r.length===0){console.log(`${o.c.dim}No evaluations in the last ${n} hours.${o.c.reset}`);return}if(e.thesis){r=r.filter((t=>t.thesisId.startsWith(e.thesis)||t.thesisShortId===e.thesis));if(r.length===0){console.log(`${o.c.dim}No evaluations for ${e.thesis} in the last ${n} hours.${o.c.reset}`);return}}if(e.json){console.log(JSON.stringify(r,null,2));return}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);const n=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});const s=Math.round(e.confidence*100);const i=Math.round(e.delta*100);let r;if(i>0){r=`${o.c.green}+${i}%${o.c.reset}`}else if(i<0){r=`${o.c.red}${i}%${o.c.reset}`}else{r=`${o.c.dim}0%${o.c.reset}`}const a=e.thesisShortId||e.thesisId?.slice(0,8)||"?";const c=(e.summary||"No summary").replace(/\n/g," ").slice(0,80);const l=e.updatedNodes||[];const d=l.length>0?l.slice(0,3).map((e=>`${e.nodeId}→${Math.round((e.newProb||0)*100)}%`)).join(", "):"";console.log(`${o.c.dim}[${n}]${o.c.reset} `+`${o.c.cyan}${a}${o.c.reset} `+`${s}% (${r}) `+`${o.c.dim}${c}${o.c.reset}`);if(d){console.log(`${" ".repeat(9)} ${o.c.dim}nodes: ${d}${o.c.reset}`)}}console.log(`${o.c.dim}${"─".repeat(75)}${o.c.reset}`);console.log()}},63746:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.fillsCommand=fillsCommand;const s=n(96139);const o=n(99236);async function fillsCommand(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){console.log(JSON.stringify(t.fills,null,2));return}if(t.fills.length===0){console.log(`${o.c.dim}No fills.${o.c.reset}`);return}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?`${parseFloat(e.yes_price_dollars)*100}¢`:`${e.yes_price||"?"}¢`;const n=e.side==="yes"?`${o.c.green}YES${o.c.reset}`:`${o.c.red}NO${o.c.reset}`;const s=e.action||"buy";const i=e.count_fp||e.count||"?";const 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}`)}},28423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.forecastCommand=forecastCommand;const s=n(96139);const o=n(99236);const i="https://api.elections.kalshi.com/trade-api/v2";async function forecastCommand(e,t){const n=parseInt(t.days||"7");const 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();const 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);const u=d-n*86400;const p=await(0,s.getForecastHistory)({seriesTicker:c,eventTicker:e,percentiles:[5e3,7500,9e3],startTs:u,endTs:d,periodInterval:1440});if(!p||p.length===0){console.log(`${o.c.dim}No forecast data for ${e}${o.c.reset}`);return}if(t.json){console.log(JSON.stringify(p,null,2));return}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(e.end_period_ts*1e3).toISOString().slice(0,10);const n=e.percentile_points||[];const s=n.find((e=>e.percentile===5e3))?.formatted_forecast||"-";const o=n.find((e=>e.percentile===7500))?.formatted_forecast||"-";const i=n.find((e=>e.percentile===9e3))?.formatted_forecast||"-";console.log(` ${t.padEnd(14)} ${s.padEnd(12)} ${o.padEnd(12)} ${i}`)}}},5596:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.getCommand=getCommand;const s=n(19218);const o=n(99236);async function getCommand(e,t){const n=new s.SFClient(t.apiKey,t.apiUrl);const i=await n.getThesis(e);if(t.json){console.log(JSON.stringify(i,null,2));return}const r=i;const a=i.positions||[];(0,o.header)(`Thesis: ${(r.id||e).slice(0,8)}`);(0,o.hr)();console.log(`${o.c.bold}Status:${o.c.reset} ${r.status||"-"}`);const c=r.confidence?(0,o.pct)(parseFloat(r.confidence)):"-";console.log(`${o.c.bold}Confidence:${o.c.reset} ${c}`);const l=r.createdAt instanceof Date?r.createdAt.toISOString():r.createdAt;const d=r.updatedAt instanceof Date?r.updatedAt.toISOString():r.updatedAt;console.log(`${o.c.bold}Created:${o.c.reset} ${(0,o.shortDate)(l)}`);console.log(`${o.c.bold}Updated:${o.c.reset} ${(0,o.shortDate)(d)}`);if(r.title){console.log(`${o.c.bold}Title:${o.c.reset} ${r.title}`)}console.log(`${o.c.bold}Thesis:${o.c.reset} ${r.rawThesis||"-"}`);if(r.webhookUrl){console.log(`${o.c.bold}Webhook:${o.c.reset} ${r.webhookUrl}`)}const u=r.causalTree;if(u&&u.nodes){(0,o.header)("Causal Tree");printNodes(u.nodes,0)}const p=r.edgeAnalysis;if(p&&p.edges){(0,o.header)("Edge Analysis");console.log(`${o.c.dim}Analyzed: ${(0,o.shortDate)(p.analyzedAt)}${o.c.reset}`);if(p.lastRescanAt){console.log(`${o.c.dim}Last rescan: ${(0,o.shortDate)(p.lastRescanAt)}${o.c.reset}`)}for(const e of p.edges){const t=e.edgeSize??0;const 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(a.length>0){(0,o.header)("Positions");for(const e of a){if(!e)continue;const t=e.status==="open"?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 h=r.lastEvaluation;if(h){(0,o.header)("Last Evaluation");const e=h.evaluatedAt instanceof Date?h.evaluatedAt.toISOString():h.evaluatedAt;console.log(`${o.c.dim}${(0,o.shortDate)(e)} | model: ${h.model||"-"}${o.c.reset}`);if(h.confidenceDelta!==undefined){const e=h.confidenceDelta;const t=e>0?o.c.green:e<0?o.c.red:o.c.dim;console.log(`Confidence: ${(0,o.pct)(h.previousConfidence)} → ${(0,o.pct)(h.newConfidence)} ${t}(${(0,o.delta)(e)})${o.c.reset}`)}if(h.summary){console.log(`\n${h.summary}`)}}console.log("")}function printNodes(e,t){for(const n of e){if(!n)continue;const e=" ".repeat(t+1);const s=n.probability!==undefined?(0,o.pct)(n.probability):"-";const i=n.importance!==undefined?` imp:${n.importance}`:"";console.log(`${e}${o.c.cyan}${n.id}${o.c.reset} ${n.label} ${o.c.dim}(${s}${i})${o.c.reset}`);if(n.children&&n.children.length>0){printNodes(n.children,t+1)}}}},87604:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.heartbeatCommand=heartbeatCommand;const s=n(99236);async function heartbeatCommand(e,t,n){const o=n.newsInterval||n.xInterval||n.model||n.budget!==undefined||n.pause||n.resume;if(o){const o={};if(n.newsInterval)o.newsIntervalMin=parseInt(n.newsInterval,10);if(n.xInterval)o.xIntervalMin=parseInt(n.xInterval,10);if(n.model)o.evalModelTier=n.model;if(n.budget!==undefined)o.monthlyBudgetUsd=parseFloat(n.budget);if(n.pause)o.paused=true;if(n.resume)o.paused=false;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){console.error(` ${s.c.red}✗ ${e.message}${s.c.reset}`);return}}try{const n=await e.getHeartbeatConfig(t);const o=n.config;const 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}`;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}`);if(i.budgetRemaining!==null){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}`)}}},9708:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.historyCommand=historyCommand;const s=n(96139);const o=n(99236);async function historyCommand(e,t){const n=await(0,s.getHistoricalMarket)(e);if(!n){console.log(`${o.c.dim}No historical data for ${e}${o.c.reset}`);return}if(t.json){console.log(JSON.stringify(n,null,2));return}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||"-"}`);if(n.last_price_dollars){console.log(` Last Price: ${Math.round(parseFloat(n.last_price_dollars)*100)}¢`)}if(n.settlement_value!==undefined){console.log(` Settlement: ${n.settlement_value}`)}if(n.volume){console.log(` Volume: ${n.volume}`)}if(n.open_interest){console.log(` Open Int: ${n.open_interest}`)}if(n.expiration_time){console.log(` Expired: ${n.expiration_time}`)}console.log()}},30896:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.ideasCommand=ideasCommand;const s=n(99236);async function ideasCommand(e){const t=process.env.SF_API_URL||"https://simplefunctions.dev";const n=new URLSearchParams;if(e.category)n.set("category",e.category);if(e.fresh)n.set("freshness",e.fresh);const o=await fetch(`${t}/api/public/ideas?${n.toString()}`);if(!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){console.log(JSON.stringify(i,null,2));return}const r=i.ideas||i;if(!Array.isArray(r)||r.length===0){console.log(`\n ${s.c.dim}No trade ideas available.${s.c.reset}\n`);return}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=e.direction==="long"?s.c.green+"▲ LONG"+s.c.reset:s.c.red+"▼ SHORT"+s.c.reset;const n="●".repeat(Math.min(e.conviction||3,5));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||""}`);if(e.catalyst)console.log(` ${s.c.dim}Catalyst: ${e.catalyst}${s.c.reset}`);if(e.risk)console.log(` ${s.c.dim}Risk: ${e.risk}${s.c.reset}`);if(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()}}},15472:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.registerIntents=registerIntents;const s=n(19218);const o=n(99236);const i={pending:"[33m",armed:"[36m",triggered:"[35m",executing:"[34m",filled:"[32m",partial:"[33m",expired:"[90m",cancelled:"[90m",rejected:"[31m"};function formatIntent(e){const t=i[e.status]||"";const n=[];const s=e.action.toUpperCase();const r=e.direction.toUpperCase();const a=e.maxPrice?` @ ≤${e.maxPrice}c`:" @ market";const c=e.venue==="kalshi"?"K":"P";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}`);if(e.triggerType!=="immediate"){const t=describeTrigger(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);const d=l.toLocaleDateString("en-US",{month:"short",day:"numeric"});n.push(` ${o.c.dim}expires ${d} · source: ${e.source}${e.rationale?` · "${e.rationale.slice(0,60)}"`:""}${o.c.reset}`);return n.join("\n")}function describeTrigger(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}}function parseTrigger(e){if(e==="immediate")return{type:"immediate"};const[t,n]=e.split(":");if(t==="below"&&n)return{type:"price_below",price:parseInt(n)};if(t==="above"&&n)return{type:"price_above",price:parseInt(n)};throw new Error(`Unknown trigger: "${e}". Use: immediate, below:<cents>, above:<cents>`)}function registerIntents(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;const n=e.all?{}:{active:!e.status,status:e.status};const{intents:i}=await t.listIntents(n);if(e.json){console.log(JSON.stringify(i,null,2));return}if(!i||i.length===0){(0,o.emptyState)("intents","Create one: sf intent buy TICKER QTY --price CENTS");return}console.log(`\n ${o.c.bold}INTENTS${o.c.reset} (${i.length})\n`);for(const e of i){console.log(formatIntent(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 createIntentCommand("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 createIntentCommand("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;const{intent:i}=await n.getIntentDetail(e);if(t.json){console.log(JSON.stringify(i,null,2));return}console.log(`\n ${o.c.bold}Intent ${i.id.slice(0,8)}${o.c.reset}\n`);console.log(formatIntent(i));console.log();if(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:false});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);const 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)}}))}async function createIntentCommand(e,t,n,i){try{const r=new s.SFClient;const a=parseInt(n);if(isNaN(a)||a<1){throw new Error("Quantity must be a positive integer")}const c=parseTrigger(i.trigger||"immediate");const l=i.price?parseInt(i.price):undefined;if(l!==undefined&&(l<1||l>99)){throw new Error("Price must be 1-99 cents")}const d={"1h":60*60*1e3,"6h":6*60*60*1e3,"1d":24*60*60*1e3,"3d":3*24*60*60*1e3,"1w":7*24*60*60*1e3};const u=d[i.expire]||d["1d"];const 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"};const h=await r.createIntent(p);if(i.json){console.log(JSON.stringify(h,null,2));return}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"}`);if(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:true});t.liquidityCommand=liquidityCommand;const s=n(19218);const o=n(96139);const i=n(34331);const r=n(97325);const a=n(99236);function classifyHorizon(e){const t=Date.now();const n=new Date(e).getTime();const s=(n-t)/(1e3*60*60*24);if(s<7)return"weekly";if(s<=35)return"monthly";return"long-term"}function horizonLabel(e){switch(e){case"weekly":return"weekly (<7d)";case"monthly":return"monthly (7-35d)";case"long-term":return"long-term (>35d)"}}function calcSlippage100(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;let 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"∞";const i=o/t;return(i*100).toFixed(1)+"¢"}async function batchProcess(e,t,n,s){const o=[];for(let i=0;i<e.length;i+=n){const r=e.slice(i,i+n);const a=await Promise.allSettled(r.map(t));for(const e of a){o.push(e.status==="fulfilled"?e.value:null)}if(i+n<e.length){await new Promise((e=>setTimeout(e,s)))}}return o}async function liquidityCommand(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}`)}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}`);console.log();return}const n=e.topic?t.filter((t=>t.toLowerCase()===e.topic.toLowerCase())):t;if(e.topic&&n.length===0){const n=t.join(", ");console.error(`Unknown topic: ${e.topic}. Valid topics: ${n}`);process.exit(1)}let c=new Set;if((0,o.isKalshiConfigured)()){try{const e=await(0,o.getPositions)();if(e){c=new Set(e.map((e=>e.ticker)))}}catch{}}const l={};for(const e of n){const t=r.TOPIC_SERIES[e];const n=[];for(const e of t){try{const t=await(0,s.kalshiFetchMarketsBySeries)(e);n.push(...t)}catch{}}if(n.length>0){l[e]=n}}const d=e.venue!=="kalshi";if(d){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||[]){if(!t.active||t.closed||!t.enableOrderBook)continue;if(!l[e])l[e]=[];l[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 u=e.horizon;const p=[];for(const[e,t]of Object.entries(l)){for(const n of t){const t=n.close_time||n.expiration_time||"";if(!t)continue;const s=classifyHorizon(t);if(u&&s!==u)continue;p.push({ticker:n.ticker,closeTime:t,topic:e,horizon:s,venue:n.venue||"kalshi",question:n.question,clobTokenIds:n.clobTokenIds})}}if(p.length===0){console.log("No markets found matching filters.");return}const h=p.filter((e=>e.venue==="kalshi"));const m=p.filter((e=>e.venue==="polymarket"));const f=await batchProcess(h,(async e=>{const t=await(0,o.getPublicOrderbook)(e.ticker);return{info:e,ob:t}}),5,100);const g=await batchProcess(m,(async e=>{if(!e.clobTokenIds)return{info:e,depth:null};const t=(0,i.parseClobTokenIds)(e.clobTokenIds);if(!t)return{info:e,depth:null};const n=await(0,i.polymarketGetOrderbookWithDepth)(t[0]);return{info:e,depth:n}}),5,100);const y=[];for(const t of f){if(!t||!t.ob)continue;const{info:n,ob:s}=t;const o=s.yes_dollars.map((([e,t])=>({price:Math.round(parseFloat(e)*100),qty:parseFloat(t)}))).filter((e=>e.price>0));const i=s.no_dollars.map((([e,t])=>({price:Math.round(parseFloat(e)*100),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;const a=i.length>0?100-i[0].price:100;const l=a-r;const d=o.reduce(((e,t)=>e+t.qty),0);const u=i.reduce(((e,t)=>e+t.qty),0);const p=calcSlippage100(s.no_dollars,100);if(e.minDepth&&d+u<e.minDepth)continue;y.push({ticker:n.ticker,shortTicker:n.ticker,topic:n.topic.toUpperCase(),horizon:n.horizon,closeTime:n.closeTime,bestBid:r,bestAsk:a,spread:l,bidDepth:d,askDepth:u,slippage100:p,held:c.has(n.ticker),venue:"kalshi"})}for(const t of g){if(!t||!t.depth)continue;const{info:n,depth:s}=t;if(e.minDepth&&s.bidDepthTop3+s.askDepthTop3<e.minDepth)continue;y.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:false,venue:"polymarket"})}if(e.json){console.log(JSON.stringify(y,null,2));return}const $=(new Date).toISOString().slice(0,10);console.log();console.log(`${a.c.bold}Liquidity Scanner${a.c.reset} ${a.c.dim}(${$} UTC)${a.c.reset}`);console.log(a.c.dim+"─".repeat(68)+a.c.reset);const k={};for(const e of y){const t=e.topic||"OTHER";if(!k[t])k[t]={};if(!k[t][e.horizon])k[t][e.horizon]=[];k[t][e.horizon].push(e)}let b=0;let w=0;let _=0;const S=["weekly","monthly","long-term"];for(const[e,t]of Object.entries(k)){for(const n of S){const s=t[n];if(!s||s.length===0)continue;const o=s.filter((e=>e.venue==="kalshi"));if(o.length>1){const e=findCommonPrefix(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)=>{if(e.venue!==t.venue)return e.venue==="kalshi"?-1:1;return e.venue==="kalshi"?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}— ${horizonLabel(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){b++;if(e.held)_++;const t=e.spread>5;if(t)w++;let n;if(e.spread<=2){n=`${a.c.green}${e.spread}¢${a.c.reset}`}else if(e.spread<=5){n=`${a.c.yellow}${e.spread}¢${a.c.reset}`}else{n=`${a.c.red}${e.spread}¢${a.c.reset}`}const s=t?" ⚠️":"";const o=e.held?` ${a.c.magenta}← held${a.c.reset}`:"";const i=(0,a.rpad)(`${e.spread}¢`,6);const 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}`;const c=e.venue==="polymarket"?`${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: ${b} markets | ${w} thin (spread>5¢) | ${_} held${a.c.reset}`);console.log()}function findCommonPrefix(e){if(e.length===0)return"";if(e.length===1)return"";let t=e[0];for(let n=1;n<e.length;n++){while(!e[n].startsWith(t)){t=t.slice(0,-1);if(t.length===0)return""}}return t}},38706:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.listCommand=listCommand;const s=n(19218);const o=n(99236);async function listCommand(e){const t=new s.SFClient(e.apiKey,e.apiUrl);const{theses:n}=await t.listTheses();if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){(0,o.emptyState)("theses",'Create one: sf create "your market thesis"');return}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=e.status==="active"?o.c.green:e.status==="forming"?o.c.yellow:o.c.dim;const 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}`)}},50869:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.loginCommand=loginCommand;const s=n(76982);const o=n(11627);const i=n(99236);const r=process.env.SF_API_URL||"https://simplefunctions.dev";async function loginCommand(e){const t=e.apiUrl||(0,o.loadConfig)().apiUrl||r;const a=(0,o.loadFileConfig)();if(a.apiKey&&!e.force){console.log(`\n ${i.c.dim}Already logged in (${a.apiKey.slice(0,12)}...).${i.c.reset}`);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`);return}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((()=>({})));console.error(` ${i.c.red}Failed to create session: ${t.error||e.status}${i.c.reset}`);return}}catch(e){console.error(` ${i.c.red}Could not reach ${t}${i.c.reset}`);return}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));const t=process.platform;const s=t==="darwin"?"open":t==="win32"?"start":"xdg-open";e(`${s} "${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=5*60*1e3;const u=2e3;const p=Date.now();while(Date.now()-p<d){await new Promise((e=>setTimeout(e,u)));try{const e=await fetch(`${t}/api/auth/cli/poll?token=${c}`);const n=await e.json();if(n.status==="ready"&&n.apiKey){(0,o.saveConfig)({...a,apiKey:n.apiKey,apiUrl:t!==r?t:undefined});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}`);console.log();return}if(n.status==="expired"){console.error(`\n ${i.c.red}Session expired. Run ${i.c.cyan}sf login${i.c.red} again.${i.c.reset}\n`);return}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`)}},23017:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.marketsCommand=marketsCommand;const s=n(35178);const o="https://simplefunctions.dev";async function marketsCommand(e){const t=await fetch(`${o}/api/public/markets`);if(!t.ok){console.error(` Error: ${t.status} ${await t.text()}`);return}const n=await t.json();if(e?.share){await(0,s.shareOutput)("markets","",n);return}if(e?.json){console.log(JSON.stringify(n,null,2));return}console.log(`\n [1mTraditional Markets[22m [2m${n.snapshotAt?.slice(0,10)||""}[22m\n`);if(!n.markets?.length){console.log(" No data available.\n");return}for(const e of n.markets){const t=e.changePct>=0?"[32m▲[39m":"[31m▼[39m";const n=e.changePct>=0?`[32m+${e.changePct}%[39m`:`[31m${e.changePct}%[39m`;const s=`$${e.price.toFixed(2)}`;console.log(` ${t} ${e.symbol.padEnd(5)} ${s.padStart(10)} ${n.padStart(16)} ${e.name}`)}console.log()}},8045:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.milestonesCommand=milestonesCommand;const s=n(19218);const o=n(99236);const i="https://api.elections.kalshi.com/trade-api/v2";async function milestonesCommand(e){const t=parseInt(e.hours||"168");const n=new Date;const r=new Date(n.getTime()+t*36e5);const a=`${i}/milestones?limit=200&minimum_start_date=${n.toISOString()}`+(e.category?`&category=${e.category}`:"");const c=await fetch(a,{headers:{Accept:"application/json"}});if(!c.ok)throw new Error(`Kalshi API ${c.status}`);const l=await c.json();let d=(l.milestones||[]).filter((e=>new Date(e.start_date).getTime()<=r.getTime()));if(e.thesis){const t=new s.SFClient(e.apiKey,e.apiUrl);const n=await t.getContext(e.thesis);const o=new Set((n.edges||[]).map((e=>e.eventTicker)).filter(Boolean));const i=new Set((n.edges||[]).map((e=>e.seriesTicker)).filter(Boolean));d=d.filter((e=>{const t=e.related_event_tickers||e.primary_event_tickers||[];return t.some((e=>o.has(e)||i.has(e.split("-")[0])))}))}if(e.json){console.log(JSON.stringify(d,null,2));return}if(d.length===0){console.log(`${o.c.dim}No milestones in the next ${t} hours.${o.c.reset}`);return}d.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 d){const t=new Date(e.start_date);const s=Math.round((t.getTime()-n.getTime())/36e5);const i=s<=24?`${o.c.bold}${s}h${o.c.reset}`:`${o.c.dim}${Math.round(s/24)}d${o.c.reset}`;const r=`${o.c.dim}[${e.category}]${o.c.reset}`;const a=(e.related_event_tickers||[]).slice(0,3).join(", ");console.log(` ${i.padEnd(12)} ${r.padEnd(25)} ${e.title}`);if(a)console.log(` ${" ".repeat(10)} ${o.c.dim}${a}${o.c.reset}`)}console.log(`\n${o.c.dim}${d.length} milestone(s)${o.c.reset}`)}},45475:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.ordersCommand=ordersCommand;const s=n(96139);const o=n(99236);async function ordersCommand(e){const t=e.status||"resting";const 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){console.log(JSON.stringify(n.orders,null,2));return}if(n.orders.length===0){console.log(`${o.c.dim}No ${t} orders.${o.c.reset}`);return}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?`${parseFloat(e.yes_price_dollars)*100}¢`:`${e.yes_price||"?"}¢`;const n=e.side==="yes"?`${o.c.green}YES${o.c.reset}`:`${o.c.red}NO${o.c.reset}`;const 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}`)}},33766:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.performanceCommand=performanceCommand;const s=n(19218);const o=n(96139);const i=n(11627);const r=n(99236);function fmtDate(e){const t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return`${t[e.getMonth()]} ${String(e.getDate()).padStart(2,"0")}`}function fmtDollar(e){const t=Math.abs(e/100);const n=t>=1e3?`${(t/1e3).toFixed(1)}k`:t>=100?t.toFixed(0):t.toFixed(2);return e>=0?`+$${n}`:`-$${n}`}function dateKey(e){return e.toISOString().slice(0,10)}function sparkline(e,t){if(e.length===0)return"";const n=Math.min(...e);const s=Math.max(...e);const o=s-n||1;const i=["▁","▂","▃","▄","▅","▆","▇","█"];return e.map((e=>{const s=Math.round((e-n)/o*(i.length-1));const a=i[s];if(t)return t(e)+a+r.c.reset;return a})).join("")}async function performanceCommand(e){if(!(0,o.isKalshiConfigured)()){console.log(`${r.c.yellow}Kalshi not configured.${r.c.reset} Run ${r.c.cyan}sf setup --kalshi${r.c.reset} first.`);return}const t=await(0,o.getFills)({limit:500});if(!t||t.fills.length===0){console.log(`${r.c.dim}No fills found.${r.c.reset}`);return}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";const o=e.side||"yes";const i=Math.round(parseFloat(e.count_fp||e.count||"0"));const r=Math.round(parseFloat(e.yes_price_dollars||"0")*100);let a=i;if(s==="sell")a=-a;if(o==="no")a=-a;const c=n.get(t)||{ticker:t,netQty:0,totalCostCents:0,totalContracts:0,earliestFillTs:Infinity};c.netQty+=a;if(a>0){const e=o==="no"?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);if(e<c.earliestFillTs)c.earliestFillTs=e}n.set(t,c)}let a=[...n.values()].filter((e=>e.netQty!==0));if(e.ticker){const t=e.ticker.toLowerCase();a=a.filter((e=>e.ticker.toLowerCase().includes(t)))}if(a.length===0){console.log(`${r.c.dim}No open positions found${e.ticker?` matching "${e.ticker}"`:""}.${r.c.reset}`);return}const c=e.since?Math.floor(new Date(e.since).getTime()/1e3):Math.min(...a.map((e=>e.earliestFillTs===Infinity?Math.floor(Date.now()/1e3)-30*86400:e.earliestFillTs)));const l=Math.floor(Date.now()/1e3);const d=await(0,o.getBatchCandlesticks)({tickers:a.map((e=>e.ticker)),startTs:c,endTs:l,periodInterval:1440});const u=new Map;for(const e of d){const t=[];for(const n of e.candlesticks||[]){const e=parseFloat(n.yes_bid?.close_dollars||"0");const s=parseFloat(n.yes_ask?.close_dollars||"0");const o=e>0&&s>0?(e+s)/2:e||s;const i=parseFloat(n.price?.close_dollars||"0")||o;const r=Math.round(i*100);const a=n.end_period_ts||n.period_end_ts||n.ts;if(a)t.push({date:dateKey(new Date(a*1e3)),close:r})}t.sort(((e,t)=>e.date.localeCompare(t.date)));u.set(e.market_ticker,t)}const p=new Set;for(const[,e]of u)for(const t of e)p.add(t.date);const h=[...p].sort();const m=new Map;for(const e of a){m.set(e.ticker,e.totalContracts>0?Math.round(e.totalCostCents/e.totalContracts):0)}const f=[];try{const e=(0,i.loadConfig)();const t=new s.SFClient(e.apiKey,e.apiUrl);const n=await t.getFeed(720);const 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||"";if(n){f.push({date:dateKey(new Date(n)),direction:t>0?"up":"down",deltaPct:Math.round(t*100),summary:e.summary||""})}}}}}catch{}const g=[];for(const e of a){const t=m.get(e.ticker)||0;const n=u.get(e.ticker)||[];const s=n.length>0?n[n.length-1].close:t;const o=(s-t)*e.netQty;const i=t*e.netQty;const r=i!==0?o/Math.abs(i)*100:0;const a=n.map((n=>(n.close-t)*e.netQty));g.push({ticker:e.ticker,qty:e.netQty,entry:t,current:s,pnlCents:o,pnlPct:r,dailyPnl:a})}g.sort(((e,t)=>Math.abs(t.pnlCents)-Math.abs(e.pnlCents)));const y=h.map((e=>{let t=0;for(const n of a){const s=u.get(n.ticker)||[];const o=m.get(n.ticker)||0;const i=s.find((t=>t.date===e));if(i)t+=(i.close-o)*n.netQty}return t}));const $=a.reduce(((e,t)=>e+t.totalCostCents),0);const k=g.reduce(((e,t)=>e+t.pnlCents),0);const b=$>0?k/$*100:0;if(e.json){console.log(JSON.stringify({positions:g.map((e=>({ticker:e.ticker,qty:e.qty,entry:e.entry,current:e.current,pnl:e.pnlCents,pnlPct:Math.round(e.pnlPct*10)/10}))),totalDailyPnl:h.map(((e,t)=>({date:e,pnl:y[t]}))),events:f,summary:{cost:$,pnl:k,pnlPct:Math.round(b*10)/10}},null,2));return}const w=h.length>0?fmtDate(new Date(h[0])):"?";const _=fmtDate(new Date);console.log();console.log(` ${r.c.bold}Portfolio Performance${r.c.reset} ${r.c.dim}(${w} → ${_})${r.c.reset}`);console.log(` ${r.c.dim}${"─".repeat(76)}${r.c.reset}`);console.log();const S=Math.max(...g.map((e=>e.ticker.length)),5)+2;const v=S+50;const pad2=(e,t)=>e.padEnd(t);console.log(` ${r.c.dim}${pad2("Ticker",S)} Qty Entry Now P&L Trend${r.c.reset}`);for(const e of g){const t=fmtDollar(e.pnlCents);const n=e.pnlCents>0?r.c.green:e.pnlCents<0?r.c.red:r.c.dim;const s=sparkline(e.dailyPnl,(e=>e>=0?r.c.green:r.c.red));console.log(` ${pad2(e.ticker,S)} `+`${(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(v)}${r.c.reset}`);const x=fmtDollar(k);const C=`${b>=0?"+":""}${b.toFixed(1)}%`;const O=k>=0?r.c.green:r.c.red;const I=sparkline(y,(e=>e>=0?r.c.green:r.c.red));console.log(` ${r.c.bold}${pad2("TOTAL",S)}${r.c.reset} `+`${(0,r.rpad)("",22)}`+`${O}${r.c.bold}${(0,r.rpad)(`${x} (${C})`,13)}${r.c.reset}`+I);if(f.length>0){const e=new Set(h);const t=f.filter((t=>e.has(t.date)));if(t.length>0){console.log();for(const e of t.slice(0,8)){const t=e.direction==="up"?`${r.c.green}▲${r.c.reset}`:`${r.c.red}▼${r.c.reset}`;const n=e.summary.length>55?e.summary.slice(0,54)+"…":e.summary;console.log(` ${t} ${r.c.dim}${fmtDate(new Date(e.date))}${r.c.reset} ${e.deltaPct>0?"+":""}${e.deltaPct}% → ${n}`)}}}console.log();const P=`$${($/100).toFixed(0)}`;console.log(` ${r.c.dim}Cost basis:${r.c.reset} ${P} ${r.c.dim}|${r.c.reset} ${O}${r.c.bold}${x} (${C})${r.c.reset}`);console.log()}},8784:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.positionsCommand=positionsCommand;const s=n(19218);const o=n(96139);const i=n(34331);const r=n(11627);const a=n(99236);async function positionsCommand(e){const t=new s.SFClient(e.apiKey,e.apiUrl);let n=null;if((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{const e=await t.listTheses();d=e.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=>e.status==="monitoring"||e.status==="active"));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);if(t!==null){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;if(!p.has(t))p.set(t,[]);p.get(t).push(e)}if(e.json){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));return}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;const n=e.average_price_paid||0;const s=e.unrealized_pnl||0;const o=s>0?a.c.green:s<0?a.c.red:a.c.dim;const i=s>=0?`+$${(s/100).toFixed(2)}`:`-$${(Math.abs(s)/100).toFixed(2)}`;const r=p.get(e.ticker)||[];const c=r[0];const l=c?.edge?.edge??c?.edge?.edgeSize??0;const d=Math.abs(l)>10?a.c.green:Math.abs(l)>5?a.c.yellow:a.c.dim;let u="HOLD";if(c){const t=e.side;const n=c.edge.direction;if(t===n&&l>3){u="HOLD"}else if(l<-3){u="CLOSE"}else{u="HOLD"}}else{u="—"}const h=u==="HOLD"?a.c.dim:u==="CLOSE"?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}`+`${d}${(0,a.rpad)(l?`${l>0?"+":""}${l.toFixed(0)}`:"-",7)}${a.c.reset}`+` ${h}${u}${a.c.reset}`)}console.log("")}else if((0,o.isKalshiConfigured)()){console.log(`\n ${a.c.dim}No open Kalshi positions.${a.c.reset}\n`)}else{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);const n=e.outcome||"YES";const s=e.size||0;const o=Math.round((e.avgPrice||0)*100);const i=Math.round((e.curPrice||e.currentPrice||0)*100);const r=e.cashPnl||(i-o)*s/100;const c=r>=0?a.c.green:a.c.red;const 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 if(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)));const 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=>e.edge.venue==="kalshi"&&!e.edge.orderbook&&Math.abs(e.edge.edge??e.edge.edgeSize??0)>5));const 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);if(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;const s=t.edge??t.edgeSize??0;const o=s>10?a.c.green:s>5?a.c.yellow:s>0?a.c.dim:a.c.red;const i=t.marketPrice??0;const r=t.thesisPrice??t.thesisImpliedPrice??0;const c=(t.market||t.marketTitle||t.marketId||"?").slice(0,29);const l=t.orderbook;const d=n.get(t.marketId);const u=l||d;const p=u?`${u.spread}¢`:"-";const h=u?u.liquidityScore:"-";const m=u?.liquidityScore==="high"?a.c.green:u?.liquidityScore==="medium"?a.c.yellow:a.c.dim;let f="WATCH";if(s>10&&u?.liquidityScore!=="low"){f="CONSIDER"}else if(s>5&&u?.liquidityScore==="high"){f="CONSIDER"}const g=f==="CONSIDER"?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}`+` ${g}${f}${a.c.reset}`)}console.log("")}else if(u.length===0){console.log(`\n${a.c.dim}No thesis edges found.${a.c.reset}\n`)}}},35344:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.promptCommand=promptCommand;async function promptCommand(e,t){const n=(t.apiUrl||process.env.SF_API_URL||"https://simplefunctions.dev").replace(/\/$/,"");const s=t.apiKey||process.env.SF_API_KEY||"";const o=new URLSearchParams;if(t.sections)o.set("sections",t.sections);if(t.maxLength)o.set("maxLength",t.maxLength);if(t.json)o.set("format","json");const i=e?`/api/thesis/${e}/prompt`:"/api/prompt";const r=o.toString()?`?${o.toString()}`:"";const 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);if(!c.endsWith("\n"))process.stdout.write("\n")}},40791:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.publishCommand=publishCommand;t.unpublishCommand=unpublishCommand;const s=n(19218);function slugify(e){return e.toLowerCase().trim().replace(/[^a-z0-9\s-]/g,"").replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,60)}async function publishCommand(e,t){const n=slugify(t.slug);if(n.length<3){console.error(`\n Error: slug too short after normalization: "${n}" (need 3+ chars)\n`);process.exit(1)}if(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`)}async function unpublishCommand(e,t){const n=new s.SFClient(t.apiKey,t.apiUrl);await n.unpublish(e);console.log(`\n ✓ Unpublished thesis ${e}\n`)}},65240:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.queryCommand=queryCommand;const s=n(35178);const o=process.env.SF_API_URL||"https://simplefunctions.dev";async function queryCommand(e,t){const n=t?.limit||"10";const i=`${o}/api/public/query?q=${encodeURIComponent(e)}&limit=${n}`;const r=await fetch(i);if(!r.ok){const e=await r.text();if(r.status===429){console.error(" Rate limited. Wait a minute and try again.")}else{console.error(` Error: ${r.status} ${e}`)}return}const a=await r.json();if(t?.share){await(0,s.shareOutput)("query",e,a);return}if(t?.json){console.log(JSON.stringify(a,null,2));return}console.log();console.log(` [1m${a.query}[22m`);console.log();if(a.answer){console.log(` ${a.answer}`);console.log()}if(a.keyFactors?.length>0){console.log(" [2mKey factors:[22m");for(const e of a.keyFactors){console.log(` • ${e}`)}console.log()}const c=a.kalshi||[];const l=a.polymarket||[];if(c.length>0||l.length>0){console.log(" [1mMarkets[22m");for(const e of c.slice(0,8)){const t=fmtVol(e.volume);const 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}`)}if(c.length>0&&l.length>0)console.log();for(const e of l.slice(0,8)){const t=fmtVol(e.volume);const 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 d=a.x||[];if(d.length>0){console.log(" [1mX signals[22m");for(const e of d.slice(0,5)){const t=`${fmtNum(e.likes)}♥ ${fmtNum(e.retweets)}⟲`;console.log(` @${e.author} ${t} ${e.text.slice(0,80)}`)}console.log()}const u=a.traditional||[];if(u.length>0){console.log(" [1mTraditional[22m");for(const e of u){const t=e.change1d>=0?"+":"";console.log(` ${e.symbol.padEnd(5)} $${e.price} ${t}${e.change1d} (${t}${e.changePct}%) ${e.name}`)}console.log()}if(a.theses?.length>0){console.log(" [1mTheses[22m");for(const e of a.theses.slice(0,3)){console.log(` ${e.confidence||"?"}% ${String(e.edges||0).padStart(2)} edges ${e.title.slice(0,50)}`)}console.log()}if(a.content?.length>0){console.log(" [1mContent[22m");for(const e of a.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 p=a.meta||{};const h=p.sources||a.sources||[];const m=p.latencyMs?`${(p.latencyMs/1e3).toFixed(1)}s`:"";console.log(` [2mSources: ${h.join(", ")}${m?` (${m})`:""}[22m`);console.log()}function fmtVol(e){if(e>1e6)return`${(e/1e6).toFixed(1)}M`;if(e>1e3)return`${(e/1e3).toFixed(0)}K`;return String(Math.round(e))}function fmtNum(e){if(e>1e6)return`${(e/1e6).toFixed(1)}M`;if(e>1e3)return`${(e/1e3).toFixed(1)}K`;return String(e)}},43423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.rfqCommand=rfqCommand;const s=n(96139);const o=n(11627);const i=n(99236);async function rfqCommand(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}`);if(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||false,...n.targetCost?{target_cost_centi_cents:parseInt(n.targetCost)*100}:{}});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)}}},52072:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.registerRuntime=registerRuntime;const s=n(19218);const o=n(96139);const i=n(99236);const r=n(79896);const a=n(16928);const c=n(70857);const l=(0,a.join)((0,c.homedir)(),".sf","runtime.pid");const d=(0,a.join)((0,c.homedir)(),".sf","runtime.log");const u=3e4;const p=3e5;const h=new Set;function registerRuntime(e){const t=e.command("runtime").description("Execution runtime daemon");t.command("start").option("--daemon","Run as background process").description("Start the execution runtime").action((async e=>{if(!(0,o.isKalshiConfigured)()){console.error(`\n ${i.c.red}Error:${i.c.reset} Kalshi credentials not configured.`);console.error(` Run: sf setup --enable-trading\n`);process.exit(1)}if((0,r.existsSync)(l)){const e=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(e),0);console.error(`\n ${i.c.yellow}Warning:${i.c.reset} Runtime already running (PID ${e}).`);console.error(` Stop it first: sf runtime stop\n`);process.exit(1)}catch{(0,r.unlinkSync)(l)}}if(e.daemon){console.error(`\n ${i.c.dim}Daemon mode not yet implemented. Run in foreground for now.${i.c.reset}\n`);process.exit(1)}await startRuntime()}));t.command("stop").description("Stop the runtime daemon").action((async()=>{if(!(0,r.existsSync)(l)){console.log(`\n ${i.c.dim}No runtime running.${i.c.reset}\n`);return}const e=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(e),"SIGTERM");(0,r.unlinkSync)(l);console.log(`\n ${i.c.green}OK${i.c.reset} Runtime stopped (PID ${e}).\n`)}catch{(0,r.unlinkSync)(l);console.log(`\n ${i.c.dim}Runtime was not running (stale PID file removed).${i.c.reset}\n`)}}));t.command("status").option("--json","JSON output").description("Show runtime status and active intents").action((async e=>{try{let t=false;let n="";if((0,r.existsSync)(l)){n=(0,r.readFileSync)(l,"utf-8").trim();try{process.kill(parseInt(n),0);t=true}catch{t=false}}const o=new s.SFClient;const{intents:a}=await o.listIntents({active:true});if(e.json){console.log(JSON.stringify({running:t,pid:t?n:null,intents:a},null,2));return}console.log();console.log(` ${i.c.bold}Runtime${i.c.reset} ${t?`${i.c.green}RUNNING${i.c.reset} (PID ${n})`:`${i.c.dim}STOPPED${i.c.reset}`}`);console.log();if(!a||a.length===0){console.log(` ${i.c.dim}No active intents.${i.c.reset}`);console.log(` Create one: sf intent buy TICKER QTY --price CENTS`);console.log();return}const c={};for(const e of a){c[e.status]=(c[e.status]||0)+1}const d=Object.entries(c).map((([e,t])=>`${t} ${e}`)).join(", ");console.log(` Active intents: ${d}`);console.log();for(const e of a){const t=e.action.toUpperCase();const n=e.direction.toUpperCase();const s=e.maxPrice?`@ ≤${e.maxPrice}c`:"@ market";const o=e.targetQuantity>0?` (${Math.round(e.filledQuantity/e.targetQuantity*100)}%)`:"";console.log(` [${e.status}] ${t} ${e.marketId} ${n} ${e.targetQuantity}${s} filled ${e.filledQuantity}/${e.targetQuantity}${o}`);if(e.triggerType!=="immediate"){const t=e.triggerType==="price_below"?`price ≤ ${e.triggerPrice}c`:e.triggerType==="price_above"?`price ≥ ${e.triggerPrice}c`:e.triggerType;console.log(` trigger: ${t}`)}}console.log();if(!t){console.log(` ${i.c.dim}Start runtime to execute: sf runtime start${i.c.reset}`);console.log()}}catch(e){console.error(`${i.c.red}Error:${i.c.reset} ${e.message}`);process.exit(1)}}))}async function startRuntime(){const e=(0,a.join)((0,c.homedir)(),".sf");if(!(0,r.existsSync)(e))(0,r.mkdirSync)(e,{recursive:true});(0,r.writeFileSync)(l,process.pid.toString());console.log();console.log(` ${i.c.bold}SimpleFunctions Runtime${i.c.reset}`);console.log(` ${i.c.dim}PID ${process.pid} · polling every ${u/1e3}s · Ctrl+C to stop${i.c.reset}`);console.log();const t=new s.SFClient;let n=0;let o=0;const shutdown=()=>{console.log(`\n ${i.c.dim}Runtime stopping...${i.c.reset}`);try{(0,r.unlinkSync)(l)}catch{}process.exit(0)};process.on("SIGINT",shutdown);process.on("SIGTERM",shutdown);while(true){o++;const e=Date.now();try{const{intents:e}=await t.listIntents({active:true});if(!e||e.length===0){if(o%10===1){log("No active intents. Waiting...")}await sleep(u);continue}for(const n of e){await processIntent(t,n)}}catch(e){log(`Error in cycle: ${e.message}`)}await sleep(u)}}async function processIntent(e,t){if(t.activateAt&&new Date(t.activateAt)>new Date)return;if(new Date(t.expireAt)<new Date){log(`Intent ${t.id.slice(0,8)} expired`);try{await e.cancelIntentAPI(t.id)}catch{}return}if(t.status==="pending"){log(`Arming intent ${t.id.slice(0,8)}: ${t.action.toUpperCase()} ${t.marketId} ${t.direction.toUpperCase()} x${t.targetQuantity}`)}if(t.status==="pending"||t.status==="armed"){const n=await evaluateTrigger(t);if(!n)return;log(`TRIGGERED: ${t.id.slice(0,8)} ${t.marketId} (${t.triggerType})`);if(t.autoExecute){await executeIntent(e,t)}else{log(` Awaiting confirmation. Use: sf intent status ${t.id.slice(0,8)}`)}}if(t.status==="triggered"&&t.autoExecute){await executeIntent(e,t)}}async function evaluateTrigger(e){switch(e.triggerType){case"immediate":return true;case"price_below":{if(!e.triggerPrice)return false;const t=await(0,o.getMarketPrice)(e.marketId);if(t===null)return false;return t<=e.triggerPrice}case"price_above":{if(!e.triggerPrice)return false;const t=await(0,o.getMarketPrice)(e.marketId);if(t===null)return false;return t>=e.triggerPrice}case"time":{if(!e.triggerAt)return false;return new Date>=new Date(e.triggerAt)}default:return false}}async function executeIntent(e,t){if(h.has(t.id)){return}if(t.venue!=="kalshi"){log(` Skipping ${t.id.slice(0,8)}: ${t.venue} execution not yet supported`);return}const n=t.targetQuantity-t.filledQuantity;if(n<=0){h.add(t.id);return}h.add(t.id);log(` Executing: ${t.action.toUpperCase()} ${t.marketId} ${t.direction.toUpperCase()} x${n}${t.maxPrice?` @ ≤${t.maxPrice}c`:""}`);try{const s=await(0,o.createOrder)({ticker:t.marketId,side:t.direction,action:t.action,type:t.maxPrice?"limit":"market",count:n,...t.maxPrice?{yes_price:t.maxPrice}:{}});const l=s.order||s;const d=l.fill_count||l.fill_count_fp||n;const u=l.yes_price||l.no_price||t.maxPrice||0;log(` ${i.c.green}FILLED${i.c.reset}: ${d} contracts, order ${l.order_id||"OK"}`);try{const e=JSON.stringify({ts:(new Date).toISOString(),intentId:t.id,action:t.action,ticker:t.marketId,side:t.direction,quantity:d,price:t.maxPrice,orderId:l.order_id,source:t.source})+"\n";(0,r.appendFileSync)((0,a.join)((0,c.homedir)(),".sf","trade-journal.jsonl"),e)}catch{}try{await e.request("PATCH",`/api/intents/${t.id}`,{fill:{orderId:l.order_id||null,fillQuantity:d,fillPrice:u,fillCostCents:Math.round(u*d),venueResponse:{order_id:l.order_id,status:l.status}}});log(` ${i.c.dim}Fill recorded to API${i.c.reset}`)}catch(e){log(` ${i.c.yellow}Warning:${i.c.reset} Failed to record fill to API: ${e.message}. Intent may re-execute on restart.`)}}catch(e){h.delete(t.id);const n=e.message||String(e);if(n.includes("403")){log(` ${i.c.red}FAILED${i.c.reset}: 403 Forbidden — Kalshi key lacks write permission`);h.add(t.id)}else{log(` ${i.c.red}FAILED${i.c.reset}: ${n}`)}}}function log(e){const t=(new Date).toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"});console.log(` ${i.c.dim}${t}${i.c.reset} ${e}`)}function sleep(e){return new Promise((t=>setTimeout(t,e)))}},46183:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.scanCommand=scanCommand;const s=n(19218);const o=n(34331);const i=n(99236);const r=n(35178);const a=process.env.SF_API_URL||"https://simplefunctions.dev";async function scanCommand(e,t){if(t.market){await showMarket(t.market.toUpperCase(),t.json);return}if(t.series){await showSeries(t.series.toUpperCase(),t.json);return}await keywordScan(e,t.json,t.venue||"all",t.share)}async function showMarket(e,t){console.log(`${i.c.dim}Fetching market ${e}...${i.c.reset}`);const n=await(0,s.kalshiFetchMarket)(e);if(t){console.log(JSON.stringify(n,null,2));return}(0,i.header)(`${n.title||n.ticker}`);if(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}`);if(n.rules_primary){console.log(`\nRules: ${n.rules_primary.slice(0,300)}`)}}async function showSeries(e,t){console.log(`${i.c.dim}Fetching events for series ${e}...${i.c.reset}`);let n=await(0,s.kalshiFetchEvents)(e);if(n.length===0){const n=await(0,s.kalshiFetchMarketsBySeries)(e);if(t){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(`${i.c.dim}No open markets found for series ${e}.${i.c.reset}`);return}(0,i.header)(`${e} — ${n.length} markets`);printMarketsTable(n);return}if(t){console.log(JSON.stringify(n,null,2));return}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}`);const t=e.markets&&e.markets.length>0?e.markets:await(0,s.kalshiFetchMarketsByEvent)(e.event_ticker);printMarketsTable(t)}}async function keywordScan(e,t,n="all",s){const c=n==="kalshi"?Promise.resolve([]):(0,o.polymarketSearch)(e,10).catch((()=>[]));if(n!=="polymarket"){console.log(`${i.c.dim}Scanning Kalshi for: "${e}"...${i.c.reset}`)}if(n!=="kalshi"){console.log(`${i.c.dim}Scanning Polymarket for: "${e}"...${i.c.reset}`)}const l=[];if(n!=="polymarket"){try{const t=`${a}/api/public/scan?q=${encodeURIComponent(e)}&limit=30`;const n=await fetch(t);if(!n.ok)throw new Error(`Proxy ${n.status}`);const s=await n.json();const o=s.matchedSeries||[];const 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;const 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);const s=n[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:s,lastPrice:t.lastTradePrice||s,volume24h:t.volume24hr||0,liquidity:t.liquidityNum||0})}}for(const e of l){if(!e.venue)e.venue="kalshi"}const p=[...l,...u];p.sort(((e,t)=>t.liquidity-e.liquidity));if(s){await(0,r.shareOutput)("scan",e,p);return}if(t){console.log(JSON.stringify(p,null,2));return}(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=e.venue==="polymarket"?"POLY ":"KLSH ";const n=e.venue==="polymarket"?i.c.blue+t+i.c.reset:i.c.cyan+t+i.c.reset;const s=e.venue==="polymarket"?(e.ticker||"").slice(0,28):(e.ticker||"").slice(0,28);console.log(n+(0,i.pad)(s,30)+(0,i.rpad)(`${Math.round(e.yesAsk*100)}¢`,6)+(0,i.rpad)(`${Math.round(e.lastPrice*100)}¢`,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("");if(!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("")}}function printMarketsTable(e){if(e.length===0){console.log(` ${i.c.dim}(no markets)${i.c.reset}`);return}e.sort(((e,t)=>{const n=parseFloat(e.yes_ask_dollars||e.last_price_dollars||"0");const s=parseFloat(t.yes_ask_dollars||t.last_price_dollars||"0");return s-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("")}},58211:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.scheduleCommand=scheduleCommand;const s=n(99236);const o="https://api.elections.kalshi.com/trade-api/v2";async function scheduleCommand(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"}});if(e.ok)i=await e.json()}catch{}if(e.json){console.log(JSON.stringify({status:n,schedule:i},null,2));return}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}`);if(n.trading_active!==undefined){console.log(` Trading Active: ${n.trading_active?"yes":"no"}`)}if(i?.schedule){console.log(` Schedule: ${JSON.stringify(i.schedule).slice(0,100)}`)}console.log()}},96616:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.settlementsCommand=settlementsCommand;const s=n(96139);const o=n(19218);const i=n(99236);async function settlementsCommand(e){const t=[];let n="";do{const e=await(0,s.getSettlements)({limit:200,cursor:n||undefined});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);const s=await n.getContext(e.thesis);const i=new Set((s.edges||[]).map((e=>e.marketId)));r=t.filter((e=>i.has(e.ticker)))}if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(`${i.c.dim}No settlements found.${i.c.reset}`);return}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");const n=parseFloat(e.yes_total_cost||e.yes_total_cost_dollars||"0")+parseFloat(e.no_total_cost||e.no_total_cost_dollars||"0");const 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}`;const 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)`)}},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:true});t.setupCommand=setupCommand;const o=s(n(23785));const i=n(35317);const r=n(11627);const a=n(19218);const c=n(96139);const l=n(83969);const green=e=>`[32m${e}[39m`;const red=e=>`[31m${e}[39m`;const dim=e=>`[2m${e}[22m`;const bold=e=>`[1m${e}[22m`;const cyan=e=>`[36m${e}[39m`;function ok(e){console.log(` ${green("✓")} ${e}`)}function fail(e){console.log(` ${red("✗")} ${e}`)}function info(e){console.log(` ${e}`)}function blank(){console.log()}function prompt(e){const t=o.default.createInterface({input:process.stdin,output:process.stdout,terminal:true});return new Promise((n=>{t.question(e,(e=>{t.close();n(e.trim())}))}))}function promptYN(e,t=true){return prompt(e).then((e=>{if(!e)return t;return e.toLowerCase().startsWith("y")}))}function openBrowser(e){const t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,i.exec)(`${t} ${e}`)}function mask(e){if(!e||e.length<=12)return e;return e.slice(0,8)+"..."+e.slice(-4)}async function validateSFKey(e,t){try{const n=await fetch(`${t}/api/thesis`,{headers:{Authorization:`Bearer ${e}`}});if(n.ok)return{valid:true,msg:`API key valid — connected to ${t.replace("https://","")}`};if(n.status===401)return{valid:false,msg:"Invalid key, please try again"};return{valid:false,msg:`Server returned ${n.status}`}}catch(e){return{valid:false,msg:`Connection failed: ${e.message}`}}}async function validateOpenRouterKey(e){try{const t=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${e}`}});if(t.ok)return{valid:true,msg:"OpenRouter connected — available model: claude-sonnet-4.6"};return{valid:false,msg:`OpenRouter returned ${t.status}`}}catch(e){return{valid:false,msg:`Connection failed: ${e.message}`}}}async function validateKalshi(){try{const e=await(0,c.getPositions)();if(e===null)return{valid:false,msg:"Kalshi authentication failed",posCount:0};return{valid:true,msg:`Kalshi authenticated — found ${e.length} position(s)`,posCount:e.length}}catch(e){return{valid:false,msg:`Kalshi connection failed: ${e.message}`,posCount:0}}}async function validateTavily(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})});if(t.ok)return{valid:true,msg:"Tavily connected"};return{valid:false,msg:`Tavily returned ${t.status}`}}catch(e){return{valid:false,msg:`Connection failed: ${e.message}`}}}async function setupCommand(e){if(e.check){return showCheck()}if(e.reset){(0,r.resetConfig)();ok("Config reset");blank();info("Run sf setup to reconfigure");blank();return}if(e.key){const t=process.env.SF_API_URL||"https://simplefunctions.dev";const n=await validateSFKey(e.key,t);if(!n.valid){fail(n.msg);process.exit(1)}const s=(0,r.loadFileConfig)();(0,r.saveConfig)({...s,apiKey:e.key,apiUrl:t});ok(n.msg);ok(`Saved to ${(0,r.getConfigPath)()}`);return}if(e.kalshi){const e=(0,r.loadFileConfig)();blank();console.log(` ${bold("Reconfigure Kalshi Credentials")}`);blank();info("Go to https://kalshi.com/account/api-keys to generate a new API key.");info("If you need trading, make sure to enable read+write permissions.");blank();await promptForKalshi(e);(0,r.saveConfig)(e);if(e.kalshiKeyId){process.env.KALSHI_API_KEY_ID=e.kalshiKeyId;process.env.KALSHI_PRIVATE_KEY_PATH=e.kalshiPrivateKeyPath}blank();return}if(e.polymarket){const e=(0,r.loadFileConfig)();blank();console.log(` ${bold("Reconfigure Polymarket Credentials")}`);blank();await promptForPolymarket(e);(0,r.saveConfig)(e);blank();return}if(e.enableTrading){const e=(0,r.loadFileConfig)();(0,r.saveConfig)({...e,tradingEnabled:true});ok("Trading enabled. sf buy / sf sell / sf cancel now available.");blank();return}if(e.disableTrading){const e=(0,r.loadFileConfig)();(0,r.saveConfig)({...e,tradingEnabled:false});ok("Trading disabled.");blank();return}return runWizard()}async function showCheck(){const e=(0,r.loadConfig)();blank();console.log(` ${bold("SimpleFunctions Config Status")}`);console.log(` ${dim("─".repeat(35))}`);blank();if(e.apiKey){ok(`SF_API_KEY ${dim(mask(e.apiKey))}`)}else{fail("SF_API_KEY not configured (required)")}if(e.openrouterKey){ok(`OPENROUTER ${dim(mask(e.openrouterKey))} (direct)`)}else if(e.apiKey){ok(`OPENROUTER ${dim("proxied via SimpleFunctions")}`)}else{fail(`OPENROUTER not configured (run sf login or set key)`)}if(e.kalshiKeyId&&e.kalshiPrivateKeyPath){ok(`KALSHI ${dim(mask(e.kalshiKeyId))}`)}else{info(`${dim("○")} KALSHI ${dim("skipped")}`)}if(e.polymarketWalletAddress){ok(`POLYMARKET ${dim(mask(e.polymarketWalletAddress))}`)}else{info(`${dim("○")} POLYMARKET ${dim("skipped")}`)}if(e.tavilyKey){ok(`TAVILY ${dim(mask(e.tavilyKey))} (direct)`)}else if(e.apiKey){ok(`TAVILY ${dim("proxied via SimpleFunctions")}`)}else{info(`${dim("○")} TAVILY ${dim("skipped")}`)}if(e.tradingEnabled){ok("TRADING enabled")}else{info(`${dim("○")} TRADING ${dim("disabled — sf setup --enable-trading")}`)}blank();console.log(` ${dim("Config file: "+(0,r.getConfigPath)())}`);blank()}async function runWizard(){blank();console.log(` ${bold("SimpleFunctions Setup")}`);console.log(` ${dim("─".repeat(25))}`);blank();const e=(0,r.loadFileConfig)();const t=e.apiUrl||"https://simplefunctions.dev";console.log(` ${bold("Step 1: API Key")}`);blank();const n=process.env.SF_API_KEY||e.apiKey;if(n){const s=await validateSFKey(n,t);if(s.valid){ok(`Detected SF_API_KEY — ${dim(mask(n))}`);info(dim("Skipping."));e.apiKey=n;blank()}else{fail(`Existing key invalid: ${s.msg}`);e.apiKey=await promptForSFKey(t)}}else{e.apiKey=await promptForSFKey(t)}e.apiUrl=t;(0,r.saveConfig)(e);process.env.SF_API_KEY=e.apiKey;console.log(` ${bold("Step 2: AI Model (for sf agent)")}`);blank();const s=process.env.OPENROUTER_API_KEY||e.openrouterKey;if(s){const t=await validateOpenRouterKey(s);if(t.valid){ok(`Detected OPENROUTER_API_KEY — ${dim(mask(s))}`);info(dim("Skipping."));e.openrouterKey=s;blank()}else{fail(`Existing key invalid: ${t.msg}`);e.openrouterKey=await promptForOpenRouterKey()}}else{e.openrouterKey=await promptForOpenRouterKey()}(0,r.saveConfig)(e);if(e.openrouterKey)process.env.OPENROUTER_API_KEY=e.openrouterKey;console.log(` ${bold("Step 3: Kalshi Exchange (optional)")}`);blank();const o=process.env.KALSHI_API_KEY_ID||e.kalshiKeyId;const 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 validateKalshi();if(t.valid){ok(`Detected Kalshi — ${dim(mask(o))} (${t.posCount} position(s))`);info(dim("Skipping."));e.kalshiKeyId=o;e.kalshiPrivateKeyPath=i;blank()}else{fail(`Existing credentials invalid: ${t.msg}`);await promptForKalshi(e)}}else{await promptForKalshi(e)}(0,r.saveConfig)(e);console.log(` ${bold("Step 4: Polymarket (optional)")}`);blank();const a=process.env.POLYMARKET_WALLET_ADDRESS||e.polymarketWalletAddress;if(a){ok(`Detected wallet — ${dim(mask(a))}`);info(dim("Skipping."));e.polymarketWalletAddress=a;blank()}else{await promptForPolymarket(e)}(0,r.saveConfig)(e);if(e.polymarketWalletAddress)process.env.POLYMARKET_WALLET_ADDRESS=e.polymarketWalletAddress;console.log(` ${bold("Step 5: News Search (optional)")}`);blank();const c=process.env.TAVILY_API_KEY||e.tavilyKey;if(c){const t=await validateTavily(c);if(t.valid){ok(`Detected TAVILY_API_KEY — ${dim(mask(c))}`);info(dim("Skipping."));e.tavilyKey=c;blank()}else{fail(`Existing key invalid: ${t.msg}`);e.tavilyKey=await promptForTavily()}}else{e.tavilyKey=await promptForTavily()}(0,r.saveConfig)(e);if(e.tavilyKey)process.env.TAVILY_API_KEY=e.tavilyKey;if(e.kalshiKeyId){console.log(` ${bold("Step 6: Trading (optional)")}`);blank();info("Warning: enabling this unlocks sf buy / sf sell / sf cancel.");info("Your Kalshi API key must have read+write permissions.");blank();const t=await promptYN(" Enable trading? (y/N) ",false);e.tradingEnabled=t;if(t){ok("Trading enabled")}else{info(dim("Skipped. You can enable later with sf setup --enable-trading."))}blank();(0,r.saveConfig)(e)}console.log(` ${dim("─".repeat(25))}`);info(`Config saved to ${dim((0,r.getConfigPath)())}`);blank();if(e.apiKey)ok("SF_API_KEY configured");else fail("SF_API_KEY not configured");if(e.openrouterKey)ok("OPENROUTER_KEY configured");else fail("OPENROUTER_KEY skipped");if(e.kalshiKeyId)ok("KALSHI configured");else info(`${dim("○")} KALSHI skipped`);if(e.tavilyKey)ok("TAVILY configured");else info(`${dim("○")} TAVILY skipped`);blank();if(e.apiKey){await handleThesisStep(e)}}async function promptForSFKey(e){info(`Don't have a key? Sign up at ${cyan("https://simplefunctions.dev/dashboard")}.`);info("Press Enter to open browser, or paste your key:");blank();while(true){const t=await prompt(" > ");if(!t){openBrowser("https://simplefunctions.dev/dashboard");info(dim("Browser opened. Paste your key here once you have it:"));continue}info(dim("Validating..."));const n=await validateSFKey(t,e);if(n.valid){ok(n.msg);blank();return t}else{fail(n.msg)}}}async function promptForOpenRouterKey(){info(`Requires an OpenRouter API key. Get one at ${cyan("https://openrouter.ai/settings/keys")}.`);info("Press Enter to skip (agent unavailable), or paste key:");blank();const e=await prompt(" > ");if(!e){info(dim("Skipped."));blank();return undefined}info(dim("Validating..."));const t=await validateOpenRouterKey(e);if(t.valid){ok(t.msg)}else{fail(t.msg);info(dim("Saved. You can re-run sf setup later to fix this."))}blank();return e}async function promptForKalshi(e){info(`Connect Kalshi to view your positions and P&L.`);info(`Requires an API Key ID and private key file.`);info(`Get them at ${cyan("https://kalshi.com/account/api-keys")}.`);info("Press Enter to skip, or paste Key ID:");blank();const t=await prompt(" > ");if(!t){info(dim("Skipped."));blank();return}info("Private key file path (default ~/.kalshi/private.pem):");const n=await prompt(" > ");const s=n||"~/.kalshi/private.pem";e.kalshiKeyId=t;e.kalshiPrivateKeyPath=s;process.env.KALSHI_API_KEY_ID=t;process.env.KALSHI_PRIVATE_KEY_PATH=s;info(dim("Validating..."));const o=await validateKalshi();if(o.valid){ok(o.msg)}else{fail(o.msg);info(dim("Saved. You can re-run sf setup later to fix this."))}blank()}async function promptForTavily(){info(`Tavily API powers the agent's web_search tool.`);info(`Get a free key at ${cyan("https://tavily.com")}.`);info("Press Enter to skip:");blank();const e=await prompt(" > ");if(!e){info(dim("Skipped."));blank();return undefined}info(dim("Validating..."));const t=await validateTavily(e);if(t.valid){ok(t.msg)}else{fail(t.msg);info(dim("Saved. You can re-run sf setup later to fix this."))}blank();return e}async function promptForPolymarket(e){info("Connect Polymarket to view positions and scan orderbooks.");info("Your Polygon wallet address is needed (starts with 0x...).");info(`Find it at ${cyan("https://polymarket.com")} → Settings → Profile.`);info("Press Enter to skip:");blank();const t=await prompt(" Wallet address > ");if(!t){info(dim("Skipped."));blank();return}if(!t.startsWith("0x")||t.length<40){fail("Invalid wallet address (must start with 0x and be 42 characters)");info(dim("Saved anyway. You can fix it later with sf setup."))}else{ok(`Wallet: ${mask(t)}`)}e.polymarketWalletAddress=t;info(dim("Private key (for future trading) — press Enter to skip:"));const n=await prompt(" Key path > ");if(n){e.polymarketPrivateKeyPath=n;ok(`Private key path: ${dim(n)}`)}blank()}async function handleThesisStep(e){try{const t=new a.SFClient(e.apiKey,e.apiUrl);const n=await t.listTheses();const s=n.theses||[];const o=s.filter((e=>e.status==="active"));if(o.length>0){console.log(` ${bold("Step 7: Theses")}`);blank();ok(`Found ${o.length} active thesis(es):`);for(const e of o.slice(0,5)){const t=typeof e.confidence==="number"?Math.round(e.confidence*100):0;const n=(e.rawThesis||e.thesis||e.title||"").slice(0,60);info(` ${dim(e.id.slice(0,8))} — ${n} — ${t}%`)}info(dim("Skipping creation."));blank();if(e.openrouterKey){console.log(` ${dim("─".repeat(25))}`);console.log(` ${bold("All set!")}`);blank();info(` ${cyan("sf agent")} Chat with your thesis`);info(` ${cyan("sf context <id>")} View thesis snapshot`);info(` ${cyan("sf positions")} View positions`);info(` ${cyan("sf setup --check")} Check config`);blank();const t=await promptYN(` Launch agent now? (Y/n) `);if(t){blank();info("Launching...");blank();await(0,l.agentCommand)(o[0].id,{model:e.model})}}else{blank();console.log(` ${bold("All set!")}`);blank();info(` ${cyan("sf list")} List all theses`);info(` ${cyan("sf context <id>")} View thesis snapshot`);info(` ${cyan("sf positions")} View positions`);info(` ${cyan("sf setup --check")} Check config`);blank()}return}console.log(` ${bold("Step 7: Create Your First Thesis")}`);blank();info("A thesis is your core market conviction. The system builds a causal model");info("from it, then continuously scans prediction markets for mispriced contracts.");blank();info("Examples:");info(` ${dim('"The Fed won\'t cut rates in 2026 — inflation stays elevated due to oil prices"')}`);info(` ${dim('"AI-driven layoffs cause consumer spending to contract, S&P drops 20% by year-end"')}`);info(` ${dim('"Trump can\'t exit the Iran conflict — oil stays above $100 for six months"')}`);blank();const i=await prompt(" Enter your thesis (press Enter to skip, use sf create later):\n > ");if(!i){blank();info(dim('Skipped. Use sf create "your thesis" to create one later.'));blank();showFinalHints(e);return}blank();info("Building causal model... (~30s)");blank();try{const n=await t.createThesis(i,true);if(n.id){const t=n.causalTree?.nodes?.length||0;const s=n.edgeAnalysis?.edges?.length||0;const o=n.edgeAnalysis?.totalMarketsAnalyzed||0;const i=Math.round((parseFloat(n.confidence)||.5)*100);ok(`Causal tree: ${t} node(s)`);ok(`Scanned ${o} markets, found ${s} contract(s) with edge`);ok(`Confidence: ${i}%`);ok(`Thesis ID: ${n.id.slice(0,8)}`);blank();if(e.openrouterKey){console.log(` ${dim("─".repeat(25))}`);console.log(` ${bold("All set!")}`);blank();const t=await promptYN(` Launch agent now? (Y/n) `);if(t){blank();info("Launching...");blank();await(0,l.agentCommand)(n.id,{model:e.model})}else{blank();showFinalHints(e)}}else{showFinalHints(e)}}else{fail(`Creation failed: ${n.error||"unknown error"}`);info(dim('You can retry later with sf create "your thesis"'));blank();showFinalHints(e)}}catch(t){fail(`Creation failed: ${t.message}`);info(dim('You can retry later with sf create "your thesis"'));blank();showFinalHints(e)}}catch{blank();showFinalHints(e)}}function showFinalHints(e){console.log(` ${dim("─".repeat(25))}`);console.log(` ${bold("All set!")}`);blank();info(` ${cyan("sf agent")} Chat with your thesis`);info(` ${cyan("sf list")} List all theses`);info(` ${cyan("sf context <id>")} View thesis snapshot`);info(` ${cyan("sf positions")} View positions`);info(` ${cyan("sf setup --check")} Check config`);blank()}},67378:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.signalCommand=signalCommand;const s=n(19218);const o=n(99236);async function signalCommand(e,t,n){const i=new s.SFClient(n.apiKey,n.apiUrl);const r=n.type||"user_note";const a=await i.injectSignal(e,r,t,"cli");if(n.json){console.log(JSON.stringify({signalId:a.signalId||null,type:r,source:"cli",content:t},null,2));return}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}`);if(a.signalId){console.log(` ${o.c.bold}ID:${o.c.reset} ${a.signalId}`)}const c=new Date;const l=c.getMinutes();const d=Math.ceil((l+1)/15)*15;const u=d-l;const p=new Date(c);p.setMinutes(d%60,0,0);if(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}`)}},72124:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.statusCommand=statusCommand;const s=n(99236);const o=n(96139);const i=n(11627);const r=process.env.SF_API_URL||"https://simplefunctions.dev";async function statusCommand(e){const t=[];const n=Date.now();try{const e=await fetch(`${r}/api`,{signal:AbortSignal.timeout(5e3)});t.push({name:"API",status:e.ok?"ok":"fail",detail:e.ok?r.replace("https://",""):`HTTP ${e.status}`,ms:Date.now()-n})}catch(e){t.push({name:"API",status:"fail",detail:e.message?.slice(0,40)||"unreachable",ms:Date.now()-n})}const a=(0,i.loadConfig)();if((0,i.isConfigured)()){const e=Date.now();try{const n=await fetch(`${r}/api/thesis`,{headers:{Authorization:`Bearer ${a.apiKey}`},signal:AbortSignal.timeout(5e3)});const s=(a.apiKey||"").slice(0,12)+"...";t.push({name:"Auth",status:n.ok?"ok":"fail",detail:n.ok?s:`HTTP ${n.status}`,ms:Date.now()-e})}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 e=Date.now();try{const n=await(0,o.getBalance)();t.push({name:"Kalshi",status:n?"ok":"fail",detail:n?`$${n.balance.toFixed(2)} balance`:"auth failed",ms:Date.now()-e})}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)"})}if(a.polymarketWalletAddress){t.push({name:"Polymarket",status:"ok",detail:a.polymarketWalletAddress.slice(0,10)+"..."})}else{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();const s=n.theses||[];const o=s.filter((e=>e.status==="active")).length;const i=s.length;t.push({name:"Theses",status:"ok",detail:`${o} active, ${i} total`})}}catch{}}const c=a.tradingEnabled;t.push({name:"Trading",status:c?"ok":"skip",detail:c?"enabled":"disabled (sf setup --enable-trading)"});if(e?.json){console.log(JSON.stringify({checks:t,timestamp:(new Date).toISOString()},null,2));return}console.log();for(const e of t){const t=e.status==="ok"?`${s.c.green}ok${s.c.reset}`:e.status==="fail"?`${s.c.red}!!${s.c.reset}`:`${s.c.dim}--${s.c.reset}`;const n=e.ms?` ${s.c.dim}${e.ms}ms${s.c.reset}`:"";console.log(` ${e.name.padEnd(14)} ${t} ${e.detail}${n}`)}console.log()}},40239:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.registerStrategies=registerStrategies;const s=n(19218);const o={active:"[32m",watching:"[33m",executed:"[36m",cancelled:"[90m",review:"[31m"};const i="[0m";const r="[2m";const a="[1m";function formatStrategy(e,t=false){const n=o[e.status]||"";const s=[];const 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=[];if(e.entryBelow!=null)l.push(`ask ≤ ${e.entryBelow}¢`);if(e.entryAbove!=null)l.push(`ask ≥ ${e.entryAbove}¢`);const d=e.stopLoss!=null?`Stop: ${e.stopLoss}¢`:"";const u=e.takeProfit!=null?`TP: ${e.takeProfit}¢`:"";const p=`Max: ${e.maxQuantity||500}`;const h=`Filled: ${e.executedQuantity||0}/${e.maxQuantity||500}`;const m=[l.length>0?`Entry: ${l.join(", ")}`:null,d||null,u||null,p,h].filter(Boolean).join(" | ");s.push(` ${m}`);if(e.softConditions){s.push(` ${r}Soft: ${e.softConditions}${i}`)}if(e.status==="review"){s.push(` [31m⚠️ Needs review${i}`)}if(e.rationale){const t=e.rationale.length>120?e.rationale.slice(0,117)+"...":e.rationale;s.push(` ${r}${t}${i}`)}const f=e.createdBy||"user";const g=e.createdAt?new Date(e.createdAt).toLocaleDateString("en-US",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}):"";s.push(` ${r}created by ${f} · ${g}${i}`);return s.join("\n")}function registerStrategies(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=t?.all?"":t?.status||"active";const o=s?`/api/thesis/${e}/strategies?status=${s}`:`/api/thesis/${e}/strategies`;const a=await n.getStrategies(e,t?.all?undefined:t?.status||"active");const c=a.strategies||[];if(c.length===0){console.log(`\n No strategies found for thesis ${e}`);if(!t?.all&&!t?.status){console.log(` ${r}Try --all to see all statuses${i}`)}console.log();return}console.log(`\n Strategies for ${e}\n`);for(const e of c){console.log(formatStrategy(e));console.log()}}else{const{theses:e}=await n.listTheses();let s=0;for(const o of e){const e=t?.all?undefined:t?.status||"active";const c=await n.getStrategies(o.id,e);const l=c.strategies||[];if(l.length===0)continue;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(formatStrategy(e));console.log()}}if(s===0){console.log(`\n No strategies found`);if(!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)}}))}},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:true});t.telegramCommand=telegramCommand;const o=n(35317);const i=s(n(79896));const r=s(n(16928));const a=s(n(70857));const c=n(11627);const l=r.default.join(a.default.homedir(),".sf","telegram.pid");const d=r.default.join(a.default.homedir(),".sf","telegram.log");function readPid(){try{const e=parseInt(i.default.readFileSync(l,"utf-8").trim());if(isNaN(e))return null;try{process.kill(e,0);return e}catch{return null}}catch{return null}}function resolveToken(e){const t=(0,c.loadConfig)();if(e){const t=(0,c.loadFileConfig)();if(t.telegramBotToken!==e){(0,c.saveConfig)({...t,telegramBotToken:e})}return e}return t.telegramBotToken||null}async function telegramCommand(e){if(e.stop){const e=readPid();if(e){process.kill(e,"SIGTERM");try{i.default.unlinkSync(l)}catch{}console.log(` Telegram bot stopped (PID ${e})`)}else{console.log(" No running Telegram bot found.")}return}if(e.status){const e=readPid();if(e){console.log(` Telegram bot running (PID ${e})`);console.log(` Log: ${d}`)}else{console.log(" Telegram bot not running.")}return}const t=resolveToken(e.token);if(!t){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");console.log(" The token will be saved to ~/.sf/config.json for future use.");return}if(e.daemon){const t=readPid();if(t){console.log(` Bot already running (PID ${t}). Use --stop first.`);return}const n=["telegram"];if(e.chatId)n.push("--chat-id",e.chatId);const s=process.argv[1];i.default.mkdirSync(r.default.dirname(l),{recursive:true});const a=i.default.openSync(d,"a");const c=(0,o.spawn)(process.execPath,[s,...n],{detached:true,stdio:["ignore",a,a],env:{...process.env}});c.unref();i.default.writeFileSync(l,String(c.pid));console.log(` Telegram bot started in background (PID ${c.pid})`);console.log(` Log: ${d}`);console.log(` Stop: sf telegram --stop`);return}const{startBot:s}=await Promise.all([n.e(830),n.e(278),n.e(12)]).then(n.bind(n,6012));await s({token:t,chatId:e.chatId?parseInt(e.chatId):undefined})}},34362:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.buyCommand=buyCommand;t.sellCommand=sellCommand;const s=n(96139);const o=n(11627);const i=n(99236);const r=n(79896);const a=n(16928);const c=n(70857);async function buyCommand(e,t,n){(0,o.requireTrading)();await executeOrder(e,t,"buy",n)}async function sellCommand(e,t,n){(0,o.requireTrading)();await executeOrder(e,t,"sell",n)}async function executeOrder(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):undefined;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(p!==undefined&&(p<1||p>99)){throw new Error("Price must be 1-99 cents.")}const h=((p||99)*l/100).toFixed(2);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: ${d==="yes"?i.c.green+"YES"+i.c.reset:i.c.red+"NO"+i.c.reset}`);console.log(` Quantity: ${l}`);console.log(` Type: ${u}`);if(p)console.log(` Price: ${p}¢`);console.log(` Max cost: $${h}`);console.log();if(!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}:{}});const o=t.order||t;console.log();console.log(` ${i.c.green}✓${i.c.reset} Order placed: ${o.order_id||"OK"}`);if(o.status)console.log(` Status: ${o.status}`);if(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");if(!(0,r.existsSync)(t))(0,r.mkdirSync)(t,{recursive:true});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);if(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`)}else{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:true});t.updateCommand=updateCommand;const s=n(35317);const o="@spfunctions/cli";function detectPackageManager(){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{const e=(0,s.execSync)("pnpm list -g --depth=0 2>/dev/null",{encoding:"utf-8"});if(e.includes(o))return"pnpm"}catch{}try{const e=(0,s.execSync)("yarn global list --depth=0 2>/dev/null",{encoding:"utf-8"});if(e.includes(o))return"yarn"}catch{}return"npm"}async function updateCommand(){console.log(" Checking for updates...");try{const e=await fetch(`https://registry.npmjs.org/${o}/latest`);if(!e.ok){console.error(" Failed to check npm registry.");return}const t=await e.json();const i=t.version;const{join:r}=await Promise.resolve().then(n.t.bind(n,16928,23));const{readFileSync:a,existsSync:c}=await Promise.resolve().then(n.t.bind(n,79896,23));let l="0.0.0";try{const e=r(__dirname,"..","package.json");if(c(e))l=JSON.parse(a(e,"utf-8")).version}catch{}if(l===i){console.log(` Already on latest version (${l}).`);return}const d=detectPackageManager();const u=d==="pnpm"?`pnpm add -g ${o}@latest`:d==="yarn"?`yarn global add ${o}@latest`:`npm install -g ${o}@latest`;console.log(` ${l} → ${i}`);console.log(` Running: ${u}\n`);(0,s.execSync)(u,{stdio:"inherit"});console.log(`\n [32m✓ Updated to ${i}[39m`)}catch(e){console.error(` Update failed: ${e.message}`);console.error(` Try manually: npm install -g ${o}@latest`)}}},96007:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.watchCommand=watchCommand;const s=n(99236);const o=n(96139);const i=process.env.SF_API_URL||"https://simplefunctions.dev";async function watchCommand(e,t,n){const o=parseMode(t);const i=parseInt(n.interval||(o==="orderbook"?"30":"60"));const r=i*1e3;const a=n.json||false;if(!a){const t=o==="price"?"":` [${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()}process.on("SIGINT",(()=>{if(!a)console.log(`\n ${s.c.dim}Watch stopped.${s.c.reset}\n`);process.exit(0)}));switch(o){case"orderbook":await watchOrderbook(e,r,a);break;case"flow":await watchFlow(e,r,a);break;case"cross-venue":await watchCrossVenue(e,r,a);break;case"all":await watchAll(e,r,a);break;default:await watchPrice(e,r,a)}}function parseMode(e){if(!e)return"price";const t=e.toLowerCase();if(t==="orderbook"||t==="ob")return"orderbook";if(t==="flow")return"flow";if(t==="cross-venue"||t==="xv"||t==="cross")return"cross-venue";if(t==="all")return"all";return"price"}async function watchPrice(e,t,n){let o=(new Date).toISOString();try{const t=new Date(Date.now()-60*60*1e3).toISOString();const i=await fetchChanges(t,e);if(i.length>0){if(!n)console.log(` ${s.c.dim}${ts()} Recent changes (last hour):${s.c.reset}`);const e=dedupeByTitle(i);for(const t of e){if(n)console.log(JSON.stringify(t));else printChange(t)}o=i[0].detectedAt}else if(!n){console.log(` ${s.c.dim}${ts()} No recent changes. Watching...${s.c.reset}`)}}catch(e){if(!n)console.error(` ${s.c.dim}${ts()} Error: ${e.message}${s.c.reset}`)}while(true){await sleep(t);try{const t=await fetchChanges(o,e);const i=n?t:dedupeByTitle(t);for(const e of i){if(n)console.log(JSON.stringify(e));else printChange(e)}if(t.length>0){o=t[0].detectedAt}else if(!n){process.stdout.write(` ${s.c.dim}${ts()} · no new changes${s.c.reset}\r`)}}catch(e){if(!n)console.error(` ${s.c.dim}${ts()} Error: ${e.message}${s.c.reset}`)}}}async function watchOrderbook(e,t,n){if(!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 discoverTickers(e);if(i.length===0){console.error(` ${s.c.dim}No Kalshi markets found for "${e}"${s.c.reset}`);process.exit(1)}if(!n){console.log(` ${s.c.dim}Tracking ${i.length} market(s)${s.c.reset}`);console.log()}let r=new Map;while(true){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||[];const c=i.no_dollars||[];const l=a.length>0?Math.round(parseFloat(a[0][0])*100):0;const d=c.length>0?100-Math.round(parseFloat(c[0][0])*100):100;const u=d-l;const p=a.slice(0,3).reduce(((e,t)=>e+parseFloat(t[1])),0);const h=c.slice(0,3).reduce(((e,t)=>e+parseFloat(t[1])),0);const m={ticker:e,title:t,bestBid:l,bestAsk:d,spread:u,bidDepth:p,askDepth:h};const f=r.get(e);if(n){console.log(JSON.stringify({type:"orderbook",ts:(new Date).toISOString(),...m}))}else{const t=u<=2?`${s.c.green}HIGH${s.c.reset}`:u<=5?`${s.c.yellow}MED${s.c.reset}`:`${s.c.red}LOW${s.c.reset}`;let n="";if(f){const e=p-f.bidDepth;const t=h-f.askDepth;if(Math.abs(e)>50||Math.abs(t)>50){const o=e>0?"+":"";const i=t>0?"+":"";n=` ${s.c.dim}depth: bids ${o}${Math.round(e)}, asks ${i}${Math.round(t)}${s.c.reset}`}}console.log(` ${ts()} ${s.c.bold}${e.slice(0,30)}${s.c.reset} bid ${l}c (${Math.round(p)}) | ask ${d}c (${Math.round(h)}) spread ${u}c [${t}]${n}`)}r.set(e,m)}catch{}}await sleep(t)}}async function watchFlow(e,t,n){let o=new Date(Date.now()-2*60*60*1e3).toISOString();const i=new Map;while(true){try{const t=await fetchChanges(o,e);for(const e of t){if(e.changeType!=="price_move")continue;let t=i.get(e.ticker);if(!t){t={ticker:e.ticker,recentDeltas:[],lastPrice:e.afterPrice||0};i.set(e.ticker,t)}t.recentDeltas.push(e.delta||0);if(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));const i=o.every((e=>e<0));if(t||i){const i=o.reduce(((e,t)=>e+Math.abs(t)),0);const r=t?"UP":"DOWN";const a=t?s.c.green:s.c.red;if(n){console.log(JSON.stringify({type:"momentum",ticker:e.ticker,direction:r,totalDelta:i,moves:o.length}))}else{console.log(` ${ts()} ${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];const i=t.recentDeltas[t.recentDeltas.length-1];if(o&&i&&Math.sign(o)!==Math.sign(i)&&Math.abs(i)>=5){if(n){console.log(JSON.stringify({type:"reversal",ticker:e.ticker,previousDelta:o,currentDelta:i}))}else{console.log(` ${ts()} ${s.c.yellow}REVERSAL${s.c.reset} ${e.ticker} was ${o>0?"+":""}${o}c, now ${i>0?"+":""}${i}c`)}}}}if(t.length>0)o=t[0].detectedAt;else if(!n)process.stdout.write(` ${s.c.dim}${ts()} · monitoring flow${s.c.reset}\r`)}catch(e){if(!n)console.error(` ${s.c.dim}${ts()} Error: ${e.message}${s.c.reset}`)}await sleep(t)}}async function watchCrossVenue(e,t,n){if(!n){console.log(` ${s.c.dim}Fetching cross-venue data from scan...${s.c.reset}`)}let o=new Date(Date.now()-2*60*60*1e3).toISOString();const i=new Map;while(true){try{const t=await fetchChanges(o,e);for(const e of t){if(e.changeType!=="price_move")continue;const t=e.title.toLowerCase().slice(0,50);let o=i.get(t);if(!o)o={kalshi:0,poly:0};if(e.venue==="kalshi")o.kalshi=e.afterPrice||0;else if(e.venue==="polymarket")o.poly=e.afterPrice||0;i.set(t,o);if(o.kalshi>0&&o.poly>0){const t=Math.abs(o.kalshi-o.poly);const 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(` ${ts()} ${n}SPREAD${s.c.reset} ${e.title.slice(0,45)} K:${o.kalshi}c P:${o.poly}c gap ${t}c (${i} higher)`)}}}}if(t.length>0)o=t[0].detectedAt;else if(!n)process.stdout.write(` ${s.c.dim}${ts()} · tracking cross-venue${s.c.reset}\r`)}catch(e){if(!n)console.error(` ${s.c.dim}${ts()} Error: ${e.message}${s.c.reset}`)}await sleep(t)}}async function watchAll(e,t,n){let o=new Date(Date.now()-60*60*1e3).toISOString();const i=new Map;const r=new Map;while(true){try{const t=await fetchChanges(o,e);for(const e of t){if(n){console.log(JSON.stringify(e))}else{printChange(e)}if(e.changeType!=="price_move")continue;let t=i.get(e.ticker);if(!t){t={ticker:e.ticker,recentDeltas:[],lastPrice:e.afterPrice||0};i.set(e.ticker,t)}t.recentDeltas.push(e.delta||0);if(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";const t=o.reduce(((e,t)=>e+Math.abs(t)),0);if(!n){const n=e==="UP"?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(e.venue==="kalshi")c.kalshi=e.afterPrice||0;else if(e.venue==="polymarket")c.poly=e.afterPrice||0;r.set(a,c);if(c.kalshi>0&&c.poly>0){const e=Math.abs(c.kalshi-c.poly);if(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`)}}}if(t.length>0)o=t[0].detectedAt;else if(!n)process.stdout.write(` ${s.c.dim}${ts()} · watching all${s.c.reset}\r`)}catch(e){if(!n)console.error(` ${s.c.dim}${ts()} Error: ${e.message}${s.c.reset}`)}await sleep(t)}}async function discoverTickers(e){try{const t=await fetch(`${i}/api/public/scan?q=${encodeURIComponent(e)}&limit=20`);if(!t.ok)return[];const n=await t.json();const s=n.results||n.markets||[];return s.filter((e=>e.ticker&&e.venue==="kalshi")).slice(0,5).map((e=>({ticker:e.ticker,title:e.title||e.ticker})))}catch{return[]}}function dedupeByTitle(e){const t=new Map;for(const n of e){const e=`${n.changeType}:${n.title}`;const s=t.get(e);if(s)s.count++;else t.set(e,{count:1,representative:n})}return Array.from(t.values()).map((({count:e,representative:t})=>{if(e>1)return{...t,title:`${t.title} (${e} contracts)`};return t}))}async function fetchChanges(e,t){let n=`${i}/api/changes?since=${encodeURIComponent(e)}&limit=50`;if(t)n+=`&q=${encodeURIComponent(t)}`;const s=await fetch(n);if(!s.ok)return[];const o=await s.json();return o.changes||[]}function printChange(e){const t=ts();const n=e.venue==="kalshi"?`${s.c.cyan}K${s.c.reset}`:e.venue==="polymarket"?`[35mP[39m`:e.venue==="traditional"?`${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(e.venue==="traditional"){const o=(e.delta||0)>0?"+":"";const i=(e.delta||0)>0?s.c.green:s.c.red;const r=((e.beforePrice||0)/100).toFixed(0);const 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?"+":"";const 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}`)}break}}}function ts(){return(new Date).toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"})}function sleep(e){return new Promise((t=>setTimeout(t,e)))}},18691:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.whatifCommand=whatifCommand;const s=n(19218);const o=n(96139);const i=n(99236);function simulateWhatIf(e,t){const n=[];function flatten(e){for(const t of e){n.push(t);if(t.children?.length)flatten(t.children)}}const s=e.causalTree?.nodes||[];flatten(s);const o=s.filter((e=>e.depth===0||e.depth===undefined&&!e.id.includes(".")));const i=new Map(t.map((e=>[e.nodeId,e.newProbability])));const r=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}}));const a=o.reduce(((e,t)=>e+(t.probability||0)*(t.importance||0)),0);const c=o.reduce(((e,t)=>{const n=i.get(t.id)??t.probability??0;return e+n*(t.importance||0)}),0);const l=new Map;for(const[e,t]of i.entries()){const s=n.find((t=>t.id===e));if(s&&s.probability>0){l.set(e,Math.max(0,Math.min(2,t/s.probability)))}}const d=(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(l.has(t)){n=l.get(t);break}}}const s=e.marketPrice||0;const o=e.thesisPrice||e.thesisImpliedPrice||s;const i=e.edge||e.edgeSize||0;const r=o-s;const a=Math.round((s+r*n)*100)/100;const c=e.direction||"yes";const d=Math.round((c==="yes"?a-s:s-a)*100)/100;const u=Math.round((d-i)*100)/100;let p="unchanged";if(Math.abs(u)<1)p="unchanged";else if(i>0&&d<0||i<0&&d>0)p="reversed";else if(Math.abs(d)<2)p="gone";else if(Math.abs(d)<Math.abs(i))p="reduced";return{marketId:e.marketId,market:e.market||e.marketTitle||e.marketId,venue:e.venue,direction:c,marketPrice:s,oldThesisPrice:o,newThesisPrice:a,oldEdge:i,newEdge:d,delta:u,signal:p,relatedNodeId:t}}));d.sort(((e,t)=>Math.abs(t.delta)-Math.abs(e.delta)));return{overrides:r,oldConfidence:a,newConfidence:c,confidenceDelta:Math.round((c-a)*100)/100,edges:d}}async function whatifCommand(e,t){if(!t.set||t.set.length===0){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}}));const r=new s.SFClient(t.apiKey,t.apiUrl);const a=await r.getContext(e);const c=simulateWhatIf(a,n);if(t.json){console.log(JSON.stringify(c,null,2));return}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(e.oldProb*100);const n=Math.round(e.newProb*100);const 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(c.oldConfidence*100);const d=Math.round(c.newConfidence*100);const u=c.confidenceDelta>0?"+":"";const 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(c.confidenceDelta*100)}${i.c.reset})`);console.log();const h=c.edges.filter((e=>e.signal!=="unchanged"));if(h.length===0){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);const n=`${Math.round(e.marketPrice)}¢`.padEnd(6);const s=`${e.oldEdge>0?"+":""}${Math.round(e.oldEdge)}`.padEnd(8);const 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])));const n=e.filter((e=>{const n=t.get(e.ticker);return n&&(n.signal==="reversed"||n.signal==="gone")}));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);const s=await(0,o.getMarketPrice)(e.ticker);const r=s!==null?((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()}},33192:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.worldCommand=worldCommand;const s=n(99236);async function worldCommand(e){const t=process.env.SF_API_URL||"https://simplefunctions.dev";if(e.delta){const n=e.since||"1h";const o=await fetch(`${t}/api/agent/world/delta?since=${encodeURIComponent(n)}`);if(!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)}`:"";const o=await fetch(`${t}/api/agent/world${n}`);if(!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()}}},84436:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.xSearchCommand=xSearchCommand;t.xVolumeCommand=xVolumeCommand;t.xNewsCommand=xNewsCommand;t.xAccountCommand=xAccountCommand;const n=process.env.SF_API_URL||"https://simplefunctions.dev";function getApiKey(){const e=process.env.SF_API_KEY||"";if(!e){console.error(" API key required. Run: sf setup");process.exit(1)}return e}async function apiFetch(e){const t=await fetch(`${n}${e}`,{headers:{Authorization:`Bearer ${getApiKey()}`}});if(!t.ok){const e=await t.text();throw new Error(`${t.status}: ${e}`)}return t.json()}async function xSearchCommand(e,t){const n=t?.raw?"raw":"summary";const s=t?.hours||"24";const o=t?.limit||"20";const i=await apiFetch(`/api/x/search?q=${encodeURIComponent(e)}&mode=${n}&hours=${s}&limit=${o}`);if(t?.json){console.log(JSON.stringify(i,null,2));return}if(i.summary){console.log(`\n [1m[36mX: ${e}[0m\n`);console.log(` ${i.summary}\n`);if(i.sentiment){const e={bullish:"[32m",bearish:"[31m",mixed:"[33m",neutral:"[2m"};console.log(` Sentiment: ${e[i.sentiment]||""}${i.sentiment}[0m`)}if(i.keyThemes?.length){console.log(` Themes: ${i.keyThemes.join(", ")}`)}console.log()}const r=i.posts||[];if(r.length>0){console.log(` [1mTop posts[22m (${r.length})\n`);for(const e of r.slice(0,10)){const t=e.metrics?.likes||0;const n=e.metrics?.retweets||0;const s=e.authorFollowers?` (${formatNum(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(i.volume){const e=i.volume;const t=e.velocityChange>1?`[32m+${Math.round((e.velocityChange-1)*100)}%[0m`:`[31m${Math.round((e.velocityChange-1)*100)}%[0m`;console.log(` [2mVolume: ${formatNum(e.totalCount)} posts (${s}h) | Velocity: ${t} | Peak: ${e.peak?.count}[0m\n`)}const a=i.news||[];if(a.length>0){console.log(` [1mX News[22m (${a.length})\n`);for(const e of a.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`)}}}async function xVolumeCommand(e,t){const n=t?.hours||"72";const s=t?.granularity||"hour";const o=await apiFetch(`/api/x/volume?q=${encodeURIComponent(e)}&hours=${n}&granularity=${s}`);if(t?.json){console.log(JSON.stringify(o,null,2));return}console.log(`\n [1m[36mX Volume: ${e}[0m\n`);console.log(` Total: ${formatNum(o.totalCount)} posts (${n}h)`);const i=o.velocityChange>1?`[32m+${Math.round((o.velocityChange-1)*100)}%[0m`:`[31m${Math.round((o.velocityChange-1)*100)}%[0m`;console.log(` Velocity: ${i}`);console.log(` Peak: ${o.peak?.count} at ${o.peak?.time?.slice(11,16)||"?"}\n`);const r=o.timeseries||[];if(r.length>0){const e=Math.max(...r.map((e=>e.count)));const t=40;for(const n of r.slice(-24)){const s=(n.time||"").slice(11,16)||"?";const o=e>0?Math.round(n.count/e*t):0;const i="▓".repeat(o);const r=String(n.count).padStart(6);console.log(` ${s} ${r} ${i}`)}}console.log()}async function xNewsCommand(e,t){const n=t?.limit||"10";const s=await apiFetch(`/api/x/news?q=${encodeURIComponent(e)}&limit=${n}`);if(t?.json){console.log(JSON.stringify(s,null,2));return}const o=s.stories||[];console.log(`\n [1m[36mX News: ${e}[0m (${o.length} stories)\n`);for(const e of o){const t=e.tickers?.length?` [33m${e.tickers.join(" ")}[0m`:"";const 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()}}async function xAccountCommand(e,t){const n=e.replace(/^@/,"");const s=t?.hours||"24";const o=t?.limit||"20";const i=await apiFetch(`/api/x/account?username=${n}&hours=${s}&limit=${o}`);if(t?.json){console.log(JSON.stringify(i,null,2));return}const r=i.posts||[];console.log(`\n [1m[36m@${n}[0m (${r.length} posts, last ${s}h)\n`);for(const e of r){const t=e.metrics?.likes||0;const n=e.metrics?.retweets||0;const 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`)}}function formatNum(e){if(e>=1e6)return`${(e/1e6).toFixed(1)}M`;if(e>=1e3)return`${(e/1e3).toFixed(1)}K`;return 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:true});t.loadFileConfig=loadFileConfig;t.loadConfig=loadConfig;t.saveConfig=saveConfig;t.resetConfig=resetConfig;t.applyConfig=applyConfig;t.isConfigured=isConfigured;t.requireTrading=requireTrading;t.getConfigPath=getConfigPath;const o=s(n(79896));const i=s(n(16928));const r=s(n(70857));const a=i.default.join(r.default.homedir(),".sf");const c=i.default.join(a,"config.json");const l="https://simplefunctions.dev";const d="anthropic/claude-sonnet-4.6";function loadFileConfig(){try{if(o.default.existsSync(c)){return JSON.parse(o.default.readFileSync(c,"utf-8"))}}catch{}return{}}function loadConfig(){const e=loadFileConfig();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||false,telegramBotToken:process.env.TELEGRAM_BOT_TOKEN||e.telegramBotToken}}function saveConfig(e){o.default.mkdirSync(a,{recursive:true});o.default.writeFileSync(c,JSON.stringify({...e,configuredAt:(new Date).toISOString()},null,2))}function resetConfig(){try{if(o.default.existsSync(c)){o.default.unlinkSync(c)}}catch{}}function applyConfig(){const e=loadFileConfig();if(!process.env.SF_API_KEY&&e.apiKey){process.env.SF_API_KEY=e.apiKey}if(!process.env.SF_API_URL&&e.apiUrl){process.env.SF_API_URL=e.apiUrl}if(!process.env.OPENROUTER_API_KEY&&e.openrouterKey){process.env.OPENROUTER_API_KEY=e.openrouterKey}if(!process.env.KALSHI_API_KEY_ID&&e.kalshiKeyId){process.env.KALSHI_API_KEY_ID=e.kalshiKeyId}if(!process.env.KALSHI_PRIVATE_KEY_PATH&&e.kalshiPrivateKeyPath){process.env.KALSHI_PRIVATE_KEY_PATH=e.kalshiPrivateKeyPath}if(!process.env.POLYMARKET_WALLET_ADDRESS&&e.polymarketWalletAddress){process.env.POLYMARKET_WALLET_ADDRESS=e.polymarketWalletAddress}if(!process.env.POLYMARKET_PRIVATE_KEY_PATH&&e.polymarketPrivateKeyPath){process.env.POLYMARKET_PRIVATE_KEY_PATH=e.polymarketPrivateKeyPath}if(!process.env.TAVILY_API_KEY&&e.tavilyKey){process.env.TAVILY_API_KEY=e.tavilyKey}if(!process.env.SF_MODEL&&e.model){process.env.SF_MODEL=e.model}}function isConfigured(){const e=loadConfig();return!!e.apiKey}function requireTrading(){const e=loadConfig();if(!e.tradingEnabled){console.error("\n Trading is disabled. Run: sf setup --enable-trading\n");process.exit(1)}if(!e.kalshiKeyId&&!process.env.KALSHI_API_KEY_ID){console.error("\n Kalshi API key not configured. Run: sf setup --kalshi\n");process.exit(1)}}function getConfigPath(){return c}},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:true});t.isKalshiConfigured=isKalshiConfigured;t.getPositions=getPositions;t.kalshiPriceCents=kalshiPriceCents;t.getMarketPrice=getMarketPrice;t.getOrderbook=getOrderbook;t.getPublicOrderbook=getPublicOrderbook;t.getSettlements=getSettlements;t.getBalance=getBalance;t.getOrders=getOrders;t.getFills=getFills;t.getForecastHistory=getForecastHistory;t.getExchangeAnnouncements=getExchangeAnnouncements;t.getHistoricalMarket=getHistoricalMarket;t.createOrder=createOrder;t.cancelOrder=cancelOrder;t.batchCancelOrders=batchCancelOrders;t.amendOrder=amendOrder;t.getBatchCandlesticks=getBatchCandlesticks;t.createRFQ=createRFQ;const o=s(n(79896));const i=s(n(16928));const r=s(n(76982));const a="https://api.elections.kalshi.com/trade-api/v2";function isKalshiConfigured(){return!!(process.env.KALSHI_API_KEY_ID&&process.env.KALSHI_PRIVATE_KEY_PATH)}function loadPrivateKey(){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){console.warn(`[Kalshi] Failed to load private key from ${t}:`,e);return null}}function signRequest(e,t,n){const s=process.env.KALSHI_API_KEY_ID;const o=Date.now().toString();const i=o+e.toUpperCase()+t;const a=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});return{headers:{"KALSHI-ACCESS-KEY":s,"KALSHI-ACCESS-SIGNATURE":a.toString("base64"),"KALSHI-ACCESS-TIMESTAMP":o,"Content-Type":"application/json",Accept:"application/json"}}}async function kalshiAuthGet(e){const t=loadPrivateKey();if(!t){throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.")}const n=`${a}${e}`;const s=e.split("?")[0];const{headers:o}=signRequest("GET",`/trade-api/v2${s}`,t);const 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 kalshiAuthPost(e,t){const n=loadPrivateKey();if(!n){throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.")}const s=`${a}${e}`;const o=e.split("?")[0];const{headers:i}=signRequest("POST",`/trade-api/v2${o}`,n);const 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()}async function kalshiAuthDelete(e){const t=loadPrivateKey();if(!t){throw new Error("Kalshi private key not loaded. Check KALSHI_PRIVATE_KEY_PATH.")}const n=`${a}${e}`;const s=e.split("?")[0];const{headers:o}=signRequest("DELETE",`/trade-api/v2${s}`,t);const 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{}}async function getPositions(){if(!isKalshiConfigured())return null;try{const e=await kalshiAuthGet("/portfolio/positions");const t=e.market_positions||e.positions||[];return t.map((e=>{const t=parseFloat(e.position_fp||"0");const n=parseFloat(e.total_traded_dollars||"0");const s=Math.abs(t);const o=t>=0?"yes":"no";const 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(parseFloat(e.realized_pnl||"0")*100),unrealized_pnl:0,total_cost:Math.round(n*100)}}))}catch(e){console.warn(`[Kalshi] Failed to fetch positions:`,e);return null}}function kalshiPriceCents(e){if(e.last_price_dollars){const t=parseFloat(e.last_price_dollars);if(!isNaN(t)&&t>0)return Math.round(t*100)}if(e.yes_bid_dollars){const t=parseFloat(e.yes_bid_dollars);if(!isNaN(t)&&t>0)return Math.round(t*100)}if(e.yes_ask_dollars){const t=parseFloat(e.yes_ask_dollars);if(!isNaN(t)&&t>0)return Math.round(t*100)}if(e.last_price!=null&&e.last_price>0)return e.last_price;if(e.yes_bid!=null&&e.yes_bid>0)return e.yes_bid;return 50}async function getMarketPrice(e){try{const t=`https://api.elections.kalshi.com/trade-api/v2/markets/${e}`;const n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)return null;const s=await n.json();const o=s.market||s;const i=kalshiPriceCents(o);return i===50&&!o.last_price_dollars&&!o.yes_bid_dollars?null:i}catch{return null}}async function getOrderbook(e){if(!isKalshiConfigured())return null;try{const t=await kalshiAuthGet(`/markets/${e}/orderbook`);const n=t.orderbook_fp||t.orderbook;if(!n)return null;const s=n.yes_dollars||n.yes||[];const o=n.no_dollars||n.no||[];const i=!!(n.yes_dollars||n.no_dollars);const r=s.map((e=>({price:i?Math.round(parseFloat(e[0])*100):Number(e[0]),qty:parseFloat(e[1])}))).filter((e=>e.price>0));const a=o.map((e=>({price:i?Math.round(parseFloat(e[0])*100):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;const l=a.length>0?100-a[0].price:100;const d=l-c;const u=r.slice(0,3).reduce(((e,t)=>e+t.qty),0);const p=a.slice(0,3).reduce(((e,t)=>e+t.qty),0);const h=Math.min(u,p);let m="low";if(d<=2&&h>=500)m="high";else if(d<=5&&h>=100)m="medium";return{bestBid:c,bestAsk:l,spread:d,bidDepth:u,askDepth:p,liquidityScore:m}}catch{return null}}async function getPublicOrderbook(e,t=20){try{const n=`${a}/markets/${e}/orderbook?depth=${t}`;const s=await fetch(n,{headers:{Accept:"application/json"}});if(!s.ok)return null;const o=await s.json();const 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}}async function getSettlements(e){if(!isKalshiConfigured())return null;try{const t=new URLSearchParams;if(e?.limit)t.set("limit",e.limit.toString());if(e?.cursor)t.set("cursor",e.cursor);if(e?.ticker)t.set("ticker",e.ticker);const n=await kalshiAuthGet(`/portfolio/settlements?${t.toString()}`);return{settlements:n.settlements||[],cursor:n.cursor||""}}catch(e){console.warn("[Kalshi] Failed to fetch settlements:",e);return null}}async function getBalance(){if(!isKalshiConfigured())return null;try{const e=await kalshiAuthGet("/portfolio/balance");const t=(e.balance||0)/100;const n=(e.portfolio_value||0)/100;return{balance:t,portfolioValue:n}}catch(e){console.warn("[Kalshi] Failed to fetch balance:",e);return null}}async function getOrders(e){if(!isKalshiConfigured())return null;try{const t=new URLSearchParams;if(e?.status)t.set("status",e.status);if(e?.ticker)t.set("ticker",e.ticker);if(e?.limit)t.set("limit",e.limit.toString());if(e?.cursor)t.set("cursor",e.cursor);const n=await kalshiAuthGet(`/portfolio/orders?${t.toString()}`);return{orders:n.orders||[],cursor:n.cursor||""}}catch(e){console.warn("[Kalshi] Failed to fetch orders:",e);return null}}async function getFills(e){if(!isKalshiConfigured())return null;try{const t=new URLSearchParams;if(e?.ticker)t.set("ticker",e.ticker);if(e?.limit)t.set("limit",e.limit.toString());if(e?.cursor)t.set("cursor",e.cursor);const n=await kalshiAuthGet(`/portfolio/fills?${t.toString()}`);return{fills:n.fills||[],cursor:n.cursor||""}}catch(e){console.warn("[Kalshi] Failed to fetch fills:",e);return null}}async function getForecastHistory(e){if(!isKalshiConfigured())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);const 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()}`;const i=await kalshiAuthGet(o);return i.forecast_history||[]}catch(e){console.warn("[Kalshi] Failed to fetch forecast:",e);return null}}async function getExchangeAnnouncements(){try{const e=await fetch(`${a}/exchange/announcements`,{headers:{Accept:"application/json"}});if(!e.ok)return[];const t=await e.json();return t.announcements||[]}catch{return[]}}async function getHistoricalMarket(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}}async function createOrder(e){return kalshiAuthPost("/portfolio/orders",e)}async function cancelOrder(e){await kalshiAuthDelete(`/portfolio/orders/${e}`)}async function batchCancelOrders(e){await kalshiAuthPost("/portfolio/orders/batched",{orders:e.map((e=>({action:"cancel",order_id:e})))})}async function amendOrder(e,t){const n=loadPrivateKey();if(!n)throw new Error("Kalshi private key not loaded.");const s=`/portfolio/orders/${e}`;const o=`${a}${s}`;const{headers:i}=signRequest("PATCH",`/trade-api/v2${s}`,n);const 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()}async function getBatchCandlesticks(e){if(!isKalshiConfigured())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());const n=await kalshiAuthGet(`/markets/candlesticks?${t.toString()}`);return n.markets||[]}catch(e){console.warn("[Kalshi] Failed to fetch candlesticks:",e);return[]}}async function createRFQ(e){return kalshiAuthPost("/communications/rfqs",e)}},34331:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.polymarketSearch=polymarketSearch;t.polymarketListEvents=polymarketListEvents;t.polymarketGetEvent=polymarketGetEvent;t.polymarketGetMarket=polymarketGetMarket;t.polymarketListTags=polymarketListTags;t.polymarketGetOrderbook=polymarketGetOrderbook;t.computeOrderbookDepth=computeOrderbookDepth;t.polymarketGetOrderbookWithDepth=polymarketGetOrderbookWithDepth;t.polymarketGetMidpoint=polymarketGetMidpoint;t.polymarketGetSpread=polymarketGetSpread;t.polymarketGetMidpoints=polymarketGetMidpoints;t.polymarketGetOHLC=polymarketGetOHLC;t.polymarketGetPriceHistory=polymarketGetPriceHistory;t.polymarketGetPositions=polymarketGetPositions;t.polymarketGetClosedPositions=polymarketGetClosedPositions;t.scoreLiquidity=scoreLiquidity;t.parseClobTokenIds=parseClobTokenIds;t.parseOutcomes=parseOutcomes;t.parseOutcomePrices=parseOutcomePrices;t.toCents=toCents;t.polymarketUrl=polymarketUrl;const n="https://gamma-api.polymarket.com";const s="https://clob.polymarket.com";const o="https://data-api.polymarket.com";async function polymarketSearch(e,t=20){const s=new URLSearchParams({q:e,limit_per_type:t.toString()});const 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||[]}async function polymarketListEvents(e){const t=new URLSearchParams({active:"true",closed:"false",limit:(e?.limit||50).toString(),offset:(e?.offset||0).toString()});if(e?.order)t.set("order",e.order);if(e?.ascending!==undefined)t.set("ascending",String(e.ascending));if(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()}async function polymarketGetEvent(e){const t=await fetch(`${n}/events/${e}`);if(!t.ok)throw new Error(`Polymarket event error: ${t.status}`);return t.json()}async function polymarketGetMarket(e){const t=await fetch(`${n}/markets/${e}`);if(!t.ok)throw new Error(`Polymarket market error: ${t.status}`);return t.json()}async function polymarketListTags(){const e=await fetch(`${n}/tags`);if(!e.ok)throw new Error(`Polymarket tags error: ${e.status}`);return e.json()}async function polymarketGetOrderbook(e){try{const t=await fetch(`${s}/book?token_id=${e}`);if(!t.ok)return null;const n=await t.json();if(n.error)return null;return n}catch{return null}}function computeOrderbookDepth(e){const t=(e.bids||[]).map((e=>({price:parseFloat(e.price),size:parseFloat(e.size)}))).sort(((e,t)=>t.price-e.price));const n=(e.asks||[]).map((e=>({price:parseFloat(e.price),size:parseFloat(e.size)}))).sort(((e,t)=>e.price-t.price));const s=t.length>0?Math.round(t[0].price*100):0;const o=n.length>0?Math.round(n[0].price*100):100;const i=o-s;const r=t.slice(0,3).reduce(((e,t)=>e+t.size),0);const a=n.slice(0,3).reduce(((e,t)=>e+t.size),0);const c=t.reduce(((e,t)=>e+t.size),0);const l=n.reduce(((e,t)=>e+t.size),0);const d=scoreLiquidity(i,r+a);return{bestBid:s,bestAsk:o,spread:i,bidDepthTop3:Math.round(r),askDepthTop3:Math.round(a),totalBidDepth:Math.round(c),totalAskDepth:Math.round(l),liquidityScore:d,levels:{bids:e.bids,asks:e.asks}}}async function polymarketGetOrderbookWithDepth(e){const t=await polymarketGetOrderbook(e);if(!t)return null;return computeOrderbookDepth(t)}async function polymarketGetMidpoint(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}}async function polymarketGetSpread(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}}async function polymarketGetMidpoints(e){if(e.length===0)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()}async function polymarketGetOHLC(e){const t=new URLSearchParams({asset_id:e.tokenId,startTs:e.startTs.toString(),fidelity:e.fidelity||"1h"});if(e.endTs)t.set("endTs",e.endTs.toString());if(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||[]}async function polymarketGetPriceHistory(e){const t=new URLSearchParams({market:e.tokenId});if(e.interval)t.set("interval",e.interval);if(e.startTs)t.set("startTs",e.startTs.toString());if(e.endTs)t.set("endTs",e.endTs.toString());if(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||[]}async function polymarketGetPositions(e){const t=await fetch(`${o}/positions?user=${e}`);if(!t.ok)return[];const n=await t.json();return Array.isArray(n)?n:[]}async function polymarketGetClosedPositions(e){const t=await fetch(`${o}/closed-positions?user=${e}`);if(!t.ok)return[];const n=await t.json();return Array.isArray(n)?n:[]}function scoreLiquidity(e,t){if(e<=2&&t>=500)return"high";if(e<=5&&t>=100)return"medium";return"low"}function parseClobTokenIds(e){try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length>=2)return[t[0],t[1]];return null}catch{return null}}function parseOutcomes(e){try{return JSON.parse(e)}catch{return[]}}function parseOutcomePrices(e){try{return JSON.parse(e)}catch{return[]}}function toCents(e){return Math.round(e*100)}function polymarketUrl(e){return`https://polymarket.com/event/${e}`}},35178:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.shareOutput=shareOutput;const n=process.env.SF_API_URL||"https://simplefunctions.dev";async function shareOutput(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){console.error(`Share failed: ${o.status}`);return}const{url:i}=await o.json();console.log();console.log(` [36m${i}[39m`);console.log()}catch(e){console.error(`Share failed: ${e.message}`)}}},40101:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.loadSkills=loadSkills;const s=n(79896);const o=n(16928);function loadSkills(){const e=[];const t=__dirname;const n=t.includes("dist")?(0,o.join)(t,"../../src/skills"):t;let i=[];try{i=(0,s.readdirSync)(n).filter((e=>e.endsWith(".md")))}catch{return e}for(const t of i){try{const i=(0,s.readFileSync)((0,o.join)(n,t),"utf-8");const r=parseSkillFile(i);if(r)e.push(r)}catch{}}try{const t=process.env.HOME||process.env.USERPROFILE||"";const n=(0,o.join)(t,".sf","skills");const i=(0,s.readdirSync)(n).filter((e=>e.endsWith(".md")));for(const t of i){try{const i=(0,s.readFileSync)((0,o.join)(n,t),"utf-8");const r=parseSkillFile(i);if(r)e.push(r)}catch{}}}catch{}return e}function parseSkillFile(e){const t=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!t)return null;const n=t[1];const s=t[2].trim();const o={};for(const e of n.split("\n")){const t=e.match(/^(\w[\w_]*)\s*:\s*(.+)$/);if(t)o[t[1]]=t[2].trim()}if(!o.name||!o.trigger)return null;const i=s.match(/## Instructions\n([\s\S]*)$/i);const r=i?i[1].trim():s;const parseArray=e=>(e||"").replace(/[\[\]]/g,"").split(",").map((e=>e.trim())).filter(Boolean);return{name:o.name,trigger:o.trigger,description:o.description||"",author:o.author||"unknown",version:o.version||"1.0.0",category:o.category||"general",tags:parseArray(o.tags),toolsUsed:parseArray(o.tools_used),estimatedTime:o.estimated_time||"",auto:o.auto,prompt:r,raw:e}}},97325:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.RISK_CATEGORIES=t.TOPIC_SERIES=void 0;t.tickerToTopic=tickerToTopic;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"};function tickerToTopic(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"}},77096:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.CLR=t.bgRgb=t.rgb=void 0;t.drawBorder=drawBorder;t.drawHDivider=drawHDivider;t.fit=fit;t.sparkline=sparkline;t.compact=compact;const rgb=(e,t,n)=>`[38;2;${e};${t};${n}m`;t.rgb=rgb;const bgRgb=(e,t,n)=>`[48;2;${e};${t};${n}m`;t.bgRgb=bgRgb;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)};function drawBorder(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)}if(s){e.write(o,i+2,` ${s} `,t.CLR.dim)}}function drawHDivider(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)}}function fit(e,t,n="left"){if(e.length>t)return e.slice(0,t-1)+"…";if(n==="right")return e.padStart(t);return e.padEnd(t)}function sparkline(e,n){if(e.length===0)return[];const s=Math.min(...e);const o=Math.max(...e);const i=o-s||1;const r="▁▂▃▄▅▆▇█";return e.map((e=>{const o=Math.round((e-s)/i*7);return{text:r[o],fg:n?n(e):t.CLR.dim}}))}function compact(e){if(Math.abs(e)>=1e6)return`${(e/1e6).toFixed(1)}M`;if(Math.abs(e)>=1e4)return`${(e/1e3).toFixed(0)}k`;if(Math.abs(e)>=1e3)return`${(e/1e3).toFixed(1)}k`;return String(Math.round(e))}},14916:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.drawChart=drawChart;const s=n(77096);function drawChart(e,t,n,o,i,r,a){if(r.length===0||o<10||i<4)return;const c=8;const l=o-c-1;const d=i-2;if(l<4||d<2)return;const u=Math.min(...r);const p=Math.max(...r);const h=p-u||1;const m=[];for(let e=0;e<l;e++){const t=e/(l-1)*(r.length-1);const n=Math.floor(t);const s=Math.min(n+1,r.length-1);const o=t-n;m.push(r[n]*(1-o)+r[s]*o)}const f=n+c+1;const g=[{row:0,value:p},{row:d-1,value:u}];let y=-1;if(u<0&&p>0){y=Math.round(p/h*(d-1));if(y>0&&y<d-1){g.push({row:y,value:0})}}for(let o=0;o<d;o++){e.write(t+o,n+c,"│",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(c),s.CLR.dim)}if(y>=0&&y<d){for(let n=0;n<l;n++){e.write(t+y,f+n,"╌",s.CLR.veryDim)}}const $=" ▁▂▃▄▅▆▇█";for(let n=0;n<l;n++){const o=m[n];const i=(o-u)/h;const r=i*d*8;const a=o>=0?s.CLR.green:s.CLR.red;for(let s=d-1;s>=0;s--){const o=d-1-s;const i=r-o*8;if(i>=8){e.write(t+s,f+n,"█",a)}else if(i>0){const o=Math.round(Math.max(1,Math.min(i,8)));e.write(t+s,f+n,$[o],a)}}}const k=t+d;e.write(k,n+c,"└",s.CLR.borderDim);for(let t=0;t<l;t++){e.write(k,f+t,"─",s.CLR.borderDim)}if(a&&a.length>0){const i=t+d+1;const r=Math.min(a.length,6);for(let t=0;t<r;t++){const c=Math.round(t*(a.length-1)/Math.max(r-1,1));const d=f+Math.round(c*(l-1)/Math.max(a.length-1,1));const u=a[c]||"";if(d>=f&&d+u.length<n+o){e.write(i,d,u.slice(0,5),s.CLR.dim)}}}}},99844:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.loadAllData=loadAllData;t.startDashboard=startDashboard;const s=n(72222);const o=n(42992);const i=n(56661);const r=n(77096);const a=n(87783);const c=n(11627);const l=n(19218);const d=n(96139);const u=n(97325);const p=n(34331);const h=n(3322);const m=n(21704);const f=n(30012);const g=n(75757);const y=n(50511);const $=n(98573);const k=n(12423);const b=n(72734);const w=n(35301);const _=n(82950);const S=n(29405);const v=n(67748);const x=n(87009);const C=15e3;const O=3e4;const I=1e4;const P=3e4;const T=6e4;const E=6e4;let A=null;function getClient(){if(A)return A;try{const e=(0,c.loadConfig)();if(!e.apiKey)return null;A=new l.SFClient(e.apiKey,e.apiUrl);return A}catch{return null}}async function loadAllData(e){const t=getClient();const[n,s,o,i]=await Promise.allSettled([(0,a.cached)("positions",C,(()=>(0,d.getPositions)())),t?(0,a.cached)("theses",O,(()=>t.listTheses())):Promise.resolve(null),(0,a.cached)("orders",I,(()=>(0,d.getOrders)({status:"resting"}))),(0,a.cached)("balance",P,(()=>(0,d.getBalance)()))]);if(n.status==="fulfilled"&&n.value){const t=n.value;const 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];if(n.status==="fulfilled"&&n.value!=null){t[e].current_value=n.value;t[e].unrealized_pnl=Math.round((n.value-t[e].average_price_paid)*t[e].quantity)}}e.positions=t}const r=(0,c.loadConfig)();if(r.polymarketWalletAddress){try{const t=await(0,a.cached)("poly-positions",C,(()=>(0,p.polymarketGetPositions)(r.polymarketWalletAddress)));if(t&&Array.isArray(t)&&t.length>0){for(const n of t){e.positions.push({ticker:(n.title||n.slug||n.asset||"").slice(0,25),quantity:n.size||0,average_price_paid:Math.round((n.avgPrice||0)*100),current_value:Math.round((n.curPrice||n.currentPrice||0)*100),unrealized_pnl:Math.round((n.cashPnl||0)*100),side:(n.outcome||"yes").toLowerCase(),venue:"polymarket"})}}}catch{}}if(s.status==="fulfilled"&&s.value){const t=s.value;e.theses=t.theses||t||[]}if(o.status==="fulfilled"&&o.value){e.orders=o.value.orders||[]}if(i.status==="fulfilled"&&i.value){e.balance=i.value.balance??0}if(t&&e.theses.length>0){const n=await Promise.allSettled(e.theses.map((e=>(0,a.cached)(`ctx:${e.id}`,O,(()=>t.getContext(e.id))))));for(let t=0;t<e.theses.length;t++){const s=n[t];if(s.status==="fulfilled"&&s.value){e.contexts.set(e.theses[t].id,s.value)}}}computeEdges(e);await loadCandles(e);if(t){try{const n=await(0,a.cached)("feed",T,(()=>t.getFeed(48)));const s=n.entries||n.feed||n;if(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",O,(()=>fetch("https://simplefunctions.dev/api/public/markets").then((e=>e.ok?e.json():null))));if(t){if(Array.isArray(t)){e.traditionalMarkets=t}else if(typeof t==="object"){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{}collectEvents(e);checkExchangeStatus(e);e.lastRefresh.all=Date.now()}function computeEdges(e){const t=[];for(const[,n]of e.contexts){if(!n?.edges)continue;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;const s=n.get(t);if(!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 loadCandles(e){const t=e.positions.map((e=>e.ticker)).filter(Boolean);if(t.length===0)return;try{const n=Math.floor(Date.now()/1e3);const s=n-7*86400;const 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");const n=parseFloat(e.yes_ask?.close_dollars||"0");const s=t>0&&n>0?(t+n)/2:t||n;const o=parseFloat(e.price?.close_dollars||"0")||s;return{close:Math.round(o*100),date:e.end_period_ts?new Date(e.end_period_ts*1e3).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 collectEvents(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)=>{const n=new Date(e.timestamp||e.date||e.time||0).getTime();const s=new Date(t.timestamp||t.date||t.time||0).getTime();return n-s}));e.events=t.filter((e=>{const t=new Date(e.timestamp||e.date||e.time||0).getTime();return t>Date.now()}))}function checkExchangeStatus(e){const t=new Date;const n=t.getUTCDay();e.exchangeOpen=n>=1&&n<=5}function renderFrame(e,t){(0,k.renderMarketBar)(e,0,t);(0,$.renderStatusBar)(e,1,t);(0,b.renderCommandBar)(e,e.rows-1,t);switch(t.mode){case"overview":renderOverview(e,t);break;case"detail":(0,w.renderDetail)(e,(0,o.fullLayout)(e.cols,e.rows),t);break;case"liquidity":(0,_.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":if(t.prevMode==="detail"){(0,w.renderDetail)(e,(0,o.fullLayout)(e.cols,e.rows),t)}else{renderOverview(e,t)}(0,v.renderTrade)(e,(0,o.fullLayout)(e.cols,e.rows),t);break}e.flush()}function renderOverview(e,t){const n=e.cols<80;const s=n?(0,o.narrowLayout)(e.cols,e.rows):(0,o.overviewLayout)(e.cols,e.rows);if(!n){const t=Math.floor(e.cols*.55);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,f.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,g.renderOrders)(e,n,t);break}}}function handleKeypress(e,t,n,s,o){const i=t.toString("utf-8");const r=t[0]===27&&t.length===1;const a=t[0]===27&&t[1]===91&&t[2]===65;const c=t[0]===27&&t[1]===91&&t[2]===66;const l=i==="\r"||i==="\n";const d=t[0]===3;if(d||i==="q"&&e.mode!=="trade"){o();return}e.error=null;switch(e.mode){case"overview":handleOverviewKey(i,a,c,l,e,n,s,o);break;case"detail":handleDetailKey(i,r,e,n,s);break;case"liquidity":handleLiquidityKey(i,a,c,r,e,n,s);break;case"whatif":handleWhatifKey(i,a,c,l,r,e,n,s);break;case"trade":handleTradeKey(i,a,c,l,r,e,n,s);break}}function handleOverviewKey(e,t,n,s,o,i,r,c){const l=o.focusArea==="positions"?o.positions:o.focusArea==="edges"?o.edges:o.intents||[];const d=Math.max(0,l.length-1);if(e==="j"||n){o.selectedIndex=Math.min(o.selectedIndex+1,d);r()}else if(e==="k"||t){o.selectedIndex=Math.max(o.selectedIndex-1,0);r()}else if(s){if(o.focusArea==="positions"&&o.positions.length>0){const e=o.positions[o.selectedIndex];o.detailTicker=e?.ticker||null;o.prevMode="overview";o.mode="detail";r()}}else if(e==="l"){o.prevMode="overview";o.mode="liquidity";o.liquiditySelectedIndex=0;loadLiquidityData(o).then(r)}else if(e==="w"){if(o.theses.length>0){o.prevMode="overview";o.mode="whatif";o.whatifThesisId=o.theses[0].id;loadWhatifData(o).then(r)}}else if(e==="b"){openTrade(o,"buy");r()}else if(e==="s"){openTrade(o,"sell");r()}else if(e==="e"){triggerEvaluate(o).then(r)}else if(e==="r"){(0,a.invalidateAll)();loadAllData(o).then(r)}else if(e==="i"){if(o.focusArea==="edges"&&o.edges.length>0){const e=o.edges[o.selectedIndex];if(e){const t=e.marketId||e.ticker||"";openTrade(o,"buy");if(o.tradeParams){o.tradeParams.ticker=t;o.tradeParams.side=e.direction||"yes";o.tradeParams.price=e.marketPrice||50}r()}}}else if(e==="x"){if(o.focusArea==="intents"&&o.intents.length>0){const e=o.intents[o.selectedIndex];if(e?.id){const t=getClient();if(t){t.request("DELETE",`/api/intents/${e.id}`).then((()=>{(0,a.invalidateAll)();loadAllData(o).then(r)})).catch((()=>{o.error="Failed to cancel intent";r()}))}}}}else if(e>="1"&&e<="9"){const t=parseInt(e)-1;if(t<o.theses.length){o.activeThesisIndex=t;r()}}else if(e==="\t"){if(o.focusArea==="positions")o.focusArea="edges";else if(o.focusArea==="edges")o.focusArea="intents";else o.focusArea="positions";o.selectedIndex=0;r()}}function handleDetailKey(e,t,n,s,o){if(t){n.mode="overview";o()}else if(e==="b"){openTrade(n,"buy");o()}else if(e==="s"){openTrade(n,"sell");o()}else if(e==="w"){if(n.theses.length>0){n.prevMode="detail";n.mode="whatif";n.whatifThesisId=n.theses[0].id;loadWhatifData(n).then(o)}}}function handleLiquidityKey(e,t,n,s,o,i,r){if(s){o.mode=o.prevMode;r()}else if(e==="j"||n){o.liquiditySelectedIndex++;r()}else if(e==="k"||t){o.liquiditySelectedIndex=Math.max(0,o.liquiditySelectedIndex-1);r()}else if(e==="\t"){const e=Object.keys(u.TOPIC_SERIES);const t=e.indexOf(o.liquidityTopic);o.liquidityTopic=e[(t+1)%e.length];o.liquiditySelectedIndex=0;loadLiquidityData(o).then(r)}else if(e==="b"){openTradeFromLiquidity(o);r()}else if(e==="r"){loadLiquidityData(o).then(r)}}function handleWhatifKey(e,t,n,s,o,i,r,a){if(o){i.mode=i.prevMode;a()}else if(e==="j"||n){const e=(i.whatifResult?.scenarios?.length||1)-1;i.whatifScenarioIndex=Math.min(i.whatifScenarioIndex+1,e);a()}else if(e==="k"||t){i.whatifScenarioIndex=Math.max(0,i.whatifScenarioIndex-1);a()}else if(s){a()}}function handleTradeKey(e,t,n,s,o,i,r,a){if(o){i.mode=i.prevMode;i.tradeParams=null;i.tradeCountdown=-1;a();return}if(!i.tradeParams)return;if(e==="\t"){i.tradeField=i.tradeField==="qty"?"price":"qty";a()}else if(t){if(i.tradeField==="qty"){i.tradeParams.qty=Math.min(i.tradeParams.qty+1,9999)}else{i.tradeParams.price=Math.min(i.tradeParams.price+1,99)}a()}else if(n){if(i.tradeField==="qty"){i.tradeParams.qty=Math.max(i.tradeParams.qty-1,1)}else{i.tradeParams.price=Math.max(i.tradeParams.price-1,1)}a()}else if(s){if(i.tradeCountdown<0){i.tradeCountdown=3;a();startCountdown(i,r,a)}}}function startCountdown(e,t,n){const tick=()=>{if(e.tradeCountdown<=0||e.mode!=="trade")return;e.tradeCountdown--;n();if(e.tradeCountdown===0){executeTrade(e,n)}else{setTimeout(tick,1e3)}};setTimeout(tick,1e3)}function openTrade(e,t){let n="";if(e.focusArea==="positions"&&e.positions.length>0){const t=e.positions[e.selectedIndex];n=t?.ticker_symbol||t?.ticker||""}else if(e.focusArea==="edges"&&e.edges.length>0){const t=e.edges[e.selectedIndex];n=t?.ticker||t?.marketId||""}else if(e.detailTicker){n=e.detailTicker}if(!n){e.error="No market selected";return}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"}function openTradeFromLiquidity(e){const t=e.liquidityData.get(e.liquidityTopic)||[];if(t.length===0)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"}async function executeTrade(e,t){if(!e.tradeParams)return;try{const n=(0,c.loadConfig)();if(!n.tradingEnabled){e.error="Trading disabled. Run: sf setup --enable-trading";e.tradeCountdown=-1;t();return}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 loadAllData(e)}catch(t){e.error=t instanceof Error?t.message.slice(0,40):"Trade failed";e.tradeCountdown=-1}t()}async function loadLiquidityData(e){const t=e.liquidityTopic;const n=u.TOPIC_SERIES[t];if(!n)return;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`;const n=await fetch(t,{headers:{Accept:"application/json"}});if(!n.ok)return[];const s=await n.json();return s.markets||[]})))));const o=[];for(const e of s){if(e.status==="fulfilled"&&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);const 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(e.status!=="fulfilled"||!e.value.ob)continue;const{mkt:t,ob:n}=e.value;const s=(n.yes_dollars||[]).map((e=>({price:Math.round(parseFloat(e[0])*100),qty:parseFloat(e[1])}))).filter((e=>e.price>0)).sort(((e,t)=>t.price-e.price));const o=(n.no_dollars||[]).map((e=>({price:Math.round(parseFloat(e[0])*100),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 loadWhatifData(e){const t=getClient();if(!t||!e.whatifThesisId)return;try{const t=e.contexts.get(e.whatifThesisId);if(!t)return;const n=t.causalTree?.nodes||t.nodes||[];const s=n.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:s,before:{confidence:e.theses[0]?.confidence,edges:e.edges.slice(0,5)},after:null}}catch{e.error="Failed to load what-if data"}}async function triggerEvaluate(e){const t=getClient();if(!t||e.theses.length===0)return;try{e.error=null;const n=e.theses[0];await t.evaluate(n.id);(0,a.invalidateAll)();await loadAllData(e)}catch(t){e.error=t instanceof Error?t.message.slice(0,40):"Evaluation failed"}}async function startDashboard(){const e=new s.ScreenBuffer;const t=(0,i.initialState)();process.stdout.write("[?1049h");process.stdout.write("[?25l");if(process.stdin.isTTY){process.stdin.setRawMode(true)}process.stdin.resume();let n=false;const scheduleRender=()=>{if(n)return;n=true;setImmediate((()=>{n=false;renderFrame(e,t)}))};const o=[];let r=false;const cleanup=()=>{if(r)return;r=true;for(const e of o)clearInterval(e);process.stdout.write("[?1049l");process.stdout.write("[?25h");if(process.stdin.isTTY){process.stdin.setRawMode(false)}process.stdin.pause();process.exit(0)};process.on("SIGINT",cleanup);process.on("SIGTERM",cleanup);try{await loadAllData(t)}catch(e){t.error=e instanceof Error?e.message.slice(0,50):"Failed to load data"}renderFrame(e,t);o.push(setInterval((async()=>{try{const e=await(0,a.cached)("positions",C,(()=>(0,d.getPositions)()));if(e){const n=await Promise.allSettled(e.map((e=>(0,a.cached)(`price:${e.ticker}`,1e4,(()=>(0,d.getMarketPrice)(e.ticker))))));for(let t=0;t<e.length;t++){const s=n[t];if(s.status==="fulfilled"&&s.value!=null){e[t].current_value=s.value}}t.positions=e;computeEdges(t)}scheduleRender()}catch{}}),C));o.push(setInterval((async()=>{try{const e=await(0,a.cached)("orders",I,(()=>(0,d.getOrders)({status:"resting"})));if(e){t.orders=e.orders||[]}scheduleRender()}catch{}}),I));o.push(setInterval((async()=>{try{const e=await(0,a.cached)("balance",P,(()=>(0,d.getBalance)()));if(e){t.balance=e.balance??0}scheduleRender()}catch{}}),P));o.push(setInterval((async()=>{try{await loadCandles(t);scheduleRender()}catch{}}),E));process.stdin.on("data",(n=>{handleKeypress(t,n,e,scheduleRender,cleanup)}));process.stdout.on("resize",(()=>{e.resize();scheduleRender()}))}},42992:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.overviewLayout=overviewLayout;t.fullLayout=fullLayout;t.narrowLayout=narrowLayout;function overviewLayout(e,t){const n=t-3;const s=Math.floor(e*.55);const o=e-s-1;const i=s+1;const r=Math.max(Math.floor(n*.4),5);const a=Math.max(Math.floor(n*.3),4);const 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}]}function fullLayout(e,t){return{name:"main",row:2,col:0,width:e,height:t-3}}function narrowLayout(e,t){const n=t-3;const 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:true});t.ScreenBuffer=void 0;class ScreenBuffer{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++){if(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++){if(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++){if(a>=0&&e>=0){this.back[a][e]={char:o,fg:i,bg:r}}}}}flush(){let e="";let t="";let n="";for(let s=0;s<this.rows;s++){for(let o=0;o<this.cols;o++){const i=this.front[s][o];const r=this.back[s][o];if(i.char!==r.char||i.fg!==r.fg||i.bg!==r.bg){e+=`[${s+1};${o+1}H`;if(r.fg!==t||r.bg!==n){e+="[0m";if(r.fg)e+=r.fg;if(r.bg)e+=r.bg;t=r.fg;n=r.bg}e+=r.char}}}if(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")}}t.ScreenBuffer=ScreenBuffer},56661:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.initialState=initialState;function initialState(){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:true});t.renderCommandBar=renderCommandBar;const s=n(77096);const o=(0,s.bgRgb)(12,12,16);const 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"}]};function renderCommandBar(e,t,n){const r=e.cols;e.fill(t,0,r,1," ","",o);const a=i[n.mode]||i.overview;const c=n.mode==="overview"?n.focusArea.toUpperCase():"";let l=1;if(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);const a=r-i.length-2;if(a>l)e.write(t,a,i,s.CLR.red,o)}}},35301:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderDetail=renderDetail;const s=n(77096);const o=n(14916);function renderDetail(e,t,n){(0,s.drawBorder)(e,t,"POSITION DETAIL");const i=t.col+2;const r=t.width-4;const a=n.positions.find((e=>(e.ticker_symbol||e.ticker)===n.detailTicker))||n.positions[0];if(!a){e.write(t.row+2,i,"No position selected",s.CLR.dim);return}const c=a.ticker_symbol||a.ticker||"???";const l=a.quantity??0;const d=a.average_price_paid??a.cost_basis??0;const u=a.current_value??d;const p=(u-d)*l;const h=p/100;const m=p>=0?s.CLR.green:s.CLR.red;const f=a.side||"yes";let g=1;e.writeStyled(t.row+g,i,[{text:(0,s.fit)(c,30),fg:s.CLR.white},{text:` ${f.toUpperCase()} `,fg:s.CLR.emerald},{text:` qty: ${l}`,fg:s.CLR.dim}]);g++;e.writeStyled(t.row+g,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}]);g++;const y=a.expiration_time||a.expiry||a.close_time||"";if(y){const n=new Date(y);const o=Math.ceil((n.getTime()-Date.now())/864e5);e.write(t.row+g,i,`Expiry: ${n.toISOString().slice(0,10)} (${o}d)`,s.CLR.dim)}g++;(0,s.drawHDivider)(e,t,g);g++;const $=Math.min(8,Math.floor((t.height-g-8)/2)+4);const k=n.candleCache.get(c)||[];if(k.length>1){const n=k.map((e=>{const t=e.close??0;return(t-d)*l/100}));const a=k.map((e=>{const t=e.date?new Date(e.date):new Date(e.end_period_ts?e.end_period_ts*1e3:0);return`${t.getMonth()+1}/${t.getDate()}`}));e.write(t.row+g,i,"Daily P&L ($)",s.CLR.title);g++;(0,o.drawChart)(e,t.row+g,i,r,$,n,a);g+=$+1}else{e.write(t.row+g,i,"No chart data available",s.CLR.dim);g+=2}if(g<t.height-5){(0,s.drawHDivider)(e,t,g);g++}const b=Math.floor(r/2)-1;const w=t.row+g;const _=t.height-g-1;e.write(w,i,"Causal Tree",s.CLR.title);let S=null;for(const[,e]of n.contexts){const t=e?.edges||[];if(t.some((e=>e.marketId===c||e.ticker===c))){S=e;break}}const v=S?.causalTree?.nodes||[];const x=[];function walk(e,t=0){for(const n of e){x.push({...n,depth:t});if(n.children)walk(n.children,t+1)}}walk(v);const C=x.filter((e=>e.depth<=1)).slice(0,_-1);for(let t=0;t<C.length;t++){const n=C[t];const o=" ".repeat(n.depth+1);const r=n.label||n.claim||n.name||n.id||"?";const a=n.probability!=null?`${Math.round(n.probability*100)}%`:"";e.writeStyled(w+1+t,i,[{text:o+(0,s.fit)(r,b-o.length-5),fg:s.CLR.text},{text:(0,s.fit)(a,5,"right"),fg:s.CLR.emerald}])}if(C.length===0){e.write(w+1,i," (no context data)",s.CLR.dim)}const O=i+b+2;e.write(w,O,"Orderbook",s.CLR.title);const I=S?.edges?.find((e=>e.marketId===c||e.ticker===c));const P=I?.orderbook;if(P){const t=P.bidPrice??P.bestBid??0;const n=P.askPrice??P.bestAsk??0;const o=P.spread??n-t;e.writeStyled(w+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(w+2,O,[{text:"Spread: ",fg:s.CLR.dim},{text:`${o}¢`,fg:o<=2?s.CLR.green:o<=5?s.CLR.yellow:s.CLR.red}]);if(P.bidDepth!=null){e.writeStyled(w+3,O,[{text:"Depth: ",fg:s.CLR.dim},{text:`bid ${P.bidDepth}`,fg:s.CLR.dim},{text:` / ask ${P.askDepth}`,fg:s.CLR.dim}])}}else{e.write(w+1,O," (no orderbook data)",s.CLR.dim)}}},30012:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderEdges=renderEdges;const s=n(77096);const o="▏▎▍▌▋▊▉█";function renderEdges(e,t,n){(0,s.drawBorder)(e,t,"TOP EDGES");const i=t.col+2;const r=t.width-4;const a=t.height-2;const c=new Set(n.positions.map((e=>e.ticker)));const l=n.edges.filter((e=>!c.has(e.marketId||e.ticker||"")));const d=l.slice(0,Math.min(a,8));if(d.length===0){e.write(t.row+1,i,"No unpositioned edges",s.CLR.dim);return}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];const l=t.row+1+a;const p=n.focusArea==="edges"&&n.selectedIndex===a;const h=p?"▸":" ";const m=c.market||c.marketTitle||c.marketId||"???";const f=c.edge??c.edgeSize??0;const g=`${f>0?"+":""}${f.toFixed(0)}¢`;const y=`${c.marketPrice??"?"}¢`;const $=c.venue==="polymarket"?"P":"K";const k=c.orderbook?.liquidityScore||"";const b=k==="high"?"H":k==="medium"?"M":k==="low"?"L":"";const w=k==="high"?s.CLR.green:k==="low"?s.CLR.yellow:s.CLR.dim;const _=6;const S=Math.abs(f)/u;const v=Math.floor(S*_);const x=S*_-v;const C=Math.min(Math.floor(x*8),7);const O=o[7].repeat(v)+(x>.1?o[C]:"");const I=f>0?s.CLR.emerald:s.CLR.red;const 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)(O,_),fg:I},{text:(0,s.fit)(g,5,"right"),fg:s.CLR.emerald},{text:b?` ${b}`:"",fg:w}])}}},87009:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderIntents=renderIntents;const s=n(77096);const 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};function renderIntents(e,t,n){(0,s.drawBorder)(e,t,"INTENTS");const i=t.col+2;const r=t.width-4;const a=t.height-2;const c=n.intents||[];if(c.length===0){e.write(t.row+1,i,"No active intents",s.CLR.dim,s.CLR.bgPanel);e.write(t.row+2,i,"Press i on an edge to create one",s.CLR.veryDim,s.CLR.bgPanel);return}for(let l=0;l<Math.min(c.length,a);l++){const a=c[l];const d=t.row+1+l;const u=n.focusArea==="intents"&&n.selectedIndex===l;const p=u?s.CLR.bgSelected:s.CLR.bgPanel;if(u)e.fill(d,t.col+1,t.width-2,1," ","",p);const h=a.status||"pending";const m=o[h]||s.CLR.dim;const f=(a.action||"buy").toUpperCase();const g=(a.direction||"yes").toUpperCase();const y=(a.marketId||a.market_id||"???").slice(0,16);const $=a.targetQuantity||a.target_quantity||0;const k=a.filledQuantity||a.filled_quantity||0;const b=a.maxPrice||a.max_price;const w=b?`≤${b}¢`:"mkt";const _=k>0?`${k}/${$}`:`${$}`;const S=Math.max(r-26,6);e.writeStyled(d,i,[{text:(0,s.fit)(h,9),fg:m,bg:p},{text:` ${f} `,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:` ${g} ${_} ${w}`,fg:s.CLR.dim,bg:p}])}}},82950:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderLiquidity=renderLiquidity;const s=n(77096);const o=n(97325);const i=(0,s.bgRgb)(30,30,35);const r=(0,s.bgRgb)(16,16,18);function renderLiquidity(e,t,n){(0,s.drawBorder)(e,t,"LIQUIDITY SCANNER");const a=t.col+2;const 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;const c=` ${o.toUpperCase()} `;const d=a?s.CLR.emerald:s.CLR.dim;const 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(c*.35));const h=8;e.writeStyled(t.row+l,a,[{text:(0,s.fit)("Market",p),fg:s.CLR.title},{text:(0,s.fit)("Bid¢",h,"right"),fg:s.CLR.title},{text:(0,s.fit)("Ask¢",h,"right"),fg:s.CLR.title},{text:(0,s.fit)("Spread",h,"right"),fg:s.CLR.title},{text:(0,s.fit)("Depth",h,"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 m=n.liquidityData.get(n.liquidityTopic)||[];const f=new Set(n.positions.map((e=>e.ticker_symbol||e.ticker)));const g=t.height-l-3;const y=groupByHorizon(m);let $=0;for(const[o,i]of y){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===$;const r=i?"▸":" ";const c=f.has(o.ticker)?"← held":"";const d=o.ticker||"???";const u=o.bestBid??o.yes_bid??0;const m=o.bestAsk??o.yes_ask??0;const g=o.spread??m-u;const y=o.totalDepth??o.depth??0;const k=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),h,"right"),fg:s.CLR.green},{text:(0,s.fit)(String(m),h,"right"),fg:s.CLR.red},{text:(0,s.fit)(String(g),h,"right"),fg:k},{text:(0,s.fit)(String(y),h,"right"),fg:s.CLR.dim},{text:c?` ${c}`:"",fg:s.CLR.emerald}]);l++;$++}}if(m.length>0){const o=Math.min(n.liquiditySelectedIndex,m.length-1);const i=Array.from(y.values()).flat();const 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=r.slippage!=null?`Slippage: ~${r.slippage}¢`:"";const i=r.edge!=null?`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}])}}}function groupByHorizon(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);if(t<=7)s="Weekly";else if(t<=35)s="Monthly";else s="Long-term"}}if(!t.has(s))t.set(s,[]);t.get(s).push(n)}const n=["Daily","Weekly","Monthly","Long-term","Other"];const s=new Map;for(const e of n){if(t.has(e))s.set(e,t.get(e))}return s}},12423:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderMarketBar=renderMarketBar;const s=n(77096);const o=(0,s.bgRgb)(12,12,16);function renderMarketBar(e,t,n){const i=e.cols;e.fill(t,0,i,1," ","",o);const r=n.traditionalMarkets||[];if(r.length===0){e.write(t,1,"SimpleFunctions",s.CLR.dim,o);return}const a=r.slice(0,6);const c=Math.floor((i-2)/a.length);for(let n=0;n<a.length;n++){const i=a[n];const r=1+n*c;const l=(i.symbol||i.name||"???").replace("SPDR ","").replace(" ETF","").slice(0,5);const d=i.changePct??i.change_pct??i.pctChange??0;const u=i.price??i.value??0;const p=u>100?Math.round(u).toLocaleString():u.toFixed(2);const h=d>=0?"+":"";const m=`${h}${d.toFixed(1)}%`;const f=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,m,f,o)}}},75757:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderOrders=renderOrders;const s=n(77096);function renderOrders(e,t,n){(0,s.drawBorder)(e,t,"ORDERS");const o=t.col+2;const i=t.width-4;const r=t.height-2;if(n.orders.length===0){e.write(t.row+1,o,"No resting orders",s.CLR.dim);return}for(let i=0;i<Math.min(n.orders.length,r);i++){const r=n.orders[i];const a=t.row+1+i;const c=(r.ticker||"???").slice(0,10);const l=Math.round(parseFloat(r.remaining_count_fp||r.initial_count_fp||"0"));const d=parseFloat(r.yes_price_dollars||"0");const u=Math.round(d*100);const p=r.status||"resting";const h=`${l}@${u}¢`;const m=new Date(r.created_time||Date.now()).getTime();const f=Math.floor((Date.now()-m)/864e5);const g=f===0?"<1d":`${f}d`;const y=f>3;const $=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:p==="filled"?s.CLR.green:s.CLR.dim},{text:(0,s.fit)(g,4,"right"),fg:y?s.CLR.yellow:s.CLR.dim}])}}},3322:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderPortfolio=renderPortfolio;const s=n(77096);function renderPortfolio(e,t,n){(0,s.drawBorder)(e,t,"POSITIONS");const o=t.col+2;const i=t.width-4;const r=t.height-2;let a=0;if(n.positions.length===0){e.write(t.row+1,o,"No positions",s.CLR.dim,s.CLR.bgPanel);e.write(t.row+2,o,"sf buy TICKER QTY --price CENTS",s.CLR.veryDim,s.CLR.bgPanel);return}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));const s=Math.abs(((t.current_value||t.average_price_paid||0)-(t.average_price_paid||0))*(t.quantity||0));return s-n}));for(const l of c){if(a+1>=r)break;const d=t.row+1+a;const u=c.indexOf(l);const p=n.focusArea==="positions"&&n.selectedIndex===u;const h=p?s.CLR.bgSelected:s.CLR.bgPanel;if(p){e.fill(d,t.col+1,t.width-2,2," ","",h)}const m=l.ticker||"???";const f=l.venue==="polymarket"?"P":"K";const g=l.venue==="polymarket"?s.CLR.purple:s.CLR.cyan;e.writeStyled(d,o,[{text:f+" ",fg:g,bg:h},{text:(0,s.fit)(m,Math.min(i-2,28)),fg:p?s.CLR.white:s.CLR.text,bg:h}]);if(a+1<r){const t=l.quantity??0;const i=l.average_price_paid??0;const r=l.current_value??i;const a=(r-i)*t;const c=a/100;const u=(c>=0?"+$":"-$")+Math.abs(c).toFixed(2);const p=c>=0?s.CLR.green:s.CLR.red;const f=[{text:` ${(0,s.compact)(t)} @ ${i}¢`,fg:s.CLR.dim,bg:h},{text:` → ${r}¢ `,fg:s.CLR.dim,bg:h},{text:(0,s.fit)(u,9),fg:p,bg:h}];const g=n.candleCache.get(m);if(g&&g.length>1){const e=g.slice(-7).map((e=>{const n=e.close??0;return(n-i)*t}));const n=(0,s.sparkline)(e,(e=>e>=0?s.CLR.green:s.CLR.red));for(const e of n)f.push({...e,bg:h})}e.writeStyled(d+1,o,f)}a+=2}}},50511:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderSignals=renderSignals;const s=n(77096);function renderSignals(e,t,n){(0,s.drawBorder)(e,t,"FEED");const o=t.col+2;const i=t.width-4;const r=t.height-2;const a=n.signals.sort(((e,t)=>{const n=new Date(e.evaluatedAt||e.timestamp||e.time||0).getTime();const s=new Date(t.evaluatedAt||t.timestamp||t.time||0).getTime();return s-n}));if(a.length===0){e.write(t.row+1,o,"No recent signals",s.CLR.dim);return}for(let n=0;n<Math.min(a.length,r);n++){const r=a[n];const c=t.row+1+n;const l=r.confidenceDelta??r.delta??r.change??0;const d=r.summary||r.title||r.content||"???";const 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=typeof l==="number"?l>=0:true;const m=typeof l==="number"&&Math.abs(l)>=.001;const f=m?h?"▲":"▼":" ";const g=h?s.CLR.green:s.CLR.red;const y=m?`${l>0?"+":""}${Math.round(l*100)}%`:"";const $=i-14;e.writeStyled(c,o,[{text:p,fg:s.CLR.veryDim},{text:` ${f}`,fg:m?g:s.CLR.dim},{text:(0,s.fit)(y,5,"right"),fg:m?g:s.CLR.dim},{text:" "+(0,s.fit)(d,$),fg:s.CLR.text}])}}},98573:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderStatusBar=renderStatusBar;const s=n(77096);const o=(0,s.bgRgb)(16,16,20);const i="│";function renderStatusBar(e,t,n){const r=e.cols;e.fill(t,0,r,1," ","",o);let a=0;let c=0;for(const e of n.positions){const t=e.average_price_paid??e.cost_basis??0;const n=e.current_value??t;const s=e.quantity??0;a+=(n-t)*s;c+=t*s}const l=a/100;const d=c>0?a/c*100:0;const u=l>=0?s.CLR.green:s.CLR.red;let p=1;const h=l>=0?"+":"";const m=`${h}$${Math.abs(l).toFixed(2)}`;const f=`${h}${d.toFixed(1)}%`;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,f,u,o);p+=f.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;if(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];const a=(r.title||"Thesis").slice(0,18);const c=r.confidence!=null?`${Math.round((r.confidence??0)*100)}%`:"?%";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;if(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 g=(n.intents||[]).filter((e=>["pending","armed","triggered","executing"].includes(e.status)));if(g.length>0){e.write(t,p,i,s.CLR.veryDim,o);p+=2;const n=`${g.length} intent${g.length>1?"s":""}`;e.write(t,p,n,s.CLR.emerald,o);p+=n.length+1}if(n.exchangeOpen!==null){e.write(t,p,i,s.CLR.veryDim,o);p+=2;const r=n.exchangeOpen?"OPEN":"CLOSED";const a=n.exchangeOpen?s.CLR.green:s.CLR.red;e.write(t,p,r,a,o)}const y=new Date;const $=y.toISOString().slice(11,19)+" UTC";e.write(t,r-$.length-1,$,s.CLR.veryDim,o)}},21704:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderThesis=renderThesis;const s=n(77096);function renderThesis(e,t,n){(0,s.drawBorder)(e,t,"THESIS");const o=t.col+2;const i=t.width-4;const r=t.height-2;let a=0;for(const c of n.theses){if(a>=r-2)break;const n=t.row+1+a;const l=c.title||c.short_title||"???";const d=c.confidence??c.current_confidence??0;const u=`${Math.round(d*100)}%`;const p=c.lastEvaluation?.confidenceDelta??c.confidence_delta??0;let h,m,f;if(p>=.02){h="▲";m=s.CLR.green;f=`+${Math.round(p*100)}`}else if(p<=-.02){h="▼";m=s.CLR.red;f=`${Math.round(p*100)}`}else{h="─";m=s.CLR.dim;f=p>=0?`+${Math.round(p*100)}`:`${Math.round(p*100)}`}const g=i-10;e.writeStyled(n,o,[{text:(0,s.fit)(l,g),fg:s.CLR.text},{text:(0,s.fit)(u,5,"right"),fg:s.CLR.white},{text:` ${h}`,fg:m},{text:(0,s.fit)(f,3,"right"),fg:m}]);a++}if(n.theses.length>0&&a<r){const a=n.theses[0];const c=n.contexts.get(a.id||a.thesis_id);const l=c?.lastEvaluation?.summary||a.lastEvaluation?.summary||"";if(l){const n=t.row+1+r-1;const 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}])}}}},67748:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderTrade=renderTrade;const s=n(77096);const o=(0,s.bgRgb)(18,18,22);const i=(0,s.bgRgb)(30,30,35);const r=(0,s.bgRgb)(16,50,40);function renderTrade(e,t,n){if(!n.tradeParams)return;const a=n.tradeParams;const c=Math.min(50,t.width-4);const l=Math.min(18,t.height-2);const d=t.col+Math.floor((t.width-c)/2);const u=t.row+Math.floor((t.height-l)/2);const 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;const m=c-4;let f=1;const g=a.action==="buy"?s.CLR.green:s.CLR.red;const y=a.action==="buy"?"BUY":"SELL";e.writeStyled(u+f,h,[{text:y+" ",fg:g},{text:a.side.toUpperCase()+" ",fg:s.CLR.emerald},{text:a.ticker,fg:s.CLR.white}]);f+=2;const $=n.positions.find((e=>(e.ticker_symbol||e.ticker)===a.ticker));const k=$?.bestBid??$?.current_value??0;const b=$?.bestAsk??k+2;e.writeStyled(u+f,h,[{text:"Bid: ",fg:s.CLR.dim},{text:`${k}¢`,fg:s.CLR.green},{text:" Ask: ",fg:s.CLR.dim},{text:`${b}¢`,fg:s.CLR.red}]);f+=2;const w=n.tradeField==="qty";const _=w?r:i;e.write(u+f,h,"Quantity:",s.CLR.dim,o);e.write(u+f,h+12,(0,s.fit)(String(a.qty),10),w?s.CLR.emerald:s.CLR.text,_);if(w)e.write(u+f,h+22," ◀",s.CLR.emerald,o);f++;const S=n.tradeField==="price";const v=S?r:i;e.write(u+f,h,"Price (¢):",s.CLR.dim,o);e.write(u+f,h+12,(0,s.fit)(String(a.price),10),S?s.CLR.emerald:s.CLR.text,v);if(S)e.write(u+f,h+22," ◀",s.CLR.emerald,o);f+=2;const x=a.qty*a.price/100;const C=a.qty;const O=C-x;e.write(u+f,h,"Preview:",s.CLR.title,o);f++;e.writeStyled(u+f,h,[{text:`Max cost: $${x.toFixed(2)}`,fg:s.CLR.dim}]);f++;e.writeStyled(u+f,h,[{text:`Max payout: $${C.toFixed(2)}`,fg:s.CLR.dim}]);f++;e.writeStyled(u+f,h,[{text:"Profit: ",fg:s.CLR.dim},{text:`$${O.toFixed(2)}`,fg:O>=0?s.CLR.green:s.CLR.red}]);f++;const I=n.edges.find((e=>(e.ticker||e.marketId)===a.ticker));if(I){const t=I.edge??I.value??0;e.writeStyled(u+f,h,[{text:"Edge: ",fg:s.CLR.dim},{text:`${t>=0?"+":""}${t}¢`,fg:t>=0?s.CLR.green:s.CLR.red}]);f++}const P=Math.max(0,a.price-k);if(P>0){e.writeStyled(u+f,h,[{text:"Slippage: ",fg:s.CLR.dim},{text:`~${P}¢`,fg:s.CLR.yellow}]);f++}f++;if(n.tradeCountdown>0){const t=` Executing in ${n.tradeCountdown}... `;const i=h+Math.floor((m-t.length)/2);e.write(u+f,i,t,s.CLR.yellow,o)}else if(n.tradeCountdown===0){e.write(u+f,h+Math.floor((m-12)/2)," EXECUTING ",s.CLR.white,(0,s.bgRgb)(16,120,80))}else{e.write(u+f,h+Math.floor((m-24)/2),"Press Enter to confirm",s.CLR.dim,o)}}},29405:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.renderWhatif=renderWhatif;const s=n(77096);const o=(0,s.bgRgb)(25,25,30);function renderWhatif(e,t,n){(0,s.drawBorder)(e,t,"WHAT-IF SCENARIO");const i=t.col+2;const r=t.width-4;let a=1;if(!n.whatifResult){e.write(t.row+a,i,'No what-if data. Press "w" from overview to start.',s.CLR.dim);return}const c=n.whatifResult;const l=c.scenarios||c.overrides||[];const d=Math.floor(r/2)-2;e.write(t.row+a,i,"Scenarios:",s.CLR.title);a++;if(l.length===0){e.write(t.row+a,i," (no scenarios available)",s.CLR.dim);a+=2}else{for(let c=0;c<l.length;c++){if(a>=t.height-8)break;const d=l[c];const u=n.whatifScenarioIndex===c;const p=u?"▸ ":" ";const h=d.name||d.description||d.nodeId||`Scenario ${c+1}`;const 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;const 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||{};const m=c.after||c.proposed||{};const f=h.confidence!=null?`${Math.round(h.confidence*100)}%`:"?%";const g=m.confidence!=null?`${Math.round(m.confidence*100)}%`:"?%";const y=(m.confidence??0)-(h.confidence??0);const $=y>=0?`+${Math.round(y*100)}%`:`${Math.round(y*100)}%`;e.writeStyled(t.row+a,u,[{text:"Confidence: ",fg:s.CLR.dim},{text:f,fg:s.CLR.text}]);e.writeStyled(t.row+a,p,[{text:"Confidence: ",fg:s.CLR.dim},{text:g,fg:s.CLR.text},{text:` (${$})`,fg:y>=0?s.CLR.green:s.CLR.red}]);a++;const k=h.edges||[];const b=m.edges||[];e.write(t.row+a,u,"Edges:",s.CLR.dim);e.write(t.row+a,p,"Edges:",s.CLR.dim);a++;const w=Math.min(Math.max(k.length,b.length),t.height-a-3);for(let n=0;n<w;n++){const o=k[n];const i=b[n];if(o){const n=(o.market||o.ticker||"").slice(0,d-10);const 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);const r=`${i.edge>=0?"+":""}${i.edge}`;const c=i.edgeDelta??i.edge-(o?.edge??0);const 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;if(n!=null){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}])}}}},99236:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.c=void 0;t.vol=vol;t.cents=cents;t.pct=pct;t.delta=delta;t.shortDate=shortDate;t.pad=pad;t.rpad=rpad;t.hr=hr;t.die=die;t.errorWithHint=errorWithHint;t.emptyState=emptyState;t.header=header;t.trunc=trunc;t.shortId=shortId;t.c={reset:"[0m",bold:"[1m",dim:"[2m",red:"[31m",green:"[32m",yellow:"[33m",blue:"[34m",magenta:"[35m",cyan:"[36m",white:"[37m",gray:"[90m"};function vol(e){if(e===null||e===undefined)return"-";const t=typeof e==="string"?parseFloat(e):e;if(isNaN(t))return"-";if(t>=1e6)return`${(t/1e6).toFixed(1)}M`;if(t>=1e3)return`${(t/1e3).toFixed(0)}K`;return t.toString()}function cents(e){if(e===null||e===undefined)return"-";const t=typeof e==="string"?parseFloat(e):e;if(isNaN(t))return"-";return`${Math.round(t*100)}¢`}function pct(e){if(e===null||e===undefined)return"-";const t=typeof e==="string"?parseFloat(e):e;if(isNaN(t))return"-";return`${Math.round(t*100)}%`}function delta(e){const t=e>0?"↑":e<0?"↓":"→";const n=e>0?"+":"";return`${t} ${n}${Math.round(e*100)}%`}function shortDate(e){if(!e)return"-";try{const t=new Date(e);const n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];const s=n[t.getMonth()];const o=t.getDate();const i=t.getHours().toString().padStart(2,"0");const r=t.getMinutes().toString().padStart(2,"0");return`${s} ${o} ${i}:${r}`}catch{return e.slice(0,16)}}function pad(e,t){if(e.length>=t)return e.slice(0,t);return e+" ".repeat(t-e.length)}function rpad(e,t){if(e.length>=t)return e.slice(0,t);return" ".repeat(t-e.length)+e}function hr(e=80){console.log(t.c.dim+"─".repeat(e)+t.c.reset)}function die(e){console.error(`${t.c.red}Error:${t.c.reset} ${e}`);process.exit(1)}function errorWithHint(e,n){console.error(`\n ${t.c.red}Error:${t.c.reset} ${e}`);if(n)console.error(` ${t.c.dim}${n}${t.c.reset}`);console.error()}function emptyState(e,n){console.log(`\n ${t.c.dim}No ${e} found.${t.c.reset}`);if(n)console.log(` ${t.c.dim}${n}${t.c.reset}`);console.log()}function header(e){console.log(`\n${t.c.bold}${t.c.cyan}${e}${t.c.reset}`)}function trunc(e,t){if(e.length<=t)return e;return e.slice(0,t-1)+"…"}function shortId(e){return e.slice(0,8)}},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);const{Command:o}=n(34348);const{CommanderError:i,InvalidArgumentError:r}=n(41135);const{Help:a}=n(79754);const{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);class Argument{constructor(e,t){this.description=t||"";this.variadic=false;this.parseArg=undefined;this.defaultValue=undefined;this.defaultValueDescription=undefined;this.argChoices=undefined;switch(e[0]){case"<":this.required=true;this._name=e.slice(1,-1);break;case"[":this.required=false;this._name=e.slice(1,-1);break;default:this.required=true;this._name=e;break}if(this._name.length>3&&this._name.slice(-3)==="..."){this.variadic=true;this._name=this._name.slice(0,-3)}}name(){return this._name}_concatValue(e,t){if(t===this.defaultValue||!Array.isArray(t)){return[e]}return t.concat(e)}default(e,t){this.defaultValue=e;this.defaultValueDescription=t;return this}argParser(e){this.parseArg=e;return this}choices(e){this.argChoices=e.slice();this.parseArg=(e,t)=>{if(!this.argChoices.includes(e)){throw new s(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(e,t)}return e};return this}argRequired(){this.required=true;return this}argOptional(){this.required=false;return this}}function humanReadableArgName(e){const t=e.name()+(e.variadic===true?"...":"");return e.required?"<"+t+">":"["+t+"]"}t.Argument=Argument;t.humanReadableArgName=humanReadableArgName},34348:(e,t,n)=>{const s=n(78474).EventEmitter;const o=n(31421);const i=n(76760);const r=n(73024);const a=n(1708);const{Argument:c,humanReadableArgName:l}=n(49154);const{CommanderError:d}=n(41135);const{Help:u}=n(79754);const{Option:p,DualOptions:h}=n(45240);const{suggestSimilar:m}=n(65030);class Command extends s{constructor(e){super();this.commands=[];this.options=[];this.parent=null;this._allowUnknownOption=false;this._allowExcessArguments=true;this.registeredArguments=[];this._args=this.registeredArguments;this.args=[];this.rawArgs=[];this.processedArgs=[];this._scriptPath=null;this._name=e||"";this._optionValues={};this._optionValueSources={};this._storeOptionsAsProperties=false;this._actionHandler=null;this._executableHandler=false;this._executableFile=null;this._executableDir=null;this._defaultCommandName=null;this._exitCallback=null;this._aliases=[];this._combineFlagAndOptionalValue=true;this._description="";this._summary="";this._argsDescription=undefined;this._enablePositionalOptions=false;this._passThroughOptions=false;this._lifeCycleHooks={};this._showHelpAfterError=false;this._showSuggestionAfterError=true;this._outputConfiguration={writeOut:e=>a.stdout.write(e),writeErr:e=>a.stderr.write(e),getOutHelpWidth:()=>a.stdout.isTTY?a.stdout.columns:undefined,getErrHelpWidth:()=>a.stderr.isTTY?a.stderr.columns:undefined,outputError:(e,t)=>t(e)};this._hidden=false;this._helpOption=undefined;this._addImplicitHelpCommand=undefined;this._helpCommand=undefined;this._helpConfiguration={}}copyInheritedSettings(e){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;return this}_getCommandAndAncestors(){const e=[];for(let t=this;t;t=t.parent){e.push(t)}return e}command(e,t,n){let s=t;let o=n;if(typeof s==="object"&&s!==null){o=s;s=null}o=o||{};const[,i,r]=e.match(/([^ ]+) *(.*)/);const a=this.createCommand(i);if(s){a.description(s);a._executableHandler=true}if(o.isDefault)this._defaultCommandName=a._name;a._hidden=!!(o.noHelp||o.hidden);a._executableFile=o.executableFile||null;if(r)a.arguments(r);this._registerCommand(a);a.parent=this;a.copyInheritedSettings(this);if(s)return this;return a}createCommand(e){return new Command(e)}createHelp(){return Object.assign(new u,this.configureHelp())}configureHelp(e){if(e===undefined)return this._helpConfiguration;this._helpConfiguration=e;return this}configureOutput(e){if(e===undefined)return this._outputConfiguration;Object.assign(this._outputConfiguration,e);return this}showHelpAfterError(e=true){if(typeof e!=="string")e=!!e;this._showHelpAfterError=e;return this}showSuggestionAfterError(e=true){this._showSuggestionAfterError=!!e;return 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()`)}t=t||{};if(t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=true;this._registerCommand(e);e.parent=this;e._checkForBrokenPassThrough();return this}createArgument(e,t){return new c(e,t)}argument(e,t,n,s){const o=this.createArgument(e,t);if(typeof n==="function"){o.default(s).argParser(n)}else{o.default(n)}this.addArgument(o);return this}arguments(e){e.trim().split(/ +/).forEach((e=>{this.argument(e)}));return 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&&e.defaultValue!==undefined&&e.parseArg===undefined){throw new Error(`a default value for a required argument is never used: '${e.name()}'`)}this.registeredArguments.push(e);return this}helpCommand(e,t){if(typeof e==="boolean"){this._addImplicitHelpCommand=e;return this}e=e??"help [command]";const[,n,s]=e.match(/([^ ]+) *(.*)/);const o=t??"display help for command";const i=this.createCommand(n);i.helpOption(false);if(s)i.arguments(s);if(o)i.description(o);this._addImplicitHelpCommand=true;this._helpCommand=i;return this}addHelpCommand(e,t){if(typeof e!=="object"){this.helpCommand(e,t);return this}this._addImplicitHelpCommand=true;this._helpCommand=e;return this}_getHelpCommand(){const e=this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"));if(e){if(this._helpCommand===undefined){this.helpCommand(undefined,undefined)}return this._helpCommand}return 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("', '")}'`)}if(this._lifeCycleHooks[e]){this._lifeCycleHooks[e].push(t)}else{this._lifeCycleHooks[e]=[t]}return this}exitOverride(e){if(e){this._exitCallback=e}else{this._exitCallback=e=>{if(e.code!=="commander.executeSubCommandAsync"){throw e}else{}}}return this}_exit(e,t,n){if(this._exitCallback){this._exitCallback(new d(e,t,n))}a.exit(e)}action(e){const listener=t=>{const n=this.registeredArguments.length;const s=t.slice(0,n);if(this._storeOptionsAsProperties){s[n]=this}else{s[n]=this.opts()}s.push(this);return e.apply(this,s)};this._actionHandler=listener;return this}createOption(e,t){return new p(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(e){if(e.code==="commander.invalidArgument"){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 knownBy=e=>[e.name()].concat(e.aliases());const t=knownBy(e).find((e=>this._findCommand(e)));if(t){const n=knownBy(this._findCommand(t)).join("|");const s=knownBy(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);const t=e.name();const n=e.attributeName();if(e.negate){const t=e.long.replace(/^--no-/,"--");if(!this._findOption(t)){this.setOptionValueWithSource(n,e.defaultValue===undefined?true:e.defaultValue,"default")}}else if(e.defaultValue!==undefined){this.setOptionValueWithSource(n,e.defaultValue,"default")}const handleOptionValue=(t,s,o)=>{if(t==null&&e.presetArg!==undefined){t=e.presetArg}const i=this.getOptionValue(n);if(t!==null&&e.parseArg){t=this._callParseArg(e,t,i,s)}else if(t!==null&&e.variadic){t=e._concatValue(t,i)}if(t==null){if(e.negate){t=false}else if(e.isBoolean()||e.optional){t=true}else{t=""}}this.setOptionValueWithSource(n,t,o)};this.on("option:"+t,(t=>{const n=`error: option '${e.flags}' argument '${t}' is invalid.`;handleOptionValue(t,n,"cli")}));if(e.envVar){this.on("optionEnv:"+t,(t=>{const n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;handleOptionValue(t,n,"env")}))}return this}_optionEx(e,t,n,s,o){if(typeof t==="object"&&t instanceof p){throw new Error("To add an Option object use addOption() instead of option() or requiredOption()")}const i=this.createOption(t,n);i.makeOptionMandatory(!!e.mandatory);if(typeof s==="function"){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:true},e,t,n,s)}combineFlagAndOptionalValue(e=true){this._combineFlagAndOptionalValue=!!e;return this}allowUnknownOption(e=true){this._allowUnknownOption=!!e;return this}allowExcessArguments(e=true){this._allowExcessArguments=!!e;return this}enablePositionalOptions(e=true){this._enablePositionalOptions=!!e;return this}passThroughOptions(e=true){this._passThroughOptions=!!e;this._checkForBrokenPassThrough();return 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=true){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")}this._storeOptionsAsProperties=!!e;return this}getOptionValue(e){if(this._storeOptionsAsProperties){return this[e]}return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,undefined)}setOptionValueWithSource(e,t,n){if(this._storeOptionsAsProperties){this[e]=t}else{this._optionValues[e]=t}this._optionValueSources[e]=n;return this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;this._getCommandAndAncestors().forEach((n=>{if(n.getOptionValueSource(e)!==undefined){t=n.getOptionValueSource(e)}}));return t}_prepareUserArgs(e,t){if(e!==undefined&&!Array.isArray(e)){throw new Error("first parameter to parse must be array or undefined")}t=t||{};if(e===undefined&&t.from===undefined){if(a.versions?.electron){t.from="electron"}const e=a.execArgv??[];if(e.includes("-e")||e.includes("--eval")||e.includes("-p")||e.includes("--print")){t.from="eval"}}if(e===undefined){e=a.argv}this.rawArgs=e.slice();let n;switch(t.from){case undefined:case"node":this._scriptPath=e[1];n=e.slice(2);break;case"electron":if(a.defaultApp){this._scriptPath=e[1];n=e.slice(2)}else{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}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);this._name=this._name||"program";return n}parse(e,t){const n=this._prepareUserArgs(e,t);this._parseCommand([],n);return this}async parseAsync(e,t){const n=this._prepareUserArgs(e,t);await this._parseCommand([],n);return this}_executeSubCommand(e,t){t=t.slice();let n=false;const s=[".js",".ts",".tsx",".mjs",".cjs"];function findFile(e,t){const n=i.resolve(e,t);if(r.existsSync(n))return n;if(s.includes(i.extname(t)))return undefined;const o=s.find((e=>r.existsSync(`${n}${e}`)));if(o)return`${n}${o}`;return undefined}this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();let c=e._executableFile||`${this._name}-${e._name}`;let l=this._executableDir||"";if(this._scriptPath){let e;try{e=r.realpathSync(this._scriptPath)}catch(t){e=this._scriptPath}l=i.resolve(i.dirname(e),l)}if(l){let t=findFile(l,c);if(!t&&!e._executableFile&&this._scriptPath){const n=i.basename(this._scriptPath,i.extname(this._scriptPath));if(n!==this._name){t=findFile(l,`${n}-${e._name}`)}}c=t||c}n=s.includes(i.extname(c));let u;if(a.platform!=="win32"){if(n){t.unshift(c);t=incrementNodeInspectorPort(a.execArgv).concat(t);u=o.spawn(a.argv[0],t,{stdio:"inherit"})}else{u=o.spawn(c,t,{stdio:"inherit"})}}else{t.unshift(c);t=incrementNodeInspectorPort(a.execArgv).concat(t);u=o.spawn(a.execPath,t,{stdio:"inherit"})}if(!u.killed){const e=["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"];e.forEach((e=>{a.on(e,(()=>{if(u.killed===false&&u.exitCode===null){u.kill(e)}}))}))}const p=this._exitCallback;u.on("close",(e=>{e=e??1;if(!p){a.exit(e)}else{p(new d(e,"commander.executeSubCommandAsync","(close)"))}}));u.on("error",(t=>{if(t.code==="ENOENT"){const t=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory";const n=`'${c}' 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)}else if(t.code==="EACCES"){throw new Error(`'${c}' not executable`)}if(!p){a.exit(1)}else{const e=new d(1,"commander.executeSubCommandAsync","(error)");e.nestedError=t;p(e)}}));this.runningCommand=u}_dispatchSubcommand(e,t,n){const s=this._findCommand(e);if(!s)this.help({error:true});let o;o=this._chainOrCallSubCommandHook(o,s,"preSubcommand");o=this._chainOrCall(o,(()=>{if(s._executableHandler){this._executeSubCommand(s,t.concat(n))}else{return s._parseCommand(t,n)}}));return o}_dispatchHelpCommand(e){if(!e){this.help()}const t=this._findCommand(e);if(t&&!t._executableHandler){t.help()}return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach(((e,t)=>{if(e.required&&this.args[t]==null){this.missingArgument(e.name())}}));if(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic){return}if(this.args.length>this.registeredArguments.length){this._excessArguments(this.args)}}_processArguments(){const myParseArg=(e,t,n)=>{let s=t;if(t!==null&&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 e=[];this.registeredArguments.forEach(((t,n)=>{let s=t.defaultValue;if(t.variadic){if(n<this.args.length){s=this.args.slice(n);if(t.parseArg){s=s.reduce(((e,n)=>myParseArg(t,n,e)),t.defaultValue)}}else if(s===undefined){s=[]}}else if(n<this.args.length){s=this.args[n];if(t.parseArg){s=myParseArg(t,s,t.defaultValue)}}e[n]=s}));this.processedArgs=e}_chainOrCall(e,t){if(e&&e.then&&typeof e.then==="function"){return e.then((()=>t()))}return t()}_chainOrCallHooks(e,t){let n=e;const s=[];this._getCommandAndAncestors().reverse().filter((e=>e._lifeCycleHooks[t]!==undefined)).forEach((e=>{e._lifeCycleHooks[t].forEach((t=>{s.push({hookedCommand:e,callback:t})}))}));if(t==="postAction"){s.reverse()}s.forEach((e=>{n=this._chainOrCall(n,(()=>e.callback(e.hookedCommand,this)))}));return n}_chainOrCallSubCommandHook(e,t,n){let s=e;if(this._lifeCycleHooks[n]!==undefined){this._lifeCycleHooks[n].forEach((e=>{s=this._chainOrCall(s,(()=>e(this,t)))}))}return s}_parseCommand(e,t){const n=this.parseOptions(t);this._parseOptionsEnv();this._parseOptionsImplied();e=e.concat(n.operands);t=n.unknown;this.args=e.concat(t);if(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){this._outputHelpIfRequested(t);return this._dispatchSubcommand(this._defaultCommandName,e,t)}if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName){this.help({error:true})}this._outputHelpIfRequested(n.unknown);this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();const checkForUnknownOptions=()=>{if(n.unknown.length>0){this.unknownOption(n.unknown[0])}};const s=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions();this._processArguments();let n;n=this._chainOrCallHooks(n,"preAction");n=this._chainOrCall(n,(()=>this._actionHandler(this.processedArgs)));if(this.parent){n=this._chainOrCall(n,(()=>{this.parent.emit(s,e,t)}))}n=this._chainOrCallHooks(n,"postAction");return n}if(this.parent&&this.parent.listenerCount(s)){checkForUnknownOptions();this._processArguments();this.parent.emit(s,e,t)}else if(e.length){if(this._findCommand("*")){return this._dispatchSubcommand("*",e,t)}if(this.listenerCount("command:*")){this.emit("command:*",e,t)}else if(this.commands.length){this.unknownCommand()}else{checkForUnknownOptions();this._processArguments()}}else if(this.commands.length){checkForUnknownOptions();this.help({error:true})}else{checkForUnknownOptions();this._processArguments()}}_findCommand(e){if(!e)return undefined;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=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===undefined){e.missingMandatoryOptionValue(t)}}))}))}_checkForConflictingLocalOptions(){const e=this.options.filter((e=>{const t=e.attributeName();if(this.getOptionValue(t)===undefined){return false}return this.getOptionValueSource(t)!=="default"}));const t=e.filter((e=>e.conflictsWith.length>0));t.forEach((t=>{const n=e.find((e=>t.conflictsWith.includes(e.attributeName())));if(n){this._conflictingOption(t,n)}}))}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e=>{e._checkForConflictingLocalOptions()}))}parseOptions(e){const t=[];const n=[];let s=t;const o=e.slice();function maybeOption(e){return e.length>1&&e[0]==="-"}let i=null;while(o.length){const e=o.shift();if(e==="--"){if(s===n)s.push(e);s.push(...o);break}if(i&&!maybeOption(e)){this.emit(`option:${i.name()}`,e);continue}i=null;if(maybeOption(e)){const t=this._findOption(e);if(t){if(t.required){const e=o.shift();if(e===undefined)this.optionMissingArgument(t);this.emit(`option:${t.name()}`,e)}else if(t.optional){let e=null;if(o.length>0&&!maybeOption(o[0])){e=o.shift()}this.emit(`option:${t.name()}`,e)}else{this.emit(`option:${t.name()}`)}i=t.variadic?t:null;continue}}if(e.length>2&&e[0]==="-"&&e[1]!=="-"){const t=this._findOption(`-${e[1]}`);if(t){if(t.required||t.optional&&this._combineFlagAndOptionalValue){this.emit(`option:${t.name()}`,e.slice(2))}else{this.emit(`option:${t.name()}`);o.unshift(`-${e.slice(2)}`)}continue}}if(/^--[^=]+=/.test(e)){const t=e.indexOf("=");const n=this._findOption(e.slice(0,t));if(n&&(n.required||n.optional)){this.emit(`option:${n.name()}`,e.slice(t+1));continue}}if(maybeOption(e)){s=n}if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(e)){t.push(e);if(o.length>0)n.push(...o);break}else if(this._getHelpCommand()&&e===this._getHelpCommand().name()){t.push(e);if(o.length>0)t.push(...o);break}else if(this._defaultCommandName){n.push(e);if(o.length>0)n.push(...o);break}}if(this._passThroughOptions){s.push(e);if(o.length>0)s.push(...o);break}s.push(e)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){const e={};const 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);if(typeof this._showHelpAfterError==="string"){this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`)}else if(this._showHelpAfterError){this._outputConfiguration.writeErr("\n");this.outputHelp({error:true})}const n=t||{};const s=n.exitCode||1;const 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();if(this.getOptionValue(t)===undefined||["default","config","env"].includes(this.getOptionValueSource(t))){if(e.required||e.optional){this.emit(`optionEnv:${e.name()}`,a.env[e.envVar])}else{this.emit(`optionEnv:${e.name()}`)}}}}))}_parseOptionsImplied(){const e=new h(this.options);const hasCustomOptionValue=e=>this.getOptionValue(e)!==undefined&&!["default","implied"].includes(this.getOptionValueSource(e));this.options.filter((t=>t.implied!==undefined&&hasCustomOptionValue(t.attributeName())&&e.valueFromOption(this.getOptionValue(t.attributeName()),t))).forEach((e=>{Object.keys(e.implied).filter((e=>!hasCustomOptionValue(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 findBestOptionFromValue=e=>{const t=e.attributeName();const n=this.getOptionValue(t);const s=this.options.find((e=>e.negate&&t===e.attributeName()));const o=this.options.find((e=>!e.negate&&t===e.attributeName()));if(s&&(s.presetArg===undefined&&n===false||s.presetArg!==undefined&&n===s.presetArg)){return s}return o||e};const getErrorMessage=e=>{const t=findBestOptionFromValue(e);const n=t.attributeName();const s=this.getOptionValueSource(n);if(s==="env"){return`environment variable '${t.envVar}'`}return`option '${t.flags}'`};const n=`error: ${getErrorMessage(e)} cannot be used with ${getErrorMessage(t)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[];let 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;const n=t===1?"":"s";const s=this.parent?` for '${this.name()}'`:"";const o=`error: too many arguments${s}. 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());if(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(e===undefined)return this._version;this._version=e;t=t||"-V, --version";n=n||"output the version number";const s=this.createOption(t,n);this._versionOptionName=s.attributeName();this._registerOption(s);this.on("option:"+s.name(),(()=>{this._outputConfiguration.writeOut(`${e}\n`);this._exit(0,"commander.version",e)}));return this}description(e,t){if(e===undefined&&t===undefined)return this._description;this._description=e;if(t){this._argsDescription=t}return this}summary(e){if(e===undefined)return this._summary;this._summary=e;return this}alias(e){if(e===undefined)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler){t=this.commands[this.commands.length-1]}if(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}'`)}t._aliases.push(e);return this}aliases(e){if(e===undefined)return this._aliases;e.forEach((e=>this.alias(e)));return this}usage(e){if(e===undefined){if(this._usage)return this._usage;const e=this.registeredArguments.map((e=>l(e)));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}this._usage=e;return this}name(e){if(e===undefined)return this._name;this._name=e;return this}nameFromFilename(e){this._name=i.basename(e,i.extname(e));return this}executableDir(e){if(e===undefined)return this._executableDir;this._executableDir=e;return this}helpInformation(e){const t=this.createHelp();if(t.helpWidth===undefined){t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()}return t.formatHelp(this,t)}_getHelpContext(e){e=e||{};const t={error:!!e.error};let n;if(t.error){n=e=>this._outputConfiguration.writeErr(e)}else{n=e=>this._outputConfiguration.writeOut(e)}t.write=e.write||n;t.command=this;return t}outputHelp(e){let t;if(typeof e==="function"){t=e;e=undefined}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);if(typeof s!=="string"&&!Buffer.isBuffer(s)){throw new Error("outputHelp callback must return a string or a Buffer")}}n.write(s);if(this._getHelpOption()?.long){this.emit(this._getHelpOption().long)}this.emit("afterHelp",n);this._getCommandAndAncestors().forEach((e=>e.emit("afterAllHelp",n)))}helpOption(e,t){if(typeof e==="boolean"){if(e){this._helpOption=this._helpOption??undefined}else{this._helpOption=null}return this}e=e??"-h, --help";t=t??"display help for command";this._helpOption=this.createOption(e,t);return this}_getHelpOption(){if(this._helpOption===undefined){this.helpOption(undefined,undefined)}return this._helpOption}addHelpOption(e){this._helpOption=e;return this}help(e){this.outputHelp(e);let t=a.exitCode||0;if(t===0&&e&&typeof e!=="function"&&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`;this.on(s,(e=>{let n;if(typeof t==="function"){n=t({error:e.error,command:e.command})}else{n=t}if(n){e.write(`${n}\n`)}}));return this}_outputHelpIfRequested(e){const t=this._getHelpOption();const n=t&&e.find((e=>t.is(e)));if(n){this.outputHelp();this._exit(0,"commander.helpDisplayed","(outputHelp)")}}}function incrementNodeInspectorPort(e){return e.map((e=>{if(!e.startsWith("--inspect")){return e}let t;let n="127.0.0.1";let s="9229";let o;if((o=e.match(/^(--inspect(-brk)?)$/))!==null){t=o[1]}else if((o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null){t=o[1];if(/^\d+$/.test(o[3])){s=o[3]}else{n=o[3]}}else if((o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null){t=o[1];n=o[3];s=o[4]}if(t&&s!=="0"){return`${t}=${n}:${parseInt(s)+1}`}return e}))}t.Command=Command},41135:(e,t)=>{class CommanderError 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=undefined}}class InvalidArgumentError extends CommanderError{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name}}t.CommanderError=CommanderError;t.InvalidArgumentError=InvalidArgumentError},79754:(e,t,n)=>{const{humanReadableArgName:s}=n(49154);class Help{constructor(){this.helpWidth=undefined;this.sortSubcommands=false;this.sortOptions=false;this.showGlobalOptions=false}visibleCommands(e){const t=e.commands.filter((e=>!e._hidden));const n=e._getHelpCommand();if(n&&!n._hidden){t.push(n)}if(this.sortSubcommands){t.sort(((e,t)=>e.name().localeCompare(t.name())))}return t}compareOptions(e,t){const getSortKey=e=>e.short?e.short.replace(/^-/,""):e.long.replace(/^--/,"");return getSortKey(e).localeCompare(getSortKey(t))}visibleOptions(e){const t=e.options.filter((e=>!e.hidden));const n=e._getHelpOption();if(n&&!n.hidden){const s=n.short&&e._findOption(n.short);const o=n.long&&e._findOption(n.long);if(!s&&!o){t.push(n)}else if(n.long&&!o){t.push(e.createOption(n.long,n.description))}else if(n.short&&!s){t.push(e.createOption(n.short,n.description))}}if(this.sortOptions){t.sort(this.compareOptions)}return 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)}if(this.sortOptions){t.sort(this.compareOptions)}return t}visibleArguments(e){if(e._argsDescription){e.registeredArguments.forEach((t=>{t.description=t.description||e._argsDescription[t.name()]||""}))}if(e.registeredArguments.find((e=>e.description))){return e.registeredArguments}return[]}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;if(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(", ")}`)}if(e.defaultValue!==undefined){const n=e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean";if(n){t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}}if(e.presetArg!==undefined&&e.optional){t.push(`preset: ${JSON.stringify(e.presetArg)}`)}if(e.envVar!==undefined){t.push(`env: ${e.envVar}`)}if(t.length>0){return`${e.description} (${t.join(", ")})`}return e.description}argumentDescription(e){const t=[];if(e.argChoices){t.push(`choices: ${e.argChoices.map((e=>JSON.stringify(e))).join(", ")}`)}if(e.defaultValue!==undefined){t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(t.length>0){const n=`(${t.join(", ")})`;if(e.description){return`${e.description} ${n}`}return n}return e.description}formatHelp(e,t){const n=t.padWidth(e,t);const s=t.helpWidth||80;const o=2;const i=2;function formatItem(e,r){if(r){const a=`${e.padEnd(n+i)}${r}`;return t.wrap(a,s-o,n+i)}return e}function formatList(e){return e.join("\n").replace(/^/gm," ".repeat(o))}let r=[`Usage: ${t.commandUsage(e)}`,""];const a=t.commandDescription(e);if(a.length>0){r=r.concat([t.wrap(a,s,0),""])}const c=t.visibleArguments(e).map((e=>formatItem(t.argumentTerm(e),t.argumentDescription(e))));if(c.length>0){r=r.concat(["Arguments:",formatList(c),""])}const l=t.visibleOptions(e).map((e=>formatItem(t.optionTerm(e),t.optionDescription(e))));if(l.length>0){r=r.concat(["Options:",formatList(l),""])}if(this.showGlobalOptions){const n=t.visibleGlobalOptions(e).map((e=>formatItem(t.optionTerm(e),t.optionDescription(e))));if(n.length>0){r=r.concat(["Global Options:",formatList(n),""])}}const d=t.visibleCommands(e).map((e=>formatItem(t.subcommandTerm(e),t.subcommandDescription(e))));if(d.length>0){r=r.concat(["Commands:",formatList(d),""])}return 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=" \\f\\t\\v - \ufeff";const i=new RegExp(`[\\n][${o}]+`);if(e.match(i))return e;const r=t-n;if(r<s)return e;const a=e.slice(0,n);const c=e.slice(n).replace("\r\n","\n");const l=" ".repeat(n);const d="";const u=`\\s${d}`;const p=new RegExp(`\n|.{1,${r-1}}([${u}]|$)|[^${u}]+?([${u}]|$)`,"g");const h=c.match(p)||[];return a+h.map(((e,t)=>{if(e==="\n")return"";return(t>0?l:"")+e.trimEnd()})).join("\n")}}t.Help=Help},45240:(e,t,n)=>{const{InvalidArgumentError:s}=n(41135);class Option{constructor(e,t){this.flags=e;this.description=t||"";this.required=e.includes("<");this.optional=e.includes("[");this.variadic=/\w\.\.\.[>\]]$/.test(e);this.mandatory=false;const n=splitOptionFlags(e);this.short=n.shortFlag;this.long=n.longFlag;this.negate=false;if(this.long){this.negate=this.long.startsWith("--no-")}this.defaultValue=undefined;this.defaultValueDescription=undefined;this.presetArg=undefined;this.envVar=undefined;this.parseArg=undefined;this.hidden=false;this.argChoices=undefined;this.conflictsWith=[];this.implied=undefined}default(e,t){this.defaultValue=e;this.defaultValueDescription=t;return this}preset(e){this.presetArg=e;return this}conflicts(e){this.conflictsWith=this.conflictsWith.concat(e);return this}implies(e){let t=e;if(typeof e==="string"){t={[e]:true}}this.implied=Object.assign(this.implied||{},t);return this}env(e){this.envVar=e;return this}argParser(e){this.parseArg=e;return this}makeOptionMandatory(e=true){this.mandatory=!!e;return this}hideHelp(e=true){this.hidden=!!e;return this}_concatValue(e,t){if(t===this.defaultValue||!Array.isArray(t)){return[e]}return t.concat(e)}choices(e){this.argChoices=e.slice();this.parseArg=(e,t)=>{if(!this.argChoices.includes(e)){throw new s(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(e,t)}return e};return this}name(){if(this.long){return this.long.replace(/^--/,"")}return this.short.replace(/^-/,"")}attributeName(){return camelcase(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class DualOptions{constructor(e){this.positiveOptions=new Map;this.negativeOptions=new Map;this.dualOptions=new Set;e.forEach((e=>{if(e.negate){this.negativeOptions.set(e.attributeName(),e)}else{this.positiveOptions.set(e.attributeName(),e)}}));this.negativeOptions.forEach(((e,t)=>{if(this.positiveOptions.has(t)){this.dualOptions.add(t)}}))}valueFromOption(e,t){const n=t.attributeName();if(!this.dualOptions.has(n))return true;const s=this.negativeOptions.get(n).presetArg;const o=s!==undefined?s:false;return t.negate===(o===e)}}function camelcase(e){return e.split("-").reduce(((e,t)=>e+t[0].toUpperCase()+t.slice(1)))}function splitOptionFlags(e){let t;let n;const s=e.split(/[ |,]+/);if(s.length>1&&!/^[[<]/.test(s[1]))t=s.shift();n=s.shift();if(!t&&/^-[^-]$/.test(n)){t=n;n=undefined}return{shortFlag:t,longFlag:n}}t.Option=Option;t.DualOptions=DualOptions},65030:(e,t)=>{const n=3;function editDistance(e,t){if(Math.abs(e.length-t.length)>n)return Math.max(e.length,t.length);const s=[];for(let t=0;t<=e.length;t++){s[t]=[t]}for(let e=0;e<=t.length;e++){s[0][e]=e}for(let n=1;n<=t.length;n++){for(let o=1;o<=e.length;o++){let i=1;if(e[o-1]===t[n-1]){i=0}else{i=1}s[o][n]=Math.min(s[o-1][n]+1,s[o][n-1]+1,s[o-1][n-1]+i);if(o>1&&n>1&&e[o-1]===t[n-2]&&e[o-2]===t[n-1]){s[o][n]=Math.min(s[o][n],s[o-2][n-2]+1)}}}return s[e.length][t.length]}function suggestSimilar(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));const s=e.startsWith("--");if(s){e=e.slice(2);t=t.map((e=>e.slice(2)))}let o=[];let i=n;const r=.4;t.forEach((t=>{if(t.length<=1)return;const n=editDistance(e,t);const s=Math.max(e.length,t.length);const a=(s-n)/s;if(a>r){if(n<i){i=n;o=[t]}else if(n===i){o.push(t)}}}));o.sort(((e,t)=>e.localeCompare(t)));if(s){o=o.map((e=>`--${e}`))}if(o.length>1){return`\n(Did you mean one of ${o.join(", ")}?)`}if(o.length===1){return`\n(Did you mean ${o[0]}?)`}return""}t.suggestSimilar=suggestSimilar}};var t={};function __nccwpck_require__(n){var s=t[n];if(s!==undefined){return s.exports}var o=t[n]={exports:{}};var i=true;try{e[n].call(o.exports,o,o.exports,__nccwpck_require__);i=false}finally{if(i)delete t[n]}return o.exports}__nccwpck_require__.m=e;(()=>{var e=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;var t;__nccwpck_require__.t=function(n,s){if(s&1)n=this(n);if(s&8)return n;if(typeof n==="object"&&n){if(s&4&&n.__esModule)return n;if(s&16&&typeof n.then==="function")return n}var o=Object.create(null);__nccwpck_require__.r(o);var i={};t=t||[null,e({}),e([]),e(e)];for(var r=s&2&&n;typeof r=="object"&&!~t.indexOf(r);r=e(r)){Object.getOwnPropertyNames(r).forEach((e=>i[e]=()=>n[e]))}i["default"]=()=>n;__nccwpck_require__.d(o,i);return o}})();(()=>{__nccwpck_require__.d=(e,t)=>{for(var n in t){if(__nccwpck_require__.o(t,n)&&!__nccwpck_require__.o(e,n)){Object.defineProperty(e,n,{enumerable:true,get:t[n]})}}}})();(()=>{__nccwpck_require__.f={};__nccwpck_require__.e=e=>Promise.all(Object.keys(__nccwpck_require__.f).reduce(((t,n)=>{__nccwpck_require__.f[n](e,t);return t}),[]))})();(()=>{__nccwpck_require__.u=e=>""+e+".index.js"})();(()=>{__nccwpck_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)})();(()=>{__nccwpck_require__.r=e=>{if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(e,"__esModule",{value:true})}})();if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";(()=>{var e={792:1};var installChunk=t=>{var n=t.modules,s=t.ids,o=t.runtime;for(var i in n){if(__nccwpck_require__.o(n,i)){__nccwpck_require__.m[i]=n[i]}}if(o)o(__nccwpck_require__);for(var r=0;r<s.length;r++)e[s[r]]=1};__nccwpck_require__.f.require=(t,n)=>{if(!e[t]){if(true){installChunk(require("./"+__nccwpck_require__.u(t)))}else e[t]=1}}})();var n={};(()=>{"use strict";var e=n;Object.defineProperty(e,"__esModule",{value:true});const t=__nccwpck_require__(18909);const s=__nccwpck_require__(11627);const o=__nccwpck_require__(19218);const i=__nccwpck_require__(38706);const r=__nccwpck_require__(5596);const a=__nccwpck_require__(97499);const c=__nccwpck_require__(46222);const l=__nccwpck_require__(67378);const d=__nccwpck_require__(67509);const u=__nccwpck_require__(46183);const p=__nccwpck_require__(96007);const h=__nccwpck_require__(8784);const m=__nccwpck_require__(91262);const f=__nccwpck_require__(83969);const g=__nccwpck_require__(85417);const y=__nccwpck_require__(40791);const $=__nccwpck_require__(22835);const k=__nccwpck_require__(60952);const b=__nccwpck_require__(40239);const w=__nccwpck_require__(8045);const _=__nccwpck_require__(28423);const S=__nccwpck_require__(96616);const v=__nccwpck_require__(44040);const x=__nccwpck_require__(45475);const C=__nccwpck_require__(63746);const O=__nccwpck_require__(44478);const I=__nccwpck_require__(18691);const P=__nccwpck_require__(34362);const T=__nccwpck_require__(80928);const E=__nccwpck_require__(58211);const A=__nccwpck_require__(43423);const M=__nccwpck_require__(72768);const R=__nccwpck_require__(9708);const L=__nccwpck_require__(33766);const N=__nccwpck_require__(50984);const D=__nccwpck_require__(69903);const F=__nccwpck_require__(35344);const q=__nccwpck_require__(71783);const K=__nccwpck_require__(91993);const j=__nccwpck_require__(81466);const U=__nccwpck_require__(50869);const z=__nccwpck_require__(87604);const H=__nccwpck_require__(65240);const B=__nccwpck_require__(23017);const J=__nccwpck_require__(84436);const W=__nccwpck_require__(15472);const G=__nccwpck_require__(52072);const X=__nccwpck_require__(33192);const Y=__nccwpck_require__(30896);const V=__nccwpck_require__(72124);const Q=__nccwpck_require__(99236);const Z=__nccwpck_require__(93402);const ee=__nccwpck_require__(64115);(0,s.applyConfig)();(0,Z.checkForUpdates)();const te=new t.Command;const ne=`\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`;te.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 ne;const{Help:n}=__nccwpck_require__(18909);const s=new n;return s.formatHelp(e,t)}}).action((async()=>{await interactiveEntry()}));async function interactiveEntry(){if(!process.stdin.isTTY){console.log(ne);return}const e=await Promise.resolve().then(__nccwpck_require__.t.bind(__nccwpck_require__,23785,23));if((0,s.isConfigured)()){try{const e=new o.SFClient;const{theses:t}=await e.listTheses();const n=(t||[]).filter((e=>e.status==="active"));if(n.length>0){await(0,f.agentCommand)(n[0].id,{});return}}catch{await(0,f.agentCommand)(undefined,{});return}}console.log();console.log(" [1mSimpleFunctions[22m — prediction market intelligence");console.log();if((0,s.isConfigured)()){console.log(" [2mYou have no active theses.[22m")}else{console.log(" [2mNo login needed to explore.[22m")}console.log();const t=e.createInterface({input:process.stdin,output:process.stdout,terminal:true});const n=await new Promise((e=>{t.question(" What's your market view? (keyword or thesis)\n [36m>[39m ",(n=>{t.close();e(n.trim())}))}));if(!n){console.log(ne);return}let i=n.replace(/[^\w\s]/g," ").split(/\s+/).filter((e=>e.length>2)).slice(0,5).join(" ");if(!i)i=n.trim().slice(0,40);console.log();console.log(` [2mScanning Kalshi + Polymarket for: "${i}"...[22m`);console.log();try{const{scanCommand:e}=await Promise.resolve().then(__nccwpck_require__.bind(__nccwpck_require__,46183));await e(i,{json:false})}catch(e){console.error(` [31mScan failed: ${e.message}[39m`)}console.log();if((0,s.isConfigured)()){console.log(" [2mWant to monitor this thesis 24/7?[22m");console.log(` [36msf create[39m "${n.slice(0,60)}"`)}else{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"]);te.hook("preAction",((e,t)=>{const n=t.name();if(se.has(n))return;const o=e.optsWithGlobals?.()||e.opts();if(o.apiKey)return;if(!(0,s.isConfigured)()){const e=process.argv.includes("--json");if(e){console.log(JSON.stringify({error:"API key required.",code:"NOT_CONFIGURED",keyUrl:"https://simplefunctions.dev/dashboard/keys",cli:"sf login"}))}else{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)}}));te.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 run((()=>(0,g.setupCommand)({check:e.check,reset:e.reset,key:e.key,enableTrading:e.enableTrading,disableTrading:e.disableTrading,kalshi:e.kalshi,polymarket:e.polymarket})))}));te.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 run((()=>(0,U.loginCommand)({apiUrl:n.apiUrl,force:e.force})))}));te.command("logout").description("Clear saved credentials").action((async()=>{await run((async()=>{const{resetConfig:e,loadFileConfig:t}=await Promise.resolve().then(__nccwpck_require__.t.bind(__nccwpck_require__,11627,23));const n=t();if(!n.apiKey){console.log(`\n ${Q.c.dim}Not logged in.${Q.c.reset}\n`);return}e();console.log(`\n Logged out. Credentials removed from ~/.sf/config.json`);console.log(` ${Q.c.dim}Run ${Q.c.cyan}sf login${Q.c.dim} to re-authenticate.${Q.c.reset}\n`)}))}));te.command("update").description("Update CLI to latest version").action((async()=>{await run((()=>(0,ee.updateCommand)()))}));te.command("status").description("Health check: verify API, auth, Kalshi, Polymarket connections").option("--json","JSON output").action((async e=>{await run((()=>(0,V.statusCommand)({json:e.json})))}));te.command("list").description("List all theses").option("--json","JSON output").action((async(e,t)=>{const n=t.optsWithGlobals();await run((()=>(0,i.listCommand)({json:e.json,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.command("get <id>").description("Get full thesis details").option("--json","Output raw JSON").action((async(e,t,n)=>{const s=n.optsWithGlobals();await run((()=>(0,r.getCommand)(e,{json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,a.contextCommand)(e,{json:t.json,share:t.share,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,c.createCommand)(e,{async:t.async,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,l.signalCommand)(e,t,{type:n.type,json:n.json,apiKey:o.apiKey,apiUrl:o.apiUrl})))}));te.command("evaluate <id>").description("Trigger a deep evaluation (heavy model, force-heavy mode)").action((async(e,t,n)=>{const s=n.optsWithGlobals();await run((()=>(0,d.evaluateCommand)(e,{apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>{const n=new o.SFClient(s.apiKey,s.apiUrl);return(0,z.heartbeatCommand)(n,e,{newsInterval:t.newsInterval,xInterval:t.xInterval,model:t.model,budget:t.budget,pause:t.pause,resume:t.resume})}))}));te.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();const o=e||"";if(!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 run((()=>(0,u.scanCommand)(o,{series:t.series,market:t.market,venue:t.venue,json:t.json,share:t.share,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,p.watchCommand)(e,t,{interval:n.interval,json:n.json,thesis:n.thesis,smart:n.smart,execute:n.execute})))}));te.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 run((()=>(0,m.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})))}));te.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 run((()=>(0,h.positionsCommand)({json:e.json,thesis:e.thesis,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.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)=>{const s=n.optsWithGlobals();await run((()=>(0,f.agentCommand)(e,{model:t.model,modelKey:t.modelKey,newSession:t.new,noTui:t.plain})))}));te.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 run((()=>(0,y.publishCommand)(e,{slug:t.slug,description:t.description,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.command("unpublish <thesisId>").description("Remove a thesis from public viewing").action((async(e,t,n)=>{const s=n.optsWithGlobals();await run((()=>(0,y.unpublishCommand)(e,{apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,$.exploreCommand)(e,{json:t.json,share:t.share})))}));te.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 run((()=>(0,k.dashboardCommand)({json:e.json,once:e.once,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.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 run((()=>(0,w.milestonesCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.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 run((()=>(0,_.forecastCommand)(e,t)))}));te.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 run((()=>(0,S.settlementsCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.command("balance").description("Kalshi account balance").option("--json","JSON output").action((async e=>{await run((()=>(0,v.balanceCommand)(e)))}));te.command("orders").description("Kalshi resting orders").option("--status <status>","Order status filter (default: resting)","resting").option("--json","JSON output").action((async e=>{await run((()=>(0,x.ordersCommand)(e)))}));te.command("fills").description("Recent trade fills").option("--ticker <ticker>","Filter by market ticker").option("--json","JSON output").action((async e=>{await run((()=>(0,C.fillsCommand)(e)))}));te.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 run((()=>(0,O.feedCommand)({...e,apiKey:n.apiKey,apiUrl:n.apiUrl})))}));te.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 run((()=>(0,j.deltaCommand)(e,{...t,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,I.whatifCommand)(e,{set:t.set,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.command("schedule").description("Exchange status and trading hours").option("--json","JSON output").action((async e=>{await run((()=>(0,E.scheduleCommand)(e)))}));te.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 run((()=>(0,P.buyCommand)(e,t,n)))}));te.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 run((()=>(0,P.sellCommand)(e,t,n)))}));te.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 run((()=>(0,T.cancelCommand)(e,t)))}));te.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 run((()=>(0,A.rfqCommand)(e,t,n)))}));te.command("announcements").description("Exchange announcements (rule changes, maintenance)").option("--json","JSON output").action((async e=>{await run((()=>(0,M.announcementsCommand)(e)))}));te.command("history <ticker>").description("Historical market data (settled/closed)").option("--json","JSON output").action((async(e,t)=>{await run((()=>(0,R.historyCommand)(e,t)))}));te.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 run((()=>(0,L.performanceCommand)(e)))}));te.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 run((()=>(0,N.liquidityCommand)({...t,topic:e})))}));te.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)=>{if(e.length===0&&!t.poly){console.error('Usage: sf book <ticker> [ticker2...] OR sf book --poly "oil price"');process.exit(1)}await run((()=>(0,D.bookCommand)(e,t)))}));te.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 run((()=>(0,F.promptCommand)(e,{sections:t.sections,maxLength:t.maxLength,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,q.augmentCommand)(e,{dryRun:t.dryRun,json:t.json,apiKey:s.apiKey,apiUrl:s.apiUrl})))}));te.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 run((()=>(0,B.marketsCommand)({json:e.json,share:e.share})))}));te.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 run((()=>(0,H.queryCommand)(e,{json:t.json,share:t.share,limit:t.limit})))}));te.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 run((()=>(0,K.telegramCommand)(e)))}));te.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 run((()=>(0,J.xSearchCommand)(e,t)))}));te.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 run((()=>(0,J.xVolumeCommand)(e,t)))}));te.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 run((()=>(0,J.xNewsCommand)(e,t)))}));te.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 run((()=>(0,J.xAccountCommand)(e,t)))}));te.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 run((()=>(0,X.worldCommand)(e)))}));te.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 run((()=>(0,Y.ideasCommand)(e)))}));(0,b.registerStrategies)(te);(0,W.registerIntents)(te);(0,G.registerRuntime)(te);async function run(e){try{await e()}catch(e){const t=e instanceof Error?e.message:String(e);if(process.argv.includes("--json")){console.log(JSON.stringify({error:t,code:e.code||"CLI_ERROR",status:e.status||1}));process.exit(1)}(0,Q.die)(t)}}te.parse()})();module.exports=n})();
|