@forwardpath/js

中文文档
0.2.0发布于 2026/10/23UNLICENSEDTypeScriptES Module零依赖近 30 天下载 3980

Framework-free client for the ForwardPath intake API.

原始使用文档
文档目录8 节
  1. Install
  2. Keys
  3. Usage
  4. createBrowserSession(options)
  5. The email form
  6. Sessions from your server
  7. Errors
  8. Page context

@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 ai

ai (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 }.

OptionDescription
baseUrlFPOS origin.
publishableKeyYour fppk_… key.
user{ id, email?, name? } for a signed-in user. Send this or anonymousId.
userHashcreateUserHash() output from @forwardpath/node, computed on your server. Needs user.
anonymousIdA stable id for a visitor with no user, e.g. getAnonymousId().
clientContextPage context, e.g. from collectClientContext().
fetchCustom 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.contactCollection is optional. It's required or off otherwise.
  • Pass shouldSendAfterContact as sendAutomaticallyWhen so the agent carries on after the answer. Don't use the AI SDK's lastAssistantMessageIsCompleteWithToolCalls alone: 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.

版本与发布记录

@forwardpath/js 共发布 4 个版本,首次发布于 2026/10/22;过去 12 个月发布了 4 个版本。

版本发布日期距今
0.2.0latest2026/10/2324 天前
0.1.12026/10/2224 天前
0.1.02026/10/2224 天前
0.0.0-stage2026/10/2224 天前

关于 @forwardpath/js 的常见问题

@forwardpath/js 是什么?

Framework-free client for the ForwardPath intake API.

如何安装 @forwardpath/js?

在项目目录运行 npm install @forwardpath/js,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:ai(^7)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@forwardpath/js 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@forwardpath/js 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@forwardpath/js 可以商用吗?

@forwardpath/js 使用 UNLICENSED 许可。作者声明为 UNLICENSED,即不授予公开使用许可(与公共领域的 Unlicense 不同)。使用前需获得作者授权。以上为概括,不构成法律意见,请以许可原文为准。

@forwardpath/js 的下载量有多少?

根据 npm 官方下载统计,@forwardpath/js 在 2026/10/16 – 2026/11/14 这 30 天内被下载 3,980 次,日均约 133 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@forwardpath/js 还在维护吗?

最新版本 0.2.0 发布于 2026/10/23(24 天前);至今共发布 4 个版本,其中过去 12 个月发布了 4 个;首次发布于 2026/10/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。