Poll OpenCode permission requests and forward chat_reply
This commit is contained in:
+126
-8
@@ -5,13 +5,22 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// ErrPermissionUnsupported reports that the connected OpenCode backend does not
|
||||
// expose the brokered approval surface. The native v1 serve translation returns
|
||||
// it; callers treat it as a documented limitation rather than an operational
|
||||
// failure, so a chat prompt does not emit a permission error frame on a backend
|
||||
// that cannot answer one.
|
||||
var ErrPermissionUnsupported = errors.New("OpenCode permission approval is not implemented for the native serve backend")
|
||||
|
||||
// Chat is the brokered OpenCode chat adapter (route B in the research): the
|
||||
// Pipelines server owns the OpenCode endpoint and credentials and turns the v2
|
||||
// HTTP API into protocol.ChatEventFrame frames. It reuses the owned-endpoint
|
||||
@@ -19,6 +28,11 @@ import (
|
||||
// no second transport or credential path is introduced.
|
||||
type Chat struct {
|
||||
conn *Connection
|
||||
// mu serializes the adapter's HTTP calls. Connection records its last
|
||||
// operation and status on the shared connection, so two calls must not
|
||||
// overlap; the permission poller runs alongside the read loop's
|
||||
// prompt/interrupt/reply calls.
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// NewChat brokers chat for one owned OpenCode endpoint. The connection must be
|
||||
@@ -31,6 +45,15 @@ func NewChat(conn *Connection) *Chat { return &Chat{conn: conn} }
|
||||
// chat adapter and callers that must reject a request before any OpenCode call.
|
||||
func ValidSessionID(id string) bool { return sessionID.MatchString(id) }
|
||||
|
||||
// call serializes the adapter's HTTP calls and forwards them through the shared
|
||||
// Connection, so no second transport is introduced and Connection's recorded
|
||||
// last operation/status is never written by two goroutines at once.
|
||||
func (c *Chat) call(ctx context.Context, method, path string, body any) ([]byte, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.conn.Call(ctx, method, path, body)
|
||||
}
|
||||
|
||||
// Prompt forwards one chat prompt through the existing Call translation
|
||||
// (authenticated, bounded, directory-scoped). The endpoint returns the inbox
|
||||
// envelope immediately; the reply arrives on Stream.
|
||||
@@ -42,7 +65,7 @@ func (c *Chat) Prompt(ctx context.Context, id, text string) error {
|
||||
return fmt.Errorf("empty chat prompt")
|
||||
}
|
||||
body := map[string]any{"parts": []map[string]string{{"type": "text", "text": text}}}
|
||||
if _, err := c.conn.Call(ctx, "post", "/api/session/"+id+"/prompt", body); err != nil {
|
||||
if _, err := c.call(ctx, "post", "/api/session/"+id+"/prompt", body); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@@ -53,7 +76,7 @@ func (c *Chat) Interrupt(ctx context.Context, id string) error {
|
||||
if !sessionID.MatchString(id) {
|
||||
return fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
if _, err := c.conn.Call(ctx, "post", "/api/session/"+id+"/interrupt", map[string]any{}); err != nil {
|
||||
if _, err := c.call(ctx, "post", "/api/session/"+id+"/interrupt", map[string]any{}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@@ -69,6 +92,7 @@ func (c *Chat) Messages(ctx context.Context, id string, limit int) ([]protocol.C
|
||||
}
|
||||
var data []byte
|
||||
var err error
|
||||
c.mu.Lock()
|
||||
if c.conn.Backend == "v1" {
|
||||
data, err = c.conn.Messages(ctx, id)
|
||||
} else {
|
||||
@@ -78,6 +102,7 @@ func (c *Chat) Messages(ctx context.Context, id string, limit int) ([]protocol.C
|
||||
}
|
||||
data, err = c.conn.Call(ctx, "get", path, nil)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -101,12 +126,108 @@ func (c *Chat) Reply(ctx context.Context, request protocol.ChatReplyRequest) err
|
||||
body["message"] = request.Message
|
||||
}
|
||||
path := "/api/session/" + request.SessionID + "/permission/" + request.RequestID + "/reply"
|
||||
if _, err := c.conn.Call(ctx, "post", path, body); err != nil {
|
||||
if _, err := c.call(ctx, "post", path, body); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Permissions lists the session's pending OpenCode approval requests, mirroring
|
||||
// GET /api/permission/request. The endpoint is global, so the decoded list is
|
||||
// filtered to sessionID; a malformed response is an error, never an empty
|
||||
// success. It reuses Connection.Call so the request keeps the shared bounds,
|
||||
// auth and translation, and reuses ValidSessionID for the same rejection the
|
||||
// other chat calls apply.
|
||||
func (c *Chat) Permissions(ctx context.Context, id string) ([]protocol.ChatPermissionFrame, error) {
|
||||
if !sessionID.MatchString(id) {
|
||||
return nil, fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
data, err := c.call(ctx, "get", "/api/permission/request", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decodeChatPermissions(id, data)
|
||||
}
|
||||
|
||||
// nativeChatPermission is one pending approval request matching the V2
|
||||
// Permission.Request schema verified against the service's /openapi.json: id,
|
||||
// sessionID, action and resources are required; save, metadata, source and
|
||||
// message are optional, so the decoder tolerates any of them being absent.
|
||||
type nativeChatPermission struct {
|
||||
ID string `json:"id"`
|
||||
SessionID string `json:"sessionID"`
|
||||
Action string `json:"action"`
|
||||
Resources []string `json:"resources"`
|
||||
Save []string `json:"save"`
|
||||
Metadata map[string]any `json:"metadata"`
|
||||
Source *nativeChatPermissionSource `json:"source"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// nativeChatPermissionSource is the incoming Permission.Source union; its single
|
||||
// (tool) member carries type plus the message id and call id (the protocol frame
|
||||
// renames messageID to message_id).
|
||||
type nativeChatPermissionSource struct {
|
||||
Type string `json:"type"`
|
||||
MessageID string `json:"messageID"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
// chatEnvelope unwraps the {"data":[...]} envelope the V2 HTTP API returns and
|
||||
// reports whether the body was that envelope with a non-nil data array; a bare
|
||||
// array or a malformed body returns ok=false. It is the single envelope rule the
|
||||
// message and permission decoders share instead of each re-deriving it.
|
||||
func chatEnvelope[T any](data []byte) ([]T, bool) {
|
||||
var response struct {
|
||||
Data []T `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &response); err != nil || response.Data == nil {
|
||||
return nil, false
|
||||
}
|
||||
return response.Data, true
|
||||
}
|
||||
|
||||
// chatPermissionRecords reads the {"data":[...]} envelope the V2 endpoint
|
||||
// returns. An unparseable body or a missing data array is an error, never an
|
||||
// empty list.
|
||||
func chatPermissionRecords(data []byte) ([]nativeChatPermission, error) {
|
||||
records, ok := chatEnvelope[nativeChatPermission](data)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid OpenCode permission response")
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// decodeChatPermissions maps the pending-request list onto protocol frames,
|
||||
// keeping only the requested session's requests (a request with no id cannot be
|
||||
// answered and is dropped).
|
||||
func decodeChatPermissions(sessionID string, data []byte) ([]protocol.ChatPermissionFrame, error) {
|
||||
records, err := chatPermissionRecords(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
frames := make([]protocol.ChatPermissionFrame, 0, len(records))
|
||||
for _, record := range records {
|
||||
if record.SessionID != sessionID || record.ID == "" {
|
||||
continue
|
||||
}
|
||||
frame := protocol.ChatPermissionFrame{
|
||||
SessionID: sessionID,
|
||||
RequestID: record.ID,
|
||||
Action: record.Action,
|
||||
Resources: record.Resources,
|
||||
Save: record.Save,
|
||||
Metadata: record.Metadata,
|
||||
Message: record.Message,
|
||||
}
|
||||
if record.Source != nil {
|
||||
frame.Source = &protocol.ChatPermissionSource{Type: record.Source.Type, MessageID: record.Source.MessageID, ID: record.Source.ID}
|
||||
}
|
||||
frames = append(frames, frame)
|
||||
}
|
||||
return frames, nil
|
||||
}
|
||||
|
||||
// Stream subscribes to the OpenCode event firehose and invokes emit for every
|
||||
// frame belonging to sessionID. It reads one bounded SSE frame at a time and
|
||||
// never polls the per-session message log; the global firehose is the only
|
||||
@@ -388,11 +509,8 @@ func (m nativeChatMessage) contentParts() []nativeChatPart {
|
||||
// the V2 HTTP API wraps them in {"data":[...]} while the native serve readback
|
||||
// returns a bare array. An unrecognised body is an error, never empty history.
|
||||
func chatMessageRecords(data []byte) ([]nativeChatMessage, error) {
|
||||
var response struct {
|
||||
Data []nativeChatMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &response); err == nil && response.Data != nil {
|
||||
return response.Data, nil
|
||||
if records, ok := chatEnvelope[nativeChatMessage](data); ok {
|
||||
return records, nil
|
||||
}
|
||||
var records []nativeChatMessage
|
||||
if err := json.Unmarshal(data, &records); err != nil {
|
||||
|
||||
@@ -3,6 +3,7 @@ package opencode
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -161,11 +162,158 @@ func TestChatRejectsInvalidSessionWithoutCalling(t *testing.T) {
|
||||
if err := chat.Interrupt(ctx, "bad id"); err == nil {
|
||||
t.Fatal("invalid interrupt session id must be rejected")
|
||||
}
|
||||
if _, err := chat.Permissions(ctx, "not-a-session"); err == nil {
|
||||
t.Fatal("invalid permission session id must be rejected")
|
||||
}
|
||||
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "not-a-session", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}); err == nil {
|
||||
t.Fatal("invalid reply session id must be rejected")
|
||||
}
|
||||
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "", Decision: protocol.ChatDecisionOnce}); err == nil {
|
||||
t.Fatal("empty reply request id must be rejected")
|
||||
}
|
||||
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: "maybe"}); err == nil {
|
||||
t.Fatal("invalid reply decision must be rejected")
|
||||
}
|
||||
if calls.Load() != 0 {
|
||||
t.Fatalf("invalid requests reached the service: %d", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatPermissionsListsAndFilters loads a pending-request fixture in the
|
||||
// verified V2 envelope (GET /api/permission/request) and asserts the adapter
|
||||
// returns the requested session's request with its fields intact, filters out a
|
||||
// foreign session's request, and reads the endpoint once.
|
||||
func TestChatPermissionsListsAndFilters(t *testing.T) {
|
||||
var reads atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/api/permission/request" {
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
return
|
||||
}
|
||||
reads.Add(1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[
|
||||
{"id":"per_1","sessionID":"ses_1","action":"bash","resources":["rm -rf /tmp"],"save":["bash:rm -rf /tmp"],"metadata":{"command":"rm -rf /tmp"},"source":{"type":"tool","messageID":"msg_1","id":"call_1"},"message":"wants to run a command"},
|
||||
{"id":"per_2","sessionID":"ses_other","action":"edit","resources":["/etc/hosts"]}
|
||||
]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
frames, err := chat.Permissions(ctx, "ses_1")
|
||||
if err != nil {
|
||||
t.Fatalf("permissions: %v", err)
|
||||
}
|
||||
if reads.Load() != 1 {
|
||||
t.Fatalf("permission endpoint read %d times, want 1", reads.Load())
|
||||
}
|
||||
if len(frames) != 1 {
|
||||
t.Fatalf("frames = %+v, want the foreign request filtered", frames)
|
||||
}
|
||||
got := frames[0]
|
||||
if got.SessionID != "ses_1" || got.RequestID != "per_1" || got.Action != "bash" {
|
||||
t.Fatalf("frame = %+v", got)
|
||||
}
|
||||
if len(got.Resources) != 1 || got.Resources[0] != "rm -rf /tmp" || len(got.Save) != 1 || got.Message != "wants to run a command" {
|
||||
t.Fatalf("frame detail = %+v", got)
|
||||
}
|
||||
if got.Metadata["command"] != "rm -rf /tmp" {
|
||||
t.Fatalf("frame metadata = %+v", got.Metadata)
|
||||
}
|
||||
if got.Source == nil || got.Source.Type != "tool" || got.Source.MessageID != "msg_1" || got.Source.ID != "call_1" {
|
||||
t.Fatalf("frame source = %+v", got.Source)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatPermissionsRejectsMalformedList pins that a response without the data
|
||||
// array is an error, not an empty success.
|
||||
func TestChatPermissionsRejectsMalformedList(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"location":{"directory":"/work"}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
if _, err := chat.Permissions(context.Background(), "ses_1"); err == nil {
|
||||
t.Fatal("a malformed permission response must be an error, not empty success")
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatPermissionReplyPostsReplyEndpoint pins the outbound approval reply: the
|
||||
// adapter must POST exactly once to
|
||||
// /api/session/{id}/permission/{requestID}/reply with the exact decision body,
|
||||
// accept the documented 204 No Content success, and surface a non-2xx failure.
|
||||
func TestChatPermissionReplyPostsReplyEndpoint(t *testing.T) {
|
||||
for _, decision := range []string{protocol.ChatDecisionOnce, protocol.ChatDecisionAlways, protocol.ChatDecisionReject} {
|
||||
t.Run(decision, func(t *testing.T) {
|
||||
type request struct{ method, path, body string }
|
||||
var mu sync.Mutex
|
||||
var requests []request
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
data, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
requests = append(requests, request{method: r.Method, path: r.URL.Path, body: string(data)})
|
||||
mu.Unlock()
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: decision}); err != nil {
|
||||
t.Fatalf("reply: %v", err)
|
||||
}
|
||||
mu.Lock()
|
||||
got := append([]request(nil), requests...)
|
||||
mu.Unlock()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("reply requests = %d, want 1: %+v", len(got), got)
|
||||
}
|
||||
if got[0].method != http.MethodPost || got[0].path != "/api/session/ses_1/permission/req_1/reply" {
|
||||
t.Fatalf("reply request = %+v", got[0])
|
||||
}
|
||||
if got[0].body != `{"decision":"`+decision+`"}` {
|
||||
t.Fatalf("reply body = %q, want decision %q", got[0].body, decision)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("failure", func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
if err := chat.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}); err == nil {
|
||||
t.Fatal("a failing reply endpoint must return an error")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestChatPermissionV1TranslationGated pins the declared backend limitation: the
|
||||
// permission list and reply are implemented against the V2 HTTP API, and the
|
||||
// native serve translation rejects them explicitly (an actionable error, no
|
||||
// guessed endpoint, no HTTP call) so the caller can see the limitation.
|
||||
func TestChatPermissionV1TranslationGated(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v1", URL: srv.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}})
|
||||
ctx := context.Background()
|
||||
if _, err := chat.Permissions(ctx, "ses_1"); !errors.Is(err, ErrPermissionUnsupported) {
|
||||
t.Fatalf("v1 permission list must return the gate sentinel, got %v", err)
|
||||
}
|
||||
if err := chat.Reply(ctx, protocol.ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: protocol.ChatDecisionOnce}); !errors.Is(err, ErrPermissionUnsupported) {
|
||||
t.Fatalf("v1 permission reply must return the gate sentinel, got %v", err)
|
||||
}
|
||||
if calls.Load() != 0 {
|
||||
t.Fatalf("gated permission requests reached the service: %d", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatInterruptPostsInterruptEndpoint pins the outbound interrupt call: the
|
||||
// adapter must POST an empty JSON body to /api/session/{id}/interrupt exactly
|
||||
// once and return nil, and it must surface a non-nil error when the endpoint
|
||||
|
||||
@@ -262,6 +262,11 @@ func (c *Connection) Native(ctx context.Context, method, path string, body any)
|
||||
evidence, _ := io.ReadAll(io.LimitReader(response.Body, 16<<10))
|
||||
return evidence, fmt.Errorf("OpenCode %s %s failed (HTTP %d)", method, path, response.StatusCode)
|
||||
}
|
||||
// A successful no-content operation (the permission-reply endpoint returns
|
||||
// 204) carries no JSON body to validate.
|
||||
if response.StatusCode == http.StatusNoContent {
|
||||
return nil, nil
|
||||
}
|
||||
if !strings.HasPrefix(response.Header.Get("Content-Type"), "application/json") {
|
||||
return nil, fmt.Errorf("OpenCode %s %s returned a non-JSON API response", method, path)
|
||||
}
|
||||
|
||||
@@ -116,6 +116,16 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([
|
||||
return json.Marshal(map[string]any{"data": map[string]string{"id": session.ID}})
|
||||
}
|
||||
clean := strings.SplitN(path, "?", 2)[0]
|
||||
// The brokered approval surface is implemented against the V2 HTTP API: the
|
||||
// documented endpoints are GET /api/permission/request and POST
|
||||
// /api/session/{id}/permission/{requestID}/reply. This native serve
|
||||
// translation does not implement them, so answer with an actionable gate
|
||||
// error instead of the generic unsupported-operation error; the permission
|
||||
// poller surfaces that limitation rather than silently reporting no pending
|
||||
// requests.
|
||||
if clean == "/api/permission/request" {
|
||||
return nil, fmt.Errorf("permission listing: %w", ErrPermissionUnsupported)
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(clean, "/api/session/"), "/")
|
||||
if strings.HasPrefix(clean, "/api/experimental/session/") {
|
||||
parts = strings.Split(strings.TrimPrefix(clean, "/api/experimental/session/"), "/")
|
||||
@@ -124,6 +134,11 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([
|
||||
return nil, fmt.Errorf("unsupported native OpenCode operation")
|
||||
}
|
||||
id := parts[0]
|
||||
// The approval reply is V2-only in this translation (see the permission-list
|
||||
// gate above); the V2 path has four trailing segments.
|
||||
if len(parts) == 4 && parts[1] == "permission" && parts[3] == "reply" {
|
||||
return nil, fmt.Errorf("permission reply: %w", ErrPermissionUnsupported)
|
||||
}
|
||||
if len(parts) == 1 && method == "delete" {
|
||||
data, err := c.Native(ctx, "delete", "/session/"+id, nil)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user