@powerhousedao/reactor-mcp 6.2.3 → 6.3.0-dev.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin-tools-B-ZmrfuR.d.mts +131 -0
- package/dist/admin-tools-B-ZmrfuR.d.mts.map +1 -0
- package/dist/admin-tools.d.mts +3 -0
- package/dist/admin-tools.mjs +192 -0
- package/dist/admin-tools.mjs.map +1 -0
- package/dist/cli.mjs +2 -1
- package/dist/cli.mjs.map +1 -1
- package/dist/index.d.mts +47 -16
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +9 -7
- package/dist/index.mjs.map +1 -1
- package/dist/server-C20v0OSn.mjs +329 -0
- package/dist/server-C20v0OSn.mjs.map +1 -0
- package/dist/tools/index.d.mts +777 -2
- package/dist/tools/index.d.mts.map +1 -0
- package/dist/tools/index.mjs +2 -2
- package/dist/tools-UCPB56U4.mjs +1714 -0
- package/dist/tools-UCPB56U4.mjs.map +1 -0
- package/package.json +22 -9
- package/dist/index-CWO1xShX.d.mts +0 -616
- package/dist/index-CWO1xShX.d.mts.map +0 -1
- package/dist/reactor-CYKTrGtF.mjs +0 -345
- package/dist/reactor-CYKTrGtF.mjs.map +0 -1
- package/dist/server-CT8k24iS.mjs +0 -58
- package/dist/server-CT8k24iS.mjs.map +0 -1
|
@@ -0,0 +1,1714 @@
|
|
|
1
|
+
import { childLogger, inspectDocumentModelDefinition, operationsByActionType } 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/model-operations.ts
|
|
646
|
+
const logger = childLogger(["reactor-mcp", "model-operations"]);
|
|
647
|
+
const logged = /* @__PURE__ */ new Set();
|
|
648
|
+
function inspect(module) {
|
|
649
|
+
const inspection = inspectDocumentModelDefinition(module);
|
|
650
|
+
if ("diagnostics" in inspection) {
|
|
651
|
+
const documentType = module.documentModel.global.id;
|
|
652
|
+
const key = `${documentType}\n${inspection.reason}`;
|
|
653
|
+
if (!logged.has(key)) {
|
|
654
|
+
logged.add(key);
|
|
655
|
+
logger.warn("Serving @type from its stored model; its definition is @reason: @diagnostics", documentType, inspection.reason, inspection.diagnostics.map((d) => d.message).join("; "));
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return inspection;
|
|
659
|
+
}
|
|
660
|
+
function structuredDefinition(module) {
|
|
661
|
+
const inspection = inspect(module);
|
|
662
|
+
return inspection.kind === "structured" ? inspection.definition : null;
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* The operations of a model authored in code, keyed by action type; empty for
|
|
666
|
+
* a model served from its stored specification. Callers consult it only for a
|
|
667
|
+
* type that names no stored operation, so every stored name keeps main's
|
|
668
|
+
* meaning.
|
|
669
|
+
*/
|
|
670
|
+
function operationsByActionType$1(module) {
|
|
671
|
+
inspect(module);
|
|
672
|
+
return operationsByActionType(module);
|
|
673
|
+
}
|
|
674
|
+
//#endregion
|
|
675
|
+
//#region src/tools/suggest.ts
|
|
676
|
+
function isSubsequence(needle, haystack) {
|
|
677
|
+
let i = 0;
|
|
678
|
+
for (let j = 0; j < haystack.length && i < needle.length; j++) if (needle[i] === haystack[j]) i++;
|
|
679
|
+
return i === needle.length;
|
|
680
|
+
}
|
|
681
|
+
function editDistance(a, b) {
|
|
682
|
+
if (a === b) return 0;
|
|
683
|
+
if (a.length === 0) return b.length;
|
|
684
|
+
if (b.length === 0) return a.length;
|
|
685
|
+
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
686
|
+
let curr = new Array(b.length + 1);
|
|
687
|
+
for (let i = 1; i <= a.length; i++) {
|
|
688
|
+
curr[0] = i;
|
|
689
|
+
for (let j = 1; j <= b.length; j++) {
|
|
690
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
691
|
+
curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
|
|
692
|
+
}
|
|
693
|
+
[prev, curr] = [curr, prev];
|
|
694
|
+
}
|
|
695
|
+
return prev[b.length];
|
|
696
|
+
}
|
|
697
|
+
/** Closest `candidates` to `query`: containment first, then edit distance. */
|
|
698
|
+
function suggestNames(query, candidates, max = 3) {
|
|
699
|
+
const q = query.toUpperCase();
|
|
700
|
+
const scored = candidates.map((name) => {
|
|
701
|
+
const u = name.toUpperCase();
|
|
702
|
+
if (u.includes(q) || q.includes(u)) return {
|
|
703
|
+
name,
|
|
704
|
+
d: 0,
|
|
705
|
+
strong: true
|
|
706
|
+
};
|
|
707
|
+
if (u.length >= q.length ? isSubsequence(q, u) : isSubsequence(u, q)) return {
|
|
708
|
+
name,
|
|
709
|
+
d: Math.abs(u.length - q.length),
|
|
710
|
+
strong: true
|
|
711
|
+
};
|
|
712
|
+
return {
|
|
713
|
+
name,
|
|
714
|
+
d: editDistance(q, u),
|
|
715
|
+
strong: false
|
|
716
|
+
};
|
|
717
|
+
});
|
|
718
|
+
const threshold = Math.max(3, Math.ceil(q.length * .6) + 3);
|
|
719
|
+
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);
|
|
720
|
+
}
|
|
721
|
+
/** `Unknown <subject> "<value>".` plus a did-you-mean line and, when short, the known names. */
|
|
722
|
+
function unknownValueMessage(subject, value, candidates, options = {}) {
|
|
723
|
+
const { knownLabel, inlineLimit = 20, context } = options;
|
|
724
|
+
const lines = [`Unknown ${subject} "${value}"${context ? ` ${context}` : ""}.`];
|
|
725
|
+
const suggestions = suggestNames(value, candidates);
|
|
726
|
+
if (suggestions.length > 0) lines.push(`Did you mean: ${suggestions.join(", ")}?`);
|
|
727
|
+
if (knownLabel && candidates.length > 0 && candidates.length <= inlineLimit) lines.push(`${knownLabel}: ${candidates.join(", ")}`);
|
|
728
|
+
return lines.join("\n");
|
|
729
|
+
}
|
|
730
|
+
//#endregion
|
|
731
|
+
//#region src/tools/schema.ts
|
|
732
|
+
/** Marks a base action that runs in whichever scope it is sent to; never itself a scope. */
|
|
733
|
+
const ANY_SCOPE = "any";
|
|
734
|
+
const BASE_OPERATIONS = [
|
|
735
|
+
{
|
|
736
|
+
name: "SET_NAME",
|
|
737
|
+
module: "base",
|
|
738
|
+
scope: "global",
|
|
739
|
+
description: "Renames the document",
|
|
740
|
+
schema: "input SetNameInput {\n name: String!\n}"
|
|
741
|
+
},
|
|
742
|
+
{
|
|
743
|
+
name: "SET_PREFERRED_EDITOR",
|
|
744
|
+
module: "base",
|
|
745
|
+
scope: "header",
|
|
746
|
+
description: "Sets the editor that opens the document",
|
|
747
|
+
schema: "input SetPreferredEditorInput {\n preferredEditor: String\n}"
|
|
748
|
+
},
|
|
749
|
+
{
|
|
750
|
+
name: "UNDO",
|
|
751
|
+
module: "base",
|
|
752
|
+
scope: "any",
|
|
753
|
+
description: "Undoes the scope's last operations",
|
|
754
|
+
schema: "input UndoInput {\n count: Int\n}"
|
|
755
|
+
},
|
|
756
|
+
{
|
|
757
|
+
name: "REDO",
|
|
758
|
+
module: "base",
|
|
759
|
+
scope: "any",
|
|
760
|
+
description: "Redoes the scope's last undone operations",
|
|
761
|
+
schema: "input RedoInput {\n count: Int\n}"
|
|
762
|
+
},
|
|
763
|
+
{
|
|
764
|
+
name: "NOOP",
|
|
765
|
+
module: "base",
|
|
766
|
+
scope: "any",
|
|
767
|
+
description: "Changes nothing"
|
|
768
|
+
}
|
|
769
|
+
];
|
|
770
|
+
const modelOperationSchema = z.object({
|
|
771
|
+
name: z.string(),
|
|
772
|
+
module: z.string(),
|
|
773
|
+
scope: z.string(),
|
|
774
|
+
description: z.string().optional(),
|
|
775
|
+
schema: z.string().optional().describe("GraphQL SDL of the action input")
|
|
776
|
+
});
|
|
777
|
+
const documentModelInfoSchema = z.object({
|
|
778
|
+
type: z.string(),
|
|
779
|
+
name: z.string(),
|
|
780
|
+
description: z.string(),
|
|
781
|
+
extension: z.string(),
|
|
782
|
+
authorName: z.string(),
|
|
783
|
+
authorWebsite: z.string()
|
|
784
|
+
});
|
|
785
|
+
function documentModelInfo(module) {
|
|
786
|
+
const global = module.documentModel.global;
|
|
787
|
+
return {
|
|
788
|
+
type: global.id,
|
|
789
|
+
name: global.name,
|
|
790
|
+
description: global.description,
|
|
791
|
+
extension: global.extension,
|
|
792
|
+
authorName: global.author.name,
|
|
793
|
+
authorWebsite: global.author.website ?? ""
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
function latestSpecification(module) {
|
|
797
|
+
return module.documentModel.global.specifications.at(-1);
|
|
798
|
+
}
|
|
799
|
+
/** The model's operations in its latest specification, without the base ones. */
|
|
800
|
+
function modelOperations(module) {
|
|
801
|
+
return (latestSpecification(module)?.modules ?? []).flatMap((m) => m.operations.filter((op) => Boolean(op.name)).map((op) => ({
|
|
802
|
+
name: op.name,
|
|
803
|
+
module: m.name,
|
|
804
|
+
scope: op.scope || "global",
|
|
805
|
+
...op.description ? { description: op.description } : {},
|
|
806
|
+
...op.schema ? { schema: op.schema } : {}
|
|
807
|
+
})));
|
|
808
|
+
}
|
|
809
|
+
const MODEL_SHADOWS_BASE = /* @__PURE__ */ new Set(["NOOP"]);
|
|
810
|
+
/**
|
|
811
|
+
* @experimental The operation an action type names: a base action the base
|
|
812
|
+
* reducer reduces itself, else the model's own (by stored name, then by action
|
|
813
|
+
* type), else the base NOOP.
|
|
814
|
+
*/
|
|
815
|
+
function resolveOperation(module, type) {
|
|
816
|
+
const base = BASE_OPERATIONS.find((op) => op.name === type);
|
|
817
|
+
if (base && !MODEL_SHADOWS_BASE.has(type)) return {
|
|
818
|
+
operation: base,
|
|
819
|
+
base: true
|
|
820
|
+
};
|
|
821
|
+
const own = modelOperations(module);
|
|
822
|
+
const byName = own.find((op) => op.name === type);
|
|
823
|
+
if (byName) return {
|
|
824
|
+
operation: byName,
|
|
825
|
+
base: false
|
|
826
|
+
};
|
|
827
|
+
const structured = operationsByActionType$1(module).get(type);
|
|
828
|
+
const byActionType = structured && own.find((op) => op.name === structured.storedName);
|
|
829
|
+
if (structured && byActionType) return {
|
|
830
|
+
operation: byActionType,
|
|
831
|
+
base: false,
|
|
832
|
+
creatorKey: structured.creatorKey
|
|
833
|
+
};
|
|
834
|
+
return base && {
|
|
835
|
+
operation: base,
|
|
836
|
+
base: true
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
/** Every action type the document accepts: the model's and the base ones. */
|
|
840
|
+
function actionOperations(module) {
|
|
841
|
+
return [...modelOperations(module), ...BASE_OPERATIONS];
|
|
842
|
+
}
|
|
843
|
+
const documentModelSummarySchema = z.object({
|
|
844
|
+
type: z.string(),
|
|
845
|
+
name: z.string(),
|
|
846
|
+
description: z.string(),
|
|
847
|
+
version: z.number().describe("Version of the latest specification"),
|
|
848
|
+
modules: z.array(z.object({
|
|
849
|
+
name: z.string(),
|
|
850
|
+
operations: z.array(z.string())
|
|
851
|
+
}))
|
|
852
|
+
});
|
|
853
|
+
/** Model name, latest version and its operation names by module. */
|
|
854
|
+
function documentModelSummary(module) {
|
|
855
|
+
const global = module.documentModel.global;
|
|
856
|
+
const latest = latestSpecification(module);
|
|
857
|
+
return {
|
|
858
|
+
type: global.id,
|
|
859
|
+
name: global.name,
|
|
860
|
+
description: global.description,
|
|
861
|
+
version: latest?.version ?? global.specifications.length,
|
|
862
|
+
modules: (latest?.modules ?? []).map((m) => ({
|
|
863
|
+
name: m.name,
|
|
864
|
+
operations: m.operations.map((op) => op.name).filter((name) => Boolean(name))
|
|
865
|
+
}))
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
const operationSliceSchema = modelOperationSchema.extend({ errors: z.array(z.object({
|
|
869
|
+
name: z.string(),
|
|
870
|
+
description: z.string().optional()
|
|
871
|
+
})).optional() });
|
|
872
|
+
/** One operation's input schema; unknown names fail with did-you-mean. */
|
|
873
|
+
function operationSchemaSlice(module, operationName) {
|
|
874
|
+
const operation = resolveOperation(module, operationName)?.operation;
|
|
875
|
+
if (!operation) throw new ReactorToolError("NOT_FOUND", unknownValueMessage("operation", operationName, actionOperations(module).map((op) => op.name), {
|
|
876
|
+
context: `for ${module.documentModel.global.id}`,
|
|
877
|
+
knownLabel: "Valid action types"
|
|
878
|
+
}));
|
|
879
|
+
const errors = ((latestSpecification(module)?.modules.flatMap((m) => m.operations).find((op) => op.name === operation.name))?.errors ?? []).filter((e) => e.name).map((e) => ({
|
|
880
|
+
name: e.name,
|
|
881
|
+
...e.description ? { description: e.description } : {}
|
|
882
|
+
}));
|
|
883
|
+
return {
|
|
884
|
+
...presentedScope(operation),
|
|
885
|
+
...errors.length ? { errors } : {}
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
function presentedScope(operation) {
|
|
889
|
+
if (operation.scope !== "any") return operation;
|
|
890
|
+
const note = "Runs in any of the document's scopes; scope defaults to global.";
|
|
891
|
+
return {
|
|
892
|
+
...operation,
|
|
893
|
+
scope: "global",
|
|
894
|
+
description: operation.description ? `${operation.description}. ${note}` : note
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
const stateSliceSchema = z.object({
|
|
898
|
+
scope: z.string(),
|
|
899
|
+
schema: z.string().describe("GraphQL SDL of the scope's state"),
|
|
900
|
+
initialValue: z.string().optional()
|
|
901
|
+
});
|
|
902
|
+
/** The state schema of one scope in the latest specification. */
|
|
903
|
+
function stateSchemaSlice(module, scope = "global") {
|
|
904
|
+
const state = latestSpecification(module)?.state[scope];
|
|
905
|
+
return {
|
|
906
|
+
scope,
|
|
907
|
+
schema: state?.schema ?? "",
|
|
908
|
+
...state?.initialValue ? { initialValue: state.initialValue } : {}
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
//#endregion
|
|
912
|
+
//#region src/tools/validation.ts
|
|
913
|
+
const actionInputSchema = z.object({
|
|
914
|
+
type: z.string().describe("Exact action type from the model's operations, e.g. SET_MODEL_NAME; see getDocumentModelSchema"),
|
|
915
|
+
input: z.unknown().optional().describe("Action input, shaped by the operation's input schema"),
|
|
916
|
+
scope: z.string().optional().describe("Defaults to the operation's scope; rarely needed")
|
|
917
|
+
});
|
|
918
|
+
function countInput(input) {
|
|
919
|
+
if (typeof input === "number") return input;
|
|
920
|
+
const count = input?.count;
|
|
921
|
+
return typeof count === "number" ? count : void 0;
|
|
922
|
+
}
|
|
923
|
+
const BASE_CREATORS = {
|
|
924
|
+
SET_NAME: (input) => baseActions.setName(input),
|
|
925
|
+
SET_PREFERRED_EDITOR: (input) => baseActions.setPreferredEditor(input),
|
|
926
|
+
UNDO: (input) => baseActions.undo(countInput(input)),
|
|
927
|
+
REDO: (input) => baseActions.redo(countInput(input)),
|
|
928
|
+
NOOP: () => baseActions.noop()
|
|
929
|
+
};
|
|
930
|
+
function issueLines(error) {
|
|
931
|
+
const issues = error.issues;
|
|
932
|
+
if (Array.isArray(issues)) return {
|
|
933
|
+
shape: true,
|
|
934
|
+
lines: issues.map((raw) => {
|
|
935
|
+
const issue = raw;
|
|
936
|
+
const path = Array.isArray(issue.path) ? issue.path.join(".") : "";
|
|
937
|
+
const message = (issue.message ?? "invalid").replace(/^Invalid input:\s*/, "");
|
|
938
|
+
return path ? `${path}: ${message}` : message;
|
|
939
|
+
})
|
|
940
|
+
};
|
|
941
|
+
return {
|
|
942
|
+
shape: false,
|
|
943
|
+
lines: [error instanceof Error ? error.message : String(error)]
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
/** Builds the actions, collecting every failure instead of stopping at the first. */
|
|
947
|
+
function validateActions(module, inputs, options = {}) {
|
|
948
|
+
const allowed = options.allowedActionTypes ? new Set(options.allowedActionTypes) : void 0;
|
|
949
|
+
const actions = [];
|
|
950
|
+
const failures = [];
|
|
951
|
+
inputs.forEach((entry, index) => {
|
|
952
|
+
const fail = (code, errors) => failures.push({
|
|
953
|
+
index,
|
|
954
|
+
type: entry.type,
|
|
955
|
+
code,
|
|
956
|
+
errors
|
|
957
|
+
});
|
|
958
|
+
if (DOCUMENT_SCOPE_ACTION_TYPES.has(entry.type)) return fail("FORBIDDEN", ["document lifecycle actions are refused; use createDocument or deleteDocument"]);
|
|
959
|
+
if (allowed && !allowed.has(entry.type)) return fail("FORBIDDEN", [`not an allowed action type (allowed: ${[...allowed].join(", ")})`]);
|
|
960
|
+
const resolved = resolveOperation(module, entry.type);
|
|
961
|
+
if (!resolved) return fail("INVALID_ACTION", ["unknown action type"]);
|
|
962
|
+
const { operation } = resolved;
|
|
963
|
+
if (entry.scope === "any") return fail("INVALID_ACTION", [`"any" is not a scope; name one, e.g. "global"`]);
|
|
964
|
+
const anyScope = operation.scope === "any";
|
|
965
|
+
const scope = entry.scope ?? (anyScope ? "global" : operation.scope);
|
|
966
|
+
if (!anyScope && scope !== operation.scope) return fail("INVALID_ACTION", [`scope "${scope}" does not match the operation's scope "${operation.scope}"`]);
|
|
967
|
+
const creator = resolved.base ? BASE_CREATORS[entry.type] : module.actions[resolved.creatorKey ?? camelCase(entry.type)];
|
|
968
|
+
if (!creator) return fail("INVALID_ACTION", [`the model has no action creator for ${entry.type}`]);
|
|
969
|
+
try {
|
|
970
|
+
actions.push({
|
|
971
|
+
...creator(entry.input ?? {}),
|
|
972
|
+
scope
|
|
973
|
+
});
|
|
974
|
+
} catch (error) {
|
|
975
|
+
fail("INVALID_ACTION", issueLines(error).lines);
|
|
976
|
+
}
|
|
977
|
+
});
|
|
978
|
+
return {
|
|
979
|
+
actions,
|
|
980
|
+
failures
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
/** One line per failed action, did-you-mean for unknown types, and input schemas for shape errors. */
|
|
984
|
+
function formatActionFailures(failures, module) {
|
|
985
|
+
const operations = module ? actionOperations(module) : [];
|
|
986
|
+
const names = operations.map((o) => o.name);
|
|
987
|
+
const nameOf = (type) => (module && resolveOperation(module, type)?.operation.name) ?? type;
|
|
988
|
+
const count = failures.length;
|
|
989
|
+
const lines = failures.map((f) => ` [${f.index}] ${f.type}: ${f.errors.join("; ")}`);
|
|
990
|
+
const sections = [];
|
|
991
|
+
const unknown = failures.filter((f) => f.code === "INVALID_ACTION" && module && !names.includes(nameOf(f.type)));
|
|
992
|
+
if (unknown.length > 0) {
|
|
993
|
+
const suggestions = new Set(unknown.flatMap((f) => suggestNames(f.type, names)));
|
|
994
|
+
const hint = suggestions.size ? `Did you mean: ${[...suggestions].join(", ")}?\n` : "";
|
|
995
|
+
sections.push(`${hint}Valid action types for ${module?.documentModel.global.id}:\n ${names.join(", ")}`);
|
|
996
|
+
}
|
|
997
|
+
const shown = /* @__PURE__ */ new Set();
|
|
998
|
+
for (const f of failures) {
|
|
999
|
+
const name = nameOf(f.type);
|
|
1000
|
+
const operation = operations.find((o) => o.name === name);
|
|
1001
|
+
if (f.code !== "INVALID_ACTION" || !operation?.schema || shown.has(operation.name)) continue;
|
|
1002
|
+
shown.add(operation.name);
|
|
1003
|
+
sections.push(`Input schema for ${operation.name}:\n${operation.schema}`);
|
|
1004
|
+
}
|
|
1005
|
+
const head = `${count} action${count === 1 ? "" : "s"} failed:\n${lines.join("\n")}`;
|
|
1006
|
+
return sections.length ? `${head}\n\n${sections.join("\n\n")}` : head;
|
|
1007
|
+
}
|
|
1008
|
+
/** The error for a batch with failures; the code is the batch's most severe one. */
|
|
1009
|
+
function actionFailuresError(failures, module) {
|
|
1010
|
+
const codes = new Set(failures.map((f) => f.code));
|
|
1011
|
+
return new ReactorToolError(codes.has("FORBIDDEN") ? "FORBIDDEN" : codes.has("INVALID_ACTION") ? "INVALID_ACTION" : "REDUCER_ERROR", formatActionFailures(failures, module), { failures });
|
|
1012
|
+
}
|
|
1013
|
+
//#endregion
|
|
1014
|
+
//#region src/tools/operations.ts
|
|
1015
|
+
async function getDocument(client, identifier, signal, options = {}) {
|
|
1016
|
+
const { branch, token } = options;
|
|
1017
|
+
try {
|
|
1018
|
+
return await client.get(identifier, branch ? { branch } : void 0, signal, token);
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
throw toReactorToolError(error, "NOT_FOUND");
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
/** The model module for a type; an unknown type fails with did-you-mean. */
|
|
1024
|
+
async function getDocumentModel(client, documentType, signal) {
|
|
1025
|
+
try {
|
|
1026
|
+
return await client.getDocumentModelModule(documentType);
|
|
1027
|
+
} catch (error) {
|
|
1028
|
+
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 });
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
const OPERATIONS_PAGE_SIZE = 100;
|
|
1032
|
+
async function storedOutcomes(client, documentId, branch, actions, before, signal) {
|
|
1033
|
+
const ids = new Set(actions.map((a) => a.id));
|
|
1034
|
+
const outcomes = /* @__PURE__ */ new Map();
|
|
1035
|
+
for (const scope of new Set(actions.map((a) => a.scope))) {
|
|
1036
|
+
let cursor = "0";
|
|
1037
|
+
while (cursor !== void 0) {
|
|
1038
|
+
const page = await client.getOperations(documentId, {
|
|
1039
|
+
branch,
|
|
1040
|
+
scopes: [scope]
|
|
1041
|
+
}, { sinceRevision: before[scope] ?? 0 }, {
|
|
1042
|
+
cursor,
|
|
1043
|
+
limit: OPERATIONS_PAGE_SIZE
|
|
1044
|
+
}, signal);
|
|
1045
|
+
for (const operation of page.results) {
|
|
1046
|
+
if (!ids.has(operation.action.id)) continue;
|
|
1047
|
+
outcomes.set(operation.action.id, {
|
|
1048
|
+
operationIndex: operation.index,
|
|
1049
|
+
...operationOutcome(operation)
|
|
1050
|
+
});
|
|
1051
|
+
}
|
|
1052
|
+
cursor = page.results.length > 0 ? page.nextCursor : void 0;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
return outcomes;
|
|
1056
|
+
}
|
|
1057
|
+
async function readable(handle) {
|
|
1058
|
+
return (await handle).readable;
|
|
1059
|
+
}
|
|
1060
|
+
async function actionOutcomes(client, receipt, actions, before, signal) {
|
|
1061
|
+
const summary = receipt.job.result;
|
|
1062
|
+
if (summary) return new Map(summary.actions.map((a) => [a.actionId, {
|
|
1063
|
+
...a,
|
|
1064
|
+
operationIndex: a.index
|
|
1065
|
+
}]));
|
|
1066
|
+
return storedOutcomes(client, receipt.documentId, receipt.branch, actions, before, signal);
|
|
1067
|
+
}
|
|
1068
|
+
async function revisionAfter(client, receipt, signal) {
|
|
1069
|
+
return { ...(await getDocument(client, receipt.documentId, signal, {
|
|
1070
|
+
branch: receipt.branch,
|
|
1071
|
+
token: receipt.token
|
|
1072
|
+
})).header.revision };
|
|
1073
|
+
}
|
|
1074
|
+
const DENIED_INDEXES = /; denied action indexes: \[(\d+(?:,\d+)*)\]$/;
|
|
1075
|
+
function deniedActions(error) {
|
|
1076
|
+
const denied = error?.denied;
|
|
1077
|
+
if (Array.isArray(denied)) return denied;
|
|
1078
|
+
if (!(error instanceof Error) || error.name !== "ReactorAccessDeniedError") return;
|
|
1079
|
+
const match = DENIED_INDEXES.exec(error.message);
|
|
1080
|
+
if (!match) return void 0;
|
|
1081
|
+
const reason = error.message.slice(0, match.index);
|
|
1082
|
+
return match[1].split(",").map((index) => ({
|
|
1083
|
+
index: Number(index),
|
|
1084
|
+
type: "",
|
|
1085
|
+
reason
|
|
1086
|
+
}));
|
|
1087
|
+
}
|
|
1088
|
+
function isDenial(error) {
|
|
1089
|
+
if (deniedActions(error)) return true;
|
|
1090
|
+
if (!(error instanceof Error)) return false;
|
|
1091
|
+
const job = error.job;
|
|
1092
|
+
return error.name === "AuthorizationDeniedError" || error.name === "JobFailedError" && job?.error?.name === "AuthorizationDeniedError";
|
|
1093
|
+
}
|
|
1094
|
+
const NO_OPERATION = "The reactor stored no operation for this action";
|
|
1095
|
+
/** Executes built actions and returns the new revision; any action not applied throws. */
|
|
1096
|
+
async function executeBuiltActions(client, document, actions, options = {}) {
|
|
1097
|
+
const { branch = DEFAULT_BRANCH, signal, module } = options;
|
|
1098
|
+
let receipt;
|
|
1099
|
+
try {
|
|
1100
|
+
receipt = await readable(client.write.execute(document.header.id, branch, actions, signal));
|
|
1101
|
+
} catch (error) {
|
|
1102
|
+
const denied = deniedActions(error);
|
|
1103
|
+
if (denied) throw actionFailuresError(denied.map((d) => ({
|
|
1104
|
+
index: d.index,
|
|
1105
|
+
type: d.type || (actions.at(d.index)?.type ?? ""),
|
|
1106
|
+
code: "FORBIDDEN",
|
|
1107
|
+
errors: [d.reason]
|
|
1108
|
+
})), module);
|
|
1109
|
+
throw toReactorToolError(error);
|
|
1110
|
+
}
|
|
1111
|
+
const outcomes = await actionOutcomes(client, receipt, actions, document.header.revision, signal);
|
|
1112
|
+
const failures = actions.flatMap((action, index) => {
|
|
1113
|
+
const outcome = outcomes.get(action.id);
|
|
1114
|
+
if (outcome?.kind === "applied") return [];
|
|
1115
|
+
return [{
|
|
1116
|
+
index,
|
|
1117
|
+
type: action.type,
|
|
1118
|
+
code: outcome?.kind === "denied" ? "FORBIDDEN" : "REDUCER_ERROR",
|
|
1119
|
+
errors: [!outcome ? NO_OPERATION : outcome.kind === "denied" ? outcome.reason : outcome.message]
|
|
1120
|
+
}];
|
|
1121
|
+
});
|
|
1122
|
+
if (failures.length > 0) throw actionFailuresError(failures, module);
|
|
1123
|
+
return revisionAfter(client, receipt, signal);
|
|
1124
|
+
}
|
|
1125
|
+
/** The model module at the document's own version. */
|
|
1126
|
+
async function getDocumentModelForDocument(client, document, signal) {
|
|
1127
|
+
try {
|
|
1128
|
+
return await client.getDocumentModelModuleForDocument(document);
|
|
1129
|
+
} catch (error) {
|
|
1130
|
+
await getDocumentModel(client, document.header.documentType, signal);
|
|
1131
|
+
throw toReactorToolError(error, "NOT_FOUND");
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
/** Finds the declared error a reducer error was, by code, class name, then default message. */
|
|
1135
|
+
function modelErrorFinder(module, actionType) {
|
|
1136
|
+
const operations = (module.documentModel.global.specifications.at(-1)?.modules ?? []).flatMap((m) => m.operations);
|
|
1137
|
+
const declared = (errors) => errors.flatMap(({ name, code }) => {
|
|
1138
|
+
if (!name) return [];
|
|
1139
|
+
const className = pascalCase(name);
|
|
1140
|
+
return [{
|
|
1141
|
+
name: className,
|
|
1142
|
+
code: code?.trim() || className
|
|
1143
|
+
}];
|
|
1144
|
+
});
|
|
1145
|
+
const ownName = resolveOperation(module, actionType)?.operation.name;
|
|
1146
|
+
const candidates = [...declared(operations.find((o) => o.name === ownName)?.errors ?? []), ...declared(operations.flatMap((o) => o.errors))];
|
|
1147
|
+
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);
|
|
1148
|
+
}
|
|
1149
|
+
function outcomeError(outcome, module, actionType) {
|
|
1150
|
+
if (!outcome) return {
|
|
1151
|
+
kind: "not-applied",
|
|
1152
|
+
message: NO_OPERATION
|
|
1153
|
+
};
|
|
1154
|
+
if (outcome.kind === "applied") return void 0;
|
|
1155
|
+
if (outcome.kind === "denied") return {
|
|
1156
|
+
kind: "denied",
|
|
1157
|
+
message: outcome.reason
|
|
1158
|
+
};
|
|
1159
|
+
const known = modelErrorFinder(module, actionType)(outcome.name, outcome.code, outcome.message);
|
|
1160
|
+
const name = known?.name ?? outcome.name;
|
|
1161
|
+
const code = known?.code ?? outcome.code;
|
|
1162
|
+
return {
|
|
1163
|
+
kind: "reducer-error",
|
|
1164
|
+
message: outcome.message,
|
|
1165
|
+
...name !== void 0 && { name },
|
|
1166
|
+
...code !== void 0 && { code }
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
async function refusedBatch(client, documentId, branch, actions, error, signal) {
|
|
1170
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1171
|
+
const notApplied = {
|
|
1172
|
+
kind: "not-applied",
|
|
1173
|
+
message: `The batch was refused, so nothing in it was written: ${message}`
|
|
1174
|
+
};
|
|
1175
|
+
const denied = deniedActions(error);
|
|
1176
|
+
if (denied) return actions.map((_, i) => {
|
|
1177
|
+
const denial = denied.find((d) => d.index === i);
|
|
1178
|
+
return denial ? {
|
|
1179
|
+
kind: "denied",
|
|
1180
|
+
message: denial.reason
|
|
1181
|
+
} : notApplied;
|
|
1182
|
+
});
|
|
1183
|
+
const evaluating = client;
|
|
1184
|
+
const target = evaluating.write.evaluateActions ? evaluating.write : evaluating;
|
|
1185
|
+
const evaluate = target.evaluateActions;
|
|
1186
|
+
if (typeof evaluate !== "function") return actions.map(() => notApplied);
|
|
1187
|
+
try {
|
|
1188
|
+
const { evaluations } = await evaluate.call(target, documentId, branch, actions.map(({ scope, type, input }) => ({
|
|
1189
|
+
scope,
|
|
1190
|
+
type,
|
|
1191
|
+
input
|
|
1192
|
+
})), void 0, signal);
|
|
1193
|
+
return actions.map((_, i) => {
|
|
1194
|
+
const evaluation = evaluations.at(i);
|
|
1195
|
+
return evaluation?.decision === "deny" ? {
|
|
1196
|
+
kind: "denied",
|
|
1197
|
+
message: evaluation.reason ?? message
|
|
1198
|
+
} : notApplied;
|
|
1199
|
+
});
|
|
1200
|
+
} catch {
|
|
1201
|
+
return actions.map(() => notApplied);
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
function isUndoRedo(type) {
|
|
1205
|
+
return type === "UNDO" || type === "REDO";
|
|
1206
|
+
}
|
|
1207
|
+
/** Every stored row of one scope. */
|
|
1208
|
+
async function scopeOperations(client, documentId, branch, scope, signal) {
|
|
1209
|
+
const rows = [];
|
|
1210
|
+
let cursor = "0";
|
|
1211
|
+
while (cursor !== void 0) {
|
|
1212
|
+
const page = await client.getOperations(documentId, {
|
|
1213
|
+
branch,
|
|
1214
|
+
scopes: [scope]
|
|
1215
|
+
}, void 0, {
|
|
1216
|
+
cursor,
|
|
1217
|
+
limit: OPERATIONS_PAGE_SIZE
|
|
1218
|
+
}, signal);
|
|
1219
|
+
rows.push(...page.results);
|
|
1220
|
+
cursor = page.results.length > 0 ? page.nextCursor : void 0;
|
|
1221
|
+
}
|
|
1222
|
+
return rows;
|
|
1223
|
+
}
|
|
1224
|
+
async function retractionBatch(client, document, module, inputs, actions, options, signal) {
|
|
1225
|
+
const { branch = DEFAULT_BRANCH } = options;
|
|
1226
|
+
const caps = undoCapabilitiesOf(document.header);
|
|
1227
|
+
if (caps === void 0 || !undoNeedsTargets(caps) || !actions.some((action) => isUndoRedo(action.type))) return;
|
|
1228
|
+
const counts = actions.map((action) => isUndoRedo(action.type) ? action.input.count : 0);
|
|
1229
|
+
const invalid = actions.flatMap((action, index) => {
|
|
1230
|
+
const count = counts[index];
|
|
1231
|
+
if (!isUndoRedo(action.type) || Number.isInteger(count) && count >= 1) return [];
|
|
1232
|
+
return [{
|
|
1233
|
+
index,
|
|
1234
|
+
type: action.type,
|
|
1235
|
+
code: "INVALID_ACTION",
|
|
1236
|
+
errors: ["count must be a positive integer"]
|
|
1237
|
+
}];
|
|
1238
|
+
});
|
|
1239
|
+
if (invalid.length > 0) throw actionFailuresError(invalid, module);
|
|
1240
|
+
const reducer = stateReducerOf(module.reducer);
|
|
1241
|
+
if (reducer === void 0) throw new ReactorToolError("INVALID_ACTION", `Document model ${document.header.documentType} has no state reducer to resolve undo targets with`);
|
|
1242
|
+
const id = document.header.id;
|
|
1243
|
+
const operations = {};
|
|
1244
|
+
for (const action of actions) {
|
|
1245
|
+
if (!isUndoRedo(action.type) || action.scope in operations) continue;
|
|
1246
|
+
operations[action.scope] = await scopeOperations(client, id, branch, action.scope, signal);
|
|
1247
|
+
}
|
|
1248
|
+
const initialState = creationState(await scopeOperations(client, id, branch, "document", signal)) ?? module.utils.createDocument().initialState;
|
|
1249
|
+
const batch = undoRedoBatch({
|
|
1250
|
+
...document,
|
|
1251
|
+
initialState,
|
|
1252
|
+
operations
|
|
1253
|
+
}, caps, reducer);
|
|
1254
|
+
const sources = [];
|
|
1255
|
+
for (const [index, action] of actions.entries()) {
|
|
1256
|
+
const before = batch.actions.length;
|
|
1257
|
+
if (isUndoRedo(action.type)) try {
|
|
1258
|
+
for (let step = 0; step < counts[index]; step++) batch.undoOrRedo(action.type, action.scope);
|
|
1259
|
+
} catch (error) {
|
|
1260
|
+
throw actionFailuresError([{
|
|
1261
|
+
index,
|
|
1262
|
+
type: action.type,
|
|
1263
|
+
code: "INVALID_ACTION",
|
|
1264
|
+
errors: [error instanceof Error ? error.message : String(error)]
|
|
1265
|
+
}], module);
|
|
1266
|
+
}
|
|
1267
|
+
else batch.add(validateActions(module, [inputs[index]], options).actions[0]);
|
|
1268
|
+
for (let i = before; i < batch.actions.length; i++) sources.push(index);
|
|
1269
|
+
}
|
|
1270
|
+
return {
|
|
1271
|
+
actions: [...batch.actions],
|
|
1272
|
+
sources
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
function perInput(inputs, sources, submitted) {
|
|
1276
|
+
return inputs.map((action, index) => {
|
|
1277
|
+
const steps = submitted.filter((r) => sources[r.index] === index);
|
|
1278
|
+
const operationIndex = steps.at(-1)?.operationIndex;
|
|
1279
|
+
const error = steps.find((step) => step.error?.kind === "denied")?.error ?? steps.find((step) => step.error)?.error;
|
|
1280
|
+
return {
|
|
1281
|
+
index,
|
|
1282
|
+
type: action.type,
|
|
1283
|
+
scope: action.scope,
|
|
1284
|
+
...operationIndex !== void 0 && { operationIndex },
|
|
1285
|
+
...error && { error }
|
|
1286
|
+
};
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
/** Validates every action, then executes them as one batch and reports each action's outcome. */
|
|
1290
|
+
async function executeActions(client, documentId, inputs, options = {}) {
|
|
1291
|
+
const { signal, branch = DEFAULT_BRANCH } = options;
|
|
1292
|
+
const document = await getDocument(client, documentId, signal, { branch });
|
|
1293
|
+
const id = document.header.id;
|
|
1294
|
+
const module = await getDocumentModelForDocument(client, document, signal);
|
|
1295
|
+
const validated = validateActions(module, inputs, options);
|
|
1296
|
+
if (validated.failures.length > 0) throw actionFailuresError(validated.failures, module);
|
|
1297
|
+
const before = { ...document.header.revision };
|
|
1298
|
+
if (validated.actions.length === 0) return {
|
|
1299
|
+
documentId: id,
|
|
1300
|
+
revision: before,
|
|
1301
|
+
success: true,
|
|
1302
|
+
results: []
|
|
1303
|
+
};
|
|
1304
|
+
const retraction = await retractionBatch(client, document, module, inputs, validated.actions, options, signal);
|
|
1305
|
+
const actions = retraction?.actions ?? validated.actions;
|
|
1306
|
+
const reported = (submitted) => retraction ? perInput(validated.actions, retraction.sources, submitted) : submitted;
|
|
1307
|
+
const result = (action, index) => ({
|
|
1308
|
+
index,
|
|
1309
|
+
type: action.type,
|
|
1310
|
+
scope: action.scope
|
|
1311
|
+
});
|
|
1312
|
+
let receipt;
|
|
1313
|
+
try {
|
|
1314
|
+
receipt = await readable(client.write.execute(id, branch, actions, signal));
|
|
1315
|
+
} catch (error) {
|
|
1316
|
+
if (!isDenial(error)) throw toReactorToolError(error);
|
|
1317
|
+
const errors = await refusedBatch(client, id, branch, actions, error, signal);
|
|
1318
|
+
return {
|
|
1319
|
+
documentId: id,
|
|
1320
|
+
revision: before,
|
|
1321
|
+
success: false,
|
|
1322
|
+
results: reported(actions.map((a, i) => ({
|
|
1323
|
+
...result(a, i),
|
|
1324
|
+
error: errors[i]
|
|
1325
|
+
})))
|
|
1326
|
+
};
|
|
1327
|
+
}
|
|
1328
|
+
const outcomes = await actionOutcomes(client, receipt, actions, before, signal);
|
|
1329
|
+
const results = reported(actions.map((action, index) => {
|
|
1330
|
+
const outcome = outcomes.get(action.id);
|
|
1331
|
+
const error = outcomeError(outcome, module, action.type);
|
|
1332
|
+
return {
|
|
1333
|
+
...result(action, index),
|
|
1334
|
+
...outcome && { operationIndex: outcome.operationIndex },
|
|
1335
|
+
...error && { error }
|
|
1336
|
+
};
|
|
1337
|
+
}));
|
|
1338
|
+
return {
|
|
1339
|
+
documentId: id,
|
|
1340
|
+
revision: await revisionAfter(client, receipt, signal),
|
|
1341
|
+
success: results.every((r) => !r.error),
|
|
1342
|
+
results
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
const ROLLBACK_TIMEOUT_MS = 1e4;
|
|
1346
|
+
async function addFileError(client, drive, documentId, signal) {
|
|
1347
|
+
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);
|
|
1348
|
+
const outcome = operation && operationOutcome(operation);
|
|
1349
|
+
if (outcome?.kind === "reducer-error") return outcome.message;
|
|
1350
|
+
if (outcome?.kind === "denied") return outcome.reason;
|
|
1351
|
+
}
|
|
1352
|
+
/** Creates the document, filed into the drive when given; a half-done filing is rolled back. */
|
|
1353
|
+
async function createDocument(client, input, signal) {
|
|
1354
|
+
const module = await getDocumentModel(client, input.documentType, signal);
|
|
1355
|
+
const drive = input.driveId ? await getDocument(client, input.driveId, signal) : void 0;
|
|
1356
|
+
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`);
|
|
1357
|
+
if (input.parentFolder && !drive) throw new ReactorToolError("INVALID_ACTION", "parentFolder needs driveId to name a drive");
|
|
1358
|
+
const documentType = module.documentModel.global.id;
|
|
1359
|
+
const name = input.name ?? "";
|
|
1360
|
+
let document;
|
|
1361
|
+
try {
|
|
1362
|
+
document = await client.newDocument(documentType, {
|
|
1363
|
+
...drive && { parentIdentifier: drive.header.id },
|
|
1364
|
+
...name && { name }
|
|
1365
|
+
}, signal);
|
|
1366
|
+
} catch (error) {
|
|
1367
|
+
throw toReactorToolError(error);
|
|
1368
|
+
}
|
|
1369
|
+
const documentId = document.header.id;
|
|
1370
|
+
const rollback = async (error) => {
|
|
1371
|
+
const e = toReactorToolError(error);
|
|
1372
|
+
try {
|
|
1373
|
+
await deleteDocument(client, documentId, AbortSignal.timeout(ROLLBACK_TIMEOUT_MS));
|
|
1374
|
+
} catch (deleteError) {
|
|
1375
|
+
if (toReactorToolError(deleteError).code !== "NOT_FOUND") return new ReactorToolError(e.code, `Document ${documentId} was created but could not be removed after: ${e.message}`, {
|
|
1376
|
+
failures: e.failures,
|
|
1377
|
+
cause: error
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
return new ReactorToolError(e.code, e.message, {
|
|
1381
|
+
failures: e.failures,
|
|
1382
|
+
cause: error
|
|
1383
|
+
});
|
|
1384
|
+
};
|
|
1385
|
+
let receipt;
|
|
1386
|
+
if (!drive) try {
|
|
1387
|
+
receipt = await readable(client.write.create(document, void 0, signal));
|
|
1388
|
+
} catch (error) {
|
|
1389
|
+
throw toReactorToolError(error);
|
|
1390
|
+
}
|
|
1391
|
+
else {
|
|
1392
|
+
try {
|
|
1393
|
+
receipt = await readable(client.write.drives.addFile(drive.header.id, document, input.parentFolder, signal));
|
|
1394
|
+
} catch (error) {
|
|
1395
|
+
throw await rollback(error);
|
|
1396
|
+
}
|
|
1397
|
+
if (drive.header.documentType === "powerhouse/document-drive") {
|
|
1398
|
+
const nodes = ((await getDocument(client, drive.header.id, signal, { token: receipt.token }).catch(() => void 0))?.state)?.global?.nodes;
|
|
1399
|
+
if (nodes && !nodes.some((node) => node.id === documentId)) {
|
|
1400
|
+
const reason = await addFileError(client, drive, documentId, signal) ?? "the drive stored no node for it";
|
|
1401
|
+
throw await rollback(new ReactorToolError("REDUCER_ERROR", `Drive ${drive.header.id} did not file the document: ${reason}`));
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
const created = await getDocument(client, documentId, signal, { token: receipt.token });
|
|
1406
|
+
return {
|
|
1407
|
+
documentId,
|
|
1408
|
+
documentType,
|
|
1409
|
+
name,
|
|
1410
|
+
...drive ? { driveId: drive.header.id } : {},
|
|
1411
|
+
revision: { ...created.header.revision }
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
/** Removes the document's node from each document drive filing it, then deletes it. */
|
|
1415
|
+
async function deleteDocument(client, documentId, signal) {
|
|
1416
|
+
const id = (await getDocument(client, documentId, signal)).header.id;
|
|
1417
|
+
const { authorizeDelete } = client.write;
|
|
1418
|
+
await authorizeDelete?.call(client.write, id, signal);
|
|
1419
|
+
const parents = await client.getIncomingRelationships(id, "child", void 0, void 0, signal).catch((error) => {
|
|
1420
|
+
throw toReactorToolError(error);
|
|
1421
|
+
});
|
|
1422
|
+
const filing = [];
|
|
1423
|
+
for (const parent of parents.results) {
|
|
1424
|
+
if (parent.header.documentType !== "powerhouse/document-drive") continue;
|
|
1425
|
+
const nodes = parent.state.global?.nodes;
|
|
1426
|
+
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`);
|
|
1427
|
+
if (nodes.some((node) => node.id === id)) filing.push(parent);
|
|
1428
|
+
}
|
|
1429
|
+
for (const parent of filing) await executeBuiltActions(client, parent, [deleteNode({ id })], { signal });
|
|
1430
|
+
try {
|
|
1431
|
+
await readable(client.write.deleteDocument(id, void 0, signal));
|
|
1432
|
+
} catch (error) {
|
|
1433
|
+
throw toReactorToolError(error);
|
|
1434
|
+
}
|
|
1435
|
+
return { documentId: id };
|
|
1436
|
+
}
|
|
1437
|
+
//#endregion
|
|
1438
|
+
//#region src/tools/reactor.ts
|
|
1439
|
+
const MAX_LISTED = 500;
|
|
1440
|
+
async function collect(first) {
|
|
1441
|
+
let page = await first.catch((error) => {
|
|
1442
|
+
throw toReactorToolError(error);
|
|
1443
|
+
});
|
|
1444
|
+
const out = [];
|
|
1445
|
+
for (;;) {
|
|
1446
|
+
out.push(...page.results);
|
|
1447
|
+
if (out.length >= MAX_LISTED || !page.next || page.results.length === 0) break;
|
|
1448
|
+
page = await page.next();
|
|
1449
|
+
}
|
|
1450
|
+
return out.slice(0, MAX_LISTED);
|
|
1451
|
+
}
|
|
1452
|
+
const filterSchema = z.string().optional().describe("JSONPath over the document state, e.g. $.global.items[?(@.status=='OPEN')] or $.global.items[-1]");
|
|
1453
|
+
/** The parameter every tool names its target document or drive by. */
|
|
1454
|
+
const TARGET = "documentId";
|
|
1455
|
+
const targetParam = (what) => z.string().optional().describe(`ID or slug of the ${what}. Required.`);
|
|
1456
|
+
const aliasParam = z.string().optional().describe(`Alias of \`${TARGET}\``);
|
|
1457
|
+
/** The target named by `documentId` or one of its aliases; they must agree. */
|
|
1458
|
+
function targetId(tool, args, aliases) {
|
|
1459
|
+
const given = new Set([TARGET, ...aliases].map((name) => args[name]).filter((id) => typeof id === "string" && id !== ""));
|
|
1460
|
+
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}\``);
|
|
1461
|
+
const [id] = given;
|
|
1462
|
+
if (!id) throw new ReactorToolError("INVALID_ACTION", `${tool} needs the target's ID in \`${TARGET}\``);
|
|
1463
|
+
return id;
|
|
1464
|
+
}
|
|
1465
|
+
const revisionSchema = z.record(z.string(), z.number()).describe("Revision per scope after the change");
|
|
1466
|
+
const readOnly = {
|
|
1467
|
+
readOnlyHint: true,
|
|
1468
|
+
destructiveHint: false,
|
|
1469
|
+
openWorldHint: false
|
|
1470
|
+
};
|
|
1471
|
+
const getDocumentModelsTool = defineTool({
|
|
1472
|
+
name: "getDocumentModels",
|
|
1473
|
+
title: "List document models",
|
|
1474
|
+
description: "List the document model types this reactor can create and edit.",
|
|
1475
|
+
inputSchema: z.object({}),
|
|
1476
|
+
outputSchema: z.object({ documentModels: z.array(documentModelInfoSchema) }),
|
|
1477
|
+
annotations: readOnly,
|
|
1478
|
+
async execute(_args, { client, signal }) {
|
|
1479
|
+
return { documentModels: (await collect(client.getDocumentModelModules(void 0, void 0, signal))).map(documentModelInfo) };
|
|
1480
|
+
}
|
|
1481
|
+
});
|
|
1482
|
+
const getDocumentModelSchemaTool = defineTool({
|
|
1483
|
+
name: "getDocumentModelSchema",
|
|
1484
|
+
title: "Read a document model schema",
|
|
1485
|
+
description: `Read a document model's schema. Without options it returns the operation names per module.
|
|
1486
|
+
Pass "compact" before addActions for every action's type, scope and input definition, and the types those inputs use.
|
|
1487
|
+
Pass "operation" for one action's input schema (GraphQL SDL), "state" for a state schema, or "filter" for a JSONPath over the latest specification.
|
|
1488
|
+
Pass "definition" to also return the structured definition of a model authored in code.`,
|
|
1489
|
+
inputSchema: z.object({
|
|
1490
|
+
type: z.string().describe("Document model type, e.g. powerhouse/document-model"),
|
|
1491
|
+
compact: z.boolean().optional().describe("Return every action's type, scope and input definition"),
|
|
1492
|
+
definition: z.boolean().optional().describe("Also return the structured definition of a model authored in code; ignored with compact, operation, state or filter"),
|
|
1493
|
+
operation: z.string().optional().describe("Action type whose input schema to return, e.g. SET_MODEL_NAME"),
|
|
1494
|
+
state: z.enum(["global", "local"]).optional().describe("Scope whose state schema to return"),
|
|
1495
|
+
filter: z.string().optional().describe("JSONPath over the latest specification, e.g. $.modules[*].name")
|
|
1496
|
+
}),
|
|
1497
|
+
outputSchema: z.object({
|
|
1498
|
+
type: z.string(),
|
|
1499
|
+
model: documentModelSummarySchema.optional(),
|
|
1500
|
+
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"),
|
|
1501
|
+
compact: compactDocumentModelSchemaSchema.optional(),
|
|
1502
|
+
operation: operationSliceSchema.optional(),
|
|
1503
|
+
state: stateSliceSchema.optional(),
|
|
1504
|
+
value: z.unknown().optional().describe("The filter's match")
|
|
1505
|
+
}),
|
|
1506
|
+
annotations: readOnly,
|
|
1507
|
+
async execute(args, { client, signal }) {
|
|
1508
|
+
const module = await getDocumentModel(client, args.type, signal);
|
|
1509
|
+
const type = module.documentModel.global.id;
|
|
1510
|
+
if (args.compact) return {
|
|
1511
|
+
type,
|
|
1512
|
+
compact: compactDocumentModelSchema(module.documentModel.global)
|
|
1513
|
+
};
|
|
1514
|
+
if (!args.operation && !args.state && !args.filter) {
|
|
1515
|
+
const definition = args.definition && structuredDefinition(module);
|
|
1516
|
+
return {
|
|
1517
|
+
type,
|
|
1518
|
+
model: documentModelSummary(module),
|
|
1519
|
+
...definition && { definition }
|
|
1520
|
+
};
|
|
1521
|
+
}
|
|
1522
|
+
let value;
|
|
1523
|
+
if (args.filter) try {
|
|
1524
|
+
value = applyJsonPath(latestSpecification(module), args.filter);
|
|
1525
|
+
} catch (error) {
|
|
1526
|
+
if (error instanceof JsonPathError) throw new ReactorToolError("INVALID_ACTION", error.message);
|
|
1527
|
+
throw error;
|
|
1528
|
+
}
|
|
1529
|
+
return {
|
|
1530
|
+
type,
|
|
1531
|
+
...args.operation ? { operation: operationSchemaSlice(module, args.operation) } : {},
|
|
1532
|
+
...args.state ? { state: stateSchemaSlice(module, args.state) } : {},
|
|
1533
|
+
...args.filter ? { value } : {}
|
|
1534
|
+
};
|
|
1535
|
+
}
|
|
1536
|
+
});
|
|
1537
|
+
const getDocumentTool = defineTool({
|
|
1538
|
+
name: "getDocument",
|
|
1539
|
+
title: "Read a document",
|
|
1540
|
+
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).",
|
|
1541
|
+
inputSchema: z.object({
|
|
1542
|
+
documentId: targetParam("document to read"),
|
|
1543
|
+
id: aliasParam,
|
|
1544
|
+
filter: filterSchema
|
|
1545
|
+
}),
|
|
1546
|
+
outputSchema: z.object({ document: documentViewSchema }),
|
|
1547
|
+
annotations: readOnly,
|
|
1548
|
+
async execute(args, { client, signal }) {
|
|
1549
|
+
return { document: documentView(await getDocument(client, targetId("getDocument", args, ["id"]), signal), { filter: args.filter }) };
|
|
1550
|
+
}
|
|
1551
|
+
});
|
|
1552
|
+
const getDocumentsTool = defineTool({
|
|
1553
|
+
name: "getDocuments",
|
|
1554
|
+
title: "List a drive's documents",
|
|
1555
|
+
description: "List the documents in a drive (its children): id, type and name.",
|
|
1556
|
+
inputSchema: z.object({
|
|
1557
|
+
documentId: targetParam("drive whose documents to list"),
|
|
1558
|
+
driveId: aliasParam,
|
|
1559
|
+
parentId: aliasParam
|
|
1560
|
+
}),
|
|
1561
|
+
outputSchema: z.object({ documents: z.array(documentSummarySchema) }),
|
|
1562
|
+
annotations: readOnly,
|
|
1563
|
+
async execute(args, { client, signal }) {
|
|
1564
|
+
const driveId = targetId("getDocuments", args, ["driveId", "parentId"]);
|
|
1565
|
+
return { documents: (await collect(client.getOutgoingRelationships(driveId, "child", void 0, void 0, signal))).map(documentSummary) };
|
|
1566
|
+
}
|
|
1567
|
+
});
|
|
1568
|
+
const getDrivesTool = defineTool({
|
|
1569
|
+
name: "getDrives",
|
|
1570
|
+
title: "List drives",
|
|
1571
|
+
description: "List the drives: id, type and name.",
|
|
1572
|
+
inputSchema: z.object({}),
|
|
1573
|
+
outputSchema: z.object({ drives: z.array(documentSummarySchema) }),
|
|
1574
|
+
annotations: readOnly,
|
|
1575
|
+
async execute(_args, { client, signal }) {
|
|
1576
|
+
return { drives: (await collect(client.find({ type: DRIVE_DOCUMENT_TYPE }, void 0, void 0, signal))).map(documentSummary) };
|
|
1577
|
+
}
|
|
1578
|
+
});
|
|
1579
|
+
const getDriveTool = defineTool({
|
|
1580
|
+
name: "getDrive",
|
|
1581
|
+
title: "Read a drive",
|
|
1582
|
+
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.",
|
|
1583
|
+
inputSchema: z.object({
|
|
1584
|
+
documentId: targetParam("drive to read"),
|
|
1585
|
+
driveId: aliasParam,
|
|
1586
|
+
id: aliasParam,
|
|
1587
|
+
filter: filterSchema
|
|
1588
|
+
}),
|
|
1589
|
+
outputSchema: z.object({ drive: documentViewSchema }),
|
|
1590
|
+
annotations: readOnly,
|
|
1591
|
+
async execute(args, { client, signal }) {
|
|
1592
|
+
return { drive: documentView(await getDocument(client, targetId("getDrive", args, ["driveId", "id"]), signal), { filter: args.filter }) };
|
|
1593
|
+
}
|
|
1594
|
+
});
|
|
1595
|
+
const createDocumentTool = defineTool({
|
|
1596
|
+
name: "createDocument",
|
|
1597
|
+
title: "Create a document",
|
|
1598
|
+
description: `Create a document, optionally inside a drive.
|
|
1599
|
+
With "driveId" the document is added to the drive as a file, so no separate ADD_FILE is needed.`,
|
|
1600
|
+
inputSchema: z.object({
|
|
1601
|
+
documentType: z.string().describe("Document model type"),
|
|
1602
|
+
name: z.string().optional().describe("Document name, also the drive file's name"),
|
|
1603
|
+
driveId: z.string().optional().describe("Drive id or slug to create the document in"),
|
|
1604
|
+
parentFolder: z.string().optional().describe("Folder id within the drive; only with driveId")
|
|
1605
|
+
}),
|
|
1606
|
+
outputSchema: z.object({
|
|
1607
|
+
documentId: z.string(),
|
|
1608
|
+
documentType: z.string(),
|
|
1609
|
+
name: z.string(),
|
|
1610
|
+
driveId: z.string().optional(),
|
|
1611
|
+
revision: revisionSchema
|
|
1612
|
+
}),
|
|
1613
|
+
annotations: {
|
|
1614
|
+
readOnlyHint: false,
|
|
1615
|
+
destructiveHint: false,
|
|
1616
|
+
openWorldHint: false
|
|
1617
|
+
},
|
|
1618
|
+
async execute(args, { client, signal }) {
|
|
1619
|
+
return createDocument(client, args, signal);
|
|
1620
|
+
}
|
|
1621
|
+
});
|
|
1622
|
+
const deleteDocumentTool = defineTool({
|
|
1623
|
+
name: "deleteDocument",
|
|
1624
|
+
title: "Delete a document",
|
|
1625
|
+
description: "Delete a document, removing it from its drive first.",
|
|
1626
|
+
inputSchema: z.object({
|
|
1627
|
+
documentId: targetParam("document to delete"),
|
|
1628
|
+
id: aliasParam
|
|
1629
|
+
}),
|
|
1630
|
+
outputSchema: z.object({ documentId: z.string() }),
|
|
1631
|
+
annotations: {
|
|
1632
|
+
readOnlyHint: false,
|
|
1633
|
+
destructiveHint: true,
|
|
1634
|
+
openWorldHint: false
|
|
1635
|
+
},
|
|
1636
|
+
async execute(args, { client, signal }) {
|
|
1637
|
+
return deleteDocument(client, targetId("deleteDocument", args, ["id"]), signal);
|
|
1638
|
+
}
|
|
1639
|
+
});
|
|
1640
|
+
const actionErrorSchema = z.object({
|
|
1641
|
+
kind: z.enum([
|
|
1642
|
+
"reducer-error",
|
|
1643
|
+
"denied",
|
|
1644
|
+
"not-applied"
|
|
1645
|
+
]).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"),
|
|
1646
|
+
message: z.string().describe("Why the action was not applied"),
|
|
1647
|
+
name: z.string().optional().describe("For a reducer-error: the error class the reducer threw"),
|
|
1648
|
+
code: z.string().optional().describe("For a reducer-error: the error's code in the document model")
|
|
1649
|
+
}).describe("Present when the action was not applied");
|
|
1650
|
+
function createAddActionsTool(options = {}) {
|
|
1651
|
+
const allowed = options.allowedActionTypes;
|
|
1652
|
+
return defineTool({
|
|
1653
|
+
name: "addActions",
|
|
1654
|
+
title: "Change a document",
|
|
1655
|
+
description: `Apply actions to a document as one batch. Send several actions in one call rather than one call each.
|
|
1656
|
+
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.
|
|
1657
|
+
Every action is validated first; on a validation failure nothing is applied and each failed action is listed.
|
|
1658
|
+
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.
|
|
1659
|
+
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(", ")}.` : ""}`,
|
|
1660
|
+
inputSchema: z.object({
|
|
1661
|
+
documentId: targetParam("document or drive to change"),
|
|
1662
|
+
id: aliasParam,
|
|
1663
|
+
actions: z.array(actionInputSchema).min(1).describe("Actions to apply, in order")
|
|
1664
|
+
}),
|
|
1665
|
+
outputSchema: z.object({
|
|
1666
|
+
documentId: z.string(),
|
|
1667
|
+
revision: revisionSchema,
|
|
1668
|
+
success: z.boolean().describe("False when any action was not applied"),
|
|
1669
|
+
results: z.array(z.object({
|
|
1670
|
+
index: z.number().describe("Position of the action in `actions`"),
|
|
1671
|
+
type: z.string(),
|
|
1672
|
+
scope: z.string(),
|
|
1673
|
+
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"),
|
|
1674
|
+
error: actionErrorSchema.optional()
|
|
1675
|
+
})).describe("One result per action, in the order they were given"),
|
|
1676
|
+
codegen: z.string().optional().describe("Present when Vetra generates code from this document: how to follow that generation")
|
|
1677
|
+
}),
|
|
1678
|
+
annotations: {
|
|
1679
|
+
readOnlyHint: false,
|
|
1680
|
+
destructiveHint: true,
|
|
1681
|
+
openWorldHint: false
|
|
1682
|
+
},
|
|
1683
|
+
async execute(args, { client, signal }) {
|
|
1684
|
+
const executed = await executeActions(client, targetId("addActions", args, ["id"]), args.actions, {
|
|
1685
|
+
allowedActionTypes: allowed,
|
|
1686
|
+
signal
|
|
1687
|
+
});
|
|
1688
|
+
const codegen = options.codegenStatus && await codegenHint(options.codegenStatus, client, executed, signal);
|
|
1689
|
+
return {
|
|
1690
|
+
...executed,
|
|
1691
|
+
...codegen && { codegen }
|
|
1692
|
+
};
|
|
1693
|
+
}
|
|
1694
|
+
});
|
|
1695
|
+
}
|
|
1696
|
+
const addActionsTool = createAddActionsTool();
|
|
1697
|
+
/** The tools every host mounts: reads, document create/delete and `addActions`. */
|
|
1698
|
+
function reactorTools(options = {}) {
|
|
1699
|
+
return [
|
|
1700
|
+
getDocumentModelsTool,
|
|
1701
|
+
getDocumentModelSchemaTool,
|
|
1702
|
+
getDrivesTool,
|
|
1703
|
+
getDriveTool,
|
|
1704
|
+
getDocumentsTool,
|
|
1705
|
+
getDocumentTool,
|
|
1706
|
+
createDocumentTool,
|
|
1707
|
+
options.allowedActionTypes || options.codegenStatus ? createAddActionsTool(options) : addActionsTool,
|
|
1708
|
+
deleteDocumentTool
|
|
1709
|
+
];
|
|
1710
|
+
}
|
|
1711
|
+
//#endregion
|
|
1712
|
+
export { trimValue as $, documentModelInfoSchema as A, stateSliceSchema as B, actionInputSchema as C, BASE_OPERATIONS as D, ANY_SCOPE as E, modelOperations as F, DRIVE_DOCUMENT_TYPE as G, unknownValueMessage as H, operationSchemaSlice as I, documentName as J, DRIVE_DOCUMENT_TYPES as K, operationSliceSchema as L, documentModelSummarySchema as M, latestSpecification as N, actionOperations as O, modelOperationSchema as P, documentViewSchema as Q, resolveOperation as R, actionFailuresError as S, validateActions as T, DEFAULT_BRANCH as U, suggestNames as V, DEFAULT_TRIM_LIMITS as W, documentSummarySchema as X, documentSummary as Y, documentView as Z, executeActions as _, toReactorToolError as _t, deleteDocumentTool as a, compactDocumentModelSchemaSchema as at, getDocumentModel as b, getDocumentTool as c, defineTool as ct, getDrivesTool as d, toAiSdkTools as dt, JsonPathError as et, reactorTools as f, toMcpTool as ft, deleteDocument as g, notFound as gt, createDocument as h, isReactorToolError as ht, createDocumentTool as i, compactDocumentModelSchema as it, documentModelSummary as j, documentModelInfo as k, getDocumentsTool as l, formatToolError as lt, targetParam as m, ReactorToolError as mt, aliasParam as n, parseJsonPath as nt, getDocumentModelSchemaTool as o, codegenHint as ot, targetId as p, REACTOR_TOOL_ERROR_CODES as pt, MAX_FILTERED_CHARS as q, createAddActionsTool as r, queryJsonPath as rt, getDocumentModelsTool as s, codegenStatusTool as st, addActionsTool as t, applyJsonPath as tt, getDriveTool as u, isWriteTool as ut, executeBuiltActions as v, formatActionFailures as w, getDocumentModelForDocument as x, getDocument as y, stateSchemaSlice as z };
|
|
1713
|
+
|
|
1714
|
+
//# sourceMappingURL=tools-UCPB56U4.mjs.map
|