Files
pipelines/internal/opencode/native.go
T

225 lines
7.3 KiB
Go

package opencode
import (
"context"
"encoding/json"
"fmt"
"path/filepath"
"regexp"
"strings"
)
var sessionID = regexp.MustCompile(`^ses[A-Za-z0-9_-]+$`)
func Permissions(rules []map[string]string) []map[string]string {
result := make([]map[string]string, 0, len(rules))
for _, rule := range rules {
permission := rule["action"]
if permission == "shell" {
permission = "bash"
}
result = append(result, map[string]string{"permission": permission, "pattern": rule["resource"], "action": rule["effect"]})
}
return result
}
func messageText(data []byte) (string, error) {
var message struct {
Info struct {
Role string `json:"role"`
Finish string `json:"finish"`
Error json.RawMessage `json:"error"`
Structured json.RawMessage `json:"structured"`
Time struct {
Completed int64 `json:"completed"`
} `json:"time"`
} `json:"info"`
Parts []struct{ Type, Text string } `json:"parts"`
}
if json.Unmarshal(data, &message) != nil || message.Info.Role != "assistant" {
return "", fmt.Errorf("OpenCode returned no completed assistant result")
}
if len(message.Info.Error) > 0 && string(message.Info.Error) != "null" {
return "", ExecutionError(message.Info.Error)
}
if message.Info.Time.Completed == 0 {
return "", fmt.Errorf("OpenCode returned no completed assistant result")
}
if len(message.Info.Structured) > 0 && string(message.Info.Structured) != "null" && (message.Info.Finish == "stop" || message.Info.Finish == "tool-calls") {
return string(message.Info.Structured), nil
}
if message.Info.Finish != "stop" {
return "", fmt.Errorf("OpenCode returned no completed assistant result")
}
var text string
for _, part := range message.Parts {
if part.Type == "text" {
text += part.Text
}
}
if text == "" {
return "", fmt.Errorf("OpenCode returned no assistant text")
}
return text, nil
}
// Call adapts the pipeline's existing V2 command contract to the native stable API.
// Sessions still use the same account/database; only our loopback serve process is owned.
func (c *Connection) Call(ctx context.Context, method, path string, body any) ([]byte, error) {
if c.Backend != "v1" {
return nil, fmt.Errorf("native adapter requires the serve backend")
}
if path == "/api/session" && method == "post" {
data, _ := json.Marshal(body)
var request struct {
Title, Agent string
Model map[string]string
Permissions []map[string]string
}
if err := json.Unmarshal(data, &request); err != nil {
return nil, err
}
rules := request.Permissions
if rules == nil {
rules = []map[string]string{{"action": "*", "resource": "*", "effect": "deny"}}
}
nativeRules := Permissions(rules)
// V1 tool implementations can match absolute file paths; preserve the exact
// approved scope in both forms, never grant a workspace-wide edit wildcard.
var scoped []map[string]string
for _, rule := range nativeRules {
scoped = append(scoped, rule)
if rule["permission"] == "edit" && rule["action"] == "allow" && !filepath.IsAbs(rule["pattern"]) {
scoped = append(scoped, map[string]string{"permission": "edit", "action": "allow", "pattern": filepath.Join(c.Directory, rule["pattern"])})
}
}
payload := map[string]any{"title": request.Title, "permission": scoped, "model": request.Model}
if request.Agent != "" {
payload["agent"] = request.Agent
}
created, err := c.Native(ctx, "post", "/session", payload)
if err != nil {
return created, err
}
var session struct {
ID string `json:"id"`
}
if json.Unmarshal(created, &session) != nil || !sessionID.MatchString(session.ID) {
return nil, fmt.Errorf("OpenCode returned an invalid native session")
}
c.models[session.ID] = map[string]string{"providerID": request.Model["providerID"], "modelID": request.Model["id"]}
return json.Marshal(map[string]any{"data": map[string]string{"id": session.ID}})
}
clean := strings.SplitN(path, "?", 2)[0]
parts := strings.Split(strings.TrimPrefix(clean, "/api/session/"), "/")
if strings.HasPrefix(clean, "/api/experimental/session/") {
parts = strings.Split(strings.TrimPrefix(clean, "/api/experimental/session/"), "/")
}
if len(parts) == 0 || !sessionID.MatchString(parts[0]) {
return nil, fmt.Errorf("unsupported native OpenCode operation")
}
id := parts[0]
if len(parts) == 1 && method == "delete" {
data, err := c.Native(ctx, "delete", "/session/"+id, nil)
if err != nil {
return nil, err
}
var confirmed bool
if json.Unmarshal(data, &confirmed) != nil || !confirmed {
return nil, fmt.Errorf("OpenCode session deletion was not confirmed")
}
delete(c.models, id)
delete(c.responses, id)
return nil, nil
}
if len(parts) != 2 {
return nil, fmt.Errorf("unsupported native OpenCode operation")
}
switch parts[1] {
case "interrupt":
data, err := c.Native(ctx, "post", "/session/"+id+"/abort", nil)
if err != nil {
return nil, err
}
var confirmed bool
if json.Unmarshal(data, &confirmed) != nil || !confirmed {
return nil, fmt.Errorf("OpenCode abort was not confirmed")
}
return nil, nil
case "generate", "prompt":
data, _ := json.Marshal(body)
var request struct {
Prompt string `json:"prompt"`
Text string `json:"text"`
Format json.RawMessage `json:"format"`
}
if err := json.Unmarshal(data, &request); err != nil {
return nil, err
}
text := request.Prompt
if text == "" {
text = request.Text
}
payload := map[string]any{"model": c.models[id], "parts": []map[string]string{{"type": "text", "text": text}}}
if len(request.Format) > 0 {
supported, err := c.supportsFormat(ctx, request.Format)
if err != nil {
var evidence []byte
if c.FormatProbe != nil {
evidence = []byte(c.FormatProbe.Response)
}
return evidence, fmt.Errorf("native structured-format compatibility check: %w", err)
}
if supported {
payload["format"] = request.Format
}
}
response, err := c.Native(ctx, "post", "/session/"+id+"/message", payload)
if err != nil {
return response, err
}
c.responses[id] = response
if parts[1] == "prompt" {
return nil, nil
}
result, err := messageText(response)
if err != nil {
return response, err
}
return json.Marshal(map[string]any{"data": map[string]string{"text": result}})
case "wait":
_, err := messageText(c.responses[id])
if err != nil {
return c.responses[id], err
}
return nil, nil
case "message":
data, err := c.Messages(ctx, id)
if err != nil {
return data, err
}
var messages []struct {
Info json.RawMessage `json:"info"`
Parts json.RawMessage `json:"parts"`
}
if json.Unmarshal(data, &messages) != nil {
return nil, fmt.Errorf("invalid native messages")
}
var converted []map[string]any
for i := len(messages) - 1; i >= 0; i-- {
m := messages[i]
var info struct {
Role, Finish string
Error, Structured json.RawMessage
Time struct{ Completed int64 }
}
if json.Unmarshal(m.Info, &info) != nil || info.Role != "assistant" {
continue
}
converted = append(converted, map[string]any{"finish": info.Finish, "completed": info.Time.Completed > 0, "error": info.Error, "structured": info.Structured, "content": m.Parts, "native_info": m.Info})
}
return json.Marshal(map[string]any{"data": converted})
}
return nil, fmt.Errorf("unsupported native OpenCode operation")
}