feat(chat): per-chat permission modes for Claude, Codex and OpenCode
This commit is contained in:
@@ -171,6 +171,9 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
|
||||
s.appliedModel = requested
|
||||
s.mu.Unlock()
|
||||
}
|
||||
if err := s.applyMode(ctx, proc); err != nil {
|
||||
return err
|
||||
}
|
||||
content, err := promptContent(text, files)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -234,6 +234,7 @@ type session struct {
|
||||
directory string
|
||||
title string
|
||||
model string // CLI model selection (alias or full id); "" uses the CLI default
|
||||
mode string // permission mode id; "" uses the CLI's own default
|
||||
createdAt int64
|
||||
|
||||
proc *process
|
||||
|
||||
@@ -456,3 +456,58 @@ func TestSignedOutCLIReturnsAnActionableError(t *testing.T) {
|
||||
t.Fatalf("error is not actionable: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermissionModeStartsTheCLIAndSwitchesALiveOne(t *testing.T) {
|
||||
chat := testChat(t)
|
||||
modeLog := filepath.Join(t.TempDir(), "modes.log")
|
||||
t.Setenv("FAKE_CLAUDE_MODE_LOG", modeLog)
|
||||
session := newCreatedChat(t, chat)
|
||||
ctx := context.Background()
|
||||
if err := chat.SetMode(ctx, session.ID, "dontAsk"); err == nil {
|
||||
t.Fatal("an unlisted mode was accepted")
|
||||
}
|
||||
modes, err := chat.Modes(ctx, session.ID)
|
||||
if err != nil || len(modes) != 5 || modes[0].ID != defaultMode || modes[3].ID != "auto" {
|
||||
t.Fatalf("modes: %+v %v", modes, err)
|
||||
}
|
||||
if err := chat.SetMode(ctx, session.ID, "auto"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
frames := subscribe(t, chat, session.ID)
|
||||
if err := chat.Prompt(ctx, session.ID, "hello"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitStepEnded(t, frames)
|
||||
entries := readArgs(t, os.Getenv("FAKE_CLAUDE_LOG"))
|
||||
if argValue(entries[len(entries)-1].Args, "--permission-mode") != "auto" {
|
||||
t.Fatalf("spawn did not start in the chosen mode: %+v", entries)
|
||||
}
|
||||
if _, err := os.Stat(modeLog); err == nil {
|
||||
t.Fatal("a process started in its mode was switched again")
|
||||
}
|
||||
|
||||
// A running CLI switches in place, without a restart.
|
||||
if err := chat.SetMode(ctx, session.ID, "plan"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if data, _ := os.ReadFile(modeLog); strings.TrimSpace(string(data)) != "plan" {
|
||||
t.Fatalf("live switch sent %q", data)
|
||||
}
|
||||
if count := len(readArgs(t, os.Getenv("FAKE_CLAUDE_LOG"))); count != len(entries) {
|
||||
t.Fatalf("the live switch restarted the CLI: %d spawns", count)
|
||||
}
|
||||
|
||||
// Back to the default: the flag is omitted on a fresh process.
|
||||
if err := chat.SetMode(ctx, session.ID, defaultMode); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat.session(session.ID).closeProcess()
|
||||
if err := chat.Prompt(ctx, session.ID, "again"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitStepEnded(t, frames)
|
||||
entries = readArgs(t, os.Getenv("FAKE_CLAUDE_LOG"))
|
||||
if argValue(entries[len(entries)-1].Args, "--permission-mode") != "" {
|
||||
t.Fatalf("the default mode passed a flag: %+v", entries[len(entries)-1])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// defaultMode is Claude Code's own ask-for-permission mode. The CLI flag has no
|
||||
// spelling for it, so a process in this mode is started without the flag; the
|
||||
// control request accepts it by name.
|
||||
const defaultMode = "default"
|
||||
|
||||
// chatModes are the Claude Code permission modes a chat can run in, in the
|
||||
// order the CLI cycles them. dontAsk is left out: it silently denies anything
|
||||
// not pre-approved, which a chat on a phone cannot recover from.
|
||||
var chatModes = []protocol.ChatMode{
|
||||
{ID: defaultMode, Name: "Ask for permission", Description: "Ask before edits and commands."},
|
||||
{ID: "acceptEdits", Name: "Accept edits", Description: "Make file edits without asking; ask for other actions."},
|
||||
{ID: "plan", Name: "Plan", Description: "Explore and plan without changing anything."},
|
||||
{ID: "auto", Name: "Auto", Description: "Act without asking, with Claude Code's safety checks."},
|
||||
{ID: "bypassPermissions", Name: "Bypass permissions", Description: "Never ask. Everything runs without checks."},
|
||||
}
|
||||
|
||||
// Modes lists the permission modes a Claude chat can switch to.
|
||||
func (c *Chat) Modes(context.Context, string) ([]protocol.ChatMode, error) {
|
||||
return append([]protocol.ChatMode(nil), chatModes...), nil
|
||||
}
|
||||
|
||||
func knownMode(mode string) bool {
|
||||
for _, known := range chatModes {
|
||||
if known.ID == mode {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetMode records the session's permission mode and applies it to a running
|
||||
// CLI at once; a later process starts in it.
|
||||
func (c *Chat) SetMode(ctx context.Context, id, mode string) error {
|
||||
if !knownMode(mode) {
|
||||
return fmt.Errorf("unknown Claude permission mode %q", mode)
|
||||
}
|
||||
s := c.session(id)
|
||||
if s == nil {
|
||||
meta, ok := transcriptSession(id)
|
||||
if !ok {
|
||||
return errors.New("unknown Claude session " + id)
|
||||
}
|
||||
s = c.sessionFor(id, meta.Directory)
|
||||
}
|
||||
s.mu.Lock()
|
||||
previous := s.mode
|
||||
s.mode = mode
|
||||
proc := s.proc
|
||||
s.mu.Unlock()
|
||||
if proc == nil {
|
||||
return nil
|
||||
}
|
||||
if err := s.applyMode(ctx, proc); err != nil {
|
||||
s.mu.Lock()
|
||||
s.mode = previous
|
||||
s.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyMode tells a running CLI the session's mode when it runs in another.
|
||||
func (s *session) applyMode(ctx context.Context, proc *process) error {
|
||||
s.mu.Lock()
|
||||
requested, current := s.mode, proc.mode
|
||||
s.mu.Unlock()
|
||||
if requested == "" || requested == current || (current == "" && requested == defaultMode) {
|
||||
return nil
|
||||
}
|
||||
setCtx, cancel := context.WithTimeout(ctx, controlRequestTimeout)
|
||||
defer cancel()
|
||||
if _, err := proc.request(setCtx, "set_permission_mode", map[string]any{"mode": requested}); err != nil {
|
||||
return fmt.Errorf("switch Claude permission mode: %w", err)
|
||||
}
|
||||
s.mu.Lock()
|
||||
proc.mode = requested
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
@@ -44,6 +44,10 @@ type process struct {
|
||||
exitErr error
|
||||
done chan struct{}
|
||||
stderrDone chan struct{}
|
||||
|
||||
// mode is the permission mode this process runs in, guarded by the
|
||||
// session's mu: set at spawn and after a confirmed set_permission_mode.
|
||||
mode string
|
||||
}
|
||||
|
||||
type controlReply struct {
|
||||
@@ -80,6 +84,12 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
|
||||
if s.model != "" {
|
||||
args = append(args, "--model", s.model)
|
||||
}
|
||||
s.mu.Lock()
|
||||
mode := s.mode
|
||||
s.mu.Unlock()
|
||||
if mode != "" && mode != defaultMode {
|
||||
args = append(args, "--permission-mode", mode)
|
||||
}
|
||||
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
|
||||
cmd.Dir = s.directory
|
||||
cmd.Env = s.chat.auth.resolve(s.chat.ctx, s.chat.binary, withServiceToken(os.Environ()))
|
||||
@@ -99,7 +109,7 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, fmt.Errorf("start Claude Code: %w", err)
|
||||
}
|
||||
p := &process{session: s, cmd: cmd, stdin: stdin, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{})}
|
||||
p := &process{session: s, cmd: cmd, stdin: stdin, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{}), mode: mode}
|
||||
go p.readStderr(stderr)
|
||||
go p.readStdout(stdout)
|
||||
go p.wait()
|
||||
|
||||
+8
-1
@@ -2,7 +2,8 @@
|
||||
"""Deterministic stand-in for the Claude Code CLI's SDK stdio protocol.
|
||||
|
||||
It implements only what Pipelines' adapter uses: initialize, stream-json turns,
|
||||
can_use_tool approvals, AskUserQuestion, set_model, interrupt, usage queries and
|
||||
can_use_tool approvals, AskUserQuestion, set_model, set_permission_mode,
|
||||
interrupt, usage queries and
|
||||
a session transcript. It never contacts a provider.
|
||||
"""
|
||||
import json
|
||||
@@ -157,6 +158,12 @@ def handle(line):
|
||||
elif subtype == "set_model":
|
||||
state["model"] = request.get("model")
|
||||
respond(value.get("request_id"), {"model": request.get("model")})
|
||||
elif subtype == "set_permission_mode":
|
||||
mode_log = os.environ.get("FAKE_CLAUDE_MODE_LOG")
|
||||
if mode_log:
|
||||
with open(mode_log, "a", encoding="utf-8") as log:
|
||||
log.write(request.get("mode", "") + "\n")
|
||||
respond(value.get("request_id"), {"mode": request.get("mode")})
|
||||
elif subtype == "interrupt":
|
||||
respond(value.get("request_id"), {"still_queued": [], "cancelled": []})
|
||||
if state["pending"]:
|
||||
|
||||
Reference in New Issue
Block a user