Validate providers and retain complete run debugging context

This commit is contained in:
2026-10-09 23:21:01 +01:00
parent f3d829bea5
commit 08b8647d5b
51 changed files with 1036 additions and 159 deletions
+3
View File
@@ -45,6 +45,9 @@ func (c OpenCodeClient) Interrupt(ctx context.Context, id string) error {
}
func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt string) (text string, err error) {
if c.Operations != nil {
c.Operations.Provider, c.Operations.Model = config.Provider, config.Model
}
if c.command == nil {
connection, err := opencode.Open(ctx, opencode.Executable(), c.Directory, c.Backend)
if err != nil {
+118
View File
@@ -0,0 +1,118 @@
package stage
import (
"encoding/json"
"regexp"
"strings"
"time"
)
// Failure evidence is bounded and credential-redacted; request bodies (which
// contain prompts) and the subprocess environment are never recorded here.
type OperationEvidence struct {
Operation string `json:"operation"`
Backend string `json:"backend"`
Executable string `json:"executable"`
Directory string `json:"directory"`
Provider string `json:"provider"`
Model string `json:"model"`
StartedAt string `json:"started_at"`
DurationMS int64 `json:"duration_ms"`
ExitCode int `json:"exit_code"`
HTTPStatus int `json:"http_status,omitempty"`
Diagnostic string `json:"diagnostic"`
Stdout string `json:"stdout,omitempty"`
Stderr string `json:"stderr,omitempty"`
}
type OperationLog struct {
Provider, Model string
Failures []OperationEvidence
}
var sensitiveKey = regexp.MustCompile(`(?i)^(authorization|password|secret|api[-_]?key|access[-_]?token|refresh[-_]?token|token|cookie|set-cookie|client[-_]?secret)$`)
var credentialText = regexp.MustCompile(`(?i)(bearer\s+)[^\s"'<>]+|\b(?:sk-[a-zA-Z0-9_-]+|tk_[a-zA-Z0-9]{29})\b|((?:api[-_]?key|access[-_]?token|refresh[-_]?token|password|client[-_]?secret|authorization|token)\s*[=:]\s*["']?)[^\s"'&,<>]+`)
var authorizationLine = regexp.MustCompile(`(?im)(authorization\s*[:=]\s*)[^\r\n]+`)
var credentialURL = regexp.MustCompile(`(https?://)[^/\s:@]+:[^/\s@]+@`)
func RedactEvidence(text string) string {
var data any
if json.Unmarshal([]byte(text), &data) == nil {
var clean func(any)
clean = func(v any) {
switch x := v.(type) {
case map[string]any:
for k, v := range x {
if sensitiveKey.MatchString(k) {
x[k] = "[REDACTED]"
} else {
clean(v)
}
}
case []any:
for _, v := range x {
clean(v)
}
}
}
clean(data)
encoded, _ := json.Marshal(data)
text = string(encoded)
}
text = credentialURL.ReplaceAllString(text, "${1}[REDACTED]@")
if !json.Valid([]byte(text)) {
text = authorizationLine.ReplaceAllString(text, "${1}[REDACTED]")
}
text = credentialText.ReplaceAllStringFunc(text, func(match string) string {
parts := credentialText.FindStringSubmatch(match)
if parts[1] != "" {
return parts[1] + "[REDACTED]"
}
if parts[2] != "" {
return parts[2] + "[REDACTED]"
}
return "[REDACTED]"
})
// Keep terminal control sequences out of diagnostic presentations.
text = strings.Map(func(r rune) rune {
if r < 32 && r != '\n' && r != '\t' {
return -1
}
return r
}, text)
if len(text) > 16<<10 {
text = text[:16<<10] + "\n[truncated]"
}
return text
}
func (l *OperationLog) record(e OperationEvidence, started time.Time) {
if l == nil {
return
}
e.Provider, e.Model = l.Provider, l.Model
e.StartedAt = started.UTC().Format(time.RFC3339Nano)
e.DurationMS = time.Since(started).Milliseconds()
e.Diagnostic = RedactEvidence(e.Diagnostic)
e.Stdout = RedactEvidence(e.Stdout)
e.Stderr = RedactEvidence(e.Stderr)
if len(l.Failures) < 32 {
l.Failures = append(l.Failures, e)
}
}
func (l *OperationLog) Transcript(original string) string {
if l == nil || len(l.Failures) == 0 {
return original
}
var data map[string]any
if json.Unmarshal([]byte(original), &data) != nil || data == nil {
data = map[string]any{}
if original != "" {
data["original_transcript"] = original
}
}
data["opencode_failures"] = l.Failures
encoded, _ := json.Marshal(data)
return string(encoded)
}
+51
View File
@@ -0,0 +1,51 @@
package stage
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func TestFailedCommandRetainsBoundedRedactedEvidence(t *testing.T) {
path := filepath.Join(t.TempDir(), "opencode")
script := `#!/bin/sh
echo '{"_tag":"UnauthorizedError","message":"provider quota exhausted","apiKey":"private-key"}'
echo 'HTTP 401 Unauthorized; Authorization: Bearer private-token' >&2
exit 7
`
if err := os.WriteFile(path, []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_OPENCODE", path)
log := &OperationLog{Provider: "fixture", Model: "model"}
_, err := (OpenCodeClient{Directory: t.TempDir(), Backend: "v2", Operations: log}).call(context.Background(), "post", "/api/experimental/session/ses_test/wait", nil)
if err == nil || len(log.Failures) != 1 {
t.Fatal(err, log)
}
e := log.Failures[0]
if e.ExitCode != 7 || e.HTTPStatus != 401 || e.Provider != "fixture" || e.Model != "model" || e.Executable != path || e.StartedAt == "" {
t.Fatal(e)
}
transcript := log.Transcript(`{"messages":["retained"]}`)
if !strings.Contains(transcript, "provider quota exhausted") || !strings.Contains(transcript, "retained") || strings.Contains(transcript, "private-key") || strings.Contains(transcript, "private-token") {
t.Fatal(transcript)
}
var data map[string]any
if json.Unmarshal([]byte(transcript), &data) != nil {
t.Fatal(transcript)
}
}
func TestEvidenceRedactionAndLimit(t *testing.T) {
for _, input := range []string{`{"nested":{"access_token":"private-value","password":"private-value"}}`, "Authorization: Basic private-value\n", "https://user:private-value@example.test/path?token=private-value", "api_key=private-value"} {
if output := RedactEvidence(input); strings.Contains(output, "private-value") {
t.Fatal(output)
}
}
if output := RedactEvidence(strings.Repeat("x", 32000)); len(output) > 16500 || !strings.Contains(output, "truncated") {
t.Fatal(len(output))
}
}
+45
View File
@@ -0,0 +1,45 @@
package stage
import (
"context"
"encoding/json"
"fmt"
"git.a-wan.net/alan/pipelines/internal/opencode"
)
// SessionEvidence only reads retained data on the execution computer. Never
// generate, resume, wait, interrupt or delete while investigating a session.
func (c OpenCodeClient) SessionEvidence(ctx context.Context, id string) (string, error) {
if !sessionIDPattern.MatchString(id) {
return "", fmt.Errorf("invalid session ID")
}
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
var session, messages, log []byte
logDiagnostic := ""
if c.Backend == "v1" {
session, err = connection.Native(ctx, "get", "/session/"+id, nil)
if err == nil {
messages, err = connection.Native(ctx, "get", "/session/"+id+"/message", nil)
}
} else {
session, err = c.call(ctx, "get", "/api/session/"+id, nil)
if err == nil {
messages, err = c.call(ctx, "get", "/api/session/"+id+"/message?order=desc&limit=20", nil)
}
if err == nil {
var logErr error
log, logErr = c.call(ctx, "get", "/api/experimental/session/"+id+"/log?follow=false", nil)
if logErr != nil {
logDiagnostic = RedactEvidence(logErr.Error())
}
}
}
data, _ := json.Marshal(map[string]string{"session": RedactEvidence(string(session)), "messages": RedactEvidence(string(messages)), "log": RedactEvidence(string(log)), "log_diagnostic": logDiagnostic})
return string(data), err
}
+10 -5
View File
@@ -3,6 +3,7 @@ package stage
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
"time"
@@ -12,6 +13,13 @@ const ModelType = "model"
const ModelID = "deepseek-v4.1-flash"
var providerID = regexp.MustCompile(`^[A-Za-z0-9_.-]+$`)
var modelID = regexp.MustCompile(`^[A-Za-z0-9_./:-]+$`)
func ValidModel(provider, model string) bool {
return len(provider) <= 200 && len(model) <= 300 && providerID.MatchString(provider) && modelID.MatchString(model)
}
// ModelConfig and ModelSpec group the settings/contracts that belong specifically
// to an LLM stage. Other stage types need not have a prompt, provider, or model.
type ModelConfig struct {
@@ -77,11 +85,8 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
return ModelSpec{}, fmt.Errorf("unknown config %q", key)
}
}
if provider := def.Configs["provider"]; provider != "opencode-go" {
return ModelSpec{}, fmt.Errorf("unsupported provider %q", provider)
}
if model := def.Configs["model"]; model != ModelID {
return ModelSpec{}, fmt.Errorf("unsupported model %q", model)
if !ValidModel(def.Configs["provider"], def.Configs["model"]) {
return ModelSpec{}, fmt.Errorf("invalid provider/model identifier; use the exact IDs validated during setup")
}
retries, err := strconv.Atoi(def.Configs["retries"])
if err != nil || retries < 0 || retries > 100 {
+1 -1
View File
@@ -81,7 +81,7 @@ func TestModelSpecAndValidation(t *testing.T) {
})
}
for _, test := range []struct{ key, value string }{
{"provider", "unknown"}, {"model", "unknown"}, {"retries", "-1"}, {"retries", "101"}, {"retries", "1.5"}, {"retries", "invalid"}, {"timeout", "1"},
{"provider", "not valid"}, {"model", "not valid"}, {"retries", "-1"}, {"retries", "101"}, {"retries", "1.5"}, {"retries", "invalid"}, {"timeout", "1"},
} {
t.Run(test.key+"="+test.value, func(t *testing.T) {
def := modelDefinition()
+16 -4
View File
@@ -27,6 +27,7 @@ type OpenCodeClient struct {
Backend string
Reference string
FormatAudit string
Operations *OperationLog
OnGenerationSession func(id, backend, reference string, active bool) error
connection *opencode.Connection
command func(context.Context, string, ...string) ([]byte, error)
@@ -60,12 +61,14 @@ 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" {
started := time.Now()
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])
}
c.Operations.record(OperationEvidence{Operation: method + " " + path, Backend: c.Backend, Executable: opencode.Executable(), Directory: c.Directory, ExitCode: -1, HTTPStatus: status, Diagnostic: err.Error(), Stdout: string(data)}, started)
if ctx.Err() != nil {
return nil, ctx.Err()
}
@@ -101,14 +104,20 @@ func (c OpenCodeClient) call(ctx context.Context, method, path string, body any)
stderr := &boundedBuffer{limit: 8 << 10}
cmd.Stdout = stdout
cmd.Stderr = stderr
started := time.Now()
if err := cmd.Run(); err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
status := 0
status, code := 0, -1
if match := httpStatusPattern.FindStringSubmatch(stderr.String()); len(match) > 0 {
status, _ = strconv.Atoi(match[1])
}
var exit *exec.ExitError
if errors.As(err, &exit) {
code = exit.ExitCode()
}
c.Operations.record(OperationEvidence{Operation: method + " " + path, Backend: c.Backend, Executable: cmd.Path, Directory: directory, ExitCode: code, HTTPStatus: status, Diagnostic: safeCommandDiagnostic(err, stdout.Bytes()), Stdout: stdout.String(), Stderr: stderr.String()}, started)
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Do not embed provider responses, prompts, credentials, or CLI logs in errors.
return nil, &openCodeError{operation: method + " " + path, status: status, diagnostic: safeCommandDiagnostic(err, stdout.Bytes())}
}
@@ -138,6 +147,9 @@ func safeCommandDiagnostic(err error, data []byte) string {
}
func (c OpenCodeClient) Generate(ctx context.Context, config ModelConfig, prompt string) (text string, err error) {
if c.Operations != nil {
c.Operations.Provider, c.Operations.Model = config.Provider, config.Model
}
if c.command == nil {
connection, err := opencode.Open(ctx, opencode.Executable(), c.Directory, c.Backend)
if err != nil {