New

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

API Referencev1.0.2

@eigenpal/docx-editor-core/agent

Document Agent

Headless, framework-agnostic API for inspecting and editing the Document model. Used by `@eigenpal/docx-editor-agents` and any adapter that wants agent capabilities without UI.

Functions(39)

Build extended selection context with additional details

declare function buildExtendedSelectionContext(doc: Document, range: Range, options?: SelectionContextOptions): ExtendedSelectionContext;

Build selection context for AI operations

declare function buildSelectionContext(doc: Document, range: Range, options?: SelectionContextOptions): SelectionContext;
fn

buildSelectionContextFromContext

Build selection context for AI operations

declare function buildSelectionContext$1(doc: Document, range: Range, options?: SelectionContextOptions$1): SelectionContext;

Compare two positions Returns: -1 if a b, 0 if equal, 1 if a b

declare function comparePositions(a: Position, b: Position): -1 | 0 | 1;

Count characters in text

declare function countCharacters(text: string, includeSpaces?: boolean): number;

Count words in text

declare function countWords(text: string): number;

Create a DocumentAgent from a DOCX buffer

declare function createAgent(buffer: ArrayBuffer): Promise<DocumentAgent>;

Create a DocumentAgent from a parsed Document

declare function createAgentFromDocument(document: Document): DocumentAgent;

Create a collapsed range (cursor) at a position

declare function createCollapsedRange(position: Position): Range;

Create a command with generated ID

declare function createCommand<T extends AgentCommand>(command: Omit<T, 'id'>): T;

Create a range from two positions

declare function createRange(start: Position, end: Position): Range;

Execute an agent command on a document Returns a new document with the command applied (immutable)

Dispatch order: 1. Try plugin handlers first (allows plugins to override built-in commands) 2. Fall back to built-in handlers

declare function executeCommand(doc: Document, command: AgentCommand): Document;

Execute multiple commands in sequence

declare function executeCommands(doc: Document, commands: AgentCommand[]): Document;

Get action description

declare function getActionDescription(action: AIAction): string;

Get action label

declare function getActionLabel(action: AIAction): string;

Build agent context from a document

declare function getAgentContext(doc: Document, options?: AgentContextOptions): AgentContext;

Get block index for a paragraph index

declare function getBlockIndexForParagraph(body: DocumentBody, paragraphIndex: number): number;

Get character count from document body

declare function getBodyCharacterCount(body: DocumentBody): number;

Get plain text from document body

declare function getBodyText(body: DocumentBody): string;

Get word count from document body

declare function getBodyWordCount(body: DocumentBody): number;

Get a simple document summary for quick context

declare function getDocumentSummary(doc: Document): string;

Get formatting at a specific position in a paragraph

declare function getFormattingAtPosition(paragraph: Paragraph, offset: number): Partial<TextFormatting>;

Get hyperlink at position

declare function getHyperlinkAtPosition(paragraph: Paragraph, offset: number): Hyperlink | undefined;

Get plain text from a hyperlink

declare function getHyperlinkText(hyperlink: Hyperlink): string;

Get paragraph at index from document body

declare function getParagraphAtIndex(body: DocumentBody, index: number): Paragraph | undefined;

Get all paragraphs from document body

declare function getParagraphs(body: DocumentBody): Paragraph[];

Get plain text from a paragraph

declare function getParagraphText(paragraph: Paragraph): string;

Get plain text from a run

declare function getRunText(run: Run): string;

Get formatting summary for a selection

declare function getSelectionFormattingSummary(doc: Document, range: Range): FormattingSummary;

Get plain text from a table

declare function getTableText(table: Table): string;

Get text after a position

declare function getTextAfter(paragraphs: Paragraph[], position: Position, maxChars: number): string;

Get text before a position

declare function getTextBefore(paragraphs: Paragraph[], position: Position, maxChars: number): string;

Check if document body has images

declare function hasImages(body: DocumentBody): boolean;

Check if document body has tables

declare function hasTables(body: DocumentBody): boolean;

Check if style ID represents a heading

declare function isHeadingStyle(styleId?: string): boolean;

Check if a position is within a range

declare function isPositionInRange(position: Position, range: Range): boolean;

Parse heading level from style ID

declare function parseHeadingLevel(styleId?: string): number | undefined;

Classes(1)

DocumentAgent provides a fluent API for document manipulation

declare class DocumentAgent
```ts
const agent = new DocumentAgent(buffer);

// Read operations
const text = agent.getText();
const wordCount = agent.getWordCount();
const variables = agent.getVariables();

// Write operations (returns new agent)
const newAgent = agent
  .insertText({ paragraphIndex: 0, offset: 0 }, 'Hello ', { formatting: { bold: true } })
  .applyStyle({ paragraphIndex: 0, offset: 0 }, { paragraphIndex: 0, offset: 5 }, 'Heading1');

// Export
const newBuffer = await newAgent.toBuffer();
```
MemberTypeSummary
(constructor)Create a new DocumentAgent
applyFormattingApply text formatting to a range
applyParagraphFormattingApply paragraph formatting
applyStyleApply a named style to a paragraph
applyVariablesApply all pending template variables
clearPendingVariablesClear pending variables
deleteRangeDelete text in a range
executeCommandsExecute multiple commands in sequence
fromBufferCreate a DocumentAgent from a DOCX buffer (async)
fromDocumentCreate a DocumentAgent from a Document object
getAgentContextGet document context for AI agents
getCharacterCountGet character count
getDocumentGet the underlying document
getFormattedTextGet formatted text segments
getPageCountGet approximate page count
getParagraphCountGet paragraph count
getPendingVariablesGet pending variable values
getStylesGet available styles from the document
getTableCountGet table count
getTextGet plain text content of the document
getVariablesGet detected template variables
getWordCountGet word count
insertImageInsert an image at a position
insertParagraphBreakInsert a paragraph break
insertTableInsert a table at a position
insertTextInsert text at a position
mergeParagraphsMerge consecutive paragraphs
replaceRangeReplace text in a range
setVariableSet a template variable value
setVariablesSet multiple template variables
toBlobExport document to Blob
toBufferExport document to DOCX ArrayBuffer

Interfaces(36)

Document context for AI agents

interface AgentContext
MemberTypeSummary
availableStylesStyleInfo[]Available styles
characterCountnumberTotal character count
hasImagesbooleanHas images
hasTablesbooleanHas tables
language?stringDocument language
outlineParagraphOutline[]Content outline (first N chars per paragraph)
paragraphCountnumberTotal paragraph count
sectionsSectionInfo[]Document sections info
variableCountnumberVariable count
variablesstring[]Detected template variables
wordCountnumberTotal word count (approximate)
interface

AgentContextOptions

packages/core/src/agent/context.ts:41

Options for building agent context

interface AgentContextOptions
MemberTypeSummary
includeFormatting?booleanInclude detailed formatting info (default: false)
includeTableContent?booleanInclude table content in context (default: false)
maxOutlineParagraphs?numberMaximum paragraphs to include in outline (default: 50)
outlineMaxChars?numberMaximum characters per paragraph in outline (default: 100)

Response from an agent action

interface AgentResponse
MemberTypeSummary
commands?AgentCommand[]Commands to execute
error?stringError message if failed
metadata?Record<string, unknown>Metadata about the response
newContent?AgentContent[]New formatted content
newText?stringNew text to insert (for rewrite/expand/etc.)
successbooleanSuccess status
warnings?string[]Warning messages
interface

AgentSelectionContext

Context about the current selection

interface SelectionContext
MemberTypeSummary
formattingPartial<TextFormatting>Current formatting of selection
inTable?booleanIs selection within a table
paragraphParagraphContextParagraph containing selection
paragraphFormattingPartial<ParagraphFormatting>Current paragraph formatting
rangeRangeSelection range
selectedTextstringSelected text
suggestedActions?SuggestedAction[]Suggested actions based on selection
textAfterstringText after selection (context)
textBeforestringText before selection (context)

AI action request

interface AIActionRequest
MemberTypeSummary
actionAIActionAction type
contextSelectionContextSelection context
customPrompt?stringCustom prompt (for 'custom' action)
options?Record<string, unknown>Additional options
targetLanguage?stringTarget language (for 'translate' action)

Apply a named style to a paragraph

interface ApplyStyleCommand extends BaseCommand
MemberTypeSummary
paragraphIndexnumberParagraph index
styleIdstringStyle ID to apply
type'applyStyle'
interface

ApplyVariablesCommand

packages/core/src/types/agentApi.ts:284

Apply all template variables

interface ApplyVariablesCommand extends BaseCommand
MemberTypeSummary
type'applyVariables'
valuesRecord<string, string>Variable values
interface

ContextSelectionOptions

Options for building selection context

interface SelectionContextOptions$1
MemberTypeSummary
contextChars?numberCharacters of context before/after selection (default: 200)
includeSuggestions?booleanInclude suggested actions (default: true)

Delete text in a range

interface DeleteTextCommand extends BaseCommand
MemberTypeSummary
rangeRangeRange to delete
type'deleteText'
interface

ExtendedSelectionContext

packages/core/src/agent/selectionContext.ts:50

Extended selection context with additional details

interface ExtendedSelectionContext extends SelectionContext
MemberTypeSummary
characterCount?numberSelection character count
contentType?'prose' | 'list' | 'heading' | 'table' | 'mixed'Content type hints
detectedLanguage?stringLanguage detection hint
documentSummary?stringDocument summary for additional context
isMultiParagraph?booleanIs selection multi-paragraph
paragraphIndices?number[]Selected paragraph indices
wordCount?numberSelection word count
interface

FormatParagraphCommand

packages/core/src/types/agentApi.ts:164

Apply paragraph formatting

interface FormatParagraphCommand extends BaseCommand
MemberTypeSummary
formattingPartial<ParagraphFormatting>Formatting to apply
paragraphIndexnumberParagraph index
type'formatParagraph'

Formatted text segment

interface FormattedTextSegment
MemberTypeSummary
formatting?TextFormattingApplied formatting
hyperlinkUrl?stringHyperlink URL if applicable
textstringText content

Apply formatting to a range

interface FormatTextCommand extends BaseCommand
MemberTypeSummary
formattingPartial<TextFormatting>Formatting to apply
rangeRangeRange to format
type'formatText'

Selection formatting summary

interface FormattingSummary
MemberTypeSummary
allFormattingPartial<TextFormatting>[]All formatting found
isConsistentbooleanIs formatting consistent across selection
predominantPartial<TextFormatting>Predominant formatting
interface

InsertHyperlinkCommand

packages/core/src/types/agentApi.ts:220

Insert a hyperlink at a range

interface InsertHyperlinkCommand extends BaseCommand
MemberTypeSummary
displayText?stringDisplay text (replaces range text if provided)
rangeRangeRange to make into a hyperlink
tooltip?stringTooltip
type'insertHyperlink'
urlstringURL of the hyperlink
interface

InsertHyperlinkOptions

packages/core/src/agent/DocumentAgent.ts:81

Options for inserting hyperlink

interface InsertHyperlinkOptions
MemberTypeSummary
displayText?stringDisplay text (overrides selected text)
tooltip?stringTooltip on hover

Insert an image at a position

interface InsertImageCommand extends BaseCommand
MemberTypeSummary
alt?stringAlt text
height?numberImage height in pixels
positionPositionPosition to insert at
srcstringImage source (base64 or URL)
type'insertImage'
width?numberImage width in pixels

Options for inserting image

interface InsertImageOptions
MemberTypeSummary
alt?stringAlt text for accessibility
height?numberImage height in pixels
width?numberImage width in pixels
interface

InsertParagraphBreakCommand

packages/core/src/types/agentApi.ts:244

Insert a paragraph break

interface InsertParagraphBreakCommand extends BaseCommand
MemberTypeSummary
positionPositionPosition to break at
type'insertParagraphBreak'

Insert a table at a position

interface InsertTableCommand extends BaseCommand
MemberTypeSummary
columnsnumberNumber of columns
data?string[][]Optional table data
hasHeader?booleanOptional header row
positionPositionPosition to insert at
rowsnumberNumber of rows
type'insertTable'

Options for inserting table

interface InsertTableOptions
MemberTypeSummary
data?string[][]Table data (2D array of strings)
hasHeader?booleanWhether first row is a header

Insert text at a position

interface InsertTextCommand extends BaseCommand
MemberTypeSummary
formatting?TextFormattingOptional formatting for the inserted text
positionPositionPosition to insert at
textstringText to insert
type'insertText'

Options for inserting text

interface InsertTextOptions
MemberTypeSummary
formatting?TextFormattingText formatting
interface

MergeParagraphsCommand

packages/core/src/types/agentApi.ts:253

Merge paragraphs

interface MergeParagraphsCommand extends BaseCommand
MemberTypeSummary
countnumberNumber of paragraphs to merge with
paragraphIndexnumberFirst paragraph index
type'mergeParagraphs'

Paragraph context for selection

interface ParagraphContext
MemberTypeSummary
fullTextstringFull paragraph text
indexnumberParagraph index
style?stringParagraph style
wordCountnumberWord count

Paragraph outline for context

interface ParagraphOutline
MemberTypeSummary
headingLevel?numberHeading level (1-9)
indexnumberParagraph index
isEmpty?booleanIs empty paragraph
isHeading?booleanIs heading
isListItem?booleanIs list item
previewstringFirst N characters
style?stringParagraph style
interface

Position_2

Position within a document

interface Position
MemberTypeSummary
contentIndex?numberOptional: Content index within paragraph (run, hyperlink, etc.)
offsetnumberOffset within the paragraph in characters
paragraphIndexnumberIndex of the paragraph (0-indexed)
sectionIndex?numberOptional: Section index
interface

Range_2

Range within a document

interface Range
MemberTypeSummary
collapsed?booleanWhether the range is collapsed (cursor position)
endPositionEnd position
startPositionStart position
interface

RemoveHyperlinkCommand

packages/core/src/types/agentApi.ts:235

Remove a hyperlink but keep the text

interface RemoveHyperlinkCommand extends BaseCommand
MemberTypeSummary
rangeRangeRange containing the hyperlink
type'removeHyperlink'

Replace text in a range

interface ReplaceTextCommand extends BaseCommand
MemberTypeSummary
formatting?TextFormattingOptional formatting for the new text
rangeRangeRange to replace
textstringReplacement text
type'replaceText'

Section information

interface SectionInfo
MemberTypeSummary
hasFooter?booleanHas footer
hasHeader?booleanHas header
indexnumberSection index
isLandscape?booleanIs landscape
pageSize?{ width: number; height: number; }Page size
paragraphCountnumberNumber of paragraphs
interface

SelectionContextOptions

packages/core/src/agent/context.ts:55

Options for building selection context

interface SelectionContextOptions
MemberTypeSummary
contextCharsAfter?numberCharacters of context after selection (default: 200)
contextCharsBefore?numberCharacters of context before selection (default: 200)
includeDocumentSummary?booleanInclude document summary (default: true)
includeSuggestions?booleanInclude suggested actions (default: true)
maxSuggestions?numberMaximum suggested actions (default: 8)

Set template variable value

interface SetVariableCommand extends BaseCommand
MemberTypeSummary
namestringVariable name
type'setVariable'
valuestringVariable value
interface

SplitParagraphCommand

packages/core/src/types/agentApi.ts:264

Split a paragraph

interface SplitParagraphCommand extends BaseCommand
MemberTypeSummary
positionPositionPosition to split at
type'splitParagraph'

Style information for context

interface StyleInfo
MemberTypeSummary
builtIn?booleanIs built-in style
idstringStyle ID
namestringDisplay name
type'paragraph' | 'character' | 'table'Style type

Suggested action for context menu

interface SuggestedAction
MemberTypeSummary
description?stringDescription
icon?stringIcon name
idstringAction ID
labelstringDisplay label
priority?numberPriority (higher = more prominent)

Type aliases(2)

Union of all command types

type AgentCommand = InsertTextCommand | ReplaceTextCommand | DeleteTextCommand | FormatTextCommand | FormatParagraphCommand | ApplyStyleCommand | InsertTableCommand | InsertImageCommand | InsertHyperlinkCommand | RemoveHyperlinkCommand | InsertParagraphBreakCommand | MergeParagraphsCommand | SplitParagraphCommand | SetVariableCommand | ApplyVariablesCommand;

AI action types for context menu

type AIAction = 'askAI' | 'rewrite' | 'expand' | 'summarize' | 'translate' | 'explain' | 'fixGrammar' | 'makeFormal' | 'makeCasual' | 'custom';

Variables(1)

Default AI actions for context menu

DEFAULT_AI_ACTIONS: AIAction[]