diff --git a/AGENTS.md b/AGENTS.md index 8adbea12..b2fad66b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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: diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 25d1d21d..7f61a6b1 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -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.", @@ -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?", @@ -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", @@ -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.", @@ -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", diff --git a/app/src/main/java/com/pulseloop/coach/anthropic/AnthropicClient.kt b/app/src/main/java/com/pulseloop/coach/anthropic/AnthropicClient.kt new file mode 100644 index 00000000..9e2c9963 --- /dev/null +++ b/app/src/main/java/com/pulseloop/coach/anthropic/AnthropicClient.kt @@ -0,0 +1,351 @@ +package com.pulseloop.coach.anthropic + +import com.pulseloop.coach.config.ClaudeModel +import com.pulseloop.coach.openai.FunctionCallOutput +import com.pulseloop.coach.openai.MessageOutput +import com.pulseloop.coach.openai.OpenAIResponse +import com.pulseloop.coach.openai.ResponseOutputItem +import com.pulseloop.coach.openai.ResponsesClient +import com.pulseloop.coach.openai.ResponsesError +import com.pulseloop.coach.openai.ResponsesHttp +import com.pulseloop.coach.openai.ResponsesToolSpecs +import com.pulseloop.coach.openai.TextContent +import kotlinx.serialization.json.* +import java.util.UUID + +/** + * Runs the coach on Claude through Anthropic's **Messages API** (`POST /v1/messages`), with the + * user's own key. Like the other adapters it takes the app's OpenAI Responses request and + * translates it, so the orchestrator, tools and confirm cards are unchanged. + * + * | Responses request | Messages request | + * |-------------------------------------|------------------------------------------------------| + * | `developer` / `system` items | top-level `system` (merged, in order) | + * | `input_text` / `input_image` parts | `text` / `image` blocks (data URLs become base64) | + * | `function` tools | `{name, description, input_schema}` | + * | `function_call_output` items | `tool_result` blocks in one user message | + * | `text.format` json_schema | `output_config.format`, schema made Claude-safe | + * | `reasoning.effort` | `output_config.effort` | + * + * Rules the API sets, each of which is a 400 if broken: + * - **No sampling parameters** (`temperature`, `top_p`, `top_k`) on API version 2026-10-21, and + * no prefill. Forced `tool_choice` is rejected by the 5.5 models, so it is never sent (`auto`). + * - **The assistant's content goes back unchanged**, thinking blocks included: the 5.5 models tie + * thinking to the conversation, and an edited one fails the next request. Each reply's whole + * `content` array is stored by response id and replayed before its tool results. + * - **Structured-output schemas** need `additionalProperties: false` on every object and take no + * numeric, length or array-size constraints ([claudeSafeSchema]). + * + * Not sent: hosted web search (Settings hides the switch for Claude, as for MiniMax), the server + * fallback beta. Prompt caching is on (top-level `cache_control`): a coach turn re-sends the same + * system prompt and tool list up to fifteen times in its tool loop. + * + * Stateful per turn, like `MiniMaxClient`; the orchestrator gets a fresh client per turn. + */ +class AnthropicClient( + private val apiKey: String, + private val model: String = ClaudeModel.DEFAULT.slug, + private val endpoint: String = "https://api.anthropic.com/v1/messages", + private val maxTokens: Int = DEFAULT_MAX_TOKENS, +) : ResponsesClient { + private val json = Json { ignoreUnknownKeys = true } + + private var system: String = "" + private var messages = mutableListOf() + /** Response id → the assistant message exactly as Claude returned it. */ + private val storedAssistant = mutableMapOf() + + override suspend fun send(requestBody: ByteArray): OpenAIResponse { + if (apiKey.isBlank()) throw ResponsesError.MissingAPIKey + val req = try { + json.parseToJsonElement(String(requestBody)).jsonObject + } catch (_: Exception) { + throw ResponsesError.Decoding("AnthropicClient: invalid request body") + } + val body = buildRequestBody(req) + val responseBody = ResponsesHttp.post( + endpoint, + json.encodeToString(JsonObject.serializer(), body).toByteArray(), + mapOf("x-api-key" to apiKey, "anthropic-version" to API_VERSION), + readTimeoutSeconds = READ_TIMEOUT_SECONDS, + ) + val root = try { + json.parseToJsonElement(responseBody).jsonObject + } catch (_: Exception) { + throw ResponsesError.Decoding("AnthropicClient: response was not a JSON object") + } + return ingestResponse(root) + } + + // ── Request (internal for unit tests) ──────────────────────────────── + + internal fun buildRequestBody(req: JsonObject): JsonObject { + val input = (req["input"] as? JsonArray)?.mapNotNull { it as? JsonObject } ?: emptyList() + val tools = (req["tools"] as? JsonArray)?.mapNotNull { it as? JsonObject } ?: emptyList() + val previousId = (req["previous_response_id"] as? JsonPrimitive)?.contentOrNull + + if (previousId == null) setupConversation(input) else appendContinuation(previousId, input) + + val body = mutableMapOf( + "model" to JsonPrimitive(model), + "max_tokens" to JsonPrimitive(maxTokens), + "messages" to JsonArray(merged(messages)), + "cache_control" to JsonObject(mapOf("type" to JsonPrimitive("ephemeral"))), + ) + if (system.isNotBlank()) body["system"] = JsonPrimitive(system) + val claudeTools = convertTools(tools) + if (claudeTools.isNotEmpty()) body["tools"] = JsonArray(claudeTools) + + val outputConfig = mutableMapOf() + effort(req)?.let { outputConfig["effort"] = JsonPrimitive(it) } + callerSchema(req)?.let { schema -> + outputConfig["format"] = JsonObject(mapOf( + "type" to JsonPrimitive("json_schema"), + "schema" to claudeSafeSchema(schema), + )) + } + if (outputConfig.isNotEmpty()) body["output_config"] = JsonObject(outputConfig) + return JsonObject(body) + } + + private fun setupConversation(input: List) { + messages = mutableListOf() + storedAssistant.clear() + val systemParts = mutableListOf() + for (item in input) { + val role = (item["role"] as? JsonPrimitive)?.contentOrNull ?: continue + if (role == "system" || role == "developer") { + textOf(item["content"]).takeIf { it.isNotBlank() }?.let { systemParts += it } + } else { + addMessage(role, item["content"]) + } + } + system = systemParts.joinToString("\n\n") + } + + /** Replays Claude's own reply for [previousId], then the tool results and any new message. */ + private fun appendContinuation(previousId: String, input: List) { + storedAssistant[previousId]?.let { messages.add(it) } + val results = mutableListOf() + for (item in input) { + val type = (item["type"] as? JsonPrimitive)?.contentOrNull + val callId = (item["call_id"] as? JsonPrimitive)?.contentOrNull + val output = (item["output"] as? JsonPrimitive)?.contentOrNull + if (type == "function_call_output" && callId != null) { + results += JsonObject(mapOf( + "type" to JsonPrimitive("tool_result"), + "tool_use_id" to JsonPrimitive(callId), + "content" to JsonPrimitive(output?.ifEmpty { "(empty)" } ?: "(empty)"), + )) + continue + } + val role = (item["role"] as? JsonPrimitive)?.contentOrNull ?: continue + if (results.isNotEmpty()) { messages.add(userBlocks(results.toList())); results.clear() } + if (role == "system" || role == "developer") { + // A mid-turn instruction rides as user text: editing `system` would reprocess the + // whole cached prefix and break the thinking the history carries. + addMessage("user", item["content"]) + } else addMessage(role, item["content"]) + } + if (results.isNotEmpty()) messages.add(userBlocks(results)) + } + + private fun userBlocks(blocks: List) = JsonObject(mapOf( + "role" to JsonPrimitive("user"), + "content" to JsonArray(blocks), + )) + + private fun addMessage(role: String, content: JsonElement?) { + val claudeRole = if (role == "assistant") "assistant" else "user" + val blocks = blocksOf(content) + if (blocks.isEmpty()) return + messages.add(JsonObject(mapOf( + "role" to JsonPrimitive(claudeRole), + "content" to JsonArray(blocks), + ))) + } + + /** Responses content (a string, or `input_text` / `input_image` parts) → Claude blocks. Empty + * text is dropped: the API rejects an empty text block. */ + private fun blocksOf(content: JsonElement?): List { + if (content is JsonPrimitive) { + val text = content.contentOrNull.orEmpty() + return if (text.isBlank()) emptyList() else listOf(textBlock(text)) + } + val parts = (content as? JsonArray)?.mapNotNull { it as? JsonObject } ?: return emptyList() + return parts.mapNotNull { part -> + when ((part["type"] as? JsonPrimitive)?.contentOrNull) { + "input_text", "output_text", "text" -> + (part["text"] as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() }?.let { textBlock(it) } + "input_image" -> (part["image_url"] as? JsonPrimitive)?.contentOrNull?.let { imageBlock(it) } + else -> null + } + } + } + + private fun textOf(content: JsonElement?): String = when (content) { + is JsonPrimitive -> content.contentOrNull.orEmpty() + is JsonArray -> content.mapNotNull { ((it as? JsonObject)?.get("text") as? JsonPrimitive)?.contentOrNull } + .joinToString("\n") + else -> "" + } + + private fun textBlock(text: String) = JsonObject(mapOf( + "type" to JsonPrimitive("text"), + "text" to JsonPrimitive(text), + )) + + /** A `data:image/jpeg;base64,…` URL becomes a base64 source; anything else is passed as a URL. */ + internal fun imageBlock(url: String): JsonObject { + val source = DATA_URL.matchEntire(url)?.let { m -> + JsonObject(mapOf( + "type" to JsonPrimitive("base64"), + "media_type" to JsonPrimitive(m.groupValues[1]), + "data" to JsonPrimitive(m.groupValues[2]), + )) + } ?: JsonObject(mapOf("type" to JsonPrimitive("url"), "url" to JsonPrimitive(url))) + return JsonObject(mapOf("type" to JsonPrimitive("image"), "source" to source)) + } + + /** Consecutive messages of one role become one: tool results and a repair prompt can both land + * in the user turn, and the API wants turns to alternate. */ + internal fun merged(list: List): List { + val out = mutableListOf() + // The conversation opens with the user; a history that starts on a coach check-in gets a + // one-line opener rather than a 400. + if (list.firstOrNull()?.get("role") == JsonPrimitive("assistant")) + out.add(userBlocks(listOf(textBlock("(Earlier in this conversation.)")))) + for (m in list) { + val last = out.lastOrNull() + if (last != null && last["role"] == m["role"]) { + val blocks = (last["content"] as JsonArray) + (m["content"] as JsonArray) + // Tool results must lead the user turn that answers them. + val (results, rest) = blocks.partition { (it as? JsonObject)?.get("type") == JsonPrimitive("tool_result") } + out[out.lastIndex] = JsonObject(mapOf("role" to m["role"]!!, "content" to JsonArray(results + rest))) + } else out.add(m) + } + return out + } + + private fun convertTools(tools: List): List = + // Hosted web search is dropped: Settings hides it for this provider. + ResponsesToolSpecs.parse(tools).functions.map { spec -> + val t = mutableMapOf("name" to JsonPrimitive(spec.name)) + spec.description?.let { t["description"] = JsonPrimitive(it) } + t["input_schema"] = spec.parameters ?: JsonObject(mapOf( + "type" to JsonPrimitive("object"), + "properties" to JsonObject(emptyMap()), + )) + JsonObject(t) + } + + private fun effort(req: JsonObject): String? = + ((req["reasoning"] as? JsonObject)?.get("effort") as? JsonPrimitive)?.contentOrNull + ?.takeIf { it in CLAUDE_EFFORTS } + + private fun callerSchema(req: JsonObject): JsonObject? { + val format = (req["text"] as? JsonObject)?.get("format") as? JsonObject ?: return null + if ((format["type"] as? JsonPrimitive)?.contentOrNull != "json_schema") return null + return format["schema"] as? JsonObject + } + + // ── Response (internal for unit tests) ─────────────────────────────── + + internal fun ingestResponse(root: JsonObject): OpenAIResponse { + if ((root["type"] as? JsonPrimitive)?.contentOrNull == "error") { + val msg = ((root["error"] as? JsonObject)?.get("message") as? JsonPrimitive)?.contentOrNull ?: "unknown error" + throw ResponsesError.Decoding("Claude error: $msg") + } + val stop = (root["stop_reason"] as? JsonPrimitive)?.contentOrNull + // A refusal can come with no content at all; check it before reading any block. + if (stop == "refusal") throw ResponsesError.Decoding(com.pulseloop.ui.i18n.tr(REFUSAL)) + + val content = (root["content"] as? JsonArray)?.mapNotNull { it as? JsonObject } ?: emptyList() + val responseId = (root["id"] as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotEmpty() } + ?: UUID.randomUUID().toString() + + val output = mutableListOf() + val text = content.filter { it["type"] == JsonPrimitive("text") } + .mapNotNull { (it["text"] as? JsonPrimitive)?.contentOrNull } + .joinToString("").trim() + if (text.isNotEmpty()) output += MessageOutput(role = "assistant", content = listOf(TextContent(text))) + for (block in content) { + if (block["type"] != JsonPrimitive("tool_use")) continue + val id = (block["id"] as? JsonPrimitive)?.contentOrNull ?: continue + val name = (block["name"] as? JsonPrimitive)?.contentOrNull ?: continue + val args = (block["input"] as? JsonObject)?.toString() ?: "{}" + output += FunctionCallOutput(id = id, callId = id, name = name, arguments = args) + } + if (output.isEmpty()) { + if (stop == "max_tokens") throw ResponsesError.Decoding("Claude's reply was cut off before it finished.") + throw ResponsesError.EmptyOutput + } + storedAssistant[responseId] = JsonObject(mapOf( + "role" to JsonPrimitive("assistant"), + "content" to JsonArray(content), + )) + return OpenAIResponse(id = responseId, output = output, usage = usage(root)) + } + + /** `input_tokens` excludes cached reads and writes, so the three are summed; the reads are the + * cached subset `CoachPricingCatalog` bills at the cache rate. */ + private fun usage(root: JsonObject): com.pulseloop.coach.usage.CoachTokenUsage? { + val u = root["usage"] as? JsonObject ?: return null + fun n(key: String) = (u[key] as? JsonPrimitive)?.intOrNull ?: 0 + val read = n("cache_read_input_tokens") + return com.pulseloop.coach.usage.CoachTokenUsage( + inputTokens = n("input_tokens") + read + n("cache_creation_input_tokens"), + outputTokens = n("output_tokens"), + cachedInputTokens = read, + ) + } + + companion object { + const val API_VERSION = "2026-10-21" + /** Room for adaptive thinking plus the reply, still under the ~16K non-streaming ceiling. */ + const val DEFAULT_MAX_TOKENS = 16000 + /** Opus thinks before it answers; 60 s, the shared default, cuts long turns off. */ + const val READ_TIMEOUT_SECONDS = 180 + const val REFUSAL = "Claude declined to answer this. Try asking it another way." + private val CLAUDE_EFFORTS = setOf("low", "medium", "high", "xhigh", "max") + private val DATA_URL = Regex("^data:([^;,]+);base64,(.*)$", RegexOption.DOT_MATCHES_ALL) + + private val UNSUPPORTED = setOf( + "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", + "minLength", "maxLength", "pattern", + "minItems", "maxItems", "uniqueItems", "minProperties", "maxProperties", + ) + private val FORMATS = setOf("date-time", "time", "date", "duration", "email", "hostname", "uri", "ipv4", "ipv6", "uuid") + + /** + * The schema with what Claude's structured outputs reject taken out: numeric, length and + * array-size constraints, unknown `format`s, and any `additionalProperties` other than + * `false` (which every object gets). `oneOf` becomes `anyOf`. Property *names* are never + * touched, so a field called `format` or `pattern` survives. The orchestrator still parses + * and repairs the reply, so a dropped constraint costs nothing it was relying on. + */ + fun claudeSafeSchema(schema: JsonObject): JsonObject { + val out = mutableMapOf() + for ((key, value) in schema) { + when (key) { + in UNSUPPORTED -> {} + "format" -> if ((value as? JsonPrimitive)?.contentOrNull in FORMATS) out[key] = value + "additionalProperties" -> {} + "properties", "\$defs", "definitions" -> + out[key] = JsonObject((value as? JsonObject)?.mapValues { (_, v) -> sub(v) } ?: emptyMap()) + "items", "not" -> out[key] = sub(value) + "anyOf", "allOf", "oneOf" -> + out[if (key == "oneOf") "anyOf" else key] = JsonArray((value as? JsonArray)?.map { sub(it) } ?: emptyList()) + else -> out[key] = value + } + } + val type = schema["type"] + val isObject = "properties" in schema || type == JsonPrimitive("object") || + (type as? JsonArray)?.contains(JsonPrimitive("object")) == true + if (isObject) out["additionalProperties"] = JsonPrimitive(false) + return JsonObject(out) + } + + private fun sub(value: JsonElement): JsonElement = (value as? JsonObject)?.let { claudeSafeSchema(it) } ?: value + } +} diff --git a/app/src/main/java/com/pulseloop/coach/config/CoachClientResolver.kt b/app/src/main/java/com/pulseloop/coach/config/CoachClientResolver.kt index bcdd609d..5fcde424 100644 --- a/app/src/main/java/com/pulseloop/coach/config/CoachClientResolver.kt +++ b/app/src/main/java/com/pulseloop/coach/config/CoachClientResolver.kt @@ -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 @@ -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, @@ -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 @@ -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, @@ -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 diff --git a/app/src/main/java/com/pulseloop/coach/config/CoachModelCatalog.kt b/app/src/main/java/com/pulseloop/coach/config/CoachModelCatalog.kt index 1de3d9ee..e8860700 100644 --- a/app/src/main/java/com/pulseloop/coach/config/CoachModelCatalog.kt +++ b/app/src/main/java/com/pulseloop/coach/config/CoachModelCatalog.kt @@ -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 @@ -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.") @@ -165,6 +170,13 @@ object CoachModelCatalog { internal fun parseIds(body: String): List = 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 = + 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 { @@ -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 } diff --git a/app/src/main/java/com/pulseloop/coach/config/CoachModelPresets.kt b/app/src/main/java/com/pulseloop/coach/config/CoachModelPresets.kt index 9140761e..0fc02d1b 100644 --- a/app/src/main/java/com/pulseloop/coach/config/CoachModelPresets.kt +++ b/app/src/main/java/com/pulseloop/coach/config/CoachModelPresets.kt @@ -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) { + 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 diff --git a/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettings.kt b/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettings.kt index 88704bd6..59c90dda 100644 --- a/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettings.kt +++ b/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettings.kt @@ -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`. */ @@ -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, @@ -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() diff --git a/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettingsStore.kt b/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettingsStore.kt index d02dbc25..00a42fd3 100644 --- a/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettingsStore.kt +++ b/app/src/main/java/com/pulseloop/coach/config/CoachProviderSettingsStore.kt @@ -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 @@ -142,6 +153,7 @@ class CoachProviderSettingsStore(context: Context) { geminiModel = geminiModel, openRouterModel = openRouterModel, minimaxModel = minimaxModel, + anthropicModel = anthropicModel, orPrivacyRouting = orPrivacyRouting, orProviderSort = orProviderSort, reasoningEffort = reasoningEffort, @@ -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" diff --git a/app/src/main/java/com/pulseloop/coach/config/ReasoningEfforts.kt b/app/src/main/java/com/pulseloop/coach/config/ReasoningEfforts.kt index 7e574ba0..dede25dc 100644 --- a/app/src/main/java/com/pulseloop/coach/config/ReasoningEfforts.kt +++ b/app/src/main/java/com/pulseloop/coach/config/ReasoningEfforts.kt @@ -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. diff --git a/app/src/main/java/com/pulseloop/coach/usage/CoachModelPricing.kt b/app/src/main/java/com/pulseloop/coach/usage/CoachModelPricing.kt index 9044578b..35afec08 100644 --- a/app/src/main/java/com/pulseloop/coach/usage/CoachModelPricing.kt +++ b/app/src/main/java/com/pulseloop/coach/usage/CoachModelPricing.kt @@ -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), diff --git a/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt b/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt index e38ee794..5307d7aa 100644 --- a/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt +++ b/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt @@ -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", diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt index 1a0b58fa..47b43be3 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt @@ -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") } diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index f2093303..66376a3a 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -287,6 +287,9 @@ fun CoachSettingsScreen(onBack: () -> Unit) { var orKeyVisible by remember { mutableStateOf(false) } var minimaxKey by remember { mutableStateOf(providerStore.minimaxApiKey) } var minimaxKeyVisible by remember { mutableStateOf(false) } + var anthropicKey by remember { mutableStateOf(providerStore.anthropicApiKey) } + var anthropicKeyVisible by remember { mutableStateOf(false) } + var anthropicModel by remember { mutableStateOf(providerStore.anthropicModel) } var geminiModel by remember { mutableStateOf(providerStore.geminiModel) } var orModel by remember { mutableStateOf(providerStore.openRouterModel) } var minimaxModel by remember { mutableStateOf(providerStore.minimaxModel) } @@ -317,6 +320,7 @@ fun CoachSettingsScreen(onBack: () -> Unit) { val providerOptions = listOf( CoachProviderMode.USER_OPENAI_KEY to "OpenAI", + CoachProviderMode.USER_ANTHROPIC_KEY to "Claude (Anthropic)", CoachProviderMode.USER_GEMINI_KEY to "Google Gemini", CoachProviderMode.USER_OPENROUTER_KEY to "OpenRouter (100+ models)", CoachProviderMode.USER_MINIMAX_KEY to "MiniMax", @@ -495,6 +499,28 @@ fun CoachSettingsScreen(onBack: () -> Unit) { onRemove = { minimaxKey = ""; providerStore.minimaxApiKey = ""; keySaves++ }, ) } + CoachProviderMode.USER_ANTHROPIC_KEY -> { + CoachModelPicker( + provider = providerMode, providerName = tr("Claude"), selected = anthropicModel, + presets = com.pulseloop.coach.config.ClaudeModel.entries.map { it.slug to tr(it.blurb) }, + savedKey = keySaves.let { providerStore.anthropicApiKey }, + onPick = { anthropicModel = it; providerStore.anthropicModel = it }, + onListing = { liveListing = it }, + ) + KeyField( + label = tr("Claude API Key"), value = anthropicKey, visible = anthropicKeyVisible, + saved = providerStore.hasAnthropicKey, + onValue = { anthropicKey = it }, onVisibility = { anthropicKeyVisible = !anthropicKeyVisible }, + onSave = { providerStore.anthropicApiKey = anthropicKey; keySaves++ }, + onRemove = { anthropicKey = ""; providerStore.anthropicApiKey = ""; keySaves++ }, + ) + Text( + tr("Create a key at console.anthropic.com. Usage is billed to your Anthropic account."), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 4.dp), + ) + } CoachProviderMode.LOCAL_OPENAI_COMPAT -> { // Any OpenAI-Chat-Completions-compatible server the user runs: Ollama, // llama.cpp, vLLM, SGLang, LM Studio. No key required — see @@ -756,11 +782,12 @@ fun CoachSettingsScreen(onBack: () -> Unit) { val effortProvider = if (providerMode in setOf( CoachProviderMode.USER_GEMINI_KEY, CoachProviderMode.USER_OPENROUTER_KEY, CoachProviderMode.USER_MINIMAX_KEY, CoachProviderMode.LOCAL_OPENAI_COMPAT, - CoachProviderMode.ON_DEVICE, + CoachProviderMode.ON_DEVICE, CoachProviderMode.USER_ANTHROPIC_KEY, )) providerMode else CoachProviderMode.USER_OPENAI_KEY val effortModel = when (effortProvider) { CoachProviderMode.USER_GEMINI_KEY -> geminiModel CoachProviderMode.USER_OPENROUTER_KEY -> orModel + CoachProviderMode.USER_ANTHROPIC_KEY -> anthropicModel CoachProviderMode.USER_OPENAI_KEY -> selectedModel else -> "" } @@ -791,11 +818,12 @@ fun CoachSettingsScreen(onBack: () -> Unit) { HorizontalDivider() - // Tool toggles. Neither MiniMax's compat endpoint nor any self-hosted engine - // has a hosted web search, so hide the toggle for both (each client drops the + // Tool toggles. Neither MiniMax's compat endpoint, any self-hosted engine nor the Claude client + // sends a hosted web search, so hide the toggle for them (each client drops the // tool anyway — this is the UI half). if (toolsApply && providerMode != CoachProviderMode.USER_MINIMAX_KEY && - providerMode != CoachProviderMode.LOCAL_OPENAI_COMPAT) { + providerMode != CoachProviderMode.LOCAL_OPENAI_COMPAT && + providerMode != CoachProviderMode.USER_ANTHROPIC_KEY) { Row(Modifier.fillMaxWidth() .switchRow(checked = webSearch, onCheckedChange = { webSearch = it; keyStore.webSearchEnabled = it diff --git a/app/src/test/java/com/pulseloop/coach/AnthropicClientTest.kt b/app/src/test/java/com/pulseloop/coach/AnthropicClientTest.kt new file mode 100644 index 00000000..eee267b1 --- /dev/null +++ b/app/src/test/java/com/pulseloop/coach/AnthropicClientTest.kt @@ -0,0 +1,241 @@ +package com.pulseloop.coach.anthropic + +import com.pulseloop.coach.config.CoachClientResolver +import com.pulseloop.coach.config.CoachProviderMode +import com.pulseloop.coach.config.CoachProviderSettings +import com.pulseloop.coach.config.ReasoningEfforts +import com.pulseloop.coach.openai.FunctionCallOutput +import com.pulseloop.coach.openai.MessageOutput +import com.pulseloop.coach.openai.ResponsesError +import com.pulseloop.coach.openai.TextContent +import com.pulseloop.coach.orchestration.CoachResponseSchema +import com.pulseloop.coach.usage.CoachPricingCatalog +import com.pulseloop.coach.usage.CoachTokenUsage +import kotlinx.serialization.json.* +import org.junit.Assert.* +import org.junit.Test + +/** Responses request → Messages request and back, with no network. */ +class AnthropicClientTest { + + private fun msg(role: String, content: JsonElement) = JsonObject(mapOf( + "role" to JsonPrimitive(role), "content" to content, + )) + private fun msg(role: String, content: String) = msg(role, JsonPrimitive(content)) + + private fun request( + input: List, + tools: List = emptyList(), + schema: JsonObject? = null, + previous: String? = null, + effort: String? = null, + ) = JsonObject(buildMap { + put("model", JsonPrimitive("claude-opus-5-5")) + put("input", JsonArray(input)) + put("tools", JsonArray(tools)) + schema?.let { put("text", JsonObject(mapOf("format" to JsonObject(mapOf( + "type" to JsonPrimitive("json_schema"), "name" to JsonPrimitive("x"), + "strict" to JsonPrimitive(true), "schema" to it, + ))))) } + previous?.let { put("previous_response_id", JsonPrimitive(it)) } + effort?.let { put("reasoning", JsonObject(mapOf("effort" to JsonPrimitive(it)))) } + }) + + private val tool = JsonObject(mapOf( + "type" to JsonPrimitive("function"), + "name" to JsonPrimitive("get_hr"), + "description" to JsonPrimitive("Heart rate"), + "parameters" to JsonObject(mapOf("type" to JsonPrimitive("object"), "properties" to JsonObject(emptyMap()))), + "strict" to JsonPrimitive(true), + )) + + private fun reply(vararg blocks: JsonObject, id: String = "msg_1", stop: String = "end_turn") = JsonObject(mapOf( + "id" to JsonPrimitive(id), + "type" to JsonPrimitive("message"), + "role" to JsonPrimitive("assistant"), + "content" to JsonArray(blocks.toList()), + "stop_reason" to JsonPrimitive(stop), + "usage" to JsonObject(mapOf( + "input_tokens" to JsonPrimitive(100), + "cache_read_input_tokens" to JsonPrimitive(900), + "cache_creation_input_tokens" to JsonPrimitive(0), + "output_tokens" to JsonPrimitive(50), + )), + )) + + private fun text(t: String) = JsonObject(mapOf("type" to JsonPrimitive("text"), "text" to JsonPrimitive(t))) + private val thinking = JsonObject(mapOf( + "type" to JsonPrimitive("thinking"), "thinking" to JsonPrimitive(""), "signature" to JsonPrimitive("sig"), + )) + private fun toolUse(id: String) = JsonObject(mapOf( + "type" to JsonPrimitive("tool_use"), "id" to JsonPrimitive(id), "name" to JsonPrimitive("get_hr"), + "input" to JsonObject(mapOf("days" to JsonPrimitive(7))), + )) + + private fun JsonObject.messages() = this["messages"]!!.jsonArray.map { it.jsonObject } + + @Test + fun systemItemsBecomeTopLevelSystemAndNoSamplingParams() { + val body = AnthropicClient("k").buildRequestBody(request(listOf( + msg("developer", "Be a coach."), msg("system", "Context."), msg("user", "Hi"), + ))) + assertEquals("Be a coach.\n\nContext.", body["system"]!!.jsonPrimitive.content) + val messages = body.messages() + assertEquals(1, messages.size) + assertEquals("user", messages[0]["role"]!!.jsonPrimitive.content) + assertEquals(16000, body["max_tokens"]!!.jsonPrimitive.int) + for (k in listOf("temperature", "top_p", "top_k", "tool_choice", "thinking")) assertFalse(k, k in body) + assertTrue("cache_control" in body) + } + + @Test + fun toolsTranslateWithoutStrictAndWebSearchIsDropped() { + val webSearch = JsonObject(mapOf("type" to JsonPrimitive("web_search"))) + val body = AnthropicClient("k").buildRequestBody(request(listOf(msg("user", "Hi")), listOf(tool, webSearch))) + val tools = body["tools"]!!.jsonArray.map { it.jsonObject } + assertEquals(1, tools.size) + assertEquals("get_hr", tools[0]["name"]!!.jsonPrimitive.content) + assertEquals("object", tools[0]["input_schema"]!!.jsonObject["type"]!!.jsonPrimitive.content) + assertFalse("strict" in tools[0]) + } + + @Test + fun effortAndSchemaGoInOutputConfig() { + val schema = JsonObject(mapOf( + "type" to JsonPrimitive("object"), + "properties" to JsonObject(mapOf("a" to JsonObject(mapOf("type" to JsonPrimitive("string"))))), + )) + val body = AnthropicClient("k").buildRequestBody(request(listOf(msg("user", "Hi")), schema = schema, effort = "high")) + val config = body["output_config"]!!.jsonObject + assertEquals("high", config["effort"]!!.jsonPrimitive.content) + assertEquals("json_schema", config["format"]!!.jsonObject["type"]!!.jsonPrimitive.content) + assertEquals(JsonPrimitive(false), config["format"]!!.jsonObject["schema"]!!.jsonObject["additionalProperties"]) + } + + @Test + fun anEffortClaudeDoesNotTakeIsDropped() { + val body = AnthropicClient("k").buildRequestBody(request(listOf(msg("user", "Hi")), effort = "none")) + assertFalse("output_config" in body) + } + + @Test + fun schemaLosesUnsupportedKeywordsButKeepsPropertyNames() { + val schema = Json.parseToJsonElement(""" + {"type":"object","additionalProperties":true,"properties":{ + "format":{"type":"string","maxLength":40,"format":"date"}, + "pattern":{"type":"integer","minimum":0,"maximum":10}, + "list":{"type":"array","minItems":1,"maxItems":3,"items":{"type":"object","properties":{"x":{"type":"number","multipleOf":1}}}}, + "pick":{"oneOf":[{"type":"string","pattern":"^a"},{"type":"null"}]}, + "odd":{"type":"string","format":"phone"} + },"required":["format"]} + """).jsonObject + val safe = AnthropicClient.claudeSafeSchema(schema).toString() + for (k in listOf("maxLength", "minimum", "maximum", "minItems", "maxItems", "multipleOf", "\"pattern\":\"", "oneOf", "phone")) + assertFalse(k, k in safe) + val props = AnthropicClient.claudeSafeSchema(schema)["properties"]!!.jsonObject + assertEquals(setOf("format", "pattern", "list", "pick", "odd"), props.keys) + assertEquals("date", props["format"]!!.jsonObject["format"]!!.jsonPrimitive.content) + assertEquals(JsonPrimitive(false), props["list"]!!.jsonObject["items"]!!.jsonObject["additionalProperties"]) + assertTrue("anyOf" in props["pick"]!!.jsonObject) + assertTrue("required" in AnthropicClient.claudeSafeSchema(schema)) + } + + @Test + fun theCoachResponseSchemaComesOutClaudeSafe() { + val safe = AnthropicClient.claudeSafeSchema(CoachResponseSchema.schema).toString() + for (k in listOf("\"maxLength\"", "\"minLength\"", "\"minimum\"", "\"maximum\"", "\"minItems\"", "\"maxItems\"", "\"additionalProperties\":true")) + assertFalse(k, k in safe) + } + + @Test + fun imagesBecomeBase64Blocks() { + val parts = JsonArray(listOf( + JsonObject(mapOf("type" to JsonPrimitive("input_text"), "text" to JsonPrimitive("What is this?"))), + JsonObject(mapOf("type" to JsonPrimitive("input_image"), "image_url" to JsonPrimitive("data:image/jpeg;base64,QUJD"))), + )) + val body = AnthropicClient("k").buildRequestBody(request(listOf(msg("user", parts)))) + val blocks = body.messages()[0]["content"]!!.jsonArray.map { it.jsonObject } + assertEquals("text", blocks[0]["type"]!!.jsonPrimitive.content) + val source = blocks[1]["source"]!!.jsonObject + assertEquals("base64", source["type"]!!.jsonPrimitive.content) + assertEquals("image/jpeg", source["media_type"]!!.jsonPrimitive.content) + assertEquals("QUJD", source["data"]!!.jsonPrimitive.content) + } + + @Test + fun historyStartingOnTheCoachGetsAUserOpenerAndEmptyTextIsDropped() { + val body = AnthropicClient("k").buildRequestBody(request(listOf( + msg("assistant", "Good morning!"), msg("user", ""), msg("user", "Hi"), + ))) + val messages = body.messages() + assertEquals(listOf("user", "assistant", "user"), messages.map { it["role"]!!.jsonPrimitive.content }) + } + + @Test + fun toolLoopReplaysClaudesContentUnchangedThenResults() { + val client = AnthropicClient("k") + client.buildRequestBody(request(listOf(msg("user", "How did I sleep?")), listOf(tool))) + val first = client.ingestResponse(reply(thinking, text("Let me check."), toolUse("toolu_1"), stop = "tool_use")) + val call = first.output.filterIsInstance().single() + assertEquals("toolu_1", call.callId) + assertEquals("""{"days":7}""", call.arguments) + + val output = JsonObject(mapOf( + "type" to JsonPrimitive("function_call_output"), + "call_id" to JsonPrimitive("toolu_1"), + "output" to JsonPrimitive("""{"hr":60}"""), + )) + val body = client.buildRequestBody(request(listOf(output), listOf(tool), previous = first.id)) + val messages = body.messages() + assertEquals(3, messages.size) + // The assistant turn goes back exactly as it came, thinking block and all. + assertEquals(JsonArray(listOf(thinking, text("Let me check."), toolUse("toolu_1"))), messages[1]["content"]) + val result = messages[2]["content"]!!.jsonArray[0].jsonObject + assertEquals("tool_result", result["type"]!!.jsonPrimitive.content) + assertEquals("toolu_1", result["tool_use_id"]!!.jsonPrimitive.content) + } + + @Test + fun aRepairPromptJoinsTheUserTurnAfterToolResults() { + val client = AnthropicClient("k") + client.buildRequestBody(request(listOf(msg("user", "Hi")))) + val first = client.ingestResponse(reply(text("not json"))) + val body = client.buildRequestBody(request(listOf(msg("user", "Return JSON.")), previous = first.id)) + assertEquals(listOf("user", "assistant", "user"), body.messages().map { it["role"]!!.jsonPrimitive.content }) + } + + @Test + fun textAndUsageAreRead() { + val res = AnthropicClient("k").ingestResponse(reply(thinking, text("{\"a\":"), text("1}"))) + val msg = res.output.single() as MessageOutput + assertEquals("{\"a\":1}", (msg.content.single() as TextContent).text) + assertEquals(CoachTokenUsage(inputTokens = 1000, outputTokens = 50, cachedInputTokens = 900), res.usage) + } + + @Test + fun refusalAndCutOffAreErrors() { + val refusal = JsonObject(mapOf("id" to JsonPrimitive("m"), "content" to JsonArray(emptyList()), "stop_reason" to JsonPrimitive("refusal"))) + val e = assertThrows(ResponsesError.Decoding::class.java) { AnthropicClient("k").ingestResponse(refusal) } + assertTrue(e.msg.contains("Claude")) + assertThrows(ResponsesError.Decoding::class.java) { + AnthropicClient("k").ingestResponse(reply(thinking, stop = "max_tokens")) + } + } + + @Test + fun resolverPicksClaudeWithItsKey() { + val s = CoachProviderSettings(providerMode = CoachProviderMode.USER_ANTHROPIC_KEY) + val res = CoachClientResolver.resolve(s, openAIKey = "sk", geminiKey = null, openRouterKey = null, anthropicKey = "sk-ant") + assertEquals("sk-ant", res.key) + assertTrue(res.client is AnthropicClient) + assertNull(CoachClientResolver.resolve(s, openAIKey = "sk", geminiKey = null, openRouterKey = null, anthropicKey = " ").key) + assertEquals("claude-opus-5-5", CoachClientResolver.activeModel(s, "gpt-6.1-sol")) + } + + @Test + fun claudeModelsHaveEffortsAndPrices() { + assertEquals(5, ReasoningEfforts.options(CoachProviderMode.USER_ANTHROPIC_KEY, "claude-sonnet-5-5").size) + val usage = CoachTokenUsage(inputTokens = 1_000_000, outputTokens = 0) + assertEquals(4.0, CoachPricingCatalog.cost("claude-opus-5-5", usage)!!, 1e-9) + } +} diff --git a/audits/2026-11-04-claude-coach-provider.md b/audits/2026-11-04-claude-coach-provider.md new file mode 100644 index 00000000..f8d2035d --- /dev/null +++ b/audits/2026-11-04-claude-coach-provider.md @@ -0,0 +1,91 @@ +# Audit: Claude as the coach (v2.13.0) + +Date: 2026-11-04 · PR: see the PR that adds this file · Auditor: Claude. The four skills were +applied by reading the code; there is no device or emulator in this session, so there are no +screenshots. + +## Scope + +- **New provider:** Settings › AI Coach › Provider › **Claude (Anthropic)**, with the user's own + key. It runs on Anthropic's Messages API (`coach/anthropic/AnthropicClient.kt`). +- **Its section** follows the same pattern as Gemini and MiniMax: + - a model picker (Opus 5.5 is the default, plus Sonnet 5.5 and Haiku 5.5, and the live list + from `/v1/models`); + - the shared key field; + - one line on where to get a key and who bills for it. +- **Reasoning effort** lists Low to Max for Claude. **Web search** is hidden for Claude, as it is + for MiniMax and Local, because the client doesn't send it. +- **No new screen and no new tokens.** + +## ux-user-flows (§13 flow review checklist) + +```mermaid +flowchart TD + A[Settings › AI Coach] --> P{Provider} + P -->|Claude| M[Model: Opus 5.5 default] + M --> K[Paste key → Save Key → Saved ✓] + K --> L[Model list loads from the key] + K --> C[Coach chat uses Claude from the next message] + C -->|bad key| E[401 shown as a coach error with its reason] + C -->|refusal| R["Claude declined… try asking another way"] +``` + +| # | Question | Result | +|---|---|---| +| 1 | Job | Use my own Claude key for the coach. Pass | +| 2 | Entries | Only the provider menu, where the other providers already are. Pass | +| 3 | Happy path | Pick Claude, paste the key, save: three actions, the same as every keyed provider. Pass | +| 4 | Branches | Default model, a preset, or one from the live list. Pass | +| 5 | States | No key, key saved (Update/Remove), list loading, list failed (falls back to the presets), retired model flagged. Pass | +| 6 | Errors | A bad key gives an HTTP 401 with its reason in the coach error. A refusal or a cut-off reply each has its own plain message. Pass | +| 7 | Control | Remove the key, switch provider; changes apply from the next message. Pass | +| 8 | Progress and resume | Not applicable | +| 9 | Memory | The key and model ride in the backup with the other providers' keys, at the owner's request; the Backup screen already warns about this. Pass | +| 10 | Exits | Back, or another provider. Pass | +| 11 | Conventions | The shared `KeyField`, `CoachModelPicker`, `PulseButton` and helper text. Pass | +| 12 | Speed | One round trip per tool step; prompt caching on; a 180 s read timeout because Opus thinks first. Pass | +| 13 | Accessibility | Unchanged components: the key field's show/hide has a label, and targets are 52dp. Pass | +| 14 | Ethics | The helper line says usage is billed to the user's Anthropic account. Health data goes to Anthropic only after the user picks it and saves a key, as with every cloud provider. Pass | +| 15 | Evidence | Unit tests on the translation (`AnthropicClientTest`); CI. Pass | + +No issues. + +## impeccable (native audit) + +| Dimension | Score | Note | +|---|---|---| +| Accessibility | 4 | Existing labelled components only | +| Performance | 4 | Prompt caching; the request runs on IO through `ResponsesHttp` | +| Appearance & theming | 4 | No new colour or size; the helper text is `bodySmall` on `onSurfaceVariant`, like its siblings | +| Platform conformance | 4 | Password-type field with the IME Done action, as before | +| Adaptivity | 4 | One column; the pt-BR strings wrap | +| **Total** | **20/20** | | + +Findings: none at P0–P2. **P3:** web search could be offered later through Claude's own server +tool, once its pairing with structured output is checked on a real key. + +## graphic-design-fundamentals (§13) + +| Item | Result | +|---|---| +| Brief, concept, hierarchy | Pass: provider, then model, then key, the same order as the other providers | +| Contrast, colour | Pass: no new colour; mint stays on Save Key | +| Alignment, spacing, typography | Pass: 4/8dp spacing, the type scale | +| Consistency, simplicity | Pass | +| Real size, accessibility | Pass (by reading) | +| Production | Pass: every new `tr()` key has a pt-BR entry (script-checked) | + +## less-is-more + +| Element | Question | Kept / cut | +|---|---|---| +| "Claude (Anthropic)" in the menu | 1 | Kept | +| Three presets with one-line blurbs | 1 | Kept: the picker needs something to show before a key exists | +| "Create a key at console.anthropic.com…" | 1 (consent: who pays) | Kept, one line | +| Web search switch | 2 (it would do nothing) | Hidden for Claude | + +No other screen changed, and taps on common actions did not go up. + +## Verdict + +Merge. There are no P0 or P1 findings.