@powerhousedao/reactor-mcp 6.2.3-dev.95 → 6.2.3-dev.97

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 +0,0 @@
1
- {"version":3,"file":"tools-BrIw7TkA.mjs","names":[],"sources":["../src/tools/errors.ts","../src/tools/definition.ts","../src/tools/codegen.ts","../src/tools/compact-schema.ts","../src/tools/jsonpath.ts","../src/tools/documents.ts","../src/tools/suggest.ts","../src/tools/model-operations.ts","../src/tools/schema.ts","../src/tools/validation.ts","../src/tools/operations.ts","../src/tools/reactor.ts"],"sourcesContent":["export const REACTOR_TOOL_ERROR_CODES = [\n \"NOT_FOUND\",\n \"FORBIDDEN\",\n \"INVALID_ACTION\",\n \"REDUCER_ERROR\",\n \"CONFLICT\",\n] as const;\n\nexport type ReactorToolErrorCode = (typeof REACTOR_TOOL_ERROR_CODES)[number];\n\n/** One rejected action: its position in the batch and why. */\nexport type ActionFailure = {\n index: number;\n type: string;\n code: Extract<\n ReactorToolErrorCode,\n \"INVALID_ACTION\" | \"FORBIDDEN\" | \"REDUCER_ERROR\"\n >;\n errors: string[];\n};\n\nexport class ReactorToolError extends Error {\n readonly code: ReactorToolErrorCode;\n readonly failures?: ActionFailure[];\n\n constructor(\n code: ReactorToolErrorCode,\n message: string,\n options: { failures?: ActionFailure[]; cause?: unknown } = {},\n ) {\n super(message, { cause: options.cause });\n this.name = \"ReactorToolError\";\n this.code = code;\n if (options.failures) this.failures = options.failures;\n }\n\n toJSON(): {\n code: ReactorToolErrorCode;\n message: string;\n failures?: ActionFailure[];\n } {\n return {\n code: this.code,\n message: this.message,\n ...(this.failures ? { failures: this.failures } : {}),\n };\n }\n}\n\nexport function isReactorToolError(error: unknown): error is ReactorToolError {\n return (\n error instanceof ReactorToolError ||\n (error instanceof Error &&\n error.name === \"ReactorToolError\" &&\n REACTOR_TOOL_ERROR_CODES.includes(\n (error as { code?: unknown }).code as ReactorToolErrorCode,\n ))\n );\n}\n\n// Reactor and piece-host errors are matched by name: they cross worker\n// boundaries, and `./tools` must not import the reactor at runtime.\nconst NAME_CODES: Partial<Record<string, ReactorToolErrorCode>> = {\n DocumentNotFoundError: \"NOT_FOUND\",\n DocumentPurgedError: \"NOT_FOUND\",\n DocumentDeletedError: \"NOT_FOUND\",\n RelationshipNotFoundError: \"NOT_FOUND\",\n DocumentModelUnavailableError: \"NOT_FOUND\",\n UnsupportedDocumentModelVersionError: \"NOT_FOUND\",\n AuthorizationDeniedError: \"FORBIDDEN\",\n ReactorAccessDeniedError: \"FORBIDDEN\",\n ReservedActionError: \"FORBIDDEN\",\n InvalidSignatureError: \"FORBIDDEN\",\n InvalidActionInputError: \"INVALID_ACTION\",\n InvalidActionInputZodError: \"INVALID_ACTION\",\n ReactorActionsFailedError: \"REDUCER_ERROR\",\n ExcessiveReshuffleError: \"CONFLICT\",\n AuthTimestampNotMonotonicError: \"CONFLICT\",\n UpgradePreconditionFailedError: \"CONFLICT\",\n InvalidOperationTimestampError: \"CONFLICT\",\n};\n\nfunction codeFromMessage(message: string): ReactorToolErrorCode | undefined {\n if (/\\bnot found\\b|does not exist|no such/i.test(message)) return \"NOT_FOUND\";\n if (/\\b(denied|forbidden|not allowed|unauthori[sz]ed)\\b/i.test(message)) {\n return \"FORBIDDEN\";\n }\n if (/\\bconflict/i.test(message)) return \"CONFLICT\";\n return undefined;\n}\n\n/** Normalizes any thrown value to a {@link ReactorToolError}. */\nexport function toReactorToolError(\n error: unknown,\n fallback: ReactorToolErrorCode = \"REDUCER_ERROR\",\n): ReactorToolError {\n if (error instanceof ReactorToolError) return error;\n // One from another realm or bundle copy, rebuilt so it has `toJSON`.\n if (isReactorToolError(error)) {\n const { failures } = error as { failures?: ActionFailure[] };\n return new ReactorToolError(error.code, error.message, {\n failures,\n cause: error,\n });\n }\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : ((JSON.stringify(error) as string | undefined) ?? \"Unknown error\");\n const name = error instanceof Error ? error.name : \"\";\n // A failed job carries the reactor error that failed it.\n const jobErrorName = (\n error as { job?: { error?: { name?: unknown } } } | null\n )?.job?.error?.name;\n const code =\n NAME_CODES[name] ??\n (typeof jobErrorName === \"string\" ? NAME_CODES[jobErrorName] : undefined) ??\n codeFromMessage(message) ??\n fallback;\n return new ReactorToolError(code, message, { cause: error });\n}\n\nexport function notFound(message: string): ReactorToolError {\n return new ReactorToolError(\"NOT_FOUND\", message);\n}\n","import type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport type { z } from \"zod\";\nimport type { ReactorToolClient } from \"./client.js\";\nimport { ReactorToolError, toReactorToolError } from \"./errors.js\";\n\n/** MCP tool annotations; structural, so no MCP SDK import is needed. */\nexport type ReactorToolAnnotations = {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n};\n\nexport type ToolContext<C = ReactorToolClient> = {\n client: C;\n signal?: AbortSignal;\n};\n\n// A transport-neutral tool: `execute` returns data matching `outputSchema`\n// or throws a ReactorToolError.\nexport type ToolDefinition<\n I extends z.ZodObject = z.ZodObject,\n O extends z.ZodObject = z.ZodObject,\n C = ReactorToolClient,\n N extends string = string,\n> = {\n name: N;\n title: string;\n description: string;\n inputSchema: I;\n outputSchema: O;\n annotations: ReactorToolAnnotations;\n execute: (args: z.infer<I>, ctx: ToolContext<C>) => Promise<z.infer<O>>;\n};\n\n// Erases the schema parameters so heterogeneous definitions share one list.\nexport type AnyToolDefinition<C = ReactorToolClient> = {\n name: string;\n title: string;\n description: string;\n inputSchema: z.ZodObject;\n outputSchema: z.ZodObject;\n annotations: ReactorToolAnnotations;\n execute: (args: never, ctx: ToolContext<C>) => Promise<unknown>;\n};\n\nexport function defineTool<\n I extends z.ZodObject,\n O extends z.ZodObject,\n N extends string,\n C = ReactorToolClient,\n>(definition: ToolDefinition<I, O, C, N>): ToolDefinition<I, O, C, N> {\n return definition;\n}\n\n/** Whether running the tool can change state; unannotated tools count as writes. */\nexport function isWriteTool(annotations?: ReactorToolAnnotations): boolean {\n return annotations?.readOnlyHint !== true;\n}\n\n/** Text of an error as the MCP and `ai` adapters report it. */\nexport function formatToolError(error: ReactorToolError): string {\n return `${error.code}: ${error.message}`;\n}\n\nexport type McpToolRecord<D extends AnyToolDefinition<never>> = {\n name: D[\"name\"];\n title: string;\n description: string;\n inputSchema: D[\"inputSchema\"][\"shape\"];\n outputSchema: D[\"outputSchema\"][\"shape\"];\n annotations: ReactorToolAnnotations;\n callback: (\n args: z.infer<D[\"inputSchema\"]>,\n extra?: { signal?: AbortSignal },\n ) => Promise<CallToolResult>;\n};\n\ntype Execute<C> = (args: unknown, ctx: ToolContext<C>) => Promise<unknown>;\n\n/** Wraps a definition for `McpServer.registerTool`; errors become `isError` results. */\nexport function toMcpTool<D extends AnyToolDefinition<C>, C>(\n definition: D,\n ctx: ToolContext<C>,\n): McpToolRecord<D> {\n const execute = definition.execute as Execute<C>;\n return {\n name: definition.name,\n title: definition.title,\n description: definition.description,\n inputSchema: definition.inputSchema.shape,\n outputSchema: definition.outputSchema.shape,\n annotations: { title: definition.title, ...definition.annotations },\n callback: async (args, extra) => {\n try {\n const result = (await execute(args, {\n ...ctx,\n signal: extra?.signal ?? ctx.signal,\n })) as Record<string, unknown>;\n return {\n content: [{ type: \"text\", text: JSON.stringify(result) }],\n structuredContent: result,\n };\n } catch (error) {\n const toolError = toReactorToolError(error);\n return {\n isError: true,\n content: [\n { type: \"text\", text: `Error: ${formatToolError(toolError)}` },\n ],\n _meta: { error: toolError.toJSON() },\n };\n }\n },\n };\n}\n\n/** Structurally an `ai` SDK `Tool`; zod schemas are accepted as-is. */\nexport type AiSdkTool<D extends AnyToolDefinition<never>> = {\n title: string;\n description: string;\n inputSchema: D[\"inputSchema\"];\n outputSchema: D[\"outputSchema\"];\n execute: (\n args: z.infer<D[\"inputSchema\"]>,\n options?: { abortSignal?: AbortSignal },\n ) => Promise<z.infer<D[\"outputSchema\"]>>;\n};\n\nexport type AiSdkToolSet<D extends AnyToolDefinition<never>> = {\n [K in D[\"name\"]]: AiSdkTool<Extract<D, { name: K }>>;\n};\n\n/** Builds an `ai` SDK ToolSet without importing `ai`; failures throw with the code in the message. */\nexport function toAiSdkTools<D extends AnyToolDefinition<C>, C>(\n definitions: readonly D[],\n ctx: ToolContext<C>,\n): AiSdkToolSet<D> {\n const tools: Record<string, AiSdkTool<D>> = {};\n for (const definition of definitions) {\n const execute = definition.execute as Execute<C>;\n tools[definition.name] = {\n title: definition.title,\n description: definition.description,\n inputSchema: definition.inputSchema,\n outputSchema: definition.outputSchema,\n execute: async (args, options) => {\n try {\n return (await execute(args, {\n ...ctx,\n signal: options?.abortSignal ?? ctx.signal,\n })) as z.infer<D[\"outputSchema\"]>;\n } catch (error) {\n const toolError = toReactorToolError(error);\n throw new ReactorToolError(\n toolError.code,\n formatToolError(toolError),\n { failures: toolError.failures, cause: error },\n );\n }\n },\n };\n }\n return tools as AiSdkToolSet<D>;\n}\n","import type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport type { CodegenStatusRegistry } from \"@powerhousedao/shared/processors\";\nimport { z } from \"zod\";\nimport type { ReactorToolReadClient } from \"./client.js\";\nimport { defineTool } from \"./definition.js\";\nimport type { ActionResult } from \"./operations.js\";\n\n/** Marks a Vetra document's codegen queued once a global change is stored, and says how to follow it. */\nexport async function codegenHint(\n codegen: CodegenStatusRegistry,\n client: ReactorToolReadClient,\n executed: { documentId: string; results: readonly ActionResult[] },\n signal?: AbortSignal,\n): Promise<string | undefined> {\n if (!codegen.active) return undefined;\n const { documentId } = executed;\n let documentType: string;\n try {\n const document = await client.get<PHDocument>(\n documentId,\n undefined,\n signal,\n );\n documentType = document.header.documentType;\n } catch {\n return undefined;\n }\n if (!codegen.watches(documentType)) return undefined;\n const written = executed.results.some(\n (result) =>\n result.scope === \"global\" && result.operationIndex !== undefined,\n );\n if (written) {\n codegen.set({\n documentId,\n documentType,\n state: \"queued\",\n message: \"Waiting for Vetra's codegen processor to pick up the change\",\n });\n }\n 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.`;\n}\n\nconst codegenStatusSchema = z.object({\n documentId: z.string(),\n documentType: z.string(),\n name: z.string().optional().describe(\"The module's name\"),\n state: z\n .enum([\n \"queued\",\n \"running\",\n \"waiting-for-install\",\n \"done\",\n \"failed\",\n \"skipped\",\n ])\n .describe(\n \"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\",\n ),\n message: z\n .string()\n .optional()\n .describe(\"Why it failed or was skipped, or what it waits for\"),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Project files the job wrote, relative to the project\"),\n updatedAt: z.string().describe(\"ISO timestamp of the last change\"),\n});\n\n/** Vetra's code generation status, for hosts that run its codegen processor. */\nexport function codegenStatusTool(codegen: CodegenStatusRegistry) {\n return defineTool({\n name: \"getCodegenStatus\",\n title: \"Read Vetra's code generation status\",\n description:\n \"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.\",\n inputSchema: z.object({\n documentId: z\n .string()\n .optional()\n .describe(\"ID of a Vetra document; omitted, every document's status\"),\n waitSeconds: z\n .number()\n .min(0)\n .max(60)\n .optional()\n .describe(\n \"Wait up to this many seconds for the job, or every job without `documentId`, to be done, failed or skipped. Defaults to 0.\",\n ),\n }),\n outputSchema: z.object({\n active: z\n .boolean()\n .describe(\"False when no Vetra codegen runs on this reactor\"),\n settled: z\n .boolean()\n .describe(\"True when every listed job is done, failed or skipped\"),\n documents: z\n .array(codegenStatusSchema)\n .describe(\"One status per document, most recently updated first\"),\n loadFailures: z\n .array(\n z.object({\n package: z.string(),\n kind: z\n .string()\n .describe('What failed to load, e.g. \"document models\"'),\n message: z.string(),\n updatedAt: z.string(),\n }),\n )\n .describe(\"Project modules that failed to load\"),\n message: z.string().optional(),\n }),\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n async execute(args, { client, signal }) {\n if (!codegen.active) {\n return {\n active: false,\n settled: true,\n documents: [],\n loadFailures: codegen.loadFailures(),\n message:\n \"No Vetra codegen runs on this reactor; `ph vetra` runs it for the project's Vetra drive\",\n };\n }\n let documentId = args.documentId;\n if (documentId !== undefined && !codegen.get(documentId)) {\n // A slug names the document as well as its ID.\n try {\n const document = await client.get<PHDocument>(\n documentId,\n undefined,\n signal,\n );\n documentId = document.header.id;\n } catch {\n // Reported below as a document without a status.\n }\n }\n const waitMs = (args.waitSeconds ?? 0) * 1000;\n const settled =\n waitMs > 0\n ? await codegen.waitUntilSettled(documentId, waitMs)\n : codegen.settled(documentId);\n const documents =\n documentId === undefined\n ? codegen.list()\n : [codegen.get(documentId)].filter((status) => status !== undefined);\n return {\n active: true,\n settled,\n documents,\n loadFailures: codegen.loadFailures(),\n ...(documentId !== undefined &&\n documents.length === 0 && {\n message: `No codegen recorded for ${args.documentId}. Vetra generates code for documents of type ${codegen.documentTypes.join(\", \")} in its drive, once they change.`,\n }),\n };\n },\n });\n}\n","import type { DocumentModelGlobalState } from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\n\nexport const compactDocumentModelSchemaSchema = z.object({\n id: z.string(),\n name: z.string(),\n version: z.number(),\n actions: z\n .array(\n z.object({\n type: z.string(),\n scope: z.string(),\n input: z\n .string()\n .nullable()\n .describe(\"The input's GraphQL definition; null without input\"),\n }),\n )\n .describe(\"What addActions takes as type, scope and input\"),\n types: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Enums and types the inputs reference from the state schemas\"),\n});\n\nexport type CompactDocumentModelSchema = z.infer<\n typeof compactDocumentModelSchemaSchema\n>;\n\nconst BUILTIN_SCALARS = new Set([\"String\", \"Int\", \"Float\", \"Boolean\", \"ID\"]);\n\nfunction stripComments(source: string) {\n return source\n .replace(/\"\"\"[\\s\\S]*?\"\"\"/g, \"\")\n .replace(/\"[^\"\\n]*\"/g, \"\")\n .replace(/#[^\\n]*/g, \"\");\n}\n\nfunction collapse(definition: string) {\n return stripComments(definition).replace(/\\s+/g, \" \").trim();\n}\n\n/** Named enum, input, type and union definitions in a GraphQL source. */\nfunction definitionsOf(source: string) {\n const definitions = new Map<string, string>();\n const pattern =\n /\\b(?:enum|input|type)\\s+(\\w+)[^{]*\\{[^}]*\\}|\\bunion\\s+(\\w+)\\s*=\\s*\\|?\\s*\\w+(?:\\s*\\|\\s*\\w+)*/g;\n for (const [definition, name, unionName] of stripComments(source).matchAll(\n pattern,\n )) {\n // An unmatched group is undefined at runtime, whatever its type says.\n definitions.set(name || unionName, collapse(definition));\n }\n return definitions;\n}\n\nfunction referencedNames(definition: string) {\n const names = new Set<string>();\n for (const match of definition.matchAll(/:\\s*\\[?\\s*(\\w+)/g)) {\n names.add(match[1]);\n }\n for (const match of definition.matchAll(/=\\s*([\\w\\s|]+)/g)) {\n for (const name of match[1].split(\"|\")) names.add(name.trim());\n }\n return names;\n}\n\n/** The parts of a document model's latest specification that writing actions needs. */\nexport function compactDocumentModelSchema(\n model: DocumentModelGlobalState,\n): CompactDocumentModelSchema {\n const spec = model.specifications.at(-1);\n const operations = spec?.modules.flatMap((module) => module.operations) ?? [];\n const stateDefinitions = definitionsOf(\n Object.values(spec?.state ?? {})\n .map((state) => state.schema)\n .join(\"\\n\"),\n );\n\n const types: Record<string, string> = {};\n const visit = (definition: string, local: Map<string, string>) => {\n for (const name of referencedNames(definition)) {\n if (BUILTIN_SCALARS.has(name) || local.has(name) || name in types) {\n continue;\n }\n const referenced = stateDefinitions.get(name);\n if (!referenced) continue;\n types[name] = referenced;\n visit(referenced, local);\n }\n };\n\n const actions = operations.flatMap((operation) => {\n if (!operation.name) return [];\n const input = operation.schema ? collapse(operation.schema) : null;\n if (operation.schema)\n visit(operation.schema, definitionsOf(operation.schema));\n return [{ type: operation.name, scope: operation.scope, input }];\n });\n\n return {\n id: model.id,\n name: model.name,\n version: spec?.version ?? 1,\n actions,\n ...(Object.keys(types).length ? { types } : {}),\n };\n}\n","// A JSONPath subset: `$`, `.name`, `['name']`, `[n]` (negative counts from the\n// end), `[(@.length-n)]`, `[*]`/`.*`, `..name`, `[a,b]` and `[?(@.path op value)]`.\n\ntype Segment =\n | { kind: \"child\"; keys: (string | number)[] }\n | { kind: \"wildcard\" }\n | { kind: \"descend\"; key: string }\n | { kind: \"recurse\" }\n | { kind: \"filter\"; path: string[]; op?: Comparison; value?: unknown };\n\ntype Comparison = \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\";\n\nexport class JsonPathError extends Error {\n constructor(path: string, reason: string) {\n super(`Invalid JSONPath \"${path}\": ${reason}`);\n this.name = \"JsonPathError\";\n }\n}\n\nconst NAME = /^[A-Za-z_$][\\w$-]*/;\n\nfunction parseLiteral(text: string, path: string): unknown {\n const t = text.trim();\n if (/^'.*'$/s.test(t)) return t.slice(1, -1).replace(/\\\\'/g, \"'\");\n if (/^\".*\"$/s.test(t)) return JSON.parse(t) as unknown;\n if (t === \"true\") return true;\n if (t === \"false\") return false;\n if (t === \"null\") return null;\n if (t !== \"\" && !Number.isNaN(Number(t))) return Number(t);\n throw new JsonPathError(path, `unsupported literal ${t}`);\n}\n\nfunction parseFilter(body: string, path: string): Segment {\n const match =\n /^@((?:\\.[A-Za-z_$][\\w$-]*)*)\\s*(?:(==|!=|<=|>=|<|>)\\s*(.+))?$/s.exec(\n body.trim(),\n );\n if (!match) throw new JsonPathError(path, `unsupported filter ${body}`);\n const keys = match[1] ? match[1].slice(1).split(\".\") : [];\n if (!match[2]) return { kind: \"filter\", path: keys };\n return {\n kind: \"filter\",\n path: keys,\n op: match[2] as Comparison,\n value: parseLiteral(match[3], path),\n };\n}\n\n// Splits on commas outside quotes.\nfunction splitUnion(body: string): string[] {\n const parts: string[] = [];\n let quote: string | undefined;\n let current = \"\";\n for (const char of body) {\n if (quote) {\n if (char === quote) quote = undefined;\n } else if (char === \"'\" || char === '\"') {\n quote = char;\n } else if (char === \",\") {\n parts.push(current);\n current = \"\";\n continue;\n }\n current += char;\n }\n parts.push(current);\n return parts;\n}\n\nfunction parseBracket(body: string, path: string): Segment {\n const t = body.trim();\n if (t === \"*\") return { kind: \"wildcard\" };\n if (t.startsWith(\"?(\") && t.endsWith(\")\")) {\n return parseFilter(t.slice(2, -1), path);\n }\n const length = /^\\(\\s*@\\.length\\s*-\\s*(\\d+)\\s*\\)$/.exec(t);\n if (length) return { kind: \"child\", keys: [-Number(length[1])] };\n const keys = splitUnion(t).map((part) => {\n const p = part.trim();\n if (/^-?\\d+$/.test(p)) return Number(p);\n const literal = parseLiteral(p, path);\n if (typeof literal !== \"string\") {\n throw new JsonPathError(path, `unsupported selector ${p}`);\n }\n return literal;\n });\n return { kind: \"child\", keys };\n}\n\n// Index of the bracket closing the one at `start`, skipping quoted text.\nfunction closingBracket(path: string, start: number): number {\n let depth = 0;\n let quote: string | undefined;\n for (let i = start; i < path.length; i++) {\n const char = path[i];\n if (quote) {\n if (char === quote && path[i - 1] !== \"\\\\\") quote = undefined;\n } else if (char === \"'\" || char === '\"') {\n quote = char;\n } else if (char === \"[\") {\n depth++;\n } else if (char === \"]\") {\n depth--;\n if (depth === 0) return i;\n }\n }\n throw new JsonPathError(path, \"unclosed [\");\n}\n\nexport function parseJsonPath(path: string): Segment[] {\n const text = path.trim();\n if (!text.startsWith(\"$\")) throw new JsonPathError(path, \"must start with $\");\n const segments: Segment[] = [];\n let i = 1;\n while (i < text.length) {\n const rest = text.slice(i);\n if (rest.startsWith(\"..\")) {\n i += 2;\n if (text[i] === \"*\") {\n segments.push({ kind: \"descend\", key: \"*\" });\n i++;\n continue;\n }\n if (text[i] === \"[\") {\n segments.push({ kind: \"recurse\" });\n continue;\n }\n const name = NAME.exec(text.slice(i));\n if (!name) throw new JsonPathError(path, `expected a name at ${i}`);\n segments.push({ kind: \"descend\", key: name[0] });\n i += name[0].length;\n } else if (rest.startsWith(\".\")) {\n i++;\n if (text[i] === \"*\") {\n segments.push({ kind: \"wildcard\" });\n i++;\n continue;\n }\n const name = NAME.exec(text.slice(i));\n if (!name) throw new JsonPathError(path, `expected a name at ${i}`);\n segments.push({ kind: \"child\", keys: [name[0]] });\n i += name[0].length;\n } else if (rest.startsWith(\"[\")) {\n const end = closingBracket(text, i);\n segments.push(parseBracket(text.slice(i + 1, end), path));\n i = end + 1;\n } else {\n throw new JsonPathError(path, `unexpected \"${text[i]}\" at ${i}`);\n }\n }\n return segments;\n}\n\nfunction children(value: unknown): unknown[] {\n if (Array.isArray(value)) return value;\n if (value !== null && typeof value === \"object\") return Object.values(value);\n return [];\n}\n\nfunction child(value: unknown, key: string | number): unknown[] {\n if (Array.isArray(value)) {\n if (typeof key === \"number\") {\n const index = key < 0 ? value.length + key : key;\n return index >= 0 && index < value.length ? [value[index]] : [];\n }\n return key === \"length\" ? [value.length] : [];\n }\n if (value !== null && typeof value === \"object\") {\n const record = value as Record<string, unknown>;\n const name = String(key);\n return Object.hasOwn(record, name) ? [record[name]] : [];\n }\n return [];\n}\n\nfunction descendants(value: unknown): unknown[] {\n const out: unknown[] = [value];\n for (const next of children(value)) out.push(...descendants(next));\n return out;\n}\n\nfunction compare(left: unknown, op: Comparison, right: unknown): boolean {\n switch (op) {\n case \"==\":\n return left === right;\n case \"!=\":\n return left !== right;\n default: {\n if (typeof left !== typeof right) return false;\n if (typeof left !== \"number\" && typeof left !== \"string\") return false;\n const l = left as number | string;\n const r = right as number | string;\n if (op === \"<\") return l < r;\n if (op === \"<=\") return l <= r;\n if (op === \">\") return l > r;\n return l >= r;\n }\n }\n}\n\nfunction matchesFilter(\n item: unknown,\n segment: Extract<Segment, { kind: \"filter\" }>,\n): boolean {\n let current: unknown[] = [item];\n for (const key of segment.path)\n current = current.flatMap((v) => child(v, key));\n if (current.length === 0) return false;\n if (!segment.op) return Boolean(current[0]);\n return compare(current[0], segment.op, segment.value);\n}\n\n/** Every node `path` selects in `value`, in document order. */\nexport function queryJsonPath(value: unknown, path: string): unknown[] {\n let nodes: unknown[] = [value];\n for (const segment of parseJsonPath(path)) {\n switch (segment.kind) {\n case \"child\":\n nodes = nodes.flatMap((n) => segment.keys.flatMap((k) => child(n, k)));\n break;\n case \"wildcard\":\n nodes = nodes.flatMap(children);\n break;\n case \"descend\":\n nodes = nodes\n .flatMap(descendants)\n .flatMap((n) =>\n segment.key === \"*\" ? children(n) : child(n, segment.key),\n );\n break;\n case \"recurse\":\n nodes = nodes.flatMap(descendants);\n break;\n case \"filter\":\n nodes = nodes.flatMap((n) =>\n children(n).filter((item) => matchesFilter(item, segment)),\n );\n break;\n }\n }\n return nodes;\n}\n\n/** The match of `path`: undefined for none, the value for one, an array for many. */\n// Paths that can match many nodes always return an array.\nfunction isDefinite(path: string): boolean {\n return parseJsonPath(path).every(\n (segment) => segment.kind === \"child\" && segment.keys.length === 1,\n );\n}\n\nexport function applyJsonPath<T = unknown>(value: unknown, path: string): T {\n const results = queryJsonPath(value, path);\n if (!isDefinite(path)) return results as T;\n return results[0] as T;\n}\n","import type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\nimport { applyJsonPath, JsonPathError } from \"./jsonpath.js\";\nimport { ReactorToolError } from \"./errors.js\";\n\nexport const DRIVE_DOCUMENT_TYPE = \"powerhouse/document-drive\";\n/** Document types that hold files, as the reactor's drive containers. */\nexport const DRIVE_DOCUMENT_TYPES: ReadonlySet<string> = new Set([\n DRIVE_DOCUMENT_TYPE,\n \"powerhouse/reactor-drive\",\n]);\nexport const DEFAULT_BRANCH = \"main\";\n\nexport type TrimLimits = {\n maxArrayItems: number;\n maxStringLength: number;\n maxDepth: number;\n};\n\nexport const DEFAULT_TRIM_LIMITS: TrimLimits = {\n maxArrayItems: 25,\n maxStringLength: 2000,\n maxDepth: 8,\n};\n\n/** Caps arrays, strings and depth, leaving a marker where it cut. */\nexport function trimValue(\n value: unknown,\n limits: Partial<TrimLimits> = {},\n): { value: unknown; truncated: boolean } {\n const l = { ...DEFAULT_TRIM_LIMITS, ...limits };\n let truncated = false;\n const walk = (v: unknown, depth: number): unknown => {\n if (typeof v === \"string\") {\n if (v.length <= l.maxStringLength) return v;\n truncated = true;\n return `${v.slice(0, l.maxStringLength)}…[+${v.length - l.maxStringLength} chars]`;\n }\n if (v === null || typeof v !== \"object\") return v;\n if (Object.keys(v).length === 0) return v;\n if (depth >= l.maxDepth) {\n truncated = true;\n return Array.isArray(v)\n ? `[array of ${v.length}]`\n : `[object with keys: ${Object.keys(v).join(\", \")}]`;\n }\n if (Array.isArray(v)) {\n const items = v.slice(0, l.maxArrayItems).map((i) => walk(i, depth + 1));\n if (v.length > l.maxArrayItems) {\n truncated = true;\n items.push(`…${v.length - l.maxArrayItems} more items`);\n }\n return items;\n }\n return Object.fromEntries(\n Object.entries(v).map(([k, child]) => [k, walk(child, depth + 1)]),\n );\n };\n return { value: walk(value, 0), truncated };\n}\n\nexport const documentSummarySchema = z.object({\n id: z.string(),\n documentType: z.string(),\n name: z.string(),\n});\n\nexport type DocumentSummary = z.infer<typeof documentSummarySchema>;\n\nfunction globalState(document: PHDocument): Record<string, unknown> {\n const global = (document.state as { global?: unknown }).global;\n return global && typeof global === \"object\"\n ? (global as Record<string, unknown>)\n : {};\n}\n\n// Models usually keep the display name in state; the header name can lag.\nexport function documentName(document: PHDocument): string {\n const name = globalState(document).name;\n return document.header.name || (typeof name === \"string\" ? name : \"\");\n}\n\nexport function documentSummary(document: PHDocument): DocumentSummary {\n return {\n id: document.header.id,\n documentType: document.header.documentType,\n name: documentName(document),\n };\n}\n\nexport const documentViewSchema = documentSummarySchema.extend({\n slug: z.string().optional(),\n branch: z.string(),\n revision: z.record(z.string(), z.number()),\n lastModifiedAtUtcIso: z.string().optional(),\n state: z\n .unknown()\n .describe(\"The model scopes, or the filter's match when one was given\"),\n truncated: z\n .boolean()\n .optional()\n .describe(\n \"True when long arrays or strings were cut; a filter reads the part it selects in full\",\n ),\n});\n\nexport type DocumentView = z.infer<typeof documentViewSchema>;\n\nexport type DocumentViewOptions = {\n /** JSONPath against the whole state, e.g. `$.global.items[0]`. */\n filter?: string;\n /** Scopes shown without a filter; empty scopes are left out. */\n scopes?: readonly string[];\n limits?: Partial<TrimLimits>;\n};\n\n/** A filter's match is returned whole up to this many JSON characters. */\nexport const MAX_FILTERED_CHARS = 100_000;\n\nfunction jsonLength(value: unknown): number {\n try {\n return (JSON.stringify(value) as string | undefined)?.length ?? 0;\n } catch {\n return Infinity;\n }\n}\n\nfunction isEmpty(value: unknown): boolean {\n return (\n value === undefined ||\n (value !== null &&\n typeof value === \"object\" &&\n Object.keys(value).length === 0)\n );\n}\n\n/** A compact document: header essentials plus model state, projected and trimmed. */\nexport function documentView(\n document: PHDocument,\n options: DocumentViewOptions = {},\n): DocumentView {\n const { filter, scopes = [\"global\", \"local\"], limits } = options;\n const state = document.state as Record<string, unknown>;\n let selected: unknown;\n if (filter) {\n try {\n selected = applyJsonPath(state, filter);\n } catch (error) {\n if (error instanceof JsonPathError) {\n throw new ReactorToolError(\"INVALID_ACTION\", error.message);\n }\n throw error;\n }\n } else {\n selected = Object.fromEntries(\n scopes\n .filter((scope) => !isEmpty(state[scope]))\n .map((scope) => [scope, state[scope]]),\n );\n }\n // A filter reads its part in full; only an oversized match is cut.\n const trimmed =\n filter && jsonLength(selected) <= MAX_FILTERED_CHARS\n ? { value: selected, truncated: false }\n : trimValue(selected, limits);\n const header = document.header;\n return {\n ...documentSummary(document),\n ...(header.slug ? { slug: header.slug } : {}),\n branch: header.branch || DEFAULT_BRANCH,\n revision: { ...header.revision },\n ...(header.lastModifiedAtUtcIso\n ? { lastModifiedAtUtcIso: header.lastModifiedAtUtcIso }\n : {}),\n state: trimmed.value,\n ...(trimmed.truncated ? { truncated: true } : {}),\n };\n}\n","// \"Did you mean\" ranking against a known set of names.\n\nfunction isSubsequence(needle: string, haystack: string): boolean {\n let i = 0;\n for (let j = 0; j < haystack.length && i < needle.length; j++) {\n if (needle[i] === haystack[j]) i++;\n }\n return i === needle.length;\n}\n\nfunction editDistance(a: string, b: string): number {\n if (a === b) return 0;\n if (a.length === 0) return b.length;\n if (b.length === 0) return a.length;\n let prev = Array.from({ length: b.length + 1 }, (_, j) => j);\n let curr = new Array<number>(b.length + 1);\n for (let i = 1; i <= a.length; i++) {\n curr[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);\n }\n [prev, curr] = [curr, prev];\n }\n return prev[b.length];\n}\n\n/** Closest `candidates` to `query`: containment first, then edit distance. */\nexport function suggestNames(\n query: string,\n candidates: readonly string[],\n max = 3,\n): string[] {\n const q = query.toUpperCase();\n const scored = candidates.map((name) => {\n const u = name.toUpperCase();\n if (u.includes(q) || q.includes(u)) return { name, d: 0, strong: true };\n const subsequence =\n u.length >= q.length ? isSubsequence(q, u) : isSubsequence(u, q);\n if (subsequence) {\n return { name, d: Math.abs(u.length - q.length), strong: true };\n }\n return { name, d: editDistance(q, u), strong: false };\n });\n const threshold = Math.max(3, Math.ceil(q.length * 0.6) + 3);\n return scored\n .filter((s) => s.strong || s.d <= threshold)\n .sort((a, b) => a.d - b.d || a.name.localeCompare(b.name))\n .slice(0, max)\n .map((s) => s.name);\n}\n\n/** `Unknown <subject> \"<value>\".` plus a did-you-mean line and, when short, the known names. */\nexport function unknownValueMessage(\n subject: string,\n value: string,\n candidates: readonly string[],\n options: { knownLabel?: string; inlineLimit?: number; context?: string } = {},\n): string {\n const { knownLabel, inlineLimit = 20, context } = options;\n const lines = [\n `Unknown ${subject} \"${value}\"${context ? ` ${context}` : \"\"}.`,\n ];\n const suggestions = suggestNames(value, candidates);\n if (suggestions.length > 0)\n lines.push(`Did you mean: ${suggestions.join(\", \")}?`);\n if (knownLabel && candidates.length > 0 && candidates.length <= inlineLimit) {\n lines.push(`${knownLabel}: ${candidates.join(\", \")}`);\n }\n return lines.join(\"\\n\");\n}\n","import type {\n DocumentModelDefinition,\n DocumentModelModule,\n DocumentModelSpecificationDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n childLogger,\n inspectDocumentModelDefinition,\n type DocumentModelDefinitionInspection,\n} from \"document-model\";\n\nconst logger = childLogger([\"reactor-mcp\", \"model-operations\"]);\n\ntype ModelSource = {\n readonly documentModel: Pick<DocumentModelModule[\"documentModel\"], \"global\">;\n readonly definition?: unknown;\n};\n\nexport type StructuredOperation = {\n readonly storedName: string;\n readonly creatorKey: string;\n};\n\nconst logged = new Set<string>();\n\nfunction inspect(module: ModelSource): DocumentModelDefinitionInspection {\n const inspection = inspectDocumentModelDefinition(module);\n if (\"diagnostics\" in inspection) {\n const documentType = module.documentModel.global.id;\n const key = `${documentType}\\n${inspection.reason}`;\n if (!logged.has(key)) {\n logged.add(key);\n logger.warn(\n \"Serving @type from its stored model; its definition is @reason: @diagnostics\",\n documentType,\n inspection.reason,\n inspection.diagnostics.map((d) => d.message).join(\"; \"),\n );\n }\n }\n return inspection;\n}\n\nexport function structuredDefinition(\n module: ModelSource,\n): DocumentModelDefinition | null {\n const inspection = inspect(module);\n return inspection.kind === \"structured\" ? inspection.definition : null;\n}\n\n// An inspected specification is a snapshot nothing mutates, so its index is\n// built once.\nconst indexes = new WeakMap<\n DocumentModelSpecificationDefinition,\n ReadonlyMap<string, StructuredOperation>\n>();\n\nconst NONE: ReadonlyMap<string, StructuredOperation> = new Map();\n\n/**\n * The operations of a model authored in code, keyed by action type; empty for\n * a model served from its stored specification. Callers consult it only for a\n * type that names no stored operation, so every stored name keeps main's\n * meaning.\n */\nexport function operationsByActionType(\n module: ModelSource,\n): ReadonlyMap<string, StructuredOperation> {\n const inspection = inspect(module);\n if (inspection.kind !== \"structured\") return NONE;\n const { specification } = inspection;\n let byActionType = indexes.get(specification);\n if (byActionType === undefined) {\n byActionType = new Map(\n specification.modules\n .flatMap((m) => m.operations)\n .map((operation) => [\n operation.actionType,\n {\n storedName: operation.name ?? operation.actionType,\n creatorKey: operation.creatorKey,\n },\n ]),\n );\n indexes.set(specification, byActionType);\n }\n return byActionType;\n}\n","import type {\n DocumentModelModule,\n DocumentSpecification,\n OperationSpecification,\n} from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\nimport { ReactorToolError } from \"./errors.js\";\nimport { operationsByActionType } from \"./model-operations.js\";\nimport { unknownValueMessage } from \"./suggest.js\";\n\n/** Marks a base action that runs in whichever scope it is sent to; never itself a scope. */\nexport const ANY_SCOPE = \"any\";\n\n// Base actions every document accepts beyond its model's operations.\nexport const BASE_OPERATIONS: readonly ModelOperation[] = [\n {\n name: \"SET_NAME\",\n module: \"base\",\n scope: \"global\",\n description: \"Renames the document\",\n schema: \"input SetNameInput {\\n name: String!\\n}\",\n },\n {\n name: \"SET_PREFERRED_EDITOR\",\n module: \"base\",\n scope: \"header\",\n description: \"Sets the editor that opens the document\",\n schema: \"input SetPreferredEditorInput {\\n preferredEditor: String\\n}\",\n },\n {\n name: \"UNDO\",\n module: \"base\",\n scope: ANY_SCOPE,\n description: \"Undoes the scope's last operations\",\n schema: \"input UndoInput {\\n count: Int\\n}\",\n },\n {\n name: \"REDO\",\n module: \"base\",\n scope: ANY_SCOPE,\n description: \"Redoes the scope's last undone operations\",\n schema: \"input RedoInput {\\n count: Int\\n}\",\n },\n {\n name: \"NOOP\",\n module: \"base\",\n scope: ANY_SCOPE,\n description: \"Changes nothing\",\n },\n];\n\nexport const modelOperationSchema = z.object({\n name: z.string(),\n module: z.string(),\n scope: z.string(),\n description: z.string().optional(),\n schema: z.string().optional().describe(\"GraphQL SDL of the action input\"),\n});\n\nexport type ModelOperation = z.infer<typeof modelOperationSchema>;\n\nexport const documentModelInfoSchema = z.object({\n type: z.string(),\n name: z.string(),\n description: z.string(),\n extension: z.string(),\n authorName: z.string(),\n authorWebsite: z.string(),\n});\n\nexport type DocumentModelInfo = z.infer<typeof documentModelInfoSchema>;\n\nexport function documentModelInfo(\n module: DocumentModelModule,\n): DocumentModelInfo {\n const global = module.documentModel.global;\n return {\n type: global.id,\n name: global.name,\n description: global.description,\n extension: global.extension,\n authorName: global.author.name,\n authorWebsite: global.author.website ?? \"\",\n };\n}\n\nexport function latestSpecification(\n module: DocumentModelModule,\n): DocumentSpecification | undefined {\n return module.documentModel.global.specifications.at(-1);\n}\n\n/** The model's operations in its latest specification, without the base ones. */\nexport function modelOperations(module: DocumentModelModule): ModelOperation[] {\n return (latestSpecification(module)?.modules ?? []).flatMap((m) =>\n m.operations\n .filter((op): op is OperationSpecification & { name: string } =>\n Boolean(op.name),\n )\n .map((op) => ({\n name: op.name,\n module: m.name,\n scope: op.scope || \"global\",\n ...(op.description ? { description: op.description } : {}),\n ...(op.schema ? { schema: op.schema } : {}),\n })),\n );\n}\n\n/** Every action type the document accepts: the model's and the base ones. */\nexport function actionOperations(\n module: DocumentModelModule,\n): ModelOperation[] {\n return [...modelOperations(module), ...BASE_OPERATIONS];\n}\n\nexport const documentModelSummarySchema = z.object({\n type: z.string(),\n name: z.string(),\n description: z.string(),\n version: z.number().describe(\"Version of the latest specification\"),\n modules: z.array(\n z.object({\n name: z.string(),\n operations: z.array(z.string()),\n }),\n ),\n});\n\nexport type DocumentModelSummary = z.infer<typeof documentModelSummarySchema>;\n\n/** Model name, latest version and its operation names by module. */\nexport function documentModelSummary(\n module: DocumentModelModule,\n): DocumentModelSummary {\n const global = module.documentModel.global;\n const latest = latestSpecification(module);\n return {\n type: global.id,\n name: global.name,\n description: global.description,\n version: latest?.version ?? global.specifications.length,\n modules: (latest?.modules ?? []).map((m) => ({\n name: m.name,\n operations: m.operations\n .map((op) => op.name)\n .filter((name): name is string => Boolean(name)),\n })),\n };\n}\n\nexport const operationSliceSchema = modelOperationSchema.extend({\n errors: z\n .array(z.object({ name: z.string(), description: z.string().optional() }))\n .optional(),\n});\n\nexport type OperationSlice = z.infer<typeof operationSliceSchema>;\n\n/** One operation's input schema; unknown names fail with did-you-mean. */\nexport function operationSchemaSlice(\n module: DocumentModelModule,\n operationName: string,\n): OperationSlice {\n const operations = actionOperations(module);\n const storedName =\n operationsByActionType(module).get(operationName)?.storedName;\n const operation =\n operations.find((op) => op.name === operationName) ??\n operations.find((op) => op.name === storedName);\n if (!operation) {\n throw new ReactorToolError(\n \"NOT_FOUND\",\n unknownValueMessage(\n \"operation\",\n operationName,\n operations.map((op) => op.name),\n {\n context: `for ${module.documentModel.global.id}`,\n knownLabel: \"Valid action types\",\n },\n ),\n );\n }\n const spec = latestSpecification(module)\n ?.modules.flatMap((m) => m.operations)\n .find((op) => op.name === operation.name);\n const errors = (spec?.errors ?? [])\n .filter((e) => e.name)\n .map((e) => ({\n name: e.name as string,\n ...(e.description ? { description: e.description } : {}),\n }));\n return {\n ...presentedScope(operation),\n ...(errors.length ? { errors } : {}),\n };\n}\n\n// ANY_SCOPE is a placeholder, so agents see the default scope and a note.\nfunction presentedScope(operation: ModelOperation): ModelOperation {\n if (operation.scope !== ANY_SCOPE) return operation;\n const note =\n \"Runs in any of the document's scopes; scope defaults to global.\";\n return {\n ...operation,\n scope: \"global\",\n description: operation.description\n ? `${operation.description}. ${note}`\n : note,\n };\n}\n\nexport const stateSliceSchema = z.object({\n scope: z.string(),\n schema: z.string().describe(\"GraphQL SDL of the scope's state\"),\n initialValue: z.string().optional(),\n});\n\nexport type StateSlice = z.infer<typeof stateSliceSchema>;\n\n/** The state schema of one scope in the latest specification. */\nexport function stateSchemaSlice(\n module: DocumentModelModule,\n scope: \"global\" | \"local\" = \"global\",\n): StateSlice {\n const state = latestSpecification(module)?.state[scope];\n return {\n scope,\n schema: state?.schema ?? \"\",\n ...(state?.initialValue ? { initialValue: state.initialValue } : {}),\n };\n}\n","import type {\n Action,\n DocumentModelModule,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n baseActions,\n DOCUMENT_SCOPE_ACTION_TYPES,\n} from \"@powerhousedao/shared/document-model\";\nimport { camelCase } from \"change-case\";\nimport { z } from \"zod\";\nimport { ReactorToolError, type ActionFailure } from \"./errors.js\";\nimport { operationsByActionType } from \"./model-operations.js\";\nimport { actionOperations, ANY_SCOPE, type ModelOperation } from \"./schema.js\";\nimport { suggestNames } from \"./suggest.js\";\n\nexport const actionInputSchema = z.object({\n type: z\n .string()\n .describe(\n \"Exact action type from the model's operations, e.g. SET_MODEL_NAME; see getDocumentModelSchema\",\n ),\n input: z\n .unknown()\n .optional()\n .describe(\"Action input, shaped by the operation's input schema\"),\n scope: z\n .string()\n .optional()\n .describe(\"Defaults to the operation's scope; rarely needed\"),\n});\n\nexport type ActionInput = z.infer<typeof actionInputSchema>;\n\nexport type ValidateActionsOptions = {\n /** Action types the caller may send; others fail as FORBIDDEN. */\n allowedActionTypes?: readonly string[];\n};\n\nexport type ValidatedActions = {\n actions: Action[];\n failures: ActionFailure[];\n};\n\ntype ActionCreator = (input: unknown) => Action;\n\nfunction countInput(input: unknown): number | undefined {\n if (typeof input === \"number\") return input;\n const count = (input as { count?: unknown } | null)?.count;\n return typeof count === \"number\" ? count : undefined;\n}\n\nconst BASE_CREATORS: Partial<Record<string, ActionCreator>> = {\n SET_NAME: (input) => baseActions.setName(input as string | { name: string }),\n SET_PREFERRED_EDITOR: (input) =>\n baseActions.setPreferredEditor(\n input as string | null | { preferredEditor: string | null },\n ),\n UNDO: (input) => baseActions.undo(countInput(input)),\n REDO: (input) => baseActions.redo(countInput(input)),\n NOOP: () => baseActions.noop(),\n};\n\nfunction issueLines(error: unknown): { lines: string[]; shape: boolean } {\n const issues = (error as { issues?: unknown }).issues;\n if (Array.isArray(issues)) {\n return {\n shape: true,\n lines: issues.map((raw) => {\n const issue = raw as { path?: unknown[]; message?: string };\n const path = Array.isArray(issue.path) ? issue.path.join(\".\") : \"\";\n const message = (issue.message ?? \"invalid\").replace(\n /^Invalid input:\\s*/,\n \"\",\n );\n return path ? `${path}: ${message}` : message;\n }),\n };\n }\n return {\n shape: false,\n lines: [error instanceof Error ? error.message : String(error)],\n };\n}\n\n/** Builds the actions, collecting every failure instead of stopping at the first. */\nexport function validateActions(\n module: DocumentModelModule,\n inputs: readonly ActionInput[],\n options: ValidateActionsOptions = {},\n): ValidatedActions {\n const operations = new Map(actionOperations(module).map((o) => [o.name, o]));\n const byActionType = operationsByActionType(module);\n const allowed = options.allowedActionTypes\n ? new Set(options.allowedActionTypes)\n : undefined;\n const actions: Action[] = [];\n const failures: ActionFailure[] = [];\n inputs.forEach((entry, index) => {\n const fail = (code: ActionFailure[\"code\"], errors: string[]) =>\n failures.push({ index, type: entry.type, code, errors });\n if (DOCUMENT_SCOPE_ACTION_TYPES.has(entry.type)) {\n return fail(\"FORBIDDEN\", [\n \"document lifecycle actions are refused; use createDocument or deleteDocument\",\n ]);\n }\n if (allowed && !allowed.has(entry.type)) {\n return fail(\"FORBIDDEN\", [\n `not an allowed action type (allowed: ${[...allowed].join(\", \")})`,\n ]);\n }\n const structured = operations.has(entry.type)\n ? undefined\n : byActionType.get(entry.type);\n const operation = operations.get(structured?.storedName ?? entry.type);\n if (!operation) {\n return fail(\"INVALID_ACTION\", [\"unknown action type\"]);\n }\n if (entry.scope === ANY_SCOPE) {\n return fail(\"INVALID_ACTION\", [\n `\"${ANY_SCOPE}\" is not a scope; name one, e.g. \"global\"`,\n ]);\n }\n const anyScope = operation.scope === ANY_SCOPE;\n const scope = entry.scope ?? (anyScope ? \"global\" : operation.scope);\n if (!anyScope && scope !== operation.scope) {\n return fail(\"INVALID_ACTION\", [\n `scope \"${scope}\" does not match the operation's scope \"${operation.scope}\"`,\n ]);\n }\n const creator =\n BASE_CREATORS[entry.type] ??\n (module.actions[structured?.creatorKey ?? camelCase(entry.type)] as\n | ActionCreator\n | undefined);\n if (!creator) {\n return fail(\"INVALID_ACTION\", [\n `the model has no action creator for ${entry.type}`,\n ]);\n }\n try {\n actions.push({ ...creator(entry.input ?? {}), scope });\n } catch (error) {\n fail(\"INVALID_ACTION\", issueLines(error).lines);\n }\n });\n return { actions, failures };\n}\n\n/** One line per failed action, did-you-mean for unknown types, and input schemas for shape errors. */\nexport function formatActionFailures(\n failures: readonly ActionFailure[],\n module?: DocumentModelModule,\n): string {\n const operations: ModelOperation[] = module ? actionOperations(module) : [];\n const names = operations.map((o) => o.name);\n const byActionType = module && operationsByActionType(module);\n const nameOf = (type: string) =>\n names.includes(type) ? type : (byActionType?.get(type)?.storedName ?? type);\n const count = failures.length;\n const lines = failures.map(\n (f) => ` [${f.index}] ${f.type}: ${f.errors.join(\"; \")}`,\n );\n const sections: string[] = [];\n const unknown = failures.filter(\n (f) =>\n f.code === \"INVALID_ACTION\" && module && !names.includes(nameOf(f.type)),\n );\n if (unknown.length > 0) {\n const suggestions = new Set(\n unknown.flatMap((f) => suggestNames(f.type, names)),\n );\n const hint = suggestions.size\n ? `Did you mean: ${[...suggestions].join(\", \")}?\\n`\n : \"\";\n sections.push(\n `${hint}Valid action types for ${module?.documentModel.global.id}:\\n ${names.join(\", \")}`,\n );\n }\n const shown = new Set<string>();\n for (const f of failures) {\n const name = nameOf(f.type);\n const operation = operations.find((o) => o.name === name);\n if (\n f.code !== \"INVALID_ACTION\" ||\n !operation?.schema ||\n shown.has(operation.name)\n ) {\n continue;\n }\n shown.add(operation.name);\n sections.push(`Input schema for ${operation.name}:\\n${operation.schema}`);\n }\n const head = `${count} action${count === 1 ? \"\" : \"s\"} failed:\\n${lines.join(\"\\n\")}`;\n return sections.length ? `${head}\\n\\n${sections.join(\"\\n\\n\")}` : head;\n}\n\n/** The error for a batch with failures; the code is the batch's most severe one. */\nexport function actionFailuresError(\n failures: ActionFailure[],\n module?: DocumentModelModule,\n): ReactorToolError {\n const codes = new Set(failures.map((f) => f.code));\n const code = codes.has(\"FORBIDDEN\")\n ? \"FORBIDDEN\"\n : codes.has(\"INVALID_ACTION\")\n ? \"INVALID_ACTION\"\n : \"REDUCER_ERROR\";\n return new ReactorToolError(code, formatActionFailures(failures, module), {\n failures,\n });\n}\n","import type {\n ConsistencyToken,\n WriteHandle,\n WriteReceipt,\n} from \"@powerhousedao/reactor\";\nimport { deleteNode } from \"@powerhousedao/shared/document-drive\";\nimport type {\n Action,\n AuthSubject,\n DocumentModelModule,\n Operation,\n OperationOutcome,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n creationState,\n operationOutcome,\n stateReducerOf,\n undoCapabilitiesOf,\n undoNeedsTargets,\n undoRedoBatch,\n} from \"@powerhousedao/shared/document-model\";\nimport { pascalCase } from \"change-case\";\nimport type { ReactorToolClient, ReactorToolReadClient } from \"./client.js\";\nimport {\n DEFAULT_BRANCH,\n DRIVE_DOCUMENT_TYPE,\n DRIVE_DOCUMENT_TYPES,\n} from \"./documents.js\";\nimport {\n ReactorToolError,\n toReactorToolError,\n type ActionFailure,\n} from \"./errors.js\";\nimport { unknownValueMessage } from \"./suggest.js\";\nimport {\n actionFailuresError,\n validateActions,\n type ActionInput,\n type ValidateActionsOptions,\n} from \"./validation.js\";\n\nexport type Revision = Record<string, number>;\n\nexport type GetDocumentOptions = {\n branch?: string;\n /** A write receipt's token, to read after that write. */\n token?: ConsistencyToken;\n};\n\nexport async function getDocument<T extends PHDocument = PHDocument>(\n client: ReactorToolReadClient,\n identifier: string,\n signal?: AbortSignal,\n options: GetDocumentOptions = {},\n): Promise<T> {\n const { branch, token } = options;\n try {\n return await client.get<T>(\n identifier,\n branch ? { branch } : undefined,\n signal,\n token,\n );\n } catch (error) {\n throw toReactorToolError(error, \"NOT_FOUND\");\n }\n}\n\n/** The model module for a type; an unknown type fails with did-you-mean. */\nexport async function getDocumentModel(\n client: ReactorToolReadClient,\n documentType: string,\n signal?: AbortSignal,\n): Promise<DocumentModelModule> {\n try {\n return await client.getDocumentModelModule(documentType);\n } catch (error) {\n const known = await client\n .getDocumentModelModules(undefined, undefined, signal)\n .then((r) => r.results.map((m) => m.documentModel.global.id))\n .catch(() => []);\n throw new ReactorToolError(\n \"NOT_FOUND\",\n unknownValueMessage(\"document type\", documentType, known, {\n knownLabel: \"Known types\",\n }),\n { cause: error },\n );\n }\n}\n\nconst OPERATIONS_PAGE_SIZE = 100;\n\n/** What became of one action: the operation it was stored as and its outcome. */\ntype StoredOutcome = { operationIndex: number } & OperationOutcome;\n\n// The operations the write appended, by action id.\nasync function storedOutcomes(\n client: ReactorToolReadClient,\n documentId: string,\n branch: string,\n actions: readonly Action[],\n before: Revision,\n signal?: AbortSignal,\n): Promise<Map<string, StoredOutcome>> {\n const ids = new Set(actions.map((a) => a.id));\n const outcomes = new Map<string, StoredOutcome>();\n for (const scope of new Set(actions.map((a) => a.scope))) {\n let cursor: string | undefined = \"0\";\n while (cursor !== undefined) {\n const page = await client.getOperations(\n documentId,\n { branch, scopes: [scope] },\n { sinceRevision: before[scope] ?? 0 },\n { cursor, limit: OPERATIONS_PAGE_SIZE },\n signal,\n );\n for (const operation of page.results) {\n if (!ids.has(operation.action.id)) continue;\n outcomes.set(operation.action.id, {\n operationIndex: operation.index,\n ...operationOutcome(operation),\n });\n }\n cursor = page.results.length > 0 ? page.nextCursor : undefined;\n }\n }\n return outcomes;\n}\n\nasync function readable(handle: Promise<WriteHandle>): Promise<WriteReceipt> {\n return (await handle).readable;\n}\n\n// The job's result names each action's outcome; a remote client's job may\n// carry none, so the stored operations are read instead.\nasync function actionOutcomes(\n client: ReactorToolReadClient,\n receipt: WriteReceipt,\n actions: readonly Action[],\n before: Revision,\n signal?: AbortSignal,\n): Promise<Map<string, StoredOutcome>> {\n const summary = receipt.job.result;\n if (summary) {\n return new Map(\n summary.actions.map((a) => [\n a.actionId,\n { ...a, operationIndex: a.index },\n ]),\n );\n }\n return storedOutcomes(\n client,\n receipt.documentId,\n receipt.branch,\n actions,\n before,\n signal,\n );\n}\n\nasync function revisionAfter(\n client: ReactorToolReadClient,\n receipt: WriteReceipt,\n signal?: AbortSignal,\n): Promise<Revision> {\n const document = await getDocument(client, receipt.documentId, signal, {\n branch: receipt.branch,\n token: receipt.token,\n });\n return { ...document.header.revision };\n}\n\n/** An action a piece host's pre-submit gate denied, by its batch index. */\ntype DeniedAction = { index: number; type: string; reason: string };\n\n// Over RPC only the message survives; the host ends it with the indexes.\nconst DENIED_INDEXES = /; denied action indexes: \\[(\\d+(?:,\\d+)*)\\]$/;\n\nfunction deniedActions(error: unknown): DeniedAction[] | undefined {\n const denied = (error as { denied?: unknown } | null)?.denied;\n if (Array.isArray(denied)) return denied as DeniedAction[];\n if (!(error instanceof Error) || error.name !== \"ReactorAccessDeniedError\") {\n return undefined;\n }\n const match = DENIED_INDEXES.exec(error.message);\n if (!match) return undefined;\n const reason = error.message.slice(0, match.index);\n return match[1].split(\",\").map((index) => ({\n index: Number(index),\n type: \"\",\n reason,\n }));\n}\n\n// A refused batch: the host's gate denied it, or admission failed the job.\nfunction isDenial(error: unknown): boolean {\n if (deniedActions(error)) return true;\n if (!(error instanceof Error)) return false;\n const job = (error as { job?: { error?: { name?: string } } }).job;\n return (\n error.name === \"AuthorizationDeniedError\" ||\n (error.name === \"JobFailedError\" &&\n job?.error?.name === \"AuthorizationDeniedError\")\n );\n}\n\nconst NO_OPERATION = \"The reactor stored no operation for this action\";\n\n/** Executes built actions and returns the new revision; any action not applied throws. */\nexport async function executeBuiltActions(\n client: ReactorToolClient,\n document: PHDocument,\n actions: Action[],\n options: {\n branch?: string;\n signal?: AbortSignal;\n module?: DocumentModelModule;\n } = {},\n): Promise<Revision> {\n const { branch = DEFAULT_BRANCH, signal, module } = options;\n let receipt: WriteReceipt;\n try {\n receipt = await readable(\n client.write.execute(document.header.id, branch, actions, signal),\n );\n } catch (error) {\n const denied = deniedActions(error);\n if (denied) {\n throw actionFailuresError(\n denied.map((d) => ({\n index: d.index,\n type: d.type || (actions.at(d.index)?.type ?? \"\"),\n code: \"FORBIDDEN\",\n errors: [d.reason],\n })),\n module,\n );\n }\n throw toReactorToolError(error);\n }\n const outcomes = await actionOutcomes(\n client,\n receipt,\n actions,\n document.header.revision,\n signal,\n );\n const failures = actions.flatMap((action, index): ActionFailure[] => {\n const outcome = outcomes.get(action.id);\n if (outcome?.kind === \"applied\") return [];\n return [\n {\n index,\n type: action.type,\n code: outcome?.kind === \"denied\" ? \"FORBIDDEN\" : \"REDUCER_ERROR\",\n errors: [\n !outcome\n ? NO_OPERATION\n : outcome.kind === \"denied\"\n ? outcome.reason\n : outcome.message,\n ],\n },\n ];\n });\n if (failures.length > 0) throw actionFailuresError(failures, module);\n return revisionAfter(client, receipt, signal);\n}\n\nexport type ExecuteActionsOptions = ValidateActionsOptions & {\n branch?: string;\n signal?: AbortSignal;\n};\n\n/** The model module at the document's own version. */\nexport async function getDocumentModelForDocument(\n client: ReactorToolReadClient,\n document: PHDocument,\n signal?: AbortSignal,\n): Promise<DocumentModelModule> {\n try {\n return await client.getDocumentModelModuleForDocument(document);\n } catch (error) {\n // An unknown type fails here with did-you-mean; a missing version below.\n await getDocumentModel(client, document.header.documentType, signal);\n throw toReactorToolError(error, \"NOT_FOUND\");\n }\n}\n\nexport type ActionError = {\n /** reducer-error: the reducer threw; denied: a policy refused it; not-applied: nothing stored it. */\n kind: \"reducer-error\" | \"denied\" | \"not-applied\";\n message: string;\n /** The model's error class, for a reducer error. */\n name?: string;\n /** The model's error code, for a reducer error. */\n code?: string;\n};\n\nexport type ActionResult = {\n index: number;\n type: string;\n scope: string;\n operationIndex?: number;\n error?: ActionError;\n};\n\nexport type ExecutedActions = {\n documentId: string;\n revision: Revision;\n /** False when any result has an error. */\n success: boolean;\n results: ActionResult[];\n};\n\ntype ModelError = { name: string; code: string };\n\n/** Finds the declared error a reducer error was, by code, class name, then default message. */\nfunction modelErrorFinder(\n module: DocumentModelModule,\n actionType: string,\n): (name?: string, code?: string, message?: string) => ModelError | undefined {\n const operations = (\n module.documentModel.global.specifications.at(-1)?.modules ?? []\n ).flatMap((m) => m.operations);\n const declared = (errors: { name: string | null; code: string | null }[]) =>\n errors.flatMap(({ name, code }) => {\n if (!name) return [];\n const className = pascalCase(name);\n return [{ name: className, code: code?.trim() || className }];\n });\n // The action's own operation first, as two operations may share an error name.\n const candidates = [\n ...declared(operations.find((o) => o.name === actionType)?.errors ?? []),\n ...declared(operations.flatMap((o) => o.errors)),\n ];\n return (name, code, message) =>\n candidates.find((e) => code !== undefined && e.code === code) ??\n candidates.find((e) => name !== undefined && e.name === name) ??\n candidates.find((e) => e.name === message);\n}\n\nfunction outcomeError(\n outcome: StoredOutcome | undefined,\n module: DocumentModelModule,\n actionType: string,\n): ActionError | undefined {\n if (!outcome) return { kind: \"not-applied\", message: NO_OPERATION };\n if (outcome.kind === \"applied\") return undefined;\n if (outcome.kind === \"denied\") {\n return { kind: \"denied\", message: outcome.reason };\n }\n const known = modelErrorFinder(module, actionType)(\n outcome.name,\n outcome.code,\n outcome.message,\n );\n const name = known?.name ?? outcome.name;\n const code = known?.code ?? outcome.code;\n return {\n kind: \"reducer-error\",\n message: outcome.message,\n ...(name !== undefined && { name }),\n ...(code !== undefined && { code }),\n };\n}\n\ntype EvaluateActions = (\n documentIdentifier: string,\n branch: string,\n candidates: { scope: string; type: string; input: unknown }[],\n subject?: AuthSubject,\n signal?: AbortSignal,\n) => Promise<{ evaluations: { decision: string; reason?: string }[] }>;\n\ntype EvaluatingClient = {\n evaluateActions?: EvaluateActions;\n write: { evaluateActions?: EvaluateActions };\n};\n\n// A policy refused the batch, so nothing in it was written.\nasync function refusedBatch(\n client: ReactorToolClient,\n documentId: string,\n branch: string,\n actions: readonly Action[],\n error: unknown,\n signal?: AbortSignal,\n): Promise<ActionError[]> {\n const message = error instanceof Error ? error.message : String(error);\n const notApplied: ActionError = {\n kind: \"not-applied\",\n message: `The batch was refused, so nothing in it was written: ${message}`,\n };\n const denied = deniedActions(error);\n if (denied) {\n return actions.map((_, i): ActionError => {\n const denial = denied.find((d) => d.index === i);\n return denial ? { kind: \"denied\", message: denial.reason } : notApplied;\n });\n }\n // Clients that can evaluate the batch name the denied actions. No subject:\n // the write was judged as the client's signer.\n const evaluating = client as unknown as EvaluatingClient;\n const target = evaluating.write.evaluateActions\n ? evaluating.write\n : evaluating;\n const evaluate = target.evaluateActions;\n if (typeof evaluate !== \"function\") return actions.map(() => notApplied);\n try {\n const { evaluations } = await evaluate.call(\n target,\n documentId,\n branch,\n actions.map(({ scope, type, input }) => ({ scope, type, input })),\n undefined,\n signal,\n );\n return actions.map((_, i): ActionError => {\n const evaluation = evaluations.at(i);\n return evaluation?.decision === \"deny\"\n ? { kind: \"denied\", message: evaluation.reason ?? message }\n : notApplied;\n });\n } catch {\n return actions.map(() => notApplied);\n }\n}\n\nfunction isUndoRedo(type: string): type is \"UNDO\" | \"REDO\" {\n return type === \"UNDO\" || type === \"REDO\";\n}\n\n/** Every stored row of one scope. */\nasync function scopeOperations(\n client: ReactorToolReadClient,\n documentId: string,\n branch: string,\n scope: string,\n signal?: AbortSignal,\n): Promise<Operation[]> {\n const rows: Operation[] = [];\n let cursor: string | undefined = \"0\";\n while (cursor !== undefined) {\n const page = await client.getOperations(\n documentId,\n { branch, scopes: [scope] },\n undefined,\n { cursor, limit: OPERATIONS_PAGE_SIZE },\n signal,\n );\n rows.push(...page.results);\n cursor = page.results.length > 0 ? page.nextCursor : undefined;\n }\n return rows;\n}\n\ntype RetractionBatch = {\n actions: Action[];\n /** The input each submitted action came from. */\n sources: number[];\n};\n\n// Base-reducer 3 (or a number this build does not know) retracts by target:\n// each step of a counted UNDO or REDO becomes one RETRACT, resolved over the\n// stored rows and the earlier actions. Undefined for every other document.\nasync function retractionBatch(\n client: ReactorToolReadClient,\n document: PHDocument,\n module: DocumentModelModule,\n inputs: readonly ActionInput[],\n actions: readonly Action[],\n options: ExecuteActionsOptions,\n signal?: AbortSignal,\n): Promise<RetractionBatch | undefined> {\n const { branch = DEFAULT_BRANCH } = options;\n const caps = undoCapabilitiesOf(document.header);\n if (\n caps === undefined ||\n !undoNeedsTargets(caps) ||\n !actions.some((action) => isUndoRedo(action.type))\n ) {\n return undefined;\n }\n const counts = actions.map((action) =>\n isUndoRedo(action.type) ? (action.input as { count?: unknown }).count : 0,\n );\n const invalid = actions.flatMap((action, index): ActionFailure[] => {\n const count = counts[index];\n if (\n !isUndoRedo(action.type) ||\n (Number.isInteger(count) && (count as number) >= 1)\n ) {\n return [];\n }\n return [\n {\n index,\n type: action.type,\n code: \"INVALID_ACTION\",\n errors: [\"count must be a positive integer\"],\n },\n ];\n });\n if (invalid.length > 0) throw actionFailuresError(invalid, module);\n const reducer = stateReducerOf(module.reducer);\n if (reducer === undefined) {\n throw new ReactorToolError(\n \"INVALID_ACTION\",\n `Document model ${document.header.documentType} has no state reducer to resolve undo targets with`,\n );\n }\n const id = document.header.id;\n const operations: Record<string, Operation[]> = {};\n for (const action of actions) {\n if (!isUndoRedo(action.type) || action.scope in operations) continue;\n operations[action.scope] = await scopeOperations(\n client,\n id,\n branch,\n action.scope,\n signal,\n );\n }\n // The served document's initialState is its head state; a scope re-derives from creation.\n const initialState =\n creationState(\n await scopeOperations(client, id, branch, \"document\", signal),\n ) ?? (module.utils.createDocument() as PHDocument).initialState;\n const batch = undoRedoBatch(\n { ...document, initialState, operations },\n caps,\n reducer,\n );\n const sources: number[] = [];\n for (const [index, action] of actions.entries()) {\n const before = batch.actions.length;\n if (isUndoRedo(action.type)) {\n try {\n for (let step = 0; step < (counts[index] as number); step++) {\n batch.undoOrRedo(action.type, action.scope);\n }\n } catch (error) {\n throw actionFailuresError(\n [\n {\n index,\n type: action.type,\n code: \"INVALID_ACTION\",\n errors: [error instanceof Error ? error.message : String(error)],\n },\n ],\n module,\n );\n }\n } else {\n // Built again as it is added: the job runs in creation order.\n batch.add(validateActions(module, [inputs[index]], options).actions[0]);\n }\n for (let i = before; i < batch.actions.length; i++) sources.push(index);\n }\n return { actions: [...batch.actions], sources };\n}\n\n// A counted UNDO or REDO was submitted as one action per step; it reports once,\n// with its last row and its first denial, else its first error.\nfunction perInput(\n inputs: readonly Action[],\n sources: readonly number[],\n submitted: readonly ActionResult[],\n): ActionResult[] {\n return inputs.map((action, index): ActionResult => {\n const steps = submitted.filter((r) => sources[r.index] === index);\n const operationIndex = steps.at(-1)?.operationIndex;\n const error =\n steps.find((step) => step.error?.kind === \"denied\")?.error ??\n steps.find((step) => step.error)?.error;\n return {\n index,\n type: action.type,\n scope: action.scope,\n ...(operationIndex !== undefined && { operationIndex }),\n ...(error && { error }),\n };\n });\n}\n\n/** Validates every action, then executes them as one batch and reports each action's outcome. */\nexport async function executeActions(\n client: ReactorToolClient,\n documentId: string,\n inputs: readonly ActionInput[],\n options: ExecuteActionsOptions = {},\n): Promise<ExecutedActions> {\n const { signal, branch = DEFAULT_BRANCH } = options;\n const document = await getDocument(client, documentId, signal, { branch });\n const id = document.header.id;\n const module = await getDocumentModelForDocument(client, document, signal);\n const validated = validateActions(module, inputs, options);\n if (validated.failures.length > 0) {\n throw actionFailuresError(validated.failures, module);\n }\n const before = { ...document.header.revision };\n if (validated.actions.length === 0) {\n return { documentId: id, revision: before, success: true, results: [] };\n }\n const retraction = await retractionBatch(\n client,\n document,\n module,\n inputs,\n validated.actions,\n options,\n signal,\n );\n const actions = retraction?.actions ?? validated.actions;\n const reported = (submitted: ActionResult[]): ActionResult[] =>\n retraction\n ? perInput(validated.actions, retraction.sources, submitted)\n : submitted;\n const result = (action: Action, index: number): ActionResult => ({\n index,\n type: action.type,\n scope: action.scope,\n });\n let receipt: WriteReceipt;\n try {\n receipt = await readable(client.write.execute(id, branch, actions, signal));\n } catch (error) {\n if (!isDenial(error)) throw toReactorToolError(error);\n const errors = await refusedBatch(\n client,\n id,\n branch,\n actions,\n error,\n signal,\n );\n return {\n documentId: id,\n revision: before,\n success: false,\n results: reported(\n actions.map((a, i) => ({ ...result(a, i), error: errors[i] })),\n ),\n };\n }\n const outcomes = await actionOutcomes(\n client,\n receipt,\n actions,\n before,\n signal,\n );\n const results = reported(\n actions.map((action, index): ActionResult => {\n const outcome = outcomes.get(action.id);\n const error = outcomeError(outcome, module, action.type);\n return {\n ...result(action, index),\n ...(outcome && { operationIndex: outcome.operationIndex }),\n ...(error && { error }),\n };\n }),\n );\n return {\n documentId: id,\n revision: await revisionAfter(client, receipt, signal),\n success: results.every((r) => !r.error),\n results,\n };\n}\n\nconst ROLLBACK_TIMEOUT_MS = 10_000;\n\nexport type CreateDocumentInput = {\n documentType: string;\n name?: string;\n /** Drive id or slug; the document becomes its child and a drive file. */\n driveId?: string;\n parentFolder?: string;\n};\n\nexport type CreatedDocument = {\n documentId: string;\n documentType: string;\n name: string;\n driveId?: string;\n revision: Revision;\n};\n\n// The reducer error of the drive's ADD_FILE for the document, if it stored one.\nasync function addFileError(\n client: ReactorToolReadClient,\n drive: PHDocument,\n documentId: string,\n signal?: AbortSignal,\n): Promise<string | undefined> {\n const page = await client\n .getOperations(\n drive.header.id,\n { scopes: [\"global\"] },\n {\n sinceRevision:\n (drive.header.revision.global as number | undefined) ?? 0,\n },\n undefined,\n signal,\n )\n .catch(() => undefined);\n const operation = page?.results.find(\n (op) =>\n op.action.type === \"ADD_FILE\" &&\n (op.action.input as { id?: unknown }).id === documentId,\n );\n const outcome = operation && operationOutcome(operation);\n if (outcome?.kind === \"reducer-error\") return outcome.message;\n if (outcome?.kind === \"denied\") return outcome.reason;\n return undefined;\n}\n\n/** Creates the document, filed into the drive when given; a half-done filing is rolled back. */\nexport async function createDocument(\n client: ReactorToolClient,\n input: CreateDocumentInput,\n signal?: AbortSignal,\n): Promise<CreatedDocument> {\n const module = await getDocumentModel(client, input.documentType, signal);\n const drive = input.driveId\n ? await getDocument(client, input.driveId, signal)\n : undefined;\n if (drive && !DRIVE_DOCUMENT_TYPES.has(drive.header.documentType)) {\n throw new ReactorToolError(\n \"INVALID_ACTION\",\n `driveId ${input.driveId} names a ${drive.header.documentType}, not a drive`,\n );\n }\n if (input.parentFolder && !drive) {\n throw new ReactorToolError(\n \"INVALID_ACTION\",\n \"parentFolder needs driveId to name a drive\",\n );\n }\n const documentType = module.documentModel.global.id;\n const name = input.name ?? \"\";\n let document: PHDocument;\n try {\n document = await client.newDocument(\n documentType,\n {\n ...(drive && { parentIdentifier: drive.header.id }),\n ...(name && { name }),\n },\n signal,\n );\n } catch (error) {\n throw toReactorToolError(error);\n }\n const documentId = document.header.id;\n // addFile creates the document before filing it; a later failure deletes\n // it and its node, under its own timeout as the caller's signal may be spent.\n const rollback = async (error: unknown) => {\n const e = toReactorToolError(error);\n try {\n await deleteDocument(\n client,\n documentId,\n AbortSignal.timeout(ROLLBACK_TIMEOUT_MS),\n );\n } catch (deleteError) {\n if (toReactorToolError(deleteError).code !== \"NOT_FOUND\") {\n return new ReactorToolError(\n e.code,\n `Document ${documentId} was created but could not be removed after: ${e.message}`,\n { failures: e.failures, cause: error },\n );\n }\n }\n return new ReactorToolError(e.code, e.message, {\n failures: e.failures,\n cause: error,\n });\n };\n let receipt: WriteReceipt;\n if (!drive) {\n try {\n receipt = await readable(\n client.write.create(document, undefined, signal),\n );\n } catch (error) {\n throw toReactorToolError(error);\n }\n } else {\n try {\n receipt = await readable(\n client.write.drives.addFile(\n drive.header.id,\n document,\n input.parentFolder,\n signal,\n ),\n );\n } catch (error) {\n throw await rollback(error);\n }\n // A document drive's reducer may reject the ADD_FILE without failing the job.\n if (drive.header.documentType === DRIVE_DOCUMENT_TYPE) {\n const filed = await getDocument(client, drive.header.id, signal, {\n token: receipt.token,\n }).catch(() => undefined);\n const nodes = (\n filed?.state as { global?: { nodes?: { id: string }[] } } | undefined\n )?.global?.nodes;\n if (nodes && !nodes.some((node) => node.id === documentId)) {\n const reason =\n (await addFileError(client, drive, documentId, signal)) ??\n \"the drive stored no node for it\";\n throw await rollback(\n new ReactorToolError(\n \"REDUCER_ERROR\",\n `Drive ${drive.header.id} did not file the document: ${reason}`,\n ),\n );\n }\n }\n }\n const created = await getDocument(client, documentId, signal, {\n token: receipt.token,\n });\n return {\n documentId,\n documentType,\n name,\n ...(drive ? { driveId: drive.header.id } : {}),\n revision: { ...created.header.revision },\n };\n}\n\ntype DriveNodes = { global?: { nodes?: unknown } };\n\ntype AuthorizingWriteClient = {\n authorizeDelete?: (id: string, signal?: AbortSignal) => Promise<void>;\n};\n\n/** Removes the document's node from each document drive filing it, then deletes it. */\nexport async function deleteDocument(\n client: ReactorToolClient,\n documentId: string,\n signal?: AbortSignal,\n): Promise<{ documentId: string }> {\n const document = await getDocument(client, documentId, signal);\n const id = document.header.id;\n // A host ACL in front of the client refuses before any drive changes.\n const { authorizeDelete } = client.write as AuthorizingWriteClient;\n await authorizeDelete?.call(client.write, id, signal);\n const parents = await client\n .getIncomingRelationships(id, \"child\", undefined, undefined, signal)\n .catch((error: unknown) => {\n throw toReactorToolError(error);\n });\n // Another drive type's node is the relationship the delete removes.\n const filing: PHDocument[] = [];\n for (const parent of parents.results) {\n if (parent.header.documentType !== DRIVE_DOCUMENT_TYPE) continue;\n const nodes = (parent.state as DriveNodes).global?.nodes;\n if (!Array.isArray(nodes)) {\n throw new ReactorToolError(\n \"FORBIDDEN\",\n `Document ${id} is filed in drive ${parent.header.id}, whose nodes you cannot read; it was not deleted`,\n );\n }\n if (nodes.some((node) => (node as { id?: unknown }).id === id)) {\n filing.push(parent);\n }\n }\n for (const parent of filing) {\n await executeBuiltActions(client, parent, [deleteNode({ id })], { signal });\n }\n try {\n await readable(client.write.deleteDocument(id, undefined, signal));\n } catch (error) {\n throw toReactorToolError(error);\n }\n return { documentId: id };\n}\n","import type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport type { CodegenStatusRegistry } from \"@powerhousedao/shared/processors\";\nimport { z } from \"zod\";\nimport { codegenHint } from \"./codegen.js\";\nimport {\n compactDocumentModelSchema,\n compactDocumentModelSchemaSchema,\n} from \"./compact-schema.js\";\nimport { defineTool } from \"./definition.js\";\nimport {\n documentSummary,\n documentSummarySchema,\n documentView,\n documentViewSchema,\n DRIVE_DOCUMENT_TYPE,\n} from \"./documents.js\";\nimport { ReactorToolError, toReactorToolError } from \"./errors.js\";\nimport { applyJsonPath, JsonPathError } from \"./jsonpath.js\";\nimport { structuredDefinition } from \"./model-operations.js\";\nimport {\n createDocument,\n deleteDocument,\n executeActions,\n getDocument,\n getDocumentModel,\n} from \"./operations.js\";\nimport {\n documentModelInfo,\n documentModelInfoSchema,\n documentModelSummary,\n documentModelSummarySchema,\n latestSpecification,\n operationSchemaSlice,\n operationSliceSchema,\n stateSchemaSlice,\n stateSliceSchema,\n} from \"./schema.js\";\nimport { actionInputSchema } from \"./validation.js\";\n\nconst MAX_LISTED = 500;\n\ntype Paged<T> = { results: T[]; next?: () => Promise<Paged<T>> };\n\nasync function collect<T>(first: Promise<Paged<T>>): Promise<T[]> {\n let page = await first.catch((error: unknown) => {\n throw toReactorToolError(error);\n });\n const out: T[] = [];\n for (;;) {\n out.push(...page.results);\n if (out.length >= MAX_LISTED || !page.next || page.results.length === 0) {\n break;\n }\n page = await page.next();\n }\n return out.slice(0, MAX_LISTED);\n}\n\nconst filterSchema = z\n .string()\n .optional()\n .describe(\n \"JSONPath over the document state, e.g. $.global.items[?(@.status=='OPEN')] or $.global.items[-1]\",\n );\n\n/** The parameter every tool names its target document or drive by. */\nconst TARGET = \"documentId\";\n\nconst targetParam = (what: string) =>\n z.string().optional().describe(`ID or slug of the ${what}. Required.`);\nconst aliasParam = z.string().optional().describe(`Alias of \\`${TARGET}\\``);\n\n/** The target named by `documentId` or one of its aliases; they must agree. */\nexport function targetId(\n tool: string,\n args: Record<string, unknown>,\n aliases: readonly string[],\n): string {\n const given = new Set(\n [TARGET, ...aliases]\n .map((name) => args[name])\n .filter((id): id is string => typeof id === \"string\" && id !== \"\"),\n );\n if (given.size > 1) {\n throw new ReactorToolError(\n \"INVALID_ACTION\",\n `${tool} got different IDs in \\`${TARGET}\\` and its aliases (${aliases.map((a) => `\\`${a}\\``).join(\", \")}); pass only \\`${TARGET}\\``,\n );\n }\n const [id] = given;\n if (!id) {\n throw new ReactorToolError(\n \"INVALID_ACTION\",\n `${tool} needs the target's ID in \\`${TARGET}\\``,\n );\n }\n return id;\n}\n\nexport { aliasParam, targetParam };\n\nconst revisionSchema = z\n .record(z.string(), z.number())\n .describe(\"Revision per scope after the change\");\n\nconst readOnly = {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n};\n\nexport const getDocumentModelsTool = defineTool({\n name: \"getDocumentModels\",\n title: \"List document models\",\n description:\n \"List the document model types this reactor can create and edit.\",\n inputSchema: z.object({}),\n outputSchema: z.object({ documentModels: z.array(documentModelInfoSchema) }),\n annotations: readOnly,\n async execute(_args, { client, signal }) {\n const modules = await collect(\n client.getDocumentModelModules(undefined, undefined, signal),\n );\n return { documentModels: modules.map(documentModelInfo) };\n },\n});\n\nexport const getDocumentModelSchemaTool = defineTool({\n name: \"getDocumentModelSchema\",\n title: \"Read a document model schema\",\n description: `Read a document model's schema. Without options it returns the operation names per module.\nPass \"compact\" before addActions for every action's type, scope and input definition, and the types those inputs use.\nPass \"operation\" for one action's input schema (GraphQL SDL), \"state\" for a state schema, or \"filter\" for a JSONPath over the latest specification.\nPass \"definition\" to also return the structured definition of a model authored in code.`,\n inputSchema: z.object({\n type: z\n .string()\n .describe(\"Document model type, e.g. powerhouse/document-model\"),\n compact: z\n .boolean()\n .optional()\n .describe(\"Return every action's type, scope and input definition\"),\n definition: z\n .boolean()\n .optional()\n .describe(\n \"Also return the structured definition of a model authored in code; ignored with compact, operation, state or filter\",\n ),\n operation: z\n .string()\n .optional()\n .describe(\n \"Action type whose input schema to return, e.g. SET_MODEL_NAME\",\n ),\n state: z\n .enum([\"global\", \"local\"])\n .optional()\n .describe(\"Scope whose state schema to return\"),\n filter: z\n .string()\n .optional()\n .describe(\n \"JSONPath over the latest specification, e.g. $.modules[*].name\",\n ),\n }),\n outputSchema: z.object({\n type: z.string(),\n model: documentModelSummarySchema.optional(),\n definition: z\n .unknown()\n .optional()\n .describe(\n \"The structured definition of a model authored in code, alongside model; change it in the package's source, not through document actions\",\n ),\n compact: compactDocumentModelSchemaSchema.optional(),\n operation: operationSliceSchema.optional(),\n state: stateSliceSchema.optional(),\n value: z.unknown().optional().describe(\"The filter's match\"),\n }),\n annotations: readOnly,\n async execute(args, { client, signal }) {\n const module = await getDocumentModel(client, args.type, signal);\n const type = module.documentModel.global.id;\n if (args.compact) {\n return {\n type,\n compact: compactDocumentModelSchema(module.documentModel.global),\n };\n }\n if (!args.operation && !args.state && !args.filter) {\n const definition = args.definition && structuredDefinition(module);\n return {\n type,\n model: documentModelSummary(module),\n ...(definition && { definition }),\n };\n }\n let value: unknown;\n if (args.filter) {\n try {\n value = applyJsonPath(latestSpecification(module), args.filter);\n } catch (error) {\n if (error instanceof JsonPathError) {\n throw new ReactorToolError(\"INVALID_ACTION\", error.message);\n }\n throw error;\n }\n }\n return {\n type,\n ...(args.operation\n ? { operation: operationSchemaSlice(module, args.operation) }\n : {}),\n ...(args.state ? { state: stateSchemaSlice(module, args.state) } : {}),\n ...(args.filter ? { value } : {}),\n };\n },\n});\n\nexport const getDocumentTool = defineTool({\n name: \"getDocument\",\n title: \"Read a document\",\n description:\n \"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).\",\n inputSchema: z.object({\n documentId: targetParam(\"document to read\"),\n id: aliasParam,\n filter: filterSchema,\n }),\n outputSchema: z.object({ document: documentViewSchema }),\n annotations: readOnly,\n async execute(args, { client, signal }) {\n const id = targetId(\"getDocument\", args, [\"id\"]);\n const document = await getDocument(client, id, signal);\n return { document: documentView(document, { filter: args.filter }) };\n },\n});\n\nexport const getDocumentsTool = defineTool({\n name: \"getDocuments\",\n title: \"List a drive's documents\",\n description:\n \"List the documents in a drive (its children): id, type and name.\",\n inputSchema: z.object({\n documentId: targetParam(\"drive whose documents to list\"),\n driveId: aliasParam,\n parentId: aliasParam,\n }),\n outputSchema: z.object({ documents: z.array(documentSummarySchema) }),\n annotations: readOnly,\n async execute(args, { client, signal }) {\n const driveId = targetId(\"getDocuments\", args, [\"driveId\", \"parentId\"]);\n const children = await collect(\n client.getOutgoingRelationships(\n driveId,\n \"child\",\n undefined,\n undefined,\n signal,\n ),\n );\n return { documents: children.map(documentSummary) };\n },\n});\n\nexport const getDrivesTool = defineTool({\n name: \"getDrives\",\n title: \"List drives\",\n description: \"List the drives: id, type and name.\",\n inputSchema: z.object({}),\n outputSchema: z.object({ drives: z.array(documentSummarySchema) }),\n annotations: readOnly,\n async execute(_args, { client, signal }) {\n const drives = await collect(\n client.find({ type: DRIVE_DOCUMENT_TYPE }, undefined, undefined, signal),\n );\n return { drives: drives.map(documentSummary) };\n },\n});\n\nexport const getDriveTool = defineTool({\n name: \"getDrive\",\n title: \"Read a drive\",\n description:\n \"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.\",\n inputSchema: z.object({\n documentId: targetParam(\"drive to read\"),\n driveId: aliasParam,\n id: aliasParam,\n filter: filterSchema,\n }),\n outputSchema: z.object({ drive: documentViewSchema }),\n annotations: readOnly,\n async execute(args, { client, signal }) {\n const driveId = targetId(\"getDrive\", args, [\"driveId\", \"id\"]);\n const drive = await getDocument<PHDocument>(client, driveId, signal);\n return { drive: documentView(drive, { filter: args.filter }) };\n },\n});\n\nexport const createDocumentTool = defineTool({\n name: \"createDocument\",\n title: \"Create a document\",\n description: `Create a document, optionally inside a drive.\nWith \"driveId\" the document is added to the drive as a file, so no separate ADD_FILE is needed.`,\n inputSchema: z.object({\n documentType: z.string().describe(\"Document model type\"),\n name: z\n .string()\n .optional()\n .describe(\"Document name, also the drive file's name\"),\n driveId: z\n .string()\n .optional()\n .describe(\"Drive id or slug to create the document in\"),\n parentFolder: z\n .string()\n .optional()\n .describe(\"Folder id within the drive; only with driveId\"),\n }),\n outputSchema: z.object({\n documentId: z.string(),\n documentType: z.string(),\n name: z.string(),\n driveId: z.string().optional(),\n revision: revisionSchema,\n }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: false,\n },\n async execute(args, { client, signal }) {\n return createDocument(client, args, signal);\n },\n});\n\nexport const deleteDocumentTool = defineTool({\n name: \"deleteDocument\",\n title: \"Delete a document\",\n description: \"Delete a document, removing it from its drive first.\",\n inputSchema: z.object({\n documentId: targetParam(\"document to delete\"),\n id: aliasParam,\n }),\n outputSchema: z.object({ documentId: z.string() }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n async execute(args, { client, signal }) {\n const id = targetId(\"deleteDocument\", args, [\"id\"]);\n return deleteDocument(client, id, signal);\n },\n});\n\nconst actionErrorSchema = z\n .object({\n kind: z\n .enum([\"reducer-error\", \"denied\", \"not-applied\"])\n .describe(\n \"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\",\n ),\n message: z.string().describe(\"Why the action was not applied\"),\n name: z\n .string()\n .optional()\n .describe(\"For a reducer-error: the error class the reducer threw\"),\n code: z\n .string()\n .optional()\n .describe(\"For a reducer-error: the error's code in the document model\"),\n })\n .describe(\"Present when the action was not applied\");\n\nexport type ReactorToolsOptions = {\n /** Action types `addActions` may send; others fail as FORBIDDEN. */\n allowedActionTypes?: readonly string[];\n /** Vetra's codegen status; `addActions` then says how to follow generation. */\n codegenStatus?: CodegenStatusRegistry;\n};\n\nexport function createAddActionsTool(options: ReactorToolsOptions = {}) {\n const allowed = options.allowedActionTypes;\n return defineTool({\n name: \"addActions\",\n title: \"Change a document\",\n description: `Apply actions to a document as one batch. Send several actions in one call rather than one call each.\nBesides 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.\nEvery action is validated first; on a validation failure nothing is applied and each failed action is listed.\nReturns 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.\nOn 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.${\n allowed ? `\\nAllowed action types: ${allowed.join(\", \")}.` : \"\"\n }`,\n inputSchema: z.object({\n documentId: targetParam(\"document or drive to change\"),\n id: aliasParam,\n actions: z\n .array(actionInputSchema)\n .min(1)\n .describe(\"Actions to apply, in order\"),\n }),\n outputSchema: z.object({\n documentId: z.string(),\n revision: revisionSchema,\n success: z.boolean().describe(\"False when any action was not applied\"),\n results: z\n .array(\n z.object({\n index: z.number().describe(\"Position of the action in `actions`\"),\n type: z.string(),\n scope: z.string(),\n operationIndex: z\n .number()\n .optional()\n .describe(\n \"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\",\n ),\n error: actionErrorSchema.optional(),\n }),\n )\n .describe(\"One result per action, in the order they were given\"),\n codegen: z\n .string()\n .optional()\n .describe(\n \"Present when Vetra generates code from this document: how to follow that generation\",\n ),\n }),\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n openWorldHint: false,\n },\n async execute(args, { client, signal }) {\n const id = targetId(\"addActions\", args, [\"id\"]);\n const executed = await executeActions(client, id, args.actions, {\n allowedActionTypes: allowed,\n signal,\n });\n const codegen =\n options.codegenStatus &&\n (await codegenHint(options.codegenStatus, client, executed, signal));\n return { ...executed, ...(codegen && { codegen }) };\n },\n });\n}\n\nexport const addActionsTool = createAddActionsTool();\n\n/** The tools every host mounts: reads, document create/delete and `addActions`. */\nexport function reactorTools(options: ReactorToolsOptions = {}) {\n return [\n getDocumentModelsTool,\n getDocumentModelSchemaTool,\n getDrivesTool,\n getDriveTool,\n getDocumentsTool,\n getDocumentTool,\n createDocumentTool,\n options.allowedActionTypes || options.codegenStatus\n ? createAddActionsTool(options)\n : addActionsTool,\n deleteDocumentTool,\n ] as const;\n}\n\nexport type ReactorTool = ReturnType<typeof reactorTools>[number];\n"],"mappings":";;;;;;AAAA,MAAa,2BAA2B;CACtC;CACA;CACA;CACA;CACA;AACF;AAeA,IAAa,mBAAb,cAAsC,MAAM;CAC1C;CACA;CAEA,YACE,MACA,SACA,UAA2D,CAAC,GAC5D;EACA,MAAM,SAAS,EAAE,OAAO,QAAQ,MAAM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