feat: extract agent execution boundary

This commit is contained in:
sam committed 2026-07-21 22:16:50 +10:00
1 parent 1d995c587d
commit a8d005a6f6
14 files changed
+822 -173

No files matched your search

+183
View File
@@ -0,0 +1,183 @@
package agentexec
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"path/filepath"
"strings"
"github.com/samcharles93/ai-sdk/agentloop"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/ai-sdk/runtime"
)
// Runner executes one autonomous stage against an already prepared workspace.
type Runner interface {
Run(ctx context.Context, workspace string, req Request) (Result, error)
}
type loopFunc func(context.Context, agentloop.Config) (agentloop.Result, error)
// InProcessRunner preserves the current execution behavior behind the v1
// agent protocol. It is replaced by a subprocess or container runner without
// changing workflow orchestration.
type InProcessRunner struct {
runtime *runtime.Runtime
log *slog.Logger
run loopFunc
}
func NewInProcessRunner(rt *runtime.Runtime, log *slog.Logger) *InProcessRunner {
return &InProcessRunner{runtime: rt, log: log, run: agentloop.Run}
}
func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request) (Result, error) {
if err := req.Validate(); err != nil {
return Result{}, err
}
if r.runtime == nil {
return Result{}, fmt.Errorf("agent runtime is not configured")
}
if r.run == nil {
return Result{}, fmt.Errorf("agent loop is not configured")
}
notes := &memoryNotes{initial: req.Notes}
captures := make(map[string][]json.RawMessage)
res, err := r.run(ctx, agentloop.Config{
Runtime: r.runtime,
ModelRef: req.Model,
WorkDir: workspace,
Mission: req.Mission,
ExtraRules: req.ExtraRules,
Notes: notes,
Gate: toAgentGate(req.Gate),
Preflight: toAgentCommands(req.Preflight),
Budget: agentloop.Budget(req.Budget),
ReadOnly: req.ReadOnly,
ProtectPaths: protectionMatcher(req.Protection, req.ReadOnly),
Extra: captureToolSet(req.CaptureTools, captures),
Logger: r.logger(req),
})
result := Result{
Version: ProtocolVersion,
TaskID: req.TaskID,
Attempt: req.Attempt,
Stage: req.Stage,
Status: string(res.Status),
StopReason: res.StopReason,
Changes: res.Changes,
Iterations: res.Iterations,
TokensUsed: res.TokensUsed,
Summary: res.Summary,
Detail: res.Detail,
AppendedNotes: notes.appended,
Captures: captures,
}
if cause := context.Cause(ctx); cause != nil {
return result, cause
}
return result, err
}
func (r *InProcessRunner) logger(req Request) *slog.Logger {
if r.log == nil {
return slog.New(slog.DiscardHandler)
}
return r.log.With("task", req.TaskID, "attempt", req.Attempt, "stage", req.Stage, "model", req.Model)
}
func toAgentGate(g Gate) agentloop.GateConfig {
return agentloop.GateConfig{
Commands: toAgentCommands(g.Commands),
MaxConsecutiveFailures: g.MaxConsecutiveFailures,
}
}
func toAgentCommands(commands []Command) []agentloop.GateCommand {
out := make([]agentloop.GateCommand, 0, len(commands))
for _, command := range commands {
out = append(out, agentloop.GateCommand{
Name: command.Name, Argv: command.Argv, ExpectFailure: command.ExpectFailure,
})
}
return out
}
func protectionMatcher(p Protection, readOnly bool) func(string) bool {
if readOnly || len(p.Suffixes)+len(p.Globs) == 0 {
return nil
}
return func(path string) bool {
for _, suffix := range p.Suffixes {
if strings.HasSuffix(path, suffix) {
return true
}
}
for _, glob := range p.Globs {
matchPath := path
if !strings.ContainsAny(glob, `/\`) {
matchPath = filepath.Base(path)
}
if matched, err := filepath.Match(glob, matchPath); err == nil && matched {
return true
}
}
return false
}
}
func captureToolSet(specs []CaptureTool, captures map[string][]json.RawMessage) core.ToolSet {
tools := make(core.ToolSet, len(specs))
for _, spec := range specs {
spec := spec
tools[spec.Name] = core.NewTool(spec.Name, spec.Description, spec.Parameters,
func(_ context.Context, input string) (string, error) {
if spec.MaxCalls > 0 && len(captures[spec.Name]) >= spec.MaxCalls {
return fmt.Sprintf("%s rejected: maximum call count is %d", spec.Name, spec.MaxCalls), nil
}
value := json.RawMessage(input)
if !json.Valid(value) {
return spec.Name + " rejected: arguments are not valid JSON", nil
}
var object map[string]json.RawMessage
if err := json.Unmarshal(value, &object); err != nil {
return spec.Name + " rejected: arguments must be a JSON object", nil
}
for _, field := range spec.RequiredFields {
if _, ok := object[field]; !ok {
return fmt.Sprintf("%s rejected: %s is required", spec.Name, field), nil
}
}
for _, field := range spec.NonEmptyStrings {
var text string
if raw, ok := object[field]; !ok || json.Unmarshal(raw, &text) != nil || strings.TrimSpace(text) == "" {
return fmt.Sprintf("%s rejected: %s must be a non-empty string", spec.Name, field), nil
}
}
for _, field := range spec.BooleanFields {
var value bool
if raw, ok := object[field]; !ok || json.Unmarshal(raw, &value) != nil {
return fmt.Sprintf("%s rejected: %s must be a boolean", spec.Name, field), nil
}
}
captures[spec.Name] = append(captures[spec.Name], append(json.RawMessage(nil), value...))
return spec.Name + " recorded", nil
})
}
return tools
}
type memoryNotes struct {
initial string
appended []string
}
func (n *memoryNotes) Load(context.Context) (string, error) { return n.initial, nil }
func (n *memoryNotes) Append(_ context.Context, entry string) error {
n.appended = append(n.appended, entry)
return nil
}
+112
View File
@@ -0,0 +1,112 @@
package agentexec
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/samcharles93/ai-sdk/agentloop"
"github.com/samcharles93/ai-sdk/runtime"
)
func TestInProcessRunnerMapsRequestAndCapturesOutput(t *testing.T) {
runner := &InProcessRunner{
runtime: runtime.NewRuntime(runtime.Config{}),
run: func(ctx context.Context, cfg agentloop.Config) (agentloop.Result, error) {
if cfg.WorkDir != "/workspace" || cfg.ModelRef != "provider/model" || cfg.Mission != "mission" {
t.Fatalf("unexpected config: workdir=%q model=%q mission=%q", cfg.WorkDir, cfg.ModelRef, cfg.Mission)
}
if cfg.ProtectPaths == nil || !cfg.ProtectPaths("nested/file_test.go") || !cfg.ProtectPaths("view_templ.go") {
t.Fatal("declarative path protection was not applied")
}
if err := cfg.Notes.Append(ctx, "verified note"); err != nil {
t.Fatal(err)
}
if _, err := cfg.Extra["decide"].Execute(ctx, `{"fit":true}`); err != nil {
t.Fatal(err)
}
return agentloop.Result{Status: agentloop.StatusPassed, Summary: "done", TokensUsed: 10}, nil
},
}
req := Request{
Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "assess", Model: "provider/model", Mission: "mission",
Protection: Protection{Suffixes: []string{"_templ.go"}, Globs: []string{"*_test.go"}},
CaptureTools: []CaptureTool{{Name: "decide", Parameters: json.RawMessage(`{"type":"object"}`), MaxCalls: 1}},
}
got, err := runner.Run(context.Background(), "/workspace", req)
if err != nil {
t.Fatal(err)
}
if got.Status != StatusPassed || got.Summary != "done" || got.TokensUsed != 10 {
t.Fatalf("unexpected result: %#v", got)
}
if len(got.AppendedNotes) != 1 || got.AppendedNotes[0] != "verified note" {
t.Fatalf("appended notes = %v", got.AppendedNotes)
}
if len(got.Captures["decide"]) != 1 || string(got.Captures["decide"][0]) != `{"fit":true}` {
t.Fatalf("captures = %v", got.Captures)
}
}
func TestProtectionMatcherAppliesBasenameAndPathGlobs(t *testing.T) {
match := protectionMatcher(Protection{Globs: []string{"*_test.go", "tests/*.rs"}}, false)
tests := []struct {
path string
want bool
}{
{path: "main_test.go", want: true},
{path: "internal/foo/bar_test.go", want: true},
{path: "tests/widget.rs", want: true},
{path: "src/widget.rs", want: false},
}
for _, tt := range tests {
if got := match(tt.path); got != tt.want {
t.Errorf("match(%q) = %v, want %v", tt.path, got, tt.want)
}
}
}
func TestCaptureToolRejectsInvalidDataBeforeRecording(t *testing.T) {
captures := make(map[string][]json.RawMessage)
tool := captureToolSet([]CaptureTool{{
Name: "decide", RequiredFields: []string{"fit", "reasons"}, NonEmptyStrings: []string{"reasons"},
BooleanFields: []string{"fit"},
}}, captures)["decide"]
output, err := tool.Execute(context.Background(), `{"fit":true,"reasons":""}`)
if err != nil {
t.Fatal(err)
}
if len(captures["decide"]) != 0 || output != "decide rejected: reasons must be a non-empty string" {
t.Fatalf("invalid capture output=%q captures=%v", output, captures)
}
}
func TestCaptureToolRejectsWrongFieldTypeBeforeRecording(t *testing.T) {
captures := make(map[string][]json.RawMessage)
tool := captureToolSet([]CaptureTool{{Name: "decide", BooleanFields: []string{"fit"}}}, captures)["decide"]
output, err := tool.Execute(context.Background(), `{"fit":"true"}`)
if err != nil {
t.Fatal(err)
}
if len(captures["decide"]) != 0 || output != "decide rejected: fit must be a boolean" {
t.Fatalf("invalid capture output=%q captures=%v", output, captures)
}
}
func TestInProcessRunnerPreservesCallerCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
runner := &InProcessRunner{
runtime: runtime.NewRuntime(runtime.Config{}),
run: func(context.Context, agentloop.Config) (agentloop.Result, error) {
return agentloop.Result{Status: agentloop.StatusParked, StopReason: agentloop.StopTimedOut}, nil
},
}
_, err := runner.Run(ctx, "/workspace", Request{
Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "build", Model: "provider/model", Mission: "mission",
})
if !errors.Is(err, context.Canceled) {
t.Fatalf("Run error = %v, want context.Canceled", err)
}
}
+127
View File
@@ -0,0 +1,127 @@
// Package agentexec defines the unprivileged agent execution boundary.
// Workflow orchestration and external side effects remain daemon-owned.
package agentexec
import (
"encoding/json"
"fmt"
"time"
)
const ProtocolVersion = 1
const StatusPassed = "passed"
// Command is one executable gate or preflight command.
type Command struct {
Name string `json:"name"`
Argv []string `json:"argv"`
ExpectFailure bool `json:"expect_failure,omitempty"`
}
// Gate is the quality gate an agent must satisfy.
type Gate struct {
Commands []Command `json:"commands,omitempty"`
MaxConsecutiveFailures int `json:"max_consecutive_failures,omitempty"`
}
// Budget bounds one autonomous execution.
type Budget struct {
MaxSteps int `json:"max_steps,omitempty"`
MaxTokens int `json:"max_tokens,omitempty"`
WallClock time.Duration `json:"wall_clock,omitempty"`
}
// Protection describes paths the agent may read but not mutate.
type Protection struct {
Suffixes []string `json:"suffixes,omitempty"`
Globs []string `json:"globs,omitempty"`
}
// CaptureTool declares a structured-output tool whose calls are returned
// to the daemon as data. It cannot call back into daemon state.
type CaptureTool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters json.RawMessage `json:"parameters,omitempty"`
RequiredFields []string `json:"required_fields,omitempty"`
NonEmptyStrings []string `json:"non_empty_strings,omitempty"`
BooleanFields []string `json:"boolean_fields,omitempty"`
MaxCalls int `json:"max_calls,omitempty"`
}
// Request is the complete, serializable input for one agent stage. The
// workspace path is supplied separately by Runner so a container runner can
// map a host path to a fixed path without exposing host layout in the wire
// protocol.
type Request struct {
Version int `json:"version"`
TaskID int64 `json:"task_id"`
Attempt int `json:"attempt"`
Stage string `json:"stage"`
Model string `json:"model"`
Mission string `json:"mission"`
ExtraRules string `json:"extra_rules,omitempty"`
ReadOnly bool `json:"read_only,omitempty"`
Budget Budget `json:"budget"`
Gate Gate `json:"gate"`
Preflight []Command `json:"preflight,omitempty"`
Protection Protection `json:"protection"`
Notes string `json:"notes,omitempty"`
CaptureTools []CaptureTool `json:"capture_tools,omitempty"`
}
// Validate rejects requests that this runner cannot safely interpret.
func (r Request) Validate() error {
if r.Version != ProtocolVersion {
return fmt.Errorf("agent protocol version %d is unsupported (want %d)", r.Version, ProtocolVersion)
}
if r.TaskID <= 0 {
return fmt.Errorf("agent request task_id must be positive")
}
if r.Attempt <= 0 {
return fmt.Errorf("agent request attempt must be positive")
}
if r.Stage == "" {
return fmt.Errorf("agent request stage is required")
}
if r.Model == "" {
return fmt.Errorf("agent request model is required")
}
return nil
}
// Result is the serializable outcome of one agent stage.
type Result struct {
Version int `json:"version"`
TaskID int64 `json:"task_id"`
Attempt int `json:"attempt"`
Stage string `json:"stage"`
Status string `json:"status"`
StopReason string `json:"stop_reason,omitempty"`
Changes []string `json:"changes,omitempty"`
Iterations int `json:"iterations,omitempty"`
TokensUsed int `json:"tokens_used,omitempty"`
Summary string `json:"summary,omitempty"`
Detail string `json:"detail,omitempty"`
AppendedNotes []string `json:"appended_notes,omitempty"`
Captures map[string][]json.RawMessage `json:"captures,omitempty"`
}
// ValidateFor rejects incompatible or misrouted results before the daemon
// applies them to task state.
func (r Result) ValidateFor(req Request) error {
if r.Version != ProtocolVersion {
return fmt.Errorf("agent result protocol version %d is unsupported (want %d)", r.Version, ProtocolVersion)
}
if r.TaskID != req.TaskID || r.Attempt != req.Attempt || r.Stage != req.Stage {
return fmt.Errorf(
"agent result identity %d/%d/%s does not match request %d/%d/%s",
r.TaskID, r.Attempt, r.Stage, req.TaskID, req.Attempt, req.Stage,
)
}
if r.Status == "" {
return fmt.Errorf("agent result status is required")
}
return nil
}
+46
View File
@@ -0,0 +1,46 @@
package agentexec
import (
"encoding/json"
"reflect"
"testing"
"time"
)
func TestProtocolRoundTrip(t *testing.T) {
want := Request{
Version: ProtocolVersion, TaskID: 42, Attempt: 3, Stage: "fix", Model: "openai/gpt-5",
Mission: "fix it", Budget: Budget{MaxSteps: 12, MaxTokens: 4000, WallClock: 2 * time.Minute},
Gate: Gate{Commands: []Command{{Name: "go", Argv: []string{"go", "test", "./..."}}}, MaxConsecutiveFailures: 2},
Protection: Protection{Suffixes: []string{"_templ.go"}, Globs: []string{"*_test.go"}},
CaptureTools: []CaptureTool{{Name: "decide", Parameters: json.RawMessage(`{"type":"object"}`), MaxCalls: 1}},
}
b, err := json.Marshal(want)
if err != nil {
t.Fatal(err)
}
var got Request
if err := json.Unmarshal(b, &got); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("round trip mismatch\ngot: %#v\nwant: %#v", got, want)
}
}
func TestRequestRejectsUnknownProtocol(t *testing.T) {
req := Request{Version: ProtocolVersion + 1, TaskID: 1, Stage: "plan", Model: "provider/model"}
if err := req.Validate(); err == nil {
t.Fatal("Validate accepted an unsupported protocol version")
}
}
func TestResultRejectsMismatchedIdentity(t *testing.T) {
req := Request{Version: ProtocolVersion, TaskID: 1, Attempt: 2, Stage: "build", Model: "provider/model"}
result := Result{
Version: ProtocolVersion, TaskID: 1, Attempt: 3, Stage: "build", Status: StatusPassed,
}
if err := result.ValidateFor(req); err == nil {
t.Fatal("ValidateFor accepted a result from another attempt")
}
}