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 } // SessionList reads the endpoint's whole OpenCode session list without the // connection's directory scope, so the brokered chat handler can filter it to // the operator's own sessions across every directory. The V2 HTTP API scopes // GET /api/session to ?directory= when given; omitting it lists every session, // which is required because an operator session may live in any directory. The // native serve list is /session. It reuses the same authenticated request path // (no second transport or endpoint); only the directory query is omitted. func (c *Connection) SessionList(ctx context.Context) ([]byte, error) { if c.Backend == "v1" { return c.nativeRequest(ctx, "get", "/session", nil, "") } if c.URL == "" { return nil, fmt.Errorf("native adapter requires the serve backend") } return c.nativeRequest(ctx, "get", "/api/session", 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. // A connection whose backend already speaks the /api HTTP surface forwards the path // unchanged: only the v1 serve surface needs the /api -> native translation below. func (c *Connection) Call(ctx context.Context, method, path string, body any) ([]byte, error) { if c.Backend != "v1" { if c.URL == "" { return nil, fmt.Errorf("native adapter requires the serve backend") } return c.Native(ctx, method, path, body) } 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}}) } // The brokered chat session list is GET /api/session on the V2 HTTP API; the // native serve surface lists sessions at /session and returns a bare array, // which the adapter's tolerant decoder accepts. This keeps chat_sessions // working on the backend that currently enables brokered chat. if path == "/api/session" && method == "get" { return c.Native(ctx, "get", "/session", nil) } 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/"), "/") } if len(parts) == 0 || !sessionID.MatchString(parts[0]) { 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 { 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"` Parts []struct { Text string `json:"text"` } `json:"parts"` } if err := json.Unmarshal(data, &request); err != nil { return nil, err } text := request.Prompt if text == "" { text = request.Text } // The brokered chat adapter sends the V2 prompt shape (a parts array); // accept it so the native translation carries the text unchanged instead // of posting an empty prompt. if text == "" { for _, part := range request.Parts { if part.Text != "" { text = part.Text break } } } 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") }