mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 12:56:06 +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>
|
val signedIn: List<String>
|
||||||
/** A guest command that signs in through $BROWSER. */
|
/** A guest command that signs in through $BROWSER. */
|
||||||
val signIn: List<String>
|
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. */
|
/** Whether [Options.plan] means anything to this CLI. */
|
||||||
val plans: Boolean
|
val plans: Boolean
|
||||||
/** Reasoning effort levels the CLI accepts, lowest first; empty when it has none. */
|
/** 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)
|
data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null)
|
||||||
|
|
||||||
companion object {
|
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
|
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
|
@VisibleForTesting
|
||||||
internal fun firstLine(text: String) = text.lineSequence().first().take(160)
|
internal fun firstLine(text: String) = text.lineSequence().first().take(160)
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,28 @@ object AgentSetup {
|
|||||||
val detail = mutableStateMapOf<Step, String>()
|
val detail = mutableStateMapOf<Step, String>()
|
||||||
var runtimeInstalled by mutableStateOf(true)
|
var runtimeInstalled by mutableStateOf(true)
|
||||||
private set
|
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 }
|
val ready: Boolean get() = Step.entries.filter { it.required }.all { status[it] == Status.DONE }
|
||||||
|
|
||||||
@@ -53,6 +75,7 @@ object AgentSetup {
|
|||||||
if (!runtimeInstalled) return
|
if (!runtimeInstalled) return
|
||||||
AgentHost.refresh(app)
|
AgentHost.refresh(app)
|
||||||
val harness = AgentHost.harness
|
val harness = AgentHost.harness
|
||||||
|
keySaved = harness.hasKey(LinuxRuntime.rootDir(app))
|
||||||
val probes = mutableListOf<Pair<Step, List<String>>>()
|
val probes = mutableListOf<Pair<Step, List<String>>>()
|
||||||
for (step in Step.entries) if (status[step] != Status.WORKING) {
|
for (step in Step.entries) if (status[step] != Status.WORKING) {
|
||||||
when (step) {
|
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
|
* 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
|
* (~/.claude, ~/.codex, ~/.local/share/opencode, gh's config) are left alone, so removing a CLI
|
||||||
* does not sign out.
|
* and installing it again does not sign out.
|
||||||
*/
|
*/
|
||||||
object AgentStorage {
|
object AgentStorage {
|
||||||
enum class Item(val paths: List<String>) {
|
enum class Item(val paths: List<String>) {
|
||||||
CLAUDE_CODE(listOf("/root/.local/share/claude", "/root/.local/bin/claude", "/root/cc")),
|
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")),
|
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")),
|
BUILD_TOOLS(listOf("/root/android-sdk", "/root/aapt2", "/root/x86root", "/root/.gradle")),
|
||||||
SOURCE(listOf("/root/DroidDeck")),
|
SOURCE(listOf("/root/DroidDeck")),
|
||||||
CACHES(listOf("/root/.cache", "/root/.npm")),
|
CACHES(listOf("/root/.cache", "/root/.npm")),
|
||||||
|
|||||||
@@ -416,7 +416,7 @@ private fun ToolsRow(title: String, detail: String, action: @Composable () -> Un
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@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 colors = MaterialTheme.colorScheme
|
||||||
val pal = LocalPalette.current
|
val pal = LocalPalette.current
|
||||||
Box(Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 12.dp, vertical = 10.dp)) {
|
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 ->
|
steps.forEachIndexed { index, step ->
|
||||||
val status = AgentSetup.status[step] ?: Status.UNKNOWN
|
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 lab = AgentHost.lab?.takeIf { it.prepare && it.running }
|
||||||
val detail = if (step == Step.PREPARE && lab != null)
|
val detail = when {
|
||||||
stringResource(R.string.agent_prepare_progress, lab.permille / 10, clock(lab.etaSeconds.toLong().coerceAtLeast(0)))
|
step == Step.PREPARE && lab != null ->
|
||||||
else AgentSetup.detail[step] ?: hint
|
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(
|
CheckRow(
|
||||||
when (status) {
|
when (status) {
|
||||||
Status.DONE -> CheckState.OK
|
Status.DONE -> CheckState.OK
|
||||||
Status.WORKING, Status.UNKNOWN -> CheckState.BUSY
|
Status.WORKING, Status.UNKNOWN -> CheckState.BUSY
|
||||||
Status.TODO, Status.FAILED -> CheckState.WARN
|
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) ||
|
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)
|
(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) {
|
if ((status == Status.TODO || status == Status.FAILED) && !blocked) {
|
||||||
val label = stringResource(if (status == Status.FAILED) R.string.agent_setup_retry else action(step))
|
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) }
|
val run = { if (step == Step.CONNECTION) pair(context) else if (keyed) openKey() else AgentSetup.run(context, step) }
|
||||||
if (step.required) PrimaryButton(label, compact = true, onClick = run) else SecondaryButton(label, compact = true, onClick = run)
|
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)) {
|
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) {
|
private fun storageTitle(item: AgentStorage.Item) = when (item) {
|
||||||
AgentStorage.Item.CLAUDE_CODE -> R.string.agent_storage_claude
|
AgentStorage.Item.CLAUDE_CODE -> R.string.agent_storage_claude
|
||||||
AgentStorage.Item.CODEX -> R.string.agent_storage_codex
|
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.BUILD_TOOLS -> R.string.agent_step_build
|
||||||
AgentStorage.Item.SOURCE -> R.string.agent_storage_source
|
AgentStorage.Item.SOURCE -> R.string.agent_storage_source
|
||||||
AgentStorage.Item.CACHES -> R.string.agent_storage_caches
|
AgentStorage.Item.CACHES -> R.string.agent_storage_caches
|
||||||
@@ -195,10 +230,10 @@ private fun storageWarning(item: AgentStorage.Item) = when (item) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@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.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.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.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.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)
|
Step.PREPARE -> stringResource(R.string.agent_step_prepare) to stringResource(R.string.agent_step_prepare_hint)
|
||||||
|
|||||||
@@ -1258,6 +1258,7 @@
|
|||||||
<string name="agent_storage_confirm">Remove now</string>
|
<string name="agent_storage_confirm">Remove now</string>
|
||||||
<string name="agent_storage_claude">Claude Code</string>
|
<string name="agent_storage_claude">Claude Code</string>
|
||||||
<string name="agent_storage_codex">Codex</string>
|
<string name="agent_storage_codex">Codex</string>
|
||||||
|
<string name="agent_storage_opencode">OpenCode</string>
|
||||||
<string name="agent_storage_source">DroidDeck source</string>
|
<string name="agent_storage_source">DroidDeck source</string>
|
||||||
<string name="agent_storage_caches">Download caches</string>
|
<string name="agent_storage_caches">Download caches</string>
|
||||||
<string name="agent_storage_source_warning">Changes that are not pushed are lost</string>
|
<string name="agent_storage_source_warning">Changes that are not pushed are lost</string>
|
||||||
@@ -1364,6 +1365,12 @@
|
|||||||
<string name="agent_action_pair">Pair</string>
|
<string name="agent_action_pair">Pair</string>
|
||||||
<string name="agent_action_install">Install</string>
|
<string name="agent_action_install">Install</string>
|
||||||
<string name="agent_action_sign_in">Sign in</string>
|
<string name="agent_action_sign_in">Sign in</string>
|
||||||
|
<string name="agent_action_free">Free models</string>
|
||||||
|
<string name="agent_action_add_key">Add key</string>
|
||||||
|
<string name="agent_key_hint">Paste your API key from opencode.ai/auth</string>
|
||||||
|
<string name="agent_key_save">Save</string>
|
||||||
|
<string name="agent_step_sign_in_key_hint">Free models, or a Zen key from opencode.ai/auth</string>
|
||||||
|
<string name="agent_step_free_models">Free models · add a Zen key for the rest</string>
|
||||||
<string name="upd_pr">PR #%1$d</string>
|
<string name="upd_pr">PR #%1$d</string>
|
||||||
<string name="upd_not_built">Not built for this copy of DroidDeck</string>
|
<string name="upd_not_built">Not built for this copy of DroidDeck</string>
|
||||||
<string name="upd_updated">Updated %1$s</string>
|
<string name="upd_updated">Updated %1$s</string>
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
package com.droiddeck.launcher.agent
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.agent.AgentHost.Entry
|
||||||
|
import org.json.JSONObject
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import java.io.File
|
||||||
|
import java.nio.file.Files
|
||||||
|
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [28], manifest = Config.NONE)
|
||||||
|
class OpenCodeTest {
|
||||||
|
private val session = "ses_1"
|
||||||
|
|
||||||
|
private fun event(type: String, part: String) = """{"type":"$type","timestamp":1,"sessionID":"$session","part":$part}"""
|
||||||
|
|
||||||
|
@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")))
|
||||||
|
}
|
||||||
|
|
||||||
|
@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<Entry>(), 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 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 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 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 verboseModelListingGivesLabelsAndWindows() {
|
||||||
|
val output = """
|
||||||
|
opencode/big-pickle
|
||||||
|
{
|
||||||
|
"id": "big-pickle",
|
||||||
|
"providerID": "opencode",
|
||||||
|
"name": "Big Pickle",
|
||||||
|
"status": "active",
|
||||||
|
"limit": {
|
||||||
|
"context": 200000,
|
||||||
|
"output": 128000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
opencode/old-free
|
||||||
|
{
|
||||||
|
"providerID": "opencode",
|
||||||
|
"name": "Old",
|
||||||
|
"status": "deprecated"
|
||||||
|
}
|
||||||
|
opencode-go/kimi-k3
|
||||||
|
{
|
||||||
|
"providerID": "opencode-go",
|
||||||
|
"name": "Kimi K3",
|
||||||
|
"limit": {
|
||||||
|
"context": 262144
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
val (models, windows) = OpenCode.listModels(output)
|
||||||
|
assertEquals(listOf(AgentHarness.Model("opencode/big-pickle", "Big Pickle"), AgentHarness.Model("opencode-go/kimi-k3", "Kimi K3 · opencode-go")), models)
|
||||||
|
assertEquals(mapOf("opencode/big-pickle" to 200000L, "opencode-go/kimi-k3" to 262144L), windows)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun modelsAndWindowComeFromTheCachedListing() {
|
||||||
|
val root = Files.createTempDirectory("rootfs").toFile()
|
||||||
|
assertEquals(emptyList<AgentHarness.Model>(), 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))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun aSavedKeyKeepsOtherProvidersAndFreeIsItsOwnMark() {
|
||||||
|
val root = Files.createTempDirectory("rootfs").toFile()
|
||||||
|
assertFalse(OpenCode.hasKey(root))
|
||||||
|
val auth = File(root, "root/.local/share/opencode/auth.json").apply { parentFile!!.mkdirs() }
|
||||||
|
auth.writeText("""{"openai":{"type":"oauth","refresh":"r"}}""")
|
||||||
|
assertFalse(OpenCode.hasKey(root))
|
||||||
|
OpenCode.saveKey(root, " sk-zen \n")
|
||||||
|
val saved = JSONObject(auth.readText())
|
||||||
|
assertEquals("r", saved.getJSONObject("openai").getString("refresh"))
|
||||||
|
assertEquals("sk-zen", saved.getJSONObject("opencode").getString("key"))
|
||||||
|
assertEquals("api", saved.getJSONObject("opencode").getString("type"))
|
||||||
|
assertTrue(OpenCode.hasKey(root))
|
||||||
|
OpenCode.useFree(root)
|
||||||
|
assertTrue(File(root, "root/.config/opencode/.droiddeck-free").exists())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun anUnreadableAuthFileIsNotReplaced() {
|
||||||
|
val root = Files.createTempDirectory("rootfs").toFile()
|
||||||
|
val auth = File(root, "root/.local/share/opencode/auth.json").apply { parentFile!!.mkdirs() }
|
||||||
|
auth.writeText("{not json")
|
||||||
|
assertTrue(runCatching { OpenCode.saveKey(root, "sk-zen") }.isFailure)
|
||||||
|
assertEquals("{not json", auth.readText())
|
||||||
|
assertFalse(OpenCode.hasKey(root))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun signInIsTheKeyOrTheFreeMark() {
|
||||||
|
val probe = OpenCode.signedIn.last()
|
||||||
|
assertTrue(probe.contains("/root/.local/share/opencode/auth.json"))
|
||||||
|
assertTrue(probe.contains("[ -e /root/.config/opencode/.droiddeck-free ]"))
|
||||||
|
assertTrue(probe.contains("models --verbose > /root/.cache/droiddeck/opencode-models.$$"))
|
||||||
|
assertEquals(listOf("/root/.local/bin/android-open", "https://opencode.ai/auth"), OpenCode.signIn)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user