feat(agent): OpenCode as a third agent, with free Zen models or a pasted Zen key (#2711)

* feat(agent): OpenCode as a third agent, with free Zen models or a pasted Zen key

* fix(agent): OpenCode's key check reads only its own entry and never overwrites an unreadable auth.json
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-16 14:33:22 -05:00
1 parent f0557302ac
commit 25cbcf0c1f
7 files changed
+423 -13

No files matched your search

@@ -19,6 +19,17 @@ interface AgentHarness {
val signedIn: List<String>
/** A guest command that signs in through $BROWSER. */
val signIn: List<String>
/**
* Where the user makes an API key, for a CLI whose own sign-in is a terminal prompt: [signIn]
* then only opens this page, and the key is pasted into DroidDeck and saved by [saveKey].
*/
val keyPage: String? get() = null
/** Whether a key from [keyPage] is saved under [rootfs]. */
fun hasKey(rootfs: File): Boolean = false
fun saveKey(rootfs: File, key: String) {}
/** Whether the CLI has models that need no account; [useFree] then counts as signed in. */
val free: Boolean get() = false
fun useFree(rootfs: File) {}
/** Whether [Options.plan] means anything to this CLI. */
val plans: Boolean
/** Reasoning effort levels the CLI accepts, lowest first; empty when it has none. */
@@ -49,7 +60,7 @@ interface AgentHarness {
data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null)
companion object {
val all: List<AgentHarness> = listOf(ClaudeCode, Codex)
val all: List<AgentHarness> = listOf(ClaudeCode, Codex, OpenCode)
fun byId(id: String?): AgentHarness = all.firstOrNull { it.id == id } ?: ClaudeCode
}
}
@@ -392,6 +403,184 @@ object Codex : AgentHarness {
}
}
/** OpenCode: `opencode run --format json`, resumed by session id. */
object OpenCode : AgentHarness {
override val id = "opencode"
override val name = "OpenCode"
override val binary = "/root/.opencode/bin/opencode"
override val skills = "root/.config/opencode/skills"
override val instructions = "root/.config/opencode/AGENTS.md"
override val install = "curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path"
private const val AUTH = "root/.local/share/opencode/auth.json"
private const val FREE = "root/.config/opencode/.droiddeck-free"
private const val MODELS = "root/.cache/droiddeck/opencode-models"
// `opencode models` lists only what the saved keys reach, so the check that runs it keeps the model list current.
override val signedIn = listOf("sh", "-c",
"mkdir -p /${MODELS.substringBeforeLast('/')}; $binary models --verbose > /$MODELS.$$ 2>/dev/null && mv -f /$MODELS.$$ /$MODELS; rm -f /$MODELS.$$; " +
"grep -q '\"type\"' /$AUTH 2>/dev/null || [ -e /$FREE ]")
override val keyPage = "https://opencode.ai/auth"
override val signIn = listOf("/root/.local/bin/android-open", keyPage)
override val free = true
override val plans = true
override val efforts = listOf("low", "medium", "high")
override fun hasKey(rootfs: File) = runCatching { JSONObject(File(rootfs, AUTH).readText()).has("opencode") }.getOrDefault(false)
/** The key opencode's own `auth login` would save for OpenCode Zen. */
override fun saveKey(rootfs: File, key: String) {
val file = File(rootfs, AUTH)
// An auth.json that cannot be read holds other providers' sign-ins too, so it is never replaced.
val auth = if (file.exists()) JSONObject(file.readText()) else JSONObject()
auth.put("opencode", JSONObject().put("type", "api").put("key", key.trim()))
file.parentFile?.mkdirs()
file.writeText(auth.toString(2) + "\n")
file.setReadable(false, false)
file.setReadable(true, true)
}
override fun useFree(rootfs: File) {
File(rootfs, FREE).apply { parentFile?.mkdirs() }.writeText("Free OpenCode Zen models, chosen in DroidDeck's agent setup.\n")
}
private class Listed(val modified: Long, val models: List<AgentHarness.Model>, val windows: Map<String, Long>)
@Volatile private var listed: Listed? = null
private fun listed(rootfs: File): Listed? {
val file = File(rootfs, MODELS)
val modified = file.lastModified().takeIf { it > 0 } ?: return null
listed?.takeIf { it.modified == modified }?.let { return it }
return runCatching { listModels(file.readText()) }.getOrNull()?.let { (models, windows) -> Listed(modified, models, windows) }?.also { listed = it }
}
override fun models(rootfs: File) = listed(rootfs)?.models.orEmpty()
/** `opencode models --verbose` prints each model's id on a line of its own, then its details as JSON. */
@VisibleForTesting
internal fun listModels(output: String): Pair<List<AgentHarness.Model>, Map<String, Long>> {
val models = mutableListOf<AgentHarness.Model>()
val windows = mutableMapOf<String, Long>()
var id: String? = null
val json = StringBuilder()
for (line in output.lineSequence()) {
val current = id
if (current == null) {
if (MODEL_ID.matches(line)) id = line.trim()
continue
}
json.appendLine(line)
if (line != "}") continue
runCatching { JSONObject(json.toString()) }.getOrNull()?.takeIf { it.optString("status") != "deprecated" }?.let { o ->
val provider = o.optString("providerID")
val label = o.optString("name").ifEmpty { current }
models += AgentHarness.Model(current, if (provider.isEmpty() || provider == "opencode") label else "$label · $provider")
o.optJSONObject("limit")?.optLong("context")?.takeIf { it > 0 }?.let { windows[current] = it }
}
id = null
json.clear()
}
return models to windows
}
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 fun turn(message: String, conversation: String?, options: AgentHarness.Options): List<String> {
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)
}
}
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 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)
}
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)
}
"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)))
}
else -> conversation?.let { AgentEvent(it) }
}
}
private fun text(part: JSONObject?, entry: (String) -> AgentHost.Entry) =
part?.optString("text")?.trim()?.takeIf { it.isNotEmpty() }?.let { listOf(entry(it)) }.orEmpty()
private fun tool(part: JSONObject): List<AgentHost.Entry> {
val id = part.optString("callID").ifEmpty { part.optString("id") }
val state = part.optJSONObject("state") ?: JSONObject()
val input = state.optJSONObject("input") ?: JSONObject()
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)
}
}
private fun detail(input: JSONObject): String {
for (key in listOf("filePath", "path", "pattern", "url", "query", "description", "prompt", "command")) {
input.optString(key).takeIf { it.isNotEmpty() }?.let { return firstLine(it) }
}
return ""
}
private fun todos(list: JSONArray?) = (0 until (list?.length() ?: 0)).mapNotNull { i ->
val todo = list?.optJSONObject(i) ?: return@mapNotNull null
val mark = when (todo.optString("status")) { "completed" -> "[x]"; "in_progress" -> "[~]"; else -> "[ ]" }
"$mark ${todo.optString("content")}"
}.joinToString("\n")
}
@VisibleForTesting
internal fun firstLine(text: String) = text.lineSequence().first().take(160)
@@ -27,6 +27,28 @@ object AgentSetup {
val detail = mutableStateMapOf<Step, String>()
var runtimeInstalled by mutableStateOf(true)
private set
/** The harness has a key from its [AgentHarness.keyPage] saved; signed in without one means its free models. */
var keySaved by mutableStateOf(false)
private set
/** Saves a pasted key for a harness that signs in with one, then checks the sign-in again. */
fun saveKey(context: Context, key: String) = signInLocally(context) { harness, root -> harness.saveKey(root, key) }
fun useFree(context: Context) = signInLocally(context) { harness, root -> harness.useFree(root) }
private fun signInLocally(context: Context, write: (AgentHarness, File) -> Unit) {
val app = context.applicationContext
val harness = AgentHost.harness
set(Step.SIGN_IN, Status.WORKING)
Thread({
val result = runCatching { write(harness, LinuxRuntime.rootDir(app)) }
main.post {
status[Step.SIGN_IN] = Status.UNKNOWN
result.exceptionOrNull()?.let { detail[Step.SIGN_IN] = it.message ?: "failed" }
check(app)
}
}, "agent-sign-in").start()
}
val ready: Boolean get() = Step.entries.filter { it.required }.all { status[it] == Status.DONE }
@@ -53,6 +75,7 @@ object AgentSetup {
if (!runtimeInstalled) return
AgentHost.refresh(app)
val harness = AgentHost.harness
keySaved = harness.hasKey(LinuxRuntime.rootDir(app))
val probes = mutableListOf<Pair<Step, List<String>>>()
for (step in Step.entries) if (status[step] != Status.WORKING) {
when (step) {
@@ -16,13 +16,14 @@ import java.nio.file.attribute.BasicFileAttributes
/**
* What the agent adds to the Linux userland, measured and removable piece by piece. Sign-ins
* (~/.claude, ~/.codex, gh's config) are left alone, so removing a CLI and installing it again
* does not sign out.
* (~/.claude, ~/.codex, ~/.local/share/opencode, gh's config) are left alone, so removing a CLI
* and installing it again does not sign out.
*/
object AgentStorage {
enum class Item(val paths: List<String>) {
CLAUDE_CODE(listOf("/root/.local/share/claude", "/root/.local/bin/claude", "/root/cc")),
CODEX(listOf("/root/.local/bin/codex", "/root/.local/bin/codex-code-mode-host")),
OPENCODE(listOf("/root/.opencode")),
BUILD_TOOLS(listOf("/root/android-sdk", "/root/aapt2", "/root/x86root", "/root/.gradle")),
SOURCE(listOf("/root/DroidDeck")),
CACHES(listOf("/root/.cache", "/root/.npm")),
@@ -416,7 +416,7 @@ private fun ToolsRow(title: String, detail: String, action: @Composable () -> Un
}
@Composable
private fun ToolsField(value: String, onValue: (String) -> Unit, hint: String, tag: String) {
internal fun ToolsField(value: String, onValue: (String) -> Unit, hint: String, tag: String) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Box(Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 12.dp, vertical = 10.dp)) {
@@ -96,27 +96,61 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) {
) {
steps.forEachIndexed { index, step ->
val status = AgentSetup.status[step] ?: Status.UNKNOWN
val (title, hint) = labels(step, AgentHost.harness.name)
val harness = AgentHost.harness
// A harness that signs in with a pasted key: the sign-in opens its key page and this field takes the key.
val keyed = step == Step.SIGN_IN && harness.keyPage != null
var keyOpen by rememberSaveable(harness.id) { mutableStateOf(false) }
val (title, hint) = labels(step, harness.name, keyed)
val lab = AgentHost.lab?.takeIf { it.prepare && it.running }
val detail = if (step == Step.PREPARE && lab != null)
stringResource(R.string.agent_prepare_progress, lab.permille / 10, clock(lab.etaSeconds.toLong().coerceAtLeast(0)))
else AgentSetup.detail[step] ?: hint
val detail = when {
step == Step.PREPARE && lab != null ->
stringResource(R.string.agent_prepare_progress, lab.permille / 10, clock(lab.etaSeconds.toLong().coerceAtLeast(0)))
keyed && status == Status.DONE && !AgentSetup.keySaved -> stringResource(R.string.agent_step_free_models)
else -> AgentSetup.detail[step] ?: hint
}
// Shown while the sign-in is pending, so it is still there after a trip to the browser for the key.
val pending = (status == Status.TODO || status == Status.FAILED) && AgentSetup.status[Step.INSTALL] == Status.DONE
val showKey = keyed && (keyOpen || pending) && status != Status.WORKING
var key by remember(harness.id) { mutableStateOf("") }
CheckRow(
when (status) {
Status.DONE -> CheckState.OK
Status.WORKING, Status.UNKNOWN -> CheckState.BUSY
Status.TODO, Status.FAILED -> CheckState.WARN
},
title, detail, divider = index < steps.lastIndex,
title, detail, divider = index < steps.lastIndex && !showKey,
) {
val blocked = (step in setOf(Step.SIGN_IN, Step.GITHUB, Step.BUILD_TOOLS) && AgentSetup.status[Step.INSTALL] != Status.DONE) ||
(step == Step.PREPARE && AgentSetup.status[Step.BUILD_TOOLS] != Status.DONE)
val openKey = {
keyOpen = true
AgentSetup.run(context, step)
}
if ((status == Status.TODO || status == Status.FAILED) && !blocked) {
val label = stringResource(if (status == Status.FAILED) R.string.agent_setup_retry else action(step))
val run = { if (step == Step.CONNECTION) pair(context) else AgentSetup.run(context, step) }
if (step.required) PrimaryButton(label, compact = true, onClick = run) else SecondaryButton(label, compact = true, onClick = run)
val run = { if (step == Step.CONNECTION) pair(context) else if (keyed) openKey() else AgentSetup.run(context, step) }
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (keyed && harness.free) SecondaryButton(stringResource(R.string.agent_action_free), compact = true) { AgentSetup.useFree(context) }
if (step.required) PrimaryButton(label, compact = true, onClick = run) else SecondaryButton(label, compact = true, onClick = run)
}
} else if (keyed && status == Status.DONE && !AgentSetup.keySaved && !keyOpen) {
SecondaryButton(stringResource(R.string.agent_action_add_key), compact = true, onClick = openKey)
}
}
if (showKey) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, bottom = 10.dp),
) {
Box(Modifier.weight(1f)) { ToolsField(key, { key = it.trim() }, stringResource(R.string.agent_key_hint), "agent-key") }
PrimaryButton(stringResource(R.string.agent_key_save), enabled = key.isNotBlank(), compact = true) {
keyOpen = false
AgentSetup.saveKey(context, key)
key = ""
}
}
if (index < steps.lastIndex) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
}
}
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp)) {
@@ -183,6 +217,7 @@ private fun StorageCard() {
private fun storageTitle(item: AgentStorage.Item) = when (item) {
AgentStorage.Item.CLAUDE_CODE -> R.string.agent_storage_claude
AgentStorage.Item.CODEX -> R.string.agent_storage_codex
AgentStorage.Item.OPENCODE -> R.string.agent_storage_opencode
AgentStorage.Item.BUILD_TOOLS -> R.string.agent_step_build
AgentStorage.Item.SOURCE -> R.string.agent_storage_source
AgentStorage.Item.CACHES -> R.string.agent_storage_caches
@@ -195,10 +230,10 @@ private fun storageWarning(item: AgentStorage.Item) = when (item) {
}
@Composable
private fun labels(step: Step, harness: String): Pair<String, String> = when (step) {
private fun labels(step: Step, harness: String, keyed: Boolean = false): Pair<String, String> = when (step) {
Step.CONNECTION -> stringResource(R.string.agent_step_connection) to stringResource(R.string.agent_step_connection_hint)
Step.INSTALL -> stringResource(R.string.agent_step_install, harness) to stringResource(R.string.agent_step_install_hint)
Step.SIGN_IN -> stringResource(R.string.agent_step_sign_in, harness) to stringResource(R.string.agent_step_sign_in_hint)
Step.SIGN_IN -> stringResource(R.string.agent_step_sign_in, harness) to stringResource(if (keyed) R.string.agent_step_sign_in_key_hint else R.string.agent_step_sign_in_hint)
Step.GITHUB -> stringResource(R.string.agent_step_github) to stringResource(R.string.agent_step_github_hint)
Step.BUILD_TOOLS -> stringResource(R.string.agent_step_build) to stringResource(R.string.agent_step_build_hint)
Step.PREPARE -> stringResource(R.string.agent_step_prepare) to stringResource(R.string.agent_step_prepare_hint)