@powerhousedao/reactor-mcp 6.2.3-dev.79 → 6.2.3-dev.80

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.
@@ -1,743 +0,0 @@
1
- import { DriveCollectionId } from "@powerhousedao/reactor";
2
- import { setAvailableOffline, setDriveIcon, setDriveName, setSharingType } from "@powerhousedao/shared/document-drive";
3
- import { baseActions, createAction, operationOutcome } from "@powerhousedao/shared/document-model";
4
- import { getCodegenStatusRegistry } from "@powerhousedao/shared/processors";
5
- import { camelCase, pascalCase } from "change-case";
6
- import { z } from "zod";
7
- //#region src/tools/compact-schema.ts
8
- const BUILTIN_SCALARS = /* @__PURE__ */ new Set([
9
- "String",
10
- "Int",
11
- "Float",
12
- "Boolean",
13
- "ID"
14
- ]);
15
- function stripComments(source) {
16
- return source.replace(/"""[\s\S]*?"""/g, "").replace(/"[^"\n]*"/g, "").replace(/#[^\n]*/g, "");
17
- }
18
- function collapse(definition) {
19
- return stripComments(definition).replace(/\s+/g, " ").trim();
20
- }
21
- /** Named enum, input, type and union definitions in a GraphQL source. */
22
- function definitionsOf(source) {
23
- const definitions = /* @__PURE__ */ new Map();
24
- 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));
25
- return definitions;
26
- }
27
- function referencedNames(definition) {
28
- const names = /* @__PURE__ */ new Set();
29
- for (const match of definition.matchAll(/:\s*\[?\s*(\w+)/g)) names.add(match[1]);
30
- for (const match of definition.matchAll(/=\s*([\w\s|]+)/g)) for (const name of match[1].split("|")) names.add(name.trim());
31
- return names;
32
- }
33
- /** The parts of a document model's latest specification that writing actions needs. */
34
- function compactDocumentModelSchema(model) {
35
- const spec = model.specifications.at(-1);
36
- const operations = spec?.modules.flatMap((module) => module.operations) ?? [];
37
- const stateDefinitions = definitionsOf(Object.values(spec?.state ?? {}).map((state) => state.schema).join("\n"));
38
- const types = {};
39
- const visit = (definition, local) => {
40
- for (const name of referencedNames(definition)) {
41
- if (BUILTIN_SCALARS.has(name) || local.has(name) || name in types) continue;
42
- const referenced = stateDefinitions.get(name);
43
- if (!referenced) continue;
44
- types[name] = referenced;
45
- visit(referenced, local);
46
- }
47
- };
48
- const actions = operations.flatMap((operation) => {
49
- if (!operation.name) return [];
50
- const input = operation.schema ? collapse(operation.schema) : null;
51
- if (operation.schema) visit(operation.schema, definitionsOf(operation.schema));
52
- return [{
53
- type: operation.name,
54
- scope: operation.scope,
55
- input
56
- }];
57
- });
58
- return {
59
- id: model.id,
60
- name: model.name,
61
- version: spec?.version ?? 1,
62
- actions,
63
- ...Object.keys(types).length ? { types } : {}
64
- };
65
- }
66
- //#endregion
67
- //#region src/tools/utils.ts
68
- var InvalidToolOutputError = class extends Error {
69
- constructor(zodError) {
70
- super("Invalid tool output\n" + zodError.message);
71
- this.name = "InvalidToolOutputError";
72
- this.cause = zodError;
73
- }
74
- };
75
- /**
76
- * Creates a tool with a callback function that handles the tool execution,
77
- * ensuring the output is valid and errors are handled and returned correctly.
78
- * @param tool The tool schema to wrap.
79
- * @param toolCallback The callback function to execute when the tool is called.
80
- * @returns A CallToolResult with structuredContent if OutputSchema is defined or content if undefined. If the
81
- * callback throws an error, the result will have isError set to true and the error message in the content.
82
- */
83
- function toolWithCallback(tool, toolCallback) {
84
- const wrappedCallback = async (args) => {
85
- try {
86
- const result = await toolCallback(args);
87
- return {
88
- content: [{
89
- type: "text",
90
- text: JSON.stringify(result)
91
- }],
92
- structuredContent: result
93
- };
94
- } catch (error) {
95
- return {
96
- isError: true,
97
- content: [{
98
- type: "text",
99
- text: `Error: ${error instanceof Error ? error.message : String(error)}`
100
- }]
101
- };
102
- }
103
- };
104
- return {
105
- ...tool,
106
- callback: wrappedCallback
107
- };
108
- }
109
- function validateDocumentModelAction(documentModelModule, action) {
110
- const errors = [];
111
- const globalState = documentModelModule.documentModel.global;
112
- if (!globalState.specifications || globalState.specifications.length === 0) {
113
- errors.push("Document model has no specifications");
114
- return {
115
- isValid: false,
116
- errors
117
- };
118
- }
119
- const latestSpec = globalState.specifications[globalState.specifications.length - 1];
120
- let operation = null;
121
- for (const module of latestSpec.modules) {
122
- const unsafeOperationOrActionOrSomething = module.operations.find((op) => op.name === action.type);
123
- if (unsafeOperationOrActionOrSomething) {
124
- operation = unsafeOperationOrActionOrSomething;
125
- break;
126
- }
127
- }
128
- if (!operation) {
129
- errors.push(`Operation "${action.type}" is not defined in any module of the document model`);
130
- return {
131
- isValid: false,
132
- errors
133
- };
134
- }
135
- const camelCaseActionType = camelCase(action.type);
136
- const actionCreator = documentModelModule.actions[camelCaseActionType];
137
- if (!actionCreator) {
138
- errors.push(`Action creator "${camelCaseActionType}" for action type "${action.type}" is not defined in documentModelDocumentModelModule.actions`);
139
- return {
140
- isValid: false,
141
- errors
142
- };
143
- }
144
- let inputError = null;
145
- try {
146
- actionCreator(action.input);
147
- } catch (e) {
148
- inputError = e instanceof Error ? e : new Error(JSON.stringify(e));
149
- }
150
- if (inputError) errors.push(`Input validation error: ${inputError.message}`);
151
- if (operation.scope && action.scope !== operation.scope) errors.push(`Action scope "${action.scope}" does not match operation scope "${operation.scope}"`);
152
- return {
153
- isValid: errors.length === 0,
154
- errors
155
- };
156
- }
157
- /** The scope each base action must carry; `null` means any scope of the document. */
158
- const BASE_ACTION_SCOPES = {
159
- SET_NAME: "global",
160
- SET_PREFERRED_EDITOR: "header",
161
- UNDO: null,
162
- REDO: null,
163
- NOOP: null
164
- };
165
- function countInput(input) {
166
- if (typeof input === "number") return input;
167
- if (typeof input === "object" && input !== null && "count" in input && typeof input.count === "number") return input.count;
168
- }
169
- /**
170
- * Builds a document-model base action (SET_NAME, SET_PREFERRED_EDITOR, UNDO,
171
- * REDO, NOOP) with its action creator. Returns `null` for any other type.
172
- */
173
- function createBaseAction(type, input, scope) {
174
- if (!Object.hasOwn(BASE_ACTION_SCOPES, type)) return null;
175
- const expectedScope = BASE_ACTION_SCOPES[type];
176
- if (expectedScope !== null && scope !== expectedScope) return {
177
- action: null,
178
- errors: [`Action scope "${scope}" does not match operation scope "${expectedScope}"`]
179
- };
180
- try {
181
- switch (type) {
182
- case "SET_NAME": return {
183
- action: baseActions.setName(input),
184
- errors: []
185
- };
186
- case "SET_PREFERRED_EDITOR": return {
187
- action: baseActions.setPreferredEditor(input),
188
- errors: []
189
- };
190
- case "UNDO": return {
191
- action: baseActions.undo(countInput(input), scope),
192
- errors: []
193
- };
194
- case "REDO": return {
195
- action: baseActions.redo(countInput(input), scope),
196
- errors: []
197
- };
198
- default: return {
199
- action: baseActions.noop(scope),
200
- errors: []
201
- };
202
- }
203
- } catch (e) {
204
- return {
205
- action: null,
206
- errors: [`Input validation error: ${e instanceof Error ? e.message : JSON.stringify(e)}`]
207
- };
208
- }
209
- }
210
- //#endregion
211
- //#region src/tools/reactor.ts
212
- const DRIVE_DOCUMENT_TYPE = "powerhouse/document-drive";
213
- /** The parameter every tool names its target document or drive by. */
214
- const TARGET = "documentId";
215
- const targetParam = (what) => z.string().optional().describe(`ID or slug of the ${what}. Required.`);
216
- const aliasParam = z.string().optional().describe(`Alias of \`${TARGET}\``);
217
- /** The target named by `documentId` or one of its aliases; they must agree. */
218
- function targetId(tool, params, aliases) {
219
- const given = new Set([TARGET, ...aliases].map((name) => params[name]).filter((id) => typeof id === "string" && id !== ""));
220
- if (given.size > 1) throw new Error(`${tool} got different IDs in \`${TARGET}\` and its aliases (${aliases.map((a) => `\`${a}\``).join(", ")}); pass only \`${TARGET}\``);
221
- const [id] = given;
222
- if (!id) throw new Error(`${tool} needs the target's ID in \`${TARGET}\``);
223
- return id;
224
- }
225
- /** The value `addDrive` got for a field in any of its shapes; they must agree. */
226
- function driveField(field, values) {
227
- const given = new Set(values.filter((value) => value != null && value !== ""));
228
- if (given.size > 1) throw new Error(`addDrive got different values for \`${field}\`; pass it once, at the top level`);
229
- const [value] = given;
230
- return value;
231
- }
232
- function outcomeError(outcome, modelErrors) {
233
- if (!outcome) return {
234
- kind: "not-applied",
235
- message: "The reactor stored no operation for this action"
236
- };
237
- switch (outcome.kind) {
238
- case "applied": return;
239
- case "reducer-error": {
240
- const known = modelErrors(outcome.name, outcome.code, outcome.message);
241
- const name = known?.name ?? outcome.name;
242
- const code = known?.code ?? outcome.code;
243
- return {
244
- kind: outcome.kind,
245
- message: outcome.message,
246
- ...name !== void 0 && { name },
247
- ...code !== void 0 && { code }
248
- };
249
- }
250
- case "denied": return {
251
- kind: outcome.kind,
252
- message: outcome.reason
253
- };
254
- }
255
- }
256
- /** Finds the declared error a reducer error was, by its code, class name or default message. */
257
- function modelErrorFinder(module, actionType) {
258
- const operations = (module.documentModel.global.specifications.at(-1)?.modules ?? []).flatMap((m) => m.operations);
259
- const declared = (errors) => errors.flatMap(({ name, code }) => {
260
- if (!name) return [];
261
- const className = pascalCase(name);
262
- return [{
263
- name: className,
264
- code: code?.trim() || className
265
- }];
266
- });
267
- const candidates = [...declared(operations.find((o) => o.name === actionType)?.errors ?? []), ...declared(operations.flatMap((o) => o.errors))];
268
- 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);
269
- }
270
- /** Waits until a write can be read back. */
271
- async function written(handle) {
272
- return (await handle).readable;
273
- }
274
- /** A job the auth policy refused at admission; such a job writes nothing. */
275
- function isDeniedJob(error) {
276
- return error instanceof Error && error.name === "JobFailedError" && error.job.error?.name === "AuthorizationDeniedError";
277
- }
278
- const createDocumentTool = {
279
- name: "createDocument",
280
- description: `Create a new document.
281
- Unless the user specifies otherwise, and a drive named "vetra" is available, add the document to that drive by providing the drive's ID in the "driveId" parameter.
282
- When "driveId" is provided, the document is created and added to the drive atomically — no separate "addActions" call with "ADD_FILE" is needed.`,
283
- inputSchema: {
284
- documentType: z.string().describe("Type of the document to create"),
285
- name: z.string().optional().describe("Optional name for the document. Used as both the document name and the drive node name when driveId is provided."),
286
- driveId: z.string().optional().describe("Optional drive ID or slug. When provided, the document is created and added to the drive atomically."),
287
- parentFolder: z.string().optional().describe("Optional folder ID within the drive to place the document in. Only used when driveId is provided.")
288
- },
289
- outputSchema: { documentId: z.string().describe("ID of the created document") }
290
- };
291
- const getDocumentTool = {
292
- name: "getDocument",
293
- description: "Retrieve a document or drive by its ID, passed as `documentId`",
294
- inputSchema: {
295
- documentId: targetParam("document to retrieve"),
296
- id: aliasParam
297
- },
298
- outputSchema: { document: z.unknown().describe("The retrieved Document") }
299
- };
300
- const getDocumentsTool = {
301
- name: "getDocuments",
302
- description: "List documents in a drive, passed as `documentId`",
303
- inputSchema: {
304
- documentId: targetParam("drive whose documents to list"),
305
- driveId: aliasParam,
306
- parentId: aliasParam
307
- },
308
- outputSchema: { documentIds: z.array(z.string()).describe("Array of document IDs") }
309
- };
310
- const deleteDocumentTool = {
311
- name: "deleteDocument",
312
- description: "Delete a document, passed as `documentId`",
313
- inputSchema: {
314
- documentId: targetParam("document to delete"),
315
- id: aliasParam
316
- },
317
- outputSchema: { success: z.boolean().describe("Whether the deletion was successful") }
318
- };
319
- const actionErrorSchema = z.object({
320
- kind: z.enum([
321
- "reducer-error",
322
- "denied",
323
- "not-applied"
324
- ]).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"),
325
- message: z.string().describe("Why the action was not applied"),
326
- name: z.string().optional().describe("For a reducer-error: the error class the reducer threw, e.g. BookNotStartedError"),
327
- code: z.string().optional().describe("For a reducer-error: the error's code in the document model, e.g. BOOK_NOT_STARTED")
328
- }).describe("Present when the action was not applied");
329
- const addActionsTool = {
330
- name: "addActions",
331
- description: "Adds actions to a document. Prefer adding multiples actions at once to reduce the number of steps. Besides the document model's operations, accepts the base actions SET_NAME (scope global, input: the name), SET_PREFERRED_EDITOR (scope header, input: { preferredEditor }), UNDO and REDO (input: { count }) and NOOP. Returns one result per action, in input order; `success` is false when any result carries 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: the denied action's error has kind `denied` and the others `not-applied`.",
332
- inputSchema: {
333
- documentId: targetParam("document or drive to change"),
334
- id: aliasParam,
335
- actions: z.array(z.object({
336
- type: z.string().describe("The name of the action"),
337
- input: z.unknown().describe("The payload of the action"),
338
- scope: z.string().describe("The scope of the action"),
339
- context: z.record(z.string(), z.unknown()).optional().describe("Optional action context")
340
- }).strict()).describe("Action to add to the document")
341
- },
342
- outputSchema: {
343
- success: z.boolean().describe("False when any action was not applied"),
344
- results: z.array(z.object({
345
- index: z.number().describe("Position of the action in `actions`"),
346
- type: z.string().describe("The action's type"),
347
- scope: z.string().describe("The action's scope"),
348
- operationIndex: z.number().optional().describe("Index of the operation the action was stored as"),
349
- error: actionErrorSchema.optional()
350
- })).describe("One result per action, in the order they were given"),
351
- codegen: z.string().optional().describe("Present when Vetra generates code from this document: how to follow that generation")
352
- }
353
- };
354
- const codegenStatusSchema = z.object({
355
- documentId: z.string(),
356
- documentType: z.string(),
357
- name: z.string().optional().describe("The module's name"),
358
- state: z.enum([
359
- "queued",
360
- "running",
361
- "waiting-for-install",
362
- "done",
363
- "failed",
364
- "skipped"
365
- ]).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"),
366
- message: z.string().optional().describe("Why it failed or was skipped, or what it waits for"),
367
- files: z.array(z.string()).optional().describe("Project files the job wrote, relative to the project"),
368
- updatedAt: z.string().describe("ISO timestamp of the last change")
369
- });
370
- const getCodegenStatusTool = {
371
- name: "getCodegenStatus",
372
- 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.",
373
- inputSchema: {
374
- documentId: z.string().optional().describe("ID of a Vetra document; omitted, every document's status"),
375
- 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.")
376
- },
377
- outputSchema: {
378
- active: z.boolean().describe("False when no Vetra codegen runs on this reactor"),
379
- settled: z.boolean().describe("True when every listed job is done, failed or skipped"),
380
- documents: z.array(codegenStatusSchema).describe("One status per document, most recently updated first"),
381
- loadFailures: z.array(z.object({
382
- package: z.string(),
383
- kind: z.string().describe("What failed to load, e.g. \"document models\""),
384
- message: z.string(),
385
- updatedAt: z.string()
386
- })).describe("Project modules that failed to load"),
387
- message: z.string().optional()
388
- }
389
- };
390
- const getDrivesTool = {
391
- name: "getDrives",
392
- description: "List all drives",
393
- inputSchema: {},
394
- outputSchema: { driveIds: z.array(z.string()).describe("Array of drive IDs") }
395
- };
396
- const driveName = z.string().optional().describe("Name of the drive");
397
- const driveIcon = z.string().nullable().optional().describe("Optional icon for the drive");
398
- const drivePreferredEditor = z.string().optional().describe("Optional app/editor module id recorded as the drive's preferred editor");
399
- const addDriveTool = {
400
- name: "addDrive",
401
- description: "Create a new drive. Pass `name` and, optionally, `icon` and `preferredEditor` at the top level. The older `driveInput` object is still accepted.",
402
- inputSchema: {
403
- name: z.string().optional().describe("Name of the drive. Required."),
404
- icon: driveIcon,
405
- preferredEditor: drivePreferredEditor,
406
- driveInput: z.object({
407
- name: driveName,
408
- icon: driveIcon,
409
- global: z.object({
410
- name: z.string().describe("Name of the drive"),
411
- icon: driveIcon
412
- }).optional().describe("Global drive properties"),
413
- preferredEditor: drivePreferredEditor,
414
- local: z.object({
415
- availableOffline: z.boolean().optional().describe("Whether drive is available offline"),
416
- sharingType: z.string().nullable().optional().describe("Sharing type")
417
- }).optional().describe("Optional local state properties")
418
- }).optional().describe("Older form of the drive configuration; prefer the top-level fields")
419
- },
420
- outputSchema: { driveId: z.string().describe("ID of the created drive") }
421
- };
422
- const getDriveTool = {
423
- name: "getDrive",
424
- description: "Get a specific drive, passed as `documentId`",
425
- inputSchema: {
426
- documentId: targetParam("drive to retrieve"),
427
- driveId: aliasParam,
428
- id: aliasParam,
429
- options: z.object({
430
- revisions: z.record(z.string(), z.number()).optional().describe("Optional revision filter"),
431
- checkHashes: z.boolean().optional().describe("Whether to check hashes")
432
- }).optional().describe("Optional get document options")
433
- },
434
- outputSchema: { drive: z.unknown().describe("Drive document") }
435
- };
436
- const deleteDriveTool = {
437
- name: "deleteDrive",
438
- description: "Delete a drive, passed as `documentId`",
439
- inputSchema: {
440
- documentId: targetParam("drive to delete"),
441
- driveId: aliasParam,
442
- id: aliasParam
443
- },
444
- outputSchema: { success: z.boolean().describe("Whether the deletion was successful") }
445
- };
446
- const addRemoteDriveTool = {
447
- name: "addRemoteDrive",
448
- description: "Connect to a remote drive",
449
- inputSchema: {
450
- url: z.string().describe("URL of the remote drive"),
451
- options: z.object({
452
- availableOffline: z.boolean().describe("Whether drive is available offline"),
453
- sharingType: z.string().nullable().optional().describe("Sharing type"),
454
- pullFilter: z.object({
455
- branch: z.array(z.string()).nullable().optional().describe("Branch filter"),
456
- documentId: z.array(z.string()).nullable().optional().describe("Document ID filter"),
457
- documentType: z.array(z.string()).nullable().optional().describe("Document type filter"),
458
- scope: z.array(z.string()).nullable().optional().describe("Scope filter")
459
- }).optional().describe("Optional pull filter"),
460
- pullInterval: z.number().optional().describe("Pull interval in milliseconds")
461
- }).describe("Remote drive options")
462
- },
463
- outputSchema: { driveId: z.string().describe("ID of the added remote drive") }
464
- };
465
- const getDocumentModelSchemaTool = {
466
- name: "getDocumentModelSchema",
467
- description: "Get the schema of a document model. Pass `compact: true` before addActions: it returns only each action's type, scope and GraphQL input definition, and the enums and types those inputs use. Omit it for the full model, with state schemas, descriptions, errors and examples.",
468
- inputSchema: {
469
- type: z.string().describe("Type of the document model"),
470
- compact: z.boolean().optional().describe("Return only the actions' types, scopes and input definitions. Defaults to false.")
471
- },
472
- outputSchema: { schema: z.unknown().describe("Schema of the document model") }
473
- };
474
- const getDocumentModelsTool = {
475
- name: "getDocumentModels",
476
- description: "Get the list of document models",
477
- inputSchema: {},
478
- outputSchema: { documentModels: z.array(z.object({
479
- name: z.string().describe("Name of the document model"),
480
- type: z.string().describe("Type of the document model"),
481
- description: z.string().describe("Description of the document model"),
482
- extension: z.string().describe("Extension of the document model"),
483
- authorName: z.string().describe("Author name of the document model"),
484
- authorWebsite: z.string().describe("Author website of the document model")
485
- })).describe("List of available document models") }
486
- };
487
- function createReactorMcpProvider(options) {
488
- const { client, syncManager, subject } = options;
489
- const view = subject ? { subject } : void 0;
490
- const codegen = options.codegenStatus ?? getCodegenStatusRegistry();
491
- /** Marks a Vetra document's codegen queued once a global change is written. */
492
- function codegenHint(document, results) {
493
- const { id, documentType } = document.header;
494
- if (!codegen.active || !codegen.watches(documentType)) return void 0;
495
- if (results.some((result) => result.scope === "global" && result.operationIndex !== void 0)) codegen.set({
496
- documentId: id,
497
- documentType,
498
- state: "queued",
499
- message: "Waiting for Vetra's codegen processor to pick up the change"
500
- });
501
- return `Vetra generates code from this document a few seconds after a change. Call getCodegenStatus with documentId "${id}" and waitSeconds to see when it is done, and why it failed or was skipped.`;
502
- }
503
- function getDocumentModelModule(documentType) {
504
- return client.getDocumentModelModule(documentType);
505
- }
506
- /** Names the denied actions of a refused batch; the others were not written either. */
507
- async function denialErrors(documentId, actions, message) {
508
- const notApplied = {
509
- kind: "not-applied",
510
- message: `The batch was refused, so nothing in it was written: ${message}`
511
- };
512
- try {
513
- const { evaluations } = await client.evaluateActions(documentId, "main", actions.map(({ scope, type, input }) => ({
514
- scope,
515
- type,
516
- input
517
- })));
518
- return evaluations.map((evaluation) => evaluation.decision === "deny" ? {
519
- kind: "denied",
520
- message: evaluation.reason
521
- } : notApplied);
522
- } catch {
523
- return actions.map(() => notApplied);
524
- }
525
- }
526
- /** For clients whose jobs carry no result: reads the operations the write appended. */
527
- async function readOutcomes(documentId, before, actions) {
528
- const ids = new Set(actions.map((action) => action.id));
529
- const outcomes = /* @__PURE__ */ new Map();
530
- for (const scope of new Set(actions.map((action) => action.scope))) {
531
- let paging;
532
- do {
533
- const page = await client.getOperations(documentId, {
534
- ...view,
535
- branch: "main",
536
- scopes: [scope]
537
- }, { sinceRevision: before.header.revision[scope] ?? 0 }, paging);
538
- for (const operation of page.results) if (ids.has(operation.action.id)) outcomes.set(operation.action.id, {
539
- index: operation.index,
540
- ...operationOutcome(operation)
541
- });
542
- paging = page.nextCursor && page.results.length ? {
543
- cursor: page.nextCursor,
544
- limit: page.options.limit
545
- } : void 0;
546
- } while (paging);
547
- }
548
- return outcomes;
549
- }
550
- const tools = {
551
- getDocument: toolWithCallback(getDocumentTool, async (params) => {
552
- const id = targetId("getDocument", params, ["id"]);
553
- const document = await client.get(id, view);
554
- return { document: {
555
- header: document.header,
556
- state: document.state
557
- } };
558
- }),
559
- createDocument: toolWithCallback(createDocumentTool, async (params) => {
560
- if (params.driveId) {
561
- const document = await client.newDocument(params.documentType, {
562
- parentIdentifier: params.driveId,
563
- name: params.name || void 0
564
- });
565
- return { documentId: (await client.drives.addFile(params.driveId, document, params.parentFolder)).header.id };
566
- }
567
- return { documentId: (await written(client.write.createEmpty(params.documentType, {}))).documentId };
568
- }),
569
- getDocuments: toolWithCallback(getDocumentsTool, async (params) => {
570
- const driveId = targetId("getDocuments", params, ["driveId", "parentId"]);
571
- return { documentIds: (await client.getOutgoingRelationships(driveId, "child", view)).results.map((doc) => doc.header.id) };
572
- }),
573
- deleteDocument: toolWithCallback(deleteDocumentTool, async (params) => {
574
- const documentId = targetId("deleteDocument", params, ["id"]);
575
- try {
576
- const driveParent = (await client.getIncomingRelationships(documentId, "child")).results.find((p) => p.header.documentType === DRIVE_DOCUMENT_TYPE);
577
- if (driveParent) await client.drives.removeNode(driveParent.header.id, documentId);
578
- else await written(client.write.deleteDocument(documentId));
579
- return { success: true };
580
- } catch {
581
- return { success: false };
582
- }
583
- }),
584
- addActions: toolWithCallback(addActionsTool, async (params) => {
585
- const documentId = targetId("addActions", params, ["id"]);
586
- const document = await client.get(documentId, view);
587
- const documentModel = await getDocumentModelModule(document.header.documentType);
588
- if (!documentModel) throw new Error(`Document model for document type '${document.header.documentType}' not found`);
589
- const actions = params.actions.map((paramAction) => {
590
- const baseAction = createBaseAction(paramAction.type, paramAction.input, paramAction.scope);
591
- if (baseAction) {
592
- if (!baseAction.action) throw new Error(`Invalid action ${JSON.stringify(paramAction)}: ${baseAction.errors.join(", ")}`);
593
- return baseAction.action;
594
- }
595
- const action = createAction(paramAction.type, paramAction.input ?? {}, void 0, void 0, paramAction.scope);
596
- const actionValidation = validateDocumentModelAction(documentModel, action);
597
- if (!actionValidation.isValid) throw new Error(`Invalid action ${JSON.stringify(action)}: ${actionValidation.errors.join(", ")}`);
598
- return action;
599
- });
600
- const handle = await client.write.execute(documentId, "main", actions);
601
- let results;
602
- try {
603
- const receipt = await handle.readable;
604
- const outcomes = receipt.job.result ? new Map(receipt.job.result.actions.map((a) => [a.actionId, a])) : await readOutcomes(receipt.documentId, document, actions);
605
- results = actions.map((action, index) => {
606
- const outcome = outcomes.get(action.id);
607
- const error = outcomeError(outcome, modelErrorFinder(documentModel, action.type));
608
- return {
609
- index,
610
- type: action.type,
611
- scope: action.scope,
612
- ...outcome && { operationIndex: outcome.index },
613
- ...error && { error }
614
- };
615
- });
616
- } catch (error) {
617
- if (!isDeniedJob(error)) throw error;
618
- const errors = await denialErrors(documentId, actions, error.message);
619
- results = actions.map((action, index) => ({
620
- index,
621
- type: action.type,
622
- scope: action.scope,
623
- error: errors[index]
624
- }));
625
- }
626
- const hint = codegenHint(document, results);
627
- return {
628
- success: results.every((result) => !result.error),
629
- results,
630
- ...hint && { codegen: hint }
631
- };
632
- }),
633
- getDrives: toolWithCallback(getDrivesTool, async () => {
634
- return { driveIds: (await client.find({ type: DRIVE_DOCUMENT_TYPE }, view)).results.map((doc) => doc.header.id) };
635
- }),
636
- addDrive: toolWithCallback(addDriveTool, async (params) => {
637
- const { driveInput } = params;
638
- const name = driveField("name", [
639
- params.name,
640
- driveInput?.name,
641
- driveInput?.global?.name
642
- ]);
643
- if (!name) throw new Error("addDrive needs the drive's `name`");
644
- const icon = driveField("icon", [
645
- params.icon,
646
- driveInput?.icon,
647
- driveInput?.global?.icon
648
- ]);
649
- const preferredEditor = driveField("preferredEditor", [params.preferredEditor, driveInput?.preferredEditor]);
650
- const { documentId: driveId } = await written(client.write.createEmpty(DRIVE_DOCUMENT_TYPE, {}));
651
- if (preferredEditor) await written(client.write.setPreferredEditor(driveId, preferredEditor));
652
- await written(client.write.rename(driveId, name));
653
- const actions = [setDriveName({ name })];
654
- if (icon) actions.push(setDriveIcon({ icon }));
655
- if (driveInput?.local?.sharingType) actions.push(setSharingType({ type: driveInput.local.sharingType }));
656
- if (driveInput?.local?.availableOffline !== void 0) actions.push(setAvailableOffline({ availableOffline: driveInput.local.availableOffline }));
657
- await written(client.write.execute(driveId, "main", actions));
658
- return { driveId };
659
- }),
660
- getDrive: toolWithCallback(getDriveTool, async (params) => {
661
- const driveId = targetId("getDrive", params, ["driveId", "id"]);
662
- const drive = await client.get(driveId, view);
663
- return { drive: {
664
- header: drive.header,
665
- state: drive.state
666
- } };
667
- }),
668
- deleteDrive: toolWithCallback(deleteDriveTool, async (params) => {
669
- const driveId = targetId("deleteDrive", params, ["driveId", "id"]);
670
- try {
671
- await written(client.write.deleteDocument(driveId));
672
- return { success: true };
673
- } catch {
674
- return { success: false };
675
- }
676
- }),
677
- addRemoteDrive: toolWithCallback(addRemoteDriveTool, async (params) => {
678
- if (!syncManager) throw new Error("Remote drive management is not available. SyncManager was not configured for this MCP server.");
679
- const response = await fetch(params.url);
680
- if (!response.ok) throw new Error(`Failed to resolve drive info from ${params.url}`);
681
- const driveInfo = await response.json();
682
- const resolvedDriveId = driveInfo.id;
683
- const collectionId = DriveCollectionId.forDrive(resolvedDriveId);
684
- if (syncManager.list().find((remote) => remote.meta.collectionId.equals(collectionId))) return { driveId: resolvedDriveId };
685
- const remoteName = `mcp-remote-${crypto.randomUUID()}`;
686
- await syncManager.add(remoteName, collectionId, {
687
- type: "gql",
688
- parameters: { url: driveInfo.graphqlEndpoint }
689
- });
690
- return { driveId: resolvedDriveId };
691
- }),
692
- getDocumentModels: toolWithCallback(getDocumentModelsTool, async () => {
693
- return { documentModels: (await client.getDocumentModelModules()).results.map((model) => {
694
- const schemaGlobal = model.documentModel.global;
695
- return {
696
- name: schemaGlobal.name,
697
- type: schemaGlobal.id,
698
- description: schemaGlobal.description,
699
- extension: schemaGlobal.extension,
700
- authorName: schemaGlobal.author.name,
701
- authorWebsite: schemaGlobal.author.website ?? ""
702
- };
703
- }) };
704
- }),
705
- getCodegenStatus: toolWithCallback(getCodegenStatusTool, async (params) => {
706
- if (!codegen.active) return {
707
- active: false,
708
- settled: true,
709
- documents: [],
710
- loadFailures: codegen.loadFailures(),
711
- message: "No Vetra codegen runs on this reactor; `ph vetra` runs it for the project's Vetra drive"
712
- };
713
- let documentId = params.documentId;
714
- if (documentId !== void 0 && !codegen.get(documentId)) try {
715
- documentId = (await client.get(documentId, view)).header.id;
716
- } catch {}
717
- const waitMs = (params.waitSeconds ?? 0) * 1e3;
718
- const settled = waitMs > 0 ? await codegen.waitUntilSettled(documentId, waitMs) : codegen.settled(documentId);
719
- const documents = documentId === void 0 ? codegen.list() : [codegen.get(documentId)].filter((status) => status !== void 0);
720
- return {
721
- active: true,
722
- settled,
723
- documents,
724
- loadFailures: codegen.loadFailures(),
725
- ...documentId !== void 0 && documents.length === 0 && { message: `No codegen recorded for ${params.documentId}. Vetra generates code for documents of type ${codegen.documentTypes.join(", ")} in its drive, once they change.` }
726
- };
727
- }),
728
- getDocumentModelSchema: toolWithCallback(getDocumentModelSchemaTool, async (params) => {
729
- const schema = (await getDocumentModelModule(params.type))?.documentModel.global;
730
- if (!schema) throw new Error(`Document model '${params.type}' not found`);
731
- return { schema: params.compact ? compactDocumentModelSchema(schema) : schema };
732
- })
733
- };
734
- return Promise.resolve({
735
- tools,
736
- resources: {},
737
- prompts: {}
738
- });
739
- }
740
- //#endregion
741
- export { toolWithCallback as _, createReactorMcpProvider as a, getCodegenStatusTool as c, getDocumentTool as d, getDocumentsTool as f, createBaseAction as g, InvalidToolOutputError as h, createDocumentTool as i, getDocumentModelSchemaTool as l, getDrivesTool as m, addDriveTool as n, deleteDocumentTool as o, getDriveTool as p, addRemoteDriveTool as r, deleteDriveTool as s, addActionsTool as t, getDocumentModelsTool as u, validateDocumentModelAction as v, compactDocumentModelSchema as y };
742
-
743
- //# sourceMappingURL=reactor-Cku02YAV.mjs.map