Files
archie/internal/tools/builtin/stderr_redact.go
T
sam e03cef17c9 feat(tools): lift tau's file and shell tools into the tool registry
The chat agent had two tools -- memory_edit and skill_activate -- so it
could not read a file, search a tree or run a command. ai-sdk's runtime
already drives a tool loop for it (MaxSteps 8, toolExecute wired as the
executor), so the loop was never the missing piece: the registry was empty
of anything useful.

Lifted from tau internal/agent/tools at commit f5289ea, per the recorded
copy-and-mutate strategy: every file carries a provenance header naming its
tau source path, the commit, and the mutations made, so refreshing from
upstream is a diff rather than archaeology.

  internal/tools/builtin/          the lifted tools, ~3.1k lines
  internal/tools/provider/builtin/ the adapter to tools.ToolEntry

Six tools: read, write, edit, shell, grep, find. Tau's own tests came with
them and pass unmodified, which is the evidence that the lift is faithful.

Deliberately not lifted:
  - agent.go (1214 lines): subagent spawning, and the only real coupling in
    the package -- 10 tau packages including chat, sessions, store and
    registry. Nothing the chat agent needs to do work.
  - skill.go: depends on tau's skills package; archie has internal/skill and
    already exposes skill_activate.
  - docs.go: serves tau's own embedded documentation via tau/docs.

Not lifting the coordinator either. It is tau's agent loop (6.4k lines over
ten packages) and archie already has one in the ai-sdk runtime; porting it
would leave two loops competing. Its cancellation and tool events are worth
having, but they are a few hundred lines built against the existing path
rather than six thousand lifted onto a second one.

The adapter bridges two shape differences: archie hands handlers decoded
arguments where tau's executor takes raw JSON, and tau reports tool-level
failure in Result.IsError rather than as an error -- surfaced as a real
error so the runtime and the guardrail engine both see it. Tools are
classified idempotent or mutating for guardrails and budgets; that is
categorisation, not a jail.

chat.workspace roots the tools and defaults to empty, which registers none
of them. They read, write and execute, so the directory has to be a
deliberate choice rather than whatever the daemon started in -- in the
container that is /.

Verified: go build, go vet, gofmt clean; full suite passes.
2026-07-29 15:46:21 +10:00

112 lines
4.1 KiB
Go

// Lifted from tau internal/agent/tools/stderr_redact.go
// tau commit f5289ea3782c099339c2d26fe3af8ebcf42ba52d (2026-07-27).
//
// Mutations from upstream:
// - package renamed tools -> builtin (archie-core already has an
// internal/tools package holding the registry these are registered into).
//
// Refresh by diffing against that path at a newer tau commit. Do not
// edit without recording the change above.
package builtin
import (
"bufio"
"io"
"log/slog"
"regexp"
"time"
)
// Redaction patterns per docs/specs/agents/03-wire-protocol.md (stderr
// handling: Redaction) and 02-spawning-and-lifecycle.md (Redaction
// contract). reBearerToken has no minimum length - the spec's own
// redaction test requirement uses a 10-character example token
// ("tok_abc123"), shorter than the {20,} it documents elsewhere for the
// sk- pattern, so this errs toward redacting too much rather than missing
// the documented test case.
var (
reBearerToken = regexp.MustCompile(`Bearer\s+[a-zA-Z0-9_\-.]+`)
reSkKey = regexp.MustCompile(`sk-[a-zA-Z0-9]{20,}`)
reEnvSecret = regexp.MustCompile(`(?i)\b([A-Za-z_]*(?:KEY|TOKEN|SECRET|PASSWORD)[A-Za-z_]*)=\S+`)
)
// redactSecrets replaces known secret patterns in a single stderr line with
// [REDACTED]. Order matters only for overlap avoidance; re-matching an
// already-redacted "[REDACTED]" value is harmless (idempotent).
func redactSecrets(line string) string {
line = reBearerToken.ReplaceAllString(line, "Bearer [REDACTED]")
line = reSkKey.ReplaceAllString(line, "[REDACTED]")
line = reEnvSecret.ReplaceAllString(line, "$1=[REDACTED]")
return line
}
const (
// stderrRateLimitBytesPerSec and stderrRateLimitWindow implement "4096
// bytes per second, averaged over a 5-second window" - bursts within
// the window are allowed (a full panic trace is captured), sustained
// high-volume output past the window budget is truncated.
stderrRateLimitBytesPerSec = 4096
stderrRateLimitWindow = 5 * time.Second
// stderrMaxCaptureBytes is the total per-instance capture cap; excess
// is discarded (the pipe is still drained so a chatty child never
// blocks on a full stderr pipe buffer).
stderrMaxCaptureBytes = 64 * 1024
)
// drainChildStderr reads r line-by-line, redacts known secret patterns,
// rate-limits and caps total capture, and logs surviving lines at ERROR
// level tagged with the child's instance ID. Never parsed for protocol
// messages - stderr is diagnostic-only (see docs/specs/agents/
// 03-wire-protocol.md). Blocks until r is exhausted (EOF on process exit);
// callers run it in its own goroutine.
func drainChildStderr(r io.Reader, instanceID string) {
drainChildStderrWithClock(r, instanceID, time.Now)
}
// drainChildStderrWithClock is drainChildStderr with an injectable clock,
// so tests can advance the rate-limit window deterministically instead of
// depending on real wall-clock time passing between reads.
func drainChildStderrWithClock(r io.Reader, instanceID string, now func() time.Time) {
scanner := bufio.NewScanner(r)
scanner.Buffer(make([]byte, 4096), 1024*1024) // tolerate long lines without unbounded growth
windowBudget := stderrRateLimitBytesPerSec * int(stderrRateLimitWindow/time.Second)
var (
totalCaptured int
capReported bool
windowStart = now()
windowBytes int
rateLimitedThisWindow bool
)
for scanner.Scan() {
line := scanner.Text()
lineBytes := len(line) + 1 // + newline, matching the byte-budget the spec describes
if totalCaptured >= stderrMaxCaptureBytes {
if !capReported {
slog.Error("[... stderr truncated: capture limit exceeded ...]", "instance_id", instanceID)
capReported = true
}
continue
}
if t := now(); t.Sub(windowStart) >= stderrRateLimitWindow {
windowStart = t
windowBytes = 0
rateLimitedThisWindow = false
}
windowBytes += lineBytes
if windowBytes > windowBudget {
if !rateLimitedThisWindow {
slog.Error("[... stderr truncated: rate limit exceeded ...]", "instance_id", instanceID)
rateLimitedThisWindow = true
}
continue
}
totalCaptured += lineBytes
slog.Error(redactSecrets(line), "instance_id", instanceID)
}
}