feat(chat): broker Codex approvals and complete typed tool interactions
This commit is contained in:
@@ -0,0 +1,196 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sort"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
type pendingApproval struct {
|
||||
requestID json.RawMessage
|
||||
method string
|
||||
frame protocol.ChatPermissionFrame
|
||||
permissions map[string]any
|
||||
answering bool
|
||||
}
|
||||
|
||||
func (c *Chat) respondResult(ctx context.Context, id json.RawMessage, result any) error {
|
||||
data, err := json.Marshal(map[string]any{"id": id, "result": result})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.writeMu.Lock()
|
||||
defer c.writeMu.Unlock()
|
||||
return c.conn.Write(ctx, websocket.MessageText, data)
|
||||
}
|
||||
|
||||
func (c *Chat) respondUnsupported(id json.RawMessage) {
|
||||
data, _ := json.Marshal(map[string]any{"id": id, "error": map[string]any{"code": -32601, "message": "This client does not support this interaction"}})
|
||||
c.writeMu.Lock()
|
||||
defer c.writeMu.Unlock()
|
||||
_ = c.conn.Write(c.ctx, websocket.MessageText, data)
|
||||
}
|
||||
|
||||
// receiveApproval retains the exact callback identity. itemId is not unique:
|
||||
// Code Mode can have multiple subcommand approvals beneath the same item.
|
||||
func (c *Chat) receiveApproval(msg rpcMessage) {
|
||||
var p struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
ItemID string `json:"itemId"`
|
||||
Command string `json:"command"`
|
||||
Cwd string `json:"cwd"`
|
||||
Reason string `json:"reason"`
|
||||
GrantRoot string `json:"grantRoot"`
|
||||
Permissions map[string]any `json:"permissions"`
|
||||
Network *struct {
|
||||
Host string `json:"host"`
|
||||
Protocol string `json:"protocol"`
|
||||
} `json:"networkApprovalContext"`
|
||||
}
|
||||
if json.Unmarshal(msg.Params, &p) != nil || p.ThreadID == "" || p.ItemID == "" {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
id := "codex_" + base64.RawURLEncoding.EncodeToString(msg.ID)
|
||||
frame := protocol.ChatPermissionFrame{SessionID: p.ThreadID, RequestID: id, Action: "command execution", Message: p.Reason, AlwaysLabel: "Allow for session"}
|
||||
if p.Command != "" {
|
||||
frame.Resources = append(frame.Resources, p.Command)
|
||||
}
|
||||
if p.Cwd != "" {
|
||||
frame.Resources = append(frame.Resources, "Directory: "+p.Cwd)
|
||||
}
|
||||
if msg.Method == "item/fileChange/requestApproval" {
|
||||
frame.Action = "file changes"
|
||||
if p.GrantRoot != "" {
|
||||
frame.Resources = append(frame.Resources, p.GrantRoot)
|
||||
}
|
||||
}
|
||||
if p.Network != nil {
|
||||
frame.Action = "network access"
|
||||
frame.Resources = append(frame.Resources, p.Network.Protocol+"://"+p.Network.Host)
|
||||
}
|
||||
if msg.Method == "item/permissions/requestApproval" {
|
||||
frame.Action = "additional permissions"
|
||||
if p.Permissions == nil {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
raw, _ := json.MarshalIndent(p.Permissions, "", " ")
|
||||
frame.Resources = append(frame.Resources, string(raw))
|
||||
}
|
||||
c.mu.Lock()
|
||||
if c.approvals == nil {
|
||||
c.approvals = map[string]pendingApproval{}
|
||||
}
|
||||
c.approvals[id] = pendingApproval{requestID: msg.ID, method: msg.Method, frame: frame, permissions: p.Permissions}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
func (c *Chat) Permissions(_ context.Context, id string) ([]protocol.ChatPermissionFrame, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.connectionErr != nil {
|
||||
return nil, c.connectionErr
|
||||
}
|
||||
frames := []protocol.ChatPermissionFrame{}
|
||||
for _, p := range c.approvals {
|
||||
if p.frame.SessionID == id {
|
||||
frames = append(frames, p.frame)
|
||||
}
|
||||
}
|
||||
sort.Slice(frames, func(i, j int) bool { return frames[i].RequestID < frames[j].RequestID })
|
||||
return frames, nil
|
||||
}
|
||||
|
||||
func (c *Chat) Forms(_ context.Context, id string) ([]protocol.ChatForm, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.connectionErr != nil {
|
||||
return nil, c.connectionErr
|
||||
}
|
||||
forms := []protocol.ChatForm{}
|
||||
for _, p := range c.forms {
|
||||
if p.threadID == id {
|
||||
forms = append(forms, p.form)
|
||||
}
|
||||
}
|
||||
sort.Slice(forms, func(i, j int) bool { return forms[i].ID < forms[j].ID })
|
||||
return forms, nil
|
||||
}
|
||||
|
||||
func (c *Chat) resolveInteraction(thread string, id json.RawMessage) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
for key, p := range c.approvals {
|
||||
if p.frame.SessionID == thread && string(p.requestID) == string(id) {
|
||||
delete(c.approvals, key)
|
||||
}
|
||||
}
|
||||
for key, p := range c.forms {
|
||||
if p.threadID == thread && string(p.requestID) == string(id) {
|
||||
delete(c.forms, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) Reply(ctx context.Context, request protocol.ChatReplyRequest) error {
|
||||
c.mu.Lock()
|
||||
p, ok := c.approvals[request.RequestID]
|
||||
if !ok || p.frame.SessionID != request.SessionID || p.answering {
|
||||
c.mu.Unlock()
|
||||
return errors.New("the Codex approval is no longer awaiting an answer")
|
||||
}
|
||||
var result any
|
||||
if p.method == "item/permissions/requestApproval" {
|
||||
granted := map[string]any{}
|
||||
scope := "turn"
|
||||
switch request.Decision {
|
||||
case protocol.ChatDecisionAlways:
|
||||
scope = "session"
|
||||
fallthrough
|
||||
case protocol.ChatDecisionOnce:
|
||||
for key, value := range p.permissions {
|
||||
if (key == "network" || key == "fileSystem") && value != nil {
|
||||
granted[key] = value
|
||||
}
|
||||
}
|
||||
case protocol.ChatDecisionReject:
|
||||
default:
|
||||
c.mu.Unlock()
|
||||
return errors.New("invalid approval decision")
|
||||
}
|
||||
result = map[string]any{"permissions": granted, "scope": scope}
|
||||
} else {
|
||||
decision := ""
|
||||
switch request.Decision {
|
||||
case protocol.ChatDecisionOnce:
|
||||
decision = "accept"
|
||||
case protocol.ChatDecisionAlways:
|
||||
decision = "acceptForSession"
|
||||
case protocol.ChatDecisionReject:
|
||||
decision = "decline"
|
||||
default:
|
||||
c.mu.Unlock()
|
||||
return errors.New("invalid approval decision")
|
||||
}
|
||||
result = map[string]any{"decision": decision}
|
||||
}
|
||||
p.answering = true
|
||||
c.approvals[request.RequestID] = p
|
||||
c.mu.Unlock()
|
||||
err := c.respondResult(ctx, p.requestID, result)
|
||||
c.mu.Lock()
|
||||
if err == nil {
|
||||
delete(c.approvals, request.RequestID)
|
||||
} else if _, exists := c.approvals[request.RequestID]; exists {
|
||||
p.answering = false
|
||||
c.approvals[request.RequestID] = p
|
||||
}
|
||||
c.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
)
|
||||
|
||||
func approvalChat(t *testing.T) (*Chat, <-chan rpcMessage) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
responses := make(chan rpcMessage, 8)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
for {
|
||||
var msg rpcMessage
|
||||
if wsjson.Read(ctx, conn, &msg) != nil {
|
||||
return
|
||||
}
|
||||
responses <- msg
|
||||
}
|
||||
}))
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http"), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := &Chat{conn: conn, ctx: ctx, cancel: cancel, forms: map[string]pendingForm{}}
|
||||
t.Cleanup(func() { cancel(); conn.CloseNow(); srv.Close() })
|
||||
return c, responses
|
||||
}
|
||||
|
||||
func TestApprovalCallbacksAreDistinctAndSessionOwned(t *testing.T) {
|
||||
c, replies := approvalChat(t)
|
||||
for _, id := range []string{`1`, `"second-callback"`} {
|
||||
c.receiveApproval(rpcMessage{ID: json.RawMessage(id), Method: "item/commandExecution/requestApproval", Params: json.RawMessage(`{"threadId":"thread-a","itemId":"shared-item","command":"echo test","cwd":"/work"}`)})
|
||||
}
|
||||
pending, _ := c.Permissions(context.Background(), "thread-a")
|
||||
if len(pending) != 2 || pending[0].RequestID == pending[1].RequestID {
|
||||
t.Fatalf("callbacks collapsed: %+v", pending)
|
||||
}
|
||||
for i, p := range pending {
|
||||
if err := c.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: "foreign", RequestID: p.RequestID, Decision: protocol.ChatDecisionOnce}); err == nil {
|
||||
t.Fatal("cross-session approval accepted")
|
||||
}
|
||||
decision := protocol.ChatDecisionOnce
|
||||
want := "accept"
|
||||
if i == 1 {
|
||||
decision = protocol.ChatDecisionAlways
|
||||
want = "acceptForSession"
|
||||
}
|
||||
if err := c.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: "thread-a", RequestID: p.RequestID, Decision: decision}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case msg := <-replies:
|
||||
var result struct {
|
||||
Decision string `json:"decision"`
|
||||
}
|
||||
json.Unmarshal(msg.Result, &result)
|
||||
if result.Decision != want || string(msg.ID) != string(capturedApprovalID(p.RequestID)) {
|
||||
t.Fatalf("wrong reply: %+v", msg)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("approval response not delivered")
|
||||
}
|
||||
}
|
||||
pending, _ = c.Permissions(context.Background(), "thread-a")
|
||||
if len(pending) != 0 {
|
||||
t.Fatal("completed approvals retained")
|
||||
}
|
||||
}
|
||||
|
||||
func capturedApprovalID(id string) []byte {
|
||||
raw, _ := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(id, "codex_"))
|
||||
return raw
|
||||
}
|
||||
|
||||
func TestPermissionGrantNeverAddsUnrequestedAccess(t *testing.T) {
|
||||
for _, decision := range []string{protocol.ChatDecisionOnce, protocol.ChatDecisionAlways, protocol.ChatDecisionReject} {
|
||||
t.Run(decision, func(t *testing.T) {
|
||||
c, replies := approvalChat(t)
|
||||
c.receiveApproval(rpcMessage{ID: json.RawMessage(`99`), Method: "item/permissions/requestApproval", Params: json.RawMessage(`{"threadId":"thread-a","itemId":"item","permissions":{"network":{"enabled":true},"fileSystem":null,"unrecognized":"never grant"}}`)})
|
||||
pending, _ := c.Permissions(context.Background(), "thread-a")
|
||||
if err := c.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: "thread-a", RequestID: pending[0].RequestID, Decision: decision}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msg := <-replies
|
||||
var response struct {
|
||||
Permissions map[string]any `json:"permissions"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
json.Unmarshal(msg.Result, &response)
|
||||
if _, ok := response.Permissions["unrecognized"]; ok {
|
||||
t.Fatal("granted unknown access")
|
||||
}
|
||||
want := 1
|
||||
if decision == protocol.ChatDecisionReject {
|
||||
want = 0
|
||||
}
|
||||
if len(response.Permissions) != want {
|
||||
t.Fatalf("grant=%s", msg.Result)
|
||||
}
|
||||
if (response.Scope == "session") != (decision == protocol.ChatDecisionAlways) {
|
||||
t.Fatalf("wrong scope: %s", msg.Result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexQuestionReadbackAndOwnership(t *testing.T) {
|
||||
c, _ := approvalChat(t)
|
||||
c.forms["question"] = pendingForm{threadID: "thread-a", form: protocol.ChatForm{ID: "question", SessionID: "thread-a"}}
|
||||
forms, _ := c.Forms(context.Background(), "thread-a")
|
||||
if len(forms) != 1 {
|
||||
t.Fatal("pending question not recoverable")
|
||||
}
|
||||
if err := c.Answer(context.Background(), protocol.ChatAnswerRequest{SessionID: "foreign", FormID: "question", Answers: map[string]any{"a": "no"}}); err == nil {
|
||||
t.Fatal("foreign session answered question")
|
||||
}
|
||||
forms, _ = c.Forms(context.Background(), "thread-a")
|
||||
if len(forms) != 1 {
|
||||
t.Fatal("refused reply consumed pending question")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPElicitationUsesTypedAnswersAndExplicitCancellation(t *testing.T) {
|
||||
for _, action := range []string{"accept", "cancel", "decline"} {
|
||||
t.Run(action, func(t *testing.T) {
|
||||
c, replies := approvalChat(t)
|
||||
c.handleServerRequest(rpcMessage{ID: json.RawMessage(`"mcp-request"`), Method: "mcpServer/elicitation/request", Params: json.RawMessage(`{"threadId":"thread-a","mode":"form","message":"MCP input","requestedSchema":{"type":"object","properties":{"enabled":{"type":"boolean"},"count":{"type":"integer","minimum":0}},"required":["enabled","count"]}}`)})
|
||||
forms, err := c.Forms(context.Background(), "thread-a")
|
||||
if err != nil || len(forms) != 1 || len(forms[0].Fields) != 2 {
|
||||
t.Fatalf("forms=%+v err=%v", forms, err)
|
||||
}
|
||||
if err := c.Answer(context.Background(), protocol.ChatAnswerRequest{SessionID: "thread-a", FormID: forms[0].ID, Action: action, Answers: map[string]any{"enabled": false, "count": 0}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msg := <-replies
|
||||
var result struct {
|
||||
Action string `json:"action"`
|
||||
Content map[string]any `json:"content"`
|
||||
}
|
||||
json.Unmarshal(msg.Result, &result)
|
||||
if result.Action != action {
|
||||
t.Fatalf("wrong action: %s", msg.Result)
|
||||
}
|
||||
if action == "accept" {
|
||||
if result.Content["enabled"] != false || result.Content["count"] != float64(0) {
|
||||
t.Fatalf("lost typed values: %s", msg.Result)
|
||||
}
|
||||
} else if result.Content != nil {
|
||||
t.Fatal("cancel/decline returned content")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvedCallbackClearsOnlyItsOwner(t *testing.T) {
|
||||
c, _ := approvalChat(t)
|
||||
c.receiveApproval(rpcMessage{ID: json.RawMessage(`7`), Method: "item/fileChange/requestApproval", Params: json.RawMessage(`{"threadId":"thread-a","itemId":"item","grantRoot":"/work"}`)})
|
||||
c.handleNotification(rpcMessage{Method: "serverRequest/resolved", Params: json.RawMessage(`{"threadId":"foreign","requestId":7}`)})
|
||||
pending, _ := c.Permissions(context.Background(), "thread-a")
|
||||
if len(pending) != 1 {
|
||||
t.Fatal("foreign notification consumed approval")
|
||||
}
|
||||
c.handleNotification(rpcMessage{Method: "serverRequest/resolved", Params: json.RawMessage(`{"threadId":"thread-a","requestId":7}`)})
|
||||
pending, _ = c.Permissions(context.Background(), "thread-a")
|
||||
if len(pending) != 0 {
|
||||
t.Fatal("resolved callback not removed")
|
||||
}
|
||||
}
|
||||
+71
-32
@@ -49,19 +49,23 @@ type Chat struct {
|
||||
writeMu sync.Mutex
|
||||
nextID int64
|
||||
|
||||
mu sync.Mutex
|
||||
pending map[string]chan rpcResponse
|
||||
subs map[string]map[chan protocol.ChatEventFrame]struct{}
|
||||
forms map[string]pendingForm
|
||||
turns map[string]string
|
||||
emitted map[string]bool
|
||||
closed bool
|
||||
mu sync.Mutex
|
||||
pending map[string]chan rpcResponse
|
||||
subs map[string]map[chan protocol.ChatEventFrame]struct{}
|
||||
forms map[string]pendingForm
|
||||
approvals map[string]pendingApproval
|
||||
turns map[string]string
|
||||
emitted map[string]bool
|
||||
closed bool
|
||||
connectionErr error
|
||||
}
|
||||
|
||||
type pendingForm struct {
|
||||
requestID json.RawMessage
|
||||
threadID string
|
||||
form protocol.ChatForm
|
||||
requestID json.RawMessage
|
||||
threadID string
|
||||
form protocol.ChatForm
|
||||
answering bool
|
||||
elicitation bool
|
||||
}
|
||||
|
||||
type rpcResponse struct {
|
||||
@@ -177,6 +181,9 @@ func (c *Chat) readLoop() {
|
||||
|
||||
func (c *Chat) failPending(err error) {
|
||||
c.mu.Lock()
|
||||
c.connectionErr = err
|
||||
c.approvals = nil
|
||||
c.forms = map[string]pendingForm{}
|
||||
pending := c.pending
|
||||
c.pending = map[string]chan rpcResponse{}
|
||||
subs := c.subs
|
||||
@@ -340,23 +347,12 @@ func (c *Chat) PromptWithMessageIDModel(ctx context.Context, id, text, messageID
|
||||
return err
|
||||
}
|
||||
|
||||
// Permissions is empty: Codex approvals are disabled on threads this adapter
|
||||
// creates (approvalPolicy never), and questions arrive as requestUserInput.
|
||||
func (c *Chat) Permissions(context.Context, string) ([]protocol.ChatPermissionFrame, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Shells is empty: Codex background terminals are not exposed through the chat
|
||||
// surface yet.
|
||||
func (c *Chat) Shells(context.Context, string) ([]protocol.ChatShell, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Reply is unused because Codex approvals are not created for these threads.
|
||||
func (c *Chat) Reply(context.Context, protocol.ChatReplyRequest) error {
|
||||
return errors.New("Codex approvals are not enabled for this chat backend")
|
||||
}
|
||||
|
||||
// ActivateSkill is an OpenCode-only chat concept.
|
||||
func (c *Chat) ActivateSkill(context.Context, string, string) error {
|
||||
return errors.New("Codex chat has no out-of-band skill activation")
|
||||
@@ -380,9 +376,8 @@ func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.Ch
|
||||
return protocol.ChatSession{}, errors.New("a directory is required")
|
||||
}
|
||||
raw, err := c.call(ctx, "thread/start", map[string]any{
|
||||
"cwd": directory,
|
||||
"approvalPolicy": "never",
|
||||
"sandbox": "workspace-write",
|
||||
"cwd": directory,
|
||||
"sandbox": "workspace-write",
|
||||
})
|
||||
if err != nil {
|
||||
return protocol.ChatSession{}, err
|
||||
@@ -481,10 +476,20 @@ func (c *Chat) Messages(ctx context.Context, id string, limit int, cursor string
|
||||
|
||||
// Answer replies to a pending requestUserInput request.
|
||||
func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) error {
|
||||
if request.Action != "" && request.Action != "accept" && request.Action != "cancel" && request.Action != "decline" {
|
||||
return errors.New("invalid form action")
|
||||
}
|
||||
c.mu.Lock()
|
||||
pending, ok := c.forms[request.FormID]
|
||||
if ok {
|
||||
delete(c.forms, request.FormID)
|
||||
if request.Action != "" && request.Action != "accept" && (!ok || !pending.elicitation) {
|
||||
c.mu.Unlock()
|
||||
return errors.New("this Codex question does not support that action")
|
||||
}
|
||||
if ok && pending.threadID == request.SessionID && !pending.answering {
|
||||
pending.answering = true
|
||||
c.forms[request.FormID] = pending
|
||||
} else {
|
||||
ok = false
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if !ok {
|
||||
@@ -503,7 +508,30 @@ func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) e
|
||||
answers[key] = map[string]any{"answers": []string{fmt.Sprint(v)}}
|
||||
}
|
||||
}
|
||||
c.respond(pending.requestID, map[string]any{"answers": answers})
|
||||
var result any = map[string]any{"answers": answers}
|
||||
if pending.elicitation {
|
||||
action := request.Action
|
||||
if action == "" {
|
||||
action = "accept"
|
||||
}
|
||||
var content any = request.Answers
|
||||
if action != "accept" {
|
||||
content = nil
|
||||
}
|
||||
result = map[string]any{"action": action, "content": content, "_meta": nil}
|
||||
}
|
||||
err := c.respondResult(ctx, pending.requestID, result)
|
||||
c.mu.Lock()
|
||||
if err == nil {
|
||||
delete(c.forms, request.FormID)
|
||||
} else if _, exists := c.forms[request.FormID]; exists {
|
||||
pending.answering = false
|
||||
c.forms[request.FormID] = pending
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.emit(protocol.ChatEventFrame{
|
||||
SessionID: pending.threadID,
|
||||
Kind: protocol.ChatEventForm,
|
||||
@@ -546,6 +574,7 @@ func (c *Chat) handleServerRequest(msg rpcMessage) {
|
||||
field := protocol.ChatFormField{
|
||||
Key: q.ID, Title: q.Question, Description: q.Header,
|
||||
Type: "string", Custom: q.IsOther, Required: true,
|
||||
Secret: q.IsSecret,
|
||||
}
|
||||
for _, option := range q.Options {
|
||||
value := option.Value
|
||||
@@ -562,17 +591,27 @@ func (c *Chat) handleServerRequest(msg rpcMessage) {
|
||||
c.forms[form.ID] = pendingForm{requestID: msg.ID, threadID: params.ThreadID, form: form}
|
||||
c.mu.Unlock()
|
||||
c.emit(protocol.ChatEventFrame{SessionID: params.ThreadID, Kind: protocol.ChatEventForm, Form: &form})
|
||||
case "item/commandExecution/requestApproval", "item/fileChange/requestApproval":
|
||||
// The thread is created with approvalPolicy never; if a provider still asks,
|
||||
// deny rather than leave the turn hanging.
|
||||
c.respond(msg.ID, map[string]any{"decision": "deny"})
|
||||
case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval":
|
||||
c.receiveApproval(msg)
|
||||
case "mcpServer/elicitation/request":
|
||||
c.receiveElicitation(msg)
|
||||
default:
|
||||
// Unknown server requests must not stall the shared connection.
|
||||
c.respond(msg.ID, map[string]any{})
|
||||
c.respondUnsupported(msg.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) handleNotification(msg rpcMessage) {
|
||||
if msg.Method == "serverRequest/resolved" {
|
||||
var p struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
RequestID json.RawMessage `json:"requestId"`
|
||||
}
|
||||
if json.Unmarshal(msg.Params, &p) == nil && p.ThreadID != "" && len(p.RequestID) > 0 {
|
||||
c.resolveInteraction(p.ThreadID, p.RequestID)
|
||||
}
|
||||
return
|
||||
}
|
||||
var params struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
TurnID string `json:"turnId"`
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Standard MCP elicitation uses the same typed question controls. Extended
|
||||
// OpenAI forms are not advertised by initialize and fail explicitly if received.
|
||||
func (c *Chat) receiveElicitation(msg rpcMessage) {
|
||||
var p struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
Mode string `json:"mode"`
|
||||
Message string `json:"message"`
|
||||
URL string `json:"url"`
|
||||
Schema struct {
|
||||
Type string `json:"type"`
|
||||
Properties map[string]json.RawMessage `json:"properties"`
|
||||
Required []string `json:"required"`
|
||||
} `json:"requestedSchema"`
|
||||
}
|
||||
if json.Unmarshal(msg.Params, &p) != nil || p.ThreadID == "" || (p.Mode != "form" && p.Mode != "url") {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
form := protocol.ChatForm{ID: "mcp_" + base64.RawURLEncoding.EncodeToString(msg.ID), SessionID: p.ThreadID, Kind: "elicitation", Title: p.Message, Actions: []string{"accept", "decline", "cancel"}}
|
||||
if p.Mode == "url" {
|
||||
form.Fields = []protocol.ChatFormField{{Key: "external", Type: "external", URL: p.URL, Title: "Continue in the external form"}}
|
||||
} else {
|
||||
if p.Schema.Type != "object" || p.Schema.Properties == nil {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
required := map[string]bool{}
|
||||
for _, key := range p.Schema.Required {
|
||||
required[key] = true
|
||||
}
|
||||
keys := make([]string, 0, len(p.Schema.Properties))
|
||||
for key := range p.Schema.Properties {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
var field struct {
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Enum []string `json:"enum"`
|
||||
Default any `json:"default"`
|
||||
Minimum any `json:"minimum"`
|
||||
Maximum any `json:"maximum"`
|
||||
MinLength *int `json:"minLength"`
|
||||
MaxLength *int `json:"maxLength"`
|
||||
MinItems *int `json:"minItems"`
|
||||
MaxItems *int `json:"maxItems"`
|
||||
Format string `json:"format"`
|
||||
Items *struct {
|
||||
Type string `json:"type"`
|
||||
Enum []string `json:"enum"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if json.Unmarshal(p.Schema.Properties[key], &field) != nil {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
out := protocol.ChatFormField{Key: key, Type: field.Type, Title: field.Title, Description: field.Description, Required: required[key], Default: field.Default, Minimum: field.Minimum, Maximum: field.Maximum, MinLength: field.MinLength, MaxLength: field.MaxLength, MinItems: field.MinItems, MaxItems: field.MaxItems, Format: field.Format}
|
||||
switch field.Type {
|
||||
case "string", "number", "integer", "boolean":
|
||||
case "array":
|
||||
if field.Items == nil || field.Items.Type != "string" {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
out.Type = "multiselect"
|
||||
field.Enum = field.Items.Enum
|
||||
out.Custom = len(field.Enum) == 0
|
||||
default:
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
for _, value := range field.Enum {
|
||||
out.Options = append(out.Options, protocol.ChatFormOption{Value: value, Label: value})
|
||||
}
|
||||
form.Fields = append(form.Fields, out)
|
||||
}
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.forms[form.ID] = pendingForm{requestID: msg.ID, threadID: p.ThreadID, form: form, elicitation: true}
|
||||
c.mu.Unlock()
|
||||
c.emit(protocol.ChatEventFrame{SessionID: p.ThreadID, Kind: protocol.ChatEventForm, Form: &form})
|
||||
}
|
||||
@@ -258,11 +258,18 @@ func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) e
|
||||
if strings.TrimSpace(request.FormID) == "" {
|
||||
return fmt.Errorf("a form id is required")
|
||||
}
|
||||
if request.Action == "cancel" {
|
||||
_, err := c.call(ctx, "delete", "/api/session/"+request.SessionID+"/form/"+url.PathEscape(request.FormID), nil)
|
||||
return err
|
||||
}
|
||||
if request.Action != "" && request.Action != "accept" {
|
||||
return fmt.Errorf("unsupported OpenCode form action")
|
||||
}
|
||||
body := map[string]any{"answer": request.Answers}
|
||||
if request.Answers == nil {
|
||||
body["answer"] = map[string]any{}
|
||||
}
|
||||
if _, err := c.call(ctx, "post", "/api/session/"+request.SessionID+"/form/"+request.FormID+"/reply", body); err != nil {
|
||||
if _, err := c.call(ctx, "post", "/api/session/"+request.SessionID+"/form/"+url.PathEscape(request.FormID)+"/reply", body); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@@ -906,13 +913,26 @@ func (c *Chat) Forms(ctx context.Context, id string) ([]protocol.ChatForm, error
|
||||
}
|
||||
|
||||
type chatFormField struct {
|
||||
Key string `json:"key"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Type string `json:"type"`
|
||||
Options []chatFormOption `json:"options"`
|
||||
Custom bool `json:"custom"`
|
||||
Required bool `json:"required"`
|
||||
Key string `json:"key"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Type string `json:"type"`
|
||||
Options []chatFormOption `json:"options"`
|
||||
Custom bool `json:"custom"`
|
||||
Required bool `json:"required"`
|
||||
URL string `json:"url"`
|
||||
Default any `json:"default"`
|
||||
Minimum any `json:"minimum"`
|
||||
Maximum any `json:"maximum"`
|
||||
MinLength *int `json:"minLength"`
|
||||
MaxLength *int `json:"maxLength"`
|
||||
MinItems *int `json:"minItems"`
|
||||
MaxItems *int `json:"maxItems"`
|
||||
Format string `json:"format"`
|
||||
Pattern string `json:"pattern"`
|
||||
Placeholder string `json:"placeholder"`
|
||||
Hidden bool `json:"hidden"`
|
||||
When []protocol.ChatFormWhen `json:"when"`
|
||||
}
|
||||
|
||||
type chatFormOption struct {
|
||||
@@ -1195,6 +1215,7 @@ func normalizeFormEvent(eventType string, data chatEvent, sessionID string, stre
|
||||
SessionID: sessionID,
|
||||
Title: form.Title,
|
||||
Kind: kind,
|
||||
Actions: []string{"accept", "cancel"},
|
||||
}
|
||||
for _, field := range form.Fields {
|
||||
out := protocol.ChatFormField{
|
||||
@@ -1204,6 +1225,9 @@ func normalizeFormEvent(eventType string, data chatEvent, sessionID string, stre
|
||||
Type: field.Type,
|
||||
Custom: field.Custom,
|
||||
Required: field.Required,
|
||||
URL: field.URL, Default: field.Default, Minimum: field.Minimum, Maximum: field.Maximum,
|
||||
MinLength: field.MinLength, MaxLength: field.MaxLength, MinItems: field.MinItems, MaxItems: field.MaxItems,
|
||||
Format: field.Format, Pattern: field.Pattern, Placeholder: field.Placeholder, Hidden: field.Hidden, When: field.When,
|
||||
}
|
||||
for _, option := range field.Options {
|
||||
value := option.Value
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestChatFormsReadbackUsesSessionOwnership(t *testing.T) {
|
||||
@@ -22,3 +24,22 @@ func TestChatFormsReadbackUsesSessionOwnership(t *testing.T) {
|
||||
t.Fatalf("forms=%+v err=%v", forms, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatQuestionCancellationDoesNotSendAnAnswer(t *testing.T) {
|
||||
calls := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if r.Method != "DELETE" || r.URL.Path != "/api/session/ses_test/form/form_test" {
|
||||
t.Errorf("unexpected cancellation: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
if err := chat.Answer(context.Background(), protocol.ChatAnswerRequest{SessionID: "ses_test", FormID: "form_test", Action: "cancel"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("calls=%d", calls)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -478,6 +478,7 @@ type ChatForm struct {
|
||||
Resolved bool `json:"resolved,omitempty"`
|
||||
Cancelled bool `json:"cancelled,omitempty"`
|
||||
Answers map[string]any `json:"answers,omitempty"`
|
||||
Actions []string `json:"actions,omitempty"`
|
||||
}
|
||||
|
||||
// ChatFormField is one question/input in a form. Type is OpenCode's field type
|
||||
@@ -491,6 +492,26 @@ type ChatFormField struct {
|
||||
Options []ChatFormOption `json:"options,omitempty"`
|
||||
Custom bool `json:"custom,omitempty"`
|
||||
Required bool `json:"required,omitempty"`
|
||||
Secret bool `json:"secret,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Default any `json:"default,omitempty"`
|
||||
Minimum any `json:"minimum,omitempty"`
|
||||
Maximum any `json:"maximum,omitempty"`
|
||||
MinLength *int `json:"min_length,omitempty"`
|
||||
MaxLength *int `json:"max_length,omitempty"`
|
||||
MinItems *int `json:"min_items,omitempty"`
|
||||
MaxItems *int `json:"max_items,omitempty"`
|
||||
Format string `json:"format,omitempty"`
|
||||
Pattern string `json:"pattern,omitempty"`
|
||||
Placeholder string `json:"placeholder,omitempty"`
|
||||
Hidden bool `json:"hidden,omitempty"`
|
||||
When []ChatFormWhen `json:"when,omitempty"`
|
||||
}
|
||||
|
||||
type ChatFormWhen struct {
|
||||
Key string `json:"key"`
|
||||
Op string `json:"op"`
|
||||
Value any `json:"value"`
|
||||
}
|
||||
|
||||
// ChatFormOption is one selectable choice in a ChatFormField.
|
||||
@@ -511,6 +532,7 @@ type ChatRenameRequest struct {
|
||||
// answer object. It is deliberately separate from ChatQuery because its payload
|
||||
// is structured answers, not a session-scoped read.
|
||||
type ChatAnswerRequest struct {
|
||||
Action string `json:"action,omitempty"`
|
||||
SessionID string `json:"session_id"`
|
||||
FormID string `json:"form_id"`
|
||||
Answers map[string]any `json:"answers"`
|
||||
@@ -553,14 +575,15 @@ type ChatShellOutputPage struct {
|
||||
// The wire shape is spec-verified; a live pending request has not been observed.
|
||||
// Every optional field is omitempty so older peers ignore it.
|
||||
type ChatPermissionFrame struct {
|
||||
SessionID string `json:"session_id"`
|
||||
RequestID string `json:"request_id"`
|
||||
Action string `json:"action,omitempty"`
|
||||
Resources []string `json:"resources,omitempty"`
|
||||
Save []string `json:"save,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
Source *ChatPermissionSource `json:"source,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
SessionID string `json:"session_id"`
|
||||
RequestID string `json:"request_id"`
|
||||
Action string `json:"action,omitempty"`
|
||||
Resources []string `json:"resources,omitempty"`
|
||||
Save []string `json:"save,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
Source *ChatPermissionSource `json:"source,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
AlwaysLabel string `json:"always_label,omitempty"`
|
||||
// Resolved, Decision and ResolvedBy report the shared, exactly-once outcome
|
||||
// of a request any client may answer: once the first answer is recorded the
|
||||
// server pushes the same frame back to every watching client with Resolved
|
||||
|
||||
@@ -30,7 +30,11 @@ func handleChatAnswer(ctx context.Context, request protocol.Message, broker chat
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a form id is required"})
|
||||
return
|
||||
}
|
||||
if len(answer.Answers) == 0 {
|
||||
if answer.Action != "" && answer.Action != "accept" && answer.Action != "decline" && answer.Action != "cancel" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "invalid form action"})
|
||||
return
|
||||
}
|
||||
if len(answer.Answers) == 0 && answer.Action == "" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "at least one answer is required"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ type browserForms struct {
|
||||
mu sync.Mutex
|
||||
pending []protocol.ChatForm
|
||||
answered int
|
||||
canceled int
|
||||
}
|
||||
|
||||
func (b browserModelFixture) Forms(context.Context, string) ([]protocol.ChatForm, error) {
|
||||
@@ -37,13 +38,25 @@ func (b browserModelFixture) Forms(context.Context, string) ([]protocol.ChatForm
|
||||
func (b browserModelFixture) Answer(_ context.Context, answer protocol.ChatAnswerRequest) error {
|
||||
b.forms.mu.Lock()
|
||||
defer b.forms.mu.Unlock()
|
||||
if answer.Answers["answer"] != "Browser answer" {
|
||||
if answer.Action != "cancel" && answer.Answers["answer"] != "Browser answer" {
|
||||
return fmt.Errorf("unexpected answer")
|
||||
}
|
||||
if answer.FormID == "form_second" {
|
||||
if answer.Answers["enabled"] != false || answer.Answers["count"] != float64(0) {
|
||||
return fmt.Errorf("typed answers were lost")
|
||||
}
|
||||
if _, ok := answer.Answers["conditional"]; ok {
|
||||
return fmt.Errorf("hidden conditional answer leaked")
|
||||
}
|
||||
}
|
||||
for i, form := range b.forms.pending {
|
||||
if form.ID == answer.FormID {
|
||||
b.forms.pending = append(b.forms.pending[:i], b.forms.pending[i+1:]...)
|
||||
b.forms.answered++
|
||||
if answer.Action == "cancel" {
|
||||
b.forms.canceled++
|
||||
} else {
|
||||
b.forms.answered++
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -109,6 +122,13 @@ func TestChatBrowserLifecycleAndModelDialog(t *testing.T) {
|
||||
handler := HandlerWithOptions(ctx, Options{Chat: browserModelFixture{fake, forms}}, store)
|
||||
defer func() { cancel(); WaitRuns(handler) }()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
if req.URL.Path == "/fixture-cancel" && req.Method == http.MethodPost {
|
||||
forms.mu.Lock()
|
||||
forms.pending = append(forms.pending, protocol.ChatForm{ID: "form_cancel", SessionID: session.ID, Title: "Cancel this question", Actions: []string{"accept", "cancel"}, Fields: []protocol.ChatFormField{{Key: "answer", Type: "string", Required: true}}})
|
||||
forms.mu.Unlock()
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
if req.URL.Path == "/fixture-attention" && req.Method == http.MethodPost {
|
||||
fake.mu.Lock()
|
||||
fake.permissions = []protocol.ChatPermissionFrame{
|
||||
@@ -118,7 +138,16 @@ func TestChatBrowserLifecycleAndModelDialog(t *testing.T) {
|
||||
fake.mu.Unlock()
|
||||
forms.mu.Lock()
|
||||
for _, id := range []string{"form_first", "form_second"} {
|
||||
forms.pending = append(forms.pending, protocol.ChatForm{ID: id, SessionID: session.ID, Title: "Recovered question", Fields: []protocol.ChatFormField{{Key: "answer", Type: "text", Title: "Your answer", Required: true}}})
|
||||
fields := []protocol.ChatFormField{{Key: "answer", Type: "string", Title: "Your answer", Required: true}}
|
||||
if id == "form_second" {
|
||||
fields = append(fields,
|
||||
protocol.ChatFormField{Key: "enabled", Type: "boolean", Title: "Enabled", Required: true},
|
||||
protocol.ChatFormField{Key: "count", Type: "integer", Title: "Count", Minimum: 0, Maximum: 5, Required: true},
|
||||
protocol.ChatFormField{Key: "secret", Type: "string", Title: "Secret", Secret: true},
|
||||
protocol.ChatFormField{Key: "conditional", Type: "string", Title: "Only when enabled", Required: true, When: []protocol.ChatFormWhen{{Key: "enabled", Op: "eq", Value: true}}},
|
||||
)
|
||||
}
|
||||
forms.pending = append(forms.pending, protocol.ChatForm{ID: id, SessionID: session.ID, Title: "Recovered question", Fields: fields})
|
||||
}
|
||||
forms.mu.Unlock()
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
@@ -138,8 +167,9 @@ func TestChatBrowserLifecycleAndModelDialog(t *testing.T) {
|
||||
fake.mu.Unlock()
|
||||
forms.mu.Lock()
|
||||
answers := forms.answered
|
||||
canceled := forms.canceled
|
||||
forms.mu.Unlock()
|
||||
if replies != 2 || answers != 2 {
|
||||
t.Fatalf("browser did not deliver all interactions: approvals=%d answers=%d", replies, answers)
|
||||
if replies != 2 || answers != 2 || canceled != 1 {
|
||||
t.Fatalf("browser did not deliver all interactions: approvals=%d answers=%d canceled=%d", replies, answers, canceled)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user