Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(host): add WorkBuddy as an agent (#215)
ForwardXuc75eac1da9dc
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.mdindex c8caf019..38db4f65 100644--- a/apps/android/WhatsNew.md+++ b/apps/android/WhatsNew.md@@ -13,15 +13,15 @@ else a generic "Bug fixes and improvements" line. Delete old sections.- Bot 傳來的圖片會直接顯示在聊天裡,點一下可以放大看,不用先下載。- 電腦上的 Codync 版本太舊時,更新提示多了「Update now」按鈕,直接從手機叫那台電腦更新。- 擴充套件一次顯示一個分類:智慧體、聯結器或技能,每個列表都分頁。點列表兩側的圓形按鈕或左右滑動翻頁,每頁可選 6、10、20 或 50 筆。-- 「憑證」移到上方電腦名稱旁;「自定義聯結器」和「自己的技能」放在各自列表上方。- 電腦使用自建中繼時,設定和連線狀態會顯示該中繼的地址,不再一律寫成 Cloudflare。+- 可以建立使用 WorkBuddy 的 Bot,在聊天裡登入即可。### en-US- Images a bot sends now show right in the chat; tap one to see it full size, no download needed.- When a computer's Codync is too old for this app, Update now on the notice updates that computer from your phone.- Extensions shows Agents, Connectors or Skills in pages: tap the round buttons or swipe, 6 to 50 per page.-- Credentials sits beside the computer's name; Custom connector and Your own skill top their lists.- A private relay shows its address in Settings and status.+- Bots can run WorkBuddy; sign in from the chat.## 2.26.0diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AgentIcons.kt b/apps/android/app/src/main/kotlin/com/codync/android/AgentIcons.ktindex 7f8f45bb..6cc27408 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AgentIcons.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AgentIcons.kt@@ -37,5 +37,6 @@ import androidx.annotation.DrawableRes"qoder" -> R.drawable.agent_qoder"qwen-code" -> R.drawable.agent_qwen_code"stakpak" -> R.drawable.agent_stakpak+ "workbuddy" -> R.drawable.agent_workbuddyelse -> null}diff --git a/apps/android/app/src/main/res/drawable/agent_workbuddy.xml b/apps/android/app/src/main/res/drawable/agent_workbuddy.xmlnew file mode 100644index 00000000..93d5a99c--- /dev/null+++ b/apps/android/app/src/main/res/drawable/agent_workbuddy.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- workbuddy.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">+ <group android:translateX="0" android:translateY="0">+ <path android:pathData="M3.15 1.5h8.15c1.16 0 2.10.94 2.1 2.1v6.15c0 1.16-0.94 2.1-2.1 2.1H8.15L5.35 14.7c-0.280.22-0.70.02-0.7-0.34V11.85H3.15c-1.16 0-2.1-0.94-2.1-2.1V3.6c0-1.160.94-2.1 2.1-2.1zm1.45 4.15a1.15 1.15 0 1 0 0.01 2.3 1.15 1.15 0 0 0-0.01-2.3zm5.15 0a1.15 1.15 0 1 0 0.01 2.3 1.15 1.15 0 0 0-0.01-2.3z" android:fillColor="#FF000000" android:fillType="evenOdd"/>+ </group>+</vector>diff --git a/apps/desktop/src/renderer/assets/agents/workbuddy.svg b/apps/desktop/src/renderer/assets/agents/workbuddy.svgnew file mode 100644index 00000000..6afd98b6--- /dev/null+++ b/apps/desktop/src/renderer/assets/agents/workbuddy.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">+ <path fill="currentColor" fill-rule="evenodd" d="M3.15 1.5h8.15c1.16 0 2.1.94 2.1 2.1v6.15c0 1.16-.94 2.1-2.1 2.1H8.15L5.35 14.7c-.28.22-.7.02-.7-.34V11.85H3.15c-1.16 0-2.1-.94-2.1-2.1V3.6c0-1.16.94-2.1 2.1-2.1zm1.45 4.15a1.15 1.15 0 1 0 .01 2.3 1.15 1.15 0 0 0-.01-2.3zm5.15 0a1.15 1.15 0 1 0 .01 2.3 1.15 1.15 0 0 0-.01-2.3z"/>+</svg>diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex bc043669..a9aaf022 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -833,6 +833,7 @@"Install the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) and run `devin auth login`.": "Installiere the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) und führe `devin auth login` aus.","Install Qoder CLI (curl -fsSL https://qoder.com/install | bash) and run `qodercli login`.": "Installiere Qoder CLI (curl -fsSL https://qoder.com/install | bash) und führe `qodercli login` aus.","Install CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) and sign in with `codebuddy`.": "Installiere CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) und melde dich mit `codebuddy` an.",+ "Install WorkBuddy from https://www.workbuddy.ai and sign in from Codync.": "Installiere WorkBuddy von https://www.workbuddy.ai und melde dich in Codync an.","Install MiniMax Code (npm install -g @minimax-ai/code) and run `mcode login`.": "Installiere MiniMax Code (npm install -g @minimax-ai/code) und führe `mcode login` aus.","Install Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) and sign in with `junie`.": "Installiere Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) und melde dich mit `junie` an.","Install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) and sign in with `agy`.": "Installiere the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) und melde dich mit `agy` an.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex 757bb03c..d90bb38c 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -833,6 +833,7 @@"Install the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) and run `devin auth login`.": "Instala the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) y ejecuta `devin auth login`.","Install Qoder CLI (curl -fsSL https://qoder.com/install | bash) and run `qodercli login`.": "Instala Qoder CLI (curl -fsSL https://qoder.com/install | bash) y ejecuta `qodercli login`.","Install CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) and sign in with `codebuddy`.": "Instala CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) e inicia sesión con `codebuddy`.",+ "Install WorkBuddy from https://www.workbuddy.ai and sign in from Codync.": "Instala WorkBuddy desde https://www.workbuddy.ai e inicia sesión desde Codync.","Install MiniMax Code (npm install -g @minimax-ai/code) and run `mcode login`.": "Instala MiniMax Code (npm install -g @minimax-ai/code) y ejecuta `mcode login`.","Install Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) and sign in with `junie`.": "Instala Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) e inicia sesión con `junie`.","Install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) and sign in with `agy`.": "Instala the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) e inicia sesión con `agy`.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex 468e531f..913c8c9d 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -833,6 +833,7 @@"Install the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) and run `devin auth login`.": "Installez the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) et exécutez `devin auth login`.","Install Qoder CLI (curl -fsSL https://qoder.com/install | bash) and run `qodercli login`.": "Installez Qoder CLI (curl -fsSL https://qoder.com/install | bash) et exécutez `qodercli login`.","Install CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) and sign in with `codebuddy`.": "Installez CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) et connectez-vous avec `codebuddy`.",+ "Install WorkBuddy from https://www.workbuddy.ai and sign in from Codync.": "Installez WorkBuddy depuis https://www.workbuddy.ai et connectez-vous depuis Codync.","Install MiniMax Code (npm install -g @minimax-ai/code) and run `mcode login`.": "Installez MiniMax Code (npm install -g @minimax-ai/code) et exécutez `mcode login`.","Install Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) and sign in with `junie`.": "Installez Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) et connectez-vous avec `junie`.","Install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) and sign in with `agy`.": "Installez the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) et connectez-vous avec `agy`.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex 07dbcf5a..5c6b3968 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -833,6 +833,7 @@"Install the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) and run `devin auth login`.": "Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) をインストールし、`devin auth login` を実行します。","Install Qoder CLI (curl -fsSL https://qoder.com/install | bash) and run `qodercli login`.": "Qoder CLI (curl -fsSL https://qoder.com/install | bash) をインストールし、`qodercli login` を実行します。","Install CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) and sign in with `codebuddy`.": "CodeBuddy コードをインストールし (npm install -g @tencent-ai/codebuddy-code)、`codebuddy` でサインインします。",+ "Install WorkBuddy from https://www.workbuddy.ai and sign in from Codync.": "WorkBuddy を https://www.workbuddy.ai からインストールし、Codync でサインインします。","Install MiniMax Code (npm install -g @minimax-ai/code) and run `mcode login`.": "MiniMax コードをインストールし (npm install -g @minimax-ai/code)、`mcode login` を実行します。","Install Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) and sign in with `junie`.": "Junie をインストールし (curl -fsSL https://junie.jetbrains.com/install.sh | bash)、`junie` でサインインします。","Install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) and sign in with `agy`.": "Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) をインストールし、`agy` でサインインします。",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex 3ebb9780..92e13392 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -833,6 +833,7 @@"Install the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) and run `devin auth login`.": "the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash)을 설치하고 `devin auth login`을 실행하세요.","Install Qoder CLI (curl -fsSL https://qoder.com/install | bash) and run `qodercli login`.": "Qoder CLI (curl -fsSL https://qoder.com/install | bash)을 설치하고 `qodercli login`을 실행하세요.","Install CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) and sign in with `codebuddy`.": "CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code)을 설치하고 `codebuddy`으로 로그인하세요.",+ "Install WorkBuddy from https://www.workbuddy.ai and sign in from Codync.": "https://www.workbuddy.ai 에서 WorkBuddy를 설치하고 Codync에서 로그인하세요.","Install MiniMax Code (npm install -g @minimax-ai/code) and run `mcode login`.": "MiniMax Code (npm install -g @minimax-ai/code)을 설치하고 `mcode login`을 실행하세요.","Install Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) and sign in with `junie`.": "Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash)을 설치하고 `junie`으로 로그인하세요.","Install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) and sign in with `agy`.": "the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash)을 설치하고 `agy`으로 로그인하세요.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex 8bbea4fe..247fb64d 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -833,6 +833,7 @@"Install the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) and run `devin auth login`.": "安装 Devin CLI(curl -fsSL https://cli.devin.ai/install.sh | bash),然后运行 `devin auth login`。","Install Qoder CLI (curl -fsSL https://qoder.com/install | bash) and run `qodercli login`.": "安装 Qoder CLI(curl -fsSL https://qoder.com/install | bash),然后运行 `qodercli login`。","Install CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) and sign in with `codebuddy`.": "安装 CodeBuddy Code(npm install -g @tencent-ai/codebuddy-code),然后用 `codebuddy` 登录。",+ "Install WorkBuddy from https://www.workbuddy.ai and sign in from Codync.": "从 https://www.workbuddy.ai 安装 WorkBuddy,然后在 Codync 里登录。","Install MiniMax Code (npm install -g @minimax-ai/code) and run `mcode login`.": "安装 MiniMax Code(npm install -g @minimax-ai/code),然后运行 `mcode login`。","Install Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) and sign in with `junie`.": "安装 Junie(curl -fsSL https://junie.jetbrains.com/install.sh | bash),然后用 `junie` 登录。","Install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) and sign in with `agy`.": "安装 Antigravity CLI(curl -fsSL https://antigravity.google/cli/install.sh | bash),然后用 `agy` 登录。",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex 748c7891..6b78c817 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -833,6 +833,7 @@"Install the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) and run `devin auth login`.": "安裝 Devin CLI(curl -fsSL https://cli.devin.ai/install.sh | bash),然後執行 `devin auth login`。","Install Qoder CLI (curl -fsSL https://qoder.com/install | bash) and run `qodercli login`.": "安裝 Qoder CLI(curl -fsSL https://qoder.com/install | bash),然後執行 `qodercli login`。","Install CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) and sign in with `codebuddy`.": "安裝 CodeBuddy Code(npm install -g @tencent-ai/codebuddy-code),然後用 `codebuddy` 登入。",+ "Install WorkBuddy from https://www.workbuddy.ai and sign in from Codync.": "從 https://www.workbuddy.ai 安裝 WorkBuddy,然後在 Codync 裡登入。","Install MiniMax Code (npm install -g @minimax-ai/code) and run `mcode login`.": "安裝 MiniMax Code(npm install -g @minimax-ai/code),然後執行 `mcode login`。","Install Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) and sign in with `junie`.": "安裝 Junie(curl -fsSL https://junie.jetbrains.com/install.sh | bash),然後用 `junie` 登入。","Install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) and sign in with `agy`.": "安裝 Antigravity CLI(curl -fsSL https://antigravity.google/cli/install.sh | bash),然後用 `agy` 登入。",diff --git a/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-workbuddy.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-workbuddy.imageset/Contents.jsonnew file mode 100644index 00000000..bf94aa85--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-workbuddy.imageset/Contents.json@@ -0,0 +1,5 @@+{+ "images" : [ { "filename" : "workbuddy.svg", "idiom" : "universal" } ],+ "info" : { "author" : "xcode", "version" : 1 },+ "properties" : { "template-rendering-intent" : "template", "preserves-vector-representation" : true }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-workbuddy.imageset/workbuddy.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-workbuddy.imageset/workbuddy.svgnew file mode 100644index 00000000..6afd98b6--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-workbuddy.imageset/workbuddy.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">+ <path fill="currentColor" fill-rule="evenodd" d="M3.15 1.5h8.15c1.16 0 2.1.94 2.1 2.1v6.15c0 1.16-.94 2.1-2.1 2.1H8.15L5.35 14.7c-.28.22-.7.02-.7-.34V11.85H3.15c-1.16 0-2.1-.94-2.1-2.1V3.6c0-1.16.94-2.1 2.1-2.1zm1.45 4.15a1.15 1.15 0 1 0 .01 2.3 1.15 1.15 0 0 0-.01-2.3zm5.15 0a1.15 1.15 0 1 0 .01 2.3 1.15 1.15 0 0 0-.01-2.3z"/>+</svg>diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex b585a3ba..909afdd6 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -15,6 +15,7 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o- 聯結器翻到還沒載入的頁面時,會從 MCP Registry 接著載入。- 「憑證」移到上方電腦名稱旁;「自定義聯結器」和「自己的技能」放在各自分類的列表上方。- 電腦使用自建中繼時,設定和連線狀態會顯示該中繼的地址,不再一律寫成 Cloudflare。+- 可以建立使用 WorkBuddy 的 Bot:Codync 會使用 WorkBuddy 桌面 App 內附的 CLI,並在聊天裡請你登入。### en-US- Images a bot sends now show right in the chat; tap one to see it full size, no download needed.@@ -23,6 +24,7 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o- Connectors keep loading from the MCP Registry as you page past what's loaded.- Credentials sits beside the computer's name at the top, and Custom connector and Your own skill sit above their lists.- When a computer uses a private relay, Settings and connection status show that relay's address instead of always saying Cloudflare.+- Create bots that run WorkBuddy: Codync uses the CLI inside the WorkBuddy desktop app and asks you to sign in from the chat.## 2.26.1diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex 7b30b0ae..cfe81198 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -89,7 +89,7 @@ Codync/| CLI and background service | `host/src/main.rs`, `service/` || API, caller permissions, event ordering | `host/src/api/`, `hub.rs` || SQLite transcript, bots, lanes and sessions | `host/src/store/` (`entries.rs`, `bots.rs`, `model.rs`, `devices.rs`, `schema.rs`) |-| Agent process, ACP, queue and session lifecycle | `host/src/agent/bot/` (`launch.rs`, `queue.rs`, `session.rs`, `turn.rs`, `updates.rs`), `acp.rs` |+| Agent process, ACP, queue and session lifecycle | `host/src/agent/bot/` (`launch.rs`, `queue.rs`, `session.rs`, `turn.rs`, `updates.rs`), `acp.rs` (+ `acp/codebuddy.rs`, CodeBuddy's ACP extensions) || Compaction timing and rollover | `host/src/agent/bot/compaction.rs`, the handoff card in `host/src/chat/handoff.rs`; the rules in `codync-mem`'s `compaction.rs` || Group room turns / bot-to-bot requests | `host/src/chat/group.rs` / `team.rs` || Voice calls (the call, the voice's instructions and tools, transcripts, call lines) | `host/src/chat/calls/` (`mod.rs`, `context.rs`, `project.rs` the git state, `tools.rs`, `announce.rs` what the voice hears while the call lasts, `speech.rs` text as a voice says it); the user's messages it relays go through `host/src/chat/messages.rs` like typed ones; clients' `CallLink` (iPhone `CodyncUI/Call/CallLink.swift`, desktop `views/call/call-link.ts`, Android `core/Calls.kt` + `HostCallLink.kt`) and call rows (`CallRows`); the call on the iPhone's Lock Screen (`CodyncUI/Call/CallActivity.swift`, the Live Activity) and Android's call notification (`VoiceService.kt`) |@@ -97,7 +97,7 @@ Codync/| Prompt snapshots and memory | `host/src/chat/context.rs`, `memory/` (`api.rs` the apps' read-only view, `tools.rs` and `file_tools.rs` the MCP tools, `files.rs` the folders and scan, `turns.rs` which bot's turn a found change is credited to, `file_api.rs`, `dream.rs`, `import.rs`); the rules in `host/crates/memory` (`codync-mem`: files and facts in `files/`, dreaming in `dream/`, tombstones in `store.rs`, the old entries in `legacy.rs`); harnesses' own memory turned off in `host/src/agent/own_memory.rs` || Identity, encryption and direct channel | `host/src/remote/identity.rs`, `crypto.rs`, `channel.rs` || Host cloud state and relay connection | `host/src/remote/cloud.rs`, `cloud_url.rs`, `relay.rs` |-| Agent discovery, sign-in, setup terminal, Node.js for npm agents | `host/src/agent/backends.rs` (+ `backends/sign_in.rs`, `backends/search_path.rs`), `registry.rs`, `auth.rs`, `term.rs`, `node.rs` |+| Agent discovery, sign-in, setup terminal, Node.js for npm agents | `host/src/agent/backends.rs` (+ `backends/catalog.rs` the known harnesses, `backends/sign_in.rs`, `backends/search_path.rs`, `backends/workbuddy.rs` the CLI inside the WorkBuddy app), `registry.rs`, `auth.rs` (+ `auth/agent.rs` starting an agent and its own sign-in, `auth/models.rs`), `term.rs`, `node.rs` || Fast mode (session config option) | `host/src/agent/config.rs`, `agent/bot/fast_mode.rs` || Marketplace, Composio, connector OAuth | `host/src/market/` || Skills a bot writes (`save_skill`) | `host/src/chat/skills.rs`, stored by `host/src/market/skills.rs` |diff --git a/docs/design/bot-memory.md b/docs/design/bot-memory.mdindex f54a7111..60952a51 100644--- a/docs/design/bot-memory.md+++ b/docs/design/bot-memory.md@@ -394,6 +394,7 @@ can, the user may keep it on for one bot ([Claude Code's own memory](#claude-cod| Copilot CLI | Copilot Memory, on for individual plans | `--excluded-tools=store_memory,vote_memory` || Qwen Code | Auto memory and its own dreaming, on | `.qwen/settings.json` in a bot's own workspace: `memory.enableManagedAutoMemory` and `enableManagedAutoDream` false. Nothing in a project folder, whose files are the user's || CodeBuddy | Auto memory | `CODEBUDDY_DISABLE_AUTO_MEMORY=1` |+| WorkBuddy | The same auto memory, in the CLI bundled with the app | `CODEBUDDY_DISABLE_AUTO_MEMORY=1` || Codex, Goose, Grok, oh-my-pi, Qoder, Cortex | Off unless the user turns it on | Nothing || Gemini CLI | Its system prompt has the model edit `~/.gemini/GEMINI.md` | Nothing: no switch short of replacing its system prompt or its home folder || Kilo Code | Memory tools, on per project | Nothing: the only per-process switch replaces the whole config |@@ -499,7 +500,7 @@ The user can keep it on per bot, for example to share the auto-memory directorysessions in the terminal. The switch sits on the memory screen with an info button on what it costs: the bot mayremember things twice, the two memories can disagree, and forgetting something in Codync doesn't reach ClaudeCode's notes. Codync then shows the folder's `MEMORY.md` read-only, so it isn't unseen. The same switch covers-Copilot, CodeBuddy and (in a bot's own workspace) Qwen Code. Using it instead of Codync's memory is planned:+Copilot, CodeBuddy, WorkBuddy and (in a bot's own workspace) Qwen Code. Using it instead of Codync's memory is planned:[harness memory](../plans/harness-memory.md).The adapter passes `claudeCode.options.settings` and `.env` through untouched, so these settings reach the SDK.diff --git a/docs/features/agent-fallback.md b/docs/features/agent-fallback.mdindex 6e20e38f..d5867a51 100644--- a/docs/features/agent-fallback.md+++ b/docs/features/agent-fallback.md@@ -57,12 +57,14 @@ Read from the ACP answer: the JSON-RPC code, the adapter's category (Claude's `d| `usageLimit` | Claude: `rate_limit`/`billing_error` with the Agent SDK's usage-limit text ("You've hit your…"). Codex: `usageLimitExceeded` | Until the reset the agent reported (`usage` windows at 100%); unknown: 1 h || `outOfCredits` | Claude `billing_error`, `account_on_hold` | 6 h || `rateLimited`, `overloaded` | Claude `rate_limit`, `overloaded`, `server_error`; codex-acp `rateLimitExceeded`, `serverOverloaded` | 1, 5, 25, then 60 min for failures in a row |-| `signedOut` | ACP `-32000`, `authentication_failed` | Until it's signed in, looking again after 1 h; an agent Codync can't sign in to (no sign-in card): 10 min. The chat of each bot that moves past it gets the agent's sign-in card (holding no message: the fallback answers it), and signing in there brings the bot back |+| `signedOut` | ACP `-32000`, `authentication_failed`, CodeBuddy's `auth` category | Until it's signed in, looking again after 1 h; an agent Codync can't sign in to (no sign-in card): 10 min. The chat of each bot that moves past it gets the agent's sign-in card (holding no message: the fallback answers it), and signing in there brings the bot back || `notStarting` | `FailureKind::NotSetUp`, `Timeout`, `Exited` | 5 min || `modelMissing` | `model_not_found`, or the agent refusing the step's model (`FailureKind::NoModel`) | None: it's the bot's setup, not the agent's. The bot skips that step until its settings change |Stop, refusal, output or step limits, a routine's time limit, compactions and uncategorized internal errors don't move-on. codex-acp still sends its 429s and overloads as reply text ([codex-acp#647](https://github.com/agentclientprotocol/codex-acp/issues/647)),+on. CodeBuddy's CLI (CodeBuddy Code, WorkBuddy) answers a failed prompt as a refusal with the error in+`_meta["codebuddy.ai/errorMessage"]`: that one counts as the error it holds (`acp::codebuddy::prompt_result`), so a+signed-out WorkBuddy moves on. codex-acp still sends its 429s and overloads as reply text ([codex-acp#647](https://github.com/agentclientprotocol/codex-acp/issues/647)),so only its usage limit moves a Codex bot on today.**Rests** (`fallback::rest`, `kv` `rest.<account>`: the agent, or a custom command's own) are the computer's: once onediff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.mdindex 34ffe400..ed1b3ecc 100644--- a/docs/features/context-and-memory.md+++ b/docs/features/context-and-memory.md@@ -118,7 +118,7 @@ Claude Code's own memory; the rules live in the `codync-mem` crate, and `chat/meadded and took out, the notes it wrote).- **The harness's own memory** is off for every bot and for background jobs (`agent/own_memory.rs`): Claude Code(`autoMemoryEnabled` and `autoDreamEnabled` false, `CLAUDE_CODE_DISABLE_AUTO_MEMORY`), Copilot (its memory tools- excluded), CodeBuddy, and Qwen Code (workspace settings, so only in a bot's own workspace: a project folder's+ excluded), CodeBuddy, WorkBuddy (the same switch as CodeBuddy), and Qwen Code (workspace settings, so only in a bot's own workspace: a project folder'sfiles are the user's). Gemini CLI, Kilo Code, Kiro and Hermes Agent have no switch Codync can use. Projectknowledge goes in the bot's own notes, and into the project's `CLAUDE.md` or `AGENTS.md` only when the user asks.- **Keeping it on.** Where Codync has the switch, the memory screen's "This bot" section offers "<harness>'s owndiff --git a/docs/features/marketplace.md b/docs/features/marketplace.mdindex 518e7af5..264995cb 100644--- a/docs/features/marketplace.md+++ b/docs/features/marketplace.md@@ -44,6 +44,10 @@ Clicking a skill (an Extensions row, an installed skill, or the info button besiRegistry-backed package connectors follow their upstream release. The host checks the Registry periodically after credentials are unlocked and checks again immediately before a package process starts. If a newer pinned npm, PyPI, OCI or NuGet reference is available, only that package/image argument is replaced; the running process is not interrupted, and the new version applies on its next launch. Network failures, missing packages and attempted downgrades leave the installed reference unchanged. Custom command connectors are never updated automatically.+## WorkBuddy++WorkBuddy is a built-in agent that runs the CLI bundled inside the WorkBuddy desktop app (`WorkBuddy AI.app` from workbuddy.ai or `WorkBuddy.app` from codebuddy.cn on macOS; `%LOCALAPPDATA%\Programs\WorkBuddy AI` or `…\WorkBuddy` on Windows). The app ships only the lite bundle (`codebuddy-lite-wb.mjs`), so Codync sets `CODEBUDDY_FORCE_LITE_WB_BUNDLE=1` and starts `{bin} --serve --acp`. `--acp` alone loads a headless bundle the app does not include, and the process exits. `--serve` is what starts ACP; `--acp` selects its stdio transport (the HTTP banner on stdout is ignored). That file is also named `codebuddy`, so Codync does not take it from `PATH`: a `codebuddy` command there stays [CodeBuddy Code](https://www.npmjs.com/package/@tencent-ai/codebuddy-code). It is a Node script, so the agent list asks for Node.js (Codync's own when the computer has none). There is no installer in Codync, and no Linux build, so Linux doesn't list it. The app's login is encrypted for the app, so the CLI does not see it: a prompt with no token comes back as `stopReason: refusal` with the error in `_meta["codebuddy.ai/errorMessage"]`, which Codync reads as that error (`acp::codebuddy::prompt_result`): a sign-in card holding the message, or the bot's next agent. Its session opens signed out, so a check asks `_codebuddy.ai/getUserInfo` instead (only whether it names an account: the answer carries tokens). On `authenticate`, Codync opens the http(s) page from the `_codebuddy.ai/authUrl` notification. Select **WorkBuddy** and sign in from that card. It honors `CODEBUDDY_DISABLE_AUTO_MEMORY`, so a bot can keep WorkBuddy's own memory on the same way as CodeBuddy Code.+## Hermes AgentHermes Agent is a built-in agent that runs its installed CLI with `hermes acp`, without an ACP registry adapter. Install it using the [official installation guide](https://hermes-agent.nousresearch.com/docs/getting-started/installation), then run `hermes acp --setup` to choose a provider and model. In Codync, refresh the agents and select **Hermes Agent** when creating a bot; leave the custom command empty.diff --git a/docs/plans/harness-memory.md b/docs/plans/harness-memory.mdindex 91fc9c95..fb66d3d2 100644--- a/docs/plans/harness-memory.md+++ b/docs/plans/harness-memory.md@@ -14,7 +14,7 @@ not pushed), so treat the design below as the spec. Current behavior:- The memory screen's "This bot" section has a switch, "Claude Code's own memory", with an info button: it keepsnotes apart from Codync's; with both on the bot may remember things twice and the two can disagree; forgettingsomething in Codync doesn't reach it; where to read it. The terminal asks the same on `m` before turning it on.-- Offered where Codync controls it (`own_memory::switchable`): Claude Code, Copilot and CodeBuddy in any folder,+- Offered where Codync controls it (`own_memory::switchable`): Claude Code, Copilot, CodeBuddy and WorkBuddy in any folder,Qwen Code only in the bot's own workspace (its switch is a file in the folder, and a project folder's files arethe user's). Gemini CLI, Kilo Code, Kiro and Hermes Agent have no switch Codync can use.- Kept on, the harness sets its memory itself (Claude Code's auto-dream too); Claude Code's `MEMORY.md` showsdiff --git a/host/src/agent/acp.rs b/host/src/agent/acp.rsindex e79ae6d7..97ab7fae 100644--- a/host/src/agent/acp.rs+++ b/host/src/agent/acp.rs@@ -3,6 +3,7 @@//! newer adapter adding a variant never breaks parsing.use crate::LockExt;+use crate::agent::fallback::reason::{self, Reason};use anyhow::{Context, Result};use serde_json::{Value, json};use std::collections::{HashMap, VecDeque};@@ -15,6 +16,8 @@ use tokio::process::{Child, ChildStdin, Command};use tokio::sync::{mpsc, oneshot};use tokio::time::Instant;+pub mod codebuddy;+/// stderr lines kept to explain a crash.const STDERR_TAIL_LINES: usize = 12;/// How long a stopped agent gets to exit by itself before what's left of it is killed.@@ -37,9 +40,9 @@ type Pending = Arc<std::sync::Mutex<HashMap<i64, oneshot::Sender<Result<Value, Vpub struct RpcError {pub code: i64,pub message: String,- /// The adapter's own category (`data.errorKind`: Claude's `rate_limit`, `overloaded`, …; codex-acp's- /// `data.codexErrorInfo` as `usage_limit_exceeded`), kept only when it's an identifier, as it can go to usage- /// analytics.+ /// The adapter's own category (`data.errorKind`: Claude's `rate_limit`, `overloaded`, …; `CodeBuddy`'s+ /// `data.category`: `auth`, `custom_model_auth`, …; codex-acp's `data.codexErrorInfo` as `usage_limit_exceeded`),+ /// kept only when it's an identifier, as it can go to usage analytics.pub kind: Option<String>,}@@ -56,13 +59,16 @@ impl std::fmt::Display for RpcError {impl std::error::Error for RpcError {}-/// Whether an agent's error asks for signing in: ACP's code, or adapters that only say so.+/// Whether an agent's error asks for signing in: ACP's code, the category of an adapter that names one, or the+/// words of one that names none. A named category is believed: `CodeBuddy`'s `custom_model_auth` (a bad key in+/// `models.json`) says "Authentication failed" but signing in doesn't fix it.pub fn needs_sign_in(e: &anyhow::Error) -> bool {- let rpc = |c: &(dyn std::error::Error + 'static)| {- c.downcast_ref::<RpcError>()- .is_some_and(|r| r.code == AUTH_REQUIRED || r.message.to_lowercase().contains("auth"))- };- e.chain().any(rpc) || e.to_string().to_lowercase().contains("auth")+ let says_auth = |text: &str| text.to_lowercase().contains("auth");+ match e.chain().find_map(|c| c.downcast_ref::<RpcError>()) {+ Some(r) if r.kind.is_some() => reason::of_rpc(r) == Some(Reason::SignedOut),+ Some(r) => r.code == AUTH_REQUIRED || says_auth(&r.message) || says_auth(&e.to_string()),+ None => says_auth(&e.to_string()),+ }}/// Whether a failed prompt may have left its session dead in the agent: an internal error the@@ -115,27 +121,29 @@ impl Answer {pub async fn response(self) -> Result<Value> {match self.rx.await {Ok(Ok(v)) => Ok(v),- Ok(Err(e)) => {- let msg = e["message"].as_str().map_or_else(|| e.to_string(), str::to_owned);- let message = match e["data"]["details"].as_str().or(e["data"].as_str()) {- Some(d) => format!("{msg} ({d})"),- None => msg,- };- let kind = e["data"]["errorKind"]- .as_str()- .map(str::to_owned)- .or_else(|| codex_kind(&e["data"]["codexErrorInfo"]))- .filter(|k| {- !k.is_empty() && k.len() <= 40 && k.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')- });- Err(RpcError { code: e["code"].as_i64().unwrap_or_default(), message, kind }.into())- }+ Ok(Err(e)) => Err(rpc_error(&e).into()),// The reader drops every waiter when the process goes away.Err(_) => Err(Failure::error(FailureKind::Exited, "agent process exited")),}}}+/// A JSON-RPC error object as an [`RpcError`].+fn rpc_error(e: &Value) -> RpcError {+ let msg = e["message"].as_str().map_or_else(|| e.to_string(), str::to_owned);+ let message = match e["data"]["details"].as_str().or(e["data"].as_str()) {+ Some(d) => format!("{msg} ({d})"),+ None => msg,+ };+ let kind = e["data"]["errorKind"]+ .as_str()+ .or(e["data"]["category"].as_str())+ .map(str::to_owned)+ .or_else(|| codex_kind(&e["data"]["codexErrorInfo"]))+ .filter(|k| !k.is_empty() && k.len() <= 40 && k.bytes().all(|b| b.is_ascii_lowercase() || b == b'_'));+ RpcError { code: e["code"].as_i64().unwrap_or_default(), message, kind }+}+/// codex-acp's category (`data.codexErrorInfo`: `"usageLimitExceeded"`, or `{"httpConnectionFailed": {…}}`) in the/// same form as Claude's `errorKind`: `usage_limit_exceeded`.fn codex_kind(info: &Value) -> Option<String> {diff --git a/host/src/agent/acp/codebuddy.rs b/host/src/agent/acp/codebuddy.rsnew file mode 100644index 00000000..d11e8a31--- /dev/null+++ b/host/src/agent/acp/codebuddy.rs@@ -0,0 +1,96 @@+//! `CodeBuddy`'s ACP extensions (its CLI runs `CodeBuddy` Code and `WorkBuddy`): a prompt that fails answers `refusal`+//! with the error in `_meta["codebuddy.ai/errorMessage"]`, `authenticate` posts the sign-in page on+//! `_codebuddy.ai/authUrl`, and `_codebuddy.ai/getUserInfo` names the signed-in account.++use super::{Acp, Incoming, rpc_error};+use anyhow::Result;+use serde_json::{Value, json};+use std::time::Duration;++/// A `session/prompt` answer, with the error `CodeBuddy` hides in a refusal returned as that error, so a sign-in, a+/// fallback or the agent's own words follow from it as from any other agent's error answer.+pub fn prompt_result(result: Value) -> Result<Value> {+ let Some(raw) = result["_meta"]["codebuddy.ai/errorMessage"].as_str().filter(|_| result["stopReason"] == "refusal")+ else {+ return Ok(result);+ };+ let error =+ serde_json::from_str::<Value>(raw).ok().filter(Value::is_object).unwrap_or_else(|| json!({"message": raw}));+ Err(rpc_error(&error).into())+}++/// The sign-in page `authenticate` posted, when it is a web page: the host opens it in the browser.+pub fn sign_in_url(incoming: &Incoming) -> Option<String> {+ let Incoming::Notification { method, params } = incoming else { return None };+ let url = params["authUrl"].as_str().filter(|_| method == "_codebuddy.ai/authUrl")?;+ let url = reqwest::Url::parse(url).ok()?;+ (matches!(url.scheme(), "https" | "http") && url.has_host()).then(|| url.into())+}++/// Whether an account is signed in (signed out, the answer has no `userInfo`). `None`: it didn't say. Nothing else+/// of the answer is read: it carries the account's tokens.+pub async fn signed_in(acp: &Acp) -> Option<bool> {+ let info = tokio::time::timeout(Duration::from_secs(15), acp.request("_codebuddy.ai/getUserInfo", json!({})));+ info.await.ok()?.ok().map(|info| !info["userInfo"].is_null())+}++#[cfg(test)]+mod tests {+ use super::super::{AUTH_REQUIRED, RpcError, needs_sign_in};+ use super::*;++ fn refusal(error: &str) -> Value {+ json!({"stopReason": "refusal", "_meta": {"codebuddy.ai/errorMessage": error}})+ }++ fn error_of(result: Value) -> anyhow::Error {+ prompt_result(result).expect_err("an error in the refusal")+ }++ #[test]+ fn a_refusal_that_hides_a_sign_in_error_asks_to_sign_in() {+ let error = error_of(refusal(+ r#"{"code":-32000,"message":"Authentication required","data":{"details":"Please use /login command to sign in to your account","category":"auth"}}"#,+ ));+ let rpc = error.downcast_ref::<RpcError>().expect("an RpcError");+ assert_eq!((rpc.code, rpc.kind.as_deref()), (AUTH_REQUIRED, Some("auth")));+ assert!(needs_sign_in(&error));+ assert!(error.to_string().contains("sign in to your account"));+ }++ #[test]+ fn a_custom_model_key_error_shows_its_own_words() {+ let error = error_of(refusal(+ r#"{"code":-32603,"message":"Internal error","data":{"details":"Authentication failed for custom model my-model. Check if the apiKey in your models.json is correct","category":"custom_model_auth"}}"#,+ ));+ assert!(!needs_sign_in(&error), "signing in doesn't fix a bad key in models.json");+ assert!(error.to_string().contains("models.json"));+ }++ #[test]+ fn a_plain_refusal_or_answer_stays() {+ let plain = json!({"stopReason": "refusal"});+ assert_eq!(prompt_result(plain.clone()).unwrap(), plain);+ let done = json!({"stopReason": "end_turn", "_meta": {"codebuddy.ai/errorMessage": "{}"}});+ assert_eq!(prompt_result(done.clone()).unwrap(), done);+ assert_eq!(error_of(refusal("Network unreachable")).to_string(), "Network unreachable");+ }++ #[test]+ fn only_a_web_page_is_opened() {+ let posted = |url: &str| Incoming::Notification {+ method: "_codebuddy.ai/authUrl".into(),+ params: json!({"authUrl": url}),+ };+ assert_eq!(+ sign_in_url(&posted("https://www.workbuddy.ai/login?state=a b")).as_deref(),+ Some("https://www.workbuddy.ai/login?state=a%20b")+ );+ for refused in ["file:///etc/passwd", "javascript:alert(1)", "workbuddy://login", "https://", "not a url"] {+ assert_eq!(sign_in_url(&posted(refused)), None, "{refused}");+ }+ let other =+ Incoming::Notification { method: "session/update".into(), params: json!({"authUrl": "https://x.dev"}) };+ assert_eq!(sign_in_url(&other), None);+ }+}diff --git a/host/src/agent/auth.rs b/host/src/agent/auth.rsindex 7b1eb654..7d1ce582 100644--- a/host/src/agent/auth.rs+++ b/host/src/agent/auth.rs@@ -5,7 +5,7 @@//! reports its login (`_auth/status_update`) is believed; when its report doesn't//! come, the harness's own CLI check decides, else it can't tell (a session proves//! nothing for it). Other agents get `session/new`: `-32000` means it needs signing-//! in. Methods come in three kinds:+//! in (`WorkBuddy` opens one signed out, so its account tells). Methods come in three kinds://! - terminal: a command (the agent's `_meta.terminal-auth`, or its own binary//! with `args`), run in a setup terminal (`term`);//! - agent: the agent signs itself in on `authenticate` (usually a browser on@@ -14,21 +14,28 @@//! environment on every launch.use crate::LockExt;-use crate::agent::acp::{AUTH_REQUIRED, Acp, Incoming, RpcError};+use crate::agent::acp::{self, AUTH_REQUIRED, Incoming, RpcError};use crate::agent::backends;-use crate::agent::registry::{Candidate, Cmd, env_prefix};+use crate::agent::registry::{Cmd, env_prefix};use crate::shell::quote as shell_quote;use crate::store::Store;-use anyhow::{Context, Result, anyhow, bail};+use anyhow::{Result, bail};use serde::Serialize;use serde_json::{Map, Value, json};use std::collections::BTreeMap;use std::ops::ControlFlow;use std::path::PathBuf;-use std::sync::{Arc, Mutex};+use std::sync::Mutex;use std::time::Duration;use tokio::sync::mpsc;+mod agent;+mod models;+pub use agent::authenticate;+use agent::start;+pub use models::models;+pub(crate) use models::{model_config, model_ids};+#[derive(Clone, Debug, Serialize)]#[serde(rename_all = "camelCase", tag = "kind")]pub enum MethodKind {@@ -93,6 +100,13 @@ pub fn env(store: &Store, backend: &str) -> Result<Vec<(String, String)>> {Ok(values.into_iter().collect())}+/// The environment `backend`'s process starts with: the saved keys, and what the harness needs to start.+pub fn launch_env(store: &Store, backend: &str) -> Result<Vec<(String, String)>> {+ let mut env = env(store, backend)?;+ backends::apply_process_env(backend, &mut env);+ Ok(env)+}+/// Names of the saved keys (values never leave the host).fn saved_env(store: &Store, backend: &str) -> Result<Vec<String>> {Ok(env(store, backend)?.into_iter().map(|(k, _)| k).collect())@@ -100,7 +114,11 @@ fn saved_env(store: &Store, backend: &str) -> Result<Vec<String>> {/// Runs a check and returns `{signedIn, detail, methods, savedEnv}`.pub async fn check(store: &Store, backend: &str) -> Result<Value> {- let status = probe(store, backend).await?;+ let mut status = probe(store, backend).await?;+ // Where a session proves nothing, a check that can't tell keeps what the last sign-in showed.+ if status.signed_in.is_none() && !backends::session_proves_sign_in(backend) {+ status.signed_in = backends::signed_in(backend);+ }backends::set_signed_in(backend, status.signed_in);CHECKED.locked().insert(backend.to_owned(), status.clone());let mut v = serde_json::to_value(&status)?;@@ -110,118 +128,6 @@ pub async fn check(store: &Store, backend: &str) -> Result<Value> {Ok(v)}-/// Discover the agent's advertised models in an isolated, prompt-free session.-/// This uses the same credentials as actual bot sessions and never reads project files.-pub async fn models(store: &Store, backend: &str) -> Result<Value> {- let (acp, mut inbox, _, _) = start(store, backend).await?;- let result = tokio::time::timeout(Duration::from_secs(60), async {- let request = acp.request("session/new", json!({"cwd": probe_dir(), "mcpServers": []}));- tokio::pin!(request);- let session = loop {- tokio::select! {- result = &mut request => break result?,- incoming = inbox.recv() => match incoming {- Some(Incoming::Request { id, .. }) => {- acp.respond_error(id, -32601, "not supported during model discovery").await?;- }- Some(Incoming::Notification { .. }) => {}- Some(Incoming::Closed { .. }) | None => bail!("agent closed during model discovery"),- }- }- };- // Cursor lists each model's options (effort, fast…) only through its own method.- let options = if backend == "cursor" {- acp.request("cursor/list_available_models", json!({})).await.unwrap_or_default()- } else {- Value::Null- };- Ok((session, options))- })- .await;- acp.kill().await;- let (session, options) = result.context("the agent's model list timed out")??;- Ok(model_catalog(&session, &options))-}--/// IDs are agent-defined: use the category, with legacy conventional IDs as a fallback.-pub(crate) fn model_config(session: &Value) -> Option<&Value> {- let options = session["configOptions"].as_array()?;- let is_select = |v: &&Value| v["type"] == "select" || v.get("type").is_none();- options- .iter()- .filter(is_select)- .find(|v| v["category"] == "model")- .or_else(|| options.iter().filter(is_select).find(|v| v["id"] == "model" || v["id"] == "models"))-}--/// The model ids the agent lists, in its order.-pub(crate) fn model_ids(session: &Value) -> Vec<String> {- let catalog = model_catalog(session, &Value::Null);- catalog["models"].as_array().into_iter().flatten().filter_map(|m| text(&m["id"])).collect()-}--/// `{models: [{id, name, description, options}], currentModelId, fastMode}`; `options` is-/// Cursor's `cursor/list_available_models` answer (`Null` for other agents).-fn model_catalog(session: &Value, options: &Value) -> Value {- fn collect(options: &Value, out: &mut Vec<Value>) {- for option in options.as_array().into_iter().flatten() {- if option["options"].is_array() {- collect(&option["options"], out);- } else if let Some(id) = text(&option["value"])- && !out.iter().any(|v| v["id"] == id)- {- out.push(json!({"id": id, "name": text(&option["name"]).unwrap_or(id),- "description": text(&option["description"])}));- }- }- }- let mut models = Vec::new();- let current = if let Some(config) = model_config(session) {- collect(&config["options"], &mut models);- text(&config["currentValue"])- } else {- for model in session["models"]["availableModels"].as_array().into_iter().flatten() {- if let Some(id) = text(&model["modelId"])- && !models.iter().any(|v| v["id"] == id)- {- models.push(json!({"id": id, "name": text(&model["name"]).unwrap_or(id),- "description": text(&model["description"])}));- }- }- text(&session["models"]["currentModelId"])- };- for model in &mut models {- model["options"] = json!(model_options(options, model["id"].as_str().unwrap_or_default()));- }- json!({"models": models, "currentModelId": current,- "fastMode": crate::agent::config::fast_mode_config(session).is_some()})-}--/// One model's options as `[{id, name, values: [{id, name}], default}]`, from Cursor's-/// `{models: [{value, configOptions}]}` (ACP select config options).-fn model_options(options: &Value, model: &str) -> Vec<Value> {- let entry = options["models"].as_array().into_iter().flatten().find(|m| m["value"] == model);- entry- .and_then(|m| m["configOptions"].as_array())- .into_iter()- .flatten()- .filter(|o| o["type"] == "select")- .filter_map(|o| {- let id = text(&o["id"])?;- let values: Vec<Value> = o["options"]- .as_array()?- .iter()- .filter_map(|v| {- let value = text(&v["value"])?;- Some(json!({"id": value, "name": text(&v["name"]).unwrap_or(value)}))- })- .collect();- Some(json!({"id": id, "name": text(&o["name"]).unwrap_or(id), "values": values,- "default": text(&o["currentValue"])}))- })- .collect()-}-async fn probe(store: &Store, backend: &str) -> Result<Status> {let (acp, mut inbox, init, cmd) = start(store, backend).await?;let methods = methods(backend, &init, &cmd);@@ -233,14 +139,19 @@ async fn probe(store: &Store, backend: &str) -> Result<Status> {}let dir = probe_dir();tokio::fs::create_dir_all(&dir).await?;- let res = tokio::time::timeout(- Duration::from_secs(60),- acp.request("session/new", json!({"cwd": dir, "mcpServers": []})),- )+ let res = tokio::time::timeout(Duration::from_secs(60), async {+ acp.request("session/new", json!({"cwd": dir, "mcpServers": []})).await?;+ // WorkBuddy opens a session before it has a token: its account says whether it's signed in.+ Ok::<_, anyhow::Error>(if backends::session_proves_sign_in(backend) {+ Some(true)+ } else {+ acp::codebuddy::signed_in(&acp).await+ })+ }).await;acp.kill().await;let (signed_in, detail) = match res {- Ok(Ok(_)) => (Some(true), None),+ Ok(Ok(signed_in)) => (signed_in, None),Ok(Err(e)) => match e.downcast_ref::<RpcError>() {Some(r) if r.code == AUTH_REQUIRED => (Some(false), Some(r.message.clone())),_ => (None, Some(format!("{e:#}"))),@@ -291,75 +202,6 @@ async fn reported_login(inbox: &mut mpsc::UnboundedReceiver<Incoming>) -> Optiontokio::time::timeout(Duration::from_secs(8), report).await.ok().flatten()}-/// Starts `backend` and completes `initialize`, trying each way to launch it.-/// The agent's inbox must stay open: the reader stops when nobody listens.-type Started = (Arc<Acp>, mpsc::UnboundedReceiver<Incoming>, Value, Cmd);--async fn start(store: &Store, backend: &str) -> Result<Started> {- let mut candidates = backends::launch_candidates(backend)?;- // The installed CLI alone when there is one: resolving the registry build can mean a long download.- if matches!(candidates.first(), Some(Candidate::Ready(_))) {- candidates.truncate(1);- }- let env = env(store, backend)?;- let dir = probe_dir();- tokio::fs::create_dir_all(&dir).await?;- let mut last = None;- let count = candidates.len();- for (i, candidate) in candidates.into_iter().enumerate() {- // A first `npx` run downloads the package: give the last candidate time.- let budget = Duration::from_secs(if i + 1 < count { 20 } else { 180 });- let cmd = match candidate.resolve(|_| {}).await {- Ok(cmd) => cmd,- Err(e) => {- last = Some(e);- continue;- }- };- let (acp, mut rx) = match Acp::spawn(&cmd.acp(), &dir.to_string_lossy(), &env) {- Ok(v) => v,- Err(e) => {- last = Some(e);- continue;- }- };- let init = acp.request(- "initialize",- json!({- "protocolVersion": 1,- "clientCapabilities": {- "fs": {"readTextFile": false, "writeTextFile": false},- "terminal": false,- // Ask for terminal sign-in methods (spec field and the older `_meta` flag),- // and for plain models with options, as bot sessions do (`bot::start_agent`).- "auth": {"terminal": true},- "_meta": {"terminal-auth": true, "parameterizedModelPicker": true},- },- "clientInfo": {"name": "codync", "title": "Codync", "version": env!("CARGO_PKG_VERSION")},- }),- );- match tokio::time::timeout(budget, init).await {- Ok(Ok(init)) => return Ok((acp, rx, init, cmd)),- Ok(Err(e)) => {- // Its last stderr line usually says why it quit.- let why = std::iter::from_fn(|| rx.try_recv().ok()).find_map(|inc| match inc {- Incoming::Closed { stderr_tail } => {- stderr_tail.lines().rev().find(|l| !l.trim().is_empty()).map(str::to_owned)- }- _ => None,- });- last = Some(match why {- Some(why) => e.context(why),- None => e,- });- }- Err(_) => last = Some(anyhow!("the agent didn't start within {}s", budget.as_secs())),- }- acp.kill().await;- }- Err(last.unwrap_or_else(|| anyhow!("couldn't start the agent")))-}-fn text(v: &Value) -> Option<String> {v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)}@@ -435,22 +277,6 @@ pub fn terminal_command(backend: &str, method: &str) -> Option<String> {})}-/// Lets the agent sign itself in (it usually opens a browser on this computer).-pub async fn authenticate(store: &Store, backend: &str, method: &str) -> Result<Value> {- let (acp, _inbox, _, _) = start(store, backend).await?;- let res =- tokio::time::timeout(Duration::from_secs(10 * 60), acp.request("authenticate", json!({"methodId": method})))- .await;- acp.kill().await;- match res {- Ok(r) => {- r.context("signing in")?;- }- Err(_) => bail!("Sign-in didn't finish within 10 minutes."),- }- check(store, backend).await-}-/// Saves the keys for an env-var method (empty values remove them), then re-checks.pub async fn set_env(store: &Store, backend: &str, vars: &Map<String, Value>) -> Result<Value> {let mut saved: BTreeMap<String, String> = env(store, backend)?.into_iter().collect();@@ -471,78 +297,6 @@ pub async fn set_env(store: &Store, backend: &str, vars: &Map<String, Value>) ->mod tests {use super::*;- #[test]- fn model_catalog_reads_grouped_config_and_preserves_agent_ids() {- let session = json!({"configOptions": [{- "id": "provider-model", "category": "model", "type": "select", "currentValue": "m2",- "options": [{"group": "a", "options": [- {"value": "m1", "name": "First"}, {"value": "m2", "name": "Second"},- {"value": "m1", "name": "Duplicate"}- ]}]- }], "models": {"availableModels": [{"modelId": "legacy", "name": "Legacy"}]}});- assert_eq!(model_config(&session).unwrap()["id"], "provider-model");- let result = model_catalog(&session, &Value::Null);- assert_eq!(result["currentModelId"], "m2");- assert_eq!(result["models"].as_array().unwrap().len(), 2);- assert_eq!(result["models"][0]["id"], "m1");- assert_eq!(result["models"][1]["name"], "Second");- assert_eq!(result["models"][1]["options"], json!([]));- assert_eq!(model_ids(&session), ["m1", "m2"]);- }-- #[test]- fn model_catalog_reads_legacy_and_missing_lists() {- let result = model_catalog(- &json!({"models": {- "currentModelId": "a", "availableModels": [- {"modelId": "a", "name": "Agent model", "description": "Available here"},- {"name": "No ID"}- ]- }}),- &Value::Null,- );- assert_eq!(result["models"].as_array().unwrap().len(), 1);- assert_eq!(result["models"][0]["description"], "Available here");- assert_eq!(- model_catalog(&json!({}), &Value::Null),- json!({"models": [], "currentModelId": null, "fastMode": false})- );- }-- #[test]- fn model_catalog_adds_cursor_model_options() {- let session = json!({"configOptions": [{"id": "model", "category": "model", "type": "select",- "currentValue": "grok-4.7", "options": [{"value": "grok-4.7", "name": "Grok 4.7"}, {"value": "auto"}]}]});- let listed = json!({"models": [{"value": "grok-4.7", "name": "Grok 4.7", "configOptions": [- {"id": "reasoning_effort", "name": "Reasoning", "category": "thought_level", "type": "select",- "currentValue": "high", "options": [{"value": "medium", "name": "Medium"}, {"value": "high", "name": "High"}]},- {"id": "fast", "type": "select", "currentValue": "true", "options": [{"value": "false", "name": "Off"}, {"value": "true"}]},- {"id": "verbose", "type": "boolean"}- ]}]});- let result = model_catalog(&session, &listed);- assert_eq!(- result["models"][0]["options"],- json!([- {"id": "reasoning_effort", "name": "Reasoning", "default": "high",- "values": [{"id": "medium", "name": "Medium"}, {"id": "high", "name": "High"}]},- {"id": "fast", "name": "fast", "default": "true",- "values": [{"id": "false", "name": "Off"}, {"id": "true", "name": "true"}]}- ])- );- assert_eq!(result["models"][1]["options"], json!([]));- }-- #[test]- fn model_config_prefers_category_and_ignores_unknown_types() {- let session = json!({"configOptions": [- {"id": "model", "type": "boolean"},- {"id": "models", "type": "select"},- {"id": "engine", "category": "model", "type": "select"}- ]});- assert_eq!(model_config(&session).unwrap()["id"], "engine");- assert!(model_config(&json!({"configOptions": [{"id": "model", "type": "boolean"}]})).is_none());- }-fn cmd() -> Cmd {Cmd { program: "npx -y pkg@1".into(), args: "--acp".into() }}diff --git a/host/src/agent/auth/agent.rs b/host/src/agent/auth/agent.rsnew file mode 100644index 00000000..c2c6aceb--- /dev/null+++ b/host/src/agent/auth/agent.rs@@ -0,0 +1,148 @@+//! Starting an agent for a check, and letting it sign itself in.++use super::{check, launch_env, probe_dir};+use crate::agent::acp::{self, Acp, Incoming};+use crate::agent::backends;+use crate::agent::registry::{Candidate, Cmd};+use crate::store::Store;+use anyhow::{Context, Result, anyhow, bail};+use serde_json::{Value, json};+use std::ffi::OsStr;+use std::sync::Arc;+use std::time::Duration;+use tokio::sync::mpsc;++/// Starts `backend` and completes `initialize`, trying each way to launch it.+/// The agent's inbox must stay open: the reader stops when nobody listens.+pub(super) type Started = (Arc<Acp>, mpsc::UnboundedReceiver<Incoming>, Value, Cmd);++pub(super) async fn start(store: &Store, backend: &str) -> Result<Started> {+ let mut candidates = backends::launch_candidates(backend)?;+ // The installed CLI alone when there is one: resolving the registry build can mean a long download.+ if matches!(candidates.first(), Some(Candidate::Ready(_))) {+ candidates.truncate(1);+ }+ let env = launch_env(store, backend)?;+ let dir = probe_dir();+ tokio::fs::create_dir_all(&dir).await?;+ let mut last = None;+ let count = candidates.len();+ for (i, candidate) in candidates.into_iter().enumerate() {+ // A first `npx` run downloads the package: give the last candidate time.+ let budget = Duration::from_secs(if i + 1 < count { 20 } else { 180 });+ let cmd = match candidate.resolve(|_| {}).await {+ Ok(cmd) => cmd,+ Err(e) => {+ last = Some(e);+ continue;+ }+ };+ let (acp, mut rx) = match Acp::spawn(&cmd.acp(), &dir.to_string_lossy(), &env) {+ Ok(v) => v,+ Err(e) => {+ last = Some(e);+ continue;+ }+ };+ let init = acp.request(+ "initialize",+ json!({+ "protocolVersion": 1,+ "clientCapabilities": {+ "fs": {"readTextFile": false, "writeTextFile": false},+ "terminal": false,+ // Ask for terminal sign-in methods (spec field and the older `_meta` flag),+ // and for plain models with options, as bot sessions do (`bot::start_agent`).+ "auth": {"terminal": true},+ "_meta": {"terminal-auth": true, "parameterizedModelPicker": true},+ },+ "clientInfo": {"name": "codync", "title": "Codync", "version": env!("CARGO_PKG_VERSION")},+ }),+ );+ match tokio::time::timeout(budget, init).await {+ Ok(Ok(init)) => return Ok((acp, rx, init, cmd)),+ Ok(Err(e)) => {+ let why = std::iter::from_fn(|| rx.try_recv().ok()).find_map(|inc| match inc {+ Incoming::Closed { stderr_tail } => stderr_reason(&stderr_tail),+ _ => None,+ });+ last = Some(match why {+ Some(why) => e.context(why),+ None => e,+ });+ }+ Err(_) => last = Some(anyhow!("the agent didn't start within {}s", budget.as_secs())),+ }+ acp.kill().await;+ }+ Err(last.unwrap_or_else(|| anyhow!("couldn't start the agent")))+}++/// The stderr line that says why the agent quit: an error line, else the last one that isn't a pretty-printed Node+/// error's closing brace.+fn stderr_reason(stderr_tail: &str) -> Option<String> {+ let lines: Vec<&str> = stderr_tail.lines().map(str::trim).filter(|line| !line.is_empty()).collect();+ lines+ .iter()+ .rev()+ .find(|line| line.contains("Error"))+ .or_else(|| lines.iter().rev().find(|line| !matches!(**line, "}" | "{" | "}," | "]" | "[")))+ .map(|line| (*line).to_owned())+}++/// Lets the agent sign itself in (it usually opens a browser on this computer).+pub async fn authenticate(store: &Store, backend: &str, method: &str) -> Result<Value> {+ let (acp, mut inbox, _, _) = start(store, backend).await?;+ let res = tokio::time::timeout(Duration::from_secs(10 * 60), sign_in(&acp, &mut inbox, method)).await;+ acp.kill().await;+ match res {+ Ok(r) => {+ r.context("signing in")?;+ }+ Err(_) => bail!("Sign-in didn't finish within 10 minutes."),+ }+ let mut status = check(store, backend).await?;+ // Completing `authenticate` is the proof for an agent whose session doesn't check the login.+ if !backends::session_proves_sign_in(backend) {+ backends::set_signed_in(backend, Some(true));+ status["signedIn"] = true.into();+ }+ Ok(status)+}++/// The agent's answer to `authenticate`. A headless CLI that only posts its sign-in page (`WorkBuddy`'s) gets it+/// opened here, once; what it asks of us meanwhile is refused.+async fn sign_in(acp: &Acp, inbox: &mut mpsc::UnboundedReceiver<Incoming>, method: &str) -> Result<Value> {+ let request = acp.request("authenticate", json!({"methodId": method}));+ tokio::pin!(request);+ let mut opened = false;+ loop {+ tokio::select! {+ result = &mut request => return result,+ incoming = inbox.recv() => match incoming {+ Some(Incoming::Request { id, .. }) => acp.respond_error(id, -32601, "not supported during sign-in").await?,+ Some(Incoming::Closed { .. }) | None => bail!("the agent closed during sign-in"),+ Some(notification) => {+ if !opened && let Some(url) = acp::codebuddy::sign_in_url(¬ification) {+ opened = true;+ if !crate::shell::open(OsStr::new(&url)) {+ tracing::warn!("couldn't open the sign-in page");+ }+ }+ }+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn stderr_reason_skips_a_closing_brace() {+ let tail = "Error: Cannot find module '../dist/codebuddy'\nRequire stack:\n- /cli/bin/codebuddy\n code: 'MODULE_NOT_FOUND'\n}\n";+ assert_eq!(stderr_reason(tail).as_deref(), Some("Error: Cannot find module '../dist/codebuddy'"));+ assert_eq!(stderr_reason("agent said no\n").as_deref(), Some("agent said no"));+ }+}diff --git a/host/src/agent/auth/models.rs b/host/src/agent/auth/models.rsnew file mode 100644index 00000000..f4466307--- /dev/null+++ b/host/src/agent/auth/models.rs@@ -0,0 +1,197 @@+//! The models an agent offers, read from a session it opens for that alone.++use super::{probe_dir, start, text};+use crate::agent::acp::Incoming;+use crate::store::Store;+use anyhow::{Context, Result, bail};+use serde_json::{Value, json};+use std::time::Duration;++/// Discover the agent's advertised models in an isolated, prompt-free session.+/// This uses the same credentials as actual bot sessions and never reads project files.+pub async fn models(store: &Store, backend: &str) -> Result<Value> {+ let (acp, mut inbox, _, _) = start(store, backend).await?;+ let result = tokio::time::timeout(Duration::from_secs(60), async {+ let request = acp.request("session/new", json!({"cwd": probe_dir(), "mcpServers": []}));+ tokio::pin!(request);+ let session = loop {+ tokio::select! {+ result = &mut request => break result?,+ incoming = inbox.recv() => match incoming {+ Some(Incoming::Request { id, .. }) => {+ acp.respond_error(id, -32601, "not supported during model discovery").await?;+ }+ Some(Incoming::Notification { .. }) => {}+ Some(Incoming::Closed { .. }) | None => bail!("agent closed during model discovery"),+ }+ }+ };+ // Cursor lists each model's options (effort, fast…) only through its own method.+ let options = if backend == "cursor" {+ acp.request("cursor/list_available_models", json!({})).await.unwrap_or_default()+ } else {+ Value::Null+ };+ Ok((session, options))+ })+ .await;+ acp.kill().await;+ let (session, options) = result.context("the agent's model list timed out")??;+ Ok(model_catalog(&session, &options))+}++/// IDs are agent-defined: use the category, with legacy conventional IDs as a fallback.+pub(crate) fn model_config(session: &Value) -> Option<&Value> {+ let options = session["configOptions"].as_array()?;+ let is_select = |v: &&Value| v["type"] == "select" || v.get("type").is_none();+ options+ .iter()+ .filter(is_select)+ .find(|v| v["category"] == "model")+ .or_else(|| options.iter().filter(is_select).find(|v| v["id"] == "model" || v["id"] == "models"))+}++/// The model ids the agent lists, in its order.+pub(crate) fn model_ids(session: &Value) -> Vec<String> {+ let catalog = model_catalog(session, &Value::Null);+ catalog["models"].as_array().into_iter().flatten().filter_map(|m| text(&m["id"])).collect()+}++/// `{models: [{id, name, description, options}], currentModelId, fastMode}`; `options` is+/// Cursor's `cursor/list_available_models` answer (`Null` for other agents).+fn model_catalog(session: &Value, options: &Value) -> Value {+ fn collect(options: &Value, out: &mut Vec<Value>) {+ for option in options.as_array().into_iter().flatten() {+ if option["options"].is_array() {+ collect(&option["options"], out);+ } else if let Some(id) = text(&option["value"])+ && !out.iter().any(|v| v["id"] == id)+ {+ out.push(json!({"id": id, "name": text(&option["name"]).unwrap_or(id),+ "description": text(&option["description"])}));+ }+ }+ }+ let mut models = Vec::new();+ let current = if let Some(config) = model_config(session) {+ collect(&config["options"], &mut models);+ text(&config["currentValue"])+ } else {+ for model in session["models"]["availableModels"].as_array().into_iter().flatten() {+ if let Some(id) = text(&model["modelId"])+ && !models.iter().any(|v| v["id"] == id)+ {+ models.push(json!({"id": id, "name": text(&model["name"]).unwrap_or(id),+ "description": text(&model["description"])}));+ }+ }+ text(&session["models"]["currentModelId"])+ };+ for model in &mut models {+ model["options"] = json!(model_options(options, model["id"].as_str().unwrap_or_default()));+ }+ json!({"models": models, "currentModelId": current,+ "fastMode": crate::agent::config::fast_mode_config(session).is_some()})+}++/// One model's options as `[{id, name, values: [{id, name}], default}]`, from Cursor's+/// `{models: [{value, configOptions}]}` (ACP select config options).+fn model_options(options: &Value, model: &str) -> Vec<Value> {+ let entry = options["models"].as_array().into_iter().flatten().find(|m| m["value"] == model);+ entry+ .and_then(|m| m["configOptions"].as_array())+ .into_iter()+ .flatten()+ .filter(|o| o["type"] == "select")+ .filter_map(|o| {+ let id = text(&o["id"])?;+ let values: Vec<Value> = o["options"]+ .as_array()?+ .iter()+ .filter_map(|v| {+ let value = text(&v["value"])?;+ Some(json!({"id": value, "name": text(&v["name"]).unwrap_or(value)}))+ })+ .collect();+ Some(json!({"id": id, "name": text(&o["name"]).unwrap_or(id), "values": values,+ "default": text(&o["currentValue"])}))+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn model_catalog_reads_grouped_config_and_preserves_agent_ids() {+ let session = json!({"configOptions": [{+ "id": "provider-model", "category": "model", "type": "select", "currentValue": "m2",+ "options": [{"group": "a", "options": [+ {"value": "m1", "name": "First"}, {"value": "m2", "name": "Second"},+ {"value": "m1", "name": "Duplicate"}+ ]}]+ }], "models": {"availableModels": [{"modelId": "legacy", "name": "Legacy"}]}});+ assert_eq!(model_config(&session).unwrap()["id"], "provider-model");+ let result = model_catalog(&session, &Value::Null);+ assert_eq!(result["currentModelId"], "m2");+ assert_eq!(result["models"].as_array().unwrap().len(), 2);+ assert_eq!(result["models"][0]["id"], "m1");+ assert_eq!(result["models"][1]["name"], "Second");+ assert_eq!(result["models"][1]["options"], json!([]));+ assert_eq!(model_ids(&session), ["m1", "m2"]);+ }++ #[test]+ fn model_catalog_reads_legacy_and_missing_lists() {+ let result = model_catalog(+ &json!({"models": {+ "currentModelId": "a", "availableModels": [+ {"modelId": "a", "name": "Agent model", "description": "Available here"},+ {"name": "No ID"}+ ]+ }}),+ &Value::Null,+ );+ assert_eq!(result["models"].as_array().unwrap().len(), 1);+ assert_eq!(result["models"][0]["description"], "Available here");+ assert_eq!(+ model_catalog(&json!({}), &Value::Null),+ json!({"models": [], "currentModelId": null, "fastMode": false})+ );+ }++ #[test]+ fn model_catalog_adds_cursor_model_options() {+ let session = json!({"configOptions": [{"id": "model", "category": "model", "type": "select",+ "currentValue": "grok-4.7", "options": [{"value": "grok-4.7", "name": "Grok 4.7"}, {"value": "auto"}]}]});+ let listed = json!({"models": [{"value": "grok-4.7", "name": "Grok 4.7", "configOptions": [+ {"id": "reasoning_effort", "name": "Reasoning", "category": "thought_level", "type": "select",+ "currentValue": "high", "options": [{"value": "medium", "name": "Medium"}, {"value": "high", "name": "High"}]},+ {"id": "fast", "type": "select", "currentValue": "true", "options": [{"value": "false", "name": "Off"}, {"value": "true"}]},+ {"id": "verbose", "type": "boolean"}+ ]}]});+ let result = model_catalog(&session, &listed);+ assert_eq!(+ result["models"][0]["options"],+ json!([+ {"id": "reasoning_effort", "name": "Reasoning", "default": "high",+ "values": [{"id": "medium", "name": "Medium"}, {"id": "high", "name": "High"}]},+ {"id": "fast", "name": "fast", "default": "true",+ "values": [{"id": "false", "name": "Off"}, {"id": "true", "name": "true"}]}+ ])+ );+ assert_eq!(result["models"][1]["options"], json!([]));+ }++ #[test]+ fn model_config_prefers_category_and_ignores_unknown_types() {+ let session = json!({"configOptions": [+ {"id": "model", "type": "boolean"},+ {"id": "models", "type": "select"},+ {"id": "engine", "category": "model", "type": "select"}+ ]});+ assert_eq!(model_config(&session).unwrap()["id"], "engine");+ assert!(model_config(&json!({"configOptions": [{"id": "model", "type": "boolean"}]})).is_none());+ }+}diff --git a/host/src/agent/backends.rs b/host/src/agent/backends.rsindex 598159d4..36cf2350 100644--- a/host/src/agent/backends.rs+++ b/host/src/agent/backends.rs@@ -14,11 +14,14 @@ use serde_json::{Value, json};use std::collections::HashSet;use std::path::Path;+mod catalog;mod search_path;mod sign_in;+mod workbuddy;+pub use catalog::HARNESSES;pub use search_path::{hydrate_path, on_path, which};pub use sign_in::{SignInCheck, cli_signed_in, refresh_sign_in, set_signed_in, signed_in};-use sign_in::{claude_signed_in, exit_ok, qoder_signed_in, says_logged_in};+pub use workbuddy::{apply_process_env, session_proves_sign_in};pub struct Harness {pub id: &'static str,@@ -64,376 +67,6 @@ impl Install {}}-pub const HARNESSES: &[Harness] = &[- Harness {- id: "claude",- name: "Claude Code",- bins: &["claude"],- local: None,- registry: Some("claude-acp"),- setup: "Install Claude Code and run `claude auth login`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://claude.ai/install.sh | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://claude.ai/install.ps1 | iex\"",- }),- login: Some("{bin} auth login"),- signed_in: Some(SignInCheck { args: "auth status", ok: claude_signed_in }),- },- Harness {- id: "codex",- name: "Codex",- bins: &["codex"],- local: None,- registry: Some("codex-acp"),- setup: "Install Codex CLI and run `codex login --device-auth`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://chatgpt.com/codex/install.sh | sh",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://chatgpt.com/codex/install.ps1 | iex\"",- }),- login: Some("{bin} login --device-auth"),- signed_in: Some(SignInCheck { args: "login status", ok: exit_ok }),- },- Harness {- id: "cursor",- name: "Cursor",- bins: &["cursor-agent", "agent"],- local: Some("{bin} acp"),- registry: Some("cursor"),- setup: "Install Cursor CLI (curl https://cursor.com/install -fsS | bash) and run `cursor-agent login`.",- install: Some(Install::Scripts {- unix: "curl https://cursor.com/install -fsS | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm 'https://cursor.com/install?win32=true' | iex\"",- }),- login: Some("NO_OPEN_BROWSER=1 {bin} login"),- signed_in: Some(SignInCheck { args: "status", ok: says_logged_in }),- },- Harness {- id: "pi",- name: "Pi",- bins: &["pi"],- local: None,- registry: Some("pi-acp"),- setup: "Install pi (npm install -g @earendil-works/pi-coding-agent), run `pi` and type /login.",- install: Some(Install::Npm("@earendil-works/pi-coding-agent")),- login: Some("{bin}"),- signed_in: None,- },- Harness {- id: "omp",- name: "oh-my-pi",- bins: &["omp"],- local: Some("{bin} acp"),- registry: None,- setup: "Install oh-my-pi (curl -fsSL https://omp.sh/install | sh -s -- --binary) and run `omp login`.",- install: Some(Install::Scripts {- // The prebuilt binary: by default the scripts build through any Bun on PATH and stop when it's older than they need.- unix: "curl -fsSL https://omp.sh/install | sh -s -- --binary",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"& ([scriptblock]::Create((irm https://omp.sh/install.ps1))) -Binary\"",- }),- login: Some("{bin} login"),- signed_in: None,- },- Harness {- id: "opencode",- name: "OpenCode",- bins: &["opencode"],- local: Some("{bin} acp"),- registry: Some("opencode"),- setup: "Install OpenCode (curl -fsSL https://opencode.ai/install | bash) and run `opencode auth login`.",- install: Some(Install::Script("curl -fsSL https://opencode.ai/install | bash")),- login: Some("{bin} auth login"),- signed_in: None,- },- Harness {- id: "grok",- name: "Grok Build",- bins: &["grok"],- local: Some("{bin} agent stdio"),- registry: Some("grok-build"),- setup: "Install Grok Build (curl -fsSL https://x.ai/cli/install.sh | bash) and run `grok login --device-auth`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://x.ai/cli/install.sh | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://x.ai/cli/install.ps1 | iex\"",- }),- login: Some("{bin} login --device-auth"),- signed_in: None,- },- Harness {- id: "gemini",- name: "Gemini CLI",- bins: &["gemini"],- local: Some("{bin} --acp"),- registry: Some("gemini"),- setup: "Install Gemini CLI (npm install -g @google/gemini-cli) and run `gemini` to sign in with Google.",- install: Some(Install::Npm("@google/gemini-cli")),- login: Some("NO_BROWSER=true {bin}"),- signed_in: None,- },- Harness {- id: "copilot",- name: "GitHub Copilot",- bins: &["copilot"],- local: Some("{bin} --acp --stdio"),- registry: Some("github-copilot-cli"),- setup: "Install Copilot CLI (curl -fsSL https://gh.io/copilot-install | bash) and run `copilot login`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://gh.io/copilot-install | bash",- windows: "winget install --id GitHub.Copilot -e",- }),- login: Some("{bin} login --device-code"),- signed_in: None,- },- Harness {- id: "qwen",- name: "Qwen Code",- bins: &["qwen"],- local: Some("{bin} --acp"),- registry: Some("qwen-code"),- setup: "Install Qwen Code (its standalone installer), run `qwen` and type /auth.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.sh | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.ps1 | iex\"",- }),- login: Some("{bin}"),- signed_in: None,- },- Harness {- id: "hermes",- name: "Hermes Agent",- bins: &["hermes"],- local: Some("{bin} acp"),- registry: None,- setup: "Install Hermes Agent and run `hermes acp --setup` to choose a provider and model.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"iex (irm https://hermes-agent.nousresearch.com/install.ps1)\"",- }),- login: Some("{bin} acp --setup"),- signed_in: None,- },- Harness {- id: "goose",- name: "goose",- bins: &["goose"],- local: Some("{bin} acp"),- registry: Some("goose"),- setup: "Install goose and run `goose configure`.",- install: Some(Install::Script(- "curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh | bash",- )),- login: Some("{bin} configure"),- signed_in: None,- },- Harness {- id: "kimi",- name: "Kimi Code",- bins: &["kimi"],- local: Some("{bin} acp"),- registry: Some("kimi"),- setup: "Install Kimi Code (curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash) and run `kimi login`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://code.kimi.com/kimi-code/install.ps1 | iex\"",- }),- login: Some("{bin} login"),- signed_in: None,- },- Harness {- id: "droid",- name: "Factory Droid",- bins: &["droid"],- local: Some("{bin} exec --output-format acp-daemon"),- registry: Some("factory-droid"),- setup: "Install Droid (curl -fsSL https://app.factory.ai/cli | sh) and sign in with `droid`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://app.factory.ai/cli | sh",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://app.factory.ai/cli/windows | iex\"",- }),- login: Some("{bin}"),- signed_in: None,- },- Harness {- id: "amp",- name: "Amp",- bins: &["amp"],- local: None,- registry: Some("amp-acp"),- setup: "Install Amp (curl -fsSL https://ampcode.com/install.sh | bash) and run `amp login`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://ampcode.com/install.sh | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://ampcode.com/install.ps1 | iex\"",- }),- login: Some("{bin} login"),- signed_in: None,- },- Harness {- id: "kilo",- name: "Kilo",- bins: &["kilo"],- local: Some("{bin} acp"),- registry: Some("kilo"),- setup: "Install Kilo CLI (npm install -g @kilocode/cli) and run `kilo auth login`.",- install: Some(Install::Npm("@kilocode/cli")),- login: Some("{bin} auth login"),- signed_in: Some(SignInCheck { args: "profile --json", ok: exit_ok }),- },- Harness {- id: "cline",- name: "Cline",- bins: &["cline"],- local: Some("{bin} --acp"),- registry: Some("cline"),- setup: "Install Cline CLI (npm install -g cline) and run `cline auth`.",- install: Some(Install::Npm("cline")),- login: Some("{bin} auth"),- signed_in: None,- },- Harness {- id: "auggie",- name: "Auggie",- bins: &["auggie"],- local: Some("{bin} --acp"),- registry: Some("auggie"),- setup: "Install Auggie (npm install -g @augmentcode/auggie) and run `auggie login`.",- install: Some(Install::Npm("@augmentcode/auggie")),- login: Some("{bin} login"),- signed_in: Some(SignInCheck { args: "account status", ok: exit_ok }),- },- Harness {- id: "vibe",- name: "Mistral Vibe",- bins: &["vibe-acp", "vibe"],- local: None,- registry: Some("mistral-vibe"),- setup: "Install Mistral Vibe (curl -LsSf https://mistral.ai/vibe/install.sh | bash) and run `vibe --setup`.",- install: Some(Install::Script("curl -LsSf https://mistral.ai/vibe/install.sh | bash")),- login: Some("vibe --setup"),- signed_in: None,- },- Harness {- id: "kiro",- name: "Kiro CLI",- bins: &["kiro-cli"],- local: Some("{bin} acp"),- registry: None,- setup: "Install Kiro CLI (curl -fsSL https://cli.kiro.dev/install | bash) and run `kiro-cli login`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://cli.kiro.dev/install | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm 'https://cli.kiro.dev/install.ps1' | iex\"",- }),- login: Some("{bin} login"),- signed_in: None,- },- Harness {- id: "devin",- name: "Devin",- bins: &["devin"],- local: Some("{bin} acp"),- registry: Some("devin"),- setup: "Install the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) and run `devin auth login`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://cli.devin.ai/install.sh | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://cli.devin.ai/install.ps1 | iex\"",- }),- login: Some("{bin} auth login"),- signed_in: None,- },- Harness {- id: "qoder",- name: "Qoder CLI",- bins: &["qodercli"],- local: Some("{bin} --acp"),- registry: Some("qoder"),- setup: "Install Qoder CLI (curl -fsSL https://qoder.com/install | bash) and run `qodercli login`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://qoder.com/install | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://qoder.com/install.ps1 | iex\"",- }),- login: Some("{bin} login"),- signed_in: Some(SignInCheck { args: "status -o json", ok: qoder_signed_in }),- },- Harness {- id: "codebuddy",- name: "CodeBuddy Code",- bins: &["codebuddy", "cbc"],- local: Some("{bin} --acp"),- registry: Some("codebuddy-code"),- setup: "Install CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) and sign in with `codebuddy`.",- install: Some(Install::Npm("@tencent-ai/codebuddy-code")),- login: Some("{bin}"),- signed_in: None,- },- Harness {- id: "minimax",- name: "MiniMax Code",- bins: &["mcode"],- local: Some("{bin} acp"),- registry: Some("minimax-code"),- setup: "Install MiniMax Code (npm install -g @minimax-ai/code) and run `mcode login`.",- install: Some(Install::Npm("@minimax-ai/code")),- login: Some("{bin} login"),- signed_in: None,- },- Harness {- id: "junie",- name: "Junie",- bins: &["junie"],- local: Some("{bin} --acp=true"),- registry: Some("junie"),- setup: "Install Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) and sign in with `junie`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://junie.jetbrains.com/install.sh | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"iex (irm 'https://junie.jetbrains.com/install.ps1')\"",- }),- login: Some("{bin}"),- signed_in: None,- },- Harness {- id: "antigravity",- name: "Google Antigravity",- bins: &["agy"],- local: None,- registry: Some("antigravity-acp"),- setup: "Install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash), then sign in from Codync with Log in with Google.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://antigravity.google/cli/install.sh | bash",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://antigravity.google/cli/install.ps1 | iex\"",- }),- // Signing in with `agy` doesn't sign in its ACP server, which keeps its own sign-in- // (`~/.gemini/antigravity-acp/settings.json`): only the server's own methods do.- login: None,- signed_in: None,- },- Harness {- id: "cortex",- name: "Cortex Code",- bins: &["cortex"],- local: Some("{bin} acp serve"),- registry: Some("cortex-code"),- setup: "Install Cortex Code (curl -LsS https://ai.snowflake.com/static/cc-scripts/install.sh | sh) and set up a connection with `cortex`.",- install: Some(Install::Scripts {- unix: "curl -LsS https://ai.snowflake.com/static/cc-scripts/install.sh | sh",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://ai.snowflake.com/static/cc-scripts/install.ps1 | iex\"",- }),- login: Some("{bin}"),- signed_in: None,- },- Harness {- id: "poolside",- name: "Poolside",- bins: &["pool"],- local: Some("{bin} acp"),- registry: Some("poolside"),- setup: "Install Poolside (curl -fsSL https://downloads.poolside.ai/pool/install.sh | sh) and run `pool login`.",- install: Some(Install::Scripts {- unix: "curl -fsSL https://downloads.poolside.ai/pool/install.sh | sh",- windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://downloads.poolside.ai/pool/install.ps1 | iex\"",- }),- login: Some("{bin} login"),- signed_in: None,- },-];-pub fn harness(id: &str) -> Option<&'static Harness> {HARNESSES.iter().find(|h| h.id == id)}@@ -445,12 +78,14 @@ pub fn list() -> Vec<Value> {let registry = registry::agents();let mut out: Vec<Value> = HARNESSES.iter()+ .filter(|h| workbuddy::offered(h.id)).map(|h| {- let path = h.bins.iter().find_map(|b| which(b));+ let path = installed_cli(h);let reg = h.registry.and_then(|id| registry.iter().find(|a| a["id"] == id));let native = path.is_some() && h.local.is_some();let runnable = native || reg.is_some_and(|a| registry::launch_kind(a).is_some());- let node = if native { None } else { reg.filter(|a| registry::needs_node(a)).and_then(|_| node::state()) };+ let needs_node = if native { workbuddy::runs_on_node(h.id) } else { reg.is_some_and(registry::needs_node) };+ let node = if needs_node { node::state() } else { None };json!({"id": h.id,"name": h.name,@@ -496,6 +131,10 @@ pub fn list() -> Vec<Value> {/// `program` is some other harness's CLI (not `backend`'s own).pub fn belongs_to_other(backend: &str, program: &str) -> bool {+ // WorkBuddy's CLI shares CodeBuddy Code's file name. The app path decides which one it is.+ if workbuddy::is_cli(program) {+ return backend != "workbuddy";+ }let name = Path::new(program).file_name().and_then(|n| n.to_str()).unwrap_or(program);let own = |h: &Harness| h.id == backend || h.registry == Some(backend);HARNESSES.iter().any(|h| !own(h) && h.bins.contains(&name))@@ -539,9 +178,7 @@ fn registry_cli(h: &Harness) -> Option<Value> {/// Codync's own sign-in command for `id` can run now.pub fn login_available(id: &str) -> bool {harness(id).is_some_and(|h| {- h.login.is_some_and(|login| {- h.bins.iter().any(|b| on_path(b)) || !login.contains("{bin}") || registry_cli(h).is_some()- })+ h.login.is_some_and(|login| installed_cli(h).is_some() || !login.contains("{bin}") || registry_cli(h).is_some())})}@@ -550,7 +187,7 @@ pub async fn login_command(id: &str) -> anyhow::Result<String> {let (h, login) = harness(id).and_then(|h| h.login.map(|login| (h, login))).ok_or_else(|| anyhow::anyhow!("no sign-in command for {id}"))?;- let bin = match h.bins.iter().find_map(|b| which(b)) {+ let bin = match installed_cli(h) {Some(p) => shell::quote(&p.to_string_lossy()),None => match registry_cli(h) {Some(agent) => registry::command(&agent, |_| {}).await?.program,@@ -561,11 +198,16 @@ pub async fn login_command(id: &str) -> anyhow::Result<String> {Ok(login.replace("{bin}", &bin))}+/// Where this harness's CLI is installed: on `PATH`, or inside the `WorkBuddy` app.+fn installed_cli(h: &Harness) -> Option<std::path::PathBuf> {+ h.bins.iter().find_map(|b| which(b)).or_else(|| (h.id == "workbuddy").then(workbuddy::find).flatten())+}+/// The installed CLI's own ACP mode, if it has one and it's installed.fn local_candidate(id: &str) -> Option<registry::Cmd> {let h = harness(id)?;let template = h.local?;- let path = h.bins.iter().find_map(|b| which(b))?;+ let path = installed_cli(h)?;let args = template.strip_prefix("{bin}").unwrap_or(template).trim().to_owned();Some(registry::Cmd { program: shell::quote(&path.to_string_lossy()), args })}diff --git a/host/src/agent/backends/catalog.rs b/host/src/agent/backends/catalog.rsnew file mode 100644index 00000000..136a5e64--- /dev/null+++ b/host/src/agent/backends/catalog.rs@@ -0,0 +1,387 @@+//! Every harness Codync knows by name: its CLI, its ACP mode and registry build, and how it's set up and signed in.++use super::sign_in::{claude_signed_in, exit_ok, qoder_signed_in, says_logged_in};+use super::{Harness, Install, SignInCheck};++pub const HARNESSES: &[Harness] = &[+ Harness {+ id: "claude",+ name: "Claude Code",+ bins: &["claude"],+ local: None,+ registry: Some("claude-acp"),+ setup: "Install Claude Code and run `claude auth login`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://claude.ai/install.sh | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://claude.ai/install.ps1 | iex\"",+ }),+ login: Some("{bin} auth login"),+ signed_in: Some(SignInCheck { args: "auth status", ok: claude_signed_in }),+ },+ Harness {+ id: "codex",+ name: "Codex",+ bins: &["codex"],+ local: None,+ registry: Some("codex-acp"),+ setup: "Install Codex CLI and run `codex login --device-auth`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://chatgpt.com/codex/install.sh | sh",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://chatgpt.com/codex/install.ps1 | iex\"",+ }),+ login: Some("{bin} login --device-auth"),+ signed_in: Some(SignInCheck { args: "login status", ok: exit_ok }),+ },+ Harness {+ id: "cursor",+ name: "Cursor",+ bins: &["cursor-agent", "agent"],+ local: Some("{bin} acp"),+ registry: Some("cursor"),+ setup: "Install Cursor CLI (curl https://cursor.com/install -fsS | bash) and run `cursor-agent login`.",+ install: Some(Install::Scripts {+ unix: "curl https://cursor.com/install -fsS | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm 'https://cursor.com/install?win32=true' | iex\"",+ }),+ login: Some("NO_OPEN_BROWSER=1 {bin} login"),+ signed_in: Some(SignInCheck { args: "status", ok: says_logged_in }),+ },+ Harness {+ id: "pi",+ name: "Pi",+ bins: &["pi"],+ local: None,+ registry: Some("pi-acp"),+ setup: "Install pi (npm install -g @earendil-works/pi-coding-agent), run `pi` and type /login.",+ install: Some(Install::Npm("@earendil-works/pi-coding-agent")),+ login: Some("{bin}"),+ signed_in: None,+ },+ Harness {+ id: "omp",+ name: "oh-my-pi",+ bins: &["omp"],+ local: Some("{bin} acp"),+ registry: None,+ setup: "Install oh-my-pi (curl -fsSL https://omp.sh/install | sh -s -- --binary) and run `omp login`.",+ install: Some(Install::Scripts {+ // The prebuilt binary: by default the scripts build through any Bun on PATH and stop when it's older than they need.+ unix: "curl -fsSL https://omp.sh/install | sh -s -- --binary",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"& ([scriptblock]::Create((irm https://omp.sh/install.ps1))) -Binary\"",+ }),+ login: Some("{bin} login"),+ signed_in: None,+ },+ Harness {+ id: "opencode",+ name: "OpenCode",+ bins: &["opencode"],+ local: Some("{bin} acp"),+ registry: Some("opencode"),+ setup: "Install OpenCode (curl -fsSL https://opencode.ai/install | bash) and run `opencode auth login`.",+ install: Some(Install::Script("curl -fsSL https://opencode.ai/install | bash")),+ login: Some("{bin} auth login"),+ signed_in: None,+ },+ Harness {+ id: "grok",+ name: "Grok Build",+ bins: &["grok"],+ local: Some("{bin} agent stdio"),+ registry: Some("grok-build"),+ setup: "Install Grok Build (curl -fsSL https://x.ai/cli/install.sh | bash) and run `grok login --device-auth`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://x.ai/cli/install.sh | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://x.ai/cli/install.ps1 | iex\"",+ }),+ login: Some("{bin} login --device-auth"),+ signed_in: None,+ },+ Harness {+ id: "gemini",+ name: "Gemini CLI",+ bins: &["gemini"],+ local: Some("{bin} --acp"),+ registry: Some("gemini"),+ setup: "Install Gemini CLI (npm install -g @google/gemini-cli) and run `gemini` to sign in with Google.",+ install: Some(Install::Npm("@google/gemini-cli")),+ login: Some("NO_BROWSER=true {bin}"),+ signed_in: None,+ },+ Harness {+ id: "copilot",+ name: "GitHub Copilot",+ bins: &["copilot"],+ local: Some("{bin} --acp --stdio"),+ registry: Some("github-copilot-cli"),+ setup: "Install Copilot CLI (curl -fsSL https://gh.io/copilot-install | bash) and run `copilot login`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://gh.io/copilot-install | bash",+ windows: "winget install --id GitHub.Copilot -e",+ }),+ login: Some("{bin} login --device-code"),+ signed_in: None,+ },+ Harness {+ id: "qwen",+ name: "Qwen Code",+ bins: &["qwen"],+ local: Some("{bin} --acp"),+ registry: Some("qwen-code"),+ setup: "Install Qwen Code (its standalone installer), run `qwen` and type /auth.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.sh | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.ps1 | iex\"",+ }),+ login: Some("{bin}"),+ signed_in: None,+ },+ Harness {+ id: "hermes",+ name: "Hermes Agent",+ bins: &["hermes"],+ local: Some("{bin} acp"),+ registry: None,+ setup: "Install Hermes Agent and run `hermes acp --setup` to choose a provider and model.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"iex (irm https://hermes-agent.nousresearch.com/install.ps1)\"",+ }),+ login: Some("{bin} acp --setup"),+ signed_in: None,+ },+ Harness {+ id: "goose",+ name: "goose",+ bins: &["goose"],+ local: Some("{bin} acp"),+ registry: Some("goose"),+ setup: "Install goose and run `goose configure`.",+ install: Some(Install::Script(+ "curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh | bash",+ )),+ login: Some("{bin} configure"),+ signed_in: None,+ },+ Harness {+ id: "kimi",+ name: "Kimi Code",+ bins: &["kimi"],+ local: Some("{bin} acp"),+ registry: Some("kimi"),+ setup: "Install Kimi Code (curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash) and run `kimi login`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://code.kimi.com/kimi-code/install.ps1 | iex\"",+ }),+ login: Some("{bin} login"),+ signed_in: None,+ },+ Harness {+ id: "droid",+ name: "Factory Droid",+ bins: &["droid"],+ local: Some("{bin} exec --output-format acp-daemon"),+ registry: Some("factory-droid"),+ setup: "Install Droid (curl -fsSL https://app.factory.ai/cli | sh) and sign in with `droid`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://app.factory.ai/cli | sh",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://app.factory.ai/cli/windows | iex\"",+ }),+ login: Some("{bin}"),+ signed_in: None,+ },+ Harness {+ id: "amp",+ name: "Amp",+ bins: &["amp"],+ local: None,+ registry: Some("amp-acp"),+ setup: "Install Amp (curl -fsSL https://ampcode.com/install.sh | bash) and run `amp login`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://ampcode.com/install.sh | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://ampcode.com/install.ps1 | iex\"",+ }),+ login: Some("{bin} login"),+ signed_in: None,+ },+ Harness {+ id: "kilo",+ name: "Kilo",+ bins: &["kilo"],+ local: Some("{bin} acp"),+ registry: Some("kilo"),+ setup: "Install Kilo CLI (npm install -g @kilocode/cli) and run `kilo auth login`.",+ install: Some(Install::Npm("@kilocode/cli")),+ login: Some("{bin} auth login"),+ signed_in: Some(SignInCheck { args: "profile --json", ok: exit_ok }),+ },+ Harness {+ id: "cline",+ name: "Cline",+ bins: &["cline"],+ local: Some("{bin} --acp"),+ registry: Some("cline"),+ setup: "Install Cline CLI (npm install -g cline) and run `cline auth`.",+ install: Some(Install::Npm("cline")),+ login: Some("{bin} auth"),+ signed_in: None,+ },+ Harness {+ id: "auggie",+ name: "Auggie",+ bins: &["auggie"],+ local: Some("{bin} --acp"),+ registry: Some("auggie"),+ setup: "Install Auggie (npm install -g @augmentcode/auggie) and run `auggie login`.",+ install: Some(Install::Npm("@augmentcode/auggie")),+ login: Some("{bin} login"),+ signed_in: Some(SignInCheck { args: "account status", ok: exit_ok }),+ },+ Harness {+ id: "vibe",+ name: "Mistral Vibe",+ bins: &["vibe-acp", "vibe"],+ local: None,+ registry: Some("mistral-vibe"),+ setup: "Install Mistral Vibe (curl -LsSf https://mistral.ai/vibe/install.sh | bash) and run `vibe --setup`.",+ install: Some(Install::Script("curl -LsSf https://mistral.ai/vibe/install.sh | bash")),+ login: Some("vibe --setup"),+ signed_in: None,+ },+ Harness {+ id: "kiro",+ name: "Kiro CLI",+ bins: &["kiro-cli"],+ local: Some("{bin} acp"),+ registry: None,+ setup: "Install Kiro CLI (curl -fsSL https://cli.kiro.dev/install | bash) and run `kiro-cli login`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://cli.kiro.dev/install | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm 'https://cli.kiro.dev/install.ps1' | iex\"",+ }),+ login: Some("{bin} login"),+ signed_in: None,+ },+ Harness {+ id: "devin",+ name: "Devin",+ bins: &["devin"],+ local: Some("{bin} acp"),+ registry: Some("devin"),+ setup: "Install the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) and run `devin auth login`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://cli.devin.ai/install.sh | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://cli.devin.ai/install.ps1 | iex\"",+ }),+ login: Some("{bin} auth login"),+ signed_in: None,+ },+ Harness {+ id: "qoder",+ name: "Qoder CLI",+ bins: &["qodercli"],+ local: Some("{bin} --acp"),+ registry: Some("qoder"),+ setup: "Install Qoder CLI (curl -fsSL https://qoder.com/install | bash) and run `qodercli login`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://qoder.com/install | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://qoder.com/install.ps1 | iex\"",+ }),+ login: Some("{bin} login"),+ signed_in: Some(SignInCheck { args: "status -o json", ok: qoder_signed_in }),+ },+ Harness {+ id: "codebuddy",+ name: "CodeBuddy Code",+ bins: &["codebuddy", "cbc"],+ local: Some("{bin} --acp"),+ registry: Some("codebuddy-code"),+ setup: "Install CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) and sign in with `codebuddy`.",+ install: Some(Install::Npm("@tencent-ai/codebuddy-code")),+ login: Some("{bin}"),+ signed_in: None,+ },+ Harness {+ id: "workbuddy",+ name: "WorkBuddy",+ // Its CLI is also named `codebuddy`, inside the app. PATH lookup would take CodeBuddy Code's.+ bins: &[],+ // `--serve` is what starts ACP. `--acp` selects the stdio transport.+ local: Some("{bin} --serve --acp"),+ registry: None,+ setup: "Install WorkBuddy from https://www.workbuddy.ai and sign in from Codync.",+ install: None,+ login: None,+ signed_in: None,+ },+ Harness {+ id: "minimax",+ name: "MiniMax Code",+ bins: &["mcode"],+ local: Some("{bin} acp"),+ registry: Some("minimax-code"),+ setup: "Install MiniMax Code (npm install -g @minimax-ai/code) and run `mcode login`.",+ install: Some(Install::Npm("@minimax-ai/code")),+ login: Some("{bin} login"),+ signed_in: None,+ },+ Harness {+ id: "junie",+ name: "Junie",+ bins: &["junie"],+ local: Some("{bin} --acp=true"),+ registry: Some("junie"),+ setup: "Install Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) and sign in with `junie`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://junie.jetbrains.com/install.sh | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"iex (irm 'https://junie.jetbrains.com/install.ps1')\"",+ }),+ login: Some("{bin}"),+ signed_in: None,+ },+ Harness {+ id: "antigravity",+ name: "Google Antigravity",+ bins: &["agy"],+ local: None,+ registry: Some("antigravity-acp"),+ setup: "Install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash), then sign in from Codync with Log in with Google.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://antigravity.google/cli/install.sh | bash",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://antigravity.google/cli/install.ps1 | iex\"",+ }),+ // Signing in with `agy` doesn't sign in its ACP server, which keeps its own sign-in+ // (`~/.gemini/antigravity-acp/settings.json`): only the server's own methods do.+ login: None,+ signed_in: None,+ },+ Harness {+ id: "cortex",+ name: "Cortex Code",+ bins: &["cortex"],+ local: Some("{bin} acp serve"),+ registry: Some("cortex-code"),+ setup: "Install Cortex Code (curl -LsS https://ai.snowflake.com/static/cc-scripts/install.sh | sh) and set up a connection with `cortex`.",+ install: Some(Install::Scripts {+ unix: "curl -LsS https://ai.snowflake.com/static/cc-scripts/install.sh | sh",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://ai.snowflake.com/static/cc-scripts/install.ps1 | iex\"",+ }),+ login: Some("{bin}"),+ signed_in: None,+ },+ Harness {+ id: "poolside",+ name: "Poolside",+ bins: &["pool"],+ local: Some("{bin} acp"),+ registry: Some("poolside"),+ setup: "Install Poolside (curl -fsSL https://downloads.poolside.ai/pool/install.sh | sh) and run `pool login`.",+ install: Some(Install::Scripts {+ unix: "curl -fsSL https://downloads.poolside.ai/pool/install.sh | sh",+ windows: "powershell -NoProfile -ExecutionPolicy Bypass -Command \"irm https://downloads.poolside.ai/pool/install.ps1 | iex\"",+ }),+ login: Some("{bin} login"),+ signed_in: None,+ },+];diff --git a/host/src/agent/backends/search_path.rs b/host/src/agent/backends/search_path.rsindex 49d66888..8be882aa 100644--- a/host/src/agent/backends/search_path.rs+++ b/host/src/agent/backends/search_path.rs@@ -114,7 +114,7 @@ fn executable_names(bin: &str) -> impl Iterator<Item = String> + '_ {extensions.iter().map(move |e| format!("{bin}{e}"))}-fn is_executable(p: &Path) -> bool {+pub(super) fn is_executable(p: &Path) -> bool {#[cfg(unix)]{use std::os::unix::fs::PermissionsExt;diff --git a/host/src/agent/backends/tests.rs b/host/src/agent/backends/tests.rsindex e2240b0b..db9bffd7 100644--- a/host/src/agent/backends/tests.rs+++ b/host/src/agent/backends/tests.rs@@ -59,6 +59,47 @@ fn every_harness_is_unique() {assert_eq!(bins.iter().collect::<HashSet<_>>().len(), bins.len(), "a CLI belongs to one harness");}+#[test]+fn workbuddy_session_does_not_prove_sign_in() {+ assert!(!session_proves_sign_in("workbuddy"));+ assert!(session_proves_sign_in("codebuddy"));+}++#[test]+fn workbuddy_starts_its_lite_bundle() {+ let workbuddy = harness("workbuddy").unwrap();+ assert_eq!(workbuddy.local, Some("{bin} --serve --acp"));+ assert!(workbuddy.login.is_none());+ let mut env = vec![("CODEBUDDY_FORCE_LITE_WB_BUNDLE".into(), "0".into())];+ apply_process_env("workbuddy", &mut env);+ assert_eq!(env, vec![("CODEBUDDY_FORCE_LITE_WB_BUNDLE".into(), "0".into())]);+ env.clear();+ apply_process_env("workbuddy", &mut env);+ assert_eq!(env, vec![("CODEBUDDY_FORCE_LITE_WB_BUNDLE".into(), "1".into())]);+ apply_process_env("codebuddy", &mut env);+ assert_eq!(env.len(), 1);+}++#[test]+fn workbuddy_cli_is_not_codebuddy_code() {+ let bundled = "/Applications/WorkBuddy.app/Contents/Resources/app.asar.unpacked/cli/bin/codebuddy";+ assert!(!belongs_to_other("workbuddy", bundled));+ assert!(belongs_to_other("codebuddy", bundled), "the app's CLI is WorkBuddy's, not CodeBuddy Code's");+ assert!(belongs_to_other("workbuddy", "/opt/homebrew/bin/codebuddy"));+}++#[test]+fn a_codebuddy_on_path_is_not_workbuddy() {+ let dir = TempDir::new();+ write_cli(&dir.0, "codebuddy");+ let _path = TestSearchPath::set(dir.0.clone());+ let on_path = dir.0.to_string_lossy().into_owned();+ let from_path =+ |c: ®istry::Candidate| matches!(c, registry::Candidate::Ready(cmd) if cmd.program.contains(&on_path));+ assert!(launch_candidates("codebuddy").unwrap().iter().any(from_path), "CodeBuddy Code's own CLI");+ assert!(!launch_candidates("workbuddy").is_ok_and(|c| c.iter().any(from_path)), "never WorkBuddy's");+}+#[test]fn hermes_uses_native_acp() {let h = harness("hermes").unwrap();diff --git a/host/src/agent/backends/workbuddy.rs b/host/src/agent/backends/workbuddy.rsnew file mode 100644index 00000000..04c0a167--- /dev/null+++ b/host/src/agent/backends/workbuddy.rs@@ -0,0 +1,127 @@+//! `WorkBuddy`'s ACP CLI lives inside the desktop app and is also named `codebuddy`.+//! Looking it up on `PATH` would take `CodeBuddy` Code's binary, so it is found only+//! under a `WorkBuddy` install.++use super::search_path::is_executable;+use std::path::{Path, PathBuf};++/// The app's folder and its CLI's folder in it: macOS, then Windows. The international build+/// (`workbuddy.ai`) is `WorkBuddy AI`; the one for mainland China (`codebuddy.cn`) is `WorkBuddy`.+const APPS_MAC: [&str; 2] = ["WorkBuddy AI.app", "WorkBuddy.app"];+const CLI_DIR_MAC: &str = "Contents/Resources/app.asar.unpacked/cli/bin";+const APPS_OTHER: [&str; 2] = ["WorkBuddy AI", "WorkBuddy"];+const CLI_DIR_OTHER: &str = "resources/app.asar.unpacked/cli/bin";++/// The desktop app ships only `codebuddy-lite-wb.mjs`. `--acp` alone loads the+/// headless bundle, which is not in the app, so the process exits immediately.+const PROCESS_ENV: &[(&str, &str)] = &[("CODEBUDDY_FORCE_LITE_WB_BUNDLE", "1")];++/// A new session proves the agent is signed in. `WorkBuddy` opens one with no token and only fails+/// the first prompt, so its session does not.+pub fn session_proves_sign_in(id: &str) -> bool {+ id != "workbuddy"+}++/// Whether Codync offers harness `id` here: the app is built for macOS and Windows only.+pub(super) fn offered(id: &str) -> bool {+ id != "workbuddy" || cfg!(any(target_os = "macos", windows))+}++/// The bundled CLI is a Node script (`#!/usr/bin/env node`): it runs on the computer's Node, or Codync's.+pub(super) fn runs_on_node(id: &str) -> bool {+ id == "workbuddy"+}++/// Environment the harness needs in addition to saved sign-in keys. A saved key wins.+pub fn apply_process_env(id: &str, env: &mut Vec<(String, String)>) {+ if id != "workbuddy" {+ return;+ }+ for (key, value) in PROCESS_ENV {+ if env.iter().any(|(name, _)| name == key) {+ continue;+ }+ env.push(((*key).to_owned(), (*value).to_owned()));+ }+}++/// The bundled CLI, when `WorkBuddy` is installed.+pub(super) fn find() -> Option<PathBuf> {+ find_in(&install_roots())+}++/// `program` is that bundled CLI (a path), not the `codebuddy` on `PATH`.+pub(super) fn is_cli(program: &str) -> bool {+ let path = Path::new(program.trim().trim_matches('"'));+ let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");+ if !matches!(name, "codebuddy" | "codebuddy.cmd" | "codebuddy.exe") {+ return false;+ }+ let text = path.to_string_lossy().replace('\\', "/");+ APPS_MAC.iter().any(|app| text.contains(&format!("/{app}/{CLI_DIR_MAC}/")))+ || APPS_OTHER.iter().any(|app| text.contains(&format!("/{app}/{CLI_DIR_OTHER}/")))+}++fn cli_dir() -> &'static str {+ if cfg!(target_os = "macos") { CLI_DIR_MAC } else { CLI_DIR_OTHER }+}++fn find_in(roots: &[PathBuf]) -> Option<PathBuf> {+ // Windows runs only these: the extensionless file next to them is the Node script itself.+ let names: &[&str] = if cfg!(windows) { &["codebuddy.cmd", "codebuddy.exe"] } else { &["codebuddy"] };+ roots+ .iter()+ .flat_map(|root| names.iter().map(move |name| root.join(cli_dir()).join(name)))+ .find(|p| is_executable(p))+}++fn install_roots() -> Vec<PathBuf> {+ let mut roots = Vec::new();+ if cfg!(target_os = "macos") {+ let home = dirs::home_dir().map(|home| home.join("Applications"));+ for app in APPS_MAC {+ roots.push(Path::new("/Applications").join(app));+ roots.extend(home.as_ref().map(|dir| dir.join(app)));+ }+ }+ if cfg!(windows) {+ // electron-builder's per-user install, then a machine-wide one.+ let local = dirs::data_local_dir();+ let program_files = std::env::var_os("ProgramFiles").map(PathBuf::from);+ for app in APPS_OTHER {+ if let Some(local) = &local {+ roots.push(local.join("Programs").join(app));+ roots.push(local.join(app));+ }+ roots.extend(program_files.as_ref().map(|dir| dir.join(app)));+ }+ }+ roots+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn either_app_bundle_counts_and_a_path_codebuddy_does_not() {+ let apps = if cfg!(target_os = "macos") { APPS_MAC } else { APPS_OTHER };+ for app in apps {+ let dir = std::env::temp_dir().join(format!("codync-workbuddy-{}", uuid::Uuid::new_v4()));+ let root = dir.join(app);+ let bin = root.join(cli_dir()).join(if cfg!(windows) { "codebuddy.cmd" } else { "codebuddy" });+ std::fs::create_dir_all(bin.parent().unwrap()).unwrap();+ std::fs::write(&bin, "#!/bin/sh\n").unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ assert_eq!(find_in(&[root]).as_deref(), Some(bin.as_path()), "{app}");+ assert!(is_cli(&bin.to_string_lossy()), "{app}");+ std::fs::remove_dir_all(dir).unwrap();+ }+ assert!(!is_cli("/opt/homebrew/bin/codebuddy"));+ assert!(!is_cli("/Applications/Other.app/Contents/Resources/app.asar.unpacked/cli/bin/codebuddy"));+ }+}diff --git a/host/src/agent/bot/session.rs b/host/src/agent/bot/session.rsindex dbcd0b2a..373f906c 100644--- a/host/src/agent/bot/session.rs+++ b/host/src/agent/bot/session.rs@@ -146,8 +146,8 @@ impl Actor {hub.set_runtime(&id, |r| r.activity = msg);};let candidates = launch_commands(&self.cfg)?;- // Keys saved from an "environment variable" sign-in.- let mut env = crate::agent::auth::env(&self.hub.store, &self.cfg.backend)?;+ // Keys saved from an "environment variable" sign-in, and what the harness needs to start.+ let mut env = crate::agent::auth::launch_env(&self.hub.store, &self.cfg.backend)?;if self.cfg.backend == "codex" && !env.iter().any(|(k, _)| k == "CODEX_CONFIG") {// Codex's `/compact` takes no instructions: the keep-list is its config's `compact_prompt`.let config = json!({"compact_prompt": codync_mem::compaction::KEEP});diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex 3b9cb4bb..23206238 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -236,7 +236,7 @@ impl Actor {}let done_tx = done_tx.clone();tokio::spawn(async move {- let _ = done_tx.send(answer.response().await);+ let _ = done_tx.send(answer.response().await.and_then(acp::codebuddy::prompt_result));});Ok(())}diff --git a/host/src/agent/fallback/reason.rs b/host/src/agent/fallback/reason.rsindex 021b10ed..251949ad 100644--- a/host/src/agent/fallback/reason.rs+++ b/host/src/agent/fallback/reason.rs@@ -71,13 +71,14 @@ pub fn of(error: &anyhow::Error) -> Option<Reason> {None}-fn of_rpc(r: &RpcError) -> Option<Reason> {+/// Why an agent's error answer moves the bot on (see [`of`]).+pub fn of_rpc(r: &RpcError) -> Option<Reason> {if r.code == AUTH_REQUIRED {return Some(Reason::SignedOut);}let usage_text = USAGE_LIMIT_TEXT.iter().any(|t| r.message.contains(t));// Claude's adapter sends the Agent SDK's assistant error (`rate_limit`…); codex-acp its `codexErrorInfo`- // (`usage_limit_exceeded`…).+ // (`usage_limit_exceeded`…); CodeBuddy its `category` (`auth`…).Some(match r.kind.as_deref() {Some("usage_limit_exceeded") => Reason::UsageLimit,Some("rate_limit" | "billing_error" | "account_on_hold") if usage_text => Reason::UsageLimit,@@ -90,7 +91,7 @@ fn of_rpc(r: &RpcError) -> Option<Reason> {| "internal_server_error"| "response_too_many_failed_attempts",) => Reason::Overloaded,- Some("authentication_failed" | "oauth_org_not_allowed" | "unauthorized") => Reason::SignedOut,+ Some("authentication_failed" | "oauth_org_not_allowed" | "unauthorized" | "auth") => Reason::SignedOut,Some("model_not_found") => Reason::ModelMissing,_ if usage_text => Reason::UsageLimit,_ => return None,diff --git a/host/src/agent/own_memory.rs b/host/src/agent/own_memory.rsindex 92725c52..8da82d54 100644--- a/host/src/agent/own_memory.rs+++ b/host/src/agent/own_memory.rs@@ -25,7 +25,7 @@ pub fn args(backend: &str) -> &'static str {/// are the user's.pub fn switchable(cfg: &BotConfig) -> bool {match cfg.backend.as_str() {- "claude" | "copilot" | "codebuddy" => true,+ "claude" | "copilot" | "codebuddy" | "workbuddy" => true,"qwen" => crate::agent::workspace::is_managed(cfg),_ => false,}@@ -172,6 +172,10 @@ mod tests {};let own = crate::agent::workspace::path(id).to_string_lossy().into_owned();assert!(kept(&bot("claude", "/work/app")), "Claude Code's is switched through its settings, in any folder");+ assert!(+ switchable(&bot("workbuddy", "/work/app")),+ "WorkBuddy is the CodeBuddy CLI and honors the same switch"+ );assert!(kept(&bot("qwen", &own)));assert!(!switchable(&bot("qwen", "/work/app")), "Qwen Code's lives in the project's own files");assert!(!switchable(&bot("codex", &own)) && !switchable(&bot("gemini", &own)));diff --git a/host/src/chat/oneshot.rs b/host/src/chat/oneshot.rsindex 501f83e4..cd632d85 100644--- a/host/src/chat/oneshot.rs+++ b/host/src/chat/oneshot.rs@@ -21,7 +21,7 @@ pub async fn one_shot(hub: &Arc<Hub>, cfg: &BotConfig, system: &str, user: &str)if hub.store.kv_read(&format!("agent-env:{}", cfg.backend))?.is_some() {crate::market::vault::unlock(hub.clone()).await?;}- let env = crate::agent::auth::env(&hub.store, &cfg.backend)?;+ let env = crate::agent::auth::launch_env(&hub.store, &cfg.backend)?;let mut conn = None;let mut last_err = None;for candidate in crate::agent::bot::launch_commands(cfg)? {@@ -71,7 +71,7 @@ pub async fn one_shot(hub: &Arc<Hub>, cfg: &BotConfig, system: &str, user: &str)let mut out = String::new();loop {tokio::select! {- r = &mut prompt => { r?; break }+ r = &mut prompt => { r.and_then(acp::codebuddy::prompt_result)?; break }inc = conn.rx.recv() => {if !collect(&acp, inc, &mut out).await {bail!("the background job's agent exited");diff --git a/host/src/shell.rs b/host/src/shell.rsindex 1ffe03bd..f6d52fe8 100644--- a/host/src/shell.rs+++ b/host/src/shell.rs@@ -1,6 +1,6 @@//! Command lines: the one place Unix and Windows differ in how agents, setup-//! terminals and wrapped status lines start. Unix runs a line with `sh -c`,-//! Windows with `cmd /c`.+//! terminals and wrapped status lines start, and in how a link opens. Unix runs a+//! line with `sh -c`, Windows with `cmd /c`.//!//! Windows hands the line to `cmd` through an environment variable: `cmd`//! expands `%VAR%` before it parses, so the line's own quotes survive whatever@@ -129,6 +129,25 @@ pub fn env_prefix<'a>(pairs: impl IntoIterator<Item = (&'a str, &'a str)>) -> Stif pairs.is_empty() || cfg!(windows) { pairs } else { format!("env {pairs}") }}+/// Opens a link or file with this computer's default app for it (a web page: the browser). Whether it started.+pub fn open(target: &std::ffi::OsStr) -> bool {+ let mut command = if cfg!(windows) {+ let mut c = std::process::Command::new("rundll32");+ c.arg("url.dll,FileProtocolHandler");+ c+ } else {+ std::process::Command::new(if cfg!(target_os = "macos") { "open" } else { "xdg-open" })+ };+ let opener = command+ .arg(target)+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .spawn();+ // Waited for, so the host, which runs for days, keeps no exited opener around.+ opener.map(|mut opener| std::thread::spawn(move || opener.wait())).is_ok()+}+/// `program` as spawnable: its full path when it's on the search path. Windows/// needs this for npm's `.cmd` shims, which `CreateProcess` won't find by name.pub fn program(name: &str) -> PathBuf {diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rsindex cd7d86b6..7a4caa76 100644--- a/host/src/tui/manage/mod.rs+++ b/host/src/tui/manage/mod.rs@@ -363,17 +363,5 @@ impl App {/// Opens `url` in this computer's browser, when the host is this computer.pub(super) fn open_browser(url: &str, host: &str) -> bool {let local = ["//127.0.0.1", "//localhost", "//[::1]"].iter().any(|h| host.contains(h));- local && !url.is_empty() && open_here(std::ffi::OsStr::new(url))-}--/// Opens a link or file with this computer's default app for it (a web page: the browser).-pub(in crate::tui) fn open_here(target: &std::ffi::OsStr) -> bool {- let mut command = if cfg!(windows) {- let mut c = std::process::Command::new("rundll32");- c.arg("url.dll,FileProtocolHandler");- c- } else {- std::process::Command::new(if cfg!(target_os = "macos") { "open" } else { "xdg-open" })- };- command.arg(target).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn().is_ok()+ local && !url.is_empty() && crate::shell::open(std::ffi::OsStr::new(url))}diff --git a/host/src/tui/net/artifacts.rs b/host/src/tui/net/artifacts.rsindex 5c80797a..3113be7d 100644--- a/host/src/tui/net/artifacts.rs+++ b/host/src/tui/net/artifacts.rs@@ -52,7 +52,7 @@ async fn deliver(let id = id.to_owned();let (path, opened) = tokio::task::spawn_blocking(move || -> Result<(PathBuf, bool)> {let path = write_temp(&temp, &name, &id, &html)?;- let opened = crate::tui::manage::open_here(path.as_os_str());+ let opened = crate::shell::open(path.as_os_str());Ok((path, opened))}).await??;diff --git a/host/tests/fallback_e2e.rs b/host/tests/fallback_e2e.rsindex 760e7322..a02bd164 100644--- a/host/tests/fallback_e2e.rs+++ b/host/tests/fallback_e2e.rs@@ -221,3 +221,62 @@ async fn a_signed_out_agent_hands_the_turn_over_and_asks_to_sign_in() {wait_for(&host, &bot, "back line", |e| e["data"]["text"] == "Back on Kimi Code.").await;assert!(last_prompt(&host, &bot, "primary").contains("Thanks"));}++/// How `CodeBuddy`'s CLI (`WorkBuddy`'s) says it's signed out: a refusal with the error in its meta.+const SIGNED_OUT_REFUSAL: &str = r#"{"code":-32000,"message":"Authentication required","data":{"details":"Please use /login command to sign in to your account","category":"auth"}}"#;++#[tokio::test]+async fn a_sign_in_error_inside_a_refusal_hands_the_turn_over() {+ let host = Host::start().await;+ let bot = json!({"name": "Hidden", "backend": "kimi", "command": agent("primary"), "connectors": [],+ "notify": false, "fallbacks": [{"backend": "codex", "command": agent("standin")}]});+ let bot = host.call("createBot", bot).await["bot"]["id"].as_str().unwrap().to_owned();+ std::fs::write(host.home.join("bots").join(&bot).join("workspace").join("primary.refusal"), SIGNED_OUT_REFUSAL)+ .unwrap();++ host.reply(&bot, "Fix the build").await;+ let reply = wait_for(&host, &bot, "reply", |e| e["kind"] == "agent" && e["data"]["final"] == true).await;+ assert_eq!(reply["data"]["text"], "standin answered");+ let line = wait_for(&host, &bot, "switch line", |e| e["data"]["agentSwitch"].is_object()).await;+ assert_eq!(line["data"]["text"], "Kimi Code is signed out. Codex carried on.");+ wait_for(&host, &bot, "sign-in card", |e| e["data"]["connectionRequest"]["kind"] == "agent").await;+ assert_eq!(bot_value(&host, &bot).await["resting"][0]["reason"], "signedOut");+}++#[tokio::test]+async fn an_error_inside_a_refusal_holds_the_message_or_says_what_it_is() {+ let host = Host::start().await;+ let bot =+ json!({"name": "Solo", "backend": "kimi", "command": agent("primary"), "connectors": [], "notify": false});+ let bot = host.call("createBot", bot).await["bot"]["id"].as_str().unwrap().to_owned();+ let refusal = host.home.join("bots").join(&bot).join("workspace").join("primary.refusal");+ std::fs::write(&refusal, SIGNED_OUT_REFUSAL).unwrap();++ // Signed out: the sign-in card holds the message and sends it again once the agent is signed in.+ host.call("send", json!({"botId": bot, "text": "Fix the build", "clientNonce": "n1"})).await;+ let card = wait_for(&host, &bot, "sign-in card", |e| e["data"]["connectionRequest"]["kind"] == "agent").await;+ assert_eq!(card["data"]["connectionRequest"]["entryIds"].as_array().map(Vec::len), Some(1), "{card}");+ std::fs::remove_file(&refusal).unwrap();+ let helper =+ json!({"name": "Helper", "backend": "kimi", "command": agent("helper"), "connectors": [], "notify": false});+ let helper = host.call("createBot", helper).await["bot"]["id"].as_str().unwrap().to_owned();+ host.reply(&helper, "Hello").await;+ let reply = wait_for(&host, &bot, "the held message's reply", |e| e["data"]["final"] == true).await;+ assert_eq!(reply["data"]["text"], "primary answered");+ assert!(last_prompt(&host, &bot, "primary").contains("Fix the build"));++ // Any other error is shown as the agent words it, with no sign-in card: signing in doesn't fix a bad key.+ let custom_model = r#"{"code":-32603,"message":"Internal error","data":{"details":"Authentication failed for custom model my-model. Check if the apiKey in your models.json is correct","category":"custom_model_auth"}}"#;+ std::fs::write(&refusal, custom_model).unwrap();+ host.call("send", json!({"botId": bot, "text": "Again", "clientNonce": "n2"})).await;+ let failed = wait_for(&host, &bot, "failure", |e| e["data"]["style"] == "error").await;+ assert!(failed["data"]["text"].as_str().unwrap().contains("Check if the apiKey in your models.json"), "{failed}");+ let history = host.call("history", json!({"botId": bot})).await;+ let cards = history["entries"].as_array().unwrap().iter().filter(|e| e["data"]["connectionRequest"].is_object());+ assert_eq!(cards.count(), 1, "no new sign-in card: {history}");++ // A refusal with nothing in it is still the agent declining.+ std::fs::write(&refusal, "").unwrap();+ host.call("send", json!({"botId": bot, "text": "Once more", "clientNonce": "n3"})).await;+ wait_for(&host, &bot, "declined notice", |e| e["data"]["text"] == "The agent declined to continue.").await;+}diff --git a/host/tests/fixtures/relay_agent.py b/host/tests/fixtures/relay_agent.pyindex 48a3fa4a..545daf17 100644--- a/host/tests/fixtures/relay_agent.py+++ b/host/tests/fixtures/relay_agent.py@@ -1,7 +1,9 @@"""ACP agent for the fallback chain test, run as `relay_agent.py <name>`. While `<name>.limit` exists in its folder,every prompt edits a file and then fails the way Claude's adapter reports a usage limit; otherwise it answers-"<name> answered". While `<name>.signedout` exists, every prompt fails asking to sign in (ACP's -32000). Sessions load-(`<name>-s<n>`) unless `<name>.noload` exists; every request goes to `<name>.jsonl` in its folder."""+"<name> answered". While `<name>.signedout` exists, every prompt fails asking to sign in (ACP's -32000). While+`<name>.refusal` exists, every prompt answers `refusal` with the file's text as `_meta["codebuddy.ai/errorMessage"]`, the+way CodeBuddy's CLI reports an error (an empty file: a plain refusal). Sessions load (`<name>-s<n>`) unless+`<name>.noload` exists; every request goes to `<name>.jsonl` in its folder."""import jsonimport os@@ -45,6 +47,11 @@ for line in sys.stdin:sid = params["sessionId"]if os.path.exists(f"{NAME}.signedout"):send({"id": message["id"], "error": {"code": -32000, "message": "Authentication required"}})+ elif os.path.exists(f"{NAME}.refusal"):+ with open(f"{NAME}.refusal", encoding="utf-8") as f:+ error = f.read()+ meta = {"_meta": {"codebuddy.ai/errorMessage": error}} if error else {}+ send({"id": message["id"], "result": {"stopReason": "refusal", **meta}})elif os.path.exists(f"{NAME}.limit"):tool = {"toolCallId": "t1", "title": "Edit a.txt", "kind": "edit", "status": "completed"}update(sid, {"sessionUpdate": "tool_call", **tool})diff --git a/web/content/docs/agents.mdx b/web/content/docs/agents.mdxindex 719bc7ac..8894a507 100644--- a/web/content/docs/agents.mdx+++ b/web/content/docs/agents.mdx@@ -31,6 +31,7 @@ For these agents, Codync knows the command it looks for, how to install it and h| Devin | `devin` | `devin auth login` || Qoder CLI | `qodercli` | `qodercli login` || CodeBuddy Code | `codebuddy` or `cbc` | run `codebuddy` |+| WorkBuddy | the CLI inside the WorkBuddy app | sign in from Codync || MiniMax Code | `mcode` | `mcode login` || Junie | `junie` | run `junie` || Google Antigravity | `agy` | sign in from Codync with **Log in with Google** |@@ -39,6 +40,8 @@ For these agents, Codync knows the command it looks for, how to install it and hSigning in to Google Antigravity with `agy` in a terminal doesn't sign in the part Codync runs, so use the sign-in option in Codync's setup sheet for it.+WorkBuddy is separate from CodeBuddy Code. Codync runs the CLI bundled in the WorkBuddy app: `WorkBuddy AI.app` (from workbuddy.ai) or `WorkBuddy.app` (from codebuddy.cn) on macOS, or its install folder on Windows (`%LOCALAPPDATA%\Programs\WorkBuddy AI` or `WorkBuddy`). That CLI only ships WorkBuddy's lite build, so Codync starts it the way the app does. It runs on Node.js: if the computer has none, Codync offers to add its own. Codync does not install WorkBuddy, and there is no Linux build, so Codync on Linux doesn't list it. Sign in from Codync: the WorkBuddy app's login stays in the app, so this CLI asks again and opens a browser. A `codebuddy` command on your `PATH` stays CodeBuddy Code.+Hermes Agent runs its own `hermes acp` mode, with the provider and model you pick in `hermes acp --setup`. On Windows, Codync also finds it in its install folders (`%LOCALAPPDATA%\hermes\bin`) without a `PATH` change. Hermes and Gemini CLI keep a memory of their own that every bot on them shares; see [Memory](/docs/memory#agents-with-a-memory-of-their-own).## Other agents from the ACP registrydiff --git a/web/content/docs/memory.mdx b/web/content/docs/memory.mdxindex 1c8bd853..676ee2b1 100644--- a/web/content/docs/memory.mdx+++ b/web/content/docs/memory.mdx@@ -75,7 +75,7 @@ The **Dreams** tab shows each run: added lines in green, taken-out lines in red,Some agents keep a memory of their own, such as Claude Code's auto memory. Codync turns it off for every bot by default, so each bot has one memory and you see all of it here.-Where Codync can switch it, the **This bot** section has a switch named after the agent, such as **Claude Code's own memory** (`m` in the terminal UI). That's available for Claude Code, GitHub Copilot, CodeBuddy Code, and Qwen Code in a bot's personal workspace. Gemini CLI, Hermes Agent, Kilo Code and Kiro have no switch Codync can use.+Where Codync can switch it, the **This bot** section has a switch named after the agent, such as **Claude Code's own memory** (`m` in the terminal UI). That's available for Claude Code, GitHub Copilot, CodeBuddy Code, WorkBuddy, and Qwen Code in a bot's personal workspace. Gemini CLI, Hermes Agent, Kilo Code and Kiro have no switch Codync can use.If you turn it on: