@wordinweb/agent 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,296 @@
1
+ # `@wordinweb/agent`
2
+
3
+ A complete DOCX creation, inspection, and editing toolkit for AI agents. It
4
+ gives agents progressive, schema-enforced control over document content,
5
+ formatting, review data, tables, equations, drawings, and page layout.
6
+
7
+ The repository includes the installable
8
+ [`wordinweb-documents` agent skill](https://github.com/theRealestAEP/wordinweb/tree/main/skills/wordinweb-documents).
9
+ It teaches agents compact composition and progressive editing. It documents
10
+ the full interface, operation schemas, result types, and composition rules.
11
+
12
+ Install the skill from GitHub for Codex:
13
+
14
+ ```bash
15
+ gh skill install theRealestAEP/wordinweb wordinweb-documents --agent codex --scope user
16
+ ```
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install @wordinweb/agent
22
+ ```
23
+
24
+ ## Live AI invitation
25
+
26
+ An AI invitation link can bootstrap a live shell session without an MCP
27
+ installation:
28
+
29
+ ```bash
30
+ npx -y --package='https://collab.word-in-web.com/wordinweb-agent.tgz?v=short-invite-3' wordinweb-agent connect '<short invitation URL>'
31
+ ```
32
+
33
+ The command starts a detached local bridge, captures the current Codex or
34
+ Claude session, and returns a `sessionId`. The bridge waits without model turns.
35
+ It resumes the agent session when the inviter sends a private message. Run each
36
+ JSON document command through a short process:
37
+
38
+ ```bash
39
+ npx -y --package='https://collab.word-in-web.com/wordinweb-agent.tgz?v=short-invite-3' wordinweb-agent session '<sessionId>' '{"command":"sync"}'
40
+ ```
41
+
42
+ The bridge supports `sync`, `capabilities`, `inspect`, `edit`, `chat`, and
43
+ `close`. `wait` remains available for manual clients. Every edit includes the
44
+ inspected revision. When the room advances, the package compares the edit's
45
+ inspected targets with their current state. Unchanged targets proceed across
46
+ the newer revision. Changed targets return `needs_sync`. The bridge places the
47
+ agent's visible collaboration cursor after its latest edit.
48
+
49
+ For a broad text task, read all non-empty stories in one bounded compact call:
50
+
51
+ ```bash
52
+ npx -y --package='https://collab.word-in-web.com/wordinweb-agent.tgz?v=short-invite-3' wordinweb-agent session '<sessionId>' '{"command":"inspect","request":{"kind":"context"}}'
53
+ ```
54
+
55
+ ## Headless use
56
+
57
+ ```ts
58
+ import { readFile, writeFile } from "node:fs/promises";
59
+ import { AgentDocument } from "@wordinweb/agent";
60
+
61
+ const agentDoc = AgentDocument.load(await readFile("input.docx"), {
62
+ provenance: { author: "Document agent" },
63
+ });
64
+
65
+ const overview = agentDoc.inspect({ kind: "overview" });
66
+ const first = agentDoc.inspect({
67
+ kind: "read",
68
+ story: "body",
69
+ maxBlocks: 20,
70
+ maxCharacters: 12_000,
71
+ });
72
+
73
+ if (!("blocks" in first) || first.blocks[0].type !== "paragraph") {
74
+ throw new Error("Expected a paragraph");
75
+ }
76
+
77
+ const paragraph = first.blocks[0];
78
+ const run = paragraph.runs[0];
79
+ await agentDoc.edit({
80
+ revision: overview.revision,
81
+ operations: [{
82
+ kind: "insertText",
83
+ at: { blockRef: paragraph.ref, runRef: run.ref, offset: 0 },
84
+ text: "Drafted without a browser. ",
85
+ }],
86
+ });
87
+
88
+ await writeFile("output.docx", agentDoc.save());
89
+ ```
90
+
91
+ For new documents, compose the complete structure in one schema-enforced call:
92
+
93
+ ```ts
94
+ const document = AgentDocument.create();
95
+ const result = await document.compose({
96
+ revision: document.revision,
97
+ page: { margins: { top: 0.75, right: 0.75, bottom: 0.75, left: 0.75 } },
98
+ body: [
99
+ { type: "paragraph", text: "Systems Decision Brief", styleId: "Title" },
100
+ { type: "heading", level: 1, text: "Context" },
101
+ { type: "paragraph", text: "The team must select a delivery model." },
102
+ {
103
+ type: "table",
104
+ headerRows: 1,
105
+ rows: [["Option", "Strength"], ["Managed", "Fast delivery"], ["Custom", "Maximum control"]],
106
+ },
107
+ {
108
+ type: "chart",
109
+ widthPx: 520,
110
+ heightPx: 280,
111
+ align: "center",
112
+ chart: {
113
+ type: "column",
114
+ title: "Decision profile",
115
+ categories: ["Control", "Speed"],
116
+ series: [{ name: "Managed", values: [8, 9] }, { name: "Custom", values: [10, 6] }],
117
+ },
118
+ },
119
+ ],
120
+ footer: [{
121
+ type: "pageNumber",
122
+ fieldKind: "pageOfTotal",
123
+ align: "center",
124
+ color: "627D98",
125
+ fontSizePt: 8,
126
+ }],
127
+ });
128
+
129
+ console.log(result.overview.outline, result.createdObjects);
130
+ ```
131
+
132
+ `AgentDocument.create()` starts a blank DOCX. `tools()` returns six portable
133
+ tool objects for composition, capabilities, inspection, edits, asset reads,
134
+ and DOCX saves.
135
+
136
+ ## Progressive inspection
137
+
138
+ For a broad text task, start with `context`. It returns text and edit references
139
+ from all non-empty stories in one response. The default global budget is 100
140
+ blocks and 24,000 characters. It omits formatting, empty metadata, bookmarks,
141
+ and object summaries. Add `include: ["bookmarks", "objects"]` only when the
142
+ task needs those fields.
143
+
144
+ Use `overview` when the task needs page setup, the outline, story counts, or
145
+ object counts. A compose call already returns this overview plus compact
146
+ summaries for created objects. Then use these requests:
147
+
148
+ - `context` returns bounded bulk editing context. Its story cursor can continue
149
+ through `read` when one story exceeds the global budget.
150
+ - `read` returns a bounded block and character window. Use its cursor for the
151
+ next window. It includes detailed formatting, components, bookmarks, and
152
+ table cell references.
153
+ - `search` returns bounded matches with block and run references.
154
+ - `object` expands one equation, image, shape, chart, SmartArt diagram, field,
155
+ note reference, or other inline component.
156
+ - `spatial` returns bounded page geometry. It also computes rotated-object
157
+ intersections, overlap area, and paint order.
158
+ - `asset` reads bytes for an `assetRef` from an object result.
159
+
160
+ Browser layout uses canvas metrics and reports `quality: "exact"`. Headless
161
+ layout uses deterministic approximate metrics and reports
162
+ `quality: "approximate"`. Both modes use the same page layout model.
163
+
164
+ ## References and edit safety
165
+
166
+ The interface exposes opaque stable references for document targets.
167
+
168
+ - `block:*` and `run:*` references identify editable nodes.
169
+ - `object:*` references identify inspectable components and supported drawing edit targets.
170
+ - `view:*` references identify render-only content, such as cached SmartArt
171
+ text or endnote content that the current editor cannot mutate.
172
+ - An object result contains `editRef` only when an edit target exists.
173
+
174
+ Every edit includes the revision that the agent inspected. A newer revision
175
+ triggers a fingerprint comparison for the referenced paragraphs, tables, and
176
+ objects. Unchanged targets proceed, while changed targets request a new
177
+ inspection. Document-wide operations use the global revision. Operation schemas
178
+ reject extra fields, internal IDs, bad reference types, and invalid canonical
179
+ intents. Local batches apply to a clone first, so a failed operation leaves the
180
+ source document unchanged.
181
+
182
+ Call `capabilities(category, kind)` or the capabilities tool before an edit.
183
+ This returns a closed JSON Schema for the selected operation. The package
184
+ exposes every canonical WordInWeb edit intent.
185
+
186
+ The portable edit tool embeds every operation schema as a discriminated
187
+ union. Nested patches, chart data, SmartArt data, table operations, and page
188
+ layout values use closed schemas.
189
+
190
+ Objects placed in a header or footer story repeat on the applicable section
191
+ pages. Insert a line with `insertShape`, then use its `editRef` with position,
192
+ size, rotation, line-style, order, or removal operations. The same operations
193
+ apply to Word-authored VML lines.
194
+
195
+ ## Solo browser session
196
+
197
+ Use `LocalDocumentSession` when a human and an agent edit the same local page.
198
+ The session owns one `DocxDocument`. Agent edits and `DocxView` edits pass
199
+ through the same canonical apply path.
200
+
201
+ ```tsx
202
+ import { useMemo } from "react";
203
+ import { DocxView, useAgentDocumentSession } from "wordinweb";
204
+ import {
205
+ AgentDocument,
206
+ LocalDocumentSession,
207
+ localDocumentViewBinding,
208
+ } from "@wordinweb/agent";
209
+
210
+ export function LocalEditor({ bytes }: { bytes: Uint8Array }) {
211
+ const session = useMemo(() => new LocalDocumentSession(bytes), [bytes]);
212
+ const binding = useMemo(() => localDocumentViewBinding(session), [session]);
213
+ const view = useAgentDocumentSession(binding);
214
+
215
+ // Give this object, or agentDoc.tools(), to the host agent runtime.
216
+ const agentDoc = useMemo(() => AgentDocument.connect(session), [session]);
217
+ void agentDoc;
218
+
219
+ return <DocxView {...view} editable style={{ height: "100vh" }} />;
220
+ }
221
+ ```
222
+
223
+ ## Collaborative and offline sessions
224
+
225
+ The existing React collaboration session already owns the live document,
226
+ stable ID allocator, media relay, and offline tail. Adapt that session without
227
+ adding React to this package:
228
+
229
+ ```ts
230
+ import {
231
+ AgentDocument,
232
+ collaborativeAgentTarget,
233
+ } from "@wordinweb/agent";
234
+
235
+ const agentDoc = AgentDocument.connect(
236
+ collaborativeAgentTarget(() => currentCollabSession),
237
+ { provenance: { author: "Document agent" } },
238
+ );
239
+ ```
240
+
241
+ The callback must return the latest `useCollab` session after each React
242
+ render. The agent API stays the same in all modes.
243
+
244
+ | Mode | Document owner | Edit route | Browser required |
245
+ | --- | --- | --- | --- |
246
+ | Headless | `AgentDocument` | Local atomic clone | No |
247
+ | Solo browser | `LocalDocumentSession` | Canonical local session | Yes, for review and human edits |
248
+ | Live collaboration | `useCollab` session | Sequenced room intent | Yes, for the room client |
249
+ | Offline collaboration | `useCollab` session | Durable offline intent tail | Yes, for the offline client |
250
+
251
+ An offline agent edit applies to the local replica and enters the same durable
252
+ tail as a human edit. Reconnect uses the existing replay and reconciliation
253
+ flow. A live agent edit passes through the existing server sequence and reaches
254
+ all collaborators.
255
+
256
+ ## Fixture and coverage gates
257
+
258
+ `npm run test:agent-fixtures` audits every DOCX in the WordInWeb parity corpus.
259
+ It checks semantic components, object detail, assets, JSON safety, every story,
260
+ every page, and overlap geometry.
261
+
262
+ Typed exhaustive gates cover canonical intents, agent capabilities, run
263
+ components, layout primitives, canonical apply, canonical validation, and DOM
264
+ rendering. The browser convergence test consumes the same canonical intent
265
+ list. A new edit or component must reach each surface before the build passes.
266
+
267
+ The repository also includes actual Codex skill evaluations. Each natural
268
+ document request starts a fresh Codex process in a temporary workspace,
269
+ installs this repository skill, creates a DOCX through the public package, and
270
+ scores the output through semantic, spatial, asset, story, section, and OOXML
271
+ evidence. The requests cover a technical brief, branded media guide, field
272
+ inspection packet, policy review copy, and visual strategy report.
273
+
274
+ ```bash
275
+ npm run test:agent-skill:codex
276
+ ```
277
+
278
+ Pass fixture names after `--` to run a focused evaluation:
279
+
280
+ ```bash
281
+ npm run test:agent-skill:codex -- media-brand-guide policy-review-copy
282
+ ```
283
+
284
+ Set `WORDINWEB_AGENT_EVAL_MODEL` to select a model. Set
285
+ `WORDINWEB_KEEP_AGENT_EVAL=1` to retain the temporary workspace for review.
286
+
287
+ `npm run test:agent-skill` checks that the GitHub skill documents every runtime
288
+ tool, inspection mode, reference family, edit operation, and agent-facing
289
+ field. It also validates every portable authoring fixture. Supply a DOCX and
290
+ its fixture name to run the complete scorer:
291
+
292
+ ```bash
293
+ WORDINWEB_AGENT_EVAL_OUTPUT=/path/to/output.docx \
294
+ WORDINWEB_AGENT_EVAL_FIXTURE=media-brand-guide \
295
+ npm run test:agent-skill
296
+ ```