Files
pipelines/internal/opencode/native.go
T
alan 18398dfa5b chat: give the operator their own sessions, separate from run sessions
chat_sessions used to list exactly the OpenCode sessions the pipelines own,
filtered through pipeline.SessionOwner (run_steps/run_session_owners), so an
operator-created chat was an accident of the run-ownership table and the
operator's working sessions were mixed with the internals of running pipelines.

Add a first-class operator session:

- internal/pipeline/operator_sessions.go: a dedicated operator_sessions table
  (session_id PK, directory, title, tag, created_at, last_used_at) with
  RecordOperatorSession (upsert preserving created_at), a one-statement
  TouchOperatorSession (no-op for a non-operator id), OperatorSessions bounded to
  128 rows most-recently-used first, and OperatorDirectories (bounded MRU,
  deduped). run_steps/run_session_owners and SessionOwner/OwnedSessions are
  untouched.
- internal/server/chat.go: chat_sessions returns operator sessions only - it
  reads the registry once, intersects it with one broker session-list call, fills
  directory/tag/created/updated from the registry, sets busy for a session held
  by another connection, keeps MRU order, and stays fail-closed (empty list, never
  the endpoint's whole list). A pipeline stage session and an untagged row can
  never be listed. chat_create resolves the directory (empty/'~'/'~/...' ->
  operator home; relative or missing rejected before any OpenCode call), calls
  broker.Create(title, resolved) and records the row with the operator tag.
  chat_directories returns home first then bounded (8) deduped recents. A
  successful prompt touches the operator session without affecting pipeline
  prompts.
- internal/opencode, internal/protocol, internal/server/websocket.go and
  message.go: unscoped session list, Create posts {"title":...,
  "location":{"directory":...}} to POST /api/session, additive protocol fields
  (omitempty) and the ChatDirectories request/response, plus the OperatorRegistry
  option defaulting to the first store. One OpenCode transport per server is
  unchanged.

Docs and references: docs/cli.md gains a "Chat sessions" section documenting the
operator-only fail-closed list, directory defaulting/rejection, chat_directories
(home first, deduped, bounded 8) and why a dedicated request was chosen.
internal/author/skill/references/operations.md's stale "Brokered OpenCode chat"
text (chat_create unbrokered, run_steps filtering, "listed the owned scratch
session" evidence) is rewritten to the operator-session registry, the fail-closed
filter, directory defaulting and the corrected live-test wording. No new
reference file, so internal/author/install.go's inventory is unchanged.

Checked for staleness elsewhere: README.md, the docs/ topic pages and the
packaged server/TUI templates carry no chat-session ownership claims, so none
needed updating.

Verified: gofmt -l clean; go vet and go build ./... clean; go test -count=1
./internal/pipeline/... ./internal/protocol/... ./internal/opencode/...
./internal/server/... and the full go test -count=1 ./... pass.
2026-10-17 11:14:25 +01:00

283 lines
9.9 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
}
// 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")
}