> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stateset.com/llms.txt
> Use this file to discover all available pages before exploring further.

# ResponseCX Platform

> The AI Workforce platform — architecture, outcome model, Workflow Studio, org provisioning, and API conventions.

# ResponseCX Platform

**The AI Workforce platform.** Outcome-priced AI agents that resolve customer work end to end
across commerce and CX — cancel orders, process returns, update subscriptions, issue refunds —
with audit trails and human escalation.

The platform ships as a multi-tenant Next.js app hosted on GKE. **ResponseCX** is the
customer-facing product surface; StateSet is the company and category brand.

## Architecture

```
Next.js 15 (React 18) + TailwindCSS 4
    |
    |-- Auth:      WorkOS (multi-tenant orgs, PKCE OAuth, sealed sessions)
    |-- Database:  Hasura GraphQL (PostgreSQL)
    |-- Vector DB: Qdrant (Gemini Embedding 2, 3072-dim), per-org collections
    |-- AI:        Claude, OpenAI, Groq, Gemini, xAI, mem0
    |-- Workflow:  Temporal (Rust orchestration engine)
    |              Ingest → Classify → Context → Generate → Review → Dispatch
    |-- Billing:   Stripe metered subscriptions + customer balance transactions
    |-- Email:     Gmail / Outlook OAuth (inbound email processing)
    |-- Infra:     Docker + GKE + nginx ingress + cert-manager
```

Node **22.x** is required and enforced on preinstall, predev, and prebuild.

```bash theme={null}
npm install --legacy-peer-deps   # mem0ai peers conflict with groq-sdk
cp .env.example .env.local
npm run dev                      # http://localhost:3000
```

## Primary surfaces

| Route              | What it does                                                                  |
| ------------------ | ----------------------------------------------------------------------------- |
| `/`                | Marketing landing with an interactive write-access proof widget               |
| `/onboarding`      | 3-step self-serve onboarding; trial defaults to no-card                       |
| `/setup`           | 6-step product wizard. `?demo=1` auto-provisions a support agent              |
| `/chat-desk`       | Operator chat queue — virtualized, 3-pane, TipTap composer                    |
| `/workflow-studio` | Configure the 15-phase Temporal pipeline. `?view=graph` for the visual editor |
| `/outcomes`        | Outcome Accounting Dashboard — SKUs, revenue, dispute ledger                  |

## Outcome model

The platform sells **outcomes**, not seats. Each outcome is a verified, end-to-end resolution
priced against BPO labor. The canonical contract is the SKU catalog in
`lib/outcomes/sku-catalog.js`.

Two SKUs are live today — Triage Outcome ($0.50) and Resolved Customer Contact ($2.00) — with
the rest in development. See
[StateSet Billing](/stateset-billing) for the catalog.

**High-Value Actions**, by default anything at or above \$100, require human approval before the
engine executes them. This is configured per brand in Workflow Studio's Review Gate phase.

Disputes are persisted in Stripe customer balance transactions, where a negative amount is a
credit on the next invoice. Customers can flag an outcome within 14 days from the Outcome
Accounting Dashboard.

## Workflow Studio

The Studio configures a **15-phase Temporal pipeline per brand**. New brands can start from a
template that pre-fills 14+ phases:

| Template                                                                    | Motion                                |
| --------------------------------------------------------------------------- | ------------------------------------- |
| `support_control_tower`                                                     | Omnichannel CX with human-in-the-loop |
| `ecommerce` / `subscription`                                                | Shopify and Recharge motions          |
| `order_status`, `return_refund`, `subscription_pause`, `order_cancellation` | Workflow-narrow templates             |

The editor supports a List ↔ Graph view toggle, a `⌘K` phase jumper, `⌘S` save, per-phase `?`
explainers, and a **pending-changes diff against the last saved config** — so you can see what
you're about to change before saving.

## Org provisioning

Creating an org runs all of this in one request:

1. WorkOS org created, creator set as `org:admin`
2. Hasura `organizations` and `access_tokens` rows created
3. Qdrant KB collection created (`{slug}_customer_support`)
4. Default AI agent created
5. Stripe customer created
6. Workflow engine tenant registered
7. Default workflow brand created, from a template if one is specified
8. All IDs written back to `access_tokens`

## API conventions

There are roughly **600 API routes**, all behind `applyApiGuards`. Every route follows the same
shape:

```js theme={null}
import { z } from 'zod';
import { applyApiGuards } from '@/lib/api/guard';
import { respondError } from '@/lib/api/errors';
import { parseBody, respondValidationError } from '@/lib/api/validation';

const schema = z.object({ name: z.string().min(1).max(200) });

export default async function handler(req, res) {
  const guard = await applyApiGuards(req, res, {
    route: 'my-route',
    methods: ['POST'],
    auth: { requireOrg: true },
    rateLimit: { keyPrefix: 'my-route', windowMs: 60_000, max: 30 },
    maxBodySize: 100_000,
  });
  if (!guard.ok) return;

  const parsed = parseBody(schema, req.body);
  if (!parsed.ok) return respondValidationError(res, parsed.error);

  try {
    return res.status(200).json({ ok: true });
  } catch (error) {
    guard.logger.error('my-route.failed', { error: error?.message });
    return respondError(res, 500, 'Operation failed');
  }
}
```

The guard provides rate limiting, method validation, WorkOS auth, body-size limits, request
timing, a structured logger, and request-id propagation.

**Auth options:** `auth: true` (user required), `auth: { requireOrg: true }`,
`auth: { requireAdmin: true }` (implies `requireOrg`), and `auth: { allowInternal: true }`.

### Security rules

These are enforced project-wide:

<Warning>
  * **Never return `error.message` to clients.** Use `respondError(res, status, 'Safe message')`
    and log the detail server-side.
  * **Validate external URLs** with `assertSafeUrl()` from `lib/security/ssrf.js`, or pass
    `ssrfCheck: true` to `fetchWithTimeout`.
  * **All MCP tool schemas need bounded `.max()` on arrays.**
  * **Admin-only routes use `auth: { requireAdmin: true }`** — the guard enforces it, so the
    handler must not re-check.
</Warning>

## Deployment

Auto-deploys on push to `master`. The workflow builds via Cloud Build, runs `kubectl set image`,
watches the rollout, smoke-checks `/api/health`, then **commits the new tag back to the
deployment manifest** so git tracks live state.

Required GitHub secrets: `GCP_SA_KEY`, `GCP_PROJECT_ID`, `GKE_CLUSTER`, `GKE_REGION`,
`GKE_NAMESPACE`, `GKE_DEPLOYMENT`, `GAR_IMAGE_PATH`.

## Related

<CardGroup cols={2}>
  <Card title="Public API (v1)" icon="code" href="/stateset-response/response-public-api">
    Build and tune agents programmatically.
  </Card>

  <Card title="MCP servers" icon="plug" href="/stateset-response/response-mcp">
    Agent-building and analytics over MCP.
  </Card>

  <Card title="Onsite chat" icon="comments" href="/stateset-response/response-chat-widget-quickstart">
    Embed the chat widget.
  </Card>

  <Card title="Billing" icon="receipt" href="/stateset-billing">
    Outcome SKUs, plans, and disputes.
  </Card>
</CardGroup>
