refactor(agentexec): remove legacy execution paths
Autonomous workflows now have exactly one production boundary: a task-scoped archie-agent receives a full-task core-NATS request and runs the worker-local stage loop. The legacy [agent] section remains decode-only for migration; it no longer selects runtime behavior.
This commit is contained in:
1 parent
cc6b093820
commit
5d00ec7b0c
65 files changed
+454
-2678
No files matched your search
@@ -0,0 +1,58 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The task-scoped archie-agent process owns the workflow and its local model
|
||||
// loop. agentexec therefore contains the worker-local stage runner, never a
|
||||
// second process boundary or a stage transport that archied can select.
|
||||
func TestPackageContainsNoLegacyExecutionModes(t *testing.T) {
|
||||
forbidden := map[string]bool{
|
||||
"InProcessRunner": true,
|
||||
"NewInProcessRunner": true,
|
||||
"SubprocessRunner": true,
|
||||
"NATSRunner": true,
|
||||
"ServeOne": true,
|
||||
"Invocation": true,
|
||||
"AgentRequestMessage": true,
|
||||
"AgentResponseEnvelope": true,
|
||||
"StageMessage": true,
|
||||
"StageConsumer": true,
|
||||
}
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fileset := token.NewFileSet()
|
||||
for _, path := range files {
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
continue
|
||||
}
|
||||
file, parseErr := parser.ParseFile(fileset, path, nil, 0)
|
||||
if parseErr != nil {
|
||||
t.Errorf("parse %s: %v", path, parseErr)
|
||||
continue
|
||||
}
|
||||
for _, declaration := range file.Decls {
|
||||
switch declaration := declaration.(type) {
|
||||
case *ast.GenDecl:
|
||||
for _, spec := range declaration.Specs {
|
||||
typeSpec, ok := spec.(*ast.TypeSpec)
|
||||
if ok && forbidden[typeSpec.Name.Name] {
|
||||
t.Errorf("%s declares legacy execution type %s", fileset.Position(typeSpec.Pos()), typeSpec.Name.Name)
|
||||
}
|
||||
}
|
||||
case *ast.FuncDecl:
|
||||
if declaration.Recv == nil && forbidden[declaration.Name.Name] {
|
||||
t.Errorf("%s declares legacy execution constructor %s", fileset.Position(declaration.Pos()), declaration.Name.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,18 +21,16 @@ import (
|
||||
|
||||
// Runner executes one autonomous stage against an already prepared workspace.
|
||||
type Runner interface {
|
||||
// report, when non-nil, is notified once per completed tool call. Only
|
||||
// a runner executing in the same process as its tools (InProcessRunner)
|
||||
// can populate it; others accept and ignore it.
|
||||
// report, when non-nil, is notified once per completed tool call.
|
||||
Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (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 {
|
||||
// LoopRunner executes one workflow stage through ai-sdk's agent loop. It is
|
||||
// worker-local: archie-agent owns the complete workflow and uses this runner
|
||||
// for each stage inside its task-scoped container.
|
||||
type LoopRunner struct {
|
||||
runtime *runtime.Runtime
|
||||
log *slog.Logger
|
||||
run loopFunc
|
||||
@@ -43,12 +41,12 @@ type InProcessRunner struct {
|
||||
Limits ToolLimits
|
||||
}
|
||||
|
||||
func NewInProcessRunner(
|
||||
func NewLoopRunner(
|
||||
rt *runtime.Runtime,
|
||||
log *slog.Logger,
|
||||
registries ...*tools.Registry,
|
||||
) *InProcessRunner {
|
||||
runner := &InProcessRunner{runtime: rt, log: log, run: agentloop.Run}
|
||||
) *LoopRunner {
|
||||
runner := &LoopRunner{runtime: rt, log: log, run: agentloop.Run}
|
||||
if len(registries) > 0 {
|
||||
runner.tools = registries[0]
|
||||
}
|
||||
@@ -67,7 +65,7 @@ func NewInProcessRunner(
|
||||
// it is not configurable.
|
||||
const workspaceToolset = "workspace"
|
||||
|
||||
func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) {
|
||||
func (r *LoopRunner) Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) {
|
||||
if err := req.Validate(); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
@@ -194,7 +192,7 @@ func pluginToolSet(req Request, workspace string, occupied ...core.ToolSet) (cor
|
||||
return set, nil
|
||||
}
|
||||
|
||||
func (r *InProcessRunner) logger(req Request) *slog.Logger {
|
||||
func (r *LoopRunner) logger(req Request) *slog.Logger {
|
||||
if r.log == nil {
|
||||
return slog.New(slog.DiscardHandler)
|
||||
}
|
||||
@@ -57,8 +57,8 @@ func TestPluginToolSetRejectsAgentLoopCollisions(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInProcessRunnerMapsRequestAndCapturesOutput(t *testing.T) {
|
||||
runner := &InProcessRunner{
|
||||
func TestLoopRunnerMapsRequestAndCapturesOutput(t *testing.T) {
|
||||
runner := &LoopRunner{
|
||||
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" {
|
||||
@@ -103,7 +103,7 @@ func TestInProcessRunnerMapsRequestAndCapturesOutput(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInProcessRunnerIncludesAvailableCentralTools(t *testing.T) {
|
||||
func TestLoopRunnerIncludesAvailableCentralTools(t *testing.T) {
|
||||
registry := tools.NewRegistry()
|
||||
if err := registry.Register(tools.ToolEntry{
|
||||
Name: "memory_search",
|
||||
@@ -113,7 +113,7 @@ func TestInProcessRunnerIncludesAvailableCentralTools(t *testing.T) {
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := &InProcessRunner{
|
||||
runner := &LoopRunner{
|
||||
runtime: runtime.NewRuntime(runtime.Config{}),
|
||||
tools: registry,
|
||||
run: func(ctx context.Context, cfg agentloop.Config) (agentloop.Result, error) {
|
||||
@@ -144,7 +144,7 @@ func TestInProcessRunnerIncludesAvailableCentralTools(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInProcessRunnerRejectsInvalidCentralToolSchemas(t *testing.T) {
|
||||
func TestLoopRunnerRejectsInvalidCentralToolSchemas(t *testing.T) {
|
||||
registry := tools.NewRegistry()
|
||||
if err := registry.Register(tools.ToolEntry{
|
||||
Name: "invalid",
|
||||
@@ -155,7 +155,7 @@ func TestInProcessRunnerRejectsInvalidCentralToolSchemas(t *testing.T) {
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := &InProcessRunner{
|
||||
runner := &LoopRunner{
|
||||
runtime: runtime.NewRuntime(runtime.Config{}),
|
||||
tools: registry,
|
||||
run: func(context.Context, agentloop.Config) (agentloop.Result, error) {
|
||||
@@ -280,10 +280,10 @@ func TestMergeToolSetsLaterWinsOnCollision(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInProcessRunnerPreservesCallerCancellation(t *testing.T) {
|
||||
func TestLoopRunnerPreservesCallerCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
runner := &InProcessRunner{
|
||||
runner := &LoopRunner{
|
||||
runtime: runtime.NewRuntime(runtime.Config{}),
|
||||
run: func(context.Context, agentloop.Config) (agentloop.Result, error) {
|
||||
return agentloop.Result{Status: agentloop.StatusParked, StopReason: agentloop.StopTimedOut}, nil
|
||||
@@ -301,8 +301,8 @@ func TestInProcessRunnerPreservesCallerCancellation(t *testing.T) {
|
||||
// tool handler discards the incoming context (the handler is declared as
|
||||
// func(_ context.Context, input string) and calls skillscript.Run without
|
||||
// forwarding ctx). Every other execution path in archie-core respects
|
||||
// context cancellation (SubprocessRunner uses exec.CommandContext,
|
||||
// InProcessRunner checks context.Cause), but a cancelled/timed-out context
|
||||
// context cancellation (LoopRunner checks context.Cause), but a
|
||||
// cancelled/timed-out context
|
||||
// has zero effect on run_go_script — a blocking script wedges the
|
||||
// goroutine permanently.
|
||||
func TestScriptToolHonorsContextCancellation(t *testing.T) {
|
||||
@@ -1,136 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/eventbus"
|
||||
)
|
||||
|
||||
// AgentRequestMessage is the NATS payload for an agent stage execution request.
|
||||
// When Workflow is set and Stages is populated, the agent runs all stages as a
|
||||
// per-task batch rather than a single stage. PRD §1.
|
||||
type AgentRequestMessage struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Stage string `json:"stage"`
|
||||
Workflow string `json:"workflow,omitempty"`
|
||||
Channel string `json:"channel,omitempty"` // "response" (default) or "system"
|
||||
Workspace string `json:"workspace"`
|
||||
Request Request `json:"request"`
|
||||
Stages []Request `json:"stages,omitempty"` // batch: all agent stages for this task
|
||||
Providers map[string]Provider `json:"providers,omitempty"`
|
||||
// MCPServers carries MCP server definitions so the agent can construct
|
||||
// transports, discover tools, and register them locally. Absent/empty
|
||||
// means no MCP servers (backward compatible).
|
||||
MCPServers []config.MCPServer `json:"mcp_servers,omitempty"`
|
||||
}
|
||||
|
||||
// AgentResponseEnvelope is the response payload published to the reply inbox.
|
||||
type AgentResponseEnvelope struct {
|
||||
Version int `json:"version"`
|
||||
Result Result `json:"result"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Channel string `json:"channel,omitempty"` // "response" (default) or "system"
|
||||
TaskCompleted bool `json:"task_completed,omitempty"` // true when all stages finished (per-task mode)
|
||||
}
|
||||
|
||||
const defaultAgentTimeout = 30 * time.Minute
|
||||
|
||||
// RequestBus is the messaging this runner needs: publish a request carrying a
|
||||
// reply address, and create the inbox that address points at.
|
||||
//
|
||||
// Declared here rather than taking eventbus.Bus because a domain defines the
|
||||
// smallest interface required to do its work -- this runner never fetches or
|
||||
// subscribes, and should not be able to.
|
||||
type RequestBus interface {
|
||||
PublishRequest(ctx context.Context, subject, replyTo string, payload []byte) error
|
||||
NewReplyInbox() (eventbus.ReplyInbox, error)
|
||||
}
|
||||
|
||||
// NATSRunner sends agent stage execution requests over the bus and waits for
|
||||
// replies on a one-shot inbox. It implements Runner.
|
||||
//
|
||||
// The name is historical: it holds no NATS type and works with any bus
|
||||
// satisfying RequestBus.
|
||||
type NATSRunner struct {
|
||||
Bus RequestBus
|
||||
Providers map[string]Provider
|
||||
MCPServers []config.MCPServer
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
// Run publishes a stage execution request to JetStream with an X-Archie-Reply
|
||||
// header, blocks on the sync inbox subscription, and returns the result.
|
||||
//
|
||||
// report is ignored: execution happens on whatever remote worker answers the
|
||||
// request, a different process with no way to call back here per tool call.
|
||||
func (r *NATSRunner) Run(ctx context.Context, workspace string, req Request, _ ToolCallReporter) (Result, error) {
|
||||
if err := req.Validate(); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
|
||||
// 1. Create reply inbox with auto-unsubscribe after one message.
|
||||
replySub, err := r.Bus.NewReplyInbox()
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("nats reply inbox: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := replySub.Close(); err != nil {
|
||||
r.Log.Warn("reply inbox close failed", "err", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// 2. Compute timeout from budget.
|
||||
timeout := defaultAgentTimeout
|
||||
if req.Budget.WallClock > 0 {
|
||||
timeout = req.Budget.WallClock
|
||||
}
|
||||
|
||||
// 3. Publish request with reply header.
|
||||
msg := AgentRequestMessage{
|
||||
TaskID: req.TaskID,
|
||||
Attempt: req.Attempt,
|
||||
Stage: req.Stage,
|
||||
Workflow: req.Workflow,
|
||||
Workspace: workspace,
|
||||
Request: req,
|
||||
Providers: r.Providers,
|
||||
MCPServers: r.MCPServers,
|
||||
}
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
|
||||
subject := SubjectForRequest(req.TaskID)
|
||||
if err := r.Bus.PublishRequest(ctx, subject, replySub.Subject(), data); err != nil {
|
||||
return Result{}, fmt.Errorf("publish agent request: %w", err)
|
||||
}
|
||||
|
||||
// 4. Wait for reply (blocking, matching SubprocessRunner.Run behaviour).
|
||||
replyCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
reply, err := replySub.Next(replyCtx)
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("agent reply: %w", err)
|
||||
}
|
||||
|
||||
// 5. Decode response.
|
||||
var envelope AgentResponseEnvelope
|
||||
if err := json.Unmarshal(reply, &envelope); err != nil {
|
||||
return Result{}, fmt.Errorf("decode agent response: %w", err)
|
||||
}
|
||||
if envelope.Error != "" {
|
||||
return envelope.Result, errors.New(envelope.Error)
|
||||
}
|
||||
if err := envelope.Result.ValidateFor(req); err != nil {
|
||||
return envelope.Result, err
|
||||
}
|
||||
return envelope.Result, nil
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/eventbus"
|
||||
arnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
)
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
type mockRunner struct{}
|
||||
|
||||
func (m *mockRunner) Run(_ context.Context, _ string, req Request, _ ToolCallReporter) (Result, error) {
|
||||
return Result{
|
||||
Version: ProtocolVersion,
|
||||
TaskID: req.TaskID,
|
||||
Attempt: req.Attempt,
|
||||
Stage: req.Stage,
|
||||
Status: StatusPassed,
|
||||
Summary: "mock:" + req.Mission,
|
||||
TokensUsed: 10,
|
||||
Iterations: 1,
|
||||
}, nil
|
||||
}
|
||||
|
||||
var mockFactory = func(providers map[string]Provider, log *slog.Logger) Runner {
|
||||
return &mockRunner{}
|
||||
}
|
||||
|
||||
// ── regression: Gap 1 -- per-task agent ──────────────────────────────
|
||||
|
||||
func TestHandleMessageReadsWorkflowField(t *testing.T) {
|
||||
// Gap 1: archie-agent is per-stage, not per-task.
|
||||
// PRD section 1: when the daemon sends a task-level message with
|
||||
// Workflow="implement" and Stages populated, the agent must run all
|
||||
// stages as a batch. Single-stage mode (Request only) is the
|
||||
// backward-compatible fallback.
|
||||
|
||||
ws := t.TempDir()
|
||||
providers := map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}}
|
||||
|
||||
// Single-stage mode: uses Request, no Workflow, no Stages.
|
||||
singleMsg := AgentRequestMessage{
|
||||
TaskID: 1,
|
||||
Attempt: 1,
|
||||
Stage: "plan",
|
||||
Workspace: ws,
|
||||
Request: Request{
|
||||
Version: ProtocolVersion, TaskID: 1, Attempt: 1,
|
||||
Stage: "plan", Model: "test/model", Mission: "single",
|
||||
Budget: Budget{MaxSteps: 1},
|
||||
},
|
||||
Providers: providers,
|
||||
}
|
||||
mockFactory := func(providers map[string]Provider, log *slog.Logger) Runner {
|
||||
return &mockRunner{}
|
||||
}
|
||||
singleResp, err := HandleMessage(context.Background(), singleMsg, slog.New(slog.DiscardHandler), mockFactory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if singleResp.TaskCompleted {
|
||||
t.Error("single-stage mode set TaskCompleted=true -- should be false")
|
||||
}
|
||||
|
||||
// Per-task mode: Workflow set, Stages populated with two stages.
|
||||
multiMsg := AgentRequestMessage{
|
||||
TaskID: 2,
|
||||
Attempt: 1,
|
||||
Stage: "plan",
|
||||
Workflow: "implement",
|
||||
Workspace: ws,
|
||||
Request: Request{
|
||||
Version: ProtocolVersion, TaskID: 2, Attempt: 1,
|
||||
Stage: "plan", Model: "test/model", Mission: "multi-1",
|
||||
Budget: Budget{MaxSteps: 1},
|
||||
},
|
||||
Stages: []Request{
|
||||
{
|
||||
Version: ProtocolVersion, TaskID: 2, Attempt: 1,
|
||||
Stage: "plan", Model: "test/model", Mission: "multi-plan",
|
||||
Budget: Budget{MaxSteps: 1},
|
||||
},
|
||||
{
|
||||
Version: ProtocolVersion, TaskID: 2, Attempt: 1,
|
||||
Stage: "build", Model: "test/model", Mission: "multi-build",
|
||||
Budget: Budget{MaxSteps: 1},
|
||||
},
|
||||
},
|
||||
Providers: providers,
|
||||
}
|
||||
multiResp, err := HandleMessage(context.Background(), multiMsg, slog.New(slog.DiscardHandler), mockFactory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !multiResp.TaskCompleted {
|
||||
t.Error("Gap 1: per-task mode did not set TaskCompleted=true. " +
|
||||
"The agent must signal task completion when all stages in a " +
|
||||
"workflow batch have been processed.")
|
||||
}
|
||||
// Batch results must aggregate from both stages.
|
||||
if multiResp.Result.TokensUsed == singleResp.Result.TokensUsed &&
|
||||
multiResp.Result.Iterations == singleResp.Result.Iterations {
|
||||
t.Error("Gap 1: per-task mode produced same token/iteration counts " +
|
||||
"as single-stage mode. Multi-stage batch must accumulate " +
|
||||
"results from all stages. See PRD section 1.")
|
||||
}
|
||||
}
|
||||
|
||||
// ── regression: Gap 3 -- response/system channel split ───────────────
|
||||
|
||||
func TestHandleMessageRoutesSystemMessagesSeparately(t *testing.T) {
|
||||
// Gap 3: no response/system channel split.
|
||||
// PRD section 2: system messages go to archie.agent.<id>.system and
|
||||
// are never forwarded to humans. Response messages go to
|
||||
// archie.agent.<id>.response for daemon review before human delivery.
|
||||
// Currently HandleMessage always returns Channel="response" -- there
|
||||
// is no code path that produces a system-channel response.
|
||||
|
||||
msg := AgentRequestMessage{
|
||||
TaskID: 1,
|
||||
Attempt: 1,
|
||||
Stage: "plan",
|
||||
Workspace: t.TempDir(),
|
||||
Request: Request{
|
||||
Version: ProtocolVersion,
|
||||
TaskID: 1,
|
||||
Attempt: 1,
|
||||
Stage: "plan",
|
||||
Model: "test/model",
|
||||
Mission: "test",
|
||||
Budget: Budget{MaxSteps: 1},
|
||||
},
|
||||
Providers: map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}},
|
||||
}
|
||||
|
||||
// Normal stage request -- should route to response channel.
|
||||
resp, err := HandleMessage(context.Background(), msg, slog.New(slog.DiscardHandler), mockFactory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Channel != "response" {
|
||||
t.Errorf("normal stage request: Channel = %q, want \"response\"", resp.Channel)
|
||||
}
|
||||
|
||||
// System message (health check, log dump request) -- should route to
|
||||
// system channel. Currently HandleMessage always returns "response".
|
||||
// The daemon sets Channel on the request to indicate message type.
|
||||
msg.Channel = "system"
|
||||
sysResp, err := HandleMessage(context.Background(), msg, slog.New(slog.DiscardHandler), mockFactory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sysResp.Channel != "system" {
|
||||
t.Error("Gap 3: HandleMessage ignores the input Channel field. " +
|
||||
"When the daemon sends a system message (Channel=\"system\"), " +
|
||||
"the response must be routed to archie.agent.<id>.system, " +
|
||||
"not to the reply inbox. Currently all responses go to the " +
|
||||
"same inbox regardless of channel. See PRD section 2.")
|
||||
}
|
||||
|
||||
// Verify the subject functions exist and are distinct.
|
||||
respSubj := SubjectForResponse(42)
|
||||
sysSubj := SubjectForSystem(42)
|
||||
if respSubj == sysSubj || respSubj == "" || sysSubj == "" {
|
||||
t.Error("Gap 3: subject functions broken -- verify SubjectForAgentResponse " +
|
||||
"and SubjectForAgentSystem return distinct, non-empty subjects.")
|
||||
}
|
||||
}
|
||||
|
||||
// ── existing tests ───────────────────────────────────────────────────
|
||||
|
||||
func startEmbeddedNATS(t *testing.T) *server.Server {
|
||||
t.Helper()
|
||||
srv := natssrv.RunRandClientPortServer()
|
||||
t.Cleanup(srv.Shutdown)
|
||||
if err := srv.EnableJetStream(&server.JetStreamConfig{StoreDir: t.TempDir()}); err != nil {
|
||||
t.Fatalf("enable jetstream: %v", err)
|
||||
}
|
||||
return srv
|
||||
}
|
||||
|
||||
func startHandler(t *testing.T, client *arnats.Client) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
|
||||
// Drain the client's own consumer rather than subscribing a second one:
|
||||
// the stream uses work-queue retention, so two consumers with
|
||||
// overlapping filter subjects conflict. This mirrors archie-agent.
|
||||
go func() {
|
||||
for ctx.Err() == nil {
|
||||
msg, err := client.Fetch(ctx)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if err := replyToStage(ctx, client, msg); err != nil {
|
||||
t.Errorf("stage handler: %v", err)
|
||||
_ = msg.Nak()
|
||||
continue
|
||||
}
|
||||
_ = msg.Ack()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// replyToStage answers one stage request with a canned passing result.
|
||||
func replyToStage(ctx context.Context, client *arnats.Client, msg eventbus.Message) error {
|
||||
var req AgentRequestMessage
|
||||
if err := json.Unmarshal(msg.Data(), &req); err != nil {
|
||||
return err
|
||||
}
|
||||
replyTo, err := msg.ReplyAddress()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := json.Marshal(AgentResponseEnvelope{
|
||||
Version: req.Request.Version,
|
||||
Result: Result{
|
||||
Version: ProtocolVersion,
|
||||
TaskID: req.TaskID,
|
||||
Attempt: req.Attempt,
|
||||
Stage: req.Stage,
|
||||
Status: StatusPassed,
|
||||
Summary: "handler-reply",
|
||||
TokensUsed: 42,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Respond(ctx, replyTo, data)
|
||||
}
|
||||
|
||||
func TestNATSRunnerRoundTrip(t *testing.T) {
|
||||
srv := startEmbeddedNATS(t)
|
||||
url := srv.ClientURL()
|
||||
|
||||
ctx := context.Background()
|
||||
client, err := arnats.Connect(ctx, arnats.Config{URL: url, Subjects: []string{workintake.SubjectTaskWildcard, SubjectAgentWildcard}, FilterSubject: SubjectAgentWildcard}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
startHandler(t, client)
|
||||
|
||||
runner := &NATSRunner{
|
||||
Bus: client,
|
||||
Providers: map[string]Provider{"openai": {Class: "openai", APIKeyEnv: "TEST_KEY"}},
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
|
||||
req := Request{
|
||||
Version: ProtocolVersion,
|
||||
TaskID: 42,
|
||||
Attempt: 1,
|
||||
Stage: "test",
|
||||
Model: "openai/gpt",
|
||||
Mission: "test mission",
|
||||
Budget: Budget{MaxSteps: 5},
|
||||
}
|
||||
|
||||
result, err := runner.Run(ctx, "/tmp/test-workspace", req, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Status != StatusPassed {
|
||||
t.Fatalf("expected passed, got %s", result.Status)
|
||||
}
|
||||
if result.Summary != "handler-reply" {
|
||||
t.Fatalf("expected 'handler-reply', got %q", result.Summary)
|
||||
}
|
||||
if result.TokensUsed != 42 {
|
||||
t.Fatalf("expected 42 tokens, got %d", result.TokensUsed)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
// Package agentexec defines the unprivileged agent execution boundary.
|
||||
// Workflow orchestration and external side effects remain daemon-owned.
|
||||
// Package agentexec defines worker-local workflow-stage execution. archie-agent
|
||||
// owns workflow orchestration; authority-bearing forge, store, and push effects
|
||||
// remain daemon-owned behind scoped RPC boundaries.
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -133,59 +132,6 @@ type Provider struct {
|
||||
BaseURL string `json:"base_url,omitempty"`
|
||||
}
|
||||
|
||||
func (p Provider) validate() error {
|
||||
if strings.TrimSpace(p.Class) == "" {
|
||||
return fmt.Errorf("provider class is required")
|
||||
}
|
||||
if p.BaseURL == "" {
|
||||
return nil
|
||||
}
|
||||
u, err := url.Parse(p.BaseURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse provider base_url: %w", err)
|
||||
}
|
||||
if u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return fmt.Errorf("provider base_url must not contain userinfo, query parameters, or a fragment")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Invocation is the single request accepted by archie-agent on stdin.
|
||||
type Invocation struct {
|
||||
Version int `json:"version"`
|
||||
Workspace string `json:"workspace"`
|
||||
Request Request `json:"request"`
|
||||
Providers map[string]Provider `json:"providers"`
|
||||
}
|
||||
|
||||
// Validate rejects invocations that cannot be executed safely.
|
||||
func (i Invocation) Validate() error {
|
||||
if i.Version != ProtocolVersion {
|
||||
return fmt.Errorf("agent invocation protocol version %d is unsupported (want %d)", i.Version, ProtocolVersion)
|
||||
}
|
||||
if i.Workspace == "" {
|
||||
return fmt.Errorf("agent invocation workspace is required")
|
||||
}
|
||||
if len(i.Providers) == 0 {
|
||||
return fmt.Errorf("agent invocation providers are required")
|
||||
}
|
||||
for name, provider := range i.Providers {
|
||||
if err := provider.validate(); err != nil {
|
||||
return fmt.Errorf("agent invocation provider %q: %w", name, err)
|
||||
}
|
||||
}
|
||||
return i.Request.Validate()
|
||||
}
|
||||
|
||||
// Response is the single envelope written by archie-agent on stdout.
|
||||
// Error carries execution errors after the worker successfully decoded the
|
||||
// invocation; process-level protocol failures use a non-zero exit status.
|
||||
type Response struct {
|
||||
Version int `json:"version"`
|
||||
Result Result `json:"result"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// ValidateFor rejects incompatible or misrouted results before the daemon
|
||||
// applies them to task state.
|
||||
func (r Result) ValidateFor(req Request) error {
|
||||
|
||||
@@ -2,8 +2,8 @@ package agentexec
|
||||
|
||||
import "github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
// NewRuntime builds the provider runtime shared by archied's in-process mode
|
||||
// and the archie-agent worker. Nil means no providers were configured.
|
||||
// NewRuntime builds a provider runtime for interactive chat or a worker-local
|
||||
// workflow stage. Nil means no providers were configured.
|
||||
func NewRuntime(providers map[string]Provider) *runtime.Runtime {
|
||||
if len(providers) == 0 {
|
||||
return nil
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// captureRunner records the Request it receives for test assertions.
|
||||
type captureRunner struct {
|
||||
callback func(Request)
|
||||
}
|
||||
|
||||
func (c *captureRunner) Run(_ context.Context, _ string, req Request, _ ToolCallReporter) (Result, error) {
|
||||
c.callback(req)
|
||||
return Result{
|
||||
Version: ProtocolVersion,
|
||||
TaskID: req.TaskID,
|
||||
Attempt: req.Attempt,
|
||||
Stage: req.Stage,
|
||||
Status: StatusPassed,
|
||||
Summary: "done",
|
||||
TokensUsed: 1,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ── regression: HandleMessage must not duplicate skill body ─────────
|
||||
|
||||
func TestHandleMessageDoesNotDuplicateSkillBody(t *testing.T) {
|
||||
// Regression for issue #65: the daemon already prepends the skill
|
||||
// body to every mission via missionWithSkill() before the Request
|
||||
// reaches HandleMessage. HandleMessage must pass the mission
|
||||
// through unchanged -- a second prepend here would duplicate the
|
||||
// skill body in the agent's context window.
|
||||
|
||||
dir := t.TempDir()
|
||||
skillsDir := filepath.Join(dir, ".agents", "skills", "archie-wf-tdd")
|
||||
if err := os.MkdirAll(skillsDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(skillsDir, "SKILL.md"), []byte(`---
|
||||
name: archie-wf-tdd
|
||||
description: TDD bugfix workflow
|
||||
version: 1.0.0
|
||||
metadata:
|
||||
archie:
|
||||
workflow: tdd
|
||||
---
|
||||
Analyse the bug. Write repro tests. Fix.
|
||||
`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Mission already includes the daemon-side prepend (as produced by
|
||||
// missionWithSkill in internal/workflow/agent.go).
|
||||
alreadyPrepended := "Follow these project-specific guidelines:\n\n" +
|
||||
"Analyse the bug. Write repro tests. Fix.\n\n---\n\n" +
|
||||
"Analyse this bug"
|
||||
|
||||
var capturedMission string
|
||||
captureFactory := func(providers map[string]Provider, log *slog.Logger) Runner {
|
||||
return &captureRunner{callback: func(req Request) {
|
||||
capturedMission = req.Mission
|
||||
}}
|
||||
}
|
||||
|
||||
msg := AgentRequestMessage{
|
||||
TaskID: 1,
|
||||
Attempt: 1,
|
||||
Stage: "analyse",
|
||||
Workflow: "tdd",
|
||||
Workspace: dir,
|
||||
Request: Request{
|
||||
Version: ProtocolVersion, TaskID: 1, Attempt: 1,
|
||||
Stage: "analyse", Model: "test/model",
|
||||
Mission: alreadyPrepended,
|
||||
Budget: Budget{MaxSteps: 1},
|
||||
},
|
||||
Providers: map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}},
|
||||
}
|
||||
|
||||
resp, err := HandleMessage(context.Background(), msg, slog.New(slog.DiscardHandler), captureFactory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp
|
||||
|
||||
// The mission must be passed through unchanged. Any modification
|
||||
// would indicate a double-prepend bug (issue #65).
|
||||
if capturedMission != alreadyPrepended {
|
||||
t.Errorf("HandleMessage modified the mission:\n got: %q\n want: %q\n\n"+
|
||||
"The daemon already prepends the skill body via missionWithSkill(). "+
|
||||
"HandleMessage must not prepend it again -- doing so duplicates content "+
|
||||
"in the agent's context window (issue #65).",
|
||||
capturedMission, alreadyPrepended)
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import "context"
|
||||
|
||||
// StageMessage is one decoded single-stage request together with the transport
|
||||
// operations that complete its delivery. Infrastructure owns the wire payload,
|
||||
// reply inbox, and acknowledgement mechanism; the worker only sees typed data.
|
||||
type StageMessage interface {
|
||||
Request() (AgentRequestMessage, error)
|
||||
Respond(context.Context, *AgentResponseEnvelope) error
|
||||
Ack() error
|
||||
Nak() error
|
||||
LogAttributes() []any
|
||||
}
|
||||
|
||||
// StageConsumer receives decoded single-stage requests.
|
||||
type StageConsumer interface {
|
||||
FetchStage(context.Context) (StageMessage, error)
|
||||
}
|
||||
@@ -5,20 +5,14 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Agent execution subjects.
|
||||
// Agent observability subjects.
|
||||
//
|
||||
// These belong to this package because it defines what an agent request and
|
||||
// response mean. They previously sat in the NATS package, which made the
|
||||
// transport the owner of Archie's agent protocol; see
|
||||
// docs/architecture/dependencies-and-contracts.md -- message schemas and the
|
||||
// subjects addressing them stay with the domain that defines them.
|
||||
//
|
||||
// The stage travels in the payload, not the subject: one subject per task
|
||||
// carrying sequential stage messages.
|
||||
const (
|
||||
// SubjectAgentWildcard matches every agent subject.
|
||||
SubjectAgentWildcard = "archie.agent.>"
|
||||
|
||||
// SubjectSystemWildcard matches every task's system subject, for a
|
||||
// daemon subscribing to all of them at once with a single core NATS
|
||||
// subscription rather than one per running task.
|
||||
@@ -34,19 +28,6 @@ const (
|
||||
subjectEventsSuffix = ".events"
|
||||
)
|
||||
|
||||
// SubjectForRequest returns the subject carrying stage execution requests for
|
||||
// a task.
|
||||
func SubjectForRequest(taskID int64) string {
|
||||
return subjectForTask(taskID, "request")
|
||||
}
|
||||
|
||||
// SubjectForResponse returns the subject for agent output destined for human
|
||||
// channels. The daemon reviews these before forwarding to issue comments,
|
||||
// labels, or pull requests.
|
||||
func SubjectForResponse(taskID int64) string {
|
||||
return subjectForTask(taskID, "response")
|
||||
}
|
||||
|
||||
// SubjectForSystem returns the subject for internal agent messages such as
|
||||
// log dumps, health, and PII warnings. The daemon reads these for
|
||||
// observability and never forwards them.
|
||||
|
||||
@@ -1,170 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const maxDiagnosticBytes = 64 << 10
|
||||
|
||||
// SubprocessRunner executes each agent stage in a fresh archie-agent process.
|
||||
type SubprocessRunner struct {
|
||||
Command string
|
||||
Args []string
|
||||
// Environ is the daemon environment to select from. AdditionalEnv names
|
||||
// operator-approved compatibility variables; the requested provider's key
|
||||
// variable is added automatically for that invocation only.
|
||||
Environ []string
|
||||
AdditionalEnv []string
|
||||
Diagnostics io.Writer
|
||||
Providers map[string]Provider
|
||||
}
|
||||
|
||||
// Run ignores report: the subprocess executes tools in its own process, so
|
||||
// there is nothing here to observe a call as it happens.
|
||||
func (r *SubprocessRunner) Run(ctx context.Context, workspace string, req Request, _ ToolCallReporter) (Result, error) {
|
||||
providerName, _, ok := strings.Cut(req.Model, "/")
|
||||
if !ok || providerName == "" {
|
||||
return Result{}, fmt.Errorf("agent model %q must be provider/model", req.Model)
|
||||
}
|
||||
provider, ok := r.Providers[providerName]
|
||||
if !ok {
|
||||
return Result{}, fmt.Errorf("agent model provider %q is not configured", providerName)
|
||||
}
|
||||
providers := map[string]Provider{providerName: provider}
|
||||
invocation := Invocation{Version: ProtocolVersion, Workspace: workspace, Request: req, Providers: providers}
|
||||
if err := invocation.Validate(); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if strings.TrimSpace(r.Command) == "" {
|
||||
return Result{}, fmt.Errorf("archie-agent command is required")
|
||||
}
|
||||
payload, err := json.Marshal(invocation)
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("encode invocation: %w", err)
|
||||
}
|
||||
payload = append(payload, '\n')
|
||||
|
||||
cmd := exec.CommandContext(ctx, r.Command, r.Args...)
|
||||
configureProcessCancellation(cmd)
|
||||
cmd.Stdin = bytes.NewReader(payload)
|
||||
cmd.Env = WorkerEnvironment(r.Environ, r.AdditionalEnv, providers)
|
||||
stdout := &cappedBuffer{limit: maxProtocolBytes}
|
||||
stderr := &cappedBuffer{limit: maxDiagnosticBytes}
|
||||
cmd.Stdout = stdout
|
||||
cmd.Stderr = stderr
|
||||
if r.Diagnostics != nil {
|
||||
cmd.Stderr = io.MultiWriter(r.Diagnostics, stderr)
|
||||
}
|
||||
if err := cmd.Run(); err != nil {
|
||||
if cause := context.Cause(ctx); cause != nil {
|
||||
if diagnostic := strings.TrimSpace(stderr.String()); diagnostic != "" {
|
||||
return Result{}, fmt.Errorf("%w: archie-agent: %s", cause, diagnostic)
|
||||
}
|
||||
return Result{}, cause
|
||||
}
|
||||
return Result{}, fmt.Errorf("archie-agent process: %w: %s", err, strings.TrimSpace(stderr.String()))
|
||||
}
|
||||
if stdout.truncated {
|
||||
return Result{}, fmt.Errorf("archie-agent response exceeds %d bytes", maxProtocolBytes)
|
||||
}
|
||||
return decodeSubprocessResponse(bytes.NewReader(stdout.Bytes()), stderr.String(), req)
|
||||
}
|
||||
|
||||
// decodeSubprocessResponse reads one Response from r and validates it
|
||||
// against req, returning the Result or an error.
|
||||
func decodeSubprocessResponse(r io.Reader, stderrText string, req Request) (Result, error) {
|
||||
var response Response
|
||||
if err := decodeOne(r, &response); err != nil {
|
||||
return Result{}, fmt.Errorf("decode archie-agent response: %w: %s", err, strings.TrimSpace(stderrText))
|
||||
}
|
||||
if response.Version != ProtocolVersion {
|
||||
return Result{}, fmt.Errorf("archie-agent response protocol version %d is unsupported", response.Version)
|
||||
}
|
||||
if response.Result.Version != 0 {
|
||||
if err := response.Result.ValidateFor(req); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
}
|
||||
if response.Error != "" {
|
||||
return response.Result, errors.New(response.Error)
|
||||
}
|
||||
if err := response.Result.ValidateFor(req); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
return response.Result, nil
|
||||
}
|
||||
|
||||
type cappedBuffer struct {
|
||||
bytes.Buffer
|
||||
limit int
|
||||
truncated bool
|
||||
}
|
||||
|
||||
func (b *cappedBuffer) Write(p []byte) (int, error) {
|
||||
original := len(p)
|
||||
remaining := b.limit - b.Len()
|
||||
if remaining <= 0 {
|
||||
b.truncated = true
|
||||
return original, nil
|
||||
}
|
||||
if len(p) > remaining {
|
||||
_, _ = b.Buffer.Write(p[:remaining])
|
||||
b.truncated = true
|
||||
return original, nil
|
||||
}
|
||||
_, _ = b.Buffer.Write(p)
|
||||
return original, nil
|
||||
}
|
||||
|
||||
// SelectEnvironment copies only named variables from environ. Later entries
|
||||
// win, matching os.Environ and exec.Cmd semantics without accidentally
|
||||
// inheriting unrelated variables. This is not an OS security boundary: a
|
||||
// same-UID subprocess may still access daemon-readable host resources.
|
||||
func SelectEnvironment(environ, names []string) []string {
|
||||
allowed := make(map[string]bool, len(names))
|
||||
for _, name := range names {
|
||||
if name != "" {
|
||||
allowed[name] = true
|
||||
}
|
||||
}
|
||||
values := make(map[string]string, len(allowed))
|
||||
for _, entry := range environ {
|
||||
name, _, ok := strings.Cut(entry, "=")
|
||||
if ok && allowed[name] {
|
||||
values[name] = entry
|
||||
}
|
||||
}
|
||||
out := make([]string, 0, len(values))
|
||||
for _, name := range names {
|
||||
if entry, ok := values[name]; ok {
|
||||
out = append(out, entry)
|
||||
delete(values, name)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DefaultEnvironmentNames are compatibility variables safe to forward by
|
||||
// default. Additional toolchain variables must be explicitly configured.
|
||||
func DefaultEnvironmentNames() []string {
|
||||
return []string{"PATH", "HOME", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "SSL_CERT_FILE", "SSL_CERT_DIR"}
|
||||
}
|
||||
|
||||
// WorkerEnvironment selects the default compatibility variables, configured
|
||||
// additions, and each provider's API-key variable. Forge credentials are not
|
||||
// forwarded unless an operator explicitly lists or reuses their variable.
|
||||
func WorkerEnvironment(environ, additional []string, providers map[string]Provider) []string {
|
||||
names := DefaultEnvironmentNames()
|
||||
names = append(names, additional...)
|
||||
for _, provider := range providers {
|
||||
names = append(names, provider.APIKeyEnv)
|
||||
}
|
||||
return SelectEnvironment(environ, names)
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
|
||||
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// configureProcessCancellation puts the worker and every command it starts in
|
||||
// a dedicated process group. CommandContext cancellation then kills the whole
|
||||
// group so toolchain grandchildren cannot continue mutating the worktree.
|
||||
func configureProcessCancellation(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
cmd.Cancel = func() error {
|
||||
if cmd.Process == nil {
|
||||
return os.ErrProcessDone
|
||||
}
|
||||
err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
if errors.Is(err, syscall.ESRCH) {
|
||||
return os.ErrProcessDone
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package agentexec
|
||||
|
||||
import "os/exec"
|
||||
|
||||
// Windows keeps exec.CommandContext's direct-process cancellation. Production
|
||||
// subprocess and container execution are currently supported on Unix hosts.
|
||||
func configureProcessCancellation(_ *exec.Cmd) {}
|
||||
@@ -1,249 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSubprocessRunnerRoundTrip(t *testing.T) {
|
||||
req := testRequest()
|
||||
result, err := helperRunner("success").Run(context.Background(), "/workspace", req, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Summary != "from child" || result.TaskID != req.TaskID || result.Attempt != req.Attempt {
|
||||
t.Fatalf("result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubprocessRunnerReturnsStampedWorkerError(t *testing.T) {
|
||||
req := testRequest()
|
||||
result, err := helperRunner("worker-error").Run(context.Background(), "/workspace", req, nil)
|
||||
if err == nil || err.Error() != "provider unavailable" {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
if result.TaskID != req.TaskID || result.Stage != req.Stage {
|
||||
t.Fatalf("partial result lost identity: %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubprocessRunnerRejectsMalformedAndOversizedOutput(t *testing.T) {
|
||||
for _, behavior := range []string{"malformed", "oversized", "multiple", "mismatched"} {
|
||||
t.Run(behavior, func(t *testing.T) {
|
||||
_, err := helperRunner(behavior).Run(context.Background(), "/workspace", testRequest(), nil)
|
||||
if err == nil {
|
||||
t.Fatal("Run succeeded")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubprocessRunnerReportsExitDiagnostics(t *testing.T) {
|
||||
_, err := helperRunner("exit").Run(context.Background(), "/workspace", testRequest(), nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "child diagnostic") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubprocessRunnerCancelsChild(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
_, err := helperRunner("hang").Run(ctx, "/workspace", testRequest(), nil)
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("error = %v, want deadline exceeded", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubprocessRunnerCancellationKillsGrandchildren(t *testing.T) {
|
||||
marker := filepath.Join(t.TempDir(), "grandchild-survived")
|
||||
runner := helperRunner("spawn-grandchild")
|
||||
runner.Environ = append(runner.Environ, "AGENT_HELPER_MARKER="+marker)
|
||||
runner.AdditionalEnv = append(runner.AdditionalEnv, "AGENT_HELPER_MARKER")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
_, err := runner.Run(ctx, "/workspace", testRequest(), nil)
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("error = %v, want deadline exceeded", err)
|
||||
}
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if _, err := os.Stat(marker); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("grandchild survived cancellation: stat error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubprocessRunnerForwardsOnlyRequestedProvider(t *testing.T) {
|
||||
runner := helperRunner("provider-scope")
|
||||
runner.Environ = append(runner.Environ, "OTHER_KEY=must-not-leak")
|
||||
runner.Providers["other"] = Provider{Class: "openai", APIKeyEnv: "OTHER_KEY"}
|
||||
if _, err := runner.Run(context.Background(), "/workspace", testRequest(), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvocationRejectsCredentialBearingProviderURL(t *testing.T) {
|
||||
for _, baseURL := range []string{
|
||||
"https://token@example.com/v1",
|
||||
"https://example.com/v1?api_key=secret",
|
||||
"https://example.com/v1#secret",
|
||||
} {
|
||||
t.Run(baseURL, func(t *testing.T) {
|
||||
invocation := Invocation{
|
||||
Version: ProtocolVersion, Workspace: "/workspace", Request: testRequest(),
|
||||
Providers: map[string]Provider{"provider": {Class: "openai", BaseURL: baseURL}},
|
||||
}
|
||||
if err := invocation.Validate(); err == nil {
|
||||
t.Fatal("Validate succeeded")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectEnvironmentDoesNotLeakUnlistedValues(t *testing.T) {
|
||||
got := WorkerEnvironment(
|
||||
[]string{"PATH=/bin", "ARCHIE_GITHUB_TOKEN=secret", "OPENAI_API_KEY=model", "PATH=/usr/bin"},
|
||||
nil,
|
||||
map[string]Provider{"openai": {APIKeyEnv: "OPENAI_API_KEY"}},
|
||||
)
|
||||
want := []string{"PATH=/usr/bin", "OPENAI_API_KEY=model"}
|
||||
if strings.Join(got, "\n") != strings.Join(want, "\n") {
|
||||
t.Fatalf("environment = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServeOneRejectsMultipleInvocations(t *testing.T) {
|
||||
input := `{"version":1} {"version":1}`
|
||||
err := ServeOne(context.Background(), strings.NewReader(input), &strings.Builder{}, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "multiple JSON values") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServeOneWritesStampedExecutionError(t *testing.T) {
|
||||
invocation := Invocation{
|
||||
Version: ProtocolVersion, Workspace: "/workspace", Request: testRequest(),
|
||||
Providers: map[string]Provider{"provider": {Class: "openai"}},
|
||||
}
|
||||
input, err := json.Marshal(invocation)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output strings.Builder
|
||||
err = serveOne(context.Background(), strings.NewReader(string(input)), &output, func(Invocation) Runner {
|
||||
return runnerFunc(func(_ context.Context, _ string, req Request, _ ToolCallReporter) (Result, error) {
|
||||
return Result{
|
||||
Version: ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt,
|
||||
Stage: req.Stage, Status: StatusPassed,
|
||||
}, errors.New("provider unavailable")
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response Response
|
||||
if err := json.Unmarshal([]byte(output.String()), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Error != "provider unavailable" || response.Result.TaskID != invocation.Request.TaskID {
|
||||
t.Fatalf("response = %#v", response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeOneRejectsOversizedInput(t *testing.T) {
|
||||
var value any
|
||||
err := decodeOne(strings.NewReader(`"`+strings.Repeat("x", maxProtocolBytes)+`"`), &value)
|
||||
if err == nil || !strings.Contains(err.Error(), "exceeds") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func helperRunner(behavior string) *SubprocessRunner {
|
||||
return &SubprocessRunner{
|
||||
Command: os.Args[0], Args: []string{"-test.run=TestAgentHelperProcess"},
|
||||
Environ: []string{
|
||||
"GO_WANT_AGENT_HELPER=1", "AGENT_HELPER_BEHAVIOR=" + behavior,
|
||||
"PROVIDER_KEY=selected",
|
||||
},
|
||||
AdditionalEnv: []string{"GO_WANT_AGENT_HELPER", "AGENT_HELPER_BEHAVIOR"},
|
||||
Providers: map[string]Provider{"provider": {Class: "openai", APIKeyEnv: "PROVIDER_KEY"}},
|
||||
}
|
||||
}
|
||||
|
||||
type runnerFunc func(context.Context, string, Request, ToolCallReporter) (Result, error)
|
||||
|
||||
func (f runnerFunc) Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) {
|
||||
return f(ctx, workspace, req, report)
|
||||
}
|
||||
|
||||
func testRequest() Request {
|
||||
return Request{
|
||||
Version: ProtocolVersion, TaskID: 42, Attempt: 3, Stage: "build",
|
||||
Model: "provider/model", Mission: "test mission",
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentHelperProcess(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
if os.Getenv("GO_WANT_AGENT_HELPER") != "1" {
|
||||
return
|
||||
}
|
||||
var invocation Invocation
|
||||
if err := json.NewDecoder(os.Stdin).Decode(&invocation); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
result := Result{
|
||||
Version: ProtocolVersion, TaskID: invocation.Request.TaskID, Attempt: invocation.Request.Attempt,
|
||||
Stage: invocation.Request.Stage, Status: StatusPassed, Summary: "from child",
|
||||
}
|
||||
switch os.Getenv("AGENT_HELPER_BEHAVIOR") {
|
||||
case "success":
|
||||
_ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result})
|
||||
case "worker-error":
|
||||
_ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result, Error: "provider unavailable"})
|
||||
case "malformed":
|
||||
if _, err := fmt.Fprint(os.Stdout, "not-json"); err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
case "oversized":
|
||||
if _, err := fmt.Fprint(os.Stdout, strings.Repeat("x", maxProtocolBytes+1)); err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
case "multiple":
|
||||
_ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result})
|
||||
_ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result})
|
||||
case "mismatched":
|
||||
result.Attempt++
|
||||
_ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result})
|
||||
case "exit":
|
||||
fmt.Fprintln(os.Stderr, "child diagnostic")
|
||||
os.Exit(2)
|
||||
case "hang":
|
||||
time.Sleep(10 * time.Second)
|
||||
case "spawn-grandchild":
|
||||
cmd := exec.CommandContext(ctx, "/bin/sh", "-c", `sleep 0.2; printf survived > "$AGENT_HELPER_MARKER"`)
|
||||
cmd.Env = os.Environ()
|
||||
if err := cmd.Start(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
time.Sleep(10 * time.Second)
|
||||
case "provider-scope":
|
||||
if len(invocation.Providers) != 1 || invocation.Providers["provider"].APIKeyEnv != "PROVIDER_KEY" ||
|
||||
os.Getenv("PROVIDER_KEY") != "selected" || os.Getenv("OTHER_KEY") != "" {
|
||||
os.Exit(2)
|
||||
}
|
||||
_ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result})
|
||||
default:
|
||||
os.Exit(2)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
@@ -23,8 +23,7 @@ type EventPublisher interface {
|
||||
// in-process *events.Bus the daemon cannot see -- the worker and the daemon
|
||||
// are separate processes connected only by NATS. This is the bridge that
|
||||
// makes those Emit calls (stage progress, outcome, parking) reach the
|
||||
// daemon's events table and dashboard timeline the same way an in-process,
|
||||
// daemon-run workflow's Bus already does.
|
||||
// daemon's events table and dashboard timeline.
|
||||
//
|
||||
// A marshal or publish failure is logged and the loop continues: one missing
|
||||
// event must never abort the ones after it, and event shipping must never
|
||||
|
||||
@@ -78,7 +78,7 @@ type ToolSetOptions struct {
|
||||
Approval tools.ApprovalRequester
|
||||
|
||||
// OnToolCall, when non-nil, is notified once per completed tool call.
|
||||
// InProcessRunner populates it so a workflow stage can surface tool
|
||||
// LoopRunner populates it so a workflow stage can surface tool
|
||||
// activity on the task timeline (archie-core-467's task-transcript
|
||||
// counterpart). Nil means no one is listening.
|
||||
OnToolCall ToolCallReporter
|
||||
@@ -94,11 +94,8 @@ type ToolCallReport struct {
|
||||
Failed bool
|
||||
}
|
||||
|
||||
// ToolCallReporter receives one ToolCallReport per completed tool call. Only
|
||||
// a runner that executes in the same process as its tools can populate this
|
||||
// -- SubprocessRunner and NATSRunner dispatch to a different process and have
|
||||
// no visibility into individual calls from here. A nil reporter is valid and
|
||||
// reports nothing.
|
||||
// ToolCallReporter receives one ToolCallReport per completed tool call. A nil
|
||||
// reporter is valid and reports nothing.
|
||||
type ToolCallReporter func(ToolCallReport)
|
||||
|
||||
// toolCallDetailBytes caps the summary ToolCallReport.Detail carries. This
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const maxProtocolBytes = 8 << 20
|
||||
|
||||
// DefaultRunnerFactory creates an InProcessRunner backed by the ai-sdk runtime.
|
||||
func DefaultRunnerFactory(providers map[string]Provider, log *slog.Logger) Runner {
|
||||
return NewInProcessRunner(NewRuntime(providers), log)
|
||||
}
|
||||
|
||||
// ServeOne decodes and executes exactly one invocation.
|
||||
func ServeOne(ctx context.Context, in io.Reader, out io.Writer, log *slog.Logger) error {
|
||||
return serveOne(ctx, in, out, func(invocation Invocation) Runner {
|
||||
return DefaultRunnerFactory(invocation.Providers, log)
|
||||
})
|
||||
}
|
||||
|
||||
func serveOne(ctx context.Context, in io.Reader, out io.Writer, newRunner func(Invocation) Runner) error {
|
||||
var invocation Invocation
|
||||
if err := decodeOne(in, &invocation); err != nil {
|
||||
return fmt.Errorf("decode invocation: %w", err)
|
||||
}
|
||||
if err := invocation.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
runner := newRunner(invocation)
|
||||
if runner == nil {
|
||||
return fmt.Errorf("agent runner is not configured")
|
||||
}
|
||||
result, runErr := runner.Run(ctx, invocation.Workspace, invocation.Request, nil)
|
||||
response := Response{Version: ProtocolVersion, Result: result}
|
||||
if runErr != nil {
|
||||
response.Error = runErr.Error()
|
||||
}
|
||||
if err := json.NewEncoder(out).Encode(response); err != nil {
|
||||
return fmt.Errorf("encode response: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReplyFunc sends a response back to the daemon.
|
||||
type ReplyFunc func(data []byte) error
|
||||
|
||||
// RunnerFactory creates a Runner from provider config. In production this
|
||||
// calls NewRuntime + NewInProcessRunner; tests inject a mock.
|
||||
type RunnerFactory func(Providers map[string]Provider, log *slog.Logger) Runner
|
||||
|
||||
// HandleMessage processes one AgentRequestMessage. When msg.Stages is
|
||||
// populated and msg.Workflow is set, it runs all stages as a per-task
|
||||
// batch. Otherwise it falls back to single-stage execution.
|
||||
//
|
||||
// It passes a nil ToolCallReporter to every Run call: this path has no
|
||||
// TaskContext and therefore no events.Bus to report through. The workflow
|
||||
// engine's own AgentStage.Stage().Run (agent.go) is what wires a real
|
||||
// reporter into tc.Emit; this entry point predates that and is not reached
|
||||
// by workflow.Run.
|
||||
func HandleMessage(ctx context.Context, msg AgentRequestMessage, log *slog.Logger, newRunner RunnerFactory) (*AgentResponseEnvelope, error) {
|
||||
runner := newRunner(msg.Providers, log)
|
||||
if runner == nil {
|
||||
return nil, fmt.Errorf("no providers configured in request")
|
||||
}
|
||||
|
||||
channel := msg.Channel
|
||||
if channel == "" {
|
||||
channel = "response"
|
||||
}
|
||||
|
||||
// Per-task mode: run all stages for this workflow as a batch.
|
||||
if msg.Workflow != "" && len(msg.Stages) > 0 {
|
||||
return runStages(ctx, runner, msg, channel, log)
|
||||
}
|
||||
|
||||
// Single-stage mode (backward compatible).
|
||||
result, runErr := runner.Run(ctx, msg.Workspace, msg.Request, nil)
|
||||
resp := &AgentResponseEnvelope{
|
||||
Version: msg.Request.Version,
|
||||
Result: result,
|
||||
Channel: channel,
|
||||
}
|
||||
if runErr != nil {
|
||||
resp.Error = runErr.Error()
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// runStages executes every stage in msg.Stages sequentially, accumulating
|
||||
// tokens, iterations, and notes. The first failure stops the batch and
|
||||
// returns immediately. On success, TaskCompleted is set.
|
||||
func runStages(ctx context.Context, runner Runner, msg AgentRequestMessage, channel string, log *slog.Logger) (*AgentResponseEnvelope, error) {
|
||||
var (
|
||||
totalTokens int
|
||||
totalIter int
|
||||
lastResult Result
|
||||
combinedNotes []string
|
||||
combinedDetail []string
|
||||
)
|
||||
|
||||
for i, stage := range msg.Stages {
|
||||
log.Info("running stage", "stage", stage.Stage, "batch", fmt.Sprintf("%d/%d", i+1, len(msg.Stages)))
|
||||
result, runErr := runner.Run(ctx, msg.Workspace, stage, nil)
|
||||
if runErr != nil {
|
||||
resp := &AgentResponseEnvelope{
|
||||
Version: stage.Version,
|
||||
Result: result,
|
||||
Error: runErr.Error(),
|
||||
Channel: channel,
|
||||
}
|
||||
return resp, nil //nolint:nilerr // runErr is reported to the caller in the response envelope's Error field; returning it here as well would double-report and abort the NATS reply
|
||||
}
|
||||
totalTokens += result.TokensUsed
|
||||
totalIter += result.Iterations
|
||||
combinedNotes = append(combinedNotes, result.AppendedNotes...)
|
||||
if result.Summary != "" {
|
||||
combinedDetail = append(combinedDetail, fmt.Sprintf("[%s] %s", stage.Stage, result.Summary))
|
||||
}
|
||||
lastResult = result
|
||||
if result.Status != StatusPassed {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
lastResult.TokensUsed = totalTokens
|
||||
lastResult.Iterations = totalIter
|
||||
lastResult.AppendedNotes = combinedNotes
|
||||
if len(combinedDetail) > 0 {
|
||||
lastResult.Summary = strings.Join(combinedDetail, "\n")
|
||||
}
|
||||
|
||||
return &AgentResponseEnvelope{
|
||||
Version: lastResult.Version,
|
||||
Result: lastResult,
|
||||
Channel: channel,
|
||||
TaskCompleted: lastResult.Status == StatusPassed,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func decodeOne(r io.Reader, value any) error {
|
||||
data, err := io.ReadAll(io.LimitReader(r, maxProtocolBytes+1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) > maxProtocolBytes {
|
||||
return fmt.Errorf("JSON value exceeds %d bytes", maxProtocolBytes)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
if err := decoder.Decode(value); err != nil {
|
||||
return err
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); err != io.EOF {
|
||||
if err == nil {
|
||||
return fmt.Errorf("multiple JSON values are not allowed")
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user