package stage import ( "bytes" "context" "encoding/json" "errors" "fmt" "git.a-wan.net/alan/pipelines/internal/opencode" "io" "os" "os/exec" "regexp" "strconv" "time" ) const maxModelRequest = 64 << 10 // CLI request body is passed as one OS argument. const maxModelResponse = 1 << 20 // 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 Backend string Reference string connection *opencode.Connection command func(context.Context, string, ...string) ([]byte, error) } type openCodeError struct { operation string status int cause error } func (e *openCodeError) Unwrap() error { return e.cause } func (e *openCodeError) Error() string { if e.status > 0 { return fmt.Sprintf("OpenCode %s failed (HTTP %d)", e.operation, e.status) } return fmt.Sprintf("OpenCode %s command failed", e.operation) } func (e *openCodeError) Retryable() bool { return e.status == 429 || e.status == 502 || e.status == 503 || e.status == 504 } 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) if err != nil { return nil, err } if len(data) > maxModelRequest { return nil, fmt.Errorf("OpenCode request exceeds 64 KiB limit") } args = append(args, "--data", string(data)) } directory := c.Directory if directory == "" { var err error directory, err = os.Getwd() if err != nil { return nil, err } } if c.command != nil { return c.command(ctx, directory, args...) } cmd := exec.CommandContext(ctx, opencode.Executable(), args...) cmd.Dir = directory stdout := &boundedBuffer{limit: maxModelResponse} stderr := &boundedBuffer{limit: 8 << 10} cmd.Stdout = stdout cmd.Stderr = stderr if err := cmd.Run(); err != nil { if ctx.Err() != nil { return nil, ctx.Err() } status := 0 if match := httpStatusPattern.FindStringSubmatch(stderr.String()); len(match) > 0 { status, _ = strconv.Atoi(match[1]) } // Do not embed provider responses, prompts, credentials, or CLI logs in errors. return nil, &openCodeError{operation: method + " " + path, status: status} } if stdout.overflow { return nil, fmt.Errorf("OpenCode response exceeds 1 MiB limit") } return stdout.Bytes(), nil } 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() if err != nil { return "", err } } // Fail before creating a session if the generation payload is too large. body := map[string]string{"prompt": prompt} encoded, err := json.Marshal(body) if err != nil { return "", err } if len(encoded) > maxModelRequest { return "", fmt.Errorf("OpenCode request exceeds 64 KiB limit") } created, err := c.call(ctx, "post", "/api/session", map[string]any{ "title": "Pipeline stage generation", "location": map[string]string{"directory": directory}, "model": map[string]string{"providerID": config.Provider, "id": config.Model}, }) if err != nil { return "", err } var session struct { Data struct { ID string `json:"id"` } `json:"data"` } if err := json.Unmarshal(created, &session); err != nil || !sessionIDPattern.MatchString(session.Data.ID) { return "", fmt.Errorf("OpenCode returned an invalid session ID") } defer func() { cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) defer cancel() if _, cleanupErr := c.call(cleanup, "delete", "/api/session/"+session.Data.ID, nil); cleanupErr != nil { text = "" err = &openCodeError{operation: "session cleanup", cause: errors.Join(err, cleanupErr)} } }() response, err := c.call(ctx, "post", "/api/session/"+session.Data.ID+"/generate", body) if err != nil { return "", err } var generated struct { Data struct { Text *string `json:"text"` } `json:"data"` } if err := json.Unmarshal(response, &generated); err != nil || generated.Data.Text == nil { return "", fmt.Errorf("OpenCode returned an invalid generation response") } return *generated.Data.Text, nil } type boundedBuffer struct { bytes.Buffer limit int overflow bool } func (b *boundedBuffer) Write(p []byte) (int, error) { n := len(p) remaining := b.limit - b.Len() if n > remaining { b.overflow = true p = p[:remaining] } _, _ = b.Buffer.Write(p) return n, nil // Drain subprocess output without retaining unbounded data. } var _ io.Writer = (*boundedBuffer)(nil)