@powerhousedao/reactor-mcp 6.2.3-dev.93 → 6.2.3-dev.94

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.
@@ -0,0 +1,1700 @@
1
+ import { childLogger, inspectDocumentModelDefinition } from "document-model";
2
+ import { deleteNode } from "@powerhousedao/shared/document-drive";
3
+ import { z } from "zod";
4
+ import { DOCUMENT_SCOPE_ACTION_TYPES, baseActions, creationState, operationOutcome, stateReducerOf, undoCapabilitiesOf, undoNeedsTargets, undoRedoBatch } from "@powerhousedao/shared/document-model";
5
+ import { camelCase, pascalCase } from "change-case";
6
+ //#region src/tools/errors.ts
7
+ const REACTOR_TOOL_ERROR_CODES = [
8
+ "NOT_FOUND",
9
+ "FORBIDDEN",
10
+ "INVALID_ACTION",
11
+ "REDUCER_ERROR",
12
+ "CONFLICT"
13
+ ];
14
+ var ReactorToolError = class extends Error {
15
+ code;
16
+ failures;
17
+ constructor(code, message, options = {}) {
18
+ super(message, { cause: options.cause });
19
+ this.name = "ReactorToolError";
20
+ this.code = code;
21
+ if (options.failures) this.failures = options.failures;
22
+ }
23
+ toJSON() {
24
+ return {
25
+ code: this.code,
26
+ message: this.message,
27
+ ...this.failures ? { failures: this.failures } : {}
28
+ };
29
+ }
30
+ };
31
+ function isReactorToolError(error) {
32
+ return error instanceof ReactorToolError || error instanceof Error && error.name === "ReactorToolError" && REACTOR_TOOL_ERROR_CODES.includes(error.code);
33
+ }
34
+ const NAME_CODES = {
35
+ DocumentNotFoundError: "NOT_FOUND",
36
+ DocumentPurgedError: "NOT_FOUND",
37
+ DocumentDeletedError: "NOT_FOUND",
38
+ RelationshipNotFoundError: "NOT_FOUND",
39
+ DocumentModelUnavailableError: "NOT_FOUND",
40
+ UnsupportedDocumentModelVersionError: "NOT_FOUND",
41
+ AuthorizationDeniedError: "FORBIDDEN",
42
+ ReactorAccessDeniedError: "FORBIDDEN",
43
+ ReservedActionError: "FORBIDDEN",
44
+ InvalidSignatureError: "FORBIDDEN",
45
+ InvalidActionInputError: "INVALID_ACTION",
46
+ InvalidActionInputZodError: "INVALID_ACTION",
47
+ ReactorActionsFailedError: "REDUCER_ERROR",
48
+ ExcessiveReshuffleError: "CONFLICT",
49
+ AuthTimestampNotMonotonicError: "CONFLICT",
50
+ UpgradePreconditionFailedError: "CONFLICT",
51
+ InvalidOperationTimestampError: "CONFLICT"
52
+ };
53
+ function codeFromMessage(message) {
54
+ if (/\bnot found\b|does not exist|no such/i.test(message)) return "NOT_FOUND";
55
+ if (/\b(denied|forbidden|not allowed|unauthori[sz]ed)\b/i.test(message)) return "FORBIDDEN";
56
+ if (/\bconflict/i.test(message)) return "CONFLICT";
57
+ }
58
+ /** Normalizes any thrown value to a {@link ReactorToolError}. */
59
+ function toReactorToolError(error, fallback = "REDUCER_ERROR") {
60
+ if (error instanceof ReactorToolError) return error;
61
+ if (isReactorToolError(error)) {
62
+ const { failures } = error;
63
+ return new ReactorToolError(error.code, error.message, {
64
+ failures,
65
+ cause: error
66
+ });
67
+ }
68
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error) ?? "Unknown error";
69
+ const name = error instanceof Error ? error.name : "";
70
+ const jobErrorName = error?.job?.error?.name;
71
+ return new ReactorToolError(NAME_CODES[name] ?? (typeof jobErrorName === "string" ? NAME_CODES[jobErrorName] : void 0) ?? codeFromMessage(message) ?? fallback, message, { cause: error });
72
+ }
73
+ function notFound(message) {
74
+ return new ReactorToolError("NOT_FOUND", message);
75
+ }
76
+ //#endregion
77
+ //#region src/tools/definition.ts
78
+ function defineTool(definition) {
79
+ return definition;
80
+ }
81
+ /** Whether running the tool can change state; unannotated tools count as writes. */
82
+ function isWriteTool(annotations) {
83
+ return annotations?.readOnlyHint !== true;
84
+ }
85
+ /** Text of an error as the MCP and `ai` adapters report it. */
86
+ function formatToolError(error) {
87
+ return `${error.code}: ${error.message}`;
88
+ }
89
+ /** Wraps a definition for `McpServer.registerTool`; errors become `isError` results. */
90
+ function toMcpTool(definition, ctx) {
91
+ const execute = definition.execute;
92
+ return {
93
+ name: definition.name,
94
+ title: definition.title,
95
+ description: definition.description,
96
+ inputSchema: definition.inputSchema.shape,
97
+ outputSchema: definition.outputSchema.shape,
98
+ annotations: {
99
+ title: definition.title,
100
+ ...definition.annotations
101
+ },
102
+ callback: async (args, extra) => {
103
+ try {
104
+ const result = await execute(args, {
105
+ ...ctx,
106
+ signal: extra?.signal ?? ctx.signal
107
+ });
108
+ return {
109
+ content: [{
110
+ type: "text",
111
+ text: JSON.stringify(result)
112
+ }],
113
+ structuredContent: result
114
+ };
115
+ } catch (error) {
116
+ const toolError = toReactorToolError(error);
117
+ return {
118
+ isError: true,
119
+ content: [{
120
+ type: "text",
121
+ text: `Error: ${formatToolError(toolError)}`
122
+ }],
123
+ _meta: { error: toolError.toJSON() }
124
+ };
125
+ }
126
+ }
127
+ };
128
+ }
129
+ /** Builds an `ai` SDK ToolSet without importing `ai`; failures throw with the code in the message. */
130
+ function toAiSdkTools(definitions, ctx) {
131
+ const tools = {};
132
+ for (const definition of definitions) {
133
+ const execute = definition.execute;
134
+ tools[definition.name] = {
135
+ title: definition.title,
136
+ description: definition.description,
137
+ inputSchema: definition.inputSchema,
138
+ outputSchema: definition.outputSchema,
139
+ execute: async (args, options) => {
140
+ try {
141
+ return await execute(args, {
142
+ ...ctx,
143
+ signal: options?.abortSignal ?? ctx.signal
144
+ });
145
+ } catch (error) {
146
+ const toolError = toReactorToolError(error);
147
+ throw new ReactorToolError(toolError.code, formatToolError(toolError), {
148
+ failures: toolError.failures,
149
+ cause: error
150
+ });
151
+ }
152
+ }
153
+ };
154
+ }
155
+ return tools;
156
+ }
157
+ //#endregion
158
+ //#region src/tools/codegen.ts
159
+ /** Marks a Vetra document's codegen queued once a global change is stored, and says how to follow it. */
160
+ async function codegenHint(codegen, client, executed, signal) {
161
+ if (!codegen.active) return void 0;
162
+ const { documentId } = executed;
163
+ let documentType;
164
+ try {
165
+ documentType = (await client.get(documentId, void 0, signal)).header.documentType;
166
+ } catch {
167
+ return;
168
+ }
169
+ if (!codegen.watches(documentType)) return void 0;
170
+ if (executed.results.some((result) => result.scope === "global" && result.operationIndex !== void 0)) codegen.set({
171
+ documentId,
172
+ documentType,
173
+ state: "queued",
174
+ message: "Waiting for Vetra's codegen processor to pick up the change"
175
+ });
176
+ return `Vetra generates code from this document a few seconds after a change. Call getCodegenStatus with documentId "${documentId}" and waitSeconds to see when it is done, and why it failed or was skipped.`;
177
+ }
178
+ const codegenStatusSchema = z.object({
179
+ documentId: z.string(),
180
+ documentType: z.string(),
181
+ name: z.string().optional().describe("The module's name"),
182
+ state: z.enum([
183
+ "queued",
184
+ "running",
185
+ "waiting-for-install",
186
+ "done",
187
+ "failed",
188
+ "skipped"
189
+ ]).describe("queued: waiting for the changes to settle or for another job; running: writing code; waiting-for-install: a dependency install runs first; done: the code is written; failed: generation threw, see message; skipped: nothing was generated, see message"),
190
+ message: z.string().optional().describe("Why it failed or was skipped, or what it waits for"),
191
+ files: z.array(z.string()).optional().describe("Project files the job wrote, relative to the project"),
192
+ updatedAt: z.string().describe("ISO timestamp of the last change")
193
+ });
194
+ /** Vetra's code generation status, for hosts that run its codegen processor. */
195
+ function codegenStatusTool(codegen) {
196
+ return defineTool({
197
+ name: "getCodegenStatus",
198
+ title: "Read Vetra's code generation status",
199
+ description: "Vetra's code generation for its documents (document models, editors, apps, processors, subgraphs and the package): each one's state, why it failed or was skipped, and the files it wrote. Vetra regenerates a document's code a few seconds after it changes; call this after addActions on such a document, with `waitSeconds` to wait until it settles, before reading or editing the generated code. `loadFailures` lists the project modules Vetra could not load, e.g. generated code that throws on import.",
200
+ inputSchema: z.object({
201
+ documentId: z.string().optional().describe("ID of a Vetra document; omitted, every document's status"),
202
+ waitSeconds: z.number().min(0).max(60).optional().describe("Wait up to this many seconds for the job, or every job without `documentId`, to be done, failed or skipped. Defaults to 0.")
203
+ }),
204
+ outputSchema: z.object({
205
+ active: z.boolean().describe("False when no Vetra codegen runs on this reactor"),
206
+ settled: z.boolean().describe("True when every listed job is done, failed or skipped"),
207
+ documents: z.array(codegenStatusSchema).describe("One status per document, most recently updated first"),
208
+ loadFailures: z.array(z.object({
209
+ package: z.string(),
210
+ kind: z.string().describe("What failed to load, e.g. \"document models\""),
211
+ message: z.string(),
212
+ updatedAt: z.string()
213
+ })).describe("Project modules that failed to load"),
214
+ message: z.string().optional()
215
+ }),
216
+ annotations: {
217
+ readOnlyHint: true,
218
+ destructiveHint: false,
219
+ openWorldHint: false
220
+ },
221
+ async execute(args, { client, signal }) {
222
+ if (!codegen.active) return {
223
+ active: false,
224
+ settled: true,
225
+ documents: [],
226
+ loadFailures: codegen.loadFailures(),
227
+ message: "No Vetra codegen runs on this reactor; `ph vetra` runs it for the project's Vetra drive"
228
+ };
229
+ let documentId = args.documentId;
230
+ if (documentId !== void 0 && !codegen.get(documentId)) try {
231
+ documentId = (await client.get(documentId, void 0, signal)).header.id;
232
+ } catch {}
233
+ const waitMs = (args.waitSeconds ?? 0) * 1e3;
234
+ const settled = waitMs > 0 ? await codegen.waitUntilSettled(documentId, waitMs) : codegen.settled(documentId);
235
+ const documents = documentId === void 0 ? codegen.list() : [codegen.get(documentId)].filter((status) => status !== void 0);
236
+ return {
237
+ active: true,
238
+ settled,
239
+ documents,
240
+ loadFailures: codegen.loadFailures(),
241
+ ...documentId !== void 0 && documents.length === 0 && { message: `No codegen recorded for ${args.documentId}. Vetra generates code for documents of type ${codegen.documentTypes.join(", ")} in its drive, once they change.` }
242
+ };
243
+ }
244
+ });
245
+ }
246
+ //#endregion
247
+ //#region src/tools/compact-schema.ts
248
+ const compactDocumentModelSchemaSchema = z.object({
249
+ id: z.string(),
250
+ name: z.string(),
251
+ version: z.number(),
252
+ actions: z.array(z.object({
253
+ type: z.string(),
254
+ scope: z.string(),
255
+ input: z.string().nullable().describe("The input's GraphQL definition; null without input")
256
+ })).describe("What addActions takes as type, scope and input"),
257
+ types: z.record(z.string(), z.string()).optional().describe("Enums and types the inputs reference from the state schemas")
258
+ });
259
+ const BUILTIN_SCALARS = /* @__PURE__ */ new Set([
260
+ "String",
261
+ "Int",
262
+ "Float",
263
+ "Boolean",
264
+ "ID"
265
+ ]);
266
+ function stripComments(source) {
267
+ return source.replace(/"""[\s\S]*?"""/g, "").replace(/"[^"\n]*"/g, "").replace(/#[^\n]*/g, "");
268
+ }
269
+ function collapse(definition) {
270
+ return stripComments(definition).replace(/\s+/g, " ").trim();
271
+ }
272
+ /** Named enum, input, type and union definitions in a GraphQL source. */
273
+ function definitionsOf(source) {
274
+ const definitions = /* @__PURE__ */ new Map();
275
+ for (const [definition, name, unionName] of stripComments(source).matchAll(/\b(?:enum|input|type)\s+(\w+)[^{]*\{[^}]*\}|\bunion\s+(\w+)\s*=\s*\|?\s*\w+(?:\s*\|\s*\w+)*/g)) definitions.set(name || unionName, collapse(definition));
276
+ return definitions;
277
+ }
278
+ function referencedNames(definition) {
279
+ const names = /* @__PURE__ */ new Set();
280
+ for (const match of definition.matchAll(/:\s*\[?\s*(\w+)/g)) names.add(match[1]);
281
+ for (const match of definition.matchAll(/=\s*([\w\s|]+)/g)) for (const name of match[1].split("|")) names.add(name.trim());
282
+ return names;
283
+ }
284
+ /** The parts of a document model's latest specification that writing actions needs. */
285
+ function compactDocumentModelSchema(model) {
286
+ const spec = model.specifications.at(-1);
287
+ const operations = spec?.modules.flatMap((module) => module.operations) ?? [];
288
+ const stateDefinitions = definitionsOf(Object.values(spec?.state ?? {}).map((state) => state.schema).join("\n"));
289
+ const types = {};
290
+ const visit = (definition, local) => {
291
+ for (const name of referencedNames(definition)) {
292
+ if (BUILTIN_SCALARS.has(name) || local.has(name) || name in types) continue;
293
+ const referenced = stateDefinitions.get(name);
294
+ if (!referenced) continue;
295
+ types[name] = referenced;
296
+ visit(referenced, local);
297
+ }
298
+ };
299
+ const actions = operations.flatMap((operation) => {
300
+ if (!operation.name) return [];
301
+ const input = operation.schema ? collapse(operation.schema) : null;
302
+ if (operation.schema) visit(operation.schema, definitionsOf(operation.schema));
303
+ return [{
304
+ type: operation.name,
305
+ scope: operation.scope,
306
+ input
307
+ }];
308
+ });
309
+ return {
310
+ id: model.id,
311
+ name: model.name,
312
+ version: spec?.version ?? 1,
313
+ actions,
314
+ ...Object.keys(types).length ? { types } : {}
315
+ };
316
+ }
317
+ //#endregion
318
+ //#region src/tools/jsonpath.ts
319
+ var JsonPathError = class extends Error {
320
+ constructor(path, reason) {
321
+ super(`Invalid JSONPath "${path}": ${reason}`);
322
+ this.name = "JsonPathError";
323
+ }
324
+ };
325
+ const NAME = /^[A-Za-z_$][\w$-]*/;
326
+ function parseLiteral(text, path) {
327
+ const t = text.trim();
328
+ if (/^'.*'$/s.test(t)) return t.slice(1, -1).replace(/\\'/g, "'");
329
+ if (/^".*"$/s.test(t)) return JSON.parse(t);
330
+ if (t === "true") return true;
331
+ if (t === "false") return false;
332
+ if (t === "null") return null;
333
+ if (t !== "" && !Number.isNaN(Number(t))) return Number(t);
334
+ throw new JsonPathError(path, `unsupported literal ${t}`);
335
+ }
336
+ function parseFilter(body, path) {
337
+ const match = /^@((?:\.[A-Za-z_$][\w$-]*)*)\s*(?:(==|!=|<=|>=|<|>)\s*(.+))?$/s.exec(body.trim());
338
+ if (!match) throw new JsonPathError(path, `unsupported filter ${body}`);
339
+ const keys = match[1] ? match[1].slice(1).split(".") : [];
340
+ if (!match[2]) return {
341
+ kind: "filter",
342
+ path: keys
343
+ };
344
+ return {
345
+ kind: "filter",
346
+ path: keys,
347
+ op: match[2],
348
+ value: parseLiteral(match[3], path)
349
+ };
350
+ }
351
+ function splitUnion(body) {
352
+ const parts = [];
353
+ let quote;
354
+ let current = "";
355
+ for (const char of body) {
356
+ if (quote) {
357
+ if (char === quote) quote = void 0;
358
+ } else if (char === "'" || char === "\"") quote = char;
359
+ else if (char === ",") {
360
+ parts.push(current);
361
+ current = "";
362
+ continue;
363
+ }
364
+ current += char;
365
+ }
366
+ parts.push(current);
367
+ return parts;
368
+ }
369
+ function parseBracket(body, path) {
370
+ const t = body.trim();
371
+ if (t === "*") return { kind: "wildcard" };
372
+ if (t.startsWith("?(") && t.endsWith(")")) return parseFilter(t.slice(2, -1), path);
373
+ const length = /^\(\s*@\.length\s*-\s*(\d+)\s*\)$/.exec(t);
374
+ if (length) return {
375
+ kind: "child",
376
+ keys: [-Number(length[1])]
377
+ };
378
+ return {
379
+ kind: "child",
380
+ keys: splitUnion(t).map((part) => {
381
+ const p = part.trim();
382
+ if (/^-?\d+$/.test(p)) return Number(p);
383
+ const literal = parseLiteral(p, path);
384
+ if (typeof literal !== "string") throw new JsonPathError(path, `unsupported selector ${p}`);
385
+ return literal;
386
+ })
387
+ };
388
+ }
389
+ function closingBracket(path, start) {
390
+ let depth = 0;
391
+ let quote;
392
+ for (let i = start; i < path.length; i++) {
393
+ const char = path[i];
394
+ if (quote) {
395
+ if (char === quote && path[i - 1] !== "\\") quote = void 0;
396
+ } else if (char === "'" || char === "\"") quote = char;
397
+ else if (char === "[") depth++;
398
+ else if (char === "]") {
399
+ depth--;
400
+ if (depth === 0) return i;
401
+ }
402
+ }
403
+ throw new JsonPathError(path, "unclosed [");
404
+ }
405
+ function parseJsonPath(path) {
406
+ const text = path.trim();
407
+ if (!text.startsWith("$")) throw new JsonPathError(path, "must start with $");
408
+ const segments = [];
409
+ let i = 1;
410
+ while (i < text.length) {
411
+ const rest = text.slice(i);
412
+ if (rest.startsWith("..")) {
413
+ i += 2;
414
+ if (text[i] === "*") {
415
+ segments.push({
416
+ kind: "descend",
417
+ key: "*"
418
+ });
419
+ i++;
420
+ continue;
421
+ }
422
+ if (text[i] === "[") {
423
+ segments.push({ kind: "recurse" });
424
+ continue;
425
+ }
426
+ const name = NAME.exec(text.slice(i));
427
+ if (!name) throw new JsonPathError(path, `expected a name at ${i}`);
428
+ segments.push({
429
+ kind: "descend",
430
+ key: name[0]
431
+ });
432
+ i += name[0].length;
433
+ } else if (rest.startsWith(".")) {
434
+ i++;
435
+ if (text[i] === "*") {
436
+ segments.push({ kind: "wildcard" });
437
+ i++;
438
+ continue;
439
+ }
440
+ const name = NAME.exec(text.slice(i));
441
+ if (!name) throw new JsonPathError(path, `expected a name at ${i}`);
442
+ segments.push({
443
+ kind: "child",
444
+ keys: [name[0]]
445
+ });
446
+ i += name[0].length;
447
+ } else if (rest.startsWith("[")) {
448
+ const end = closingBracket(text, i);
449
+ segments.push(parseBracket(text.slice(i + 1, end), path));
450
+ i = end + 1;
451
+ } else throw new JsonPathError(path, `unexpected "${text[i]}" at ${i}`);
452
+ }
453
+ return segments;
454
+ }
455
+ function children(value) {
456
+ if (Array.isArray(value)) return value;
457
+ if (value !== null && typeof value === "object") return Object.values(value);
458
+ return [];
459
+ }
460
+ function child(value, key) {
461
+ if (Array.isArray(value)) {
462
+ if (typeof key === "number") {
463
+ const index = key < 0 ? value.length + key : key;
464
+ return index >= 0 && index < value.length ? [value[index]] : [];
465
+ }
466
+ return key === "length" ? [value.length] : [];
467
+ }
468
+ if (value !== null && typeof value === "object") {
469
+ const record = value;
470
+ const name = String(key);
471
+ return Object.hasOwn(record, name) ? [record[name]] : [];
472
+ }
473
+ return [];
474
+ }
475
+ function descendants(value) {
476
+ const out = [value];
477
+ for (const next of children(value)) out.push(...descendants(next));
478
+ return out;
479
+ }
480
+ function compare(left, op, right) {
481
+ switch (op) {
482
+ case "==": return left === right;
483
+ case "!=": return left !== right;
484
+ default: {
485
+ if (typeof left !== typeof right) return false;
486
+ if (typeof left !== "number" && typeof left !== "string") return false;
487
+ const l = left;
488
+ const r = right;
489
+ if (op === "<") return l < r;
490
+ if (op === "<=") return l <= r;
491
+ if (op === ">") return l > r;
492
+ return l >= r;
493
+ }
494
+ }
495
+ }
496
+ function matchesFilter(item, segment) {
497
+ let current = [item];
498
+ for (const key of segment.path) current = current.flatMap((v) => child(v, key));
499
+ if (current.length === 0) return false;
500
+ if (!segment.op) return Boolean(current[0]);
501
+ return compare(current[0], segment.op, segment.value);
502
+ }
503
+ /** Every node `path` selects in `value`, in document order. */
504
+ function queryJsonPath(value, path) {
505
+ let nodes = [value];
506
+ for (const segment of parseJsonPath(path)) switch (segment.kind) {
507
+ case "child":
508
+ nodes = nodes.flatMap((n) => segment.keys.flatMap((k) => child(n, k)));
509
+ break;
510
+ case "wildcard":
511
+ nodes = nodes.flatMap(children);
512
+ break;
513
+ case "descend":
514
+ nodes = nodes.flatMap(descendants).flatMap((n) => segment.key === "*" ? children(n) : child(n, segment.key));
515
+ break;
516
+ case "recurse":
517
+ nodes = nodes.flatMap(descendants);
518
+ break;
519
+ case "filter": nodes = nodes.flatMap((n) => children(n).filter((item) => matchesFilter(item, segment)));
520
+ }
521
+ return nodes;
522
+ }
523
+ /** The match of `path`: undefined for none, the value for one, an array for many. */
524
+ function isDefinite(path) {
525
+ return parseJsonPath(path).every((segment) => segment.kind === "child" && segment.keys.length === 1);
526
+ }
527
+ function applyJsonPath(value, path) {
528
+ const results = queryJsonPath(value, path);
529
+ if (!isDefinite(path)) return results;
530
+ return results[0];
531
+ }
532
+ //#endregion
533
+ //#region src/tools/documents.ts
534
+ const DRIVE_DOCUMENT_TYPE = "powerhouse/document-drive";
535
+ /** Document types that hold files, as the reactor's drive containers. */
536
+ const DRIVE_DOCUMENT_TYPES = /* @__PURE__ */ new Set([DRIVE_DOCUMENT_TYPE, "powerhouse/reactor-drive"]);
537
+ const DEFAULT_BRANCH = "main";
538
+ const DEFAULT_TRIM_LIMITS = {
539
+ maxArrayItems: 25,
540
+ maxStringLength: 2e3,
541
+ maxDepth: 8
542
+ };
543
+ /** Caps arrays, strings and depth, leaving a marker where it cut. */
544
+ function trimValue(value, limits = {}) {
545
+ const l = {
546
+ ...DEFAULT_TRIM_LIMITS,
547
+ ...limits
548
+ };
549
+ let truncated = false;
550
+ const walk = (v, depth) => {
551
+ if (typeof v === "string") {
552
+ if (v.length <= l.maxStringLength) return v;
553
+ truncated = true;
554
+ return `${v.slice(0, l.maxStringLength)}…[+${v.length - l.maxStringLength} chars]`;
555
+ }
556
+ if (v === null || typeof v !== "object") return v;
557
+ if (Object.keys(v).length === 0) return v;
558
+ if (depth >= l.maxDepth) {
559
+ truncated = true;
560
+ return Array.isArray(v) ? `[array of ${v.length}]` : `[object with keys: ${Object.keys(v).join(", ")}]`;
561
+ }
562
+ if (Array.isArray(v)) {
563
+ const items = v.slice(0, l.maxArrayItems).map((i) => walk(i, depth + 1));
564
+ if (v.length > l.maxArrayItems) {
565
+ truncated = true;
566
+ items.push(`…${v.length - l.maxArrayItems} more items`);
567
+ }
568
+ return items;
569
+ }
570
+ return Object.fromEntries(Object.entries(v).map(([k, child]) => [k, walk(child, depth + 1)]));
571
+ };
572
+ return {
573
+ value: walk(value, 0),
574
+ truncated
575
+ };
576
+ }
577
+ const documentSummarySchema = z.object({
578
+ id: z.string(),
579
+ documentType: z.string(),
580
+ name: z.string()
581
+ });
582
+ function globalState(document) {
583
+ const global = document.state.global;
584
+ return global && typeof global === "object" ? global : {};
585
+ }
586
+ function documentName(document) {
587
+ const name = globalState(document).name;
588
+ return document.header.name || (typeof name === "string" ? name : "");
589
+ }
590
+ function documentSummary(document) {
591
+ return {
592
+ id: document.header.id,
593
+ documentType: document.header.documentType,
594
+ name: documentName(document)
595
+ };
596
+ }
597
+ const documentViewSchema = documentSummarySchema.extend({
598
+ slug: z.string().optional(),
599
+ branch: z.string(),
600
+ revision: z.record(z.string(), z.number()),
601
+ lastModifiedAtUtcIso: z.string().optional(),
602
+ state: z.unknown().describe("The model scopes, or the filter's match when one was given"),
603
+ truncated: z.boolean().optional().describe("True when long arrays or strings were cut; a filter reads the part it selects in full")
604
+ });
605
+ /** A filter's match is returned whole up to this many JSON characters. */
606
+ const MAX_FILTERED_CHARS = 1e5;
607
+ function jsonLength(value) {
608
+ try {
609
+ return JSON.stringify(value)?.length ?? 0;
610
+ } catch {
611
+ return Infinity;
612
+ }
613
+ }
614
+ function isEmpty(value) {
615
+ return value === void 0 || value !== null && typeof value === "object" && Object.keys(value).length === 0;
616
+ }
617
+ /** A compact document: header essentials plus model state, projected and trimmed. */
618
+ function documentView(document, options = {}) {
619
+ const { filter, scopes = ["global", "local"], limits } = options;
620
+ const state = document.state;
621
+ let selected;
622
+ if (filter) try {
623
+ selected = applyJsonPath(state, filter);
624
+ } catch (error) {
625
+ if (error instanceof JsonPathError) throw new ReactorToolError("INVALID_ACTION", error.message);
626
+ throw error;
627
+ }
628
+ else selected = Object.fromEntries(scopes.filter((scope) => !isEmpty(state[scope])).map((scope) => [scope, state[scope]]));
629
+ const trimmed = filter && jsonLength(selected) <= 1e5 ? {
630
+ value: selected,
631
+ truncated: false
632
+ } : trimValue(selected, limits);
633
+ const header = document.header;
634
+ return {
635
+ ...documentSummary(document),
636
+ ...header.slug ? { slug: header.slug } : {},
637
+ branch: header.branch || "main",
638
+ revision: { ...header.revision },
639
+ ...header.lastModifiedAtUtcIso ? { lastModifiedAtUtcIso: header.lastModifiedAtUtcIso } : {},
640
+ state: trimmed.value,
641
+ ...trimmed.truncated ? { truncated: true } : {}
642
+ };
643
+ }
644
+ //#endregion
645
+ //#region src/tools/suggest.ts
646
+ function isSubsequence(needle, haystack) {
647
+ let i = 0;
648
+ for (let j = 0; j < haystack.length && i < needle.length; j++) if (needle[i] === haystack[j]) i++;
649
+ return i === needle.length;
650
+ }
651
+ function editDistance(a, b) {
652
+ if (a === b) return 0;
653
+ if (a.length === 0) return b.length;
654
+ if (b.length === 0) return a.length;
655
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
656
+ let curr = new Array(b.length + 1);
657
+ for (let i = 1; i <= a.length; i++) {
658
+ curr[0] = i;
659
+ for (let j = 1; j <= b.length; j++) {
660
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
661
+ curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
662
+ }
663
+ [prev, curr] = [curr, prev];
664
+ }
665
+ return prev[b.length];
666
+ }
667
+ /** Closest `candidates` to `query`: containment first, then edit distance. */
668
+ function suggestNames(query, candidates, max = 3) {
669
+ const q = query.toUpperCase();
670
+ const scored = candidates.map((name) => {
671
+ const u = name.toUpperCase();
672
+ if (u.includes(q) || q.includes(u)) return {
673
+ name,
674
+ d: 0,
675
+ strong: true
676
+ };
677
+ if (u.length >= q.length ? isSubsequence(q, u) : isSubsequence(u, q)) return {
678
+ name,
679
+ d: Math.abs(u.length - q.length),
680
+ strong: true
681
+ };
682
+ return {
683
+ name,
684
+ d: editDistance(q, u),
685
+ strong: false
686
+ };
687
+ });
688
+ const threshold = Math.max(3, Math.ceil(q.length * .6) + 3);
689
+ return scored.filter((s) => s.strong || s.d <= threshold).sort((a, b) => a.d - b.d || a.name.localeCompare(b.name)).slice(0, max).map((s) => s.name);
690
+ }
691
+ /** `Unknown <subject> "<value>".` plus a did-you-mean line and, when short, the known names. */
692
+ function unknownValueMessage(subject, value, candidates, options = {}) {
693
+ const { knownLabel, inlineLimit = 20, context } = options;
694
+ const lines = [`Unknown ${subject} "${value}"${context ? ` ${context}` : ""}.`];
695
+ const suggestions = suggestNames(value, candidates);
696
+ if (suggestions.length > 0) lines.push(`Did you mean: ${suggestions.join(", ")}?`);
697
+ if (knownLabel && candidates.length > 0 && candidates.length <= inlineLimit) lines.push(`${knownLabel}: ${candidates.join(", ")}`);
698
+ return lines.join("\n");
699
+ }
700
+ //#endregion
701
+ //#region src/tools/model-operations.ts
702
+ const logger = childLogger(["reactor-mcp", "model-operations"]);
703
+ const logged = /* @__PURE__ */ new Set();
704
+ function inspect(module) {
705
+ const inspection = inspectDocumentModelDefinition(module);
706
+ if ("diagnostics" in inspection) {
707
+ const documentType = module.documentModel.global.id;
708
+ const key = `${documentType}\n${inspection.reason}`;
709
+ if (!logged.has(key)) {
710
+ logged.add(key);
711
+ logger.warn("Serving @type from its stored model; its definition is @reason: @diagnostics", documentType, inspection.reason, inspection.diagnostics.map((d) => d.message).join("; "));
712
+ }
713
+ }
714
+ return inspection;
715
+ }
716
+ function structuredDefinition(module) {
717
+ const inspection = inspect(module);
718
+ return inspection.kind === "structured" ? inspection.definition : null;
719
+ }
720
+ const indexes = /* @__PURE__ */ new WeakMap();
721
+ const NONE = /* @__PURE__ */ new Map();
722
+ /**
723
+ * The operations of a model authored in code, keyed by action type; empty for
724
+ * a model served from its stored specification. Callers consult it only for a
725
+ * type that names no stored operation, so every stored name keeps main's
726
+ * meaning.
727
+ */
728
+ function operationsByActionType(module) {
729
+ const inspection = inspect(module);
730
+ if (inspection.kind !== "structured") return NONE;
731
+ const { specification } = inspection;
732
+ let byActionType = indexes.get(specification);
733
+ if (byActionType === void 0) {
734
+ byActionType = new Map(specification.modules.flatMap((m) => m.operations).map((operation) => [operation.actionType, {
735
+ storedName: operation.name ?? operation.actionType,
736
+ creatorKey: operation.creatorKey
737
+ }]));
738
+ indexes.set(specification, byActionType);
739
+ }
740
+ return byActionType;
741
+ }
742
+ //#endregion
743
+ //#region src/tools/schema.ts
744
+ /** Marks a base action that runs in whichever scope it is sent to; never itself a scope. */
745
+ const ANY_SCOPE = "any";
746
+ const BASE_OPERATIONS = [
747
+ {
748
+ name: "SET_NAME",
749
+ module: "base",
750
+ scope: "global",
751
+ description: "Renames the document",
752
+ schema: "input SetNameInput {\n name: String!\n}"
753
+ },
754
+ {
755
+ name: "SET_PREFERRED_EDITOR",
756
+ module: "base",
757
+ scope: "header",
758
+ description: "Sets the editor that opens the document",
759
+ schema: "input SetPreferredEditorInput {\n preferredEditor: String\n}"
760
+ },
761
+ {
762
+ name: "UNDO",
763
+ module: "base",
764
+ scope: "any",
765
+ description: "Undoes the scope's last operations",
766
+ schema: "input UndoInput {\n count: Int\n}"
767
+ },
768
+ {
769
+ name: "REDO",
770
+ module: "base",
771
+ scope: "any",
772
+ description: "Redoes the scope's last undone operations",
773
+ schema: "input RedoInput {\n count: Int\n}"
774
+ },
775
+ {
776
+ name: "NOOP",
777
+ module: "base",
778
+ scope: "any",
779
+ description: "Changes nothing"
780
+ }
781
+ ];
782
+ const modelOperationSchema = z.object({
783
+ name: z.string(),
784
+ module: z.string(),
785
+ scope: z.string(),
786
+ description: z.string().optional(),
787
+ schema: z.string().optional().describe("GraphQL SDL of the action input")
788
+ });
789
+ const documentModelInfoSchema = z.object({
790
+ type: z.string(),
791
+ name: z.string(),
792
+ description: z.string(),
793
+ extension: z.string(),
794
+ authorName: z.string(),
795
+ authorWebsite: z.string()
796
+ });
797
+ function documentModelInfo(module) {
798
+ const global = module.documentModel.global;
799
+ return {
800
+ type: global.id,
801
+ name: global.name,
802
+ description: global.description,
803
+ extension: global.extension,
804
+ authorName: global.author.name,
805
+ authorWebsite: global.author.website ?? ""
806
+ };
807
+ }
808
+ function latestSpecification(module) {
809
+ return module.documentModel.global.specifications.at(-1);
810
+ }
811
+ /** The model's operations in its latest specification, without the base ones. */
812
+ function modelOperations(module) {
813
+ return (latestSpecification(module)?.modules ?? []).flatMap((m) => m.operations.filter((op) => Boolean(op.name)).map((op) => ({
814
+ name: op.name,
815
+ module: m.name,
816
+ scope: op.scope || "global",
817
+ ...op.description ? { description: op.description } : {},
818
+ ...op.schema ? { schema: op.schema } : {}
819
+ })));
820
+ }
821
+ /** Every action type the document accepts: the model's and the base ones. */
822
+ function actionOperations(module) {
823
+ return [...modelOperations(module), ...BASE_OPERATIONS];
824
+ }
825
+ const documentModelSummarySchema = z.object({
826
+ type: z.string(),
827
+ name: z.string(),
828
+ description: z.string(),
829
+ version: z.number().describe("Version of the latest specification"),
830
+ modules: z.array(z.object({
831
+ name: z.string(),
832
+ operations: z.array(z.string())
833
+ }))
834
+ });
835
+ /** Model name, latest version and its operation names by module. */
836
+ function documentModelSummary(module) {
837
+ const global = module.documentModel.global;
838
+ const latest = latestSpecification(module);
839
+ return {
840
+ type: global.id,
841
+ name: global.name,
842
+ description: global.description,
843
+ version: latest?.version ?? global.specifications.length,
844
+ modules: (latest?.modules ?? []).map((m) => ({
845
+ name: m.name,
846
+ operations: m.operations.map((op) => op.name).filter((name) => Boolean(name))
847
+ }))
848
+ };
849
+ }
850
+ const operationSliceSchema = modelOperationSchema.extend({ errors: z.array(z.object({
851
+ name: z.string(),
852
+ description: z.string().optional()
853
+ })).optional() });
854
+ /** One operation's input schema; unknown names fail with did-you-mean. */
855
+ function operationSchemaSlice(module, operationName) {
856
+ const operations = actionOperations(module);
857
+ const storedName = operationsByActionType(module).get(operationName)?.storedName;
858
+ const operation = operations.find((op) => op.name === operationName) ?? operations.find((op) => op.name === storedName);
859
+ if (!operation) throw new ReactorToolError("NOT_FOUND", unknownValueMessage("operation", operationName, operations.map((op) => op.name), {
860
+ context: `for ${module.documentModel.global.id}`,
861
+ knownLabel: "Valid action types"
862
+ }));
863
+ const errors = ((latestSpecification(module)?.modules.flatMap((m) => m.operations).find((op) => op.name === operation.name))?.errors ?? []).filter((e) => e.name).map((e) => ({
864
+ name: e.name,
865
+ ...e.description ? { description: e.description } : {}
866
+ }));
867
+ return {
868
+ ...presentedScope(operation),
869
+ ...errors.length ? { errors } : {}
870
+ };
871
+ }
872
+ function presentedScope(operation) {
873
+ if (operation.scope !== "any") return operation;
874
+ const note = "Runs in any of the document's scopes; scope defaults to global.";
875
+ return {
876
+ ...operation,
877
+ scope: "global",
878
+ description: operation.description ? `${operation.description}. ${note}` : note
879
+ };
880
+ }
881
+ const stateSliceSchema = z.object({
882
+ scope: z.string(),
883
+ schema: z.string().describe("GraphQL SDL of the scope's state"),
884
+ initialValue: z.string().optional()
885
+ });
886
+ /** The state schema of one scope in the latest specification. */
887
+ function stateSchemaSlice(module, scope = "global") {
888
+ const state = latestSpecification(module)?.state[scope];
889
+ return {
890
+ scope,
891
+ schema: state?.schema ?? "",
892
+ ...state?.initialValue ? { initialValue: state.initialValue } : {}
893
+ };
894
+ }
895
+ //#endregion
896
+ //#region src/tools/validation.ts
897
+ const actionInputSchema = z.object({
898
+ type: z.string().describe("Exact action type from the model's operations, e.g. SET_MODEL_NAME; see getDocumentModelSchema"),
899
+ input: z.unknown().optional().describe("Action input, shaped by the operation's input schema"),
900
+ scope: z.string().optional().describe("Defaults to the operation's scope; rarely needed")
901
+ });
902
+ function countInput(input) {
903
+ if (typeof input === "number") return input;
904
+ const count = input?.count;
905
+ return typeof count === "number" ? count : void 0;
906
+ }
907
+ const BASE_CREATORS = {
908
+ SET_NAME: (input) => baseActions.setName(input),
909
+ SET_PREFERRED_EDITOR: (input) => baseActions.setPreferredEditor(input),
910
+ UNDO: (input) => baseActions.undo(countInput(input)),
911
+ REDO: (input) => baseActions.redo(countInput(input)),
912
+ NOOP: () => baseActions.noop()
913
+ };
914
+ function issueLines(error) {
915
+ const issues = error.issues;
916
+ if (Array.isArray(issues)) return {
917
+ shape: true,
918
+ lines: issues.map((raw) => {
919
+ const issue = raw;
920
+ const path = Array.isArray(issue.path) ? issue.path.join(".") : "";
921
+ const message = (issue.message ?? "invalid").replace(/^Invalid input:\s*/, "");
922
+ return path ? `${path}: ${message}` : message;
923
+ })
924
+ };
925
+ return {
926
+ shape: false,
927
+ lines: [error instanceof Error ? error.message : String(error)]
928
+ };
929
+ }
930
+ /** Builds the actions, collecting every failure instead of stopping at the first. */
931
+ function validateActions(module, inputs, options = {}) {
932
+ const operations = new Map(actionOperations(module).map((o) => [o.name, o]));
933
+ const byActionType = operationsByActionType(module);
934
+ const allowed = options.allowedActionTypes ? new Set(options.allowedActionTypes) : void 0;
935
+ const actions = [];
936
+ const failures = [];
937
+ inputs.forEach((entry, index) => {
938
+ const fail = (code, errors) => failures.push({
939
+ index,
940
+ type: entry.type,
941
+ code,
942
+ errors
943
+ });
944
+ if (DOCUMENT_SCOPE_ACTION_TYPES.has(entry.type)) return fail("FORBIDDEN", ["document lifecycle actions are refused; use createDocument or deleteDocument"]);
945
+ if (allowed && !allowed.has(entry.type)) return fail("FORBIDDEN", [`not an allowed action type (allowed: ${[...allowed].join(", ")})`]);
946
+ const structured = operations.has(entry.type) ? void 0 : byActionType.get(entry.type);
947
+ const operation = operations.get(structured?.storedName ?? entry.type);
948
+ if (!operation) return fail("INVALID_ACTION", ["unknown action type"]);
949
+ if (entry.scope === "any") return fail("INVALID_ACTION", [`"any" is not a scope; name one, e.g. "global"`]);
950
+ const anyScope = operation.scope === "any";
951
+ const scope = entry.scope ?? (anyScope ? "global" : operation.scope);
952
+ if (!anyScope && scope !== operation.scope) return fail("INVALID_ACTION", [`scope "${scope}" does not match the operation's scope "${operation.scope}"`]);
953
+ const creator = BASE_CREATORS[entry.type] ?? module.actions[structured?.creatorKey ?? camelCase(entry.type)];
954
+ if (!creator) return fail("INVALID_ACTION", [`the model has no action creator for ${entry.type}`]);
955
+ try {
956
+ actions.push({
957
+ ...creator(entry.input ?? {}),
958
+ scope
959
+ });
960
+ } catch (error) {
961
+ fail("INVALID_ACTION", issueLines(error).lines);
962
+ }
963
+ });
964
+ return {
965
+ actions,
966
+ failures
967
+ };
968
+ }
969
+ /** One line per failed action, did-you-mean for unknown types, and input schemas for shape errors. */
970
+ function formatActionFailures(failures, module) {
971
+ const operations = module ? actionOperations(module) : [];
972
+ const names = operations.map((o) => o.name);
973
+ const byActionType = module && operationsByActionType(module);
974
+ const nameOf = (type) => names.includes(type) ? type : byActionType?.get(type)?.storedName ?? type;
975
+ const count = failures.length;
976
+ const lines = failures.map((f) => ` [${f.index}] ${f.type}: ${f.errors.join("; ")}`);
977
+ const sections = [];
978
+ const unknown = failures.filter((f) => f.code === "INVALID_ACTION" && module && !names.includes(nameOf(f.type)));
979
+ if (unknown.length > 0) {
980
+ const suggestions = new Set(unknown.flatMap((f) => suggestNames(f.type, names)));
981
+ const hint = suggestions.size ? `Did you mean: ${[...suggestions].join(", ")}?\n` : "";
982
+ sections.push(`${hint}Valid action types for ${module?.documentModel.global.id}:\n ${names.join(", ")}`);
983
+ }
984
+ const shown = /* @__PURE__ */ new Set();
985
+ for (const f of failures) {
986
+ const name = nameOf(f.type);
987
+ const operation = operations.find((o) => o.name === name);
988
+ if (f.code !== "INVALID_ACTION" || !operation?.schema || shown.has(operation.name)) continue;
989
+ shown.add(operation.name);
990
+ sections.push(`Input schema for ${operation.name}:\n${operation.schema}`);
991
+ }
992
+ const head = `${count} action${count === 1 ? "" : "s"} failed:\n${lines.join("\n")}`;
993
+ return sections.length ? `${head}\n\n${sections.join("\n\n")}` : head;
994
+ }
995
+ /** The error for a batch with failures; the code is the batch's most severe one. */
996
+ function actionFailuresError(failures, module) {
997
+ const codes = new Set(failures.map((f) => f.code));
998
+ return new ReactorToolError(codes.has("FORBIDDEN") ? "FORBIDDEN" : codes.has("INVALID_ACTION") ? "INVALID_ACTION" : "REDUCER_ERROR", formatActionFailures(failures, module), { failures });
999
+ }
1000
+ //#endregion
1001
+ //#region src/tools/operations.ts
1002
+ async function getDocument(client, identifier, signal, options = {}) {
1003
+ const { branch, token } = options;
1004
+ try {
1005
+ return await client.get(identifier, branch ? { branch } : void 0, signal, token);
1006
+ } catch (error) {
1007
+ throw toReactorToolError(error, "NOT_FOUND");
1008
+ }
1009
+ }
1010
+ /** The model module for a type; an unknown type fails with did-you-mean. */
1011
+ async function getDocumentModel(client, documentType, signal) {
1012
+ try {
1013
+ return await client.getDocumentModelModule(documentType);
1014
+ } catch (error) {
1015
+ throw new ReactorToolError("NOT_FOUND", unknownValueMessage("document type", documentType, await client.getDocumentModelModules(void 0, void 0, signal).then((r) => r.results.map((m) => m.documentModel.global.id)).catch(() => []), { knownLabel: "Known types" }), { cause: error });
1016
+ }
1017
+ }
1018
+ const OPERATIONS_PAGE_SIZE = 100;
1019
+ async function storedOutcomes(client, documentId, branch, actions, before, signal) {
1020
+ const ids = new Set(actions.map((a) => a.id));
1021
+ const outcomes = /* @__PURE__ */ new Map();
1022
+ for (const scope of new Set(actions.map((a) => a.scope))) {
1023
+ let cursor = "0";
1024
+ while (cursor !== void 0) {
1025
+ const page = await client.getOperations(documentId, {
1026
+ branch,
1027
+ scopes: [scope]
1028
+ }, { sinceRevision: before[scope] ?? 0 }, {
1029
+ cursor,
1030
+ limit: OPERATIONS_PAGE_SIZE
1031
+ }, signal);
1032
+ for (const operation of page.results) {
1033
+ if (!ids.has(operation.action.id)) continue;
1034
+ outcomes.set(operation.action.id, {
1035
+ operationIndex: operation.index,
1036
+ ...operationOutcome(operation)
1037
+ });
1038
+ }
1039
+ cursor = page.results.length > 0 ? page.nextCursor : void 0;
1040
+ }
1041
+ }
1042
+ return outcomes;
1043
+ }
1044
+ async function readable(handle) {
1045
+ return (await handle).readable;
1046
+ }
1047
+ async function actionOutcomes(client, receipt, actions, before, signal) {
1048
+ const summary = receipt.job.result;
1049
+ if (summary) return new Map(summary.actions.map((a) => [a.actionId, {
1050
+ ...a,
1051
+ operationIndex: a.index
1052
+ }]));
1053
+ return storedOutcomes(client, receipt.documentId, receipt.branch, actions, before, signal);
1054
+ }
1055
+ async function revisionAfter(client, receipt, signal) {
1056
+ return { ...(await getDocument(client, receipt.documentId, signal, {
1057
+ branch: receipt.branch,
1058
+ token: receipt.token
1059
+ })).header.revision };
1060
+ }
1061
+ const DENIED_INDEXES = /; denied action indexes: \[(\d+(?:,\d+)*)\]$/;
1062
+ function deniedActions(error) {
1063
+ const denied = error?.denied;
1064
+ if (Array.isArray(denied)) return denied;
1065
+ if (!(error instanceof Error) || error.name !== "ReactorAccessDeniedError") return;
1066
+ const match = DENIED_INDEXES.exec(error.message);
1067
+ if (!match) return void 0;
1068
+ const reason = error.message.slice(0, match.index);
1069
+ return match[1].split(",").map((index) => ({
1070
+ index: Number(index),
1071
+ type: "",
1072
+ reason
1073
+ }));
1074
+ }
1075
+ function isDenial(error) {
1076
+ if (deniedActions(error)) return true;
1077
+ if (!(error instanceof Error)) return false;
1078
+ const job = error.job;
1079
+ return error.name === "AuthorizationDeniedError" || error.name === "JobFailedError" && job?.error?.name === "AuthorizationDeniedError";
1080
+ }
1081
+ const NO_OPERATION = "The reactor stored no operation for this action";
1082
+ /** Executes built actions and returns the new revision; any action not applied throws. */
1083
+ async function executeBuiltActions(client, document, actions, options = {}) {
1084
+ const { branch = DEFAULT_BRANCH, signal, module } = options;
1085
+ let receipt;
1086
+ try {
1087
+ receipt = await readable(client.write.execute(document.header.id, branch, actions, signal));
1088
+ } catch (error) {
1089
+ const denied = deniedActions(error);
1090
+ if (denied) throw actionFailuresError(denied.map((d) => ({
1091
+ index: d.index,
1092
+ type: d.type || (actions.at(d.index)?.type ?? ""),
1093
+ code: "FORBIDDEN",
1094
+ errors: [d.reason]
1095
+ })), module);
1096
+ throw toReactorToolError(error);
1097
+ }
1098
+ const outcomes = await actionOutcomes(client, receipt, actions, document.header.revision, signal);
1099
+ const failures = actions.flatMap((action, index) => {
1100
+ const outcome = outcomes.get(action.id);
1101
+ if (outcome?.kind === "applied") return [];
1102
+ return [{
1103
+ index,
1104
+ type: action.type,
1105
+ code: outcome?.kind === "denied" ? "FORBIDDEN" : "REDUCER_ERROR",
1106
+ errors: [!outcome ? NO_OPERATION : outcome.kind === "denied" ? outcome.reason : outcome.message]
1107
+ }];
1108
+ });
1109
+ if (failures.length > 0) throw actionFailuresError(failures, module);
1110
+ return revisionAfter(client, receipt, signal);
1111
+ }
1112
+ /** The model module at the document's own version. */
1113
+ async function getDocumentModelForDocument(client, document, signal) {
1114
+ try {
1115
+ return await client.getDocumentModelModuleForDocument(document);
1116
+ } catch (error) {
1117
+ await getDocumentModel(client, document.header.documentType, signal);
1118
+ throw toReactorToolError(error, "NOT_FOUND");
1119
+ }
1120
+ }
1121
+ /** Finds the declared error a reducer error was, by code, class name, then default message. */
1122
+ function modelErrorFinder(module, actionType) {
1123
+ const operations = (module.documentModel.global.specifications.at(-1)?.modules ?? []).flatMap((m) => m.operations);
1124
+ const declared = (errors) => errors.flatMap(({ name, code }) => {
1125
+ if (!name) return [];
1126
+ const className = pascalCase(name);
1127
+ return [{
1128
+ name: className,
1129
+ code: code?.trim() || className
1130
+ }];
1131
+ });
1132
+ const candidates = [...declared(operations.find((o) => o.name === actionType)?.errors ?? []), ...declared(operations.flatMap((o) => o.errors))];
1133
+ return (name, code, message) => candidates.find((e) => code !== void 0 && e.code === code) ?? candidates.find((e) => name !== void 0 && e.name === name) ?? candidates.find((e) => e.name === message);
1134
+ }
1135
+ function outcomeError(outcome, module, actionType) {
1136
+ if (!outcome) return {
1137
+ kind: "not-applied",
1138
+ message: NO_OPERATION
1139
+ };
1140
+ if (outcome.kind === "applied") return void 0;
1141
+ if (outcome.kind === "denied") return {
1142
+ kind: "denied",
1143
+ message: outcome.reason
1144
+ };
1145
+ const known = modelErrorFinder(module, actionType)(outcome.name, outcome.code, outcome.message);
1146
+ const name = known?.name ?? outcome.name;
1147
+ const code = known?.code ?? outcome.code;
1148
+ return {
1149
+ kind: "reducer-error",
1150
+ message: outcome.message,
1151
+ ...name !== void 0 && { name },
1152
+ ...code !== void 0 && { code }
1153
+ };
1154
+ }
1155
+ async function refusedBatch(client, documentId, branch, actions, error, signal) {
1156
+ const message = error instanceof Error ? error.message : String(error);
1157
+ const notApplied = {
1158
+ kind: "not-applied",
1159
+ message: `The batch was refused, so nothing in it was written: ${message}`
1160
+ };
1161
+ const denied = deniedActions(error);
1162
+ if (denied) return actions.map((_, i) => {
1163
+ const denial = denied.find((d) => d.index === i);
1164
+ return denial ? {
1165
+ kind: "denied",
1166
+ message: denial.reason
1167
+ } : notApplied;
1168
+ });
1169
+ const evaluating = client;
1170
+ const target = evaluating.write.evaluateActions ? evaluating.write : evaluating;
1171
+ const evaluate = target.evaluateActions;
1172
+ if (typeof evaluate !== "function") return actions.map(() => notApplied);
1173
+ try {
1174
+ const { evaluations } = await evaluate.call(target, documentId, branch, actions.map(({ scope, type, input }) => ({
1175
+ scope,
1176
+ type,
1177
+ input
1178
+ })), void 0, signal);
1179
+ return actions.map((_, i) => {
1180
+ const evaluation = evaluations.at(i);
1181
+ return evaluation?.decision === "deny" ? {
1182
+ kind: "denied",
1183
+ message: evaluation.reason ?? message
1184
+ } : notApplied;
1185
+ });
1186
+ } catch {
1187
+ return actions.map(() => notApplied);
1188
+ }
1189
+ }
1190
+ function isUndoRedo(type) {
1191
+ return type === "UNDO" || type === "REDO";
1192
+ }
1193
+ /** Every stored row of one scope. */
1194
+ async function scopeOperations(client, documentId, branch, scope, signal) {
1195
+ const rows = [];
1196
+ let cursor = "0";
1197
+ while (cursor !== void 0) {
1198
+ const page = await client.getOperations(documentId, {
1199
+ branch,
1200
+ scopes: [scope]
1201
+ }, void 0, {
1202
+ cursor,
1203
+ limit: OPERATIONS_PAGE_SIZE
1204
+ }, signal);
1205
+ rows.push(...page.results);
1206
+ cursor = page.results.length > 0 ? page.nextCursor : void 0;
1207
+ }
1208
+ return rows;
1209
+ }
1210
+ async function retractionBatch(client, document, module, inputs, actions, options, signal) {
1211
+ const { branch = DEFAULT_BRANCH } = options;
1212
+ const caps = undoCapabilitiesOf(document.header);
1213
+ if (caps === void 0 || !undoNeedsTargets(caps) || !actions.some((action) => isUndoRedo(action.type))) return;
1214
+ const counts = actions.map((action) => isUndoRedo(action.type) ? action.input.count : 0);
1215
+ const invalid = actions.flatMap((action, index) => {
1216
+ const count = counts[index];
1217
+ if (!isUndoRedo(action.type) || Number.isInteger(count) && count >= 1) return [];
1218
+ return [{
1219
+ index,
1220
+ type: action.type,
1221
+ code: "INVALID_ACTION",
1222
+ errors: ["count must be a positive integer"]
1223
+ }];
1224
+ });
1225
+ if (invalid.length > 0) throw actionFailuresError(invalid, module);
1226
+ const reducer = stateReducerOf(module.reducer);
1227
+ if (reducer === void 0) throw new ReactorToolError("INVALID_ACTION", `Document model ${document.header.documentType} has no state reducer to resolve undo targets with`);
1228
+ const id = document.header.id;
1229
+ const operations = {};
1230
+ for (const action of actions) {
1231
+ if (!isUndoRedo(action.type) || action.scope in operations) continue;
1232
+ operations[action.scope] = await scopeOperations(client, id, branch, action.scope, signal);
1233
+ }
1234
+ const initialState = creationState(await scopeOperations(client, id, branch, "document", signal)) ?? module.utils.createDocument().initialState;
1235
+ const batch = undoRedoBatch({
1236
+ ...document,
1237
+ initialState,
1238
+ operations
1239
+ }, caps, reducer);
1240
+ const sources = [];
1241
+ for (const [index, action] of actions.entries()) {
1242
+ const before = batch.actions.length;
1243
+ if (isUndoRedo(action.type)) try {
1244
+ for (let step = 0; step < counts[index]; step++) batch.undoOrRedo(action.type, action.scope);
1245
+ } catch (error) {
1246
+ throw actionFailuresError([{
1247
+ index,
1248
+ type: action.type,
1249
+ code: "INVALID_ACTION",
1250
+ errors: [error instanceof Error ? error.message : String(error)]
1251
+ }], module);
1252
+ }
1253
+ else batch.add(validateActions(module, [inputs[index]], options).actions[0]);
1254
+ for (let i = before; i < batch.actions.length; i++) sources.push(index);
1255
+ }
1256
+ return {
1257
+ actions: [...batch.actions],
1258
+ sources
1259
+ };
1260
+ }
1261
+ function perInput(inputs, sources, submitted) {
1262
+ return inputs.map((action, index) => {
1263
+ const steps = submitted.filter((r) => sources[r.index] === index);
1264
+ const operationIndex = steps.at(-1)?.operationIndex;
1265
+ const error = steps.find((step) => step.error?.kind === "denied")?.error ?? steps.find((step) => step.error)?.error;
1266
+ return {
1267
+ index,
1268
+ type: action.type,
1269
+ scope: action.scope,
1270
+ ...operationIndex !== void 0 && { operationIndex },
1271
+ ...error && { error }
1272
+ };
1273
+ });
1274
+ }
1275
+ /** Validates every action, then executes them as one batch and reports each action's outcome. */
1276
+ async function executeActions(client, documentId, inputs, options = {}) {
1277
+ const { signal, branch = DEFAULT_BRANCH } = options;
1278
+ const document = await getDocument(client, documentId, signal, { branch });
1279
+ const id = document.header.id;
1280
+ const module = await getDocumentModelForDocument(client, document, signal);
1281
+ const validated = validateActions(module, inputs, options);
1282
+ if (validated.failures.length > 0) throw actionFailuresError(validated.failures, module);
1283
+ const before = { ...document.header.revision };
1284
+ if (validated.actions.length === 0) return {
1285
+ documentId: id,
1286
+ revision: before,
1287
+ success: true,
1288
+ results: []
1289
+ };
1290
+ const retraction = await retractionBatch(client, document, module, inputs, validated.actions, options, signal);
1291
+ const actions = retraction?.actions ?? validated.actions;
1292
+ const reported = (submitted) => retraction ? perInput(validated.actions, retraction.sources, submitted) : submitted;
1293
+ const result = (action, index) => ({
1294
+ index,
1295
+ type: action.type,
1296
+ scope: action.scope
1297
+ });
1298
+ let receipt;
1299
+ try {
1300
+ receipt = await readable(client.write.execute(id, branch, actions, signal));
1301
+ } catch (error) {
1302
+ if (!isDenial(error)) throw toReactorToolError(error);
1303
+ const errors = await refusedBatch(client, id, branch, actions, error, signal);
1304
+ return {
1305
+ documentId: id,
1306
+ revision: before,
1307
+ success: false,
1308
+ results: reported(actions.map((a, i) => ({
1309
+ ...result(a, i),
1310
+ error: errors[i]
1311
+ })))
1312
+ };
1313
+ }
1314
+ const outcomes = await actionOutcomes(client, receipt, actions, before, signal);
1315
+ const results = reported(actions.map((action, index) => {
1316
+ const outcome = outcomes.get(action.id);
1317
+ const error = outcomeError(outcome, module, action.type);
1318
+ return {
1319
+ ...result(action, index),
1320
+ ...outcome && { operationIndex: outcome.operationIndex },
1321
+ ...error && { error }
1322
+ };
1323
+ }));
1324
+ return {
1325
+ documentId: id,
1326
+ revision: await revisionAfter(client, receipt, signal),
1327
+ success: results.every((r) => !r.error),
1328
+ results
1329
+ };
1330
+ }
1331
+ const ROLLBACK_TIMEOUT_MS = 1e4;
1332
+ async function addFileError(client, drive, documentId, signal) {
1333
+ const operation = (await client.getOperations(drive.header.id, { scopes: ["global"] }, { sinceRevision: drive.header.revision.global ?? 0 }, void 0, signal).catch(() => void 0))?.results.find((op) => op.action.type === "ADD_FILE" && op.action.input.id === documentId);
1334
+ const outcome = operation && operationOutcome(operation);
1335
+ if (outcome?.kind === "reducer-error") return outcome.message;
1336
+ if (outcome?.kind === "denied") return outcome.reason;
1337
+ }
1338
+ /** Creates the document, filed into the drive when given; a half-done filing is rolled back. */
1339
+ async function createDocument(client, input, signal) {
1340
+ const module = await getDocumentModel(client, input.documentType, signal);
1341
+ const drive = input.driveId ? await getDocument(client, input.driveId, signal) : void 0;
1342
+ if (drive && !DRIVE_DOCUMENT_TYPES.has(drive.header.documentType)) throw new ReactorToolError("INVALID_ACTION", `driveId ${input.driveId} names a ${drive.header.documentType}, not a drive`);
1343
+ if (input.parentFolder && !drive) throw new ReactorToolError("INVALID_ACTION", "parentFolder needs driveId to name a drive");
1344
+ const documentType = module.documentModel.global.id;
1345
+ const name = input.name ?? "";
1346
+ let document;
1347
+ try {
1348
+ document = await client.newDocument(documentType, {
1349
+ ...drive && { parentIdentifier: drive.header.id },
1350
+ ...name && { name }
1351
+ }, signal);
1352
+ } catch (error) {
1353
+ throw toReactorToolError(error);
1354
+ }
1355
+ const documentId = document.header.id;
1356
+ const rollback = async (error) => {
1357
+ const e = toReactorToolError(error);
1358
+ try {
1359
+ await deleteDocument(client, documentId, AbortSignal.timeout(ROLLBACK_TIMEOUT_MS));
1360
+ } catch (deleteError) {
1361
+ if (toReactorToolError(deleteError).code !== "NOT_FOUND") return new ReactorToolError(e.code, `Document ${documentId} was created but could not be removed after: ${e.message}`, {
1362
+ failures: e.failures,
1363
+ cause: error
1364
+ });
1365
+ }
1366
+ return new ReactorToolError(e.code, e.message, {
1367
+ failures: e.failures,
1368
+ cause: error
1369
+ });
1370
+ };
1371
+ let receipt;
1372
+ if (!drive) try {
1373
+ receipt = await readable(client.write.create(document, void 0, signal));
1374
+ } catch (error) {
1375
+ throw toReactorToolError(error);
1376
+ }
1377
+ else {
1378
+ try {
1379
+ receipt = await readable(client.write.drives.addFile(drive.header.id, document, input.parentFolder, signal));
1380
+ } catch (error) {
1381
+ throw await rollback(error);
1382
+ }
1383
+ if (drive.header.documentType === "powerhouse/document-drive") {
1384
+ const nodes = ((await getDocument(client, drive.header.id, signal, { token: receipt.token }).catch(() => void 0))?.state)?.global?.nodes;
1385
+ if (nodes && !nodes.some((node) => node.id === documentId)) {
1386
+ const reason = await addFileError(client, drive, documentId, signal) ?? "the drive stored no node for it";
1387
+ throw await rollback(new ReactorToolError("REDUCER_ERROR", `Drive ${drive.header.id} did not file the document: ${reason}`));
1388
+ }
1389
+ }
1390
+ }
1391
+ const created = await getDocument(client, documentId, signal, { token: receipt.token });
1392
+ return {
1393
+ documentId,
1394
+ documentType,
1395
+ name,
1396
+ ...drive ? { driveId: drive.header.id } : {},
1397
+ revision: { ...created.header.revision }
1398
+ };
1399
+ }
1400
+ /** Removes the document's node from each document drive filing it, then deletes it. */
1401
+ async function deleteDocument(client, documentId, signal) {
1402
+ const id = (await getDocument(client, documentId, signal)).header.id;
1403
+ const { authorizeDelete } = client.write;
1404
+ await authorizeDelete?.call(client.write, id, signal);
1405
+ const parents = await client.getIncomingRelationships(id, "child", void 0, void 0, signal).catch((error) => {
1406
+ throw toReactorToolError(error);
1407
+ });
1408
+ const filing = [];
1409
+ for (const parent of parents.results) {
1410
+ if (parent.header.documentType !== "powerhouse/document-drive") continue;
1411
+ const nodes = parent.state.global?.nodes;
1412
+ if (!Array.isArray(nodes)) throw new ReactorToolError("FORBIDDEN", `Document ${id} is filed in drive ${parent.header.id}, whose nodes you cannot read; it was not deleted`);
1413
+ if (nodes.some((node) => node.id === id)) filing.push(parent);
1414
+ }
1415
+ for (const parent of filing) await executeBuiltActions(client, parent, [deleteNode({ id })], { signal });
1416
+ try {
1417
+ await readable(client.write.deleteDocument(id, void 0, signal));
1418
+ } catch (error) {
1419
+ throw toReactorToolError(error);
1420
+ }
1421
+ return { documentId: id };
1422
+ }
1423
+ //#endregion
1424
+ //#region src/tools/reactor.ts
1425
+ const MAX_LISTED = 500;
1426
+ async function collect(first) {
1427
+ let page = await first.catch((error) => {
1428
+ throw toReactorToolError(error);
1429
+ });
1430
+ const out = [];
1431
+ for (;;) {
1432
+ out.push(...page.results);
1433
+ if (out.length >= MAX_LISTED || !page.next || page.results.length === 0) break;
1434
+ page = await page.next();
1435
+ }
1436
+ return out.slice(0, MAX_LISTED);
1437
+ }
1438
+ const filterSchema = z.string().optional().describe("JSONPath over the document state, e.g. $.global.items[?(@.status=='OPEN')] or $.global.items[-1]");
1439
+ /** The parameter every tool names its target document or drive by. */
1440
+ const TARGET = "documentId";
1441
+ const targetParam = (what) => z.string().optional().describe(`ID or slug of the ${what}. Required.`);
1442
+ const aliasParam = z.string().optional().describe(`Alias of \`${TARGET}\``);
1443
+ /** The target named by `documentId` or one of its aliases; they must agree. */
1444
+ function targetId(tool, args, aliases) {
1445
+ const given = new Set([TARGET, ...aliases].map((name) => args[name]).filter((id) => typeof id === "string" && id !== ""));
1446
+ if (given.size > 1) throw new ReactorToolError("INVALID_ACTION", `${tool} got different IDs in \`${TARGET}\` and its aliases (${aliases.map((a) => `\`${a}\``).join(", ")}); pass only \`${TARGET}\``);
1447
+ const [id] = given;
1448
+ if (!id) throw new ReactorToolError("INVALID_ACTION", `${tool} needs the target's ID in \`${TARGET}\``);
1449
+ return id;
1450
+ }
1451
+ const revisionSchema = z.record(z.string(), z.number()).describe("Revision per scope after the change");
1452
+ const readOnly = {
1453
+ readOnlyHint: true,
1454
+ destructiveHint: false,
1455
+ openWorldHint: false
1456
+ };
1457
+ const getDocumentModelsTool = defineTool({
1458
+ name: "getDocumentModels",
1459
+ title: "List document models",
1460
+ description: "List the document model types this reactor can create and edit.",
1461
+ inputSchema: z.object({}),
1462
+ outputSchema: z.object({ documentModels: z.array(documentModelInfoSchema) }),
1463
+ annotations: readOnly,
1464
+ async execute(_args, { client, signal }) {
1465
+ return { documentModels: (await collect(client.getDocumentModelModules(void 0, void 0, signal))).map(documentModelInfo) };
1466
+ }
1467
+ });
1468
+ const getDocumentModelSchemaTool = defineTool({
1469
+ name: "getDocumentModelSchema",
1470
+ title: "Read a document model schema",
1471
+ description: `Read a document model's schema. Without options it returns the operation names per module.
1472
+ Pass "compact" before addActions for every action's type, scope and input definition, and the types those inputs use.
1473
+ Pass "operation" for one action's input schema (GraphQL SDL), "state" for a state schema, or "filter" for a JSONPath over the latest specification.
1474
+ Pass "definition" to also return the structured definition of a model authored in code.`,
1475
+ inputSchema: z.object({
1476
+ type: z.string().describe("Document model type, e.g. powerhouse/document-model"),
1477
+ compact: z.boolean().optional().describe("Return every action's type, scope and input definition"),
1478
+ definition: z.boolean().optional().describe("Also return the structured definition of a model authored in code; ignored with compact, operation, state or filter"),
1479
+ operation: z.string().optional().describe("Action type whose input schema to return, e.g. SET_MODEL_NAME"),
1480
+ state: z.enum(["global", "local"]).optional().describe("Scope whose state schema to return"),
1481
+ filter: z.string().optional().describe("JSONPath over the latest specification, e.g. $.modules[*].name")
1482
+ }),
1483
+ outputSchema: z.object({
1484
+ type: z.string(),
1485
+ model: documentModelSummarySchema.optional(),
1486
+ definition: z.unknown().optional().describe("The structured definition of a model authored in code, alongside model; change it in the package's source, not through document actions"),
1487
+ compact: compactDocumentModelSchemaSchema.optional(),
1488
+ operation: operationSliceSchema.optional(),
1489
+ state: stateSliceSchema.optional(),
1490
+ value: z.unknown().optional().describe("The filter's match")
1491
+ }),
1492
+ annotations: readOnly,
1493
+ async execute(args, { client, signal }) {
1494
+ const module = await getDocumentModel(client, args.type, signal);
1495
+ const type = module.documentModel.global.id;
1496
+ if (args.compact) return {
1497
+ type,
1498
+ compact: compactDocumentModelSchema(module.documentModel.global)
1499
+ };
1500
+ if (!args.operation && !args.state && !args.filter) {
1501
+ const definition = args.definition && structuredDefinition(module);
1502
+ return {
1503
+ type,
1504
+ model: documentModelSummary(module),
1505
+ ...definition && { definition }
1506
+ };
1507
+ }
1508
+ let value;
1509
+ if (args.filter) try {
1510
+ value = applyJsonPath(latestSpecification(module), args.filter);
1511
+ } catch (error) {
1512
+ if (error instanceof JsonPathError) throw new ReactorToolError("INVALID_ACTION", error.message);
1513
+ throw error;
1514
+ }
1515
+ return {
1516
+ type,
1517
+ ...args.operation ? { operation: operationSchemaSlice(module, args.operation) } : {},
1518
+ ...args.state ? { state: stateSchemaSlice(module, args.state) } : {},
1519
+ ...args.filter ? { value } : {}
1520
+ };
1521
+ }
1522
+ });
1523
+ const getDocumentTool = defineTool({
1524
+ name: "getDocument",
1525
+ title: "Read a document",
1526
+ description: "Read a document by id or slug: header essentials and its global and local state. Long arrays and strings are cut; pass a filter to read a part in full (up to 100,000 characters).",
1527
+ inputSchema: z.object({
1528
+ documentId: targetParam("document to read"),
1529
+ id: aliasParam,
1530
+ filter: filterSchema
1531
+ }),
1532
+ outputSchema: z.object({ document: documentViewSchema }),
1533
+ annotations: readOnly,
1534
+ async execute(args, { client, signal }) {
1535
+ return { document: documentView(await getDocument(client, targetId("getDocument", args, ["id"]), signal), { filter: args.filter }) };
1536
+ }
1537
+ });
1538
+ const getDocumentsTool = defineTool({
1539
+ name: "getDocuments",
1540
+ title: "List a drive's documents",
1541
+ description: "List the documents in a drive (its children): id, type and name.",
1542
+ inputSchema: z.object({
1543
+ documentId: targetParam("drive whose documents to list"),
1544
+ driveId: aliasParam,
1545
+ parentId: aliasParam
1546
+ }),
1547
+ outputSchema: z.object({ documents: z.array(documentSummarySchema) }),
1548
+ annotations: readOnly,
1549
+ async execute(args, { client, signal }) {
1550
+ const driveId = targetId("getDocuments", args, ["driveId", "parentId"]);
1551
+ return { documents: (await collect(client.getOutgoingRelationships(driveId, "child", void 0, void 0, signal))).map(documentSummary) };
1552
+ }
1553
+ });
1554
+ const getDrivesTool = defineTool({
1555
+ name: "getDrives",
1556
+ title: "List drives",
1557
+ description: "List the drives: id, type and name.",
1558
+ inputSchema: z.object({}),
1559
+ outputSchema: z.object({ drives: z.array(documentSummarySchema) }),
1560
+ annotations: readOnly,
1561
+ async execute(_args, { client, signal }) {
1562
+ return { drives: (await collect(client.find({ type: DRIVE_DOCUMENT_TYPE }, void 0, void 0, signal))).map(documentSummary) };
1563
+ }
1564
+ });
1565
+ const getDriveTool = defineTool({
1566
+ name: "getDrive",
1567
+ title: "Read a drive",
1568
+ description: "Read a drive by id or slug, including its folder and file nodes. Pass a filter such as $.global.nodes[?(@.kind=='file')] to narrow it.",
1569
+ inputSchema: z.object({
1570
+ documentId: targetParam("drive to read"),
1571
+ driveId: aliasParam,
1572
+ id: aliasParam,
1573
+ filter: filterSchema
1574
+ }),
1575
+ outputSchema: z.object({ drive: documentViewSchema }),
1576
+ annotations: readOnly,
1577
+ async execute(args, { client, signal }) {
1578
+ return { drive: documentView(await getDocument(client, targetId("getDrive", args, ["driveId", "id"]), signal), { filter: args.filter }) };
1579
+ }
1580
+ });
1581
+ const createDocumentTool = defineTool({
1582
+ name: "createDocument",
1583
+ title: "Create a document",
1584
+ description: `Create a document, optionally inside a drive.
1585
+ With "driveId" the document is added to the drive as a file, so no separate ADD_FILE is needed.`,
1586
+ inputSchema: z.object({
1587
+ documentType: z.string().describe("Document model type"),
1588
+ name: z.string().optional().describe("Document name, also the drive file's name"),
1589
+ driveId: z.string().optional().describe("Drive id or slug to create the document in"),
1590
+ parentFolder: z.string().optional().describe("Folder id within the drive; only with driveId")
1591
+ }),
1592
+ outputSchema: z.object({
1593
+ documentId: z.string(),
1594
+ documentType: z.string(),
1595
+ name: z.string(),
1596
+ driveId: z.string().optional(),
1597
+ revision: revisionSchema
1598
+ }),
1599
+ annotations: {
1600
+ readOnlyHint: false,
1601
+ destructiveHint: false,
1602
+ openWorldHint: false
1603
+ },
1604
+ async execute(args, { client, signal }) {
1605
+ return createDocument(client, args, signal);
1606
+ }
1607
+ });
1608
+ const deleteDocumentTool = defineTool({
1609
+ name: "deleteDocument",
1610
+ title: "Delete a document",
1611
+ description: "Delete a document, removing it from its drive first.",
1612
+ inputSchema: z.object({
1613
+ documentId: targetParam("document to delete"),
1614
+ id: aliasParam
1615
+ }),
1616
+ outputSchema: z.object({ documentId: z.string() }),
1617
+ annotations: {
1618
+ readOnlyHint: false,
1619
+ destructiveHint: true,
1620
+ openWorldHint: false
1621
+ },
1622
+ async execute(args, { client, signal }) {
1623
+ return deleteDocument(client, targetId("deleteDocument", args, ["id"]), signal);
1624
+ }
1625
+ });
1626
+ const actionErrorSchema = z.object({
1627
+ kind: z.enum([
1628
+ "reducer-error",
1629
+ "denied",
1630
+ "not-applied"
1631
+ ]).describe("reducer-error: the reducer threw; denied: an auth policy refused it; not-applied: it was not written, e.g. because another action of the batch was denied"),
1632
+ message: z.string().describe("Why the action was not applied"),
1633
+ name: z.string().optional().describe("For a reducer-error: the error class the reducer threw"),
1634
+ code: z.string().optional().describe("For a reducer-error: the error's code in the document model")
1635
+ }).describe("Present when the action was not applied");
1636
+ function createAddActionsTool(options = {}) {
1637
+ const allowed = options.allowedActionTypes;
1638
+ return defineTool({
1639
+ name: "addActions",
1640
+ title: "Change a document",
1641
+ description: `Apply actions to a document as one batch. Send several actions in one call rather than one call each.
1642
+ Besides the model's operations it accepts the base actions SET_NAME, SET_PREFERRED_EDITOR, UNDO, REDO (input: { count }; on base-reducer 3 each step retracts one row, counting rows added earlier in the same call) and NOOP.
1643
+ Every action is validated first; on a validation failure nothing is applied and each failed action is listed.
1644
+ Returns one result per action, in input order; "success" is false when any result has an "error". An action its reducer rejected is stored as an operation that changes nothing, and the rest of the batch still applies. When a policy denies an action, the whole batch is refused.
1645
+ On base-reducer 3 the call fails and writes nothing when an UNDO or REDO has nothing to retract, or when the reactor refuses one of its RETRACTs because another write changed the target first.${allowed ? `\nAllowed action types: ${allowed.join(", ")}.` : ""}`,
1646
+ inputSchema: z.object({
1647
+ documentId: targetParam("document or drive to change"),
1648
+ id: aliasParam,
1649
+ actions: z.array(actionInputSchema).min(1).describe("Actions to apply, in order")
1650
+ }),
1651
+ outputSchema: z.object({
1652
+ documentId: z.string(),
1653
+ revision: revisionSchema,
1654
+ success: z.boolean().describe("False when any action was not applied"),
1655
+ results: z.array(z.object({
1656
+ index: z.number().describe("Position of the action in `actions`"),
1657
+ type: z.string(),
1658
+ scope: z.string(),
1659
+ operationIndex: z.number().optional().describe("Index of the operation the action was stored as; for a counted UNDO or REDO on base-reducer 3, the last of its RETRACT rows"),
1660
+ error: actionErrorSchema.optional()
1661
+ })).describe("One result per action, in the order they were given"),
1662
+ codegen: z.string().optional().describe("Present when Vetra generates code from this document: how to follow that generation")
1663
+ }),
1664
+ annotations: {
1665
+ readOnlyHint: false,
1666
+ destructiveHint: true,
1667
+ openWorldHint: false
1668
+ },
1669
+ async execute(args, { client, signal }) {
1670
+ const executed = await executeActions(client, targetId("addActions", args, ["id"]), args.actions, {
1671
+ allowedActionTypes: allowed,
1672
+ signal
1673
+ });
1674
+ const codegen = options.codegenStatus && await codegenHint(options.codegenStatus, client, executed, signal);
1675
+ return {
1676
+ ...executed,
1677
+ ...codegen && { codegen }
1678
+ };
1679
+ }
1680
+ });
1681
+ }
1682
+ const addActionsTool = createAddActionsTool();
1683
+ /** The tools every host mounts: reads, document create/delete and `addActions`. */
1684
+ function reactorTools(options = {}) {
1685
+ return [
1686
+ getDocumentModelsTool,
1687
+ getDocumentModelSchemaTool,
1688
+ getDrivesTool,
1689
+ getDriveTool,
1690
+ getDocumentsTool,
1691
+ getDocumentTool,
1692
+ createDocumentTool,
1693
+ options.allowedActionTypes || options.codegenStatus ? createAddActionsTool(options) : addActionsTool,
1694
+ deleteDocumentTool
1695
+ ];
1696
+ }
1697
+ //#endregion
1698
+ export { JsonPathError as $, documentModelInfoSchema as A, suggestNames as B, actionInputSchema as C, BASE_OPERATIONS as D, ANY_SCOPE as E, modelOperations as F, DRIVE_DOCUMENT_TYPES as G, DEFAULT_BRANCH as H, operationSchemaSlice as I, documentSummary as J, MAX_FILTERED_CHARS as K, operationSliceSchema as L, documentModelSummarySchema as M, latestSpecification as N, actionOperations as O, modelOperationSchema as P, trimValue as Q, stateSchemaSlice as R, actionFailuresError as S, validateActions as T, DEFAULT_TRIM_LIMITS as U, unknownValueMessage as V, DRIVE_DOCUMENT_TYPE as W, documentView as X, documentSummarySchema as Y, documentViewSchema as Z, executeActions as _, deleteDocumentTool as a, codegenHint as at, getDocumentModel as b, getDocumentTool as c, formatToolError as ct, getDrivesTool as d, toMcpTool as dt, applyJsonPath as et, reactorTools as f, REACTOR_TOOL_ERROR_CODES as ft, deleteDocument as g, toReactorToolError as gt, createDocument as h, notFound as ht, createDocumentTool as i, compactDocumentModelSchemaSchema as it, documentModelSummary as j, documentModelInfo as k, getDocumentsTool as l, isWriteTool as lt, targetParam as m, isReactorToolError as mt, aliasParam as n, queryJsonPath as nt, getDocumentModelSchemaTool as o, codegenStatusTool as ot, targetId as p, ReactorToolError as pt, documentName as q, createAddActionsTool as r, compactDocumentModelSchema as rt, getDocumentModelsTool as s, defineTool as st, addActionsTool as t, parseJsonPath as tt, getDriveTool as u, toAiSdkTools as ut, executeBuiltActions as v, formatActionFailures as w, getDocumentModelForDocument as x, getDocument as y, stateSliceSchema as z };
1699
+
1700
+ //# sourceMappingURL=tools-BrIw7TkA.mjs.map