Skip to content

armgit / ax

Public Imported from GitHub
0

Agent Executor (AX) is Google's open agentic orchestration runtime

Go

Add durable conversation resumability to the Antigravity Interactions harness (#180)

zbl94b0e97874a68a
diff --git a/internal/harness/antigravityinteractions.go b/internal/harness/antigravityinteractions.go
index a15231f..d136bda 100644
--- a/internal/harness/antigravityinteractions.go
+++ b/internal/harness/antigravityinteractions.go
@@ -30,25 +30,30 @@ package harness
// no executor is configured, no third-party tools are advertised.
//
// Neither kind of tool call is surfaced to the caller: Run drives the whole
-// interaction to completion (initial turn -> resume -> resume -> ... -> final
-// answer) and only forwards the agent's text output via Handler.OnMessage.
+// interaction loop to completion (initial turn -> continuation turn -> ... ->
+// final answer) and only forwards the agent's text output via Handler.OnMessage.
+// Each turn after the first is chained to the previous one via the Interactions
+// API's previous_interaction_id; this is an implementation detail of the loop,
+// not an AX resume.
//
-// Queue carries human input only -- the initial prompt and, in the future,
-// "steering" messages injected mid-run. It never carries tool results (the
-// harness produces those itself). Queued input is drained at each interaction
-// gap (every resume point), which is the only place the harness can influence an
-// otherwise atomic interaction.
+// Queue carries human input only -- the initial prompt and "steering" messages
+// injected mid-run. It never carries tool results (the harness produces those
+// itself). Queued input is drained at each interaction gap, which is the only
+// place the harness can influence an otherwise atomic interaction.
import (
"bufio"
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
+ "math/rand"
"net/http"
"os"
"sort"
+ "strconv"
"strings"
"sync"
"time"
@@ -91,7 +96,7 @@ type AntigravityInteractionsConfig struct {
Agent string
// SystemInstruction, if set, is sent as the interaction's system_instruction
// (a free-form system prompt prepended to the agent's own instructions). It
- // is sent on every turn so it persists across resumes.
+ // is sent on every turn of the interaction loop so it persists across them.
SystemInstruction string
// MaxTurns caps the number of interaction turns the harness will drive within
// a single Run before giving up. Defaults to 100.
@@ -115,6 +120,17 @@ type AntigravityInteractionsConfig struct {
// HTTPClient overrides the HTTP client. If nil, a default client with a long
// timeout is used.
HTTPClient *http.Client
+
+ // StateDir is the directory where each conversation's resume cursor is
+ // persisted, so a conversation can resume after a restart. It is required:
+ // NewAntigravityInteractionsHarness returns an error if it is empty.
+ //
+ // Correctness relies on a single writer per conversation: writes are
+ // last-write-wins with no compare-and-swap. This is an expectation the caller
+ // must satisfy (e.g. by routing a conversation id to one worker, or resuming
+ // a worker from that conversation's snapshot) -- it is not currently enforced
+ // by the controller.
+ StateDir string
}
func (c *AntigravityInteractionsConfig) withDefaults() {
@@ -143,6 +159,11 @@ type AntigravityInteractionsHarness struct {
cfg AntigravityInteractionsConfig
httpClient *http.Client
+ // cursors persists each conversation's resume cursor to disk so a conversation
+ // can resume after a restart. It is always non-nil (the constructor requires a
+ // usable state directory).
+ cursors *cursorStore
+
// tsOnce guards lazy initialization of ts, the resolved OAuth2 token source.
// It is resolved on first use (rather than in the constructor) so credential
// errors surface to the caller of Run instead of at construction time.
@@ -152,24 +173,49 @@ type AntigravityInteractionsHarness struct {
}
// NewAntigravityInteractionsHarness creates a harness from the given config,
-// filling in defaults for unset fields.
-func NewAntigravityInteractionsHarness(cfg AntigravityInteractionsConfig) *AntigravityInteractionsHarness {
+// filling in defaults for unset fields. It returns an error if cfg.StateDir is
+// empty or the cursor store cannot be created: resume-cursor persistence is
+// required, so a usable state directory must be provided.
+func NewAntigravityInteractionsHarness(cfg AntigravityInteractionsConfig) (*AntigravityInteractionsHarness, error) {
cfg.withDefaults()
hc := cfg.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 10 * time.Minute}
}
- return &AntigravityInteractionsHarness{cfg: cfg, httpClient: hc}
+ if cfg.StateDir == "" {
+ return nil, errors.New("AntigravityInteractionsConfig.StateDir must be set")
+ }
+ cursors, err := newCursorStore(cfg.StateDir)
+ if err != nil {
+ return nil, fmt.Errorf("creating cursor store: %w", err)
+ }
+ return &AntigravityInteractionsHarness{cfg: cfg, httpClient: hc, cursors: cursors}, nil
}
-// Start implements Harness.Start.
+// Start implements Harness.Start. It loads any previously persisted resume
+// cursor for conversationID so the returned Execution resumes the existing
+// interaction chain instead of starting a new one.
func (h *AntigravityInteractionsHarness) Start(ctx context.Context, conversationID string, harnessConfig []byte) (Execution, error) {
- return &antigravityInteractionsExecution{
+ e := &antigravityInteractionsExecution{
harness: h,
conversationID: conversationID,
id: uuid.NewString(),
harnessConfig: harnessConfig,
- }, nil
+ }
+
+ cur, found, err := h.cursors.load(conversationID)
+ if err != nil {
+ // A real load failure must not be silently treated as "new", which would
+ // lose an existing conversation's history.
+ return nil, fmt.Errorf("loading resume cursor for %q: %w", conversationID, err)
+ }
+ if found {
+ // A persisted cursor is only written after a successful turn, so a
+ // non-empty interaction id means the conversation has already started;
+ // the first-turn check in Run derives that from prevInteractionID.
+ e.prevInteractionID = cur.PrevInteractionID
+ }
+ return e, nil
}
// antigravityInteractionsExecution implements Execution. It is long-lived
@@ -186,10 +232,10 @@ type antigravityInteractionsExecution struct {
queued []*proto.Message
closed bool
- // started is false until the initial turn has been sent.
- started bool
- // prevInteractionID chains resume turns (the interaction chain this Execution
- // owns).
+ // prevInteractionID chains the turns of the interaction loop (the interaction
+ // chain this Execution owns), and is the value persisted for cross-Execution
+ // resume. It is empty until the first turn completes successfully; an empty
+ // value therefore means "no turn has succeeded yet" (the first turn).
prevInteractionID string
}
@@ -229,13 +275,22 @@ func (e *antigravityInteractionsExecution) drainQueue() []any {
return messagesToInputSteps(msgs)
}
-func (e *antigravityInteractionsExecution) setPrevID(id string) {
+// setPrevID records the latest interaction id (in memory) and durably persists
+// the resume cursor so the conversation can resume after a restart. A persistence
+// failure is returned to the caller so the run can decide how to handle it rather
+// than silently losing durability.
+func (e *antigravityInteractionsExecution) setPrevID(ctx context.Context, id string) error {
if id == "" {
- return
+ return nil
}
e.mu.Lock()
e.prevInteractionID = id
e.mu.Unlock()
+
+ if err := e.harness.cursors.save(e.conversationID, resumeCursor{PrevInteractionID: id}); err != nil {
+ return fmt.Errorf("persisting resume cursor: %w", err)
+ }
+ return nil
}
// Run implements Execution.Run. It drives the interaction to completion,
@@ -252,7 +307,6 @@ func (e *antigravityInteractionsExecution) Run(ctx context.Context, handler Hand
e.mu.Unlock()
return fmt.Errorf("execution session already closed")
}
- started := e.started
prevID := e.prevInteractionID
e.mu.Unlock()
@@ -262,16 +316,15 @@ func (e *antigravityInteractionsExecution) Run(ctx context.Context, handler Hand
}
// Initial input for this Run: drain whatever is queued (the prompt on the
- // first Run, or steering input on later Runs).
+ // first Run, or steering input on later Runs). An empty prevID means no turn
+ // has completed yet, so this is the conversation's first turn. (A first turn
+ // that failed leaves prevID empty, so a retried Run is correctly treated as
+ // the first turn again.)
input := e.drainQueue()
- if !started {
- if len(input) == 0 {
+ if len(input) == 0 {
+ if prevID == "" {
return fmt.Errorf("no input messages queued for the initial turn")
}
- e.mu.Lock()
- e.started = true
- e.mu.Unlock()
- } else if len(input) == 0 {
return fmt.Errorf("Run called with no queued input and no work pending")
}
@@ -280,7 +333,9 @@ func (e *antigravityInteractionsExecution) Run(ctx context.Context, handler Hand
return fmt.Errorf("interaction turn failed: %w", err)
}
prevID = res.interactionID
- e.setPrevID(prevID)
+ if err := e.setPrevID(ctx, prevID); err != nil {
+ return err
+ }
for turn := 0; turn < e.harness.cfg.MaxTurns; turn++ {
e.harness.debugTurn(e.conversationID, turn+1, len(res.toolCalls))
@@ -315,10 +370,12 @@ func (e *antigravityInteractionsExecution) Run(ctx context.Context, handler Hand
res, err = e.harness.postTurn(ctx, token, e.harness.newRequest(next, prevID))
if err != nil {
- return fmt.Errorf("resume turn failed: %w", err)
+ return fmt.Errorf("continuation turn failed: %w", err)
}
prevID = res.interactionID
- e.setPrevID(prevID)
+ if err := e.setPrevID(ctx, prevID); err != nil {
+ return err
+ }
}
// Hit the turn cap while still driving tools.
@@ -369,7 +426,7 @@ type userInputStep struct {
Content []textPart `json:"content"`
}
-// toolResultStep is one tool result returned on a resume turn: a flat Step with
+// toolResultStep is one tool result returned on a continuation turn: a flat Step with
// "type":"function_result", the matching call_id, the tool name, and the result
// object under "result".
type toolResultStep struct {
@@ -519,6 +576,14 @@ func (h *AntigravityInteractionsHarness) interactionsURL() string {
interactionsEndpoint, interactionsAPIVersion, cloudProject(), cloudLocation())
}
+// Endpoint returns the Interactions API base endpoint this harness targets
+// (e.g. the prod or autopush host). Exposed so callers/tools can log which
+// backend is in use, since the endpoint is a compile-time constant.
+func Endpoint() string { return interactionsEndpoint }
+
+// APIVersion returns the Interactions API version this harness targets.
+func APIVersion() string { return interactionsAPIVersion }
+
// token returns a bearer access token from the harness's OAuth2 token source.
// The source is resolved once (lazily) and auto-refreshes thereafter.
func (h *AntigravityInteractionsHarness) token(ctx context.Context) (string, error) {
@@ -552,7 +617,7 @@ func newTokenSource(ctx context.Context) (oauth2.TokenSource, error) {
// newRequest builds an interactionRequest common to every turn. The environment
// is always the client-side ("local") environment -- this harness exists to
// execute the agent's built-in env tools locally. Tools are re-declared on every
-// turn so they stay known to the agent across resumes.
+// turn so they stay known to the agent across the turns of the interaction loop.
func (h *AntigravityInteractionsHarness) newRequest(input []any, previousID string) interactionRequest {
var tools []FunctionTool
if h.cfg.ThirdPartyExecutor != nil {
@@ -571,8 +636,93 @@ func (h *AntigravityInteractionsHarness) newRequest(input []any, previousID stri
}
}
-// postTurn POSTs the request and streams the SSE response for one turn.
+// retryableHTTPError marks a transient HTTP response that should be retried.
+// retryAfter is the server-suggested delay (parsed from the Retry-After
+// header), or 0 if none was provided.
+type retryableHTTPError struct {
+ status int
+ retryAfter time.Duration
+ body string
+}
+
+func (e *retryableHTTPError) Error() string {
+ return fmt.Sprintf("HTTP %d: %s", e.status, e.body)
+}
+
+// Retry tuning for transient rate-limit (429) responses. The stateful
+// interaction quota is per-minute, so the backoff must be able to span ~a
+// minute; with these values the cumulative wait reaches ~1-2 minutes before
+// giving up.
+const (
+ rateLimitMaxRetries = 6
+ rateLimitBaseDelay = 2 * time.Second
+ rateLimitMaxDelay = 32 * time.Second
+)
+
+// postTurn POSTs one turn, retrying on HTTP 429 (rate limit / quota) with
+// exponential backoff and jitter, honoring a Retry-After header when present.
+// Creating an interaction is not idempotent, so only 429 -- which is rejected
+// before any interaction is created -- is retried here.
func (h *AntigravityInteractionsHarness) postTurn(ctx context.Context, token string, reqBody interactionRequest) (*turnResult, error) {
+ delay := rateLimitBaseDelay
+ for attempt := 0; ; attempt++ {
+ res, err := h.postTurnOnce(ctx, token, reqBody)
+ if err == nil {
+ return res, nil
+ }
+ var re *retryableHTTPError
+ if !errors.As(err, &re) || attempt >= rateLimitMaxRetries {
+ return nil, err
+ }
+
+ wait := re.retryAfter
+ if wait <= 0 {
+ wait = backoffWithJitter(delay)
+ }
+ fmt.Fprintf(os.Stderr, "[harness] rate limited (HTTP %d); retrying in %s (attempt %d/%d)\n",
+ re.status, wait.Round(time.Millisecond), attempt+1, rateLimitMaxRetries)
+
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(wait):
+ }
+ if delay *= 2; delay > rateLimitMaxDelay {
+ delay = rateLimitMaxDelay
+ }
+ }
+}
+
+// backoffWithJitter returns a randomized delay in [delay/2, delay] to avoid
+// synchronized retries.
+func backoffWithJitter(delay time.Duration) time.Duration {
+ half := delay / 2
+ return half + time.Duration(rand.Int63n(int64(half)+1))
+}
+
+// parseRetryAfter parses a Retry-After header value, which may be either an
+// integer number of seconds or an HTTP date. Returns 0 if absent or unparseable.
+func parseRetryAfter(v string) time.Duration {
+ v = strings.TrimSpace(v)
+ if v == "" {
+ return 0
+ }
+ if secs, err := strconv.Atoi(v); err == nil {
+ if secs <= 0 {
+ return 0
+ }
+ return time.Duration(secs) * time.Second
+ }
+ if t, err := http.ParseTime(v); err == nil {
+ if d := time.Until(t); d > 0 {
+ return d
+ }
+ }
+ return 0
+}
+
+// postTurnOnce POSTs the request and streams the SSE response for one turn.
+func (h *AntigravityInteractionsHarness) postTurnOnce(ctx context.Context, token string, reqBody interactionRequest) (*turnResult, error) {
body, err := json.Marshal(reqBody)
if err != nil {
return nil, err
@@ -595,7 +745,17 @@ func (h *AntigravityInteractionsHarness) postTurn(ctx context.Context, token str
if _, err := b.ReadFrom(resp.Body); err != nil {
return nil, fmt.Errorf("HTTP %d (failed to read error body: %v)", resp.StatusCode, err)
}
- return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, b.String())
+ msg := b.String()
+ // 429 means the request was rejected by quota before any interaction was
+ // created, so it is safe to retry (unlike a partial 5xx). Mark it.
+ if resp.StatusCode == http.StatusTooManyRequests {
+ return nil, &retryableHTTPError{
+ status: resp.StatusCode,
+ retryAfter: parseRetryAfter(resp.Header.Get("Retry-After")),
+ body: msg,
+ }
+ }
+ return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, msg)
}
return h.parseStreamedTurn(resp.Body)
}
diff --git a/internal/harness/antigravityinteractions_test.go b/internal/harness/antigravityinteractions_test.go
new file mode 100644
index 0000000..efb95b8
--- /dev/null
+++ b/internal/harness/antigravityinteractions_test.go
@@ -0,0 +1,222 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package harness
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+
+ "golang.org/x/oauth2"
+)
+
+// fakeInteractions is a fake Interactions API: an http.RoundTripper that records
+// the decoded request body of every POST and replies with a canned SSE stream.
+// It lets the harness's real Start/Run/cursorStore code run end to end while the
+// network is faked, so we can assert exactly what previous_interaction_id the
+// harness sends on each turn.
+type fakeInteractions struct {
+ mu sync.Mutex
+ // requests holds the decoded body of each interaction request, in order.
+ requests []interactionRequest
+ // interactionIDs are returned (in order) as the completed interaction id for
+ // successive turns; the i-th request gets interactionIDs[i].
+ interactionIDs []string
+}
+
+func (f *fakeInteractions) RoundTrip(req *http.Request) (*http.Response, error) {
+ body, err := io.ReadAll(req.Body)
+ if err != nil {
+ return nil, err
+ }
+ var decoded interactionRequest
+ if err := json.Unmarshal(body, &decoded); err != nil {
+ return nil, fmt.Errorf("fake server: decoding request: %w", err)
+ }
+
+ f.mu.Lock()
+ idx := len(f.requests)
+ f.requests = append(f.requests, decoded)
+ id := fmt.Sprintf("INT-%d", idx+1)
+ if idx < len(f.interactionIDs) {
+ id = f.interactionIDs[idx]
+ }
+ f.mu.Unlock()
+
+ // A minimal completed turn: no tool calls, so Run finishes in one turn.
+ sse := "" +
+ "event: interaction.created\n" +
+ `data: {"interaction":{"id":"` + id + `","status":"in_progress"},"event_type":"interaction.created"}` + "\n\n" +
+ "event: interaction.completed\n" +
+ `data: {"interaction":{"id":"` + id + `","status":"completed"},"event_type":"interaction.completed"}` + "\n\n" +
+ "event: done\n" +
+ "data: [DONE]\n\n"
+
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(sse)),
+ Request: req,
+ }, nil
+}
+
+func (f *fakeInteractions) recorded() []interactionRequest {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]interactionRequest(nil), f.requests...)
+}
+
+// newTestHarness builds a harness wired to the fake server, a static token (no
+// ADC), and the given state dir. It also sets the project env so the request URL
+// and X-Goog-User-Project header are well-formed.
+func newTestHarness(t *testing.T, fake *fakeInteractions, stateDir string) *AntigravityInteractionsHarness {
+ t.Helper()
+ t.Setenv(envCloudProject, "test-project")
+ h, err := NewAntigravityInteractionsHarness(AntigravityInteractionsConfig{
+ Agent: "test-agent",
+ StateDir: stateDir,
+ HTTPClient: &http.Client{Transport: fake},
+ TokenSource: oauth2.StaticTokenSource(&oauth2.Token{AccessToken: "fake-token"}),
+ })
+ if err != nil {
+ t.Fatalf("NewAntigravityInteractionsHarness: %v", err)
+ }
+ return h
+}
+
+// runOneTurn starts an Execution for conversationID, queues a single user
+// message, and runs it to completion.
+func runOneTurn(t *testing.T, h *AntigravityInteractionsHarness, conversationID, prompt string) {
+ t.Helper()
+ ctx := context.Background()
+ exec, err := h.Start(ctx, conversationID, nil)
+ if err != nil {
+ t.Fatalf("Start(%q): %v", conversationID, err)
+ }
+ if err := exec.Queue(ctx, userText(prompt)); err != nil {
+ t.Fatalf("Queue: %v", err)
+ }
+ if err := exec.Run(ctx, &mockHandler{}); err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if err := exec.Close(ctx); err != nil {
+ t.Fatalf("Close: %v", err)
+ }
+}
+
+// TestResumeAcrossRestart is the core CUJ: a first Execution starts a new
+// interaction chain (empty previous_interaction_id) and persists the returned
+// interaction id; then a brand-new harness over the SAME state dir (a simulated
+// restart / snapshot restore) loads that cursor and sends it as
+// previous_interaction_id on the next request.
+func TestResumeAcrossRestart(t *testing.T) {
+ fake := &fakeInteractions{interactionIDs: []string{"INT-1", "INT-2"}}
+ stateDir := t.TempDir()
+
+ // First Execution: starts the chain.
+ h1 := newTestHarness(t, fake, stateDir)
+ runOneTurn(t, h1, "conv-1", "hello")
+
+ // Simulated restart: a brand-new harness over the same state dir, so any
+ // resumed state must come from disk, not h1's memory.
+ h2 := newTestHarness(t, fake, stateDir)
+ runOneTurn(t, h2, "conv-1", "again")
+
+ reqs := fake.recorded()
+ if len(reqs) != 2 {
+ t.Fatalf("expected 2 requests, got %d", len(reqs))
+ }
+ if reqs[0].PreviousInteractionID != "" {
+ t.Errorf("turn 1: previous_interaction_id = %q, want empty (new chain)", reqs[0].PreviousInteractionID)
+ }
+ if got, want := reqs[1].PreviousInteractionID, "INT-1"; got != want {
+ t.Errorf("turn 2 (after restart): previous_interaction_id = %q, want %q (resumed from persisted cursor)", got, want)
+ }
+}
+
+// TestNewRequiresStateDir verifies that the constructor rejects an empty
+// StateDir: resume-cursor persistence is required.
+func TestNewRequiresStateDir(t *testing.T) {
+ t.Setenv(envCloudProject, "test-project")
+ _, err := NewAntigravityInteractionsHarness(AntigravityInteractionsConfig{
+ Agent: "test-agent",
+ StateDir: "", // missing
+ TokenSource: oauth2.StaticTokenSource(&oauth2.Token{AccessToken: "fake-token"}),
+ })
+ if err == nil {
+ t.Fatal("NewAntigravityInteractionsHarness with empty StateDir: got nil error, want error")
+ }
+}
+
+// TestSameHarnessSecondTurnResumes checks that even without a "restart", a second
+// Execution on the same harness/conversation continues the chain via the cursor.
+func TestSameHarnessSecondTurnResumes(t *testing.T) {
+ fake := &fakeInteractions{interactionIDs: []string{"INT-1", "INT-2"}}
+ h := newTestHarness(t, fake, t.TempDir())
+
+ runOneTurn(t, h, "conv-1", "hello")
+ runOneTurn(t, h, "conv-1", "again")
+
+ reqs := fake.recorded()
+ if len(reqs) != 2 {
+ t.Fatalf("expected 2 requests, got %d", len(reqs))
+ }
+ if got, want := reqs[1].PreviousInteractionID, "INT-1"; got != want {
+ t.Errorf("turn 2: previous_interaction_id = %q, want %q", got, want)
+ }
+}
+
+// TestCursorStoreLoadSave is a focused unit test of the harness-local cursor
+// store round-trip.
+func TestCursorStoreLoadSave(t *testing.T) {
+ cs, err := newCursorStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("newCursorStore: %v", err)
+ }
+
+ // Missing key: found is false, no error.
+ if _, found, err := cs.load("missing"); err != nil || found {
+ t.Fatalf("load(missing) = found=%v err=%v, want found=false err=nil", found, err)
+ }
+
+ // Round-trip.
+ if err := cs.save("conv-1", resumeCursor{PrevInteractionID: "INT-7"}); err != nil {
+ t.Fatalf("save: %v", err)
+ }
+ cur, found, err := cs.load("conv-1")
+ if err != nil || !found {
+ t.Fatalf("load(conv-1) = found=%v err=%v, want found=true err=nil", found, err)
+ }
+ if cur.PrevInteractionID != "INT-7" {
+ t.Errorf("loaded PrevInteractionID = %q, want %q", cur.PrevInteractionID, "INT-7")
+ }
+
+ // Last-write-wins overwrite.
+ if err := cs.save("conv-1", resumeCursor{PrevInteractionID: "INT-8"}); err != nil {
+ t.Fatalf("save (overwrite): %v", err)
+ }
+ cur, _, err = cs.load("conv-1")
+ if err != nil {
+ t.Fatalf("load after overwrite: %v", err)
+ }
+ if cur.PrevInteractionID != "INT-8" {
+ t.Errorf("after overwrite PrevInteractionID = %q, want %q", cur.PrevInteractionID, "INT-8")
+ }
+}
diff --git a/internal/harness/antigravityinteractions_tools.go b/internal/harness/antigravityinteractions_tools.go
index e565b71..d45ecc0 100644
--- a/internal/harness/antigravityinteractions_tools.go
+++ b/internal/harness/antigravityinteractions_tools.go
@@ -29,13 +29,14 @@ import (
// send back as a function_result step. The built-in environment tools enumerated
// in the switch below (file reads, command execution, and the file-mutation
// family) are executed internally against the local filesystem/shell; every
-// other tool is dispatched to the configured ThirdPartyExecutor. All execution
-// is internal to the harness -- no tool call is surfaced to the caller.
+// other tool is dispatched to the configured ThirdPartyExecutor, or, if none is
+// configured, returned as an error result. All execution is internal to the
+// harness -- no tool call is surfaced to the caller.
//
// Argument names match the agent's tool schema (PascalCase). Mutation tools
-// (move/delete_dir/file_change family) require no success payload -- on success
-// they return an empty result; on failure they return {"error": <message>},
-// which marks the step as failed.
+// (move, delete_dir, create_file, edit_file, multi_edit_file, delete_file)
+// require no success payload -- on success they return an empty result; on
+// failure they return {"error": <message>}, which marks the step as failed.
func (h *AntigravityInteractionsHarness) executeTool(ctx context.Context, call capturedToolCall) any {
switch call.name {
case "view_file":
@@ -70,7 +71,7 @@ func (h *AntigravityInteractionsHarness) executeTool(ctx context.Context, call c
// These run against the actual local filesystem/shell because they ARE the
// client-side environment. Argument names follow the agent's tool schema
// (view_file -> AbsolutePath, run_command -> CommandLine, list_dir ->
-// DirectoryPath), and result field names follow what the proxy maps back into
+// DirectoryPath), and result field names follow what the server maps back into
// the step's own output (content, Output/ExitCode, results).
// ---------------------------------------------------------------------------
diff --git a/internal/harness/cursorstore.go b/internal/harness/cursorstore.go
new file mode 100644
index 0000000..5973113
--- /dev/null
+++ b/internal/harness/cursorstore.go
@@ -0,0 +1,119 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package harness
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+)
+
+// resumeCursor is the small per-conversation state persisted so a conversation
+// can resume across restarts/replicas. It records the tail of the server-side
+// interaction chain (PrevInteractionID).
+//
+// It is a struct (rather than a bare string) so it can grow to hold richer
+// resume state later, e.g. partial function-call results for mid-tool-loop
+// recovery, without changing the on-disk shape's identity.
+type resumeCursor struct {
+ PrevInteractionID string `json:"prev_interaction_id"`
+}
+
+// cursorStore is a minimal filesystem-backed store for resume cursors, local to
+// the Antigravity Interactions harness. Each conversation maps to one file whose
+// contents are the JSON-encoded cursor.
+//
+// It assumes a single writer per conversation (the controller guarantees at most
+// one Execution per conversation), so writes are last-write-wins with no
+// compare-and-swap. Writes are atomic (temp file + rename) so a reader never
+// observes a torn value.
+type cursorStore struct {
+ dir string
+}
+
+// newCursorStore creates a cursorStore rooted at dir, creating it if needed.
+func newCursorStore(dir string) (*cursorStore, error) {
+ if dir == "" {
+ return nil, errors.New("cursorStore dir must not be empty")
+ }
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return nil, fmt.Errorf("creating cursor dir %q: %w", dir, err)
+ }
+ return &cursorStore{dir: dir}, nil
+}
+
+// path maps a conversation id to its cursor file. The id is hashed so arbitrary
+// id strings map to a safe, fixed-length filename.
+func (s *cursorStore) path(conversationID string) string {
+ sum := sha256.Sum256([]byte(conversationID))
+ return filepath.Join(s.dir, hex.EncodeToString(sum[:])+".json")
+}
+
+// load returns the stored cursor for conversationID. found is false if no cursor
+// has been persisted yet; a non-nil error means the lookup itself failed (which
+// callers must not treat as "no cursor").
+func (s *cursorStore) load(conversationID string) (cur resumeCursor, found bool, err error) {
+ blob, err := os.ReadFile(s.path(conversationID))
+ if errors.Is(err, os.ErrNotExist) {
+ return resumeCursor{}, false, nil
+ }
+ if err != nil {
+ return resumeCursor{}, false, fmt.Errorf("reading cursor: %w", err)
+ }
+ if err := json.Unmarshal(blob, &cur); err != nil {
+ return resumeCursor{}, false, fmt.Errorf("decoding cursor: %w", err)
+ }
+ return cur, true, nil
+}
+
+// save durably writes the cursor for conversationID (last-write-wins).
+func (s *cursorStore) save(conversationID string, cur resumeCursor) error {
+ blob, err := json.Marshal(cur)
+ if err != nil {
+ return fmt.Errorf("encoding cursor: %w", err)
+ }
+ return s.atomicWrite(s.path(conversationID), blob)
+}
+
+// atomicWrite writes value to a temp file, fsyncs it, and renames it into place
+// so a reader never observes a partial write.
+func (s *cursorStore) atomicWrite(path string, value []byte) error {
+ tmp, err := os.CreateTemp(s.dir, ".tmp-*")
+ if err != nil {
+ return fmt.Errorf("creating temp file: %w", err)
+ }
+ tmpName := tmp.Name()
+ defer os.Remove(tmpName) // no-op if the rename succeeded
+
+ if _, err := tmp.Write(value); err != nil {
+ tmp.Close()
+ return fmt.Errorf("writing temp file: %w", err)
+ }
+ if err := tmp.Sync(); err != nil {
+ tmp.Close()
+ return fmt.Errorf("syncing temp file: %w", err)
+ }
+ if err := tmp.Close(); err != nil {
+ return fmt.Errorf("closing temp file: %w", err)
+ }
+ if err := os.Rename(tmpName, path); err != nil {
+ return fmt.Errorf("renaming temp file into place: %w", err)
+ }
+ return nil
+}
diff --git a/internal/harness/harness.go b/internal/harness/harness.go
index 6296271..716f016 100644
--- a/internal/harness/harness.go
+++ b/internal/harness/harness.go
@@ -32,6 +32,13 @@ type Handler interface {
}
// Harness represents a service capable of starting execution sessions.
+//
+// Single-writer expectation: the controller must ensure that at most one
+// Execution exists per conversation id at a time. Harness implementations rely
+// on this invariant -- for example, a harness that durably persists
+// per-conversation state may use a last-write-wins store without
+// compare-and-swap, which is correct only because there is a single writer per
+// conversation.
type Harness interface {
// Start initializes a new Execution session for a conversation. harnessConfig
// carries optional per-request harness configuration; it is opaque to the