CyberStrikeAI/internal/multiagent/pi_local_tools.go

712 lines
20 KiB
Go

package multiagent
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"io/fs"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
"cyberstrike-ai/internal/agentruntime"
"cyberstrike-ai/internal/mcp"
"cyberstrike-ai/internal/security"
"cyberstrike-ai/internal/skillpackage"
"cyberstrike-ai/internal/tooloutput"
"github.com/disintegration/imaging"
_ "golang.org/x/image/webp"
)
// piLocalCatalog is explicit host registration: Pi never receives default host filesystem tools.
func (r *piRun) piLocalCatalog(ctx context.Context) ([]agentruntime.Tool, map[string]bool, error) {
var tools []agentruntime.Tool
names := map[string]bool{}
if r.cfg.MultiAgent.Skills.Disable {
return tools, names, nil
}
str := map[string]any{"type": "string"}
if r.cfg.MultiAgent.Runtime.PlantaskEnable && r.cfg.SkillsDir != "" {
for _, t := range piPlanTools() {
tools = append(tools, t)
names[t.Name] = true
}
}
options, _ := ctx.Value(piOptionsKey{}).(PiRunOptions)
if root := strings.TrimSpace(r.cfg.SkillsDir); root != "" && options.Native == nil {
skills, err := skillpackage.ListSkillSummaries(root)
if err != nil && !os.IsNotExist(err) {
return nil, nil, err
}
if len(skills) > 0 {
name := r.cfg.MultiAgent.Skills.SkillToolName
if name == "" {
name = "skill"
}
tools = append(tools, agentruntime.Tool{Name: name, Description: "Load the instructions and resource paths of an available skill", Parameters: piToolSchema(map[string]any{"name": str}, "name")})
names[name] = true
}
}
if r.cfg.MultiAgent.Skills.FilesystemToolsEffective() && !localToolPermissionDenied(ctx, "execute") {
for _, t := range []agentruntime.Tool{
{Name: "read_file", Description: "Read a text file with 1-based line offset/limit pagination, or return a supported image (png/jpeg/gif/webp) for vision models", Parameters: piToolSchema(map[string]any{"path": str, "offset": map[string]any{"type": "integer", "minimum": 1}, "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 2000}}, "path")},
{Name: "write_file", Description: "Write UTF-8 text to a file, creating parent directories as needed", Parameters: piToolSchema(map[string]any{"path": str, "content": str}, "path", "content")},
{Name: "edit_file", Description: "Replace exact text in a file; supports one old_text/new_text pair or a batch edits array, preserves CRLF, and returns a change summary", Parameters: piToolSchema(map[string]any{"path": str, "old_text": str, "new_text": str, "edits": map[string]any{"type": "array", "items": map[string]any{"type": "object", "properties": map[string]any{"old_text": str, "new_text": str}, "required": []string{"old_text", "new_text"}}}}, "path")},
{Name: "ls", Description: "List directory entries", Parameters: piToolSchema(map[string]any{"path": str}, "path")},
{Name: "glob", Description: "Find files recursively by glob; supports filename patterns and path patterns with ** and subdirectory wildcards", Parameters: piToolSchema(map[string]any{"path": str, "pattern": str}, "path", "pattern")},
{Name: "grep", Description: "Search UTF-8 files recursively with a regular expression; skips binary files and truncates long lines", Parameters: piToolSchema(map[string]any{"path": str, "pattern": str, "include": str}, "path", "pattern")},
{Name: "execute", Description: "Execute a shell command in the host task context with bounded output and process-tree cancellation", Parameters: piToolSchema(map[string]any{"command": str, "cwd": str}, "command")},
} {
tools = append(tools, t)
names[t.Name] = true
}
}
return tools, names, nil
}
type piBoundedOutput struct {
mu sync.Mutex
body strings.Builder
truncated bool
onChunk func(string)
spool io.Writer
spoolPath string
lastWrite atomic.Int64
}
func (b *piBoundedOutput) Write(p []byte) (int, error) {
b.lastWrite.Store(time.Now().UnixNano())
b.mu.Lock()
defer b.mu.Unlock()
if b.spool != nil {
if _, err := b.spool.Write(p); err != nil {
return 0, err
}
}
left := 256*1024 - b.body.Len()
if left > len(p) {
left = len(p)
}
if left > 0 {
b.body.Write(p[:left])
if b.onChunk != nil {
b.onChunk(string(p[:left]))
}
}
if left < len(p) {
b.truncated = true
}
return len(p), nil
}
func (b *piBoundedOutput) String() string {
b.mu.Lock()
defer b.mu.Unlock()
text := b.body.String()
if b.truncated {
text += "\n[Preview truncated at 256 KiB; full output: " + b.spoolPath + "]"
}
return text
}
func (r *piRun) executePiLocal(ctx context.Context, call agentruntime.ToolCall) (agentruntime.ToolResult, error) {
if call.Name == "TaskCreate" || call.Name == "TaskUpdate" || call.Name == "TaskGet" || call.Name == "TaskList" {
return r.executePiPlan(ctx, call)
}
arg := func(key string) string { v, _ := call.Arguments[key].(string); return v }
skillName := r.cfg.MultiAgent.Skills.SkillToolName
if skillName == "" {
skillName = "skill"
}
if call.Name == skillName {
name := arg("name")
skills, err := skillpackage.ListSkillSummaries(r.cfg.SkillsDir)
if err != nil {
return agentruntime.ToolResult{}, err
}
found := false
for _, s := range skills {
if s.ID == name {
found = true
break
}
}
if !found {
return agentruntime.ToolResult{}, fmt.Errorf("unknown skill: %s", name)
}
view, err := skillpackage.LoadSkill(r.cfg.SkillsDir, name, skillpackage.LoadOptions{Depth: "full"})
if err != nil {
return agentruntime.ToolResult{}, err
}
body, _ := json.Marshal(view)
return agentruntime.ToolResult{Content: string(body)}, nil
}
path := arg("path")
if path != "" {
var err error
path, err = filepath.Abs(path)
if err != nil {
return agentruntime.ToolResult{}, err
}
}
result := agentruntime.ToolResult{}
switch call.Name {
case "execute":
if arg("command") == "" {
return result, fmt.Errorf("command is required")
}
timeout := time.Duration(agentToolTimeoutMinutes(r.cfg)) * time.Minute
execCtx, cancel := context.WithCancel(ctx)
if timeout > 0 {
cancel()
execCtx, cancel = context.WithTimeout(ctx, timeout)
}
defer cancel()
registry := mcp.AgentExecuteRunRegistryFromContext(ctx)
if registry != nil {
registry.RegisterActiveAgentExecute(r.conversationID, cancel)
defer registry.UnregisterActiveAgentExecute(r.conversationID)
}
cmd := exec.CommandContext(execCtx, "/bin/sh", "-c", arg("command"))
cmd.Dir = arg("cwd")
security.ConfigureShellCmdForAgentExecute(cmd)
output := &piBoundedOutput{}
output.lastWrite.Store(time.Now().UnixNano())
idleSeconds := r.cfg.Agent.ShellNoOutputTimeoutSeconds
if idleSeconds == 0 {
idleSeconds = 300
}
idleDone := make(chan struct{})
defer close(idleDone)
var idleExpired atomic.Bool
if idleSeconds > 0 {
go func() {
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-idleDone:
return
case <-execCtx.Done():
return
case <-ticker.C:
if time.Since(time.Unix(0, output.lastWrite.Load())) >= time.Duration(idleSeconds)*time.Second {
idleExpired.Store(true)
cancel()
return
}
}
}
}()
}
spoolPath, err := tooloutput.WriteTruncFile(tooloutput.SpillOpts{RootDir: r.cfg.MultiAgent.Runtime.ReductionRootDir, ConversationID: r.conversationID}, "")
if err != nil {
return result, err
}
spool, err := os.OpenFile(spoolPath, os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
return result, err
}
defer spool.Close()
output.spool = spool
output.spoolPath = spoolPath
cmd.Stdout = output
cmd.Stderr = output
id := r.ag.BeginLocalToolExecution(ctx, call.Name, call.Arguments)
r.ag.RegisterLocalToolExecutionCancel(id, cancel)
defer r.ag.UnregisterLocalToolExecutionCancel(id)
output.onChunk = func(chunk string) { r.ag.AppendLocalToolExecutionPartialOutput(id, chunk) }
session, err := security.StartShellSessionContext(execCtx, cmd)
if err == nil {
err = session.Wait()
}
result.Content = output.String()
result.IsError = err != nil
result.ExecutionID = r.ag.FinishLocalToolExecution(ctx, id, call.Name, call.Arguments, result.Content, err)
if err != nil {
result.Content += "\n" + err.Error()
}
if idleExpired.Load() && err != nil {
result.Content += fmt.Sprintf("\nCommand stopped after %d seconds without stdout/stderr.", idleSeconds)
}
if registry != nil {
if note := registry.TakeAgentExecuteAbortNote(r.conversationID); note != "" {
result.Content += "\nTool stopped by the user. Follow-up instruction: " + note
}
}
return result, nil
case "read_file":
f, err := os.Open(path)
if err != nil {
return result, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return result, err
}
if !st.Mode().IsRegular() {
return result, fmt.Errorf("not a regular file")
}
if img, ok, err := readPiLocalImage(path, f, st.Size()); ok {
if err != nil {
return result, err
}
result = img
break
}
offset, limit := 1, 1000
if n, ok := call.Arguments["offset"].(float64); ok && n >= 1 {
offset = int(n)
}
if n, ok := call.Arguments["limit"].(float64); ok && n > 0 {
limit = int(n)
if limit > 2000 {
limit = 2000
}
}
reader := bufio.NewReaderSize(f, 64*1024)
var out strings.Builder
lineNo, emitted, budget := 0, 0, 64*1024
anyTrunc, hitBudget := false, false
for {
line, trunc, err := readPiCappedLine(reader, 4096)
if err == io.EOF {
break
}
if err != nil {
return result, err
}
lineNo++
if lineNo < offset || emitted >= limit || hitBudget {
continue
}
text := line
if trunc {
text += " [line truncated]"
anyTrunc = true
}
if out.Len()+len(text)+1 > budget {
hitBudget = true
continue
}
if emitted > 0 {
out.WriteByte('\n')
}
out.WriteString(text)
emitted++
}
if emitted == 0 {
return result, nil
}
if anyTrunc || hitBudget || offset+emitted-1 < lineNo {
out.WriteString(fmt.Sprintf("\n[lines %d-%d of %d; next offset %d]", offset, offset+emitted-1, lineNo, offset+emitted))
}
result.Content = out.String()
case "write_file", "edit_file":
unlock := lockPiFilePath(path)
defer unlock()
mode := os.FileMode(0o600)
if st, err := os.Stat(path); err == nil {
if !st.Mode().IsRegular() {
return result, fmt.Errorf("not a regular file")
}
mode = st.Mode().Perm()
}
var content string
if call.Name == "edit_file" {
updated, summary, err := applyPiFileEdits(path, call.Arguments)
if err != nil {
return result, err
}
content = updated
result.Content = summary
} else {
content = arg("content")
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return result, err
}
}
if err := os.WriteFile(path, []byte(content), mode); err != nil {
return result, err
}
if call.Name == "write_file" {
result.Content = "Updated " + path
}
case "ls":
entries, err := os.ReadDir(path)
if err != nil {
return result, err
}
var names []string
for _, e := range entries {
n := e.Name()
if e.IsDir() {
n += "/"
}
names = append(names, n)
}
result.Content = strings.Join(names, "\n")
case "glob", "grep":
pattern := arg("pattern")
var re *regexp.Regexp
if call.Name == "grep" {
var err error
re, err = regexp.Compile(pattern)
if err != nil {
return result, err
}
}
include := arg("include")
globPattern := strings.TrimPrefix(pattern, "./")
globByPath := strings.Contains(globPattern, "/")
var hits []string
err := filepath.WalkDir(path, func(p string, d fs.DirEntry, err error) error {
if ctx.Err() != nil {
return ctx.Err()
}
if err != nil {
return err
}
if len(hits) >= 1000 {
return fs.SkipAll
}
if d.IsDir() {
if d.Name() == ".git" || d.Name() == "node_modules" {
return fs.SkipDir
}
return nil
}
if d.Type()&os.ModeSymlink != 0 {
return nil
}
if call.Name == "glob" {
var matched bool
if globByPath {
rel, e := filepath.Rel(path, p)
if e != nil {
return e
}
matched = piGlobMatchPath(globPattern, filepath.ToSlash(rel))
} else {
var e error
matched, e = filepath.Match(globPattern, d.Name())
if e != nil {
return e
}
}
if matched {
hits = append(hits, p)
}
return nil
}
if include != "" {
ok, e := filepath.Match(include, d.Name())
if e != nil {
return e
}
if !ok {
return nil
}
}
st, e := d.Info()
if e != nil || !st.Mode().IsRegular() || st.Size() > 2*1024*1024 {
return nil
}
b, e := os.ReadFile(p)
if e != nil {
return e
}
if bytes.IndexByte(b[:min(512, len(b))], 0) >= 0 {
return nil
}
for i, line := range strings.Split(string(b), "\n") {
if re.MatchString(line) {
hits = append(hits, fmt.Sprintf("%s:%d:%s", p, i+1, truncatePiRunes(line, 500)))
if len(hits) >= 1000 {
break
}
}
}
return nil
})
if err != nil {
return result, err
}
result.Content = strings.Join(hits, "\n")
default:
return result, fmt.Errorf("unknown local tool")
}
result.ExecutionID = r.ag.FinishLocalToolExecution(ctx, "", call.Name, call.Arguments, result.Content, nil)
return result, nil
}
var piFileLocks sync.Map
func lockPiFilePath(path string) func() {
v, _ := piFileLocks.LoadOrStore(path, &sync.Mutex{})
mu := v.(*sync.Mutex)
mu.Lock()
return mu.Unlock
}
func readPiCappedLine(r *bufio.Reader, cap int) (string, bool, error) {
var parts []byte
trunc := false
sawData := false
for {
frag, isPrefix, err := r.ReadLine()
if len(frag) > 0 {
sawData = true
if !trunc {
room := cap - len(parts)
if len(frag) <= room {
parts = append(parts, frag...)
} else {
if room > 0 {
parts = append(parts, frag[:room]...)
}
trunc = true
}
}
}
if err != nil {
if err == io.EOF && sawData {
return string(parts), trunc, nil
}
return "", false, err
}
if !isPrefix {
return string(parts), trunc, nil
}
}
}
func readPiLocalImage(path string, f *os.File, size int64) (agentruntime.ToolResult, bool, error) {
header := make([]byte, 512)
n, _ := io.ReadFull(f, header)
mime := http.DetectContentType(header[:n])
if _, err := f.Seek(0, io.SeekStart); err != nil {
return agentruntime.ToolResult{}, false, err
}
switch mime {
case "image/png", "image/jpeg", "image/gif", "image/webp":
default:
return agentruntime.ToolResult{}, false, nil
}
if size > 10*1024*1024 {
return agentruntime.ToolResult{}, true, fmt.Errorf("image exceeds 10 MiB")
}
raw, err := io.ReadAll(io.LimitReader(f, 10*1024*1024+1))
if err != nil {
return agentruntime.ToolResult{}, true, err
}
// Polyglot payloads (e.g. GIF89a followed by PHP/text) sniff as image/*;
// verify full image decoding and fall back to text when there are no NUL bytes.
decoded, _, decErr := image.Decode(bytes.NewReader(raw))
if decErr != nil {
if bytes.IndexByte(raw, 0) < 0 {
if _, seekErr := f.Seek(0, io.SeekStart); seekErr != nil {
return agentruntime.ToolResult{}, true, seekErr
}
return agentruntime.ToolResult{}, false, nil
}
return agentruntime.ToolResult{}, true, fmt.Errorf("decode image: %w", decErr)
}
bounds := decoded.Bounds()
out, outMIME := raw, mime
if len(raw) > 4*1024*1024 || bounds.Dx() > 4096 || bounds.Dy() > 4096 {
compressed, err := compressPiDecodedImage(decoded)
if err != nil {
return agentruntime.ToolResult{}, true, err
}
out, outMIME = compressed, "image/jpeg"
}
return agentruntime.ToolResult{
Content: fmt.Sprintf("[Image %s (%s, %d bytes)]", path, outMIME, len(out)),
Images: []agentruntime.Image{{MIMEType: outMIME, Data: out}},
}, true, nil
}
func compressPiDecodedImage(src image.Image) ([]byte, error) {
dim := 2048
dst := imaging.Fit(src, dim, dim, imaging.Lanczos)
for attempt := 0; attempt < 6; attempt++ {
if attempt > 0 {
dim = int(float64(dim) * 0.85)
if dim < 256 {
dim = 256
}
dst = imaging.Fit(src, dim, dim, imaging.Lanczos)
}
for q := 85; q >= 55; q -= 10 {
var buf bytes.Buffer
if err := imaging.Encode(&buf, dst, imaging.JPEG, imaging.JPEGQuality(q)); err != nil {
return nil, err
}
if buf.Len() <= 4*1024*1024 {
return buf.Bytes(), nil
}
}
}
return nil, fmt.Errorf("could not compress image under 4 MiB")
}
func applyPiFileEdits(path string, args map[string]any) (string, string, error) {
b, err := os.ReadFile(path)
if err != nil {
return "", "", err
}
orig := string(b)
crlf := strings.Contains(orig, "\r\n")
norm := strings.ReplaceAll(orig, "\r\n", "\n")
type piEdit struct{ old, new string }
var edits []piEdit
if raw, ok := args["edits"].([]any); ok && len(raw) > 0 {
for _, item := range raw {
m, ok := item.(map[string]any)
if !ok {
return "", "", fmt.Errorf("edits entries must be objects")
}
o, _ := m["old_text"].(string)
n, _ := m["new_text"].(string)
edits = append(edits, piEdit{o, n})
}
} else {
o, _ := args["old_text"].(string)
n, _ := args["new_text"].(string)
edits = append(edits, piEdit{o, n})
}
current := norm
for _, e := range edits {
oldNorm := strings.ReplaceAll(e.old, "\r\n", "\n")
newNorm := strings.ReplaceAll(e.new, "\r\n", "\n")
if oldNorm == "" {
return "", "", fmt.Errorf("old_text must not be empty")
}
current, err = replacePiUnique(current, oldNorm, newNorm)
if err != nil {
return "", "", err
}
}
final := current
if crlf {
final = strings.ReplaceAll(current, "\n", "\r\n")
}
return final, piEditSummary(path, norm, current), nil
}
func replacePiUnique(content, old, new string) (string, error) {
if strings.Count(content, old) == 1 {
return strings.Replace(content, old, new, 1), nil
}
lines := strings.Split(old, "\n")
parts := make([]string, len(lines))
for i, l := range lines {
parts[i] = regexp.QuoteMeta(strings.TrimRight(l, " \t"))
}
re, err := regexp.Compile(strings.Join(parts, "[ \t]*\n") + "[ \t]*")
if err != nil {
return "", err
}
locs := re.FindAllStringIndex(content, -1)
if len(locs) != 1 {
return "", fmt.Errorf("old_text must match exactly once (found %d)", len(locs))
}
loc := locs[0]
return content[:loc[0]] + new + content[loc[1]:], nil
}
func piEditSummary(path, oldNorm, newNorm string) string {
if oldNorm == newNorm {
return "Updated " + path + " (no line changes)"
}
oldLines := strings.Split(oldNorm, "\n")
newLines := strings.Split(newNorm, "\n")
prefix := 0
for prefix < len(oldLines) && prefix < len(newLines) && oldLines[prefix] == newLines[prefix] {
prefix++
}
suffix := 0
for suffix < len(oldLines)-prefix && suffix < len(newLines)-prefix && oldLines[len(oldLines)-1-suffix] == newLines[len(newLines)-1-suffix] {
suffix++
}
var b strings.Builder
fmt.Fprintf(&b, "Updated %s (first changed line %d)\n", path, prefix+1)
ctxStart := prefix - 2
if ctxStart < 0 {
ctxStart = 0
}
for i := ctxStart; i < prefix; i++ {
b.WriteString(" " + oldLines[i] + "\n")
}
oldMid := oldLines[prefix : len(oldLines)-suffix]
newMid := newLines[prefix : len(newLines)-suffix]
for i, l := range oldMid {
if i >= 16 {
b.WriteString("-...\n")
break
}
b.WriteString("-" + l + "\n")
}
for i, l := range newMid {
if i >= 16 {
b.WriteString("+...\n")
break
}
b.WriteString("+" + l + "\n")
}
afterStart := len(newLines) - suffix
for i := afterStart; i < afterStart+2 && i < len(newLines); i++ {
b.WriteString(" " + newLines[i] + "\n")
}
return strings.TrimRight(b.String(), "\n")
}
func piGlobMatchPath(pattern, rel string) bool {
return piMatchSegments(strings.Split(pattern, "/"), strings.Split(rel, "/"))
}
func piMatchSegments(pat, path []string) bool {
if len(pat) == 0 {
return len(path) == 0
}
if pat[0] == "**" {
for i := 0; i <= len(path); i++ {
if piMatchSegments(pat[1:], path[i:]) {
return true
}
}
return false
}
if len(path) == 0 {
return false
}
ok, err := filepath.Match(pat[0], path[0])
if err != nil || !ok {
return false
}
return piMatchSegments(pat[1:], path[1:])
}
func truncatePiRunes(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n]) + "... [truncated]"
}