@folijs/agent 0.3.2 → 0.4.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.
Files changed (65) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +124 -21
  3. package/dist/changes.d.ts +23 -0
  4. package/dist/changes.d.ts.map +1 -0
  5. package/dist/changes.js +136 -0
  6. package/dist/changes.js.map +1 -0
  7. package/dist/formatting.d.ts +24 -0
  8. package/dist/formatting.d.ts.map +1 -0
  9. package/dist/formatting.js +106 -0
  10. package/dist/formatting.js.map +1 -0
  11. package/dist/handles.js +32 -12
  12. package/dist/handles.js.map +1 -1
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +3 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/inserts.d.ts +42 -0
  18. package/dist/inserts.d.ts.map +1 -0
  19. package/dist/inserts.js +242 -0
  20. package/dist/inserts.js.map +1 -0
  21. package/dist/operations.d.ts.map +1 -1
  22. package/dist/operations.js +52 -27
  23. package/dist/operations.js.map +1 -1
  24. package/dist/paragraphs.d.ts +16 -0
  25. package/dist/paragraphs.d.ts.map +1 -0
  26. package/dist/paragraphs.js +146 -0
  27. package/dist/paragraphs.js.map +1 -0
  28. package/dist/read.d.ts +15 -1
  29. package/dist/read.d.ts.map +1 -1
  30. package/dist/read.js +138 -6
  31. package/dist/read.js.map +1 -1
  32. package/dist/schema.d.ts +25 -0
  33. package/dist/schema.d.ts.map +1 -0
  34. package/dist/schema.js +51 -0
  35. package/dist/schema.js.map +1 -0
  36. package/dist/session.d.ts +79 -2
  37. package/dist/session.d.ts.map +1 -1
  38. package/dist/session.js +147 -18
  39. package/dist/session.js.map +1 -1
  40. package/dist/stories.d.ts +2 -0
  41. package/dist/stories.d.ts.map +1 -0
  42. package/dist/stories.js +80 -0
  43. package/dist/stories.js.map +1 -0
  44. package/dist/tables.d.ts +21 -0
  45. package/dist/tables.d.ts.map +1 -0
  46. package/dist/tables.js +485 -0
  47. package/dist/tables.js.map +1 -0
  48. package/dist/tools.d.ts +89 -0
  49. package/dist/tools.d.ts.map +1 -0
  50. package/dist/tools.js +717 -0
  51. package/dist/tools.js.map +1 -0
  52. package/package.json +4 -4
  53. package/src/changes.ts +193 -0
  54. package/src/formatting.ts +149 -0
  55. package/src/handles.ts +40 -13
  56. package/src/index.ts +23 -0
  57. package/src/inserts.ts +339 -0
  58. package/src/operations.ts +71 -34
  59. package/src/paragraphs.ts +188 -0
  60. package/src/read.ts +141 -9
  61. package/src/schema.ts +74 -0
  62. package/src/session.ts +256 -20
  63. package/src/stories.ts +92 -0
  64. package/src/tables.ts +664 -0
  65. package/src/tools.ts +925 -0
package/src/tools.ts ADDED
@@ -0,0 +1,925 @@
1
+ /**
2
+ * The tools (ADR-0013): what a model is given to edit a session's document, with the words it
3
+ * reads (names, descriptions, JSON Schemas, the instructions). An app running its own model
4
+ * loop gives it `agentTools(session)`; `@folijs/mcp` serves the same definitions, and its code
5
+ * mode (`run`) gets its methods from them.
6
+ */
7
+ import type { Ok, Result } from "./result.js";
8
+ import { invalid, type JsonSchema, type JsonSchemaOrAny } from "./schema.js";
9
+ import type { Session } from "./session.js";
10
+ import { UNTRACKED_TABLE_EDIT } from "./tables.js";
11
+ import type { Control } from "./templates.js";
12
+
13
+ /** Blocks the `read` tool gives when it is not told how many. */
14
+ export const READ_LIMIT = 200;
15
+
16
+ /**
17
+ * What to say to the model once, before the tools (a system prompt's part). Each tool's
18
+ * description stands without it.
19
+ */
20
+ export const INSTRUCTIONS = `These tools read and edit Word documents (.docx). Every edit is a tracked change a person will accept or reject in Word: change only what the task asks, and use comment to explain a change that is not obvious.
21
+
22
+ Work on what read shows. read gives the document a line per block:
23
+ [b7] Clause, 1.1, changed: text
24
+ [b7] is the block's handle: pass it to the other tools. After it come where the block is in a table (r1 c1: row and grid column; c1-2 a cell spanning two; "merged down" or "merged up" a vertical merge, its text in the top cell), its style, its list number, "changed" if it has tracked changes, its comments; after the colon, its text. ↵ is a line break. A line "table, 3 rows, 2 columns" is a table: its cells' blocks follow, indented. A line "not editable: …" is content you cannot change.
25
+ Words in brackets ([picture], [note], [empty: Offer date]) are not text: never put them in find. [empty: …] is a content control to fill with fill_control; «Name» is a merge field to fill with update_fields.
26
+ A handle stays its block's while you edit; a deleted block's is refused. A tool that changes the document returns the blocks it changed as they are now: do not read again to check (after update_fields do: it returns none). When a tool refuses, its message says what to do instead: follow it.
27
+ read shows the body; read with headers also shows the headers and footers after the body (in a read in parts, after its last part), their handles h1, f1…, which the same tools edit: no comments, breaks or notes go there, and their content controls are not filled. The text of notes ([note]) is not shown.`;
28
+
29
+ /** What a tool answers the model: text, and whether it is a refusal. */
30
+ export interface ToolAnswer {
31
+ text: string;
32
+ isError?: boolean;
33
+ }
34
+
35
+ /** A tool bound to a session: give the model its name, description and schema; call `run`. */
36
+ export interface AgentTool {
37
+ name: string;
38
+ /** For the model: what it does, when to use it, what it returns. */
39
+ description: string;
40
+ /** Its arguments, as a JSON Schema object. */
41
+ inputSchema: JsonSchema & { type: "object" };
42
+ /** Does what the model asked; arguments that do not fit the schema are refused in words. */
43
+ run(args?: Record<string, unknown>): ToolAnswer;
44
+ }
45
+
46
+ /**
47
+ * A method of code mode's `doc` (ADR-0010): what a script calls instead of a tool. A refusal
48
+ * is thrown as an `Error` with its message.
49
+ */
50
+ export interface ScriptMethod {
51
+ name: string;
52
+ /** Its line in the summary of `doc` a model is given. */
53
+ signature: string;
54
+ /**
55
+ * What a run counts of it: `edit`, the blocks its value's `blocks` are; `insert`, those and
56
+ * how many; `delete`, a block deleted or emptied; `fields`, fields updated.
57
+ */
58
+ effect?: "edit" | "insert" | "delete" | "fields";
59
+ call(session: Session, args: readonly unknown[], host?: ToolHost): unknown;
60
+ }
61
+
62
+ /**
63
+ * What the app gives the tools that the document does not hold (23.6): a picture's bytes for a
64
+ * path the model names. Without it, pictures are refused.
65
+ */
66
+ export interface ToolHost {
67
+ picture?(path: string): Result<{ data: Uint8Array; contentType?: string }>;
68
+ }
69
+
70
+ /** A tool over any session: what `agentTools` binds, and what a server serves. */
71
+ export interface ToolDefinition {
72
+ name: string;
73
+ description: string;
74
+ inputSchema: JsonSchema & { type: "object" };
75
+ /**
76
+ * Arguments are taken as checked against `inputSchema` (`invalid` first: `agentTools` does);
77
+ * others may be there.
78
+ */
79
+ run(session: Session, args: Record<string, unknown>, host?: ToolHost): ToolAnswer;
80
+ /** Its methods in code mode, in the order they are listed. */
81
+ methods: readonly ScriptMethod[];
82
+ /** Only for a session that reviews changes (`SessionOptions.review`, 23.8). */
83
+ review?: true;
84
+ }
85
+
86
+ const HANDLE: JsonSchema = {
87
+ type: "string",
88
+ description: "The block's handle, from a read line: b7.",
89
+ };
90
+ const args = (
91
+ properties: Record<string, JsonSchemaOrAny>,
92
+ required: readonly string[] = [],
93
+ ): JsonSchema & { type: "object" } => ({
94
+ type: "object",
95
+ properties,
96
+ required,
97
+ additionalProperties: false,
98
+ });
99
+
100
+ /** A result of the library as a tool's: its text, or its refusal's message. */
101
+ const told = (
102
+ result: { ok: true; text: string } | { ok: false; message: string },
103
+ more = "",
104
+ ): ToolAnswer =>
105
+ result.ok ? { text: result.text + more } : { text: result.message, isError: true };
106
+
107
+ /** A result for a script: its refusal thrown. */
108
+ const given = <T>(result: Result<T>): Ok<T> => {
109
+ if (!result.ok) throw new Error(result.message);
110
+ return result;
111
+ };
112
+
113
+ const control = (c: Control) =>
114
+ [
115
+ `${c.name} (${c.kind}${c.readOnly ? ", locked" : ""}), in [${c.block}]: `,
116
+ c.empty ? "empty" : JSON.stringify(c.value),
117
+ c.items ? `; one of ${c.items.map((i) => JSON.stringify(i)).join(", ")}` : "",
118
+ c.name !== c.id ? `; id ${JSON.stringify(c.id)}` : "",
119
+ ].join("");
120
+
121
+ // A script's arguments are JSON of any shape: the library refuses what does not fit, as it does
122
+ // for a tool, so they are passed as they come.
123
+ type Args = readonly [never, never, never, never];
124
+
125
+ /** The tools, in the order a model is given them. */
126
+ export const AGENT_TOOLS: readonly ToolDefinition[] = [
127
+ {
128
+ name: "read",
129
+ description: `Reads an open document: its body as it would be with every tracked change accepted, a line per block, each starting with its handle. Reads ${READ_LIMIT} blocks unless limit says otherwise; a long document is read in parts with from.`,
130
+ inputSchema: args({
131
+ from: { ...HANDLE, description: "Start at this block's handle. Default: the first block." },
132
+ limit: {
133
+ type: "integer",
134
+ minimum: 1,
135
+ maximum: 2000,
136
+ description: "At most this many blocks.",
137
+ },
138
+ formatting: {
139
+ type: "boolean",
140
+ description:
141
+ "Also show each paragraph's text formatting of its own (bold, font, size, color, links), on a line under it.",
142
+ },
143
+ headers: {
144
+ type: "boolean",
145
+ description:
146
+ "Also read the headers and footers after the body (in parts: after the last part), each under a line saying where it is used. Their handles are h1, f1…; the other tools edit them as the body's, but for comments, breaks, notes and content controls.",
147
+ },
148
+ }),
149
+ run(session, { from, limit, formatting, headers }) {
150
+ const result = session.read({
151
+ ...(from === undefined ? {} : { from: from as string }),
152
+ limit: (limit as number | undefined) ?? READ_LIMIT,
153
+ ...(formatting === true ? { formatting: true } : {}),
154
+ ...(headers === true ? { headers: true } : {}),
155
+ });
156
+ return told(result, result.ok && result.next ? `\n(more: read from "${result.next}")` : "");
157
+ },
158
+ methods: [
159
+ {
160
+ name: "blocks",
161
+ signature:
162
+ "doc.blocks({ formatting?, headers? }): Block[] // every block of the body (headers: then headers' and footers', each with story), in order, as it reads now (a copy: call again after edits)",
163
+ call: (session, [a]: Args) => {
164
+ const options = (a ?? {}) as { formatting?: unknown; headers?: unknown };
165
+ return given(
166
+ session.read({
167
+ formatting: options.formatting === true,
168
+ headers: options.headers === true,
169
+ }),
170
+ ).blocks;
171
+ },
172
+ },
173
+ {
174
+ name: "block",
175
+ signature: "doc.block(handle): Block",
176
+ call: (session, [a]: Args) => given(session.block(a)).block,
177
+ },
178
+ ],
179
+ },
180
+ {
181
+ name: "replace_text",
182
+ description:
183
+ 'Replaces text in one paragraph, as a tracked change. find is the exact text as read shows it, capitals and spaces included, long enough to be in the block once (or pass all). The replacement takes the formatting of what it replaces; "" deletes. Returns the block as it reads now.',
184
+ inputSchema: args(
185
+ {
186
+ handle: HANDLE,
187
+ find: { type: "string", description: "The text to replace, exactly as read shows it." },
188
+ replacement: {
189
+ type: "string",
190
+ description: 'The new text. ↵ is a line break. "" deletes.',
191
+ },
192
+ all: { type: "boolean", description: "Replace every place find is in the block." },
193
+ },
194
+ ["handle", "find", "replacement"],
195
+ ),
196
+ run: (session, { handle, find, replacement, all }) =>
197
+ told(
198
+ session.replaceText(handle as string, find as string, replacement as string, {
199
+ all: all === true,
200
+ }),
201
+ ),
202
+ methods: [
203
+ {
204
+ name: "replaceText",
205
+ signature:
206
+ "doc.replaceText(handle, find, replacement, { all? }): { blocks, replaced, refused } // replaced: places changed; refused: places that could not be (locked)",
207
+ effect: "edit",
208
+ call(session, [a, b, c, d]: Args) {
209
+ const { blocks, replaced, refused } = given(session.replaceText(a, b, c, d));
210
+ return { blocks, replaced, refused };
211
+ },
212
+ },
213
+ ],
214
+ },
215
+ {
216
+ name: "insert_paragraphs",
217
+ description:
218
+ "Inserts new paragraphs before or after a block (a paragraph, a table, any block), as a tracked change. Each is formatted like the paragraph it goes next to, its style, indents and numbering included (after a heading: as body text), unless it names a style. Returns the new blocks with their handles.",
219
+ inputSchema: args(
220
+ {
221
+ handle: HANDLE,
222
+ where: { type: "string", enum: ["after", "before"], description: "Default: after." },
223
+ paragraphs: {
224
+ type: "array",
225
+ description: "The paragraphs, in order: each its text, or its text and a style.",
226
+ items: {
227
+ anyOf: [
228
+ { type: "string" },
229
+ {
230
+ type: "object",
231
+ properties: {
232
+ text: { type: "string" },
233
+ style: {
234
+ type: "string",
235
+ description: "A paragraph style's name, as read or list_styles shows it.",
236
+ },
237
+ },
238
+ required: ["text"],
239
+ additionalProperties: false,
240
+ },
241
+ ],
242
+ },
243
+ },
244
+ },
245
+ ["handle", "paragraphs"],
246
+ ),
247
+ run: (session, { handle, where, paragraphs }) =>
248
+ told(
249
+ where === "before"
250
+ ? session.insertBefore(handle as string, paragraphs as string[])
251
+ : session.insertAfter(handle as string, paragraphs as string[]),
252
+ ),
253
+ methods: [
254
+ {
255
+ name: "insertAfter",
256
+ signature:
257
+ 'doc.insertAfter(handle, paragraphs): { blocks } // paragraphs: "text" | { text, style? } | a list of them; blocks: the new ones',
258
+ effect: "insert",
259
+ call: (session, [a, b]: Args) => ({ blocks: given(session.insertAfter(a, b)).blocks }),
260
+ },
261
+ {
262
+ name: "insertBefore",
263
+ signature: "doc.insertBefore(handle, paragraphs): { blocks }",
264
+ effect: "insert",
265
+ call: (session, [a, b]: Args) => ({ blocks: given(session.insertBefore(a, b)).blocks }),
266
+ },
267
+ ],
268
+ },
269
+ {
270
+ name: "delete_block",
271
+ description:
272
+ "Deletes a paragraph, or a table with all its cells, as a tracked change. A paragraph that must stay (the last of the document or of a cell, one before a table, one that ends a section) is emptied instead, and the answer says so.",
273
+ inputSchema: args({ handle: HANDLE }, ["handle"]),
274
+ run: (session, { handle }) => told(session.deleteBlock(handle as string)),
275
+ methods: [
276
+ {
277
+ name: "deleteBlock",
278
+ signature:
279
+ "doc.deleteBlock(handle): { text } // text: a sentence saying what was done",
280
+ effect: "delete",
281
+ call: (session, [a]: Args) => ({ text: given(session.deleteBlock(a)).text }),
282
+ },
283
+ ],
284
+ },
285
+ {
286
+ name: "set_style",
287
+ description:
288
+ "Puts a paragraph in a paragraph style (Heading 2, Normal…), as a tracked formatting change. Returns the block as it reads now.",
289
+ inputSchema: args(
290
+ {
291
+ handle: HANDLE,
292
+ style: {
293
+ type: "string",
294
+ description: "The style's name, as read or list_styles shows it; capitals do not count.",
295
+ },
296
+ },
297
+ ["handle", "style"],
298
+ ),
299
+ run: (session, { handle, style }) => told(session.setStyle(handle as string, style as string)),
300
+ methods: [
301
+ { name: "styles", signature: "doc.styles(): string[]", call: (session) => session.styles() },
302
+ {
303
+ name: "setStyle",
304
+ signature: "doc.setStyle(handle, style): { blocks }",
305
+ effect: "edit",
306
+ call: (session, [a, b]: Args) => ({ blocks: given(session.setStyle(a, b)).blocks }),
307
+ },
308
+ ],
309
+ },
310
+ {
311
+ name: "list_styles",
312
+ description:
313
+ "Lists the paragraph styles of an open document, by the names set_style and insert_paragraphs take.",
314
+ inputSchema: args({}),
315
+ run: (session) => ({ text: session.styles().join("\n") }),
316
+ methods: [],
317
+ },
318
+ {
319
+ name: "comment",
320
+ description:
321
+ "Adds a comment to a paragraph, in the margin as in Word: on the whole paragraph, or on text in it. Use it to explain a change or to ask the reader something. It does not change the text. A deleted block takes none: to explain a deletion, comment the block before or after it.",
322
+ inputSchema: args(
323
+ {
324
+ handle: HANDLE,
325
+ text: {
326
+ type: "string",
327
+ description: "The comment. A line break starts a new paragraph.",
328
+ },
329
+ on: {
330
+ type: "string",
331
+ description:
332
+ "Text of the block to anchor the comment to, exactly as read shows it, there once.",
333
+ },
334
+ },
335
+ ["handle", "text"],
336
+ ),
337
+ run: (session, { handle, text, on }) =>
338
+ told(
339
+ session.comment(
340
+ handle as string,
341
+ text as string,
342
+ on === undefined ? {} : { on: on as string },
343
+ ),
344
+ ),
345
+ methods: [
346
+ {
347
+ name: "comment",
348
+ signature:
349
+ "doc.comment(handle, text, { on? }): { blocks, comment } // comment: the new comment's id",
350
+ effect: "edit",
351
+ call(session, [a, b, c]: Args) {
352
+ const { blocks, comment } = given(session.comment(a, b, c));
353
+ return { blocks, comment };
354
+ },
355
+ },
356
+ ],
357
+ },
358
+ {
359
+ name: "list_controls",
360
+ description:
361
+ "Lists the content controls of an open document: the blanks a template leaves to fill (read shows an unfilled one as [empty: Title]). Each with its name for fill_control, its kind, its value, a list's items, and the block it is in.",
362
+ inputSchema: args({}),
363
+ run(session) {
364
+ const all = session.controls();
365
+ return {
366
+ text: all.length ? all.map(control).join("\n") : "The document has no content controls.",
367
+ };
368
+ },
369
+ methods: [
370
+ {
371
+ name: "controls",
372
+ signature:
373
+ "doc.controls(): Control[] // { id, name, kind, value, empty, items?, readOnly, block }",
374
+ call: (session) => session.controls(),
375
+ },
376
+ ],
377
+ },
378
+ {
379
+ name: "fill_control",
380
+ description:
381
+ "Fills a content control, as a tracked change: text for a text control, one of its items for a list, a day as yyyy-mm-dd for a date, true or false for a check box; null empties it. name is the control's name from list_controls (controls that share a name are all filled; a control's id fills that one). Returns the blocks changed.",
382
+ inputSchema: args(
383
+ {
384
+ name: { type: "string", description: "The control's name, title or id." },
385
+ value: {
386
+ anyOf: [{ type: "string" }, { type: "boolean" }, { type: "null" }],
387
+ description: "The value: text, true or false, or null to empty the control.",
388
+ },
389
+ },
390
+ ["name", "value"],
391
+ ),
392
+ run(session, { name, value }) {
393
+ const result = session.fillControl(name as string, value as string | boolean | null);
394
+ return told(result, result.ok ? `\n${result.controls.map(control).join("\n")}` : "");
395
+ },
396
+ methods: [
397
+ {
398
+ name: "fillControl",
399
+ signature:
400
+ "doc.fillControl(name, value): { blocks, controls, unfilled } // unfilled: controls of that name that did not take the value, each with why",
401
+ effect: "edit",
402
+ call(session, [a, b]: Args) {
403
+ const { blocks, controls, unfilled } = given(session.fillControl(a, b));
404
+ return { blocks, controls, unfilled };
405
+ },
406
+ },
407
+ ],
408
+ },
409
+ {
410
+ name: "update_fields",
411
+ description:
412
+ "Fills the document's merge fields («Name» in a read) from data, and updates its other fields (dates, cross-references), as tracked changes. A table of contents is left as it is unless contents is true. Returns what was updated and what was left, in words; read again to see the text.",
413
+ inputSchema: args({
414
+ data: {
415
+ type: "object",
416
+ description: 'Merge field names with their values: { "FirstName": "Ada" }.',
417
+ additionalProperties: true,
418
+ },
419
+ contents: {
420
+ type: "boolean",
421
+ description:
422
+ "Build the tables of contents again from the headings as they are now. Their entries become new blocks with new handles, and their page numbers stay empty until Word updates the field: say so to the reader. Default: false.",
423
+ },
424
+ }),
425
+ run: (session, { data, contents }) =>
426
+ told(
427
+ session.updateFields({
428
+ ...(data === undefined ? {} : { data: data as Record<string, string> }),
429
+ ...(contents === true ? { contents: true } : {}),
430
+ }),
431
+ ),
432
+ methods: [
433
+ {
434
+ name: "updateFields",
435
+ signature:
436
+ "doc.updateFields({ data?, contents? }): { updated, unchanged, rebuilt, text } // counts, and a sentence",
437
+ effect: "fields",
438
+ call(session, [a]: Args) {
439
+ const { updated, unchanged, rebuilt, text } = given(session.updateFields(a));
440
+ return { updated, unchanged, rebuilt, text };
441
+ },
442
+ },
443
+ ],
444
+ },
445
+ {
446
+ name: "edit_table",
447
+ description:
448
+ "Tables, as tracked changes. handle names a table: its \"table\" line's, or a paragraph's in one of its cells; row and column are numbered as read prints them (r2 c1). Actions: insert_table, a new table after (or before) the block handle names, cells its rows of texts; insert_rows after (or before) row, made like it, cells their texts; delete_rows, rows their numbers; set_cells, values [{ row, column, text }], each cell's whole text; set_style, style a table style's name (null: none); shade, fill RRGGBB (null: none) on the table, a row, a column or one cell; header_rows, count rows from the top repeated on each page (0: none). Columns, merging, splitting and widths cannot be tracked: the answer says what to do instead. Returns the table as it reads now.",
449
+ inputSchema: args(
450
+ {
451
+ handle: {
452
+ ...HANDLE,
453
+ description:
454
+ "A table's handle, or a paragraph's in one of its cells (insert_table: the block to put it next to).",
455
+ },
456
+ action: {
457
+ type: "string",
458
+ enum: [
459
+ "insert_table",
460
+ "insert_rows",
461
+ "delete_rows",
462
+ "set_cells",
463
+ "set_style",
464
+ "shade",
465
+ "header_rows",
466
+ "insert_columns",
467
+ "delete_columns",
468
+ "merge_cells",
469
+ "split_cell",
470
+ "column_width",
471
+ ],
472
+ description: "What to do; the description says which arguments each takes.",
473
+ },
474
+ where: { type: "string", enum: ["after", "before"], description: "Default: after." },
475
+ cells: {
476
+ type: "array",
477
+ description:
478
+ 'Rows of cell texts: [["Item", "Price"], ["Tea", "3.50"]]. ↵ is a line break.',
479
+ items: { type: "array", items: { type: "string" } },
480
+ },
481
+ row: { type: "integer", minimum: 1, description: "A row, as read numbers it: r2 is 2." },
482
+ column: {
483
+ type: "integer",
484
+ minimum: 1,
485
+ description: "A grid column, as read numbers it: c1 is 1.",
486
+ },
487
+ rows: {
488
+ type: "array",
489
+ description: "delete_rows: the rows, as read numbers them.",
490
+ items: { type: "integer", minimum: 1 },
491
+ },
492
+ values: {
493
+ type: "array",
494
+ description: "set_cells: each cell's row, column and whole new text.",
495
+ items: {
496
+ type: "object",
497
+ properties: {
498
+ row: { type: "integer", minimum: 1 },
499
+ column: { type: "integer", minimum: 1 },
500
+ text: { type: "string" },
501
+ },
502
+ required: ["row", "column", "text"],
503
+ additionalProperties: false,
504
+ },
505
+ },
506
+ header: {
507
+ type: "boolean",
508
+ description:
509
+ "insert_table: the first row is a header row, repeated on each page (as header_rows 1).",
510
+ },
511
+ style: {
512
+ anyOf: [{ type: "string" }, { type: "null" }],
513
+ description: "A table style's name (insert_table, set_style).",
514
+ },
515
+ fill: { anyOf: [{ type: "string" }, { type: "null" }], description: "RRGGBB: D9E2F3." },
516
+ count: {
517
+ type: "integer",
518
+ minimum: 0,
519
+ description: "header_rows: how many rows from the top.",
520
+ },
521
+ },
522
+ ["handle", "action"],
523
+ ),
524
+ run(session, a) {
525
+ const handle = a.handle as string;
526
+ const need = (...keys: string[]) => {
527
+ const missing = keys.filter((k) => a[k] === undefined);
528
+ return missing.length
529
+ ? { text: `${a.action as string} needs ${missing.join(" and ")}.`, isError: true }
530
+ : null;
531
+ };
532
+ switch (a.action) {
533
+ case "insert_table":
534
+ return (
535
+ need("cells") ??
536
+ told(
537
+ session.insertTable(handle, a.cells as string[][], {
538
+ ...(a.where === undefined ? {} : { where: a.where as "after" | "before" }),
539
+ ...(a.header === true ? { header: true } : {}),
540
+ ...(typeof a.style === "string" ? { style: a.style } : {}),
541
+ }),
542
+ )
543
+ );
544
+ case "insert_rows":
545
+ return (
546
+ need("row", "cells") ??
547
+ told(
548
+ session.insertRows(
549
+ handle,
550
+ a.row as number,
551
+ a.cells as string[][],
552
+ a.where === "before" ? "before" : "after",
553
+ ),
554
+ )
555
+ );
556
+ case "delete_rows":
557
+ return need("rows") ?? told(session.deleteRows(handle, a.rows as number[]));
558
+ case "set_cells":
559
+ return need("values") ?? told(session.setCells(handle, a.values as never));
560
+ case "set_style":
561
+ return need("style") ?? told(session.setTableStyle(handle, a.style as string | null));
562
+ case "shade":
563
+ return (
564
+ need("fill") ??
565
+ told(
566
+ session.shadeCells(handle, a.fill as string | null, {
567
+ ...(a.row === undefined ? {} : { row: a.row as number }),
568
+ ...(a.column === undefined ? {} : { column: a.column as number }),
569
+ }),
570
+ )
571
+ );
572
+ case "header_rows":
573
+ return need("count") ?? told(session.setHeaderRows(handle, a.count as number));
574
+ default:
575
+ return { text: UNTRACKED_TABLE_EDIT, isError: true };
576
+ }
577
+ },
578
+ methods: [
579
+ {
580
+ name: "insertTable",
581
+ signature:
582
+ 'doc.insertTable(handle, cells, { where?, header?, style? }): { blocks } // cells: [["Item", "Price"], ["Tea", "3.50"]]; blocks: the table and its cells',
583
+ effect: "insert",
584
+ call: (session, [a, b, c]: Args) => ({
585
+ blocks: given(session.insertTable(a, b, c)).blocks,
586
+ }),
587
+ },
588
+ {
589
+ name: "insertRows",
590
+ signature:
591
+ 'doc.insertRows(table, row, cells, where?): { blocks } // where: "after" | "before"',
592
+ effect: "insert",
593
+ call: (session, [a, b, c, d]: Args) => ({
594
+ blocks: given(session.insertRows(a, b, c, d)).blocks,
595
+ }),
596
+ },
597
+ {
598
+ name: "deleteRows",
599
+ signature: "doc.deleteRows(table, rows): { text, rows }",
600
+ effect: "delete",
601
+ call(session, [a, b]: Args) {
602
+ const { text, rows } = given(session.deleteRows(a, b));
603
+ return { text, rows };
604
+ },
605
+ },
606
+ {
607
+ name: "setCells",
608
+ signature: "doc.setCells(table, [{ row, column, text }]): { blocks }",
609
+ effect: "edit",
610
+ call: (session, [a, b]: Args) => ({ blocks: given(session.setCells(a, b)).blocks }),
611
+ },
612
+ {
613
+ name: "tableStyles",
614
+ signature: "doc.tableStyles(): string[]",
615
+ call: (session) => session.tableStyles(),
616
+ },
617
+ {
618
+ name: "setTableStyle",
619
+ signature: "doc.setTableStyle(table, style | null): { blocks }",
620
+ effect: "edit",
621
+ call: (session, [a, b]: Args) => ({ blocks: given(session.setTableStyle(a, b)).blocks }),
622
+ },
623
+ {
624
+ name: "shadeCells",
625
+ signature: "doc.shadeCells(table, fill | null, { row?, column? }): { blocks }",
626
+ effect: "edit",
627
+ call: (session, [a, b, c]: Args) => ({ blocks: given(session.shadeCells(a, b, c)).blocks }),
628
+ },
629
+ {
630
+ name: "setHeaderRows",
631
+ signature: "doc.setHeaderRows(table, count): { blocks }",
632
+ effect: "edit",
633
+ call: (session, [a, b]: Args) => ({ blocks: given(session.setHeaderRows(a, b)).blocks }),
634
+ },
635
+ ],
636
+ },
637
+ {
638
+ name: "format_text",
639
+ description:
640
+ "Formats a paragraph's text, as a tracked formatting change: all of it, or on text in it (exactly as read shows it, there once, or every place with all). format says what to change, the rest stays: bold, italic, underline, strike (true or false), font (a name), size (points), color (RRGGBB), highlight (a Word highlight color by name: yellow, green…), link (an address; null takes a link off); null gives font, size or color back to the style. read with formatting shows what text has now. Returns the block as it reads now.",
641
+ inputSchema: args(
642
+ {
643
+ handle: HANDLE,
644
+ format: {
645
+ type: "object",
646
+ description: 'What to change: { "bold": true, "color": "1F3864" }.',
647
+ properties: {
648
+ bold: { type: "boolean" },
649
+ italic: { type: "boolean" },
650
+ underline: { type: "boolean" },
651
+ strike: { type: "boolean" },
652
+ font: { anyOf: [{ type: "string" }, { type: "null" }] },
653
+ size: { anyOf: [{ type: "number" }, { type: "null" }] },
654
+ color: { anyOf: [{ type: "string" }, { type: "null" }] },
655
+ highlight: { anyOf: [{ type: "string" }, { type: "null" }] },
656
+ link: { anyOf: [{ type: "string" }, { type: "null" }] },
657
+ },
658
+ additionalProperties: false,
659
+ },
660
+ on: {
661
+ type: "string",
662
+ description: "Text of the block to format, exactly as read shows it. Default: all of it.",
663
+ },
664
+ all: { type: "boolean", description: "Every place on is in the block." },
665
+ },
666
+ ["handle", "format"],
667
+ ),
668
+ run: (session, { handle, format, on, all }) =>
669
+ told(
670
+ session.formatText(handle as string, format as never, {
671
+ ...(on === undefined ? {} : { on: on as string }),
672
+ ...(all === true ? { all: true } : {}),
673
+ }),
674
+ ),
675
+ methods: [
676
+ {
677
+ name: "formatText",
678
+ signature: "doc.formatText(handle, format, { on?, all? }): { blocks }",
679
+ effect: "edit",
680
+ call: (session, [a, b, c]: Args) => ({ blocks: given(session.formatText(a, b, c)).blocks }),
681
+ },
682
+ ],
683
+ },
684
+ {
685
+ name: "format_paragraph",
686
+ description:
687
+ "Formats paragraphs, as tracked formatting changes: handles, one or several (paragraphs next to each other become one list). format says what to change, the rest stays: align (left, center, right, justify), lineSpacing (a multiple: 1, 1.15, 1.5, 2), spaceBefore and spaceAfter (points), indent (more or less: half an inch, or a list level), list (bullet, numbered; null takes the numbering off); null gives spacing back to the style. read with formatting shows a paragraph's own. Returns the blocks as they read now.",
688
+ inputSchema: args(
689
+ {
690
+ handles: {
691
+ type: "array",
692
+ description: 'The paragraphs\' handles, from read: ["b4", "b5"].',
693
+ items: { type: "string" },
694
+ },
695
+ format: {
696
+ type: "object",
697
+ description: 'What to change: { "align": "center", "spaceAfter": 6 }.',
698
+ properties: {
699
+ align: { type: "string", enum: ["left", "center", "right", "justify"] },
700
+ lineSpacing: { anyOf: [{ type: "number" }, { type: "null" }] },
701
+ spaceBefore: { anyOf: [{ type: "number" }, { type: "null" }] },
702
+ spaceAfter: { anyOf: [{ type: "number" }, { type: "null" }] },
703
+ indent: { type: "string", enum: ["more", "less"] },
704
+ list: {
705
+ anyOf: [{ type: "string", enum: ["bullet", "numbered"] }, { type: "null" }],
706
+ },
707
+ },
708
+ additionalProperties: false,
709
+ },
710
+ },
711
+ ["handles", "format"],
712
+ ),
713
+ run: (session, { handles, format }) =>
714
+ told(session.formatParagraphs(handles as string[], format as never)),
715
+ methods: [
716
+ {
717
+ name: "formatParagraphs",
718
+ signature: "doc.formatParagraphs(handles, format): { blocks }",
719
+ effect: "edit",
720
+ call: (session, [a, b]: Args) => ({ blocks: given(session.formatParagraphs(a, b)).blocks }),
721
+ },
722
+ ],
723
+ },
724
+ {
725
+ name: "insert",
726
+ description:
727
+ "Inserts what is not text, as a tracked insertion, next to or in a paragraph (handle): a picture (path to an image file, and alt: what it shows; width or height in points, else its own size fitted to the page) or a horizontal line, as a paragraph of its own after (or before) it; a page break or a section break (start: nextPage, continuous, evenPage, oddPage) at its end (or start); a footnote or endnote, its text, at the paragraph's end or after on text in it. Returns the blocks made or changed.",
728
+ inputSchema: args(
729
+ {
730
+ handle: HANDLE,
731
+ what: {
732
+ type: "string",
733
+ enum: [
734
+ "picture",
735
+ "page_break",
736
+ "section_break",
737
+ "horizontal_rule",
738
+ "footnote",
739
+ "endnote",
740
+ ],
741
+ description: "What to insert.",
742
+ },
743
+ where: { type: "string", enum: ["after", "before"], description: "Default: after." },
744
+ path: { type: "string", description: "picture: the image file (.png, .jpg, .gif)." },
745
+ alt: {
746
+ type: "string",
747
+ description: "picture: what it shows, for a reader who cannot see it.",
748
+ },
749
+ width: { type: "number", description: "picture: in points." },
750
+ height: { type: "number", description: "picture: in points." },
751
+ start: {
752
+ type: "string",
753
+ enum: ["nextPage", "continuous", "evenPage", "oddPage"],
754
+ description: "section_break: where the next section starts. Default: nextPage.",
755
+ },
756
+ text: { type: "string", description: "footnote, endnote: the note's text." },
757
+ on: {
758
+ type: "string",
759
+ description: "footnote, endnote: text of the paragraph the note follows.",
760
+ },
761
+ },
762
+ ["handle", "what"],
763
+ ),
764
+ run(session, a, host) {
765
+ const handle = a.handle as string;
766
+ const where = a.where === "before" ? { where: "before" as const } : {};
767
+ switch (a.what) {
768
+ case "picture": {
769
+ if (!host?.picture)
770
+ return {
771
+ text: "Pictures cannot be inserted here: the app gives no files.",
772
+ isError: true,
773
+ };
774
+ if (typeof a.path !== "string" || typeof a.alt !== "string")
775
+ return { text: "picture needs path and alt.", isError: true };
776
+ const file = host.picture(a.path);
777
+ if (!file.ok) return { text: file.message, isError: true };
778
+ return told(
779
+ session.insertItem(
780
+ handle,
781
+ {
782
+ kind: "picture",
783
+ data: file.data,
784
+ ...(file.contentType ? { contentType: file.contentType } : {}),
785
+ alt: a.alt,
786
+ ...(typeof a.width === "number" ? { width: a.width } : {}),
787
+ ...(typeof a.height === "number" ? { height: a.height } : {}),
788
+ },
789
+ where,
790
+ ),
791
+ );
792
+ }
793
+ case "page_break":
794
+ return told(session.insertItem(handle, { kind: "pageBreak" }, where));
795
+ case "section_break":
796
+ return told(
797
+ session.insertItem(
798
+ handle,
799
+ { kind: "sectionBreak", ...(a.start ? { start: a.start as never } : {}) },
800
+ where,
801
+ ),
802
+ );
803
+ case "horizontal_rule":
804
+ return told(session.insertItem(handle, { kind: "horizontalRule" }, where));
805
+ default:
806
+ if (typeof a.text !== "string")
807
+ return { text: `${a.what as string} needs text.`, isError: true };
808
+ return told(
809
+ session.insertItem(handle, {
810
+ kind: a.what === "endnote" ? "endnote" : "footnote",
811
+ text: a.text,
812
+ ...(typeof a.on === "string" ? { on: a.on } : {}),
813
+ }),
814
+ );
815
+ }
816
+ },
817
+ methods: [
818
+ {
819
+ name: "insert",
820
+ signature:
821
+ 'doc.insert(handle, { kind, ... }, { where? }): { blocks } // kind: "picture" (path, alt, width?, height?) | "pageBreak" | "sectionBreak" (start?) | "horizontalRule" | "footnote" | "endnote" (text, on?)',
822
+ effect: "edit",
823
+ call(session, [a, b, c]: Args, host) {
824
+ const item = b as Record<string, unknown> | undefined;
825
+ if (item?.kind === "picture") {
826
+ if (!host?.picture)
827
+ throw new Error("Pictures cannot be inserted here: the app gives no files.");
828
+ const file = given(host.picture(String(item.path)));
829
+ const { path: _, contentType: __, ...rest } = item;
830
+ return {
831
+ blocks: given(
832
+ session.insertItem(
833
+ a,
834
+ {
835
+ ...rest,
836
+ data: file.data,
837
+ ...(file.contentType ? { contentType: file.contentType } : {}),
838
+ } as never,
839
+ c,
840
+ ),
841
+ ).blocks,
842
+ };
843
+ }
844
+ return { blocks: given(session.insertItem(a, b, c)).blocks };
845
+ },
846
+ },
847
+ ],
848
+ },
849
+ {
850
+ name: "review",
851
+ review: true,
852
+ description:
853
+ 'Lists the document\'s tracked changes, a line each ([c12] inserted, Bob (2026-11-20), in [b7]: "text"), and accepts or rejects them as Word does: by their numbers (ids: [12] for c12), or all of them (ids: "all", every header and footer too; author: only that person\'s). Accepted insertions stay, accepted deletions go; rejecting does the opposite. The list shows deleted text that read leaves out.',
854
+ inputSchema: args(
855
+ {
856
+ action: { type: "string", enum: ["list", "accept", "reject"], description: "What to do." },
857
+ ids: {
858
+ anyOf: [
859
+ { type: "array", items: { type: "integer" } },
860
+ { type: "string", enum: ["all"] },
861
+ ],
862
+ description: 'accept, reject: the changes\' numbers ([12] for c12), or "all".',
863
+ },
864
+ author: { type: "string", description: 'With ids "all": only this person\'s changes.' },
865
+ },
866
+ ["action"],
867
+ ),
868
+ run(session, { action, ids, author }) {
869
+ if (action === "list") return told(session.changes());
870
+ if (ids === undefined) return { text: `${action as string} needs ids.`, isError: true };
871
+ const options = typeof author === "string" ? { author } : {};
872
+ return told(
873
+ action === "accept"
874
+ ? session.acceptChanges(ids as number[] | "all", options)
875
+ : session.rejectChanges(ids as number[] | "all", options),
876
+ );
877
+ },
878
+ methods: [
879
+ {
880
+ name: "changes",
881
+ signature:
882
+ "doc.changes(): { changes, text } // changes: { id, kind, author, date, block, text }[], in order",
883
+ call(session) {
884
+ const { changes, text } = given(session.changes());
885
+ return { changes, text };
886
+ },
887
+ },
888
+ {
889
+ name: "acceptChanges",
890
+ signature: 'doc.acceptChanges(ids | "all", { author? }): { text }',
891
+ call: (session, [a, b]: Args) => ({ text: given(session.acceptChanges(a, b)).text }),
892
+ },
893
+ {
894
+ name: "rejectChanges",
895
+ signature: 'doc.rejectChanges(ids | "all", { author? }): { text }',
896
+ call: (session, [a, b]: Args) => ({ text: given(session.rejectChanges(a, b)).text }),
897
+ },
898
+ ],
899
+ },
900
+ ];
901
+
902
+ /** The tools a session is given: the review tool only to one that reviews changes. */
903
+ export const toolsFor = (session: { reviewing: boolean }): readonly ToolDefinition[] =>
904
+ AGENT_TOOLS.filter((tool) => !tool.review || session.reviewing);
905
+
906
+ /**
907
+ * The tools over one session, for an app that runs its own model loop: give the model
908
+ * `INSTRUCTIONS` and each tool's name, description and schema, and pass its calls to `run`.
909
+ * A call whose arguments do not fit the schema is answered with why, as a refusal. `host`
910
+ * gives the `insert` tool a picture's bytes by path; without it, pictures are refused.
911
+ */
912
+
913
+ export function agentTools(session: Session, host: ToolHost = {}): AgentTool[] {
914
+ return toolsFor(session).map(({ name, description, inputSchema, run }) => ({
915
+ name,
916
+ description,
917
+ inputSchema,
918
+ run(a = {}) {
919
+ const wrong = invalid(a, inputSchema);
920
+ return wrong
921
+ ? { text: `Wrong arguments for ${name}: ${wrong}.`, isError: true }
922
+ : run(session, a, host);
923
+ },
924
+ }));
925
+ }