Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: add opencode thinking variants
Multica Evee2720f7d3304
diff --git a/apps/docs/content/docs/providers.ko.mdx b/apps/docs/content/docs/providers.ko.mdxindex 8ccfad13ab..d266dadae0 100644--- a/apps/docs/content/docs/providers.ko.mdx+++ b/apps/docs/content/docs/providers.ko.mdx@@ -22,7 +22,7 @@ Multica는 **12개의 AI 코딩 도구**를 기본 지원합니다. 이들은| **Hermes** | Nous Research | ✅ | ✅ | `.agent_context/skills/` (fallback) | 동적 탐색 || **Kimi** | Moonshot | ✅ | ✅ | `.kimi/skills/` | 동적 탐색 || **Kiro CLI** | Amazon | ✅ | ✅ | `.kiro/skills/` | 동적 탐색 |-| **OpenCode** | SST | ✅ | ✅ | `.opencode/skills/` | 동적 탐색 |+| **OpenCode** | SST | ✅ | ✅ | `.opencode/skills/` | 동적 탐색 + variant || **OpenClaw** | 오픈소스 | ✅ | ✅ | `.agent_context/skills/` (fallback) | 에이전트에 바인딩되어 작업마다 전환 불가 || **Pi** | Inflection AI | ✅ (세션이 파일 경로) | ❌ | `.pi/skills/` | 동적 탐색 |@@ -66,7 +66,7 @@ Amazon에서 제공합니다. `kiro-cli acp`를 통해 stdio 위에서 ACP를### OpenCode-SST에서 제공하는 오픈소스입니다. 사용 가능한 모델을 동적으로 탐색합니다(CLI의 구성 파일을 스캔). 세션 재개가 동작하고, 에이전트의 `mcp_config` 필드를 소비합니다. Multica는 `OPENCODE_CONFIG_CONTENT` 환경 변수를 통해 이를 인라인으로 주입하므로, 에이전트의 MCP 서버가 작업 디렉터리의 `opencode.json`(에이전트 또는 사용자가 소유하는 파일)을 건드리지 않고 OpenCode에 전달됩니다. **자신의 모델 카탈로그를 커스터마이징하고 싶은, 만지작거리기 좋아하는 사용자에게 적합합니다.**+SST에서 제공하는 오픈소스입니다. 사용 가능한 모델과 모델 variant를 동적으로 탐색합니다(CLI의 구성 파일을 스캔). 세션 재개가 동작하고, 에이전트의 `mcp_config` 필드를 소비합니다. Multica는 `OPENCODE_CONFIG_CONTENT` 환경 변수를 통해 이를 인라인으로 주입하므로, 에이전트의 MCP 서버가 작업 디렉터리의 `opencode.json`(에이전트 또는 사용자가 소유하는 파일)을 건드리지 않고 OpenCode에 전달됩니다. 모델이 variant를 노출하면 Multica는 이를 에이전트 thinking selector로 표시하고 선택한 값을 `opencode run --variant`로 전달합니다. **자신의 모델 카탈로그를 커스터마이징하고 싶은, 만지작거리기 좋아하는 사용자에게 적합합니다.**### OpenClawdiff --git a/apps/docs/content/docs/providers.mdx b/apps/docs/content/docs/providers.mdxindex 62b20cb078..29e967c66f 100644--- a/apps/docs/content/docs/providers.mdx+++ b/apps/docs/content/docs/providers.mdx@@ -22,7 +22,7 @@ For guidance on picking a tool when creating an agent, see [Creating and configu| **Hermes** | Nous Research | ✅ | ✅ | `.agent_context/skills/` (fallback) | Dynamic discovery || **Kimi** | Moonshot | ✅ | ✅ | `.kimi/skills/` | Dynamic discovery || **Kiro CLI** | Amazon | ✅ | ✅ | `.kiro/skills/` | Dynamic discovery |-| **OpenCode** | SST | ✅ | ✅ | `.opencode/skills/` | Dynamic discovery |+| **OpenCode** | SST | ✅ | ✅ | `.opencode/skills/` | Dynamic discovery + variants || **OpenClaw** | Open source | ✅ | ✅ | `.agent_context/skills/` (fallback) | Bound to the agent, can't be switched per task || **Pi** | Inflection AI | ✅ (session is a file path) | ❌ | `.pi/skills/` | Dynamic discovery |@@ -66,7 +66,7 @@ From Amazon. Uses ACP over stdio via `kiro-cli acp`. Session resumption works th### OpenCode-From SST, open source. Dynamically discovers available models (scans the CLI's configuration file). Session resumption works, and it consumes the agent's `mcp_config` field — Multica injects it inline through the `OPENCODE_CONFIG_CONTENT` environment variable, so the agent's MCP servers reach OpenCode without writing anything into the task workdir's `opencode.json` (the agent or the user keep ownership of that file). **Suitable for tinkerers who want to customize their model catalog.**+From SST, open source. Dynamically discovers available models and model variants (scans the CLI's configuration file). Session resumption works, and it consumes the agent's `mcp_config` field — Multica injects it inline through the `OPENCODE_CONFIG_CONTENT` environment variable, so the agent's MCP servers reach OpenCode without writing anything into the task workdir's `opencode.json` (the agent or the user keep ownership of that file). When a model exposes variants, Multica shows them as the agent thinking selector and passes the selected value through `opencode run --variant`. **Suitable for tinkerers who want to customize their model catalog.**### OpenClawdiff --git a/apps/docs/content/docs/providers.zh.mdx b/apps/docs/content/docs/providers.zh.mdxindex e4b5d015a7..ac8843e77c 100644--- a/apps/docs/content/docs/providers.zh.mdx+++ b/apps/docs/content/docs/providers.zh.mdx@@ -22,7 +22,7 @@ Multica 内置支持 **12 款 AI 编程工具**。它们都实现了同一套接| **Hermes** | Nous Research | ✅ | ✅ | `.agent_context/skills/` (fallback)| 动态发现 || **Kimi** | Moonshot | ✅ | ✅ | `.kimi/skills/` | 动态发现 || **Kiro CLI** | Amazon | ✅ | ✅ | `.kiro/skills/` | 动态发现 |-| **OpenCode** | SST | ✅ | ✅ | `.opencode/skills/` | 动态发现 |+| **OpenCode** | SST | ✅ | ✅ | `.opencode/skills/` | 动态发现 + variant || **OpenClaw** | 开源项目 | ✅ | ✅ | `.agent_context/skills/` (fallback)| 绑定在智能体上,不能在任务里切换 || **Pi** | Inflection AI | ✅(session 为文件路径)| ❌ | `.pi/skills/` | 动态发现 |@@ -66,7 +66,7 @@ Amazon 出品。通过 `kiro-cli acp` 使用 ACP stdio 协议。会话恢复走### OpenCode-SST 出品,开源。动态发现可用模型(扫 CLI 的配置文件)。会话恢复真用,会消费智能体的 `mcp_config` 字段——Multica 通过 `OPENCODE_CONFIG_CONTENT` 环境变量内联注入,让智能体的 MCP server 直接到达 OpenCode,**不会去碰任务工作目录里的 `opencode.json`**(那个文件归智能体或用户所有)。**适合爱折腾、想自定义模型目录**的开发者。+SST 出品,开源。动态发现可用模型和模型 variant(扫 CLI 的配置文件)。会话恢复真用,会消费智能体的 `mcp_config` 字段——Multica 通过 `OPENCODE_CONFIG_CONTENT` 环境变量内联注入,让智能体的 MCP server 直接到达 OpenCode,**不会去碰任务工作目录里的 `opencode.json`**(那个文件归智能体或用户所有)。当模型暴露 variant 时,Multica 会把它显示成智能体的思考强度选择,并通过 `opencode run --variant` 传给 OpenCode。**适合爱折腾、想自定义模型目录**的开发者。### OpenClawdiff --git a/apps/web/features/landing/i18n/en.ts b/apps/web/features/landing/i18n/en.tsindex 20e8d64dc4..0483fbf03c 100644--- a/apps/web/features/landing/i18n/en.ts+++ b/apps/web/features/landing/i18n/en.ts@@ -303,6 +303,7 @@ export function createEnDict(allowSignup: boolean): LandingDict {"Agent lists can be filtered by runtime machine, so teams can quickly find the agents tied to a device or local service","SMTP relays now support secure SMTPS connections on port 465","OpenCode runtimes can use MCP settings saved on an agent",+ "OpenCode agents now expose model variants as thinking controls and pass the selected effort through the runtime",],improvements: ["Mobile Issue headers now use cleaner controls that stay easier to reach on small screens",diff --git a/apps/web/features/landing/i18n/ko.ts b/apps/web/features/landing/i18n/ko.tsindex fe121929e7..ab604ed4ff 100644--- a/apps/web/features/landing/i18n/ko.ts+++ b/apps/web/features/landing/i18n/ko.ts@@ -278,6 +278,7 @@ export function createKoDict(allowSignup: boolean): LandingDict {"에이전트 목록을 런타임 머신별로 필터링해 특정 기기나 로컬 서비스에 연결된 에이전트를 더 빨리 찾을 수 있습니다.","메일 발송 설정에서 465번 포트의 보안 SMTP 연결을 사용할 수 있습니다.","OpenCode 런타임이 에이전트에 저장된 MCP 설정을 사용할 수 있습니다.",+ "OpenCode 에이전트는 모델 variant를 thinking control로 표시하고 선택한 값을 런타임에 전달합니다.",],improvements: ["모바일 이슈 상단의 조작 버튼이 더 정돈되어 작은 화면에서도 다루기 쉽습니다.",diff --git a/apps/web/features/landing/i18n/zh.ts b/apps/web/features/landing/i18n/zh.tsindex 47fae9740b..94ea3cb275 100644--- a/apps/web/features/landing/i18n/zh.ts+++ b/apps/web/features/landing/i18n/zh.ts@@ -303,6 +303,7 @@ export function createZhDict(allowSignup: boolean): LandingDict {"智能体列表可以按运行机器筛选,更快找到绑定到某台设备或本机运行服务的智能体","邮件发送服务现在支持安全的 465 端口连接","OpenCode 运行环境可以使用智能体里保存的 MCP 设置",+ "OpenCode 智能体现在会把模型 variant 显示为思考强度控制,并把选择结果传给运行时",],improvements: ["移动端 Issue 顶部操作更清晰,小屏幕上也更容易点击",diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 0d7fa42d30..c015b46854 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -559,7 +559,7 @@ export interface RuntimeModel {default?: boolean;/*** Per-model reasoning/effort catalog discovered by the daemon. Currently- * populated for claude and codex runtimes only; omitted (or undefined)+ * populated for claude, codex, and opencode runtimes; omitted (or undefined)* for every other provider, which the UI treats as "no thinking-level* picker for this model". See MUL-2339.*/diff --git a/packages/views/agents/components/inspector/thinking-picker.tsx b/packages/views/agents/components/inspector/thinking-picker.tsxindex ecde79f1df..157fa92016 100644--- a/packages/views/agents/components/inspector/thinking-picker.tsx+++ b/packages/views/agents/components/inspector/thinking-picker.tsx@@ -11,8 +11,8 @@ import { useT } from "../../../i18n";/*** Per-agent reasoning/effort picker (MUL-2339). Renders only when the- * current model exposes a non-empty `supported_levels` set — Claude and- * Codex today; every other provider gets nothing. The catalog is daemon-+ * current model exposes a non-empty `supported_levels` set — Claude, Codex,+ * and OpenCode today; every other provider gets nothing. The catalog is daemon-* discovered, so the value/label pairs match each CLI's own UI (`Low`,* `Extra high`, …) verbatim; never normalised across providers.*diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 65fc142d61..0f0daa8b77 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -37,10 +37,11 @@ type ExecOptions struct {McpConfig json.RawMessage // if non-nil, MCP server config to pass via --mcp-config// ThinkingLevel is the runtime-native reasoning/effort value (e.g.// Claude's "low|medium|high|xhigh|max", Codex's "none|minimal|low|- // medium|high|xhigh"). Empty means "use the runtime/model default" —+ // medium|high|xhigh", OpenCode's model variant names). Empty means+ // "use the runtime/model default" —// every backend that consumes this skips its --effort / reasoning_effort// injection so the upstream CLI's own default applies. Currently honoured- // by the claude and codex backends only; other backends ignore the+ // by the claude, codex, and opencode backends; other backends ignore the// field rather than fail (so MUL-2339 can grow runtime support// incrementally without breaking unrelated agents).ThinkingLevel stringdiff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex 2c4de9e58e..8879cc1f84 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -9,6 +9,7 @@ import ("io""os""os/exec"+ "sort""strings""sync""time"@@ -82,11 +83,10 @@ const modelCacheTTL = 60 * time.Second// openclaw) it shells out with caching and falls back to the static// list on failure.//-// For claude and codex, the static catalog is augmented with per-model-// thinking-level options discovered from the local CLI (see-// discoverClaudeThinking / discoverCodexThinking). Discovery failures-// silently leave Thinking == nil on each entry, which the UI treats-// as "no picker for this model" rather than blocking model selection.+// For claude, codex, and opencode, the catalog is augmented with per-model+// thinking-level options discovered from the local CLI. Discovery failures+// silently leave Thinking == nil on each entry, which the UI treats as+// "no picker for this model" rather than blocking model selection.//// executablePath lets the caller point at a non-default binary; pass// "" to use the provider's default name on PATH.@@ -130,7 +130,7 @@ func ListModels(ctx context.Context, providerType, executablePath string) ([]Modreturn discoverKiroModels(ctx, executablePath)})case "opencode":- return cachedDiscovery(providerType, func() ([]Model, error) {+ return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() ([]Model, error) {return discoverOpenCodeModels(ctx, executablePath)})case "pi":@@ -188,6 +188,13 @@ func cachedDiscovery(key string, fn func() ([]Model, error)) ([]Model, error) {return models, nil}+func discoveryCacheKey(providerType, executablePath string) string {+ if executablePath == "" {+ return providerType+ }+ return providerType + ":" + executablePath+}+// ── Static catalogs ──// claudeStaticModels reflects the Claude Code CLI's accepted --model@@ -330,9 +337,12 @@ func isOpenAIReasoningSeriesID(id string) bool {// ── Dynamic discovery ──-// discoverOpenCodeModels runs `opencode models` and parses its tabular-// output. The CLI prints `provider/model` rows; we emit them verbatim-// as IDs so what the user sees matches what `--model` accepts.+// discoverOpenCodeModels runs `opencode models --verbose` and parses its+// output. The CLI prints `provider/model` rows, followed by JSON metadata+// when verbose mode is enabled; we emit IDs verbatim so what the user sees+// matches what `--model` accepts, and project any model `variants` into the+// thinking-level picker because OpenCode's `run --variant` flag is its+// provider-specific reasoning-effort surface.// On any failure (CLI missing, parse error, timeout) we fall back to// an empty list so the creatable UI still works.func discoverOpenCodeModels(ctx context.Context, executablePath string) ([]Model, error) {@@ -344,53 +354,193 @@ func discoverOpenCodeModels(ctx context.Context, executablePath string) ([]Model}runCtx, cancel := context.WithTimeout(ctx, 5*time.Second)defer cancel()- cmd := exec.CommandContext(runCtx, executablePath, "models")+ cmd := exec.CommandContext(runCtx, executablePath, "models", "--verbose")hideAgentWindow(cmd)out, err := cmd.Output()if err != nil {- return []Model{}, nil+ cmd = exec.CommandContext(runCtx, executablePath, "models")+ hideAgentWindow(cmd)+ out, err = cmd.Output()+ if err != nil {+ return []Model{}, nil+ }}return parseOpenCodeModels(string(out)), nil}// parseOpenCodeModels accepts the `opencode models` text output and-// extracts IDs. Output format (v0.x): a header row followed by rows-// whose first whitespace-delimited field is `provider/model`.+// extracts IDs. Non-verbose output is one `provider/model` row per line.+// Verbose output appends a pretty-printed JSON object after each ID; when+// that object contains `variants`, each enabled variant becomes a thinking+// level that the backend later passes through `opencode run --variant`.func parseOpenCodeModels(output string) []Model {- scanner := bufio.NewScanner(strings.NewReader(output))- scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)+ lines := strings.Split(output, "\n")var models []Model- seen := map[string]bool{}- for scanner.Scan() {- line := strings.TrimSpace(scanner.Text())+ indexByID := map[string]int{}+ for i := 0; i < len(lines); i++ {+ line := strings.TrimSpace(lines[i])if line == "" {continue}- first := strings.Fields(line)- if len(first) == 0 {+ id := parseOpenCodeModelIDLine(line)+ if id == "" {continue}- id := first[0]- if !strings.Contains(id, "/") {- continue+ idx, seen := indexByID[id]+ if !seen {+ provider := ""+ if slash := strings.Index(id, "/"); slash > 0 {+ provider = id[:slash]+ }+ idx = len(models)+ indexByID[id] = idx+ models = append(models, Model{ID: id, Label: id, Provider: provider})}- // Skip the header row (opencode prints e.g. PROVIDER/MODEL in caps).- if id == strings.ToUpper(id) {- continue++ next := i + 1+ for next < len(lines) && strings.TrimSpace(lines[next]) == "" {+ next++}- if seen[id] {+ if next >= len(lines) || !strings.HasPrefix(strings.TrimSpace(lines[next]), "{") {continue}- seen[id] = true- provider := ""- if i := strings.Index(id, "/"); i > 0 {- provider = id[:i]+ raw, resumeAt := collectOpenCodeModelJSON(lines, next)+ if json.Valid(raw) {+ annotateOpenCodeModelMetadata(&models[idx], raw)}- models = append(models, Model{ID: id, Label: id, Provider: provider})+ i = resumeAt - 1}return models}+func parseOpenCodeModelIDLine(line string) string {+ fields := strings.Fields(line)+ if len(fields) == 0 {+ return ""+ }+ id := fields[0]+ if strings.HasPrefix(id, `"`) || strings.HasPrefix(id, "{") || strings.HasPrefix(id, "[") {+ return ""+ }+ if !strings.Contains(id, "/") {+ return ""+ }+ // Skip header rows such as PROVIDER/MODEL.+ if id == strings.ToUpper(id) {+ return ""+ }+ return id+}++func collectOpenCodeModelJSON(lines []string, start int) ([]byte, int) {+ var b strings.Builder+ for i := start; i < len(lines); i++ {+ line := strings.TrimSpace(lines[i])+ if i > start && parseOpenCodeModelIDLine(line) != "" {+ return []byte(b.String()), i+ }+ if b.Len() > 0 {+ b.WriteByte('\n')+ }+ b.WriteString(lines[i])+ if json.Valid([]byte(b.String())) {+ return []byte(b.String()), i + 1+ }+ }+ return []byte(b.String()), len(lines)+}++type opencodeModelMetadata struct {+ Reasoning bool `json:"reasoning"`+ Variants map[string]opencodeModelVariant `json:"variants"`+}++type opencodeModelVariant struct {+ Disabled bool `json:"disabled"`+ ReasoningEffort string `json:"reasoningEffort"`+ Thinking json.RawMessage `json:"thinking"`+}++var opencodeVariantLabel = map[string]string{+ "none": "None",+ "minimal": "Minimal",+ "low": "Low",+ "medium": "Medium",+ "high": "High",+ "xhigh": "Extra high",+ "max": "Max",+}++var opencodeVariantOrder = map[string]int{+ "none": 0,+ "minimal": 1,+ "low": 2,+ "medium": 3,+ "high": 4,+ "xhigh": 5,+ "max": 6,+}++func annotateOpenCodeModelMetadata(model *Model, raw []byte) {+ var meta opencodeModelMetadata+ if err := json.Unmarshal(raw, &meta); err != nil {+ return+ }+ if !meta.Reasoning && !openCodeVariantsLookReasoning(meta.Variants) {+ return+ }+ levels := openCodeThinkingLevelsFromVariants(meta.Variants)+ if len(levels) == 0 {+ return+ }+ model.Thinking = &ModelThinking{SupportedLevels: levels}+}++func openCodeVariantsLookReasoning(variants map[string]opencodeModelVariant) bool {+ for name, variant := range variants {+ if _, known := opencodeVariantOrder[name]; known {+ return true+ }+ if variant.ReasoningEffort != "" || len(variant.Thinking) > 0 {+ return true+ }+ }+ return false+}++func openCodeThinkingLevelsFromVariants(variants map[string]opencodeModelVariant) []ThinkingLevel {+ if len(variants) == 0 {+ return nil+ }+ values := make([]string, 0, len(variants))+ for value, variant := range variants {+ if value == "" || variant.Disabled {+ continue+ }+ values = append(values, value)+ }+ sort.Slice(values, func(i, j int) bool {+ left, leftKnown := opencodeVariantOrder[values[i]]+ right, rightKnown := opencodeVariantOrder[values[j]]+ if leftKnown && rightKnown {+ return left < right+ }+ if leftKnown != rightKnown {+ return leftKnown+ }+ return values[i] < values[j]+ })+ levels := make([]ThinkingLevel, 0, len(values))+ for _, value := range values {+ label, ok := opencodeVariantLabel[value]+ if !ok {+ label = strings.Title(strings.ReplaceAll(value, "-", " ")) //nolint:staticcheck+ }+ levels = append(levels, ThinkingLevel{Value: value, Label: label})+ }+ return levels+}+// discoverPiModels runs `pi --list-models` and parses its output.// Older pi versions print the list to stderr; newer versions use// stdout. We capture both and parse whichever is non-empty.diff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.goindex 12122bb796..ba6987c7d0 100644--- a/server/pkg/agent/models_test.go+++ b/server/pkg/agent/models_test.go@@ -2,6 +2,8 @@ package agentimport ("context"+ "path/filepath"+ "runtime""strings""testing")@@ -284,6 +286,126 @@ nonprefixed-line}}+func TestParseOpenCodeModelsVerboseVariants(t *testing.T) {+ input := `openai/gpt-5+{+ "id": "gpt-5",+ "name": "GPT-5",+ "reasoning": true,+ "variants": {+ "high": { "reasoningEffort": "high" },+ "low": { "reasoningEffort": "low" },+ "xhigh": { "reasoningEffort": "xhigh" },+ "fast-mode": { "reasoningEffort": "low" },+ "disabled": { "disabled": true }+ }+}+anthropic/claude-sonnet-4-6+{+ "id": "claude-sonnet-4-6",+ "reasoning": true,+ "variants": {+ "max": { "thinking": { "type": "enabled", "budgetTokens": 32000 } },+ "high": { "thinking": { "type": "enabled", "budgetTokens": 16000 } }+ }+}+`+ models := parseOpenCodeModels(input)+ if len(models) != 2 {+ t.Fatalf("expected 2 models, got %d: %+v", len(models), models)+ }+ if models[0].Thinking == nil {+ t.Fatalf("expected first model to expose thinking variants")+ }+ got := make([]string, 0, len(models[0].Thinking.SupportedLevels))+ for _, lvl := range models[0].Thinking.SupportedLevels {+ got = append(got, lvl.Value)+ if lvl.Value == "xhigh" && lvl.Label != "Extra high" {+ t.Errorf("xhigh label: got %q, want Extra high", lvl.Label)+ }+ if lvl.Value == "fast-mode" && lvl.Label != "Fast Mode" {+ t.Errorf("custom variant label: got %q, want Fast Mode", lvl.Label)+ }+ }+ want := []string{"low", "high", "xhigh", "fast-mode"}+ if strings.Join(got, ",") != strings.Join(want, ",") {+ t.Fatalf("variant order/values: got %v, want %v", got, want)+ }+ if models[1].Thinking == nil || len(models[1].Thinking.SupportedLevels) != 2 {+ t.Fatalf("expected second model variants, got %+v", models[1].Thinking)+ }+}++func TestParseOpenCodeModelsMalformedVerboseBlockKeepsFollowingModels(t *testing.T) {+ input := `openai/gpt-5+{+ "id": "gpt-5",+ "reasoning": true,+ "variants": {+ "high": {}+ }+anthropic/claude-sonnet-4-6+{+ "id": "claude-sonnet-4-6",+ "reasoning": true,+ "variants": {+ "high": {},+ "max": {}+ }+}+`+ models := parseOpenCodeModels(input)+ if len(models) != 2 {+ t.Fatalf("expected both model rows to survive malformed JSON, got %d: %+v", len(models), models)+ }+ if models[0].ID != "openai/gpt-5" {+ t.Fatalf("unexpected first model: %+v", models[0])+ }+ if models[0].Thinking != nil {+ t.Fatalf("malformed first JSON block should not annotate thinking: %+v", models[0].Thinking)+ }+ if models[1].ID != "anthropic/claude-sonnet-4-6" {+ t.Fatalf("unexpected second model: %+v", models[1])+ }+ if models[1].Thinking == nil || len(models[1].Thinking.SupportedLevels) != 2 {+ t.Fatalf("valid following JSON block should still annotate thinking: %+v", models[1].Thinking)+ }+}++func TestDiscoverOpenCodeModelsFallsBackWhenVerboseFails(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fake binary requires a POSIX shell")+ }++ dir := t.TempDir()+ fake := filepath.Join(dir, "opencode")+ script := `#!/bin/sh+if [ "$1" = "models" ] && [ "$2" = "--verbose" ]; then+ exit 2+fi+if [ "$1" = "models" ]; then+ cat <<'EOF'+PROVIDER/MODEL CONTEXT MAX_OUT+openai/gpt-4o 128000 16384+EOF+ exit 0+fi+exit 1+`+ writeTestExecutable(t, fake, []byte(script))++ models, err := discoverOpenCodeModels(context.Background(), fake)+ if err != nil {+ t.Fatalf("discoverOpenCodeModels: %v", err)+ }+ if len(models) != 1 {+ t.Fatalf("expected fallback non-verbose model, got %d: %+v", len(models), models)+ }+ if models[0].ID != "openai/gpt-4o" || models[0].Thinking != nil {+ t.Fatalf("unexpected fallback model: %+v", models[0])+ }+}+func TestParsePiModels(t *testing.T) {input := `openai:gpt-4oanthropic:claude-opus-4-7diff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.goindex 076bab69a4..e9c758b820 100644--- a/server/pkg/agent/opencode.go+++ b/server/pkg/agent/opencode.go@@ -19,6 +19,7 @@ import (var opencodeBlockedArgs = map[string]blockedArgMode{"--format": blockedWithValue, // json output format for daemon communication"--dir": blockedWithValue, // task workdir anchor for skill / AGENTS.md discovery+ "--variant": blockedWithValue, // owned by agent.thinking_level"--dangerously-skip-permissions": blockedStandalone, // daemon manages non-interactive permission prompts}@@ -67,6 +68,9 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecOif opts.Model != "" {args = append(args, "--model", opts.Model)}+ if opts.ThinkingLevel != "" {+ args = append(args, "--variant", opts.ThinkingLevel)+ }if opts.SystemPrompt != "" {args = append(args, "--prompt", opts.SystemPrompt)}diff --git a/server/pkg/agent/opencode_test.go b/server/pkg/agent/opencode_test.goindex a7cca3ba38..daa543ef00 100644--- a/server/pkg/agent/opencode_test.go+++ b/server/pkg/agent/opencode_test.go@@ -954,6 +954,74 @@ func TestOpencodeBackendAnchorsDirAndPWD(t *testing.T) {}}+func TestOpencodeBackendInjectsThinkingVariant(t *testing.T) {+ t.Parallel()++ tempDir := t.TempDir()+ argsFile := filepath.Join(tempDir, "argv.txt")+ fakePath := filepath.Join(tempDir, "opencode")+ writeTestExecutable(t, fakePath, []byte(fakeOpencodeScript()))++ backend, err := New("opencode", Config{+ ExecutablePath: fakePath,+ Logger: slog.Default(),+ Env: map[string]string{+ "OPENCODE_ARGS_FILE": argsFile,+ },+ })+ if err != nil {+ t.Fatalf("new opencode backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{+ Model: "opencode/deepseek-v4",+ ThinkingLevel: "max",+ CustomArgs: []string{"--variant", "low", "--keep-me"},+ Timeout: 5 * time.Second,+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ <-session.Result++ raw, err := os.ReadFile(argsFile)+ if err != nil {+ t.Fatalf("read args file: %v", err)+ }+ args := splitNonEmptyLines(string(raw))+ if !containsAdjacent(args, "--model", "opencode/deepseek-v4") {+ t.Fatalf("expected --model opencode/deepseek-v4 in args: %v", args)+ }+ if !containsAdjacent(args, "--variant", "max") {+ t.Fatalf("expected daemon-injected --variant max in args: %v", args)+ }+ if argIndexOf(args, "--model") > argIndexOf(args, "--variant") {+ t.Errorf("expected --variant after --model for readability: %v", args)+ }+ count := 0+ for _, arg := range args {+ if arg == "--variant" {+ count+++ }+ }+ if count != 1 {+ t.Fatalf("expected exactly one --variant, got %d: %v", count, args)+ }+ if argIndexOf(args, "low") >= 0 {+ t.Errorf("filtered user --variant value still appears: %v", args)+ }+ if argIndexOf(args, "--keep-me") < 0 {+ t.Errorf("non-blocked custom arg was dropped: %v", args)+ }+}+func TestOpencodeBackendDoesNotUsePermissionEnvOverride(t *testing.T) {t.Parallel()diff --git a/server/pkg/agent/thinking.go b/server/pkg/agent/thinking.goindex 356b9bcde7..851111a09e 100644--- a/server/pkg/agent/thinking.go+++ b/server/pkg/agent/thinking.go@@ -11,13 +11,15 @@ import ()// thinking.go discovers per-model reasoning/effort catalogs for the-// claude and codex backends so the daemon can advertise them to the+// claude, codex, and opencode backends so the daemon can advertise them to the// UI without hard-coding (and getting wrong) what's installed locally.//// MUL-2339: we deliberately do not flatten Claude's `low|medium|high|// xhigh|max` and Codex's `none|minimal|low|medium|high|xhigh` onto a-// shared enum — what users pick must round-trip exactly through each-// CLI's own value vocabulary.+// shared enum. OpenCode exposes provider-specific model variants through+// `opencode run --variant`, and those names can be extended by local+// opencode.json config. What users pick must round-trip exactly through+// each CLI's own value vocabulary.// ── Cache ────────────────────────────────────────────────────────────//@@ -396,6 +398,9 @@ func ValidateThinkingLevel(ctx context.Context, providerType, executablePath, mo}}if target == "" {+ if providerType == "opencode" {+ return anyModelSupportsThinkingValue(models, value), nil+ }return false, nil}}@@ -416,15 +421,33 @@ func ValidateThinkingLevel(ctx context.Context, providerType, executablePath, moreturn false, nil}-// providerThinkingEnums is the server-side accept-list for each runtime's-// reasoning-effort vocabulary. The server doesn't have local CLI binaries,-// so it cannot do per-model discovery the way the daemon can; what it CAN-// do is reject values that are not in any version of the provider's enum-// at all. Per-model gaps (e.g. user sets `xhigh` while the chosen model-// only supports up to `high`) surface as a daemon-side task failure with-// a clear error, not a server-side 400 — that split is intentional so the-// API behaviour stays consistent (always-400 on literal-invalid, never-// auto-clear on combination-invalid). See MUL-2339 review notes.+func anyModelSupportsThinkingValue(models []Model, value string) bool {+ for _, m := range models {+ if m.Thinking == nil {+ continue+ }+ for _, lvl := range m.Thinking.SupportedLevels {+ if lvl.Value == value {+ return true+ }+ }+ }+ return false+}++// providerThinkingEnums is the server-side accept-list for runtimes with a+// fixed reasoning-effort vocabulary. OpenCode is deliberately absent because+// its `--variant` values come from the local model catalog and custom+// opencode.json entries can define additional variant names.+//+// The server doesn't have local CLI binaries, so it cannot do per-model+// discovery the way the daemon can; what it CAN do is reject values that are+// not in any version of the provider's enum at all. Per-model gaps (e.g. user+// sets `xhigh` while the chosen model only supports up to `high`) are handled+// by the daemon's pre-execution guard, which logs and skips injection rather+// than mutating persisted agent state. That split keeps API behaviour+// consistent: always 400 on literal-invalid, never auto-clear on+// combination-invalid. See MUL-2339 review notes.//// Keep these lists permissive: they're a "is this a known token in this// runtime's universe" check, not an "is this the right level for this@@ -451,7 +474,8 @@ var providerThinkingEnums = map[string]map[string]bool{// IsKnownThinkingValue reports whether `value` is a recognised effort// token for the given provider. Empty string is always accepted (means// "use runtime default"). Unknown providers (no thinking concept) accept-// only empty.+// only empty; OpenCode accepts well-formed variant names because its local+// catalog can be extended by opencode.json.//// This is the cheap synchronous gate the server uses on CreateAgent /// UpdateAgent. Unlike ValidateThinkingLevel it does NOT consult the live@@ -460,9 +484,31 @@ func IsKnownThinkingValue(providerType, value string) bool {if value == "" {return true}+ if providerType == "opencode" {+ return isValidOpenCodeVariantName(value)+ }enum, ok := providerThinkingEnums[providerType]if !ok {return false}return enum[value]}++func isValidOpenCodeVariantName(value string) bool {+ if len(value) > 64 {+ return false+ }+ for i, r := range value {+ valid := r >= 'a' && r <= 'z' ||+ r >= 'A' && r <= 'Z' ||+ r >= '0' && r <= '9' ||+ r == '-' || r == '_' || r == '.'+ if !valid {+ return false+ }+ if i == 0 && (r == '-' || r == '_' || r == '.') {+ return false+ }+ }+ return true+}diff --git a/server/pkg/agent/thinking_test.go b/server/pkg/agent/thinking_test.goindex 54f2b95e03..e9b1767b89 100644--- a/server/pkg/agent/thinking_test.go+++ b/server/pkg/agent/thinking_test.go@@ -257,6 +257,11 @@ func TestIsKnownThinkingValue(t *testing.T) {{"codex", "minimal", true},{"codex", "xhigh", true},{"codex", "max", false}, // Claude-only token rejected for Codex+ {"opencode", "", true},+ {"opencode", "max", true},+ {"opencode", "fast-mode", true}, // custom opencode.json variant names are valid+ {"opencode", ".hidden", false}, // reject suspicious / malformed names server-side+ {"opencode", "bad value", false}, // spaces are not valid variant names{"hermes", "", true},{"hermes", "low", false}, // hermes has no thinking concept}@@ -371,6 +376,59 @@ func TestValidateThinkingLevel_ExplicitModel(t *testing.T) {}}+func TestValidateThinkingLevel_OpenCodeEmptyModelUsesAdvertisedVariants(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fake binary requires a POSIX shell")+ }++ modelCacheMu.Lock()+ delete(modelCache, "opencode")+ modelCacheMu.Unlock()+ defer func() {+ modelCacheMu.Lock()+ delete(modelCache, "opencode")+ modelCacheMu.Unlock()+ }()++ dir := t.TempDir()+ fake := filepath.Join(dir, "opencode")+ script := `#!/bin/sh+if [ "$1" = "models" ]; then+ cat <<'EOF'+opencode/deepseek-v4+{+ "id": "deepseek-v4",+ "reasoning": true,+ "variants": {+ "high": {},+ "max": {}+ }+}+EOF+ exit 0+fi+echo "opencode 9.9.9"+`+ writeTestExecutable(t, fake, []byte(script))++ ctx := context.Background()+ ok, err := ValidateThinkingLevel(ctx, "opencode", fake, "", "max")+ if err != nil {+ t.Fatalf("unexpected err: %v", err)+ }+ if !ok {+ t.Fatalf("expected empty-model opencode max to pass when any advertised model supports it")+ }++ ok, err = ValidateThinkingLevel(ctx, "opencode", fake, "", "xhigh")+ if err != nil {+ t.Fatalf("unexpected err: %v", err)+ }+ if ok {+ t.Fatalf("xhigh should fail when no advertised OpenCode model exposes it")+ }+}+// writeFakeClaudeHelpBinary writes a small shell script that mimics// `claude --help`, emitting the full effort superset line so per-model// projection has something to filter. Returns the path to the executable.@@ -650,4 +708,3 @@ func argIndexOf(slice []string, target string) int {}return -1}-