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})
|
||||
}
|
||||
Reference in New Issue
Block a user