# Build with 10xGraph: instructions for the coding agent

You are building an application on 10xGraph, the open-source, self-hosted infrastructure for AI agents. The developer writes the agent, its tools and tasks. 10xGraph runs them behind an API server with authentication, roles, tenant isolation, durable state in Postgres and Redis, background jobs, tracing and the audit log, and its CLI generates the project, the tests and the deploy files.

The work has two phases. **Phase 1:** set up and run the project, then stop and ask the user what to build. **Phase 2:** build only what the user describes, after they agree to a short plan. Never start Phase 2 on your own, and never write app code, tools or prompts in Phase 1.

Follow these steps in order. For every task, use the 10xGraph way listed below. Do not hand-write what the CLI generates or what the framework already does. When this file and your habits disagree, this file wins.

Docs index: https://10xgraph.com/llms.txt. Every docs page has a markdown copy at `https://10xgraph.com/docs/<page>.md`. Read the docs, not the GitHub source, unless you need to confirm a suspected bug.

---

## Phase 1: Set up and run

Steps 1 to 5. Do all of them, then stop at Step 5. Phase 1 writes no application code.

### Step 1. Ask at most five questions

Every project is a production project: Postgres for state, Redis for the cache, auth on (JWT unless the user picks another scheme), rate limits, tests and evals. Do not offer a quick or in-memory setup.

Ask these in one short message, with the recommended answer marked. Skip any question the request already answers. If the user says "use the defaults", take the recommended answers.

| # | Question | Choices (recommended first) | `init` flag |
|---|---|---|---|
| 1 | Which model provider? | Google, OpenAI, Anthropic | `--provider google\|openai\|anthropic` |
| 2 | Project name? | Suggest one from the request | `--name` |
| 3 | How do users log in? | Your app or an identity provider issues JWTs; another scheme (API keys, JWKS URL, session cookie); nobody yet, local only | `--auth jwt\|custom\|none` |
| 4 | Should the agent remember users across conversations, or answer from documents? | No; yes | `--storage postgres`, or `--storage postgres-memory` |
| 5 | Any background or scheduled work (nightly reports, long tasks)? | No; yes | `--worker none`, or `--worker redis` |

Do not ask anything else up front. Everything else comes from the request or the defaults:
- **The kind of agent:** not now. `init` writes a small demo `ReactAgent`; you choose the real class with table A in Step 8, in Phase 2, after the user describes the work.
- **Extras only when the request names them:**
  - tracing: `--otel`;
  - the frontend connection (WebSocket, AG-UI): not up front; Step 12 asks it once the backend works;
  - RabbitMQ or Kafka for jobs: `--worker rabbitmq` or `--worker kafka`.
- **Otherwise** keep the `init` defaults. Do not add options the user did not ask for.
- **The coding assistant:** you know which one you are. Use it in Step 2.

When the project is generated, they can turn on more later with `10xgraph config` (a browser UI for `10xgraph.json`) or by asking you. Add a feature later only when the user asks for it.

---

### Step 2. Install and generate the project

Work in a virtual environment (Python 3.12 or newer).

```bash
python -m venv .venv && source .venv/bin/activate
pip install 10xgraph 10xgraph-api
```

Build the `init` command from the answers. Run it with `--dry-run` first, then for real:

```bash
10xgraph init --mode full --name <name> --provider <google|openai|anthropic> \
  --auth <jwt|custom|none> --storage <postgres|postgres-memory> --worker <none|redis> \
  --skills <claude|codex|github|standard|none> --yes --non-interactive --dry-run
```

Add an extra flag from Step 1 only when the request named it.

`--skills` installs the 10xGraph skill for the assistant you are: `claude` (Claude Code), `codex` (Codex), `github` (GitHub Copilot), or `standard` for any other agent that follows the open standard (`AGENTS.md` for rules, `.agents/skills/` for skills), such as Antigravity or Gemini CLI. In non-interactive mode it defaults to `none`, so always pass it.

What this command gives you with no other flags:
- JWT auth;
- rate limits and token revocation on;
- Redis as the cache store (it follows `--storage`);
- tests and evals scaffolded;
- no worker, no tracing, no AG-UI.

Always pass `--storage postgres` with `--mode full`: in full mode storage defaults to `memory`, which loses threads on restart. `--yes --non-interactive` stops `init` from asking again what you already asked.

What `init` writes for coding agents:
- `AGENTS.md` with the 10xGraph rules block (between `<!-- 10xgraph:start -->` and `<!-- 10xgraph:end -->`). It carries the same rules as this file, and every agent reads it on every session.
- `CLAUDE.md` with the single line `@AGENTS.md`, so Claude Code reads the same rules. An existing `CLAUDE.md` is left untouched.
- With `--skills`: the skill (`.claude/skills/10xgraph`, `.agents/skills/10xgraph` or `.github/skills/10xgraph`) and the block in that assistant's instruction file.

The skill is the full playbook. Open it whenever a task is not covered here, and tell every subagent you start to load it too.

After `init`:

```bash
pip install -e ".[test]"     # the dependencies init wrote into pyproject.toml
cp .env.example .env         # the user fills in the secrets
```

### Step 3. Secrets and backing services

Never read, print or commit `.env`. The user fills in the secrets: the model API key, `JWT_SECRET_KEY`, `DATABASE_URL` and `REDIS_URL`. You may read `.env.example`.

The production setup needs Postgres and Redis running before `10xgraph dev`: the server's startup check refuses to boot otherwise. If the user has none, point them to the Docker Compose snippet in https://10xgraph.com/docs/integrations/postgres-and-redis.md and the section on running `10xgraph dev` against Docker backends in https://10xgraph.com/docs/server/run-the-server.md. In short: publish the ports on `127.0.0.1` and use `localhost`, not the service names, in `DATABASE_URL` and `REDIS_URL`.

If the services or the secrets are missing, stop and ask the user. Never switch storage to memory or SQLite, turn auth off, or weaken any other setting to get the server to start.

### Step 4. Verify and run

When the secrets are filled in and the services are up:

```bash
10xgraph test                  # unit tests (reads "test" in 10xgraph.json); no real model calls
10xgraph audit                 # package versions and project environment
10xgraph dev                   # starts the server on 127.0.0.1:8000 and opens the playground
```

The template ships a small demo agent that answers, so the user can try it in the playground right away. On a machine without a browser use `10xgraph dev --no-open`, and check it from another shell with `curl -s http://127.0.0.1:8000/ping`. Leave the server running for the user.

### Step 5. Stop and ask what to build

Stop here. Do not edit the demo agent, the demo weather tool or the system prompt. Report in 4 to 5 lines what was set up: the agent class, auth, storage, worker, the skill installed, and that the server runs at http://127.0.0.1:8000 with the playground. Then ask:

**"What should the agent do, which tools does it need, and which real systems (API, database, MCP server) do those tools read or change?"**

Wait for the answer. If the request was only a name, or is vague, do not start Phase 2.

---

## Phase 2: Build what the user describes

Steps 6 to 14. Start only when the user has described the work.

### Step 6. Show the plan, then wait for a yes

Even when the request already names tools and data sources, show a short plan first and build only after the user agrees. The plan has:
- the agent class (table A in Step 8);
- each tool, with the real system it calls;
- which tools act (refund, delete, send, pay) and go behind `ToolGuard`;
- the system prompt in one or two sentences, taken from the user's words;
- any new env vars.

Never write dummy, fake or sample data into tools. Never invent tools, data sources or prompt content the user did not ask for. If you do not know the real endpoint, database or MCP server for a tool, ask. Replacing the template's demo weather tool is part of Phase 2.

---

### Step 7. Build inside the generated layout

`init --mode full` wrote this layout. Keep it. Every project built on 10xGraph looks the same, which is what makes it maintainable.

```
<project>/
├── 10xgraph.json          # server config: agent, auth, cache_store, injectq, observability, test, evaluation
├── .env.example           # every env var the project reads, with safe example values (committed)
├── .env                   # real values (never committed)
├── pyproject.toml
├── AGENTS.md              # the 10xGraph rules block; every coding agent reads it
├── CLAUDE.md              # "@AGENTS.md", so Claude Code reads the same rules
├── graph/
│   ├── agent.py           # wiring only: checkpointer, store, container, agent, app = agent.compile(...)
│   ├── state.py           # AgentState subclass: fields only, no logic
│   ├── prompts.py         # system prompts as constants
│   ├── tools/
│   │   └── <domain>.py    # one module per domain (orders.py, billing.py): typed functions with docstrings
│   ├── agents/            # only for several agents: one module per sub-agent
│   └── validators/        # input validators, lifecycle hooks, the CallbackManager (manager.py)
├── auth/                  # only with --auth custom
├── worker/tasks.py        # only with --worker: @broker.task functions
├── tests/                 # only with --tests: test_tools_<domain>.py, test_graph_<flow>.py
└── evals/                 # only with --evals: <flow>_eval.py
```

Layout rules:
1. `graph/agent.py` holds wiring only. Tools, prompts, state and validators live in their own files and are imported.
2. Tool signatures never carry a user id, tenant id or org id. A tool that needs the caller reads it from the injected `config` (Step 8).
3. There is no `services/` folder. Data access and API code a tool needs lives in the tool's module, or a helper module next to it in `graph/tools/`. A shared client (DB pool, HTTP client) is created once in `graph/agent.py`, bound in the InjectQ container, and injected into the tool. Never keep it in a module global.
4. Optional folders exist only when the feature is on, and `init` creates them. To add a feature later, re-run the matching `init` option in a scratch folder and copy the folder shape. Never invent another place for it.
5. One graph per server process: the `agent` key in `10xgraph.json` points to one `app`. Several agents go inside one graph (`graph/agents/` plus a prebuilt multi-agent class), not in several servers.
6. No new top-level folders unless the user asks. Never add `src/`, `app/`, `api/`, `core/` or `services/` packages.
7. Config goes in `10xgraph.json` and `.env`. Every new env var goes into `.env.example` in the same change.
8. Keep the file names `init` generated. Imports depend on them.
9. Tests mirror the source: `graph/tools/orders.py` is tested in `tests/test_tools_orders.py`.

---

### Step 8. The 10xGraph way for every task

| Task | The 10xGraph way | Not this |
|---|---|---|
| Start a project | `10xgraph init --mode full` with flags | Files and folders by hand |
| Add an agent | A prebuilt agent in `graph/agent.py` (table A) | A hand-written agent loop, a new package |
| Add a tool | A typed function with a docstring in `graph/tools/<domain>.py`, passed in `tools=[...]` | Tools defined in `agent.py`, classes wrapping `ToolNode` |
| Business logic and data access | In the tool module or a helper next to it; shared clients bound in InjectQ and injected | Module globals, data code in graph nodes, a `services/` package |
| Change settings | `10xgraph config` (browser UI) or `10xgraph.json` | Settings hard-coded in Python, a second config file |
| Run locally | `10xgraph dev` (127.0.0.1:8000, opens the playground; `--no-open` to skip it) | `uvicorn ...`, a hand-written FastAPI `main.py` |
| Call the agent from a frontend or service | `10xgraph-client` (`TenxGraphClient`) or the documented REST and WebSocket routes | Raw `fetch` to guessed URLs |
| An endpoint the server does not have | Tell the user: 10xGraph does not support custom endpoints. Use the existing routes (a tool, a background task over `/v1/tasks`, the store or file routes) if one fits | Mounting routes into the generated server, a second FastAPI app next to it |
| Authentication | `"auth": "jwt"` (table B) | A custom `BaseAuth` for normal JWT tokens |
| Roles and access | `roles`, `default_role`, `roles_claim`, `tenant_claims` in `10xgraph.json` | Permission checks hand-written in routes, `user_id` arguments on tools |
| Tools that act (refund, delete, send, pay) | `ToolGuard` with `permissions`, `strict=True`, and `approval` for risky ones (1.1 RC) | `if role == "admin"` inside the tool, trusting the model to obey |
| Conversation state | `PgCheckpointer` passed to `compile(checkpointer=...)` | A `checkpointer` key in `10xgraph.json` (the server refuses to boot), `InMemoryCheckpointer` in production |
| Long-term memory | `MemoryConfig` with `PgVectorStore` (or `QdrantStore` if the user runs Qdrant) | Hand-rolled vector DB code |
| Files and media | The media store and the `/v1/files` routes | Own file storage code |
| Human approval | `interrupt()` and resume, or `ToolGuard(approval=...)` | A hand-written approval loop |
| MCP tools | `ToolNode(client=...)`, with `mcp_auth=` for servers that check the user | A hand-written MCP client, user or tenant arguments on MCP tools |
| Several models per run | `model_registry={...}` on the agent and `config={"model": name}` | Several graphs, `if` branches on the model name |
| Background jobs and schedules | `from tenxgraph_api.jobs import broker` in `worker/tasks.py`; `10xgraph worker`, `10xgraph scheduler` | Celery, cron, `asyncio.create_task` inside a request |
| Unit tests | `TestAgent`, `QuickTest`, `MockToolRegistry` from `tenxgraph.qa.testing`; `10xgraph test` | Tests that call the real model |
| Quality evaluation | `10xgraph eval` with `*_eval.py` files in `evals/` | Hand-written scoring scripts |
| Check the environment | `10xgraph audit` | Guessing versions |
| Logs | `LOG_LEVEL` (INFO in production; DEBUG only while debugging, it shows message text) | `print`, own logging setup |
| Traces and metrics | The `observability` block in `10xgraph.json` (Phoenix, OTLP, LangSmith, Logfire), the built-in Prometheus metrics, the audit log | Hand-wired OpenTelemetry, a custom metrics endpoint |
| Rate limits | `cache_store.rate_limit` in `10xgraph.json` | Custom middleware |
| Prompt-injection checks | Validators in `graph/validators/`, registered on the `CallbackManager` | Ad hoc string checks in tools |
| Deploy | `10xgraph build --docker-compose --k8s` (add `--worker` and `--scheduler` when used) | A hand-written Dockerfile, Compose file or manifests |

### Table A. Which agent

All are in `tenxgraph.prebuilt.agent`.

| The user wants | Use |
|---|---|
| A tool-calling assistant (the common case, and the default) | `ReactAgent` |
| Output in a fixed JSON shape | `StructuredOutputAgent` with a Pydantic schema |
| Answers from documents | `RAGAgent` with `PgVectorStore` or `QdrantStore` |
| A long multi-step task that needs a plan | `PlanActReflectAgent` |
| Several specialist agents with one in charge (only if asked) | `SupervisorTeamAgent` |
| Agents handing the conversation to each other (only if asked) | `SwarmAgent` |
| Voice in and out | `AudioAgent` |
| None of the above fits | `StateGraph` with `Agent`, `ToolNode`, `AgentState`. Tell the user why no prebuilt agent fits before you write it. |

Do not add routers, handoffs, guard nodes or approval nodes the user did not ask for.

### Table B. Which auth

| Situation | Use |
|---|---|
| The app or its backend issues the tokens (shared secret) | `"auth": "jwt"`, `JWT_SECRET_KEY` (32+ characters), HS256 |
| An identity provider with a known public key (RS, ES, PS) | `"auth": "jwt"`, `JWT_ALGORITHM` and the public key in `JWT_SECRET_KEY`; `JWT_SECRET_KEYS` and `kid` for rotation; optional `JWT_ISSUER`, `JWT_AUDIENCE` |
| Keys fetched from a JWKS URL | A custom `BaseAuth` in `auth/agent_auth.py` (`--auth custom`). JWKS fetching is not built in. |
| Not JWT (API keys, a session cookie from another app, mTLS headers from a proxy) | A custom `BaseAuth` in `auth/agent_auth.py` |
| A local demo only | `"auth": null`. The server is open: never expose it. |

In every case: roles come from `roles` and `roles_claim` (or `permissions_claim`) and `default_role`; tenancy comes from `tenant_claims`; the user id comes from the verified token, never from a header or a body field. A custom `BaseAuth` returns at least `user_id`.

Roles example (`10xgraph.json`):

```json
{
  "auth": {
    "method": "jwt",
    "roles_claim": "roles",
    "tenant_claims": ["org_id"],
    "roles": {
      "customer": {"permissions": ["graph:*", "threads:*", "files:*"], "reach": "own"},
      "admin": {"inherits": ["customer"], "permissions": ["tools:*"], "reach": "tenant"}
    },
    "default_role": "customer"
  }
}
```

### Table C. Storage, memory, cache

| Need | Use |
|---|---|
| Production conversation state | `PgCheckpointer(postgres_dsn=DATABASE_URL, redis_url=REDIS_URL)` |
| One local process | `SqliteCheckpointer` |
| A quick try | `InMemoryCheckpointer` (lost on restart; never in production) |
| Long-term memory | `MemoryConfig` with `PgVectorStore` in the same Postgres, or `QdrantStore` |
| Rate limits, run locks, token revocation across replicas | `"cache_store": {"type": "redis"}` |

### How tools get the caller and shared clients

```python
# graph/tools/orders.py
from injectq import Inject

from graph.tools.orders_db import OrdersDB   # a helper next to the tool, not a services/ package


async def get_order(
    order_id: str,                                # from the model
    config: dict | None = None,                   # injected by 10xGraph, hidden from the model
    db: OrdersDB = Inject[OrdersDB],              # injected from the container
) -> str:
    """Look up one order by its id and return its status and total."""
    user = (config or {}).get("user") or {}       # the verified caller, set by the server
    org_id = (user.get("tenant") or {}).get("org_id")
    return await db.get_order(order_id, org_id=org_id)
```

```python
# graph/agent.py (wiring only)
container = InjectQ.get_instance()
container.bind_instance(OrdersDB, OrdersDB(os.getenv("DATABASE_URL")))
```

Behind the API server, `config["user"]` holds the caller: `user_id`, `tenant`, `roles`, `permissions`, `reach`. `user` is a reserved key: clients cannot set it. Never take identity from tool arguments, state, message text or model output.

### Tools that act: ToolGuard (10xGraph 1.1, release candidate)

A model can call a tool it should not, by mistake or because injected text told it to. Hiding a tool is not a control. `ToolGuard` checks every tool call against the caller's permissions before it runs:

```python
# graph/validators/manager.py
from tenxgraph.core.graph import ToolGuard

ToolGuard(
    permissions={"get_order": "tools:get_order", "refund": "tools:refund"},
    approval={"refund"},      # a human says yes before it runs
    strict=True,              # no identity means denied for guarded tools
).register(callback_manager)
```

Grant `tools:<name>` (or `tools:*`) through `roles` in `10xgraph.json`. With auth on and no role granting it, a guarded tool is denied.

ToolGuard needs 10xGraph 1.1, a release candidate today (`pip install --pre 10xgraph 10xgraph-api`). Do not switch versions on your own. If the project has tools that act, tell the user ToolGuard exists and let them choose. On 1.0, check `Identity.can()` in the tool as https://10xgraph.com/docs/guides/authorization-scopes.md shows.

Tools may run more than once after a crash or retry. Give every tool that changes data an idempotency key (for example the order id plus the action).

### More snippets to copy

Read the page before you write the code; each page has a working example.

| Topic | Page |
|---|---|
| Agent with tools and `PgCheckpointer` | https://10xgraph.com/docs/guides/prebuilt-agents.md |
| Dependency injection | https://10xgraph.com/docs/guides/use-dependency-injection.md |
| Auth, roles, tenants | https://10xgraph.com/docs/server/auth.md |
| ToolGuard and zero-trust agents | https://10xgraph.com/docs/security/zero-trust-agents.md |
| Human approval | https://10xgraph.com/docs/guides/add-human-approval.md |
| MCP and `mcp_auth` | https://10xgraph.com/docs/guides/use-mcp.md and https://10xgraph.com/docs/guides/call-services-as-the-user.md |
| Long-term memory | https://10xgraph.com/docs/guides/use-pgvector-store.md |
| Prompt-injection validators | https://10xgraph.com/docs/guides/protect-against-prompt-injection.md |
| Background jobs | https://10xgraph.com/docs/guides/run-background-tasks.md |
| Traces | https://10xgraph.com/docs/guides/send-traces.md |
| Rate limits | https://10xgraph.com/docs/server/rate-limiting.md |
| Unit tests | https://10xgraph.com/docs/testing/unit-tests.md |
| Evals | https://10xgraph.com/docs/testing/run-evals.md |
| TypeScript client | https://10xgraph.com/docs/client/create-client.md and https://10xgraph.com/docs/client/invoke-agent.md |
| Deploy | https://10xgraph.com/docs/server/deploy.md |
| Production checklist | https://10xgraph.com/docs/server/production-checklist.md |

Frontend call:

```ts
import { Message, TenxGraphClient } from '10xgraph-client';

const client = new TenxGraphClient({
  baseUrl: 'http://localhost:8000',
  auth: { type: 'bearer', token: userToken },
});
const result = await client.invoke([Message.text_message('Where is order 1042?')]);
```

The server accepts only `user` messages from a client. The system prompt lives in the agent on the server.

---

### Step 9. Tuned defaults: keep them

10xGraph ships tuned for speed and safety. The measured overhead is 96 ms per request at 10 users and 188 ms at 100 (median, a ReAct agent with two AI calls and one tool call), including auth, rate limits, checkpoints and the audit log. That holds only if you do not override the defaults.

1. **Pools.** Pass `postgres_dsn` (or `dsn` to `PgVectorStore`) and let 10xGraph build the pool. A pool you build yourself keeps asyncpg's full reset and costs a round trip on every release. If you must share a pool, follow the "Performance tuning" section of https://10xgraph.com/docs/production/scaling.md.
2. **Connection budget.** The template sets `pool_config` sizes and `WEB_CONCURRENCY` that fit a default Postgres (100 connections) with 2 replicas; the comment in `graph/agent.py` shows the math: (checkpointer pool + store pool) x `WEB_CONCURRENCY` x replicas, under `max_connections` with headroom. Keep those numbers. When you raise workers or replicas, redo the math, change `pool_config` to fit, and tell the user.
3. **No in-memory or SQLite state with several workers.** Production uses `PgCheckpointer` and Redis.
4. **Never weaken a safety setting to make an error go away.** Do not set `STRICT_PRODUCTION_CHECKS=false`, `ORIGINS="*"`, docs paths on in production, `fail_open: true` on the rate limit, `enforce_user_isolation=False`, `LOG_REDACT_SECRETS=false` or `LOG_LEVEL=DEBUG` in production. Fix the cause and tell the user.
5. **Keep a context manager on every agent** (`MessageContextManager(max_messages=20)` in the template). Without one, every message is sent every turn and latency and cost grow with the thread.
6. **Compile once,** at import in `graph/agent.py`. Never build or compile the graph inside a request, a tool or a task.
7. **Leave parallel tool calls on.** Do not tell the model to "call one tool at a time" unless the tools depend on each other.
8. **`recursion_limit` stays 25** unless the agent's normal path needs more. It is the only per-run cap. Say why if you raise it. Do not add token or cost budgets.

---

### Step 10. Never do

- Custom routes inside the generated server, or a second FastAPI app beside it.
- `uvicorn` or a hand-written FastAPI app to serve the agent.
- A hand-written Dockerfile, Compose file or Kubernetes manifest.
- Tests that call the real model.
- Celery, cron or `asyncio.create_task` for background work.
- Hand-wired OpenTelemetry or a custom metrics endpoint.
- Subclassing `ToolNode` or overriding private methods.
- `user_id`, tenant or org arguments on tools (local or MCP).
- Module globals for services and clients.
- A `checkpointer` key in `10xgraph.json`.
- Reading, printing or committing `.env`. Secrets go in `.env`, never in `10xgraph.json` or code.
- Working around a 10xGraph bug in app code. Report it with a minimal repro: https://github.com/10xGraph/10xGraph/issues (core) or https://github.com/10xGraph/10xgraph-api/issues (server and CLI).
- Dummy, fake or sample data in tools.
- Tools, prompts or features the user did not ask for.
- Starting to build before the user describes the work.
- Writing a promise in code comments or docs ("coming soon"). Write what the code does today.

---

### Step 11. Verify and finish

Run these before you say a change is done:

```bash
10xgraph test                  # unit tests; no real model calls
10xgraph eval                  # if evals/ exists and the user has a model key set
10xgraph audit                 # package versions and project environment
10xgraph dev --no-open         # start the server, then in another shell:
curl -s http://127.0.0.1:8000/ping
```

Then send one real request through the playground or `10xgraph-client` (with auth on, the user gives you a test token). Stop the server when done.

For deploy:

```bash
10xgraph build --docker-compose --k8s            # add --worker and --scheduler when the project uses them
```

Run exactly one scheduler. Re-run `build` with flags rather than editing the generated files; if you must edit one, say why.

Before production, walk the checklist with the user (https://10xgraph.com/docs/server/production-checklist.md):
- auth on, `JWT_SECRET_KEY` 32+ characters;
- `PgCheckpointer` and Redis; `REDIS_URL` set before running more than one worker;
- `MODE=production`; `ORIGINS` and `ALLOWED_HOST` set, never `*`; docs paths off;
- rate limit on; token revocation where needed;
- `ToolGuard` on every tool that acts; idempotency keys on tools with side effects;
- prompt-injection validators registered;
- `LOG_LEVEL=INFO`; a tracing backend in the `observability` block;
- `10xgraph audit` passes; deploy files from `10xgraph build`.

`.env.example` must list every env var the project reads.

---

### Step 12. Connect the frontend (ask once the backend works)

Do not ask about the frontend up front. When the backend passes Step 11, or when the user starts on the frontend, ask one question and suggest the answer that fits this project:

**"How will your frontend talk to the agent?"**

| Choice | Suggest it when |
|---|---|
| `10xgraph-client` over REST and streaming (`invoke`, `stream`) | The default: a web, Node or mobile app with turn-based chat. Works through every proxy. |
| `10xgraph-client` over WebSocket (`wsStream`) | The frontend runs remote tools (browser or device tools such as location, clipboard, local files), keeps one connection open for many runs, or needs realtime voice (`/v1/graph/live`) |
| An AG-UI client SDK (for example `@ag-ui/client`) | The frontend is already built on AG-UI components |
| No frontend: another backend service calls it | `10xgraph-client` from Node, or the documented REST routes |

Look at the project before you suggest:
- Remote tools in `10xgraph.json` (`remote_tools`) or in the request: suggest WebSocket.
- `AudioAgent` or voice in the request: suggest WebSocket.
- Otherwise suggest REST and streaming.

Set up only the choice the user picks.

**`10xgraph-client` (REST, streaming or WebSocket):**
- `npm install 10xgraph-client`.
- Create `TenxGraphClient` with `baseUrl` and the user's bearer token from your app's login. Never put a server secret in the frontend.
- Send only `user` messages. The system prompt stays on the server.
- Keep the thread id the server returns and send it on the next message to continue the conversation.

**WebSocket, in addition:**
- Add the `websocket` extra to `10xgraph-api` in `pyproject.toml` (`10xgraph-api[...,websocket]`), reinstall, and set `"websocket": {"enabled": true}` in `10xgraph.json`. `10xgraph config` can set it too.
- In the browser the client sends the token in the `10xgraph-bearer` subprotocol. Never put a token in the URL.

**Remote tools:**
- Declare each tool in `remote_tools` in `10xgraph.json` (schema on the server).
- Register a handler for each with `registerToolHandler` (or `registerTool`) in the client before the first `invoke`, `stream` or `wsStream`.
- Validate the arguments in the handler: they are model output.
- Keep business data, auth, rate limits and anything with secrets in server tools. Remote tools are only for what lives on the client.

**AG-UI:**
- Add the `ag-ui` extra to `10xgraph-api` in `pyproject.toml`, reinstall, and set `"ag_ui": {"enabled": true}` in `10xgraph.json`. The endpoint is `POST /v1/ag-ui`, with the same bearer token.
- Keep `allow_client_tools` false unless the frontend must bring its own tools for a run.

**For every choice:**
- Set `ORIGINS` in `.env` to the frontend's origin (never `*` in production) and add it to `.env.example`.
- Do not write your own `fetch` wrapper, SSE parser or socket protocol for the agent routes.

Read before you write the frontend code:
- https://10xgraph.com/docs/client/create-client.md
- https://10xgraph.com/docs/client/stream-responses.md
- https://10xgraph.com/docs/client/remote-tools.md
- https://10xgraph.com/docs/client/nextjs-and-react.md
- https://10xgraph.com/docs/client/secure-your-frontend.md
- https://10xgraph.com/docs/server/websockets.md
- https://10xgraph.com/docs/server/ag-ui.md

---

### Step 13. When something is not covered

1. Look in the docs index (https://10xgraph.com/llms.txt) for the 10xGraph way.
2. If there is none, tell the user before you write anything.
3. Then write the simplest code inside the layout above. Never patch the framework from the app, and never invent a framework-level workaround.

---

### Step 14. Record the project setup

This file is read once. The project lives much longer. `init` already wrote the 10xGraph rules into `AGENTS.md` (and `CLAUDE.md` points to it), so every later session starts with them. Your part:

1. **Check the rules are there.** `AGENTS.md` has the block between `<!-- 10xgraph:start -->` and `<!-- 10xgraph:end -->`, and `CLAUDE.md` contains `@AGENTS.md`. If not, run `10xgraph skills --agent <claude|codex|github>` and check again.
2. **Never edit inside the markers.** `10xgraph skills` replaces that block on every reinstall, and your edits would be lost.
3. **Add a short "Project setup" section after the end marker** in `AGENTS.md`, with what this project chose and why. Keep it to facts a later session needs:

```markdown
## Project setup

- Agent: <ReactAgent | ...>, chosen because <reason>.
- Auth: <jwt | custom | none>; roles: <role names and what each may do>.
- Storage: <postgres | postgres-memory>; worker: <none | redis>; frontend: <client REST | client WebSocket | AG-UI | none>.
- Tools that act and how they are guarded: <tool: permission, approval>.
- Decisions the user made that differ from the defaults: <decision and reason>.
```

4. **An agent that reads neither `AGENTS.md` nor `.agents/skills/`:** point that agent's project rules file to `AGENTS.md`, or copy the block into it if the agent cannot follow a reference.

Update the "Project setup" section whenever a later change alters one of these facts. Tell the user what you wrote and where.
