Commit Graph

1087 Commits

Author SHA1 Message Date
shinchan-zhai
4c73a7960d fix: SSE streaming for no-tool path, batch ticker API, security & cleanup
- Fix thinkAndActStream: emit delta event for non-tool responses (was silent)
- Add fallback to streaming on first LLM call failure
- Add batch ticker endpoint /api/agent/tickers (3 API calls → 1)
- Update MarketTicker to use batch endpoint, remove unused state
- Warn loudly when JWT_SECRET uses default value
- Fix 华为 mapping (was incorrectly mapped to Tencent)
- Replace ioutil.ReadAll with safe.ReadAllLimited in nofxos client
- Remove unused variable in hyperliquid trader_account
- Wrap CoinAnk WS readers with safe.GoNamed for panic recovery
- Use 100dvh for mobile viewport in AgentChatPage
- console.log → console.warn for auth events
2026-03-23 14:01:11 +08:00
shinchan-zhai
bd3d532239 feat: real SSE streaming for agent chat + data cleanup on startup
SSE Streaming:
- Add POST /api/agent/chat/stream endpoint with real SSE streaming
- Agent.HandleMessageStream() streams final LLM response via onEvent callback
- Tool-calling rounds use non-streaming; tool status sent as 'tool' events
- Frontend uses ReadableStream API instead of fake word-by-word setTimeout
- SSE events: tool (tool execution), delta (text chunk), done (complete), error

Data Maintenance:
- Add cleanupOldData() on server startup (decisions >90d, equity >180d)
- Add CleanOldRecords to DecisionStore and EquityStore
- Add store-level logger for cleanup operations

Exchange Traders:
- Add GetAccountInfo() to Bitget, Bybit, Indodax, KuCoin, Lighter, OKX traders
- Remove unused imports in Aster/Lighter traders
2026-03-23 13:31:09 +08:00
shinchan-zhai
5fc826b4e0 docs: stock trading design + add Alpaca/LongPort tasks to self-drive queue
- Comprehensive design doc: US/HK/A-share trading API comparison
- Phase 1: Alpaca (US stocks) - paper trading first
- Phase 2: LongPort (HK stocks)
- Phase 3: A-share via Stock Connect
- 10 new [PENDING] tasks for self-drive cron
2026-03-23 13:05:39 +08:00
shinchan-zhai
2b2e7d815f docs: update nofxi-tasks.md — record 12:52 batch 2026-03-23 12:59:20 +08:00
shinchan-zhai
8fbbaad670 fix: graceful HTTP shutdown, add ErrorBoundary, fix chart responsive height
- main.go: call server.Shutdown() on SIGTERM/SIGINT to drain in-flight requests
- Add React ErrorBoundary component (catches render crashes, shows retry UI)
- Wrap main content area and settings page with ErrorBoundary
- Fix ChartTabs.tsx: replace runtime window.innerWidth check with Tailwind responsive class (h-[500px] md:h-[600px])
- Restarted backend with latest build (health endpoint now returns proper timestamp)
2026-03-23 12:58:38 +08:00
shinchan-zhai
e65093f35e docs: update nofxi-tasks.md — record 12:37 batch 2026-03-23 12:45:03 +08:00
shinchan-zhai
54dce726cb feat: dynamic crypto detection, trade history tool, fix 9 ticker leaks
- Agent gatherContext: expand from 10 hardcoded symbols to 38+ known symbols
  plus dynamic XXXUSDT pattern extraction (caps at 5 to avoid slow context)
- Add get_trade_history tool: LLM can now query closed trades with PnL summary
  (win rate, total PnL, recent N trades across all traders)
- Fix ticker.Stop() leak in ALL 9 exchange order_sync goroutines:
  OKX, Hyperliquid, Aster, Bybit, KuCoin, Gate, Bitget, Lighter, Binance
  — tickers were never stopped when traders were stopped, leaking goroutines
2026-03-23 12:44:40 +08:00
shinchan-zhai
809b95d316 docs: update nofxi-tasks.md — record 12:22 batch 2026-03-23 12:29:43 +08:00
shinchan-zhai
60b97399e4 fix: consistent safe type helpers in auto_trader, log emergency exit errors
- Replace all raw pos["key"].(type) assertions with posFloat64/posString/posInt64 helpers
  across auto_trader_decision, auto_trader_grid, auto_trader_grid_orders,
  auto_trader_grid_regime, auto_trader_loop, auto_trader_orders, auto_trader_risk
- Add posInt64 helper for int64 extraction (createdTime etc)
- Fix emergencyExit: log CloseLong/CloseShort errors instead of silently dropping
- Fix emergencyExit: log GetPositions error on failure
- Upgrade closeAllPositions log level from Infof to Warnf for close failures
- Zero raw type assertions remaining in auto_trader_* files
2026-03-23 12:29:21 +08:00
shinchan-zhai
708ffdb7bd fix: toFloat handles json.Number, CORS credentials+wildcard bug, strategy config error handling
- agent/agent.go: toFloat() now handles json.Number and int32 types to prevent silent data loss
- api/server.go: CORS fix — echo specific origin instead of '*' when credentials are enabled (browsers reject Allow-Credentials with wildcard)
- api/strategy.go: all 4 json.Unmarshal calls now check errors and return 'config_error' field instead of silently serving zero-value configs
- store/decision.go: explicitly mark best-effort unmarshal with _ = assignment for clarity
2026-03-23 12:10:55 +08:00
shinchan-zhai
2dbbc82506 docs: update nofxi-tasks.md with panic prevention work 2026-03-23 12:02:06 +08:00
shinchan-zhai
acc52f2cf7 fix: prevent panics from unsafe type assertions in trading code + add request body limit
Security & Reliability:
- Add requestBodyLimitMiddleware (1MB) to prevent OOM from oversized API payloads
- Fix defer resp.Body.Close() inside loop in getPublicIPFromAPI (connection leak)
- Add posFloat64/posString safe helpers for position map access

Panic Prevention (critical for trading):
- Convert 30+ unsafe type assertions (pos["key"].(type)) to safe comma-ok
  pattern across all exchange traders: OKX, Hyperliquid, Aster, Bybit,
  KuCoin, Gate, Bitget, Binance
- Fix auto_trader_risk.go: drawdown monitor could panic and silently stop
  monitoring, leaving positions unprotected
- Fix auto_trader_decision.go & auto_trader_loop.go: core trading loop
  position parsing now crash-proof
- All trader/ code now has zero unsafe type assertions

Frontend:
- Fix config.ts: rejected promise cached forever on network error (never retries)
2026-03-23 12:01:44 +08:00
shinchan-zhai
44d1ef42ad fix: Lighter CancelStopOrders now filters by TriggerPrice, proxyBinance checks upstream status
- CancelStopOrders: only cancel orders with non-empty TriggerPrice (was canceling ALL orders including regular limit orders — safety bug)
- proxyBinance: return 502 when upstream returns non-200 instead of silently proxying error pages
- Remove redundant CORS headers in agent/web.go (already handled by gin middleware)
2026-03-23 11:40:34 +08:00
shinchan-zhai
79b583bd9a docs: update nofxi-tasks.md — record 11:22 batch 2026-03-23 11:29:16 +08:00
shinchan-zhai
bb459d6f9f fix: Bybit shared HTTP client, auth token bugs, consistent safe.ReadAllLimited
- Bybit: replace http.Get/http.DefaultClient with shared bybitHTTPClient (30s timeout, connection pooling)
- Frontend: fix resetPassword missing auth token (endpoint now requires auth)
- Frontend: fix SettingsPage using wrong localStorage key ('token' → 'auth_token')
- Agent: migrate remaining io.ReadAll(io.LimitReader()) to safe.ReadAllLimited for consistency
- Remove unused 'io' imports from brain.go and sentinel.go
2026-03-23 11:28:54 +08:00
shinchan-zhai
b9c9f05603 robustness: shared HTTP client, HTTP status checks, abort controller, streaming perf
- web.go: reuse shared binanceClient with connection pooling instead of per-request client
- sentinel.go: check HTTP status code before parsing Binance ticker response
- brain.go: check HTTP status codes in news scan and market brief APIs
- brain.go: add cleanStaleSignals() to prevent unbounded sync.Map growth
- scheduler.go: periodically clean expired pending trades
- AgentChatPage.tsx: add AbortController to cancel in-flight requests
- AgentChatPage.tsx: check response.ok before parsing JSON
- AgentChatPage.tsx: batch word streaming (~40 frames max) to reduce re-renders
- AgentChatPage.tsx: handle AbortError gracefully (remove orphan bot message)
2026-03-23 11:10:19 +08:00
shinchan-zhai
7ccac89e2b docs: update nofxi-tasks.md — record 10:52 batch progress 2026-03-23 11:00:48 +08:00
shinchan-zhai
88f6fa7911 robustness: add HTTP status code checks to market data & provider APIs
- market/api_client.go: check StatusCode for exchangeInfo, klines, price
  endpoints + add truncateBody helper for safe error messages
- market/data.go: check StatusCode for openInterest and premiumIndex
- provider/coinank: check StatusCode for GET and POST requests
- provider/twelvedata: check StatusCode for time series and quote APIs
- Prevents confusing JSON unmarshal errors when APIs return 429/500/etc
2026-03-23 11:00:24 +08:00
shinchan-zhai
3c698e3fc5 perf: reuse shared HTTP client in Hyperliquid trader
Previously each direct API call (orders, sync, account) created a new
http.Client, preventing TCP/TLS connection reuse. Now all calls share
a single client on the HyperliquidTrader struct (30s timeout).
2026-03-23 10:56:54 +08:00
shinchan-zhai
982ee668c9 security: add safe.ReadAllLimited — bound all HTTP response body reads to 10MB
- Created safe/io.go with ReadAllLimited helper (default 10MB limit)
- Replaced 62 unbounded io.ReadAll(resp.Body) calls across 32 files
- Covers all exchange traders (Hyperliquid, Bybit, Binance, OKX, Aster,
  KuCoin, Gate, Bitget, Lighter, Indodax), providers (CoinAnk, Alpaca,
  TwelveData), MCP client/x402, market data, wallet, telegram, kernel
- Prevents OOM from malicious/buggy exchange API responses
- Previously fixed: brain.go, sentinel.go already had manual LimitReader
2026-03-23 10:55:03 +08:00
shinchan-zhai
1d0d6f7afd security: sanitize internal error messages in API responses
- handler_trader.go: remove loadErr.Error() from 500 responses (2 instances)
- handler_ai_cost.go: replace err.Error() with generic message, add logging
- Internal errors now logged server-side, not exposed to clients
2026-03-23 10:46:22 +08:00
shinchan-zhai
c438cc031d security: upgrade vulnerable deps + refactor AgentChatPage
Dependencies upgraded:
- go-ethereum v1.16.7 → v1.16.8 (fixes GO-2026-4508 DoS + GO-2026-4314/4315 p2p vulns)
- golang-jwt/jwt v5.2.0 → v5.2.2 (fixes GO-2025-3553 header parsing memory alloc)
- quic-go v0.54.0 → v0.57.0 (fixes GO-2025-4233 HTTP/3 QPACK DoS)

Frontend refactor:
- Extract WelcomeScreen component (welcome state + suggestion cards)
- Extract ChatMessages component (message list with avatars + streaming)
- Extract ChatInput component (textarea + send button + Cmd+K shortcut)
- AgentChatPage: 825 → 480 lines

Note: 3 stdlib vulns (GO-2026-4599/4600/4601) require Go 1.26.1 upgrade
2026-03-23 10:44:18 +08:00
shinchan-zhai
ef438b4240 docs: update nofxi-tasks.md — record complete panic recovery coverage 2026-03-23 10:30:32 +08:00
shinchan-zhai
5e06037fa2 reliability: wrap all 27 bare goroutines with safe.Go/GoNamed panic recovery
Applied safe.GoNamed to:
- 9 exchange order_sync goroutines (OKX, Hyperliquid, Aster, Bybit, KuCoin, Gate, Bitget, Lighter, Binance×2)
- Drawdown monitor (auto_trader_risk.go)
- Brain news scanner + market briefs (agent/brain.go)
- Sentinel scanner (agent/sentinel.go)
- Agent scheduler (agent/scheduler.go)
- x402 idle watchdog (mcp/payment/x402.go)
- MCP stream idle watchdog (mcp/client.go)
- Rate limiter cleanup (api/rate_limiter.go)
- 3 telemetry fire-and-forget sends (telemetry/experience.go)
- CoinAnk WS handler (provider/coinank/coinank_api/kline_ws.go)
- API server goroutine (main.go)

Added manual defer/recover with error reporting to:
- Telegram AI agent handler (sends error msg to user on panic)
- Trader data fetch (returns error result on panic to prevent deadlock)

Before: a panic in ANY of these 27 goroutines would crash the entire
trading process with zero diagnostics. Now all panics are caught, logged
with stack traces, and the process continues running.
2026-03-23 10:30:13 +08:00
shinchan-zhai
07b4f30b85 docs: update nofxi-tasks.md — record 10:07 batch progress 2026-03-23 10:15:41 +08:00
shinchan-zhai
6a2cb9bbef security+reliability: remove public decrypt endpoint, add panic recovery for goroutines
Security:
- Remove /api/crypto/decrypt from public routes. The endpoint allowed
  anyone to decrypt ciphertext without authentication. Internal callers
  (exchange/model handlers) use the service directly and are behind auth.

Reliability:
- Add safe.Go / safe.GoNamed panic recovery wrapper (safe/go.go).
  Previously 31 goroutines had zero recover() calls — a single panic
  in any trader goroutine would crash the entire process.
- Apply safe.GoNamed to all trader launch paths:
  - StartAll, RestoreRunning, LoadSingleTrader auto-start
  - API handler start/restart endpoints
- Panics are now logged with full stack traces instead of crashing.
2026-03-23 10:15:02 +08:00
shinchan-zhai
21504bc392 refactor: propagate request context in kline handlers, extract MessageRenderer component
- handler_klines.go: pass c.Request.Context() to all external API calls
  instead of context.Background(). Client disconnects now cancel upstream
  requests to CoinAnk, Alpaca, TwelveData, Hyperliquid.
- Extract renderMessageContent + renderInline into
  components/agent/MessageRenderer.tsx (187 lines).
  AgentChatPage.tsx reduced from 1009 → 825 lines.
2026-03-23 10:11:17 +08:00
shinchan-zhai
cbf78e6b88 docs: update nofxi-tasks.md — mark completed, clean false positives 2026-03-23 09:54:53 +08:00
shinchan-zhai
52b9e4e645 fix: news seen map eviction strategy — keep half instead of clearing all
Previously when the seen map exceeded 1000 entries, ALL entries were
deleted, losing dedup state and causing re-notifications. Now evicts
~half the entries, preserving recent URLs for dedup continuity.
2026-03-23 09:54:31 +08:00
shinchan-zhai
f26a69d222 security: configurable CORS origins, limit sentinel response body
- Add CORS_ALLOWED_ORIGINS config (comma-separated origins, default allow-all)
- CORS middleware now validates Origin header against allowlist
- Add io.LimitReader to sentinel.go (was unbounded, now 256KB)
- Include previous: agent chat auth middleware + frontend token header
2026-03-23 09:53:49 +08:00
shinchan-zhai
7b602e70e6 security: sanitize markdown link URLs to prevent javascript: XSS
Only allow http/https URLs in rendered markdown links. Replace any
non-http(s) URL with '#' to prevent potential javascript: URI attacks.
2026-03-23 09:44:32 +08:00
shinchan-zhai
9c49a4c8cc security: login rate limiting, fix health endpoint, harden error handling
- Fix health endpoint returning null time (use time.Now() instead of context value)
- Add LoginRateLimiter: 5 attempts per 15min window, 5min block on brute-force
- Apply rate limiting to login/register endpoints
- Move reset-password to authenticated routes (was unauthenticated — critical vuln)
- Limit response body sizes on proxy/external API calls (prevent memory exhaustion)
- Sanitize error messages in agent chat endpoint (don't leak internal errors)
- Record login success/failure for rate limiting tracking
2026-03-23 09:43:20 +08:00
shinchan-zhai
0030639ec5 chore: remove ~100 debug console.log statements from frontend
Cleaned up verbose debug logging left from development:
- AdvancedChart.tsx: removed ~50 debug logs (time parsing, order fetching, marker creation)
- ChartWithOrders.tsx: removed debug logs and unused klineMinTime/klineMaxTime variables
- ChartWithOrdersSimple.tsx: removed data loading debug logs
- ChartTabs.tsx: removed render/selection debug logs
- ComparisonChart.tsx: removed equity history debug logs
- AITradersPage.tsx: removed 🔥 DEBUG logs from handleSaveEditTrader
- App.tsx: removed mount debug log

Kept legitimate console.error/console.warn for actual error handling.
2026-03-23 09:31:37 +08:00
shinchan-zhai
59e7e37db1 fix: enforce tool-based data only — Agent can no longer fabricate prices
- System prompt now has absolute rule: no tool result = no price
- Pre-market overview must call search_stock for each major stock
- Index futures explicitly marked as unsupported
- Training data prices explicitly declared outdated and forbidden
- Applied to both CN and EN prompts
2026-03-23 09:28:06 +08:00
shinchan-zhai
f37c63f9bb fix: prevent Agent from fabricating position/balance data
- Add strict data truthfulness rules to system prompt (CN + EN)
- Positions MUST come from get_positions tool only
- Balance MUST come from get_balance tool only
- Looking up a stock price != user owns it
- Fix unused variable warnings in hyperliquid trader
2026-03-23 09:25:58 +08:00
shinchan-zhai
4fff212dcd feat: US stock pre-market/after-hours data support
- Parse extended hours fields from Sina Finance API (field 21-24)
- Display pre-market/after-hours price, change%, and time in stock quotes
- Update system prompt: stocks have real-time data via search_stock tool
- Remove incorrect 'no real-time stock data' disclaimer
2026-03-23 09:20:38 +08:00
shinchan-zhai
7d79be02e0 fix: root route shows Agent page instead of LandingPage
- / now defaults to AgentChatPage (NOFXi's main interface)
- Agent page accessible without login
- LandingPage only shown at /landing or for non-agent pages when not logged in
2026-03-23 09:14:34 +08:00
shinchan-zhai
e4a59f36ed feat(ui): final polish — ChatGPT-style welcome screen, enhanced markdown, typing indicator
- Welcome state: centered greeting with 4 suggestion cards (ChatGPT style grid)
- Enhanced markdown: headers, numbered/bullet lists, links, italic, HR support
- Typing indicator: bouncing dots animation while waiting for response
- Refined dark theme: subtle rgba borders, backdrop blur, better contrast hierarchy
- Improved sidebar: slimmer 280px, glass morphism effect, smoother hover states
- MarketTicker: crypto icons (₿/Ξ/◎), skeleton loading, monospace prices
- Input area: ArrowUp send icon, ⌘K shortcut hint, focus ring glow
- Keyboard shortcuts: Cmd+K focus input, Esc close mobile sidebar
- Custom scrollbar styling, hidden scrollbar for quick actions bar
- Removed initial bot message in favor of interactive welcome state
2026-03-23 03:25:43 +08:00
shinchan-zhai
27fab11b68 chore: remove legacy nofxi/ subdirectory
All functionality has been migrated to the top-level agent/ package.
The old nofxi/ code was fully self-contained with no external references.
Integration plan doc preserved in docs/nofx-integration-plan.md.

Removed 35 files, ~4400 lines of dead code.
2026-03-23 03:08:07 +08:00
shinchan-zhai
d8d136ced6 feat: dynamic stock search via Sina suggest API
- Add searchStock() using Sina's suggest API (type=11,31,41)
- Supports A-share, HK, and US markets dynamically
- No longer limited to hardcoded knownStocks map
- resolveStockCodeDynamic: tries static map first, then API fallback
- extractStockKeyword: smart keyword extraction from natural language
- New LLM tool 'search_stock': agent can proactively search stocks
- Top 3 search results auto-enriched with real-time quotes
- System prompts updated for both zh/en
2026-03-23 02:54:20 +08:00
shinchan-zhai
203d5b4d14 feat: wire NOFXi Agent into Telegram bot
- Add NOFXiAgent interface and SetNOFXiAgent() in telegram/bot.go
- Telegram messages now route through the unified agent.Agent
  instead of the legacy telegram/agent package
- Language hint injected from Telegram config for proper i18n
- Legacy telegram/agent path preserved as fallback
- Agent created before Telegram bot starts in main.go
- Build verified, API tested
2026-03-23 02:39:02 +08:00
shinchan-zhai
4fa375771d feat(agent): LLM tool-calling for auto trade execution
- New agent/tools.go: defines LLM tools (execute_trade, get_positions,
  get_balance, get_market_price)
- thinkAndAct now uses CallWithRequestFull with tool-calling loop
  (max 5 rounds) — LLM autonomously decides when to call tools
- Trade safety: execute_trade creates pending orders requiring user
  confirmation ('确认 trade_xxx' / 'confirm trade_xxx')
- Pending trades expire after 5 minutes
- System prompt updated with tool usage instructions and safety rules
- Both paths work: regex shortcut ('做多 BTC 0.01') and natural
  language ('帮我开一个BTC多单') via LLM tool calling
- Fallback: if tool-calling fails, degrades to plain LLM call
2026-03-23 02:27:25 +08:00
shinchan-zhai
752e90dbe2 feat: add multi-turn conversation memory to Agent
- Add chatHistory store (in-memory, per user, last 20 messages)
- Agent now passes full conversation context to LLM via CallWithRequest
- Records both user messages and assistant responses
- Add /clear command to reset conversation history
- Add 'Clear' quick action button in frontend
- Supports natural multi-turn conversations (follow-up questions, context)
2026-03-23 02:13:26 +08:00
shinchan-zhai
a41ee3ca3d feat: redesign AgentChatPage - Agent-centric UI with side panels
- Rewrite AgentChatPage as primary interface with Perplexity-style layout
- Add right sidebar with Market Ticker, Positions, and Trader Status panels
- Sidebar is collapsible and responsive (auto-hides on mobile)
- Each sidebar section independently collapsible
- Chat area: centered 720px max-width with smooth streaming effect
- Simple markdown rendering (bold, code blocks, inline code)
- Quick action chips redesigned as pill buttons with hover effects
- Input upgraded to auto-resizing textarea
- New components: MarketTicker, PositionsPanel, TraderStatusPanel
- Dark theme consistent with NOFXi brand colors
- Real-time data via SWR for positions and trader status
2026-03-23 02:10:48 +08:00
shinchan-zhai
5382e89cae feat: real-time data for A-shares, HK stocks, and US stocks
Data source: Sina Finance API (free, no key needed)
- A股: sh/sz prefix, GBK→UTF-8, 30+ fields
- 港股: hk prefix, different field layout
- 美股: gb_ prefix, USD prices

Coverage:
- 20+ A-share stocks (拓维信息/贵州茅台/比亚迪/宁德时代...)
- 12 HK stocks (腾讯/阿里/美团/小米/京东...)
- 20 US tickers (AAPL/TSLA/NVDA/MSFT/GOOGL/AMZN...)
- Auto-detect 6-digit A-share codes, 5-digit HK codes
- US ticker symbols recognized (TSLA, AAPL, etc.)

All three markets tested:
- A股 拓维信息: ¥35.57 (-6.71%) 
- 港股 腾讯: HK$510.50 (-0.49%) 
- 美股 TSLA: $367.96 (-3.24%) 
2026-03-23 01:44:28 +08:00
shinchan-zhai
bd6fe6bd6d feat: real-time A-share stock data via Sina Finance API
NOFXi can now fetch REAL stock prices for A-shares.

Data source: Sina Finance hq.sinajs.cn (free, no API key)
- Name, price, open, prev close, high, low, volume, turnover
- Change % calculated from prev close
- GBK → UTF-8 encoding handled

Stock resolution:
- Known stocks: 拓维信息→sz002261, 贵州茅台→sh600519, etc.
- Auto-detect 6-digit codes in user text
- Prefix detection: 6xx→sh, 0xx/3xx→sz

Context injection:
- Stock data auto-appended to LLM context when user mentions a stock
- AI sees REAL price, volume, change % — cannot fabricate

Tested: '拓维信息这只股,10万元,1个月交易计划'
→ Returns ¥35.57 (real price), -6.71% (real change), 53.94亿成交额
→ Strategy based on actual price levels, not hallucinated
2026-03-23 01:41:40 +08:00
shinchan-zhai
c04579108f fix: AI no longer fabricates prices for assets without real-time data
System prompt now explicitly:
- Lists which assets have real-time data (crypto) and which don't (stocks/forex)
- FORBIDS fabricating specific prices
- Requires disclosure: 'based on historical knowledge, not live data'
- Allows strategy frameworks but not fake price levels

Tested: 拓维信息 → now says '我没有A股实时数据' upfront, gives
strategy framework without fake prices. Honesty > confidence.
2026-03-23 01:38:26 +08:00
shinchan-zhai
60d12a3151 fix: bypass SSRF DNS resolver for AI API calls
SSRF protection was blocking AI API calls because Go's custom resolver
couldn't resolve external domains (DNS timeout). curl worked because it
uses the system resolver.

Fix: Agent creates MCP client with standard http.Client (no SSRF filter)
since we control the API URLs.

Tested: '帮我看看拓维信息这只股,我有10万元,帮我制定1个月交易计划'
→ Returns professional A-share analysis with entry/exit strategy in 5.8s
2026-03-23 01:30:14 +08:00
shinchan-zhai
ac958efe48 refactor: delete router.go — LLM is the brain, not regex
DELETED: agent/router.go (regex-based intent routing)

The fundamental architecture was wrong. A real AI Agent doesn't use
pattern matching to understand users. It uses AI.

New flow:
1. User says anything
2. /help and /status → instant response (no AI needed)
3. Setup keywords → onboard flow
4. EVERYTHING else → LLM with full context

The LLM receives:
- System prompt with NOFXi's capabilities and behavior rules
- Real-time market data (auto-detected from mentioned symbols)
- Live trader positions and status
- User's message

The LLM decides what to do. Not regex. Not if-else. The AI.

This is what makes it an Agent, not a chatbot.
2026-03-23 01:21:00 +08:00
shinchan-zhai
52f6f15ebe fix: smart routing + auto AI client from store
1. Complex natural language → AI chat (not regex analyze)
   '拓维信息这个股怎么样帮我写策略' now goes to AI, not broken regex

2. Agent auto-loads AI client from store on startup
   - Scans AIModel configs, creates MCP client from first available
   - No manual injection needed

3. Added start.sh for one-command startup (backend + frontend)

Routing logic:
- /analyze BTC (simple, ≤3 words) → structured analyze
- Complex sentences → AI chat with full context
- This is the key insight: regex can't parse natural language, AI can
2026-03-23 01:15:07 +08:00