From f0f7f7a116f6e359e7ec1fd7f233fad056b4c2ee Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:43:55 -0500 Subject: [PATCH] feat(agent): permission modes for every harness, asking first by default (#2854) * fix(agent): show the side menu's agent page whenever the tab is shown * feat(agent): permission modes for every harness, asking first by default * test(agent): give the drawer page tests their agent page explicitly * fix(agent): fail turns on lost stdin writes, wait for Codex to initialize, keep approvals visible * fix(agent): redo setup on a kept process after it failed, keep approvals in view * fix(agent): keep full-page panels closed while an approval waits --- .../droiddeck/launcher/agent/AgentHarness.kt | 709 +++++++++++++----- .../com/droiddeck/launcher/agent/AgentHost.kt | 115 ++- .../droiddeck/launcher/agent/AgentNotice.kt | 11 +- .../com/droiddeck/launcher/ui/AgentPage.kt | 59 +- .../com/droiddeck/launcher/ui/AgentPanels.kt | 16 +- .../droiddeck/launcher/ui/AgentSetupView.kt | 4 +- .../launcher/ui/SessionDrawerPage.kt | 2 +- app/src/main/res/values/strings.xml | 16 + .../droiddeck/launcher/agent/AgentHostTest.kt | 163 ++-- .../droiddeck/launcher/agent/OpenCodeTest.kt | 170 +++-- .../launcher/ui/SessionDrawerPageTest.kt | 10 +- 11 files changed, 967 insertions(+), 308 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt index 1db8009699..9ae46f143c 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt @@ -1,11 +1,13 @@ package com.droiddeck.launcher.agent +import androidx.annotation.StringRes import androidx.annotation.VisibleForTesting +import com.droiddeck.launcher.R import org.json.JSONArray import org.json.JSONObject import java.io.File -/** One coding agent CLI in the Linux userland, run one process per turn (or kept open, see [input]). */ +/** One coding agent CLI in the Linux userland, run as a process that takes its turns over stdin (see [AgentProtocol]). */ interface AgentHarness { val id: String val name: String @@ -35,22 +37,20 @@ interface AgentHarness { /** Whether the CLI has models that need no account; [useFree] then counts as signed in. */ val free: Boolean get() = false fun useFree(rootfs: File) {} + /** Usage reports the conversation's whole cost rather than the turn's. */ + val sessionCost: Boolean get() = false /** Whether [Options.plan] means anything to this CLI. */ val plans: Boolean /** Reasoning effort levels the CLI accepts, lowest first; empty when it has none. */ val efforts: List /** Models to offer besides the CLI's default; [rootfs] is where the CLI's own files can be read. */ fun models(rootfs: File): List - /** The guest command for one turn; [conversation] is null for the first one. */ + /** How the CLI may run its tools, the one that asks before each action first and the default. */ + val permissions: List + /** The guest command of the process that runs the conversation's turns; [conversation] is null for a new one. */ fun turn(message: String, conversation: String?, options: Options): List - /** - * The line that hands [message] to a [turn] process over stdin, or null when the message is already in the - * command. A process that takes its messages this way stays open between turns, so work it started in the - * background can wake it, as it does in the CLI's own terminal. - */ - fun input(message: String): String? = null - /** One line of the CLI's output, or null when it carries nothing to show. */ - fun parse(line: String): AgentEvent? + /** A new reader for one [turn] process; it keeps what that process has said so far. */ + fun protocol(): AgentProtocol /** The folder, under the userland's root, where the CLI loads user skills (`/SKILL.md`). */ val skills: String /** The CLI's global instructions file under the userland's root, where DroidDeck keeps its rules in a marked block. */ @@ -65,14 +65,42 @@ interface AgentHarness { /** An API reached with a key; [keyPage] is where the key is made, and a [custom] one is any OpenAI-compatible server. */ data class Provider(val id: String, val name: String, val keyPage: String? = null, val custom: Boolean = false) - data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null) + /** A permission mode; [id] is DroidDeck's own name for it, which each CLI maps to its flags. */ + data class Permission(val id: String, @StringRes val label: Int, @StringRes val hint: Int) + + data class Options( + val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null, + val permission: String = ASK, val workdir: String = "/root", + ) companion object { + const val ASK = "ask" + const val EDITS = "edits" + const val AUTO = "auto" + const val DONT_ASK = "dontask" + const val FULL = "full" + val all: List = listOf(ClaudeCode, Codex, OpenCode) fun byId(id: String?): AgentHarness = all.firstOrNull { it.id == id } ?: ClaudeCode } } +/** What goes to one CLI process's stdin, and what its output lines mean. */ +interface AgentProtocol { + /** + * The lines that start a turn of [message]; [started] is true for a process that has just been started. The + * process stays open between turns, so work it started in the background can wake it. + */ + fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List + /** One line of the process's output, or null when it carries nothing to show. */ + fun parse(line: String): AgentEvent? + /** The line that answers [approval]. */ + fun answer(approval: AgentHost.Approval, allow: Boolean): String +} + +/** The message a CLI tells its model when the user denies a tool call. */ +internal const val DENIED = "The user denied this tool call." + /** What one line of output carries: whole entries, or text still being written. */ data class AgentEvent( val conversation: String? = null, @@ -89,6 +117,12 @@ data class AgentEvent( val background: Boolean = false, /** The error a background turn ended with, if it failed. */ val backgroundError: String? = null, + /** Lines to write to the process's stdin right away, the next step of a request it has answered. */ + val reply: List = emptyList(), + /** A tool call that waits for the user to allow it. */ + val approval: AgentHost.Approval? = null, + /** The id of an approval the CLI no longer waits for. */ + val resolved: String? = null, ) /** Claude Code: `claude -p` with stream-json input and output, resumed by session id. */ @@ -130,22 +164,54 @@ object ClaudeCode : AgentHarness { AgentHarness.Model("opus", "Opus"), AgentHarness.Model("sonnet", "Sonnet"), AgentHarness.Model("haiku", "Haiku"), ) - // DroidDeck runs the agent unattended on the user's own device; permission prompts have no one to answer them. + override val permissions = listOf( + AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint), + AgentHarness.Permission(AgentHarness.EDITS, R.string.agent_permission_edits, R.string.agent_permission_edits_hint), + AgentHarness.Permission(AgentHarness.AUTO, R.string.agent_permission_auto, R.string.agent_permission_auto_hint), + AgentHarness.Permission(AgentHarness.DONT_ASK, R.string.agent_permission_dont_ask, R.string.agent_permission_dont_ask_hint), + AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint), + ) + + private val MODES = mapOf( + AgentHarness.ASK to "manual", AgentHarness.EDITS to "acceptEdits", AgentHarness.AUTO to "auto", + AgentHarness.DONT_ASK to "dontAsk", AgentHarness.FULL to "bypassPermissions", + ) + + /** + * Prompts reach DroidDeck as can_use_tool requests on stdout (the SDK's stdio prompt tool). Plan mode keeps + * answering none, so a turn that would leave plan mode ends on its plan. + */ override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList { addAll(listOf(binary, "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages")) - addAll(listOf("--permission-mode", if (options.plan) "plan" else "bypassPermissions")) + val mode = if (options.plan) "plan" else MODES[options.permission] ?: "manual" + addAll(listOf("--permission-mode", mode)) + if (mode != "plan" && mode != "bypassPermissions") add("--permission-prompt-tool=stdio") options.model?.let { addAll(listOf("--model", it)) } options.effort?.let { addAll(listOf("--effort", it)) } options.brief?.let { addAll(listOf("--append-system-prompt", it)) } if (conversation != null) addAll(listOf("--resume", conversation)) } - override fun input(message: String): String? = JSONObject() + fun input(message: String): String = JSONObject() .put("type", "user") .put("message", JSONObject().put("role", "user").put("content", JSONArray().put(JSONObject().put("type", "text").put("text", message)))) .toString() - override fun parse(line: String): AgentEvent? { + override fun protocol(): AgentProtocol = object : AgentProtocol { + override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean) = listOf(this@ClaudeCode.input(message)) + override fun parse(line: String) = this@ClaudeCode.parse(line) + override fun answer(approval: AgentHost.Approval, allow: Boolean) = this@ClaudeCode.answer(approval, allow) + } + + @VisibleForTesting + internal fun answer(approval: AgentHost.Approval, allow: Boolean): String { + val decision = if (allow) JSONObject().put("behavior", "allow").put("updatedInput", runCatching { JSONObject(approval.payload) }.getOrDefault(JSONObject())) + else JSONObject().put("behavior", "deny").put("message", DENIED) + return JSONObject().put("type", "control_response") + .put("response", JSONObject().put("subtype", "success").put("request_id", approval.id).put("response", decision)).toString() + } + + fun parse(line: String): AgentEvent? { val o = runCatching { JSONObject(line) }.getOrNull() ?: return null val conversation = o.optString("session_id").takeIf { it.isNotEmpty() } // A subagent's messages carry the call that started it; only its tool calls are shown, under that call. @@ -192,6 +258,13 @@ object ClaudeCode : AgentHarness { AgentEvent(conversation, results) } "rate_limit_event" -> AgentEvent(conversation, limits = limits(o.optJSONObject("rate_limit_info"))) + "control_request" -> { + val request = o.optJSONObject("request")?.takeIf { it.optString("subtype") == "can_use_tool" } ?: return null + val tool = request.optString("tool_name") + val input = request.optJSONObject("input") ?: JSONObject() + AgentEvent(approval = AgentHost.Approval(o.optString("request_id"), tool, detail(input), fullInput(tool, input), input.toString())) + } + "control_cancel_request" -> AgentEvent(resolved = o.optString("request_id")) // The CLI starts turns of its own for background tasks (a resumed session first answers the ones the last // run left behind). Such a result is not the end of the user's turn; the host decides what it ends. "result" -> { @@ -274,7 +347,7 @@ object ClaudeCode : AgentHarness { }.joinToString("\n") } -/** OpenAI Codex: `codex exec --json`, resumed by thread id. */ +/** OpenAI Codex: `codex app-server`, its JSON-RPC protocol over stdio, resumed by thread id. */ object Codex : AgentHarness { override val id = "codex" override val name = "Codex" @@ -300,6 +373,13 @@ object Codex : AgentHarness { override val plans = false override val efforts = listOf("low", "medium", "high") + // Codex's sandbox needs Landlock and seccomp, which proot does not provide, so commands run unsandboxed + // and "untrusted" is what makes Codex ask before each one that is not known to be safe. + override val permissions = listOf( + AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint), + AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint), + ) + /** Codex keeps the models its account can use in `~/.codex/models_cache.json` once it has run. */ override fun models(rootfs: File): List = runCatching { val o = JSONObject(File(rootfs, "root/.codex/models_cache.json").readText()) @@ -312,106 +392,230 @@ object Codex : AgentHarness { } }.getOrDefault(emptyList()) - // Codex's own sandbox needs Landlock and seccomp, which proot does not provide. - override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList { - addAll(listOf(binary, "exec")) - if (conversation != null) addAll(listOf("resume", conversation)) - addAll(listOf("--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check")) - options.model?.let { addAll(listOf("-m", it)) } - options.effort?.let { addAll(listOf("-c", "model_reasoning_effort=\"$it\"")) } - // codex exec has no system prompt option, so a new conversation starts with the brief. - add(if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message) - } + override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = withoutStderr("codex", listOf(binary, "app-server")) - override fun parse(line: String): AgentEvent? { - val o = runCatching { JSONObject(line) }.getOrNull() ?: return null - val item = o.optJSONObject("item") - val id = item?.optString("id").orEmpty() - val entries = when (o.optString("type")) { - "thread.started" -> return AgentEvent(o.optString("thread_id").takeIf { it.isNotEmpty() }) - "item.started" -> when (item?.optString("type")) { - "command_execution" -> shellCommand(item.optString("command")).let { listOf(AgentHost.Entry.Used(id, "Shell", firstLine(it), it)) } - "mcp_tool_call" -> listOf(AgentHost.Entry.Used(id, item.optString("tool").ifEmpty { "Tool" }, item.optString("server"), item.optJSONObject("arguments")?.toString(2).orEmpty())) - "web_search" -> listOf(AgentHost.Entry.Used(id, "Search", item.optString("query"), item.optString("query"))) - else -> emptyList() - } - "item.updated" -> when (item?.optString("type")) { - "todo_list" -> listOf(todoEntry(id, item)) - else -> emptyList() - } - "item.completed" -> when (item?.optString("type")) { - "agent_message" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Said(it)) }.orEmpty() - "reasoning" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Thought(it)) }.orEmpty() - "command_execution" -> listOf(AgentHost.Entry.Result(id, item.optString("aggregated_output"), - item.has("exit_code") && !item.isNull("exit_code") && item.optInt("exit_code") != 0)) - "mcp_tool_call" -> listOf(AgentHost.Entry.Result(id, item.optJSONObject("result")?.toString(2) ?: item.optJSONObject("error")?.optString("message").orEmpty(), - item.optString("status") == "failed")) - "web_search" -> listOf(AgentHost.Entry.Result(id, "", false)) - "file_change" -> listOf( - AgentHost.Entry.Used(id, "Edit", changedFiles(item), changedFiles(item).replace(", ", "\n")), - AgentHost.Entry.Result(id, item.optString("status"), item.optString("status") == "failed"), - ) - "todo_list" -> listOf(todoEntry(id, item)) - "error" -> listOf(AgentHost.Entry.Said("⚠ " + item.optString("message"))) - else -> emptyList() - } - "turn.completed" -> return AgentEvent( - entries = listOf(AgentHost.Entry.Finished(null)), - usage = o.optJSONObject("usage")?.let { AgentHost.Usage(0, 0.0, it.optLong("input_tokens") + it.optLong("cached_input_tokens"), it.optLong("output_tokens")) }, + override fun protocol(): AgentProtocol = Protocol() + + @VisibleForTesting + internal class Protocol : AgentProtocol { + private var next = 1 + private var thread: String? = null + /** The initialize request, the thread/start or thread/resume sent once it succeeds, and the turn that waits for its thread. */ + private var initializing = -1 + private var initialized = false + private var open: String? = null + private var opening = -1 + private var waiting: JSONObject? = null + private var starting = -1 + private var turnId = "" + /** Each file change's paths and diffs, from its start; an approval for it names only the item. */ + private val changes = mutableMapOf() + private var input = 0L + private var output = 0L + + override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List { + val turn = JSONObject() + .put("input", JSONArray().put(JSONObject().put("type", "text").put("text", message).put("text_elements", JSONArray()))) + options.model?.let { turn.put("model", it) } + options.effort?.let { turn.put("effort", it) } + val known = thread + if (!started && known != null) return listOf(startTurn(turn.put("threadId", known))) + val params = JSONObject() + .put("approvalPolicy", if (options.permission == AgentHarness.FULL) "never" else "untrusted") + .put("sandbox", "danger-full-access") + options.model?.let { params.put("model", it) } + options.brief?.let { params.put("developerInstructions", it) } + if (conversation != null) params.put("threadId", conversation) + waiting = turn + opening = next++ + val request = JSONObject().put("id", opening).put("method", if (conversation != null) "thread/resume" else "thread/start").put("params", params).toString() + // Codex refuses a second initialize on one connection, so a thread that failed to open is asked for again alone. + if (initialized) return listOf(request) + open = request + initializing = next++ + return listOf( + JSONObject().put("id", initializing).put("method", "initialize") + .put("params", JSONObject().put("clientInfo", JSONObject().put("name", "droiddeck").put("title", "DroidDeck").put("version", "1")) + .put("capabilities", JSONObject.NULL)).toString(), ) - "turn.failed" -> listOf(AgentHost.Entry.Finished(o.optJSONObject("error")?.optString("message") ?: "turn failed")) - // codex reports a dropped stream it is retrying as an error event, and the turn goes on. - "error" -> o.optString("message").let { message -> - if (message.startsWith("Reconnecting...")) emptyList() else listOf(AgentHost.Entry.Finished(message.ifEmpty { "error" })) - } - else -> emptyList() } - return if (entries.isEmpty()) null else AgentEvent(entries = entries) + + private fun startTurn(params: JSONObject): String { + starting = next++ + return JSONObject().put("id", starting).put("method", "turn/start").put("params", params).toString() + } + + override fun answer(approval: AgentHost.Approval, allow: Boolean): String = + JSONObject(approval.payload).put("result", JSONObject().put("decision", if (allow) "accept" else "decline")).toString() + + override fun parse(line: String): AgentEvent? { + val o = runCatching { JSONObject(line) }.getOrNull() ?: return null + val method = o.optString("method") + if (method.isEmpty()) return response(o) + val params = o.optJSONObject("params") ?: JSONObject() + if (o.has("id")) return request(o.get("id"), method, params) + return notification(method, params) + } + + private fun response(o: JSONObject): AgentEvent? { + val id = o.optInt("id", -1) + val error = o.optJSONObject("error")?.optString("message")?.ifEmpty { "error" } + return when (id) { + initializing -> { + if (error != null) return AgentEvent(entries = listOf(AgentHost.Entry.Finished(error))) + initialized = true + val request = open ?: return null + open = null + AgentEvent(reply = listOf(JSONObject().put("method", "initialized").toString(), request)) + } + opening -> { + if (error != null) return AgentEvent(entries = listOf(AgentHost.Entry.Finished(error))) + val started = o.optJSONObject("result")?.optJSONObject("thread")?.optString("id")?.takeIf { it.isNotEmpty() } ?: return null + thread = started + val turn = waiting ?: return AgentEvent(started) + waiting = null + AgentEvent(started, reply = listOf(startTurn(turn.put("threadId", started)))) + } + starting -> error?.let { AgentEvent(entries = listOf(AgentHost.Entry.Finished(it))) } + else -> null + } + } + + private fun request(id: Any, method: String, params: JSONObject): AgentEvent { + val payload = JSONObject().put("id", id).toString() + return when (method) { + "item/commandExecution/requestApproval" -> { + val command = shellCommand(params.optString("command")) + val reason = params.optString("reason").takeIf { it.isNotEmpty() && it != "null" } + AgentEvent(approval = AgentHost.Approval(id.toString(), "Shell", firstLine(command), listOfNotNull(command, reason).joinToString("\n\n"), payload)) + } + "item/fileChange/requestApproval" -> { + val list = changes[params.optString("itemId")] ?: JSONArray() + val files = (0 until list.length()).mapNotNull { list.optJSONObject(it) } + AgentEvent(approval = AgentHost.Approval( + id.toString(), "Edit", files.joinToString(", ") { it.optString("path") }.take(400), + files.joinToString("\n\n") { it.optString("path") + "\n" + patchLines(it.optString("diff"), it.optJSONObject("kind")?.optString("type").orEmpty()) }, payload, + )) + } + // Everything else asks for something DroidDeck has no screen for; refusing keeps the turn going. + else -> AgentEvent(reply = listOf(JSONObject(payload) + .put("error", JSONObject().put("code", -32601).put("message", "DroidDeck cannot answer $method")).toString())) + } + } + + private fun notification(method: String, params: JSONObject): AgentEvent? { + val item = params.optJSONObject("item") + val id = item?.optString("id").orEmpty() + val entries: List = when (method) { + "thread/started" -> return params.optJSONObject("thread")?.optString("id")?.takeIf { it.isNotEmpty() }?.let { AgentEvent(it) } + "turn/started" -> { + turnId = params.optJSONObject("turn")?.optString("id").orEmpty() + input = 0 + output = 0 + return null + } + "item/agentMessage/delta" -> return AgentEvent(text = params.optString("delta")) + "item/reasoning/summaryTextDelta", "item/reasoning/textDelta" -> return AgentEvent(thinking = params.optString("delta")) + "item/started" -> when (item?.optString("type")) { + "commandExecution" -> shellCommand(item.optString("command")).let { listOf(AgentHost.Entry.Used(id, "Shell", firstLine(it), it)) } + "mcpToolCall" -> listOf(AgentHost.Entry.Used(id, item.optString("tool").ifEmpty { "Tool" }, item.optString("server"), item.opt("arguments")?.let(::pretty).orEmpty())) + "webSearch" -> listOf(AgentHost.Entry.Used(id, "Search", item.optString("query"), item.optString("query"))) + "fileChange" -> { + val list = item.optJSONArray("changes") ?: JSONArray() + changes[id] = list + fileEntries(id, list) + } + else -> emptyList() + } + "item/completed" -> when (item?.optString("type")) { + "agentMessage" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Said(it)) }.orEmpty() + "reasoning" -> { + val parts = (strings(item.optJSONArray("summary")) + strings(item.optJSONArray("content"))).joinToString("\n\n").trim() + if (parts.isEmpty()) emptyList() else listOf(AgentHost.Entry.Thought(parts)) + } + "commandExecution" -> { + val status = item.optString("status") + val exit = if (item.isNull("exitCode")) 0 else item.optInt("exitCode") + val out = item.optString("aggregatedOutput").takeUnless { item.isNull("aggregatedOutput") }.orEmpty() + listOf(AgentHost.Entry.Result(id, if (status == "declined") out.ifEmpty { DENIED } else out, status != "completed" || exit != 0)) + } + "mcpToolCall" -> listOf(AgentHost.Entry.Result(id, + item.optJSONObject("result")?.let(::pretty) ?: item.optJSONObject("error")?.optString("message").orEmpty(), item.optString("status") == "failed")) + "webSearch" -> listOf(AgentHost.Entry.Result(id, "", false)) + "fileChange" -> { + val list = item.optJSONArray("changes") ?: changes[id] ?: JSONArray() + changes.remove(id) + val failed = item.optString("status") != "completed" + (0 until list.length()).map { AgentHost.Entry.Result("$id#$it", if (failed) item.optString("status") else "", failed) } + } + else -> emptyList() + } + "turn/plan/updated" -> listOf(plan(params.optJSONArray("plan"))) + "thread/tokenUsage/updated" -> { + val usage = params.optJSONObject("tokenUsage") ?: return null + val last = usage.optJSONObject("last") + input += last?.optLong("inputTokens") ?: 0 + output += last?.optLong("outputTokens") ?: 0 + return AgentEvent( + context = last?.optLong("totalTokens")?.takeIf { it > 0 }, + window = usage.optLong("modelContextWindow").takeIf { it > 0 }, + ) + } + "account/rateLimits/updated" -> return rateLimits(params.optJSONObject("rateLimits"))?.let { AgentEvent(limits = it) } + "serverRequest/resolved" -> return AgentEvent(resolved = params.opt("requestId")?.toString()) + "turn/completed" -> { + val turn = params.optJSONObject("turn") ?: JSONObject() + val error = when (turn.optString("status")) { + "failed" -> turn.optJSONObject("error")?.optString("message")?.ifEmpty { null } ?: "turn failed" + else -> null + } + return AgentEvent( + entries = listOf(AgentHost.Entry.Finished(error)), + usage = AgentHost.Usage(if (turn.isNull("durationMs")) 0 else turn.optLong("durationMs"), 0.0, input, output), + ) + } + else -> emptyList() + } + return if (entries.isEmpty()) null else AgentEvent(entries = entries) + } + + private fun plan(steps: JSONArray?): AgentHost.Entry.Used { + val text = (0 until (steps?.length() ?: 0)).mapNotNull { i -> + val step = steps?.optJSONObject(i) ?: return@mapNotNull null + val mark = when (step.optString("status")) { "completed" -> "[x]"; "inProgress" -> "[~]"; else -> "[ ]" } + "$mark ${step.optString("step")}" + }.joinToString("\n") + return AgentHost.Entry.Used("$turnId-todo", "TodoWrite", "", text, output = "") + } } - private const val TOKEN_COUNT = "\"payload\":{\"type\":\"token_count\"" - - /** Codex prints no limits with --json; its session log, named after the thread, has a token_count event each step. */ - override fun usage(rootfs: File, conversation: String?): AgentEvent? { - conversation ?: return null - val log = File(rootfs, "root/.codex/sessions").walkBottomUp().filter { it.isFile && it.name.endsWith("-$conversation.jsonl") } - .maxByOrNull { it.lastModified() } ?: return null - val last = runCatching { log.readLines().lastOrNull { it.contains(TOKEN_COUNT) } }.getOrNull() ?: return null - return tokenCount(last) + /** One Edit per changed file: its path, then the diff as lines led by ' ', '-' or '+'. */ + private fun fileEntries(id: String, changes: JSONArray) = (0 until changes.length()).mapNotNull { i -> + val change = changes.optJSONObject(i) ?: return@mapNotNull null + val path = change.optString("path") + AgentHost.Entry.Used("$id#$i", "Edit", path, path + "\n" + patchLines(change.optString("diff"), change.optJSONObject("kind")?.optString("type").orEmpty())) } @VisibleForTesting - internal fun tokenCount(line: String): AgentEvent? { - val payload = runCatching { JSONObject(line).optJSONObject("payload") }.getOrNull()?.takeIf { it.optString("type") == "token_count" } ?: return null - val info = payload.optJSONObject("info") - val rates = payload.optJSONObject("rate_limits") - val limits = listOf("primary", "secondary").mapNotNull { key -> - val w = rates?.optJSONObject(key) ?: return@mapNotNull null - AgentHost.Limit(w.optInt("window_minutes"), w.optDouble("used_percent", 0.0).toInt(), w.optLong("resets_at")) - } - return AgentEvent( - context = info?.optJSONObject("last_token_usage")?.optLong("total_tokens")?.takeIf { it > 0 }, - window = info?.optLong("model_context_window")?.takeIf { it > 0 }, - limits = limits.takeIf { it.isNotEmpty() }, - ) + internal fun rateLimits(snapshot: JSONObject?): List? { + snapshot ?: return null + return listOf("primary", "secondary").mapNotNull { key -> + val w = snapshot.optJSONObject(key) ?: return@mapNotNull null + AgentHost.Limit(w.optInt("windowDurationMins"), w.optDouble("usedPercent", 0.0).toInt(), w.optLong("resetsAt")) + }.takeIf { it.isNotEmpty() } } - private fun todoEntry(id: String, item: JSONObject): AgentHost.Entry.Used { - val items = item.optJSONArray("items") ?: JSONArray() - val text = (0 until items.length()).mapNotNull { i -> - val todo = items.optJSONObject(i) ?: return@mapNotNull null - "${if (todo.optBoolean("completed")) "[x]" else "[ ]"} ${todo.optString("text")}" - }.joinToString("\n") - return AgentHost.Entry.Used("$id-todo", "TodoWrite", "", text, output = "") - } + private fun strings(list: JSONArray?) = (0 until (list?.length() ?: 0)).mapNotNull { list?.optString(it)?.takeIf { s -> s.isNotBlank() } } - private fun changedFiles(item: JSONObject): String { - val changes = item.optJSONArray("changes") ?: return "" - return (0 until changes.length()).mapNotNull { changes.optJSONObject(it)?.optString("path") }.joinToString(", ").take(400) + private fun pretty(value: Any): String = when (value) { + is JSONObject -> value.toString(2) + is JSONArray -> value.toString(2) + JSONObject.NULL -> "" + else -> value.toString() } } -/** OpenCode: `opencode run --format json`, resumed by session id. */ +/** OpenCode: `opencode acp`, the Agent Client Protocol over stdio, resumed by session id. */ object OpenCode : AgentHarness { override val id = "opencode" override val name = "OpenCode" @@ -579,86 +783,234 @@ object OpenCode : AgentHarness { private val MODEL_ID = Regex("""^[\w.-]+/\S+$""") - private class Spent(var cost: Double = 0.0, var input: Long = 0, var output: Long = 0) - private val spent = Spent() - @Volatile private var model: String? = null + override val permissions = listOf( + AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint), + AgentHarness.Permission(AgentHarness.EDITS, R.string.agent_permission_edits, R.string.agent_permission_edits_hint), + AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint), + ) - override fun turn(message: String, conversation: String?, options: AgentHarness.Options): List { - synchronized(spent) { spent.cost = 0.0; spent.input = 0; spent.output = 0 } - model = options.model - // DroidDeck runs the agent unattended; --auto approves all the agent does not deny itself, and plan mode denies edits. - return buildList { - addAll(listOf(binary, "run", "--format", "json", "--auto", "--thinking")) - if (conversation != null) addAll(listOf("-s", conversation)) - if (options.plan) addAll(listOf("--agent", "plan")) - options.model?.let { addAll(listOf("-m", it)) } - options.effort?.let { addAll(listOf("--variant", it)) } - add("--") - // opencode run has no system prompt option, so a new conversation starts with the brief. - add(if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message) + /** + * Rules merged over the user's opencode config. OpenCode applies the last rule that matches in key order, so the + * asking modes name each permission rather than "*", which could land after a rule of the user's and override it. + */ + @VisibleForTesting + internal fun rules(permission: String): JSONObject { + val asks = listOf("bash", "webfetch", "websearch", "codesearch") + return when (permission) { + AgentHarness.FULL -> JSONObject().put("*", "allow") + AgentHarness.EDITS -> JSONObject().put("edit", "allow").apply { asks.forEach { put(it, "ask") } } + else -> JSONObject().put("edit", "ask").apply { asks.forEach { put(it, "ask") } } } } - override fun usage(rootfs: File, conversation: String?): AgentEvent? { - val id = model ?: return null - return listed(rootfs)?.windows?.get(id)?.let { AgentEvent(window = it) } - } + override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = + withoutStderr("opencode", listOf("/usr/bin/env", "OPENCODE_PERMISSION=${rules(options.permission)}", binary, "acp")) - override fun parse(line: String): AgentEvent? { - val o = runCatching { JSONObject(line) }.getOrNull() ?: return null - val conversation = o.optString("sessionID").takeIf { it.isNotEmpty() } - val part = o.optJSONObject("part") - return when (o.optString("type")) { - "text" -> AgentEvent(conversation, text(part) { AgentHost.Entry.Said(it) }) - "reasoning" -> AgentEvent(conversation, text(part) { AgentHost.Entry.Thought(it) }) - "tool_use" -> AgentEvent(conversation, part?.let { tool(it) }.orEmpty()) - "step_finish" -> { - val tokens = part?.optJSONObject("tokens") - val cache = tokens?.optJSONObject("cache") - val total = synchronized(spent) { - spent.cost += part?.optDouble("cost", 0.0) ?: 0.0 - spent.input += (tokens?.optLong("input") ?: 0) + (cache?.optLong("read") ?: 0) + (cache?.optLong("write") ?: 0) - spent.output += (tokens?.optLong("output") ?: 0) + (tokens?.optLong("reasoning") ?: 0) - AgentHost.Usage(0, spent.cost, spent.input, spent.output) + /** The conversation's cost so far; DroidDeck takes the turn's share from what its chat has recorded. */ + override val sessionCost = true + + override fun protocol(): AgentProtocol = Protocol() + + /** `opencode acp`: the Agent Client Protocol, JSON-RPC over stdio. */ + @VisibleForTesting + internal class Protocol : AgentProtocol { + private enum class Stage { INIT, SESSION, CONFIG, PROMPT, IDLE } + + private var next = 1 + private var stage = Stage.IDLE + private var pending = -1 + private var session: String? = null + private var resume: String? = null + private var cwd = "/root" + /** Requests for the session still to send, each once the one before it has been answered. */ + private val queue = ArrayDeque<(String) -> JSONObject>() + private val said = StringBuilder() + private val thought = StringBuilder() + /** Each tool call's name, which only its first update carries, and its latest entry. */ + private val names = mutableMapOf() + private val used = mutableMapOf() + private var cost = 0.0 + private var started = 0L + + override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List { + val text = if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message + val prompt = { id: String -> + JSONObject().put("sessionId", id).put("prompt", JSONArray().put(JSONObject().put("type", "text").put("text", text))) + } + queue.clear() + val known = session + if (!started && known != null && configured) return listOf(send(Stage.PROMPT, "session/prompt", prompt(known))) + fun option(config: String, value: String) = { id: String -> JSONObject().put("sessionId", id).put("configId", config).put("value", value) } + options.model?.let { queue += option("model", it) } + options.effort?.let { queue += option("effort", it) } + queue += option("mode", if (options.plan) "plan" else "build") + queue += prompt + // A session whose options were refused sets them all again before its next prompt. + if (!started && known != null) return listOf(advance(known)) + resume = conversation + cwd = options.workdir + return listOf(send(Stage.INIT, "initialize", JSONObject().put("protocolVersion", 1).put("clientCapabilities", JSONObject()))) + } + + private fun send(stage: Stage, method: String, params: JSONObject): String { + this.stage = stage + pending = next++ + if (stage == Stage.PROMPT) started = System.currentTimeMillis() + return JSONObject().put("jsonrpc", "2.0").put("id", pending).put("method", method).put("params", params).toString() + } + + /** The next queued request: the prompt once nothing else is left. */ + private fun advance(id: String): String { + val make = queue.removeFirst() + val params = make(id) + configuring = params.optString("configId") + configured = queue.isEmpty() + return if (queue.isEmpty()) send(Stage.PROMPT, "session/prompt", params) else send(Stage.CONFIG, "session/set_config_option", params) + } + + /** The config option the pending set_config_option sets. */ + private var configuring = "" + /** The session's model, effort and mode were all set, so a later prompt can go straight to it. */ + private var configured = false + + override fun answer(approval: AgentHost.Approval, allow: Boolean): String = JSONObject(approval.payload).put("jsonrpc", "2.0") + .put("result", JSONObject().put("outcome", JSONObject().put("outcome", "selected").put("optionId", if (allow) "once" else "reject"))).toString() + + override fun parse(line: String): AgentEvent? { + val o = runCatching { JSONObject(line) }.getOrNull() ?: return null + val method = o.optString("method") + val params = o.optJSONObject("params") ?: JSONObject() + return when { + method.isEmpty() -> response(o) + o.has("id") -> request(o.get("id"), method, params) + method == "session/update" -> update(params.optJSONObject("update") ?: return null) + else -> null + } + } + + private fun response(o: JSONObject): AgentEvent? { + if (o.optInt("id", -1) != pending) return null + val error = o.optJSONObject("error")?.let { it.optJSONObject("data")?.optString("message")?.ifEmpty { null } ?: it.optString("message").ifEmpty { "error" } } + val result = o.optJSONObject("result") ?: JSONObject() + return when (stage) { + Stage.INIT -> error?.let(::failed) ?: AgentEvent(reply = listOf( + resume?.let { send(Stage.SESSION, "session/resume", JSONObject().put("sessionId", it).put("cwd", cwd).put("mcpServers", JSONArray())) } + ?: send(Stage.SESSION, "session/new", JSONObject().put("cwd", cwd).put("mcpServers", JSONArray())), + )) + Stage.SESSION -> { + if (error != null) return failed(error) + val id = result.optString("sessionId").ifEmpty { resume.orEmpty() }.takeIf { it.isNotEmpty() } ?: return failed("no session") + session = id + AgentEvent(id, reply = listOf(advance(id))) } - val context = tokens?.optLong("total")?.takeIf { it > 0 } - // A step that ends to run tools is followed by another; any other reason ends the turn. - if (part?.optString("reason") == "tool-calls") AgentEvent(conversation, context = context) - else AgentEvent(conversation, listOf(AgentHost.Entry.Finished(null)), context = context, usage = total) + // A model without effort levels refuses one and the turn goes on with its default; a refused + // mode would run a plan turn as a build one, so it ends the turn instead. + Stage.CONFIG -> if (error != null && configuring == "mode") failed(error) else AgentEvent(reply = listOf(advance(session ?: return null))) + Stage.PROMPT -> { + stage = Stage.IDLE + val usage = result.optJSONObject("usage") + val reason = result.optString("stopReason") + AgentEvent( + session, + flush() + AgentHost.Entry.Finished(error ?: if (reason == "refusal") "refused" else null), + usage = AgentHost.Usage( + System.currentTimeMillis() - started, cost, + (usage?.optLong("inputTokens") ?: 0) + (usage?.optLong("cachedReadTokens") ?: 0), + (usage?.optLong("outputTokens") ?: 0) + (usage?.optLong("thoughtTokens") ?: 0), + ), + ) + } + Stage.IDLE -> null } - "error" -> { - val error = o.optJSONObject("error") - val message = error?.optJSONObject("data")?.optString("message")?.takeIf { it.isNotEmpty() } - ?: error?.optString("message")?.takeIf { it.isNotEmpty() } ?: error?.optString("name")?.takeIf { it.isNotEmpty() } ?: "error" - AgentEvent(conversation, listOf(AgentHost.Entry.Finished(message))) + } + + private fun failed(error: String): AgentEvent { + stage = Stage.IDLE + configured = false + return AgentEvent(session, flush() + AgentHost.Entry.Finished(error)) + } + + private fun request(id: Any, method: String, params: JSONObject): AgentEvent { + val payload = JSONObject().put("id", id).toString() + if (method != "session/request_permission") { + // File writes and terminals stay with OpenCode, which does them itself when the client declines. + return AgentEvent(reply = listOf(JSONObject(payload).put("jsonrpc", "2.0") + .put("error", JSONObject().put("code", -32601).put("message", "DroidDeck cannot answer $method")).toString())) } - else -> conversation?.let { AgentEvent(it) } + val call = params.optJSONObject("toolCall") ?: JSONObject() + val raw = call.optJSONObject("rawInput") ?: JSONObject() + val name = names[call.optString("toolCallId")] ?: call.optString("kind") + val kind = call.optString("kind") + val approval = when { + kind == "execute" -> AgentHost.Approval(id.toString(), "Bash", firstLine(raw.optString("command")), raw.optString("command"), payload) + // OpenCode asks for a folder outside the workspace on its own, before the tool's own ask. + raw.has("parentDir") -> AgentHost.Approval( + id.toString(), "External directory", raw.optString("parentDir"), + listOf(raw.optString("parentDir"), raw.optString("command")).filter { it.isNotEmpty() }.joinToString("\n\n"), payload, + ) + raw.has("diff") -> { + val path = raw.optString("filepath") + AgentHost.Approval(id.toString(), "Edit", path, path + "\n" + patchLines(raw.optString("diff"), ""), payload) + } + else -> AgentHost.Approval(id.toString(), toolName(name), call.optString("title"), raw.toString(2), payload) + } + return AgentEvent(session, flush(), approval = approval) + } + + private fun update(u: JSONObject): AgentEvent? = when (u.optString("sessionUpdate")) { + "agent_message_chunk" -> chunk(u)?.let { said.append(it); AgentEvent(session, text = it) } + "agent_thought_chunk" -> chunk(u)?.let { thought.append(it); AgentEvent(session, thinking = it) } + "tool_call", "tool_call_update" -> AgentEvent(session, flush() + tool(u)) + "usage_update" -> { + u.optJSONObject("cost")?.optDouble("amount")?.takeIf { !it.isNaN() }?.let { cost = it } + AgentEvent(session, context = u.optLong("used").takeIf { it > 0 }, window = u.optLong("size").takeIf { it > 0 }) + } + else -> null + } + + private fun chunk(u: JSONObject) = u.optJSONObject("content")?.takeIf { it.optString("type") == "text" }?.optString("text")?.takeIf { it.isNotEmpty() } + + /** What was written since the last entry, as whole entries. */ + private fun flush(): List = buildList { + thought.toString().trim().takeIf { it.isNotEmpty() }?.let { add(AgentHost.Entry.Thought(it)) } + said.toString().trim().takeIf { it.isNotEmpty() }?.let { add(AgentHost.Entry.Said(it)) } + thought.clear() + said.clear() + } + + private fun tool(u: JSONObject): List { + val id = u.optString("toolCallId") + if (u.optString("sessionUpdate") == "tool_call") names[id] = u.optString("title") + val input = u.optJSONObject("rawInput")?.takeIf { it.length() > 0 } + val entry = if (input != null || used[id] == null) tool(id, names[id].orEmpty(), input ?: JSONObject()) else used.getValue(id) + used[id] = entry + val raw = u.optJSONObject("rawOutput") + return when (u.optString("status")) { + "completed" -> { + val exit = raw?.optJSONObject("metadata")?.opt("exit") + listOf(entry, AgentHost.Entry.Result(id, raw?.optString("output")?.ifEmpty { null } ?: content(u), exit is Number && exit.toInt() != 0)) + } + "failed" -> listOf(entry, AgentHost.Entry.Result(id, raw?.optString("error")?.ifEmpty { null } ?: content(u), true)) + else -> listOf(entry) + } + } + + private fun content(u: JSONObject): String { + val list = u.optJSONArray("content") ?: return "" + return (0 until list.length()).mapNotNull { list.optJSONObject(it)?.optJSONObject("content")?.optString("text") }.joinToString("\n") } } - private fun text(part: JSONObject?, entry: (String) -> AgentHost.Entry) = - part?.optString("text")?.trim()?.takeIf { it.isNotEmpty() }?.let { listOf(entry(it)) }.orEmpty() + private fun toolName(name: String) = name.replaceFirstChar { it.uppercase() }.ifEmpty { "Tool" } - private fun tool(part: JSONObject): List { - val id = part.optString("callID").ifEmpty { part.optString("id") } - val state = part.optJSONObject("state") ?: JSONObject() - val input = state.optJSONObject("input") ?: JSONObject() + private fun tool(id: String, name: String, input: JSONObject): AgentHost.Entry.Used { val path = input.optString("filePath") - val (name, detail, full) = when (val tool = part.optString("tool")) { - "bash" -> Triple("Bash", firstLine(input.optString("command")), input.optString("command")) - "edit" -> Triple("Edit", path, path + "\n" + lineDiff(input.optString("oldString"), input.optString("newString"))) - "write" -> Triple("Write", path, path + "\n" + lineDiff("", input.optString("content"))) - "todowrite" -> Triple("TodoWrite", "", todos(input.optJSONArray("todos"))) - else -> Triple(tool.replaceFirstChar { it.uppercase() }.ifEmpty { "Tool" }, detail(input), input.toString(2)) - } - val used = AgentHost.Entry.Used(id, name, detail, full) - return when (state.optString("status")) { - "completed" -> { - val exit = state.optJSONObject("metadata")?.opt("exit") - listOf(used, AgentHost.Entry.Result(id, state.optString("output"), exit is Number && exit.toInt() != 0)) - } - "error" -> listOf(used, AgentHost.Entry.Result(id, state.optString("error"), true)) - else -> listOf(used) + return when (name) { + "bash" -> AgentHost.Entry.Used(id, "Bash", firstLine(input.optString("command")), input.optString("command")) + "edit" -> AgentHost.Entry.Used(id, "Edit", path, path + "\n" + lineDiff(input.optString("oldString"), input.optString("newString"))) + "write" -> AgentHost.Entry.Used(id, "Write", path, path + "\n" + lineDiff("", input.optString("content"))) + "todowrite" -> AgentHost.Entry.Used(id, "TodoWrite", "", todos(input.optJSONArray("todos"))) + else -> AgentHost.Entry.Used(id, toolName(name), detail(input), if (input.length() == 0) "" else input.toString(2)) } } @@ -679,6 +1031,13 @@ object OpenCode : AgentHarness { @VisibleForTesting internal fun firstLine(text: String) = text.lineSequence().first().take(160) +/** + * [command] with its stderr in a log of its own under /root/.cache/droiddeck. The agent's stdout and stderr share one + * pipe, and a log line written in the middle of a long JSON line would make that line unreadable. + */ +internal fun withoutStderr(log: String, command: List) = + listOf("/bin/sh", "-c", "mkdir -p /root/.cache/droiddeck; exec \"\$@\" 2>/root/.cache/droiddeck/$log.log", "sh") + command + private const val DIFF_CONTEXT = 2 /** @@ -701,6 +1060,18 @@ internal fun lineDiff(old: String, new: String): String { }.joinToString("\n") } +/** A unified diff's hunks without their headers; an added or deleted file's diff is its whole content. */ +@VisibleForTesting +internal fun patchLines(diff: String, kind: String): String { + val lines = diff.removeSuffix("\n").lines() + when (kind) { + "add" -> return lines.joinToString("\n") { "+$it" } + "delete" -> return lines.joinToString("\n") { "-$it" } + } + val start = lines.indexOfFirst { it.startsWith("@@") } + return (if (start < 0) lines else lines.drop(start)).filter { it.isNotEmpty() && !it.startsWith("@@") && !it.startsWith("\\") }.joinToString("\n") +} + private val SHELL_WRAPPER = Regex("^/bin/(?:ba)?sh -l?c '(.*)'$", RegexOption.DOT_MATCHES_ALL) /** Codex runs each command as `/bin/bash -lc ''`; the command is what the user wants to read. */ diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt index de00d5ce73..80667afef0 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt @@ -21,8 +21,8 @@ import java.nio.file.Files /** * The launcher's agent: a coding agent CLI ([AgentHarness]) from the Linux userland, run headless - * outside any game or desktop session: one process per turn, or for a CLI that takes its messages over - * stdin one process kept open between turns, so background work can start a turn of its own. Conversations are kept on disk + * outside any game or desktop session as one process that takes its messages over stdin and stays open + * between turns, so background work can start a turn of its own. Conversations are kept on disk * ([AgentChats]), so a restart (a Lab build, a crash) continues the same one. */ object AgentHost { @@ -56,6 +56,9 @@ object AgentHost { /** A message typed while the agent was working, sent when the turn ends. */ data class Queued(val text: String, val files: List) + /** A tool call the CLI waits on the user to allow; [payload] is what its protocol needs to answer. */ + data class Approval(val id: String, val tool: String, val detail: String, val input: String, val payload: String = "") + enum class State { MISSING, IDLE, WORKING } private const val TAG = "AgentHost" @@ -94,6 +97,12 @@ object AgentHost { private set var plan by mutableStateOf(false) private set + /** The chosen [AgentHarness.Permission] of [harness]; asking first until the user picks another. */ + var permission by mutableStateOf(AgentHarness.ASK) + private set + /** Tool calls of the running turn that wait for the user, oldest first. */ + val approvals = mutableStateListOf() + private var approvalNoticed = false var chat by mutableStateOf(null) private set /** A reply finished since the conversation was last on screen. */ @@ -123,7 +132,9 @@ object AgentHost { var lab by mutableStateOf(null) private set - private class Turn(val process: Process, val pid: Int, val stdin: java.io.OutputStream? = null) { + private class Turn(val process: Process, val pid: Int, val protocol: AgentProtocol, val stdin: java.io.OutputStream) { + fun write(lines: List) = synchronized(this) { stdin.apply { lines.forEach { write((it + "\n").toByteArray()) }; flush() } } + var writingGeneration: Int? = null var exitStatus: Int? = null var costs: AgentCostTracker? = null @@ -171,6 +182,8 @@ object AgentHost { model = prefs(app).getString(modelKey(harness), null) effort = prefs(app).getString(effortKey(harness), null)?.takeIf { it in harness.efforts } plan = prefs(app).getBoolean(PLAN_KEY, false) + permission = prefs(app).getString(permissionKey(harness), null)?.takeIf { id -> harness.permissions.any { it.id == id } } + ?: harness.permissions.first().id limits = decodeLimits(prefs(app).getString(limitsKey(harness), null)) available = LinuxRuntime.hasRootfs(app) installed = harness.files.all { guestFileExists(app, it) } @@ -273,6 +286,42 @@ object AgentHost { prefs(context).edit().putBoolean(PLAN_KEY, on).apply() } + /** Kept per CLI, for every conversation; the CLI process restarts with it on the next message. */ + fun choosePermission(context: Context, id: String) { + if (harness.permissions.none { it.id == id }) return + permission = id + prefs(context).edit().putString(permissionKey(harness), id).apply() + } + + /** Lets the CLI run [approval]'s tool call, or tells it the user said no. */ + fun answer(context: Context, approval: Approval, allow: Boolean) { + if (!approvals.remove(approval)) return + val running = turn ?: session ?: return + val line = running.protocol.answer(approval, allow) + val app = context.applicationContext + val current = harness + Thread({ runCatching { running.write(listOf(line)) }.onFailure { lost(app, running, current, it) } }, "agent-approval").start() + approvalsChanged(app) + } + + /** The approval notice goes once nothing waits on the user any more. */ + private fun approvalsChanged(app: Context) { + if (approvals.isNotEmpty() || !approvalNoticed) return + approvalNoticed = false + AgentNotice.clear(app) + } + + /** + * A line the CLI waits for could not be written, so it would wait forever: its process ends, which ends + * the turn, and the chat says why. A request that may have reached it is not sent again. + */ + private fun lost(app: Context, from: Turn, current: AgentHarness, error: Throwable) { + Log.w(TAG, "could not write to ${current.name}", error) + main.post { if (turn === from || session === from) record(app, Entry.Notice("Could not write to ${current.name}: ${error.message ?: error.javaClass.simpleName}")) } + AgentProcesses.killTree(from.pid) + from.process.destroy() + } + fun models(context: Context) = harness.models(LinuxRuntime.rootDir(context.applicationContext)) /** Sends [text] now, or after the current turn when the agent is working. */ @@ -303,19 +352,20 @@ object AgentHost { val current = harness val prompt = AgentAttachments.prompt(message, attached) turnPlanned = plan && current.plans - val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort) - val command = current.turn(prompt, conversation, options) - val line = current.input(prompt) - val key = "${current.id}|$id|$model|$turnPlanned|$effort" + val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort, permission, workspace(app)) + val key = "${current.id}|$id|$model|$turnPlanned|$effort|$permission" + val resumed = conversation background = false + approvals.clear() + approvalsChanged(app) val kept = session - if (kept != null && line != null && sessionKey == key && kept.process.isAlive) { + if (kept != null && sessionKey == key && kept.process.isAlive) { main.removeCallbacks(reap) turn = kept kept.writingGeneration = gen kept.clearingCosts = prompt == "/clear" Thread({ - val written = runCatching { synchronized(kept) { kept.stdin?.apply { write((line + "\n").toByteArray()); flush() } != null } }.getOrDefault(false) + val written = runCatching { kept.write(kept.protocol.input(prompt, resumed, options, started = false)) }.isSuccess // The process died between turns: the same message goes to a new one, which resumes the conversation. main.post { if (kept.writingGeneration == gen) kept.writingGeneration = null @@ -323,7 +373,7 @@ object AgentHost { if (!written) { dropSession() turn = null - spawn(app, gen, current, current.turn(prompt, conversation, options), line, key) + spawn(app, gen, current, prompt, resumed, options, key) } else kept.exitStatus?.let { processExited(app, kept, current, it) } } } @@ -331,12 +381,14 @@ object AgentHost { return } dropSession() - spawn(app, gen, current, command, line, key) + spawn(app, gen, current, prompt, resumed, options, key) } - private fun spawn(app: Context, gen: Int, current: AgentHarness, command: List, line: String?, key: String) { - val workdir = workspace(app) - var threadConversation = conversation + private fun spawn(app: Context, gen: Int, current: AgentHarness, prompt: String, resumed: String?, options: AgentHarness.Options, key: String) { + val workdir = options.workdir + val command = current.turn(prompt, resumed, options) + val protocol = current.protocol() + var threadConversation = resumed Thread({ runCatching { current.prepare(LinuxRuntime.rootDir(app)) } runCatching { AgentSetup.installHelpers(app) } @@ -349,17 +401,18 @@ object AgentHost { main.post { if (generation == gen) finish(app, e.message ?: "could not start") } return@Thread } - val started = Turn(child, AgentProcesses.pidOf(child), if (line != null) child.outputStream else null).apply { - if (current === ClaudeCode && line != null) costs = AgentCostTracker() + val started = Turn(child, AgentProcesses.pidOf(child), protocol, child.outputStream).apply { + if (current === ClaudeCode) costs = AgentCostTracker() } OrphanReaper.keep(started.pid) main.post { if (generation == gen && state == State.WORKING && turn == null) { turn = started - if (line != null) { session = started; sessionKey = key } + session = started + sessionKey = key } else AgentProcesses.killTree(started.pid) } - if (line != null) runCatching { child.outputStream.apply { write((line + "\n").toByteArray()); flush() } } else child.outputStream.close() + runCatching { started.write(protocol.input(prompt, resumed, options, started = true)) }.onFailure { lost(app, started, current, it) } val raw = runCatching { val log = File(app.filesDir, TURN_LOG).apply { parentFile?.mkdirs() } log.renameTo(File(app.filesDir, "$TURN_LOG.1")) @@ -368,7 +421,8 @@ object AgentHost { runCatching { child.inputStream.bufferedReader().forEachLine { output -> runCatching { raw?.apply { write(output); newLine(); flush() } } - val parsed = current.parse(output) ?: return@forEachLine + val parsed = protocol.parse(output) ?: return@forEachLine + if (parsed.reply.isNotEmpty()) runCatching { started.write(parsed.reply) }.onFailure { lost(app, started, current, it) } parsed.conversation?.let { threadConversation = it } val done = parsed.entries.any { it is Entry.Finished } val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull() @@ -410,7 +464,7 @@ object AgentHost { if (background && state == State.WORKING) finish(app, event.backgroundError, usage = event.usage?.let { from.costs?.perTurn(it) ?: it }) return } - val content = event.text != null || event.thinking != null || event.entries.any { it !is Entry.Finished } + val content = event.text != null || event.thinking != null || event.approval != null || event.entries.any { it !is Entry.Finished } if (content && state == State.IDLE && session === from) { main.removeCallbacks(reap) background = true @@ -428,10 +482,17 @@ object AgentHost { from.clearingCosts = false } val applied = if (finished != null && state == State.WORKING && event.usage != null) - event.copy(usage = from.costs?.perTurn(event.usage) ?: event.usage) else event + event.copy(usage = turnCost(from.costs?.perTurn(event.usage) ?: event.usage)) else event apply(app, applied) } + /** A CLI that reports the conversation's whole cost spent what this chat has not recorded yet. */ + private fun turnCost(usage: Usage): Usage { + if (!harness.sessionCost) return usage + val recorded = entries.sumOf { (it as? Entry.Finished)?.usage?.costUsd ?: 0.0 } + return usage.copy(costUsd = (usage.costUsd - recorded).coerceAtLeast(0.0)) + } + /** Ends the CLI process kept between turns, and with it whatever it still runs in the background. */ private fun dropSession() { main.removeCallbacks(reap) @@ -529,6 +590,15 @@ object AgentHost { } event.text?.let { live += it } event.thinking?.let { liveThinking += it } + event.resolved?.let { id -> + approvals.removeAll { it.id == id } + approvalsChanged(app) + } + event.approval?.takeIf { a -> state == State.WORKING && approvals.none { it.id == a.id } }?.let { + approvals += it + approvalNoticed = true + AgentNotice.post(app, AgentNotice.Kind.APPROVAL, listOf(it.tool, it.detail).filter { s -> s.isNotEmpty() }.joinToString(": ")) + } event.context?.let { context = it } event.window?.let { window = it } event.limits?.let { reported -> @@ -549,6 +619,8 @@ object AgentHost { private fun finish(app: Context, error: String?, stopped: Boolean = false, usage: Usage? = null) { if (state != State.WORKING) return turn = null + approvals.clear() + approvalsChanged(app) val answeredTask = background background = false main.removeCallbacks(reap) @@ -762,6 +834,7 @@ object AgentHost { private const val LINGER_MS = 20 * 60_000L private fun modelKey(harness: AgentHarness) = "model_${harness.id}" + private fun permissionKey(harness: AgentHarness) = "permission_${harness.id}" private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}" @VisibleForTesting diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentNotice.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentNotice.kt index edba77a0c8..22203ace48 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentNotice.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentNotice.kt @@ -16,10 +16,10 @@ internal object AgentNotice { private const val CHANNEL_ID = "agent_done" private const val NOTIFICATION_ID = 4108 - enum class Kind { DONE, FAILED, QUESTION } + enum class Kind { DONE, FAILED, QUESTION, APPROVAL } fun post(context: Context, kind: Kind, text: String) { - if (onScreen(context)) return + if (onScreen(context, kind)) return val manager = context.getSystemService(NotificationManager::class.java) ?: return manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_done_channel), NotificationManager.IMPORTANCE_DEFAULT)) val open = PendingIntent.getActivity(context, 2, @@ -31,6 +31,7 @@ internal object AgentNotice { Kind.DONE -> R.string.agent_done Kind.FAILED -> R.string.agent_done_failed Kind.QUESTION -> R.string.agent_done_question + Kind.APPROVAL -> R.string.agent_done_approval }) runCatching { manager.notify(NOTIFICATION_ID, Notification.Builder(context, CHANNEL_ID) @@ -49,9 +50,9 @@ internal object AgentNotice { context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID) } - /** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble. */ - private fun onScreen(context: Context): Boolean { - if (AgentPet.floating) return true + /** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble but has no way to answer an approval. */ + private fun onScreen(context: Context, kind: Kind): Boolean { + if (AgentPet.floating && kind != Kind.APPROVAL) return true val state = ActivityManager.RunningAppProcessInfo().also { ActivityManager.getMyMemoryState(it) } return AgentPet.agentOnScreen > 0 && state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt index 32c48765bc..01a486b574 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -30,6 +30,7 @@ import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.ime import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding @@ -39,6 +40,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions @@ -128,7 +130,7 @@ import kotlinx.coroutines.launch internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES, TOOLS } /** Slash commands the app handles itself; others go to the CLI, which has its own. */ -private val LOCAL_COMMANDS = listOf("/new", "/model", "/plan", "/history", "/processes", "/stop") +private val LOCAL_COMMANDS = listOf("/new", "/model", "/permissions", "/plan", "/history", "/processes", "/stop") private val CLI_COMMANDS = listOf("/compact", "/cost", "/review", "/init") /** @@ -207,7 +209,7 @@ private fun AgentPageContent( var setup by rememberSaveable { mutableStateOf(false) } val draft = rememberSaveable { mutableStateOf("") } if (setup || AgentHost.state == AgentHost.State.MISSING || !(AgentSetup.ready || AgentSetup.completed(context))) { - AgentSetupView(modifier, onDone = { setup = false }) + AgentSetupView(modifier, firstControl = inputModifier, onDone = { setup = false }) return } var panel by rememberSaveable { mutableStateOf(AgentPanel.NONE) } @@ -233,6 +235,10 @@ private fun AgentPageContent( // The keyboard leaves too little height for a panel and the editor together, so typing closes the panel. val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0 LaunchedEffect(keyboardOpen) { if (keyboardOpen && (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE)) panel = AgentPanel.NONE } + // History, processes and tools take the whole page, which would hide an approval the turn is waiting on. + LaunchedEffect(AgentHost.approvals.size, panel) { + if (AgentHost.approvals.isNotEmpty() && (panel == AgentPanel.HISTORY || panel == AgentPanel.PROCESSES || panel == AgentPanel.TOOLS)) panel = AgentPanel.NONE + } Column( modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e -> val k = e.nativeKeyEvent @@ -279,7 +285,8 @@ private fun AgentPageContent( readingBack = false scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) } } - val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() + val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() && + AgentHost.approvals.isEmpty() var listHeight by remember { mutableIntStateOf(0) } Box( Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack).onGloballyPositioned { @@ -354,7 +361,7 @@ private fun AgentTopBar(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstC } } -/** The harness, model, effort and plan mode, opening the model picker; [compact] names only the model. */ +/** The harness, model, effort, a permission mode other than asking first and plan mode, opening the model picker; [compact] names only the model. */ @Composable private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstControl: Modifier, modifier: Modifier = Modifier, compact: Boolean = false) { val context = LocalContext.current @@ -365,8 +372,12 @@ private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstCon modifier = modifier.then(if (compact) Modifier.widthIn(max = 120.dp) else Modifier).height(36.dp).clip(Shape12).then(firstControl) .clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"), ) { - val parts = if (compact) listOf(model) - else listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans }) + val mode = AgentHost.harness.permissions.drop(1).firstOrNull { it.id == AgentHost.permission }?.let { stringResource(it.label) } + val parts = if (compact) listOfNotNull(mode ?: model) + else listOfNotNull( + AgentHost.harness.name, model, AgentHost.effort, mode, + stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans }, + ) Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp)) @@ -523,6 +534,39 @@ internal fun clock(seconds: Long): String { } } +/** The oldest tool call that waits for the user; tapping its input shows all of it. */ +@Composable +private fun AgentApprovalCard(approval: AgentHost.Approval, more: Int) { + val context = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var open by remember(approval.id) { mutableStateOf(false) } + Column( + Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, AttentionAmber, Shape14) + .padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-approval"), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Column(Modifier.weight(1f)) { + Text(stringResource(R.string.agent_approval_title, approval.tool), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + if (more > 0) Text(stringResource(R.string.agent_approval_more, more), fontSize = 12.5.sp, color = pal.onSurfaceVariant) + } + SecondaryButton(stringResource(R.string.agent_approval_deny), compact = true, modifier = Modifier.testTag("agent-approval-deny")) { + AgentHost.answer(context, approval, allow = false) + } + PrimaryButton(stringResource(R.string.agent_approval_allow), compact = true, modifier = Modifier.testTag("agent-approval-allow")) { + AgentHost.answer(context, approval, allow = true) + } + } + val body = approval.input.ifBlank { approval.detail } + val shown = Modifier.fillMaxWidth().padding(top = 6.dp) + .then(if (open) Modifier.heightIn(max = 280.dp).verticalScroll(rememberScrollState()) else Modifier).clickable { open = !open } + if (body.isNotBlank()) Text( + body, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, + maxLines = if (open) Int.MAX_VALUE else 4, overflow = TextOverflow.Ellipsis, modifier = shown, + ) + } +} + @Composable private fun AgentLabCard() { val context = LocalContext.current @@ -675,7 +719,7 @@ private fun AgentComposer( val text = draft.trim() when (text.substringBefore(' ')) { "/new" -> AgentHost.forget(context) - "/model" -> onPanel(AgentPanel.MODEL) + "/model", "/permissions" -> onPanel(AgentPanel.MODEL) "/plan" -> AgentHost.choosePlan(context, !AgentHost.plan) "/history" -> onPanel(AgentPanel.HISTORY) "/processes" -> onPanel(AgentPanel.PROCESSES) @@ -692,6 +736,7 @@ private fun AgentComposer( val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0 Column(Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp)) { if (labOpen) AgentLabCard() + AgentHost.approvals.firstOrNull()?.let { AgentApprovalCard(it, AgentHost.approvals.size - 1) } if (hasActivity()) Row( horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt index 1029db97ea..a462fca130 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt @@ -67,7 +67,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext -/** The model, reasoning effort and plan mode for the next turns; a conversation keeps going with whatever is chosen. */ +/** The model, reasoning effort, permissions and plan mode for the next turns; a conversation keeps going with whatever is chosen. */ @Composable internal fun AgentModelPicker() { val context = LocalContext.current @@ -92,6 +92,20 @@ internal fun AgentModelPicker() { } } } + val modes = AgentHost.harness.permissions + if (modes.size > 1) Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text(stringResource(R.string.agent_permissions), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(horizontal = 2.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) { + for (mode in modes) { + val label = stringResource(mode.label) + if (mode.id == AgentHost.permission) PrimaryButton(label, compact = true, modifier = Modifier.testTag("agent-permission")) {} + else SecondaryButton(label, compact = true, modifier = Modifier.testTag("agent-permission")) { AgentHost.choosePermission(context, mode.id) } + } + } + modes.firstOrNull { it.id == AgentHost.permission }?.let { + Text(stringResource(it.hint), fontSize = 12.5.sp, color = pal.onSurfaceVariant, modifier = Modifier.padding(horizontal = 2.dp)) + } + } if (AgentHost.harness.plans) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp)) { Column(Modifier.weight(1f)) { Text(stringResource(R.string.agent_plan), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt index 00d7880937..3f7293b748 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt @@ -48,7 +48,7 @@ import com.droiddeck.launcher.agent.AgentSetup.Step import com.droiddeck.launcher.core.WirelessAdbPairingService @Composable -internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) { +internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifier, onDone: () -> Unit = {}) { val context = LocalContext.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -78,7 +78,7 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) { Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { for (harness in AgentHarness.all) { val chosen = harness == AgentHost.harness - if (chosen) PrimaryButton(harness.name, compact = true) {} else SecondaryButton(harness.name, enabled = !AgentSetup.busy, compact = true) { AgentHost.choose(context, harness) } + if (chosen) PrimaryButton(harness.name, compact = true, modifier = firstControl) {} else SecondaryButton(harness.name, enabled = !AgentSetup.busy, compact = true) { AgentHost.choose(context, harness) } } } val steps = Step.entries diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt index cb438903b7..d65852ece2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt @@ -14,7 +14,7 @@ internal enum class SessionDrawerPage(val firstControl: String) { } internal fun sessionDrawerPages( - hasSecondScreen: Boolean, hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentHost.installed && com.droiddeck.launcher.agent.AgentTab.shown, + hasSecondScreen: Boolean, hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, ): List = SessionDrawerPage.entries.filter { (hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN) && (hasGlasses || it != SessionDrawerPage.GLASSES) && diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index da2cf23085..44e51c682c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1256,6 +1256,7 @@ Agent finished Agent stopped with an error Agent has a question + Agent is waiting for your OK %d step %d steps @@ -1333,6 +1334,21 @@ Plan first Plan Proposes a plan without changing anything + Permissions + Ask first + Asks before edits and commands that need your OK + Accept edits + Edits files freely, asks before commands + Auto + A safety check decides, blocking risky actions + Don\'t ask + Denies anything your settings don\'t allow + Full access + Runs everything without asking + Allow %1$s? + Allow + Deny + +%1$d more Conversations No conversations yet Just now diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt index 30cb71009e..e51a0d2fca 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt @@ -84,10 +84,10 @@ class AgentHostTest { val command = ClaudeCode.turn("hello there", null, AgentHarness.Options()) assertEquals("stream-json", command[command.indexOf("--input-format") + 1]) assertFalse("hello there" in command) - val line = org.json.JSONObject(ClaudeCode.input("hello there")!!) + val line = org.json.JSONObject(ClaudeCode.input("hello there")) assertEquals("user", line.getString("type")) assertEquals("hello there", line.getJSONObject("message").getJSONArray("content").getJSONObject(0).getString("text")) - assertNull(Codex.input("hi")) + assertEquals(listOf(ClaudeCode.input("hi")), ClaudeCode.protocol().input("hi", "abc", AgentHarness.Options(), started = false)) } @Test fun aTaskNotificationResultIsMarkedBackgroundAndCarriesItsUsage() { @@ -126,13 +126,35 @@ class AgentHostTest { assertTrue(used("Monitor", """{"command":"tail -f log"}""").background) } - @Test fun claudeTurnsBypassPermissionsOrPlanAndTakeAModel() { + @Test fun claudeTurnsAskFirstByDefaultAndTakeAModel() { val first = ClaudeCode.turn("hi", null, AgentHarness.Options()) - assertTrue("bypassPermissions" in first && "--resume" !in first && "--model" !in first && "--include-partial-messages" in first) + assertEquals("manual", first[first.indexOf("--permission-mode") + 1]) + assertTrue("--permission-prompt-tool=stdio" in first && "--resume" !in first && "--model" !in first && "--include-partial-messages" in first) val next = ClaudeCode.turn("hi", "abc", AgentHarness.Options(model = "opus", plan = true)) assertEquals("abc", next[next.indexOf("--resume") + 1]) assertEquals("opus", next[next.indexOf("--model") + 1]) assertEquals("plan", next[next.indexOf("--permission-mode") + 1]) + assertFalse("--permission-prompt-tool=stdio" in next) + fun mode(permission: String) = ClaudeCode.turn("hi", null, AgentHarness.Options(permission = permission)).let { it[it.indexOf("--permission-mode") + 1] } + assertEquals(listOf("manual", "acceptEdits", "auto", "dontAsk", "bypassPermissions"), ClaudeCode.permissions.map { mode(it.id) }) + assertFalse("--permission-prompt-tool=stdio" in ClaudeCode.turn("hi", null, AgentHarness.Options(permission = AgentHarness.FULL))) + } + + @Test fun claudePermissionPromptsBecomeApprovalsAnsweredOnStdin() { + val event = ClaudeCode.parse("""{"type":"control_request","request_id":"r1","request":{"subtype":"can_use_tool","tool_name":"Bash","input":{"command":"rm -rf build"},"tool_use_id":"t1"}}""")!! + val approval = event.approval!! + assertEquals(AgentHost.Approval("r1", "Bash", "rm -rf build", "rm -rf build", """{"command":"rm -rf build"}"""), approval) + val allow = org.json.JSONObject(ClaudeCode.answer(approval, allow = true)) + assertEquals("control_response", allow.getString("type")) + val response = allow.getJSONObject("response") + assertEquals("r1", response.getString("request_id")) + assertEquals("allow", response.getJSONObject("response").getString("behavior")) + assertEquals("rm -rf build", response.getJSONObject("response").getJSONObject("updatedInput").getString("command")) + val deny = org.json.JSONObject(ClaudeCode.answer(approval, allow = false)).getJSONObject("response").getJSONObject("response") + assertEquals("deny", deny.getString("behavior")) + assertTrue(deny.getString("message").isNotEmpty()) + assertEquals("r1", ClaudeCode.parse("""{"type":"control_cancel_request","request_id":"r1"}""")!!.resolved) + assertNull(ClaudeCode.parse("""{"type":"control_request","request_id":"r2","request":{"subtype":"hook_callback"}}""")) } @Test fun claudeShowsWholeEditsAndTodos() { @@ -142,28 +164,99 @@ class AgentHostTest { """{"todos":[{"content":"read","status":"completed"},{"content":"fix","status":"in_progress"},{"content":"test","status":"pending"}]}"""))) } - @Test fun codexEventsBecomeEntries() { - assertEquals("t1", Codex.parse("""{"type":"thread.started","thread_id":"t1"}""")!!.conversation) - assertEquals(listOf(Entry.Used("i1", "Shell", "uname -m", "uname -m")), - Codex.parse("""{"type":"item.started","item":{"id":"i1","type":"command_execution","command":"uname -m","status":"in_progress"}}""")!!.entries) - assertEquals(listOf(Entry.Result("i1", "aarch64\n", false)), - Codex.parse("""{"type":"item.completed","item":{"id":"i1","type":"command_execution","command":"uname -m","aggregated_output":"aarch64\n","exit_code":0}}""")!!.entries) - assertEquals(listOf(Entry.Said("It is aarch64.")), - Codex.parse("""{"type":"item.completed","item":{"id":"i2","type":"agent_message","text":"It is aarch64."}}""")!!.entries) - assertEquals(Entry.Used("i3", "Edit", "a.kt, b.kt", "a.kt\nb.kt"), - Codex.parse("""{"type":"item.completed","item":{"id":"i3","type":"file_change","status":"completed","changes":[{"path":"a.kt"},{"path":"b.kt"}]}}""")!!.entries.first()) - assertEquals(listOf(Entry.Finished(null)), Codex.parse("""{"type":"turn.completed","usage":{}}""")!!.entries) - assertEquals(listOf(Entry.Finished("quota")), Codex.parse("""{"type":"turn.failed","error":{"message":"quota"}}""")!!.entries) - assertNull(Codex.parse("""{"type":"error","message":"Reconnecting... 1/5 (stream disconnected before completion)"}""")) - assertEquals(listOf(Entry.Finished("unauthorized")), Codex.parse("""{"type":"error","message":"unauthorized"}""")!!.entries) - assertNull(Codex.parse("""{"type":"item.started","item":{"type":"reasoning"}}""")) + private fun json(line: String) = org.json.JSONObject(line) + + @Test fun codexOpensAThreadThenStartsTheTurn() { + val command = Codex.turn("hi", null, AgentHarness.Options()) + assertEquals(listOf("/root/.local/bin/codex", "app-server"), command.takeLast(2)) + assertTrue(command[2].endsWith("2>/root/.cache/droiddeck/codex.log")) + val p = Codex.Protocol() + val init = json(p.input("hi", null, AgentHarness.Options(model = "gpt", effort = "high", brief = "brief"), started = true).single()) + assertEquals("initialize", init.getString("method")) + val lines = p.parse("""{"id":${init.getInt("id")},"result":{"userAgent":"codex"}}""")!!.reply + assertEquals(listOf("initialized", "thread/start"), lines.map { json(it).getString("method") }) + val start = json(lines[1]) + val params = start.getJSONObject("params") + assertEquals("untrusted", params.getString("approvalPolicy")) + assertEquals("danger-full-access", params.getString("sandbox")) + assertEquals("brief", params.getString("developerInstructions")) + val opened = p.parse("""{"id":${start.getInt("id")},"result":{"thread":{"id":"t1"},"approvalPolicy":"untrusted"}}""")!! + assertEquals("t1", opened.conversation) + val turn = json(opened.reply.single()) + assertEquals("turn/start", turn.getString("method")) + assertEquals("t1", turn.getJSONObject("params").getString("threadId")) + assertEquals("hi", turn.getJSONObject("params").getJSONArray("input").getJSONObject(0).getString("text")) + assertEquals("high", turn.getJSONObject("params").getString("effort")) + val next = json(p.input("again", "t1", AgentHarness.Options(), started = false).single()) + assertEquals("turn/start", next.getString("method")) + assertEquals("t1", next.getJSONObject("params").getString("threadId")) + fun opening(q: Codex.Protocol, conversation: String?, options: AgentHarness.Options): org.json.JSONObject { + val id = json(q.input("hi", conversation, options, started = true).single()).getInt("id") + return json(q.parse("""{"id":$id,"result":{}}""")!!.reply.last()) + } + val resumed = opening(Codex.Protocol(), "t9", AgentHarness.Options(permission = AgentHarness.FULL)) + assertEquals("thread/resume", resumed.getString("method")) + assertEquals("t9", resumed.getJSONObject("params").getString("threadId")) + assertEquals("never", resumed.getJSONObject("params").getString("approvalPolicy")) + assertEquals(listOf(Entry.Finished("no such thread")), Codex.Protocol().let { q -> + val id = opening(q, "gone", AgentHarness.Options()).getInt("id") + q.parse("""{"id":$id,"error":{"code":-32600,"message":"no such thread"}}""")!!.entries + }) + // A thread that failed to open is asked for again on the same connection without a second initialize. + Codex.Protocol().let { q -> + val id = opening(q, "gone", AgentHarness.Options()).getInt("id") + q.parse("""{"id":$id,"error":{"code":-32600,"message":"no such thread"}}""") + assertEquals(listOf("thread/resume"), q.input("again", "gone", AgentHarness.Options(), started = false).map { json(it).getString("method") }) + } + assertEquals(listOf(Entry.Finished("not signed in")), Codex.Protocol().let { q -> + val id = json(q.input("hi", null, AgentHarness.Options(), started = true).single()).getInt("id") + q.parse("""{"id":$id,"error":{"code":-32600,"message":"not signed in"}}""")!!.entries + }) } - @Test fun codexTurnsSkipItsSandboxResumeAndTakeAModel() { - assertEquals(listOf("/root/.local/bin/codex", "exec", "--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check", "hi"), - Codex.turn("hi", null, AgentHarness.Options())) - assertEquals(listOf("/root/.local/bin/codex", "exec", "resume", "t1", "--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check", "-m", "gpt", "hi"), - Codex.turn("hi", "t1", AgentHarness.Options(model = "gpt"))) + @Test fun codexItemsBecomeEntries() { + val p = Codex.Protocol() + assertEquals(listOf(Entry.Used("e1", "Shell", "touch x", "touch x")), p.parse( + """{"method":"item/started","params":{"item":{"type":"commandExecution","id":"e1","command":"/bin/bash -lc 'touch x'","status":"inProgress","aggregatedOutput":null,"exitCode":null}}}""")!!.entries) + assertEquals(listOf(Entry.Result("e1", "", false)), p.parse( + """{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"e1","command":"/bin/bash -lc 'touch x'","status":"completed","aggregatedOutput":null,"exitCode":0}}}""")!!.entries) + assertTrue((p.parse("""{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"e2","command":"false","status":"declined","aggregatedOutput":null,"exitCode":null}}}""")!!.entries.single() as Entry.Result).failed) + assertEquals(listOf(Entry.Said("done")), p.parse("""{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"m1","text":"done","phase":"final_answer"}}}""")!!.entries) + assertEquals("Do", p.parse("""{"method":"item/agentMessage/delta","params":{"itemId":"m1","delta":"Do"}}""")!!.text) + assertEquals(listOf(Entry.Used("f1#0", "Edit", "/w/note.txt", "/w/note.txt\n+hi")), p.parse( + """{"method":"item/started","params":{"item":{"type":"fileChange","id":"f1","changes":[{"path":"/w/note.txt","kind":{"type":"add"},"diff":"hi\n"}],"status":"inProgress"}}}""")!!.entries) + assertEquals(listOf(Entry.Result("f1#0", "", false)), p.parse( + """{"method":"item/completed","params":{"item":{"type":"fileChange","id":"f1","changes":[{"path":"/w/note.txt","kind":{"type":"add"},"diff":"hi\n"}],"status":"completed"}}}""")!!.entries) + p.parse("""{"method":"turn/started","params":{"turn":{"id":"u1"}}}""") + assertEquals("[x] read\n[~] fix\n[ ] test", (p.parse("""{"method":"turn/plan/updated","params":{"plan":[{"step":"read","status":"completed"},{"step":"fix","status":"inProgress"},{"step":"test","status":"pending"}]}}""")!!.entries.single() as Entry.Used).input) + val usage = p.parse("""{"method":"thread/tokenUsage/updated","params":{"tokenUsage":{"total":{"totalTokens":32017},"last":{"totalTokens":16055,"inputTokens":16019,"outputTokens":36},"modelContextWindow":258400}}}""")!! + assertEquals(16_055L, usage.context) + assertEquals(258_400L, usage.window) + assertEquals(listOf(AgentHost.Limit(10_080, 84, 1795123687)), p.parse( + """{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","primary":{"usedPercent":84,"windowDurationMins":10080,"resetsAt":1795123687},"secondary":null}}}""")!!.limits) + val end = p.parse("""{"method":"turn/completed","params":{"turn":{"id":"u1","status":"completed","error":null,"durationMs":4200}}}""")!! + assertEquals(listOf(Entry.Finished(null)), end.entries) + assertEquals(AgentHost.Usage(4200, 0.0, 16_019, 36), end.usage) + assertEquals(listOf(Entry.Finished("quota")), p.parse("""{"method":"turn/completed","params":{"turn":{"id":"u2","status":"failed","error":{"message":"quota"},"durationMs":null}}}""")!!.entries) + assertNull(p.parse("""{"method":"error","params":{"error":{"message":"Reconnecting..."},"willRetry":true}}""")) + assertNull(p.parse("not json")) + } + + @Test fun codexApprovalRequestsWaitForTheUser() { + val p = Codex.Protocol() + val command = p.parse("""{"method":"item/commandExecution/requestApproval","id":0,"params":{"kind":"command","itemId":"e1","command":"/bin/bash -lc 'touch x'","cwd":"/w"}}""")!!.approval!! + assertEquals(AgentHost.Approval("0", "Shell", "touch x", "touch x", """{"id":0}"""), command) + assertEquals("""{"id":0,"result":{"decision":"accept"}}""", p.answer(command, allow = true)) + assertEquals("decline", json(p.answer(command, allow = false)).getJSONObject("result").getString("decision")) + p.parse("""{"method":"item/started","params":{"item":{"type":"fileChange","id":"f1","changes":[{"path":"/w/a.kt","kind":{"type":"update"},"diff":"@@ -1 +1 @@\n-old\n+new\n"}],"status":"inProgress"}}}""") + val edit = p.parse("""{"method":"item/fileChange/requestApproval","id":1,"params":{"itemId":"f1","reason":null}}""")!!.approval!! + assertEquals("Edit", edit.tool) + assertEquals("/w/a.kt", edit.detail) + assertEquals("/w/a.kt\n-old\n+new", edit.input) + val refused = json(p.parse("""{"method":"item/tool/requestUserInput","id":2,"params":{}}""")!!.reply.single()) + assertEquals(2, refused.getInt("id")) + assertTrue(refused.has("error")) + assertEquals("1", p.parse("""{"method":"serverRequest/resolved","params":{"requestId":1}}""")!!.resolved) } @Test fun aToolIdUsedAgainInALaterTurnIsANewCall() { @@ -289,28 +382,6 @@ class AgentHostTest { assertEquals(1_000_000L, result.window) } - @Test fun codexTokenCountsCarryContextAndLimits() { - val event = Codex.tokenCount("""{"timestamp":"t","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"total_tokens":90000},"last_token_usage":{"total_tokens":41000},"model_context_window":272000},"rate_limits":{"primary":{"used_percent":12.5,"window_minutes":300,"resets_at":1794435600},"secondary":{"used_percent":40.0,"window_minutes":10080,"resets_at":1794592800}}}}""")!! - assertEquals(41_000L, event.context) - assertEquals(272_000L, event.window) - assertEquals(listOf(AgentHost.Limit(300, 12, 1794435600), AgentHost.Limit(10_080, 40, 1794592800)), event.limits) - assertNull(Codex.tokenCount("""{"type":"event_msg","payload":{"type":"agent_message"}}""")) - } - - @Test fun codexUsageComesFromTheThreadsSessionLog() { - val root = Files.createTempDirectory("rootfs").toFile() - val log = File(root, "root/.codex/sessions/2026/11/12/rollout-2026-11-12T10-00-00-thread1.jsonl").apply { parentFile!!.mkdirs() } - log.writeText( - """{"type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"total_tokens":15692},"model_context_window":258400},"rate_limits":{"primary":{"used_percent":86.0,"window_minutes":10080,"resets_at":1794716485},"secondary":null}}}""" + "\n" + - """{"type":"response_item","payload":{"type":"additional_tools","tools":[{"description":"reports token_count as it goes"}]}}""" + "\n", - ) - val event = Codex.usage(root, "thread1")!! - assertEquals(15_692L, event.context) - assertEquals(258_400L, event.window) - assertEquals(listOf(AgentHost.Limit(10_080, 86, 1794716485)), event.limits) - assertNull(Codex.usage(root, "other")) - } - @Test fun limitsRoundTripThroughPrefs() { val limits = listOf(AgentHost.Limit(300, 7, 1794435600), AgentHost.Limit(10_080, 85, 1794592800)) assertEquals(limits, AgentHost.decodeLimits(AgentHost.encodeLimits(limits))) diff --git a/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt index d05f5f09f3..24ce085ec0 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt @@ -18,61 +18,133 @@ import java.nio.file.Files class OpenCodeTest { private val session = "ses_1" - private fun event(type: String, part: String) = """{"type":"$type","timestamp":1,"sessionID":"$session","part":$part}""" + private fun json(line: String) = JSONObject(line) + private fun update(u: String) = """{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"$session","update":$u}}""" - @Test fun turnsResumeByIdAndCarryModelPlanAndVariant() { - assertEquals(listOf(OpenCode.binary, "run", "--format", "json", "--auto", "--thinking", "--", "brief\n\nhi"), - OpenCode.turn("hi", null, AgentHarness.Options(brief = "brief"))) - assertEquals(listOf(OpenCode.binary, "run", "--format", "json", "--auto", "--thinking", "-s", "ses_1", "--agent", "plan", - "-m", "opencode/big-pickle", "--variant", "high", "--", "-hi"), - OpenCode.turn("-hi", "ses_1", AgentHarness.Options(model = "opencode/big-pickle", plan = true, brief = "brief", effort = "high"))) + /** Drives a new process through initialize and session/new to the prompt, returning it and the prompt's id. */ + private fun opened(options: AgentHarness.Options = AgentHarness.Options()): Pair { + val p = OpenCode.Protocol() + var line = p.input("hi", null, options, started = true).single() + var result = "{}" + while (true) { + val request = json(line) + if (request.getString("method") == "session/prompt") return p to request.getInt("id") + if (request.getString("method") == "session/new") result = """{"sessionId":"$session"}""" + line = p.parse("""{"jsonrpc":"2.0","id":${request.getInt("id")},"result":$result}""")!!.reply.single() + } } - @Test fun textReasoningAndStepsBecomeEntries() { - OpenCode.turn("hi", null, AgentHarness.Options()) - assertEquals(session, OpenCode.parse(event("step_start", """{"type":"step-start"}"""))!!.conversation) - assertEquals(listOf(Entry.Said("x86_64")), OpenCode.parse(event("text", """{"type":"text","text":" x86_64\n"}"""))!!.entries) - assertEquals(listOf(Entry.Thought("why")), OpenCode.parse(event("reasoning", """{"type":"reasoning","text":"why"}"""))!!.entries) - val step = OpenCode.parse(event("step_finish", """{"reason":"tool-calls","tokens":{"total":7894,"input":6013,"output":89,"reasoning":0,"cache":{"write":0,"read":1792}},"cost":0.01}"""))!! - assertEquals(emptyList(), step.entries) - assertEquals(7894L, step.context) - val end = OpenCode.parse(event("step_finish", """{"reason":"stop","tokens":{"total":7927,"input":241,"output":6,"reasoning":2,"cache":{"write":0,"read":7680}},"cost":0.02}"""))!! - assertEquals(listOf(Entry.Finished(null)), end.entries) - assertEquals(AgentHost.Usage(0, 0.03, 6013L + 1792 + 241 + 7680, 89L + 6 + 2), end.usage!!.copy(costUsd = Math.round(end.usage!!.costUsd * 100) / 100.0)) + @Test fun turnsServeAcpUnderTheChosenRules() { + val command = OpenCode.turn("hi", null, AgentHarness.Options()).dropWhile { it != "/usr/bin/env" } + assertEquals(listOf("/usr/bin/env", OpenCode.binary, "acp"), listOf(command[0]) + command.drop(2)) + val ask = json(command[1].removePrefix("OPENCODE_PERMISSION=")) + assertEquals("ask", ask.getString("edit")) + assertEquals("ask", ask.getString("bash")) + assertFalse(ask.has("*")) + assertEquals("allow", OpenCode.rules(AgentHarness.EDITS).getString("edit")) + assertEquals("ask", OpenCode.rules(AgentHarness.EDITS).getString("bash")) + assertEquals("""{"*":"allow"}""", OpenCode.rules(AgentHarness.FULL).toString()) } - @Test fun eachTurnCountsOnlyItsOwnSteps() { - OpenCode.turn("one", null, AgentHarness.Options()) - OpenCode.parse(event("step_finish", """{"reason":"stop","tokens":{"input":100,"output":10,"cache":{}},"cost":1}""")) - OpenCode.turn("two", session, AgentHarness.Options()) - val end = OpenCode.parse(event("step_finish", """{"reason":"stop","tokens":{"input":5,"output":1,"cache":{}},"cost":0}"""))!! - assertEquals(AgentHost.Usage(0, 0.0, 5, 1), end.usage) + @Test fun aNewProcessOpensItsSessionAndSetsModelModeAndEffortBeforeThePrompt() { + val p = OpenCode.Protocol() + val init = json(p.input("hi", null, AgentHarness.Options(model = "opencode/big-pickle", effort = "high", brief = "brief", workdir = "/root/DroidDeck"), started = true).single()) + assertEquals("initialize", init.getString("method")) + val new = json(p.parse("""{"jsonrpc":"2.0","id":${init.getInt("id")},"result":{"protocolVersion":1}}""")!!.reply.single()) + assertEquals("session/new", new.getString("method")) + assertEquals("/root/DroidDeck", new.getJSONObject("params").getString("cwd")) + val created = p.parse("""{"jsonrpc":"2.0","id":${new.getInt("id")},"result":{"sessionId":"$session","configOptions":[]}}""")!! + assertEquals(session, created.conversation) + val sent = mutableListOf() + var line = created.reply.single() + while (true) { + val request = json(line) + sent += request + if (request.getString("method") == "session/prompt") break + // A refused effort, one the model does not have, does not stop the turn. + val refused = request.getJSONObject("params").getString("configId") == "effort" + val answer = if (refused) """"error":{"code":-32602,"message":"no"}""" else """"result":{}""" + line = p.parse("""{"jsonrpc":"2.0","id":${request.getInt("id")},$answer}""")!!.reply.single() + } + assertEquals(listOf("model" to "opencode/big-pickle", "effort" to "high", "mode" to "build"), + sent.dropLast(1).map { it.getJSONObject("params").let { o -> o.getString("configId") to o.getString("value") } }) + assertEquals("brief\n\nhi", sent.last().getJSONObject("params").getJSONArray("prompt").getJSONObject(0).getString("text")) + val again = json(p.input("two", session, AgentHarness.Options(brief = "brief"), started = false).single()) + assertEquals("session/prompt", again.getString("method")) + assertEquals("two", again.getJSONObject("params").getJSONArray("prompt").getJSONObject(0).getString("text")) } - @Test fun toolsBecomeCallsWithTheirResults() { - val bash = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"bash","callID":"c1","state":{"status":"completed","input":{"command":"uname -m"},"output":"aarch64\n","metadata":{"exit":0}}}"""))!! - assertEquals(listOf(Entry.Used("c1", "Bash", "uname -m", "uname -m"), Entry.Result("c1", "aarch64\n", false)), bash.entries) - val failed = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"bash","callID":"c2","state":{"status":"completed","input":{"command":"false"},"output":"(no output)","metadata":{"exit":1}}}"""))!! - assertTrue((failed.entries[1] as Entry.Result).failed) - val edit = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"edit","callID":"c3","state":{"status":"completed","input":{"filePath":"/w/a.txt","oldString":"hi","newString":"bye"},"output":"Edit applied successfully."}}"""))!! - assertEquals(Entry.Used("c3", "Edit", "/w/a.txt", "/w/a.txt\n-hi\n+bye"), edit.entries[0]) - val write = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"write","callID":"c4","state":{"status":"completed","input":{"filePath":"/w/b.txt","content":"one\n"},"output":"Wrote file successfully."}}"""))!! - assertEquals("/w/b.txt\n+one", (write.entries[0] as Entry.Used).input) - val todo = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"todowrite","callID":"c5","state":{"status":"completed","input":{"todos":[{"content":"A","status":"completed"},{"content":"B","status":"in_progress"},{"content":"C","status":"pending"}]},"output":"[]"}}"""))!! - assertEquals("[x] A\n[~] B\n[ ] C", (todo.entries[0] as Entry.Used).input) - val read = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"read","callID":"c6","state":{"status":"error","input":{"filePath":"/nope"},"error":"File not found"}}"""))!! - assertEquals("Read", (read.entries[0] as Entry.Used).tool) - assertEquals("/nope", (read.entries[0] as Entry.Used).detail) - assertEquals(Entry.Result("c6", "File not found", true), read.entries[1]) - val running = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"bash","callID":"c7","state":{"status":"running","input":{"command":"sleep 9"}}}"""))!! - assertEquals(listOf(Entry.Used("c7", "Bash", "sleep 9", "sleep 9")), running.entries) + @Test fun aResumedSessionPlansWhenAsked() { + val p = OpenCode.Protocol() + val init = json(p.input("hi", "ses_9", AgentHarness.Options(plan = true), started = true).single()) + val resume = json(p.parse("""{"jsonrpc":"2.0","id":${init.getInt("id")},"result":{}}""")!!.reply.single()) + assertEquals("session/resume", resume.getString("method")) + assertEquals("ses_9", resume.getJSONObject("params").getString("sessionId")) + val resumed = p.parse("""{"jsonrpc":"2.0","id":${resume.getInt("id")},"result":{"configOptions":[]}}""")!! + assertEquals("ses_9", resumed.conversation) + val mode = json(resumed.reply.single()) + assertEquals("plan", mode.getJSONObject("params").getString("value")) + assertEquals(listOf(Entry.Finished("Invalid mode")), p.parse("""{"jsonrpc":"2.0","id":${mode.getInt("id")},"error":{"code":-32602,"message":"Invalid mode"}}""")!!.entries) + // The next message on the same process asks for the mode again rather than prompting in whatever mode the session has. + val retry = json(p.input("again", "ses_9", AgentHarness.Options(plan = true), started = false).single()) + assertEquals("session/set_config_option", retry.getString("method")) + assertEquals("plan", retry.getJSONObject("params").getString("value")) + val prompt = json(p.parse("""{"jsonrpc":"2.0","id":${retry.getInt("id")},"result":{}}""")!!.reply.single()) + assertEquals("session/prompt", prompt.getString("method")) + p.parse("""{"jsonrpc":"2.0","id":${prompt.getInt("id")},"result":{"stopReason":"end_turn"}}""") + assertEquals("session/prompt", json(p.input("third", "ses_9", AgentHarness.Options(plan = true), started = false).single()).getString("method")) + val gone = OpenCode.Protocol() + val id = json(gone.input("hi", "ses_x", AgentHarness.Options(), started = true).single()).getInt("id") + val resumeId = json(gone.parse("""{"jsonrpc":"2.0","id":$id,"result":{}}""")!!.reply.single()).getInt("id") + assertEquals(listOf(Entry.Finished("Session not found")), gone.parse("""{"jsonrpc":"2.0","id":$resumeId,"error":{"code":-32603,"message":"Internal error","data":{"message":"Session not found"}}}""")!!.entries) } - @Test fun errorsEndTheTurn() { - assertEquals(listOf(Entry.Finished("Invalid credential")), OpenCode.parse( - """{"type":"error","sessionID":"ses_1","error":{"name":"APIError","data":{"message":"Invalid credential","statusCode":401}}}""")!!.entries) - assertEquals(listOf(Entry.Finished("UnknownError")), OpenCode.parse("""{"type":"error","error":{"name":"UnknownError"}}""")!!.entries) - assertNull(OpenCode.parse("not json")) + @Test fun chunksAndToolCallsBecomeEntries() { + val (p, prompt) = opened() + assertEquals("We need", p.parse(update("""{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"We need"}}"""))!!.thinking) + val pending = p.parse(update("""{"sessionUpdate":"tool_call","toolCallId":"c1","title":"bash","kind":"execute","status":"pending","locations":[],"rawInput":{"cwd":"/work"}}"""))!! + assertEquals(listOf(Entry.Thought("We need"), Entry.Used("c1", "Bash", "", "")), pending.entries) + assertEquals(listOf(Entry.Used("c1", "Bash", "touch /work/probe.txt", "touch /work/probe.txt")), p.parse(update( + """{"sessionUpdate":"tool_call_update","toolCallId":"c1","status":"in_progress","kind":"execute","title":"touch /work/probe.txt","rawInput":{"command":"touch /work/probe.txt","cwd":"/work"}}"""))!!.entries) + assertEquals(listOf(Entry.Used("c1", "Bash", "touch /work/probe.txt", "touch /work/probe.txt"), Entry.Result("c1", "(no output)", false)), p.parse(update( + """{"sessionUpdate":"tool_call_update","toolCallId":"c1","status":"completed","title":"touch /work/probe.txt","content":[{"type":"content","content":{"type":"text","text":"(no output)"}}],"rawOutput":{"output":"(no output)","metadata":{"exit":0}}}"""))!!.entries) + p.parse(update("""{"sessionUpdate":"tool_call","toolCallId":"c2","title":"write","kind":"edit","status":"pending","rawInput":{}}""")) + assertEquals(Entry.Used("c2", "Write", "/work/note.txt", "/work/note.txt\n+hi"), p.parse(update( + """{"sessionUpdate":"tool_call_update","toolCallId":"c2","status":"in_progress","kind":"edit","title":"write","rawInput":{"content":"hi","filePath":"/work/note.txt"}}"""))!!.entries.single()) + assertEquals(Entry.Result("c2", "The user rejected permission to use this specific tool call.", true), p.parse(update( + """{"sessionUpdate":"tool_call_update","toolCallId":"c2","status":"failed","rawOutput":{"error":"The user rejected permission to use this specific tool call."}}"""))!!.entries[1]) + assertEquals("done", p.parse(update("""{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"done"}}"""))!!.text) + val usage = p.parse(update("""{"sessionUpdate":"usage_update","used":7760,"size":200000,"cost":{"amount":0.25,"currency":"USD"}}"""))!! + assertEquals(7760L, usage.context) + assertEquals(200_000L, usage.window) + val end = p.parse("""{"jsonrpc":"2.0","id":$prompt,"result":{"stopReason":"end_turn","usage":{"inputTokens":592,"outputTokens":3,"totalTokens":7763,"cachedReadTokens":7168}}}""")!! + assertEquals(listOf(Entry.Said("done"), Entry.Finished(null)), end.entries) + assertEquals(0.25, end.usage!!.costUsd, 0.0) + assertEquals(592L + 7168, end.usage!!.inputTokens) + assertTrue(OpenCode.sessionCost) + } + + @Test fun permissionRequestsWaitForTheUser() { + val (p, prompt) = opened() + p.parse(update("""{"sessionUpdate":"tool_call","toolCallId":"c1","title":"bash","kind":"execute","status":"pending","rawInput":{}}""")) + val bash = p.parse("""{"jsonrpc":"2.0","id":0,"method":"session/request_permission","params":{"sessionId":"$session","toolCall":{"toolCallId":"c1","title":"touch /w/x","kind":"execute","status":"pending","rawInput":{"command":"touch /w/x"}},"options":[{"optionId":"once","kind":"allow_once","name":"Allow once"},{"optionId":"reject","kind":"reject_once","name":"Reject"}]}}""")!!.approval!! + assertEquals(AgentHost.Approval("0", "Bash", "touch /w/x", "touch /w/x", """{"id":0}"""), bash) + val outside = p.parse("""{"jsonrpc":"2.0","id":5,"method":"session/request_permission","params":{"sessionId":"$session","toolCall":{"toolCallId":"c1","title":"touch /root/x","kind":"other","rawInput":{"command":"touch /root/x","parentDir":"/root"}}}}""")!!.approval!! + assertEquals("External directory", outside.tool) + assertEquals("/root", outside.detail) + val allow = json(p.answer(bash, allow = true)) + assertEquals(0, allow.getInt("id")) + assertEquals("once", allow.getJSONObject("result").getJSONObject("outcome").getString("optionId")) + assertEquals("reject", json(p.answer(bash, allow = false)).getJSONObject("result").getJSONObject("outcome").getString("optionId")) + val edit = p.parse("""{"jsonrpc":"2.0","id":1,"method":"session/request_permission","params":{"sessionId":"$session","toolCall":{"toolCallId":"c2","title":"/w/a.txt","kind":"edit","rawInput":{"filepath":"/w/a.txt","diff":"Index: /w/a.txt\n===\n--- /w/a.txt\n+++ /w/a.txt\n@@ -1,1 +1,1 @@\n-old\n+new\n"}}}}""")!!.approval!! + assertEquals("Edit", edit.tool) + assertEquals("/w/a.txt\n-old\n+new", edit.input) + val write = json(p.parse("""{"jsonrpc":"2.0","id":2,"method":"fs/write_text_file","params":{"sessionId":"$session","path":"/w/a.txt","content":"new"}}""")!!.reply.single()) + assertEquals(2, write.getInt("id")) + assertTrue(write.has("error")) + assertEquals(listOf(Entry.Finished("Invalid credential")), p.parse( + """{"jsonrpc":"2.0","id":$prompt,"error":{"code":-32603,"message":"Internal error","data":{"message":"Invalid credential"}}}""")!!.entries) + assertNull(p.parse("not json")) } @Test fun verboseModelListingGivesLabelsAndWindows() { @@ -108,16 +180,12 @@ class OpenCodeTest { assertEquals(mapOf("opencode/big-pickle" to 200000L, "opencode-go/kimi-k3" to 262144L), windows) } - @Test fun modelsAndWindowComeFromTheCachedListing() { + @Test fun modelsComeFromTheCachedListing() { val root = Files.createTempDirectory("rootfs").toFile() assertEquals(emptyList(), OpenCode.models(root)) File(root, "root/.cache/droiddeck/opencode-models").apply { parentFile!!.mkdirs() } .writeText("opencode/big-pickle\n{\n \"providerID\": \"opencode\",\n \"name\": \"Big Pickle\",\n \"limit\": {\"context\": 200000}\n}\n") assertEquals(listOf(AgentHarness.Model("opencode/big-pickle", "Big Pickle")), OpenCode.models(root)) - OpenCode.turn("hi", null, AgentHarness.Options(model = "opencode/big-pickle")) - assertEquals(200000L, OpenCode.usage(root, session)!!.window) - OpenCode.turn("hi", null, AgentHarness.Options()) - assertNull(OpenCode.usage(root, session)) } private fun provider(id: String) = OpenCode.providers.first { it.id == id } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt index 15888d289f..58b8ba055b 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -5,7 +5,7 @@ import org.junit.Test class SessionDrawerPageTest { @Test fun singleScreenNavigationStartsWithControllerAndSkipsSecondScreen() { - val pages = sessionDrawerPages(false) + val pages = sessionDrawerPages(false, hasAgent = false) assertEquals(SessionDrawerPage.CONTROLLER, pages.first()) assertFalse(SessionDrawerPage.SECOND_SCREEN in pages) assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1)) @@ -14,11 +14,11 @@ class SessionDrawerPageTest { } @Test fun connectedSecondaryDisplayAddsItsPageAfterControllerAndPreservesOtherPages() { - val connected = sessionDrawerPages(true) + val connected = sessionDrawerPages(true, hasAgent = false) assertEquals(SessionDrawerPage.SECOND_SCREEN, connected.step(SessionDrawerPage.CONTROLLER, 1)) assertEquals(SessionDrawerPage.DISPLAY, connected.step(SessionDrawerPage.SECOND_SCREEN, 1)) - assertEquals(sessionDrawerPages(false), connected.filter { it != SessionDrawerPage.SECOND_SCREEN }) - for (pages in listOf(connected, sessionDrawerPages(false))) { + assertEquals(sessionDrawerPages(false, hasAgent = false), connected.filter { it != SessionDrawerPage.SECOND_SCREEN }) + for (pages in listOf(connected, sessionDrawerPages(false, hasAgent = false))) { assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1)) assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1)) assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1)) @@ -27,7 +27,7 @@ class SessionDrawerPageTest { } } - @Test fun theAgentPageComesBeforeSessionOnlyWhenTheAgentIsInstalled() { + @Test fun theAgentPageComesBeforeSessionOnlyWhenTheTabIsShown() { val with = sessionDrawerPages(false, hasAgent = true) assertEquals(SessionDrawerPage.AGENT, with.step(SessionDrawerPage.GAMES, 1)) assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1))