Relocating internal/nats as-is would have cemented its problems into the approved layout, so this is a rewrite rather than a move. What was wrong: - Conn() *nats.Conn, PublishMsg(*nats.Msg) and Fetch() jetstream.Msg pushed SDK types into all four consumers, so the broker was not replaceable -- the opposite of what dependencies-and-contracts.md requires. - PublishTask took seven positional parameters, six of them strings, where a transposed argument was a silent bug. - Labels travelled as a comma-separated string and were re-split on every publish. - Fetch returned (nil, nil) for 'no message', which every caller had to remember to special-case. - The logger field was stored and never used. - Stream name, consumer name and every timeout were hardcoded constants. - Errors were inconsistently wrapped; several paths returned bare errors. - Connect repeated nc.Close() on each failure branch. What replaces it: - One concern per file: config, errors, subjects, message, client, publisher, consumer. - Publisher/Consumer/Requester interfaces with compile-time assertions, so callers depend on behaviour and can be faked without a broker. - A Message wrapper keeps jetstream types behind the boundary; consumers no longer import the NATS SDK at all. - TaskEnvelope with []string labels and JSON methods preserving the comma-separated wire form for already-queued messages. - Sentinel errors (ErrNoMessage, ErrNotConnected, ErrNoReplyAddress, ErrInvalidConfig) and %w wrapping with operation context throughout. - Config with validation and defaults; a single deferred cleanup in Connect. - CoreConn() as the one documented escape hatch, for the *rpc packages that are themselves NATS infrastructure. Consumers migrated: cmd/archied, cmd/archie-agent, internal/daemon, internal/agentexec. Behaviour, subjects and wire format unchanged.
114 lines
3.6 KiB
Go
114 lines
3.6 KiB
Go
package agentexec
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"time"
|
|
|
|
|
|
arnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
|
)
|
|
|
|
// 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"`
|
|
}
|
|
|
|
// 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
|
|
|
|
// 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 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,
|
|
}
|
|
data, err := json.Marshal(msg)
|
|
if err != nil {
|
|
return Result{}, err
|
|
}
|
|
|
|
subject := arnats.SubjectForAgentRequest(req.TaskID)
|
|
if err := r.Nats.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
|
|
}
|