Skip to content

React API ​

The complete React surface: provider setup, declaration hooks, components, and the shared option types they use. Every signature below is the React form.

This page lists only @plingjs/react entry points, plus the shared-package types used with them.

API overview · Shared package API

PackagePeer dependenciesVersion
@plingjs/reactreact >=180.1.0-alpha.2

The current package version is 0.1.0-alpha.2; stability is preview. This is a pre-1.0 alpha, so a minor release may still change the API.

Minimal example ​

ts
import { createPling, PlingProvider, AgentDock } from "@plingjs/react";

const pling = createPling({ namespace: "todo" });

<PlingProvider pling={pling}>
  <AgentDock />
</PlingProvider>;

Entry and lifecycle ​

Create the application runtime, install the adapter, and release its observers.

APIKindReference
createPlingFunctionReference
PlingProviderComponentReference
usePlingFunctionReference
usePlingUiFunctionReference
PlingElementInterfaceReference
pling.destroyMethodReference

createPling ​

Creates the application-level Pling instance and returns the adapter-specific runtime object.

Imports

@plingjs/react

Signature

ts
// React
createPling(options?: PlingOptions): PlingElement;
createPling(registry: Registry | undefined, options?: PlingOptions): PlingElement;

Parameters and options

ParameterTypeRequiredDefaultDescription
ui.locale"en-US" | "zh-CN" | "auto" | stringNoen-USLanguage used by the built-in assistant UI. "auto" follows the browser language.
ui.theme"light" | "dark" | "auto" | PlingThemeOverridesNolightTheme for the built-in surfaces. An object can override tokens or choose a mode.
ui.theme.mode"light" | "dark" | "auto"NolightExplicit mode when the theme is an object. "auto" follows the operating-system preference.
ui.theme.tokensPartial<PlingThemeTokens>No—Overrides individual design tokens such as colours, radii, shadows, and font families. Keys not supplied keep the selected light or dark defaults.
ui.messagesPlingCatalogOverridesNo—Adds or replaces message catalog entries for one or more locales.
ui.messages.<locale>Partial<Record<PlingMessageKey, string>>No—Message overrides for one BCP 47 locale. Missing keys fall back to the built-in catalog.
ui.classNamesPlingClassNamesNo—Extra class names applied to the built-in chat, dock, launcher, and panel.
ui.classNames.dockstringNo—Extra class for the dock shell.
ui.classNames.panelstringNo—Extra class for the panel shell.
ui.classNames.launcherstringNo—Extra class for the launcher button.
ui.classNames.chatstringNo—Extra class for the chat surface.
onWarn(message: string) => voidNoconsole.warnReceives development warnings and declaration diagnostics. Defaults to console.warn.
registryRegistryNo—Uses an existing action registry instead of creating one. Do not combine it with shared.
sharedPlingPageNo—Joins a page runtime shared by several framework islands. registry and scopes are then owned by that page runtime.
namespacestringNo—Prefixes action and record ids for this adapter instance, for example add becomes todo/add.
scopesScopeControllerOptionsNo—Overrides visibility and hit-testing behavior. Intended for tests and unusual rendering hosts.
agentAgentSetupNo—Wires the model, hooks, confirmation, continuity, and observability used by built-in assistant surfaces.
deriveboolean | DeriveOptionsNofalseEnables optional L1 derivation from native clickable elements. Disabled by default; derived actions are marked as guesses.
presenceboolean | PresenceOptionsNotrueControls target highlighting while the agent operates the page.
revealSensitivebooleanNotrueRestores sensitive-value tokens to their real values in the rendered chat only. Model requests and storage keep the tokens.

Returns

The adapter instance. Vue 3 and React return PlingElement; Vue 2.7 and Vanilla return VanillaPling.

Defaults

  • No declaration means no action; derive is off by default.
  • Presence is on by default.
  • revealSensitive is true by default.

Example 1 · React application setup

tsx
import { createRoot } from "react-dom/client";
import { createPling, PlingProvider } from "@plingjs/react";

const pling = createPling({ namespace: "todo" });

createRoot(document.getElementById("root")!).render(
  <PlingProvider pling={pling}>
    <App />
  </PlingProvider>,
);

Example 2 · Route model calls through a same-origin gateway

tsx
const pling = createPling({
  agent: {
    config: {
      baseUrl: "/llm/v1",
      model: "gpt-4.1-mini",
    },
    trace: true,
  },
});

Canonical reference

Open the corresponding reference

PlingProvider ​

Publishes a Pling instance to the React tree. Every React declaration hook reads from this provider.

Imports

@plingjs/react

Signature

ts
// React
PlingProvider({ pling, children }: PlingProviderProps): ReactElement

Parameters and options

ParameterTypeRequiredDefaultDescription
plingPlingElementYes—Application runtime returned by createPling.
childrenReactNodeNo—React subtree that can call Pling hooks and mount assistant components.

Example 1 · Scope the runtime to the React tree

tsx
const pling = createPling();

root.render(
  <PlingProvider pling={pling}>
    <App />
  </PlingProvider>,
);

Canonical reference

Open the corresponding reference

usePling ​

Reads the nearest Pling instance from the framework tree.

Imports

@plingjs/react

Signature

ts
// React
usePling(): PlingElement

Parameters

None.

Example 1 · Read the provider runtime

tsx
const pling = usePling();

const report = pling.inspectCoverage();

Canonical reference

Open the corresponding reference

usePlingUi ​

Subscribes a React component to the shared locale, theme, CSS variables, and message snapshot.

Imports

@plingjs/react

Signature

ts
// React
usePlingUi(): PlingUiSnapshot

Parameters

None.

Example 1 · Re-render when locale or theme changes

tsx
function Toolbar() {
  const ui = usePlingUi();
  return <span>{ui.locale} · {ui.resolvedTheme}</span>;
}

Canonical reference

Open the corresponding reference

PlingElement ​

The Vue 3 and React application runtime: registry, UI controller, page tracker, task routing, coverage, and cleanup.

Imports

@plingjs/react

Signature

ts
// React
interface PlingElement {
  ui: PlingUiController;
  registry: Registry;
  feedback: FeedbackCollector;
  scopes: ScopeController;
  setActiveScopes(scopes: Iterable<string>): void;
  presence: PresenceController | null;
  derived(): DeriveController | null;
  task: PlingTaskController;
  ask(prompt: string, options?: PlingAskOptions): Promise<void>;
  inspectCoverage(root?: Element | null): CoverageReport;
  destroy(): void;
  warn(message: string): void;
  agent?: AgentSetup;
  revealSensitive: boolean;
}

Parameters and options

ParameterTypeRequiredDefaultDescription
uiPlingUiControllerNo—Locale, theme, catalog, and CSS-variable controller.
registryRegistryNo—Shared action, record, state, and feedback registry.
feedbackFeedbackCollectorNo—Page-level feedback collector shared by the application.
scopesScopeControllerNo—Region visibility, viewport, and occlusion controller.
setActiveScopes(scopes: Iterable<string>) => voidNo—Manually replaces the active region set.
presencePresenceController | nullNo—Target highlighting controller; null when presence is disabled.
derived() => DeriveController | nullNo—Returns the optional L1 deriver.
taskPlingTaskControllerNo—Task routing controller used by built-in surfaces.
ask(prompt: string, options?: PlingAskOptions) => Promise<void>No—Routes a human-authored task to a mounted assistant surface.
inspectCoverage(root?: Element | null) => CoverageReportNo—Scans a root element for actionable controls without declarations.
destroy() => voidNo—Stops observers and releases declarations owned by this runtime.
warn(message: string) => voidNo—Emits a framework warning through the configured channel.
agentAgentSetupNo—Application-level assistant wiring, when supplied to createPling.
revealSensitivebooleanNo—Whether the rendered chat restores sensitive tokens.

Example 1 · Inspect what the page exposes

tsx
const pling = createPling();

console.table(pling.inspectCoverage().targets);

Canonical reference

Open the corresponding reference

pling.destroy ​

Stops observers, derived actions, scopes, presence, UI subscriptions, and mounted assistant surfaces.

Imports

@plingjs/react

Signature

ts
// React
pling.destroy(): void

Parameters

None.

Example 1 · Release the runtime

tsx
useEffect(() => () => pling.destroy(), []);

Canonical reference

Open the corresponding reference

Page declarations ​

Declare actions, records, regions, state, feedback, task entrances, and sensitive values.

APIKindReference
Element actionDeclarationReference
Function-level actionDeclarationReference
RegionDeclarationReference
RecordDeclarationReference
Read-only stateDeclarationReference
exposePlingStateFunctionReference
Page feedbackDeclarationReference
Task entranceDeclarationReference
Guide targetDeclarationReference
sensitiveFunctionReference

Element action ​

Declares what a control does. The description is the model's only explanation; execution still goes through availability, approval, and expectations.

Imports

@plingjs/react

Signature

ts
// React
usePlingTool<T extends Element = HTMLElement>(options: PlingToolOptions): RefCallback<T>

Parameters and options

ParameterTypeRequiredDefaultDescription
optionsPlingToolOptionsYes—The same fields as ToolOptions; the hook returns a ref callback to attach to the element.

Example 1 · Declare an element action

tsx
const addRef = usePlingTool({
  id: "add",
  desc: "添加一条待办",
  kind: "write",
  run: () => add(),
});

return <button ref={addRef}>添加</button>;

Canonical reference

Open the corresponding reference

Function-level action ​

Registers a business operation that has no dedicated DOM control.

Imports

@plingjs/react

Signature

ts
// React
useAgentTool(options: AgentToolOptions): void

Parameters and options

ParameterTypeRequiredDefaultDescription
optionsAgentToolOptionsYes—Id, description, risk, availability, parameters, expectation, and implementation.

Example 1 · Register an application action

tsx
useAgentTool({
  id: "clear_completed",
  desc: "清除所有已完成待办",
  kind: "write",
  run: () => clearCompleted(),
});

Canonical reference

Open the corresponding reference

Region ​

Declares a structural region and its reachability. Regions explain context; they are not permission boundaries.

Imports

@plingjs/react

Signature

ts
// React
usePlingScope<T extends Element = HTMLElement>(options: PlingScopeOptions): RefCallback<T>

Parameters and options

ParameterTypeRequiredDefaultDescription
optionsPlingScopeOptionsYes—Region id and optional model-facing metadata.

Example 1 · Describe a list region

tsx
const scopeRef = usePlingScope({ id: "todos", label: "待办列表", role: "list" });

return <section ref={scopeRef}>...</section>;

Canonical reference

Open the corresponding reference

Record ​

Gives one row a stable identity and a bounded set of readable fields. Records are read-only.

Imports

@plingjs/react

Signature

ts
// React
usePlingRecord<T extends Element = HTMLElement>(value: RecordValue | null | undefined): RefCallback<T>

Parameters and options

ParameterTypeRequiredDefaultDescription
valueRecordValue | null | undefinedYes—The row value. The hook returns a ref callback for the row element.

Example 1 · Expose a row

tsx
function TodoRow({ todo }: { todo: Todo }) {
  const recordRef = usePlingRecord({ data: todo, fields: { text: todo.text, done: todo.done } });
  return <li ref={recordRef}>{todo.text}</li>;
}

Canonical reference

Open the corresponding reference

Read-only state ​

Exposes a derived view of current UI state. State has no setter; writes must be declared as actions.

Imports

@plingjs/react

Signature

ts
// React
usePlingState(key: string, source: PlingStateSource, options?: PlingStateOptions | string): () => void

Parameters and options

ParameterTypeRequiredDefaultDescription
keystringYes—Stable state-view name used in page context and diagnostics.
sourceunknown | (() => unknown) | Ref<unknown> | Record<string, unknown>Yes—A value, ref, or read function. Prefer a function so the snapshot reflects current state.
optionsStateOptions | stringNo—A description object or a description string. Name the view and explain what it means.

Example 1 · Expose filters and counts

tsx
usePlingState("todo", () => ({
  filter,
  total: todos.length,
  remaining: todos.filter((todo) => !todo.done).length,
}), { description: "当前筛选与未完成数量" });

Canonical reference

Open the corresponding reference

exposePlingState ​

Registers a read-only state view outside the React component tree. It returns an unregister function.

Imports

@plingjs/react

Signature

ts
// React
exposePlingState(pling: Pick<PlingElement, "registry">, key: string, source: PlingStateSource, options?: PlingStateOptions | string): () => void

Parameters and options

ParameterTypeRequiredDefaultDescription
plingPick<PlingElement, "registry">Yes—Runtime or any object with the same registry property.
keystringYes—Stable state-view name.
sourcePlingStateSourceYes—Value or read function evaluated for each snapshot.
optionsPlingStateOptions | stringNo—Model-facing description.

Example 1 · Expose state outside React

tsx
const off = exposePlingState(pling, "filters", () => ({
  status: store.getState().status,
  count: store.getState().visible.length,
}), { description: "列表筛选与可见条数" });

Canonical reference

Open the corresponding reference

Page feedback ​

Publishes user-visible feedback or a short page-level explanation without turning it into an action.

Imports

@plingjs/react

Signature

ts
// React
usePlingFeedback(value: PlingFeedbackInput, options?: PlingFeedbackOptions): void

Parameters and options

ParameterTypeRequiredDefaultDescription
valuePlingFeedbackInputYes—Feedback value or array of values.
optionsPlingFeedbackOptionsNo—Fallback id and scope for the feedback declarations.

Example 1 · Expose a form error

tsx
usePlingFeedback(error ? { message: error, field: "email", severity: "error" } : null);

Canonical reference

Open the corresponding reference

Task entrance ​

Routes a human-authored instruction to the mounted assistant. It is not exposed to the model as an action.

Imports

@plingjs/react

Signature

ts
// React
pling.ask(prompt: string, options?: PlingAskOptions): Promise<void>

Parameters and options

ParameterTypeRequiredDefaultDescription
promptstringYes—Natural-language task sent to the mounted assistant surface.
options.surfacestringNo—Named surface id. Omit it when only one surface is mounted.
options.sourceElementNo—Element that triggered the task, for custom hosts and diagnostics.

Example 1 · Route a human task

tsx
await pling.ask("整理今天的待办并标出最紧急的一项", { surface: "dock" });

Canonical reference

Open the corresponding reference

Guide target ​

Highlights a non-action target while a person completes a handoff step.

Imports

@plingjs/react

Signature

ts
// React
usePlingGuideTarget<T extends Element = HTMLElement>(id: string): RefCallback<T>

Parameters and options

ParameterTypeRequiredDefaultDescription
idstringYes—Guide target id referenced by a HandoffStep.highlight value.

Example 1 · Highlight a handoff target

tsx
const captchaRef = usePlingGuideTarget<HTMLInputElement>("captcha");

return <input ref={captchaRef} />;

Canonical reference

Open the corresponding reference

sensitive ​

Marks a value for outbound masking, tokenization, or a hint while keeping the field name visible.

Imports

@plingjs/core · @plingjs/react

Signature

ts
// React
sensitive<T>(value: T, options?: SensitivityMode | SensitiveOptions): SensitiveValue<T>

Parameters and options

ParameterTypeRequiredDefaultDescription
valueTYes—Value that enters page context and the model transcript.
options"masked" | "hidden" | SensitiveOptionsNo"masked"Controls whether the model sees a placeholder or no value. The real value remains in the browser.

Example 1 · Mask a phone number

ts
const phone = sensitive(customer.phone, "masked");

Canonical reference

Open the corresponding reference

Shared option types ​

The option shapes referenced by declarations. Adapter aliases are listed where the name differs.

APIKindReference
ToolOptionsTypeReference
ScopeOptionsTypeReference
RecordValueTypeReference
State optionsTypeReference
AgentSetupTypeReference
KindTypeReference
ParamDeclarationTypeReference
AgentToolOptionsTypeReference
ExpectationTypeReference
HandoffStepTypeReference
FlowStepTypeReference
RegionRoleTypeReference
PlingUiOptionsTypeReference

ToolOptions ​

The action declaration shape shared by every adapter.

Imports

@plingjs/react · @plingjs/core

Signature

ts
// React
type PlingToolOptions = AtomicToolOptions | ParamsToolOptions

Parameters and options

ParameterTypeRequiredDefaultDescription
descstringYes—Required model-facing description of what the control or operation does. This is the primary signal used to select the tool.
idstringNogenerated once per bindingStable action id. Omit only for one-off controls; list rows and flows should use stable ids.
kind"read" | "write" | "danger"NowriteRisk level used for approval and auditing. Omitted values are fail-closed and treated as write.
confirmboolean | "always"Noderived from kindOverrides approval derivation. false skips confirmation, true requires it, and always never offers a persistent allow option.
action"click" | "fill" | "select" | "press" | "hover"Noinferred from elementOverrides primitive inference. By default form inputs use fill and other elements use click.
keystringNoEnterKey used by an action whose primitive is press.
scopestringNonearest scopeExplicit region id. Omitted values inherit the nearest declared scope.
fidelity"high" | "auto" | "low"NoinferredDeclares how trustworthy the execution target is. Setting it stops automatic target relocation.
targetstringNo—CSS selector, scoped to the declared element, used to choose the concrete target.
autoTargetbooleanNotrueAutomatically locates a unique native control inside the declared element.
available() => boolean | string | undefinedNo—Business precondition checked before the action appears as available. A returned string is shown to the model as the reason.
expectExpectationNo—Success criterion checked after execution. Failure produces EXPECTATION_FAILED instead of a false success.
handoffboolean | string | HandoffOptionsNo—Hands the step to the user instead of simulating it. The boolean or string form supplies the reason.
paramsParamDeclarationConditional—Parameter schema for the parameterized form. When present, run receives the validated parameter object rather than a single primitive value.
run(valueOrArgs) => void | Promise<void>No—Injected implementation. Atomic actions receive the primitive value; parameterized actions receive the full argument object. Ignored when steps is present.
stepsreadonly FlowStep[]No—Turns the declaration into a single model-facing flow that executes registered action ids in order. Do not combine it with run.

Type shape

ts
interface ToolOptionsBase {
  desc: string;
  id?: string;
  kind?: "read" | "write" | "danger";
  confirm?: boolean | "always";
  action?: "click" | "fill" | "select" | "press" | "hover";
  key?: string;
  scope?: string;
  fidelity?: Fidelity;
  target?: string;
  autoTarget?: boolean;
  available?: () => boolean | string | undefined;
  expect?: Expectation;
  handoff?: boolean | string | { reason?; expect?; steps?; timeout? };
}

type ToolOptions =
  | { params?: undefined; run?: (value?: unknown) => void | Promise<void> }
  | { params: ParamDeclaration; run?: (args: Record<string, unknown>) => void | Promise<void> };

Example 1 · Parameterized declaration

tsx
const moveRef = usePlingTool({
  id: "move_task",
  desc: "把待办移动到指定位置",
  params: [{ name: "position", label: "新位置", type: "number", min: 1 }],
  run: ({ position }) => moveTask(Number(position)),
});

Canonical reference

Open the corresponding reference

ScopeOptions ​

The region declaration shape. Vue 3 exposes the equivalent value as ScopeValue.

Imports

@plingjs/react

Signature

ts
// React
interface PlingScopeOptions {
  id: string;
  label?: string;
  description?: string;
  role?: RegionRole;
  parent?: string;
}

Parameters and options

ParameterTypeRequiredDefaultDescription
idstringYes—Stable region id. It is written to the DOM and inherited by descendant declarations.
labelstringNo—Short model-facing name, for example 待办列表.
descriptionstringNo—Explains what the region is for and when actions inside it apply.
roleRegionRoleNo—Structural role such as main, dialog, toolbar, or list. It affects reading order and context, not permissions.
parentstringNo—Explicit parent region id for portals, overlays, or detach-to-body cases.

Example 1 · Region metadata

ts
const scope = {
  id: "orders",
  label: "订单列表",
  description: "当前筛选结果,每行可以打开或删除",
  role: "list",
  parent: "main",
};

Canonical reference

Open the corresponding reference

RecordValue ​

A row value or a full record declaration with explicit id, label, and fields.

Imports

@plingjs/core

Signature

ts
// React
type RecordValue =
  | object
  | {
      data: object;
      id?: string | number;
      label?: string;
      fields?: Record<string, unknown>;
    }

Parameters and options

ParameterTypeRequiredDefaultDescription
plain object.id | keystring | numberNo—Default primary key when the row itself is passed as a plain object.
envelope.dataobjectConditional—Row data wrapped in the explicit record envelope.
envelope.idstring | numberNo—Overrides the primary key when the field is not named id or key.
envelope.labelstringNo—Human- and model-readable row label.
envelope.fieldsRecord<string, unknown>No—Allowlist of fields visible to the model. Without it, all row fields except the primary key are exposed.

Example 1 · Explicit field allowlist

ts
const value = {
  data: order,
  id: order.code,
  label: `订单 ${order.code}`,
  fields: { customer: order.customer, total: order.total },
};

Canonical reference

Open the corresponding reference

State options ​

Optional description for a read-only state view.

Imports

@plingjs/react

Signature

ts
// React
interface PlingStateOptions { description?: string }

Parameters and options

ParameterTypeRequiredDefaultDescription
descriptionstringNo—Explains the state view and its units or bounds. Describe a view, not the entire store.

Example 1 · Describe a bounded view

ts
{ description: "当前筛选项、总条数与未完成条数" }

Canonical reference

Open the corresponding reference

AgentSetup ​

Application-level runtime options: model overrides, hooks, gates, event handling, trace, and continuity.

Imports

@plingjs/react

Signature

ts
// React
type AgentSetup = Omit<AgentRuntimeOptions, "config" | "registry" | "gate"> & {
  config?: AgentConfigOverrides;
  gate?: () => boolean;
}

Parameters and options

ParameterTypeRequiredDefaultDescription
configAgentConfigOverridesNo—Partial model and runtime configuration. Omitted fields are read from VITE_AGENT_* environment variables or framework defaults.
llmLlmNo—Injects the model call function. Use it for a test model, a server proxy, or a non-OpenAI-compatible transport.
responseLocalestring | (() => string)No—Locale used when composing the response-language instruction. A function is re-read before each model request.
telemetryTelemetryNo—Collects token, duration, cost, and retry metrics for the current runtime.
traceboolean | AgentTraceOptionsNofalseKeeps a bounded in-memory trace of model requests for the read-only inspector. Disabled by default.
settle() => Promise<void>No—Replaces the page-settle wait used between actions. Most useful in deterministic tests and non-browser hosts.
hooksHookRegistryNo—Tool lifecycle hooks shared by every surface created from this application runtime.
onEvent(event: SessionEvent) => voidNo—Receives the same session event stream that powers the chat and activity views.
onApproval(pending: PendingApproval | null) => voidNo—Called when an approval request appears or clears. Use it to connect a custom approval UI.
onHandoff(pending: PendingHandoff | null) => voidNo—Called when a human-handoff request appears or clears.
policyConfirmGateNo—Replaces the default approval gate. When provided, the built-in gate and chat approval buttons are not used.
approvalTimeoutMsnumberNo60000Time to wait for a human approval before treating it as denied.
handoffTimeoutMsnumberNo300000Default time to wait for a human handoff. A tool-level handoff.timeout overrides it.
handoffHandoffGateNo—Replaces the built-in handoff queue with a custom channel.
idstringNo—Stable session id for multi-session hosts.
onLeaseLost() => voidNo—Called when another tab or host takes over the shared session lease.
continuityContinuitySettingNo—Enables bounded conversation continuity across full-page navigation. "tab" uses sessionStorage. Omit to disable it.
gate() => booleanNotrueReturns false to disable the built-in confirmation channel for this application. Defaults to enabled.

Example 1 · Application-level assistant setup

ts
const pling = createPling({
  agent: {
    config: { limits: { maxTurns: 12 } },
    trace: true,
    gate: () => true,
  },
});

Canonical reference

Open the corresponding reference

Kind ​

The action risk level used by approval policy.

Imports

@plingjs/core

Signature

ts
// React
type Kind = "read" | "write" | "danger"

Parameters and options

ParameterTypeRequiredDefaultDescription
read"read"No—No business state change. Visibility, navigation, and inspection belong here.
write"write"No—Changes business state but is not destructive or irreversible.
danger"danger"No—Destructive, irreversible, or high-impact. Approval defaults to stricter handling.

Example 1 · Choose a risk level

ts
pling.tool(deleteButton, { desc: "删除此订单", kind: "danger" });

Canonical reference

Open the corresponding reference

ParamDeclaration ​

Array shorthand or JSON Schema used to validate action arguments.

Imports

@plingjs/core

Signature

ts
// React
type ParamDeclaration = readonly ToolParam[] | JsonSchema

Parameters and options

ParameterTypeRequiredDefaultDescription
[].namestringYes—Argument key received by run and visible to the model.
[].labelstringYes—Required explanation of the argument. It is the model's only semantic hint.
[].type"string" | "number" | "boolean"No"string"Argument type. Includes coercion from obvious string forms and rejects invalid values.
[].optionalbooleanNofalseMarks the argument optional. Arguments are required by default.
[].valuesreadonly (string | number)[]No—Closed static value set. Use it when the model must choose from known values.
[].options() => readonly ParamOption[]No—Dynamic value set, re-read for each snapshot and execution.
[].min | [].maxnumber | (() => number)No—Numeric bounds for number arguments, including dynamic bounds.
[].minLength | [].maxLengthnumberNo—String length bounds.
[].patternRegExp | stringNo—Regular-expression constraint for a string argument.
[].format"date"No—Semantic format validation. A date must be a real calendar date.
JSON Schema.type"object"Conditional"object"The direct JSON Schema form must describe an object.
JSON Schema.propertiesRecord<string, unknown>No—Property schemas for the direct JSON Schema form.
JSON Schema.requiredstring[]No—Required property names for the direct JSON Schema form.

Example 1 · Compact parameter declaration

ts
const params = [
  { name: "orderId", label: "订单号", pattern: /^SO-\d{4}$/ },
  { name: "note", label: "新备注", maxLength: 200 },
  { name: "notify", label: "是否通知客户", type: "boolean", optional: true },
];

Canonical reference

Open the corresponding reference

AgentToolOptions ​

The declaration shape for a function-level action: stable id, model-facing description, optional schema, availability, expectation, and implementation.

Imports

@plingjs/react

Signature

ts
// React
interface AgentToolOptions {
  id: string;
  desc: string;
  kind?: Kind;
  confirm?: boolean | "always";
  params?: ParamDeclaration;
  available?: () => boolean | string;
  expect?: Expectation;
  run: (args: Record<string, unknown>) => unknown;
}

Parameters and options

ParameterTypeRequiredDefaultDescription
idstringYes—Globally unique action id used by the model.
descstringYes—Required semantic description of the operation.
kindKindNowriteRisk level. Omitted values are fail-closed and treated as write.
confirmboolean | "always"Noderived from kindOverrides the normal approval policy.
paramsParamDeclarationNo—Argument schema and validation; run receives the normalized object.
available() => boolean | stringNo—Precondition check. A string is returned to the model as the unavailability reason.
expectExpectationNo—Success criterion checked after run completes.
run(args: Record<string, unknown>) => unknownYes—Validated implementation. Sensitive placeholders are restored before it runs.

Example 1 · Function action with parameters

ts
useAgentTool({
  id: "set_priority",
  desc: "设置订单优先级",
  kind: "write",
  params: [{ name: "level", label: "优先级", values: ["low", "normal", "high"] }],
  run: ({ level }) => setPriority(String(level)),
});

Canonical reference

Open the corresponding reference

Expectation ​

A success condition checked after an action finishes.

Imports

@plingjs/core

Signature

ts
// React
interface Expectation {
  desc?: string;
  check(): boolean | Promise<boolean>;
  timeout?: number;
}

Parameters and options

ParameterTypeRequiredDefaultDescription
descstringNo—Human-readable statement of the expected outcome. It is included in success and failure receipts.
check() => boolean | Promise<boolean>Yes—Predicate evaluated after execution. Exceptions remain developer errors and are not swallowed.
timeoutnumberNo2000Maximum wait in milliseconds before reporting EXPECTATION_FAILED.

Example 1 · Verify a new row exists

ts
const expect = {
  desc: "新待办出现在列表中",
  check: () => todos.some((todo) => todo.text === "准备发布"),
  timeout: 3000,
};

Canonical reference

Open the corresponding reference

HandoffStep ​

One instruction shown to a person during human handoff.

Imports

@plingjs/core

Signature

ts
// React
interface HandoffStep {
  text: string;
  highlight?: string;
}

Parameters and options

ParameterTypeRequiredDefaultDescription
textstringYes—Instruction shown to the person who takes over.
highlightstringNo—Optional guide-target id or action id to highlight while the step is active.

Example 1 · Guide a human step

ts
const steps = [
  { text: "填写短信验证码", highlight: "captcha" },
  { text: "点击提交", highlight: "submit" },
];

Canonical reference

Open the corresponding reference

FlowStep ​

One step in a compound action. Flow steps are not a second execution channel.

Imports

@plingjs/core

Signature

ts
// React
interface FlowStep {
  action: string;
  args?: Record<string, unknown> | ((params: Record<string, unknown>) => Record<string, unknown>);
  expect?: Expectation;
  desc?: string;
  optional?: boolean;
  idempotent?: boolean;
}

Parameters and options

ParameterTypeRequiredDefaultDescription
actionstringYes—Registered action id to execute. It may contain placeholders.
argsRecord<string, unknown> | ((params) => Record<string, unknown>)No—Step arguments. Strings may reference flow parameters; a function receives the complete parameter object.
expectExpectationNo—Overrides the step action's own success criterion.
descstringNo—Human-readable step description used in progress and receipts.
optionalbooleanNofalseA failed optional step is skipped instead of aborting the flow.
idempotentbooleanNofalseAllows safe retry after an execution or expectation failure. Pre-execution failures are always retryable.

Example 1 · Reference a parameter in a step

ts
const steps = [
  { action: "edit@order:{{orderId}}", desc: "打开订单" },
  { action: "dialog_note", args: { text: "{{note}}" }, desc: "填写备注" },
  { action: "dialog_save", desc: "保存" },
];

Canonical reference

Open the corresponding reference

RegionRole ​

The structural role of a region.

Imports

@plingjs/core

Signature

ts
// React
type RegionRole =
  | "page"
  | "header"
  | "nav"
  | "main"
  | "aside"
  | "section"
  | "form"
  | "dialog"
  | "toolbar"
  | "list"
  | "footer"

Parameters and options

ParameterTypeRequiredDefaultDescription
role"page" | "header" | "nav" | "main" | "aside" | "section" | "form" | "dialog" | "toolbar" | "list" | "footer"Yes—Adds structural context for disambiguating actions with similar names. It does not grant or restrict permissions.

Example 1 · Disambiguate two confirm buttons

ts
pling.scope(dialog, { id: "edit_dialog", role: "dialog", label: "编辑订单" });
pling.scope(toolbar, { id: "bulk_toolbar", role: "toolbar", label: "批量操作" });

Canonical reference

Open the corresponding reference

PlingUiOptions ​

Locale, theme, message overrides, and class names for the shared assistant UI.

Imports

@plingjs/ui

Signature

ts
// React
interface PlingUiOptions {
  locale?: PlingLocale;
  theme?: PlingTheme;
  messages?: PlingCatalogOverrides;
  classNames?: PlingClassNames;
}

Parameters and options

ParameterTypeRequiredDefaultDescription
locale"en-US" | "zh-CN" | "auto" | stringNoen-USLanguage used by the built-in assistant UI. "auto" follows the browser language.
theme"light" | "dark" | "auto" | PlingThemeOverridesNolightTheme for the built-in surfaces. An object can override tokens or choose a mode.
theme.mode"light" | "dark" | "auto"NolightExplicit mode when the theme is an object. "auto" follows the operating-system preference.
theme.tokensPartial<PlingThemeTokens>No—Overrides individual design tokens such as colours, radii, shadows, and font families. Keys not supplied keep the selected light or dark defaults.
messagesPlingCatalogOverridesNo—Adds or replaces message catalog entries for one or more locales.
messages.<locale>Partial<Record<PlingMessageKey, string>>No—Message overrides for one BCP 47 locale. Missing keys fall back to the built-in catalog.
classNamesPlingClassNamesNo—Extra class names applied to the built-in chat, dock, launcher, and panel.
classNames.dockstringNo—Extra class for the dock shell.
classNames.panelstringNo—Extra class for the panel shell.
classNames.launcherstringNo—Extra class for the launcher button.
classNames.chatstringNo—Extra class for the chat surface.

Example 1 · Chinese UI with a token override

ts
const ui = {
  locale: "zh-CN",
  theme: { mode: "light", tokens: { colorPrimary: "#0b6bcb" } },
  classNames: { dock: "product-assistant" },
};

Canonical reference

Open the corresponding reference

Assistant surfaces ​

Mounted conversation and inspection surfaces. They render the shared runtime; they do not create a second agent.

APIKindReference
AgentDockComponentReference
AgentInlineComponentReference
AgentChatComponentReference
AgentDebugComponentReference

AgentDock ​

Floating or sidebar assistant surface. Owns placement, task registration, open state, and the activity view.

Imports

@plingjs/react

Signature

ts
// React
<AgentDock />

Parameters and options

ParameterTypeRequiredDefaultDescription
classNamestringNo—Extra class for the outer shell, commonly used for page-grid sizing.
titlestringNo—Assistant title. Defaults to the localized catalog value.
placeholderstringNo—Composer placeholder.
emptyHintstringNo—Message shown before the first turn.
quickreadonly string[]No[]Suggested prompts that remain available between runs.
defaultOpenbooleanNofalseWhether the surface starts open.
configAgentConfigOverridesNo—Overrides model and runtime settings for this surface only.
llmLlmNo—Injected model function for this surface. Overrides application-level agent.llm.
hooksHookRegistryNo—Tool hooks for this surface. Falls back to application-level hooks.
gate() => booleanNo—Confirmation-channel switch for this surface.
registryRegistryNo—Action registry to operate. Defaults to the provider registry.
debugboolean | AgentTraceOptionsNofalseEnables the read-only request inspector inside Activity. Disabled by default.
onSessionEvent(event: SessionEvent) => voidNo—Receives every session event for audit or custom UI.
onOpenChange(open: boolean) => voidNo—Called when the dock opens or closes.
navigate(href: string) => voidNowindow.location.replaceNavigation implementation after a completed task.
layout"dock" | "sidebar" | "inline"No"dock"Floating dock, viewport-edge sidebar, or inline grid surface.
side"left" | "right"No"right"Sidebar edge when layout is sidebar.
launcherPlacement"bottom" | "center"No"bottom"Position of the collapsed sidebar launcher.
launcherLabelstringNo—Custom label for the collapsed launcher.
surfaceIdstringNo"dock"Named surface used by pling.ask({ surface }). Built-in docks default to dock.
ref.send(prompt)(prompt: string) => Promise<void>No—Imperative handle that opens the dock and sends a prompt.
ref.ask(prompt, options)(prompt: string, options?: PlingAskOptions) => Promise<void>No—Imperative handle with optional named-surface routing.

Example 1 · One-tag React dock

tsx
<AgentDock
  title="待办助手"
  quick={["把第一条待办标记完成"]}
  debug
  onSessionEvent={audit}
/>

Canonical reference

Open the corresponding reference

AgentInline ​

Embeds the conversation in a business column instead of a floating surface.

Imports

@plingjs/react

Signature

ts
// React
<AgentInline />

Parameters and options

ParameterTypeRequiredDefaultDescription
classNamestringNo—Extra class for the grid surface.
titlestringNo—Assistant title.
placeholderstringNo—Composer placeholder.
emptyHintstringNo—Empty-state copy.
quickreadonly string[]No—Suggested prompts.
configAgentConfigOverridesNo—Surface-level model overrides.
llmLlmNo—Injected model function.
hooksHookRegistryNo—Surface-level tool hooks.
gate() => booleanNo—Confirmation-channel switch.
registryRegistryNo—Registry to operate.
debugboolean | AgentTraceOptionsNo—Enables the read-only request inspector.
onSessionEvent(event: SessionEvent) => voidNo—Session event callback.
navigate(href: string) => voidNo—Post-task navigation implementation.
surfaceIdstringNo"inline"Task-routing name. Inline surfaces default to inline.

Example 1 · Reserve a workbench column

tsx
<div className="workspace">
  <main>...</main>
  <AgentInline title="操作助手" />
</div>

Canonical reference

Open the corresponding reference

AgentChat ​

Renders a conversation and confirmation state without owning placement or the session.

Imports

@plingjs/react

Signature

ts
// React
<AgentChat />

Parameters and options

ParameterTypeRequiredDefaultDescription
titlestringNo—Chat header title.
eventsreadonly SessionEvent[]No[]Event transcript to render.
runningbooleanNofalseDisables input and shows the running state.
pendingPendingApproval | nullNonullCurrent approval request.
pendingHandoffPendingHandoff | nullNo—Current human-handoff request.
placeholderstringNo—Composer placeholder.
emptyHintstringNo—Empty-state copy.
uiPlingUiControllerNo—Locale and theme controller. Defaults to an English standalone controller.
classNamestringNo—Extra class for the outer chat surface.
toolsbooleanNofalseIncludes raw tool-call lines in the transcript.
reveal(text: string) => stringNo—Render-only text transform.
resume{ goal?: string; interrupted?: boolean } | nullNonullShows the continue-previous-task banner.
actionsReactNodeNo—Toolbar content in the header.
footerReactNodeNo—Content rendered above the composer.
onSend(text: string) => voidNo—User submitted a message.
onReply(decision: boolean | "always") => voidNo—User answered an approval request.
onHandoff(done: boolean) => voidNo—User completed or cancelled a handoff.
onHandoffStep(delta: number) => voidNo—User moved between handoff steps.
onResume() => voidNo—User accepted the resume banner.
onDismissResume() => voidNo—User dismissed the resume banner.
onStop() => voidNo—User requested cancellation while running.

Example 1 · Render an externally managed chat

tsx
<AgentChat
  events={events}
  running={running}
  pending={pending}
  onSend={send}
  onReply={reply}
/>

Canonical reference

Open the corresponding reference

AgentDebug ​

React read-only inspector for the runtime already driving a conversation.

Imports

@plingjs/react

Signature

ts
// React
<AgentDebug runtime={runtime} registry={registry} />

Parameters and options

ParameterTypeRequiredDefaultDescription
runtimeAgentRuntimeYes—The runtime that is already driving the current conversation. The component never creates a second runtime.
registryRegistryYes—Registry whose snapshot and coverage should be inspected.

Example 1 · Inspect the active conversation

tsx
<AgentDebug runtime={runtime} registry={pling.registry} />

Canonical reference

Open the corresponding reference

Page identity and continuity ​

Read page identity, share a runtime across frames, and inspect declared coverage.

APIKindReference
PlingPageInterfaceReference
createPlingPageFunctionReference
sharePlingPageWithFrameFunctionReference
plingPageFromParentFunctionReference
waitForPlingPageFromParentFunctionReference
inspectCoverageMethodReference

PlingPage ​

A page-level runtime shared by multiple framework islands or same-origin frames.

Imports

@plingjs/dom · @plingjs/react

Signature

ts
// React
interface PlingPage {
  readonly registry: Registry;
  readonly scopes: ScopeController;
  readonly feedback: FeedbackCollector;
  destroy(): void;
}

Parameters and options

ParameterTypeRequiredDefaultDescription
registryRegistryNo—Shared action, record, state, and feedback registry.
scopesScopeControllerNo—Shared region visibility and occlusion controller.
feedbackFeedbackCollectorNo—Page-level feedback collector that observes the document once.
destroy()voidNo—Stops page observers and clears automatic scopes. Adapters should destroy their declarations first.

Example 1 · Share one page runtime

ts
const page = createPlingPage();
const vuePling = createPling({ shared: page });
const reactPling = createPling({ shared: page });

Canonical reference

Open the corresponding reference

createPlingPage ​

Creates the shared registry, scopes, and page identity that adapters can join with shared.

Imports

@plingjs/dom · @plingjs/react

Signature

ts
// React
createPlingPage(options?: PlingPageOptions): PlingPage

Parameters and options

ParameterTypeRequiredDefaultDescription
options.registryRegistryNo—Existing registry to share. A new registry is created when omitted.
options.scopesScopeControllerOptionsNo—Visibility and hit-testing overrides for the shared page.

Example 1 · Create a mixed-framework page runtime

ts
const page = createPlingPage();

// Pass the same page to Vue, React, or Vanilla islands:
const pling = createPling({ shared: page, namespace: "orders" });

Canonical reference

Open the corresponding reference

sharePlingPageWithFrame ​

Shares a page runtime with a same-origin iframe and returns a cleanup function.

Imports

@plingjs/dom · @plingjs/react

Signature

ts
// React
sharePlingPageWithFrame(frame: HTMLIFrameElement, page: PlingPage): () => void

Parameters and options

ParameterTypeRequiredDefaultDescription
frameHTMLIFrameElementYes—Same-origin iframe that should receive the shared page runtime.
pagePlingPageYes—Runtime created by createPlingPage.

Example 1 · Share a runtime with a same-origin frame

ts
const page = createPlingPage();
const stop = sharePlingPageWithFrame(iframe, page);

// On teardown:
stop();
page.destroy();

Canonical reference

Open the corresponding reference

plingPageFromParent ​

Reads a shared page runtime from the parent window when the current document is an embedded frame.

Imports

@plingjs/dom · @plingjs/react

Signature

ts
// React
plingPageFromParent(win?: Window): PlingPage | undefined

Parameters and options

ParameterTypeRequiredDefaultDescription
winWindowNowindowWindow whose parent should be checked. Defaults to the current window.

Example 1 · Read a shared page synchronously

ts
const page = plingPageFromParent();
if (page) createPling({ shared: page });

Canonical reference

Open the corresponding reference

waitForPlingPageFromParent ​

Waits for a parent frame to publish its page runtime.

Imports

@plingjs/dom · @plingjs/react

Signature

ts
// React
waitForPlingPageFromParent(options?: WaitForFramePageOptions): Promise<PlingPage>

Parameters and options

ParameterTypeRequiredDefaultDescription
options.windowWindowNowindowChild window to listen on. Defaults to the current window.
options.timeoutMsnumberNo5000Maximum wait. Zero waits indefinitely. Rejects when another positive timeout expires.

Example 1 · Wait for the parent runtime

ts
const page = await waitForPlingPageFromParent({ timeoutMs: 8000 });
createPling({ shared: page });

Canonical reference

Open the corresponding reference

inspectCoverage ​

Scans the mounted page for interactive controls that have no declaration. It reports; it never registers an action.

Imports

@plingjs/react · @plingjs/dom

Signature

ts
// React
pling.inspectCoverage(root?: Element | null): CoverageReport

Parameters and options

ParameterTypeRequiredDefaultDescription
rootElement | nullNo—Application root to scan. Vue uses its mount root; React and DOM callers may pass any root.
return.totalnumberNo—Recognized actionable controls in the root.
return.declarednumberNo—Controls with a direct declaration.
return.derivednumberNo—Controls produced by optional L1 derivation.
return.groupednumberNo—Controls covered by a declaration on an ancestor. Review these manually.
return.missingnumberNo—Actionable controls with no declaration in their ancestry.
return.coveragePercentnumber | nullNo—Covered controls divided by total; null when there are no controls.
return.targetsCoverageTarget[]No—Grouped and missing controls with labels and nearby action ids.

Example 1 · Inspect React coverage

tsx
const report = pling.inspectCoverage(document.getElementById("root"));

Canonical reference

Open the corresponding reference

Version and compatibility ​

PackageVersionPeer dependencies
@plingjs/vue0.1.0-alpha.2vue ^3
@plingjs/react0.1.0-alpha.2react >=18
@plingjs/vue20.1.0-alpha.2vue ^2.7.0
@plingjs/vanilla0.1.0-alpha.2—
ItemValue
Introduced0.1.0-alpha.2
StabilityPre-1.0 alpha; a minor release may change the API

Machine-readable copy ​