feat: promote archie-agent to NATS-connected per-task worker
Replaces stdin/stdout subprocess transport with NATS JetStream request-reply pattern. The Runner interface and workflow orchestration are unchanged. New NATSRunner (implements Runner): - Publishes AgentRequestMessage to JetStream with X-Archie-Reply header - Blocks on core NATS inbox subscription for response - Same Run(ctx, workspace, req) (Result, error) contract Rewritten archie-agent (cmd/archie-agent): - Long-running NATS-connected process (was 28-line stdin/stdout) - Pull-consumes from ARCHIE_TASKS with archie.agent.> filter - Builds InProcessRunner, executes agent loop, replies to inbox - Graceful shutdown via signal handling Extended internal/nats: - SubjectAgentWildcard, SubjectForAgentRequest, ReplyHeader - Conn() accessor, NewReplyInbox(), PublishMsg() for JetStream - Stream subjects extended to ["archie.task.>", "archie.agent.>"] Config: "nats" added as valid agent.mode alongside inprocess/subprocess Tests: NATSRunner round-trip with embedded NATS server + handler
This commit is contained in:
1 parent
bb2193e5e4
commit
8c4bb1ef1d
11 files changed
+1309
-18
No files matched your search
@@ -0,0 +1,107 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
|
||||
arnats "github.com/samcharles93/archie-core/internal/nats"
|
||||
)
|
||||
|
||||
// AgentRequestMessage is the NATS payload for an agent stage execution request.
|
||||
type AgentRequestMessage struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
Attempt int `json:"attempt"`
|
||||
Stage string `json:"stage"`
|
||||
Workspace string `json:"workspace"`
|
||||
Request Request `json:"request"`
|
||||
Providers map[string]Provider `json:"providers,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"`
|
||||
}
|
||||
|
||||
const defaultAgentTimeout = 30 * time.Minute
|
||||
|
||||
// NATSRunner sends agent stage execution requests over NATS JetStream and
|
||||
// waits for replies on core NATS inboxes. It implements Runner.
|
||||
type NATSRunner struct {
|
||||
Nats *arnats.Client
|
||||
Providers map[string]Provider
|
||||
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.
|
||||
func (r *NATSRunner) Run(ctx context.Context, workspace string, req Request) (Result, error) {
|
||||
if err := req.Validate(); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
|
||||
// 1. Create reply inbox with auto-unsubscribe after one message.
|
||||
replySub, err := r.Nats.NewReplyInbox()
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("nats reply inbox: %w", err)
|
||||
}
|
||||
defer replySub.Unsubscribe()
|
||||
|
||||
// 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,
|
||||
Workspace: workspace,
|
||||
Request: req,
|
||||
Providers: r.Providers,
|
||||
}
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
|
||||
subject := arnats.SubjectForAgentRequest(req.TaskID, req.Stage)
|
||||
headers := natsio.Header{}
|
||||
headers.Set(arnats.ReplyHeader, replySub.Subject)
|
||||
|
||||
if _, err := r.Nats.PublishMsg(ctx, &natsio.Msg{
|
||||
Subject: subject,
|
||||
Data: data,
|
||||
Header: headers,
|
||||
}); err != nil {
|
||||
return Result{}, fmt.Errorf("publish agent request: %w", err)
|
||||
}
|
||||
|
||||
// 4. Wait for reply (blocking, matching SubprocessRunner.Run behaviour).
|
||||
reply, err := replySub.NextMsg(timeout)
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("agent reply: %w", err)
|
||||
}
|
||||
|
||||
// 5. Decode response.
|
||||
var envelope AgentResponseEnvelope
|
||||
if err := json.Unmarshal(reply.Data, &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
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
arnats "github.com/samcharles93/archie-core/internal/nats"
|
||||
)
|
||||
|
||||
func startEmbeddedNATS(t *testing.T) *server.Server {
|
||||
t.Helper()
|
||||
// RunRandClientPortServer doesn't enable JetStream. Enable it separately.
|
||||
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
|
||||
}
|
||||
|
||||
// handler subscribes to archie.agent.> and replies with a canned result.
|
||||
func startHandler(t *testing.T, nc *natsio.Conn) {
|
||||
t.Helper()
|
||||
js, err := jetstream.New(nc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stream, err := js.CreateOrUpdateStream(context.Background(), jetstream.StreamConfig{
|
||||
Name: "ARCHIE_TASKS",
|
||||
Subjects: []string{"archie.task.>", "archie.agent.>"},
|
||||
Storage: jetstream.FileStorage,
|
||||
Retention: jetstream.WorkQueuePolicy,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cons, err := stream.CreateOrUpdateConsumer(context.Background(), jetstream.ConsumerConfig{
|
||||
Name: "test-agent",
|
||||
FilterSubject: arnats.SubjectAgentWildcard,
|
||||
AckPolicy: jetstream.AckExplicitPolicy,
|
||||
MaxDeliver: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
batch, err := cons.Fetch(1, jetstream.FetchMaxWait(5 * time.Second))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for msg := range batch.Messages() {
|
||||
if msg == nil {
|
||||
continue
|
||||
}
|
||||
var req AgentRequestMessage
|
||||
json.Unmarshal(msg.Data(), &req)
|
||||
replyTo := msg.Headers().Get(arnats.ReplyHeader)
|
||||
resp := 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,
|
||||
},
|
||||
}
|
||||
data, _ := json.Marshal(resp)
|
||||
nc.Publish(replyTo, data)
|
||||
msg.Ack()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func TestNATSRunnerRoundTrip(t *testing.T) {
|
||||
srv := startEmbeddedNATS(t)
|
||||
url := srv.ClientURL()
|
||||
|
||||
ctx := context.Background()
|
||||
client, err := arnats.Connect(ctx, url, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
// Start the handler that simulates archie-agent.
|
||||
startHandler(t, client.Conn())
|
||||
|
||||
runner := &NATSRunner{
|
||||
Nats: 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, MaxTokens: 100},
|
||||
}
|
||||
|
||||
result, err := runner.Run(ctx, "/tmp/test-workspace", req)
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -296,9 +296,9 @@ func Load(path string) (Config, error) {
|
||||
cfg.Agent.Command = "archie-agent"
|
||||
}
|
||||
switch cfg.Agent.Mode {
|
||||
case "inprocess", "subprocess":
|
||||
case "inprocess", "subprocess", "nats":
|
||||
default:
|
||||
return cfg, fmt.Errorf("config: agent.mode %q is invalid (want inprocess or subprocess)", cfg.Agent.Mode)
|
||||
return cfg, fmt.Errorf("config: agent.mode %q is invalid (want inprocess, subprocess, or nats)", cfg.Agent.Mode)
|
||||
}
|
||||
if cfg.Agent.Mode == "subprocess" && strings.TrimSpace(cfg.Agent.Command) == "" {
|
||||
return cfg, fmt.Errorf("config: agent.command is required in subprocess mode")
|
||||
|
||||
+24
-1
@@ -54,7 +54,7 @@ func Connect(ctx context.Context, url string, log *slog.Logger) (*Client, error)
|
||||
|
||||
stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
|
||||
Name: streamName,
|
||||
Subjects: []string{"archie.task.>"},
|
||||
Subjects: []string{"archie.task.>", "archie.agent.>"},
|
||||
Storage: jetstream.FileStorage,
|
||||
Retention: jetstream.WorkQueuePolicy,
|
||||
Duplicates: dedupWindow,
|
||||
@@ -81,9 +81,32 @@ func Connect(ctx context.Context, url string, log *slog.Logger) (*Client, error)
|
||||
return &Client{conn: nc, js: js, stream: stream, consumer: consumer, log: log}, nil
|
||||
}
|
||||
|
||||
// Conn returns the underlying NATS connection for core NATS operations
|
||||
// (inbox subscriptions, direct publishes).
|
||||
func (c *Client) Conn() *nats.Conn { return c.conn }
|
||||
|
||||
// PublishMsg publishes a message to JetStream with optional headers.
|
||||
func (c *Client) PublishMsg(ctx context.Context, msg *nats.Msg) (*jetstream.PubAck, error) {
|
||||
return c.js.PublishMsg(ctx, msg)
|
||||
}
|
||||
|
||||
// Close drains and closes the NATS connection.
|
||||
func (c *Client) Close() { c.conn.Close() }
|
||||
|
||||
// NewReplyInbox creates a unique inbox subject and returns a synchronous
|
||||
// subscription configured to auto-unsubscribe after one message.
|
||||
func (c *Client) NewReplyInbox() (*nats.Subscription, error) {
|
||||
sub, err := c.conn.SubscribeSync(c.conn.NewInbox())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := sub.AutoUnsubscribe(1); err != nil {
|
||||
sub.Unsubscribe()
|
||||
return nil, err
|
||||
}
|
||||
return sub, nil
|
||||
}
|
||||
|
||||
// PublishTask publishes a discovered issue to the appropriate NATS subject.
|
||||
// The Nats-Msg-Id header enables JetStream dedup within the dedup window.
|
||||
func (c *Client) PublishTask(ctx context.Context, owner, repo string, number int, title, body, labels string) error {
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
// Package nats manages the NATS JetStream connection for task distribution.
|
||||
// When configured, the daemon publishes discovered issues to NATS subjects
|
||||
// and consumes them back via a JetStream pull consumer. When not configured
|
||||
// (nil client), the existing SQLite ClaimNext flow is used unchanged.
|
||||
// Package nats manages the NATS JetStream connection for task distribution
|
||||
// and agent communication. When configured, the daemon publishes discovered
|
||||
// issues to NATS subjects and consumes them back via a JetStream pull
|
||||
// consumer. Agent workers consume stage execution requests and reply via
|
||||
// core NATS inboxes. When not configured (nil client), the existing SQLite
|
||||
// ClaimNext flow is used unchanged.
|
||||
package nats
|
||||
|
||||
import "strings"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Task distribution subjects. Each subject encodes the workflow type so
|
||||
// future multi-daemon deployments can filter by workflow.
|
||||
@@ -35,3 +40,19 @@ func SubjectForLabels(labels []string) string {
|
||||
}
|
||||
return SubjectTaskDefault
|
||||
}
|
||||
|
||||
// Agent communication subjects.
|
||||
const (
|
||||
// SubjectAgentWildcard matches all agent stage execution requests.
|
||||
SubjectAgentWildcard = "archie.agent.>"
|
||||
)
|
||||
|
||||
// SubjectForAgentRequest returns the JetStream subject for a stage request.
|
||||
func SubjectForAgentRequest(taskID int64, stage string) string {
|
||||
return fmt.Sprintf("archie.agent.%d.%s", taskID, stage)
|
||||
}
|
||||
|
||||
// ReplyHeader is the custom NATS header carrying the daemon's reply inbox.
|
||||
// JetStream's PublishMsg consumes the Reply field internally for PubAck, so
|
||||
// the reply address is carried via this header instead.
|
||||
const ReplyHeader = "X-Archie-Reply"
|
||||
Reference in new issue
Block a user