refactor: pre-cleanup.
This commit is contained in:
1 parent
0ceab9d897
commit
e10cbbc92c
53 files changed
+3596
-648
No files matched your search
@@ -32,6 +32,10 @@ type InProcessRunner struct {
|
||||
log *slog.Logger
|
||||
run loopFunc
|
||||
tools *tools.Registry
|
||||
|
||||
// Limits bounds the size of tool results fed back into the stage. The
|
||||
// zero value applies no limits.
|
||||
Limits ToolLimits
|
||||
}
|
||||
|
||||
func NewInProcessRunner(
|
||||
@@ -46,6 +50,18 @@ func NewInProcessRunner(
|
||||
return runner
|
||||
}
|
||||
|
||||
// workspaceToolset names the central-registry toolset a task agent must not
|
||||
// inherit. Those tools are rooted at the chat workspace, not the task's
|
||||
// worktree, and they reach the filesystem through their own handlers -- so
|
||||
// agentloop's ReadOnly and ProtectPaths, which gate only the tools agentloop
|
||||
// registers itself, do not apply to them. A feasibility stage running
|
||||
// ReadOnly could otherwise write, and a TDD fix stage could edit the very
|
||||
// tests it is being graded against.
|
||||
//
|
||||
// This is an invariant of task execution rather than a deployment choice, so
|
||||
// it is not configurable.
|
||||
const workspaceToolset = "workspace"
|
||||
|
||||
func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request) (Result, error) {
|
||||
if err := req.Validate(); err != nil {
|
||||
return Result{}, err
|
||||
@@ -59,7 +75,7 @@ func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request
|
||||
|
||||
notes := &memoryNotes{initial: req.Notes}
|
||||
captures := make(map[string][]json.RawMessage)
|
||||
centralTools, err := BuildToolSet(r.tools)
|
||||
centralTools, err := BuildToolSet(r.tools, r.Limits.Options(workspaceToolset))
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("build central tool set: %w", err)
|
||||
}
|
||||
|
||||
@@ -4,12 +4,94 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
|
||||
aicore "github.com/samcharles93/ai-sdk/core"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// ToolLimits are the configured result limits for one chat turn or agent
|
||||
// stage. It holds only settings, never accumulated state, so it is safe to
|
||||
// store on a long-lived runner and share across tasks.
|
||||
//
|
||||
// A negative limit means no limit; see config.ToolPolicy for why zero cannot
|
||||
// carry that meaning.
|
||||
type ToolLimits struct {
|
||||
MaxResultChars int
|
||||
TurnBudgetChars int
|
||||
SpillDir string
|
||||
}
|
||||
|
||||
// EnsureSpillDir creates the spill directory if one is configured.
|
||||
//
|
||||
// Call it once at startup. Without it the directory never exists, and because
|
||||
// TurnBudget's write failure is silent every oversized result falls back to
|
||||
// inline truncation -- spilling looks configured and does nothing. An empty
|
||||
// SpillDir is not an error: it selects inline truncation deliberately.
|
||||
func (l ToolLimits) EnsureSpillDir() error {
|
||||
if l.SpillDir == "" {
|
||||
return nil
|
||||
}
|
||||
// 0700: spill files are verbatim tool output and may hold anything the
|
||||
// tools could read.
|
||||
if err := os.MkdirAll(l.SpillDir, 0o700); err != nil {
|
||||
return fmt.Errorf("create tool spill directory %s: %w", l.SpillDir, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Options builds the tool-set options for a single turn or stage, minting a
|
||||
// fresh TurnBudget each time.
|
||||
//
|
||||
// The budget must never outlive one turn: a shared counter would let one
|
||||
// task's tool output exhaust another's allowance, and nothing would reset it.
|
||||
func (l ToolLimits) Options(excludeToolsets ...string) ToolSetOptions {
|
||||
opts := ToolSetOptions{
|
||||
MaxResultChars: l.MaxResultChars,
|
||||
ExcludeToolsets: excludeToolsets,
|
||||
}
|
||||
if l.TurnBudgetChars > 0 {
|
||||
opts.Budget = tools.NewTurnBudget(l.TurnBudgetChars, l.SpillDir)
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
// ToolSetOptions bounds what a built tool set may do and return.
|
||||
//
|
||||
// The zero value builds every available tool with no result limits, which is
|
||||
// the behaviour this package had before the options existed.
|
||||
type ToolSetOptions struct {
|
||||
// Budget accounts for the aggregate size of tool results across one chat
|
||||
// turn or agent stage, and supplies the spill directory oversized results
|
||||
// are displaced to. Nil disables budget accounting entirely.
|
||||
Budget *tools.TurnBudget
|
||||
|
||||
// MaxResultChars caps a single tool result. Entries setting
|
||||
// ToolEntry.MaxResultSizeChars override it. Zero or negative means no cap.
|
||||
MaxResultChars int
|
||||
|
||||
// ExcludeToolsets omits entries whose ToolEntry.Toolset matches. Task
|
||||
// agents use it to drop the chat workspace's file and shell tools, which
|
||||
// are rooted at a directory that is not the task's worktree and which
|
||||
// bypass the agent loop's read-only and protected-path enforcement.
|
||||
ExcludeToolsets []string
|
||||
}
|
||||
|
||||
// resultLimit returns the cap that applies to one entry.
|
||||
func (o ToolSetOptions) resultLimit(entry tools.ToolEntry) int {
|
||||
if entry.MaxResultSizeChars != 0 {
|
||||
return entry.MaxResultSizeChars
|
||||
}
|
||||
return o.MaxResultChars
|
||||
}
|
||||
|
||||
// excludes reports whether an entry's toolset is omitted.
|
||||
func (o ToolSetOptions) excludes(entry tools.ToolEntry) bool {
|
||||
return slices.Contains(o.ExcludeToolsets, entry.Toolset)
|
||||
}
|
||||
|
||||
// BuildToolSet converts every currently-available entry in reg into an
|
||||
// ai-sdk core.ToolSet, ready to pass as core.GenerateOptions.Tools for a
|
||||
// multi-step chat turn. A nil registry (memory/tools disabled) returns
|
||||
@@ -20,12 +102,31 @@ import (
|
||||
// tools.Handler exchanges a decoded map. The returned Execute functions
|
||||
// do the JSON <-> map translation and surface decode failures as errors
|
||||
// rather than silently dropping malformed model input.
|
||||
func BuildToolSet(reg *tools.Registry) (aicore.ToolSet, error) {
|
||||
set := aicore.ToolSet{}
|
||||
//
|
||||
// This is the only path from a registered tools.ToolEntry to a model, so it is
|
||||
// also where result limits are enforced. The model runtime owns the tool loop
|
||||
// and decides what to invoke, so archie cannot gate a batch -- but it builds
|
||||
// every Execute closure here, which makes per-call accounting reachable.
|
||||
func BuildToolSet(reg *tools.Registry, opts ToolSetOptions) (aicore.ToolSet, error) {
|
||||
if reg == nil {
|
||||
return set, nil
|
||||
return aicore.ToolSet{}, nil
|
||||
}
|
||||
for _, entry := range reg.All() {
|
||||
return BuildToolSetFrom(reg.All(), opts)
|
||||
}
|
||||
|
||||
// BuildToolSetFrom converts a loose slice of entries under the same rules as
|
||||
// [BuildToolSet].
|
||||
//
|
||||
// It exists for tools that are bound per turn rather than registered globally
|
||||
// -- the task tools carry the calling gateway's identity, so there is one set
|
||||
// of them per gateway and they cannot live in the process-wide registry. Pass
|
||||
// the same ToolSetOptions to both calls so a single turn shares one budget.
|
||||
func BuildToolSetFrom(entries []tools.ToolEntry, opts ToolSetOptions) (aicore.ToolSet, error) {
|
||||
set := aicore.ToolSet{}
|
||||
for _, entry := range entries {
|
||||
if opts.excludes(entry) {
|
||||
continue
|
||||
}
|
||||
available, err := safeToolAvailable(entry)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tool %s availability: %w", entry.Name, err)
|
||||
@@ -47,7 +148,7 @@ func BuildToolSet(reg *tools.Registry) (aicore.ToolSet, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tool %s schema: %w", entry.Name, err)
|
||||
}
|
||||
set[entry.Name] = aicore.NewTool(entry.Name, entry.Description, params, toolExecute(entry))
|
||||
set[entry.Name] = aicore.NewTool(entry.Name, entry.Description, params, toolExecute(entry, opts))
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
@@ -71,9 +172,23 @@ func safeResolvedSchema(entry tools.ToolEntry) (schema tools.JSONSchema, err err
|
||||
}
|
||||
|
||||
// toolExecute adapts a tools.ToolEntry's Handler to core.Tool's
|
||||
// Execute(ctx, jsonInput string) (jsonOutput string, err error) shape.
|
||||
func toolExecute(entry tools.ToolEntry) func(context.Context, string) (string, error) {
|
||||
// Execute(ctx, jsonInput string) (jsonOutput string, err error) shape, and
|
||||
// applies the turn's result accounting.
|
||||
//
|
||||
// The cap is applied to the marshalled payload rather than to the handler's
|
||||
// return value, because the marshalled form is what actually reaches the
|
||||
// model: JSON escaping can change the length materially, so capping the Go
|
||||
// value would bound the wrong string.
|
||||
func toolExecute(entry tools.ToolEntry, opts ToolSetOptions) func(context.Context, string) (string, error) {
|
||||
limit := opts.resultLimit(entry)
|
||||
return func(ctx context.Context, input string) (string, error) {
|
||||
// A turn that has spent its budget must say so. Returning an error
|
||||
// tells the model it has run out; returning an empty result would
|
||||
// read as "the tool found nothing" and invite it to try again.
|
||||
if opts.Budget != nil && opts.Budget.Exceeded() {
|
||||
return "", fmt.Errorf("tool %s: turn budget exceeded (%d chars)", entry.Name, opts.Budget.MaxChars)
|
||||
}
|
||||
|
||||
var args map[string]any
|
||||
if input != "" {
|
||||
if err := json.Unmarshal([]byte(input), &args); err != nil {
|
||||
@@ -88,6 +203,11 @@ func toolExecute(entry tools.ToolEntry) func(context.Context, string) (string, e
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("tool %s: encode output: %w", entry.Name, err)
|
||||
}
|
||||
return string(data), nil
|
||||
|
||||
payload := tools.CapPayload(entry.Name, string(data), limit, opts.Budget)
|
||||
if opts.Budget != nil {
|
||||
opts.Budget.Consume(len(payload))
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
aicore "github.com/samcharles93/ai-sdk/core"
|
||||
@@ -214,7 +217,7 @@ func TestBuildToolSetReportsInvalidDynamicSchemas(t *testing.T) {
|
||||
)
|
||||
func() {
|
||||
defer func() { panicked = recover() }()
|
||||
_, err = BuildToolSet(registry)
|
||||
_, err = BuildToolSet(registry, ToolSetOptions{})
|
||||
}()
|
||||
if panicked != nil {
|
||||
t.Fatalf("BuildToolSet() panicked: %v", panicked)
|
||||
@@ -228,9 +231,243 @@ func TestBuildToolSetReportsInvalidDynamicSchemas(t *testing.T) {
|
||||
|
||||
func mustBuildToolSet(t *testing.T, registry *tools.Registry) map[string]*aicore.Tool {
|
||||
t.Helper()
|
||||
set, err := BuildToolSet(registry)
|
||||
return mustBuildToolSetWith(t, registry, ToolSetOptions{})
|
||||
}
|
||||
|
||||
func mustBuildToolSetWith(t *testing.T, registry *tools.Registry, opts ToolSetOptions) map[string]*aicore.Tool {
|
||||
t.Helper()
|
||||
set, err := BuildToolSet(registry, opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
// registryReturning builds a single-entry registry whose tool returns payload.
|
||||
func registryReturning(t *testing.T, entry tools.ToolEntry, payload string) *tools.Registry {
|
||||
t.Helper()
|
||||
reg := tools.NewRegistry()
|
||||
entry.Handler = func(context.Context, map[string]any) (any, error) { return payload, nil }
|
||||
if err := reg.Register(entry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return reg
|
||||
}
|
||||
|
||||
// TestToolSetCapsResults covers the limit that decides how much of a tool
|
||||
// result reaches the model. The workspace tools truncate themselves, so the
|
||||
// entries that matter here are the ones that do not: skill bodies and MCP
|
||||
// results were previously handed over whole.
|
||||
func TestToolSetCapsResults(t *testing.T) {
|
||||
const payloadSize = 4000
|
||||
payload := strings.Repeat("z", payloadSize)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
entryLimit int // ToolEntry.MaxResultSizeChars
|
||||
defaultLimit int // ToolSetOptions.MaxResultChars
|
||||
wantTruncated bool
|
||||
}{
|
||||
{name: "under the default passes through", defaultLimit: payloadSize * 2},
|
||||
{name: "over the default is capped", defaultLimit: 100, wantTruncated: true},
|
||||
{name: "per-entry limit overrides a larger default", entryLimit: 100, defaultLimit: payloadSize * 2, wantTruncated: true},
|
||||
{name: "per-entry limit overrides a smaller default", entryLimit: payloadSize * 2, defaultLimit: 100},
|
||||
{name: "negative default disables capping", defaultLimit: -1},
|
||||
{name: "zero default disables capping", defaultLimit: 0},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
reg := registryReturning(t, tools.ToolEntry{
|
||||
Name: "big",
|
||||
MaxResultSizeChars: tc.entryLimit,
|
||||
}, payload)
|
||||
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: tc.defaultLimit})
|
||||
out, err := set["big"].Execute(context.Background(), "{}")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
truncated := strings.Contains(out, "truncated")
|
||||
if truncated != tc.wantTruncated {
|
||||
t.Fatalf("truncated = %v, want %v (result %d bytes)", truncated, tc.wantTruncated, len(out))
|
||||
}
|
||||
if !tc.wantTruncated && len(out) < payloadSize {
|
||||
t.Errorf("result is %d bytes, want the whole %d-byte payload", len(out), payloadSize)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolSetSpillsOversizeResults proves an oversized result is displaced to
|
||||
// disk rather than lost: the model gets a path it can read back with the read
|
||||
// tool, which is the whole point of spilling instead of truncating.
|
||||
func TestToolSetSpillsOversizeResults(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
budget := tools.NewTurnBudget(1_000_000, dir)
|
||||
payload := strings.Repeat("q", 4000)
|
||||
|
||||
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, payload)
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, Budget: budget})
|
||||
|
||||
out, err := set["big"].Execute(context.Background(), "{}")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out, "spilled") {
|
||||
t.Fatalf("result = %q, want a spill reference", out)
|
||||
}
|
||||
|
||||
spilled := budget.Spilled()
|
||||
if len(spilled) != 1 || spilled[0].Path == "" {
|
||||
t.Fatalf("Spilled() = %+v, want one spill with a path", spilled)
|
||||
}
|
||||
if !strings.Contains(out, spilled[0].Path) {
|
||||
t.Errorf("result %q does not name the spill path %q", out, spilled[0].Path)
|
||||
}
|
||||
body, err := os.ReadFile(spilled[0].Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(body), payload) {
|
||||
t.Error("spill file does not hold the full payload")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolLimitsCreatesSpillDir covers the gap that made spilling dead code in
|
||||
// production: the configured directory defaults to <work_dir>/tool-spill and
|
||||
// nothing ever created it, while TurnBudget.Spill swallows the write error. So
|
||||
// every oversized result silently fell back to inline truncation and the spill
|
||||
// path was never exercised outside tests that made their own directory.
|
||||
func TestToolLimitsCreatesSpillDir(t *testing.T) {
|
||||
// A nested path proves the whole tree is created, not just a leaf.
|
||||
dir := filepath.Join(t.TempDir(), "work", "tool-spill")
|
||||
limits := ToolLimits{MaxResultChars: 100, TurnBudgetChars: 1_000_000, SpillDir: dir}
|
||||
|
||||
if err := limits.EnsureSpillDir(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, err := os.Stat(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("spill directory was not created: %v", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
t.Fatalf("%s is not a directory", dir)
|
||||
}
|
||||
|
||||
// And a spill actually lands there once it exists.
|
||||
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, strings.Repeat("z", 5000))
|
||||
set := mustBuildToolSetWith(t, reg, limits.Options())
|
||||
if _, err := set["big"].Execute(context.Background(), "{}"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
t.Error("no spill file was written into the created directory")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolLimitsEnsureSpillDirNoop covers the disabled case: no directory
|
||||
// configured is not an error, it selects inline truncation.
|
||||
func TestToolLimitsEnsureSpillDirNoop(t *testing.T) {
|
||||
if err := (ToolLimits{}).EnsureSpillDir(); err != nil {
|
||||
t.Errorf("EnsureSpillDir() with no directory = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolSetChargesBudgetOnce pins the invariant that makes the turn budget
|
||||
// mean anything: a turn is charged exactly the bytes it was shown.
|
||||
//
|
||||
// Displacing an oversized result to disk used to charge the full displaced
|
||||
// size AND the short reference handed back, so two 60 KB results burned more
|
||||
// than the 200 K default budget while the model saw about 200 characters.
|
||||
func TestToolSetChargesBudgetOnce(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
spillDir bool
|
||||
}{
|
||||
{name: "results spilled to disk", spillDir: true},
|
||||
{name: "results truncated inline", spillDir: false},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := ""
|
||||
if tc.spillDir {
|
||||
dir = t.TempDir()
|
||||
}
|
||||
budget := tools.NewTurnBudget(1_000_000, dir)
|
||||
reg := registryReturning(t, tools.ToolEntry{Name: "big"}, strings.Repeat("q", 60_000))
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, Budget: budget})
|
||||
|
||||
delivered := 0
|
||||
for range 2 {
|
||||
out, err := set["big"].Execute(context.Background(), "{}")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
delivered += len(out)
|
||||
}
|
||||
|
||||
if used := budget.Used(); used != delivered {
|
||||
t.Errorf("budget charged %d for %d delivered characters", used, delivered)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolSetBudgetStopsFurtherCalls checks the aggregate cap: once a turn has
|
||||
// spent its budget the next tool call must fail loudly, so the model is told it
|
||||
// has run out rather than silently receiving nothing.
|
||||
func TestToolSetBudgetStopsFurtherCalls(t *testing.T) {
|
||||
budget := tools.NewTurnBudget(50, "")
|
||||
reg := registryReturning(t, tools.ToolEntry{Name: "chatty"}, strings.Repeat("w", 200))
|
||||
set := mustBuildToolSetWith(t, reg, ToolSetOptions{Budget: budget})
|
||||
|
||||
if _, err := set["chatty"].Execute(context.Background(), "{}"); err != nil {
|
||||
t.Fatalf("first call: %v", err)
|
||||
}
|
||||
if !budget.Exceeded() {
|
||||
t.Fatal("budget should be exceeded after a 200-byte result against a 50-byte cap")
|
||||
}
|
||||
_, err := set["chatty"].Execute(context.Background(), "{}")
|
||||
if err == nil {
|
||||
t.Fatal("second call succeeded, want a budget-exceeded error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "budget") {
|
||||
t.Errorf("error = %v, want it to name the budget", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolSetExcludesToolsets covers the task-agent case: a task runs in its
|
||||
// own worktree, so the chat workspace's file and shell tools must not follow it
|
||||
// in and bypass the agent loop's read-only and protected-path enforcement.
|
||||
func TestToolSetExcludesToolsets(t *testing.T) {
|
||||
reg := tools.NewRegistry()
|
||||
for _, e := range []tools.ToolEntry{
|
||||
{Name: "shell", Toolset: "workspace"},
|
||||
{Name: "memory_edit", Toolset: "memory"},
|
||||
} {
|
||||
e.Handler = func(context.Context, map[string]any) (any, error) { return "ok", nil }
|
||||
if err := reg.Register(e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
full := mustBuildToolSetWith(t, reg, ToolSetOptions{})
|
||||
if len(full) != 2 {
|
||||
t.Fatalf("with no exclusions the set has %d tools, want 2", len(full))
|
||||
}
|
||||
|
||||
limited := mustBuildToolSetWith(t, reg, ToolSetOptions{ExcludeToolsets: []string{"workspace"}})
|
||||
if _, ok := limited["shell"]; ok {
|
||||
t.Error("workspace tool survived the exclusion")
|
||||
}
|
||||
if _, ok := limited["memory_edit"]; !ok {
|
||||
t.Error("memory tool was dropped, want only the workspace toolset excluded")
|
||||
}
|
||||
}
|
||||
@@ -284,15 +284,57 @@ type MCPServer struct {
|
||||
}
|
||||
|
||||
// ToolPolicy holds tool execution limits.
|
||||
//
|
||||
// The size limits use a negative value for "no limit". Defaulting cannot
|
||||
// distinguish an explicit 0 from an absent key, so zero has to stay available
|
||||
// as "unset, give me the default" -- which leaves negative as the only way an
|
||||
// operator can turn a cap off deliberately.
|
||||
type ToolPolicy struct {
|
||||
MaxResultChars int `yaml:"max_result_chars" json:"max_result_chars"`
|
||||
ParallelExecution bool `yaml:"parallel_execution" json:"parallel_execution"`
|
||||
// MaxResultChars caps a single tool result before it reaches the model.
|
||||
// Tools that set ToolEntry.MaxResultSizeChars override it.
|
||||
MaxResultChars int `toml:"max_result_chars" yaml:"max_result_chars" json:"max_result_chars"`
|
||||
// TurnBudgetChars caps the aggregate size of all tool results in one
|
||||
// chat turn or agent stage.
|
||||
TurnBudgetChars int `toml:"turn_budget_chars" yaml:"turn_budget_chars" json:"turn_budget_chars"`
|
||||
// SpillDir is where results too large to inline are written so the model
|
||||
// can be handed a path instead of losing the content. Empty disables
|
||||
// spilling, leaving inline truncation as the only option.
|
||||
SpillDir string `toml:"spill_dir" yaml:"spill_dir" json:"spill_dir"`
|
||||
ParallelExecution bool `toml:"parallel_execution" yaml:"parallel_execution" json:"parallel_execution"`
|
||||
}
|
||||
|
||||
// WebFetchConfig controls the web_fetch tool.
|
||||
type WebFetchConfig struct {
|
||||
// Enabled advertises the tool to the model. Nil means unset, which
|
||||
// defaults to true.
|
||||
//
|
||||
// This is a pointer rather than a bool because defaulting cannot tell
|
||||
// `enabled = false` from an absent key, and turning the tool off has to
|
||||
// be expressible. Use IsEnabled rather than reading it directly.
|
||||
Enabled *bool `toml:"enabled" yaml:"enabled" json:"enabled"`
|
||||
|
||||
// Timeout bounds one fetch including redirects.
|
||||
Timeout Duration `toml:"timeout" yaml:"timeout" json:"timeout"`
|
||||
|
||||
// MaxBytes bounds how much of a response body is read.
|
||||
MaxBytes int64 `toml:"max_bytes" yaml:"max_bytes" json:"max_bytes"`
|
||||
|
||||
// AllowPrivateNetworks permits fetching loopback, private and
|
||||
// link-local addresses. Off by default: this daemon's own dashboard,
|
||||
// NATS and the Docker API answer on those, and the URL to fetch
|
||||
// arrives through chat, which is an untrusted path.
|
||||
AllowPrivateNetworks bool `toml:"allow_private_networks" yaml:"allow_private_networks" json:"allow_private_networks"`
|
||||
}
|
||||
|
||||
// IsEnabled reports whether the fetch tool should be registered, treating an
|
||||
// absent setting as enabled.
|
||||
func (c WebFetchConfig) IsEnabled() bool { return c.Enabled == nil || *c.Enabled }
|
||||
|
||||
// ToolsConfig holds MCP server and tool policy configuration.
|
||||
type ToolsConfig struct {
|
||||
MCPServers []MCPServer `toml:"mcp_servers" yaml:"mcp_servers" json:"mcp_servers"`
|
||||
Policy ToolPolicy `toml:"tool_policy" yaml:"tool_policy" json:"tool_policy"`
|
||||
MCPServers []MCPServer `toml:"mcp_servers" yaml:"mcp_servers" json:"mcp_servers"`
|
||||
Policy ToolPolicy `toml:"tool_policy" yaml:"tool_policy" json:"tool_policy"`
|
||||
WebFetch WebFetchConfig `toml:"web_fetch" yaml:"web_fetch" json:"web_fetch"`
|
||||
}
|
||||
|
||||
// Config is the daemon configuration.
|
||||
@@ -526,6 +568,24 @@ type ChatConfig struct {
|
||||
// they read, write and execute, so the directory must be a deliberate
|
||||
// choice rather than whatever the daemon happens to start in.
|
||||
Workspace string `toml:"workspace" yaml:"workspace"`
|
||||
// UnrestrictedFilesystem lifts the workspace jail from the chat agent's
|
||||
// read, write, edit, find and grep tools, letting them reach any absolute
|
||||
// path. Relative paths still resolve against Workspace.
|
||||
//
|
||||
// Off by default. Turn it on when the agent is a general-purpose operator
|
||||
// rather than an assistant scoped to one project: partitioning and
|
||||
// mounting a disk, migrating data between filesystems, or editing service
|
||||
// units are all cross-filesystem by nature, and a jail makes them
|
||||
// impossible.
|
||||
//
|
||||
// This widens which TOOL can do the work, not what the agent can reach.
|
||||
// The shell tool has never been confined, so a jailed deployment only
|
||||
// pushed the agent into doing everything through shell -- losing the
|
||||
// truncation, line numbering and read-before-write protection the
|
||||
// dedicated tools give it. Grant it deliberately all the same: it is the
|
||||
// difference between an agent that can edit /etc directly and one that has
|
||||
// to be asked to.
|
||||
UnrestrictedFilesystem bool `toml:"unrestricted_filesystem" yaml:"unrestricted_filesystem"`
|
||||
// MaxSteps caps how many model/tool round-trips one chat turn may take
|
||||
// before the runtime stops and returns what it has. Zero uses the
|
||||
// default.
|
||||
|
||||
@@ -370,7 +370,7 @@ func TestRuntimeMaxConcurrentPasses(t *testing.T) {
|
||||
// b is woken, but the slot is taken: b's pass count cannot advance
|
||||
// past its initial run while a is in flight.
|
||||
before := b.passCalls.Load()
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
rt.Nudge("b")
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
@@ -47,7 +47,7 @@ func TestWakeOnPrimaryInputForwardsOnlyPrimaryKinds(t *testing.T) {
|
||||
|
||||
// Derived curator output and unrelated events must not wake the
|
||||
// curator: no check, no pass.
|
||||
for i := 0; i < 3; i++ {
|
||||
for range 3 {
|
||||
bus.Publish(events.Event{Kind: events.KindCuratorRun})
|
||||
bus.Publish(events.Event{Kind: events.KindCuratorAction})
|
||||
bus.Publish(events.Event{Kind: events.KindCuratorError})
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultTaskListLimit is how many tasks a bare task_list returns.
|
||||
defaultTaskListLimit = 20
|
||||
|
||||
// maxTaskListLimit bounds what the model can ask for. A queue of a few
|
||||
// hundred tasks would otherwise land in the context window whole.
|
||||
maxTaskListLimit = 100
|
||||
)
|
||||
|
||||
// ChatTaskSummary is the per-task view the task tools return. It is
|
||||
// deliberately narrower than a store task: notes, plan and body are the bulk
|
||||
// of a row and none of them help answer "what are you working on?".
|
||||
type ChatTaskSummary struct {
|
||||
ID int64 `json:"id"`
|
||||
Repo string `json:"repo"` // "owner/name"
|
||||
Title string `json:"title"`
|
||||
Status string `json:"status"`
|
||||
Workflow string `json:"workflow,omitempty"`
|
||||
PRNumber int `json:"pr_number,omitempty"`
|
||||
}
|
||||
|
||||
// ChatTaskLister is the read surface the task tools need. It mirrors the
|
||||
// existing chatTaskWriter/chatTaskController pattern: gateway states what it
|
||||
// needs and the daemon supplies an adapter over the store, so this package
|
||||
// keeps its independence from internal/store.
|
||||
type ChatTaskLister interface {
|
||||
ListChatTasks(ctx context.Context, identity string, limit int) ([]ChatTaskSummary, error)
|
||||
}
|
||||
|
||||
// TaskListResult is what task_list returns.
|
||||
type TaskListResult struct {
|
||||
Tasks []ChatTaskSummary `json:"tasks"`
|
||||
}
|
||||
|
||||
// TaskSpawnResult is what task_spawn returns.
|
||||
type TaskSpawnResult struct {
|
||||
ID int64 `json:"id"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// TaskTools builds the chat tools that let Archie see and add to its own work
|
||||
// queue. Until these existed, /spawn and the task list were slash commands only
|
||||
// a human could type, so "what are you working on?" had no tool path at all.
|
||||
//
|
||||
// Both tools are bound to identity at construction. The model never supplies
|
||||
// it: a model that could name an identity could read or file work belonging to
|
||||
// another instance on the same host.
|
||||
//
|
||||
// A nil backend omits its tool rather than registering one that always fails,
|
||||
// so a daemon without chat task support advertises nothing.
|
||||
//
|
||||
// Deliberately absent: task_approve and task_cancel. waiting_human is the one
|
||||
// point in the task lifecycle where a person must act, and /approve is that
|
||||
// gate. The text reaching a chat turn is untrusted -- a forge issue body or an
|
||||
// inbound email can be quoted into it -- so a tool that approves Archie's own
|
||||
// work would remove the only human checkpoint in the lifecycle. Cancel is
|
||||
// destructive on the same untrusted path. Both remain slash commands.
|
||||
func TaskTools(lister ChatTaskLister, creator TaskCreator, identity string) []tools.ToolEntry {
|
||||
var entries []tools.ToolEntry
|
||||
if lister != nil {
|
||||
entries = append(entries, taskListTool(lister, identity))
|
||||
}
|
||||
if creator != nil {
|
||||
entries = append(entries, taskSpawnTool(creator, identity))
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
func taskListTool(lister ChatTaskLister, identity string) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: "task_list",
|
||||
Toolset: "tasks",
|
||||
Description: "List the tasks this instance is working on, most recent first. " +
|
||||
"Use it to answer questions about current, queued, parked or finished work. " +
|
||||
"Optionally filter by status (queued, running, waiting_human, parked, pr_open, merged, rejected).",
|
||||
Classification: tools.ClassIdempotent,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"status": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Only return tasks with this status. Omit for all statuses.",
|
||||
},
|
||||
"limit": map[string]any{
|
||||
"type": "integer",
|
||||
"description": fmt.Sprintf(
|
||||
"Maximum tasks to return. Defaults to %d, capped at %d.",
|
||||
defaultTaskListLimit, maxTaskListLimit),
|
||||
},
|
||||
},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
limit := taskListLimit(input)
|
||||
|
||||
// The bound identity, never input["identity"].
|
||||
all, err := lister.ListChatTasks(ctx, identity, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("task_list: %w", err)
|
||||
}
|
||||
|
||||
status := strings.TrimSpace(strings.ToLower(asString(input["status"])))
|
||||
// Non-nil even when empty: an empty queue is an answer, and a
|
||||
// null would read to the model as a failed call worth retrying.
|
||||
filtered := make([]ChatTaskSummary, 0, len(all))
|
||||
for _, task := range all {
|
||||
if status != "" && !strings.EqualFold(task.Status, status) {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, task)
|
||||
}
|
||||
return TaskListResult{Tasks: filtered}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func taskSpawnTool(creator TaskCreator, identity string) tools.ToolEntry {
|
||||
return tools.ToolEntry{
|
||||
Name: "task_spawn",
|
||||
Toolset: "tasks",
|
||||
Description: "Queue a new task for this instance to work on in its own worktree, " +
|
||||
"opening a pull request for review when it finishes. " +
|
||||
"Use it when the user asks for work to be carried out rather than answered in chat.",
|
||||
Classification: tools.ClassMutating,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"title": map[string]any{
|
||||
"type": "string",
|
||||
"description": "What the task should accomplish, as a single instruction.",
|
||||
},
|
||||
"repo": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Target repository as \"owner/name\". Omit to use this instance's default repository. A repository this instance is not configured for is refused.",
|
||||
},
|
||||
"workflow": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Workflow to run (e.g. implement, tdd, feasibility). Omit to let the daemon route it.",
|
||||
},
|
||||
},
|
||||
"required": []any{"title"},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
title := strings.TrimSpace(asString(input["title"]))
|
||||
if title == "" {
|
||||
return nil, fmt.Errorf("task_spawn: title is required")
|
||||
}
|
||||
|
||||
id, err := creator.CreateTask(ctx, SpawnRequest{
|
||||
Title: title,
|
||||
Repo: strings.TrimSpace(asString(input["repo"])),
|
||||
Workflow: strings.TrimSpace(asString(input["workflow"])),
|
||||
// The bound identity, never input["identity"]. CreateTask
|
||||
// enforces the repository allow-list for it.
|
||||
Identity: identity,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("task_spawn: %w", err)
|
||||
}
|
||||
return TaskSpawnResult{
|
||||
ID: id,
|
||||
Message: fmt.Sprintf("queued task %d: %s", id, title),
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// taskListLimit resolves the requested limit, falling back to the default for
|
||||
// anything absent or non-positive and clamping the rest.
|
||||
//
|
||||
// JSON numbers decode as float64, but a model that emits an integer through a
|
||||
// different provider path can arrive as int, so both are accepted.
|
||||
func taskListLimit(input map[string]any) int {
|
||||
var limit int
|
||||
switch v := input["limit"].(type) {
|
||||
case float64:
|
||||
limit = int(v)
|
||||
case int:
|
||||
limit = v
|
||||
}
|
||||
if limit <= 0 {
|
||||
return defaultTaskListLimit
|
||||
}
|
||||
return min(limit, maxTaskListLimit)
|
||||
}
|
||||
|
||||
// asString reads a string field, tolerating an absent or wrongly-typed value
|
||||
// rather than failing the call over it.
|
||||
func asString(v any) string {
|
||||
s, _ := v.(string)
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
type fakeLister struct {
|
||||
tasks []ChatTaskSummary
|
||||
err error
|
||||
|
||||
gotIdentity string
|
||||
gotLimit int
|
||||
}
|
||||
|
||||
func (f *fakeLister) ListChatTasks(_ context.Context, identity string, limit int) ([]ChatTaskSummary, error) {
|
||||
f.gotIdentity, f.gotLimit = identity, limit
|
||||
return f.tasks, f.err
|
||||
}
|
||||
|
||||
type fakeCreator struct {
|
||||
id int64
|
||||
err error
|
||||
|
||||
got SpawnRequest
|
||||
}
|
||||
|
||||
func (f *fakeCreator) CreateTask(_ context.Context, req SpawnRequest) (int64, error) {
|
||||
f.got = req
|
||||
return f.id, f.err
|
||||
}
|
||||
|
||||
// toolNamed pulls one entry out of the built set.
|
||||
func toolNamed(t *testing.T, entries []tools.ToolEntry, name string) tools.ToolEntry {
|
||||
t.Helper()
|
||||
for _, e := range entries {
|
||||
if e.Name == name {
|
||||
return e
|
||||
}
|
||||
}
|
||||
t.Fatalf("TaskTools() has no %q entry", name)
|
||||
return tools.ToolEntry{}
|
||||
}
|
||||
|
||||
func TestTaskToolsValidate(t *testing.T) {
|
||||
entries := TaskTools(&fakeLister{}, &fakeCreator{}, "archie")
|
||||
if len(entries) == 0 {
|
||||
t.Fatal("TaskTools() returned nothing")
|
||||
}
|
||||
for _, e := range entries {
|
||||
if err := e.Validate(); err != nil {
|
||||
t.Errorf("entry %q: %v", e.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskToolsOmitNilBackends checks that a daemon without chat task support
|
||||
// advertises nothing, rather than offering a tool that always fails.
|
||||
func TestTaskToolsOmitNilBackends(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
lister ChatTaskLister
|
||||
creator TaskCreator
|
||||
want []string
|
||||
}{
|
||||
{name: "both", lister: &fakeLister{}, creator: &fakeCreator{}, want: []string{"task_list", "task_spawn"}},
|
||||
{name: "lister only", lister: &fakeLister{}, want: []string{"task_list"}},
|
||||
{name: "creator only", creator: &fakeCreator{}, want: []string{"task_spawn"}},
|
||||
{name: "neither"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
entries := TaskTools(tc.lister, tc.creator, "archie")
|
||||
var got []string
|
||||
for _, e := range entries {
|
||||
got = append(got, e.Name)
|
||||
}
|
||||
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
|
||||
t.Errorf("tools = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskListUsesBoundIdentity is the authorization property: the identity
|
||||
// comes from the gateway that built the tool, never from the model. A model
|
||||
// that could name an identity could read another instance's work.
|
||||
func TestTaskListUsesBoundIdentity(t *testing.T) {
|
||||
lister := &fakeLister{tasks: []ChatTaskSummary{{ID: 7, Title: "wire the thing", Status: "running"}}}
|
||||
entry := toolNamed(t, TaskTools(lister, nil, "archie"), "task_list")
|
||||
|
||||
// The model supplies an identity; it must be ignored.
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{"identity": "someone-else"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if lister.gotIdentity != "archie" {
|
||||
t.Errorf("listed identity %q, want the bound %q", lister.gotIdentity, "archie")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskListLimit(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input map[string]any
|
||||
want int
|
||||
}{
|
||||
{name: "default when absent", input: map[string]any{}, want: defaultTaskListLimit},
|
||||
{name: "explicit", input: map[string]any{"limit": float64(5)}, want: 5},
|
||||
{name: "clamped to the maximum", input: map[string]any{"limit": float64(10_000)}, want: maxTaskListLimit},
|
||||
{name: "non-positive falls back to the default", input: map[string]any{"limit": float64(0)}, want: defaultTaskListLimit},
|
||||
{name: "negative falls back to the default", input: map[string]any{"limit": float64(-3)}, want: defaultTaskListLimit},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
lister := &fakeLister{}
|
||||
entry := toolNamed(t, TaskTools(lister, nil, "archie"), "task_list")
|
||||
if _, err := entry.Handler(context.Background(), tc.input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if lister.gotLimit != tc.want {
|
||||
t.Errorf("limit = %d, want %d", lister.gotLimit, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskListFiltersByStatus(t *testing.T) {
|
||||
lister := &fakeLister{tasks: []ChatTaskSummary{
|
||||
{ID: 1, Status: "running"},
|
||||
{ID: 2, Status: "queued"},
|
||||
{ID: 3, Status: "running"},
|
||||
}}
|
||||
entry := toolNamed(t, TaskTools(lister, nil, "archie"), "task_list")
|
||||
|
||||
out, err := entry.Handler(context.Background(), map[string]any{"status": "running"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, ok := out.(TaskListResult)
|
||||
if !ok {
|
||||
t.Fatalf("handler returned %T, want TaskListResult", out)
|
||||
}
|
||||
if len(result.Tasks) != 2 {
|
||||
t.Fatalf("got %d tasks, want the 2 running ones", len(result.Tasks))
|
||||
}
|
||||
for _, task := range result.Tasks {
|
||||
if task.Status != "running" {
|
||||
t.Errorf("task %d has status %q, want only running", task.ID, task.Status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskListEmptyIsNotAnError guards against the model reading an empty
|
||||
// queue as a broken tool and retrying.
|
||||
func TestTaskListEmptyIsNotAnError(t *testing.T) {
|
||||
entry := toolNamed(t, TaskTools(&fakeLister{}, nil, "archie"), "task_list")
|
||||
|
||||
out, err := entry.Handler(context.Background(), map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatalf("empty list returned an error: %v", err)
|
||||
}
|
||||
result, ok := out.(TaskListResult)
|
||||
if !ok {
|
||||
t.Fatalf("handler returned %T, want TaskListResult", out)
|
||||
}
|
||||
if result.Tasks == nil {
|
||||
t.Error("Tasks is nil, want an empty slice so it marshals as [] not null")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskListPropagatesStoreError(t *testing.T) {
|
||||
lister := &fakeLister{err: errors.New("database is gone")}
|
||||
entry := toolNamed(t, TaskTools(lister, nil, "archie"), "task_list")
|
||||
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{}); err == nil {
|
||||
t.Fatal("handler error = nil, want the store failure surfaced")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskSpawn(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input map[string]any
|
||||
creator *fakeCreator
|
||||
wantErr bool
|
||||
wantTitle string
|
||||
wantRepo string
|
||||
}{
|
||||
{
|
||||
name: "title only",
|
||||
input: map[string]any{"title": "fix the parser"},
|
||||
creator: &fakeCreator{id: 42},
|
||||
wantTitle: "fix the parser",
|
||||
},
|
||||
{
|
||||
name: "with repo and workflow",
|
||||
input: map[string]any{"title": "port it", "repo": "acme/app", "workflow": "tdd"},
|
||||
creator: &fakeCreator{id: 43},
|
||||
wantTitle: "port it",
|
||||
wantRepo: "acme/app",
|
||||
},
|
||||
{
|
||||
name: "missing title is refused",
|
||||
input: map[string]any{},
|
||||
creator: &fakeCreator{id: 44},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "blank title is refused",
|
||||
input: map[string]any{"title": " "},
|
||||
creator: &fakeCreator{id: 45},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "creator rejection surfaces",
|
||||
input: map[string]any{"title": "x", "repo": "not/allowed"},
|
||||
creator: &fakeCreator{err: fmt.Errorf("repo %q is not configured for this identity", "not/allowed")},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
entry := toolNamed(t, TaskTools(nil, tc.creator, "archie"), "task_spawn")
|
||||
out, err := entry.Handler(context.Background(), tc.input)
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("handler error = nil, want a refusal")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tc.creator.got.Title != tc.wantTitle {
|
||||
t.Errorf("title = %q, want %q", tc.creator.got.Title, tc.wantTitle)
|
||||
}
|
||||
if tc.creator.got.Repo != tc.wantRepo {
|
||||
t.Errorf("repo = %q, want %q", tc.creator.got.Repo, tc.wantRepo)
|
||||
}
|
||||
// Identity is bound, never taken from the model.
|
||||
if tc.creator.got.Identity != "archie" {
|
||||
t.Errorf("identity = %q, want the bound %q", tc.creator.got.Identity, "archie")
|
||||
}
|
||||
result, ok := out.(TaskSpawnResult)
|
||||
if !ok {
|
||||
t.Fatalf("handler returned %T, want TaskSpawnResult", out)
|
||||
}
|
||||
if result.ID != tc.creator.id {
|
||||
t.Errorf("id = %d, want %d", result.ID, tc.creator.id)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskSpawnIgnoresModelIdentity is the counterpart to the list case: a
|
||||
// model must not be able to file work under another instance's identity.
|
||||
func TestTaskSpawnIgnoresModelIdentity(t *testing.T) {
|
||||
creator := &fakeCreator{id: 1}
|
||||
entry := toolNamed(t, TaskTools(nil, creator, "archie"), "task_spawn")
|
||||
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{
|
||||
"title": "sneaky",
|
||||
"identity": "other-archie",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if creator.got.Identity != "archie" {
|
||||
t.Errorf("identity = %q, want the bound %q", creator.got.Identity, "archie")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskToolsExcludeApprovalTools records a deliberate omission: approving a
|
||||
// waiting_human task is the one human checkpoint in the lifecycle, and chat is
|
||||
// an untrusted input path. If these are ever added they must be a considered
|
||||
// decision, not an accident.
|
||||
func TestTaskToolsExcludeApprovalTools(t *testing.T) {
|
||||
entries := TaskTools(&fakeLister{}, &fakeCreator{}, "archie")
|
||||
for _, e := range entries {
|
||||
switch e.Name {
|
||||
case "task_approve", "task_cancel":
|
||||
t.Errorf("%q is exposed to the model; approval must stay a human action", e.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// Defaults applied to absent input. Named so a reader can find the value
|
||||
@@ -25,6 +26,19 @@ const (
|
||||
defaultContainerUptime = 60 * time.Minute
|
||||
defaultVolumeTTL = 72 * time.Hour
|
||||
defaultPullPolicy = "missing"
|
||||
|
||||
// defaultMaxResultChars bounds one tool result. It matches the 50KB the
|
||||
// lifted workspace tools already truncate themselves at
|
||||
// (tools/builtin.DefaultMaxBytes), so those stay the binding limit and
|
||||
// only tools with no truncation of their own -- skill bodies, MCP
|
||||
// results -- see a change.
|
||||
defaultMaxResultChars = 50_000
|
||||
|
||||
defaultWebFetchTimeout = 30 * time.Second
|
||||
// defaultWebFetchMaxBytes bounds a fetched body before the result limit
|
||||
// above trims it further. Generous enough for a documentation page,
|
||||
// small enough that a large download cannot occupy the daemon.
|
||||
defaultWebFetchMaxBytes = 2_000_000
|
||||
)
|
||||
|
||||
// applyDefaults fills in every absent value. It never reports an error and
|
||||
@@ -43,6 +57,43 @@ func (l *Loader) applyDefaults(cfg *config.Config) {
|
||||
applyDispatchDefaults(cfg)
|
||||
applyIdentityDefaults(cfg)
|
||||
applyContainerDefaults(cfg)
|
||||
applyToolPolicyDefaults(cfg)
|
||||
}
|
||||
|
||||
// applyToolPolicyDefaults fills the tool result limits.
|
||||
//
|
||||
// Zero means "unset" and takes the default; a negative value is the operator
|
||||
// saying "no limit" and is left alone. See [config.ToolPolicy].
|
||||
func applyToolPolicyDefaults(cfg *config.Config) {
|
||||
if cfg.Tools.Policy.MaxResultChars == 0 {
|
||||
cfg.Tools.Policy.MaxResultChars = defaultMaxResultChars
|
||||
}
|
||||
if cfg.Tools.Policy.TurnBudgetChars == 0 {
|
||||
cfg.Tools.Policy.TurnBudgetChars = tools.DefaultTurnBudgetChars
|
||||
}
|
||||
// SpillDir is deliberately NOT defaulted.
|
||||
//
|
||||
// Spilling hands the model a file path to read back, and the read tool is
|
||||
// confined to chat.workspace. A default under work_dir is outside that for
|
||||
// any workspace narrower than the whole home directory, and always outside
|
||||
// a task agent's worktree -- so the model would be given a path it cannot
|
||||
// open and the result would be lost rather than displaced. Truncating
|
||||
// inline at least shows the first part of the result and says so.
|
||||
//
|
||||
// An operator who wants spilling points this at a directory inside the
|
||||
// workspace; startup warns when it is not (see cmd/archied).
|
||||
applyWebFetchDefaults(cfg)
|
||||
}
|
||||
|
||||
// applyWebFetchDefaults fills the fetch tool's settings. Enabled is left alone
|
||||
// when the operator set it either way; see [config.WebFetchConfig].
|
||||
func applyWebFetchDefaults(cfg *config.Config) {
|
||||
if cfg.Tools.WebFetch.Timeout == 0 {
|
||||
cfg.Tools.WebFetch.Timeout = config.Duration(defaultWebFetchTimeout)
|
||||
}
|
||||
if cfg.Tools.WebFetch.MaxBytes == 0 {
|
||||
cfg.Tools.WebFetch.MaxBytes = defaultWebFetchMaxBytes
|
||||
}
|
||||
}
|
||||
|
||||
// DefaultWorkDir returns the work directory an unset work_dir would have been
|
||||
|
||||
@@ -151,6 +151,143 @@ func TestLoadAgentDefaultsAndOverrides(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadToolPolicyDefaultsAndOverrides covers the result-size and turn-budget
|
||||
// limits end to end from TOML. Before these fields carried toml tags they could
|
||||
// not be set from the daemon's config at all, so a test that only exercised
|
||||
// defaulting would have passed against a setting no operator could reach.
|
||||
//
|
||||
// A negative value means "disabled" rather than zero: defaulting cannot tell an
|
||||
// explicit 0 from an absent key, so zero has to stay available as "unset".
|
||||
func TestLoadToolPolicyDefaultsAndOverrides(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
policy string
|
||||
wantMaxResult int
|
||||
wantTurnBudget int
|
||||
wantSpillDir string
|
||||
}{
|
||||
{
|
||||
// SpillDir has no default on purpose: a path outside
|
||||
// chat.workspace is one the read tool refuses, so the model would
|
||||
// be handed a reference it cannot open. Absent means truncate
|
||||
// inline.
|
||||
name: "defaults",
|
||||
wantMaxResult: 50_000,
|
||||
wantTurnBudget: 200_000,
|
||||
wantSpillDir: "",
|
||||
},
|
||||
{
|
||||
name: "explicit values",
|
||||
policy: "[tools.tool_policy]\nmax_result_chars = 1234\nturn_budget_chars = 5678\nspill_dir = \"/var/spool/archie\"\n",
|
||||
wantMaxResult: 1234,
|
||||
wantTurnBudget: 5678,
|
||||
wantSpillDir: "/var/spool/archie",
|
||||
},
|
||||
{
|
||||
name: "negative disables both caps",
|
||||
policy: "[tools.tool_policy]\nmax_result_chars = -1\nturn_budget_chars = -1\n",
|
||||
wantMaxResult: -1,
|
||||
wantTurnBudget: -1,
|
||||
wantSpillDir: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" + tt.policy +
|
||||
"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
policy := cfg.Tools.Policy
|
||||
if policy.MaxResultChars != tt.wantMaxResult {
|
||||
t.Errorf("MaxResultChars = %d, want %d", policy.MaxResultChars, tt.wantMaxResult)
|
||||
}
|
||||
if policy.TurnBudgetChars != tt.wantTurnBudget {
|
||||
t.Errorf("TurnBudgetChars = %d, want %d", policy.TurnBudgetChars, tt.wantTurnBudget)
|
||||
}
|
||||
if policy.SpillDir != tt.wantSpillDir {
|
||||
t.Errorf("SpillDir = %q, want %q", policy.SpillDir, tt.wantSpillDir)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadWebFetchDefaultsAndOverrides covers the fetch tool's settings.
|
||||
//
|
||||
// The enabled case matters most: it is a pointer precisely so an operator can
|
||||
// turn the tool off, which a plain bool could not express because defaulting
|
||||
// cannot tell `enabled = false` from an absent key.
|
||||
func TestLoadWebFetchDefaultsAndOverrides(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
webFetch string
|
||||
wantEnabled bool
|
||||
wantTimeout time.Duration
|
||||
wantMaxBytes int64
|
||||
wantPrivate bool
|
||||
}{
|
||||
{
|
||||
name: "defaults",
|
||||
wantEnabled: true,
|
||||
wantTimeout: 30 * time.Second,
|
||||
wantMaxBytes: 2_000_000,
|
||||
},
|
||||
{
|
||||
name: "explicitly disabled",
|
||||
webFetch: "[tools.web_fetch]\nenabled = false\n",
|
||||
wantEnabled: false,
|
||||
wantTimeout: 30 * time.Second,
|
||||
wantMaxBytes: 2_000_000,
|
||||
},
|
||||
{
|
||||
name: "overrides",
|
||||
webFetch: "[tools.web_fetch]\ntimeout = \"5s\"\nmax_bytes = 4096\nallow_private_networks = true\n",
|
||||
wantEnabled: true,
|
||||
wantTimeout: 5 * time.Second,
|
||||
wantMaxBytes: 4096,
|
||||
wantPrivate: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" + tt.webFetch +
|
||||
"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
wf := cfg.Tools.WebFetch
|
||||
if got := wf.IsEnabled(); got != tt.wantEnabled {
|
||||
t.Errorf("IsEnabled() = %v, want %v", got, tt.wantEnabled)
|
||||
}
|
||||
if got := wf.Timeout.Std(); got != tt.wantTimeout {
|
||||
t.Errorf("Timeout = %s, want %s", got, tt.wantTimeout)
|
||||
}
|
||||
if wf.MaxBytes != tt.wantMaxBytes {
|
||||
t.Errorf("MaxBytes = %d, want %d", wf.MaxBytes, tt.wantMaxBytes)
|
||||
}
|
||||
if wf.AllowPrivateNetworks != tt.wantPrivate {
|
||||
t.Errorf("AllowPrivateNetworks = %v, want %v", wf.AllowPrivateNetworks, tt.wantPrivate)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadContainerVolumeTTL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -123,7 +123,7 @@ func (a Announcer) detectChanged(state map[string]string, prefix string) (change
|
||||
changed[component.ID] = true
|
||||
}
|
||||
}
|
||||
return
|
||||
return changed, stateChanged
|
||||
}
|
||||
|
||||
// sendAndRecord sends the announcement and updates state on success.
|
||||
|
||||
@@ -79,7 +79,7 @@ type Service struct {
|
||||
}
|
||||
|
||||
func (s *Service) Check(ctx context.Context, recipient int64) (Snapshot, error) {
|
||||
if s.Catalog == nil {
|
||||
if s == nil || s.Catalog == nil {
|
||||
return Snapshot{}, errors.New("update discovery is not configured")
|
||||
}
|
||||
snapshot, err := s.Catalog.Check(ctx)
|
||||
@@ -109,7 +109,7 @@ func (s *Service) Check(ctx context.Context, recipient int64) (Snapshot, error)
|
||||
// Defer records only the exact versions the caller displayed. It refuses a
|
||||
// changed catalog rather than silently suppressing a release the user never saw.
|
||||
func (s *Service) Defer(ctx context.Context, recipient int64, expected Snapshot) error {
|
||||
if s.Catalog == nil {
|
||||
if s == nil || s.Catalog == nil {
|
||||
return errors.New("update discovery is not configured")
|
||||
}
|
||||
if s.StatePath == "" {
|
||||
@@ -139,13 +139,13 @@ func (s *Service) Defer(ctx context.Context, recipient int64, expected Snapshot)
|
||||
}
|
||||
|
||||
func (s *Service) Install(ctx context.Context, progress func(string)) error {
|
||||
if s.Installer == nil {
|
||||
if s == nil || s.Installer == nil {
|
||||
return errors.New("update installation is not configured")
|
||||
}
|
||||
return s.Installer.Install(ctx, progress)
|
||||
}
|
||||
|
||||
func (s *Service) CanInstall() bool { return s.Installer != nil }
|
||||
func (s *Service) CanInstall() bool { return s != nil && s.Installer != nil }
|
||||
|
||||
type deferrals map[string]map[string]string
|
||||
|
||||
|
||||
@@ -61,6 +61,23 @@ func TestServiceInstallForwardsProgressAndFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNilServiceReturnsConfigurationErrors(t *testing.T) {
|
||||
var service *Service
|
||||
|
||||
if _, err := service.Check(context.Background(), 0); err == nil {
|
||||
t.Fatal("nil service check returned nil error")
|
||||
}
|
||||
if err := service.Defer(context.Background(), 0, Snapshot{}); err == nil {
|
||||
t.Fatal("nil service defer returned nil error")
|
||||
}
|
||||
if err := service.Install(context.Background(), nil); err == nil {
|
||||
t.Fatal("nil service install returned nil error")
|
||||
}
|
||||
if service.CanInstall() {
|
||||
t.Fatal("nil service reports that installation is available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatSnapshotReportsAvailableAndUnchangedComponents(t *testing.T) {
|
||||
got := FormatSnapshot(Snapshot{Components: []Component{
|
||||
{Label: "THE GATEWAY", Installed: "v1", Available: "v2", Changelog: "- safer updates"},
|
||||
|
||||
@@ -284,7 +284,7 @@ func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail s
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
res, err := tx.ExecContext(ctx,
|
||||
`UPDATE tasks SET status=?, updated_at=datetime('now') WHERE id=? AND status=?`, to, taskID, from)
|
||||
@@ -366,7 +366,7 @@ func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, workflow
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
res, err := tx.ExecContext(ctx, `
|
||||
UPDATE tasks SET status='queued',
|
||||
|
||||
+133
-14
@@ -3,8 +3,9 @@ package tools
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// DefaultTurnBudgetChars is the default per-turn aggregate output budget
|
||||
@@ -84,25 +85,143 @@ func (b *TurnBudget) Spill(toolName string, content []byte) SpillRef {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
sizeChars := len(content)
|
||||
ref := SpillRef{SizeChars: sizeChars}
|
||||
|
||||
if b.spillDir != "" {
|
||||
path := filepath.Join(b.spillDir, fmt.Sprintf("spill-%s-%d", toolName, b.used))
|
||||
if err := os.WriteFile(path, content, 0o644); err == nil {
|
||||
ref.Path = path
|
||||
}
|
||||
}
|
||||
|
||||
b.spilled = append(b.spilled, ref)
|
||||
b.used += sizeChars
|
||||
ref := b.writeSpillLocked(toolName, content)
|
||||
b.used += ref.SizeChars
|
||||
if b.used > b.MaxChars {
|
||||
b.exceeded = true
|
||||
}
|
||||
|
||||
return ref
|
||||
}
|
||||
|
||||
// WriteSpill writes content to the spill directory and records the reference
|
||||
// without charging the budget.
|
||||
//
|
||||
// It exists so that displacing a result to disk and billing for it are separate
|
||||
// decisions. A caller that hands the model a short spill reference has shown it
|
||||
// only those few characters and should be charged for those; charging the full
|
||||
// displaced size as well bills a turn twice for one result and exhausts it
|
||||
// early. [CapPayload] uses this; the batch-dispatch path uses [TurnBudget.Spill],
|
||||
// which still charges, because it accounts for the result separately.
|
||||
func (b *TurnBudget) WriteSpill(toolName string, content []byte) SpillRef {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.writeSpillLocked(toolName, content)
|
||||
}
|
||||
|
||||
// writeSpillLocked performs the write. Must be called with b.mu held.
|
||||
func (b *TurnBudget) writeSpillLocked(toolName string, content []byte) SpillRef {
|
||||
ref := SpillRef{SizeChars: len(content)}
|
||||
|
||||
if b.spillDir != "" {
|
||||
ref.Path = writeSpillFile(b.spillDir, toolName, content)
|
||||
}
|
||||
|
||||
b.spilled = append(b.spilled, ref)
|
||||
return ref
|
||||
}
|
||||
|
||||
// writeSpillFile writes content to a fresh file in dir, returning its path or
|
||||
// "" when the write fails. A failure is not an error here: the caller falls
|
||||
// back to inline truncation, which is degraded but correct.
|
||||
//
|
||||
// The name comes from CreateTemp rather than from budget state. A budget is
|
||||
// minted per turn and every turn shares one directory, so any within-budget
|
||||
// counter restarts at zero each turn and the second turn would overwrite the
|
||||
// first turn's file, handing one session a reference that resolves to another
|
||||
// session's output.
|
||||
//
|
||||
// 0600 because this is verbatim tool output -- shell stdout, file contents, MCP
|
||||
// responses. It is the first place archie persists that material and it can
|
||||
// hold anything the tools could read.
|
||||
func writeSpillFile(dir, toolName string, content []byte) string {
|
||||
f, err := os.CreateTemp(dir, "spill-"+sanitiseToolName(toolName)+"-*")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if err := f.Chmod(0o600); err != nil {
|
||||
return ""
|
||||
}
|
||||
if _, err := f.Write(content); err != nil {
|
||||
return ""
|
||||
}
|
||||
return f.Name()
|
||||
}
|
||||
|
||||
// sanitiseToolName strips path separators and other characters that must not
|
||||
// reach a filename. MCP tool names are supplied by a third-party server, so a
|
||||
// name like "../../etc/passwd" is reachable input rather than a hypothetical.
|
||||
func sanitiseToolName(name string) string {
|
||||
var b strings.Builder
|
||||
b.Grow(len(name))
|
||||
for _, r := range name {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_', r == '-':
|
||||
b.WriteRune(r)
|
||||
default:
|
||||
b.WriteByte('_')
|
||||
}
|
||||
}
|
||||
if b.Len() == 0 {
|
||||
return "tool"
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// CapPayload bounds one tool result to max bytes before it reaches the model.
|
||||
// It is the single definition of that rule: [enforcePerToolLimit] applies it on
|
||||
// the batch-dispatch path, and the agent tool set applies it to the marshalled
|
||||
// payload it hands back to the model.
|
||||
//
|
||||
// When budget has a spill directory the whole result is written there and the
|
||||
// model is given the path, so an oversized result is displaced rather than
|
||||
// lost. Without one -- or when the write fails -- the result is truncated
|
||||
// inline on a rune boundary.
|
||||
//
|
||||
// Either way the return value carries a notice naming the tool and the full
|
||||
// size. Shortening a result silently is how a model concludes a file is empty
|
||||
// or a search found nothing, so the fact of truncation is never implicit.
|
||||
//
|
||||
// max <= 0 disables capping.
|
||||
func CapPayload(toolName, payload string, limit int, budget *TurnBudget) string {
|
||||
if limit <= 0 || len(payload) <= limit {
|
||||
return payload
|
||||
}
|
||||
|
||||
if budget != nil {
|
||||
// WriteSpill, not Spill: the caller charges for what it actually
|
||||
// hands the model, which is the short reference below, not the
|
||||
// displaced payload.
|
||||
if ref := budget.WriteSpill(toolName, []byte(payload)); ref.Path != "" {
|
||||
return fmt.Sprintf(
|
||||
"[%s: result spilled to %s (%d characters); too large to inline]",
|
||||
toolName, ref.Path, ref.SizeChars,
|
||||
)
|
||||
}
|
||||
// Spill was disabled or failed -- fall through to inline truncation.
|
||||
}
|
||||
|
||||
return truncateAtRuneBoundary(payload, limit) + fmt.Sprintf(
|
||||
"\n\n[%s: result truncated, showing the first %d of %d characters]",
|
||||
toolName, limit, len(payload),
|
||||
)
|
||||
}
|
||||
|
||||
// truncateAtRuneBoundary cuts s to at most max bytes without splitting a
|
||||
// multi-byte rune. A half rune is invalid UTF-8: some providers reject the
|
||||
// request outright and others render a replacement character mid-word, so the
|
||||
// cut always retreats to a boundary even when that costs a few bytes.
|
||||
func truncateAtRuneBoundary(s string, limit int) string {
|
||||
if limit >= len(s) {
|
||||
return s
|
||||
}
|
||||
for limit > 0 && !utf8.RuneStart(s[limit]) {
|
||||
limit--
|
||||
}
|
||||
return s[:limit]
|
||||
}
|
||||
|
||||
// Used reports the total characters consumed so far.
|
||||
func (b *TurnBudget) Used() int {
|
||||
b.mu.Lock()
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func TestDefaultTurnBudgetChars(t *testing.T) {
|
||||
@@ -205,6 +206,278 @@ func TestTurnBudgetSpillFileNaming(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapPayload(t *testing.T) {
|
||||
const (
|
||||
toolName = "skill_activate"
|
||||
short = "abcdefghij" // 10 bytes
|
||||
)
|
||||
long := strings.Repeat("x", 500)
|
||||
// oversize begins with short, so a truncation at len(short) is
|
||||
// recognisable in the result rather than being an opaque prefix.
|
||||
oversize := short + long
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
// budget selects how the TurnBudget is built: "none" passes nil,
|
||||
// "spill" gives it a usable directory, "nospill" gives it none,
|
||||
// "badspill" gives it a directory that cannot be written.
|
||||
budget string
|
||||
payload string
|
||||
max int
|
||||
wantPayload string // exact result, when the payload passes through
|
||||
wantContain []string // substrings the capped result must carry
|
||||
}{
|
||||
{
|
||||
name: "no cap when max is zero",
|
||||
budget: "none",
|
||||
payload: long,
|
||||
max: 0,
|
||||
wantPayload: long,
|
||||
},
|
||||
{
|
||||
name: "no cap when max is negative",
|
||||
budget: "none",
|
||||
payload: long,
|
||||
max: -1,
|
||||
wantPayload: long,
|
||||
},
|
||||
{
|
||||
name: "under the cap passes through",
|
||||
budget: "none",
|
||||
payload: short,
|
||||
max: len(short) + 1,
|
||||
wantPayload: short,
|
||||
},
|
||||
{
|
||||
name: "exactly at the cap passes through",
|
||||
budget: "none",
|
||||
payload: short,
|
||||
max: len(short),
|
||||
wantPayload: short,
|
||||
},
|
||||
{
|
||||
name: "over the cap without a budget truncates and names the tool",
|
||||
budget: "none",
|
||||
payload: oversize,
|
||||
max: len(short),
|
||||
wantContain: []string{short, toolName, "510"},
|
||||
},
|
||||
{
|
||||
name: "over the cap with no spill directory truncates",
|
||||
budget: "nospill",
|
||||
payload: oversize,
|
||||
max: len(short),
|
||||
wantContain: []string{short, toolName, "510"},
|
||||
},
|
||||
{
|
||||
name: "over the cap with a spill directory reports the path",
|
||||
budget: "spill",
|
||||
payload: oversize,
|
||||
max: len(short),
|
||||
wantContain: []string{toolName, "spill-"},
|
||||
},
|
||||
{
|
||||
name: "spill write failure falls back to truncation",
|
||||
budget: "badspill",
|
||||
payload: oversize,
|
||||
max: len(short),
|
||||
wantContain: []string{short, toolName, "510"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var budget *TurnBudget
|
||||
switch tc.budget {
|
||||
case "spill":
|
||||
budget = NewTurnBudget(1_000_000, t.TempDir())
|
||||
case "nospill":
|
||||
budget = NewTurnBudget(1_000_000, "")
|
||||
case "badspill":
|
||||
f, err := os.CreateTemp(t.TempDir(), "spill-blocker")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
budget = NewTurnBudget(1_000_000, filepath.Join(f.Name(), "sub"))
|
||||
}
|
||||
|
||||
got := CapPayload(toolName, tc.payload, tc.max, budget)
|
||||
|
||||
if tc.wantPayload != "" {
|
||||
if got != tc.wantPayload {
|
||||
t.Errorf("CapPayload() = %q, want it returned unchanged", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, want := range tc.wantContain {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("CapPayload() = %q, want it to contain %q", got, want)
|
||||
}
|
||||
}
|
||||
if len(got) >= len(tc.payload) {
|
||||
t.Errorf("CapPayload() returned %d bytes, want fewer than the %d-byte payload", len(got), len(tc.payload))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCapPayloadDoesNotChargeBudget pins the accounting boundary.
|
||||
//
|
||||
// CapPayload displaces an oversized result to disk; it must not also bill for
|
||||
// it. Spill used to charge the FULL uncapped length while the caller charged
|
||||
// the capped length on top, so a turn was billed for far more than it was ever
|
||||
// shown and ran out of budget early.
|
||||
func TestCapPayloadDoesNotChargeBudget(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
spillDir bool
|
||||
}{
|
||||
{name: "spilled to disk", spillDir: true},
|
||||
{name: "truncated inline", spillDir: false},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := ""
|
||||
if tc.spillDir {
|
||||
dir = t.TempDir()
|
||||
}
|
||||
budget := NewTurnBudget(1_000_000, dir)
|
||||
|
||||
CapPayload("big", strings.Repeat("x", 5000), 100, budget)
|
||||
|
||||
if used := budget.Used(); used != 0 {
|
||||
t.Errorf("Used() = %d after CapPayload, want 0: accounting belongs to the caller", used)
|
||||
}
|
||||
if budget.Exceeded() {
|
||||
t.Error("budget reports exceeded after a single capped result")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSpillChargesBudget is the other half: the batch-dispatch path calls Spill
|
||||
// directly and relies on it charging, so that behaviour must not drift.
|
||||
func TestSpillChargesBudget(t *testing.T) {
|
||||
budget := NewTurnBudget(1_000_000, t.TempDir())
|
||||
content := []byte(strings.Repeat("y", 300))
|
||||
|
||||
budget.Spill("tool", content)
|
||||
|
||||
if used := budget.Used(); used != len(content) {
|
||||
t.Errorf("Used() = %d, want %d", used, len(content))
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteSpillUniquePaths guards a collision the previous naming scheme hid:
|
||||
// the file name was derived from the budget's consumed count, so two spills
|
||||
// that did not change it would overwrite each other.
|
||||
func TestWriteSpillUniquePaths(t *testing.T) {
|
||||
budget := NewTurnBudget(1_000_000, t.TempDir())
|
||||
|
||||
first := budget.WriteSpill("tool", []byte("first"))
|
||||
second := budget.WriteSpill("tool", []byte("second"))
|
||||
|
||||
if first.Path == "" || second.Path == "" {
|
||||
t.Fatalf("spill paths empty: %q %q", first.Path, second.Path)
|
||||
}
|
||||
if first.Path == second.Path {
|
||||
t.Fatalf("both spills wrote to %q; the second overwrote the first", first.Path)
|
||||
}
|
||||
for _, want := range []struct {
|
||||
ref SpillRef
|
||||
body string
|
||||
}{{first, "first"}, {second, "second"}} {
|
||||
got, err := os.ReadFile(want.ref.Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != want.body {
|
||||
t.Errorf("%s holds %q, want %q", want.ref.Path, got, want.body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteSpillUniqueAcrossBudgets is the collision that matters in practice.
|
||||
// A TurnBudget is minted per chat turn and per agent stage while every one of
|
||||
// them shares a single spill directory, so a name derived from within-budget
|
||||
// state restarts each turn and the second turn silently overwrites the first --
|
||||
// leaving one session holding a reference to another session's output.
|
||||
func TestWriteSpillUniqueAcrossBudgets(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
firstTurn := NewTurnBudget(1_000_000, dir)
|
||||
secondTurn := NewTurnBudget(1_000_000, dir)
|
||||
|
||||
a := firstTurn.WriteSpill("read", []byte("first turn output"))
|
||||
b := secondTurn.WriteSpill("read", []byte("second turn output"))
|
||||
|
||||
if a.Path == "" || b.Path == "" {
|
||||
t.Fatalf("spill paths empty: %q %q", a.Path, b.Path)
|
||||
}
|
||||
if a.Path == b.Path {
|
||||
t.Fatalf("both turns wrote to %q", a.Path)
|
||||
}
|
||||
got, err := os.ReadFile(a.Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != "first turn output" {
|
||||
t.Errorf("first turn's spill holds %q; a later turn overwrote it", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteSpillFilePermissions checks the mode on the first place archie
|
||||
// persists verbatim tool output. It can hold anything the tools could read --
|
||||
// file contents, shell stdout, MCP responses -- so it must not be world- or
|
||||
// group-readable.
|
||||
func TestWriteSpillFilePermissions(t *testing.T) {
|
||||
budget := NewTurnBudget(1_000_000, t.TempDir())
|
||||
|
||||
ref := budget.WriteSpill("shell", []byte("secret output"))
|
||||
if ref.Path == "" {
|
||||
t.Fatal("spill was not written")
|
||||
}
|
||||
info, err := os.Stat(ref.Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if perm := info.Mode().Perm(); perm != 0o600 {
|
||||
t.Errorf("spill file mode = %04o, want 0600", perm)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteSpillSanitisesToolName covers a name reaching the filesystem. MCP
|
||||
// tool names come from a third-party server, so a name carrying path
|
||||
// separators is reachable input rather than a hypothetical.
|
||||
func TestWriteSpillSanitisesToolName(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
budget := NewTurnBudget(1_000_000, dir)
|
||||
|
||||
ref := budget.WriteSpill("../../etc/passwd", []byte("payload"))
|
||||
if ref.Path == "" {
|
||||
t.Fatal("spill was not written")
|
||||
}
|
||||
if filepath.Dir(ref.Path) != dir {
|
||||
t.Errorf("spill escaped to %q, want it inside %q", ref.Path, dir)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCapPayloadKeepsRunesIntact guards the truncation boundary: cutting a
|
||||
// multi-byte rune in half hands the model invalid UTF-8, which some providers
|
||||
// reject outright and others render as a replacement character mid-word.
|
||||
func TestCapPayloadKeepsRunesIntact(t *testing.T) {
|
||||
payload := strings.Repeat("é", 100) // 2 bytes per rune
|
||||
|
||||
for max := 1; max <= 20; max++ {
|
||||
got := CapPayload("read", payload, max, nil)
|
||||
if !utf8.ValidString(got) {
|
||||
t.Errorf("max=%d: CapPayload() returned invalid UTF-8: %q", max, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTurnBudgetSpillDirPermissions(t *testing.T) {
|
||||
// Create a regular file and use a sub-path as the spill directory.
|
||||
// Even root cannot write a file when a path component is a regular
|
||||
|
||||
@@ -4,6 +4,13 @@
|
||||
// Mutations from upstream:
|
||||
// - package renamed tools -> builtin (archie-core already has an
|
||||
// internal/tools package holding the registry these are registered into).
|
||||
// - path confinement is switchable (SetPathConfinement). tau's agent is a
|
||||
// coding assistant scoped to one project, where a workspace jail is always
|
||||
// right. archie's chat agent is also used as a general-purpose operator --
|
||||
// partitioning a disk and mounting it, migrating data between filesystems,
|
||||
// editing unit files -- and a jail makes that impossible. The shell tool
|
||||
// was never confined anyway, so the jail only ever shaped which tool got
|
||||
// used, not what the agent could reach.
|
||||
//
|
||||
// Refresh by diffing against that path at a newer tau commit. Do not
|
||||
// edit without recording the change above.
|
||||
@@ -14,6 +21,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -70,9 +78,41 @@ func isReadConfined(base, target string) bool {
|
||||
return cache != "" && isConfined(cache, target)
|
||||
}
|
||||
|
||||
// pathConfinement gates the workspace jail on the file tools. It defaults to
|
||||
// on; see SetPathConfinement.
|
||||
//
|
||||
// Process-wide rather than per-tool because it is a deployment posture, not a
|
||||
// property of one tool: a daemon either trusts its agent with the filesystem or
|
||||
// it does not, and there is one builtin tool set per process.
|
||||
var pathConfinement atomic.Bool
|
||||
|
||||
func init() { pathConfinement.Store(true) }
|
||||
|
||||
// SetPathConfinement turns the workspace jail on the read, write, edit, find
|
||||
// and grep tools on or off. It is set once at startup from configuration.
|
||||
//
|
||||
// Disabling it makes those tools reach any absolute path. That is the point:
|
||||
// an agent asked to partition a new disk, mount it and migrate data onto it is
|
||||
// working across the filesystem by definition, and a jail turns a capable
|
||||
// operator into a useless one.
|
||||
//
|
||||
// It widens which TOOL can do the work, not what the agent can reach. The shell
|
||||
// tool has never been confined -- it can cd anywhere, and only command.Hardline
|
||||
// screens it -- so a jailed deployment simply pushed the agent into doing
|
||||
// everything through shell, losing the truncation, line numbering,
|
||||
// read-before-write tracking and structured errors the dedicated tools provide.
|
||||
//
|
||||
// Relative paths still resolve against the workspace either way (see
|
||||
// resolvePath), so turning this off does not silently move where an existing
|
||||
// relative path lands.
|
||||
func SetPathConfinement(enabled bool) { pathConfinement.Store(enabled) }
|
||||
|
||||
// isConfined checks whether target is within (or equal to) the base directory.
|
||||
// Returns false if target escapes via ../ or is an unrelated absolute path.
|
||||
func isConfined(base, target string) bool {
|
||||
if !pathConfinement.Load() {
|
||||
return true // confinement disabled by configuration
|
||||
}
|
||||
if base == "" {
|
||||
return true // no confinement if cwd is unset
|
||||
}
|
||||
|
||||
@@ -9,6 +9,65 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestPathConfinementToggle covers the escape hatch for deployments where the
|
||||
// agent is a general-purpose operator rather than a coding assistant scoped to
|
||||
// one project -- formatting and mounting a new disk, migrating data between
|
||||
// filesystems, editing service units. Confining those to one directory makes
|
||||
// the agent useless, so the jail has to be switchable.
|
||||
//
|
||||
// Not parallel: the toggle is process-wide.
|
||||
func TestPathConfinementToggle(t *testing.T) {
|
||||
const workspace = "/home/sam"
|
||||
outside := []string{"/etc/fstab", "/mnt/newdisk/data", "/srv"}
|
||||
|
||||
t.Run("confined by default", func(t *testing.T) {
|
||||
for _, target := range outside {
|
||||
if isConfined(workspace, target) {
|
||||
t.Errorf("isConfined(%q, %q) = true, want false by default", workspace, target)
|
||||
}
|
||||
if isReadConfined(workspace, target) {
|
||||
t.Errorf("isReadConfined(%q, %q) = true, want false by default", workspace, target)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unconfined when disabled", func(t *testing.T) {
|
||||
SetPathConfinement(false)
|
||||
t.Cleanup(func() { SetPathConfinement(true) })
|
||||
|
||||
for _, target := range outside {
|
||||
if !isConfined(workspace, target) {
|
||||
t.Errorf("isConfined(%q, %q) = false with confinement disabled", workspace, target)
|
||||
}
|
||||
if !isReadConfined(workspace, target) {
|
||||
t.Errorf("isReadConfined(%q, %q) = false with confinement disabled", workspace, target)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("restored after re-enabling", func(t *testing.T) {
|
||||
if isConfined(workspace, "/etc/fstab") {
|
||||
t.Error("confinement did not come back after being re-enabled")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestResolvePathUnaffectedByConfinement pins the property that makes the
|
||||
// toggle safe to flip: relative paths stay rooted at the workspace either way,
|
||||
// so turning the jail off widens what an ABSOLUTE path can reach without
|
||||
// silently changing where a relative one lands.
|
||||
func TestResolvePathUnaffectedByConfinement(t *testing.T) {
|
||||
SetPathConfinement(false)
|
||||
t.Cleanup(func() { SetPathConfinement(true) })
|
||||
|
||||
if got := resolvePath("/home/sam", "notes.md"); got != "/home/sam/notes.md" {
|
||||
t.Errorf("resolvePath relative = %q, want it still rooted at the workspace", got)
|
||||
}
|
||||
if got := resolvePath("/home/sam", "/etc/fstab"); got != "/etc/fstab" {
|
||||
t.Errorf("resolvePath absolute = %q, want it untouched", got)
|
||||
}
|
||||
}
|
||||
|
||||
// withGoModCache points the module-cache lookup at a temp dir for the duration
|
||||
// of a test, so these tests never depend on the host's real GOMODCACHE.
|
||||
func withGoModCache(t *testing.T, dir string) {
|
||||
|
||||
+36
-39
@@ -329,6 +329,11 @@ func firstParallelSafeIdx(groups []gatedGroup) (int, bool) {
|
||||
|
||||
// dispatchOne runs a single call with budget, guardrail, and per-tool
|
||||
// limit checks.
|
||||
//
|
||||
// Callers that do not own the batch cannot use this: it caps
|
||||
// DispatchResult.Preview, whereas a caller handing the result straight to a
|
||||
// model has to cap the payload it actually sends. [CapPayload] is the shared
|
||||
// rule between the two; this sequence is specific to batch dispatch.
|
||||
func dispatchOne(
|
||||
ctx context.Context,
|
||||
call ToolCall,
|
||||
@@ -353,7 +358,7 @@ func dispatchOne(
|
||||
result := invokeTool(ctx, call)
|
||||
|
||||
// Enforce per-tool result size limit (17.4).
|
||||
enforcePerToolLimit(&result, call.Entry, budget)
|
||||
capped := enforcePerToolLimit(&result, call.Entry, budget)
|
||||
|
||||
// Track guardrail.
|
||||
if guardrail != nil {
|
||||
@@ -366,63 +371,55 @@ func dispatchOne(
|
||||
|
||||
// Consume budget.
|
||||
if budget != nil && !result.IsError() {
|
||||
consumeBudgetForResult(&result, call.Entry, budget)
|
||||
consumeBudgetForResult(&result, call.Entry, budget, capped)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// enforcePerToolLimit checks whether the result exceeds the tool's
|
||||
// MaxResultSizeChars and spills or truncates accordingly. When a budget
|
||||
// is available, the full output is spilled to disk; otherwise it is
|
||||
// truncated inline. If spill-to-disk fails, falls back to inline
|
||||
// truncation.
|
||||
func enforcePerToolLimit(result *DispatchResult, entry ToolEntry, budget *TurnBudget) {
|
||||
// enforcePerToolLimit replaces the preview when the result exceeds the tool's
|
||||
// MaxResultSizeChars, spilling to disk when the budget offers a directory and
|
||||
// truncating inline otherwise. [CapPayload] owns that rule; this only decides
|
||||
// whether it applies.
|
||||
//
|
||||
// Returns whether the result was capped, so the budget accounting below does
|
||||
// not spill the same output a second time.
|
||||
func enforcePerToolLimit(result *DispatchResult, entry ToolEntry, budget *TurnBudget) bool {
|
||||
if result.IsError() || entry.MaxResultSizeChars <= 0 || result.Output == nil {
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
fullOutput := fmt.Sprint(result.Output)
|
||||
if len(fullOutput) <= entry.MaxResultSizeChars {
|
||||
return
|
||||
}
|
||||
|
||||
// Result exceeds per-tool limit.
|
||||
if budget != nil {
|
||||
ref := budget.Spill(entry.Name, []byte(fullOutput))
|
||||
if ref.Path != "" {
|
||||
result.Preview = fmt.Sprintf("[spilled to %s, %d chars]", ref.Path, ref.SizeChars)
|
||||
return
|
||||
}
|
||||
// Spill failed -- fall through to inline truncation.
|
||||
}
|
||||
|
||||
// Truncate inline when no spill directory or spill failed.
|
||||
if entry.MaxResultSizeChars > 0 && len(fullOutput) > entry.MaxResultSizeChars {
|
||||
result.Preview = fullOutput[:entry.MaxResultSizeChars] +
|
||||
"... [truncated (per-tool limit)]"
|
||||
capped := CapPayload(entry.Name, fullOutput, entry.MaxResultSizeChars, budget)
|
||||
if capped == fullOutput {
|
||||
return false
|
||||
}
|
||||
result.Preview = capped
|
||||
return true
|
||||
}
|
||||
|
||||
// consumeBudgetForResult accounts for the result against the turn budget.
|
||||
// When the budget is exceeded during consumption, the full output is
|
||||
// spilled to disk and the preview is replaced with a spill reference.
|
||||
func consumeBudgetForResult(result *DispatchResult, entry ToolEntry, budget *TurnBudget) {
|
||||
func consumeBudgetForResult(result *DispatchResult, entry ToolEntry, budget *TurnBudget, alreadyCapped bool) {
|
||||
if budget == nil || result.IsError() {
|
||||
return
|
||||
}
|
||||
|
||||
// Only consume budget for fresh results (not already spilled by
|
||||
// per-tool limit enforcement).
|
||||
if !budget.Consume(len(result.Preview)) {
|
||||
// Budget exceeded on this result -- spill the full output.
|
||||
if result.Output != nil {
|
||||
fullOutput := fmt.Sprint(result.Output)
|
||||
ref := budget.Spill(entry.Name, []byte(fullOutput))
|
||||
if ref.Path != "" {
|
||||
result.Preview = fmt.Sprintf("[spilled to %s, %d chars]", ref.Path, ref.SizeChars)
|
||||
}
|
||||
}
|
||||
if budget.Consume(len(result.Preview)) {
|
||||
return
|
||||
}
|
||||
|
||||
// Budget exhausted on this result. Spill the full output so it is
|
||||
// displaced rather than lost -- unless the per-tool limit already did,
|
||||
// in which case repeating it would write a second identical file and
|
||||
// orphan the first, whose path the preview already names.
|
||||
if alreadyCapped || result.Output == nil {
|
||||
return
|
||||
}
|
||||
fullOutput := fmt.Sprint(result.Output)
|
||||
if ref := budget.WriteSpill(entry.Name, []byte(fullOutput)); ref.Path != "" {
|
||||
result.Preview = fmt.Sprintf("[spilled to %s, %d chars]", ref.Path, ref.SizeChars)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,11 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// maxTruncationNotice bounds the explanatory notice CapPayload appends when it
|
||||
// truncates inline. Tests assert the capped payload plus this allowance, so a
|
||||
// notice that grew without bound would fail rather than quietly eat context.
|
||||
const maxTruncationNotice = 128
|
||||
|
||||
func TestExecutionClassString(t *testing.T) {
|
||||
tests := []struct {
|
||||
c ExecutionClass
|
||||
@@ -612,10 +617,12 @@ func TestDispatchPerToolLimitSpillFailureFallback(t *testing.T) {
|
||||
}
|
||||
|
||||
// Should be truncated to MaxResultSizeChars even though spill failed.
|
||||
if !strings.Contains(results[0].Preview, "truncated (per-tool limit)") {
|
||||
if !strings.Contains(results[0].Preview, "truncated") {
|
||||
t.Errorf("expected inline truncation fallback, got: %s", results[0].Preview)
|
||||
}
|
||||
maxPreview := len("[... truncated (per-tool limit)]") + e.MaxResultSizeChars
|
||||
// The payload is cut to the limit; the notice explaining the cut is the
|
||||
// only thing allowed past it.
|
||||
maxPreview := e.MaxResultSizeChars + maxTruncationNotice
|
||||
if len(results[0].Preview) > maxPreview {
|
||||
t.Errorf("preview too long (%d chars), expected at most %d", len(results[0].Preview), maxPreview)
|
||||
}
|
||||
@@ -667,7 +674,7 @@ func TestDispatchPerToolLimitNoBudgetTruncates(t *testing.T) {
|
||||
if len(results) != 1 {
|
||||
t.Fatalf("expected 1 result, got %d", len(results))
|
||||
}
|
||||
if !strings.Contains(results[0].Preview, "truncated (per-tool limit)") {
|
||||
if !strings.Contains(results[0].Preview, "truncated") {
|
||||
t.Errorf("expected truncation with nil budget, got: %s", results[0].Preview)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,10 @@ type Provider struct {
|
||||
// workspace is the directory file and shell operations are rooted at.
|
||||
workspace string
|
||||
|
||||
// unrestricted lifts the workspace jail from the file tools. See
|
||||
// config.ChatConfig.UnrestrictedFilesystem for when that is wanted.
|
||||
unrestricted bool
|
||||
|
||||
// registry holds the constructed tools. Built once in Start so
|
||||
// Discover cannot partially fail.
|
||||
registry *toolsbuiltin.Registry
|
||||
@@ -36,8 +40,11 @@ type Provider struct {
|
||||
// New creates a provider rooted at workspace. An empty workspace is a
|
||||
// configuration error, reported by Start rather than silently defaulting to
|
||||
// the daemon's own working directory.
|
||||
func New(workspace string) *Provider {
|
||||
return &Provider{workspace: workspace}
|
||||
//
|
||||
// unrestricted lets the file tools reach absolute paths outside workspace;
|
||||
// relative paths still resolve against it either way.
|
||||
func New(workspace string, unrestricted bool) *Provider {
|
||||
return &Provider{workspace: workspace, unrestricted: unrestricted}
|
||||
}
|
||||
|
||||
// Manifest declares the adapter's tool capability.
|
||||
@@ -59,6 +66,11 @@ func (p *Provider) Start(ctx context.Context) error {
|
||||
if p.workspace == "" {
|
||||
return errors.New("workspace tool provider: workspace directory is not configured")
|
||||
}
|
||||
// Set before the tools are built. Confinement is consulted per call, so
|
||||
// ordering only matters in that it must precede the first tool call, but
|
||||
// keeping it next to construction is where a reader will look for it.
|
||||
toolsbuiltin.SetPathConfinement(!p.unrestricted)
|
||||
|
||||
registry := toolsbuiltin.NewRegistry()
|
||||
if err := toolsbuiltin.RegisterBuiltins(registry, p.workspace); err != nil {
|
||||
return fmt.Errorf("workspace tool provider: register builtins: %w", err)
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
func startedProvider(t *testing.T, workspace string) *provider.Provider {
|
||||
t.Helper()
|
||||
p := provider.New(workspace)
|
||||
p := provider.New(workspace, false)
|
||||
if err := p.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
@@ -155,7 +155,80 @@ func shellHandler(t *testing.T, workspace string) func(context.Context, map[stri
|
||||
func TestUnconfiguredWorkspaceIsRejected(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if err := provider.New("").Start(context.Background()); err == nil {
|
||||
if err := provider.New("", false).Start(context.Background()); err == nil {
|
||||
t.Error("a provider with no workspace started successfully")
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnrestrictedFilesystemReachesOutsideWorkspace covers the operator
|
||||
// posture end to end, through a real read of a real file.
|
||||
//
|
||||
// A deployment whose agent partitions disks, mounts them and migrates data is
|
||||
// working across the filesystem by definition. Confined, every one of those
|
||||
// touches has to go through shell -- which was never confined anyway -- so the
|
||||
// jail only ever decided which tool did the work, not what the agent reached.
|
||||
//
|
||||
// Not parallel: confinement is process-wide, so these two subtests must not
|
||||
// run beside tests that assume the default.
|
||||
func TestUnrestrictedFilesystemReachesOutsideWorkspace(t *testing.T) {
|
||||
// A file deliberately outside the workspace, as /etc or a fresh mount
|
||||
// would be.
|
||||
outside := filepath.Join(t.TempDir(), "fstab")
|
||||
if err := os.WriteFile(outside, []byte("UUID=1234 /mnt/newdisk ext4 defaults 0 2\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
unrestricted bool
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "confined refuses", unrestricted: false, wantErr: true},
|
||||
{name: "unrestricted reads", unrestricted: true},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p := provider.New(t.TempDir(), tc.unrestricted)
|
||||
if err := p.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
|
||||
entries, err := p.Discover(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var read func(context.Context, map[string]any) (any, error)
|
||||
for _, e := range entries {
|
||||
if e.Name == "read" {
|
||||
read = e.Handler
|
||||
}
|
||||
}
|
||||
if read == nil {
|
||||
t.Fatal("no read tool discovered")
|
||||
}
|
||||
|
||||
out, err := read(context.Background(), map[string]any{"path": outside})
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("read reached outside the workspace while confined")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("read was refused with confinement disabled: %v", err)
|
||||
}
|
||||
if text, ok := out.(string); !ok || !strings.Contains(text, "/mnt/newdisk") {
|
||||
t.Errorf("read returned %#v, want the file contents", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Leave the process as we found it for any test that runs after.
|
||||
t.Cleanup(func() {
|
||||
p := provider.New(t.TempDir(), false)
|
||||
_ = p.Start(context.Background())
|
||||
_ = p.Stop(context.Background())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package webfetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// ToolName is the registry name of the fetch tool.
|
||||
const ToolName = "web_fetch"
|
||||
|
||||
// Tool builds the registry entry for cfg, or nil when the fetcher is
|
||||
// disabled. Returning nil rather than an entry that always refuses keeps a
|
||||
// capability the operator turned off out of the model's tool list entirely --
|
||||
// an advertised tool that never works costs a round trip to discover.
|
||||
func Tool(cfg Config) *tools.ToolEntry {
|
||||
if !cfg.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
client := New(cfg)
|
||||
|
||||
return &tools.ToolEntry{
|
||||
Name: ToolName,
|
||||
Toolset: "web",
|
||||
Description: "Fetch a web page or API response over http/https and return its readable text. " +
|
||||
"HTML is reduced to text; JSON, XML and plain text are returned as received. " +
|
||||
"Use it to read documentation, changelogs, issues or any URL the user provides.",
|
||||
// Reading a URL has no side effect on this host, so it is safe to
|
||||
// run alongside other reads.
|
||||
Classification: tools.ClassIdempotent,
|
||||
Schema: tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"url": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Absolute http:// or https:// URL to fetch.",
|
||||
},
|
||||
"raw": map[string]any{
|
||||
"type": "boolean",
|
||||
"description": "Return the response body unchanged instead of extracting readable text from HTML. Defaults to false.",
|
||||
},
|
||||
},
|
||||
"required": []any{"url"},
|
||||
},
|
||||
Handler: func(ctx context.Context, input map[string]any) (any, error) {
|
||||
target, _ := input["url"].(string)
|
||||
if strings.TrimSpace(target) == "" {
|
||||
return nil, fmt.Errorf("%s: url is required", ToolName)
|
||||
}
|
||||
raw, _ := input["raw"].(bool)
|
||||
|
||||
body, err := client.Fetch(ctx, target, raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", ToolName, err)
|
||||
}
|
||||
return body, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
// Package webfetch retrieves a URL on the model's behalf and returns readable
|
||||
// text.
|
||||
//
|
||||
// The interesting part is not the fetch, it is the refusals. archied runs on a
|
||||
// host where the Docker API, NATS and its own dashboard answer on private
|
||||
// addresses, and the URL it is asked to fetch arrives in chat -- an untrusted
|
||||
// path, since a forge issue body or an inbound email can end up quoted into a
|
||||
// turn. So the address is vetted at dial time rather than by inspecting the
|
||||
// URL: a name that looks public can resolve to a private address, and only the
|
||||
// resolved address tells the truth.
|
||||
package webfetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxRedirects bounds a redirect chain. Each hop is re-vetted by the
|
||||
// dialer, so this only stops a loop from spending the timeout.
|
||||
maxRedirects = 5
|
||||
|
||||
// statusExcerpt is how much of a failed response body is quoted back.
|
||||
// Enough to tell an API error message from an HTML error page.
|
||||
statusExcerpt = 200
|
||||
)
|
||||
|
||||
// Config controls the fetcher. The zero value is disabled.
|
||||
type Config struct {
|
||||
// Enabled advertises the tool. When false, Tool returns nil so the
|
||||
// model is never shown a capability the operator turned off.
|
||||
Enabled bool
|
||||
|
||||
// Timeout bounds one fetch, redirects included.
|
||||
Timeout time.Duration
|
||||
|
||||
// MaxBytes bounds how much of a response body is read.
|
||||
MaxBytes int64
|
||||
|
||||
// AllowPrivateNetworks permits loopback, private, link-local and
|
||||
// carrier-grade-NAT addresses. Off by default: leaving it off is what
|
||||
// keeps the daemon's own control surfaces out of reach.
|
||||
AllowPrivateNetworks bool
|
||||
}
|
||||
|
||||
// Client fetches URLs under a Config.
|
||||
type Client struct {
|
||||
cfg Config
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
// New builds a Client whose transport refuses disallowed addresses at dial
|
||||
// time.
|
||||
func New(cfg Config) *Client {
|
||||
c := &Client{cfg: cfg}
|
||||
transport := &http.Transport{
|
||||
DialContext: c.dialContext,
|
||||
TLSHandshakeTimeout: cfg.Timeout,
|
||||
ResponseHeaderTimeout: cfg.Timeout,
|
||||
DisableKeepAlives: true,
|
||||
}
|
||||
c.http = &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: cfg.Timeout,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= maxRedirects {
|
||||
return fmt.Errorf("stopped after %d redirects", maxRedirects)
|
||||
}
|
||||
return checkScheme(req.URL)
|
||||
},
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// Fetch retrieves rawURL and returns its readable content. When raw is true
|
||||
// the body is returned as received rather than reduced to text.
|
||||
func (c *Client) Fetch(ctx context.Context, rawURL string, raw bool) (string, error) {
|
||||
parsed, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid url %q: %w", rawURL, err)
|
||||
}
|
||||
if err := checkScheme(parsed); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
// Some sites serve a different, poorer page to an unidentified client,
|
||||
// and a few refuse one outright.
|
||||
req.Header.Set("User-Agent", "archie-webfetch/1.0 (+https://github.com/samcharles93/archie-core)")
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,text/plain,application/json;q=0.9,*/*;q=0.1")
|
||||
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return "", unwrapFetchError(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, truncated, err := c.readBody(resp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("%s returned %d %s: %s",
|
||||
parsed.Redacted(), resp.StatusCode, http.StatusText(resp.StatusCode), excerpt(body))
|
||||
}
|
||||
|
||||
mediaType := contentType(resp)
|
||||
rendered, err := render(mediaType, body, raw, len(body))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if truncated {
|
||||
rendered += fmt.Sprintf("\n\n[webfetch: response truncated at %d bytes]", c.cfg.MaxBytes)
|
||||
}
|
||||
return rendered, nil
|
||||
}
|
||||
|
||||
// readBody reads at most MaxBytes, reporting whether more was available.
|
||||
func (c *Client) readBody(resp *http.Response) (string, bool, error) {
|
||||
limit := c.cfg.MaxBytes
|
||||
if limit <= 0 {
|
||||
limit = 1 << 20
|
||||
}
|
||||
// One byte past the limit distinguishes "exactly at the limit" from
|
||||
// "there was more".
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return string(data[:limit]), true, nil
|
||||
}
|
||||
return string(data), false, nil
|
||||
}
|
||||
|
||||
// render turns a body into what the model sees, refusing anything that is not
|
||||
// text. Returning binary would spend the context window on bytes the model
|
||||
// cannot read.
|
||||
func render(mediaType, body string, raw bool, size int) (string, error) {
|
||||
switch {
|
||||
case raw:
|
||||
return body, nil
|
||||
case mediaType == "text/html", mediaType == "application/xhtml+xml":
|
||||
return htmlToText(body), nil
|
||||
case strings.HasPrefix(mediaType, "text/"),
|
||||
mediaType == "application/json",
|
||||
mediaType == "application/xml",
|
||||
strings.HasSuffix(mediaType, "+json"),
|
||||
strings.HasSuffix(mediaType, "+xml"):
|
||||
return body, nil
|
||||
default:
|
||||
return "", fmt.Errorf("refusing %s (%d bytes): only text, html, json and xml are readable", mediaType, size)
|
||||
}
|
||||
}
|
||||
|
||||
// contentType returns the media type without parameters, defaulting to plain
|
||||
// text when the server sends nothing.
|
||||
func contentType(resp *http.Response) string {
|
||||
raw := resp.Header.Get("Content-Type")
|
||||
if raw == "" {
|
||||
return "text/plain"
|
||||
}
|
||||
if i := strings.IndexByte(raw, ';'); i >= 0 {
|
||||
raw = raw[:i]
|
||||
}
|
||||
return strings.ToLower(strings.TrimSpace(raw))
|
||||
}
|
||||
|
||||
// excerpt quotes the start of a failed response so the model can tell an API
|
||||
// error message from a generic error page.
|
||||
func excerpt(body string) string {
|
||||
body = strings.TrimSpace(body)
|
||||
if len(body) <= statusExcerpt {
|
||||
return body
|
||||
}
|
||||
return body[:statusExcerpt] + "..."
|
||||
}
|
||||
|
||||
// checkScheme allows only http and https. Anything else -- file:, data:,
|
||||
// gopher: -- reaches something that is not a web server.
|
||||
func checkScheme(u *url.URL) error {
|
||||
switch u.Scheme {
|
||||
case "http", "https":
|
||||
return nil
|
||||
case "":
|
||||
return fmt.Errorf("url %q has no scheme: give an absolute http:// or https:// url", u.String())
|
||||
default:
|
||||
return fmt.Errorf("refusing scheme %q: only http and https are fetched", u.Scheme)
|
||||
}
|
||||
}
|
||||
|
||||
// unwrapFetchError strips the url.Error wrapper so the refusal the dialer or
|
||||
// the redirect check produced is what the model reads, rather than being
|
||||
// buried behind Go's transport prose.
|
||||
func unwrapFetchError(err error) error {
|
||||
var urlErr *url.Error
|
||||
if errors.As(err, &urlErr) && urlErr.Err != nil {
|
||||
return urlErr.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// dialContext resolves the host and refuses addresses the daemon must not be
|
||||
// talked into reaching, then dials a vetted address directly.
|
||||
//
|
||||
// Vetting here rather than on the URL is the whole point: between a pre-flight
|
||||
// check and the connection, a name can resolve to something else. Dialing the
|
||||
// address that was actually approved closes that window.
|
||||
func (c *Client) dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid address %q: %w", addr, err)
|
||||
}
|
||||
|
||||
ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dialer := &net.Dialer{Timeout: c.cfg.Timeout}
|
||||
var refused []string
|
||||
for _, ip := range ips {
|
||||
if !c.addressAllowed(ip.IP) {
|
||||
refused = append(refused, ip.IP.String())
|
||||
continue
|
||||
}
|
||||
conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(ip.IP.String(), port))
|
||||
if err == nil {
|
||||
return conn, nil
|
||||
}
|
||||
}
|
||||
|
||||
if len(refused) > 0 {
|
||||
return nil, fmt.Errorf(
|
||||
"refusing to connect to %s: it resolves to the private or loopback address %s, which is where this host's own services live; set tools.web_fetch.allow_private_networks to permit it",
|
||||
host, strings.Join(refused, ", "))
|
||||
}
|
||||
return nil, fmt.Errorf("could not connect to %s", host)
|
||||
}
|
||||
|
||||
// addressAllowed reports whether an address may be reached.
|
||||
func (c *Client) addressAllowed(ip net.IP) bool {
|
||||
if c.cfg.AllowPrivateNetworks {
|
||||
return true
|
||||
}
|
||||
switch {
|
||||
case ip.IsLoopback(), ip.IsPrivate(), ip.IsUnspecified(),
|
||||
ip.IsLinkLocalUnicast(), ip.IsLinkLocalMulticast(),
|
||||
ip.IsInterfaceLocalMulticast(), ip.IsMulticast():
|
||||
return false
|
||||
case isCarrierGradeNAT(ip):
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// isCarrierGradeNAT reports whether ip is in 100.64.0.0/10, which net.IP has
|
||||
// no predicate for and which routes to infrastructure rather than the public
|
||||
// internet.
|
||||
func isCarrierGradeNAT(ip net.IP) bool {
|
||||
v4 := ip.To4()
|
||||
return v4 != nil && v4[0] == 100 && v4[1] >= 64 && v4[1] <= 127
|
||||
}
|
||||
|
||||
// blockedElements hold text that is markup machinery rather than content.
|
||||
var blockedElements = map[string]bool{
|
||||
"script": true, "style": true, "noscript": true,
|
||||
"head": true, "template": true, "svg": true,
|
||||
}
|
||||
|
||||
// htmlToText reduces a document to the text a reader would see. It is
|
||||
// deliberately simple: the goal is to spend the context window on prose
|
||||
// instead of markup, not to reproduce a browser.
|
||||
func htmlToText(body string) string {
|
||||
doc, err := html.Parse(strings.NewReader(body))
|
||||
if err != nil {
|
||||
// Unparseable markup still has readable text in it; handing back
|
||||
// the raw document beats returning nothing.
|
||||
return body
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
var walk func(*html.Node)
|
||||
walk = func(n *html.Node) {
|
||||
if n.Type == html.ElementNode && blockedElements[n.Data] {
|
||||
return
|
||||
}
|
||||
if n.Type == html.TextNode {
|
||||
if text := strings.TrimSpace(n.Data); text != "" {
|
||||
b.WriteString(text)
|
||||
b.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
for child := n.FirstChild; child != nil; child = child.NextSibling {
|
||||
walk(child)
|
||||
}
|
||||
// Block-level elements end a line so headings and paragraphs do not
|
||||
// run together into one wall of text.
|
||||
if n.Type == html.ElementNode && breaksLine(n.Data) {
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
}
|
||||
walk(doc)
|
||||
|
||||
return collapseBlankLines(b.String())
|
||||
}
|
||||
|
||||
// breaksLine reports whether an element should end the current line.
|
||||
func breaksLine(tag string) bool {
|
||||
switch tag {
|
||||
case "p", "div", "br", "li", "tr", "section", "article", "header", "footer",
|
||||
"h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "pre":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// collapseBlankLines trims each line and squeezes runs of blank lines, which
|
||||
// nested markup produces in quantity.
|
||||
func collapseBlankLines(s string) string {
|
||||
lines := strings.Split(s, "\n")
|
||||
out := make([]string, 0, len(lines))
|
||||
blank := false
|
||||
for _, line := range lines {
|
||||
line = strings.Join(strings.Fields(line), " ")
|
||||
if line == "" {
|
||||
if blank {
|
||||
continue
|
||||
}
|
||||
blank = true
|
||||
} else {
|
||||
blank = false
|
||||
}
|
||||
out = append(out, line)
|
||||
}
|
||||
return strings.TrimSpace(strings.Join(out, "\n"))
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package webfetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// testConfig is the base every case starts from. Private networks are allowed
|
||||
// because httptest binds loopback; the cases that exercise the SSRF control
|
||||
// override it explicitly.
|
||||
func testConfig() Config {
|
||||
return Config{
|
||||
Enabled: true,
|
||||
Timeout: 5 * time.Second,
|
||||
MaxBytes: 1 << 20,
|
||||
AllowPrivateNetworks: true,
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchExtractsContent(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
contentType string
|
||||
body string
|
||||
raw bool
|
||||
wantContain []string
|
||||
wantAbsent []string
|
||||
}{
|
||||
{
|
||||
name: "html is reduced to readable text",
|
||||
contentType: "text/html; charset=utf-8",
|
||||
body: `<html><head><title>T</title>
|
||||
<style>body{color:red}</style>
|
||||
<script>var x = "should not appear";</script></head>
|
||||
<body><h1>Heading</h1><p>Body text here.</p></body></html>`,
|
||||
wantContain: []string{"Heading", "Body text here."},
|
||||
wantAbsent: []string{"should not appear", "color:red", "<p>"},
|
||||
},
|
||||
{
|
||||
name: "raw returns the html unmodified",
|
||||
contentType: "text/html",
|
||||
body: `<p>markup</p>`,
|
||||
raw: true,
|
||||
wantContain: []string{"<p>markup</p>"},
|
||||
},
|
||||
{
|
||||
name: "json passes through untouched",
|
||||
contentType: "application/json",
|
||||
body: `{"key":"value"}`,
|
||||
wantContain: []string{`{"key":"value"}`},
|
||||
},
|
||||
{
|
||||
name: "plain text passes through untouched",
|
||||
contentType: "text/plain",
|
||||
body: "just words",
|
||||
wantContain: []string{"just words"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", tc.contentType)
|
||||
fmt.Fprint(w, tc.body)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
got, err := New(testConfig()).Fetch(context.Background(), srv.URL, tc.raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range tc.wantContain {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("result %q does not contain %q", got, want)
|
||||
}
|
||||
}
|
||||
for _, absent := range tc.wantAbsent {
|
||||
if strings.Contains(got, absent) {
|
||||
t.Errorf("result %q should not contain %q", got, absent)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchRejectsUnsupportedContentType(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
fmt.Fprint(w, "\x89PNG\r\n\x1a\n")
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() error = nil, want a refusal naming the content type")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "image/png") {
|
||||
t.Errorf("error = %v, want it to name the content type", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchCapsBodySize(t *testing.T) {
|
||||
const limit = 512
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
fmt.Fprint(w, strings.Repeat("a", limit*10))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cfg := testConfig()
|
||||
cfg.MaxBytes = limit
|
||||
got, err := New(cfg).Fetch(context.Background(), srv.URL, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) > limit*2 { // body plus a truncation notice, nowhere near 10x
|
||||
t.Errorf("result is %d bytes, want it bounded near the %d-byte limit", len(got), limit)
|
||||
}
|
||||
if !strings.Contains(got, "truncated") {
|
||||
t.Errorf("result %q should say it was truncated", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchReportsHTTPStatus(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{name: "not found", status: http.StatusNotFound, body: "no such page"},
|
||||
{name: "forbidden", status: http.StatusForbidden, body: "denied"},
|
||||
{name: "rate limited", status: http.StatusTooManyRequests, body: "slow down"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(tc.status)
|
||||
fmt.Fprint(w, tc.body)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatalf("Fetch() error = nil, want the %d reported", tc.status)
|
||||
}
|
||||
// The model has to tell 404 from 403 from a rate limit to decide
|
||||
// whether retrying or rewording the URL is worth it.
|
||||
if !strings.Contains(err.Error(), fmt.Sprint(tc.status)) {
|
||||
t.Errorf("error = %v, want it to carry status %d", err, tc.status)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.body) {
|
||||
t.Errorf("error = %v, want it to carry a body excerpt", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchCapsRedirects(t *testing.T) {
|
||||
var srv *httptest.Server
|
||||
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, srv.URL+"/next", http.StatusFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, err := New(testConfig()).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() error = nil, want a redirect-limit refusal")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "redirect") {
|
||||
t.Errorf("error = %v, want it to name the redirect limit", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchRejectsUnsupportedSchemes(t *testing.T) {
|
||||
tests := []string{
|
||||
"file:///etc/passwd",
|
||||
"ftp://example.com/x",
|
||||
"gopher://example.com",
|
||||
"data:text/plain,hello",
|
||||
"not-a-url",
|
||||
}
|
||||
|
||||
for _, target := range tests {
|
||||
t.Run(target, func(t *testing.T) {
|
||||
_, err := New(testConfig()).Fetch(context.Background(), target, false)
|
||||
if err == nil {
|
||||
t.Fatalf("Fetch(%q) error = nil, want a scheme refusal", target)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchBlocksPrivateAddresses is the SSRF control. archied runs on a host
|
||||
// where the Docker API, NATS and its own dashboard are reachable on private
|
||||
// addresses, so a model that can be talked into fetching one of those is a
|
||||
// real hole. httptest binds loopback, which makes it exactly the case to
|
||||
// assert against.
|
||||
func TestFetchBlocksPrivateAddresses(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
fmt.Fprint(w, "internal service")
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
t.Run("blocked by default", func(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.AllowPrivateNetworks = false
|
||||
_, err := New(cfg).Fetch(context.Background(), srv.URL, false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() reached a loopback address, want a refusal")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "private") && !strings.Contains(err.Error(), "loopback") {
|
||||
t.Errorf("error = %v, want it to explain the address was refused", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allowed when configured", func(t *testing.T) {
|
||||
cfg := testConfig() // AllowPrivateNetworks is true
|
||||
got, err := New(cfg).Fetch(context.Background(), srv.URL, false)
|
||||
if err != nil {
|
||||
t.Fatalf("Fetch() with private networks allowed: %v", err)
|
||||
}
|
||||
if !strings.Contains(got, "internal service") {
|
||||
t.Errorf("result = %q, want the body", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestFetchBlocksAtDialTime proves the check is on the resolved address rather
|
||||
// than on the URL string. A hostname that looks public but resolves to a
|
||||
// private address must still be refused, which a pre-flight URL check cannot
|
||||
// do and which is how DNS-rebinding defeats one.
|
||||
func TestFetchBlocksAtDialTime(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.AllowPrivateNetworks = false
|
||||
|
||||
// localtest.me and its subdomains are a public DNS name resolving to
|
||||
// 127.0.0.1. Resolution may be unavailable in a sandbox, so a lookup
|
||||
// failure is not a test failure -- but a success must be a refusal.
|
||||
_, err := New(cfg).Fetch(context.Background(), "http://localtest.me/", false)
|
||||
if err == nil {
|
||||
t.Fatal("Fetch() reached a public name resolving to loopback, want a refusal")
|
||||
}
|
||||
if strings.Contains(err.Error(), "scheme") {
|
||||
t.Errorf("error = %v, want an address refusal rather than a scheme refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolDisabledReturnsNil(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.Enabled = false
|
||||
if Tool(cfg) != nil {
|
||||
t.Error("Tool() returned an entry while disabled, want nil so it is not advertised")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolRejectsMissingURL(t *testing.T) {
|
||||
entry := Tool(testConfig())
|
||||
if entry == nil {
|
||||
t.Fatal("Tool() = nil, want an entry when enabled")
|
||||
}
|
||||
if _, err := entry.Handler(context.Background(), map[string]any{}); err == nil {
|
||||
t.Error("Handler() error = nil, want a refusal when url is absent")
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
@@ -70,7 +71,7 @@ func (s *Server) chatReady(w http.ResponseWriter) (*ChatService, bool) {
|
||||
http.Error(w, "chat is not configured", http.StatusNotImplemented)
|
||||
return nil, false
|
||||
}
|
||||
if s.Chat.Router.Updates == nil && s.Chat.Updates != nil {
|
||||
if !chatUpdateServiceConfigured(s.Chat.Router.Updates) && chatUpdateServiceConfigured(s.Chat.Updates) {
|
||||
s.Chat.Router.Updates = s.Chat.Updates
|
||||
}
|
||||
if s.Chat.Router.Dangerous == nil && s.Chat.Dangerous != nil {
|
||||
@@ -79,6 +80,19 @@ func (s *Server) chatReady(w http.ResponseWriter) (*ChatService, bool) {
|
||||
return s.Chat, true
|
||||
}
|
||||
|
||||
func chatUpdateServiceConfigured(updates ChatUpdateService) bool {
|
||||
if updates == nil {
|
||||
return false
|
||||
}
|
||||
value := reflect.ValueOf(updates)
|
||||
switch value.Kind() {
|
||||
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
|
||||
return !value.IsNil()
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
if !ok {
|
||||
@@ -329,7 +343,7 @@ func (s *Server) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if chat.Updates == nil {
|
||||
if !chatUpdateServiceConfigured(chat.Updates) {
|
||||
http.Error(w, "updates are not configured", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
@@ -350,7 +364,7 @@ func (s *Server) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if chat.Updates == nil {
|
||||
if !chatUpdateServiceConfigured(chat.Updates) {
|
||||
http.Error(w, "updates are not configured", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
@@ -371,7 +385,7 @@ func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if chat.Updates == nil || !chat.Updates.CanInstall() {
|
||||
if !chatUpdateServiceConfigured(chat.Updates) || !chat.Updates.CanInstall() {
|
||||
http.Error(w, "update installation is not configured", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -256,6 +256,20 @@ func TestChatUpdateEndpoints(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatUpdateEndpointRejectsTypedNilService(t *testing.T) {
|
||||
var updates *releaseupdate.Service
|
||||
sessions := gateway.NewSessionStoreMemory("test")
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
|
||||
server := &Server{Chat: &ChatService{Router: router, Sessions: sessions, Updates: updates}}
|
||||
|
||||
res := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(res, httptest.NewRequest(http.MethodGet, "/api/chat/update", nil))
|
||||
if res.Code != http.StatusNotImplemented {
|
||||
t.Fatalf("typed-nil update service status = %d, body = %s", res.Code, res.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatDangerousApprovalEndpoints(t *testing.T) {
|
||||
sessions := gateway.NewSessionStoreMemory("test")
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
|
||||
Reference in new issue
Block a user