Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(agent): support Pi thinking levels through RPC model discovery (MUL-5924) (#6629)

Chan Nyein Thawf97db4fc5ac9
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 16e0df0771..6c18483601 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -1122,6 +1122,7 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
// thinking_level validation: fixed-enum providers reject unknown literals;
// dynamic-catalog providers (Codex/OpenCode) reject malformed tokens here.
+ // Pi has a fixed token universe and a daemon-discovered per-model subset.
// Per-model gaps are enforced by the daemon at execution time (MUL-2339):
// combination-invalid values are logged and omitted from the invocation.
if !agent.IsKnownThinkingValue(runtime.Provider, req.ThinkingLevel) {
diff --git a/server/internal/handler/agent_thinking_test.go b/server/internal/handler/agent_thinking_test.go
index 9d04c841d3..6e07bdfcd7 100644
--- a/server/internal/handler/agent_thinking_test.go
+++ b/server/internal/handler/agent_thinking_test.go
@@ -99,6 +99,56 @@ func TestCreateAgent_ThinkingLevel_ValidationConsistency(t *testing.T) {
})
}
+func TestCreateAgent_PiThinkingLevelValidation(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ piRuntimeID := createPiProviderRuntime(t)
+ t.Cleanup(func() {
+ testPool.Exec(ctx,
+ `DELETE FROM agent WHERE workspace_id = $1 AND name LIKE 'pi-thinking-%'`,
+ testWorkspaceID,
+ )
+ })
+
+ t.Run("native max value succeeds", func(t *testing.T) {
+ body := map[string]any{
+ "name": "pi-thinking-max",
+ "runtime_id": piRuntimeID,
+ "visibility": "private",
+ "max_concurrent_tasks": 1,
+ "thinking_level": "max",
+ }
+ w := httptest.NewRecorder()
+ testHandler.CreateAgent(w, newRequest(http.MethodPost, "/api/agents", body))
+ if w.Code != http.StatusCreated {
+ t.Fatalf("Pi thinking_level=max: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp map[string]any
+ _ = json.NewDecoder(w.Body).Decode(&resp)
+ if resp["thinking_level"] != "max" {
+ t.Fatalf("Pi thinking_level response = %v, want max", resp["thinking_level"])
+ }
+ })
+
+ t.Run("non-Pi token is rejected", func(t *testing.T) {
+ body := map[string]any{
+ "name": "pi-thinking-ultra",
+ "runtime_id": piRuntimeID,
+ "visibility": "private",
+ "max_concurrent_tasks": 1,
+ "thinking_level": "ultra",
+ }
+ w := httptest.NewRecorder()
+ testHandler.CreateAgent(w, newRequest(http.MethodPost, "/api/agents", body))
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("Pi thinking_level=ultra: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+}
+
func TestAgentServiceTierValidationAndTriState(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
@@ -590,6 +640,26 @@ func createHermesProviderRuntime(t *testing.T) string {
return runtimeID
}
+func createPiProviderRuntime(t *testing.T) string {
+ t.Helper()
+ var runtimeID string
+ err := testPool.QueryRow(context.Background(), `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status,
+ device_info, metadata, last_seen_at, owner_id
+ )
+ VALUES ($1, NULL, $2, 'cloud', 'pi', 'online', $3, '{}'::jsonb, now(), $4)
+ RETURNING id
+ `, testWorkspaceID, "Pi Thinking Runtime", "Pi thinking-level test runtime", testUserID).Scan(&runtimeID)
+ if err != nil {
+ t.Fatalf("create pi runtime: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)
+ })
+ return runtimeID
+}
+
// createCodexProviderRuntime mirrors createClaudeProviderRuntime but for
// the codex provider, so runtime-switch tests can exercise a real
// cross-provider transition.
diff --git a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
index d9d53bae1f..626afc707f 100644
--- a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
@@ -119,7 +119,7 @@ multica agent copy <source-agent-id> --runtime-id <target> --model <model> # cr
| `avatar_url` | `agent.avatar_url` | none; an explicit non-empty value is preserved, while omitted/empty creates a random `emoji:<glyph>` avatar | catalog/listing UI only — NOT the runtime prompt |
| `runtime_id` | `agent.runtime_id` (nullable) | required at create (400) + must resolve to a runtime in this workspace | selects runtime/provider; `NULL` means unbound — see below |
| `model` | `agent.model` (nullable) | none beyond runtime support | daemon reads; empty = runtime default |
-| `thinking_level` | `agent.thinking_level` (nullable) | provider-level enum; unknown literal → 400. A runtime with no reasoning control (e.g. `hermes`) rejects EVERY non-empty value and says so — that 400 is a capability answer, not a bad token | daemon; empty = runtime default |
+| `thinking_level` | `agent.thinking_level` (nullable) | provider-level enum/safe-token gate; unknown literal → 400. Pi accepts only `off|minimal|low|medium|high|xhigh|max`, then the daemon checks the selected model's RPC-discovered subset. A runtime with no reasoning control (e.g. `hermes`) rejects EVERY non-empty value and says so — that 400 is a capability answer, not a bad token | daemon; empty = runtime default |
| `service_tier` | `agent.service_tier` (nullable) | Codex-only safe token; other providers reject; exact model/tier pair checked by daemon | daemon → Codex app-server; empty = local Codex config |
| `custom_args` | `agent.custom_args` (JSON array) | JSON shape checked CLI-side; server stores as-is | daemon (extra CLI switches); defaults to `[]` |
| `runtime_config` | `agent.runtime_config` (JSON) | JSON shape checked CLI-side; server stores as-is | runtime-specific config; defaults to `{}` |
@@ -142,22 +142,26 @@ to 6 while an explicitly supplied 0 is rejected; on update, omission preserves
the current value. The CLI performs the same range check before sending create
or update requests.
-`thinking_level` is validated only at the provider level: fixed-catalog
-providers reject an unrecognized literal, while dynamic-catalog providers such
-as Codex/OpenCode accept a syntactically safe token. A value unsupported for
-the chosen model is NOT rejected here — the daemon checks its local model
-catalog at execution time, logs a warning, and omits the incompatible override.
+`thinking_level` is validated only at the provider level: fixed-vocabulary
+providers reject an unrecognized literal, while dynamic-vocabulary providers
+such as Codex/OpenCode accept a syntactically safe token. Pi's provider-level
+vocabulary is fixed (`off|minimal|low|medium|high|xhigh|max`), but its exact
+supported subset is model-specific and discovered from the local Pi RPC model
+catalog. A value unsupported for the chosen model is NOT rejected here — the
+daemon checks its local model catalog at execution time, logs a warning, and
+omits the incompatible override.
Set it from the CLI with `--thinking-level` on `agent create` and `agent
update`, mirroring `--model`: the flag is a thin pass-through to the top-level
`thinking_level` field, and on update an empty string (`--thinking-level ""`)
clears it back to the runtime default. The CLI deliberately does not enumerate
the valid levels — they are runtime/model-specific (Claude currently uses
-`low|medium|high|xhigh|max`; Codex values are discovered from the runtime's
-model catalog). It forwards the token, the server applies the provider's
-fixed-enum or safe-token gate, and the daemon performs the exact model/level
-check. A runtime whose provider has no thinking concept rejects any non-empty
-value with a 400.
+`low|medium|high|xhigh|max`; Pi uses
+`off|minimal|low|medium|high|xhigh|max`; Codex values are discovered from the
+runtime's model catalog). It forwards the token, the server applies the
+provider's fixed-enum or safe-token gate, and the daemon performs the exact
+model/level check. A runtime whose provider has no thinking concept rejects any
+non-empty value with a 400.
`service_tier` is the matching first-class Codex speed control. Set it with
`--service-tier <catalog-id>` on create/update; use `--service-tier ""` on
@@ -173,7 +177,9 @@ explicit model fail closed because the effective config.toml model is unknown.
`custom_args` are raw provider CLI args. The CLI help notes that some providers
(codex app-server, openclaw) reject `--model` inside `custom_args` — but that is
documented CLI guidance, not a server-enforced invariant; nothing in the create
-handler inspects `custom_args` for a model flag.
+handler inspects `custom_args` for a model flag. Pi is stricter at invocation
+time: `--thinking` in `custom_args` is filtered because the first-class
+`thinking_level` field owns that flag and must be the only source of its value.
## Env & secrets
diff --git a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md
index 5d9c70be98..2a18694aaa 100644
--- a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md
+++ b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md
@@ -67,7 +67,7 @@ only.
| `description` ≤ 255 code points | 627–629 | `utf8.RuneCountInString(req.Description) > maxAgentDescriptionLength` → 400 |
| `runtime_id` required | 631–633 | `if req.RuntimeID == ""` → 400 "runtime_id is required" |
| `runtime_id` must resolve in workspace | 642–658 | parsed + `GetAgentRuntimeForWorkspace`; unknown → 400 "invalid runtime_id" |
-| `thinking_level` provider-level validation | 896–903 | `!agent.IsKnownThinkingValue(runtime.Provider, req.ThinkingLevel)` → 400; fixed providers use an enum, Codex/OpenCode use safe-token syntax, and per-model gaps are deferred to daemon (MUL-2339) |
+| `thinking_level` provider-level validation | `agent.go` create/update paths | `!agent.IsKnownThinkingValue(runtime.Provider, req.ThinkingLevel)` → 400; fixed-vocabulary providers use an enum (Pi: `off|minimal|low|medium|high|xhigh|max`), Codex/OpenCode use safe-token syntax, and per-model gaps are deferred to daemon (MUL-2339) |
| `thinking_level` rejection copy | `agent.go` `thinkingLevelRejection` / `existingThinkingLevelRejection` | Splits "runtime has no reasoning control" from "unrecognised token" so a runtime-capability 400 does not read as a typo; both carry-over branches point at `thinking_level=""` (MUL-5770) |
| `service_tier` provider-level validation | `agent.go` create/update paths | Non-empty values are Codex-only safe tokens; exact per-model support is daemon-owned |
| Defaults: `{}` config/env, `[]` args | 688–701 | `RuntimeConfig`→`{}`, `CustomEnv`→`{}`, `CustomArgs`→`[]` when nil, before insert |
@@ -97,9 +97,11 @@ only.
| Codex fallback catalog | `models.go` 301–354 | Used for Codex <0.122.0 and failed/malformed discovery; includes current verified visible models plus legacy `gpt-5.3-codex`, with a separate `Thinking` catalog on every model |
| Codex discovery version gate | `thinking.go` 280, 306–337 | `codex debug models --bundled` is used only for parseable versions ≥0.122.0; unsupported versions and command/parse/empty failures return the static model + thinking fallback |
| Codex catalog projection | `thinking.go` `parseCodexModelCatalog` | Hidden models are excluded; visible model, reasoning, and `service_tiers` metadata are preserved |
-| Per-model thinking validation | `thinking.go` 547–640 | `ValidateThinkingLevel` accepts only values in the explicit model's `Thinking.SupportedLevels`; an empty Codex model fails closed because its effective `config.toml` model is unknown |
-| Dynamic Codex token gate | `thinking.go` 642–710 | Server persistence accepts syntactically safe Codex tokens so new catalog values do not require a Multica release; exact support remains a daemon-local per-model check |
-| Runtime reasoning capability | `thinking.go` `ThinkingControlSupported` | True for the fixed-enum providers plus Codex/OpenCode. False for runtimes with no effort dial on the surface the daemon drives — Hermes' ACP adapter never carries `reasoning_config` onto a session, so its CLI-level `agent.reasoning_effort` cannot be reached from Multica (verified against Hermes Agent v0.18.2, MUL-5770) |
+| Pi RPC model/thinking discovery | `models.go` `discoverPiModelsRPC` / `piThinkingFromRPCModel` | Starts an ephemeral `pi --mode rpc --no-session` process, requests `get_state` + `get_available_models`, preserves extension-registered providers, marks the current model as Default, and mirrors Pi's exact per-model `reasoning` / `thinkingLevelMap` rules. Older/forked Pi falls back to `--list-models` with no guessed thinking catalog. |
+| Pi invocation effort | `pi.go` `buildPiArgs` / `piBlockedArgs` | A non-empty persisted value becomes `--thinking <level>`; custom `--thinking` flags are filtered so the first-class field is the sole owner. |
+| Per-model thinking validation | `thinking.go` `ValidateThinkingLevel` | Accepts only values in the explicit model's `Thinking.SupportedLevels`; Pi empty-model validation resolves to the RPC current-model Default, while an empty Codex model fails closed because its effective `config.toml` model is unknown. |
+| Dynamic Codex token gate | `thinking.go` `IsKnownThinkingValue` | Server persistence accepts syntactically safe Codex/OpenCode tokens so new catalog values do not require a Multica release; Pi instead uses its fixed seven-token CLI vocabulary. Exact support remains a daemon-local per-model check. |
+| Runtime reasoning capability | `thinking.go` `ThinkingControlSupported` | True for the fixed-enum providers (including Pi) plus Codex/OpenCode. False for runtimes with no effort dial on the surface the daemon drives — Hermes' ACP adapter never carries `reasoning_config` onto a session, so its CLI-level `agent.reasoning_effort` cannot be reached from Multica (verified against Hermes Agent v0.18.2, MUL-5770) |
| Per-model service-tier validation | `thinking.go` `ValidateServiceTier` | Accepts only a tier advertised for the explicit Codex model; empty model fails closed because config.toml is unknown |
| Daemon invalid-combination handling | `internal/daemon/daemon.go` 3860–3892 | Before execution, invalid `(provider, model, thinking_level)` combinations log a warning and omit the override rather than failing the task |
diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.go
index 870f7f9b50..293a114f2f 100644
--- a/server/pkg/agent/models.go
+++ b/server/pkg/agent/models.go
@@ -53,8 +53,9 @@ type ModelServiceTier struct {
// ModelThinking carries the per-model reasoning/effort catalog
// surfaced by an agent runtime. Values are runtime-native — Codex can emit
// "none|minimal|low|medium|high|xhigh|max|ultra"; Claude emits
-// "low|medium|high|xhigh|max". The frontend renders SupportedLevels
-// as-is so what users see matches each CLI's own UI.
+// "low|medium|high|xhigh|max"; Pi emits
+// "off|minimal|low|medium|high|xhigh|max". The frontend renders
+// SupportedLevels as-is so what users see matches each CLI's own UI.
type ModelThinking struct {
SupportedLevels []ThinkingLevel `json:"supported_levels"`
// DefaultLevel is the value the runtime picks when no override is
@@ -120,7 +121,7 @@ const modelCacheTTL = 60 * time.Second
// pi, openclaw) it shells out with caching and falls back where the
// provider has a safe static catalog.
//
-// For claude, codex, and opencode, the catalog is augmented with per-model
+// For claude, codex, opencode, and pi, the catalog is augmented with per-model
// thinking-level options discovered from the local CLI. Codex discovery
// failures fall back to a model + thinking snapshot; providers without a safe
// fallback leave Thinking nil, which makes the UI hide the thinking picker.
@@ -760,16 +761,251 @@ func openCodeThinkingLevelsFromVariants(variants map[string]opencodeModelVariant
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.
+var piThinkingLevelLabels = map[string]string{
+ "off": "Off",
+ "minimal": "Minimal",
+ "low": "Low",
+ "medium": "Medium",
+ "high": "High",
+ "xhigh": "Extra high",
+ "max": "Max",
+}
+
+var piThinkingLevelOrder = []string{"off", "minimal", "low", "medium", "high", "xhigh", "max"}
+
+// Keep Pi discovery within the established 15-second window while reserving a
+// real opportunity for the compatibility fallback when RPC hangs.
+const (
+ piRPCDiscoveryTimeout = 7 * time.Second
+ piTableDiscoveryTimeout = 8 * time.Second
+)
+
+type piRPCModel struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Provider string `json:"provider"`
+ Reasoning bool `json:"reasoning"`
+ ThinkingLevelMap map[string]*string `json:"thinkingLevelMap"`
+}
+
+type piRPCState struct {
+ Model *piRPCModel `json:"model"`
+ ThinkingLevel string `json:"thinkingLevel"`
+}
+
+type piRPCResponse struct {
+ ID string `json:"id"`
+ Type string `json:"type"`
+ Command string `json:"command"`
+ Success bool `json:"success"`
+ Data json.RawMessage `json:"data"`
+}
+
+// discoverPiModels asks Pi's RPC API for its machine-readable model catalog.
+// The RPC model objects carry the exact per-model reasoning metadata that the
+// human-readable `--list-models` table reduces to a yes/no column. Older Pi
+// versions and pi-family forks may not implement RPC, so discovery falls back
+// to the existing table parser without advertising a guessed thinking catalog.
func discoverPiModels(ctx context.Context, executablePath string) ([]Model, error) {
+ return discoverPiModelsWithin(ctx, executablePath, piRPCDiscoveryTimeout, piTableDiscoveryTimeout)
+}
+
+func discoverPiModelsWithin(ctx context.Context, executablePath string, rpcTimeout, tableTimeout time.Duration) ([]Model, error) {
if executablePath == "" {
executablePath = "pi"
}
- if _, err := exec.LookPath(executablePath); err != nil {
+ lookedUp, err := exec.LookPath(executablePath)
+ if err != nil {
return []Model{}, nil
}
+ // Split the established 15-second discovery budget so an RPC surface that
+ // accepts the mode but never answers cannot starve the compatibility table
+ // fallback. Both phase contexts still inherit caller cancellation.
+ rpcCtx, rpcCancel := context.WithTimeout(ctx, rpcTimeout)
+ models, ok := discoverPiModelsRPC(rpcCtx, executablePath, lookedUp)
+ rpcCancel()
+ if ok {
+ return models, nil
+ }
+
+ tableCtx, tableCancel := context.WithTimeout(ctx, tableTimeout)
+ defer tableCancel()
+ return discoverPiModelsTable(tableCtx, executablePath)
+}
+
+// discoverPiModelsRPC starts a short-lived Pi RPC session and requests both
+// the available models and current state. The state identifies the model Pi
+// will choose when Multica omits --model; its thinking level is the runtime's
+// effective default for that selected model.
+func discoverPiModelsRPC(ctx context.Context, executablePath, lookedUp string) ([]Model, bool) {
+ args := []string{
+ "--mode", "rpc",
+ "--no-session",
+ // Extensions stay enabled because Pi extensions can register providers
+ // and models; disabling them would make RPC discovery disagree with the
+ // catalog used by real task execution.
+ "--no-skills",
+ "--no-prompt-templates",
+ "--no-context-files",
+ }
+ argv0, cmdArgs := choosePiInvocation(executablePath, lookedUp, args, slog.Default())
+ cmd := exec.CommandContext(ctx, argv0, cmdArgs...)
+ hideAgentWindow(cmd)
+ cmd.WaitDelay = time.Second
+ cmd.Stderr = io.Discard
+
+ stdin, err := cmd.StdinPipe()
+ if err != nil {
+ return nil, false
+ }
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ _ = stdin.Close()
+ return nil, false
+ }
+ if err := cmd.Start(); err != nil {
+ _ = stdin.Close()
+ return nil, false
+ }
+
+ encoder := json.NewEncoder(stdin)
+ requests := []map[string]string{
+ {"id": "multica-state", "type": "get_state"},
+ {"id": "multica-models", "type": "get_available_models"},
+ }
+ for _, request := range requests {
+ if err := encoder.Encode(request); err != nil {
+ _ = stdin.Close()
+ _ = cmd.Wait()
+ return nil, false
+ }
+ }
+
+ var (
+ rawModels []piRPCModel
+ state piRPCState
+ modelsDone bool
+ stateDone bool
+ )
+ scanner := newAgentStreamScanner(stdout)
+ for scanner.Scan() {
+ var response piRPCResponse
+ if err := json.Unmarshal(scanner.Bytes(), &response); err != nil || response.Type != "response" {
+ continue
+ }
+ switch {
+ case response.ID == "multica-state" || response.Command == "get_state":
+ stateDone = true
+ if response.Success {
+ _ = json.Unmarshal(response.Data, &state)
+ }
+ case response.ID == "multica-models" || response.Command == "get_available_models":
+ modelsDone = true
+ if response.Success {
+ var payload struct {
+ Models []piRPCModel `json:"models"`
+ }
+ if err := json.Unmarshal(response.Data, &payload); err == nil {
+ rawModels = payload.Models
+ }
+ }
+ }
+ if modelsDone && stateDone {
+ break
+ }
+ }
+
+ // Pi's RPC loop waits for more commands while stdin remains open. EOF ends
+ // the throwaway session cleanly; the context remains a safety net for an
+ // older/forked CLI that ignores EOF or never completes both responses.
+ _ = stdin.Close()
+ _, _ = io.Copy(io.Discard, stdout)
+ if err := cmd.Wait(); err != nil && ctx.Err() == nil {
+ return nil, false
+ }
+ if !modelsDone || len(rawModels) == 0 {
+ return nil, false
+ }
+ return piModelsFromRPC(rawModels, state), true
+}
+
+func piModelsFromRPC(rawModels []piRPCModel, state piRPCState) []Model {
+ defaultID := ""
+ if state.Model != nil && state.Model.Provider != "" && state.Model.ID != "" {
+ defaultID = state.Model.Provider + "/" + state.Model.ID
+ }
+
+ models := make([]Model, 0, len(rawModels))
+ seen := make(map[string]bool, len(rawModels))
+ for _, raw := range rawModels {
+ provider := strings.TrimSpace(raw.Provider)
+ modelID := strings.TrimSpace(raw.ID)
+ if provider == "" || modelID == "" {
+ continue
+ }
+ id := provider + "/" + modelID
+ if seen[id] {
+ continue
+ }
+ seen[id] = true
+
+ model := Model{
+ ID: id,
+ Label: id,
+ Provider: provider,
+ Default: id == defaultID,
+ Thinking: piThinkingFromRPCModel(raw),
+ }
+ if model.Default && model.Thinking != nil && piThinkingSupports(model.Thinking, state.ThinkingLevel) {
+ model.Thinking.DefaultLevel = state.ThinkingLevel
+ }
+ models = append(models, model)
+ }
+ return models
+}
+
+// piThinkingFromRPCModel follows Pi's getSupportedThinkingLevels(model) for
+// reasoning-capable models: off..high are available unless explicitly mapped
+// to null; xhigh/max require an explicit non-null mapping. Pi reports only
+// "off" for reasoning=false; Multica intentionally hides that no-op picker.
+func piThinkingFromRPCModel(model piRPCModel) *ModelThinking {
+ if !model.Reasoning {
+ return nil
+ }
+ levels := make([]ThinkingLevel, 0, len(piThinkingLevelOrder))
+ for _, value := range piThinkingLevelOrder {
+ mapped, present := model.ThinkingLevelMap[value]
+ if present && mapped == nil {
+ continue
+ }
+ if (value == "xhigh" || value == "max") && !present {
+ continue
+ }
+ levels = append(levels, ThinkingLevel{Value: value, Label: piThinkingLevelLabels[value]})
+ }
+ if len(levels) == 0 {
+ return nil
+ }
+ return &ModelThinking{SupportedLevels: levels}
+}
+
+func piThinkingSupports(thinking *ModelThinking, value string) bool {
+ if thinking == nil || value == "" {
+ return false
+ }
+ for _, level := range thinking.SupportedLevels {
+ if level.Value == value {
+ return true
+ }
+ }
+ return false
+}
+
+// discoverPiModelsTable runs the legacy human-readable catalog command.
+// Older pi versions print the list to stderr; newer versions use stdout. We
+// capture both and parse whichever is non-empty. The fallback intentionally
+// leaves Thinking nil because the table exposes only a yes/no capability bit.
+func discoverPiModelsTable(ctx context.Context, executablePath string) ([]Model, error) {
// Newer pi fetches its catalog from each configured provider over the
// network, so discovery time scales with provider count — a multi-provider
// setup measured ~4.6-4.8s, right at the old 5s cap. When jitter pushed it
diff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.go
index bf6f07c6c0..749f3d5a76 100644
--- a/server/pkg/agent/models_test.go
+++ b/server/pkg/agent/models_test.go
@@ -8,6 +8,7 @@ import (
"strconv"
"strings"
"testing"
+ "time"
)
func TestStaticModelCatalogsHaveValidEntries(t *testing.T) {
@@ -644,6 +645,131 @@ func TestCachedDiscoveryDoesNotCacheEmpty(t *testing.T) {
}
}
+func writeFakePiRPCModelsBinary(t *testing.T) string {
+ t.Helper()
+ fakePath := filepath.Join(t.TempDir(), "pi")
+ script := `#!/bin/sh
+if [ "$1" = "--mode" ] && [ "$2" = "rpc" ]; then
+ IFS= read -r _state_request
+ IFS= read -r _models_request
+ printf '%s\n' '{"id":"multica-state","type":"response","command":"get_state","success":true,"data":{"model":{"id":"gpt-5.6-luna","name":"Luna","provider":"openai-multi","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":"none","low":"low","medium":null,"high":"high","xhigh":"xhigh","max":"max"}},"thinkingLevel":"max"}}'
+ printf '%s\n' '{"id":"multica-models","type":"response","command":"get_available_models","success":true,"data":{"models":[{"id":"gpt-5.6-sol","name":"Sol","provider":"openai-multi","reasoning":true},{"id":"gpt-5.6-luna","name":"Luna","provider":"openai-multi","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":"none","low":"low","medium":null,"high":"high","xhigh":"xhigh","max":"max"}},{"id":"plain-chat","name":"Plain chat","provider":"openai-multi","reasoning":false}]}}'
+ exit 0
+fi
+printf '%s\n' 'provider model context max-out thinking images'
+printf '%s\n' 'fallback fallback-model 128K 8K yes no'
+`
+ writeTestExecutable(t, fakePath, []byte(script))
+ return fakePath
+}
+
+func TestDiscoverPiModelsRPCThinkingCatalog(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("fake pi binary is a /bin/sh script")
+ }
+ fakePath := writeFakePiRPCModelsBinary(t)
+
+ models, err := discoverPiModels(context.Background(), fakePath)
+ if err != nil {
+ t.Fatalf("discoverPiModels: %v", err)
+ }
+ if len(models) != 3 {
+ t.Fatalf("expected 3 RPC models, got %d: %+v", len(models), models)
+ }
+ byID := make(map[string]Model, len(models))
+ for _, model := range models {
+ byID[model.ID] = model
+ }
+
+ sol := byID["openai-multi/gpt-5.6-sol"]
+ if sol.Thinking == nil || !hasThinkingLevel(sol.Thinking, "medium") || hasThinkingLevel(sol.Thinking, "xhigh") || hasThinkingLevel(sol.Thinking, "max") {
+ t.Fatalf("unexpected Sol thinking catalog: %+v", sol.Thinking)
+ }
+ luna := byID["openai-multi/gpt-5.6-luna"]
+ if !luna.Default {
+ t.Fatal("current Pi model must be marked as the runtime default")
+ }
+ if luna.Thinking == nil || luna.Thinking.DefaultLevel != "max" {
+ t.Fatalf("unexpected Luna thinking default: %+v", luna.Thinking)
+ }
+ for _, level := range []string{"off", "minimal", "low", "high", "xhigh", "max"} {
+ if !hasThinkingLevel(luna.Thinking, level) {
+ t.Errorf("Luna missing level %q: %+v", level, luna.Thinking)
+ }
+ }
+ if hasThinkingLevel(luna.Thinking, "medium") {
+ t.Errorf("explicitly null Pi level must stay disabled: %+v", luna.Thinking)
+ }
+ if got := byID["openai-multi/plain-chat"].Thinking; got != nil {
+ t.Fatalf("non-reasoning Pi model must not expose a picker: %+v", got)
+ }
+ if _, ok := byID["fallback/fallback-model"]; ok {
+ t.Fatal("successful RPC discovery must not append the table fallback")
+ }
+}
+
+func TestDiscoverPiModelsIDLessRPCErrorFallsBack(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("fake pi binary is a /bin/sh script")
+ }
+
+ fakePath := filepath.Join(t.TempDir(), "pi")
+ script := `#!/bin/sh
+if [ "$1" = "--mode" ] && [ "$2" = "rpc" ]; then
+ IFS= read -r _state_request
+ IFS= read -r _models_request
+ printf '%s\n' '{"id":"multica-state","type":"response","command":"get_state","success":true,"data":{"thinkingLevel":"high"}}'
+ printf '%s\n' '{"type":"response","command":"get_available_models","success":false,"error":"Unknown command: get_available_models"}'
+ cat >/dev/null
+ exit 0
+fi
+printf '%s\n' 'provider model context max-out thinking images'
+printf '%s\n' 'fallback fallback-model 128K 8K yes no'
+`
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ models, err := discoverPiModels(ctx, fakePath)
+ if err != nil {
+ t.Fatalf("discoverPiModels: %v", err)
+ }
+ if len(models) != 1 || models[0].ID != "fallback/fallback-model" {
+ t.Fatalf("ID-less RPC error must terminate that request and use the table fallback, got %+v", models)
+ }
+}
+
+func TestDiscoverPiModelsHungRPCPreservesTableFallbackBudget(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("fake pi binary is a /bin/sh script")
+ }
+
+ fakePath := filepath.Join(t.TempDir(), "pi")
+ script := `#!/bin/sh
+if [ "$1" = "--mode" ] && [ "$2" = "rpc" ]; then
+ IFS= read -r _state_request
+ IFS= read -r _models_request
+ exec sleep 30
+fi
+printf '%s\n' 'provider model context max-out thinking images'
+printf '%s\n' 'fallback fallback-model 128K 8K yes no'
+`
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ started := time.Now()
+ models, err := discoverPiModelsWithin(context.Background(), fakePath, 100*time.Millisecond, time.Second)
+ elapsed := time.Since(started)
+ if err != nil {
+ t.Fatalf("discoverPiModels: %v", err)
+ }
+ if len(models) != 1 || models[0].ID != "fallback/fallback-model" {
+ t.Fatalf("hung RPC must leave time for the table fallback, got %+v after %s", models, elapsed)
+ }
+ if elapsed >= 2*time.Second {
+ t.Fatalf("RPC phase consumed the table fallback budget: elapsed %s", elapsed)
+ }
+}
+
func TestParsePiModels(t *testing.T) {
input := `openai:gpt-4o
anthropic:claude-opus-4-7
@@ -788,6 +914,9 @@ func TestDiscoverPiModelsNonZeroExit(t *testing.T) {
if len(models) != 1 || models[0].ID != "glm-coding-plan/glm-4.7" {
t.Fatalf("expected exactly [glm-coding-plan/glm-4.7] despite non-zero exit, got %+v", models)
}
+ if models[0].Thinking != nil {
+ t.Fatalf("human-table fallback must not guess thinking levels: %+v", models[0].Thinking)
+ }
})
}
}
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.go
index e5c6266b3c..c4c4e14c46 100644
--- a/server/pkg/agent/pi.go
+++ b/server/pkg/agent/pi.go
@@ -502,10 +502,11 @@ func decodePiResult(raw json.RawMessage) string {
// overridden by user-configured custom_args. Overriding these would
// break the daemon↔Pi communication protocol.
var piBlockedArgs = map[string]blockedArgMode{
- "-p": blockedStandalone, // non-interactive mode
- "--print": blockedStandalone, // alias for -p
- "--mode": blockedWithValue, // "json" event stream protocol
- "--session": blockedWithValue, // daemon manages the session path
+ "-p": blockedStandalone, // non-interactive mode
+ "--print": blockedStandalone, // alias for -p
+ "--mode": blockedWithValue, // "json" event stream protocol
+ "--session": blockedWithValue, // daemon manages the session path
+ "--thinking": blockedWithValue, // owned by agent.thinking_level
}
// piCustomArgModes mirrors Pi 0.83's built-in parser closely enough to
@@ -575,6 +576,7 @@ var piCustomArgModes = map[string]blockedArgMode{
// --session <path> session log file (created upfront, reused on resume)
// --provider <name> provider, when Model is "provider/id"
// --model <id> model identifier
+// --thinking <level> per-agent reasoning level override
//
// The prompt is deliberately absent from argv. Pi reads a non-TTY stdin in
// print/JSON mode; using that supported path prevents Windows PowerShell's npm
@@ -596,6 +598,9 @@ func buildPiArgs(sessionPath string, opts ExecOptions, logger *slog.Logger) []st
args = append(args, "--model", model)
}
}
+ if opts.ThinkingLevel != "" {
+ args = append(args, "--thinking", opts.ThinkingLevel)
+ }
// Note: we intentionally do NOT pass --tools here. Omitting it lets
// Pi use its full tool registry, including user-installed extension
// tools. Passing --tools acts as a restrictive allowlist that
diff --git a/server/pkg/agent/pi_test.go b/server/pkg/agent/pi_test.go
index 1e3342e7fb..fc1948d41a 100644
--- a/server/pkg/agent/pi_test.go
+++ b/server/pkg/agent/pi_test.go
@@ -24,11 +24,12 @@ func TestBuildPiArgsNoToolAllowlist(t *testing.T) {
func TestBuildPiArgsBasicFlags(t *testing.T) {
args := buildPiArgs("/tmp/s.jsonl", ExecOptions{
- Model: "anthropic/claude-sonnet-4-20250514",
+ Model: "anthropic/claude-sonnet-4-20250514",
+ ThinkingLevel: "high",
}, slog.Default())
joined := strings.Join(args, " ")
- for _, want := range []string{"-p", "--mode json", "--session /tmp/s.jsonl", "--provider anthropic", "--model claude-sonnet-4-20250514"} {
+ for _, want := range []string{"-p", "--mode json", "--session /tmp/s.jsonl", "--provider anthropic", "--model claude-sonnet-4-20250514", "--thinking high"} {
if !strings.Contains(joined, want) {
t.Errorf("expected %q in args, got: %v", want, args)
}
@@ -87,7 +88,8 @@ func TestBuildPiArgsFiltersCustomInputButKeepsOptionValues(t *testing.T) {
"--verbose",
"after-boolean",
"--extension-option", "extension-value",
- "--thinking", "high",
+ "--thinking", "low",
+ "--thinking=medium",
"--offline",
"trailing-input",
},
@@ -102,7 +104,6 @@ func TestBuildPiArgsFiltersCustomInputButKeepsOptionValues(t *testing.T) {
for _, pair := range [][2]string{
{"--tools", "read,bash"},
{"--extension-option", "extension-value"},
- {"--thinking", "high"},
} {
found := false
for i := 0; i+1 < len(args); i++ {
@@ -115,6 +116,36 @@ func TestBuildPiArgsFiltersCustomInputButKeepsOptionValues(t *testing.T) {
t.Errorf("option/value %q %q missing from %v", pair[0], pair[1], args)
}
}
+ for _, arg := range args {
+ if arg == "--thinking" || strings.HasPrefix(arg, "--thinking=") || arg == "low" || arg == "medium" {
+ t.Errorf("custom --thinking must be owned by thinking_level and filtered, got %v", args)
+ }
+ }
+}
+
+func TestBuildPiArgsThinkingLevelOverridesCustomArgs(t *testing.T) {
+ t.Parallel()
+
+ args := buildPiArgs("/tmp/s.jsonl", ExecOptions{
+ ThinkingLevel: "max",
+ CustomArgs: []string{"--thinking", "low", "--thinking=medium"},
+ }, slog.Default())
+
+ count := 0
+ for i, arg := range args {
+ if arg == "--thinking" {
+ count++
+ if i+1 >= len(args) || args[i+1] != "max" {
+ t.Fatalf("selected thinking level missing from args: %v", args)
+ }
+ }
+ if strings.HasPrefix(arg, "--thinking=") {
+ t.Fatalf("custom inline thinking flag leaked through: %v", args)
+ }
+ }
+ if count != 1 {
+ t.Fatalf("expected exactly one daemon-owned --thinking flag, got %d in %v", count, args)
+ }
}
func TestPiExecuteRejectsEmptyPrompt(t *testing.T) {
diff --git a/server/pkg/agent/thinking.go b/server/pkg/agent/thinking.go
index a615c5ffc5..f2ff462add 100644
--- a/server/pkg/agent/thinking.go
+++ b/server/pkg/agent/thinking.go
@@ -11,8 +11,8 @@ import (
)
// thinking.go discovers per-model reasoning/effort catalogs for 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.
+// claude, codex, opencode, and pi 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|max|ultra`
@@ -760,6 +760,17 @@ var providerThinkingEnums = map[string]map[string]bool{
"medium": true,
"high": true,
},
+ // Pi owns a fixed CLI vocabulary; RPC discovery narrows this universe to
+ // the exact subset supported by each model before execution.
+ "pi": {
+ "off": true,
+ "minimal": true,
+ "low": true,
+ "medium": true,
+ "high": true,
+ "xhigh": true,
+ "max": true,
+ },
}
// thinkingDynamicCatalogProviders are the runtimes whose effort vocabulary is
diff --git a/server/pkg/agent/thinking_test.go b/server/pkg/agent/thinking_test.go
index 520423ebc8..a4fd865ba9 100644
--- a/server/pkg/agent/thinking_test.go
+++ b/server/pkg/agent/thinking_test.go
@@ -467,6 +467,12 @@ func TestIsKnownThinkingValue(t *testing.T) {
{"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
+ {"pi", "", true},
+ {"pi", "off", true},
+ {"pi", "minimal", true},
+ {"pi", "max", true},
+ {"pi", "ultra", false},
+ {"pi", "future-level", false},
{"hermes", "", true},
{"hermes", "low", false}, // hermes' ACP surface exposes no effort dial
{"grok", "", true},
@@ -501,6 +507,7 @@ func TestThinkingControlSupported(t *testing.T) {
{"grok", true},
{"codex", true}, // dynamic catalog, validated per model by the daemon
{"opencode", true}, // dynamic variant names from opencode.json
+ {"pi", true}, // fixed tokens, per-model subset discovered over RPC
{"hermes", false}, // ACP adapter drops reasoning entirely (MUL-5770)
{"kimi", false},
{"qwenpaw", false},
@@ -521,7 +528,7 @@ func TestThinkingControlSupported(t *testing.T) {
// reject a level while claiming the runtime supports one, or vice versa.
func TestThinkingControlSupportedMatchesTokenGate(t *testing.T) {
t.Parallel()
- providers := []string{"claude", "codebuddy", "grok", "codex", "opencode", "hermes", "kimi", "cursor"}
+ providers := []string{"claude", "codebuddy", "grok", "codex", "opencode", "pi", "hermes", "kimi", "cursor"}
// "medium" is in every fixed enum and is a well-formed dynamic token, so a
// provider with any reasoning control accepts it.
for _, provider := range providers {
@@ -557,6 +564,34 @@ func TestCodexAdvertisedLevelsArePersistable(t *testing.T) {
// layer call this; if it gets default-model wrong, any agent without an
// explicit model set would have its thinking_level dropped silently.
+func TestValidateThinkingLevel_PiRPCPerModelCatalog(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("fake pi binary is a /bin/sh script")
+ }
+ fakePi := writeFakePiRPCModelsBinary(t)
+ ctx := context.Background()
+
+ check := func(model, value string, want bool) {
+ t.Helper()
+ ok, err := ValidateThinkingLevel(ctx, "pi", fakePi, model, value)
+ if err != nil {
+ t.Fatalf("ValidateThinkingLevel(pi, %q, %q): %v", model, value, err)
+ }
+ if ok != want {
+ t.Errorf("ValidateThinkingLevel(pi, %q, %q) = %v, want %v", model, value, ok, want)
+ }
+ }
+
+ check("openai-multi/gpt-5.6-sol", "high", true)
+ check("openai-multi/gpt-5.6-sol", "xhigh", false)
+ check("openai-multi/gpt-5.6-luna", "max", true)
+ check("openai-multi/gpt-5.6-luna", "medium", false)
+ check("openai-multi/plain-chat", "off", false)
+ check("", "max", true) // current Pi model is Luna
+ check("", "medium", false) // Luna explicitly disables medium in the fixture
+ check("openai-multi/gpt-5.6-luna", "", true)
+}
+
func TestValidateThinkingLevel_EmptyModelResolvesToDefault(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script fake binary requires a POSIX shell")