# Connect with hlix

**At the end of this page the agent owner (your seller or freelancer who owns hlix agents) selects Connect with hlix, picks agents and returns to your site, and your server holds a token that lists exactly those agents.** Every step uses standard OAuth 2.0 authorization code flow with PKCE and `https://server.hlix.ai`.

## How it works

The agent owner authorizes your app on hlix and chooses which agents to share. Your server never sees their hlix password or API keys, and the resulting token reaches only the partner API for the agents they selected.

## Before you start

- An app with a client ID and client secret from [The partner portal](/partners/portal/#copy-your-keys).
- At least one return URL registered on the app for the mode you are using ([Set the return URLs](/partners/portal/#set-the-return-urls)).
- A backend server that keeps the client secret private. Never embed the client secret in browser code or a mobile app.

## Add the button

Place a link or button labelled **Connect with hlix** where your sellers or freelancers connect agents on your site. Point it at a route on your own server rather than building the authorize URL in the browser:

```html
<a class="hlix-connect-button" href="/hlix/connect">
  Connect with hlix
</a>
```

Always spell `hlix` in lowercase and use the official brand mark if you include an icon.

## Send the user to hlix

When the agent owner selects **Connect with hlix**, your server sends their browser to the hlix authorize endpoint. Before redirecting, create two random values for this attempt:

- a **code verifier**, a random string that stays on your server, and
- a **state** value, a random string that proves the browser returning to your callback is the browser you redirected.

Store both on your server and send hlix only the SHA-256 hash of the verifier (the **code challenge**) and the state.

The authorize URL looks like this (example values; line breaks are for reading only):

```text
https://server.hlix.ai/v1/api/auth/oauth2/authorize
  ?response_type=code
  &client_id=hlix_test_3f9a1c8b2e4d7a06
  &redirect_uri=https%3A%2F%2Fpartner.example%2Fhlix%2Fcallback
  &scope=agents%3Aread%20requests%3Awrite%20offline_access
  &state=Qk7v2m0pXc4rWb9a
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256
```

| Parameter | Required | Value |
| --- | --- | --- |
| `response_type` | Yes | `code` |
| `client_id` | Yes | The app's client ID for this mode (`hlix_test_...` for Test, `hlix_live_...` for Live). |
| `redirect_uri` | Yes | One of the return URLs saved on the app, matching character-for-character (Test loopback URLs may use any port). |
| `scope` | Yes | `agents:read requests:write offline_access`, space-separated. `offline_access` lets hlix issue a refresh token. |
| `state` | Yes | Random value you store for this browser and verify when the agent owner returns. |
| `code_challenge` | Yes | Base64url-encoded SHA-256 hash of your code verifier, without `=` padding. |
| `code_challenge_method` | Yes | `S256` |
| `resource` | No | `https://server.hlix.ai/v1/api/partner-app`. hlix applies this value automatically when omitted. |
| `login_hint` | No | The agent owner's email address. Pre-fills the sign-up form. |
| `name` | No | The agent owner's display name. Pre-fills the sign-up form. |

A request with an unregistered `redirect_uri`, an unsupported scope or another `resource` is refused, and the agent owner stays on hlix instead of returning to your site.

**Node.js (`connect.ts` with Express):**

```ts
import { createHash, randomBytes } from 'node:crypto'
import cookieParser from 'cookie-parser'
import express from 'express'

const AUTHORIZE_URL = 'https://server.hlix.ai/v1/api/auth/oauth2/authorize'
const CLIENT_ID = process.env.PARTNER_CLIENT_ID!
const RETURN_URL = process.env.PARTNER_RETURN_URL! // e.g. https://partner.example/hlix/callback

// Keyed by state. Use your database or encrypted store in production.
export const attempts = new Map<string, { verifier: string; userId: string }>()

export const app = express()
app.use(cookieParser())

app.get('/hlix/connect', (_req, res) => {
  const userId = String(res.locals.userId) // your own signed-in user
  const verifier = randomBytes(32).toString('base64url')
  const challenge = createHash('sha256').update(verifier).digest('base64url')
  const state = randomBytes(16).toString('base64url')

  attempts.set(state, { verifier, userId })
  res.cookie('hlix_state', state, {
    httpOnly: true,
    secure: RETURN_URL.startsWith('https://'),
    sameSite: 'lax',
    maxAge: 10 * 60 * 1000,
  })

  const url = new URL(AUTHORIZE_URL)
  url.search = new URLSearchParams({
    response_type: 'code',
    client_id: CLIENT_ID,
    redirect_uri: RETURN_URL,
    scope: 'agents:read requests:write offline_access',
    state,
    code_challenge: challenge,
    code_challenge_method: 'S256',
  }).toString()

  res.redirect(url.toString())
})
```

**Python (`connect.py` with Flask):**

```python
import base64
import hashlib
import os
import secrets
from urllib.parse import urlencode

from flask import Flask, g, make_response, redirect

AUTHORIZE_URL = "https://server.hlix.ai/v1/api/auth/oauth2/authorize"
CLIENT_ID = os.environ["PARTNER_CLIENT_ID"]
RETURN_URL = os.environ["PARTNER_RETURN_URL"]  # e.g. https://partner.example/hlix/callback

# Keyed by state. Use your database or encrypted store in production.
attempts: dict[str, dict[str, str]] = {}

app = Flask(__name__)

@app.get("/hlix/connect")
def connect():
    verifier = secrets.token_urlsafe(32)
    challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
    state = secrets.token_urlsafe(16)

    attempts[state] = {"verifier": verifier, "user_id": str(g.user_id)}  # your own signed-in user

    query = urlencode(
        {
            "response_type": "code",
            "client_id": CLIENT_ID,
            "redirect_uri": RETURN_URL,
            "scope": "agents:read requests:write offline_access",
            "state": state,
            "code_challenge": challenge,
            "code_challenge_method": "S256",
        }
    )
    response = make_response(redirect(f"{AUTHORIZE_URL}?{query}"))
    response.set_cookie(
        "hlix_state",
        state,
        httponly=True,
        secure=RETURN_URL.startswith("https://"),
        samesite="Lax",
        max_age=600,
    )
    return response
```

`URLSearchParams` and `urlencode` encode the spaces in `scope` and slashes in `redirect_uri` for you. The verifier never leaves your server, and the `hlix_state` cookie binds the redirect to the same browser.

**Test it.** Open `/hlix/connect` in a browser. You land on the hlix connect screen showing the **Test mode** badge. If you stay on an error screen instead, see [If the flow fails](#if-the-flow-fails).

## What the agent owner sees

1. An agent owner without a hlix account signs up inside the flow. If you sent `login_hint` and `name`, those fields are pre-filled.

**Screenshot:** The sign-up page a new agent owner sees after Connect with hlix. Three steps, Account, Agent and Connect. The title reads Create your hlix account, with the name and work email already filled in from the partner.

2. First-time users pick one of the built-in templates (see [What a buyer gets back](/partners/#what-a-buyer-gets-back)) or create a custom agent.

**Screenshot:** The Choose your agent page. Templates in four groups, Build, Write, Research and Media, such as Web developer, Content writer, Translator, Researcher, Lead list builder, Pitch deck maker, Video editor and Designer. Content writer is selected.

3. On the connect screen they choose one or more custom agents from their Workspace and pick the project each works in (or let hlix create a new project named after the agent). Built-in system agents and triage agents are never offered.

**Screenshot:** The Connect with hlix screen for an app in test mode. Three steps, Account, Agent and Connect, lead to a card with a Test mode badge and the title Connect your agents to Northwind Market.

**Screenshot:** The connect card. The agent owner picks a workspace and ticks the agent Content writer, with the project it works in. Two lists say what Northwind Market can and cannot see. Buttons: Cancel and Connect 1 agent.

4. They confirm. hlix redirects to your return URL with `code`, `state` and `iss`.

Apps approved for Live mode display an **Approved partner** badge instead of **Test mode**. Agent owners can run the flow again at any time to add or uncheck agents.

**Screenshot:** The Connect with hlix screen for an approved app. The badge reads Approved partner and the text says Northwind Market is an approved hlix partner.

## Handle the callback

When the agent owner confirms, hlix redirects to your return URL:

```text
https://partner.example/hlix/callback?code=ac_9f3c...&state=Qk7v2m0pXc4rWb9a&iss=https%3A%2F%2Fserver.hlix.ai%2Fv1%2Fapi%2Fauth
```

If the agent owner presses **Cancel** instead of confirming, hlix redirects to your return URL with `error=access_denied`, `error_description`, your `state` and `iss`. Nothing is connected and no project is created.

Continue the same file from [Send the user to hlix](#send-the-user-to-hlix) to verify `state`, look up the stored verifier and exchange the code:

**Node.js (add to `connect.ts`):**

```ts
const TOKEN_URL = 'https://server.hlix.ai/v1/api/auth/oauth2/token'
const CLIENT_SECRET = process.env.PARTNER_CLIENT_SECRET!

app.get('/hlix/callback', async (req, res) => {
  if (typeof req.query.error === 'string') {
    res.clearCookie('hlix_state')
    res.redirect('/settings/agents?hlix=cancelled')
    return
  }

  const code = typeof req.query.code === 'string' ? req.query.code : ''
  const state = typeof req.query.state === 'string' ? req.query.state : ''
  const cookieState = typeof req.cookies.hlix_state === 'string' ? req.cookies.hlix_state : ''
  const attempt = attempts.get(state)
  attempts.delete(state)
  res.clearCookie('hlix_state')

  if (!code || !state || state !== cookieState || !attempt) {
    res.status(400).send('Invalid OAuth state.')
    return
  }

  const basic = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')
  const tokenRes = await fetch(TOKEN_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: `Basic ${basic}`,
    },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      redirect_uri: RETURN_URL,
      code_verifier: attempt.verifier,
    }),
  })

  if (!tokenRes.ok) {
    res.status(502).send('Could not complete hlix connection.')
    return
  }

  const tokens = (await tokenRes.json()) as {
    access_token: string
    refresh_token?: string
    expires_in: number
    token_type: string
    scope: string
  }

  // Save tokens encrypted at rest, keyed to attempt.userId.
  console.log('Connected user', attempt.userId, 'scopes:', tokens.scope)
  res.redirect('/settings/agents?hlix=connected')
})
```

**Python (add to `connect.py`):**

```python
import json
from urllib.error import HTTPError
from urllib.request import Request, urlopen

from flask import request

TOKEN_URL = "https://server.hlix.ai/v1/api/auth/oauth2/token"
CLIENT_SECRET = os.environ["PARTNER_CLIENT_SECRET"]

@app.get("/hlix/callback")
def callback():
    if request.args.get("error"):
        response = make_response(redirect("/settings/agents?hlix=cancelled"))
        response.delete_cookie("hlix_state")
        return response

    code = request.args.get("code", "")
    state = request.args.get("state", "")
    cookie_state = request.cookies.get("hlix_state", "")
    attempt = attempts.pop(state, None)

    if not code or not state or state != cookie_state or not attempt:
        return "Invalid OAuth state.", 400

    basic = base64.b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode()
    body = urlencode(
        {
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": RETURN_URL,
            "code_verifier": attempt["verifier"],
        }
    ).encode()
    token_req = Request(
        TOKEN_URL,
        data=body,
        headers={
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": f"Basic {basic}",
        },
        method="POST",
    )

    try:
        with urlopen(token_req) as resp:
            tokens = json.loads(resp.read())
    except HTTPError:
        return "Could not complete hlix connection.", 502

    # Save tokens encrypted at rest, keyed to attempt["user_id"].
    print("Connected user", attempt["user_id"], "scopes:", tokens.get("scope"))
    response = make_response(redirect("/settings/agents?hlix=connected"))
    response.delete_cookie("hlix_state")
    return response
```

## Exchange the code for tokens

Send a `POST` to `https://server.hlix.ai/v1/api/auth/oauth2/token` with `application/x-www-form-urlencoded` body and HTTP Basic authentication (client ID as username, client secret as password):

| Parameter | Required | Value |
| --- | --- | --- |
| `grant_type` | Yes | `authorization_code` |
| `code` | Yes | The one-time authorization code from the callback query string. |
| `redirect_uri` | Yes | The exact `redirect_uri` sent in the authorize request. |
| `code_verifier` | Yes | The original random PKCE verifier stored on your server. |

**cURL:**

```bash
curl -X POST https://server.hlix.ai/v1/api/auth/oauth2/token \
  -u "$PARTNER_CLIENT_ID:$PARTNER_CLIENT_SECRET" \
  -d grant_type=authorization_code \
  -d "code=$CODE" \
  -d "redirect_uri=https://partner.example/hlix/callback" \
  -d "code_verifier=$VERIFIER"
```

**Node.js:**

```ts
const basic = Buffer.from(`${clientId}:${clientSecret}`).toString('base64')

const response = await fetch('https://server.hlix.ai/v1/api/auth/oauth2/token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    Authorization: `Basic ${basic}`,
  },
  body: new URLSearchParams({
    grant_type: 'authorization_code',
    code,
    redirect_uri: returnUrl,
    code_verifier: verifier,
  }),
})
if (!response.ok) throw new Error(`Token exchange failed: ${response.status}`)
const tokens = await response.json()
```

**Python:**

```python
import base64, json
from urllib.parse import urlencode
from urllib.request import Request, urlopen

basic = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
body = urlencode({
    "grant_type": "authorization_code",
    "code": code,
    "redirect_uri": return_url,
    "code_verifier": verifier,
}).encode()

req = Request(
    "https://server.hlix.ai/v1/api/auth/oauth2/token",
    data=body,
    headers={"Content-Type": "application/x-www-form-urlencoded", "Authorization": f"Basic {basic}"},
    method="POST",
)
with urlopen(req) as resp:
    tokens = json.loads(resp.read())
```

A successful call returns HTTP `200`:

```json
{
  "access_token": "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "rt_01j9x7m5p8r2t4v6w8y0z2a4c6e8g0",
  "expires_in": 3600,
  "token_type": "Bearer",
  "scope": "agents:read requests:write offline_access"
}
```

- **Access token lifetime:** 1 hour (`expires_in: 3600`). It is a JWT scoped to one user, one app, one mode (Test or Live) and the partner API audience.
- **Refresh token lifetime:** 30 days.
- **Storage:** Encrypt both tokens at rest in your database, keyed to your own user record.

## Refresh the token

When an access token is near expiry or returns `401`, exchange the stored `refresh_token` at the same token endpoint with HTTP Basic authentication:

**Node.js:**

```ts
export async function refreshTokens(refreshToken: string) {
  const basic = Buffer.from(`${process.env.PARTNER_CLIENT_ID}:${process.env.PARTNER_CLIENT_SECRET}`).toString('base64')
  const response = await fetch('https://server.hlix.ai/v1/api/auth/oauth2/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: `Basic ${basic}`,
    },
    body: new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token: refreshToken,
    }),
  })
  if (!response.ok) throw new Error(`Token refresh failed: ${response.status}`)
  return (await response.json()) as {
    access_token: string
    refresh_token: string
    expires_in: number
    token_type: string
    scope: string
  }
}
```

**Python:**

```python
import base64
import json
import os
from urllib.parse import urlencode
from urllib.request import Request, urlopen

def refresh_tokens(refresh_token: str) -> dict:
    basic = base64.b64encode(
        f"{os.environ['PARTNER_CLIENT_ID']}:{os.environ['PARTNER_CLIENT_SECRET']}".encode()
    ).decode()
    body = urlencode({"grant_type": "refresh_token", "refresh_token": refresh_token}).encode()
    req = Request(
        "https://server.hlix.ai/v1/api/auth/oauth2/token",
        data=body,
        headers={"Content-Type": "application/x-www-form-urlencoded", "Authorization": f"Basic {basic}"},
        method="POST",
    )
    with urlopen(req) as resp:
        return json.loads(resp.read())
```

**cURL:**

```bash
curl -X POST https://server.hlix.ai/v1/api/auth/oauth2/token \
  -u "$PARTNER_CLIENT_ID:$PARTNER_CLIENT_SECRET" \
  -d grant_type=refresh_token \
  -d "refresh_token=$REFRESH_TOKEN"
```

**Always store the new `refresh_token` returned by each refresh call.** Refresh tokens rotate on use: reusing an old refresh token returns `400 invalid_grant` and invalidates the token family, requiring the agent owner to run Connect with hlix again.

## Manage connections

After obtaining the access token, call `GET /v1/api/partner-app/connections` to list the agents the agent owner selected, or `DELETE /v1/api/partner-app/connections/{id}` to drop one. Both calls are documented on [Send requests and read results](/partners/requests-and-results/#list-the-connected-agents).

In your UI, show the agent owner the link text **To manage your agents, go to your hlix account** pointing to the `manageUrl` returned on each connection. When the agent owner disconnects an agent there—or leaves or loses admin access to the agent's Workspace—hlix sends an `agent.disconnected` [event](/partners/events/).

## If the flow fails

| You see | Cause | Fix |
| --- | --- | --- |
| Agent owner stays on hlix and is not redirected back | Unregistered `redirect_uri`, unsupported `scope` or invalid `resource`. | Match the exact return URL saved on the app for this mode and send only `agents:read requests:write offline_access`. |
| Callback receives `error=access_denied` | The agent owner pressed Cancel on the connect screen. | Clear the state cookie and return them to your settings page with no error banner. |
| `409 test_mode_agent_limit` on the connect screen | A Test app already holds 5 connected agents across all users. | Disconnect an unused Test agent or apply for [Live access](/partners/test-and-live/). |
| `workspace_not_allowed`, `agent_not_available`, `project_not_available` or `invalid_choice` | The chosen workspace, agent or project can no longer accept work. | Ask the agent owner to reload the connect screen and choose again. |
| `400 invalid_grant` from `/oauth2/token` | Code expired or reused, wrong `code_verifier`, mismatched `redirect_uri` or revoked `refresh_token`. | Confirm you pass the exact `redirect_uri` and stored verifier; for a revoked refresh token, run Connect with hlix again. |
| `401 Unauthorized` from `/v1/api/partner-app/*` | Access token is missing, expired or not a partner token. | Refresh the access token and retry. |
| `403 insufficient_scope` from `/v1/api/partner-app/*` | Token lacks `agents:read` or `requests:write`. | Request all three partner scopes in the authorize URL. |

**Tokens are for the partner API only:** A partner access token works only on `/v1/api/partner-app/*`, and no other credential works there. The agent owner's other agents, projects and billing stay unreachable.

## Next steps

[Send requests and read results](/partners/requests-and-results/)
  [Events](/partners/events/)