harness: LiteLLM client, Redmine intake, REPORT writeback, gated bash tool
OpenAI-compatible chat client for the LiteLLM proxy (base_url normalization,
Bearer auth, retry/backoff on 429/5xx/transport, usage accounting) - stdlib
http only. Intake lists issues in scope from /issues.json with the task
class read from a configurable custom field. Writeback lands each turn as
REPORT-<vertical>-<task>-<ts>.md plus REPORT-latest.md (atomic rename) with
model/tier/token telemetry. The bash tool ports maki's permission semantics
without tree-sitter: segment-by-segment compound-command checks, deny beats
allow, word-boundary "cmd *" matching, $()/backtick/subshell denied, output
truncation, per-command timeout with process-group cleanup.
💘 Generated with Crush
Assisted-by: Crush:glm-5.2
This commit is contained in:
@@ -0,0 +1,263 @@
|
||||
// Package tools implements the harness tool palette. v0 ships bash: an
|
||||
// allow-listed executor whose gate ports maki's permission semantics
|
||||
// (segment-by-segment command matching, deny beats allow, subshells and
|
||||
// command substitution denied outright in headless mode) without the
|
||||
// tree-sitter dependency; the full parse lands with the permission layer.
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.knownelement.com/reachableceo/MOPAC/harness/internal/llm"
|
||||
)
|
||||
|
||||
// ErrDenied marks gate rejections; the conductor surfaces them to the model
|
||||
// as tool results and counts them, they do not fail the turn.
|
||||
var ErrDenied = errors.New("bash: denied by permission gate")
|
||||
|
||||
// BashOptions configures the bash tool.
|
||||
type BashOptions struct {
|
||||
WorkRoot string
|
||||
Allow []string
|
||||
Deny []string
|
||||
DefaultAllow bool
|
||||
Timeout time.Duration
|
||||
MaxOutputBytes int
|
||||
}
|
||||
|
||||
// BashTool is the allow-listed bash executor.
|
||||
type BashTool struct {
|
||||
opts BashOptions
|
||||
}
|
||||
|
||||
// NewBashTool validates options and prepares the work root.
|
||||
func NewBashTool(opts BashOptions) (*BashTool, error) {
|
||||
if opts.WorkRoot == "" {
|
||||
opts.WorkRoot = "."
|
||||
}
|
||||
abs, err := filepath.Abs(opts.WorkRoot)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bash tool: %w", err)
|
||||
}
|
||||
if err := os.MkdirAll(abs, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("bash tool: %w", err)
|
||||
}
|
||||
opts.WorkRoot = abs
|
||||
if opts.Timeout <= 0 {
|
||||
opts.Timeout = 60 * time.Second
|
||||
}
|
||||
if opts.MaxOutputBytes <= 0 {
|
||||
opts.MaxOutputBytes = 100_000
|
||||
}
|
||||
return &BashTool{opts: opts}, nil
|
||||
}
|
||||
|
||||
// Definition returns the OpenAI function tool schema advertised to the model.
|
||||
func (b *BashTool) Definition() llm.Tool {
|
||||
return llm.Tool{
|
||||
Type: "function",
|
||||
Function: llm.ToolDefinition{
|
||||
Name: "bash",
|
||||
Description: "Run a bash command from the task work root. Compound commands (&&, ||, ;, |) are checked segment by segment against an allow-list; command substitution, backticks, and subshells are always denied. Unmatched or denied commands fail.",
|
||||
Parameters: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"command": map[string]any{
|
||||
"type": "string",
|
||||
"description": "The bash command to run.",
|
||||
},
|
||||
},
|
||||
"required": []string{"command"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Check returns nil when the command passes the gate.
|
||||
func (b *BashTool) Check(command string) error {
|
||||
if strings.TrimSpace(command) == "" {
|
||||
return fmt.Errorf("%w: empty command", ErrDenied)
|
||||
}
|
||||
if hasComplexConstruct(command) {
|
||||
return fmt.Errorf("%w: %q uses command substitution/subshell constructs, which are not decomposable", ErrDenied, command)
|
||||
}
|
||||
scopes := SplitCommand(command)
|
||||
if len(scopes) == 0 {
|
||||
return fmt.Errorf("%w: empty command", ErrDenied)
|
||||
}
|
||||
for _, s := range scopes {
|
||||
if p := matchAny(b.opts.Deny, s); p != "" {
|
||||
return fmt.Errorf("%w: segment %q matches deny rule %q", ErrDenied, s, p)
|
||||
}
|
||||
}
|
||||
for _, s := range scopes {
|
||||
if matchAny(b.opts.Allow, s) == "" && !b.opts.DefaultAllow {
|
||||
return fmt.Errorf("%w: segment %q not covered by any allow rule (default deny)", ErrDenied, s)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Run gate-checks and executes one bash tool call. On success (and on
|
||||
// non-zero exit) it returns the captured output; err is non-nil for gate
|
||||
// rejections (ErrDenied), timeouts, and spawn failures.
|
||||
func (b *BashTool) Run(ctx context.Context, args json.RawMessage) (string, error) {
|
||||
var in struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
if len(args) == 0 {
|
||||
return "", fmt.Errorf("bash: missing arguments")
|
||||
}
|
||||
if err := json.Unmarshal(args, &in); err != nil {
|
||||
return "", fmt.Errorf("bash: bad arguments: %w", err)
|
||||
}
|
||||
if err := b.Check(in.Command); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, b.opts.Timeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(cctx, "bash", "-c", in.Command)
|
||||
cmd.Dir = b.opts.WorkRoot
|
||||
setPgroup(cmd)
|
||||
out, err := cmd.CombinedOutput()
|
||||
killGroup(cmd) // reap any grandchildren the direct kill missed
|
||||
res := b.truncate(out)
|
||||
if cctx.Err() == context.DeadlineExceeded {
|
||||
return res, fmt.Errorf("bash: timed out after %s", b.opts.Timeout)
|
||||
}
|
||||
if err != nil {
|
||||
return res, fmt.Errorf("bash: %w", err)
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (b *BashTool) truncate(out []byte) string {
|
||||
if len(out) <= b.opts.MaxOutputBytes {
|
||||
return string(out)
|
||||
}
|
||||
cut := b.opts.MaxOutputBytes
|
||||
for cut > 0 && !utf8.RuneStart(out[cut]) {
|
||||
cut--
|
||||
}
|
||||
return string(out[:cut]) + fmt.Sprintf("\n...[truncated %d bytes]", len(out)-cut)
|
||||
}
|
||||
|
||||
// hasComplexConstruct reports constructs the text-level decomposer cannot
|
||||
// safely split: command/process substitution, backticks, subshells. In
|
||||
// headless mode these deny (maki: force_prompt with no channel => deny).
|
||||
func hasComplexConstruct(cmd string) bool {
|
||||
return strings.Contains(cmd, "$(") ||
|
||||
strings.Contains(cmd, "`") ||
|
||||
strings.Contains(cmd, "<(") ||
|
||||
strings.Contains(cmd, ">(") ||
|
||||
strings.HasPrefix(strings.TrimSpace(cmd), "(")
|
||||
}
|
||||
|
||||
// SplitCommand decomposes a compound command into its segment scopes by
|
||||
// splitting on &&, ||, ;, | and newlines outside quotes. Redirections stay
|
||||
// part of their segment (they must be explicitly allowed by text).
|
||||
func SplitCommand(cmd string) []string {
|
||||
var out []string
|
||||
var cur strings.Builder
|
||||
inSingle, inDouble := false, false
|
||||
runes := []rune(cmd)
|
||||
flush := func() {
|
||||
if s := strings.TrimSpace(cur.String()); s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
cur.Reset()
|
||||
}
|
||||
for i := 0; i < len(runes); i++ {
|
||||
r := runes[i]
|
||||
switch {
|
||||
case inSingle:
|
||||
if r == '\'' {
|
||||
inSingle = false
|
||||
}
|
||||
cur.WriteRune(r)
|
||||
case inDouble:
|
||||
if r == '\\' && i+1 < len(runes) {
|
||||
cur.WriteRune(r)
|
||||
i++
|
||||
cur.WriteRune(runes[i])
|
||||
continue
|
||||
}
|
||||
if r == '"' {
|
||||
inDouble = false
|
||||
}
|
||||
cur.WriteRune(r)
|
||||
case r == '\'':
|
||||
inSingle = true
|
||||
cur.WriteRune(r)
|
||||
case r == '"':
|
||||
inDouble = true
|
||||
cur.WriteRune(r)
|
||||
case (r == '&' || r == '|') && i+1 < len(runes) && runes[i+1] == r:
|
||||
flush()
|
||||
i++
|
||||
case r == ';' || r == '|' || r == '\n':
|
||||
flush()
|
||||
default:
|
||||
cur.WriteRune(r)
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return out
|
||||
}
|
||||
|
||||
// matchAny returns the first pattern in list that matches scope, or "".
|
||||
func matchAny(list []string, scope string) string {
|
||||
for _, p := range list {
|
||||
if ScopeMatches(p, scope) {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ScopeMatches ports maki's scope matcher. Order matters: universal
|
||||
// wildcards, then "/**" path prefixes, then " *" word-boundary command
|
||||
// prefixes, then bare "*" raw prefixes, then exact match.
|
||||
func ScopeMatches(pattern, scope string) bool {
|
||||
switch {
|
||||
case pattern == "*" || pattern == "/**" || pattern == "/*":
|
||||
return true
|
||||
case strings.HasSuffix(pattern, "/**"):
|
||||
return hasPathPrefix(scope, strings.TrimSuffix(pattern, "/**"))
|
||||
case strings.HasSuffix(pattern, " *"):
|
||||
head := strings.TrimSuffix(pattern, " *")
|
||||
return scope == head || strings.HasPrefix(scope, head+" ")
|
||||
case strings.HasSuffix(pattern, "*"):
|
||||
return strings.HasPrefix(scope, strings.TrimSuffix(pattern, "*"))
|
||||
default:
|
||||
return pattern == scope
|
||||
}
|
||||
}
|
||||
|
||||
// hasPathPrefix reports whether scope names a path inside dir. v0 is lexical
|
||||
// (Clean + Abs); symlink-aware canonicalization lands with the permission
|
||||
// layer, as does write-root confinement.
|
||||
func hasPathPrefix(scope, dir string) bool {
|
||||
absScope, err := filepath.Abs(filepath.Clean(scope))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
absDir, err := filepath.Abs(filepath.Clean(dir))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if absScope == absDir {
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(absScope, absDir+string(filepath.Separator))
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestScopeMatches(t *testing.T) {
|
||||
cases := []struct {
|
||||
pattern string
|
||||
scope string
|
||||
want bool
|
||||
}{
|
||||
// "cmd *" word-boundary prefix (maki semantics).
|
||||
{"pwd *", "pwd", true},
|
||||
{"pwd *", "pwd -L", true},
|
||||
{"pwd *", "pwdx", false},
|
||||
{"pwd *", "pwd secret", true},
|
||||
{"git diff *", "git diff", true},
|
||||
{"git diff *", "git diff HEAD~1", true},
|
||||
{"git diff *", "git difftool", false},
|
||||
// Universal wildcards.
|
||||
{"*", "anything at all", true},
|
||||
{"**", "anything", false}, // not a universal form; exact match
|
||||
// Bare "*" raw prefix.
|
||||
{"pfx*", "pfxthing", true},
|
||||
{"pfx*", "pfz", false},
|
||||
// Exact.
|
||||
{"go version", "go version", true},
|
||||
{"go version", "go version -m", false},
|
||||
// Path prefix.
|
||||
{"/tmp/work/**", "/tmp/work", true},
|
||||
{"/tmp/work/**", "/tmp/work/sub/f", true},
|
||||
{"/tmp/work/**", "/tmp/workx/f", false},
|
||||
{"/tmp/work/**", "/tmp/other", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := ScopeMatches(tc.pattern, tc.scope); got != tc.want {
|
||||
t.Errorf("ScopeMatches(%q, %q) = %v, want %v", tc.pattern, tc.scope, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitCommand(t *testing.T) {
|
||||
cases := []struct {
|
||||
cmd string
|
||||
want []string
|
||||
}{
|
||||
{"ls -la", []string{"ls -la"}},
|
||||
{"git diff && rm -rf /", []string{"git diff", "rm -rf /"}},
|
||||
{"a || b ; c", []string{"a", "b", "c"}},
|
||||
{"cat f | grep x", []string{"cat f", "grep x"}},
|
||||
{`echo "a && b"`, []string{`echo "a && b"`}},
|
||||
{`echo 'p | q'`, []string{`echo 'p | q'`}},
|
||||
{" ", nil},
|
||||
{"echo hi > out.txt", []string{"echo hi > out.txt"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := SplitCommand(tc.cmd)
|
||||
if len(got) != len(tc.want) {
|
||||
t.Errorf("SplitCommand(%q) = %v, want %v", tc.cmd, got, tc.want)
|
||||
continue
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != tc.want[i] {
|
||||
t.Errorf("SplitCommand(%q)[%d] = %q, want %q", tc.cmd, i, got[i], tc.want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newTool(t *testing.T, allow, deny []string) *BashTool {
|
||||
t.Helper()
|
||||
b, err := NewBashTool(BashOptions{
|
||||
WorkRoot: t.TempDir(),
|
||||
Allow: allow,
|
||||
Deny: deny,
|
||||
Timeout: 5 * time.Second,
|
||||
MaxOutputBytes: 100_000,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func TestCheckGate(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
allow []string
|
||||
deny []string
|
||||
cmd string
|
||||
ok bool
|
||||
want string // substring of denial reason when !ok
|
||||
}{
|
||||
{"simple allow", []string{"echo *"}, nil, "echo hi", true, ""},
|
||||
{"exact allow", []string{"pwd"}, nil, "pwd", true, ""},
|
||||
{"uncovered", []string{"echo *"}, nil, "ls -la", false, "not covered by any allow rule"},
|
||||
{"compound all allowed", []string{"git *"}, nil, "git diff && git status", true, ""},
|
||||
{"compound one bad", []string{"git *"}, nil, "git diff && rm -rf /", false, `segment "rm -rf /"`},
|
||||
{"deny beats allow", []string{"*"}, []string{"sudo *"}, "sudo id", false, `matches deny rule "sudo *"`},
|
||||
{"deny beats allow compound", []string{"*"}, []string{"rm -rf *"}, "git status && rm -rf /", false, "deny rule"},
|
||||
{"pipe splits", []string{"cat *", "grep *"}, nil, "cat f | grep x", true, ""},
|
||||
{"pipe uncovered", []string{"cat *"}, nil, "cat f | grep x", false, `segment "grep x"`},
|
||||
{"command substitution denied", []string{"*"}, nil, "echo $(rm -rf /)", false, "not decomposable"},
|
||||
{"backticks denied", []string{"*"}, nil, "echo `id`", false, "not decomposable"},
|
||||
{"subshell denied", []string{"*"}, nil, "(cd / && rm -rf /)", false, "not decomposable"},
|
||||
{"empty", []string{"*"}, nil, " ", false, "empty command"},
|
||||
{"word boundary", []string{"pwd *"}, nil, "pwdx", false, "not covered"},
|
||||
{"redirect is part of scope", []string{"go *"}, nil, "go test > /tmp/out", true, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
b := newTool(t, tc.allow, tc.deny)
|
||||
err := b.Check(tc.cmd)
|
||||
if tc.ok {
|
||||
if err != nil {
|
||||
t.Fatalf("Check(%q) = %v, want nil", tc.cmd, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, ErrDenied) {
|
||||
t.Fatalf("Check(%q) = %v, want ErrDenied", tc.cmd, err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("denial %q does not contain %q", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultAllow(t *testing.T) {
|
||||
b, err := NewBashTool(BashOptions{
|
||||
WorkRoot: t.TempDir(),
|
||||
Allow: nil,
|
||||
DefaultAllow: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := b.Check("anything --at --all"); err != nil {
|
||||
t.Errorf("default allow should pass uncovered scopes: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun(t *testing.T) {
|
||||
t.Run("allowed echo", func(t *testing.T) {
|
||||
b := newTool(t, []string{"echo *"}, nil)
|
||||
out, err := b.Run(context.Background(), json.RawMessage(`{"command":"echo hello mopac"}`))
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if !strings.Contains(out, "hello mopac") {
|
||||
t.Errorf("output = %q", out)
|
||||
}
|
||||
})
|
||||
t.Run("denied returns ErrDenied without executing", func(t *testing.T) {
|
||||
b := newTool(t, []string{"echo *"}, []string{"sudo *"})
|
||||
out, err := b.Run(context.Background(), json.RawMessage(`{"command":"sudo rm -rf /"}`))
|
||||
if !errors.Is(err, ErrDenied) {
|
||||
t.Fatalf("err = %v, want ErrDenied", err)
|
||||
}
|
||||
if out != "" {
|
||||
t.Errorf("denied run must not produce output, got %q", out)
|
||||
}
|
||||
})
|
||||
t.Run("nonzero exit reports output", func(t *testing.T) {
|
||||
b := newTool(t, []string{"false"}, nil)
|
||||
out, err := b.Run(context.Background(), json.RawMessage(`{"command":"false"}`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for exit 1")
|
||||
}
|
||||
if out != "" {
|
||||
t.Errorf("no output expected, got %q", out)
|
||||
}
|
||||
})
|
||||
t.Run("timeout kills command", func(t *testing.T) {
|
||||
b, err := NewBashTool(BashOptions{
|
||||
WorkRoot: t.TempDir(),
|
||||
Allow: []string{"sleep *"},
|
||||
Timeout: 300 * time.Millisecond,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start := time.Now()
|
||||
_, err = b.Run(context.Background(), json.RawMessage(`{"command":"sleep 30"}`))
|
||||
if err == nil || !strings.Contains(err.Error(), "timed out") {
|
||||
t.Fatalf("err = %v, want timeout", err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 5*time.Second {
|
||||
t.Fatalf("timeout did not fire, took %s", elapsed)
|
||||
}
|
||||
})
|
||||
t.Run("output truncation", func(t *testing.T) {
|
||||
b, err := NewBashTool(BashOptions{
|
||||
WorkRoot: t.TempDir(),
|
||||
Allow: []string{"echo *"},
|
||||
Timeout: 5 * time.Second,
|
||||
MaxOutputBytes: 100,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := b.Run(context.Background(), json.RawMessage(`{"command":"echo 012345678901234567890123456789012345678901456789012345678901234567890123456789012345678901234567890123456789"}`))
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if !strings.Contains(out, "[truncated") {
|
||||
t.Errorf("expected truncation marker in %q", out)
|
||||
}
|
||||
if len(out) > 200 {
|
||||
t.Errorf("output not truncated: %d bytes", len(out))
|
||||
}
|
||||
})
|
||||
t.Run("bad json args", func(t *testing.T) {
|
||||
b := newTool(t, []string{"echo *"}, nil)
|
||||
if _, err := b.Run(context.Background(), json.RawMessage(`{"command": 42}`)); err == nil {
|
||||
t.Fatal("expected arg error")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDefinitionSchema(t *testing.T) {
|
||||
b := newTool(t, nil, nil)
|
||||
def := b.Definition()
|
||||
if def.Function.Name != "bash" || def.Type != "function" {
|
||||
t.Errorf("definition = %+v", def)
|
||||
}
|
||||
if def.Function.Parameters["required"] == nil {
|
||||
t.Error("parameters must mark command required")
|
||||
}
|
||||
// Sanity: the schema must marshal (it goes straight into requests).
|
||||
if _, err := json.Marshal(def); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !unix
|
||||
|
||||
package tools
|
||||
|
||||
import "os/exec"
|
||||
|
||||
func setPgroup(c *exec.Cmd) {}
|
||||
|
||||
func killGroup(c *exec.Cmd) {}
|
||||
@@ -0,0 +1,24 @@
|
||||
//go:build unix
|
||||
|
||||
package tools
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// setPgroup puts the bash child in its own process group so a timeout or
|
||||
// cancel kills the whole tree, not just the shell (crush/maki gotcha:
|
||||
// plain Kill orphans grandchildren).
|
||||
func setPgroup(c *exec.Cmd) {
|
||||
c.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
}
|
||||
|
||||
// killGroup SIGKILLs the child's process group after Wait; no-op if the
|
||||
// child never started.
|
||||
func killGroup(c *exec.Cmd) {
|
||||
if c.Process == nil {
|
||||
return
|
||||
}
|
||||
_ = syscall.Kill(-c.Process.Pid, syscall.SIGKILL)
|
||||
}
|
||||
Reference in New Issue
Block a user