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