# Context-aware Octy

> An Octy embedded in the organisation's own site that knows the visitor's context: page hints, or a short-lived token the organisation's server signs about the signed-in visitor, with the scope it narrows to and the facts it carries.

An Octy™ profile embedded in the organisation’s own site can be told about the visitor in front of it. A client onboarding assistant, for example, can know which applicant is being onboarded, which step of the application they are on and which product they applied for, and answer for that applicant from the profile’s own knowledge.

Context never widens what a profile can see. It narrows the knowledge Octy searches and gives the model facts about the visitor; the profile’s corpora, tier, audience and controls stay as they are.

Visitor context, and the profile’s presentation (full page or embedded), apply to a profile that runs in a client deployment. A profile on Atlantic’s hosting keeps visitor context off.

## The three modes

Set the mode under **Agents → Octy profiles → Settings → Visitor context**.

| Mode                  | What the host page sends                                                | What Octy does with it                                                                         |
| --------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| **Off** (the default) | Nothing                                                                 | Answers as for any visitor                                                                     |
| **Page hints**        | The page’s path, and a step and title the page sets                     | Treats them as untrusted page context. Hints never change access                               |
| **Signed**            | A token the organisation’s own server signs about the signed-in visitor | Verifies it, then narrows retrieval to the token’s scope and gives the model the token’s facts |

## What the host page sends

The widget sends the context with each question. The host page provides it in one of two ways.

- **A token endpoint.** For signed context, the Widget tab’s snippet carries `data-octy-context-url="/octy-context"`. The widget requests that address on the host page’s own origin, with the visitor’s cookies, and reads `{"token": "..."}` from the answer. It requests a new token when the current one is within 60 seconds of expiry.
- **The element’s property.** A page that places the `<aal-octy>` element itself sets `context` directly:

```js
document.querySelector("aal-octy").context = {
  token: "eyJhbGciOiJFZERTQSIs...",              // signed context, from your server
  hints: { step: "Identity check", title: "Open an account" },
};
```

Hints default from the page: `path` is the page’s path, and `step` and `title` are sent only when the page sets them. Each hint is plain text of at most 200 characters, and at most three hints are sent.

## Minting a token on your own server

The token is a compact JSON Web Token signed with a private key that stays on the organisation’s server. LightHouse holds only the matching public key.

### The key pair

Make an Ed25519 key pair, keep the private key with the server’s other secrets, and add the public key to the profile under **Public keys**:

```sh
openssl genpkey -algorithm ed25519 -out octy-context.pem
openssl pkey -in octy-context.pem -pubout -out octy-context.pub.pem
```

ES256 (a P-256 key) is accepted as well. LightHouse refuses anything that is, or contains, a private key.

### The claims

| Claim        | Value                                                                                                                 |
| ------------ | --------------------------------------------------------------------------------------------------------------------- |
| Header `alg` | `EdDSA` or `ES256`, matching the key                                                                                  |
| Header `kid` | The key id given for the public key in LightHouse                                                                     |
| `iss`        | The **Issuer** set on the profile                                                                                     |
| `aud`        | The profile’s id, shown on the Widget tab                                                                             |
| `sub`        | An opaque identifier for the visitor, such as a salted hash of the applicant number. Never an email address or a name |
| `iat`, `exp` | Issue and expiry times. `exp` minus `iat` may not exceed the profile’s longest token lifetime, at most 900 seconds    |
| `aal_scope`  | Optional: `{"labels": [...], "collections": [...]}`, narrowing what Octy searches                                     |
| `aal_facts`  | Optional: a JSON object of facts about the visitor, at most 4 KB                                                      |

### The endpoint

The endpoint sits behind the organisation’s own sign-in, answers only for the signed-in visitor, and is never cached. A token lifetime of a few minutes is usual; the widget asks again before it expires.

**Python**

```python
# pip install flask "pyjwt[crypto]"
import time

import jwt
from flask import Flask, jsonify

app = Flask(__name__)
ISSUER = "https://onboarding.example.com"
AUDIENCE = "op_..."                  # the profile's id, from the Widget tab
KEY_ID = "2026-11"
PRIVATE_KEY = open("/run/secrets/octy-context.pem").read()


def octy_context():
    applicant = current_applicant()  # your own session
    now = int(time.time())
    claims = {
        "iss": ISSUER, "aud": AUDIENCE, "sub": applicant.opaque_id,
        "iat": now, "exp": now + 300,
        "aal_scope": {"labels": [applicant.product]},
        "aal_facts": {"application_step": applicant.step, "product": applicant.product,
                      "documents_outstanding": applicant.documents_outstanding},
    }
    token = jwt.encode(claims, PRIVATE_KEY, algorithm="EdDSA", headers={"kid": KEY_ID})
    response = jsonify(token=token)
    response.headers["Cache-Control"] = "no-store"
    return response


# GET /octy-context, behind your own sign-in.
app.add_url_rule("/octy-context", view_func=login_required(octy_context))
```

**TypeScript**

```ts
// npm install express jose
import { readFileSync } from "node:fs";
import express from "express";
import { importPKCS8, SignJWT } from "jose";

const ISSUER = "https://onboarding.example.com";
const AUDIENCE = "op_...";           // the profile's id, from the Widget tab
const KEY_ID = "2026-11";
const privateKey = await importPKCS8(readFileSync("/run/secrets/octy-context.pem", "utf8"), "EdDSA");

const app = express();

app.get("/octy-context", requireSignIn, async (req, res) => {   // your own sign-in
  const applicant = currentApplicant(req);                        // your own session
  const token = await new SignJWT({
    aal_scope: { labels: [applicant.product] },
    aal_facts: { application_step: applicant.step, product: applicant.product,
                 documents_outstanding: applicant.documentsOutstanding },
  })
    .setProtectedHeader({ alg: "EdDSA", kid: KEY_ID })
    .setIssuer(ISSUER)
    .setAudience(AUDIENCE)
    .setSubject(applicant.opaqueId)
    .setIssuedAt()
    .setExpirationTime("5m")
    .sign(privateKey);
  res.set("Cache-Control", "no-store").json({ token });
});
```

The Widget tab shows a shorter Python example with the profile’s issuer, id and newest key id filled in.

## What Octy does with the context

- **Scope.** `aal_scope` narrows retrieval to the labels and collections it names, intersected with what the profile may already see. A label or collection outside the profile’s knowledge adds nothing.
- **Facts.** `aal_facts` reaches the model as facts about the visitor, set apart from the question and the passages. Octy uses them to answer for this visitor, for example to say which documents the applicant still has to provide. Facts are data: an instruction placed in a fact is not followed.
- **Hints.** Page hints reach the model as untrusted page context. They help Octy understand where the visitor is and never change what it may search or say.
- **Refusals.** A signed token that fails verification is refused with HTTP 401 and a plain reason: `context_invalid` (signature, key id, issuer or audience) or `context_expired`. With **Require context** on, a question without a token is refused `context_required`.

## Signed context as the visitor’s sign-in

By default, signed context adds to the deployment’s own sign-in: where the profile is not public, the visitor still signs in to the deployment as usual.

With **Require context** on, **Use the token as the visitor’s sign-in** makes a valid token the visitor’s sign-in for that profile. The organisation’s server then vouches for the visitor on this profile, and the deployment’s own sign-in no longer applies to it. The visitor has no roles beyond what the token’s scope narrows to, and every answer’s evidence records that the visitor was signed in by context. Other profiles and every administration page keep the deployment’s sign-in.

Turn it on only where the organisation’s own site already signs the visitor in, as an onboarding portal does.

## The deployment’s own Octy

The Octy a deployment runs from its own configuration, answering on `POST /v1/octy/chat`, takes the same context: the configuration’s `visitor_context` holds the same settings (mode, issuer, keys, Require context and, if wanted, the token as sign-in), and the request body carries the same `context` object as the widget’s. That Octy’s tools run as before, now with the context’s scope and facts. Octy profiles run no tools.

## What evidence records

Each answer’s evidence and telemetry record the context as `{mode, kid, sub_hash, claims_sha256}`: the mode, the key that verified the token, a hash of the visitor identifier and a hash of the claims. Answers given to a visitor signed in by context are marked as such. Neither the facts nor the hints are recorded.

## The security model

- **The private key never leaves the organisation’s server.** LightHouse holds public keys only and refuses a private key, so a LightHouse administrator cannot mint tokens.
- **A token is bound to one profile.** `aud` is the profile’s id and `iss` the profile’s issuer; a token for another profile, or from another issuer, is refused.
- **A token is short-lived.** Its lifetime is capped by the profile, at most 900 seconds, with 60 seconds’ allowance for clock difference.
- **Context narrows and never widens.** The token’s scope is intersected with the profile’s own knowledge; hints change nothing about access.
- **The token endpoint is the organisation’s.** It runs on the host page’s own origin, behind the organisation’s sign-in. The content security policy needs `'self'` in `connect-src` for it; the Widget tab lists it.
- **Visitor identifiers stay opaque.** Use an opaque `sub`. Evidence records only its hash.
- **Every change is audited.** The mode, the issuer, the sign-in setting and each key added or removed are in the profile’s audit trail, keys named by id and fingerprint.

## Rotating a key

A profile holds at most two public keys, so a key can be replaced without a gap.

1. Make a new key pair and add the new public key under **Public keys** with a new key id. Save. Both keys now verify tokens.
2. Move the server to the new private key and key id.
3. When tokens signed with the old key have expired, remove the old key and save.

The last key cannot be removed while the mode is Signed: add its replacement first.

## Setting it up

1. Open the profile in LightHouse (**Agents → Octy profiles**). It must run in a deployment.
2. On **Settings**, under **Presentation**, choose **Embedded** for an Octy that lives inside the organisation’s own site, or keep **Full page**.
3. Under **Visitor context**, choose **Signed**, enter the **Issuer**, set the longest token lifetime, add the public key, and turn on **Require context** where every question must come with a token. Save.
4. Add the token endpoint to the organisation’s server.
5. Copy the snippet from the **Widget** tab, with `data-octy-context-url`, and add `'self'` to the page’s `connect-src`.
6. For the profile’s own page to answer, set `AAL_OCTY_PUBLIC_URL` on the deployment to the public address of its Octy service, or list that host under **Allowed origins**.

See [The website widget](/octy/widget/) for the snippet, branding and the content security policy.

Source: https://docs.atlanticagenticlabs.com/octy/context/
