Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1117,6 +1117,23 @@ and each one fails silently if broken:

It is exclusive with a paired ring: a `DeviceIdentified` turns it off.

## Claude as the coach: the Messages API, translated

**Read this before touching `coach/anthropic/`.** `AnthropicClient` runs the coach on Claude with
the user's own key, translating the app's Responses-shaped request the way the other adapters do.
Each rule below is a 400 on every turn if broken:

- **No sampling parameters, no prefill, no forced `tool_choice`** (API version `2026-10-21`, and
the 5.5 models reject forced tool use). Effort goes in `output_config.effort`.
- **Claude's reply goes back unchanged**, thinking blocks included: the 5.5 models tie thinking to
the conversation. The client stores each reply's whole `content` and replays it before its tool
results; don't rebuild it from the parsed text.
- **Structured-output schemas go through `claudeSafeSchema`**: `additionalProperties: false` on
every object, no numeric, length or array-size constraints. A caller's own schema (meal estimate,
lab report, summary) is sent the same way.
- Web search isn't sent, and Settings hides its switch for Claude. Its key and model ride in the
backup with the other providers' keys (`ArchivedSettings.SECURE_KEYS`).

## MCP on your network: read-only, paired, private addresses only

**Read this before touching `mcp/` or `ui/screens/McpSettingsUi.kt`.** Threat model:
Expand Down
7 changes: 7 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@
"Backup & data": "Backup e dados",
"Backups include your AI coach setup and its API keys, readable by anyone with the file. Keep backup files private.": "Os backups incluem a configuração do coach de IA e as chaves de API, legíveis por quem tiver o arquivo. Guarde os arquivos de backup em local privado.",
"Balance Macros (30/40/30)": "Equilibrar macros (30/40/30)",
"Balanced, half the price": "Equilibrado, metade do preço",
"Banana": "Banana",
"Barcode": "Código de barras",
"Barcode scanning needs a working device camera. Enter the food manually instead.": "A leitura de código de barras precisa de uma câmera funcionando. Insira o alimento manualmente.",
Expand Down Expand Up @@ -369,8 +370,11 @@
"Choose metrics": "Escolher métricas",
"Chopp": "Chopp",
"Cider / other": "Sidra / outros",
"Claude": "Claude",
"Claude API Key": "Chave de API do Claude",
"Claude Desktop on my laptop": "Claude Desktop no meu notebook",
"Claude Desktop or Cursor": "Claude Desktop ou Cursor",
"Claude declined to answer this. Try asking it another way.": "O Claude não quis responder a isso. Tente perguntar de outro jeito.",
"Clear": "Limpar",
"Clear Demo Data": "Apagar dados de demonstração",
"Clear Demo Data?": "Apagar dados de demonstração?",
Expand Down Expand Up @@ -456,6 +460,7 @@
"Couldn't scan for rings. Try again.": "Não foi possível procurar anéis. Tente de novo.",
"Couldn't update this record": "Não foi possível atualizar este registro",
"Court sessions": "Sessões em quadra",
"Create a key at console.anthropic.com. Usage is billed to your Anthropic account.": "Crie uma chave em console.anthropic.com. O uso é cobrado na sua conta da Anthropic.",
"Critical": "Crítico",
"Current offset: %+.0f mg/dL": "Ajuste atual: %+.0f mg/dL",
"Cuscuz com ovo": "Cuscuz com ovo",
Expand Down Expand Up @@ -676,6 +681,7 @@
"Factory reset ring?": "Restaurar anel de fábrica?",
"Fair": "Razoável",
"Fallback schedule (used when no Bedtime/DND mode was active):": "Horário alternativo (usado quando nenhum modo Hora de dormir/Não perturbe estava ativo):",
"Fastest and cheapest": "O mais rápido e barato",
"Fasting 100–125 is above the typical range.": "Em jejum, 100–125 está acima da faixa típica.",
"Fasting normal is up to 99 mg/dL.": "Em jejum, o normal é até 99 mg/dL.",
"Fasting ≥126. Talk to a clinician if confirmed by a meter.": "Em jejum ≥126. Fale com um profissional de saúde se for confirmado por um medidor.",
Expand Down Expand Up @@ -1062,6 +1068,7 @@
"More drinks": "Mais bebidas",
"Morning": "Manhã",
"Morning type": "Matutino",
"Most capable (default)": "O mais capaz (padrão)",
"Move every hour": "Mexa-se a cada hora",
"Move outdoors to start tracking your route.": "Vá para um lugar aberto para começar a gravar o trajeto.",
"Move reminder": "Lembrete para se mexer",
Expand Down
351 changes: 351 additions & 0 deletions app/src/main/java/com/pulseloop/coach/anthropic/AnthropicClient.kt

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.pulseloop.coach.config

import com.pulseloop.coach.anthropic.AnthropicClient
import com.pulseloop.coach.gemini.GeminiClient
import com.pulseloop.coach.local.LocalEndpoint
import com.pulseloop.coach.local.LocalOpenAICompatClient
Expand Down Expand Up @@ -42,6 +43,7 @@ object CoachClientResolver {
openRouterKey: String?,
minimaxKey: String? = null,
localKey: String? = null,
anthropicKey: String? = null,
openAIClientFactory: (String) -> ResponsesClient = { OpenAIResponsesClient(it) },
/** On-device only: whether the model file is on the phone. Passed in so this stays pure-JVM. */
onDeviceReady: Boolean = false,
Expand All @@ -64,6 +66,10 @@ object CoachClientResolver {
val key = minimaxKey?.takeIf { it.isNotBlank() }
Resolution(key, MiniMaxClient(apiKey = key ?: "", model = settings.resolvedMinimaxModel))
}
CoachProviderMode.USER_ANTHROPIC_KEY -> {
val key = anthropicKey?.takeIf { it.isNotBlank() }
Resolution(key, AnthropicClient(apiKey = key ?: "", model = settings.resolvedAnthropicModel))
}
CoachProviderMode.LOCAL_OPENAI_COMPAT -> {
// Readiness is a base URL that would actually work — `validate`, not `isNotBlank`.
// Settings persists the field on every keystroke, so a blank-check flips the coach to
Expand Down Expand Up @@ -118,6 +124,7 @@ object CoachClientResolver {
openRouterKey = store.openRouterApiKey,
minimaxKey = store.minimaxApiKey,
localKey = store.localApiKey,
anthropicKey = store.anthropicApiKey,
openAIClientFactory = openAIClientFactory,
onDeviceReady = onDevice?.isReady() == true,
onDeviceEngine = onDevice ?: NoOnDeviceEngine,
Expand Down Expand Up @@ -169,6 +176,7 @@ object CoachClientResolver {
CoachProviderMode.USER_GEMINI_KEY -> settings.geminiModel
CoachProviderMode.USER_OPENROUTER_KEY -> settings.resolvedOpenRouterModel
CoachProviderMode.USER_MINIMAX_KEY -> settings.resolvedMinimaxModel
CoachProviderMode.USER_ANTHROPIC_KEY -> settings.resolvedAnthropicModel
// Reported verbatim for attribution — including blank, which is a valid llama.cpp
// setup. `CoachPricingCatalog` prices this provider at $0 regardless of the string.
CoachProviderMode.LOCAL_OPENAI_COMPAT -> settings.resolvedLocalModel
Expand Down
13 changes: 13 additions & 0 deletions app/src/main/java/com/pulseloop/coach/config/CoachModelCatalog.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import kotlinx.serialization.json.*
* | Gemini | `GET …/v1beta/models` (paged) | display name, `generateContent` only |
* | OpenRouter | `GET openrouter.ai/api/v1/models` | name, reasoning levels, expiry date |
* | MiniMax | `GET api.minimax.io/v1/models` | ids only |
* | Claude | `GET api.anthropic.com/v1/models` | display name |
*
* OpenRouter is the only one that says which reasoning levels a model accepts
* (`reasoning.supported_efforts`) or when it is being retired (`expiration_date`); for the others
Expand Down Expand Up @@ -86,6 +87,10 @@ object CoachModelCatalog {
CoachProviderMode.USER_OPENAI_KEY -> parseOpenAI(get(url, mapOf("Authorization" to "Bearer $apiKey")))
CoachProviderMode.USER_OPENROUTER_KEY -> parseOpenRouter(get(url, mapOf("Authorization" to "Bearer $apiKey")))
CoachProviderMode.USER_MINIMAX_KEY -> parseIds(get(url, mapOf("Authorization" to "Bearer $apiKey")))
CoachProviderMode.USER_ANTHROPIC_KEY -> parseAnthropic(get("$url?limit=1000", mapOf(
"x-api-key" to apiKey,
"anthropic-version" to com.pulseloop.coach.anthropic.AnthropicClient.API_VERSION,
)))
else -> emptyList()
}
if (entries.isEmpty()) return Result.Failure("The provider listed no usable models.")
Expand Down Expand Up @@ -165,6 +170,13 @@ object CoachModelCatalog {
internal fun parseIds(body: String): List<Entry> =
dataArray(body).mapNotNull { (it as? JsonObject)?.string("id") }.distinct().sorted().map { Entry(it) }

/** Anthropic's `{"data":[{"id","display_name"}]}`; only `claude-` ids, newest listed first. */
internal fun parseAnthropic(body: String): List<Entry> =
dataArray(body).mapNotNull { it as? JsonObject }.mapNotNull { m ->
val id = m.string("id")?.takeIf { it.startsWith("claude-") } ?: return@mapNotNull null
Entry(id, name = m.string("display_name"))
}.distinctBy { it.id }

// ── Internals ────────────────────────────────────────────────────────

private suspend fun fetchGemini(url: String, apiKey: String): List<Entry> {
Expand Down Expand Up @@ -205,6 +217,7 @@ object CoachModelCatalog {
CoachProviderMode.USER_OPENROUTER_KEY to "https://openrouter.ai/api/v1/models",
// Global host, as MiniMaxClient uses.
CoachProviderMode.USER_MINIMAX_KEY to "https://api.minimax.io/v1/models",
CoachProviderMode.USER_ANTHROPIC_KEY to "https://api.anthropic.com/v1/models",
)

private val JSON = Json { ignoreUnknownKeys = true }
Expand Down
15 changes: 15 additions & 0 deletions app/src/main/java/com/pulseloop/coach/config/CoachModelPresets.kt
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,21 @@ enum class MiniMaxModel(val slug: String, val blurb: String) {
}
}

/**
* Claude models for the coach on the user's own Anthropic key. All three take effort `low`
* through `max` in `output_config.effort` and think adaptively; the live `/v1/models` list in
* [CoachModelCatalog] adds any newer one.
*/
enum class ClaudeModel(val slug: String, val blurb: String, val reasoningEfforts: List<ReasoningEffort>) {
OPUS("claude-opus-5-5", "Most capable (default)", ReasoningEffort.LOW_TO_MAX),
SONNET("claude-sonnet-5-5", "Balanced, half the price", ReasoningEffort.LOW_TO_MAX),
HAIKU("claude-haiku-5-5", "Fastest and cheapest", ReasoningEffort.LOW_TO_MAX);

companion object {
val DEFAULT = OPUS
}
}

/**
* Ported from [CoachModel] in CoachSettings.swift.
* Preset OpenAI model choices. The stored model (`ApiKeyStore.model`) is a free
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ enum class CoachProviderMode(val rawValue: String, val label: String) {
USER_GEMINI_KEY("userGeminiKey", "Gemini (your key)"),
USER_OPENROUTER_KEY("userOpenRouterKey", "OpenRouter (your key)"),
USER_MINIMAX_KEY("userMiniMaxKey", "MiniMax (your key)"),
/** Claude through Anthropic's Messages API, with the user's own key (`AnthropicClient`). */
USER_ANTHROPIC_KEY("userAnthropicKey", "Claude (your key)"),
/** Any OpenAI-Chat-Completions-compatible server the user runs themselves — Ollama,
* llama.cpp, vLLM, SGLang, LM Studio. The API key is optional here; the readiness sentinel
* is the base URL. See `docs/local-llm-coach.md`. */
Expand Down Expand Up @@ -45,6 +47,8 @@ data class CoachProviderSettings(
val openRouterModel: String = OpenRouterModel.DEFAULT.slug,
/** MiniMax model slug (see [MiniMaxModel] presets). */
val minimaxModel: String = MiniMaxModel.DEFAULT.slug,
/** Claude model id (see [ClaudeModel] presets). */
val anthropicModel: String = ClaudeModel.DEFAULT.slug,
/** OpenRouter-only: route only through providers that don't log/train on
* prompts (sends `provider.data_collection = "deny"`). */
val orPrivacyRouting: Boolean = false,
Expand Down Expand Up @@ -82,6 +86,10 @@ data class CoachProviderSettings(
val resolvedMinimaxModel: String
get() = minimaxModel.trim().ifEmpty { MiniMaxModel.DEFAULT.slug }

/** The Claude model id to use; the default preset when the stored one is blank. */
val resolvedAnthropicModel: String
get() = anthropicModel.trim().ifEmpty { ClaudeModel.DEFAULT.slug }

/** The local base URL with surrounding whitespace gone; blank when unconfigured. There's no
* default to fall back to — every engine listens on a different port. */
val resolvedLocalBaseUrl: String get() = localBaseUrl.trim()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ class CoachProviderSettingsStore(context: Context) {

val hasMinimaxKey: Boolean get() = minimaxApiKey.isNotBlank()

var anthropicApiKey: String
get() = prefs.getString(KEY_ANTHROPIC_API_KEY, "") ?: ""
set(value) { prefs.edit().putString(KEY_ANTHROPIC_API_KEY, value.trim()).apply() }

val hasAnthropicKey: Boolean get() = anthropicApiKey.isNotBlank()

/** Claude model id (see [ClaudeModel] presets, or one from the live list). */
var anthropicModel: String
get() = prefs.getString(KEY_ANTHROPIC_MODEL, ClaudeModel.DEFAULT.slug) ?: ClaudeModel.DEFAULT.slug
set(value) { prefs.edit().putString(KEY_ANTHROPIC_MODEL, value).apply() }

/** Gemini model slug (see [GeminiModel] presets). Retired 2.x slugs are remapped to the
* current rolling alias on read so no one stays stuck on a deprecated model (issue #22). */
var geminiModel: String
Expand Down Expand Up @@ -142,6 +153,7 @@ class CoachProviderSettingsStore(context: Context) {
geminiModel = geminiModel,
openRouterModel = openRouterModel,
minimaxModel = minimaxModel,
anthropicModel = anthropicModel,
orPrivacyRouting = orPrivacyRouting,
orProviderSort = orProviderSort,
reasoningEffort = reasoningEffort,
Expand All @@ -159,6 +171,9 @@ class CoachProviderSettingsStore(context: Context) {
private const val KEY_GEMINI_API_KEY = "gemini_api_key"
private const val KEY_OPENROUTER_API_KEY = "openrouter_api_key"
private const val KEY_MINIMAX_API_KEY = "minimax_api_key"
// Both ride in the backup (ArchivedSettings.SECURE_KEYS), like every provider's key.
private const val KEY_ANTHROPIC_API_KEY = "anthropic_api_key"
private const val KEY_ANTHROPIC_MODEL = "anthropic_model"
private const val KEY_GEMINI_MODEL = "gemini_model"
private const val KEY_OPENROUTER_MODEL = "openrouter_model"
private const val KEY_MINIMAX_MODEL = "minimax_model"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ object ReasoningEfforts {
OpenRouterModel.entries.firstOrNull { it.slug == slug }?.reasoningEfforts ?: live?.reasoningEfforts
CoachProviderMode.USER_GEMINI_KEY ->
GeminiModel.entries.firstOrNull { it.slug == slug }?.reasoningEfforts ?: geminiLevels(slug)
CoachProviderMode.USER_ANTHROPIC_KEY ->
ClaudeModel.entries.firstOrNull { it.slug == slug }?.reasoningEfforts ?: live?.reasoningEfforts
// Neither client sends a `reasoning` field (MiniMax reasons inline; see the local
// client's header), so there is nothing to choose.
// The on-device model has no effort setting either.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ object CoachPricingCatalog {
"gemini-4-argon" to CoachModelPrice(2.00, 0.10, 10.00),
"gemini-2.5-flash" to CoachModelPrice(0.30, 0.03, 2.50),
"gemini-2.5-pro" to CoachModelPrice(1.25, 0.125, 10.00), // <=200k-token tier; >200k bills 2x
// Claude (native, Anthropic's own ids). Cached = cache-read rate.
"claude-opus-5-5" to CoachModelPrice(4.00, 0.20, 20.00),
"claude-sonnet-5-5" to CoachModelPrice(2.00, 0.20, 10.00),
"claude-haiku-5-5" to CoachModelPrice(0.10, 0.01, 0.50), // <=100k-token tier
"claude-fable-5-1" to CoachModelPrice(10.00, 0.25, 50.00),
// OpenRouter (vendor/model slugs). List prices match the vendors';
// cached rates use the vendor cache-read price.
"anthropic/claude-sonnet-5.5" to CoachModelPrice(2.00, 0.10, 10.00),
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/java/com/pulseloop/data/ArchivedSettings.kt
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ object ArchivedSettings {
// AI coach: switches, provider, keys, models, the custom API.
"coach_enabled", "coach_model", "openai_api_key", "coach_provider_mode",
"gemini_api_key", "gemini_model", "openrouter_api_key", "openrouter_model",
"minimax_api_key", "minimax_model", "openrouter_privacy_routing", "openrouter_provider_sort",
"minimax_api_key", "minimax_model", "anthropic_api_key", "anthropic_model",
"openrouter_privacy_routing", "openrouter_provider_sort",
"coach_reasoning_effort", "coach_image_input_enabled", "web_search_enabled",
"write_tools_enabled", "environment_context_enabled",
"local_llm_base_url", "local_llm_api_key", "local_llm_model", "local_llm_tool_calling",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ fun SettingsScreen(
CoachProviderMode.USER_GEMINI_KEY -> providerStore.geminiModel
CoachProviderMode.USER_OPENROUTER_KEY -> providerStore.openRouterModel
CoachProviderMode.USER_MINIMAX_KEY -> providerStore.minimaxModel
CoachProviderMode.USER_ANTHROPIC_KEY -> providerStore.anthropicModel
// Local: the model name, or just "Local" for a server (llama.cpp) that ignores the field.
CoachProviderMode.LOCAL_OPENAI_COMPAT ->
providerStore.localModel.ifBlank { tr("Local") }
Expand Down
Loading
Loading