Files
archie/.scratch/explore-chunkB-nats-reply.md
T
sam 8c4bb1ef1d 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
2026-07-22 02:13:01 +10:00

322 lines
14 KiB
Markdown

# nats-reply
Now I have a complete understanding. Here is the comprehensive report.
---
## NATS Agent Communication Reply Pattern -- Design Report
### Sources Read
- `/work/apps/archie-core/internal/nats/client.go` -- existing JetStream Client, PublishTask, Fetch, Connect
- `/work/apps/archie-core/internal/nats/subjects.go` -- existing subject constants
- `/work/apps/archie-core/internal/daemon/daemon.go` -- current NATS integration in the daemon
- `/work/apps/archie-core/internal/config/config.go` -- NATSConfig struct
- `/work/apps/archie-core/go.mod` -- nats.go v1.52.0, nats-server/v2 v2.14.3
- `/work/apps/archie-core/internal/agentexec/inprocess.go` -- Runner interface definition (line 20)
- `/work/apps/archie-core/internal/agentexec/subprocess.go` -- SubprocessRunner.Run (blocks on exec.Command)
- `/work/apps/archie-core/internal/agentexec/protocol.go` -- Request, Result, Invocation, Response types
- `/work/apps/archie-core/internal/workflow/agent.go` -- how AgentStage calls `tc.Agent.Run(ctx, tc.Dir, req)` (line 110)
- `/home/sam/go/pkg/mod/github.com/nats-io/nats.go@v1.52.0/jetstream/publish.go` -- PublishMsg internals
- `/home/sam/go/pkg/mod/github.com/nats-io/nats.go@v1.52.0/jetstream/message.go` -- jetstream.Msg interface (Reply(), Headers(), etc.)
- `/home/sam/go/pkg/mod/github.com/nats-io/nats.go@v1.52.0/context.go` -- RequestMsgWithContext, requestWithContext
- `/home/sam/go/pkg/mod/github.com/nats-io/nats.go@v1.52.0/nats.go` -- Msg struct, NewInbox, createNewRequestAndSend
- `/work/apps/archie-core/.scratch/plan-nats-design.md` -- the original Phase 1 NATS task distribution design document
---
### Key Finding: `PublishMsg` Eats the Reply Field
The most critical technical finding is in `jetstream/publish.go` (line 229-232) and `context.go` (line 40-84). When you call:
```go
js.PublishMsg(ctx, &nats.Msg{Subject: subj, Reply: "my.reply", Data: data})
```
The `PublishMsg` implementation calls `js.conn.RequestMsgWithContext(ctx, m)`, which internally calls `createNewRequestAndSend(subj, hdr, data)` (new style) or `oldRequestWithContext` (old style). Both paths create a **fresh inbox** for the JetStream PubAck response and call `nc.publish(subj, respInbox, ...)` -- the reply subject you set on the `nats.Msg` is **completely ignored**. The wire-level `Reply` on the published NATS message is the PubAck inbox, not your custom reply subject.
There is a second issue: even if the Reply did pass through, it would need to point at an inbox the JetStream server could reach. And `PublishMsgAsync` explicitly rejects messages with `Reply` set (`ErrAsyncPublishReplySubjectSet`, line 336-337 of publish.go).
**This means: the reply-to address must be carried outside the `nats.Msg.Reply` field -- in custom headers or the message body.**
---
### 1. Subject Naming Pattern
**Requests** (published by the daemon to JetStream):
```
archie.agent.<task_id>.<stage>
```
Examples: `archie.agent.42.planner`, `archie.agent.42.builder`, `archie.agent.17.analyst`
**Responses** (published by the agent worker back to the daemon):
Use core NATS reply inboxes, generated by `nc.NewInbox()`:
```
_INBOX.<random-hex-string>
```
These are ephemeral, one-shot subjects. No JetStream stream is involved on the response path.
**Why not a deterministic subject for responses?** The daemon needs to wait for exactly one response from a specific agent execution. An inbox subscription is the NATS-idiomatic way: it creates a unique subject per request, the daemon subscribes to it before publishing, and no other subscriber can accidentally consume the response.
**New subject constants to add to `internal/nats/subjects.go`:**
```go
const SubjectAgentRequest = "archie.agent." // prefix, full subject is built with task_id and stage
func SubjectForAgentRequest(taskID int64, stage string) string {
return fmt.Sprintf("archie.agent.%d.%s", taskID, stage)
}
```
---
### 2. JetStream or Core NATS?
**Hybrid: JetStream for requests, core NATS for responses.**
| Aspect | Requests | Responses |
|--------|----------|-----------|
| Transport | JetStream (`js.PublishMsg`) | Core NATS (`nc.Publish`) |
| Persistence | Yes (survives daemon crash) | No (ephemeral) |
| Dedup | Yes (Nats-Msg-Id header) | Not needed |
| Delivery guarantee | At-least-once (consumer retries) | Best-effort (daemon subscribed) |
**Rationale:**
- The **request** (agentexec.Request) is a large, important payload. If the daemon crashes after publishing but before the response arrives, JetStream retains the message. A restarted daemon (or a different daemon on the same stream) can pick it up.
- The **response** is an ephemeral, one-shot delivery. If the daemon disconnects while waiting (crash, network blip), the response is lost -- but that is acceptable because the agent will eventually time out waiting for a result confirmation and the daemon can re-issue the request.
- Using JetStream for responses would require a second pull consumer and polling -- incompatible with the blocking `Runner.Run` contract.
- The existing `nc.Conn` is already available via `js.Conn()`, so no extra connection is needed.
---
### 3. Correlating Requests with Responses
Use **reply inbox** correlation -- the standard NATS request-reply pattern:
1. Daemon calls `nc.NewInbox()` to get a unique reply subject
2. Daemon subscribes to that inbox via `nc.SubscribeSync(inbox)` with `AutoUnsubscribe(1)`
3. Daemon sets the inbox address in a **custom header** `X-Archie-Reply` on the JetStream message
4. Daemon publishes the agent request via `js.PublishMsg`
5. Daemon blocks on `sub.NextMsg(timeout)` waiting for the response
6. Agent worker receives the JetStream message, reads the `X-Archie-Reply` header
7. Agent worker processes the request (may take minutes)
8. Agent worker publishes the result to the reply inbox via `nc.Publish(replySubject, jsonResult)`
9. Daemon receives the response and returns `agentexec.Result`
**No separate correlation ID is needed.** The reply inbox IS the correlation mechanism. The `agentexec.Response` already carries `TaskID`, `Attempt`, and `Stage` for validation (`ValidateFor` in `agentexec/protocol.go:176-190`), so we get double-checking on the identity of the response without any new identifiers.
---
### 4. Changes to `internal/nats`
#### 4a. New message types
Add to `client.go` (or a new `agent.go`):
```go
// 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 agentexec.Request `json:"request"`
Providers map[string]agentexec.Provider `json:"providers,omitempty"`
}
// AgentResponseEnvelope is the response payload published to the reply inbox.
type AgentResponseEnvelope struct {
Version int `json:"version"`
Result agentexec.Result `json:"result"`
Error string `json:"error,omitempty"`
}
```
#### 4b. New methods on `Client`
```go
// ReplyHeader is the custom header carrying the daemon's reply inbox.
const ReplyHeader = "X-Archie-Reply"
// NewReplyInbox creates a unique inbox and returns a sync subscription.
func (c *Client) NewReplyInbox() (*nats.Subscription, error) {
sub, err := c.conn.SubscribeSync(c.conn.NewInbox())
if err != nil {
return nil, err
}
sub.AutoUnsubscribe(1) // exactly one response expected
return sub, nil
}
// PublishAgentRequest publishes an agent execution request to JetStream
// with the reply inbox set in the X-Archie-Reply header.
func (c *Client) PublishAgentRequest(ctx context.Context, req agentexec.Request, providers map[string]agentexec.Provider, workspace string, replyInbox string) error {
msg := AgentRequestMessage{
TaskID: req.TaskID,
Attempt: req.Attempt,
Stage: req.Stage,
Workspace: workspace,
Request: req,
Providers: providers,
}
data, err := json.Marshal(msg)
if err != nil {
return err
}
subject := SubjectForAgentRequest(req.TaskID, req.Stage)
headers := nats.Header{}
headers.Set(ReplyHeader, replyInbox)
msgID := fmt.Sprintf("%s%d/%d/%s", msgPrefix, req.TaskID, req.Attempt, req.Stage)
headers.Set("Nats-Msg-Id", msgID)
_, err = c.js.PublishMsg(ctx, &nats.Msg{
Subject: subject,
Data: data,
Header: headers,
})
return err
}
```
#### 4c. New stream or extend existing
The existing `ARCHIE_TASKS` stream has subjects `["archie.task.>"]`. Agent requests use `archie.agent.<task_id>.<stage>`, which does **not** match `archie.task.>`.
**Recommendation: Extend the existing stream's subjects** by adding `"archie.agent.>"` to `StreamConfig.Subjects`. This is simpler than creating a second stream and avoids managing two stream lifecycles:
```go
stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
Name: streamName,
Subjects: []string{"archie.task.>", "archie.agent.>"},
Storage: jetstream.FileStorage,
Retention: jetstream.WorkQueuePolicy,
Duplicates: dedupWindow,
})
```
The same WorkQueuePolicy works: when an agent receives and acks the request, it is removed from the stream. If the daemon crashes, the message stays until the agent acks or `MaxDeliver` is reached.
**Alternative: Create a dedicated `ARCHIE_AGENT` stream.** This would allow different retention/deduplication settings (e.g., a `LimitsPolicy` with a `MaxAge` of 1 hour vs the current WorkQueue). But this adds complexity. Start with the extension approach.
#### 4d. NATSRunner: bridge between Runner interface and NATS
Create `/work/apps/archie-core/internal/agentexec/nats.go`:
```go
type NATSRunner struct {
Nats *nats.Client
Providers map[string]agentexec.Provider
Log *slog.Logger
}
func (r *NATSRunner) Run(ctx context.Context, workspace string, req agentexec.Request) (agentexec.Result, error) {
if err := req.Validate(); err != nil {
return agentexec.Result{}, err
}
// 1. Create reply inbox
replySub, err := r.Nats.NewReplyInbox()
if err != nil {
return agentexec.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
if err := r.Nats.PublishAgentRequest(ctx, req, r.Providers, workspace, replySub.Subject); err != nil {
return agentexec.Result{}, fmt.Errorf("publish agent request: %w", err)
}
// 4. Wait for reply (blocking, matching SubprocessRunner.Run behavior)
reply, err := replySub.NextMsg(timeout)
if err != nil {
return agentexec.Result{}, fmt.Errorf("agent reply timeout: %w", err)
}
// 5. Decode response
var envelope AgentResponseEnvelope
if err := json.Unmarshal(reply.Data, &envelope); err != nil {
return agentexec.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 agentexec.Result{}, err
}
return envelope.Result, nil
}
```
---
### 5. Simplest Possible Reply Pattern
**Respondent's note: the paragraphs below are the core answer.**
The simplest pattern that works with the existing JetStream setup:
1. **Daemon side** (NATSRunner, blocking like SubprocessRunner):
- `sub, _ := nc.SubscribeSync(nc.NewInbox())` -- creates a unique reply subject as a sync subscription
- `sub.AutoUnsubscribe(1)` -- exactly one reply expected
- Publish to JetStream: `js.PublishMsg(ctx, &nats.Msg{Subject: "archie.agent.<taskID>.<stage>", Header: {"X-Archie-Reply": [inbox]}, Data: payload})`
- Block: `msg, err := sub.NextMsg(budget.WallClock)` -- returns `agentexec.Result` on success, error on timeout
- Unsubscribe the inbox
2. **Agent side** (archie-agent worker, or any consumer):
- Receive via JetStream pull consumer
- `replyTo := msg.Headers().Get("X-Archie-Reply")`
- Process the request (the existing agentloop)
- Result: `nc.Publish(replyTo, jsonBytes)` -- a core NATS publish, no JetStream involved
3. **No additional JetStream consumers, streams, or streams needed.** The existing `nc.Conn` (exposed as `js.Conn()`) handles both directions.
**NATS API calls involved:**
| Operation | API Call | Package |
|-----------|----------|---------|
| Create reply inbox | `nc.NewInbox()` / `nc.SubscribeSync(inbox)` | `nats.go` core |
| Publish request | `js.PublishMsg(ctx, &nats.Msg{...})` | `jetstream` |
| Wait for reply | `sub.NextMsg(timeout)` | `nats.go` core |
| Send reply (agent) | `nc.Publish(reply, data)` | `nats.go` core |
**Total new lines of code in `internal/nats`:** approximately 100-120 lines (two message structs, two new helper functions, one new subject function, and the header constant).
**Total new lines for `NATSRunner`:** approximately 50-60 lines.
---
### Configuration and Wiring
The daemon already supports `agent.mode` with values `"inprocess"` and `"subprocess"`. Add `"nats"` as a third mode.
In `cmd/archied/main.go`, when `cfg.Agent.Mode == "nats"`:
```go
runner := &agentexec.NATSRunner{
Nats: natsClient,
Providers: agentexec.ProviderConfig(cfg.Providers),
Log: log.With("runner", "nats"),
}
```
No changes are needed to the `workflow` package or the daemon's `process` method -- they already consume `tc.Agent.Run(ctx, tc.Dir, req)` via the `agentexec.Runner` interface.
---
### Critical Technical Decision: Reply Subject in Headers
The `X-Archie-Reply` header approach was chosen over alternatives:
- **Reply in `nats.Msg.Reply` field**: Does not work -- `PublishMsg` internally uses the Reply field for the JetStream PubAck response and overwrites whatever you set.
- **Reply in message body**: Would require the agent to parse the JSON body before knowing where to respond -- a chicken-and-egg problem if the body is corrupted or the format changes.
- **Correlation ID in headers + deterministic response subject**: Would require provisioning a consumer on the response subject and polling -- breaks the blocking `Runner.Run` contract.
The reply inbox approach gives us:
- No polling (daemon blocks on sync subscription)
- Automatic correlation (each request gets a unique inbox)
- No consumer lifecycle management for responses
- Matching the existing `SubprocessRunner` blocking contract exactly