build: 内置 norma 模块,构建不再依赖上游仓库

把 github.com/Autumn-27/norma v0.4.3(commit 320ae32)的源码复制到
third_party/norma,并用 go.mod 的 replace 指向本地副本。上游删除仓库或
改写 tag 都不再影响本仓库构建。

- 已验证 GOPROXY=off 下可完整编译并打出发行包
- go.sum 中该模块的两条校验记录随之删除(本地 replace 不需要哈希)
- 升级方法与授权注意事项见 third_party/README.md
This commit is contained in:
wangdefa committed 2026-10-20 21:10:41 -07:00
1 parent a819fa3230
commit f782b612ec
213 files changed
+37401 -2

No files matched your search

+120
View File
@@ -0,0 +1,120 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/Autumn-27/norma/permission"
)
// Option is one selectable choice for an AskUserQuestion.
type Option struct {
Label string
Description string
}
// Question is a single structured question the agent poses mid-task.
type Question struct {
Header string // short label/category, e.g. "Auth method"
Question string // the full question text
Options []Option
MultiSelect bool
}
// Answer is the user's response to a Question.
type Answer struct {
// Selected holds the chosen option label(s). For free-form input the host
// may return the typed text here.
Selected []string
}
// AskUserFunc is the host's question callback (a CLI prompt, a GUI, a web form,
// or an automated policy). Like CanUseTool it is synchronous: the tool blocks
// until it returns. The host decides the UI; the SDK only defines the contract.
type AskUserFunc func(ctx context.Context, q Question) Answer
// NewAskUserQuestion builds the AskUserQuestion tool bound to a host callback.
// It lets the agent pause a long task to ask the user a structured question
// (with options) and continue with the answer — without ending the turn.
func NewAskUserQuestion(ask AskUserFunc) CoreTool {
return Build(Spec{
Name: "AskUserQuestion",
Description: "Asks the user one or more multiple-choice questions and returns their answers. Use it when you genuinely need the user to decide between options to proceed — not for things you can determine yourself or sensible defaults.",
Prompt: "Provide each question with a short header, the question text, and 2-4 concise options (label + one-line description). Set multiSelect when several options may apply. Ask only when blocked on a decision that is the user's to make.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"questions": map[string]any{
"type": "array",
"description": "1-4 questions to ask.",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"header": map[string]any{"type": "string", "description": "Very short label (≤12 chars)."},
"question": map[string]any{"type": "string", "description": "The question to ask."},
"multiSelect": map[string]any{"type": "boolean", "description": "Allow multiple selections."},
"options": map[string]any{
"type": "array",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"label": map[string]any{"type": "string"},
"description": map[string]any{"type": "string"},
},
"required": []any{"label"},
},
},
},
"required": []any{"question", "options"},
},
},
},
"required": []any{"questions"},
},
// Not concurrency-safe (it blocks on the user) and self-allowed (asking a
// question never needs a permission prompt of its own).
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Allowed()
},
Run: func(ctx context.Context, input json.RawMessage, _ *ToolContext) (Result, error) {
var in struct {
Questions []struct {
Header string `json:"header"`
Question string `json:"question"`
MultiSelect bool `json:"multiSelect"`
Options []Option `json:"options"`
} `json:"questions"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
if len(in.Questions) == 0 {
return Errorf("Error: no questions provided"), nil
}
if ask == nil {
return Errorf("Error: no question handler is configured; ask the user in plain text instead"), nil
}
var b strings.Builder
for _, q := range in.Questions {
ans := ask(ctx, Question{Header: q.Header, Question: q.Question, Options: q.Options, MultiSelect: q.MultiSelect})
fmt.Fprintf(&b, "Q: %s\nA: %s\n\n", q.Question, strings.Join(ans.Selected, ", "))
}
return Text(strings.TrimSpace(b.String())), nil
},
})
}
// UnmarshalJSON lets Option accept the lowercase JSON the model emits.
func (o *Option) UnmarshalJSON(data []byte) error {
var raw struct {
Label string `json:"label"`
Description string `json:"description"`
}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
o.Label, o.Description = raw.Label, raw.Description
return nil
}
+40
View File
@@ -0,0 +1,40 @@
package tool
import (
"context"
"strings"
"testing"
)
func TestAskUserQuestion(t *testing.T) {
var asked []Question
ask := func(_ context.Context, q Question) Answer {
asked = append(asked, q)
// Pick the first option's label.
return Answer{Selected: []string{q.Options[0].Label}}
}
tl := NewAskUserQuestion(ask)
input := `{"questions":[{"header":"DB","question":"Which database?","options":[{"label":"Postgres","description":"relational"},{"label":"SQLite","description":"embedded"}]}]}`
if err := ValidateInput(tl.InputSchema(), []byte(input)); err != nil {
t.Fatalf("schema: %v", err)
}
res, err := tl.Call(context.Background(), []byte(input), &ToolContext{})
if err != nil {
t.Fatalf("call: %v", err)
}
if len(asked) != 1 || asked[0].Header != "DB" || len(asked[0].Options) != 2 {
t.Fatalf("question not passed through: %+v", asked)
}
if !strings.Contains(res.Flatten(), "Which database?") || !strings.Contains(res.Flatten(), "Postgres") {
t.Fatalf("answer not returned: %q", res.Flatten())
}
}
func TestAskUserQuestionNoHandler(t *testing.T) {
tl := NewAskUserQuestion(nil)
res, _ := tl.Call(context.Background(), []byte(`{"questions":[{"question":"x","options":[{"label":"a"}]}]}`), &ToolContext{})
if !res.IsError {
t.Fatal("expected error when no handler configured")
}
}
+209
View File
@@ -0,0 +1,209 @@
package tool
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"os/exec"
"regexp"
"strings"
"time"
"github.com/Autumn-27/norma/permission"
)
// catastrophicBash matches a small set of irreversibly destructive commands
// that are hard-denied regardless of mode (NFR-10). This is a safety floor, not
// a full sandbox — hosts should still gate Bash via CanUseTool.
var catastrophicBash = []*regexp.Regexp{
regexp.MustCompile(`\brm\s+(-[a-zA-Z]*\s+)*-[a-zA-Z]*[rf][a-zA-Z]*\s+(-[a-zA-Z]+\s+)*/(\s|$)`), // rm -rf /
regexp.MustCompile(`:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;`), // fork bomb
regexp.MustCompile(`\bmkfs\.\w+\s+/dev/`), // format a device
regexp.MustCompile(`\bdd\b[^\n]*\bof=/dev/(sd|nvme|hd)`), // overwrite a disk
}
// disallowedAutoBackground lists commands that must never be silently moved to
// the background on timeout.
var disallowedAutoBackground = []string{"sleep"}
// NewBash builds the Bash tool: run a shell command with a timeout, optionally in
// the background.
func NewBash() CoreTool {
props := map[string]any{
"command": map[string]any{"type": "string", "description": "The shell command to execute."},
"timeout_ms": map[string]any{"type": "integer", "description": "Timeout in ms (default 120000, max 600000)."},
}
desc := "Executes a shell command in the working directory and returns combined stdout and stderr. Use for running tests, builds, package managers, and git. Prefer the dedicated file tools for file work."
prompt := "The command runs through the shell, so you are not limited to one command: chain steps with && or ;, use pipes, and pass multi-line scripts or heredocs. For anything beyond a simple one-liner — loops, parsing, string/JSON handling, HTTP logic, computation — prefer writing a short script (Python, Node, shell, etc.) and executing it (e.g. via a heredoc or by writing a file then running it) rather than forcing everything into a single command. A timeout (default 120s, max 600s) applies. Avoid commands needing interactive input."
if !BackgroundTasksDisabled() {
props["run_in_background"] = map[string]any{
"type": "boolean",
"description": "Run in the background and return immediately; read its output later with TaskOutput or Read, and you are notified when it completes. A foreground command that exceeds its timeout is also moved to the background automatically.",
}
desc += " Set run_in_background to return immediately and read the output later."
}
return Build(Spec{
Name: "Bash",
Description: desc,
Prompt: prompt,
Schema: map[string]any{
"type": "object",
"properties": props,
"required": []any{"command"},
},
Permissions: bashPermissions,
Run: runBash,
})
}
func bashPermissions(_ context.Context, input json.RawMessage, _ permission.Context) permission.Decision {
var in struct {
Command string `json:"command"`
}
_ = json.Unmarshal(input, &in)
for _, re := range catastrophicBash {
if re.MatchString(in.Command) {
return permission.Denied("denied: command appears irreversibly destructive and is blocked by the safety floor")
}
}
return permission.AskUser("run shell command: " + in.Command)
}
func runBash(ctx context.Context, input json.RawMessage, tc *ToolContext) (Result, error) {
var in struct {
Command string `json:"command"`
TimeoutMS int `json:"timeout_ms"`
RunInBackground bool `json:"run_in_background"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
if strings.TrimSpace(in.Command) == "" {
return Errorf("Error: command is required"), nil
}
timeout := 120 * time.Second
if in.TimeoutMS > 0 {
timeout = time.Duration(in.TimeoutMS) * time.Millisecond
if timeout > 600*time.Second {
timeout = 600 * time.Second
}
}
// Background-capable path: requires a task manager on the context.
if tc != nil && tc.Tasks != nil && !BackgroundTasksDisabled() {
return runBashManaged(ctx, tc, in.Command, timeout, in.RunInBackground)
}
// Fallback: synchronous execution (unchanged legacy behavior).
return runBashSync(ctx, tc, in.Command, timeout)
}
// runBashManaged runs the command through the task manager, supporting explicit
// background launch and timeout auto-backgrounding.
func runBashManaged(ctx context.Context, tc *ToolContext, command string, timeout time.Duration, explicitBG bool) (Result, error) {
spec := SpawnSpec{Command: command, Kind: KindBash, WorkingDir: tc.WorkingDir, Description: short(command), Env: tc.Env}
if explicitBG {
t, err := tc.Tasks.Spawn(spec)
if err != nil {
return Errorf("Error: failed to start background command: " + err.Error()), nil
}
tc.Tasks.Background(t.ID)
return Text(fmt.Sprintf(
"Running in background as %s. Output file: %s\nUse TaskOutput{task_id:%q} or Read to read its output; you are notified when it completes.",
t.ID, t.OutputPath, t.ID)), nil
}
t, finished, output, err := tc.Tasks.RunForeground(ctx, spec, timeout)
if err != nil {
if t != nil {
tc.Tasks.Forget(t.ID)
}
return Errorf("Error: " + err.Error()), nil
}
if finished {
info, _ := tc.Tasks.Get(t.ID)
tc.Tasks.Forget(t.ID)
if info.Status == TaskFailed {
if strings.TrimSpace(output) == "" {
output = "(no output)"
}
return Errorf(fmt.Sprintf("%s\n\n[exit code %d]", Capture(tc, output), info.ExitCode)), nil
}
if strings.TrimSpace(output) == "" {
output = "(command produced no output)"
}
return Text(Capture(tc, output)), nil
}
// Timed out while still running.
if autoBackgroundAllowed(command) {
tc.Tasks.Background(t.ID)
return Text(fmt.Sprintf(
"Command still running after %s; moved to background as %s. Output file: %s\nUse TaskOutput{task_id:%q} to read its output; you are notified when it completes.",
timeout, t.ID, t.OutputPath, t.ID)), nil
}
out, _ := tc.Tasks.Output(t.ID, 0)
tc.Tasks.Kill(t.ID)
tc.Tasks.Forget(t.ID)
return Errorf(Capture(tc, out) + fmt.Sprintf("\n\n[command timed out after %s]", timeout)), nil
}
// runBashSync is the original blocking implementation, used when no task manager
// is available (background execution disabled).
func runBashSync(ctx context.Context, tc *ToolContext, command string, timeout time.Duration) (Result, error) {
cctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
shell, flags := shellCmd()
cmd := exec.CommandContext(cctx, shell, append(flags, command)...)
if tc != nil {
cmd.Dir = tc.WorkingDir
if env := withEnv(tc.Env); env != nil {
cmd.Env = env
}
}
var buf bytes.Buffer
cmd.Stdout = &buf
cmd.Stderr = &buf
err := cmd.Run()
out := Capture(tc, buf.String())
if cctx.Err() == context.DeadlineExceeded {
return Errorf(out + fmt.Sprintf("\n\n[command timed out after %s]", timeout)), nil
}
if err != nil {
var ee *exec.ExitError
if errors.As(err, &ee) {
if out == "" {
out = "(no output)"
}
return Errorf(fmt.Sprintf("%s\n\n[exit code %d]", out, ee.ExitCode())), nil
}
return Errorf(fmt.Sprintf("%s\n\n[failed to run: %v]", out, err)), nil
}
if strings.TrimSpace(out) == "" {
out = "(command produced no output)"
}
return Text(out), nil
}
// autoBackgroundAllowed reports whether a timed-out command may be moved to the
// background instead of being killed.
func autoBackgroundAllowed(command string) bool {
fields := strings.Fields(command)
if len(fields) == 0 {
return false
}
base := fields[0]
if i := strings.LastIndexAny(base, "/\\"); i >= 0 {
base = base[i+1:]
}
for _, d := range disallowedAutoBackground {
if base == d {
return false
}
}
return true
}
+384
View File
@@ -0,0 +1,384 @@
package tool
import (
"context"
"encoding/json"
"encoding/pem"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestReadHardening(t *testing.T) {
dir := t.TempDir()
// Directory → error.
if r := run(t, NewRead(), dir, map[string]any{"file_path": "."}); !r.IsError {
t.Fatal("reading a directory should error")
}
// Binary file → notice, not garbage.
os.WriteFile(filepath.Join(dir, "bin"), []byte{0x00, 0x01, 0x02, 'h', 'i'}, 0o644)
if r := run(t, NewRead(), dir, map[string]any{"file_path": "bin"}); !strings.Contains(r.Flatten(), "binary file") {
t.Fatalf("binary not detected: %q", r.Flatten())
}
// Long line truncation.
os.WriteFile(filepath.Join(dir, "long.txt"), []byte(strings.Repeat("a", 5000)), 0o644)
out := run(t, NewRead(), dir, map[string]any{"file_path": "long.txt"}).Flatten()
if !strings.Contains(out, "line truncated") {
t.Fatalf("long line not truncated: len=%d", len(out))
}
}
func TestReadTruncationGuidesOffset(t *testing.T) {
dir := t.TempDir()
body := strings.Repeat("padding line of some length\n", 300) + "TAILMARKER\n"
os.WriteFile(filepath.Join(dir, "big.txt"), []byte(body), 0o644)
raw, _ := json.Marshal(map[string]any{"file_path": "big.txt"})
// Small MaxOutputChars forces truncation; effective budget = 200 + readOutputBonus.
res, err := NewRead().Call(context.Background(), raw, &ToolContext{WorkingDir: dir, MaxOutputChars: 200})
if err != nil {
t.Fatalf("read: %v", err)
}
out := res.Flatten()
if !strings.Contains(out, "truncated to fit the output limit") || !strings.Contains(out, "offset=") {
t.Fatalf("missing truncation + offset guidance: %q", out)
}
// The +readOutputBonus(1000) lifts the budget well above MaxOutputChars(200).
if len(out) <= 200 {
t.Fatalf("Read budget should exceed MaxOutputChars by the bonus; got len=%d", len(out))
}
// Head is line-bounded and the tail line is not shown.
if strings.Contains(out, "TAILMARKER") {
t.Fatalf("tail line should not appear after truncation: %q", out)
}
}
func TestReadTruncationDoesNotSpill(t *testing.T) {
dir := t.TempDir()
spill := t.TempDir()
body := strings.Repeat("padding line of some length\n", 300)
os.WriteFile(filepath.Join(dir, "big.txt"), []byte(body), 0o644)
raw, _ := json.Marshal(map[string]any{"file_path": "big.txt"})
// Even with an OutputDir configured, Read does not spill a copy — the source
// file is on disk, so it just guides the model to page on with offset.
res, _ := NewRead().Call(context.Background(), raw, &ToolContext{WorkingDir: dir, OutputDir: spill, MaxOutputChars: 200})
out := res.Flatten()
if !strings.Contains(out, "offset=") || strings.Contains(out, "saved to") {
t.Fatalf("Read should guide offset without spilling: %q", out)
}
if files, _ := os.ReadDir(spill); len(files) != 0 {
t.Fatalf("Read must not spill to OutputDir, found %d file(s)", len(files))
}
}
func TestWriteCreatedVsOverwrote(t *testing.T) {
dir := t.TempDir()
if r := run(t, NewWrite(), dir, map[string]any{"file_path": "f.txt", "content": "a"}); !strings.Contains(r.Flatten(), "Created") {
t.Fatalf("expected Created: %q", r.Flatten())
}
if r := run(t, NewWrite(), dir, map[string]any{"file_path": "f.txt", "content": "b"}); !strings.Contains(r.Flatten(), "Overwrote") {
t.Fatalf("expected Overwrote: %q", r.Flatten())
}
if r := run(t, NewWrite(), dir, map[string]any{"file_path": ".", "content": "x"}); !r.IsError {
t.Fatal("writing over a directory should error")
}
}
func TestMultiEditAtomic(t *testing.T) {
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "f.go"), []byte("alpha beta gamma"), 0o644)
// Two good edits apply in order.
run(t, NewMultiEdit(), dir, map[string]any{
"file_path": "f.go",
"edits": []any{
map[string]any{"old_string": "alpha", "new_string": "ALPHA"},
map[string]any{"old_string": "gamma", "new_string": "GAMMA"},
},
})
if b, _ := os.ReadFile(filepath.Join(dir, "f.go")); string(b) != "ALPHA beta GAMMA" {
t.Fatalf("multiedit result: %q", b)
}
// A failing edit aborts the whole batch (file unchanged).
r := run(t, NewMultiEdit(), dir, map[string]any{
"file_path": "f.go",
"edits": []any{
map[string]any{"old_string": "beta", "new_string": "BETA"},
map[string]any{"old_string": "nonexistent", "new_string": "x"},
},
})
if !r.IsError {
t.Fatal("expected error for unmatched edit")
}
if b, _ := os.ReadFile(filepath.Join(dir, "f.go")); string(b) != "ALPHA beta GAMMA" {
t.Fatalf("file should be unchanged after failed multiedit: %q", b)
}
}
func TestLS(t *testing.T) {
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "b.txt"), []byte("hi"), 0o644)
os.MkdirAll(filepath.Join(dir, "sub"), 0o755)
out := run(t, NewLS(), dir, map[string]any{}).Flatten()
if !strings.Contains(out, "sub/") || !strings.Contains(out, "b.txt") {
t.Fatalf("ls output: %q", out)
}
}
func TestTodoWrite(t *testing.T) {
store := NewTodoStore()
st := store.Tool()
res, _ := st.Call(context.Background(), []byte(`{"todos":[{"content":"build","status":"in_progress"},{"content":"test","status":"pending"}]}`), &ToolContext{})
items := store.List()
if len(items) != 2 || items[0].Status != TodoInProgress {
t.Fatalf("todos: %+v", items)
}
// tool_result is an ack, not the list (the list rides the tool_use input and
// the todo system-reminder).
if !strings.Contains(res.Flatten(), "successfully") || strings.Contains(res.Flatten(), "build") {
t.Fatalf("expected ack without the list, got: %q", res.Flatten())
}
}
func TestRenderTodoReminder(t *testing.T) {
if RenderTodoReminder(nil) != "" {
t.Fatal("empty list should render as empty string")
}
out := RenderTodoReminder([]Todo{
{Content: "build", Status: TodoInProgress},
{Content: "test", Status: TodoPending},
})
want := "1. [in_progress] build\n2. [pending] test"
if out != want {
t.Fatalf("render:\n got %q\nwant %q", out, want)
}
}
func TestWebFetch(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("content-type", "text/html")
w.Write([]byte(`<html><body><script>secret()</script><h1>Title</h1><p>Hello &amp; bye</p></body></html>`))
}))
defer srv.Close()
raw, _ := json.Marshal(map[string]any{"url": srv.URL})
res, err := NewWebFetch(WebFetchConfig{}).Call(context.Background(), raw, &ToolContext{})
if err != nil {
t.Fatalf("webfetch: %v", err)
}
out := res.Flatten()
if !strings.Contains(out, "Title") || !strings.Contains(out, "Hello & bye") {
t.Fatalf("text extraction: %q", out)
}
if strings.Contains(out, "secret") {
t.Fatalf("script should be stripped: %q", out)
}
}
func TestWebFetchRejectsStaticAssets(t *testing.T) {
var hits int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
hits++
w.Write([]byte("console.log(1)"))
}))
defer srv.Close()
// .js/.css (and with a query string), images, fonts → rejected before any request.
for _, path := range []string{"/app.js", "/main.css", "/bundle.min.js?v=3", "/logo.png", "/font.woff2"} {
raw, _ := json.Marshal(map[string]any{"url": srv.URL + path})
res, err := NewWebFetch(WebFetchConfig{}).Call(context.Background(), raw, &ToolContext{})
if err != nil {
t.Fatalf("webfetch %s: %v", path, err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "static asset") {
t.Fatalf("%s should be rejected as a static asset, got: %q (isErr=%v)", path, res.Flatten(), res.IsError)
}
}
if hits != 0 {
t.Fatalf("no network request should be made for static assets, got %d", hits)
}
// A normal page path still works.
raw, _ := json.Marshal(map[string]any{"url": srv.URL + "/docs/guide"})
res, _ := NewWebFetch(WebFetchConfig{}).Call(context.Background(), raw, &ToolContext{})
if res.IsError {
t.Fatalf("normal page path should not be rejected: %q", res.Flatten())
}
}
func TestProxyLikelyErr(t *testing.T) {
// Proxy/MITM-caused failures → a direct retry may help.
for _, s := range []string{
`Get "https://x/": EOF`,
"proxyconnect tcp: dial tcp 127.0.0.1:8788: connect: connection refused",
"read tcp: connection reset by peer",
"http2: server sent GOAWAY",
"remote error: tls: handshake failure",
"malformed HTTP response",
} {
if !proxyLikelyErr(errors.New(s)) {
t.Errorf("want retry (proxy-likely) for %q", s)
}
}
// Target/caller problems → a direct retry won't fix them.
for _, s := range []string{
"dial tcp: lookup nope.invalid: no such host",
"context deadline exceeded",
"context canceled",
"net/http: request canceled (Client.Timeout exceeded while awaiting headers)",
} {
if proxyLikelyErr(errors.New(s)) {
t.Errorf("want NO retry for %q", s)
}
}
if proxyLikelyErr(nil) {
t.Error("nil error must be false")
}
}
// TestWebFetchProxyFallback proves a proxied fetch that fails for a proxy-caused
// reason (here: the proxy port is dead → connection refused) retries once directly
// (no proxy) and reaches the target. A successful fetch is not annotated.
func TestWebFetchProxyFallback(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("content-type", "text/html")
w.Write([]byte(`<html><body><h1>Direct OK</h1></body></html>`))
}))
defer srv.Close()
raw, _ := json.Marshal(map[string]any{"url": srv.URL})
res, err := NewWebFetch(WebFetchConfig{Proxy: "http://127.0.0.1:1"}).Call(context.Background(), raw, &ToolContext{})
if err != nil {
t.Fatalf("webfetch: %v", err)
}
out := res.Flatten()
if !strings.Contains(out, "Direct OK") {
t.Fatalf("direct fallback should have fetched the page: %q", out)
}
}
// TestWebFetchCompact verifies the HTML→Markdown output is token-lean: nested
// blocks don't leave blank lines, and per-line indentation is stripped, while
// content and list structure are preserved.
func TestWebFetchCompact(t *testing.T) {
const page = `<html><body>
<div> <div> <p>Para one</p> </div> </div>
<div><p>Para two</p></div>
<ul><li>alpha</li><li>beta</li></ul>
</body></html>`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("content-type", "text/html")
w.Write([]byte(page))
}))
defer srv.Close()
raw, _ := json.Marshal(map[string]any{"url": srv.URL})
out := mustFetch(t, raw)
if strings.Contains(out, "\n\n") {
t.Fatalf("output must have no blank lines (compact): %q", out)
}
if strings.Contains(out, "\n ") || strings.Contains(out, " \n") {
t.Fatalf("output must not keep spaces hugging newlines: %q", out)
}
for _, w := range []string{"Para one", "Para two", "- alpha", "- beta"} {
if !strings.Contains(out, w) {
t.Fatalf("content %q missing in:\n%s", w, out)
}
}
}
func TestWebFetchExtract(t *testing.T) {
const page = `<html><head><meta name="generator" content="WP 6.0"></head><body>
<!-- TODO remove backdoor /admin.php -->
<h1>Login</h1>
<form method="post" action="/login">
<input type="text" name="user"><input type="password" name="pass">
<input type="hidden" name="csrf" value="abc123">
</form>
<script src="/js/app.js"></script>
<script>fetch("/api/v1/users")</script>
<a href="/admin">admin</a>
</body></html>`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("content-type", "text/html")
w.Write([]byte(page))
}))
defer srv.Close()
// Without extract: no RECON section, markdown body only.
raw, _ := json.Marshal(map[string]any{"url": srv.URL})
out := mustFetch(t, raw)
if strings.Contains(out, "RECON") {
t.Fatalf("extract=false must not emit RECON: %q", out)
}
// With extract: comments, script src, inline endpoint, hidden field, meta all preserved.
raw, _ = json.Marshal(map[string]any{"url": srv.URL, "extract": true})
out = mustFetch(t, raw)
for _, want := range []string{"RECON", "backdoor /admin.php", "/js/app.js", "/api/v1/users", "csrf(hidden=abc123)", "generator=WP 6.0", "POST /login"} {
if !strings.Contains(out, want) {
t.Fatalf("recon missing %q in:\n%s", want, out)
}
}
}
// TestWebFetchCACert proves CACert makes HTTPS through a self-signed (MITM-style)
// server verify: it fails without the CA and succeeds once the CA is trusted —
// the proper alternative to InsecureTLS.
func TestWebFetchCACert(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("content-type", "text/html")
w.Write([]byte("<h1>secure</h1>"))
}))
defer srv.Close()
caFile := filepath.Join(t.TempDir(), "ca.pem")
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw})
if err := os.WriteFile(caFile, certPEM, 0o600); err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal(map[string]any{"url": srv.URL})
// No CA → the self-signed cert fails verification.
res, _ := NewWebFetch(WebFetchConfig{}).Call(context.Background(), raw, &ToolContext{})
if out := res.Flatten(); !strings.Contains(out, "Error fetching URL") {
t.Fatalf("expected TLS failure without CA, got: %q", out)
}
// CA trusted → verification passes, content fetched.
res, _ = NewWebFetch(WebFetchConfig{CACert: caFile}).Call(context.Background(), raw, &ToolContext{})
if out := res.Flatten(); !strings.Contains(out, "secure") {
t.Fatalf("expected success with CA, got: %q", out)
}
}
func mustFetch(t *testing.T, raw []byte) string {
t.Helper()
res, err := NewWebFetch(WebFetchConfig{}).Call(context.Background(), raw, &ToolContext{})
if err != nil {
t.Fatalf("webfetch: %v", err)
}
return res.Flatten()
}
// TestBashEnvInjection proves ToolContext.Env is layered into the Bash
// subprocess environment (and overrides inherited values).
func TestBashEnvInjection(t *testing.T) {
t.Setenv("HTTP_PROXY", "inherited-should-be-overridden")
raw, _ := json.Marshal(map[string]any{"command": "echo proxy=$HTTP_PROXY ca=$SSL_CERT_FILE"})
tc := &ToolContext{Env: []string{
"HTTP_PROXY=http://127.0.0.1:8080",
"SSL_CERT_FILE=/etc/ca.pem",
}}
res, err := NewBash().Call(context.Background(), raw, tc)
if err != nil {
t.Fatalf("bash: %v", err)
}
out := res.Flatten()
if !strings.Contains(out, "proxy=http://127.0.0.1:8080") || !strings.Contains(out, "ca=/etc/ca.pem") {
t.Fatalf("env not injected/overridden: %q", out)
}
}
+54
View File
@@ -0,0 +1,54 @@
package tool
import (
"os"
"strings"
"testing"
)
// First pass spills oversized output; a second pass over that result must not
// spill again or change it — the marker makes CaptureOnce idempotent, which is
// what lets a global post-tool net coexist with tools that Capture themselves.
func TestCaptureOnceSpillIsIdempotent(t *testing.T) {
dir := t.TempDir()
tc := &ToolContext{WorkingDir: dir, OutputDir: dir, MaxOutputChars: 100}
long := strings.Repeat("x", 5000)
first := CaptureOnce(tc, long)
if !strings.Contains(first, "<persisted-output>") {
t.Fatalf("first CaptureOnce should spill oversized output: %q", first)
}
if files, _ := os.ReadDir(dir); len(files) != 1 {
t.Fatalf("expected exactly 1 spill file, got %d", len(files))
}
second := CaptureOnce(tc, first)
if second != first {
t.Fatalf("CaptureOnce not idempotent on spilled output:\n first=%q\n second=%q", first, second)
}
if files, _ := os.ReadDir(dir); len(files) != 1 {
t.Fatalf("second CaptureOnce spilled again: %d files", len(files))
}
}
// Without an OutputDir, Capture falls back to head+tail truncation (a different
// marker). CaptureOnce must recognise that too and not re-truncate.
func TestCaptureOnceTruncationIsIdempotent(t *testing.T) {
tc := &ToolContext{MaxOutputChars: 100}
long := strings.Repeat("y", 5000)
first := CaptureOnce(tc, long)
if !strings.Contains(first, "characters truncated]") {
t.Fatalf("expected truncation marker: %q", first)
}
if second := CaptureOnce(tc, first); second != first {
t.Fatalf("CaptureOnce re-truncated already-truncated output")
}
}
func TestCaptureOncePassesShortOutput(t *testing.T) {
tc := &ToolContext{MaxOutputChars: 100}
if got := CaptureOnce(tc, "ok"); got != "ok" {
t.Fatalf("short output changed: %q", got)
}
}
+272
View File
@@ -0,0 +1,272 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
"sync"
"github.com/Autumn-27/norma/permission"
)
// Deferred tools: a mechanism to keep a tool callable while withholding its schema
// from the model's tool list (saving context tokens). Only the tool NAME surfaces
// (via RenderDeferredToolsBlock, placed by the host in the cached system prompt).
// The model discovers a deferred tool's schema with SearchExtraTools, then invokes
// it with ExecuteExtraTool. Both access tools stay in the model's list (never
// deferred). See docs/mcp-deferred-tools-方案设计.md.
// Fixed names of the two always-loaded access tools.
const (
SearchExtraToolsName = "SearchExtraTools"
ExecuteExtraToolName = "ExecuteExtraTool"
)
// UnlockSet is a session-scoped, concurrency-safe set of deferred-tool names that
// are currently callable via ExecuteExtraTool. Globally-available deferred tools
// are seeded at construction; skill-gated ones are added at runtime when their
// skill loads. Withholding the schema (deferred) is separate from gating the call
// (unlock): a name may be listed yet locked until its skill is invoked.
type UnlockSet struct {
mu sync.RWMutex
names map[string]bool
}
// NewUnlockSet builds an unlock set seeded with the given tool names.
func NewUnlockSet(initial ...string) *UnlockSet {
s := &UnlockSet{names: make(map[string]bool, len(initial))}
for _, n := range initial {
s.names[n] = true
}
return s
}
// Add unlocks the given tool names (idempotent).
func (s *UnlockSet) Add(names ...string) {
s.mu.Lock()
defer s.mu.Unlock()
for _, n := range names {
s.names[n] = true
}
}
// Has reports whether name is currently unlocked (callable).
func (s *UnlockSet) Has(name string) bool {
s.mu.RLock()
defer s.mu.RUnlock()
return s.names[name]
}
// List returns the unlocked names, sorted.
func (s *UnlockSet) List() []string {
s.mu.RLock()
defer s.mu.RUnlock()
out := make([]string, 0, len(s.names))
for n := range s.names {
out = append(out, n)
}
sort.Strings(out)
return out
}
// RenderDeferredToolsBlock renders the <available-deferred-tools> block: the given
// tool names (one per line, sorted) plus the fixed usage instruction. Returns "" if
// names is empty. Hosts place this in the CACHED system-prompt prefix (a SystemPrompt
// segment before DynamicBoundary) — see design doc §2.1 / C1.
func RenderDeferredToolsBlock(names []string) string {
if len(names) == 0 {
return ""
}
sorted := append([]string(nil), names...)
sort.Strings(sorted)
var b strings.Builder
b.WriteString("<available-deferred-tools>\n")
for _, n := range sorted {
b.WriteString(n)
b.WriteByte('\n')
}
b.WriteString("</available-deferred-tools>\n")
b.WriteString("IMPORTANT: The tools listed above are deferred — they are NOT in your tool list. ")
b.WriteString("To use one you MUST first discover it via " + SearchExtraToolsName +
" (returns its schema), then invoke it via " + ExecuteExtraToolName + ".\n")
b.WriteString("Tool priority: use core tools for core tasks (e.g. bash/curl for HTTP); " +
"only use " + ExecuteExtraToolName + " for a deferred tool when the task truly needs it.")
return b.String()
}
// NewSearchExtraTools builds the always-loaded discovery tool. deferred is the set
// of tool names whose schemas are withheld; the tool searches those names in reg
// and returns each match's name + description + params schema.
func NewSearchExtraTools(reg *Registry, deferred []string) CoreTool {
deferredSet := make(map[string]bool, len(deferred))
for _, n := range deferred {
deferredSet[n] = true
}
ordered := append([]string(nil), deferred...)
sort.Strings(ordered)
return Build(Spec{
Name: SearchExtraToolsName,
Description: "Discover deferred tools (not in your tool list) and get their schemas, then invoke via " +
ExecuteExtraToolName + ". Query forms: \"select:Name\" exact, \"select:A,B\" multiple, or free keywords to match name/description.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"query": map[string]any{
"type": "string",
"description": "\"select:<name>\" exact (comma-separated for multiple), or keywords.",
},
},
"required": []any{"query"},
},
ReadOnly: func(json.RawMessage) bool { return true },
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Allowed()
},
Run: func(_ context.Context, in json.RawMessage, _ *ToolContext) (Result, error) {
var args struct {
Query string `json:"query"`
}
_ = json.Unmarshal(in, &args)
q := strings.TrimSpace(args.Query)
if q == "" {
return Errorf("Error: query is required"), nil
}
var matches []CoreTool
seen := map[string]bool{}
addByFullName := func(name string) {
if seen[name] || !deferredSet[name] {
return
}
if t, ok := reg.Get(name); ok {
seen[name] = true
matches = append(matches, t)
}
}
// addByQuery resolves one query token: exact full-name first, then
// case-insensitive suffix match against each deferred tool name so that
// short MCP tool names like "list_projects" also find
// "mcp__scopesentry__list_projects".
addByQuery := func(token string) {
token = strings.TrimSpace(token)
if token == "" {
return
}
// 1. exact match
addByFullName(token)
if seen[token] {
return
}
// 2. suffix / substring match (case-insensitive) for short names
lower := strings.ToLower(token)
for _, name := range ordered {
lname := strings.ToLower(name)
// match if full name equals, ends with __token, or contains token
if lname == lower ||
strings.HasSuffix(lname, "__"+lower) ||
strings.Contains(lname, lower) {
addByFullName(name)
}
}
}
if strings.HasPrefix(q, "select:") {
for _, part := range strings.Split(strings.TrimPrefix(q, "select:"), ",") {
addByQuery(part)
}
} else {
// Multi-token keyword search: every space-separated token must appear
// in the normalised haystack (__ replaced by space for MCP tool names).
tokens := strings.Fields(strings.ToLower(q))
for _, name := range ordered {
t, ok := reg.Get(name)
if !ok {
continue
}
// normalise __ → space so "scopesentry list_projects" finds
// "mcp__scopesentry__list_projects".
haystack := strings.ReplaceAll(
strings.ToLower(t.Name()+" "+t.Description()), "__", " ")
allMatch := true
for _, tok := range tokens {
if !strings.Contains(haystack, tok) {
allMatch = false
break
}
}
if allMatch {
addByFullName(name)
}
}
}
if len(matches) == 0 {
return Text("No matching deferred tools for query: " + q), nil
}
var b strings.Builder
fmt.Fprintf(&b, "Found %d deferred tool(s). Invoke with %s({\"tool_name\":\"<name>\",\"params\":{...}}):\n",
len(matches), ExecuteExtraToolName)
for _, t := range matches {
schemaJSON, _ := json.Marshal(t.InputSchema())
fmt.Fprintf(&b, "\n## %s\n%s\nparams schema: %s\n", t.Name(), t.Description(), string(schemaJSON))
}
return Text(b.String()), nil
},
})
}
// NewExecuteExtraTool builds the always-loaded invoker for deferred tools. It runs
// the named tool from reg, but only if it is currently in the unlock set. Schema is
// validated before the call. unlock may be nil (then every registry tool is
// callable — no gating).
func NewExecuteExtraTool(reg *Registry, unlock *UnlockSet) CoreTool {
return Build(Spec{
Name: ExecuteExtraToolName,
Description: "Invoke a deferred tool discovered via " + SearchExtraToolsName +
". tool_name is the deferred tool's exact name; params must match its schema.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"tool_name": map[string]any{
"type": "string",
"description": "Exact name of the deferred tool (from " + SearchExtraToolsName + " / <available-deferred-tools>).",
},
"params": map[string]any{
"type": "object",
"description": "Parameters for the tool, matching its schema.",
},
},
"required": []any{"tool_name"},
},
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Allowed()
},
Run: func(ctx context.Context, in json.RawMessage, tc *ToolContext) (Result, error) {
var args struct {
ToolName string `json:"tool_name"`
Params json.RawMessage `json:"params"`
}
if err := json.Unmarshal(in, &args); err != nil {
return Errorf("Error: " + err.Error()), nil
}
if args.ToolName == "" {
return Errorf("Error: tool_name is required"), nil
}
t, ok := reg.Get(args.ToolName)
if !ok {
return Errorf("Error: unknown tool " + args.ToolName), nil
}
if unlock != nil && !unlock.Has(args.ToolName) {
return Errorf("Error: tool " + args.ToolName +
" is not unlocked in this session — load the skill that provides it first."), nil
}
params := args.Params
if len(params) == 0 {
params = json.RawMessage("{}")
}
if err := ValidateInput(t.InputSchema(), params); err != nil {
return Errorf("Error: invalid params for " + args.ToolName + ": " + err.Error()), nil
}
return t.Call(ctx, params, tc)
},
})
}
+113
View File
@@ -0,0 +1,113 @@
package tool
import (
"context"
"encoding/json"
"strings"
"testing"
)
// echoTool is a trivial deferred tool that echoes its "msg" param.
func echoTool() CoreTool {
return Build(Spec{
Name: "echo",
Description: "Echoes the msg parameter back.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{"msg": map[string]any{"type": "string"}},
"required": []any{"msg"},
},
Run: func(_ context.Context, in json.RawMessage, _ *ToolContext) (Result, error) {
var a struct {
Msg string `json:"msg"`
}
_ = json.Unmarshal(in, &a)
return Text("echo:" + a.Msg), nil
},
})
}
func TestUnlockSet(t *testing.T) {
s := NewUnlockSet("a", "b")
if !s.Has("a") || !s.Has("b") || s.Has("c") {
t.Fatalf("seed wrong: %v", s.List())
}
s.Add("c")
if !s.Has("c") {
t.Fatal("Add failed")
}
if got := s.List(); len(got) != 3 || got[0] != "a" || got[2] != "c" {
t.Fatalf("List not sorted/complete: %v", got)
}
}
func TestRenderDeferredToolsBlock(t *testing.T) {
if RenderDeferredToolsBlock(nil) != "" {
t.Fatal("empty names should render empty")
}
out := RenderDeferredToolsBlock([]string{"mcp__b__y", "mcp__a__x"})
if !strings.Contains(out, "<available-deferred-tools>") ||
!strings.Contains(out, "mcp__a__x") || !strings.Contains(out, "mcp__b__y") ||
!strings.Contains(out, ExecuteExtraToolName) {
t.Fatalf("block missing parts:\n%s", out)
}
// sorted: a before b
if strings.Index(out, "mcp__a__x") > strings.Index(out, "mcp__b__y") {
t.Fatal("names not sorted")
}
}
func TestSearchExtraTools(t *testing.T) {
reg := NewRegistry(echoTool())
search := NewSearchExtraTools(reg, []string{"echo"})
// exact select
r, _ := search.Call(context.Background(), json.RawMessage(`{"query":"select:echo"}`), nil)
txt := r.Content[0].Text
if !strings.Contains(txt, "## echo") || !strings.Contains(txt, "params schema") {
t.Fatalf("select:echo missing schema:\n%s", txt)
}
// keyword
r, _ = search.Call(context.Background(), json.RawMessage(`{"query":"echoes"}`), nil)
if !strings.Contains(r.Content[0].Text, "## echo") {
t.Fatalf("keyword search failed:\n%s", r.Content[0].Text)
}
// non-deferred name → not found (registry has it but it is not in deferred list)
reg2 := NewRegistry(echoTool())
search2 := NewSearchExtraTools(reg2, []string{"other"})
r, _ = search2.Call(context.Background(), json.RawMessage(`{"query":"select:echo"}`), nil)
if !strings.Contains(r.Content[0].Text, "No matching") {
t.Fatalf("non-deferred should not surface:\n%s", r.Content[0].Text)
}
}
func TestExecuteExtraTool(t *testing.T) {
reg := NewRegistry(echoTool())
unlock := NewUnlockSet("echo")
exec := NewExecuteExtraTool(reg, unlock)
// unlocked → runs
r, _ := exec.Call(context.Background(), json.RawMessage(`{"tool_name":"echo","params":{"msg":"hi"}}`), nil)
if r.IsError || r.Content[0].Text != "echo:hi" {
t.Fatalf("expected echo:hi, got %+v", r)
}
// locked → rejected
locked := NewExecuteExtraTool(reg, NewUnlockSet())
r, _ = locked.Call(context.Background(), json.RawMessage(`{"tool_name":"echo","params":{"msg":"hi"}}`), nil)
if !r.IsError || !strings.Contains(r.Content[0].Text, "not unlocked") {
t.Fatalf("locked tool should be rejected, got %+v", r)
}
// unknown tool
r, _ = exec.Call(context.Background(), json.RawMessage(`{"tool_name":"nope","params":{}}`), nil)
if !r.IsError || !strings.Contains(r.Content[0].Text, "unknown tool") {
t.Fatalf("unknown tool should error, got %+v", r)
}
// invalid params (missing required msg) → schema validation error
r, _ = exec.Call(context.Background(), json.RawMessage(`{"tool_name":"echo","params":{}}`), nil)
if !r.IsError || !strings.Contains(r.Content[0].Text, "invalid params") {
t.Fatalf("invalid params should error, got %+v", r)
}
}
+250
View File
@@ -0,0 +1,250 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
// NewRead builds the Read tool: reads a file with cat -n style line numbers and
// optional offset/limit.
func NewRead() CoreTool {
return Build(Spec{
Name: "Read",
Description: "Reads a file from the local filesystem and returns its contents with line numbers. Use offset/limit for large files. Always read a file before editing it.",
Prompt: "file_path may be absolute or relative to the working directory. Output lines are prefixed with their 1-based line number.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"file_path": map[string]any{"type": "string", "description": "Path to the file to read."},
"offset": map[string]any{"type": "integer", "description": "1-based line to start from."},
"limit": map[string]any{"type": "integer", "description": "Max lines to read (default 2000)."},
},
"required": []any{"file_path"},
},
ReadOnly: always,
Concurrent: always,
Permissions: allowReadOnly,
Run: runRead,
})
}
const maxLineLen = 2000
func runRead(_ context.Context, input json.RawMessage, tc *ToolContext) (Result, error) {
var in struct {
FilePath string `json:"file_path"`
Offset int `json:"offset"`
Limit int `json:"limit"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
path := resolvePath(tc, in.FilePath)
info, err := os.Stat(path)
if err != nil {
return Errorf(fmt.Sprintf("Error reading %s: %v", in.FilePath, err)), nil
}
if info.IsDir() {
return Errorf(fmt.Sprintf("Error: %s is a directory, not a file. Use LS or Glob to list its contents.", in.FilePath)), nil
}
data, err := os.ReadFile(path)
if err != nil {
return Errorf(fmt.Sprintf("Error reading %s: %v", in.FilePath, err)), nil
}
if isBinary(data) {
return Text(fmt.Sprintf("[binary file %s not shown — %d bytes]", in.FilePath, len(data))), nil
}
lines := strings.Split(string(data), "\n")
start := 0
if in.Offset > 0 {
start = in.Offset - 1
}
if start > len(lines) {
start = len(lines)
}
limit := in.Limit
if limit <= 0 {
limit = 2000
}
end := start + limit
if end > len(lines) {
end = len(lines)
}
var b strings.Builder
for i := start; i < end; i++ {
line := lines[i]
if len(line) > maxLineLen {
line = line[:maxLineLen] + "… [line truncated]"
}
fmt.Fprintf(&b, "%6d\t%s\n", i+1, line)
}
if b.Len() == 0 {
if len(data) == 0 {
return Text("(file is empty)"), nil
}
return Text("(no lines in the requested range)"), nil
}
return Text(readCapture(tc, b.String(), start)), nil
}
// readOutputBonus lifts the Read tool's output budget above the shared default
// (ToolContext.MaxOutputChars): Read gets a little more room before truncating.
const readOutputBonus = 1000
// readCapture bounds Read's line-numbered output. When it exceeds the Read budget
// (MaxToolOutputChars + readOutputBonus) it cuts at a line boundary and tells the
// model the exact offset to continue from — the source file is already on disk, so
// there is no need to spill a copy: the model just pages on with Read(offset=…).
// start is the 0-based line the output began at.
func readCapture(tc *ToolContext, s string, start int) string {
max := maxOut(tc) + readOutputBonus
if len(s) <= max {
return s
}
head, headLines := headWithinBudget(s, max)
nextOffset := start + headLines + 1 // 1-based file line to continue from
return head + fmt.Sprintf(
"\n... [Read truncated to fit the output limit. Continue reading the file with Read offset=%d (and an optional limit), or narrow with Grep/`sed -n`.] ...",
nextOffset)
}
// headWithinBudget returns the largest whole-line prefix of s within max bytes and
// the number of lines it contains. Falls back to a hard cut if a single line
// already exceeds the budget (no newline within reach).
func headWithinBudget(s string, max int) (string, int) {
if len(s) <= max {
return s, strings.Count(s, "\n")
}
cut := strings.LastIndexByte(s[:max], '\n')
if cut < 0 {
return s[:max], 0
}
head := s[:cut+1]
return head, strings.Count(head, "\n")
}
// isBinary reports whether data looks like a binary (non-text) file, using the
// common heuristic of a NUL byte in the first chunk.
func isBinary(data []byte) bool {
n := len(data)
if n > 8000 {
n = 8000
}
for i := 0; i < n; i++ {
if data[i] == 0 {
return true
}
}
return false
}
// NewWrite builds the Write tool: creates or overwrites a file.
func NewWrite() CoreTool {
return Build(Spec{
Name: "Write",
Description: "Writes a file to the local filesystem, creating parent directories and overwriting any existing file. Prefer Edit for modifying existing files.",
Prompt: "Provide the complete file contents — Write replaces the whole file.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"file_path": map[string]any{"type": "string", "description": "Path of the file to write."},
"content": map[string]any{"type": "string", "description": "Full contents to write."},
},
"required": []any{"file_path", "content"},
},
Run: runWrite,
})
}
func runWrite(_ context.Context, input json.RawMessage, tc *ToolContext) (Result, error) {
var in struct {
FilePath string `json:"file_path"`
Content string `json:"content"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
path := resolvePath(tc, in.FilePath)
existed := false
if info, err := os.Stat(path); err == nil {
if info.IsDir() {
return Errorf(fmt.Sprintf("Error: %s is an existing directory, not a file.", in.FilePath)), nil
}
existed = true
}
if dir := filepath.Dir(path); dir != "" {
if err := os.MkdirAll(dir, 0o755); err != nil {
return Errorf(fmt.Sprintf("Error creating directory: %v", err)), nil
}
}
if err := os.WriteFile(path, []byte(in.Content), 0o644); err != nil {
return Errorf(fmt.Sprintf("Error writing %s: %v", in.FilePath, err)), nil
}
verb := "Created"
if existed {
verb = "Overwrote"
}
return Text(fmt.Sprintf("%s %s (%d bytes)", verb, in.FilePath, len(in.Content))), nil
}
// NewEdit builds the Edit tool: exact string replacement with uniqueness check.
func NewEdit() CoreTool {
return Build(Spec{
Name: "Edit",
Description: "Performs an exact string replacement in a file. old_string must match exactly once unless replace_all is set. Read the file first so old_string matches precisely.",
Prompt: "old_string must match the file exactly (whitespace included) and be unique unless replace_all is true. new_string must differ from old_string.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"file_path": map[string]any{"type": "string", "description": "Path of the file to edit."},
"old_string": map[string]any{"type": "string", "description": "Exact text to replace."},
"new_string": map[string]any{"type": "string", "description": "Replacement text."},
"replace_all": map[string]any{"type": "boolean", "description": "Replace all occurrences."},
},
"required": []any{"file_path", "old_string", "new_string"},
},
Run: runEdit,
})
}
func runEdit(_ context.Context, input json.RawMessage, tc *ToolContext) (Result, error) {
var in struct {
FilePath string `json:"file_path"`
OldString string `json:"old_string"`
NewString string `json:"new_string"`
ReplaceAll bool `json:"replace_all"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
if in.OldString == in.NewString {
return Errorf("Error: old_string and new_string are identical"), nil
}
path := resolvePath(tc, in.FilePath)
data, err := os.ReadFile(path)
if err != nil {
return Errorf(fmt.Sprintf("Error reading %s: %v", in.FilePath, err)), nil
}
content := string(data)
count := strings.Count(content, in.OldString)
if count == 0 {
return Errorf(fmt.Sprintf("Error: old_string not found in %s", in.FilePath)), nil
}
if count > 1 && !in.ReplaceAll {
return Errorf(fmt.Sprintf("Error: old_string is not unique in %s (%d matches); add context or set replace_all", in.FilePath, count)), nil
}
var updated string
if in.ReplaceAll {
updated = strings.ReplaceAll(content, in.OldString, in.NewString)
} else {
updated = strings.Replace(content, in.OldString, in.NewString, 1)
}
if err := os.WriteFile(path, []byte(updated), 0o644); err != nil {
return Errorf(fmt.Sprintf("Error writing %s: %v", in.FilePath, err)), nil
}
return Text(fmt.Sprintf("Edited %s (%d replacement(s))", in.FilePath, count)), nil
}
+104
View File
@@ -0,0 +1,104 @@
package tool
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync/atomic"
"time"
)
const defaultMaxOutput = 30000
func maxOut(tc *ToolContext) int {
if tc != nil && tc.MaxOutputChars > 0 {
return tc.MaxOutputChars
}
return defaultMaxOutput
}
var spillSeq atomic.Int64
// Capture bounds a tool's textual output for the model. When the output exceeds
// the limit (ToolContext.MaxOutputChars, default 30000) and the host configured
// an OutputDir, the FULL output is written to a file there and a tight head + a
// pointer to that file is returned — so the model can read slices on demand
// (grep/sed) instead of losing the overflow. Without an OutputDir it falls back
// to a head+tail truncation (the overflow is discarded). Tools that produce
// potentially large output should return Capture(tc, output) rather than the raw
// string.
func Capture(tc *ToolContext, s string) string {
max := maxOut(tc)
if len(s) <= max {
return s
}
if tc != nil && tc.OutputDir != "" {
if path, err := spillOutput(tc.OutputDir, s); err == nil {
ref := path
if tc.WorkingDir != "" {
if rel, e := filepath.Rel(tc.WorkingDir, path); e == nil && !strings.HasPrefix(rel, "..") {
ref = rel
}
}
lines := strings.Count(s, "\n") + 1
return s[:max] + fmt.Sprintf(
"\n\n... <persisted-output>[Output too large: full %d bytes / %d lines.Full output saved to %s </persisted-output>",
len(s), lines, ref)
}
}
return truncate(s, max)
}
// alreadyCaptured reports whether s already carries a marker Capture leaves
// behind — a spill pointer or a head+tail truncation notice. It is how a global
// post-tool net recognises output a tool already ran through Capture itself.
//
// A false negative (legitimate text that happens to contain a marker) only means
// the guard fails to re-cap already-large output; it never corrupts. The markers
// are distinctive enough that this is vanishingly rare.
func alreadyCaptured(s string) bool {
return strings.Contains(s, "<persisted-output>") || strings.Contains(s, "characters truncated]")
}
// CaptureOnce is Capture with an idempotency guard: output a tool already ran
// through Capture (so it carries a spill pointer or truncation notice) is
// returned unchanged. This lets a single post-tool net cap every tool's output
// without re-truncating or re-spilling what built-in / MCP / custom tools
// already handled themselves. Output within the limit is a no-op either way,
// since Capture returns it unchanged.
func CaptureOnce(tc *ToolContext, s string) string {
if alreadyCaptured(s) {
return s
}
return Capture(tc, s)
}
func spillOutput(dir, s string) (string, error) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
name := fmt.Sprintf("output-%d-%d.txt", time.Now().Unix(), spillSeq.Add(1))
path := filepath.Join(dir, name)
if err := os.WriteFile(path, []byte(s), 0o644); err != nil {
return "", err
}
return path, nil
}
// resolvePath joins a relative path against the working directory.
func resolvePath(tc *ToolContext, p string) string {
if filepath.IsAbs(p) || tc == nil || tc.WorkingDir == "" {
return p
}
return filepath.Join(tc.WorkingDir, p)
}
// truncate trims s to max characters, keeping head and tail.
func truncate(s string, max int) string {
if max <= 0 || len(s) <= max {
return s
}
half := max / 2
return s[:half] + fmt.Sprintf("\n\n... [%d characters truncated] ...\n\n", len(s)-max) + s[len(s)-half:]
}
+71
View File
@@ -0,0 +1,71 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"os"
"sort"
"strings"
)
// NewLS builds the LS tool: lists the entries of a directory.
func NewLS() CoreTool {
return Build(Spec{
Name: "LS",
Description: "Lists the files and subdirectories of a directory (non-recursive). Use Glob to match by pattern across depth, or Grep to search contents.",
Prompt: "path may be absolute or relative to the working directory; defaults to the working directory.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"path": map[string]any{"type": "string", "description": "Directory to list (default working directory)."},
},
},
ReadOnly: always,
Concurrent: always,
Permissions: allowReadOnly,
Run: runLS,
})
}
func runLS(_ context.Context, input json.RawMessage, tc *ToolContext) (Result, error) {
var in struct {
Path string `json:"path"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
dir := tc.WorkingDir
if in.Path != "" {
dir = resolvePath(tc, in.Path)
}
if dir == "" {
dir = "."
}
entries, err := os.ReadDir(dir)
if err != nil {
return Errorf(fmt.Sprintf("Error listing %s: %v", in.Path, err)), nil
}
if len(entries) == 0 {
return Text("(empty directory)"), nil
}
sort.Slice(entries, func(i, j int) bool {
if entries[i].IsDir() != entries[j].IsDir() {
return entries[i].IsDir() // directories first
}
return entries[i].Name() < entries[j].Name()
})
var b strings.Builder
for _, e := range entries {
if e.IsDir() {
fmt.Fprintf(&b, "%s/\n", e.Name())
continue
}
var size int64
if info, err := e.Info(); err == nil {
size = info.Size()
}
fmt.Fprintf(&b, "%s\t%d bytes\n", e.Name(), size)
}
return Text(Capture(tc, b.String())), nil
}
+59
View File
@@ -0,0 +1,59 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"strings"
)
// NewMonitor builds the Monitor tool: start a long-running streaming process in
// the background (tail -f, watch, a dev server, a polling loop) and return
// immediately. Inspect it with Read/TaskOutput and end it with TaskStop.
func NewMonitor() CoreTool {
return Build(Spec{
Name: "Monitor",
Description: "Starts a long-running streaming process in the background (e.g. tail -f, watch, a dev server, a polling loop) and returns immediately with a task id and output-file path. Use Read or TaskOutput to inspect it and TaskStop to end it.",
Prompt: "Provide a command that streams output over time. It always runs in the background; you are notified if it exits on its own.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"command": map[string]any{"type": "string", "description": "The streaming command to run."},
"description": map[string]any{"type": "string", "description": "Short description of what is being monitored."},
},
"required": []any{"command"},
},
// Same catastrophic-command safety floor as Bash.
Permissions: bashPermissions,
Run: runMonitor,
})
}
func runMonitor(_ context.Context, input json.RawMessage, tc *ToolContext) (Result, error) {
var in struct {
Command string `json:"command"`
Description string `json:"description"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
if strings.TrimSpace(in.Command) == "" {
return Errorf("Error: command is required"), nil
}
if tc == nil || tc.Tasks == nil {
return Errorf("Error: background tasks are not enabled"), nil
}
t, err := tc.Tasks.Spawn(SpawnSpec{
Command: in.Command,
Description: in.Description,
Kind: KindMonitor,
WorkingDir: tc.WorkingDir,
})
if err != nil {
return Errorf("Error: failed to start monitor: " + err.Error()), nil
}
tc.Tasks.Background(t.ID)
return Text(fmt.Sprintf(
"Started monitor %s. Output file: %s\nUse TaskOutput{task_id:%q} or Read to inspect it; TaskStop{task_id:%q} to end it.",
t.ID, t.OutputPath, t.ID, t.ID)), nil
}
+87
View File
@@ -0,0 +1,87 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"os"
"strings"
)
// NewMultiEdit builds the MultiEdit tool: applies a sequence of exact-string
// replacements to one file atomically. Edits apply in order to the in-memory
// content; if any fails to match, nothing is written.
func NewMultiEdit() CoreTool {
return Build(Spec{
Name: "MultiEdit",
Description: "Applies several exact string replacements to a single file in one atomic operation. Edits are applied in order; if any old_string fails to match (or isn't unique without replace_all), the whole operation aborts and the file is left unchanged.",
Prompt: "Use this instead of multiple Edit calls on the same file. Each edit's old_string must match the file as modified by the preceding edits. Read the file first.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"file_path": map[string]any{"type": "string", "description": "Path of the file to edit."},
"edits": map[string]any{
"type": "array",
"description": "Edits to apply in order.",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"old_string": map[string]any{"type": "string", "description": "Exact text to replace."},
"new_string": map[string]any{"type": "string", "description": "Replacement text."},
"replace_all": map[string]any{"type": "boolean", "description": "Replace all occurrences."},
},
"required": []any{"old_string", "new_string"},
},
},
},
"required": []any{"file_path", "edits"},
},
Run: runMultiEdit,
})
}
func runMultiEdit(_ context.Context, input json.RawMessage, tc *ToolContext) (Result, error) {
var in struct {
FilePath string `json:"file_path"`
Edits []struct {
OldString string `json:"old_string"`
NewString string `json:"new_string"`
ReplaceAll bool `json:"replace_all"`
} `json:"edits"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
if len(in.Edits) == 0 {
return Errorf("Error: no edits provided"), nil
}
path := resolvePath(tc, in.FilePath)
data, err := os.ReadFile(path)
if err != nil {
return Errorf(fmt.Sprintf("Error reading %s: %v", in.FilePath, err)), nil
}
content := string(data)
total := 0
for i, e := range in.Edits {
if e.OldString == e.NewString {
return Errorf(fmt.Sprintf("Error in edit %d: old_string and new_string are identical", i+1)), nil
}
count := strings.Count(content, e.OldString)
if count == 0 {
return Errorf(fmt.Sprintf("Error in edit %d: old_string not found", i+1)), nil
}
if count > 1 && !e.ReplaceAll {
return Errorf(fmt.Sprintf("Error in edit %d: old_string is not unique (%d matches); add context or set replace_all", i+1, count)), nil
}
if e.ReplaceAll {
content = strings.ReplaceAll(content, e.OldString, e.NewString)
} else {
content = strings.Replace(content, e.OldString, e.NewString, 1)
}
total += count
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
return Errorf(fmt.Sprintf("Error writing %s: %v", in.FilePath, err)), nil
}
return Text(fmt.Sprintf("Applied %d edits to %s (%d replacement(s))", len(in.Edits), in.FilePath, total)), nil
}
+17
View File
@@ -0,0 +1,17 @@
//go:build windows
package tool
import (
"errors"
"os"
"os/exec"
)
// startPTY is unsupported on Windows (no ConPTY integration yet). Interactive
// shell sessions degrade to an explicit error there.
func startPTY(_ *exec.Cmd, _, _ int) (*os.File, error) {
return nil, errors.New("interactive shell (PTY) is not supported on this platform")
}
func ptySupported() bool { return false }
+19
View File
@@ -0,0 +1,19 @@
//go:build !windows
package tool
import (
"os"
"os/exec"
"github.com/creack/pty"
)
// startPTY launches cmd attached to a new pseudo-terminal of the given size and
// returns the master file (read output / write input). Unix implementation via
// creack/pty. ptySupported reports platform support.
func startPTY(cmd *exec.Cmd, rows, cols int) (*os.File, error) {
return pty.StartWithSize(cmd, &pty.Winsize{Rows: uint16(rows), Cols: uint16(cols)})
}
func ptySupported() bool { return true }
+67
View File
@@ -0,0 +1,67 @@
package tool
import "github.com/Autumn-27/norma/llm"
// Registry is an ordered, name-indexed collection of tools (FR-04.3).
type Registry struct {
order []string
byName map[string]CoreTool
}
// NewRegistry builds a registry from tools, preserving order.
func NewRegistry(tools ...CoreTool) *Registry {
r := &Registry{byName: map[string]CoreTool{}}
for _, t := range tools {
r.Add(t)
}
return r
}
// Add registers a tool, replacing any existing one with the same name.
func (r *Registry) Add(t CoreTool) {
if _, ok := r.byName[t.Name()]; !ok {
r.order = append(r.order, t.Name())
}
r.byName[t.Name()] = t
}
// Get returns the named tool.
func (r *Registry) Get(name string) (CoreTool, bool) {
t, ok := r.byName[name]
return t, ok
}
// List returns all tools in registration order.
func (r *Registry) List() []CoreTool {
out := make([]CoreTool, 0, len(r.order))
for _, n := range r.order {
out = append(out, r.byName[n])
}
return out
}
// Schemas renders the registry into provider-facing tool definitions, merging
// each tool's extended Prompt into its description.
func (r *Registry) Schemas() []llm.ToolSchema {
tools := r.List()
out := make([]llm.ToolSchema, 0, len(tools))
for _, t := range tools {
desc := t.Description()
if p := t.Prompt(); p != "" {
desc += "\n\n" + p
}
out = append(out, llm.ToolSchema{Name: t.Name(), Description: desc, InputSchema: t.InputSchema()})
}
return out
}
// DefaultTools returns the core toolset every agent gets: the file/shell tools
// (Read, Write, Edit, MultiEdit, LS, Glob, Grep, Bash) plus Sleep — a small
// context-cancellable wait that pairs with background execution. Network and
// stateful tools (WebFetch, TodoWrite) remain opt-in via their own constructors.
func DefaultTools() []CoreTool {
return []CoreTool{
NewRead(), NewWrite(), NewEdit(), NewMultiEdit(), NewLS(), NewGlob(), NewGrep(), NewBash(),
NewSleep(),
}
}
+176
View File
@@ -0,0 +1,176 @@
package tool
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
)
// Ripgrep integration: the Grep tool prefers the ripgrep binary when available
// (faster, .gitignore-aware, full ripgrep syntax) and falls back to the pure-Go
// implementation otherwise. Resolution runs once:
//
// 1. an `rg` already on PATH is used as-is;
// 2. otherwise a best-effort `npm install -g @vscode/ripgrep` runs (npm is
// assumed present) and the installed binary is located;
// 3. on any failure — no npm, install error, binary not found — the pure-Go
// grep is used, so search always works.
//
// Env controls:
// - NORMA_DISABLE_RIPGREP=1 force the pure-Go implementation (also used by tests)
// - NORMA_RIPGREP_NO_INSTALL=1 use an existing rg but never auto-install
var (
rgOnce sync.Once
rgResolved string
)
// RipgrepPath returns the resolved ripgrep binary path, or "" when the pure-Go
// grep should be used. The heavy resolution (detect + optional npm install) runs
// at most once per process.
func RipgrepPath() string {
if os.Getenv("NORMA_DISABLE_RIPGREP") != "" {
return ""
}
rgOnce.Do(func() { rgResolved = resolveRipgrep() })
return rgResolved
}
// EnsureRipgrep warms ripgrep resolution so the cost (including a possible npm
// install) is paid at startup rather than on the first Grep call. Hosts may call
// it once at boot. Returns the resolved path ("" = Go fallback).
func EnsureRipgrep() string { return RipgrepPath() }
func resolveRipgrep() string {
if p, err := exec.LookPath("rg"); err == nil {
return p
}
if os.Getenv("NORMA_RIPGREP_NO_INSTALL") != "" {
return ""
}
return installRipgrepViaNpm()
}
func installRipgrepViaNpm() string {
if _, err := exec.LookPath("npm"); err != nil {
return "" // no npm → Go fallback
}
cmd := exec.Command("npm", "install", "-g", "@vscode/ripgrep")
if err := cmd.Run(); err != nil {
return ""
}
if p, err := exec.LookPath("rg"); err == nil {
return p
}
return npmGlobalRipgrep()
}
// npmGlobalRipgrep locates the rg binary vendored by @vscode/ripgrep in the npm
// global root (it exposes no `rg` command, so we resolve the path directly).
func npmGlobalRipgrep() string {
out, err := exec.Command("npm", "root", "-g").Output()
if err != nil {
return ""
}
name := "rg"
if runtime.GOOS == "windows" {
name = "rg.exe"
}
p := filepath.Join(strings.TrimSpace(string(out)), "@vscode", "ripgrep", "bin", name)
if st, err := os.Stat(p); err == nil && !st.IsDir() {
return p
}
return ""
}
// ripgrepReq carries the parsed Grep parameters for the ripgrep backend.
type ripgrepReq struct {
pattern, glob, typ, mode string
ignoreCase, multiline, showLines bool
before, after int
root string
headLimit *int
offset int
}
// runWithRipgrep runs the query through the rg binary and formats the result.
// Returns ok=false when rg failed for a real reason (not "no matches"), so the
// caller falls back to the Go implementation.
func runWithRipgrep(rg string, r ripgrepReq, tc *ToolContext) (Result, bool) {
args := []string{"--color", "never"}
if r.ignoreCase {
args = append(args, "-i")
}
if r.multiline {
args = append(args, "-U", "--multiline-dotall")
}
switch r.mode {
case "files_with_matches":
args = append(args, "-l")
case "count":
args = append(args, "-c")
default: // content
args = append(args, "--no-heading")
if r.showLines {
args = append(args, "-n")
}
if r.before > 0 {
args = append(args, "-B", strconv.Itoa(r.before))
}
if r.after > 0 {
args = append(args, "-A", strconv.Itoa(r.after))
}
}
if r.glob != "" {
args = append(args, "--glob", r.glob)
}
if r.typ != "" {
if _, known := rgFileTypes[strings.ToLower(r.typ)]; known {
args = append(args, "--type", r.typ)
} else {
args = append(args, "--glob", "*."+r.typ) // unknown type → extension glob
}
}
// Run inside root so printed paths are root-relative (matching the Go impl).
dir, target := r.root, "."
if st, err := os.Stat(r.root); err == nil && !st.IsDir() {
dir, target = filepath.Dir(r.root), filepath.Base(r.root)
}
// `-e pattern --` keeps a pattern/path starting with '-' from being read as a flag.
args = append(args, "-e", r.pattern, "--", target)
cmd := exec.Command(rg, args...)
cmd.Dir = dir
out, err := cmd.Output()
if err != nil {
var ee *exec.ExitError
if errors.As(err, &ee) && ee.ExitCode() == 1 {
return Text("No matches found"), true // rg exit 1 = no matches
}
return Result{}, false // real failure → Go fallback
}
trimmed := strings.TrimRight(string(out), "\n")
if trimmed == "" {
return Text("No matches found"), true
}
lines := strings.Split(trimmed, "\n")
headLimit := 250
if r.headLimit != nil {
headLimit = *r.headLimit
}
kept, more := applyHeadOffset(lines, headLimit, r.offset)
res := strings.Join(kept, "\n")
if len(kept) > 0 {
res += "\n"
}
if more > 0 {
res += fmt.Sprintf("... [%d more result(s) — page with offset=%d, or head_limit=0 for all] ...\n", more, r.offset+len(kept))
}
return Text(Capture(tc, res)), true
}
+34
View File
@@ -0,0 +1,34 @@
package tool
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestRipgrepPathDisabled(t *testing.T) {
t.Setenv("NORMA_DISABLE_RIPGREP", "1")
if RipgrepPath() != "" {
t.Fatal("NORMA_DISABLE_RIPGREP should force the Go implementation")
}
}
func TestGrepViaRipgrepIfAvailable(t *testing.T) {
if _, err := exec.LookPath("rg"); err != nil {
t.Skip("rg not installed — skipping the ripgrep-backed path")
}
// Use the existing rg; never auto-install during tests.
t.Setenv("NORMA_RIPGREP_NO_INSTALL", "1")
os.Unsetenv("NORMA_DISABLE_RIPGREP")
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "x.go"), []byte("package main\nfunc Zed(){}\n"), 0o644)
os.WriteFile(filepath.Join(dir, "y.txt"), []byte("nothing here\n"), 0o644)
res := run(t, NewGrep(), dir, map[string]any{"pattern": "Zed", "output_mode": "files_with_matches"})
if !strings.Contains(res.Flatten(), "x.go") || strings.Contains(res.Flatten(), "y.txt") {
t.Fatalf("ripgrep-backed grep: %q", res.Flatten())
}
}
+110
View File
@@ -0,0 +1,110 @@
package tool
import (
"encoding/json"
"fmt"
"strings"
)
// ValidateInput checks a raw JSON input against a minimal subset of JSON Schema
// sufficient for tool inputs: object type, required properties, and per-property
// primitive type checks (string/number/integer/boolean/array/object). It never
// panics; a non-nil error means the input is invalid (FR-04.5, NFR-07).
func ValidateInput(schema map[string]any, raw json.RawMessage) error {
if schema == nil {
return nil
}
var v any
if len(raw) == 0 {
v = map[string]any{}
} else if err := json.Unmarshal(raw, &v); err != nil {
return fmt.Errorf("input is not valid JSON: %w", err)
}
return validateValue(schema, v, "")
}
func validateValue(schema map[string]any, v any, path string) error {
typ, _ := schema["type"].(string)
switch typ {
case "object", "":
m, ok := v.(map[string]any)
if !ok {
if typ == "" {
return nil
}
return fmt.Errorf("%s: expected object", at(path))
}
for _, req := range toStrings(schema["required"]) {
if _, present := m[req]; !present {
return fmt.Errorf("%s: missing required property %q", at(path), req)
}
}
props, _ := schema["properties"].(map[string]any)
for key, val := range m {
ps, ok := props[key].(map[string]any)
if !ok {
continue // unknown property — tolerate
}
if err := validateValue(ps, val, join(path, key)); err != nil {
return err
}
}
case "string":
if _, ok := v.(string); !ok {
return fmt.Errorf("%s: expected string", at(path))
}
case "integer":
if f, ok := v.(float64); !ok || f != float64(int64(f)) {
return fmt.Errorf("%s: expected integer", at(path))
}
case "number":
if _, ok := v.(float64); !ok {
return fmt.Errorf("%s: expected number", at(path))
}
case "boolean":
if _, ok := v.(bool); !ok {
return fmt.Errorf("%s: expected boolean", at(path))
}
case "array":
arr, ok := v.([]any)
if !ok {
return fmt.Errorf("%s: expected array", at(path))
}
if items, ok := schema["items"].(map[string]any); ok {
for i, el := range arr {
if err := validateValue(items, el, fmt.Sprintf("%s[%d]", path, i)); err != nil {
return err
}
}
}
}
return nil
}
func toStrings(v any) []string {
arr, ok := v.([]any)
if !ok {
return nil
}
out := make([]string, 0, len(arr))
for _, e := range arr {
if s, ok := e.(string); ok {
out = append(out, s)
}
}
return out
}
func join(path, key string) string {
if path == "" {
return key
}
return path + "." + key
}
func at(path string) string {
if path == "" {
return "input"
}
return strings.TrimPrefix(path, ".")
}
+477
View File
@@ -0,0 +1,477 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
)
var skipDirs = map[string]bool{".git": true, "node_modules": true, "vendor": true}
// NewGlob builds the Glob tool: find files by pattern, newest first.
func NewGlob() CoreTool {
return Build(Spec{
Name: "Glob",
Description: "Finds files whose path matches a glob pattern (supports ** for any depth, e.g. \"**/*.go\"). Returns paths sorted by modification time, newest first.",
Prompt: "Use this instead of `find`. The pattern matches paths relative to the search directory.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"pattern": map[string]any{"type": "string", "description": "Glob pattern, e.g. src/**/*.go"},
"path": map[string]any{"type": "string", "description": "Directory to search (default working dir)."},
},
"required": []any{"pattern"},
},
ReadOnly: always,
Concurrent: always,
Permissions: allowReadOnly,
Run: runGlob,
})
}
func runGlob(_ context.Context, input json.RawMessage, tc *ToolContext) (Result, error) {
var in struct {
Pattern string `json:"pattern"`
Path string `json:"path"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
root := tc.WorkingDir
if in.Path != "" {
root = resolvePath(tc, in.Path)
}
if root == "" {
root = "."
}
type match struct {
path string
mod int64
}
var matches []match
_ = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
if skipDirs[d.Name()] {
return filepath.SkipDir
}
return nil
}
rel, rerr := filepath.Rel(root, p)
if rerr != nil {
rel = p
}
if matchGlob(in.Pattern, rel) {
var mod int64
if info, e := d.Info(); e == nil {
mod = info.ModTime().UnixNano()
}
matches = append(matches, match{p, mod})
}
return nil
})
sort.Slice(matches, func(i, j int) bool { return matches[i].mod > matches[j].mod })
if len(matches) == 0 {
return Text("No files found"), nil
}
var b strings.Builder
for _, m := range matches {
b.WriteString(m.path)
b.WriteByte('\n')
}
return Text(Capture(tc, b.String())), nil
}
func matchGlob(pattern, path string) bool {
pattern = filepath.ToSlash(pattern)
path = filepath.ToSlash(path)
if !strings.Contains(pattern, "/") {
if ok, _ := filepath.Match(pattern, filepath.Base(path)); ok {
return true
}
}
return globSegments(strings.Split(pattern, "/"), strings.Split(path, "/"))
}
func globSegments(pat, name []string) bool {
if len(pat) == 0 {
return len(name) == 0
}
if pat[0] == "**" {
for i := 0; i <= len(name); i++ {
if globSegments(pat[1:], name[i:]) {
return true
}
}
return false
}
if len(name) == 0 {
return false
}
if ok, _ := filepath.Match(pat[0], name[0]); !ok {
return false
}
return globSegments(pat[1:], name[1:])
}
// NewGrep builds the Grep tool: regex content search (RE2).
const grepDescription = "A powerful search tool built on ripgrep\n" +
"\n" +
"Usage:\n" +
"- ALWAYS use Grep for search tasks. NEVER invoke `grep` or `rg` as a Bash command. The Grep tool has been optimized for correct permissions and access.\n" +
"- Supports full regex syntax (e.g., \"log.*Error\", \"function\\s+\\w+\")\n" +
"- Filter files with glob parameter (e.g., \"*.js\", \"**/*.tsx\") or type parameter (e.g., \"js\", \"py\", \"rust\")\n" +
"- Output modes: \"content\" shows matching lines, \"files_with_matches\" shows only file paths (default), \"count\" shows match counts\n" +
"- Use Agent tool for open-ended searches requiring multiple rounds\n" +
"- Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use `interface\\{\\}` to find `interface{}` in Go code)\n" +
"- Prefer `head_limit` to avoid large result sets.\n" +
"- Multiline matching: By default patterns match within single lines only. For cross-line patterns like `struct \\{[\\s\\S]*?field`, use `multiline: true`\n" +
"- Prefer Grep over terminal rg/grep for codebase search unless you specifically need shell features."
func NewGrep() CoreTool {
return Build(Spec{
Name: "Grep",
Description: grepDescription,
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"pattern": map[string]any{"type": "string", "description": "RE2 regular expression to search for."},
"path": map[string]any{"type": "string", "description": "File or directory to search. Defaults to the working directory."},
"glob": map[string]any{"type": "string", "description": "Only search files matching this glob, e.g. *.go or *.{ts,tsx}"},
"type": map[string]any{"type": "string", "description": "Only search a file type, e.g. go, py, js, ts, rust, java. Unknown types are treated as an extension (type:foo → *.foo)."},
"output_mode": map[string]any{"type": "string", "description": "files_with_matches (default) | content | count"},
"-i": map[string]any{"type": "boolean", "description": "Case-insensitive."},
"-n": map[string]any{"type": "boolean", "description": "Show line numbers (content mode). Default true."},
"-A": map[string]any{"type": "integer", "description": "Lines of context to show after each match (content mode)."},
"-B": map[string]any{"type": "integer", "description": "Lines of context to show before each match (content mode)."},
"-C": map[string]any{"type": "integer", "description": "Lines of context before and after each match (content mode)."},
"multiline": map[string]any{"type": "boolean", "description": "Multiline mode: . matches newlines and patterns may span lines. Default false."},
"head_limit": map[string]any{"type": "integer", "description": "Limit output to the first N results (lines/files/counts). Default 250; pass 0 for unlimited."},
"offset": map[string]any{"type": "integer", "description": "Skip the first N results before applying head_limit (paging). Default 0."},
},
"required": []any{"pattern"},
},
ReadOnly: always,
Concurrent: always,
Permissions: allowReadOnly,
Run: runGrep,
})
}
func runGrep(_ context.Context, input json.RawMessage, tc *ToolContext) (Result, error) {
var in struct {
Pattern string `json:"pattern"`
Path string `json:"path"`
Glob string `json:"glob"`
Type string `json:"type"`
OutputMode string `json:"output_mode"`
IgnoreCase bool `json:"-i"`
LineNums *bool `json:"-n"`
After int `json:"-A"`
Before int `json:"-B"`
Context int `json:"-C"`
Multiline bool `json:"multiline"`
HeadLimit *int `json:"head_limit"`
Offset int `json:"offset"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
before, after := in.Before, in.After
if in.Context > 0 {
before, after = in.Context, in.Context
}
// RE2 inline flags: (?i) case-insensitive, (?s) dotall for multiline.
flags := ""
if in.IgnoreCase {
flags += "i"
}
if in.Multiline {
flags += "s"
}
pat := in.Pattern
if flags != "" {
pat = "(?" + flags + ")" + pat
}
re, err := regexp.Compile(pat)
if err != nil {
return Errorf(fmt.Sprintf("Error: invalid regex: %v", err)), nil
}
root := tc.WorkingDir
if in.Path != "" {
root = resolvePath(tc, in.Path)
}
if root == "" {
root = "."
}
mode := in.OutputMode
if mode == "" {
mode = "files_with_matches"
}
showLines := true
if in.LineNums != nil {
showLines = *in.LineNums
}
// Prefer the ripgrep binary when available; fall back to the Go walk below.
if rg := RipgrepPath(); rg != "" {
if res, ok := runWithRipgrep(rg, ripgrepReq{
pattern: in.Pattern, glob: in.Glob, typ: in.Type, mode: mode,
ignoreCase: in.IgnoreCase, multiline: in.Multiline, showLines: showLines,
before: before, after: after, root: root, headLimit: in.HeadLimit, offset: in.Offset,
}, tc); ok {
return res, nil
}
}
typeGlobs := rgTypeGlobs(in.Type)
var results []grepHit
scan := func(p, base string) {
fh := scanFile(p, base, re, mode, showLines, in.Multiline, before, after)
if fh != nil {
results = append(results, *fh)
}
}
info, statErr := os.Stat(root)
if statErr != nil {
return Errorf(fmt.Sprintf("Error: %v", statErr)), nil
}
if info.IsDir() {
_ = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
if skipDirs[d.Name()] {
return filepath.SkipDir
}
return nil
}
base := filepath.Base(p)
if in.Glob != "" {
if ok, _ := filepath.Match(in.Glob, base); !ok {
return nil
}
}
if len(typeGlobs) > 0 && !matchAnyGlob(typeGlobs, base) {
return nil
}
scan(p, root)
return nil
})
} else {
scan(root, filepath.Dir(root))
}
if len(results) == 0 {
return Text("No matches found"), nil
}
sort.Slice(results, func(i, j int) bool { return results[i].path < results[j].path })
// Flatten to output entries per mode, then page with offset + head_limit.
var lines []string
switch mode {
case "content":
for _, r := range results {
lines = append(lines, r.lines...)
}
case "count":
for _, r := range results {
lines = append(lines, fmt.Sprintf("%s: %d", r.path, r.count))
}
default: // files_with_matches
for _, r := range results {
lines = append(lines, r.path)
}
}
headLimit := 250
if in.HeadLimit != nil {
headLimit = *in.HeadLimit
}
kept, more := applyHeadOffset(lines, headLimit, in.Offset)
out := strings.Join(kept, "\n")
if len(kept) > 0 {
out += "\n"
}
if more > 0 {
out += fmt.Sprintf("... [%d more result(s) — page with offset=%d, or head_limit=0 for all] ...\n", more, in.Offset+len(kept))
}
return Text(Capture(tc, out)), nil
}
// rgFileTypes maps a ripgrep-style file type to its globs (common subset).
var rgFileTypes = map[string][]string{
"go": {"*.go"},
"py": {"*.py", "*.pyi"},
"python": {"*.py", "*.pyi"},
"js": {"*.js", "*.jsx", "*.mjs", "*.cjs", "*.vue"},
"ts": {"*.ts", "*.tsx", "*.mts", "*.cts"},
"rust": {"*.rs"},
"java": {"*.java"},
"kotlin": {"*.kt", "*.kts"},
"c": {"*.c", "*.h"},
"cpp": {"*.cpp", "*.cc", "*.cxx", "*.hpp", "*.hh", "*.hxx", "*.h"},
"cs": {"*.cs"},
"rb": {"*.rb"},
"ruby": {"*.rb"},
"php": {"*.php"},
"swift": {"*.swift"},
"sh": {"*.sh", "*.bash", "*.zsh"},
"html": {"*.html", "*.htm"},
"css": {"*.css", "*.scss", "*.sass", "*.less"},
"json": {"*.json"},
"yaml": {"*.yaml", "*.yml"},
"toml": {"*.toml"},
"xml": {"*.xml"},
"md": {"*.md", "*.markdown"},
"markdown": {"*.md", "*.markdown"},
"sql": {"*.sql"},
"proto": {"*.proto"},
}
// rgTypeGlobs resolves a type name to its globs; an unknown type falls back to
// treating it as a bare extension (type:foo → *.foo). Empty type → nil.
func rgTypeGlobs(t string) []string {
if t == "" {
return nil
}
if g, ok := rgFileTypes[strings.ToLower(t)]; ok {
return g
}
return []string{"*." + t}
}
func matchAnyGlob(globs []string, name string) bool {
for _, g := range globs {
if ok, _ := filepath.Match(g, name); ok {
return true
}
}
return false
}
// applyHeadOffset skips the first offset entries then keeps at most limit (0 =
// unlimited). more is the number of entries beyond the kept window.
func applyHeadOffset(lines []string, limit, offset int) (kept []string, more int) {
if offset > 0 {
if offset >= len(lines) {
return nil, 0
}
lines = lines[offset:]
}
if limit > 0 && len(lines) > limit {
return lines[:limit], len(lines) - limit
}
return lines, 0
}
// grepHit holds one file's grep results.
type grepHit struct {
path string
lines []string
count int
}
func scanFile(path, base string, re *regexp.Regexp, mode string, showLines, multiline bool, before, after int) *grepHit {
data, err := os.ReadFile(path)
if err != nil || isBinary(data) {
return nil
}
rel := path
if r, e := filepath.Rel(base, path); e == nil {
rel = r
}
lines := strings.Split(string(data), "\n")
if n := len(lines); n > 0 && lines[n-1] == "" {
lines = lines[:n-1] // drop the empty element from a trailing newline
}
var matches []int
if multiline {
// Match against the whole file; a line "matches" if it overlaps any match span.
lineStart := make([]int, len(lines))
off := 0
for i, ln := range lines {
lineStart[i] = off
off += len(ln) + 1 // + newline
}
hit := make([]bool, len(lines))
for _, loc := range re.FindAllIndex(data, -1) {
s, e := loc[0], loc[1]
for i := range lines {
ls, le := lineStart[i], lineStart[i]+len(lines[i])
if s <= le && e > ls {
hit[i] = true
}
}
}
for i, h := range hit {
if h {
matches = append(matches, i)
}
}
} else {
for i, ln := range lines {
if re.MatchString(ln) {
matches = append(matches, i)
}
}
}
if len(matches) == 0 {
return nil
}
res := &grepHit{path: rel, count: len(matches)}
if mode != "content" {
return res
}
isMatch := make(map[int]bool, len(matches))
for _, m := range matches {
isMatch[m] = true
}
// Collect the set of line indices to print (matches plus context), in order.
var order []int
seen := map[int]bool{}
for _, m := range matches {
lo, hi := m-before, m+after
if lo < 0 {
lo = 0
}
if hi >= len(lines) {
hi = len(lines) - 1
}
for j := lo; j <= hi; j++ {
if !seen[j] {
seen[j] = true
order = append(order, j)
}
}
}
sort.Ints(order)
hasContext := before > 0 || after > 0
prev := -2
for _, j := range order {
if hasContext && prev >= 0 && j != prev+1 {
res.lines = append(res.lines, "--") // separate non-contiguous groups
}
sep := "-" // context line
if isMatch[j] {
sep = ":" // matching line
}
if showLines {
res.lines = append(res.lines, fmt.Sprintf("%s%s%d%s%s", rel, sep, j+1, sep, lines[j]))
} else {
res.lines = append(res.lines, fmt.Sprintf("%s%s%s", rel, sep, lines[j]))
}
prev = j
}
return res
}
+447
View File
@@ -0,0 +1,447 @@
package tool
import (
"context"
"fmt"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/hinshun/vt10x"
)
// Interactive PTY shell sessions (docs/交互式shell设计.md). A session is a persistent
// pseudo-terminal running an interactive program (msfconsole / ssh / a REPL / …) that
// the agent drives by sending input (text / named keys / raw bytes) and reading output
// incrementally (raw stream) or as a rendered screen snapshot (vt10x). Sessions live on
// the per-Session task Manager (tc.Tasks) and are cleaned up with it.
// Tunables.
const (
sessRingCap = 256 << 10 // per-session raw scrollback kept in memory
sessDefQuietMs = 8000 // silence that counts as "command done"
sessDefGraceMs = 15000 // startup grace before quiet can fire
sessDefIdleMs = 30 * 60 * 1000
sessRereadMs = 5 * 60 * 1000 // keep an exited session this long for re-reads
sessDefRows = 24
sessDefCols = 80
sessDefReadLine = 200
sessDefReadByte = 8192
sessWaitCapMs = 120000 // default hard wait ceiling for shell_send(wait)
)
// InteractiveShellDisabled reports whether interactive shell sessions are turned off
// via AGENT_CORE_DISABLE_INTERACTIVE_SHELL (mirrors BackgroundTasksDisabled).
func InteractiveShellDisabled() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("AGENT_CORE_DISABLE_INTERACTIVE_SHELL"))) {
case "1", "true", "yes", "on":
return true
}
return false
}
// ptySession is one live interactive PTY.
type ptySession struct {
id string
command string
rows int
cols int
mode string // interactive | hands-free | dispatch
prompt *regexp.Regexp
cmd *exec.Cmd
ptmx *os.File
mu sync.Mutex
buf []byte // raw scrollback (ring, capped)
total int64 // total bytes ever produced (absolute cursor space)
emu vt10x.Terminal
state string // starting | running | exited | closed
exitCode *int
lastOut time.Time
exitedAt time.Time
readCur int64 // tool-side read cursor (shell_read without since_cursor continues here)
notifyCh chan struct{} // pinged on new output
done chan struct{} // closed when the process exits
}
func (s *ptySession) readCursor() int64 {
s.mu.Lock()
defer s.mu.Unlock()
return s.readCur
}
func (s *ptySession) setReadCursor(c int64) {
s.mu.Lock()
s.readCur = c
s.mu.Unlock()
}
// --- ring buffer + output ---
func (s *ptySession) append(p []byte) {
s.mu.Lock()
s.buf = append(s.buf, p...)
s.total += int64(len(p))
if len(s.buf) > sessRingCap {
s.buf = s.buf[len(s.buf)-sessRingCap:]
}
if s.emu != nil {
_, _ = s.emu.Write(p)
}
s.lastOut = time.Now()
s.mu.Unlock()
select {
case s.notifyCh <- struct{}{}:
default:
}
}
func (s *ptySession) tailStr(n int) string {
s.mu.Lock()
defer s.mu.Unlock()
if n <= 0 || n > len(s.buf) {
return string(s.buf)
}
return string(s.buf[len(s.buf)-n:])
}
// readSince returns the output produced after absolute cursor c, advancing the
// returned cursor by exactly what is handed back (front-capped for pagination).
func (s *ptySession) readSince(c int64, maxLines, maxBytes int, drain bool) (out string, cursor int64, omitted bool) {
s.mu.Lock()
defer s.mu.Unlock()
start := s.total - int64(len(s.buf))
if c >= s.total {
return "", s.total, false
}
from := c
if from < start {
from, omitted = start, true
}
seg := s.buf[from-start:]
if !drain {
if maxBytes > 0 && len(seg) > maxBytes {
seg = seg[:maxBytes]
}
if maxLines > 0 {
if idx := nthByte(seg, '\n', maxLines); idx >= 0 {
seg = seg[:idx+1]
}
}
}
return string(seg), from + int64(len(seg)), omitted
}
func nthByte(b []byte, ch byte, n int) int {
c := 0
for i, x := range b {
if x == ch {
if c++; c == n {
return i
}
}
}
return -1
}
// screen renders the vt10x-emulated terminal grid (lazy-init: the emulator is only
// created — and the scrollback replayed into it — on the first screen read).
func (s *ptySession) screen() (grid string, rows, cols, curX, curY int) {
s.mu.Lock()
defer s.mu.Unlock()
if s.emu == nil {
s.emu = vt10x.New(vt10x.WithSize(s.cols, s.rows))
_, _ = s.emu.Write(s.buf)
}
cols, rows = s.emu.Size()
var b strings.Builder
for y := 0; y < rows; y++ {
var line strings.Builder
for x := 0; x < cols; x++ {
ch := s.emu.Cell(x, y).Char
if ch == 0 {
ch = ' '
}
line.WriteRune(ch)
}
b.WriteString(strings.TrimRight(line.String(), " "))
b.WriteByte('\n')
}
cur := s.emu.Cursor()
return b.String(), rows, cols, cur.X, cur.Y
}
func (s *ptySession) running() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.state == "starting" || s.state == "running"
}
func (s *ptySession) exit() *int {
s.mu.Lock()
defer s.mu.Unlock()
return s.exitCode
}
// waitComplete blocks until a completion signal: prompt/sentinel match on the tail,
// output silence for quiet, the process exits, or the deadline/ctx fires. Returns the
// reason. grace delays the first quiet check so a slow-starting program isn't judged done.
func (s *ptySession) waitComplete(ctx context.Context, quiet, grace, timeout time.Duration, prompt *regexp.Regexp, sentinel string) string {
dl := time.NewTimer(timeout)
defer dl.Stop()
first := quiet
if grace > first {
first = grace
}
qt := time.NewTimer(first)
defer qt.Stop()
for {
select {
case <-s.done:
return "exited"
case <-ctx.Done():
return "timeout"
case <-dl.C:
return "timeout"
case <-s.notifyCh:
tail := s.tailStr(4096)
if prompt != nil && prompt.MatchString(tail) {
return "prompt"
}
if sentinel != "" && strings.Contains(tail, sentinel) {
return "sentinel"
}
if !qt.Stop() {
select {
case <-qt.C:
default:
}
}
qt.Reset(quiet)
case <-qt.C:
return "quiet"
}
}
}
// --- Manager session methods ---
func (m *Manager) reapSessions() {
now := time.Now()
m.sessMu.Lock()
var kill []*ptySession
for id, s := range m.sessions {
s.mu.Lock()
idle := now.Sub(s.lastOut)
exited := s.state == "exited"
gone := exited && !s.exitedAt.IsZero() && now.Sub(s.exitedAt) > sessRereadMs*time.Millisecond
stale := !exited && idle > sessDefIdleMs*time.Millisecond
s.mu.Unlock()
if gone || stale {
kill = append(kill, s)
delete(m.sessions, id)
}
}
m.sessMu.Unlock()
for _, s := range kill {
s.kill()
}
}
func (s *ptySession) kill() {
s.mu.Lock()
s.state = "closed"
ptmx, cmd := s.ptmx, s.cmd
s.mu.Unlock()
if ptmx != nil {
_ = ptmx.Close()
}
if cmd != nil && cmd.Process != nil {
treeKill(cmd.Process)
}
}
func (m *Manager) closeAllSessions() {
m.sessMu.Lock()
ss := make([]*ptySession, 0, len(m.sessions))
for _, s := range m.sessions {
ss = append(ss, s)
}
m.sessions = map[string]*ptySession{}
m.sessMu.Unlock()
for _, s := range ss {
s.kill()
}
}
func (m *Manager) session(id string) (*ptySession, bool) {
m.sessMu.Lock()
defer m.sessMu.Unlock()
s, ok := m.sessions[id]
return s, ok
}
// openSession starts an interactive program in a fresh PTY and begins its read loop.
func (m *Manager) openSession(command, workDir string, env []string, rows, cols int, mode string, prompt *regexp.Regexp) (*ptySession, error) {
if !ptySupported() {
return nil, fmt.Errorf("交互式 shell(PTY) 在当前平台不支持")
}
m.reapSessions()
if rows <= 0 {
rows = sessDefRows
}
if cols <= 0 {
cols = sessDefCols
}
shell, flags := shellCmd()
cmd := exec.CommandContext(m.rootCtx, shell, append(flags, command)...)
cmd.Dir = workDir
if e := withEnv(env); e != nil {
cmd.Env = e
}
ptmx, err := startPTY(cmd, rows, cols)
if err != nil {
return nil, err
}
m.sessMu.Lock()
m.sessSeq++
id := fmt.Sprintf("sh_%d", m.sessSeq)
m.sessMu.Unlock()
s := &ptySession{
id: id, command: command, rows: rows, cols: cols, mode: mode, prompt: prompt,
cmd: cmd, ptmx: ptmx, state: "running", lastOut: time.Now(),
notifyCh: make(chan struct{}, 1), done: make(chan struct{}),
}
m.sessMu.Lock()
m.sessions[id] = s
m.sessMu.Unlock()
go m.readLoop(s)
return s, nil
}
func (m *Manager) readLoop(s *ptySession) {
b := make([]byte, 32*1024)
for {
n, err := s.ptmx.Read(b)
if n > 0 {
s.append(b[:n])
}
if err != nil {
break
}
}
_ = s.cmd.Wait()
s.mu.Lock()
if s.state != "closed" {
s.state = "exited"
}
if s.cmd.ProcessState != nil {
ec := s.cmd.ProcessState.ExitCode()
s.exitCode = &ec
}
s.exitedAt = time.Now()
s.mu.Unlock()
close(s.done)
}
// dispatchWaiter (dispatch mode) waits for the first completion signal and enqueues a
// task-notification with the tail, so the model is woken between turns to review it.
func (m *Manager) dispatchWaiter(s *ptySession, quiet, grace, timeout time.Duration) {
by := s.waitComplete(m.rootCtx, quiet, grace, timeout, s.prompt, "")
from := s.total - 4096
if from < 0 {
from = 0
}
tail, _, _ := s.readSince(from, 0, 4096, true)
status := TaskCompleted
if !s.running() {
status = TaskCompleted
}
m.enqueueSessNote(s, KindBash, status, fmt.Sprintf("交互会话 %s(%s)%s。用 shell_read(session_id=%q) 继续,或 shell_close 结束。\n%s",
s.id, short(s.command), by, s.id, tail))
}
// enqueueSessNote queues a task-notification for a session so the model is woken
// between turns (dispatch completion / monitor pattern hit / session exit).
func (m *Manager) enqueueSessNote(s *ptySession, kind TaskKind, status TaskStatus, summary string) {
m.mu.Lock()
m.pending = append(m.pending, Notification{TaskID: s.id, Kind: kind, Status: status, Summary: summary})
m.mu.Unlock()
}
// monitorWaiter (monitor mode) keeps the session alive and watches its output for any
// of the given patterns; each pattern fires a one-shot notification when first matched.
// A session exit fires a final notification. The session is NOT killed on a match.
func (m *Manager) monitorWaiter(s *ptySession, pats []*regexp.Regexp) {
fired := make([]bool, len(pats))
for {
select {
case <-m.rootCtx.Done():
return
case <-s.done:
from := s.total - 4096
if from < 0 {
from = 0
}
tail, _, _ := s.readSince(from, 0, 4096, true)
m.enqueueSessNote(s, KindMonitor, TaskCompleted,
fmt.Sprintf("监听会话 %s(%s)已结束(exit %s)。\n%s", s.id, short(s.command), fmtExit(s.exit()), tail))
return
case <-s.notifyCh:
tail := s.tailStr(8192)
for i, p := range pats {
if !fired[i] && p.MatchString(tail) {
fired[i] = true
m.enqueueSessNote(s, KindMonitor, TaskRunning,
fmt.Sprintf("监听会话 %s 命中 /%s/:\n%s", s.id, p.String(), tail))
}
}
}
}
}
// --- input building ---
var namedKeys = map[string]string{
"enter": "\r", "return": "\r", "tab": "\t", "esc": "\x1b", "escape": "\x1b",
"backspace": "\x7f", "space": " ", "up": "\x1b[A", "down": "\x1b[B",
"right": "\x1b[C", "left": "\x1b[D", "home": "\x1b[H", "end": "\x1b[F",
"pageup": "\x1b[5~", "pagedown": "\x1b[6~", "delete": "\x1b[3~", "insert": "\x1b[2~",
}
func keyToBytes(k string) (string, bool) {
k = strings.ToLower(strings.TrimSpace(k))
if v, ok := namedKeys[k]; ok {
return v, true
}
if strings.HasPrefix(k, "ctrl+") && len(k) == 6 {
c := k[5]
switch {
case c >= 'a' && c <= 'z':
return string([]byte{c & 0x1f}), true
case c == '[':
return "\x1b", true
case c == '\\':
return "\x1c", true
}
}
return "", false
}
func hexToBytes(items []string) []byte {
var out []byte
for _, h := range items {
h = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(h)), "0x")
if v, err := strconv.ParseUint(h, 16, 8); err == nil {
out = append(out, byte(v))
}
}
return out
}
+133
View File
@@ -0,0 +1,133 @@
package tool
import (
"context"
"regexp"
"strings"
"testing"
"time"
)
// TestShellToolsJSONSessionID drives the tools via their JSON input (snake_case
// session_id) to guard against missing json tags — without tags session_id never
// binds and every read/send/close reports "会话不存在".
func TestShellToolsJSONSessionID(t *testing.T) {
if !ptySupported() {
t.Skip("no PTY on this platform")
}
m, err := NewManager("test-tools")
if err != nil {
t.Fatal(err)
}
defer m.Cleanup()
s, err := m.openSession("cat", "", nil, 24, 80, "hands-free", nil)
if err != nil {
t.Fatal(err)
}
tc := &ToolContext{Tasks: m}
ctx := context.Background()
res, _ := NewShellRead().Call(ctx, []byte(`{"session_id":"`+s.id+`","view":"stream"}`), tc)
if res.IsError {
t.Fatalf("shell_read by session_id failed: %s", res.Flatten())
}
res, _ = NewShellClose().Call(ctx, []byte(`{"session_id":"`+s.id+`"}`), tc)
if res.IsError {
t.Fatalf("shell_close by session_id failed: %s", res.Flatten())
}
}
// TestShellMonitor: a session in monitor mode fires a notification when a watched
// pattern shows up in the output — without ending the session.
func TestShellMonitor(t *testing.T) {
if !ptySupported() {
t.Skip("no PTY on this platform")
}
m, err := NewManager("test-mon")
if err != nil {
t.Fatal(err)
}
defer m.Cleanup()
s, err := m.openSession("printf 'START\\n'; sleep 0.3; printf 'TRIGGERWORD\\n'; sleep 5", "", nil, 24, 80, "monitor", nil)
if err != nil {
t.Fatal(err)
}
go m.monitorWaiter(s, []*regexp.Regexp{regexp.MustCompile("TRIGGERWORD")})
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
for _, n := range m.DrainNotifications() {
if strings.Contains(n.Summary, "TRIGGERWORD") {
return // success
}
}
time.Sleep(50 * time.Millisecond)
}
t.Fatal("expected monitor notification for TRIGGERWORD")
}
// TestShellSessionEcho drives a real PTY: `cat` echoes stdin, so sending a line
// should show up in the incremental read — exercising open/send/read end to end.
func TestShellSessionEcho(t *testing.T) {
if !ptySupported() {
t.Skip("no PTY on this platform")
}
m, err := NewManager("test-shell")
if err != nil {
t.Fatal(err)
}
defer m.Cleanup()
s, err := m.openSession("cat", "", nil, 24, 80, "hands-free", nil)
if err != nil {
t.Fatalf("openSession: %v", err)
}
if _, err := s.ptmx.Write([]byte("hello-pty\r")); err != nil {
t.Fatalf("write: %v", err)
}
deadline := time.Now().Add(3 * time.Second)
var out string
for time.Now().Before(deadline) {
out, _, _ = s.readSince(0, 0, 8192, true)
if strings.Contains(out, "hello-pty") {
return // success
}
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("expected echoed input in output, got %q", out)
}
func TestKeyToBytes(t *testing.T) {
cases := map[string]string{
"ctrl+c": "\x03", "ctrl+d": "\x04", "enter": "\r", "tab": "\t",
"esc": "\x1b", "up": "\x1b[A", "backspace": "\x7f",
}
for k, want := range cases {
got, ok := keyToBytes(k)
if !ok || got != want {
t.Errorf("keyToBytes(%q)=%q,%v want %q", k, got, ok, want)
}
}
if _, ok := keyToBytes("bogus"); ok {
t.Errorf("expected bogus key to be rejected")
}
}
func TestHexToBytes(t *testing.T) {
got := hexToBytes([]string{"0x1b", "5b", "0x41"})
if string(got) != "\x1b[A" {
t.Errorf("hexToBytes=%q want ESC[A", got)
}
}
func TestReadSinceIncremental(t *testing.T) {
s := &ptySession{notifyCh: make(chan struct{}, 1)}
s.append([]byte("line1\nline2\n"))
out, cur, _ := s.readSince(0, 0, 8192, false)
if out != "line1\nline2\n" {
t.Fatalf("got %q", out)
}
s.append([]byte("line3\n"))
out2, _, _ := s.readSince(cur, 0, 8192, false)
if out2 != "line3\n" {
t.Fatalf("incremental got %q", out2)
}
}
+368
View File
@@ -0,0 +1,368 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"regexp"
"time"
"github.com/Autumn-27/norma/permission"
)
// The interactive-shell tool family (opt-in; NOT in DefaultTools). ShellSessionTools
// returns all five. They require a task Manager on the ToolContext (tc.Tasks) — that is
// where the PTY sessions live and get cleaned up. See docs/交互式shell设计.md.
// ShellSessionTools returns the five interactive-shell tools. Callers add them to
// Options.Tools only when interactive shell is enabled for the agent.
func ShellSessionTools() []CoreTool {
return []CoreTool{NewShellOpen(), NewShellSend(), NewShellRead(), NewShellClose(), NewShellList()}
}
func sessTool(name, desc string, schema map[string]any, readOnly bool, run func(context.Context, json.RawMessage, *ToolContext) (Result, error)) CoreTool {
return Build(Spec{
Name: name, Description: desc, Schema: schema,
ReadOnly: func(json.RawMessage) bool { return readOnly },
Concurrent: func(json.RawMessage) bool { return false },
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Allowed()
},
Run: run,
})
}
func obj(props map[string]any, required ...string) map[string]any {
m := map[string]any{"type": "object", "properties": props}
if len(required) > 0 {
m["required"] = required
}
return m
}
func strProp(d string) map[string]any { return map[string]any{"type": "string", "description": d} }
func boolProp(d string) map[string]any { return map[string]any{"type": "boolean", "description": d} }
func intProp(d string) map[string]any { return map[string]any{"type": "integer", "description": d} }
func arrStr(d string) map[string]any {
return map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": d}
}
func jsonResult(v any) (Result, error) {
b, err := json.Marshal(v)
if err != nil {
return Errorf("marshal: " + err.Error()), nil
}
return Text(string(b)), nil
}
func sessManager(tc *ToolContext) (*Manager, *Result) {
if InteractiveShellDisabled() {
r := Errorf("交互式 shell 已被全局停用(AGENT_CORE_DISABLE_INTERACTIVE_SHELL)")
return nil, &r
}
if tc == nil || tc.Tasks == nil {
r := Errorf("交互式 shell 需要后台任务管理器(未启用)")
return nil, &r
}
return tc.Tasks, nil
}
func ms(v int, def int) time.Duration {
if v <= 0 {
v = def
}
return time.Duration(v) * time.Millisecond
}
// NewShellOpen 开一个交互会话。
func NewShellOpen() CoreTool {
desc := "开一个持久 PTY 交互会话运行【交互式/需真 TTY 的程序】(msfconsole/ssh 交互/mysql、python 等 REPL/密码提示/nc 会话),返回 session_id。**一次性、非交互命令用 Bash**。mode: interactive=阻塞到首个提示符/静默再返回启动输出; hands-free(默认)=立即返回, 之后用 shell_read 轮询; dispatch=立即返回, 完成时发通知; monitor=立即返回, 后台盯 watch 关键词命中即发通知(会话不结束, 仅本次运行内存活)。可设 prompt_regex(如 'msf6? >\\s*$')精确判定完成。用完务必 shell_close。"
schema := obj(map[string]any{
"command": strProp("要运行的交互程序,如 'msfconsole -q' / 'ssh user@host' / 'python3'"),
"mode": strProp("interactive | hands-free(默认) | dispatch | monitor"),
"watch": arrStr("monitor 模式必填:要盯的关键词/正则数组,输出里命中任一即发通知(每个只报一次)"),
"prompt_regex": strProp("可选:命令完成判定的提示符正则(匹配输出末尾)"),
"rows": intProp("可选:PTY 行数(默认 24)"),
"cols": intProp("可选:PTY 列数(默认 80)"),
"quiet_ms": intProp("可选:静默多少毫秒算完成(默认 8000)"),
"startup_grace_ms": intProp("可选:启动宽限毫秒,此期间不触发静默判定(默认 15000)"),
}, "command")
return sessTool("shell_open", desc, schema, false, func(ctx context.Context, in json.RawMessage, tc *ToolContext) (Result, error) {
m, errR := sessManager(tc)
if errR != nil {
return *errR, nil
}
var a struct {
Command string `json:"command"`
Mode string `json:"mode"`
PromptRegex string `json:"prompt_regex"`
Watch []string `json:"watch"`
Rows int `json:"rows"`
Cols int `json:"cols"`
QuietMs int `json:"quiet_ms"`
StartupGraceMs int `json:"startup_grace_ms"`
}
_ = json.Unmarshal(in, &a)
if a.Command == "" {
return Errorf("command 必填"), nil
}
mode := a.Mode
if mode == "" {
mode = "hands-free"
}
switch mode {
case "hands-free", "interactive", "dispatch", "monitor":
default:
return Errorf("mode 需为 interactive | hands-free | dispatch | monitor"), nil
}
var watch []*regexp.Regexp
if mode == "monitor" {
if len(a.Watch) == 0 {
return Errorf("monitor 模式必须给 watch(要盯的关键词/正则)"), nil
}
for _, w := range a.Watch {
re, err := regexp.Compile(w)
if err != nil {
return Errorf("watch 正则无效 " + w + ": " + err.Error()), nil
}
watch = append(watch, re)
}
}
var pr *regexp.Regexp
if a.PromptRegex != "" {
re, err := regexp.Compile(a.PromptRegex)
if err != nil {
return Errorf("prompt_regex 无效: " + err.Error()), nil
}
pr = re
}
workDir := ""
var env []string
if tc != nil {
workDir, env = tc.WorkingDir, tc.Env
}
s, err := m.openSession(a.Command, workDir, env, a.Rows, a.Cols, mode, pr)
if err != nil {
return Errorf("开启会话失败: " + err.Error()), nil
}
quiet, grace := ms(a.QuietMs, sessDefQuietMs), ms(a.StartupGraceMs, sessDefGraceMs)
switch mode {
case "interactive":
by := s.waitComplete(ctx, quiet, grace, ms(0, sessWaitCapMs), pr, "")
out, cur, _ := s.readSince(0, 0, sessDefReadByte*4, false)
return jsonResult(map[string]any{"session_id": s.id, "state": "running", "done_by": by, "output": out, "cursor": cur, "running": s.running()})
case "dispatch":
go m.dispatchWaiter(s, quiet, grace, ms(0, sessWaitCapMs))
return jsonResult(map[string]any{"session_id": s.id, "state": "running", "dispatched": true})
case "monitor":
go m.monitorWaiter(s, watch)
return jsonResult(map[string]any{"session_id": s.id, "state": "running", "monitoring": len(watch)})
default: // hands-free
return jsonResult(map[string]any{"session_id": s.id, "state": "running"})
}
})
}
// NewShellSend 向会话发送输入/按键。
func NewShellSend() CoreTool {
desc := "向一个交互会话发送输入:text/submit/keys/hex/paste 可组合,按出现顺序发送(各参数含义见字段)。wait=true(默认)等命令完成并带回增量输出。"
schema := obj(map[string]any{
"session_id": strProp("会话 id(shell_open 返回)"),
"text": strProp("要输入的文本(不自动回车)"),
"submit": boolProp("是否在文本后追加回车执行"),
"keys": arrStr("具名键: ctrl+c/ctrl+d/tab/enter/esc/up/down/left/right/..."),
"hex": arrStr("原始字节的十六进制, 如 ['0x1b','0x5b','0x41']"),
"paste": strProp("多行粘贴(bracketed paste, 不触发逐行执行)"),
"wait": boolProp("是否同步等到命令完成(默认 true)"),
"prompt_regex": strProp("可选:覆盖会话默认的完成判定提示符"),
"quiet_ms": intProp("可选:静默判定阈值毫秒(默认 8000)"),
"timeout_ms": intProp("可选:wait 的硬超时毫秒(默认 120000)"),
}, "session_id")
return sessTool("shell_send", desc, schema, false, func(ctx context.Context, in json.RawMessage, tc *ToolContext) (Result, error) {
m, errR := sessManager(tc)
if errR != nil {
return *errR, nil
}
var a struct {
SessionID string `json:"session_id"`
Text string `json:"text"`
Paste string `json:"paste"`
PromptRegex string `json:"prompt_regex"`
Submit bool `json:"submit"`
Keys []string `json:"keys"`
Hex []string `json:"hex"`
Wait *bool `json:"wait"`
QuietMs int `json:"quiet_ms"`
TimeoutMs int `json:"timeout_ms"`
}
_ = json.Unmarshal(in, &a)
s, ok := m.session(a.SessionID)
if !ok {
return Errorf("会话不存在: " + a.SessionID), nil
}
if !s.running() {
return Errorf("会话已结束(exit " + fmtExit(s.exit()) + "),用 shell_read 读取尾部输出或 shell_close"), nil
}
before := s.total
// build & write input in order: text, submit(\r), keys, hex, paste
var payload []byte
if a.Text != "" {
payload = append(payload, a.Text...)
}
if a.Submit {
payload = append(payload, '\r')
}
for _, k := range a.Keys {
if b, ok := keyToBytes(k); ok {
payload = append(payload, b...)
} else {
return Errorf("未知按键: " + k), nil
}
}
if len(a.Hex) > 0 {
payload = append(payload, hexToBytes(a.Hex)...)
}
if a.Paste != "" {
payload = append(payload, "\x1b[200~"...)
payload = append(payload, a.Paste...)
payload = append(payload, "\x1b[201~"...)
}
if len(payload) == 0 {
return Errorf("没有可发送的输入(text/submit/keys/hex/paste 至少给一个)"), nil
}
if _, err := s.ptmx.Write(payload); err != nil {
return Errorf("写入失败: " + err.Error()), nil
}
wait := a.Wait == nil || *a.Wait
if !wait {
return jsonResult(map[string]any{"session_id": s.id, "sent": len(payload), "running": s.running()})
}
pr := s.prompt
if a.PromptRegex != "" {
if re, err := regexp.Compile(a.PromptRegex); err == nil {
pr = re
}
}
by := s.waitComplete(ctx, ms(a.QuietMs, sessDefQuietMs), 0, ms(a.TimeoutMs, sessWaitCapMs), pr, "")
out, cur, omitted := s.readSince(before, 0, sessDefReadByte, false)
return jsonResult(map[string]any{"session_id": s.id, "output": out, "done_by": by, "cursor": cur, "running": s.running(), "omitted": omitted})
})
}
// NewShellRead 读输出:增量流 或 整屏快照。
func NewShellRead() CoreTool {
desc := "读一个交互会话的输出(不发输入)。view=stream(默认)增量原始流(流式首选,续读/可 drain 取全量); view=screen 整屏 vt 快照(适合 vim/htop 等全屏程序)。"
schema := obj(map[string]any{
"session_id": strProp("会话 id"),
"view": strProp("stream(默认) | screen"),
"since_cursor": intProp("stream: 从该游标之后读; 不传则用会话内部游标续读"),
"max_lines": intProp("stream: 最多返回行数(默认 200)"),
"max_bytes": intProp("stream: 最多返回字节(默认 8192)"),
"drain": boolProp("stream: true=返回自上次以来全部原始流(忽略上限)"),
}, "session_id")
// per-session read cursor kept here (tool-side) so unspecified reads continue.
return sessTool("shell_read", desc, schema, true, func(_ context.Context, in json.RawMessage, tc *ToolContext) (Result, error) {
m, errR := sessManager(tc)
if errR != nil {
return *errR, nil
}
var a struct {
SessionID string `json:"session_id"`
View string `json:"view"`
SinceCursor *int64 `json:"since_cursor"`
MaxLines int `json:"max_lines"`
MaxBytes int `json:"max_bytes"`
Drain bool `json:"drain"`
}
_ = json.Unmarshal(in, &a)
s, ok := m.session(a.SessionID)
if !ok {
return Errorf("会话不存在: " + a.SessionID), nil
}
if a.View == "screen" {
grid, rows, cols, cx, cy := s.screen()
return jsonResult(map[string]any{"view": "screen", "screen": grid, "rows": rows, "cols": cols,
"cursor": map[string]int{"row": cy, "col": cx}, "running": s.running()})
}
var from int64
if a.SinceCursor != nil {
from = *a.SinceCursor
} else {
from = s.readCursor()
}
maxLines, maxBytes := a.MaxLines, a.MaxBytes
if maxLines == 0 {
maxLines = sessDefReadLine
}
if maxBytes == 0 {
maxBytes = sessDefReadByte
}
out, cur, omitted := s.readSince(from, maxLines, maxBytes, a.Drain)
s.setReadCursor(cur)
res := map[string]any{"view": "stream", "output": out, "cursor": cur, "running": s.running(), "omitted": omitted}
if ec := s.exit(); ec != nil {
res["exit_code"] = *ec
}
return jsonResult(res)
})
}
// NewShellClose 关闭会话。
func NewShellClose() CoreTool {
schema := obj(map[string]any{"session_id": strProp("会话 id")}, "session_id")
return sessTool("shell_close", "关闭一个交互会话(杀掉进程、释放 PTY)。", schema, false, func(_ context.Context, in json.RawMessage, tc *ToolContext) (Result, error) {
m, errR := sessManager(tc)
if errR != nil {
return *errR, nil
}
var a struct {
SessionID string `json:"session_id"`
}
_ = json.Unmarshal(in, &a)
s, ok := m.session(a.SessionID)
if !ok {
return Errorf("会话不存在: " + a.SessionID), nil
}
ec := s.exit()
s.kill()
m.sessMu.Lock()
delete(m.sessions, a.SessionID)
m.sessMu.Unlock()
return jsonResult(map[string]any{"closed": a.SessionID, "exit_code": exitOrNil(ec)})
})
}
// NewShellList 列出会话。
func NewShellList() CoreTool {
return sessTool("shell_list", "列出当前所有交互会话及状态。", obj(map[string]any{}), true, func(_ context.Context, _ json.RawMessage, tc *ToolContext) (Result, error) {
m, errR := sessManager(tc)
if errR != nil {
return *errR, nil
}
m.reapSessions()
m.sessMu.Lock()
defer m.sessMu.Unlock()
out := make([]map[string]any, 0, len(m.sessions))
for _, s := range m.sessions {
s.mu.Lock()
out = append(out, map[string]any{"session_id": s.id, "command": s.command, "state": s.state,
"mode": s.mode, "idle_ms": time.Since(s.lastOut).Milliseconds()})
s.mu.Unlock()
}
return jsonResult(map[string]any{"sessions": out})
})
}
// --- small helpers ---
func fmtExit(ec *int) string {
if ec == nil {
return "?"
}
return fmt.Sprintf("%d", *ec)
}
func exitOrNil(ec *int) any {
if ec == nil {
return nil
}
return *ec
}
+52
View File
@@ -0,0 +1,52 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"time"
)
// NewSleep returns a tool that waits N seconds, interruptible via context. It pairs
// with background task execution: after spawning long-running work (e.g. a Bash
// command with run_in_background), an agent can sleep, then read partial output with
// TaskOutput. Part of DefaultTools — every agent gets it.
//
// The wait is cancelled the moment ctx is done (pause/stop/timeout), returning
// promptly rather than blocking out the deadline.
func NewSleep() CoreTool {
return Build(Spec{
Name: "sleep",
Description: "Waits for N seconds, then returns. Use to let a backgrounded command make progress before reading its partial output with TaskOutput. Interrupted immediately if the run is paused or stopped.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"seconds": map[string]any{"type": "integer", "description": "Seconds to wait, 1-3600."},
},
"required": []string{"seconds"},
},
ReadOnly: always,
Concurrent: always,
Permissions: allowReadOnly,
Run: runSleep,
})
}
func runSleep(ctx context.Context, in json.RawMessage, _ *ToolContext) (Result, error) {
var a struct {
Seconds int `json:"seconds"`
}
_ = json.Unmarshal(in, &a)
if a.Seconds < 1 {
a.Seconds = 1
}
if a.Seconds > 3600 {
a.Seconds = 3600
}
select {
case <-time.After(time.Duration(a.Seconds) * time.Second):
return Text(fmt.Sprintf("slept %ds", a.Seconds)), nil
case <-ctx.Done():
return Text("sleep interrupted"), nil
}
}
+40
View File
@@ -0,0 +1,40 @@
package tool
import (
"context"
"encoding/json"
"testing"
"time"
)
func TestSleepReturns(t *testing.T) {
tl := NewSleep()
if tl.Name() != "sleep" || !tl.IsReadOnly(nil) {
t.Fatalf("unexpected identity: name=%q readonly=%v", tl.Name(), tl.IsReadOnly(nil))
}
res, err := tl.Call(context.Background(), json.RawMessage(`{"seconds":1}`), nil)
if err != nil || res.IsError {
t.Fatalf("call: err=%v res=%v", err, res)
}
if got := res.Flatten(); got != "slept 1s" {
t.Fatalf("got %q, want %q", got, "slept 1s")
}
}
func TestSleepInterrupted(t *testing.T) {
// A large requested duration must return promptly once ctx is cancelled, not
// block out the (clamped) wait.
ctx, cancel := context.WithCancel(context.Background())
go func() { time.Sleep(20 * time.Millisecond); cancel() }()
start := time.Now()
res, err := NewSleep().Call(ctx, json.RawMessage(`{"seconds":3600}`), nil)
if err != nil {
t.Fatal(err)
}
if elapsed := time.Since(start); elapsed > time.Second {
t.Fatalf("interrupt too slow: %v", elapsed)
}
if got := res.Flatten(); got != "sleep interrupted" {
t.Fatalf("got %q, want interrupted", got)
}
}
+591
View File
@@ -0,0 +1,591 @@
package tool
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)
// Background task execution.
//
// A Manager owns the set of background processes started during a Session. Each
// task runs detached from the per-turn context (so it outlives the agent turn
// that launched it), streams its combined stdout/stderr to a per-task file on
// disk, and — when it finishes — enqueues a notification the harness drains into
// the conversation. The model is told only the task id, status, and output-file
// path; it reads the actual output on demand (Read or the TaskOutput tool).
// TaskStatus is the lifecycle state of a background task.
type TaskStatus string
const (
TaskRunning TaskStatus = "running"
TaskCompleted TaskStatus = "completed"
TaskFailed TaskStatus = "failed"
TaskKilled TaskStatus = "killed"
)
// Terminal reports whether the status is final (the process has exited).
func (s TaskStatus) Terminal() bool {
return s == TaskCompleted || s == TaskFailed || s == TaskKilled
}
// TaskKind distinguishes a one-shot background command from a long-lived monitor.
type TaskKind string
const (
KindBash TaskKind = "bash"
KindMonitor TaskKind = "monitor"
)
// Tunables for the on-disk output store.
const (
// maxTaskOutputBytes caps a single task's output file; a task that exceeds it
// is terminated to keep a runaway process from filling the disk.
maxTaskOutputBytes = 50 << 20 // 50 MiB
// staleSessionTTL bounds how long another session's task directory survives
// before it is garbage-collected on the next Manager creation.
staleSessionTTL = 24 * time.Hour
)
// Task is a single background process tracked by a Manager. Its mutable fields
// are guarded by Manager.mu; read snapshots through Manager methods (which copy
// into TaskInfo).
type Task struct {
ID string
Kind TaskKind
Command string
Description string
Status TaskStatus
ExitCode int
StartTime time.Time
EndTime time.Time
OutputPath string
// internal, guarded by Manager.mu
backgrounded bool // surfaced as a background task: notify on exit
notified bool // completion already enqueued into pending
oversize bool // terminated by the size watchdog
cmd *exec.Cmd
done chan struct{} // closed by watch when the process exits
}
func (t *Task) info() TaskInfo {
return TaskInfo{
ID: t.ID, Kind: t.Kind, Command: t.Command, Description: t.Description,
Status: t.Status, ExitCode: t.ExitCode,
StartTime: t.StartTime, EndTime: t.EndTime,
OutputPath: t.OutputPath, Backgrounded: t.backgrounded,
}
}
// TaskInfo is an immutable snapshot of a task for safe reads outside the lock.
type TaskInfo struct {
ID string
Kind TaskKind
Command string
Description string
Status TaskStatus
ExitCode int
StartTime time.Time
EndTime time.Time
OutputPath string
Backgrounded bool
}
// Notification is surfaced to the model when a backgrounded task exits.
type Notification struct {
TaskID string
Kind TaskKind
Status TaskStatus
OutputPath string
Summary string
}
// String renders the notification as the <task-notification> block injected into
// the conversation. It deliberately carries only the path, not the output.
func (n Notification) String() string {
return fmt.Sprintf("<task-notification>\n"+
" <task-id>%s</task-id>\n"+
" <task-type>%s</task-type>\n"+
" <status>%s</status>\n"+
" <output-file>%s</output-file>\n"+
" <summary>%s</summary>\n"+
"</task-notification>",
n.TaskID, n.Kind, n.Status, n.OutputPath, n.Summary)
}
// SpawnSpec describes a process to launch in the background.
type SpawnSpec struct {
Command string
Description string
Kind TaskKind
WorkingDir string
// Env holds extra "KEY=VALUE" entries layered onto the process environment for
// this command (see ToolContext.Env). Empty = inherit unchanged.
Env []string
}
// withEnv returns the current process environment extended with extra
// "KEY=VALUE" entries, or nil when extra is empty (child inherits unchanged).
// os/exec dedups by key — case-insensitive on Windows, keeping the LAST
// occurrence — so the appended entries override inherited ones on every OS.
func withEnv(extra []string) []string {
if len(extra) == 0 {
return nil
}
return append(os.Environ(), extra...)
}
// Manager owns the background tasks of one Session.
type Manager struct {
mu sync.Mutex
tasks map[string]*Task
order []string
pending []Notification
dir string
seq int
rootCtx context.Context
rootCancel context.CancelFunc
// interactive PTY shell sessions (see shell_session.go). Separate map + mutex
// from the file-based tasks above: sessions are persistent, stdin-driven, and
// keep an in-memory ring buffer rather than streaming to a file.
sessMu sync.Mutex
sessions map[string]*ptySession
sessSeq int
}
func baseTaskDir() string { return filepath.Join(os.TempDir(), "norma") }
// NewManager creates the per-session task directory and garbage-collects stale
// directories left by previous sessions.
func NewManager(sessionID string) (*Manager, error) {
if sessionID == "" {
sessionID = "default"
}
dir := filepath.Join(baseTaskDir(), sessionID, "tasks")
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
cleanStaleSessions(baseTaskDir(), sessionID)
ctx, cancel := context.WithCancel(context.Background())
return &Manager{
tasks: map[string]*Task{},
sessions: map[string]*ptySession{},
dir: dir,
rootCtx: ctx,
rootCancel: cancel,
}, nil
}
// cleanStaleSessions removes sibling session directories older than the TTL.
func cleanStaleSessions(base, current string) {
entries, err := os.ReadDir(base)
if err != nil {
return
}
cutoff := time.Now().Add(-staleSessionTTL)
for _, e := range entries {
if !e.IsDir() || e.Name() == current {
continue
}
info, err := e.Info()
if err != nil {
continue
}
if info.ModTime().Before(cutoff) {
_ = os.RemoveAll(filepath.Join(base, e.Name()))
}
}
}
// Spawn launches a process detached from the per-turn context. Its output streams
// to a file; a watch goroutine records the exit status and (if backgrounded) a
// completion notification.
func (m *Manager) Spawn(spec SpawnSpec) (*Task, error) {
m.mu.Lock()
m.seq++
id := fmt.Sprintf("task_%d", m.seq)
m.mu.Unlock()
outPath := filepath.Join(m.dir, id+".output")
f, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
return nil, err
}
kind := spec.Kind
if kind == "" {
kind = KindBash
}
shell, flags := shellCmd()
cmd := exec.CommandContext(m.rootCtx, shell, append(flags, spec.Command)...)
cmd.Dir = spec.WorkingDir
if env := withEnv(spec.Env); env != nil {
cmd.Env = env
}
cmd.Stdout = f
cmd.Stderr = f
setDetached(cmd)
if err := cmd.Start(); err != nil {
_ = f.Close()
_ = os.Remove(outPath)
return nil, err
}
t := &Task{
ID: id,
Kind: kind,
Command: spec.Command,
Description: spec.Description,
Status: TaskRunning,
StartTime: time.Now(),
OutputPath: outPath,
cmd: cmd,
done: make(chan struct{}),
}
m.mu.Lock()
m.tasks[id] = t
m.order = append(m.order, id)
m.mu.Unlock()
go m.watch(t, f)
return t, nil
}
func (m *Manager) watch(t *Task, f *os.File) {
stop := make(chan struct{})
go m.watchSize(t, stop)
err := t.cmd.Wait()
close(stop)
_ = f.Close()
m.mu.Lock()
if t.Status == TaskRunning { // not pre-empted by Kill / watchdog
if err == nil {
t.Status = TaskCompleted
t.ExitCode = 0
} else if ee, ok := err.(*exec.ExitError); ok {
t.Status = TaskFailed
t.ExitCode = ee.ExitCode()
} else {
t.Status = TaskFailed
t.ExitCode = -1
}
}
t.EndTime = time.Now()
close(t.done)
if t.backgrounded && !t.notified && (t.Status == TaskCompleted || t.Status == TaskFailed) {
t.notified = true
m.pending = append(m.pending, m.notifFor(t))
}
m.mu.Unlock()
}
// watchSize terminates a task whose output file grows past the cap.
func (m *Manager) watchSize(t *Task, stop chan struct{}) {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-stop:
return
case <-ticker.C:
if fi, err := os.Stat(t.OutputPath); err == nil && fi.Size() > maxTaskOutputBytes {
m.terminate(t, TaskFailed, true)
return
}
}
}
}
// terminate kills a still-running task, recording the given terminal status. The
// watch goroutine observes the exit and finalizes EndTime / notifications.
func (m *Manager) terminate(t *Task, status TaskStatus, oversize bool) {
m.mu.Lock()
if t.Status != TaskRunning {
m.mu.Unlock()
return
}
t.Status = status
t.oversize = oversize
proc := t.cmd.Process
m.mu.Unlock()
if proc != nil {
treeKill(proc)
}
}
func (m *Manager) notifFor(t *Task) Notification {
var sum string
switch {
case t.oversize:
sum = fmt.Sprintf("Task %q 输出超过上限已被终止 (%s)。", short(t.Command), t.Kind)
case t.Status == TaskCompleted:
sum = fmt.Sprintf("Task %q 已完成 (exit %d)。用 TaskOutput 或 Read 读取输出文件。", short(t.Command), t.ExitCode)
case t.Status == TaskFailed:
sum = fmt.Sprintf("Task %q 失败 (exit %d)。用 TaskOutput 或 Read 读取输出文件。", short(t.Command), t.ExitCode)
default:
sum = fmt.Sprintf("Task %q %s。", short(t.Command), t.Status)
}
return Notification{TaskID: t.ID, Kind: t.Kind, Status: t.Status, OutputPath: t.OutputPath, Summary: sum}
}
// Background marks a task as backgrounded: its completion will be surfaced to the
// model. If the task already finished (a race against a fast command), the
// notification is enqueued immediately.
func (m *Manager) Background(id string) {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tasks[id]
if !ok {
return
}
t.backgrounded = true
if t.Status.Terminal() && !t.notified && (t.Status == TaskCompleted || t.Status == TaskFailed) {
t.notified = true
m.pending = append(m.pending, m.notifFor(t))
}
}
// Forget removes a task from the registry and deletes its output file. Used for
// foreground commands once their output has been returned inline.
func (m *Manager) Forget(id string) {
m.mu.Lock()
t, ok := m.tasks[id]
if ok {
delete(m.tasks, id)
for i, n := range m.order {
if n == id {
m.order = append(m.order[:i], m.order[i+1:]...)
break
}
}
}
m.mu.Unlock()
if ok {
_ = os.Remove(t.OutputPath)
}
}
// RunForeground starts a task and waits up to timeout. finished is true if the
// process exited within the timeout (output is then returned); otherwise the task
// keeps running and the caller decides whether to background or kill it. A
// cancelled ctx kills the task and returns ctx.Err().
func (m *Manager) RunForeground(ctx context.Context, spec SpawnSpec, timeout time.Duration) (t *Task, finished bool, output string, err error) {
t, err = m.Spawn(spec)
if err != nil {
return nil, false, "", err
}
if timeout <= 0 {
timeout = 120 * time.Second
}
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-t.done:
out, _ := m.Output(t.ID, 0)
return t, true, out, nil
case <-timer.C:
return t, false, "", nil
case <-ctx.Done():
m.Kill(t.ID)
<-t.done
return t, false, "", ctx.Err()
}
}
// Kill terminates a running task (process tree) and marks it killed.
func (m *Manager) Kill(id string) bool {
m.mu.Lock()
t, ok := m.tasks[id]
m.mu.Unlock()
if !ok {
return false
}
m.terminate(t, TaskKilled, false)
return true
}
// KillAll terminates every running task and returns how many were stopped.
func (m *Manager) KillAll() int {
m.mu.Lock()
ts := make([]*Task, 0, len(m.tasks))
for _, t := range m.tasks {
ts = append(ts, t)
}
m.mu.Unlock()
n := 0
for _, t := range ts {
m.mu.Lock()
running := t.Status == TaskRunning
m.mu.Unlock()
if running {
m.terminate(t, TaskKilled, false)
n++
}
}
return n
}
// Get returns a snapshot of one task.
func (m *Manager) Get(id string) (TaskInfo, bool) {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tasks[id]
if !ok {
return TaskInfo{}, false
}
return t.info(), true
}
// List returns snapshots of all tasks in creation order.
func (m *Manager) List() []TaskInfo {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]TaskInfo, 0, len(m.order))
for _, id := range m.order {
if t, ok := m.tasks[id]; ok {
out = append(out, t.info())
}
}
return out
}
// Wait blocks until the task exits or the timeout/ctx fires. ok is true only if
// the task reached a terminal state.
func (m *Manager) Wait(ctx context.Context, id string, timeout time.Duration) (TaskInfo, bool) {
m.mu.Lock()
t, ok := m.tasks[id]
m.mu.Unlock()
if !ok {
return TaskInfo{}, false
}
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-t.done:
info, _ := m.Get(id)
return info, true
case <-timer.C:
info, _ := m.Get(id)
return info, false
case <-ctx.Done():
info, _ := m.Get(id)
return info, false
}
}
// Output returns the tail of a task's output file, up to maxBytes (default 30000).
func (m *Manager) Output(id string, maxBytes int) (string, error) {
m.mu.Lock()
t, ok := m.tasks[id]
m.mu.Unlock()
if !ok {
return "", fmt.Errorf("unknown task %q", id)
}
return tailFile(t.OutputPath, maxBytes)
}
// DrainNotifications returns and clears the pending completion notifications.
func (m *Manager) DrainNotifications() []Notification {
m.mu.Lock()
defer m.mu.Unlock()
if len(m.pending) == 0 {
return nil
}
out := m.pending
m.pending = nil
return out
}
// Cleanup kills all tasks, cancels the root context, and removes the session's
// task directory. Safe to call on a nil Manager.
func (m *Manager) Cleanup() {
if m == nil {
return
}
m.KillAll()
m.closeAllSessions()
if m.rootCancel != nil {
m.rootCancel()
}
_ = os.RemoveAll(filepath.Dir(m.dir)) // <base>/<sessionID>
}
// tailFile reads the last maxBytes of a file, prefixing a notice when earlier
// output is omitted.
func tailFile(path string, maxBytes int) (string, error) {
if maxBytes <= 0 {
maxBytes = defaultMaxOutput
}
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return "", err
}
size := fi.Size()
if size <= int64(maxBytes) {
b, err := io.ReadAll(f)
if err != nil {
return "", err
}
return string(b), nil
}
off := size - int64(maxBytes)
if _, err := f.Seek(off, io.SeekStart); err != nil {
return "", err
}
b, err := io.ReadAll(f)
if err != nil {
return "", err
}
return fmt.Sprintf("[%d KB of earlier output omitted — read the output file directly for full output]\n", off/1024) + string(b), nil
}
// shellCmd returns the platform shell and the argument flags that precede the
// command string. On Windows it uses PowerShell with -NoProfile -NonInteractive
// (the command is passed to -Command) so a user profile can't inject banners or
// prompts and an interactive prompt can't hang an unattended run. Elsewhere it
// uses `bash -c`.
func shellCmd() (string, []string) {
if runtime.GOOS == "windows" {
return "powershell", []string{"-NoProfile", "-NonInteractive", "-Command"}
}
return "bash", []string{"-c"}
}
// short trims a command to a compact single-line label for summaries.
func short(s string) string {
s = strings.TrimSpace(s)
s = strings.ReplaceAll(s, "\n", " ")
if len(s) > 60 {
return s[:57] + "..."
}
return s
}
// BackgroundTasksDisabled reports whether background execution is turned off via
// the AGENT_CORE_DISABLE_BACKGROUND_TASKS environment variable.
func BackgroundTasksDisabled() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("AGENT_CORE_DISABLE_BACKGROUND_TASKS"))) {
case "1", "true", "yes", "on":
return true
}
return false
}
+258
View File
@@ -0,0 +1,258 @@
package tool
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func runTC(t *testing.T, tl CoreTool, tc *ToolContext, in any) Result {
t.Helper()
raw, _ := json.Marshal(in)
if err := ValidateInput(tl.InputSchema(), raw); err != nil {
t.Fatalf("%s schema: %v", tl.Name(), err)
}
res, err := tl.Call(context.Background(), raw, tc)
if err != nil {
t.Fatalf("%s: %v", tl.Name(), err)
}
return res
}
func newTestManager(t *testing.T) *Manager {
t.Helper()
m, err := NewManager("test-" + t.Name())
if err != nil {
t.Fatalf("NewManager: %v", err)
}
t.Cleanup(m.Cleanup)
return m
}
func waitTerminal(t *testing.T, m *Manager, id string) TaskInfo {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
if info, ok := m.Get(id); ok && info.Status.Terminal() {
return info
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("task %s did not reach a terminal state", id)
return TaskInfo{}
}
// A backgrounded task records its exit and enqueues a completion notification
// carrying the output-file path (not the output itself).
func TestManagerSpawnCompleteNotifies(t *testing.T) {
m := newTestManager(t)
// Output ("42") deliberately differs from the command text so we can assert the
// notification carries the path, not the output.
task, err := m.Spawn(SpawnSpec{Command: `expr 6 \* 7`})
if err != nil {
t.Fatalf("Spawn: %v", err)
}
m.Background(task.ID)
info := waitTerminal(t, m, task.ID)
if info.Status != TaskCompleted || info.ExitCode != 0 {
t.Fatalf("status=%s exit=%d", info.Status, info.ExitCode)
}
out, err := m.Output(task.ID, 0)
if err != nil || !strings.Contains(out, "42") {
t.Fatalf("output=%q err=%v", out, err)
}
notes := m.DrainNotifications()
if len(notes) != 1 || notes[0].Status != TaskCompleted {
t.Fatalf("notifications=%+v", notes)
}
if !strings.Contains(notes[0].String(), task.OutputPath) {
t.Fatalf("notification should carry the output path: %s", notes[0].String())
}
if strings.Contains(notes[0].String(), "42") {
t.Fatalf("notification must NOT carry the output content: %s", notes[0].String())
}
// Drained once; nothing left.
if again := m.DrainNotifications(); len(again) != 0 {
t.Fatalf("notifications not cleared after drain: %+v", again)
}
}
// A failing command records a non-zero exit code.
func TestManagerFailedExitCode(t *testing.T) {
m := newTestManager(t)
task, _ := m.Spawn(SpawnSpec{Command: "exit 3"})
m.Background(task.ID)
info := waitTerminal(t, m, task.ID)
if info.Status != TaskFailed || info.ExitCode != 3 {
t.Fatalf("status=%s exit=%d", info.Status, info.ExitCode)
}
}
// Bash run_in_background returns immediately and the task is later readable.
func TestBashExplicitBackground(t *testing.T) {
m := newTestManager(t)
tc := &ToolContext{Tasks: m}
res := runTC(t, NewBash(), tc, map[string]any{"command": "echo bg-out", "run_in_background": true})
if res.IsError || !strings.Contains(res.Flatten(), "background") {
t.Fatalf("expected background launch: %q (err=%v)", res.Flatten(), res.IsError)
}
tasks := m.List()
if len(tasks) != 1 {
t.Fatalf("expected 1 task, got %d", len(tasks))
}
id := tasks[0].ID
waitTerminal(t, m, id)
out := runTC(t, NewTaskOutput(), tc, map[string]any{"task_id": id}).Flatten()
if !strings.Contains(out, "bg-out") {
t.Fatalf("TaskOutput=%q", out)
}
}
// A foreground command returns its output inline and leaves no task behind.
func TestBashForegroundInline(t *testing.T) {
m := newTestManager(t)
tc := &ToolContext{Tasks: m}
res := runTC(t, NewBash(), tc, map[string]any{"command": "echo fg-out"})
if res.IsError || !strings.Contains(res.Flatten(), "fg-out") {
t.Fatalf("foreground output=%q err=%v", res.Flatten(), res.IsError)
}
if tasks := m.List(); len(tasks) != 0 {
t.Fatalf("foreground task should be forgotten, got %d", len(tasks))
}
}
// A long-running command that exceeds its timeout is moved to the background.
func TestBashAutoBackgroundOnTimeout(t *testing.T) {
m := newTestManager(t)
tc := &ToolContext{Tasks: m}
res := runTC(t, NewBash(), tc, map[string]any{
"command": "while true; do echo tick; sleep 0.1; done",
"timeout_ms": 300,
})
if res.IsError || !strings.Contains(res.Flatten(), "background") {
t.Fatalf("expected auto-background: %q (err=%v)", res.Flatten(), res.IsError)
}
tasks := m.List()
if len(tasks) != 1 || tasks[0].Status != TaskRunning {
t.Fatalf("expected 1 running task, got %+v", tasks)
}
// Stop it.
if r := runTC(t, NewTaskStop(), tc, map[string]any{"task_id": tasks[0].ID}); r.IsError {
t.Fatalf("TaskStop: %q", r.Flatten())
}
info := waitTerminal(t, m, tasks[0].ID)
if info.Status != TaskKilled {
t.Fatalf("expected killed, got %s", info.Status)
}
}
// sleep is on the auto-background denylist: a timed-out sleep is killed, not
// backgrounded, and surfaces a timeout error.
func TestBashSleepTimesOutNotBackgrounded(t *testing.T) {
m := newTestManager(t)
tc := &ToolContext{Tasks: m}
res := runTC(t, NewBash(), tc, map[string]any{"command": "sleep 5", "timeout_ms": 200})
if !res.IsError || !strings.Contains(res.Flatten(), "timed out") {
t.Fatalf("expected timeout error: %q (err=%v)", res.Flatten(), res.IsError)
}
if tasks := m.List(); len(tasks) != 0 {
t.Fatalf("timed-out sleep should be forgotten, got %d", len(tasks))
}
}
func TestTaskListAndStopAll(t *testing.T) {
m := newTestManager(t)
tc := &ToolContext{Tasks: m}
for i := 0; i < 2; i++ {
task, _ := m.Spawn(SpawnSpec{Command: "sleep 5"})
m.Background(task.ID)
}
list := runTC(t, NewTaskList(), tc, map[string]any{}).Flatten()
if strings.Count(list, "task_") != 2 {
t.Fatalf("TaskList=%q", list)
}
if r := runTC(t, NewTaskStop(), tc, map[string]any{}); !strings.Contains(r.Flatten(), "Stopped 2") {
t.Fatalf("TaskStop all=%q", r.Flatten())
}
}
// Monitor always backgrounds and reports an output file.
func TestMonitorBackgrounds(t *testing.T) {
m := newTestManager(t)
tc := &ToolContext{Tasks: m}
res := runTC(t, NewMonitor(), tc, map[string]any{"command": "sleep 5", "description": "watcher"})
if res.IsError || !strings.Contains(res.Flatten(), "monitor") {
t.Fatalf("Monitor=%q err=%v", res.Flatten(), res.IsError)
}
tasks := m.List()
if len(tasks) != 1 || tasks[0].Kind != KindMonitor || tasks[0].Status != TaskRunning {
t.Fatalf("monitor task=%+v", tasks)
}
}
// TaskOutput block=true waits for completion.
func TestTaskOutputBlock(t *testing.T) {
m := newTestManager(t)
tc := &ToolContext{Tasks: m}
task, _ := m.Spawn(SpawnSpec{Command: "sleep 0.3; echo done"})
m.Background(task.ID)
out := runTC(t, NewTaskOutput(), tc, map[string]any{"task_id": task.ID, "block": true, "timeout_ms": 5000}).Flatten()
if !strings.Contains(out, "done") || !strings.Contains(out, "completed") {
t.Fatalf("blocking TaskOutput=%q", out)
}
}
// Tools degrade gracefully when no manager is configured.
func TestToolsWithoutManager(t *testing.T) {
tc := &ToolContext{}
if r := runTC(t, NewTaskOutput(), tc, map[string]any{"task_id": "task_1"}); !strings.Contains(r.Flatten(), "not enabled") {
t.Fatalf("TaskOutput without manager=%q", r.Flatten())
}
if r := runTC(t, NewMonitor(), tc, map[string]any{"command": "echo x"}); !strings.Contains(r.Flatten(), "not enabled") {
t.Fatalf("Monitor without manager=%q", r.Flatten())
}
}
func TestTailFileOmitsEarlier(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "out")
var b strings.Builder
for i := 0; i < 5000; i++ {
b.WriteString("0123456789\n")
}
if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {
t.Fatal(err)
}
out, err := tailFile(path, 1000)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, "earlier output omitted") {
t.Fatalf("expected omission notice: %q", out[:80])
}
if len(out) > 1000+200 {
t.Fatalf("tail too large: %d", len(out))
}
}
func TestCleanupRemovesDir(t *testing.T) {
m, err := NewManager("cleanup-test")
if err != nil {
t.Fatal(err)
}
task, _ := m.Spawn(SpawnSpec{Command: "sleep 5"})
dir := filepath.Dir(m.dir)
m.Cleanup()
if _, err := os.Stat(dir); !os.IsNotExist(err) {
t.Fatalf("session dir not removed: %v", err)
}
// The spawned process is killed by Cleanup.
info, _ := m.Get(task.ID)
if info.Status == TaskRunning {
t.Fatalf("task still running after cleanup")
}
}
+25
View File
@@ -0,0 +1,25 @@
//go:build !windows
package tool
import (
"os"
"os/exec"
"syscall"
)
// setDetached puts the child in its own process group so it survives the
// per-turn context and can be killed as a whole tree.
func setDetached(cmd *exec.Cmd) {
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
}
cmd.SysProcAttr.Setpgid = true
}
// treeKill terminates the process group, falling back to the lone process.
func treeKill(p *os.Process) {
if err := syscall.Kill(-p.Pid, syscall.SIGKILL); err != nil {
_ = p.Kill()
}
}
+26
View File
@@ -0,0 +1,26 @@
//go:build windows
package tool
import (
"os"
"os/exec"
"strconv"
"syscall"
)
// createNewProcessGroup isolates the child from our console so it survives the
// per-turn context.
const createNewProcessGroup = 0x00000200 // CREATE_NEW_PROCESS_GROUP
func setDetached(cmd *exec.Cmd) {
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
}
cmd.SysProcAttr.CreationFlags |= createNewProcessGroup
}
// treeKill terminates the process and its descendants via taskkill.
func treeKill(p *os.Process) {
_ = exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(p.Pid)).Run()
}
+40
View File
@@ -0,0 +1,40 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"strings"
)
// NewTaskList builds the TaskList tool: enumerate this session's background tasks.
func NewTaskList() CoreTool {
return Build(Spec{
Name: "TaskList",
Description: "Lists the background tasks started in this session with their status, exit code, and command.",
Schema: map[string]any{"type": "object", "properties": map[string]any{}},
ReadOnly: always,
Concurrent: always,
Permissions: allowReadOnly,
Run: runTaskList,
})
}
func runTaskList(_ context.Context, _ json.RawMessage, tc *ToolContext) (Result, error) {
if tc == nil || tc.Tasks == nil {
return Errorf("Error: background tasks are not enabled"), nil
}
tasks := tc.Tasks.List()
if len(tasks) == 0 {
return Text("No background tasks."), nil
}
var b strings.Builder
for _, t := range tasks {
fmt.Fprintf(&b, "%s [%s] %s", t.ID, t.Kind, t.Status)
if t.Status == TaskCompleted || t.Status == TaskFailed {
fmt.Fprintf(&b, " exit=%d", t.ExitCode)
}
fmt.Fprintf(&b, " %s\n", short(t.Command))
}
return Text(b.String()), nil
}
+72
View File
@@ -0,0 +1,72 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"time"
)
// NewTaskOutput builds the TaskOutput tool: read the captured output of a
// background task (from Bash run_in_background or Monitor), optionally blocking
// until it finishes.
func NewTaskOutput() CoreTool {
return Build(Spec{
Name: "TaskOutput",
Description: "Reads the output of a background task started by Bash (run_in_background) or Monitor. You can also Read the task's output-file path directly. Set block=true to wait for the task to finish first.",
Prompt: "Provide the task_id. With block=true the call waits until the task reaches a terminal state (up to timeout_ms) before returning its output.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"task_id": map[string]any{"type": "string", "description": "The task id (e.g. task_1)."},
"max_bytes": map[string]any{"type": "integer", "description": "Max bytes of output to return from the tail (default 30000)."},
"block": map[string]any{"type": "boolean", "description": "Wait until the task finishes before returning (default false)."},
"timeout_ms": map[string]any{"type": "integer", "description": "Max wait when block=true (default 30000)."},
},
"required": []any{"task_id"},
},
ReadOnly: always,
Concurrent: always,
Permissions: allowReadOnly,
Run: runTaskOutput,
})
}
func runTaskOutput(ctx context.Context, input json.RawMessage, tc *ToolContext) (Result, error) {
var in struct {
TaskID string `json:"task_id"`
MaxBytes int `json:"max_bytes"`
Block bool `json:"block"`
TimeoutMS int `json:"timeout_ms"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
if tc == nil || tc.Tasks == nil {
return Errorf("Error: background tasks are not enabled"), nil
}
if in.TaskID == "" {
return Errorf("Error: task_id is required"), nil
}
info, ok := tc.Tasks.Get(in.TaskID)
if !ok {
return Errorf(fmt.Sprintf("Error: unknown task %q", in.TaskID)), nil
}
if in.Block && !info.Status.Terminal() {
timeout := 30 * time.Second
if in.TimeoutMS > 0 {
timeout = time.Duration(in.TimeoutMS) * time.Millisecond
}
info, _ = tc.Tasks.Wait(ctx, in.TaskID, timeout)
}
out, err := tc.Tasks.Output(in.TaskID, in.MaxBytes)
if err != nil {
return Errorf("Error: " + err.Error()), nil
}
header := fmt.Sprintf("[task %s | %s", info.ID, info.Status)
if info.Status == TaskCompleted || info.Status == TaskFailed {
header += fmt.Sprintf(" | exit %d", info.ExitCode)
}
header += "]\n"
return Text(Capture(tc, header+out)), nil
}
+43
View File
@@ -0,0 +1,43 @@
package tool
import (
"context"
"encoding/json"
"fmt"
)
// NewTaskStop builds the TaskStop tool: kill a running background task (or all).
func NewTaskStop() CoreTool {
return Build(Spec{
Name: "TaskStop",
Description: "Stops a running background task, killing its process tree. Pass a task_id, or omit it to stop all running tasks.",
Prompt: "Provide task_id to stop one task, or leave it empty to stop all running tasks.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"task_id": map[string]any{"type": "string", "description": "The id of the task to stop. Empty stops all running tasks."},
},
},
// Stopping a process the agent itself launched is a safe control op.
Permissions: allowReadOnly,
Run: runTaskStop,
})
}
func runTaskStop(_ context.Context, input json.RawMessage, tc *ToolContext) (Result, error) {
var in struct {
TaskID string `json:"task_id"`
}
_ = json.Unmarshal(input, &in)
if tc == nil || tc.Tasks == nil {
return Errorf("Error: background tasks are not enabled"), nil
}
if in.TaskID == "" {
n := tc.Tasks.KillAll()
return Text(fmt.Sprintf("Stopped %d running task(s).", n)), nil
}
if tc.Tasks.Kill(in.TaskID) {
return Text(fmt.Sprintf("Stopped task %s.", in.TaskID)), nil
}
return Errorf(fmt.Sprintf("Error: unknown task %q", in.TaskID)), nil
}
+109
View File
@@ -0,0 +1,109 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"strings"
"sync"
"github.com/Autumn-27/norma/permission"
)
// TodoStatus is the state of a todo item.
type TodoStatus string
const (
TodoPending TodoStatus = "pending"
TodoInProgress TodoStatus = "in_progress"
TodoCompleted TodoStatus = "completed"
)
// Todo is one task in the agent's working plan.
type Todo struct {
Content string `json:"content"`
Status TodoStatus `json:"status"`
}
// TodoStore holds the current todo list across tool calls. It is safe for
// concurrent reads; the host can inspect progress via List.
type TodoStore struct {
mu sync.Mutex
items []Todo
}
// NewTodoStore returns an empty store.
func NewTodoStore() *TodoStore { return &TodoStore{} }
// List returns a snapshot of the current todos.
func (s *TodoStore) List() []Todo {
s.mu.Lock()
defer s.mu.Unlock()
return append([]Todo(nil), s.items...)
}
func (s *TodoStore) set(items []Todo) {
s.mu.Lock()
s.items = items
s.mu.Unlock()
}
// Tool returns the TodoWrite tool bound to this store. The agent uses it to
// plan and track multi-step work; each call replaces the whole list.
func (s *TodoStore) Tool() CoreTool {
return Build(Spec{
Name: "TodoWrite",
Description: "Records and updates a structured todo list for the current task. Use it to plan multi-step work and to mark progress — replace the whole list each call, marking exactly one item in_progress while working.",
Prompt: "status is one of: pending, in_progress, completed. Keep the list current: mark a task completed as soon as it's done; don't batch completions.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"todos": map[string]any{
"type": "array",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"content": map[string]any{"type": "string"},
"status": map[string]any{"type": "string", "enum": []any{"pending", "in_progress", "completed"}},
},
"required": []any{"content", "status"},
},
},
},
"required": []any{"todos"},
},
ReadOnly: func(json.RawMessage) bool { return false },
Concurrent: func(json.RawMessage) bool { return false },
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Allowed()
},
Run: func(_ context.Context, input json.RawMessage, _ *ToolContext) (Result, error) {
var in struct {
Todos []Todo `json:"todos"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
s.set(in.Todos)
// Ack only — the list itself is visible in the model's own tool_use
// input and is re-surfaced on demand via the todo system-reminder
// (harness). Mirrors claude-code's TodoWrite result.
return Text(todoAck), nil
},
})
}
const todoAck = "Todos have been modified successfully. Keep the todo list current and continue with the tasks."
// RenderTodoReminder renders the todo list for the system-reminder body, one
// numbered item per line ("N. [status] content"). Returns "" for an empty list.
func RenderTodoReminder(todos []Todo) string {
if len(todos) == 0 {
return ""
}
var b strings.Builder
for i, t := range todos {
fmt.Fprintf(&b, "%d. [%s] %s\n", i+1, t.Status, t.Content)
}
return strings.TrimRight(b.String(), "\n")
}
+172
View File
@@ -0,0 +1,172 @@
// Package tool defines the CoreTool contract and the built-in file/shell tools
// that give the agent its hands. Every tool is self-describing: a name and
// description for the model, a JSON-Schema input, behavioral flags used by the
// scheduler (read-only / concurrency-safe), a permission self-check, and a Call
// method. New tools are built through Build, which applies fail-closed defaults.
package tool
import (
"context"
"encoding/json"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
)
// ProgressInfo is an incremental progress update emitted during a long tool run.
type ProgressInfo struct {
Message string
}
// ToolContext carries per-call execution state into a tool.
type ToolContext struct {
WorkingDir string
AgentID string
// ToolUseID is the id of the tool_use block this call answers. Tools that
// need to refer back to their own call in the conversation — to anchor
// something to it, or to recognise it later — read it here.
ToolUseID string
MaxOutputChars int
// OutputDir, when set, makes oversized tool output spill to a file there
// (full content preserved) instead of being discarded by truncation; the
// tool returns a head + a pointer to the file. Empty disables spilling.
OutputDir string
// Emit reports progress; may be nil. Safe to call from the tool goroutine.
Emit func(ProgressInfo)
// Tasks is the background-task manager for this session; may be nil (background
// execution disabled). Tools use it to spawn, read, and stop background work.
Tasks *Manager
// Env holds extra "KEY=VALUE" entries injected into the environment of Bash
// subprocesses (both foreground and background). Applied on top of the parent
// process environment, so these override inherited values. Empty = inherit
// unchanged. Used e.g. to route child-command HTTP through a proxy + trust a
// CA, without affecting the agent's own process.
Env []string
}
func (tc *ToolContext) progress(msg string) {
if tc != nil && tc.Emit != nil {
tc.Emit(ProgressInfo{Message: msg})
}
}
// Result is the outcome of a tool call. Content is the tool_result payload fed
// back to the model.
type Result struct {
Content []llm.ContentBlock
IsError bool
// Extra holds additional messages the tool injects into the conversation
// right after its tool_result (e.g. the Skill tool emits the invoked skill's
// instructions as an independent user message rather than burying them in the
// tool_result). Appended in order; nil for ordinary tools.
Extra []llm.Message
}
// Text builds a successful text result.
func Text(s string) Result { return Result{Content: []llm.ContentBlock{llm.TextBlock(s)}} }
// Errorf builds an error result.
func Errorf(s string) Result {
return Result{Content: []llm.ContentBlock{llm.TextBlock(s)}, IsError: true}
}
// Flatten concatenates the text of a result's content blocks.
func (r Result) Flatten() string {
var s string
for _, b := range r.Content {
if b.Type == llm.BlockText {
s += b.Text
}
}
return s
}
// CoreTool is a capability the agent can invoke (FR-04.1).
type CoreTool interface {
Name() string
Description() string
Prompt() string
InputSchema() map[string]any
IsReadOnly(input json.RawMessage) bool
IsConcurrencySafe(input json.RawMessage) bool
CheckPermissions(ctx context.Context, input json.RawMessage, pc permission.Context) permission.Decision
Call(ctx context.Context, input json.RawMessage, tc *ToolContext) (Result, error)
}
// Spec declares a tool. Build fills unset behavioral fields with fail-closed
// defaults (FR-04.2): not read-only, not concurrency-safe, requires approval.
type Spec struct {
Name string
Description string
Prompt string
Schema map[string]any
ReadOnly func(json.RawMessage) bool
Concurrent func(json.RawMessage) bool
Permissions func(ctx context.Context, input json.RawMessage, pc permission.Context) permission.Decision
Run func(ctx context.Context, input json.RawMessage, tc *ToolContext) (Result, error)
// RawInput hands Run whatever the model produced, skipping the schema check
// the harness otherwise applies first.
//
// Schema stays required and is still advertised to the model — the two are
// separate jobs. Schema tells the model what to send; validation decides what
// gets through. A tool that repairs malformed arguments itself needs the
// first and is defeated by the second: a truncated or fence-wrapped call is
// not valid JSON, so it would be rejected before Run ever saw it, and the
// repair could never run.
//
// Only set this on a tool that treats its input as untrusted bytes and
// answers every shape with a Result rather than an error.
RawInput bool
}
// Build constructs a CoreTool from a Spec, applying fail-closed defaults.
func Build(s Spec) CoreTool { return &builtTool{spec: s} }
type builtTool struct{ spec Spec }
func (t *builtTool) Name() string { return t.spec.Name }
func (t *builtTool) Description() string { return t.spec.Description }
func (t *builtTool) Prompt() string { return t.spec.Prompt }
func (t *builtTool) InputSchema() map[string]any { return t.spec.Schema }
// AcceptsRawInput reports whether this tool parses its own arguments.
//
// Deliberately not on CoreTool: that interface is public, and adding a method
// would break every host implementing it. The harness asks for it with an
// optional type assertion, the same way it discovers ContextView.
func (t *builtTool) AcceptsRawInput() bool { return t.spec.RawInput }
func (t *builtTool) IsReadOnly(in json.RawMessage) bool {
if t.spec.ReadOnly == nil {
return false
}
return t.spec.ReadOnly(in)
}
func (t *builtTool) IsConcurrencySafe(in json.RawMessage) bool {
if t.spec.Concurrent == nil {
return false
}
return t.spec.Concurrent(in)
}
func (t *builtTool) CheckPermissions(ctx context.Context, in json.RawMessage, pc permission.Context) permission.Decision {
if t.spec.Permissions == nil {
return permission.AskUser("approve " + t.spec.Name + "?")
}
return t.spec.Permissions(ctx, in, pc)
}
func (t *builtTool) Call(ctx context.Context, in json.RawMessage, tc *ToolContext) (Result, error) {
return t.spec.Run(ctx, in, tc)
}
// readOnlyTrue / concurrentTrue are shared helpers for read tools.
func always(json.RawMessage) bool { return true }
// allowReadOnly is a permission self-check that auto-allows (used by read tools;
// the pipeline also auto-allows read-only, this makes intent explicit).
func allowReadOnly(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Allowed()
}
+159
View File
@@ -0,0 +1,159 @@
package tool
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Autumn-27/norma/permission"
)
func run(t *testing.T, tl CoreTool, dir string, in any) Result {
t.Helper()
raw, _ := json.Marshal(in)
if err := ValidateInput(tl.InputSchema(), raw); err != nil {
t.Fatalf("%s schema: %v", tl.Name(), err)
}
res, err := tl.Call(context.Background(), raw, &ToolContext{WorkingDir: dir})
if err != nil {
t.Fatalf("%s: %v", tl.Name(), err)
}
return res
}
func TestFileTools(t *testing.T) {
dir := t.TempDir()
run(t, NewWrite(), dir, map[string]any{"file_path": "a.txt", "content": "hello\nworld\n"})
if b, _ := os.ReadFile(filepath.Join(dir, "a.txt")); string(b) != "hello\nworld\n" {
t.Fatalf("write: %q", b)
}
res := run(t, NewRead(), dir, map[string]any{"file_path": "a.txt"})
if !strings.Contains(res.Flatten(), "1\thello") {
t.Fatalf("read: %q", res.Flatten())
}
run(t, NewEdit(), dir, map[string]any{"file_path": "a.txt", "old_string": "world", "new_string": "gophers"})
if b, _ := os.ReadFile(filepath.Join(dir, "a.txt")); string(b) != "hello\ngophers\n" {
t.Fatalf("edit: %q", b)
}
run(t, NewWrite(), dir, map[string]any{"file_path": "b.txt", "content": "x x"})
if r := run(t, NewEdit(), dir, map[string]any{"file_path": "b.txt", "old_string": "x", "new_string": "y"}); !r.IsError {
t.Fatalf("expected non-unique edit error")
}
}
func TestSearchTools(t *testing.T) {
t.Setenv("NORMA_DISABLE_RIPGREP", "1")
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "one.go"), []byte("package main\nfunc Foo(){}\n"), 0o644)
os.WriteFile(filepath.Join(dir, "two.txt"), []byte("Foo lives\n"), 0o644)
res := run(t, NewGrep(), dir, map[string]any{"pattern": "Foo", "glob": "*.go", "output_mode": "files_with_matches"})
if !strings.Contains(res.Flatten(), "one.go") || strings.Contains(res.Flatten(), "two.txt") {
t.Fatalf("grep glob: %q", res.Flatten())
}
res = run(t, NewGlob(), dir, map[string]any{"pattern": "**/*.go"})
if !strings.Contains(res.Flatten(), "one.go") {
t.Fatalf("glob: %q", res.Flatten())
}
}
func TestGrepContextLines(t *testing.T) {
t.Setenv("NORMA_DISABLE_RIPGREP", "1")
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "f.txt"), []byte("a\nb\nMATCH\nd\ne\n"), 0o644)
// -C 1 should include the line before and after the match, with the match
// line using ':' and context lines using '-'.
res := run(t, NewGrep(), dir, map[string]any{"pattern": "MATCH", "output_mode": "content", "-C": 1})
out := res.Flatten()
for _, want := range []string{"f.txt-2-b", "f.txt:3:MATCH", "f.txt-4-d"} {
if !strings.Contains(out, want) {
t.Fatalf("context output missing %q:\n%s", want, out)
}
}
if strings.Contains(out, "f.txt-1-a") {
t.Fatalf("-C 1 should not reach line 1:\n%s", out)
}
}
func TestGrepTypeFilter(t *testing.T) {
t.Setenv("NORMA_DISABLE_RIPGREP", "1")
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "a.go"), []byte("needle here\n"), 0o644)
os.WriteFile(filepath.Join(dir, "b.py"), []byte("needle here\n"), 0o644)
os.WriteFile(filepath.Join(dir, "c.txt"), []byte("needle here\n"), 0o644)
// type: go → only the .go file.
out := run(t, NewGrep(), dir, map[string]any{"pattern": "needle", "type": "go"}).Flatten()
if !strings.Contains(out, "a.go") || strings.Contains(out, "b.py") || strings.Contains(out, "c.txt") {
t.Fatalf("type=go filter: %q", out)
}
// Unknown type falls back to *.<type>.
out = run(t, NewGrep(), dir, map[string]any{"pattern": "needle", "type": "txt"}).Flatten()
if !strings.Contains(out, "c.txt") || strings.Contains(out, "a.go") {
t.Fatalf("type=txt fallback: %q", out)
}
}
func TestGrepMultiline(t *testing.T) {
t.Setenv("NORMA_DISABLE_RIPGREP", "1")
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "f.txt"), []byte("start\nalpha\nbeta\nend\n"), 0o644)
// Without multiline, a cross-line pattern doesn't match.
out := run(t, NewGrep(), dir, map[string]any{"pattern": "alpha.*beta", "output_mode": "files_with_matches"}).Flatten()
if strings.Contains(out, "f.txt") {
t.Fatalf("cross-line pattern should not match without multiline: %q", out)
}
// With multiline, . spans the newline.
out = run(t, NewGrep(), dir, map[string]any{"pattern": "alpha.*beta", "multiline": true, "output_mode": "files_with_matches"}).Flatten()
if !strings.Contains(out, "f.txt") {
t.Fatalf("multiline should match across lines: %q", out)
}
}
func TestGrepHeadLimitAndOffset(t *testing.T) {
t.Setenv("NORMA_DISABLE_RIPGREP", "1")
dir := t.TempDir()
for _, n := range []string{"a", "b", "c", "d", "e"} {
os.WriteFile(filepath.Join(dir, n+".txt"), []byte("hit\n"), 0o644)
}
// head_limit caps the number of files and notes the remainder.
out := run(t, NewGrep(), dir, map[string]any{"pattern": "hit", "head_limit": 2}).Flatten()
if strings.Count(out, ".txt") != 2 || !strings.Contains(out, "more result") {
t.Fatalf("head_limit=2 should keep 2 and note the rest: %q", out)
}
// offset pages past the first results.
out = run(t, NewGrep(), dir, map[string]any{"pattern": "hit", "head_limit": 2, "offset": 2}).Flatten()
if !strings.Contains(out, "c.txt") || strings.Contains(out, "a.txt") {
t.Fatalf("offset=2 should skip a/b and show c: %q", out)
}
}
func TestBashAndSafetyFloor(t *testing.T) {
dir := t.TempDir()
res := run(t, NewBash(), dir, map[string]any{"command": "echo hi"})
if !strings.Contains(res.Flatten(), "hi") {
t.Fatalf("bash: %q", res.Flatten())
}
// Safety floor: rm -rf / must be denied by CheckPermissions.
bash := NewBash()
raw, _ := json.Marshal(map[string]any{"command": "rm -rf /"})
if d := bash.CheckPermissions(context.Background(), raw, permission.Context{}); d.Behavior != permission.Deny {
t.Fatalf("expected deny for rm -rf /, got %v", d.Behavior)
}
}
func TestSchemaValidation(t *testing.T) {
// Missing required field.
raw, _ := json.Marshal(map[string]any{"offset": 1})
if err := ValidateInput(NewRead().InputSchema(), raw); err == nil {
t.Fatal("expected missing file_path error")
}
// Wrong type.
raw, _ = json.Marshal(map[string]any{"file_path": 123})
if err := ValidateInput(NewRead().InputSchema(), raw); err == nil {
t.Fatal("expected type error")
}
}
+491
View File
@@ -0,0 +1,491 @@
package tool
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
"github.com/Autumn-27/norma/permission"
"golang.org/x/net/html"
)
// WebFetchConfig tunes the network behavior of a WebFetch tool.
type WebFetchConfig struct {
// Proxy, when set, routes requests through this http(s) proxy URL. Empty = direct.
Proxy string
// CACert, when set, is a path to a PEM CA certificate added to the system
// trust pool. This lets WebFetch *verify* HTTPS fetched through a MITM/recording
// proxy that re-signs certificates with its own CA — the proper alternative to
// InsecureTLS, keeping verification on for every other connection. Preferred
// over InsecureTLS; ignored when InsecureTLS is set.
CACert string
// InsecureTLS skips TLS certificate verification entirely (equivalent to
// curl -k). A blunt fallback when no CA cert is available; prefer CACert.
InsecureTLS bool
}
// NewWebFetch builds the WebFetch tool: fetches a URL over HTTP(S) and returns
// its content as Markdown (HTML is parsed and rendered; non-HTML is returned
// as-is). With extract=true it also appends a RECON section that preserves the
// signal HTML→Markdown normally discards — comments, <script> sources, inline
// endpoints, forms/inputs (including hidden) and meta tags — useful for security
// reconnaissance. cfg optionally routes requests through a proxy and/or skips
// TLS verification (see WebFetchConfig). It is network-facing, so it is not part
// of DefaultTools and requires permission to run.
func NewWebFetch(cfg WebFetchConfig) CoreTool {
return Build(Spec{
Name: "WebFetch",
Description: "Fetches an HTTP(S) HTML page, documentation page, or API response and returns it as Markdown. Do not use this tool for static assets, including JavaScript, CSS, source maps, images, fonts, audio, or video—even if their URLs are found in a fetched page or explicitly requested. Fetch the owning page instead. Set `extract=true` to list comments, scripts, stylesheets, endpoints, forms, links, and meta tags. Listed asset URLs are for inspection only and must not be fetched. Large responses may be truncated. This makes an external network request.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"url": map[string]any{"type": "string", "description": "The absolute http(s) URL to fetch. JS/CSS/static-asset suffix URLs are not allowed."},
"extract": map[string]any{"type": "boolean", "description": "When true, append a RECON section preserving HTML comments, <script src>, inline-script endpoints, forms/inputs (including hidden), links and meta tags. Default false."},
},
"required": []any{"url"},
},
// Network access is open-world: require approval rather than auto-allow.
Permissions: func(_ context.Context, input json.RawMessage, _ permission.Context) permission.Decision {
var in struct {
URL string `json:"url"`
}
_ = json.Unmarshal(input, &in)
return permission.AskUser("fetch external URL: " + in.URL)
},
Run: webFetchRunner(cfg),
})
}
const maxFetchBytes = 2 << 20 // 2 MiB
// newFetchClient returns an HTTP client honoring the proxy / TLS config.
func newFetchClient(cfg WebFetchConfig) *http.Client {
if cfg.Proxy == "" && !cfg.InsecureTLS && cfg.CACert == "" {
return &http.Client{}
}
tr := &http.Transport{}
if cfg.Proxy != "" {
if pu, err := url.Parse(cfg.Proxy); err == nil {
tr.Proxy = http.ProxyURL(pu)
}
}
switch {
case cfg.InsecureTLS:
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
case cfg.CACert != "":
// Trust the proxy's CA in addition to the system roots, so certs it
// re-signs verify while every other connection stays fully checked.
if pem, err := os.ReadFile(cfg.CACert); err == nil {
pool, _ := x509.SystemCertPool()
if pool == nil {
pool = x509.NewCertPool()
}
if pool.AppendCertsFromPEM(pem) {
tr.TLSClientConfig = &tls.Config{RootCAs: pool}
}
}
}
return &http.Client{Transport: tr}
}
// proxyLikelyErr reports whether a fetch error is the kind a recording/MITM proxy
// introduces — a closed tunnel (EOF / connection reset), a failed CONNECT, or a
// TLS/HTTP2 mismatch — so a direct (no-proxy) retry may succeed. Name-resolution
// failures and caller cancellation/timeout are target- or caller-side problems a
// direct retry won't fix, so those return false (no retry).
func proxyLikelyErr(err error) bool {
if err == nil {
return false
}
s := strings.ToLower(err.Error())
for _, n := range []string{"no such host", "context canceled", "context deadline", "timeout"} {
if strings.Contains(s, n) {
return false
}
}
for _, p := range []string{
"eof", "connection reset", "connection refused", "proxyconnect",
"broken pipe", "forcibly closed", "malformed", "http2", "http/2",
"tls:", "protocol error",
} {
if strings.Contains(s, p) {
return true
}
}
return false
}
// staticAssetExts are file extensions WebFetch refuses: linked resources (scripts,
// styles, source maps, images, fonts, media, wasm) that are not page content.
var staticAssetExts = map[string]bool{
".js": true, ".mjs": true, ".cjs": true, ".css": true, ".map": true,
".png": true, ".jpg": true, ".jpeg": true, ".gif": true, ".svg": true,
".webp": true, ".avif": true, ".ico": true, ".bmp": true,
".woff": true, ".woff2": true, ".ttf": true, ".otf": true, ".eot": true,
".wasm": true, ".mp4": true, ".webm": true, ".mp3": true, ".wav": true, ".ogg": true,
}
// staticAssetExt returns the offending extension (with dot) if rawURL points at a
// static asset, or "" otherwise. The query string and fragment are ignored, so
// "/app.js?v=3" is still caught.
func staticAssetExt(rawURL string) string {
path := rawURL
if u, err := url.Parse(rawURL); err == nil {
path = u.Path
}
if i := strings.LastIndexByte(path, '/'); i >= 0 {
path = path[i+1:] // last segment only
}
dot := strings.LastIndexByte(path, '.')
if dot < 0 {
return ""
}
if ext := strings.ToLower(path[dot:]); staticAssetExts[ext] {
return ext
}
return ""
}
func webFetchRunner(cfg WebFetchConfig) func(context.Context, json.RawMessage, *ToolContext) (Result, error) {
client := newFetchClient(cfg)
// direct is the no-proxy fallback used when a proxied fetch fails for a
// proxy-caused reason (closed tunnel / failed CONNECT / TLS or HTTP2 mismatch):
// it bypasses the configured proxy so a recording/MITM hiccup doesn't fail an
// otherwise-reachable URL. nil when no proxy is configured (nothing to bypass).
var direct *http.Client
if cfg.Proxy != "" {
direct = newFetchClient(WebFetchConfig{InsecureTLS: cfg.InsecureTLS})
}
return func(ctx context.Context, input json.RawMessage, _ *ToolContext) (Result, error) {
var in struct {
URL string `json:"url"`
Extract bool `json:"extract"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
if !strings.HasPrefix(in.URL, "http://") && !strings.HasPrefix(in.URL, "https://") {
return Errorf("Error: url must start with http:// or https://"), nil
}
if ext := staticAssetExt(in.URL); ext != "" {
return Errorf("Error: WebFetch does not fetch static assets (" + ext + " file). It reads HTML pages, documentation, and API responses — not linked resources like scripts, styles, images, or fonts. Fetch the page that references this asset instead."), nil
}
cctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(cctx, http.MethodGet, in.URL, nil)
if err != nil {
return Errorf("Error: " + err.Error()), nil
}
req.Header.Set("user-agent", "norma/0.4")
resp, err := client.Do(req)
// One direct retry when the proxied attempt failed for a proxy-caused reason.
// A non-proxy error (bad host, caller timeout/cancel) is returned as-is — a
// direct retry wouldn't fix it. The direct response is NOT captured by the proxy.
if err != nil && direct != nil && proxyLikelyErr(err) {
if r2, e2 := http.NewRequestWithContext(cctx, http.MethodGet, in.URL, nil); e2 == nil {
r2.Header.Set("user-agent", "norma/0.4")
if resp2, err2 := direct.Do(r2); err2 == nil {
resp, err = resp2, nil
} else {
err = err2 // surface the direct failure (more representative of the target)
}
}
}
if err != nil {
return Errorf("Error fetching URL: " + err.Error()), nil
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxFetchBytes))
header := fmt.Sprintf("[%d %s] %s\n", resp.StatusCode, http.StatusText(resp.StatusCode), in.URL)
// Cheap fingerprint signal that HTML→Markdown would otherwise hide.
if sv := resp.Header.Get("Server"); sv != "" {
header += "Server: " + sv + "\n"
}
if xp := resp.Header.Get("X-Powered-By"); xp != "" {
header += "X-Powered-By: " + xp + "\n"
}
var out string
if strings.Contains(strings.ToLower(resp.Header.Get("content-type")), "html") {
doc, perr := html.Parse(strings.NewReader(string(body)))
if perr != nil { // html.Parse is lenient; this is effectively unreachable
out = string(body)
} else {
out = htmlToMarkdown(doc)
if in.Extract {
if recon := extractRecon(doc); recon != "" {
out += "\n\n" + recon
}
}
}
} else {
out = string(body)
}
return Text(truncate(header+strings.TrimSpace(out), 50000)), nil
}
}
var (
reWS = regexp.MustCompile(`[ \t]+`)
reLineTrim = regexp.MustCompile(` *\n *`) // strip spaces hugging a newline
reBlankLines = regexp.MustCompile(`\n{2,}`) // collapse blank lines → one newline
// reEndpoint matches quoted absolute URLs and root-relative paths in inline JS.
reEndpoint = regexp.MustCompile("[\"'`](https?://[^\"'`\\s]+|/[A-Za-z0-9._~$&'()*+,;=:@%/?#\\[\\]-]{2,})[\"'`]")
)
// skipMarkdown are elements whose subtree carries no readable prose.
var skipMarkdown = map[string]bool{"script": true, "style": true, "noscript": true, "svg": true, "template": true}
// htmlToMarkdown renders the visible content of a parsed document as Markdown.
// Text nodes are already entity-decoded by the parser, so no unescaping is needed.
func htmlToMarkdown(doc *html.Node) string {
var b strings.Builder
renderNode(&b, doc)
s := reWS.ReplaceAllString(b.String(), " ")
s = reLineTrim.ReplaceAllString(s, "\n") // drop indentation / trailing spaces per line
s = reBlankLines.ReplaceAllString(s, "\n") // no blank lines — compact, token-lean output
return strings.TrimSpace(s)
}
func renderNode(b *strings.Builder, n *html.Node) {
switch n.Type {
case html.TextNode:
b.WriteString(strings.ReplaceAll(n.Data, "\n", " "))
return
case html.ElementNode:
if skipMarkdown[n.Data] {
return
}
default:
if n.Type != html.DocumentNode {
return
}
}
tag := ""
if n.Type == html.ElementNode {
tag = n.Data
}
switch tag {
case "h1", "h2", "h3", "h4", "h5", "h6":
b.WriteString("\n\n" + strings.Repeat("#", int(tag[1]-'0')) + " ")
renderChildren(b, n)
b.WriteString("\n\n")
case "title":
b.WriteString("\n\n# ")
renderChildren(b, n)
b.WriteString("\n\n")
case "p", "div", "section", "article", "header", "footer", "main", "ul", "ol", "table", "tr", "blockquote":
b.WriteString("\n\n")
renderChildren(b, n)
b.WriteString("\n\n")
case "br":
b.WriteString("\n")
case "hr":
b.WriteString("\n\n---\n\n")
case "li":
b.WriteString("\n- ")
renderChildren(b, n)
case "a":
var inner strings.Builder
renderChildren(&inner, n)
text := strings.TrimSpace(inner.String())
if href := attr(n, "href"); href != "" && text != "" {
fmt.Fprintf(b, "[%s](%s)", text, href)
} else {
b.WriteString(text)
}
case "img":
if src := attr(n, "src"); src != "" {
fmt.Fprintf(b, "![%s](%s)", attr(n, "alt"), src)
}
case "strong", "b":
b.WriteString("**")
renderChildren(b, n)
b.WriteString("**")
case "em", "i":
b.WriteString("*")
renderChildren(b, n)
b.WriteString("*")
case "code":
b.WriteString("`")
renderChildren(b, n)
b.WriteString("`")
case "pre":
var inner strings.Builder
textOnly(&inner, n)
b.WriteString("\n\n```\n" + strings.TrimSpace(inner.String()) + "\n```\n\n")
default:
renderChildren(b, n)
}
}
func renderChildren(b *strings.Builder, n *html.Node) {
for c := n.FirstChild; c != nil; c = c.NextSibling {
renderNode(b, c)
}
}
// extractRecon walks the document for security-relevant signal that Markdown
// rendering drops: comments, script sources, inline endpoints, forms, meta, links.
func extractRecon(doc *html.Node) string {
var comments, scriptSrcs, inlineEndpoints, forms, metas, links []string
seenLink := map[string]bool{}
var walk func(n *html.Node)
walk = func(n *html.Node) {
switch n.Type {
case html.CommentNode:
if c := oneLine(n.Data, 300); c != "" {
comments = append(comments, c)
}
case html.ElementNode:
switch n.Data {
case "script":
if src := attr(n, "src"); src != "" {
scriptSrcs = append(scriptSrcs, src)
} else {
var body strings.Builder
textOnly(&body, n)
for _, m := range reEndpoint.FindAllStringSubmatch(body.String(), 40) {
inlineEndpoints = append(inlineEndpoints, m[1])
}
}
case "form":
forms = append(forms, describeForm(n))
case "meta":
name := attr(n, "name")
if name == "" {
name = attr(n, "property")
}
if content := attr(n, "content"); name != "" && content != "" {
metas = append(metas, name+"="+oneLine(content, 120))
}
case "a", "link":
if h := attr(n, "href"); h != "" && !seenLink[h] {
seenLink[h] = true
links = append(links, h)
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(doc)
var b strings.Builder
b.WriteString("=== RECON ===")
reconSection(&b, "COMMENTS", comments)
reconSection(&b, "SCRIPTS (src)", dedup(scriptSrcs))
reconSection(&b, "INLINE ENDPOINTS", dedup(inlineEndpoints))
reconSection(&b, "FORMS", forms)
reconSection(&b, "META", metas)
reconSection(&b, "LINKS", capSlice(links, 100))
if b.Len() == len("=== RECON ===") {
return "" // nothing worth reporting
}
return b.String()
}
// describeForm summarizes a <form> as "METHOD action → name(type[=value]) …".
// Hidden inputs keep their value (CSRF tokens, parameter defaults matter in recon).
func describeForm(form *html.Node) string {
method := strings.ToUpper(attr(form, "method"))
if method == "" {
method = "GET"
}
var inputs []string
var walk func(n *html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode {
switch n.Data {
case "input", "textarea", "select":
typ := attr(n, "type")
if typ == "" {
typ = n.Data
}
desc := attr(n, "name") + "(" + typ
if typ == "hidden" {
if v := attr(n, "value"); v != "" {
desc += "=" + oneLine(v, 60)
}
}
inputs = append(inputs, desc+")")
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(form)
return fmt.Sprintf("%s %s → %s", method, attr(form, "action"), strings.Join(inputs, " "))
}
// --- small helpers ---
func attr(n *html.Node, key string) string {
for _, a := range n.Attr {
if a.Key == key {
return a.Val
}
}
return ""
}
func textOnly(b *strings.Builder, n *html.Node) {
if n.Type == html.TextNode {
b.WriteString(n.Data)
return
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
textOnly(b, c)
}
}
func oneLine(s string, max int) string {
s = strings.Join(strings.Fields(s), " ")
if len(s) > max {
return s[:max] + "…"
}
return s
}
func reconSection(b *strings.Builder, title string, items []string) {
if len(items) == 0 {
return
}
b.WriteString("\n\n## " + title + "\n")
for _, it := range items {
b.WriteString("- " + it + "\n")
}
}
func dedup(in []string) []string {
seen := map[string]bool{}
out := in[:0:0]
for _, s := range in {
if s == "" || seen[s] {
continue
}
seen[s] = true
out = append(out, s)
}
return out
}
func capSlice(in []string, n int) []string {
if len(in) <= n {
return in
}
return append(in[:n:n], fmt.Sprintf("… (%d more)", len(in)-n))
}
+641
View File
@@ -0,0 +1,641 @@
package tool
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/Autumn-27/norma/permission"
"golang.org/x/net/html"
)
// SearchResult is one web-search hit, normalized across backends.
type SearchResult struct {
Title string `json:"title"`
URL string `json:"url"`
Description string `json:"description"`
Position int `json:"position"`
}
// searchProvider is a pluggable web-search backend. Search-only by design —
// content extraction is handled elsewhere (WebFetch). Implementations must not
// panic; network/parse failures come back as an error.
type searchProvider interface {
Name() string
Search(ctx context.Context, query string, limit int) ([]SearchResult, error)
}
// WebSearchConfig selects and configures the active search backend.
type WebSearchConfig struct {
// Backend chooses the provider: "ddgs" (DuckDuckGo scrape, no key),
// "brave-free" (Brave Search API, needs BraveAPIKey), "tavily" (Tavily
// Search API, needs TavilyAPIKey), or "deepseek" (DeepSeek's server-side
// web search, needs DeepSeek*). Empty defaults to "ddgs".
Backend string
// BraveAPIKey authenticates the "brave-free" backend. Required (and only
// used) when Backend == "brave-free".
BraveAPIKey string
// TavilyAPIKey authenticates the "tavily" backend. Required (and only
// used) when Backend == "tavily".
TavilyAPIKey string
// DeepSeekBaseURL / DeepSeekAPIKey / DeepSeekModel configure the "deepseek"
// backend. That backend does NOT call a search API — DeepSeek has none.
// Search there only exists inside its Anthropic-compatible messages endpoint
// as the web_search_20250305 server tool, so this provider spends one model
// call per search. BaseURL must be the Anthropic-format root (the provider
// appends /v1/messages); the OpenAI-format endpoint rejects server tools
// outright ("unknown variant, expected `function`").
DeepSeekBaseURL string
DeepSeekAPIKey string
DeepSeekModel string
// Proxy, when set, routes search requests through this http(s) proxy URL —
// useful when the search endpoint is only reachable via a proxy. Empty = direct.
Proxy string
// CACert / InsecureTLS mirror WebFetchConfig: trust a proxy's CA in addition
// to the system roots (CACert), or skip TLS verification entirely (InsecureTLS).
// Prefer CACert. See WebFetchConfig for the full semantics.
CACert string
InsecureTLS bool
}
// NewWebSearch builds the web_search tool for the configured backend. It returns
// an error when the config is unusable (unknown backend, or brave-free without a
// key) so a session fails fast at construction instead of at first call. The tool
// is network-facing, so it is not part of DefaultTools and requires permission.
func NewWebSearch(cfg WebSearchConfig) (CoreTool, error) {
prov, err := newSearchProvider(cfg)
if err != nil {
return nil, err
}
return Build(Spec{
Name: "web_search",
Description: "Search the web and return a ranked list of results (title, URL, description) — metadata only, up to 5 by default. Use WebFetch to read the full content of a specific URL. This makes an external network request.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{
"query": map[string]any{"type": "string", "description": "The search query."},
"limit": map[string]any{"type": "integer", "description": "Maximum number of results to return (1-20). Default 5.", "minimum": 1, "maximum": 20},
},
"required": []any{"query"},
},
// Read-only and safe to run concurrently, but network-facing: require approval.
ReadOnly: func(json.RawMessage) bool { return true },
Concurrent: func(json.RawMessage) bool { return true },
Permissions: func(_ context.Context, input json.RawMessage, _ permission.Context) permission.Decision {
var in struct {
Query string `json:"query"`
}
_ = json.Unmarshal(input, &in)
return permission.AskUser("web search: " + in.Query)
},
Run: webSearchRunner(prov),
}), nil
}
// newSearchProvider builds the search backend for cfg (shared by NewWebSearch and
// WebSearchProbe). One http.Client honors the proxy / TLS config. Returns an error
// on an unknown backend, or brave-free without a key.
func newSearchProvider(cfg WebSearchConfig) (searchProvider, error) {
backend := strings.ToLower(strings.TrimSpace(cfg.Backend))
if backend == "" {
backend = "ddgs"
}
client := newFetchClient(WebFetchConfig{Proxy: cfg.Proxy, CACert: cfg.CACert, InsecureTLS: cfg.InsecureTLS})
switch backend {
case "ddgs":
return &ddgsProvider{client: client, endpoint: ddgsEndpoint}, nil
case "brave-free":
key := strings.TrimSpace(cfg.BraveAPIKey)
if key == "" {
return nil, fmt.Errorf("web_search: backend %q requires a Brave Search API key", backend)
}
return &braveProvider{apiKey: key, client: client, endpoint: braveEndpoint}, nil
case "tavily":
key := strings.TrimSpace(cfg.TavilyAPIKey)
if key == "" {
return nil, fmt.Errorf("web_search: backend %q requires a Tavily API key", backend)
}
return &tavilyProvider{apiKey: key, client: client, endpoint: tavilyEndpoint}, nil
case "deepseek":
key := strings.TrimSpace(cfg.DeepSeekAPIKey)
if key == "" {
return nil, fmt.Errorf("web_search: backend %q requires a DeepSeek API key", backend)
}
base := strings.TrimSpace(cfg.DeepSeekBaseURL)
if base == "" {
return nil, fmt.Errorf("web_search: backend %q requires the Anthropic-format base URL of the DeepSeek profile", backend)
}
model := strings.TrimSpace(cfg.DeepSeekModel)
if model == "" {
return nil, fmt.Errorf("web_search: backend %q requires a model name", backend)
}
return &deepseekProvider{apiKey: key, model: model, client: client, endpoint: deepseekMessagesURL(base)}, nil
default:
return nil, fmt.Errorf("web_search: unknown backend %q (want \"ddgs\", \"brave-free\", \"tavily\", or \"deepseek\")", backend)
}
}
// WebSearchProbe runs a one-off search with cfg and returns the results, bypassing
// the tool/permission layer. It's the entry point for a connectivity/config check
// (e.g. a "test" button): same backend selection + proxy/TLS handling as the
// web_search tool, so a success means the live tool would reach the backend too.
func WebSearchProbe(ctx context.Context, cfg WebSearchConfig, query string, limit int) ([]SearchResult, error) {
prov, err := newSearchProvider(cfg)
if err != nil {
return nil, err
}
if limit <= 0 {
limit = 3
}
return prov.Search(ctx, query, limit)
}
func webSearchRunner(prov searchProvider) func(context.Context, json.RawMessage, *ToolContext) (Result, error) {
return func(ctx context.Context, input json.RawMessage, _ *ToolContext) (Result, error) {
var in struct {
Query string `json:"query"`
Limit int `json:"limit"`
}
if err := json.Unmarshal(input, &in); err != nil {
return Result{}, err
}
query := strings.TrimSpace(in.Query)
if query == "" {
return Errorf("Error: query must not be empty"), nil
}
limit := in.Limit
if limit <= 0 {
limit = 5
}
if limit > 20 {
limit = 20
}
// Hard wall-clock cap so a slow/rate-limited backend can't hang the agent
// loop. A backend that runs a model call per search (deepseek) declares a
// longer cap of its own; plain HTTP backends keep the 30s default.
wall := 30 * time.Second
if tp, ok := prov.(interface{ Timeout() time.Duration }); ok {
wall = tp.Timeout()
}
cctx, cancel := context.WithTimeout(ctx, wall)
defer cancel()
results, err := prov.Search(cctx, query, limit)
if err != nil {
return Errorf(fmt.Sprintf("Error searching web via %s: %s", prov.Name(), err.Error())), nil
}
out, _ := json.MarshalIndent(map[string]any{
"backend": prov.Name(),
"query": query,
"results": results,
}, "", " ")
return Text(truncate(string(out), 50000)), nil
}
}
// ─── DuckDuckGo (ddgs) ───────────────────────────────────────────────────────
// No API key. Scrapes the DuckDuckGo HTML endpoint (the same approach as the
// Python `ddgs` package) and parses results out of the returned markup. This is
// an unofficial endpoint: DuckDuckGo rate-limits by IP and may change the markup,
// so failures are surfaced as errors rather than treated as fatal.
const ddgsEndpoint = "https://html.duckduckgo.com/html/"
type ddgsProvider struct {
client *http.Client
endpoint string
}
func (p *ddgsProvider) Name() string { return "ddgs" }
func (p *ddgsProvider) Search(ctx context.Context, query string, limit int) ([]SearchResult, error) {
form := url.Values{"q": {query}, "kl": {"wt-wt"}}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint, strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// A browser-like UA — the endpoint blocks obviously-automated clients.
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0")
req.Header.Set("Referer", "https://html.duckduckgo.com/")
resp, err := p.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusAccepted || resp.StatusCode == http.StatusTooManyRequests {
return nil, fmt.Errorf("DuckDuckGo is rate-limiting (HTTP %d); try again later or switch backend", resp.StatusCode)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("DuckDuckGo returned HTTP %d", resp.StatusCode)
}
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxFetchBytes))
doc, err := html.Parse(strings.NewReader(string(body)))
if err != nil {
return nil, fmt.Errorf("could not parse DuckDuckGo response: %w", err)
}
return parseDDGS(doc, limit), nil
}
// parseDDGS walks the DuckDuckGo HTML result page. Each result carries a title
// anchor with class "result__a" (its href is a //duckduckgo.com/l/?uddg=<target>
// redirect) and a snippet element with class "result__snippet". We collect titles
// and snippets in document order and pair them by index.
func parseDDGS(doc *html.Node, limit int) []SearchResult {
type hit struct{ title, href string }
var hits []hit
var snippets []string
var walk func(n *html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "a" && hasClass(n, "result__a") {
hits = append(hits, hit{title: nodeText(n), href: unwrapDDGHref(attr(n, "href"))})
}
if n.Type == html.ElementNode && hasClass(n, "result__snippet") {
snippets = append(snippets, nodeText(n))
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(doc)
var out []SearchResult
for i, h := range hits {
if len(out) >= limit {
break
}
if h.href == "" {
continue
}
desc := ""
if i < len(snippets) {
desc = snippets[i]
}
out = append(out, SearchResult{
Title: strings.TrimSpace(h.title),
URL: h.href,
Description: strings.TrimSpace(desc),
Position: len(out) + 1,
})
}
return out
}
// unwrapDDGHref resolves DuckDuckGo's redirect wrapper. Result links come back as
// "//duckduckgo.com/l/?uddg=<url-encoded target>&rut=…"; we return the decoded
// target. A plain http(s) href is returned unchanged.
func unwrapDDGHref(href string) string {
if href == "" {
return ""
}
if strings.HasPrefix(href, "//") {
href = "https:" + href
}
u, err := url.Parse(href)
if err != nil {
return href
}
if target := u.Query().Get("uddg"); target != "" {
return target
}
if strings.HasPrefix(href, "http://") || strings.HasPrefix(href, "https://") {
return href
}
return ""
}
// ─── Brave Search (free tier) ────────────────────────────────────────────────
// Official Brave Search API. Free tier is 2,000 queries/month (1 qps). Auth via
// the X-Subscription-Token header.
const braveEndpoint = "https://api.search.brave.com/res/v1/web/search"
type braveProvider struct {
apiKey string
client *http.Client
endpoint string
}
func (p *braveProvider) Name() string { return "brave-free" }
func (p *braveProvider) Search(ctx context.Context, query string, limit int) ([]SearchResult, error) {
count := min(limit, 20) // Brave caps `count` at 20.
q := url.Values{"q": {query}, "count": {fmt.Sprintf("%d", count)}}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.endpoint+"?"+q.Encode(), nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Subscription-Token", p.apiKey)
resp, err := p.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Brave Search returned HTTP %d", resp.StatusCode)
}
var payload struct {
Web struct {
Results []struct {
Title string `json:"title"`
URL string `json:"url"`
Description string `json:"description"`
} `json:"results"`
} `json:"web"`
}
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxFetchBytes))
if err := json.Unmarshal(body, &payload); err != nil {
return nil, fmt.Errorf("could not parse Brave Search response: %w", err)
}
var out []SearchResult
for _, r := range payload.Web.Results {
if len(out) >= limit {
break
}
out = append(out, SearchResult{
Title: r.Title,
URL: r.URL,
Description: r.Description,
Position: len(out) + 1,
})
}
return out, nil
}
// ─── Tavily Search ───────────────────────────────────────────────────────────
// Official Tavily Search API. Requires an API key (tvly-…). Returns results
// with extracted content summaries, making it a good complement to WebFetch.
const tavilyEndpoint = "https://api.tavily.com/search"
type tavilyProvider struct {
apiKey string
client *http.Client
endpoint string
}
func (p *tavilyProvider) Name() string { return "tavily" }
func (p *tavilyProvider) Search(ctx context.Context, query string, limit int) ([]SearchResult, error) {
body, err := json.Marshal(map[string]any{
"api_key": p.apiKey,
"query": query,
"max_results": min(limit, 20),
"search_depth": "basic",
})
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint, strings.NewReader(string(body)))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := p.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Tavily Search returned HTTP %d", resp.StatusCode)
}
var payload struct {
Results []struct {
Title string `json:"title"`
URL string `json:"url"`
Content string `json:"content"`
} `json:"results"`
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, maxFetchBytes))
if err := json.Unmarshal(raw, &payload); err != nil {
return nil, fmt.Errorf("could not parse Tavily Search response: %w", err)
}
var out []SearchResult
for _, r := range payload.Results {
if len(out) >= limit {
break
}
out = append(out, SearchResult{
Title: r.Title,
URL: r.URL,
Description: r.Content,
Position: len(out) + 1,
})
}
return out, nil
}
// ─── DeepSeek (server-side web search) ───────────────────────────────────────
// Unlike every other backend here, DeepSeek exposes no search API to call. Its
// search only exists inside the Anthropic-compatible messages endpoint as the
// web_search_20250305 *server* tool: we declare the tool, DeepSeek's own model
// decides to search, DeepSeek's servers run the search, and the hits come back
// as web_search_tool_result blocks in the same response. So one search here
// costs one model call, and the queries are chosen server-side rather than by
// the caller (query below is a search *instruction*, not a literal term).
//
// Streaming is mandatory, not a preference: DeepSeek's non-streaming response
// embeds raw newlines inside JSON string literals, which encoding/json rejects
// with "invalid character '\n' in string literal". The SSE frames are clean.
// deepseekMessagesURL normalizes a profile base URL to the messages endpoint,
// tolerating bases written with or without the /v1 suffix.
func deepseekMessagesURL(base string) string {
b := strings.TrimRight(strings.TrimSpace(base), "/")
switch {
case strings.HasSuffix(b, "/v1/messages"):
return b
case strings.HasSuffix(b, "/v1"):
return b + "/messages"
default:
return b + "/v1/messages"
}
}
type deepseekProvider struct {
apiKey string
model string
client *http.Client
endpoint string
}
func (p *deepseekProvider) Name() string { return "deepseek" }
// Timeout overrides the runner's default cap: this backend runs a full model
// inference (plus the server-side search) per call, so it needs far more room
// than a plain search HTTP request.
func (p *deepseekProvider) Timeout() time.Duration { return 120 * time.Second }
func (p *deepseekProvider) Search(ctx context.Context, query string, limit int) ([]SearchResult, error) {
// One server-side search returns ~10 hits; allow a second round only when the
// caller asked for more than that. Capped so a runaway loop can't bill us.
maxUses := (limit + 9) / 10
if maxUses < 1 {
maxUses = 1
}
if maxUses > 3 {
maxUses = 3
}
body, err := json.Marshal(map[string]any{
"model": p.model,
"max_tokens": 1024,
"stream": true,
"messages": []any{map[string]any{
"role": "user",
"content": "Search the web for: " + query + "\n\nUse the web_search tool. Do not answer from memory; reply with at most one short sentence once the search is done.",
}},
"tools": []any{map[string]any{
"type": "web_search_20250305",
"name": "web_search",
"max_uses": maxUses,
}},
})
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint, strings.NewReader(string(body)))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "text/event-stream")
req.Header.Set("x-api-key", p.apiKey)
req.Header.Set("anthropic-version", "2023-06-01")
resp, err := p.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, fmt.Errorf("DeepSeek search returned HTTP %d: %s", resp.StatusCode, truncate(strings.TrimSpace(string(raw)), 300))
}
return parseDeepSeekStream(resp.Body, limit)
}
// parseDeepSeekStream pulls web_search_tool_result blocks out of the SSE stream.
// Results arrive whole inside content_block_start (they are not deltas), so only
// that frame matters; text/thinking deltas are skipped.
func parseDeepSeekStream(r io.Reader, limit int) ([]SearchResult, error) {
sc := bufio.NewScanner(io.LimitReader(r, maxFetchBytes))
// A single result frame carries ~10 hits each with a multi-KB encrypted_content
// payload — observed at ~58KB, already past bufio's 64KB default ceiling.
sc.Buffer(make([]byte, 0, 64*1024), maxFetchBytes)
var out []SearchResult
var toolErr string
seen := map[string]bool{}
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if !strings.HasPrefix(line, "data:") {
continue
}
payload := strings.TrimSpace(line[len("data:"):])
if payload == "" || payload == "[DONE]" {
continue
}
var frame struct {
Type string `json:"type"`
ContentBlock struct {
Type string `json:"type"`
Content []struct {
Type string `json:"type"`
Title string `json:"title"`
URL string `json:"url"`
ErrorCode string `json:"error_code"`
} `json:"content"`
} `json:"content_block"`
Error struct {
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal([]byte(payload), &frame); err != nil {
continue // tolerate keep-alives and any frame shape we don't model
}
if frame.Type == "error" && frame.Error.Message != "" {
return nil, fmt.Errorf("DeepSeek search stream error: %s", frame.Error.Message)
}
if frame.Type != "content_block_start" || frame.ContentBlock.Type != "web_search_tool_result" {
continue
}
for _, hit := range frame.ContentBlock.Content {
// Failures ride in the same array as hits, e.g.
// {"type":"web_search_tool_result_error","error_code":"max_uses_exceeded"}.
if hit.ErrorCode != "" {
if toolErr == "" {
toolErr = hit.ErrorCode
}
continue
}
if hit.URL == "" || seen[hit.URL] {
continue
}
seen[hit.URL] = true
out = append(out, SearchResult{
Title: firstNonEmpty(hit.Title, hostOf(hit.URL)),
URL: hit.URL,
// Description stays empty by design: DeepSeek returns page content
// only as encrypted_content, which is not readable here. Follow up
// with WebFetch when a snippet is needed.
Position: len(out) + 1,
})
if len(out) >= limit {
return out, nil
}
}
}
if err := sc.Err(); err != nil {
return nil, fmt.Errorf("could not read DeepSeek search stream: %w", err)
}
// Only surface a tool-side failure when it cost us every result.
if len(out) == 0 && toolErr != "" {
return nil, fmt.Errorf("DeepSeek web search failed: %s", toolErr)
}
return out, nil
}
// ─── small helpers ───────────────────────────────────────────────────────────
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if strings.TrimSpace(v) != "" {
return v
}
}
return ""
}
// hostOf is the title fallback for hits DeepSeek returns with an empty title.
func hostOf(raw string) string {
if u, err := url.Parse(raw); err == nil && u.Host != "" {
return u.Host
}
return raw
}
// hasClass reports whether an element node's class attribute contains class
// (whitespace-delimited match).
func hasClass(n *html.Node, class string) bool {
for _, c := range strings.Fields(attr(n, "class")) {
if c == class {
return true
}
}
return false
}
// nodeText returns the concatenated, whitespace-collapsed text of a node's subtree.
func nodeText(n *html.Node) string {
var b strings.Builder
textOnly(&b, n)
return strings.Join(strings.Fields(b.String()), " ")
}
+235
View File
@@ -0,0 +1,235 @@
package tool
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
func TestNewWebSearchConfig(t *testing.T) {
if _, err := NewWebSearch(WebSearchConfig{Backend: "ddgs"}); err != nil {
t.Fatalf("ddgs backend should build: %v", err)
}
if _, err := NewWebSearch(WebSearchConfig{}); err != nil {
t.Fatalf("empty backend should default to ddgs: %v", err)
}
if _, err := NewWebSearch(WebSearchConfig{Backend: "brave-free"}); err == nil {
t.Fatal("brave-free without key should error")
}
if _, err := NewWebSearch(WebSearchConfig{Backend: "brave-free", BraveAPIKey: "k"}); err != nil {
t.Fatalf("brave-free with key should build: %v", err)
}
if _, err := NewWebSearch(WebSearchConfig{Backend: "nope"}); err == nil {
t.Fatal("unknown backend should error")
}
}
func TestDDGSSearchParse(t *testing.T) {
// Minimal fixture mimicking the html.duckduckgo.com/html/ result markup,
// including the //duckduckgo.com/l/?uddg= redirect wrapper.
page := `<html><body>
<div class="result">
<a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fa&rut=x">First Result</a>
<a class="result__snippet">First snippet text.</a>
</div>
<div class="result">
<a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.org%2Fb">Second Result</a>
<a class="result__snippet">Second snippet.</a>
</div>
</body></html>`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil || r.Form.Get("q") == "" {
t.Errorf("expected form q param, got err=%v form=%v", err, r.Form)
}
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write([]byte(page))
}))
defer srv.Close()
p := &ddgsProvider{client: srv.Client(), endpoint: srv.URL}
res, err := p.Search(context.Background(), "test query", 5)
if err != nil {
t.Fatalf("Search: %v", err)
}
if len(res) != 2 {
t.Fatalf("want 2 results, got %d: %+v", len(res), res)
}
if res[0].URL != "https://example.com/a" {
t.Errorf("uddg redirect not unwrapped: %q", res[0].URL)
}
if res[0].Title != "First Result" || res[0].Description != "First snippet text." {
t.Errorf("bad result[0]: %+v", res[0])
}
if res[0].Position != 1 || res[1].Position != 2 {
t.Errorf("positions not 1-indexed: %d %d", res[0].Position, res[1].Position)
}
// limit is honored.
res, _ = p.Search(context.Background(), "test", 1)
if len(res) != 1 {
t.Errorf("limit=1 should yield 1 result, got %d", len(res))
}
}
func TestBraveSearchParse(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-Subscription-Token"); got != "secret-key" {
t.Errorf("missing/incorrect auth header: %q", got)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"web":{"results":[
{"title":"T1","url":"https://a.example","description":"D1"},
{"title":"T2","url":"https://b.example","description":"D2"}
]}}`))
}))
defer srv.Close()
p := &braveProvider{apiKey: "secret-key", client: srv.Client(), endpoint: srv.URL}
res, err := p.Search(context.Background(), "q", 5)
if err != nil {
t.Fatalf("Search: %v", err)
}
if len(res) != 2 || res[0].Title != "T1" || res[1].URL != "https://b.example" {
t.Fatalf("bad parse: %+v", res)
}
if res[0].Position != 1 {
t.Errorf("position not 1-indexed: %d", res[0].Position)
}
}
func TestBraveHTTPError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}))
defer srv.Close()
p := &braveProvider{apiKey: "k", client: srv.Client(), endpoint: srv.URL}
if _, err := p.Search(context.Background(), "q", 5); err == nil {
t.Fatal("expected error on HTTP 401")
}
}
func TestUnwrapDDGHref(t *testing.T) {
cases := map[string]string{
"//duckduckgo.com/l/?uddg=https%3A%2F%2Fx.com%2Fy&rut=z": "https://x.com/y",
"https://plain.example/path": "https://plain.example/path",
"": "",
}
for in, want := range cases {
if got := unwrapDDGHref(in); got != want {
t.Errorf("unwrapDDGHref(%q) = %q, want %q", in, got, want)
}
}
// Sanity: url encoding round-trips as expected.
if _, err := url.Parse("//duckduckgo.com/l/?uddg=x"); err != nil {
t.Fatal(err)
}
}
func TestDeepSeekConfigValidation(t *testing.T) {
full := WebSearchConfig{Backend: "deepseek", DeepSeekBaseURL: "https://api.deepseek.com/anthropic", DeepSeekAPIKey: "k", DeepSeekModel: "deepseek-chat"}
if _, err := NewWebSearch(full); err != nil {
t.Fatalf("fully configured deepseek backend should build: %v", err)
}
for _, tc := range []struct {
name string
mut func(*WebSearchConfig)
}{
{"missing key", func(c *WebSearchConfig) { c.DeepSeekAPIKey = "" }},
{"missing base url", func(c *WebSearchConfig) { c.DeepSeekBaseURL = "" }},
{"missing model", func(c *WebSearchConfig) { c.DeepSeekModel = "" }},
} {
cfg := full
tc.mut(&cfg)
if _, err := NewWebSearch(cfg); err == nil {
t.Fatalf("deepseek backend with %s should error", tc.name)
}
}
}
func TestDeepSeekMessagesURL(t *testing.T) {
want := "https://api.deepseek.com/anthropic/v1/messages"
for _, in := range []string{
"https://api.deepseek.com/anthropic",
"https://api.deepseek.com/anthropic/",
"https://api.deepseek.com/anthropic/v1",
"https://api.deepseek.com/anthropic/v1/messages",
} {
if got := deepseekMessagesURL(in); got != want {
t.Errorf("deepseekMessagesURL(%q) = %q, want %q", in, got, want)
}
}
}
func TestParseDeepSeekStream(t *testing.T) {
// Mirrors a real DeepSeek stream: hits arrive whole inside content_block_start
// (never as deltas), an empty title needs a host fallback, the same URL can
// repeat across rounds, and a tool-side failure rides in the same array as
// the hits. Unknown fields ("caller") must not break decoding.
stream := `event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"server_tool_use","id":"call_00","name":"web_search","input":{},"caller":{"type":"direct"}}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"query\":\"x\"}"}}
event: content_block_start
data: {"type":"content_block_start","index":1,"content_block":{"type":"web_search_tool_result","tool_use_id":"call_00","content":[{"type":"web_search_result","title":"First","url":"https://a.example/1","encrypted_content":"zzz"},{"type":"web_search_result","title":"","url":"https://b.example/2"},{"type":"web_search_result","title":"Dup","url":"https://a.example/1"}]}}
event: content_block_start
data: {"type":"content_block_start","index":2,"content_block":{"type":"web_search_tool_result","tool_use_id":"call_01","content":[{"type":"web_search_tool_result_error","error_code":"max_uses_exceeded"}]}}
event: content_block_start
data: {"type":"content_block_start","index":3,"content_block":{"type":"text","text":""}}
data: [DONE]
`
got, err := parseDeepSeekStream(strings.NewReader(stream), 10)
if err != nil {
t.Fatalf("parse: %v", err)
}
if len(got) != 2 {
t.Fatalf("want 2 results (dup dropped, error item skipped), got %d: %+v", len(got), got)
}
if got[0].Title != "First" || got[0].URL != "https://a.example/1" || got[0].Position != 1 {
t.Errorf("first result wrong: %+v", got[0])
}
// Empty title falls back to the host so the model still has a label.
if got[1].Title != "b.example" {
t.Errorf("empty title should fall back to host, got %q", got[1].Title)
}
// DeepSeek only returns encrypted page content, so there is never a snippet.
if got[0].Description != "" {
t.Errorf("description should stay empty, got %q", got[0].Description)
}
}
func TestParseDeepSeekStreamLimitAndErrors(t *testing.T) {
hits := `{"type":"content_block_start","index":1,"content_block":{"type":"web_search_tool_result","content":[{"type":"web_search_result","title":"A","url":"https://a.example"},{"type":"web_search_result","title":"B","url":"https://b.example"},{"type":"web_search_result","title":"C","url":"https://c.example"}]}}`
got, err := parseDeepSeekStream(strings.NewReader("data: "+hits+"\n\n"), 2)
if err != nil {
t.Fatalf("parse: %v", err)
}
if len(got) != 2 {
t.Fatalf("limit should cap results at 2, got %d", len(got))
}
// A failure with no usable hits must surface rather than look like "no results".
onlyErr := `data: {"type":"content_block_start","index":1,"content_block":{"type":"web_search_tool_result","content":[{"type":"web_search_tool_result_error","error_code":"max_uses_exceeded"}]}}`
if _, err := parseDeepSeekStream(strings.NewReader(onlyErr+"\n\n"), 5); err == nil {
t.Fatal("a result-less stream carrying an error_code should error")
}
// Stream-level error frames propagate too.
streamErr := `data: {"type":"error","error":{"type":"overloaded_error","message":"boom"}}`
if _, err := parseDeepSeekStream(strings.NewReader(streamErr+"\n\n"), 5); err == nil {
t.Fatal("stream error frame should error")
}
// An empty but well-formed stream is "no results", not a failure.
if res, err := parseDeepSeekStream(strings.NewReader("data: [DONE]\n\n"), 5); err != nil || len(res) != 0 {
t.Fatalf("empty stream should yield no results and no error, got %v / %v", res, err)
}
}