Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

v3.3.1

tilakpatel22bfd764d39d76
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py
index 7fc5fc2b3..15adb3bd3 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py
@@ -594,14 +594,11 @@ class CoreAgent:
# tool_call_limit caps how many tool iterations the agent
# can make per run, preventing infinite loops while still
# allowing multi-step autonomous tool use.
- # stream_intermediate_steps surfaces each tool call as it happens.
# =================================================================
if all_tools:
# Cap tool call iterations — default 10, max 20
max_iter = min(int(config.get("max_iterations", 10)), 20)
agent_kwargs["tool_call_limit"] = max_iter
- # Surface intermediate reasoning/tool steps in streaming
- agent_kwargs["stream_intermediate_steps"] = True
# =================================================================
# 10. Output Settings
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py
index a9364c0ab..10fa397ad 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py
@@ -112,10 +112,11 @@ def main(args=None):
# Check for streaming mode
streaming = "--stream" in args
- args = [a for a in args if a != "--stream"]
+ use_stdin = "--stdin" in args
+ args = [a for a in args if a not in ("--stream", "--stdin")]
try:
- if len(args) == 0:
+ if use_stdin or len(args) == 0:
# Read payload from stdin (used when payload is too large for argv)
payload_str = sys.stdin.read().strip()
if not payload_str:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py
index 80f181279..f3b7a0e33 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py
@@ -1,4 +1,4 @@
-"""
+"""
Fincept LLM Model - Custom adapter for Fincept's built-in LLM endpoint.
The /research/llm endpoint wraps GLM (via Anthropic API format at z.ai):
@@ -17,6 +17,8 @@ This adapter:
import httpx
import json
import logging
+import threading
+import time
from dataclasses import dataclass
from typing import Any, Optional, Dict, List, Iterator, AsyncIterator
@@ -26,6 +28,57 @@ from agno.models.response import ModelResponse
logger = logging.getLogger(__name__)
+# ── Cross-process rate limiter: max 1 request/second to Fincept endpoint ──────
+# Uses a lock file so multiple Python subprocesses (AI panel + Agent panel)
+# share the same rate limit rather than each having their own in-memory counter.
+import os
+import tempfile
+
+_RATE_LOCK_FILE = os.path.join(tempfile.gettempdir(), "fincept_llm_rate.lock")
+_RATE_TS_FILE = os.path.join(tempfile.gettempdir(), "fincept_llm_rate.ts")
+_fincept_proc_lock = threading.Lock() # within-process serialisation
+
+def _rate_limit_fincept() -> None:
+ """
+ Block until at least 1.2 seconds have passed since the last call
+ across ALL Python processes on this machine.
+ Uses an exclusive file lock + a shared timestamp file.
+ """
+ with _fincept_proc_lock:
+ # Acquire the cross-process file lock
+ while True:
+ try:
+ fd = os.open(_RATE_LOCK_FILE, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
+ os.close(fd)
+ break # we hold the lock
+ except FileExistsError:
+ time.sleep(0.05)
+
+ try:
+ # Read last call timestamp
+ last_ts = 0.0
+ try:
+ with open(_RATE_TS_FILE, "r") as f:
+ last_ts = float(f.read().strip())
+ except Exception:
+ pass
+
+ # Wait until 2.0 s have elapsed since last call
+ now = time.time()
+ wait = 2.0 - (now - last_ts)
+ if wait > 0:
+ time.sleep(wait)
+
+ # Write current timestamp
+ with open(_RATE_TS_FILE, "w") as f:
+ f.write(str(time.time()))
+ finally:
+ # Always release the file lock
+ try:
+ os.remove(_RATE_LOCK_FILE)
+ except Exception:
+ pass
+
FINCEPT_DEFAULT_URL = "https://finceptbackend.share.zrok.io/research/llm"
@@ -124,7 +177,8 @@ class FinceptChat(Model):
max_tokens: Optional[int] = None
# Max tool call rounds before forcing a final answer
- max_tool_rounds: int = 8
+ # Keep low for Fincept endpoint — each round = 1 API call, gateway times out after ~60s
+ max_tool_rounds: int = 5
# ── HTTP request ──────────────────────────────────────────────────────────
@@ -141,6 +195,8 @@ class FinceptChat(Model):
Returns the full data dict:
{"response": str, "tool_calls": [...], "model": str, ...}
"""
+ _rate_limit_fincept()
+
headers = {"Content-Type": "application/json"}
if self.api_key:
headers["X-API-Key"] = self.api_key
@@ -160,35 +216,61 @@ class FinceptChat(Model):
if tool_choice:
payload["tool_choice"] = tool_choice
- try:
- with httpx.Client(timeout=120.0) as client:
- resp = client.post(self.base_url, json=payload, headers=headers)
-
- if resp.status_code != 200:
- error_detail = ""
- try:
- err_data = resp.json()
- error_detail = err_data.get("detail", err_data.get("message", ""))
- except Exception:
- error_detail = resp.text[:200]
- raise RuntimeError(
- f"Fincept API error ({resp.status_code}): {error_detail}"
- )
+ last_error: Optional[RuntimeError] = None
+ for attempt in range(3):
+ try:
+ with httpx.Client(timeout=120.0) as client:
+ resp = client.post(self.base_url, json=payload, headers=headers)
+
+ if resp.status_code == 429:
+ # Rate limited — wait longer and retry (don't call _rate_limit_fincept
+ # here since that would update the shared timestamp without a real call)
+ wait = 5.0 * (attempt + 1) # 5s, 10s, 15s
+ logger.warning(f"FinceptChat: 429 rate limit on attempt {attempt + 1}, waiting {wait}s")
+ time.sleep(wait)
+ last_error = RuntimeError(
+ f"Fincept API error (429): rate limit hit after {attempt + 1} attempts"
+ )
+ continue
+
+ if resp.status_code in (502, 504):
+ wait = 3.0 * (attempt + 1) # 3s, 6s, 9s
+ logger.warning(f"FinceptChat: {resp.status_code} on attempt {attempt + 1}, waiting {wait}s")
+ time.sleep(wait)
+ last_error = RuntimeError(
+ f"Fincept API error ({resp.status_code}): gateway error"
+ )
+ continue
+
+ if resp.status_code != 200:
+ error_detail = ""
+ try:
+ err_data = resp.json()
+ error_detail = err_data.get("detail", err_data.get("message", ""))
+ except Exception:
+ error_detail = resp.text[:200]
+ raise RuntimeError(
+ f"Fincept API error ({resp.status_code}): {error_detail}"
+ )
+
+ outer = resp.json()
+ # Unwrap: {"success": true, "data": {...}}
+ if isinstance(outer, dict) and "data" in outer:
+ return outer["data"]
+ return outer
+
+ except httpx.TimeoutException:
+ last_error = RuntimeError("Fincept API request timed out (120s)")
+ logger.warning(f"FinceptChat: timeout on attempt {attempt + 1}")
+ continue
+ except httpx.ConnectError as e:
+ raise RuntimeError(f"Cannot connect to Fincept API: {e}")
+ except RuntimeError:
+ raise
+ except Exception as e:
+ raise RuntimeError(f"Fincept API call failed: {e}")
- outer = resp.json()
- # Unwrap: {"success": true, "data": {...}}
- if isinstance(outer, dict) and "data" in outer:
- return outer["data"]
- return outer
-
- except httpx.TimeoutException:
- raise RuntimeError("Fincept API request timed out (120s)")
- except httpx.ConnectError as e:
- raise RuntimeError(f"Cannot connect to Fincept API: {e}")
- except RuntimeError:
- raise
- except Exception as e:
- raise RuntimeError(f"Fincept API call failed: {e}")
+ raise last_error or RuntimeError("Fincept API failed after 3 attempts")
# ── Tool execution ────────────────────────────────────────────────────────
@@ -235,12 +317,11 @@ class FinceptChat(Model):
# ── Native function-calling loop ──────────────────────────────────────────
- # Fincept endpoint hard limit is 50k chars.
- # We target 35k for the full prompt (prompt + tool context),
- # leaving headroom for system instructions and response.
- _PROMPT_CHAR_BUDGET = 35_000
+ # Fincept endpoint hard limit is ~50k chars, but gateway times out on large prompts.
+ # Keep the full prompt (query + tool context) under 20k chars to stay fast.
+ _PROMPT_CHAR_BUDGET = 20_000
# Per-tool-result cap — prevents a single large result from dominating
- _TOOL_RESULT_CAP = 4_000
+ _TOOL_RESULT_CAP = 2_000
def _run_tool_loop(
self,
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/tools/terminal_toolkit.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/tools/terminal_toolkit.py
index 74551a540..528e6a094 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/tools/terminal_toolkit.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/tools/terminal_toolkit.py
@@ -42,7 +42,7 @@ class TerminalToolkit:
self,
endpoint: str,
tool_definitions: List[Dict[str, Any]],
- timeout_seconds: int = 30,
+ timeout_seconds: int = 85,
**kwargs,
):
self.endpoint = endpoint.rstrip("/")
diff --git a/fincept-terminal-desktop/src-tauri/src/mcp_bridge.rs b/fincept-terminal-desktop/src-tauri/src/mcp_bridge.rs
index 5d81e1b99..d14b93f15 100644
--- a/fincept-terminal-desktop/src-tauri/src/mcp_bridge.rs
+++ b/fincept-terminal-desktop/src-tauri/src/mcp_bridge.rs
@@ -182,7 +182,8 @@ fn handle_tool_call(
return;
}
- // Wait for TypeScript to call register_mcp_tool_result (max 30 seconds).
+ // Wait for TypeScript to call register_mcp_tool_result (max 90 seconds).
+ // Economics tools (CEIC, central bank rates) can take 15-30s each.
// We're on a std thread (not a tokio task), so we create a minimal runtime.
let result = {
let rt = tokio::runtime::Builder::new_current_thread()
@@ -190,7 +191,7 @@ fn handle_tool_call(
.build()
.expect("mini runtime for MCP bridge");
rt.block_on(async {
- tokio::time::timeout(std::time::Duration::from_secs(30), rx).await
+ tokio::time::timeout(std::time::Duration::from_secs(90), rx).await
})
};
diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/hooks/useAgentConfig.ts b/fincept-terminal-desktop/src/components/tabs/agent-config/hooks/useAgentConfig.ts
index 094de41a3..f7873d2db 100644
--- a/fincept-terminal-desktop/src/components/tabs/agent-config/hooks/useAgentConfig.ts
+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/hooks/useAgentConfig.ts
@@ -16,6 +16,7 @@ import {
getLLMConfigs,
getActiveLLMConfig,
getAgentConfigs,
+ getSetting,
LLM_PROVIDERS as DB_LLM_PROVIDERS,
type AgentConfigData,
} from '@/services/core/sqliteService';
@@ -442,6 +443,16 @@ export function useAgentConfig() {
apiKeys[`${config.provider}_base_url`] = config.base_url;
}
}
+ // Always include the Fincept session API key (saved on login) so
+ // the finagent_core Python agent can use the fincept provider even
+ // if the user hasn't manually added it in LLM Settings.
+ if (!apiKeys['fincept']) {
+ const finceptKey = await getSetting('fincept_api_key');
+ if (finceptKey) {
+ apiKeys['fincept'] = finceptKey;
+ apiKeys['FINCEPT_API_KEY'] = finceptKey;
+ }
+ }
return apiKeys;
} catch (err) {
console.error('[useAgentConfig] Failed to get API keys:', err);
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx
index b8c219482..a97baeaa1 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx
@@ -4,14 +4,16 @@
* Thin shell composing modular sub-components
*/
-import React, { useState, useCallback, useMemo } from 'react';
+import React, { useState, useCallback, useMemo, useRef } from 'react';
import { useEffect } from 'react';
import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';
import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { Briefcase, RefreshCw, Bot, X } from 'lucide-react';
+import { Briefcase, RefreshCw, Bot, X, ChevronDown } from 'lucide-react';
import { FINCEPT, COMMON_STYLES } from './finceptStyles';
import agentService from '@/services/agentService';
-import { sqliteService } from '@/services/core/sqliteService';
+import { sqliteService, getSetting, getAgentConfigs } from '@/services/core/sqliteService';
+import type { AgentConfig } from '@/services/core/sqliteService';
+import MarkdownRenderer from '@/components/common/MarkdownRenderer';
import { usePortfolioOperations } from './hooks/usePortfolioOperations';
import { usePortfolioMetrics } from './hooks/usePortfolioMetrics';
import { useModalState } from './hooks/useModalState';
@@ -61,6 +63,96 @@ const PortfolioTab: React.FC = () => {
const [aiAnalyzing, setAiAnalyzing] = useState(false);
const [aiResult, setAiResult] = useState<string | null>(null);
const [showAiPanel, setShowAiPanel] = useState(false);
+ const [aiAnalysisType, setAiAnalysisType] = useState<'full' | 'risk' | 'rebalance' | 'opportunities'>('full');
+ // Cache: keyed by analysisType, cleared when portfolio changes
+ const aiResultCache = useRef<Record<string, string>>({});
+ const agentResultCache = useRef<Record<string, string>>({});
+ const lastPortfolioId = useRef<string | null>(null);
+
+ // ── Agent Runner state ──
+ const [agentRunning, setAgentRunning] = useState(false);
+ const [agentResult, setAgentResult] = useState<string | null>(null);
+ const [showAgentPanel, setShowAgentPanel] = useState(false);
+ const [savedAgents, setSavedAgents] = useState<AgentConfig[]>([]);
+ const [selectedAgentId, setSelectedAgentId] = useState<string>('');
+
+ // Load saved agents once on mount
+ useEffect(() => {
+ getAgentConfigs().then(agents => {
+ setSavedAgents(agents);
+ if (agents.length > 0) setSelectedAgentId(agents[0].id);
+ }).catch(() => {});
+ }, []);
+
+ // ── Run saved agent on portfolio ──
+ const handleRunAgent = useCallback(async (forceRefresh = false) => {
+ if (!portfolioSummary || agentRunning) return;
+ setShowAgentPanel(true);
+ if (!selectedAgentId) return;
+ const agentCfgRow = savedAgents.find(a => a.id === selectedAgentId);
+ if (!agentCfgRow) return;
+ // Show cached result immediately if available
+ if (!forceRefresh && agentResultCache.current[selectedAgentId]) {
+ setAgentResult(agentResultCache.current[selectedAgentId]);
+ return;
+ }
+ setAgentRunning(true);
+ setAgentResult(null);
+
+ try {
+ const agentCfg = JSON.parse(agentCfgRow.config_json || '{}');
+
+ // Build api keys
+ const llmConfigs = await sqliteService.getLLMConfigs();
+ const apiKeys: Record<string, string> = {};
+ for (const cfg of llmConfigs) {
+ if (cfg.api_key) {
+ apiKeys[cfg.provider.toUpperCase() + '_API_KEY'] = cfg.api_key;
+ apiKeys[cfg.provider] = cfg.api_key;
+ apiKeys[cfg.provider.toLowerCase()] = cfg.api_key;
+ }
+ if (cfg.base_url) {
+ apiKeys[cfg.provider.toUpperCase() + '_BASE_URL'] = cfg.base_url;
+ apiKeys[cfg.provider + '_base_url'] = cfg.base_url;
+ }
+ }
+ if (!apiKeys['fincept']) {
+ const finceptKey = await getSetting('fincept_api_key');
+ if (finceptKey) { apiKeys['fincept'] = finceptKey; apiKeys['FINCEPT_API_KEY'] = finceptKey; }
+ }
+
+ // Build portfolio context to prepend to the agent query
+ const portfolioHoldings = portfolioSummary.holdings || [];
+ const holdingsSummary = portfolioHoldings.map((h: any) =>
+ h.symbol + ': ' + h.quantity + ' units @ $' + (h.current_price || 0).toFixed(2) +
+ ' | Weight: ' + (h.weight || 0).toFixed(1) + '%'
+ ).join('\n');
+ const portfolioContext = [
+ '=== PORTFOLIO CONTEXT ===',
+ 'Portfolio: ' + (portfolioSummary.portfolio?.name || 'Unknown'),
+ 'NAV: ' + currency + ' ' + portfolioSummary.total_market_value.toFixed(2),
+ 'Holdings (' + portfolioHoldings.length + '):',
+ holdingsSummary,
+ '========================',
+ '',
+ 'Please analyze the portfolio above and provide actionable insights.',
+ ].join('\n');
+
+ const result = await agentService.runAgent(
+ portfolioContext,
+ { ...agentCfg, markdown: true },
+ apiKeys
+ );
+
+ const agentText = result.response || result.error || 'No response returned.';
+ agentResultCache.current[selectedAgentId] = agentText;
+ setAgentResult(agentText);
+ } catch (err: any) {
+ setAgentResult('Agent run failed: ' + (err?.message || 'Unknown error'));
+ } finally {
+ setAgentRunning(false);
+ }
+ }, [portfolioSummary, agentRunning, selectedAgentId, savedAgents, currency]);
// Auto-select highest weighted holding when holdings change
useEffect(() => {
@@ -108,22 +200,28 @@ const PortfolioTab: React.FC = () => {
}, []);
// ── AI portfolio analysis ──
- const handleAnalyzeWithAI = useCallback(async () => {
+ const handleAnalyzeWithAI = useCallback(async (forceRefresh = false) => {
if (!portfolioSummary || aiAnalyzing) return;
- setAiAnalyzing(true);
+ // Invalidate cache if portfolio changed
+ const currentPortfolioId = portfolioSummary.portfolio?.id ?? 'unknown';
+ if (lastPortfolioId.current !== currentPortfolioId) {
+ aiResultCache.current = {};
+ agentResultCache.current = {};
+ lastPortfolioId.current = currentPortfolioId;
+ }
+ // Always open the panel
setShowAiPanel(true);
+ // If we have a cached result and not forcing refresh, show it immediately
+ if (!forceRefresh && aiResultCache.current[aiAnalysisType]) {
+ setAiResult(aiResultCache.current[aiAnalysisType]);
+ return;
+ }
+ setAiAnalyzing(true);
setAiResult(null);
try {
- // Load active LLM config from DB (same pattern as Agent Config tab)
const llmConfigs = await sqliteService.getLLMConfigs();
- const activeLLM = llmConfigs.find(c => c.is_active) ?? llmConfigs[0] ?? null;
- if (!activeLLM) {
- setAiResult('No LLM configured. Please add a model in Settings → LLM Configuration.');
- return;
- }
-
- // Build apiKeys map (same as useAgentConfig.getApiKeys)
+ // Build apiKeys from LLM configs
const apiKeys: Record<string, string> = {};
for (const cfg of llmConfigs) {
if (cfg.api_key) {
@@ -137,26 +235,42 @@ const PortfolioTab: React.FC = () => {
}
}
- // Build AgentConfig using active LLM
+ // Always include the Fincept session key (available to every logged-in user)
+ if (!apiKeys['fincept']) {
+ const finceptKey = await getSetting('fincept_api_key');
+ if (finceptKey) {
+ apiKeys['fincept'] = finceptKey;
+ apiKeys['FINCEPT_API_KEY'] = finceptKey;
+ }
+ }
+
+ // Resolve which LLM to use — prefer active, fall back to fincept
+ const activeLLM = llmConfigs.find(c => c.is_active) ?? llmConfigs[0] ?? null;
+ const provider = activeLLM?.provider ?? 'fincept';
+ const model_id = activeLLM?.model ?? 'fincept-llm';
+
+ if (!activeLLM && !apiKeys['fincept']) {
+ setAiResult('No LLM configured. Please add a model in Settings → LLM Configuration.');
+ return;
+ }
+
const agentConfig = {
- model: {
- provider: activeLLM.provider,
- model_id: activeLLM.model,
- temperature: 0.7,
- max_tokens: 4096,
- },
- instructions: 'You are a professional portfolio analyst with CFA-level expertise. Provide clear, actionable financial analysis.',
+ model: { provider, model_id, temperature: 0.3 },
+ instructions: 'You are a professional portfolio analyst with CFA-level expertise. Use ALL available tools to gather live data before making recommendations. Cite specific numbers in your analysis.',
tools: [],
+ markdown: true,
};
- const result = await agentService.runPortfolioAnalysis(portfolioSummary, 'full', apiKeys, agentConfig);
- setAiResult(result.response || result.error || 'No analysis returned.');
+ const result = await agentService.runPortfolioAnalysis(portfolioSummary, aiAnalysisType, apiKeys, agentConfig);
+ const analysisText = result.response || result.error || 'No analysis returned.';
+ aiResultCache.current[aiAnalysisType] = analysisText;
+ setAiResult(analysisText);
} catch (err: any) {
setAiResult(`Analysis failed: ${err?.message || 'Unknown error'}`);
} finally {
setAiAnalyzing(false);
}
- }, [portfolioSummary, aiAnalyzing]);
+ }, [portfolioSummary, aiAnalyzing, aiAnalysisType]);
return (
<div style={{
@@ -193,6 +307,8 @@ const PortfolioTab: React.FC = () => {
onToggleFFN={() => { setShowFFN(v => !v); setDetailView(null); }}
onAnalyzeWithAI={portfolioSummary ? handleAnalyzeWithAI : undefined}
aiAnalyzing={aiAnalyzing}
+ onRunAgent={portfolioSummary ? () => setShowAgentPanel(true) : undefined}
+ agentRunning={agentRunning}
detailView={detailView}
onSetDetailView={selectedPortfolio ? (view) => { setDetailView(view); if (view) setShowFFN(false); } : undefined}
/>
@@ -307,7 +423,7 @@ const PortfolioTab: React.FC = () => {
{showAiPanel && (
<div style={{
position: 'absolute', top: '40px', right: '12px', zIndex: 200,
- width: '420px', maxHeight: '70vh',
+ width: '480px', maxHeight: '75vh',
backgroundColor: '#0A0A0A', border: '1px solid #9D4EDD',
boxShadow: '0 8px 32px rgba(157,78,221,0.3)',
display: 'flex', flexDirection: 'column',
@@ -332,17 +448,187 @@ const PortfolioTab: React.FC = () => {
<X size={12} />
</button>
</div>
- {/* Content */}
- <div style={{
- flex: 1, overflowY: 'auto', padding: '12px',
- fontSize: '11px', color: '#FFFFFF', lineHeight: '1.6',
- whiteSpace: 'pre-wrap', fontFamily: '"IBM Plex Mono", monospace',
- }}>
+
+ {/* Analysis type selector */}
+ <div style={{ display: 'flex', borderBottom: '1px solid #2A2A2A', backgroundColor: '#0F0F0F' }}>
+ {(['full', 'risk', 'rebalance', 'opportunities'] as const).map(type => (
+ <button
+ key={type}
+ onClick={() => {
+ if (aiAnalyzing) return;
+ setAiAnalysisType(type);
+ // Show cached result immediately if available
+ if (aiResultCache.current[type]) {
+ setAiResult(aiResultCache.current[type]);
+ } else {
+ setAiResult(null);
+ }
+ }}
+ disabled={aiAnalyzing}
+ style={{
+ flex: 1, padding: '5px 4px',
+ backgroundColor: aiAnalysisType === type ? '#9D4EDD22' : 'transparent',
+ border: 'none',
+ borderBottom: aiAnalysisType === type ? '2px solid #9D4EDD' : '2px solid transparent',
+ color: aiAnalysisType === type ? '#9D4EDD' : '#787878',
+ fontSize: '8px', fontWeight: 700, letterSpacing: '0.5px',
+ cursor: aiAnalyzing ? 'wait' : 'pointer', textTransform: 'uppercase',
+ }}
+ >
+ {type === 'full' ? 'FULL' : type === 'risk' ? 'RISK' : type === 'rebalance' ? 'REBALANCE' : 'OPPORTUNITIES'}
+ </button>
+ ))}
+ </div>
+
+ {/* Run button when no result yet or to re-run */}
+ {!aiAnalyzing && (
+ <div style={{ padding: '6px 12px', borderBottom: '1px solid #1A1A1A', backgroundColor: '#080808' }}>
+ <button
+ onClick={() => {
+ // Clear cache entry so re-run fetches fresh data
+ delete aiResultCache.current[aiAnalysisType];
+ handleAnalyzeWithAI(true);
+ }}
+ style={{
+ width: '100%', padding: '5px',
+ backgroundColor: '#9D4EDD22', border: '1px solid #9D4EDD44',
+ color: '#9D4EDD', fontSize: '9px', fontWeight: 700,
+ letterSpacing: '0.5px', cursor: 'pointer',
+ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '5px',
+ }}
+ >
+ <Bot size={9} />
+ {aiResult ? `RE-RUN ${aiAnalysisType.toUpperCase()} ANALYSIS` : `RUN ${aiAnalysisType.toUpperCase()} ANALYSIS`}
+ </button>
+ </div>
+ )}
+
+ {/* Content — rendered markdown */}
+ <div style={{ flex: 1, overflowY: 'auto', padding: '12px' }}>
{aiAnalyzing ? (
- <div style={{ color: '#9D4EDD', opacity: 0.7 }}>Analyzing portfolio with AI agent...</div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', alignItems: 'center', paddingTop: '24px' }}>
+ <RefreshCw size={16} color="#9D4EDD" className="animate-spin" />
+ <span style={{ color: '#9D4EDD', fontSize: '10px', opacity: 0.8 }}>
+ Running {aiAnalysisType} analysis with live tools...
+ </span>
+ </div>
) : aiResult ? (
- aiResult
- ) : null}
+ <div style={{ fontSize: '11px', lineHeight: '1.6' }}>
+ <MarkdownRenderer content={aiResult} />
+ </div>
+ ) : (
+ <div style={{ color: '#555', fontSize: '10px', textAlign: 'center', paddingTop: '24px' }}>
+ Select an analysis type above and click Run.
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* ═══ AGENT RUNNER PANEL ═══ */}
+ {showAgentPanel && (
+ <div style={{
+ position: 'absolute', top: '40px', right: '508px', zIndex: 200,
+ width: '480px', maxHeight: '75vh',
+ backgroundColor: '#0A0A0A', border: '1px solid #00D4AA',
+ boxShadow: '0 8px 32px rgba(0,212,170,0.2)',
+ display: 'flex', flexDirection: 'column',
+ }}>
+ {/* Header */}
+ <div style={{
+ padding: '8px 12px', borderBottom: '1px solid #2A2A2A',
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
+ backgroundColor: '#00D4AA12',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Bot size={12} color="#00D4AA" />
+ <span style={{ fontSize: '10px', fontWeight: 800, color: '#00D4AA', letterSpacing: '1px' }}>
+ AGENT RUNNER
+ </span>
+ {agentRunning && <RefreshCw size={9} color="#00D4AA" className="animate-spin" />}
+ </div>
+ <button
+ onClick={() => setShowAgentPanel(false)}
+ style={{ background: 'none', border: 'none', color: '#787878', cursor: 'pointer', padding: '2px', display: 'flex' }}
+ >
+ <X size={12} />
+ </button>
+ </div>
+
+ {/* Agent selector */}
+ <div style={{ padding: '8px 12px', borderBottom: '1px solid #1A1A1A', backgroundColor: '#0D0D0D' }}>
+ <div style={{ fontSize: '8px', color: '#555', fontWeight: 700, letterSpacing: '0.5px', marginBottom: '4px' }}>SELECT AGENT</div>
+ <div style={{ position: 'relative' }}>
+ <select
+ value={selectedAgentId}
+ onChange={e => {
+ const newId = e.target.value;
+ setSelectedAgentId(newId);
+ if (agentResultCache.current[newId]) {
+ setAgentResult(agentResultCache.current[newId]);
+ } else {
+ setAgentResult(null);
+ }
+ }}
+ disabled={agentRunning}
+ style={{
+ width: '100%', padding: '5px 8px',
+ backgroundColor: '#0A0A0A', border: '1px solid #2A2A2A',
+ color: '#E0E0E0', fontSize: '10px', cursor: 'pointer',
+ appearance: 'none', outline: 'none',
+ }}
+ >
+ {savedAgents.length === 0 && (
+ <option value="">No agents saved — create one in Agent Config tab</option>
+ )}
+ {savedAgents.map(a => (
+ <option key={a.id} value={a.id}>
+ {a.name}{a.description ? ' — ' + a.description.slice(0, 40) : ''}
+ </option>
+ ))}
+ </select>
+ <ChevronDown size={10} color="#555" style={{ position: 'absolute', right: '8px', top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
+ </div>
+
+ {/* Run button */}
+ {!agentRunning && savedAgents.length > 0 && (
+ <button
+ onClick={() => {
+ if (agentResult) delete agentResultCache.current[selectedAgentId];
+ handleRunAgent(agentResult ? true : false);
+ }}
+ style={{
+ marginTop: '6px', width: '100%', padding: '5px',
+ backgroundColor: '#00D4AA22', border: '1px solid #00D4AA44',
+ color: '#00D4AA', fontSize: '9px', fontWeight: 700,
+ letterSpacing: '0.5px', cursor: 'pointer',
+ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '5px',
+ }}
+ >
+ <Bot size={9} />
+ {agentResult ? 'RE-RUN AGENT' : 'RUN AGENT ON PORTFOLIO'}
+ </button>
+ )}
+ </div>
+
+ {/* Result */}
+ <div style={{ flex: 1, overflowY: 'auto', padding: '12px' }}>
+ {agentRunning ? (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', alignItems: 'center', paddingTop: '24px' }}>
+ <RefreshCw size={16} color="#00D4AA" className="animate-spin" />
+ <span style={{ color: '#00D4AA', fontSize: '10px', opacity: 0.8 }}>
+ Agent is analyzing your portfolio...
+ </span>
+ </div>
+ ) : agentResult ? (
+ <div style={{ fontSize: '11px', lineHeight: '1.6' }}>
+ <MarkdownRenderer content={agentResult} />
+ </div>
+ ) : (
+ <div style={{ color: '#555', fontSize: '10px', textAlign: 'center', paddingTop: '24px' }}>
+ Select an agent above and click Run.
+ </div>
+ )}
</div>
</div>
)}
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/components/CommandBar.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/components/CommandBar.tsx
index 2489cf3f5..2c785a05f 100644
--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/components/CommandBar.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/components/CommandBar.tsx
@@ -34,6 +34,8 @@ interface CommandBarProps {
onToggleFFN?: () => void;
onAnalyzeWithAI?: () => void;
aiAnalyzing?: boolean;
+ onRunAgent?: () => void;
+ agentRunning?: boolean;
detailView?: DetailView | null;
onSetDetailView?: (view: DetailView | null) => void;
}
@@ -53,7 +55,7 @@ const DETAIL_VIEW_BUTTONS: { view: DetailView; label: string; icon: React.Elemen
const CommandBar: React.FC<CommandBarProps> = ({
portfolios, selectedPortfolio, onSelectPortfolio, portfolioSummary,
onCreatePortfolio, onDeletePortfolio, onBuy, onSell, onRefresh, onExport, onExportJSON, onImport, refreshing, currency,
- refreshIntervalMs, onSetRefreshInterval, showFFN, onToggleFFN, onAnalyzeWithAI, aiAnalyzing,
+ refreshIntervalMs, onSetRefreshInterval, showFFN, onToggleFFN, onAnalyzeWithAI, aiAnalyzing, onRunAgent, agentRunning,
detailView, onSetDetailView,
}) => {
const { t } = useTranslation('portfolio');
@@ -339,6 +341,26 @@ const CommandBar: React.FC<CommandBarProps> = ({
{aiAnalyzing ? 'ANALYZING...' : 'AI'}
</button>
)}
+ {onRunAgent && (
+ <button
+ onClick={onRunAgent}
+ disabled={agentRunning}
+ title="Run a saved agent on this portfolio"
+ style={{
+ padding: '5px 10px',
+ backgroundColor: agentRunning ? '#00D4AA22' : 'transparent',
+ border: '1px solid #00D4AA',
+ color: '#00D4AA',
+ cursor: agentRunning ? 'wait' : 'pointer',
+ display: 'flex', alignItems: 'center', gap: '4px',
+ fontSize: '9px', fontWeight: 700, letterSpacing: '0.5px',
+ opacity: agentRunning ? 0.7 : 1,
+ }}
+ >
+ <Bot size={10} className={agentRunning ? 'animate-pulse' : ''} />
+ {agentRunning ? 'RUNNING...' : 'AGENT'}
+ </button>
+ )}
</div>
)}
</div>
diff --git a/fincept-terminal-desktop/src/services/agentService.ts b/fincept-terminal-desktop/src/services/agentService.ts
index bae3918b6..b5841f3de 100644
--- a/fincept-terminal-desktop/src/services/agentService.ts
+++ b/fincept-terminal-desktop/src/services/agentService.ts
@@ -396,14 +396,20 @@ async function getTerminalToolDefinitions(): Promise<AgentConfig['terminal_tools
*/
async function execute<T = any>(payload: AgentPayload): Promise<AgentResponse<T>> {
try {
- // Inject terminal tool schemas for 'run' actions so Python can use TypeScript tools
+ // Inject terminal tool schemas for 'run' actions so Python can use TypeScript tools.
+ // Skip for Fincept provider — its endpoint has a ~50KB payload limit and terminal tools
+ // are not needed there (the Portfolio Analyst agent uses its own built-in MCP tools).
if (payload.action === 'run' && payload.config) {
- const terminalTools = await getTerminalToolDefinitions();
- if (terminalTools && terminalTools.length > 0) {
- payload = {
- ...payload,
- config: { ...payload.config, terminal_tools: terminalTools },
- };
+ const provider = payload.config.model?.provider?.toLowerCase() ?? '';
+ const isFincept = provider === 'fincept' || provider === 'fincept-llm';
+ if (!isFincept) {
+ const terminalTools = await getTerminalToolDefinitions();
+ if (terminalTools && terminalTools.length > 0) {
+ payload = {
+ ...payload,
+ config: { ...payload.config, terminal_tools: terminalTools },
+ };
+ }
}
}
const result = await invoke<string>('execute_core_agent', { payload });
@@ -1029,7 +1035,9 @@ export async function createPortfolioPlan(
}
/**
- * Run AI analysis on a portfolio summary - formats data and routes to agent
+ * Run AI analysis on a portfolio using live internal MCP tools.
+ * The agent fetches real-time holdings, risk metrics, diversification, and
+ * macro data itself via the terminal tool bridge — not pre-baked text.
*/
export async function runPortfolioAnalysis(
portfolioSummary: {
@@ -1054,17 +1062,58 @@ export async function runPortfolioAnalysis(
apiKeys?: Record<string, string>,
agentConfig?: AgentConfig,
): Promise<AgentResponse> {
- const topHoldings = portfolioSummary.holdings
- .sort((a, b) => b.weight - a.weight)
- .slice(0, 10)
- .map(h => `${h.symbol} (${h.weight.toFixed(1)}%, P&L: ${h.unrealized_pnl_percent.toFixed(1)}%)`)
- .join(', ');
+ const portfolioId = portfolioSummary.portfolio.id;
+ const portfolioName = portfolioSummary.portfolio.name;
+ const currency = portfolioSummary.portfolio.currency;
+ const nav = `${currency} ${portfolioSummary.total_market_value.toFixed(2)}`;
+ // Each analysis type gets a focused query that tells the agent
+ // exactly which tools to call and what to do with the results.
const queries: Record<string, string> = {
- full: `Analyze my portfolio "${portfolioSummary.portfolio.name}": NAV ${portfolioSummary.portfolio.currency} ${portfolioSummary.total_market_value.toFixed(2)}, Total P&L ${portfolioSummary.total_unrealized_pnl_percent.toFixed(2)}%, Day change ${portfolioSummary.total_day_change_percent.toFixed(2)}%. Top holdings: ${topHoldings}. Provide comprehensive analysis: risk assessment, diversification, key risks, and actionable recommendations.`,
- risk: `Risk analysis for portfolio "${portfolioSummary.portfolio.name}": NAV ${portfolioSummary.portfolio.currency} ${portfolioSummary.total_market_value.toFixed(2)}. Holdings: ${topHoldings}. Assess concentration risk, correlation, volatility exposure, and suggest risk mitigation strategies.`,
- rebalance: `Rebalancing recommendations for portfolio "${portfolioSummary.portfolio.name}": Holdings: ${topHoldings}. Suggest optimal rebalancing to improve diversification, risk-adjusted returns, and alignment with best practices.`,
- opportunities: `Investment opportunities for portfolio "${portfolioSummary.portfolio.name}": Current holdings: ${topHoldings}. Identify gaps, sectors to add, underweighted areas, and specific buy/sell recommendations.`,
+ full: `Run a comprehensive analysis of my portfolio "${portfolioName}" (ID: ${portfolioId}, NAV: ${nav}).
+Use these tools in order:
+1. get_my_stocks — get all holdings with current prices, weights, and P&L
+2. calculate_advanced_metrics with portfolio_id="${portfolioId}" — get Sharpe ratio, VaR, volatility, max drawdown
+3. analyze_diversification with portfolio_id="${portfolioId}" — assess concentration and sector spread
+4. economics_central_bank_rates — get global central bank rates
+5. economics_inverted_yields — check yield curve inversion signals
+6. economics_calendar — get upcoming macro events
+7. economics_ceic_series with country="united-states" indicator="GDP" — get GDP trend
+8. economics_ceic_series with country="united-states" indicator="CPI" — get inflation trend
+
+Then provide a structured report: portfolio snapshot, risk metrics, diversification, macro environment, and specific actionable recommendations.`,
+
+ risk: `Perform a risk analysis of portfolio "${portfolioName}" (ID: ${portfolioId}, NAV: ${nav}).
+Use these tools:
+1. get_my_stocks — get all holdings and current weights
+2. calculate_advanced_metrics with portfolio_id="${portfolioId}" — get Sharpe ratio, VaR 95%, volatility, max drawdown
+3. analyze_diversification with portfolio_id="${portfolioId}" — get concentration risk and sector breakdown
+4. economics_inverted_yields — check recession signals from yield curve
+5. economics_central_bank_rates — get rate environment
+
+Deliver: overall risk rating, key risk factors with specific numbers, stress scenarios, and risk mitigation actions.`,
+
+ rebalance: `Generate a rebalancing plan for portfolio "${portfolioName}" (ID: ${portfolioId}, NAV: ${nav}).
+Use these tools:
+1. get_my_stocks — get all holdings with exact weights
+2. analyze_diversification with portfolio_id="${portfolioId}" — identify concentration issues
+3. calculate_advanced_metrics with portfolio_id="${portfolioId}" — get current Sharpe and volatility
+4. economics_central_bank_rates — understand the rate environment
+5. economics_bond_spreads — assess fixed income conditions
+6. economics_inverted_yields — check recession signals
+
+Deliver: current vs target allocation table, specific trades to make (buy X / sell Y with amounts), and expected improvement in risk metrics.`,
+
+ opportunities: `Identify investment opportunities for portfolio "${portfolioName}" (ID: ${portfolioId}, NAV: ${nav}).
+Use these tools:
+1. get_my_stocks — see current holdings and any gaps
+2. analyze_diversification with portfolio_id="${portfolioId}" — identify underweighted sectors/geographies
+3. economics_ceic_series with country="china" indicator="GDP" — check China growth
+4. economics_ceic_series with country="india" indicator="GDP" — check India growth
+5. economics_central_bank_rates — find easing cycles (rate cuts = opportunity signal)
+6. economics_upcoming_events — upcoming catalysts
+
+Deliver: gaps in current allocation, specific assets/ETFs/sectors to add, and macro-driven opportunities with rationale.`,
};
return execute({
diff --git a/fincept-terminal-desktop/src/services/chat/llmApi.ts b/fincept-terminal-desktop/src/services/chat/llmApi.ts
index 32e741981..4960d55fc 100644
--- a/fincept-terminal-desktop/src/services/chat/llmApi.ts
+++ b/fincept-terminal-desktop/src/services/chat/llmApi.ts
@@ -5,6 +5,37 @@ import { fetch } from '@tauri-apps/plugin-http';
import { invoke } from '@tauri-apps/api/core';
import { llmLogger } from '../core/loggerService';
+// ── Fincept rate limiter + auth helper (TypeScript side) ─────────────────────
+// The Python subprocess has its own file-based rate limiter, but the Chat tab
+// calls the Fincept endpoint directly via fetch() — bypassing Python entirely.
+// This limiter enforces ≥2s between any two Fincept API calls from TypeScript.
+let _finceptLastCallTs = 0;
+async function _finceptRateLimit(): Promise<void> {
+ const now = Date.now();
+ const wait = 2000 - (now - _finceptLastCallTs);
+ if (wait > 0) await new Promise(r => setTimeout(r, wait));
+ _finceptLastCallTs = Date.now();
+}
+
+/**
+ * Build Fincept request headers. Tries config.apiKey first, then falls back
+ * to the session key stored in settings. Never sends an empty X-API-Key header.
+ */
+async function _finceptHeaders(apiKey?: string): Promise<Record<string, string>> {
+ let key = apiKey;
+ if (!key) {
+ try {
+ const { getSetting } = await import('../core/sqliteService');
+ key = await getSetting('fincept_api_key') || '';
+ } catch {
+ key = '';
+ }
+ }
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
+ if (key) headers['X-API-Key'] = key;
+ return headers;
+}
+
// Native SDK imports
import { ChatOpenAI } from '@langchain/openai';
import { ChatAnthropic } from '@langchain/anthropic';
@@ -532,12 +563,10 @@ class LLMApiService {
llmLogger.debug('Fincept API request:', { url, bodyKeys: Object.keys(requestBody) });
+ await _finceptRateLimit();
const response = await fetch(url, {
method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-API-Key': config.apiKey || ''
- },
+ headers: await _finceptHeaders(config.apiKey),
body: JSON.stringify(requestBody)
});
@@ -1033,12 +1062,10 @@ Mention the year-over-year growth percentages when discussing financial performa
console.log('[Fincept Tools] Request body:', JSON.stringify(requestBody, null, 2));
llmLogger.debug('Fincept API with tools request:', { url, tools: tools.length });
+ await _finceptRateLimit();
const response = await fetch(url, {
method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-API-Key': config.apiKey || ''
- },
+ headers: await _finceptHeaders(config.apiKey),
body: JSON.stringify(requestBody)
});
@@ -1131,12 +1158,10 @@ Mention the year-over-year growth percentages when discussing financial performa
max_tokens: config.maxTokens
};
+ await _finceptRateLimit();
const followUpResponse = await fetch(url, {
method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-API-Key': config.apiKey || ''
- },
+ headers: await _finceptHeaders(config.apiKey),
body: JSON.stringify(followUpBody)
});
diff --git a/portfolio-analyst-agent.json b/portfolio-analyst-agent.json
new file mode 100644
index 000000000..7547473d2
--- /dev/null
+++ b/portfolio-analyst-agent.json
@@ -0,0 +1,16 @@
+{
+ "name": "Portfolio Analyst",
+ "description": "Analyzes portfolio holdings, macro conditions, and provides rebalancing recommendations with CFA-level insights.",
+ "category": "finance",
+ "config_json": {
+ "model": {
+ "provider": "fincept",
+ "model_id": "fincept-llm",
+ "temperature": 0.3
+ },
+ "instructions": "You are a CFA-level portfolio analyst with deep expertise in asset allocation, risk management, and macroeconomic analysis.\n\nWhen given a portfolio, you MUST:\n1. Call get_my_stocks to fetch current holdings and live prices\n2. Call calculate_advanced_metrics to get Sharpe ratio, volatility, beta, VaR\n3. Call analyze_diversification to assess sector/geographic concentration\n4. Call economics_central_bank_rates to get current central bank rates globally\n5. Call economics_inverted_yields to check yield curve inversion signals\n6. Call economics_bond_spreads to assess credit risk environment\n7. Call economics_calendar to identify upcoming market-moving events\n8. Call economics_ceic_series with country='united-states' and indicator='GDP' for growth context\n9. Call economics_ceic_series with country='united-states' and indicator='CPI' for inflation context\n\nAfter gathering ALL data, produce a structured report with:\n\n## Portfolio Overview\n- Current NAV, number of holdings, top positions\n\n## Performance Metrics\n- Sharpe ratio, volatility, beta, max drawdown, VaR\n- Compare to benchmarks where possible\n\n## Macro Environment\n- Fed/central bank stance and rate outlook\n- Inflation trajectory (CPI trend)\n- GDP growth signals\n- Yield curve status (normal/inverted/flat)\n- Credit spreads (risk-on vs risk-off)\n- Key upcoming events that could move markets\n\n## Risk Assessment\n- Concentration risks (sector, geography, single-name)\n- Correlation analysis\n- Tail risk exposures\n- Current macro headwinds/tailwinds for each position\n\n## Rebalancing Recommendations\nFor each recommendation provide:\n- Action: REDUCE / INCREASE / HOLD / EXIT / INITIATE\n- Asset: ticker and name\n- Current weight vs target weight\n- Rationale: cite specific numbers from the data you collected\n- Risk/Reward: expected outcome\n\n## Priority Actions\nRank top 3 most urgent changes with clear reasoning.\n\nAlways cite specific numbers. Never make vague statements. Be direct and actionable.",
+ "tools": [],
+ "markdown": true,
+ "max_iterations": 15
+ }
+}