A frontend-only library for browser Agent conversations and JavaScript execution in native Workers. It requires no application backend, Pluxel runtime, login system or server RPC endpoint. Cap’n Web connects the page and its Worker over a local MessagePort; the exposed API can be an ordinary local RpcTarget wrapped in a RpcStub.
Model conversations can call a user-configured inference endpoint directly from the browser, subject to that endpoint’s CORS and credentials. Worker-only execution needs no model service. The source checkout includes examples/local-react, a local API and deterministic model demonstration with no backend or model key.
In this guide, application or host means the frontend that embeds the library. A React “effect” means React.useEffect, never Pluxel’s plugin effects.
| Use | Install library packages | Shared peers | Vite plugin |
|---|---|---|---|
| Execute JavaScript against a local capability | Core; import /execution |
Cap’n Web | Not needed |
| Headless model conversation | Core; import the root entry | Cap’n Web | Enable for pi browser adaptation |
| React with your own assistant-ui components | Core + React bridge | Cap’n Web, React, React DOM, assistant-ui | Enable |
| Ready-made chat UI | Core + React bridge + UI | Same as React bridge | Enable; import UI stylesheet |
The package names are @pluxel/browser-worker-agent, @pluxel/browser-worker-agent-react and @pluxel/browser-worker-agent-ui. Dependencies flow from UI to React to core. The /execution module imports no model or UI code, although installing the core package also installs its pi dependencies.
Clone the independent repository (Node 24+ and pnpm 11):
git clone https://github.com/PluxelJS/browser-worker-agent.git
cd browser-worker-agent
pnpm install --frozen-lockfile
pnpm build:allThese instructions use the vendored source or locally packed artifacts; they do not assume that the package names are published to a registry. To add the source to a pnpm application, copy this directory to vendor/browser-worker-agent, include it and vendor/browser-worker-agent/packages/* in the application’s workspace, and merge the named catalogs from this directory’s pnpm-workspace.yaml into the application’s workspace file. Run the following in the consuming frontend package (omit the React/UI packages and peers for headless use):
pnpm add '@pluxel/browser-worker-agent@workspace:*' '@pluxel/browser-worker-agent-react@workspace:*' '@pluxel/browser-worker-agent-ui@workspace:*'
pnpm add 'capnweb@^0.12.0' 'react@^19.3.0' 'react-dom@^19.3.0' '@assistant-ui/react@^0.15.23'
pnpm add -D 'vite@^8.3.1'Build the source packages with pnpm build:all from the copied vendor/browser-worker-agent directory before starting your frontend; the exported Worker artifact is generated by that build. To run the source example inside the parent workspace too, include vendor/browser-worker-agent/examples/* in its workspace members.
For consumption outside that workspace, copy this directory outside any parent pnpm workspace and build three tarballs:
pnpm install
pnpm build:all
mkdir -p artifacts
pnpm pack --pack-destination artifacts
pnpm --dir packages/react pack --pack-destination ../../artifacts
pnpm --dir packages/ui pack --pack-destination ../../artifactsFrom your application, replace /path/to/browser-worker-agent with that directory:
pnpm add /path/to/browser-worker-agent/artifacts/pluxel-browser-worker-agent-0.1.0.tgz /path/to/browser-worker-agent/artifacts/pluxel-browser-worker-agent-react-0.1.0.tgz /path/to/browser-worker-agent/artifacts/pluxel-browser-worker-agent-ui-0.1.0.tgz
pnpm add 'capnweb@^0.12.0' 'react@^19.3.0' 'react-dom@^19.3.0' '@assistant-ui/react@^0.15.23'
pnpm add -D 'vite@^8.3.1'For /execution, install only the core tarball and Cap’n Web. Headless sessions additionally use the Vite integration below. Packing resolves workspace/catalog references into ordinary dependency versions; consumers of tarballs do not need the source catalogs.
This directory is an independent pnpm workspace with its own lockfile and native pncat dev tool. Run its maintenance commands from a standalone checkout (outside a parent pnpm workspace):
pnpm install --frozen-lockfile
pnpm catalog:add <package>
pnpm catalog:migrate
pnpm catalog:clean
pnpm install
pnpm catalog:detectpncat.config.ts selects named catalogs; pnpm-workspace.yaml owns their versions. Migration preserves peer compatibility ranges, and the existing exact pi versions must only change together with the adapter verification described below. catalog:migrate and catalog:clean leave installation to the explicit pnpm install step. catalog:detect reports uncataloged dependencies; upstream pncat does not turn findings into a failing exit code, so this is a maintenance report rather than a CI gate.
When this directory is embedded in a larger workspace, that workspace owns installation and the active catalogs. Keep the standalone workspace file and lockfile valid when changing these source manifests; independent consumers use the native pncat commands above and do not need a Pluxel CLI.
import { defineConfig } from 'vite'
import { browserWorkerAgent } from '@pluxel/browser-worker-agent/vite'
export default defineConfig({
plugins: [browserWorkerAgent()],
})Keep your existing React plugin if you use one. This optional build entry adapts pi’s browser imports; it does not load Vite into your browser runtime. Worker assets use Vite’s native Worker URL handling independently. /execution needs no library-specific plugin, alias or dependency-prebundling setting. See Vite integration details for the compatibility boundary.
The implementation pins pi-ai and pi-agent-core to 1.1.0 in the named catalogs. The browser adapter depends on specific pi module structure, so upgrading pi requires the adapter and fresh-cache/packed-consumer tests to pass together. If a recognized module no longer has the expected shape, the adapter reports its path and upgrade guidance instead of silently skipping adaptation. The manifests declare shared peer compatibility: Cap’n Web ^0.12.0, React/React DOM ^19.3.0, assistant-ui ^0.15.23, and the optional build-time Vite peer ^8.3.1. Lockfiles record the tested resolutions.
pi remains a regular implementation dependency. Shared Cap’n Web, core/React bridge and React/assistant-ui contexts are peers so the application selects one compatible runtime family. Internal UI controls remain regular dependencies; Streamdown and its plugins are bundled by the UI package. Peer declarations express compatibility; build externalization separately determines bundle contents.
From this directory in a source checkout:
pnpm install
pnpm build:all
pnpm --dir examples/local-react devOpen the URL printed by Vite. The example uses an in-memory notebook API, a real Worker/MessagePort and a deterministic pi demo model; it does not call an inference service or require a key. Its scripted replies demonstrate the integration, not natural-language model capability. Switching notebooks demonstrates separate local history/session scopes. pnpm --dir examples/local-react typecheck and pnpm --dir examples/local-react build validate the consumer; node tests/example-browser.mjs exercises it in Chromium. Source examples and test tools are not included in the runtime tarballs; the inline examples below use only public package exports.
This complete browser-side operation uses no network transport, authentication or model:
import { RpcStub, RpcTarget } from 'capnweb'
import { runJavaScript } from '@pluxel/browser-worker-agent/execution'
class LocalApi extends RpcTarget {
readValue() {
return { value: 42 }
}
}
const shared = new RpcStub(new LocalApi())
try {
const result = await runJavaScript({
code: 'return await api.readValue()',
acquireApi: () => {
const api = shared.dup()
return { api, release: () => api[Symbol.dispose]() }
},
})
console.log(result.status, result.value)
} finally {
shared[Symbol.dispose]()
}The application owns shared; each execution borrows a separate reference. The executor owns the fresh Worker, its MessagePort and the acquired lease. It calls release() exactly once, including late acquisition after cancellation, without disposing an application-owned shared connection or root reference.
Create a session in React useEffect, and dispose it in that effect’s cleanup. The session owns model requests, subscriptions and Worker executions. The example’s scopeKey is simply a local history namespace, such as a document or workspace ID; it does not represent authentication.
import { useEffect, useState } from 'react'
import { RpcStub, RpcTarget } from 'capnweb'
import { createAgentSession } from '@pluxel/browser-worker-agent'
import { AgentWorkspace } from '@pluxel/browser-worker-agent-ui'
import '@pluxel/browser-worker-agent-ui/styles.css'
class LocalApi extends RpcTarget {
readValue() {
return { value: 42 }
}
}
type Session = ReturnType<typeof createAgentSession>
function Workspace({ scopeKey }: { scopeKey: string }) {
const [session, setSession] = useState<Session | null>(null)
useEffect(() => {
const shared = new RpcStub(new LocalApi())
const next = createAgentSession({
scopeKey,
documents: [
{
id: 'api',
title: 'Local API',
version: '1',
text: 'api.readValue() returns { value: number }.',
},
],
entryDocumentId: 'api',
acquireApi: () => {
const api = shared.dup()
return { api, release: () => api[Symbol.dispose]() }
},
})
setSession(next)
return () => {
next.dispose()
shared[Symbol.dispose]()
}
}, [scopeKey])
return session ? <AgentWorkspace session={session} /> : null
}
export function App({ workspaceId = 'local-demo' }: { workspaceId?: string }) {
return (
<div style={{ height: '100dvh' }}>
<Workspace key={workspaceId} scopeKey={workspaceId} />
</div>
)
}The keyed component starts with empty React state when workspaceId changes, so it cannot render the previous workspace’s session while the next effect starts. Dispose the session before its owned root capability; each run releases its duplicate independently. React Strict Mode may run setup/cleanup twice in development; every setup above creates fresh resources. Unmounting AgentWorkspace or AgentWorkspaceProvider alone does not dispose a session created by your application.
Use a stable key for a fixed local workspace. If your application replaces the API object or another input that defines the session, also replace the keyed boundary (or explicitly hide the old session until a matching replacement exists). Authentication and remote connections are optional application integrations, not session requirements. The UI starts unconfigured and lets the user choose a model; the runnable local example uses a deterministic model instead.
For headless use, use the same local API and createAgentSession options without React. Read session.getSnapshot(), subscribe with session.subscribe(listener), configure a model with setModel(), and send with send(). Call the returned unsubscribe function and session.dispose() when your frontend owner retires. History methods include newConversation(), listHistory(), restore(), renameHistory(), archiveHistory(), exportHistory(), retrySaveHistory() and deleteHistory(). Native pi Model/Models injection supports explicit providers and deterministic local models.
createAgentSession accepts generation: { maxTokens, timeoutMs } for main conversation requests. Defaults are 4096 tokens and 60 seconds; both values must be positive safe integers. Each request clamps maxTokens to the selected model’s limit. This does not change the separate, bounded background title request.
The existing top-level timeoutMs controls JavaScript execution. Both createAgentSession and runJavaScript accept createWorker: () => Worker for a host-owned asset loader. Return a new module Worker running this version’s exported /worker entry on each call. The executor owns termination, including cancellation and failure; the application continues to own its root capability and any optional shared RPC connection. The default factory remains suitable for the verified Vite build path. Custom factories allow other deployment layouts without replacing the execution protocol.
import { runJavaScript } from '@pluxel/browser-worker-agent/execution'
const result = await runJavaScript({
code: 'return await api.readValue()',
acquireApi: () => {
const api = shared.dup()
return { api, release: () => api[Symbol.dispose]() }
},
// workerAssetUrl is resolved/served by your build system from the /worker export.
createWorker: () => new Worker(workerAssetUrl, { type: 'module' }),
timeoutMs: 15_000,
})The shared capability can be local, as above. Custom Worker creation changes asset loading, not API authority. Stopping a Worker does not roll back a call already dispatched to the page API.
Pass components to replace only presentation while retaining the default runtime, grouping, errors, history and composer. Define component types outside the rendering function so streamed updates do not remount them.
Welcomereceives{ configured, onConfigure }; useonConfigureto open the built-in model settings.Textreads assistant-ui’s native message-part context and renders assistant text/reasoning. A replacement owns its rendering and URL/HTML handling.Toolreceives nativeToolCallMessagePartProps. A registered assistant-ui tool UI still takes precedence. Rendering a result does not execute it.
theme accepts CSS colors for background, foreground, primary, primary-foreground, muted, muted-foreground, border and destructive. These tokens apply to both the chat and its portalled dialogs/popovers, independently per instance. className controls the workspace layout.
import { AgentWorkspace, type AgentWorkspaceWelcomeProps } from '@pluxel/browser-worker-agent-ui'
import '@pluxel/browser-worker-agent-ui/styles.css'
function Welcome({ configured, onConfigure }: AgentWorkspaceWelcomeProps) {
return (
<div>
<h2>Project assistant</h2>
{!configured && <button onClick={onConfigure}>Connect a model</button>}
</div>
)
}
;<AgentWorkspace
session={session}
components={{ Welcome }}
theme={{ primary: '#2563eb', 'primary-foreground': '#ffffff' }}
/>For a completely different design system, consume the React bridge directly and compose native assistant-ui primitives. The default UI is not a prerequisite for using the session.
| Entry | Responsibility | UI requirements |
|---|---|---|
@pluxel/browser-worker-agent |
pi session, tools, Worker, local history | No React or HeroUI |
@pluxel/browser-worker-agent-react |
AgentWorkspaceProvider, useAgentWorkspace, native assistant-ui runtime and drafts |
React and assistant-ui; no CSS or HeroUI |
@pluxel/browser-worker-agent-ui |
Ready-made AgentWorkspace, official chat/list components and model controls |
React and assistant-ui |
@pluxel/browser-worker-agent-ui/styles.css |
Compiled registry utilities and scoped default UI tokens | Explicit consumer import |
Use the UI-neutral provider with your project's existing assistant-ui Thread:
import { AgentWorkspaceProvider } from '@pluxel/browser-worker-agent-react'
import { Thread } from './components/assistant-ui/thread'
// The provider installs AssistantRuntimeProvider; do not create a second runtime.
function Chat() {
return (
<AgentWorkspaceProvider session={session}>
<Thread />
</AgentWorkspaceProvider>
)
}useAgentWorkspace() exposes session, snapshot, projected messages, native runtime and history. Native Thread, Composer, Message and ThreadList primitives work inside the provider with any UI library. The history controller exposes loading/errors, management actions and intent; a new-thread request during execution or failed storage sets intent.kind === 'new'. A custom view must show its own confirmation before calling session.newConversation({ discardUnsaved }) through history.perform, then clear the intent. Removing the provider retires display state; the host still disposes its session. Switching the provider's session resets drafts and consumer overlays together. This entry imports no library stylesheet or HeroUI dependency.
An unconfigured workspace starts with an inline connection action, without opening a modal or preselecting OpenAI. The input area contains the message editor and official ModelSelector, optional references and send/stop controls. Context estimates, the complete token count/limit and progress remain visible in the header: beside the title on wide screens and on its second row on narrow screens. The header also groups state and history controls. New conversation is the first action in the conversation list, above search, in both the collapsible desktop sidebar and narrow-screen Sheet. Model changes preserve the draft and caret and return focus to the composer. The picker prefers the latest online-discovered models for the exact current provider, protocol, endpoint, environment and key; otherwise it uses the compatible reference catalog. Custom and catalog-unknown online models can switch within that connection. Other connections and externally supplied credentials open the settings dialog. Model selection is disabled during execution. Official shadcn/Radix Command, Select, Input and Dialog components supply the fields, searchable lists and settings dialog; small screens use a single-column form with internal scrolling.
Conversation selection and its transcript share the session ID through assistant-ui's ExternalStoreThreadListAdapter. The official ThreadList row is 32px high and shows only its title and a native more menu for rename, archive/unarchive, JSON export and confirmed deletion. Inline rename supports Enter to save, Escape to cancel and blur to save; a failure retains the edit. Native list and menu primitives own keyboard focus. Search still matches titles and bounded recent-message previews; previews, timestamps and counts are not rendered as subtitles. It renders 50 rows at a time with an explicit load-more action. Manual management and restoration do not send model requests or execute tools. Restoring archived history retains its archived state; users can unarchive explicitly. Each visited saved conversation retains its unsent composer draft in workspace memory. Replacing the host session clears these drafts and overlays.
After the first turn completes successfully, the current native model summarizes a short title in the user's language. This is one independent background request with no tools, only bounded first-user and final-assistant text, a small output budget and a deadline. It does not enter the transcript or hold up sending. Failures retain the first-user-text fallback; manual names win over late model results. Sending again, switching conversations/models, deleting, stopping or disposing cancels the pending request. Generated and manual titles survive later transcript saves. Hosts can set createAgentSession({ titleGeneration: false, ... }) to avoid this extra request.
The header shows the selected title, running state, actual local-save state and a conservative context estimate with its limit and progress, clearly distinguished from exact tokenizer measurements. Conversation information groups the update time of the last successfully persisted transcript version, user-turn/execution counts and local-history/backup details. The list and input area omit repeated persistent notes; routine state remains in the header and messages use compact spacing. Saving failures retain the current transcript, offer retry/export, and block switching away until recovery or explicit confirmation to discard unsaved content. Starting a new conversation while running requires confirming that execution will stop; already dispatched business effects still require the host's recovery controls.
The chat presentation adapts assistant-ui's official Thread, ThreadList, ToolGroup, Reasoning, ModelSelector and ComposerTriggerPopover registry sources, preserving their default component structure and native interactions. Source fingerprints, supported adaptations and MIT attribution are recorded in THIRD_PARTY_NOTICES.md, shipped with the UI package (source path: packages/ui/THIRD_PARTY_NOTICES.md). Official shadcn/Radix components supply buttons, fields, alerts, menus and dialogs throughout this UI. Handwritten CSS handles host geometry and overflow; the custom Markdown component map, Prism styling and duplicate clipboard timers are removed.
@assistant-ui/react-streamdown's StreamdownTextPrimitive reads the active message part and defers native block rendering. Streamdown's code and CJK plugins provide highlighting, standard code/table copy and download controls, and streaming Markdown. Raw HTML is skipped before parsing; allowed URL protocols are http:, https:, irc:, ircs:, mailto: and xmpp:, with ordinary relative links retained and data images disabled. Code blocks use a 24rem scroll limit without line numbers. Tools pass raw code or JSON to the public block slot and native CodeBlock components, so embedded fences and HTML remain literal text, without constructing Markdown wrappers. Display and copying never run snippets. Execution logs are read-only disclosures; the host owns business receipts and recovery UI.
One user turn is displayed as one assistant message. Native MessagePrimitive.GroupedParts groups adjacent intermediate prose, reasoning, tool calls and results into process disclosures, expanded while running and automatically collapsed when the turn settles. The official Reasoning element previews streamed thoughts, follows their latest text until the reader scrolls up, and gives manual disclosure changes priority. The final tool-free step's text stays visible; the public Streamdown CodeBlockCopyButton receives only that answer, with native copied-state/timers and visible failure feedback. Users can reopen the process; stopped, truncated and failed turns keep a notice outside it, including after history restoration. The display ID stays stable across tool continuations and history restoration. This projection preserves the raw pi messages and their status. The thread and composer fill the available host width; the host chooses the surrounding page layout.
During a run the composer remains editable, while Enter does not start a concurrent request. Stop preserves that draft. Stream updates are coalesced; terminal state and cancellation publish immediately, and buffered deltas periodically yield to browser input. Settled turns, decoded tool results and message sizes are reused instead of reprocessing the whole history. Code blocks above 8,000 characters remain complete and copyable as plain text, avoiding a large syntax-token DOM.
Hosts can supply optional referenceSources to the React component. assistant-ui's native trigger popover handles searching, keyboard selection and IME; selecting a reference inserts host-provided text without sending a message or executing a tool.
import type { WorkspaceReferenceSource } from '@pluxel/browser-worker-agent-ui'
const referenceSources: WorkspaceReferenceSource[] = [
{
trigger: '@',
label: 'Resources',
items: [
{
id: 'resource:alpha',
label: 'Alpha',
description: 'Resource ID: alpha',
insertText: 'Alpha (resourceId="alpha")',
},
],
},
]
// Render <AgentWorkspace session={session} referenceSources={referenceSources} />.Each source can also provide isLoading, error and onRefresh. An error hides selectable items. The host owns resource lookup, unique IDs, insertion text, freshness and scope isolation; changing the session clears the prior composer and popovers. References are data for the model, with no additional authority. The package does not interpret application resource types or grant access.
The settings form lists the 42 native providers in the tested pi catalog. Select a provider, search its chat model catalog, and enter its API key or supported inference token. Native model metadata supplies the protocol, endpoint, context window and compatibility settings. This is a reference catalog, not a list of account entitlements. After entering connection details, use 在线获取模型 to query the selected endpoint: OpenAI-compatible Responses/Chat Completions use /models under the configured API base, and Anthropic uses its paginated /v1/models API. Results are searchable; manual model IDs remain available when discovery is unsupported or blocked by CORS. Unknown models require an explicit protocol, endpoint and context window (the form offers a conservative 32000 default). Listing a model does not prove tool or protocol support. The reference catalog follows the locked pi version. New custom connections default to Responses; existing programmatic settings without an API retain Chat Completions compatibility. Native models retain the API defined by their provider, except DeepSeek and global Moonshot K3, whose pinned Chat Completions factories are composed with pi’s native Responses adapter. Following the DeepSeek Responses contract, both current DeepSeek models use /responses; system instructions remain system because DeepSeek treats developer as user content. This stateless API replays local transcript and tool results; it does not rely on stored responses or previous_response_id. Following the Kimi Responses contract, only global Moonshot kimi-k3 defaults to https://api.moonshot.ai/v1/responses; Kimi treats developer as a system instruction. Its reasoning summaries are replayed after tool results, with the server's default reasoning effort. Older Moonshot models and the separate China and Kimi Coding providers retain their native protocols. Explicitly injected pi models keep their supplied API and dispatch, and custom Chat Completions connections remain supported. The workspace uses native provider factories and Models.streamSimple(), without creating another provider runtime or business tool schema.
39 providers have a browser API-key/token chat path. Amazon Bedrock is blocked because its pi implementation requires Node; OpenAI Codex is blocked because it only declares OAuth; TypeSafe is blocked because its models are classifiers rather than chat models. These entries remain visible with the reason they cannot run. Native OAuth login and refresh are not provided by this workspace, and it does not add a backend model proxy.
Some providers need more than a key:
| Provider | Browser configuration |
|---|---|
| Azure OpenAI | Required Azure Endpoint (AZURE_OPENAI_BASE_URL); optional API Version (AZURE_OPENAI_API_VERSION, default v1) and deployment mapping (AZURE_OPENAI_DEPLOYMENT_NAME_MAP, such as gpt-4o-mini=my-deployment). Multiple mappings use commas; absent a mapping, the deployment name is the model ID. |
| Cloudflare Workers AI | Key/token and CLOUDFLARE_ACCOUNT_ID. |
| Cloudflare AI Gateway | Key/token, CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_GATEWAY_ID. Its native auth uses the gateway-specific header. |
| Google Vertex AI | Explicit Google Cloud API key. ADC, project/location authentication and service-account files are unavailable in the browser. |
| GitHub Copilot | An already valid Copilot inference token. The form does not exchange a GitHub PAT for a Copilot token, acquire one through OAuth or refresh it. |
| Radius | Radius API key, using the native pi-messages protocol and default Radius catalog. A custom Radius endpoint can use the custom protocol below. |
Custom providers accept a base URL, model ID, key and context window with one of eight native pi APIs:
| API | Protocol |
|---|---|
openai-completions |
OpenAI Chat Completions |
openai-responses |
OpenAI Responses |
anthropic-messages |
Anthropic Messages |
google-generative-ai |
Google Gemini |
google-vertex |
Google Vertex AI with an API key |
azure-openai-responses |
Azure OpenAI Responses; Base URL is the endpoint, with optional version/deployment fields |
mistral-conversations |
Mistral Conversations |
pi-messages |
pi Messages / Radius |
For programmatic settings, call setModel() while the session is idle:
session.setModel({ provider: 'openai', model: 'gpt-4o-mini', apiKey: userKey })
session.setModel({
provider: 'custom',
api: 'anthropic-messages',
baseUrl: 'https://models.example/anthropic',
model: 'my-model',
apiKey: customKey,
contextWindow: 32_000,
})Native pi Model and Models injection through createAgentSession({ model, models, apiKey, ... }) remains available, including for controlled providers. An injected collection can resolve its own credentials when apiKey is omitted; that credential store remains host-owned and is not modified or cleared by the library. Settings use a separate, session-owned key. Custom endpoints must implement the selected protocol; Google adapters do not support a custom fetch wrapper.
By default keys remain in session memory and are cleared on disposal or host scope replacement. A host can opt into tab persistence with modelStorage: sessionStorage (or a namespaced adapter implementing getItem/setItem/removeItem). Only the current connection is stored, under the session scope; it survives navigation/reload, while conversations and capabilities remain separately owned. This includes the API key and is browser storage, not an encrypted vault. clearModel() removes the saved connection and active key. Storage failures are visible in the snapshot and UI; the active connection can still work in memory. Reopening settings leaves the password field blank; a blank key reuses the existing key only when the provider, endpoint and provider configuration are unchanged (and the custom API also matches). Changing that credential scope requires a new key. Model-setting keys are excluded from snapshots and history; IndexedDB contains messages and execution records. Loading history restores display and permits an explicit next user turn, without replaying tools or retrieving keys.
The model endpoint must allow browser CORS and authorize the selected model. No live provider was executed for this implementation, and CORS or account access has not been verified for each service. Controlled providers establish the browser integration path, not universal service availability.
The agent has exactly three tools:
searchDocs: searches document IDs, titles and text; returns up to five 500-character excerpts. An exact document ID selects that document. Multi-term queries prefer the documents covering the most terms, and excerpts start at the most relevant line.readDoc: retrieves up to 60 lines or 6,000 characters. Optional line ranges are inclusive and one-based. Anextposition containsstartLineand a zero-basedstartCharacteroffset; pass them back withoutendLineto continue exactly, including a partial line or its newline separator. Offsets use JavaScript string indexing.truncatedindicates that the requested range exceeded the page budget;nextcan also follow a completed explicit range when the document has more content.runJavaScript: an async JavaScript function body withapiandprint(value); await RPC calls and return ordinary JSON-compatible data. Model feedback containsstatus,outputs, optionalvalue/errorandtruncated; it does not repeat the submitted source or bookkeeping. Full code and timestamps remain in execution history.
Search excerpts are navigation aids, not complete declarations. Hosts should provide small method/type documents and link the exact related document IDs, rather than repeatedly inlining a whole API catalog. Optional entryDocumentId names a small guide to read first for host API tasks; it must belong to the supplied collection. Only its ID enters the system prompt; constructing a session never runs tools or preloads document text. Invalid queries, unknown IDs and malformed ranges throw DocumentError with a stable code, a short recovery hint and the relevant bounds, without returning the full catalog.
Each runJavaScript call owns a fresh Worker, MessagePort session and API lease. Return, error, stop and timeout retire them and release all run-owned child references; short scripts need no disposal boilerplate. Read once with native promise pipelining (return await api.settings().featuresDto()), or reuse an awaited capability with const. For an earlier lexical release, prefer using child = await api.feature(); the root api belongs to the executor. Await RPC results and return ordinary data. A return with outstanding RPCs is an error; execution failure ends the turn without repeating the script. Dispatched writes may still complete after retirement.
Stopping aborts the model request and terminates the Worker, including infinite CPU loops. It releases that execution's references and preserves prior output. Already dispatched effects may still complete; the library cannot roll back or recover business writes. The host's separate operation records remain authoritative.
Code is limited to 64,000 characters; printed output to 32,000 characters/64 entries; return values to 16,000 characters. Truncation is explicit. The receiver also retires a Worker that exceeds the normal 66-packet feedback budget, including invalid or directly generated postMessage packets, so output storage limits cannot be bypassed by flooding the UI queue. The default timeout is 60 seconds, configurable up to 300 seconds. Model input and responses are bounded, and nearing the configured context window prompts a new conversation. Errors distinguish syntax, RPC, execution, timeout and stop outcomes.
pnpm build emits the core ESM entries, declarations and Worker asset. pnpm build:all additionally builds the React bridge and ready-made UI, including ui.css and their declarations. The React and UI packages require the core package, React, React DOM and assistant-ui as peers; the UI also requires the React bridge. Shared peers and regular runtime dependencies remain external in library builds. The UI ships its adopted shadcn controls, imports Radix as a regular external dependency, and bundles @assistant-ui/react-streamdown, Streamdown and the code/CJK plugins. Consumers use this one built renderer without plugin peer overrides or separately installed renderer versions. None of the packages depends on HeroUI. The core entry does not import React or any UI library. No entry imports host source paths or business components.
Import the ready-made UI and its compiled stylesheet explicitly:
import { AgentWorkspace } from '@pluxel/browser-worker-agent-ui'
import '@pluxel/browser-worker-agent-ui/styles.css'The library compiles registry utilities and shadcn default semantic tokens within .aui-root. A React-owned scope wrapper and portal container keep dialogs, menus, references, popovers and native Streamdown table fullscreen views within the same scope; containers retire with their UI owner. Consumers do not need HeroUI, a Tailwind plugin or source scanning to style this view. Scoped light/dark tokens keep the chat independent of the host dashboard theme; no global preflight or global button/input overrides are emitted.
Each package’s packed exports refer only to its own dist; development source conditions are removed by publishConfig. Workspace development resolves @pluxel/browser-worker-agent-ui and @pluxel/browser-worker-agent-ui/styles.css to packages/ui/src, avoiding stale built styles overriding live UI changes.
The core build uses Rolldown directly: main-thread dependencies stay external, while the Worker is a separate, self-contained browser bundle. Its Cap’n Web runtime belongs to that separate realm; the main thread shares the host's peer runtime. A standard new Worker(new URL('./execution.worker.js', import.meta.url), { type: 'module' }) reference remains in the library output. Vite resolves the corresponding TypeScript file during workspace development and handles the published JavaScript asset in consumers. There is no generated-code rewrite tied to Vite internals. React and UI retain Vite builds for their presentation assets.
The Worker-only /execution entry needs no library-specific plugin, alias or optimizeDeps configuration. Full Agent consumers using pi should enable the /vite integration below. The independent packed core test executes real Worker RPC in both Vite development and a production build deployed under /agent/. Other bundlers must support this standard Worker URL pattern, or supply createWorker with the exported /worker artifact. Their integration is not covered by the Vite tests.
Generated code is compiled only inside the Worker. A deployment with CSP must allow dynamic compilation on the Worker response while keeping the main document's script-src restricted; do not enable main-page unsafe-eval for this feature. The pack smoke serves a restrictive main-page CSP and a separate Worker-only policy. A Worker provides termination and a separate thread, without a hard memory quota or an additional application permission boundary.
The Vite integration replaces pi-ai’s provider environment probe only in browser environments. Browser model requests use explicit scoped credentials and environment values; no server environment or filesystem is exposed and no Node polyfill is installed. Server builds retain pi’s original implementation.
IndexedDB stores scope-partitioned plain JSON messages, complete execution records, titles, previews and archive metadata. It does not store connection settings, keys or RPC capabilities, and the package has no cross-device history synchronization. The list projects one cursor record at a time; it does not aggregate all full transcripts with getAll(). Save state becomes saved only after its transaction completes. Coalesced snapshots preserve explicitly edited titles and archive state, and a retired deletion cannot be recreated by that owner's delayed save or disposal.
listHistory() returns bounded previews and counts; messageCount counts user turns, not the internal tool/assistant message count. renameHistory(id, title) accepts 1–80 characters. archiveHistory(id, boolean) changes metadata without affecting business data. exportHistory(id) returns { version, exportedAt, conversation } JSON without connection settings or scopeKey; the active unsaved transcript can also be exported if browser storage fails. The React UI downloads it as a JSON file. Deletion removes only that local history record and opens an empty conversation if it was selected; independent host operation journals remain intact. Management failures reject and remain visible. Pending operations block new model submissions until the transcript and selected ID agree.
newConversation() and restore(id) wait for queued persistence and retain unsaved content on failure. Headless hosts can explicitly pass { discardUnsaved: true } after their own confirmation. retrySaveHistory() retries the retained snapshot. None of these operations restore credentials, replay recorded tools or reconstruct live capabilities.
Tabs in the same browser share IndexedDB. Explicit title/archive edits are preserved atomically, but concurrent transcript writes remain last-writer-wins; this is not live cross-tab synchronization. The list refreshes when the window regains focus or the user requests it.
pnpm test
pnpm build:all
pnpm test:browser
pnpm test:providers
pnpm test:packThe browser tests use Chromium, native pi models and controlled streaming providers. The pack smoke exercises actual Workers/MessagePorts, history and UI behavior. Omni-specific acceptance remains in the consumer repository under host/web/tests/agent-workspace-browser.mjs. The pack smoke installs a tarball into an independent temporary Vite project, typechecks, builds and runs it under CSP. It does not publish a package. These controlled providers prove the integration path; they do not establish compatibility with an untested live model service.
Full Agent consumers using Vite enable the optional build integration:
import { defineConfig } from 'vite'
import { browserWorkerAgent } from '@pluxel/browser-worker-agent/vite'
export default defineConfig({
plugins: [browserWorkerAgent()],
})/vite uses the optional peer described in Tested dependency boundary. It is a build-time entry;
importing the browser runtime does not load Vite. The plugin applies the pinned pi version’s
four intentional lazy-import hints during browser dependency prebundling and
normal transforms, and supplies a scoped browser implementation of pi’s provider
environment lookup. It preserves the lazy boundary for Node-only Bedrock and OAuth
implementations without exposing those capabilities to browser code. It neither
installs Node polyfills nor filters warnings globally. Server environments remain
unchanged. Consumers do not need a package-manager patch or custom aliases.
Worker assets use Vite’s native Worker URL handling independently of this plugin.
Consumers importing only /execution can omit it. Other build tools may use the
Worker artifact directly; adapting pi’s browser dependency graph outside Vite is
not covered by this integration. This entry is a Vite plugin, not a general
Rolldown plugin.
test:browser first runs tests/browser-imports.mjs against a fresh Vite cache
and Chromium. It checks that all 42 catalog providers load without dynamic-import
analysis warnings, browser errors or requests to Node-only implementations.
Requires Node 24+ and pnpm 11. Copy or check out this directory outside any parent workspace, then run pnpm install, pnpm exec playwright install chromium and pnpm verify. The local pnpm-workspace.yaml defines all named catalogs used by these packages; dependency versions, lockfile and compiler settings are self-contained. Packing resolves catalog references into publishable dependency versions. The React and UI packages live in packages/react and packages/ui; use pnpm build:all to build the three packages in dependency order. The core package has no React or presentation dependencies; @pluxel/browser-worker-agent-react and @pluxel/browser-worker-agent-ui require React, React DOM and assistant-ui at the declared versions.
The package name describes the browser execution capability. AgentWorkspace remains the presentation component; createAgentSession owns the headless conversation lifecycle. The frontend supplies API documents and capabilities. Applications that add authentication, business writes or cache integration own those optional concerns; none is required by this library. The default UI currently uses Chinese labels; a localization API is not provided.