Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat: model registry fixes, token usage UI, auth runtime check, remove Groq/Cerebras from agents
trohitg6e312768639c
diff --git a/CLAUDE.md b/CLAUDE.mdindex 64abc847..6b841fb7 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1709,7 +1709,7 @@ deploy_workflow() -> Sets up triggers, returns immediately- **Execution Engine**: Routes AI nodes to Python Flask backend with auto-injection of API keys#### Supported AI Providers & Models-All 6 providers are available across aiAgent, chatAgent (Zeenie), and all specialized agents. Model parameters (max output, context length, thinking type, temperature range) are managed by `ModelRegistryService` (`server/services/model_registry.py`) which fetches from OpenRouter and falls back to `server/config/llm_defaults.json`.+4 providers are available for aiAgent, chatAgent (Zeenie), and all specialized agents: OpenAI, Anthropic, Google (Gemini), OpenRouter. Groq and Cerebras are available as standalone chat model nodes only (groqChatModel, cerebrasChatModel). Model parameters (max output, context length, thinking type, temperature range) are managed by `ModelRegistryService` (`server/services/model_registry.py`) which fetches from OpenRouter and falls back to `server/config/llm_defaults.json`.| Provider | Key Models | Context | Max Output | Thinking | Temp Range ||----------|-----------|---------|-----------|----------|------------|diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsxindex 992b77a3..dbe9af82 100644--- a/client/src/components/parameterPanel/MiddleSection.tsx+++ b/client/src/components/parameterPanel/MiddleSection.tsx@@ -236,6 +236,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({session_id: string;total: number;threshold: number;+ context_length?: number;count: number;}>('get_compaction_stats', {session_id: actualSessionId,@@ -248,6 +249,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({session_id: statsResponse.session_id || actualSessionId,total: statsResponse.total || 0,threshold: statsResponse.threshold,+ context_length: statsResponse.context_length || 0,count: statsResponse.count || 0});}@@ -775,80 +777,101 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({style={{ marginTop: 16 }}items={[{key: 'tokens',- label: (- <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>- <ThunderboltOutlined />- Token Usage- {compactionStats && (- <Typography.Text type="secondary" style={{ marginLeft: 'auto' }}>- {Math.round(compactionStats.total / 1000)}K / {Math.round(compactionStats.threshold / 1000)}K- </Typography.Text>- )}- </span>- ),+ label: (() => {+ const ctxLen = compactionStats?.context_length || 0;+ const displayMax = ctxLen > 0 ? ctxLen : compactionStats?.threshold || 0;+ return (+ <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>+ <ThunderboltOutlined />+ Token Usage+ {compactionStats && displayMax > 0 && (+ <Typography.Text type="secondary" style={{ marginLeft: 'auto' }}>+ {Math.round(compactionStats.total / 1000)}K / {Math.round(displayMax / 1000)}K{ctxLen > 0 ? ' context' : ''}+ </Typography.Text>+ )}+ </span>+ );+ })(),children: compactionLoading ? (<Spin />- ) : compactionStats ? (- <>- <Progress- percent={Math.round((compactionStats.total / compactionStats.threshold) * 100)}- status={compactionStats.total >= compactionStats.threshold * 0.8 ? 'exception' : 'active'}- />- <Row gutter={16} style={{ marginTop: 16 }}>- <Col span={8}><Statistic title="Total" value={compactionStats.total} /></Col>- <Col span={8}>- {isEditingThreshold ? (- <div>- <Typography.Text type="secondary" style={{ fontSize: 12 }}>Threshold</Typography.Text>- <div style={{ display: 'flex', gap: 4, marginTop: 4 }}>- <InputNumber- size="small"- value={editThresholdValue}- onChange={(v) => setEditThresholdValue(v || compactionStats.threshold)}- min={10000}- max={2000000}- step={10000}- style={{ width: 100 }}- />- <Button- size="small"- type="primary"- icon={<SaveOutlined />}- loading={savingThreshold}- onClick={async () => {- setSavingThreshold(true);- try {- await sendRequest('configure_compaction', {- session_id: connectedMemorySessionId,- threshold: editThresholdValue- });- if (compactionStats && connectedMemorySessionId && currentWorkflow?.id) {- updateCompactionStats(currentWorkflow.id, connectedMemorySessionId, { ...compactionStats, threshold: editThresholdValue });+ ) : compactionStats ? (() => {+ const ctxLen = compactionStats.context_length || 0;+ const hasContext = ctxLen > 0;+ const progressMax = hasContext ? ctxLen : compactionStats.threshold;+ const percent = progressMax > 0 ? Math.round((compactionStats.total / progressMax) * 100) : 0;+ const isWarning = hasContext+ ? compactionStats.total >= ctxLen * 0.8+ : compactionStats.total >= compactionStats.threshold * 0.8;+ return (+ <>+ <Progress+ percent={Math.min(percent, 100)}+ status={isWarning ? 'exception' : 'active'}+ />+ {hasContext && compactionStats.threshold > 0 && (+ <Typography.Text type="secondary" style={{ fontSize: 11, display: 'block', marginTop: 4 }}>+ Compaction at {Math.round(compactionStats.threshold / 1000)}K ({Math.round(compactionStats.threshold / ctxLen * 100)}% of context)+ </Typography.Text>+ )}+ <Row gutter={16} style={{ marginTop: 12 }}>+ <Col span={8}><Statistic title="Total" value={compactionStats.total} /></Col>+ <Col span={8}>+ {isEditingThreshold ? (+ <div>+ <Typography.Text type="secondary" style={{ fontSize: 12 }}>Threshold</Typography.Text>+ <div style={{ display: 'flex', gap: 4, marginTop: 4 }}>+ <InputNumber+ size="small"+ value={editThresholdValue}+ onChange={(v) => setEditThresholdValue(v || compactionStats.threshold)}+ min={10000}+ max={2000000}+ step={10000}+ style={{ width: 100 }}+ />+ <Button+ size="small"+ type="primary"+ icon={<SaveOutlined />}+ loading={savingThreshold}+ onClick={async () => {+ setSavingThreshold(true);+ try {+ await sendRequest('configure_compaction', {+ session_id: connectedMemorySessionId,+ threshold: editThresholdValue+ });+ if (compactionStats && connectedMemorySessionId && currentWorkflow?.id) {+ updateCompactionStats(currentWorkflow.id, connectedMemorySessionId, { ...compactionStats, threshold: editThresholdValue });+ }+ setIsEditingThreshold(false);+ message.success('Threshold updated');+ } catch (_err) {+ message.error('Failed to update threshold');+ } finally {+ setSavingThreshold(false);}- setIsEditingThreshold(false);- message.success('Threshold updated');- } catch (_err) {- message.error('Failed to update threshold');- } finally {- setSavingThreshold(false);- }- }}- />+ }}+ />+ </div></div>- </div>- ) : (- <div onClick={() => { setEditThresholdValue(compactionStats.threshold); setIsEditingThreshold(true); }} style={{ cursor: 'pointer' }}>- <Statistic title={<span>Threshold <EditOutlined style={{ fontSize: 10, marginLeft: 4 }} /></span>} value={compactionStats.threshold} />- </div>+ ) : (+ <div onClick={() => { setEditThresholdValue(compactionStats.threshold); setIsEditingThreshold(true); }} style={{ cursor: 'pointer' }}>+ <Statistic title={<span>Threshold <EditOutlined style={{ fontSize: 10, marginLeft: 4 }} /></span>} value={compactionStats.threshold} />+ </div>+ )}+ </Col>+ <Col span={hasContext ? 4 : 8}><Statistic title="Compactions" value={compactionStats.count} /></Col>+ {hasContext && (+ <Col span={4}><Statistic title="Context" value={`${Math.round(ctxLen / 1000)}K`} /></Col>)}- </Col>- <Col span={8}><Statistic title="Compactions" value={compactionStats.count} /></Col>- </Row>- <Typography.Text type="secondary" style={{ fontSize: 12, marginTop: 8, display: 'block' }}>- Session: {compactionStats.session_id}- </Typography.Text>- </>- ) : (+ </Row>+ <Typography.Text type="secondary" style={{ fontSize: 12, marginTop: 8, display: 'block' }}>+ Session: {compactionStats.session_id}+ </Typography.Text>+ </>+ );+ })() : (<Typography.Text type="secondary">No data yet. Run the agent to start tracking.</Typography.Text>)}]}diff --git a/client/src/config/api.ts b/client/src/config/api.tsindex 2f34eef4..3d0a6b27 100644--- a/client/src/config/api.ts+++ b/client/src/config/api.ts@@ -5,7 +5,6 @@interface ApiConfig {readonly PYTHON_BASE_URL: string;- readonly AUTH_ENABLED: boolean;}/**@@ -22,9 +21,6 @@ function getApiConfig(): ApiConfig {return {// Python FastAPI backend (port 3010 in dev, same origin in prod)PYTHON_BASE_URL: viteEnv.VITE_PYTHON_SERVICE_URL || (isProduction ? '' : 'http://localhost:3010'),-- // Authentication enabled (default true, set VITE_AUTH_ENABLED=false to disable)- AUTH_ENABLED: viteEnv.VITE_AUTH_ENABLED !== 'false',};}diff --git a/client/src/contexts/AuthContext.tsx b/client/src/contexts/AuthContext.tsxindex 4ebddc2a..e961c741 100644--- a/client/src/contexts/AuthContext.tsx+++ b/client/src/contexts/AuthContext.tsx@@ -19,6 +19,7 @@ export interface User {}export interface AuthStatus {+ auth_enabled: boolean;auth_mode: 'single' | 'multi';authenticated: boolean;user: User | null;@@ -43,21 +44,13 @@ const AuthContext = createContext<AuthContextType | undefined>(undefined);const getApiBase = () => `${API_CONFIG.PYTHON_BASE_URL}/api/auth`;export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {- // When auth is disabled, bypass authentication entirely- const authEnabled = API_CONFIG.AUTH_ENABLED;-- const [user, setUser] = useState<User | null>(authEnabled ? null : { id: 0, email: 'anonymous', display_name: 'Anonymous', is_owner: true });- const [isLoading, setIsLoading] = useState(authEnabled);+ const [user, setUser] = useState<User | null>(null);+ const [isLoading, setIsLoading] = useState(true);const [authMode, setAuthMode] = useState<'single' | 'multi'>('single');const [canRegister, setCanRegister] = useState(false);const [error, setError] = useState<string | null>(null);const checkAuth = useCallback(async (retryCount = 0): Promise<void> => {- // Skip auth check if auth is disabled- if (!authEnabled) {- setIsLoading(false);- return;- }const maxRetries = 5;const baseDelay = 1000; // 1 second@@ -67,6 +60,14 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children});const data: AuthStatus = await response.json();+ // Runtime auth check: if backend says auth is disabled, set anonymous user+ if (data.auth_enabled === false) {+ setUser({ id: 0, email: 'anonymous', display_name: 'Anonymous', is_owner: true });+ setIsLoading(false);+ setError(null);+ return;+ }+setAuthMode(data.auth_mode);setCanRegister(data.can_register);@@ -91,7 +92,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ childrensetIsLoading(false);}}- }, [authEnabled]);+ }, []);// Check auth status on mountuseEffect(() => {diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex 17ed4f3c..45f5c2e7 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -214,6 +214,7 @@ export interface CompactionStats {session_id: string;total: number;threshold: number;+ context_length?: number;count: number;total_cost?: number;}diff --git a/client/src/nodeDefinitions/aiAgentNodes.ts b/client/src/nodeDefinitions/aiAgentNodes.tsindex 8f823f78..418223e1 100644--- a/client/src/nodeDefinitions/aiAgentNodes.ts+++ b/client/src/nodeDefinitions/aiAgentNodes.ts@@ -75,17 +75,9 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {name: 'Google (Gemini)',value: 'gemini'},- {- name: 'Groq',- value: 'groq'- },{name: 'OpenRouter',value: 'openrouter'- },- {- name: 'Cerebras',- value: 'cerebras'}],default: 'openai',@@ -249,17 +241,9 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {name: 'Google (Gemini)',value: 'gemini'},- {- name: 'Groq',- value: 'groq'- },{name: 'OpenRouter',value: 'openrouter'- },- {- name: 'Cerebras',- value: 'cerebras'}],default: 'openai',diff --git a/client/src/nodeDefinitions/specializedAgentNodes.ts b/client/src/nodeDefinitions/specializedAgentNodes.tsindex 363a6e8f..5a4c02cf 100644--- a/client/src/nodeDefinitions/specializedAgentNodes.ts+++ b/client/src/nodeDefinitions/specializedAgentNodes.ts@@ -68,9 +68,7 @@ export const AI_AGENT_PROPERTIES: INodeProperties[] = [{ name: 'OpenAI', value: 'openai' },{ name: 'Anthropic (Claude)', value: 'anthropic' },{ name: 'Google (Gemini)', value: 'gemini' },- { name: 'Groq', value: 'groq' },- { name: 'OpenRouter', value: 'openrouter' },- { name: 'Cerebras', value: 'cerebras' }+ { name: 'OpenRouter', value: 'openrouter' }],default: 'openai',description: 'The AI provider to use (configure API keys in Credentials)'diff --git a/client/src/vite-env.d.ts b/client/src/vite-env.d.tsindex b32f5221..476f613f 100644--- a/client/src/vite-env.d.ts+++ b/client/src/vite-env.d.ts@@ -2,7 +2,6 @@interface ImportMetaEnv {readonly VITE_ANDROID_RELAY_URL: string;- readonly VITE_AUTH_ENABLED: string;readonly VITE_CLIENT_PORT: string;readonly VITE_PYTHON_BACKEND_URL: string;}diff --git a/client/vite.config.js b/client/vite.config.jsindex 69a9e0a5..63fceca5 100644--- a/client/vite.config.js+++ b/client/vite.config.js@@ -30,7 +30,6 @@ export default defineConfig(({ mode }) => {// Expose VITE_ prefixed env vars to client code via import.meta.envdefine: {__APP_VERSION__: JSON.stringify(version),- 'import.meta.env.VITE_AUTH_ENABLED': JSON.stringify(getEnv('VITE_AUTH_ENABLED', 'true')),'import.meta.env.VITE_PYTHON_SERVICE_URL': JSON.stringify(getEnv('VITE_PYTHON_SERVICE_URL', '')),'import.meta.env.VITE_WHATSAPP_SERVICE_URL': JSON.stringify(getEnv('VITE_WHATSAPP_SERVICE_URL', '')),'import.meta.env.VITE_ANDROID_RELAY_URL': JSON.stringify(getEnv('VITE_ANDROID_RELAY_URL', '')),diff --git a/package-lock.json b/package-lock.jsonindex 748c471d..5aa6d528 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "machinaos",- "version": "0.0.43",+ "version": "0.0.44","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "machinaos",- "version": "0.0.43",+ "version": "0.0.44","hasInstallScript": true,"license": "MIT","workspaces": [diff --git a/server/config/llm_defaults.json b/server/config/llm_defaults.jsonindex 608a09d9..641e1382 100644--- a/server/config/llm_defaults.json+++ b/server/config/llm_defaults.json@@ -29,22 +29,22 @@"temperature_range": [0.0, 2.0]},"anthropic": {- "default_model": "claude-sonnet-4.6",+ "default_model": "claude-sonnet-4-6","detection_patterns": ["claude", "anthropic"],"max_output_tokens": {- "claude-opus-4.6": 128000,- "claude-sonnet-4.6": 128000,- "claude-haiku-4.5": 64000,- "claude-sonnet-4": 64000,- "claude-opus-4": 32000,+ "claude-opus-4-6": 128000,+ "claude-sonnet-4-6": 128000,+ "claude-haiku-4-5": 64000,+ "claude-sonnet-4-0": 64000,+ "claude-opus-4-0": 32000,"_default": 8192},"context_length": {- "claude-opus-4.6": 1000000,- "claude-sonnet-4.6": 1000000,- "claude-haiku-4.5": 200000,- "claude-sonnet-4": 200000,- "claude-opus-4": 200000,+ "claude-opus-4-6": 1000000,+ "claude-sonnet-4-6": 1000000,+ "claude-haiku-4-5": 200000,+ "claude-sonnet-4-0": 200000,+ "claude-opus-4-0": 200000,"_default": 200000},"thinking_type": "budget",@@ -88,13 +88,13 @@"default_model": "llama-4-scout","detection_patterns": ["groq"],"max_output_tokens": {- "llama-4-scout": 16384,+ "llama-4-scout": 8192,"llama-4-maverick": 16384,- "llama-3.3-70b": 16384,- "llama-3.1-8b": 8192,+ "llama-3.3-70b": 32768,+ "llama-3.1-8b": 131072,"qwen3-32b": 40960,"gpt-oss-120b": 65536,- "gpt-oss-20b": 16384,+ "gpt-oss-20b": 65536,"_default": 8192},"context_length": {@@ -102,7 +102,7 @@"llama-4-maverick": 131072,"llama-3.3-70b": 131072,"llama-3.1-8b": 131072,- "qwen3-32b": 40960,+ "qwen3-32b": 131072,"gpt-oss-120b": 131072,"gpt-oss-20b": 131072,"_default": 131072diff --git a/server/config/model_registry.json b/server/config/model_registry.jsonindex 74d25c62..0591c818 100644--- a/server/config/model_registry.json+++ b/server/config/model_registry.json@@ -1,8 +1,73 @@{- "_generated": "2026-03-10T10:01:41.781715+00:00",+ "_generated": "2026-03-11T10:02:14.102765+00:00","_source": "openrouter",- "_model_count": 346,+ "_model_count": 339,"models": {+ "bytedance-seed/seed-2.0-lite": {+ "id": "bytedance-seed/seed-2.0-lite",+ "name": "ByteDance Seed: Seed-2.0-Lite",+ "provider": "bytedance-seed",+ "local_id": "seed-2.0-lite",+ "context_length": 262144,+ "max_output_tokens": 131072,+ "input_price_per_mtok": 0.25,+ "output_price_per_mtok": 2.0,+ "supports_thinking": false,+ "thinking_type": "none",+ "temperature_range": [+ 0.0,+ 2.0+ ],+ "is_reasoning_model": false,+ "supported_parameters": [+ "frequency_penalty",+ "include_reasoning",+ "max_tokens",+ "reasoning",+ "response_format",+ "stop",+ "structured_outputs",+ "temperature",+ "tool_choice",+ "tools",+ "top_p"+ ]+ },+ "qwen/qwen3.5-9b": {+ "id": "qwen/qwen3.5-9b",+ "name": "Qwen: Qwen3.5-9B",+ "provider": "qwen",+ "local_id": "qwen3.5-9b",+ "context_length": 262144,+ "max_output_tokens": 0,+ "input_price_per_mtok": 0.1,+ "output_price_per_mtok": 0.15,+ "supports_thinking": false,+ "thinking_type": "none",+ "temperature_range": [+ 0.0,+ 2.0+ ],+ "is_reasoning_model": false,+ "supported_parameters": [+ "frequency_penalty",+ "include_reasoning",+ "logit_bias",+ "max_tokens",+ "min_p",+ "presence_penalty",+ "reasoning",+ "repetition_penalty",+ "response_format",+ "stop",+ "structured_outputs",+ "temperature",+ "tool_choice",+ "tools",+ "top_k",+ "top_p"+ ]+ },"openai/gpt-5.4-pro": {"id": "openai/gpt-5.4-pro","name": "OpenAI: GPT-5.4 Pro",@@ -603,9 +668,9 @@"provider": "minimax","local_id": "minimax-m2.5","context_length": 196608,- "max_output_tokens": 196608,- "input_price_per_mtok": 0.295,- "output_price_per_mtok": 1.2,+ "max_output_tokens": 0,+ "input_price_per_mtok": 0.27,+ "output_price_per_mtok": 0.95,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -643,9 +708,9 @@"provider": "z-ai","local_id": "glm-5","context_length": 202752,- "max_output_tokens": 0,- "input_price_per_mtok": 0.8,- "output_price_per_mtok": 2.56,+ "max_output_tokens": 131072,+ "input_price_per_mtok": 0.72,+ "output_price_per_mtok": 2.3,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -1908,8 +1973,10 @@"is_reasoning_model": false,"supported_parameters": ["frequency_penalty",+ "logprobs","max_tokens","presence_penalty",+ "repetition_penalty","response_format","seed","stop",@@ -1917,6 +1984,7 @@"temperature","tool_choice","tools",+ "top_logprobs","top_p"]},@@ -3344,40 +3412,6 @@"top_p"]},- "z-ai/glm-4.6:exacto": {- "id": "z-ai/glm-4.6:exacto",- "name": "Z.ai: GLM 4.6 (exacto)",- "provider": "z-ai",- "local_id": "glm-4.6:exacto",- "context_length": 204800,- "max_output_tokens": 131072,- "input_price_per_mtok": 0.44,- "output_price_per_mtok": 1.76,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "include_reasoning",- "max_tokens",- "presence_penalty",- "reasoning",- "repetition_penalty",- "response_format",- "seed",- "stop",- "structured_outputs",- "temperature",- "tool_choice",- "tools",- "top_k",- "top_p"- ]- },"anthropic/claude-sonnet-4.5": {"id": "anthropic/claude-sonnet-4.5","name": "Anthropic: Claude Sonnet 4.5",@@ -3677,41 +3711,6 @@"tools"]},- "deepseek/deepseek-v3.1-terminus:exacto": {- "id": "deepseek/deepseek-v3.1-terminus:exacto",- "name": "DeepSeek: DeepSeek V3.1 Terminus (exacto)",- "provider": "deepseek",- "local_id": "deepseek-v3.1-terminus:exacto",- "context_length": 163840,- "max_output_tokens": 0,- "input_price_per_mtok": 0.21,- "output_price_per_mtok": 0.79,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "include_reasoning",- "max_tokens",- "min_p",- "presence_penalty",- "reasoning",- "repetition_penalty",- "response_format",- "seed",- "stop",- "structured_outputs",- "temperature",- "tool_choice",- "tools",- "top_k",- "top_p"- ]- },"deepseek/deepseek-v3.1-terminus": {"id": "deepseek/deepseek-v3.1-terminus","name": "DeepSeek: DeepSeek V3.1 Terminus",@@ -4133,36 +4132,6 @@"top_p"]},- "moonshotai/kimi-k2-0905:exacto": {- "id": "moonshotai/kimi-k2-0905:exacto",- "name": "MoonshotAI: Kimi K2 0905 (exacto)",- "provider": "moonshotai",- "local_id": "kimi-k2-0905:exacto",- "context_length": 262144,- "max_output_tokens": 0,- "input_price_per_mtok": 0.6,- "output_price_per_mtok": 2.5,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "max_tokens",- "presence_penalty",- "response_format",- "seed",- "stop",- "structured_outputs",- "temperature",- "tool_choice",- "tools",- "top_p"- ]- },"qwen/qwen3-30b-a3b-thinking-2507": {"id": "qwen/qwen3-30b-a3b-thinking-2507","name": "Qwen: Qwen3 30B A3B Thinking 2507",@@ -4682,41 +4651,6 @@"top_p"]},- "openai/gpt-oss-120b:exacto": {- "id": "openai/gpt-oss-120b:exacto",- "name": "OpenAI: gpt-oss-120b (exacto)",- "provider": "openai",- "local_id": "gpt-oss-120b:exacto",- "context_length": 131072,- "max_output_tokens": 0,- "input_price_per_mtok": 0.039,- "output_price_per_mtok": 0.19,- "supports_thinking": true,- "thinking_type": "effort",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "include_reasoning",- "max_tokens",- "min_p",- "presence_penalty",- "reasoning",- "repetition_penalty",- "response_format",- "seed",- "stop",- "structured_outputs",- "temperature",- "tool_choice",- "tools",- "top_k",- "top_p"- ]- },"openai/gpt-oss-20b:free": {"id": "openai/gpt-oss-20b:free","name": "OpenAI: gpt-oss-20b (free)",@@ -5123,35 +5057,6 @@"top_p"]},- "qwen/qwen3-coder:exacto": {- "id": "qwen/qwen3-coder:exacto",- "name": "Qwen: Qwen3 Coder 480B A35B (exacto)",- "provider": "qwen",- "local_id": "qwen3-coder:exacto",- "context_length": 262144,- "max_output_tokens": 65536,- "input_price_per_mtok": 0.22,- "output_price_per_mtok": 1.8,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "max_tokens",- "repetition_penalty",- "response_format",- "seed",- "structured_outputs",- "temperature",- "tool_choice",- "tools",- "top_k",- "top_p"- ]- },"bytedance/ui-tars-1.5-7b": {"id": "bytedance/ui-tars-1.5-7b","name": "ByteDance: UI-TARS 7B ",@@ -6889,7 +6794,7 @@"provider": "deepseek","local_id": "deepseek-chat-v3-0324","context_length": 163840,- "max_output_tokens": 163840,+ "max_output_tokens": 0,"input_price_per_mtok": 0.2,"output_price_per_mtok": 0.77,"supports_thinking": false,@@ -8520,36 +8425,6 @@"top_p"]},- "raifle/sorcererlm-8x22b": {- "id": "raifle/sorcererlm-8x22b",- "name": "SorcererLM 8x22B",- "provider": "raifle",- "local_id": "sorcererlm-8x22b",- "context_length": 16000,- "max_output_tokens": 0,- "input_price_per_mtok": 4.5,- "output_price_per_mtok": 4.5,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "logit_bias",- "max_tokens",- "min_p",- "presence_penalty",- "repetition_penalty",- "seed",- "stop",- "temperature",- "top_k",- "top_p"- ]- },"thedrummer/unslopnemo-12b": {"id": "thedrummer/unslopnemo-12b","name": "TheDrummer: UnslopNemo 12B",@@ -8860,13 +8735,10 @@"is_reasoning_model": false,"supported_parameters": ["frequency_penalty",- "logit_bias","max_tokens",- "min_p","presence_penalty","repetition_penalty","seed",- "stop","temperature","top_k","top_p"@@ -8962,35 +8834,6 @@"top_p"]},- "neversleep/llama-3.1-lumimaid-8b": {- "id": "neversleep/llama-3.1-lumimaid-8b",- "name": "NeverSleep: Lumimaid v0.2 8B",- "provider": "neversleep",- "local_id": "llama-3.1-lumimaid-8b",- "context_length": 32768,- "max_output_tokens": 4096,- "input_price_per_mtok": 0.09,- "output_price_per_mtok": 0.6,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "logprobs",- "max_tokens",- "presence_penalty",- "response_format",- "stop",- "structured_outputs",- "temperature",- "top_logprobs",- "top_p"- ]- },"cohere/command-r-08-2024": {"id": "cohere/command-r-08-2024","name": "Cohere: Command R (08-2024)",@@ -9058,10 +8901,10 @@"name": "Sao10K: Llama 3.1 Euryale 70B v2.2","provider": "sao10k","local_id": "l3.1-euryale-70b",- "context_length": 32768,- "max_output_tokens": 32768,- "input_price_per_mtok": 0.65,- "output_price_per_mtok": 0.75,+ "context_length": 131072,+ "max_output_tokens": 16384,+ "input_price_per_mtok": 0.85,+ "output_price_per_mtok": 0.85,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -9071,7 +8914,6 @@"is_reasoning_model": false,"supported_parameters": ["frequency_penalty",- "logprobs","max_tokens","min_p","presence_penalty",@@ -9084,7 +8926,6 @@"tool_choice","tools","top_k",- "top_logprobs","top_p"]},@@ -9123,8 +8964,8 @@"name": "Nous: Hermes 3 70B Instruct","provider": "nousresearch","local_id": "hermes-3-llama-3.1-70b",- "context_length": 65536,- "max_output_tokens": 65536,+ "context_length": 131072,+ "max_output_tokens": 0,"input_price_per_mtok": 0.3,"output_price_per_mtok": 0.3,"supports_thinking": false,@@ -9136,7 +8977,6 @@"is_reasoning_model": false,"supported_parameters": ["frequency_penalty",- "logprobs","max_tokens","min_p","presence_penalty",@@ -9144,10 +8984,8 @@"response_format","seed","stop",- "structured_outputs","temperature","top_k",- "top_logprobs","top_p"]},@@ -9618,35 +9456,6 @@"top_p"]},- "meta/llama-guard-2-8b": {- "id": "meta-llama/llama-guard-2-8b",- "name": "Meta: LlamaGuard 2 8B",- "provider": "meta",- "local_id": "llama-guard-2-8b",- "context_length": 8192,- "max_output_tokens": 0,- "input_price_per_mtok": 0.2,- "output_price_per_mtok": 0.2,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "logit_bias",- "max_tokens",- "min_p",- "presence_penalty",- "repetition_penalty",- "stop",- "temperature",- "top_k",- "top_p"- ]- },"openai/gpt-4o-2024-05-13": {"id": "openai/gpt-4o-2024-05-13","name": "OpenAI: GPT-4o (2024-05-13)",@@ -10058,33 +9867,6 @@"top_p"]},- "neversleep/noromaid-20b": {- "id": "neversleep/noromaid-20b",- "name": "Noromaid 20B",- "provider": "neversleep",- "local_id": "noromaid-20b",- "context_length": 4096,- "max_output_tokens": 2048,- "input_price_per_mtok": 1.0,- "output_price_per_mtok": 1.75,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "max_tokens",- "presence_penalty",- "response_format",- "stop",- "structured_outputs",- "temperature",- "top_p"- ]- },"alpindale/goliath-120b": {"id": "alpindale/goliath-120b","name": "Goliath 120B",diff --git a/server/config/pricing.json b/server/config/pricing.jsonindex 2a037867..3a2da963 100644--- a/server/config/pricing.json+++ b/server/config/pricing.json@@ -12,11 +12,11 @@"_default": {"input": 2.50, "output": 15.00}},"anthropic": {- "claude-opus-4.6": {"input": 5.00, "output": 25.00, "cache_read": 0.50},- "claude-sonnet-4.6": {"input": 3.00, "output": 15.00, "cache_read": 0.30},- "claude-haiku-4.5": {"input": 1.00, "output": 5.00, "cache_read": 0.10},- "claude-sonnet-4": {"input": 3.00, "output": 15.00, "cache_read": 0.30},- "claude-opus-4": {"input": 15.00, "output": 75.00, "cache_read": 1.50},+ "claude-opus-4-6": {"input": 5.00, "output": 25.00, "cache_read": 0.50},+ "claude-sonnet-4-6": {"input": 3.00, "output": 15.00, "cache_read": 0.30},+ "claude-haiku-4-5": {"input": 1.00, "output": 5.00, "cache_read": 0.10},+ "claude-sonnet-4-0": {"input": 3.00, "output": 15.00, "cache_read": 0.30},+ "claude-opus-4-0": {"input": 15.00, "output": 75.00, "cache_read": 1.50},"_default": {"input": 3.00, "output": 15.00, "cache_read": 0.30}},"gemini": {diff --git a/server/routers/auth.py b/server/routers/auth.pyindex 9345c331..b639f64d 100644--- a/server/routers/auth.py+++ b/server/routers/auth.py@@ -72,7 +72,13 @@ async def get_auth_status(# Check if registration is availablecan_register = await user_auth.can_register()+ # Determine if auth is enabled from server config+ auth_enabled = True+ if settings.vite_auth_enabled and settings.vite_auth_enabled.lower() == 'false':+ auth_enabled = False+return {+ "auth_enabled": auth_enabled,"auth_mode": status["auth_mode"],"authenticated": current_user is not None,"user": current_user,diff --git a/server/services/ai.py b/server/services/ai.pyindex 7319433d..c4f5d473 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -297,7 +297,7 @@ PROVIDER_CONFIGS: Dict[str, ProviderConfig] = {api_key_param='anthropic_api_key',max_tokens_param='max_tokens',detection_patterns=('claude', 'anthropic'),- default_model=_get_default_model('anthropic', 'claude-opus-4.6'),+ default_model=_get_default_model('anthropic', 'claude-opus-4-6'),models_endpoint='https://api.anthropic.com/v1/models',models_header_fn=_anthropic_headers),@@ -1232,85 +1232,43 @@ class AIService:model_class = config.model_class or _get_google_genai_class()return model_class(**kwargs)+ def _get_curated_models(self, provider: str) -> List[str]:+ """Get curated model list from llm_defaults.json for a provider.++ Returns model IDs from max_output_tokens keys (excluding _default),+ preserving config order. Returns empty list if provider has no curated list.+ """+ provider_cfg = _LLM_DEFAULTS.get("providers", {}).get(provider, {})+ max_tokens_map = provider_cfg.get("max_output_tokens", {})+ return [m for m in max_tokens_map if m != "_default"]+async def fetch_models(self, provider: str, api_key: str) -> List[str]:- """Fetch available models from provider API."""- async with httpx.AsyncClient(timeout=self.settings.ai_timeout) as client:- if provider == 'openai':- response = await client.get(- 'https://api.openai.com/v1/models',- headers={'Authorization': f'Bearer {api_key}'}- )- response.raise_for_status()- data = response.json()+ """Fetch available models from provider API.- # Filter for chat models including o-series reasoning models- models = []- for model in data.get('data', []):- model_id = model['id'].lower()- # Include GPT models and o-series reasoning models (o1, o3, o4)- is_gpt = 'gpt' in model_id- is_o_series = any(f'o{n}' in model_id for n in ['1', '3', '4'])- is_excluded = 'instruct' in model_id or 'embedding' in model_id or 'realtime' in model_id- if (is_gpt or is_o_series) and not is_excluded:- models.append(model['id'])-- # Sort by priority - o-series reasoning models at top- def get_priority(model_name: str) -> int:- m = model_name.lower()- # O-series reasoning models first- if 'o4-mini' in m: return 1- if 'o4' in m: return 2- if 'o3-mini' in m: return 3- if 'o3' in m: return 4- if 'o1-mini' in m: return 5- if 'o1' in m: return 6- # Then GPT models- if 'gpt-4o-mini' in m: return 10- if 'gpt-4o' in m: return 11- if 'gpt-4-turbo' in m: return 12- if 'gpt-4' in m: return 13- if 'gpt-3.5' in m: return 20- return 99-- return sorted(models, key=get_priority)-- elif provider == 'anthropic':- response = await client.get(- 'https://api.anthropic.com/v1/models',- headers={- 'x-api-key': api_key,- 'anthropic-version': '2023-06-01'- }- )- response.raise_for_status()- data = response.json()- return [model['id'] for model in data.get('data', [])- if model.get('type') == 'model']+ For providers with curated lists in llm_defaults.json, validates the API key+ and returns only the curated models (3 latest + 2 popular). For OpenRouter,+ returns all available models grouped by free/paid.+ """+ if provider == 'cerebras' and not CEREBRAS_AVAILABLE:+ raise ValueError(f"Cerebras provider not available: {CEREBRAS_IMPORT_ERROR or 'langchain-cerebras package not installed'}")- elif provider == 'gemini':- response = await client.get(- f'https://generativelanguage.googleapis.com/v1beta/models?key={api_key}'- )- response.raise_for_status()- data = response.json()+ config = PROVIDER_CONFIGS.get(provider)+ if not config:+ raise ValueError(f"Unsupported provider: {provider}")- models = []- for model in data.get('models', []):- name = model.get('name', '')- if ('gemini' in name and- 'generateContent' in model.get('supportedGenerationMethods', [])):- models.append(name.replace('models/', ''))+ curated = self._get_curated_models(provider)+ endpoint = config.models_endpoint+ headers = config.models_header_fn(api_key)- return sorted(models)+ async with httpx.AsyncClient(timeout=self.settings.ai_timeout) as client:+ # Gemini uses query param for key instead of header+ url = f"{endpoint}?key={api_key}" if provider == 'gemini' else endpoint+ response = await client.get(url, headers=headers)+ response.raise_for_status()- elif provider == 'openrouter':- response = await client.get(- 'https://openrouter.ai/api/v1/models',- headers={'Authorization': f'Bearer {api_key}'}- )- response.raise_for_status()+ # OpenRouter: return all models (aggregator, no curated list)+ if provider == 'openrouter':data = response.json()-free_models = []paid_models = []for model in data.get('data', []):@@ -1322,57 +1280,20 @@ class AIService:prompt_price = float(pricing.get('prompt', '0') or '0')completion_price = float(pricing.get('completion', '0') or '0')is_free = prompt_price == 0 and completion_price == 0- # Add [FREE] tag to free modelsdisplay_name = f"[FREE] {model_id}" if is_free else model_idif is_free:free_models.append(display_name)else:paid_models.append(display_name)-- # Return free models first, then paid models (both sorted)return sorted(free_models) + sorted(paid_models)- elif provider == 'groq':- response = await client.get(- 'https://api.groq.com/openai/v1/models',- headers={'Authorization': f'Bearer {api_key}'}- )- response.raise_for_status()- data = response.json()-- models = []- for model in data.get('data', []):- model_id = model.get('id', '')- # Include all models from Groq API- if model_id:- models.append(model_id)-- return sorted(models)+ # All other providers: return curated list from llm_defaults.json+ # The API call above validates the key; we return the curated set+ if curated:+ return curated- elif provider == 'cerebras':- if not CEREBRAS_AVAILABLE:- raise ValueError(f"Cerebras provider not available: {CEREBRAS_IMPORT_ERROR or 'langchain-cerebras package not installed'}")- response = await client.get(- 'https://api.cerebras.ai/v1/models',- headers={'Authorization': f'Bearer {api_key}'}- )- response.raise_for_status()- data = response.json()-- models = []- for model in data.get('data', []):- model_id = model.get('id', '')- # Include all models from Cerebras API- if model_id:- models.append(model_id)-- return sorted(models)-- else:- # Provide helpful error for Cerebras if import failed- if provider == 'cerebras' and not CEREBRAS_AVAILABLE:- raise ValueError(f"Cerebras provider not available: {CEREBRAS_IMPORT_ERROR or 'langchain-cerebras package not installed'}")- raise ValueError(f"Unsupported provider: {provider}")+ # Fallback: return default model if no curated list+ return [config.default_model]async def execute_chat(self, node_id: str, node_type: str, parameters: Dict[str, Any]) -> Dict[str, Any]:"""Execute AI chat model."""diff --git a/server/services/auth.py b/server/services/auth.pyindex 6de74e83..0927d46b 100644--- a/server/services/auth.py+++ b/server/services/auth.py@@ -1,6 +1,8 @@"""API key management service with encrypted credentials database."""import hashlib+import json+from pathlib import Pathfrom typing import Dict, Any, Optional, Listfrom core.config import Settingsdiff --git a/server/services/compaction.py b/server/services/compaction.pyindex 2193a11e..10f9eb55 100644--- a/server/services/compaction.py+++ b/server/services/compaction.py@@ -183,11 +183,17 @@ class CompactionService:ratio = await self._get_compaction_ratio()threshold = self.get_model_threshold(model, provider, ratio=ratio)+ # Get the model's full context window size for frontend display+ from services.model_registry import get_model_registry+ registry = get_model_registry()+ context_length = registry.get_context_length(model, provider)+return {"total": new_total,"total_cost": new_total_cost,"cost": cost,"threshold": threshold,+ "context_length": context_length,"needs_compaction": self._config.enabled and new_total >= threshold}@@ -220,10 +226,18 @@ class CompactionService:threshold = self.get_model_threshold(model, provider, ratio=ratio)else:threshold = self._config.threshold+ # Get context window size for frontend display+ context_length = 0+ if model and provider:+ from services.model_registry import get_model_registry+ registry = get_model_registry()+ context_length = registry.get_context_length(model, provider)+return {"session_id": session_id,"total": state["cumulative_total"],"threshold": threshold,+ "context_length": context_length,"count": state.get("compaction_count", 0),}diff --git a/server/services/model_registry.py b/server/services/model_registry.pyindex a76dca86..cd1f6cae 100644--- a/server/services/model_registry.py+++ b/server/services/model_registry.py@@ -169,37 +169,65 @@ class ModelRegistryService:# Core lookups# -------------------------------------------------------------------------+ @staticmethod+ def _model_variants(model: str) -> List[str]:+ """Generate dot and hyphen variants of a model ID for fuzzy matching.++ Model IDs use inconsistent version separators across sources:+ - OpenRouter/registry: dots (claude-sonnet-4.6)+ - llm_defaults.json: hyphens (claude-sonnet-4-6)++ Returns the original plus any variants with swapped separators.+ """+ variants = [model]+ # digit-hyphen-digit -> digit.digit (e.g., claude-sonnet-4-6 -> claude-sonnet-4.6)+ dot_variant = re.sub(r'(\d)-(\d)', r'\1.\2', model)+ if dot_variant != model:+ variants.append(dot_variant)+ # digit.digit -> digit-digit (e.g., claude-sonnet-4.6 -> claude-sonnet-4-6)+ hyphen_variant = re.sub(r'(\d)\.(\d)', r'\1-\2', model)+ if hyphen_variant != model:+ variants.append(hyphen_variant)+ return variants+def get_model_info(self, model: str, provider: str) -> Optional[ModelInfo]:"""Look up model info with waterfall strategy.- 1. Exact match on provider/model+ 1. Exact match on provider/model (tries dot/hyphen variants)2. Prefix match for versioned IDs3. Cross-provider check (for OpenRouter models)4. Returns None if not found"""# Strip [FREE] prefix if presentmodel = model.replace("[FREE] ", "")+ variants = self._model_variants(model)- # 1. Exact match- key = f"{provider}/{model}"- if key in self._models:- return self._models[key]+ # 1. Exact match (try all dot/hyphen variants)+ for variant in variants:+ key = f"{provider}/{variant}"+ if key in self._models:+ return self._models[key]# 2. Prefix match (e.g., claude-3-5-sonnet-20241022 -> claude-3-5-sonnet)for stored_key, info in self._models.items():- if info.provider == provider and model.startswith(info.local_id):- return info-- # 3. Cross-provider: try OpenRouter key format directly- for stored_key, info in self._models.items():- if info.local_id == model:- return info+ if info.provider == provider:+ for variant in variants:+ if variant.startswith(info.local_id) or info.local_id.startswith(variant):+ return info++ # 3. Cross-provider lookup (OpenRouter only - same model on different+ # providers can have different context windows and limits)+ if provider == "openrouter":+ for stored_key, info in self._models.items():+ if info.local_id in variants:+ return info# 4. For OpenRouter, try stripping provider prefix from modelif provider == "openrouter" and "/" in model:_, local = model.split("/", 1)+ local_variants = self._model_variants(local)for stored_key, info in self._models.items():- if info.local_id == local:+ if info.local_id in local_variants:return inforeturn None@@ -456,15 +484,19 @@ class ModelRegistryService:"""Fallback: get max output tokens from llm_defaults.json."""providers = self._llm_defaults.get("providers", {})token_map = providers.get(provider, {}).get("max_output_tokens", {})+ variants = self._model_variants(model)- # Exact match- if model in token_map:- return token_map[model]+ # Exact match (try dot/hyphen variants)+ for variant in variants:+ if variant in token_map:+ return token_map[variant]- # Prefix match+ # Prefix match (try dot/hyphen variants)for key, val in token_map.items():- if key != "_default" and isinstance(val, int) and model.startswith(key):- return val+ if key != "_default" and isinstance(val, int):+ for variant in variants:+ if variant.startswith(key):+ return valreturn token_map.get("_default", 4096)@@ -472,15 +504,19 @@ class ModelRegistryService:"""Fallback: get context length from llm_defaults.json."""providers = self._llm_defaults.get("providers", {})ctx_map = providers.get(provider, {}).get("context_length", {})+ variants = self._model_variants(model)- # Exact match- if model in ctx_map:- return ctx_map[model]+ # Exact match (try dot/hyphen variants)+ for variant in variants:+ if variant in ctx_map:+ return ctx_map[variant]- # Prefix match+ # Prefix match (try dot/hyphen variants)for key, val in ctx_map.items():- if key != "_default" and isinstance(val, int) and model.startswith(key):- return val+ if key != "_default" and isinstance(val, int):+ for variant in variants:+ if variant.startswith(key):+ return valreturn ctx_map.get("_default", 128000)diff --git a/server/services/telegram_service.py b/server/services/telegram_service.pyindex 346c089d..85639d1e 100644--- a/server/services/telegram_service.py+++ b/server/services/telegram_service.py@@ -12,7 +12,7 @@ from datetime import datetimefrom typing import Any, Dict, Optionalfrom telegram import Bot, Update-from telegram.error import BadRequest+from telegram.error import BadRequest, NetworkErrorfrom telegram.ext import Application, ContextTypes, MessageHandler, filtersfrom telegram.helpers import escape_markdown@@ -116,7 +116,20 @@ class TelegramService:logger.info(f"[Telegram] Bot validated: @{me.username} (ID: {me.id})")# Build application- self._application = Application.builder().token(token).build()+ self._application = (+ Application.builder()+ .token(token)+ # Long-polling timeouts (get_updates holds connection open ~10s)+ .get_updates_read_timeout(30.0)+ .get_updates_write_timeout(10.0)+ .get_updates_connect_timeout(10.0)+ .get_updates_pool_timeout(5.0)+ # Regular API call timeouts (send_message, etc.)+ .read_timeout(10.0)+ .write_timeout(10.0)+ .connect_timeout(10.0)+ .build()+ )self._bot = self._application.botself._token = token@@ -197,6 +210,13 @@ class TelegramService:logger.error(f"[Telegram] Disconnect error: {e}")return {"success": False, "error": str(e)}+ def _on_polling_error(self, error) -> None:+ """Handle polling errors (called by PTB's internal retry loop)."""+ if isinstance(error, NetworkError):+ logger.debug(f"[Telegram] Network error during polling (auto-retrying): {error}")+ else:+ logger.error(f"[Telegram] Polling error: {error}")+async def _run_polling(self):"""Run polling loop in background."""try:@@ -205,6 +225,7 @@ class TelegramService:await self._application.updater.start_polling(drop_pending_updates=True,allowed_updates=Update.ALL_TYPES,+ error_callback=self._on_polling_error,)# Keep running until cancelled