mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 22:05:59 +00:00
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:
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")),
|
||||
|
||||
Reference in new issue
Block a user