New

docx-editor 1.x has shipped. Vue support, i18n, agents. Read the migration guide →

API Referencev1.0.2

@eigenpal/docx-editor-agents/react

React entry. Hooks, components, and types that need React as a peer dependency. Pair with `/server` (or `/ai-sdk/server`) for the API route that drives the LLM.

Functions(8)

declare function AgentChatLog(input: AgentChatLogProps): react_jsx_runtime.JSX.Element;
declare function AgentComposer(input: AgentComposerProps): react_jsx_runtime.JSX.Element;
declare function AgentPanel(input: AgentPanelProps): react_jsx_runtime.JSX.Element;
declare function AgentSuggestionChip(input: AgentSuggestionChipProps): react_jsx_runtime.JSX.Element;

Collapsible timeline of an assistant turn's tool calls. Lives above the assistant text bubble. Auto-collapses when the turn finishes; click the summary row to re-expand.

declare function AgentTimeline(input: AgentTimelineProps): react_jsx_runtime.JSX.Element | null;

Friendly UI label for a tool — sourced from the registry's `displayName`, falling back to a sentence-case version of the snake_case name. Used by `<AgentTimeline>` and any other UI that lists running / completed tools.

declare function getToolDisplayName(name: string): string;
getToolDisplayName('add_comment') // → 'Adding comment'
getToolDisplayName('fetch_clause_template') // → 'Fetch clause template'

Hook that creates an EditorBridge and provides tool execution.

declare function useAgentChat(options: UseAgentChatOptions): UseAgentChatReturn;
declare function useDocxAgentTools(options: UseDocxAgentToolsOptions): UseDocxAgentToolsReturn;

Interfaces(15)

interface AgentChatLogProps
MemberTypeSummary
autoScroll?booleanAuto-scroll to bottom on new messages / loading toggles. Default: true.
className?string
earlierLabel?(count: number) => string"+ N earlier steps" — pass for i18n. Default English.
emptyState?ReactNodeShown when there are no messages and not loading.
error?string | nullRender an error bubble after the last message.
humanizeToolName?(name: string) => stringMap a tool name to a friendly label for the per-message timeline. Pass `getToolDisplayName` from `@eigenpal/docx-editor-agents/react` to use the toolkit's registry-aware labels (e.g. "Adding comment").
loading?booleanRender thinking dots at the bottom of the list.
maxVisibleCalls?numberCap the tool-call timeline to this many recent rows. Default 3.
messagesAgentMessage[]
style?CSSProperties
summaryLabel?(count: number) => string"N steps" — pass for i18n. Default English.
thinkingLabel?string"Assistant is thinking" aria-label. Default English.
workingLabel?(count: number) => string"Working… N steps" — pass for i18n. Default English.
interface AgentComposerProps
MemberTypeSummary
className?string
disabled?boolean
footnote?ReactNodeSmall text under the input — typically a scope reminder.
onChange(next: string) => void
onSubmit() => void
placeholder?string
sendLabel?stringSend-button aria-label. Default `'Send'`.
valuestring
interface

AgentContextSnapshot

packages/agents/src/types.ts:250

Snapshot of what the user is looking at — pass this to your agent's system prompt so it knows the current selection / page without an extra `read_selection` round-trip.

interface AgentContextSnapshot
MemberTypeSummary
currentPagenumber1-indexed page the cursor / selection is on. 0 if unknown.
selectionSelectionInfo | nullUser's current selection or cursor (null if editor isn't focused).
totalPagesnumberTotal number of pages currently rendered.
interface AgentMessage
MemberTypeSummary
idstring
role'user' | 'assistant'
status?'streaming' | 'done'`streaming` while the model is still calling tools / writing text; `done` once the turn is final.
textstring
toolCalls?AgentToolCall[]Tool calls the assistant made for this turn, in order. The timeline stays expanded while `status === 'streaming'` and auto-collapses to an "N steps" summary when the message hits `status === 'done'`.
interface AgentPanelProps
MemberTypeSummary
childrenReactNodePanel content. Render whatever you want — a chat, tabs, settings, anything.
className?stringOptional class on the outer wrapper.
closed?booleanWhen `true`, the panel collapses to zero width with an ease-out transition (the children are still mounted so chat state survives close/reopen). The DocxEditor wrapper passes this when the user toggles the panel — kept off by default for standalone usage.
closeLabel?stringClose button aria-label. Defaults to `'Close panel'`.
defaultWidth?numberDefault width when uncontrolled.
icon?ReactNodeHeader icon node. Defaults to a sparkle SVG.
maxWidth?numberMax drag width.
minWidth?numberMin drag width.
onClose?() => voidHeader close button click. Omit to hide the close button.
onWidthChange?(w: number) => voidWidth change callback (drag end and intermediate).
resizeHandleLabel?stringResize handle aria-label. Defaults to `'Resize agent panel'`.
title?stringHeader title. Defaults to `'Assistant'`. Pass a localised string for i18n.
width?numberControlled width in pixels. Omit for uncontrolled (internal state + localStorage).
interface AgentSuggestionChipProps
MemberTypeSummary
disabled?boolean
labelstring
onClick() => void
interface AgentTimelineProps
MemberTypeSummary
earlierLabel?(count: number) => string"+ N earlier steps" — pass for i18n. Default English.
humanizeName?(name: string) => stringMap a tool name to a friendly label. Defaults to a sentence-case conversion of the snake_case name. Pass `getToolDisplayName` from `@eigenpal/docx-editor-agents/react` to use the toolkit's registry.
maxVisibleCalls?numberCap the number of rendered call rows — older entries collapse into a "+N earlier steps" header. Default 3.
streaming?booleanWhether the parent assistant turn is still streaming. While true, the timeline is forced expanded and shows a spinner; on false it auto-collapses to an "N steps" summary unless the user expanded it.
summaryLabel?(count: number) => string"N steps" — pass for i18n. Default English.
toolCallsAgentToolCall[]Tool calls in chronological order.
workingLabel?(count: number) => string"Working… N steps" — pass for i18n. Default English.

Shared agent UI types — framework-agnostic. Both React and Vue adapters (and the AI SDK adapters) consume this single declaration.

Keeping the types here lets us tweak the chat schema without writing the same drift fix in four files.

interface AgentToolCall
MemberTypeSummary
error?stringSet when the call errored — surfaces in the timeline as failed.
idstringStable id for keying.
input?unknownJSON-able input the agent passed. Rendered in the expanded view.
namestringTool name (e.g. `read_document`, `add_comment`).
result?stringResult text or summary. Set after the call completes.
status'running' | 'done' | 'error'`running` while in flight, `done` on success, `error` on failure.
interface

AgentToolDefinition

packages/agents/src/tools/types.ts:13

Definition of an agent tool — name, JSON-schema input, handler. Use this to build custom tools alongside the built-in `agentTools`.

interface AgentToolDefinition<TInput = Record<string, unknown>>
MemberTypeSummary
descriptionstringHuman-readable description for the LLM
displayName?stringFriendly UI label for the tool. Shown in the agent panel's timeline (e.g. "Reading document"). Falls back to a sentence-case version of `name` if omitted, so consumer-defined tools render readably without specifying this.
handler(input: TInput, bridge: EditorBridge) => AgentToolResultHandler — receives parsed input + bridge, returns result
inputSchemaRecord<string, unknown>JSON Schema for the input parameters
namestringTool name (used in tool_use blocks)

Result returned by a tool handler. `success: false` carries an `error` message; `success: true` may carry tool-specific `data`.

interface AgentToolResult
MemberTypeSummary
data?unknown
error?string
successboolean

Agent-bridge contract every editor adapter (React, Vue, future) MUST satisfy. Versioning: additions are coordinated minor bumps across the fixed group; signature changes / removals are major. See `openspec/changes/vue-editor-robust-implementation/design.md` Decision 18.

interface EditorRefLike
MemberTypeSummary
addComment
applyFormattingApply character formatting to a paragraph or sub-range. Returns false on missing paraId / ambiguous search.
findInDocument
getComments
getCurrentPage1-indexed page the user's cursor / selection is on. 0 if unknown.
getDocument
getEditorRef
getPageContentRead a single page's paragraphs (1-indexed). Returns null if the page does not exist.
getSelectionInfo
getTotalPagesTotal number of pages currently rendered.
onContentChange
onSelectionChange
proposeChange
replyToComment
resolveComment
scrollToParaId
setParagraphStyleApply a paragraph style by styleId. Returns false if paraId is unknown.
interface

UseAgentChatOptions

packages/agents/src/useAgentChat.ts:23

useAgentChat — React hook that wires agent tools to a live DocxEditor.

interface UseAgentChatOptions
```tsx
import { useAgentChat } from '@eigenpal/docx-editor-agents/react';

const { executeToolCall, toolSchemas } = useAgentChat({ editorRef, author: 'Assistant' });

// Pass toolSchemas to your AI provider, execute tool calls on the client
const result = executeToolCall('add_comment', { paragraphIndex: 3, text: 'Fix this.' });
```
MemberTypeSummary
author?stringDefault author name for comments and changes. Default: 'AI'
editorRefReact.RefObject<EditorRefLike | null>Reference to the DocxEditor (must match EditorRefLike interface).
interface UseAgentChatReturn
MemberTypeSummary
executeToolCall(toolName: string, input: Record<string, unknown>) => AgentToolResultExecute a tool call through the bridge.
toolSchemasReturnType<typeof getToolSchemas>Tool schemas in OpenAI function calling format. Pass to your AI provider.
interface

UseDocxAgentToolsOptions

packages/agents/src/useDocxAgentTools.ts:45

useDocxAgentTools — wires the toolkit to a live DocxEditor for BYO chat frameworks.

Returns three things consumers need to plug an agent into the editor:

- `tools` — schemas in OpenAI function-calling format. Pass to `streamText({ tools })`, OpenAI's `tools` field, Anthropic's `tools`, or any provider that accepts that shape. - `executeToolCall` — the executor. Hand to AI SDK's `onToolCall`, or call yourself when you wire up tool calls manually. - `getContext` — snapshot of `{selection, currentPage, paragraphCount}` for system-prompt injection. Pass through `prepareRequestBody` (AI SDK) or inline into your own request body so the agent always knows what the user is looking at without an extra tool round-trip.

Custom tools merge with the built-ins via the `tools` option. Names collide → consumer wins (your override replaces the built-in by name).

interface UseDocxAgentToolsOptions
```tsx
const { tools, executeToolCall, getContext } = useDocxAgentTools({
  editorRef,
  author: 'Assistant',
  tools: {
    fetch_clause: {
      name: 'fetch_clause',
      description: 'Fetch a clause template by name.',
      inputSchema: { type: 'object', properties: { name: { type: 'string' } } },
      handler: async (input) => ({ success: true, data: await fetchTemplate(input.name) }),
    },
  },
});
```
MemberTypeSummary
author?stringDefault author name for comments / tracked changes. Default: 'AI'.
editorRefReact.RefObject<EditorRefLike | null>Reference to the DocxEditor (must match EditorRefLike).
exclude?readonly string[]Block-list of built-in tool names to hide. Applied after `include`. Use for agents that should not write tracked changes:
include?readonly string[]Allow-list of built-in tool names to expose. When provided, only the named tools are returned (custom tools from `tools` always pass). Useful for read-only or scope-restricted agents:
tools?Record<string, AgentToolDefinition<any>>Optional consumer-defined tools to merge with the built-ins. Keyed by tool name. A tool with the same name as a built-in **replaces** it. Pass a stable reference (memoized or module-level) to avoid rebuilding the tool list on every render.
interface

UseDocxAgentToolsReturn

packages/agents/src/useDocxAgentTools.ts:75
interface UseDocxAgentToolsReturn
MemberTypeSummary
executeToolCall(name: string, args: Record<string, unknown>) => AgentToolResultExecute a tool call by name. Pass to AI SDK's `onToolCall`.
getContext() => AgentContextSnapshotSnapshot of the user's current view for system-prompt injection.
toolsReturnType<typeof getToolSchemas>Tool schemas in OpenAI function calling format — pass to your AI provider.