@astralbeam/sdk

中文文档
0.30.1发布于 2026/11/07MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 3152

Frontend SDK for AstralBeam: drop-in agent UI, chat streaming, and server helpers

原始使用文档
文档目录9 节
  1. Quick start
  2. Authentication
  3. Options
  4. Tools and widgets
  5. MCP connections
  6. Documentation
  7. Entry points
  8. Examples
  9. License

@astralbeam/sdk

Embed an agent chat sidebar or read-only tenant directories in your web app, or build your own chat UI with the headless core. The widgets isolate their styles in shadow roots.

npm install @astralbeam/sdk

Quick start

One component in React, one function everywhere else. Full setup, including the required token endpoint, is in Getting started.

import { AstralBeamChat } from "@astralbeam/sdk/react"

export function Sidebar() {
  return (
    <aside style={{ height: "100dvh" }}>
      <AstralBeamChat />
    </aside>
  )
}
import { mountAstralBeamChat } from "@astralbeam/sdk/client"

const handle = mountAstralBeamChat(document.getElementById("sidebar")!, {})
// Update with handle.update({ colorScheme: "dark" }), then clean up with handle.unmount().

Without npm or a bundler, import the same entry from jsDelivr in a module script. Pin an exact version and the full /dist/client.js path, because the loader imports its lazy chunks relative to itself. See Script tag.

<div id="sidebar" style="height:100dvh"></div>
<script type="module">
  import { mountAstralBeamChat } from "https://cdn.jsdelivr.net/npm/@astralbeam/[email protected]/dist/client.js"

  mountAstralBeamChat(document.getElementById("sidebar"), {})
</script>
  • Chat resizes horizontally and fills its parent's height. Give it a definite height (min-h-0 in a flex column) and flexible width.
  • Chat uses the hosted cloud by default. Tokens come from your application. For self-hosting, set apiUrl to your deployment’s /api base.
  • @astralbeam/sdk/client ships no React. The chat loads as a lazy chunk with its own bundled copy.
  • No runtime dependencies. react and react-dom are optional peers used only by @astralbeam/sdk/react.
  • Mount it above your router if the transcript should survive page navigation.

Authentication

Your server must authenticate the host session and mint a chat token before the widget can chat. Keep the API key server-only. See Authentication.

Replace getApplicationSession below with your application's authenticated session lookup. Return the current user and their verified customer-account membership as session.user and session.tenant.

import { createAstralBeamToken } from "@astralbeam/sdk/server"

const apiKey = process.env.ASTRALBEAM_API_KEY // key_<organizationId>_<id>_abo_<secret>

export async function POST(request: Request) {
  const headers = { "Cache-Control": "no-store" }
  if (!apiKey) return Response.json({ error: "Not configured" }, { status: 503, headers })
  const session = await getApplicationSession(request)
  if (!session) return Response.json({ error: "Unauthenticated" }, { status: 401, headers })
  try {
    const token = await createAstralBeamToken({
      apiKey,
      user: {
        id: session.user.id,
        name: session.user.name,
        metadata: { email: session.user.email },
      },
      tenant: {
        id: session.tenant.id,
        name: session.tenant.name,
        metadata: { plan: session.tenant.plan },
      },
    })
    return Response.json({ token }, { headers })
  } catch {
    return Response.json({ error: "Token could not be issued" }, { status: 500, headers })
  }
}
  • Authenticate once and derive stable user.id and tenant.id values from that trusted session.
  • Keep API keys server-only. Tokens are signed, not encrypted, so their claims must contain no secrets.
  • Return Cache-Control: no-store and fail closed when configuration or authentication is missing.
  • Directory access additionally requires signed user.admin: true, derived from trusted tenant permissions, and persisted records. Follow Tenant directories.
  • For employee-facing Tenant management, use createAstralBeamOrganizationToken. The API client guide covers database-backed roles and browser integration.

After acquiring a token, components call POST /api/v1/me and renew before expiry. See authentication and refresh behavior.

Options

Pass options as React props or apply a subset with handle.update(options). Presentation changes preserve chat. Changing threadId selects a conversation, and changing apiUrl clears the previous deployment's state. See Configuration for all options, defaults, layout, and chrome slots.

Most embeds let <AstralBeamChat {...options} /> manage the session. For external controls, create chat with useAstralBeamChat(options) and render <AstralBeamChat chat={chat} />. Configure authentication and tools on the hook, with widgets and appearance on the view. Call actions directly on chat and read state through chat.getState().

Conversations are saved automatically and start private. The widget searches saved conversation titles. Reopening history does not execute earlier tool calls. Disconnecting can interrupt the current response.

The headless session exposes conversation navigation, search, and pagination. With useAstralBeamChat, access these through chat, for example chat.openThread(threadId). History loads a page at a time. reset() starts a new chat and keeps the saved one.

Download an attachment with chat.getThreadAttachment({ threadId, fileId }), which returns a Blob. Organization and participant tenant scope come from your credentials. Administrative downloads also pass tenantId. Use { preview: true } as the second argument for a thumbnail. Only previews of your unsent uploads may omit threadId.

By default, threadId: "auto" restores this tab's selection after reload using session storage, scoped to the current account, API, and placementKey ?? agentId ?? "default". Use distinct placement keys for independent chats with the same agent. A fresh, independently opened tab starts a new chat. Use threadId: "new" to bypass restoration, or pass a saved thread UUID. The widget keeps unsent text and uploaded file references in local storage per placement, account, API, and conversation. Reopening restores the draft without sending it automatically. The host owns sidebar visibility and can persist it separately in session storage.

Tools and widgets

A tool does something: its execute runs in your page. A widget shows something: its render draws your UI into the conversation. Both are declared with a description and a parameters schema. See Tools and widgets.

tools: {
  restart_service: {
    metadata: { title: "Restart a service" },
    description: "Restart one of the host app's services by name",
    parameters: { type: "object", properties: { service: { type: "string" } }, required: ["service"] },
    execute: async ({ service }) => await restartService(String(service)),
  },
},
widgets: {
  systemStatus: {
    description: "Shows the current status of the host app's systems",
    parameters: { type: "object", properties: { degraded: { type: "boolean" } } },
    render: ({ degraded }) => <StatusCard degraded={Boolean(degraded)} />,
  },
}
  • Schemas are plain JSON Schema, or any Standard Schema validator (Zod, Valibot, ArkType).
  • Only a Standard Schema validates input in the browser. With plain JSON Schema, treat input as untrusted.
  • Return plain JSON values from tools, with no undefined fields. If a result cannot be sent, the action may still have happened.

MCP connections

Remote tools appear under MCP connections in the authenticated Tenant widget. Organization admins configure the available MCP servers. Each TenantUser creates their own connection to a server. Public endpoints, static headers and OAuth are supported. Tool results follow the conversation's visibility and retention rules. Disconnect removes the saved connection and its credentials from AstralBeam.

Headless consumers can use chat.getMcpCatalog(), chat.manageMcpConnection(operation) and chat.authorizeMcpConnection({ mcpServerId, id? }). Start OAuth from a user gesture to open its popup. Browser binding and completion use the authenticated session. Server tool titles arrive in state.serverToolTitles, independently of host tool execution.

Reuse the dashboard's server list and form with AstralBeamMcpServers from /react or mountAstralBeamMcpServers from /client. Supply the server list and authorized write callbacks. See MCP server management.

Documentation

GuideCovers
API clientTyped resource and chat requests with API keys or JWTs.
Getting startedinstall, mount, layout requirements.
Script tagloading from jsDelivr without a bundler, and Ruby on Rails.
Authenticationthe token endpoint, its security rules, and minting in other languages.
Tenant directoriesprovisioning, Tenant and user listings, saved conversation browsing, lifecycle, and options.
Configurationevery option, and what update can change.
Themingcolor schemes, CSS tokens, the shadow-root boundary.
Tools and widgetsschemas, live state, rendering into the transcript.
Attachmentsfile kinds, limits, what the endpoint enforces.
Limitsrequest, attachment, and sandbox limits.
Sandboxsteps, the opt-in panel, downloads, inline images.
Headlessown the whole chat UI on the same session.
Security modelwho grants, who enforces, what the client can change.

Entry points

Read-only Tenant, TenantUser and conversation widgets are available from /client and /react. See Tenant directories for setup and embedding examples.

React directory refs expose refresh() and reset(), both returning Promise<void>. Use props for updates and conditional rendering to unmount. Vanilla handles also expose update() and unmount(). Unmount during sign-out or identity changes. See the lifecycle contract for authentication, caching, remount reuse, and action completion.

There is no root export.

Entry pointContentsPeer dependency
@astralbeam/sdk/clientChat, directory, and MCP server mountsnone
@astralbeam/sdk/corecreateAstralBeamChat, the headless sessionnone
@astralbeam/sdk/reactChat hooks and isolated UI wrappersreact, react-dom
@astralbeam/sdk/serverTenant and organization token mintersnone
@astralbeam/sdk/apiResource and chat HTTP helpersnone

Types resolve under every TypeScript module resolution mode, including classic "moduleResolution": "node". Requires TypeScript 5.0 or later because declarations use const type parameters, which fail to parse on TypeScript 4.x.

Examples

examples/linearity-react is a TanStack Start and shadcn/ui project tracker with two workspaces, localStorage persistence, and an assistant named Astro. It demonstrates validated tools, live issue cards, tenant switching, and a Basic Auth gate for a hosted playground.

examples/todos embeds the sidebar and a tenant-scoped user listing in a minimal TanStack Start app. Both use the same demo token route. The app also demonstrates host tools over live React state and a todoCard widget, with no Tailwind or shadcn/ui of its own.

examples/todos-rails is the same app in Ruby on Rails 8. It loads the SDK from jsDelivr through an import map, mounts it from a plain ES module, mints tokens with the jwt gem, and gives the agent tools over the app's JSON API.

License

MIT

版本与发布记录

@astralbeam/sdk 共发布 74 个版本,首次发布于 2026/08/19;过去 12 个月发布了 74 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.30.1latest2026/11/07今天
0.30.22026/11/07今天
0.30.32026/11/07今天
0.30.42026/11/07今天
0.30.02026/11/07今天
0.29.62026/11/071 天前

关于 @astralbeam/sdk 的常见问题

@astralbeam/sdk 是什么?

Frontend SDK for AstralBeam: drop-in agent UI, chat streaming, and server helpers

如何安装 @astralbeam/sdk?

在项目目录运行 npm install @astralbeam/sdk,或使用 pnpm add / yarn add / bun add。

@astralbeam/sdk 支持 TypeScript 吗?

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

@astralbeam/sdk 支持 ESM 还是 CommonJS?

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

@astralbeam/sdk 可以商用吗?

@astralbeam/sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@astralbeam/sdk 的下载量有多少?

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

@astralbeam/sdk 还在维护吗?

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