@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)
buildExtendedSelectionContext
Build extended selection context with additional details
declare function buildExtendedSelectionContext(doc: Document, range: Range, options?: SelectionContextOptions): ExtendedSelectionContext;buildSelectionContext
Build selection context for AI operations
declare function buildSelectionContext(doc: Document, range: Range, options?: SelectionContextOptions): SelectionContext;buildSelectionContextFromContext
Build selection context for AI operations
declare function buildSelectionContext$1(doc: Document, range: Range, options?: SelectionContextOptions$1): SelectionContext;comparePositions
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;countCharacters
Count characters in text
declare function countCharacters(text: string, includeSpaces?: boolean): number;countWords
Count words in text
declare function countWords(text: string): number;createAgent
Create a DocumentAgent from a DOCX buffer
declare function createAgent(buffer: ArrayBuffer): Promise<DocumentAgent>;createAgentFromDocument
Create a DocumentAgent from a parsed Document
declare function createAgentFromDocument(document: Document): DocumentAgent;createCollapsedRange
Create a collapsed range (cursor) at a position
declare function createCollapsedRange(position: Position): Range;createCommand
Create a command with generated ID
declare function createCommand<T extends AgentCommand>(command: Omit<T, 'id'>): T;createRange
Create a range from two positions
declare function createRange(start: Position, end: Position): Range;executeCommand
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;executeCommands
Execute multiple commands in sequence
declare function executeCommands(doc: Document, commands: AgentCommand[]): Document;getActionDescription
Get action description
declare function getActionDescription(action: AIAction): string;getActionLabel
Get action label
declare function getActionLabel(action: AIAction): string;getAgentContext
Build agent context from a document
declare function getAgentContext(doc: Document, options?: AgentContextOptions): AgentContext;getBlockIndexForParagraph
Get block index for a paragraph index
declare function getBlockIndexForParagraph(body: DocumentBody, paragraphIndex: number): number;getBodyCharacterCount
Get character count from document body
declare function getBodyCharacterCount(body: DocumentBody): number;getBodyText
Get plain text from document body
declare function getBodyText(body: DocumentBody): string;getBodyWordCount
Get word count from document body
declare function getBodyWordCount(body: DocumentBody): number;getDocumentSummary
Get a simple document summary for quick context
declare function getDocumentSummary(doc: Document): string;getFormattingAtPosition
Get formatting at a specific position in a paragraph
declare function getFormattingAtPosition(paragraph: Paragraph, offset: number): Partial<TextFormatting>;getHyperlinkAtPosition
Get hyperlink at position
declare function getHyperlinkAtPosition(paragraph: Paragraph, offset: number): Hyperlink | undefined;getHyperlinkText
Get plain text from a hyperlink
declare function getHyperlinkText(hyperlink: Hyperlink): string;getParagraphAtIndex
Get paragraph at index from document body
declare function getParagraphAtIndex(body: DocumentBody, index: number): Paragraph | undefined;getParagraphs
Get all paragraphs from document body
declare function getParagraphs(body: DocumentBody): Paragraph[];getParagraphText
Get plain text from a paragraph
declare function getParagraphText(paragraph: Paragraph): string;getRunText
Get plain text from a run
declare function getRunText(run: Run): string;getSelectionFormattingSummary
Get formatting summary for a selection
declare function getSelectionFormattingSummary(doc: Document, range: Range): FormattingSummary;getTableText
Get plain text from a table
declare function getTableText(table: Table): string;getTextAfter
Get text after a position
declare function getTextAfter(paragraphs: Paragraph[], position: Position, maxChars: number): string;getTextBefore
Get text before a position
declare function getTextBefore(paragraphs: Paragraph[], position: Position, maxChars: number): string;hasHyperlinks
Check if document body has hyperlinks
declare function hasHyperlinks(body: DocumentBody): boolean;hasImages
Check if document body has images
declare function hasImages(body: DocumentBody): boolean;hasTables
Check if document body has tables
declare function hasTables(body: DocumentBody): boolean;isHeadingStyle
Check if style ID represents a heading
declare function isHeadingStyle(styleId?: string): boolean;isPositionInHyperlink
Check if position is within a hyperlink
declare function isPositionInHyperlink(paragraph: Paragraph, offset: number): boolean;isPositionInRange
Check if a position is within a range
declare function isPositionInRange(position: Position, range: Range): boolean;parseHeadingLevel
Parse heading level from style ID
declare function parseHeadingLevel(styleId?: string): number | undefined;Classes(1)
DocumentAgent
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();
```| Member | Type | Summary |
|---|---|---|
| (constructor) | — | Create a new DocumentAgent |
| applyFormatting | — | Apply text formatting to a range |
| applyParagraphFormatting | — | Apply paragraph formatting |
| applyStyle | — | Apply a named style to a paragraph |
| applyVariables | — | Apply all pending template variables |
| clearPendingVariables | — | Clear pending variables |
| deleteRange | — | Delete text in a range |
| executeCommands | — | Execute multiple commands in sequence |
| fromBuffer | — | Create a DocumentAgent from a DOCX buffer (async) |
| fromDocument | — | Create a DocumentAgent from a Document object |
| getAgentContext | — | Get document context for AI agents |
| getCharacterCount | — | Get character count |
| getDocument | — | Get the underlying document |
| getFormattedText | — | Get formatted text segments |
| getPageCount | — | Get approximate page count |
| getParagraphCount | — | Get paragraph count |
| getPendingVariables | — | Get pending variable values |
| getStyles | — | Get available styles from the document |
| getTableCount | — | Get table count |
| getText | — | Get plain text content of the document |
| getVariables | — | Get detected template variables |
| getWordCount | — | Get word count |
| insertHyperlink | — | Insert a hyperlink |
| insertImage | — | Insert an image at a position |
| insertParagraphBreak | — | Insert a paragraph break |
| insertTable | — | Insert a table at a position |
| insertText | — | Insert text at a position |
| mergeParagraphs | — | Merge consecutive paragraphs |
| removeHyperlink | — | Remove a hyperlink but keep the text |
| replaceRange | — | Replace text in a range |
| setVariable | — | Set a template variable value |
| setVariables | — | Set multiple template variables |
| toBlob | — | Export document to Blob |
| toBuffer | — | Export document to DOCX ArrayBuffer |
Interfaces(36)
AgentContext
Document context for AI agents
interface AgentContext| Member | Type | Summary |
|---|---|---|
| availableStyles | StyleInfo[] | Available styles |
| characterCount | number | Total character count |
| hasHyperlinks | boolean | Has hyperlinks |
| hasImages | boolean | Has images |
| hasTables | boolean | Has tables |
| language? | string | Document language |
| outline | ParagraphOutline[] | Content outline (first N chars per paragraph) |
| paragraphCount | number | Total paragraph count |
| sections | SectionInfo[] | Document sections info |
| variableCount | number | Variable count |
| variables | string[] | Detected template variables |
| wordCount | number | Total word count (approximate) |
AgentContextOptions
Options for building agent context
interface AgentContextOptions| Member | Type | Summary |
|---|---|---|
| includeFormatting? | boolean | Include detailed formatting info (default: false) |
| includeTableContent? | boolean | Include table content in context (default: false) |
| maxOutlineParagraphs? | number | Maximum paragraphs to include in outline (default: 50) |
| outlineMaxChars? | number | Maximum characters per paragraph in outline (default: 100) |
AgentResponse
Response from an agent action
interface AgentResponse| Member | Type | Summary |
|---|---|---|
| commands? | AgentCommand[] | Commands to execute |
| error? | string | Error message if failed |
| metadata? | Record<string, unknown> | Metadata about the response |
| newContent? | AgentContent[] | New formatted content |
| newText? | string | New text to insert (for rewrite/expand/etc.) |
| success | boolean | Success status |
| warnings? | string[] | Warning messages |
AgentSelectionContext
Context about the current selection
interface SelectionContext| Member | Type | Summary |
|---|---|---|
| formatting | Partial<TextFormatting> | Current formatting of selection |
| inHyperlink? | boolean | Is selection within a hyperlink |
| inTable? | boolean | Is selection within a table |
| paragraph | ParagraphContext | Paragraph containing selection |
| paragraphFormatting | Partial<ParagraphFormatting> | Current paragraph formatting |
| range | Range | Selection range |
| selectedText | string | Selected text |
| suggestedActions? | SuggestedAction[] | Suggested actions based on selection |
| textAfter | string | Text after selection (context) |
| textBefore | string | Text before selection (context) |
AIActionRequest
AI action request
interface AIActionRequest| Member | Type | Summary |
|---|---|---|
| action | AIAction | Action type |
| context | SelectionContext | Selection context |
| customPrompt? | string | Custom prompt (for 'custom' action) |
| options? | Record<string, unknown> | Additional options |
| targetLanguage? | string | Target language (for 'translate' action) |
ApplyStyleCommand
Apply a named style to a paragraph
interface ApplyStyleCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| paragraphIndex | number | Paragraph index |
| styleId | string | Style ID to apply |
| type | 'applyStyle' |
ApplyVariablesCommand
Apply all template variables
interface ApplyVariablesCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| type | 'applyVariables' | |
| values | Record<string, string> | Variable values |
ContextSelectionOptions
Options for building selection context
interface SelectionContextOptions$1| Member | Type | Summary |
|---|---|---|
| contextChars? | number | Characters of context before/after selection (default: 200) |
| includeSuggestions? | boolean | Include suggested actions (default: true) |
DeleteTextCommand
Delete text in a range
interface DeleteTextCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| range | Range | Range to delete |
| type | 'deleteText' |
ExtendedSelectionContext
Extended selection context with additional details
interface ExtendedSelectionContext extends SelectionContext| Member | Type | Summary |
|---|---|---|
| characterCount? | number | Selection character count |
| contentType? | 'prose' | 'list' | 'heading' | 'table' | 'mixed' | Content type hints |
| detectedLanguage? | string | Language detection hint |
| documentSummary? | string | Document summary for additional context |
| isMultiParagraph? | boolean | Is selection multi-paragraph |
| paragraphIndices? | number[] | Selected paragraph indices |
| wordCount? | number | Selection word count |
FormatParagraphCommand
Apply paragraph formatting
interface FormatParagraphCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| formatting | Partial<ParagraphFormatting> | Formatting to apply |
| paragraphIndex | number | Paragraph index |
| type | 'formatParagraph' |
FormattedTextSegment
Formatted text segment
interface FormattedTextSegment| Member | Type | Summary |
|---|---|---|
| formatting? | TextFormatting | Applied formatting |
| hyperlinkUrl? | string | Hyperlink URL if applicable |
| isHyperlink? | boolean | Is part of a hyperlink |
| text | string | Text content |
FormatTextCommand
Apply formatting to a range
interface FormatTextCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| formatting | Partial<TextFormatting> | Formatting to apply |
| range | Range | Range to format |
| type | 'formatText' |
FormattingSummary
Selection formatting summary
interface FormattingSummary| Member | Type | Summary |
|---|---|---|
| allFormatting | Partial<TextFormatting>[] | All formatting found |
| isConsistent | boolean | Is formatting consistent across selection |
| predominant | Partial<TextFormatting> | Predominant formatting |
InsertHyperlinkCommand
Insert a hyperlink at a range
interface InsertHyperlinkCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| displayText? | string | Display text (replaces range text if provided) |
| range | Range | Range to make into a hyperlink |
| tooltip? | string | Tooltip |
| type | 'insertHyperlink' | |
| url | string | URL of the hyperlink |
InsertHyperlinkOptions
Options for inserting hyperlink
interface InsertHyperlinkOptions| Member | Type | Summary |
|---|---|---|
| displayText? | string | Display text (overrides selected text) |
| tooltip? | string | Tooltip on hover |
InsertImageCommand
Insert an image at a position
interface InsertImageCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| alt? | string | Alt text |
| height? | number | Image height in pixels |
| position | Position | Position to insert at |
| src | string | Image source (base64 or URL) |
| type | 'insertImage' | |
| width? | number | Image width in pixels |
InsertImageOptions
Options for inserting image
interface InsertImageOptions| Member | Type | Summary |
|---|---|---|
| alt? | string | Alt text for accessibility |
| height? | number | Image height in pixels |
| width? | number | Image width in pixels |
InsertParagraphBreakCommand
Insert a paragraph break
interface InsertParagraphBreakCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| position | Position | Position to break at |
| type | 'insertParagraphBreak' |
InsertTableCommand
Insert a table at a position
interface InsertTableCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| columns | number | Number of columns |
| data? | string[][] | Optional table data |
| hasHeader? | boolean | Optional header row |
| position | Position | Position to insert at |
| rows | number | Number of rows |
| type | 'insertTable' |
InsertTableOptions
Options for inserting table
interface InsertTableOptions| Member | Type | Summary |
|---|---|---|
| data? | string[][] | Table data (2D array of strings) |
| hasHeader? | boolean | Whether first row is a header |
InsertTextCommand
Insert text at a position
interface InsertTextCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| formatting? | TextFormatting | Optional formatting for the inserted text |
| position | Position | Position to insert at |
| text | string | Text to insert |
| type | 'insertText' |
InsertTextOptions
Options for inserting text
interface InsertTextOptions| Member | Type | Summary |
|---|---|---|
| formatting? | TextFormatting | Text formatting |
MergeParagraphsCommand
Merge paragraphs
interface MergeParagraphsCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| count | number | Number of paragraphs to merge with |
| paragraphIndex | number | First paragraph index |
| type | 'mergeParagraphs' |
ParagraphContext
Paragraph context for selection
interface ParagraphContext| Member | Type | Summary |
|---|---|---|
| fullText | string | Full paragraph text |
| index | number | Paragraph index |
| style? | string | Paragraph style |
| wordCount | number | Word count |
ParagraphOutline
Paragraph outline for context
interface ParagraphOutline| Member | Type | Summary |
|---|---|---|
| headingLevel? | number | Heading level (1-9) |
| index | number | Paragraph index |
| isEmpty? | boolean | Is empty paragraph |
| isHeading? | boolean | Is heading |
| isListItem? | boolean | Is list item |
| preview | string | First N characters |
| style? | string | Paragraph style |
Position_2
Position within a document
interface Position| Member | Type | Summary |
|---|---|---|
| contentIndex? | number | Optional: Content index within paragraph (run, hyperlink, etc.) |
| offset | number | Offset within the paragraph in characters |
| paragraphIndex | number | Index of the paragraph (0-indexed) |
| sectionIndex? | number | Optional: Section index |
Range_2
Range within a document
interface Range| Member | Type | Summary |
|---|---|---|
| collapsed? | boolean | Whether the range is collapsed (cursor position) |
| end | Position | End position |
| start | Position | Start position |
RemoveHyperlinkCommand
Remove a hyperlink but keep the text
interface RemoveHyperlinkCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| range | Range | Range containing the hyperlink |
| type | 'removeHyperlink' |
ReplaceTextCommand
Replace text in a range
interface ReplaceTextCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| formatting? | TextFormatting | Optional formatting for the new text |
| range | Range | Range to replace |
| text | string | Replacement text |
| type | 'replaceText' |
SectionInfo
Section information
interface SectionInfo| Member | Type | Summary |
|---|---|---|
| hasFooter? | boolean | Has footer |
| hasHeader? | boolean | Has header |
| index | number | Section index |
| isLandscape? | boolean | Is landscape |
| pageSize? | {
width: number;
height: number;
} | Page size |
| paragraphCount | number | Number of paragraphs |
SelectionContextOptions
Options for building selection context
interface SelectionContextOptions| Member | Type | Summary |
|---|---|---|
| contextCharsAfter? | number | Characters of context after selection (default: 200) |
| contextCharsBefore? | number | Characters of context before selection (default: 200) |
| includeDocumentSummary? | boolean | Include document summary (default: true) |
| includeSuggestions? | boolean | Include suggested actions (default: true) |
| maxSuggestions? | number | Maximum suggested actions (default: 8) |
SetVariableCommand
Set template variable value
interface SetVariableCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| name | string | Variable name |
| type | 'setVariable' | |
| value | string | Variable value |
SplitParagraphCommand
Split a paragraph
interface SplitParagraphCommand extends BaseCommand| Member | Type | Summary |
|---|---|---|
| position | Position | Position to split at |
| type | 'splitParagraph' |
StyleInfo
Style information for context
interface StyleInfo| Member | Type | Summary |
|---|---|---|
| builtIn? | boolean | Is built-in style |
| id | string | Style ID |
| name | string | Display name |
| type | 'paragraph' | 'character' | 'table' | Style type |
SuggestedAction
Suggested action for context menu
interface SuggestedAction| Member | Type | Summary |
|---|---|---|
| description? | string | Description |
| icon? | string | Icon name |
| id | string | Action ID |
| label | string | Display label |
| priority? | number | Priority (higher = more prominent) |
Type aliases(2)
AgentCommand
Union of all command types
type AgentCommand = InsertTextCommand | ReplaceTextCommand | DeleteTextCommand | FormatTextCommand | FormatParagraphCommand | ApplyStyleCommand | InsertTableCommand | InsertImageCommand | InsertHyperlinkCommand | RemoveHyperlinkCommand | InsertParagraphBreakCommand | MergeParagraphsCommand | SplitParagraphCommand | SetVariableCommand | ApplyVariablesCommand;AIAction
AI action types for context menu
type AIAction = 'askAI' | 'rewrite' | 'expand' | 'summarize' | 'translate' | 'explain' | 'fixGrammar' | 'makeFormal' | 'makeCasual' | 'custom';Variables(1)
DEFAULT_AI_ACTIONS
Default AI actions for context menu
DEFAULT_AI_ACTIONS: AIAction[]