@forwardpath/js
v0.2.0
Published
Framework-free client for the ForwardPath intake API.
Readme
@forwardpath/js
Framework-free client for the ForwardPath intake API. It streams the intake
agent through the AI SDK, uploads files and collects
page context. @forwardpath/react and @forwardpath/node build on it.
Install
npm install @forwardpath/js aiai (v7) is a peer dependency.
Keys
A publishable key (fppk_…) is public by design. It's safe in browser code
and only works from the origins allowed on the key. Create one per project
in the ForwardPath portal.
Your secret API key (fp_…) can mint sessions for any user. Keep it on your
server. This package never sends it.
Usage
import { useChat } from "@ai-sdk/react";
import {
collectClientContext,
createBrowserSession,
createIntakeChatTransport,
getAnonymousId,
shouldSendAfterContact,
uploadAttachment,
type UploadedAttachment,
} from "@forwardpath/js";
const baseUrl = "https://app.forwardpath.ai";
const attachments: UploadedAttachment[] = [];
let session: { token: string; expiresAt: string } | null = null;
// Mints a session in the browser; mints again a minute before it expires.
async function getSessionToken() {
if (!session || Date.parse(session.expiresAt) - Date.now() < 60_000) {
session = await createBrowserSession({
baseUrl,
publishableKey: "fppk_…",
// For a signed-in user, send user: { id, email, name } instead.
anonymousId: getAnonymousId(),
clientContext: collectClientContext({ appName: "Acme" }),
});
}
return session.token;
}
const transport = createIntakeChatTransport({
baseUrl,
getSessionToken,
getClientContext: () =>
collectClientContext({ appName: "Acme", appVersion: "2.4.0" }),
getUploadedAttachments: () => attachments,
});
// In a React component:
const { messages, sendMessage, addToolOutput } = useChat({
transport,
sendAutomaticallyWhen: shouldSendAfterContact,
});
// Attach a file before the next message:
attachments.push(
await uploadAttachment({
baseUrl,
sessionToken: await getSessionToken(),
file,
}),
);getSessionToken runs before each chat request, so it can return a cached
token and mint a new one when the old one expires.
createBrowserSession(options)
Calls POST /api/v1/intake/browser-sessions and resolves to
{ token, expiresAt, projectSlug, contactCollection, reporter }.
| Option | Description |
| --- | --- |
| baseUrl | FPOS origin. |
| publishableKey | Your fppk_… key. |
| user | { id, email?, name? } for a signed-in user. Send this or anonymousId. |
| userHash | createUserHash() output from @forwardpath/node, computed on your server. Needs user. |
| anonymousId | A stable id for a visitor with no user, e.g. getAnonymousId(). |
| clientContext | Page context, e.g. from collectClientContext(). |
| fetch | Custom fetch. |
reporter.identity is verified with a valid userHash, claimed with
user alone (the browser named the user, so treat it as unverified) and
anonymous with anonymousId. A bad key or userHash rejects with a 401,
an origin the key doesn't allow with a 403.
getAnonymousId() returns a random id kept in localStorage under
forwardpath:anonymous-id. Where storage is blocked it lasts for the page
load. On a server every caller gets the same id, so call it in the browser.
The email form
When the agent has no email for the reporter and the key collects emails, it
calls the client-side tool requestContact. The chat shows it as a
tool-requestContact part in the input-available state. Show a form, then
answer with addToolOutput:
addToolOutput({
tool: "requestContact",
toolCallId: part.toolCallId,
output: { email: "[email protected]", name: "Ada" }, // or { skipped: true }
});- Check the email with
isContactEmail(email)first. The API rejects the whole chat request if the email is invalid. - Offer a skip only when the assistant message's
metadata.contactCollectionisoptional. It'srequiredoroffotherwise. - Pass
shouldSendAfterContactassendAutomaticallyWhenso the agent carries on after the answer. Don't use the AI SDK'slastAssistantMessageIsCompleteWithToolCallsalone: it resends forever once the agent files the report. - Don't send a new message while the form is open. The API can't take a chat with an unanswered tool call.
@forwardpath/react does all of this for you.
Sessions from your server
To mint sessions on your server with your secret API key, use
@forwardpath/node and have getSessionToken fetch the token from your own
route, e.g. POST /api/forwardpath/session.
Errors
createBrowserSession and uploadAttachment throw, and the chat transport
rejects with, ForwardPathApiError on a non-2xx response. It has status,
code (e.g. unauthorized, validation_error, rate_limited), title and
an optional detail.
import { ForwardPathApiError } from "@forwardpath/js";
try {
await uploadAttachment({ baseUrl, sessionToken, file });
} catch (error) {
if (error instanceof ForwardPathApiError && error.status === 401) {
// Session expired: mint a new one and retry.
}
}Page context
collectClientContext(extra?) reads the page URL, host, path, title,
referrer, user agent, language, time zone and viewport size, then merges in
appName, appVersion, environment and custom. Outside a browser it
returns only extra, so it is safe to call during server rendering. Values past
the API's limits (e.g. custom is capped at 30 keys and 4000 characters)
are clipped or dropped, so they can't fail the chat request.
