2026-03-19 20:46:20 -04:00
|
|
|
"""LLM backends — Grok (xAI) and Claude (Anthropic).
|
2026-02-21 16:53:16 +00:00
|
|
|
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
Provides drop-in replacements for the Agno Agent that expose the same
|
|
|
|
|
run(message, stream) → RunResult interface used by the dashboard and the
|
|
|
|
|
print_response(message, stream) interface used by the CLI.
|
2026-02-21 16:53:16 +00:00
|
|
|
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
Backends:
|
|
|
|
|
- GrokBackend: xAI Grok API via OpenAI-compatible SDK (opt-in premium)
|
2026-02-28 09:35:44 -05:00
|
|
|
- ClaudeBackend: Anthropic Claude API — lightweight cloud fallback
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
|
|
|
|
|
No cloud by default. No telemetry. Sats are sovereignty, boss.
|
2026-02-21 16:53:16 +00:00
|
|
|
"""
|
|
|
|
|
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
import logging
|
2026-02-21 16:53:16 +00:00
|
|
|
import platform
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
import time
|
ruff (#169)
* polish: streamline nav, extract inline styles, improve tablet UX
- Restructure desktop nav from 8+ flat links + overflow dropdown into
5 grouped dropdowns (Core, Agents, Intel, System, More) matching
the mobile menu structure to reduce decision fatigue
- Extract all inline styles from mission_control.html and base.html
notification elements into mission-control.css with semantic classes
- Replace JS-built innerHTML with secure DOM construction in
notification loader and chat history
- Add CONNECTING state to connection indicator (amber) instead of
showing OFFLINE before WebSocket connects
- Add tablet breakpoint (1024px) with larger touch targets for
Apple Pencil / stylus use and safe-area padding for iPad toolbar
- Add active-link highlighting in desktop dropdown menus
- Rename "Mission Control" page title to "System Overview" to
disambiguate from the chat home page
- Add "Home — Timmy Time" page title to index.html
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* fix(security): move auth-gate credentials to environment variables
Hardcoded username, password, and HMAC secret in auth-gate.py replaced
with os.environ lookups. Startup now refuses to run if any variable is
unset. Added AUTH_GATE_SECRET/USER/PASS to .env.example.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* refactor(tooling): migrate from black+isort+bandit to ruff
Replace three separate linting/formatting tools with a single ruff
invocation. Updates tox.ini (lint, format, pre-push, pre-commit envs),
.pre-commit-config.yaml, and CI workflow. Fixes all ruff errors
including unused imports, missing raise-from, and undefined names.
Ruff config maps existing bandit skips to equivalent S-rules.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-11 12:23:35 -04:00
|
|
|
from dataclasses import dataclass
|
2026-02-21 16:53:16 +00:00
|
|
|
|
[loop-cycle-40] fix: use get_system_prompt() in cloud backends (#135) (#138)
## What
Cloud backends (Grok, Claude, AirLLM) were importing SYSTEM_PROMPT directly, which is always SYSTEM_PROMPT_LITE and contains unformatted {model_name} and {session_id} placeholders.
## Changes
- backends.py: Replace `from timmy.prompts import SYSTEM_PROMPT` with `from timmy.prompts import get_system_prompt`
- AirLLM: uses `get_system_prompt(tools_enabled=False, session_id="airllm")` (LITE tier, correct)
- Grok: uses `get_system_prompt(tools_enabled=True, session_id="grok")` (FULL tier)
- Claude: uses `get_system_prompt(tools_enabled=True, session_id="claude")` (FULL tier)
- 9 new tests verify formatted model names, correct tier selection, and session_id formatting
## Tests
1508 passed, 0 failed (41 new tests this cycle)
Fixes #135
Co-authored-by: Kimi Agent <kimi@timmy.local>
Reviewed-on: http://localhost:3000/rockachopa/Timmy-time-dashboard/pulls/138
Reviewed-by: rockachopa <alexpaynex@gmail.com>
Co-authored-by: hermes <hermes@timmy.local>
Co-committed-by: hermes <hermes@timmy.local>
2026-03-15 09:44:43 -04:00
|
|
|
from timmy.prompts import get_system_prompt
|
2026-02-21 16:53:16 +00:00
|
|
|
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2026-02-21 16:53:16 +00:00
|
|
|
|
feat: quality analysis — bug fixes, mobile tests, HITL checklist
Senior architect review findings + remediations:
BUG FIX — critical interface mismatch
- TimmyAirLLMAgent only exposed print_response(); dashboard route calls
agent.run() → AttributeError when AirLLM backend is selected.
Added run() → RunResult(content) as primary inference entry point;
print_response() now delegates to run() so both call sites share
one inference path.
- Added RunResult dataclass for Agno-compatible structured return.
BUG FIX — hardcoded model name in health status partial
- health_status.html rendered literal "llama3.2" regardless of
OLLAMA_MODEL env var. Route now passes settings.ollama_model to
the template context; partial renders {{ model }} instead.
FEATURE — /mobile-test HITL checklist page
- 22 human-executable test scenarios across: Layout, Touch & Input,
Chat behaviour, Health, Scroll, Notch/Home Bar, Live UI.
- Pass/Fail/Skip buttons with sessionStorage state persistence.
- Live progress bar + final score summary.
- TEST link added to Mission Control header for quick access on phone.
TEST — 32 new automated mobile quality tests (M1xx–M6xx)
- M1xx: viewport/meta tags (8 tests)
- M2xx: touch target sizing — 44 px min-height, manipulation (4 tests)
- M3xx: iOS zoom prevention, autocapitalize, enterkeyhint (5 tests)
- M4xx: HTMX robustness — hx-sync drop, disabled-elt, polling (5 tests)
- M5xx: safe-area insets, overscroll, dvh units (5 tests)
- M6xx: AirLLM interface contract — run(), RunResult, delegation (5 tests)
Total test count: 61 → 93 (all passing).
https://claude.ai/code/session_01RBuRCBXZNkAQQXXGiJNDmt
2026-02-21 17:21:47 +00:00
|
|
|
@dataclass
|
|
|
|
|
class RunResult:
|
|
|
|
|
"""Minimal Agno-compatible run result — carries the model's response text."""
|
2026-03-08 12:50:44 -04:00
|
|
|
|
feat: quality analysis — bug fixes, mobile tests, HITL checklist
Senior architect review findings + remediations:
BUG FIX — critical interface mismatch
- TimmyAirLLMAgent only exposed print_response(); dashboard route calls
agent.run() → AttributeError when AirLLM backend is selected.
Added run() → RunResult(content) as primary inference entry point;
print_response() now delegates to run() so both call sites share
one inference path.
- Added RunResult dataclass for Agno-compatible structured return.
BUG FIX — hardcoded model name in health status partial
- health_status.html rendered literal "llama3.2" regardless of
OLLAMA_MODEL env var. Route now passes settings.ollama_model to
the template context; partial renders {{ model }} instead.
FEATURE — /mobile-test HITL checklist page
- 22 human-executable test scenarios across: Layout, Touch & Input,
Chat behaviour, Health, Scroll, Notch/Home Bar, Live UI.
- Pass/Fail/Skip buttons with sessionStorage state persistence.
- Live progress bar + final score summary.
- TEST link added to Mission Control header for quick access on phone.
TEST — 32 new automated mobile quality tests (M1xx–M6xx)
- M1xx: viewport/meta tags (8 tests)
- M2xx: touch target sizing — 44 px min-height, manipulation (4 tests)
- M3xx: iOS zoom prevention, autocapitalize, enterkeyhint (5 tests)
- M4xx: HTMX robustness — hx-sync drop, disabled-elt, polling (5 tests)
- M5xx: safe-area insets, overscroll, dvh units (5 tests)
- M6xx: AirLLM interface contract — run(), RunResult, delegation (5 tests)
Total test count: 61 → 93 (all passing).
https://claude.ai/code/session_01RBuRCBXZNkAQQXXGiJNDmt
2026-02-21 17:21:47 +00:00
|
|
|
content: str
|
2026-03-15 11:20:30 -04:00
|
|
|
confidence: float | None = None
|
feat: quality analysis — bug fixes, mobile tests, HITL checklist
Senior architect review findings + remediations:
BUG FIX — critical interface mismatch
- TimmyAirLLMAgent only exposed print_response(); dashboard route calls
agent.run() → AttributeError when AirLLM backend is selected.
Added run() → RunResult(content) as primary inference entry point;
print_response() now delegates to run() so both call sites share
one inference path.
- Added RunResult dataclass for Agno-compatible structured return.
BUG FIX — hardcoded model name in health status partial
- health_status.html rendered literal "llama3.2" regardless of
OLLAMA_MODEL env var. Route now passes settings.ollama_model to
the template context; partial renders {{ model }} instead.
FEATURE — /mobile-test HITL checklist page
- 22 human-executable test scenarios across: Layout, Touch & Input,
Chat behaviour, Health, Scroll, Notch/Home Bar, Live UI.
- Pass/Fail/Skip buttons with sessionStorage state persistence.
- Live progress bar + final score summary.
- TEST link added to Mission Control header for quick access on phone.
TEST — 32 new automated mobile quality tests (M1xx–M6xx)
- M1xx: viewport/meta tags (8 tests)
- M2xx: touch target sizing — 44 px min-height, manipulation (4 tests)
- M3xx: iOS zoom prevention, autocapitalize, enterkeyhint (5 tests)
- M4xx: HTMX robustness — hx-sync drop, disabled-elt, polling (5 tests)
- M5xx: safe-area insets, overscroll, dvh units (5 tests)
- M6xx: AirLLM interface contract — run(), RunResult, delegation (5 tests)
Total test count: 61 → 93 (all passing).
https://claude.ai/code/session_01RBuRCBXZNkAQQXXGiJNDmt
2026-02-21 17:21:47 +00:00
|
|
|
|
|
|
|
|
|
2026-02-21 16:53:16 +00:00
|
|
|
def is_apple_silicon() -> bool:
|
|
|
|
|
"""Return True when running on an M-series Mac (arm64 Darwin)."""
|
|
|
|
|
return platform.system() == "Darwin" and platform.machine() == "arm64"
|
|
|
|
|
|
|
|
|
|
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
# ── Grok (xAI) Backend ─────────────────────────────────────────────────────
|
|
|
|
|
# Premium cloud augmentation — opt-in only, never the default path.
|
|
|
|
|
|
|
|
|
|
# Available Grok models (configurable via GROK_DEFAULT_MODEL)
|
|
|
|
|
GROK_MODELS: dict[str, str] = {
|
|
|
|
|
"grok-3-fast": "grok-3-fast",
|
|
|
|
|
"grok-3": "grok-3",
|
|
|
|
|
"grok-3-mini": "grok-3-mini",
|
|
|
|
|
"grok-3-mini-fast": "grok-3-mini-fast",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class GrokUsageStats:
|
|
|
|
|
"""Tracks Grok API usage for cost monitoring and Spark logging."""
|
2026-03-08 12:50:44 -04:00
|
|
|
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
total_requests: int = 0
|
|
|
|
|
total_prompt_tokens: int = 0
|
|
|
|
|
total_completion_tokens: int = 0
|
|
|
|
|
total_latency_ms: float = 0.0
|
|
|
|
|
errors: int = 0
|
ruff (#169)
* polish: streamline nav, extract inline styles, improve tablet UX
- Restructure desktop nav from 8+ flat links + overflow dropdown into
5 grouped dropdowns (Core, Agents, Intel, System, More) matching
the mobile menu structure to reduce decision fatigue
- Extract all inline styles from mission_control.html and base.html
notification elements into mission-control.css with semantic classes
- Replace JS-built innerHTML with secure DOM construction in
notification loader and chat history
- Add CONNECTING state to connection indicator (amber) instead of
showing OFFLINE before WebSocket connects
- Add tablet breakpoint (1024px) with larger touch targets for
Apple Pencil / stylus use and safe-area padding for iPad toolbar
- Add active-link highlighting in desktop dropdown menus
- Rename "Mission Control" page title to "System Overview" to
disambiguate from the chat home page
- Add "Home — Timmy Time" page title to index.html
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* fix(security): move auth-gate credentials to environment variables
Hardcoded username, password, and HMAC secret in auth-gate.py replaced
with os.environ lookups. Startup now refuses to run if any variable is
unset. Added AUTH_GATE_SECRET/USER/PASS to .env.example.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* refactor(tooling): migrate from black+isort+bandit to ruff
Replace three separate linting/formatting tools with a single ruff
invocation. Updates tox.ini (lint, format, pre-push, pre-commit envs),
.pre-commit-config.yaml, and CI workflow. Fixes all ruff errors
including unused imports, missing raise-from, and undefined names.
Ruff config maps existing bandit skips to equivalent S-rules.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-11 12:23:35 -04:00
|
|
|
last_request_at: float | None = None
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def estimated_cost_sats(self) -> int:
|
|
|
|
|
"""Rough cost estimate in sats based on token usage."""
|
|
|
|
|
# ~$5/1M input tokens, ~$15/1M output tokens for Grok
|
|
|
|
|
# At ~$100k/BTC, 1 sat ≈ $0.001
|
|
|
|
|
input_cost = (self.total_prompt_tokens / 1_000_000) * 5
|
|
|
|
|
output_cost = (self.total_completion_tokens / 1_000_000) * 15
|
|
|
|
|
total_usd = input_cost + output_cost
|
|
|
|
|
return int(total_usd / 0.001) # Convert to sats
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class GrokBackend:
|
|
|
|
|
"""xAI Grok backend — premium cloud augmentation for frontier reasoning.
|
|
|
|
|
|
|
|
|
|
Uses the OpenAI-compatible SDK to connect to xAI's API.
|
|
|
|
|
Only activated when GROK_ENABLED=true and XAI_API_KEY is set.
|
|
|
|
|
|
2026-03-19 20:46:20 -04:00
|
|
|
Exposes the same interface as Agno Agent:
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
run(message, stream) → RunResult [dashboard]
|
|
|
|
|
print_response(message, stream) → None [CLI]
|
|
|
|
|
health_check() → dict [monitoring]
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
ruff (#169)
* polish: streamline nav, extract inline styles, improve tablet UX
- Restructure desktop nav from 8+ flat links + overflow dropdown into
5 grouped dropdowns (Core, Agents, Intel, System, More) matching
the mobile menu structure to reduce decision fatigue
- Extract all inline styles from mission_control.html and base.html
notification elements into mission-control.css with semantic classes
- Replace JS-built innerHTML with secure DOM construction in
notification loader and chat history
- Add CONNECTING state to connection indicator (amber) instead of
showing OFFLINE before WebSocket connects
- Add tablet breakpoint (1024px) with larger touch targets for
Apple Pencil / stylus use and safe-area padding for iPad toolbar
- Add active-link highlighting in desktop dropdown menus
- Rename "Mission Control" page title to "System Overview" to
disambiguate from the chat home page
- Add "Home — Timmy Time" page title to index.html
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* fix(security): move auth-gate credentials to environment variables
Hardcoded username, password, and HMAC secret in auth-gate.py replaced
with os.environ lookups. Startup now refuses to run if any variable is
unset. Added AUTH_GATE_SECRET/USER/PASS to .env.example.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* refactor(tooling): migrate from black+isort+bandit to ruff
Replace three separate linting/formatting tools with a single ruff
invocation. Updates tox.ini (lint, format, pre-push, pre-commit envs),
.pre-commit-config.yaml, and CI workflow. Fixes all ruff errors
including unused imports, missing raise-from, and undefined names.
Ruff config maps existing bandit skips to equivalent S-rules.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-11 12:23:35 -04:00
|
|
|
api_key: str | None = None,
|
|
|
|
|
model: str | None = None,
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
) -> None:
|
|
|
|
|
from config import settings
|
|
|
|
|
|
fix: Docker-first test suite, UX improvements, and bug fixes (#100)
Dashboard UX:
- Restructure nav from 22 flat links to 6 core + MORE dropdown
- Add mobile nav section labels (Core, Intelligence, Agents, System, Commerce)
- Defer marked.js and dompurify.js loading, consolidate CDN to jsdelivr
- Optimize font weights (drop unused 300/500), bump style.css cache buster
- Remove duplicate HTMX load triggers from sidebar and health panels
Bug fixes:
- Fix Timmy showing OFFLINE by registering after swarm recovery sweep
- Fix ThinkingEngine await bug with asyncio.run_coroutine_threadsafe
- Fix chat auto-scroll by calling scrollChat() after history partial loads
- Add missing /voice/button page and /voice/command endpoint
- Fix Grok api_key="" treated as falsy falling through to env key
- Fix self_modify PROJECT_ROOT using settings.repo_root instead of __file__
Docker test infrastructure:
- Bind-mount hands/, docker/, Dockerfiles, and compose files into test container
- Add fontconfig + fonts-dejavu-core for creative/assembler TextClip tests
- Initialize minimal git repo in Dockerfile.test for GitSafety compatibility
- Fix introspection and path resolution tests for Docker /app context
All 1863 tests pass in Docker (0 failures, 77 skipped).
Co-authored-by: Alexander Payne <apayne@MM.local>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 22:14:37 -05:00
|
|
|
self._api_key = api_key if api_key is not None else settings.xai_api_key
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
self._model = model or settings.grok_default_model
|
|
|
|
|
self._history: list[dict[str, str]] = []
|
|
|
|
|
self.stats = GrokUsageStats()
|
|
|
|
|
|
|
|
|
|
if not self._api_key:
|
|
|
|
|
logger.warning(
|
ruff (#169)
* polish: streamline nav, extract inline styles, improve tablet UX
- Restructure desktop nav from 8+ flat links + overflow dropdown into
5 grouped dropdowns (Core, Agents, Intel, System, More) matching
the mobile menu structure to reduce decision fatigue
- Extract all inline styles from mission_control.html and base.html
notification elements into mission-control.css with semantic classes
- Replace JS-built innerHTML with secure DOM construction in
notification loader and chat history
- Add CONNECTING state to connection indicator (amber) instead of
showing OFFLINE before WebSocket connects
- Add tablet breakpoint (1024px) with larger touch targets for
Apple Pencil / stylus use and safe-area padding for iPad toolbar
- Add active-link highlighting in desktop dropdown menus
- Rename "Mission Control" page title to "System Overview" to
disambiguate from the chat home page
- Add "Home — Timmy Time" page title to index.html
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* fix(security): move auth-gate credentials to environment variables
Hardcoded username, password, and HMAC secret in auth-gate.py replaced
with os.environ lookups. Startup now refuses to run if any variable is
unset. Added AUTH_GATE_SECRET/USER/PASS to .env.example.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* refactor(tooling): migrate from black+isort+bandit to ruff
Replace three separate linting/formatting tools with a single ruff
invocation. Updates tox.ini (lint, format, pre-push, pre-commit envs),
.pre-commit-config.yaml, and CI workflow. Fixes all ruff errors
including unused imports, missing raise-from, and undefined names.
Ruff config maps existing bandit skips to equivalent S-rules.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-11 12:23:35 -04:00
|
|
|
"GrokBackend created without XAI_API_KEY — calls will fail until key is configured"
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def _get_client(self):
|
|
|
|
|
"""Create OpenAI client configured for xAI endpoint."""
|
|
|
|
|
import httpx
|
|
|
|
|
from openai import OpenAI
|
|
|
|
|
|
2026-03-21 03:41:09 +00:00
|
|
|
from config import settings
|
|
|
|
|
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
return OpenAI(
|
|
|
|
|
api_key=self._api_key,
|
2026-03-20 22:47:05 +00:00
|
|
|
base_url=settings.xai_base_url,
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
timeout=httpx.Timeout(300.0),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
async def _get_async_client(self):
|
|
|
|
|
"""Create async OpenAI client configured for xAI endpoint."""
|
|
|
|
|
import httpx
|
|
|
|
|
from openai import AsyncOpenAI
|
|
|
|
|
|
2026-03-21 03:41:09 +00:00
|
|
|
from config import settings
|
|
|
|
|
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
return AsyncOpenAI(
|
|
|
|
|
api_key=self._api_key,
|
2026-03-20 22:47:05 +00:00
|
|
|
base_url=settings.xai_base_url,
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
timeout=httpx.Timeout(300.0),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# ── Public interface (mirrors Agno Agent) ─────────────────────────────
|
|
|
|
|
|
|
|
|
|
def run(self, message: str, *, stream: bool = False) -> RunResult:
|
|
|
|
|
"""Synchronous inference via Grok API.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
message: User prompt
|
|
|
|
|
stream: Accepted for API compat; Grok returns full response
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
RunResult with response content
|
|
|
|
|
"""
|
|
|
|
|
if not self._api_key:
|
2026-03-08 12:50:44 -04:00
|
|
|
return RunResult(content="Grok is not configured. Set XAI_API_KEY to enable.")
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
|
|
|
|
|
start = time.time()
|
|
|
|
|
messages = self._build_messages(message)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
client = self._get_client()
|
|
|
|
|
response = client.chat.completions.create(
|
|
|
|
|
model=self._model,
|
|
|
|
|
messages=messages,
|
|
|
|
|
temperature=0.7,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
content = response.choices[0].message.content or ""
|
|
|
|
|
latency_ms = (time.time() - start) * 1000
|
|
|
|
|
|
|
|
|
|
# Track usage
|
|
|
|
|
self.stats.total_requests += 1
|
|
|
|
|
self.stats.total_latency_ms += latency_ms
|
|
|
|
|
self.stats.last_request_at = time.time()
|
|
|
|
|
if response.usage:
|
|
|
|
|
self.stats.total_prompt_tokens += response.usage.prompt_tokens
|
|
|
|
|
self.stats.total_completion_tokens += response.usage.completion_tokens
|
|
|
|
|
|
|
|
|
|
# Update conversation history
|
|
|
|
|
self._history.append({"role": "user", "content": message})
|
|
|
|
|
self._history.append({"role": "assistant", "content": content})
|
|
|
|
|
# Keep last 10 turns
|
|
|
|
|
if len(self._history) > 20:
|
|
|
|
|
self._history = self._history[-20:]
|
|
|
|
|
|
|
|
|
|
logger.info(
|
|
|
|
|
"Grok response: %d tokens in %.0fms (model=%s)",
|
|
|
|
|
response.usage.completion_tokens if response.usage else 0,
|
|
|
|
|
latency_ms,
|
|
|
|
|
self._model,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return RunResult(content=content)
|
|
|
|
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
self.stats.errors += 1
|
|
|
|
|
logger.error("Grok API error: %s", exc)
|
2026-03-08 12:50:44 -04:00
|
|
|
return RunResult(content=f"Grok temporarily unavailable: {exc}")
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
|
|
|
|
|
async def arun(self, message: str) -> RunResult:
|
|
|
|
|
"""Async inference via Grok API — used by cascade router and tools."""
|
|
|
|
|
if not self._api_key:
|
2026-03-08 12:50:44 -04:00
|
|
|
return RunResult(content="Grok is not configured. Set XAI_API_KEY to enable.")
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
|
|
|
|
|
start = time.time()
|
|
|
|
|
messages = self._build_messages(message)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
client = await self._get_async_client()
|
|
|
|
|
response = await client.chat.completions.create(
|
|
|
|
|
model=self._model,
|
|
|
|
|
messages=messages,
|
|
|
|
|
temperature=0.7,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
content = response.choices[0].message.content or ""
|
|
|
|
|
latency_ms = (time.time() - start) * 1000
|
|
|
|
|
|
|
|
|
|
# Track usage
|
|
|
|
|
self.stats.total_requests += 1
|
|
|
|
|
self.stats.total_latency_ms += latency_ms
|
|
|
|
|
self.stats.last_request_at = time.time()
|
|
|
|
|
if response.usage:
|
|
|
|
|
self.stats.total_prompt_tokens += response.usage.prompt_tokens
|
|
|
|
|
self.stats.total_completion_tokens += response.usage.completion_tokens
|
|
|
|
|
|
|
|
|
|
# Update conversation history
|
|
|
|
|
self._history.append({"role": "user", "content": message})
|
|
|
|
|
self._history.append({"role": "assistant", "content": content})
|
|
|
|
|
if len(self._history) > 20:
|
|
|
|
|
self._history = self._history[-20:]
|
|
|
|
|
|
|
|
|
|
logger.info(
|
|
|
|
|
"Grok async response: %d tokens in %.0fms (model=%s)",
|
|
|
|
|
response.usage.completion_tokens if response.usage else 0,
|
|
|
|
|
latency_ms,
|
|
|
|
|
self._model,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return RunResult(content=content)
|
|
|
|
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
self.stats.errors += 1
|
|
|
|
|
logger.error("Grok async API error: %s", exc)
|
2026-03-08 12:50:44 -04:00
|
|
|
return RunResult(content=f"Grok temporarily unavailable: {exc}")
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
|
|
|
|
|
def print_response(self, message: str, *, stream: bool = True) -> None:
|
|
|
|
|
"""Run inference and render the response to stdout (CLI interface)."""
|
|
|
|
|
result = self.run(message, stream=stream)
|
|
|
|
|
try:
|
|
|
|
|
from rich.console import Console
|
|
|
|
|
from rich.markdown import Markdown
|
2026-03-08 12:50:44 -04:00
|
|
|
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
Console().print(Markdown(result.content))
|
|
|
|
|
except ImportError:
|
|
|
|
|
print(result.content)
|
|
|
|
|
|
|
|
|
|
def health_check(self) -> dict:
|
|
|
|
|
"""Check Grok API connectivity and return status."""
|
|
|
|
|
if not self._api_key:
|
|
|
|
|
return {
|
|
|
|
|
"ok": False,
|
|
|
|
|
"error": "XAI_API_KEY not configured",
|
|
|
|
|
"backend": "grok",
|
|
|
|
|
"model": self._model,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
client = self._get_client()
|
|
|
|
|
# Lightweight check — list models
|
|
|
|
|
client.models.list()
|
|
|
|
|
return {
|
|
|
|
|
"ok": True,
|
|
|
|
|
"error": None,
|
|
|
|
|
"backend": "grok",
|
|
|
|
|
"model": self._model,
|
|
|
|
|
"stats": {
|
|
|
|
|
"total_requests": self.stats.total_requests,
|
|
|
|
|
"estimated_cost_sats": self.stats.estimated_cost_sats,
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
except Exception as exc:
|
2026-03-21 03:50:26 +00:00
|
|
|
logger.exception("Grok health check failed")
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
return {
|
|
|
|
|
"ok": False,
|
|
|
|
|
"error": str(exc),
|
|
|
|
|
"backend": "grok",
|
|
|
|
|
"model": self._model,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def estimated_cost(self) -> int:
|
|
|
|
|
"""Return estimated cost in sats for all requests so far."""
|
|
|
|
|
return self.stats.estimated_cost_sats
|
|
|
|
|
|
|
|
|
|
# ── Private helpers ───────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
def _build_messages(self, message: str) -> list[dict[str, str]]:
|
|
|
|
|
"""Build the messages array for the API call."""
|
[loop-cycle-40] fix: use get_system_prompt() in cloud backends (#135) (#138)
## What
Cloud backends (Grok, Claude, AirLLM) were importing SYSTEM_PROMPT directly, which is always SYSTEM_PROMPT_LITE and contains unformatted {model_name} and {session_id} placeholders.
## Changes
- backends.py: Replace `from timmy.prompts import SYSTEM_PROMPT` with `from timmy.prompts import get_system_prompt`
- AirLLM: uses `get_system_prompt(tools_enabled=False, session_id="airllm")` (LITE tier, correct)
- Grok: uses `get_system_prompt(tools_enabled=True, session_id="grok")` (FULL tier)
- Claude: uses `get_system_prompt(tools_enabled=True, session_id="claude")` (FULL tier)
- 9 new tests verify formatted model names, correct tier selection, and session_id formatting
## Tests
1508 passed, 0 failed (41 new tests this cycle)
Fixes #135
Co-authored-by: Kimi Agent <kimi@timmy.local>
Reviewed-on: http://localhost:3000/rockachopa/Timmy-time-dashboard/pulls/138
Reviewed-by: rockachopa <alexpaynex@gmail.com>
Co-authored-by: hermes <hermes@timmy.local>
Co-committed-by: hermes <hermes@timmy.local>
2026-03-15 09:44:43 -04:00
|
|
|
messages = [
|
|
|
|
|
{"role": "system", "content": get_system_prompt(tools_enabled=True, session_id="grok")}
|
|
|
|
|
]
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
# Include conversation history for context
|
|
|
|
|
messages.extend(self._history[-10:])
|
|
|
|
|
messages.append({"role": "user", "content": message})
|
|
|
|
|
return messages
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ── Module-level Grok singleton ─────────────────────────────────────────────
|
|
|
|
|
|
ruff (#169)
* polish: streamline nav, extract inline styles, improve tablet UX
- Restructure desktop nav from 8+ flat links + overflow dropdown into
5 grouped dropdowns (Core, Agents, Intel, System, More) matching
the mobile menu structure to reduce decision fatigue
- Extract all inline styles from mission_control.html and base.html
notification elements into mission-control.css with semantic classes
- Replace JS-built innerHTML with secure DOM construction in
notification loader and chat history
- Add CONNECTING state to connection indicator (amber) instead of
showing OFFLINE before WebSocket connects
- Add tablet breakpoint (1024px) with larger touch targets for
Apple Pencil / stylus use and safe-area padding for iPad toolbar
- Add active-link highlighting in desktop dropdown menus
- Rename "Mission Control" page title to "System Overview" to
disambiguate from the chat home page
- Add "Home — Timmy Time" page title to index.html
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* fix(security): move auth-gate credentials to environment variables
Hardcoded username, password, and HMAC secret in auth-gate.py replaced
with os.environ lookups. Startup now refuses to run if any variable is
unset. Added AUTH_GATE_SECRET/USER/PASS to .env.example.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* refactor(tooling): migrate from black+isort+bandit to ruff
Replace three separate linting/formatting tools with a single ruff
invocation. Updates tox.ini (lint, format, pre-push, pre-commit envs),
.pre-commit-config.yaml, and CI workflow. Fixes all ruff errors
including unused imports, missing raise-from, and undefined names.
Ruff config maps existing bandit skips to equivalent S-rules.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-11 12:23:35 -04:00
|
|
|
_grok_backend: GrokBackend | None = None
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_grok_backend() -> GrokBackend:
|
|
|
|
|
"""Get or create the Grok backend singleton."""
|
|
|
|
|
global _grok_backend
|
|
|
|
|
if _grok_backend is None:
|
|
|
|
|
_grok_backend = GrokBackend()
|
|
|
|
|
return _grok_backend
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def grok_available() -> bool:
|
|
|
|
|
"""Return True when Grok is enabled and API key is configured."""
|
|
|
|
|
try:
|
|
|
|
|
from config import settings
|
2026-03-08 12:50:44 -04:00
|
|
|
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
return settings.grok_enabled and bool(settings.xai_api_key)
|
2026-03-14 19:07:14 -04:00
|
|
|
except Exception as exc:
|
|
|
|
|
logger.warning("Backend check failed (grok_available): %s", exc)
|
feat: add Grok (xAI) as opt-in premium backend with monetization
- Add GrokBackend class in src/timmy/backends.py with full sync/async
support, health checks, usage stats, and cost estimation in sats
- Add consult_grok tool to Timmy's toolkit for proactive Grok queries
- Extend cascade router with Grok provider type for failover chain
- Add Grok Mode toggle card to Mission Control dashboard (HTMX live)
- Add "Ask Grok" button on chat input for direct Grok queries
- Add /grok/* routes: status, toggle, chat, stats endpoints
- Integrate Lightning invoice generation for Grok usage monetization
- Add GROK_ENABLED, XAI_API_KEY, GROK_DEFAULT_MODEL, GROK_MAX_SATS_PER_QUERY,
GROK_FREE config settings via pydantic-settings
- Update .env.example and docker-compose.yml with Grok env vars
- Add 21 tests covering backend, tools, and route endpoints (all green)
Local-first ethos preserved: Grok is premium augmentation only,
disabled by default, and Lightning-payable when enabled.
https://claude.ai/code/session_01FygwN8wS8J6WGZ8FPb7XGV
2026-02-27 01:12:51 +00:00
|
|
|
return False
|
2026-02-28 09:35:44 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# ── Claude (Anthropic) Backend ─────────────────────────────────────────────
|
|
|
|
|
# Lightweight cloud fallback — used when Ollama is offline and the user
|
|
|
|
|
# has set ANTHROPIC_API_KEY. Follows the same sovereign-first philosophy:
|
|
|
|
|
# never the default, only activated explicitly or as a last-resort fallback.
|
|
|
|
|
|
|
|
|
|
CLAUDE_MODELS: dict[str, str] = {
|
|
|
|
|
"haiku": "claude-haiku-4-5-20251001",
|
|
|
|
|
"sonnet": "claude-sonnet-4-20250514",
|
|
|
|
|
"opus": "claude-opus-4-20250514",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ClaudeBackend:
|
|
|
|
|
"""Anthropic Claude backend — cloud fallback when local models are offline.
|
|
|
|
|
|
2026-03-19 20:46:20 -04:00
|
|
|
Uses the official Anthropic SDK. Same interface as GrokBackend:
|
2026-02-28 09:35:44 -05:00
|
|
|
run(message, stream) → RunResult [dashboard]
|
|
|
|
|
print_response(message, stream) → None [CLI]
|
|
|
|
|
health_check() → dict [monitoring]
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
ruff (#169)
* polish: streamline nav, extract inline styles, improve tablet UX
- Restructure desktop nav from 8+ flat links + overflow dropdown into
5 grouped dropdowns (Core, Agents, Intel, System, More) matching
the mobile menu structure to reduce decision fatigue
- Extract all inline styles from mission_control.html and base.html
notification elements into mission-control.css with semantic classes
- Replace JS-built innerHTML with secure DOM construction in
notification loader and chat history
- Add CONNECTING state to connection indicator (amber) instead of
showing OFFLINE before WebSocket connects
- Add tablet breakpoint (1024px) with larger touch targets for
Apple Pencil / stylus use and safe-area padding for iPad toolbar
- Add active-link highlighting in desktop dropdown menus
- Rename "Mission Control" page title to "System Overview" to
disambiguate from the chat home page
- Add "Home — Timmy Time" page title to index.html
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* fix(security): move auth-gate credentials to environment variables
Hardcoded username, password, and HMAC secret in auth-gate.py replaced
with os.environ lookups. Startup now refuses to run if any variable is
unset. Added AUTH_GATE_SECRET/USER/PASS to .env.example.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* refactor(tooling): migrate from black+isort+bandit to ruff
Replace three separate linting/formatting tools with a single ruff
invocation. Updates tox.ini (lint, format, pre-push, pre-commit envs),
.pre-commit-config.yaml, and CI workflow. Fixes all ruff errors
including unused imports, missing raise-from, and undefined names.
Ruff config maps existing bandit skips to equivalent S-rules.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-11 12:23:35 -04:00
|
|
|
api_key: str | None = None,
|
|
|
|
|
model: str | None = None,
|
2026-02-28 09:35:44 -05:00
|
|
|
) -> None:
|
|
|
|
|
from config import settings
|
|
|
|
|
|
|
|
|
|
self._api_key = api_key or settings.anthropic_api_key
|
|
|
|
|
raw_model = model or settings.claude_model
|
|
|
|
|
# Allow short names like "haiku" / "sonnet" / "opus"
|
|
|
|
|
self._model = CLAUDE_MODELS.get(raw_model, raw_model)
|
|
|
|
|
self._history: list[dict[str, str]] = []
|
|
|
|
|
|
|
|
|
|
if not self._api_key:
|
|
|
|
|
logger.warning(
|
|
|
|
|
"ClaudeBackend created without ANTHROPIC_API_KEY — "
|
|
|
|
|
"calls will fail until key is configured"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def _get_client(self):
|
|
|
|
|
"""Create Anthropic client."""
|
|
|
|
|
import anthropic
|
|
|
|
|
|
|
|
|
|
return anthropic.Anthropic(api_key=self._api_key)
|
|
|
|
|
|
|
|
|
|
# ── Public interface (mirrors Agno Agent) ─────────────────────────────
|
|
|
|
|
|
|
|
|
|
def run(self, message: str, *, stream: bool = False, **kwargs) -> RunResult:
|
|
|
|
|
"""Synchronous inference via Claude API."""
|
|
|
|
|
if not self._api_key:
|
2026-03-08 12:50:44 -04:00
|
|
|
return RunResult(content="Claude is not configured. Set ANTHROPIC_API_KEY to enable.")
|
2026-02-28 09:35:44 -05:00
|
|
|
|
|
|
|
|
start = time.time()
|
|
|
|
|
messages = self._build_messages(message)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
client = self._get_client()
|
|
|
|
|
response = client.messages.create(
|
|
|
|
|
model=self._model,
|
|
|
|
|
max_tokens=1024,
|
[loop-cycle-40] fix: use get_system_prompt() in cloud backends (#135) (#138)
## What
Cloud backends (Grok, Claude, AirLLM) were importing SYSTEM_PROMPT directly, which is always SYSTEM_PROMPT_LITE and contains unformatted {model_name} and {session_id} placeholders.
## Changes
- backends.py: Replace `from timmy.prompts import SYSTEM_PROMPT` with `from timmy.prompts import get_system_prompt`
- AirLLM: uses `get_system_prompt(tools_enabled=False, session_id="airllm")` (LITE tier, correct)
- Grok: uses `get_system_prompt(tools_enabled=True, session_id="grok")` (FULL tier)
- Claude: uses `get_system_prompt(tools_enabled=True, session_id="claude")` (FULL tier)
- 9 new tests verify formatted model names, correct tier selection, and session_id formatting
## Tests
1508 passed, 0 failed (41 new tests this cycle)
Fixes #135
Co-authored-by: Kimi Agent <kimi@timmy.local>
Reviewed-on: http://localhost:3000/rockachopa/Timmy-time-dashboard/pulls/138
Reviewed-by: rockachopa <alexpaynex@gmail.com>
Co-authored-by: hermes <hermes@timmy.local>
Co-committed-by: hermes <hermes@timmy.local>
2026-03-15 09:44:43 -04:00
|
|
|
system=get_system_prompt(tools_enabled=True, session_id="claude"),
|
2026-02-28 09:35:44 -05:00
|
|
|
messages=messages,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
content = response.content[0].text if response.content else ""
|
|
|
|
|
latency_ms = (time.time() - start) * 1000
|
|
|
|
|
|
|
|
|
|
# Update conversation history
|
|
|
|
|
self._history.append({"role": "user", "content": message})
|
|
|
|
|
self._history.append({"role": "assistant", "content": content})
|
|
|
|
|
if len(self._history) > 20:
|
|
|
|
|
self._history = self._history[-20:]
|
|
|
|
|
|
|
|
|
|
logger.info(
|
|
|
|
|
"Claude response: %d chars in %.0fms (model=%s)",
|
|
|
|
|
len(content),
|
|
|
|
|
latency_ms,
|
|
|
|
|
self._model,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return RunResult(content=content)
|
|
|
|
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
logger.error("Claude API error: %s", exc)
|
2026-03-08 12:50:44 -04:00
|
|
|
return RunResult(content=f"Claude temporarily unavailable: {exc}")
|
2026-02-28 09:35:44 -05:00
|
|
|
|
|
|
|
|
def print_response(self, message: str, *, stream: bool = True) -> None:
|
|
|
|
|
"""Run inference and render the response to stdout (CLI interface)."""
|
|
|
|
|
result = self.run(message, stream=stream)
|
|
|
|
|
try:
|
|
|
|
|
from rich.console import Console
|
|
|
|
|
from rich.markdown import Markdown
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-02-28 09:35:44 -05:00
|
|
|
Console().print(Markdown(result.content))
|
|
|
|
|
except ImportError:
|
|
|
|
|
print(result.content)
|
|
|
|
|
|
|
|
|
|
def health_check(self) -> dict:
|
|
|
|
|
"""Check Claude API connectivity."""
|
|
|
|
|
if not self._api_key:
|
|
|
|
|
return {
|
|
|
|
|
"ok": False,
|
|
|
|
|
"error": "ANTHROPIC_API_KEY not configured",
|
|
|
|
|
"backend": "claude",
|
|
|
|
|
"model": self._model,
|
|
|
|
|
}
|
|
|
|
|
try:
|
|
|
|
|
client = self._get_client()
|
|
|
|
|
# Lightweight ping — tiny completion
|
|
|
|
|
client.messages.create(
|
|
|
|
|
model=self._model,
|
|
|
|
|
max_tokens=4,
|
|
|
|
|
messages=[{"role": "user", "content": "ping"}],
|
|
|
|
|
)
|
|
|
|
|
return {"ok": True, "error": None, "backend": "claude", "model": self._model}
|
|
|
|
|
except Exception as exc:
|
2026-03-21 03:50:26 +00:00
|
|
|
logger.exception("Claude health check failed")
|
2026-02-28 09:35:44 -05:00
|
|
|
return {"ok": False, "error": str(exc), "backend": "claude", "model": self._model}
|
|
|
|
|
|
|
|
|
|
# ── Private helpers ───────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
def _build_messages(self, message: str) -> list[dict[str, str]]:
|
|
|
|
|
"""Build the messages array for the API call."""
|
|
|
|
|
messages = list(self._history[-10:])
|
|
|
|
|
messages.append({"role": "user", "content": message})
|
|
|
|
|
return messages
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ── Module-level Claude singleton ──────────────────────────────────────────
|
|
|
|
|
|
ruff (#169)
* polish: streamline nav, extract inline styles, improve tablet UX
- Restructure desktop nav from 8+ flat links + overflow dropdown into
5 grouped dropdowns (Core, Agents, Intel, System, More) matching
the mobile menu structure to reduce decision fatigue
- Extract all inline styles from mission_control.html and base.html
notification elements into mission-control.css with semantic classes
- Replace JS-built innerHTML with secure DOM construction in
notification loader and chat history
- Add CONNECTING state to connection indicator (amber) instead of
showing OFFLINE before WebSocket connects
- Add tablet breakpoint (1024px) with larger touch targets for
Apple Pencil / stylus use and safe-area padding for iPad toolbar
- Add active-link highlighting in desktop dropdown menus
- Rename "Mission Control" page title to "System Overview" to
disambiguate from the chat home page
- Add "Home — Timmy Time" page title to index.html
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* fix(security): move auth-gate credentials to environment variables
Hardcoded username, password, and HMAC secret in auth-gate.py replaced
with os.environ lookups. Startup now refuses to run if any variable is
unset. Added AUTH_GATE_SECRET/USER/PASS to .env.example.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
* refactor(tooling): migrate from black+isort+bandit to ruff
Replace three separate linting/formatting tools with a single ruff
invocation. Updates tox.ini (lint, format, pre-push, pre-commit envs),
.pre-commit-config.yaml, and CI workflow. Fixes all ruff errors
including unused imports, missing raise-from, and undefined names.
Ruff config maps existing bandit skips to equivalent S-rules.
https://claude.ai/code/session_015uPUoKyYa8M2UAcyk5Gt6h
---------
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-11 12:23:35 -04:00
|
|
|
_claude_backend: ClaudeBackend | None = None
|
2026-02-28 09:35:44 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_claude_backend() -> ClaudeBackend:
|
|
|
|
|
"""Get or create the Claude backend singleton."""
|
|
|
|
|
global _claude_backend
|
|
|
|
|
if _claude_backend is None:
|
|
|
|
|
_claude_backend = ClaudeBackend()
|
|
|
|
|
return _claude_backend
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def claude_available() -> bool:
|
|
|
|
|
"""Return True when Anthropic API key is configured."""
|
|
|
|
|
try:
|
|
|
|
|
from config import settings
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-02-28 09:35:44 -05:00
|
|
|
return bool(settings.anthropic_api_key)
|
2026-03-14 19:07:14 -04:00
|
|
|
except Exception as exc:
|
|
|
|
|
logger.warning("Backend check failed (claude_available): %s", exc)
|
2026-02-28 09:35:44 -05:00
|
|
|
return False
|