Files

197 lines
5.7 KiB
Go

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
}