Agent Executor (AX) is Google's open agentic orchestration runtime
Go
Restructure AX into a general-purpose orchestration layer for agentic tasks
JBDdc4f36cdba64
diff --git a/.dockerignore b/.dockerignoreindex 14a1425..374fce4 100644--- a/.dockerignore+++ b/.dockerignore@@ -1,8 +1,11 @@.git.idea.vscode+.claude*.log-eventlog/tmp/-node_modules/bin/+ax+ax-server+ax-task-runner+ax-controllerdiff --git a/.github/workflows/go.yml b/.github/workflows/go.ymlindex 9130a0d..e68bd2d 100644--- a/.github/workflows/go.yml+++ b/.github/workflows/go.yml@@ -12,9 +12,6 @@# See the License for the specific language governing permissions and# limitations under the License.-# This workflow will build a golang project-# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go-name: Goon:@@ -24,29 +21,13 @@ on:branches: [ "main" ]jobs:-- build:+ build-and-test:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v4- - name: Cache addlicense- id: cache-addlicense- uses: actions/cache@v4- with:- path: ~/go/bin/addlicense- key: ${{ runner.os }}-addlicense-v1.2.0-- - name: Install addlicense- if: steps.cache-addlicense.outputs.cache-hit != 'true'- run: go install github.com/google/[email protected]-- - name: Check license headers- run: |- $(go env GOPATH)/bin/addlicense -check .-- name: Set up Go- uses: actions/setup-go@v4+ uses: actions/setup-go@v5with:go-version-file: go.mod@@ -55,8 +36,12 @@ jobs:go mod tidygit diff --exit-code go.mod go.sum- - name: Build- run: go build -v ./...+ - name: Build local binaries+ run: |+ go build -v ./cmd/ax+ go build -v ./cmd/ax-controller+ go build -v ./cmd/ax-server+ go build -v ./cmd/ax-task-runner- name: Testrun: go test -v ./...diff --git a/.github/workflows/python.yml b/.github/workflows/python.ymldeleted file mode 100644index 135f891..0000000--- a/.github/workflows/python.yml+++ /dev/null@@ -1,51 +0,0 @@-# 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.--# Runs pytest against the antigravity harness sidecar-# (python/antigravity/harness_server_test.py). Split from go.yml so the-# Go workflow stays Go-only and this can evolve independently as more-# Python surface area lands.--name: Python--on:- push:- branches: [ "main" ]- pull_request:- branches: [ "main" ]--jobs:-- test:- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v4-- - name: Set up Python- uses: actions/setup-python@v5- with:- python-version: '3.11'-- - name: Install Python deps- # Runtime deps from python/antigravity/requirements.txt plus test-only- # tooling. Version floors on pytest match the upstream google-antigravity- # SDK's own dev extras (see google-antigravity/antigravity-sdk-python- # pyproject.toml) so this doesn't drift. pytest-timeout is added here- # only -- our tests spin up real gRPC servers on random ports and can hang.- run: pip install -r python/antigravity/requirements.txt 'pytest>=7.0' 'pytest-timeout>=2.0'-- - name: Run Python tests- # --timeout guards against hung gRPC servers so a stuck test can't- # eat the whole workflow budget.- run: python -m pytest python/antigravity/ --timeout=30 --timeout-method=thread -vdiff --git a/.gitignore b/.gitignoreindex fa40af3..22061f5 100644--- a/.gitignore+++ b/.gitignore@@ -1,9 +1,11 @@-bin/*-eventlog/*+# Binaries+bin/+/tmp/+*.exe+*.test/ax-*.log-ax-bin-python/__pycache__-python/proto/__pycache__-__pycache__/-e2e+/ax-server+/ax-task-runner+/ax-controller++cmd/ax-task-runner/__pycache__/antigravity_bootstrap.cpython-313.pycdiff --git a/.ko.yaml b/.ko.yamlindex 0041fed..18e06c8 100644--- a/.ko.yaml+++ b/.ko.yaml@@ -12,4 +12,24 @@# See the License for the specific language governing permissions and# limitations under the License.-defaultBaseImage: gcr.io/distroless/static+defaultBaseImage: cgr.dev/chainguard/static:latest+baseImageOverrides:+ github.com/google/ax/cmd/ax-task-runner: alpine/git:latest+builds:+ - id: ax-controller+ main: ./cmd/ax-controller+ env:+ - CGO_ENABLED=0+ flags:+ - -trimpath+ ldflags:+ - -s -w+ - id: ax-task-runner+ main: ./cmd/ax-task-runner+ env:+ - CGO_ENABLED=0+ flags:+ - -trimpath+ ldflags:+ - -s -w+diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex bb90899..e722b72 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1,140 +1,122 @@-# How to contribute+# How to Contribute-We'd love to accept your patches and contributions to this project. However, please note our current temporary policy below.+We welcome contributions to AX!-> [!IMPORTANT]-> **Temporary Pause on External Contributions**->-> AX is currently undergoing a significant architectural redesign, and the codebase is highly unstable. To ensure we can focus on stabilizing the core framework, we are temporarily **pausing the acceptance of external Pull Requests**.->-> Please do not open Pull Requests at this time, as they are likely to conflict with ongoing changes and may be closed without review. Instead, we encourage you to:-> - Open an **Issue** to propose feature requests or report bugs.-> - Join discussions on existing issues to share your feedback.->-> We will update this guide once the core architecture stabilizes and we are ready to welcome contributions again. Thank you for your understanding and patience!--## Before you begin+## Before You Begin### Sign our Contributor License Agreement-All submissions to this project need to follow Google’s [Contributor-License Agreement (CLA)](https://cla.developers.google.com/about), which-covers any original work of authorship included in the submission. This-doesn't prohibit the use of coding assistance tools, including tool-,-AI-, or machine-generated code, as long as these submissions abide by the-CLA's requirements.+All submissions to this project need to follow Google’s [Contributor License Agreement (CLA)](https://cla.developers.google.com/about), which covers any original work of authorship included in the submission. This doesn't prohibit the use of coding assistance tools, including tool-, AI-, or machine-generated code, as long as these submissions abide by the CLA's requirements.-You (or your employer) retain the copyright to your contribution; this simply-gives us permission to use and redistribute your contributions as part of the-project.+You (or your employer) retain the copyright to your contribution; this simply gives us permission to use and redistribute your contributions as part of the project.-If you or your current employer have already signed the Google CLA (even if it-was for a different project), you probably don't need to do it again.+If you or your current employer have already signed the Google CLA (even if it was for a different project), you probably don't need to do it again. Visit <https://cla.developers.google.com/> to see your current agreements or sign a new one.-Visit <https://cla.developers.google.com/> to see your current agreements or to-sign a new one.+### Community Guidelines-### Review our community guidelines+This project follows [Google's Open Source Community Guidelines](https://opensource.google/conduct/).-This project follows-[Google's Open Source Community Guidelines](https://opensource.google/conduct/).+### Code Reviews-### Code reviews+All submissions, including submissions by project members, require review. We use GitHub pull requests for this purpose. Consult [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more information on using pull requests.-All submissions, including submissions by project members, require review. We-use GitHub pull requests for this purpose. Consult-[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more-information on using pull requests.+----## Contribution workflow+## Development Workflow-### Generate Protobuf Code+### Prerequisites-```bash-make proto-```+- **Go 1.27+**+- **[`ko`](https://ko.build/)** (for building and deploying control plane images)+- **Docker** or **Podman** (for building the Linux task-runner container image)+- A Kubernetes cluster with [Agent Substrate](https://github.com/agent-substrate/substrate) installed++### Building Binaries-### Run Tests+Build all local binaries (`bin/ax`, `bin/ax-controller`, `bin/ax-server`):```bash-make test+make build```-### Install the ax CLI+Or install the `ax` CLI directly into `$(go env GOPATH)/bin`:```bashmake install```-Ensure that $GOPATH/bin is in your $PATH.+Make sure that `$(go env GOPATH)/bin` is on your `$PATH`:```bashexport PATH="$PATH:$(go env GOPATH)/bin"```-If you have the `GOBIN` environment variable set, it will be installed there instead.-Make sure the installation directory is in your `$PATH`.+### Running Tests-To add the default location to your `PATH` for the current session, run:+Run all unit and integration tests (including the mock Substrate gRPC server and API server tests):```bash-export PATH="$PATH:$(go env GOPATH)/bin"-```--### Creating a pull request--First, clone the repo:--```-git clone [email protected]:google/ax.git-```--If you already have cloned the repo locally, make sure that-your main branch is up to date:--```-git checkout main-git pull -q -r origin main+make test```-Check a new feature branch:+Or run via `go test`:-```-git checkout -b my-feature+```bash+go test -v ./...```-Make edits to files, and test them locally. Add the changes (e.g. git add .) to stage.-Commit the changes once you staged the changes:--```-git commit -m "Describe he changes made"-```+### Building the Task Runner Image-Push the branch to the origin and open a pull request:+Cross-compile the task runner for `linux/amd64` and package the container image:+```bash+make build-task-runner```-git push origin my-feature-```--Visit https://github.com/google/ax to open a pull request.--## Troubleshooting--### Outdated table schema--AX is still under heavy development and the database schema is not yet stable. If you encounter errors related to outdated table schemas, you can reset the database by deleting the `eventlog` directory.--An example:+To build and push to a remote container registry:```bash-ax --input "hello"--Error: error creating controller: failed to create event log: sqlite_eventlog: create index exec_checkpoint_id: SQL logic error: no such column: checkpoint_id (1)+make push-task-runner TASK_RUNNER_REPO=gcr.io/<your-project>/ax-task-runner```-Delete the `eventlog` directory and try again.+### Deploying to Kubernetes++Deploy Redis, controller, and server components to your cluster in the `ax-system` namespace:```bash-rm -rf ./eventlog-```+make deploy AX_IMAGE_REPO=gcr.io/<your-project>/ax-images+```++---++## Creating a Pull Request++1. **Fork or Clone the Repository**:+ ```bash+ git clone [email protected]:rakyll/ax2.git+ cd ax2+ ```++2. **Ensure `main` is up to date**:+ ```bash+ git checkout main+ git pull -r origin main+ ```++3. **Create a feature branch**:+ ```bash+ git checkout -b my-feature+ ```++4. **Make changes and verify**:+ - Run tests: `make test`+ - Ensure clean modules: `go mod tidy` and verify with `git diff --exit-code go.mod go.sum`+ - Build binaries: `make build`++5. **Commit and open a PR**:+ ```bash+ git add .+ git commit -m "feat: describe your changes"+ git push origin my-feature+ ```+ Open a pull request on GitHub describing the motivation and changes.diff --git a/DESIGN.md b/DESIGN.mdnew file mode 100644index 0000000..055c357--- /dev/null+++ b/DESIGN.md@@ -0,0 +1,90 @@+# AX Design++## Architecture++Storing millions of short-lived tasks as Kubernetes CRDs pushes etcd past its comfort zone (single-digit GB storage limits, write-rate bottlenecks, control plane degradation). AX keeps its state in Redis and uses Redis Streams as the work queue between the API server and a horizontally scaled pool of controllers.++```+ ax apply -f task.yaml+ │+ ▼+ ax-server+ (gRPC API + /healthz)+ │+ store & publish event+ │+ ▼+ Redis+ (Task Hashes + Event Streams + PubSub)+ │+ XREADGROUP (Streams)+ │+ ▼+ ax-controller+ (Horizontally Scaled Workers)+ │+ gRPC (Control API)+ │+ ▼+ Agent Substrate+ ┌───────────────────────────────┐+ │ • Atespace Provisioning │+ │ • Actor Creation & Activation │+ │ • Worker Assignment │+ │ • Egress Policy Filtering │+ └───────────────────────────────┘+```++## Components++| Binary | Role |+|---|---|+| `ax` | Developer CLI. Applies manifests, inspects and watches resources, tunnels to the cluster. |+| `ax-server` | Stateless gRPC API on port 8080. Validates manifests, persists to Redis, publishes events. |+| `ax-controller` | Reconciliation workers. Consume the Redis stream, provision atespaces and actors on Agent Substrate, apply egress policy, and drive tasks toward desired state. Scale by adding replicas. |+| `ax-task-runner` | Entrypoint inside every task container. Bootstraps the workspace, serves metadata, and runs the agent command. A thin wrapper over the `runner` package, which custom images can embed directly. |++## API reference++The control plane exposes the `ax.v1alpha1.AX` gRPC service. Health checks are plain HTTP: `GET /healthz` on the same port returns `200 OK`.++**Tasks**++| RPC | Description |+|---|---|+| `GetTask` | Get a task by atespace and name. |+| `ListTasks` | List tasks in an atespace, with pagination. |+| `UpdateTask` | Create or update a task. |+| `DeleteTask` | Delete a task. |+| `SuspendTask` | Checkpoint actor state and pause the task. |+| `ResumeTask` | Resume a suspended task. |+| `WatchTask` | Server-streaming RPC that emits status and condition transitions as they happen. |++**Gateways**++| RPC | Description |+|---|---|+| `GetGateway` | Get a gateway by atespace and name. |+| `ListGateways` | List gateways in an atespace. |+| `UpdateGateway` | Create or update a gateway. |+| `DeleteGateway` | Delete a gateway. |++**Workspaces**++| RPC | Description |+|---|---|+| `GetWorkspace` | Get a workspace by atespace and name. |+| `ListWorkspaces` | List workspaces in an atespace. |+| `UpdateWorkspace` | Create or update a workspace. |+| `DeleteWorkspace` | Delete a workspace. |++**Models**++| RPC | Description |+|---|---|+| `GetModel` | Get a model configuration by atespace and name. |+| `ListModels` | List model configurations in an atespace. |+| `UpdateModel` | Create or update a model configuration. |+| `DeleteModel` | Delete a model configuration. |++Request and response types follow the `<Method>Request` / `<Method>Response` convention. Generated Go types live in [`pkg/apis/v1alpha1`](pkg/apis/v1alpha1).diff --git a/ax.yaml b/Dockerfile.task-runnersimilarity index 55%rename from ax.yamlrename to Dockerfile.task-runnerindex 41b2104..29dc3e1 100644--- a/ax.yaml+++ b/Dockerfile.task-runner@@ -12,23 +12,20 @@# See the License for the specific language governing permissions and# limitations under the License.-# Sample LOCAL configuration for the AX *harness* build (compiled with -tags=harness).-# Usage: ax serve --config ax.yaml-# ax --config ax.yaml --input "hello" # uses default harness (antigravity)-version: v1alpha+FROM python:3.12-slim-server:- address: ":8494"+RUN apt-get update && apt-get install -y --no-install-recommends \+ git \+ curl \+ ca-certificates \+ openssh-client \+ procps \+ bash \+ && rm -rf /var/lib/apt/lists/*-eventlog:- sqlite:- filename: "eventlog/log.sqlite"+RUN pip install --no-cache-dir google-antigravity-antigravity: {}+COPY bin/linux_amd64/ax-task-runner /usr/local/bin/ax-task-runner+COPY cmd/ax-task-runner/antigravity_bootstrap.py /usr/local/bin/antigravity_bootstrap.py-registry:- antigravity-interactions: {}--telemetry:- otlp:- enabled: true+ENTRYPOINT ["/usr/local/bin/ax-task-runner"]diff --git a/LICENSE b/LICENSEindex 261eeb9..d645695 100644--- a/LICENSE+++ b/LICENSE@@ -1,3 +1,4 @@+Apache LicenseVersion 2.0, January 2004http://www.apache.org/licenses/diff --git a/Makefile b/Makefileindex 189a2b8..cdfac40 100644--- a/Makefile+++ b/Makefile@@ -1,64 +1,97 @@-.PHONY: all build proto test test-python clean install deps clean-logs+# 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.-# Build all binaries-all: proto build+SHELL := /bin/bash-# Build binaries-build:- @echo "Building ax..."+# Configuration+AX_IMAGE_REPO ?= gcr.io/ax-substrate/ate-images+TASK_RUNNER_REPO ?= $(AX_IMAGE_REPO)/ax-task-runner+CONTAINER_CLI ?= $(shell which podman 2>/dev/null || which docker 2>/dev/null)++.PHONY: all build build-binaries build-task-runner install push push-task-runner deploy deploy-controller deploy-server deploy-redis apply-example test clean++all: build++## --------------------------------------+## Build Targets+## --------------------------------------++# Build all local binaries (ax CLI, controller, server)+build: build-binaries++build-binaries:+ @echo "==> Building local binaries (ax, ax-controller, ax-server)..."@mkdir -p bin- @go build -o bin/ax ./cmd/ax- @echo "Build complete!"---# Generate protobuf code-proto:- @echo "Generating protobuf code..."- @export PATH=$$PATH:$$(go env GOPATH)/bin && \- protoc --go_out=. --go_opt=paths=source_relative \- --go-grpc_out=. --go-grpc_opt=paths=source_relative \- proto/ax.proto proto/content.proto- @python3 -m grpc_tools.protoc -I. --python_out=python --grpc_python_out=python proto/ax.proto proto/content.proto- @$$(go env GOPATH)/bin/addlicense -l apache python/proto/*.py- @echo "Protobuf generation complete!"--# Run Go tests-test:- @echo "Running Go tests..."- @go test -v ./...--# Run Python tests for the antigravity harness sidecar.-# Assumes deps are installed for the same interpreter as `python3`, e.g.:-# python3 -m pip install -r python/antigravity/requirements.txt \-# 'pytest>=7.0' 'pytest-timeout>=2.0'-# --timeout guards against hung gRPC servers.-test-python:- @echo "Running Python tests..."- @python3 -m pytest python/antigravity/ --timeout=30 --timeout-method=thread--# Clean build artifacts-clean:- @echo "Cleaning..."- @rm -rf bin/- @rm -rf eventlog/- @echo "Clean complete!"+ go build -trimpath -ldflags="-s -w" -o bin/ax ./cmd/ax+ go build -trimpath -ldflags="-s -w" -o bin/ax-controller ./cmd/ax-controller+ go build -trimpath -ldflags="-s -w" -o bin/ax-server ./cmd/ax-server-# Install ax to GOPATH/bin+# Install the ax CLI into $(go env GOPATH)/bininstall:- @echo "Installing ax..."- @go install ./cmd/ax- @echo "Install complete!"--# Install dependencies-deps:- @echo "Installing dependencies..."- @go mod download- @go install google.golang.org/protobuf/cmd/protoc-gen-go@latest- @go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest- @go install github.com/google/addlicense@latest- @echo "Dependencies installed!"--clean-logs:- @echo "Cleaning the event logs..."- rm -rf ./eventlog- mkdir ./eventlog+ @echo "==> Installing ax CLI to $$(go env GOPATH)/bin..."+ go install -trimpath -ldflags="-s -w" ./cmd/ax++# Cross-compile ax-task-runner for Linux amd64 and build container image with Python, Antigravity, and git/curl+build-task-runner:+ @echo "==> Cross-compiling ax-task-runner for linux/amd64..."+ @mkdir -p bin/linux_amd64+ GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o bin/linux_amd64/ax-task-runner ./cmd/ax-task-runner+ @echo "==> Building container image $(TASK_RUNNER_REPO):latest using $(CONTAINER_CLI)..."+ $(CONTAINER_CLI) build --platform linux/amd64 -t $(TASK_RUNNER_REPO):latest -f Dockerfile.task-runner .++# Push task-runner container image to registry+push-task-runner: build-task-runner+ @echo "==> Pushing task runner image to $(TASK_RUNNER_REPO):latest..."+ $(CONTAINER_CLI) push $(TASK_RUNNER_REPO):latest+ @echo "==> Current pushed digest:"+ @gcloud container images list-tags $(TASK_RUNNER_REPO) --filter="tags=latest" --format="get(digest)"++# Build and push all images+push: push-task-runner++## --------------------------------------+## Deployment Targets+## --------------------------------------++# Deploy all AX components to Kubernetes (Redis, ax-controller, ax-server)+deploy: deploy-redis deploy-controller deploy-server++deploy-redis:+ @echo "==> Deploying Redis to ax-system namespace..."+ kubectl apply -f deploy/redis.yaml++deploy-controller:+ @echo "==> Building and deploying ax-controller using ko..."+ KO_DOCKER_REPO=$(AX_IMAGE_REPO) ko apply -f deploy/ax-controller.yaml++deploy-server:+ @echo "==> Building and deploying ax-server using ko..."+ KO_DOCKER_REPO=$(AX_IMAGE_REPO) ko apply -f deploy/ax-server.yaml++# Apply example task and resources+apply-example:+ @echo "==> Applying example task and resources using bin/ax..."+ ./bin/ax apply -f examples/task.yaml++## --------------------------------------+## Test & Verification Targets+## --------------------------------------++test:+ @echo "==> Running tests..."+ go test -v ./...++clean:+ @echo "==> Cleaning build artifacts..."+ rm -rf bin/diff --git a/README.md b/README.mdindex 44e94b6..27e2202 100644--- a/README.md+++ b/README.md@@ -1,335 +1,185 @@-# Agent Executor (AX)+<h1>+ <img src="assets/axolotl.svg" width="70" align="absmiddle" alt="AX axolotl">+ AX+</h1>> [!WARNING]-> 🚧 **AX is in active early development.**->-> We are actively refining our core, resumption protocols,-> and runtime specifications, which will introduce major breaking+> We are still actively refining our core concepts, protocols,+> and specifications. We will likely to introduce major breaking> changes prior to a stable release.->-> **Temporary Policy:** We are temporarily pausing the acceptance of external Pull Requests while we stabilize the core architecture. We warmly encourage you to open Issues for feedback and feature requests instead.--AX, short for Agent Executor, is a distributed harness runtime.-It dynamically provisions isolated environments from suspendable/resumable-images to execute harnesses and agents.-AX is designed for reliability, with native support for recovery-and execution resumption, even in distributed setups.--## Features--- **Distributed Runtime**: Harnesses, skills, tools, and agents can execute in isolation-- **Resumption**: Automatic recovery from failures or interruptions-- **Built-in Harnesses**: Support for frontier harnesses and custom implementations-- **Portability**: Runs anywhere, scales to small and large deployments-- **Customizability**: Bring custom environment, MCP tools, skills, instructions, and more--Built-in consistency and resumability features:-- **Single-Writer Architecture**: Single controller ensures consistent state management-- **Event Log**: Durable execution state with automatic recovery-- **Advanced Resumption**: Support for compute-layer actor resumption on compatible platforms--## Demo--[](https://www.youtube.com/watch?v=L5Iw1IrZ6Nc)--Watch our demo to see AX works when deployed on [Agent Substrate](https://github.com/agent-substrate/substrate).--## Overview--```mermaid-%%{init: {"flowchart": {"diagramPadding": 80}}}%%-graph LR- Client-- subgraph Cluster[" "]- Server["AX Server<br/>(multi-tenant)"]- DB["Event Log <br/>Storage"]- ControlService["Agent Substrate"]- Actor["AX Agent or Harness<br/>(session-tenant)"]- end-- SnapshotService["Snapshots"]- Models- MCPServer["MCP server"]-- Client <-->|resumable stream| Server- Server <-->|scan/append| DB- Server --> ControlService- ControlService -->|resume/suspend| Actor- Server <-->|resumable stream| Actor- ControlService <-->|read/write| SnapshotService- Actor -.-> Models- Actor --> MCPServer-```--As agents evolve from simple assistants to autonomous long running workers,-developers need a robust runtime to manage state, ensure reliability,-and audit execution. As we are moving away from monolithic agents towards-distributed harnesses where tools, skills and agents are deployed as-isolated actors, a distributed runtime with dynamically spawned isolated-workers becomes a necessity. AX provides the foundational layer to fill these gaps.--While compute-agnostic, AX is aiming to provide the best-experience on Kubernetes.--We expect every sophisticated agentic application will need the-capabilities provided by AX.-We are building this layer as a widely available foundation,-enabling developers to focus on building their applications rather-than infrastructure. We decided to build this project in public to-validate every design decision before a stable release is cut.-We highly encourage you to give us feedback.-## Installation+**Declare an agentic task with workspaces and gateway specifications. AX sandboxes it, wires up its workspace, fences its network, and helps running it at scale.**-Install the ax CLI directly from the repository:+AX is a high-throughput, declarative orchestrator to run billions of autonomous agent workloads in a cluster. It runs on top of [Agent Substrate](https://github.com/agent-substrate/substrate) for sandboxed execution and is built to run billions of tasks per cluster. If you have used Kubernetes, `ax` will feel similar.-```bash-go install github.com/google/ax/cmd/ax@latest+```yaml+# task.yaml+apiVersion: ax.io/v1alpha1+kind: Workspace+metadata:+ name: golang+spec:+ git:+ - repo: https://github.com/golang/go.git+ branch: "my-fix"+---+apiVersion: ax.io/v1alpha1+kind: Task+metadata:+ name: test+spec:+ workspaces:+ - name: golang+ goal: "Ensure that Go tool chain is available and is built from source"+ debug: true # lets you `ax ssh` into the sandbox```-### Verify Installation--Check that ax is installed correctly:+Then apply it, watch it come up, and look over the agent's shoulder:```bash-ax --help+ax apply -f task.yaml+ax watch task test+ax ssh test -- ls -al /workspace```-You should see the ax CLI usage information.+## Why?-### Kubernetes+Agents are a new kind of workload. They are neither stateless microservices nor run-to-completion batch jobs. They accumulate state, need strict isolation, call out to model APIs and tool servers, and can burn money in a loop if nobody is watching. AX gives you four small primitives that handle all of that declaratively:-AX is natively supported on-[Agent Substrate](https://github.com/agent-substrate/substrate)-on Kubernetes and it's the recommended deployment option for production-use. For more details on setup and configuration, see the-[deployment guide](./manifests/README.md).-Read more about [this new layer](https://cloud.google.com/blog/products/containers-kubernetes/bringing-you-agent-sandbox-on-gke-and-agent-substrate)-that provides higher density to agentic workloads on Kubernetes.+| You want to... | AX gives you |+|---|---|+| Run untrusted agent code in an isolated sandbox with CPU/memory limits | **`Task`** |+| Pre-wire Git repos, MCP servers, and skill packages so every agent starts warm | **`Workspace`** |+| Lock outbound traffic down to an explicit host allowlist | **`Gateway`** |+| Configure which LLM the platform itself uses, with credentials from a Kubernetes secret | **`Model`** |+| Pause an idle agent and pick up exactly where it left off | `ax suspend` / `ax resume` |+| Shell into a running agent to see what it is doing | `ax ssh` |-## Authentication+Everything is expressed as `ax.io/v1alpha1` manifests and applied with a single command.-The built-in Antigravity harness supports Google AI Studio and Vertex AI.+## Quick start-For Google AI Studio, set a Gemini API key:+### 1. Install the CLI```bash-export GEMINI_API_KEY="your-api-key"+go install github.com/google/ax/cmd/ax@latest```-For Vertex AI, configure Application Default Credentials and the target project-and location:+This puts the `ax` binary in `$(go env GOPATH)/bin`. Make sure that directory is on your `PATH`.-```bash-gcloud auth application-default login-export GOOGLE_CLOUD_PROJECT="your-project-id"-export GOOGLE_CLOUD_LOCATION="us-central1"-export GOOGLE_GENAI_USE_VERTEXAI=true-```+### 2. Deploy the control plane-## Quickstart--The CLI starts the built-in Antigravity harness automatically. No separate harness server setup is required.+You need a Kubernetes cluster, [`ko`](https://ko.build/) (`brew install ko`), a container registry your cluster can pull from, and a reachable Agent Substrate Control API (in-cluster default: `api.ate-system.svc.cluster.local:443`).```bash-# Using the checked-in ax.yaml, which sets Antigravity as the default harness.-ax --input "Can you list this directory?"--# Executing with an AX server-ax --input "Can you list this directory?" --server localhost:8494+make deploy AX_IMAGE_REPO=<your-registry>```-Conversations can be continued any time:+This deploys Redis, then builds and deploys the control plane images with `ko`. Everything lands in the `ax-system` namespace.-```bash-ax --conversation d85a4b4e-c53b-4c84-b879-f10d905bce40 \- --input "Show me the contents of README.md"-```--Instead of running the default harness, you can start executing-any registered harness:+### 3. Run your first task```bash-ax --input "Can you write me a simple HTTP server in Python?"+ax apply -f examples/task.yaml # Task + Workspace + Gateway + Model in one file+ax get tasks+# NAME ATESPACE PHASE ACTOR WORKER-IP AGE+# task123 default Running task123 10.20.3.67 1m++ax watch task task123 # stream phase and condition changes live+ax ssh task123 -- ls -la /workspace # poke around inside the sandbox+ax suspend task task123 # checkpoint and pause+ax resume task task123 # pick up where it left off```-If anything goes wrong during the execution of a harness,-you can resume an incomplete execution in a conversation:-```bash-ax --conversation edf98ef5-4bb1-4a9e-a091-3a77e03727e6 --resume-```+Want to see the whole lifecycle end to end? Run [`./demo.sh`](demo.sh). It applies a custom workspace, waits for readiness, runs commands over `ax ssh`, and suspends the task.+## Documentation-## Usage+| Guide | Read it to... |+|---|---|+| [Concepts](docs/concepts.md) | Learn what a `Task`, `Workspace`, `Gateway`, and `Model` each do, and how a task moves through phases and conditions. |+| [Manifests](docs/manifests.md) | Write your own YAML, with an annotated example of every kind. |+| [Sandbox](docs/sandbox.md) | See what the runner does on boot and what your command can rely on: metadata server, guest services, environment. |+| [Runners](docs/runner.md) | Understand the contract between the control plane and the task container, and build your own runner image to replace the default. |+| [Networking](docs/networking.md) | Reach a running task through the atenet router from the cluster, your laptop, or a gRPC client. |+| [Architecture](DESIGN.md) | Understand how the control plane fits together, plus the [API reference](DESIGN.md#api-reference). |+| [Development](docs/development.md) | Build, test, and ship changes to AX itself. |-Execute a new conversation or resume an existing one. If no conversation ID is provided, a new UUID will be generated.--```bash-ax \- [--input <text>] \- [--conversation <id>] \- [--agent <id>] \- [--agent-config <json>] \- [--agent-config-file <file.json>] \- [--server <address>] \- [--config <file>] \- [--resume]-```+## CLI usage-Options:-- `--agent`: Agent ID (optional, default agent is used if not specified)-- `--agent-config`: Per-request agent configuration as an inline JSON string (mutually exclusive with `--agent-config-file`)-- `--agent-config-file`: Path to a JSON file with per-request agent configuration-- `--config`: Path to YAML configuration file (only used with a local built-in AX server) (default "ax.yaml")-- `--conversation`: Conversation ID (optional, generates UUID if not provided)-- `--input`: Input message to send (optional)-- `--resume`: Resume a conversation without inputs-- `--server`: gRPC controller server address (if specified, connects to remote server; otherwise runs with a local built-in AX server)+`ax` talks to the control plane over gRPC. It is deliberately `kubectl`-shaped: `apply`, `get`, `describe`, `watch`, `delete`, plus a few agent-specific verbs.-**Examples:**+### Everyday commands```bash-# Execute a new execution-ax --input "Hello agents!"--# Resume an existing execution with new input-ax --conversation a53d4db3-1165-4925-87da-be6c72bbdeb1 --input "Ok, now let's do something else..."--# Execute using server mode-ax --server localhost:8494 --input "Hello agents!"--# Execute with per-request agent config-ax --agent-config '{"system_instructions":"Answer in one sentence.","model":"gemini-3.5-flash"}' \- --input "Explain durable execution."--# To keep the same JSON in a file, use `--agent-config-file` instead:-ax --agent-config-file antigravity.json --input "Explain durable execution."+# Apply anything (multi-document YAML, file or stdin)+ax apply -f examples/task.yaml++# Tasks+ax get tasks # list+ax get tasks -a my-atespace # list in another atespace+ax get task task123 # full spec + live status as YAML+ax describe task task123 # human-readable detail+ax watch task task123 # stream status and condition transitions+ax suspend task task123 # checkpoint actor state and pause+ax resume task task123 # resume a suspended task+ax delete task task123++# Shell into the running sandbox+ax ssh task123 # interactive shell (task needs spec.debug: true)+ax ssh task123 -- ls -la /workspace # one-off command+ax ssh task123 -- python3 main.py++# Gateways, workspaces, models follow the same pattern+ax get gateways+# NAME ATESPACE LISTENERS EGRESS-HOSTS+# default-gateway default 8494/gRPC,8080/HTTP *+ax describe gateway default-gateway+ax delete gateway default-gateway++ax get workspaces+# NAME ATESPACE GIT-REPOS MCP-SERVERS+# default-workspace default 1 1+ax describe workspace default-workspace+ax delete workspace default-workspace++ax get models+# NAME ATESPACE PROVIDER MODEL+# default-model default google gemini-3.8-flash+ax describe model default-model+ax delete model default-model++# Connection plumbing+ax ctx # active kube context and how ax is reaching the control plane+ax tunnel list # background tunnels (state lives in ~/.ax/tunnels)+ax tunnel stop+ax version```-### Serve+### Works with `kubectx`-Run the AX controller as a gRPC server. Loads configuration from a YAML file (default: ax.yaml).+`ax` follows your active Kubernetes context. Switch clusters and `ax` resolves and tunnels to that cluster's control plane in the background.```bash-ax serve [--config <path>]-```+kubectx staging-cluster+ax get tasks-Options:-- `--config`: Path to YAML configuration file (default "ax.yaml")+kubectx prod-cluster+ax get tasks-Example configuration file (`ax.yaml`):-```yaml-version: v1alpha--server:- address: ":8494"--eventlog:- sqlite:- filename: "eventlog/log.sqlite"+# Or target a context without switching+ax --context=dev-cluster get tasks```-Example:-```bash-# Start server with default config (ax.yaml)-ax serve--# Start server with custom config-ax serve --config my-config.yaml-```--## Extensions--### Harnesses--AX provides built-in harnesses (e.g. Antigravity) but you can bring your-own harness implementation by implementing `HarnessService`. On supported-compute services (e.g. Agent Substrate), AX automatically runs the-harness in isolation with automatic resumption and suspension.--Traditional agents (e.g. tool use or workflow agents), or-language models can be implemented as harnesses.--### Skills--Built-in harnesses like Antigravity includes built-in support for-Agent Skills. See [Skills](examples/skills) for more.--### MCP Tools--Built-in harnesses like Antigravity provides support for discovering-and making calls to MCP tools when they are configured.--## What AX is NOT?-* A managed service. AX is self-hosted and not a managed service.- We aim to make it easy for users to deploy and operate it on- their Kubernetes clusters.-* An agentic framework. AX is agnostic of the framework used- to build agents.--## Roadmap--Below is an overview of our upcoming features and planned changes:--1. Support for elicitation-1. Improvements to resumption protocols-1. Trajectory exposition-1. Better telemetry exposition-1. Integrations with Google registries, networking policies, and more-1. Introduction of a `FilesystemService` for file system operations--## Contributing--Please refer to the [CONTRIBUTING.md](CONTRIBUTING.md) guide for instructions-on how to contribute to this project.--We are currently undergoing a significant architectural redesign, and external contributions are temporarily paused.-However, in the meantime, we warmly encourage you to file bugs and-send feature requests.--## History--Over the years, teams across Google built and operated several-distributed execution engines. As these systems evolved, certain-architectural patterns consistently stood the test of time.-The teams realized they were repeatedly solving similar-orchestration problems, prompting the push to extract these-lessons into common runtime layer.--While this common layer was taking shape, the AI landscape underwent-a massive shift. Applications were transitioning from-statless tool use agents to autonomous, long-running, self improving-agents that often need isolated resumable execution environments.-Also, from an efficiency standpoint, agentic workloads are inherently bursty.-An agent might compute intensively for a minute, then sit idle for-hours or days awaiting human approval. Keeping a stateful actor active-during these long idle periods is highly inefficient and cost-prohibitive-at scale.-Over the last 10 years, Kubernetes has become the standard for-large scale job orchestration, but it was fundamentally designed for-stateless microservices or predictable batch jobs ---not for suspending and resuming stateful, sandboxed agent actors.--Driven by these dual challenges, we decided to build a robust, common-agentic orchestrator designed specifically for the new compute-layers we are developing on Kubernetes. Our goal is to ease-the productionization of agents, allowing developers-and researchers to focus on building and evaluating their-applications rather than dealing with underlying infrastructure.--AX is developed and maintained by the team actively working on-Google's internal runtime. Although the two projects operate-at different layers today, we are applying our knowledge-and insights to AX in the public domain every day.--## Acknowledgements+### Global flags-We thank Google DeepMind for their earlier work in distributed harnesses which-heavily influenced AX.-We thank the Google Kubernetes Engine team for their deep contributions-regarding isolation, resumption and job scheduling.+| Flag | Description | Default |+|---|---|---|+| `-a`, `--atespace` | Atespace scope for the command | `default` |+| `-n`, `--namespace` | Kubernetes namespace where AX is installed | `ax-system` |+| `--context` | Kubernetes context to target | active `kubectx` / `current-context` |+| `--server` | Control plane address, bypassing auto-detection | derived from kube context, or `$AX_SERVER` |## License-Apache 2.0+Apache License 2.0. See [LICENSE](LICENSE) for details.diff --git a/assets/axolotl-mono.svg b/assets/axolotl-mono.svgnew file mode 100644index 0000000..93d25b1--- /dev/null+++ b/assets/axolotl-mono.svg@@ -0,0 +1,26 @@+<svg xmlns="http://www.w3.org/2000/svg" width="150" height="100" viewBox="5 35 150 100" role="img" aria-label="AX single-color axolotl logo">+ <title>AX — one color</title>+ <style>+ svg:root { color: #432B41; }+ @media (prefers-color-scheme: dark) {+ svg:root { color: #FFF4F7; }+ }+ </style>+ <defs>+ <mask id="ax-face" maskUnits="userSpaceOnUse" x="0" y="0" width="160" height="160" style="mask-type:luminance">+ <rect width="160" height="160" fill="white" />+ <g>+ <circle cx="64" cy="86" r="4.7" fill="black" />+ <circle cx="96" cy="86" r="4.7" fill="black" />+ <path d="M73 101 Q80 109 87 101" fill="none" stroke="black" stroke-width="3.8" stroke-linecap="round" stroke-linejoin="round" />+ </g>+ </mask>+ </defs>+ <g mask="url(#ax-face)">+ <path d="M47 66 L29 48 M42 82 L18 73 M45 99 L23 104" fill="none" stroke="currentColor" stroke-width="15" stroke-linecap="round" stroke-linejoin="round" />+ <g transform="translate(160 0) scale(-1 1)">+ <path d="M47 66 L29 48 M42 82 L18 73 M45 99 L23 104" fill="none" stroke="currentColor" stroke-width="15" stroke-linecap="round" stroke-linejoin="round" />+ </g>+ <path d="M80 48 C54 48 35 67 35 90 C35 114 53 130 80 130 C107 130 125 114 125 90 C125 67 106 48 80 48 Z" fill="currentColor" />+ </g>+</svg>diff --git a/assets/axolotl.svg b/assets/axolotl.svgnew file mode 100644index 0000000..70a1fd5--- /dev/null+++ b/assets/axolotl.svg@@ -0,0 +1,19 @@+<svg xmlns="http://www.w3.org/2000/svg" width="150" height="100" viewBox="5 35 150 100" role="img" aria-label="AX axolotl logo">+ <title>AX</title>+ <g>+ <path d="M47 66 L29 48 M42 82 L18 73 M45 99 L23 104" fill="none" stroke="#F15B85" stroke-width="15" stroke-linecap="round" stroke-linejoin="round" />+ <g transform="translate(160 0) scale(-1 1)">+ <path d="M47 66 L29 48 M42 82 L18 73 M45 99 L23 104" fill="none" stroke="#F15B85" stroke-width="15" stroke-linecap="round" stroke-linejoin="round" />+ </g>+ <path d="M80 48 C54 48 35 67 35 90 C35 114 53 130 80 130 C107 130 125 114 125 90 C125 67 106 48 80 48 Z" fill="#FFAAC0" />+ </g>+ <g>+ <ellipse cx="53" cy="101" rx="7" ry="4" fill="#F77FA3" />+ <ellipse cx="107" cy="101" rx="7" ry="4" fill="#F77FA3" />+ </g>+ <g>+ <circle cx="64" cy="86" r="4.7" fill="#432B41" />+ <circle cx="96" cy="86" r="4.7" fill="#432B41" />+ <path d="M73 101 Q80 109 87 101" fill="none" stroke="#432B41" stroke-width="3.8" stroke-linecap="round" stroke-linejoin="round" />+ </g>+</svg>diff --git a/cmd/ax-controller/main.go b/cmd/ax-controller/main.gonew file mode 100644index 0000000..9d1020e--- /dev/null+++ b/cmd/ax-controller/main.go@@ -0,0 +1,111 @@+// 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 main++import (+ "context"+ "flag"+ "log/slog"+ "os"+ "os/signal"+ "syscall"++ "github.com/google/ax/internal/controller"+ "github.com/google/ax/internal/store/redis"+ "github.com/google/ax/internal/substrate"+ goredis "github.com/redis/go-redis/v9"+)++func main() {+ var (+ substrateEndpoint string+ substrateAuthority string+ substrateTokenFile string+ substrateCAFile string+ substrateInsecureTLS bool+ substratePlaintext bool+ defaultTemplate string+ defaultTemplateAtespace string+ redisAddr string+ redisPassword string+ redisGroup string+ redisConsumer string+ )++ flag.StringVar(&redisAddr, "redis-addr", "localhost:6379", "Redis server address (e.g. localhost:6379)")+ flag.StringVar(&redisPassword, "redis-password", "", "Redis password")+ flag.StringVar(&redisGroup, "redis-group", "ax-controllers", "Redis stream consumer group")+ flag.StringVar(&redisConsumer, "redis-consumer", "", "Redis stream consumer ID (defaults to hostname)")+ flag.StringVar(&substrateEndpoint, "substrate-endpoint", "api.ate-system.svc.cluster.local:443", "Agent Substrate Control API endpoint")+ flag.StringVar(&substrateAuthority, "substrate-authority", "api.ate-system.svc", "Authority / TLS ServerName for Substrate endpoint")+ flag.StringVar(&substrateTokenFile, "substrate-token-file", "", "Path to bearer token file for Substrate auth")+ flag.StringVar(&substrateCAFile, "substrate-ca-file", "", "Path to CA PEM file for Substrate TLS")+ flag.BoolVar(&substrateInsecureTLS, "substrate-insecure-tls", false, "Skip Substrate TLS verification")+ flag.BoolVar(&substratePlaintext, "substrate-plaintext", false, "Use insecure plaintext gRPC connection to Substrate")+ flag.StringVar(&defaultTemplate, "template", "default-template", "Default Substrate ActorTemplate name")+ flag.StringVar(&defaultTemplateAtespace, "template-atespace", "ax-system", "Default Substrate ActorTemplate atespace")+ flag.Parse()++ if envRedis := os.Getenv("REDIS_ADDR"); envRedis != "" {+ redisAddr = envRedis+ }+ if envPass := os.Getenv("REDIS_PASSWORD"); envPass != "" && redisPassword == "" {+ redisPassword = envPass+ }++ logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))+ slog.SetDefault(logger)++ slog.Info("starting ax-controller",+ "redisAddr", redisAddr,+ "group", redisGroup,+ "substrateEndpoint", substrateEndpoint,+ "authority", substrateAuthority,+ "templateAtespace", defaultTemplateAtespace,+ "template", defaultTemplate,+ )++ subClient, err := substrate.NewClientWithOptions(substrate.ClientOptions{+ Target: substrateEndpoint,+ Authority: substrateAuthority,+ TokenFile: substrateTokenFile,+ CAFile: substrateCAFile,+ InsecureTLS: substrateInsecureTLS,+ Plaintext: substratePlaintext,+ })+ if err != nil {+ slog.Error("failed to initialize substrate client", "error", err)+ os.Exit(1)+ }+ defer subClient.Close()++ reconciler := controller.NewTaskReconciler(subClient, defaultTemplate, defaultTemplateAtespace)++ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer cancel()++ rClient := goredis.NewClient(&goredis.Options{+ Addr: redisAddr,+ Password: redisPassword,+ })+ defer rClient.Close()++ rStore := redis.NewStore(rClient, redis.Options{})+ worker := controller.NewWorker(rStore, reconciler, redisGroup, redisConsumer)+ if err := worker.Run(ctx); err != nil && err != context.Canceled {+ slog.Error("redis worker stopped with error", "error", err)+ os.Exit(1)+ }+}diff --git a/cmd/ax-server/main.go b/cmd/ax-server/main.gonew file mode 100644index 0000000..8e1a98e--- /dev/null+++ b/cmd/ax-server/main.go@@ -0,0 +1,92 @@+// 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 main++import (+ "context"+ "flag"+ "log/slog"+ "net/http"+ "os"+ "os/signal"+ "syscall"+ "time"++ "github.com/google/ax/internal/server"+ "github.com/google/ax/internal/store/redis"+ goredis "github.com/redis/go-redis/v9"+)++func main() {+ var (+ listenAddr string+ redisAddr string+ redisPassword string+ )++ flag.StringVar(&listenAddr, "addr", ":8080", "HTTP listen address")+ flag.StringVar(&redisAddr, "redis-addr", "localhost:6379", "Redis server address")+ flag.StringVar(&redisPassword, "redis-password", "", "Redis password")+ flag.Parse()++ if envAddr := os.Getenv("ADDR"); envAddr != "" {+ listenAddr = envAddr+ }+ if envRedis := os.Getenv("REDIS_ADDR"); envRedis != "" {+ redisAddr = envRedis+ }+ if envPass := os.Getenv("REDIS_PASSWORD"); envPass != "" {+ redisPassword = envPass+ }++ logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))+ slog.SetDefault(logger)++ slog.Info("starting ax-server", "listenAddr", listenAddr, "redisAddr", redisAddr)++ rClient := goredis.NewClient(&goredis.Options{+ Addr: redisAddr,+ Password: redisPassword,+ })+ defer rClient.Close()++ rStore := redis.NewStore(rClient, redis.Options{})+ srv := server.NewServer(rStore)++ httpServer := &http.Server{+ Addr: listenAddr,+ Handler: srv.Handler(),+ }+ httpServer.Protocols = new(http.Protocols)+ httpServer.Protocols.SetHTTP1(true)+ httpServer.Protocols.SetUnencryptedHTTP2(true)++ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer cancel()++ go func() {+ if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {+ slog.Error("HTTP server failed", "error", err)+ os.Exit(1)+ }+ }()++ <-ctx.Done()+ slog.Info("shutting down ax-server")++ shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer shutdownCancel()+ _ = httpServer.Shutdown(shutdownCtx)+}diff --git a/cmd/ax-task-runner/antigravity_bootstrap.py b/cmd/ax-task-runner/antigravity_bootstrap.pynew file mode 100644index 0000000..600870b--- /dev/null+++ b/cmd/ax-task-runner/antigravity_bootstrap.py@@ -0,0 +1,129 @@+# 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.++"""Prepare an AX workspace with the Antigravity agent.++Usage:+ antigravity_bootstrap.py --goal "<goal>" [--workspace DIR] [--data-dir DIR]++The agent is confined to the workspace directory: the process changes into it,+the agent's file tools are restricted to it, and agent state is kept outside it+in --data-dir when given.++The caller (ax-task-runner) owns the overall timeout and only invokes this script+when a goal is set and GEMINI_API_KEY is present. The API key is read from the+environment only, never from a flag, so it does not show up in process listings.+Exits non-zero on failure so the caller can log it; the caller decides whether to+continue.+"""++import argparse+import asyncio+import logging+import os+import sys++logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")++API_KEY_ENV = "GEMINI_API_KEY"+DEFAULT_WORKSPACE = "/workspace"++SYSTEM_INSTRUCTIONS = (+ "You are the AX Antigravity workspace setup agent. Your job is to initialize the "+ "workspace at {workspace_dir} and prepare it for developer or task execution "+ "according to the declared goal. The current working directory is the workspace. "+ "Run all commands from there and only create or modify files inside it; do not touch "+ "paths outside the workspace."+)+++def parse_args(argv: list[str]) -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ prog="antigravity_bootstrap.py",+ description="Prepare an AX workspace with the Antigravity agent.",+ )+ parser.add_argument(+ "--goal",+ default="",+ help="What the agent should set the workspace up for. If empty, the script exits without running the agent.",+ )+ parser.add_argument(+ "--workspace",+ default=DEFAULT_WORKSPACE,+ help=f"Workspace directory the agent operates in (default: {DEFAULT_WORKSPACE}).",+ )+ parser.add_argument(+ "--data-dir",+ default="",+ help="Where the agent keeps its own state, outside the workspace. Omit to use the SDK default.",+ )+ return parser.parse_args(argv)+++async def run_bootstrap(goal: str, workspace_dir: str, data_dir: str) -> None:+ from google.antigravity import Agent, CapabilitiesConfig, LocalAgentConfig+ from google.antigravity.hooks import policy++ config_kwargs = dict(+ workspaces=[workspace_dir],+ capabilities=CapabilitiesConfig(),+ # Deny file tools outside the workspace; allow everything else (including+ # run_command, which the SDK denies by default). Denies take priority.+ policies=[*policy.workspace_only([workspace_dir]), policy.allow_all()],+ api_key=os.environ[API_KEY_ENV],+ system_instructions=SYSTEM_INSTRUCTIONS.format(workspace_dir=workspace_dir),+ )+ if data_dir:+ os.makedirs(data_dir, exist_ok=True)+ config_kwargs["save_dir"] = data_dir+ config_kwargs["app_data_dir"] = data_dir++ async with Agent(LocalAgentConfig(**config_kwargs)) as agent:+ logging.info("Antigravity agent started in %s; dispatching goal prompt", workspace_dir)+ prompt = (+ f"Set up the workspace directory {workspace_dir} (your current working directory) "+ f"according to the following goal: {goal}"+ )+ response = await agent.chat(prompt)+ reply_text = await response.text()+ logging.info("Antigravity workspace setup completed with response:")+ print(reply_text)+++def main(argv: list[str]) -> int:+ args = parse_args(argv)+ workspace_dir = os.path.abspath(args.workspace)++ if not args.goal:+ logging.info("No goal provided for Antigravity workspace bootstrap; skipping")+ return 0+ if not os.environ.get(API_KEY_ENV):+ logging.error("%s is not set; cannot run Antigravity workspace bootstrap", API_KEY_ENV)+ return 1+ if not os.path.isdir(workspace_dir):+ logging.error("Workspace directory %s does not exist", workspace_dir)+ return 1++ os.chdir(workspace_dir)+ logging.info("Starting Antigravity workspace bootstrap in %s with goal: %s", workspace_dir, args.goal)+ try:+ asyncio.run(run_bootstrap(args.goal, workspace_dir, args.data_dir))+ except Exception:+ logging.exception("Antigravity workspace setup failed")+ return 1+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/cmd/ax-task-runner/main.go b/cmd/ax-task-runner/main.gonew file mode 100644index 0000000..e94564e--- /dev/null+++ b/cmd/ax-task-runner/main.go@@ -0,0 +1,146 @@+// 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.++// Command ax-task-runner is the entrypoint of every AX task container. It+// loads the Task and Workspace specs and hands them to the runner package,+// which does everything else.+//+// The controller delivers the Task as YAML in AX_TASK_YAML and the bound+// Workspaces as a multi-document YAML stream in AX_WORKSPACES_YAML. For local+// runs the specs can be read from files instead with --task-file and one or+// more --workspace-file flags.+package main++import (+ "context"+ "errors"+ "flag"+ "fmt"+ "io"+ "log/slog"+ "os"+ "os/signal"+ "strings"+ "syscall"++ "github.com/google/ax/pkg/apis/v1alpha1"+ "github.com/google/ax/runner"+ "gopkg.in/yaml.v3"+)++// stringList collects a repeatable flag.+type stringList []string++func (l *stringList) String() string { return strings.Join(*l, ",") }+func (l *stringList) Set(v string) error { *l = append(*l, v); return nil }++func main() {+ var (+ cfg runner.Config+ taskFile string+ wsFiles stringList+ )+ flag.IntVar(&cfg.Port, "port", runner.DefaultPort, "Port for the metadata and guest server")+ flag.StringVar(&taskFile, "task-file", "", "Read the Task YAML from this file instead of AX_TASK_YAML")+ flag.Var(&wsFiles, "workspace-file", "Read Workspace YAML from this file instead of the environment; repeatable, and each file may hold several documents")+ flag.Parse()++ logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))+ slog.SetDefault(logger)++ var task v1alpha1.Task+ if err := loadSpec(taskFile, "AX_TASK_YAML", &task); err != nil {+ fatal(err)+ } else if task.GetMetadata() != nil {+ cfg.Task = &task+ }++ workspaces, err := loadWorkspaces(wsFiles)+ if err != nil {+ fatal(err)+ }+ cfg.Workspaces = workspaces++ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer stop()++ if err := runner.Run(ctx, cfg); err != nil {+ fatal(err)+ }+}++// loadSpec decodes YAML into out from file when set, otherwise from the named+// environment variable. It is not an error for neither to be present.+func loadSpec(file, envVar string, out any) error {+ var raw []byte+ switch {+ case file != "":+ data, err := os.ReadFile(file)+ if err != nil {+ return fmt.Errorf("reading %s: %w", file, err)+ }+ raw = data+ case os.Getenv(envVar) != "":+ raw = []byte(os.Getenv(envVar))+ default:+ return nil+ }+ if err := yaml.Unmarshal(raw, out); err != nil {+ return fmt.Errorf("parsing %T: %w", out, err)+ }+ return nil+}++// loadWorkspaces reads Workspace documents from the given files, or when none+// are given from AX_WORKSPACES_YAML. Empty documents are skipped. It is not an+// error for no source to be present.+func loadWorkspaces(files []string) ([]*v1alpha1.Workspace, error) {+ var sources [][]byte+ switch {+ case len(files) > 0:+ for _, f := range files {+ data, err := os.ReadFile(f)+ if err != nil {+ return nil, fmt.Errorf("reading %s: %w", f, err)+ }+ sources = append(sources, data)+ }+ case os.Getenv("AX_WORKSPACES_YAML") != "":+ sources = append(sources, []byte(os.Getenv("AX_WORKSPACES_YAML")))+ }++ var workspaces []*v1alpha1.Workspace+ for _, src := range sources {+ dec := yaml.NewDecoder(strings.NewReader(string(src)))+ for {+ var ws v1alpha1.Workspace+ err := dec.Decode(&ws)+ if errors.Is(err, io.EOF) {+ break+ }+ if err != nil {+ return nil, fmt.Errorf("parsing workspace yaml: %w", err)+ }+ if ws.GetMetadata() != nil {+ workspaces = append(workspaces, &ws)+ }+ }+ }+ return workspaces, nil+}++func fatal(err error) {+ slog.Error("task runner failed", "error", err)+ os.Exit(1)+}diff --git a/cmd/ax/Dockerfile b/cmd/ax/Dockerfiledeleted file mode 100644index 7a505cd..0000000--- a/cmd/ax/Dockerfile+++ /dev/null@@ -1,101 +0,0 @@-# 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.--# Multi-target AX image build:-# --target antigravity : python:3.13-slim + the Antigravity Python sidecar-# (SDK, localharness, agent). Used by the antigravity-# harness actor (`ax harness antigravity`).-# --target ax : debian:stable-slim + the Go `ax` binary. Used by-# the ax-server (`ax serve`) and the Go interactions-# harness actor (`ax harness antigravity-interactions`).-#-# Build context: repository root. Images target the cluster's linux/amd64 nodes,-# so build with `--platform linux/amd64`.-# For a standalone build:-# docker build --platform linux/amd64 --target antigravity -f cmd/ax/Dockerfile -t <ref> . && docker push <ref>-# docker build --platform linux/amd64 --target ax -f cmd/ax/Dockerfile -t <ref> . && docker push <ref>--# --- Stage 1: build the ax Go binary ------------------------------------------FROM --platform=$BUILDPLATFORM golang:1.26 AS build-ARG TARGETOS=linux-ARG TARGETARCH=amd64-WORKDIR /src-COPY go.mod go.sum ./-RUN go mod download-COPY . .-RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \- go build -o /out/ax ./cmd/ax--# --- antigravity image --------FROM python:3.13-slim AS antigravity-WORKDIR /workspace--RUN apt-get update \- && apt-get install -y --no-install-recommends \- ca-certificates \- curl \- less \- procps \- wget \- && rm -rf /var/lib/apt/lists/*--# Antigravity runtime deps, installed from PyPI at build time.-COPY python/antigravity/requirements.txt /tmp/requirements.txt-RUN pip install --no-cache-dir -r /tmp/requirements.txt--# Python sidecar (with generated proto stubs), the agent it serves, and the ax-# binary built in stage 1.-COPY python/ /ax-app/python--# You can copy skills or use skills managers (e.g. npx skills)-# to download them into the image.-# Example: COPY examples/skills/ /ax/skills/--ENV SKILLS_DIR=/ax/skills-COPY --from=build /out/ax /ax-app/ax--# `from python.proto import ...` needs /ax-app on the path; the generated stubs do-# `from proto import ...`, which needs /ax-app/python.-ENV PYTHONPATH=/ax-app:/ax-app/python--# Flush stdout/stderr immediately so server logs surface in container logs.-ENV PYTHONUNBUFFERED=1--EXPOSE 80--# Default command for local docker runs. Substrate ignores the image CMD and runs-# the ActorTemplate `command` instead. `ax harness` forks the Python sidecar,-# which serves the HarnessService on :80.-CMD ["/ax-app/ax", "harness", \- "--host", "0.0.0.0", "--port", "80"]--# --- ax image (Go-only) for the interactions harness and ax-server ------------FROM debian:stable-slim AS ax-WORKDIR /workspace--RUN apt-get update \- && apt-get install -y --no-install-recommends \- ca-certificates \- curl \- less \- procps \- wget \- && rm -rf /var/lib/apt/lists/*--COPY --from=build /out/ax /ax-app/ax--EXPOSE 80--CMD ["/ax-app/ax", "harness", "antigravity-interactions", \- "--host", "0.0.0.0", "--port", "80"]diff --git a/cmd/ax/agentconfig.go b/cmd/ax/agentconfig.godeleted file mode 100644index 398f2d9..0000000--- a/cmd/ax/agentconfig.go+++ /dev/null@@ -1,138 +0,0 @@-// 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 main--import (- "bytes"- "encoding/json"- "errors"- "fmt"- "os"- "strings"-- "github.com/google/ax/cmd/ax/internal"-)--// runConfigMenu shows the /config menu and returns the (possibly updated) config.-// An updated config is sent on subsequent requests.-func runConfigMenu(d *internal.Display, agentConfig []byte) ([]byte, error) {- for {- action, err := d.PromptForConfigAction()- if err != nil {- if errors.Is(err, internal.ErrUserAborted) {- return agentConfig, nil // Esc/Ctrl+C on the menu cancels /config.- }- return agentConfig, err- }-- switch action {- case "edit":- cfg, done, err := editAgentConfig(d, agentConfig)- if err != nil {- return agentConfig, err- }- if done {- return cfg, nil- }- case "load":- cfg, done, err := loadAgentConfig(d)- if err != nil {- return agentConfig, err- }- if done {- return cfg, nil- }- default: // "cancel" or anything else- return agentConfig, nil- }- }-}--// editAgentConfig opens the JSON editor pre-filled with the current config. It-// returns the updated config with done=true if the config was updated, or-// done=false (config ignored) if the user cancelled back to the menu. Invalid-// JSON is reported and the editor re-opens with the user's draft so they can fix-// it.-func editAgentConfig(d *internal.Display, agentConfig []byte) ([]byte, bool, error) {- draft := prettyAgentConfig(agentConfig)- for {- edited, err := d.PromptForConfigEdit(draft)- if err != nil {- if errors.Is(err, internal.ErrUserAborted) {- return nil, false, nil // Back to the menu.- }- return nil, false, err- }- normalized, err := normalizeAgentConfigJSON(edited)- if err != nil {- d.ShowNotice(fmt.Sprintf("Invalid config: %v", err))- draft = edited // Preserve the user's input so they can fix it.- continue- }- return normalized, true, nil- }-}--// loadAgentConfig lets the user pick a JSON file and loads it. It returns the-// loaded config with done=true, or done=false (config ignored) if the user-// cancelled back to the menu or the file could not be used.-func loadAgentConfig(d *internal.Display) ([]byte, bool, error) {- path, err := d.PromptForConfigFile()- if err != nil {- if errors.Is(err, internal.ErrUserAborted) {- return nil, false, nil // Back to the menu.- }- return nil, false, err- }- b, err := os.ReadFile(strings.TrimSpace(path))- if err != nil {- d.ShowNotice(fmt.Sprintf("Failed to read file: %v", err))- return nil, false, nil- }- normalized, err := normalizeAgentConfigJSON(string(b))- if err != nil {- d.ShowNotice(fmt.Sprintf("Invalid config: %v", err))- return nil, false, nil- }- return normalized, true, nil-}--// normalizeAgentConfigJSON trims and validates the given JSON config, returning-// the bytes to send on the wire. Empty input clears the config (returns nil). The-// config must be a JSON object.-func normalizeAgentConfigJSON(s string) ([]byte, error) {- s = strings.TrimSpace(s)- if s == "" {- return nil, nil- }- var obj map[string]any- if err := json.Unmarshal([]byte(s), &obj); err != nil {- return nil, err- }- return []byte(s), nil-}--// prettyAgentConfig returns an indented JSON rendering of the config bytes for-// display, falling back to the raw bytes if they cannot be parsed.-func prettyAgentConfig(b []byte) string {- if len(b) == 0 {- return ""- }- var buf bytes.Buffer- if err := json.Indent(&buf, b, "", " "); err != nil {- return string(b)- }- return buf.String()-}diff --git a/cmd/ax/agentconfig_test.go b/cmd/ax/agentconfig_test.godeleted file mode 100644index fd10bcb..0000000--- a/cmd/ax/agentconfig_test.go+++ /dev/null@@ -1,81 +0,0 @@-// 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 main--import (- "strings"- "testing"-)--func TestNormalizeAgentConfigJSON(t *testing.T) {- tests := []struct {- name string- in string- want string- wantErr bool- }{- {name: "empty", in: "", want: ""},- {name: "whitespace clears", in: " \n\t ", want: ""},- {name: "valid object", in: `{"model":"gemini"}`, want: `{"model":"gemini"}`},- {name: "trims surrounding whitespace", in: " {\"model\":\"gemini\"}\n", want: `{"model":"gemini"}`},- {name: "nested object", in: `{"a":{"b":1},"c":[1,2]}`, want: `{"a":{"b":1},"c":[1,2]}`},- {name: "invalid json", in: `{bad}`, wantErr: true},- {name: "non-object array", in: `[1,2,3]`, wantErr: true},- {name: "non-object scalar", in: `42`, wantErr: true},- }- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got, err := normalizeAgentConfigJSON(tt.in)- if tt.wantErr {- if err == nil {- t.Fatalf("expected error, got nil (result %q)", got)- }- return- }- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if string(got) != tt.want {- t.Errorf("got %q, want %q", got, tt.want)- }- if tt.want == "" && got != nil {- t.Errorf("expected nil for cleared config, got %q", got)- }- })- }-}--func TestPrettyAgentConfig(t *testing.T) {- if got := prettyAgentConfig(nil); got != "" {- t.Errorf("nil: got %q, want empty string", got)- }- if got := prettyAgentConfig([]byte{}); got != "" {- t.Errorf("empty: got %q, want empty string", got)- }-- // Invalid JSON falls back to the raw bytes.- if got := prettyAgentConfig([]byte("not json")); got != "not json" {- t.Errorf("invalid: got %q, want raw passthrough", got)- }-- // Valid JSON is rendered multi-line and indented.- got := prettyAgentConfig([]byte(`{"model":"gemini"}`))- if !strings.Contains(got, "model") || !strings.Contains(got, "gemini") {- t.Errorf("valid: got %q, want it to contain the key and value", got)- }- if !strings.Contains(got, "\n") {- t.Errorf("valid: got %q, want indented multi-line output", got)- }-}diff --git a/cmd/ax/doctor.go b/cmd/ax/doctor.godeleted file mode 100644index 77f89c5..0000000--- a/cmd/ax/doctor.go+++ /dev/null@@ -1,251 +0,0 @@-// 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 main--import (- "errors"- "fmt"- "io"- "net"- "os"- "os/exec"- "path/filepath"- "runtime"- "strconv"- "strings"- "syscall"- "time"-- "charm.land/lipgloss/v2"- "github.com/google/ax/internal/config"- "github.com/spf13/cobra"-)--var doctorEndpoint string--var doctorCmd = &cobra.Command{- Use: "doctor",- Short: "Diagnose and display health of the AX runtime, sidecar process, and system metrics",- Long: `Display the current diagnostic status of:-- Python sidecar process (PID, CPU, Memory RSS, Uptime, Command)-- gRPC harness endpoint connectivity-- AX config/assets directory status-- Go runtime memory and goroutines`,- SilenceUsage: true,- RunE: func(cmd *cobra.Command, args []string) error {- printStatus(os.Stdout, doctorEndpoint)- return nil- },-}--func init() {- doctorCmd.Flags().StringVar(&doctorEndpoint, "endpoint", "127.0.0.1:50053", "Harness gRPC endpoint to monitor")-}--// Stats holds the sampled metrics and state of the AX system.-type Stats struct {- Timestamp time.Time- AssetsDir string- SidecarPID int- SidecarAlive bool- SidecarCPU string- SidecarRSS string- SidecarUptime string- SidecarCmd string- Endpoint string- EndpointActive bool- PythonVersion string- GoVersion string- NumGoroutine int- MemAllocMB float64- NumAssetsFiles int- AssetsSizeKB int64-}--// Sampler collects status of the AX runtime and Python sidecar.-type Sampler struct {- endpoint string-}--// NewSampler creates a new Sampler for the given endpoint.-func NewSampler(endpoint string) *Sampler {- if endpoint == "" {- endpoint = "127.0.0.1:50053"- }- return &Sampler{- endpoint: endpoint,- }-}--// Sample collects current metrics from the system.-func (s *Sampler) Sample() Stats {- st := Stats{- Timestamp: time.Now(),- Endpoint: s.endpoint,- GoVersion: runtime.Version(),- NumGoroutine: runtime.NumGoroutine(),- }-- var m runtime.MemStats- runtime.ReadMemStats(&m)- st.MemAllocMB = float64(m.Alloc) / (1024 * 1024)-- // 1. Assets dir- assetsDir, err := config.AXAssetsDir()- if err == nil {- st.AssetsDir = assetsDir- if entries, err := os.ReadDir(assetsDir); err == nil {- st.NumAssetsFiles = len(entries)- for _, e := range entries {- if info, err := e.Info(); err == nil {- st.AssetsSizeKB += info.Size() / 1024- }- }- }-- pidFile := filepath.Join(assetsDir, "sidecar.pid")- if data, err := os.ReadFile(pidFile); err == nil {- if pid, err := strconv.Atoi(strings.TrimSpace(string(data))); err == nil && pid > 0 {- st.SidecarPID = pid- st.SidecarAlive = isProcessAlive(pid)- }- }- }-- // 2. Sidecar process details if alive- if st.SidecarAlive && st.SidecarPID > 0 {- out, err := exec.Command("ps", "-p", strconv.Itoa(st.SidecarPID), "-o", "%cpu,rss,etime,command").Output()- if err == nil {- lines := strings.Split(strings.TrimSpace(string(out)), "\n")- if len(lines) >= 2 {- fields := strings.Fields(lines[1])- if len(fields) >= 4 {- st.SidecarCPU = fields[0] + "%"- if rssKB, err := strconv.ParseFloat(fields[1], 64); err == nil {- st.SidecarRSS = fmt.Sprintf("%.1f MB", rssKB/1024)- } else {- st.SidecarRSS = fields[1] + " KB"- }- st.SidecarUptime = fields[2]- st.SidecarCmd = strings.Join(fields[3:], " ")- }- }- }- }-- // 3. Check endpoint connectivity- conn, err := net.DialTimeout("tcp", s.endpoint, 120*time.Millisecond)- if err == nil {- st.EndpointActive = true- _ = conn.Close()- }-- // 4. Python version- if out, err := exec.Command("python3", "--version").Output(); err == nil {- st.PythonVersion = strings.TrimSpace(string(out))- } else {- st.PythonVersion = "python3 not found"- }-- return st-}--func isProcessAlive(pid int) bool {- if pid <= 0 {- return false- }- proc, err := os.FindProcess(pid)- if err != nil {- return false- }- err = proc.Signal(syscall.Signal(0))- return err == nil || errors.Is(err, syscall.EPERM)-}--// Display handles plain text rendering of AX runtime metrics using bold labels and headers.-type Display struct {- w io.Writer- styleBold lipgloss.Style- styleTitle lipgloss.Style-}--// NewDisplay creates a new Display writer.-func NewDisplay(w io.Writer) *Display {- if w == nil {- w = os.Stdout- }-- return &Display{- w: w,- styleBold: lipgloss.NewStyle().Bold(true),- styleTitle: lipgloss.NewStyle().Bold(true),- }-}--// Render formats and prints the system status in plain bold text.-func (d *Display) Render(stats Stats) {- var b strings.Builder-- b.WriteString(d.styleTitle.Render("ax doctor") + " (" + stats.Timestamp.Format("2006-01-02 15:04:05 MST") + ")\n\n")-- b.WriteString(d.styleBold.Render("Sidecar:") + "\n")- if stats.SidecarAlive {- b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Status:")), "RUNNING"))- b.WriteString(fmt.Sprintf(" %s %d\n", d.styleBold.Render(fmt.Sprintf("%-14s", "PID:")), stats.SidecarPID))- if stats.SidecarCPU != "" {- b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "CPU:")), stats.SidecarCPU))- }- if stats.SidecarRSS != "" {- b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Memory (RSS):")), stats.SidecarRSS))- }- if stats.SidecarUptime != "" {- b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Elapsed Time:")), stats.SidecarUptime))- }- if stats.SidecarCmd != "" {- b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Command:")), stats.SidecarCmd))- }- } else {- b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Status:")), "STOPPED"))- b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "PID:")), "none"))- }-- endpointStatus := stats.Endpoint- if stats.EndpointActive {- endpointStatus += " (ACTIVE)"- } else {- endpointStatus += " (UNREACHABLE)"- }- b.WriteString(fmt.Sprintf(" %s %s\n\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Endpoint:")), endpointStatus))-- b.WriteString(d.styleBold.Render("Assets:") + "\n")- b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Assets Dir:")), stats.AssetsDir))- b.WriteString(fmt.Sprintf(" %s %d files (%d KB)\n\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Asset Files:")), stats.NumAssetsFiles, stats.AssetsSizeKB))-- b.WriteString(d.styleBold.Render("Environment:") + "\n")- b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Python:")), stats.PythonVersion))- b.WriteString(fmt.Sprintf(" %s %s\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Go Runtime:")), stats.GoVersion))- b.WriteString(fmt.Sprintf(" %s %d\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Goroutines:")), stats.NumGoroutine))- b.WriteString(fmt.Sprintf(" %s %.2f MB\n", d.styleBold.Render(fmt.Sprintf("%-14s", "Go Memory:")), stats.MemAllocMB))-- fmt.Fprint(d.w, b.String())-}--// printStatus samples the system and renders the output to w.-func printStatus(w io.Writer, endpoint string) {- sampler := NewSampler(endpoint)- stats := sampler.Sample()- display := NewDisplay(w)- display.Render(stats)-}diff --git a/cmd/ax/doctor_test.go b/cmd/ax/doctor_test.godeleted file mode 100644index 8994ddd..0000000--- a/cmd/ax/doctor_test.go+++ /dev/null@@ -1,147 +0,0 @@-// 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 main--import (- "bytes"- "net"- "os"- "os/exec"- "path/filepath"- "strconv"- "strings"- "testing"-)--func TestDoctorCommandRegistration(t *testing.T) {- cmd, _, err := rootCmd.Find([]string{"doctor"})- if err != nil {- t.Fatalf("failed to find 'doctor' subcommand: %v", err)- }- if cmd.Name() != "doctor" {- t.Fatalf("expected subcommand name 'doctor', got '%s'", cmd.Name())- }-- if endpointFlag := cmd.Flags().Lookup("endpoint"); endpointFlag == nil {- t.Errorf("expected --endpoint flag on doctor command")- }-}--func TestSampler_NoSidecar(t *testing.T) {- tmpDir := t.TempDir()- t.Setenv("AX_DURABLE_DIR", tmpDir)-- sampler := NewSampler("127.0.0.1:0")- stats := sampler.Sample()-- if stats.SidecarAlive {- t.Errorf("expected SidecarAlive to be false, got true")- }- if stats.SidecarPID != 0 {- t.Errorf("expected SidecarPID to be 0, got %d", stats.SidecarPID)- }- if stats.AssetsDir != filepath.Join(tmpDir, ".ax") {- t.Errorf("expected AssetsDir %s, got %s", filepath.Join(tmpDir, ".ax"), stats.AssetsDir)- }-}--func TestSampler_WithActiveProcessAndEndpoint(t *testing.T) {- tmpDir := t.TempDir()- t.Setenv("AX_DURABLE_DIR", tmpDir)-- cmd := exec.Command("sleep", "10")- if err := cmd.Start(); err != nil {- t.Fatalf("failed to start sleep process: %v", err)- }- defer func() {- _ = cmd.Process.Kill()- _ = cmd.Wait()- }()-- axDir := filepath.Join(tmpDir, ".ax")- if err := os.MkdirAll(axDir, 0755); err != nil {- t.Fatalf("failed to create axDir: %v", err)- }- if err := os.WriteFile(filepath.Join(axDir, "sidecar.pid"), []byte(strconv.Itoa(cmd.Process.Pid)+"\n"), 0644); err != nil {- t.Fatalf("failed to write pid file: %v", err)- }-- l, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- t.Fatalf("failed to listen: %v", err)- }- defer l.Close()-- sampler := NewSampler(l.Addr().String())- stats := sampler.Sample()-- if !stats.SidecarAlive {- t.Errorf("expected SidecarAlive to be true")- }- if stats.SidecarPID != cmd.Process.Pid {- t.Errorf("expected SidecarPID %d, got %d", cmd.Process.Pid, stats.SidecarPID)- }- if !stats.EndpointActive {- t.Errorf("expected EndpointActive to be true")- }-}--func TestDisplay_Render(t *testing.T) {- var buf bytes.Buffer- display := NewDisplay(&buf)-- stats := Stats{- AssetsDir: "/test/assets",- SidecarPID: 1234,- SidecarAlive: true,- SidecarCPU: "0.5%",- SidecarRSS: "45.2 MB",- SidecarUptime: "02:15",- SidecarCmd: "python3 -m test",- Endpoint: "127.0.0.1:50053",- PythonVersion: "Python 3.13.0",- GoVersion: "go1.26.3",- NumGoroutine: 5,- MemAllocMB: 12.4,- }-- display.Render(stats)- output := buf.String()-- if !strings.Contains(output, "ax doctor") {- t.Errorf("expected output to contain 'ax doctor'")- }- if !strings.Contains(output, "1234") {- t.Errorf("expected output to contain PID '1234'")- }- if !strings.Contains(output, "RUNNING") {- t.Errorf("expected output to contain 'RUNNING'")- }- if !strings.Contains(output, "Assets:") {- t.Errorf("expected output to contain 'Assets:'")- }- if !strings.Contains(output, "Environment:") {- t.Errorf("expected output to contain 'Environment:'")- }-}--func TestPrintStatus(t *testing.T) {- var buf bytes.Buffer- printStatus(&buf, "127.0.0.1:0")-- if buf.Len() == 0 {- t.Errorf("expected non-empty printStatus output")- }-}diff --git a/cmd/ax/exec.go b/cmd/ax/exec.godeleted file mode 100644index 33623f2..0000000--- a/cmd/ax/exec.go+++ /dev/null@@ -1,526 +0,0 @@-// 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 main--import (- "context"- "errors"- "fmt"- "io"- "os"- "os/signal"- "strings"- "sync"- "syscall"- "time"-- "github.com/google/ax/cmd/ax/internal"- "github.com/google/ax/cmd/ax/internal/cliutil"- "github.com/google/ax/proto"- "github.com/google/uuid"- "github.com/spf13/cobra"-)--var (- execConversationID string- execAgentID string- execAgentConfigFile string- execAgentConfig string- execInput string- execServerAddr string- execConfigFile string- execResume bool // allow resuming an execution without inputs-)--var execCmd = &cobra.Command{- Use: "exec",- Short: "Execute a conversation or resume an existing one",- Long: `Execute a new conversation or resume an existing one.-If no conversation ID is provided, a new UUID will be generated.`,- SilenceUsage: true,- RunE: runExec,-}--func registerExecFlags(cmd *cobra.Command) {- cmd.Flags().StringVar(&execConversationID, "conversation", "", "Conversation ID (optional, generates UUID if not provided)")- cmd.Flags().StringVar(&execAgentID, "agent", "", "Agent ID (optional, default agent is used if not specified)")- cmd.Flags().StringVar(&execAgentConfigFile, "agent-config-file", "", "Path to a JSON file with per-request agent configuration")- cmd.Flags().StringVar(&execAgentConfig, "agent-config", "", "Per-request agent configuration as an inline JSON string (mutually exclusive with --agent-config-file)")- cmd.Flags().StringVar(&execInput, "input", "", "Input message to send (optional)")- cmd.Flags().StringVar(&execServerAddr, "server", "", "gRPC controller server address (if specified, connects to remote server; otherwise runs with a local built-in AX server)")- cmd.Flags().StringVar(&execConfigFile, "config", "ax.yaml", "Path to YAML configuration file (only used with a local built-in AX server)")- cmd.Flags().BoolVar(&execResume, "resume", false, "Resume a conversation without inputs")- cmd.MarkFlagsMutuallyExclusive("input", "resume")- cmd.MarkFlagsMutuallyExclusive("agent-config", "agent-config-file")-}--func init() {- registerExecFlags(execCmd)-}--// TODO(jbd): Add multimodal input flags, e.g. --input-image.--var (- // The concrete type is *controller.Controller- execController cliutil.Controller- interruptHandler = NewInterruptHandler()-)--func runExec(cmd *cobra.Command, args []string) error {- ctx := cmd.Context()-- if execConversationID == "" {- execConversationID = uuid.NewString()- }-- // Setup signal handling for graceful shutdown- ctx, cancel := context.WithCancel(ctx)- defer cancel()-- sigChan := make(chan os.Signal, 2) // Buffer to not miss signals- signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)-- go func() {- for {- sig := <-sigChan- if sig == syscall.SIGTERM {- fmt.Println("\nReceived SIGTERM, exiting...")- interruptHandler.exit()- }-- if !interruptHandler.TriggerCancel() {- if interruptHandler.HandleInterrupt() {- fmt.Println("\nExiting...")- interruptHandler.exit()- }- }- }- }()-- if execServerAddr == "" {- cfg, err := newConfig(cmd, execConfigFile)- if err != nil {- return err- }- // Validate configuration (matches `ax serve`).- if err := cfg.Validate(); err != nil {- return fmt.Errorf("invalid configuration: %w", err)- }- c, err := cliutil.NewControllerFromConfig(ctx, cfg)- if err != nil {- return fmt.Errorf("error creating controller: %w", err)- }- execController = c- }-- var agentConfig []byte- if execAgentConfigFile != "" {- b, err := os.ReadFile(execAgentConfigFile)- if err != nil {- return fmt.Errorf("failed to read agent config %q: %w", execAgentConfigFile, err)- }- agentConfig = b- } else if execAgentConfig != "" {- agentConfig = []byte(execAgentConfig)- }-- return execLoop(ctx, execConversationID, execAgentID, agentConfig, execInput)-}--func execLoop(ctx context.Context, id string, harnessID string, agentConfig []byte, input string) error {- d := internal.NewDisplay(id, os.Stdout)- d.DisplayHeader()-- var inputs []*proto.Step- if !execResume {- var quit bool- var err error- input, agentConfig, quit, err = promptUser(d, input, agentConfig)- if err != nil {- return err- }- if quit {- return nil- }- inputs = []*proto.Step{- {- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Role: "user",- Content: []*proto.Content{- {- Type: &proto.Content_Text{- Text: &proto.TextContent{- Text: input,- },- },- },- },- },- },- },- }- }-- for {- reqCtx, cancel := context.WithCancel(ctx)- interruptHandler.SetActiveCancel(cancel)-- d.StartLoading("Waiting for response...")- conf, err := runAutoExec(reqCtx, d, &proto.CreateInteractionEvent{- ConversationId: id,- AgentId: harnessID,- AgentConfig: agentConfig,- Inputs: inputs,- })- d.StopLoading()-- interruptHandler.ClearActiveCancel()- cancel()-- if err != nil {- if errors.Is(err, context.Canceled) {- fmt.Println("Request canceled.")- inputs = nil- continue- }- return err- }-- if conf != nil {- for {- approved, err := d.PromptForApproval(conf.Question)- if err != nil {- if errors.Is(err, internal.ErrUserAborted) {- if interruptHandler.HandleInterrupt() {- return nil- }- continue- }- return err- }- var decision []*proto.Step- if approved {- decision = []*proto.Step{{- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Role: "user",- Content: []*proto.Content{- {- Type: &proto.Content_Confirmation{- Confirmation: &proto.ConfirmationContent{- Id: conf.Id,- Decision: &proto.ConfirmationContent_Approval{- Approval: &proto.ApprovalDecision{Approved: true},- },- },- },- },- },- },- },- }}- } else {- decision = []*proto.Step{{- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Role: "user",- Content: []*proto.Content{- {- Type: &proto.Content_Confirmation{- Confirmation: &proto.ConfirmationContent{- Id: conf.Id,- Decision: &proto.ConfirmationContent_Decline{- Decline: &proto.DeclineDecision{Declined: true},- },- },- },- },- },- },- },- }}- }-- reqCtx, cancel := context.WithCancel(ctx)- interruptHandler.SetActiveCancel(cancel)-- d.StartLoading("Waiting for response...")- conf, err = runAutoExec(reqCtx, d, &proto.CreateInteractionEvent{- ConversationId: id,- AgentId: harnessID,- AgentConfig: agentConfig,- Inputs: decision,- })- d.StopLoading()-- interruptHandler.ClearActiveCancel()- cancel()-- if err != nil {- if errors.Is(err, context.Canceled) {- fmt.Println("Request canceled.")- inputs = nil- break- }- return err- }- if conf == nil {- break- }- }- }-- // Per-request config: clear the config after each turn.- var quit bool- input, agentConfig, quit, err = promptUser(d, "", agentConfig)- if err != nil {- return err- }- if quit {- return nil- }-- inputs = []*proto.Step{- {- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Role: "user",- Content: []*proto.Content{- {- Type: &proto.Content_Text{- Text: &proto.TextContent{- Text: input,- },- },- },- },- },- },- },- }- }-}--func runAutoExec(ctx context.Context, d *internal.Display, req *proto.CreateInteractionEvent) (*proto.ConfirmationContent, error) {- fn := runExecHeadless- if execServerAddr != "" {- fn = runExecServer- }- return fn(ctx, d, req)-}--func runExecHeadless(ctx context.Context, d *internal.Display, req *proto.CreateInteractionEvent) (*proto.ConfirmationContent, error) {- var confirmation *proto.ConfirmationContent- var lastStep int64- outputHandler := cliutil.ExecHandler(func(resp *proto.CreateInteractionResponse) error {- for _, step := range resp.Outputs {- if step.Index != 0 {- lastStep = step.Index- }- if contentStep := step.GetContent(); contentStep != nil {- for _, c := range contentStep.Content {- if conf := c.GetConfirmation(); conf != nil {- confirmation = conf- }- }- }- }- displayContents(d, resp.Outputs)- return nil- })- if err := execController.Exec(ctx, req, outputHandler); err != nil {- d.StopLoading()- return nil, fmt.Errorf("error executing with local server: %w", err)- }-- if confirmation == nil {- if lastStep != 0 {- d.FinishOutput(fmt.Sprintf("step=%d", lastStep))- } else {- d.FinishOutput("")- }- }- return confirmation, nil-}--func runExecServer(ctx context.Context, d *internal.Display, req *proto.CreateInteractionEvent) (*proto.ConfirmationContent, error) {- conn, err := connect(execServerAddr)- if err != nil {- d.StopLoading()- return nil, err- }- defer conn.Close()-- client := proto.NewInteractionsServiceClient(conn)- stream, err := client.CreateInteraction(ctx, req)- if err != nil {- d.StopLoading()- return nil, fmt.Errorf("error executing: %w", err)- }-- var confirmation *proto.ConfirmationContent- var lastStep int64- for {- resp, err := stream.Recv()- if err == io.EOF {- d.StopLoading()- break- }- if err != nil {- d.StopLoading()- return nil, fmt.Errorf("error receiving response: %w", err)- }- if resp.Outputs != nil {- for _, step := range resp.Outputs {- if step.Index != 0 {- lastStep = step.Index- }- if contentStep := step.GetContent(); contentStep != nil {- for _, c := range contentStep.Content {- if conf := c.GetConfirmation(); conf != nil {- confirmation = conf- }- }- }- }- displayContents(d, resp.Outputs)- }- }- if confirmation == nil {- if lastStep != 0 {- d.FinishOutput(fmt.Sprintf("step=%d", lastStep))- } else {- d.FinishOutput("")- }- }- return confirmation, nil-}--func displayContents(d *internal.Display, steps []*proto.Step) {- for _, step := range steps {- d.Display(step)- }-}--// promptUser loops until the user provides a non-empty input string.-// The "/config" command opens the agent config menu.-// It returns:-// - string: the valid user input-// - []byte: the (possibly updated) agent config-// - bool: true if the user entered a quit command-// - error: any error that occurred during prompting-func promptUser(d *internal.Display, input string, agentConfig []byte) (string, []byte, bool, error) {- for {- for strings.TrimSpace(input) == "" {- var err error- input, err = d.PromptForInput()- if err != nil {- if errors.Is(err, internal.ErrUserAborted) {- if interruptHandler.HandleInterrupt() {- return "", agentConfig, true, nil- }- input = "" // Continue loop to prompt again- continue- }- return "", agentConfig, false, err- }- }-- trimmed := strings.TrimSpace(input)- if trimmed == "/config" {- cfg, err := runConfigMenu(d, agentConfig)- if err != nil {- return "", agentConfig, false, err- }- agentConfig = cfg- input = "" // Re-prompt after handling the config.- continue- }-- d.DisplayInput(input)- if strings.ToLower(trimmed) == "q" {- d.ShowResumption(execConversationID, execServerAddr)- return "", agentConfig, true, nil- }- return input, agentConfig, false, nil- }-}--// InterruptHandler encapsulates the cancellation and signal handling state.-type InterruptHandler struct {- mu sync.Mutex- activeCancel context.CancelFunc- interruptCount int32-}--// NewInterruptHandler creates a new InterruptHandler.-func NewInterruptHandler() *InterruptHandler {- return &InterruptHandler{}-}--// SetActiveCancel sets the active cancel function.-func (h *InterruptHandler) SetActiveCancel(cancel context.CancelFunc) {- h.mu.Lock()- defer h.mu.Unlock()- h.activeCancel = cancel-}--// ClearActiveCancel clears the active cancel function.-func (h *InterruptHandler) ClearActiveCancel() {- h.mu.Lock()- defer h.mu.Unlock()- h.activeCancel = nil-}--// HandleInterrupt increments the interrupt count and returns true if the process should exit.-// It also starts a timer to reset the count.-func (h *InterruptHandler) HandleInterrupt() bool {- h.mu.Lock()- defer h.mu.Unlock()- h.interruptCount++- if h.interruptCount == 1 {- fmt.Println("\nPress Ctrl+C again to exit.")- go func() {- time.Sleep(2 * time.Second)- h.mu.Lock()- h.interruptCount = 0- h.mu.Unlock()- }()- return false- }- return true-}--// TriggerCancel triggers cancellation if there is an active cancel function.-// It returns true if it triggered cancellation, or false if there was no active cancellation.-func (h *InterruptHandler) TriggerCancel() bool {- h.mu.Lock()- defer h.mu.Unlock()- if h.activeCancel != nil {- fmt.Println("\nCanceling current request...")- h.activeCancel()- return true- }- return false-}--// exit gracefully shuts down the controller (if any) and terminates the process.-func (h *InterruptHandler) exit() {- if execController != nil {- execController.Close()- }- os.Exit(1)-}diff --git a/cmd/ax/harness.go b/cmd/ax/harness.godeleted file mode 100644index 7e37395..0000000--- a/cmd/ax/harness.go+++ /dev/null@@ -1,227 +0,0 @@-// 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 main: the `ax harness` command. It runs one harness in-process,-// selected by the optional [harness-id] argument: "antigravity" (default)-// or "antigravity-interactions"-package main--import (- "context"- "encoding/base64"- "fmt"- "log"- "net"- "net/http"- "os"- "os/signal"- "strconv"- "syscall"- "time"-- "github.com/google/ax/internal/config"- "github.com/google/ax/internal/harness/antigravity"- "github.com/google/ax/internal/harness/antigravityinteractions"- "github.com/google/ax/internal/pythonsidecar"- "github.com/spf13/cobra"- "google.golang.org/grpc"- "google.golang.org/grpc/credentials/insecure"- healthpb "google.golang.org/grpc/health/grpc_health_v1"-)--var (- harnessPort int- harnessHost string-)--// harnessReadyzPort is the port for the HTTP /readyz readiness endpoint.-const harnessReadyzPort = 8081--var harnessCmd = &cobra.Command{- Use: "harness [harness-id]",- Short: "Run the harness gRPC server",- Args: cobra.MaximumNArgs(1),- Hidden: true,- RunE: runHarness,-}--func init() {- harnessCmd.Flags().IntVar(&harnessPort, "port", 50053, "Port for the HarnessService to listen on")- harnessCmd.Flags().StringVar(&harnessHost, "host", "127.0.0.1", "Host interface for the HarnessService to bind")- rootCmd.AddCommand(harnessCmd)-}--// setHarnessWorkDir changes the process working directory to AX_HARNESS_WORKDIR-// when it is set. The forked Python sidecar inherits it, which scopes the agent's-// default workspace (os.getcwd()) away from its own source tree.-func setHarnessWorkDir() error {- dir := os.Getenv("AX_HARNESS_WORKDIR")- if dir == "" {- return nil- }- if err := os.MkdirAll(dir, 0755); err != nil {- return fmt.Errorf("create harness working directory %q: %w", dir, err)- }- if err := os.Chdir(dir); err != nil {- return fmt.Errorf("set harness working directory %q: %w", dir, err)- }- log.Printf("harness working directory set to %s", dir)- return nil-}--// runHarness runs the harness selected by the optional [harness-id] argument:-// "antigravity" (default) or "antigravity-interactions".-func runHarness(cmd *cobra.Command, args []string) error {- harnessID := config.AntigravityHarnessID- if len(args) > 0 {- harnessID = args[0]- }- switch harnessID {- case config.AntigravityInteractionsHarnessID:- return runAntigravityInteractionsHarness(cmd.Context())- case config.AntigravityHarnessID:- return runAntigravityHarness(cmd)- default:- return fmt.Errorf("unknown harness %q (want %q or %q)",- harnessID, config.AntigravityHarnessID, config.AntigravityInteractionsHarnessID)- }-}--// runAntigravityHarness forks the Antigravity Python sidecar server, which serves-// the HarnessService (and gRPC health) on the configured port. ax harness-// supervises the child: it forwards termination signals and exits with its status.-func runAntigravityHarness(cmd *cobra.Command) error {- if err := setHarnessWorkDir(); err != nil {- return err- }-- stateDir, err := antigravity.DefaultStateDir()- if err != nil {- return fmt.Errorf("failed to resolve antigravity state dir: %w", err)- }-- addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(harnessPort))- cfg := pythonsidecar.Config{- Module: "python.antigravity.harness_server",- Args: []string{- "--host", harnessHost,- "--port", strconv.Itoa(harnessPort),- "--state-dir", stateDir,- },- Stdout: os.Stdout,- Stderr: os.Stderr,- ReadyFunc: pythonsidecar.TCPReady(addr),- Address: addr,- }-- sidecar := pythonsidecar.New(cfg)- if err := sidecar.Start(cmd.Context(), ""); err != nil {- return fmt.Errorf("failed to start antigravity harness server: %w", err)- }- log.Printf("forked antigravity harness server (pid %d) on %s:%d", sidecar.Pid(), harnessHost, harnessPort)-- // Serve the /readyz endpoint that substrate's readiness probe polls (during- // golden snapshotting and per-actor Run/Restore).- go serveReadyz(harnessReadyzPort, harnessPort)-- // Forward termination signals to the child so substrate can stop the actor.- sigChan := make(chan os.Signal, 1)- signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)- go func() {- <-sigChan- _ = sidecar.Stop()- }()-- if err := sidecar.Wait(); err != nil {- return fmt.Errorf("antigravity harness server exited: %w", err)- }- return nil-}--// runAntigravityInteractionsHarness runs the Go Antigravity Interactions harness-// server (HarnessService + gRPC health + HTTP /readyz) on the configured ports.-func runAntigravityInteractionsHarness(ctx context.Context) error {- if err := setHarnessWorkDir(); err != nil {- return err- }-- // Read harness config from ax.yaml handed to the actor via AX_CONFIG_CONTENT.- // Fall back to built-in defaults.- var hc config.AntigravityInteractionsHarnessConfig- if raw := os.Getenv("AX_CONFIG_CONTENT"); raw != "" {- if data, err := base64.StdEncoding.DecodeString(raw); err != nil {- log.Printf("AX_CONFIG_CONTENT: base64 decode failed, using defaults: %v", err)- } else if cfg, err := config.LoadFromBytes(data); err != nil {- log.Printf("AX_CONFIG_CONTENT: parse failed, using defaults: %v", err)- } else {- hc = cfg.Registry.AntigravityInteractions- }- }- agent := hc.Agent- if agent == "" {- agent = antigravityinteractions.DefaultAgent- }- // AX owns the resume-cursor path (a harness implementation detail), so it's- // derived internally rather than read from ax.yaml.- stateDir, err := antigravityinteractions.DefaultStateDir()- if err != nil {- return err- }-- // WorkDir is the agent's working directory. It is authoritative for built-in- // env tools (see AntigravityInteractionsConfig.WorkDir) so their execution- // does not depend on the process cwd. Empty falls back to the process cwd.- workDir := os.Getenv("AX_HARNESS_WORKDIR")-- cfg := antigravityinteractions.AntigravityInteractionsConfig{- Agent: agent,- StateDir: stateDir,- WorkDir: workDir,- SystemInstruction: antigravityinteractions.JoinSystemInstruction(hc.SystemInstruction, antigravityinteractions.WorkspaceSystemInstruction(workDir)),- }- return antigravityinteractions.Serve(ctx, cfg, harnessHost, harnessPort, harnessReadyzPort)-}--// serveReadyz serves the HTTP /readyz endpoint on readyzPort that substrate's-// readiness probe polls (during golden snapshotting and per-actor Run/Restore).-// Each request forwards to the forked harness's gRPC health Check.-func serveReadyz(readyzPort, grpcPort int) {- conn, err := grpc.NewClient(- net.JoinHostPort("127.0.0.1", strconv.Itoa(grpcPort)),- grpc.WithTransportCredentials(insecure.NewCredentials()),- )- if err != nil {- log.Printf("readyz: failed to create gRPC health client: %v", err)- return- }- healthClient := healthpb.NewHealthClient(conn)-- mux := http.NewServeMux()- mux.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {- ctx, cancel := context.WithTimeout(r.Context(), time.Second)- defer cancel()- resp, err := healthClient.Check(ctx, &healthpb.HealthCheckRequest{})- if err != nil || resp.GetStatus() != healthpb.HealthCheckResponse_SERVING {- http.Error(w, "not ready", http.StatusServiceUnavailable)- return- }- w.WriteHeader(http.StatusOK)- _, _ = w.Write([]byte("ok\n"))- })-- addr := net.JoinHostPort(harnessHost, strconv.Itoa(readyzPort))- if err := http.ListenAndServe(addr, mux); err != nil {- log.Printf("readyz server on %s exited: %v", addr, err)- }-}diff --git a/cmd/ax/harness_test.go b/cmd/ax/harness_test.godeleted file mode 100644index cabe160..0000000--- a/cmd/ax/harness_test.go+++ /dev/null@@ -1,132 +0,0 @@-// 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 main--import (- "fmt"- "net"- "net/http"- "os"- "path/filepath"- "testing"- "time"-- "google.golang.org/grpc"- "google.golang.org/grpc/health"- healthpb "google.golang.org/grpc/health/grpc_health_v1"-)--func TestSetHarnessWorkDir(t *testing.T) {- // os.Chdir is global process state; save and restore it around the test.- orig, err := os.Getwd()- if err != nil {- t.Fatalf("getwd: %v", err)- }- t.Cleanup(func() { _ = os.Chdir(orig) })-- t.Run("unset leaves the working directory unchanged", func(t *testing.T) {- t.Setenv("AX_HARNESS_WORKDIR", "")- before, _ := os.Getwd()- if err := setHarnessWorkDir(); err != nil {- t.Fatalf("setHarnessWorkDir: %v", err)- }- after, _ := os.Getwd()- if before != after {- t.Errorf("working directory changed: %q -> %q", before, after)- }- })-- t.Run("set changes the working directory", func(t *testing.T) {- dir := t.TempDir()- t.Setenv("AX_HARNESS_WORKDIR", dir)- if err := setHarnessWorkDir(); err != nil {- t.Fatalf("setHarnessWorkDir: %v", err)- }- got, err := os.Getwd()- if err != nil {- t.Fatalf("getwd: %v", err)- }- want, _ := filepath.EvalSymlinks(dir)- gotResolved, _ := filepath.EvalSymlinks(got)- if gotResolved != want {- t.Errorf("working directory = %q, want %q", gotResolved, want)- }- })-- t.Run("missing directory is created", func(t *testing.T) {- dir := filepath.Join(t.TempDir(), "created", "workdir")- t.Setenv("AX_HARNESS_WORKDIR", dir)- if err := setHarnessWorkDir(); err != nil {- t.Fatalf("setHarnessWorkDir: %v", err)- }- if _, err := os.Stat(dir); err != nil {- t.Errorf("working directory %q was not created: %v", dir, err)- }- })-}--func TestServeReadyz(t *testing.T) {- // Start a real gRPC server exposing the standard health service; this stands- // in for the Antigravity Python harness that serveReadyz probes.- grpcListener, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- t.Fatalf("listen for gRPC: %v", err)- }- healthServer := health.NewServer()- grpcServer := grpc.NewServer()- healthpb.RegisterHealthServer(grpcServer, healthServer)- go func() { _ = grpcServer.Serve(grpcListener) }()- t.Cleanup(grpcServer.Stop)- grpcPort := grpcListener.Addr().(*net.TCPAddr).Port-- // Reserve an ephemeral port for /readyz, then hand it to serveReadyz to bind.- readyzListener, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- t.Fatalf("listen for readyz: %v", err)- }- readyzPort := readyzListener.Addr().(*net.TCPAddr).Port- _ = readyzListener.Close()-- // Start with the harness not serving, then run serveReadyz against it.- healthServer.SetServingStatus("", healthpb.HealthCheckResponse_NOT_SERVING)- go serveReadyz(readyzPort, grpcPort)- url := fmt.Sprintf("http://127.0.0.1:%d/readyz", readyzPort)-- // /readyz re-derives readiness from gRPC health on every request: 503 until- // the harness is SERVING, 200 once it is, and back to 503 if it stops serving.- waitReadyz(t, url, http.StatusServiceUnavailable)- healthServer.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)- waitReadyz(t, url, http.StatusOK)- healthServer.SetServingStatus("", healthpb.HealthCheckResponse_NOT_SERVING)- waitReadyz(t, url, http.StatusServiceUnavailable)-}--func waitReadyz(t *testing.T, url string, want int) {- t.Helper()- deadline := time.Now().Add(5 * time.Second)- got := 0- for time.Now().Before(deadline) {- resp, err := http.Get(url)- if err == nil {- got = resp.StatusCode- _ = resp.Body.Close()- if got == want {- return- }- }- time.Sleep(10 * time.Millisecond)- }- t.Fatalf("GET %s = %d, want %d", url, got, want)-}diff --git a/cmd/ax/harnessclient.go b/cmd/ax/harnessclient.godeleted file mode 100644index 26b1d69..0000000--- a/cmd/ax/harnessclient.go+++ /dev/null@@ -1,139 +0,0 @@-// 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 main implements a simple client for the fake HarnessService.-// It is intended for testing purposes only and should be replaced with-// the actual ax client implementation.-// TODO(wjjclaud): Update or replace this file with ax client implementation.-package main--import (- "context"- "fmt"- "io"- "log"- "strings"-- "github.com/google/ax/proto"- "github.com/google/uuid"- "github.com/spf13/cobra"- "google.golang.org/grpc"- "google.golang.org/grpc/credentials/insecure"-)--var (- harnessServerAddr string- agentClientID string-)--var harnessClientCmd = &cobra.Command{- Use: "harnessclient",- Short: "Run the harness client to connect to the server",- Hidden: true,- RunE: runHarnessClient,-}--func init() {- harnessClientCmd.Flags().StringVar(&harnessServerAddr, "server", "localhost:50053", "The server address for the gRPC HarnessService.")- harnessClientCmd.Flags().StringVar(&agentClientID, "agent", "testharness", "The agent id to send on the request envelope.")- rootCmd.AddCommand(harnessClientCmd)-}--func runHarnessClient(cmd *cobra.Command, args []string) error {- ctx := context.Background()-- log.Printf("Connecting to HarnessService at %s...", harnessServerAddr)- conn, err := grpc.NewClient(harnessServerAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))- if err != nil {- return fmt.Errorf("failed to connect to server: %v", err)- }- defer conn.Close()-- client := proto.NewHarnessServiceClient(conn)- stream, err := client.Connect(ctx)- if err != nil {- return fmt.Errorf("failed to call Connect: %v", err)- }-- // Wait for user input from stdin if not specified, but for simple execution, send a single frame.- var input string- if len(args) > 0 {- input = strings.Join(args, " ")- } else {- input = "Hello from harness client!"- }-- // A single HarnessRequest{start} initiates the turn.- start := &proto.HarnessRequest{- ConversationId: uuid.NewString(),- AgentId: agentClientID,- Type: &proto.HarnessRequest_Start{- Start: &proto.HarnessStart{- Steps: []*proto.Step{- {- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Role: "user",- Content: []*proto.Content{- {Type: &proto.Content_Text{Text: &proto.TextContent{Text: input}}},- },- },- },- },- },- },- },- }- if err := stream.Send(start); err != nil {- return fmt.Errorf("failed to send start: %v", err)- }- if err := stream.CloseSend(); err != nil {- return fmt.Errorf("failed to close send side: %v", err)- }-- // Drain HarnessResponse frames until HarnessEnd / EOF.- for {- resp, err := stream.Recv()- if err == io.EOF {- break- }- if err != nil {- return fmt.Errorf("failed to receive response: %v", err)- }- switch payload := resp.Type.(type) {- case *proto.HarnessResponse_Outputs:- for i, step := range payload.Outputs.Steps {- if contentStep := step.GetContent(); contentStep != nil {- for _, c := range contentStep.Content {- var text string- if tb, ok := c.Type.(*proto.Content_Text); ok {- text = tb.Text.Text- }- fmt.Printf("Server > step[%d] (%s): %s\n", i, contentStep.Role, text)- }- }- }- case *proto.HarnessResponse_End:- if errDetail := payload.End.GetError(); errDetail != nil {- fmt.Printf("Server > [end] state=%s error=(code=%d description=%q)\n",- payload.End.GetState(), errDetail.GetCode(), errDetail.GetDescription())- } else {- fmt.Printf("Server > [end] state=%s\n", payload.End.GetState())- }- }- }-- log.Println("Stream closed successfully by server.")- return nil-}diff --git a/cmd/ax/internal/cliutil/cliutil.go b/cmd/ax/internal/cliutil/cliutil.godeleted file mode 100644index 51933aa..0000000--- a/cmd/ax/internal/cliutil/cliutil.go+++ /dev/null@@ -1,211 +0,0 @@-// 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 cliutil--import (- "context"- "fmt"- "os"-- "github.com/google/ax/internal/config"- "github.com/google/ax/internal/controller"- "github.com/google/ax/internal/controller/eventlog"- "github.com/google/ax/internal/harness"- "github.com/google/ax/internal/harness/antigravity"- "github.com/google/ax/internal/harness/antigravityinteractions"- "github.com/google/ax/internal/harness/substrate"- "github.com/google/ax/internal/skills"- "github.com/google/ax/internal/skills/geminienterprise"- "github.com/google/ax/internal/skills/local"-)--// Controller is the active controller type for this build.-type Controller = *controller.Controller--// ExecHandler is the handler type accepted by Controller.Exec.-type ExecHandler = controller.ExecHandler--// Config is the configuration type for this build.-type Config = config.Config--// LoadFromFile loads configuration from a YAML file.-func LoadFromFile(path string) (*Config, error) {- return config.LoadFromFile(path)-}--// DefaultConfig returns a configuration with default values set.-func DefaultConfig() *Config {- return config.DefaultConfig()-}--// NewControllerFromConfig creates a controller.Controller instance based on the provided configuration.-func NewControllerFromConfig(ctx context.Context, cfg *Config) (*controller.Controller, error) {- reg := controller.NewRegistry()-- // AX_SUBSTRATE selects how built-in harnesses run: locally (unset) or as- // substrate actors ("1").- substrateMode := os.Getenv("AX_SUBSTRATE") == "1"-- // Validate config before local-mode antigravity.New forks the Python- // sidecar, so a config error surfaces without spawning a subprocess.- // Validate config before local-mode antigravity.New forks the Python- // sidecar, so a config error surfaces without spawning a subprocess.- if len(cfg.Registry.Substrate) > 0 && !substrateMode {- return nil, fmt.Errorf("custom substrate harnesses require AX_SUBSTRATE=1")- }-- var defaultHarnessID string- var err error-- // Resolve skills once, up front (skills config is top-level and- // harness-agnostic; each actor runs a single harness that consumes the- // resulting folder). Two parallel sources feed the same result:- // - Registries: fetched from the Gemini Enterprise Skill Registry and- // materialized to their target_dir.- // - Local: directories already on disk, used as-is.- // Both are unconditional when configured and fail-safe: a source error- // degrades capability but never blocks harness creation. The interactions- // harness (no SKILLS_DIR concept) is told where the skills are via a pointer- // appended to its system instruction. Only the local process path resolves- // skills; substrate/pod does not yet read ax.yaml.- //- // TODO(joycel): wire the Antigravity SDK harness too. It discovers skills via- // SKILLS_DIR, so its SKILLS_DIR needs to be pointed at the resolved skill- // directories (registry target_dir(s) and/or local path(s)); currently only- // the interactions harness is fully wired.- var skillsPointer string- if !substrateMode {- var groups []skills.Group- groups = append(groups, geminienterprise.Materialize(ctx, cfg.Skills)...)- groups = append(groups, local.Discover(cfg.Skills)...)- skillsPointer = antigravityinteractions.SkillsSystemInstruction(groups)- }-- // Built-in Antigravity harness.- var antigravityHarness harness.Harness- if !substrateMode {- address := cfg.Antigravity.Endpoint- if address == "" {- address = cfg.Registry.Antigravity.Endpoint- }- if address == "" {- address = "127.0.0.1:50053"- }- // Local mode: the harness owns the Python sidecar. AX owns the- // trajectory storage path (a harness implementation detail), so it's- // derived internally rather than exposed in ax.yaml.- stateDir, sErr := antigravity.DefaultStateDir()- if sErr != nil {- return nil, fmt.Errorf("antigravity harness: %w", sErr)- }- antigravityHarness, err = antigravity.New(ctx, address, stateDir, true)- if err != nil {- return nil, fmt.Errorf("antigravity harness: %w", err)- }- } else {- antigravityHarness, err = substrate.New(config.AntigravityHarnessID, "", "", config.AntigravityHarnessTemplate, 80)- if err != nil {- return nil, fmt.Errorf("antigravity harness: %w", err)- }- }- if err := reg.RegisterHarness(config.AntigravityHarnessID, antigravityHarness); err != nil {- return nil, fmt.Errorf("register antigravity harness: %w", err)- }- if cfg.Antigravity.Default || cfg.Registry.Antigravity.Default {- defaultHarnessID = config.AntigravityHarnessID- }-- // Built-in Antigravity Interactions harness.- var antigravityInteractionsHarness harness.Harness- if !substrateMode {- aiCfg := cfg.Registry.AntigravityInteractions- agent := aiCfg.Agent- if agent == "" {- agent = antigravityinteractions.DefaultAgent- }- // AX owns the resume-cursor path (a harness implementation detail), so- // it's derived internally rather than exposed in ax.yaml.- stateDir, sErr := antigravityinteractions.DefaultStateDir()- if sErr != nil {- return nil, fmt.Errorf("antigravity-interactions harness: %w", sErr)- }- // WorkDir is the agent's working directory, authoritative for built-in env- // tools (see AntigravityInteractionsConfig.WorkDir). Mirrors the substrate- // path (cmd/ax harness): sourced from AX_HARNESS_WORKDIR, empty falls back- // to the process cwd.- workDir := os.Getenv("AX_HARNESS_WORKDIR")- // skillsPointer was built once, up front, from the top-level skills- // config (see above). Append it, plus the workspace pointer, to any- // configured system instruction.- systemInstruction := antigravityinteractions.JoinSystemInstruction(- antigravityinteractions.JoinSystemInstruction(aiCfg.SystemInstruction, skillsPointer),- antigravityinteractions.WorkspaceSystemInstruction(workDir),- )- antigravityInteractionsHarness, err = antigravityinteractions.New(antigravityinteractions.AntigravityInteractionsConfig{- Agent: agent,- SystemInstruction: systemInstruction,- StateDir: stateDir,- WorkDir: workDir,- })- } else {- antigravityInteractionsHarness, err = substrate.New(config.AntigravityInteractionsHarnessID, "", "", config.AntigravityInteractionsTemplate, 80)- }- if err != nil {- return nil, fmt.Errorf("antigravity-interactions harness: %w", err)- }- if err := reg.RegisterHarness(config.AntigravityInteractionsHarnessID, antigravityInteractionsHarness); err != nil {- return nil, fmt.Errorf("register antigravity-interactions harness: %w", err)- }- if cfg.Registry.AntigravityInteractions.Default {- defaultHarnessID = config.AntigravityInteractionsHarnessID- }-- for _, sc := range cfg.Registry.Substrate {- h, err := sc.NewHarness("")- if err != nil {- return nil, fmt.Errorf("substrate harness %q: %w", sc.ID, err)- }- if err := reg.RegisterHarness(sc.ID, h); err != nil {- return nil, fmt.Errorf("register substrate harness %q: %w", sc.ID, err)- }- if sc.Default {- defaultHarnessID = sc.ID- }- }-- // Antigravity is the default harness by default if no other harness set Default: true.- if defaultHarnessID == "" {- defaultHarnessID = config.AntigravityHarnessID- }-- // Set the default harness.- if err := reg.SetDefaultHarness(defaultHarnessID); err != nil {- return nil, fmt.Errorf("set default harness %q: %w", defaultHarnessID, err)- }-- return controller.New(ctx, controller.Config{- Registry: reg,- EventLogBuilder: func() (eventlog.EventLog, error) {- if cfg.EventLog.PostgresConfig.DSN != "" {- dsn := os.ExpandEnv(cfg.EventLog.PostgresConfig.DSN)- if dsn == "" {- return nil, fmt.Errorf("eventlog: postgres dsn %q expanded to empty", cfg.EventLog.PostgresConfig.DSN)- }- return eventlog.OpenPostgresEventLog(dsn)- }- return eventlog.OpenSQLiteEventLog(cfg.EventLog.SQLiteConfig.Filename)- },- })-}diff --git a/cmd/ax/internal/cliutil/cliutil_test.go b/cmd/ax/internal/cliutil/cliutil_test.godeleted file mode 100644index 7b99202..0000000--- a/cmd/ax/internal/cliutil/cliutil_test.go+++ /dev/null@@ -1,129 +0,0 @@-// 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 cliutil--import (- "context"- "path/filepath"- "strings"- "testing"-- "github.com/google/ax/internal/config"-)--func TestNewControllerFromConfig_BuiltinSubstrate(t *testing.T) {- t.Setenv("AX_SUBSTRATE", "1")-- cfg := &config.Config{- EventLog: config.EventLogConfig{- SQLiteConfig: config.SQLiteConfig{- Filename: filepath.Join(t.TempDir(), "log.sqlite"),- },- },- Registry: config.RegistryConfig{- Antigravity: config.AntigravityHarnessConfig{- Default: true,- },- },- }-- c, err := NewControllerFromConfig(context.Background(), cfg)- if err != nil {- t.Fatalf("NewControllerFromConfig: %v", err)- }- if c == nil {- t.Fatal("expected non-nil controller")- }- c.Close()-}--func TestNewControllerFromConfig_InteractionsSubstrate(t *testing.T) {- t.Setenv("AX_SUBSTRATE", "1")-- cfg := &config.Config{- EventLog: config.EventLogConfig{- SQLiteConfig: config.SQLiteConfig{- Filename: filepath.Join(t.TempDir(), "log.sqlite"),- },- },- Registry: config.RegistryConfig{- Antigravity: config.AntigravityHarnessConfig{Default: true},- },- }-- c, err := NewControllerFromConfig(context.Background(), cfg)- if err != nil {- t.Fatalf("NewControllerFromConfig: %v", err)- }- if c == nil {- t.Fatal("expected non-nil controller")- }- defer c.Close()-- if _, err := c.Registry().Harness(config.AntigravityInteractionsHarnessID); err != nil {- t.Errorf("interactions harness not registered in substrate mode: %v", err)- }-}--func TestNewControllerFromConfig_CustomHarnessRequiresSubstrateMode(t *testing.T) {- t.Setenv("AX_SUBSTRATE", "")-- cfg := &config.Config{- EventLog: config.EventLogConfig{- SQLiteConfig: config.SQLiteConfig{- Filename: filepath.Join(t.TempDir(), "log.sqlite"),- },- },- Registry: config.RegistryConfig{- Substrate: []config.SubstrateHarnessConfig{- {ID: "custom", Namespace: "team-ns", Template: "custom-template"},- },- },- }-- _, err := NewControllerFromConfig(context.Background(), cfg)- if err == nil {- t.Fatal("expected error for custom substrate harness without AX_SUBSTRATE=1, got nil")- }- if !strings.Contains(err.Error(), "AX_SUBSTRATE=1") {- t.Errorf("expected error to mention AX_SUBSTRATE=1, got: %v", err)- }-}--func TestNewControllerFromConfig_CustomHarnessInSubstrateMode(t *testing.T) {- t.Setenv("AX_SUBSTRATE", "1")-- cfg := &config.Config{- EventLog: config.EventLogConfig{- SQLiteConfig: config.SQLiteConfig{- Filename: filepath.Join(t.TempDir(), "log.sqlite"),- },- },- Registry: config.RegistryConfig{- Substrate: []config.SubstrateHarnessConfig{- {ID: "custom", Namespace: "team-ns", Template: "custom-template"},- },- },- }-- c, err := NewControllerFromConfig(context.Background(), cfg)- if err != nil {- t.Fatalf("NewControllerFromConfig: %v", err)- }- if c == nil {- t.Fatal("expected non-nil controller")- }- c.Close()-}diff --git a/cmd/ax/internal/display.go b/cmd/ax/internal/display.godeleted file mode 100644index 28bc5ca..0000000--- a/cmd/ax/internal/display.go+++ /dev/null@@ -1,474 +0,0 @@-// 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 internal--import (- "encoding/json"- "fmt"- "io"- "os"- "sync"- "time"-- "charm.land/bubbles/v2/key"- tea "charm.land/bubbletea/v2"- "charm.land/huh/v2"- "charm.land/lipgloss/v2"- "github.com/google/ax/proto"- "google.golang.org/protobuf/types/known/structpb"-)--const (- boxWidth = 100-)--var (- isDark = lipgloss.HasDarkBackground(os.Stdin, os.Stdout)- lightDark = lipgloss.LightDark(isDark)-- purple = lightDark(lipgloss.Color("#5A56E0"), lipgloss.Color("#7571F9"))- comment = lightDark(lipgloss.Color("#a0a0a0"), lipgloss.Color("#6d6d6d"))-)--// ErrUserAborted is returned when the user aborts a prompt.-var ErrUserAborted = huh.ErrUserAborted--type displayState int--const (- stateNone displayState = iota- stateText- stateThought-)--type Display struct {- id string- w io.Writer // Target output writer, e.g., os.Stdout or a test buffer-- userStyle lipgloss.Style- checkpointStyle lipgloss.Style- idStyle lipgloss.Style- resumeStyle lipgloss.Style- toolStyle lipgloss.Style-- state displayState // Tracks the last printed chunk type to correctly format transition newlines-- loadingMu sync.Mutex- loadingStop chan struct{}- loadingDone chan struct{}-}--func NewDisplay(id string, w io.Writer) *Display {- if w == nil {- w = os.Stdout- }- return &Display{- id: id,- w: w,- userStyle: lipgloss.NewStyle().Foreground(purple),- checkpointStyle: lipgloss.NewStyle().Foreground(comment),- idStyle: lipgloss.NewStyle().Foreground(comment),- resumeStyle: lipgloss.NewStyle().Foreground(comment),- toolStyle: lipgloss.NewStyle().Bold(true),- state: stateNone,- }-}--func isTerminal(w io.Writer) bool {- if f, ok := w.(*os.File); ok {- fi, err := f.Stat()- if err != nil {- return false- }- return (fi.Mode() & os.ModeCharDevice) != 0- }- return false-}--// StartLoading displays an animated loading bar on the current terminal line-// until StopLoading is called.-func (d *Display) StartLoading(msg string) {- d.loadingMu.Lock()- defer d.loadingMu.Unlock()-- if d.loadingStop != nil {- close(d.loadingStop)- <-d.loadingDone- d.loadingStop = nil- d.loadingDone = nil- }-- if !isTerminal(d.w) {- return- }-- stop := make(chan struct{})- done := make(chan struct{})- d.loadingStop = stop- d.loadingDone = done-- go func() {- defer close(done)- start := time.Now()- ticker := time.NewTicker(100 * time.Millisecond)- defer ticker.Stop()-- frames := []string{"|", "/", "-", "\\"}- spinnerStyle := lipgloss.NewStyle().Foreground(purple)- msgStyle := lipgloss.NewStyle().Foreground(comment)-- idx := 0- for {- select {- case <-stop:- fmt.Fprint(d.w, "\r\033[K")- return- case <-ticker.C:- elapsed := time.Since(start).Seconds()- frame := spinnerStyle.Render(frames[idx%len(frames)])- txt := msgStyle.Render(fmt.Sprintf("%s (%.1fs)", msg, elapsed))- fmt.Fprintf(d.w, "\r\033[K%s %s", frame, txt)- idx++- }- }- }()-}--// StopLoading clears the active loading bar if one is running.-func (d *Display) StopLoading() {- d.loadingMu.Lock()- defer d.loadingMu.Unlock()-- if d.loadingStop != nil {- close(d.loadingStop)- <-d.loadingDone- d.loadingStop = nil- d.loadingDone = nil- }-}--// DisplayInput displays the user input.-func (d *Display) DisplayInput(text string) {- d.StopLoading()- if d.state != stateNone {- fmt.Fprintln(d.w)- }- d.state = stateNone- fmt.Fprintf(d.w, "%s %s\n",- d.userStyle.Render("⏺"),- text,- )- fmt.Fprintln(d.w)-}--// Display prints a step according to its type.-func (d *Display) Display(step *proto.Step) {- d.StopLoading()- if step == nil {- return- }- switch o := step.Type.(type) {- case *proto.Step_Content:- if o.Content == nil {- return- }- for _, content := range o.Content.Content {- d.displayContent(content)- }-- case *proto.Step_Thought:- if o.Thought == nil {- return- }- for _, summary := range o.Thought.GetSummary() {- if textContent := summary.GetText(); textContent != nil {- if d.state != stateThought {- if d.state == stateText {- fmt.Fprintln(d.w)- }- fmt.Fprint(d.w, "Thinking: ")- }- d.state = stateThought- fmt.Fprint(d.w, textContent.Text)- }- }-- case *proto.Step_ToolCall:- if d.state != stateNone {- fmt.Fprintln(d.w)- }- d.state = stateNone- if o.ToolCall != nil && o.ToolCall.GetFunctionCall() != nil {- fn := o.ToolCall.GetFunctionCall()- argsStr := formatStruct(fn.Arguments)- if argsStr != "" {- fmt.Fprintf(d.w, "🛠 %s(%s)\n\n", d.toolStyle.Render(fn.Name), argsStr)- } else {- fmt.Fprintf(d.w, "🛠 %s()\n\n", d.toolStyle.Render(fn.Name))- }- }-- case *proto.Step_ToolResult:- if d.state != stateNone {- fmt.Fprintln(d.w)- }- d.state = stateNone- if o.ToolResult != nil && o.ToolResult.GetFunctionResult() != nil {- res := o.ToolResult.GetFunctionResult()- if res.IsError {- fmt.Fprintf(d.w, "❌ Tool Error (%s): %s\n\n", d.toolStyle.Render(res.Name), formatValue(res.Result))- }- }-- default:- d.displaySystem(fmt.Sprintf("unknown step type: %v", o))- }-}--func formatStruct(s *structpb.Struct) string {- if s == nil || len(s.Fields) == 0 {- return ""- }- b, err := json.Marshal(s.AsMap())- if err != nil {- return ""- }- return string(b)-}--func formatValue(v *proto.Value) string {- if v == nil {- return ""- }- switch k := v.Kind.(type) {- case *proto.Value_StringValue:- return k.StringValue- case *proto.Value_NumberValue:- return fmt.Sprintf("%v", k.NumberValue)- case *proto.Value_BoolValue:- return fmt.Sprintf("%v", k.BoolValue)- case *proto.Value_StructValue:- if k.StructValue != nil {- b, _ := json.Marshal(k.StructValue.AsMap())- return string(b)- }- }- return ""-}--func (d *Display) displayContent(content *proto.Content) {- if content == nil {- return- }- switch o := content.Type.(type) {- case *proto.Content_Text:- if d.state == stateThought {- fmt.Fprintln(d.w) // end the thinking line- }- d.state = stateText- fmt.Fprint(d.w, o.Text.Text)-- case *proto.Content_Confirmation:- // Let the confirmation prompt handle displaying the question.-- case *proto.Content_Image, *proto.Content_Audio, *proto.Content_Video, *proto.Content_Document:- d.displaySystem(fmt.Sprintf("unsupported output type for display: %T", o))-- default:- d.displaySystem(fmt.Sprintf("unknown output type: %v", o))- }-}--// displaySystem prints a system/error message on a new line.-func (d *Display) displaySystem(text string) {- if d.state != stateNone {- fmt.Fprintln(d.w)- }- d.state = stateNone- fmt.Fprintln(d.w, text)-}--// ShowNotice prints an informational message (e.g. the current harness config-// or a validation error) on its own line.-func (d *Display) ShowNotice(text string) {- d.displaySystem(text)-}--// FinishOutput completes the streaming output and shows info if provided-func (d *Display) FinishOutput(info string) {- d.StopLoading()- if d.state != stateNone {- fmt.Fprintln(d.w)- }- d.state = stateNone- if info != "" {- fmt.Fprintln(d.w, d.checkpointStyle.Render(info))- }- fmt.Fprintln(d.w)-}--func (d *Display) DisplayHeader() {- fmt.Fprintln(d.w, d.idStyle.Render("Conversation: "+d.id))- fmt.Fprintln(d.w)-}--// PromptForApproval shows an accept/reject dialog-// Returns true if accepted, false if rejected, and an error if cancelled (Ctrl+C)-func (d *Display) PromptForApproval(question string) (bool, error) {- d.StopLoading()- var accepted bool- form := huh.NewForm(- huh.NewGroup(- huh.NewConfirm().- Title(question).- Affirmative("Accept").- Negative("Reject").- Value(&accepted),- ),- ).WithWidth(boxWidth)-- if err := form.Run(); err != nil {- return false, err- }- return accepted, nil-}--// PromptForInput shows the input box and returns the user input-// Returns the input string and an error if the user cancelled (Ctrl+C)-func (d *Display) PromptForInput() (string, error) {- d.StopLoading()- var userInput string-- // Rebind tab to complete the suggestion and enter to submit.- keymap := huh.NewDefaultKeyMap()- keymap.Input.AcceptSuggestion = key.NewBinding(key.WithKeys("tab"), key.WithHelp("tab", "complete"))- keymap.Input.Next = key.NewBinding(key.WithKeys("enter"), key.WithHelp("enter", "submit"))-- form := huh.NewForm(- huh.NewGroup(- huh.NewInput().- Placeholder("Enter prompt... (type `q` to quit)").- Suggestions([]string{"/config"}).- Value(&userInput),- ),- ).WithWidth(boxWidth).WithShowHelp(false).WithKeyMap(keymap)-- if err := form.Run(); err != nil {- return "", err- }- return userInput, nil-}--// configKeyMap returns a huh keymap for the /config menu that cancels on esc in-// addition to the default ctrl+c, and shows a consistent "esc close" hint in-// every field's help footer.-func configKeyMap() *huh.KeyMap {- km := huh.NewDefaultKeyMap()- km.Quit = key.NewBinding(key.WithKeys("ctrl+c", "esc"), key.WithHelp("esc", "close"))-- // Surface the esc hint through a slot that stays enabled.- closeHint := key.NewBinding(key.WithKeys("esc"), key.WithHelp("esc", "close"))- km.Select.Filter = closeHint- km.Text.Editor = closeHint- return km-}--// clearMenuOnCancel converts the interrupt huh emits on cancel (esc/ctrl+c) into-// a graceful quit.-var clearMenuOnCancel = tea.WithFilter(func(_ tea.Model, msg tea.Msg) tea.Msg {- if _, ok := msg.(tea.InterruptMsg); ok {- return tea.QuitMsg{}- }- return msg-})--// PromptForConfigAction shows the /config menu and returns the chosen action,-// one of "edit", "load", or "cancel". It returns an error if the user cancelled-// (Ctrl+C or Esc).-func (d *Display) PromptForConfigAction() (string, error) {- var action string- form := huh.NewForm(- huh.NewGroup(- huh.NewSelect[string]().- Title("Harness config").- Options(- huh.NewOption("View/edit config", "edit"),- huh.NewOption("Load from file", "load"),- huh.NewOption("Cancel", "cancel"),- ).- Value(&action),- ),- ).WithWidth(boxWidth).WithKeyMap(configKeyMap()).WithProgramOptions(clearMenuOnCancel)-- if err := form.Run(); err != nil {- return "", err- }- return action, nil-}--// PromptForConfigEdit shows a multi-line editor pre-filled with current and-// returns the edited text. It returns an error if the user cancelled (Ctrl+C or-// Esc).-func (d *Display) PromptForConfigEdit(current string) (string, error) {- text := current- form := huh.NewForm(- huh.NewGroup(- huh.NewText().- Title("Harness config (JSON, leave empty to clear)").- Lines(10).- ExternalEditor(true).- Value(&text),- ),- ).WithWidth(boxWidth).WithKeyMap(configKeyMap()).WithProgramOptions(clearMenuOnCancel)-- if err := form.Run(); err != nil {- return "", err- }- return text, nil-}--// PromptForConfigFile shows a file browser for selecting a JSON config file and-// returns the chosen path. It returns an error if the user cancelled (Ctrl+C or-// Esc).-func (d *Display) PromptForConfigFile() (string, error) {- var path string- form := huh.NewForm(- huh.NewGroup(- huh.NewFilePicker().- Title("Load harness config").- CurrentDirectory(".").- AllowedTypes([]string{".json"}).- FileAllowed(true).- DirAllowed(false).- Picking(true).- Height(10).- Value(&path),- ),- ).WithWidth(boxWidth).WithKeyMap(configKeyMap()).WithProgramOptions(clearMenuOnCancel)-- if err := form.Run(); err != nil {- return "", err- }- return path, nil-}--func (d *Display) ShowResumption(id string, server string) {- fmt.Fprintln(d.w, d.resumeStyle.Render("To resume the conversation,"))- if server != "" {- fmt.Fprintln(d.w, d.resumeStyle.Render(fmt.Sprintf("ax --conversation %s --server %s", id, server)))- } else {- fmt.Fprintln(d.w, d.resumeStyle.Render(fmt.Sprintf("ax --conversation %s", id)))- }-}diff --git a/cmd/ax/internal/display_test.go b/cmd/ax/internal/display_test.godeleted file mode 100644index d610816..0000000--- a/cmd/ax/internal/display_test.go+++ /dev/null@@ -1,186 +0,0 @@-// 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 internal--import (- "bytes"- "testing"-- "github.com/google/ax/proto"- "google.golang.org/protobuf/types/known/structpb"-)--func TestDisplay_Streaming(t *testing.T) {- stepText := func(txt string) *proto.Step {- return &proto.Step{- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Content: []*proto.Content{- {Type: &proto.Content_Text{Text: &proto.TextContent{Text: txt}}},- },- },- },- }- }- stepThought := func(txt string) *proto.Step {- return &proto.Step{- Type: &proto.Step_Thought{- Thought: &proto.ThoughtStep{- Summary: []*proto.Content{- {Type: &proto.Content_Text{Text: &proto.TextContent{Text: txt}}},- },- },- },- }- }-- t.Run("consecutive thought chunks are concatenated with prefix", func(t *testing.T) {- t.Parallel()- var buf bytes.Buffer- d := NewDisplay("test-id", &buf)-- d.Display(stepThought("thinking "))- d.Display(stepThought("deeply"))-- got := buf.String()- want := "Thinking: thinking deeply"- if got != want {- t.Errorf("got %q, want %q", got, want)- }- })-- t.Run("transition from thought to text adds newline", func(t *testing.T) {- t.Parallel()- var buf bytes.Buffer- d := NewDisplay("test-id", &buf)-- d.Display(stepThought("thinking"))- d.Display(stepText("Hello"))-- got := buf.String()- want := "Thinking: thinking\nHello"- if got != want {- t.Errorf("got %q, want %q", got, want)- }- })-- t.Run("transition from text to thought adds newline", func(t *testing.T) {- t.Parallel()- var buf bytes.Buffer- d := NewDisplay("test-id", &buf)-- d.Display(stepText("Hello"))- d.Display(stepThought("thinking"))-- got := buf.String()- want := "Hello\nThinking: thinking"- if got != want {- t.Errorf("got %q, want %q", got, want)- }- })-- t.Run("FinishOutput empty resets state and adds newlines", func(t *testing.T) {- t.Parallel()- var buf bytes.Buffer- d := NewDisplay("test-id", &buf)-- d.Display(stepText("Hello"))- d.FinishOutput("")-- got := buf.String()- want := "Hello\n\n"- if got != want {- t.Errorf("got %q, want %q", got, want)- }- })-- t.Run("FinishOutput with info prints info and resets state", func(t *testing.T) {- t.Parallel()- var buf bytes.Buffer- d := NewDisplay("test-id", &buf)-- d.Display(stepText("Hello"))- d.FinishOutput("seq=1")-- got := buf.String()- if !bytes.HasPrefix([]byte(got), []byte("Hello\n")) {- t.Errorf("expected Hello to end with newline, got %q", got)- }- if !bytes.Contains([]byte(got), []byte("seq=1")) {- t.Errorf("expected output to contain seq=1, got %q", got)- }- })-- t.Run("displaySystem resets state and prints newline", func(t *testing.T) {- t.Parallel()- var buf bytes.Buffer- d := NewDisplay("test-id", &buf)-- d.Display(stepText("Hello"))- d.displaySystem("system message")-- got := buf.String()- want := "Hello\nsystem message\n"- if got != want {- t.Errorf("got %q, want %q", got, want)- }- })-- t.Run("DisplayInput resets state and adds separation newlines", func(t *testing.T) {- t.Parallel()- var buf bytes.Buffer- d := NewDisplay("test-id", &buf)-- d.Display(stepText("Hello"))- d.DisplayInput("prompt")-- got := buf.String()- if !bytes.HasPrefix([]byte(got), []byte("Hello\n")) {- t.Errorf("expected Hello to end with newline, got %q", got)- }- if !bytes.Contains([]byte(got), []byte("prompt")) {- t.Errorf("expected output to contain prompt, got %q", got)- }- })-- t.Run("ToolCall displays formatted tool name and parameters", func(t *testing.T) {- t.Parallel()- var buf bytes.Buffer- d := NewDisplay("test-id", &buf)-- args, err := structpb.NewStruct(map[string]any{"query": "golang"})- if err != nil {- t.Fatalf("failed to create struct: %v", err)- }-- d.Display(&proto.Step{- Type: &proto.Step_ToolCall{- ToolCall: &proto.ToolCallStep{- Type: &proto.ToolCallStep_FunctionCall{- FunctionCall: &proto.FunctionCallStep{- Name: "search_web",- Arguments: args,- },- },- },- },- })-- got := buf.String()- if !bytes.Contains([]byte(got), []byte("🛠")) || !bytes.Contains([]byte(got), []byte("search_web")) || !bytes.Contains([]byte(got), []byte("golang")) {- t.Errorf("expected output to display formatted tool call, got %q", got)- }- })-}diff --git a/cmd/ax/main.go b/cmd/ax/main.goindex 0112a76..7b2922e 100644--- a/cmd/ax/main.go+++ b/cmd/ax/main.go@@ -12,73 +12,1219 @@// See the License for the specific language governing permissions and// limitations under the License.-// AX is a server for managing agent orchestrator tasks.-// It provides commands to execute tasks, resume from checkpoints,-// register agents, and run the controller server.package mainimport (+ "bytes"+ "context""errors""fmt"+ "io"+ "net""os"+ "sort"+ "strconv"+ "strings"+ "text/tabwriter"+ "time"- "github.com/google/ax/cmd/ax/internal/cliutil"- "github.com/spf13/cobra"+ "github.com/google/ax/internal/guest"+ "github.com/google/ax/internal/tunnel"+ "github.com/google/ax/pkg/apis/v1alpha1""google.golang.org/grpc"+ "google.golang.org/grpc/codes""google.golang.org/grpc/credentials/insecure"+ "google.golang.org/grpc/status"+ "google.golang.org/protobuf/proto"+ "gopkg.in/yaml.v3")func main() {- if err := rootCmd.Execute(); err != nil {+ if len(os.Args) < 2 {+ printUsage()+ os.Exit(1)+ }++ var (+ cmd string+ cleanArgs []string+ atespace = "default"+ explicitServer = ""+ kubeContext = ""+ axNamespace = "ax-system"+ )++ args := os.Args[1:]+ for i := 0; i < len(args); i++ {+ arg := args[i]+ if arg == "-a" || arg == "--atespace" {+ if i+1 < len(args) {+ atespace = args[i+1]+ i+++ }+ } else if strings.HasPrefix(arg, "--atespace=") {+ atespace = strings.TrimPrefix(arg, "--atespace=")+ } else if arg == "--server" {+ if i+1 < len(args) {+ explicitServer = args[i+1]+ i+++ }+ } else if strings.HasPrefix(arg, "--server=") {+ explicitServer = strings.TrimPrefix(arg, "--server=")+ } else if arg == "--context" {+ if i+1 < len(args) {+ kubeContext = args[i+1]+ i+++ }+ } else if strings.HasPrefix(arg, "--context=") {+ kubeContext = strings.TrimPrefix(arg, "--context=")+ } else if arg == "-n" || arg == "--namespace" {+ if i+1 < len(args) {+ axNamespace = args[i+1]+ i+++ }+ } else if strings.HasPrefix(arg, "--namespace=") {+ axNamespace = strings.TrimPrefix(arg, "--namespace=")+ } else if cmd == "" && !strings.HasPrefix(arg, "-") {+ cmd = arg+ } else {+ cleanArgs = append(cleanArgs, arg)+ }+ }++ if cmd == "" {+ printUsage()+ os.Exit(1)+ }++ // Commands that don't require an AX server connection+ switch cmd {+ case "version":+ fmt.Println("ax version v1alpha1 (standalone redis engine)")+ return+ case "help", "-h", "--help":+ printUsage()+ return+ case "ctx", "context":+ if err := runContext(kubeContext); err != nil {+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)+ os.Exit(1)+ }+ return+ case "tunnel":+ if err := runTunnel(cleanArgs); err != nil {+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)+ os.Exit(1)+ }+ return+ }++ // Resolve the AX server URL (auto-tunneling to active kube context if not explicitly set)+ serverURL, err := tunnel.EnsureServerURL(tunnel.Options{+ ServerURL: explicitServer,+ Context: kubeContext,+ Namespace: axNamespace,+ })+ if err != nil {+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)+ os.Exit(1)+ }++ switch cmd {+ case "apply":+ err = runApply(serverURL, cleanArgs)+ case "get":+ err = runGet(serverURL, atespace, cleanArgs)+ case "describe":+ err = runDescribe(serverURL, atespace, cleanArgs)+ case "watch":+ err = runWatch(serverURL, atespace, cleanArgs)+ case "suspend":+ err = runSuspend(serverURL, atespace, cleanArgs)+ case "resume":+ err = runResume(serverURL, atespace, cleanArgs)+ case "delete":+ err = runDelete(serverURL, atespace, cleanArgs)+ case "ssh":+ err = runSSH(serverURL, atespace, kubeContext, cleanArgs)+ default:+ fmt.Fprintf(os.Stderr, "unknown command: %s\n", cmd)+ printUsage()+ os.Exit(1)+ }++ if err != nil {fmt.Fprintf(os.Stderr, "Error: %v\n", err)os.Exit(1)}}-var rootCmd = &cobra.Command{- Use: "ax",- Short: "Execute a conversation or resume an existing one",- Long: `Execute a new conversation or resume an existing one.-If no conversation ID is provided, a new UUID will be generated.`,- SilenceUsage: true,- SilenceErrors: true,- RunE: runExec,+func printUsage() {+ fmt.Println(`AX CLI - Autonomous agent execution control++Usage:+ ax [command] [flags]++Available Commands:+ apply -f <file> Apply resources (tasks, gateways, workspaces, models) from a file or stdin+ get tasks List tasks+ get task <name> Get a specific task+ get gateways List gateways+ get gateway <name> Get a specific gateway+ get workspaces List workspaces+ get workspace <name> Get a specific workspace+ get models List models+ get model <name> Get a specific model+ describe task <name> Show detailed information about a task+ describe gateway <name> Show detailed information about a gateway+ describe workspace <name> Show detailed information about a workspace+ describe model <name> Show detailed information about a model+ watch task <name> Stream live status and condition updates for a task+ ssh <task-name> [-- cmd] Run a command or shell inside the running task container+ suspend task <name> Suspend execution of a task and checkpoint state+ resume task <name> Resume execution of a suspended task+ delete task <name> Delete a task+ delete gateway <name> Delete a gateway+ delete workspace <name> Delete a workspace+ delete model <name> Delete a model+ ctx, context Show active Kubernetes context and AX connection+ tunnel <list|stop> Manage background tunnels to Kubernetes clusters+ version Print AX version++Flags:+ -a, --atespace string Task atespace scope (default: "default")+ -n, --namespace string Kubernetes namespace where AX is installed (default: "ax-system")+ --context string Kubernetes context (defaults to active kubectx / current-context)+ --server string AX API server address (default: auto-detected from kube context or $AX_SERVER)`)}-func init() {- registerExecFlags(rootCmd)+func getAXClient(serverURL string) (v1alpha1.AXClient, *grpc.ClientConn, error) {+ target := strings.TrimPrefix(serverURL, "http://")+ target = strings.TrimPrefix(target, "https://")+ conn, err := grpc.NewClient(target, grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ return nil, nil, fmt.Errorf("connecting to %s: %w", target, err)+ }+ return v1alpha1.NewAXClient(conn), conn, nil+}- rootCmd.AddCommand(execCmd)- rootCmd.AddCommand(serveCmd)- rootCmd.AddCommand(doctorCmd)+func runApply(serverURL string, args []string) error {+ data, ok, err := manifestFromArgs(args)+ if err != nil {+ return err+ }+ if !ok {+ return fmt.Errorf("missing required flag: -f <file>")+ }++ client, conn, err := getAXClient(serverURL)+ if err != nil {+ return err+ }+ defer conn.Close()++ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()++ // Manifests are parsed here and submitted one resource at a time through the+ // typed RPCs; the server never sees raw YAML.+ decoder := yaml.NewDecoder(bytes.NewReader(data))+ for docIndex := 1; ; docIndex++ {+ var doc yaml.Node+ if err := decoder.Decode(&doc); err != nil {+ if errors.Is(err, io.EOF) {+ return nil+ }+ return fmt.Errorf("decoding document %d: %w", docIndex, err)+ }+ if doc.Kind == 0 || (doc.Kind == yaml.DocumentNode && len(doc.Content) == 0) {+ continue // empty document, e.g. a trailing "---"+ }++ kind, name, outcome, err := applyDocument(ctx, client, &doc)+ if err != nil {+ return fmt.Errorf("applying document %d: %w", docIndex, err)+ }+ fmt.Printf("%s.ax.io/%s %s\n", strings.ToLower(kind), name, outcome)+ }}-func connect(server string) (*grpc.ClientConn, error) {- conn, err := grpc.NewClient(server,- grpc.WithTransportCredentials(insecure.NewCredentials()),- )+// applyDocument decodes one manifest by its kind and submits it with the matching+// Update RPC. It reports the kind, the resource name, and whether the resource was+// created, configured (spec changed), or unchanged, in the style of kubectl apply.+func applyDocument(ctx context.Context, client v1alpha1.AXClient, doc *yaml.Node) (kind, name, outcome string, err error) {+ var head struct {+ Kind string `yaml:"kind"`+ }+ if err := doc.Decode(&head); err != nil {+ return "", "", "", fmt.Errorf("reading kind: %w", err)+ }++ switch head.Kind {+ case v1alpha1.KindTask:+ var task v1alpha1.Task+ if err := doc.Decode(&task); err != nil {+ return "", "", "", err+ }+ existing, err := client.GetTask(ctx, &v1alpha1.GetTaskRequest{Atespace: task.GetMetadata().GetAtespace(), Name: task.GetMetadata().GetName()})+ outcome, err := applyOutcome(err, existing.GetSpec(), task.GetSpec())+ if err != nil {+ return "", "", "", err+ }+ res, err := client.UpdateTask(ctx, &v1alpha1.UpdateTaskRequest{Task: &task})+ return head.Kind, res.GetMetadata().GetName(), outcome, err++ case v1alpha1.KindGateway:+ var gw v1alpha1.Gateway+ if err := doc.Decode(&gw); err != nil {+ return "", "", "", err+ }+ existing, err := client.GetGateway(ctx, &v1alpha1.GetGatewayRequest{Atespace: gw.GetMetadata().GetAtespace(), Name: gw.GetMetadata().GetName()})+ outcome, err := applyOutcome(err, existing.GetSpec(), gw.GetSpec())+ if err != nil {+ return "", "", "", err+ }+ res, err := client.UpdateGateway(ctx, &v1alpha1.UpdateGatewayRequest{Gateway: &gw})+ return head.Kind, res.GetMetadata().GetName(), outcome, err++ case v1alpha1.KindWorkspace:+ var ws v1alpha1.Workspace+ if err := doc.Decode(&ws); err != nil {+ return "", "", "", err+ }+ existing, err := client.GetWorkspace(ctx, &v1alpha1.GetWorkspaceRequest{Atespace: ws.GetMetadata().GetAtespace(), Name: ws.GetMetadata().GetName()})+ outcome, err := applyOutcome(err, existing.GetSpec(), ws.GetSpec())+ if err != nil {+ return "", "", "", err+ }+ res, err := client.UpdateWorkspace(ctx, &v1alpha1.UpdateWorkspaceRequest{Workspace: &ws})+ return head.Kind, res.GetMetadata().GetName(), outcome, err++ case v1alpha1.KindModel:+ var m v1alpha1.Model+ if err := doc.Decode(&m); err != nil {+ return "", "", "", err+ }+ existing, err := client.GetModel(ctx, &v1alpha1.GetModelRequest{Atespace: m.GetMetadata().GetAtespace(), Name: m.GetMetadata().GetName()})+ outcome, err := applyOutcome(err, existing.GetSpec(), m.GetSpec())+ if err != nil {+ return "", "", "", err+ }+ res, err := client.UpdateModel(ctx, &v1alpha1.UpdateModelRequest{Model: &m})+ return head.Kind, res.GetMetadata().GetName(), outcome, err++ case "":+ return "", "", "", errors.New("missing kind")+ default:+ return "", "", "", fmt.Errorf("unsupported kind %q (expected Task, Gateway, Workspace, or Model)", head.Kind)+ }+}++// applyOutcome classifies an apply from the result of looking up the existing+// resource: "created" when it did not exist, "unchanged" when its spec already+// matches, and "configured" otherwise. Lookup failures other than NotFound are+// returned as errors.+func applyOutcome(lookupErr error, existingSpec, newSpec proto.Message) (string, error) {+ if lookupErr != nil {+ if status.Code(lookupErr) == codes.NotFound {+ return "created", nil+ }+ return "", fmt.Errorf("looking up existing resource: %w", lookupErr)+ }+ if proto.Equal(existingSpec, newSpec) {+ return "unchanged", nil+ }+ return "configured", nil+}++func runGet(serverURL, atespace string, args []string) error {+ if len(args) == 0 {+ return fmt.Errorf("specify resource to get (e.g. 'ax get tasks' or 'ax get task <name>')")+ }++ resource := strings.ToLower(args[0])++ client, conn, err := getAXClient(serverURL)if err != nil {- return nil, fmt.Errorf("failed to connect to server: %w", err)+ return err}- return conn, nil+ defer conn.Close()++ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ if resource == "tasks" || resource == "task" && len(args) == 1 {+ resp, err := client.ListTasks(ctx, &v1alpha1.ListTasksRequest{Atespace: atespace})+ if err != nil {+ return fmt.Errorf("listing tasks: %w", err)+ }++ tasks := resp.Tasks++ w := tabwriter.NewWriter(os.Stdout, 0, 8, 3, ' ', 0)+ fmt.Fprintln(w, "NAME\tATESPACE\tPHASE\tACTOR\tWORKER-IP\tAGE")+ for _, t := range tasks {+ workerIP := ""+ actor := ""+ phase := "Pending"+ if t.Status != nil {+ workerIP = t.Status.WorkerIp+ actor = t.Status.Actor+ if t.Status.Phase != "" {+ phase = t.Status.Phase+ }+ }+ if workerIP == "" {+ workerIP = "<none>"+ }+ if actor == "" {+ actor = "<none>"+ }+ age := "<unknown>"+ name := ""+ tAtespace := ""+ if t.Metadata != nil {+ name = t.Metadata.Name+ tAtespace = t.Metadata.Atespace+ if t.Metadata.CreationTimestamp != nil {+ age = formatAge(time.Since(t.Metadata.CreationTimestamp.AsTime()))+ }+ }+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n",+ name,+ tAtespace,+ phase,+ actor,+ workerIP,+ age,+ )+ }+ return w.Flush()+ }++ if (resource == "task" || resource == "tasks") && len(args) >= 2 {+ name := args[1]+ task, err := client.GetTask(ctx, &v1alpha1.GetTaskRequest{Atespace: atespace, Name: name})+ if err != nil {+ return fmt.Errorf("getting task %q: %w", name, err)+ }++ return yaml.NewEncoder(os.Stdout).Encode(task)+ }++ if resource == "gateways" || resource == "gateway" && len(args) == 1 {+ resp, err := client.ListGateways(ctx, &v1alpha1.ListGatewaysRequest{Atespace: atespace})+ if err != nil {+ return fmt.Errorf("listing gateways: %w", err)+ }++ gateways := resp.Gateways++ w := tabwriter.NewWriter(os.Stdout, 0, 8, 3, ' ', 0)+ fmt.Fprintln(w, "NAME\tATESPACE\tLISTENERS\tEGRESS-HOSTS")+ for _, g := range gateways {+ var listenerList []string+ if g.Spec != nil {+ for _, l := range g.Spec.Listeners {+ listenerList = append(listenerList, fmt.Sprintf("%d/%s", l.Port, l.Protocol))+ }+ }+ listenersStr := strings.Join(listenerList, ",")+ if listenersStr == "" {+ listenersStr = "<none>"+ }++ var hostList []string+ if g.Spec != nil && g.Spec.Egress != nil && g.Spec.Egress.Allowlist != nil {+ for _, h := range g.Spec.Egress.Allowlist.Hosts {+ hostList = append(hostList, h.Host)+ }+ }+ egressStr := strings.Join(hostList, ",")+ if egressStr == "" {+ egressStr = "<none>"+ }++ name := ""+ gwAtespace := ""+ if g.Metadata != nil {+ name = g.Metadata.Name+ gwAtespace = g.Metadata.Atespace+ }+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\n",+ name,+ gwAtespace,+ listenersStr,+ egressStr,+ )+ }+ return w.Flush()+ }++ if (resource == "gateway" || resource == "gateways") && len(args) >= 2 {+ name := args[1]+ gw, err := client.GetGateway(ctx, &v1alpha1.GetGatewayRequest{Atespace: atespace, Name: name})+ if err != nil {+ return fmt.Errorf("getting gateway %q: %w", name, err)+ }++ return yaml.NewEncoder(os.Stdout).Encode(gw)+ }++ if resource == "workspaces" || resource == "workspace" && len(args) == 1 {+ resp, err := client.ListWorkspaces(ctx, &v1alpha1.ListWorkspacesRequest{Atespace: atespace})+ if err != nil {+ return fmt.Errorf("listing workspaces: %w", err)+ }++ workspaces := resp.Workspaces++ w := tabwriter.NewWriter(os.Stdout, 0, 8, 3, ' ', 0)+ fmt.Fprintln(w, "NAME\tATESPACE\tGIT-REPOS\tMCP-SERVERS")+ for _, ws := range workspaces {+ gitCount := "0"+ mcpCount := "0"+ if ws.Spec != nil {+ gitCount = fmt.Sprintf("%d", len(ws.Spec.Git))+ if ws.Spec.Mcp != nil {+ mcpCount = fmt.Sprintf("%d", len(ws.Spec.Mcp.Servers))+ }+ }+ name := ""+ wsAtespace := ""+ if ws.Metadata != nil {+ name = ws.Metadata.Name+ wsAtespace = ws.Metadata.Atespace+ }+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\n",+ name,+ wsAtespace,+ gitCount,+ mcpCount,+ )+ }+ return w.Flush()+ }++ if (resource == "workspace" || resource == "workspaces") && len(args) >= 2 {+ name := args[1]+ ws, err := client.GetWorkspace(ctx, &v1alpha1.GetWorkspaceRequest{Atespace: atespace, Name: name})+ if err != nil {+ return fmt.Errorf("getting workspace %q: %w", name, err)+ }++ return yaml.NewEncoder(os.Stdout).Encode(ws)+ }++ if resource == "models" || resource == "model" && len(args) == 1 {+ resp, err := client.ListModels(ctx, &v1alpha1.ListModelsRequest{Atespace: atespace})+ if err != nil {+ return fmt.Errorf("listing models: %w", err)+ }++ models := resp.Models++ w := tabwriter.NewWriter(os.Stdout, 0, 8, 3, ' ', 0)+ fmt.Fprintln(w, "NAME\tATESPACE\tPROVIDER\tMODEL")+ for _, m := range models {+ name := ""+ mAtespace := ""+ if m.Metadata != nil {+ name = m.Metadata.Name+ mAtespace = m.Metadata.Atespace+ }+ provider := ""+ modelName := ""+ if m.Spec != nil {+ provider = m.Spec.Provider+ modelName = m.Spec.Model+ }+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\n",+ name,+ mAtespace,+ provider,+ modelName,+ )+ }+ return w.Flush()+ }++ if (resource == "model" || resource == "models") && len(args) >= 2 {+ name := args[1]+ m, err := client.GetModel(ctx, &v1alpha1.GetModelRequest{Atespace: atespace, Name: name})+ if err != nil {+ return fmt.Errorf("getting model %q: %w", name, err)+ }++ return yaml.NewEncoder(os.Stdout).Encode(m)+ }++ return fmt.Errorf("unknown resource %q", resource)}-const currentVersion = "v1alpha"+func runDescribe(serverURL, atespace string, args []string) error {+ if len(args) < 2 {+ return fmt.Errorf("usage: ax describe <task|gateway|workspace|model> <name>")+ }+ kind := strings.ToLower(args[0])+ name := args[1]++ client, conn, err := getAXClient(serverURL)+ if err != nil {+ return err+ }+ defer conn.Close()++ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ if kind == "model" || kind == "models" {+ m, err := client.GetModel(ctx, &v1alpha1.GetModelRequest{Atespace: atespace, Name: name})+ if err != nil {+ return fmt.Errorf("getting model %q: %w", name, err)+ }++ mName := ""+ mAtespace := ""+ if m.Metadata != nil {+ mName = m.Metadata.Name+ mAtespace = m.Metadata.Atespace+ }+ fmt.Printf("Name: %s\n", mName)+ fmt.Printf("Atespace: %s\n", mAtespace)+ if m.Spec != nil {+ fmt.Printf("Provider: %s\n", m.Spec.Provider)+ fmt.Printf("Model: %s\n", m.Spec.Model)+ if params := m.Spec.GetParameters().AsMap(); len(params) > 0 {+ fmt.Println("Parameters:")+ keys := make([]string, 0, len(params))+ for k := range params {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ for _, k := range keys {+ fmt.Printf(" %s: %v\n", k, params[k])+ }+ }+ if m.Spec.SecretKey != nil {+ if m.Spec.SecretKey.Name != "" && m.Spec.SecretKey.Key != "" && m.Spec.SecretKey.Name != m.Spec.SecretKey.Key {+ fmt.Printf("Secret Key: %s (key: %s)\n", m.Spec.SecretKey.Name, m.Spec.SecretKey.Key)+ } else if m.Spec.SecretKey.Key != "" {+ fmt.Printf("Secret Key: %s\n", m.Spec.SecretKey.Key)+ } else if m.Spec.SecretKey.Name != "" {+ fmt.Printf("Secret Key: %s\n", m.Spec.SecretKey.Name)+ }+ }+ }+ return nil+ }++ if kind == "workspace" || kind == "workspaces" {+ ws, err := client.GetWorkspace(ctx, &v1alpha1.GetWorkspaceRequest{Atespace: atespace, Name: name})+ if err != nil {+ return fmt.Errorf("getting workspace %q: %w", name, err)+ }++ wsName := ""+ wsAtespace := ""+ if ws.Metadata != nil {+ wsName = ws.Metadata.Name+ wsAtespace = ws.Metadata.Atespace+ }+ fmt.Printf("Name: %s\n", wsName)+ fmt.Printf("Atespace: %s\n", wsAtespace)+ if ws.Spec != nil {+ if len(ws.Spec.Git) > 0 {+ fmt.Println("Git Repositories:")+ for _, g := range ws.Spec.Git {+ branch := g.Branch+ if branch == "" {+ branch = "main"+ }+ fmt.Printf(" - %s (%s, branch: %s)\n", g.Name, g.Repo, branch)+ }+ }+ if ws.Spec.Mcp != nil {+ if len(ws.Spec.Mcp.Registries) > 0 {+ fmt.Println("MCP Registries:")+ for _, r := range ws.Spec.Mcp.Registries {+ fmt.Printf(" - Provider: %s, Query: %q\n", r.Provider, r.Query)+ }+ }+ if len(ws.Spec.Mcp.Servers) > 0 {+ fmt.Println("MCP Servers:")+ for _, s := range ws.Spec.Mcp.Servers {+ if s.Endpoint != "" {+ fmt.Printf(" - %s: %s\n", s.Name, s.Endpoint)+ } else {+ fmt.Printf(" - %s: %s %v\n", s.Name, s.Command, s.Args)+ }+ }+ }+ }+ if ws.Spec.Skills != nil {+ if len(ws.Spec.Skills.Registries) > 0 {+ fmt.Println("Skill Registries:")+ for _, r := range ws.Spec.Skills.Registries {+ fmt.Printf(" - Provider: %s, Query: %q\n", r.Provider, r.Query)+ }+ }+ if ws.Spec.Skills.Path != "" {+ fmt.Printf("Skills Path: %s\n", ws.Spec.Skills.Path)+ }+ }+ }+ return nil+ }++ if kind == "gateway" || kind == "gateways" {+ gw, err := client.GetGateway(ctx, &v1alpha1.GetGatewayRequest{Atespace: atespace, Name: name})+ if err != nil {+ return fmt.Errorf("getting gateway %q: %w", name, err)+ }-func newConfig(cmd *cobra.Command, configFile string) (*cliutil.Config, error) {- cfg, err := cliutil.LoadFromFile(configFile)- configFlagChanged := (cmd.Flags().Lookup("config") != nil && cmd.Flags().Changed("config")) ||- (cmd.Flags().Lookup("agent-config-file") != nil && cmd.Flags().Changed("agent-config-file"))- if errors.Is(err, os.ErrNotExist) && !configFlagChanged {- cfg := cliutil.DefaultConfig()- cfg.Version = currentVersion- return cfg, nil+ gwName := ""+ gwAtespace := ""+ if gw.Metadata != nil {+ gwName = gw.Metadata.Name+ gwAtespace = gw.Metadata.Atespace+ }+ fmt.Printf("Name: %s\n", gwName)+ fmt.Printf("Atespace: %s\n", gwAtespace)+ if gw.Spec != nil {+ if len(gw.Spec.Listeners) > 0 {+ fmt.Println("Listeners:")+ for _, l := range gw.Spec.Listeners {+ fmt.Printf(" - %s: %d (%s)\n", l.Name, l.Port, l.Protocol)+ }+ }+ if gw.Spec.Egress != nil && gw.Spec.Egress.Allowlist != nil && len(gw.Spec.Egress.Allowlist.Hosts) > 0 {+ fmt.Println("Egress Allowlist:")+ for _, h := range gw.Spec.Egress.Allowlist.Hosts {+ fmt.Printf(" - %s:%d\n", h.Host, h.Port)+ }+ }+ }+ return nil}++ task, err := client.GetTask(ctx, &v1alpha1.GetTaskRequest{Atespace: atespace, Name: name})if err != nil {- return nil, fmt.Errorf("error loading config file '%s': %w", configFile, err)+ return fmt.Errorf("getting task %q: %w", name, err)+ }++ taskName := ""+ taskAtespace := ""+ if task.Metadata != nil {+ taskName = task.Metadata.Name+ taskAtespace = task.Metadata.Atespace+ }+ phase := ""+ actor := ""+ workerIP := ""+ var conditions []*v1alpha1.Condition+ if task.Status != nil {+ phase = task.Status.Phase+ actor = task.Status.Actor+ workerIP = task.Status.WorkerIp+ conditions = task.Status.Conditions+ }++ fmt.Printf("Name: %s\n", taskName)+ fmt.Printf("Atespace: %s\n", taskAtespace)+ fmt.Printf("Phase: %s\n", phase)+ fmt.Printf("Actor: %s\n", actor)+ fmt.Printf("Worker IP: %s\n", workerIP)+ if task.Spec != nil {+ if task.Spec.Gateway != nil {+ fmt.Printf("Gateway: %s\n", task.Spec.Gateway.Name)+ }+ if refs := task.Spec.WorkspaceRefs(); len(refs) > 0 {+ paths := task.Spec.WorkspacePaths()+ fmt.Println("Workspaces:")+ for i, ref := range refs {+ fmt.Printf(" - %s path=%s", ref.Name, paths[i])+ if ref.Goal != "" {+ fmt.Printf(" goal=%q", ref.Goal)+ }+ fmt.Println()+ }+ }+ if task.Spec.Image != "" {+ fmt.Printf("Image: %s\n", task.Spec.Image)+ }+ if len(task.Spec.Command) > 0 {+ fmt.Printf("Command: %v\n", task.Spec.Command)+ }+ }++ if len(conditions) > 0 {+ fmt.Println("\nConditions:")+ w := tabwriter.NewWriter(os.Stdout, 0, 8, 2, ' ', 0)+ fmt.Fprintln(w, " TYPE\tSTATUS\tREASON\tMESSAGE")+ for _, c := range conditions {+ fmt.Fprintf(w, " %s\t%s\t%s\t%s\n", c.Type, c.Status, c.Reason, c.Message)+ }+ _ = w.Flush()}- if cfg.Version != currentVersion {- return nil, fmt.Errorf("unsupported config version %q, must be %q", cfg.Version, currentVersion)++ return nil+}++func runWatch(serverURL, atespace string, args []string) error {+ if len(args) < 2 {+ return fmt.Errorf("usage: ax watch task <name>")+ }+ name := args[1]++ client, conn, err := getAXClient(serverURL)+ if err != nil {+ return err}- return cfg, nil+ defer conn.Close()++ stream, err := client.WatchTask(context.Background(), &v1alpha1.WatchTaskRequest{Atespace: atespace, Name: name})+ if err != nil {+ return fmt.Errorf("watching task: %w", err)+ }++ fmt.Printf("Watching task %s/%s...\n", atespace, name)++ for {+ resp, err := stream.Recv()+ if err != nil {+ if errors.Is(err, io.EOF) {+ return nil+ }+ return fmt.Errorf("receiving stream update: %w", err)+ }++ task := resp.Task+ if task != nil {+ phase := ""+ actor := ""+ workerIP := ""+ if task.Status != nil {+ phase = task.Status.Phase+ actor = task.Status.Actor+ workerIP = task.Status.WorkerIp+ }+ fmt.Printf("[%s] Phase: %-10s Actor: %-18s WorkerIP: %s\n",+ time.Now().Format("15:04:05"),+ phase,+ actor,+ workerIP,+ )+ if phase == "Running" || phase == "Completed" || phase == "Failed" {+ fmt.Printf("Task reached terminal phase %q.\n", phase)+ break+ }+ }+ }+ return nil+}++// runDelete removes one resource by kind and name.+func runDelete(serverURL, atespace string, args []string) error {+ if len(args) < 2 {+ return fmt.Errorf("usage: ax delete <task|gateway|workspace|model> <name>")+ }+ kind, err := normalizeKind(args[0])+ if err != nil {+ return err+ }++ client, conn, err := getAXClient(serverURL)+ if err != nil {+ return err+ }+ defer conn.Close()++ // Task deletion waits for the controller to tear down the actor, which can take+ // a while; the other kinds are removed synchronously.+ timeout := 15 * time.Second+ if kind == v1alpha1.KindTask {+ timeout = deleteTaskTimeout+ }+ ctx, cancel := context.WithTimeout(context.Background(), timeout)+ defer cancel()++ return deleteResource(ctx, client, kind, atespace, args[1])+}++const (+ deleteTaskTimeout = 5 * time.Minute+ deletePollInterval = 500 * time.Millisecond+)++// deleteResource requests deletion, then blocks until the resource is really gone+// and prints a kubectl-style confirmation.+func deleteResource(ctx context.Context, client v1alpha1.AXClient, kind, atespace, name string) error {+ lower := strings.ToLower(kind)++ var err error+ switch kind {+ case v1alpha1.KindTask:+ _, err = client.DeleteTask(ctx, &v1alpha1.DeleteTaskRequest{Atespace: atespace, Name: name})+ case v1alpha1.KindGateway:+ _, err = client.DeleteGateway(ctx, &v1alpha1.DeleteGatewayRequest{Atespace: atespace, Name: name})+ case v1alpha1.KindWorkspace:+ _, err = client.DeleteWorkspace(ctx, &v1alpha1.DeleteWorkspaceRequest{Atespace: atespace, Name: name})+ case v1alpha1.KindModel:+ _, err = client.DeleteModel(ctx, &v1alpha1.DeleteModelRequest{Atespace: atespace, Name: name})+ default:+ return fmt.Errorf("unsupported kind %q", kind)+ }+ if err != nil {+ return fmt.Errorf("deleting %s %s/%s: %w", lower, atespace, name, err)+ }++ if err := waitForDeletion(ctx, client, kind, atespace, name); err != nil {+ return err+ }+ fmt.Printf("%s.ax.io/%s deleted\n", lower, name)+ return nil+}++// waitForDeletion polls until the resource returns NotFound or ctx expires.+func waitForDeletion(ctx context.Context, client v1alpha1.AXClient, kind, atespace, name string) error {+ lookup := func() error {+ var err error+ switch kind {+ case v1alpha1.KindTask:+ _, err = client.GetTask(ctx, &v1alpha1.GetTaskRequest{Atespace: atespace, Name: name})+ case v1alpha1.KindGateway:+ _, err = client.GetGateway(ctx, &v1alpha1.GetGatewayRequest{Atespace: atespace, Name: name})+ case v1alpha1.KindWorkspace:+ _, err = client.GetWorkspace(ctx, &v1alpha1.GetWorkspaceRequest{Atespace: atespace, Name: name})+ case v1alpha1.KindModel:+ _, err = client.GetModel(ctx, &v1alpha1.GetModelRequest{Atespace: atespace, Name: name})+ }+ return err+ }++ announced := false+ for {+ err := lookup()+ if status.Code(err) == codes.NotFound {+ return nil+ }+ if err != nil {+ return fmt.Errorf("checking %s %s/%s after delete: %w", strings.ToLower(kind), atespace, name, err)+ }+ if !announced {+ fmt.Fprintf(os.Stderr, "waiting for %s %s/%s to be deleted...\n", strings.ToLower(kind), atespace, name)+ announced = true+ }+ select {+ case <-ctx.Done():+ return fmt.Errorf("timed out waiting for %s %s/%s to be deleted; it is still being torn down (check `ax describe` and the controller logs)", strings.ToLower(kind), atespace, name)+ case <-time.After(deletePollInterval):+ }+ }+}++// normalizeKind maps user-typed kinds ("task", "tasks", "Task") to the canonical+// manifest kind, rejecting anything unknown.+func normalizeKind(kind string) (string, error) {+ switch strings.ToLower(strings.TrimSuffix(kind, "s")) {+ case "task":+ return v1alpha1.KindTask, nil+ case "gateway":+ return v1alpha1.KindGateway, nil+ case "workspace":+ return v1alpha1.KindWorkspace, nil+ case "model":+ return v1alpha1.KindModel, nil+ case "":+ return "", errors.New("missing kind")+ default:+ return "", fmt.Errorf("unsupported kind %q (expected task, gateway, workspace, or model)", kind)+ }+}++// manifestFromArgs returns the manifest named by -f/--file (or stdin for "-").+// ok is false when no -f flag is present.+func manifestFromArgs(args []string) (data []byte, ok bool, err error) {+ for i := 0; i < len(args); i++ {+ if args[i] != "-f" && args[i] != "--file" {+ continue+ }+ if i+1 >= len(args) {+ return nil, true, errors.New("-f requires a file path (or - for stdin)")+ }+ path := args[i+1]+ if path == "-" {+ data, err = io.ReadAll(os.Stdin)+ } else {+ data, err = os.ReadFile(path)+ }+ if err != nil {+ return nil, true, fmt.Errorf("reading %s: %w", path, err)+ }+ return data, true, nil+ }+ return nil, false, nil+}++func runSuspend(serverURL, atespace string, args []string) error {+ name := ""+ if len(args) == 1 {+ name = args[0]+ } else if len(args) >= 2 {+ if args[0] == "task" || args[0] == "tasks" {+ name = args[1]+ } else {+ name = args[0]+ }+ } else {+ return fmt.Errorf("usage: ax suspend task <name>")+ }++ client, conn, err := getAXClient(serverURL)+ if err != nil {+ return err+ }+ defer conn.Close()++ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ if _, err := client.SuspendTask(ctx, &v1alpha1.SuspendTaskRequest{Atespace: atespace, Name: name}); err != nil {+ return fmt.Errorf("suspending task: %w", err)+ }++ fmt.Printf("task.ax.io/%s suspended\n", name)+ return nil+}++func runResume(serverURL, atespace string, args []string) error {+ name := ""+ if len(args) == 1 {+ name = args[0]+ } else if len(args) >= 2 {+ if args[0] == "task" || args[0] == "tasks" {+ name = args[1]+ } else {+ name = args[0]+ }+ } else {+ return fmt.Errorf("usage: ax resume task <name>")+ }++ client, conn, err := getAXClient(serverURL)+ if err != nil {+ return err+ }+ defer conn.Close()++ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ if _, err := client.ResumeTask(ctx, &v1alpha1.ResumeTaskRequest{Atespace: atespace, Name: name}); err != nil {+ return fmt.Errorf("resuming task: %w", err)+ }++ fmt.Printf("task.ax.io/%s resumed\n", name)+ return nil+}++func formatAge(d time.Duration) string {+ if d < time.Minute {+ return fmt.Sprintf("%ds", int(d.Seconds()))+ }+ if d < time.Hour {+ return fmt.Sprintf("%dm", int(d.Minutes()))+ }+ if d < 24*time.Hour {+ return fmt.Sprintf("%dh", int(d.Hours()))+ }+ return fmt.Sprintf("%dd", int(d.Hours()/24))+}++func runContext(kubeContext string) error {+ ctxName, err := tunnel.CurrentContext(kubeContext)+ if err != nil || ctxName == "" {+ fmt.Println("No active Kubernetes context detected.")+ fmt.Println("Fallback server: http://localhost:8080 (or set $AX_SERVER / --server)")+ return nil+ }++ fmt.Printf("Active Kubernetes Context: %s\n", ctxName)+ if t, err := tunnel.GetTunnel(ctxName); err == nil && t != nil {+ status := "Healthy"+ if !tunnel.IsTunnelHealthy(t.Port) {+ status = "Stale / Not responding"+ }+ fmt.Printf("AX Tunnel: http://127.0.0.1:%d -> %s/svc/%s:8080 (PID: %d, %s)\n",+ t.Port, t.Namespace, t.Service, t.PID, status)+ } else {+ fmt.Println("AX Tunnel: No background tunnel running (will auto-connect on next command)")+ }+ return nil+}++func runTunnel(args []string) error {+ if len(args) == 0 {+ return fmt.Errorf("specify tunnel action: 'ax tunnel list' or 'ax tunnel stop [context]'")+ }++ switch args[0] {+ case "list":+ tunnels, err := tunnel.ListTunnels()+ if err != nil {+ return err+ }+ if len(tunnels) == 0 {+ fmt.Println("No active tunnels found in ~/.ax/tunnels.")+ return nil+ }+ w := tabwriter.NewWriter(os.Stdout, 0, 8, 2, ' ', 0)+ fmt.Fprintln(w, "CONTEXT\tLOCAL PORT\tREMOTE SERVICE\tPID\tSTATUS\tCREATED")+ for _, t := range tunnels {+ status := "Active"+ if !tunnel.IsTunnelHealthy(t.Port) {+ status = "Stale"+ }+ fmt.Fprintf(w, "%s\t%d\t%s/%s\t%d\t%s\t%s\n",+ t.Context, t.Port, t.Namespace, t.Service, t.PID, status, t.CreatedAt.Format("2006-01-02 15:04:05"))+ }+ return w.Flush()++ case "stop":+ if len(args) > 1 {+ ctxName := args[1]+ if err := tunnel.StopTunnelByContext(ctxName); err != nil {+ return fmt.Errorf("stopping tunnel for context %q: %w", ctxName, err)+ }+ fmt.Printf("Tunnel stopped for context %q\n", ctxName)+ return nil+ }+ cur, err := tunnel.CurrentContext("")+ if err != nil || cur == "" {+ return fmt.Errorf("no current context found to stop tunnel")+ }+ if err := tunnel.StopTunnelByContext(cur); err != nil {+ return fmt.Errorf("stopping tunnel for context %q: %w", cur, err)+ }+ fmt.Printf("Tunnel stopped for context %q\n", cur)+ return nil++ default:+ return fmt.Errorf("unknown tunnel subcommand: %s (available: list, stop)", args[0])+ }+}++func runSSH(serverURL, atespace, kubeContext string, args []string) error {+ if len(args) == 0 {+ return fmt.Errorf("usage: ax ssh <task-name> [-- command...]")+ }++ taskName := args[0]+ var cmdToRun []string+ for i := 1; i < len(args); i++ {+ if args[i] == "--" {+ cmdToRun = args[i+1:]+ break+ } else {+ cmdToRun = append(cmdToRun, args[i])+ }+ }++ if len(cmdToRun) == 0 {+ cmdToRun = []string{"/bin/sh"}+ }++ client, conn, err := getAXClient(serverURL)+ if err != nil {+ return err+ }+ defer conn.Close()++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ task, err := client.GetTask(ctx, &v1alpha1.GetTaskRequest{+ Atespace: atespace,+ Name: taskName,+ })+ if err != nil {+ return fmt.Errorf("fetching task %q: %w", taskName, err)+ }++ if task == nil || task.Status == nil {+ return fmt.Errorf("task %q has no status available", taskName)+ }++ if task.Status.Phase != "Running" {+ return fmt.Errorf("task %q is in phase %q (must be Running to ssh)", taskName, task.Status.Phase)+ }++ if !task.GetSpec().GetDebug() {+ return fmt.Errorf("task %q does not expose guest services; set spec.debug: true and re-apply to enable ax ssh", taskName)+ }++ workerIP := task.Status.WorkerIp+ if workerIP == "" {+ return fmt.Errorf("task %q has no worker IP assigned", taskName)+ }++ // The runner serves guest services on port 80 unless the worker IP says otherwise.+ host := workerIP+ port := 80+ if h, p, err := net.SplitHostPort(workerIP); err == nil {+ host = h+ if parsedPort, err := strconv.Atoi(p); err == nil {+ port = parsedPort+ }+ }++ targetActor := fmt.Sprintf("%s/%s", task.Metadata.Atespace, task.Status.Actor)+ var (+ guestClient *guest.Client+ cleanup func()+ )++ // 1. First, check if worker IP is directly reachable (e.g. within cluster or local mesh)+ d := net.Dialer{Timeout: 500 * time.Millisecond}+ guestEndpoint := net.JoinHostPort(host, fmt.Sprint(port))+ if testConn, dialErr := d.Dial("tcp", guestEndpoint); dialErr == nil {+ _ = testConn.Close()+ guestClient, err = guest.Dial(guestEndpoint)+ if err != nil {+ return fmt.Errorf("connecting to guest at %s: %w", guestEndpoint, err)+ }+ } else {+ // 2. Connect via the Substrate atenet-router service in ate-system (port 80)+ localPort, pfCleanup, err := tunnel.PortForward(context.Background(), kubeContext, "ate-system", "svc/atenet-router", 80)+ if err != nil {+ return fmt.Errorf("establishing port-forward to atenet-router: %w", err)+ }+ cleanup = pfCleanup+ routerEndpoint := fmt.Sprintf("127.0.0.1:%d", localPort)+ guestClient, err = guest.DialTarget(routerEndpoint, targetActor)+ if err != nil {+ return fmt.Errorf("connecting to guest via atenet-router at %s: %w", routerEndpoint, err)+ }+ }++ if cleanup != nil {+ defer cleanup()+ }+ defer guestClient.Close()++ exitCode, err := guestClient.Exec(context.Background(), guest.ExecOptions{+ Command: cmdToRun,+ Stdout: os.Stdout,+ Stderr: os.Stderr,+ })+ if err != nil {+ return err+ }++ if exitCode != 0 {+ os.Exit(exitCode)+ }++ return nil}diff --git a/cmd/ax/serve.go b/cmd/ax/serve.godeleted file mode 100644index d0b407e..0000000--- a/cmd/ax/serve.go+++ /dev/null@@ -1,113 +0,0 @@-// 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 main--import (- "context"- "fmt"- "log/slog"- "os"- "os/signal"- "syscall"-- "github.com/google/ax/cmd/ax/internal/cliutil"- "github.com/google/ax/internal/server"- "github.com/google/ax/internal/telemetry"- "github.com/spf13/cobra"- "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"-)--var (- serveConfigFile string-)--var serveCmd = &cobra.Command{- Use: "serve",- Short: "Run controller as a gRPC server",- Long: `Run the AX controller as a gRPC server.-Loads configuration from a YAML file (default: ax.yaml).`,- RunE: runServe,-}--func init() {- serveCmd.Flags().StringVar(&serveConfigFile, "config", "ax.yaml", "Path to YAML configuration file")-}--func runServe(cmd *cobra.Command, args []string) error {- ctx := cmd.Context()-- // Initialize structured logging (JSON to stdout)- slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))-- cfg, err := newConfig(cmd, serveConfigFile)- if err != nil {- return err- }-- // Validate configuration- if err := cfg.Validate(); err != nil {- return fmt.Errorf("invalid configuration: %w", err)- }-- // Initialize OpenTelemetry SDK- if cfg.Telemetry.OTLP.Enabled {- var opts []otlptracegrpc.Option- endpoint := cfg.Telemetry.OTLP.Endpoint- if endpoint == "" {- endpoint = defaultEndpoint- }- opts = append(opts, otlptracegrpc.WithEndpoint(endpoint))- if gcpOpts, ok := gcpTelemetryOpts(endpoint); ok {- opts = append(opts, gcpOpts...)- } else {- opts = append(opts, otlptracegrpc.WithInsecure())- }-- shutdown, err := telemetry.SetTraceProvider(ctx, "ax-server", opts...)- if err != nil {- return fmt.Errorf("failed to initialize telemetry: %w", err)- }- defer func() {- if err := shutdown(context.Background()); err != nil {- slog.Error("failed to shutdown telemetry", "error", err)- }- }()- }-- c, err := cliutil.NewControllerFromConfig(ctx, cfg)- if err != nil {- return fmt.Errorf("error creating controller: %w", err)- }- defer c.Close()-- // Create server- srv := server.New(c)-- // Setup signal handling for graceful shutdown- sigChan := make(chan os.Signal, 1)- signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)-- go func() {- <-sigChan- slog.InfoContext(ctx, "Received interrupt, shutting down...")- srv.GracefulStop()- }()- slog.InfoContext(ctx, "Starting AX server", slog.String("address", cfg.Server.Address))- if err := srv.Serve(cfg.Server.Address); err != nil {- return fmt.Errorf("error serving: %w", err)- }-- return nil-}diff --git a/cmd/ax/serve_gcp.go b/cmd/ax/serve_gcp.godeleted file mode 100644index 63e559b..0000000--- a/cmd/ax/serve_gcp.go+++ /dev/null@@ -1,32 +0,0 @@-// 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 main--import (- "github.com/google/ax/internal/telemetry"- "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"-)--const defaultEndpoint = "telemetry.googleapis.com"--// gcpTelemetryOpts returns the OTLP options for Google Cloud Trace if the endpoint-// matches the Google Cloud Trace endpoint. It returns the options and a boolean-// indicating if the endpoint was matched.-func gcpTelemetryOpts(endpoint string) ([]otlptracegrpc.Option, bool) {- if endpoint == defaultEndpoint || endpoint == defaultEndpoint+":443" {- return []otlptracegrpc.Option{telemetry.WithGCPCredentials()}, true- }- return nil, false-}diff --git a/demo.sh b/demo.shnew file mode 100755index 0000000..3fad06b--- /dev/null+++ b/demo.sh@@ -0,0 +1,177 @@+#!/usr/bin/env bash+# 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.++# AX demo: the full lifecycle of one task in about two minutes.+#+# 1. Declare a Workspace (a Git repo) and a Task in YAML and apply them.+# 2. Watch the task come up and the workspace get cloned.+# 3. Look inside the task with `ax ssh`.+# 4. Suspend the task, checkpointing its workspace.+#+# Environment:+# AX_BIN path to the ax CLI (default: ./bin/ax)+# ATESPACE atespace to run the demo in (default: default)+# NO_COLOR set to disable colored output++set -euo pipefail++AX_BIN="${AX_BIN:-./bin/ax}"++# ax runs the CLI at AX_BIN so the commands below read the way you would type them.+ax() { "${AX_BIN}" "$@"; }+ATESPACE="${ATESPACE:-default}"+TASK_NAME="demo-task"+WORKSPACE_NAME="demo-workspace"+REPO_URL="https://github.com/chalk/chalk.git"++# ---------------------------------------------------------------------------+# Presentation helpers+# ---------------------------------------------------------------------------++if [[ -t 1 && -z "${NO_COLOR:-}" ]]; then+ BOLD=$'\e[1m'; DIM=$'\e[2m'; CYAN=$'\e[36m'; GREEN=$'\e[32m'; YELLOW=$'\e[33m'; RESET=$'\e[0m'+else+ BOLD=""; DIM=""; CYAN=""; GREEN=""; YELLOW=""; RESET=""+fi++STEP=0+step() {+ STEP=$((STEP + 1))+ printf '\n%s%s━━ %d. %s%s\n\n' "${BOLD}" "${CYAN}" "${STEP}" "$*" "${RESET}"+}++# run prints the command the way you would type it, then runs it.+run() {+ printf '%s$ %s%s\n' "${DIM}" "$*" "${RESET}"+ "$@"+}++# in_sandbox runs a shell snippet inside the task over `ax ssh`.+in_sandbox() {+ printf "%s\$ ax ssh %s -- sh -c '%s'%s\n" "${DIM}" "${TASK_NAME}" "$1" "${RESET}"+ ax ssh "${TASK_NAME}" -a "${ATESPACE}" -- sh -c "$1"+}++ok() { printf '%s✔ %s%s\n' "${GREEN}" "$*" "${RESET}"; }+note() { printf '%s%s%s\n' "${YELLOW}" "$*" "${RESET}"; }+task_field() {+ ax describe task "${TASK_NAME}" -a "${ATESPACE}" 2>/dev/null | awk -v key="$1" '$1 == key {print $2}'+}++# wait_for PHASE [READY] polls the task until it reaches PHASE (and Ready=READY+# when given), printing a dot per poll and the elapsed time when it gets there.+wait_for() {+ local want_phase="$1" want_ready="${2:-}" timeout="${3:-180}"+ local start phase ready elapsed+ start=$(date +%s)+ printf '%swaiting for Phase=%s' "${DIM}" "${want_phase}"+ [[ -n "${want_ready}" ]] && printf ' Ready=%s' "${want_ready}"+ printf '%s ' "${RESET}"+ while :; do+ phase=$(task_field "Phase:")+ ready=$(task_field "Ready")+ if [[ "${phase}" == "${want_phase}" && ( -z "${want_ready}" || "${ready}" == "${want_ready}" ) ]]; then+ elapsed=$(( $(date +%s) - start ))+ printf ' %s%ds%s\n' "${GREEN}" "${elapsed}" "${RESET}"+ return 0+ fi+ if (( $(date +%s) - start > timeout )); then+ printf '\n'+ note "Gave up after ${timeout}s. Last seen Phase=${phase:-?} Ready=${ready:-?}"+ ax describe task "${TASK_NAME}" -a "${ATESPACE}" || true+ return 1+ fi+ printf '.'+ sleep 2+ done+}++# ---------------------------------------------------------------------------+# Demo+# ---------------------------------------------------------------------------++printf '\n%s🚀 AX demo%s %sworkspace=%s task=%s atespace=%s%s\n' \+ "${BOLD}" "${RESET}" "${DIM}" "${WORKSPACE_NAME}" "${TASK_NAME}" "${ATESPACE}" "${RESET}"++step "Clean up any previous demo run"+CLEANED=0+ax delete task "${TASK_NAME}" -a "${ATESPACE}" >/dev/null 2>&1 && { ok "removed old task"; CLEANED=1; } || true+ax delete workspace "${WORKSPACE_NAME}" -a "${ATESPACE}" >/dev/null 2>&1 && { ok "removed old workspace"; CLEANED=1; } || true+(( CLEANED )) || echo "nothing to clean up"++step "Declare a Workspace and a Task"+DEMO_YAML=$(mktemp /tmp/ax-demo-XXXXXX)+trap 'rm -f "${DEMO_YAML}"' EXIT+cat <<YAML > "${DEMO_YAML}"+apiVersion: ax.io/v1alpha1+kind: Workspace+metadata:+ name: ${WORKSPACE_NAME}+ atespace: ${ATESPACE}+spec:+ git:+ - name: chalk+ repo: "${REPO_URL}"+ branch: "main"+ depth: 1+---+apiVersion: ax.io/v1alpha1+kind: Task+metadata:+ name: ${TASK_NAME}+ atespace: ${ATESPACE}+spec:+ debug: true # serve guest services so we can ax ssh in+ image: "gcr.io/ax-substrate/ate-images/ax-task-runner@sha256:3a0dea6ad8b55278685db58aca6e37dc4ba04056831d45bef3aaeafdca43cac6"+ workspaces:+ - name: ${WORKSPACE_NAME}+ path: "/workspace"+ env:+ - name: DEMO_ENV+ value: "active"+YAML+printf '%s' "${DIM}"; sed 's/^/ /' "${DEMO_YAML}"; printf '%s\n\n' "${RESET}"+run ax apply -f "${DEMO_YAML}"++step "Watch the task come up"+note "The controller creates an actor on Agent Substrate; the runner clones ${REPO_URL##*/} into /workspace."+wait_for "Running" "True"+ok "${TASK_NAME} is Running and Ready"+echo+run ax get tasks -a "${ATESPACE}"+echo+run ax describe task "${TASK_NAME}" -a "${ATESPACE}"++step "Look inside the task with ax ssh"+in_sandbox 'ls -la /workspace'+echo+in_sandbox 'ls -la /workspace/chalk'+echo+in_sandbox 'echo "DEMO_ENV=$DEMO_ENV"; echo "AX_METADATA_URL=$AX_METADATA_URL"'+echo+note "The runner serves the task's own spec back to it over HTTP:"+in_sandbox 'curl -s "$AX_METADATA_URL/metadata/v1alpha1/ax/task" | head -20'++step "Suspend the task"+run ax suspend task "${TASK_NAME}" -a "${ATESPACE}"+wait_for "Suspended"+ok "${TASK_NAME} is Suspended. The workspace has been checkpointed and the sandbox is gone."+echo+run ax get tasks -a "${ATESPACE}"++printf '\n%s🎉 Demo complete.%s %s is left Suspended. Pick it back up or clean up with:\n\n' "${BOLD}" "${RESET}" "${TASK_NAME}"+printf ' ax resume task %s -a %s\n' "${TASK_NAME}" "${ATESPACE}"+printf ' ax ssh %s -a %s\n' "${TASK_NAME}" "${ATESPACE}"+printf ' ax delete task %s -a %s\n\n' "${TASK_NAME}" "${ATESPACE}"diff --git a/deploy/ax-controller.yaml b/deploy/ax-controller.yamlnew file mode 100644index 0000000..20492cc--- /dev/null+++ b/deploy/ax-controller.yaml@@ -0,0 +1,117 @@+# 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.++apiVersion: v1+kind: Namespace+metadata:+ name: ax-system+---+apiVersion: v1+kind: ServiceAccount+metadata:+ name: ax-controller+ namespace: ax-system+---+apiVersion: rbac.authorization.k8s.io/v1+kind: ClusterRole+metadata:+ name: ax-controller+rules:+ - apiGroups: [""]+ resources: ["secrets"]+ verbs: ["get", "list", "watch"]+---+apiVersion: rbac.authorization.k8s.io/v1+kind: ClusterRoleBinding+metadata:+ name: ax-controller+subjects:+ - kind: ServiceAccount+ name: ax-controller+ namespace: ax-system+roleRef:+ apiGroup: rbac.authorization.k8s.io+ kind: ClusterRole+ name: ax-controller+---+apiVersion: apps/v1+kind: Deployment+metadata:+ name: ax-controller+ namespace: ax-system+ labels:+ app.kubernetes.io/name: ax-controller+ app.kubernetes.io/part-of: ax+spec:+ replicas: 1+ selector:+ matchLabels:+ app.kubernetes.io/name: ax-controller+ template:+ metadata:+ labels:+ app.kubernetes.io/name: ax-controller+ spec:+ serviceAccountName: ax-controller+ containers:+ - name: controller+ image: ko://github.com/google/ax/cmd/ax-controller+ imagePullPolicy: IfNotPresent+ args:+ - "--redis-addr=ax-redis.ax-system.svc.cluster.local:6379"+ - "--substrate-endpoint=api.ate-system.svc.cluster.local:443"+ - "--substrate-authority=api.ate-system.svc"+ - "--substrate-token-file=/var/run/secrets/ateapi/token"+ - "--substrate-ca-file=/run/servicedns-ca/trust-bundle.pem"+ - "--template=default-template"+ - "--template-atespace=ax-system"+ env:+ - name: ATENET_ROUTER_ADDR+ value: "atenet-router.ate-system.svc.cluster.local:80"+ resources:+ requests:+ cpu: "100m"+ memory: "128Mi"+ limits:+ cpu: "500m"+ memory: "512Mi"+ securityContext:+ readOnlyRootFilesystem: true+ allowPrivilegeEscalation: false+ volumeMounts:+ - mountPath: /var/run/secrets/ateapi+ name: ate-token+ readOnly: true+ - mountPath: /run/servicedns-ca+ name: servicedns-ca+ readOnly: true+ volumes:+ - name: ate-token+ projected:+ defaultMode: 420+ sources:+ - serviceAccountToken:+ audience: api.ate-system.svc+ expirationSeconds: 7200+ path: token+ - name: servicedns-ca+ projected:+ defaultMode: 420+ sources:+ - clusterTrustBundle:+ labelSelector:+ matchLabels:+ podcert.ate.dev/canarying: live+ path: trust-bundle.pem+ signerName: servicedns.podcert.ate.dev/identitydiff --git a/deploy/ax-server.yaml b/deploy/ax-server.yamlnew file mode 100644index 0000000..658a9dd--- /dev/null+++ b/deploy/ax-server.yaml@@ -0,0 +1,77 @@+# 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.++apiVersion: apps/v1+kind: Deployment+metadata:+ name: ax-server+ namespace: ax-system+ labels:+ app.kubernetes.io/name: ax-server+ app.kubernetes.io/part-of: ax+spec:+ replicas: 1+ selector:+ matchLabels:+ app.kubernetes.io/name: ax-server+ template:+ metadata:+ labels:+ app.kubernetes.io/name: ax-server+ spec:+ containers:+ - name: ax-server+ image: ko://github.com/google/ax/cmd/ax-server+ imagePullPolicy: IfNotPresent+ args:+ - "--addr=:8080"+ - "--redis-addr=ax-redis.ax-system.svc.cluster.local:6379"+ ports:+ - containerPort: 8080+ name: http+ resources:+ requests:+ cpu: 100m+ memory: 128Mi+ limits:+ cpu: 1000m+ memory: 1Gi+ readinessProbe:+ httpGet:+ path: /healthz+ port: 8080+ initialDelaySeconds: 2+ periodSeconds: 5+ livenessProbe:+ httpGet:+ path: /healthz+ port: 8080+ initialDelaySeconds: 5+ periodSeconds: 10+---+apiVersion: v1+kind: Service+metadata:+ name: ax-server+ namespace: ax-system+ labels:+ app.kubernetes.io/name: ax-server+ app.kubernetes.io/part-of: ax+spec:+ ports:+ - port: 8080+ targetPort: 8080+ name: http+ selector:+ app.kubernetes.io/name: ax-serverdiff --git a/deploy/redis.yaml b/deploy/redis.yamlnew file mode 100644index 0000000..6a199b9--- /dev/null+++ b/deploy/redis.yaml@@ -0,0 +1,66 @@+# 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.++apiVersion: v1+kind: Namespace+metadata:+ name: ax-system+---+apiVersion: apps/v1+kind: Deployment+metadata:+ name: ax-redis+ namespace: ax-system+ labels:+ app.kubernetes.io/name: ax-redis+ app.kubernetes.io/part-of: ax+spec:+ replicas: 1+ selector:+ matchLabels:+ app.kubernetes.io/name: ax-redis+ template:+ metadata:+ labels:+ app.kubernetes.io/name: ax-redis+ spec:+ containers:+ - name: redis+ image: redis:7-alpine+ ports:+ - containerPort: 6379+ name: redis+ resources:+ requests:+ cpu: 100m+ memory: 128Mi+ limits:+ cpu: 1000m+ memory: 1Gi+---+apiVersion: v1+kind: Service+metadata:+ name: ax-redis+ namespace: ax-system+ labels:+ app.kubernetes.io/name: ax-redis+ app.kubernetes.io/part-of: ax+spec:+ ports:+ - port: 6379+ targetPort: 6379+ name: redis+ selector:+ app.kubernetes.io/name: ax-redisdiff --git a/docs/concepts.md b/docs/concepts.mdnew file mode 100644index 0000000..1522309--- /dev/null+++ b/docs/concepts.md@@ -0,0 +1,43 @@+# Core concepts++Every AX resource lives in an **atespace**. The default atespace is `default`.++## Task++The smallest unit of isolated execution. A `Task` declares the container image and command, compute requests and limits, environment variables, a reference to a `Gateway`, and references to one or more `Workspace`s under `spec.workspaces`. Each workspace is mounted at its own path, and the first serves as the command's working directory.++The unit is deliberately small. An agent is not one process that runs to completion; over its lifetime it plans, delegates, retries, and fans work out. AX does not try to model that shape. It gives you one primitive that is cheap to create, isolate, suspend, and throw away, and lets the agent compose as many of them as its work demands. A single task may be the whole job, or it may be the root of a large tree of tasks spawned as the agent breaks the problem down. Either way each node gets the same sandbox, the same lifecycle, and the same tooling.++### Lifecycle++`status.phase` is a one-word summary of where the task is: `Running`, `Suspended`, `Failed`, `Terminating`, and so on. Conditions carry the detail. Watch them with `ax watch` or poll them with `ax describe`.++| Condition | True when |+|---|---|+| `WorkspaceReady` | Every workspace has finished setting up. Stays True afterwards. |+| `GatewayReady` | The gateway's network policies were applied to the sandbox. |+| `Ready` | The task is running and `WorkspaceReady` is True. This is the one to wait on. |++Two transitions are worth knowing. Suspending a task sets `Ready` to False with reason `TaskSuspended`; resuming sets it back. Deleting a task moves it to `Terminating` while the controller tears down the sandbox, then removes the record entirely. `ax delete` blocks until that has happened.++## Workspace++Getting an agent to the point where it can start working is tedious. Before the first useful action it needs its data sources in place, such as repositories cloned at the right revision or buckets mounted, the tools it is allowed to call, and the skills it should bring along. Every task that needs the same environment repeats that setup, and every agent framework reinvents it. A `Workspace` exists to make that work declarative and done once.++A `Workspace` populates the filesystem and tool landscape. Declare it once, bind it from as many tasks as you like, and the runner materializes it inside each sandbox before the command starts:++- **Git repositories** cloned into subdirectories of the workspace path.+- **MCP servers and registries** (Model Context Protocol) that the agent can call.+- **Skill registries** and the path where skills are materialized.++A binding can also carry a `goal`, a plain-language description of the environment the task needs. On first boot the runner hands that goal to an agent that finishes the setup, for example installing a toolchain or dependencies, so the task's own command starts in a ready environment.++## Gateway++Network boundary for a task. Declares listeners the task exposes and an **egress allowlist** of hosts and ports the sandbox may reach. Use it to restrict an agent to, say, your LLM provider and your Git host.++## Model++A `Model` is not a model. It is a named model configuration: which provider to call, which model identifier to use, provider-specific generation parameters such as temperature, and a reference to the Kubernetes secret holding the API key.++Declaring it as a resource is what makes it manageable across the cluster. The configuration lives in one place instead of in every agent's environment, so rotating a key, pinning a new model version, or tightening a parameter is one `ax apply` rather than a hunt through task definitions. AX's own components read it too, for example when planning a workspace from a goal.diff --git a/docs/development.md b/docs/development.mdnew file mode 100644index 0000000..c765b85--- /dev/null+++ b/docs/development.md@@ -0,0 +1,29 @@+# Development++## Prerequisites++- Go 1.27++- [`ko`](https://ko.build/) for building and deploying control plane images+- Docker or Podman for the task runner image+- A Kubernetes cluster and kubeconfig++## Build++```bash+make build # bin/ax, bin/ax-controller, bin/ax-server+make install # install the ax CLI into $(go env GOPATH)/bin+make build-task-runner # cross-compile the runner for linux/amd64 and build its image+make push-task-runner # ...and push it (set TASK_RUNNER_REPO)+```++## Test++Runs everything, including the mock Substrate gRPC server, in-memory store validation, and API server tests:++```bash+make test # or: go test -v ./...+```++## Contributing++See [CONTRIBUTING.md](../CONTRIBUTING.md) for contribution guidelines, CLA requirements, and PR workflows.diff --git a/docs/logo.md b/docs/logo.mdnew file mode 100644index 0000000..545c99c--- /dev/null+++ b/docs/logo.md@@ -0,0 +1,14 @@+# The AX mascot++<img src="../assets/axolotl.svg" width="160" alt="AX's pink axolotl mascot, with a round face, blush cheeks, and three gills on each side.">++AX's mascot is an **[axolotl](https://animals.sandiegozoo.org/animals/axolotl)**, an aquatic salamander recognizable by the feathery external gills around its head. The three rounded branches on each side of the mascot are stylized gills.++The name is a natural fit: **ax**olotl starts with **AX**. The round pink face, small smile, and blush cheeks represents the friendly nature of the project.++## Logo files++- [Color logo](../assets/axolotl.svg): the primary mascot, used in the README and documentation.+- [Monochrome logo](../assets/axolotl-mono.svg): a single-color version for places where color is limited. Its facial features are transparent cutouts.++Both files are SVGs with transparent backgrounds and a 3:2 aspect ratio. Preserve their proportions when resizing and leave room around the gills.diff --git a/docs/manifests.md b/docs/manifests.mdnew file mode 100644index 0000000..a0fa502--- /dev/null+++ b/docs/manifests.md@@ -0,0 +1,151 @@+# Writing manifests++All four kinds can live in one multi-document YAML file. See [`examples/task.yaml`](../examples/task.yaml) for a complete, working set.++## Task++```yaml+apiVersion: ax.io/v1alpha1+kind: Task+metadata:+ name: task123+ atespace: default+spec:+ image: "ghcr.io/my-org/my-agent-image"+ command: ["python", "agent.py"]+ env:+ - name: ENVIRONMENT+ value: "production"++ resources:+ requests:+ cpu: "500m"+ memory: "1Gi"+ limits:+ cpu: "2"+ memory: "4Gi"++ workspaces:+ - name: default-workspace+ path: "/workspace"+ goal: "Install dependencies and run the test suite" # Antigravity prepares the workspace to this goal on first run++ gateway:+ name: default-gateway++ debug: true # serve guest services inside the sandbox so `ax ssh` works; off by default+```++### Binding several workspaces++`spec.workspaces` takes as many entries as you like, so a task can compose reusable `Workspace` resources, for example the code to work on plus a shared set of tools:++```yaml+spec:+ workspaces:+ - name: my-service # mounted at /workspace/my-service, the command's working directory+ goal: "Install dependencies and run the test suite"+ - name: team-tools+ path: "/workspace/tools" # explicit mount path+```++Each entry is set up independently at its own path, in order. Every entry needs a `name`; without a `path` it lands at `/workspace/<name>`, and paths must be unique. The first entry is the working directory of `spec.command`, and the task reports `WorkspaceReady` only once all of them are prepared. See [`examples/multi-workspace.yaml`](../examples/multi-workspace.yaml) for a complete set.++## Workspace++```yaml+apiVersion: ax.io/v1alpha1+kind: Workspace+metadata:+ name: default-workspace+ atespace: default+spec:+ git:+ - name: origin+ repo: "https://github.com/chalk/chalk.git"+ branch: "main"+ mcp:+ registries:+ - provider: google+ query: "mcp.tags:build"+ servers:+ - name: git-tools+ endpoint: "http://git-mcp.default.svc.cluster.local:8080"+ skills:+ registries:+ - provider: google+ query: "skills.tags:nodejs"+ path: "/.agents/skills"+```++## Gateway++```yaml+apiVersion: ax.io/v1alpha1+kind: Gateway+metadata:+ name: default-gateway+ atespace: default+spec:+ listeners:+ - name: grpc+ port: 8494+ protocol: gRPC+ - name: http+ port: 8080+ protocol: HTTP+ egress:+ allowlist:+ hosts:+ - host: "*" # allow everything on 443; tighten this in production+ port: 443+```++## Model++For Google models, store the API key and set `provider: google`.++```bash+kubectl create secret generic gemini-api-secret --from-literal=GEMINI_API_KEY="AIzaSy..."+```++Then reference it from the `Model`:++```yaml+apiVersion: ax.io/v1alpha1+kind: Model+metadata:+ name: default-model+ atespace: default+spec:+ provider: google+ model: gemini-3.8-flash+ secretKey:+ name: gemini-api-secret+ key: GEMINI_API_KEY+ parameters:+ temperature: 0.9+```++For Anthropic models, store the key the same way and set `provider: anthropic`.++```bash+kubectl create secret generic anthropic-api-secret --from-literal=ANTHROPIC_API_KEY="sk-ant-..."+```++```yaml+apiVersion: ax.io/v1alpha1+kind: Model+metadata:+ name: claude-model+ atespace: default+spec:+ provider: anthropic+ model: claude-opus-5+ secretKey:+ name: anthropic-api-secret+ key: ANTHROPIC_API_KEY+ parameters:+ maxTokens: 16000+ temperature: 0.9+```diff --git a/docs/networking.md b/docs/networking.mdnew file mode 100644index 0000000..2e57e6e--- /dev/null+++ b/docs/networking.md@@ -0,0 +1,32 @@+# Networking++Tasks do not get a Kubernetes Service or Ingress of their own. Every request to a task goes through Agent Substrate's **atenet router**, the `atenet-router` Service in the `ate-system` namespace. The router reads a single header, `ate-target-actor`, resolves the actor to the worker it is running on, resumes it first if it was suspended, and proxies the request there. `Host` and `:authority` are left alone for your application; the header alone selects the target.++The header value is `<atespace>/<task>`. The controller always names a task's actor after the task, so `default/task123` reaches the task `task123` in the `default` atespace.++## From inside the cluster++Use the Service DNS name and add the header. This is exactly how the controller polls a task's readiness.++```bash+curl -H "ate-target-actor: default/task123" \+ http://atenet-router.ate-system.svc.cluster.local/metadata/v1alpha1/ax/task+```++## From your machine++Port-forward the router, then talk to it the same way.++```bash+kubectl -n ate-system port-forward svc/atenet-router 8001:80+curl -H "ate-target-actor: default/task123" http://localhost:8001/readyz+```++## gRPC request routing++Send the header as outgoing metadata under the lowercase key. This is what `ax ssh` does to reach the guest services.++```go+ctx = metadata.AppendToOutgoingContext(ctx, "ate-target-actor", "default/task123")+resp, err := client.SomeMethod(ctx, req)+```diff --git a/docs/runner.md b/docs/runner.mdnew file mode 100644index 0000000..92c6e99--- /dev/null+++ b/docs/runner.md@@ -0,0 +1,176 @@+# Runners++A runner is the program that AX starts as PID 1 inside every task container. It is the bridge between the control plane and whatever your agent actually is: the controller hands it the `Task` and `Workspace` specs, and the runner turns them into a prepared workspace, a running command, and a small HTTP surface that the rest of AX uses to observe the sandbox.++AX ships a default runner, `ax-task-runner`, baked into the default task image. You do not have to use it. Any binary that honors the contract below can be packaged into a container image and named in `spec.image`, and the control plane will treat it exactly like the default.++This page describes what a runner must do. For what the default runner exposes to your command once it is up, see [Sandbox](sandbox.md).++## How a runner is launched++The controller does not run `spec.command` as the container entrypoint. It always starts the container with a fixed command and lets the runner take it from there:++| What the controller sets | Value |+|---|---|+| Container image | `spec.image`, or the default `ax-task-runner` image when unset |+| Container command | `/usr/local/bin/ax-task-runner`, always |+| `AX_TASK_YAML` | The full `Task` resource as YAML, including status |+| `AX_WORKSPACES_YAML` | Every bound `Workspace` resource as a multi-document YAML stream, in the task's binding order |+| `spec.env` entries | Each one set directly in the container environment |+| `GEMINI_API_KEY` | Set when the atespace has a Gemini credential configured |+| Volume | A durable directory mounted at `/workspace` |+| Readiness probe | `GET /readyz` on port 80 |++Two consequences follow from that table. Your image must contain an executable at `/usr/local/bin/ax-task-runner`, even if it is a symlink or a shell wrapper around something else. And `spec.command` reaches the runner only through `AX_TASK_YAML`; the runner is responsible for parsing it and starting it.++The `/workspace` volume is what survives suspend and resume. Agent Substrate snapshots it when a task is suspended and restores it into a fresh container when the task is resumed, so the runner will see the same files but a new process tree.++## What a runner must do++**Serve HTTP on port 80.** Both Agent Substrate and the AX controller probe the container on this port. The paths that matter:++| Path | Behavior |+|---|---|+| `/healthz` | Return `200` as soon as the runner is alive. |+| `/readyz` | Return `503` until the workspace is prepared, then `200`. The controller polls this to set the task's `WorkspaceReady` condition, and `ax watch` shows the transition. |+| `/metadata/v1alpha1/ax/task` | Return the `Task` as `application/yaml`. Optional, but your command and `ax` tooling may expect it. |+| `/metadata/v1alpha1/ax/workspaces` | Return every bound `Workspace` as a multi-document YAML stream. Optional, as above. |++**Prepare each workspace once.** A task binds workspaces through `spec.workspaces`. For each binding, at its path, clone the Git repos from `spec.git`, create the skills path, write any MCP configuration, and run any environment bootstrap the binding asks for through its `goal`. A binding without a path lands at `/workspace/<name>`. Record that setup happened somewhere on the durable volume or in a known location, per workspace, then skip the work on later boots. Resume restarts the container, and re-cloning into a restored workspace would destroy the agent's state. The default runner writes a marker file under `/ax` for each workspace path.++**Run the command and supervise it.** Start `spec.command` as a child process with the first workspace as its working directory. Give it `AX_METADATA_URL` pointing at your own HTTP server plus every `spec.env` entry. Put it in its own process group so you can signal everything it spawns.++**Stay up after the command exits.** The runner is PID 1, and the container lives as long as it does. If the runner exits when the command does, the metadata server goes with it and `ax ssh` stops working. Log the exit status and keep serving until you are told to stop. The control plane does not currently read the command's exit status back from the container.++**Shut down cleanly on `SIGTERM`.** Stop and suspend both deliver `SIGTERM` to PID 1. Forward it to the command's process group, wait a bounded grace period, then `SIGKILL` whatever is left. Flush anything the agent needs to survive a resume before you exit.++**Serve guest services only when asked.** When `spec.debug` is true, the runner should also serve the [Agent Substrate guest services](https://github.com/agent-substrate/env) over gRPC on port 80, multiplexed with the HTTP endpoints using `h2c`. This is what `ax ssh` connects to. When `spec.debug` is false, leave them off. They allow arbitrary process execution and file access inside the sandbox, and `ax ssh` refuses to connect to a task that has not opted in.++## The default runner++`ax-task-runner` lives in `cmd/ax-task-runner` and is a thin wrapper over the `runner` Go package. It implements everything above and is documented from the inside in [Sandbox](sandbox.md). Its image, built from `Dockerfile.task-runner`, is Python 3.12 with `git`, `curl`, `openssh-client`, and the Antigravity agent installed, because the goal-based workspace bootstrap hands the goal to Antigravity.++```bash+make build-task-runner # cross-compile for linux/amd64 and build the image+make push-task-runner # push it; set TASK_RUNNER_REPO to choose the registry+```++## Replacing the default runner++There are three levels of customization. Pick the shallowest one that solves your problem.++### 1. Extend the default image++If the runner behavior is fine and you only need different tools in the sandbox, build on top of the default image and keep its entrypoint:++```dockerfile+# Pin the same digest the examples use so the runner behavior is reproducible.+FROM gcr.io/ax-substrate/ate-images/ax-task-runner@sha256:69b764607ec7f1e433d83d2eca17dccfa04f663b43f071fd376e2dd716a57f8c++RUN apt-get update && apt-get install -y --no-install-recommends nodejs npm \+ && rm -rf /var/lib/apt/lists/*+RUN npm install -g my-agent+```++The runner binary stays at `/usr/local/bin/ax-task-runner`, so nothing else changes.++### 2. Embed the runner package in your own binary++If you want the standard lifecycle but need to run code around it, import `github.com/google/ax/runner` and call `runner.Run` yourself. This gives you a hook for the command's exit and a place to do your own setup before or after the metadata server starts:++```go+package main++import (+ "context"+ "log/slog"+ "os"+ "os/signal"+ "strings"+ "syscall"++ "github.com/google/ax/pkg/apis/v1alpha1"+ "github.com/google/ax/runner"+ "gopkg.in/yaml.v3"+)++func main() {+ var task v1alpha1.Task+ _ = yaml.Unmarshal([]byte(os.Getenv("AX_TASK_YAML")), &task)++ // AX_WORKSPACES_YAML is a multi-document stream, one Workspace per document.+ var workspaces []*v1alpha1.Workspace+ dec := yaml.NewDecoder(strings.NewReader(os.Getenv("AX_WORKSPACES_YAML")))+ for {+ var ws v1alpha1.Workspace+ if err := dec.Decode(&ws); err != nil {+ break+ }+ workspaces = append(workspaces, &ws)+ }++ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer stop()++ err := runner.Run(ctx, runner.Config{+ Task: &task,+ Workspaces: workspaces,+ OnCommandExit: func(exit runner.CommandExit) {+ slog.Info("agent finished", "exitCode", exit.ExitCode)+ // Upload artifacts, notify a webhook, and so on.+ },+ })+ if err != nil {+ slog.Error("runner failed", "error", err)+ os.Exit(1)+ }+}+```++Cross-compile it for `linux/amd64` with `CGO_ENABLED=0` and copy it into your image at `/usr/local/bin/ax-task-runner`.++### 3. Write a runner from scratch++If the default lifecycle does not fit, for example because your agent framework already supervises processes or you want a different workspace layout, write your own in any language. Read `AX_TASK_YAML` and `AX_WORKSPACES_YAML`, satisfy the contract in the previous section, and install the result at `/usr/local/bin/ax-task-runner`. The `ax.io/v1alpha1` schema is defined in `pkg/apis/v1alpha1/ax.proto`, and [Manifests](manifests.md) walks through every field.++### Ship it++Whichever route you take, push the image to a registry the cluster can pull from and reference it in the task:++```yaml+apiVersion: ax.io/v1alpha1+kind: Task+metadata:+ name: custom-runner+spec:+ image: "ghcr.io/my-org/my-runner@sha256:..."+ command: ["my-agent", "--goal", "fix the flaky test"]+ debug: true+```++The controller provisions a dedicated Agent Substrate actor template for each distinct image and environment, so different tasks can run different runners side by side in the same atespace.++## Testing a runner locally++The default runner accepts its specs from files as well as the environment, which makes it easy to run outside a cluster. Your own runner should offer something similar:++```bash+ax-task-runner --task-file task.yaml --workspace-file code.yaml --workspace-file tools.yaml --port 8080++# In another shell:+curl -i http://127.0.0.1:8080/readyz+curl -s http://127.0.0.1:8080/metadata/v1alpha1/ax/task+```++Once the image is built, the fastest end-to-end check is a task with `debug: true` and `ax ssh` into it to confirm the workspace, the command, and the environment look the way you expect.++## Checklist++- Executable present at `/usr/local/bin/ax-task-runner`+- Reads `AX_TASK_YAML` and `AX_WORKSPACES_YAML`+- Serves `/healthz` and `/readyz` on port 80, with `/readyz` returning `503` until every workspace is ready+- Prepares each workspace exactly once across restarts and resumes, at its own path+- Starts `spec.command` in the first workspace with `AX_METADATA_URL` and `spec.env`+- Keeps running after the command exits+- Forwards `SIGTERM` to the command's process group and exits after a grace period+- Serves guest gRPC services on port 80 only when `spec.debug` is truediff --git a/docs/sandbox.md b/docs/sandbox.mdnew file mode 100644index 0000000..b6fff77--- /dev/null+++ b/docs/sandbox.md@@ -0,0 +1,39 @@+# Inside the sandbox++Every task container starts with `ax-task-runner` as PID 1. On boot it:++1. Loads the `Task` and every bound `Workspace` spec.+2. Starts a metadata and guest-management daemon on port 80.+3. On the first run, prepares each workspace at its own path, in binding order: clones Git repos, sets up the skills path, and, if the binding has a goal, hands that goal to an Antigravity agent to finish environment setup. The agent needs `GEMINI_API_KEY` in the container and gets 10 minutes by default; set `AX_BOOTSTRAP_TIMEOUT` to a Go duration to change that. The task reports not-ready until every workspace, including any agent run, has finished.+4. Starts `spec.command` as a child process, with the first workspace as its working directory and `AX_METADATA_URL` plus `spec.env` in its environment, and supervises it.++The runner stays up as PID 1 whether or not the command is still running, so the metadata server keeps answering and `ax ssh` still works after the command has exited. Its exit code is logged. When the sandbox is stopped or suspended, the runner sends the command's process group `SIGTERM`, waits ten seconds, and then kills whatever is left.++## Metadata server++The daemon speaks HTTP/1.1 and `h2c` on the same port. Your agent can introspect its own configuration without any SDK:++| Endpoint | Method | Returns | Description |+|---|---|---|---|+| `/healthz` | `GET` | `text/plain` | Liveness. Always `200 OK`. |+| `/readyz` | `GET` | `text/plain` | Readiness. `503` while the workspace is initializing, `200` once clones, MCP config, and skills are in place. |+| `/metadata/v1alpha1/ax/task` | `GET` | `application/yaml` | Full spec and status of the current `Task`. |+| `/metadata/v1alpha1/ax/workspaces` | `GET` | `application/yaml` | Every bound `Workspace`, as a multi-document stream in binding order. |++```bash+# From inside a task:+curl -s "$AX_METADATA_URL/metadata/v1alpha1/ax/task"+```++## Guest services++When a task sets `spec.debug: true`, the same port also serves the [Agent Substrate guest services](https://github.com/agent-substrate/env) over gRPC. They are off by default because they allow arbitrary process execution and file access inside the sandbox, and `ax ssh` refuses to connect to a task that has not enabled them.++- **Process service**: start, inspect, stream output from, and kill processes. This is what powers `ax ssh`.+- **File system service**: streaming file reads and writes inside the workspace.++## Environment provided to your command++| Variable | Value |+|---|---|+| `AX_METADATA_URL` | Base URL of the metadata server, e.g. `http://127.0.0.1:80` |diff --git a/examples/simple.yaml b/examples/simple.yamlnew file mode 100644index 0000000..2ce2a5d--- /dev/null+++ b/examples/simple.yaml@@ -0,0 +1,33 @@+# 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.++# The smallest useful Task: no Workspace, Gateway, or Model.+#+# The controller runs it on the default task-runner image with an empty+# /workspace directory and allows all egress on port 443.+#+# ax apply -f examples/simple.yaml+# ax describe task simple-task+# ax ssh simple-task -- ls -la /workspace+apiVersion: ax.io/v1alpha1+kind: Task+metadata:+ name: simple-task+ atespace: default+spec:+ image: "gcr.io/ax-substrate/ate-images/ax-task-runner@sha256:3a0dea6ad8b55278685db58aca6e37dc4ba04056831d45bef3aaeafdca43cac6"+ env:+ - name: ENVIRONMENT+ value: "test"+ debug: true # serve guest services so `ax ssh` works; off by defaultdiff --git a/examples/skills/README.md b/examples/skills/README.mddeleted file mode 100644index 2f4e388..0000000--- a/examples/skills/README.md+++ /dev/null@@ -1,37 +0,0 @@-# Skills--AX has built-in support for [Agent Skills](https://agentskills.io).--## Configuration--To enable skills with a custom directory, you can set the `skills_dir` in your `ax.yaml` file:--```yaml-planner:- gemini:- model: "gemini-3.5-flash"- timeout: "60s"- skills_dir: "./examples/skills"-```--If you omit `skills_dir` in your `ax.yaml` file, AX will check the `SKILLS_DIR` environment variable first, and finally fall back to `~/.agents/skills`.--## Example: Using the `emoji` Skill--AX contains a sample `emoji` skill in `examples/skills/emoji`. If you run a task that matches the description of the skill, the planner will automatically activate it and execute its scripts!--Run the following command in your terminal:--```bash-ax --input "Give me an emoji for happy"-```--The planner will:-1. Discover the `emoji` skill.-2. Determine that your query matches its description.-3. Call `activate_skill` to load the instructions.-4. Execute the `emoji` skill via text generation or script execution based on its instructions.--### Custom Skills--Refer to the [Agent Skills](https://agentskills.io) documentation for more information on how to create custom skills.\ No newline at end of filediff --git a/examples/skills/emoji/SKILL.md b/examples/skills/emoji/SKILL.mddeleted file mode 100644index 4a50246..0000000--- a/examples/skills/emoji/SKILL.md+++ /dev/null@@ -1,9 +0,0 @@-----name: emoji-description: Returns a corresponding emoji for a given word (e.g. happy, magic etc).------# Instructions-When the user asks for an emoji for a specific word or concept, use this skill.-1. Call `run_skill_script` to execute `emoji.sh`, passing the word as the first argument.-2. Return the output emoji directly to the user.diff --git a/examples/skills/emoji/scripts/emoji.sh b/examples/skills/emoji/scripts/emoji.shdeleted file mode 100755index ff8f5cb..0000000--- a/examples/skills/emoji/scripts/emoji.sh+++ /dev/null@@ -1,34 +0,0 @@-#!/bin/sh--# 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.--# Return an ASCII emoticon based on the input word-# Convert input to lowercase using tr for case-insensitive matching-word=$(echo "$1" | tr '[:upper:]' '[:lower:]')--case "$word" in- "happy"|"smile"|"joy") echo ":-)" ;;- "sad"|"cry") echo ":-(" ;;- "shrug"|"dunno"|"whatever") echo "¯\_(ツ)_/¯" ;;- "flip"|"angry"|"rage") echo "(╯°□°)╯︵ ┻━┻" ;;- "table"|"putback") echo "┬─┬ノ( º _ ºノ)" ;;- "magic"|"sparkle") echo "(ノ◕ヮ◕)ノ*:・゚✧" ;;- "sunglasses"|"cool") echo "(•_•) / ( •_•)>⌐■-■ / (⌐■_■)" ;;- "sundar"|"ceo") echo "👓(⌐■_■) 👍" ;;- "dance"|"party") echo "♪~ ᕕ(ᐛ)ᕗ" ;;- "wink") echo ";-)" ;;- "surprise"|"gasp") echo "(O_O)" ;;- *) echo "¯\_(ツ)_/¯ (unknown word)" ;;-esacdiff --git a/examples/skills/lowercase/SKILL.md b/examples/skills/lowercase/SKILL.mddeleted file mode 100644index 47a2c77..0000000--- a/examples/skills/lowercase/SKILL.md+++ /dev/null@@ -1,9 +0,0 @@-----name: lowercase-description: Converts the provided input string to lowercase.------# Instructions-When the user asks to convert a text to lowercase, or if you need to lowercase a string for processing, use this skill.-1. Call `run_skill_script` to execute `lowercase.sh`, passing the text as the first argument.-2. Return the lowered text directly to the user.diff --git a/examples/skills/lowercase/scripts/lowercase.sh b/examples/skills/lowercase/scripts/lowercase.shdeleted file mode 100755index f28b33d..0000000--- a/examples/skills/lowercase/scripts/lowercase.sh+++ /dev/null@@ -1,17 +0,0 @@-#!/bin/bash--# 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.-# Converts argument to lowercase-echo "$1" | tr '[:upper:]' '[:lower:]'diff --git a/examples/task.yaml b/examples/task.yamlnew file mode 100644index 0000000..7e41c72--- /dev/null+++ b/examples/task.yaml@@ -0,0 +1,98 @@+# 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.++apiVersion: ax.io/v1alpha1+kind: Task+metadata:+ name: task123+ atespace: default+spec:+ env:+ - name: ENVIRONMENT+ value: "test"+ image: "gcr.io/ax-substrate/ate-images/ax-task-runner@sha256:3a0dea6ad8b55278685db58aca6e37dc4ba04056831d45bef3aaeafdca43cac6"++ resources:+ requests:+ cpu: "500m"+ memory: "1Gi"+ limits:+ cpu: "2"+ memory: "4Gi"++ workspaces:+ - name: default-workspace+ path: "/workspace"++ gateway:+ name: default-gateway++ debug: true # serve guest services so `ax ssh` works; off by default+---+apiVersion: ax.io/v1alpha1+kind: Workspace+metadata:+ name: default-workspace+ atespace: default+spec:+ git:+ - name: origin+ repo: "https://github.com/chalk/chalk.git"+ branch: "main"+ mcp:+ registries:+ - provider: google+ query: "mcp.tags:build"+ servers:+ - name: git-tools+ endpoint: "http://git-mcp.default.svc.cluster.local:8080"+ skills:+ registries:+ - provider: google+ query: "skills.tags:nodejs"+ path: "/.agents/skills"+---+apiVersion: ax.io/v1alpha1+kind: Gateway+metadata:+ name: default-gateway+ atespace: default+spec:+ listeners:+ - name: grpc+ port: 8494+ protocol: gRPC++ - name: http+ port: 8080+ protocol: HTTP+ egress:+ allowlist:+ hosts:+ - host: "*"+ port: 443+---+apiVersion: ax.io/v1alpha1+kind: Model+metadata:+ name: default-model+ atespace: default+spec:+ provider: google+ model: gemini-3.8-flash+ secretKey:+ name: gemini-api-secret+ key: GEMINI_API_KEY+ parameters:+ temperature: 0.9diff --git a/go.mod b/go.modindex 73c022f..3f8918d 100644--- a/go.mod+++ b/go.mod@@ -1,73 +1,24 @@module github.com/google/ax-go 1.26.3+go 1.27.1require (- charm.land/bubbles/v2 v2.0.0- charm.land/bubbletea/v2 v2.0.2- charm.land/huh/v2 v2.0.3- charm.land/lipgloss/v2 v2.0.3- cloud.google.com/go/compute/metadata v0.9.0- github.com/agent-substrate/substrate v0.0.0-20260706222328-3cb7433bd8a8- github.com/google/uuid v1.6.0- github.com/jackc/pgx/v5 v5.10.0- github.com/spf13/cobra v1.10.2- go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.69.0- go.opentelemetry.io/otel v1.44.0- go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0- go.opentelemetry.io/otel/sdk v1.44.0- go.opentelemetry.io/otel/trace v1.44.0- golang.org/x/oauth2 v0.36.0- google.golang.org/grpc v1.81.1- google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af+ github.com/agent-substrate/env v0.0.11-0.20260912052224-4468a200b170+ github.com/agent-substrate/substrate v0.0.0-20260911232748-672533541dbf+ github.com/redis/go-redis/v9 v9.22.0+ google.golang.org/grpc v1.83.2+ google.golang.org/protobuf v1.36.12gopkg.in/yaml.v3 v3.0.1- modernc.org/sqlite v1.47.0)require (- github.com/atotto/clipboard v0.1.4 // indirect- github.com/catppuccin/go v0.3.0 // indirect- github.com/cenkalti/backoff/v5 v5.0.3 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirect- github.com/charmbracelet/colorprofile v0.4.3 // indirect- github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8 // indirect- github.com/charmbracelet/x/ansi v0.11.7 // indirect- github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect- github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect- github.com/charmbracelet/x/term v0.2.2 // indirect- github.com/charmbracelet/x/termios v0.1.1 // indirect- github.com/charmbracelet/x/windows v0.2.2 // indirect- github.com/clipperhouse/displaywidth v0.11.0 // indirect- github.com/clipperhouse/uax29/v2 v2.7.0 // indirect- github.com/dustin/go-humanize v1.0.1 // indirect- github.com/go-logr/logr v1.4.3 // indirect- github.com/go-logr/stdr v1.2.2 // indirect- github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect- github.com/inconshreveable/mousetrap v1.1.0 // indirect- github.com/jackc/pgpassfile v1.0.0 // indirect- github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect- github.com/jackc/puddle/v2 v2.2.2 // indirect- github.com/lucasb-eyer/go-colorful v1.4.0 // indirect- github.com/mattn/go-isatty v0.0.20 // indirect- github.com/mattn/go-runewidth v0.0.23 // indirect- github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect- github.com/muesli/cancelreader v0.2.2 // indirect- github.com/ncruces/go-strftime v1.0.0 // indirect- github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect- github.com/rivo/uniseg v0.4.7 // indirect- github.com/spf13/pflag v1.0.10 // indirect- github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect- go.opentelemetry.io/auto/sdk v1.2.1 // indirect- go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect- go.opentelemetry.io/otel/metric v1.44.0 // indirect- go.opentelemetry.io/proto/otlp v1.10.0 // indirect- golang.org/x/net v0.55.0 // indirect- golang.org/x/sync v0.20.0 // indirect- golang.org/x/sys v0.45.0 // indirect- golang.org/x/text v0.37.0 // indirect- google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect- google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect- modernc.org/libc v1.70.0 // indirect- modernc.org/mathutil v1.7.1 // indirect- modernc.org/memory v1.11.0 // indirect+ github.com/kr/pretty v0.3.1 // indirect+ github.com/rogpeppe/go-internal v1.14.1 // indirect+ go.uber.org/atomic v1.11.0 // indirect+ golang.org/x/net v0.58.0 // indirect+ golang.org/x/sys v0.47.0 // indirect+ golang.org/x/text v0.41.0 // indirect+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260720211330-0afa2a65878a // indirect+ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect)diff --git a/go.sum b/go.sumindex a5bc044..5287948 100644--- a/go.sum+++ b/go.sum@@ -1,147 +1,47 @@-charm.land/bubbles/v2 v2.0.0 h1:tE3eK/pHjmtrDiRdoC9uGNLgpopOd8fjhEe31B/ai5s=-charm.land/bubbles/v2 v2.0.0/go.mod h1:rCHoleP2XhU8um45NTuOWBPNVHxnkXKTiZqcclL/qOI=-charm.land/bubbletea/v2 v2.0.2 h1:4CRtRnuZOdFDTWSff9r8QFt/9+z6Emubz3aDMnf/dx0=-charm.land/bubbletea/v2 v2.0.2/go.mod h1:3LRff2U4WIYXy7MTxfbAQ+AdfM3D8Xuvz2wbsOD9OHQ=-charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=-charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=-charm.land/lipgloss/v2 v2.0.3 h1:yM2zJ4Cf5Y51b7RHIwioil4ApI/aypFXXVHSwlM6RzU=-charm.land/lipgloss/v2 v2.0.3/go.mod h1:7myLU9iG/3xluAWzpY/fSxYYHCgoKTie7laxk6ATwXA=-cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=-cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=-github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=-github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=-github.com/agent-substrate/substrate v0.0.0-20260706222328-3cb7433bd8a8 h1:tUeBjLs9TJgIWfML2dlZ3UOFG3dacbwrIYkas2ctBgY=-github.com/agent-substrate/substrate v0.0.0-20260706222328-3cb7433bd8a8/go.mod h1:2cvSnnHPwZRAhkrC2LH1bQd1tQBfL3p+zU6pZiHBUkA=-github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=-github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=-github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o=-github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w=-github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY=-github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=-github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=-github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=+github.com/agent-substrate/env v0.0.11-0.20260912052224-4468a200b170 h1:8AxhEx3BL7J8c+zqnYq5S3aH0J/4z85/JYWoo1dr6xY=+github.com/agent-substrate/env v0.0.11-0.20260912052224-4468a200b170/go.mod h1:RZ4ACmDqWQx7fgX9b1EaFJskeYTZh1Y7uZinDtp7U2o=+github.com/agent-substrate/substrate v0.0.0-20260911232748-672533541dbf h1:FC9Ed75cCczI6unzgMe1Ss3J0mzX2GOiASSHBQnIl/E=+github.com/agent-substrate/substrate v0.0.0-20260911232748-672533541dbf/go.mod h1:WBkGfDCbVFbtJTEMpIIbq59yEgko1L4WHJIEVGBdems=+github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=+github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=+github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=+github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=-github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=-github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=-github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8 h1:eyFRbAmexyt43hVfeyBofiGSEmJ7krjLOYt/9CF5NKA=-github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8/go.mod h1:SQpCTRNBtzJkwku5ye4S3HEuthAlGy2n9VXZnWkEW98=-github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dAYC84jI=-github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ=-github.com/charmbracelet/x/conpty v0.1.1 h1:s1bUxjoi7EpqiXysVtC+a8RrvPPNcNvAjfi4jxsAuEs=-github.com/charmbracelet/x/conpty v0.1.1/go.mod h1:OmtR77VODEFbiTzGE9G1XiRJAga6011PIm4u5fTNZpk=-github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA=-github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0=-github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=-github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I=-github.com/charmbracelet/x/exp/ordered v0.1.0 h1:55/qLwjIh0gL0Vni+QAWk7T/qRVP6sBf+2agPBgnOFE=-github.com/charmbracelet/x/exp/ordered v0.1.0/go.mod h1:5UHwmG+is5THxMyCJHNPCn2/ecI07aKNrW+LcResjJ8=-github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4=-github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ=-github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=-github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=-github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=-github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=-github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=-github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=-github.com/charmbracelet/x/xpty v0.1.3 h1:eGSitii4suhzrISYH50ZfufV3v085BXQwIytcOdFSsw=-github.com/charmbracelet/x/xpty v0.1.3/go.mod h1:poPYpWuLDBFCKmKLDnhBp51ATa0ooD8FhypRwEFtH3Y=-github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=-github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=-github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=-github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=-github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik=-github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=-github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=-github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=-github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=-github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=-github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=-github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=-github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA=-github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ=-github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A=-github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds=-github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=-github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=-github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=-github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=+github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=+github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=-github.com/google/pprof v0.0.0-20250602020802-c6617b811d0e h1:FJta/0WsADCe1r9vQjdHbd3KuiLPu7Y9WlyLGwMUNyE=-github.com/google/pprof v0.0.0-20250602020802-c6617b811d0e/go.mod h1:5hDyRhoBCxViHszMt12TnOpEI4VVi+U8Gm9iphldiMA=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=-github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=-github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=-github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=-github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=-github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=-github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=-github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=-github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=-github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=-github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=-github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=-github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=-github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=-github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=+github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=+github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=+github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=-github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=-github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=-github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=-github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=-github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=-github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=-github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=-github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=-github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=-github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=-github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=-github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=-github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=-github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=-github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=-github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=-github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=-github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=-github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=-github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=-github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=+github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=+github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0=+github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4=+github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=-github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=-github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=-github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=-github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=-github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=-github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=-github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=-github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=-github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=-github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=-github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=-github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=-github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=+github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=+github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=+github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=+github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=-go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.69.0 h1:2yEATaop1/a1I4psnSLgWVPLWwCzkqWakgJy7xTDVy0=-go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.69.0/go.mod h1:D7J12YRapIekYyPWgGPlA/23pRmpSEZC5xJC/TTLI9U=go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=-go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=-go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=-go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0 h1:qazEJlUOQzhCpzQpFETGby7EdqjI1wsd0W+6Gg1SCTU=-go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0/go.mod h1:fOD2Yefuxixkx3ahVNf0O/PERb6r4OlbxfATVnYvzCo=go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=@@ -150,69 +50,26 @@ go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRkgo.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=-go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=-go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=-go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=-go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=-go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=-golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=-golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=-golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=-golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=-golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=-golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=-golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=-golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=-golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=-golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=-golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=-golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=-golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=-golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=-golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=-golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=+go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=+golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=+golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=+golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=+golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=-google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8=-google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY=-google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=-google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=-google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ=-google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I=-google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af h1:+5/Sw3GsDNlEmu7TfklWKPdQ0Ykja5VEmq2i817+jbI=-google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260720211330-0afa2a65878a h1:qI/YMH1ep2qQtqcp00gMQyoU7mjvbhg88GJKCvfoLj0=+google.golang.org/genproto/googleapis/rpc v0.0.0-20260720211330-0afa2a65878a/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=+google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=+google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=-gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=-modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=-modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=-modernc.org/ccgo/v4 v4.32.0 h1:hjG66bI/kqIPX1b2yT6fr/jt+QedtP2fqojG2VrFuVw=-modernc.org/ccgo/v4 v4.32.0/go.mod h1:6F08EBCx5uQc38kMGl+0Nm0oWczoo1c7cgpzEry7Uc0=-modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=-modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=-modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=-modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=-modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=-modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=-modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=-modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=-modernc.org/libc v1.70.0 h1:U58NawXqXbgpZ/dcdS9kMshu08aiA6b7gusEusqzNkw=-modernc.org/libc v1.70.0/go.mod h1:OVmxFGP1CI/Z4L3E0Q3Mf1PDE0BucwMkcXjjLntvHJo=-modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=-modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=-modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=-modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=-modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=-modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=-modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=-modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=-modernc.org/sqlite v1.47.0 h1:R1XyaNpoW4Et9yly+I2EeX7pBza/w+pmYee/0HJDyKk=-modernc.org/sqlite v1.47.0/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig=-modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=-modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=-modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=-modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=diff --git a/internal/ate/client.go b/internal/ate/client.godeleted file mode 100644index 81a5c06..0000000--- a/internal/ate/client.go+++ /dev/null@@ -1,109 +0,0 @@-// 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 ate provides a client for the Agent Substrate Control API.-package ate--import (- "context"- "fmt"-- "github.com/agent-substrate/substrate/pkg/proto/ateapipb"- "google.golang.org/grpc"- "google.golang.org/grpc/codes"- "google.golang.org/grpc/credentials/insecure"- "google.golang.org/grpc/status"-)--type Client struct {- namespace string- template string- conn *grpc.ClientConn-}--// NewClient creates a new actor client.-func NewClient(ns, template, target string, opts ...grpc.DialOption) (*Client, error) {- if ns == "" {- return nil, fmt.Errorf("namespace cannot be empty")- }- if template == "" {- return nil, fmt.Errorf("template cannot be empty")- }- if target == "" {- target = "api.ate-system.svc:443"- }- if len(opts) == 0 {- opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))- }- conn, err := grpc.NewClient(target, opts...)- if err != nil {- return nil, fmt.Errorf("error when creating Control client: %w", err)- }- return &Client{- namespace: ns,- template: template,- conn: conn,- }, nil-}--// CreateActor creates a new actor.-func (c *Client) CreateActor(ctx context.Context, id string) (*ateapipb.CreateActorResponse, error) {- client := ateapipb.NewControlClient(c.conn)- // TODO(wjjclaud): Configure atespace in manifests instead of reusing the namespace.- if _, err := client.CreateAtespace(ctx, &ateapipb.CreateAtespaceRequest{Name: c.namespace}); err != nil && status.Code(err) != codes.AlreadyExists {- return nil, fmt.Errorf("error when calling Control.CreateAtespace: %w", err)- }- resp, err := client.CreateActor(ctx, &ateapipb.CreateActorRequest{- ActorRef: &ateapipb.ActorRef{Atespace: c.namespace, Name: id},- ActorTemplateNamespace: c.namespace,- ActorTemplateName: c.template,- })- if err != nil {- return nil, fmt.Errorf("error when calling Control.CreateActor: %w", err)- }- return resp, nil-}--// ResumeActor resumes the actor, scheduling it onto a worker. The returned-// actor carries the worker IP once it is running.-func (c *Client) ResumeActor(ctx context.Context, id string) (*ateapipb.ResumeActorResponse, error) {- client := ateapipb.NewControlClient(c.conn)- resp, err := client.ResumeActor(ctx, &ateapipb.ResumeActorRequest{- ActorRef: &ateapipb.ActorRef{Atespace: c.namespace, Name: id},- })- if err != nil {- return nil, fmt.Errorf("error when calling Control.ResumeActor: %w", err)- }- return resp, nil-}--// SuspendActor suspends the actor.-func (c *Client) SuspendActor(ctx context.Context, id string) (*ateapipb.SuspendActorResponse, error) {- client := ateapipb.NewControlClient(c.conn)- resp, err := client.SuspendActor(ctx, &ateapipb.SuspendActorRequest{- ActorRef: &ateapipb.ActorRef{Atespace: c.namespace, Name: id},- })- if err != nil {- return nil, fmt.Errorf("error when calling Control.SuspendActor: %w", err)- }- return resp, nil-}--// Close closes the gRPC connection.-func (c *Client) Close() error {- if c.conn != nil {- return c.conn.Close()- }- return nil-}diff --git a/internal/cmd/e2e/main.go b/internal/cmd/e2e/main.godeleted file mode 100644index 6f8c42a..0000000--- a/internal/cmd/e2e/main.go+++ /dev/null@@ -1,143 +0,0 @@-// 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 main implements an end-to-end demonstration of the Antigravity harness-// integration with AX Controller V2.-//-// TO RUN THIS E2E DEMONSTRATION:-//-// Step 1: Start the Python gRPC Harness Server (in a separate terminal or background):-//-// PYTHONPATH=python:. /Users/anjalisridhar/.gemini/jetski/worktrees/harness-interface-3/implement-agy-sdk-streaming-20260528/.venv/bin/python python/antigravity/harness_server.py --port 50053-//-// Step 2: Run this Go E2E client:-//-// go run internal/cmd/e2e/main.go-package main--import (- "context"- "fmt"- "log"- "net"- "os"- "time"-- "github.com/google/ax/internal/controller"- "github.com/google/ax/internal/controller/eventlog"- "github.com/google/ax/internal/controller/eventlog/eventlogtest"- "github.com/google/ax/internal/harness/antigravity"- "github.com/google/ax/proto"-)--func main() {- ctx := context.Background()- fmt.Println("==================================================")- fmt.Println("AX Controller V2 - E2E Harness Demonstration")- fmt.Println("==================================================")-- // -------------------------------------------------------------------------- // Demo 1: Unregistered Harness (Should fail)- // -------------------------------------------------------------------------- fmt.Println("\n--- Demo 1: Unregistered Harness ---")- fmt.Println("Requesting 'unregistered-agent'. Exec should fail since no harness is registered.")- runDemo(ctx, "unregistered-agent", func(reg *controller.Registry) {- // Do not register any harness- })-- // -------------------------------------------------------------------------- // Demo 2: Antigravity Execution (Requires google-antigravity & GEMINI_API_KEY)- // -------------------------------------------------------------------------- fmt.Println("\n--- Demo 2: Antigravity Execution ---")- fmt.Println("Registering 'antigravity' with real script. Attempting execution.")- if os.Getenv("GEMINI_API_KEY") == "" {- fmt.Println("WARNING: GEMINI_API_KEY is not set. Execution will likely fail if dependencies are missing, but we will try anyway.")- }- runDemo(ctx, "antigravity", func(reg *controller.Registry) {- // With the new stateful gRPC-based streaming harness, connectivity checks on the- // server address replace the build-time checks for local script file presence.- address := "localhost:50053"- conn, err := net.DialTimeout("tcp", address, 1*time.Second)- if err != nil {- log.Fatalf("Antigravity harness server not active at %s: %v", address, err)- }- conn.Close()- fmt.Printf("Connected to Antigravity gRPC harness server at %s\n", address)- // TODO: add a companion demo that uses autoStart=true (mirrors ax exec local mode).- h, _ := antigravity.New(ctx, address, "", false)- reg.RegisterHarness("antigravity", h)- })-}--func runDemo(ctx context.Context, harnessID string, setupRegistry func(reg *controller.Registry)) {- reg := controller.NewRegistry()- setupRegistry(reg)-- log := &eventlogtest.MemoryEventLog{}- c, err := controller.New(ctx, controller.Config{- Registry: reg,- EventLogBuilder: func() (eventlog.EventLog, error) {- return log, nil- },- })- if err != nil {- fmt.Printf("Error creating controller: %v\n", err)- return- }- defer c.Close()-- handler := controller.ExecHandler(func(resp *proto.CreateInteractionResponse) error {- for _, out := range resp.Outputs {- if contentStep := out.GetContent(); contentStep != nil {- for _, c := range contentStep.Content {- if textContent := c.GetText().GetText(); textContent != "" {- fmt.Printf("Agent Output: %s\n", textContent)- }- }- } else if toolCall := out.GetToolCall(); toolCall != nil {- fmt.Printf("Agent Triggered Tool Call: %s (ID: %s)\n", toolCall.GetFunctionCall().Name, toolCall.Id)- }- }- return nil- })-- inputs := []*proto.Step{- {- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Role: "user",- Content: []*proto.Content{- {- Type: &proto.Content_Text{- Text: &proto.TextContent{Text: "What is the weather in New York?"},- },- },- },- },- },- },- }-- err = c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: "e2e-conv",- Inputs: inputs,- AgentId: harnessID,- }, handler)-- if err != nil {- fmt.Printf("Execution Failed (as expected if environment is not ready): %v\n", err)- } else {- fmt.Println("Execution Succeeded!")- }-}diff --git a/internal/config/config.go b/internal/config/config.godeleted file mode 100644index e22b05d..0000000--- a/internal/config/config.go+++ /dev/null@@ -1,375 +0,0 @@-// 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 config provides configuration for the controller server path.-package config--import (- "fmt"- "os"- "path/filepath"- "strings"-- "github.com/google/ax/internal/harness"- "github.com/google/ax/internal/harness/substrate"- "gopkg.in/yaml.v3"-)--const (- // The substrate namespace reserved for AX's built-in harnesses.- defaultNamespace = "ax"- // The port for harnesses running as substrate actors. Substrate's- // actor networking DNATs inbound workerPodIP:80 to the actor.- substrateDefaultPort = 80- // Harness IDs reserved for AX's built-in harnesses.- AntigravityHarnessID = "antigravity"- AntigravityInteractionsHarnessID = "antigravity-interactions"- // AntigravityHarnessTemplate is the substrate ActorTemplate that runs the- // Antigravity harness.- AntigravityHarnessTemplate = "ax-harness-antigravity-template"- // AntigravityInteractionsTemplate is the substrate ActorTemplate that runs- // the Antigravity Interactions harness.- AntigravityInteractionsTemplate = "ax-harness-interactions-template"-)--// Config represents the main configuration for the AX harness server.-type Config struct {- Version string `yaml:"version"`- Server ServerConfig `yaml:"server"`- EventLog EventLogConfig `yaml:"eventlog"`- Antigravity AntigravityHarnessConfig `yaml:"antigravity,omitempty"`- Registry RegistryConfig `yaml:"registry,omitempty"`- // Skills makes agent skills available on disk before the harness starts. It- // is harness-agnostic: each actor runs exactly one harness, which consumes- // the resulting folder(s). Optional; disabled when no source is enabled. See- // SkillsConfig for the available sources.- Skills SkillsConfig `yaml:"skills,omitempty"`- Telemetry TelemetryConfig `yaml:"telemetry,omitempty"`-}--// ServerConfig configures the gRPC server.-type ServerConfig struct {- Address string `yaml:"address"` // Server address to listen on (e.g., ":8494")-}--// TelemetryConfig configures telemetry options.-type TelemetryConfig struct {- OTLP OTLPConfig `yaml:"otlp,omitempty"`-}--// OTLPConfig configures the OTLP exporter.-type OTLPConfig struct {- Enabled bool `yaml:"enabled,omitempty"`- Endpoint string `yaml:"endpoint,omitempty"` // OTLP collector endpoint (e.g., "localhost:4317")-}--// SQLiteConfig configures the SQLite event log file.-type SQLiteConfig struct {- Filename string `yaml:"filename"` // SQLite file for event log storage-}--// PostgresConfig configures the Postgres event log.-type PostgresConfig struct {- DSN string `yaml:"dsn"` // Postgres connection DSN-}--// EventLogConfig configures the event log storage.-type EventLogConfig struct {- SQLiteConfig SQLiteConfig `yaml:"sqlite,omitempty"`- PostgresConfig PostgresConfig `yaml:"postgres,omitempty"`-}--// RegistryConfig groups harnesses to serve by type. There are two categories:-// - Built-in harnesses (e.g. Antigravity, AntigravityInteractions) whose-// implementation and container image are provided by AX.-// - Custom harnesses on substrate whose implementation and container image are-// provided by the user via their own ActorTemplate.-type RegistryConfig struct {- Antigravity AntigravityHarnessConfig `yaml:"antigravity,omitempty"`- AntigravityInteractions AntigravityInteractionsHarnessConfig `yaml:"antigravity-interactions,omitempty"`- Substrate []SubstrateHarnessConfig `yaml:"substrate,omitempty"`-}--// AntigravityHarnessConfig registers the built-in Antigravity harness.-type AntigravityHarnessConfig struct {- Default bool `yaml:"default,omitempty"`- Endpoint string `yaml:"endpoint,omitempty"` // HarnessService address-}--// AntigravityInteractionsHarnessConfig registers the built-in Antigravity-// Interactions harness (over the Vertex GenAI Interactions API).-type AntigravityInteractionsHarnessConfig struct {- Default bool `yaml:"default,omitempty"` // Default harness or not- Agent string `yaml:"agent,omitempty"` // Interactions API agent (default: antigravityinteractions.DefaultAgent)- // SystemInstruction is a free-form system prompt sent on every turn.- SystemInstruction string `yaml:"system_instruction,omitempty"`-}--// SkillsConfig configures optional skill sources (top-level, harness-agnostic).-// There are two parallel source types:-// - Registries source skills from the Gemini Enterprise Skill Registry,-// materializing them into a target directory.-// - Local points at directories that already contain skills on disk (each a-// parent dir holding <skill-id>/SKILL.md subfolders, matching the layout of-// examples/skills and a registry's target_dir). Nothing is fetched; the-// directory is used as-is.-//-// Both may be configured together, and both feed the same downstream consumers-// (e.g. a harness system-instruction pointer).-type SkillsConfig struct {- Registries []SkillsRegistryConfig `yaml:"registries,omitempty"`- Local []LocalSkillsConfig `yaml:"local,omitempty"`-}--// Validate checks the (top-level) skills config.-func (s SkillsConfig) Validate() error {- for i := range s.Registries {- if err := s.Registries[i].validate(i); err != nil {- return err- }- }- for i := range s.Local {- if err := s.Local[i].validate(i); err != nil {- return err- }- }- return nil-}--// LocalSkillsConfig sources skills from a directory already present on disk. The-// path is a parent directory containing one subfolder per skill (each with a-// SKILL.md); the subfolder name is the skill id. This mirrors the layout of-// examples/skills and a registry's target_dir, so nothing is downloaded.-type LocalSkillsConfig struct {- Enabled bool `yaml:"enabled,omitempty"`- // Path is the parent directory holding <skill-id>/SKILL.md subfolders.- // Required when Enabled.- Path string `yaml:"path,omitempty"`-}--// validate checks one local skills source. idx is its index within the local-// list, for error context. Existence/readability of the path is intentionally-// not checked here: discovery is fail-safe (a bad path degrades capability-// rather than blocking harness creation), so it is validated at discovery time.-func (lc LocalSkillsConfig) validate(idx int) error {- if !lc.Enabled {- return nil- }- if strings.TrimSpace(lc.Path) == "" {- return fmt.Errorf("skills.local[%d] requires path (a directory containing <skill-id>/SKILL.md subfolders)", idx)- }- return nil-}--// validate enforces that, when this registry source is enabled, exactly one-// selection mode is set (skills, query, or all) — a config-level "oneof". idx is-// the registry's index within the registries list, for error context.-func (rc SkillsRegistryConfig) validate(idx int) error {- if !rc.Enabled {- return nil- }- if rc.TargetDir == "" {- return fmt.Errorf("skills.registries[%d] requires target_dir (skills materialize to <target_dir>/<skill-id>/)", idx)- }- modes := 0- if len(rc.Skills) > 0 {- modes++- }- if rc.Query != nil {- modes++- }- if rc.All {- modes++- }- switch {- case modes == 0:- return fmt.Errorf("skills.registries[%d] requires exactly one selection mode (set one of skills, query, or all)", idx)- case modes > 1:- return fmt.Errorf("skills.registries[%d] sets multiple selection modes; set exactly one of skills, query, or all", idx)- }- if rc.Query != nil && rc.Query.Text == "" {- return fmt.Errorf("skills.registries[%d].query requires a non-empty text", idx)- }- return nil-}--// SkillsRegistryConfig sources agentskills.io skills from the Gemini Skill-// Registry. When Enabled, exactly one selection mode should be set (Skills,-// Query, or All); if none is set, all skills are materialized.-type SkillsRegistryConfig struct {- Enabled bool `yaml:"enabled,omitempty"`- // Project owns the skills (projects/{Project}/locations/{Location}/skills).- // Empty falls back to the GOOGLE_CLOUD_PROJECT environment variable.- Project string `yaml:"project,omitempty"`- // Location is the registry region, e.g. "us-central1". Empty falls back to- // GOOGLE_CLOUD_LOCATION, then a built-in default.- Location string `yaml:"location,omitempty"`-- // --- selection (choose one) ----- // Skills is an explicit allowlist of skills, each optionally pinned to a- // revision. Takes precedence over Query and All.- Skills []SkillRefConfig `yaml:"skills,omitempty"`- // Query is a semantic search selection; its top matches are materialized.- // TopK lives inside it because it only has meaning for a query.- Query *SkillsQueryConfig `yaml:"query,omitempty"`- // All materializes every skill in the project/location (used when neither- // Skills nor Query is set; can also be set explicitly).- All bool `yaml:"all,omitempty"`-- // TargetDir is the base directory skills are materialized into: each skill- // is written to <TargetDir>/<skill-id>/. Required when Enabled.- TargetDir string `yaml:"target_dir,omitempty"`-}--// SkillsQueryConfig selects skills by semantic search.-type SkillsQueryConfig struct {- // Text is the semantic search string (required for query selection).- Text string `yaml:"text"`- // TopK bounds the number of matches (<=0 uses the server default).- TopK int `yaml:"top_k,omitempty"`-}--// SkillRefConfig identifies a skill to materialize, optionally pinned.-type SkillRefConfig struct {- ID string `yaml:"id"`- Revision string `yaml:"revision,omitempty"`-}--// SubstrateHarnessConfig registers a custom harness deployed on substrate-// from a user-provided container image.-type SubstrateHarnessConfig struct {- ID string `yaml:"id"` // Unique harness identifier- Namespace string `yaml:"namespace"` // ActorTemplate namespace (user-owned, not "ax")- Template string `yaml:"template"` // ActorTemplate name- Port int `yaml:"port,omitempty"` // HarnessService port- Default bool `yaml:"default,omitempty"` // Default harness or not-}--// NewHarness builds the custom harness. Custom harnesses always run as substrate-// actors from the user's own ActorTemplate.-func (c SubstrateHarnessConfig) NewHarness(endpoint string) (harness.Harness, error) {- port := c.Port- if port == 0 {- port = substrateDefaultPort- }- return newSubstrateHarness(c.ID, endpoint, c.Namespace, c.Template, port)-}--// newSubstrateHarness brings up a harness that is deployed as a substrate actor.-func newSubstrateHarness(harnessID, endpoint, namespace, template string, port int) (harness.Harness, error) {- sh, err := substrate.New(harnessID, endpoint, namespace, template, port)- if err != nil {- return nil, err- }- return sh, nil-}--// LoadFromFile loads configuration from a YAML file.-func LoadFromFile(path string) (*Config, error) {- data, err := os.ReadFile(path)- if err != nil {- return nil, fmt.Errorf("failed to read config file: %w", err)- }- return LoadFromBytes(data)-}--// LoadFromBytes parses configuration from YAML bytes and applies defaults.-func LoadFromBytes(data []byte) (*Config, error) {- var cfg Config- if err := yaml.Unmarshal(data, &cfg); err != nil {- return nil, fmt.Errorf("failed to parse config: %w", err)- }-- cfg.setDefaults()-- return &cfg, nil-}--// DefaultConfig returns a configuration with default values set.-func DefaultConfig() *Config {- var cfg Config- cfg.setDefaults()- return &cfg-}--// setDefaults sets default values for optional fields.-func (c *Config) setDefaults() {- if c.Server.Address == "" {- c.Server.Address = ":8494"- }- if c.EventLog.SQLiteConfig.Filename == "" {- c.EventLog.SQLiteConfig.Filename = "eventlog/log.sqlite"- }-}--// Validate validates the configuration.-func (c *Config) Validate() error {- if c.Server.Address == "" {- return fmt.Errorf("server.address is required")- }- if c.EventLog.PostgresConfig.DSN == "" && c.EventLog.SQLiteConfig.Filename == "" {- return fmt.Errorf("eventlog requires either postgres.dsn or sqlite.filename")- }-- var defaultCount int- if c.Antigravity.Default || c.Registry.Antigravity.Default {- defaultCount++- }- if c.Registry.AntigravityInteractions.Default {- defaultCount++- }-- for _, sc := range c.Registry.Substrate {- if sc.ID == "" {- return fmt.Errorf("substrate harness id is required")- }- if sc.ID == AntigravityHarnessID || sc.ID == AntigravityInteractionsHarnessID {- return fmt.Errorf("substrate harness id %q is reserved for built-in harnesses", sc.ID)- }- if sc.Namespace == "" {- return fmt.Errorf("substrate harness %q: namespace is required", sc.ID)- }- if sc.Namespace == defaultNamespace {- return fmt.Errorf("substrate harness %q: namespace %q is reserved for built-in harnesses", sc.ID, defaultNamespace)- }- if sc.Template == "" {- return fmt.Errorf("substrate harness %q: template is required", sc.ID)- }- if sc.Default {- defaultCount++- }- }-- if defaultCount > 1 {- return fmt.Errorf("multiple harnesses marked as default")- }-- if err := c.Skills.Validate(); err != nil {- return err- }-- return nil-}--func AXAssetsDir() (string, error) {- if dir := os.Getenv("AX_DURABLE_DIR"); dir != "" {- return filepath.Join(dir, ".ax"), nil- }- home, err := os.UserHomeDir()- if err != nil {- return "", fmt.Errorf("resolving home directory: %w", err)- }- return filepath.Join(home, ".ax"), nil-}diff --git a/internal/config/config_test.go b/internal/config/config_test.godeleted file mode 100644index a4c5ab2..0000000--- a/internal/config/config_test.go+++ /dev/null@@ -1,421 +0,0 @@-// 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 config--import (- "os"- "path/filepath"- "strings"- "testing"-- "gopkg.in/yaml.v3"-)--func TestSubstrateNewHarness(t *testing.T) {- h, err := SubstrateHarnessConfig{ID: "c", Namespace: "team-ns", Template: "custom-template"}.NewHarness("api.ate-system.svc:443")- if err != nil {- t.Fatalf("NewHarness: %v", err)- }- if h == nil {- t.Fatal("expected non-nil harness")- }-}--// validConfig returns a config that passes Validate, that tests can mutate.-func validConfig() *Config {- c := DefaultConfig()- c.Registry = RegistryConfig{- Antigravity: AntigravityHarnessConfig{Default: true},- Substrate: []SubstrateHarnessConfig{- {ID: "custom", Namespace: "team-ns", Template: "custom-template"},- },- }- return c-}--func TestValidate_ValidConfig(t *testing.T) {- if err := validConfig().Validate(); err != nil {- t.Fatalf("Validate() = %v, want nil", err)- }-}--func TestValidate_CustomIDRequired(t *testing.T) {- c := validConfig()- c.Registry.Substrate[0].ID = ""- err := c.Validate()- if err == nil || !strings.Contains(err.Error(), "substrate harness id") {- t.Fatalf("Validate() = %v, want substrate id error", err)- }-}--func TestValidate_CustomIDReserved(t *testing.T) {- c := validConfig()- c.Registry.Substrate[0].ID = "antigravity"- err := c.Validate()- if err == nil || !strings.Contains(err.Error(), "reserved") {- t.Fatalf("Validate() = %v, want reserved id error", err)- }-}--func TestValidate_CustomNamespaceRequired(t *testing.T) {- c := validConfig()- c.Registry.Substrate[0].Namespace = ""- err := c.Validate()- if err == nil || !strings.Contains(err.Error(), "namespace is required") {- t.Fatalf("Validate() = %v, want namespace-required error", err)- }-}--func TestValidate_CustomNamespaceReserved(t *testing.T) {- c := validConfig()- c.Registry.Substrate[0].Namespace = defaultNamespace- err := c.Validate()- if err == nil || !strings.Contains(err.Error(), "reserved") {- t.Fatalf("Validate() = %v, want reserved-namespace error", err)- }-}--func TestValidate_CustomTemplateRequired(t *testing.T) {- c := validConfig()- c.Registry.Substrate[0].Template = ""- err := c.Validate()- if err == nil || !strings.Contains(err.Error(), "template is required") {- t.Fatalf("Validate() = %v, want template-required error", err)- }-}--func TestValidate_MultipleDefaults(t *testing.T) {- c := validConfig()- c.Registry.Substrate[0].Default = true- err := c.Validate()- if err == nil || !strings.Contains(err.Error(), "multiple harnesses marked as default") {- t.Fatalf("Validate() = %v, want multiple defaults error", err)- }-}--func TestValidate_InteractionsIDReserved(t *testing.T) {- c := validConfig()- c.Registry.Substrate[0].ID = "antigravity-interactions"- err := c.Validate()- if err == nil || !strings.Contains(err.Error(), "reserved") {- t.Fatalf("Validate() = %v, want reserved id error", err)- }-}--func TestValidate_InteractionsValid(t *testing.T) {- c := validConfig()- c.Registry.AntigravityInteractions = AntigravityInteractionsHarnessConfig{- Agent: "projects/p/locations/global/agents/a",- }- if err := c.Validate(); err != nil {- t.Fatalf("Validate() = %v, want nil", err)- }-}--func TestLoadFromFile_Version(t *testing.T) {- data := `-version: "1.2.3"-server:- address: ":8080"-eventlog:- sqlite:- filename: "test.db"-`- var cfg Config- if err := yaml.Unmarshal([]byte(data), &cfg); err != nil {- t.Fatalf("Unmarshal failed: %v", err)- }- if cfg.Version != "1.2.3" {- t.Errorf("cfg.Version = %q, want %q", cfg.Version, "1.2.3")- }-}--func TestLoadFromBytes(t *testing.T) {- cfg, err := LoadFromBytes([]byte(`-version: v1alpha-antigravity: {}-`))- if err != nil {- t.Fatalf("LoadFromBytes: %v", err)- }- if cfg.Version != "v1alpha" {- t.Errorf("Version = %q, want %q", cfg.Version, "v1alpha")- }- // setDefaults must run (same as LoadFromFile).- if got, want := cfg.Server.Address, ":8494"; got != want {- t.Errorf("Server.Address = %q, want default %q", got, want)- }-}--// TestLoadFromBytes_Invalid returns an error on malformed YAML.-func TestLoadFromBytes_Invalid(t *testing.T) {- if _, err := LoadFromBytes([]byte("registry: [unterminated")); err == nil {- t.Fatal("LoadFromBytes(invalid): got nil error, want error")- }-}--func TestParse_SkillsByID(t *testing.T) {- data := `-skills:- registries:- - enabled: true- project: my-proj- location: us-central1- target_dir: /tmp/ax-skills- skills:- - id: emoji- - id: lowercase- revision: rev-3-`- var cfg Config- if err := yaml.Unmarshal([]byte(data), &cfg); err != nil {- t.Fatalf("Unmarshal failed: %v", err)- }- if len(cfg.Skills.Registries) != 1 {- t.Fatalf("registries = %d, want 1", len(cfg.Skills.Registries))- }- reg := cfg.Skills.Registries[0]- if !reg.Enabled || reg.Project != "my-proj" || reg.Location != "us-central1" || reg.TargetDir != "/tmp/ax-skills" {- t.Errorf("registry = %+v, want enabled my-proj/us-central1 /tmp/ax-skills", reg)- }- if len(reg.Skills) != 2 {- t.Fatalf("skills = %d, want 2", len(reg.Skills))- }- if reg.Skills[0].ID != "emoji" || reg.Skills[0].Revision != "" {- t.Errorf("skills[0] = %+v, want {emoji }", reg.Skills[0])- }- if reg.Skills[1].ID != "lowercase" || reg.Skills[1].Revision != "rev-3" {- t.Errorf("skills[1] = %+v, want {lowercase rev-3}", reg.Skills[1])- }- if reg.Query != nil {- t.Errorf("Query = %+v, want nil in by-id mode", reg.Query)- }-}--func TestParse_SkillsByQuery(t *testing.T) {- data := `-skills:- registries:- - enabled: true- project: my-proj- target_dir: /tmp/ax-skills- query:- text: "find gcp skills"- top_k: 5-`- var cfg Config- if err := yaml.Unmarshal([]byte(data), &cfg); err != nil {- t.Fatalf("Unmarshal failed: %v", err)- }- regs := cfg.Skills.Registries- if len(regs) != 1 || regs[0].Query == nil {- t.Fatalf("registries = %+v, want one with a query block", regs)- }- if regs[0].Query.Text != "find gcp skills" || regs[0].Query.TopK != 5 {- t.Errorf("Query = %+v, want {find gcp skills 5}", *regs[0].Query)- }-}--func TestParse_MultipleRegistries(t *testing.T) {- data := `-skills:- registries:- - enabled: true- project: org-proj- target_dir: /tmp/org- all: true- - enabled: true- project: team-proj- target_dir: /tmp/team- skills:- - id: teamskill-`- var cfg Config- if err := yaml.Unmarshal([]byte(data), &cfg); err != nil {- t.Fatalf("Unmarshal failed: %v", err)- }- regs := cfg.Skills.Registries- if len(regs) != 2 {- t.Fatalf("registries = %d, want 2", len(regs))- }- if regs[0].Project != "org-proj" || regs[0].TargetDir != "/tmp/org" || !regs[0].All {- t.Errorf("registries[0] = %+v, want org-proj /tmp/org all", regs[0])- }- if regs[1].Project != "team-proj" || regs[1].TargetDir != "/tmp/team" || len(regs[1].Skills) != 1 {- t.Errorf("registries[1] = %+v, want team-proj /tmp/team [teamskill]", regs[1])- }- // Each registry has exactly one selection mode + target_dir, so validation passes.- if err := cfg.Skills.Validate(); err != nil {- t.Errorf("Skills.Validate() = %v, want nil", err)- }-}--func TestValidate_SkillsSelectionOneof(t *testing.T) {- // withRegistry returns a valid config carrying a single top-level registry.- // It fills TargetDir (a required field) unless the caller already set one, so- // selection-mode assertions aren't masked by the target_dir check.- withRegistry := func(rc SkillsRegistryConfig) *Config {- if rc.Enabled && rc.TargetDir == "" {- rc.TargetDir = "/tmp/skills"- }- c := validConfig()- c.Skills.Registries = []SkillsRegistryConfig{rc}- return c- }-- t.Run("disabled skips validation", func(t *testing.T) {- if err := withRegistry(SkillsRegistryConfig{Enabled: false}).Validate(); err != nil {- t.Fatalf("Validate() = %v, want nil", err)- }- })-- t.Run("enabled without target_dir is an error", func(t *testing.T) {- c := validConfig()- c.Skills.Registries = []SkillsRegistryConfig{- {Enabled: true, Project: "p", All: true}, // valid mode, but no target_dir- }- err := c.Validate()- if err == nil || !strings.Contains(err.Error(), "target_dir") {- t.Fatalf("Validate() = %v, want target_dir error", err)- }- })-- t.Run("zero selection modes is an error", func(t *testing.T) {- err := withRegistry(SkillsRegistryConfig{Enabled: true, Project: "p"}).Validate()- if err == nil || !strings.Contains(err.Error(), "exactly one selection mode") {- t.Fatalf("Validate() = %v, want exactly-one error", err)- }- })-- t.Run("multiple selection modes is an error", func(t *testing.T) {- err := withRegistry(SkillsRegistryConfig{- Enabled: true, Project: "p",- Skills: []SkillRefConfig{{ID: "emoji"}},- All: true,- }).Validate()- if err == nil || !strings.Contains(err.Error(), "multiple selection modes") {- t.Fatalf("Validate() = %v, want multiple-modes error", err)- }- })-- t.Run("exactly one is valid", func(t *testing.T) {- err := withRegistry(SkillsRegistryConfig{- Enabled: true, Project: "p",- Skills: []SkillRefConfig{{ID: "emoji"}},- }).Validate()- if err != nil {- t.Fatalf("Validate() = %v, want nil", err)- }- })-- t.Run("query with empty text is an error", func(t *testing.T) {- err := withRegistry(SkillsRegistryConfig{- Enabled: true, Project: "p",- Query: &SkillsQueryConfig{Text: ""},- }).Validate()- if err == nil || !strings.Contains(err.Error(), "non-empty text") {- t.Fatalf("Validate() = %v, want empty-text error", err)- }- })-- t.Run("second registry invalid is caught", func(t *testing.T) {- c := validConfig()- c.Skills.Registries = []SkillsRegistryConfig{- {Enabled: true, Project: "p", TargetDir: "/tmp/a", All: true},- {Enabled: true, Project: "p", TargetDir: "/tmp/b"}, // no selection mode- }- err := c.Validate()- if err == nil || !strings.Contains(err.Error(), "registries[1]") {- t.Fatalf("Validate() = %v, want error citing registries[1]", err)- }- })-}--func TestAXAssetsDir(t *testing.T) {- t.Run("durable-dir env roots the .ax tree on the volume", func(t *testing.T) {- t.Setenv("AX_DURABLE_DIR", "/mnt/durable")- got, err := AXAssetsDir()- if err != nil {- t.Fatalf("AXAssetsDir: %v", err)- }- want := filepath.Join("/mnt/durable", ".ax")- if got != want {- t.Errorf("AXAssetsDir() = %q, want %q", got, want)- }- })- t.Run("unset roots under the home directory", func(t *testing.T) {- t.Setenv("AX_DURABLE_DIR", "")- home, err := os.UserHomeDir()- if err != nil {- t.Skipf("no home directory: %v", err)- }- got, err := AXAssetsDir()- if err != nil {- t.Fatalf("AXAssetsDir: %v", err)- }- want := filepath.Join(home, ".ax")- if got != want {- t.Errorf("AXAssetsDir() = %q, want %q", got, want)- }- })-}--func TestValidate_LocalSkills(t *testing.T) {- withLocal := func(lcs ...LocalSkillsConfig) *Config {- c := validConfig()- c.Skills.Local = lcs- return c- }-- t.Run("disabled skips validation", func(t *testing.T) {- if err := withLocal(LocalSkillsConfig{Enabled: false}).Validate(); err != nil {- t.Fatalf("Validate() = %v, want nil", err)- }- })-- t.Run("enabled without path is an error", func(t *testing.T) {- err := withLocal(LocalSkillsConfig{Enabled: true}).Validate()- if err == nil || !strings.Contains(err.Error(), "path") {- t.Fatalf("Validate() = %v, want path error", err)- }- })-- t.Run("enabled with path is valid", func(t *testing.T) {- if err := withLocal(LocalSkillsConfig{Enabled: true, Path: "./examples/skills"}).Validate(); err != nil {- t.Fatalf("Validate() = %v, want nil", err)- }- })-- t.Run("second local invalid is caught", func(t *testing.T) {- err := withLocal(- LocalSkillsConfig{Enabled: true, Path: "/tmp/a"},- LocalSkillsConfig{Enabled: true}, // no path- ).Validate()- if err == nil || !strings.Contains(err.Error(), "local[1]") {- t.Fatalf("Validate() = %v, want error citing local[1]", err)- }- })-- t.Run("registries and local can coexist", func(t *testing.T) {- c := validConfig()- c.Skills.Registries = []SkillsRegistryConfig{- {Enabled: true, Project: "p", TargetDir: "/tmp/a", All: true},- }- c.Skills.Local = []LocalSkillsConfig{{Enabled: true, Path: "/tmp/local"}}- if err := c.Validate(); err != nil {- t.Fatalf("Validate() = %v, want nil", err)- }- })-}diff --git a/internal/controller/controller.go b/internal/controller/controller.godeleted file mode 100644index b5c4b59..0000000--- a/internal/controller/controller.go+++ /dev/null@@ -1,275 +0,0 @@-// 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 controller implements the single-writer orchestrator that coordinates-// agentic loops, manages executions, and communicates with local and remote agents.-package controller--import (- "context"- "fmt"- "log/slog"-- "github.com/google/ax/internal/controller/eventlog"- "github.com/google/ax/proto"- "google.golang.org/protobuf/encoding/protojson"- "google.golang.org/protobuf/types/known/structpb"-)--type ExecHandler func(resp *proto.CreateInteractionResponse) error--// Controller is the main controller that coordinates all components.-// It acts as a single-writer system for managing agentic loops.-type Controller struct {- registry *Registry- eventLog eventlog.EventLog-}--// Config configures the controller.-type Config struct {- Registry *Registry- EventLogBuilder eventlog.EventLogBuilder-}--// New creates a new controller instance.-func New(ctx context.Context, cfg Config) (*Controller, error) {- if cfg.Registry == nil {- return nil, fmt.Errorf("registry is required")- }- if cfg.EventLogBuilder == nil {- return nil, fmt.Errorf("event log builder is required")- }- eventLog, err := cfg.EventLogBuilder()- if err != nil {- return nil, fmt.Errorf("failed to create event log: %w", err)- }-- return &Controller{- registry: cfg.Registry,- eventLog: eventLog,- }, nil-}--// Exec executes a new agentic loop execution or resumes an existing one.-// If id is empty, a UUID will be generated.-// If the execution already exists, it will be resumed with optional new inputs.-func (d *Controller) Exec(ctx context.Context, req *proto.CreateInteractionEvent, handler ExecHandler) error {- if req.ConversationId == "" {- return fmt.Errorf("conversation_id is required")- }-- // TODO(jbd): Resume an incomplete execution if there exists one.- // TODO(jbd): Enable bringing a remote harness that implements HarnessService.- // TODO(anj): We need to consolidate agents and harness registration.- // Adding harness registration support temporarily.- l := newLogger(d.eventLog, req.ConversationId, req.AgentId)- state, storedHarnessID, err := l.ResumptionState(ctx)- if err != nil {- return fmt.Errorf("failed to check resumption state: %w", err)- }-- // On resume, use the conversation's recorded harness. Using a different harness- // for the same conversation is not allowed.- if req.AgentId != "" && storedHarnessID != "" && req.AgentId != storedHarnessID {- return fmt.Errorf("resumption not allowed: harness ID changed from %s to %s", storedHarnessID, req.AgentId)- }- harnessID := req.AgentId- // Use the conversations's stored harness if no harness is specified.- if harnessID == "" {- harnessID = storedHarnessID- }- // For new conversations, use the default harness if no harness is specified.- if harnessID == "" {- harnessID = d.registry.defaultHarness- }- l.harnessID = harnessID-- h, err := d.registry.Harness(harnessID)- if err != nil {- return fmt.Errorf("failed to get harness %q: %w", harnessID, err)- }-- hhandler := &harnessHandler{- logger: l,- execHandler: handler,- }-- if state == proto.State_STATE_PENDING {- // If the state is pending, first try to resume the- // pending execution. If the state is COMPLETED or FAILED, start- // a new execution.- exec, err := h.Start(ctx, req.ConversationId, req.AgentConfig)- if err != nil {- return fmt.Errorf("failed to start harness session: %w", err)- }- defer exec.Close(ctx)-- if err := exec.Run(ctx, hhandler); err != nil {- return fmt.Errorf("harness execution failed: %w", err)- }- }-- if len(req.Inputs) == 0 {- // No more inputs, just return.- return nil- }-- exec, err := h.Start(ctx, req.ConversationId, req.AgentConfig)- if err != nil {- return fmt.Errorf("failed to start harness session: %w", err)- }- defer exec.Close(ctx)-- if err := exec.Queue(ctx, req.Inputs...); err != nil {- return fmt.Errorf("failed to queue inputs: %w", err)- }- // Log inputs before running harness- if _, err := l.LogInputs(ctx, req.Inputs, req.AgentConfig); err != nil {- return fmt.Errorf("failed to log inputs: %w", err)- }- if err := exec.Run(ctx, hhandler); err != nil {- return fmt.Errorf("harness execution failed: %w", err)- }- return nil-}--type harnessHandler struct {- logger *logger- execHandler ExecHandler-}--func (a *harnessHandler) OnMessage(ctx context.Context, execID string, step *proto.Step) error {- // Log every response received from the harness- // TODO(anj): The harness should send the full input sent to get this particular response.- logStep, err := a.logger.LogOutputs(ctx, []*proto.Step{step}, proto.State_STATE_PENDING)- if err != nil {- slog.WarnContext(ctx, "Failed to log streamed message to event log",- slog.String("conversation_id", a.logger.conversationID),- slog.Any("error", err),- )- }-- if step != nil {- step.Index = logStep- }-- if a.execHandler == nil {- return nil- }- return a.execHandler(&proto.CreateInteractionResponse{- Outputs: []*proto.Step{step},- })-}--func (a *harnessHandler) OnComplete(ctx context.Context, execID string) error {- // Mark the execution turn as completed in the conversation log- if _, err := a.logger.LogOutputs(ctx, nil, proto.State_STATE_COMPLETED); err != nil {- slog.WarnContext(ctx, "Failed to mark completion state in event log",- slog.String("conversation_id", a.logger.conversationID),- slog.Any("error", err),- )- }- if a.execHandler == nil {- return nil- }- return nil-}--// Registry returns the agent registry.-func (d *Controller) Registry() *Registry {- return d.registry-}--// Close gracefully shuts down the controller.-func (d *Controller) Close() error {- if err := d.eventLog.Close(); err != nil {- return fmt.Errorf("failed to close event log: %w", err)- }- if err := d.registry.Close(); err != nil {- return fmt.Errorf("failed to close registry: %w", err)- }- return nil-}--type logger struct {- conversationID string- interactionID string- el eventlog.EventLog- harnessID string-}--func newLogger(- el eventlog.EventLog,- conversationID string,- harnessID string) *logger {- return &logger{- el: el,- conversationID: conversationID,- harnessID: harnessID,- }-}--// ResumptionState returns the conversation's current state and the harness it used.-func (l *logger) ResumptionState(ctx context.Context) (proto.State, string, error) {- events, err := l.el.Events(ctx, l.conversationID)- if err != nil {- return proto.State_STATE_UNSPECIFIED, "", err- }-- var state proto.State- var harnessID string- for _, ev := range events {- if harnessID == "" && ev.AgentId != "" {- harnessID = ev.AgentId- }- if ev.State != proto.State_STATE_UNSPECIFIED {- state = ev.State- }- }- return state, harnessID, nil-}--func (l *logger) LogInputs(ctx context.Context, steps []*proto.Step, agentConfig []byte) (int64, error) {- // Parse the agent config into a human-readable struct for logging.- var cfg *structpb.Struct- if len(agentConfig) > 0 {- cfg = &structpb.Struct{}- if err := protojson.Unmarshal(agentConfig, cfg); err != nil {- slog.WarnContext(ctx, "Failed to parse agent config for logging",- slog.String("conversation_id", l.conversationID),- slog.Any("error", err),- )- cfg = nil- }- }- ev := &proto.StepEvent{- ConversationId: l.conversationID,- InteractionId: l.interactionID,- AgentId: l.harnessID,- AgentConfig: cfg,- Steps: steps,- State: proto.State_STATE_PENDING,- }- return l.el.Append(ctx, ev)-}--func (l *logger) LogOutputs(ctx context.Context, steps []*proto.Step, state proto.State) (int64, error) {- ev := &proto.StepEvent{- ConversationId: l.conversationID,- InteractionId: l.interactionID,- Steps: steps,- State: state,- }- return l.el.Append(ctx, ev)-}diff --git a/internal/controller/controller_test.go b/internal/controller/controller_test.godeleted file mode 100644index c452764..0000000--- a/internal/controller/controller_test.go+++ /dev/null@@ -1,631 +0,0 @@-// 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 controller--import (- "context"- "fmt"- "strings"- "testing"-- "github.com/google/ax/internal/controller/eventlog"- "github.com/google/ax/internal/controller/eventlog/eventlogtest"- "github.com/google/ax/internal/harness"- "github.com/google/ax/internal/harness/harnesstest"- "github.com/google/ax/proto"-)--type fakeHarness struct{}--func (f *fakeHarness) Start(ctx context.Context, conversationID string, config []byte) (harness.Execution, error) {- return &fakeExecution{id: "fake-exec-id"}, nil-}--type fakeExecution struct {- id string- queued []*proto.Step-}--func (f *fakeExecution) ID() string {- return f.id-}--func (f *fakeExecution) Queue(ctx context.Context, steps ...*proto.Step) error {- f.queued = append(f.queued, steps...)- return nil-}--func (f *fakeExecution) Run(ctx context.Context, handler harness.Handler) error {- step := &proto.Step{- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Role: "assistant",- Content: []*proto.Content{- {- Type: &proto.Content_Text{- Text: &proto.TextContent{- Text: "Hello world",- },- },- },- },- },- },- }- if err := handler.OnMessage(ctx, f.id, step); err != nil {- return err- }- return handler.OnComplete(ctx, f.id)-}--func (f *fakeExecution) Close(ctx context.Context) error {- return nil-}--func TestController2_ExecHelloWorld(t *testing.T) {- ctx := context.Background()- cid := "test-conversation-id"-- log := &eventlogtest.MemoryEventLog{}- reg := NewRegistry()- if err := reg.RegisterHarness("default-harness", &fakeHarness{}); err != nil {- t.Fatal(err)- }- if err := reg.SetDefaultHarness("default-harness"); err != nil {- t.Fatal(err)- }-- c, err := New(ctx, Config{- Registry: reg,- EventLogBuilder: func() (eventlog.EventLog, error) {- return log, nil- },- })- if err != nil {- t.Fatal(err)- }- defer c.Close()-- var outputs []*proto.Step- handler := ExecHandler(func(resp *proto.CreateInteractionResponse) error {- outputs = append(outputs, resp.Outputs...)- return nil- })-- err = c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: cid,- Inputs: []*proto.Step{harnesstest.UserStep("Trigger prompt")},- }, handler)- if err != nil {- t.Fatalf("Controller2.Exec failed: %v", err)- }-- if len(outputs) != 1 {- t.Fatalf("expected exactly 1 output message, got %d", len(outputs))- }-- gotText := outputs[0].GetContent().Content[0].GetText().GetText()- if gotText != "Hello world" {- t.Errorf("expected 'Hello world' output text response, got %q", gotText)- }-- // Verify that events were logged correctly in Conversation Log- events, err := log.Events(ctx, cid)- if err != nil {- t.Fatalf("failed to retrieve logged events: %v", err)- }-- if len(events) != 3 {- t.Fatalf("expected 3 logged events, got %d", len(events))- }-- // 1. First event should be inputs- if len(events[0].Steps) != 1 {- t.Errorf("expected 1 step in first event, got %d", len(events[0].Steps))- } else {- gotInputText := events[0].Steps[0].GetContent().Content[0].GetText().GetText()- if gotInputText != "Trigger prompt" {- t.Errorf("expected 'Trigger prompt' in logged input, got %q", gotInputText)- }- }- if events[0].State != proto.State_STATE_PENDING {- t.Errorf("expected first event state to be PENDING, got %v", events[0].State)- }-- // 2. Second event should be output- if len(events[1].Steps) != 1 {- t.Errorf("expected 1 step in second event, got %d", len(events[1].Steps))- } else {- gotOutputText := events[1].Steps[0].GetContent().Content[0].GetText().GetText()- if gotOutputText != "Hello world" {- t.Errorf("expected 'Hello world' in logged output, got %q", gotOutputText)- }- }- if events[1].State != proto.State_STATE_PENDING {- t.Errorf("expected second event state to be PENDING, got %v", events[1].State)- }-- // 3. Third event should be completion- if len(events[2].Steps) != 0 {- t.Errorf("expected 0 steps in third event, got %d", len(events[2].Steps))- }- if events[2].State != proto.State_STATE_COMPLETED {- t.Errorf("expected third event state to be COMPLETED, got %v", events[2].State)- }--}--func TestController2_ExecWithAgentID(t *testing.T) {- ctx := context.Background()- cid := "test-conversation-id"-- log := &eventlogtest.MemoryEventLog{}- reg := NewRegistry()- if err := reg.RegisterHarness("my-agent", &fakeHarness{}); err != nil {- t.Fatal(err)- }-- c, err := New(ctx, Config{- Registry: reg,- EventLogBuilder: func() (eventlog.EventLog, error) {- return log, nil- },- })- if err != nil {- t.Fatal(err)- }- defer c.Close()-- var outputs []*proto.Step- handler := ExecHandler(func(resp *proto.CreateInteractionResponse) error {- outputs = append(outputs, resp.Outputs...)- return nil- })-- err = c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: cid,- AgentId: "my-agent",- Inputs: []*proto.Step{harnesstest.UserStep("Trigger prompt")},- }, handler)- if err != nil {- t.Fatalf("Controller2.Exec failed: %v", err)- }-- if len(outputs) != 1 {- t.Fatalf("expected exactly 1 output message, got %d", len(outputs))- }-- gotText := outputs[0].GetContent().Content[0].GetText().GetText()- if gotText != "Hello world" {- t.Errorf("expected 'Hello world' output text response, got %q", gotText)- }-}--func TestController2_ExecHarnessNotFound(t *testing.T) {- ctx := context.Background()- cid := "test-conversation-id"-- log := &eventlogtest.MemoryEventLog{}- reg := NewRegistry() // Empty registry, will force error for any requested agent-- c, err := New(ctx, Config{- Registry: reg,- EventLogBuilder: func() (eventlog.EventLog, error) {- return log, nil- },- })- if err != nil {- t.Fatal(err)- }- defer c.Close()-- handler := ExecHandler(func(resp *proto.CreateInteractionResponse) error {- return nil- })-- err = c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: cid,- AgentId: "antigravity",- Inputs: []*proto.Step{harnesstest.UserStep("Trigger prompt")},- }, handler)- if err == nil {- t.Fatal("expected error requesting unregistered agent, got nil")- }-}--type testHarness struct {- startCalls int- startFunc func(ctx context.Context, conversationID string) (harness.Execution, error)-}--func (c *testHarness) Start(ctx context.Context, conversationID string, config []byte) (harness.Execution, error) {- c.startCalls++- return c.startFunc(ctx, conversationID)-}--type testExecution struct {- id string- queueCalls int- runCalls int- closeCalls int- queued []*proto.Step- runFunc func(ctx context.Context, execID string, handler harness.Handler) error-}--func (c *testExecution) ID() string {- return c.id-}--func (c *testExecution) Queue(ctx context.Context, steps ...*proto.Step) error {- c.queueCalls++- c.queued = append(c.queued, steps...)- return nil-}--func (c *testExecution) Run(ctx context.Context, handler harness.Handler) error {- c.runCalls++- if c.runFunc != nil {- return c.runFunc(ctx, c.id, handler)- }- return nil-}--func (c *testExecution) Close(ctx context.Context) error {- c.closeCalls++- return nil-}--func TestController2_ExecResumptionFlow(t *testing.T) {- // Subtest 1: New Execution with Inputs- t.Run("NewExecutionWithInputs", func(t *testing.T) {- ctx := context.Background()- cid := "new-conv"-- log := &eventlogtest.MemoryEventLog{}- reg := NewRegistry()-- var exec *testExecution- h := &testHarness{- startFunc: func(ctx context.Context, conversationID string) (harness.Execution, error) {- exec = &testExecution{- id: "exec-new",- runFunc: func(ctx context.Context, execID string, handler harness.Handler) error {- return handler.OnComplete(ctx, execID)- },- }- return exec, nil- },- }- if err := reg.RegisterHarness("test-agent", h); err != nil {- t.Fatal(err)- }-- c, err := New(ctx, Config{- Registry: reg,- EventLogBuilder: func() (eventlog.EventLog, error) { return log, nil },- })- if err != nil {- t.Fatal(err)- }- defer c.Close()-- err = c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: cid,- AgentId: "test-agent",- Inputs: []*proto.Step{harnesstest.UserStep("Hello")},- }, func(resp *proto.CreateInteractionResponse) error { return nil })- if err != nil {- t.Fatal(err)- }-- if h.startCalls != 1 {- t.Errorf("expected 1 Start call, got %d", h.startCalls)- }- if exec.queueCalls != 1 {- t.Errorf("expected 1 Queue call, got %d", exec.queueCalls)- }- if exec.runCalls != 1 {- t.Errorf("expected 1 Run call, got %d", exec.runCalls)- }- })-- // Subtest 2: Pending Execution with NO New Inputs- t.Run("PendingExecutionWithoutNewInputs", func(t *testing.T) {- ctx := context.Background()- cid := "pending-no-inputs"-- log := &eventlogtest.MemoryEventLog{}- // Seed the event log with a pending event- _, err := log.Append(ctx, &proto.StepEvent{- ConversationId: cid,- AgentId: "test-agent",- State: proto.State_STATE_PENDING,- Steps: []*proto.Step{harnesstest.UserStep("Initial")},- })- if err != nil {- t.Fatal(err)- }-- reg := NewRegistry()-- var exec *testExecution- h := &testHarness{- startFunc: func(ctx context.Context, conversationID string) (harness.Execution, error) {- exec = &testExecution{- id: "exec-pending",- runFunc: func(ctx context.Context, execID string, handler harness.Handler) error {- return handler.OnComplete(ctx, execID)- },- }- return exec, nil- },- }- if err := reg.RegisterHarness("test-agent", h); err != nil {- t.Fatal(err)- }-- c, err := New(ctx, Config{- Registry: reg,- EventLogBuilder: func() (eventlog.EventLog, error) { return log, nil },- })- if err != nil {- t.Fatal(err)- }- defer c.Close()-- err = c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: cid,- AgentId: "test-agent",- Inputs: nil, // NO new inputs- }, func(resp *proto.CreateInteractionResponse) error { return nil })- if err != nil {- t.Fatal(err)- }-- if h.startCalls != 1 {- t.Errorf("expected 1 Start call, got %d", h.startCalls)- }- if exec.queueCalls != 0 {- t.Errorf("expected 0 Queue calls, got %d", exec.queueCalls)- }- if exec.runCalls != 1 {- t.Errorf("expected 1 Run call, got %d", exec.runCalls)- }- })-- // Subtest 3: Pending Execution WITH New Inputs- t.Run("PendingExecutionWithNewInputs", func(t *testing.T) {- ctx := context.Background()- cid := "pending-with-inputs"-- log := &eventlogtest.MemoryEventLog{}- // Seed the event log with a pending event- _, err := log.Append(ctx, &proto.StepEvent{- ConversationId: cid,- AgentId: "test-agent",- State: proto.State_STATE_PENDING,- Steps: []*proto.Step{harnesstest.UserStep("Initial")},- })- if err != nil {- t.Fatal(err)- }-- reg := NewRegistry()-- var execs []*testExecution- h := &testHarness{- startFunc: func(ctx context.Context, conversationID string) (harness.Execution, error) {- exec := &testExecution{- id: fmt.Sprintf("exec-%d", len(execs)+1),- runFunc: func(ctx context.Context, execID string, handler harness.Handler) error {- return handler.OnComplete(ctx, execID)- },- }- execs = append(execs, exec)- return exec, nil- },- }- if err := reg.RegisterHarness("test-agent", h); err != nil {- t.Fatal(err)- }-- c, err := New(ctx, Config{- Registry: reg,- EventLogBuilder: func() (eventlog.EventLog, error) { return log, nil },- })- if err != nil {- t.Fatal(err)- }- defer c.Close()-- err = c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: cid,- AgentId: "test-agent",- Inputs: []*proto.Step{harnesstest.UserStep("New input")},- }, func(resp *proto.CreateInteractionResponse) error { return nil })- if err != nil {- t.Fatal(err)- }-- // It should start the harness twice: once for resumption, once for new inputs.- if h.startCalls != 2 {- t.Errorf("expected 2 Start calls, got %d", h.startCalls)- }- if len(execs) != 2 {- t.Fatalf("expected 2 execution sessions, got %d", len(execs))- }-- // The first session (resumption) should NOT have queued inputs and should run.- if execs[0].queueCalls != 0 {- t.Errorf("expected first session to have 0 Queue calls, got %d", execs[0].queueCalls)- }- if execs[0].runCalls != 1 {- t.Errorf("expected first session to have 1 Run call, got %d", execs[0].runCalls)- }-- // The second session (new inputs) should have queued inputs and run.- if execs[1].queueCalls != 1 {- t.Errorf("expected second session to have 1 Queue call, got %d", execs[1].queueCalls)- }- if execs[1].runCalls != 1 {- t.Errorf("expected second session to have 1 Run call, got %d", execs[1].runCalls)- }- })-}--// A conversation started on one harness must resume on that harness when the-// harness id is empty, not fall back to the registry default.-func TestExec_ResumeEmptyHarnessUsesStored(t *testing.T) {- ctx := context.Background()- cid := "resume-empty"- log := &eventlogtest.MemoryEventLog{}- reg := NewRegistry()-- def := &testHarness{startFunc: func(context.Context, string) (harness.Execution, error) {- return &testExecution{}, nil- }}- stored := &testHarness{startFunc: func(context.Context, string) (harness.Execution, error) {- return &testExecution{}, nil- }}- if err := reg.RegisterHarness("harness-a", def); err != nil {- t.Fatal(err)- }- if err := reg.RegisterHarness("harness-b", stored); err != nil {- t.Fatal(err)- }- if err := reg.SetDefaultHarness("harness-a"); err != nil {- t.Fatal(err)- }-- c, err := New(ctx, Config{- Registry: reg,- EventLogBuilder: func() (eventlog.EventLog, error) { return log, nil },- })- if err != nil {- t.Fatal(err)- }- defer c.Close()-- noop := ExecHandler(func(*proto.CreateInteractionResponse) error { return nil })-- // Turn 1: explicitly run the NON-default harness.- if err := c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: cid,- AgentId: "harness-b",- Inputs: []*proto.Step{harnesstest.UserStep("hi")},- }, noop); err != nil {- t.Fatalf("turn 1: %v", err)- }-- // Turn 2: resume WITHOUT a harness id. Must reuse harness-b, not the default.- before := stored.startCalls- if err := c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: cid,- Inputs: []*proto.Step{harnesstest.UserStep("more")},- }, noop); err != nil {- t.Fatalf("turn 2 (resume, empty harness): %v", err)- }- if stored.startCalls <= before {- t.Errorf("stored harness not used on resume (startCalls stayed %d)", stored.startCalls)- }- if def.startCalls != 0 {- t.Errorf("default harness used on resume (startCalls=%d), want the stored harness", def.startCalls)- }-}--// Verifies that an explicit harness change during resume is rejected.-func TestExec_ResumeExplicitDifferentHarnessRejected(t *testing.T) {- ctx := context.Background()- cid := "resume-mismatch"- log := &eventlogtest.MemoryEventLog{}- reg := NewRegistry()- if err := reg.RegisterHarness("harness-a", &testHarness{startFunc: func(context.Context, string) (harness.Execution, error) {- return &testExecution{}, nil- }}); err != nil {- t.Fatal(err)- }- if err := reg.RegisterHarness("harness-b", &testHarness{startFunc: func(context.Context, string) (harness.Execution, error) {- return &testExecution{}, nil- }}); err != nil {- t.Fatal(err)- }-- c, err := New(ctx, Config{- Registry: reg,- EventLogBuilder: func() (eventlog.EventLog, error) { return log, nil },- })- if err != nil {- t.Fatal(err)- }- defer c.Close()-- noop := ExecHandler(func(*proto.CreateInteractionResponse) error { return nil })-- if err := c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: cid,- AgentId: "harness-a",- Inputs: []*proto.Step{harnesstest.UserStep("hi")},- }, noop); err != nil {- t.Fatalf("turn 1: %v", err)- }- err = c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: cid,- AgentId: "harness-b",- Inputs: []*proto.Step{harnesstest.UserStep("more")},- }, noop)- if err == nil || !strings.Contains(err.Error(), "harness ID changed from harness-a to harness-b") {- t.Fatalf("resume with a different harness: got %v, want error 'harness ID changed from harness-a to harness-b'", err)- }-}--// Verifies that a new conversation started without a harness id records the-// default harness's canonical id, not "".-func TestExec_NewConversationLogsCanonicalDefault(t *testing.T) {- ctx := context.Background()- cid := "canonical-log"- log := &eventlogtest.MemoryEventLog{}- reg := NewRegistry()- if err := reg.RegisterHarness("harness-a", &testHarness{startFunc: func(context.Context, string) (harness.Execution, error) {- return &testExecution{}, nil- }}); err != nil {- t.Fatal(err)- }- if err := reg.SetDefaultHarness("harness-a"); err != nil {- t.Fatal(err)- }-- c, err := New(ctx, Config{- Registry: reg,- EventLogBuilder: func() (eventlog.EventLog, error) { return log, nil },- })- if err != nil {- t.Fatal(err)- }- defer c.Close()-- if err := c.Exec(ctx, &proto.CreateInteractionEvent{- ConversationId: cid,- Inputs: []*proto.Step{harnesstest.UserStep("hi")},- }, ExecHandler(func(*proto.CreateInteractionResponse) error { return nil })); err != nil {- t.Fatalf("exec: %v", err)- }- _, stored, err := newLogger(log, cid, "").ResumptionState(ctx)- if err != nil {- t.Fatalf("ResumptionState: %v", err)- }- if stored != "harness-a" {- t.Errorf("logged harness id = %q, want canonical %q (not empty)", stored, "harness-a")- }-}diff --git a/internal/controller/eventlog/eventlog.go b/internal/controller/eventlog/eventlog.godeleted file mode 100644index 0abbd37..0000000--- a/internal/controller/eventlog/eventlog.go+++ /dev/null@@ -1,43 +0,0 @@-// 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 eventlog contains an AX event log.-package eventlog--import (- "context"-- "github.com/google/ax/proto"- "google.golang.org/protobuf/encoding/protojson"-)--// EventLogBuilder builds new event logs.-type EventLogBuilder func() (EventLog, error)--// EventLog is the persistent, append-only record of all actions taken in an-// exec. Every entry is an atomic step: replaying the log in order brings-// the executor back to a consistent state from which execution can resume.-type EventLog interface {- // Append adds a step event to the end of the log.- Append(ctx context.Context, event *proto.StepEvent) (int64, error)-- // Events returns all events for the conversation.- Events(ctx context.Context, conversationID string) ([]*proto.StepEvent, error)-- // Close releases the underlying resources and closes the log.- Close() error-}--var marshalOpts = protojson.MarshalOptions{UseProtoNames: true}-var unmarshalOpts = protojson.UnmarshalOptions{DiscardUnknown: true}diff --git a/internal/controller/eventlog/eventlogtest/eventlog.go b/internal/controller/eventlog/eventlogtest/eventlog.godeleted file mode 100644index 97a7fec..0000000--- a/internal/controller/eventlog/eventlogtest/eventlog.go+++ /dev/null@@ -1,76 +0,0 @@-// 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 eventlogtest--import (- "context"- "sync"-- "github.com/google/ax/proto"-)--// MemoryEventLog is an in-memory EventLog useful for testing and short-lived-// executions. It does not survive process restarts.-type MemoryEventLog struct {- mu sync.Mutex- AllEvents []*proto.StepEvent-}--func (m *MemoryEventLog) Append(_ context.Context, event *proto.StepEvent) (int64, error) {- m.mu.Lock()- defer m.mu.Unlock()-- maxStep := int64(0)- for _, ev := range m.AllEvents {- if ev.ConversationId == event.ConversationId {- maxStep++- }- }- step := maxStep + 1- m.AllEvents = append(m.AllEvents, event)- return step, nil-}--func (m *MemoryEventLog) Events(_ context.Context, conversationID string) ([]*proto.StepEvent, error) {- m.mu.Lock()- defer m.mu.Unlock()-- out := make([]*proto.StepEvent, 0)- for _, ev := range m.AllEvents {- if ev.ConversationId == conversationID {- out = append(out, ev)- }- }- return out, nil-}--// Drop removes every event for which drop returns true.-// It is provided for testing and crash-simulation purposes.-func (m *MemoryEventLog) Drop(drop func(*proto.StepEvent) bool) {- m.mu.Lock()- defer m.mu.Unlock()-- kept := m.AllEvents[:0]- for _, ev := range m.AllEvents {- if !drop(ev) {- kept = append(kept, ev)- }- }- m.AllEvents = kept-}--func (m *MemoryEventLog) Close() error {- return nil-}diff --git a/internal/controller/eventlog/postgres.go b/internal/controller/eventlog/postgres.godeleted file mode 100644index db3b4e5..0000000--- a/internal/controller/eventlog/postgres.go+++ /dev/null@@ -1,57 +0,0 @@-// 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 eventlog--import (- "context"- "database/sql"- "fmt"- "time"-- _ "github.com/jackc/pgx/v5/stdlib"-)--// OpenPostgresEventLog connects to the PostgreSQL database described by dsn and-// initializes the event log schema. Caller is responsible to ensure it is safe-// for concurrent use.-func OpenPostgresEventLog(dsn string) (EventLog, error) {- db, err := sql.Open("pgx", dsn)- if err != nil {- return nil, fmt.Errorf("postgres_eventlog: open: %w", err)- }-- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)- defer cancel()-- if err := db.PingContext(ctx); err != nil {- db.Close()- return nil, fmt.Errorf("postgres_eventlog: ping: %w", err)- }-- // Create tables if they don't exist.- if _, err := db.ExecContext(ctx, `- CREATE TABLE IF NOT EXISTS conversation_log (- conversation_id TEXT NOT NULL,- step INTEGER NOT NULL,- payload TEXT NOT NULL,- PRIMARY KEY (conversation_id, step)- )`); err != nil {- db.Close()- return nil, fmt.Errorf("postgres_eventlog: create conversation_log table: %w", err)- }--- return &sqlEventLog{db: db}, nil-}diff --git a/internal/controller/eventlog/sql.go b/internal/controller/eventlog/sql.godeleted file mode 100644index a8999c8..0000000--- a/internal/controller/eventlog/sql.go+++ /dev/null@@ -1,118 +0,0 @@-// 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 eventlog--import (- "context"- "database/sql"- "fmt"-- "github.com/google/ax/proto"- "go.opentelemetry.io/otel"- "go.opentelemetry.io/otel/attribute"- "go.opentelemetry.io/otel/codes"- "go.opentelemetry.io/otel/trace"-)--// sqlEventLog is a database backed EventLog shared by the SQLite and-// PostgreSQL implementations.-type sqlEventLog struct {- db *sql.DB-}--// Append serializes the event to JSON and inserts it into the database.-func (l *sqlEventLog) Append(ctx context.Context, event *proto.StepEvent) (step int64, err error) {- ctx, endSpan := l.startSpan(ctx, "Append", event.ConversationId)- defer func() { endSpan(err) }()-- tx, err := l.db.BeginTx(ctx, nil)- if err != nil {- return 0, fmt.Errorf("eventlog: begin tx: %w", err)- }- defer tx.Rollback()-- if err := tx.QueryRowContext(ctx, "SELECT COALESCE(MAX(step), 0) + 1 FROM conversation_log WHERE conversation_id = $1", event.ConversationId).Scan(&step); err != nil {- return 0, fmt.Errorf("eventlog: compute step: %w", err)- }-- payload, err := marshalOpts.Marshal(event)- if err != nil {- return 0, fmt.Errorf("eventlog: marshal event: %w", err)- }-- if _, err := tx.ExecContext(ctx,- "INSERT INTO conversation_log (conversation_id, step, payload) VALUES ($1, $2, $3)",- event.ConversationId, step, string(payload)); err != nil {- return 0, fmt.Errorf("eventlog: insert conversation: %w", err)- }-- if err := tx.Commit(); err != nil {- return 0, fmt.Errorf("eventlog: commit: %w", err)- }-- return step, nil-}--// Events retrieves all events from the database for a conversation, ordered by step.-func (l *sqlEventLog) Events(ctx context.Context, conversationID string) (events []*proto.StepEvent, err error) {- ctx, endSpan := l.startSpan(ctx, "Events", conversationID)- defer func() { endSpan(err) }()-- rows, err := l.db.QueryContext(ctx, "SELECT payload FROM conversation_log WHERE conversation_id = $1 ORDER BY step", conversationID)- if err != nil {- return nil, fmt.Errorf("eventlog: query conversation: %w", err)- }- defer rows.Close()-- for rows.Next() {- var payload string- if err := rows.Scan(&payload); err != nil {- return nil, fmt.Errorf("eventlog: scan conversation: %w", err)- }-- ev := &proto.StepEvent{}- if err := unmarshalOpts.Unmarshal([]byte(payload), ev); err != nil {- return nil, fmt.Errorf("eventlog: unmarshal event: %w", err)- }- events = append(events, ev)- }-- if err := rows.Err(); err != nil {- return nil, fmt.Errorf("eventlog: iterate conversation: %w", err)- }-- return events, nil-}--// Close releases the database connection.-func (l *sqlEventLog) Close() error {- return l.db.Close()-}--func (l *sqlEventLog) startSpan(ctx context.Context, name string, conversationID string) (context.Context, func(err error)) {- const tracerName = "eventlog.sql"- tracer := otel.Tracer(tracerName)-- ctx, span := tracer.Start(ctx, tracerName+"/"+name, trace.WithAttributes(- attribute.String("conversation_id", conversationID),- ))- return ctx, func(err error) {- if err != nil {- span.RecordError(err)- span.SetStatus(codes.Error, err.Error())- }- span.End()- }-}diff --git a/internal/controller/eventlog/sql_test.go b/internal/controller/eventlog/sql_test.godeleted file mode 100644index 65c9b43..0000000--- a/internal/controller/eventlog/sql_test.go+++ /dev/null@@ -1,161 +0,0 @@-// 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 eventlog--import (- "context"- "os"- "path/filepath"- "testing"-- "github.com/google/ax/proto"-)--// testEventLog runs the EventLog contract against a backend. newLog returns a-// fresh, empty event log for each subtest, using the subtest's *testing.T for-// temp dirs and cleanup.-//-// Subtests derive their IDs from t.Name() (which includes the backend and-// subtest name) and clear them with DeleteAll before and after running, so they-// are safe against the shared Postgres database and harmless against SQLite's-// per-test file.-func testEventLog(t *testing.T, newLog func(t *testing.T) EventLog) {- t.Run("AppendAndEvents", func(t *testing.T) {- ctx := context.Background()- log := newLog(t)-- conv := t.Name() + "-conv-1"- task1 := t.Name() + "-task-1"- task2 := t.Name() + "-task-2"-- // 1. Conversation log.- cev1 := &proto.StepEvent{ConversationId: conv, InteractionId: task1}- cev2 := &proto.StepEvent{ConversationId: conv, InteractionId: task2}- s1, err := log.Append(ctx, cev1)- if err != nil {- t.Fatalf("failed to append cev1: %v", err)- }- s2, err := log.Append(ctx, cev2)- if err != nil {- t.Fatalf("failed to append cev2: %v", err)- }-- cEvents, err := log.Events(ctx, conv)- if err != nil {- t.Fatalf("failed to read conversation events: %v", err)- }- if len(cEvents) != 2 {- t.Fatalf("expected 2 conversation events, got %d", len(cEvents))- }- if s1 != 1 || s2 != 2 {- t.Errorf("conversation events out of order: %d, %d", s1, s2)- }- if cEvents[0].InteractionId != task1 || cEvents[1].InteractionId != task2 {- t.Errorf("conversation events mismatch: %q, %q", cEvents[0].InteractionId, cEvents[1].InteractionId)- }-- })-- t.Run("Empty", func(t *testing.T) {- ctx := context.Background()- log := newLog(t)-- events, err := log.Events(ctx, t.Name()+"-none")- if err != nil {- t.Fatalf("failed to read events: %v", err)- }- if len(events) != 0 {- t.Fatalf("expected 0 events, got %d", len(events))- }- })-- // AutoStep exercises the step==0 auto-assignment path: appends with Step unset- // receive sequential numbers starting at 1.- t.Run("AutoStep", func(t *testing.T) {- ctx := context.Background()- log := newLog(t)-- conv := t.Name() + "-conv"-- const n = 3- for i := int64(1); i <= n; i++ {- step, err := log.Append(ctx, &proto.StepEvent{ConversationId: conv, InteractionId: "t"})- if err != nil {- t.Fatalf("auto-step append failed: %v", err)- }- if step != i {- t.Errorf("expected step %d, got %d", i, step)- }- }-- events, err := log.Events(ctx, conv)- if err != nil {- t.Fatalf("failed to read events: %v", err)- }- if len(events) != n {- t.Fatalf("expected %d events, got %d", n, len(events))- }- })-}--// TestSQLiteEventLog runs the EventLog contract against the SQLite backend.-func TestSQLiteEventLog(t *testing.T) {- testEventLog(t, func(t *testing.T) EventLog {- t.Helper()- log, err := OpenSQLiteEventLog(filepath.Join(t.TempDir(), "test.db"))- if err != nil {- t.Fatalf("failed to open sqlite event log: %v", err)- }- t.Cleanup(func() { log.Close() })- return log- })-}--// TestPostgresEventLog runs the EventLog contract against the Postgres backend-// described by PG_TEST_DSN, skipping when that variable is not set.-func TestPostgresEventLog(t *testing.T) {- dsn := os.Getenv("PG_TEST_DSN")- if dsn == "" {- t.Skip("PG_TEST_DSN not set; skipping Postgres event log tests")- }- testEventLog(t, func(t *testing.T) EventLog {- t.Helper()- log, err := OpenPostgresEventLog(dsn)- if err != nil {- t.Fatalf("failed to open postgres event log: %v", err)- }- t.Cleanup(func() { log.Close() })- return log- })-}--// TestSQLiteEventLog_CreatesParentDirectory is SQLite-specific: OpenSQLiteEventLog-// must create the database file's parent directory if it does not exist.-func TestSQLiteEventLog_CreatesParentDirectory(t *testing.T) {- dbPath := filepath.Join(t.TempDir(), "newdir", "test.db")-- log, err := OpenSQLiteEventLog(dbPath)- if err != nil {- t.Fatalf("failed to open sqlite event log and create directory: %v", err)- }- defer log.Close()-- if _, err := os.Stat(filepath.Dir(dbPath)); os.IsNotExist(err) {- t.Fatalf("expected parent directory to be created, but it does not exist")- }- if _, err := os.Stat(dbPath); os.IsNotExist(err) {- t.Fatalf("expected database file to be created, but it does not exist")- }-}diff --git a/internal/controller/eventlog/sqlite.go b/internal/controller/eventlog/sqlite.godeleted file mode 100644index ad3f411..0000000--- a/internal/controller/eventlog/sqlite.go+++ /dev/null@@ -1,56 +0,0 @@-// 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 eventlog--import (- "database/sql"- "fmt"- "os"- "path/filepath"- "time"-- _ "modernc.org/sqlite"-)--const sqliteBusyTimeout = 10 * time.Second--// OpenSQLiteEventLog opens (or creates) a SQLite database at path and initializes the event log schema.-func OpenSQLiteEventLog(path string) (EventLog, error) {- dir := filepath.Dir(path)- if err := os.MkdirAll(dir, 0755); err != nil {- return nil, fmt.Errorf("sqlite_eventlog: mkdir %s: %w", dir, err)- }-- dsn := fmt.Sprintf("%s?_pragma=busy_timeout(%d)&_txlock=immediate", path, sqliteBusyTimeout.Milliseconds())- db, err := sql.Open("sqlite", dsn)- if err != nil {- return nil, fmt.Errorf("sqlite_eventlog: open %s: %w", dsn, err)- }-- // Create tables if they don't exist.- if _, err := db.Exec(`- CREATE TABLE IF NOT EXISTS conversation_log (- conversation_id TEXT NOT NULL,- step INTEGER NOT NULL,- payload TEXT NOT NULL,- PRIMARY KEY (conversation_id, step)- )`); err != nil {- db.Close()- return nil, fmt.Errorf("sqlite_eventlog: create conversation_log table: %w", err)- }--- return &sqlEventLog{db: db}, nil-}diff --git a/internal/controller/reconciler.go b/internal/controller/reconciler.gonew file mode 100644index 0000000..31c399b--- /dev/null+++ b/internal/controller/reconciler.go@@ -0,0 +1,480 @@+// 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 controller++import (+ "context"+ "crypto/sha256"+ "errors"+ "fmt"+ "log/slog"+ "net"+ "net/http"+ "os"+ "regexp"+ "sort"+ "strings"+ "time"++ "github.com/google/ax/internal/model"+ "github.com/google/ax/internal/substrate"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/status"+ "google.golang.org/protobuf/types/known/timestamppb"+ "gopkg.in/yaml.v3"+)++const (+ geminiSecretName = "gemini-api-secret"+ geminiSecretKey = "GEMINI_API_KEY"+ // secretLookupTimeout bounds the Kubernetes secret lookup so a slow or+ // unreachable cluster cannot stall reconciliation.+ secretLookupTimeout = 2 * time.Second+ // templateDigestBytes is how many bytes of the spec digest go into a+ // per-task ActorTemplate name.+ templateDigestBytes = 4+ // defaultWorkspaceReadyTimeout is how long Reconcile waits for a freshly+ // resumed actor to finish workspace setup.+ defaultWorkspaceReadyTimeout = 15 * time.Second+ workspaceReadyPollInterval = 500 * time.Millisecond+)++// SecretResolver looks up a key from a Kubernetes secret in the given namespace.+type SecretResolver func(ctx context.Context, namespace, secretName, key string) (string, error)++// TaskReconciler reconciles Task resources by provisioning and orchestrating+// sandboxed Actors on Agent Substrate.+type TaskReconciler struct {+ client *substrate.Client+ httpClient *http.Client+ defaultTemplate string+ defaultTemplateAtespace string++ // SecretResolver resolves the Gemini API key for task containers. It defaults+ // to the Kubernetes secret lookup; tests replace it to avoid touching a cluster.+ SecretResolver SecretResolver++ // WorkspaceReadyTimeout bounds how long Reconcile waits for the actor's workspace+ // to report ready before recording it as still initializing.+ WorkspaceReadyTimeout time.Duration+}++// NewTaskReconciler creates a new TaskReconciler.+func NewTaskReconciler(client *substrate.Client, defaultTemplate, defaultTemplateAtespace string) *TaskReconciler {+ if defaultTemplate == "" {+ defaultTemplate = "default-template"+ }+ if defaultTemplateAtespace == "" {+ defaultTemplateAtespace = "ax-system"+ }+ return &TaskReconciler{+ client: client,+ httpClient: &http.Client{Timeout: 2 * time.Second},+ defaultTemplate: defaultTemplate,+ defaultTemplateAtespace: defaultTemplateAtespace,+ SecretResolver: model.GetKubernetesSecret,+ WorkspaceReadyTimeout: defaultWorkspaceReadyTimeout,+ }+}++// Reconcile handles the reconciliation loop for a single Task.+func (r *TaskReconciler) Reconcile(ctx context.Context, task *v1alpha1.Task, gateway *v1alpha1.Gateway, workspaces ...*v1alpha1.Workspace) (*v1alpha1.Task, error) {+ if task.Metadata == nil {+ task.Metadata = &v1alpha1.ObjectMeta{}+ }+ if task.Status == nil {+ task.Status = &v1alpha1.TaskStatus{}+ }+ atespace := task.Metadata.Atespace+ if atespace == "" {+ atespace = "default"+ }+ task.Metadata.Atespace = atespace++ if task.Spec == nil {+ task.Spec = &v1alpha1.TaskSpec{}+ }+ if task.Spec.Image == "" {+ task.Spec.Image = v1alpha1.DefaultTaskImage+ }++ slog.Info("reconciling task", "name", task.Metadata.Name, "atespace", atespace, "image", task.Spec.Image)++ now := time.Now()++ // 1. Ensure the Atespace exists in Substrate+ if err := r.client.EnsureAtespace(ctx, atespace); err != nil {+ r.setCondition(task, "Ready", "False", "AtespaceCreationFailed", err.Error(), now)+ task.Status.Phase = "Failed"+ return task, fmt.Errorf("ensuring atespace: %w", err)+ }++ // 2. The actor is always named after the task, so the two can be used+ // interchangeably (for example in the router's ate-target-actor header).+ // Whatever a client put in status.actor is overwritten.+ actorName := task.Metadata.Name+ task.Status.Actor = actorName+ if task.Status.Id == "" {+ task.Status.Id = fmt.Sprintf("task-%s-%d", task.Metadata.Name, now.Unix())+ }++ // 3. Ensure Actor exists on Substrate+ templateName := r.defaultTemplate+ templateAtespace := r.defaultTemplateAtespace+ if parts := strings.SplitN(templateName, "/", 2); len(parts) == 2 {+ templateAtespace = parts[0]+ templateName = parts[1]+ }++ // Prepare container environment variables (task env + credentials + specs)+ extraEnv := make(map[string]string)+ if task.Spec != nil {+ for _, e := range task.Spec.Env {+ if e.Name != "" {+ extraEnv[e.Name] = e.Value+ }+ }+ }++ if geminiKey := r.lookupGeminiKey(ctx, atespace); geminiKey != "" {+ extraEnv[geminiSecretKey] = geminiKey+ }++ // Inject Task YAML specification into container environment+ if taskYAML, err := yaml.Marshal(task); err == nil {+ extraEnv["AX_TASK_YAML"] = string(taskYAML)+ }++ // Inject the bound Workspace specs as a multi-document YAML stream.+ if wsYAML, err := marshalWorkspaces(workspaces); err == nil && wsYAML != "" {+ extraEnv["AX_WORKSPACES_YAML"] = wsYAML+ }++ // If a custom image, workspace, or extra environment is specified, provision or use a dedicated ActorTemplate+ if task.Spec != nil && (task.Spec.Image != "" || len(extraEnv) > 0) {+ slog.Info("ensuring custom ActorTemplate for task", "image", task.Spec.Image)+ customTemplateName := taskTemplateName(task.Metadata.Name, task.Spec.Image, extraEnv)++ tmpl, err := r.client.EnsureActorTemplateWithImage(ctx, templateAtespace, templateName, atespace, customTemplateName, task.Spec.Image, extraEnv)+ if err != nil {+ slog.Warn("could not create custom ActorTemplate, falling back to default template", "error", err)+ } else if tmpl != nil && tmpl.Metadata != nil {+ templateAtespace = tmpl.Metadata.Atespace+ templateName = tmpl.Metadata.Name+ slog.Info("using custom ActorTemplate for actor", "templateAtespace", templateAtespace, "templateName", templateName)+ }+ }++ _, err := r.client.EnsureActor(ctx, atespace, actorName, templateAtespace, templateName)+ if err != nil {+ r.setNotReady(task, "ActorCreationFailed", err.Error(), now)+ task.Status.Phase = "Failed"+ return task, fmt.Errorf("ensuring actor: %w", err)+ }++ // 4. Apply Egress Policy to Actor+ var egressAllowlist *v1alpha1.EgressAllowlist+ if gateway != nil && gateway.Spec != nil && gateway.Spec.Egress != nil && gateway.Spec.Egress.Allowlist != nil {+ egressAllowlist = gateway.Spec.Egress.Allowlist+ } else {+ // Default to allow all egress if no explicit gateway restriction is set+ egressAllowlist = &v1alpha1.EgressAllowlist{+ Hosts: []*v1alpha1.HostRule{+ {Host: "*", Port: 443},+ },+ }+ }+ if err := r.client.ApplyEgressPolicy(ctx, atespace, actorName, egressAllowlist); err != nil {+ slog.Warn("could not apply egress policy (continuing)", "actor", actorName, "error", err)+ r.setCondition(task, condGatewayReady, "False", "PolicyApplyFailed", err.Error(), now)+ } else {+ r.setCondition(task, condGatewayReady, "True", "PoliciesApplied", "Network policies active", now)+ }++ // 5. Suspend or Resume the Actor+ if task.Spec != nil && task.Spec.Suspend {+ slog.Info("suspending actor on Substrate", "actor", actorName)+ if err := r.client.SuspendActor(ctx, atespace, actorName); err != nil {+ r.setNotReady(task, "ActorSuspendFailed", err.Error(), now)+ task.Status.Phase = "Failed"+ return task, fmt.Errorf("suspending actor: %w", err)+ }+ task.Status.WorkerIp = ""+ task.Status.Phase = "Suspended"+ r.setCondition(task, condReady, "False", "TaskSuspended", "Task is suspended", now)+ slog.Info("task successfully suspended", "name", task.Metadata.Name, "actor", actorName)+ return task, nil+ }++ // Resume the Actor to activate container execution+ slog.Info("resuming actor on Substrate worker", "actor", actorName)+ _, workerIP, err := r.client.ResumeActor(ctx, atespace, actorName)+ if err != nil {+ r.setNotReady(task, "ActorResumeFailed", err.Error(), now)+ task.Status.Phase = "Failed"+ return task, fmt.Errorf("resuming actor: %w", err)+ }++ task.Status.WorkerIp = workerIP+ task.Status.Phase = "Running"++ // Check if workspace setup inside the actor has completed+ host := workerIP+ port := "80"+ if h, p, err := net.SplitHostPort(workerIP); err == nil {+ host = h+ port = p+ }+ readyURL := fmt.Sprintf("http://%s:%s/readyz?check=workspace", host, port)+ // Workspace setup happens once per task. After it has completed, WorkspaceReady stays+ // True across suspend/resume cycles, so only poll while it is still initializing.+ workspaceReady := r.conditionTrue(task, condWorkspaceReady)+ if workerIP != "" && !workspaceReady {+ // Poll briefly for workspace setup completion+ pollCtx, cancel := context.WithTimeout(ctx, r.WorkspaceReadyTimeout)+ defer cancel()++ ticker := time.NewTicker(workspaceReadyPollInterval)+ defer ticker.Stop()++ checkReady := func() bool {+ // 1. Direct readyz check+ req, _ := http.NewRequestWithContext(pollCtx, http.MethodGet, readyURL, nil)+ if resp, err := r.httpClient.Do(req); err == nil {+ _ = resp.Body.Close()+ if resp.StatusCode == http.StatusOK {+ return true+ }+ }++ // 2. Router-based readyz check (in-cluster via atenet-router)+ if routerAddr := os.Getenv("ATENET_ROUTER_ADDR"); routerAddr != "" {+ rReq, _ := http.NewRequestWithContext(pollCtx, http.MethodGet, fmt.Sprintf("http://%s/readyz?check=workspace", routerAddr), nil)+ if rReq != nil {+ rReq.Header.Set("ate-target-actor", fmt.Sprintf("%s/%s", atespace, actorName))+ if resp, err := r.httpClient.Do(rReq); err == nil {+ _ = resp.Body.Close()+ if resp.StatusCode == http.StatusOK {+ return true+ }+ }+ }+ }+ return false+ }++ // Initial check+ workspaceReady = checkReady()++ for !workspaceReady {+ select {+ case <-pollCtx.Done():+ goto DonePolling+ case <-ticker.C:+ if checkReady() {+ workspaceReady = true+ goto DonePolling+ }+ }+ }+ }+DonePolling:++ // The task is Ready only once its actor is running and the workspace inside it is set up.+ if workspaceReady {+ if !r.conditionTrue(task, condWorkspaceReady) {+ r.setCondition(task, condWorkspaceReady, "True", "SetupComplete", fmt.Sprintf("Workspace setup completed at %s", workerIP), time.Now())+ }+ r.setCondition(task, condReady, "True", "TaskRunning", "Task is running and its workspace is ready", time.Now())+ } else {+ r.setCondition(task, condWorkspaceReady, "False", "Initializing", fmt.Sprintf("Workspace is initializing at %s", workerIP), time.Now())+ r.setCondition(task, condReady, "False", "WorkspaceInitializing", "Waiting for workspace setup to complete", time.Now())+ }++ slog.Info("task successfully reconciled and running",+ "name", task.Metadata.Name,+ "actor", actorName,+ "workerIP", workerIP,+ "workspaceReady", workspaceReady,+ "phase", task.Status.Phase,+ )++ return task, nil+}++// Condition types reported on Task status.+const (+ // condReady reports whether the task as a whole is ready to do work: its actor is+ // running and the workspace inside it has finished setting up.+ condReady = "Ready"+ // condWorkspaceReady reports whether the workspace inside the actor has finished setting up.+ condWorkspaceReady = "WorkspaceReady"+ // condGatewayReady reports whether the gateway's network policies were applied to the actor.+ condGatewayReady = "GatewayReady"+)++// setNotReady marks the task's Ready condition False. WorkspaceReady is left untouched:+// workspace setup is a one-time step whose result outlives actor failures and suspends.+func (r *TaskReconciler) setNotReady(task *v1alpha1.Task, reason, message string, t time.Time) {+ r.setCondition(task, condReady, "False", reason, message, t)+}++// conditionTrue reports whether the task currently has the given condition with status True.+func (r *TaskReconciler) conditionTrue(task *v1alpha1.Task, condType string) bool {+ if task.Status == nil {+ return false+ }+ for _, c := range task.Status.Conditions {+ if c.Type == condType {+ return c.Status == "True"+ }+ }+ return false+}++func (r *TaskReconciler) setCondition(task *v1alpha1.Task, condType, status, reason, message string, t time.Time) {+ ts := timestamppb.New(t)+ for i, c := range task.Status.Conditions {+ if c.Type == condType {+ task.Status.Conditions[i].Status = status+ task.Status.Conditions[i].Reason = reason+ task.Status.Conditions[i].Message = message+ task.Status.Conditions[i].LastTransitionTime = ts+ return+ }+ }+ task.Status.Conditions = append(task.Status.Conditions, &v1alpha1.Condition{+ Type: condType,+ Status: status,+ Reason: reason,+ Message: message,+ LastTransitionTime: ts,+ })+}++// lookupGeminiKey resolves the Gemini API key for the task container, preferring the+// Kubernetes secret in the task's atespace and falling back to the controller's own+// environment. It returns "" when neither source has a value.+func (r *TaskReconciler) lookupGeminiKey(ctx context.Context, atespace string) string {+ if r.SecretResolver != nil {+ lookupCtx, cancel := context.WithTimeout(ctx, secretLookupTimeout)+ defer cancel()+ if key, err := r.SecretResolver(lookupCtx, atespace, geminiSecretName, geminiSecretKey); err == nil && key != "" {+ slog.Info("resolved GEMINI_API_KEY from kubernetes secret for actor template", "atespace", atespace)+ return key+ }+ }+ if key := os.Getenv(geminiSecretKey); key != "" {+ slog.Info("resolved GEMINI_API_KEY from controller environment for actor template")+ return key+ }+ return ""+}++// taskTemplateName derives the per-task ActorTemplate name from the task name and a+// digest of the image and container environment, so a spec change yields a new template.+func taskTemplateName(taskName, image string, env map[string]string) string {+ h := sha256.New()+ h.Write([]byte(image))+ keys := make([]string, 0, len(env))+ for k := range env {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ for _, k := range keys {+ h.Write([]byte(k + "=" + env[k] + ";"))+ }+ return fmt.Sprintf("%s-tmpl-%x", taskName, h.Sum(nil)[:templateDigestBytes])+}++// taskTemplatePattern matches every ActorTemplate name taskTemplateName can produce+// for the given task, across all spec revisions.+func taskTemplatePattern(taskName string) *regexp.Regexp {+ return regexp.MustCompile(fmt.Sprintf("^%s-tmpl-[0-9a-f]{%d}$", regexp.QuoteMeta(taskName), 2*templateDigestBytes))+}++// ReconcileDelete cleans up Substrate resources when a Task is deleted: the actor,+// which shares the task's name, then every ActorTemplate provisioned for the task.+func (r *TaskReconciler) ReconcileDelete(ctx context.Context, atespace, taskName string) error {+ if atespace == "" {+ atespace = "default"+ }+ slog.Info("deleting Substrate actor for task", "atespace", atespace, "task", taskName)+ if err := r.client.DeleteActor(ctx, atespace, taskName); err != nil {+ return err+ }+ if err := r.deleteTaskTemplates(ctx, atespace, taskName); err != nil {+ slog.Warn("could not clean up actor templates for task", "task", taskName, "error", err)+ }+ return nil+}++// deleteTaskTemplates removes all ActorTemplates belonging to the task. Templates+// accumulate across spec revisions, so this matches by name pattern rather than+// recomputing a single digest. If an actor deletion is still finishing in Substrate,+// template deletion may briefly return Aborted, so we retry with backoff.+func (r *TaskReconciler) deleteTaskTemplates(ctx context.Context, atespace, taskName string) error {+ templates, err := r.client.ListActorTemplates(ctx, atespace)+ if err != nil {+ return err+ }+ pattern := taskTemplatePattern(taskName)+ var errs []error+ for _, tmpl := range templates {+ name := tmpl.GetMetadata().GetName()+ if !pattern.MatchString(name) {+ continue+ }+ slog.Info("deleting Substrate actor template for task", "atespace", atespace, "task", taskName, "template", name)+ var delErr error+ for attempt := 0; attempt < 5; attempt++ {+ delErr = r.client.DeleteActorTemplate(ctx, atespace, name)+ if delErr == nil || status.Code(delErr) == codes.NotFound {+ delErr = nil+ break+ }+ select {+ case <-ctx.Done():+ delErr = ctx.Err()+ break+ case <-time.After(500 * time.Millisecond):+ }+ }+ if delErr != nil {+ errs = append(errs, delErr)+ }+ }+ return errors.Join(errs...)+}++// marshalWorkspaces renders the workspaces as a multi-document YAML stream in+// order, skipping nil entries. It returns "" when there is nothing to render.+func marshalWorkspaces(workspaces []*v1alpha1.Workspace) (string, error) {+ var sb strings.Builder+ enc := yaml.NewEncoder(&sb)+ for _, ws := range workspaces {+ if ws == nil {+ continue+ }+ if err := enc.Encode(ws); err != nil {+ return "", err+ }+ }+ if err := enc.Close(); err != nil {+ return "", err+ }+ return sb.String(), nil+}diff --git a/internal/controller/reconciler_test.go b/internal/controller/reconciler_test.gonew file mode 100644index 0000000..e699ee0--- /dev/null+++ b/internal/controller/reconciler_test.go@@ -0,0 +1,456 @@+// 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 controller_test++import (+ "context"+ "net"+ "net/http"+ "testing"+ "time"++ "github.com/agent-substrate/substrate/pkg/proto/ateapipb"+ "github.com/google/ax/internal/controller"+ "github.com/google/ax/internal/substrate"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "google.golang.org/grpc"+ "google.golang.org/grpc/credentials/insecure"+)++type mockControlServer struct {+ ateapipb.UnimplementedControlServer+ workerIP string+ createdAtespaces []string+ createdActors []string+ resumedActors []string+ suspendedActors []string+ createdPolicies []string+ deletedActors []string+ actorTemplates map[string]bool+ deletedTemplates []string+}++// noSecrets is a SecretResolver for tests: it never finds a key and never touches a cluster.+func noSecrets(context.Context, string, string, string) (string, error) {+ return "", nil+}++func (m *mockControlServer) CreateAtespace(ctx context.Context, req *ateapipb.CreateAtespaceRequest) (*ateapipb.Atespace, error) {+ name := ""+ if req.Atespace != nil && req.Atespace.Metadata != nil {+ name = req.Atespace.Metadata.Name+ }+ m.createdAtespaces = append(m.createdAtespaces, name)+ return &ateapipb.Atespace{Metadata: &ateapipb.ResourceMetadata{Name: name}}, nil+}++func (m *mockControlServer) CreateActor(ctx context.Context, req *ateapipb.CreateActorRequest) (*ateapipb.Actor, error) {+ name := ""+ if req.Actor != nil && req.Actor.Metadata != nil {+ name = req.Actor.Metadata.Name+ }+ m.createdActors = append(m.createdActors, name)+ return &ateapipb.Actor{+ Metadata: &ateapipb.ResourceMetadata{Name: name},+ Status: &ateapipb.ActorStatus{+ State: ateapipb.ActorState_ACTOR_STATE_SUSPENDED,+ },+ }, nil+}++func (m *mockControlServer) ResumeActor(ctx context.Context, req *ateapipb.ResumeActorRequest) (*ateapipb.ResumeActorResponse, error) {+ name := ""+ if req.Actor != nil {+ name = req.Actor.Name+ }+ m.resumedActors = append(m.resumedActors, name)+ wIP := "10.244.1.42"+ if m.workerIP != "" {+ wIP = m.workerIP+ }+ return &ateapipb.ResumeActorResponse{+ Actor: &ateapipb.Actor{+ Metadata: &ateapipb.ResourceMetadata{Name: name},+ Status: &ateapipb.ActorStatus{+ State: ateapipb.ActorState_ACTOR_STATE_RUNNING,+ WorkerAssignment: &ateapipb.WorkerAssignment{+ WorkerPod: "worker-pod-1",+ WorkerPodIp: wIP,+ },+ },+ },+ Resumed: true,+ }, nil+}++func (m *mockControlServer) SuspendActor(ctx context.Context, req *ateapipb.SuspendActorRequest) (*ateapipb.SuspendActorResponse, error) {+ name := ""+ if req.Actor != nil {+ name = req.Actor.Name+ }+ m.suspendedActors = append(m.suspendedActors, name)+ return &ateapipb.SuspendActorResponse{}, nil+}++func (m *mockControlServer) CreateActorEgressPolicy(ctx context.Context, req *ateapipb.CreateActorEgressPolicyRequest) (*ateapipb.EgressPolicy, error) {+ actorName := ""+ if req.Actor != nil {+ actorName = req.Actor.Name+ }+ m.createdPolicies = append(m.createdPolicies, actorName)+ return &ateapipb.EgressPolicy{}, nil+}++func (m *mockControlServer) DeleteActor(ctx context.Context, req *ateapipb.DeleteActorRequest) (*ateapipb.Actor, error) {+ name := req.GetActor().GetName()+ m.deletedActors = append(m.deletedActors, name)+ return &ateapipb.Actor{Metadata: &ateapipb.ResourceMetadata{Name: name}}, nil+}++func (m *mockControlServer) ListActorTemplates(ctx context.Context, req *ateapipb.ListActorTemplatesRequest) (*ateapipb.ListActorTemplatesResponse, error) {+ resp := &ateapipb.ListActorTemplatesResponse{}+ for name := range m.actorTemplates {+ resp.ActorTemplates = append(resp.ActorTemplates, &ateapipb.ActorTemplate{+ Metadata: &ateapipb.ResourceMetadata{Name: name, Atespace: req.GetAtespace()},+ })+ }+ return resp, nil+}++func (m *mockControlServer) DeleteActorTemplate(ctx context.Context, req *ateapipb.DeleteActorTemplateRequest) (*ateapipb.ActorTemplate, error) {+ name := req.GetActorTemplate().GetName()+ delete(m.actorTemplates, name)+ m.deletedTemplates = append(m.deletedTemplates, name)+ return &ateapipb.ActorTemplate{Metadata: &ateapipb.ResourceMetadata{Name: name}}, nil+}++func TestTaskReconciler(t *testing.T) {+ ctx := context.Background()++ // 1. Start in-process mock gRPC Substrate server+ lis, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("failed to listen: %v", err)+ }+ defer lis.Close()++ mockSrv := &mockControlServer{}+ grpcServer := grpc.NewServer()+ ateapipb.RegisterControlServer(grpcServer, mockSrv)+ go grpcServer.Serve(lis)+ defer grpcServer.Stop()++ // 2. Initialize Substrate client+ client, err := substrate.NewClient(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ t.Fatalf("failed to create substrate client: %v", err)+ }+ defer client.Close()++ // 3. Reconcile Task+ reconciler := controller.NewTaskReconciler(client, "test-template", "ax-system")+ reconciler.SecretResolver = noSecrets+ reconciler.WorkspaceReadyTimeout = 200 * time.Millisecond++ task := &v1alpha1.Task{+ ApiVersion: v1alpha1.APIVersion,+ Kind: v1alpha1.KindTask,+ Metadata: &v1alpha1.ObjectMeta{+ Name: "test-task",+ Atespace: "default",+ },+ Spec: &v1alpha1.TaskSpec{+ Image: "ghrc.io/my-org/my-image",+ Command: []string{"/bin/task-runner"},+ Gateway: &v1alpha1.GatewayRef{+ Name: "default-gateway",+ },+ },+ // A client-supplied actor name must not survive: the actor is always+ // named after the task.+ Status: &v1alpha1.TaskStatus{Actor: "not-the-task"},+ }++ gateway := &v1alpha1.Gateway{+ Spec: &v1alpha1.GatewaySpec{+ Egress: &v1alpha1.EgressConfig{+ Allowlist: &v1alpha1.EgressAllowlist{+ Hosts: []*v1alpha1.HostRule{+ {Host: "api.anthropic.com", Port: 443},+ {Host: "github.com", Port: 443},+ },+ },+ },+ },+ }++ reconciled, err := reconciler.Reconcile(ctx, task, gateway)+ if err != nil {+ t.Fatalf("Reconcile failed: %v", err)+ }++ // 4. Validate reconciliation results+ if reconciled.Status.Phase != "Running" {+ t.Errorf("expected phase 'Running', got %q", reconciled.Status.Phase)+ }+ if reconciled.Status.Actor != "test-task" {+ t.Errorf("expected actor 'test-task', got %q", reconciled.Status.Actor)+ }+ if reconciled.Status.WorkerIp != "10.244.1.42" {+ t.Errorf("expected worker IP '10.244.1.42', got %q", reconciled.Status.WorkerIp)+ }++ // Verify mock was called+ if len(mockSrv.createdAtespaces) != 1 || mockSrv.createdAtespaces[0] != "default" {+ t.Errorf("expected atespace 'default' created, got %v", mockSrv.createdAtespaces)+ }+ if len(mockSrv.createdActors) != 1 || mockSrv.createdActors[0] != "test-task" {+ t.Errorf("expected actor 'test-task' created, got %v", mockSrv.createdActors)+ }+ if len(mockSrv.resumedActors) != 1 || mockSrv.resumedActors[0] != "test-task" {+ t.Errorf("expected actor 'test-task' resumed, got %v", mockSrv.resumedActors)+ }+ if len(mockSrv.createdPolicies) != 1 || mockSrv.createdPolicies[0] != "test-task" {+ t.Errorf("expected egress policy created for 'test-task', got %v", mockSrv.createdPolicies)+ }+}++func TestTaskReconciler_Suspend(t *testing.T) {+ ctx := context.Background()++ lis, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("failed to listen: %v", err)+ }+ defer lis.Close()++ mockSrv := &mockControlServer{}+ grpcServer := grpc.NewServer()+ ateapipb.RegisterControlServer(grpcServer, mockSrv)+ go grpcServer.Serve(lis)+ defer grpcServer.Stop()++ client, err := substrate.NewClient(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ t.Fatalf("failed to create substrate client: %v", err)+ }+ defer client.Close()++ reconciler := controller.NewTaskReconciler(client, "test-template", "ax-system")+ reconciler.SecretResolver = noSecrets+ reconciler.WorkspaceReadyTimeout = 200 * time.Millisecond++ task := &v1alpha1.Task{+ ApiVersion: v1alpha1.APIVersion,+ Kind: v1alpha1.KindTask,+ Metadata: &v1alpha1.ObjectMeta{+ Name: "suspend-task",+ Atespace: "default",+ },+ Spec: &v1alpha1.TaskSpec{+ Suspend: true,+ Image: "ghrc.io/my-org/my-image",+ },+ }++ reconciled, err := reconciler.Reconcile(ctx, task, nil)+ if err != nil {+ t.Fatalf("Reconcile failed: %v", err)+ }++ if reconciled.Status.Phase != "Suspended" {+ t.Errorf("expected phase 'Suspended', got %q", reconciled.Status.Phase)+ }+ if reconciled.Status.WorkerIp != "" {+ t.Errorf("expected empty worker IP, got %q", reconciled.Status.WorkerIp)+ }+ if len(mockSrv.suspendedActors) != 1 || mockSrv.suspendedActors[0] != "suspend-task" {+ t.Errorf("expected actor 'suspend-task' suspended, got %v", mockSrv.suspendedActors)+ }+}++func TestTaskReconciler_WorkspaceReady(t *testing.T) {+ ctx := context.Background()++ // 1. Mock Substrate Control Server+ lis, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("failed to listen: %v", err)+ }+ defer lis.Close()++ // 2. Mock Worker readyz HTTP server+ httpLis, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("failed to listen http: %v", err)+ }+ defer httpLis.Close()++ httpMux := http.NewServeMux()+ httpMux.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("ok\n"))+ })+ httpServer := &http.Server{Handler: httpMux}+ go httpServer.Serve(httpLis)+ defer httpServer.Close()++ workerHost, workerPortStr, _ := net.SplitHostPort(httpLis.Addr().String())+ // In our mock, the worker IP returned by ResumeActor will have our mock ready server listening.+ // But our reconciler connects to port 9999 by default: fmt.Sprintf("http://%s:9999/readyz", workerIP).+ // If workerIP includes a port or is a host, let's verify how it handles it.+ _ = workerHost+ _ = workerPortStr++ mockSrv := &mockControlServer{}+ grpcServer := grpc.NewServer()+ ateapipb.RegisterControlServer(grpcServer, mockSrv)+ go grpcServer.Serve(lis)+ defer grpcServer.Stop()++ client, err := substrate.NewClient(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ t.Fatalf("failed to create substrate client: %v", err)+ }+ defer client.Close()++ reconciler := controller.NewTaskReconciler(client, "test-template", "ax-system")+ reconciler.SecretResolver = noSecrets+ reconciler.WorkspaceReadyTimeout = 200 * time.Millisecond++ task := &v1alpha1.Task{+ ApiVersion: v1alpha1.APIVersion,+ Kind: v1alpha1.KindTask,+ Metadata: &v1alpha1.ObjectMeta{+ Name: "ready-task",+ Atespace: "default",+ },+ Spec: &v1alpha1.TaskSpec{},+ }++ // Case 1: Worker not responding on readyz -> WorkspaceReady=False and Ready=False.+ reconciled, err := reconciler.Reconcile(ctx, task, nil)+ if err != nil {+ t.Fatalf("Reconcile failed: %v", err)+ }+ assertCondition(t, reconciled, "WorkspaceReady", "False", "Initializing")+ assertCondition(t, reconciled, "Ready", "False", "WorkspaceInitializing")++ // Case 2: Worker readyz endpoint succeeds -> WorkspaceReady=True and Ready=True.+ mockSrv.workerIP = httpLis.Addr().String()+ reconciledReady, err := reconciler.Reconcile(ctx, task, nil)+ if err != nil {+ t.Fatalf("Reconcile with ready worker failed: %v", err)+ }+ assertCondition(t, reconciledReady, "WorkspaceReady", "True", "SetupComplete")+ assertCondition(t, reconciledReady, "Ready", "True", "TaskRunning")++ // Case 3: Suspending the task -> Ready=False (TaskSuspended), but the workspace was+ // already initialized so WorkspaceReady stays True.+ task = reconciledReady+ task.Spec.Suspend = true+ reconciledSuspended, err := reconciler.Reconcile(ctx, task, nil)+ if err != nil {+ t.Fatalf("Reconcile with suspend failed: %v", err)+ }+ if reconciledSuspended.Status.Phase != "Suspended" {+ t.Errorf("expected phase Suspended, got %s", reconciledSuspended.Status.Phase)+ }+ assertCondition(t, reconciledSuspended, "Ready", "False", "TaskSuspended")+ assertCondition(t, reconciledSuspended, "WorkspaceReady", "True", "SetupComplete")++ // Case 4: Resuming with the worker unreachable -> the reconciler trusts the recorded+ // WorkspaceReady instead of re-polling, so the task is Ready again immediately.+ mockSrv.workerIP = "127.0.0.1:1"+ task = reconciledSuspended+ task.Spec.Suspend = false+ reconciledResumed, err := reconciler.Reconcile(ctx, task, nil)+ if err != nil {+ t.Fatalf("Reconcile with resume failed: %v", err)+ }+ assertCondition(t, reconciledResumed, "WorkspaceReady", "True", "SetupComplete")+ assertCondition(t, reconciledResumed, "Ready", "True", "TaskRunning")+}++// assertCondition fails the test unless the task has a condition of the given type with+// the expected status and reason.+func assertCondition(t *testing.T, task *v1alpha1.Task, condType, wantStatus, wantReason string) {+ t.Helper()+ for _, c := range task.Status.Conditions {+ if c.Type != condType {+ continue+ }+ if c.Status != wantStatus || c.Reason != wantReason {+ t.Errorf("expected %s=%s (%s), got Status=%s Reason=%s", condType, wantStatus, wantReason, c.Status, c.Reason)+ }+ return+ }+ t.Errorf("expected %s condition to be set", condType)+}++func TestReconcileDelete_RemovesActorAndTemplates(t *testing.T) {+ ctx := context.Background()++ lis, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("failed to listen: %v", err)+ }+ defer lis.Close()++ mockSrv := &mockControlServer{actorTemplates: map[string]bool{+ "job-tmpl-0a1b2c3d": true, // current revision of task "job"+ "job-tmpl-deadbeef": true, // stale revision of task "job"+ "job-tmpl-deadbeef-tmpl-01234567": true, // belongs to a task literally named "job-tmpl-deadbeef"+ "jobs-tmpl-0a1b2c3d": true, // belongs to task "jobs"+ "default-template": true,+ }}+ grpcServer := grpc.NewServer()+ ateapipb.RegisterControlServer(grpcServer, mockSrv)+ go grpcServer.Serve(lis)+ defer grpcServer.Stop()++ client, err := substrate.NewClient(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ t.Fatalf("failed to create substrate client: %v", err)+ }+ defer client.Close()++ reconciler := controller.NewTaskReconciler(client, "test-template", "ax-system")+ reconciler.SecretResolver = noSecrets+ reconciler.WorkspaceReadyTimeout = 200 * time.Millisecond++ if err := reconciler.ReconcileDelete(ctx, "default", "job"); err != nil {+ t.Fatalf("ReconcileDelete failed: %v", err)+ }++ if len(mockSrv.deletedActors) != 1 || mockSrv.deletedActors[0] != "job" {+ t.Errorf("expected actor 'job' to be deleted, got %v", mockSrv.deletedActors)+ }++ wantDeleted := map[string]bool{"job-tmpl-0a1b2c3d": true, "job-tmpl-deadbeef": true}+ if len(mockSrv.deletedTemplates) != len(wantDeleted) {+ t.Errorf("expected %d templates deleted, got %v", len(wantDeleted), mockSrv.deletedTemplates)+ }+ for _, name := range mockSrv.deletedTemplates {+ if !wantDeleted[name] {+ t.Errorf("unexpected template deleted: %s", name)+ }+ }+ for _, keep := range []string{"job-tmpl-deadbeef-tmpl-01234567", "jobs-tmpl-0a1b2c3d", "default-template"} {+ if !mockSrv.actorTemplates[keep] {+ t.Errorf("template %s should not have been deleted", keep)+ }+ }+}diff --git a/internal/controller/registry.go b/internal/controller/registry.godeleted file mode 100644index 7c1ab57..0000000--- a/internal/controller/registry.go+++ /dev/null@@ -1,79 +0,0 @@-// 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 controller--import (- "fmt"- "sync"-- "github.com/google/ax/internal/harness"-)--// Registry manages a collection of harnesses.-type Registry struct {- mu sync.RWMutex- harnesses map[string]harness.Harness- defaultHarness string-}--// NewRegistry creates a new harness registry.-func NewRegistry() *Registry {- return &Registry{- harnesses: make(map[string]harness.Harness),- }-}--// RegisterHarness registers a harness under the given id.-func (r *Registry) RegisterHarness(id string, h harness.Harness) error {- if err := validateID(id); err != nil {- return err- }-- r.mu.Lock()- defer r.mu.Unlock()-- if _, ok := r.harnesses[id]; ok {- return fmt.Errorf("harness %q already registered", id)- }- r.harnesses[id] = h- return nil-}--// Harness retrieves a harness by id.-func (r *Registry) Harness(id string) (harness.Harness, error) {- r.mu.RLock()- defer r.mu.RUnlock()- h, ok := r.harnesses[id]- if !ok {- return nil, fmt.Errorf("harness %s not found", id)- }- return h, nil-}--// SetDefaultHarness marks a registered harness id as the default.-func (r *Registry) SetDefaultHarness(id string) error {- r.mu.Lock()- defer r.mu.Unlock()- if _, ok := r.harnesses[id]; !ok {- return fmt.Errorf("harness %q not found", id)- }- r.defaultHarness = id- return nil-}--// Close releases resources held by the registry.-func (r *Registry) Close() error {- return nil-}diff --git a/internal/controller/registry_test.go b/internal/controller/registry_test.godeleted file mode 100644index 5b26fe8..0000000--- a/internal/controller/registry_test.go+++ /dev/null@@ -1,87 +0,0 @@-// 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 controller--import (- "context"- "testing"-- "github.com/google/ax/internal/harness"-)--type dummyHarness struct{}--func (d *dummyHarness) Start(ctx context.Context, conversationID string, config []byte) (harness.Execution, error) {- return nil, nil-}--func TestRegistry_RegisterHarness(t *testing.T) {- r := NewRegistry()- h := &dummyHarness{}-- if err := r.RegisterHarness("antigravity", h); err != nil {- t.Fatalf("RegisterHarness(valid id): %v", err)- }-- // Duplicate id is rejected.- if err := r.RegisterHarness("antigravity", h); err == nil {- t.Error("expected error registering duplicate id, got nil")- }-- // Invalid id is rejected.- if err := r.RegisterHarness("bad id", h); err == nil {- t.Error("expected error registering invalid id, got nil")- }-- // Empty id is reserved for the default harness.- if err := r.RegisterHarness("", h); err == nil {- t.Error("expected error registering empty id, got nil")- }-}--func TestRegistry_FindHarness(t *testing.T) {- r := NewRegistry()- h := &dummyHarness{}- if err := r.RegisterHarness("antigravity", h); err != nil {- t.Fatalf("RegisterHarness: %v", err)- }-- if _, err := r.Harness("antigravity"); err != nil {- t.Errorf("Harness(antigravity): %v", err)- }- if _, err := r.Harness("missing"); err == nil {- t.Error("expected error looking up missing harness, got nil")- }-}--func TestRegistry_SetDefaultHarness(t *testing.T) {- r := NewRegistry()- if err := r.RegisterHarness("antigravity", &dummyHarness{}); err != nil {- t.Fatalf("RegisterHarness: %v", err)- }-- // An unregistered id is rejected.- if err := r.SetDefaultHarness("missing"); err == nil {- t.Error("SetDefaultHarness(missing): expected error, got nil")- }-- // A registered id becomes the default.- if err := r.SetDefaultHarness("antigravity"); err != nil {- t.Fatalf("SetDefaultHarness(antigravity): %v", err)- }- if r.defaultHarness != "antigravity" {- t.Errorf("defaultHarness = %q, want %q", r.defaultHarness, "antigravity")- }-}diff --git a/internal/controller/validation.go b/internal/controller/validation.godeleted file mode 100644index 729b243..0000000--- a/internal/controller/validation.go+++ /dev/null@@ -1,36 +0,0 @@-// 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 controller--import (- "errors"- "fmt"- "regexp"-)--var validIDRegex = regexp.MustCompile(`^[A-Za-z0-9\-_]+$`)--// validateID checks if a harness ID contains allowed characters.-func validateID(id string) error {- if id == "" {- return errors.New("empty ID")- }-- if !validIDRegex.MatchString(id) {- return fmt.Errorf("invalid harness ID %q: must only contain A-Z, a-z, 0-9, -, and _", id)- }-- return nil-}diff --git a/internal/controller/validation_test.go b/internal/controller/validation_test.godeleted file mode 100644index 4b1dde1..0000000--- a/internal/controller/validation_test.go+++ /dev/null@@ -1,72 +0,0 @@-// 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 controller--import (- "testing"-)--func TestValidateID(t *testing.T) {- tests := []struct {- name string- id string- wantErr bool- }{- {- name: "valid lowercase",- id: "task123",- wantErr: false,- },- {- name: "valid mixed",- id: "Task-ID_123",- wantErr: false,- },- {- name: "valid simple",- id: "Task-ID",- wantErr: false,- },- {- name: "valid underscore",- id: "task_id",- wantErr: false,- },- {- name: "invalid space",- id: "task id",- wantErr: true,- },- {- name: "invalid char",- id: "task!",- wantErr: true,- },- {- name: "empty",- id: "",- wantErr: true,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- err := validateID(tt.id)- if (err != nil) != tt.wantErr {- t.Errorf("validateID(%q) error = %v, wantErr %v", tt.id, err, tt.wantErr)- }- })- }-}diff --git a/internal/controller/worker.go b/internal/controller/worker.gonew file mode 100644index 0000000..398b090--- /dev/null+++ b/internal/controller/worker.go@@ -0,0 +1,167 @@+// 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 controller++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "os"+ "time"++ "github.com/google/ax/internal/store"+ "github.com/google/ax/pkg/apis/v1alpha1"+)++const (+ defaultWorkerGroup = "ax-controllers"+ // readRetryDelay is how long the worker waits after a transient error from the+ // event queue before trying again.+ readRetryDelay = time.Second+)++// Worker consumes task events from the store's event queue and reconciles each+// task against Substrate. Run several with the same group name to share the load;+// every event is handled by exactly one of them.+type Worker struct {+ store store.Store+ reconciler *TaskReconciler+ group string+ consumer string+}++// NewWorker creates a worker that joins group as consumer. An empty group uses the+// default controller group; an empty consumer derives a unique name from the host.+func NewWorker(s store.Store, reconciler *TaskReconciler, group, consumer string) *Worker {+ if group == "" {+ group = defaultWorkerGroup+ }+ if consumer == "" {+ hostname, _ := os.Hostname()+ consumer = fmt.Sprintf("%s-%d", hostname, time.Now().UnixNano()%10000)+ }+ return &Worker{+ store: s,+ reconciler: reconciler,+ group: group,+ consumer: consumer,+ }+}++// Run subscribes to task events and processes them until ctx is done. It returns+// ctx.Err() on shutdown; every event is acknowledged after processing, even when+// reconciliation fails, so a bad task cannot wedge the queue.+func (w *Worker) Run(ctx context.Context) error {+ slog.Info("starting AX task worker", "group", w.group, "consumer", w.consumer)++ sub, err := w.store.Subscribe(ctx, w.group, w.consumer)+ if err != nil {+ return fmt.Errorf("subscribing to task events: %w", err)+ }+ defer sub.Close()++ for {+ ev, err := sub.Next(ctx)+ if err != nil {+ if ctx.Err() != nil {+ slog.Info("stopping AX task worker")+ return ctx.Err()+ }+ slog.Error("error reading task events", "error", err)+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(readRetryDelay):+ }+ continue+ }++ if err := w.processEvent(ctx, ev); err != nil {+ slog.Error("error processing task event",+ "id", ev.ID,+ "atespace", ev.Atespace,+ "name", ev.Name,+ "action", ev.Action,+ "error", err,+ )+ }+ if err := sub.Ack(ctx, ev); err != nil {+ slog.Warn("failed to acknowledge task event", "id", ev.ID, "error", err)+ }+ }+}++func (w *Worker) processEvent(ctx context.Context, ev store.TaskEvent) error {+ if ev.Action == "delete" {+ slog.Info("handling task deletion event", "atespace", ev.Atespace, "name", ev.Name)+ if err := w.reconciler.ReconcileDelete(ctx, ev.Atespace, ev.Name); err != nil {+ // Leave the record in Terminating so the failure is visible; re-running+ // `ax delete` republishes the event and retries the cleanup.+ return fmt.Errorf("cleaning up task %s/%s: %w", ev.Atespace, ev.Name, err)+ }+ if err := w.store.DeleteTask(ctx, ev.Atespace, ev.Name); err != nil {+ return fmt.Errorf("removing task record %s/%s: %w", ev.Atespace, ev.Name, err)+ }+ return nil+ }++ task, err := w.store.GetTask(ctx, ev.Atespace, ev.Name)+ if err != nil {+ if errors.Is(err, store.ErrNotFound) {+ slog.Info("task not found, skipping reconcile", "atespace", ev.Atespace, "name", ev.Name)+ return nil+ }+ return fmt.Errorf("fetching task %s/%s: %w", ev.Atespace, ev.Name, err)+ }++ var gw *v1alpha1.Gateway+ if task.Spec.Gateway != nil && task.Spec.Gateway.Name != "" {+ g, err := w.store.GetGateway(ctx, task.Metadata.Atespace, task.Spec.Gateway.Name)+ if err == nil {+ gw = g+ } else if !errors.Is(err, store.ErrNotFound) {+ slog.Warn("error fetching gateway", "name", task.Spec.Gateway.Name, "error", err)+ }+ }++ // Resolve every bound workspace. A missing one is skipped so the task still+ // runs; the runner creates an empty directory at its path.+ var workspaces []*v1alpha1.Workspace+ for _, ref := range task.Spec.WorkspaceRefs() {+ if ref.Name == "" {+ continue+ }+ wsp, err := w.store.GetWorkspace(ctx, task.Metadata.Atespace, ref.Name)+ if err == nil {+ workspaces = append(workspaces, wsp)+ } else if !errors.Is(err, store.ErrNotFound) {+ slog.Warn("error fetching workspace", "name", ref.Name, "error", err)+ }+ }++ reconciled, err := w.reconciler.Reconcile(ctx, task, gw, workspaces...)+ if err != nil {+ task.Status.Phase = "Failed"+ _ = w.store.UpdateTaskStatus(ctx, task.Metadata.Atespace, task.Metadata.Name, task.Status)+ return fmt.Errorf("reconciling task %s/%s: %w", task.Metadata.Atespace, task.Metadata.Name, err)+ }++ if err := w.store.UpdateTaskStatus(ctx, task.Metadata.Atespace, task.Metadata.Name, reconciled.Status); err != nil {+ return fmt.Errorf("updating task status %s/%s: %w", task.Metadata.Atespace, task.Metadata.Name, err)+ }++ return nil+}diff --git a/internal/controller/worker_test.go b/internal/controller/worker_test.gonew file mode 100644index 0000000..91acd61--- /dev/null+++ b/internal/controller/worker_test.go@@ -0,0 +1,188 @@+// 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 controller_test++import (+ "context"+ "net"+ "testing"+ "time"++ "github.com/agent-substrate/substrate/pkg/proto/ateapipb"+ "github.com/google/ax/internal/controller"+ "github.com/google/ax/internal/store/memory"+ "github.com/google/ax/internal/substrate"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "google.golang.org/grpc"+ "google.golang.org/grpc/credentials/insecure"+)++func TestWorkerReconciliation(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ // 1. Start in-process mock Substrate server+ lis, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("failed to listen: %v", err)+ }+ defer lis.Close()++ mockSrv := &mockControlServer{}+ grpcServer := grpc.NewServer()+ ateapipb.RegisterControlServer(grpcServer, mockSrv)+ go grpcServer.Serve(lis)+ defer grpcServer.Stop()++ // 2. Substrate client+ subClient, err := substrate.NewClient(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ t.Fatalf("failed to create substrate client: %v", err)+ }+ defer subClient.Close()++ reconciler := controller.NewTaskReconciler(subClient, "default-template", "ax-system")+ reconciler.SecretResolver = noSecrets+ reconciler.WorkspaceReadyTimeout = 200 * time.Millisecond++ // 3. In-memory store+ memStore := memory.NewStore()++ // Pre-create gateway+ _ = memStore.SaveGateway(ctx, &v1alpha1.Gateway{+ Metadata: &v1alpha1.ObjectMeta{Name: "default-gw", Atespace: "default"},+ Spec: &v1alpha1.GatewaySpec{+ Egress: &v1alpha1.EgressConfig{+ Allowlist: &v1alpha1.EgressAllowlist{+ Hosts: []*v1alpha1.HostRule{{Host: "api.openai.com"}},+ },+ },+ },+ })++ // Save task+ task := &v1alpha1.Task{+ Metadata: &v1alpha1.ObjectMeta{Name: "worker-task", Atespace: "default"},+ Spec: &v1alpha1.TaskSpec{+ Gateway: &v1alpha1.GatewayRef{Name: "default-gw"},+ Image: "ghrc.io/test/img",+ },+ }+ if err := memStore.SaveTask(ctx, task); err != nil {+ t.Fatalf("failed to save task: %v", err)+ }++ // 4. Start the worker in the background+ worker := controller.NewWorker(memStore, reconciler, "test-group", "worker-1")+ go func() {+ _ = worker.Run(ctx)+ }()++ // 5. Poll store until task reaches "Running" phase+ deadline := time.Now().Add(3 * time.Second)+ var finalTask *v1alpha1.Task+ for time.Now().Before(deadline) {+ tItem, err := memStore.GetTask(ctx, "default", "worker-task")+ if err == nil && tItem.Status.Phase == "Running" {+ finalTask = tItem+ break+ }+ time.Sleep(50 * time.Millisecond)+ }++ if finalTask == nil {+ t.Fatalf("task did not transition to Running phase in time")+ }++ if finalTask.Status.Actor != "worker-task" {+ t.Errorf("expected actor 'worker-task', got %q", finalTask.Status.Actor)+ }+ if finalTask.Status.WorkerIp != "10.244.1.42" {+ t.Errorf("expected worker IP '10.244.1.42', got %q", finalTask.Status.WorkerIp)+ }+}++func TestWorkerDeletion(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ lis, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("failed to listen: %v", err)+ }+ defer lis.Close()++ mockSrv := &mockControlServer{actorTemplates: map[string]bool{"doomed-tmpl-0a1b2c3d": true}}+ grpcServer := grpc.NewServer()+ ateapipb.RegisterControlServer(grpcServer, mockSrv)+ go grpcServer.Serve(lis)+ defer grpcServer.Stop()++ subClient, err := substrate.NewClient(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ t.Fatalf("failed to create substrate client: %v", err)+ }+ defer subClient.Close()++ reconciler := controller.NewTaskReconciler(subClient, "default-template", "ax-system")+ reconciler.SecretResolver = noSecrets+ reconciler.WorkspaceReadyTimeout = 200 * time.Millisecond++ memStore := memory.NewStore()+ task := &v1alpha1.Task{+ Metadata: &v1alpha1.ObjectMeta{Name: "doomed", Atespace: "default"},+ Spec: &v1alpha1.TaskSpec{Image: "ghcr.io/test/img"},+ Status: &v1alpha1.TaskStatus{Phase: "Running", Actor: "doomed"},+ }+ if err := memStore.SaveTask(ctx, task); err != nil {+ t.Fatalf("failed to save task: %v", err)+ }+ // Drain the reconcile event SaveTask published so only the delete is processed.+ drain, _ := memStore.Subscribe(ctx, "drain", "drain")+ drainCtx, drainCancel := context.WithTimeout(ctx, time.Second)+ _, _ = drain.Next(drainCtx)+ drainCancel()++ if err := memStore.MarkTaskDeleting(ctx, "default", "doomed"); err != nil {+ t.Fatalf("MarkTaskDeleting failed: %v", err)+ }+ marked, err := memStore.GetTask(ctx, "default", "doomed")+ if err != nil {+ t.Fatalf("GetTask after mark failed: %v", err)+ }+ if marked.Status.Phase != v1alpha1.PhaseTerminating {+ t.Fatalf("expected phase Terminating, got %q", marked.Status.Phase)+ }++ worker := controller.NewWorker(memStore, reconciler, "test-group", "worker-1")+ go func() { _ = worker.Run(ctx) }()++ deadline := time.Now().Add(3 * time.Second)+ for time.Now().Before(deadline) {+ if _, err := memStore.GetTask(ctx, "default", "doomed"); err != nil {+ break+ }+ time.Sleep(50 * time.Millisecond)+ }+ if _, err := memStore.GetTask(ctx, "default", "doomed"); err == nil {+ t.Fatalf("expected task record to be removed after cleanup")+ }+ if len(mockSrv.deletedActors) != 1 || mockSrv.deletedActors[0] != "doomed" {+ t.Errorf("expected actor 'doomed' deleted, got %v", mockSrv.deletedActors)+ }+ if len(mockSrv.deletedTemplates) != 1 || mockSrv.deletedTemplates[0] != "doomed-tmpl-0a1b2c3d" {+ t.Errorf("expected template deleted, got %v", mockSrv.deletedTemplates)+ }+}diff --git a/internal/guest/client.go b/internal/guest/client.gonew file mode 100644index 0000000..959e1fe--- /dev/null+++ b/internal/guest/client.go@@ -0,0 +1,152 @@+// 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 guest++import (+ "context"+ "errors"+ "fmt"+ "io"+ "strings"+ "time"++ ateenvv1alpha "github.com/agent-substrate/env/proto/ateenv/v1alpha"+ "google.golang.org/grpc"+ "google.golang.org/grpc/credentials/insecure"+ "google.golang.org/grpc/metadata"+)++// Client interacts with the in-actor guest daemon.+type Client struct {+ grpcConn *grpc.ClientConn+ process ateenvv1alpha.ProcessServiceClient+ filesystem ateenvv1alpha.FileSystemServiceClient+}++// Dial connects to the guest daemon at the specified target (e.g., "127.0.0.1:80").+func Dial(target string) (*Client, error) {+ return DialTarget(target, "")+}++// DialTarget connects to the guest daemon at the specified target, optionally injecting+// the 'ate-target-actor' metadata header on all calls (required when routing via atenet-router).+func DialTarget(target string, targetActor string) (*Client, error) {+ target = strings.TrimPrefix(target, "http://")+ target = strings.TrimPrefix(target, "https://")++ dialOpts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}+ if targetActor != "" {+ dialOpts = append(dialOpts,+ grpc.WithChainUnaryInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {+ ctx = metadata.AppendToOutgoingContext(ctx, "ate-target-actor", targetActor)+ return invoker(ctx, method, req, reply, cc, opts...)+ }),+ grpc.WithChainStreamInterceptor(func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {+ ctx = metadata.AppendToOutgoingContext(ctx, "ate-target-actor", targetActor)+ return streamer(ctx, desc, cc, method, opts...)+ }),+ )+ }++ conn, err := grpc.NewClient(target, dialOpts...)+ if err != nil {+ return nil, fmt.Errorf("connecting to guest at %s: %w", target, err)+ }++ return &Client{+ grpcConn: conn,+ process: ateenvv1alpha.NewProcessServiceClient(conn),+ filesystem: ateenvv1alpha.NewFileSystemServiceClient(conn),+ }, nil+}++// Close terminates the underlying gRPC client connection.+func (c *Client) Close() error {+ if c.grpcConn != nil {+ return c.grpcConn.Close()+ }+ return nil+}++// ExecOptions holds parameters for running a command in the task actor.+type ExecOptions struct {+ Command []string+ Cwd string+ Env map[string]string+ Stdout io.Writer+ Stderr io.Writer+}++// Exec runs a command inside the task container and streams stdout/stderr until completion.+// It returns the process exit code.+func (c *Client) Exec(ctx context.Context, opts ExecOptions) (int, error) {+ if len(opts.Command) == 0 {+ return 1, errors.New("exec: command cannot be empty")+ }++ proc, err := c.process.StartProcess(ctx, &ateenvv1alpha.StartProcessRequest{+ Command: opts.Command,+ Cwd: opts.Cwd,+ Env: opts.Env,+ })+ if err != nil {+ return 1, fmt.Errorf("starting process: %w", err)+ }++ pid := proc.GetProcessId()+ stream, err := c.process.StreamProcessOutput(ctx, &ateenvv1alpha.StreamProcessOutputRequest{+ ProcessId: pid,+ Follow: true,+ })+ if err != nil {+ return 1, fmt.Errorf("streaming process output: %w", err)+ }++ // With Follow set, the stream ends with the final process state.+ for {+ out, err := stream.Recv()+ if errors.Is(err, io.EOF) {+ break+ }+ if err != nil {+ return 1, fmt.Errorf("receiving output stream: %w", err)+ }+ if exit := out.GetExit(); exit != nil {+ return int(exit.GetExitCode()), nil+ }+ if data := out.GetStdout(); len(data) > 0 && opts.Stdout != nil {+ _, _ = opts.Stdout.Write(data)+ }+ if data := out.GetStderr(); len(data) > 0 && opts.Stderr != nil {+ _, _ = opts.Stderr.Write(data)+ }+ }++ // The stream closed without reporting an exit; fall back to polling.+ for {+ proc, err := c.process.GetProcess(ctx, &ateenvv1alpha.GetProcessRequest{ProcessId: pid})+ if err != nil {+ return 1, fmt.Errorf("getting process state: %w", err)+ }+ if proc.GetState() != ateenvv1alpha.ProcessState_PROCESS_STATE_RUNNING {+ return int(proc.GetExitCode()), nil+ }+ select {+ case <-ctx.Done():+ return 1, ctx.Err()+ case <-time.After(50 * time.Millisecond):+ }+ }+}diff --git a/internal/harness/antigravity/antigravity.go b/internal/harness/antigravity/antigravity.godeleted file mode 100644index ab18ee8..0000000--- a/internal/harness/antigravity/antigravity.go+++ /dev/null@@ -1,229 +0,0 @@-// 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 antigravity--import (- "context"- "fmt"- "io"- "net"- "os"- "os/signal"- "path/filepath"- "sync"- "syscall"-- "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"- "go.opentelemetry.io/otel"- "google.golang.org/grpc"- "google.golang.org/grpc/credentials/insecure"-- "github.com/google/ax/internal/config"- "github.com/google/ax/internal/harness"- "github.com/google/ax/internal/pythonsidecar"- "github.com/google/ax/proto"- "github.com/google/ax/python"- "github.com/google/uuid"-)--// Compile-time interface assertions.-var _ harness.Harness = (*AntigravityHarness)(nil)-var _ harness.Execution = (*antigravityExecution)(nil)--// DefaultStateDir returns the default trajectory storage directory,-// ~/.ax/antigravity/conversations. AX owns this path so it stays a harness-// implementation detail rather than a user-facing ax.yaml knob. It lives-// outside the agent's working directory on purpose: the working directory is-// the agent's operating surface (it reads and edits files there), so AX's-// internal state is kept separate to avoid the agent seeing or clobbering it.-func DefaultStateDir() (string, error) {- axDir, err := config.AXAssetsDir()- if err != nil {- return "", err- }- return filepath.Join(axDir, "antigravity", "conversations"), nil-}--// AntigravityHarness implements the Harness interface by connecting to the-// Antigravity Python agent server over gRPC.-type AntigravityHarness struct {- address string- sidecar *pythonsidecar.Sidecar // non-nil when this harness forked the process-}--// New creates a new AntigravityHarness. When autoStart is true, New forks the-// Antigravity Python sidecar and waits for it to become reachable. If-// stateDir is non-empty, it is passed to the sidecar as --state-dir; empty-// stateDir lets the sidecar apply its own default.-func New(ctx context.Context, address, stateDir string, autoStart bool) (*AntigravityHarness, error) {- if address == "" {- address = "127.0.0.1:50053"- }- h := &AntigravityHarness{address: address}- if !autoStart {- return h, nil- }- host, port, err := net.SplitHostPort(address)- if err != nil {- return nil, fmt.Errorf("antigravity: invalid address %q: %w", address, err)- }- args := []string{"--host", host, "--port", port}- if stateDir != "" {- args = append(args, "--state-dir", stateDir)- }- cfg := pythonsidecar.Config{- Module: "python.antigravity.harness_server",- Args: args,- ReadyFunc: pythonsidecar.TCPReady(address),- Address: address,- }- sidecar := pythonsidecar.New(cfg)- path, err := pythonsidecar.Setup(ctx, pythonsidecar.SetupOptions{- FS: python.FS,- })- if err != nil {- return nil, fmt.Errorf("failed to setup antigravity harness server assets: %w", err)- }- if err := sidecar.Start(ctx, path); err != nil {- return nil, fmt.Errorf("failed to start antigravity harness server: %w", err)- }- h.sidecar = sidecar- // Own the sidecar lifecycle here (no registry->controller->antigravity- // teardown chain): on ctrl-C / SIGTERM, stop the Python process- // directly. Mirrors cmd/ax/harness.go.- sigChan := make(chan os.Signal, 1)- signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)- go func() {- <-sigChan- _ = sidecar.Stop()- }()- return h, nil-}--// Stop terminates the underlying Python sidecar process if it was started by this harness.-func (h *AntigravityHarness) Stop() error {- if h.sidecar != nil {- return h.sidecar.Stop()- }- return nil-}--// Start implements Harness.Start.-func (h *AntigravityHarness) Start(ctx context.Context, conversationID string, config []byte) (harness.Execution, error) {- return &antigravityExecution{- harness: h,- conversationID: conversationID,- id: uuid.NewString(),- config: config,- }, nil-}--// antigravityExecution implements the Execution interface.-type antigravityExecution struct {- harness *AntigravityHarness- conversationID string- id string- config []byte-- mu sync.Mutex- queued []*proto.Step- closed bool-}--// ID implements Execution.ID.-func (e *antigravityExecution) ID() string {- return e.id-}--// Queue implements Execution.Queue.-func (e *antigravityExecution) Queue(ctx context.Context, steps ...*proto.Step) error {- e.mu.Lock()- defer e.mu.Unlock()- if e.closed {- return fmt.Errorf("execution session already closed")- }- e.queued = append(e.queued, steps...)- return nil-}--// Run executes the turn over gRPC bidirectional streaming and forwards events to the handler.-func (e *antigravityExecution) Run(ctx context.Context, handler harness.Handler) error {- ctx, span := otel.Tracer("antigravity-harness").Start(ctx, "Run")- defer span.End()-- e.mu.Lock()- if e.closed {- e.mu.Unlock()- return fmt.Errorf("execution session already closed")- }- // Retrieve queued inputs- inputs := e.queued- e.queued = nil- e.mu.Unlock()-- if len(inputs) == 0 {- return fmt.Errorf("no input messages queued for execution turn")- }-- // 1. Connect to the gRPC server- dialOpts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}- dialOpts = append(dialOpts, grpc.WithStatsHandler(otelgrpc.NewClientHandler()))- conn, err := grpc.DialContext(ctx, e.harness.address, dialOpts...)- if err != nil {- return fmt.Errorf("failed to connect to gRPC harness server at %s: %w", e.harness.address, err)- }- defer conn.Close()-- // 2. Create HarnessService client.- client := proto.NewHarnessServiceClient(conn)-- // 3. Build standard HarnessRequest.- start := &proto.HarnessRequest{- ConversationId: e.conversationID,- AgentId: "antigravity",- Type: &proto.HarnessRequest_Start{- Start: &proto.HarnessStart{- AgentConfig: e.config,- Steps: inputs,- },- },- }-- // 4. Call Connect to start bidirectional streaming- stream, err := client.Connect(ctx)- if err != nil {- return fmt.Errorf("failed to call gRPC HarnessService.Connect: %w", err)- }- // A server that fails before reading the start frame makes Send/CloseSend- // report io.EOF; the real status is surfaced by DrainStream's Recv below, so- // only treat non-EOF errors as send failures.- if err := stream.Send(start); err != nil && err != io.EOF {- return fmt.Errorf("failed to send harness start: %w", err)- }- if err := stream.CloseSend(); err != nil && err != io.EOF {- return fmt.Errorf("failed to close stream send direction: %w", err)- }-- // 5. Stream responses and trigger callbacks- return harness.DrainStream(ctx, stream, e.id, handler)-}--// Close implements Execution.Close.-func (e *antigravityExecution) Close(ctx context.Context) error {- e.mu.Lock()- defer e.mu.Unlock()- e.closed = true- return nil-}diff --git a/internal/harness/antigravity/antigravity_test.go b/internal/harness/antigravity/antigravity_test.godeleted file mode 100644index d8f263f..0000000--- a/internal/harness/antigravity/antigravity_test.go+++ /dev/null@@ -1,135 +0,0 @@-// 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 antigravity--import (- "bytes"- "context"- "path/filepath"- "strings"- "testing"-- "github.com/google/ax/internal/harness/harnesstest"- "github.com/google/ax/proto"-)--var antigravityAgentConfig = []byte(`{"system_instructions":"be terse"}`)--func TestRun_AutoStartFalse_ServerOK_Succeeds(t *testing.T) {- srv := &harnesstest.MockHarnessServer{- Outputs: []*proto.Step{harnesstest.ThoughtStep("Analyzing"), harnesstest.AssistantStep("Hello world")},- }- harnessClient, err := New(context.Background(), harnesstest.StartHarnessServer(t, srv), "", false)- if err != nil {- t.Fatalf("New: %v", err)- }-- exec, err := harnessClient.Start(context.Background(), "conv-test", antigravityAgentConfig)- if err != nil {- t.Fatalf("failed to start execution: %v", err)- }- defer exec.Close(context.Background())-- if err := exec.Queue(context.Background(), userStep("Hi")); err != nil {- t.Fatalf("failed to queue message: %v", err)- }-- handler := &harnesstest.MockHandler{}- if err := exec.Run(context.Background(), handler); err != nil {- t.Fatalf("Run failed: %v", err)- }-- if !handler.IsDone() {- t.Error("expected OnComplete to be called")- }- steps := handler.Collected()- if len(steps) != 2 {- t.Fatalf("expected 2 steps, got %d", len(steps))- }- if got := steps[0].GetThought().GetSummary()[0].GetText().GetText(); got != "Analyzing" {- t.Errorf("expected 'Analyzing', got %q", got)- }- if got := steps[1].GetContent().Content[0].GetText().GetText(); got != "Hello world" {- t.Errorf("expected 'Hello world', got %q", got)- }- // The harness propagated the conversation id and config to the server.- convID, _, agentConfig, _ := srv.Received()- if convID != "conv-test" {- t.Errorf("server got convID=%q, want conv-test", convID)- }- if !bytes.Equal(agentConfig, antigravityAgentConfig) {- t.Errorf("server got agentConfig=%q, want %q", agentConfig, antigravityAgentConfig)- }-}--func TestRun_AutoStartFalse_ServerErrorFrame_Fails(t *testing.T) {- srv := &harnesstest.MockHarnessServer{FailConnect: true, ErrMessage: "internal mock server crash"}- harnessClient, err := New(context.Background(), harnesstest.StartHarnessServer(t, srv), "", false)- if err != nil {- t.Fatalf("New: %v", err)- }-- exec, _ := harnessClient.Start(context.Background(), "conv-test", antigravityAgentConfig)- defer exec.Close(context.Background())-- if err := exec.Queue(context.Background(), userStep("Hi")); err != nil {- t.Fatalf("failed to queue message: %v", err)- }-- err = exec.Run(context.Background(), &harnesstest.MockHandler{})- if err == nil {- t.Fatal("expected error from Run(), got nil")- }- if !strings.Contains(err.Error(), "internal mock server crash") {- t.Errorf("unexpected error message: %v", err)- }-}--// TestNew_AutoStartFalse_NilSidecar: autoStart=false leaves sidecar nil.-func TestNew_AutoStartFalse_NilSidecar(t *testing.T) {- h, err := New(context.Background(), "127.0.0.1:1", "", false)- if err != nil {- t.Fatalf("New: %v", err)- }- if h.sidecar != nil {- t.Errorf("expected sidecar to be nil, got %v", h.sidecar)- }-}--// TestDefaultStateDir returns ~/.ax/antigravity/conversations under the user's-// home directory.-func TestDefaultStateDir(t *testing.T) {- home := t.TempDir()- t.Setenv("HOME", home)-- got, err := DefaultStateDir()- if err != nil {- t.Fatalf("DefaultStateDir: %v", err)- }- if want := filepath.Join(home, ".ax", "antigravity", "conversations"); got != want {- t.Errorf("DefaultStateDir() = %q, want %q", got, want)- }-}--func userStep(text string) *proto.Step {- return &proto.Step{- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Role: "user",- Content: []*proto.Content{{Type: &proto.Content_Text{Text: &proto.TextContent{Text: text}}}},- },- },- }-}diff --git a/internal/harness/antigravityinteractions/antigravityinteractions.go b/internal/harness/antigravityinteractions/antigravityinteractions.godeleted file mode 100644index fef8da2..0000000--- a/internal/harness/antigravityinteractions/antigravityinteractions.go+++ /dev/null@@ -1,993 +0,0 @@-// 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 antigravityinteractions--// AntigravityInteractionsHarness drives an Antigravity agent through the Vertex-// GenAI Interactions API over HTTPS + Server-Sent Events, using the steps-based-// ("step_list") request format. It implements the Harness interface for the-// client-side ("local") environment: the agent runs server-side as the brain-// while the harness, on the client, drives the turn loop and executes every tool-// the agent yields.-//-// Tool execution (all internal to the harness):-//-// - Built-in environment tools (view_file, run_command, list_dir, ...) are-// executed against the local filesystem/shell.-// - Third-party / MCP tools are executed via a ThirdPartyExecutor, the seam-// through which the controller injects the caller's tool implementations. If-// 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 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 "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"- "path/filepath"- "sort"- "strconv"- "strings"- "sync"- "time"-- "github.com/google/ax/internal/config"- "github.com/google/ax/internal/harness"- "github.com/google/ax/proto"- "github.com/google/uuid"- "golang.org/x/oauth2"- "golang.org/x/oauth2/google"-)--const (- // interactionsEndpoint is the public Vertex GenAI dataplane endpoint.- interactionsEndpoint = "https://aiplatform.googleapis.com"- // interactionsAPIVersion is the Interactions API version this harness targets.- interactionsAPIVersion = "v1beta1"- // cloudPlatformScope is the OAuth2 scope required to call Vertex AI.- cloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"-- // Cloud project and location are read from these standard environment- // variables (see https://github.com/google/ax#authentication).- envCloudProject = "GOOGLE_CLOUD_PROJECT"- envCloudLocation = "GOOGLE_CLOUD_LOCATION"- // defaultLocation is used when GOOGLE_CLOUD_LOCATION is unset.- defaultLocation = "global"-- // DefaultAgent is the Interactions API agent used when the harness is- // registered without an explicit agent override.- DefaultAgent = "antigravity-preview-05-2026"-)--// Compile-time interface assertions.-var _ harness.Harness = (*AntigravityInteractionsHarness)(nil)-var _ harness.Execution = (*antigravityInteractionsExecution)(nil)--// AntigravityInteractionsConfig configures an AntigravityInteractionsHarness.-// Use New, which fills sensible defaults.-//-// Cloud project and location come from the standard GOOGLE_CLOUD_PROJECT and-// GOOGLE_CLOUD_LOCATION environment variables.-type AntigravityInteractionsConfig struct {- // --- Required ----- // Agent is the Interactions API agent name to run. Required: the API rejects a- // request with no agent.- Agent string-- // StateDir is the directory where each conversation's resume cursor is- // persisted, so a conversation can resume after a restart. Required: New- // 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-- // --- Optional ----- // WorkDir is the working directory the agent operates in. When set, it is the- // authoritative base for built-in env tools: run_command executes there (and- // resolves a relative Cwd against it). This makes tool execution independent- // of the process's ambient cwd. Empty means "use the process cwd" (the- // previous behavior). Defaults from AX_HARNESS_WORKDIR.- WorkDir 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 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.- MaxTurns int- // Debug, if true, logs concise per-conversation tool activity to stderr: a- // line for each function call (FC) the agent yields and each function result- // (FR) the harness produces. Useful for observing the FC/FR exchange that is- // otherwise internal to the harness.- Debug bool- // ThirdPartyExecutor executes third-party (non-built-in) function tool calls- // and declares them to the agent. It is the seam for the controller to inject- // the caller's tool implementations. If nil, the harness advertises no- // third-party tools and any non-built-in call the agent attempts yields an- // error result.- ThirdPartyExecutor ThirdPartyExecutor- // TokenSource overrides how the bearer token is obtained. If nil, the harness- // builds an auto-refreshing source from Application Default Credentials.- TokenSource oauth2.TokenSource-}--func (c *AntigravityInteractionsConfig) withDefaults() {- if c.MaxTurns == 0 {- c.MaxTurns = 100- }- if c.WorkDir == "" {- c.WorkDir = os.Getenv("AX_HARNESS_WORKDIR")- }-}--// cloudProject returns the Cloud project id from GOOGLE_CLOUD_PROJECT.-func cloudProject() string {- return os.Getenv(envCloudProject)-}--// cloudLocation returns the Cloud location from GOOGLE_CLOUD_LOCATION, falling-// back to the default ("global").-func cloudLocation() string {- if loc := os.Getenv(envCloudLocation); loc != "" {- return loc- }- return defaultLocation-}--// DefaultStateDir returns the default resume-cursor directory,-// <AXAssetsDir>/antigravityinteractions/cursors, used when a caller does not set-// StateDir explicitly. Locally that is ~/.ax/...; on a substrate actor-// AX_DURABLE_DIR points AXAssetsDir at a durable volume (e.g. /durable/.ax), kept-// outside the agent's working directory so the agent does not see or modify it.-// New still requires a non-empty StateDir; callers apply this default.-func DefaultStateDir() (string, error) {- axDir, err := config.AXAssetsDir()- if err != nil {- return "", err- }- return filepath.Join(axDir, "antigravityinteractions", "cursors"), nil-}--// AntigravityInteractionsHarness implements Harness by talking to the public-// Vertex GenAI Interactions API.-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.- tsOnce sync.Once- ts oauth2.TokenSource- tsErr error-}--// New creates a harness from the given config, 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 New(cfg AntigravityInteractionsConfig) (*AntigravityInteractionsHarness, error) {- return newWithHTTPClient(cfg, nil)-}--// newWithHTTPClient is New with an injectable HTTP client. If hc is nil it builds-// the default client. It exists so tests can inject a fake transport; the public-// config intentionally does not expose an HTTP client override.-func newWithHTTPClient(cfg AntigravityInteractionsConfig, hc *http.Client) (*AntigravityInteractionsHarness, error) {- cfg.withDefaults()- if hc == nil {- // Disable HTTP keep-alives so no TCP/TLS connection is reused across- // requests. On substrate the actor is suspended after a turn and resumed- // for the next (with a new routable IP), which leaves any pooled keep-alive- // connection stale; reusing it makes the next turn's request fail. Opening a- // fresh connection per request avoids that at the cost of an extra handshake.- //- // Clone DefaultTransport (rather than a bare &http.Transport{}) so we inherit- // its production defaults -- proxy from the environment, dial/TLS/handshake- // timeouts, and HTTP/2 -- and only override keep-alives.- tr := http.DefaultTransport.(*http.Transport).Clone()- tr.DisableKeepAlives = true- hc = &http.Client{Timeout: 10 * time.Minute, Transport: tr}- }- 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. 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, config []byte) (harness.Execution, error) {- e := &antigravityInteractionsExecution{- harness: h,- conversationID: conversationID,- id: uuid.NewString(),- config: config,- }-- 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-// across Run calls and owns the interaction chain (prevInteractionID). Queue-// may be called concurrently with Run to inject steering input, which is-// drained at each interaction gap.-type antigravityInteractionsExecution struct {- harness *AntigravityInteractionsHarness- conversationID string- id string- config []byte-- mu sync.Mutex- queued []*proto.Step- closed bool-- // 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-}--// ID implements Execution.ID.-func (e *antigravityInteractionsExecution) ID() string { return e.id }--// Queue implements Execution.Queue. It carries human input only: the initial-// prompt, or steering messages injected mid-run. Tool results are NOT queued by-// the caller -- the harness executes all tools itself. Queued messages are-// drained at the next interaction gap within Run.-func (e *antigravityInteractionsExecution) Queue(ctx context.Context, steps ...*proto.Step) error {- e.mu.Lock()- defer e.mu.Unlock()- if e.closed {- return fmt.Errorf("execution session already closed")- }- e.queued = append(e.queued, steps...)- return nil-}--// Close implements Execution.Close.-func (e *antigravityInteractionsExecution) Close(ctx context.Context) error {- e.mu.Lock()- defer e.mu.Unlock()- e.closed = true- return nil-}--// drainQueue removes and returns any queued human input, converting it to-// user_input steps. Called at each interaction gap so newly-queued steering-// messages are folded into the next interaction.-func (e *antigravityInteractionsExecution) drainQueue() []any {- e.mu.Lock()- steps := e.queued- e.queued = nil- e.mu.Unlock()- return stepsToInputSteps(steps)-}--// 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 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,-// executing every tool the agent yields internally (built-in env tools locally,-// third-party tools via the configured executor) and resuming until the agent-// produces a final answer (a turn with no tool calls) or the turn cap is hit.-//-// The agent's text output is forwarded via handler.OnMessage; handler.OnComplete-// is called once when the conversation finishes. At each interaction gap, any-// human input queued via Queue (steering) is folded into the next turn.-func (e *antigravityInteractionsExecution) Run(ctx context.Context, handler harness.Handler) error {- e.mu.Lock()- if e.closed {- e.mu.Unlock()- return fmt.Errorf("execution session already closed")- }- prevID := e.prevInteractionID- e.mu.Unlock()-- token, err := e.harness.token(ctx)- if err != nil {- return fmt.Errorf("obtaining access token: %w", err)- }-- // Initial input for this Run: drain whatever is queued (the prompt on the- // 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 len(input) == 0 {- if prevID == "" {- return fmt.Errorf("no input messages queued for the initial turn")- }- return fmt.Errorf("Run called with no queued input and no work pending")- }-- // Set the working directory for this execution. Substrate resets the- // process cwd to the OCI spec's root directory, "/" after gVisor- // restore. We need to explicitly set it for each execution.- if workDir := os.Getenv("AX_HARNESS_WORKDIR"); workDir != "" {- if err := os.Chdir(workDir); err != nil {- return fmt.Errorf("set working directory %q: %w", workDir, err)- }- }-- res, err := e.harness.postTurn(ctx, token, e.harness.newRequest(input, prevID))- if err != nil {- return fmt.Errorf("interaction turn failed: %w", err)- }- prevID = res.interactionID- 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))- if err := emitText(ctx, handler, e.id, res.modelText); err != nil {- return err- }-- // Execute every tool the agent yielded (built-in env tools and- // third-party tools alike are executed internally) and collect the- // results to send back.- var next []any- for i, call := range res.toolCalls {- e.harness.debugCall(e.conversationID, i+1, len(res.toolCalls), call)- out := e.harness.executeTool(ctx, call)- e.harness.debugResult(e.conversationID, call.name, out)- next = append(next, toolResultStep{- Type: "function_result",- CallID: call.callID,- Name: call.name,- Result: out,- })- }-- // Fold in any human input queued (steering) since the last gap.- next = append(next, e.drainQueue()...)-- // If the agent yielded no tool calls and there is no queued input to send,- // the conversation is complete.- if len(next) == 0 {- return handler.OnComplete(ctx, e.id)- }-- res, err = e.harness.postTurn(ctx, token, e.harness.newRequest(next, prevID))- if err != nil {- return fmt.Errorf("continuation turn failed: %w", err)- }- prevID = res.interactionID- if err := e.setPrevID(ctx, prevID); err != nil {- return err- }- }-- // Hit the turn cap while still driving tools.- return handler.OnComplete(ctx, e.id)-}--// emitText forwards non-empty model text to the handler as a Step.-func emitText(ctx context.Context, handler harness.Handler, execID, text string) error {- if strings.TrimSpace(text) == "" {- return nil- }- return handler.OnMessage(ctx, execID, &proto.Step{- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Role: "assistant",- Content: []*proto.Content{- {Type: &proto.Content_Text{Text: &proto.TextContent{Text: text}}},- },- },- },- })-}--// stepsToInputSteps converts queued ax Steps (human input) into user_input-// steps. Only text content is supported as input today.-func stepsToInputSteps(steps []*proto.Step) []any {- var out []any- for _, s := range steps {- if contentStep := s.GetContent(); contentStep != nil {- for _, part := range contentStep.Content {- if t, ok := part.GetType().(*proto.Content_Text); ok && t.Text.GetText() != "" {- out = append(out, userInputStep{- Type: "user_input",- Content: []textPart{{Type: "text", Text: t.Text.GetText()}},- })- }- }- }- }- return out-}--// ----------------------------------------------------------------------------// Wire types and helpers (steps-based Interactions API).-// -----------------------------------------------------------------------------// textPart is a single Content part within a user_input step.-type textPart struct {- Type string `json:"type"`- Text string `json:"text"`-}--// userInputStep is the steps-based representation of a user prompt.-type userInputStep struct {- Type string `json:"type"` // "user_input"- Content []textPart `json:"content"`-}--// 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 {- Type string `json:"type"` // "function_result"- CallID string `json:"call_id"`- Name string `json:"name"`- Result any `json:"result"`-}--// FunctionTool is a client-declared function tool declaration. It is the element-// type a ThirdPartyExecutor returns from Declarations.-type FunctionTool struct {- Type string `json:"type"` // "function"- Name string `json:"name"`- Desc string `json:"description,omitempty"`- Params any `json:"parameters,omitempty"`-}--// environmentConfig is the JSON shape of the Interaction.environment oneof. This-// harness always uses {"type":"local"} (the client-side environment).-type environmentConfig struct {- Type string `json:"type"`-}--type interactionRequest struct {- Stream bool `json:"stream"`- Background bool `json:"background"`- Store bool `json:"store"`- Agent string `json:"agent"`- SystemInstruction string `json:"system_instruction,omitempty"`- Environment *environmentConfig `json:"environment,omitempty"`- PreviousInteractionID string `json:"previous_interaction_id,omitempty"`- Input []any `json:"input,omitempty"`- Tools []FunctionTool `json:"tools,omitempty"`-}--// capturedToolCall is a tool call the agent yielded during a turn.-type capturedToolCall struct {- callID string- name string- arguments map[string]any-}--// turnResult is what we extracted from streaming one turn.-type turnResult struct {- interactionID string- toolCalls []capturedToolCall- modelText string-}--// Debug output layout. When Debug is enabled, each Run turn is logged as a-// hierarchical block so the function-call / function-result (FC/FR) exchange is-// easy to follow:-//-// [harness:e2e-conv] ==== turn 1 (2 function calls) ============-// [harness:e2e-conv] FC 1/2 list_dir-// [harness:e2e-conv] DirectoryPath: .-// [harness:e2e-conv] explanation: Listing the current directory.-// [harness:e2e-conv] FR list_dir-// [harness:e2e-conv] results: [...]-// [harness:e2e-conv] FC 2/2 run_command-// [harness:e2e-conv] CommandLine: pwd-// [harness:e2e-conv] FR run_command-// [harness:e2e-conv] ExitCode: 0-// [harness:e2e-conv] Output: /home/user/project-const (- debugIndentCall = " " // FC / FR lines, under the turn header- debugIndentDetail = " " // params and result values, under FC / FR-)--// debugln writes a single debug line (prefixed with the conversation id) to-// stderr when Debug is enabled.-func (h *AntigravityInteractionsHarness) debugln(conversationID, line string) {- if !h.cfg.Debug {- return- }- fmt.Fprintf(os.Stderr, "[harness:%s] %s\n", conversationID, line)-}--// debugTurn logs the separator header that begins a turn.-func (h *AntigravityInteractionsHarness) debugTurn(conversationID string, turn, numCalls int) {- if !h.cfg.Debug {- return- }- plural := "s"- if numCalls == 1 {- plural = ""- }- header := fmt.Sprintf("==== turn %d (%d function call%s) ", turn, numCalls, plural)- // Pad the header with '=' to a fixed width for an easy visual break.- if pad := 56 - len(header); pad > 0 {- header += strings.Repeat("=", pad)- }- h.debugln(conversationID, header)-}--// debugCall logs a function call (FC): a header line plus one indented line per-// argument (keys sorted for stable output).-func (h *AntigravityInteractionsHarness) debugCall(conversationID string, idx, total int, call capturedToolCall) {- if !h.cfg.Debug {- return- }- h.debugln(conversationID, fmt.Sprintf("%sFC %d/%d %s", debugIndentCall, idx, total, call.name))- h.debugKeyValues(conversationID, call.arguments)-}--// debugResult logs a function result (FR): a header line plus the indented-// result value(s).-func (h *AntigravityInteractionsHarness) debugResult(conversationID, name string, result any) {- if !h.cfg.Debug {- return- }- h.debugln(conversationID, fmt.Sprintf("%sFR %s", debugIndentCall, name))- if m, ok := result.(map[string]any); ok {- h.debugKeyValues(conversationID, m)- return- }- h.debugln(conversationID, debugIndentDetail+debugTruncate(fmt.Sprintf("%v", result)))-}--// debugKeyValues logs a map as one "key: value" line per entry, indented under-// an FC/FR header, with keys sorted for stable output.-func (h *AntigravityInteractionsHarness) debugKeyValues(conversationID string, m map[string]any) {- keys := make([]string, 0, len(m))- for k := range m {- keys = append(keys, k)- }- sort.Strings(keys)- for _, k := range keys {- h.debugln(conversationID, fmt.Sprintf("%s%s: %s", debugIndentDetail, k, debugTruncate(fmt.Sprintf("%v", m[k]))))- }-}--// debugTruncate collapses newlines and caps very long values so a single debug-// line stays readable.-func debugTruncate(s string) string {- s = strings.ReplaceAll(s, "\n", "\\n")- const max = 200- if len(s) > max {- return s[:max] + "…"- }- return s-}--func (h *AntigravityInteractionsHarness) interactionsURL() string {- return fmt.Sprintf("%s/%s/projects/%s/locations/%s/interactions",- 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) {- h.tsOnce.Do(func() {- if h.cfg.TokenSource != nil {- h.ts = h.cfg.TokenSource- return- }- h.ts, h.tsErr = newTokenSource(ctx)- })- if h.tsErr != nil {- return "", h.tsErr- }- tok, err := h.ts.Token()- if err != nil {- return "", fmt.Errorf("obtaining access token: %w", err)- }- return tok.AccessToken, nil-}--// newTokenSource builds an auto-refreshing OAuth2 token source for Vertex AI-// from Application Default Credentials.-func newTokenSource(ctx context.Context) (oauth2.TokenSource, error) {- creds, err := google.FindDefaultCredentials(ctx, cloudPlatformScope)- if err != nil {- return nil, fmt.Errorf("finding application default credentials: %w", err)- }- return creds.TokenSource, nil-}--// 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 the turns of the interaction loop.-func (h *AntigravityInteractionsHarness) newRequest(input []any, previousID string) interactionRequest {- var tools []FunctionTool- if h.cfg.ThirdPartyExecutor != nil {- tools = h.cfg.ThirdPartyExecutor.Declarations()- }- return interactionRequest{- Stream: true,- Background: true,- Store: true,- Agent: h.cfg.Agent,- SystemInstruction: h.cfg.SystemInstruction,- Environment: &environmentConfig{Type: "local"},- PreviousInteractionID: previousID,- Input: input,- Tools: tools,- }-}--// 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- }- httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, h.interactionsURL(), bytes.NewReader(body))- if err != nil {- return nil, err- }- httpReq.Header.Set("Authorization", "Bearer "+token)- httpReq.Header.Set("Content-Type", "application/json")- httpReq.Header.Set("X-Goog-User-Project", cloudProject())-- resp, err := h.httpClient.Do(httpReq)- if err != nil {- return nil, err- }- defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- b := new(bytes.Buffer)- if _, err := b.ReadFrom(resp.Body); err != nil {- return nil, fmt.Errorf("HTTP %d (failed to read error body: %v)", resp.StatusCode, err)- }- 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)-}--// serverErrorMessage extracts a human-readable message from an SSE "error"-// event. The error payload is an object with a "message" field (and often a-// "status"/"code"); e.g. {"error":{"message":"...","status":"INVALID_ARGUMENT"}}.-// Falls back to a generic string when the shape is unexpected so the caller-// always gets a non-empty error.-func serverErrorMessage(event map[string]any) string {- errObj, ok := event["error"].(map[string]any)- if !ok {- return "unknown server error"- }- msg, _ := errObj["message"].(string)- status, _ := errObj["status"].(string)- switch {- case msg != "" && status != "":- return fmt.Sprintf("%s (%s)", msg, status)- case msg != "":- return msg- case status != "":- return status- default:- return "unknown server error"- }-}--// parseStreamedTurn parses the event:/data: Server-Sent Events stream for one-// interaction turn and extracts the tool calls the agent yielded and the model's-// text output.-//-// Function-call streaming works per step index: a step.start announces the call-// (id, name, sometimes inline arguments), then step.delta "arguments_delta"-// events carry the arguments as a JSON STRING. The server re-emits the SAME call-// (same id) at several consecutive indices while it streams, and each emission-// carries the COMPLETE arguments JSON (a snapshot, not an incremental fragment).-// So we track state per step index, always REPLACING the latest arguments-// snapshot, then dedupe by id at the end -- concatenating snapshots would-// corrupt the JSON.-func (h *AntigravityInteractionsHarness) parseStreamedTurn(body io.Reader) (*turnResult, error) {- turn := &turnResult{}-- // pendingCall accumulates one function call as it streams in.- type pendingCall struct {- id string- name string- argsJSON string // latest complete arguments JSON snapshot- args map[string]any // inline arguments, if provided directly- }- callsByStepIndex := map[int]*pendingCall{}- var stepIndexOrder []int-- scanner := bufio.NewScanner(body)- scanner.Buffer(make([]byte, 64*1024), 64*1024*1024)- for scanner.Scan() {- line := scanner.Text()- if !strings.HasPrefix(line, "data:") {- continue- }- eventJSON := strings.TrimSpace(strings.TrimPrefix(line, "data:"))- if eventJSON == "[DONE]" {- break- }- var event map[string]any- if err := json.Unmarshal([]byte(eventJSON), &event); err != nil {- continue- }- switch event["event_type"] {- case "error":- // The server reports a turn-level failure (e.g. INVALID_ARGUMENT for a- // malformed client tool result) as an SSE "error" event. Surface it as- // a real error so the caller aborts the turn instead of treating the- // stream as a completed-but-empty turn. Silently dropping it made an- // empty directory listing look like a blank "no response, seq=0" turn- // AND caused the failing turn's interaction id to be persisted as a- // poisoned resume cursor.- return nil, fmt.Errorf(- "antigravity interactions: server error event: %s",- serverErrorMessage(event),- )-- case "interaction.created", "interaction.completed", "interaction.status_update":- if interaction, ok := event["interaction"].(map[string]any); ok {- if id, ok := interaction["id"].(string); ok && id != "" {- turn.interactionID = id- }- }- if id, ok := event["interaction_id"].(string); ok && id != "" {- turn.interactionID = id- }-- case "step.start":- // encoding/json decodes JSON numbers as float64; convert the step- // index to int at this boundary so the maps are keyed by a plain int.- stepIndexF, _ := event["index"].(float64)- stepIndex := int(stepIndexF)- if step, ok := event["step"].(map[string]any); ok && step["type"] == "function_call" {- call := callsByStepIndex[stepIndex]- if call == nil {- call = &pendingCall{}- callsByStepIndex[stepIndex] = call- stepIndexOrder = append(stepIndexOrder, stepIndex)- }- if id, ok := step["id"].(string); ok && id != "" {- call.id = id- }- if name, ok := step["name"].(string); ok && name != "" {- call.name = name- }- if inlineArgs, ok := step["arguments"].(map[string]any); ok && len(inlineArgs) > 0 {- call.args = inlineArgs- }- }- case "step.delta":- stepIndexF, _ := event["index"].(float64)- stepIndex := int(stepIndexF)- if delta, ok := event["delta"].(map[string]any); ok {- switch delta["type"] {- case "arguments_delta":- if call := callsByStepIndex[stepIndex]; call != nil {- if argsSnapshot, ok := delta["arguments"].(string); ok && argsSnapshot != "" {- call.argsJSON = argsSnapshot // snapshot: replace, not append- }- }- case "text":- if textChunk, ok := delta["text"].(string); ok {- // Text deltas are mostly incremental, but the server- // periodically re-sends a full cumulative restatement of the- // text so far (e.g. when finalizing a turn before a tool- // call). Detect that case and replace rather than append, so- // the restated text is not duplicated.- if strings.HasPrefix(textChunk, turn.modelText) && turn.modelText != "" {- turn.modelText = textChunk- } else {- turn.modelText += textChunk- }- }- }- }- }- }- if err := scanner.Err(); err != nil {- return nil, err- }-- // Collapse the per-step-index pending calls into unique tool calls, in- // first-seen order, deduped by id. A call missing a name or id is an- // incomplete streaming artifact and is skipped.- seenCallIDs := map[string]bool{}- for _, stepIndex := range stepIndexOrder {- call := callsByStepIndex[stepIndex]- if call.name == "" || call.id == "" || seenCallIDs[call.id] {- continue- }- seenCallIDs[call.id] = true- if call.args == nil && call.argsJSON != "" {- var parsedArgs map[string]any- if err := json.Unmarshal([]byte(call.argsJSON), &parsedArgs); err == nil {- call.args = parsedArgs- }- }- if call.args == nil {- call.args = map[string]any{}- }- turn.toolCalls = append(turn.toolCalls, capturedToolCall{- callID: call.id, name: call.name, arguments: call.args,- })- }- return turn, nil-}diff --git a/internal/harness/antigravityinteractions/antigravityinteractions_test.go b/internal/harness/antigravityinteractions/antigravityinteractions_test.godeleted file mode 100644index af524a4..0000000--- a/internal/harness/antigravityinteractions/antigravityinteractions_test.go+++ /dev/null@@ -1,302 +0,0 @@-// 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 antigravityinteractions--import (- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "path/filepath"- "strings"- "sync"- "testing"-- "github.com/google/ax/internal/harness/harnesstest"- "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 := newWithHTTPClient(AntigravityInteractionsConfig{- Agent: "test-agent",- StateDir: stateDir,- TokenSource: oauth2.StaticTokenSource(&oauth2.Token{AccessToken: "fake-token"}),- }, &http.Client{Transport: fake})- if err != nil {- t.Fatalf("newWithHTTPClient: %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, harnesstest.UserStep(prompt)); err != nil {- t.Fatalf("Queue: %v", err)- }- if err := exec.Run(ctx, &harnesstest.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 := New(AntigravityInteractionsConfig{- Agent: "test-agent",- StateDir: "", // missing- TokenSource: oauth2.StaticTokenSource(&oauth2.Token{AccessToken: "fake-token"}),- })- if err == nil {- t.Fatal("New 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")- }-}--// TestDefaultStateDir returns ~/.ax/antigravityinteractions/cursors under the-// user's home directory.-func TestDefaultStateDir(t *testing.T) {- home := t.TempDir()- t.Setenv("HOME", home)-- got, err := DefaultStateDir()- if err != nil {- t.Fatalf("DefaultStateDir: %v", err)- }- if want := filepath.Join(home, ".ax", "antigravityinteractions", "cursors"); got != want {- t.Errorf("DefaultStateDir() = %q, want %q", got, want)- }-}--// TestParseStreamedTurnSurfacesErrorEvent verifies that a server-emitted SSE-// "error" event (e.g. INVALID_ARGUMENT for a malformed client tool result) is-// surfaced as a real error, instead of being silently dropped and returned as a-// completed-but-empty turn. Dropping it made an empty directory listing look-// like a blank "no response" turn and poisoned the resume cursor with the-// failing interaction's id.-func TestParseStreamedTurnSurfacesErrorEvent(t *testing.T) {- sse := "" +- "event: interaction.created\n" +- `data: {"interaction":{"id":"INT-1","status":"in_progress"},"event_type":"interaction.created"}` + "\n\n" +- "event: error\n" +- `data: {"event_type":"error","error":{"message":"field 'results' must be a list_value, got unset","status":"INVALID_ARGUMENT"}}` + "\n\n" +- "event: done\n" +- "data: [DONE]\n\n"-- h := &AntigravityInteractionsHarness{}- turn, err := h.parseStreamedTurn(strings.NewReader(sse))- if err == nil {- t.Fatalf("parseStreamedTurn() = %+v, nil error; want an error for the SSE error event", turn)- }- if !strings.Contains(err.Error(), "INVALID_ARGUMENT") {- t.Errorf("error = %q, want it to include the server status INVALID_ARGUMENT", err)- }- if !strings.Contains(err.Error(), "must be a list_value") {- t.Errorf("error = %q, want it to include the server message", err)- }-}--func TestServerErrorMessage(t *testing.T) {- tests := []struct {- name string- event map[string]any- want string- }{- {- name: "message and status",- event: map[string]any{"error": map[string]any{"message": "boom", "status": "INVALID_ARGUMENT"}},- want: "boom (INVALID_ARGUMENT)",- },- {- name: "message only",- event: map[string]any{"error": map[string]any{"message": "boom"}},- want: "boom",- },- {- name: "status only",- event: map[string]any{"error": map[string]any{"status": "UNAVAILABLE"}},- want: "UNAVAILABLE",- },- {- name: "no error object",- event: map[string]any{"event_type": "error"},- want: "unknown server error",- },- }- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- if got := serverErrorMessage(tt.event); got != tt.want {- t.Errorf("serverErrorMessage() = %q, want %q", got, tt.want)- }- })- }-}diff --git a/internal/harness/antigravityinteractions/antigravityinteractions_tools.go b/internal/harness/antigravityinteractions/antigravityinteractions_tools.godeleted file mode 100644index d3541c0..0000000--- a/internal/harness/antigravityinteractions/antigravityinteractions_tools.go+++ /dev/null@@ -1,545 +0,0 @@-// 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 antigravityinteractions--import (- "context"- "fmt"- "os"- "os/exec"- "path/filepath"- "sort"- "strconv"- "strings"- "time"- "unicode/utf8"-)--// executeTool runs a tool call the agent yielded and returns the result value to-// 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, 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, 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":- return execViewFile(call)- case "run_command":- return execRunCommand(ctx, call, h.cfg.WorkDir)- case "list_dir", "list_directory":- return execListDir(call)- case "move":- return execMove(call)- case "delete_dir":- return execDeleteDir(call)- case "create_file":- return execCreateFile(call)- case "edit_file":- return execEditFile(call)- case "multi_edit_file":- return execMultiEditFile(call)- case "delete_file":- return execDeleteFile(call)- default:- if h.cfg.ThirdPartyExecutor == nil {- return map[string]any{"error": fmt.Sprintf("no executor configured for third-party tool %q", call.name)}- }- return h.cfg.ThirdPartyExecutor.Execute(ctx, call.name, call.arguments)- }-}--// ----------------------------------------------------------------------------// Built-in environment tools: real local implementations.-//-// 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 server maps back into-// the step's own output (content, Output/ExitCode, results).-// -----------------------------------------------------------------------------// view_file result caps. Mirrors the Antigravity view_file contract:-// StartLine/EndLine are 1-indexed inclusive, at most viewFileMaxLines lines are-// returned per view, and content is byte-capped with a ContentOffset-// continuation so a large file can't blob a multi-hundred-KB tool result that-// stalls the turn / blows past API context limits.-const (- viewFileMaxLines = 2000- viewFileMaxBytes = 256 * 1024 // 256 KiB-)--func execViewFile(call capturedToolCall) any {- path := stringArg(call.arguments, "AbsolutePath")- if path == "" {- return map[string]any{"error": "view_file: missing required argument 'AbsolutePath'"}- }- data, err := os.ReadFile(path)- if err != nil {- return map[string]any{"error": fmt.Sprintf("view_file: %v", err)}- }-- // Resolve the 1-indexed inclusive line window using slice notation (see- // resolveLineWindow), then apply the byte cap, honoring ContentOffset as the- // read position within the windowed content. The caps bound the result size so- // a large file can't blob.- start, startSet := intArgOK(call.arguments, "StartLine")- end, endSet := intArgOK(call.arguments, "EndLine")- offset := intArg(call.arguments, "ContentOffset")-- whole := string(data)- windowed, lo, hi, totalLines := resolveLineWindow(whole, start, startSet, end, endSet)- content := applyByteWindow(windowed, offset)-- // Return the metadata the server needs to distinguish a complete read from a- // paginated/byte-truncated one:- // - start_line/end_line: 0-indexed inclusive served line range (the result- // is 0-indexed; the tool-call StartLine/EndLine args are 1-indexed).- // - content_offset: byte offset within the line-range content this slice- // starts at (for pagination continuation).- // - line_range_bytes: total bytes of the selected line range *before* byte- // truncation; the server compares content_offset+len(content) against- // this to detect byte truncation.- // - num_lines/num_bytes: whole-file totals.- result := map[string]any{- "content": content,- "content_offset": offset,- "line_range_bytes": len(windowed),- "num_lines": totalLines,- "num_bytes": len(whole),- }- // Only report a concrete served range when there was content to serve;- // otherwise leave the (0,0) default.- if lo > 0 && hi >= lo {- result["start_line"] = lo - 1 // 1-indexed -> 0-indexed- result["end_line"] = hi - 1- }- return result-}--// resolveLineWindow returns the requested line window of content, following the-// Antigravity view_file slice notation over 1-indexed inclusive [start, end]:-//-// - neither set: the first viewFileMaxLines lines (or the whole file if smaller)-// - start only: viewFileMaxLines lines starting at start (forward window)-// - end only: viewFileMaxLines lines ending at end (backward window)-// - both set: lines [start, end], capped to viewFileMaxLines from start-//-// It returns the joined window text, the served 1-indexed inclusive [lo, hi]-// range (0, 0 when nothing is served), and the whole-file total line count.-func resolveLineWindow(content string, start int, startSet bool, end int, endSet bool) (windowed string, lo, hi, total int) {- lines := strings.Split(content, "\n")- // strings.Split on a trailing newline yields a final empty element; drop it so- // line counts match the file's logical lines.- if n := len(lines); n > 0 && lines[n-1] == "" {- lines = lines[:n-1]- }- total = len(lines)- if total == 0 {- return "", 0, 0, 0- }-- // Compute a 1-indexed inclusive [lo, hi] window per slice notation.- switch {- case !startSet && !endSet:- lo, hi = 1, viewFileMaxLines- case startSet && !endSet:- lo = start- hi = start + viewFileMaxLines - 1- case !startSet && endSet:- hi = end- lo = end - viewFileMaxLines + 1- default: // both set- lo, hi = start, end- if hi-lo+1 > viewFileMaxLines {- hi = lo + viewFileMaxLines - 1- }- }-- // Clamp to the file bounds.- if lo < 1 {- lo = 1- }- if hi > total {- hi = total- }- if lo > total || hi < lo {- // Window is entirely past EOF (or inverted after clamping): nothing to show.- return "", 0, 0, total- }-- return strings.Join(lines[lo-1:hi], "\n"), lo, hi, total-}--// applyByteWindow returns the slice of content starting at offset (the agent's-// ContentOffset), capped to viewFileMaxBytes so a large window can't blob. When-// it truncates, the cut is backed off to the last complete UTF-8 rune so the-// returned string is always valid UTF-8 (never a split multi-byte character).-//-// Callers detect truncation and the resume point from the returned slice: the-// window was truncated when offset+len(out) < len(content), and the agent-// resumes by re-reading with ContentOffset == offset+len(out).-func applyByteWindow(content string, offset int) string {- if offset < 0 {- offset = 0- }- if offset > len(content) {- offset = len(content)- }- remaining := content[offset:]- if len(remaining) <= viewFileMaxBytes {- return remaining- }-- // Cap at viewFileMaxBytes, then back off to a valid UTF-8 boundary so we- // don't split a multi-byte rune across the cut.- cut := viewFileMaxBytes- for cut > 0 && !utf8.RuneStart(remaining[cut]) {- cut--- }- // remaining[cut] is now the start of a rune (or cut == 0). Guard the- // pathological case of a single rune larger than the cap: emit at least that- // rune so we always make forward progress.- if cut == 0 {- _, size := utf8.DecodeRuneInString(remaining)- cut = size- }- return remaining[:cut]-}--// runCommandTimeout bounds how long a single run_command may take, so a runaway-// command (e.g. `find /`, or `ping` without a count) cannot wedge the harness.-const runCommandTimeout = 60 * time.Second--func execRunCommand(ctx context.Context, call capturedToolCall, workDir string) any {- cmdLine := stringArg(call.arguments, "CommandLine")- if cmdLine == "" {- return map[string]any{"error": "run_command: missing required argument 'CommandLine'"}- }-- // Bound the command's runtime so it cannot hang the harness.- runCtx, cancel := context.WithTimeout(ctx, runCommandTimeout)- defer cancel()-- cmd := exec.CommandContext(runCtx, "/bin/sh", "-c", cmdLine)- // Resolve the working directory. workDir is authoritative so execution does- // not depend on the process's ambient cwd. A model-supplied Cwd is honored- // relative to workDir if relative, or as-is if absolute; without one, the- // command runs in workDir.- cmd.Dir = resolveRunDir(workDir, stringArg(call.arguments, "Cwd"))-- out, err := cmd.CombinedOutput()-- // Timed out: report a clear, non-zero result rather than blocking.- if runCtx.Err() == context.DeadlineExceeded {- return map[string]any{- "Output": fmt.Sprintf("%scommand timed out after %s", out, runCommandTimeout),- "ExitCode": 124, // conventional timeout exit code- }- }-- exitCode := 0- if err != nil {- if ee, ok := err.(*exec.ExitError); ok {- exitCode = ee.ExitCode()- } else {- // Failed to start: surface as a non-zero exit + output.- return map[string]any{"Output": fmt.Sprintf("%s%v", out, err), "ExitCode": 1}- }- }- return map[string]any{"Output": string(out), "ExitCode": exitCode}-}--// resolveRunDir picks the directory run_command executes in.-//-// - No cwd arg: run in workDir (or the process cwd if workDir is empty).-// - Absolute cwd: honored as-is (the agent asked for a specific location).-// - Relative cwd: resolved against workDir, keeping the agent scoped to its-// workspace rather than the process's ambient cwd.-//-// Returning "" makes exec use the process's current directory, matching the-// prior behavior when no working directory is configured.-func resolveRunDir(workDir, cwd string) string {- switch {- case cwd == "":- return workDir- case filepath.IsAbs(cwd):- return cwd- case workDir == "":- return cwd- default:- return filepath.Join(workDir, cwd)- }-}--func execListDir(call capturedToolCall) any {- dir := stringArg(call.arguments, "DirectoryPath")- if dir == "" {- return map[string]any{"error": "list_dir: missing required argument 'DirectoryPath'"}- }- entries, err := os.ReadDir(dir)- if err != nil {- return map[string]any{"error": fmt.Sprintf("list_dir: %v", err)}- }- results := make([]map[string]any, 0, len(entries))- for _, e := range entries {- var sizeBytes int64- if info, err := e.Info(); err == nil {- sizeBytes = info.Size()- }- results = append(results, map[string]any{- "name": e.Name(),- "is_dir": e.IsDir(),- "size_bytes": sizeBytes,- })- }- sort.Slice(results, func(i, j int) bool {- return results[i]["name"].(string) < results[j]["name"].(string)- })- return map[string]any{"results": results}-}--// ----------------------------------------------------------------------------// Built-in file mutation tools.-//-// These mutate the real local filesystem. By contract, a successful mutation-// needs no result payload (the server renders success from the call's input-// args); a failure is reported as {"error": <message>}, which marks the step-// ERROR. Argument names follow the agent's tool schema (PascalCase).-// -----------------------------------------------------------------------------// mutationOK is the empty success result for a mutation tool.-func mutationOK() any { return map[string]any{} }--func mutationErr(tool string, err error) any {- return map[string]any{"error": fmt.Sprintf("%s: %v", tool, err)}-}--// execMove implements the "move" tool: SourcePath -> DestinationPath.-func execMove(call capturedToolCall) any {- src := stringArg(call.arguments, "SourcePath")- dst := stringArg(call.arguments, "DestinationPath")- if src == "" || dst == "" {- return mutationErr("move", fmt.Errorf("missing required argument 'SourcePath' and/or 'DestinationPath'"))- }- if err := os.Rename(src, dst); err != nil {- return mutationErr("move", err)- }- return mutationOK()-}--// execDeleteDir implements the "delete_dir" tool: removes DirectoryPath. Force-// allows recursive removal; otherwise only an empty directory is removed.-func execDeleteDir(call capturedToolCall) any {- dir := stringArg(call.arguments, "DirectoryPath")- if dir == "" {- return mutationErr("delete_dir", fmt.Errorf("missing required argument 'DirectoryPath'"))- }- var err error- if boolArg(call.arguments, "Force") {- err = os.RemoveAll(dir)- } else {- err = os.Remove(dir) // fails if not empty / not a dir- }- if err != nil {- return mutationErr("delete_dir", err)- }- return mutationOK()-}--// execCreateFile implements the "create_file" tool: writes Content to TargetFile.-// Overwrite must be true to replace an existing file.-func execCreateFile(call capturedToolCall) any {- path := stringArg(call.arguments, "TargetFile")- if path == "" {- return mutationErr("create_file", fmt.Errorf("missing required argument 'TargetFile'"))- }- if !boolArg(call.arguments, "Overwrite") {- if _, err := os.Stat(path); err == nil {- return mutationErr("create_file", fmt.Errorf("file %q already exists and Overwrite is false", path))- }- }- if dir := filepath.Dir(path); dir != "" {- if err := os.MkdirAll(dir, 0o755); err != nil {- return mutationErr("create_file", err)- }- }- if err := os.WriteFile(path, []byte(stringArg(call.arguments, "Content")), 0o644); err != nil {- return mutationErr("create_file", err)- }- return mutationOK()-}--// execEditFile implements the "edit_file" tool: replaces the first occurrence of-// TargetContent with ReplacementContent in TargetFile.-func execEditFile(call capturedToolCall) any {- path := stringArg(call.arguments, "TargetFile")- target := stringArg(call.arguments, "TargetContent")- repl := stringArg(call.arguments, "ReplacementContent")- if path == "" || target == "" {- return mutationErr("edit_file", fmt.Errorf("missing required argument 'TargetFile' and/or 'TargetContent'"))- }- return applyReplacements(path, "edit_file", []replacement{{target: target, repl: repl}})-}--// execMultiEditFile implements the "multi_edit_file" tool: applies a list of-// search/replace ReplacementChunks to TargetFile, in order.-func execMultiEditFile(call capturedToolCall) any {- path := stringArg(call.arguments, "TargetFile")- if path == "" {- return mutationErr("multi_edit_file", fmt.Errorf("missing required argument 'TargetFile'"))- }- chunks, ok := call.arguments["ReplacementChunks"].([]any)- if !ok {- return mutationErr("multi_edit_file", fmt.Errorf("missing or invalid 'ReplacementChunks' array"))- }- reps := make([]replacement, 0, len(chunks))- for _, c := range chunks {- m, ok := c.(map[string]any)- if !ok {- return mutationErr("multi_edit_file", fmt.Errorf("each ReplacementChunk must be an object"))- }- reps = append(reps, replacement{- target: stringArg(m, "TargetContent"),- repl: stringArg(m, "ReplacementContent"),- })- }- return applyReplacements(path, "multi_edit_file", reps)-}--// execDeleteFile implements the "delete_file" tool: removes TargetFile.-func execDeleteFile(call capturedToolCall) any {- path := stringArg(call.arguments, "TargetFile")- if path == "" {- return mutationErr("delete_file", fmt.Errorf("missing required argument 'TargetFile'"))- }- if err := os.Remove(path); err != nil {- return mutationErr("delete_file", err)- }- return mutationOK()-}--// replacement is a single search/replace edit.-type replacement struct {- target string- repl string-}--// applyReplacements reads path, applies each search/replace (first occurrence,-// in order), and writes the result back. Each target must be found.-func applyReplacements(path, tool string, reps []replacement) any {- data, err := os.ReadFile(path)- if err != nil {- return mutationErr(tool, err)- }- content := string(data)- for i, r := range reps {- if r.target == "" {- return mutationErr(tool, fmt.Errorf("chunk %d has empty TargetContent", i))- }- idx := strings.Index(content, r.target)- if idx < 0 {- return mutationErr(tool, fmt.Errorf("chunk %d: TargetContent not found in %q", i, path))- }- content = content[:idx] + r.repl + content[idx+len(r.target):]- }- if err := os.WriteFile(path, []byte(content), 0o644); err != nil {- return mutationErr(tool, err)- }- return mutationOK()-}--// ----------------------------------------------------------------------------// Third-party / MCP function tools.-//-// Third-party tools are executed INTERNALLY by the harness, via a-// ThirdPartyExecutor. The executor both declares the tools (advertised to the-// agent in the request's "tools" field) and executes calls to them.-//-// The executor is the seam for the controller to inject the caller's own tool-// implementations (and their declarations). If no executor is configured, the-// harness advertises no third-party tools and reports an error result for any-// non-built-in call the agent attempts.-// -----------------------------------------------------------------------------// ThirdPartyExecutor declares and executes third-party (non-built-in) function-// tools. The harness owns when it is called; an implementation just needs to-// describe its tools and produce a result for a given call.-type ThirdPartyExecutor interface {- // Declarations returns the tool declarations advertised to the agent.- Declarations() []FunctionTool- // Execute runs the named tool with the given arguments and returns the result- // value to send back to the agent (wrapped into the function_result step).- Execute(ctx context.Context, name string, args map[string]any) any-}--// ----------------------------------------------------------------------------// Argument helpers.-// -----------------------------------------------------------------------------func stringArg(args map[string]any, name string) string {- if args == nil {- return ""- }- if v, ok := args[name].(string); ok {- return v- }- return ""-}--func boolArg(args map[string]any, name string) bool {- if args == nil {- return false- }- if v, ok := args[name].(bool); ok {- return v- }- return false-}--// intArg reads an integer argument. JSON numbers decode to float64, but tolerate-// int and numeric strings too. Returns 0 when absent or unparseable.-func intArg(args map[string]any, name string) int {- n, _ := intArgOK(args, name)- return n-}--// intArgOK is like intArg but also reports whether the argument was present and-// parseable. Callers use the ok flag to distinguish "unset" from an explicit 0-// (needed for view_file slice notation, where start-only vs end-only differ).-func intArgOK(args map[string]any, name string) (int, bool) {- if args == nil {- return 0, false- }- switch v := args[name].(type) {- case float64:- return int(v), true- case int:- return v, true- case int64:- return int(v), true- case string:- if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {- return n, true- }- }- return 0, false-}diff --git a/internal/harness/antigravityinteractions/antigravityinteractions_tools_test.go b/internal/harness/antigravityinteractions/antigravityinteractions_tools_test.godeleted file mode 100644index 38bc9ce..0000000--- a/internal/harness/antigravityinteractions/antigravityinteractions_tools_test.go+++ /dev/null@@ -1,425 +0,0 @@-// 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 antigravityinteractions--import (- "context"- "fmt"- "os"- "path/filepath"- "strings"- "testing"- "unicode/utf8"-)--// numberedLines returns "1\n2\n...\nN\n".-func numberedLines(n int) string {- var b strings.Builder- for i := 1; i <= n; i++ {- fmt.Fprintf(&b, "%d\n", i)- }- return b.String()-}--func TestResolveLineWindow(t *testing.T) {- content := "l1\nl2\nl3\nl4\nl5\n"- tests := []struct {- name string- start int- startSet bool- end int- endSet bool- want string- }{- {"neither set (small file)", 0, false, 0, false, "l1\nl2\nl3\nl4\nl5"},- {"both set middle", 2, true, 4, true, "l2\nl3\nl4"},- {"both set whole", 1, true, 5, true, "l1\nl2\nl3\nl4\nl5"},- {"start only", 3, true, 0, false, "l3\nl4\nl5"},- {"end only", 0, false, 3, true, "l1\nl2\nl3"},- {"end past EOF clamps", 3, true, 999, true, "l3\nl4\nl5"},- {"start past EOF empty", 99, true, 0, false, ""},- }- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got, _, _, _ := resolveLineWindow(content, tt.start, tt.startSet, tt.end, tt.endSet)- if got != tt.want {- t.Errorf("content = %q, want %q", got, tt.want)- }- })- }-}--func TestResolveLineWindow_StartOnlyForwardWindow(t *testing.T) {- // start only => viewFileMaxLines lines starting at start (forward window).- content := numberedLines(viewFileMaxLines + 500)- got, _, _, _ := resolveLineWindow(content, 10, true, 0, false)- lines := strings.Split(got, "\n")- if len(lines) != viewFileMaxLines {- t.Fatalf("got %d lines, want forward window of %d", len(lines), viewFileMaxLines)- }- if lines[0] != "10" {- t.Errorf("first line = %q, want %q (window starts at start)", lines[0], "10")- }-}--func TestResolveLineWindow_EndOnlyBackwardWindow(t *testing.T) {- // end only => viewFileMaxLines lines ending at end (backward window).- total := viewFileMaxLines + 500- content := numberedLines(total)- end := total // last line- got, _, _, _ := resolveLineWindow(content, 0, false, end, true)- lines := strings.Split(got, "\n")- if len(lines) != viewFileMaxLines {- t.Fatalf("got %d lines, want backward window of %d", len(lines), viewFileMaxLines)- }- if lines[len(lines)-1] != fmt.Sprintf("%d", end) {- t.Errorf("last line = %q, want %q (window ends at end)", lines[len(lines)-1], fmt.Sprintf("%d", end))- }-}--func TestResolveLineWindow_NeitherSetCapsToMaxLines(t *testing.T) {- content := numberedLines(viewFileMaxLines + 100)- got, _, _, _ := resolveLineWindow(content, 0, false, 0, false)- if n := len(strings.Split(got, "\n")); n != viewFileMaxLines {- t.Errorf("got %d lines, want cap %d", n, viewFileMaxLines)- }-}--func TestApplyByteWindow(t *testing.T) {- // truncated reports whether applyByteWindow(content, offset)==out capped the- // window, i.e. there is still content past the returned slice. Callers derive- // this the same way from the wire fields (offset+len(content) <- // line_range_bytes).- truncated := func(content string, offset, gotLen int) bool {- return offset+gotLen < len(content)- }-- t.Run("under cap: not truncated", func(t *testing.T) {- got := applyByteWindow("hello", 0)- if got != "hello" || truncated("hello", 0, len(got)) {- t.Errorf("got %q (truncated=%v), want hello (false)", got, truncated("hello", 0, len(got)))- }- })- t.Run("over cap truncates to viewFileMaxBytes + resumes at next", func(t *testing.T) {- big := strings.Repeat("x", viewFileMaxBytes+100)- got := applyByteWindow(big, 0)- if len(got) != viewFileMaxBytes || !truncated(big, 0, len(got)) {- t.Errorf("got len %d (truncated=%v), want %d (true)", len(got), truncated(big, 0, len(got)), viewFileMaxBytes)- }- // Resume offset is offset+len(got); the remainder is the trailing 100 bytes.- if next := len(got); next != viewFileMaxBytes {- t.Errorf("resume offset = %d, want %d", next, viewFileMaxBytes)- }- })- t.Run("resume via offset returns remainder", func(t *testing.T) {- big := strings.Repeat("x", viewFileMaxBytes+100)- got := applyByteWindow(big, viewFileMaxBytes)- if len(got) != 100 || truncated(big, viewFileMaxBytes, len(got)) {- t.Errorf("got len %d (truncated=%v), want 100 (false)", len(got), truncated(big, viewFileMaxBytes, len(got)))- }- })- t.Run("offset past end is empty", func(t *testing.T) {- got := applyByteWindow("abc", 999)- if got != "" {- t.Errorf("got %q, want empty", got)- }- })- t.Run("caps at valid UTF-8 boundary (no split rune)", func(t *testing.T) {- // Fill just under the cap with ASCII, then place a 3-byte rune ("€" is- // U+20AC, 3 bytes) straddling the cap so a naive byte cut would split it.- const r = "€" // 3 bytes: E2 82 AC- pad := viewFileMaxBytes - 1 // cap lands 1 byte into the rune- content := strings.Repeat("a", pad) + r + "tail"- got := applyByteWindow(content, 0)- if !truncated(content, 0, len(got)) {- t.Fatal("expected truncation")- }- if !utf8.ValidString(got) {- t.Errorf("returned content is not valid UTF-8 (split rune): last bytes %x", got[len(got)-3:])- }- // The rune must not be partially included: length backs off to pad.- if len(got) != pad {- t.Errorf("got len %d, want %d (backed off before the straddling rune)", len(got), pad)- }- // Resuming from offset+len(got) yields the rune intact at the front.- rest := applyByteWindow(content, len(got))- if !strings.HasPrefix(rest, r) {- t.Errorf("resume did not start at the rune boundary: %.6q", rest)- }- })-}--func TestExecViewFile_HonorsRange(t *testing.T) {- dir := t.TempDir()- path := filepath.Join(dir, "f.txt")- if err := os.WriteFile(path, []byte("a\nb\nc\nd\ne\n"), 0o644); err != nil {- t.Fatal(err)- }- res := execViewFile(capturedToolCall{arguments: map[string]any{- "AbsolutePath": path,- "StartLine": float64(2), // JSON numbers arrive as float64- "EndLine": float64(3),- }})- m := res.(map[string]any)- if m["content"] != "b\nc" {- t.Errorf("content = %q, want %q", m["content"], "b\nc")- }-}--func TestExecViewFile_LargeFileIsCapped(t *testing.T) {- dir := t.TempDir()- path := filepath.Join(dir, "big.csv")- var b strings.Builder- for i := 0; i < 5000; i++ {- fmt.Fprintf(&b, "row-%d-with-some-padding\n", i)- }- if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {- t.Fatal(err)- }- // No range requested (the regression: previously returned the whole file).- res := execViewFile(capturedToolCall{arguments: map[string]any{"AbsolutePath": path}})- content := res.(map[string]any)["content"].(string)- if len(content) > viewFileMaxBytes {- t.Errorf("content = %d bytes, exceeds cap %d", len(content), viewFileMaxBytes)- }- if lines := len(strings.Split(content, "\n")); lines > viewFileMaxLines {- t.Errorf("content = %d lines, exceeds cap %d", lines, viewFileMaxLines)- }-}--func TestExecViewFile_PaginationMetadataAndResume(t *testing.T) {- dir := t.TempDir()- path := filepath.Join(dir, "wide.txt")- totalBytes := viewFileMaxBytes + 50- // One long single line exceeding the byte cap.- if err := os.WriteFile(path, []byte(strings.Repeat("z", totalBytes)), 0o644); err != nil {- t.Fatal(err)- }- // First read: capped at viewFileMaxBytes; reports pagination metadata so the- // converter can detect byte truncation (content_offset+len(content) <- // line_range_bytes).- first := execViewFile(capturedToolCall{arguments: map[string]any{"AbsolutePath": path}}).(map[string]any)- if got := first["content"].(string); len(got) != viewFileMaxBytes {- t.Fatalf("first read = %d bytes, want cap %d", len(got), viewFileMaxBytes)- }- if first["content_offset"] != 0 {- t.Errorf("content_offset = %v, want 0", first["content_offset"])- }- if first["line_range_bytes"] != totalBytes {- t.Errorf("line_range_bytes = %v, want %d (pre-truncation total)", first["line_range_bytes"], totalBytes)- }- // Byte-truncation detectable: offset + len(content) < line_range_bytes.- if got := first["content_offset"].(int) + len(first["content"].(string)); got >= first["line_range_bytes"].(int) {- t.Errorf("offset+len = %d, want < line_range_bytes %d (should look truncated)", got, first["line_range_bytes"])- }-- // Resume from where the first slice ended: returns the remaining 50 bytes.- resumeOffset := len(first["content"].(string)) // 0 + viewFileMaxBytes- second := execViewFile(capturedToolCall{arguments: map[string]any{- "AbsolutePath": path,- "ContentOffset": float64(resumeOffset),- }}).(map[string]any)- if got := second["content"].(string); len(got) != 50 {- t.Errorf("resume read = %d bytes, want 50", len(got))- }- // Now complete: offset + len == line_range_bytes.- if got := second["content_offset"].(int) + len(second["content"].(string)); got != second["line_range_bytes"].(int) {- t.Errorf("resume offset+len = %d, want == line_range_bytes %d (complete)", got, second["line_range_bytes"])- }-}--func TestExecViewFile_MultiByteRuneStraddlesByteCap(t *testing.T) {- dir := t.TempDir()- path := filepath.Join(dir, "wide_utf8.txt")- // One long single line: ASCII padding so the byte cap lands 1 byte into a- // 3-byte rune ("€" is U+20AC, E2 82 AC), followed by more content so the read- // is byte-truncated and must continue.- const r = "€"- pad := viewFileMaxBytes - 1- content := strings.Repeat("a", pad) + r + strings.Repeat("b", 40)- if err := os.WriteFile(path, []byte(content), 0o644); err != nil {- t.Fatal(err)- }-- // First page: capped, backed off before the straddling rune -> valid UTF-8.- first := execViewFile(capturedToolCall{arguments: map[string]any{"AbsolutePath": path}}).(map[string]any)- firstContent := first["content"].(string)- if !utf8.ValidString(firstContent) {- t.Errorf("first page is not valid UTF-8 (split rune): last bytes %x", firstContent[len(firstContent)-3:])- }- if len(firstContent) != pad {- t.Errorf("first page = %d bytes, want %d (backed off before the straddling rune)", len(firstContent), pad)- }- // Byte-truncation detectable: content_offset+len(content) < line_range_bytes.- if got := first["content_offset"].(int) + len(firstContent); got >= first["line_range_bytes"].(int) {- t.Errorf("offset+len = %d, want < line_range_bytes %d (should look truncated)", got, first["line_range_bytes"])- }-- // Second page: resume from where the first ended. The rune must appear intact- // at the front and the page must be valid UTF-8.- resumeOffset := first["content_offset"].(int) + len(firstContent)- second := execViewFile(capturedToolCall{arguments: map[string]any{- "AbsolutePath": path,- "ContentOffset": float64(resumeOffset),- }}).(map[string]any)- secondContent := second["content"].(string)- if !utf8.ValidString(secondContent) {- t.Errorf("resume page is not valid UTF-8: first bytes %x", secondContent[:3])- }- if !strings.HasPrefix(secondContent, r) {- t.Errorf("resume page did not start at the rune boundary: %.6q", secondContent)- }- // Now complete: offset + len == line_range_bytes.- if got := second["content_offset"].(int) + len(secondContent); got != second["line_range_bytes"].(int) {- t.Errorf("resume offset+len = %d, want == line_range_bytes %d (complete)", got, second["line_range_bytes"])- }-}--func TestExecViewFile_CompleteReadMetadata(t *testing.T) {- dir := t.TempDir()- path := filepath.Join(dir, "small.txt")- if err := os.WriteFile(path, []byte("a\nb\nc\n"), 0o644); err != nil {- t.Fatal(err)- }- res := execViewFile(capturedToolCall{arguments: map[string]any{"AbsolutePath": path}}).(map[string]any)- // 3 lines, served whole: start_line=0, end_line=2 (0-indexed inclusive).- if res["start_line"] != 0 || res["end_line"] != 2 {- t.Errorf("served range = (%v,%v), want (0,2)", res["start_line"], res["end_line"])- }- if res["num_lines"] != 3 {- t.Errorf("num_lines = %v, want 3", res["num_lines"])- }- // Complete (not byte-truncated): content_offset+len(content) == line_range_bytes.- if got := res["content_offset"].(int) + len(res["content"].(string)); got != res["line_range_bytes"].(int) {- t.Errorf("offset+len = %d, want == line_range_bytes %d (complete read)", got, res["line_range_bytes"])- }-}--func TestExecViewFile_MissingPath(t *testing.T) {- res := execViewFile(capturedToolCall{arguments: map[string]any{}})- m := res.(map[string]any)- if _, ok := m["error"]; !ok {- t.Errorf("expected error for missing AbsolutePath, got %+v", m)- }-}--func TestIntArgOK(t *testing.T) {- args := map[string]any{- "f": float64(7),- "i": 9,- "s": "12",- "z": float64(0),- "bad": "nope",- }- cases := []struct {- name string- wantN int- wantOK bool- }{- {"f", 7, true},- {"i", 9, true},- {"s", 12, true},- {"z", 0, true}, // explicit 0 is present- {"bad", 0, false},- {"absent", 0, false},- }- for _, c := range cases {- n, ok := intArgOK(args, c.name)- if n != c.wantN || ok != c.wantOK {- t.Errorf("intArgOK(%q) = (%d,%v), want (%d,%v)", c.name, n, ok, c.wantN, c.wantOK)- }- }-}--func TestResolveRunDir(t *testing.T) {- cases := []struct {- name string- workDir string- cwd string- want string- }{- {"no cwd -> workDir", "/workspace", "", "/workspace"},- {"relative cwd joined to workDir", "/workspace", "sub/dir", "/workspace/sub/dir"},- {"absolute cwd honored as-is", "/workspace", "/etc", "/etc"},- {"no workDir, no cwd -> empty (process cwd)", "", "", ""},- {"no workDir, relative cwd -> cwd", "", "sub", "sub"},- {"no workDir, absolute cwd -> cwd", "", "/etc", "/etc"},- }- for _, c := range cases {- if got := resolveRunDir(c.workDir, c.cwd); got != c.want {- t.Errorf("%s: resolveRunDir(%q,%q) = %q, want %q", c.name, c.workDir, c.cwd, got, c.want)- }- }-}--func TestExecRunCommand_RunsInWorkDir(t *testing.T) {- // Create a workspace with a marker file; `ls` from workDir (no Cwd arg) must- // list it, proving execution is scoped to workDir and not the process cwd.- work := t.TempDir()- if err := os.WriteFile(filepath.Join(work, "marker.txt"), []byte("x"), 0o644); err != nil {- t.Fatal(err)- }-- t.Run("no cwd runs in workDir", func(t *testing.T) {- res := execRunCommand(context.Background(),- capturedToolCall{arguments: map[string]any{"CommandLine": "ls"}},- work).(map[string]any)- if code := res["ExitCode"]; code != 0 {- t.Fatalf("ExitCode = %v, want 0 (output: %v)", code, res["Output"])- }- if out, _ := res["Output"].(string); !strings.Contains(out, "marker.txt") {- t.Errorf("Output = %q, want it to list marker.txt (ran in wrong dir)", out)- }- })-- t.Run("pwd reports workDir", func(t *testing.T) {- res := execRunCommand(context.Background(),- capturedToolCall{arguments: map[string]any{"CommandLine": "pwd"}},- work).(map[string]any)- out, _ := res["Output"].(string)- // macOS /tmp is a symlink to /private/tmp, so compare by suffix/resolved.- if got := strings.TrimSpace(out); got != work && !strings.HasSuffix(got, work) {- resolved, _ := filepath.EvalSymlinks(work)- if got != resolved {- t.Errorf("pwd = %q, want %q", got, work)- }- }- })-- t.Run("relative cwd resolves under workDir", func(t *testing.T) {- if err := os.Mkdir(filepath.Join(work, "sub"), 0o755); err != nil {- t.Fatal(err)- }- if err := os.WriteFile(filepath.Join(work, "sub", "inner.txt"), []byte("y"), 0o644); err != nil {- t.Fatal(err)- }- res := execRunCommand(context.Background(),- capturedToolCall{arguments: map[string]any{"CommandLine": "ls", "Cwd": "sub"}},- work).(map[string]any)- if out, _ := res["Output"].(string); !strings.Contains(out, "inner.txt") {- t.Errorf("Output = %q, want it to list inner.txt (relative Cwd not resolved under workDir)", out)- }- })-}--func TestWorkspaceSystemInstruction(t *testing.T) {- if got := WorkspaceSystemInstruction(""); got != "" {- t.Errorf("empty workDir = %q, want empty", got)- }- got := WorkspaceSystemInstruction("/workspace")- if !strings.Contains(got, "/workspace") {- t.Errorf("instruction = %q, want it to mention the working directory", got)- }-}diff --git a/internal/harness/antigravityinteractions/cursorstore.go b/internal/harness/antigravityinteractions/cursorstore.godeleted file mode 100644index 9ebfc99..0000000--- a/internal/harness/antigravityinteractions/cursorstore.go+++ /dev/null@@ -1,119 +0,0 @@-// 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 antigravityinteractions--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/antigravityinteractions/server.go b/internal/harness/antigravityinteractions/server.godeleted file mode 100644index c705afe..0000000--- a/internal/harness/antigravityinteractions/server.go+++ /dev/null@@ -1,225 +0,0 @@-// 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 antigravityinteractions--import (- "context"- "errors"- "fmt"- "log"- "net"- "net/http"- "os"- "os/signal"- "strconv"- "sync"- "syscall"-- "github.com/google/ax/internal/harness"- "github.com/google/ax/proto"- "google.golang.org/grpc"- "google.golang.org/grpc/health"- healthpb "google.golang.org/grpc/health/grpc_health_v1"-)--// server adapts the Antigravity Interactions harness (a Go harness.Harness) onto-// the gRPC HarnessService that the AX controller connects to. One server serves-// one actor's lifetime; substrate creates the actor per request.-type server struct {- proto.UnimplementedHarnessServiceServer- h harness.Harness-}--// Serve builds the Antigravity Interactions harness from cfg and serves the-// HarnessService (plus gRPC health) on host:port, and an HTTP /readyz endpoint on-// readyzPort that reflects this server's own serving state. It blocks until ctx-// is cancelled or a termination signal (SIGINT/SIGTERM) is received, then shuts-// down gracefully.-func Serve(ctx context.Context, cfg AntigravityInteractionsConfig, host string, port, readyzPort int) error {- h, err := New(cfg)- if err != nil {- return fmt.Errorf("creating antigravity interactions harness: %w", err)- }-- lis, err := net.Listen("tcp", net.JoinHostPort(host, strconv.Itoa(port)))- if err != nil {- return fmt.Errorf("listen on %s:%d: %w", host, port, err)- }-- grpcServer := grpc.NewServer()- proto.RegisterHarnessServiceServer(grpcServer, &server{h: h})-- // gRPC health: report SERVING for the default service so the controller's- // health checks pass.- hs := health.NewServer()- hs.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)- healthpb.RegisterHealthServer(grpcServer, hs)-- // Go-based readiness: /readyz is OK once this server is up and serving.- readyzSrv := serveReadyz(host, readyzPort)-- // Shut down on ctx cancellation or termination signals.- ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)- defer stop()- go func() {- <-ctx.Done()- log.Printf("antigravity interactions harness: shutting down")- if readyzSrv != nil {- _ = readyzSrv.Close()- }- grpcServer.GracefulStop()- }()-- log.Printf("antigravity interactions harness serving on %s:%d (readyz :%d)", host, port, readyzPort)- if err := grpcServer.Serve(lis); err != nil {- return fmt.Errorf("harness gRPC server: %w", err)- }- return nil-}--// serveReadyz starts an HTTP server exposing /readyz that returns 200 as long as-// this process's gRPC server is running. Readiness is intrinsic to this server.-func serveReadyz(host string, readyzPort int) *http.Server {- mux := http.NewServeMux()- mux.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- _, _ = w.Write([]byte("ok\n"))- })- srv := &http.Server{- Addr: net.JoinHostPort(host, strconv.Itoa(readyzPort)),- Handler: mux,- }- go func() {- if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {- log.Printf("readyz server on %s exited: %v", srv.Addr, err)- }- }()- return srv-}--// Connect drives one harness execution. Per the HarnessService contract, the-// client sends HarnessRequest{start} (and may send one HarnessRequest{cancel}-// mid-stream); the server streams zero or more HarnessResponse{outputs} frames-// terminated by exactly one HarnessResponse{end}.-func (s *server) Connect(stream proto.HarnessService_ConnectServer) error {- ctx, cancel := context.WithCancel(stream.Context())- defer cancel()-- // The first frame must be a start.- req, err := stream.Recv()- if err != nil {- return err- }- start := req.GetStart()- if start == nil {- return fmt.Errorf("first HarnessRequest must be a start frame")- }- convID := req.GetConversationId()-- exec, err := s.h.Start(ctx, convID, start.GetAgentConfig())- if err != nil {- return sendEnd(stream, convID, proto.State_STATE_FAILED, err)- }- defer func() { _ = exec.Close(context.WithoutCancel(ctx)) }()-- if len(start.GetSteps()) > 0 {- if err := exec.Queue(ctx, start.GetSteps()...); err != nil {- return sendEnd(stream, convID, proto.State_STATE_FAILED, err)- }- }-- // Watch for a mid-stream cancel frame; it cancels the run's context.- //- // Note: mid-run steering (injecting extra human input while a turn is running)- // is intentionally NOT supported here. The execution can accept steering via- // Queue, but the HarnessRequest oneof only defines {start, cancel} -- there is- // no wire frame to carry additional input after start -- so a client cannot- // deliver steering over Connect. Multi-turn conversation is instead expressed- // as separate Connect executions that resume via the persisted cursor. Any- // non-cancel frame received here is therefore ignored.- go func() {- for {- r, err := stream.Recv()- if err != nil {- return // stream closed or errored; run ends by other means- }- if r.GetCancel() != nil {- cancel()- return- }- }- }()-- // Run the turn, forwarding each agent message as an outputs frame.- handler := &streamHandler{stream: stream, convID: convID}- if err := exec.Run(ctx, handler); err != nil {- if ctx.Err() != nil {- return sendEnd(stream, convID, proto.State_STATE_CANCELED, ctx.Err())- }- return sendEnd(stream, convID, proto.State_STATE_FAILED, err)- }- if serr := handler.err(); serr != nil {- return serr // failed while sending an outputs frame; stream is broken- }- return sendEnd(stream, convID, proto.State_STATE_COMPLETED, nil)-}--// streamHandler forwards each message the harness produces during a turn as a-// HarnessResponse{outputs} frame.-type streamHandler struct {- stream proto.HarnessService_ConnectServer- convID string-- mu sync.Mutex- sendErr error-}--var _ harness.Handler = (*streamHandler)(nil)--func (h *streamHandler) OnMessage(_ context.Context, _ string, step *proto.Step) error {- err := h.stream.Send(&proto.HarnessResponse{- ConversationId: h.convID,- Type: &proto.HarnessResponse_Outputs{- Outputs: &proto.HarnessOutputs{Steps: []*proto.Step{step}},- },- })- if err != nil {- h.mu.Lock()- h.sendErr = err- h.mu.Unlock()- }- return err-}--func (h *streamHandler) OnComplete(_ context.Context, _ string) error { return nil }--func (h *streamHandler) err() error {- h.mu.Lock()- defer h.mu.Unlock()- return h.sendErr-}--// sendEnd sends the single terminal HarnessResponse{end} frame. If err is-// non-nil, it is attached as the terminal Error.-func sendEnd(stream proto.HarnessService_ConnectServer, convID string, state proto.State, err error) error {- end := &proto.HarnessEnd{State: state}- if err != nil {- end.Error = &proto.Error{Description: err.Error()}- }- return stream.Send(&proto.HarnessResponse{- ConversationId: convID,- Type: &proto.HarnessResponse_End{End: end},- })-}diff --git a/internal/harness/antigravityinteractions/server_test.go b/internal/harness/antigravityinteractions/server_test.godeleted file mode 100644index 5e33b18..0000000--- a/internal/harness/antigravityinteractions/server_test.go+++ /dev/null@@ -1,142 +0,0 @@-// 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 antigravityinteractions--import (- "context"- "errors"- "io"- "net"- "testing"-- "github.com/google/ax/internal/harness/harnesstest"- "github.com/google/ax/proto"- "google.golang.org/grpc"- "google.golang.org/grpc/credentials/insecure"- "google.golang.org/grpc/test/bufconn"-)--// startTestServer serves the HarnessService (backed by h) over an in-memory-// bufconn and returns a connected HarnessService client.-func startTestServer(t *testing.T, h *AntigravityInteractionsHarness) proto.HarnessServiceClient {- t.Helper()- lis := bufconn.Listen(1024 * 1024)- s := grpc.NewServer()- proto.RegisterHarnessServiceServer(s, &server{h: h})- go func() { _ = s.Serve(lis) }()- t.Cleanup(s.Stop)-- conn, err := grpc.NewClient(- "passthrough:///bufnet",- grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {- return lis.DialContext(ctx)- }),- grpc.WithTransportCredentials(insecure.NewCredentials()),- )- if err != nil {- t.Fatalf("dial bufconn: %v", err)- }- t.Cleanup(func() { _ = conn.Close() })- return proto.NewHarnessServiceClient(conn)-}--// TestConnect_StartToEnd verifies the Connect wire contract: a start frame drives-// one harness turn, and the stream terminates with exactly one HarnessEnd-// (COMPLETED) against the fake Interactions API.-func TestConnect_StartToEnd(t *testing.T) {- fake := &fakeInteractions{interactionIDs: []string{"INT-1"}}- h := newTestHarness(t, fake, t.TempDir())- client := startTestServer(t, h)-- stream, err := client.Connect(context.Background())- if err != nil {- t.Fatalf("Connect: %v", err)- }- if err := stream.Send(&proto.HarnessRequest{- ConversationId: "conv-1",- AgentId: "antigravity-interactions",- Type: &proto.HarnessRequest_Start{- Start: &proto.HarnessStart{Steps: []*proto.Step{harnesstest.UserStep("hello")}},- },- }); err != nil {- t.Fatalf("send start: %v", err)- }- _ = stream.CloseSend()-- var gotEnd *proto.HarnessEnd- for {- resp, err := stream.Recv()- if errors.Is(err, io.EOF) {- break- }- if err != nil {- t.Fatalf("recv: %v", err)- }- if end := resp.GetEnd(); end != nil {- if gotEnd != nil {- t.Fatalf("received more than one HarnessEnd")- }- gotEnd = end- }- }-- if gotEnd == nil {- t.Fatal("stream ended without a HarnessEnd frame")- }- if gotEnd.GetState() != proto.State_STATE_COMPLETED {- t.Errorf("terminal state = %v, want COMPLETED (error: %v)", gotEnd.GetState(), gotEnd.GetError())- }-- // The fake recorded the request: first turn has no previous_interaction_id.- reqs := fake.recorded()- if len(reqs) != 1 {- t.Fatalf("fake received %d requests, want 1", len(reqs))- }- if reqs[0].PreviousInteractionID != "" {- t.Errorf("previous_interaction_id = %q, want empty", reqs[0].PreviousInteractionID)- }-}--// TestConnect_FirstFrameMustBeStart verifies that a non-start first frame is-// rejected.-func TestConnect_FirstFrameMustBeStart(t *testing.T) {- fake := &fakeInteractions{}- h := newTestHarness(t, fake, t.TempDir())- client := startTestServer(t, h)-- stream, err := client.Connect(context.Background())- if err != nil {- t.Fatalf("Connect: %v", err)- }- if err := stream.Send(&proto.HarnessRequest{- ConversationId: "conv-1",- Type: &proto.HarnessRequest_Cancel{Cancel: &proto.HarnessCancel{}},- }); err != nil {- t.Fatalf("send cancel: %v", err)- }- _ = stream.CloseSend()-- // Draining the stream should surface an error (Connect returns it).- for {- _, err := stream.Recv()- if err == nil {- continue- }- if errors.Is(err, io.EOF) {- t.Fatal("expected an error for a non-start first frame, got clean EOF")- }- break // got the expected non-EOF error- }-}diff --git a/internal/harness/antigravityinteractions/skills.go b/internal/harness/antigravityinteractions/skills.godeleted file mode 100644index 8e3ecc9..0000000--- a/internal/harness/antigravityinteractions/skills.go+++ /dev/null@@ -1,63 +0,0 @@-// 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 antigravityinteractions--import (- "fmt"- "strings"-- "github.com/google/ax/internal/skills"-)--// SkillsSystemInstruction builds a system-instruction pointer telling the agent-// where its skills live and lists them. It is source-agnostic: the skills may-// come from the Gemini Enterprise Skill Registry or from a local directory ---// both produce []skills.Group.-//-// This is discovery logic specific to the Antigravity Interactions harness: it-// has no SKILLS_DIR concept, so it must be told where to find skills via its-// system instruction (its built-in file tools then read that directory).-// Harnesses that auto-discover a skills directory (e.g. the Antigravity SDK-// harness via SKILLS_DIR) do not use this.-func SkillsSystemInstruction(groups []skills.Group) string {- if len(groups) == 0 {- return ""- }- var b strings.Builder- for _, g := range groups {- if b.Len() > 0 {- b.WriteString("\n")- }- fmt.Fprintf(&b, "Agent skills are available under %s. Available skills:", g.Dir)- for _, s := range g.Skills {- fmt.Fprintf(&b, " %s", s.ID)- }- b.WriteString(". Read a skill's SKILL.md before using it.")- }- return b.String()-}--// JoinSystemInstruction combines a user-configured system instruction with an-// optional skills pointer (from SkillsSystemInstruction), dropping empties.-func JoinSystemInstruction(base, pointer string) string {- parts := make([]string, 0, 2)- if strings.TrimSpace(base) != "" {- parts = append(parts, base)- }- if strings.TrimSpace(pointer) != "" {- parts = append(parts, pointer)- }- return strings.Join(parts, "\n\n")-}diff --git a/internal/harness/antigravityinteractions/skills_test.go b/internal/harness/antigravityinteractions/skills_test.godeleted file mode 100644index 9fa8edc..0000000--- a/internal/harness/antigravityinteractions/skills_test.go+++ /dev/null@@ -1,68 +0,0 @@-// 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 antigravityinteractions--import (- "strings"- "testing"-- "github.com/google/ax/internal/skills"-)--func TestSkillsSystemInstruction(t *testing.T) {- t.Run("empty result yields empty pointer", func(t *testing.T) {- if got := SkillsSystemInstruction(nil); got != "" {- t.Errorf("empty result pointer = %q, want empty", got)- }- })-- t.Run("mentions dir and skill ids", func(t *testing.T) {- groups := []skills.Group{{- Dir: "/workspace",- Skills: []skills.Skill{{ID: "emoji"}, {ID: "lowercase"}},- }}- got := SkillsSystemInstruction(groups)- if !strings.Contains(got, "/workspace") || !strings.Contains(got, "emoji") || !strings.Contains(got, "lowercase") {- t.Errorf("pointer = %q, want it to mention dir and skill ids", got)- }- })-- t.Run("multiple groups produce multiple lines", func(t *testing.T) {- groups := []skills.Group{- {Dir: "/a", Skills: []skills.Skill{{ID: "s1"}}},- {Dir: "/b", Skills: []skills.Skill{{ID: "s2"}}},- }- got := SkillsSystemInstruction(groups)- if !strings.Contains(got, "/a") || !strings.Contains(got, "/b") || !strings.Contains(got, "\n") {- t.Errorf("pointer = %q, want both dirs on separate lines", got)- }- })-}--func TestJoinSystemInstruction(t *testing.T) {- cases := []struct {- base, ptr, want string- }{- {"", "", ""},- {"base only", "", "base only"},- {"", "ptr only", "ptr only"},- {"base", "ptr", "base\n\nptr"},- }- for _, c := range cases {- if got := JoinSystemInstruction(c.base, c.ptr); got != c.want {- t.Errorf("join(%q,%q) = %q, want %q", c.base, c.ptr, got, c.want)- }- }-}diff --git a/internal/harness/antigravityinteractions/workspace.go b/internal/harness/antigravityinteractions/workspace.godeleted file mode 100644index 744f016..0000000--- a/internal/harness/antigravityinteractions/workspace.go+++ /dev/null@@ -1,37 +0,0 @@-// 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 antigravityinteractions--import (- "fmt"- "strings"-)--// WorkspaceSystemInstruction builds a system-instruction snippet that orients-// the agent about its working directory.-//-// This complements the executor making WorkDir authoritative (see-// AntigravityInteractionsConfig.WorkDir): the executor guarantees commands run-// in the right place, while this tells the agent so it emits sensible paths-// (relative to the workspace, not the process root "/"). Returns "" when-// workDir is empty.-func WorkspaceSystemInstruction(workDir string) string {- if strings.TrimSpace(workDir) == "" {- return ""- }- return fmt.Sprintf("Your working directory is %s. Run commands and resolve "+- "relative paths there unless you have a specific reason to use an "+- "absolute path elsewhere.", workDir)-}diff --git a/internal/harness/harness.go b/internal/harness/harness.godeleted file mode 100644index 24b5878..0000000--- a/internal/harness/harness.go+++ /dev/null@@ -1,63 +0,0 @@-// 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 defines a common execution boundary and lifecycle hooks-// for interacting with agents, planners, or external gRPC services.-package harness--import (- "context"-- "github.com/google/ax/proto"-)--// Handler defines the streaming event hook callbacks for an execution turn.-type Handler interface {- // OnMessage is invoked when the agent generates output content during its turn.- OnMessage(ctx context.Context, execID string, step *proto.Step) error-- // OnComplete is invoked when the agent finishes its current execution turn.- OnComplete(ctx context.Context, execID string) error-}--// 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. config- // carries optional per-request configuration; it is opaque to the- // controller and interpreted by the harness implementation.- Start(ctx context.Context, conversationID string, config []byte) (Execution, error)-}--// Execution represents an active interactive session with an agent or planner.-type Execution interface {- // Run executes the session and streams events to the provided Handler.- // It blocks until the current turn completes or fails.- Run(ctx context.Context, handler Handler) error-- // Queue enqueues new input steps to be processed in the next turn.- Queue(ctx context.Context, steps ...*proto.Step) error-- // ID returns the unique execution session ID.- ID() string-- // Close cleanly releases all resources associated with the execution session.- Close(ctx context.Context) error-}diff --git a/internal/harness/harnesstest/harnesstest.go b/internal/harness/harnesstest/harnesstest.godeleted file mode 100644index 42b22bc..0000000--- a/internal/harness/harnesstest/harnesstest.go+++ /dev/null@@ -1,307 +0,0 @@-// 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 harnesstest--// Shared in-process mocks for the harness tests: a mock Substrate Control server-// (the substrate control plane), a mock HarnessService server (the harness-// inside an actor), a recording Handler, and message builders.--import (- "context"- "net"- "sync"- "testing"-- "github.com/agent-substrate/substrate/pkg/proto/ateapipb"- "github.com/google/ax/internal/harness"- "github.com/google/ax/proto"- "google.golang.org/grpc"- "google.golang.org/grpc/codes"- "google.golang.org/grpc/health"- "google.golang.org/grpc/health/grpc_health_v1"- "google.golang.org/grpc/status"-)--// mockControlServer is an in-process ateapipb.ControlServer that records the-// actor lifecycle calls SubstrateHarness makes and lets tests steer the-// CreateActor/ResumeActor responses. Only the three RPCs SubstrateHarness uses-// are implemented; the rest come from the embedded Unimplemented server.-type MockControlServer struct {- ateapipb.UnimplementedControlServer-- mu sync.Mutex- createCalls []string- resumeCalls []string- suspendCalls []string-- CreateErr error // returned from CreateActor when non-nil- ResumeIP string // AteomPodIp returned from ResumeActor- ResumeNilActor bool // when true, ResumeActor returns a nil Actor-}--func (f *MockControlServer) CreateAtespace(_ context.Context, req *ateapipb.CreateAtespaceRequest) (*ateapipb.CreateAtespaceResponse, error) {- return &ateapipb.CreateAtespaceResponse{Atespace: &ateapipb.Atespace{Name: req.GetName()}}, nil-}--func (f *MockControlServer) CreateActor(_ context.Context, req *ateapipb.CreateActorRequest) (*ateapipb.CreateActorResponse, error) {- f.mu.Lock()- f.createCalls = append(f.createCalls, req.GetActorRef().GetName())- f.mu.Unlock()- if f.CreateErr != nil {- return nil, f.CreateErr- }- return &ateapipb.CreateActorResponse{Actor: &ateapipb.Actor{ActorId: req.GetActorRef().GetName()}}, nil-}--func (f *MockControlServer) ResumeActor(_ context.Context, req *ateapipb.ResumeActorRequest) (*ateapipb.ResumeActorResponse, error) {- f.mu.Lock()- f.resumeCalls = append(f.resumeCalls, req.GetActorRef().GetName())- f.mu.Unlock()- if f.ResumeNilActor {- return &ateapipb.ResumeActorResponse{}, nil- }- return &ateapipb.ResumeActorResponse{Actor: &ateapipb.Actor{ActorId: req.GetActorRef().GetName(), AteomPodIp: f.ResumeIP}}, nil-}--func (f *MockControlServer) SuspendActor(_ context.Context, req *ateapipb.SuspendActorRequest) (*ateapipb.SuspendActorResponse, error) {- f.mu.Lock()- f.suspendCalls = append(f.suspendCalls, req.GetActorRef().GetName())- f.mu.Unlock()- return &ateapipb.SuspendActorResponse{}, nil-}--// Calls returns copies of the recorded call lists.-func (f *MockControlServer) Calls() (create, resume, suspend []string) {- f.mu.Lock()- defer f.mu.Unlock()- return append([]string(nil), f.createCalls...),- append([]string(nil), f.resumeCalls...),- append([]string(nil), f.suspendCalls...)-}--// mockHarnessServer is an in-process proto.HarnessServiceServer standing in for-// the harness running inside an actor (substrate) or a local subprocess-// (antigravity). It records the start frame and emits its configured outputs-// followed by a terminal HarnessEnd.-type MockHarnessServer struct {- proto.UnimplementedHarnessServiceServer-- // Outputs are the steps emitted (in a single Outputs frame) before the- // terminal HarnessEnd. When nil, each input is echoed as "ack: <input>".- Outputs []*proto.Step- // FailConnect makes Connect return an RPC error before any frame.- FailConnect bool- // FailFrame makes Connect terminate the turn with HarnessEnd{STATE_FAILED}.- FailFrame bool- // ErrCode is the error code used by FailFrame.- ErrCode int32- // ErrMessage is the error text used by FailConnect/FailFrame.- ErrMessage string-- mu sync.Mutex- gotConvID string- gotHarnessID string- gotAgentConfig []byte- gotInputs []string-}--func (s *MockHarnessServer) Connect(stream proto.HarnessService_ConnectServer) error {- if s.FailConnect {- return status.Error(codes.Internal, s.ErrMessage)- }-- req, err := stream.Recv()- if err != nil {- return err- }-- var inputs []string- for _, step := range req.GetStart().GetSteps() {- if contentStep := step.GetContent(); contentStep != nil {- for _, c := range contentStep.Content {- if text := c.GetText().GetText(); text != "" {- inputs = append(inputs, text)- }- }- }- }- s.mu.Lock()- s.gotConvID = req.GetConversationId()- s.gotHarnessID = req.GetAgentId()- s.gotAgentConfig = req.GetStart().GetAgentConfig()- s.gotInputs = inputs- s.mu.Unlock()-- convID := req.GetConversationId()- if s.FailFrame {- return stream.Send(&proto.HarnessResponse{- ConversationId: convID,- Type: &proto.HarnessResponse_End{- End: &proto.HarnessEnd{- State: proto.State_STATE_FAILED,- Error: &proto.Error{- Code: s.ErrCode,- Description: s.ErrMessage,- },- },- },- })- }-- steps := s.Outputs- if steps == nil {- for _, in := range inputs {- steps = append(steps, AssistantStep("ack: "+in))- }- }- if len(steps) > 0 {- if err := stream.Send(&proto.HarnessResponse{- ConversationId: convID,- Type: &proto.HarnessResponse_Outputs{- Outputs: &proto.HarnessOutputs{Steps: steps},- },- }); err != nil {- return err- }- }- return stream.Send(&proto.HarnessResponse{- ConversationId: convID,- Type: &proto.HarnessResponse_End{End: &proto.HarnessEnd{State: proto.State_STATE_COMPLETED}},- })-}--// Received returns a copy of the start frame the server received.-func (s *MockHarnessServer) Received() (convID, harnessID string, agentConfig []byte, inputs []string) {- s.mu.Lock()- defer s.mu.Unlock()- return s.gotConvID, s.gotHarnessID, append([]byte(nil), s.gotAgentConfig...), append([]string(nil), s.gotInputs...)-}--// MockHandler records the steps and completion streamed during a turn.-type MockHandler struct {- mu sync.Mutex- steps []*proto.Step- complete bool-}--var _ harness.Handler = (*MockHandler)(nil)--func (h *MockHandler) OnMessage(_ context.Context, _ string, step *proto.Step) error {- h.mu.Lock()- defer h.mu.Unlock()- h.steps = append(h.steps, step)- return nil-}--func (h *MockHandler) OnComplete(_ context.Context, _ string) error {- h.mu.Lock()- defer h.mu.Unlock()- h.complete = true- return nil-}--func (h *MockHandler) IsDone() bool {- h.mu.Lock()- defer h.mu.Unlock()- return h.complete-}--// Collected returns a copy of the steps received via OnMessage.-func (h *MockHandler) Collected() []*proto.Step {- h.mu.Lock()- defer h.mu.Unlock()- return append([]*proto.Step(nil), h.steps...)-}--// Texts returns the text content of each received step, in order.-func (h *MockHandler) Texts() []string {- h.mu.Lock()- defer h.mu.Unlock()- var out []string- for _, s := range h.steps {- if contentStep := s.GetContent(); contentStep != nil {- for _, part := range contentStep.Content {- out = append(out, part.GetText().GetText())- }- }- }- return out-}--func UserStep(text string) *proto.Step {- return &proto.Step{- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Role: "user",- Content: []*proto.Content{{Type: &proto.Content_Text{Text: &proto.TextContent{Text: text}}}},- },- },- }-}--func AssistantStep(text string) *proto.Step {- return &proto.Step{- Type: &proto.Step_Content{- Content: &proto.ContentStep{- Role: "assistant",- Content: []*proto.Content{{Type: &proto.Content_Text{Text: &proto.TextContent{Text: text}}}},- },- },- }-}--func ThoughtStep(summary string) *proto.Step {- return &proto.Step{- Type: &proto.Step_Thought{- Thought: &proto.ThoughtStep{- Summary: []*proto.Content{- {Type: &proto.Content_Text{Text: &proto.TextContent{Text: summary}}},- },- },- },- }-}--// StartHarnessServer starts a HarnessService + health server (status SERVING)-// on a random local port and returns its address.-func StartHarnessServer(t *testing.T, srv *MockHarnessServer) string {- t.Helper()- lis, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- t.Fatalf("failed to listen: %v", err)- }- s := grpc.NewServer()- proto.RegisterHarnessServiceServer(s, srv)- hs := health.NewServer()- hs.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)- grpc_health_v1.RegisterHealthServer(s, hs)- go func() { _ = s.Serve(lis) }()- t.Cleanup(s.Stop)- return lis.Addr().String()-}--// StartControlServer starts a mock Substrate Control server on a random local port.-func StartControlServer(t *testing.T, srv *MockControlServer) string {- t.Helper()- lis, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- t.Fatalf("failed to listen: %v", err)- }- s := grpc.NewServer()- ateapipb.RegisterControlServer(s, srv)- go func() { _ = s.Serve(lis) }()- t.Cleanup(s.Stop)- return lis.Addr().String()-}diff --git a/internal/harness/stream.go b/internal/harness/stream.godeleted file mode 100644index 54430d4..0000000--- a/internal/harness/stream.go+++ /dev/null@@ -1,68 +0,0 @@-// 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"- "fmt"- "io"-- "github.com/google/ax/proto"-)--// DrainStream reads from the harness gRPC stream until io.EOF, dispatching messages-// to the handler, and returns the final execution status.-func DrainStream(ctx context.Context, stream proto.HarnessService_ConnectClient, execID string, handler Handler) error {- var endState proto.State- var endErr error- hasEnd := false-- for {- resp, err := stream.Recv()- if err == io.EOF {- break- }- if err != nil {- return fmt.Errorf("gRPC harness streaming failure: %w", err)- }-- switch payload := resp.Type.(type) {- case *proto.HarnessResponse_Outputs:- for _, step := range payload.Outputs.Steps {- if err := handler.OnMessage(ctx, execID, step); err != nil {- return fmt.Errorf("failed to dispatch streamed output: %w", err)- }- }- case *proto.HarnessResponse_End:- hasEnd = true- endState = payload.End.GetState()- if endState == proto.State_STATE_FAILED {- if errDetail := payload.End.GetError(); errDetail != nil {- endErr = fmt.Errorf("harness failed: [%d] %s", errDetail.GetCode(), errDetail.GetDescription())- } else {- endErr = fmt.Errorf("harness failed with no error details")- }- }- }- }-- if !hasEnd {- return fmt.Errorf("harness stream ended without HarnessEnd frame")- }- if endState == proto.State_STATE_FAILED {- return endErr- }- return handler.OnComplete(ctx, execID)-}diff --git a/internal/harness/substrate/substrate.go b/internal/harness/substrate/substrate.godeleted file mode 100644index 15d1975..0000000--- a/internal/harness/substrate/substrate.go+++ /dev/null@@ -1,256 +0,0 @@-// 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 substrate--import (- "context"- "crypto/tls"- "errors"- "fmt"- "io"- "log/slog"- "sync"- "time"-- "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"- "go.opentelemetry.io/otel"- "google.golang.org/grpc"- "google.golang.org/grpc/codes"- "google.golang.org/grpc/credentials"- "google.golang.org/grpc/credentials/insecure"- "google.golang.org/grpc/health/grpc_health_v1"- "google.golang.org/grpc/status"-- "github.com/google/ax/internal/harness"- "github.com/google/ax/internal/ate"- "github.com/google/ax/proto"- "github.com/google/uuid"-)--// Compile-time interface assertions.-var _ harness.Harness = (*SubstrateHarness)(nil)-var _ harness.Execution = (*substrateExecution)(nil)--// healthCheckTimeout defines the maximum time Start waits for a freshly-// created/resumed actor's harness to become reachable and ready.-const healthCheckTimeout = 60 * time.Second--// SubstrateHarness manages execution in a SubstrATE sandboxed actor over gRPC HarnessService.-type SubstrateHarness struct {- harnessID string- ateClient *ate.Client- port int- dialOpts []grpc.DialOption-}--// New creates a new SubstrateHarness.-func New(harnessID string, endpoint string, namespace string, template string, port int, opts ...grpc.DialOption) (*SubstrateHarness, error) {- if port == 0 {- port = 50053 // Default HarnessService port- }- if namespace == "" {- namespace = "ax"- }- if template == "" {- template = "ax-harness-antigravity-template"- }- controlCreds := grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}))- client, err := ate.NewClient(namespace, template, endpoint, controlCreds)- if err != nil {- return nil, fmt.Errorf("failed to create ATE client: %w", err)- }- if len(opts) == 0 {- opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))- }- opts = append(opts, grpc.WithStatsHandler(otelgrpc.NewClientHandler()))- return &SubstrateHarness{- harnessID: harnessID,- ateClient: client,- port: port,- dialOpts: opts,- }, nil-}--// Start implements Harness interface. It creates/resumes the target actor.-func (h *SubstrateHarness) Start(ctx context.Context, conversationID string, config []byte) (harness.Execution, error) {- if conversationID == "" {- return nil, errors.New("SubstrateHarness needs valid conversationID")- }-- // CreateActor is idempotent here: on follow-up turns the actor was created- // (and suspended) on a previous turn, so AlreadyExists is expected and fine.- if _, err := h.ateClient.CreateActor(ctx, conversationID); err != nil && status.Code(err) != codes.AlreadyExists {- return nil, fmt.Errorf("failed to create substrate actor %s: %w", conversationID, err)- }-- // Resume the actor so it is scheduled onto a worker and gets a routable IP.- resumeResp, err := h.ateClient.ResumeActor(ctx, conversationID)- if err != nil {- return nil, fmt.Errorf("failed to resume substrate actor %s: %w", conversationID, err)- }- actor := resumeResp.Actor- if actor == nil {- return nil, fmt.Errorf("received nil actor in response for %s", conversationID)- }- if actor.AteomPodIp == "" {- return nil, fmt.Errorf("actor %s has no active worker IP address", conversationID)- }-- // Establish connection to the actor's worker IP- workerAddr := fmt.Sprintf("%s:%d", actor.AteomPodIp, h.port)- conn, err := grpc.NewClient(workerAddr, h.dialOpts...)- if err != nil {- return nil, fmt.Errorf("failed to dial remote harness service at %s: %w", workerAddr, err)- }-- // Wait for the harness to be reachable and ready before handing back the- // execution.- if err := waitForHealthy(ctx, conn, healthCheckTimeout); err != nil {- conn.Close()- return nil, fmt.Errorf("harness for %s not ready at %s: %w", conversationID, workerAddr, err)- }-- return &substrateExecution{- harness: h,- conversationID: conversationID,- execID: uuid.NewString(),- conn: conn,- client: proto.NewHarnessServiceClient(conn),- config: config,- }, nil-}--// waitForHealthy blocks until the harness behind conn reports SERVING via the-// standard gRPC health protocol until timeout. A harness that is reachable-// but does not implement the health service (Unimplemented) is treated as-// ready; connection failures (Unavailable) and NOT_SERVING are retried.-func waitForHealthy(ctx context.Context, conn *grpc.ClientConn, timeout time.Duration) error {- ctx, cancel := context.WithTimeout(ctx, timeout)- defer cancel()-- client := grpc_health_v1.NewHealthClient(conn)- const maxBackoff = 2 * time.Second- backoff := 100 * time.Millisecond- for {- resp, err := client.Check(ctx, &grpc_health_v1.HealthCheckRequest{Service: ""})- if err == nil && resp.GetStatus() == grpc_health_v1.HealthCheckResponse_SERVING {- return nil- }- if status.Code(err) == codes.Unimplemented {- // Reachable but no health service: the port is up, proceed.- return nil- }-- select {- case <-ctx.Done():- if err != nil {- return fmt.Errorf("harness not healthy within %s: %w", timeout, err)- }- return fmt.Errorf("harness not healthy within %s (last status: %s)", timeout, resp.GetStatus())- case <-time.After(backoff):- }- backoff *= 2- if backoff > maxBackoff {- backoff = maxBackoff- }- }-}--type substrateExecution struct {- harness *SubstrateHarness- conversationID string- execID string- conn *grpc.ClientConn- client proto.HarnessServiceClient- config []byte-- mu sync.Mutex- pending []*proto.Step-}--func (e *substrateExecution) ID() string {- return e.execID-}--func (e *substrateExecution) Queue(ctx context.Context, steps ...*proto.Step) error {- e.mu.Lock()- defer e.mu.Unlock()- e.pending = append(e.pending, steps...)- return nil-}--func (e *substrateExecution) Run(ctx context.Context, handler harness.Handler) error {- ctx, span := otel.Tracer("substrate-harness").Start(ctx, "Run")- defer span.End()-- e.mu.Lock()- inputs := e.pending- e.pending = nil- e.mu.Unlock()-- stream, err := e.client.Connect(ctx)- if err != nil {- return fmt.Errorf("failed to open harness service stream: %w", err)- }-- // Send a HarnessRequest to initiate the turn.- start := &proto.HarnessRequest{- ConversationId: e.conversationID,- AgentId: e.harness.harnessID,- Type: &proto.HarnessRequest_Start{- Start: &proto.HarnessStart{- AgentConfig: e.config,- Steps: inputs,- },- },- }- // A server that fails before reading the start frame makes Send/CloseSend- // report io.EOF; the real status is surfaced by DrainStream's Recv below, so- // only treat non-EOF errors as send failures.- if err := stream.Send(start); err != nil && err != io.EOF {- return fmt.Errorf("failed to send harness start: %w", err)- }-- // Close send direction to trigger server processing.- if err := stream.CloseSend(); err != nil && err != io.EOF {- return fmt.Errorf("failed to close stream send direction: %w", err)- }-- // Drain HarnessResponse frames until the terminal HarnessEnd.- return harness.DrainStream(ctx, stream, e.execID, handler)-}--func (e *substrateExecution) Close(ctx context.Context) error {- // Close connection- if e.conn != nil {- e.conn.Close()- }-- // Suspend actor to return resource to standard standby pool- slog.InfoContext(ctx, "Suspending SubstrATE actor",- slog.String("conversation_id", e.conversationID),- slog.String("exec_id", e.execID),- )- suspendCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()- if _, err := e.harness.ateClient.SuspendActor(suspendCtx, e.conversationID); err != nil {- slog.ErrorContext(ctx, "Failed to suspend SubstrATE actor",- slog.String("conversation_id", e.conversationID),- slog.Any("error", err),- )- }-- return nil-}diff --git a/internal/harness/substrate/substrate_test.go b/internal/harness/substrate/substrate_test.godeleted file mode 100644index 6b2a668..0000000--- a/internal/harness/substrate/substrate_test.go+++ /dev/null@@ -1,290 +0,0 @@-// 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 substrate--import (- "bytes"- "context"- "net"- "slices"- "strconv"- "strings"- "testing"- "time"-- "github.com/google/ax/internal/harness/harnesstest"- "github.com/google/ax/internal/ate"- "google.golang.org/grpc"- "google.golang.org/grpc/codes"- "google.golang.org/grpc/credentials/insecure"- "google.golang.org/grpc/health"- "google.golang.org/grpc/health/grpc_health_v1"- "google.golang.org/grpc/status"-)--var substrateAgentConfig = []byte(`{"model":"gemini-2.5-pro"}`)--// startHealthTestServer starts a gRPC server on a random local port. If hs is-// non-nil the standard health service is registered. Returns the listen address.-func startHealthTestServer(t *testing.T, hs *health.Server) string {- t.Helper()- lis, err := net.Listen("tcp", "localhost:0")- if err != nil {- t.Fatalf("failed to listen: %v", err)- }- s := grpc.NewServer()- if hs != nil {- grpc_health_v1.RegisterHealthServer(s, hs)- }- go func() {- _ = s.Serve(lis)- }()- t.Cleanup(s.Stop)- return lis.Addr().String()-}--func dialTestConn(t *testing.T, addr string) *grpc.ClientConn {- t.Helper()- conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))- if err != nil {- t.Fatalf("failed to dial %s: %v", addr, err)- }- t.Cleanup(func() { conn.Close() })- return conn-}--func TestWaitForHealthy_Serving(t *testing.T) {- hs := health.NewServer()- hs.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)- conn := dialTestConn(t, startHealthTestServer(t, hs))-- if err := waitForHealthy(context.Background(), conn, 5*time.Second); err != nil {- t.Fatalf("expected healthy, got %v", err)- }-}--func TestWaitForHealthy_UnimplementedProceeds(t *testing.T) {- // Server is up but does not register the health service.- conn := dialTestConn(t, startHealthTestServer(t, nil))-- if err := waitForHealthy(context.Background(), conn, 5*time.Second); err != nil {- t.Fatalf("expected to proceed when health is unimplemented, got %v", err)- }-}--func TestWaitForHealthy_TimesOut(t *testing.T) {- hs := health.NewServer()- hs.SetServingStatus("", grpc_health_v1.HealthCheckResponse_NOT_SERVING)- conn := dialTestConn(t, startHealthTestServer(t, hs))-- if err := waitForHealthy(context.Background(), conn, 500*time.Millisecond); err == nil {- t.Fatal("expected timeout error while NOT_SERVING, got nil")- }-}--func TestWaitForHealthy_StatusChange(t *testing.T) {- hs := health.NewServer()- hs.SetServingStatus("", grpc_health_v1.HealthCheckResponse_NOT_SERVING)- conn := dialTestConn(t, startHealthTestServer(t, hs))-- go func() {- time.Sleep(150 * time.Millisecond)- hs.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)- }()-- if err := waitForHealthy(context.Background(), conn, 5*time.Second); err != nil {- t.Fatalf("expected healthy after status flip, got %v", err)- }-}--func TestWaitForHealthy_ServerDown(t *testing.T) {- // Reserve a port then release it so nothing is listening there.- lis, err := net.Listen("tcp", "localhost:0")- if err != nil {- t.Fatalf("failed to listen: %v", err)- }- addr := lis.Addr().String()- lis.Close()- conn := dialTestConn(t, addr)-- if err := waitForHealthy(context.Background(), conn, 500*time.Millisecond); err == nil {- t.Fatal("expected timeout error when server is down, got nil")- }-}--// newTestSubstrateHarness builds a SubstrateHarness wired to the mock control-// server and the mock harness server. It constructs the struct directly (rather-// than via NewSubstrateHarness) so the control client can use insecure-// credentials instead of the TLS that NewSubstrateHarness hard-codes.-func newTestSubstrateHarness(t *testing.T, ctrlAddr, harnessAddr string) *SubstrateHarness {- t.Helper()- _, portStr, err := net.SplitHostPort(harnessAddr)- if err != nil {- t.Fatalf("bad harness addr %q: %v", harnessAddr, err)- }- port, err := strconv.Atoi(portStr)- if err != nil {- t.Fatalf("bad harness port %q: %v", portStr, err)- }- client, err := ate.NewClient("ax", "antigravity-template", ctrlAddr,- grpc.WithTransportCredentials(insecure.NewCredentials()))- if err != nil {- t.Fatalf("failed to create ate client: %v", err)- }- return &SubstrateHarness{- harnessID: "antigravity",- ateClient: client,- port: port,- dialOpts: []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())},- }-}--// Test full SubstrateHarness Start -> Run -> Close flow against the shared-// in-process mocks (see mocks_test.go).-// They lock in the wiring that a substrate bump or an ax-side change could silently-// break: create/resume idempotency, worker-IP extraction, the health gate, the-// Connect streaming protocol, and suspend-on-close.-func TestSubstrateHarness_StartAndRun(t *testing.T) {- ctrl := &harnesstest.MockControlServer{ResumeIP: "127.0.0.1"}- srv := &harnesstest.MockHarnessServer{}- h := newTestSubstrateHarness(t, harnesstest.StartControlServer(t, ctrl), harnesstest.StartHarnessServer(t, srv))-- ctx := context.Background()- exec, err := h.Start(ctx, "conv-1", substrateAgentConfig)- if err != nil {- t.Fatalf("Start: %v", err)- }- if err := exec.Queue(ctx, harnesstest.UserStep("hi")); err != nil {- t.Fatalf("Queue: %v", err)- }- handler := &harnesstest.MockHandler{}- if err := exec.Run(ctx, handler); err != nil {- t.Fatalf("Run: %v", err)- }-- // The harness server received the start frame with the right identifiers.- convID, harnessID, agentConfig, inputs := srv.Received()- if convID != "conv-1" || harnessID != "antigravity" {- t.Errorf("server got convID=%q harnessID=%q, want conv-1/antigravity", convID, harnessID)- }- if !bytes.Equal(agentConfig, substrateAgentConfig) {- t.Errorf("server got agentConfig=%q, want %q", agentConfig, substrateAgentConfig)- }- if !slices.Equal(inputs, []string{"hi"}) {- t.Errorf("server got inputs=%v, want [hi]", inputs)- }-- // The handler streamed the output and completed.- if !handler.IsDone() {- t.Error("handler did not complete")- }- if got := handler.Texts(); !slices.Equal(got, []string{"ack: hi"}) {- t.Errorf("handler messages=%v, want [ack: hi]", got)- }-- // CreateActor then ResumeActor ran for the conversation; no suspend yet.- create, resume, suspend := ctrl.Calls()- want := []string{"conv-1"}- if !slices.Equal(create, want) || !slices.Equal(resume, want) {- t.Errorf("create=%v resume=%v, want %v each", create, resume, want)- }- if len(suspend) != 0 {- t.Errorf("suspend called before Close: %v", suspend)- }-- // Close suspends the actor.- if err := exec.Close(ctx); err != nil {- t.Fatalf("Close: %v", err)- }- if _, _, suspend = ctrl.Calls(); !slices.Equal(suspend, want) {- t.Errorf("suspend=%v, want %v", suspend, want)- }-}--func TestSubstrateHarness_CreateAlreadyExistsTolerated(t *testing.T) {- ctrl := &harnesstest.MockControlServer{- ResumeIP: "127.0.0.1",- CreateErr: status.Error(codes.AlreadyExists, "exists"),- }- h := newTestSubstrateHarness(t, harnesstest.StartControlServer(t, ctrl), harnesstest.StartHarnessServer(t, &harnesstest.MockHarnessServer{}))-- ctx := context.Background()- exec, err := h.Start(ctx, "conv-1", substrateAgentConfig)- if err != nil {- t.Fatalf("Start should tolerate AlreadyExists: %v", err)- }- t.Cleanup(func() { _ = exec.Close(ctx) })-- if err := exec.Queue(ctx, harnesstest.UserStep("hi")); err != nil {- t.Fatalf("Queue: %v", err)- }- handler := &harnesstest.MockHandler{}- if err := exec.Run(ctx, handler); err != nil {- t.Fatalf("Run: %v", err)- }- if !handler.IsDone() {- t.Error("handler did not complete")- }- if _, resume, _ := ctrl.Calls(); !slices.Equal(resume, []string{"conv-1"}) {- t.Errorf("resume=%v, want [conv-1]", resume)- }-}--func TestSubstrateHarness_ResumeNoWorkerIP(t *testing.T) {- ctrl := &harnesstest.MockControlServer{ResumeIP: ""} // empty AteomPodIp- h := newTestSubstrateHarness(t, harnesstest.StartControlServer(t, ctrl), harnesstest.StartHarnessServer(t, &harnesstest.MockHarnessServer{}))-- _, err := h.Start(context.Background(), "conv-1", substrateAgentConfig)- if err == nil {- t.Fatal("expected error for empty worker IP, got nil")- }- if !strings.Contains(err.Error(), "no active worker IP") {- t.Errorf("error = %v, want it to mention 'no active worker IP'", err)- }-}--func TestSubstrateHarness_ResumeNilActor(t *testing.T) {- ctrl := &harnesstest.MockControlServer{ResumeNilActor: true}- h := newTestSubstrateHarness(t, harnesstest.StartControlServer(t, ctrl), harnesstest.StartHarnessServer(t, &harnesstest.MockHarnessServer{}))-- _, err := h.Start(context.Background(), "conv-1", substrateAgentConfig)- if err == nil {- t.Fatal("expected error for nil actor, got nil")- }- if !strings.Contains(err.Error(), "nil actor") {- t.Errorf("error = %v, want it to mention 'nil actor'", err)- }-}--func TestSubstrateHarness_HarnessFailedFrame(t *testing.T) {- ctrl := &harnesstest.MockControlServer{ResumeIP: "127.0.0.1"}- srv := &harnesstest.MockHarnessServer{FailFrame: true, ErrCode: 13, ErrMessage: "boom"}- h := newTestSubstrateHarness(t, harnesstest.StartControlServer(t, ctrl), harnesstest.StartHarnessServer(t, srv))-- ctx := context.Background()- exec, err := h.Start(ctx, "conv-1", substrateAgentConfig)- if err != nil {- t.Fatalf("Start: %v", err)- }- t.Cleanup(func() { _ = exec.Close(ctx) })- if err := exec.Queue(ctx, harnesstest.UserStep("hi")); err != nil {- t.Fatalf("Queue: %v", err)- }- if err := exec.Run(ctx, &harnesstest.MockHandler{}); err == nil {- t.Fatal("expected error from failed harness frame, got nil")- } else if !strings.Contains(err.Error(), "harness failed") {- t.Errorf("error = %v, want it to mention 'harness failed'", err)- }-}diff --git a/internal/metadata/server.go b/internal/metadata/server.gonew file mode 100644index 0000000..fb4feba--- /dev/null+++ b/internal/metadata/server.go@@ -0,0 +1,238 @@+// 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 metadata++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "net"+ "net/http"+ "strings"+ "sync"++ "github.com/agent-substrate/env/guest"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "google.golang.org/grpc"+ "gopkg.in/yaml.v3"+)++// Server is the cloud-style metadata server running inside the task actor container,+// multiplexing HTTP metadata endpoints and guest gRPC daemon services on a single port.+type Server struct {+ port int+ server *http.Server+ grpcServer *grpc.Server+ grpcCleanup func()+ mu sync.RWMutex+ task *v1alpha1.Task+ workspaces []*v1alpha1.Workspace+ workspaceReady bool+}++// ServerOptions configures optional settings for the metadata and guest server.+type ServerOptions struct {+ WorkspacePath string+ LogDir string+}++// NewServer creates a new metadata and guest server serving the task and its+// bound workspaces, in the task's declaration order. Nil workspaces are dropped.+func NewServer(port int, task *v1alpha1.Task, workspaces []*v1alpha1.Workspace, opts ...ServerOptions) *Server {+ if port <= 0 {+ port = 9999+ }+ s := &Server{+ port: port,+ task: task,+ workspaces: compactWorkspaces(workspaces),+ }++ var opt ServerOptions+ if len(opts) > 0 {+ opt = opts[0]+ }++ // Guest services expose process execution and file access inside the container,+ // so they are only served when the task opts in via spec.debug.+ if task.GetSpec().GetDebug() {+ guestCfg := guest.DefaultConfig()+ if opt.WorkspacePath != "" {+ guestCfg.Workspace = opt.WorkspacePath+ }+ if opt.LogDir != "" {+ guestCfg.LogDir = opt.LogDir+ }++ grpcServer, grpcCleanup, err := guest.NewServer(guestCfg)+ if err != nil {+ slog.Error("failed to initialize guest gRPC server", "error", err)+ } else {+ s.grpcServer = grpcServer+ s.grpcCleanup = grpcCleanup+ slog.Info("guest services enabled (spec.debug is true)")+ }+ } else {+ slog.Info("guest services disabled; set spec.debug: true on the Task to enable ax ssh")+ }++ mux := http.NewServeMux()+ mux.HandleFunc("/healthz", s.handleHealthz)+ mux.HandleFunc("/readyz", s.handleReadyz)++ // Metadata endpoints:+ // /metadata/v1alpha1/ax/task the Task+ // /metadata/v1alpha1/ax/workspaces every bound Workspace, as a YAML stream+ mux.HandleFunc("/metadata/v1alpha1/ax/task", s.handleTask)+ mux.HandleFunc("/metadata/v1alpha1/ax/workspaces", s.handleWorkspaces)++ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if s.grpcServer != nil && r.ProtoMajor == 2 && strings.HasPrefix(r.Header.Get("Content-Type"), "application/grpc") {+ s.grpcServer.ServeHTTP(w, r)+ return+ }+ mux.ServeHTTP(w, r)+ })++ s.server = &http.Server{+ Addr: fmt.Sprintf(":%d", port),+ Handler: handler,+ }+ s.server.Protocols = new(http.Protocols)+ s.server.Protocols.SetHTTP1(true)+ s.server.Protocols.SetUnencryptedHTTP2(true)++ return s+}++// Start begins serving the metadata HTTP and guest gRPC service in a background goroutine.+func (s *Server) Start() error {+ lis, err := net.Listen("tcp", s.server.Addr)+ if err != nil {+ return fmt.Errorf("metadata server listening on %s: %w", s.server.Addr, err)+ }++ slog.Info("metadata and guest server started", "addr", s.server.Addr)++ go func() {+ if err := s.server.Serve(lis); err != nil && !errors.Is(err, http.ErrServerClosed) {+ slog.Error("metadata server error", "error", err)+ }+ }()++ return nil+}++// Stop gracefully stops the metadata and guest server.+func (s *Server) Stop(ctx context.Context) error {+ if s.grpcCleanup != nil {+ s.grpcCleanup()+ }+ return s.server.Shutdown(ctx)+}++// UpdateState allows dynamic updates to the current Task and Workspaces.+func (s *Server) UpdateState(task *v1alpha1.Task, workspaces []*v1alpha1.Workspace) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.task = task+ s.workspaces = compactWorkspaces(workspaces)+}++// compactWorkspaces returns a copy of workspaces without nil entries.+func compactWorkspaces(workspaces []*v1alpha1.Workspace) []*v1alpha1.Workspace {+ out := make([]*v1alpha1.Workspace, 0, len(workspaces))+ for _, ws := range workspaces {+ if ws != nil {+ out = append(out, ws)+ }+ }+ return out+}++// SetWorkspaceReady updates whether the maiden run workspace setup has completed.+func (s *Server) SetWorkspaceReady(ready bool) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.workspaceReady = ready+}++// IsWorkspaceReady returns whether the workspace setup has completed.+func (s *Server) IsWorkspaceReady() bool {+ s.mu.RLock()+ defer s.mu.RUnlock()+ return s.workspaceReady+}++func (s *Server) handleHealthz(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("ok\n"))+}++func (s *Server) handleReadyz(w http.ResponseWriter, r *http.Request) {+ s.mu.RLock()+ ready := s.workspaceReady+ s.mu.RUnlock()++ if !ready {+ http.Error(w, "workspace initializing", http.StatusServiceUnavailable)+ return+ }++ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("ok\n"))+}++func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) {+ s.mu.RLock()+ task := s.task+ s.mu.RUnlock()++ if task == nil {+ http.Error(w, "task metadata not available", http.StatusNotFound)+ return+ }++ w.Header().Set("Content-Type", "application/yaml")+ if err := yaml.NewEncoder(w).Encode(task); err != nil {+ http.Error(w, err.Error(), http.StatusInternalServerError)+ }+}++// handleWorkspaces serves every bound workspace as a multi-document YAML stream+// in the task's declaration order.+func (s *Server) handleWorkspaces(w http.ResponseWriter, r *http.Request) {+ s.mu.RLock()+ workspaces := s.workspaces+ s.mu.RUnlock()++ if len(workspaces) == 0 {+ http.Error(w, "workspace metadata not available", http.StatusNotFound)+ return+ }++ w.Header().Set("Content-Type", "application/yaml")+ enc := yaml.NewEncoder(w)+ for _, ws := range workspaces {+ if err := enc.Encode(ws); err != nil {+ http.Error(w, err.Error(), http.StatusInternalServerError)+ return+ }+ }+ if err := enc.Close(); err != nil {+ http.Error(w, err.Error(), http.StatusInternalServerError)+ }+}diff --git a/internal/metadata/server_test.go b/internal/metadata/server_test.gonew file mode 100644index 0000000..7564d4d--- /dev/null+++ b/internal/metadata/server_test.go@@ -0,0 +1,204 @@+// 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 metadata_test++import (+ "context"+ "io"+ "net/http"+ "testing"+ "time"++ ateenvv1alpha "github.com/agent-substrate/env/proto/ateenv/v1alpha"+ "github.com/google/ax/internal/metadata"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "google.golang.org/grpc"+ "google.golang.org/grpc/credentials/insecure"+ "gopkg.in/yaml.v3"+)++func TestMetadataServer(t *testing.T) {+ task := &v1alpha1.Task{+ ApiVersion: v1alpha1.APIVersion,+ Kind: v1alpha1.KindTask,+ Metadata: &v1alpha1.ObjectMeta{+ Name: "task123",+ Atespace: "default",+ },+ Spec: &v1alpha1.TaskSpec{+ Image: "ghcr.io/test/img",+ Debug: true,+ },+ Status: &v1alpha1.TaskStatus{+ Id: "task-task123-1",+ Phase: "Running",+ },+ }++ ws := &v1alpha1.Workspace{+ ApiVersion: v1alpha1.APIVersion,+ Kind: v1alpha1.KindWorkspace,+ Metadata: &v1alpha1.ObjectMeta{+ Name: "ws-default",+ Atespace: "default",+ },+ Spec: &v1alpha1.WorkspaceSpec{},+ }++ ws2 := &v1alpha1.Workspace{+ ApiVersion: v1alpha1.APIVersion,+ Kind: v1alpha1.KindWorkspace,+ Metadata: &v1alpha1.ObjectMeta{Name: "ws-tools", Atespace: "default"},+ Spec: &v1alpha1.WorkspaceSpec{},+ }++ srv := metadata.NewServer(9999, task, []*v1alpha1.Workspace{ws, ws2})+ if err := srv.Start(); err != nil {+ t.Fatalf("failed to start server: %v", err)+ }+ defer srv.Stop(context.Background())++ // Wait briefly for listen+ time.Sleep(50 * time.Millisecond)++ // Test /healthz+ resp, err := http.Get("http://127.0.0.1:9999/healthz")+ if err != nil {+ t.Fatalf("healthz request failed: %v", err)+ }+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("expected 200 OK, got %d", resp.StatusCode)+ }++ // Test /readyz before workspace ready+ resp, err = http.Get("http://127.0.0.1:9999/readyz")+ if err != nil {+ t.Fatalf("readyz request failed: %v", err)+ }+ if resp.StatusCode != http.StatusServiceUnavailable {+ t.Fatalf("expected 503 Service Unavailable before setup, got %d", resp.StatusCode)+ }++ // Mark workspace ready+ srv.SetWorkspaceReady(true)++ // Test /readyz after workspace ready+ resp, err = http.Get("http://127.0.0.1:9999/readyz")+ if err != nil {+ t.Fatalf("readyz request failed: %v", err)+ }+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("expected 200 OK after setup, got %d", resp.StatusCode)+ }++ // Test /metadata/v1alpha1/ax/task+ resp, err = http.Get("http://127.0.0.1:9999/metadata/v1alpha1/ax/task")+ if err != nil {+ t.Fatalf("get task metadata failed: %v", err)+ }+ defer resp.Body.Close()++ body, _ := io.ReadAll(resp.Body)+ var fetchedTask v1alpha1.Task+ if err := yaml.Unmarshal(body, &fetchedTask); err != nil {+ t.Fatalf("unmarshaling task yaml: %v", err)+ }+ if fetchedTask.Metadata.Name != "task123" {+ t.Errorf("expected task name 'task123', got %s", fetchedTask.Metadata.Name)+ }++ // Test /metadata/v1alpha1/ax/workspaces returns every bound workspace in order+ resp, err = http.Get("http://127.0.0.1:9999/metadata/v1alpha1/ax/workspaces")+ if err != nil {+ t.Fatalf("get workspaces metadata failed: %v", err)+ }+ defer resp.Body.Close()+ var names []string+ dec := yaml.NewDecoder(resp.Body)+ for {+ var doc v1alpha1.Workspace+ if err := dec.Decode(&doc); err != nil {+ if err == io.EOF {+ break+ }+ t.Fatalf("decoding workspaces stream: %v", err)+ }+ names = append(names, doc.Metadata.Name)+ }+ if len(names) != 2 || names[0] != "ws-default" || names[1] != "ws-tools" {+ t.Errorf("expected workspaces [ws-default ws-tools], got %v", names)+ }++ // Test multiplexed gRPC ProcessService on the same port+ grpcConn, err := grpc.NewClient("127.0.0.1:9999", grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ t.Fatalf("dialing gRPC: %v", err)+ }+ defer grpcConn.Close()++ procClient := ateenvv1alpha.NewProcessServiceClient(grpcConn)+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()++ startResp, err := procClient.StartProcess(ctx, &ateenvv1alpha.StartProcessRequest{+ Command: []string{"echo", "hello-from-guest"},+ })+ if err != nil {+ t.Fatalf("StartProcess via multiplexed port failed: %v", err)+ }+ if startResp.GetProcessId() == "" {+ t.Errorf("expected non-empty process ID")+ }+}++func TestMetadataServer_GuestServicesRequireDebug(t *testing.T) {+ task := &v1alpha1.Task{+ Metadata: &v1alpha1.ObjectMeta{Name: "no-debug", Atespace: "default"},+ Spec: &v1alpha1.TaskSpec{Image: "ghcr.io/test/img"},+ }++ srv := metadata.NewServer(9998, task, nil)+ if err := srv.Start(); err != nil {+ t.Fatalf("failed to start server: %v", err)+ }+ defer srv.Stop(context.Background())+ time.Sleep(100 * time.Millisecond)++ // HTTP metadata still works.+ resp, err := http.Get("http://127.0.0.1:9998/metadata/v1alpha1/ax/task")+ if err != nil {+ t.Fatalf("task metadata request failed: %v", err)+ }+ resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("expected 200 from task metadata, got %d", resp.StatusCode)+ }++ // Guest gRPC is not served.+ grpcConn, err := grpc.NewClient("127.0.0.1:9998", grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ t.Fatalf("failed to create grpc client: %v", err)+ }+ defer grpcConn.Close()++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ _, err = ateenvv1alpha.NewProcessServiceClient(grpcConn).StartProcess(ctx, &ateenvv1alpha.StartProcessRequest{+ Command: []string{"echo", "hi"},+ })+ if err == nil {+ t.Fatalf("expected StartProcess to fail when spec.debug is false")+ }+}diff --git a/internal/model/client.go b/internal/model/client.gonew file mode 100644index 0000000..f5884d7--- /dev/null+++ b/internal/model/client.go@@ -0,0 +1,622 @@+// 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 model++import (+ "bytes"+ "context"+ "crypto/tls"+ "crypto/x509"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "os"+ "os/exec"+ "strings"+ "time"++ "github.com/google/ax/internal/store"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "google.golang.org/protobuf/types/known/structpb"+)++// Supported providers and default models+const (+ ProviderGoogle = "google"++ DefaultModel = "gemini-3.8-flash"+ DefaultModelResourceName = "default-model"+ DefaultAtespace = "default"+ DefaultSecretName = "gemini-api-secret"+ DefaultSecretKey = "GEMINI_API_KEY"+)++// systemInstructionParam is the Parameters key holding a default system+// instruction. It is not a generation parameter, so it is lifted out of the map.+const systemInstructionParam = "systemInstruction"++// SecretKeyRef references a secret key for authentication.+type SecretKeyRef = v1alpha1.SecretKeyRef++// Config specifies the configuration for the model client.+// It maps directly to the common Model CRD (v1alpha1.Model / v1alpha1.ModelSpec)+// with additional client runtime options (API keys, endpoints, timeouts).+type Config struct {+ Name string `json:"name,omitempty" yaml:"name,omitempty"`+ Atespace string `json:"atespace,omitempty" yaml:"atespace,omitempty"`+ Provider string `json:"provider" yaml:"provider"`+ Model string `json:"model,omitempty" yaml:"model,omitempty"`+ // Parameters are provider-specific generation settings passed through to the+ // model API, for example temperature or maxOutputTokens for Gemini. A+ // systemInstruction entry is sent as the system instruction rather than as a+ // generation parameter.+ Parameters map[string]any `json:"parameters,omitempty" yaml:"parameters,omitempty"`+ SecretKey *SecretKeyRef `json:"secretKey,omitempty" yaml:"secretKey,omitempty"`+ APIKey string `json:"apiKey,omitempty" yaml:"apiKey,omitempty"`+ BaseURL string `json:"baseURL,omitempty" yaml:"baseURL,omitempty"`+ DisableRemote bool `json:"disableRemote,omitempty" yaml:"disableRemote,omitempty"`+}++// ConfigFromSpec creates a Config from a v1alpha1.ModelSpec.+func ConfigFromSpec(spec *v1alpha1.ModelSpec) Config {+ if spec == nil {+ return DefaultConfig()+ }+ secKey := spec.SecretKey+ if secKey == nil {+ secKey = &SecretKeyRef{+ Name: DefaultSecretName,+ Key: DefaultSecretKey,+ }+ }+ return Config{+ Name: DefaultModelResourceName,+ Atespace: DefaultAtespace,+ Provider: spec.Provider,+ Model: spec.Model,+ Parameters: spec.GetParameters().AsMap(),+ SecretKey: secKey,+ }+}++// ConfigFromCRD creates a Config from a v1alpha1.Model resource.+func ConfigFromCRD(m *v1alpha1.Model) Config {+ if m == nil {+ return DefaultConfig()+ }+ cfg := ConfigFromSpec(m.Spec)+ if m.Metadata != nil {+ if m.Metadata.Name != "" {+ cfg.Name = m.Metadata.Name+ }+ if m.Metadata.Atespace != "" {+ cfg.Atespace = m.Metadata.Atespace+ }+ }+ return cfg+}++// DefaultConfig returns the default configuration targeting "default-model" with Gemini 3.8 Flash.+func DefaultConfig() Config {+ return Config{+ Name: DefaultModelResourceName,+ Atespace: DefaultAtespace,+ Provider: ProviderGoogle,+ Model: DefaultModel,+ SecretKey: &SecretKeyRef{+ Name: DefaultSecretName,+ Key: DefaultSecretKey,+ },+ }+}++// GenerateRequest specifies the input for model inference.+type GenerateRequest struct {+ Model string `json:"model,omitempty"`+ Prompt string `json:"prompt"`+ SystemInstruction string `json:"systemInstruction,omitempty"`+ Temperature float64 `json:"temperature,omitempty"`+ MaxTokens int `json:"maxTokens,omitempty"`+}++// GenerateResponse holds the completion output and token statistics.+type GenerateResponse struct {+ Model string `json:"model"`+ Content string `json:"content"`+ Usage UsageStats `json:"usage"`+}++// UsageStats provides token counts for the inference call.+type UsageStats struct {+ PromptTokens int `json:"promptTokens"`+ CompletionTokens int `json:"completionTokens"`+ TotalTokens int `json:"totalTokens"`+}++// SecretResolverFunc is a callback function for resolving secrets by name and key.+type SecretResolverFunc func(secretName, key string) (string, error)++// Client is an LLM client that executes inference using its configured Config.+// System components like Workspace use Client directly without needing a model server.+type Client struct {+ cfg Config+ httpClient *http.Client+ secretResolver SecretResolverFunc+}++// Option configures Client runtime behaviors.+type Option func(*Client)++// WithAPIKey sets or overrides the provider API key.+func WithAPIKey(key string) Option {+ return func(c *Client) {+ c.cfg.APIKey = key+ }+}++// WithSecretKey configures a secret key reference for resolving the API key.+func WithSecretKey(name, key string) Option {+ return func(c *Client) {+ c.cfg.SecretKey = &SecretKeyRef{Name: name, Key: key}+ if resolved := c.resolveAPIKey(); resolved != "" {+ c.cfg.APIKey = resolved+ }+ }+}++// WithSecretResolver sets a custom secret resolver callback.+func WithSecretResolver(fn SecretResolverFunc) Option {+ return func(c *Client) {+ c.secretResolver = fn+ }+}++// WithStore instructs the client constructor to load configuration from the store for the given model.+// If modelName is empty, it defaults to "default-model". If atespace is empty, it defaults to "default".+func WithStore(ctx context.Context, s store.Store, atespace, modelName string) Option {+ return func(c *Client) {+ if modelName == "" {+ modelName = DefaultModelResourceName+ }+ if atespace == "" {+ atespace = DefaultAtespace+ }+ if s != nil {+ m, err := s.GetModel(ctx, atespace, modelName)+ if err == nil && m != nil {+ c.cfg = ConfigFromCRD(m)+ }+ }+ }+}++// WithBaseURL overrides the provider base URL (useful for testing or local endpoints).+func WithBaseURL(url string) Option {+ return func(c *Client) {+ c.cfg.BaseURL = strings.TrimRight(url, "/")+ }+}++// WithHTTPClient sets a custom http.Client.+func WithHTTPClient(client *http.Client) Option {+ return func(c *Client) {+ if client != nil {+ c.httpClient = client+ }+ }+}++// WithDisableRemote forces local fallback generation without remote network calls.+func WithDisableRemote(disable bool) Option {+ return func(c *Client) {+ c.cfg.DisableRemote = disable+ }+}++// NewClient creates a new model client using the provided Config.+func NewClient(cfg Config, opts ...Option) *Client {+ if cfg.Name == "" {+ cfg.Name = DefaultModelResourceName+ }+ if cfg.Atespace == "" {+ cfg.Atespace = DefaultAtespace+ }+ if cfg.Model == "" {+ cfg.Model = DefaultModel+ }+ if cfg.Provider == "" {+ cfg.Provider = ProviderGoogle+ }+ if cfg.SecretKey == nil && (cfg.Name == DefaultModelResourceName || cfg.Name == "") {+ cfg.SecretKey = &SecretKeyRef{+ Name: DefaultSecretName,+ Key: DefaultSecretKey,+ }+ }++ c := &Client{+ cfg: cfg,+ httpClient: &http.Client{+ Timeout: 60 * time.Second,+ },+ }++ for _, opt := range opts {+ opt(c)+ }++ if c.cfg.APIKey == "" {+ c.cfg.APIKey = c.resolveAPIKey()+ }++ return c+}++// resolveAPIKey resolves the API key from explicit config or Kubernetes secrets.+func (c *Client) resolveAPIKey() string {+ if c.cfg.APIKey != "" {+ return c.cfg.APIKey+ }++ if c.cfg.SecretKey == nil {+ return ""+ }++ // 1. Custom secret resolver function if provided (e.g. for testing)+ if c.secretResolver != nil {+ if val, err := c.secretResolver(c.cfg.SecretKey.Name, c.cfg.SecretKey.Key); err == nil && val != "" {+ return val+ }+ }++ // 2. Fetch from Kubernetes Secret+ namespace := c.cfg.Atespace+ if namespace == "" {+ namespace = DefaultAtespace+ }+ val, err := GetKubernetesSecret(context.Background(), namespace, c.cfg.SecretKey.Name, c.cfg.SecretKey.Key)+ if err == nil && val != "" {+ return val+ }++ return ""+}++// GetKubernetesSecret retrieves a secret from the Kubernetes API or kubectl CLI.+func GetKubernetesSecret(ctx context.Context, namespace, secretName, key string) (string, error) {+ if secretName == "" || key == "" {+ return "", fmt.Errorf("secret name and key must not be empty")+ }+ if namespace == "" {+ namespace = DefaultAtespace+ }++ // 1. In-cluster Kubernetes API (inside pod)+ if k8sHost := os.Getenv("KUBERNETES_SERVICE_HOST"); k8sHost != "" {+ k8sPort := os.Getenv("KUBERNETES_SERVICE_PORT")+ if k8sPort == "" {+ k8sPort = "443"+ }++ tokenPath := "/var/run/secrets/kubernetes.io/serviceaccount/token"+ tokenData, err := os.ReadFile(tokenPath)+ if err == nil {+ token := strings.TrimSpace(string(tokenData))++ // If namespace was not specified, use pod's serviceaccount namespace+ if namespace == "" {+ if nsData, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); err == nil {+ if ns := strings.TrimSpace(string(nsData)); ns != "" {+ namespace = ns+ }+ }+ }++ caCertPool := x509.NewCertPool()+ if caData, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"); err == nil {+ caCertPool.AppendCertsFromPEM(caData)+ }++ tr := &http.Transport{+ TLSClientConfig: &tls.Config{+ RootCAs: caCertPool,+ },+ }+ k8sClient := &http.Client{+ Transport: tr,+ Timeout: 10 * time.Second,+ }++ url := fmt.Sprintf("https://%s:%s/api/v1/namespaces/%s/secrets/%s", k8sHost, k8sPort, namespace, secretName)+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)+ if err == nil {+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("Accept", "application/json")+ resp, err := k8sClient.Do(req)+ if err == nil {+ defer resp.Body.Close()+ if resp.StatusCode == http.StatusOK {+ var secretObj struct {+ Data map[string]string `json:"data"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&secretObj); err == nil {+ if encoded, ok := secretObj.Data[key]; ok {+ decoded, err := base64.StdEncoding.DecodeString(encoded)+ if err == nil {+ return strings.TrimSpace(string(decoded)), nil+ }+ }+ }+ }+ }+ }+ }+ }++ // 2. Fallback to kubectl CLI (for local development outside cluster)+ cmd := exec.CommandContext(ctx, "kubectl", "get", "secret", secretName, "-n", namespace,+ "-o", fmt.Sprintf("jsonpath={.data.%s}", key))+ out, err := cmd.Output()+ if err == nil {+ raw := strings.TrimSpace(string(out))+ if raw != "" {+ decoded, err := base64.StdEncoding.DecodeString(raw)+ if err == nil {+ return strings.TrimSpace(string(decoded)), nil+ }+ }+ }++ return "", fmt.Errorf("kubernetes secret %s/%s with key %s not found", namespace, secretName, key)+}++// NewClientFromSpec creates a new model client from a v1alpha1.ModelSpec.+func NewClientFromSpec(spec *v1alpha1.ModelSpec, opts ...Option) *Client {+ return NewClient(ConfigFromSpec(spec), opts...)+}++// NewClientFromCRD creates a new model client from a v1alpha1.Model CRD resource.+func NewClientFromCRD(m *v1alpha1.Model, opts ...Option) *Client {+ if m == nil {+ return NewDefaultClient(opts...)+ }+ return NewClient(ConfigFromCRD(m), opts...)+}++// NewDefaultClient creates a model client configured with the "default-model" resource and Gemini 3.8 Flash.+func NewDefaultClient(opts ...Option) *Client {+ return NewClient(DefaultConfig(), opts...)+}++// NewClientFromStore creates a model client by reading the model CRD from the store.+// If name is empty, it defaults to "default-model". If atespace is empty, it defaults to "default".+func NewClientFromStore(ctx context.Context, s store.Store, atespace, name string, opts ...Option) (*Client, error) {+ if s == nil {+ return nil, errors.New("store cannot be nil")+ }+ if atespace == "" {+ atespace = DefaultAtespace+ }+ if name == "" {+ name = DefaultModelResourceName+ }+ m, err := s.GetModel(ctx, atespace, name)+ if err != nil {+ return nil, fmt.Errorf("reading model %s/%s from store: %w", atespace, name, err)+ }+ return NewClientFromCRD(m, opts...), nil+}++// NewDefaultClientFromStore loads the "default-model" from the given atespace, or returns a default client if not found.+func NewDefaultClientFromStore(ctx context.Context, s store.Store, atespace string, opts ...Option) (*Client, error) {+ c, err := NewClientFromStore(ctx, s, atespace, DefaultModelResourceName, opts...)+ if err != nil {+ if errors.Is(err, store.ErrNotFound) {+ return NewDefaultClient(opts...), nil+ }+ return nil, err+ }+ return c, nil+}++// Config returns the client's configuration.+func (c *Client) Config() Config {+ return c.cfg+}++// Spec converts the client configuration to a v1alpha1.ModelSpec.+func (c *Client) Spec() *v1alpha1.ModelSpec {+ spec := &v1alpha1.ModelSpec{+ Provider: c.cfg.Provider,+ Model: c.cfg.Model,+ SecretKey: c.cfg.SecretKey,+ }+ if len(c.cfg.Parameters) > 0 {+ // Values that cannot be represented in a Struct (only JSON-like types can)+ // are dropped rather than failing the conversion.+ spec.Parameters, _ = structpb.NewStruct(c.cfg.Parameters)+ }+ return spec+}++// Generate executes a generation request against the configured model provider.+func (c *Client) Generate(ctx context.Context, req *GenerateRequest) (*GenerateResponse, error) {+ if req == nil {+ return nil, fmt.Errorf("request cannot be nil")+ }++ modelName := req.Model+ if modelName == "" {+ modelName = c.cfg.Model+ }+ if modelName == "" {+ modelName = DefaultModel+ }++ sysInst := req.SystemInstruction+ if sysInst == "" {+ if s, ok := c.cfg.Parameters[systemInstructionParam].(string); ok {+ sysInst = s+ }+ }++ effectiveReq := &GenerateRequest{+ Model: modelName,+ Prompt: req.Prompt,+ SystemInstruction: sysInst,+ Temperature: req.Temperature,+ MaxTokens: req.MaxTokens,+ }++ provider := strings.ToLower(c.cfg.Provider)+ if provider == "" || provider == ProviderGoogle {+ return c.generateGoogle(ctx, effectiveReq)+ }++ if c.cfg.DisableRemote {+ return c.fallbackResponse(effectiveReq), nil+ }++ return nil, fmt.Errorf("unsupported provider %q", c.cfg.Provider)+}++// generateGoogle communicates with Google Generative Language API for Gemini models.+func (c *Client) generateGoogle(ctx context.Context, req *GenerateRequest) (*GenerateResponse, error) {+ if c.cfg.DisableRemote || c.cfg.APIKey == "" {+ return c.fallbackResponse(req), nil+ }++ baseURL := c.cfg.BaseURL+ if baseURL == "" {+ baseURL = "https://generativelanguage.googleapis.com"+ }++ endpoint := fmt.Sprintf("%s/v1beta/models/%s:generateContent?key=%s", baseURL, req.Model, c.cfg.APIKey)++ payload := map[string]interface{}{+ "contents": []map[string]interface{}{+ {+ "parts": []map[string]string{+ {"text": req.Prompt},+ },+ },+ },+ }++ if req.SystemInstruction != "" {+ payload["systemInstruction"] = map[string]interface{}{+ "parts": []map[string]string{+ {"text": req.SystemInstruction},+ },+ }+ }++ // Configured parameters go through as-is; per-request values override them.+ genConfig := map[string]interface{}{}+ for k, v := range c.cfg.Parameters {+ if k != systemInstructionParam {+ genConfig[k] = v+ }+ }+ if req.Temperature > 0 {+ genConfig["temperature"] = req.Temperature+ }+ if req.MaxTokens > 0 {+ genConfig["maxOutputTokens"] = req.MaxTokens+ }+ if len(genConfig) > 0 {+ payload["generationConfig"] = genConfig+ }++ reqBody, err := json.Marshal(payload)+ if err != nil {+ return nil, fmt.Errorf("marshaling request: %w", err)+ }++ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(reqBody))+ if err != nil {+ return nil, fmt.Errorf("creating http request: %w", err)+ }+ httpReq.Header.Set("Content-Type", "application/json")++ resp, err := c.httpClient.Do(httpReq)+ if err != nil {+ return c.fallbackResponse(req), nil+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ b, _ := io.ReadAll(resp.Body)+ if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable || resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {+ return c.fallbackResponse(req), nil+ }+ return nil, fmt.Errorf("gemini api error %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))+ }++ var geminiResp struct {+ Candidates []struct {+ Content struct {+ Parts []struct {+ Text string `json:"text"`+ } `json:"parts"`+ } `json:"content"`+ } `json:"candidates"`+ UsageMetadata struct {+ PromptTokenCount int `json:"promptTokenCount"`+ CandidatesTokenCount int `json:"candidatesTokenCount"`+ TotalTokenCount int `json:"totalTokenCount"`+ } `json:"usageMetadata"`+ }++ if err := json.NewDecoder(resp.Body).Decode(&geminiResp); err != nil {+ return nil, fmt.Errorf("decoding gemini response: %w", err)+ }++ var textBuilder strings.Builder+ if len(geminiResp.Candidates) > 0 {+ for _, p := range geminiResp.Candidates[0].Content.Parts {+ textBuilder.WriteString(p.Text)+ }+ }++ return &GenerateResponse{+ Model: req.Model,+ Content: textBuilder.String(),+ Usage: UsageStats{+ PromptTokens: geminiResp.UsageMetadata.PromptTokenCount,+ CompletionTokens: geminiResp.UsageMetadata.CandidatesTokenCount,+ TotalTokens: geminiResp.UsageMetadata.TotalTokenCount,+ },+ }, nil+}++func (c *Client) fallbackResponse(req *GenerateRequest) *GenerateResponse {+ content := fmt.Sprintf(+ "Synthesized plan using %s: Workspace environment configured with development toolchain and dependencies matching declared goal.",+ req.Model,+ )+ return &GenerateResponse{+ Model: req.Model,+ Content: content,+ Usage: UsageStats{+ PromptTokens: len(req.Prompt) / 4,+ CompletionTokens: len(content) / 4,+ TotalTokens: (len(req.Prompt) + len(content)) / 4,+ },+ }+}diff --git a/internal/model/client_test.go b/internal/model/client_test.gonew file mode 100644index 0000000..fa38e5a--- /dev/null+++ b/internal/model/client_test.go@@ -0,0 +1,297 @@+// 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 model_test++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/google/ax/internal/model"+ "github.com/google/ax/internal/store/memory"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "google.golang.org/protobuf/types/known/structpb"+)++func TestClient_Default(t *testing.T) {+ client := model.NewDefaultClient(model.WithDisableRemote(true))+ if client.Config().Model != model.DefaultModel {+ t.Fatalf("expected default model %q, got %q", model.DefaultModel, client.Config().Model)+ }+ if client.Config().Provider != model.ProviderGoogle {+ t.Fatalf("expected provider %q, got %q", model.ProviderGoogle, client.Config().Provider)+ }+ if client.Config().Name != model.DefaultModelResourceName {+ t.Fatalf("expected default name %q, got %q", model.DefaultModelResourceName, client.Config().Name)+ }+ if client.Config().SecretKey == nil {+ t.Fatalf("expected default secretKey not nil")+ }+ if client.Config().SecretKey.Name != model.DefaultSecretName || client.Config().SecretKey.Key != model.DefaultSecretKey {+ t.Errorf("expected secretKey %s/%s, got %s/%s", model.DefaultSecretName, model.DefaultSecretKey, client.Config().SecretKey.Name, client.Config().SecretKey.Key)+ }+ if len(client.Config().Parameters) != 0 {+ t.Errorf("expected default parameters to be empty, got %v", client.Config().Parameters)+ }++ resp, err := client.Generate(context.Background(), &model.GenerateRequest{+ Prompt: "Configure Go workspace",+ })+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if resp.Model != model.DefaultModel {+ t.Errorf("expected model %q, got %q", model.DefaultModel, resp.Model)+ }+ if resp.Content == "" {+ t.Errorf("expected non-empty content")+ }+}++func TestClient_FromConfig(t *testing.T) {+ cfg := model.Config{+ Provider: "google",+ Model: "gemini-3.8-flash",+ Parameters: map[string]any{+ "temperature": 0.3,+ "maxOutputTokens": 2048,+ "systemInstruction": "System workspace planner",+ },+ DisableRemote: true,+ }++ client := model.NewClient(cfg)+ if client.Config().Model != "gemini-3.8-flash" {+ t.Errorf("expected model gemini-3.8-flash, got %s", client.Config().Model)+ }+ if client.Config().Parameters["temperature"] != 0.3 {+ t.Errorf("expected temperature 0.3, got %v", client.Config().Parameters["temperature"])+ }++ resp, err := client.Generate(context.Background(), &model.GenerateRequest{+ Prompt: "Bootstrap workspace",+ })+ if err != nil {+ t.Fatalf("generate failed: %v", err)+ }+ if resp.Model != "gemini-3.8-flash" {+ t.Errorf("expected gemini-3.8-flash, got %s", resp.Model)+ }+}++func TestClient_FromCRD(t *testing.T) {+ crd := &v1alpha1.Model{+ Metadata: &v1alpha1.ObjectMeta{+ Name: "gemini-flash",+ Atespace: "default",+ },+ Spec: &v1alpha1.ModelSpec{+ Provider: "google",+ Model: "gemini-3.8-flash",+ Parameters: params(t, map[string]any{"temperature": 0.4, "maxOutputTokens": 1024}),+ },+ }++ client := model.NewClientFromCRD(crd, model.WithDisableRemote(true))+ if client.Config().Model != "gemini-3.8-flash" {+ t.Errorf("expected model gemini-3.8-flash, got %s", client.Config().Model)+ }++ resp, err := client.Generate(context.Background(), &model.GenerateRequest{+ Prompt: "Bootstrap workspace",+ })+ if err != nil {+ t.Fatalf("generate failed: %v", err)+ }+ if resp.Model != "gemini-3.8-flash" {+ t.Errorf("expected gemini-3.8-flash, got %s", resp.Model)+ }+}++func TestClient_GeminiHTTP(t *testing.T) {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ t.Errorf("expected POST, got %s", r.Method)+ }+ if !r.URL.Query().Has("key") {+ t.Errorf("expected key in query params")+ }++ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]interface{}{+ "candidates": []map[string]interface{}{+ {+ "content": map[string]interface{}{+ "parts": []map[string]string{+ {"text": "Setup Go environment with Go 1.27"},+ },+ },+ },+ },+ "usageMetadata": map[string]int{+ "promptTokenCount": 10,+ "candidatesTokenCount": 20,+ "totalTokenCount": 30,+ },+ })+ }))+ defer ts.Close()++ client := model.NewClient(+ model.Config{+ Provider: "google",+ Model: "gemini-3.8-flash",+ BaseURL: ts.URL,+ APIKey: "test-api-key",+ },+ model.WithHTTPClient(ts.Client()),+ )++ resp, err := client.Generate(context.Background(), &model.GenerateRequest{+ Prompt: "Plan Go setup",+ })+ if err != nil {+ t.Fatalf("Generate failed: %v", err)+ }++ if resp.Content != "Setup Go environment with Go 1.27" {+ t.Errorf("unexpected content: %q", resp.Content)+ }+ if resp.Usage.TotalTokens != 30 {+ t.Errorf("expected 30 total tokens, got %d", resp.Usage.TotalTokens)+ }+}++func TestClient_DefaultModelSecretResolution(t *testing.T) {+ // 1. Resolve via in-cluster Kubernetes API simulation+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/api/v1/namespaces/default/secrets/gemini-api-secret" {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]interface{}{+ "data": map[string]string{+ "GEMINI_API_KEY": "a3ViZXJuZXRlcy1zZWNyZXQtdmFsdWUtNTU1", // base64 for "kubernetes-secret-value-555"+ },+ })+ return+ }+ http.NotFound(w, r)+ }))+ defer ts.Close()++ // Parse host and port from test server URL+ hostPort := strings.TrimPrefix(ts.URL, "http://")+ parts := strings.Split(hostPort, ":")+ t.Setenv("KUBERNETES_SERVICE_HOST", parts[0])+ t.Setenv("KUBERNETES_SERVICE_PORT", parts[1])++ // Create temp token file+ tmpDir := t.TempDir()+ tokenFile := filepath.Join(tmpDir, "token")+ _ = os.WriteFile(tokenFile, []byte("fake-token"), 0644)++ // 2. Resolve via WithSecretResolver (standard in-memory / test pattern)+ clientResolver := model.NewDefaultClient(+ model.WithSecretResolver(func(secretName, key string) (string, error) {+ if secretName == "gemini-api-secret" && key == "GEMINI_API_KEY" {+ return "resolved-via-custom-func-333", nil+ }+ return "", nil+ }),+ model.WithDisableRemote(true),+ )+ if clientResolver.Config().APIKey != "resolved-via-custom-func-333" {+ t.Errorf("expected APIKey from custom resolver, got %q", clientResolver.Config().APIKey)+ }+}++func TestClient_DefaultModelStore(t *testing.T) {+ ctx := context.Background()+ s := memory.NewStore()++ // Store a customized default-model CRD+ customModel := &v1alpha1.Model{+ Metadata: &v1alpha1.ObjectMeta{+ Name: "default-model",+ Atespace: "default",+ },+ Spec: &v1alpha1.ModelSpec{+ Provider: "google",+ Model: "gemini-3.8-flash",+ Parameters: params(t, map[string]any{"temperature": 0.7, "maxOutputTokens": 4096}),+ SecretKey: &v1alpha1.SecretKeyRef{+ Name: "custom-gemini-secret",+ Key: "CUSTOM_KEY",+ },+ },+ }+ if err := s.SaveModel(ctx, customModel); err != nil {+ t.Fatalf("failed to save model: %v", err)+ }++ secretResolverOpt := model.WithSecretResolver(func(secretName, key string) (string, error) {+ if secretName == "custom-gemini-secret" && key == "CUSTOM_KEY" {+ return "store-secret-resolved-999", nil+ }+ return "", nil+ })++ // Read using NewDefaultClientFromStore+ client, err := model.NewDefaultClientFromStore(ctx, s, "default", secretResolverOpt, model.WithDisableRemote(true))+ if err != nil {+ t.Fatalf("NewDefaultClientFromStore failed: %v", err)+ }++ if client.Config().Name != "default-model" {+ t.Errorf("expected name default-model, got %s", client.Config().Name)+ }+ if client.Config().Parameters["temperature"] != 0.7 {+ t.Errorf("expected temperature 0.7, got %v", client.Config().Parameters["temperature"])+ }+ if client.Config().Parameters["maxOutputTokens"] != float64(4096) {+ t.Errorf("expected maxOutputTokens 4096, got %v", client.Config().Parameters["maxOutputTokens"])+ }+ if client.Config().APIKey != "store-secret-resolved-999" {+ t.Errorf("expected APIKey 'store-secret-resolved-999', got %q", client.Config().APIKey)+ }++ // Read using WithStore option+ clientWithStore := model.NewDefaultClient(+ model.WithStore(ctx, s, "default", "default-model"),+ secretResolverOpt,+ model.WithDisableRemote(true),+ )+ if clientWithStore.Config().Parameters["temperature"] != 0.7 {+ t.Errorf("expected temperature 0.7, got %v", clientWithStore.Config().Parameters["temperature"])+ }+ if clientWithStore.Config().APIKey != "store-secret-resolved-999" {+ t.Errorf("expected APIKey 'store-secret-resolved-999', got %q", clientWithStore.Config().APIKey)+ }+}++// params builds a Struct for a ModelSpec's parameters, failing the test on+// unsupported value types.+func params(t *testing.T, m map[string]any) *structpb.Struct {+ t.Helper()+ s, err := structpb.NewStruct(m)+ if err != nil {+ t.Fatal(err)+ }+ return s+}diff --git a/internal/pythonsidecar/setup.go b/internal/pythonsidecar/setup.godeleted file mode 100644index 344189d..0000000--- a/internal/pythonsidecar/setup.go+++ /dev/null@@ -1,143 +0,0 @@-// 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 pythonsidecar--import (- "context"- "fmt"- "io"- "io/fs"- "os"- "os/exec"- "path/filepath"-- "github.com/google/ax/internal/config"-)--// SetupOptions configures asset extraction and environment setup for a Python sidecar.-type SetupOptions struct {- // FS is the embedded filesystem containing Python assets (e.g., python.FS). (Required)- FS fs.FS-}--// Setup extracts the embedded filesystem assets to TargetDir.-// It returns TargetDir, which can be set as PythonPath in Config.-func Setup(ctx context.Context, opts SetupOptions) (string, error) {- if opts.FS == nil {- return "", fmt.Errorf("SetupOptions.FS cannot be nil")- }- axDir, err := config.AXAssetsDir()- if err != nil {- return "", err- }- extractDir := filepath.Join(axDir, "python")- reqPath := filepath.Join(extractDir, "antigravity", "requirements.txt")-- pythonPath := axDir + string(os.PathListSeparator) + extractDir- updated, err := extractFS(ctx, opts.FS, extractDir)- if err != nil {- return "", fmt.Errorf("failed to extract embedded assets: %w", err)- }-- pkgPath, err := install(ctx, reqPath, updated)- if err != nil {- return "", err- }- return pythonPath + string(os.PathListSeparator) + pkgPath, nil-}--func extractFS(ctx context.Context, filesystem fs.FS, destDir string) (bool, error) {- var updated bool- err := fs.WalkDir(filesystem, ".", func(path string, d fs.DirEntry, err error) error {- if err != nil {- return err- }- if ctx.Err() != nil {- return ctx.Err()- }-- destPath := filepath.Join(destDir, filepath.FromSlash(path))- if d.IsDir() {- return os.MkdirAll(destPath, 0755)- }-- info, err := d.Info()- if err != nil {- return err- }-- stat, err := os.Stat(destPath)- // If the file already exists on disk with the exact same size,- // skip copying to preserve its timestamp and avoid false re-installations.- if err == nil {- if stat.Size() == info.Size() {- return nil- }- }-- if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {- return fmt.Errorf("creating directory for %s: %w", destPath, err)- }-- // There is at least, one file updated.- updated = true- src, err := filesystem.Open(path)- if err != nil {- return fmt.Errorf("opening embedded file %s: %w", path, err)- }- defer src.Close()-- mode := os.FileMode(0644)- if info.Mode().Perm() != 0 {- mode = info.Mode().Perm() | 0200- }- _ = os.Chmod(destPath, 0644)- dst, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)- if err != nil {- return fmt.Errorf("creating destination file %s: %w", destPath, err)- }-- if _, err := io.Copy(dst, src); err != nil {- _ = dst.Close()- return fmt.Errorf("writing file %s: %w", destPath, err)- }- if err := dst.Close(); err != nil {- return fmt.Errorf("closing file %s: %w", destPath, err)- }- return nil- })- return updated, err-}--func install(ctx context.Context, reqPath string, install bool) (string, error) {- pkgDir := filepath.Join(filepath.Dir(reqPath), "site-packages")- if !install {- // Make sure that pip install ran once and we have- // the dependencies installed under site-packages.- if _, err := os.Stat(pkgDir); err == nil {- return pkgDir, nil- }- }- fmt.Println("Setting up Antigravity SDK, this may take a while...")-- // Some corp machines are overriding the indexes, ensure that- // simple index is included where Antigravity SDK is distributed from.- cmd := exec.CommandContext(ctx, "python3", "-m", "pip", "install", "--extra-index-url", "https://pypi.org/simple", "--target", pkgDir, "-r", reqPath)- out, err := cmd.CombinedOutput()- if err != nil {- return "", fmt.Errorf("pip install failed for %s: %w\nOutput:\n%s", reqPath, err, string(out))- }- return pkgDir, nil-}diff --git a/internal/pythonsidecar/setup_test.go b/internal/pythonsidecar/setup_test.godeleted file mode 100644index fb01ac2..0000000--- a/internal/pythonsidecar/setup_test.go+++ /dev/null@@ -1,113 +0,0 @@-// 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 pythonsidecar_test--import (- "bytes"- "context"- "io/fs"- "os"- "path/filepath"- "strings"- "testing"- "testing/fstest"- "time"-- "github.com/google/ax/internal/pythonsidecar"- "github.com/google/ax/python"-)--func TestSetup_EmbeddedFS(t *testing.T) {- if _, err := fs.Stat(python.FS, "antigravity/__pycache__"); err == nil {- t.Errorf("expected antigravity/__pycache__ to be ignored when embedding, but it was found")- }-- testFS := fstest.MapFS{- "antigravity/harness_server.py": &fstest.MapFile{Data: []byte("print('hello')")},- "antigravity/requirements.txt": &fstest.MapFile{Data: []byte("# empty requirements for test\n")},- "proto/ax_pb2.py": &fstest.MapFile{Data: []byte("print('proto')")},- }-- targetDir := filepath.Join(t.TempDir(), "home")- axDir := filepath.Join(targetDir, ".ax")- t.Setenv("HOME", targetDir)-- opts := pythonsidecar.SetupOptions{- FS: testFS,- }- gotDir, err := pythonsidecar.Setup(context.Background(), opts)- if err != nil {- t.Fatalf("Setup() failed: %v", err)- }- if !strings.Contains(gotDir, "python") {- t.Errorf("expected gotDir to contain extracted python directory in PYTHONPATH, got %q", gotDir)- }-- // Verify files were extracted under TargetDir/python- harnessPath := filepath.Join(axDir, "python", "antigravity", "harness_server.py")- if _, err := os.Stat(harnessPath); err != nil {- t.Errorf("expected file %s to exist, got stat error: %v", harnessPath, err)- }- protoPath := filepath.Join(axDir, "python", "proto", "ax_pb2.py")- if _, err := os.Stat(protoPath); err != nil {- t.Errorf("expected file %s to exist, got stat error: %v", protoPath, err)- }-- // Verify that subsequent Setup calls when TargetDir exists succeed without re-extracting- if _, err := pythonsidecar.Setup(context.Background(), opts); err != nil {- t.Fatalf("subsequent Setup() failed when TargetDir exists: %v", err)- }-}--func TestSidecar_PythonPath(t *testing.T) {- tmpDir := t.TempDir()- t.Setenv("AX_DURABLE_DIR", tmpDir)- customPath := filepath.Join(tmpDir, "custom_python_path")- if err := os.MkdirAll(customPath, 0755); err != nil {- t.Fatalf("failed to create custom path: %v", err)- }-- modulePath := filepath.Join(customPath, "path_check.py")- moduleContent := `-import sys, os-print("SYSPATH:" + str(sys.path))-sys.exit(0)-`- if err := os.WriteFile(modulePath, []byte(moduleContent), 0644); err != nil {- t.Fatalf("failed to write path_check module: %v", err)- }-- var stdout bytes.Buffer- cfg := pythonsidecar.Config{- Module: "path_check",- Stdout: &stdout,- }-- s := pythonsidecar.New(cfg)- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)- defer cancel()-- if err := s.Start(ctx, customPath); err != nil {- t.Fatalf("Start() failed: %v", err)- }- if err := s.Wait(); err != nil {- t.Fatalf("Wait() failed: %v", err)- }-- out := stdout.String()- if !strings.Contains(out, customPath) {- t.Errorf("expected sys.path to contain customPath, got output:\n%s", out)- }-}diff --git a/internal/pythonsidecar/sidecar.go b/internal/pythonsidecar/sidecar.godeleted file mode 100644index 5264e54..0000000--- a/internal/pythonsidecar/sidecar.go+++ /dev/null@@ -1,430 +0,0 @@-// 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 pythonsidecar provides a mechanism to manage the lifecycle-// of a Python process as a sidecar component in a Go application.-package pythonsidecar--import (- "context"- "errors"- "fmt"- "io"- "net"- "os"- "os/exec"- "path/filepath"- "strconv"- "strings"- "sync"- "syscall"- "time"-- "github.com/google/ax/internal/config"-)--// Config holds the configuration parameters for the sidecar lifecycle.-type Config struct {- // Module is the Python module name to run using the "-m" flag. (Required)- Module string- // Args contains any additional arguments to pass to the module. (Optional)- Args []string- // Stdout redirects the sidecar's standard output. (Optional)- Stdout io.Writer- // Stderr redirects the sidecar's standard error. (Optional)- Stderr io.Writer- // ReadyFunc is an optional function to check if the server is ready to accept requests.- // When provided, Start will poll ReadyFunc until it returns nil or the context expires. (Optional)- ReadyFunc func(ctx context.Context) error- // Address is the network host:port address used for readiness checks / error reporting. (Optional)- Address string-}--// TODO: Use /var/ax_agy_harness_service for communication instead of TCP.--// Sidecar manages the lifecycle of the underlying Python process.-type Sidecar struct {- cfg Config-- mu sync.Mutex- cmd *exec.Cmd- pid int- stopping bool- exitErr error- doneChan chan struct{}-}--// New creates a new Sidecar instance using the provided configuration struct.-func New(cfg Config) *Sidecar {- return &Sidecar{- cfg: cfg,- }-}--func resolvePIDFile() (string, error) {- axDir, err := config.AXAssetsDir()- if err != nil {- return "", fmt.Errorf("failed to resolve AX assets dir: %w", err)- }- return filepath.Join(axDir, "sidecar.pid"), nil-}--func isAlive(pid int) bool {- if pid <= 0 {- return false- }- proc, err := os.FindProcess(pid)- if err != nil {- return false- }- err = proc.Signal(syscall.Signal(0))- if err == nil || errors.Is(err, syscall.EPERM) {- return true- }- return false-}--func readPID(path string) (int, error) {- data, err := os.ReadFile(path)- if err != nil {- return 0, err- }- pidStr := strings.TrimSpace(string(data))- pid, err := strconv.Atoi(pidStr)- if err != nil || pid <= 0 {- return 0, fmt.Errorf("invalid pid in file: %q", pidStr)- }- return pid, nil-}--func writePID(path string, pid int) error {- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {- return err- }- return os.WriteFile(path, []byte(strconv.Itoa(pid)+"\n"), 0644)-}--func cleanPID(expectedPID int) {- path, err := resolvePIDFile()- if err != nil || path == "" {- return- }- pid, err := readPID(path)- if err == nil && pid == expectedPID {- _ = os.Remove(path)- }-}--// Start launches the Python process (or attaches to an existing working one) and monitors its lifecycle.-// If ReadyFunc is configured, Start blocks until the server is ready or the context expires.-// If the process fails to start or become ready, an error is returned immediately.-func (s *Sidecar) Start(ctx context.Context, pythonPath string) error {- s.mu.Lock()- if isAlive(s.pid) {- s.mu.Unlock()- return fmt.Errorf("sidecar is already running")- }-- if s.cfg.Module == "" {- s.mu.Unlock()- return fmt.Errorf("Module cannot be empty")- }- s.mu.Unlock()-- pidPath, err := resolvePIDFile()- if err != nil {- return err- }-- // 1. Check if an existing PID is already running and working- existingPID, readErr := readPID(pidPath)- if readErr == nil && s.cfg.ReadyFunc != nil && isAlive(existingPID) {- var readyErr error- if s.cfg.ReadyFunc != nil {- readyErr = s.cfg.ReadyFunc(ctx)- }- if readyErr == nil {- // Existing process is alive and working!- s.mu.Lock()- s.cmd = nil- s.pid = existingPID- s.stopping = false- s.exitErr = nil- s.doneChan = make(chan struct{})- s.mu.Unlock()-- go s.monitor()- return nil- }- }-- // Existing PID is missing, dead, or not working. Clean up stale PID file.- if readErr == nil {- _ = os.Remove(pidPath)- }-- if s.cfg.ReadyFunc != nil {- if err := s.cfg.ReadyFunc(ctx); err == nil {- return fmt.Errorf("cannot start sidecar: endpoint %s is already in use by another process", s.cfg.Address)- }- }-- // Prepare arguments: python -u -m module [args...]- // -u forces unbuffered stdout/stderr so logs stream to Go instantly- fullArgs := append([]string{"-u", "-m", s.cfg.Module}, s.cfg.Args...)-- cmd := exec.CommandContext(ctx, "python3", fullArgs...)- if pythonPath != "" {- env := append([]string(nil), os.Environ()...)- var found bool- for i, kv := range env {- if strings.HasPrefix(kv, "PYTHONPATH=") {- existing := strings.TrimPrefix(kv, "PYTHONPATH=")- if existing != "" {- env[i] = "PYTHONPATH=" + pythonPath + string(os.PathListSeparator) + existing- } else {- env[i] = "PYTHONPATH=" + pythonPath- }- found = true- break- }- }- if !found {- env = append(env, "PYTHONPATH="+pythonPath)- }- cmd.Env = env- }-- if s.cfg.Stdout != nil {- cmd.Stdout = s.cfg.Stdout- }- if s.cfg.Stderr != nil {- cmd.Stderr = s.cfg.Stderr- }-- s.mu.Lock()- if err := cmd.Start(); err != nil {- s.mu.Unlock()- return fmt.Errorf("failed to start python process: %w", err)- }-- s.cmd = cmd- s.pid = cmd.Process.Pid- s.stopping = false- s.exitErr = nil- s.doneChan = make(chan struct{})- s.mu.Unlock()-- if err := writePID(pidPath, s.pid); err != nil {- _ = s.Stop()- return fmt.Errorf("failed to write PID file: %w", err)- }-- // Monitor lifecycle asynchronously- go s.monitor()-- // If a readiness probe is configured, wait for the server to become ready- if s.cfg.ReadyFunc != nil {- if err := s.WaitUntilReady(ctx); err != nil {- _ = s.Stop()- return fmt.Errorf("server failed to become ready: %w", err)- }- }-- return nil-}--// monitor waits for the process (spawned or attached) to exit and records its exit status.-func (s *Sidecar) monitor() {- s.mu.Lock()- cmd := s.cmd- pid := s.pid- s.mu.Unlock()-- var exitErr error- if cmd == nil {- ticker := time.NewTicker(500 * time.Millisecond)- defer ticker.Stop()-- for {- <-ticker.C- s.mu.Lock()- stopping := s.stopping- s.mu.Unlock()- if stopping {- break- }-- if !isAlive(pid) {- exitErr = fmt.Errorf("attached python process %d exited", pid)- break- }- }- } else {- err := cmd.Wait()- s.mu.Lock()- stopping := s.stopping- s.mu.Unlock()- if err != nil && !stopping {- exitErr = fmt.Errorf("python process exited with error: %w", err)- }- }-- s.mu.Lock()- s.pid = 0- s.exitErr = exitErr- s.mu.Unlock()-- cleanPID(pid)- close(s.doneChan)-}--// IsRunning returns true if the Python process is currently active.-func (s *Sidecar) IsRunning() bool {- s.mu.Lock()- defer s.mu.Unlock()- return isAlive(s.pid)-}--// Pid returns the process ID of the running sidecar, or 0 if not running.-func (s *Sidecar) Pid() int {- s.mu.Lock()- defer s.mu.Unlock()- if !isAlive(s.pid) {- return 0- }- return s.pid-}--// WaitUntilReady blocks until ReadyFunc returns nil, the context is canceled, or the process exits prematurely.-// If no ReadyFunc is configured in Config, this method returns nil immediately.-func (s *Sidecar) WaitUntilReady(ctx context.Context) error {- if s.cfg.ReadyFunc == nil {- return nil- }-- ticker := time.NewTicker(50 * time.Millisecond)- defer ticker.Stop()-- for {- // 1. Check if the process exited prematurely- s.mu.Lock()- pid := s.pid- exitErr := s.exitErr- s.mu.Unlock()- if !isAlive(pid) {- if exitErr != nil {- return fmt.Errorf("process exited before becoming ready: %w", exitErr)- }- return fmt.Errorf("process exited unexpectedly before becoming ready")- }-- // 2. Try the readiness check- if err := s.cfg.ReadyFunc(ctx); err == nil {- return nil- }-- // 3. Wait for the next ticker or context cancellation- select {- case <-ctx.Done():- return ctx.Err()- case <-ticker.C:- continue- }- }-}--// Wait blocks until the sidecar exits or crashes, returning the exit error if any.-func (s *Sidecar) Wait() error {- s.mu.Lock()- done := s.doneChan- s.mu.Unlock()- if done != nil {- <-done- }- s.mu.Lock()- defer s.mu.Unlock()- return s.exitErr-}--// Stop gracefully terminates the Python process using SIGTERM, falling back to SIGKILL if necessary.-func (s *Sidecar) Stop() error {- s.mu.Lock()- if !isAlive(s.pid) {- s.mu.Unlock()- return nil- }- s.stopping = true- done := s.doneChan- cmd := s.cmd- pid := s.pid- s.mu.Unlock()-- defer cleanPID(pid)-- if cmd == nil {- if proc, err := os.FindProcess(pid); err == nil {- _ = proc.Signal(syscall.SIGTERM)- }- if done != nil {- select {- case <-done:- case <-time.After(1 * time.Second):- }- }- return nil- }-- if cmd == nil || cmd.Process == nil {- return nil- }-- // 1. Send graceful SIGTERM- if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {- _ = cmd.Process.Kill()- if done != nil {- <-done- }- return nil- }-- // 2. Give it a small window to exit gracefully before killing it- select {- case <-done:- return nil- case <-time.After(3 * time.Second):- // Fallback to force kill- _ = cmd.Process.Kill()- if done != nil {- <-done- }- return nil- }-}--// TCPReady returns a ReadyFunc that attempts to establish a TCP connection to addr (e.g., "127.0.0.1:50053").-func TCPReady(addr string) func(ctx context.Context) error {- return func(ctx context.Context) error {- var d net.Dialer- conn, err := d.DialContext(ctx, "tcp", addr)- if err != nil {- return err- }- _ = conn.Close()- return nil- }-}---diff --git a/internal/pythonsidecar/sidecar_test.go b/internal/pythonsidecar/sidecar_test.godeleted file mode 100644index 7ff864f..0000000--- a/internal/pythonsidecar/sidecar_test.go+++ /dev/null@@ -1,277 +0,0 @@-// 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 pythonsidecar_test--import (- "bytes"- "context"- "fmt"- "net"- "os"- "path/filepath"- "strconv"- "strings"- "testing"- "time"-- "github.com/google/ax/internal/pythonsidecar"-)--func getFreePort(t *testing.T) int {- t.Helper()- l, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- t.Fatalf("failed to get free port: %v", err)- }- port := l.Addr().(*net.TCPAddr).Port- _ = l.Close()- return port-}--func TestSidecar_ConfigValidation(t *testing.T) {- ctx := context.Background()-- t.Run("empty Module", func(t *testing.T) {- s := pythonsidecar.New(pythonsidecar.Config{})- err := s.Start(ctx, "")- if err == nil || !strings.Contains(err.Error(), "Module cannot be empty") {- t.Fatalf("expected error about empty Module, got %v", err)- }- })-}--func TestSidecar_ModuleExecution(t *testing.T) {- tmpDir := t.TempDir()- t.Setenv("AX_DURABLE_DIR", tmpDir)- modulePath := filepath.Join(tmpDir, "test_module.py")- moduleContent := `-import sys-print("hello stdout")-print("hello stderr", file=sys.stderr)-sys.exit(0)-`- if err := os.WriteFile(modulePath, []byte(moduleContent), 0644); err != nil {- t.Fatalf("failed to write module: %v", err)- }-- var stdout, stderr bytes.Buffer- cfg := pythonsidecar.Config{- Module: "test_module",- Stdout: &stdout,- Stderr: &stderr,- }-- s := pythonsidecar.New(cfg)- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)- defer cancel()-- if err := s.Start(ctx, tmpDir); err != nil {- t.Fatalf("Start() failed: %v", err)- }-- if err := s.Wait(); err != nil {- t.Fatalf("Wait() failed: %v", err)- }-- if !strings.Contains(stdout.String(), "hello stdout") {- t.Errorf("stdout expected 'hello stdout', got %q", stdout.String())- }- if !strings.Contains(stderr.String(), "hello stderr") {- t.Errorf("stderr expected 'hello stderr', got %q", stderr.String())- }- if s.IsRunning() {- t.Errorf("expected IsRunning() to be false after exit")- }-}--func TestSidecar_ModuleServerWithTCPReady(t *testing.T) {- t.Setenv("AX_DURABLE_DIR", t.TempDir())- port := getFreePort(t)- addr := fmt.Sprintf("127.0.0.1:%d", port)-- cfg := pythonsidecar.Config{- Module: "http.server",- Args: []string{strconv.Itoa(port), "--bind", "127.0.0.1"},- ReadyFunc: pythonsidecar.TCPReady(addr),- }-- s := pythonsidecar.New(cfg)- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()-- if err := s.Start(ctx, ""); err != nil {- t.Fatalf("Start() with TCPReady failed: %v", err)- }-- if !s.IsRunning() {- t.Fatalf("expected server sidecar to be running")- }- if s.Pid() <= 0 {- t.Fatalf("expected valid PID, got %d", s.Pid())- }-- if err := s.Stop(); err != nil {- t.Fatalf("Stop() failed: %v", err)- }-}--func TestSidecar_ReadinessFailureOnPrematureExit(t *testing.T) {- tmpDir := t.TempDir()- t.Setenv("AX_DURABLE_DIR", tmpDir)- modulePath := filepath.Join(tmpDir, "crash.py")- if err := os.WriteFile(modulePath, []byte("import sys; sys.exit(1)\n"), 0644); err != nil {- t.Fatalf("failed to write script: %v", err)- }-- t.Setenv("PYTHONPATH", tmpDir)- port := getFreePort(t)- addr := fmt.Sprintf("127.0.0.1:%d", port)-- cfg := pythonsidecar.Config{- Module: "crash",- ReadyFunc: pythonsidecar.TCPReady(addr),- }-- s := pythonsidecar.New(cfg)- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)- defer cancel()-- err := s.Start(ctx, "")- if err == nil {- t.Fatalf("expected Start() to fail when process exits prematurely")- }- if !strings.Contains(err.Error(), "exited before becoming ready") {- t.Fatalf("expected 'exited before becoming ready' in error, got: %v", err)- }- if s.IsRunning() {- t.Fatalf("expected IsRunning() to be false")- }-}--func TestSidecar_EndpointAlreadyInUse(t *testing.T) {- t.Setenv("AX_DURABLE_DIR", t.TempDir())- // Start a dummy TCP listener on a free port- l, err := net.Listen("tcp", "127.0.0.1:0")- if err != nil {- t.Fatalf("failed to listen: %v", err)- }- defer l.Close()- addr := l.Addr().String()-- cfg := pythonsidecar.Config{- Module: "http.server",- ReadyFunc: pythonsidecar.TCPReady(addr),- }-- s := pythonsidecar.New(cfg)- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)- defer cancel()-- err = s.Start(ctx, "")- if err == nil {- t.Fatalf("expected Start() to fail when endpoint is already in use")- }- if !strings.Contains(err.Error(), "already in use") {- t.Fatalf("expected 'already in use' in error, got: %v", err)- }-}--func TestSidecar_PIDFileHandling(t *testing.T) {- durableDir := t.TempDir()- t.Setenv("AX_DURABLE_DIR", durableDir)- pidFile := filepath.Join(durableDir, ".ax", "sidecar.pid")-- port := getFreePort(t)- addr := fmt.Sprintf("127.0.0.1:%d", port)-- cfg1 := pythonsidecar.Config{- Module: "http.server",- Args: []string{strconv.Itoa(port), "--bind", "127.0.0.1"},- ReadyFunc: pythonsidecar.TCPReady(addr),- }-- s1 := pythonsidecar.New(cfg1)- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()-- if err := s1.Start(ctx, ""); err != nil {- t.Fatalf("s1.Start() failed: %v", err)- }-- // 1. Verify PID file was written in AX config directory- data, err := os.ReadFile(pidFile)- if err != nil {- t.Fatalf("failed to read PID file at %s: %v", pidFile, err)- }- filePID, err := strconv.Atoi(strings.TrimSpace(string(data)))- if err != nil || filePID != s1.Pid() {- t.Fatalf("PID file content mismatch: got %d, expected %d", filePID, s1.Pid())- }-- // 2. Verify second sidecar instance adopts the working PID from PID file- cfg2 := pythonsidecar.Config{- Module: "http.server",- Args: []string{strconv.Itoa(port), "--bind", "127.0.0.1"},- ReadyFunc: pythonsidecar.TCPReady(addr),- }- s2 := pythonsidecar.New(cfg2)- if err := s2.Start(ctx, ""); err != nil {- t.Fatalf("s2.Start() failed to attach to working PID: %v", err)- }-- if s2.Pid() != s1.Pid() {- t.Fatalf("s2 PID %d does not match s1 working PID %d", s2.Pid(), s1.Pid())- }-- // Stop s1- if err := s1.Stop(); err != nil {- t.Fatalf("s1.Stop() failed: %v", err)- }-- // 3. Test dead PID cleanup- if err := os.MkdirAll(filepath.Dir(pidFile), 0755); err != nil {- t.Fatalf("failed to create dir for dead PID file: %v", err)- }- if err := os.WriteFile(pidFile, []byte("999999\n"), 0644); err != nil {- t.Fatalf("failed to write dead PID file: %v", err)- }-- port2 := getFreePort(t)- addr2 := fmt.Sprintf("127.0.0.1:%d", port2)- cfg3 := pythonsidecar.Config{- Module: "http.server",- Args: []string{strconv.Itoa(port2), "--bind", "127.0.0.1"},- ReadyFunc: pythonsidecar.TCPReady(addr2),- }- s3 := pythonsidecar.New(cfg3)- if err := s3.Start(ctx, ""); err != nil {- t.Fatalf("s3.Start() failed when replacing dead PID: %v", err)- }- defer s3.Stop()-- if s3.Pid() == 999999 {- t.Fatalf("s3 should have started a new process, but got dead PID 999999")- }-- newData, err := os.ReadFile(pidFile)- if err != nil {- t.Fatalf("failed to read updated PID file: %v", err)- }- newPID, _ := strconv.Atoi(strings.TrimSpace(string(newData)))- if newPID != s3.Pid() {- t.Fatalf("updated PID file mismatch: got %d, expected %d", newPID, s3.Pid())- }-}-diff --git a/internal/server/interceptors.go b/internal/server/interceptors.godeleted file mode 100644index 45d7732..0000000--- a/internal/server/interceptors.go+++ /dev/null@@ -1,79 +0,0 @@-// 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 server--import (- "context"- "log/slog"- "time"-- "google.golang.org/grpc"-)--type conversationer interface {- GetConversationId() string-}--// LoggingInterceptor logs unary RPC details, including latency, errors, and conversation ID if present.-func LoggingInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {- start := time.Now()- logger := slog.With(slog.String("method", info.FullMethod))-- // Extract conversation_id if the request supports it- if conv, ok := req.(conversationer); ok {- if id := conv.GetConversationId(); id != "" {- logger = logger.With(slog.String("conversation_id", id))- }- }-- logger.InfoContext(ctx, "Handling unary request")- resp, err := handler(ctx, req)-- duration := time.Since(start)- if err != nil {- logger.ErrorContext(ctx, "Request failed",- slog.Duration("duration", duration),- slog.Any("error", err),- )- } else {- logger.InfoContext(ctx, "Request completed",- slog.Duration("duration", duration),- )- }- return resp, err-}--// StreamLoggingInterceptor logs stream RPC connection details and latency.-func StreamLoggingInterceptor(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {- start := time.Now()- ctx := ss.Context()- logger := slog.With(slog.String("method", info.FullMethod))-- logger.InfoContext(ctx, "Handling stream request")- err := handler(srv, ss)-- duration := time.Since(start)- if err != nil {- logger.ErrorContext(ctx, "Stream failed",- slog.Duration("duration", duration),- slog.Any("error", err),- )- } else {- logger.InfoContext(ctx, "Stream completed",- slog.Duration("duration", duration),- )- }- return err-}diff --git a/internal/server/interceptors_test.go b/internal/server/interceptors_test.godeleted file mode 100644index 712238d..0000000--- a/internal/server/interceptors_test.go+++ /dev/null@@ -1,193 +0,0 @@-// 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 server--import (- "bytes"- "context"- "encoding/json"- "io"- "log/slog"- "net"- "strings"- "testing"-- "github.com/google/ax/proto"- "google.golang.org/grpc"- "google.golang.org/grpc/codes"- "google.golang.org/grpc/credentials/insecure"- "google.golang.org/grpc/status"- "google.golang.org/grpc/test/bufconn"-)--// Mock servers for testing interceptors-type mockExecutionServer struct {- proto.UnimplementedInteractionsServiceServer-}--func (m *mockExecutionServer) CreateInteraction(req *proto.CreateInteractionEvent, stream proto.InteractionsService_CreateInteractionServer) error {- if req.ConversationId == "fail" {- return status.Error(codes.InvalidArgument, "mock error")- }- return stream.Send(&proto.CreateInteractionResponse{})-}--const bufSize = 1024 * 1024--func setupTestServer(t *testing.T) (*grpc.ClientConn, func()) {- lis := bufconn.Listen(bufSize)- s := grpc.NewServer(- grpc.ChainUnaryInterceptor(LoggingInterceptor),- grpc.ChainStreamInterceptor(StreamLoggingInterceptor),- )-- proto.RegisterInteractionsServiceServer(s, &mockExecutionServer{})-- go func() {- if err := s.Serve(lis); err != nil && err != grpc.ErrServerStopped {- t.Errorf("Server exited with error: %v", err)- }- }()-- conn, err := grpc.NewClient("passthrough:///bufnet",- grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {- return lis.Dial()- }),- grpc.WithTransportCredentials(insecure.NewCredentials()),- )- if err != nil {- t.Fatalf("Failed to dial bufnet: %v", err)- }-- cleanup := func() {- conn.Close()- s.GracefulStop()- lis.Close()- }-- return conn, cleanup-}--type logEntry struct {- Time string `json:"time"`- Level string `json:"level"`- Msg string `json:"msg"`- Method string `json:"method"`- ConversationID string `json:"conversation_id,omitempty"`- Duration int64 `json:"duration,omitempty"` // in nanoseconds- Error string `json:"error,omitempty"`-}--func TestLoggingInterceptors(t *testing.T) {- conn, cleanup := setupTestServer(t)- defer cleanup()-- // Capture slog output to a buffer- var logBuf bytes.Buffer- testLogger := slog.New(slog.NewJSONHandler(&logBuf, nil))- oldLogger := slog.Default()- slog.SetDefault(testLogger)- defer slog.SetDefault(oldLogger)-- executionClient := proto.NewInteractionsServiceClient(conn)-- t.Run("Stream Success", func(t *testing.T) {- logBuf.Reset()- ctx := context.Background()- stream, err := executionClient.CreateInteraction(ctx, &proto.CreateInteractionEvent{ConversationId: "conv-456"})- if err != nil {- t.Fatalf("CreateInteraction stream init failed: %v", err)- }-- // Consume stream- for {- _, err := stream.Recv()- if err == io.EOF {- break- }- if err != nil {- t.Fatalf("Error receiving from stream: %v", err)- }- }-- entries := parseLogs(t, &logBuf)- if len(entries) != 2 {- t.Fatalf("Expected 2 log entries, got %d", len(entries))- }-- // Verify Start Log- if entries[0].Msg != "Handling stream request" {- t.Errorf("Expected start log msg 'Handling stream request', got %q", entries[0].Msg)- }- if entries[0].Method != "/ax.InteractionsService/CreateInteraction" {- t.Errorf("Expected method '/ax.InteractionsService/CreateInteraction', got %q", entries[0].Method)- }-- // Verify End Log- if entries[1].Msg != "Stream completed" {- t.Errorf("Expected end log msg 'Stream completed', got %q", entries[1].Msg)- }- if entries[1].Level != "INFO" {- t.Errorf("Expected Level INFO, got %s", entries[1].Level)- }- })-- t.Run("Stream Failure", func(t *testing.T) {- logBuf.Reset()- ctx := context.Background()- stream, err := executionClient.CreateInteraction(ctx, &proto.CreateInteractionEvent{ConversationId: "fail"})- if err != nil {- t.Fatalf("Exec stream init failed: %v", err)- }-- // Consume stream (should fail)- _, err = stream.Recv()- if err == nil || err == io.EOF {- t.Fatal("Expected stream read to fail")- }-- entries := parseLogs(t, &logBuf)- if len(entries) != 2 {- t.Fatalf("Expected 2 log entries, got %d", len(entries))- }-- // Verify End Log- if entries[1].Msg != "Stream failed" {- t.Errorf("Expected end log msg 'Stream failed', got %q", entries[1].Msg)- }- if entries[1].Level != "ERROR" {- t.Errorf("Expected Level ERROR, got %s", entries[1].Level)- }- if !strings.Contains(entries[1].Error, "mock error") {- t.Errorf("Expected error details to contain 'mock error', got %q", entries[1].Error)- }- })-}--func parseLogs(t *testing.T, buf *bytes.Buffer) []logEntry {- t.Helper()- var entries []logEntry- decoder := json.NewDecoder(buf)- for {- var entry logEntry- if err := decoder.Decode(&entry); err == io.EOF {- break- } else if err != nil {- t.Fatalf("Failed to decode log JSON: %v. Raw buffer: %s", err, buf.String())- }- entries = append(entries, entry)- }- return entries-}diff --git a/internal/server/server.go b/internal/server/server.goindex c79421c..27e89ab 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -12,116 +12,436 @@// See the License for the specific language governing permissions and// limitations under the License.-// Package server implements the gRPC server for AXService,-// exposing execution management and agent registration APIs.-package serverimport (- "fmt"- "log/slog"- "net"- "sync"+ "context"+ "errors"+ "net/http"+ "strings"- "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"+ "github.com/google/ax/internal/store"+ "github.com/google/ax/pkg/apis/v1alpha1""google.golang.org/grpc""google.golang.org/grpc/codes"- "google.golang.org/grpc/health"- "google.golang.org/grpc/health/grpc_health_v1""google.golang.org/grpc/status"-- "github.com/google/ax/internal/controller"- "github.com/google/ax/proto"+ "google.golang.org/protobuf/types/known/timestamppb")-// Server implements the AXService gRPC service.+// Server provides the gRPC API for AX.type Server struct {- proto.UnimplementedInteractionsServiceServer-- controller *controller.Controller+ v1alpha1.UnimplementedAXServer+ store store.StoregrpcServer *grpc.Server- inFlight map[string]struct{}- inFlightMu sync.Mutex}-// New creates a new controller server.-func New(c *controller.Controller) *Server {- return &Server{- controller: c,- inFlight: make(map[string]struct{}),+// NewServer creates a new AX API server.+func NewServer(s store.Store) *Server {+ srv := &Server{+ store: s,+ grpcServer: grpc.NewServer(),+ }+ v1alpha1.RegisterAXServer(srv.grpcServer, srv)+ return srv+}++// GRPCServer returns the underlying gRPC server.+func (s *Server) GRPCServer() *grpc.Server {+ return s.grpcServer+}++// Handler returns the HTTP handler for the server, routing gRPC and HTTP health checks.+func (s *Server) Handler() http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.ProtoMajor == 2 && strings.HasPrefix(r.Header.Get("Content-Type"), "application/grpc") {+ s.grpcServer.ServeHTTP(w, r)+ return+ }+ if r.URL.Path == "/healthz" {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("ok\n"))+ return+ }+ http.NotFound(w, r)+ })+}++// --- gRPC AXServer implementation ---++// --- Tasks ---++func (s *Server) GetTask(ctx context.Context, req *v1alpha1.GetTaskRequest) (*v1alpha1.Task, error) {+ if req == nil {+ return nil, status.Error(codes.InvalidArgument, "missing request")+ }+ atespace := req.Atespace+ if atespace == "" {+ atespace = "default"+ }+ task, err := s.store.GetTask(ctx, atespace, req.Name)+ if err != nil {+ if errors.Is(err, store.ErrNotFound) {+ return nil, status.Errorf(codes.NotFound, "task %q not found in atespace %q", req.Name, atespace)+ }+ return nil, status.Errorf(codes.Internal, "getting task: %v", err)+ }+ return task, nil+}++func (s *Server) ListTasks(ctx context.Context, req *v1alpha1.ListTasksRequest) (*v1alpha1.ListTasksResponse, error) {+ atespace := ""+ limit := int64(50)+ offset := int64(0)+ if req != nil {+ atespace = req.Atespace+ if req.Limit > 0 {+ limit = req.Limit+ }+ if req.Offset >= 0 {+ offset = req.Offset+ }+ }+ tasks, err := s.store.ListTasks(ctx, atespace, limit, offset)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "listing tasks: %v", err)+ }+ return &v1alpha1.ListTasksResponse{Tasks: tasks}, nil+}++func (s *Server) UpdateTask(ctx context.Context, req *v1alpha1.UpdateTaskRequest) (*v1alpha1.Task, error) {+ if req == nil || req.Task == nil {+ return nil, status.Error(codes.InvalidArgument, "task required")+ }+ task := req.Task+ if err := v1alpha1.ValidateTask(task); err != nil {+ return nil, status.Error(codes.InvalidArgument, err.Error())+ }+ task.Metadata = defaultMetadata(task.Metadata, func(atespace, name string) *v1alpha1.ObjectMeta {+ existing, err := s.store.GetTask(ctx, atespace, name)+ if err != nil {+ return nil+ }+ return existing.GetMetadata()+ })+ if err := s.store.SaveTask(ctx, task); err != nil {+ return nil, status.Errorf(codes.Internal, "saving task: %v", err)+ }+ return task, nil+}++func (s *Server) DeleteTask(ctx context.Context, req *v1alpha1.DeleteTaskRequest) (*v1alpha1.DeleteTaskResponse, error) {+ if req == nil {+ return nil, status.Error(codes.InvalidArgument, "missing request")+ }+ atespace := req.Atespace+ if atespace == "" {+ atespace = "default"+ }+ // Deletion is two-phase: mark the task Terminating and let the controller tear+ // down the actor before the record is removed. Clients poll GetTask for NotFound.+ if err := s.store.MarkTaskDeleting(ctx, atespace, req.Name); err != nil {+ if errors.Is(err, store.ErrNotFound) {+ return nil, status.Errorf(codes.NotFound, "task %q not found in atespace %q", req.Name, atespace)+ }+ return nil, status.Errorf(codes.Internal, "deleting task: %v", err)+ }+ return &v1alpha1.DeleteTaskResponse{}, nil+}++func (s *Server) SuspendTask(ctx context.Context, req *v1alpha1.SuspendTaskRequest) (*v1alpha1.Task, error) {+ if req == nil {+ return nil, status.Error(codes.InvalidArgument, "missing request")+ }+ atespace := req.Atespace+ if atespace == "" {+ atespace = "default"+ }+ task, err := s.store.GetTask(ctx, atespace, req.Name)+ if err != nil {+ if errors.Is(err, store.ErrNotFound) {+ return nil, status.Errorf(codes.NotFound, "task %q not found in atespace %q", req.Name, atespace)+ }+ return nil, status.Errorf(codes.Internal, "getting task: %v", err)+ }+ if task.Spec == nil {+ task.Spec = &v1alpha1.TaskSpec{}+ }+ task.Spec.Suspend = true+ if err := s.store.SaveTask(ctx, task); err != nil {+ return nil, status.Errorf(codes.Internal, "suspending task: %v", err)+ }+ return task, nil+}++func (s *Server) ResumeTask(ctx context.Context, req *v1alpha1.ResumeTaskRequest) (*v1alpha1.Task, error) {+ if req == nil {+ return nil, status.Error(codes.InvalidArgument, "missing request")+ }+ atespace := req.Atespace+ if atespace == "" {+ atespace = "default"+ }+ task, err := s.store.GetTask(ctx, atespace, req.Name)+ if err != nil {+ if errors.Is(err, store.ErrNotFound) {+ return nil, status.Errorf(codes.NotFound, "task %q not found in atespace %q", req.Name, atespace)+ }+ return nil, status.Errorf(codes.Internal, "getting task: %v", err)}+ if task.Spec == nil {+ task.Spec = &v1alpha1.TaskSpec{}+ }+ task.Spec.Suspend = false+ if err := s.store.SaveTask(ctx, task); err != nil {+ return nil, status.Errorf(codes.Internal, "resuming task: %v", err)+ }+ return task, nil}-// CreateInteraction executes a new agentic task with streaming responses.-func (s *Server) CreateInteraction(req *proto.CreateInteractionEvent, stream grpc.ServerStreamingServer[proto.CreateInteractionResponse]) error {+func (s *Server) WatchTask(req *v1alpha1.WatchTaskRequest, stream grpc.ServerStreamingServer[v1alpha1.WatchTaskResponse]) error {+ if req == nil {+ return status.Error(codes.InvalidArgument, "missing request")+ }+ atespace := req.Atespace+ if atespace == "" {+ atespace = "default"+ }ctx := stream.Context()- slog.InfoContext(ctx, "Executing request",- slog.String("request", req.String()),- )+ ch, closer, err := s.store.WatchTask(ctx, atespace, req.Name)+ if err != nil {+ return status.Errorf(codes.Internal, "watching task: %v", err)+ }+ defer closer.Close()- inFlight, cleanup := s.markInFlight(req.ConversationId)- if inFlight {- return status.Errorf(codes.FailedPrecondition, "conversation %q is already in flight", req.ConversationId)+ if initial, err := s.store.GetTask(ctx, atespace, req.Name); err == nil {+ if err := stream.Send(&v1alpha1.WatchTaskResponse{Task: initial, Action: "INITIAL"}); err != nil {+ return err+ }}- defer cleanup()- outputHandler := controller.ExecHandler(func(resp *proto.CreateInteractionResponse) error {- return stream.Send(resp)+ for {+ select {+ case <-ctx.Done():+ return ctx.Err()+ case task, ok := <-ch:+ if !ok {+ return nil+ }+ if err := stream.Send(&v1alpha1.WatchTaskResponse{Task: task, Action: "MODIFIED"}); err != nil {+ return err+ }+ if task.Status != nil && (task.Status.Phase == "Running" || task.Status.Phase == "Failed" || task.Status.Phase == "Completed") {+ return nil+ }+ }+ }+}++// --- Gateways ---++func (s *Server) GetGateway(ctx context.Context, req *v1alpha1.GetGatewayRequest) (*v1alpha1.Gateway, error) {+ if req == nil {+ return nil, status.Error(codes.InvalidArgument, "missing request")+ }+ atespace := req.Atespace+ if atespace == "" {+ atespace = "default"+ }+ gw, err := s.store.GetGateway(ctx, atespace, req.Name)+ if err != nil {+ if errors.Is(err, store.ErrNotFound) {+ return nil, status.Errorf(codes.NotFound, "gateway %q not found in atespace %q", req.Name, atespace)+ }+ return nil, status.Errorf(codes.Internal, "getting gateway: %v", err)+ }+ return gw, nil+}++func (s *Server) ListGateways(ctx context.Context, req *v1alpha1.ListGatewaysRequest) (*v1alpha1.ListGatewaysResponse, error) {+ atespace := ""+ if req != nil {+ atespace = req.Atespace+ }+ gateways, err := s.store.ListGateways(ctx, atespace)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "listing gateways: %v", err)+ }+ return &v1alpha1.ListGatewaysResponse{Gateways: gateways}, nil+}++func (s *Server) UpdateGateway(ctx context.Context, req *v1alpha1.UpdateGatewayRequest) (*v1alpha1.Gateway, error) {+ if req == nil || req.Gateway == nil {+ return nil, status.Error(codes.InvalidArgument, "gateway required")+ }+ req.Gateway.Metadata = defaultMetadata(req.Gateway.Metadata, func(atespace, name string) *v1alpha1.ObjectMeta {+ existing, err := s.store.GetGateway(ctx, atespace, name)+ if err != nil {+ return nil+ }+ return existing.GetMetadata()})- return s.controller.Exec(ctx, req, outputHandler)+ if err := s.store.SaveGateway(ctx, req.Gateway); err != nil {+ return nil, status.Errorf(codes.Internal, "saving gateway: %v", err)+ }+ return req.Gateway, nil+}++func (s *Server) DeleteGateway(ctx context.Context, req *v1alpha1.DeleteGatewayRequest) (*v1alpha1.DeleteGatewayResponse, error) {+ if req == nil {+ return nil, status.Error(codes.InvalidArgument, "missing request")+ }+ atespace := req.Atespace+ if atespace == "" {+ atespace = "default"+ }+ if err := s.store.DeleteGateway(ctx, atespace, req.Name); err != nil {+ return nil, status.Errorf(codes.Internal, "deleting gateway: %v", err)+ }+ return &v1alpha1.DeleteGatewayResponse{}, nil+}++// --- Workspaces ---++func (s *Server) GetWorkspace(ctx context.Context, req *v1alpha1.GetWorkspaceRequest) (*v1alpha1.Workspace, error) {+ if req == nil {+ return nil, status.Error(codes.InvalidArgument, "missing request")+ }+ atespace := req.Atespace+ if atespace == "" {+ atespace = "default"+ }+ ws, err := s.store.GetWorkspace(ctx, atespace, req.Name)+ if err != nil {+ if errors.Is(err, store.ErrNotFound) {+ return nil, status.Errorf(codes.NotFound, "workspace %q not found in atespace %q", req.Name, atespace)+ }+ return nil, status.Errorf(codes.Internal, "getting workspace: %v", err)+ }+ return ws, nil}-// Serve starts the gRPC server on the specified address.-func (s *Server) Serve(address string, opts ...grpc.ServerOption) error {- lis, err := net.Listen("tcp", address)+func (s *Server) ListWorkspaces(ctx context.Context, req *v1alpha1.ListWorkspacesRequest) (*v1alpha1.ListWorkspacesResponse, error) {+ atespace := ""+ if req != nil {+ atespace = req.Atespace+ }+ workspaces, err := s.store.ListWorkspaces(ctx, atespace)if err != nil {- return fmt.Errorf("failed to listen: %w", err)+ return nil, status.Errorf(codes.Internal, "listing workspaces: %v", err)}+ return &v1alpha1.ListWorkspacesResponse{Workspaces: workspaces}, nil+}- opts = append(opts,- grpc.ChainUnaryInterceptor(LoggingInterceptor),- grpc.ChainStreamInterceptor(StreamLoggingInterceptor),- grpc.StatsHandler(otelgrpc.NewServerHandler()),- )+func (s *Server) UpdateWorkspace(ctx context.Context, req *v1alpha1.UpdateWorkspaceRequest) (*v1alpha1.Workspace, error) {+ if req == nil || req.Workspace == nil {+ return nil, status.Error(codes.InvalidArgument, "workspace required")+ }+ req.Workspace.Metadata = defaultMetadata(req.Workspace.Metadata, func(atespace, name string) *v1alpha1.ObjectMeta {+ existing, err := s.store.GetWorkspace(ctx, atespace, name)+ if err != nil {+ return nil+ }+ return existing.GetMetadata()+ })+ if err := s.store.SaveWorkspace(ctx, req.Workspace); err != nil {+ return nil, status.Errorf(codes.Internal, "saving workspace: %v", err)+ }+ return req.Workspace, nil+}- s.grpcServer = grpc.NewServer(opts...)- proto.RegisterInteractionsServiceServer(s.grpcServer, s)+func (s *Server) DeleteWorkspace(ctx context.Context, req *v1alpha1.DeleteWorkspaceRequest) (*v1alpha1.DeleteWorkspaceResponse, error) {+ if req == nil {+ return nil, status.Error(codes.InvalidArgument, "missing request")+ }+ atespace := req.Atespace+ if atespace == "" {+ atespace = "default"+ }+ if err := s.store.DeleteWorkspace(ctx, atespace, req.Name); err != nil {+ return nil, status.Errorf(codes.Internal, "deleting workspace: %v", err)+ }+ return &v1alpha1.DeleteWorkspaceResponse{}, nil+}- // Register standard gRPC Health Check server.- hs := health.NewServer()- hs.SetServingStatus("AX", grpc_health_v1.HealthCheckResponse_SERVING)- grpc_health_v1.RegisterHealthServer(s.grpcServer, hs)+// --- Models ---- if err := s.grpcServer.Serve(lis); err != nil {- return fmt.Errorf("failed to serve: %w", err)+func (s *Server) GetModel(ctx context.Context, req *v1alpha1.GetModelRequest) (*v1alpha1.Model, error) {+ if req == nil {+ return nil, status.Error(codes.InvalidArgument, "missing request")}- return nil+ atespace := req.Atespace+ if atespace == "" {+ atespace = "default"+ }+ model, err := s.store.GetModel(ctx, atespace, req.Name)+ if err != nil {+ if errors.Is(err, store.ErrNotFound) {+ return nil, status.Errorf(codes.NotFound, "model %q not found in atespace %q", req.Name, atespace)+ }+ return nil, status.Errorf(codes.Internal, "getting model: %v", err)+ }+ return model, nil}-// GracefulStop stops the gRPC server gracefully.-func (s *Server) GracefulStop() {- slog.Info("Stopping server gracefully...")- if s.controller != nil {- s.controller.Close()+func (s *Server) ListModels(ctx context.Context, req *v1alpha1.ListModelsRequest) (*v1alpha1.ListModelsResponse, error) {+ atespace := ""+ if req != nil {+ atespace = req.Atespace}- if s.grpcServer != nil {- s.grpcServer.GracefulStop()+ models, err := s.store.ListModels(ctx, atespace)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "listing models: %v", err)}+ return &v1alpha1.ListModelsResponse{Models: models}, nil}-func (s *Server) markInFlight(id string) (exists bool, cleanup func()) {- s.inFlightMu.Lock()- defer s.inFlightMu.Unlock()+func (s *Server) UpdateModel(ctx context.Context, req *v1alpha1.UpdateModelRequest) (*v1alpha1.Model, error) {+ if req == nil || req.Model == nil {+ return nil, status.Error(codes.InvalidArgument, "model required")+ }+ req.Model.Metadata = defaultMetadata(req.Model.Metadata, func(atespace, name string) *v1alpha1.ObjectMeta {+ existing, err := s.store.GetModel(ctx, atespace, name)+ if err != nil {+ return nil+ }+ return existing.GetMetadata()+ })+ if err := s.store.SaveModel(ctx, req.Model); err != nil {+ return nil, status.Errorf(codes.Internal, "saving model: %v", err)+ }+ return req.Model, nil+}- _, ok := s.inFlight[id]- if ok {- return true, func() {}+// defaultMetadata normalizes resource metadata before a save: a missing atespace+// becomes "default", and the creation timestamp is carried over from the existing+// resource (looked up via existing) or set to now for a new one.+func defaultMetadata(meta *v1alpha1.ObjectMeta, existing func(atespace, name string) *v1alpha1.ObjectMeta) *v1alpha1.ObjectMeta {+ if meta == nil {+ meta = &v1alpha1.ObjectMeta{}+ }+ if meta.Atespace == "" {+ meta.Atespace = "default"+ }+ if meta.CreationTimestamp == nil {+ if prev := existing(meta.Atespace, meta.Name); prev.GetCreationTimestamp() != nil {+ meta.CreationTimestamp = prev.GetCreationTimestamp()+ } else {+ meta.CreationTimestamp = timestamppb.Now()+ }}- s.inFlight[id] = struct{}{}+ return meta+}- return false, func() {- s.inFlightMu.Lock()- delete(s.inFlight, id)- s.inFlightMu.Unlock()+func (s *Server) DeleteModel(ctx context.Context, req *v1alpha1.DeleteModelRequest) (*v1alpha1.DeleteModelResponse, error) {+ if req == nil {+ return nil, status.Error(codes.InvalidArgument, "missing request")+ }+ atespace := req.Atespace+ if atespace == "" {+ atespace = "default"+ }+ if err := s.store.DeleteModel(ctx, atespace, req.Name); err != nil {+ return nil, status.Errorf(codes.Internal, "deleting model: %v", err)}+ return &v1alpha1.DeleteModelResponse{}, nil}diff --git a/internal/server/server_test.go b/internal/server/server_test.gonew file mode 100644index 0000000..9cb1726--- /dev/null+++ b/internal/server/server_test.go@@ -0,0 +1,305 @@+// 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 server_test++import (+ "context"+ "net"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/google/ax/internal/server"+ "github.com/google/ax/internal/store/memory"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "google.golang.org/grpc"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/credentials/insecure"+ "google.golang.org/grpc/status"+)++func TestServerHealthzHTTP(t *testing.T) {+ memStore := memory.NewStore()+ srv := server.NewServer(memStore)++ req := httptest.NewRequest(http.MethodGet, "/healthz", nil)+ rec := httptest.NewRecorder()+ srv.Handler().ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200 OK from /healthz, got %d", rec.Code)+ }+ if rec.Body.String() != "ok\n" {+ t.Fatalf("expected 'ok\\n' from /healthz, got %q", rec.Body.String())+ }++ // Verify non-healthz HTTP returns 404+ req404 := httptest.NewRequest(http.MethodGet, "/api/v1/tasks", nil)+ rec404 := httptest.NewRecorder()+ srv.Handler().ServeHTTP(rec404, req404)+ if rec404.Code != http.StatusNotFound {+ t.Fatalf("expected 404 Not Found for /api/v1/tasks, got %d", rec404.Code)+ }+}++func TestServerGRPC(t *testing.T) {+ memStore := memory.NewStore()+ srv := server.NewServer(memStore)++ ln, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("failed to listen: %v", err)+ }+ defer ln.Close()++ httpServer := &http.Server{+ Handler: srv.Handler(),+ }+ httpServer.Protocols = new(http.Protocols)+ httpServer.Protocols.SetHTTP1(true)+ httpServer.Protocols.SetUnencryptedHTTP2(true)++ go func() {+ _ = httpServer.Serve(ln)+ }()+ defer httpServer.Close()++ conn, err := grpc.NewClient(ln.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ t.Fatalf("failed to dial gRPC: %v", err)+ }+ defer conn.Close()++ client := v1alpha1.NewAXClient(conn)+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ // 1. Create one resource of each kind through the typed RPCs. Metadata is left+ // partially empty to exercise server-side defaulting.+ if _, err := client.UpdateGateway(ctx, &v1alpha1.UpdateGatewayRequest{Gateway: &v1alpha1.Gateway{+ Metadata: &v1alpha1.ObjectMeta{Name: "grpc-gw"},+ Spec: &v1alpha1.GatewaySpec{+ Listeners: []*v1alpha1.Listener{{Name: "http", Port: 80, Protocol: "HTTP"}},+ },+ }}); err != nil {+ t.Fatalf("UpdateGateway failed: %v", err)+ }+ if _, err := client.UpdateWorkspace(ctx, &v1alpha1.UpdateWorkspaceRequest{Workspace: &v1alpha1.Workspace{+ Metadata: &v1alpha1.ObjectMeta{Name: "grpc-ws"},+ Spec: &v1alpha1.WorkspaceSpec{},+ }}); err != nil {+ t.Fatalf("UpdateWorkspace failed: %v", err)+ }+ if _, err := client.UpdateModel(ctx, &v1alpha1.UpdateModelRequest{Model: &v1alpha1.Model{+ Metadata: &v1alpha1.ObjectMeta{Name: "grpc-model"},+ Spec: &v1alpha1.ModelSpec{Provider: "google", Model: "gemini-3.8-flash"},+ }}); err != nil {+ t.Fatalf("UpdateModel failed: %v", err)+ }+ if _, err := client.UpdateTask(ctx, &v1alpha1.UpdateTaskRequest{Task: &v1alpha1.Task{+ Metadata: &v1alpha1.ObjectMeta{Name: "grpc-task"},+ Spec: &v1alpha1.TaskSpec{Image: "alpine"},+ }}); err != nil {+ t.Fatalf("UpdateTask failed: %v", err)+ }++ // 2. Defaulting applies to every kind: atespace and creation timestamp are filled in.+ gw, err := client.GetGateway(ctx, &v1alpha1.GetGatewayRequest{Atespace: "default", Name: "grpc-gw"})+ if err != nil {+ t.Fatalf("GetGateway failed: %v", err)+ }+ if gw.GetMetadata().GetAtespace() != "default" || gw.GetMetadata().GetCreationTimestamp() == nil {+ t.Errorf("expected gateway metadata to be defaulted, got %v", gw.GetMetadata())+ }++ // 3. GetTask & ListTasks+ task, err := client.GetTask(ctx, &v1alpha1.GetTaskRequest{Atespace: "default", Name: "grpc-task"})+ if err != nil {+ t.Fatalf("GetTask failed: %v", err)+ }+ if task.Metadata.Name != "grpc-task" {+ t.Errorf("expected name 'grpc-task', got %s", task.Metadata.Name)+ }+ if task.Metadata.CreationTimestamp == nil {+ t.Errorf("expected creation timestamp to be populated on applied task")+ }++ listTasksResp, err := client.ListTasks(ctx, &v1alpha1.ListTasksRequest{Atespace: "default"})+ if err != nil {+ t.Fatalf("ListTasks failed: %v", err)+ }+ if len(listTasksResp.Tasks) != 1 {+ t.Fatalf("expected 1 task in list, got %d", len(listTasksResp.Tasks))+ }+ if listTasksResp.Tasks[0].Metadata.CreationTimestamp == nil {+ t.Errorf("expected creation timestamp on listed task")+ }++ // Test UpdateTask+ task.Spec.Image = "ghcr.io/test/updated-image"+ updatedTask, err := client.UpdateTask(ctx, &v1alpha1.UpdateTaskRequest{Task: task})+ if err != nil {+ t.Fatalf("UpdateTask failed: %v", err)+ }+ if updatedTask.Spec.Image != "ghcr.io/test/updated-image" {+ t.Errorf("expected image 'ghcr.io/test/updated-image', got %s", updatedTask.Spec.Image)+ }++ // 4. Suspend & Resume Task+ suspTask, err := client.SuspendTask(ctx, &v1alpha1.SuspendTaskRequest{Atespace: "default", Name: "grpc-task"})+ if err != nil {+ t.Fatalf("SuspendTask failed: %v", err)+ }+ if !suspTask.Spec.Suspend {+ t.Errorf("expected task to be suspended")+ }++ resTask, err := client.ResumeTask(ctx, &v1alpha1.ResumeTaskRequest{Atespace: "default", Name: "grpc-task"})+ if err != nil {+ t.Fatalf("ResumeTask failed: %v", err)+ }+ if resTask.Spec.Suspend {+ t.Errorf("expected task to be resumed")+ }++ // 5. Gateways+ gw, err = client.GetGateway(ctx, &v1alpha1.GetGatewayRequest{Atespace: "default", Name: "grpc-gw"})+ if err != nil {+ t.Fatalf("GetGateway failed: %v", err)+ }+ if gw.Metadata.Name != "grpc-gw" {+ t.Errorf("expected gateway 'grpc-gw', got %s", gw.Metadata.Name)+ }++ listGatewaysResp, err := client.ListGateways(ctx, &v1alpha1.ListGatewaysRequest{Atespace: "default"})+ if err != nil {+ t.Fatalf("ListGateways failed: %v", err)+ }+ if len(listGatewaysResp.Gateways) != 1 {+ t.Fatalf("expected 1 gateway in list, got %d", len(listGatewaysResp.Gateways))+ }++ // 6. Workspaces+ ws, err := client.GetWorkspace(ctx, &v1alpha1.GetWorkspaceRequest{Atespace: "default", Name: "grpc-ws"})+ if err != nil {+ t.Fatalf("GetWorkspace failed: %v", err)+ }+ if ws.Metadata.Name != "grpc-ws" {+ t.Errorf("expected workspace 'grpc-ws', got %s", ws.Metadata.Name)+ }++ listWorkspacesResp, err := client.ListWorkspaces(ctx, &v1alpha1.ListWorkspacesRequest{Atespace: "default"})+ if err != nil {+ t.Fatalf("ListWorkspaces failed: %v", err)+ }+ if len(listWorkspacesResp.Workspaces) != 1 {+ t.Fatalf("expected 1 workspace in list, got %d", len(listWorkspacesResp.Workspaces))+ }++ // 7. Models+ model, err := client.GetModel(ctx, &v1alpha1.GetModelRequest{Atespace: "default", Name: "grpc-model"})+ if err != nil {+ t.Fatalf("GetModel failed: %v", err)+ }+ if model.Metadata.Name != "grpc-model" {+ t.Errorf("expected model 'grpc-model', got %s", model.Metadata.Name)+ }++ listModelsResp, err := client.ListModels(ctx, &v1alpha1.ListModelsRequest{Atespace: "default"})+ if err != nil {+ t.Fatalf("ListModels failed: %v", err)+ }+ if len(listModelsResp.Models) != 1 {+ t.Fatalf("expected 1 model in list, got %d", len(listModelsResp.Models))+ }++ // 7b. WatchTask (should receive INITIAL state)+ stream, err := client.WatchTask(ctx, &v1alpha1.WatchTaskRequest{Atespace: "default", Name: "grpc-task"})+ if err != nil {+ t.Fatalf("WatchTask failed: %v", err)+ }+ watchMsg, err := stream.Recv()+ if err != nil {+ t.Fatalf("WatchTask Recv failed: %v", err)+ }+ if watchMsg.Action != "INITIAL" {+ t.Errorf("expected INITIAL action, got %s", watchMsg.Action)+ }+ if watchMsg.Task == nil || watchMsg.Task.Metadata == nil || watchMsg.Task.Metadata.Name != "grpc-task" {+ t.Errorf("expected task 'grpc-task' in watch, got %+v", watchMsg.Task)+ }++ // 8. Delete operations+ // Task deletion is two-phase: the RPC marks the task Terminating and the+ // controller removes the record after tearing down the actor.+ if _, err := client.DeleteTask(ctx, &v1alpha1.DeleteTaskRequest{Atespace: "default", Name: "grpc-task"}); err != nil {+ t.Fatalf("DeleteTask failed: %v", err)+ }+ terminating, err := client.GetTask(ctx, &v1alpha1.GetTaskRequest{Atespace: "default", Name: "grpc-task"})+ if err != nil {+ t.Fatalf("GetTask after DeleteTask failed: %v", err)+ }+ if terminating.GetStatus().GetPhase() != v1alpha1.PhaseTerminating {+ t.Errorf("expected phase %q after DeleteTask, got %q", v1alpha1.PhaseTerminating, terminating.GetStatus().GetPhase())+ }+ if _, err := client.DeleteTask(ctx, &v1alpha1.DeleteTaskRequest{Atespace: "default", Name: "no-such-task"}); status.Code(err) != codes.NotFound {+ t.Errorf("expected NotFound deleting a missing task, got %v", err)+ }+ // Stand in for the controller finishing cleanup.+ if err := memStore.DeleteTask(ctx, "default", "grpc-task"); err != nil {+ t.Fatalf("removing task record failed: %v", err)+ }+ if _, err := client.DeleteGateway(ctx, &v1alpha1.DeleteGatewayRequest{Atespace: "default", Name: "grpc-gw"}); err != nil {+ t.Fatalf("DeleteGateway failed: %v", err)+ }+ if _, err := client.DeleteWorkspace(ctx, &v1alpha1.DeleteWorkspaceRequest{Atespace: "default", Name: "grpc-ws"}); err != nil {+ t.Fatalf("DeleteWorkspace failed: %v", err)+ }+ if _, err := client.DeleteModel(ctx, &v1alpha1.DeleteModelRequest{Atespace: "default", Name: "grpc-model"}); err != nil {+ t.Fatalf("DeleteModel failed: %v", err)+ }++ // Check 404 after delete+ _, err = client.GetTask(ctx, &v1alpha1.GetTaskRequest{Atespace: "default", Name: "grpc-task"})+ if status.Code(err) != codes.NotFound {+ t.Fatalf("expected NotFound code, got %v", err)+ }+}++func TestUpdateTask_ValidatesWorkspaceBindings(t *testing.T) {+ srv := server.NewServer(memory.NewStore())+ ctx := context.Background()++ _, err := srv.UpdateTask(ctx, &v1alpha1.UpdateTaskRequest{Task: &v1alpha1.Task{+ Metadata: &v1alpha1.ObjectMeta{Name: "bad"},+ Spec: &v1alpha1.TaskSpec{+ Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a", Path: "/same"}, {Name: "b", Path: "/same"}},+ },+ }})+ if status.Code(err) != codes.InvalidArgument {+ t.Fatalf("expected InvalidArgument for colliding workspace paths, got %v", err)+ }++ _, err = srv.UpdateTask(ctx, &v1alpha1.UpdateTaskRequest{Task: &v1alpha1.Task{+ Metadata: &v1alpha1.ObjectMeta{Name: "good"},+ Spec: &v1alpha1.TaskSpec{+ Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a"}, {Name: "b"}},+ },+ }})+ if err != nil {+ t.Fatalf("expected a valid multi-workspace task to be accepted, got %v", err)+ }+}diff --git a/internal/skills/geminienterprise/client.go b/internal/skills/geminienterprise/client.godeleted file mode 100644index 2e385e9..0000000--- a/internal/skills/geminienterprise/client.go+++ /dev/null@@ -1,400 +0,0 @@-// 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.--// This file is the internal Gemini Enterprise Skill Registry transport client: it talks to the-// Vertex AI v1beta1 REST API (ListSkills / GetSkill / GetSkillRevision /-// skills:retrieve), fetches skill payloads, and safe-unzips them to disk. The-// public, config-driven orchestration lives in materialize.go.--package geminienterprise--import (- "context"- "encoding/base64"- "encoding/json"- "errors"- "fmt"- "io"- "log"- "net/http"- "net/url"- "os"- "path/filepath"- "strings"- "time"-- "golang.org/x/oauth2"- "golang.org/x/oauth2/google"-)--// cloudPlatformScope is the OAuth2 scope required to call Vertex AI (read path-// needs roles/aiplatform.viewer).-const cloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"--// apiVersion is the Vertex AI API version the Skill Registry is exposed under.-const apiVersion = "v1beta1"--// defaultHTTPTimeout bounds a single registry HTTP call.-const defaultHTTPTimeout = 60 * time.Second--// client fetches a selected set of skills from the Gemini Enterprise Skill Registry and-// writes them into a target directory as agentskills.io skill folders.-type client struct {- baseURL string // .../v1beta1/projects/{project}/locations/{location}/skills- http *http.Client- ts oauth2.TokenSource- caps unzipCaps-}--// clientOptions configures a client. newClient fills defaults for optional fields.-type clientOptions struct {- // --- Required ----- // Project is the Google Cloud project that owns the skills.- Project string- // Location is the registry region, e.g. "us-central1". Selects the Vertex- // host (https://{Location}-aiplatform.googleapis.com) unless Endpoint is set.- Location string-- // --- Optional (newClient fills defaults) ----- // Endpoint overrides the API host (scheme+host, no trailing slash), e.g. a- // sandbox host or an httptest.Server URL in unit tests.- Endpoint string- // HTTPClient is the client used for all registry calls. Defaults to- // http.Client{Timeout: 60s}.- HTTPClient *http.Client- // TokenSource provides the OAuth2 bearer token. If nil, ADC is used- // (roles/aiplatform.viewer). Set to a static source in tests.- TokenSource oauth2.TokenSource- // Caps bounds a defensive local unzip of untrusted payloads.- Caps unzipCaps-}--// newClient constructs a client from options. It validates required fields and-// fills defaults; it performs no network I/O.-func newClient(opts clientOptions) (*client, error) {- if opts.Project == "" {- return nil, errors.New("registry: Project is required")- }- if opts.Location == "" {- return nil, errors.New("registry: Location is required")- }-- host := opts.Endpoint- if host == "" {- host = fmt.Sprintf("https://%s-aiplatform.googleapis.com", opts.Location)- }- host = strings.TrimSuffix(host, "/")- baseURL := fmt.Sprintf("%s/%s/projects/%s/locations/%s/skills",- host, apiVersion, opts.Project, opts.Location)-- httpClient := opts.HTTPClient- if httpClient == nil {- httpClient = &http.Client{Timeout: defaultHTTPTimeout}- }-- ts := opts.TokenSource- if ts == nil {- creds, err := google.FindDefaultCredentials(context.Background(), cloudPlatformScope)- if err != nil {- return nil, fmt.Errorf("registry: finding application default credentials: %w", err)- }- ts = creds.TokenSource- }-- return &client{- baseURL: baseURL,- http: httpClient,- ts: ts,- caps: opts.Caps.withDefaults(),- }, nil-}--// selection describes WHICH skills to fetch. Exactly one of the three modes-// should be set (all / by-id / by-query).-type selection struct {- // All fetches every skill returned by ListSkills for the project/location.- All bool- // SkillRefs is an explicit allowlist, each optionally pinned to a revision.- SkillRefs []skillRef- // Query is a semantic search string; the top matches are fetched. TopK bounds- // the result count (<=0 means the server default).- Query string- TopK int-}--// skillRef identifies a single skill to fetch, optionally pinned.-type skillRef struct {- SkillID string- Revision string // empty => latest default revision-}--// fetchResult reports the outcome of a fetch call. fetch is fail-safe: a skill-// that cannot be fetched or unzipped is recorded in skipped.-type fetchResult struct {- materialized []materializedSkill- skipped []skippedSkill-}--// skippedSkill records a skill that was intentionally not written, and why.-type skippedSkill struct {- skillID string- reason error-}--// fetch resolves the selection, fetches each skill's payload, and safe-unzips it-// into targetDir as <targetDir>/<skillID>/... targetDir is created if missing.-//-// claimed enforces first-wins across the whole operation: a skill id whose-// (targetDir, id) was already materialized (by this registry's own selection or-// an earlier registry sharing the dir) is skipped with a warning rather than-// overwriting the winner. regIdx is the registry's index, for log context.-//-// It is fail-safe: individual skill failures are collected in fetchResult.skipped;-// fetch returns a non-nil error only for whole-operation failures.-func (c *client) fetch(ctx context.Context, sel selection, targetDir string, claimed *claimSet, regIdx int) (*fetchResult, error) {- refs, err := c.resolveSelection(ctx, sel)- if err != nil {- return nil, fmt.Errorf("registry: resolving selection: %w", err)- }- if err := os.MkdirAll(targetDir, 0o755); err != nil {- return nil, fmt.Errorf("registry: creating target dir %q: %w", targetDir, err)- }-- res := &fetchResult{}- for _, ref := range refs {- // First-wins: skip (with a warning) any id already materialized into this- // dir, rather than overwriting it.- if won, byRegistry := claimed.claim(targetDir, ref.SkillID, regIdx); !won {- log.Printf("skills: registries[%d] skill %q already materialized into %s by registries[%d]; keeping the first, skipping this one",- regIdx, ref.SkillID, targetDir, byRegistry)- continue- }- mat, err := c.fetchAndWrite(ctx, ref, targetDir)- if err != nil {- res.skipped = append(res.skipped, skippedSkill{skillID: ref.SkillID, reason: err})- continue- }- res.materialized = append(res.materialized, *mat)- }- return res, nil-}--// resolveSelection turns a selection into a concrete list of skillRefs to fetch.-func (c *client) resolveSelection(ctx context.Context, sel selection) ([]skillRef, error) {- switch {- case len(sel.SkillRefs) > 0:- return sel.SkillRefs, nil- case sel.Query != "":- ids, err := c.retrieveSkillIDs(ctx, sel.Query, sel.TopK)- if err != nil {- return nil, err- }- return toRefs(ids), nil- case sel.All:- ids, err := c.listSkillIDs(ctx)- if err != nil {- return nil, err- }- return toRefs(ids), nil- default:- return nil, errors.New("empty selection: set All, SkillRefs, or Query")- }-}--// fetchAndWrite fetches one skill's payload (latest or pinned) and unzips it.-func (c *client) fetchAndWrite(ctx context.Context, ref skillRef, targetDir string) (*materializedSkill, error) {- if ref.SkillID == "" {- return nil, errors.New("skill ref has empty SkillID")- }- payloadB64, revision, err := c.fetchPayload(ctx, ref)- if err != nil {- return nil, err- }- zipped, err := base64.StdEncoding.DecodeString(payloadB64)- if err != nil {- return nil, fmt.Errorf("decoding payload: %w", err)- }- skillDir := filepath.Join(targetDir, ref.SkillID)- // Replace any prior materialization of this skill so stale files don't linger.- if err := os.RemoveAll(skillDir); err != nil {- return nil, fmt.Errorf("clearing %q: %w", skillDir, err)- }- if err := safeUnzip(zipped, skillDir, c.caps); err != nil {- // Leave no partial dir behind on failure.- _ = os.RemoveAll(skillDir)- return nil, fmt.Errorf("unzipping: %w", err)- }- return &materializedSkill{SkillID: ref.SkillID, Revision: revision, Dir: skillDir}, nil-}--// fetchPayload returns the base64 zippedFilesystem and the concrete revision id-// for a skill ref (GetSkill for latest, GetSkillRevision when pinned).-func (c *client) fetchPayload(ctx context.Context, ref skillRef) (payloadB64, revision string, err error) {- if ref.Revision != "" {- // GetSkillRevision: payload is nested under "skill".- var resp skillRevisionResponse- if err := c.getJSON(ctx, c.baseURL+"/"+ref.SkillID+"/revisions/"+ref.Revision, &resp); err != nil {- return "", "", err- }- if resp.Skill.ZippedFilesystem == "" {- return "", "", errors.New("GetSkillRevision: empty zippedFilesystem")- }- return resp.Skill.ZippedFilesystem, ref.Revision, nil- }- // GetSkill: payload at top level.- var resp skillResponse- if err := c.getJSON(ctx, c.baseURL+"/"+ref.SkillID, &resp); err != nil {- return "", "", err- }- if resp.ZippedFilesystem == "" {- return "", "", errors.New("GetSkill: empty zippedFilesystem")- }- return resp.ZippedFilesystem, resp.currentRevision(), nil-}--// listSkillIDs pages through ListSkills and returns all skill ids.-func (c *client) listSkillIDs(ctx context.Context) ([]string, error) {- var ids []string- pageToken := ""- for {- u := c.baseURL- if pageToken != "" {- u += "?pageToken=" + url.QueryEscape(pageToken)- }- var resp listSkillsResponse- if err := c.getJSON(ctx, u, &resp); err != nil {- return nil, err- }- for _, s := range resp.Skills {- if id := s.id(); id != "" {- ids = append(ids, id)- }- }- if resp.NextPageToken == "" {- return ids, nil- }- pageToken = resp.NextPageToken- }-}--// retrieveSkillIDs runs semantic search (skills:retrieve) and returns skill ids.-func (c *client) retrieveSkillIDs(ctx context.Context, query string, topK int) ([]string, error) {- u := c.baseURL + ":retrieve?query=" + url.QueryEscape(query)- if topK > 0 {- u += fmt.Sprintf("&topK=%d", topK)- }- var resp retrieveSkillsResponse- if err := c.getJSON(ctx, u, &resp); err != nil {- return nil, err- }- var ids []string- for _, r := range resp.RetrievedSkills {- if id := lastSegment(r.SkillName); id != "" {- ids = append(ids, id)- }- }- return ids, nil-}--// getJSON issues an authenticated GET and decodes the JSON body into out.-func (c *client) getJSON(ctx context.Context, rawURL string, out any) error {- req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)- if err != nil {- return err- }- tok, err := c.ts.Token()- if err != nil {- return fmt.Errorf("obtaining token: %w", err)- }- tok.SetAuthHeader(req)- req.Header.Set("Content-Type", "application/json")-- resp, err := c.http.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()- body, _ := io.ReadAll(resp.Body)- if resp.StatusCode != http.StatusOK {- return fmt.Errorf("HTTP %d: %s", resp.StatusCode, truncate(string(body), 512))- }- if err := json.Unmarshal(body, out); err != nil {- return fmt.Errorf("decoding response: %w", err)- }- return nil-}--// --- Wire types (AIP-standard shapes; see the design doc appendix). -----type listSkillsResponse struct {- Skills []skillResponse `json:"skills"`- NextPageToken string `json:"nextPageToken"`-}--// retrieveSkillsResponse is a skills:retrieve result. Each hit carries the skill-// resource name in a flat "skillName" field (not a nested skill object).-type retrieveSkillsResponse struct {- RetrievedSkills []struct {- SkillName string `json:"skillName"` // projects/.../skills/{id}- } `json:"retrievedSkills"`-}--// skillResponse is a Skill resource. GetSkill returns the payload at top level.-type skillResponse struct {- Name string `json:"name"` // projects/.../skills/{id}- DisplayName string `json:"displayName"`- Description string `json:"description"`- State string `json:"state"`- DefaultRevision string `json:"defaultRevision"`- ZippedFilesystem string `json:"zippedFilesystem"`-}--// skillRevisionResponse is a GetSkillRevision result; the payload is nested-// under "skill".-type skillRevisionResponse struct {- Name string `json:"name"` // projects/.../skills/{id}/revisions/{rev}- Skill skillResponse `json:"skill"`-}--// id extracts the trailing skill id from a resource name.-func (s skillResponse) id() string { return lastSegment(s.Name) }--// currentRevision reports the skill's default revision id, if the server provided-// one (best-effort; may be empty for "latest").-func (s skillResponse) currentRevision() string { return lastSegment(s.DefaultRevision) }--func lastSegment(resourceName string) string {- if resourceName == "" {- return ""- }- parts := strings.Split(resourceName, "/")- return parts[len(parts)-1]-}--func toRefs(ids []string) []skillRef {- refs := make([]skillRef, 0, len(ids))- for _, id := range ids {- refs = append(refs, skillRef{SkillID: id})- }- return refs-}--func truncate(s string, n int) string {- if len(s) <= n {- return s- }- return s[:n] + "...(truncated)"-}diff --git a/internal/skills/geminienterprise/client_test.go b/internal/skills/geminienterprise/client_test.godeleted file mode 100644index 39285b5..0000000--- a/internal/skills/geminienterprise/client_test.go+++ /dev/null@@ -1,414 +0,0 @@-// 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 geminienterprise--import (- "archive/zip"- "bytes"- "context"- "encoding/base64"- "encoding/json"- "fmt"- "net/http"- "net/http/httptest"- "os"- "path/filepath"- "strings"- "testing"-- "golang.org/x/oauth2"-)--// zipFixtureB64 builds an in-memory zip from name->content and returns the base64-// string the registry would return in `zippedFilesystem`.-func zipFixtureB64(t *testing.T, files map[string]string) string {- t.Helper()- var buf bytes.Buffer- zw := zip.NewWriter(&buf)- for name, content := range files {- w, err := zw.Create(name)- if err != nil {- t.Fatalf("zip create %q: %v", name, err)- }- if _, err := w.Write([]byte(content)); err != nil {- t.Fatalf("zip write %q: %v", name, err)- }- }- if err := zw.Close(); err != nil {- t.Fatalf("zip close: %v", err)- }- return base64.StdEncoding.EncodeToString(buf.Bytes())-}--// rawZipFixture returns the raw zip bytes (for direct safeUnzip tests).-func rawZipFixture(t *testing.T, files map[string]string) []byte {- t.Helper()- b, err := base64.StdEncoding.DecodeString(zipFixtureB64(t, files))- if err != nil {- t.Fatalf("decode fixture: %v", err)- }- return b-}--// newFakeClient returns a client pointed at an httptest.Server whose handler is-// provided by the caller, with a no-op token source.-func newFakeClient(t *testing.T, handler http.HandlerFunc) *client {- t.Helper()- srv := httptest.NewServer(handler)- t.Cleanup(srv.Close)- c, err := newClient(clientOptions{- Project: "test-project",- Location: "us-central1",- Endpoint: srv.URL,- TokenSource: oauth2.StaticTokenSource(&oauth2.Token{AccessToken: "fake"}),- })- if err != nil {- t.Fatalf("newClient: %v", err)- }- return c-}--func TestFetchByID_Latest(t *testing.T) {- payload := zipFixtureB64(t, map[string]string{- "SKILL.md": "---\nname: emoji\n---\n# do stuff",- "scripts/x.sh": "echo hi",- })- c := newFakeClient(t, func(w http.ResponseWriter, r *http.Request) {- // GetSkill: .../skills/emoji -> zippedFilesystem at top level.- if !strings.HasSuffix(r.URL.Path, "/skills/emoji") {- http.Error(w, "unexpected path "+r.URL.Path, http.StatusNotFound)- return- }- writeJSON(t, w, skillResponse{- Name: "projects/p/locations/us-central1/skills/emoji",- DefaultRevision: "projects/p/locations/us-central1/skills/emoji/revisions/rev-7",- ZippedFilesystem: payload,- })- })-- dir := t.TempDir()- res, err := c.fetch(context.Background(),- selection{SkillRefs: []skillRef{{SkillID: "emoji"}}}, dir, newClaimSet(), 0)- if err != nil {- t.Fatalf("fetch: %v", err)- }- if len(res.skipped) != 0 {- t.Fatalf("unexpected skipped: %+v", res.skipped)- }- if len(res.materialized) != 1 {- t.Fatalf("materialized = %d, want 1", len(res.materialized))- }- got := res.materialized[0]- if got.SkillID != "emoji" || got.Revision != "rev-7" {- t.Errorf("got %+v, want SkillID=emoji Revision=rev-7", got)- }- assertFile(t, filepath.Join(dir, "emoji", "SKILL.md"), "---\nname: emoji\n---\n# do stuff")- assertFile(t, filepath.Join(dir, "emoji", "scripts", "x.sh"), "echo hi")-}--func TestFetchByID_PinnedRevision(t *testing.T) {- payload := zipFixtureB64(t, map[string]string{"SKILL.md": "pinned"})- c := newFakeClient(t, func(w http.ResponseWriter, r *http.Request) {- // GetSkillRevision: .../skills/emoji/revisions/rev-3 -> nested under "skill".- if !strings.HasSuffix(r.URL.Path, "/skills/emoji/revisions/rev-3") {- http.Error(w, "unexpected path "+r.URL.Path, http.StatusNotFound)- return- }- writeJSON(t, w, skillRevisionResponse{- Name: "projects/p/locations/us-central1/skills/emoji/revisions/rev-3",- Skill: skillResponse{ZippedFilesystem: payload},- })- })-- dir := t.TempDir()- res, err := c.fetch(context.Background(),- selection{SkillRefs: []skillRef{{SkillID: "emoji", Revision: "rev-3"}}}, dir, newClaimSet(), 0)- if err != nil {- t.Fatalf("fetch: %v", err)- }- if len(res.materialized) != 1 || res.materialized[0].Revision != "rev-3" {- t.Fatalf("got %+v, want one skill pinned at rev-3", res.materialized)- }- assertFile(t, filepath.Join(dir, "emoji", "SKILL.md"), "pinned")-}--func TestFetchAll_Paginated(t *testing.T) {- pa := zipFixtureB64(t, map[string]string{"SKILL.md": "a"})- pb := zipFixtureB64(t, map[string]string{"SKILL.md": "b"})- c := newFakeClient(t, func(w http.ResponseWriter, r *http.Request) {- switch {- case strings.HasSuffix(r.URL.Path, "/skills") && r.URL.Query().Get("pageToken") == "":- writeJSON(t, w, listSkillsResponse{- Skills: []skillResponse{{Name: ".../skills/a"}},- NextPageToken: "TOK",- })- case strings.HasSuffix(r.URL.Path, "/skills") && r.URL.Query().Get("pageToken") == "TOK":- writeJSON(t, w, listSkillsResponse{Skills: []skillResponse{{Name: ".../skills/b"}}})- case strings.HasSuffix(r.URL.Path, "/skills/a"):- writeJSON(t, w, skillResponse{Name: ".../skills/a", ZippedFilesystem: pa})- case strings.HasSuffix(r.URL.Path, "/skills/b"):- writeJSON(t, w, skillResponse{Name: ".../skills/b", ZippedFilesystem: pb})- default:- http.Error(w, "unexpected "+r.URL.String(), http.StatusNotFound)- }- })-- dir := t.TempDir()- res, err := c.fetch(context.Background(), selection{All: true}, dir, newClaimSet(), 0)- if err != nil {- t.Fatalf("fetch: %v", err)- }- if len(res.materialized) != 2 {- t.Fatalf("materialized = %d, want 2 (paged)", len(res.materialized))- }- assertFile(t, filepath.Join(dir, "a", "SKILL.md"), "a")- assertFile(t, filepath.Join(dir, "b", "SKILL.md"), "b")-}--func TestFetchByQuery(t *testing.T) {- payload := zipFixtureB64(t, map[string]string{"SKILL.md": "found"})- c := newFakeClient(t, func(w http.ResponseWriter, r *http.Request) {- switch {- case strings.Contains(r.URL.Path, "/skills:retrieve"):- if got := r.URL.Query().Get("query"); got != "emoji stuff" {- t.Errorf("query = %q, want %q", got, "emoji stuff")- }- writeJSON(t, w, retrieveSkillsResponse{- RetrievedSkills: []struct {- SkillName string `json:"skillName"`- }{{SkillName: ".../skills/emoji"}},- })- case strings.HasSuffix(r.URL.Path, "/skills/emoji"):- writeJSON(t, w, skillResponse{Name: ".../skills/emoji", ZippedFilesystem: payload})- default:- http.Error(w, "unexpected "+r.URL.String(), http.StatusNotFound)- }- })-- dir := t.TempDir()- res, err := c.fetch(context.Background(),- selection{Query: "emoji stuff", TopK: 3}, dir, newClaimSet(), 0)- if err != nil {- t.Fatalf("fetch: %v", err)- }- if len(res.materialized) != 1 {- t.Fatalf("materialized = %d, want 1", len(res.materialized))- }- assertFile(t, filepath.Join(dir, "emoji", "SKILL.md"), "found")-}--func TestFetchFailSafe_OneBadSkillSkipped(t *testing.T) {- good := zipFixtureB64(t, map[string]string{"SKILL.md": "ok"})- c := newFakeClient(t, func(w http.ResponseWriter, r *http.Request) {- switch {- case strings.HasSuffix(r.URL.Path, "/skills/good"):- writeJSON(t, w, skillResponse{Name: ".../skills/good", ZippedFilesystem: good})- case strings.HasSuffix(r.URL.Path, "/skills/bad"):- http.Error(w, "boom", http.StatusInternalServerError)- default:- http.Error(w, "unexpected", http.StatusNotFound)- }- })-- dir := t.TempDir()- res, err := c.fetch(context.Background(),- selection{SkillRefs: []skillRef{{SkillID: "good"}, {SkillID: "bad"}}}, dir, newClaimSet(), 0)- if err != nil {- t.Fatalf("fetch returned whole-op error, want fail-safe: %v", err)- }- if len(res.materialized) != 1 || res.materialized[0].SkillID != "good" {- t.Errorf("materialized = %+v, want only 'good'", res.materialized)- }- if len(res.skipped) != 1 || res.skipped[0].skillID != "bad" {- t.Errorf("skipped = %+v, want only 'bad'", res.skipped)- }- // The bad skill left no directory behind.- if _, err := os.Stat(filepath.Join(dir, "bad")); !os.IsNotExist(err) {- t.Errorf("expected no dir for 'bad', stat err = %v", err)- }-}--func TestFetch_FirstWinsAcrossSharedClaimSet(t *testing.T) {- // Two fetches (simulating two registries) into the SAME dir with a SHARED- // claim set. Both offer skill id "dup"; only the first should be written.- payloadA := zipFixtureB64(t, map[string]string{"SKILL.md": "from-A"})- payloadB := zipFixtureB64(t, map[string]string{"SKILL.md": "from-B"})-- makeClient := func(payload string) *client {- return newFakeClient(t, func(w http.ResponseWriter, r *http.Request) {- if !strings.HasSuffix(r.URL.Path, "/skills/dup") {- http.Error(w, "unexpected "+r.URL.Path, http.StatusNotFound)- return- }- writeJSON(t, w, skillResponse{Name: ".../skills/dup", ZippedFilesystem: payload})- })- }-- dir := t.TempDir()- claimed := newClaimSet()- sel := selection{SkillRefs: []skillRef{{SkillID: "dup"}}}-- // Registry 0 wins.- res0, err := makeClient(payloadA).fetch(context.Background(), sel, dir, claimed, 0)- if err != nil {- t.Fatalf("fetch #0: %v", err)- }- if len(res0.materialized) != 1 {- t.Fatalf("registry 0 materialized %d, want 1", len(res0.materialized))- }-- // Registry 1 offers the same id into the same dir -> skipped (not written).- res1, err := makeClient(payloadB).fetch(context.Background(), sel, dir, claimed, 1)- if err != nil {- t.Fatalf("fetch #1: %v", err)- }- if len(res1.materialized) != 0 {- t.Errorf("registry 1 materialized %d, want 0 (first-wins)", len(res1.materialized))- }- // The content on disk must be the FIRST writer's.- assertFile(t, filepath.Join(dir, "dup", "SKILL.md"), "from-A")-}--func TestNewClientValidation(t *testing.T) {- if _, err := newClient(clientOptions{Location: "us-central1"}); err == nil {- t.Error("expected error for missing Project")- }- if _, err := newClient(clientOptions{Project: "p"}); err == nil {- t.Error("expected error for missing Location")- }-}--// --- safeUnzip unit tests -----func TestSafeUnzip_Basic(t *testing.T) {- z := rawZipFixture(t, map[string]string{- "SKILL.md": "hi",- "scripts/tool.sh": "run",- "references/a.txt": "ref",- })- dir := t.TempDir()- if err := safeUnzip(z, filepath.Join(dir, "s"), unzipCaps{}.withDefaults()); err != nil {- t.Fatalf("safeUnzip: %v", err)- }- assertFile(t, filepath.Join(dir, "s", "SKILL.md"), "hi")- assertFile(t, filepath.Join(dir, "s", "scripts", "tool.sh"), "run")-}--func TestSafeUnzip_PreservesExecutableMode(t *testing.T) {- // Build a zip with an executable script (0755) and a normal file (0644),- // setting per-entry modes via CreateHeader.- var buf bytes.Buffer- zw := zip.NewWriter(&buf)- writeEntry := func(name, content string, mode os.FileMode) {- hdr := &zip.FileHeader{Name: name, Method: zip.Deflate}- hdr.SetMode(mode)- w, err := zw.CreateHeader(hdr)- if err != nil {- t.Fatalf("CreateHeader %q: %v", name, err)- }- if _, err := w.Write([]byte(content)); err != nil {- t.Fatalf("write %q: %v", name, err)- }- }- writeEntry("scripts/tool.sh", "#!/bin/sh\necho hi\n", 0o755)- writeEntry("SKILL.md", "hi", 0o644)- if err := zw.Close(); err != nil {- t.Fatalf("zip close: %v", err)- }-- dir := t.TempDir()- if err := safeUnzip(buf.Bytes(), filepath.Join(dir, "s"), unzipCaps{}.withDefaults()); err != nil {- t.Fatalf("safeUnzip: %v", err)- }-- scriptInfo, err := os.Stat(filepath.Join(dir, "s", "scripts", "tool.sh"))- if err != nil {- t.Fatal(err)- }- if scriptInfo.Mode().Perm()&0o100 == 0 {- t.Errorf("script mode = %v, want owner-execute bit set (0755 preserved)", scriptInfo.Mode().Perm())- }- mdInfo, err := os.Stat(filepath.Join(dir, "s", "SKILL.md"))- if err != nil {- t.Fatal(err)- }- if mdInfo.Mode().Perm()&0o111 != 0 {- t.Errorf("SKILL.md mode = %v, want no execute bits (0644)", mdInfo.Mode().Perm())- }-}--func TestSafeUnzip_ZipSlipRejected(t *testing.T) {- for _, bad := range []string{"../evil.txt", "a/../../evil.txt", "/etc/evil"} {- z := rawZipFixture(t, map[string]string{bad: "x"})- dir := t.TempDir()- err := safeUnzip(z, filepath.Join(dir, "s"), unzipCaps{}.withDefaults())- if err == nil {- t.Errorf("entry %q: expected rejection, got nil", bad)- continue- }- if _, statErr := os.Stat(filepath.Join(dir, "evil.txt")); !os.IsNotExist(statErr) {- t.Errorf("entry %q: file escaped destination", bad)- }- }-}--func TestSafeUnzip_TooManyFiles(t *testing.T) {- files := map[string]string{}- for i := 0; i < 5; i++ {- files[fmt.Sprintf("f%d.txt", i)] = "x"- }- z := rawZipFixture(t, files)- err := safeUnzip(z, t.TempDir(), unzipCaps{MaxFiles: 3}.withDefaults())- if err == nil || !strings.Contains(err.Error(), "exceeds cap") {- t.Fatalf("expected MaxFiles cap error, got %v", err)- }-}--func TestSafeUnzip_TooLarge(t *testing.T) {- z := rawZipFixture(t, map[string]string{"big.txt": strings.Repeat("A", 1000)})- err := safeUnzip(z, t.TempDir(), unzipCaps{MaxTotalUnzippedBytes: 100}.withDefaults())- if err == nil || !strings.Contains(err.Error(), "size") {- t.Fatalf("expected size cap error, got %v", err)- }-}--func TestSafeUnzip_TooDeep(t *testing.T) {- z := rawZipFixture(t, map[string]string{"a/b/c/d/e/f/g/h/i/j/deep.txt": "x"})- err := safeUnzip(z, t.TempDir(), unzipCaps{MaxDepth: 3}.withDefaults())- if err == nil || !strings.Contains(err.Error(), "depth") {- t.Fatalf("expected depth cap error, got %v", err)- }-}--// --- helpers -----func writeJSON(t *testing.T, w http.ResponseWriter, v any) {- t.Helper()- w.Header().Set("Content-Type", "application/json")- if err := json.NewEncoder(w).Encode(v); err != nil {- t.Fatalf("encode response: %v", err)- }-}--func assertFile(t *testing.T, path, want string) {- t.Helper()- got, err := os.ReadFile(path)- if err != nil {- t.Fatalf("reading %q: %v", path, err)- }- if string(got) != want {- t.Errorf("%q = %q, want %q", path, got, want)- }-}diff --git a/internal/skills/geminienterprise/materialize.go b/internal/skills/geminienterprise/materialize.godeleted file mode 100644index d48a715..0000000--- a/internal/skills/geminienterprise/materialize.go+++ /dev/null@@ -1,165 +0,0 @@-// 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 geminienterprise turns a harness's skills configuration into on-disk-// skill folders. It sources agentskills.io skills from the Gemini Enterprise-// Skill Registry (a managed, versioned catalog exposed over the Vertex AI-// v1beta1 REST API) and writes each skill to <target_dir>/<skill-id>/.-//-// // It is harness-agnostic: it only writes files and reports what it wrote (as-// []skills.Group). It knows nothing about specific harnesses, SKILLS_DIR, or-// discovery pointers — callers decide how a given harness is told where its-// skills are.-//-// Scope: read-only. This package never creates, updates, or deletes registry-// skills (authoring is out of scope).-package geminienterprise--import (- "context"- "log"- "os"- "strings"-- "github.com/google/ax/internal/config"- "github.com/google/ax/internal/skills"-)--// Environment fallbacks for project/location (the registry target_dir is a-// required config field, so it has no env fallback).-const (- envCloudProject = "GOOGLE_CLOUD_PROJECT"- envCloudLocation = "GOOGLE_CLOUD_LOCATION"-- defaultRegistryLocation = "us-central1"-)--// materializedSkill records one skill written to disk. It carries the resolved-// revision (registry-specific detail) internally; Materialize converts these to-// []skills.Group at its boundary.-type materializedSkill struct {- SkillID string- Revision string- Dir string // path of the written skill folder (<target_dir>/<skill-id>/)-}--// Materialize materializes every enabled registry in sc into its configured-// target_dir (each skill at <target_dir>/<skill-id>/) and reports what it wrote.-//-// target_dir is a required, validated config field (see config.SkillsConfig), so-// this does not fall back to any env var or the working directory. It is-// fail-safe: disabled registries are skipped, and any registry error is logged-// and swallowed so a skill problem never blocks harness creation. When the same-// skill id would be written into the same dir more than once (within one-// registry's selection, or across registries sharing a dir), the FIRST writer-// wins and later duplicates are skipped with a warning. Substrate/pod-// materialization is a separate, later path; this wires the local flow only.-func Materialize(ctx context.Context, sc config.SkillsConfig) []skills.Group {- var groups []skills.Group- // claimed tracks (target_dir, skill-id) pairs already written across all- // registries so the FIRST writer of an id into a dir wins; later duplicates- // (within one registry's selection, or across registries sharing a dir) are- // skipped with a warning instead of silently overwriting.- claimed := newClaimSet()- // TODO: fetches are sequential (both here and per-skill in client.fetch);- // consider bounded-concurrent download/unzip to speed up materialization.- // TODO: bound overall materialization with a deadline (only per-call HTTP- // timeouts exist today); e.g. a default ~120s that users can override.- for i := range sc.Registries {- rc := sc.Registries[i]- if !rc.Enabled {- continue- }- project := firstNonEmpty(rc.Project, os.Getenv(envCloudProject))- if project == "" {- log.Printf("skills: registries[%d] enabled but no project (config or %s); skipping", i, envCloudProject)- continue- }- location := firstNonEmpty(rc.Location, os.Getenv(envCloudLocation), defaultRegistryLocation)-- c, err := newClient(clientOptions{Project: project, Location: location})- if err != nil {- log.Printf("skills: registries[%d] client init failed: %v; skipping", i, err)- continue- }- out, err := c.fetch(ctx, selectionFromConfig(rc), rc.TargetDir, claimed, i)- if err != nil {- log.Printf("skills: registries[%d] fetch failed: %v; continuing", i, err)- continue- }- for _, s := range out.skipped {- log.Printf("skills: registries[%d] skipped %q: %v", i, s.skillID, s.reason)- }- if len(out.materialized) == 0 {- continue- }- log.Printf("skills: registries[%d] materialized %d skill(s) into %s (skipped %d)",- i, len(out.materialized), rc.TargetDir, len(out.skipped))- group := skills.Group{Dir: rc.TargetDir}- for _, m := range out.materialized {- group.Skills = append(group.Skills, skills.Skill{ID: m.SkillID, Dir: m.Dir})- }- groups = append(groups, group)- }- return groups-}--// claimSet tracks which (dir, skill-id) pairs have already been materialized, so-// the first writer of a given id into a given dir wins.-type claimSet struct {- seen map[string]int // key -> registry index that first claimed it-}--func newClaimSet() *claimSet { return &claimSet{seen: map[string]int{}} }--func claimKey(dir, id string) string { return dir + "\x00" + id }--// claim records (dir, id) as owned by registry regIdx and returns true if this-// is the first claim. If already claimed, it returns false and the index of the-// registry that won.-func (c *claimSet) claim(dir, id string, regIdx int) (won bool, byRegistry int) {- key := claimKey(dir, id)- if prev, ok := c.seen[key]; ok {- return false, prev- }- c.seen[key] = regIdx- return true, regIdx-}--// selectionFromConfig maps a SkillsRegistryConfig to a selection:-// - explicit Skills list => by-id (with optional revision pin)-// - else Query => by-query-// - else => all-func selectionFromConfig(rc config.SkillsRegistryConfig) selection {- if len(rc.Skills) > 0 {- refs := make([]skillRef, 0, len(rc.Skills))- for _, s := range rc.Skills {- refs = append(refs, skillRef{SkillID: s.ID, Revision: s.Revision})- }- return selection{SkillRefs: refs}- }- if rc.Query != nil && strings.TrimSpace(rc.Query.Text) != "" {- return selection{Query: rc.Query.Text, TopK: rc.Query.TopK}- }- return selection{All: true}-}--func firstNonEmpty(vals ...string) string {- for _, v := range vals {- if v != "" {- return v- }- }- return ""-}diff --git a/internal/skills/geminienterprise/materialize_test.go b/internal/skills/geminienterprise/materialize_test.godeleted file mode 100644index 3f99951..0000000--- a/internal/skills/geminienterprise/materialize_test.go+++ /dev/null@@ -1,100 +0,0 @@-// 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 geminienterprise--import (- "context"- "testing"-- "github.com/google/ax/internal/config"-)--func TestSelectionFromConfig(t *testing.T) {- t.Run("explicit skills take precedence", func(t *testing.T) {- rc := config.SkillsRegistryConfig{- Skills: []config.SkillRefConfig{{ID: "emoji"}, {ID: "lowercase", Revision: "rev-3"}},- Query: &config.SkillsQueryConfig{Text: "ignored"},- }- sel := selectionFromConfig(rc)- if sel.All || sel.Query != "" {- t.Fatalf("got %+v, want by-id", sel)- }- if len(sel.SkillRefs) != 2 ||- sel.SkillRefs[0].SkillID != "emoji" || sel.SkillRefs[0].Revision != "" ||- sel.SkillRefs[1].SkillID != "lowercase" || sel.SkillRefs[1].Revision != "rev-3" {- t.Fatalf("refs = %+v", sel.SkillRefs)- }- })-- t.Run("query when no explicit skills", func(t *testing.T) {- sel := selectionFromConfig(config.SkillsRegistryConfig{- Query: &config.SkillsQueryConfig{Text: "find gcp", TopK: 5},- })- if sel.Query != "find gcp" || sel.TopK != 5 {- t.Fatalf("got %+v, want query=find gcp topK=5", sel)- }- })-- t.Run("empty query text falls through to all", func(t *testing.T) {- sel := selectionFromConfig(config.SkillsRegistryConfig{Query: &config.SkillsQueryConfig{Text: " "}})- if !sel.All {- t.Fatalf("got %+v, want All (blank query text)", sel)- }- })-- t.Run("all when nothing set", func(t *testing.T) {- if sel := selectionFromConfig(config.SkillsRegistryConfig{}); !sel.All {- t.Fatalf("got %+v, want All", sel)- }- })-}--func TestClaimSet_FirstWins(t *testing.T) {- cs := newClaimSet()- if won, by := cs.claim("/dir", "s1", 0); !won || by != 0 {- t.Fatalf("first claim = (%v,%d), want (true,0)", won, by)- }- // Same (dir,id) again -> loses, reports the first registry (0).- if won, by := cs.claim("/dir", "s1", 2); won || by != 0 {- t.Fatalf("dup claim = (%v,%d), want (false,0)", won, by)- }- // Same id, different dir -> independent, wins.- if won, _ := cs.claim("/other", "s1", 1); !won {- t.Fatal("same id in different dir should win")- }- // Different id, same dir -> wins.- if won, _ := cs.claim("/dir", "s2", 1); !won {- t.Fatal("different id in same dir should win")- }-}--func TestMaterialize_DisabledIsEmpty(t *testing.T) {- // Disabled config => no-op, empty result, no error/panic.- if res := Materialize(context.Background(), config.SkillsConfig{}); len(res) != 0 {- t.Errorf("disabled Materialize = %+v, want empty", res)- }-}--func TestMaterialize_EnabledNoProjectIsEmpty(t *testing.T) {- // Enabled with a target_dir but no project (config empty, GOOGLE_CLOUD_PROJECT- // unset) => fail-safe empty result (no panic, no materialization).- t.Setenv(envCloudProject, "")- sc := config.SkillsConfig{Registries: []config.SkillsRegistryConfig{- {Enabled: true, TargetDir: t.TempDir()},- }}- if res := Materialize(context.Background(), sc); len(res) != 0 {- t.Errorf("no-project Materialize = %+v, want empty", res)- }-}diff --git a/internal/skills/geminienterprise/unzip.go b/internal/skills/geminienterprise/unzip.godeleted file mode 100644index df1046b..0000000--- a/internal/skills/geminienterprise/unzip.go+++ /dev/null@@ -1,202 +0,0 @@-// 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 geminienterprise--import (- "archive/zip"- "bytes"- "fmt"- "io"- "os"- "path/filepath"- "strings"-)--// unzipCaps bounds a defensive local unzip of an untrusted skill payload. Even-// though the registry validates payloads server-side, the local unzip must-// independently guard against Zip-Slip (entries with "..", absolute paths, or-// symlinks) and resource exhaustion.-type unzipCaps struct {- // MaxFiles caps the number of entries per skill archive.- MaxFiles int- // MaxTotalUnzippedBytes caps the total unzipped size per skill archive.- MaxTotalUnzippedBytes int64- // MaxDepth caps directory nesting depth within a skill archive.- MaxDepth int-}--// The registry's documented payload caps, used as defaults.-const (- defaultMaxFiles = 10_000- defaultMaxTotalBytes = 500 << 20 // 500 MiB- defaultMaxDepth = 8-)--// withDefaults fills any zero-valued cap with the registry's documented limit.-func (c unzipCaps) withDefaults() unzipCaps {- if c.MaxFiles <= 0 {- c.MaxFiles = defaultMaxFiles- }- if c.MaxTotalUnzippedBytes <= 0 {- c.MaxTotalUnzippedBytes = defaultMaxTotalBytes- }- if c.MaxDepth <= 0 {- c.MaxDepth = defaultMaxDepth- }- return c-}--// safeUnzip extracts a zip archive into destDir, defensively rejecting unsafe-// entries and enforcing caps. destDir must not exist yet or must be safe to-// write into; callers clear it beforehand.-//-// Guards:-// - Zip-Slip: every entry must resolve to a path inside destDir.-// - Absolute paths and paths containing ".." are rejected.-// - Symlinks (and any non-regular, non-dir mode) are rejected.-// - MaxFiles / MaxDepth / MaxTotalUnzippedBytes are enforced; the running-// total is checked while copying so a lying uncompressed-size can't be used-// to blow past the cap.-func safeUnzip(archive []byte, destDir string, caps unzipCaps) error {- zr, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive)))- if err != nil {- return fmt.Errorf("opening zip: %w", err)- }- if len(zr.File) > caps.MaxFiles {- return fmt.Errorf("archive has %d entries, exceeds cap %d", len(zr.File), caps.MaxFiles)- }-- // Resolve destDir to an absolute, clean base for containment checks.- absDest, err := filepath.Abs(destDir)- if err != nil {- return fmt.Errorf("resolving dest: %w", err)- }- if err := os.MkdirAll(absDest, 0o755); err != nil {- return fmt.Errorf("creating dest: %w", err)- }-- var total int64- for _, f := range zr.File {- if err := validateEntryName(f.Name, caps.MaxDepth); err != nil {- return err- }- // Reject symlinks and any special modes; only dirs and regular files.- mode := f.Mode()- if mode&os.ModeSymlink != 0 {- return fmt.Errorf("entry %q is a symlink (rejected)", f.Name)- }- if !mode.IsDir() && !mode.IsRegular() {- return fmt.Errorf("entry %q has unsupported mode %v (rejected)", f.Name, mode)- }-- target := filepath.Join(absDest, filepath.FromSlash(f.Name))- // Containment: target must be within absDest.- if !withinBase(absDest, target) {- return fmt.Errorf("entry %q escapes destination (zip-slip)", f.Name)- }-- if f.FileInfo().IsDir() {- if err := os.MkdirAll(target, 0o755); err != nil {- return fmt.Errorf("creating dir %q: %w", f.Name, err)- }- continue- }-- if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {- return fmt.Errorf("creating parent of %q: %w", f.Name, err)- }- written, err := writeCappedFile(f, target, caps.MaxTotalUnzippedBytes-total)- if err != nil {- return err- }- total += written- if total > caps.MaxTotalUnzippedBytes {- return fmt.Errorf("archive exceeds unzipped size cap %d bytes", caps.MaxTotalUnzippedBytes)- }- }- return nil-}--// validateEntryName rejects absolute paths, "..", and over-deep nesting.-func validateEntryName(name string, maxDepth int) error {- if name == "" {- return fmt.Errorf("empty entry name")- }- // Reject Windows-style and POSIX absolute paths.- if filepath.IsAbs(name) || strings.HasPrefix(name, "/") || strings.HasPrefix(name, `\`) {- return fmt.Errorf("entry %q is an absolute path (rejected)", name)- }- slashed := strings.ReplaceAll(name, `\`, "/")- for _, seg := range strings.Split(slashed, "/") {- if seg == ".." {- return fmt.Errorf("entry %q contains '..' (rejected)", name)- }- }- depth := 0- for _, seg := range strings.Split(strings.Trim(slashed, "/"), "/") {- if seg != "" && seg != "." {- depth++- }- }- if depth > maxDepth {- return fmt.Errorf("entry %q nesting depth %d exceeds cap %d", name, depth, maxDepth)- }- return nil-}--// withinBase reports whether target is inside base (after cleaning).-func withinBase(base, target string) bool {- rel, err := filepath.Rel(base, target)- if err != nil {- return false- }- return rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))-}--// writeCappedFile copies one zip entry to disk, refusing to write more than-// remaining bytes (so a mismatched declared size can't overrun the cap).-func writeCappedFile(f *zip.File, target string, remaining int64) (int64, error) {- if remaining < 0 {- return 0, fmt.Errorf("unzipped size cap exceeded before %q", f.Name)- }- rc, err := f.Open()- if err != nil {- return 0, fmt.Errorf("opening entry %q: %w", f.Name, err)- }- defer rc.Close()-- // Preserve the archive entry's permission bits so executable skill scripts- // (e.g. under scripts/) stay executable after extraction. Chmod after create- // so the mode sticks regardless of the process umask.- perm := f.Mode().Perm()- out, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)- if err != nil {- return 0, fmt.Errorf("creating file %q: %w", f.Name, err)- }- defer out.Close()- if err := out.Chmod(perm); err != nil {- return 0, fmt.Errorf("setting mode on %q: %w", f.Name, err)- }-- // Limit the copy to remaining+1 so we can detect overrun deterministically.- n, err := io.Copy(out, io.LimitReader(rc, remaining+1))- if err != nil {- return n, fmt.Errorf("writing %q: %w", f.Name, err)- }- if n > remaining {- return n, fmt.Errorf("entry %q exceeds remaining unzipped size budget", f.Name)- }- return n, nil-}diff --git a/internal/skills/local/local.go b/internal/skills/local/local.godeleted file mode 100644index 1a7cd1a..0000000--- a/internal/skills/local/local.go+++ /dev/null@@ -1,102 +0,0 @@-// 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 local discovers agent skills that already exist on disk. It is the-// local-directory counterpart to internal/skills/geminienterprise: instead of-// fetching from the Gemini Enterprise Skill Registry, it treats a configured-// directory as a ready-made skills folder and reports what it finds.-//-// A local skills path is a parent directory containing one subfolder per skill,-// each with a SKILL.md (the same layout as examples/skills and a registry's-// target_dir). Nothing is written; the directory is used as-is.-//-// It is harness-agnostic and produces []skills.Group, so the same consumers that-// handle registry skills handle local ones.-package local--import (- "log"- "os"- "path/filepath"-- "github.com/google/ax/internal/config"- "github.com/google/ax/internal/skills"-)--// skillManifest is the file that marks a subdirectory as a skill.-const skillManifest = "SKILL.md"--// Discover enumerates every enabled local skills path in sc and reports the-// skills found on disk. Each enabled path is a parent directory whose immediate-// subfolders containing a SKILL.md are treated as skills (subfolder name = skill-// id).-//-// It is fail-safe, mirroring geminienterprise.Materialize: disabled entries are-// skipped, and any path that is missing, unreadable, not a directory, or-// contains no skills is logged and skipped so a local-skills problem never-// blocks harness creation. Paths are resolved to absolute form so the reported-// directories are stable regardless of the process working directory.-func Discover(sc config.SkillsConfig) []skills.Group {- var groups []skills.Group- for i := range sc.Local {- lc := sc.Local[i]- if !lc.Enabled {- continue- }- group, ok := discoverOne(lc.Path, i)- if !ok {- continue- }- groups = append(groups, group)- }- return groups-}--// discoverOne scans a single local skills path. idx is the entry's index within-// the local list, for log context. It returns ok=false (and logs the reason)-// when the path yields no usable skills.-func discoverOne(path string, idx int) (skills.Group, bool) {- abs, err := filepath.Abs(path)- if err != nil {- log.Printf("skills: local[%d] %q: resolving absolute path: %v; skipping", idx, path, err)- return skills.Group{}, false- }- entries, err := os.ReadDir(abs)- if err != nil {- log.Printf("skills: local[%d] %q: reading directory: %v; skipping", idx, abs, err)- return skills.Group{}, false- }-- group := skills.Group{Dir: abs}- for _, e := range entries {- if !e.IsDir() {- continue- }- skillDir := filepath.Join(abs, e.Name())- manifest := filepath.Join(skillDir, skillManifest)- if info, err := os.Stat(manifest); err != nil || info.IsDir() {- // No SKILL.md (or it is a directory): not a skill. Silently skip so- // non-skill entries (e.g. a README) don't produce log noise.- continue- }- group.Skills = append(group.Skills, skills.Skill{ID: e.Name(), Dir: skillDir})- }-- if len(group.Skills) == 0 {- log.Printf("skills: local[%d] %q: no skills found (no <skill-id>/%s subfolders); skipping", idx, abs, skillManifest)- return skills.Group{}, false- }- log.Printf("skills: local[%d] discovered %d skill(s) in %s", idx, len(group.Skills), abs)- return group, true-}diff --git a/internal/skills/local/local_test.go b/internal/skills/local/local_test.godeleted file mode 100644index 38f90bf..0000000--- a/internal/skills/local/local_test.go+++ /dev/null@@ -1,161 +0,0 @@-// 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 local--import (- "os"- "path/filepath"- "sort"- "testing"-- "github.com/google/ax/internal/config"-)--// writeSkillDir creates <parent>/<id>/SKILL.md so the id is discovered as a-// skill.-func writeSkillDir(t *testing.T, parent, id string) {- t.Helper()- dir := filepath.Join(parent, id)- if err := os.MkdirAll(dir, 0o755); err != nil {- t.Fatal(err)- }- if err := os.WriteFile(filepath.Join(dir, skillManifest), []byte("# "+id+"\n"), 0o644); err != nil {- t.Fatal(err)- }-}--func TestDiscover_FindsSkillSubdirs(t *testing.T) {- root := t.TempDir()- writeSkillDir(t, root, "emoji")- writeSkillDir(t, root, "lowercase")- // A non-skill subdir (no SKILL.md) and a stray file must be ignored.- if err := os.MkdirAll(filepath.Join(root, "not-a-skill"), 0o755); err != nil {- t.Fatal(err)- }- if err := os.WriteFile(filepath.Join(root, "README.md"), []byte("hi"), 0o644); err != nil {- t.Fatal(err)- }-- groups := Discover(config.SkillsConfig{Local: []config.LocalSkillsConfig{- {Enabled: true, Path: root},- }})- if len(groups) == 0 {- t.Fatal("expected skills, got none")- }- if len(groups) != 1 {- t.Fatalf("groups = %d, want 1", len(groups))- }- g := groups[0]- // Dir is reported as an absolute path.- if !filepath.IsAbs(g.Dir) {- t.Errorf("group Dir = %q, want absolute", g.Dir)- }- var got []string- for _, s := range g.Skills {- got = append(got, s.ID)- wantDir := filepath.Join(g.Dir, s.ID)- if s.Dir != wantDir {- t.Errorf("skill %q Dir = %q, want %q", s.ID, s.Dir, wantDir)- }- }- sort.Strings(got)- if len(got) != 2 || got[0] != "emoji" || got[1] != "lowercase" {- t.Errorf("skill ids = %v, want [emoji lowercase]", got)- }-}--func TestDiscover_DisabledIsSkipped(t *testing.T) {- root := t.TempDir()- writeSkillDir(t, root, "emoji")- groups := Discover(config.SkillsConfig{Local: []config.LocalSkillsConfig{- {Enabled: false, Path: root},- }})- if len(groups) != 0 {- t.Errorf("disabled entry produced skills: %+v", groups)- }-}--func TestDiscover_MissingPathDegrades(t *testing.T) {- // A non-existent path must not panic or error; it degrades to no skills.- groups := Discover(config.SkillsConfig{Local: []config.LocalSkillsConfig{- {Enabled: true, Path: filepath.Join(t.TempDir(), "does-not-exist")},- }})- if len(groups) != 0 {- t.Errorf("missing path produced skills: %+v", groups)- }-}--func TestDiscover_EmptyDirDegrades(t *testing.T) {- // A directory with no <skill-id>/SKILL.md subfolders yields no skills.- groups := Discover(config.SkillsConfig{Local: []config.LocalSkillsConfig{- {Enabled: true, Path: t.TempDir()},- }})- if len(groups) != 0 {- t.Errorf("empty dir produced skills: %+v", groups)- }-}--func TestDiscover_MultiplePaths(t *testing.T) {- a := t.TempDir()- b := t.TempDir()- writeSkillDir(t, a, "s1")- writeSkillDir(t, b, "s2")- groups := Discover(config.SkillsConfig{Local: []config.LocalSkillsConfig{- {Enabled: true, Path: a},- {Enabled: true, Path: b},- }})- if len(groups) != 2 {- t.Fatalf("groups = %d, want 2", len(groups))- }- var got []string- for _, g := range groups {- for _, s := range g.Skills {- got = append(got, s.ID)- }- }- sort.Strings(got)- if len(got) != 2 || got[0] != "s1" || got[1] != "s2" {- t.Errorf("skill ids = %v, want [s1 s2]", got)- }-}--// TestDiscover_ExamplesSkillsFixture points at the repo's real examples/skills-// directory to guard the expected on-disk layout (parent dir of <skill>/SKILL.md-// subfolders, with a README.md that must be ignored).-func TestDiscover_ExamplesSkillsFixture(t *testing.T) {- // This test file lives at internal/skills/local/; examples/skills is at the- // repo root.- examples := filepath.Join("..", "..", "..", "examples", "skills")- if _, err := os.Stat(examples); err != nil {- t.Skipf("examples/skills not found (%v); skipping", err)- }- groups := Discover(config.SkillsConfig{Local: []config.LocalSkillsConfig{- {Enabled: true, Path: examples},- }})- if len(groups) == 0 {- t.Fatal("expected skills from examples/skills, got none")- }- var got []string- for _, g := range groups {- for _, s := range g.Skills {- got = append(got, s.ID)- }- }- sort.Strings(got)- // emoji and lowercase ship in examples/skills; README.md must be ignored.- if len(got) != 2 || got[0] != "emoji" || got[1] != "lowercase" {- t.Errorf("examples/skills ids = %v, want [emoji lowercase]", got)- }-}diff --git a/internal/skills/skills.go b/internal/skills/skills.godeleted file mode 100644index 1646a34..0000000--- a/internal/skills/skills.go+++ /dev/null@@ -1,37 +0,0 @@-// 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 skills defines the mode-agnostic result shape that describes which-// agent skills are available on disk and where. Both skill sources -- the-// Gemini Enterprise Skill Registry (internal/skills/geminienterprise) and the-// local directory mode (internal/skills/local) -- produce slices of Group so a-// single consumer (e.g. a harness system-instruction builder) can serve both-// without depending on either source package.-package skills--// Group associates a set of skills with the directory that contains them. Each-// skill lives at <Dir>/<skill-id>/ (with a SKILL.md inside).-type Group struct {- Dir string- Skills []Skill-}--// Skill identifies one on-disk skill.-type Skill struct {- // ID is the skill identifier, which is also its directory name under the- // group's Dir.- ID string- // Dir is the absolute path of the skill's own folder (<group Dir>/<ID>/).- Dir string-}diff --git a/internal/store/memory/store.go b/internal/store/memory/store.gonew file mode 100644index 0000000..8a0b13d--- /dev/null+++ b/internal/store/memory/store.go@@ -0,0 +1,423 @@+// 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 memory++import (+ "context"+ "errors"+ "fmt"+ "io"+ "sync"+ "time"++ "github.com/google/ax/internal/store"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "google.golang.org/protobuf/proto"+)++type closerFunc func() error++func (f closerFunc) Close() error { return f() }++// clone returns a deep copy of a protobuf message so stored resources are never+// shared with callers. Copying the struct by value is unsafe: generated messages+// embed internal state, including a mutex.+func clone[T proto.Message](m T) T {+ return proto.Clone(m).(T)+}++// MemoryStore is an in-memory implementation of store.Store for testing and single-node setups.+type MemoryStore struct {+ mu sync.RWMutex+ tasks map[string]*v1alpha1.Task+ gateways map[string]*v1alpha1.Gateway+ models map[string]*v1alpha1.Model+ workspaces map[string]*v1alpha1.Workspace+ events chan store.TaskEvent+ watchers map[string][]chan *v1alpha1.Task+}++// NewStore creates a new in-memory Store.+func NewStore() *MemoryStore {+ return &MemoryStore{+ tasks: make(map[string]*v1alpha1.Task),+ gateways: make(map[string]*v1alpha1.Gateway),+ models: make(map[string]*v1alpha1.Model),+ workspaces: make(map[string]*v1alpha1.Workspace),+ events: make(chan store.TaskEvent, 1000),+ watchers: make(map[string][]chan *v1alpha1.Task),+ }+}++func taskKey(atespace, name string) string {+ if atespace == "" {+ atespace = "default"+ }+ return fmt.Sprintf("%s:%s", atespace, name)+}++func (s *MemoryStore) SaveTask(ctx context.Context, task *v1alpha1.Task) error {+ if task.Metadata == nil {+ task.Metadata = &v1alpha1.ObjectMeta{}+ }+ if task.Metadata.Name == "" {+ return errors.New("task name is required")+ }+ if task.Metadata.Atespace == "" {+ task.Metadata.Atespace = "default"+ }+ if task.Status == nil {+ task.Status = &v1alpha1.TaskStatus{}+ }+ if task.Status.Phase == "" {+ task.Status.Phase = "Pending"+ }++ key := taskKey(task.Metadata.Atespace, task.Metadata.Name)++ s.mu.Lock()+ cp := clone(task)+ s.tasks[key] = cp++ event := store.TaskEvent{+ ID: fmt.Sprintf("%d", time.Now().UnixNano()),+ Atespace: task.Metadata.Atespace,+ Name: task.Metadata.Name,+ Action: "reconcile",+ }++ // Notify watchers+ if chs, ok := s.watchers[key]; ok {+ for _, ch := range chs {+ select {+ case ch <- cp:+ default:+ }+ }+ }+ s.mu.Unlock()++ select {+ case s.events <- event:+ default:+ }++ return nil+}++func (s *MemoryStore) GetTask(ctx context.Context, atespace, name string) (*v1alpha1.Task, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()++ key := taskKey(atespace, name)+ t, ok := s.tasks[key]+ if !ok {+ return nil, store.ErrNotFound+ }+ cp := clone(t)+ return cp, nil+}++func (s *MemoryStore) ListTasks(ctx context.Context, atespace string, limit, offset int64) ([]*v1alpha1.Task, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()++ var result []*v1alpha1.Task+ for _, t := range s.tasks {+ if atespace == "" || atespace == "*" || t.Metadata.Atespace == atespace {+ cp := clone(t)+ result = append(result, cp)+ }+ }++ if offset >= int64(len(result)) {+ return []*v1alpha1.Task{}, nil+ }+ end := offset + limit+ if limit <= 0 || end > int64(len(result)) {+ end = int64(len(result))+ }+ return result[offset:end], nil+}++func (s *MemoryStore) UpdateTaskStatus(ctx context.Context, atespace, name string, status *v1alpha1.TaskStatus) error {+ key := taskKey(atespace, name)++ s.mu.Lock()+ defer s.mu.Unlock()++ t, ok := s.tasks[key]+ if !ok {+ return store.ErrNotFound+ }+ t.Status = status+ cp := clone(t)++ if chs, ok := s.watchers[key]; ok {+ for _, ch := range chs {+ select {+ case ch <- cp:+ default:+ }+ }+ }+ return nil+}++func (s *MemoryStore) MarkTaskDeleting(ctx context.Context, atespace, name string) error {+ key := taskKey(atespace, name)++ s.mu.Lock()+ t, ok := s.tasks[key]+ if !ok {+ s.mu.Unlock()+ return store.ErrNotFound+ }+ if t.Status == nil {+ t.Status = &v1alpha1.TaskStatus{}+ }+ t.Status.Phase = v1alpha1.PhaseTerminating+ cp := clone(t)+ if chs, ok := s.watchers[key]; ok {+ for _, ch := range chs {+ select {+ case ch <- cp:+ default:+ }+ }+ }+ s.mu.Unlock()++ select {+ case s.events <- store.TaskEvent{+ ID: fmt.Sprintf("%d", time.Now().UnixNano()),+ Atespace: atespace,+ Name: name,+ Action: "delete",+ }:+ default:+ }+ return nil+}++func (s *MemoryStore) DeleteTask(ctx context.Context, atespace, name string) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ delete(s.tasks, taskKey(atespace, name))+ return nil+}++func (s *MemoryStore) SaveGateway(ctx context.Context, gw *v1alpha1.Gateway) error {+ if gw.Metadata.Name == "" {+ return errors.New("gateway name is required")+ }+ if gw.Metadata.Atespace == "" {+ gw.Metadata.Atespace = "default"+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ cp := clone(gw)+ s.gateways[taskKey(gw.Metadata.Atespace, gw.Metadata.Name)] = cp+ return nil+}++func (s *MemoryStore) GetGateway(ctx context.Context, atespace, name string) (*v1alpha1.Gateway, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()++ gw, ok := s.gateways[taskKey(atespace, name)]+ if !ok {+ return nil, store.ErrNotFound+ }+ cp := clone(gw)+ return cp, nil+}++func (s *MemoryStore) ListGateways(ctx context.Context, atespace string) ([]*v1alpha1.Gateway, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()++ var result []*v1alpha1.Gateway+ for _, g := range s.gateways {+ if atespace == "" || atespace == "*" || g.Metadata.Atespace == atespace {+ cp := clone(g)+ result = append(result, cp)+ }+ }+ return result, nil+}++func (s *MemoryStore) DeleteGateway(ctx context.Context, atespace, name string) error {+ s.mu.Lock()+ defer s.mu.Unlock()++ delete(s.gateways, taskKey(atespace, name))+ return nil+}++func (s *MemoryStore) SaveModel(ctx context.Context, model *v1alpha1.Model) error {+ if model.Metadata.Name == "" {+ return errors.New("model name is required")+ }+ if model.Metadata.Atespace == "" {+ model.Metadata.Atespace = "default"+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ cp := clone(model)+ s.models[taskKey(model.Metadata.Atespace, model.Metadata.Name)] = cp+ return nil+}++func (s *MemoryStore) GetModel(ctx context.Context, atespace, name string) (*v1alpha1.Model, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()++ m, ok := s.models[taskKey(atespace, name)]+ if !ok {+ return nil, store.ErrNotFound+ }+ cp := clone(m)+ return cp, nil+}++func (s *MemoryStore) ListModels(ctx context.Context, atespace string) ([]*v1alpha1.Model, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()++ var result []*v1alpha1.Model+ for _, m := range s.models {+ if atespace == "" || atespace == "*" || m.Metadata.Atespace == atespace {+ cp := clone(m)+ result = append(result, cp)+ }+ }+ return result, nil+}++func (s *MemoryStore) DeleteModel(ctx context.Context, atespace, name string) error {+ s.mu.Lock()+ defer s.mu.Unlock()++ delete(s.models, taskKey(atespace, name))+ return nil+}++func (s *MemoryStore) SaveWorkspace(ctx context.Context, ws *v1alpha1.Workspace) error {+ if ws.Metadata.Name == "" {+ return errors.New("workspace name is required")+ }+ if ws.Metadata.Atespace == "" {+ ws.Metadata.Atespace = "default"+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ cp := clone(ws)+ s.workspaces[taskKey(ws.Metadata.Atespace, ws.Metadata.Name)] = cp+ return nil+}++func (s *MemoryStore) GetWorkspace(ctx context.Context, atespace, name string) (*v1alpha1.Workspace, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()++ ws, ok := s.workspaces[taskKey(atespace, name)]+ if !ok {+ return nil, store.ErrNotFound+ }+ cp := clone(ws)+ return cp, nil+}++func (s *MemoryStore) ListWorkspaces(ctx context.Context, atespace string) ([]*v1alpha1.Workspace, error) {+ s.mu.RLock()+ defer s.mu.RUnlock()++ var result []*v1alpha1.Workspace+ for _, w := range s.workspaces {+ if atespace == "" || atespace == "*" || w.Metadata.Atespace == atespace {+ cp := clone(w)+ result = append(result, cp)+ }+ }+ return result, nil+}++func (s *MemoryStore) DeleteWorkspace(ctx context.Context, atespace, name string) error {+ s.mu.Lock()+ defer s.mu.Unlock()++ delete(s.workspaces, taskKey(atespace, name))+ return nil+}++// Subscribe returns a subscription over the store's single event channel. Every+// subscription shares that channel, so each event reaches exactly one subscriber,+// which matches the group semantics of the Redis implementation. Groups and+// consumers are accepted for interface parity but carry no meaning here.+func (s *MemoryStore) Subscribe(ctx context.Context, group, consumer string) (store.Subscription, error) {+ return &subscription{events: s.events}, nil+}++type subscription struct {+ events <-chan store.TaskEvent+}++func (sub *subscription) Next(ctx context.Context) (store.TaskEvent, error) {+ select {+ case ev := <-sub.events:+ return ev, nil+ case <-ctx.Done():+ return store.TaskEvent{}, ctx.Err()+ }+}++// Ack is a no-op: the channel hands each event out once, so there is nothing to retain.+func (sub *subscription) Ack(ctx context.Context, ev store.TaskEvent) error {+ return nil+}++func (sub *subscription) Close() error {+ return nil+}++func (s *MemoryStore) WatchTask(ctx context.Context, atespace, name string) (<-chan *v1alpha1.Task, io.Closer, error) {+ key := taskKey(atespace, name)+ ch := make(chan *v1alpha1.Task, 10)++ s.mu.Lock()+ s.watchers[key] = append(s.watchers[key], ch)+ s.mu.Unlock()++ closer := closerFunc(func() error {+ s.mu.Lock()+ defer s.mu.Unlock()+ chs := s.watchers[key]+ for i, c := range chs {+ if c == ch {+ s.watchers[key] = append(chs[:i], chs[i+1:]...)+ close(ch)+ break+ }+ }+ return nil+ })++ return ch, closer, nil+}++func (s *MemoryStore) Close() error {+ return nil+}diff --git a/internal/store/redis/store.go b/internal/store/redis/store.gonew file mode 100644index 0000000..0bbf7aa--- /dev/null+++ b/internal/store/redis/store.go@@ -0,0 +1,848 @@+// 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 redis++import (+ "context"+ "errors"+ "fmt"+ "io"+ "strings"+ "time"++ "github.com/google/ax/internal/store"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "github.com/redis/go-redis/v9"+ "google.golang.org/protobuf/encoding/protojson"+)++const (+ defaultStreamName = "ax:stream:tasks"+ defaultReadBatchSize = 10+ defaultReadBlock = 2 * time.Second+)++var (+ jsonMarshalOpts = protojson.MarshalOptions{UseProtoNames: false, EmitUnpopulated: false}+ jsonUnmarshalOpts = protojson.UnmarshalOptions{DiscardUnknown: true}+)++// Options contains configuration for the Redis store.+type Options struct {+ StreamName string+ KeyPrefix string+ TTL time.Duration // Optional TTL for task records++ // ReadBatchSize is how many events one XREADGROUP call may return.+ ReadBatchSize int64+ // ReadBlock is how long one XREADGROUP call waits for events before returning+ // empty. Shorter values make shutdown more responsive at the cost of more calls.+ ReadBlock time.Duration+}++// Store is a Redis-backed implementation of store.Store.+type Store struct {+ client *redis.Client+ opts Options+}++// NewStore creates a new Redis store.+func NewStore(client *redis.Client, opts Options) *Store {+ if opts.StreamName == "" {+ opts.StreamName = defaultStreamName+ }+ if opts.KeyPrefix == "" {+ opts.KeyPrefix = "ax"+ }+ if opts.ReadBatchSize <= 0 {+ opts.ReadBatchSize = defaultReadBatchSize+ }+ if opts.ReadBlock <= 0 {+ opts.ReadBlock = defaultReadBlock+ }+ return &Store{+ client: client,+ opts: opts,+ }+}++func (s *Store) taskKey(atespace, name string) string {+ return fmt.Sprintf("%s:task:%s:%s", s.opts.KeyPrefix, atespace, name)+}++func (s *Store) gwKey(atespace, name string) string {+ return fmt.Sprintf("%s:gw:%s:%s", s.opts.KeyPrefix, atespace, name)+}++func (s *Store) gwIndexKey() string {+ return fmt.Sprintf("%s:gateways:index", s.opts.KeyPrefix)+}++func (s *Store) gwAtespaceIndexKey(atespace string) string {+ return fmt.Sprintf("%s:gateways:atespace:%s", s.opts.KeyPrefix, atespace)+}++func (s *Store) modelKey(atespace, name string) string {+ return fmt.Sprintf("%s:model:%s:%s", s.opts.KeyPrefix, atespace, name)+}++func (s *Store) modelIndexKey() string {+ return fmt.Sprintf("%s:models:index", s.opts.KeyPrefix)+}++func (s *Store) modelAtespaceIndexKey(atespace string) string {+ return fmt.Sprintf("%s:models:atespace:%s", s.opts.KeyPrefix, atespace)+}++func (s *Store) wsKey(atespace, name string) string {+ return fmt.Sprintf("%s:workspace:%s:%s", s.opts.KeyPrefix, atespace, name)+}++func (s *Store) wsIndexKey() string {+ return fmt.Sprintf("%s:workspaces:index", s.opts.KeyPrefix)+}++func (s *Store) wsAtespaceIndexKey(atespace string) string {+ return fmt.Sprintf("%s:workspaces:atespace:%s", s.opts.KeyPrefix, atespace)+}++func (s *Store) taskIndexKey() string {+ return fmt.Sprintf("%s:tasks:index", s.opts.KeyPrefix)+}++func (s *Store) taskAtespaceIndexKey(atespace string) string {+ return fmt.Sprintf("%s:tasks:atespace:%s", s.opts.KeyPrefix, atespace)+}++func (s *Store) taskPubSubChannel(atespace, name string) string {+ return fmt.Sprintf("%s:pubsub:task:%s:%s", s.opts.KeyPrefix, atespace, name)+}++// SaveTask stores or updates a task and publishes a reconcile event to the stream.+func (s *Store) SaveTask(ctx context.Context, task *v1alpha1.Task) error {+ if task.Metadata == nil {+ task.Metadata = &v1alpha1.ObjectMeta{}+ }+ if task.Metadata.Name == "" {+ return errors.New("task name is required")+ }+ if task.Metadata.Atespace == "" {+ task.Metadata.Atespace = "default"+ }+ if task.ApiVersion == "" {+ task.ApiVersion = v1alpha1.APIVersion+ }+ if task.Kind == "" {+ task.Kind = v1alpha1.KindTask+ }+ if task.Status == nil {+ task.Status = &v1alpha1.TaskStatus{}+ }+ if task.Status.Phase == "" {+ task.Status.Phase = "Pending"+ }++ data, err := protojson.Marshal(task)+ if err != nil {+ return fmt.Errorf("marshaling task: %w", err)+ }++ atespace := task.Metadata.Atespace+ name := task.Metadata.Name+ score := float64(time.Now().UnixNano())+ member := fmt.Sprintf("%s:%s", atespace, name)++ pipe := s.client.TxPipeline()+ pipe.Set(ctx, s.taskKey(atespace, name), data, s.opts.TTL)+ pipe.ZAdd(ctx, s.taskIndexKey(), redis.Z{Score: score, Member: member})+ pipe.ZAdd(ctx, s.taskAtespaceIndexKey(atespace), redis.Z{Score: score, Member: name})+ pipe.XAdd(ctx, &redis.XAddArgs{+ Stream: s.opts.StreamName,+ Values: map[string]interface{}{+ "action": "reconcile",+ "atespace": atespace,+ "name": name,+ },+ })+ pipe.Publish(ctx, s.taskPubSubChannel(atespace, name), data)++ _, err = pipe.Exec(ctx)+ if err != nil {+ return fmt.Errorf("saving task to redis: %w", err)+ }+ return nil+}++// GetTask retrieves a task by atespace and name.+func (s *Store) GetTask(ctx context.Context, atespace, name string) (*v1alpha1.Task, error) {+ if atespace == "" {+ atespace = "default"+ }+ val, err := s.client.Get(ctx, s.taskKey(atespace, name)).Result()+ if err != nil {+ if errors.Is(err, redis.Nil) {+ return nil, store.ErrNotFound+ }+ return nil, fmt.Errorf("getting task from redis: %w", err)+ }++ var task v1alpha1.Task+ if err := jsonUnmarshalOpts.Unmarshal([]byte(val), &task); err != nil {+ return nil, fmt.Errorf("unmarshaling task: %w", err)+ }+ return &task, nil+}++// ListTasks lists tasks ordered by newest first.+func (s *Store) ListTasks(ctx context.Context, atespace string, limit, offset int64) ([]*v1alpha1.Task, error) {+ if limit <= 0 {+ limit = 50+ }+ start := offset+ stop := offset + limit - 1++ var members []string+ var err error++ if atespace == "" || atespace == "*" {+ members, err = s.client.ZRevRange(ctx, s.taskIndexKey(), start, stop).Result()+ } else {+ names, nErr := s.client.ZRevRange(ctx, s.taskAtespaceIndexKey(atespace), start, stop).Result()+ if nErr == nil {+ for _, n := range names {+ members = append(members, fmt.Sprintf("%s:%s", atespace, n))+ }+ }+ err = nErr+ }++ if err != nil {+ return nil, fmt.Errorf("listing task index: %w", err)+ }+ if len(members) == 0 {+ return []*v1alpha1.Task{}, nil+ }++ keys := make([]string, len(members))+ for i, m := range members {+ parts := strings.SplitN(m, ":", 2)+ if len(parts) == 2 {+ keys[i] = s.taskKey(parts[0], parts[1])+ } else {+ keys[i] = s.taskKey("default", m)+ }+ }++ vals, err := s.client.MGet(ctx, keys...).Result()+ if err != nil {+ return nil, fmt.Errorf("batch fetching tasks: %w", err)+ }++ tasks := make([]*v1alpha1.Task, 0, len(vals))+ for _, v := range vals {+ if v == nil {+ continue+ }+ str, ok := v.(string)+ if !ok {+ continue+ }+ var t v1alpha1.Task+ if err := jsonUnmarshalOpts.Unmarshal([]byte(str), &t); err == nil {+ tasks = append(tasks, &t)+ }+ }+ return tasks, nil+}++// UpdateTaskStatus updates only the status portion of a task.+func (s *Store) UpdateTaskStatus(ctx context.Context, atespace, name string, status *v1alpha1.TaskStatus) error {+ task, err := s.GetTask(ctx, atespace, name)+ if err != nil {+ return err+ }++ task.Status = status+ data, err := jsonMarshalOpts.Marshal(task)+ if err != nil {+ return fmt.Errorf("marshaling task status: %w", err)+ }++ pipe := s.client.TxPipeline()+ pipe.Set(ctx, s.taskKey(atespace, name), data, s.opts.TTL)+ pipe.Publish(ctx, s.taskPubSubChannel(atespace, name), data)+ _, err = pipe.Exec(ctx)+ if err != nil {+ return fmt.Errorf("updating task status in redis: %w", err)+ }+ return nil+}++// MarkTaskDeleting flips the task to the Terminating phase, notifies watchers, and+// publishes a delete event for the controller. The record stays until DeleteTask.+func (s *Store) MarkTaskDeleting(ctx context.Context, atespace, name string) error {+ if atespace == "" {+ atespace = "default"+ }+ task, err := s.GetTask(ctx, atespace, name)+ if err != nil {+ return err+ }+ if task.Status == nil {+ task.Status = &v1alpha1.TaskStatus{}+ }+ task.Status.Phase = v1alpha1.PhaseTerminating+ data, err := protojson.Marshal(task)+ if err != nil {+ return fmt.Errorf("marshaling task: %w", err)+ }++ pipe := s.client.TxPipeline()+ pipe.Set(ctx, s.taskKey(atespace, name), data, s.opts.TTL)+ pipe.Publish(ctx, s.taskPubSubChannel(atespace, name), data)+ pipe.XAdd(ctx, &redis.XAddArgs{+ Stream: s.opts.StreamName,+ Values: map[string]interface{}{+ "action": "delete",+ "atespace": atespace,+ "name": name,+ },+ })+ if _, err := pipe.Exec(ctx); err != nil {+ return fmt.Errorf("marking task deleting in redis: %w", err)+ }+ return nil+}++// DeleteTask removes the task record and its index entries. No event is published.+func (s *Store) DeleteTask(ctx context.Context, atespace, name string) error {+ if atespace == "" {+ atespace = "default"+ }+ member := fmt.Sprintf("%s:%s", atespace, name)++ pipe := s.client.TxPipeline()+ pipe.Del(ctx, s.taskKey(atespace, name))+ pipe.ZRem(ctx, s.taskIndexKey(), member)+ pipe.ZRem(ctx, s.taskAtespaceIndexKey(atespace), name)+ if _, err := pipe.Exec(ctx); err != nil {+ return fmt.Errorf("deleting task from redis: %w", err)+ }+ return nil+}++// SaveGateway stores a gateway.+func (s *Store) SaveGateway(ctx context.Context, gw *v1alpha1.Gateway) error {+ if gw.Metadata == nil {+ gw.Metadata = &v1alpha1.ObjectMeta{}+ }+ if gw.Metadata.Name == "" {+ return errors.New("gateway name is required")+ }+ if gw.Metadata.Atespace == "" {+ gw.Metadata.Atespace = "default"+ }+ if gw.ApiVersion == "" {+ gw.ApiVersion = v1alpha1.APIVersion+ }+ if gw.Kind == "" {+ gw.Kind = v1alpha1.KindGateway+ }++ data, err := protojson.Marshal(gw)+ if err != nil {+ return fmt.Errorf("marshaling gateway: %w", err)+ }++ atespace := gw.Metadata.Atespace+ name := gw.Metadata.Name+ score := float64(time.Now().UnixNano())+ member := fmt.Sprintf("%s:%s", atespace, name)++ pipe := s.client.TxPipeline()+ pipe.Set(ctx, s.gwKey(atespace, name), data, 0)+ pipe.ZAdd(ctx, s.gwIndexKey(), redis.Z{Score: score, Member: member})+ pipe.ZAdd(ctx, s.gwAtespaceIndexKey(atespace), redis.Z{Score: score, Member: name})+ _, err = pipe.Exec(ctx)+ return err+}++// DeleteGateway removes a gateway.+func (s *Store) DeleteGateway(ctx context.Context, atespace, name string) error {+ if atespace == "" {+ atespace = "default"+ }+ member := fmt.Sprintf("%s:%s", atespace, name)++ pipe := s.client.TxPipeline()+ pipe.Del(ctx, s.gwKey(atespace, name))+ pipe.ZRem(ctx, s.gwIndexKey(), member)+ pipe.ZRem(ctx, s.gwAtespaceIndexKey(atespace), name)+ _, err := pipe.Exec(ctx)+ return err+}++// ListGateways lists gateways for an atespace or across all atespaces.+func (s *Store) ListGateways(ctx context.Context, atespace string) ([]*v1alpha1.Gateway, error) {+ var members []string+ var err error++ if atespace == "" || atespace == "*" {+ members, err = s.client.ZRevRange(ctx, s.gwIndexKey(), 0, -1).Result()+ } else {+ names, nErr := s.client.ZRevRange(ctx, s.gwAtespaceIndexKey(atespace), 0, -1).Result()+ if nErr == nil {+ for _, n := range names {+ members = append(members, fmt.Sprintf("%s:%s", atespace, n))+ }+ }+ err = nErr+ }++ if err != nil {+ return nil, fmt.Errorf("listing gateway index: %w", err)+ }+ if len(members) == 0 {+ return []*v1alpha1.Gateway{}, nil+ }++ keys := make([]string, len(members))+ for i, m := range members {+ parts := strings.SplitN(m, ":", 2)+ if len(parts) == 2 {+ keys[i] = s.gwKey(parts[0], parts[1])+ } else {+ keys[i] = s.gwKey("default", m)+ }+ }++ vals, err := s.client.MGet(ctx, keys...).Result()+ if err != nil {+ return nil, fmt.Errorf("batch fetching gateways: %w", err)+ }++ gateways := make([]*v1alpha1.Gateway, 0, len(vals))+ for _, v := range vals {+ if v == nil {+ continue+ }+ str, ok := v.(string)+ if !ok {+ continue+ }+ var gw v1alpha1.Gateway+ if err := jsonUnmarshalOpts.Unmarshal([]byte(str), &gw); err == nil {+ gateways = append(gateways, &gw)+ }+ }+ return gateways, nil+}++// GetGateway retrieves a gateway by atespace and name.+func (s *Store) GetGateway(ctx context.Context, atespace, name string) (*v1alpha1.Gateway, error) {+ if atespace == "" {+ atespace = "default"+ }+ val, err := s.client.Get(ctx, s.gwKey(atespace, name)).Result()+ if err != nil {+ if errors.Is(err, redis.Nil) {+ return nil, store.ErrNotFound+ }+ return nil, fmt.Errorf("getting gateway from redis: %w", err)+ }++ var gw v1alpha1.Gateway+ if err := jsonUnmarshalOpts.Unmarshal([]byte(val), &gw); err != nil {+ return nil, fmt.Errorf("unmarshaling gateway: %w", err)+ }+ return &gw, nil+}++// SaveModel stores a model.+func (s *Store) SaveModel(ctx context.Context, model *v1alpha1.Model) error {+ if model.Metadata == nil {+ model.Metadata = &v1alpha1.ObjectMeta{}+ }+ if model.Metadata.Name == "" {+ return errors.New("model name is required")+ }+ if model.Metadata.Atespace == "" {+ model.Metadata.Atespace = "default"+ }+ if model.ApiVersion == "" {+ model.ApiVersion = v1alpha1.APIVersion+ }+ if model.Kind == "" {+ model.Kind = v1alpha1.KindModel+ }++ data, err := protojson.Marshal(model)+ if err != nil {+ return fmt.Errorf("marshaling model: %w", err)+ }++ atespace := model.Metadata.Atespace+ name := model.Metadata.Name+ score := float64(time.Now().UnixNano())+ member := fmt.Sprintf("%s:%s", atespace, name)++ pipe := s.client.TxPipeline()+ pipe.Set(ctx, s.modelKey(atespace, name), data, 0)+ pipe.ZAdd(ctx, s.modelIndexKey(), redis.Z{Score: score, Member: member})+ pipe.ZAdd(ctx, s.modelAtespaceIndexKey(atespace), redis.Z{Score: score, Member: name})+ _, err = pipe.Exec(ctx)+ return err+}++// DeleteModel removes a model.+func (s *Store) DeleteModel(ctx context.Context, atespace, name string) error {+ if atespace == "" {+ atespace = "default"+ }+ member := fmt.Sprintf("%s:%s", atespace, name)++ pipe := s.client.TxPipeline()+ pipe.Del(ctx, s.modelKey(atespace, name))+ pipe.ZRem(ctx, s.modelIndexKey(), member)+ pipe.ZRem(ctx, s.modelAtespaceIndexKey(atespace), name)+ _, err := pipe.Exec(ctx)+ return err+}++// ListModels lists models for an atespace or across all atespaces.+func (s *Store) ListModels(ctx context.Context, atespace string) ([]*v1alpha1.Model, error) {+ var members []string+ var err error++ if atespace == "" || atespace == "*" {+ members, err = s.client.ZRevRange(ctx, s.modelIndexKey(), 0, -1).Result()+ } else {+ names, nErr := s.client.ZRevRange(ctx, s.modelAtespaceIndexKey(atespace), 0, -1).Result()+ if nErr == nil {+ for _, n := range names {+ members = append(members, fmt.Sprintf("%s:%s", atespace, n))+ }+ }+ err = nErr+ }++ if err != nil {+ return nil, fmt.Errorf("listing model index: %w", err)+ }+ if len(members) == 0 {+ return []*v1alpha1.Model{}, nil+ }++ keys := make([]string, len(members))+ for i, m := range members {+ parts := strings.SplitN(m, ":", 2)+ if len(parts) == 2 {+ keys[i] = s.modelKey(parts[0], parts[1])+ } else {+ keys[i] = s.modelKey("default", m)+ }+ }++ vals, err := s.client.MGet(ctx, keys...).Result()+ if err != nil {+ return nil, fmt.Errorf("batch fetching models: %w", err)+ }++ models := make([]*v1alpha1.Model, 0, len(vals))+ for _, v := range vals {+ if v == nil {+ continue+ }+ str, ok := v.(string)+ if !ok {+ continue+ }+ var m v1alpha1.Model+ if err := jsonUnmarshalOpts.Unmarshal([]byte(str), &m); err == nil {+ models = append(models, &m)+ }+ }+ return models, nil+}++// GetModel retrieves a model by atespace and name.+func (s *Store) GetModel(ctx context.Context, atespace, name string) (*v1alpha1.Model, error) {+ if atespace == "" {+ atespace = "default"+ }+ val, err := s.client.Get(ctx, s.modelKey(atespace, name)).Result()+ if err != nil {+ if errors.Is(err, redis.Nil) {+ return nil, store.ErrNotFound+ }+ return nil, fmt.Errorf("getting model from redis: %w", err)+ }++ var m v1alpha1.Model+ if err := jsonUnmarshalOpts.Unmarshal([]byte(val), &m); err != nil {+ return nil, fmt.Errorf("unmarshaling model: %w", err)+ }+ return &m, nil+}++// SaveWorkspace stores a workspace.+func (s *Store) SaveWorkspace(ctx context.Context, ws *v1alpha1.Workspace) error {+ if ws.Metadata == nil {+ ws.Metadata = &v1alpha1.ObjectMeta{}+ }+ if ws.Metadata.Name == "" {+ return errors.New("workspace name is required")+ }+ if ws.Metadata.Atespace == "" {+ ws.Metadata.Atespace = "default"+ }+ if ws.ApiVersion == "" {+ ws.ApiVersion = v1alpha1.APIVersion+ }+ if ws.Kind == "" {+ ws.Kind = v1alpha1.KindWorkspace+ }++ data, err := protojson.Marshal(ws)+ if err != nil {+ return fmt.Errorf("marshaling workspace: %w", err)+ }++ atespace := ws.Metadata.Atespace+ name := ws.Metadata.Name+ score := float64(time.Now().UnixNano())+ member := fmt.Sprintf("%s:%s", atespace, name)++ pipe := s.client.TxPipeline()+ pipe.Set(ctx, s.wsKey(atespace, name), data, 0)+ pipe.ZAdd(ctx, s.wsIndexKey(), redis.Z{Score: score, Member: member})+ pipe.ZAdd(ctx, s.wsAtespaceIndexKey(atespace), redis.Z{Score: score, Member: name})+ _, err = pipe.Exec(ctx)+ return err+}++// DeleteWorkspace removes a workspace.+func (s *Store) DeleteWorkspace(ctx context.Context, atespace, name string) error {+ if atespace == "" {+ atespace = "default"+ }+ member := fmt.Sprintf("%s:%s", atespace, name)++ pipe := s.client.TxPipeline()+ pipe.Del(ctx, s.wsKey(atespace, name))+ pipe.ZRem(ctx, s.wsIndexKey(), member)+ pipe.ZRem(ctx, s.wsAtespaceIndexKey(atespace), name)+ _, err := pipe.Exec(ctx)+ return err+}++// ListWorkspaces lists workspaces for an atespace or across all atespaces.+func (s *Store) ListWorkspaces(ctx context.Context, atespace string) ([]*v1alpha1.Workspace, error) {+ var members []string+ var err error++ if atespace == "" || atespace == "*" {+ members, err = s.client.ZRevRange(ctx, s.wsIndexKey(), 0, -1).Result()+ } else {+ names, nErr := s.client.ZRevRange(ctx, s.wsAtespaceIndexKey(atespace), 0, -1).Result()+ if nErr == nil {+ for _, n := range names {+ members = append(members, fmt.Sprintf("%s:%s", atespace, n))+ }+ }+ err = nErr+ }++ if err != nil {+ return nil, fmt.Errorf("listing workspace index: %w", err)+ }+ if len(members) == 0 {+ return []*v1alpha1.Workspace{}, nil+ }++ keys := make([]string, len(members))+ for i, m := range members {+ parts := strings.SplitN(m, ":", 2)+ if len(parts) == 2 {+ keys[i] = s.wsKey(parts[0], parts[1])+ } else {+ keys[i] = s.wsKey("default", m)+ }+ }++ vals, err := s.client.MGet(ctx, keys...).Result()+ if err != nil {+ return nil, fmt.Errorf("batch fetching workspaces: %w", err)+ }++ workspaces := make([]*v1alpha1.Workspace, 0, len(vals))+ for _, v := range vals {+ if v == nil {+ continue+ }+ str, ok := v.(string)+ if !ok {+ continue+ }+ var w v1alpha1.Workspace+ if err := jsonUnmarshalOpts.Unmarshal([]byte(str), &w); err == nil {+ workspaces = append(workspaces, &w)+ }+ }+ return workspaces, nil+}++// GetWorkspace retrieves a workspace by atespace and name.+func (s *Store) GetWorkspace(ctx context.Context, atespace, name string) (*v1alpha1.Workspace, error) {+ if atespace == "" {+ atespace = "default"+ }+ val, err := s.client.Get(ctx, s.wsKey(atespace, name)).Result()+ if err != nil {+ if errors.Is(err, redis.Nil) {+ return nil, store.ErrNotFound+ }+ return nil, fmt.Errorf("getting workspace from redis: %w", err)+ }++ var w v1alpha1.Workspace+ if err := jsonUnmarshalOpts.Unmarshal([]byte(val), &w); err != nil {+ return nil, fmt.Errorf("unmarshaling workspace: %w", err)+ }+ return &w, nil+}++// Subscribe joins a Redis Streams consumer group, creating the group (and the+// stream) if needed. A new group starts at the tail of the stream, so it only+// sees events published after it was created; an existing group keeps its+// position and any pending entries.+func (s *Store) Subscribe(ctx context.Context, group, consumer string) (store.Subscription, error) {+ err := s.client.XGroupCreateMkStream(ctx, s.opts.StreamName, group, "$").Err()+ if err != nil && !strings.Contains(err.Error(), "BUSYGROUP") {+ return nil, fmt.Errorf("creating consumer group %q: %w", group, err)+ }+ return &subscription{store: s, group: group, consumer: consumer}, nil+}++// subscription reads from a consumer group in batches and hands events out one+// at a time. Delivery is at-least-once: an event stays in the group's pending+// list until Ack is called for it.+type subscription struct {+ store *Store+ group string+ consumer string+ pending []store.TaskEvent+}++func (sub *subscription) Next(ctx context.Context) (store.TaskEvent, error) {+ for len(sub.pending) == 0 {+ if err := ctx.Err(); err != nil {+ return store.TaskEvent{}, err+ }+ events, err := sub.read(ctx)+ if err != nil {+ return store.TaskEvent{}, err+ }+ sub.pending = events+ }+ ev := sub.pending[0]+ sub.pending = sub.pending[1:]+ return ev, nil+}++// read performs one blocking XREADGROUP call. It returns an empty slice, not an+// error, when the block time elapses without events.+func (sub *subscription) read(ctx context.Context) ([]store.TaskEvent, error) {+ streams, err := sub.store.client.XReadGroup(ctx, &redis.XReadGroupArgs{+ Group: sub.group,+ Consumer: sub.consumer,+ Streams: []string{sub.store.opts.StreamName, ">"},+ Count: sub.store.opts.ReadBatchSize,+ Block: sub.store.opts.ReadBlock,+ }).Result()+ if err != nil {+ if errors.Is(err, redis.Nil) {+ return nil, nil+ }+ return nil, fmt.Errorf("reading task events: %w", err)+ }++ var events []store.TaskEvent+ for _, stream := range streams {+ for _, msg := range stream.Messages {+ events = append(events, eventFromMessage(msg))+ }+ }+ return events, nil+}++func (sub *subscription) Ack(ctx context.Context, ev store.TaskEvent) error {+ return sub.store.client.XAck(ctx, sub.store.opts.StreamName, sub.group, ev.ID).Err()+}++// Close releases the subscription. The consumer is deliberately left registered+// so that any events it had claimed but not acknowledged remain claimable.+func (sub *subscription) Close() error {+ return nil+}++// eventFromMessage decodes a stream entry. "namespace" is accepted as a legacy+// alias for "atespace".+func eventFromMessage(msg redis.XMessage) store.TaskEvent {+ ev := store.TaskEvent{ID: msg.ID}+ if atespace, ok := msg.Values["atespace"].(string); ok {+ ev.Atespace = atespace+ } else if ns, ok := msg.Values["namespace"].(string); ok {+ ev.Atespace = ns+ }+ if name, ok := msg.Values["name"].(string); ok {+ ev.Name = name+ }+ if action, ok := msg.Values["action"].(string); ok {+ ev.Action = action+ }+ return ev+}++// WatchTask subscribes to status change notifications for a specific task.+func (s *Store) WatchTask(ctx context.Context, atespace, name string) (<-chan *v1alpha1.Task, io.Closer, error) {+ if atespace == "" {+ atespace = "default"+ }+ pubsub := s.client.Subscribe(ctx, s.taskPubSubChannel(atespace, name))+ _, err := pubsub.Receive(ctx)+ if err != nil {+ return nil, nil, fmt.Errorf("subscribing to task watch: %w", err)+ }++ ch := make(chan *v1alpha1.Task, 10)+ go func() {+ defer close(ch)+ msgCh := pubsub.Channel()+ for msg := range msgCh {+ var t v1alpha1.Task+ if err := jsonUnmarshalOpts.Unmarshal([]byte(msg.Payload), &t); err == nil {+ ch <- &t+ }+ }+ }()++ return ch, pubsub, nil+}++// Close closes the underlying Redis client connection.+func (s *Store) Close() error {+ return s.client.Close()+}diff --git a/internal/store/store.go b/internal/store/store.gonew file mode 100644index 0000000..1e84a0f--- /dev/null+++ b/internal/store/store.go@@ -0,0 +1,90 @@+// 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 store++import (+ "context"+ "errors"+ "io"++ "github.com/google/ax/pkg/apis/v1alpha1"+)++var (+ ErrNotFound = errors.New("resource not found")+)++// TaskEvent represents an event published to the task event stream.+type TaskEvent struct {+ ID string+ Atespace string+ Name string+ Action string // "reconcile", "delete"+}++// EventQueue delivers task events to groups of cooperating workers. Every event+// is delivered to exactly one member of a group, and stays pending until that+// member acknowledges it, so a crashed worker's events can be picked up again.+type EventQueue interface {+ // Subscribe joins group as consumer, creating the group if it does not exist.+ // All members of a group share one stream of events.+ Subscribe(ctx context.Context, group, consumer string) (Subscription, error)+}++// Subscription is one consumer's view of an EventQueue group.+type Subscription interface {+ // Next blocks until an event is available or ctx is done.+ Next(ctx context.Context) (TaskEvent, error)+ // Ack marks an event as processed so it is not delivered again.+ Ack(ctx context.Context, ev TaskEvent) error+ // Close releases the subscription. Unacknowledged events stay pending for the group.+ Close() error+}++// Store defines the storage and event streaming interface for AX resources.+type Store interface {+ EventQueue++ SaveTask(ctx context.Context, task *v1alpha1.Task) error+ GetTask(ctx context.Context, atespace, name string) (*v1alpha1.Task, error)+ ListTasks(ctx context.Context, atespace string, limit, offset int64) ([]*v1alpha1.Task, error)+ UpdateTaskStatus(ctx context.Context, atespace, name string, status *v1alpha1.TaskStatus) error+ // MarkTaskDeleting begins a two-phase delete: the task's phase becomes+ // "Terminating" and a delete event is published for the controller, which+ // removes the actor and then calls DeleteTask. Returns ErrNotFound if the+ // task does not exist.+ MarkTaskDeleting(ctx context.Context, atespace, name string) error+ // DeleteTask removes the task record. It publishes no event; callers are+ // expected to have cleaned up the task's actor first.+ DeleteTask(ctx context.Context, atespace, name string) error++ SaveGateway(ctx context.Context, gw *v1alpha1.Gateway) error+ GetGateway(ctx context.Context, atespace, name string) (*v1alpha1.Gateway, error)+ ListGateways(ctx context.Context, atespace string) ([]*v1alpha1.Gateway, error)+ DeleteGateway(ctx context.Context, atespace, name string) error++ SaveWorkspace(ctx context.Context, ws *v1alpha1.Workspace) error+ GetWorkspace(ctx context.Context, atespace, name string) (*v1alpha1.Workspace, error)+ ListWorkspaces(ctx context.Context, atespace string) ([]*v1alpha1.Workspace, error)+ DeleteWorkspace(ctx context.Context, atespace, name string) error++ SaveModel(ctx context.Context, model *v1alpha1.Model) error+ GetModel(ctx context.Context, atespace, name string) (*v1alpha1.Model, error)+ ListModels(ctx context.Context, atespace string) ([]*v1alpha1.Model, error)+ DeleteModel(ctx context.Context, atespace, name string) error++ WatchTask(ctx context.Context, atespace, name string) (<-chan *v1alpha1.Task, io.Closer, error)+ Close() error+}diff --git a/internal/substrate/client.go b/internal/substrate/client.gonew file mode 100644index 0000000..bacb078--- /dev/null+++ b/internal/substrate/client.go@@ -0,0 +1,535 @@+// 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 substrate++import (+ "context"+ "crypto/tls"+ "crypto/x509"+ "fmt"+ "log/slog"+ "os"+ "strings"+ "time"++ "github.com/agent-substrate/substrate/pkg/proto/ateapipb"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "google.golang.org/grpc"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/credentials"+ "google.golang.org/grpc/credentials/insecure"+ "google.golang.org/grpc/status"+ "google.golang.org/protobuf/types/known/emptypb"+)++// ClientOptions configures connection to the Substrate Control API server.+type ClientOptions struct {+ Target string+ Authority string+ TokenFile string+ CAFile string+ InsecureTLS bool+ Plaintext bool+}++type tokenAuth struct {+ tokenFile string+}++func (t tokenAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {+ if t.tokenFile == "" {+ return nil, nil+ }+ b, err := os.ReadFile(t.tokenFile)+ if err != nil {+ return nil, fmt.Errorf("reading token file %q: %w", t.tokenFile, err)+ }+ return map[string]string{+ "authorization": "Bearer " + strings.TrimSpace(string(b)),+ }, nil+}++func (t tokenAuth) RequireTransportSecurity() bool {+ return false+}++// Client wraps the Substrate Control API client.+type Client struct {+ conn *grpc.ClientConn+ control ateapipb.ControlClient+}++// NewClientWithOptions connects to Substrate with full TLS and auth configuration.+func NewClientWithOptions(opts ClientOptions, extraDialOpts ...grpc.DialOption) (*Client, error) {+ if opts.Target == "" {+ opts.Target = "api.ate-system.svc.cluster.local:443"+ }++ // Auto-detect token file if not specified+ if opts.TokenFile == "" {+ if envToken := os.Getenv("SUBSTRATE_TOKEN_FILE"); envToken != "" {+ opts.TokenFile = envToken+ } else if _, err := os.Stat("/var/run/secrets/ateapi/token"); err == nil {+ opts.TokenFile = "/var/run/secrets/ateapi/token"+ }+ }++ // Auto-detect CA file if not specified+ if opts.CAFile == "" {+ if envCA := os.Getenv("SUBSTRATE_CA_FILE"); envCA != "" {+ opts.CAFile = envCA+ } else if _, err := os.Stat("/run/servicedns-ca/trust-bundle.pem"); err == nil {+ opts.CAFile = "/run/servicedns-ca/trust-bundle.pem"+ } else if _, err := os.Stat("/run/servicedns-ca/ca.pem"); err == nil {+ opts.CAFile = "/run/servicedns-ca/ca.pem"+ }+ }++ dialOpts := append([]grpc.DialOption{}, extraDialOpts...)++ if opts.Plaintext {+ dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))+ } else {+ tlsConfig := &tls.Config{}+ if opts.InsecureTLS {+ tlsConfig.InsecureSkipVerify = true+ }+ if opts.Authority != "" {+ tlsConfig.ServerName = opts.Authority+ } else if strings.Contains(opts.Target, "api.ate-system.svc") {+ tlsConfig.ServerName = "api.ate-system.svc"+ }++ if opts.CAFile != "" {+ caCert, err := os.ReadFile(opts.CAFile)+ if err != nil {+ return nil, fmt.Errorf("reading CA file %q: %w", opts.CAFile, err)+ }+ pool := x509.NewCertPool()+ if !pool.AppendCertsFromPEM(caCert) {+ return nil, fmt.Errorf("failed to parse CA certificate from %q", opts.CAFile)+ }+ tlsConfig.RootCAs = pool+ }++ dialOpts = append(dialOpts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))+ }++ authority := opts.Authority+ if authority == "" && strings.Contains(opts.Target, "api.ate-system.svc") {+ authority = "api.ate-system.svc"+ }+ if authority != "" {+ dialOpts = append(dialOpts, grpc.WithAuthority(authority))+ }++ if opts.TokenFile != "" {+ dialOpts = append(dialOpts, grpc.WithPerRPCCredentials(tokenAuth{tokenFile: opts.TokenFile}))+ }++ conn, err := grpc.NewClient(opts.Target, dialOpts...)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Substrate control service at %s: %w", opts.Target, err)+ }+ return &Client{+ conn: conn,+ control: ateapipb.NewControlClient(conn),+ }, nil+}++// NewClient establishes a connection to the Substrate Control API server.+func NewClient(target string, opts ...grpc.DialOption) (*Client, error) {+ if len(opts) > 0 {+ if target == "" {+ target = "api.ate-system.svc.cluster.local:443"+ }+ conn, err := grpc.NewClient(target, opts...)+ if err != nil {+ return nil, fmt.Errorf("failed to connect to Substrate control service at %s: %w", target, err)+ }+ return &Client{+ conn: conn,+ control: ateapipb.NewControlClient(conn),+ }, nil+ }++ // Auto-configure options when no explicit dial options given+ return NewClientWithOptions(ClientOptions{Target: target})+}++// Close closes the gRPC connection.+func (c *Client) Close() error {+ if c.conn != nil {+ return c.conn.Close()+ }+ return nil+}++// EnsureAtespace creates the atespace if it does not already exist.+func (c *Client) EnsureAtespace(ctx context.Context, atespace string) error {+ req := &ateapipb.CreateAtespaceRequest{+ Atespace: &ateapipb.Atespace{+ Metadata: &ateapipb.ResourceMetadata{+ Name: atespace,+ },+ },+ }+ _, err := c.control.CreateAtespace(ctx, req)+ if err != nil && status.Code(err) != codes.AlreadyExists {+ return fmt.Errorf("creating atespace %q: %w", atespace, err)+ }+ return nil+}++// GetActorTemplate fetches an ActorTemplate by name.+func (c *Client) GetActorTemplate(ctx context.Context, atespace, templateName string) (*ateapipb.ActorTemplate, error) {+ req := &ateapipb.GetActorTemplateRequest{+ ActorTemplate: &ateapipb.ObjectRef{+ Atespace: atespace,+ Name: templateName,+ },+ }+ return c.control.GetActorTemplate(ctx, req)+}++const (+ DefaultGuestCommand = "/usr/local/bin/ax-task-runner"+ DefaultSnapshotsBucket = "gs://snapshot-substrate-test-ax-substrate/ate-env/"+)++// BuildActorTemplate constructs a Substrate ActorTemplate based on the standard ate-env specification.+func BuildActorTemplate(atespace, name, image string, envMap map[string]string, command []string, snapshotsBucket string) *ateapipb.ActorTemplate {+ if atespace == "" {+ atespace = "default"+ }+ if image == "" {+ image = v1alpha1.DefaultTaskImage+ }+ if len(command) == 0 {+ command = []string{DefaultGuestCommand}+ }+ if snapshotsBucket == "" {+ if envBucket := os.Getenv("AX_SNAPSHOTS_BUCKET"); envBucket != "" {+ snapshotsBucket = envBucket+ } else {+ snapshotsBucket = DefaultSnapshotsBucket+ }+ }++ var envList []*ateapipb.EnvVar+ for k, v := range envMap {+ envList = append(envList, &ateapipb.EnvVar{+ Name: k,+ Value: v,+ })+ }++ return &ateapipb.ActorTemplate{+ Metadata: &ateapipb.ResourceMetadata{+ Name: name,+ Atespace: atespace,+ },+ Containers: []*ateapipb.Container{{+ Name: "guest",+ Image: image,+ Command: command,+ Env: envList,+ Readyz: &ateapipb.ContainerReadyz{+ HttpGet: &ateapipb.HTTPGetAction{+ Path: "/readyz",+ Port: 80,+ },+ },+ VolumeMounts: []*ateapipb.VolumeMount{{+ Name: "workspace",+ MountPath: "/workspace",+ }},+ }},+ Volumes: []*ateapipb.Volume{{+ Name: "workspace",+ DurableDir: &ateapipb.DurableDirVolumeSource{},+ }},+ SnapshotsConfig: &ateapipb.SnapshotsConfig{+ StorageLocation: snapshotsBucket,+ OnPause: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA,+ OnCommit: ateapipb.SnapshotContentScope_SNAPSHOT_CONTENT_SCOPE_DATA,+ OnResume: &ateapipb.OnResumeConfig{+ FromData: ateapipb.ResumeSource_RESUME_SOURCE_GOLDEN,+ },+ },+ SandboxConfig: &ateapipb.SandboxConfig{+ SandboxClass: ateapipb.SandboxClass_SANDBOX_CLASS_GVISOR,+ ConfigName: "gvisor-default",+ },+ }+}++// EnsureActorTemplateWithImage creates an ActorTemplate using the specified container image and optional environment variables.+func (c *Client) EnsureActorTemplateWithImage(ctx context.Context, baseAtespace, baseTemplate, targetAtespace, targetTemplate, image string, extraEnv ...map[string]string) (*ateapipb.ActorTemplate, error) {+ existing, err := c.GetActorTemplate(ctx, targetAtespace, targetTemplate)+ if err == nil && existing != nil {+ return existing, nil+ }++ envMap := make(map[string]string)+ for _, envs := range extraEnv {+ for k, v := range envs {+ envMap[k] = v+ }+ }++ tmpl := BuildActorTemplate(targetAtespace, targetTemplate, image, envMap, nil, "")+ req := &ateapipb.CreateActorTemplateRequest{+ ActorTemplate: tmpl,+ }+ created, err := c.control.CreateActorTemplate(ctx, req)+ if err != nil && status.Code(err) != codes.AlreadyExists {+ return nil, fmt.Errorf("creating actor template %s/%s: %w", targetAtespace, targetTemplate, err)+ }+ if created != nil {+ return created, nil+ }+ return c.GetActorTemplate(ctx, targetAtespace, targetTemplate)+}++// EnsureActor creates an Actor in the specified atespace deriving from an ActorTemplate.+func (c *Client) EnsureActor(ctx context.Context, atespace, actorName, templateAtespace, templateName string) (*ateapipb.Actor, error) {+ req := &ateapipb.CreateActorRequest{+ Actor: &ateapipb.Actor{+ Metadata: &ateapipb.ResourceMetadata{+ Atespace: atespace,+ Name: actorName,+ },+ ActorTemplate: &ateapipb.ObjectRef{+ Atespace: templateAtespace,+ Name: templateName,+ },+ },+ }+ actor, err := c.control.CreateActor(ctx, req)+ if err != nil {+ if status.Code(err) == codes.AlreadyExists {+ existing, getErr := c.control.GetActor(ctx, &ateapipb.GetActorRequest{+ Actor: &ateapipb.ObjectRef{+ Atespace: atespace,+ Name: actorName,+ },+ })+ if getErr == nil && existing != nil {+ state := existing.GetStatus().GetState()+ if state == ateapipb.ActorState_ACTOR_STATE_CRASHED {+ slog.Warn("existing actor is crashed, deleting and recreating", "actor", actorName)+ _, _ = c.control.DeleteActor(ctx, &ateapipb.DeleteActorRequest{+ Actor: &ateapipb.ObjectRef{+ Atespace: atespace,+ Name: actorName,+ },+ AnyState: true,+ })+ state = ateapipb.ActorState_ACTOR_STATE_DELETING+ }+ if state == ateapipb.ActorState_ACTOR_STATE_DELETING {+ // Wait briefly for previous actor deletion to finalize before recreating+ for i := 0; i < 20; i++ {+ select {+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-time.After(500 * time.Millisecond):+ }+ actor, err = c.control.CreateActor(ctx, req)+ if err == nil {+ return actor, nil+ }+ if status.Code(err) != codes.AlreadyExists {+ break+ }+ }+ return nil, fmt.Errorf("actor %s/%s is still deleting; please retry", atespace, actorName)+ }+ }+ return existing, getErr+ }+ return nil, fmt.Errorf("creating actor %s/%s: %w", atespace, actorName, err)+ }+ return actor, nil+}++// ResumeActor resumes the specified actor onto a worker and returns the worker details.+func (c *Client) ResumeActor(ctx context.Context, atespace, actorName string) (*ateapipb.Actor, string, error) {+ req := &ateapipb.ResumeActorRequest{+ Actor: &ateapipb.ObjectRef{+ Atespace: atespace,+ Name: actorName,+ },+ }+ resp, err := c.control.ResumeActor(ctx, req)+ if err != nil {+ return nil, "", fmt.Errorf("resuming actor %s/%s: %w", atespace, actorName, err)+ }+ if resp.Actor == nil {+ return nil, "", fmt.Errorf("nil actor returned when resuming %s/%s", atespace, actorName)+ }+ var workerIP string+ if resp.Actor.Status != nil && resp.Actor.Status.WorkerAssignment != nil {+ workerIP = resp.Actor.Status.WorkerAssignment.WorkerPodIp+ }+ return resp.Actor, workerIP, nil+}++// SuspendActor suspends the specified actor, triggering state checkpointing.+func (c *Client) SuspendActor(ctx context.Context, atespace, actorName string) error {+ req := &ateapipb.SuspendActorRequest{+ Actor: &ateapipb.ObjectRef{+ Atespace: atespace,+ Name: actorName,+ },+ }+ _, err := c.control.SuspendActor(ctx, req)+ if err != nil {+ return fmt.Errorf("suspending actor %s/%s: %w", atespace, actorName, err)+ }+ return nil+}++// DeleteActor deletes the specified actor from Substrate.+func (c *Client) DeleteActor(ctx context.Context, atespace, actorName string) error {+ req := &ateapipb.DeleteActorRequest{+ Actor: &ateapipb.ObjectRef{+ Atespace: atespace,+ Name: actorName,+ },+ AnyState: true,+ }+ _, err := c.control.DeleteActor(ctx, req)+ if err != nil && status.Code(err) != codes.NotFound {+ return fmt.Errorf("deleting actor %s/%s: %w", atespace, actorName, err)+ }+ return nil+}++// ListActorTemplates returns all ActorTemplates in the given atespace.+func (c *Client) ListActorTemplates(ctx context.Context, atespace string) ([]*ateapipb.ActorTemplate, error) {+ resp, err := c.control.ListActorTemplates(ctx, &ateapipb.ListActorTemplatesRequest{Atespace: atespace})+ if err != nil {+ return nil, fmt.Errorf("listing actor templates in %s: %w", atespace, err)+ }+ if resp.GetNextPageToken() != "" {+ slog.Warn("actor template listing was truncated", "atespace", atespace)+ }+ return resp.GetActorTemplates(), nil+}++// DeleteActorTemplate deletes the specified ActorTemplate. A missing template is not an error.+func (c *Client) DeleteActorTemplate(ctx context.Context, atespace, templateName string) error {+ req := &ateapipb.DeleteActorTemplateRequest{+ ActorTemplate: &ateapipb.ObjectRef{+ Atespace: atespace,+ Name: templateName,+ },+ }+ _, err := c.control.DeleteActorTemplate(ctx, req)+ if err != nil && status.Code(err) != codes.NotFound {+ return fmt.Errorf("deleting actor template %s/%s: %w", atespace, templateName, err)+ }+ return nil+}++// ApplyEgressPolicy applies egress rules to the Actor from a Gateway's allowlist.+func (c *Client) ApplyEgressPolicy(ctx context.Context, atespace, actorName string, allowlist *v1alpha1.EgressAllowlist) error {+ if allowlist == nil || len(allowlist.Hosts) == 0 {+ return nil+ }++ var patterns []string+ var allowAll bool+ var cidrs []string++ for _, h := range allowlist.Hosts {+ if h.Host == "*" || h.Host == "0.0.0.0/0" {+ allowAll = true+ break+ }+ if strings.Contains(h.Host, "/") {+ cidrs = append(cidrs, h.Host)+ } else if h.Host != "" {+ patterns = append(patterns, h.Host)+ }+ }++ var rules []*ateapipb.EgressRule+ if allowAll {+ rules = append(rules, &ateapipb.EgressRule{+ All: &emptypb.Empty{},+ })+ } else {+ if len(patterns) > 0 {+ rules = append(rules, &ateapipb.EgressRule{+ Hostnames: &ateapipb.HostnameRule{+ Patterns: patterns,+ },+ })+ }+ if len(cidrs) > 0 {+ rules = append(rules, &ateapipb.EgressRule{+ Cidrs: &ateapipb.CIDRRule{+ Cidrs: cidrs,+ },+ })+ }+ }++ egressPolicy := &ateapipb.EgressPolicy{+ Metadata: &ateapipb.ResourceMetadata{+ Atespace: atespace,+ Name: "default",+ },+ Rules: rules,+ }++ actorRef := &ateapipb.ObjectRef{+ Atespace: atespace,+ Name: actorName,+ }++ // Try creating the policy; if it already exists, update it.+ createReq := &ateapipb.CreateActorEgressPolicyRequest{+ Actor: actorRef,+ EgressPolicy: egressPolicy,+ }+ _, err := c.control.CreateActorEgressPolicy(ctx, createReq)+ if err != nil {+ if status.Code(err) == codes.AlreadyExists {+ existing, getErr := c.control.GetActorEgressPolicy(ctx, &ateapipb.GetActorEgressPolicyRequest{+ Actor: actorRef,+ })+ if getErr == nil && existing != nil && existing.Metadata != nil {+ egressPolicy.Metadata.Uid = existing.Metadata.Uid+ egressPolicy.Metadata.Version = existing.Metadata.Version+ }+ updateReq := &ateapipb.UpdateActorEgressPolicyRequest{+ Actor: actorRef,+ EgressPolicy: egressPolicy,+ }+ _, updateErr := c.control.UpdateActorEgressPolicy(ctx, updateReq)+ if updateErr != nil {+ return fmt.Errorf("updating egress policy on %s/%s: %w", atespace, actorName, updateErr)+ }+ return nil+ }+ slog.Warn("failed to apply egress policy", "actor", actorName, "error", err)+ return fmt.Errorf("creating egress policy on %s/%s: %w", atespace, actorName, err)+ }+ return nil+}diff --git a/internal/telemetry/telemetry.go b/internal/telemetry/telemetry.godeleted file mode 100644index ac0da9e..0000000--- a/internal/telemetry/telemetry.go+++ /dev/null@@ -1,106 +0,0 @@-// 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 telemetry--import (- "context"- "fmt"- "os"-- "cloud.google.com/go/compute/metadata"- "go.opentelemetry.io/otel"- "go.opentelemetry.io/otel/attribute"- "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"- "go.opentelemetry.io/otel/propagation"- "go.opentelemetry.io/otel/sdk/resource"- sdktrace "go.opentelemetry.io/otel/sdk/trace"- semconv "go.opentelemetry.io/otel/semconv/v1.26.0"- oauth2google "golang.org/x/oauth2/google"- "google.golang.org/grpc"- "google.golang.org/grpc/credentials/google"-)--const defaultEndpoint = "telemetry.googleapis.com"--// WithGCPCredentials returns an option that configures the OTLP exporter to use Google Cloud credentials.-func WithGCPCredentials() otlptracegrpc.Option {- bundle := google.NewDefaultCredentials()- return otlptracegrpc.WithDialOption(- grpc.WithTransportCredentials(bundle.TransportCredentials()),- grpc.WithPerRPCCredentials(bundle.PerRPCCredentials()),- )-}--// SetTraceProvider initializes the OpenTelemetry SDK.-// It returns a shutdown function that should be called when the application exits.-func SetTraceProvider(ctx context.Context, service string, opts ...otlptracegrpc.Option) (func(context.Context) error, error) {- // 1. Set global propagator. This is crucial for context propagation over gRPC/HTTP.- otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(- propagation.TraceContext{},- propagation.Baggage{},- ))-- // 2. Create OTLP Exporter.- exporter, err := otlptracegrpc.New(ctx, opts...)- if err != nil {- return nil, fmt.Errorf("failed to create OTLP trace exporter: %w", err)- }-- // 3. Define Resource.- attrs := []attribute.KeyValue{- semconv.ServiceNameKey.String(service),- }- if projectID := detectGCPProjectID(ctx); projectID != "" {- attrs = append(attrs, attribute.String("gcp.project_id", projectID))- }-- res, err := resource.New(ctx,- resource.WithAttributes(attrs...),- resource.WithProcess(),- resource.WithTelemetrySDK(),- )- if err != nil {- return nil, fmt.Errorf("failed to create resource: %w", err)- }-- // 4. Create TracerProvider.- bsp := sdktrace.NewBatchSpanProcessor(exporter)- tp := sdktrace.NewTracerProvider(- sdktrace.WithSampler(sdktrace.AlwaysSample()),- sdktrace.WithResource(res),- sdktrace.WithSpanProcessor(bsp),- )-- otel.SetTracerProvider(tp)-- return func(shutdownCtx context.Context) error {- return tp.Shutdown(shutdownCtx)- }, nil-}--func detectGCPProjectID(ctx context.Context) string {- if proj := os.Getenv("GOOGLE_CLOUD_PROJECT"); proj != "" {- return proj- }- if metadata.OnGCEWithContext(ctx) {- if proj, err := metadata.ProjectIDWithContext(ctx); err == nil {- return proj- }- }- if creds, err := oauth2google.FindDefaultCredentials(ctx); err == nil && creds.ProjectID != "" {- return creds.ProjectID- }- return ""-}diff --git a/internal/tunnel/context.go b/internal/tunnel/context.gonew file mode 100644index 0000000..794830c--- /dev/null+++ b/internal/tunnel/context.go@@ -0,0 +1,70 @@+// 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 tunnel++import (+ "os"+ "os/exec"+ "path/filepath"+ "strings"++ "gopkg.in/yaml.v3"+)++type kubeConfig struct {+ CurrentContext string `yaml:"current-context"`+}++// CurrentContext returns the active Kubernetes context, checking:+// 1. Explicitly passed override+// 2. KUBECONTEXT environment variable+// 3. ~/.kube/config current-context (fast parse via YAML)+// 4. Fallback to 'kubectl config current-context'+func CurrentContext(override string) (string, error) {+ if override != "" {+ return override, nil+ }+ if env := os.Getenv("KUBECONTEXT"); env != "" {+ return env, nil+ }++ // Fast path: try reading kubeconfig directly+ kubeconfigPath := os.Getenv("KUBECONFIG")+ if kubeconfigPath == "" {+ home, err := os.UserHomeDir()+ if err == nil {+ kubeconfigPath = filepath.Join(home, ".kube", "config")+ }+ }++ if kubeconfigPath != "" && !strings.Contains(kubeconfigPath, string(os.PathListSeparator)) {+ if data, err := os.ReadFile(kubeconfigPath); err == nil {+ var cfg kubeConfig+ if err := yaml.Unmarshal(data, &cfg); err == nil && cfg.CurrentContext != "" {+ return cfg.CurrentContext, nil+ }+ }+ }++ // Fallback to kubectl CLI+ out, err := exec.Command("kubectl", "config", "current-context").Output()+ if err == nil {+ ctx := strings.TrimSpace(string(out))+ if ctx != "" {+ return ctx, nil+ }+ }+ return "", err+}diff --git a/internal/tunnel/tunnel.go b/internal/tunnel/tunnel.gonew file mode 100644index 0000000..6ab44eb--- /dev/null+++ b/internal/tunnel/tunnel.go@@ -0,0 +1,390 @@+// 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 tunnel++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "regexp"+ "strconv"+ "strings"+ "syscall"+ "time"+)++var portForwardRegex = regexp.MustCompile(`Forwarding from .*:(\d+)\s+->`)++type TunnelInfo struct {+ Context string `json:"context"`+ Namespace string `json:"namespace"`+ Service string `json:"service"`+ Port int `json:"port"`+ PID int `json:"pid"`+ CreatedAt time.Time `json:"created_at"`+}++type Options struct {+ ServerURL string+ Context string+ Namespace string // default: ax-system+ Service string // default: ax-server+ Target string // e.g. "pod/name" or "svc/name" (overrides Service if set)+ Port int // remote port, default: 8080+}++func SanitizeContext(name string) string {+ var sb strings.Builder+ for _, r := range name {+ if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {+ sb.WriteRune(r)+ } else {+ sb.WriteRune('_')+ }+ }+ s := sb.String()+ if s == "" {+ return "default"+ }+ return s+}++func TunnelDir() (string, error) {+ if dir := os.Getenv("AX_HOME"); dir != "" {+ p := filepath.Join(dir, "tunnels")+ return p, os.MkdirAll(p, 0755)+ }+ home, err := os.UserHomeDir()+ if err != nil {+ return "", err+ }+ p := filepath.Join(home, ".ax", "tunnels")+ return p, os.MkdirAll(p, 0755)+}++func GetTunnel(ctxName string) (*TunnelInfo, error) {+ dir, err := TunnelDir()+ if err != nil {+ return nil, err+ }+ statePath := filepath.Join(dir, SanitizeContext(ctxName)+".json")+ data, err := os.ReadFile(statePath)+ if err != nil {+ return nil, err+ }+ var info TunnelInfo+ if err := json.Unmarshal(data, &info); err != nil {+ return nil, err+ }+ return &info, nil+}++func SaveTunnel(info *TunnelInfo) error {+ dir, err := TunnelDir()+ if err != nil {+ return err+ }+ statePath := filepath.Join(dir, SanitizeContext(info.Context)+".json")+ data, err := json.MarshalIndent(info, "", " ")+ if err != nil {+ return err+ }+ return os.WriteFile(statePath, data, 0644)+}++func StopTunnel(info *TunnelInfo) error {+ if info == nil {+ return nil+ }+ if info.PID > 0 {+ // Attempt to terminate process group and single process+ _ = syscall.Kill(-info.PID, syscall.SIGTERM)+ _ = syscall.Kill(info.PID, syscall.SIGTERM)+ }++ dir, err := TunnelDir()+ if err == nil {+ _ = os.Remove(filepath.Join(dir, SanitizeContext(info.Context)+".json"))+ }+ return nil+}++func StopTunnelByContext(ctxName string) error {+ info, err := GetTunnel(ctxName)+ if err != nil {+ return err+ }+ return StopTunnel(info)+}++func ListTunnels() ([]*TunnelInfo, error) {+ dir, err := TunnelDir()+ if err != nil {+ return nil, err+ }+ entries, err := os.ReadDir(dir)+ if err != nil {+ return nil, err+ }++ var results []*TunnelInfo+ for _, entry := range entries {+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {+ continue+ }+ data, err := os.ReadFile(filepath.Join(dir, entry.Name()))+ if err != nil {+ continue+ }+ var info TunnelInfo+ if err := json.Unmarshal(data, &info); err != nil {+ continue+ }+ results = append(results, &info)+ }+ return results, nil+}++func IsTunnelHealthy(port int) bool {+ if port <= 0 {+ return false+ }+ client := http.Client{Timeout: 400 * time.Millisecond}+ resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/healthz", port))+ if err != nil {+ return false+ }+ _ = resp.Body.Close()+ return resp.StatusCode == http.StatusOK+}++// EnsureServerURL resolves the AX server URL.+// If ServerURL or AX_SERVER is explicitly set, it returns that.+// Otherwise, it checks the active Kubernetes context (or opts.Context)+// and establishes/reuses a background port-forward tunnel to svc/ax-server.+func EnsureServerURL(opts Options) (string, error) {+ if opts.ServerURL != "" {+ return opts.ServerURL, nil+ }+ if env := os.Getenv("AX_SERVER"); env != "" {+ return env, nil+ }++ ctxName, err := CurrentContext(opts.Context)+ if err != nil || ctxName == "" {+ // No Kubernetes context found; fallback to local default+ return "http://localhost:8080", nil+ }++ if opts.Namespace == "" {+ if envNs := os.Getenv("AX_SYSTEM_NAMESPACE"); envNs != "" {+ opts.Namespace = envNs+ } else {+ opts.Namespace = "ax-system"+ }+ }+ if opts.Service == "" {+ opts.Service = "ax-server"+ }+ if opts.Port == 0 {+ opts.Port = 8080+ }++ // Check for existing active tunnel+ if existing, err := GetTunnel(ctxName); err == nil && existing != nil {+ if IsTunnelHealthy(existing.Port) {+ return fmt.Sprintf("http://127.0.0.1:%d", existing.Port), nil+ }+ // Existing tunnel is unhealthy or stale, clean it up+ _ = StopTunnel(existing)+ }++ // Start new background port-forward for this context+ dir, err := TunnelDir()+ if err != nil {+ return "", fmt.Errorf("creating tunnel directory: %w", err)+ }+ logPath := filepath.Join(dir, SanitizeContext(ctxName)+".log")+ logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)+ if err != nil {+ return "", fmt.Errorf("opening tunnel log: %w", err)+ }+ defer logFile.Close()++ var kArgs []string+ if ctxName != "" {+ kArgs = append(kArgs, "--context", ctxName)+ }+ targetRes := fmt.Sprintf("svc/%s", opts.Service)+ if opts.Target != "" {+ targetRes = opts.Target+ }+ kArgs = append(kArgs, "port-forward", "-n", opts.Namespace, targetRes, fmt.Sprintf(":%d", opts.Port))++ cmd := exec.Command("kubectl", kArgs...)+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}+ cmd.Stdout = logFile+ cmd.Stderr = logFile++ if err := cmd.Start(); err != nil {+ return "", fmt.Errorf("spawning kubectl port-forward for context %q: %w", ctxName, err)+ }++ // Wait for port assignment from log output+ localPort := 0+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ time.Sleep(50 * time.Millisecond)++ logData, err := os.ReadFile(logPath)+ if err != nil {+ continue+ }+ if match := portForwardRegex.FindStringSubmatch(string(logData)); len(match) > 1 {+ p, err := strconv.Atoi(match[1])+ if err == nil && p > 0 {+ localPort = p+ break+ }+ }++ // Check if command exited prematurely+ if err := syscall.Kill(cmd.Process.Pid, 0); err != nil {+ return "", fmt.Errorf("kubectl port-forward exited for context %q: %s", ctxName, strings.TrimSpace(string(logData)))+ }+ }++ if localPort == 0 {+ _ = cmd.Process.Kill()+ logData, _ := os.ReadFile(logPath)+ return "", fmt.Errorf("timeout waiting for kubectl port-forward on context %q: %s", ctxName, strings.TrimSpace(string(logData)))+ }++ // Wait for healthz to respond+ healthy := false+ healthDeadline := time.Now().Add(3 * time.Second)+ for time.Now().Before(healthDeadline) {+ if IsTunnelHealthy(localPort) {+ healthy = true+ break+ }+ time.Sleep(100 * time.Millisecond)+ }++ if !healthy {+ _ = cmd.Process.Kill()+ return "", fmt.Errorf("tunnel started on port %d but health check failed for context %q", localPort, ctxName)+ }++ info := &TunnelInfo{+ Context: ctxName,+ Namespace: opts.Namespace,+ Service: opts.Service,+ Port: localPort,+ PID: cmd.Process.Pid,+ CreatedAt: time.Now(),+ }+ _ = SaveTunnel(info)++ return fmt.Sprintf("http://127.0.0.1:%d", localPort), nil+}++// PortForward starts an ephemeral port-forward to a Kubernetes resource (e.g. pod/name or svc/name)+// and returns the local assigned port and a cleanup function.+func PortForward(ctx context.Context, kubeContext, namespace, targetResource string, remotePort int) (int, func(), error) {+ ctxName, err := CurrentContext(kubeContext)+ if err != nil {+ ctxName = ""+ }++ var kArgs []string+ if ctxName != "" {+ kArgs = append(kArgs, "--context", ctxName)+ }+ if namespace != "" {+ kArgs = append(kArgs, "-n", namespace)+ }+ kArgs = append(kArgs, "port-forward", targetResource, fmt.Sprintf(":%d", remotePort))++ cmd := exec.CommandContext(ctx, "kubectl", kArgs...)+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}++ pr, pw, err := os.Pipe()+ if err != nil {+ return 0, nil, fmt.Errorf("creating pipe: %w", err)+ }+ cmd.Stdout = pw+ cmd.Stderr = pw++ if err := cmd.Start(); err != nil {+ _ = pr.Close()+ _ = pw.Close()+ return 0, nil, fmt.Errorf("spawning kubectl port-forward for %s: %w", targetResource, err)+ }++ portChan := make(chan int, 1)+ errChan := make(chan error, 1)++ go func() {+ buf := make([]byte, 1024)+ var output strings.Builder+ for {+ n, err := pr.Read(buf)+ if n > 0 {+ output.Write(buf[:n])+ if match := portForwardRegex.FindStringSubmatch(output.String()); len(match) > 1 {+ p, convErr := strconv.Atoi(match[1])+ if convErr == nil && p > 0 {+ portChan <- p+ }+ }+ }+ if err != nil {+ select {+ case errChan <- fmt.Errorf("kubectl port-forward exited: %s", strings.TrimSpace(output.String())):+ default:+ }+ return+ }+ }+ }()++ cleanup := func() {+ _ = pr.Close()+ _ = pw.Close()+ if cmd.Process != nil {+ _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)+ _ = cmd.Process.Kill()+ }+ }++ select {+ case p := <-portChan:+ return p, cleanup, nil+ case err := <-errChan:+ cleanup()+ return 0, nil, err+ case <-time.After(8 * time.Second):+ cleanup()+ return 0, nil, fmt.Errorf("timed out waiting for port-forward to %s", targetResource)+ case <-ctx.Done():+ cleanup()+ return 0, nil, ctx.Err()+ }+}diff --git a/internal/tunnel/tunnel_test.go b/internal/tunnel/tunnel_test.gonew file mode 100644index 0000000..000862a--- /dev/null+++ b/internal/tunnel/tunnel_test.go@@ -0,0 +1,56 @@+// 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 tunnel++import (+ "testing"+)++func TestSanitizeContext(t *testing.T) {+ tests := []struct {+ input string+ want string+ }{+ {"my-cluster", "my-cluster"},+ {"gke_project_us-central1_cluster", "gke_project_us-central1_cluster"},+ {"arn:aws:eks:us-west-2:123456789:cluster/prod", "arn_aws_eks_us-west-2_123456789_cluster_prod"},+ {"", "default"},+ }++ for _, tt := range tests {+ got := SanitizeContext(tt.input)+ if got != tt.want {+ t.Errorf("SanitizeContext(%q) = %q; want %q", tt.input, got, tt.want)+ }+ }+}++func TestPortForwardRegex(t *testing.T) {+ cases := []struct {+ log string+ port string+ }{+ {"Forwarding from 127.0.0.1:54947 -> 8080\n", "54947"},+ {"Forwarding from [::1]:61234 -> 8080\n", "61234"},+ {"Some prelude\nForwarding from 127.0.0.1:8080 -> 8080\n", "8080"},+ }++ for _, c := range cases {+ match := portForwardRegex.FindStringSubmatch(c.log)+ if len(match) < 2 || match[1] != c.port {+ t.Errorf("expected port %q from %q, got %v", c.port, c.log, match)+ }+ }+}diff --git a/internal/workspace/planner.go b/internal/workspace/planner.gonew file mode 100644index 0000000..79b4b4a--- /dev/null+++ b/internal/workspace/planner.go@@ -0,0 +1,112 @@+// 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 workspace++import (+ "context"+ "fmt"++ "github.com/google/ax/internal/model"+ "github.com/google/ax/internal/store"+ "github.com/google/ax/pkg/apis/v1alpha1"+)++// EnvironmentPlan represents the resolved environment and tool setup for a workspace.+type EnvironmentPlan struct {+ WorkspaceName string `json:"workspaceName"`+ Goal string `json:"goal"`+ ModelUsed string `json:"modelUsed"`+ PlanSummary string `json:"planSummary"`+ GitRepos []*v1alpha1.GitRepo `json:"gitRepos,omitempty"`+ MCPConfig *v1alpha1.MCPConfig `json:"mcpConfig,omitempty"`+ Skills *v1alpha1.SkillsConfig `json:"skills,omitempty"`+}++// Planner resolves and prepares workspace environments using a model client.+type Planner struct {+ client *model.Client+}++// NewPlanner creates a new Workspace planner backed by a model client.+func NewPlanner(client *model.Client) *Planner {+ if client == nil {+ client = model.NewDefaultClient()+ }+ return &Planner{+ client: client,+ }+}++// NewPlannerWithConfig creates a new Workspace planner using the provided model.Config.+func NewPlannerWithConfig(cfg model.Config, opts ...model.Option) *Planner {+ return NewPlanner(model.NewClient(cfg, opts...))+}++// NewPlannerFromStore creates a Workspace planner by loading the "default-model" configuration from the store.+func NewPlannerFromStore(ctx context.Context, s store.Store, atespace string, opts ...model.Option) (*Planner, error) {+ client, err := model.NewDefaultClientFromStore(ctx, s, atespace, opts...)+ if err != nil {+ return nil, err+ }+ return NewPlanner(client), nil+}++// PlanEnvironment analyzes the declared goal, workspace repositories, MCP servers,+// and skills using Gemini 3.8 Flash to synthesize execution setup instructions.+func (p *Planner) PlanEnvironment(ctx context.Context, ws *v1alpha1.Workspace, goal string) (*EnvironmentPlan, error) {+ if ws == nil {+ return nil, fmt.Errorf("workspace cannot be nil")+ }++ wsName := ""+ if ws.Metadata != nil {+ wsName = ws.Metadata.Name+ }+ var gitRepos []*v1alpha1.GitRepo+ var mcpConfig *v1alpha1.MCPConfig+ var skills *v1alpha1.SkillsConfig+ if ws.Spec != nil {+ gitRepos = ws.Spec.Git+ mcpConfig = ws.Spec.Mcp+ skills = ws.Spec.Skills+ }++ prompt := fmt.Sprintf(+ "Synthesize an environment bootstrap and toolchain plan for workspace %q with goal %q. Git repositories: %d, MCP servers: %v",+ wsName,+ goal,+ len(gitRepos),+ mcpConfig != nil,+ )++ resp, err := p.client.Generate(ctx, &model.GenerateRequest{+ Model: model.DefaultModel, // gemini-3.8-flash+ Prompt: prompt,+ SystemInstruction: "You are the AX system workspace environment planner. Output concise bootstrap plans for agent workspaces.",+ })+ if err != nil {+ return nil, fmt.Errorf("generating environment plan for workspace %s: %w", wsName, err)+ }++ return &EnvironmentPlan{+ WorkspaceName: wsName,+ Goal: goal,+ ModelUsed: resp.Model,+ PlanSummary: resp.Content,+ GitRepos: gitRepos,+ MCPConfig: mcpConfig,+ Skills: skills,+ }, nil+}diff --git a/internal/workspace/planner_test.go b/internal/workspace/planner_test.gonew file mode 100644index 0000000..4236db6--- /dev/null+++ b/internal/workspace/planner_test.go@@ -0,0 +1,112 @@+// 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 workspace_test++import (+ "context"+ "testing"++ "github.com/google/ax/internal/model"+ "github.com/google/ax/internal/store/memory"+ "github.com/google/ax/internal/workspace"+ "github.com/google/ax/pkg/apis/v1alpha1"+)++func TestWorkspacePlanner_PlanEnvironment(t *testing.T) {+ planner := workspace.NewPlannerWithConfig(+ model.Config{+ Provider: model.ProviderGoogle,+ Model: model.DefaultModel,+ DisableRemote: true,+ },+ )++ ws := &v1alpha1.Workspace{+ Metadata: &v1alpha1.ObjectMeta{+ Name: "default-workspace",+ Atespace: "default",+ },+ Spec: &v1alpha1.WorkspaceSpec{+ Git: []*v1alpha1.GitRepo{+ {+ Name: "origin",+ Repo: "https://github.com/chalk/chalk.git",+ Branch: "main",+ },+ },+ },+ }++ plan, err := planner.PlanEnvironment(context.Background(), ws, "Setup a Go development environment")+ if err != nil {+ t.Fatalf("PlanEnvironment failed: %v", err)+ }++ if plan.WorkspaceName != "default-workspace" {+ t.Errorf("expected workspace 'default-workspace', got %s", plan.WorkspaceName)+ }+ if plan.ModelUsed != model.DefaultModel {+ t.Errorf("expected model %q, got %q", model.DefaultModel, plan.ModelUsed)+ }+ if plan.PlanSummary == "" {+ t.Errorf("expected non-empty plan summary")+ }+}++func TestWorkspacePlanner_FromStore(t *testing.T) {+ ctx := context.Background()+ s := memory.NewStore()++ customModel := &v1alpha1.Model{+ Metadata: &v1alpha1.ObjectMeta{+ Name: "default-model",+ Atespace: "default",+ },+ Spec: &v1alpha1.ModelSpec{+ Provider: "google",+ Model: "gemini-3.8-flash",+ SecretKey: &v1alpha1.SecretKeyRef{+ Name: "gemini-api-secret",+ Key: "GEMINI_API_KEY",+ },+ },+ }+ if err := s.SaveModel(ctx, customModel); err != nil {+ t.Fatalf("failed to save model: %v", err)+ }++ t.Setenv("GEMINI_API_KEY", "test-key-1234")++ planner, err := workspace.NewPlannerFromStore(ctx, s, "default", model.WithDisableRemote(true))+ if err != nil {+ t.Fatalf("NewPlannerFromStore failed: %v", err)+ }++ ws := &v1alpha1.Workspace{+ Metadata: &v1alpha1.ObjectMeta{+ Name: "store-workspace",+ Atespace: "default",+ },+ Spec: &v1alpha1.WorkspaceSpec{},+ }++ plan, err := planner.PlanEnvironment(ctx, ws, "Setup Go environment")+ if err != nil {+ t.Fatalf("PlanEnvironment failed: %v", err)+ }+ if plan.ModelUsed != "gemini-3.8-flash" {+ t.Errorf("expected model gemini-3.8-flash, got %s", plan.ModelUsed)+ }+}diff --git a/internal/workspace/setup.go b/internal/workspace/setup.gonew file mode 100644index 0000000..600d2d7--- /dev/null+++ b/internal/workspace/setup.go@@ -0,0 +1,376 @@+// 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 workspace++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "time"++ "github.com/google/ax/pkg/apis/v1alpha1"+)++const (+ // DefaultAXDir is the default directory inside the container used for AX system state and logs.+ DefaultAXDir = "/ax"+ // InitializedMarkerFilename is the base name of the marker file written after a successful maiden run.+ InitializedMarkerFilename = "initialized"++ defaultWorkspacePath = "/workspace"+ defaultBranch = "main"+ defaultRepoDirName = "repo"++ gitSuccessLog = "git-success.log"+ gitErrorLog = "git-error.log"+ gitRetries = 5+ gitRetryDelay = 2 * time.Second++ bootstrapScriptPath = "/usr/local/bin/antigravity_bootstrap.py"+ // bootstrapAPIKeyEnv must be set for the Antigravity agent to run.+ bootstrapAPIKeyEnv = "GEMINI_API_KEY"+ // bootstrapTimeoutEnv overrides the default bootstrap timeout with a Go duration string.+ bootstrapTimeoutEnv = "AX_BOOTSTRAP_TIMEOUT"+ // bootstrapDataDir, under AXDir, is where the agent keeps its own state so+ // conversation logs and caches stay out of the workspace.+ bootstrapDataDir = "antigravity"+ // defaultBootstrapTimeout allows the agent enough time to install toolchains and+ // dependencies. The workspace reports not-ready until it finishes.+ defaultBootstrapTimeout = 10 * time.Minute++ dirPerm = 0o755+ filePerm = 0o644+)++// AXDir is the directory inside the container used for AX system state and logs.+// Tests override it to keep state out of the workspace.+var AXDir = DefaultAXDir++// SetupResult contains details about the workspace maiden initialization.+type SetupResult struct {+ WorkspacePath string+ ClonedRepos []string+ SkillsMounted string+ IsMaidenRun bool+ // BootstrapRan reports whether the Antigravity agent ran to completion for the goal.+ BootstrapRan bool+}++// SetupWorkspace prepares the workspace directory on its maiden run: it clones the+// declared Git repositories, creates the skills path, and invokes the Antigravity+// bootstrap when a goal is provided. A marker file under AXDir records a completed+// maiden run so subsequent calls are no-ops.+//+// Git failures are logged and recorded under AXDir but do not abort setup. The marker+// is withheld in that case so the next start retries the clone.+func SetupWorkspace(ctx context.Context, ws *v1alpha1.Workspace, targetPath string, goal string) (*SetupResult, error) {+ if targetPath == "" {+ targetPath = defaultWorkspacePath+ }+ // Tooling downstream (git, the Antigravity agent) scopes itself to this path,+ // so it must be absolute.+ if abs, err := filepath.Abs(targetPath); err == nil {+ targetPath = abs+ }+ res := &SetupResult{WorkspacePath: targetPath}++ if err := os.MkdirAll(targetPath, dirPerm); err != nil {+ return nil, fmt.Errorf("creating workspace directory %s: %w", targetPath, err)+ }+ if err := os.MkdirAll(AXDir, dirPerm); err != nil {+ slog.Warn("creating ax state directory", "dir", AXDir, "error", err)+ }++ markerPath := filepath.Join(AXDir, MarkerName(targetPath))+ if _, err := os.Stat(markerPath); err == nil {+ slog.Info("workspace already initialized; skipping maiden run setup", "path", targetPath)+ return res, nil+ }++ slog.Info("executing workspace maiden run setup", "path", targetPath)+ res.IsMaidenRun = true++ gitOK := true+ if ws != nil && ws.Spec != nil {+ res.ClonedRepos, gitOK = cloneRepos(ctx, ws.Spec.Git, targetPath)+ res.SkillsMounted = setupSkills(ws.Spec.Skills)+ }++ if goal != "" {+ res.BootstrapRan = runBootstrap(ctx, goal, targetPath)+ }++ if !gitOK {+ slog.Warn("maiden run workspace setup completed with errors; marker omitted to allow retry", "path", targetPath)+ return res, nil+ }++ writeMarker(markerPath, ws)+ slog.Info("maiden run workspace setup completed successfully", "path", targetPath)+ return res, nil+}++// cloneRepos fetches each declared repository into the workspace. It returns the+// repositories that succeeded and whether every clone succeeded.+func cloneRepos(ctx context.Context, repos []*v1alpha1.GitRepo, targetPath string) ([]string, bool) {+ var cloned []string+ ok := true+ for _, repo := range repos {+ if repo == nil || repo.Repo == "" {+ continue+ }++ dest := cloneDestination(repo, targetPath)+ if err := os.MkdirAll(dest, dirPerm); err != nil {+ slog.Warn("failed to create destination dir", "dir", dest, "error", err)+ }++ branch := repo.Branch+ if branch == "" {+ branch = defaultBranch+ }++ slog.Info("initializing and fetching git repo", "repo", repo.Repo, "branch", branch, "dir", dest, "depth", repo.Depth)+ out, err := retry(ctx, gitRetries, gitRetryDelay, func() ([]byte, error) {+ return fetchRepo(ctx, dest, repo.Repo, branch, repo.Depth)+ })+ if err != nil {+ ok = false+ slog.Warn("git fetch error (continuing setup)", "repo", repo.Repo, "error", err, "output", string(out))+ writeStateFile(gitErrorLog, fmt.Appendf(nil, "error: %v\noutput: %s\n", err, out))+ continue+ }++ cloned = append(cloned, repo.Repo)+ writeStateFile(gitSuccessLog, out)+ }+ return cloned, ok+}++// cloneDestination resolves where a repository is checked out.+//+// An explicit Dir wins: "." means the workspace root, an absolute path is used as-is,+// and anything else is relative to the workspace. Otherwise the directory is named after+// the repository's Name, unless that is empty or a generic placeholder such as "origin",+// in which case the name is derived from the repository URL.+func cloneDestination(repo *v1alpha1.GitRepo, targetPath string) string {+ if repo.Dir != "" {+ switch {+ case repo.Dir == ".":+ return targetPath+ case filepath.IsAbs(repo.Dir):+ return repo.Dir+ default:+ return filepath.Join(targetPath, repo.Dir)+ }+ }++ name := repo.Name+ if name == "" || name == defaultRepoDirName || name == "origin" {+ if derived := RepoDirName(repo.Repo); derived != "" {+ name = derived+ } else if name == "" {+ name = defaultRepoDirName+ }+ }+ return filepath.Join(targetPath, name)+}++// fetchRepo initializes dir as a git repository pointed at repoURL, fetches branch,+// and checks it out. If depth > 0, it performs a shallow fetch. It is idempotent so it+// can be retried against a partially initialized directory. Arguments are passed+// directly to git, never through a shell.+func fetchRepo(ctx context.Context, dir, repoURL, branch string, depth int32) ([]byte, error) {+ var combined []byte+ run := func(args ...string) error {+ cmd := exec.CommandContext(ctx, "git", args...)+ cmd.Dir = dir+ out, err := cmd.CombinedOutput()+ combined = append(combined, out...)+ if err != nil {+ return fmt.Errorf("git %s: %w", args[0], err)+ }+ return nil+ }++ if err := run("init"); err != nil {+ return combined, err+ }+ // A retry lands on an already initialized directory, so fall back to updating the remote.+ if err := run("remote", "add", "origin", repoURL); err != nil {+ if err := run("remote", "set-url", "origin", repoURL); err != nil {+ return combined, err+ }+ }+ fetchArgs := []string{"fetch"}+ if depth > 0 {+ fetchArgs = append(fetchArgs, fmt.Sprintf("--depth=%d", depth))+ }+ fetchArgs = append(fetchArgs, "origin", branch)+ if err := run(fetchArgs...); err != nil {+ return combined, err+ }+ if err := run("checkout", "-f", "FETCH_HEAD"); err != nil {+ return combined, err+ }+ return combined, nil+}++// retry runs op up to attempts times, waiting delay between failures. It stops early+// when ctx is done and never sleeps after the final attempt.+func retry(ctx context.Context, attempts int, delay time.Duration, op func() ([]byte, error)) ([]byte, error) {+ var (+ out []byte+ err error+ )+ for attempt := 1; attempt <= attempts; attempt++ {+ out, err = op()+ if err == nil {+ return out, nil+ }+ if attempt == attempts {+ break+ }+ slog.Warn("git operation failed, will retry", "attempt", attempt, "max", attempts, "error", err, "output", string(out))+ select {+ case <-ctx.Done():+ return out, errors.Join(err, ctx.Err())+ case <-time.After(delay):+ }+ }+ return out, err+}++// setupSkills creates the skills directory if one is declared and returns its path.+func setupSkills(skills *v1alpha1.SkillsConfig) string {+ if skills == nil || skills.Path == "" {+ return ""+ }+ if err := os.MkdirAll(skills.Path, dirPerm); err != nil {+ slog.Warn("creating skills dir", "path", skills.Path, "error", err)+ }+ return skills.Path+}++// runBootstrap hands the goal to the Antigravity agent so it can prepare the workspace.+// It reports whether the agent ran to completion. The agent needs the bootstrap script+// installed and an API key in the environment; when either is missing the step is+// skipped with a log line. Failures are logged and otherwise ignored so the task's own+// command still starts.+func runBootstrap(ctx context.Context, goal, targetPath string) bool {+ if _, err := os.Stat(bootstrapScriptPath); err != nil {+ slog.Info("Antigravity bootstrap script not installed; skipping", "script", bootstrapScriptPath)+ return false+ }+ if os.Getenv(bootstrapAPIKeyEnv) == "" {+ slog.Warn("workspace goal set but no API key available; skipping Antigravity bootstrap", "env", bootstrapAPIKeyEnv)+ return false+ }++ timeout := bootstrapTimeout()+ slog.Info("invoking Antigravity workspace bootstrap with goal", "goal", goal, "dir", targetPath, "timeout", timeout)+ ctx, cancel := context.WithTimeout(ctx, timeout)+ defer cancel()++ dataDir := filepath.Join(AXDir, bootstrapDataDir)+ if err := os.MkdirAll(dataDir, dirPerm); err != nil {+ slog.Warn("creating Antigravity data dir", "dir", dataDir, "error", err)+ }++ cmd := exec.CommandContext(ctx, "python3", bootstrapScriptPath,+ "--goal", goal,+ "--workspace", targetPath,+ "--data-dir", dataDir,+ )+ cmd.Dir = targetPath+ cmd.Stdout = os.Stdout+ cmd.Stderr = os.Stderr+ if err := cmd.Run(); err != nil {+ if ctx.Err() != nil {+ slog.Warn("Antigravity bootstrap timed out (continuing)", "timeout", timeout)+ } else {+ slog.Warn("Antigravity bootstrap failed (continuing)", "error", err)+ }+ return false+ }+ slog.Info("Antigravity bootstrap completed successfully")+ return true+}++// bootstrapTimeout returns the configured bootstrap timeout, falling back to the default+// when the override is unset or unparsable.+func bootstrapTimeout() time.Duration {+ raw := os.Getenv(bootstrapTimeoutEnv)+ if raw == "" {+ return defaultBootstrapTimeout+ }+ d, err := time.ParseDuration(raw)+ if err != nil || d <= 0 {+ slog.Warn("invalid bootstrap timeout; using default", "env", bootstrapTimeoutEnv, "value", raw, "default", defaultBootstrapTimeout)+ return defaultBootstrapTimeout+ }+ return d+}++// MarkerName returns the maiden-run marker file name for a workspace mounted at+// path. The name is derived from the path so several workspaces in one+// container track their setup independently.+func MarkerName(path string) string {+ if path == "" {+ path = defaultWorkspacePath+ }+ clean := strings.Trim(filepath.Clean(path), "/")+ if clean == "" {+ clean = "root"+ }+ return InitializedMarkerFilename + "-" + strings.ReplaceAll(clean, "/", "-")+}++// writeMarker records a completed maiden run.+func writeMarker(path string, ws *v1alpha1.Workspace) {+ name := "unknown"+ if ws != nil && ws.GetMetadata() != nil && ws.GetMetadata().GetName() != "" {+ name = ws.GetMetadata().GetName()+ }+ content := fmt.Sprintf("workspace: %s\ninitialized_at: %s\n", name, time.Now().UTC().Format(time.RFC3339))+ if err := os.WriteFile(path, []byte(content), filePerm); err != nil {+ slog.Warn("failed to write initialized marker file", "path", path, "error", err)+ }+}++// writeStateFile writes a diagnostic file under AXDir, logging rather than failing on error.+func writeStateFile(name string, data []byte) {+ path := filepath.Join(AXDir, name)+ if err := os.WriteFile(path, data, filePerm); err != nil {+ slog.Warn("failed to write state file", "path", path, "error", err)+ }+}++// RepoDirName extracts the repository name from a git URL or local path.+// For example "https://github.com/chalk/chalk.git" yields "chalk".+func RepoDirName(repoURL string) string {+ trimmed := strings.TrimSuffix(strings.TrimSpace(repoURL), "/")+ trimmed = strings.TrimSuffix(trimmed, ".git")+ idx := strings.LastIndexAny(trimmed, "/:")+ if idx < 0 {+ return trimmed+ }+ return trimmed[idx+1:]+}diff --git a/internal/workspace/setup_test.go b/internal/workspace/setup_test.gonew file mode 100644index 0000000..9026369--- /dev/null+++ b/internal/workspace/setup_test.go@@ -0,0 +1,286 @@+// 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 workspace_test++import (+ "context"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+ "time"++ "github.com/google/ax/internal/workspace"+ "github.com/google/ax/pkg/apis/v1alpha1"+)++func TestSetupWorkspace_MaidenRun(t *testing.T) {+ tempDir, err := os.MkdirTemp("", "ax-ws-test-*")+ if err != nil {+ t.Fatalf("failed to create temp dir: %v", err)+ }+ defer os.RemoveAll(tempDir)++ ws := &v1alpha1.Workspace{+ Metadata: &v1alpha1.ObjectMeta{+ Name: "test-ws",+ },+ Spec: &v1alpha1.WorkspaceSpec{+ Skills: &v1alpha1.SkillsConfig{+ Path: filepath.Join(tempDir, "skills"),+ },+ },+ }++ stateDir := filepath.Join(tempDir, "ax-state")+ origAXDir := workspace.AXDir+ workspace.AXDir = stateDir+ defer func() { workspace.AXDir = origAXDir }()++ // 1. Maiden run+ res1, err := workspace.SetupWorkspace(context.Background(), ws, tempDir, "Test maiden run setup")+ if err != nil {+ t.Fatalf("maiden setup failed: %v", err)+ }+ if !res1.IsMaidenRun {+ t.Errorf("expected maiden run to be true")+ }++ // Verify marker file exists under stateDir/initialized+ markerFile := filepath.Join(stateDir, workspace.MarkerName(tempDir))+ if _, err := os.Stat(markerFile); os.IsNotExist(err) {+ t.Errorf("expected marker file %s to exist", markerFile)+ }++ // Verify workspace directory has no .ax-initialized or .ax directory+ if _, err := os.Stat(filepath.Join(tempDir, ".ax-initialized")); !os.IsNotExist(err) {+ t.Errorf("expected .ax-initialized not to be in workspace")+ }+ if _, err := os.Stat(filepath.Join(tempDir, ".ax")); !os.IsNotExist(err) {+ t.Errorf("expected .ax directory not to be in workspace")+ }++ // 2. Second run (should detect already initialized)+ res2, err := workspace.SetupWorkspace(context.Background(), ws, tempDir, "")+ if err != nil {+ t.Fatalf("second setup failed: %v", err)+ }+ if res2.IsMaidenRun {+ t.Errorf("expected maiden run to be false on second run")+ }+}++func TestSetupWorkspace_GitSubdir(t *testing.T) {+ tempDir, err := os.MkdirTemp("", "ax-ws-git-*")+ if err != nil {+ t.Fatalf("failed to create temp dir: %v", err)+ }+ defer os.RemoveAll(tempDir)++ // Create a dummy source git repository+ srcDir, err := os.MkdirTemp("", "ax-src-git-*")+ if err != nil {+ t.Fatalf("failed to create src dir: %v", err)+ }+ defer os.RemoveAll(srcDir)++ // Init source repo+ // git init -b requires git 2.28+; symbolic-ref works on any version.+ initCmd := exec.Command("sh", "-c", "git init && git symbolic-ref HEAD refs/heads/main && git config user.email '[email protected]' && git config user.name 'AX' && echo 'hello' > README.md && git add . && git commit -m 'initial'")+ initCmd.Dir = srcDir+ if out, err := initCmd.CombinedOutput(); err != nil {+ t.Fatalf("failed to init test git repo: %v (%s)", err, string(out))+ }++ ws := &v1alpha1.Workspace{+ Metadata: &v1alpha1.ObjectMeta{+ Name: "test-git-ws",+ },+ Spec: &v1alpha1.WorkspaceSpec{+ Git: []*v1alpha1.GitRepo{+ {+ Name: "ax",+ Repo: srcDir,+ },+ },+ },+ }++ stateDir := filepath.Join(tempDir, "ax-state")+ origAXDir := workspace.AXDir+ workspace.AXDir = stateDir+ defer func() { workspace.AXDir = origAXDir }()++ res, err := workspace.SetupWorkspace(context.Background(), ws, tempDir, "")+ if err != nil {+ t.Fatalf("setup failed: %v", err)+ }+ if len(res.ClonedRepos) != 1 {+ t.Errorf("expected 1 cloned repo, got %d", len(res.ClonedRepos))+ }++ // Verify repo was cloned into subdirectory 'ax' inside tempDir+ clonedGit := filepath.Join(tempDir, "ax", ".git")+ if _, err := os.Stat(clonedGit); os.IsNotExist(err) {+ t.Errorf("expected %s to exist", clonedGit)+ }++ // Verify git-success.log is created under stateDir and NOT inside workspace+ logFile := filepath.Join(stateDir, "git-success.log")+ if _, err := os.Stat(logFile); os.IsNotExist(err) {+ t.Errorf("expected git log file %s to exist in stateDir", logFile)+ }+ if _, err := os.Stat(filepath.Join(tempDir, ".ax-git-success.log")); !os.IsNotExist(err) {+ t.Errorf("expected .ax-git-success.log NOT to exist in workspace")+ }+}++func TestSetupWorkspace_GitError(t *testing.T) {+ tempDir, err := os.MkdirTemp("", "ax-ws-git-err-*")+ if err != nil {+ t.Fatalf("failed to create temp dir: %v", err)+ }+ defer os.RemoveAll(tempDir)++ ws := &v1alpha1.Workspace{+ Metadata: &v1alpha1.ObjectMeta{+ Name: "test-git-err-ws",+ },+ Spec: &v1alpha1.WorkspaceSpec{+ Git: []*v1alpha1.GitRepo{+ {+ Name: "invalid-repo",+ Repo: "https://127.0.0.1:9/nonexistent/repo.git",+ },+ },+ },+ }++ stateDir := filepath.Join(tempDir, "ax-state")+ origAXDir := workspace.AXDir+ workspace.AXDir = stateDir+ defer func() { workspace.AXDir = origAXDir }()++ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()++ _, _ = workspace.SetupWorkspace(ctx, ws, tempDir, "")++ // Verify git-error.log is created under stateDir and NOT inside workspace+ errLog := filepath.Join(stateDir, "git-error.log")+ if _, err := os.Stat(errLog); os.IsNotExist(err) {+ t.Errorf("expected git error log %s to exist under stateDir", errLog)+ }++ // Verify workspace directory does not have .ax-git-error.log or .ax+ if _, err := os.Stat(filepath.Join(tempDir, ".ax-git-error.log")); !os.IsNotExist(err) {+ t.Errorf("expected .ax-git-error.log NOT to exist in workspace")+ }+ if _, err := os.Stat(filepath.Join(tempDir, ".ax")); !os.IsNotExist(err) {+ t.Errorf("expected .ax directory NOT to exist in workspace")+ }++ // Verify initialization marker was not created due to failure+ markerFile := filepath.Join(stateDir, workspace.MarkerName(tempDir))+ if _, err := os.Stat(markerFile); !os.IsNotExist(err) {+ t.Errorf("expected marker file %s NOT to exist after failure", markerFile)+ }+}++func TestSetupWorkspace_GitDepth(t *testing.T) {+ tempDir, err := os.MkdirTemp("", "ax-ws-git-depth-*")+ if err != nil {+ t.Fatalf("failed to create temp dir: %v", err)+ }+ defer os.RemoveAll(tempDir)++ // Create a dummy source git repository with 3 commits+ srcDir, err := os.MkdirTemp("", "ax-src-git-*")+ if err != nil {+ t.Fatalf("failed to create src dir: %v", err)+ }+ defer os.RemoveAll(srcDir)++ initCmd := exec.Command("sh", "-c", `+git init &&+git symbolic-ref HEAD refs/heads/main &&+git config user.email '[email protected]' &&+git config user.name 'AX' &&+echo '1' > file.txt && git add . && git commit -m 'commit 1' &&+echo '2' > file.txt && git add . && git commit -m 'commit 2' &&+echo '3' > file.txt && git add . && git commit -m 'commit 3'+`)+ initCmd.Dir = srcDir+ if out, err := initCmd.CombinedOutput(); err != nil {+ t.Fatalf("failed to init test git repo with commits: %v (%s)", err, string(out))+ }++ ws := &v1alpha1.Workspace{+ Metadata: &v1alpha1.ObjectMeta{+ Name: "test-shallow-git-ws",+ },+ Spec: &v1alpha1.WorkspaceSpec{+ Git: []*v1alpha1.GitRepo{+ {+ Name: "ax",+ Repo: srcDir,+ Depth: 1,+ },+ },+ },+ }++ stateDir := filepath.Join(tempDir, "ax-state")+ origAXDir := workspace.AXDir+ workspace.AXDir = stateDir+ defer func() { workspace.AXDir = origAXDir }()++ res, err := workspace.SetupWorkspace(context.Background(), ws, tempDir, "")+ if err != nil {+ t.Fatalf("setup failed: %v", err)+ }+ if len(res.ClonedRepos) != 1 {+ t.Errorf("expected 1 cloned repo, got %d", len(res.ClonedRepos))+ }++ // Verify commit count in cloned repo is exactly 1+ countCmd := exec.Command("git", "rev-list", "--count", "HEAD")+ countCmd.Dir = filepath.Join(tempDir, "ax")+ out, err := countCmd.Output()+ if err != nil {+ t.Fatalf("failed to count commits: %v", err)+ }+ if got := string(out); got != "1\n" && got != "1" {+ t.Errorf("expected 1 commit with depth=1, got %q", got)+ }+}++func TestMarkerName(t *testing.T) {+ tests := map[string]string{+ "/workspace": "initialized-workspace",+ "/workspace/": "initialized-workspace",+ "": "initialized-workspace",+ "/": "initialized-root",+ "/workspace/tools": "initialized-workspace-tools",+ "/workspace/a/b": "initialized-workspace-a-b",+ "/srv/data": "initialized-srv-data",+ "/workspace/tools/": "initialized-workspace-tools",+ }+ for path, want := range tests {+ if got := workspace.MarkerName(path); got != want {+ t.Errorf("MarkerName(%q) = %q, want %q", path, got, want)+ }+ }+}diff --git a/manifests/README.md b/manifests/README.mddeleted file mode 100644index 1bd3291..0000000--- a/manifests/README.md+++ /dev/null@@ -1,193 +0,0 @@-# AX Harness Deployment on Kubernetes--> [!WARNING]->-> This path is experimental and incomplete: the manifests, scripts, and-> runtime behavior will change and may break without notice.--This directory contains Kubernetes manifests and configurations to deploy-and verify the AX on Kubernetes using Agent Substrate.--The target Kubernetes cluster is assumed to have-[Agent Substrate](https://github.com/agent-substrate/substrate) installed.-------## 🚀 Deploying to Agent Substrate--### 1. Build and Deploy--> [!NOTE]-> Do not manually edit `manifests/ax-deployment.yaml`. The installation script automatically injects your `${GEMINI_API_KEY}`, `${AX_SNAPSHOTS_BUCKET}`, and the built `${AX_IMAGE}`, `${AX_ANTIGRAVITY_IMAGE}`, and `${ATEOM_IMAGE}` references during deployment.--The installation script builds the required images and applies the resolved-manifests to your cluster:--- the **ax** image (the Go `ax` binary only), built from the `ax`- target of `cmd/ax/Dockerfile`; used by the ax-server and the Go interactions- harness,-- the **ax-antigravity** image (the Antigravity Python- sidecar: SDK, localharness, agent), built from the `antigravity` target of- `cmd/ax/Dockerfile`; used by the antigravity harness actor,-- the **ateom-gvisor** worker image, built with `ko` from the `go.mod` pinned- substrate module.--#### Build prerequisites--The ax-antigravity image bundles the antigravity SDK, installed from PyPI at-build time. Both images target the cluster's **linux/amd64**-nodes and are built with `--platform linux/amd64`.--You also need a container engine to build and push the ax images. The script-auto-detects one (preferring a **running** docker, then podman); force a choice-with `CONTAINER_ENGINE=docker` or `CONTAINER_ENGINE=podman`:--- **Docker** — Docker Desktop (macOS; cross-builds linux/amd64 via emulation) or- Docker Engine (Linux; native).-- **Podman** — on macOS, start a machine first with `podman machine init &&- podman machine start` (cross-builds linux/amd64 via emulation); on Linux it- runs natively (podman/buildah >= 4.0).--#### Registry authentication--`GOOGLE_CLOUD_PROJECT` sets `AX_IMAGE_REPO=gcr.io/$GOOGLE_CLOUD_PROJECT`. The deploy pushes three-images — the **ax** and **ax-antigravity** images (via your container engine) and-the **ateom** image (via `ko`) — and all authenticate through the gcloud-credential helper:--```bash-gcloud auth login # authenticate gcloud-gcloud auth configure-docker # set up the gcr.io credential helper-```--#### Deploy--The event log is stored in Postgres. By default ax-server connects to an-**existing** Postgres that you provide via the `AX_EVENTLOG_DSN` env var (bring your own database). Pass `--deploy-postgres` to also-create a **bundled** Postgres in-cluster instead (for testing).--```bash-export GOOGLE_CLOUD_PROJECT="ax-substrate" # Your GCP project ID-export GEMINI_API_KEY="your-api-key"-export AX_SNAPSHOTS_BUCKET="snapshot-substrate-test-$GOOGLE_CLOUD_PROJECT"--# Connect to your existing Postgres:-export AX_EVENTLOG_DSN="postgres://user:pass@host:5432/db?sslmode=require"-./manifests/install-ax.sh --deploy-ax-server--# Or deploy a bundled Postgres for testing:-./manifests/install-ax.sh --deploy-ax-server --deploy-postgres-```--The bundled Postgres uses an auto-generated password. To get its DSN:--```bash-kubectl get secret ax-eventlog-postgres -n ax -o go-template='{{.data.dsn | base64decode}}'-```--#### Vertex AI access for the Antigravity Interactions harness--> [!NOTE]-> You may skip this if you only use the default harness.--The Antigravity **Interactions** harness (`ax harness antigravity-interactions`,-ActorTemplate `ax-harness-interactions-template`) calls the Vertex AI GenAI API-and authenticates with the actor's Google Cloud credentials — unlike the default-Antigravity harness, which uses `GEMINI_API_KEY`.--The worker pods (WorkerPool `ax-harness-workerpool`, namespace `ax`) have no GSA-annotation, so with Workload Identity the actor authenticates **directly as the-Kubernetes ServiceAccount principal** `ax/default`. Grant that principal-`roles/aiplatform.user` on the project the harness reads from `GOOGLE_CLOUD_PROJECT`, or-Vertex calls fail with `PermissionDenied (403)`. IAM changes can take a minute or two to propagate.--```bash-PROJECT_NUMBER="$(gcloud projects describe "${GOOGLE_CLOUD_PROJECT}" --format='value(projectNumber)')"--gcloud projects add-iam-policy-binding "${GOOGLE_CLOUD_PROJECT}" \- --role=roles/aiplatform.user \- --member="principal://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${GOOGLE_CLOUD_PROJECT}.svc.id.goog/subject/ns/ax/sa/default" \- --condition=None-```--### 2. Port-Forward Services--```bash-# Port-forward the ax-server ReplicaSet-kubectl port-forward -n ax rs/ax-server 8494:8494-```--### 3. Test End-to-End--Run an execution targeting the port-forwarded server.--```bash-ax --server=localhost:8494 --input="hello, who are you?"-```--The server should respond with something like:-```text-Conversation: fb344a18-3720-4c4f-8a6e-2ce34db975b3--⏺ hello, who are you?--I am a helpful assistant. How can I help you today?-```-*The request is served by the antigravity harness actor running on Substrate.*--## 🧹 How to Uninstall--To remove the AX server and its components, run:--```bash-./manifests/install-ax.sh --delete-ax-server-```--> [!NOTE]-> The event-log database is preserved by default. If you want to-> delete everything including the data, after the command above, be careful and-> run:->-> ```bash-> kubectl delete namespace ax-> ```-------## 🛠️ Inspection & Diagnostics--Use the **`kubectl ate`** CLI tool to inspect the live states of-active actors and allocated standby worker pool instances:--```bash-kubectl ate get actors -a ax--kubectl ate get workers-```--List the pods running in the `ax` namespace:--```bash-# Add `-o wide` to see node/IP assignments, or `-w` to watch status changes.-kubectl get pods -n ax-```--## Substrate compatibility--AX pins [Agent Substrate](https://github.com/agent-substrate/substrate) in-`go.mod`, and the **ateom** worker image is built from that pinned version. The-cluster's substrate **CRDs and control plane** must be compatible with the-manifest AX applies.--When installing substrate, keep three things aligned: the ax `go.mod` pin = your-local substrate checkout = the cluster's installed substrate.--```bash-# Get AX's pinned substrate commit:-commit=$(go list -m -f '{{.Version}}' github.com/agent-substrate/substrate | sed 's/.*-//')-echo "$commit" # e.g. fe93d160a1df--# Check it out on a normal branch in your substrate clone (avoids a detached HEAD):-git -C <substrate> fetch origin-git -C <substrate> switch -C ax-pinned "$commit"-```diff --git a/manifests/ax-deployment.yaml b/manifests/ax-deployment.yamldeleted file mode 100644index 072682f..0000000--- a/manifests/ax-deployment.yaml+++ /dev/null@@ -1,164 +0,0 @@-# 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.--# TODO(jbd): This yaml will eventually become the ax-deployment.yaml.tmpl.--# ----------------------------------------------------------------------------# Namespaces-# ----------------------------------------------------------------------------# Namespace "ax" is reserved for built-in harnesses. Users who bring their own-# harness images should add their own namespaces.-apiVersion: v1-kind: Namespace-metadata:- name: ax-----# ----------------------------------------------------------------------------# Built-in harnesses-# ----------------------------------------------------------------------------apiVersion: ate.dev/v1alpha1-kind: WorkerPool-metadata:- name: ax-harness-workerpool- namespace: ax- labels:- workload: ax-harness-spec:- replicas: 5- ateomImage: ${ATEOM_IMAGE}-----apiVersion: ate.dev/v1alpha1-kind: ActorTemplate-metadata:- name: ax-harness-antigravity-template- namespace: ax-spec:- workerSelector:- matchLabels:- workload: ax-harness- pauseImage: "gcr.io/gke-release/pause@sha256:bcbd57ba5653580ec647b16d8163cdd1112df3609129b01f912a8032e48265da"- containers:- - name: "axantigravity"- image: ${AX_ANTIGRAVITY_IMAGE}- # Substrate ignores the image CMD/ENV/WORKDIR, so the harness command and- # environment are specified here. `ax harness antigravity` forks the- # Antigravity Python sidecar, which serves on port 80 because substrate- # DNATs workerPodIP:80.- command: ["/ax-app/ax", "harness", "antigravity",- "--host", "0.0.0.0", "--port", "80"]- env:- - name: GEMINI_API_KEY- value: "${GEMINI_API_KEY}"- - name: PYTHONPATH- value: "/ax-app:/ax-app/python"- - name: PYTHONUNBUFFERED- value: "1"- - name: SKILLS_DIR- value: "/ax/skills"- - name: AX_HARNESS_WORKDIR- value: "/workspace"- readyz:- httpGet:- path: /readyz- port: 8081- snapshotsConfig:- location: gs://${AX_SNAPSHOTS_BUCKET}/axantigravity/-----apiVersion: ate.dev/v1alpha1-kind: ActorTemplate-metadata:- name: ax-harness-interactions-template- namespace: ax-spec:- workerSelector:- matchLabels:- workload: ax-harness- pauseImage: "gcr.io/gke-release/pause@sha256:bcbd57ba5653580ec647b16d8163cdd1112df3609129b01f912a8032e48265da"- containers:- - name: "axinteractions"- image: ${AX_IMAGE}- # Substrate ignores the image CMD/ENV/WORKDIR, so the harness command and- # environment are specified here. `ax harness antigravity-interactions` runs- # the Go Interactions harness on port 80 because substrate DNATs workerPodIP:80.- command: ["/ax-app/ax", "harness", "antigravity-interactions",- "--host", "0.0.0.0", "--port", "80"]- env:- - name: GOOGLE_CLOUD_PROJECT- value: "${GOOGLE_CLOUD_PROJECT}"- - name: AX_HARNESS_WORKDIR- value: "/durable/workspace"- - name: AX_DURABLE_DIR- value: "/durable"- # Content of manifests/ax.yaml- - name: AX_CONFIG_CONTENT- value: "${AX_CONFIG_CONTENT}"- readyz:- httpGet:- path: /readyz- port: 8081- volumeMounts:- - name: durable- mountPath: /durable- volumes:- - name: durable- durableDir: {}- snapshotsConfig:- location: gs://${AX_SNAPSHOTS_BUCKET}/axinteractions/- onPause: Data- onCommit: Data------# ----------------------------------------------------------------------------# AX Server-# ----------------------------------------------------------------------------apiVersion: apps/v1-kind: ReplicaSet-metadata:- name: ax-server- namespace: ax- labels:- app: ax-server-spec:- replicas: 3- selector:- matchLabels:- app: ax-server- template:- metadata:- labels:- app: ax-server- spec:- containers:- - name: ax-server- image: ${AX_IMAGE}- command: ["/ax-app/ax", "serve", "--config", "/etc/ax/ax.yaml"]- ports:- - containerPort: 8494- env:- - name: GEMINI_API_KEY- value: "${GEMINI_API_KEY}"- - name: AX_SUBSTRATE- value: "1"- - name: AX_EVENTLOG_DSN- valueFrom:- secretKeyRef:- name: ax-eventlog-postgres- key: dsn- volumeMounts:- - name: ax-config- mountPath: /etc/ax- volumes:- - name: ax-config- configMap:- name: ax-server-configdiff --git a/manifests/ax-postgres.yaml b/manifests/ax-postgres.yamldeleted file mode 100644index ccf1fb1..0000000--- a/manifests/ax-postgres.yaml+++ /dev/null@@ -1,87 +0,0 @@-# 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.--# ----------------------------------------------------------------------------# Event log storage (PostgreSQL)-#-# Applied by manifests/install-ax.sh only when --deploy-postgres is passed. By default-# ax-server connects to an existing Postgres via AX_EVENTLOG_DSN and these-# resources are not deployed. The ax-eventlog-postgres Secret (holding the-# password used below and the DSN) is created by install-ax.sh.-# ----------------------------------------------------------------------------apiVersion: v1-kind: Service-metadata:- name: ax-eventlog-postgres- namespace: ax- labels:- app: ax-eventlog-postgres-spec:- selector:- app: ax-eventlog-postgres- ports:- - port: 5432- targetPort: 5432-----apiVersion: apps/v1-kind: StatefulSet-metadata:- name: ax-eventlog-postgres- namespace: ax- labels:- app: ax-eventlog-postgres-spec:- serviceName: ax-eventlog-postgres- replicas: 1- selector:- matchLabels:- app: ax-eventlog-postgres- template:- metadata:- labels:- app: ax-eventlog-postgres- spec:- containers:- - name: postgres- image: postgres:16- ports:- - containerPort: 5432- env:- - name: POSTGRES_DB- value: axeventlog- - name: POSTGRES_USER- value: axuser- - name: POSTGRES_PASSWORD- valueFrom:- secretKeyRef:- name: ax-eventlog-postgres- key: password- - name: PGDATA- value: /var/lib/postgresql/data/pgdata- volumeMounts:- - name: data- mountPath: /var/lib/postgresql/data- readinessProbe:- exec:- command: ["pg_isready", "-U", "axuser", "-d", "axeventlog"]- initialDelaySeconds: 5- periodSeconds: 5- volumeClaimTemplates:- - metadata:- name: data- spec:- accessModes: ["ReadWriteOnce"]- resources:- requests:- storage: 10Gidiff --git a/manifests/ax.yaml b/manifests/ax.yamldeleted file mode 100644index b40a838..0000000--- a/manifests/ax.yaml+++ /dev/null@@ -1,30 +0,0 @@-# 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.--# Deploy configuration for AX on Agent Substrate. install-ax.sh renders this-# single source into two places:-# - the ax-server-config ConfigMap (mounted at /etc/ax/ax.yaml), read by the-# controller (`ax serve`); and-# - the AX_CONFIG_CONTENT env (base64 of this file) on each ActorTemplate,-# so a substrate actor can read its config.-version: v1alpha--eventlog:- postgres:- dsn: ${AX_EVENTLOG_DSN}--antigravity: {}--registry:- antigravity-interactions: {}diff --git a/manifests/install-ax.sh b/manifests/install-ax.shdeleted file mode 100755index 82ebde8..0000000--- a/manifests/install-ax.sh+++ /dev/null@@ -1,371 +0,0 @@-#!/bin/bash-# 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.--set -e-set -u-set -o pipefail--ROOT=$(git rev-parse --show-toplevel)-cd "${ROOT}"--if [[ -n "${GOOGLE_CLOUD_PROJECT:-}" ]]; then- export AX_IMAGE_REPO="gcr.io/${GOOGLE_CLOUD_PROJECT}"- echo "Using AX_IMAGE_REPO: ${AX_IMAGE_REPO}" >&2-fi--export KO_DEFAULTPLATFORMS="${KO_DEFAULTPLATFORMS:-linux/amd64}"--# ANSI color codes for prettier output-COLOR_CYAN='\033[1;36m'-COLOR_RESET='\033[0m'--function log_step() {- local step_name="$1"- echo -e "${COLOR_CYAN}[step]: ${step_name}${COLOR_RESET}"-}--# wait_with_spinner runs a blocking command while showing a simple spinner on an-# interactive terminal, then reports "done"/"failed" and returns the command's-# exit status.-wait_with_spinner() {- local msg="$1"; shift- if [[ ! -t 2 ]]; then- "$@"- return $?- fi-- local out; out="$(mktemp)"- "$@" >"${out}" 2>&1 &- local pid=$! frames='|/-\' i=0- while kill -0 "${pid}" 2>/dev/null; do- i=$(( (i + 1) % ${#frames} ))- printf '\r%s %s' "${frames:${i}:1}" "${msg}" >&2- sleep 0.1- done-- local status=0- wait "${pid}" || status=$?- if [[ "${status}" -eq 0 ]]; then- printf '\r\033[K%s... done\n' "${msg}" >&2- else- printf '\r\033[K%s... failed\n' "${msg}" >&2- cat "${out}" >&2- fi- rm -f "${out}"- return "${status}"-}--function usage() {- echo "Usage: $0 [options]"- echo ""- echo "Options:"- echo " --deploy-ax-server Build images and deploy AX server and components"- echo " --delete-ax-server Delete AX server and components, preserving the event-log database"- echo " --deploy-postgres With --deploy-ax-server: also deploy a bundled Postgres for testing (default: connect to an existing Postgres via AX_EVENTLOG_DSN)"- echo " -h, --help Show this help message"-}--run_kubectl() {- kubectl \- ${KUBECTL_CONTEXT:+--context=${KUBECTL_CONTEXT}} \- "$@"-}--# detect_container_engine selects the OCI build/push tool when CONTAINER_ENGINE-# is not set explicitly. It prefers a *working* docker (daemon reachable), then a-# working podman, so a docker CLI installed without a running daemon does not-# shadow a working podman. As a last resort it picks whichever CLI exists so the-# build step can surface an actionable daemon error.-detect_container_engine() {- if [[ -n "${CONTAINER_ENGINE:-}" ]]; then- return # Respect an explicit override; do not second-guess it.- fi- if docker info >/dev/null 2>&1; then- CONTAINER_ENGINE=docker- elif podman info >/dev/null 2>&1; then- CONTAINER_ENGINE=podman- elif command -v docker >/dev/null 2>&1; then- CONTAINER_ENGINE=docker- elif command -v podman >/dev/null 2>&1; then- CONTAINER_ENGINE=podman- else- CONTAINER_ENGINE=docker- fi-}--# _build_and_push_ax builds one target of cmd/ax/Dockerfile into ${repo}:<git-sha>,-# pushes it, and echoes the digest-pinned reference on stdout. Args:-# $1 repo - fully-qualified image repo (e.g. gcr.io/proj/ax)-# $2 target - Dockerfile target stage (ax | antigravity)-# Requires AX_IMAGE_REPO and a container engine.-_build_and_push_ax() {- local repo="$1" target="$2"- if [[ -z "${AX_IMAGE_REPO:-}" ]]; then- echo "Error: AX_IMAGE_REPO environment variable must be set" >&2- exit 1- fi- detect_container_engine- if ! command -v "${CONTAINER_ENGINE}" >/dev/null 2>&1; then- echo "Error: container engine '${CONTAINER_ENGINE}' not found in PATH." >&2- echo "Install it or set CONTAINER_ENGINE to an available builder." >&2- exit 1- fi-- local tag image digest- tag="$(git rev-parse --short HEAD)"- image="${repo}:${tag}"-- log_step "build ${target} -> ${image}" >&2- "${CONTAINER_ENGINE}" build \- --platform linux/amd64 \- --target "${target}" \- -f cmd/ax/Dockerfile \- -t "${image}" \- . 2>&1 \- | awk '{ sub(/^\[[0-9]+\/[0-9]+\] /, ""); print; fflush() }' >&2-- # Push the readable tag, then resolve the pushed manifest digest so the- # ActorTemplate can reference the image by digest (snapshot-safe).- if [[ "${CONTAINER_ENGINE}" == *podman* ]]; then- local digestfile- digestfile="$(mktemp)"- "${CONTAINER_ENGINE}" push --digestfile="${digestfile}" "${image}" >&2- digest="$(cat "${digestfile}")"- rm -f "${digestfile}"- else- "${CONTAINER_ENGINE}" push "${image}" >&2- local repo_digest- repo_digest="$("${CONTAINER_ENGINE}" image inspect --format '{{index .RepoDigests 0}}' "${image}")"- digest="${repo_digest##*@}"- fi-- if [[ "${digest}" != sha256:* ]]; then- echo "Error: could not resolve a sha256 digest for ${image} (got '${digest}')." >&2- exit 1- fi-- echo "${repo}@${digest}"-}--# build_ax_image builds and pushes the Go-only ax image used by the ax-server and the-# Go interactions harness.-build_ax_image() {- _build_and_push_ax "${AX_IMAGE_REPO}/ax" ax-}--# build_ax_antigravity_image builds and pushes the antigravity image used by the-# antigravity harness.-build_ax_antigravity_image() {- _build_and_push_ax "${AX_IMAGE_REPO}/ax-antigravity" antigravity-}--build_ateom_image() {- if [[ -n "${ATEOM_IMAGE:-}" ]]; then- echo "${ATEOM_IMAGE}"- return- fi- if [[ -z "${AX_IMAGE_REPO:-}" ]]; then- echo "Error: AX_IMAGE_REPO environment variable must be set" >&2- exit 1- fi-- # Resolve the substrate source for the version AX is pinned to in go.mod.- go mod download github.com/agent-substrate/substrate- local sub_dir ateom_ref- sub_dir="$(go list -m -f '{{.Dir}}' github.com/agent-substrate/substrate)"- if [[ -z "${sub_dir}" ]]; then- echo "Error: could not locate the substrate module (go list -m)." >&2- exit 1- fi-- log_step "build_ateom_image (from ${sub_dir})" >&2- ateom_ref="$(cd "${sub_dir}" && KO_DOCKER_REPO="${AX_IMAGE_REPO}" GOFLAGS="" ko build --platform=linux/amd64 -B ./cmd/ateom-gvisor)"-- if [[ "${ateom_ref}" != *@sha256:* ]]; then- echo "Error: ko did not return a digest-pinned ateom image (got '${ateom_ref}')." >&2- exit 1- fi- echo "${ateom_ref}"-}--deploy_ax_server() {- log_step "deploy_ax_server"-- # Check dependencies- if [[ -z "${GEMINI_API_KEY:-}" ]]; then- echo "Error: GEMINI_API_KEY environment variable must be set" >&2- exit 1- fi- if [[ -z "${AX_SNAPSHOTS_BUCKET:-}" ]]; then- echo "Error: AX_SNAPSHOTS_BUCKET environment variable must be set" >&2- exit 1- fi- # The default (external Postgres) path needs a DSN; fail fast before building.- if [[ "${DEPLOY_POSTGRES}" != "true" && -z "${AX_EVENTLOG_DSN:-}" ]]; then- echo "Error: AX_EVENTLOG_DSN must be set to your Postgres DSN, or pass --deploy-postgres to deploy a bundled test Postgres." >&2- exit 1- fi-- echo "Using GCS Bucket: ${AX_SNAPSHOTS_BUCKET}"-- # Build and push the images, capturing their digest-pinned references.- local ax_image ax_antigravity_image ateom_image- ax_image=$(build_ax_image)- ax_antigravity_image=$(build_ax_antigravity_image)- ateom_image=$(build_ateom_image)-- # Resolve the event-log Postgres DSN. By default ax-server connects to an- # existing Postgres via AX_EVENTLOG_DSN; --deploy-postgres creates a bundled- # Postgres in-cluster (for testing) and derives the DSN from it.- local pg_dsn pg_password=""- if [[ "${DEPLOY_POSTGRES}" == "true" ]]; then- # Reuse the existing bundled-Postgres password if present, else POSTGRES_PASSWORD,- # else generate one.- local existing_pw- existing_pw="$(run_kubectl -n ax get secret ax-eventlog-postgres -o go-template='{{.data.password | base64decode}}' 2>/dev/null || true)"- if [[ -n "${existing_pw}" ]]; then- pg_password="${existing_pw}"- else- pg_password="${POSTGRES_PASSWORD:-$(openssl rand -hex 16)}"- fi- pg_dsn="postgres://axuser:${pg_password}@ax-eventlog-postgres.ax.svc:5432/axeventlog?sslmode=disable"- else- pg_dsn="${AX_EVENTLOG_DSN}"- echo "Using existing Postgres via AX_EVENTLOG_DSN." >&2- fi-- # Base64 of the single-source config file (manifests/ax.yaml), injected into- # each ActorTemplate's AX_CONFIG_CONTENT env so substrate actors read their config- # without a mounted ConfigMap.- local ax_config_content- ax_config_content="$(base64 < manifests/ax.yaml | tr -d '\n')"-- # Common substitutions applied to every rendered manifest.- local render_sed=(- -e "s|\${GEMINI_API_KEY}|${GEMINI_API_KEY}|g"- -e "s|\${AX_SNAPSHOTS_BUCKET}|${AX_SNAPSHOTS_BUCKET}|g"- -e "s|\${AX_IMAGE}|${ax_image}|g"- -e "s|\${AX_ANTIGRAVITY_IMAGE}|${ax_antigravity_image}|g"- -e "s|\${ATEOM_IMAGE}|${ateom_image}|g"- -e "s|\${GOOGLE_CLOUD_PROJECT}|${GOOGLE_CLOUD_PROJECT:-}|g"- -e "s|\${AX_CONFIG_CONTENT}|${ax_config_content}|g"- )-- # Render and apply the core manifest (namespace, harnesses, ax-server).- if ! sed "${render_sed[@]}" manifests/ax-deployment.yaml | run_kubectl apply -f -; then- echo >&2- echo "Error: cluster rejected the manifest. An \"unknown field\" error usually means the" >&2- echo "cluster's substrate is incompatible with AX's go.mod pin — see" >&2- echo "manifests/README.md (\"Substrate compatibility\")." >&2- exit 1- fi-- # Create/update the controller ConfigMap from the single-source config file- # (manifests/ax.yaml) -- the same file that seeds the actors' AX_CONFIG_CONTENT.- # ax-server mounts it at /etc/ax/ax.yaml.- run_kubectl -n ax create configmap ax-server-config \- --from-file=ax.yaml=manifests/ax.yaml \- --dry-run=client -o yaml | run_kubectl apply -f --- # Create/update the event-log Secret with the DSN (and, for the bundled Postgres,- # its password). ax-server reads AX_EVENTLOG_DSN from this Secret's dsn key.- local secret_args=(--from-literal=dsn="${pg_dsn}")- if [[ "${DEPLOY_POSTGRES}" == "true" ]]; then- secret_args+=(--from-literal=password="${pg_password}")- fi- run_kubectl -n ax create secret generic ax-eventlog-postgres "${secret_args[@]}" \- --dry-run=client -o yaml | run_kubectl apply -f --- # With --deploy-postgres, create the bundled Postgres and wait for it to be- # ready before ax-server relies on it.- if [[ "${DEPLOY_POSTGRES}" == "true" ]]; then- run_kubectl apply -f manifests/ax-postgres.yaml- log_step "wait for statefulset/ax-eventlog-postgres to be ready"- wait_with_spinner "waiting for postgres (timeout ${AX_WAIT_TIMEOUT:-5m})" \- run_kubectl -n ax rollout status statefulset/ax-eventlog-postgres \- --timeout="${AX_WAIT_TIMEOUT:-5m}"- fi-- # Wait for the antigravity ActorTemplate's golden snapshot to be ready.- log_step "wait for actortemplate/ax-harness-antigravity-template to be Ready"- wait_with_spinner "waiting for antigravity golden snapshot (timeout ${AX_WAIT_TIMEOUT:-5m})" \- run_kubectl wait --for=condition=Ready actortemplate/ax-harness-antigravity-template \- -n ax --timeout="${AX_WAIT_TIMEOUT:-5m}"-- # Wait for the interactions ActorTemplate's golden snapshot to be ready.- log_step "wait for actortemplate/ax-harness-interactions-template to be Ready"- wait_with_spinner "waiting for interactions golden snapshot (timeout ${AX_WAIT_TIMEOUT:-5m})" \- run_kubectl wait --for=condition=Ready actortemplate/ax-harness-interactions-template \- -n ax --timeout="${AX_WAIT_TIMEOUT:-5m}"-- echo ""- echo "Forward the AX server by running the following command (optional)"- echo "kubectl port-forward -n ax rs/ax-server 8494:8494"- echo ""- echo "Then, run: ax --server localhost:8494 [--agent antigravity|antigravity-interactions]"-}--# delete_ax_server removes the AX server and harness resources but preserves the-# event-log database: it leaves the namespace and the Postgres subsystem-# (Service/Secret/StatefulSet and its PVC) intact so a later redeploy reuses the-# existing data.-delete_ax_server() {- log_step "delete_ax_server"-- run_kubectl -n ax delete --ignore-not-found \- replicaset/ax-server \- configmap/ax-server-config \- actortemplate/ax-harness-antigravity-template \- actortemplate/ax-harness-interactions-template \- workerpool/ax-harness-workerpool-}--if [ "$#" -eq 0 ]; then- usage- exit 1-fi--# Event-log Postgres: by default ax-server connects to an existing Postgres via-# the AX_EVENTLOG_DSN env var. --deploy-postgres additionally creates a bundled-# Postgres in-cluster (for testing on Substrate).-DEPLOY_POSTGRES=false--# If -h or --help appears anywhere in the command line, print the usage and exit.-for arg in "$@"; do- case "$arg" in- -h|--help)- usage- exit 0- ;;- --deploy-postgres)- DEPLOY_POSTGRES=true- ;;- esac-done--while [[ "$#" -gt 0 ]]; do- case $1 in- --deploy-ax-server) deploy_ax_server ;;- --delete-ax-server) delete_ax_server ;;- --deploy-postgres) ;; # resolved in the pre-scan above- *)- echo "Error: unknown option: $1" >&2- echo ""- usage- exit 1- ;;- esac- shift-donediff --git a/pkg/apis/v1alpha1/ax.pb.go b/pkg/apis/v1alpha1/ax.pb.gonew file mode 100644index 0000000..b1adb26--- /dev/null+++ b/pkg/apis/v1alpha1/ax.pb.go@@ -0,0 +1,3580 @@+// 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.++// Code generated by protoc-gen-go. DO NOT EDIT.+// versions:+// protoc-gen-go v1.36.11+// protoc v7.34.1+// source: pkg/apis/v1alpha1/ax.proto++package v1alpha1++import (+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"+ structpb "google.golang.org/protobuf/types/known/structpb"+ timestamppb "google.golang.org/protobuf/types/known/timestamppb"+ reflect "reflect"+ sync "sync"+ unsafe "unsafe"+)++const (+ // Verify that this generated code is sufficiently up-to-date.+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)+ // Verify that runtime/protoimpl is sufficiently up-to-date.+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)+)++// ObjectMeta is metadata for AX resources.+type ObjectMeta struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`+ Atespace string `protobuf:"bytes,2,opt,name=atespace,proto3" json:"atespace,omitempty"`+ CreationTimestamp *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=creation_timestamp,json=creationTimestamp,proto3" json:"creation_timestamp,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ObjectMeta) Reset() {+ *x = ObjectMeta{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[0]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ObjectMeta) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ObjectMeta) ProtoMessage() {}++func (x *ObjectMeta) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[0]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ObjectMeta.ProtoReflect.Descriptor instead.+func (*ObjectMeta) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{0}+}++func (x *ObjectMeta) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *ObjectMeta) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *ObjectMeta) GetCreationTimestamp() *timestamppb.Timestamp {+ if x != nil {+ return x.CreationTimestamp+ }+ return nil+}++type Task struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ApiVersion string `protobuf:"bytes,1,opt,name=api_version,json=apiVersion,proto3" json:"api_version,omitempty"`+ Kind string `protobuf:"bytes,2,opt,name=kind,proto3" json:"kind,omitempty"`+ Metadata *ObjectMeta `protobuf:"bytes,3,opt,name=metadata,proto3" json:"metadata,omitempty"`+ Spec *TaskSpec `protobuf:"bytes,4,opt,name=spec,proto3" json:"spec,omitempty"`+ Status *TaskStatus `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Task) Reset() {+ *x = Task{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[1]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Task) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Task) ProtoMessage() {}++func (x *Task) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[1]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Task.ProtoReflect.Descriptor instead.+func (*Task) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{1}+}++func (x *Task) GetApiVersion() string {+ if x != nil {+ return x.ApiVersion+ }+ return ""+}++func (x *Task) GetKind() string {+ if x != nil {+ return x.Kind+ }+ return ""+}++func (x *Task) GetMetadata() *ObjectMeta {+ if x != nil {+ return x.Metadata+ }+ return nil+}++func (x *Task) GetSpec() *TaskSpec {+ if x != nil {+ return x.Spec+ }+ return nil+}++func (x *Task) GetStatus() *TaskStatus {+ if x != nil {+ return x.Status+ }+ return nil+}++type TaskSpec struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Suspend bool `protobuf:"varint,2,opt,name=suspend,proto3" json:"suspend,omitempty"`+ Image string `protobuf:"bytes,3,opt,name=image,proto3" json:"image,omitempty"`+ Command []string `protobuf:"bytes,4,rep,name=command,proto3" json:"command,omitempty"`+ Env []*EnvVar `protobuf:"bytes,5,rep,name=env,proto3" json:"env,omitempty"`+ Resources *ResourceReqs `protobuf:"bytes,6,opt,name=resources,proto3" json:"resources,omitempty"`+ // workspaces binds one or more Workspaces, each mounted at its own path+ // under /workspace. The first entry is the task command's working directory.+ Workspaces []*WorkspaceRef `protobuf:"bytes,7,rep,name=workspaces,proto3" json:"workspaces,omitempty"`+ Gateway *GatewayRef `protobuf:"bytes,8,opt,name=gateway,proto3" json:"gateway,omitempty"`+ // debug enables the in-container guest services (process execution and file+ // access) that back `ax ssh`. Off by default.+ Debug bool `protobuf:"varint,10,opt,name=debug,proto3" json:"debug,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *TaskSpec) Reset() {+ *x = TaskSpec{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[2]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *TaskSpec) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*TaskSpec) ProtoMessage() {}++func (x *TaskSpec) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[2]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use TaskSpec.ProtoReflect.Descriptor instead.+func (*TaskSpec) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{2}+}++func (x *TaskSpec) GetSuspend() bool {+ if x != nil {+ return x.Suspend+ }+ return false+}++func (x *TaskSpec) GetImage() string {+ if x != nil {+ return x.Image+ }+ return ""+}++func (x *TaskSpec) GetCommand() []string {+ if x != nil {+ return x.Command+ }+ return nil+}++func (x *TaskSpec) GetEnv() []*EnvVar {+ if x != nil {+ return x.Env+ }+ return nil+}++func (x *TaskSpec) GetResources() *ResourceReqs {+ if x != nil {+ return x.Resources+ }+ return nil+}++func (x *TaskSpec) GetWorkspaces() []*WorkspaceRef {+ if x != nil {+ return x.Workspaces+ }+ return nil+}++func (x *TaskSpec) GetGateway() *GatewayRef {+ if x != nil {+ return x.Gateway+ }+ return nil+}++func (x *TaskSpec) GetDebug() bool {+ if x != nil {+ return x.Debug+ }+ return false+}++type EnvVar struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`+ Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *EnvVar) Reset() {+ *x = EnvVar{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[3]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *EnvVar) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*EnvVar) ProtoMessage() {}++func (x *EnvVar) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[3]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use EnvVar.ProtoReflect.Descriptor instead.+func (*EnvVar) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{3}+}++func (x *EnvVar) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *EnvVar) GetValue() string {+ if x != nil {+ return x.Value+ }+ return ""+}++type ResourceReqs struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Requests *ResourceList `protobuf:"bytes,1,opt,name=requests,proto3" json:"requests,omitempty"`+ Limits *ResourceList `protobuf:"bytes,2,opt,name=limits,proto3" json:"limits,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ResourceReqs) Reset() {+ *x = ResourceReqs{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[4]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ResourceReqs) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ResourceReqs) ProtoMessage() {}++func (x *ResourceReqs) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[4]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ResourceReqs.ProtoReflect.Descriptor instead.+func (*ResourceReqs) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{4}+}++func (x *ResourceReqs) GetRequests() *ResourceList {+ if x != nil {+ return x.Requests+ }+ return nil+}++func (x *ResourceReqs) GetLimits() *ResourceList {+ if x != nil {+ return x.Limits+ }+ return nil+}++type ResourceList struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Cpu string `protobuf:"bytes,1,opt,name=cpu,proto3" json:"cpu,omitempty"`+ Memory string `protobuf:"bytes,2,opt,name=memory,proto3" json:"memory,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ResourceList) Reset() {+ *x = ResourceList{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[5]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ResourceList) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ResourceList) ProtoMessage() {}++func (x *ResourceList) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[5]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ResourceList.ProtoReflect.Descriptor instead.+func (*ResourceList) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{5}+}++func (x *ResourceList) GetCpu() string {+ if x != nil {+ return x.Cpu+ }+ return ""+}++func (x *ResourceList) GetMemory() string {+ if x != nil {+ return x.Memory+ }+ return ""+}++type WorkspaceRef struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`+ Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`+ Goal string `protobuf:"bytes,3,opt,name=goal,proto3" json:"goal,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *WorkspaceRef) Reset() {+ *x = WorkspaceRef{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[6]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *WorkspaceRef) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*WorkspaceRef) ProtoMessage() {}++func (x *WorkspaceRef) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[6]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use WorkspaceRef.ProtoReflect.Descriptor instead.+func (*WorkspaceRef) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{6}+}++func (x *WorkspaceRef) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *WorkspaceRef) GetPath() string {+ if x != nil {+ return x.Path+ }+ return ""+}++func (x *WorkspaceRef) GetGoal() string {+ if x != nil {+ return x.Goal+ }+ return ""+}++type GatewayRef struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *GatewayRef) Reset() {+ *x = GatewayRef{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[7]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *GatewayRef) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*GatewayRef) ProtoMessage() {}++func (x *GatewayRef) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[7]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use GatewayRef.ProtoReflect.Descriptor instead.+func (*GatewayRef) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{7}+}++func (x *GatewayRef) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type TaskStatus struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Phase string `protobuf:"bytes,1,opt,name=phase,proto3" json:"phase,omitempty"`+ Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"`+ Actor string `protobuf:"bytes,3,opt,name=actor,proto3" json:"actor,omitempty"`+ // json_name keeps the established `workerIP` spelling in YAML and JSON.+ WorkerIp string `protobuf:"bytes,4,opt,name=worker_ip,json=workerIP,proto3" json:"worker_ip,omitempty"`+ PendingApproval *PendingApproval `protobuf:"bytes,5,opt,name=pending_approval,json=pendingApproval,proto3" json:"pending_approval,omitempty"`+ Usage *UsageStats `protobuf:"bytes,6,opt,name=usage,proto3" json:"usage,omitempty"`+ Conditions []*Condition `protobuf:"bytes,7,rep,name=conditions,proto3" json:"conditions,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *TaskStatus) Reset() {+ *x = TaskStatus{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[8]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *TaskStatus) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*TaskStatus) ProtoMessage() {}++func (x *TaskStatus) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[8]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use TaskStatus.ProtoReflect.Descriptor instead.+func (*TaskStatus) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{8}+}++func (x *TaskStatus) GetPhase() string {+ if x != nil {+ return x.Phase+ }+ return ""+}++func (x *TaskStatus) GetId() string {+ if x != nil {+ return x.Id+ }+ return ""+}++func (x *TaskStatus) GetActor() string {+ if x != nil {+ return x.Actor+ }+ return ""+}++func (x *TaskStatus) GetWorkerIp() string {+ if x != nil {+ return x.WorkerIp+ }+ return ""+}++func (x *TaskStatus) GetPendingApproval() *PendingApproval {+ if x != nil {+ return x.PendingApproval+ }+ return nil+}++func (x *TaskStatus) GetUsage() *UsageStats {+ if x != nil {+ return x.Usage+ }+ return nil+}++func (x *TaskStatus) GetConditions() []*Condition {+ if x != nil {+ return x.Conditions+ }+ return nil+}++type PendingApproval struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`+ Action string `protobuf:"bytes,2,opt,name=action,proto3" json:"action,omitempty"`+ RequestedAt *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=requested_at,json=requestedAt,proto3" json:"requested_at,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PendingApproval) Reset() {+ *x = PendingApproval{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[9]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PendingApproval) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PendingApproval) ProtoMessage() {}++func (x *PendingApproval) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[9]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PendingApproval.ProtoReflect.Descriptor instead.+func (*PendingApproval) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{9}+}++func (x *PendingApproval) GetId() string {+ if x != nil {+ return x.Id+ }+ return ""+}++func (x *PendingApproval) GetAction() string {+ if x != nil {+ return x.Action+ }+ return ""+}++func (x *PendingApproval) GetRequestedAt() *timestamppb.Timestamp {+ if x != nil {+ return x.RequestedAt+ }+ return nil+}++type UsageStats struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ PromptTokens int32 `protobuf:"varint,1,opt,name=prompt_tokens,json=promptTokens,proto3" json:"prompt_tokens,omitempty"`+ CompletionTokens int32 `protobuf:"varint,2,opt,name=completion_tokens,json=completionTokens,proto3" json:"completion_tokens,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *UsageStats) Reset() {+ *x = UsageStats{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[10]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *UsageStats) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*UsageStats) ProtoMessage() {}++func (x *UsageStats) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[10]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use UsageStats.ProtoReflect.Descriptor instead.+func (*UsageStats) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{10}+}++func (x *UsageStats) GetPromptTokens() int32 {+ if x != nil {+ return x.PromptTokens+ }+ return 0+}++func (x *UsageStats) GetCompletionTokens() int32 {+ if x != nil {+ return x.CompletionTokens+ }+ return 0+}++type Condition struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`+ Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"`+ LastTransitionTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=last_transition_time,json=lastTransitionTime,proto3" json:"last_transition_time,omitempty"`+ Reason string `protobuf:"bytes,4,opt,name=reason,proto3" json:"reason,omitempty"`+ Message string `protobuf:"bytes,5,opt,name=message,proto3" json:"message,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Condition) Reset() {+ *x = Condition{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[11]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Condition) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Condition) ProtoMessage() {}++func (x *Condition) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[11]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Condition.ProtoReflect.Descriptor instead.+func (*Condition) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{11}+}++func (x *Condition) GetType() string {+ if x != nil {+ return x.Type+ }+ return ""+}++func (x *Condition) GetStatus() string {+ if x != nil {+ return x.Status+ }+ return ""+}++func (x *Condition) GetLastTransitionTime() *timestamppb.Timestamp {+ if x != nil {+ return x.LastTransitionTime+ }+ return nil+}++func (x *Condition) GetReason() string {+ if x != nil {+ return x.Reason+ }+ return ""+}++func (x *Condition) GetMessage() string {+ if x != nil {+ return x.Message+ }+ return ""+}++type Gateway struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ApiVersion string `protobuf:"bytes,1,opt,name=api_version,json=apiVersion,proto3" json:"api_version,omitempty"`+ Kind string `protobuf:"bytes,2,opt,name=kind,proto3" json:"kind,omitempty"`+ Metadata *ObjectMeta `protobuf:"bytes,3,opt,name=metadata,proto3" json:"metadata,omitempty"`+ Spec *GatewaySpec `protobuf:"bytes,4,opt,name=spec,proto3" json:"spec,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Gateway) Reset() {+ *x = Gateway{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[12]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Gateway) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Gateway) ProtoMessage() {}++func (x *Gateway) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[12]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Gateway.ProtoReflect.Descriptor instead.+func (*Gateway) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{12}+}++func (x *Gateway) GetApiVersion() string {+ if x != nil {+ return x.ApiVersion+ }+ return ""+}++func (x *Gateway) GetKind() string {+ if x != nil {+ return x.Kind+ }+ return ""+}++func (x *Gateway) GetMetadata() *ObjectMeta {+ if x != nil {+ return x.Metadata+ }+ return nil+}++func (x *Gateway) GetSpec() *GatewaySpec {+ if x != nil {+ return x.Spec+ }+ return nil+}++type GatewaySpec struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Listeners []*Listener `protobuf:"bytes,1,rep,name=listeners,proto3" json:"listeners,omitempty"`+ Egress *EgressConfig `protobuf:"bytes,2,opt,name=egress,proto3" json:"egress,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *GatewaySpec) Reset() {+ *x = GatewaySpec{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[13]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *GatewaySpec) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*GatewaySpec) ProtoMessage() {}++func (x *GatewaySpec) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[13]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use GatewaySpec.ProtoReflect.Descriptor instead.+func (*GatewaySpec) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{13}+}++func (x *GatewaySpec) GetListeners() []*Listener {+ if x != nil {+ return x.Listeners+ }+ return nil+}++func (x *GatewaySpec) GetEgress() *EgressConfig {+ if x != nil {+ return x.Egress+ }+ return nil+}++type Listener struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`+ Port int32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"`+ Protocol string `protobuf:"bytes,3,opt,name=protocol,proto3" json:"protocol,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Listener) Reset() {+ *x = Listener{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[14]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Listener) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Listener) ProtoMessage() {}++func (x *Listener) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[14]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Listener.ProtoReflect.Descriptor instead.+func (*Listener) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{14}+}++func (x *Listener) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *Listener) GetPort() int32 {+ if x != nil {+ return x.Port+ }+ return 0+}++func (x *Listener) GetProtocol() string {+ if x != nil {+ return x.Protocol+ }+ return ""+}++type EgressConfig struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Allowlist *EgressAllowlist `protobuf:"bytes,1,opt,name=allowlist,proto3" json:"allowlist,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *EgressConfig) Reset() {+ *x = EgressConfig{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[15]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *EgressConfig) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*EgressConfig) ProtoMessage() {}++func (x *EgressConfig) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[15]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use EgressConfig.ProtoReflect.Descriptor instead.+func (*EgressConfig) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{15}+}++func (x *EgressConfig) GetAllowlist() *EgressAllowlist {+ if x != nil {+ return x.Allowlist+ }+ return nil+}++type EgressAllowlist struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Hosts []*HostRule `protobuf:"bytes,1,rep,name=hosts,proto3" json:"hosts,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *EgressAllowlist) Reset() {+ *x = EgressAllowlist{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[16]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *EgressAllowlist) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*EgressAllowlist) ProtoMessage() {}++func (x *EgressAllowlist) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[16]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use EgressAllowlist.ProtoReflect.Descriptor instead.+func (*EgressAllowlist) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{16}+}++func (x *EgressAllowlist) GetHosts() []*HostRule {+ if x != nil {+ return x.Hosts+ }+ return nil+}++type HostRule struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"`+ Port int32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *HostRule) Reset() {+ *x = HostRule{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[17]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *HostRule) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*HostRule) ProtoMessage() {}++func (x *HostRule) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[17]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use HostRule.ProtoReflect.Descriptor instead.+func (*HostRule) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{17}+}++func (x *HostRule) GetHost() string {+ if x != nil {+ return x.Host+ }+ return ""+}++func (x *HostRule) GetPort() int32 {+ if x != nil {+ return x.Port+ }+ return 0+}++type Workspace struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ApiVersion string `protobuf:"bytes,1,opt,name=api_version,json=apiVersion,proto3" json:"api_version,omitempty"`+ Kind string `protobuf:"bytes,2,opt,name=kind,proto3" json:"kind,omitempty"`+ Metadata *ObjectMeta `protobuf:"bytes,3,opt,name=metadata,proto3" json:"metadata,omitempty"`+ Spec *WorkspaceSpec `protobuf:"bytes,4,opt,name=spec,proto3" json:"spec,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Workspace) Reset() {+ *x = Workspace{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[18]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Workspace) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Workspace) ProtoMessage() {}++func (x *Workspace) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[18]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Workspace.ProtoReflect.Descriptor instead.+func (*Workspace) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{18}+}++func (x *Workspace) GetApiVersion() string {+ if x != nil {+ return x.ApiVersion+ }+ return ""+}++func (x *Workspace) GetKind() string {+ if x != nil {+ return x.Kind+ }+ return ""+}++func (x *Workspace) GetMetadata() *ObjectMeta {+ if x != nil {+ return x.Metadata+ }+ return nil+}++func (x *Workspace) GetSpec() *WorkspaceSpec {+ if x != nil {+ return x.Spec+ }+ return nil+}++type WorkspaceSpec struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Git []*GitRepo `protobuf:"bytes,1,rep,name=git,proto3" json:"git,omitempty"`+ Mcp *MCPConfig `protobuf:"bytes,2,opt,name=mcp,proto3" json:"mcp,omitempty"`+ Skills *SkillsConfig `protobuf:"bytes,3,opt,name=skills,proto3" json:"skills,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *WorkspaceSpec) Reset() {+ *x = WorkspaceSpec{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[19]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *WorkspaceSpec) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*WorkspaceSpec) ProtoMessage() {}++func (x *WorkspaceSpec) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[19]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use WorkspaceSpec.ProtoReflect.Descriptor instead.+func (*WorkspaceSpec) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{19}+}++func (x *WorkspaceSpec) GetGit() []*GitRepo {+ if x != nil {+ return x.Git+ }+ return nil+}++func (x *WorkspaceSpec) GetMcp() *MCPConfig {+ if x != nil {+ return x.Mcp+ }+ return nil+}++func (x *WorkspaceSpec) GetSkills() *SkillsConfig {+ if x != nil {+ return x.Skills+ }+ return nil+}++type GitRepo struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`+ Repo string `protobuf:"bytes,2,opt,name=repo,proto3" json:"repo,omitempty"`+ Branch string `protobuf:"bytes,3,opt,name=branch,proto3" json:"branch,omitempty"`+ Dir string `protobuf:"bytes,4,opt,name=dir,proto3" json:"dir,omitempty"`+ Depth int32 `protobuf:"varint,5,opt,name=depth,proto3" json:"depth,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *GitRepo) Reset() {+ *x = GitRepo{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[20]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *GitRepo) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*GitRepo) ProtoMessage() {}++func (x *GitRepo) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[20]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use GitRepo.ProtoReflect.Descriptor instead.+func (*GitRepo) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{20}+}++func (x *GitRepo) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *GitRepo) GetRepo() string {+ if x != nil {+ return x.Repo+ }+ return ""+}++func (x *GitRepo) GetBranch() string {+ if x != nil {+ return x.Branch+ }+ return ""+}++func (x *GitRepo) GetDir() string {+ if x != nil {+ return x.Dir+ }+ return ""+}++func (x *GitRepo) GetDepth() int32 {+ if x != nil {+ return x.Depth+ }+ return 0+}++type MCPConfig struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Registries []*MCPRegistry `protobuf:"bytes,1,rep,name=registries,proto3" json:"registries,omitempty"`+ Servers []*MCPServer `protobuf:"bytes,2,rep,name=servers,proto3" json:"servers,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *MCPConfig) Reset() {+ *x = MCPConfig{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[21]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *MCPConfig) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*MCPConfig) ProtoMessage() {}++func (x *MCPConfig) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[21]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use MCPConfig.ProtoReflect.Descriptor instead.+func (*MCPConfig) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{21}+}++func (x *MCPConfig) GetRegistries() []*MCPRegistry {+ if x != nil {+ return x.Registries+ }+ return nil+}++func (x *MCPConfig) GetServers() []*MCPServer {+ if x != nil {+ return x.Servers+ }+ return nil+}++type MCPRegistry struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Provider string `protobuf:"bytes,1,opt,name=provider,proto3" json:"provider,omitempty"`+ Project string `protobuf:"bytes,2,opt,name=project,proto3" json:"project,omitempty"`+ Query string `protobuf:"bytes,3,opt,name=query,proto3" json:"query,omitempty"`+ Servers []*MCPServer `protobuf:"bytes,4,rep,name=servers,proto3" json:"servers,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *MCPRegistry) Reset() {+ *x = MCPRegistry{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[22]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *MCPRegistry) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*MCPRegistry) ProtoMessage() {}++func (x *MCPRegistry) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[22]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use MCPRegistry.ProtoReflect.Descriptor instead.+func (*MCPRegistry) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{22}+}++func (x *MCPRegistry) GetProvider() string {+ if x != nil {+ return x.Provider+ }+ return ""+}++func (x *MCPRegistry) GetProject() string {+ if x != nil {+ return x.Project+ }+ return ""+}++func (x *MCPRegistry) GetQuery() string {+ if x != nil {+ return x.Query+ }+ return ""+}++func (x *MCPRegistry) GetServers() []*MCPServer {+ if x != nil {+ return x.Servers+ }+ return nil+}++type MCPServer struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`+ Endpoint string `protobuf:"bytes,2,opt,name=endpoint,proto3" json:"endpoint,omitempty"`+ Command string `protobuf:"bytes,3,opt,name=command,proto3" json:"command,omitempty"`+ Args []string `protobuf:"bytes,4,rep,name=args,proto3" json:"args,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *MCPServer) Reset() {+ *x = MCPServer{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[23]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *MCPServer) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*MCPServer) ProtoMessage() {}++func (x *MCPServer) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[23]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use MCPServer.ProtoReflect.Descriptor instead.+func (*MCPServer) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{23}+}++func (x *MCPServer) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *MCPServer) GetEndpoint() string {+ if x != nil {+ return x.Endpoint+ }+ return ""+}++func (x *MCPServer) GetCommand() string {+ if x != nil {+ return x.Command+ }+ return ""+}++func (x *MCPServer) GetArgs() []string {+ if x != nil {+ return x.Args+ }+ return nil+}++type SkillsConfig struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Registries []*SkillRegistry `protobuf:"bytes,1,rep,name=registries,proto3" json:"registries,omitempty"`+ Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SkillsConfig) Reset() {+ *x = SkillsConfig{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[24]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SkillsConfig) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SkillsConfig) ProtoMessage() {}++func (x *SkillsConfig) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[24]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SkillsConfig.ProtoReflect.Descriptor instead.+func (*SkillsConfig) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{24}+}++func (x *SkillsConfig) GetRegistries() []*SkillRegistry {+ if x != nil {+ return x.Registries+ }+ return nil+}++func (x *SkillsConfig) GetPath() string {+ if x != nil {+ return x.Path+ }+ return ""+}++type SkillRegistry struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Provider string `protobuf:"bytes,1,opt,name=provider,proto3" json:"provider,omitempty"`+ Project string `protobuf:"bytes,2,opt,name=project,proto3" json:"project,omitempty"`+ Query string `protobuf:"bytes,3,opt,name=query,proto3" json:"query,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SkillRegistry) Reset() {+ *x = SkillRegistry{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[25]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SkillRegistry) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SkillRegistry) ProtoMessage() {}++func (x *SkillRegistry) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[25]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SkillRegistry.ProtoReflect.Descriptor instead.+func (*SkillRegistry) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{25}+}++func (x *SkillRegistry) GetProvider() string {+ if x != nil {+ return x.Provider+ }+ return ""+}++func (x *SkillRegistry) GetProject() string {+ if x != nil {+ return x.Project+ }+ return ""+}++func (x *SkillRegistry) GetQuery() string {+ if x != nil {+ return x.Query+ }+ return ""+}++type Model struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ ApiVersion string `protobuf:"bytes,1,opt,name=api_version,json=apiVersion,proto3" json:"api_version,omitempty"`+ Kind string `protobuf:"bytes,2,opt,name=kind,proto3" json:"kind,omitempty"`+ Metadata *ObjectMeta `protobuf:"bytes,3,opt,name=metadata,proto3" json:"metadata,omitempty"`+ Spec *ModelSpec `protobuf:"bytes,4,opt,name=spec,proto3" json:"spec,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *Model) Reset() {+ *x = Model{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[26]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *Model) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*Model) ProtoMessage() {}++func (x *Model) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[26]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use Model.ProtoReflect.Descriptor instead.+func (*Model) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{26}+}++func (x *Model) GetApiVersion() string {+ if x != nil {+ return x.ApiVersion+ }+ return ""+}++func (x *Model) GetKind() string {+ if x != nil {+ return x.Kind+ }+ return ""+}++func (x *Model) GetMetadata() *ObjectMeta {+ if x != nil {+ return x.Metadata+ }+ return nil+}++func (x *Model) GetSpec() *ModelSpec {+ if x != nil {+ return x.Spec+ }+ return nil+}++type ModelSpec struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Provider string `protobuf:"bytes,1,opt,name=provider,proto3" json:"provider,omitempty"`+ Model string `protobuf:"bytes,2,opt,name=model,proto3" json:"model,omitempty"`+ SecretKey *SecretKeyRef `protobuf:"bytes,6,opt,name=secret_key,json=secretKey,proto3" json:"secret_key,omitempty"`+ // parameters are provider-specific generation settings passed through to the+ // model API as-is, for example temperature or maxOutputTokens for Gemini.+ Parameters *structpb.Struct `protobuf:"bytes,7,opt,name=parameters,proto3" json:"parameters,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ModelSpec) Reset() {+ *x = ModelSpec{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[27]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ModelSpec) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ModelSpec) ProtoMessage() {}++func (x *ModelSpec) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[27]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ModelSpec.ProtoReflect.Descriptor instead.+func (*ModelSpec) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{27}+}++func (x *ModelSpec) GetProvider() string {+ if x != nil {+ return x.Provider+ }+ return ""+}++func (x *ModelSpec) GetModel() string {+ if x != nil {+ return x.Model+ }+ return ""+}++func (x *ModelSpec) GetSecretKey() *SecretKeyRef {+ if x != nil {+ return x.SecretKey+ }+ return nil+}++func (x *ModelSpec) GetParameters() *structpb.Struct {+ if x != nil {+ return x.Parameters+ }+ return nil+}++type SecretKeyRef struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`+ Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SecretKeyRef) Reset() {+ *x = SecretKeyRef{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[28]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SecretKeyRef) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SecretKeyRef) ProtoMessage() {}++func (x *SecretKeyRef) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[28]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SecretKeyRef.ProtoReflect.Descriptor instead.+func (*SecretKeyRef) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{28}+}++func (x *SecretKeyRef) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *SecretKeyRef) GetKey() string {+ if x != nil {+ return x.Key+ }+ return ""+}++// Tasks+type GetTaskRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *GetTaskRequest) Reset() {+ *x = GetTaskRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[29]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *GetTaskRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*GetTaskRequest) ProtoMessage() {}++func (x *GetTaskRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[29]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use GetTaskRequest.ProtoReflect.Descriptor instead.+func (*GetTaskRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{29}+}++func (x *GetTaskRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *GetTaskRequest) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type ListTasksRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"`+ Offset int64 `protobuf:"varint,3,opt,name=offset,proto3" json:"offset,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ListTasksRequest) Reset() {+ *x = ListTasksRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[30]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ListTasksRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ListTasksRequest) ProtoMessage() {}++func (x *ListTasksRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[30]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ListTasksRequest.ProtoReflect.Descriptor instead.+func (*ListTasksRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{30}+}++func (x *ListTasksRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *ListTasksRequest) GetLimit() int64 {+ if x != nil {+ return x.Limit+ }+ return 0+}++func (x *ListTasksRequest) GetOffset() int64 {+ if x != nil {+ return x.Offset+ }+ return 0+}++type ListTasksResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Tasks []*Task `protobuf:"bytes,1,rep,name=tasks,proto3" json:"tasks,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ListTasksResponse) Reset() {+ *x = ListTasksResponse{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[31]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ListTasksResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ListTasksResponse) ProtoMessage() {}++func (x *ListTasksResponse) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[31]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ListTasksResponse.ProtoReflect.Descriptor instead.+func (*ListTasksResponse) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{31}+}++func (x *ListTasksResponse) GetTasks() []*Task {+ if x != nil {+ return x.Tasks+ }+ return nil+}++type UpdateTaskRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Task *Task `protobuf:"bytes,1,opt,name=task,proto3" json:"task,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *UpdateTaskRequest) Reset() {+ *x = UpdateTaskRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[32]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *UpdateTaskRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*UpdateTaskRequest) ProtoMessage() {}++func (x *UpdateTaskRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[32]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use UpdateTaskRequest.ProtoReflect.Descriptor instead.+func (*UpdateTaskRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{32}+}++func (x *UpdateTaskRequest) GetTask() *Task {+ if x != nil {+ return x.Task+ }+ return nil+}++type DeleteTaskRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *DeleteTaskRequest) Reset() {+ *x = DeleteTaskRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[33]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *DeleteTaskRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*DeleteTaskRequest) ProtoMessage() {}++func (x *DeleteTaskRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[33]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use DeleteTaskRequest.ProtoReflect.Descriptor instead.+func (*DeleteTaskRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{33}+}++func (x *DeleteTaskRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *DeleteTaskRequest) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type DeleteTaskResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *DeleteTaskResponse) Reset() {+ *x = DeleteTaskResponse{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[34]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *DeleteTaskResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*DeleteTaskResponse) ProtoMessage() {}++func (x *DeleteTaskResponse) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[34]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use DeleteTaskResponse.ProtoReflect.Descriptor instead.+func (*DeleteTaskResponse) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{34}+}++type SuspendTaskRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SuspendTaskRequest) Reset() {+ *x = SuspendTaskRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[35]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SuspendTaskRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SuspendTaskRequest) ProtoMessage() {}++func (x *SuspendTaskRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[35]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SuspendTaskRequest.ProtoReflect.Descriptor instead.+func (*SuspendTaskRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{35}+}++func (x *SuspendTaskRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *SuspendTaskRequest) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type ResumeTaskRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ResumeTaskRequest) Reset() {+ *x = ResumeTaskRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[36]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ResumeTaskRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ResumeTaskRequest) ProtoMessage() {}++func (x *ResumeTaskRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[36]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ResumeTaskRequest.ProtoReflect.Descriptor instead.+func (*ResumeTaskRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{36}+}++func (x *ResumeTaskRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *ResumeTaskRequest) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type WatchTaskRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *WatchTaskRequest) Reset() {+ *x = WatchTaskRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[37]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *WatchTaskRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*WatchTaskRequest) ProtoMessage() {}++func (x *WatchTaskRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[37]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use WatchTaskRequest.ProtoReflect.Descriptor instead.+func (*WatchTaskRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{37}+}++func (x *WatchTaskRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *WatchTaskRequest) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type WatchTaskResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Task *Task `protobuf:"bytes,1,opt,name=task,proto3" json:"task,omitempty"`+ Action string `protobuf:"bytes,2,opt,name=action,proto3" json:"action,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *WatchTaskResponse) Reset() {+ *x = WatchTaskResponse{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[38]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *WatchTaskResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*WatchTaskResponse) ProtoMessage() {}++func (x *WatchTaskResponse) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[38]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use WatchTaskResponse.ProtoReflect.Descriptor instead.+func (*WatchTaskResponse) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{38}+}++func (x *WatchTaskResponse) GetTask() *Task {+ if x != nil {+ return x.Task+ }+ return nil+}++func (x *WatchTaskResponse) GetAction() string {+ if x != nil {+ return x.Action+ }+ return ""+}++// Gateways+type GetGatewayRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *GetGatewayRequest) Reset() {+ *x = GetGatewayRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[39]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *GetGatewayRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*GetGatewayRequest) ProtoMessage() {}++func (x *GetGatewayRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[39]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use GetGatewayRequest.ProtoReflect.Descriptor instead.+func (*GetGatewayRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{39}+}++func (x *GetGatewayRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *GetGatewayRequest) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type ListGatewaysRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ListGatewaysRequest) Reset() {+ *x = ListGatewaysRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[40]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ListGatewaysRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ListGatewaysRequest) ProtoMessage() {}++func (x *ListGatewaysRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[40]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ListGatewaysRequest.ProtoReflect.Descriptor instead.+func (*ListGatewaysRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{40}+}++func (x *ListGatewaysRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++type ListGatewaysResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Gateways []*Gateway `protobuf:"bytes,1,rep,name=gateways,proto3" json:"gateways,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ListGatewaysResponse) Reset() {+ *x = ListGatewaysResponse{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[41]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ListGatewaysResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ListGatewaysResponse) ProtoMessage() {}++func (x *ListGatewaysResponse) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[41]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ListGatewaysResponse.ProtoReflect.Descriptor instead.+func (*ListGatewaysResponse) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{41}+}++func (x *ListGatewaysResponse) GetGateways() []*Gateway {+ if x != nil {+ return x.Gateways+ }+ return nil+}++type UpdateGatewayRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Gateway *Gateway `protobuf:"bytes,1,opt,name=gateway,proto3" json:"gateway,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *UpdateGatewayRequest) Reset() {+ *x = UpdateGatewayRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[42]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *UpdateGatewayRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*UpdateGatewayRequest) ProtoMessage() {}++func (x *UpdateGatewayRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[42]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use UpdateGatewayRequest.ProtoReflect.Descriptor instead.+func (*UpdateGatewayRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{42}+}++func (x *UpdateGatewayRequest) GetGateway() *Gateway {+ if x != nil {+ return x.Gateway+ }+ return nil+}++type DeleteGatewayRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *DeleteGatewayRequest) Reset() {+ *x = DeleteGatewayRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[43]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *DeleteGatewayRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*DeleteGatewayRequest) ProtoMessage() {}++func (x *DeleteGatewayRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[43]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use DeleteGatewayRequest.ProtoReflect.Descriptor instead.+func (*DeleteGatewayRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{43}+}++func (x *DeleteGatewayRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *DeleteGatewayRequest) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type DeleteGatewayResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *DeleteGatewayResponse) Reset() {+ *x = DeleteGatewayResponse{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[44]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *DeleteGatewayResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*DeleteGatewayResponse) ProtoMessage() {}++func (x *DeleteGatewayResponse) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[44]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use DeleteGatewayResponse.ProtoReflect.Descriptor instead.+func (*DeleteGatewayResponse) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{44}+}++// Workspaces+type GetWorkspaceRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *GetWorkspaceRequest) Reset() {+ *x = GetWorkspaceRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[45]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *GetWorkspaceRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*GetWorkspaceRequest) ProtoMessage() {}++func (x *GetWorkspaceRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[45]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use GetWorkspaceRequest.ProtoReflect.Descriptor instead.+func (*GetWorkspaceRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{45}+}++func (x *GetWorkspaceRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *GetWorkspaceRequest) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type ListWorkspacesRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ListWorkspacesRequest) Reset() {+ *x = ListWorkspacesRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[46]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ListWorkspacesRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ListWorkspacesRequest) ProtoMessage() {}++func (x *ListWorkspacesRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[46]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ListWorkspacesRequest.ProtoReflect.Descriptor instead.+func (*ListWorkspacesRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{46}+}++func (x *ListWorkspacesRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++type ListWorkspacesResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Workspaces []*Workspace `protobuf:"bytes,1,rep,name=workspaces,proto3" json:"workspaces,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ListWorkspacesResponse) Reset() {+ *x = ListWorkspacesResponse{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[47]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ListWorkspacesResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ListWorkspacesResponse) ProtoMessage() {}++func (x *ListWorkspacesResponse) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[47]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ListWorkspacesResponse.ProtoReflect.Descriptor instead.+func (*ListWorkspacesResponse) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{47}+}++func (x *ListWorkspacesResponse) GetWorkspaces() []*Workspace {+ if x != nil {+ return x.Workspaces+ }+ return nil+}++type UpdateWorkspaceRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Workspace *Workspace `protobuf:"bytes,1,opt,name=workspace,proto3" json:"workspace,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *UpdateWorkspaceRequest) Reset() {+ *x = UpdateWorkspaceRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[48]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *UpdateWorkspaceRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*UpdateWorkspaceRequest) ProtoMessage() {}++func (x *UpdateWorkspaceRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[48]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use UpdateWorkspaceRequest.ProtoReflect.Descriptor instead.+func (*UpdateWorkspaceRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{48}+}++func (x *UpdateWorkspaceRequest) GetWorkspace() *Workspace {+ if x != nil {+ return x.Workspace+ }+ return nil+}++type DeleteWorkspaceRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *DeleteWorkspaceRequest) Reset() {+ *x = DeleteWorkspaceRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[49]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *DeleteWorkspaceRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*DeleteWorkspaceRequest) ProtoMessage() {}++func (x *DeleteWorkspaceRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[49]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use DeleteWorkspaceRequest.ProtoReflect.Descriptor instead.+func (*DeleteWorkspaceRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{49}+}++func (x *DeleteWorkspaceRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *DeleteWorkspaceRequest) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type DeleteWorkspaceResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *DeleteWorkspaceResponse) Reset() {+ *x = DeleteWorkspaceResponse{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[50]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *DeleteWorkspaceResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*DeleteWorkspaceResponse) ProtoMessage() {}++func (x *DeleteWorkspaceResponse) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[50]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use DeleteWorkspaceResponse.ProtoReflect.Descriptor instead.+func (*DeleteWorkspaceResponse) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{50}+}++// Models+type GetModelRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *GetModelRequest) Reset() {+ *x = GetModelRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[51]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *GetModelRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*GetModelRequest) ProtoMessage() {}++func (x *GetModelRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[51]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use GetModelRequest.ProtoReflect.Descriptor instead.+func (*GetModelRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{51}+}++func (x *GetModelRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *GetModelRequest) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type ListModelsRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ListModelsRequest) Reset() {+ *x = ListModelsRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[52]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ListModelsRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ListModelsRequest) ProtoMessage() {}++func (x *ListModelsRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[52]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ListModelsRequest.ProtoReflect.Descriptor instead.+func (*ListModelsRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{52}+}++func (x *ListModelsRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++type ListModelsResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Models []*Model `protobuf:"bytes,1,rep,name=models,proto3" json:"models,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *ListModelsResponse) Reset() {+ *x = ListModelsResponse{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[53]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *ListModelsResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*ListModelsResponse) ProtoMessage() {}++func (x *ListModelsResponse) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[53]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use ListModelsResponse.ProtoReflect.Descriptor instead.+func (*ListModelsResponse) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{53}+}++func (x *ListModelsResponse) GetModels() []*Model {+ if x != nil {+ return x.Models+ }+ return nil+}++type UpdateModelRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Model *Model `protobuf:"bytes,1,opt,name=model,proto3" json:"model,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *UpdateModelRequest) Reset() {+ *x = UpdateModelRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[54]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *UpdateModelRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*UpdateModelRequest) ProtoMessage() {}++func (x *UpdateModelRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[54]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use UpdateModelRequest.ProtoReflect.Descriptor instead.+func (*UpdateModelRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{54}+}++func (x *UpdateModelRequest) GetModel() *Model {+ if x != nil {+ return x.Model+ }+ return nil+}++type DeleteModelRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"`+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *DeleteModelRequest) Reset() {+ *x = DeleteModelRequest{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[55]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *DeleteModelRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*DeleteModelRequest) ProtoMessage() {}++func (x *DeleteModelRequest) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[55]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use DeleteModelRequest.ProtoReflect.Descriptor instead.+func (*DeleteModelRequest) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{55}+}++func (x *DeleteModelRequest) GetAtespace() string {+ if x != nil {+ return x.Atespace+ }+ return ""+}++func (x *DeleteModelRequest) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++type DeleteModelResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *DeleteModelResponse) Reset() {+ *x = DeleteModelResponse{}+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[56]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *DeleteModelResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*DeleteModelResponse) ProtoMessage() {}++func (x *DeleteModelResponse) ProtoReflect() protoreflect.Message {+ mi := &file_pkg_apis_v1alpha1_ax_proto_msgTypes[56]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use DeleteModelResponse.ProtoReflect.Descriptor instead.+func (*DeleteModelResponse) Descriptor() ([]byte, []int) {+ return file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP(), []int{56}+}++var File_pkg_apis_v1alpha1_ax_proto protoreflect.FileDescriptor++const file_pkg_apis_v1alpha1_ax_proto_rawDesc = "" ++ "\n" ++ "\x1apkg/apis/v1alpha1/ax.proto\x12\vax.v1alpha1\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\x87\x01\n" ++ "\n" ++ "ObjectMeta\x12\x12\n" ++ "\x04name\x18\x01 \x01(\tR\x04name\x12\x1a\n" ++ "\batespace\x18\x02 \x01(\tR\batespace\x12I\n" ++ "\x12creation_timestamp\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\x11creationTimestamp\"\xcc\x01\n" ++ "\x04Task\x12\x1f\n" ++ "\vapi_version\x18\x01 \x01(\tR\n" ++ "apiVersion\x12\x12\n" ++ "\x04kind\x18\x02 \x01(\tR\x04kind\x123\n" ++ "\bmetadata\x18\x03 \x01(\v2\x17.ax.v1alpha1.ObjectMetaR\bmetadata\x12)\n" ++ "\x04spec\x18\x04 \x01(\v2\x15.ax.v1alpha1.TaskSpecR\x04spec\x12/\n" ++ "\x06status\x18\x05 \x01(\v2\x17.ax.v1alpha1.TaskStatusR\x06status\"\xd4\x02\n" ++ "\bTaskSpec\x12\x18\n" ++ "\asuspend\x18\x02 \x01(\bR\asuspend\x12\x14\n" ++ "\x05image\x18\x03 \x01(\tR\x05image\x12\x18\n" ++ "\acommand\x18\x04 \x03(\tR\acommand\x12%\n" ++ "\x03env\x18\x05 \x03(\v2\x13.ax.v1alpha1.EnvVarR\x03env\x127\n" ++ "\tresources\x18\x06 \x01(\v2\x19.ax.v1alpha1.ResourceReqsR\tresources\x129\n" ++ "\n" ++ "workspaces\x18\a \x03(\v2\x19.ax.v1alpha1.WorkspaceRefR\n" ++ "workspaces\x121\n" ++ "\agateway\x18\b \x01(\v2\x17.ax.v1alpha1.GatewayRefR\agateway\x12\x14\n" ++ "\x05debug\x18\n" ++ " \x01(\bR\x05debugJ\x04\b\x01\x10\x02J\x04\b\t\x10\n" ++ "R\x04goalR\bpolicies\"2\n" ++ "\x06EnvVar\x12\x12\n" ++ "\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" ++ "\x05value\x18\x02 \x01(\tR\x05value\"x\n" ++ "\fResourceReqs\x125\n" ++ "\brequests\x18\x01 \x01(\v2\x19.ax.v1alpha1.ResourceListR\brequests\x121\n" ++ "\x06limits\x18\x02 \x01(\v2\x19.ax.v1alpha1.ResourceListR\x06limits\"8\n" ++ "\fResourceList\x12\x10\n" ++ "\x03cpu\x18\x01 \x01(\tR\x03cpu\x12\x16\n" ++ "\x06memory\x18\x02 \x01(\tR\x06memory\"J\n" ++ "\fWorkspaceRef\x12\x12\n" ++ "\x04name\x18\x01 \x01(\tR\x04name\x12\x12\n" ++ "\x04path\x18\x02 \x01(\tR\x04path\x12\x12\n" ++ "\x04goal\x18\x03 \x01(\tR\x04goal\" \n" ++ "\n" ++ "GatewayRef\x12\x12\n" ++ "\x04name\x18\x01 \x01(\tR\x04name\"\x95\x02\n" ++ "\n" ++ "TaskStatus\x12\x14\n" ++ "\x05phase\x18\x01 \x01(\tR\x05phase\x12\x0e\n" ++ "\x02id\x18\x02 \x01(\tR\x02id\x12\x14\n" ++ "\x05actor\x18\x03 \x01(\tR\x05actor\x12\x1b\n" ++ "\tworker_ip\x18\x04 \x01(\tR\bworkerIP\x12G\n" ++ "\x10pending_approval\x18\x05 \x01(\v2\x1c.ax.v1alpha1.PendingApprovalR\x0fpendingApproval\x12-\n" ++ "\x05usage\x18\x06 \x01(\v2\x17.ax.v1alpha1.UsageStatsR\x05usage\x126\n" ++ "\n" ++ "conditions\x18\a \x03(\v2\x16.ax.v1alpha1.ConditionR\n" ++ "conditions\"x\n" ++ "\x0fPendingApproval\x12\x0e\n" ++ "\x02id\x18\x01 \x01(\tR\x02id\x12\x16\n" ++ "\x06action\x18\x02 \x01(\tR\x06action\x12=\n" ++ "\frequested_at\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\vrequestedAt\"^\n" ++ "\n" ++ "UsageStats\x12#\n" ++ "\rprompt_tokens\x18\x01 \x01(\x05R\fpromptTokens\x12+\n" ++ "\x11completion_tokens\x18\x02 \x01(\x05R\x10completionTokens\"\xb7\x01\n" ++ "\tCondition\x12\x12\n" ++ "\x04type\x18\x01 \x01(\tR\x04type\x12\x16\n" ++ "\x06status\x18\x02 \x01(\tR\x06status\x12L\n" ++ "\x14last_transition_time\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\x12lastTransitionTime\x12\x16\n" ++ "\x06reason\x18\x04 \x01(\tR\x06reason\x12\x18\n" ++ "\amessage\x18\x05 \x01(\tR\amessage\"\xa1\x01\n" ++ "\aGateway\x12\x1f\n" ++ "\vapi_version\x18\x01 \x01(\tR\n" ++ "apiVersion\x12\x12\n" ++ "\x04kind\x18\x02 \x01(\tR\x04kind\x123\n" ++ "\bmetadata\x18\x03 \x01(\v2\x17.ax.v1alpha1.ObjectMetaR\bmetadata\x12,\n" ++ "\x04spec\x18\x04 \x01(\v2\x18.ax.v1alpha1.GatewaySpecR\x04spec\"u\n" ++ "\vGatewaySpec\x123\n" ++ "\tlisteners\x18\x01 \x03(\v2\x15.ax.v1alpha1.ListenerR\tlisteners\x121\n" ++ "\x06egress\x18\x02 \x01(\v2\x19.ax.v1alpha1.EgressConfigR\x06egress\"N\n" ++ "\bListener\x12\x12\n" ++ "\x04name\x18\x01 \x01(\tR\x04name\x12\x12\n" ++ "\x04port\x18\x02 \x01(\x05R\x04port\x12\x1a\n" ++ "\bprotocol\x18\x03 \x01(\tR\bprotocol\"J\n" ++ "\fEgressConfig\x12:\n" ++ "\tallowlist\x18\x01 \x01(\v2\x1c.ax.v1alpha1.EgressAllowlistR\tallowlist\">\n" ++ "\x0fEgressAllowlist\x12+\n" ++ "\x05hosts\x18\x01 \x03(\v2\x15.ax.v1alpha1.HostRuleR\x05hosts\"2\n" ++ "\bHostRule\x12\x12\n" ++ "\x04host\x18\x01 \x01(\tR\x04host\x12\x12\n" ++ "\x04port\x18\x02 \x01(\x05R\x04port\"\xa5\x01\n" ++ "\tWorkspace\x12\x1f\n" ++ "\vapi_version\x18\x01 \x01(\tR\n" ++ "apiVersion\x12\x12\n" ++ "\x04kind\x18\x02 \x01(\tR\x04kind\x123\n" ++ "\bmetadata\x18\x03 \x01(\v2\x17.ax.v1alpha1.ObjectMetaR\bmetadata\x12.\n" ++ "\x04spec\x18\x04 \x01(\v2\x1a.ax.v1alpha1.WorkspaceSpecR\x04spec\"\x94\x01\n" ++ "\rWorkspaceSpec\x12&\n" ++ "\x03git\x18\x01 \x03(\v2\x14.ax.v1alpha1.GitRepoR\x03git\x12(\n" ++ "\x03mcp\x18\x02 \x01(\v2\x16.ax.v1alpha1.MCPConfigR\x03mcp\x121\n" ++ "\x06skills\x18\x03 \x01(\v2\x19.ax.v1alpha1.SkillsConfigR\x06skills\"q\n" ++ "\aGitRepo\x12\x12\n" ++ "\x04name\x18\x01 \x01(\tR\x04name\x12\x12\n" ++ "\x04repo\x18\x02 \x01(\tR\x04repo\x12\x16\n" ++ "\x06branch\x18\x03 \x01(\tR\x06branch\x12\x10\n" ++ "\x03dir\x18\x04 \x01(\tR\x03dir\x12\x14\n" ++ "\x05depth\x18\x05 \x01(\x05R\x05depth\"w\n" ++ "\tMCPConfig\x128\n" ++ "\n" ++ "registries\x18\x01 \x03(\v2\x18.ax.v1alpha1.MCPRegistryR\n" ++ "registries\x120\n" ++ "\aservers\x18\x02 \x03(\v2\x16.ax.v1alpha1.MCPServerR\aservers\"\x8b\x01\n" ++ "\vMCPRegistry\x12\x1a\n" ++ "\bprovider\x18\x01 \x01(\tR\bprovider\x12\x18\n" ++ "\aproject\x18\x02 \x01(\tR\aproject\x12\x14\n" ++ "\x05query\x18\x03 \x01(\tR\x05query\x120\n" ++ "\aservers\x18\x04 \x03(\v2\x16.ax.v1alpha1.MCPServerR\aservers\"i\n" ++ "\tMCPServer\x12\x12\n" ++ "\x04name\x18\x01 \x01(\tR\x04name\x12\x1a\n" ++ "\bendpoint\x18\x02 \x01(\tR\bendpoint\x12\x18\n" ++ "\acommand\x18\x03 \x01(\tR\acommand\x12\x12\n" ++ "\x04args\x18\x04 \x03(\tR\x04args\"^\n" ++ "\fSkillsConfig\x12:\n" ++ "\n" ++ "registries\x18\x01 \x03(\v2\x1a.ax.v1alpha1.SkillRegistryR\n" ++ "registries\x12\x12\n" ++ "\x04path\x18\x02 \x01(\tR\x04path\"[\n" ++ "\rSkillRegistry\x12\x1a\n" ++ "\bprovider\x18\x01 \x01(\tR\bprovider\x12\x18\n" ++ "\aproject\x18\x02 \x01(\tR\aproject\x12\x14\n" ++ "\x05query\x18\x03 \x01(\tR\x05query\"\x9d\x01\n" ++ "\x05Model\x12\x1f\n" ++ "\vapi_version\x18\x01 \x01(\tR\n" ++ "apiVersion\x12\x12\n" ++ "\x04kind\x18\x02 \x01(\tR\x04kind\x123\n" ++ "\bmetadata\x18\x03 \x01(\v2\x17.ax.v1alpha1.ObjectMetaR\bmetadata\x12*\n" ++ "\x04spec\x18\x04 \x01(\v2\x16.ax.v1alpha1.ModelSpecR\x04spec\"\xef\x01\n" ++ "\tModelSpec\x12\x1a\n" ++ "\bprovider\x18\x01 \x01(\tR\bprovider\x12\x14\n" ++ "\x05model\x18\x02 \x01(\tR\x05model\x128\n" ++ "\n" ++ "secret_key\x18\x06 \x01(\v2\x19.ax.v1alpha1.SecretKeyRefR\tsecretKey\x127\n" ++ "\n" ++ "parameters\x18\a \x01(\v2\x17.google.protobuf.StructR\n" ++ "parametersJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\vtemperatureR\n" ++ "max_tokensR\x12system_instruction\"4\n" ++ "\fSecretKeyRef\x12\x12\n" ++ "\x04name\x18\x01 \x01(\tR\x04name\x12\x10\n" ++ "\x03key\x18\x02 \x01(\tR\x03key\"@\n" ++ "\x0eGetTaskRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\"\\\n" ++ "\x10ListTasksRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x14\n" ++ "\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x16\n" ++ "\x06offset\x18\x03 \x01(\x03R\x06offset\"<\n" ++ "\x11ListTasksResponse\x12'\n" ++ "\x05tasks\x18\x01 \x03(\v2\x11.ax.v1alpha1.TaskR\x05tasks\":\n" ++ "\x11UpdateTaskRequest\x12%\n" ++ "\x04task\x18\x01 \x01(\v2\x11.ax.v1alpha1.TaskR\x04task\"C\n" ++ "\x11DeleteTaskRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\"\x14\n" ++ "\x12DeleteTaskResponse\"D\n" ++ "\x12SuspendTaskRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\"C\n" ++ "\x11ResumeTaskRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\"B\n" ++ "\x10WatchTaskRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\"R\n" ++ "\x11WatchTaskResponse\x12%\n" ++ "\x04task\x18\x01 \x01(\v2\x11.ax.v1alpha1.TaskR\x04task\x12\x16\n" ++ "\x06action\x18\x02 \x01(\tR\x06action\"C\n" ++ "\x11GetGatewayRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\"1\n" ++ "\x13ListGatewaysRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\"H\n" ++ "\x14ListGatewaysResponse\x120\n" ++ "\bgateways\x18\x01 \x03(\v2\x14.ax.v1alpha1.GatewayR\bgateways\"F\n" ++ "\x14UpdateGatewayRequest\x12.\n" ++ "\agateway\x18\x01 \x01(\v2\x14.ax.v1alpha1.GatewayR\agateway\"F\n" ++ "\x14DeleteGatewayRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\"\x17\n" ++ "\x15DeleteGatewayResponse\"E\n" ++ "\x13GetWorkspaceRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\"3\n" ++ "\x15ListWorkspacesRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\"P\n" ++ "\x16ListWorkspacesResponse\x126\n" ++ "\n" ++ "workspaces\x18\x01 \x03(\v2\x16.ax.v1alpha1.WorkspaceR\n" ++ "workspaces\"N\n" ++ "\x16UpdateWorkspaceRequest\x124\n" ++ "\tworkspace\x18\x01 \x01(\v2\x16.ax.v1alpha1.WorkspaceR\tworkspace\"H\n" ++ "\x16DeleteWorkspaceRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\"\x19\n" ++ "\x17DeleteWorkspaceResponse\"A\n" ++ "\x0fGetModelRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\"/\n" ++ "\x11ListModelsRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\"@\n" ++ "\x12ListModelsResponse\x12*\n" ++ "\x06models\x18\x01 \x03(\v2\x12.ax.v1alpha1.ModelR\x06models\">\n" ++ "\x12UpdateModelRequest\x12(\n" ++ "\x05model\x18\x01 \x01(\v2\x12.ax.v1alpha1.ModelR\x05model\"D\n" ++ "\x12DeleteModelRequest\x12\x1a\n" ++ "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\"\x15\n" ++ "\x13DeleteModelResponse2\x9e\v\n" ++ "\x02AX\x129\n" ++ "\aGetTask\x12\x1b.ax.v1alpha1.GetTaskRequest\x1a\x11.ax.v1alpha1.Task\x12J\n" ++ "\tListTasks\x12\x1d.ax.v1alpha1.ListTasksRequest\x1a\x1e.ax.v1alpha1.ListTasksResponse\x12?\n" ++ "\n" ++ "UpdateTask\x12\x1e.ax.v1alpha1.UpdateTaskRequest\x1a\x11.ax.v1alpha1.Task\x12M\n" ++ "\n" ++ "DeleteTask\x12\x1e.ax.v1alpha1.DeleteTaskRequest\x1a\x1f.ax.v1alpha1.DeleteTaskResponse\x12A\n" ++ "\vSuspendTask\x12\x1f.ax.v1alpha1.SuspendTaskRequest\x1a\x11.ax.v1alpha1.Task\x12?\n" ++ "\n" ++ "ResumeTask\x12\x1e.ax.v1alpha1.ResumeTaskRequest\x1a\x11.ax.v1alpha1.Task\x12L\n" ++ "\tWatchTask\x12\x1d.ax.v1alpha1.WatchTaskRequest\x1a\x1e.ax.v1alpha1.WatchTaskResponse0\x01\x12B\n" ++ "\n" ++ "GetGateway\x12\x1e.ax.v1alpha1.GetGatewayRequest\x1a\x14.ax.v1alpha1.Gateway\x12S\n" ++ "\fListGateways\x12 .ax.v1alpha1.ListGatewaysRequest\x1a!.ax.v1alpha1.ListGatewaysResponse\x12H\n" ++ "\rUpdateGateway\x12!.ax.v1alpha1.UpdateGatewayRequest\x1a\x14.ax.v1alpha1.Gateway\x12V\n" ++ "\rDeleteGateway\x12!.ax.v1alpha1.DeleteGatewayRequest\x1a\".ax.v1alpha1.DeleteGatewayResponse\x12H\n" ++ "\fGetWorkspace\x12 .ax.v1alpha1.GetWorkspaceRequest\x1a\x16.ax.v1alpha1.Workspace\x12Y\n" ++ "\x0eListWorkspaces\x12\".ax.v1alpha1.ListWorkspacesRequest\x1a#.ax.v1alpha1.ListWorkspacesResponse\x12N\n" ++ "\x0fUpdateWorkspace\x12#.ax.v1alpha1.UpdateWorkspaceRequest\x1a\x16.ax.v1alpha1.Workspace\x12\\\n" ++ "\x0fDeleteWorkspace\x12#.ax.v1alpha1.DeleteWorkspaceRequest\x1a$.ax.v1alpha1.DeleteWorkspaceResponse\x12<\n" ++ "\bGetModel\x12\x1c.ax.v1alpha1.GetModelRequest\x1a\x12.ax.v1alpha1.Model\x12M\n" ++ "\n" ++ "ListModels\x12\x1e.ax.v1alpha1.ListModelsRequest\x1a\x1f.ax.v1alpha1.ListModelsResponse\x12B\n" ++ "\vUpdateModel\x12\x1f.ax.v1alpha1.UpdateModelRequest\x1a\x12.ax.v1alpha1.Model\x12P\n" ++ "\vDeleteModel\x12\x1f.ax.v1alpha1.DeleteModelRequest\x1a .ax.v1alpha1.DeleteModelResponseB(Z&github.com/google/ax/pkg/apis/v1alpha1b\x06proto3"++var (+ file_pkg_apis_v1alpha1_ax_proto_rawDescOnce sync.Once+ file_pkg_apis_v1alpha1_ax_proto_rawDescData []byte+)++func file_pkg_apis_v1alpha1_ax_proto_rawDescGZIP() []byte {+ file_pkg_apis_v1alpha1_ax_proto_rawDescOnce.Do(func() {+ file_pkg_apis_v1alpha1_ax_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_pkg_apis_v1alpha1_ax_proto_rawDesc), len(file_pkg_apis_v1alpha1_ax_proto_rawDesc)))+ })+ return file_pkg_apis_v1alpha1_ax_proto_rawDescData+}++var file_pkg_apis_v1alpha1_ax_proto_msgTypes = make([]protoimpl.MessageInfo, 57)+var file_pkg_apis_v1alpha1_ax_proto_goTypes = []any{+ (*ObjectMeta)(nil), // 0: ax.v1alpha1.ObjectMeta+ (*Task)(nil), // 1: ax.v1alpha1.Task+ (*TaskSpec)(nil), // 2: ax.v1alpha1.TaskSpec+ (*EnvVar)(nil), // 3: ax.v1alpha1.EnvVar+ (*ResourceReqs)(nil), // 4: ax.v1alpha1.ResourceReqs+ (*ResourceList)(nil), // 5: ax.v1alpha1.ResourceList+ (*WorkspaceRef)(nil), // 6: ax.v1alpha1.WorkspaceRef+ (*GatewayRef)(nil), // 7: ax.v1alpha1.GatewayRef+ (*TaskStatus)(nil), // 8: ax.v1alpha1.TaskStatus+ (*PendingApproval)(nil), // 9: ax.v1alpha1.PendingApproval+ (*UsageStats)(nil), // 10: ax.v1alpha1.UsageStats+ (*Condition)(nil), // 11: ax.v1alpha1.Condition+ (*Gateway)(nil), // 12: ax.v1alpha1.Gateway+ (*GatewaySpec)(nil), // 13: ax.v1alpha1.GatewaySpec+ (*Listener)(nil), // 14: ax.v1alpha1.Listener+ (*EgressConfig)(nil), // 15: ax.v1alpha1.EgressConfig+ (*EgressAllowlist)(nil), // 16: ax.v1alpha1.EgressAllowlist+ (*HostRule)(nil), // 17: ax.v1alpha1.HostRule+ (*Workspace)(nil), // 18: ax.v1alpha1.Workspace+ (*WorkspaceSpec)(nil), // 19: ax.v1alpha1.WorkspaceSpec+ (*GitRepo)(nil), // 20: ax.v1alpha1.GitRepo+ (*MCPConfig)(nil), // 21: ax.v1alpha1.MCPConfig+ (*MCPRegistry)(nil), // 22: ax.v1alpha1.MCPRegistry+ (*MCPServer)(nil), // 23: ax.v1alpha1.MCPServer+ (*SkillsConfig)(nil), // 24: ax.v1alpha1.SkillsConfig+ (*SkillRegistry)(nil), // 25: ax.v1alpha1.SkillRegistry+ (*Model)(nil), // 26: ax.v1alpha1.Model+ (*ModelSpec)(nil), // 27: ax.v1alpha1.ModelSpec+ (*SecretKeyRef)(nil), // 28: ax.v1alpha1.SecretKeyRef+ (*GetTaskRequest)(nil), // 29: ax.v1alpha1.GetTaskRequest+ (*ListTasksRequest)(nil), // 30: ax.v1alpha1.ListTasksRequest+ (*ListTasksResponse)(nil), // 31: ax.v1alpha1.ListTasksResponse+ (*UpdateTaskRequest)(nil), // 32: ax.v1alpha1.UpdateTaskRequest+ (*DeleteTaskRequest)(nil), // 33: ax.v1alpha1.DeleteTaskRequest+ (*DeleteTaskResponse)(nil), // 34: ax.v1alpha1.DeleteTaskResponse+ (*SuspendTaskRequest)(nil), // 35: ax.v1alpha1.SuspendTaskRequest+ (*ResumeTaskRequest)(nil), // 36: ax.v1alpha1.ResumeTaskRequest+ (*WatchTaskRequest)(nil), // 37: ax.v1alpha1.WatchTaskRequest+ (*WatchTaskResponse)(nil), // 38: ax.v1alpha1.WatchTaskResponse+ (*GetGatewayRequest)(nil), // 39: ax.v1alpha1.GetGatewayRequest+ (*ListGatewaysRequest)(nil), // 40: ax.v1alpha1.ListGatewaysRequest+ (*ListGatewaysResponse)(nil), // 41: ax.v1alpha1.ListGatewaysResponse+ (*UpdateGatewayRequest)(nil), // 42: ax.v1alpha1.UpdateGatewayRequest+ (*DeleteGatewayRequest)(nil), // 43: ax.v1alpha1.DeleteGatewayRequest+ (*DeleteGatewayResponse)(nil), // 44: ax.v1alpha1.DeleteGatewayResponse+ (*GetWorkspaceRequest)(nil), // 45: ax.v1alpha1.GetWorkspaceRequest+ (*ListWorkspacesRequest)(nil), // 46: ax.v1alpha1.ListWorkspacesRequest+ (*ListWorkspacesResponse)(nil), // 47: ax.v1alpha1.ListWorkspacesResponse+ (*UpdateWorkspaceRequest)(nil), // 48: ax.v1alpha1.UpdateWorkspaceRequest+ (*DeleteWorkspaceRequest)(nil), // 49: ax.v1alpha1.DeleteWorkspaceRequest+ (*DeleteWorkspaceResponse)(nil), // 50: ax.v1alpha1.DeleteWorkspaceResponse+ (*GetModelRequest)(nil), // 51: ax.v1alpha1.GetModelRequest+ (*ListModelsRequest)(nil), // 52: ax.v1alpha1.ListModelsRequest+ (*ListModelsResponse)(nil), // 53: ax.v1alpha1.ListModelsResponse+ (*UpdateModelRequest)(nil), // 54: ax.v1alpha1.UpdateModelRequest+ (*DeleteModelRequest)(nil), // 55: ax.v1alpha1.DeleteModelRequest+ (*DeleteModelResponse)(nil), // 56: ax.v1alpha1.DeleteModelResponse+ (*timestamppb.Timestamp)(nil), // 57: google.protobuf.Timestamp+ (*structpb.Struct)(nil), // 58: google.protobuf.Struct+}+var file_pkg_apis_v1alpha1_ax_proto_depIdxs = []int32{+ 57, // 0: ax.v1alpha1.ObjectMeta.creation_timestamp:type_name -> google.protobuf.Timestamp+ 0, // 1: ax.v1alpha1.Task.metadata:type_name -> ax.v1alpha1.ObjectMeta+ 2, // 2: ax.v1alpha1.Task.spec:type_name -> ax.v1alpha1.TaskSpec+ 8, // 3: ax.v1alpha1.Task.status:type_name -> ax.v1alpha1.TaskStatus+ 3, // 4: ax.v1alpha1.TaskSpec.env:type_name -> ax.v1alpha1.EnvVar+ 4, // 5: ax.v1alpha1.TaskSpec.resources:type_name -> ax.v1alpha1.ResourceReqs+ 6, // 6: ax.v1alpha1.TaskSpec.workspaces:type_name -> ax.v1alpha1.WorkspaceRef+ 7, // 7: ax.v1alpha1.TaskSpec.gateway:type_name -> ax.v1alpha1.GatewayRef+ 5, // 8: ax.v1alpha1.ResourceReqs.requests:type_name -> ax.v1alpha1.ResourceList+ 5, // 9: ax.v1alpha1.ResourceReqs.limits:type_name -> ax.v1alpha1.ResourceList+ 9, // 10: ax.v1alpha1.TaskStatus.pending_approval:type_name -> ax.v1alpha1.PendingApproval+ 10, // 11: ax.v1alpha1.TaskStatus.usage:type_name -> ax.v1alpha1.UsageStats+ 11, // 12: ax.v1alpha1.TaskStatus.conditions:type_name -> ax.v1alpha1.Condition+ 57, // 13: ax.v1alpha1.PendingApproval.requested_at:type_name -> google.protobuf.Timestamp+ 57, // 14: ax.v1alpha1.Condition.last_transition_time:type_name -> google.protobuf.Timestamp+ 0, // 15: ax.v1alpha1.Gateway.metadata:type_name -> ax.v1alpha1.ObjectMeta+ 13, // 16: ax.v1alpha1.Gateway.spec:type_name -> ax.v1alpha1.GatewaySpec+ 14, // 17: ax.v1alpha1.GatewaySpec.listeners:type_name -> ax.v1alpha1.Listener+ 15, // 18: ax.v1alpha1.GatewaySpec.egress:type_name -> ax.v1alpha1.EgressConfig+ 16, // 19: ax.v1alpha1.EgressConfig.allowlist:type_name -> ax.v1alpha1.EgressAllowlist+ 17, // 20: ax.v1alpha1.EgressAllowlist.hosts:type_name -> ax.v1alpha1.HostRule+ 0, // 21: ax.v1alpha1.Workspace.metadata:type_name -> ax.v1alpha1.ObjectMeta+ 19, // 22: ax.v1alpha1.Workspace.spec:type_name -> ax.v1alpha1.WorkspaceSpec+ 20, // 23: ax.v1alpha1.WorkspaceSpec.git:type_name -> ax.v1alpha1.GitRepo+ 21, // 24: ax.v1alpha1.WorkspaceSpec.mcp:type_name -> ax.v1alpha1.MCPConfig+ 24, // 25: ax.v1alpha1.WorkspaceSpec.skills:type_name -> ax.v1alpha1.SkillsConfig+ 22, // 26: ax.v1alpha1.MCPConfig.registries:type_name -> ax.v1alpha1.MCPRegistry+ 23, // 27: ax.v1alpha1.MCPConfig.servers:type_name -> ax.v1alpha1.MCPServer+ 23, // 28: ax.v1alpha1.MCPRegistry.servers:type_name -> ax.v1alpha1.MCPServer+ 25, // 29: ax.v1alpha1.SkillsConfig.registries:type_name -> ax.v1alpha1.SkillRegistry+ 0, // 30: ax.v1alpha1.Model.metadata:type_name -> ax.v1alpha1.ObjectMeta+ 27, // 31: ax.v1alpha1.Model.spec:type_name -> ax.v1alpha1.ModelSpec+ 28, // 32: ax.v1alpha1.ModelSpec.secret_key:type_name -> ax.v1alpha1.SecretKeyRef+ 58, // 33: ax.v1alpha1.ModelSpec.parameters:type_name -> google.protobuf.Struct+ 1, // 34: ax.v1alpha1.ListTasksResponse.tasks:type_name -> ax.v1alpha1.Task+ 1, // 35: ax.v1alpha1.UpdateTaskRequest.task:type_name -> ax.v1alpha1.Task+ 1, // 36: ax.v1alpha1.WatchTaskResponse.task:type_name -> ax.v1alpha1.Task+ 12, // 37: ax.v1alpha1.ListGatewaysResponse.gateways:type_name -> ax.v1alpha1.Gateway+ 12, // 38: ax.v1alpha1.UpdateGatewayRequest.gateway:type_name -> ax.v1alpha1.Gateway+ 18, // 39: ax.v1alpha1.ListWorkspacesResponse.workspaces:type_name -> ax.v1alpha1.Workspace+ 18, // 40: ax.v1alpha1.UpdateWorkspaceRequest.workspace:type_name -> ax.v1alpha1.Workspace+ 26, // 41: ax.v1alpha1.ListModelsResponse.models:type_name -> ax.v1alpha1.Model+ 26, // 42: ax.v1alpha1.UpdateModelRequest.model:type_name -> ax.v1alpha1.Model+ 29, // 43: ax.v1alpha1.AX.GetTask:input_type -> ax.v1alpha1.GetTaskRequest+ 30, // 44: ax.v1alpha1.AX.ListTasks:input_type -> ax.v1alpha1.ListTasksRequest+ 32, // 45: ax.v1alpha1.AX.UpdateTask:input_type -> ax.v1alpha1.UpdateTaskRequest+ 33, // 46: ax.v1alpha1.AX.DeleteTask:input_type -> ax.v1alpha1.DeleteTaskRequest+ 35, // 47: ax.v1alpha1.AX.SuspendTask:input_type -> ax.v1alpha1.SuspendTaskRequest+ 36, // 48: ax.v1alpha1.AX.ResumeTask:input_type -> ax.v1alpha1.ResumeTaskRequest+ 37, // 49: ax.v1alpha1.AX.WatchTask:input_type -> ax.v1alpha1.WatchTaskRequest+ 39, // 50: ax.v1alpha1.AX.GetGateway:input_type -> ax.v1alpha1.GetGatewayRequest+ 40, // 51: ax.v1alpha1.AX.ListGateways:input_type -> ax.v1alpha1.ListGatewaysRequest+ 42, // 52: ax.v1alpha1.AX.UpdateGateway:input_type -> ax.v1alpha1.UpdateGatewayRequest+ 43, // 53: ax.v1alpha1.AX.DeleteGateway:input_type -> ax.v1alpha1.DeleteGatewayRequest+ 45, // 54: ax.v1alpha1.AX.GetWorkspace:input_type -> ax.v1alpha1.GetWorkspaceRequest+ 46, // 55: ax.v1alpha1.AX.ListWorkspaces:input_type -> ax.v1alpha1.ListWorkspacesRequest+ 48, // 56: ax.v1alpha1.AX.UpdateWorkspace:input_type -> ax.v1alpha1.UpdateWorkspaceRequest+ 49, // 57: ax.v1alpha1.AX.DeleteWorkspace:input_type -> ax.v1alpha1.DeleteWorkspaceRequest+ 51, // 58: ax.v1alpha1.AX.GetModel:input_type -> ax.v1alpha1.GetModelRequest+ 52, // 59: ax.v1alpha1.AX.ListModels:input_type -> ax.v1alpha1.ListModelsRequest+ 54, // 60: ax.v1alpha1.AX.UpdateModel:input_type -> ax.v1alpha1.UpdateModelRequest+ 55, // 61: ax.v1alpha1.AX.DeleteModel:input_type -> ax.v1alpha1.DeleteModelRequest+ 1, // 62: ax.v1alpha1.AX.GetTask:output_type -> ax.v1alpha1.Task+ 31, // 63: ax.v1alpha1.AX.ListTasks:output_type -> ax.v1alpha1.ListTasksResponse+ 1, // 64: ax.v1alpha1.AX.UpdateTask:output_type -> ax.v1alpha1.Task+ 34, // 65: ax.v1alpha1.AX.DeleteTask:output_type -> ax.v1alpha1.DeleteTaskResponse+ 1, // 66: ax.v1alpha1.AX.SuspendTask:output_type -> ax.v1alpha1.Task+ 1, // 67: ax.v1alpha1.AX.ResumeTask:output_type -> ax.v1alpha1.Task+ 38, // 68: ax.v1alpha1.AX.WatchTask:output_type -> ax.v1alpha1.WatchTaskResponse+ 12, // 69: ax.v1alpha1.AX.GetGateway:output_type -> ax.v1alpha1.Gateway+ 41, // 70: ax.v1alpha1.AX.ListGateways:output_type -> ax.v1alpha1.ListGatewaysResponse+ 12, // 71: ax.v1alpha1.AX.UpdateGateway:output_type -> ax.v1alpha1.Gateway+ 44, // 72: ax.v1alpha1.AX.DeleteGateway:output_type -> ax.v1alpha1.DeleteGatewayResponse+ 18, // 73: ax.v1alpha1.AX.GetWorkspace:output_type -> ax.v1alpha1.Workspace+ 47, // 74: ax.v1alpha1.AX.ListWorkspaces:output_type -> ax.v1alpha1.ListWorkspacesResponse+ 18, // 75: ax.v1alpha1.AX.UpdateWorkspace:output_type -> ax.v1alpha1.Workspace+ 50, // 76: ax.v1alpha1.AX.DeleteWorkspace:output_type -> ax.v1alpha1.DeleteWorkspaceResponse+ 26, // 77: ax.v1alpha1.AX.GetModel:output_type -> ax.v1alpha1.Model+ 53, // 78: ax.v1alpha1.AX.ListModels:output_type -> ax.v1alpha1.ListModelsResponse+ 26, // 79: ax.v1alpha1.AX.UpdateModel:output_type -> ax.v1alpha1.Model+ 56, // 80: ax.v1alpha1.AX.DeleteModel:output_type -> ax.v1alpha1.DeleteModelResponse+ 62, // [62:81] is the sub-list for method output_type+ 43, // [43:62] is the sub-list for method input_type+ 43, // [43:43] is the sub-list for extension type_name+ 43, // [43:43] is the sub-list for extension extendee+ 0, // [0:43] is the sub-list for field type_name+}++func init() { file_pkg_apis_v1alpha1_ax_proto_init() }+func file_pkg_apis_v1alpha1_ax_proto_init() {+ if File_pkg_apis_v1alpha1_ax_proto != nil {+ return+ }+ type x struct{}+ out := protoimpl.TypeBuilder{+ File: protoimpl.DescBuilder{+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_pkg_apis_v1alpha1_ax_proto_rawDesc), len(file_pkg_apis_v1alpha1_ax_proto_rawDesc)),+ NumEnums: 0,+ NumMessages: 57,+ NumExtensions: 0,+ NumServices: 1,+ },+ GoTypes: file_pkg_apis_v1alpha1_ax_proto_goTypes,+ DependencyIndexes: file_pkg_apis_v1alpha1_ax_proto_depIdxs,+ MessageInfos: file_pkg_apis_v1alpha1_ax_proto_msgTypes,+ }.Build()+ File_pkg_apis_v1alpha1_ax_proto = out.File+ file_pkg_apis_v1alpha1_ax_proto_goTypes = nil+ file_pkg_apis_v1alpha1_ax_proto_depIdxs = nil+}diff --git a/pkg/apis/v1alpha1/ax.proto b/pkg/apis/v1alpha1/ax.protonew file mode 100644index 0000000..62bd57a--- /dev/null+++ b/pkg/apis/v1alpha1/ax.proto@@ -0,0 +1,387 @@+// 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.++syntax = "proto3";++package ax.v1alpha1;++import "google/protobuf/struct.proto";+import "google/protobuf/timestamp.proto";++option go_package = "github.com/google/ax/pkg/apis/v1alpha1";++// AX defines the core control plane gRPC service for autonomous agent orchestration.+service AX {+ // Manifests are parsed by the client (see `ax apply`) and submitted through the+ // typed Update* RPCs below; the server never receives raw YAML.++ // Tasks+ rpc GetTask(GetTaskRequest) returns (Task);+ rpc ListTasks(ListTasksRequest) returns (ListTasksResponse);+ rpc UpdateTask(UpdateTaskRequest) returns (Task);+ rpc DeleteTask(DeleteTaskRequest) returns (DeleteTaskResponse);+ rpc SuspendTask(SuspendTaskRequest) returns (Task);+ rpc ResumeTask(ResumeTaskRequest) returns (Task);+ rpc WatchTask(WatchTaskRequest) returns (stream WatchTaskResponse);++ // Gateways+ rpc GetGateway(GetGatewayRequest) returns (Gateway);+ rpc ListGateways(ListGatewaysRequest) returns (ListGatewaysResponse);+ rpc UpdateGateway(UpdateGatewayRequest) returns (Gateway);+ rpc DeleteGateway(DeleteGatewayRequest) returns (DeleteGatewayResponse);++ // Workspaces+ rpc GetWorkspace(GetWorkspaceRequest) returns (Workspace);+ rpc ListWorkspaces(ListWorkspacesRequest) returns (ListWorkspacesResponse);+ rpc UpdateWorkspace(UpdateWorkspaceRequest) returns (Workspace);+ rpc DeleteWorkspace(DeleteWorkspaceRequest) returns (DeleteWorkspaceResponse);++ // Models+ rpc GetModel(GetModelRequest) returns (Model);+ rpc ListModels(ListModelsRequest) returns (ListModelsResponse);+ rpc UpdateModel(UpdateModelRequest) returns (Model);+ rpc DeleteModel(DeleteModelRequest) returns (DeleteModelResponse);++}++// ObjectMeta is metadata for AX resources.+message ObjectMeta {+ string name = 1;+ string atespace = 2;+ google.protobuf.Timestamp creation_timestamp = 3;+}++// --- Task ---++message Task {+ string api_version = 1;+ string kind = 2;+ ObjectMeta metadata = 3;+ TaskSpec spec = 4;+ TaskStatus status = 5;+}++message TaskSpec {+ // Field 1 was `goal`, removed; the workspace goal lives on WorkspaceRef.+ reserved 1;+ reserved "goal";+ bool suspend = 2;+ string image = 3;+ repeated string command = 4;+ repeated EnvVar env = 5;+ ResourceReqs resources = 6;+ // workspaces binds one or more Workspaces, each mounted at its own path+ // under /workspace. The first entry is the task command's working directory.+ repeated WorkspaceRef workspaces = 7;+ GatewayRef gateway = 8;+ // Field 9 was `policies` (budget and approval config), removed for now.+ reserved 9;+ reserved "policies";+ // debug enables the in-container guest services (process execution and file+ // access) that back `ax ssh`. Off by default.+ bool debug = 10;+}++message EnvVar {+ string name = 1;+ string value = 2;+}++message ResourceReqs {+ ResourceList requests = 1;+ ResourceList limits = 2;+}++message ResourceList {+ string cpu = 1;+ string memory = 2;+}++message WorkspaceRef {+ string name = 1;+ string path = 2;+ string goal = 3;+}++message GatewayRef {+ string name = 1;+}++message TaskStatus {+ string phase = 1;+ string id = 2;+ string actor = 3;+ // json_name keeps the established `workerIP` spelling in YAML and JSON.+ string worker_ip = 4 [json_name = "workerIP"];+ PendingApproval pending_approval = 5;+ UsageStats usage = 6;+ repeated Condition conditions = 7;+}++message PendingApproval {+ string id = 1;+ string action = 2;+ google.protobuf.Timestamp requested_at = 3;+}++message UsageStats {+ int32 prompt_tokens = 1;+ int32 completion_tokens = 2;+}++message Condition {+ string type = 1;+ string status = 2;+ google.protobuf.Timestamp last_transition_time = 3;+ string reason = 4;+ string message = 5;+}++// --- Gateway ---++message Gateway {+ string api_version = 1;+ string kind = 2;+ ObjectMeta metadata = 3;+ GatewaySpec spec = 4;+}++message GatewaySpec {+ repeated Listener listeners = 1;+ EgressConfig egress = 2;+}++message Listener {+ string name = 1;+ int32 port = 2;+ string protocol = 3;+}++message EgressConfig {+ EgressAllowlist allowlist = 1;+}++message EgressAllowlist {+ repeated HostRule hosts = 1;+}++message HostRule {+ string host = 1;+ int32 port = 2;+}++// --- Workspace ---++message Workspace {+ string api_version = 1;+ string kind = 2;+ ObjectMeta metadata = 3;+ WorkspaceSpec spec = 4;+}++message WorkspaceSpec {+ repeated GitRepo git = 1;+ MCPConfig mcp = 2;+ SkillsConfig skills = 3;+}++message GitRepo {+ string name = 1;+ string repo = 2;+ string branch = 3;+ string dir = 4;+ int32 depth = 5;+}++message MCPConfig {+ repeated MCPRegistry registries = 1;+ repeated MCPServer servers = 2;+}++message MCPRegistry {+ string provider = 1;+ string project = 2;+ string query = 3;+ repeated MCPServer servers = 4;+}++message MCPServer {+ string name = 1;+ string endpoint = 2;+ string command = 3;+ repeated string args = 4;+}++message SkillsConfig {+ repeated SkillRegistry registries = 1;+ string path = 2;+}++message SkillRegistry {+ string provider = 1;+ string project = 2;+ string query = 3;+}++// --- Model ---++message Model {+ string api_version = 1;+ string kind = 2;+ ObjectMeta metadata = 3;+ ModelSpec spec = 4;+}++message ModelSpec {+ string provider = 1;+ string model = 2;+ // Fields 3-5 were typed temperature, max_tokens, and system_instruction;+ // provider settings now live in the free-form `parameters` map.+ reserved 3, 4, 5;+ reserved "temperature", "max_tokens", "system_instruction";+ SecretKeyRef secret_key = 6;+ // parameters are provider-specific generation settings passed through to the+ // model API as-is, for example temperature or maxOutputTokens for Gemini.+ google.protobuf.Struct parameters = 7;+}++message SecretKeyRef {+ string name = 1;+ string key = 2;+}++// --- RPC Request & Response Messages ---++// Tasks+message GetTaskRequest {+ string atespace = 1;+ string name = 2;+}++message ListTasksRequest {+ string atespace = 1;+ int64 limit = 2;+ int64 offset = 3;+}++message ListTasksResponse {+ repeated Task tasks = 1;+}++message UpdateTaskRequest {+ Task task = 1;+}++message DeleteTaskRequest {+ string atespace = 1;+ string name = 2;+}++message DeleteTaskResponse {}++message SuspendTaskRequest {+ string atespace = 1;+ string name = 2;+}++message ResumeTaskRequest {+ string atespace = 1;+ string name = 2;+}++message WatchTaskRequest {+ string atespace = 1;+ string name = 2;+}++message WatchTaskResponse {+ Task task = 1;+ string action = 2;+}++// Gateways+message GetGatewayRequest {+ string atespace = 1;+ string name = 2;+}++message ListGatewaysRequest {+ string atespace = 1;+}++message ListGatewaysResponse {+ repeated Gateway gateways = 1;+}++message UpdateGatewayRequest {+ Gateway gateway = 1;+}++message DeleteGatewayRequest {+ string atespace = 1;+ string name = 2;+}++message DeleteGatewayResponse {}++// Workspaces+message GetWorkspaceRequest {+ string atespace = 1;+ string name = 2;+}++message ListWorkspacesRequest {+ string atespace = 1;+}++message ListWorkspacesResponse {+ repeated Workspace workspaces = 1;+}++message UpdateWorkspaceRequest {+ Workspace workspace = 1;+}++message DeleteWorkspaceRequest {+ string atespace = 1;+ string name = 2;+}++message DeleteWorkspaceResponse {}++// Models+message GetModelRequest {+ string atespace = 1;+ string name = 2;+}++message ListModelsRequest {+ string atespace = 1;+}++message ListModelsResponse {+ repeated Model models = 1;+}++message UpdateModelRequest {+ Model model = 1;+}++message DeleteModelRequest {+ string atespace = 1;+ string name = 2;+}++message DeleteModelResponse {}+diff --git a/pkg/apis/v1alpha1/ax_grpc.pb.go b/pkg/apis/v1alpha1/ax_grpc.pb.gonew file mode 100644index 0000000..d106157--- /dev/null+++ b/pkg/apis/v1alpha1/ax_grpc.pb.go@@ -0,0 +1,835 @@+// 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.++// Code generated by protoc-gen-go-grpc. DO NOT EDIT.+// versions:+// - protoc-gen-go-grpc v1.6.0+// - protoc v7.34.1+// source: pkg/apis/v1alpha1/ax.proto++package v1alpha1++import (+ context "context"+ grpc "google.golang.org/grpc"+ codes "google.golang.org/grpc/codes"+ status "google.golang.org/grpc/status"+)++// This is a compile-time assertion to ensure that this generated file+// is compatible with the grpc package it is being compiled against.+// Requires gRPC-Go v1.64.0 or later.+const _ = grpc.SupportPackageIsVersion9++const (+ AX_GetTask_FullMethodName = "/ax.v1alpha1.AX/GetTask"+ AX_ListTasks_FullMethodName = "/ax.v1alpha1.AX/ListTasks"+ AX_UpdateTask_FullMethodName = "/ax.v1alpha1.AX/UpdateTask"+ AX_DeleteTask_FullMethodName = "/ax.v1alpha1.AX/DeleteTask"+ AX_SuspendTask_FullMethodName = "/ax.v1alpha1.AX/SuspendTask"+ AX_ResumeTask_FullMethodName = "/ax.v1alpha1.AX/ResumeTask"+ AX_WatchTask_FullMethodName = "/ax.v1alpha1.AX/WatchTask"+ AX_GetGateway_FullMethodName = "/ax.v1alpha1.AX/GetGateway"+ AX_ListGateways_FullMethodName = "/ax.v1alpha1.AX/ListGateways"+ AX_UpdateGateway_FullMethodName = "/ax.v1alpha1.AX/UpdateGateway"+ AX_DeleteGateway_FullMethodName = "/ax.v1alpha1.AX/DeleteGateway"+ AX_GetWorkspace_FullMethodName = "/ax.v1alpha1.AX/GetWorkspace"+ AX_ListWorkspaces_FullMethodName = "/ax.v1alpha1.AX/ListWorkspaces"+ AX_UpdateWorkspace_FullMethodName = "/ax.v1alpha1.AX/UpdateWorkspace"+ AX_DeleteWorkspace_FullMethodName = "/ax.v1alpha1.AX/DeleteWorkspace"+ AX_GetModel_FullMethodName = "/ax.v1alpha1.AX/GetModel"+ AX_ListModels_FullMethodName = "/ax.v1alpha1.AX/ListModels"+ AX_UpdateModel_FullMethodName = "/ax.v1alpha1.AX/UpdateModel"+ AX_DeleteModel_FullMethodName = "/ax.v1alpha1.AX/DeleteModel"+)++// AXClient is the client API for AX service.+//+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.+//+// AX defines the core control plane gRPC service for autonomous agent orchestration.+type AXClient interface {+ // Tasks+ GetTask(ctx context.Context, in *GetTaskRequest, opts ...grpc.CallOption) (*Task, error)+ ListTasks(ctx context.Context, in *ListTasksRequest, opts ...grpc.CallOption) (*ListTasksResponse, error)+ UpdateTask(ctx context.Context, in *UpdateTaskRequest, opts ...grpc.CallOption) (*Task, error)+ DeleteTask(ctx context.Context, in *DeleteTaskRequest, opts ...grpc.CallOption) (*DeleteTaskResponse, error)+ SuspendTask(ctx context.Context, in *SuspendTaskRequest, opts ...grpc.CallOption) (*Task, error)+ ResumeTask(ctx context.Context, in *ResumeTaskRequest, opts ...grpc.CallOption) (*Task, error)+ WatchTask(ctx context.Context, in *WatchTaskRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[WatchTaskResponse], error)+ // Gateways+ GetGateway(ctx context.Context, in *GetGatewayRequest, opts ...grpc.CallOption) (*Gateway, error)+ ListGateways(ctx context.Context, in *ListGatewaysRequest, opts ...grpc.CallOption) (*ListGatewaysResponse, error)+ UpdateGateway(ctx context.Context, in *UpdateGatewayRequest, opts ...grpc.CallOption) (*Gateway, error)+ DeleteGateway(ctx context.Context, in *DeleteGatewayRequest, opts ...grpc.CallOption) (*DeleteGatewayResponse, error)+ // Workspaces+ GetWorkspace(ctx context.Context, in *GetWorkspaceRequest, opts ...grpc.CallOption) (*Workspace, error)+ ListWorkspaces(ctx context.Context, in *ListWorkspacesRequest, opts ...grpc.CallOption) (*ListWorkspacesResponse, error)+ UpdateWorkspace(ctx context.Context, in *UpdateWorkspaceRequest, opts ...grpc.CallOption) (*Workspace, error)+ DeleteWorkspace(ctx context.Context, in *DeleteWorkspaceRequest, opts ...grpc.CallOption) (*DeleteWorkspaceResponse, error)+ // Models+ GetModel(ctx context.Context, in *GetModelRequest, opts ...grpc.CallOption) (*Model, error)+ ListModels(ctx context.Context, in *ListModelsRequest, opts ...grpc.CallOption) (*ListModelsResponse, error)+ UpdateModel(ctx context.Context, in *UpdateModelRequest, opts ...grpc.CallOption) (*Model, error)+ DeleteModel(ctx context.Context, in *DeleteModelRequest, opts ...grpc.CallOption) (*DeleteModelResponse, error)+}++type aXClient struct {+ cc grpc.ClientConnInterface+}++func NewAXClient(cc grpc.ClientConnInterface) AXClient {+ return &aXClient{cc}+}++func (c *aXClient) GetTask(ctx context.Context, in *GetTaskRequest, opts ...grpc.CallOption) (*Task, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Task)+ err := c.cc.Invoke(ctx, AX_GetTask_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) ListTasks(ctx context.Context, in *ListTasksRequest, opts ...grpc.CallOption) (*ListTasksResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(ListTasksResponse)+ err := c.cc.Invoke(ctx, AX_ListTasks_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) UpdateTask(ctx context.Context, in *UpdateTaskRequest, opts ...grpc.CallOption) (*Task, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Task)+ err := c.cc.Invoke(ctx, AX_UpdateTask_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) DeleteTask(ctx context.Context, in *DeleteTaskRequest, opts ...grpc.CallOption) (*DeleteTaskResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(DeleteTaskResponse)+ err := c.cc.Invoke(ctx, AX_DeleteTask_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) SuspendTask(ctx context.Context, in *SuspendTaskRequest, opts ...grpc.CallOption) (*Task, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Task)+ err := c.cc.Invoke(ctx, AX_SuspendTask_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) ResumeTask(ctx context.Context, in *ResumeTaskRequest, opts ...grpc.CallOption) (*Task, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Task)+ err := c.cc.Invoke(ctx, AX_ResumeTask_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) WatchTask(ctx context.Context, in *WatchTaskRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[WatchTaskResponse], error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ stream, err := c.cc.NewStream(ctx, &AX_ServiceDesc.Streams[0], AX_WatchTask_FullMethodName, cOpts...)+ if err != nil {+ return nil, err+ }+ x := &grpc.GenericClientStream[WatchTaskRequest, WatchTaskResponse]{ClientStream: stream}+ if err := x.ClientStream.SendMsg(in); err != nil {+ return nil, err+ }+ if err := x.ClientStream.CloseSend(); err != nil {+ return nil, err+ }+ return x, nil+}++// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.+type AX_WatchTaskClient = grpc.ServerStreamingClient[WatchTaskResponse]++func (c *aXClient) GetGateway(ctx context.Context, in *GetGatewayRequest, opts ...grpc.CallOption) (*Gateway, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Gateway)+ err := c.cc.Invoke(ctx, AX_GetGateway_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) ListGateways(ctx context.Context, in *ListGatewaysRequest, opts ...grpc.CallOption) (*ListGatewaysResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(ListGatewaysResponse)+ err := c.cc.Invoke(ctx, AX_ListGateways_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) UpdateGateway(ctx context.Context, in *UpdateGatewayRequest, opts ...grpc.CallOption) (*Gateway, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Gateway)+ err := c.cc.Invoke(ctx, AX_UpdateGateway_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) DeleteGateway(ctx context.Context, in *DeleteGatewayRequest, opts ...grpc.CallOption) (*DeleteGatewayResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(DeleteGatewayResponse)+ err := c.cc.Invoke(ctx, AX_DeleteGateway_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) GetWorkspace(ctx context.Context, in *GetWorkspaceRequest, opts ...grpc.CallOption) (*Workspace, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Workspace)+ err := c.cc.Invoke(ctx, AX_GetWorkspace_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) ListWorkspaces(ctx context.Context, in *ListWorkspacesRequest, opts ...grpc.CallOption) (*ListWorkspacesResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(ListWorkspacesResponse)+ err := c.cc.Invoke(ctx, AX_ListWorkspaces_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) UpdateWorkspace(ctx context.Context, in *UpdateWorkspaceRequest, opts ...grpc.CallOption) (*Workspace, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Workspace)+ err := c.cc.Invoke(ctx, AX_UpdateWorkspace_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) DeleteWorkspace(ctx context.Context, in *DeleteWorkspaceRequest, opts ...grpc.CallOption) (*DeleteWorkspaceResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(DeleteWorkspaceResponse)+ err := c.cc.Invoke(ctx, AX_DeleteWorkspace_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) GetModel(ctx context.Context, in *GetModelRequest, opts ...grpc.CallOption) (*Model, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Model)+ err := c.cc.Invoke(ctx, AX_GetModel_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) ListModels(ctx context.Context, in *ListModelsRequest, opts ...grpc.CallOption) (*ListModelsResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(ListModelsResponse)+ err := c.cc.Invoke(ctx, AX_ListModels_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) UpdateModel(ctx context.Context, in *UpdateModelRequest, opts ...grpc.CallOption) (*Model, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(Model)+ err := c.cc.Invoke(ctx, AX_UpdateModel_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *aXClient) DeleteModel(ctx context.Context, in *DeleteModelRequest, opts ...grpc.CallOption) (*DeleteModelResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(DeleteModelResponse)+ err := c.cc.Invoke(ctx, AX_DeleteModel_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++// AXServer is the server API for AX service.+// All implementations must embed UnimplementedAXServer+// for forward compatibility.+//+// AX defines the core control plane gRPC service for autonomous agent orchestration.+type AXServer interface {+ // Tasks+ GetTask(context.Context, *GetTaskRequest) (*Task, error)+ ListTasks(context.Context, *ListTasksRequest) (*ListTasksResponse, error)+ UpdateTask(context.Context, *UpdateTaskRequest) (*Task, error)+ DeleteTask(context.Context, *DeleteTaskRequest) (*DeleteTaskResponse, error)+ SuspendTask(context.Context, *SuspendTaskRequest) (*Task, error)+ ResumeTask(context.Context, *ResumeTaskRequest) (*Task, error)+ WatchTask(*WatchTaskRequest, grpc.ServerStreamingServer[WatchTaskResponse]) error+ // Gateways+ GetGateway(context.Context, *GetGatewayRequest) (*Gateway, error)+ ListGateways(context.Context, *ListGatewaysRequest) (*ListGatewaysResponse, error)+ UpdateGateway(context.Context, *UpdateGatewayRequest) (*Gateway, error)+ DeleteGateway(context.Context, *DeleteGatewayRequest) (*DeleteGatewayResponse, error)+ // Workspaces+ GetWorkspace(context.Context, *GetWorkspaceRequest) (*Workspace, error)+ ListWorkspaces(context.Context, *ListWorkspacesRequest) (*ListWorkspacesResponse, error)+ UpdateWorkspace(context.Context, *UpdateWorkspaceRequest) (*Workspace, error)+ DeleteWorkspace(context.Context, *DeleteWorkspaceRequest) (*DeleteWorkspaceResponse, error)+ // Models+ GetModel(context.Context, *GetModelRequest) (*Model, error)+ ListModels(context.Context, *ListModelsRequest) (*ListModelsResponse, error)+ UpdateModel(context.Context, *UpdateModelRequest) (*Model, error)+ DeleteModel(context.Context, *DeleteModelRequest) (*DeleteModelResponse, error)+ mustEmbedUnimplementedAXServer()+}++// UnimplementedAXServer must be embedded to have+// forward compatible implementations.+//+// NOTE: this should be embedded by value instead of pointer to avoid a nil+// pointer dereference when methods are called.+type UnimplementedAXServer struct{}++func (UnimplementedAXServer) GetTask(context.Context, *GetTaskRequest) (*Task, error) {+ return nil, status.Error(codes.Unimplemented, "method GetTask not implemented")+}+func (UnimplementedAXServer) ListTasks(context.Context, *ListTasksRequest) (*ListTasksResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method ListTasks not implemented")+}+func (UnimplementedAXServer) UpdateTask(context.Context, *UpdateTaskRequest) (*Task, error) {+ return nil, status.Error(codes.Unimplemented, "method UpdateTask not implemented")+}+func (UnimplementedAXServer) DeleteTask(context.Context, *DeleteTaskRequest) (*DeleteTaskResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method DeleteTask not implemented")+}+func (UnimplementedAXServer) SuspendTask(context.Context, *SuspendTaskRequest) (*Task, error) {+ return nil, status.Error(codes.Unimplemented, "method SuspendTask not implemented")+}+func (UnimplementedAXServer) ResumeTask(context.Context, *ResumeTaskRequest) (*Task, error) {+ return nil, status.Error(codes.Unimplemented, "method ResumeTask not implemented")+}+func (UnimplementedAXServer) WatchTask(*WatchTaskRequest, grpc.ServerStreamingServer[WatchTaskResponse]) error {+ return status.Error(codes.Unimplemented, "method WatchTask not implemented")+}+func (UnimplementedAXServer) GetGateway(context.Context, *GetGatewayRequest) (*Gateway, error) {+ return nil, status.Error(codes.Unimplemented, "method GetGateway not implemented")+}+func (UnimplementedAXServer) ListGateways(context.Context, *ListGatewaysRequest) (*ListGatewaysResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method ListGateways not implemented")+}+func (UnimplementedAXServer) UpdateGateway(context.Context, *UpdateGatewayRequest) (*Gateway, error) {+ return nil, status.Error(codes.Unimplemented, "method UpdateGateway not implemented")+}+func (UnimplementedAXServer) DeleteGateway(context.Context, *DeleteGatewayRequest) (*DeleteGatewayResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method DeleteGateway not implemented")+}+func (UnimplementedAXServer) GetWorkspace(context.Context, *GetWorkspaceRequest) (*Workspace, error) {+ return nil, status.Error(codes.Unimplemented, "method GetWorkspace not implemented")+}+func (UnimplementedAXServer) ListWorkspaces(context.Context, *ListWorkspacesRequest) (*ListWorkspacesResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method ListWorkspaces not implemented")+}+func (UnimplementedAXServer) UpdateWorkspace(context.Context, *UpdateWorkspaceRequest) (*Workspace, error) {+ return nil, status.Error(codes.Unimplemented, "method UpdateWorkspace not implemented")+}+func (UnimplementedAXServer) DeleteWorkspace(context.Context, *DeleteWorkspaceRequest) (*DeleteWorkspaceResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method DeleteWorkspace not implemented")+}+func (UnimplementedAXServer) GetModel(context.Context, *GetModelRequest) (*Model, error) {+ return nil, status.Error(codes.Unimplemented, "method GetModel not implemented")+}+func (UnimplementedAXServer) ListModels(context.Context, *ListModelsRequest) (*ListModelsResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method ListModels not implemented")+}+func (UnimplementedAXServer) UpdateModel(context.Context, *UpdateModelRequest) (*Model, error) {+ return nil, status.Error(codes.Unimplemented, "method UpdateModel not implemented")+}+func (UnimplementedAXServer) DeleteModel(context.Context, *DeleteModelRequest) (*DeleteModelResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method DeleteModel not implemented")+}+func (UnimplementedAXServer) mustEmbedUnimplementedAXServer() {}+func (UnimplementedAXServer) testEmbeddedByValue() {}++// UnsafeAXServer may be embedded to opt out of forward compatibility for this service.+// Use of this interface is not recommended, as added methods to AXServer will+// result in compilation errors.+type UnsafeAXServer interface {+ mustEmbedUnimplementedAXServer()+}++func RegisterAXServer(s grpc.ServiceRegistrar, srv AXServer) {+ // If the following call panics, it indicates UnimplementedAXServer was+ // embedded by pointer and is nil. This will cause panics if an+ // unimplemented method is ever invoked, so we test this at initialization+ // time to prevent it from happening at runtime later due to I/O.+ if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {+ t.testEmbeddedByValue()+ }+ s.RegisterService(&AX_ServiceDesc, srv)+}++func _AX_GetTask_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(GetTaskRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).GetTask(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_GetTask_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).GetTask(ctx, req.(*GetTaskRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_ListTasks_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(ListTasksRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).ListTasks(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_ListTasks_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).ListTasks(ctx, req.(*ListTasksRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_UpdateTask_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(UpdateTaskRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).UpdateTask(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_UpdateTask_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).UpdateTask(ctx, req.(*UpdateTaskRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_DeleteTask_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(DeleteTaskRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).DeleteTask(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_DeleteTask_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).DeleteTask(ctx, req.(*DeleteTaskRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_SuspendTask_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(SuspendTaskRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).SuspendTask(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_SuspendTask_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).SuspendTask(ctx, req.(*SuspendTaskRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_ResumeTask_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(ResumeTaskRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).ResumeTask(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_ResumeTask_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).ResumeTask(ctx, req.(*ResumeTaskRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_WatchTask_Handler(srv interface{}, stream grpc.ServerStream) error {+ m := new(WatchTaskRequest)+ if err := stream.RecvMsg(m); err != nil {+ return err+ }+ return srv.(AXServer).WatchTask(m, &grpc.GenericServerStream[WatchTaskRequest, WatchTaskResponse]{ServerStream: stream})+}++// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.+type AX_WatchTaskServer = grpc.ServerStreamingServer[WatchTaskResponse]++func _AX_GetGateway_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(GetGatewayRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).GetGateway(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_GetGateway_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).GetGateway(ctx, req.(*GetGatewayRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_ListGateways_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(ListGatewaysRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).ListGateways(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_ListGateways_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).ListGateways(ctx, req.(*ListGatewaysRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_UpdateGateway_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(UpdateGatewayRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).UpdateGateway(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_UpdateGateway_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).UpdateGateway(ctx, req.(*UpdateGatewayRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_DeleteGateway_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(DeleteGatewayRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).DeleteGateway(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_DeleteGateway_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).DeleteGateway(ctx, req.(*DeleteGatewayRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_GetWorkspace_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(GetWorkspaceRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).GetWorkspace(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_GetWorkspace_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).GetWorkspace(ctx, req.(*GetWorkspaceRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_ListWorkspaces_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(ListWorkspacesRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).ListWorkspaces(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_ListWorkspaces_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).ListWorkspaces(ctx, req.(*ListWorkspacesRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_UpdateWorkspace_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(UpdateWorkspaceRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).UpdateWorkspace(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_UpdateWorkspace_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).UpdateWorkspace(ctx, req.(*UpdateWorkspaceRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_DeleteWorkspace_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(DeleteWorkspaceRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).DeleteWorkspace(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_DeleteWorkspace_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).DeleteWorkspace(ctx, req.(*DeleteWorkspaceRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_GetModel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(GetModelRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).GetModel(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_GetModel_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).GetModel(ctx, req.(*GetModelRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_ListModels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(ListModelsRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).ListModels(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_ListModels_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).ListModels(ctx, req.(*ListModelsRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_UpdateModel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(UpdateModelRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).UpdateModel(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_UpdateModel_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).UpdateModel(ctx, req.(*UpdateModelRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _AX_DeleteModel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(DeleteModelRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AXServer).DeleteModel(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AX_DeleteModel_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AXServer).DeleteModel(ctx, req.(*DeleteModelRequest))+ }+ return interceptor(ctx, in, info, handler)+}++// AX_ServiceDesc is the grpc.ServiceDesc for AX service.+// It's only intended for direct use with grpc.RegisterService,+// and not to be introspected or modified (even as a copy)+var AX_ServiceDesc = grpc.ServiceDesc{+ ServiceName: "ax.v1alpha1.AX",+ HandlerType: (*AXServer)(nil),+ Methods: []grpc.MethodDesc{+ {+ MethodName: "GetTask",+ Handler: _AX_GetTask_Handler,+ },+ {+ MethodName: "ListTasks",+ Handler: _AX_ListTasks_Handler,+ },+ {+ MethodName: "UpdateTask",+ Handler: _AX_UpdateTask_Handler,+ },+ {+ MethodName: "DeleteTask",+ Handler: _AX_DeleteTask_Handler,+ },+ {+ MethodName: "SuspendTask",+ Handler: _AX_SuspendTask_Handler,+ },+ {+ MethodName: "ResumeTask",+ Handler: _AX_ResumeTask_Handler,+ },+ {+ MethodName: "GetGateway",+ Handler: _AX_GetGateway_Handler,+ },+ {+ MethodName: "ListGateways",+ Handler: _AX_ListGateways_Handler,+ },+ {+ MethodName: "UpdateGateway",+ Handler: _AX_UpdateGateway_Handler,+ },+ {+ MethodName: "DeleteGateway",+ Handler: _AX_DeleteGateway_Handler,+ },+ {+ MethodName: "GetWorkspace",+ Handler: _AX_GetWorkspace_Handler,+ },+ {+ MethodName: "ListWorkspaces",+ Handler: _AX_ListWorkspaces_Handler,+ },+ {+ MethodName: "UpdateWorkspace",+ Handler: _AX_UpdateWorkspace_Handler,+ },+ {+ MethodName: "DeleteWorkspace",+ Handler: _AX_DeleteWorkspace_Handler,+ },+ {+ MethodName: "GetModel",+ Handler: _AX_GetModel_Handler,+ },+ {+ MethodName: "ListModels",+ Handler: _AX_ListModels_Handler,+ },+ {+ MethodName: "UpdateModel",+ Handler: _AX_UpdateModel_Handler,+ },+ {+ MethodName: "DeleteModel",+ Handler: _AX_DeleteModel_Handler,+ },+ },+ Streams: []grpc.StreamDesc{+ {+ StreamName: "WatchTask",+ Handler: _AX_WatchTask_Handler,+ ServerStreams: true,+ },+ },+ Metadata: "pkg/apis/v1alpha1/ax.proto",+}diff --git a/pkg/apis/v1alpha1/types.go b/pkg/apis/v1alpha1/types.gonew file mode 100644index 0000000..a65e626--- /dev/null+++ b/pkg/apis/v1alpha1/types.go@@ -0,0 +1,281 @@+// 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 v1alpha1++import (+ "bytes"+ "encoding/json"+ "fmt"+ "strconv"+ "strings"+ "time"++ "google.golang.org/protobuf/encoding/protojson"+ "google.golang.org/protobuf/proto"+ "gopkg.in/yaml.v3"+)++const (+ APIVersion = "ax.io/v1alpha1"+ KindTask = "Task"+ KindGateway = "Gateway"+ KindWorkspace = "Workspace"+ KindModel = "Model"++ DefaultTaskImage = "gcr.io/ax-substrate/ate-images/ax-task-runner"++ // PhaseTerminating marks a task whose deletion has been requested and whose+ // actor is being torn down. The record disappears once cleanup completes.+ PhaseTerminating = "Terminating"+)++// YAML encoding.+//+// The API kinds are protobuf messages, so protojson is the single source of+// truth for their wire names (lowerCamelCase), timestamp format (RFC 3339), and+// which fields are omitted when unset. YAML is bridged through it: manifests are+// decoded generically, converted to JSON, and then decoded strictly by protojson,+// so unknown or misspelled fields are rejected. Output is protojson rendered as+// a yaml.Node so field order follows the proto definition instead of being+// sorted.+//+// A few legacy manifest shapes are still accepted. They are rewritten on the+// generic document before strict decoding by the per-kind normalizers below.++var (+ protoMarshal = protojson.MarshalOptions{}+ protoUnmarshal = protojson.UnmarshalOptions{} // unknown fields are errors+)++// normalizer rewrites a generically decoded document in place so legacy shapes+// match the current schema before strict decoding.+type normalizer func(doc map[string]any)++func marshalYAML(m proto.Message) (any, error) {+ data, err := protoMarshal.Marshal(m)+ if err != nil {+ return nil, err+ }+ return jsonToYAMLNode(data)+}++func unmarshalYAML(value *yaml.Node, m proto.Message, normalize normalizer) error {+ var doc any+ if err := value.Decode(&doc); err != nil {+ return err+ }+ if obj, ok := doc.(map[string]any); ok && normalize != nil {+ normalize(obj)+ }+ data, err := json.Marshal(doc)+ if err != nil {+ return fmt.Errorf("converting yaml to json: %w", err)+ }+ return protoUnmarshal.Unmarshal(data, m)+}++// jsonToYAMLNode converts a JSON document into a yaml.Node tree, preserving+// object key order and tagging scalars so the YAML encoder quotes strings that+// would otherwise read as another type (for example a status of "True").+func jsonToYAMLNode(data []byte) (*yaml.Node, error) {+ dec := json.NewDecoder(bytes.NewReader(data))+ dec.UseNumber()+ return readJSONValue(dec)+}++func readJSONValue(dec *json.Decoder) (*yaml.Node, error) {+ tok, err := dec.Token()+ if err != nil {+ return nil, err+ }+ switch v := tok.(type) {+ case json.Delim:+ switch v {+ case '{':+ n := &yaml.Node{Kind: yaml.MappingNode}+ for dec.More() {+ keyTok, err := dec.Token()+ if err != nil {+ return nil, err+ }+ key, _ := keyTok.(string)+ val, err := readJSONValue(dec)+ if err != nil {+ return nil, err+ }+ n.Content = append(n.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key}, val)+ }+ _, err = dec.Token() // closing '}'+ return n, err+ case '[':+ n := &yaml.Node{Kind: yaml.SequenceNode}+ for dec.More() {+ val, err := readJSONValue(dec)+ if err != nil {+ return nil, err+ }+ n.Content = append(n.Content, val)+ }+ _, err = dec.Token() // closing ']'+ return n, err+ }+ return nil, fmt.Errorf("unexpected json delimiter %q", v)+ case string:+ // protojson renders timestamps as RFC 3339 strings. Let those stay plain+ // scalars, which YAML reads as timestamps; every other string is tagged so+ // values like "True" or "1" are quoted and read back as strings.+ tag := "!!str"+ if _, err := time.Parse(time.RFC3339Nano, v); err == nil {+ tag = "!!timestamp"+ }+ return &yaml.Node{Kind: yaml.ScalarNode, Tag: tag, Value: v}, nil+ case json.Number:+ tag := "!!int"+ if strings.ContainsAny(v.String(), ".eE") {+ tag = "!!float"+ }+ return &yaml.Node{Kind: yaml.ScalarNode, Tag: tag, Value: v.String()}, nil+ case bool:+ return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!bool", Value: strconv.FormatBool(v)}, nil+ case nil:+ return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!null", Value: "null"}, nil+ }+ return nil, fmt.Errorf("unexpected json token %v", tok)+}++// Legacy manifest shapes.++// normalizeWorkspace accepts spec.mcp written as a bare list of servers.+func normalizeWorkspace(doc map[string]any) {+ spec, _ := doc["spec"].(map[string]any)+ if list, ok := spec["mcp"].([]any); ok {+ spec["mcp"] = map[string]any{"servers": list}+ }+}++// normalizeModel accepts older spellings of the secret reference: spec.secretKeyRef,+// spec.apiKey.secretKeyRef, and a bare string meaning the secret name and key are+// the same.+func normalizeModel(doc map[string]any) {+ spec, ok := doc["spec"].(map[string]any)+ if !ok {+ return+ }+ if _, has := spec["secretKey"]; !has {+ if ref, ok := spec["secretKeyRef"]; ok {+ spec["secretKey"] = ref+ } else if apiKey, ok := spec["apiKey"].(map[string]any); ok {+ if ref, ok := apiKey["secretKeyRef"]; ok {+ spec["secretKey"] = ref+ }+ }+ }+ delete(spec, "secretKeyRef")+ delete(spec, "apiKey")+ if s, ok := spec["secretKey"].(string); ok {+ spec["secretKey"] = map[string]any{"name": s, "key": s}+ }+}++// Per-kind YAML methods. Nested messages are handled by protojson as part of+// their parent, so only the kinds that are encoded on their own need these.++func (t *Task) MarshalYAML() (any, error) { return marshalYAML(t) }+func (t *Task) UnmarshalYAML(n *yaml.Node) error { return unmarshalYAML(n, t, nil) }++func (g *Gateway) MarshalYAML() (any, error) { return marshalYAML(g) }+func (g *Gateway) UnmarshalYAML(n *yaml.Node) error { return unmarshalYAML(n, g, nil) }++func (w *Workspace) MarshalYAML() (any, error) { return marshalYAML(w) }+func (w *Workspace) UnmarshalYAML(n *yaml.Node) error { return unmarshalYAML(n, w, normalizeWorkspace) }++func (m *Model) MarshalYAML() (any, error) { return marshalYAML(m) }+func (m *Model) UnmarshalYAML(n *yaml.Node) error { return unmarshalYAML(n, m, normalizeModel) }++// Workspace bindings.+//+// A task binds one or more workspaces through spec.workspaces. Every entry is+// treated the same way regardless of how many there are.++// DefaultWorkspacePath is the durable volume every workspace lives under. A+// binding without a path is mounted at DefaultWorkspacePath/<name>, and a task+// with no bindings gets an empty working directory at DefaultWorkspacePath.+const DefaultWorkspacePath = "/workspace"++// WorkspaceRefs returns the workspaces the task binds, in declaration order,+// with nil entries dropped.+func (s *TaskSpec) WorkspaceRefs() []*WorkspaceRef {+ if s == nil {+ return nil+ }+ out := make([]*WorkspaceRef, 0, len(s.GetWorkspaces()))+ for _, r := range s.GetWorkspaces() {+ if r != nil {+ out = append(out, r)+ }+ }+ return out+}++// WorkspacePaths returns the mount path of each workspace in WorkspaceRefs, in+// the same order. An explicit path wins; otherwise the workspace lands at+// DefaultWorkspacePath/<name>.+func (s *TaskSpec) WorkspacePaths() []string {+ refs := s.WorkspaceRefs()+ paths := make([]string, len(refs))+ for i, r := range refs {+ if r.GetPath() != "" {+ paths[i] = r.GetPath()+ } else {+ paths[i] = DefaultWorkspacePath + "/" + r.GetName()+ }+ }+ return paths+}++// ValidateTask reports the first problem with a task's spec that would make it+// impossible to run correctly. It is called by the API server before saving.+func ValidateTask(t *Task) error {+ spec := t.GetSpec()+ if spec == nil {+ return nil+ }+ refs := spec.WorkspaceRefs()+ paths := spec.WorkspacePaths()+ names := make(map[string]bool, len(refs))+ seen := make(map[string]string, len(refs))+ for i, r := range refs {+ field := fmt.Sprintf("spec.workspaces[%d]", i)+ if r.GetName() == "" {+ return fmt.Errorf("%s: name is required", field)+ }+ if names[r.GetName()] {+ return fmt.Errorf("%s: workspace %q is bound more than once", field, r.GetName())+ }+ names[r.GetName()] = true+ if r.GetPath() != "" && !strings.HasPrefix(r.GetPath(), "/") {+ return fmt.Errorf("%s: path %q must be absolute", field, r.GetPath())+ }+ p := strings.TrimRight(paths[i], "/")+ if p == "" {+ p = "/"+ }+ if other, dup := seen[p]; dup {+ return fmt.Errorf("%s: path %q is already used by workspace %q", field, paths[i], other)+ }+ seen[p] = r.GetName()+ }+ return nil+}diff --git a/pkg/apis/v1alpha1/types_test.go b/pkg/apis/v1alpha1/types_test.gonew file mode 100644index 0000000..83deaa4--- /dev/null+++ b/pkg/apis/v1alpha1/types_test.go@@ -0,0 +1,499 @@+// 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 v1alpha1_test++import (+ "strings"+ "testing"+ "time"++ "github.com/google/ax/pkg/apis/v1alpha1"+ "google.golang.org/protobuf/proto"+ "google.golang.org/protobuf/types/known/structpb"+ "google.golang.org/protobuf/types/known/timestamppb"+ "gopkg.in/yaml.v3"+)++// fullTask returns a Task with every field populated so round trips exercise+// the whole schema, including timestamps and status.+func fullTask() *v1alpha1.Task {+ return &v1alpha1.Task{+ ApiVersion: v1alpha1.APIVersion,+ Kind: v1alpha1.KindTask,+ Metadata: &v1alpha1.ObjectMeta{+ Name: "full",+ Atespace: "default",+ CreationTimestamp: timestamppb.New(time.Date(2026, 9, 19, 12, 0, 0, 0, time.UTC)),+ },+ Spec: &v1alpha1.TaskSpec{+ Suspend: true,+ Image: "example.com/img:1",+ Command: []string{"sh", "-c", "true"},+ Env: []*v1alpha1.EnvVar{{Name: "A", Value: "1"}},+ Resources: &v1alpha1.ResourceReqs{+ Requests: &v1alpha1.ResourceList{Cpu: "500m", Memory: "1Gi"},+ },+ Workspaces: []*v1alpha1.WorkspaceRef{{Name: "ws", Path: "/workspace", Goal: "build"}},+ Gateway: &v1alpha1.GatewayRef{Name: "gw"},+ Debug: true,+ },+ Status: &v1alpha1.TaskStatus{+ Phase: "Running",+ Id: "id-1",+ Actor: "actor-1",+ WorkerIp: "10.0.0.5:80",+ Conditions: []*v1alpha1.Condition{{+ Type: "Ready",+ Status: "True",+ Reason: "TaskRunning",+ Message: "ok",+ LastTransitionTime: timestamppb.New(time.Date(2026, 9, 19, 12, 5, 0, 0, time.UTC)),+ }},+ },+ }+}++func TestTask_RoundTrip(t *testing.T) {+ want := fullTask()+ out, err := yaml.Marshal(want)+ if err != nil {+ t.Fatal(err)+ }+ var got v1alpha1.Task+ if err := yaml.Unmarshal(out, &got); err != nil {+ t.Fatalf("unmarshal: %v\n%s", err, out)+ }+ if !proto.Equal(want, &got) {+ t.Errorf("yaml round trip changed the task\n%s", out)+ }+}++func TestTask_YAMLFieldNames(t *testing.T) {+ out, err := yaml.Marshal(fullTask())+ if err != nil {+ t.Fatal(err)+ }+ for _, want := range []string{"workerIP: 10.0.0.5:80", "lastTransitionTime: 2026-09-19T12:05:00Z", "creationTimestamp: 2026-09-19T12:00:00Z"} {+ if !strings.Contains(string(out), want) {+ t.Errorf("yaml missing %s:\n%s", want, out)+ }+ }+}++func TestTask_YAMLOutputShape(t *testing.T) {+ out, err := yaml.Marshal(fullTask())+ if err != nil {+ t.Fatal(err)+ }+ s := string(out)++ // Top-level keys follow the proto definition, not alphabetical order.+ order := []string{"apiVersion:", "kind:", "metadata:", "spec:", "status:"}+ last := -1+ for _, key := range order {+ idx := strings.Index(s, "\n"+key)+ if key == "apiVersion:" {+ idx = strings.Index(s, key)+ }+ if idx < 0 || idx < last {+ t.Errorf("expected %s in proto order, got:\n%s", key, s)+ }+ last = idx+ }++ // Strings that look like other types are quoted so they read back as strings.+ if !strings.Contains(s, `status: "True"`) {+ t.Errorf("expected condition status to be quoted:\n%s", s)+ }+ // Unset fields are omitted rather than rendered as null.+ if strings.Contains(s, "null") {+ t.Errorf("expected no null values:\n%s", s)+ }+}++func TestStrictDecoding_RejectsUnknownFields(t *testing.T) {+ var task v1alpha1.Task+ err := yaml.Unmarshal([]byte("kind: Task\nspec:\n imgae: typo\n"), &task)+ if err == nil || !strings.Contains(err.Error(), "imgae") {+ t.Errorf("expected error naming the unknown field, got %v", err)+ }++ var gw v1alpha1.Gateway+ err = yaml.Unmarshal([]byte("kind: Gateway\nspec:\n egress:\n allowlst: {}\n"), &gw)+ if err == nil || !strings.Contains(err.Error(), "allowlst") {+ t.Errorf("expected error naming the nested unknown field, got %v", err)+ }+}++func TestGateway_RoundTrip(t *testing.T) {+ want := &v1alpha1.Gateway{+ ApiVersion: v1alpha1.APIVersion,+ Kind: v1alpha1.KindGateway,+ Metadata: &v1alpha1.ObjectMeta{Name: "gw", Atespace: "default"},+ Spec: &v1alpha1.GatewaySpec{+ Listeners: []*v1alpha1.Listener{{Name: "http", Port: 8080, Protocol: "HTTP"}},+ Egress: &v1alpha1.EgressConfig{Allowlist: &v1alpha1.EgressAllowlist{+ Hosts: []*v1alpha1.HostRule{{Host: "*", Port: 443}},+ }},+ },+ }+ out, err := yaml.Marshal(want)+ if err != nil {+ t.Fatal(err)+ }+ var got v1alpha1.Gateway+ if err := yaml.Unmarshal(out, &got); err != nil {+ t.Fatal(err)+ }+ if !proto.Equal(want, &got) {+ t.Errorf("gateway round trip changed:\n%s", out)+ }+ if !strings.Contains(string(out), "port: 8080") {+ t.Errorf("expected integer port to render unquoted:\n%s", out)+ }+}++func TestWorkspace_MCP_UnmarshalYAML(t *testing.T) {+ // Legacy: spec.mcp as a bare list of servers.+ flatYAML := `+kind: Workspace+spec:+ mcp:+ - name: tool-1+ endpoint: "http://tool-1:8080"+ - name: tool-2+ command: "npx"+ args: ["-y", "@modelcontextprotocol/server"]+`+ var flatWS v1alpha1.Workspace+ if err := yaml.Unmarshal([]byte(flatYAML), &flatWS); err != nil {+ t.Fatalf("unmarshaling flat mcp: %v", err)+ }+ if len(flatWS.Spec.Mcp.GetServers()) != 2 || flatWS.Spec.Mcp.Servers[0].Name != "tool-1" {+ t.Fatalf("unexpected servers from flat list: %+v", flatWS.Spec.Mcp)+ }++ // Current: registries and servers, including a static registry with nested servers.+ structuredYAML := `+kind: Workspace+spec:+ mcp:+ registries:+ - provider: google+ query: "mcp.tags:git"+ - provider: static+ servers:+ - name: git-tools+ endpoint: "http://git-mcp.default.svc.cluster.local:8080"+ servers:+ - name: tool-1+ endpoint: "http://tool-1:8080"+`+ var ws v1alpha1.Workspace+ if err := yaml.Unmarshal([]byte(structuredYAML), &ws); err != nil {+ t.Fatalf("unmarshaling structured mcp: %v", err)+ }+ if len(ws.Spec.Mcp.Registries) != 2 || ws.Spec.Mcp.Registries[0].Query != "mcp.tags:git" {+ t.Errorf("unexpected registries: %+v", ws.Spec.Mcp.Registries)+ }+ if got := ws.Spec.Mcp.Registries[1]; got.Provider != "static" || len(got.Servers) != 1 || got.Servers[0].Name != "git-tools" {+ t.Errorf("unexpected static registry: %+v", got)+ }+ if len(ws.Spec.Mcp.Servers) != 1 {+ t.Errorf("unexpected servers: %+v", ws.Spec.Mcp.Servers)+ }+}++func TestWorkspace_RoundTrip(t *testing.T) {+ wsYAML := `+apiVersion: ax.io/v1alpha1+kind: Workspace+metadata:+ name: full-ws+ atespace: default+spec:+ git:+ - name: origin+ repo: "https://github.com/chalk/chalk.git"+ branch: "main"+ dir: chalk+ depth: 1+ mcp:+ registries:+ - provider: google+ query: "mcp.tags:build"+ skills:+ registries:+ - provider: google+ query: "skills.tags:golang"+ path: "/.agents/skills"+`+ var ws v1alpha1.Workspace+ if err := yaml.Unmarshal([]byte(wsYAML), &ws); err != nil {+ t.Fatalf("unmarshaling workspace: %v", err)+ }+ if ws.Spec.Git[0].Depth != 1 || ws.Spec.Skills.Path != "/.agents/skills" {+ t.Fatalf("unexpected workspace: %+v", ws.Spec)+ }++ out, err := yaml.Marshal(&ws)+ if err != nil {+ t.Fatal(err)+ }+ var again v1alpha1.Workspace+ if err := yaml.Unmarshal(out, &again); err != nil {+ t.Fatal(err)+ }+ if !proto.Equal(&ws, &again) {+ t.Errorf("workspace round trip changed:\n%s", out)+ }+}++// The original schema bound a single workspace under spec.workspace. That field+// is gone, so manifests still using it are rejected like any unknown field.+func TestTask_SingularWorkspace_Rejected(t *testing.T) {+ taskYAML := `+apiVersion: ax.io/v1alpha1+kind: Task+metadata:+ name: test-task+spec:+ workspace:+ name: default-workspace+`+ var task v1alpha1.Task+ err := yaml.Unmarshal([]byte(taskYAML), &task)+ if err == nil || !strings.Contains(err.Error(), "workspace") {+ t.Fatalf("expected spec.workspace to be rejected as unknown, got %v", err)+ }+}++func TestModel_SecretKey_UnmarshalYAML(t *testing.T) {+ cases := map[string]string{+ "structured": `+spec:+ provider: google+ secretKey:+ name: the-secret+ key: the-key+`,+ "legacy secretKeyRef": `+spec:+ provider: google+ secretKeyRef:+ name: the-secret+ key: the-key+`,+ "legacy apiKey.secretKeyRef": `+spec:+ provider: google+ apiKey:+ secretKeyRef:+ name: the-secret+ key: the-key+`,+ }+ for name, src := range cases {+ t.Run(name, func(t *testing.T) {+ var m v1alpha1.Model+ if err := yaml.Unmarshal([]byte("kind: Model\n"+src), &m); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ if got := m.Spec.GetSecretKey(); got.GetName() != "the-secret" || got.GetKey() != "the-key" {+ t.Errorf("unexpected secretKey: %+v", got)+ }+ })+ }++ t.Run("legacy bare string", func(t *testing.T) {+ var m v1alpha1.Model+ if err := yaml.Unmarshal([]byte("kind: Model\nspec:\n provider: google\n secretKey: GEMINI_API_KEY\n"), &m); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ if got := m.Spec.GetSecretKey(); got.GetName() != "GEMINI_API_KEY" || got.GetKey() != "GEMINI_API_KEY" {+ t.Errorf("unexpected secretKey: %+v", got)+ }+ })+}++func TestModel_RoundTrip(t *testing.T) {+ want := &v1alpha1.Model{+ ApiVersion: v1alpha1.APIVersion,+ Kind: v1alpha1.KindModel,+ Metadata: &v1alpha1.ObjectMeta{Name: "m", Atespace: "default"},+ Spec: &v1alpha1.ModelSpec{+ Provider: "google",+ Model: "gemini-3.8-flash",+ SecretKey: &v1alpha1.SecretKeyRef{Name: "gemini-api-secret", Key: "GEMINI_API_KEY"},+ Parameters: mustStruct(t, map[string]any{+ "temperature": 0.2,+ "maxOutputTokens": 4096,+ "systemInstruction": "be brief",+ "stopSequences": []any{"END"},+ }),+ },+ }+ out, err := yaml.Marshal(want)+ if err != nil {+ t.Fatal(err)+ }+ var got v1alpha1.Model+ if err := yaml.Unmarshal(out, &got); err != nil {+ t.Fatalf("unmarshal: %v\n%s", err, out)+ }+ if !proto.Equal(want, &got) {+ t.Errorf("model round trip changed:\n%s", out)+ }+ for _, want := range []string{"temperature: 0.2", "maxOutputTokens: 4096", "- END"} {+ if !strings.Contains(string(out), want) {+ t.Errorf("expected %q in parameters output:\n%s", want, out)+ }+ }+}++func mustStruct(t *testing.T, m map[string]any) *structpb.Struct {+ t.Helper()+ s, err := structpb.NewStruct(m)+ if err != nil {+ t.Fatal(err)+ }+ return s+}++func TestTaskSpec_WorkspaceRefs(t *testing.T) {+ single := &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "one"}}}+ if refs := single.WorkspaceRefs(); len(refs) != 1 || refs[0].Name != "one" {+ t.Errorf("single: refs = %v", refs)+ }+ if paths := single.WorkspacePaths(); len(paths) != 1 || paths[0] != v1alpha1.DefaultWorkspacePath+"/one" {+ t.Errorf("single: paths = %v, want [%s/one]", paths, v1alpha1.DefaultWorkspacePath)+ }++ multi := &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{+ {Name: "code"},+ nil,+ {Name: "tools", Path: "/opt/tools"},+ }}+ refs := multi.WorkspaceRefs()+ if len(refs) != 2 || refs[0].Name != "code" || refs[1].Name != "tools" {+ t.Errorf("multi: refs = %v", refs)+ }+ if paths := multi.WorkspacePaths(); len(paths) != 2 || paths[0] != "/workspace/code" || paths[1] != "/opt/tools" {+ t.Errorf("multi: paths = %v", paths)+ }++ var nilSpec *v1alpha1.TaskSpec+ if refs := nilSpec.WorkspaceRefs(); len(refs) != 0 {+ t.Errorf("nil spec: refs = %v", refs)+ }+ if paths := (&v1alpha1.TaskSpec{}).WorkspacePaths(); len(paths) != 0 {+ t.Errorf("empty spec: paths = %v", paths)+ }+}++func TestValidateTask(t *testing.T) {+ tests := []struct {+ name string+ spec *v1alpha1.TaskSpec+ wantErr string+ }{+ {name: "nil spec"},+ {name: "no workspaces", spec: &v1alpha1.TaskSpec{}},+ {name: "list of one", spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a"}}}},+ {+ name: "nameless entry with path",+ spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Path: "/w"}}},+ wantErr: "spec.workspaces[0]: name is required",+ },+ {name: "list default paths", spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a"}, {Name: "b"}}}},+ {name: "list explicit paths", spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a", Path: "/x"}, {Name: "b", Path: "/y"}}}},+ {+ name: "nameless entry in list",+ spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a"}, {Path: "/b"}}},+ wantErr: "spec.workspaces[1]: name is required",+ },+ {+ name: "duplicate name",+ spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a", Path: "/x"}, {Name: "a", Path: "/y"}}},+ wantErr: `workspace "a" is bound more than once`,+ },+ {+ name: "duplicate path",+ spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a", Path: "/same"}, {Name: "b", Path: "/same/"}}},+ wantErr: `path "/same/" is already used by workspace "a"`,+ },+ {+ name: "default path collides with explicit",+ spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a"}, {Name: "b", Path: "/workspace/a"}}},+ wantErr: "already used",+ },+ {+ name: "relative path",+ spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "a", Path: "rel"}}},+ wantErr: "spec.workspaces[0]: path \"rel\" must be absolute",+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := v1alpha1.ValidateTask(&v1alpha1.Task{Spec: tt.spec})+ if tt.wantErr == "" {+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ return+ }+ if err == nil || !strings.Contains(err.Error(), tt.wantErr) {+ t.Fatalf("error = %v, want containing %q", err, tt.wantErr)+ }+ })+ }+}++func TestTask_Workspaces_YAML(t *testing.T) {+ taskYAML := `+apiVersion: ax.io/v1alpha1+kind: Task+metadata:+ name: multi+spec:+ workspaces:+ - name: code+ goal: "build it"+ - name: tools+ path: /opt/tools+`+ var task v1alpha1.Task+ if err := yaml.Unmarshal([]byte(taskYAML), &task); err != nil {+ t.Fatalf("unmarshaling task: %v", err)+ }+ refs := task.Spec.WorkspaceRefs()+ if len(refs) != 2 || refs[0].Name != "code" || refs[0].Goal != "build it" || refs[1].Path != "/opt/tools" {+ t.Fatalf("unexpected refs: %v", refs)+ }+ out, err := yaml.Marshal(&task)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(out), "workspaces:") || strings.Contains(string(out), "\n workspace:") {+ t.Errorf("expected workspaces list and no singular workspace in output:\n%s", out)+ }+ var back v1alpha1.Task+ if err := yaml.Unmarshal(out, &back); err != nil {+ t.Fatalf("round trip: %v", err)+ }+ if !proto.Equal(&task, &back) {+ t.Errorf("round trip changed the task:\n%s", out)+ }+}diff --git a/proto/ax.pb.go b/proto/ax.pb.godeleted file mode 100644index 9603c37..0000000--- a/proto/ax.pb.go+++ /dev/null@@ -1,1764 +0,0 @@-// 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.--// Code generated by protoc-gen-go. DO NOT EDIT.-// versions:-// protoc-gen-go v1.36.11-// protoc v5.28.2-// source: proto/ax.proto--package proto--import (- protoreflect "google.golang.org/protobuf/reflect/protoreflect"- protoimpl "google.golang.org/protobuf/runtime/protoimpl"- structpb "google.golang.org/protobuf/types/known/structpb"- reflect "reflect"- sync "sync"- unsafe "unsafe"-)--const (- // Verify that this generated code is sufficiently up-to-date.- _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)- // Verify that runtime/protoimpl is sufficiently up-to-date.- _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)-)--// State represents the state of an execution-type State int32--const (- State_STATE_UNSPECIFIED State = 0 // Unspecified state- State_STATE_PENDING State = 1- State_STATE_FAILED State = 2- State_STATE_COMPLETED State = 3- State_STATE_CANCELED State = 4-)--// Enum value maps for State.-var (- State_name = map[int32]string{- 0: "STATE_UNSPECIFIED",- 1: "STATE_PENDING",- 2: "STATE_FAILED",- 3: "STATE_COMPLETED",- 4: "STATE_CANCELED",- }- State_value = map[string]int32{- "STATE_UNSPECIFIED": 0,- "STATE_PENDING": 1,- "STATE_FAILED": 2,- "STATE_COMPLETED": 3,- "STATE_CANCELED": 4,- }-)--func (x State) Enum() *State {- p := new(State)- *p = x- return p-}--func (x State) String() string {- return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))-}--func (State) Descriptor() protoreflect.EnumDescriptor {- return file_proto_ax_proto_enumTypes[0].Descriptor()-}--func (State) Type() protoreflect.EnumType {- return &file_proto_ax_proto_enumTypes[0]-}--func (x State) Number() protoreflect.EnumNumber {- return protoreflect.EnumNumber(x)-}--// Deprecated: Use State.Descriptor instead.-func (State) EnumDescriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{0}-}--// CancelReason explains why an in-flight execution is canceled.-type CancelReason int32--const (- CancelReason_CANCEL_REASON_UNSPECIFIED CancelReason = 0- CancelReason_CANCEL_REASON_USER_REQUESTED CancelReason = 1- CancelReason_CANCEL_REASON_TIMEOUT CancelReason = 2- CancelReason_CANCEL_REASON_INTERNAL_ERROR CancelReason = 3-)--// Enum value maps for CancelReason.-var (- CancelReason_name = map[int32]string{- 0: "CANCEL_REASON_UNSPECIFIED",- 1: "CANCEL_REASON_USER_REQUESTED",- 2: "CANCEL_REASON_TIMEOUT",- 3: "CANCEL_REASON_INTERNAL_ERROR",- }- CancelReason_value = map[string]int32{- "CANCEL_REASON_UNSPECIFIED": 0,- "CANCEL_REASON_USER_REQUESTED": 1,- "CANCEL_REASON_TIMEOUT": 2,- "CANCEL_REASON_INTERNAL_ERROR": 3,- }-)--func (x CancelReason) Enum() *CancelReason {- p := new(CancelReason)- *p = x- return p-}--func (x CancelReason) String() string {- return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))-}--func (CancelReason) Descriptor() protoreflect.EnumDescriptor {- return file_proto_ax_proto_enumTypes[1].Descriptor()-}--func (CancelReason) Type() protoreflect.EnumType {- return &file_proto_ax_proto_enumTypes[1]-}--func (x CancelReason) Number() protoreflect.EnumNumber {- return protoreflect.EnumNumber(x)-}--// Deprecated: Use CancelReason.Descriptor instead.-func (CancelReason) EnumDescriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{1}-}--// A conversation is the historical session that consist of-// a number of execution. A conversation cannot be continued-// before the last execution is completed or failed.-type StepEvent struct {- state protoimpl.MessageState `protogen:"open.v1"`- ConversationId string `protobuf:"bytes,1,opt,name=conversation_id,json=conversationId,proto3" json:"conversation_id,omitempty"`- InteractionId string `protobuf:"bytes,2,opt,name=interaction_id,json=interactionId,proto3" json:"interaction_id,omitempty"`- AgentId string `protobuf:"bytes,3,opt,name=agent_id,json=agentId,proto3" json:"agent_id,omitempty"`- AgentConfig *structpb.Struct `protobuf:"bytes,4,opt,name=agent_config,json=agentConfig,proto3" json:"agent_config,omitempty"`- Steps []*Step `protobuf:"bytes,5,rep,name=steps,proto3" json:"steps,omitempty"`- State State `protobuf:"varint,6,opt,name=state,proto3,enum=ax.State" json:"state,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *StepEvent) Reset() {- *x = StepEvent{}- mi := &file_proto_ax_proto_msgTypes[0]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *StepEvent) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*StepEvent) ProtoMessage() {}--func (x *StepEvent) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[0]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use StepEvent.ProtoReflect.Descriptor instead.-func (*StepEvent) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{0}-}--func (x *StepEvent) GetConversationId() string {- if x != nil {- return x.ConversationId- }- return ""-}--func (x *StepEvent) GetInteractionId() string {- if x != nil {- return x.InteractionId- }- return ""-}--func (x *StepEvent) GetAgentId() string {- if x != nil {- return x.AgentId- }- return ""-}--func (x *StepEvent) GetAgentConfig() *structpb.Struct {- if x != nil {- return x.AgentConfig- }- return nil-}--func (x *StepEvent) GetSteps() []*Step {- if x != nil {- return x.Steps- }- return nil-}--func (x *StepEvent) GetState() State {- if x != nil {- return x.State- }- return State_STATE_UNSPECIFIED-}--type HarnessStart struct {- state protoimpl.MessageState `protogen:"open.v1"`- // Per-execution agent configuration.- AgentConfig []byte `protobuf:"bytes,1,opt,name=agent_config,json=agentConfig,proto3" json:"agent_config,omitempty"`- Steps []*Step `protobuf:"bytes,2,rep,name=steps,proto3" json:"steps,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *HarnessStart) Reset() {- *x = HarnessStart{}- mi := &file_proto_ax_proto_msgTypes[1]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *HarnessStart) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*HarnessStart) ProtoMessage() {}--func (x *HarnessStart) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[1]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use HarnessStart.ProtoReflect.Descriptor instead.-func (*HarnessStart) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{1}-}--func (x *HarnessStart) GetAgentConfig() []byte {- if x != nil {- return x.AgentConfig- }- return nil-}--func (x *HarnessStart) GetSteps() []*Step {- if x != nil {- return x.Steps- }- return nil-}--// HarnessCancel aborts the in-flight harness execution.-type HarnessCancel struct {- state protoimpl.MessageState `protogen:"open.v1"`- Reason CancelReason `protobuf:"varint,1,opt,name=reason,proto3,enum=ax.CancelReason" json:"reason,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *HarnessCancel) Reset() {- *x = HarnessCancel{}- mi := &file_proto_ax_proto_msgTypes[2]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *HarnessCancel) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*HarnessCancel) ProtoMessage() {}--func (x *HarnessCancel) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[2]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use HarnessCancel.ProtoReflect.Descriptor instead.-func (*HarnessCancel) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{2}-}--func (x *HarnessCancel) GetReason() CancelReason {- if x != nil {- return x.Reason- }- return CancelReason_CANCEL_REASON_UNSPECIFIED-}--type HarnessRequest struct {- state protoimpl.MessageState `protogen:"open.v1"`- ConversationId string `protobuf:"bytes,1,opt,name=conversation_id,json=conversationId,proto3" json:"conversation_id,omitempty"`- AgentId string `protobuf:"bytes,2,opt,name=agent_id,json=agentId,proto3" json:"agent_id,omitempty"`- // Types that are valid to be assigned to Type:- //- // *HarnessRequest_Start- // *HarnessRequest_Cancel- Type isHarnessRequest_Type `protobuf_oneof:"type"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *HarnessRequest) Reset() {- *x = HarnessRequest{}- mi := &file_proto_ax_proto_msgTypes[3]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *HarnessRequest) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*HarnessRequest) ProtoMessage() {}--func (x *HarnessRequest) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[3]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use HarnessRequest.ProtoReflect.Descriptor instead.-func (*HarnessRequest) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{3}-}--func (x *HarnessRequest) GetConversationId() string {- if x != nil {- return x.ConversationId- }- return ""-}--func (x *HarnessRequest) GetAgentId() string {- if x != nil {- return x.AgentId- }- return ""-}--func (x *HarnessRequest) GetType() isHarnessRequest_Type {- if x != nil {- return x.Type- }- return nil-}--func (x *HarnessRequest) GetStart() *HarnessStart {- if x != nil {- if x, ok := x.Type.(*HarnessRequest_Start); ok {- return x.Start- }- }- return nil-}--func (x *HarnessRequest) GetCancel() *HarnessCancel {- if x != nil {- if x, ok := x.Type.(*HarnessRequest_Cancel); ok {- return x.Cancel- }- }- return nil-}--type isHarnessRequest_Type interface {- isHarnessRequest_Type()-}--type HarnessRequest_Start struct {- Start *HarnessStart `protobuf:"bytes,3,opt,name=start,proto3,oneof"`-}--type HarnessRequest_Cancel struct {- Cancel *HarnessCancel `protobuf:"bytes,4,opt,name=cancel,proto3,oneof"`-}--func (*HarnessRequest_Start) isHarnessRequest_Type() {}--func (*HarnessRequest_Cancel) isHarnessRequest_Type() {}--type HarnessOutputs struct {- state protoimpl.MessageState `protogen:"open.v1"`- Steps []*Step `protobuf:"bytes,1,rep,name=steps,proto3" json:"steps,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *HarnessOutputs) Reset() {- *x = HarnessOutputs{}- mi := &file_proto_ax_proto_msgTypes[4]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *HarnessOutputs) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*HarnessOutputs) ProtoMessage() {}--func (x *HarnessOutputs) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[4]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use HarnessOutputs.ProtoReflect.Descriptor instead.-func (*HarnessOutputs) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{4}-}--func (x *HarnessOutputs) GetSteps() []*Step {- if x != nil {- return x.Steps- }- return nil-}--type Error struct {- state protoimpl.MessageState `protogen:"open.v1"`- // A status code, corresponds to google.golang.org/grpc/codes.- Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"`- // A description of the error.- Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *Error) Reset() {- *x = Error{}- mi := &file_proto_ax_proto_msgTypes[5]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *Error) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*Error) ProtoMessage() {}--func (x *Error) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[5]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use Error.ProtoReflect.Descriptor instead.-func (*Error) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{5}-}--func (x *Error) GetCode() int32 {- if x != nil {- return x.Code- }- return 0-}--func (x *Error) GetDescription() string {- if x != nil {- return x.Description- }- return ""-}--type HarnessEnd struct {- state protoimpl.MessageState `protogen:"open.v1"`- // Terminal state for the harness execution.- State State `protobuf:"varint,1,opt,name=state,proto3,enum=ax.State" json:"state,omitempty"`- // Optional error details.- Error *Error `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *HarnessEnd) Reset() {- *x = HarnessEnd{}- mi := &file_proto_ax_proto_msgTypes[6]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *HarnessEnd) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*HarnessEnd) ProtoMessage() {}--func (x *HarnessEnd) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[6]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use HarnessEnd.ProtoReflect.Descriptor instead.-func (*HarnessEnd) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{6}-}--func (x *HarnessEnd) GetState() State {- if x != nil {- return x.State- }- return State_STATE_UNSPECIFIED-}--func (x *HarnessEnd) GetError() *Error {- if x != nil {- return x.Error- }- return nil-}--type HarnessResponse struct {- state protoimpl.MessageState `protogen:"open.v1"`- ConversationId string `protobuf:"bytes,1,opt,name=conversation_id,json=conversationId,proto3" json:"conversation_id,omitempty"`- // Types that are valid to be assigned to Type:- //- // *HarnessResponse_Outputs- // *HarnessResponse_End- Type isHarnessResponse_Type `protobuf_oneof:"type"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *HarnessResponse) Reset() {- *x = HarnessResponse{}- mi := &file_proto_ax_proto_msgTypes[7]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *HarnessResponse) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*HarnessResponse) ProtoMessage() {}--func (x *HarnessResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[7]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use HarnessResponse.ProtoReflect.Descriptor instead.-func (*HarnessResponse) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{7}-}--func (x *HarnessResponse) GetConversationId() string {- if x != nil {- return x.ConversationId- }- return ""-}--func (x *HarnessResponse) GetType() isHarnessResponse_Type {- if x != nil {- return x.Type- }- return nil-}--func (x *HarnessResponse) GetOutputs() *HarnessOutputs {- if x != nil {- if x, ok := x.Type.(*HarnessResponse_Outputs); ok {- return x.Outputs- }- }- return nil-}--func (x *HarnessResponse) GetEnd() *HarnessEnd {- if x != nil {- if x, ok := x.Type.(*HarnessResponse_End); ok {- return x.End- }- }- return nil-}--type isHarnessResponse_Type interface {- isHarnessResponse_Type()-}--type HarnessResponse_Outputs struct {- Outputs *HarnessOutputs `protobuf:"bytes,2,opt,name=outputs,proto3,oneof"`-}--type HarnessResponse_End struct {- End *HarnessEnd `protobuf:"bytes,3,opt,name=end,proto3,oneof"`-}--func (*HarnessResponse_Outputs) isHarnessResponse_Type() {}--func (*HarnessResponse_End) isHarnessResponse_Type() {}--// CreateInteractionEvent for creating an interaction.-type CreateInteractionEvent struct {- state protoimpl.MessageState `protogen:"open.v1"`- ConversationId string `protobuf:"bytes,1,opt,name=conversation_id,json=conversationId,proto3" json:"conversation_id,omitempty"` // Unique conversation identifier- Inputs []*Step `protobuf:"bytes,2,rep,name=inputs,proto3" json:"inputs,omitempty"` // New inputs- AgentId string `protobuf:"bytes,4,opt,name=agent_id,json=agentId,proto3" json:"agent_id,omitempty"` // Agent ID, empty selects the default agent- AgentConfig []byte `protobuf:"bytes,5,opt,name=agent_config,json=agentConfig,proto3" json:"agent_config,omitempty"` // Per-request agent configuration (opaque JSON), if any- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *CreateInteractionEvent) Reset() {- *x = CreateInteractionEvent{}- mi := &file_proto_ax_proto_msgTypes[8]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *CreateInteractionEvent) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*CreateInteractionEvent) ProtoMessage() {}--func (x *CreateInteractionEvent) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[8]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use CreateInteractionEvent.ProtoReflect.Descriptor instead.-func (*CreateInteractionEvent) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{8}-}--func (x *CreateInteractionEvent) GetConversationId() string {- if x != nil {- return x.ConversationId- }- return ""-}--func (x *CreateInteractionEvent) GetInputs() []*Step {- if x != nil {- return x.Inputs- }- return nil-}--func (x *CreateInteractionEvent) GetAgentId() string {- if x != nil {- return x.AgentId- }- return ""-}--func (x *CreateInteractionEvent) GetAgentConfig() []byte {- if x != nil {- return x.AgentConfig- }- return nil-}--// CreateInteractionResponse contains the result of an interaction.-type CreateInteractionResponse struct {- state protoimpl.MessageState `protogen:"open.v1"`- Outputs []*Step `protobuf:"bytes,1,rep,name=outputs,proto3" json:"outputs,omitempty"` // Output content- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *CreateInteractionResponse) Reset() {- *x = CreateInteractionResponse{}- mi := &file_proto_ax_proto_msgTypes[9]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *CreateInteractionResponse) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*CreateInteractionResponse) ProtoMessage() {}--func (x *CreateInteractionResponse) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[9]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use CreateInteractionResponse.ProtoReflect.Descriptor instead.-func (*CreateInteractionResponse) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{9}-}--func (x *CreateInteractionResponse) GetOutputs() []*Step {- if x != nil {- return x.Outputs- }- return nil-}--type Step struct {- state protoimpl.MessageState `protogen:"open.v1"`- Description string `protobuf:"bytes,16,opt,name=description,proto3" json:"description,omitempty"`- // Types that are valid to be assigned to Type:- //- // *Step_Content- // *Step_Thought- // *Step_ToolCall- // *Step_ToolResult- Type isStep_Type `protobuf_oneof:"type"`- Index int64 `protobuf:"varint,22,opt,name=index,proto3" json:"index,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *Step) Reset() {- *x = Step{}- mi := &file_proto_ax_proto_msgTypes[10]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *Step) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*Step) ProtoMessage() {}--func (x *Step) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[10]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use Step.ProtoReflect.Descriptor instead.-func (*Step) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{10}-}--func (x *Step) GetDescription() string {- if x != nil {- return x.Description- }- return ""-}--func (x *Step) GetType() isStep_Type {- if x != nil {- return x.Type- }- return nil-}--func (x *Step) GetContent() *ContentStep {- if x != nil {- if x, ok := x.Type.(*Step_Content); ok {- return x.Content- }- }- return nil-}--func (x *Step) GetThought() *ThoughtStep {- if x != nil {- if x, ok := x.Type.(*Step_Thought); ok {- return x.Thought- }- }- return nil-}--func (x *Step) GetToolCall() *ToolCallStep {- if x != nil {- if x, ok := x.Type.(*Step_ToolCall); ok {- return x.ToolCall- }- }- return nil-}--func (x *Step) GetToolResult() *ToolResultStep {- if x != nil {- if x, ok := x.Type.(*Step_ToolResult); ok {- return x.ToolResult- }- }- return nil-}--func (x *Step) GetIndex() int64 {- if x != nil {- return x.Index- }- return 0-}--type isStep_Type interface {- isStep_Type()-}--type Step_Content struct {- Content *ContentStep `protobuf:"bytes,12,opt,name=content,proto3,oneof"`-}--type Step_Thought struct {- Thought *ThoughtStep `protobuf:"bytes,3,opt,name=thought,proto3,oneof"`-}--type Step_ToolCall struct {- ToolCall *ToolCallStep `protobuf:"bytes,4,opt,name=tool_call,json=toolCall,proto3,oneof"`-}--type Step_ToolResult struct {- ToolResult *ToolResultStep `protobuf:"bytes,5,opt,name=tool_result,json=toolResult,proto3,oneof"`-}--func (*Step_Content) isStep_Type() {}--func (*Step_Thought) isStep_Type() {}--func (*Step_ToolCall) isStep_Type() {}--func (*Step_ToolResult) isStep_Type() {}--type ContentStep struct {- state protoimpl.MessageState `protogen:"open.v1"`- Role string `protobuf:"bytes,1,opt,name=role,proto3" json:"role,omitempty"`- Content []*Content `protobuf:"bytes,2,rep,name=content,proto3" json:"content,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *ContentStep) Reset() {- *x = ContentStep{}- mi := &file_proto_ax_proto_msgTypes[11]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *ContentStep) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*ContentStep) ProtoMessage() {}--func (x *ContentStep) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[11]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use ContentStep.ProtoReflect.Descriptor instead.-func (*ContentStep) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{11}-}--func (x *ContentStep) GetRole() string {- if x != nil {- return x.Role- }- return ""-}--func (x *ContentStep) GetContent() []*Content {- if x != nil {- return x.Content- }- return nil-}--type ThoughtStep struct {- state protoimpl.MessageState `protogen:"open.v1"`- // A signature hash for backend validation.- Signature []byte `protobuf:"bytes,1,opt,name=signature,proto3" json:"signature,omitempty"`- // A summary of the thought.- Summary []*Content `protobuf:"bytes,2,rep,name=summary,proto3" json:"summary,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *ThoughtStep) Reset() {- *x = ThoughtStep{}- mi := &file_proto_ax_proto_msgTypes[12]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *ThoughtStep) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*ThoughtStep) ProtoMessage() {}--func (x *ThoughtStep) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[12]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use ThoughtStep.ProtoReflect.Descriptor instead.-func (*ThoughtStep) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{12}-}--func (x *ThoughtStep) GetSignature() []byte {- if x != nil {- return x.Signature- }- return nil-}--func (x *ThoughtStep) GetSummary() []*Content {- if x != nil {- return x.Summary- }- return nil-}--type ToolCallStep struct {- state protoimpl.MessageState `protogen:"open.v1"`- Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`- Signature []byte `protobuf:"bytes,2,opt,name=signature,proto3" json:"signature,omitempty"`- // Types that are valid to be assigned to Type:- //- // *ToolCallStep_FunctionCall- Type isToolCallStep_Type `protobuf_oneof:"type"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *ToolCallStep) Reset() {- *x = ToolCallStep{}- mi := &file_proto_ax_proto_msgTypes[13]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *ToolCallStep) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*ToolCallStep) ProtoMessage() {}--func (x *ToolCallStep) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[13]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use ToolCallStep.ProtoReflect.Descriptor instead.-func (*ToolCallStep) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{13}-}--func (x *ToolCallStep) GetId() string {- if x != nil {- return x.Id- }- return ""-}--func (x *ToolCallStep) GetSignature() []byte {- if x != nil {- return x.Signature- }- return nil-}--func (x *ToolCallStep) GetType() isToolCallStep_Type {- if x != nil {- return x.Type- }- return nil-}--func (x *ToolCallStep) GetFunctionCall() *FunctionCallStep {- if x != nil {- if x, ok := x.Type.(*ToolCallStep_FunctionCall); ok {- return x.FunctionCall- }- }- return nil-}--type isToolCallStep_Type interface {- isToolCallStep_Type()-}--type ToolCallStep_FunctionCall struct {- FunctionCall *FunctionCallStep `protobuf:"bytes,3,opt,name=function_call,json=functionCall,proto3,oneof"`-}--func (*ToolCallStep_FunctionCall) isToolCallStep_Type() {}--type FunctionCallStep struct {- state protoimpl.MessageState `protogen:"open.v1"`- Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`- Arguments *structpb.Struct `protobuf:"bytes,2,opt,name=arguments,proto3" json:"arguments,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *FunctionCallStep) Reset() {- *x = FunctionCallStep{}- mi := &file_proto_ax_proto_msgTypes[14]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *FunctionCallStep) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*FunctionCallStep) ProtoMessage() {}--func (x *FunctionCallStep) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[14]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use FunctionCallStep.ProtoReflect.Descriptor instead.-func (*FunctionCallStep) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{14}-}--func (x *FunctionCallStep) GetName() string {- if x != nil {- return x.Name- }- return ""-}--func (x *FunctionCallStep) GetArguments() *structpb.Struct {- if x != nil {- return x.Arguments- }- return nil-}--type ToolResultStep struct {- state protoimpl.MessageState `protogen:"open.v1"`- CallId string `protobuf:"bytes,1,opt,name=call_id,json=callId,proto3" json:"call_id,omitempty"`- Signature []byte `protobuf:"bytes,2,opt,name=signature,proto3" json:"signature,omitempty"`- // Types that are valid to be assigned to Type:- //- // *ToolResultStep_FunctionResult- Type isToolResultStep_Type `protobuf_oneof:"type"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *ToolResultStep) Reset() {- *x = ToolResultStep{}- mi := &file_proto_ax_proto_msgTypes[15]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *ToolResultStep) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*ToolResultStep) ProtoMessage() {}--func (x *ToolResultStep) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[15]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use ToolResultStep.ProtoReflect.Descriptor instead.-func (*ToolResultStep) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{15}-}--func (x *ToolResultStep) GetCallId() string {- if x != nil {- return x.CallId- }- return ""-}--func (x *ToolResultStep) GetSignature() []byte {- if x != nil {- return x.Signature- }- return nil-}--func (x *ToolResultStep) GetType() isToolResultStep_Type {- if x != nil {- return x.Type- }- return nil-}--func (x *ToolResultStep) GetFunctionResult() *FunctionResultStep {- if x != nil {- if x, ok := x.Type.(*ToolResultStep_FunctionResult); ok {- return x.FunctionResult- }- }- return nil-}--type isToolResultStep_Type interface {- isToolResultStep_Type()-}--type ToolResultStep_FunctionResult struct {- FunctionResult *FunctionResultStep `protobuf:"bytes,3,opt,name=function_result,json=functionResult,proto3,oneof"`-}--func (*ToolResultStep_FunctionResult) isToolResultStep_Type() {}--type FunctionResultStep struct {- state protoimpl.MessageState `protogen:"open.v1"`- // The name of the tool that was called.- Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`- // Whether the tool call resulted in an error.- IsError bool `protobuf:"varint,3,opt,name=is_error,json=isError,proto3" json:"is_error,omitempty"`- // The result of the tool call.- Result *Value `protobuf:"bytes,7,opt,name=result,proto3" json:"result,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *FunctionResultStep) Reset() {- *x = FunctionResultStep{}- mi := &file_proto_ax_proto_msgTypes[16]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *FunctionResultStep) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*FunctionResultStep) ProtoMessage() {}--func (x *FunctionResultStep) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[16]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use FunctionResultStep.ProtoReflect.Descriptor instead.-func (*FunctionResultStep) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{16}-}--func (x *FunctionResultStep) GetName() string {- if x != nil {- return x.Name- }- return ""-}--func (x *FunctionResultStep) GetIsError() bool {- if x != nil {- return x.IsError- }- return false-}--func (x *FunctionResultStep) GetResult() *Value {- if x != nil {- return x.Result- }- return nil-}--type Value struct {- state protoimpl.MessageState `protogen:"open.v1"`- // The kind of value.- //- // Types that are valid to be assigned to Kind:- //- // *Value_NullValue- // *Value_NumberValue- // *Value_StringValue- // *Value_BoolValue- // *Value_StructValue- // *Value_ListValue- // *Value_ContentValue- Kind isValue_Kind `protobuf_oneof:"kind"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *Value) Reset() {- *x = Value{}- mi := &file_proto_ax_proto_msgTypes[17]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *Value) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*Value) ProtoMessage() {}--func (x *Value) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[17]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use Value.ProtoReflect.Descriptor instead.-func (*Value) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{17}-}--func (x *Value) GetKind() isValue_Kind {- if x != nil {- return x.Kind- }- return nil-}--func (x *Value) GetNullValue() structpb.NullValue {- if x != nil {- if x, ok := x.Kind.(*Value_NullValue); ok {- return x.NullValue- }- }- return structpb.NullValue(0)-}--func (x *Value) GetNumberValue() float64 {- if x != nil {- if x, ok := x.Kind.(*Value_NumberValue); ok {- return x.NumberValue- }- }- return 0-}--func (x *Value) GetStringValue() string {- if x != nil {- if x, ok := x.Kind.(*Value_StringValue); ok {- return x.StringValue- }- }- return ""-}--func (x *Value) GetBoolValue() bool {- if x != nil {- if x, ok := x.Kind.(*Value_BoolValue); ok {- return x.BoolValue- }- }- return false-}--func (x *Value) GetStructValue() *structpb.Struct {- if x != nil {- if x, ok := x.Kind.(*Value_StructValue); ok {- return x.StructValue- }- }- return nil-}--func (x *Value) GetListValue() *ListValue {- if x != nil {- if x, ok := x.Kind.(*Value_ListValue); ok {- return x.ListValue- }- }- return nil-}--func (x *Value) GetContentValue() *Content {- if x != nil {- if x, ok := x.Kind.(*Value_ContentValue); ok {- return x.ContentValue- }- }- return nil-}--type isValue_Kind interface {- isValue_Kind()-}--type Value_NullValue struct {- // Represents a null value.- NullValue structpb.NullValue `protobuf:"varint,1,opt,name=null_value,json=nullValue,proto3,enum=google.protobuf.NullValue,oneof"`-}--type Value_NumberValue struct {- // Represents a double value.- NumberValue float64 `protobuf:"fixed64,2,opt,name=number_value,json=numberValue,proto3,oneof"`-}--type Value_StringValue struct {- // Represents a string value.- StringValue string `protobuf:"bytes,3,opt,name=string_value,json=stringValue,proto3,oneof"`-}--type Value_BoolValue struct {- // Represents a boolean value.- BoolValue bool `protobuf:"varint,4,opt,name=bool_value,json=boolValue,proto3,oneof"`-}--type Value_StructValue struct {- // Represents a structured value.- StructValue *structpb.Struct `protobuf:"bytes,5,opt,name=struct_value,json=structValue,proto3,oneof"`-}--type Value_ListValue struct {- // Represents a repeated `Value`.- ListValue *ListValue `protobuf:"bytes,6,opt,name=list_value,json=listValue,proto3,oneof"`-}--type Value_ContentValue struct {- // Represents rich content (text, image, etc.).- ContentValue *Content `protobuf:"bytes,7,opt,name=content_value,json=contentValue,proto3,oneof"`-}--func (*Value_NullValue) isValue_Kind() {}--func (*Value_NumberValue) isValue_Kind() {}--func (*Value_StringValue) isValue_Kind() {}--func (*Value_BoolValue) isValue_Kind() {}--func (*Value_StructValue) isValue_Kind() {}--func (*Value_ListValue) isValue_Kind() {}--func (*Value_ContentValue) isValue_Kind() {}--// `ListValue` is a wrapper around a repeated field of values.-type ListValue struct {- state protoimpl.MessageState `protogen:"open.v1"`- // Repeated field of dynamically typed values.- Values []*Value `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *ListValue) Reset() {- *x = ListValue{}- mi := &file_proto_ax_proto_msgTypes[18]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *ListValue) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*ListValue) ProtoMessage() {}--func (x *ListValue) ProtoReflect() protoreflect.Message {- mi := &file_proto_ax_proto_msgTypes[18]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use ListValue.ProtoReflect.Descriptor instead.-func (*ListValue) Descriptor() ([]byte, []int) {- return file_proto_ax_proto_rawDescGZIP(), []int{18}-}--func (x *ListValue) GetValues() []*Value {- if x != nil {- return x.Values- }- return nil-}--var File_proto_ax_proto protoreflect.FileDescriptor--const file_proto_ax_proto_rawDesc = "" +- "\n" +- "\x0eproto/ax.proto\x12\x02ax\x1a\x1cgoogle/protobuf/struct.proto\x1a\x13proto/content.proto\"\xf3\x01\n" +- "\tStepEvent\x12'\n" +- "\x0fconversation_id\x18\x01 \x01(\tR\x0econversationId\x12%\n" +- "\x0einteraction_id\x18\x02 \x01(\tR\rinteractionId\x12\x19\n" +- "\bagent_id\x18\x03 \x01(\tR\aagentId\x12:\n" +- "\fagent_config\x18\x04 \x01(\v2\x17.google.protobuf.StructR\vagentConfig\x12\x1e\n" +- "\x05steps\x18\x05 \x03(\v2\b.ax.StepR\x05steps\x12\x1f\n" +- "\x05state\x18\x06 \x01(\x0e2\t.ax.StateR\x05state\"Q\n" +- "\fHarnessStart\x12!\n" +- "\fagent_config\x18\x01 \x01(\fR\vagentConfig\x12\x1e\n" +- "\x05steps\x18\x02 \x03(\v2\b.ax.StepR\x05steps\"9\n" +- "\rHarnessCancel\x12(\n" +- "\x06reason\x18\x01 \x01(\x0e2\x10.ax.CancelReasonR\x06reason\"\xb3\x01\n" +- "\x0eHarnessRequest\x12'\n" +- "\x0fconversation_id\x18\x01 \x01(\tR\x0econversationId\x12\x19\n" +- "\bagent_id\x18\x02 \x01(\tR\aagentId\x12(\n" +- "\x05start\x18\x03 \x01(\v2\x10.ax.HarnessStartH\x00R\x05start\x12+\n" +- "\x06cancel\x18\x04 \x01(\v2\x11.ax.HarnessCancelH\x00R\x06cancelB\x06\n" +- "\x04type\"0\n" +- "\x0eHarnessOutputs\x12\x1e\n" +- "\x05steps\x18\x01 \x03(\v2\b.ax.StepR\x05steps\"=\n" +- "\x05Error\x12\x12\n" +- "\x04code\x18\x01 \x01(\x05R\x04code\x12 \n" +- "\vdescription\x18\x02 \x01(\tR\vdescription\"N\n" +- "\n" +- "HarnessEnd\x12\x1f\n" +- "\x05state\x18\x01 \x01(\x0e2\t.ax.StateR\x05state\x12\x1f\n" +- "\x05error\x18\x02 \x01(\v2\t.ax.ErrorR\x05error\"\x96\x01\n" +- "\x0fHarnessResponse\x12'\n" +- "\x0fconversation_id\x18\x01 \x01(\tR\x0econversationId\x12.\n" +- "\aoutputs\x18\x02 \x01(\v2\x12.ax.HarnessOutputsH\x00R\aoutputs\x12\"\n" +- "\x03end\x18\x03 \x01(\v2\x0e.ax.HarnessEndH\x00R\x03endB\x06\n" +- "\x04type\"\xa7\x01\n" +- "\x16CreateInteractionEvent\x12'\n" +- "\x0fconversation_id\x18\x01 \x01(\tR\x0econversationId\x12 \n" +- "\x06inputs\x18\x02 \x03(\v2\b.ax.StepR\x06inputs\x12\x19\n" +- "\bagent_id\x18\x04 \x01(\tR\aagentId\x12!\n" +- "\fagent_config\x18\x05 \x01(\fR\vagentConfigJ\x04\b\x03\x10\x04\"?\n" +- "\x19CreateInteractionResponse\x12\"\n" +- "\aoutputs\x18\x01 \x03(\v2\b.ax.StepR\aoutputs\"\x88\x02\n" +- "\x04Step\x12 \n" +- "\vdescription\x18\x10 \x01(\tR\vdescription\x12+\n" +- "\acontent\x18\f \x01(\v2\x0f.ax.ContentStepH\x00R\acontent\x12+\n" +- "\athought\x18\x03 \x01(\v2\x0f.ax.ThoughtStepH\x00R\athought\x12/\n" +- "\ttool_call\x18\x04 \x01(\v2\x10.ax.ToolCallStepH\x00R\btoolCall\x125\n" +- "\vtool_result\x18\x05 \x01(\v2\x12.ax.ToolResultStepH\x00R\n" +- "toolResult\x12\x14\n" +- "\x05index\x18\x16 \x01(\x03R\x05indexB\x06\n" +- "\x04type\"Z\n" +- "\vContentStep\x12\x12\n" +- "\x04role\x18\x01 \x01(\tR\x04role\x12%\n" +- "\acontent\x18\x02 \x03(\v2\v.ax.ContentR\acontentR\x04typeR\n" +- "event_type\"d\n" +- "\vThoughtStep\x12\x1c\n" +- "\tsignature\x18\x01 \x01(\fR\tsignature\x12%\n" +- "\asummary\x18\x02 \x03(\v2\v.ax.ContentR\asummaryR\x04typeR\n" +- "event_type\"\x8d\x01\n" +- "\fToolCallStep\x12\x0e\n" +- "\x02id\x18\x01 \x01(\tR\x02id\x12\x1c\n" +- "\tsignature\x18\x02 \x01(\fR\tsignature\x12;\n" +- "\rfunction_call\x18\x03 \x01(\v2\x14.ax.FunctionCallStepH\x00R\ffunctionCallB\x06\n" +- "\x04typeR\n" +- "event_type\"c\n" +- "\x10FunctionCallStep\x12\x12\n" +- "\x04name\x18\x01 \x01(\tR\x04name\x125\n" +- "\targuments\x18\x02 \x01(\v2\x17.google.protobuf.StructR\targumentsR\x04type\"\x9e\x01\n" +- "\x0eToolResultStep\x12\x17\n" +- "\acall_id\x18\x01 \x01(\tR\x06callId\x12\x1c\n" +- "\tsignature\x18\x02 \x01(\fR\tsignature\x12A\n" +- "\x0ffunction_result\x18\x03 \x01(\v2\x16.ax.FunctionResultStepH\x00R\x0efunctionResultB\x06\n" +- "\x04typeR\n" +- "event_type\"\x8a\x01\n" +- "\x12FunctionResultStep\x12\x12\n" +- "\x04name\x18\x02 \x01(\tR\x04name\x12\x19\n" +- "\bis_error\x18\x03 \x01(\bR\aisError\x12!\n" +- "\x06result\x18\a \x01(\v2\t.ax.ValueR\x06resultJ\x04\b\x01\x10\x02J\x04\b\x04\x10\x05J\x04\b\n" +- "\x10\vJ\x04\b\v\x10\fJ\x04\b\f\x10\rR\x04type\"\xd9\x02\n" +- "\x05Value\x12;\n" +- "\n" +- "null_value\x18\x01 \x01(\x0e2\x1a.google.protobuf.NullValueH\x00R\tnullValue\x12#\n" +- "\fnumber_value\x18\x02 \x01(\x01H\x00R\vnumberValue\x12#\n" +- "\fstring_value\x18\x03 \x01(\tH\x00R\vstringValue\x12\x1f\n" +- "\n" +- "bool_value\x18\x04 \x01(\bH\x00R\tboolValue\x12<\n" +- "\fstruct_value\x18\x05 \x01(\v2\x17.google.protobuf.StructH\x00R\vstructValue\x12.\n" +- "\n" +- "list_value\x18\x06 \x01(\v2\r.ax.ListValueH\x00R\tlistValue\x122\n" +- "\rcontent_value\x18\a \x01(\v2\v.ax.ContentH\x00R\fcontentValueB\x06\n" +- "\x04kind\".\n" +- "\tListValue\x12!\n" +- "\x06values\x18\x01 \x03(\v2\t.ax.ValueR\x06values*l\n" +- "\x05State\x12\x15\n" +- "\x11STATE_UNSPECIFIED\x10\x00\x12\x11\n" +- "\rSTATE_PENDING\x10\x01\x12\x10\n" +- "\fSTATE_FAILED\x10\x02\x12\x13\n" +- "\x0fSTATE_COMPLETED\x10\x03\x12\x12\n" +- "\x0eSTATE_CANCELED\x10\x04*\x8c\x01\n" +- "\fCancelReason\x12\x1d\n" +- "\x19CANCEL_REASON_UNSPECIFIED\x10\x00\x12 \n" +- "\x1cCANCEL_REASON_USER_REQUESTED\x10\x01\x12\x19\n" +- "\x15CANCEL_REASON_TIMEOUT\x10\x02\x12 \n" +- "\x1cCANCEL_REASON_INTERNAL_ERROR\x10\x032H\n" +- "\x0eHarnessService\x126\n" +- "\aConnect\x12\x12.ax.HarnessRequest\x1a\x13.ax.HarnessResponse(\x010\x012g\n" +- "\x13InteractionsService\x12P\n" +- "\x11CreateInteraction\x12\x1a.ax.CreateInteractionEvent\x1a\x1d.ax.CreateInteractionResponse0\x01B\x1cZ\x1agithub.com/google/ax/protob\x06proto3"--var (- file_proto_ax_proto_rawDescOnce sync.Once- file_proto_ax_proto_rawDescData []byte-)--func file_proto_ax_proto_rawDescGZIP() []byte {- file_proto_ax_proto_rawDescOnce.Do(func() {- file_proto_ax_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proto_ax_proto_rawDesc), len(file_proto_ax_proto_rawDesc)))- })- return file_proto_ax_proto_rawDescData-}--var file_proto_ax_proto_enumTypes = make([]protoimpl.EnumInfo, 2)-var file_proto_ax_proto_msgTypes = make([]protoimpl.MessageInfo, 19)-var file_proto_ax_proto_goTypes = []any{- (State)(0), // 0: ax.State- (CancelReason)(0), // 1: ax.CancelReason- (*StepEvent)(nil), // 2: ax.StepEvent- (*HarnessStart)(nil), // 3: ax.HarnessStart- (*HarnessCancel)(nil), // 4: ax.HarnessCancel- (*HarnessRequest)(nil), // 5: ax.HarnessRequest- (*HarnessOutputs)(nil), // 6: ax.HarnessOutputs- (*Error)(nil), // 7: ax.Error- (*HarnessEnd)(nil), // 8: ax.HarnessEnd- (*HarnessResponse)(nil), // 9: ax.HarnessResponse- (*CreateInteractionEvent)(nil), // 10: ax.CreateInteractionEvent- (*CreateInteractionResponse)(nil), // 11: ax.CreateInteractionResponse- (*Step)(nil), // 12: ax.Step- (*ContentStep)(nil), // 13: ax.ContentStep- (*ThoughtStep)(nil), // 14: ax.ThoughtStep- (*ToolCallStep)(nil), // 15: ax.ToolCallStep- (*FunctionCallStep)(nil), // 16: ax.FunctionCallStep- (*ToolResultStep)(nil), // 17: ax.ToolResultStep- (*FunctionResultStep)(nil), // 18: ax.FunctionResultStep- (*Value)(nil), // 19: ax.Value- (*ListValue)(nil), // 20: ax.ListValue- (*structpb.Struct)(nil), // 21: google.protobuf.Struct- (*Content)(nil), // 22: ax.Content- (structpb.NullValue)(0), // 23: google.protobuf.NullValue-}-var file_proto_ax_proto_depIdxs = []int32{- 21, // 0: ax.StepEvent.agent_config:type_name -> google.protobuf.Struct- 12, // 1: ax.StepEvent.steps:type_name -> ax.Step- 0, // 2: ax.StepEvent.state:type_name -> ax.State- 12, // 3: ax.HarnessStart.steps:type_name -> ax.Step- 1, // 4: ax.HarnessCancel.reason:type_name -> ax.CancelReason- 3, // 5: ax.HarnessRequest.start:type_name -> ax.HarnessStart- 4, // 6: ax.HarnessRequest.cancel:type_name -> ax.HarnessCancel- 12, // 7: ax.HarnessOutputs.steps:type_name -> ax.Step- 0, // 8: ax.HarnessEnd.state:type_name -> ax.State- 7, // 9: ax.HarnessEnd.error:type_name -> ax.Error- 6, // 10: ax.HarnessResponse.outputs:type_name -> ax.HarnessOutputs- 8, // 11: ax.HarnessResponse.end:type_name -> ax.HarnessEnd- 12, // 12: ax.CreateInteractionEvent.inputs:type_name -> ax.Step- 12, // 13: ax.CreateInteractionResponse.outputs:type_name -> ax.Step- 13, // 14: ax.Step.content:type_name -> ax.ContentStep- 14, // 15: ax.Step.thought:type_name -> ax.ThoughtStep- 15, // 16: ax.Step.tool_call:type_name -> ax.ToolCallStep- 17, // 17: ax.Step.tool_result:type_name -> ax.ToolResultStep- 22, // 18: ax.ContentStep.content:type_name -> ax.Content- 22, // 19: ax.ThoughtStep.summary:type_name -> ax.Content- 16, // 20: ax.ToolCallStep.function_call:type_name -> ax.FunctionCallStep- 21, // 21: ax.FunctionCallStep.arguments:type_name -> google.protobuf.Struct- 18, // 22: ax.ToolResultStep.function_result:type_name -> ax.FunctionResultStep- 19, // 23: ax.FunctionResultStep.result:type_name -> ax.Value- 23, // 24: ax.Value.null_value:type_name -> google.protobuf.NullValue- 21, // 25: ax.Value.struct_value:type_name -> google.protobuf.Struct- 20, // 26: ax.Value.list_value:type_name -> ax.ListValue- 22, // 27: ax.Value.content_value:type_name -> ax.Content- 19, // 28: ax.ListValue.values:type_name -> ax.Value- 5, // 29: ax.HarnessService.Connect:input_type -> ax.HarnessRequest- 10, // 30: ax.InteractionsService.CreateInteraction:input_type -> ax.CreateInteractionEvent- 9, // 31: ax.HarnessService.Connect:output_type -> ax.HarnessResponse- 11, // 32: ax.InteractionsService.CreateInteraction:output_type -> ax.CreateInteractionResponse- 31, // [31:33] is the sub-list for method output_type- 29, // [29:31] is the sub-list for method input_type- 29, // [29:29] is the sub-list for extension type_name- 29, // [29:29] is the sub-list for extension extendee- 0, // [0:29] is the sub-list for field type_name-}--func init() { file_proto_ax_proto_init() }-func file_proto_ax_proto_init() {- if File_proto_ax_proto != nil {- return- }- file_proto_content_proto_init()- file_proto_ax_proto_msgTypes[3].OneofWrappers = []any{- (*HarnessRequest_Start)(nil),- (*HarnessRequest_Cancel)(nil),- }- file_proto_ax_proto_msgTypes[7].OneofWrappers = []any{- (*HarnessResponse_Outputs)(nil),- (*HarnessResponse_End)(nil),- }- file_proto_ax_proto_msgTypes[10].OneofWrappers = []any{- (*Step_Content)(nil),- (*Step_Thought)(nil),- (*Step_ToolCall)(nil),- (*Step_ToolResult)(nil),- }- file_proto_ax_proto_msgTypes[13].OneofWrappers = []any{- (*ToolCallStep_FunctionCall)(nil),- }- file_proto_ax_proto_msgTypes[15].OneofWrappers = []any{- (*ToolResultStep_FunctionResult)(nil),- }- file_proto_ax_proto_msgTypes[17].OneofWrappers = []any{- (*Value_NullValue)(nil),- (*Value_NumberValue)(nil),- (*Value_StringValue)(nil),- (*Value_BoolValue)(nil),- (*Value_StructValue)(nil),- (*Value_ListValue)(nil),- (*Value_ContentValue)(nil),- }- type x struct{}- out := protoimpl.TypeBuilder{- File: protoimpl.DescBuilder{- GoPackagePath: reflect.TypeOf(x{}).PkgPath(),- RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_ax_proto_rawDesc), len(file_proto_ax_proto_rawDesc)),- NumEnums: 2,- NumMessages: 19,- NumExtensions: 0,- NumServices: 2,- },- GoTypes: file_proto_ax_proto_goTypes,- DependencyIndexes: file_proto_ax_proto_depIdxs,- EnumInfos: file_proto_ax_proto_enumTypes,- MessageInfos: file_proto_ax_proto_msgTypes,- }.Build()- File_proto_ax_proto = out.File- file_proto_ax_proto_goTypes = nil- file_proto_ax_proto_depIdxs = nil-}diff --git a/proto/ax.proto b/proto/ax.protodeleted file mode 100644index 7ba2fec..0000000--- a/proto/ax.proto+++ /dev/null@@ -1,236 +0,0 @@-// 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.--syntax = "proto3";--package ax;--import "google/protobuf/struct.proto";-import "proto/content.proto";--option go_package = "github.com/google/ax/proto";--// WARNING: This file is in active development and-// significant changes can be made with breaking changes.--// A conversation is the historical session that consist of-// a number of execution. A conversation cannot be continued-// before the last execution is completed or failed.-message StepEvent {- string conversation_id = 1;- string interaction_id = 2;- string agent_id = 3;- google.protobuf.Struct agent_config = 4;- repeated Step steps = 5;- State state = 6;-}--message HarnessStart {- // Per-execution agent configuration.- bytes agent_config = 1;- repeated Step steps = 2;-}--// HarnessCancel aborts the in-flight harness execution.-message HarnessCancel {- CancelReason reason = 1;-}--message HarnessRequest {- string conversation_id = 1;- string agent_id = 2;- oneof type {- HarnessStart start = 3;- HarnessCancel cancel = 4;- }-}--message HarnessOutputs {- repeated Step steps = 1;-}--message Error {- // A status code, corresponds to google.golang.org/grpc/codes.- int32 code = 1;- // A description of the error.- string description = 2;-}--message HarnessEnd {- // Terminal state for the harness execution.- State state = 1;- // Optional error details.- Error error = 2;-}--message HarnessResponse {- string conversation_id = 1;- oneof type {- HarnessOutputs outputs = 2;- HarnessEnd end = 3;- }-}--service HarnessService {- // Connect drives one harness execution. The client sends- // HarnessRequest{start} (and may send one HarnessRequest{cancel}- // mid-stream), and the server streams zero or more HarnessResponse{outputs}- // frames terminated by exactly one HarnessResponse{end}.- rpc Connect(stream HarnessRequest) returns (stream HarnessResponse);-}--// State represents the state of an execution-enum State {- STATE_UNSPECIFIED = 0; // Unspecified state- STATE_PENDING = 1;- STATE_FAILED = 2;- STATE_COMPLETED = 3;- STATE_CANCELED = 4;-}--// CancelReason explains why an in-flight execution is canceled.-enum CancelReason {- CANCEL_REASON_UNSPECIFIED = 0;- CANCEL_REASON_USER_REQUESTED = 1;- CANCEL_REASON_TIMEOUT = 2;- CANCEL_REASON_INTERNAL_ERROR = 3;-}--// CreateInteractionEvent for creating an interaction.-message CreateInteractionEvent {- string conversation_id = 1; // Unique conversation identifier- repeated Step inputs = 2; // New inputs- reserved 3;-- string agent_id = 4; // Agent ID, empty selects the default agent- bytes agent_config = 5; // Per-request agent configuration (opaque JSON), if any-}--// CreateInteractionResponse contains the result of an interaction.-message CreateInteractionResponse {- repeated Step outputs = 1; // Output content-}--service InteractionsService {- // CreateInteraction executes an agentic task or resumes an existing one with streaming responses- // If the conversation_id already exists, it will be resumed.- rpc CreateInteraction(CreateInteractionEvent) returns (stream CreateInteractionResponse);-}--// TODO(jbd): CreateInteraction should return an Interaction message-// and the outputs should be polled from the Interaction.--message Step {- string description = 16;-- oneof type {- ContentStep content = 12;- ThoughtStep thought = 3;- ToolCallStep tool_call = 4;- ToolResultStep tool_result = 5;- }-- int64 index = 22;-}--message ContentStep {- reserved "type";- reserved "event_type";-- string role = 1;- repeated Content content = 2;-}--message ThoughtStep {- reserved "type";- reserved "event_type";-- // A signature hash for backend validation.- bytes signature = 1;- // A summary of the thought.- repeated Content summary = 2;-}--message ToolCallStep {- reserved "event_type";-- string id = 1;-- bytes signature = 2;-- oneof type {- FunctionCallStep function_call = 3;- }-}--message FunctionCallStep {- reserved "type";-- string name = 1;-- google.protobuf.Struct arguments = 2;-}--message ToolResultStep {- reserved "event_type";-- string call_id = 1;-- bytes signature = 2;-- oneof type {- FunctionResultStep function_result = 3;- }-}--message FunctionResultStep {- reserved "type";- reserved 1, 4;-- // The name of the tool that was called.- string name = 2;-- // Whether the tool call resulted in an error.- bool is_error = 3;-- // The result of the tool call.- Value result = 7;- reserved 10, 11, 12;-}--message Value {- // The kind of value.- oneof kind {- // Represents a null value.- google.protobuf.NullValue null_value = 1;- // Represents a double value.- double number_value = 2;- // Represents a string value.- string string_value = 3;- // Represents a boolean value.- bool bool_value = 4;- // Represents a structured value.- google.protobuf.Struct struct_value = 5;- // Represents a repeated `Value`.- ListValue list_value = 6;- // Represents rich content (text, image, etc.).- Content content_value = 7;- }-}--// `ListValue` is a wrapper around a repeated field of values.-message ListValue {- // Repeated field of dynamically typed values.- repeated Value values = 1;-}\ No newline at end of filediff --git a/proto/ax_grpc.pb.go b/proto/ax_grpc.pb.godeleted file mode 100644index 1af304c..0000000--- a/proto/ax_grpc.pb.go+++ /dev/null@@ -1,246 +0,0 @@-// 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.--// Code generated by protoc-gen-go-grpc. DO NOT EDIT.-// versions:-// - protoc-gen-go-grpc v1.5.1-// - protoc v5.28.2-// source: proto/ax.proto--package proto--import (- context "context"- grpc "google.golang.org/grpc"- codes "google.golang.org/grpc/codes"- status "google.golang.org/grpc/status"-)--// This is a compile-time assertion to ensure that this generated file-// is compatible with the grpc package it is being compiled against.-// Requires gRPC-Go v1.64.0 or later.-const _ = grpc.SupportPackageIsVersion9--const (- HarnessService_Connect_FullMethodName = "/ax.HarnessService/Connect"-)--// HarnessServiceClient is the client API for HarnessService service.-//-// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.-type HarnessServiceClient interface {- // Connect drives one harness execution. The client sends- // HarnessRequest{start} (and may send one HarnessRequest{cancel}- // mid-stream), and the server streams zero or more HarnessResponse{outputs}- // frames terminated by exactly one HarnessResponse{end}.- Connect(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[HarnessRequest, HarnessResponse], error)-}--type harnessServiceClient struct {- cc grpc.ClientConnInterface-}--func NewHarnessServiceClient(cc grpc.ClientConnInterface) HarnessServiceClient {- return &harnessServiceClient{cc}-}--func (c *harnessServiceClient) Connect(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[HarnessRequest, HarnessResponse], error) {- cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)- stream, err := c.cc.NewStream(ctx, &HarnessService_ServiceDesc.Streams[0], HarnessService_Connect_FullMethodName, cOpts...)- if err != nil {- return nil, err- }- x := &grpc.GenericClientStream[HarnessRequest, HarnessResponse]{ClientStream: stream}- return x, nil-}--// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.-type HarnessService_ConnectClient = grpc.BidiStreamingClient[HarnessRequest, HarnessResponse]--// HarnessServiceServer is the server API for HarnessService service.-// All implementations must embed UnimplementedHarnessServiceServer-// for forward compatibility.-type HarnessServiceServer interface {- // Connect drives one harness execution. The client sends- // HarnessRequest{start} (and may send one HarnessRequest{cancel}- // mid-stream), and the server streams zero or more HarnessResponse{outputs}- // frames terminated by exactly one HarnessResponse{end}.- Connect(grpc.BidiStreamingServer[HarnessRequest, HarnessResponse]) error- mustEmbedUnimplementedHarnessServiceServer()-}--// UnimplementedHarnessServiceServer must be embedded to have-// forward compatible implementations.-//-// NOTE: this should be embedded by value instead of pointer to avoid a nil-// pointer dereference when methods are called.-type UnimplementedHarnessServiceServer struct{}--func (UnimplementedHarnessServiceServer) Connect(grpc.BidiStreamingServer[HarnessRequest, HarnessResponse]) error {- return status.Errorf(codes.Unimplemented, "method Connect not implemented")-}-func (UnimplementedHarnessServiceServer) mustEmbedUnimplementedHarnessServiceServer() {}-func (UnimplementedHarnessServiceServer) testEmbeddedByValue() {}--// UnsafeHarnessServiceServer may be embedded to opt out of forward compatibility for this service.-// Use of this interface is not recommended, as added methods to HarnessServiceServer will-// result in compilation errors.-type UnsafeHarnessServiceServer interface {- mustEmbedUnimplementedHarnessServiceServer()-}--func RegisterHarnessServiceServer(s grpc.ServiceRegistrar, srv HarnessServiceServer) {- // If the following call pancis, it indicates UnimplementedHarnessServiceServer was- // embedded by pointer and is nil. This will cause panics if an- // unimplemented method is ever invoked, so we test this at initialization- // time to prevent it from happening at runtime later due to I/O.- if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {- t.testEmbeddedByValue()- }- s.RegisterService(&HarnessService_ServiceDesc, srv)-}--func _HarnessService_Connect_Handler(srv interface{}, stream grpc.ServerStream) error {- return srv.(HarnessServiceServer).Connect(&grpc.GenericServerStream[HarnessRequest, HarnessResponse]{ServerStream: stream})-}--// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.-type HarnessService_ConnectServer = grpc.BidiStreamingServer[HarnessRequest, HarnessResponse]--// HarnessService_ServiceDesc is the grpc.ServiceDesc for HarnessService service.-// It's only intended for direct use with grpc.RegisterService,-// and not to be introspected or modified (even as a copy)-var HarnessService_ServiceDesc = grpc.ServiceDesc{- ServiceName: "ax.HarnessService",- HandlerType: (*HarnessServiceServer)(nil),- Methods: []grpc.MethodDesc{},- Streams: []grpc.StreamDesc{- {- StreamName: "Connect",- Handler: _HarnessService_Connect_Handler,- ServerStreams: true,- ClientStreams: true,- },- },- Metadata: "proto/ax.proto",-}--const (- InteractionsService_CreateInteraction_FullMethodName = "/ax.InteractionsService/CreateInteraction"-)--// InteractionsServiceClient is the client API for InteractionsService service.-//-// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.-type InteractionsServiceClient interface {- // CreateInteraction executes an agentic task or resumes an existing one with streaming responses- // If the conversation_id already exists, it will be resumed.- CreateInteraction(ctx context.Context, in *CreateInteractionEvent, opts ...grpc.CallOption) (grpc.ServerStreamingClient[CreateInteractionResponse], error)-}--type interactionsServiceClient struct {- cc grpc.ClientConnInterface-}--func NewInteractionsServiceClient(cc grpc.ClientConnInterface) InteractionsServiceClient {- return &interactionsServiceClient{cc}-}--func (c *interactionsServiceClient) CreateInteraction(ctx context.Context, in *CreateInteractionEvent, opts ...grpc.CallOption) (grpc.ServerStreamingClient[CreateInteractionResponse], error) {- cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)- stream, err := c.cc.NewStream(ctx, &InteractionsService_ServiceDesc.Streams[0], InteractionsService_CreateInteraction_FullMethodName, cOpts...)- if err != nil {- return nil, err- }- x := &grpc.GenericClientStream[CreateInteractionEvent, CreateInteractionResponse]{ClientStream: stream}- if err := x.ClientStream.SendMsg(in); err != nil {- return nil, err- }- if err := x.ClientStream.CloseSend(); err != nil {- return nil, err- }- return x, nil-}--// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.-type InteractionsService_CreateInteractionClient = grpc.ServerStreamingClient[CreateInteractionResponse]--// InteractionsServiceServer is the server API for InteractionsService service.-// All implementations must embed UnimplementedInteractionsServiceServer-// for forward compatibility.-type InteractionsServiceServer interface {- // CreateInteraction executes an agentic task or resumes an existing one with streaming responses- // If the conversation_id already exists, it will be resumed.- CreateInteraction(*CreateInteractionEvent, grpc.ServerStreamingServer[CreateInteractionResponse]) error- mustEmbedUnimplementedInteractionsServiceServer()-}--// UnimplementedInteractionsServiceServer must be embedded to have-// forward compatible implementations.-//-// NOTE: this should be embedded by value instead of pointer to avoid a nil-// pointer dereference when methods are called.-type UnimplementedInteractionsServiceServer struct{}--func (UnimplementedInteractionsServiceServer) CreateInteraction(*CreateInteractionEvent, grpc.ServerStreamingServer[CreateInteractionResponse]) error {- return status.Errorf(codes.Unimplemented, "method CreateInteraction not implemented")-}-func (UnimplementedInteractionsServiceServer) mustEmbedUnimplementedInteractionsServiceServer() {}-func (UnimplementedInteractionsServiceServer) testEmbeddedByValue() {}--// UnsafeInteractionsServiceServer may be embedded to opt out of forward compatibility for this service.-// Use of this interface is not recommended, as added methods to InteractionsServiceServer will-// result in compilation errors.-type UnsafeInteractionsServiceServer interface {- mustEmbedUnimplementedInteractionsServiceServer()-}--func RegisterInteractionsServiceServer(s grpc.ServiceRegistrar, srv InteractionsServiceServer) {- // If the following call pancis, it indicates UnimplementedInteractionsServiceServer was- // embedded by pointer and is nil. This will cause panics if an- // unimplemented method is ever invoked, so we test this at initialization- // time to prevent it from happening at runtime later due to I/O.- if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {- t.testEmbeddedByValue()- }- s.RegisterService(&InteractionsService_ServiceDesc, srv)-}--func _InteractionsService_CreateInteraction_Handler(srv interface{}, stream grpc.ServerStream) error {- m := new(CreateInteractionEvent)- if err := stream.RecvMsg(m); err != nil {- return err- }- return srv.(InteractionsServiceServer).CreateInteraction(m, &grpc.GenericServerStream[CreateInteractionEvent, CreateInteractionResponse]{ServerStream: stream})-}--// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.-type InteractionsService_CreateInteractionServer = grpc.ServerStreamingServer[CreateInteractionResponse]--// InteractionsService_ServiceDesc is the grpc.ServiceDesc for InteractionsService service.-// It's only intended for direct use with grpc.RegisterService,-// and not to be introspected or modified (even as a copy)-var InteractionsService_ServiceDesc = grpc.ServiceDesc{- ServiceName: "ax.InteractionsService",- HandlerType: (*InteractionsServiceServer)(nil),- Methods: []grpc.MethodDesc{},- Streams: []grpc.StreamDesc{- {- StreamName: "CreateInteraction",- Handler: _InteractionsService_CreateInteraction_Handler,- ServerStreams: true,- },- },- Metadata: "proto/ax.proto",-}diff --git a/proto/content.pb.go b/proto/content.pb.godeleted file mode 100644index f3474d6..0000000--- a/proto/content.pb.go+++ /dev/null@@ -1,1352 +0,0 @@-// 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.--// Code generated by protoc-gen-go. DO NOT EDIT.-// versions:-// protoc-gen-go v1.36.11-// protoc v5.28.2-// source: proto/content.proto--package proto--import (- protoreflect "google.golang.org/protobuf/reflect/protoreflect"- protoimpl "google.golang.org/protobuf/runtime/protoimpl"- reflect "reflect"- sync "sync"- unsafe "unsafe"-)--const (- // Verify that this generated code is sufficiently up-to-date.- _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)- // Verify that runtime/protoimpl is sufficiently up-to-date.- _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)-)--// Resolution for input media (images/video).-type MediaResolution int32--const (- MediaResolution_MEDIA_RESOLUTION_UNSPECIFIED MediaResolution = 0- MediaResolution_LOW MediaResolution = 1- MediaResolution_MEDIUM MediaResolution = 2- MediaResolution_HIGH MediaResolution = 3- MediaResolution_ULTRA_HIGH MediaResolution = 4-)--// Enum value maps for MediaResolution.-var (- MediaResolution_name = map[int32]string{- 0: "MEDIA_RESOLUTION_UNSPECIFIED",- 1: "LOW",- 2: "MEDIUM",- 3: "HIGH",- 4: "ULTRA_HIGH",- }- MediaResolution_value = map[string]int32{- "MEDIA_RESOLUTION_UNSPECIFIED": 0,- "LOW": 1,- "MEDIUM": 2,- "HIGH": 3,- "ULTRA_HIGH": 4,- }-)--func (x MediaResolution) Enum() *MediaResolution {- p := new(MediaResolution)- *p = x- return p-}--func (x MediaResolution) String() string {- return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))-}--func (MediaResolution) Descriptor() protoreflect.EnumDescriptor {- return file_proto_content_proto_enumTypes[0].Descriptor()-}--func (MediaResolution) Type() protoreflect.EnumType {- return &file_proto_content_proto_enumTypes[0]-}--func (x MediaResolution) Number() protoreflect.EnumNumber {- return protoreflect.EnumNumber(x)-}--// Deprecated: Use MediaResolution.Descriptor instead.-func (MediaResolution) EnumDescriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{0}-}--type ImageContent_MimeType int32--const (- ImageContent_TYPE_UNSPECIFIED ImageContent_MimeType = 0- ImageContent_TYPE_PNG ImageContent_MimeType = 1 // image/png- ImageContent_TYPE_JPEG ImageContent_MimeType = 2 // image/jpeg- ImageContent_TYPE_WEBP ImageContent_MimeType = 3 // image/webp- ImageContent_TYPE_HEIC ImageContent_MimeType = 4 // image/heic- ImageContent_TYPE_HEIF ImageContent_MimeType = 5 // image/heif- ImageContent_TYPE_GIF ImageContent_MimeType = 7 // image/gif- ImageContent_TYPE_BMP ImageContent_MimeType = 8 // image/bmp- ImageContent_TYPE_TIFF ImageContent_MimeType = 9 // image/tiff-)--// Enum value maps for ImageContent_MimeType.-var (- ImageContent_MimeType_name = map[int32]string{- 0: "TYPE_UNSPECIFIED",- 1: "TYPE_PNG",- 2: "TYPE_JPEG",- 3: "TYPE_WEBP",- 4: "TYPE_HEIC",- 5: "TYPE_HEIF",- 7: "TYPE_GIF",- 8: "TYPE_BMP",- 9: "TYPE_TIFF",- }- ImageContent_MimeType_value = map[string]int32{- "TYPE_UNSPECIFIED": 0,- "TYPE_PNG": 1,- "TYPE_JPEG": 2,- "TYPE_WEBP": 3,- "TYPE_HEIC": 4,- "TYPE_HEIF": 5,- "TYPE_GIF": 7,- "TYPE_BMP": 8,- "TYPE_TIFF": 9,- }-)--func (x ImageContent_MimeType) Enum() *ImageContent_MimeType {- p := new(ImageContent_MimeType)- *p = x- return p-}--func (x ImageContent_MimeType) String() string {- return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))-}--func (ImageContent_MimeType) Descriptor() protoreflect.EnumDescriptor {- return file_proto_content_proto_enumTypes[1].Descriptor()-}--func (ImageContent_MimeType) Type() protoreflect.EnumType {- return &file_proto_content_proto_enumTypes[1]-}--func (x ImageContent_MimeType) Number() protoreflect.EnumNumber {- return protoreflect.EnumNumber(x)-}--// Deprecated: Use ImageContent_MimeType.Descriptor instead.-func (ImageContent_MimeType) EnumDescriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{4, 0}-}--type AudioContent_MimeType int32--const (- AudioContent_TYPE_UNSPECIFIED AudioContent_MimeType = 0- AudioContent_TYPE_WAV AudioContent_MimeType = 1 // audio/wav- AudioContent_TYPE_MP3 AudioContent_MimeType = 2 // audio/mp3- AudioContent_TYPE_AIFF AudioContent_MimeType = 3 // audio/aiff- AudioContent_TYPE_AAC AudioContent_MimeType = 4 // audio/aac- AudioContent_TYPE_OGG AudioContent_MimeType = 5 // audio/ogg- AudioContent_TYPE_FLAC AudioContent_MimeType = 6 // audio/flac- AudioContent_TYPE_MPEG AudioContent_MimeType = 7 // audio/mpeg- AudioContent_TYPE_M4A AudioContent_MimeType = 8 // audio/m4a- AudioContent_TYPE_L16 AudioContent_MimeType = 9 // audio/l16- AudioContent_TYPE_S16LE AudioContent_MimeType = 10 // audio/s16le- AudioContent_TYPE_OPUS AudioContent_MimeType = 11 // audio/opus- AudioContent_TYPE_ALAW AudioContent_MimeType = 12 // audio/alaw- AudioContent_TYPE_MULAW AudioContent_MimeType = 13 // audio/mulaw-)--// Enum value maps for AudioContent_MimeType.-var (- AudioContent_MimeType_name = map[int32]string{- 0: "TYPE_UNSPECIFIED",- 1: "TYPE_WAV",- 2: "TYPE_MP3",- 3: "TYPE_AIFF",- 4: "TYPE_AAC",- 5: "TYPE_OGG",- 6: "TYPE_FLAC",- 7: "TYPE_MPEG",- 8: "TYPE_M4A",- 9: "TYPE_L16",- 10: "TYPE_S16LE",- 11: "TYPE_OPUS",- 12: "TYPE_ALAW",- 13: "TYPE_MULAW",- }- AudioContent_MimeType_value = map[string]int32{- "TYPE_UNSPECIFIED": 0,- "TYPE_WAV": 1,- "TYPE_MP3": 2,- "TYPE_AIFF": 3,- "TYPE_AAC": 4,- "TYPE_OGG": 5,- "TYPE_FLAC": 6,- "TYPE_MPEG": 7,- "TYPE_M4A": 8,- "TYPE_L16": 9,- "TYPE_S16LE": 10,- "TYPE_OPUS": 11,- "TYPE_ALAW": 12,- "TYPE_MULAW": 13,- }-)--func (x AudioContent_MimeType) Enum() *AudioContent_MimeType {- p := new(AudioContent_MimeType)- *p = x- return p-}--func (x AudioContent_MimeType) String() string {- return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))-}--func (AudioContent_MimeType) Descriptor() protoreflect.EnumDescriptor {- return file_proto_content_proto_enumTypes[2].Descriptor()-}--func (AudioContent_MimeType) Type() protoreflect.EnumType {- return &file_proto_content_proto_enumTypes[2]-}--func (x AudioContent_MimeType) Number() protoreflect.EnumNumber {- return protoreflect.EnumNumber(x)-}--// Deprecated: Use AudioContent_MimeType.Descriptor instead.-func (AudioContent_MimeType) EnumDescriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{5, 0}-}--type DocumentContent_MimeType int32--const (- DocumentContent_TYPE_UNSPECIFIED DocumentContent_MimeType = 0- DocumentContent_TYPE_PDF DocumentContent_MimeType = 1 // application/pdf- DocumentContent_TYPE_JSON DocumentContent_MimeType = 2 // application/json- DocumentContent_TYPE_PYTHON DocumentContent_MimeType = 3 // text/x-python-)--// Enum value maps for DocumentContent_MimeType.-var (- DocumentContent_MimeType_name = map[int32]string{- 0: "TYPE_UNSPECIFIED",- 1: "TYPE_PDF",- 2: "TYPE_JSON",- 3: "TYPE_PYTHON",- }- DocumentContent_MimeType_value = map[string]int32{- "TYPE_UNSPECIFIED": 0,- "TYPE_PDF": 1,- "TYPE_JSON": 2,- "TYPE_PYTHON": 3,- }-)--func (x DocumentContent_MimeType) Enum() *DocumentContent_MimeType {- p := new(DocumentContent_MimeType)- *p = x- return p-}--func (x DocumentContent_MimeType) String() string {- return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))-}--func (DocumentContent_MimeType) Descriptor() protoreflect.EnumDescriptor {- return file_proto_content_proto_enumTypes[3].Descriptor()-}--func (DocumentContent_MimeType) Type() protoreflect.EnumType {- return &file_proto_content_proto_enumTypes[3]-}--func (x DocumentContent_MimeType) Number() protoreflect.EnumNumber {- return protoreflect.EnumNumber(x)-}--// Deprecated: Use DocumentContent_MimeType.Descriptor instead.-func (DocumentContent_MimeType) EnumDescriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{6, 0}-}--type VideoContent_MimeType int32--const (- VideoContent_TYPE_UNSPECIFIED VideoContent_MimeType = 0- VideoContent_TYPE_MP4 VideoContent_MimeType = 1 // video/mp4- VideoContent_TYPE_MPEG VideoContent_MimeType = 2 // video/mpeg- VideoContent_TYPE_MPG VideoContent_MimeType = 3 // video/mpg- VideoContent_TYPE_MOV VideoContent_MimeType = 4 // video/mov- VideoContent_TYPE_AVI VideoContent_MimeType = 5 // video/avi- VideoContent_TYPE_X_FLV VideoContent_MimeType = 6 // video/x-flv- VideoContent_TYPE_WEBM VideoContent_MimeType = 7 // video/webm- VideoContent_TYPE_WMV VideoContent_MimeType = 8 // video/wmv- VideoContent_TYPE_3GPP VideoContent_MimeType = 9 // video/3gpp-)--// Enum value maps for VideoContent_MimeType.-var (- VideoContent_MimeType_name = map[int32]string{- 0: "TYPE_UNSPECIFIED",- 1: "TYPE_MP4",- 2: "TYPE_MPEG",- 3: "TYPE_MPG",- 4: "TYPE_MOV",- 5: "TYPE_AVI",- 6: "TYPE_X_FLV",- 7: "TYPE_WEBM",- 8: "TYPE_WMV",- 9: "TYPE_3GPP",- }- VideoContent_MimeType_value = map[string]int32{- "TYPE_UNSPECIFIED": 0,- "TYPE_MP4": 1,- "TYPE_MPEG": 2,- "TYPE_MPG": 3,- "TYPE_MOV": 4,- "TYPE_AVI": 5,- "TYPE_X_FLV": 6,- "TYPE_WEBM": 7,- "TYPE_WMV": 8,- "TYPE_3GPP": 9,- }-)--func (x VideoContent_MimeType) Enum() *VideoContent_MimeType {- p := new(VideoContent_MimeType)- *p = x- return p-}--func (x VideoContent_MimeType) String() string {- return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))-}--func (VideoContent_MimeType) Descriptor() protoreflect.EnumDescriptor {- return file_proto_content_proto_enumTypes[4].Descriptor()-}--func (VideoContent_MimeType) Type() protoreflect.EnumType {- return &file_proto_content_proto_enumTypes[4]-}--func (x VideoContent_MimeType) Number() protoreflect.EnumNumber {- return protoreflect.EnumNumber(x)-}--// Deprecated: Use VideoContent_MimeType.Descriptor instead.-func (VideoContent_MimeType) EnumDescriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{7, 0}-}--// TextContent represents a text content.-type TextContent struct {- state protoimpl.MessageState `protogen:"open.v1"`- Text string `protobuf:"bytes,3,opt,name=text,proto3" json:"text,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *TextContent) Reset() {- *x = TextContent{}- mi := &file_proto_content_proto_msgTypes[0]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *TextContent) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*TextContent) ProtoMessage() {}--func (x *TextContent) ProtoReflect() protoreflect.Message {- mi := &file_proto_content_proto_msgTypes[0]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use TextContent.ProtoReflect.Descriptor instead.-func (*TextContent) Descriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{0}-}--func (x *TextContent) GetText() string {- if x != nil {- return x.Text- }- return ""-}--type ApprovalDecision struct {- state protoimpl.MessageState `protogen:"open.v1"`- Approved bool `protobuf:"varint,1,opt,name=approved,proto3" json:"approved,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *ApprovalDecision) Reset() {- *x = ApprovalDecision{}- mi := &file_proto_content_proto_msgTypes[1]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *ApprovalDecision) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*ApprovalDecision) ProtoMessage() {}--func (x *ApprovalDecision) ProtoReflect() protoreflect.Message {- mi := &file_proto_content_proto_msgTypes[1]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use ApprovalDecision.ProtoReflect.Descriptor instead.-func (*ApprovalDecision) Descriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{1}-}--func (x *ApprovalDecision) GetApproved() bool {- if x != nil {- return x.Approved- }- return false-}--type DeclineDecision struct {- state protoimpl.MessageState `protogen:"open.v1"`- Declined bool `protobuf:"varint,1,opt,name=declined,proto3" json:"declined,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *DeclineDecision) Reset() {- *x = DeclineDecision{}- mi := &file_proto_content_proto_msgTypes[2]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *DeclineDecision) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*DeclineDecision) ProtoMessage() {}--func (x *DeclineDecision) ProtoReflect() protoreflect.Message {- mi := &file_proto_content_proto_msgTypes[2]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use DeclineDecision.ProtoReflect.Descriptor instead.-func (*DeclineDecision) Descriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{2}-}--func (x *DeclineDecision) GetDeclined() bool {- if x != nil {- return x.Declined- }- return false-}--type ConfirmationContent struct {- state protoimpl.MessageState `protogen:"open.v1"`- Id string `protobuf:"bytes,3,opt,name=id,proto3" json:"id,omitempty"`- Question string `protobuf:"bytes,4,opt,name=question,proto3" json:"question,omitempty"`- // Types that are valid to be assigned to Decision:- //- // *ConfirmationContent_Approval- // *ConfirmationContent_Decline- Decision isConfirmationContent_Decision `protobuf_oneof:"decision"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *ConfirmationContent) Reset() {- *x = ConfirmationContent{}- mi := &file_proto_content_proto_msgTypes[3]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *ConfirmationContent) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*ConfirmationContent) ProtoMessage() {}--func (x *ConfirmationContent) ProtoReflect() protoreflect.Message {- mi := &file_proto_content_proto_msgTypes[3]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use ConfirmationContent.ProtoReflect.Descriptor instead.-func (*ConfirmationContent) Descriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{3}-}--func (x *ConfirmationContent) GetId() string {- if x != nil {- return x.Id- }- return ""-}--func (x *ConfirmationContent) GetQuestion() string {- if x != nil {- return x.Question- }- return ""-}--func (x *ConfirmationContent) GetDecision() isConfirmationContent_Decision {- if x != nil {- return x.Decision- }- return nil-}--func (x *ConfirmationContent) GetApproval() *ApprovalDecision {- if x != nil {- if x, ok := x.Decision.(*ConfirmationContent_Approval); ok {- return x.Approval- }- }- return nil-}--func (x *ConfirmationContent) GetDecline() *DeclineDecision {- if x != nil {- if x, ok := x.Decision.(*ConfirmationContent_Decline); ok {- return x.Decline- }- }- return nil-}--type isConfirmationContent_Decision interface {- isConfirmationContent_Decision()-}--type ConfirmationContent_Approval struct {- Approval *ApprovalDecision `protobuf:"bytes,5,opt,name=approval,proto3,oneof"`-}--type ConfirmationContent_Decline struct {- Decline *DeclineDecision `protobuf:"bytes,6,opt,name=decline,proto3,oneof"`-}--func (*ConfirmationContent_Approval) isConfirmationContent_Decision() {}--func (*ConfirmationContent_Decline) isConfirmationContent_Decision() {}--// An image content block.-type ImageContent struct {- state protoimpl.MessageState `protogen:"open.v1"`- MimeType ImageContent_MimeType `protobuf:"varint,1,opt,name=mime_type,json=mimeType,proto3,enum=ax.ImageContent_MimeType" json:"mime_type,omitempty"`- // Types that are valid to be assigned to DataOrUri:- //- // *ImageContent_Data- // *ImageContent_Uri- DataOrUri isImageContent_DataOrUri `protobuf_oneof:"data_or_uri"`- Resolution MediaResolution `protobuf:"varint,5,opt,name=resolution,proto3,enum=ax.MediaResolution" json:"resolution,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *ImageContent) Reset() {- *x = ImageContent{}- mi := &file_proto_content_proto_msgTypes[4]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *ImageContent) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*ImageContent) ProtoMessage() {}--func (x *ImageContent) ProtoReflect() protoreflect.Message {- mi := &file_proto_content_proto_msgTypes[4]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use ImageContent.ProtoReflect.Descriptor instead.-func (*ImageContent) Descriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{4}-}--func (x *ImageContent) GetMimeType() ImageContent_MimeType {- if x != nil {- return x.MimeType- }- return ImageContent_TYPE_UNSPECIFIED-}--func (x *ImageContent) GetDataOrUri() isImageContent_DataOrUri {- if x != nil {- return x.DataOrUri- }- return nil-}--func (x *ImageContent) GetData() []byte {- if x != nil {- if x, ok := x.DataOrUri.(*ImageContent_Data); ok {- return x.Data- }- }- return nil-}--func (x *ImageContent) GetUri() string {- if x != nil {- if x, ok := x.DataOrUri.(*ImageContent_Uri); ok {- return x.Uri- }- }- return ""-}--func (x *ImageContent) GetResolution() MediaResolution {- if x != nil {- return x.Resolution- }- return MediaResolution_MEDIA_RESOLUTION_UNSPECIFIED-}--type isImageContent_DataOrUri interface {- isImageContent_DataOrUri()-}--type ImageContent_Data struct {- Data []byte `protobuf:"bytes,2,opt,name=data,proto3,oneof"`-}--type ImageContent_Uri struct {- Uri string `protobuf:"bytes,6,opt,name=uri,proto3,oneof"`-}--func (*ImageContent_Data) isImageContent_DataOrUri() {}--func (*ImageContent_Uri) isImageContent_DataOrUri() {}--// An audio content block.-type AudioContent struct {- state protoimpl.MessageState `protogen:"open.v1"`- MimeType AudioContent_MimeType `protobuf:"varint,1,opt,name=mime_type,json=mimeType,proto3,enum=ax.AudioContent_MimeType" json:"mime_type,omitempty"`- // Types that are valid to be assigned to DataOrUri:- //- // *AudioContent_Data- // *AudioContent_Uri- DataOrUri isAudioContent_DataOrUri `protobuf_oneof:"data_or_uri"`- Channels int32 `protobuf:"varint,7,opt,name=channels,proto3" json:"channels,omitempty"`- SampleRate int32 `protobuf:"varint,8,opt,name=sample_rate,json=sampleRate,proto3" json:"sample_rate,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *AudioContent) Reset() {- *x = AudioContent{}- mi := &file_proto_content_proto_msgTypes[5]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *AudioContent) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*AudioContent) ProtoMessage() {}--func (x *AudioContent) ProtoReflect() protoreflect.Message {- mi := &file_proto_content_proto_msgTypes[5]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use AudioContent.ProtoReflect.Descriptor instead.-func (*AudioContent) Descriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{5}-}--func (x *AudioContent) GetMimeType() AudioContent_MimeType {- if x != nil {- return x.MimeType- }- return AudioContent_TYPE_UNSPECIFIED-}--func (x *AudioContent) GetDataOrUri() isAudioContent_DataOrUri {- if x != nil {- return x.DataOrUri- }- return nil-}--func (x *AudioContent) GetData() []byte {- if x != nil {- if x, ok := x.DataOrUri.(*AudioContent_Data); ok {- return x.Data- }- }- return nil-}--func (x *AudioContent) GetUri() string {- if x != nil {- if x, ok := x.DataOrUri.(*AudioContent_Uri); ok {- return x.Uri- }- }- return ""-}--func (x *AudioContent) GetChannels() int32 {- if x != nil {- return x.Channels- }- return 0-}--func (x *AudioContent) GetSampleRate() int32 {- if x != nil {- return x.SampleRate- }- return 0-}--type isAudioContent_DataOrUri interface {- isAudioContent_DataOrUri()-}--type AudioContent_Data struct {- Data []byte `protobuf:"bytes,2,opt,name=data,proto3,oneof"`-}--type AudioContent_Uri struct {- Uri string `protobuf:"bytes,5,opt,name=uri,proto3,oneof"`-}--func (*AudioContent_Data) isAudioContent_DataOrUri() {}--func (*AudioContent_Uri) isAudioContent_DataOrUri() {}--// A document content block.-type DocumentContent struct {- state protoimpl.MessageState `protogen:"open.v1"`- MimeType DocumentContent_MimeType `protobuf:"varint,1,opt,name=mime_type,json=mimeType,proto3,enum=ax.DocumentContent_MimeType" json:"mime_type,omitempty"`- // Types that are valid to be assigned to DataOrUri:- //- // *DocumentContent_Data- // *DocumentContent_Uri- DataOrUri isDocumentContent_DataOrUri `protobuf_oneof:"data_or_uri"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *DocumentContent) Reset() {- *x = DocumentContent{}- mi := &file_proto_content_proto_msgTypes[6]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *DocumentContent) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*DocumentContent) ProtoMessage() {}--func (x *DocumentContent) ProtoReflect() protoreflect.Message {- mi := &file_proto_content_proto_msgTypes[6]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use DocumentContent.ProtoReflect.Descriptor instead.-func (*DocumentContent) Descriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{6}-}--func (x *DocumentContent) GetMimeType() DocumentContent_MimeType {- if x != nil {- return x.MimeType- }- return DocumentContent_TYPE_UNSPECIFIED-}--func (x *DocumentContent) GetDataOrUri() isDocumentContent_DataOrUri {- if x != nil {- return x.DataOrUri- }- return nil-}--func (x *DocumentContent) GetData() []byte {- if x != nil {- if x, ok := x.DataOrUri.(*DocumentContent_Data); ok {- return x.Data- }- }- return nil-}--func (x *DocumentContent) GetUri() string {- if x != nil {- if x, ok := x.DataOrUri.(*DocumentContent_Uri); ok {- return x.Uri- }- }- return ""-}--type isDocumentContent_DataOrUri interface {- isDocumentContent_DataOrUri()-}--type DocumentContent_Data struct {- Data []byte `protobuf:"bytes,2,opt,name=data,proto3,oneof"`-}--type DocumentContent_Uri struct {- Uri string `protobuf:"bytes,5,opt,name=uri,proto3,oneof"`-}--func (*DocumentContent_Data) isDocumentContent_DataOrUri() {}--func (*DocumentContent_Uri) isDocumentContent_DataOrUri() {}--// A video content block.-type VideoContent struct {- state protoimpl.MessageState `protogen:"open.v1"`- MimeType VideoContent_MimeType `protobuf:"varint,1,opt,name=mime_type,json=mimeType,proto3,enum=ax.VideoContent_MimeType" json:"mime_type,omitempty"`- // Types that are valid to be assigned to DataOrUri:- //- // *VideoContent_Data- // *VideoContent_Uri- DataOrUri isVideoContent_DataOrUri `protobuf_oneof:"data_or_uri"`- Resolution MediaResolution `protobuf:"varint,5,opt,name=resolution,proto3,enum=ax.MediaResolution" json:"resolution,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *VideoContent) Reset() {- *x = VideoContent{}- mi := &file_proto_content_proto_msgTypes[7]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *VideoContent) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*VideoContent) ProtoMessage() {}--func (x *VideoContent) ProtoReflect() protoreflect.Message {- mi := &file_proto_content_proto_msgTypes[7]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use VideoContent.ProtoReflect.Descriptor instead.-func (*VideoContent) Descriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{7}-}--func (x *VideoContent) GetMimeType() VideoContent_MimeType {- if x != nil {- return x.MimeType- }- return VideoContent_TYPE_UNSPECIFIED-}--func (x *VideoContent) GetDataOrUri() isVideoContent_DataOrUri {- if x != nil {- return x.DataOrUri- }- return nil-}--func (x *VideoContent) GetData() []byte {- if x != nil {- if x, ok := x.DataOrUri.(*VideoContent_Data); ok {- return x.Data- }- }- return nil-}--func (x *VideoContent) GetUri() string {- if x != nil {- if x, ok := x.DataOrUri.(*VideoContent_Uri); ok {- return x.Uri- }- }- return ""-}--func (x *VideoContent) GetResolution() MediaResolution {- if x != nil {- return x.Resolution- }- return MediaResolution_MEDIA_RESOLUTION_UNSPECIFIED-}--type isVideoContent_DataOrUri interface {- isVideoContent_DataOrUri()-}--type VideoContent_Data struct {- Data []byte `protobuf:"bytes,2,opt,name=data,proto3,oneof"`-}--type VideoContent_Uri struct {- Uri string `protobuf:"bytes,6,opt,name=uri,proto3,oneof"`-}--func (*VideoContent_Data) isVideoContent_DataOrUri() {}--func (*VideoContent_Uri) isVideoContent_DataOrUri() {}--type Content struct {- state protoimpl.MessageState `protogen:"open.v1"`- // Types that are valid to be assigned to Type:- //- // *Content_Text- // *Content_Image- // *Content_Audio- // *Content_Document- // *Content_Video- // *Content_Confirmation- Type isContent_Type `protobuf_oneof:"type"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *Content) Reset() {- *x = Content{}- mi := &file_proto_content_proto_msgTypes[8]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *Content) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*Content) ProtoMessage() {}--func (x *Content) ProtoReflect() protoreflect.Message {- mi := &file_proto_content_proto_msgTypes[8]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use Content.ProtoReflect.Descriptor instead.-func (*Content) Descriptor() ([]byte, []int) {- return file_proto_content_proto_rawDescGZIP(), []int{8}-}--func (x *Content) GetType() isContent_Type {- if x != nil {- return x.Type- }- return nil-}--func (x *Content) GetText() *TextContent {- if x != nil {- if x, ok := x.Type.(*Content_Text); ok {- return x.Text- }- }- return nil-}--func (x *Content) GetImage() *ImageContent {- if x != nil {- if x, ok := x.Type.(*Content_Image); ok {- return x.Image- }- }- return nil-}--func (x *Content) GetAudio() *AudioContent {- if x != nil {- if x, ok := x.Type.(*Content_Audio); ok {- return x.Audio- }- }- return nil-}--func (x *Content) GetDocument() *DocumentContent {- if x != nil {- if x, ok := x.Type.(*Content_Document); ok {- return x.Document- }- }- return nil-}--func (x *Content) GetVideo() *VideoContent {- if x != nil {- if x, ok := x.Type.(*Content_Video); ok {- return x.Video- }- }- return nil-}--func (x *Content) GetConfirmation() *ConfirmationContent {- if x != nil {- if x, ok := x.Type.(*Content_Confirmation); ok {- return x.Confirmation- }- }- return nil-}--type isContent_Type interface {- isContent_Type()-}--type Content_Text struct {- Text *TextContent `protobuf:"bytes,10,opt,name=text,proto3,oneof"`-}--type Content_Image struct {- Image *ImageContent `protobuf:"bytes,11,opt,name=image,proto3,oneof"`-}--type Content_Audio struct {- Audio *AudioContent `protobuf:"bytes,12,opt,name=audio,proto3,oneof"`-}--type Content_Document struct {- Document *DocumentContent `protobuf:"bytes,13,opt,name=document,proto3,oneof"`-}--type Content_Video struct {- Video *VideoContent `protobuf:"bytes,14,opt,name=video,proto3,oneof"`-}--type Content_Confirmation struct {- Confirmation *ConfirmationContent `protobuf:"bytes,26,opt,name=confirmation,proto3,oneof"` // TODO(jbd): Remove out of the Content and replace it with EliciationStep.-}--func (*Content_Text) isContent_Type() {}--func (*Content_Image) isContent_Type() {}--func (*Content_Audio) isContent_Type() {}--func (*Content_Document) isContent_Type() {}--func (*Content_Video) isContent_Type() {}--func (*Content_Confirmation) isContent_Type() {}--var File_proto_content_proto protoreflect.FileDescriptor--const file_proto_content_proto_rawDesc = "" +- "\n" +- "\x13proto/content.proto\x12\x02ax\"3\n" +- "\vTextContent\x12\x12\n" +- "\x04text\x18\x03 \x01(\tR\x04textJ\x04\b\x01\x10\x02J\x04\b\x02\x10\x03R\x04type\".\n" +- "\x10ApprovalDecision\x12\x1a\n" +- "\bapproved\x18\x01 \x01(\bR\bapproved\";\n" +- "\x0fDeclineDecision\x12\x1a\n" +- "\bdeclined\x18\x01 \x01(\bR\bdeclinedJ\x04\b\x02\x10\x03R\x06reason\"\xc4\x01\n" +- "\x13ConfirmationContent\x12\x0e\n" +- "\x02id\x18\x03 \x01(\tR\x02id\x12\x1a\n" +- "\bquestion\x18\x04 \x01(\tR\bquestion\x122\n" +- "\bapproval\x18\x05 \x01(\v2\x14.ax.ApprovalDecisionH\x00R\bapproval\x12/\n" +- "\adecline\x18\x06 \x01(\v2\x13.ax.DeclineDecisionH\x00R\adeclineB\n" +- "\n" +- "\bdecisionJ\x04\b\x01\x10\x02J\x04\b\x02\x10\x03R\x04type\"\xde\x02\n" +- "\fImageContent\x126\n" +- "\tmime_type\x18\x01 \x01(\x0e2\x19.ax.ImageContent.MimeTypeR\bmimeType\x12\x14\n" +- "\x04data\x18\x02 \x01(\fH\x00R\x04data\x12\x12\n" +- "\x03uri\x18\x06 \x01(\tH\x00R\x03uri\x123\n" +- "\n" +- "resolution\x18\x05 \x01(\x0e2\x13.ax.MediaResolutionR\n" +- "resolution\"\x9b\x01\n" +- "\bMimeType\x12\x14\n" +- "\x10TYPE_UNSPECIFIED\x10\x00\x12\f\n" +- "\bTYPE_PNG\x10\x01\x12\r\n" +- "\tTYPE_JPEG\x10\x02\x12\r\n" +- "\tTYPE_WEBP\x10\x03\x12\r\n" +- "\tTYPE_HEIC\x10\x04\x12\r\n" +- "\tTYPE_HEIF\x10\x05\x12\f\n" +- "\bTYPE_GIF\x10\a\x12\f\n" +- "\bTYPE_BMP\x10\b\x12\r\n" +- "\tTYPE_TIFF\x10\t\"\x04\b\x06\x10\x06B\r\n" +- "\vdata_or_uriJ\x04\b\x03\x10\x04R\x04type\"\xb6\x03\n" +- "\fAudioContent\x126\n" +- "\tmime_type\x18\x01 \x01(\x0e2\x19.ax.AudioContent.MimeTypeR\bmimeType\x12\x14\n" +- "\x04data\x18\x02 \x01(\fH\x00R\x04data\x12\x12\n" +- "\x03uri\x18\x05 \x01(\tH\x00R\x03uri\x12\x1a\n" +- "\bchannels\x18\a \x01(\x05R\bchannels\x12\x1f\n" +- "\vsample_rate\x18\b \x01(\x05R\n" +- "sampleRate\"\xdf\x01\n" +- "\bMimeType\x12\x14\n" +- "\x10TYPE_UNSPECIFIED\x10\x00\x12\f\n" +- "\bTYPE_WAV\x10\x01\x12\f\n" +- "\bTYPE_MP3\x10\x02\x12\r\n" +- "\tTYPE_AIFF\x10\x03\x12\f\n" +- "\bTYPE_AAC\x10\x04\x12\f\n" +- "\bTYPE_OGG\x10\x05\x12\r\n" +- "\tTYPE_FLAC\x10\x06\x12\r\n" +- "\tTYPE_MPEG\x10\a\x12\f\n" +- "\bTYPE_M4A\x10\b\x12\f\n" +- "\bTYPE_L16\x10\t\x12\x0e\n" +- "\n" +- "TYPE_S16LE\x10\n" +- "\x12\r\n" +- "\tTYPE_OPUS\x10\v\x12\r\n" +- "\tTYPE_ALAW\x10\f\x12\x0e\n" +- "\n" +- "TYPE_MULAW\x10\rB\r\n" +- "\vdata_or_uriJ\x04\b\x03\x10\x04J\x04\b\x06\x10\aR\x04typeR\x04rate\"\xe1\x01\n" +- "\x0fDocumentContent\x129\n" +- "\tmime_type\x18\x01 \x01(\x0e2\x1c.ax.DocumentContent.MimeTypeR\bmimeType\x12\x14\n" +- "\x04data\x18\x02 \x01(\fH\x00R\x04data\x12\x12\n" +- "\x03uri\x18\x05 \x01(\tH\x00R\x03uri\"N\n" +- "\bMimeType\x12\x14\n" +- "\x10TYPE_UNSPECIFIED\x10\x00\x12\f\n" +- "\bTYPE_PDF\x10\x01\x12\r\n" +- "\tTYPE_JSON\x10\x02\x12\x0f\n" +- "\vTYPE_PYTHON\x10\x03B\r\n" +- "\vdata_or_uriJ\x04\b\x03\x10\x04R\x04type\"\xe6\x02\n" +- "\fVideoContent\x126\n" +- "\tmime_type\x18\x01 \x01(\x0e2\x19.ax.VideoContent.MimeTypeR\bmimeType\x12\x14\n" +- "\x04data\x18\x02 \x01(\fH\x00R\x04data\x12\x12\n" +- "\x03uri\x18\x06 \x01(\tH\x00R\x03uri\x123\n" +- "\n" +- "resolution\x18\x05 \x01(\x0e2\x13.ax.MediaResolutionR\n" +- "resolution\"\xa3\x01\n" +- "\bMimeType\x12\x14\n" +- "\x10TYPE_UNSPECIFIED\x10\x00\x12\f\n" +- "\bTYPE_MP4\x10\x01\x12\r\n" +- "\tTYPE_MPEG\x10\x02\x12\f\n" +- "\bTYPE_MPG\x10\x03\x12\f\n" +- "\bTYPE_MOV\x10\x04\x12\f\n" +- "\bTYPE_AVI\x10\x05\x12\x0e\n" +- "\n" +- "TYPE_X_FLV\x10\x06\x12\r\n" +- "\tTYPE_WEBM\x10\a\x12\f\n" +- "\bTYPE_WMV\x10\b\x12\r\n" +- "\tTYPE_3GPP\x10\tB\r\n" +- "\vdata_or_uriJ\x04\b\x03\x10\x04R\x04type\"\xb4\x02\n" +- "\aContent\x12%\n" +- "\x04text\x18\n" +- " \x01(\v2\x0f.ax.TextContentH\x00R\x04text\x12(\n" +- "\x05image\x18\v \x01(\v2\x10.ax.ImageContentH\x00R\x05image\x12(\n" +- "\x05audio\x18\f \x01(\v2\x10.ax.AudioContentH\x00R\x05audio\x121\n" +- "\bdocument\x18\r \x01(\v2\x13.ax.DocumentContentH\x00R\bdocument\x12(\n" +- "\x05video\x18\x0e \x01(\v2\x10.ax.VideoContentH\x00R\x05video\x12=\n" +- "\fconfirmation\x18\x1a \x01(\v2\x17.ax.ConfirmationContentH\x00R\fconfirmationB\x06\n" +- "\x04typeJ\x04\b\x01\x10\n" +- "J\x04\b\x0f\x10\x1a*b\n" +- "\x0fMediaResolution\x12 \n" +- "\x1cMEDIA_RESOLUTION_UNSPECIFIED\x10\x00\x12\a\n" +- "\x03LOW\x10\x01\x12\n" +- "\n" +- "\x06MEDIUM\x10\x02\x12\b\n" +- "\x04HIGH\x10\x03\x12\x0e\n" +- "\n" +- "ULTRA_HIGH\x10\x04B\x1cZ\x1agithub.com/google/ax/protob\x06proto3"--var (- file_proto_content_proto_rawDescOnce sync.Once- file_proto_content_proto_rawDescData []byte-)--func file_proto_content_proto_rawDescGZIP() []byte {- file_proto_content_proto_rawDescOnce.Do(func() {- file_proto_content_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proto_content_proto_rawDesc), len(file_proto_content_proto_rawDesc)))- })- return file_proto_content_proto_rawDescData-}--var file_proto_content_proto_enumTypes = make([]protoimpl.EnumInfo, 5)-var file_proto_content_proto_msgTypes = make([]protoimpl.MessageInfo, 9)-var file_proto_content_proto_goTypes = []any{- (MediaResolution)(0), // 0: ax.MediaResolution- (ImageContent_MimeType)(0), // 1: ax.ImageContent.MimeType- (AudioContent_MimeType)(0), // 2: ax.AudioContent.MimeType- (DocumentContent_MimeType)(0), // 3: ax.DocumentContent.MimeType- (VideoContent_MimeType)(0), // 4: ax.VideoContent.MimeType- (*TextContent)(nil), // 5: ax.TextContent- (*ApprovalDecision)(nil), // 6: ax.ApprovalDecision- (*DeclineDecision)(nil), // 7: ax.DeclineDecision- (*ConfirmationContent)(nil), // 8: ax.ConfirmationContent- (*ImageContent)(nil), // 9: ax.ImageContent- (*AudioContent)(nil), // 10: ax.AudioContent- (*DocumentContent)(nil), // 11: ax.DocumentContent- (*VideoContent)(nil), // 12: ax.VideoContent- (*Content)(nil), // 13: ax.Content-}-var file_proto_content_proto_depIdxs = []int32{- 6, // 0: ax.ConfirmationContent.approval:type_name -> ax.ApprovalDecision- 7, // 1: ax.ConfirmationContent.decline:type_name -> ax.DeclineDecision- 1, // 2: ax.ImageContent.mime_type:type_name -> ax.ImageContent.MimeType- 0, // 3: ax.ImageContent.resolution:type_name -> ax.MediaResolution- 2, // 4: ax.AudioContent.mime_type:type_name -> ax.AudioContent.MimeType- 3, // 5: ax.DocumentContent.mime_type:type_name -> ax.DocumentContent.MimeType- 4, // 6: ax.VideoContent.mime_type:type_name -> ax.VideoContent.MimeType- 0, // 7: ax.VideoContent.resolution:type_name -> ax.MediaResolution- 5, // 8: ax.Content.text:type_name -> ax.TextContent- 9, // 9: ax.Content.image:type_name -> ax.ImageContent- 10, // 10: ax.Content.audio:type_name -> ax.AudioContent- 11, // 11: ax.Content.document:type_name -> ax.DocumentContent- 12, // 12: ax.Content.video:type_name -> ax.VideoContent- 8, // 13: ax.Content.confirmation:type_name -> ax.ConfirmationContent- 14, // [14:14] is the sub-list for method output_type- 14, // [14:14] is the sub-list for method input_type- 14, // [14:14] is the sub-list for extension type_name- 14, // [14:14] is the sub-list for extension extendee- 0, // [0:14] is the sub-list for field type_name-}--func init() { file_proto_content_proto_init() }-func file_proto_content_proto_init() {- if File_proto_content_proto != nil {- return- }- file_proto_content_proto_msgTypes[3].OneofWrappers = []any{- (*ConfirmationContent_Approval)(nil),- (*ConfirmationContent_Decline)(nil),- }- file_proto_content_proto_msgTypes[4].OneofWrappers = []any{- (*ImageContent_Data)(nil),- (*ImageContent_Uri)(nil),- }- file_proto_content_proto_msgTypes[5].OneofWrappers = []any{- (*AudioContent_Data)(nil),- (*AudioContent_Uri)(nil),- }- file_proto_content_proto_msgTypes[6].OneofWrappers = []any{- (*DocumentContent_Data)(nil),- (*DocumentContent_Uri)(nil),- }- file_proto_content_proto_msgTypes[7].OneofWrappers = []any{- (*VideoContent_Data)(nil),- (*VideoContent_Uri)(nil),- }- file_proto_content_proto_msgTypes[8].OneofWrappers = []any{- (*Content_Text)(nil),- (*Content_Image)(nil),- (*Content_Audio)(nil),- (*Content_Document)(nil),- (*Content_Video)(nil),- (*Content_Confirmation)(nil),- }- type x struct{}- out := protoimpl.TypeBuilder{- File: protoimpl.DescBuilder{- GoPackagePath: reflect.TypeOf(x{}).PkgPath(),- RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_content_proto_rawDesc), len(file_proto_content_proto_rawDesc)),- NumEnums: 5,- NumMessages: 9,- NumExtensions: 0,- NumServices: 0,- },- GoTypes: file_proto_content_proto_goTypes,- DependencyIndexes: file_proto_content_proto_depIdxs,- EnumInfos: file_proto_content_proto_enumTypes,- MessageInfos: file_proto_content_proto_msgTypes,- }.Build()- File_proto_content_proto = out.File- file_proto_content_proto_goTypes = nil- file_proto_content_proto_depIdxs = nil-}diff --git a/proto/content.proto b/proto/content.protodeleted file mode 100644index f703615..0000000--- a/proto/content.proto+++ /dev/null@@ -1,167 +0,0 @@-// 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.--syntax = "proto3";--package ax;--option go_package = "github.com/google/ax/proto";--// TextContent represents a text content.-message TextContent {- reserved 1, 2;- reserved "type";- string text = 3;-}--message ApprovalDecision {- bool approved = 1;-}--message DeclineDecision {- reserved 2;- reserved "reason";- bool declined = 1;-}--message ConfirmationContent {- reserved 1, 2;- reserved "type";- string id = 3;- string question = 4;- oneof decision {- ApprovalDecision approval = 5;- DeclineDecision decline = 6;- }-}--// Resolution for input media (images/video).-enum MediaResolution {- MEDIA_RESOLUTION_UNSPECIFIED = 0;- LOW = 1;- MEDIUM = 2;- HIGH = 3;- ULTRA_HIGH = 4;-}--// An image content block.-message ImageContent {- reserved 3;- reserved "type";-- enum MimeType {- reserved 6;- TYPE_UNSPECIFIED = 0;- TYPE_PNG = 1; // image/png- TYPE_JPEG = 2; // image/jpeg- TYPE_WEBP = 3; // image/webp- TYPE_HEIC = 4; // image/heic- TYPE_HEIF = 5; // image/heif- TYPE_GIF = 7; // image/gif- TYPE_BMP = 8; // image/bmp- TYPE_TIFF = 9; // image/tiff- }- MimeType mime_type = 1;- oneof data_or_uri {- bytes data = 2;- string uri = 6;- }- MediaResolution resolution = 5;-}--// An audio content block.-message AudioContent {- reserved 3, 6;- reserved "type", "rate";-- enum MimeType {- TYPE_UNSPECIFIED = 0;- TYPE_WAV = 1; // audio/wav- TYPE_MP3 = 2; // audio/mp3- TYPE_AIFF = 3; // audio/aiff- TYPE_AAC = 4; // audio/aac- TYPE_OGG = 5; // audio/ogg- TYPE_FLAC = 6; // audio/flac- TYPE_MPEG = 7; // audio/mpeg- TYPE_M4A = 8; // audio/m4a- TYPE_L16 = 9; // audio/l16- TYPE_S16LE = 10; // audio/s16le- TYPE_OPUS = 11; // audio/opus- TYPE_ALAW = 12; // audio/alaw- TYPE_MULAW = 13; // audio/mulaw- }- MimeType mime_type = 1;- oneof data_or_uri {- bytes data = 2;- string uri = 5;- }- int32 channels = 7;- int32 sample_rate = 8;-}--// A document content block.-message DocumentContent {- reserved 3;- reserved "type";-- enum MimeType {- TYPE_UNSPECIFIED = 0;- TYPE_PDF = 1; // application/pdf- TYPE_JSON = 2; // application/json- TYPE_PYTHON = 3; // text/x-python- }- MimeType mime_type = 1;- oneof data_or_uri {- bytes data = 2;- string uri = 5;- }-}--// A video content block.-message VideoContent {- reserved 3;- reserved "type";-- enum MimeType {- TYPE_UNSPECIFIED = 0;- TYPE_MP4 = 1; // video/mp4- TYPE_MPEG = 2; // video/mpeg- TYPE_MPG = 3; // video/mpg- TYPE_MOV = 4; // video/mov- TYPE_AVI = 5; // video/avi- TYPE_X_FLV = 6; // video/x-flv- TYPE_WEBM = 7; // video/webm- TYPE_WMV = 8; // video/wmv- TYPE_3GPP = 9; // video/3gpp- }- MimeType mime_type = 1;- oneof data_or_uri {- bytes data = 2;- string uri = 6;- }- MediaResolution resolution = 5;-}--message Content {- reserved 1 to 9, 15 to 25;-- oneof type {- TextContent text = 10;- ImageContent image = 11;- AudioContent audio = 12;- DocumentContent document = 13;- VideoContent video = 14;- ConfirmationContent confirmation = 26; // TODO(jbd): Remove out of the Content and replace it with EliciationStep.- }-}diff --git a/python/antigravity/__init__.py b/python/antigravity/__init__.pydeleted file mode 100644index 58d482e..0000000--- a/python/antigravity/__init__.py+++ /dev/null@@ -1,13 +0,0 @@-# 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.diff --git a/python/antigravity/config.json b/python/antigravity/config.jsondeleted file mode 100644index 9f78bbb..0000000--- a/python/antigravity/config.json+++ /dev/null@@ -1,3 +0,0 @@-{- "model": "gemini-3.1-pro-preview"-}\ No newline at end of filediff --git a/python/antigravity/harness_server.py b/python/antigravity/harness_server.pydeleted file mode 100644index 2a11e31..0000000--- a/python/antigravity/harness_server.py+++ /dev/null@@ -1,501 +0,0 @@-# 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-#-# https://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.--# NOTE ON ARCHITECTURE:-# This gRPC server implements the AX HarnessService protocol. It embeds the-# Antigravity weather agent logic directly, serving it over production gRPC.--import argparse--import asyncio-import json-import logging-import os-import pathlib-import re-import sys-import grpc-from grpc_health.v1 import health, health_pb2, health_pb2_grpc-from google.protobuf.struct_pb2 import Struct---from python.proto import ax_pb2-from python.proto import ax_pb2_grpc-from python.proto import content_pb2-from google.antigravity import Agent, AgentConfig, LocalAgentConfig-from google.antigravity.types import Text, Thought, ToolCall--# Fields that come from outside agent_config and must not be set through it:-# - conversation_id: taken from the runtime request (request.conversation_id).-# - save_dir: derived at the server level from the configured state_dir.-# TODO: add validation for fields that are unsafe to set per execution-# (e.g. credentials, deployment routing) or that may only be set at-# conversation creation.-_NON_AGENT_CONFIG_FIELDS = frozenset({"conversation_id", "save_dir"})---class AgentConfigError(ValueError):- """Raised when request agent_config is not a valid overlay."""---class ConversationIdError(ValueError):- """Raised when a request's conversation_id is unusable as a save_dir name."""---def _validate_conversation_id(conversation_id: str) -> None:- """Guards conversation_id for safe use as a save_dir path component.-- Rejects empty ids and path separators / "." / ".." so a request cannot- escape state_dir. The id-format contract (length, charset) is left to the- Antigravity harness (forwarded cascade_id) to avoid the layers drifting.- """- if not conversation_id:- raise ConversationIdError("conversation_id must be set")- if "/" in conversation_id or "\\" in conversation_id:- raise ConversationIdError(- "conversation_id must not contain a path separator, got "- f"{conversation_id!r}"- )- if conversation_id in (".", ".."):- raise ConversationIdError(- f"conversation_id must not be a path component, got {conversation_id!r}"- )---def _env_use_vertex() -> bool:- """True if env requests the Vertex AI backend (vs. AI Studio API key)."""- return os.environ.get("GOOGLE_GENAI_USE_VERTEXAI", "").lower() in (- "true",- "1",- ) or os.environ.get("GOOGLE_GENAI_USE_ENTERPRISE", "").lower() in ("true", "1")---def _build_default_config() -> LocalAgentConfig:- """Builds the default agent config the sidecar serves on startup.-- Credentials/backend come from the standard GenAI env vars, which the- AGY SDK reads natively as of google-antigravity 0.1.7.-- TODO(#194): per-request `agent_config` will override fields of this- default on a per-conversation basis. Until then, every conversation uses- this config.- """- vertex = _env_use_vertex() or None- project = os.environ.get("GOOGLE_CLOUD_PROJECT") if vertex else None- location = os.environ.get("GOOGLE_CLOUD_LOCATION") if vertex else None- return LocalAgentConfig(- vertex=vertex,- project=project,- location=location,- )---def _has_credentials(config: AgentConfig | None) -> bool:- """Checks if Gemini credentials are set per AGY's accepted sources.-- Mirrors AGY's own validation. AGY accepts exactly these sources:- 1. GEMINI_API_KEY environment variable (read directly by AGY).- 2. config.api_key set programmatically (AI Studio path).- 3. Vertex requested (config.vertex or GOOGLE_GENAI_USE_VERTEXAI /- GOOGLE_GENAI_USE_ENTERPRISE) + GOOGLE_CLOUD_{PROJECT,LOCATION}.- 4. Vertex requested + config.api_key set (Express Mode; covered by 2).-- """- # Check env - AGY reads GEMINI_API_KEY directly from os.environ.- if os.environ.get("GEMINI_API_KEY"):- return True-- # AI Studio path via programmatic api_key.- if config and getattr(config, "api_key", None):- return True-- # Vertex path: requested via config.vertex or env, project+location via env.- if _env_use_vertex() or bool(getattr(config, "vertex", False)):- if os.environ.get("GOOGLE_CLOUD_PROJECT") and os.environ.get(- "GOOGLE_CLOUD_LOCATION"- ):- return True-- return False---def _existing_sdk_conv_id(save_dir: str) -> str | None:- # SDK persists each conversation as {save_dir}/{sdk_conv_id}.db where sdk_conv_id- # is SDK-picked (a hash), not our AX conversation_id. We give each AX conversation- # its own save_dir so at most one .db lives there; the SDK conv_id is its stem.- dbs = list(pathlib.Path(save_dir).glob("*.db"))- return dbs[0].stem if dbs else None---def _reject_disallowed_fields(overrides: dict[str, object]) -> None:- """Best-effort validation of a request agent_config overlay's keys.-- Rejects fields managed outside agent_config and unknown top-level- fields (typos that LocalAgentConfig's extra="ignore" would otherwise- silently drop).- Top-level only: nested-key and value/type validation is delegated to the- SDK's own LocalAgentConfig validation when the config is constructed.- """- managed = sorted(set(overrides) & _NON_AGENT_CONFIG_FIELDS)- if managed:- raise AgentConfigError(- f"field(s) managed outside agent_config cannot be set: {', '.join(managed)}"- )- unknown = sorted(set(overrides) - set(LocalAgentConfig.model_fields))- if unknown:- raise AgentConfigError(f"unknown config field(s): {', '.join(unknown)}")---class AntigravityHarnessServiceServicer(ax_pb2_grpc.HarnessServiceServicer):- """Implements the ax.HarnessService protocol over gRPC."""-- def __init__(self, default_config: AgentConfig, state_dir: pathlib.Path):- self._default_config = default_config- self._state_dir = state_dir-- def _build_config_for(- self, conversation_id: str, agent_config: bytes = b""- ) -> LocalAgentConfig:- # Overlay the request's agent_config (JSON-in-bytes) onto the server- # default. The parsed dict is a local intermediate only; this method's- # boundary type is the validated LocalAgentConfig.- if agent_config:- try:- overrides = json.loads(agent_config.decode("utf-8"))- except (UnicodeDecodeError, json.JSONDecodeError) as exc:- raise AgentConfigError(f"expected UTF-8 JSON: {exc}") from exc- if not isinstance(overrides, dict):- raise AgentConfigError("top-level JSON value must be an object")- _reject_disallowed_fields(overrides)- else:- overrides = {}-- # Persistence values managed outside agent_config go on last so a- # request can never redirect trajectory storage. Per-AX-conv save_dir- # under the configured state_dir base; resume by the SDK's own conv_id- # if a trajectory already exists there. SDK auto-creates the directory.- overrides["save_dir"] = str(self._state_dir / conversation_id)- if sdk_conv_id := _existing_sdk_conv_id(overrides["save_dir"]):- overrides["conversation_id"] = sdk_conv_id-- # Reconstruct (not model_copy) so the SDK re-validates overlaid values- # and surfaces its own error.- values = {- name: getattr(self._default_config, name)- for name in self._default_config.model_fields_set- }- values.update(overrides)- try:- return LocalAgentConfig(**values)- except (TypeError, ValueError) as exc:- raise AgentConfigError(str(exc)) from exc-- async def Connect(self, request_iterator, context):- # Each HarnessRequest{start} drives one stateless turn; the stream stays- # open across turns until the client half-closes.- async for request in request_iterator:- if request.WhichOneof("type") != "start":- continue # cancel frames not handled yet-- async for response in self._run_turn(request):- yield response-- async def _run_turn(self, request):- print(f"[gRPC] Connect turn requested. conv_id={request.conversation_id}")-- # Guard conversation_id for safe use as a save_dir path component- # below. The id-format contract (length, charset) is owned by the- # Antigravity harness via the forwarded cascade_id.- try:- _validate_conversation_id(request.conversation_id)- except ConversationIdError as exc:- yield ax_pb2.HarnessResponse(- conversation_id=request.conversation_id,- end=ax_pb2.HarnessEnd(- state=ax_pb2.STATE_FAILED,- error=ax_pb2.Error(- code=3, # INVALID_ARGUMENT- description=f"Invalid conversation_id: {exc}",- ),- ),- )- return-- # 1. Retrieve and check steps- ax_steps = request.start.steps- if not ax_steps:- yield ax_pb2.HarnessResponse(- conversation_id=request.conversation_id,- end=ax_pb2.HarnessEnd(- state=ax_pb2.STATE_FAILED,- error=ax_pb2.Error(- code=3, # INVALID_ARGUMENT- description="No steps found in start payload",- ),- ),- )- return-- latest_step = ax_steps[-1]-- if latest_step.WhichOneof("type") != "content":- yield ax_pb2.HarnessResponse(- conversation_id=request.conversation_id,- end=ax_pb2.HarnessEnd(- state=ax_pb2.STATE_FAILED,- error=ax_pb2.Error(- code=3, # INVALID_ARGUMENT- description="Latest step must be a content step",- ),- ),- )- return-- content_step = latest_step.content- if not content_step.content or content_step.content[0].WhichOneof("type") != "text":- yield ax_pb2.HarnessResponse(- conversation_id=request.conversation_id,- end=ax_pb2.HarnessEnd(- state=ax_pb2.STATE_FAILED,- error=ax_pb2.Error(- code=3, # INVALID_ARGUMENT- description="Latest step must contain text content",- ),- ),- )- return- latest_query_text = content_step.content[0].text.text-- if not self._default_config:- yield ax_pb2.HarnessResponse(- conversation_id=request.conversation_id,- end=ax_pb2.HarnessEnd(- state=ax_pb2.STATE_FAILED,- error=ax_pb2.Error(- code=9, # FAILED_PRECONDITION- description="Agent config is not loaded on the server",- ),- ),- )- return- try:- per_conv_config = self._build_config_for(- request.conversation_id, request.start.agent_config- )- print(- f"[gRPC] Starting Agent for conv_id={request.conversation_id}, save_dir={per_conv_config.save_dir}"- )- async with Agent(per_conv_config) as agent:- conversation = agent.conversation-- print(f"[gRPC] Running chat query: {latest_query_text}")- response = await conversation.chat(latest_query_text)-- # To avoid streaming individual tokens inside TextContent messages (which is not- # supported by the Interactions proto/TextContent specifications), we buffer- # contiguous blocks of text and thought chunks, yielding them only when the- # contiguous block ends or a different chunk type is received.- text_chunks = []- thought_chunks = []-- def flush_text():- if not text_chunks:- return None- step = ax_pb2.Step(- content=ax_pb2.ContentStep(- role="assistant",- content=[- content_pb2.Content(- text=content_pb2.TextContent(text="".join(text_chunks))- )- ],- )- )- text_chunks.clear()- return ax_pb2.HarnessResponse(- conversation_id=request.conversation_id,- outputs=ax_pb2.HarnessOutputs(steps=[step]),- )-- def flush_thought():- if not thought_chunks:- return None-- # Normalize Gemini's thinking output: collapse runs of 3+ newlines- # (emitted between reasoning sections) to exactly one blank line- # and strip trailing whitespace. Then append exactly one trailing- # newline so downstream displays render a blank line between the- # thinking block and whatever follows (next thought, tool call,- # or answer text). Without the trailing newline the display's- # transition logic emits only one newline, gluing blocks together.- raw_text = "".join(thought_chunks)- clean_text = re.sub(r"\n{3,}", "\n\n", raw_text).rstrip() + "\n"-- summary = [- content_pb2.Content(- text=content_pb2.TextContent(text=clean_text)- )- ]- thought_chunks.clear()- step = ax_pb2.Step(- thought=ax_pb2.ThoughtStep(summary=summary)- )- return ax_pb2.HarnessResponse(- conversation_id=request.conversation_id,- outputs=ax_pb2.HarnessOutputs(steps=[step]),- )-- async for chunk in response.chunks:- if isinstance(chunk, Text):- if resp := flush_thought():- yield resp- text_chunks.append(chunk.text)- elif isinstance(chunk, Thought):- if resp := flush_text():- yield resp- thought_chunks.append(chunk.text)- elif isinstance(chunk, ToolCall):- # Flush all pending text/thought buffers before dispatching the tool call- if resp := flush_text():- yield resp- if resp := flush_thought():- yield resp-- struct_args = Struct()- struct_args.update(chunk.args)-- func_call = ax_pb2.FunctionCallStep(- name=str(chunk.name), arguments=struct_args- )- step = ax_pb2.Step(- tool_call=ax_pb2.ToolCallStep(- id=chunk.id or "", function_call=func_call- )- )- yield ax_pb2.HarnessResponse(- conversation_id=request.conversation_id,- outputs=ax_pb2.HarnessOutputs(steps=[step]),- )-- # Flush any remaining text/thought buffers after the generator loop ends- if resp := flush_text():- yield resp- if resp := flush_thought():- yield resp-- # Yield completion end frame- yield ax_pb2.HarnessResponse(- conversation_id=request.conversation_id,- end=ax_pb2.HarnessEnd(state=ax_pb2.STATE_COMPLETED),- )- print("[gRPC] Turn completed successfully.")-- except AgentConfigError as exc:- yield ax_pb2.HarnessResponse(- conversation_id=request.conversation_id,- end=ax_pb2.HarnessEnd(- state=ax_pb2.STATE_FAILED,- error=ax_pb2.Error(- code=3, # INVALID_ARGUMENT- description=f"Invalid agent_config: {exc}",- ),- ),- )- return- except Exception as e:- logging.exception("Error inside Connect servicer execution")- yield ax_pb2.HarnessResponse(- conversation_id=request.conversation_id,- end=ax_pb2.HarnessEnd(- state=ax_pb2.STATE_FAILED,- error=ax_pb2.Error(- code=13, # INTERNAL- description=f"Agent execution terminated due to error. ({str(e)})",- ),- ),- )- return---async def _serve(- host: str, port: int, default_config: AgentConfig, state_dir: pathlib.Path-):- server = grpc.aio.server()- servicer = AntigravityHarnessServiceServicer(default_config, state_dir)- ax_pb2_grpc.add_HarnessServiceServicer_to_server(servicer, server)-- # Serve the standard gRPC health protocol.- health_servicer = health.aio.HealthServicer()- health_pb2_grpc.add_HealthServicer_to_server(health_servicer, server)- await health_servicer.set("", health_pb2.HealthCheckResponse.SERVING)-- listen_addr = f"{host}:{port}"- server.add_insecure_port(listen_addr)- print(f"Starting gRPC harness server on {listen_addr}...")- await server.start()- await server.wait_for_termination()---def _enhance_config_from_env(config) -> None:- skills_dir = os.environ.get("SKILLS_DIR")- if skills_dir and os.path.isdir(skills_dir):- print(f"Adding preinstalled skills directory to agent config: {skills_dir}")- if not hasattr(config, "skills_paths") or config.skills_paths is None:- config.skills_paths = []- config.skills_paths = list(config.skills_paths)- if skills_dir not in config.skills_paths:- config.skills_paths.append(skills_dir)---def main():- parser = argparse.ArgumentParser(description="Antigravity gRPC Harness Server")- parser.add_argument(- "--port", type=int, default=50053, help="Port to bind the server to"- )- parser.add_argument(- "--host", default="localhost", help="Host to bind the server to"- )- parser.add_argument(- "--state-dir",- default=str(pathlib.Path.home() / ".ax" / "antigravity" / "conversations"),- help="Base directory for per-conversation trajectory storage",- )- args = parser.parse_args()-- try:- default_config = _build_default_config()- _enhance_config_from_env(default_config)- if not _has_credentials(default_config):- raise ValueError(- "No Gemini credentials configured. Set GEMINI_API_KEY "- "(AI Studio) or GOOGLE_GENAI_USE_VERTEXAI=True + "- "GOOGLE_CLOUD_{PROJECT,LOCATION} (Vertex AI)."- )- except ValueError as e:- # Single startup-config exit point.- print(f"ERROR: {e}", file=sys.stderr)- sys.exit(1)-- asyncio.run(- _serve(- args.host,- args.port,- default_config,- pathlib.Path(args.state_dir).expanduser(),- )- )---if __name__ == "__main__":- main()diff --git a/python/antigravity/harness_server_test.py b/python/antigravity/harness_server_test.pydeleted file mode 100644index 0bafc8d..0000000--- a/python/antigravity/harness_server_test.py+++ /dev/null@@ -1,680 +0,0 @@-# 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-#-# https://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.--import asyncio-import json-import pytest-import grpc-from python.proto import ax_pb2, ax_pb2_grpc, content_pb2-from python.antigravity.harness_server import AntigravityHarnessServiceServicer-from python.antigravity.harness_server import ConversationIdError-from python.antigravity.harness_server import AgentConfigError-from python.antigravity.harness_server import _validate_conversation_id-from google.antigravity import LocalAgentConfig--def mock_config(monkeypatch):- monkeypatch.setenv("GEMINI_API_KEY", "mock-api-key")- return LocalAgentConfig(system_instructions="Test instructions")--def test_grpc_connect_success(mock_config, monkeypatch, tmp_path):- async def _run():- # 1. Start temporary local gRPC server on random open port- server = grpc.aio.server()- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- ax_pb2_grpc.add_HarnessServiceServicer_to_server(servicer, server)- port = server.add_insecure_port("localhost:0")- await server.start()-- # 2. Connect async stub channel- addr = f"localhost:{port}"- async with grpc.aio.insecure_channel(addr) as channel:- stub = ax_pb2_grpc.HarnessServiceStub(channel)-- # Mock the underlying Antigravity SDK class calls- class MockConversation:- def __init__(self):- self._steps = []- async def chat(self, text):- class MockResponse:- def __init__(self):- self.chunks = self._chunk_generator()- async def _chunk_generator(self):- from google.antigravity.types import Text, Thought- yield Thought(text="Thinking details", step_index=0)- yield Text(text="Hello human", step_index=0)- return MockResponse()-- class MockAgent:- def __init__(self, config):- self.conversation = MockConversation()- async def __aenter__(self):- return self- async def __aexit__(self, exc_type, exc, tb):- pass-- monkeypatch.setattr("python.antigravity.harness_server.Agent", MockAgent)-- # 3. Construct and fire a HarnessRequest{start} over the bidi stream- start_payload = ax_pb2.HarnessStart(- steps=[- ax_pb2.Step(- content=ax_pb2.ContentStep(- role="user",- content=[content_pb2.Content(text=content_pb2.TextContent(text="Hi"))],- )- )- ]- )- req = ax_pb2.HarnessRequest(- conversation_id="conv-test",- agent_id="antigravity",- start=start_payload- )-- async def request_iter():- yield req-- responses = []- async for resp in stub.Connect(request_iter()):- responses.append(resp)-- # 4. Assert outputs are correctly mapped and completed- assert len(responses) == 3 # Thought + Text + End- assert responses[0].outputs.steps[0].thought.summary[0].text.text == "Thinking details\n"- assert responses[1].outputs.steps[0].content.content[0].text.text == "Hello human"- assert responses[2].WhichOneof('type') == 'end'- assert responses[2].end.state == ax_pb2.STATE_COMPLETED-- await server.stop(0)-- asyncio.run(_run())---def test_grpc_connect_agent_per_turn_with_save_dir(mock_config, monkeypatch, tmp_path):- """Each turn spawns a fresh Agent with per-conv save_dir under the- configured state_dir. Same AX conv_id -> same save_dir- (SDK-native resume)."""-- async def _run():- server = grpc.aio.server()- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- ax_pb2_grpc.add_HarnessServiceServicer_to_server(servicer, server)- port = server.add_insecure_port("localhost:0")- await server.start()-- addr = f"localhost:{port}"- async with grpc.aio.insecure_channel(addr) as channel:- stub = ax_pb2_grpc.HarnessServiceStub(channel)-- class MockConversation:- async def chat(self, text):- class MockResponse:- def __init__(self):- self.chunks = self._chunk_generator()- async def _chunk_generator(self):- from google.antigravity.types import Text- yield Text(text="Response", step_index=0)- return MockResponse()-- agent_instances = []- class MockAgent:- def __init__(self, config):- self.config = config- self.conversation = MockConversation()- agent_instances.append(self)- async def __aenter__(self):- return self- async def __aexit__(self, exc_type, exc, tb):- pass-- monkeypatch.setattr("python.antigravity.harness_server.Agent", MockAgent)-- async def fire(conv_id):- req = ax_pb2.HarnessRequest(- conversation_id=conv_id,- agent_id="antigravity",- start=ax_pb2.HarnessStart(- steps=[- ax_pb2.Step(- content=ax_pb2.ContentStep(- role="user",- content=[content_pb2.Content(text=content_pb2.TextContent(text="Hi"))],- )- )- ]- ),- )- async def req_iter():- yield req- async for _ in stub.Connect(req_iter()):- pass-- await fire("conv-1")- await fire("conv-1")- await fire("conv-2")-- assert len(agent_instances) == 3- save_dirs = [a.config.save_dir for a in agent_instances]- assert save_dirs[0] == save_dirs[1]- assert save_dirs[0] != save_dirs[2]- assert save_dirs[0] == str(tmp_path / "conv-1")- assert save_dirs[2] == str(tmp_path / "conv-2")- # conversation_id only passed when trajectory exists (not in these mocked runs).- assert [a.config.conversation_id for a in agent_instances] == [None, None, None]-- await server.stop(0)-- asyncio.run(_run())---def test_health_check(tmp_path):- async def _run():- from grpc_health.v1 import health, health_pb2, health_pb2_grpc-- cfg = LocalAgentConfig(system_instructions="health-check stub")- server = grpc.aio.server()- ax_pb2_grpc.add_HarnessServiceServicer_to_server(AntigravityHarnessServiceServicer(cfg, tmp_path), server)- health_servicer = health.aio.HealthServicer()- health_pb2_grpc.add_HealthServicer_to_server(health_servicer, server)- await health_servicer.set("", health_pb2.HealthCheckResponse.SERVING)- port = server.add_insecure_port("localhost:0")- await server.start()- try:- async with grpc.aio.insecure_channel(f"localhost:{port}") as channel:- stub = health_pb2_grpc.HealthStub(channel)- resp = await stub.Check(health_pb2.HealthCheckRequest(service=""))- assert resp.status == health_pb2.HealthCheckResponse.SERVING- finally:- await server.stop(0)-- asyncio.run(_run())---def test_has_credentials_missing(monkeypatch):- """Returns False when neither env nor config provides credentials."""- from python.antigravity.harness_server import _has_credentials-- monkeypatch.delenv("GEMINI_API_KEY", raising=False)- monkeypatch.delenv("GOOGLE_GENAI_USE_VERTEXAI", raising=False)- monkeypatch.delenv("GOOGLE_GENAI_USE_ENTERPRISE", raising=False)-- cfg = LocalAgentConfig(system_instructions="test")- assert _has_credentials(cfg) is False---def test_has_credentials_vertex_requires_project_and_location(monkeypatch):- """Vertex needs project+location; as of AGY 0.1.7 these come from env."""- from python.antigravity.harness_server import _has_credentials-- monkeypatch.delenv("GEMINI_API_KEY", raising=False)- monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "True")- monkeypatch.delenv("GOOGLE_CLOUD_PROJECT", raising=False)- monkeypatch.delenv("GOOGLE_CLOUD_LOCATION", raising=False)-- cfg = LocalAgentConfig(system_instructions="test")- assert _has_credentials(cfg) is False-- monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "p")- assert _has_credentials(cfg) is False-- monkeypatch.delenv("GOOGLE_CLOUD_PROJECT", raising=False)- monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "us-central1")- assert _has_credentials(cfg) is False-- monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "p")- monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "us-central1")- assert _has_credentials(cfg) is True---def test_has_credentials_vertex_express_mode(monkeypatch):- """vertex=True + api_key (Express Mode) is accepted even without project/location."""- from python.antigravity.harness_server import _has_credentials-- monkeypatch.delenv("GEMINI_API_KEY", raising=False)-- cfg = LocalAgentConfig(system_instructions="test", vertex=True, api_key="express-key")- assert _has_credentials(cfg) is True---def test_grpc_connect_programmatic_credentials(monkeypatch, tmp_path):- monkeypatch.delenv("GEMINI_API_KEY", raising=False)- monkeypatch.delenv("GOOGLE_API_KEY", raising=False)- monkeypatch.delenv("GOOGLE_GENAI_USE_VERTEXAI", raising=False)- monkeypatch.delenv("GOOGLE_GENAI_USE_ENTERPRISE", raising=False)-- # Config with API key programmatically set- cfg = LocalAgentConfig(system_instructions="Test instructions", api_key="mock-config-api-key")-- async def _run():- server = grpc.aio.server()- servicer = AntigravityHarnessServiceServicer(cfg, tmp_path)- ax_pb2_grpc.add_HarnessServiceServicer_to_server(servicer, server)- port = server.add_insecure_port("localhost:0")- await server.start()-- addr = f"localhost:{port}"- async with grpc.aio.insecure_channel(addr) as channel:- stub = ax_pb2_grpc.HarnessServiceStub(channel)-- # Mock Agent so we can test programmatic config logic passes- class MockConversation:- def __init__(self):- self._steps = []- async def chat(self, text):- class MockResponse:- def __init__(self):- self.chunks = self._chunk_generator()- async def _chunk_generator(self):- from google.antigravity.types import Text- yield Text(text="Passed check", step_index=0)- return MockResponse()-- class MockAgent:- def __init__(self, config):- self.conversation = MockConversation()- async def __aenter__(self):- return self- async def __aexit__(self, exc_type, exc, tb):- pass- monkeypatch.setattr("python.antigravity.harness_server.Agent", MockAgent)-- start_payload = ax_pb2.HarnessStart(- steps=[- ax_pb2.Step(- content=ax_pb2.ContentStep(- role="user",- content=[content_pb2.Content(text=content_pb2.TextContent(text="Hi"))],- )- )- ]- )- req = ax_pb2.HarnessRequest(- conversation_id="conv-test-prog",- agent_id="antigravity",- start=start_payload- )-- async def request_iter():- yield req-- responses = []- async for resp in stub.Connect(request_iter()):- responses.append(resp)-- assert len(responses) == 2 # Text + End- assert responses[0].outputs.steps[0].content.content[0].text.text == "Passed check"- assert responses[1].WhichOneof('type') == 'end'- assert responses[1].end.state == ax_pb2.STATE_COMPLETED-- await server.stop(0)-- asyncio.run(_run())---def test_enhance_config_from_env(monkeypatch, tmp_path):- from python.antigravity.harness_server import _enhance_config_from_env- from google.antigravity import LocalAgentConfig- import os-- # Create a mock skills dir- skills_dir = tmp_path / "skills"- skills_dir.mkdir()-- cfg = LocalAgentConfig(system_instructions="test")-- # Test: Using SKILLS_DIR env var- monkeypatch.setenv("SKILLS_DIR", str(skills_dir))- _enhance_config_from_env(cfg)- assert str(skills_dir) in cfg.skills_paths---def test_grpc_connect_tool_call_flushes_buffers(mock_config, monkeypatch, tmp_path):- """ToolCall chunks immediately flush any pending text and thought buffers- before sending the tool_call output message."""-- async def _run():- server = grpc.aio.server()- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- ax_pb2_grpc.add_HarnessServiceServicer_to_server(servicer, server)- port = server.add_insecure_port("localhost:0")- await server.start()-- addr = f"localhost:{port}"- async with grpc.aio.insecure_channel(addr) as channel:- stub = ax_pb2_grpc.HarnessServiceStub(channel)-- class MockConversation:- def __init__(self):- self._steps = []- async def chat(self, text):- class MockResponse:- def __init__(self):- self.chunks = self._chunk_generator()- async def _chunk_generator(self):- from google.antigravity.types import Text, Thought, ToolCall- yield Thought(text="Think1", step_index=0)- yield Thought(text=" Think2", step_index=0)- yield ToolCall(id="tc-123", name="tool1", args={"a": 1}, step_index=0)- yield Text(text="Hello", step_index=0)- yield Text(text=" human", step_index=0)- return MockResponse()-- class MockAgent:- def __init__(self, config):- self.conversation = MockConversation()- async def __aenter__(self):- return self- async def __aexit__(self, exc_type, exc, tb):- pass- monkeypatch.setattr("python.antigravity.harness_server.Agent", MockAgent)-- start_payload = ax_pb2.HarnessStart(- steps=[- ax_pb2.Step(- content=ax_pb2.ContentStep(- role="user",- content=[content_pb2.Content(text=content_pb2.TextContent(text="Hi"))],- )- )- ]- )- req = ax_pb2.HarnessRequest(- conversation_id="conv-test-buffer",- agent_id="antigravity",- start=start_payload- )-- async def request_iter():- yield req-- responses = []- async for resp in stub.Connect(request_iter()):- responses.append(resp)-- # Responses should be:- # 1. Thought ("Think1 Think2") - flushed when ToolCall is encountered- # 2. ToolCall ("tool1") - processed immediately- # 3. Text ("Hello human") - flushed at the end- # 4. End frame- assert len(responses) == 4-- # Assert 1st response: Thought summary text is "Think1 Think2"- assert responses[0].outputs.steps[0].WhichOneof('type') == 'thought'- assert responses[0].outputs.steps[0].thought.summary[0].text.text == "Think1 Think2\n"-- # Assert 2nd response: ToolCall name is "tool1"- assert responses[1].outputs.steps[0].WhichOneof('type') == 'tool_call'- assert responses[1].outputs.steps[0].tool_call.function_call.name == "tool1"-- # Assert 3rd response: Text content is "Hello human"- assert responses[2].outputs.steps[0].WhichOneof('type') == 'content'- assert responses[2].outputs.steps[0].content.content[0].text.text == "Hello human"-- # Assert 4th response: Completion end frame- assert responses[3].WhichOneof('type') == 'end'- assert responses[3].end.state == ax_pb2.STATE_COMPLETED-- await server.stop(0)-- asyncio.run(_run())--def test_build_default_config_routes_to_vertex_via_env(monkeypatch):- """Bare default config + Vertex env vars routes to Vertex (AGY 0.1.7).-- The SDK hydrates vertex onto the config and project/location onto the- VertexEndpoint, so we assert the resolved endpoint rather than- config.{project,location}.- """- from python.antigravity.harness_server import _build_default_config- from google.antigravity import types-- monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "True")- monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "env-project")- monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "us-east1")- cfg = _build_default_config()- endpoint = cfg._build_shorthand_endpoint()- assert isinstance(endpoint, types.VertexEndpoint)- assert endpoint.project == "env-project"- assert endpoint.location == "us-east1"---def test_servicer_requires_default_config():- """Constructor takes a default config; passing nothing is a TypeError."""- with pytest.raises(TypeError, match="default_config"):- AntigravityHarnessServiceServicer()---def test_run_turn_guards_against_missing_default_config(monkeypatch, tmp_path):- """If something sets _default_config to None at runtime (future bug in- per-request layering, #194), _run_turn returns STATE_FAILED instead of- crashing the server.- """- async def _run():- cfg = LocalAgentConfig(system_instructions="will be set to None")- servicer = AntigravityHarnessServiceServicer(cfg, tmp_path)- servicer._default_config = None- server = grpc.aio.server()- ax_pb2_grpc.add_HarnessServiceServicer_to_server(servicer, server)- port = server.add_insecure_port("localhost:0")- await server.start()- try:- async with grpc.aio.insecure_channel(f"localhost:{port}") as channel:- stub = ax_pb2_grpc.HarnessServiceStub(channel)- req = ax_pb2.HarnessRequest(- conversation_id="conv-guard",- agent_id="antigravity",- start=ax_pb2.HarnessStart(steps=[- ax_pb2.Step(content=ax_pb2.ContentStep(- role="user",- content=[content_pb2.Content(text=content_pb2.TextContent(text="Hi"))],- )),- ]),- )- async def request_iter():- yield req- responses = []- async for resp in stub.Connect(request_iter()):- responses.append(resp)- assert len(responses) == 1- assert responses[0].end.state == ax_pb2.STATE_FAILED- assert responses[0].end.error.code == 9- assert "Agent config is not loaded" in responses[0].end.error.description- finally:- await server.stop(0)- asyncio.run(_run())---def test_agent_config_empty_is_noop(mock_config, tmp_path):- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- assert servicer._build_config_for("conv-1", b"").system_instructions == (- mock_config.system_instructions- )- assert servicer._build_config_for("conv-1", b"{}").system_instructions == (- mock_config.system_instructions- )---def test_agent_config_overlay_applies(mock_config, tmp_path):- # Fields flow through to the SDK, which validates values.- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- raw = json.dumps({"system_instructions": "Answer in one sentence."}).encode()-- config = servicer._build_config_for("conv-1", raw)-- assert config.system_instructions == "Answer in one sentence."---def test_agent_config_overlay_keeps_ax_managed_save_dir(mock_config, tmp_path):- # A valid overlay must not disturb the AX-injected save_dir.- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- raw = json.dumps({"system_instructions": "x"}).encode()-- config = servicer._build_config_for("conv-1", raw)-- assert config.system_instructions == "x"- assert config.save_dir == str(tmp_path / "conv-1")---def test_agent_config_overlay_does_not_mutate_default(mock_config, tmp_path):- # Reconstruction must not mutate the shared server default.- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- servicer._build_config_for(- "conv-1", json.dumps({"system_instructions": "overridden"}).encode()- )- assert mock_config.system_instructions == "Test instructions"---def test_agent_config_overlay_applies_multiple_fields(mock_config, tmp_path):- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- raw = json.dumps({- "system_instructions": "x",- "model": "gemini-2.5-pro",- }).encode()-- config = servicer._build_config_for("conv-1", raw)-- assert config.system_instructions == "x"- assert config.model == "gemini-2.5-pro"--[email protected](("raw_config", "error"), [- (b"{", "expected UTF-8 JSON"),- (b"\xff", "expected UTF-8 JSON"),- (json.dumps([]).encode(), "top-level JSON value must be an object"),- (json.dumps({"save_dir": "/tmp/other"}).encode(), "managed outside agent_config"),- (json.dumps({"conversation_id": "other"}).encode(), "managed outside agent_config"),- (- json.dumps({"capabilities": {"enabled_tools": ["not-a-tool"]}}).encode(),- "validation error",- ),- (json.dumps({"system_instruction": "typo"}).encode(), "unknown config field"),- (json.dumps({"model": "m", "frobnicate": True}).encode(), "unknown config field"),-])-def test_agent_config_rejects(mock_config, tmp_path, raw_config, error):- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- from python.antigravity.harness_server import AgentConfigError- with pytest.raises(AgentConfigError, match=error):- servicer._build_config_for("conv-1", raw_config)---def test_run_turn_invalid_agent_config_maps_to_invalid_argument(mock_config, tmp_path):- async def _run():- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- req = ax_pb2.HarnessRequest(- conversation_id="conv-1",- agent_id="antigravity",- start=ax_pb2.HarnessStart(- agent_config=b"{",- steps=[ax_pb2.Step(content=ax_pb2.ContentStep(- role="user",- content=[content_pb2.Content(text=content_pb2.TextContent(text="hi"))],- ))],- ),- )- responses = [r async for r in servicer._run_turn(req)]- assert len(responses) == 1- assert responses[0].end.state == ax_pb2.STATE_FAILED- assert responses[0].end.error.code == 3- assert "Invalid agent_config" in responses[0].end.error.description-- asyncio.run(_run())---def test_agent_config_unknown_field_names_are_reported(mock_config, tmp_path):- # The error lists the offending field(s), sorted, so a typo is actionable;- # any unknown field rejects the whole overlay (no silent drop) and valid- # fields in the same request are not flagged.- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- from python.antigravity.harness_server import AgentConfigError- raw = json.dumps({"zzz_bad": 1, "aaa_bad": 2, "system_instructions": "ok"}).encode()- with pytest.raises(AgentConfigError) as excinfo:- servicer._build_config_for("conv-1", raw)- msg = str(excinfo.value)- assert "unknown config field(s): aaa_bad, zzz_bad" in msg- assert "system_instructions" not in msg---[email protected]("conv_id", [- "conv-1", # short ids are fine here; the harness owns the format contract- "conv-test",- "11111111-2222-3333-4444-555555555555",- "a", # single char, still a safe dir name-])-def test_validate_conversation_id_accepts_path_safe(conv_id):- # Should not raise: these are all usable as a save_dir path component.- _validate_conversation_id(conv_id)--[email protected](("conv_id", "error"), [- ("", "must be set"),- ("..", "path component"),- (".", "path component"),- ("../escape", "path separator"),- ("a/b", "path separator"),- ("nested/../conv", "path separator"),- ("back\\slash", "path separator"),-])-def test_validate_conversation_id_rejects_unsafe(conv_id, error):- with pytest.raises(ConversationIdError, match=error):- _validate_conversation_id(conv_id)---def test_run_turn_unsafe_conversation_id_maps_to_invalid_argument(mock_config, tmp_path):- # An unsafe conversation_id is rejected at the boundary: the turn yields a- # single STATE_FAILED end frame with INVALID_ARGUMENT, before any agent runs.- async def _run():- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- req = ax_pb2.HarnessRequest(- conversation_id="../escape",- agent_id="antigravity",- start=ax_pb2.HarnessStart(- steps=[ax_pb2.Step(content=ax_pb2.ContentStep(- role="user",- content=[content_pb2.Content(text=content_pb2.TextContent(text="hi"))],- ))],- ),- )- responses = [r async for r in servicer._run_turn(req)]- assert len(responses) == 1- assert responses[0].end.state == ax_pb2.STATE_FAILED- assert responses[0].end.error.code == 3- assert "Invalid conversation_id" in responses[0].end.error.description-- asyncio.run(_run())---def test_run_turn_rejects_conversation_id_before_creating_save_dir(mock_config, tmp_path):- # Validation must happen before conversation_id is used as a storage- # directory name, so a rejected id leaves no directory behind under (or- # outside) state_dir.- async def _run():- servicer = AntigravityHarnessServiceServicer(mock_config, tmp_path)- req = ax_pb2.HarnessRequest(- conversation_id="../escape",- agent_id="antigravity",- start=ax_pb2.HarnessStart(- steps=[ax_pb2.Step(content=ax_pb2.ContentStep(- role="user",- content=[content_pb2.Content(text=content_pb2.TextContent(text="hi"))],- ))],- ),- )- responses = [r async for r in servicer._run_turn(req)]- assert len(responses) == 1- assert responses[0].end.state == ax_pb2.STATE_FAILED- assert list(tmp_path.iterdir()) == []-- asyncio.run(_run())diff --git a/python/antigravity/requirements.txt b/python/antigravity/requirements.txtdeleted file mode 100644index 323f422..0000000--- a/python/antigravity/requirements.txt+++ /dev/null@@ -1,5 +0,0 @@-# Runtime dependencies for the antigravity HarnessService server-# (python/antigravity/harness_server.py).-google-antigravity==0.1.10-protobuf>=7.35.0-grpcio-health-checking==1.83.0diff --git a/python/proto/__init__.py b/python/proto/__init__.pydeleted file mode 100644index ce346f1..0000000--- a/python/proto/__init__.py+++ /dev/null@@ -1,21 +0,0 @@-# 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.--"""Generated proto files."""--import sys-import os--# Add this directory to sys.path to allow generated files to find each other.-sys.path.insert(0, os.path.dirname(__file__))diff --git a/python/proto/ax_pb2.py b/python/proto/ax_pb2.pydeleted file mode 100644index 42f9d65..0000000--- a/python/proto/ax_pb2.py+++ /dev/null@@ -1,87 +0,0 @@-# 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.--# -*- coding: utf-8 -*--# Generated by the protocol buffer compiler. DO NOT EDIT!-# source: proto/ax.proto-# Protobuf Python Version: 4.25.1-"""Generated protocol buffer code."""-from google.protobuf import descriptor as _descriptor-from google.protobuf import descriptor_pool as _descriptor_pool-from google.protobuf import symbol_database as _symbol_database-from google.protobuf.internal import builder as _builder-# @@protoc_insertion_point(imports)--_sym_db = _symbol_database.Default()---from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2-from proto import content_pb2 as proto_dot_content__pb2---DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0eproto/ax.proto\x12\x02\x61x\x1a\x1cgoogle/protobuf/struct.proto\x1a\x13proto/content.proto\"\xb0\x01\n\tStepEvent\x12\x17\n\x0f\x63onversation_id\x18\x01 \x01(\t\x12\x16\n\x0einteraction_id\x18\x02 \x01(\t\x12\x10\n\x08\x61gent_id\x18\x03 \x01(\t\x12-\n\x0c\x61gent_config\x18\x04 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x17\n\x05steps\x18\x05 \x03(\x0b\x32\x08.ax.Step\x12\x18\n\x05state\x18\x06 \x01(\x0e\x32\t.ax.State\"=\n\x0cHarnessStart\x12\x14\n\x0c\x61gent_config\x18\x01 \x01(\x0c\x12\x17\n\x05steps\x18\x02 \x03(\x0b\x32\x08.ax.Step\"1\n\rHarnessCancel\x12 \n\x06reason\x18\x01 \x01(\x0e\x32\x10.ax.CancelReason\"\x8b\x01\n\x0eHarnessRequest\x12\x17\n\x0f\x63onversation_id\x18\x01 \x01(\t\x12\x10\n\x08\x61gent_id\x18\x02 \x01(\t\x12!\n\x05start\x18\x03 \x01(\x0b\x32\x10.ax.HarnessStartH\x00\x12#\n\x06\x63\x61ncel\x18\x04 \x01(\x0b\x32\x11.ax.HarnessCancelH\x00\x42\x06\n\x04type\")\n\x0eHarnessOutputs\x12\x17\n\x05steps\x18\x01 \x03(\x0b\x32\x08.ax.Step\"*\n\x05\x45rror\x12\x0c\n\x04\x63ode\x18\x01 \x01(\x05\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\"@\n\nHarnessEnd\x12\x18\n\x05state\x18\x01 \x01(\x0e\x32\t.ax.State\x12\x18\n\x05\x65rror\x18\x02 \x01(\x0b\x32\t.ax.Error\"x\n\x0fHarnessResponse\x12\x17\n\x0f\x63onversation_id\x18\x01 \x01(\t\x12%\n\x07outputs\x18\x02 \x01(\x0b\x32\x12.ax.HarnessOutputsH\x00\x12\x1d\n\x03\x65nd\x18\x03 \x01(\x0b\x32\x0e.ax.HarnessEndH\x00\x42\x06\n\x04type\"y\n\x16\x43reateInteractionEvent\x12\x17\n\x0f\x63onversation_id\x18\x01 \x01(\t\x12\x18\n\x06inputs\x18\x02 \x03(\x0b\x32\x08.ax.Step\x12\x10\n\x08\x61gent_id\x18\x04 \x01(\t\x12\x14\n\x0c\x61gent_config\x18\x05 \x01(\x0cJ\x04\x08\x03\x10\x04\"6\n\x19\x43reateInteractionResponse\x12\x19\n\x07outputs\x18\x01 \x03(\x0b\x32\x08.ax.Step\"\xcc\x01\n\x04Step\x12\x13\n\x0b\x64\x65scription\x18\x10 \x01(\t\x12\"\n\x07\x63ontent\x18\x0c \x01(\x0b\x32\x0f.ax.ContentStepH\x00\x12\"\n\x07thought\x18\x03 \x01(\x0b\x32\x0f.ax.ThoughtStepH\x00\x12%\n\ttool_call\x18\x04 \x01(\x0b\x32\x10.ax.ToolCallStepH\x00\x12)\n\x0btool_result\x18\x05 \x01(\x0b\x32\x12.ax.ToolResultStepH\x00\x12\r\n\x05index\x18\x16 \x01(\x03\x42\x06\n\x04type\"K\n\x0b\x43ontentStep\x12\x0c\n\x04role\x18\x01 \x01(\t\x12\x1c\n\x07\x63ontent\x18\x02 \x03(\x0b\x32\x0b.ax.ContentR\x04typeR\nevent_type\"P\n\x0bThoughtStep\x12\x11\n\tsignature\x18\x01 \x01(\x0c\x12\x1c\n\x07summary\x18\x02 \x03(\x0b\x32\x0b.ax.ContentR\x04typeR\nevent_type\"p\n\x0cToolCallStep\x12\n\n\x02id\x18\x01 \x01(\t\x12\x11\n\tsignature\x18\x02 \x01(\x0c\x12-\n\rfunction_call\x18\x03 \x01(\x0b\x32\x14.ax.FunctionCallStepH\x00\x42\x06\n\x04typeR\nevent_type\"R\n\x10\x46unctionCallStep\x12\x0c\n\x04name\x18\x01 \x01(\t\x12*\n\targuments\x18\x02 \x01(\x0b\x32\x17.google.protobuf.StructR\x04type\"{\n\x0eToolResultStep\x12\x0f\n\x07\x63\x61ll_id\x18\x01 \x01(\t\x12\x11\n\tsignature\x18\x02 \x01(\x0c\x12\x31\n\x0f\x66unction_result\x18\x03 \x01(\x0b\x32\x16.ax.FunctionResultStepH\x00\x42\x06\n\x04typeR\nevent_type\"s\n\x12\x46unctionResultStep\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x10\n\x08is_error\x18\x03 \x01(\x08\x12\x19\n\x06result\x18\x07 \x01(\x0b\x32\t.ax.ValueJ\x04\x08\x01\x10\x02J\x04\x08\x04\x10\x05J\x04\x08\n\x10\x0bJ\x04\x08\x0b\x10\x0cJ\x04\x08\x0c\x10\rR\x04type\"\x83\x02\n\x05Value\x12\x30\n\nnull_value\x18\x01 \x01(\x0e\x32\x1a.google.protobuf.NullValueH\x00\x12\x16\n\x0cnumber_value\x18\x02 \x01(\x01H\x00\x12\x16\n\x0cstring_value\x18\x03 \x01(\tH\x00\x12\x14\n\nbool_value\x18\x04 \x01(\x08H\x00\x12/\n\x0cstruct_value\x18\x05 \x01(\x0b\x32\x17.google.protobuf.StructH\x00\x12#\n\nlist_value\x18\x06 \x01(\x0b\x32\r.ax.ListValueH\x00\x12$\n\rcontent_value\x18\x07 \x01(\x0b\x32\x0b.ax.ContentH\x00\x42\x06\n\x04kind\"&\n\tListValue\x12\x19\n\x06values\x18\x01 \x03(\x0b\x32\t.ax.Value*l\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x11\n\rSTATE_PENDING\x10\x01\x12\x10\n\x0cSTATE_FAILED\x10\x02\x12\x13\n\x0fSTATE_COMPLETED\x10\x03\x12\x12\n\x0eSTATE_CANCELED\x10\x04*\x8c\x01\n\x0c\x43\x61ncelReason\x12\x1d\n\x19\x43\x41NCEL_REASON_UNSPECIFIED\x10\x00\x12 \n\x1c\x43\x41NCEL_REASON_USER_REQUESTED\x10\x01\x12\x19\n\x15\x43\x41NCEL_REASON_TIMEOUT\x10\x02\x12 \n\x1c\x43\x41NCEL_REASON_INTERNAL_ERROR\x10\x03\x32H\n\x0eHarnessService\x12\x36\n\x07\x43onnect\x12\x12.ax.HarnessRequest\x1a\x13.ax.HarnessResponse(\x01\x30\x01\x32g\n\x13InteractionsService\x12P\n\x11\x43reateInteraction\x12\x1a.ax.CreateInteractionEvent\x1a\x1d.ax.CreateInteractionResponse0\x01\x42\x1cZ\x1agithub.com/google/ax/protob\x06proto3')--_globals = globals()-_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)-_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'proto.ax_pb2', _globals)-if _descriptor._USE_C_DESCRIPTORS == False:- _globals['DESCRIPTOR']._options = None- _globals['DESCRIPTOR']._serialized_options = b'Z\032github.com/google/ax/proto'- _globals['_STATE']._serialized_start=2070- _globals['_STATE']._serialized_end=2178- _globals['_CANCELREASON']._serialized_start=2181- _globals['_CANCELREASON']._serialized_end=2321- _globals['_STEPEVENT']._serialized_start=74- _globals['_STEPEVENT']._serialized_end=250- _globals['_HARNESSSTART']._serialized_start=252- _globals['_HARNESSSTART']._serialized_end=313- _globals['_HARNESSCANCEL']._serialized_start=315- _globals['_HARNESSCANCEL']._serialized_end=364- _globals['_HARNESSREQUEST']._serialized_start=367- _globals['_HARNESSREQUEST']._serialized_end=506- _globals['_HARNESSOUTPUTS']._serialized_start=508- _globals['_HARNESSOUTPUTS']._serialized_end=549- _globals['_ERROR']._serialized_start=551- _globals['_ERROR']._serialized_end=593- _globals['_HARNESSEND']._serialized_start=595- _globals['_HARNESSEND']._serialized_end=659- _globals['_HARNESSRESPONSE']._serialized_start=661- _globals['_HARNESSRESPONSE']._serialized_end=781- _globals['_CREATEINTERACTIONEVENT']._serialized_start=783- _globals['_CREATEINTERACTIONEVENT']._serialized_end=904- _globals['_CREATEINTERACTIONRESPONSE']._serialized_start=906- _globals['_CREATEINTERACTIONRESPONSE']._serialized_end=960- _globals['_STEP']._serialized_start=963- _globals['_STEP']._serialized_end=1167- _globals['_CONTENTSTEP']._serialized_start=1169- _globals['_CONTENTSTEP']._serialized_end=1244- _globals['_THOUGHTSTEP']._serialized_start=1246- _globals['_THOUGHTSTEP']._serialized_end=1326- _globals['_TOOLCALLSTEP']._serialized_start=1328- _globals['_TOOLCALLSTEP']._serialized_end=1440- _globals['_FUNCTIONCALLSTEP']._serialized_start=1442- _globals['_FUNCTIONCALLSTEP']._serialized_end=1524- _globals['_TOOLRESULTSTEP']._serialized_start=1526- _globals['_TOOLRESULTSTEP']._serialized_end=1649- _globals['_FUNCTIONRESULTSTEP']._serialized_start=1651- _globals['_FUNCTIONRESULTSTEP']._serialized_end=1766- _globals['_VALUE']._serialized_start=1769- _globals['_VALUE']._serialized_end=2028- _globals['_LISTVALUE']._serialized_start=2030- _globals['_LISTVALUE']._serialized_end=2068- _globals['_HARNESSSERVICE']._serialized_start=2323- _globals['_HARNESSSERVICE']._serialized_end=2395- _globals['_INTERACTIONSSERVICE']._serialized_start=2397- _globals['_INTERACTIONSSERVICE']._serialized_end=2500-# @@protoc_insertion_point(module_scope)diff --git a/python/proto/ax_pb2_grpc.py b/python/proto/ax_pb2_grpc.pydeleted file mode 100644index 0b3286f..0000000--- a/python/proto/ax_pb2_grpc.py+++ /dev/null@@ -1,147 +0,0 @@-# 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.--# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!-"""Client and server classes corresponding to protobuf-defined services."""-import grpc--from proto import ax_pb2 as proto_dot_ax__pb2---class HarnessServiceStub(object):- """Missing associated documentation comment in .proto file."""-- def __init__(self, channel):- """Constructor.-- Args:- channel: A grpc.Channel.- """- self.Connect = channel.stream_stream(- '/ax.HarnessService/Connect',- request_serializer=proto_dot_ax__pb2.HarnessRequest.SerializeToString,- response_deserializer=proto_dot_ax__pb2.HarnessResponse.FromString,- )---class HarnessServiceServicer(object):- """Missing associated documentation comment in .proto file."""-- def Connect(self, request_iterator, context):- """Connect drives one harness execution. The client sends- HarnessRequest{start} (and may send one HarnessRequest{cancel}- mid-stream), and the server streams zero or more HarnessResponse{outputs}- frames terminated by exactly one HarnessResponse{end}.- """- context.set_code(grpc.StatusCode.UNIMPLEMENTED)- context.set_details('Method not implemented!')- raise NotImplementedError('Method not implemented!')---def add_HarnessServiceServicer_to_server(servicer, server):- rpc_method_handlers = {- 'Connect': grpc.stream_stream_rpc_method_handler(- servicer.Connect,- request_deserializer=proto_dot_ax__pb2.HarnessRequest.FromString,- response_serializer=proto_dot_ax__pb2.HarnessResponse.SerializeToString,- ),- }- generic_handler = grpc.method_handlers_generic_handler(- 'ax.HarnessService', rpc_method_handlers)- server.add_generic_rpc_handlers((generic_handler,))--- # This class is part of an EXPERIMENTAL API.-class HarnessService(object):- """Missing associated documentation comment in .proto file."""-- @staticmethod- def Connect(request_iterator,- target,- options=(),- channel_credentials=None,- call_credentials=None,- insecure=False,- compression=None,- wait_for_ready=None,- timeout=None,- metadata=None):- return grpc.experimental.stream_stream(request_iterator, target, '/ax.HarnessService/Connect',- proto_dot_ax__pb2.HarnessRequest.SerializeToString,- proto_dot_ax__pb2.HarnessResponse.FromString,- options, channel_credentials,- insecure, call_credentials, compression, wait_for_ready, timeout, metadata)---class InteractionsServiceStub(object):- """Missing associated documentation comment in .proto file."""-- def __init__(self, channel):- """Constructor.-- Args:- channel: A grpc.Channel.- """- self.CreateInteraction = channel.unary_stream(- '/ax.InteractionsService/CreateInteraction',- request_serializer=proto_dot_ax__pb2.CreateInteractionEvent.SerializeToString,- response_deserializer=proto_dot_ax__pb2.CreateInteractionResponse.FromString,- )---class InteractionsServiceServicer(object):- """Missing associated documentation comment in .proto file."""-- def CreateInteraction(self, request, context):- """CreateInteraction executes an agentic task or resumes an existing one with streaming responses- If the conversation_id already exists, it will be resumed.- """- context.set_code(grpc.StatusCode.UNIMPLEMENTED)- context.set_details('Method not implemented!')- raise NotImplementedError('Method not implemented!')---def add_InteractionsServiceServicer_to_server(servicer, server):- rpc_method_handlers = {- 'CreateInteraction': grpc.unary_stream_rpc_method_handler(- servicer.CreateInteraction,- request_deserializer=proto_dot_ax__pb2.CreateInteractionEvent.FromString,- response_serializer=proto_dot_ax__pb2.CreateInteractionResponse.SerializeToString,- ),- }- generic_handler = grpc.method_handlers_generic_handler(- 'ax.InteractionsService', rpc_method_handlers)- server.add_generic_rpc_handlers((generic_handler,))--- # This class is part of an EXPERIMENTAL API.-class InteractionsService(object):- """Missing associated documentation comment in .proto file."""-- @staticmethod- def CreateInteraction(request,- target,- options=(),- channel_credentials=None,- call_credentials=None,- insecure=False,- compression=None,- wait_for_ready=None,- timeout=None,- metadata=None):- return grpc.experimental.unary_stream(request, target, '/ax.InteractionsService/CreateInteraction',- proto_dot_ax__pb2.CreateInteractionEvent.SerializeToString,- proto_dot_ax__pb2.CreateInteractionResponse.FromString,- options, channel_credentials,- insecure, call_credentials, compression, wait_for_ready, timeout, metadata)diff --git a/python/proto/content_pb2.py b/python/proto/content_pb2.pydeleted file mode 100644index f6f7d60..0000000--- a/python/proto/content_pb2.py+++ /dev/null@@ -1,67 +0,0 @@-# 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.--# -*- coding: utf-8 -*--# Generated by the protocol buffer compiler. DO NOT EDIT!-# source: proto/content.proto-# Protobuf Python Version: 4.25.1-"""Generated protocol buffer code."""-from google.protobuf import descriptor as _descriptor-from google.protobuf import descriptor_pool as _descriptor_pool-from google.protobuf import symbol_database as _symbol_database-from google.protobuf.internal import builder as _builder-# @@protoc_insertion_point(imports)--_sym_db = _symbol_database.Default()-----DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x13proto/content.proto\x12\x02\x61x\"-\n\x0bTextContent\x12\x0c\n\x04text\x18\x03 \x01(\tJ\x04\x08\x01\x10\x02J\x04\x08\x02\x10\x03R\x04type\"$\n\x10\x41pprovalDecision\x12\x10\n\x08\x61pproved\x18\x01 \x01(\x08\"1\n\x0f\x44\x65\x63lineDecision\x12\x10\n\x08\x64\x65\x63lined\x18\x01 \x01(\x08J\x04\x08\x02\x10\x03R\x06reason\"\xa3\x01\n\x13\x43onfirmationContent\x12\n\n\x02id\x18\x03 \x01(\t\x12\x10\n\x08question\x18\x04 \x01(\t\x12(\n\x08\x61pproval\x18\x05 \x01(\x0b\x32\x14.ax.ApprovalDecisionH\x00\x12&\n\x07\x64\x65\x63line\x18\x06 \x01(\x0b\x32\x13.ax.DeclineDecisionH\x00\x42\n\n\x08\x64\x65\x63isionJ\x04\x08\x01\x10\x02J\x04\x08\x02\x10\x03R\x04type\"\xbd\x02\n\x0cImageContent\x12,\n\tmime_type\x18\x01 \x01(\x0e\x32\x19.ax.ImageContent.MimeType\x12\x0e\n\x04\x64\x61ta\x18\x02 \x01(\x0cH\x00\x12\r\n\x03uri\x18\x06 \x01(\tH\x00\x12\'\n\nresolution\x18\x05 \x01(\x0e\x32\x13.ax.MediaResolution\"\x9b\x01\n\x08MimeType\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x0c\n\x08TYPE_PNG\x10\x01\x12\r\n\tTYPE_JPEG\x10\x02\x12\r\n\tTYPE_WEBP\x10\x03\x12\r\n\tTYPE_HEIC\x10\x04\x12\r\n\tTYPE_HEIF\x10\x05\x12\x0c\n\x08TYPE_GIF\x10\x07\x12\x0c\n\x08TYPE_BMP\x10\x08\x12\r\n\tTYPE_TIFF\x10\t\"\x04\x08\x06\x10\x06\x42\r\n\x0b\x64\x61ta_or_uriJ\x04\x08\x03\x10\x04R\x04type\"\x8b\x03\n\x0c\x41udioContent\x12,\n\tmime_type\x18\x01 \x01(\x0e\x32\x19.ax.AudioContent.MimeType\x12\x0e\n\x04\x64\x61ta\x18\x02 \x01(\x0cH\x00\x12\r\n\x03uri\x18\x05 \x01(\tH\x00\x12\x10\n\x08\x63hannels\x18\x07 \x01(\x05\x12\x13\n\x0bsample_rate\x18\x08 \x01(\x05\"\xdf\x01\n\x08MimeType\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x0c\n\x08TYPE_WAV\x10\x01\x12\x0c\n\x08TYPE_MP3\x10\x02\x12\r\n\tTYPE_AIFF\x10\x03\x12\x0c\n\x08TYPE_AAC\x10\x04\x12\x0c\n\x08TYPE_OGG\x10\x05\x12\r\n\tTYPE_FLAC\x10\x06\x12\r\n\tTYPE_MPEG\x10\x07\x12\x0c\n\x08TYPE_M4A\x10\x08\x12\x0c\n\x08TYPE_L16\x10\t\x12\x0e\n\nTYPE_S16LE\x10\n\x12\r\n\tTYPE_OPUS\x10\x0b\x12\r\n\tTYPE_ALAW\x10\x0c\x12\x0e\n\nTYPE_MULAW\x10\rB\r\n\x0b\x64\x61ta_or_uriJ\x04\x08\x03\x10\x04J\x04\x08\x06\x10\x07R\x04typeR\x04rate\"\xcc\x01\n\x0f\x44ocumentContent\x12/\n\tmime_type\x18\x01 \x01(\x0e\x32\x1c.ax.DocumentContent.MimeType\x12\x0e\n\x04\x64\x61ta\x18\x02 \x01(\x0cH\x00\x12\r\n\x03uri\x18\x05 \x01(\tH\x00\"N\n\x08MimeType\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x0c\n\x08TYPE_PDF\x10\x01\x12\r\n\tTYPE_JSON\x10\x02\x12\x0f\n\x0bTYPE_PYTHON\x10\x03\x42\r\n\x0b\x64\x61ta_or_uriJ\x04\x08\x03\x10\x04R\x04type\"\xc5\x02\n\x0cVideoContent\x12,\n\tmime_type\x18\x01 \x01(\x0e\x32\x19.ax.VideoContent.MimeType\x12\x0e\n\x04\x64\x61ta\x18\x02 \x01(\x0cH\x00\x12\r\n\x03uri\x18\x06 \x01(\tH\x00\x12\'\n\nresolution\x18\x05 \x01(\x0e\x32\x13.ax.MediaResolution\"\xa3\x01\n\x08MimeType\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x0c\n\x08TYPE_MP4\x10\x01\x12\r\n\tTYPE_MPEG\x10\x02\x12\x0c\n\x08TYPE_MPG\x10\x03\x12\x0c\n\x08TYPE_MOV\x10\x04\x12\x0c\n\x08TYPE_AVI\x10\x05\x12\x0e\n\nTYPE_X_FLV\x10\x06\x12\r\n\tTYPE_WEBM\x10\x07\x12\x0c\n\x08TYPE_WMV\x10\x08\x12\r\n\tTYPE_3GPP\x10\tB\r\n\x0b\x64\x61ta_or_uriJ\x04\x08\x03\x10\x04R\x04type\"\x81\x02\n\x07\x43ontent\x12\x1f\n\x04text\x18\n \x01(\x0b\x32\x0f.ax.TextContentH\x00\x12!\n\x05image\x18\x0b \x01(\x0b\x32\x10.ax.ImageContentH\x00\x12!\n\x05\x61udio\x18\x0c \x01(\x0b\x32\x10.ax.AudioContentH\x00\x12\'\n\x08\x64ocument\x18\r \x01(\x0b\x32\x13.ax.DocumentContentH\x00\x12!\n\x05video\x18\x0e \x01(\x0b\x32\x10.ax.VideoContentH\x00\x12/\n\x0c\x63onfirmation\x18\x1a \x01(\x0b\x32\x17.ax.ConfirmationContentH\x00\x42\x06\n\x04typeJ\x04\x08\x01\x10\nJ\x04\x08\x0f\x10\x1a*b\n\x0fMediaResolution\x12 \n\x1cMEDIA_RESOLUTION_UNSPECIFIED\x10\x00\x12\x07\n\x03LOW\x10\x01\x12\n\n\x06MEDIUM\x10\x02\x12\x08\n\x04HIGH\x10\x03\x12\x0e\n\nULTRA_HIGH\x10\x04\x42\x1cZ\x1agithub.com/google/ax/protob\x06proto3')--_globals = globals()-_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)-_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'proto.content_pb2', _globals)-if _descriptor._USE_C_DESCRIPTORS == False:- _globals['DESCRIPTOR']._options = None- _globals['DESCRIPTOR']._serialized_options = b'Z\032github.com/google/ax/proto'- _globals['_MEDIARESOLUTION']._serialized_start=1842- _globals['_MEDIARESOLUTION']._serialized_end=1940- _globals['_TEXTCONTENT']._serialized_start=27- _globals['_TEXTCONTENT']._serialized_end=72- _globals['_APPROVALDECISION']._serialized_start=74- _globals['_APPROVALDECISION']._serialized_end=110- _globals['_DECLINEDECISION']._serialized_start=112- _globals['_DECLINEDECISION']._serialized_end=161- _globals['_CONFIRMATIONCONTENT']._serialized_start=164- _globals['_CONFIRMATIONCONTENT']._serialized_end=327- _globals['_IMAGECONTENT']._serialized_start=330- _globals['_IMAGECONTENT']._serialized_end=647- _globals['_IMAGECONTENT_MIMETYPE']._serialized_start=465- _globals['_IMAGECONTENT_MIMETYPE']._serialized_end=620- _globals['_AUDIOCONTENT']._serialized_start=650- _globals['_AUDIOCONTENT']._serialized_end=1045- _globals['_AUDIOCONTENT_MIMETYPE']._serialized_start=783- _globals['_AUDIOCONTENT_MIMETYPE']._serialized_end=1006- _globals['_DOCUMENTCONTENT']._serialized_start=1048- _globals['_DOCUMENTCONTENT']._serialized_end=1252- _globals['_DOCUMENTCONTENT_MIMETYPE']._serialized_start=1147- _globals['_DOCUMENTCONTENT_MIMETYPE']._serialized_end=1225- _globals['_VIDEOCONTENT']._serialized_start=1255- _globals['_VIDEOCONTENT']._serialized_end=1580- _globals['_VIDEOCONTENT_MIMETYPE']._serialized_start=1390- _globals['_VIDEOCONTENT_MIMETYPE']._serialized_end=1553- _globals['_CONTENT']._serialized_start=1583- _globals['_CONTENT']._serialized_end=1840-# @@protoc_insertion_point(module_scope)diff --git a/python/proto/content_pb2_grpc.py b/python/proto/content_pb2_grpc.pydeleted file mode 100644index fe9b2e7..0000000--- a/python/proto/content_pb2_grpc.py+++ /dev/null@@ -1,18 +0,0 @@-# 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.--# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!-"""Client and server classes corresponding to protobuf-defined services."""-import grpc-diff --git a/python/python.go b/python/python.godeleted file mode 100644index faa502e..0000000--- a/python/python.go+++ /dev/null@@ -1,24 +0,0 @@-// 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 python embeds the Python directory assets (such as antigravity and proto modules)-// for use by the sidecar and harnesses.-package python--import "embed"--// FS contains the embedded python/ directory assets.-//-//go:embed antigravity proto antigravity/_*.py proto/_*.py-var FS embed.FSdiff --git a/runner/runner.go b/runner/runner.gonew file mode 100644index 0000000..4eaadb0--- /dev/null+++ b/runner/runner.go@@ -0,0 +1,246 @@+// 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 runner implements the logic that runs inside every AX task container.+//+// Given a Task and its Workspace, a run starts the metadata and guest server,+// performs the maiden-run workspace setup, and then starts the task's command+// as a supervised child process. The runner stays up as the container's main+// process until it is told to stop, so the sandbox remains inspectable after+// the command has finished. The ax-task-runner binary is a thin wrapper around+// [Run]; custom images can embed the same behavior by calling it directly.+package runner++import (+ "context"+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "syscall"+ "time"++ "github.com/google/ax/internal/metadata"+ "github.com/google/ax/internal/workspace"+ "github.com/google/ax/pkg/apis/v1alpha1"+)++const (+ // DefaultPort is where the metadata and guest server listens when Config.Port+ // is zero. It matches the port Agent Substrate probes for readiness.+ DefaultPort = 80+ // DefaultWorkspacePath is the command's working directory when the task+ // binds no workspaces.+ DefaultWorkspacePath = v1alpha1.DefaultWorkspacePath++ // stopGracePeriod is how long a running task command gets to exit after+ // SIGTERM before it is killed during shutdown.+ stopGracePeriod = 10 * time.Second+)++// Config controls a single Run.+type Config struct {+ // Port is where the metadata HTTP endpoints and guest gRPC services listen.+ // Zero means DefaultPort.+ Port int+ // Task is the task to run. It supplies the command, its environment, and+ // the workspace bindings. Nil runs with no command and default settings.+ Task *v1alpha1.Task+ // Workspaces are the Workspace resources the task binds. Each is matched to+ // an entry of the task's spec.workspaces by name.+ Workspaces []*v1alpha1.Workspace+ // OnCommandExit, when set, is called once the task command has exited.+ OnCommandExit func(CommandExit)+}++// mount pairs one workspace binding from the task spec with the Workspace+// resource that satisfies it and the path it is set up at.+type mount struct {+ ref *v1alpha1.WorkspaceRef+ ws *v1alpha1.Workspace+ path string+}++// resolveMounts lines up the task's workspace bindings with the Workspace+// resources in cfg. Bindings are matched by name; a binding whose Workspace was+// not supplied is set up as an empty directory.+func resolveMounts(cfg Config) []mount {+ byName := make(map[string]*v1alpha1.Workspace, len(cfg.Workspaces))+ for _, ws := range cfg.Workspaces {+ if ws != nil {+ byName[ws.GetMetadata().GetName()] = ws+ }+ }++ spec := cfg.Task.GetSpec()+ refs := spec.WorkspaceRefs()+ paths := spec.WorkspacePaths()+ mounts := make([]mount, len(refs))+ for i, ref := range refs {+ mounts[i] = mount{ref: ref, ws: byName[ref.GetName()], path: paths[i]}+ }+ return mounts+}++// CommandExit describes how the task command finished.+type CommandExit struct {+ // Pid of the command's process.+ Pid int+ // ExitCode is the command's exit status, or -1 if it was killed by a signal.+ ExitCode int+ // Err is nil when the command exited with status zero.+ Err error+}++// Run executes the task-runner lifecycle and blocks until ctx is cancelled.+//+// Every workspace the task binds is set up in declaration order, each at its+// own path. The task's spec.command, if any, is then started as a child process+// in its own process group with the first workspace as its working directory+// and AX_METADATA_URL plus spec.env in its environment. The metadata and guest+// server keeps serving whether or not the command is still running. When ctx is+// cancelled a running command is sent SIGTERM, given a grace period, and then+// killed.+//+// Workspace setup failures are logged but do not abort the run; the task simply+// never reports ready. Run returns an error only when the runner itself cannot+// start, for example when the metadata server or the command fails to launch.+func Run(ctx context.Context, cfg Config) error {+ port := cfg.Port+ if port <= 0 {+ port = DefaultPort+ }+ mounts := resolveMounts(cfg)+ if len(mounts) == 0 {+ // Nothing bound: still provide an empty working directory at the default path.+ mounts = []mount{{ref: &v1alpha1.WorkspaceRef{}, path: DefaultWorkspacePath}}+ }+ wsPath := mounts[0].path+ workspaces := make([]*v1alpha1.Workspace, 0, len(mounts))+ paths := make([]string, len(mounts))+ for i, m := range mounts {+ paths[i] = m.path+ if m.ws != nil {+ workspaces = append(workspaces, m.ws)+ }+ }+ slog.Info("initializing AX task runner", "port", port, "wsPath", wsPath, "workspaces", paths)++ metadataURL := fmt.Sprintf("http://127.0.0.1:%d", port)+ _ = os.Setenv("AX_METADATA_URL", metadataURL)+ for _, e := range cfg.Task.GetSpec().GetEnv() {+ _ = os.Setenv(e.GetName(), e.GetValue())+ }++ metaServer := metadata.NewServer(port, cfg.Task, workspaces, metadata.ServerOptions{WorkspacePath: wsPath})+ if err := metaServer.Start(); err != nil {+ return fmt.Errorf("starting metadata server: %w", err)+ }+ defer func() {+ slog.Info("shutting down metadata server")+ _ = metaServer.Stop(context.Background())+ }()++ ready := true+ for _, m := range mounts {+ if _, err := workspace.SetupWorkspace(ctx, m.ws, m.path, m.ref.GetGoal()); err != nil {+ slog.Error("workspace maiden run setup failed", "workspace", m.ref.GetName(), "path", m.path, "error", err)+ ready = false+ }+ }+ if ready {+ metaServer.SetWorkspaceReady(true)+ slog.Info("workspace maiden run setup marked ready", "count", len(mounts))+ }++ cmdArgs := cfg.Task.GetSpec().GetCommand()+ if len(cmdArgs) == 0 {+ slog.Info("no task command specified; serving metadata until stopped")+ <-ctx.Done()+ return nil+ }++ cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)+ cmd.Dir = wsPath+ cmd.Stdin = os.Stdin+ cmd.Stdout = os.Stdout+ cmd.Stderr = os.Stderr+ cmd.Env = commandEnv(cfg.Task, port)+ // A dedicated process group lets shutdown signal the command together with+ // anything it spawned.+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}++ if err := cmd.Start(); err != nil {+ return fmt.Errorf("starting task command %v: %w", cmdArgs, err)+ }+ slog.Info("started task command", "pid", cmd.Process.Pid, "command", cmdArgs)++ exited := make(chan error, 1)+ go func() { exited <- cmd.Wait() }()++ select {+ case err := <-exited:+ reportExit(cfg, cmd, err)+ // Keep the sandbox up and inspectable until told to stop.+ <-ctx.Done()+ case <-ctx.Done():+ reportExit(cfg, cmd, stopCommand(cmd, exited))+ }+ return nil+}++// stopCommand asks the command's process group to terminate, kills it if it has+// not exited within the grace period, and returns the command's exit result.+func stopCommand(cmd *exec.Cmd, exited <-chan error) error {+ pid := cmd.Process.Pid+ slog.Info("stopping task command", "pid", pid)+ _ = syscall.Kill(-pid, syscall.SIGTERM)++ timer := time.NewTimer(stopGracePeriod)+ defer timer.Stop()+ select {+ case err := <-exited:+ return err+ case <-timer.C:+ slog.Warn("task command did not exit within grace period; killing", "pid", pid, "gracePeriod", stopGracePeriod)+ _ = syscall.Kill(-pid, syscall.SIGKILL)+ return <-exited+ }+}++// reportExit logs how the command finished and notifies the OnCommandExit hook.+func reportExit(cfg Config, cmd *exec.Cmd, err error) {+ exit := CommandExit{Pid: cmd.Process.Pid, ExitCode: -1, Err: err}+ if cmd.ProcessState != nil {+ exit.ExitCode = cmd.ProcessState.ExitCode()+ }+ if err != nil {+ slog.Error("task command exited with error", "pid", exit.Pid, "exitCode", exit.ExitCode, "error", err)+ } else {+ slog.Info("task command completed successfully", "pid", exit.Pid)+ }+ if cfg.OnCommandExit != nil {+ cfg.OnCommandExit(exit)+ }+}++// commandEnv builds the environment for the task command: the runner's own+// environment, the metadata URL, and the Task's spec.env entries.+func commandEnv(task *v1alpha1.Task, port int) []string {+ env := append(os.Environ(), fmt.Sprintf("AX_METADATA_URL=http://127.0.0.1:%d", port))+ for _, e := range task.GetSpec().GetEnv() {+ env = append(env, fmt.Sprintf("%s=%s", e.GetName(), e.GetValue()))+ }+ return env+}diff --git a/runner/runner_test.go b/runner/runner_test.gonew file mode 100644index 0000000..e44cea1--- /dev/null+++ b/runner/runner_test.go@@ -0,0 +1,304 @@+// 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 runner_test++import (+ "context"+ "fmt"+ "io"+ "net"+ "net/http"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/google/ax/internal/workspace"+ "github.com/google/ax/pkg/apis/v1alpha1"+ "github.com/google/ax/runner"+)++func TestRun_StartsTaskCommandWithInjectedEnv(t *testing.T) {+ h := newHarness(t)+ outFile := filepath.Join(t.TempDir(), "out.txt")+ h.task.Spec.Env = []*v1alpha1.EnvVar{{Name: "DEMO_ENV", Value: "from-task"}}+ h.task.Spec.Command = []string{"sh", "-c", `echo "$DEMO_ENV $AX_METADATA_URL $(pwd)" > ` + outFile}++ exit := h.runUntilCommandExits(t)+ if exit.Err != nil || exit.ExitCode != 0 {+ t.Fatalf("unexpected exit: %+v", exit)+ }++ out, err := os.ReadFile(outFile)+ if err != nil {+ t.Fatalf("command did not write its output: %v", err)+ }+ fields := strings.Fields(string(out))+ if len(fields) != 3 || fields[0] != "from-task" || fields[1] != fmt.Sprintf("http://127.0.0.1:%d", h.cfg.Port) {+ t.Errorf("unexpected env in command: %q", out)+ }+ // The working directory is the workspace path; compare resolved paths since+ // temp dirs may involve symlinks.+ wantDir, _ := filepath.EvalSymlinks(h.wsPath)+ if gotDir, _ := filepath.EvalSymlinks(fields[2]); gotDir != wantDir {+ t.Errorf("command cwd = %q, want workspace %q", fields[2], h.wsPath)+ }+}++func TestRun_ReportsCommandExitCode(t *testing.T) {+ h := newHarness(t)+ h.task.Spec.Command = []string{"sh", "-c", "exit 3"}++ exit := h.runUntilCommandExits(t)+ if exit.ExitCode != 3 || exit.Err == nil {+ t.Errorf("expected exit code 3 with an error, got %+v", exit)+ }+}++func TestRun_KeepsServingAfterCommandExits(t *testing.T) {+ h := newHarness(t)+ h.task.Spec.Command = []string{"true"}++ h.runUntilCommandExits(t)++ // The command is gone but the runner, and with it the metadata server, is not.+ resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/healthz", h.cfg.Port))+ if err != nil {+ t.Fatalf("metadata server not reachable after command exit: %v", err)+ }+ resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Errorf("healthz = %d, want 200", resp.StatusCode)+ }+ select {+ case <-h.finished:+ t.Fatalf("Run returned before cancellation: %v", h.err)+ default:+ }+}++func TestRun_StopsRunningCommandOnCancel(t *testing.T) {+ h := newHarness(t)+ // A shell with a sleeping child: the whole process group must be stopped.+ h.task.Spec.Command = []string{"sh", "-c", "sleep 30; sleep 30"}+ h.start(t)++ // Give the command a moment to start before cancelling.+ time.Sleep(100 * time.Millisecond)+ h.cancel()++ h.waitFinished(t, 5*time.Second)+ if exit := h.waitExit(t); exit.Err == nil {+ t.Errorf("expected the stopped command to report a signal exit, got %+v", exit)+ }+}++func TestRun_WithoutCommandWaitsForContext(t *testing.T) {+ h := newHarness(t)+ h.start(t)++ select {+ case <-h.finished:+ t.Fatalf("Run returned before cancellation: %v", h.err)+ case <-time.After(200 * time.Millisecond):+ }++ h.cancel()+ h.waitFinished(t, 5*time.Second)+}++func TestRun_DefaultsWithoutTask(t *testing.T) {+ // A nil Task still serves metadata; the port comes from Config.+ h := newHarness(t)+ h.cfg.Task = nil+ h.start(t)++ waitHealthy(t, h.cfg.Port)+ h.cancel()+ h.waitFinished(t, 5*time.Second)+}++// waitHealthy polls the metadata server's health endpoint until it answers.+func waitHealthy(t *testing.T, port int) {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/healthz", port))+ if err == nil {+ resp.Body.Close()+ return+ }+ time.Sleep(20 * time.Millisecond)+ }+ t.Fatal("metadata server never became reachable")+}++// harness runs the runner in the background with all state under a temp dir,+// a free port, and a hook that captures the command's exit.+type harness struct {+ cfg runner.Config+ task *v1alpha1.Task+ wsPath string++ cancel context.CancelFunc+ finished chan struct{}+ err error+ exited chan runner.CommandExit+}++func newHarness(t *testing.T) *harness {+ t.Helper()+ dir := t.TempDir()++ origAXDir := workspace.AXDir+ workspace.AXDir = filepath.Join(dir, "ax")+ t.Cleanup(func() { workspace.AXDir = origAXDir })++ h := &harness{+ wsPath: filepath.Join(dir, "workspace"),+ finished: make(chan struct{}),+ exited: make(chan runner.CommandExit, 1),+ }+ h.task = &v1alpha1.Task{+ Metadata: &v1alpha1.ObjectMeta{Name: "lib-task", Atespace: "default"},+ Spec: &v1alpha1.TaskSpec{Workspaces: []*v1alpha1.WorkspaceRef{{Name: "ws", Path: h.wsPath}}},+ }+ h.cfg = runner.Config{+ Port: freePort(t),+ Task: h.task,+ OnCommandExit: func(e runner.CommandExit) { h.exited <- e },+ }+ return h+}++// start launches Run in the background. Cleanup cancels it and waits for it to+// return so no runner outlives its test.+func (h *harness) start(t *testing.T) {+ t.Helper()+ ctx, cancel := context.WithCancel(context.Background())+ h.cancel = cancel+ go func() {+ h.err = runner.Run(ctx, h.cfg)+ close(h.finished)+ }()+ t.Cleanup(func() {+ cancel()+ h.waitFinished(t, 15*time.Second)+ })+}++// waitFinished blocks until Run has returned and fails the test if it returned+// an error or did not return in time. It is safe to call more than once.+func (h *harness) waitFinished(t *testing.T, timeout time.Duration) {+ t.Helper()+ select {+ case <-h.finished:+ if h.err != nil {+ t.Fatalf("Run returned error: %v", h.err)+ }+ case <-time.After(timeout):+ t.Fatal("Run did not return in time")+ }+}++func (h *harness) waitExit(t *testing.T) runner.CommandExit {+ t.Helper()+ select {+ case e := <-h.exited:+ return e+ case <-time.After(10 * time.Second):+ t.Fatal("command did not exit in time")+ return runner.CommandExit{}+ }+}++// runUntilCommandExits starts the runner and blocks until the command has+// exited, leaving the runner itself alive.+func (h *harness) runUntilCommandExits(t *testing.T) runner.CommandExit {+ t.Helper()+ h.start(t)+ return h.waitExit(t)+}++func freePort(t *testing.T) int {+ t.Helper()+ lis, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ defer lis.Close()+ return lis.Addr().(*net.TCPAddr).Port+}++func TestRun_SetsUpEveryWorkspace(t *testing.T) {+ h := newHarness(t)+ root := t.TempDir()+ codePath := filepath.Join(root, "code")+ toolsPath := filepath.Join(root, "tools")+ outFile := filepath.Join(root, "out.txt")++ h.task.Spec.Workspaces = []*v1alpha1.WorkspaceRef{+ {Name: "code", Path: codePath},+ {Name: "tools", Path: toolsPath},+ }+ h.cfg.Workspaces = []*v1alpha1.Workspace{+ {Metadata: &v1alpha1.ObjectMeta{Name: "tools"}, Spec: &v1alpha1.WorkspaceSpec{}},+ {Metadata: &v1alpha1.ObjectMeta{Name: "code"}, Spec: &v1alpha1.WorkspaceSpec{}},+ }+ h.task.Spec.Command = []string{"sh", "-c", "pwd > " + outFile}++ exit := h.runUntilCommandExits(t)+ if exit.Err != nil || exit.ExitCode != 0 {+ t.Fatalf("unexpected exit: %+v", exit)+ }++ // Both workspace directories exist and each has its own maiden-run marker.+ for _, p := range []string{codePath, toolsPath} {+ if st, err := os.Stat(p); err != nil || !st.IsDir() {+ t.Errorf("workspace dir %s missing: %v", p, err)+ }+ marker := filepath.Join(workspace.AXDir, workspace.MarkerName(p))+ if _, err := os.Stat(marker); err != nil {+ t.Errorf("marker %s missing: %v", marker, err)+ }+ }++ // The command ran in the first workspace.+ out, _ := os.ReadFile(outFile)+ wantDir, _ := filepath.EvalSymlinks(codePath)+ if gotDir, _ := filepath.EvalSymlinks(strings.TrimSpace(string(out))); gotDir != wantDir {+ t.Errorf("command cwd = %q, want first workspace %q", strings.TrimSpace(string(out)), codePath)+ }++ // Readiness reflects all workspaces, and the metadata server lists them in binding order.+ resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/readyz", h.cfg.Port))+ if err != nil {+ t.Fatal(err)+ }+ resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Errorf("readyz = %d, want 200", resp.StatusCode)+ }+ resp, err = http.Get(fmt.Sprintf("http://127.0.0.1:%d/metadata/v1alpha1/ax/workspaces", h.cfg.Port))+ if err != nil {+ t.Fatal(err)+ }+ defer resp.Body.Close()+ body, _ := io.ReadAll(resp.Body)+ if !strings.Contains(string(body), "name: code") || !strings.Contains(string(body), "name: tools") || strings.Index(string(body), "name: code") > strings.Index(string(body), "name: tools") {+ t.Errorf("workspaces endpoint should list code then tools:\n%s", body)+ }+}