Initial commit: Go agentic harness extracted from Felix

This commit is contained in:
sausheong committed 2026-05-07 11:31:42 +08:00
commit 1f2c471ff9
89 files changed
+19388

No files matched your search

+175
View File
@@ -0,0 +1,175 @@
package tool
import (
"context"
"encoding/json"
"fmt"
)
// JobScheduler is the interface for scheduling recurring jobs.
// This avoids importing the cron package directly (decoupling).
// The cron.Scheduler implements this via an adapter in main.go.
//
// AddJob takes the agent ID the job will run as. Empty agentID lets the
// adapter pick a default (typically the first configured agent) — only
// useful for legacy persisted jobs and UI calls that don't know better.
type JobScheduler interface {
AddJob(agentID, name, schedule, prompt string) error
RemoveJob(name string) error
ListJobs() []JobInfo
PauseJob(name string) error
ResumeJob(name string) error
UpdateJobSchedule(name, schedule string) error
}
// JobInfo is a summary of a scheduled job, returned by ListJobs.
type JobInfo struct {
Name string `json:"name"`
AgentID string `json:"agentId,omitempty"`
Schedule string `json:"schedule"`
Prompt string `json:"prompt"`
Paused bool `json:"paused"`
}
// CronTool allows the agent to dynamically schedule recurring tasks.
//
// AgentID is the calling agent's ID, baked in at construction so jobs the
// LLM schedules execute as the agent that scheduled them. Empty is allowed
// (adapter falls back to its default agent) but should be avoided in
// production wiring.
type CronTool struct {
AgentID string
Scheduler JobScheduler
}
type cronInput struct {
Action string `json:"action"` // "add", "remove", or "list"
Name string `json:"name,omitempty"` // job name (for add/remove)
Schedule string `json:"schedule,omitempty"` // interval e.g. "30m", "1h", "24h" (for add)
Prompt string `json:"prompt,omitempty"` // prompt to send to the agent (for add)
}
func (t *CronTool) Name() string { return "cron" }
func (t *CronTool) Description() string {
return `Schedule, stop, or list recurring tasks. Supports three actions:
- "add": Schedule a new recurring job. Requires "name" (unique identifier), "schedule" (Go duration string like "30m", "1h", "24h"), and "prompt" (the instruction to execute each interval).
- "remove": Stop and remove a scheduled job. Requires "name".
- "list": List all currently scheduled jobs.
Jobs run as the agent that scheduled them — same model, workspace, tools, and policies. You cannot schedule a job to run as a different agent.
Use this to set up automated checks, reminders, or periodic tasks.`
}
func (t *CronTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["add", "remove", "list"],
"description": "The action to perform: add a new job, remove an existing job, or list all jobs"
},
"name": {
"type": "string",
"description": "Unique name for the job (required for add)"
},
"schedule": {
"type": "string",
"description": "How often to run, as a Go duration string (e.g. \"30m\", \"1h\", \"24h\") (required for add)"
},
"prompt": {
"type": "string",
"description": "The prompt/instruction to execute each interval (required for add)"
}
},
"required": ["action"]
}`)
}
// IsConcurrencySafe returns false — cron mutates the scheduler's job list.
func (t *CronTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
func (t *CronTool) Execute(ctx context.Context, input json.RawMessage) (ToolResult, error) {
var in cronInput
if err := json.Unmarshal(input, &in); err != nil {
return ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
if t.Scheduler == nil {
return ToolResult{Error: "cron scheduling is not available"}, nil
}
switch in.Action {
case "add":
return t.addJob(in)
case "remove":
return t.removeJob(in)
case "list":
return t.listJobs()
default:
return ToolResult{Error: fmt.Sprintf("unknown action: %q (valid: add, remove, list)", in.Action)}, nil
}
}
func (t *CronTool) addJob(in cronInput) (ToolResult, error) {
if in.Name == "" {
return ToolResult{Error: "name is required for add action"}, nil
}
if in.Schedule == "" {
return ToolResult{Error: "schedule is required for add action"}, nil
}
if in.Prompt == "" {
return ToolResult{Error: "prompt is required for add action"}, nil
}
if err := t.Scheduler.AddJob(t.AgentID, in.Name, in.Schedule, in.Prompt); err != nil {
return ToolResult{Error: fmt.Sprintf("failed to schedule job: %v", err)}, nil
}
msg := fmt.Sprintf("Scheduled job %q to run every %s", in.Name, in.Schedule)
if t.AgentID != "" {
msg += fmt.Sprintf(" as agent %q", t.AgentID)
}
return ToolResult{
Output: msg,
Metadata: map[string]any{
"name": in.Name,
"schedule": in.Schedule,
"agentId": t.AgentID,
},
}, nil
}
func (t *CronTool) removeJob(in cronInput) (ToolResult, error) {
if in.Name == "" {
return ToolResult{Error: "name is required for remove action"}, nil
}
if err := t.Scheduler.RemoveJob(in.Name); err != nil {
return ToolResult{Error: fmt.Sprintf("failed to remove job: %v", err)}, nil
}
return ToolResult{
Output: fmt.Sprintf("Removed job %q", in.Name),
}, nil
}
func (t *CronTool) listJobs() (ToolResult, error) {
jobs := t.Scheduler.ListJobs()
if len(jobs) == 0 {
return ToolResult{Output: "No scheduled jobs."}, nil
}
out, err := json.MarshalIndent(jobs, "", " ")
if err != nil {
return ToolResult{Error: fmt.Sprintf("failed to marshal jobs: %v", err)}, nil
}
return ToolResult{
Output: fmt.Sprintf("%d scheduled job(s):\n%s", len(jobs), string(out)),
Metadata: map[string]any{
"count": len(jobs),
},
}, nil
}
+193
View File
@@ -0,0 +1,193 @@
package tool
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// mockJobScheduler records calls and returns canned data.
type mockJobScheduler struct {
lastJobAgentID string
lastJobName string
lastJobSchedule string
lastJobPrompt string
removedName string
jobs []JobInfo
addErr error
removeErr error
}
func (m *mockJobScheduler) AddJob(agentID, name, schedule, prompt string) error {
m.lastJobAgentID = agentID
m.lastJobName = name
m.lastJobSchedule = schedule
m.lastJobPrompt = prompt
return m.addErr
}
func (m *mockJobScheduler) RemoveJob(name string) error {
m.removedName = name
return m.removeErr
}
func (m *mockJobScheduler) ListJobs() []JobInfo {
return m.jobs
}
func (m *mockJobScheduler) PauseJob(name string) error {
return nil
}
func (m *mockJobScheduler) ResumeJob(name string) error {
return nil
}
func (m *mockJobScheduler) UpdateJobSchedule(name, schedule string) error {
return nil
}
func TestCronToolName(t *testing.T) {
tool := &CronTool{}
assert.Equal(t, "cron", tool.Name())
}
func TestCronToolParameters(t *testing.T) {
tool := &CronTool{}
params := tool.Parameters()
assert.True(t, json.Valid(params), "Parameters() should return valid JSON")
}
func TestCronToolAddJob(t *testing.T) {
scheduler := &mockJobScheduler{}
tool := &CronTool{AgentID: "alice", Scheduler: scheduler}
input, _ := json.Marshal(cronInput{
Action: "add",
Name: "daily-check",
Schedule: "24h",
Prompt: "Run daily diagnostics",
})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Empty(t, result.Error)
assert.Contains(t, result.Output, "daily-check")
assert.Contains(t, result.Output, "24h")
assert.Contains(t, result.Output, "alice")
assert.Equal(t, "alice", scheduler.lastJobAgentID)
assert.Equal(t, "daily-check", scheduler.lastJobName)
assert.Equal(t, "24h", scheduler.lastJobSchedule)
assert.Equal(t, "Run daily diagnostics", scheduler.lastJobPrompt)
}
func TestCronToolListJobs(t *testing.T) {
scheduler := &mockJobScheduler{
jobs: []JobInfo{
{Name: "job1", Schedule: "1h", Prompt: "check status"},
{Name: "job2", Schedule: "30m", Prompt: "monitor logs"},
},
}
tool := &CronTool{Scheduler: scheduler}
input, _ := json.Marshal(cronInput{Action: "list"})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Empty(t, result.Error)
assert.Contains(t, result.Output, "2 scheduled job(s)")
assert.Contains(t, result.Output, "job1")
assert.Contains(t, result.Output, "job2")
}
func TestCronToolListJobsEmpty(t *testing.T) {
scheduler := &mockJobScheduler{jobs: []JobInfo{}}
tool := &CronTool{Scheduler: scheduler}
input, _ := json.Marshal(cronInput{Action: "list"})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Empty(t, result.Error)
assert.Contains(t, result.Output, "No scheduled jobs")
}
func TestCronToolUnknownAction(t *testing.T) {
scheduler := &mockJobScheduler{}
tool := &CronTool{Scheduler: scheduler}
input, _ := json.Marshal(cronInput{Action: "delete"})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "unknown action")
assert.Contains(t, result.Error, "delete")
}
func TestCronToolAddMissingName(t *testing.T) {
scheduler := &mockJobScheduler{}
tool := &CronTool{Scheduler: scheduler}
input, _ := json.Marshal(cronInput{
Action: "add",
Schedule: "1h",
Prompt: "do stuff",
})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "name is required")
}
func TestCronToolAddMissingSchedule(t *testing.T) {
scheduler := &mockJobScheduler{}
tool := &CronTool{Scheduler: scheduler}
input, _ := json.Marshal(cronInput{
Action: "add",
Name: "job1",
Prompt: "do stuff",
})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "schedule is required")
}
func TestCronToolAddMissingPrompt(t *testing.T) {
scheduler := &mockJobScheduler{}
tool := &CronTool{Scheduler: scheduler}
input, _ := json.Marshal(cronInput{
Action: "add",
Name: "job1",
Schedule: "1h",
})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "prompt is required")
}
func TestCronToolNilScheduler(t *testing.T) {
tool := &CronTool{Scheduler: nil}
input, _ := json.Marshal(cronInput{Action: "list"})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "not available")
}
func TestCronToolAddJobError(t *testing.T) {
scheduler := &mockJobScheduler{addErr: errors.New("duplicate name")}
tool := &CronTool{Scheduler: scheduler}
input, _ := json.Marshal(cronInput{
Action: "add",
Name: "job1",
Schedule: "1h",
Prompt: "do stuff",
})
result, err := tool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "failed to schedule job")
assert.Contains(t, result.Error, "duplicate name")
}
+114
View File
@@ -0,0 +1,114 @@
package tool
import (
"context"
"encoding/json"
"fmt"
)
// LoadSkillTool fetches a skill body by name. Decoupled from the skill
// package via the Lookup func — keeps internal/tools free of skill/memory
// imports. Caller wires Lookup at construction (typically in
// agent.BuildRuntimeForAgent where the *skill.Loader is already in scope).
type LoadSkillTool struct {
// Lookup returns (body, true) if a skill with the given name exists,
// (_, false) otherwise. Implementations should match by exact name —
// fuzzy matching belongs to the agent index, not the loader.
Lookup func(name string) (body string, ok bool)
}
func (t *LoadSkillTool) Name() string { return "load_skill" }
func (t *LoadSkillTool) Description() string {
return "Load the full body of a skill by name. Use after consulting the Skills Index to read a skill's instructions; the body is returned as the tool output and becomes available in your next response. Pass the exact skill name from the index."
}
func (t *LoadSkillTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Exact skill name as listed in the Skills Index"
}
},
"required": ["name"]
}`)
}
func (t *LoadSkillTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
func (t *LoadSkillTool) Execute(_ context.Context, input json.RawMessage) (ToolResult, error) {
var in struct {
Name string `json:"name"`
}
if err := json.Unmarshal(input, &in); err != nil {
return ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
if in.Name == "" {
return ToolResult{Error: "name is required"}, nil
}
if t.Lookup == nil {
return ToolResult{Error: "no skill loader configured"}, nil
}
body, ok := t.Lookup(in.Name)
if !ok {
return ToolResult{Error: fmt.Sprintf("skill not found: %q", in.Name)}, nil
}
if body == "" {
// Found but empty body — surface explicitly so the agent doesn't
// loop trying to load a placeholder skill.
return ToolResult{Output: fmt.Sprintf("(skill %q loaded but has no body content)", in.Name)}, nil
}
return ToolResult{Output: body}, nil
}
// LoadMemoryTool fetches a memory entry body by id. Same decoupling
// pattern as LoadSkillTool.
type LoadMemoryTool struct {
Lookup func(id string) (body string, ok bool)
}
func (t *LoadMemoryTool) Name() string { return "load_memory" }
func (t *LoadMemoryTool) Description() string {
return "Load the full body of a memory entry by id. Use after consulting the Memory Index to read an entry's content; the body is returned as the tool output. Pass the exact id from the index."
}
func (t *LoadMemoryTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Exact memory entry id as listed in the Memory Index"
}
},
"required": ["id"]
}`)
}
func (t *LoadMemoryTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
func (t *LoadMemoryTool) Execute(_ context.Context, input json.RawMessage) (ToolResult, error) {
var in struct {
ID string `json:"id"`
}
if err := json.Unmarshal(input, &in); err != nil {
return ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
if in.ID == "" {
return ToolResult{Error: "id is required"}, nil
}
if t.Lookup == nil {
return ToolResult{Error: "no memory manager configured"}, nil
}
body, ok := t.Lookup(in.ID)
if !ok {
return ToolResult{Error: fmt.Sprintf("memory entry not found: %q", in.ID)}, nil
}
if body == "" {
return ToolResult{Output: fmt.Sprintf("(memory entry %q loaded but is empty)", in.ID)}, nil
}
return ToolResult{Output: body}, nil
}
+117
View File
@@ -0,0 +1,117 @@
package tool
import (
"context"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// --- LoadSkillTool ---
func TestLoadSkillToolReturnsBody(t *testing.T) {
tool := &LoadSkillTool{
Lookup: func(name string) (string, bool) {
if name == "ffmpeg" {
return "FFMPEG_BODY", true
}
return "", false
},
}
in, _ := json.Marshal(map[string]string{"name": "ffmpeg"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
assert.Equal(t, "FFMPEG_BODY", res.Output)
assert.Empty(t, res.Error)
}
func TestLoadSkillToolNotFoundReturnsError(t *testing.T) {
tool := &LoadSkillTool{
Lookup: func(string) (string, bool) { return "", false },
}
in, _ := json.Marshal(map[string]string{"name": "ghost"})
res, _ := tool.Execute(context.Background(), in)
assert.Empty(t, res.Output)
assert.Contains(t, res.Error, "skill not found")
assert.Contains(t, res.Error, `"ghost"`)
}
func TestLoadSkillToolMissingNameRejected(t *testing.T) {
tool := &LoadSkillTool{Lookup: func(string) (string, bool) { return "", true }}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{}`))
assert.Equal(t, "name is required", res.Error)
}
func TestLoadSkillToolNilLookup(t *testing.T) {
// Construct without Lookup (e.g., misconfigured runtime). The tool
// must NOT panic — it needs to surface a clean error so the agent
// can reason about the failure rather than the run blowing up.
tool := &LoadSkillTool{}
in, _ := json.Marshal(map[string]string{"name": "x"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
assert.Contains(t, res.Error, "no skill loader configured")
}
func TestLoadSkillToolInvalidJSON(t *testing.T) {
tool := &LoadSkillTool{Lookup: func(string) (string, bool) { return "", true }}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{not json`))
assert.Contains(t, res.Error, "invalid input")
}
func TestLoadSkillToolEmptyBody(t *testing.T) {
// Found but body empty → emit a placeholder Output (not Error). An
// Error would imply "doesn't exist"; an empty Output would imply
// "succeeded with nothing useful". The placeholder distinguishes.
tool := &LoadSkillTool{Lookup: func(string) (string, bool) { return "", true }}
in, _ := json.Marshal(map[string]string{"name": "blank"})
res, _ := tool.Execute(context.Background(), in)
assert.Empty(t, res.Error)
assert.Contains(t, res.Output, `"blank"`)
assert.Contains(t, res.Output, "no body content")
}
func TestLoadSkillToolNameAndDescription(t *testing.T) {
tool := &LoadSkillTool{}
assert.Equal(t, "load_skill", tool.Name())
assert.NotEmpty(t, tool.Description())
assert.True(t, tool.IsConcurrencySafe(nil), "load_skill is read-only and must be parallel-safe")
}
// --- LoadMemoryTool ---
func TestLoadMemoryToolReturnsBody(t *testing.T) {
tool := &LoadMemoryTool{
Lookup: func(id string) (string, bool) {
if id == "feedback_xyz" {
return "FEEDBACK_BODY", true
}
return "", false
},
}
in, _ := json.Marshal(map[string]string{"id": "feedback_xyz"})
res, _ := tool.Execute(context.Background(), in)
assert.Equal(t, "FEEDBACK_BODY", res.Output)
}
func TestLoadMemoryToolNotFound(t *testing.T) {
tool := &LoadMemoryTool{Lookup: func(string) (string, bool) { return "", false }}
in, _ := json.Marshal(map[string]string{"id": "ghost"})
res, _ := tool.Execute(context.Background(), in)
assert.Contains(t, res.Error, "memory entry not found")
}
func TestLoadMemoryToolMissingIDRejected(t *testing.T) {
tool := &LoadMemoryTool{Lookup: func(string) (string, bool) { return "x", true }}
res, _ := tool.Execute(context.Background(), json.RawMessage(`{}`))
assert.Equal(t, "id is required", res.Error)
}
func TestLoadMemoryToolNameAndDescription(t *testing.T) {
tool := &LoadMemoryTool{}
assert.Equal(t, "load_memory", tool.Name())
assert.NotEmpty(t, tool.Description())
assert.True(t, tool.IsConcurrencySafe(nil))
}
+85
View File
@@ -0,0 +1,85 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"github.com/sausheong/harness/llm"
)
// DecisionBehavior is the outcome of a permission check.
type DecisionBehavior int
const (
DecisionAllow DecisionBehavior = iota
DecisionDeny
)
// Decision is the result of a PermissionChecker.Check call. Reason is surfaced
// into the tool result when the behavior is Deny; it is ignored when Allow.
type Decision struct {
Behavior DecisionBehavior
Reason string
}
// PermissionChecker decides whether a tool call may proceed. It is consulted
// once per tool invocation, after the call's input has been parsed but before
// the tool's Execute runs. Implementations must be safe for concurrent use.
//
// The input is passed (and may be ignored by simple implementations) so future
// input-aware checkers can implement the same interface without a signature
// change.
type PermissionChecker interface {
Check(ctx context.Context, agentID, toolName string, input json.RawMessage) Decision
// FilterToolDefs returns the subset of toolDefs visible to the given
// agent. The order of the input is preserved. Used at tool-list-assembly
// time so the LLM only advertises tools the agent is permitted to call.
// Implementations must be safe for concurrent use.
FilterToolDefs(toolDefs []llm.ToolDef, agentID string) []llm.ToolDef
}
// StaticChecker is the default PermissionChecker. It wraps existing per-agent
// tools.Policy values keyed by agent ID. An agent not present in the map is
// treated as allow-all (matches today's behavior when no policy is configured).
type StaticChecker struct {
perAgent map[string]Policy
}
// NewStaticChecker builds a StaticChecker. A nil or empty map means allow-all
// for every agent.
func NewStaticChecker(perAgent map[string]Policy) *StaticChecker {
if perAgent == nil {
perAgent = map[string]Policy{}
}
return &StaticChecker{perAgent: perAgent}
}
// Check implements PermissionChecker.
func (c *StaticChecker) Check(_ context.Context, agentID, toolName string, _ json.RawMessage) Decision {
p, ok := c.perAgent[agentID]
if !ok || p.IsAllowed(toolName) {
return Decision{Behavior: DecisionAllow}
}
return Decision{
Behavior: DecisionDeny,
Reason: fmt.Sprintf("tool %q is not allowed for agent %q", toolName, agentID),
}
}
// FilterToolDefs implements PermissionChecker. Unknown agents see the full
// toolDefs list (matches Check's allow-all default). Known agents have their
// list filtered through Policy.IsAllowed.
func (c *StaticChecker) FilterToolDefs(toolDefs []llm.ToolDef, agentID string) []llm.ToolDef {
p, ok := c.perAgent[agentID]
if !ok {
return toolDefs // unknown agent → allow-all (matches Check)
}
out := make([]llm.ToolDef, 0, len(toolDefs))
for _, td := range toolDefs {
if p.IsAllowed(td.Name) {
out = append(out, td)
}
}
return out
}
+112
View File
@@ -0,0 +1,112 @@
package tool
import (
"context"
"encoding/json"
"testing"
"github.com/sausheong/harness/llm"
"github.com/stretchr/testify/require"
)
func TestStaticChecker_AllowsListedTool(t *testing.T) {
c := NewStaticChecker(map[string]Policy{
"agent1": {Allow: []string{"read_file", "bash"}},
})
d := c.Check(context.Background(), "agent1", "read_file", json.RawMessage(`{}`))
require.Equal(t, DecisionAllow, d.Behavior)
require.Empty(t, d.Reason)
}
func TestStaticChecker_DeniesUnlistedTool(t *testing.T) {
c := NewStaticChecker(map[string]Policy{
"agent1": {Allow: []string{"read_file"}},
})
d := c.Check(context.Background(), "agent1", "bash", json.RawMessage(`{}`))
require.Equal(t, DecisionDeny, d.Behavior)
require.Contains(t, d.Reason, "bash")
require.Contains(t, d.Reason, "agent1")
}
func TestStaticChecker_DeniesExplicitlyDeniedTool(t *testing.T) {
c := NewStaticChecker(map[string]Policy{
"agent1": {Deny: []string{"bash"}},
})
d := c.Check(context.Background(), "agent1", "bash", json.RawMessage(`{}`))
require.Equal(t, DecisionDeny, d.Behavior)
}
func TestStaticChecker_UnknownAgentDefaultsToAllow(t *testing.T) {
// An agent not present in the map is treated as allow-all. This matches
// today's behavior when no policy is configured: tools just run.
c := NewStaticChecker(map[string]Policy{})
d := c.Check(context.Background(), "agent_unknown", "bash", json.RawMessage(`{}`))
require.Equal(t, DecisionAllow, d.Behavior)
}
func TestStaticChecker_NilCheckerNotPossible(t *testing.T) {
// Sanity: ensure NewStaticChecker handles a nil map by treating it as empty.
c := NewStaticChecker(nil)
d := c.Check(context.Background(), "any", "any", nil)
require.Equal(t, DecisionAllow, d.Behavior)
}
func TestStaticChecker_FilterToolDefs_UnknownAgentReturnsFullList(t *testing.T) {
c := NewStaticChecker(map[string]Policy{
"agent1": {Allow: []string{"read_file"}},
})
defs := []llm.ToolDef{{Name: "read_file"}, {Name: "bash"}}
out := c.FilterToolDefs(defs, "unknown_agent")
require.Equal(t, defs, out, "unknown agent must see the full toolset")
}
func TestStaticChecker_FilterToolDefs_AllowList(t *testing.T) {
c := NewStaticChecker(map[string]Policy{
"agent1": {Allow: []string{"read_file", "bash"}},
})
defs := []llm.ToolDef{
{Name: "read_file"},
{Name: "write_file"}, // not in allow list
{Name: "bash"},
}
out := c.FilterToolDefs(defs, "agent1")
require.Len(t, out, 2)
require.Equal(t, "read_file", out[0].Name)
require.Equal(t, "bash", out[1].Name)
}
func TestStaticChecker_FilterToolDefs_DenyList(t *testing.T) {
c := NewStaticChecker(map[string]Policy{
"agent1": {Deny: []string{"bash"}},
})
defs := []llm.ToolDef{
{Name: "read_file"},
{Name: "bash"}, // denied
{Name: "web_fetch"},
}
out := c.FilterToolDefs(defs, "agent1")
require.Len(t, out, 2)
require.Equal(t, "read_file", out[0].Name)
require.Equal(t, "web_fetch", out[1].Name)
}
func TestStaticChecker_FilterToolDefs_EmptyInput(t *testing.T) {
c := NewStaticChecker(map[string]Policy{
"agent1": {Allow: []string{"read_file"}},
})
out := c.FilterToolDefs([]llm.ToolDef{}, "agent1")
require.Empty(t, out)
}
func TestStaticChecker_FilterToolDefs_OrderPreserved(t *testing.T) {
c := NewStaticChecker(map[string]Policy{
"agent1": {}, // no policy → allow-all
})
defs := []llm.ToolDef{
{Name: "z_tool"},
{Name: "a_tool"},
{Name: "m_tool"},
}
out := c.FilterToolDefs(defs, "agent1")
require.Equal(t, defs, out, "order must be preserved")
}
+31
View File
@@ -0,0 +1,31 @@
package tool
// Policy defines allow/deny rules for tool execution.
type Policy struct {
Allow []string // tool names to allow (empty = allow all)
Deny []string // tool names to deny (checked after allow)
}
// IsAllowed checks whether a tool name is permitted by this policy.
// Logic: if Allow is non-empty, the tool must be in Allow.
// If the tool is in Deny, it is blocked regardless.
func (p Policy) IsAllowed(toolName string) bool {
// Check deny list first
for _, d := range p.Deny {
if d == toolName || d == "*" {
return false
}
}
// If allow list is non-empty, tool must be in it
if len(p.Allow) > 0 {
for _, a := range p.Allow {
if a == toolName || a == "*" {
return true
}
}
return false
}
return true
}
+62
View File
@@ -0,0 +1,62 @@
package tool
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestPolicyAllowAll(t *testing.T) {
p := Policy{} // empty allow/deny = allow all
assert.True(t, p.IsAllowed("bash"))
assert.True(t, p.IsAllowed("read_file"))
assert.True(t, p.IsAllowed("anything"))
}
func TestPolicyAllowList(t *testing.T) {
p := Policy{
Allow: []string{"read_file", "write_file"},
}
assert.True(t, p.IsAllowed("read_file"))
assert.True(t, p.IsAllowed("write_file"))
assert.False(t, p.IsAllowed("bash"))
assert.False(t, p.IsAllowed("edit_file"))
}
func TestPolicyDenyList(t *testing.T) {
p := Policy{
Deny: []string{"bash"},
}
assert.False(t, p.IsAllowed("bash"))
assert.True(t, p.IsAllowed("read_file"))
assert.True(t, p.IsAllowed("write_file"))
}
func TestPolicyAllowAndDeny(t *testing.T) {
// Allow overridden by deny
p := Policy{
Allow: []string{"read_file", "bash"},
Deny: []string{"bash"},
}
assert.True(t, p.IsAllowed("read_file"))
assert.False(t, p.IsAllowed("bash")) // denied despite being in allow
assert.False(t, p.IsAllowed("web_fetch")) // not in allow
}
func TestPolicyWildcardAllow(t *testing.T) {
p := Policy{
Allow: []string{"*"},
Deny: []string{"bash"},
}
assert.True(t, p.IsAllowed("read_file"))
assert.False(t, p.IsAllowed("bash"))
}
func TestPolicyWildcardDeny(t *testing.T) {
p := Policy{
Deny: []string{"*"},
}
assert.False(t, p.IsAllowed("bash"))
assert.False(t, p.IsAllowed("read_file"))
}
+179
View File
@@ -0,0 +1,179 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
)
// SubagentFactory builds a SubagentRunner for the given subagent ID. The
// implementation enforces the recursion-depth cap and validates that agentID
// refers to an opt-in subagent (Subagent: true in AgentConfig). The
// parentDepth argument lets the factory check `parentDepth+1 <= max` before
// constructing anything.
type SubagentFactory func(ctx context.Context, agentID string, parentDepth int) (SubagentRunner, error)
// SubagentRunner is the narrow interface TaskTool calls. It exists so that
// internal/tools can stay decoupled from internal/agent — agent.Runtime
// satisfies this contract via a small adapter (built in T6).
type SubagentRunner interface {
// Run executes the subagent with the given prompt. It returns a channel
// that the caller drains until close. Each event signals a step:
// - Text != "": a text delta to accumulate into the final tool output
// - Done == true: subagent finished cleanly
// - Aborted == true: subagent terminated due to cancellation
// - Err != nil: subagent failed
Run(ctx context.Context, prompt string) (<-chan AgentEventLike, error)
}
// AgentEventLike is the minimal event shape TaskTool needs from the agent
// package's AgentEvent. Defined here to avoid an import cycle between
// internal/tools and internal/agent. The subagent's Run goroutine adapts its
// AgentEvent into AgentEventLike for the channel TaskTool consumes.
type AgentEventLike struct {
Type int // matches agent.EventType (caller-defined int constants)
Text string
Done bool
Aborted bool
Err error
}
// TaskTool is the "task" tool — lets a parent agent delegate work to a
// subagent registered in the config (AgentConfig.Subagent: true). The
// subagent's final assistant text becomes this tool's Output.
//
// Not concurrency-safe (returns false from IsConcurrencySafe): a parent
// running multiple parallel "task" calls would spawn multiple subagent
// runtimes that all forward events to the same parent event channel,
// which is fine in principle but currently untested. Mark unsafe to be
// conservative; can be loosened later if integration tests prove parallel
// subagents work.
type TaskTool struct {
factory SubagentFactory
parentDepth int
eligible map[string]string // agent_id → description (for the tool-description block)
descBlock string // pre-formatted block listing available subagents
}
// NewTaskTool constructs a TaskTool. parentDepth is the depth of the
// invoking Runtime — passed straight through to factory() at execute time
// so depth-cap enforcement is centralised in the factory. eligible is the
// subset of agents flagged Subagent: true; it must be non-empty (caller
// is responsible for the empty-map gate per spec Section 6).
func NewTaskTool(factory SubagentFactory, parentDepth int, eligible map[string]string) *TaskTool {
return &TaskTool{
factory: factory,
parentDepth: parentDepth,
eligible: eligible,
descBlock: formatEligibleBlock(eligible),
}
}
// formatEligibleBlock renders the alphabetically-sorted list of available
// subagents that gets appended to the tool's Description. Sorting matters
// for prompt-cache stability — see Registry.ToolDefs for the same reason.
func formatEligibleBlock(eligible map[string]string) string {
if len(eligible) == 0 {
return ""
}
ids := make([]string, 0, len(eligible))
for id := range eligible {
ids = append(ids, id)
}
sort.Strings(ids)
var b strings.Builder
b.WriteString("\n\nAvailable subagents:\n")
for _, id := range ids {
fmt.Fprintf(&b, " - %s: %s\n", id, eligible[id])
}
return b.String()
}
// Name returns the tool name as advertised to the LLM.
func (*TaskTool) Name() string { return "task" }
// Description tells the parent LLM what the tool does and which subagents are
// available. The subagent listing is appended at construction time so the
// description is stable across invocations of the same TaskTool instance.
func (t *TaskTool) Description() string {
return "Delegate a subtask to a specialized subagent. The subagent runs " +
"independently with its own tools and system prompt; its final " +
"response is returned as this tool's output." + t.descBlock
}
// Parameters returns the JSON Schema for the tool input.
func (*TaskTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"required": ["agent_id", "prompt"],
"properties": {
"agent_id": {
"type": "string",
"description": "ID of the subagent to invoke. Must be one of the listed subagents in this tool's description."
},
"prompt": {
"type": "string",
"description": "The instruction to send to the subagent. Be self-contained — the subagent has no access to the parent conversation."
}
}
}`)
}
// IsConcurrencySafe is false: see TaskTool comment for rationale.
func (*TaskTool) IsConcurrencySafe(json.RawMessage) bool { return false }
// Execute parses the tool input, invokes the factory to construct a subagent
// runner, drains its events, and returns the accumulated assistant text as
// the tool result. Returns a tool error (in ToolResult.Error) for invalid
// input, unknown agent_id, depth-cap exceeded, subagent abort, and subagent
// error. Returns a Go error only if the factory itself returns one in a way
// that must propagate — currently never (factory errors land in ToolResult.Error).
func (t *TaskTool) Execute(ctx context.Context, input json.RawMessage) (ToolResult, error) {
var args struct {
AgentID string `json:"agent_id"`
Prompt string `json:"prompt"`
}
if err := json.Unmarshal(input, &args); err != nil {
return ToolResult{Error: fmt.Sprintf("invalid task input: %v", err)}, nil
}
if args.AgentID == "" || args.Prompt == "" {
return ToolResult{Error: "task: agent_id and prompt are required"}, nil
}
if _, ok := t.eligible[args.AgentID]; !ok {
ids := make([]string, 0, len(t.eligible))
for id := range t.eligible {
ids = append(ids, id)
}
sort.Strings(ids)
return ToolResult{
Error: fmt.Sprintf("task: unknown subagent %q (eligible: %s)", args.AgentID, strings.Join(ids, ", ")),
}, nil
}
runner, err := t.factory(ctx, args.AgentID, t.parentDepth)
if err != nil {
return ToolResult{Error: fmt.Sprintf("task: %v", err)}, nil
}
events, err := runner.Run(ctx, args.Prompt)
if err != nil {
return ToolResult{Error: fmt.Sprintf("task: subagent run failed: %v", err)}, nil
}
var out strings.Builder
for ev := range events {
switch {
case ev.Aborted:
return ToolResult{Error: "task: subagent aborted"}, nil
case ev.Err != nil:
return ToolResult{Error: fmt.Sprintf("task: subagent error: %v", ev.Err)}, nil
case ev.Text != "":
out.WriteString(ev.Text)
}
// Done is implicit on channel close after a Done event; we just continue draining.
}
return ToolResult{Output: out.String()}, nil
}
+136
View File
@@ -0,0 +1,136 @@
package tool
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
)
// stubRunner is a SubagentRunner whose Run returns a pre-built event channel.
// Used to drive TaskTool through specific event sequences without spinning up
// a real agent Runtime.
type stubRunner struct {
events []AgentEventLike
runErr error
}
func (s *stubRunner) Run(_ context.Context, _ string) (<-chan AgentEventLike, error) {
if s.runErr != nil {
return nil, s.runErr
}
ch := make(chan AgentEventLike, len(s.events))
for _, ev := range s.events {
ch <- ev
}
close(ch)
return ch, nil
}
func TestTaskTool_UnknownAgentReturnsError(t *testing.T) {
factory := SubagentFactory(func(_ context.Context, _ string, _ int) (SubagentRunner, error) {
t.Fatal("factory should not be called for unknown agent_id")
return nil, nil
})
tt := NewTaskTool(factory, 0, map[string]string{"researcher": "Web research"})
in := json.RawMessage(`{"agent_id": "ghost", "prompt": "hi"}`)
res, err := tt.Execute(context.Background(), in)
if err != nil {
t.Fatalf("unexpected Go error: %v", err)
}
if res.Error == "" {
t.Fatal("expected ToolResult.Error to be set")
}
// Should mention what was rejected and what's allowed.
if !strings.Contains(res.Error, "ghost") || !strings.Contains(res.Error, "researcher") {
t.Errorf("error should name the rejected agent and the eligible ones: %q", res.Error)
}
}
func TestTaskTool_DelegatesToFactoryAndCapturesText(t *testing.T) {
runner := &stubRunner{events: []AgentEventLike{
{Text: "hello "},
{Text: "world"},
{Done: true},
}}
factory := SubagentFactory(func(_ context.Context, agentID string, parentDepth int) (SubagentRunner, error) {
if agentID != "researcher" {
t.Errorf("factory called with %q, want researcher", agentID)
}
if parentDepth != 1 {
t.Errorf("parentDepth=%d, want 1", parentDepth)
}
return runner, nil
})
tt := NewTaskTool(factory, 1, map[string]string{"researcher": "Web research"})
in := json.RawMessage(`{"agent_id": "researcher", "prompt": "summarize Go"}`)
res, err := tt.Execute(context.Background(), in)
if err != nil {
t.Fatalf("unexpected Go error: %v", err)
}
if res.Error != "" {
t.Fatalf("unexpected tool error: %s", res.Error)
}
if res.Output != "hello world" {
t.Errorf("got Output=%q, want %q", res.Output, "hello world")
}
}
func TestTaskTool_SubagentAbortReturnsErrorResult(t *testing.T) {
runner := &stubRunner{events: []AgentEventLike{
{Text: "partial..."},
{Aborted: true},
}}
factory := SubagentFactory(func(_ context.Context, _ string, _ int) (SubagentRunner, error) {
return runner, nil
})
tt := NewTaskTool(factory, 0, map[string]string{"r": "desc"})
res, _ := tt.Execute(context.Background(), json.RawMessage(`{"agent_id":"r","prompt":"go"}`))
if res.Error == "" || !strings.Contains(res.Error, "abort") {
t.Errorf("expected abort error, got: %q", res.Error)
}
}
func TestTaskTool_FactoryDepthErrorPassesThrough(t *testing.T) {
factory := SubagentFactory(func(_ context.Context, _ string, _ int) (SubagentRunner, error) {
return nil, errors.New("subagent depth limit 3 reached")
})
tt := NewTaskTool(factory, 3, map[string]string{"r": "desc"})
res, _ := tt.Execute(context.Background(), json.RawMessage(`{"agent_id":"r","prompt":"go"}`))
if res.Error == "" || !strings.Contains(res.Error, "depth limit") {
t.Errorf("expected depth-limit error, got: %q", res.Error)
}
}
func TestTaskTool_MalformedInputReturnsError(t *testing.T) {
tt := NewTaskTool(func(_ context.Context, _ string, _ int) (SubagentRunner, error) {
t.Fatal("factory should not be called for malformed input")
return nil, nil
}, 0, map[string]string{"r": "desc"})
cases := []struct {
name string
in string
}{
{"not json", `not json`},
{"missing agent_id", `{"prompt":"go"}`},
{"missing prompt", `{"agent_id":"r"}`},
{"empty fields", `{"agent_id":"","prompt":""}`},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
res, err := tt.Execute(context.Background(), json.RawMessage(c.in))
if err != nil {
t.Fatalf("unexpected Go error: %v", err)
}
if res.Error == "" {
t.Errorf("expected tool error for %s, got: %+v", c.name, res)
}
})
}
}
+315
View File
@@ -0,0 +1,315 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"unicode"
"github.com/sausheong/harness/llm"
)
// ExpandHome rewrites a leading "~" or "~/" in p to the user's home directory.
// Other tildes (mid-path, "~user/...") are left alone — Felix never escalates
// privileges, so cross-user tilde expansion would silently fail anyway.
//
// The shell ($BASH/zsh) does this expansion before exec, which is why the
// bash tool works without it. read/write/edit_file call os.Open directly so
// they need to handle "~/" themselves.
func ExpandHome(p string) string {
if p == "~" {
if home, err := os.UserHomeDir(); err == nil {
return home
}
return p
}
if strings.HasPrefix(p, "~/") {
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, p[2:])
}
}
return p
}
// ResolveExistingPath returns a path that actually exists on disk, recovering
// from Unicode-whitespace mismatches between what the LLM supplies and what
// the filesystem holds. Resolution order:
// 1. The path as given.
// 2. The Unicode-sanitized variant (NBSP / narrow-NBSP / ideographic /
// en/em/figure-space → ASCII space; zero-width chars stripped).
// 3. The parent directory is scanned and an entry whose own sanitized name
// equals the sanitized basename of the requested path is used — but only
// if the match is unambiguous.
//
// If nothing resolves, p is returned so the caller's error message reflects
// what the LLM actually supplied. Never used for write paths — writing to a
// "resolved" path could create files in unintended locations.
func ResolveExistingPath(p string) string {
if _, err := os.Stat(p); err == nil {
return p
}
if alt := SanitizeLLMText(p); alt != p {
if _, err := os.Stat(alt); err == nil {
return alt
}
}
dir, base := filepath.Split(p)
if dir == "" {
dir = "."
}
entries, err := os.ReadDir(dir)
if err != nil {
return p
}
target := SanitizeLLMText(base)
var matches []string
for _, e := range entries {
if SanitizeLLMText(e.Name()) == target {
matches = append(matches, e.Name())
}
}
if len(matches) == 1 {
return filepath.Join(dir, matches[0])
}
return p
}
// ResolveExistingPathStrict is like ResolveExistingPath but the dir-scan
// fallback only fires when the matched on-disk entry actually contains a
// non-ASCII whitespace character. Used by the bash tool, where freeform
// commands include both read-paths (which we want to recover) and create-
// paths like `mkdir /tmp/newdir` (which must NOT be silently substituted
// with a similarly-named pre-existing entry).
func ResolveExistingPathStrict(p string) string {
if _, err := os.Stat(p); err == nil {
return p
}
if alt := SanitizeLLMText(p); alt != p {
if _, err := os.Stat(alt); err == nil {
return alt
}
}
dir, base := filepath.Split(p)
if dir == "" {
dir = "."
}
entries, err := os.ReadDir(dir)
if err != nil {
return p
}
target := SanitizeLLMText(base)
var matches []string
for _, e := range entries {
if SanitizeLLMText(e.Name()) == target && HasUnicodeWhitespace(e.Name()) {
matches = append(matches, e.Name())
}
}
if len(matches) == 1 {
return filepath.Join(dir, matches[0])
}
return p
}
// HasUnicodeWhitespace reports whether s contains any of the whitespace or
// invisible characters that SanitizeLLMText normalizes away.
func HasUnicodeWhitespace(s string) bool {
for _, r := range s {
switch r {
case '\u200B', '\u200C', '\u200D', '\u2060', '\uFEFF', '\u2028', '\u2029':
return true
}
if r != ' ' && r != '\t' && r != '\n' && r != '\r' && unicode.IsSpace(r) {
return true
}
}
return false
}
// SanitizeLLMText normalizes Unicode whitespace lookalikes that small or
// quantized LLMs sometimes emit in place of ASCII space and newline, and
// strips zero-width characters that have no shell or filesystem meaning.
// Used as a fallback by ResolveExistingPath, not applied eagerly to LLM
// input (eager sanitization breaks the case where a file genuinely
// contains NBSP in its name).
func SanitizeLLMText(s string) string {
var b strings.Builder
b.Grow(len(s))
for _, r := range s {
switch r {
case '\u200B', '\u200C', '\u200D', '\u2060', '\uFEFF':
continue // zero-width / BOM: drop
case '\u2028', '\u2029':
b.WriteByte('\n') // line / paragraph separator → newline
default:
if r != ' ' && r != '\t' && r != '\n' && r != '\r' && unicode.IsSpace(r) {
b.WriteByte(' ') // any other Unicode whitespace → ASCII space
continue
}
b.WriteRune(r)
}
}
return b.String()
}
// Tool is the interface that all Felix tools must implement.
type Tool interface {
Name() string
Description() string
Parameters() json.RawMessage // JSON Schema
Execute(ctx context.Context, input json.RawMessage) (ToolResult, error)
// IsConcurrencySafe reports whether this tool can be invoked in parallel
// with other concurrency-safe tools in the same dispatch batch. Pure-read
// tools should return true; anything that mutates state or has ordering
// sensitivity should return false. The input parameter is plumbed for
// future input-aware classifiers (e.g., bash subcommand-specific safety);
// current impls may ignore it. Implementations MUST NOT panic on weird
// input — the partitioner treats panics as unsafe via recover().
IsConcurrencySafe(input json.RawMessage) bool
}
// ToolResult holds the output of a tool execution.
type ToolResult struct {
Output string `json:"output"`
Error string `json:"error,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Images []llm.ImageContent `json:"-"` // image attachments (not JSON-serialized)
}
// Executor is the interface used by agent runtime for tool operations.
// Implemented by Registry.
type Executor interface {
Execute(ctx context.Context, name string, input json.RawMessage) (ToolResult, error)
ToolDefs() []llm.ToolDef
Names() []string
Get(name string) (Tool, bool)
}
// Registry manages a collection of available tools.
type Registry struct {
mu sync.RWMutex
tools map[string]Tool
}
// NewRegistry creates a new tool registry.
func NewRegistry() *Registry {
return &Registry{
tools: make(map[string]Tool),
}
}
// Register adds a tool to the registry.
func (r *Registry) Register(t Tool) {
r.mu.Lock()
defer r.mu.Unlock()
r.tools[t.Name()] = t
}
// Get returns a tool by name.
func (r *Registry) Get(name string) (Tool, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
t, ok := r.tools[name]
return t, ok
}
// Execute runs a tool by name with the given input.
func (r *Registry) Execute(ctx context.Context, name string, input json.RawMessage) (ToolResult, error) {
t, ok := r.Get(name)
if !ok {
return ToolResult{}, fmt.Errorf("unknown tool: %q", name)
}
return t.Execute(ctx, input)
}
// ToolDefs returns the tool definitions for the LLM API.
// Output is sorted by tool name so the LLM-request prefix is stable across
// turns — required for prompt-cache hits and for compaction-summary
// reproducibility. Map iteration in Go is randomized; without sorting,
// every turn would invalidate the cache and a single tool reordering
// could change a generated summary's content.
func (r *Registry) ToolDefs() []llm.ToolDef {
r.mu.RLock()
defer r.mu.RUnlock()
names := make([]string, 0, len(r.tools))
for name := range r.tools {
names = append(names, name)
}
sort.Strings(names)
defs := make([]llm.ToolDef, 0, len(names))
for _, name := range names {
t := r.tools[name]
defs = append(defs, llm.ToolDef{
Name: t.Name(),
Description: t.Description(),
Parameters: t.Parameters(),
})
}
return defs
}
// Names returns the names of all registered tools, sorted alphabetically.
// See ToolDefs() for why ordering matters.
func (r *Registry) Names() []string {
r.mu.RLock()
defer r.mu.RUnlock()
names := make([]string, 0, len(r.tools))
for name := range r.tools {
names = append(names, name)
}
sort.Strings(names)
return names
}
// ValidatePathInWorkDir ensures that the resolved path is within the workspace.
// It resolves symlinks and normalizes the path to prevent traversal attacks.
// Exported for the concrete-tool packages (file, bash, etc.) that share
// this workspace-clamp invariant.
func ValidatePathInWorkDir(path, workDir string) error {
if workDir == "" {
return nil
}
absWork, err := filepath.Abs(workDir)
if err != nil {
return fmt.Errorf("invalid workspace: %w", err)
}
absPath, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}
// Resolve symlinks to prevent symlink-based traversal
realWork, err := filepath.EvalSymlinks(absWork)
if err != nil {
realWork = absWork // workspace might not exist yet
}
// For the target path, resolve the parent directory (file may not exist yet)
parentDir := filepath.Dir(absPath)
realParent, err := filepath.EvalSymlinks(parentDir)
if err != nil {
// Parent doesn't exist — use the unresolved absolute path
realParent = parentDir
}
realPath := filepath.Join(realParent, filepath.Base(absPath))
if !strings.HasPrefix(realPath, realWork+string(filepath.Separator)) && realPath != realWork {
return fmt.Errorf("path %q is outside workspace %q", path, workDir)
}
return nil
}
// RegisterCron registers the cron tool with the given scheduler. agentID is
// baked into the tool so jobs the agent schedules later run as the same
// agent that scheduled them.
func RegisterCron(reg *Registry, agentID string, scheduler JobScheduler) {
reg.Register(&CronTool{AgentID: agentID, Scheduler: scheduler})
}
+59
View File
@@ -0,0 +1,59 @@
package tool
import (
"context"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
// stubTool is a minimal Tool implementation for ordering tests.
type stubTool struct {
name string
}
func (s *stubTool) Name() string { return s.name }
func (s *stubTool) Description() string { return s.name + " description" }
func (s *stubTool) Parameters() json.RawMessage { return json.RawMessage(`{}`) }
func (s *stubTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
func (s *stubTool) Execute(ctx context.Context, in json.RawMessage) (ToolResult, error) {
return ToolResult{}, nil
}
// TestToolDefsAreDeterministic guards against map-iteration cache breakage.
// Tool definitions feed directly into the LLM prefix; nondeterministic order
// invalidates the prompt cache on every turn — both a 10× cost regression
// and a real correctness issue when summaries depend on stable history.
func TestToolDefsAreDeterministic(t *testing.T) {
reg := NewRegistry()
for _, name := range []string{"zebra", "alpha", "mango", "banana", "kiwi"} {
reg.Register(&stubTool{name: name})
}
first := reg.ToolDefs()
for i := range 50 {
got := reg.ToolDefs()
assert.Equal(t, len(first), len(got), "length must be stable")
for j := range first {
assert.Equal(t, first[j].Name, got[j].Name,
"position %d must be stable across calls (iteration %d)", j, i)
}
}
for i := 1; i < len(first); i++ {
assert.LessOrEqual(t, first[i-1].Name, first[i].Name,
"ToolDefs must return tools sorted by name")
}
}
func TestNamesAreDeterministic(t *testing.T) {
reg := NewRegistry()
for _, name := range []string{"zebra", "alpha", "mango"} {
reg.Register(&stubTool{name: name})
}
got := reg.Names()
assert.Equal(t, []string{"alpha", "mango", "zebra"}, got,
"Names() must return tools sorted by name")
}