refactor: pre-cleanup.

This commit is contained in:
sam committed 2026-08-06 01:40:15 +10:00
1 parent 0ceab9d897
commit e10cbbc92c
53 files changed
+3596 -648

No files matched your search

+133 -14
View File
@@ -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()
+273
View File
@@ -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
+40
View File
@@ -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
}
+59
View File
@@ -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
View File
@@ -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)
}
}
+10 -3
View File
@@ -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)
}
}
+14 -2
View File
@@ -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())
})
}
+62
View File
@@ -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
},
}
}
+352
View File
@@ -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"))
}
+272
View File
@@ -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")
}
}