npm package: @spfunctions/cli
Description: Prediction market intelligence CLI. Causal thesis model, 24/7 Kalshi/Polymarket scan, live orderbook, edge detection. Interactive agent mode with tool calling.
Latest version: 3.0.8

# SimpleFunctions CLI (`sf`)

A terminal-native prediction market agent. Builds causal models of the world, scans 4,000+ Kalshi and Polymarket contracts for mispricings, and trades on your thesis — autonomously or with you in the loop.

```
$ sf world
# World State — 2026-04-09T13:00 UTC
SF Index v2: Disagree 57/100 | GeoRisk 35/100 | Breadth +0.33 | Activity 86/100

Markets: SPY $655.94 (+0.12%) | GLD $429.08 (-1.79%) | USO $138.18 (+11.99%)

## Geopolitical
- Will the U.S. invade Iran before 2027?: 54c (-7c)
- Russia x Ukraine ceasefire by end of 2026?: 30c

## Economy
- US recession by end of 2026?: 28c
- How many Fed rate cuts in 2026?: 0 (0 bps): 36c
```

## Install

```bash
npm install -g @spfunctions/cli
sf login                # browser auth (recommended)
sf status               # verify everything works
```

## What it does

**World model** — Real-time prediction index distilled from thousands of markets. One command gives any LLM situational awareness.

```bash
sf world                    # ~800 token world state snapshot
sf world --delta            # what changed since last check (~30 tokens)
sf world --focus energy,geo # deep coverage on specific topics
sf ideas                    # S&T-style trade ideas with catalyst + risk
```

**Thesis engine** — Structured causal models with Bayesian node trees, continuous evaluation against live market data, and automatic edge detection.

```bash
sf create "Oil will exceed $120 by Q3 due to Hormuz disruption"
sf list                     # all theses with confidence + status
sf context <id>             # causal tree + top edges + positions
sf evaluate <id>            # trigger deep re-evaluation
sf signal <id> "OPEC cuts"  # inject a signal for next eval cycle
```

**Edge detection** — Cross-venue scanner compares your model's probabilities against Kalshi and Polymarket prices.

```bash
sf edges                    # top mispricings across all theses
sf scan "recession"         # search 4,000+ markets by keyword
sf book KXRECSSNBER-26      # orderbook depth
sf watch oil orderbook      # live terminal orderbook stream
sf watch "fed" all --smart  # LLM-filtered alerts + news divergence detection
```

**Intent system** — Declarative execution: describe what you want, the runtime handles when and how.

```bash
sf intent buy KXRECSSNBER-26 10 --price 30 --trigger below:28 --auto
sf intent list              # active intents + fill status
sf runtime start            # daemon evaluates triggers, executes orders
```

**Interactive agent** — Natural language interface with 30+ tools. Maintains a persistent workspace, shares context across sessions, and can schedule its own future actions.

```bash
sf agent <id>               # TUI agent with tool calling
sf agent <id> --once "summarize my portfolio risk"  # single-shot
sf agent <id> --plain       # readline mode, no TUI
sf telegram --daemon        # Telegram bot (text + voice)
```

**X / Twitter intelligence** — Social signal layer.

```bash
sf x "tariff impact"        # discussion summary + top posts
sf x-volume "iran oil"      # volume and velocity trend
sf x-news "fed rate"        # Grok-aggregated news stories
sf x-account @elikinosian   # recent posts from an account
```

## Setup

### Quick (browser login)

```bash
sf login
```

### Power user

```bash
sf setup                    # interactive wizard: API key, Kalshi, Polymarket, trading
sf setup --check            # show config status
sf setup --polymarket       # configure Polymarket wallet
sf setup --enable-trading   # unlock buy/sell/intent commands
```

Config is saved to `~/.sf/config.json`. Environment variables override config values:

```bash
export SF_API_KEY=sf_live_xxx
export KALSHI_API_KEY_ID=xxx
export KALSHI_PRIVATE_KEY_PATH=~/.kalshi/private.pem
```

### Verify

```bash
$ sf status
  API            ok  simplefunctions.dev 252ms
  Auth           ok  sf_live_8838...
  Kalshi         ok  $156.42 balance
  Polymarket     ok  0xd53b9354...
  Theses         ok  4 active, 4 total
  Trading        ok  enabled
  Runtime        --  not running (sf runtime start)
  Telegram       ok  PID 84372
```

## Command Reference

### World Model (no auth required)

| Command | Description |
|---------|-------------|
| `sf world` | Prediction index: markets + geopolitics + economy + crypto + elections |
| `sf world --delta` | Changes since last check (~30 tokens, ideal for agent polling) |
| `sf world --focus <topics>` | Deep coverage on specific topics |
| `sf ideas` | Trade ideas with conviction, catalyst, direction, risk |
| `sf query "question"` | LLM-enhanced market knowledge search |
| `sf markets` | Traditional markets: SPY, VIX, bonds, gold, oil |

### Thesis

| Command | Description |
|---------|-------------|
| `sf list` | All theses with status, confidence, last update |
| `sf get <id>` | Full details: causal tree, edges, evaluation history |
| `sf context [id]` | No id: global market snapshot. With id: thesis context |
| `sf create "thesis"` | Create a new thesis |
| `sf signal <id> "text"` | Inject signal for next evaluation |
| `sf evaluate <id>` | Trigger deep re-evaluation |
| `sf augment <id>` | Evolve causal tree with new nodes |
| `sf heartbeat <id>` | View/configure autonomous evaluation schedule + costs |
| `sf publish` / `sf unpublish <id>` | Manage public visibility |

### Markets

| Command | Description |
|---------|-------------|
| `sf scan "keywords"` | Search Kalshi + Polymarket by keyword |
| `sf scan --series TICKER` | Browse all markets in a Kalshi series |
| `sf edges [--json]` | Top mispricings across all theses |
| `sf watch [query] [mode]` | Live market watch (modes: orderbook, flow, cross-venue, all) |
| `sf watch "q" --smart` | LLM-filtered alerts + news divergence via monitor-the-situation |
| `sf watch "q" --smart --execute` | Auto-create trading intents from detected signals |
| `sf book <ticker> [...]` | Orderbook depth for specific markets |
| `sf whatif <id>` | What-if scenario analysis on causal tree |
| `sf liquidity [topic]` | Orderbook liquidity scanner |
| `sf forecast <event>` | Market distribution (P50/P75/P90) |
| `sf explore [slug]` | Browse public theses |

### Portfolio

| Command | Description |
|---------|-------------|
| `sf positions` | Kalshi + Polymarket positions with P&L |
| `sf balance` | Account balance |
| `sf orders` | Resting (open) orders |
| `sf fills` | Recent trade fills |
| `sf settlements` | Settled contracts with final P&L |
| `sf performance` | P&L over time with event annotations |
| `sf dashboard` | Interactive TUI portfolio overview |

### Intents & Runtime

Intents are declarative execution orders. You define the trade and trigger condition; the runtime daemon evaluates and executes.

| Command | Description |
|---------|-------------|
| `sf intent buy <ticker> <qty>` | Create buy intent (`--trigger below:28`, `--trigger time:<ISO>`, `--soft "condition"`, `--auto`) |
| `sf intent sell <ticker> <qty>` | Create sell intent |
| `sf intent list` | Active intents (`--all` for history) |
| `sf intent status <id>` | Detailed status + fills |
| `sf intent cancel <id>` | Cancel an intent |
| `sf runtime start` | Start execution daemon (Kalshi + Polymarket) |
| `sf runtime stop` | Stop daemon |
| `sf runtime status` | Active intents + runtime state |
| `sf backtest <ticker>` | Strategy backtest (`--entry-below 35 --stop 20 --tp 60 --days 30`) |
| `sf heartbeat <id>` | View/configure heartbeat + closed-loop (`--closed-loop-entry`, `--closed-loop-exit`) |

### Trading (requires `--enable-trading`)

| Command | Description |
|---------|-------------|
| `sf buy <ticker> <qty>` | Buy contracts (`--price 31`, `--market`, `--side yes\|no`) |
| `sf sell <ticker> <qty>` | Sell contracts |
| `sf cancel [orderId]` | Cancel order(s) |
| `sf rfq <ticker> <qty>` | Request for quote on large orders |

### Agent

| Command | Description |
|---------|-------------|
| `sf agent [id]` | Interactive agent (TUI with panels) |
| `sf agent [id] --plain` | Readline mode, pipe-friendly |
| `sf agent [id] --once "prompt"` | Single-shot: run, answer, exit |
| `sf prompt [id]` | Print dynamic system prompt for any LLM |
| `sf telegram [--daemon]` | Telegram bot (text + voice messages) |

The agent has 30+ tools including market scanning, trading, workspace read/write, X search, self-wake scheduling, and a math calculator. Slash commands inside the agent: `/voice` `/tree` `/edges` `/pos` `/eval` `/balance` `/intents` `/wakes` `/alerts` `/switch` `/model` `/help` `/exit`.

### X / Twitter

| Command | Description |
|---------|-------------|
| `sf x "query"` | Discussion summary + top posts |
| `sf x-volume "query"` | Discussion volume and velocity trend |
| `sf x-news "query"` | Grok-aggregated news stories |
| `sf x-account @username` | Recent posts from a specific account |

### Info

| Command | Description |
|---------|-------------|
| `sf feed` | Evaluation history stream |
| `sf delta <id>` | Changes since last check |
| `sf milestones` | Upcoming Kalshi events |
| `sf schedule` | Exchange status |
| `sf announcements` | Exchange announcements |
| `sf history <ticker>` | Historical market data |
| `sf status` | Full system health check |

### Sharing

Any command with `--share` generates a short URL:

```bash
sf scan "gold" --share
sf query "fed rate" --share
sf context --share
```

## JSON Output

Most commands support `--json` for machine-readable output:

```bash
sf list --json
sf context f582bf76 --json
sf edges --json
sf world --json
sf ideas --json
sf intent list --json
```

## For AI Agents

If you are an AI agent (Claude, GPT, Cursor, etc.), these are the commands that matter:

### Setup

```bash
npm install -g @spfunctions/cli
sf login                          # or: export SF_API_KEY=sf_live_xxx
sf list                           # verify: should print theses
```

### Primary commands

```bash
# World state in ~800 tokens — give your agent situational awareness
sf world --json

# What changed since last poll — ~30 tokens, efficient for loops
sf world --delta --json

# Thesis context: causal tree + edges + positions + evaluation
sf context <thesisId> --json

# Top mispricings across all theses
sf edges --json

# Single-shot agent: ask a question, get an answer, exit
sf agent <thesisId> --once "what is the biggest risk to my portfolio?"
```

### Key JSON fields

`sf context <id> --json` returns:

```json
{
  "confidence": 0.31,
  "causalTree": {
    "nodes": [{ "id": "n1", "label": "...", "probability": 0.95 }]
  },
  "edges": [{
    "marketId": "KXWTIMAX-26DEC31-T140",
    "venue": "kalshi",
    "marketPrice": 62,
    "thesisPrice": 95,
    "edge": 33
  }]
}
```

- `confidence` — overall thesis probability (0 to 1)
- `edges[].edge` — mispricing in cents (positive = market underpriced vs model)
- `edges[].marketPrice` — current market price (0-100 cents)

### Patterns

```bash
# Monitor: poll world state, react to deltas
sf world --delta --json

# React to news: inject signal, re-evaluate, read updated state
sf signal <id> "Breaking: OPEC cuts production" --type news
sf evaluate <id>
sf context <id> --json

# Trade: create intent with trigger, let runtime execute
sf intent buy KXRECSSNBER-26 5 --price 30 --trigger below:28 --auto
sf runtime start
```

### Error codes

| Error | Fix |
|-------|-----|
| "API key required" | `sf login` or set `SF_API_KEY` |
| "Thesis not found" | `sf list` to get valid IDs (8-char prefix works) |
| "Kalshi not configured" | `sf setup` to add Kalshi credentials |
| "Trading disabled" | `sf setup --enable-trading` |

## Architecture

```
You ──→ sf agent ──→ LLM (Claude/GPT) ──→ 30+ tools
              │                                  │
              │         ┌────────────────────────┘
              ▼         ▼
         ┌─────────────────────┐
         │   SF API Server     │
         │  thesis · edges ·   │
         │  intents · eval ·   │
         │  proxy (LLM/TTS)    │
         └────────┬────────────┘
                  │
         ┌────────┴────────┐
         │                 │
    ┌────▼────┐     ┌──────▼──────┐
    │ Kalshi  │     │ Polymarket  │
    │  API    │     │    API      │
    └─────────┘     └─────────────┘

Local only (never leaves your machine):
  ~/.sf/config.json     — API keys, Kalshi private key path
  ~/.sf/workspace/      — agent scratchpad (notes, context logs)
  ~/.sf/wake/           — scheduled agent wake conditions
  ~/.sf/bus/            — daemon ↔ agent message bus
  ~/.sf/trade-journal.jsonl — local trade log
```

**Kalshi credentials never leave your machine.** Orders are signed locally with your RSA private key and sent directly to the Kalshi API. The SF server never sees your trading keys.

## Local Development

```bash
cd cli
npm install
npm run dev -- list          # run without building
npm run build                # compile to dist/
npm run test                 # run tests
npm link                     # install as global 'sf' command
```

## License

MIT