Simplify Go installation and support standard OpenCode releases
This commit is contained in:
@@ -5,11 +5,13 @@ import (
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"git.a-wan.net/alan/pipelines/internal/draft"
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"pipelines/internal/draft"
|
||||
"regexp"
|
||||
"time"
|
||||
)
|
||||
|
||||
//go:embed skill/SKILL.md skill/references/format.md
|
||||
@@ -47,6 +49,14 @@ func Workspace(d draft.Draft) (string, error) {
|
||||
// PrepareSession explicitly loads the skill without starting a model turn.
|
||||
// The existing user's CLI handles discovery and authentication; no auth is exported.
|
||||
func PrepareSession(ctx context.Context, executable, workspace, name string) (string, error) {
|
||||
connection, err := opencode.Open(ctx, executable, workspace, "")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer connection.Close()
|
||||
if connection.Backend == "v1" {
|
||||
return prepareNative(ctx, connection, workspace, name)
|
||||
}
|
||||
call := func(method, path string, body any) ([]byte, error) {
|
||||
args := []string{"api", method, path}
|
||||
if body != nil {
|
||||
@@ -82,11 +92,41 @@ func PrepareSession(ctx context.Context, executable, workspace, name string) (st
|
||||
return "", err
|
||||
}
|
||||
if err = os.WriteFile(filepath.Join(workspace, "SESSION"), []byte(id+"\n"), 0600); err != nil {
|
||||
_, _ = call("delete", "/api/session/"+id, nil)
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func prepareNative(ctx context.Context, connection *opencode.Connection, workspace, name string) (id string, err error) {
|
||||
data, err := connection.Native(ctx, "post", "/session", map[string]string{"title": "Pipeline draft: " + name})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var result struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if json.Unmarshal(data, &result) != nil || !regexp.MustCompile(`^ses[a-zA-Z0-9_-]+$`).MatchString(result.ID) {
|
||||
return "", fmt.Errorf("invalid OpenCode native session")
|
||||
}
|
||||
id = result.ID
|
||||
defer func() {
|
||||
if err != nil {
|
||||
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
_, _ = connection.Native(cleanup, "delete", "/session/"+id, nil)
|
||||
}
|
||||
}()
|
||||
skill, _ := content.ReadFile("skill/SKILL.md")
|
||||
reference, _ := content.ReadFile("skill/references/format.md")
|
||||
instructions := "Pipeline authoring skill (preloaded; no inference requested):\n" + string(skill) + "\nDefinition reference:\n" + string(reference)
|
||||
if _, err = connection.Native(ctx, "post", "/session/"+id+"/message", map[string]any{"noReply": true, "parts": []map[string]string{{"type": "text", "text": instructions}}}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
err = os.WriteFile(filepath.Join(workspace, "SESSION"), []byte(id+"\n"), 0600)
|
||||
return id, err
|
||||
}
|
||||
|
||||
func Prompt(d draft.Draft, request, command string) string {
|
||||
if request == "" {
|
||||
request = "Ask me what this pipeline should do or what to change, then help me edit its draft."
|
||||
|
||||
@@ -2,9 +2,9 @@ package author
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/draft"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pipelines/internal/draft"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -21,7 +21,7 @@ func TestSkillActivationIsExplicitAndNoResume(t *testing.T) {
|
||||
}
|
||||
capture := filepath.Join(t.TempDir(), "calls")
|
||||
script := filepath.Join(t.TempDir(), "opencode")
|
||||
os.WriteFile(script, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" >> '"+capture+"'\nif [ \"$3\" = /api/session ]; then printf '%s' '{\"data\":{\"id\":\"ses_test\"}}'; fi\n"), 0700)
|
||||
os.WriteFile(script, []byte("#!/bin/sh\nif [ \"$1\" = --help ]; then printf '%s\\n' ' api commands'; exit 0; fi\nprintf '%s\\n' \"$@\" >> '"+capture+"'\nif [ \"$3\" = /api/session ]; then printf '%s' '{\"data\":{\"id\":\"ses_test\"}}'; fi\n"), 0700)
|
||||
id, err := PrepareSession(context.Background(), script, workspace, d.Name)
|
||||
if err != nil || id != "ses_test" {
|
||||
t.Fatal(id, err)
|
||||
@@ -40,7 +40,7 @@ func TestSkillFailureDoesNotLaunchAndCleansOnlyCreatedSession(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
capture := filepath.Join(workspace, "calls")
|
||||
script := filepath.Join(workspace, "opencode")
|
||||
os.WriteFile(script, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" >> '"+capture+"'\nif [ \"$3\" = /api/session ]; then printf '%s' '{\"data\":{\"id\":\"ses_new\"}}'; exit 0; fi\nif [ \"$2\" = delete ]; then exit 0; fi\nexit 1\n"), 0700)
|
||||
os.WriteFile(script, []byte("#!/bin/sh\nif [ \"$1\" = --help ]; then printf '%s\\n' ' api commands'; exit 0; fi\nprintf '%s\\n' \"$@\" >> '"+capture+"'\nif [ \"$3\" = /api/session ]; then printf '%s' '{\"data\":{\"id\":\"ses_new\"}}'; exit 0; fi\nif [ \"$2\" = delete ]; then exit 0; fi\nexit 1\n"), 0700)
|
||||
if _, err := PrepareSession(context.Background(), script, workspace, "name"); err == nil {
|
||||
t.Fatal("missing skill allowed")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package author
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"git.a-wan.net/alan/pipelines/internal/draft"
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestStableAuthoringInstructionsPreloadedWithoutInference(t *testing.T) {
|
||||
executable := os.Getenv("PIPELINES_TEST_OPENCODE_V1")
|
||||
if executable == "" {
|
||||
t.Skip("set PIPELINES_TEST_OPENCODE_V1 for no-inference authoring preload test")
|
||||
}
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", home+"/config")
|
||||
t.Setenv("XDG_DATA_HOME", home+"/data")
|
||||
t.Setenv("XDG_CACHE_HOME", home+"/cache")
|
||||
t.Setenv("XDG_STATE_HOME", home+"/state")
|
||||
t.Setenv("PIPELINES_DRAFT_DIR", home+"/drafts")
|
||||
d, err := draft.Create("native authoring", "draft source", "ws://localhost", true, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
workspace, err := Workspace(d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
id, err := PrepareSession(ctx, executable, workspace, d.Name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := opencode.Open(ctx, executable, workspace, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
defer c.Native(context.Background(), "delete", "/session/"+id, nil)
|
||||
data, err := c.Native(ctx, "get", "/session/"+id+"/message", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var messages []struct {
|
||||
Info struct {
|
||||
Role string `json:"role"`
|
||||
} `json:"info"`
|
||||
Parts []struct{ Type, Text string } `json:"parts"`
|
||||
}
|
||||
if json.Unmarshal(data, &messages) != nil || len(messages) != 1 || messages[0].Info.Role != "user" {
|
||||
t.Fatal("preload ran inference or missing message", string(data))
|
||||
}
|
||||
text := messages[0].Parts[0].Text
|
||||
if !strings.Contains(text, "Do not submit or run by default") && !strings.Contains(text, "Do not submit or run") {
|
||||
if !strings.Contains(text, "Do not submit") {
|
||||
t.Fatal("draft-only instruction not preloaded", text)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(text, "Definition reference") || !strings.Contains(text, "provider=opencode-go") {
|
||||
t.Fatal("format reference not preloaded")
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: Pipeline authoring
|
||||
name: pipelines
|
||||
description: Create or edit validated pipeline Markdown drafts with the pipelines CLI; preserve immutable versions and require explicit submission.
|
||||
---
|
||||
|
||||
|
||||
+6
-6
@@ -15,13 +15,13 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/author"
|
||||
"git.a-wan.net/alan/pipelines/internal/client"
|
||||
"git.a-wan.net/alan/pipelines/internal/draft"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/tui"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"pipelines/internal/author"
|
||||
"pipelines/internal/client"
|
||||
"pipelines/internal/draft"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/tui"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
|
||||
@@ -11,11 +11,11 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"pipelines/internal/cli"
|
||||
"pipelines/internal/draft"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/server"
|
||||
"git.a-wan.net/alan/pipelines/internal/cli"
|
||||
"git.a-wan.net/alan/pipelines/internal/draft"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/server"
|
||||
)
|
||||
|
||||
func setup(t *testing.T) (func(...string) (string, error), *pipeline.Store, string) {
|
||||
@@ -145,7 +145,7 @@ func TestCLIAuthorOpenCodeGetsScopedSkillAndLeavesDraft(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
capture := filepath.Join(root, "invocation")
|
||||
script := filepath.Join(root, "opencode")
|
||||
os.WriteFile(script, []byte("#!/bin/sh\nif [ \"$1\" = api ]; then\n if [ \"$3\" = /api/session ]; then printf '%s' '{\"data\":{\"id\":\"ses_test\"}}'; fi\n exit 0\nfi\nprintf '%s\\n' \"$@\" > "+"'"+capture+"'"+"\n"), 0700)
|
||||
os.WriteFile(script, []byte("#!/bin/sh\nif [ \"$1\" = --help ]; then printf '%s\\n' ' api commands'; exit 0; fi\nif [ \"$1\" = api ]; then\n if [ \"$3\" = /api/session ]; then printf '%s' '{\"data\":{\"id\":\"ses_test\"}}'; fi\n exit 0\nfi\nprintf '%s\\n' \"$@\" > "+"'"+capture+"'"+"\n"), 0700)
|
||||
if _, err := run("new", "scoped skill", "Make a digest", "--opencode", script); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -33,11 +33,12 @@ var notes = map[string]string{
|
||||
}
|
||||
|
||||
var serviceHelp = map[string]string{
|
||||
"serve": "Run the native server in the foreground. Its flags are documented by pipelines serve --help. Installation never starts it automatically.",
|
||||
"start": "Start the per-user native pipeline server and this installation's Docker ntfy together.",
|
||||
"stop": "Stop both services. Active execution is interrupted; file changes are not rolled back.",
|
||||
"restart": "Stop, then start both services, retaining definitions, run history, and credentials.",
|
||||
"status": "Show pipeline/ntfy health and the public phone connection (no credentials).",
|
||||
"doctor": "Check both health endpoints and host OpenCode API discovery; does not execute a model.",
|
||||
"logs": "Follow the native server log. Press Ctrl+C to stop following.",
|
||||
"uninstall": "Remove this installation; retain data by default. --purge explicitly deletes this installation and its ntfy volume; --yes skips prompts.",
|
||||
"uninstall": "Remove verified Go binaries from this command's bin directory; retain data and drafts. --yes skips confirmation. Existing managed installations can be selected explicitly with PIPELINES_PREFIX.",
|
||||
}
|
||||
|
||||
@@ -28,11 +28,13 @@ EXECUTE
|
||||
ping Check the server connection
|
||||
rpc <request.json|-> Send any protocol command (automation escape hatch)
|
||||
|
||||
SERVICE / INTERFACE (managed installation)
|
||||
tui Open the dashboard (default with no command)
|
||||
start | stop | restart Manage the native server + Docker ntfy together
|
||||
status | doctor | logs Health, OpenCode discovery, server logs
|
||||
uninstall [--purge] Remove app; retain data unless explicitly purged
|
||||
SERVER / INTERFACE
|
||||
tui Open the dashboard (default with no command)
|
||||
serve Start native server in the foreground (Ctrl+C stops it)
|
||||
uninstall [--yes] Remove verified Go binaries; retain data and drafts
|
||||
|
||||
Legacy managed installs: select PIPELINES_PREFIX explicitly for start/stop,
|
||||
restart/status/doctor/logs and retained-data or --purge uninstallation.
|
||||
|
||||
Options: --url ws://127.0.0.1:8080/connect --json --help
|
||||
Use pipelines help <command> for its flags. Names with spaces must be quoted.
|
||||
|
||||
@@ -8,9 +8,9 @@ import (
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func Dial(ctx context.Context, url string) (*websocket.Conn, error) {
|
||||
|
||||
@@ -19,18 +19,13 @@ type Config struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
// Load finds the manifest next to the actual Go binary, including via a system PATH symlink.
|
||||
// A standalone go-installed CLI can also select a prefix with PIPELINES_PREFIX.
|
||||
// Load selects a legacy managed installation only via an explicit PIPELINES_PREFIX.
|
||||
func Load(executable string) (*Config, error) {
|
||||
resolved, err := filepath.EvalSymlinks(executable)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prefix := os.Getenv("PIPELINES_PREFIX")
|
||||
if prefix == "" {
|
||||
prefix = filepath.Dir(filepath.Dir(resolved))
|
||||
return nil, nil
|
||||
}
|
||||
prefix, err = filepath.Abs(prefix)
|
||||
prefix, err := filepath.Abs(prefix)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -60,8 +55,8 @@ func (c Config) Environment() error {
|
||||
}
|
||||
}
|
||||
}
|
||||
for key, value := range map[string]string{"PIPELINES_URL": "ws://127.0.0.1:" + strconv.Itoa(c.ServerPort) + "/connect", "PIPELINES_OPENCODE": c.OpenCode, "PATH": c.Path} {
|
||||
if key != "PATH" && os.Getenv(key) != "" {
|
||||
for key, value := range map[string]string{"PIPELINES_URL": "ws://127.0.0.1:" + strconv.Itoa(c.ServerPort) + "/connect", "PIPELINES_OPENCODE": c.OpenCode} {
|
||||
if os.Getenv(key) != "" {
|
||||
continue
|
||||
}
|
||||
if err := os.Setenv(key, value); err != nil {
|
||||
|
||||
@@ -18,6 +18,7 @@ func TestCompiledCommandFindsManifestThroughSystemLink(t *testing.T) {
|
||||
os.WriteFile(filepath.Join(root, "pipelines-install.json"), data, 0600)
|
||||
link := filepath.Join(t.TempDir(), "pipelines")
|
||||
os.Symlink(binary, link)
|
||||
t.Setenv("PIPELINES_PREFIX", root)
|
||||
loaded, err := Load(link)
|
||||
if err != nil || loaded == nil || loaded.Prefix != root {
|
||||
t.Fatal(loaded, err)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package installation
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"debug/buildinfo"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Uninstall removes only verified binaries from the current command's Go bin directory.
|
||||
// Data is deliberately retained: custom server database paths cannot be safely inferred.
|
||||
func Uninstall(executable string, args []string, in io.Reader, out io.Writer) error {
|
||||
f := flag.NewFlagSet("uninstall", flag.ContinueOnError)
|
||||
f.SetOutput(out)
|
||||
yes := f.Bool("yes", false, "Skip confirmation")
|
||||
if err := f.Parse(args); err != nil {
|
||||
if err == flag.ErrHelp {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if len(f.Args()) > 0 {
|
||||
return fmt.Errorf("uninstall takes no positional arguments")
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(executable)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dir := filepath.Dir(resolved)
|
||||
var files []string
|
||||
for _, command := range []string{"pipelines", "pipelines-server", "pipelines-tui"} {
|
||||
path := filepath.Join(dir, command)
|
||||
info, err := buildinfo.ReadFile(path)
|
||||
if os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot verify %s; no binaries removed: %w", path, err)
|
||||
}
|
||||
if info.Path != "git.a-wan.net/alan/pipelines/cmd/"+command {
|
||||
return fmt.Errorf("%s is not a Pipelines Go binary; no binaries removed", path)
|
||||
}
|
||||
files = append(files, path)
|
||||
}
|
||||
if !*yes {
|
||||
fmt.Fprintf(out, "Remove %s? Data and drafts are retained. [y/N] ", strings.Join(files, ", "))
|
||||
answer, err := bufio.NewReader(in).ReadString('\n')
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(strings.ToLower(answer)) != "y" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
for _, path := range files {
|
||||
if err := os.Remove(path); err != nil {
|
||||
return fmt.Errorf("remove %s: %w (use the permissions appropriate to your bin directory)", path, err)
|
||||
}
|
||||
}
|
||||
fmt.Fprintln(out, "Removed Go binaries. Pipeline history, drafts, and OpenCode configuration were retained.")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
// Package opencode adapts the two published OpenCode API families without installing a CLI.
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MaxRequest = 64 << 10
|
||||
const MaxResponse = 1 << 20
|
||||
|
||||
type Connection struct {
|
||||
Backend, Executable, Directory string
|
||||
URL string
|
||||
password string
|
||||
process *exec.Cmd
|
||||
done chan error
|
||||
models map[string]map[string]string
|
||||
responses map[string][]byte
|
||||
}
|
||||
|
||||
// Reference records only our ephemeral loopback service credentials, never provider auth.
|
||||
// The private file lets crash recovery abort the same owned service, not a new instance.
|
||||
func (c *Connection) Reference() (string, error) {
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dir := filepath.Join(cache, "pipelines", "private")
|
||||
if err = os.MkdirAll(dir, 0700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
f, err := os.CreateTemp(dir, "opencode-connection-*.json")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
data, _ := json.Marshal(map[string]string{"url": c.URL, "password": c.password, "directory": c.Directory})
|
||||
_, writeErr := f.Write(data)
|
||||
closeErr := f.Close()
|
||||
if writeErr != nil {
|
||||
return "", writeErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return "", closeErr
|
||||
}
|
||||
return f.Name(), nil
|
||||
}
|
||||
|
||||
func FromReference(path string) (*Connection, error) {
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Mode().Perm() != 0600 || info.Size()>MaxRequest {
|
||||
return nil, fmt.Errorf("invalid private OpenCode connection reference")
|
||||
}
|
||||
if stat, ok := info.Sys().(*syscall.Stat_t); !ok || stat.Uid != uint32(os.Getuid()) {
|
||||
return nil, fmt.Errorf("OpenCode reference belongs to another user")
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var reference struct{ URL, Password, Directory string }
|
||||
if err = json.Unmarshal(data, &reference); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u, err := url.Parse(reference.URL)
|
||||
if err != nil || u.Scheme != "http" || u.Hostname() != "127.0.0.1" || u.Port() == "" || u.Path != "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || len(reference.Password) != 64 {
|
||||
return nil, fmt.Errorf("invalid owned OpenCode service endpoint")
|
||||
}
|
||||
return &Connection{Backend: "v1", URL: reference.URL, password: reference.Password, Directory: reference.Directory}, nil
|
||||
}
|
||||
|
||||
func Executable() string {
|
||||
if path := os.Getenv("PIPELINES_OPENCODE"); path != "" {
|
||||
return path
|
||||
}
|
||||
return "opencode"
|
||||
}
|
||||
|
||||
// Detect checks the advertised command interface, not an assumed release number.
|
||||
func Detect(ctx context.Context, executable string) (string, error) {
|
||||
cmd := exec.CommandContext(ctx, executable, "--help")
|
||||
data, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot run the selected OpenCode CLI: %w", err)
|
||||
}
|
||||
if regexp.MustCompile(`(?m)^\s*(?:opencode\s+)?api\s`).Match(data) {
|
||||
return "v2", nil
|
||||
}
|
||||
if regexp.MustCompile(`(?m)^\s*(?:opencode\s+)?serve\s`).Match(data) {
|
||||
return "v1", nil
|
||||
}
|
||||
return "", fmt.Errorf("selected OpenCode CLI advertises neither api nor serve")
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, executable, directory, backend string) (*Connection, error) {
|
||||
if executable == "" {
|
||||
executable = Executable()
|
||||
}
|
||||
if directory == "" {
|
||||
var err error
|
||||
directory, err = os.Getwd()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if backend == "" {
|
||||
var err error
|
||||
backend, err = Detect(ctx, executable)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
c := &Connection{Backend: backend, Executable: executable, Directory: directory, models: map[string]map[string]string{}, responses: map[string][]byte{}}
|
||||
if backend == "v2" {
|
||||
return c, nil
|
||||
}
|
||||
if backend != "v1" {
|
||||
return nil, fmt.Errorf("unknown OpenCode backend %q", backend)
|
||||
}
|
||||
secret := make([]byte, 32)
|
||||
if _, err := rand.Read(secret); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.password = hex.EncodeToString(secret)
|
||||
c.process = exec.Command(executable, "serve", "--hostname", "127.0.0.1", "--port", "0")
|
||||
c.process.Dir = directory
|
||||
for _, entry := range os.Environ() {
|
||||
if !strings.HasPrefix(entry, "OPENCODE_SERVER_PASSWORD=") && !strings.HasPrefix(entry, "OPENCODE_SERVER_USERNAME=") {
|
||||
c.process.Env = append(c.process.Env, entry)
|
||||
}
|
||||
}
|
||||
c.process.Env = append(c.process.Env, "OPENCODE_SERVER_PASSWORD="+c.password, "OPENCODE_SERVER_USERNAME=pipelines")
|
||||
stdout, err := c.process.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.process.Stderr = io.Discard
|
||||
if err = c.process.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.done = make(chan error, 1)
|
||||
go func() { c.done <- c.process.Wait() }()
|
||||
address := make(chan string, 1)
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(stdout)
|
||||
pattern := regexp.MustCompile(`http://127\.0\.0\.1:[0-9]+`)
|
||||
sent := false
|
||||
for scanner.Scan() {
|
||||
if !sent {
|
||||
if found := pattern.FindString(scanner.Text()); found != "" {
|
||||
address <- found
|
||||
sent = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
startup, stop := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer stop()
|
||||
select {
|
||||
case c.URL = <-address:
|
||||
case <-c.done:
|
||||
c.process = nil
|
||||
return nil, fmt.Errorf("OpenCode serve exited before becoming ready")
|
||||
case <-startup.Done():
|
||||
c.Close()
|
||||
return nil, fmt.Errorf("OpenCode serve startup: %w", startup.Err())
|
||||
}
|
||||
health, err := c.Native(startup, "get", "/global/health", nil)
|
||||
var result struct {
|
||||
Healthy bool `json:"healthy"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if err != nil || json.Unmarshal(health, &result) != nil || !result.Healthy || result.Version == "" {
|
||||
c.Close()
|
||||
return nil, fmt.Errorf("OpenCode serve did not return the expected native health contract")
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *Connection) Close() {
|
||||
if c.process == nil {
|
||||
return
|
||||
}
|
||||
_ = c.process.Process.Signal(syscall.SIGTERM)
|
||||
select {
|
||||
case <-c.done:
|
||||
case <-time.After(5 * time.Second):
|
||||
_ = c.process.Process.Kill()
|
||||
<-c.done
|
||||
}
|
||||
c.process = nil
|
||||
}
|
||||
|
||||
func (c *Connection) Native(ctx context.Context, method, path string, body any) ([]byte, error) {
|
||||
u, err := url.Parse(c.URL + path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query := u.Query()
|
||||
query.Set("directory", c.Directory)
|
||||
u.RawQuery = query.Encode()
|
||||
var data []byte
|
||||
if body != nil {
|
||||
data, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(data) > MaxRequest {
|
||||
return nil, fmt.Errorf("OpenCode request exceeds 64 KiB")
|
||||
}
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, strings.ToUpper(method), u.String(), bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.SetBasicAuth("pipelines", c.password)
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return nil, fmt.Errorf("OpenCode native API request failed")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("OpenCode %s %s failed (HTTP %d)", method, path, response.StatusCode)
|
||||
}
|
||||
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)
|
||||
}
|
||||
data, err = io.ReadAll(io.LimitReader(response.Body, MaxResponse+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(data) > MaxResponse {
|
||||
return nil, fmt.Errorf("OpenCode response exceeds 1 MiB")
|
||||
}
|
||||
if !json.Valid(data) {
|
||||
return nil, fmt.Errorf("OpenCode returned invalid JSON")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// This test does no inference and never uses or copies the user's login.
|
||||
func TestStableNativeSessionContractLive(t *testing.T) {
|
||||
executable := os.Getenv("PIPELINES_TEST_OPENCODE_V1")
|
||||
if executable == "" {
|
||||
t.Skip("set PIPELINES_TEST_OPENCODE_V1 for no-inference stable CLI contract test")
|
||||
}
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", home+"/config")
|
||||
t.Setenv("XDG_DATA_HOME", home+"/data")
|
||||
t.Setenv("XDG_CACHE_HOME", home+"/cache")
|
||||
t.Setenv("XDG_STATE_HOME", home+"/state")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
||||
defer cancel()
|
||||
c, err := Open(ctx, executable, home, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
if c.Backend != "v1" {
|
||||
t.Fatal("expected native serve backend")
|
||||
}
|
||||
data, err := c.Call(ctx, "post", "/api/session", map[string]any{"title": "Pipelines contract test", "model": map[string]string{"providerID": "opencode-go", "id": "deepseek-v4.1-flash"}, "permissions": []map[string]string{{"action": "*", "resource": "*", "effect": "deny"}, {"action": "read", "resource": "*", "effect": "allow"}, {"action": "shell", "resource": "go test ./...", "effect": "allow"}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var result struct {
|
||||
Data struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
json.Unmarshal(data, &result)
|
||||
defer c.Call(context.Background(), "delete", "/api/session/"+result.Data.ID, nil)
|
||||
data, err = c.Native(ctx, "get", "/session/"+result.Data.ID, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var session struct {
|
||||
Permission []map[string]string `json:"permission"`
|
||||
}
|
||||
json.Unmarshal(data, &session)
|
||||
if len(session.Permission) != 3 || session.Permission[2]["permission"] != "bash" {
|
||||
t.Fatal("scoped native permission contract not retained", string(data))
|
||||
}
|
||||
ref, err := c.Reference()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(ref)
|
||||
recovered, err := FromReference(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = recovered.Call(ctx, "post", "/api/session/"+result.Data.ID+"/interrupt", nil); err != nil {
|
||||
t.Fatal("cannot abort same owned service via durable reference", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
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"`
|
||||
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" || message.Info.Finish != "stop" || message.Info.Time.Completed == 0 {
|
||||
return "", fmt.Errorf("OpenCode returned no completed assistant result")
|
||||
}
|
||||
if len(message.Info.Error) > 0 && string(message.Info.Error) != "null" {
|
||||
return "", fmt.Errorf("OpenCode agent reported an execution error")
|
||||
}
|
||||
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 nil, 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 map[string]string
|
||||
if err := json.Unmarshal(data, &request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
text := request["prompt"]
|
||||
if text == "" {
|
||||
text = request["text"]
|
||||
}
|
||||
response, err := c.Native(ctx, "post", "/session/"+id+"/message", map[string]any{"model": c.models[id], "parts": []map[string]string{{"type": "text", "text": text}}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.responses[id] = response
|
||||
if parts[1] == "prompt" {
|
||||
return nil, nil
|
||||
}
|
||||
result, err := messageText(response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(map[string]any{"data": map[string]string{"text": result}})
|
||||
case "wait":
|
||||
_, err := messageText(c.responses[id])
|
||||
return nil, err
|
||||
case "message":
|
||||
data, err := c.Native(ctx, "get", "/session/"+id+"/message", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var messages []struct {
|
||||
Info map[string]any `json:"info"`
|
||||
Parts []map[string]any `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]
|
||||
if m.Info["role"] != "assistant" {
|
||||
continue
|
||||
}
|
||||
converted = append(converted, map[string]any{"finish": m.Info["finish"], "error": m.Info["error"], "content": m.Parts, "native_info": m.Info})
|
||||
}
|
||||
return json.Marshal(map[string]any{"data": converted})
|
||||
}
|
||||
return nil, fmt.Errorf("unsupported native OpenCode operation")
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNativeSessionModelPermissionsGenerationAndAbort(t *testing.T) {
|
||||
var created, prompted, deleted, aborted bool
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Query().Get("directory") != "/repo" {
|
||||
t.Error("workspace lost")
|
||||
}
|
||||
switch r.Method + " " + r.URL.Path {
|
||||
case "POST /session":
|
||||
var body struct {
|
||||
Model map[string]string
|
||||
Permission []map[string]string
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
if body.Model["id"] != "model" || body.Model["providerID"] != "provider" || body.Permission[0]["action"] != "deny" || body.Permission[1]["permission"] != "bash" {
|
||||
t.Error("model or scoped permissions lost", body)
|
||||
}
|
||||
created = true
|
||||
w.Write([]byte(`{"id":"ses_native"}`))
|
||||
case "POST /session/ses_native/message":
|
||||
var body struct {
|
||||
Model map[string]string
|
||||
Parts []map[string]string
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
if body.Model["modelID"] != "model" || body.Parts[0]["text"] != "exact prompt" {
|
||||
t.Error("prompt or message model changed", body)
|
||||
}
|
||||
prompted = true
|
||||
w.Write([]byte(`{"info":{"role":"assistant","finish":"stop","time":{"completed":1}},"parts":[{"type":"text","text":"result"}]}`))
|
||||
case "GET /session/ses_native/message":
|
||||
w.Write([]byte(`[{"info":{"role":"assistant","finish":"stop","time":{"completed":1}},"parts":[{"type":"text","text":"result"}]}]`))
|
||||
case "POST /session/ses_native/abort":
|
||||
aborted = true
|
||||
w.Write([]byte("true"))
|
||||
case "DELETE /session/ses_native":
|
||||
deleted = true
|
||||
w.Write([]byte("true"))
|
||||
default:
|
||||
t.Error("unexpected native operation", r.Method, r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
c := &Connection{Backend: "v1", URL: server.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}}
|
||||
ctx := context.Background()
|
||||
_, err := c.Call(ctx, "post", "/api/session", map[string]any{"model": map[string]string{"providerID": "provider", "id": "model"}, "permissions": []map[string]string{{"action": "*", "resource": "*", "effect": "deny"}, {"action": "shell", "resource": "go test ./...", "effect": "allow"}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := c.Call(ctx, "post", "/api/session/ses_native/generate", map[string]string{"prompt": "exact prompt"})
|
||||
if err != nil || !strings.Contains(string(data), "result") {
|
||||
t.Fatal(string(data), err)
|
||||
}
|
||||
if _, err = c.Call(ctx, "post", "/api/experimental/session/ses_native/wait", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = c.Call(ctx, "get", "/api/session/ses_native/message?order=desc", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = c.Call(ctx, "post", "/api/session/ses_native/interrupt", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = c.Call(ctx, "delete", "/api/session/ses_native", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !created || !prompted || !deleted || !aborted {
|
||||
t.Fatal("native lifecycle incomplete")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTMLBridgeIsNotAnAPIAndErrorsAreRedacted(t *testing.T) {
|
||||
for _, status := range []int{200, 500} {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(status)
|
||||
w.Write([]byte("secret-token HTML"))
|
||||
}))
|
||||
c := &Connection{URL: server.URL}
|
||||
_, err := c.Native(context.Background(), "get", "/api/session", nil)
|
||||
server.Close()
|
||||
if err == nil || strings.Contains(err.Error(), "secret-token") {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, body := range []string{`{"info":{"role":"assistant","finish":"tool-calls","time":{"completed":1}},"parts":[]}`, `{"info":{"role":"assistant","finish":"stop"},"parts":[{"type":"text","text":"unfinished"}]}`, `{"info":{"role":"assistant","finish":"stop","time":{"completed":1},"error":{"message":"bad"}},"parts":[{"type":"text","text":"failed"}]}`} {
|
||||
if _, err := messageText([]byte(body)); err == nil {
|
||||
t.Fatal("unfinished/error response accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Package paths centralizes standard user locations; callers can override them.
|
||||
package paths
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func Data() (string, error) {
|
||||
if dir := os.Getenv("XDG_DATA_HOME"); dir != "" {
|
||||
return filepath.Abs(filepath.Join(dir, "pipelines"))
|
||||
}
|
||||
if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
|
||||
dir, err := os.UserConfigDir()
|
||||
return filepath.Join(dir, "pipelines"), err
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
return filepath.Join(home, ".local", "share", "pipelines"), err
|
||||
}
|
||||
func Database() (string, error) { dir, err := Data(); return filepath.Join(dir, "pipelines.db"), err }
|
||||
@@ -0,0 +1,15 @@
|
||||
package paths
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDataLocationIsIndependentOfExecutable(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_DATA_HOME", dir)
|
||||
db, err := Database()
|
||||
if err != nil || db != filepath.Join(dir, "pipelines", "pipelines.db") {
|
||||
t.Fatal(db, err)
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@ package pipeline
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestShowcaseDefinitions(t *testing.T) {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"os"
|
||||
"pipelines/internal/protocol"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ package pipeline
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func (s *Store) initRuns() error {
|
||||
@@ -27,6 +27,9 @@ started_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, finished_at TEXT, PRIMARY KE
|
||||
CREATE INDEX IF NOT EXISTS run_latest ON pipeline_runs(id DESC);
|
||||
CREATE TABLE IF NOT EXISTS step_notifications (
|
||||
run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, receipts_json TEXT NOT NULL,
|
||||
PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence));
|
||||
CREATE TABLE IF NOT EXISTS run_session_owners (
|
||||
run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, backend TEXT NOT NULL, reference TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence));`)
|
||||
return err
|
||||
}
|
||||
@@ -211,8 +214,49 @@ func (s *Store) BeginStep(ctx context.Context, id int64, sequence int, key strin
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) RunSession(ctx context.Context, id int64, sequence int, session string, active bool) error {
|
||||
return affected(s.db.ExecContext(ctx, "UPDATE run_steps SET session_id=?,agent_active=? WHERE run_id=? AND sequence=? AND status='running'", session, active, id, sequence))
|
||||
func (s *Store) RunSession(ctx context.Context, id int64, sequence int, session string, active bool, metadata ...string) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err = affected(tx.ExecContext(ctx, "UPDATE run_steps SET session_id=?,agent_active=? WHERE run_id=? AND sequence=? AND status='running'", session, active, id, sequence)); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(metadata) > 0 {
|
||||
backend := metadata[0]
|
||||
if backend == "" {
|
||||
backend = "v2"
|
||||
}
|
||||
reference := ""
|
||||
if len(metadata) > 1 {
|
||||
reference = metadata[1]
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "INSERT INTO run_session_owners(run_id,sequence,backend,reference) VALUES(?,?,?,?) ON CONFLICT(run_id,sequence) DO UPDATE SET backend=excluded.backend,reference=excluded.reference", id, sequence, backend, reference); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
type SessionOwner struct{ ID, Backend, Directory, Reference string }
|
||||
|
||||
func (s *Store) ActiveSessionOwners(ctx context.Context) ([]SessionOwner, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT s.session_id,COALESCE(o.backend,'v2'),r.workspace,COALESCE(o.reference,'')
|
||||
FROM run_steps s JOIN pipeline_runs r ON r.id=s.run_id LEFT JOIN run_session_owners o ON o.run_id=s.run_id AND o.sequence=s.sequence WHERE s.agent_active=1 AND s.session_id<>''`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var owners []SessionOwner
|
||||
for rows.Next() {
|
||||
var owner SessionOwner
|
||||
if err = rows.Scan(&owner.ID, &owner.Backend, &owner.Directory, &owner.Reference); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owners = append(owners, owner)
|
||||
}
|
||||
return owners, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) FinishStep(ctx context.Context, id int64, step protocol.RunStep) error {
|
||||
|
||||
@@ -2,7 +2,7 @@ package pipeline
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@ package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"time"
|
||||
)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// StageDefinition adapts normalized/persisted graph data for type implementations.
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
type constantStage struct{}
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -3,9 +3,9 @@ package pipeline
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"path/filepath"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
@@ -2,8 +2,8 @@ package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"path/filepath"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -4,12 +4,12 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"git.a-wan.net/alan/pipelines/internal/cli"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"pipelines/internal/cli"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"net/url"
|
||||
"os"
|
||||
"pipelines/internal/protocol"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -3,12 +3,12 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -4,15 +4,15 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
|
||||
@@ -2,12 +2,12 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
||||
@@ -8,11 +8,11 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
)
|
||||
|
||||
func TestRunWebSocketRemainsResponsiveAndAuditable(t *testing.T) {
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
type runner struct {
|
||||
@@ -27,16 +27,16 @@ type runner struct {
|
||||
}
|
||||
|
||||
func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
|
||||
sessions, err := s.ActiveAgentSessions(ctx)
|
||||
sessions, err := s.ActiveSessionOwners(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, id := range sessions {
|
||||
for _, owner := range sessions {
|
||||
stop, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
err := (stage.OpenCodeClient{}).Interrupt(stop, id)
|
||||
err := (stage.OpenCodeClient{Backend: owner.Backend, Directory: owner.Directory, Reference: owner.Reference}).Interrupt(stop, owner.ID)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot interrupt previously active agent %s: %w", id, err)
|
||||
return nil, fmt.Errorf("cannot interrupt previously active agent %s: %w", owner.ID, err)
|
||||
}
|
||||
}
|
||||
if err := s.RecoverRuns(ctx); err != nil {
|
||||
@@ -241,7 +241,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
client.OnSession = func(session string, active bool) error {
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
return r.store.RunSession(c, id, sequence, session, active)
|
||||
return r.store.RunSession(c, id, sequence, session, active, client.Backend, client.Reference)
|
||||
}
|
||||
var result stage.Result
|
||||
var err error
|
||||
|
||||
@@ -7,9 +7,9 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
func TestRunnerRoutingPersistenceAndIdempotency(t *testing.T) {
|
||||
|
||||
@@ -2,12 +2,12 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -2,9 +2,9 @@ package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"log"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"time"
|
||||
)
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -2,12 +2,12 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -2,10 +2,10 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"pipelines/examples"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/examples"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Handler serves the persistent connection. Canceling ctx stops active clients.
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
type logBuffer struct {
|
||||
|
||||
@@ -2,11 +2,11 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -23,11 +25,35 @@ func (c OpenCodeClient) Interrupt(ctx context.Context, id string) error {
|
||||
if !sessionIDPattern.MatchString(id) {
|
||||
return fmt.Errorf("invalid session ID")
|
||||
}
|
||||
if c.command == nil && c.connection == nil {
|
||||
var connection *opencode.Connection
|
||||
var err error
|
||||
if c.Backend == "v1" && c.Reference != "" {
|
||||
connection, err = opencode.FromReference(c.Reference)
|
||||
} else {
|
||||
connection, err = opencode.Open(ctx, opencode.Executable(), c.Directory, c.Backend)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer connection.Close()
|
||||
c.connection = connection
|
||||
c.Backend = connection.Backend
|
||||
}
|
||||
_, err := c.call(ctx, "post", "/api/session/"+id+"/interrupt", map[string]any{})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt string) (text string, err error) {
|
||||
if c.command == nil {
|
||||
connection, err := opencode.Open(ctx, opencode.Executable(), c.Directory, c.Backend)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer connection.Close()
|
||||
c.connection = connection
|
||||
c.Backend = connection.Backend
|
||||
}
|
||||
rules := c.permissionRules()
|
||||
data, err := c.call(ctx, "post", "/api/session", map[string]any{"title": "Pipeline audited agent stage", "agent": "build", "location": map[string]string{"directory": c.Directory}, "model": map[string]string{"providerID": config.Provider, "id": config.Model}, "permissions": rules})
|
||||
if err != nil {
|
||||
@@ -42,8 +68,22 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
|
||||
return "", fmt.Errorf("invalid agent session")
|
||||
}
|
||||
c.SessionID = created.Data.ID
|
||||
if c.connection != nil && c.Backend == "v1" {
|
||||
c.Reference, err = c.connection.Reference()
|
||||
if err != nil {
|
||||
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second)
|
||||
defer cancel()
|
||||
_, _ = c.call(cleanup, "delete", "/api/session/"+c.SessionID, nil)
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if c.OnSession != nil {
|
||||
if err := c.OnSession(c.SessionID, true); err != nil {
|
||||
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second)
|
||||
defer cancel()
|
||||
if _, cleanupErr := c.call(cleanup, "delete", "/api/session/"+c.SessionID, nil); cleanupErr != nil {
|
||||
return "", fmt.Errorf("agent ownership could not be recorded and session cleanup failed")
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
@@ -60,8 +100,12 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
|
||||
if persistErr := c.OnSession(c.SessionID, false); persistErr != nil {
|
||||
err = persistErr
|
||||
text = ""
|
||||
return
|
||||
}
|
||||
}
|
||||
if c.Reference != "" {
|
||||
_ = os.Remove(c.Reference)
|
||||
}
|
||||
}()
|
||||
tools := c.Tools
|
||||
if tools == nil {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"git.a-wan.net/alan/pipelines/internal/opencode"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -17,13 +18,16 @@ import (
|
||||
const maxModelRequest = 64 << 10 // CLI request body is passed as one OS argument.
|
||||
const maxModelResponse = 1 << 20
|
||||
|
||||
// OpenCodeClient reuses OpenCode V2's service discovery and authenticated accounts.
|
||||
// OpenCodeClient reuses the selected OpenCode CLI and its authenticated accounts.
|
||||
// No API keys are copied into pipeline definitions, subprocess arguments, or logs.
|
||||
// A fresh location-scoped session avoids unrelated user conversation history and
|
||||
// is deleted after generation. Generation is text-only: no agent tools are run.
|
||||
type OpenCodeClient struct {
|
||||
Directory string // empty uses the pipeline server's working directory
|
||||
command func(context.Context, string, ...string) ([]byte, error)
|
||||
Directory string // empty uses the pipeline server's working directory
|
||||
Backend string
|
||||
Reference string
|
||||
connection *opencode.Connection
|
||||
command func(context.Context, string, ...string) ([]byte, error)
|
||||
}
|
||||
|
||||
type openCodeError struct {
|
||||
@@ -48,6 +52,20 @@ var sessionIDPattern = regexp.MustCompile(`^ses[A-Za-z0-9_-]+$`)
|
||||
var httpStatusPattern = regexp.MustCompile(`HTTP (\d{3})`)
|
||||
|
||||
func (c OpenCodeClient) call(ctx context.Context, method, path string, body any) ([]byte, error) {
|
||||
if c.connection != nil && c.connection.Backend == "v1" {
|
||||
data, err := c.connection.Call(ctx, method, path, body)
|
||||
if err != nil {
|
||||
status := 0
|
||||
if match := httpStatusPattern.FindStringSubmatch(err.Error()); len(match) > 0 {
|
||||
status, _ = strconv.Atoi(match[1])
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return nil, &openCodeError{operation: method + " " + path, status: status, cause: err}
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
args := []string{"api", method, path}
|
||||
if body != nil {
|
||||
data, err := json.Marshal(body)
|
||||
@@ -70,7 +88,7 @@ func (c OpenCodeClient) call(ctx context.Context, method, path string, body any)
|
||||
if c.command != nil {
|
||||
return c.command(ctx, directory, args...)
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, "opencode", args...)
|
||||
cmd := exec.CommandContext(ctx, opencode.Executable(), args...)
|
||||
cmd.Dir = directory
|
||||
stdout := &boundedBuffer{limit: maxModelResponse}
|
||||
stderr := &boundedBuffer{limit: 8 << 10}
|
||||
@@ -94,6 +112,15 @@ func (c OpenCodeClient) call(ctx context.Context, method, path string, body any)
|
||||
}
|
||||
|
||||
func (c OpenCodeClient) Generate(ctx context.Context, config ModelConfig, prompt string) (text string, err error) {
|
||||
if c.command == nil {
|
||||
connection, err := opencode.Open(ctx, opencode.Executable(), c.Directory, c.Backend)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer connection.Close()
|
||||
c.connection = connection
|
||||
c.Backend = connection.Backend
|
||||
}
|
||||
directory := c.Directory
|
||||
if directory == "" {
|
||||
directory, err = os.Getwd()
|
||||
|
||||
@@ -33,7 +33,7 @@ func ToolNames(def Definition) ([]string, bool, error) {
|
||||
return tools, true, nil
|
||||
}
|
||||
|
||||
var verificationCommands = []string{"go test ./...", "go test -count=1 ./...", "go test -race ./...", "go test -race -count=1 ./...", "go vet ./...", "go build ./cmd/server ./cmd/tui"}
|
||||
var verificationCommands = []string{"go test ./...", "go test -count=1 ./...", "go test -race ./...", "go test -race -count=1 ./...", "go vet ./...", "go build ./cmd/..."}
|
||||
|
||||
func (c *AgentClient) permissionRules() []map[string]string {
|
||||
rules := []map[string]string{{"action": "*", "resource": "*", "effect": "deny"}}
|
||||
|
||||
@@ -3,9 +3,9 @@ package tui
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/sahilm/fuzzy"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
)
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@ package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -13,10 +13,10 @@ import (
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
|
||||
"pipelines/internal/client"
|
||||
"pipelines/internal/draft"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/client"
|
||||
"git.a-wan.net/alan/pipelines/internal/draft"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
type editedMsg struct {
|
||||
|
||||
@@ -12,8 +12,8 @@ import (
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/server"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/server"
|
||||
)
|
||||
|
||||
func TestCreateAndSubmit(t *testing.T) {
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"github.com/sahilm/fuzzy"
|
||||
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
var commands = []string{":logs", ":new", ":templates", ":refresh", ":ping", ":edit", ":submit", ":versions", ":run", ":runs", ":home", ":quit"}
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func press(m Model, key string) Model {
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"pipelines/internal/pipeline"
|
||||
)
|
||||
|
||||
func TestShowcaseGraphsRender(t *testing.T) {
|
||||
|
||||
@@ -5,9 +5,9 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func outcomes(stage protocol.Stage) []string {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"sort"
|
||||
)
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func nestedForkGraph(t *testing.T) protocol.Graph {
|
||||
|
||||
@@ -2,7 +2,7 @@ package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"sort"
|
||||
)
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestRenderGraphWithCyclesAndDefaults(t *testing.T) {
|
||||
|
||||
@@ -7,11 +7,11 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"github.com/muesli/termenv"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
var sgr = regexp.MustCompile(`\x1b\[([0-9;]*)m`)
|
||||
|
||||
@@ -18,8 +18,8 @@ import (
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"github.com/coder/websocket"
|
||||
|
||||
"pipelines/internal/client"
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/client"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
type connectedMsg struct{ conn *websocket.Conn }
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
|
||||
"pipelines/internal/server"
|
||||
"git.a-wan.net/alan/pipelines/internal/server"
|
||||
)
|
||||
|
||||
func TestTKeyPingRoundTrip(t *testing.T) {
|
||||
|
||||
@@ -2,8 +2,8 @@ package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
type paneGeometry struct {
|
||||
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"github.com/muesli/termenv"
|
||||
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func panelModel(t *testing.T) Model {
|
||||
|
||||
@@ -3,10 +3,10 @@ package tui
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/sahilm/fuzzy"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
)
|
||||
|
||||
|
||||
@@ -9,9 +9,9 @@ import (
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/sahilm/fuzzy"
|
||||
|
||||
"pipelines/internal/draft"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/draft"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func selectionWindow(count, index, capacity int) (int, int) {
|
||||
|
||||
@@ -12,9 +12,9 @@ import (
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/server"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/server"
|
||||
)
|
||||
|
||||
func TestSearchVersionsAndEditSubmission(t *testing.T) {
|
||||
|
||||
@@ -8,9 +8,9 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func (m *Model) closeRuns() {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Animation is driven by a local timer, never by extra server requests.
|
||||
|
||||
@@ -2,13 +2,13 @@ package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/server"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/server"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -5,10 +5,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/charmbracelet/bubbles/textarea"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
type runTick struct{}
|
||||
|
||||
@@ -2,10 +2,10 @@ package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -2,12 +2,12 @@ package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.a-wan.net/alan/pipelines/internal/draft"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/glamour"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"pipelines/internal/draft"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
)
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@ package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.a-wan.net/alan/pipelines/examples"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pipelines/examples"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/charmbracelet/bubbles/help"
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"pipelines/internal/protocol"
|
||||
"sort"
|
||||
)
|
||||
|
||||
|
||||
@@ -3,11 +3,11 @@ package tui
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user