Skip to content
中文

Open hosted chat

Add a button that takes signed-in users to a separate Praxis Hosted chat page. Your backend authenticates the user, issues a link, and redirects immediately. No chat component is installed on your host page. The link also works in email or chat messages: the customer signs in only by clicking Start conversation on the page, so link previews do not use it up. Your backend issues that code with the organization API key at POST /customer/v1/grant_codes and builds the link itself; see Customer sign-in.

Prepare your agent

You need Bun, an API key in the agent’s organization, and a service agent with instructions, a runtime environment, and embed settings. The agent must have a short number. Open it under 服务智能体 (Service agents) in the Dashboard, check the short number (5–8 letters or digits) in its header, and copy both it and the public agent_… ID.

Save embed settings first: open 接入 → 接入方式与外观 → 嵌入设置, then click 保存嵌入设置 (a new agent has no embed settings yet). Embed settings can be configured in the Dashboard or through the API; see embed settings. This example uses a local host at http://localhost:4242; chat opens on the hosted domain.

Hosted is a separate page and cannot be embedded in an iframe. To keep users inside the current page, choose iframe or the Kit component.

Runtime environment and vaults come from the agent version pinned by the grant code. Set environment_id and vault_ids in the agent configuration, save and apply it, then issue a new grant code. The old embed-policy fields are deprecated and do not choose the session environment.

Issue a link and redirect

Save this complete server as server.ts. It binds only to loopback, authenticates two test accounts through HTTP Basic, and checks the form request’s origin. PRAXIS_API_KEY stays on the backend. external_user_id comes from the authenticated account, never a form field.

import { timingSafeEqual } from "node:crypto";
const apiKey = process.env.PRAXIS_API_KEY;
const agentId = process.env.PRAXIS_AGENT_ID;
const identityNumber = process.env.PRAXIS_AGENT_IDENTITY;
const password = process.env.DEMO_PASSWORD;
if (!apiKey || !agentId || !identityNumber || !password) throw new Error("Set the four server variables");
const origin = "http://localhost:4242";
const noStore = { "Cache-Control": "no-store" };
function authenticate(request: Request): string | undefined {
const supplied = Buffer.from(request.headers.get("Authorization") ?? "");
for (const id of ["customer_123", "customer_456"]) {
const expected = Buffer.from("Basic " + Buffer.from(`${id}:${password}`).toString("base64"));
if (supplied.length === expected.length && timingSafeEqual(supplied, expected)) return id;
}
}
Bun.serve({
hostname: "127.0.0.1", port: 4242,
async fetch(request) {
const url = new URL(request.url);
if (url.origin !== origin) return new Response("Use localhost:4242", { status: 403 });
const userId = authenticate(request);
if (!userId) return new Response("Sign in", {
status: 401, headers: { ...noStore, "WWW-Authenticate": 'Basic realm="Local demo"' },
});
if (request.method === "GET" && url.pathname === "/") {
return new Response(Bun.file("index.html"), { headers: noStore });
}
if (request.method !== "POST" || url.pathname !== "/api/praxis-hosted") {
return new Response("Not found", { status: 404 });
}
if (request.headers.get("Origin") !== origin) {
return new Response("Origin rejected", { status: 403 });
}
try {
// Hosted codes are bound to no origin: only the click at the chat page spends them.
const response = await fetch("https://api.deepraxis.com/customer/v1/grant_codes", {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({ customer_id: userId, resources: [{ scope: `agent:${agentId}:chat` }] }),
signal: AbortSignal.timeout(30_000),
});
if (!response.ok) return new Response("Token issuance failed", {
status: response.status, headers: noStore,
});
const data = await response.json();
if (typeof data.code !== "string") throw new Error("Invalid grant code response");
// The host builds the chat link; the one-time code rides the fragment and never reaches a server log.
const link = `https://agent.praxisusercontent.com/a/${identityNumber}?mode=hosted#grant=${data.code}`;
return new Response(null, {
status: 302, headers: { ...noStore, Location: link },
});
} catch {
return new Response("Token service unavailable", { status: 502, headers: noStore });
}
},
});
console.log(origin);

grant_codes issues a one-time sign-in code for this customer; an organization-level token names no agent, so issuance names the chat door as the resource agent:<public id>:chat. Successful issuance returns HTTP 201. The host builds the hosted address https://agent.praxisusercontent.com/a/<short number>?mode=hosted#grant=<code>, responds with HTTP 302 and puts it in Location, taking the browser to chat. The code travels only in the #grant= fragment; the API key stays on the backend.

Configure the actual agent ID, API key, and your chosen local test password in the server environment. Save the page in the next section, then start from the same directory:

终端窗口
export PRAXIS_AGENT_ID="agent_REPLACE_ME"
export PRAXIS_AGENT_IDENTITY="ABC123"
# Set PRAXIS_API_KEY and DEMO_PASSWORD in this server process, then run:
bun server.ts

Expected: the terminal shows the local address. Unauthenticated requests and requests from a different origin cannot issue links. In an existing application, replace test-account authentication with session validation and put the route behind login and CSRF protection. Do not use this test-account mechanism for production login.

Add an opening button

Save this as index.html in the same directory. A normal form submission follows the backend redirect. A background fetch request alone does not navigate the browser.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Order support</title>
<form action="/api/praxis-hosted" method="post">
<button type="submit">Open order assistant</button>
</form>
</html>

Open http://localhost:4242, sign in as customer_123 using your test password, and click the button. Expect a page on agent.praxisusercontent.com with a Start conversation button. Click it: the chat input appears and #grant=… leaves the address bar. Each click on your host button requests a fresh link; do not cache the previous result.

Understand link lifetime

The link’s #grant=… fragment is a one-time sign-in code, not an access token. It is valid for 15 minutes after issuance (set expires_in from 60 to 900 seconds) and can be exchanged once. Browsers never send the fragment to a server, so it does not appear in access logs. Do not log, bookmark, or share code-bearing links; each link is for one customer.

The hosted page opens with only Start conversation and does not exchange the code, so email and chat apps that fetch link previews do not use it up. The page removes #grant= from the address bar as soon as it loads, keeping the code only in memory. When the customer clicks, the page submits grant_code to POST /customer/v1/access_tokens and receives an access token. Your backend must not exchange the code first, which would consume the customer’s link.

After sign-in, the hosted page keeps the sign-in in the browser storage of agent.praxisusercontent.com and renews the access token once 80% of its lifetime has passed, without interrupting a reply in progress. An access token lasts 1 hour and renews automatically while the page is open; one sign-in lasts at most max_session_seconds (7 days by default). Reopening the hosted page in the same browser within 1 hour of closing it returns to the conversation; after that the token has expired and the customer opens the link again. When the sign-in ends or is revoked, the page asks the customer to open a new link from where they got it; unfinished input stays in the current tab. A new link always wins over a kept sign-in, so a different customer opening their own link on a shared computer replaces the previous sign-in.

Verify the integration

Use this server-side request to check issuance shape. It prints only the customer ID, expiration, and whether a code came back, without printing the code itself. This independent API check does not navigate a browser. Its fixed customer ID is for controlled testing; your application must use authenticated identity.

终端窗口
set -o pipefail
curl --fail-with-body --silent --show-error \
-X POST https://api.deepraxis.com/customer/v1/grant_codes \
-H "Authorization: Bearer $PRAXIS_API_KEY" \
-H "Content-Type: application/json" \
--data '{"customer_id":"customer_123","resources":[{"scope":"agent:agent_REPLACE_ME:chat"}]}' \
| jq '{customer_id, expires_at, has_code: (.code | startswith("cgc_"))}'

Then exercise the complete button flow. The network panel should show a host POST returning 302; the hosted page makes no exchange request until you click Start conversation, then access_tokens returns 201 and chat appears. Send an order question and confirm a real reply. A loading interface alone does not establish success. Close the tab and open the same address without #grant=: expect to return to the conversation.

Enter as customer_456 in a separate browser and confirm it cannot read the first account’s conversations. Unauthenticated host requests should return HTTP 401. To test link expiration, issue a test link with expires_in set to 60 and click Start conversation after 60 seconds. Expect a notice that the link has expired.

Handle failures and appearance

Exchange returns GRANT_CODE_INVALID (HTTP 401) for expired, used, and unknown codes; the page says the link has expired, and the customer restarts from your host. Issuance returns HTTP 400 when no resources entry has the shape agent:<public id>:chat; copy the public ID from the Dashboard and retry. On a lost connection the page keeps Start conversation so the customer can click again. For HTTP 429, wait according to Retry-After.

Save appearance under 接入 → 接入方式与外观 → iframe. Hosted shares settings such as name, theme, and greeting. Persistent appearance can currently only be configured in the Dashboard. Hosted always displays a full-page conversation without a floating launcher. The Dashboard’s Hosted → 打开预览 button is a preview and does not replace host issuance for real signed-in users.

Next steps