@powerhousedao/workflow 6.2.3-dev.94 → 6.2.3-dev.96

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/browser/{BlockSelector-DFzzAWXh.js → BlockSelector-CEdYUqjx.js} +38 -37
  2. package/dist/browser/BlockSelector-CEdYUqjx.js.map +1 -0
  3. package/dist/browser/{connection-form-O02M1hkC.js → connection-form-Biksq2jW.js} +4 -4
  4. package/dist/browser/{connection-form-O02M1hkC.js.map → connection-form-Biksq2jW.js.map} +1 -1
  5. package/dist/browser/{connection-PaKXHYz9.js → connection-ilYFCRUK.js} +2 -2
  6. package/dist/browser/{connection-PaKXHYz9.js.map → connection-ilYFCRUK.js.map} +1 -1
  7. package/dist/browser/{data-tree-DKS0EQys.js → data-tree-Cq-s6bJp.js} +2 -2
  8. package/dist/browser/{data-tree-DKS0EQys.js.map → data-tree-Cq-s6bJp.js.map} +1 -1
  9. package/dist/browser/document-models/connection/index.js +1 -1
  10. package/dist/browser/document-models/workflow/index.js +1 -1
  11. package/dist/browser/{editor-gCkAwv09.js → editor-CIqKi7XK.js} +6 -6
  12. package/dist/browser/{editor-gCkAwv09.js.map → editor-CIqKi7XK.js.map} +1 -1
  13. package/dist/browser/{editor-BPF_SXdt.js → editor-DYjoPfta.js} +8 -8
  14. package/dist/browser/{editor-BPF_SXdt.js.map → editor-DYjoPfta.js.map} +1 -1
  15. package/dist/browser/{editor-xBTKbbNO.js → editor-GeRXGdie.js} +6 -6
  16. package/dist/browser/{editor-xBTKbbNO.js.map → editor-GeRXGdie.js.map} +1 -1
  17. package/dist/browser/editors/connection-editor/module.js +1 -1
  18. package/dist/browser/editors/runtime/index.js +1 -1
  19. package/dist/browser/editors/workflow-editor/module.js +1 -1
  20. package/dist/browser/editors/workflow-studio/module.js +1 -1
  21. package/dist/browser/index.js +127 -87
  22. package/dist/browser/index.js.map +1 -1
  23. package/dist/browser/{runtime-queries-C5bqAgQy.js → runtime-queries-FmEzElOY.js} +39 -20
  24. package/dist/browser/runtime-queries-FmEzElOY.js.map +1 -0
  25. package/dist/browser/{trigger-text-BfIu-QcC.js → trigger-text-DH6HIeoa.js} +4 -4
  26. package/dist/browser/{trigger-text-BfIu-QcC.js.map → trigger-text-DH6HIeoa.js.map} +1 -1
  27. package/dist/browser/{workflow-BFdnSGRD.js → workflow-2gR2JXUS.js} +2 -2
  28. package/dist/browser/{workflow-BFdnSGRD.js.map → workflow-2gR2JXUS.js.map} +1 -1
  29. package/dist/node/pieces/ai/descriptor.json +1 -1
  30. package/dist/node/pieces/ai/package.json +1 -1
  31. package/dist/node/pieces/reactor/descriptor.json +1 -1
  32. package/dist/node/pieces/reactor/package.json +1 -1
  33. package/dist/powerhouse.manifest.json +2 -2
  34. package/dist/types/ai/runtime.d.ts +13 -0
  35. package/dist/types/ai/runtime.d.ts.map +1 -0
  36. package/dist/types/ai/tools.d.ts +6 -2
  37. package/dist/types/ai/tools.d.ts.map +1 -1
  38. package/dist/types/ai/workflow-tools.d.ts.map +1 -1
  39. package/dist/types/editors/workflow-editor/runtime-api.d.ts +13 -12
  40. package/dist/types/editors/workflow-editor/runtime-api.d.ts.map +1 -1
  41. package/dist/types/editors/workflow-editor/runtime-client.d.ts +8 -2
  42. package/dist/types/editors/workflow-editor/runtime-client.d.ts.map +1 -1
  43. package/dist/types/editors/workflow-editor/runtime-context.d.ts +1 -1
  44. package/dist/types/editors/workflow-editor/runtime-context.d.ts.map +1 -1
  45. package/dist/types/editors/workflow-editor/use-workflow-runtime.d.ts +13 -0
  46. package/dist/types/editors/workflow-editor/use-workflow-runtime.d.ts.map +1 -0
  47. package/dist/types/editors/workflow-editor/use-workflow-runtime.test.d.ts +2 -0
  48. package/dist/types/editors/workflow-editor/use-workflow-runtime.test.d.ts.map +1 -0
  49. package/dist/types/scripts/ui-stack.d.ts.map +1 -1
  50. package/dist/types/test/switchboards.d.ts +20 -0
  51. package/dist/types/test/switchboards.d.ts.map +1 -0
  52. package/package.json +11 -11
  53. package/dist/browser/BlockSelector-DFzzAWXh.js.map +0 -1
  54. package/dist/browser/runtime-queries-C5bqAgQy.js.map +0 -1
  55. package/dist/types/ai/runtime-url.d.ts +0 -2
  56. package/dist/types/ai/runtime-url.d.ts.map +0 -1
  57. package/dist/types/ai/runtime-url.test.d.ts +0 -2
  58. package/dist/types/ai/runtime-url.test.d.ts.map +0 -1
  59. package/dist/types/editors/workflow-editor/use-runtime-url.d.ts +0 -2
  60. package/dist/types/editors/workflow-editor/use-runtime-url.d.ts.map +0 -1
  61. package/dist/types/test/drive-window.d.ts +0 -6
  62. package/dist/types/test/drive-window.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["READ_ONLY","runConnectionCheck","manifestJson"],"sources":["../../editors/workflow-editor/runtime-api.ts","../../ai/runtime-url.ts","../../ai/workflow-tools.ts","../../ai/tools.ts","../../editors/editors.ts","../../index.ts"],"sourcesContent":["// Ambient runtime client for the AI tools, which run outside any editor.\n// Editors never import this: each one gets its own client from RuntimeProvider.\nimport type { BlockRef } from \"@powerhousedao/pieces-framework/block-type\";\nimport {\n createRuntimeClient,\n DEFAULT_RUNTIME_URL,\n type RunsScope,\n type RuntimeClient,\n} from \"./runtime-client.js\";\nimport {\n blockFormQuery,\n catalogQuery,\n createRuntimeQueryClient,\n} from \"./runtime-queries.js\";\n\nexport type * from \"./runtime-client.js\";\nexport { DEFAULT_RUNTIME_URL };\n\nlet ambient: RuntimeClient = createRuntimeClient(DEFAULT_RUNTIME_URL);\n// Keys start with the URL, so switching runtimes needs no cache reset.\nconst ambientQueries = createRuntimeQueryClient();\n\nexport function setRuntimeUrl(url: string): void {\n if (url !== ambient.url) ambient = createRuntimeClient(url);\n}\n\nexport const getBlockForm = (block: BlockRef) =>\n ambientQueries.fetchQuery(blockFormQuery(ambient, block));\nexport const fetchPieceCatalog = () =>\n ambientQueries.fetchQuery(catalogQuery(ambient));\nexport const fetchPieceActions = (packageName: string) =>\n ambient.fetchPieceActions(packageName);\nexport const fetchPieceTriggers = (packageName: string) =>\n ambient.fetchPieceTriggers(packageName);\nexport const searchPieces = (\n query: string,\n filter: Parameters<RuntimeClient[\"searchPieces\"]>[1],\n) => ambient.searchPieces(query, filter);\nexport const fetchConnections = () => ambient.fetchConnections();\nexport const checkConnection = (connectionId: string) =>\n ambient.checkConnection(connectionId);\nexport const fetchRuns = (scope?: RunsScope) => ambient.fetchRuns(scope);\nexport const fireWorkflow = (workflowId: string, payload?: unknown) =>\n ambient.fireWorkflow(workflowId, payload);\n","// Points the module-level runtime client at the selected drive's\n// workflow-runtime subgraph before an AI tool talks to it.\nimport { getPHStore } from \"@powerhousedao/reactor-browser\";\nimport { resolveDriveSwitchboard } from \"@powerhousedao/reactor-browser/ai\";\nimport {\n DEFAULT_RUNTIME_URL,\n setRuntimeUrl,\n} from \"../editors/workflow-editor/runtime-api.js\";\n\nconst warnedDrives = new Set<string>();\n\nexport function syncRuntimeUrl(): void {\n if (typeof window === \"undefined\") return;\n const driveId = getPHStore()?.selectedDriveId;\n const switchboard = resolveDriveSwitchboard(driveId);\n // No resolvable switchboard (no selection, or a local/unsynced drive):\n // reset to the default rather than leaving a prior drive's URL attached.\n if (!switchboard && driveId && !warnedDrives.has(driveId)) {\n // A Workflows drive has to be attached as a REMOTE of the switchboard\n // that runs the workflow runtime; a local copy renders the studio against\n // whatever answers at the default URL.\n warnedDrives.add(driveId);\n console.warn(\n `[workflow] Drive \"${driveId}\" is not synced from a switchboard, so Workflow Studio falls back to ${DEFAULT_RUNTIME_URL}. ` +\n \"Attach the switchboard's Workflows drive (its /d/<slug> URL) instead of a local drive.\",\n );\n }\n setRuntimeUrl(\n switchboard\n ? `${switchboard.graphqlUrl}/workflow-runtime`\n : DEFAULT_RUNTIME_URL,\n );\n}\n","// AI tool descriptors for authoring and running workflows: the pinned blocks\n// a piece offers, a block's config props, the built-in core blocks with\n// the expression syntax, run history and manual firing. Complements the\n// connector/connection tools in tools.ts, which cover the catalog and auth.\nimport type { PhAiToolDescriptor } from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\nimport {\n fetchPieceActions,\n fetchPieceTriggers,\n fetchRuns,\n fireWorkflow,\n getBlockForm,\n} from \"../editors/workflow-editor/runtime-api.js\";\nimport type { BlockFormProp } from \"../editors/workflow-editor/ui/forms.js\";\nimport { REACTOR_CONNECTOR_ID } from \"../document-models/connection/v1/src/reactor-connection.js\";\nimport {\n CORE_PIECE,\n REACTOR_PIECE,\n type BlockRef,\n} from \"../editors/workflow-editor/ui/blocks.js\";\nimport { syncRuntimeUrl } from \"./runtime-url.js\";\nimport { flowPorts } from \"@powerhousedao/pieces-framework/workflow\";\n\nconst READ_ONLY = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\nfunction kindOf(block: BlockRef): \"trigger\" | \"step\" {\n return block.kind === \"trigger\" ? \"trigger\" : \"step\";\n}\n\n// The fields ADD_STEP or SET_TRIGGER takes for the block.\nfunction blockFields(block: BlockRef) {\n return {\n pieceName: block.pieceName,\n pieceVersion: block.pieceVersion,\n ...(block.kind === \"trigger\"\n ? { triggerName: block.name }\n : { actionName: block.name }),\n };\n}\n\n// The onward ports the block's descriptor declares; \"error\" is a failure route.\nfunction portsFor(form: { ports?: readonly string[] }): string[] {\n return flowPorts(form.ports ?? []);\n}\n\nfunction describeProp(prop: BlockFormProp) {\n return {\n name: prop.name,\n label: prop.displayName,\n type: prop.type,\n required: prop.required,\n ...(prop.description ? { description: prop.description } : {}),\n ...(prop.defaultValue !== undefined ? { default: prop.defaultValue } : {}),\n ...(prop.staticOptions\n ? { options: prop.staticOptions.map((option) => option.value) }\n : {}),\n ...(prop.hasDynamicResolver ? { dynamicOptions: true } : {}),\n };\n}\n\nconst EXPRESSIONS = [\n \"Step configs and edge conditions may contain expressions in double braces.\",\n \"{{trigger.payload.<field>}} reads the trigger payload: for the core manual trigger the payload passed to fireWorkflow; for the reactor piece's document triggers it carries documentId, documentType, driveId and name.\",\n \"{{steps.<key>.output.<path>}} reads an upstream step's output by that step's key, e.g. {{steps.fetch.output.body.title}}.\",\n \"The reactor piece's document-create and document-dispatch output a reference { documentId, documentType, branch, revision }, e.g. {{steps.create.output.documentId}}; read the document with document-get to use its state. document-get outputs the document as { header, state }, e.g. {{steps.get.output.state.global.name}} or {{steps.get.output.header.id}}. document-find outputs { results, nextCursor }: each result has a header (and state with includeState), and nextCursor, present while more match, goes in a later find's cursor.\",\n \"{{variables.<key>}} reads a workflow variable.\",\n \"'a' || 'b' picks the first non-empty value, e.g. {{trigger.payload.url || 'https://example.com'}}.\",\n \"A whole-string expression yields the raw value; text around expressions is interpolated.\",\n];\n\nconst GRAPH_RULES = [\n \"A workflow is a powerhouse/workflow document. Build it with SET_TRIGGER once, ADD_STEP per step (each with a unique id and key), and ADD_EDGE from the trigger id to the first step and between steps.\",\n \"An edge must leave on a port its source declares (getWorkflowBlockConfig lists them): 'next' for the trigger and ordinary steps, 'true' and 'false' for the core branch action, 'error' to route a failure. An edge on any other port is never taken, and the run is flagged with a warning.\",\n \"A step names its block with pieceName, pieceVersion and actionName; the trigger with pieceName, pieceVersion and triggerName. pieceVersion is an exact semver: copy the fields getWorkflowPieceBlocks or listWorkflowCoreBlocks return.\",\n `The built-in blocks (manual, schedule and webhook triggers, branch and assert) belong to the piece ${CORE_PIECE}.`,\n \"The core router's ports follow its config: 'branch_1' … 'branch_N', one per entry of its branches list in order, then 'otherwise'. The core loop leaves on 'each' into its body, which runs once per item and must not lead out of the body, and on 'next' after the last item; body steps read {{steps.<loop key>.output.item}} and .index.\",\n \"Steps whose piece needs a connection must set connectionId to a powerhouse/connection document id (see getConnections).\",\n `Every step and trigger whose block reports requireReactor (getWorkflowBlockConfig) must set reactorConnectionId to a powerhouse/connection document with authType REACTOR and connectorId ${REACTOR_CONNECTOR_ID} (see getConnections); the ${REACTOR_PIECE} blocks all do. Without one the block gets no reactor access and fails. The connection's config { endpoint: \"local\", access?: \"read\", filter?: { documentType?, documentId?, driveId?, actionType? } } limits which documents it reads and writes. connectionId stays for credentials; a document block normally needs none.`,\n \"Runs execute the published snapshot, not the draft. PUBLISH_WORKFLOW only snapshots the draft, so publish again after every edit that should run.\",\n \"Only ENABLED workflows get trigger instances and can be fired. PUBLISH_WORKFLOW does not enable: to turn a workflow on, dispatch SET_WORKFLOW_STATUS ENABLED after PUBLISH_WORKFLOW (the same batch works). SET_WORKFLOW_STATUS ENABLED is refused until the workflow has been published once.\",\n];\n\nexport const getWorkflowPieceBlocksTool: PhAiToolDescriptor = {\n name: \"getWorkflowPieceBlocks\",\n description:\n \"Lists the actions and triggers of one piece, each with the pieceName, pieceVersion and actionName or triggerName to use in ADD_STEP or SET_TRIGGER. Takes the piece package name from getConnectors. Call getWorkflowBlockConfig next for a block's config props.\",\n inputSchema: {\n packageName: z\n .string()\n .describe(\"Piece package name, e.g. @activepieces/piece-http.\"),\n },\n annotations: { title: \"Get Workflow Piece Blocks\", ...READ_ONLY },\n callback: async (args: { packageName: string }) => {\n syncRuntimeUrl();\n const [actions, triggers] = await Promise.all([\n fetchPieceActions(args.packageName),\n fetchPieceTriggers(args.packageName),\n ]);\n return {\n packageName: args.packageName,\n actions: actions.map((action) => ({\n pieceName: action.pieceName,\n pieceVersion: action.pieceVersion,\n actionName: action.name,\n displayName: action.displayName,\n description: action.description,\n })),\n triggers: triggers.map((trigger) => ({\n pieceName: trigger.pieceName,\n pieceVersion: trigger.pieceVersion,\n triggerName: trigger.name,\n displayName: trigger.displayName,\n description: trigger.description,\n strategy: trigger.strategy,\n })),\n };\n },\n};\n\nexport const getWorkflowBlockConfigTool: PhAiToolDescriptor = {\n name: \"getWorkflowBlockConfig\",\n description:\n \"Describes the config of one block (a core block or a piece's action or trigger): prop names, types, whether required, allowed options, the output ports, whether a connection is needed, and requireReactor (read | write) when it needs a reactor connection. Use it before writing a step or trigger config.\",\n inputSchema: {\n pieceName: z\n .string()\n .describe(\n `Piece package name, e.g. ${CORE_PIECE} or @activepieces/piece-http.`,\n ),\n pieceVersion: z.string().describe(\"Exact semver of the piece.\"),\n name: z\n .string()\n .describe(\"Action or trigger name, e.g. branch or send_request.\"),\n kind: z.enum([\"action\", \"trigger\"]).describe(\"action or trigger.\"),\n },\n annotations: { title: \"Get Workflow Block Config\", ...READ_ONLY },\n callback: async (args: BlockRef) => {\n const block: BlockRef = {\n pieceName: args.pieceName,\n pieceVersion: args.pieceVersion,\n name: args.name,\n kind: args.kind,\n };\n syncRuntimeUrl();\n const form = await getBlockForm(block);\n if (!form) {\n return {\n ...blockFields(block),\n error:\n \"Unknown block. Use getConnectors and getWorkflowPieceBlocks to find valid blocks (documents live in @powerhousedao/piece-reactor), or listWorkflowCoreBlocks for built-ins.\",\n };\n }\n return {\n ...blockFields(block),\n title: form.title,\n kind: kindOf(block),\n requiresConnection: form.auth === \"required\",\n // read | write: the block needs a reactorConnectionId granting this.\n requireReactor: form.requireReactor ?? null,\n props: form.props.map(describeProp),\n ports: portsFor(form),\n };\n },\n};\n\nexport const listWorkflowCoreBlocksTool: PhAiToolDescriptor = {\n name: \"listWorkflowCoreBlocks\",\n description: `Lists the built-in blocks of the ${CORE_PIECE} piece (manual, schedule and webhook triggers, branch and assert) with their pinned fields and config props, plus the expression syntax and the rules for building a powerhouse/workflow document. Documents are read and written by the @powerhousedao/piece-reactor blocks; list those with getWorkflowPieceBlocks.`,\n inputSchema: {},\n annotations: { title: \"List Workflow Core Blocks\", ...READ_ONLY },\n callback: async () => {\n syncRuntimeUrl();\n // The reactor serves the core piece's descriptors, as it does any piece's.\n const [actions, triggers] = await Promise.all([\n fetchPieceActions(CORE_PIECE),\n fetchPieceTriggers(CORE_PIECE),\n ]);\n const blocks: BlockRef[] = [\n ...triggers.map((entry) => ({ ...entry, kind: \"trigger\" as const })),\n ...actions.map((entry) => ({ ...entry, kind: \"action\" as const })),\n ].map((entry) => ({\n pieceName: entry.pieceName,\n pieceVersion: entry.pieceVersion,\n name: entry.name,\n kind: entry.kind,\n }));\n const forms = await Promise.all(blocks.map(getBlockForm));\n return {\n blocks: blocks.flatMap((block, index) => {\n const form = forms[index];\n if (!form) return [];\n return [\n {\n ...blockFields(block),\n title: form.title,\n kind: kindOf(block),\n props: form.props.map(describeProp),\n ports: portsFor(form),\n },\n ];\n }),\n expressions: EXPRESSIONS,\n rules: GRAPH_RULES,\n };\n },\n};\n\nexport const listWorkflowRunsTool: PhAiToolDescriptor = {\n name: \"listWorkflowRuns\",\n description:\n \"Lists recent workflow runs, newest first, with status, error and each step's outcome. Filter by workflowId to inspect one workflow, or by driveId for every workflow in a drive.\",\n inputSchema: {\n workflowId: z\n .string()\n .optional()\n .describe(\"Workflow document id to filter by.\"),\n driveId: z\n .string()\n .optional()\n .describe(\"Drive id to filter by (all workflows in that drive).\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .describe(\"Maximum runs to return (default 10).\"),\n },\n annotations: { title: \"List Workflow Runs\", ...READ_ONLY },\n callback: async (args: {\n workflowId?: string;\n driveId?: string;\n limit?: number;\n }) => {\n syncRuntimeUrl();\n const runs = await fetchRuns({\n workflowId: args.workflowId,\n driveId: args.driveId,\n limit: args.limit ?? 10,\n });\n return {\n runs: runs.map((run) => ({\n id: run.id,\n workflowId: run.workflowId,\n workflowName: run.workflowName,\n status: run.status,\n error: run.error,\n triggerKind: run.triggerKind,\n startedAt: run.startedAt,\n endedAt: run.endedAt,\n steps: run.steps.map((step) => ({\n key: step.stepKey,\n status: step.status,\n error: step.error,\n })),\n })),\n };\n },\n};\n\nexport const fireWorkflowTool: PhAiToolDescriptor = {\n name: \"fireWorkflow\",\n description:\n \"Fires an ENABLED workflow whose trigger is the core manual trigger and runs its published snapshot to completion. The payload becomes {{trigger.payload}}. Returns the run id and final status.\",\n inputSchema: {\n workflowId: z.string().describe(\"Workflow document id.\"),\n payload: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Trigger payload object.\"),\n },\n annotations: {\n title: \"Fire Workflow\",\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n callback: (args: {\n workflowId: string;\n payload?: Record<string, unknown>;\n }) => {\n syncRuntimeUrl();\n return fireWorkflow(args.workflowId, args.payload ?? {});\n },\n};\n\n/** Workflow authoring and run tools, merged into `aiTools` in tools.ts. */\nexport const workflowTools: PhAiToolDescriptor[] = [\n getWorkflowPieceBlocksTool,\n getWorkflowBlockConfigTool,\n listWorkflowCoreBlocksTool,\n listWorkflowRunsTool,\n fireWorkflowTool,\n];\n","// Read-only AI tool descriptors for the Connect assistant: the project's\n// piece catalog, connection documents, and connection health. The `aiTools`\n// export is how the host app discovers this package's tools (the line in the\n// project index is synced by `ph generate`).\nimport { getPHStore } from \"@powerhousedao/reactor-browser\";\nimport type { PhAiToolDescriptor } from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\nimport {\n connectorIdForPiece,\n isConfigValueMissing,\n packageFromConnectorId,\n planFromAuth,\n type AuthField,\n} from \"../editors/connection-editor/piece-auth.js\";\nimport {\n checkConnection as runConnectionCheck,\n fetchConnections,\n fetchPieceActions,\n fetchPieceCatalog,\n fetchPieceTriggers,\n searchPieces,\n type PieceSummary,\n} from \"../editors/workflow-editor/runtime-api.js\";\nimport { syncRuntimeUrl } from \"./runtime-url.js\";\nimport { workflowTools } from \"./workflow-tools.js\";\n\nconst MAX_CONNECTORS = 20;\n\nexport interface ConnectorField {\n name: string;\n label: string;\n required: boolean;\n description?: string;\n secret: boolean;\n}\n\nexport interface ConnectorDetail {\n connectorId: string;\n pieceName: string;\n displayName: string;\n description: string;\n version: string;\n authType: string;\n /** False for auth kinds the runtime cannot execute yet (OIDC). */\n supported: boolean;\n /** OAUTH2: a person finishes it by signing in from the connection editor. */\n signIn?: \"oauth2\";\n fields: ConnectorField[];\n actions: string[];\n triggers: string[];\n}\n\nfunction toField(field: AuthField, secret: boolean): ConnectorField {\n return {\n name: field.name,\n label: field.displayName,\n required: field.required,\n description: field.description,\n secret,\n };\n}\n\nasync function connectorDetail(piece: PieceSummary): Promise<ConnectorDetail> {\n const plan = planFromAuth(piece.auth);\n const [actions, triggers] = await Promise.all([\n fetchPieceActions(piece.name),\n fetchPieceTriggers(piece.name),\n ]);\n return {\n connectorId: connectorIdForPiece(piece.name),\n pieceName: piece.name,\n displayName: piece.displayName,\n description: piece.description,\n version: piece.version,\n authType: plan.authType,\n supported: plan.supported,\n ...(plan.oauth2 ? { signIn: \"oauth2\" as const } : {}),\n fields: [\n ...plan.configFields.map((field) => toField(field, false)),\n ...plan.secretFields.map((field) => toField(field, true)),\n ],\n actions: actions.map((action) => action.name),\n triggers: triggers.map((trigger) => trigger.name),\n };\n}\n\n// Pieces the runtime's search ranks for the query, actions' and triggers'\n// rankings interleaved; null while its index builds, where it has none, or\n// when it ranks nothing (a package name, say).\nasync function rankedPieces(\n catalog: PieceSummary[],\n query: string,\n): Promise<PieceSummary[] | null> {\n let results;\n try {\n results = await Promise.all(\n ([\"action\", \"trigger\"] as const).map((kind) =>\n searchPieces(query, { kind, limit: 50 }),\n ),\n );\n } catch {\n return null;\n }\n if (results.some((result) => result.status !== \"ready\")) return null;\n const byName = new Map(catalog.map((piece) => [piece.name, piece]));\n const ranked = new Map<string, PieceSummary>();\n const longest = Math.max(...results.map((result) => result.pieces.length));\n for (let rank = 0; rank < longest; rank++) {\n for (const result of results) {\n const name = result.pieces.at(rank)?.pieceName;\n const piece = name === undefined ? undefined : byName.get(name);\n if (piece && !ranked.has(piece.name)) ranked.set(piece.name, piece);\n }\n }\n return ranked.size > 0 ? [...ranked.values()] : null;\n}\n\n/**\n * Stage one of connector discovery: the catalog, optionally narrowed by the\n * runtime's piece search (a substring match while its index builds), capped\n * at {@link MAX_CONNECTORS}. Full auth/action/trigger detail is fetched only\n * for the surviving entries (stage two).\n */\nexport async function getConnectors(query?: string): Promise<{\n total: number;\n matches: number;\n truncated: boolean;\n connectors: ConnectorDetail[];\n}> {\n syncRuntimeUrl();\n const catalog = await fetchPieceCatalog();\n const needle = query?.trim().toLowerCase();\n // A package name is an answer, not a search.\n const exact = catalog.filter((piece) => piece.name.toLowerCase() === needle);\n const matches = !needle\n ? [...catalog]\n : exact.length > 0\n ? exact\n : ((await rankedPieces(catalog, needle)) ??\n catalog.filter((piece) =>\n [piece.name, piece.displayName, piece.description].some((field) =>\n field.toLowerCase().includes(needle),\n ),\n ));\n const page = matches.slice(0, MAX_CONNECTORS);\n const connectors = await Promise.all(page.map(connectorDetail));\n return {\n total: catalog.length,\n matches: matches.length,\n truncated: matches.length > page.length,\n connectors,\n };\n}\n\ninterface ConnectionState {\n config?: unknown;\n secretRefs?: { name: string }[];\n}\n\nexport interface ConnectionDetail {\n id: string;\n name: string;\n connectorId: string;\n authType: string;\n status: string;\n accountLabel: string | null;\n /** Required secret fields with no stored ref, by auth property name. */\n missingSecrets: string[];\n /** Required config fields with no value, by auth property name. */\n missingConfig: string[];\n}\n\n/**\n * Every connection document with its credential state compared against the\n * piece's auth plan. Only field names and opaque refs are surfaced; secret\n * values never do.\n */\nexport async function getConnections(): Promise<{\n connections: ConnectionDetail[];\n}> {\n syncRuntimeUrl();\n const [catalog, summaries] = await Promise.all([\n fetchPieceCatalog(),\n fetchConnections(),\n ]);\n const client = getPHStore()?.reactorClient;\n const connections = await Promise.all(\n summaries.map(async (summary) => {\n const piece = catalog.find(\n (entry) => entry.name === packageFromConnectorId(summary.connectorId),\n );\n const plan = planFromAuth(piece?.auth ?? null);\n let state: ConnectionState | undefined;\n if (client) {\n try {\n const document = await client.get(summary.id);\n state = (document.state as { global?: ConnectionState }).global;\n } catch {\n state = undefined;\n }\n }\n const refNames = new Set(\n (state?.secretRefs ?? []).map((ref) => ref.name),\n );\n const config = (state?.config ?? {}) as Record<string, unknown>;\n return {\n id: summary.id,\n name: summary.name,\n connectorId: summary.connectorId,\n authType: summary.authType,\n status: summary.status,\n accountLabel: summary.accountLabel,\n missingSecrets: plan.secretFields\n .filter((field) => field.required && !refNames.has(field.name))\n .map((field) => field.name),\n missingConfig: plan.configFields\n .filter(\n (field) =>\n field.required && isConfigValueMissing(config[field.name]),\n )\n .map((field) => field.name),\n };\n }),\n );\n return { connections };\n}\n\nconst READ_ONLY = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\nexport const getConnectorsTool: PhAiToolDescriptor = {\n name: \"getConnectors\",\n description:\n 'Lists the connectors (pieces) available to the workflow runtime with their auth fields, actions, and triggers. Without a query it returns up to 20 connectors; pass `query` to search, best match first: words can name the piece or what it does (e.g. \"slack send message\"), in any order, and small typos are tolerated. Secret fields are listed by name only, never by value.',\n inputSchema: { query: z.string().optional() },\n annotations: { title: \"Get Connectors\", ...READ_ONLY },\n callback: (args: { query?: string }) => getConnectors(args.query),\n};\n\nexport const getConnectionsTool: PhAiToolDescriptor = {\n name: \"getConnections\",\n description:\n \"Lists the project's connection documents with their credential status: which required secrets and config values are still missing, and the last account label. Secret values are never included. A connection with authType REACTOR is bound through a step's or trigger's reactorConnectionId, never connectionId.\",\n inputSchema: {},\n annotations: { title: \"Get Connections\", ...READ_ONLY },\n callback: () => getConnections(),\n};\n\nexport const checkConnectionTool: PhAiToolDescriptor = {\n name: \"checkConnection\",\n description:\n \"Runs a connection's own check against its stored credentials to verify they work. Takes a connection id (from getConnections) and reports success, the failure detail, and the account label when the provider returns one.\",\n inputSchema: { connectionId: z.string() },\n annotations: { title: \"Check Connection\", ...READ_ONLY },\n callback: (args: { connectionId: string }) => {\n syncRuntimeUrl();\n return runConnectionCheck(args.connectionId);\n },\n};\n\n/** Tool descriptors the host app offers the AI assistant. */\nexport const aiTools: PhAiToolDescriptor[] = [\n getConnectorsTool,\n getConnectionsTool,\n checkConnectionTool,\n ...workflowTools,\n];\n","/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport type { EditorModule } from \"document-model\";\nimport { ConnectionEditor } from \"./connection-editor/module.js\";\nimport { WorkflowEditor } from \"./workflow-editor/module.js\";\nimport { WorkflowStudio } from \"./workflow-studio/module.js\";\n\nexport const editors: EditorModule[] = [\n ConnectionEditor,\n WorkflowEditor,\n WorkflowStudio,\n];\n","import type { Manifest } from \"document-model\";\nimport manifestJson from \"./powerhouse.manifest.json\" with { type: \"json\" };\n\nexport { aiTools } from \"./ai/tools.js\";\nexport { documentModels } from \"./document-models/document-models.js\";\nexport { upgradeManifests } from \"./document-models/upgrade-manifests.js\";\nexport { editors } from \"./editors/editors.js\";\nexport const manifest = manifestJson as Manifest;\n"],"mappings":";;;;;;;;;;;;;AAkBA,IAAI,UAAyB,oBAAoB,mBAAmB;AAEpE,MAAM,iBAAiB,yBAAyB;AAEhD,SAAgB,cAAc,KAAmB;CAC/C,IAAI,QAAQ,QAAQ,KAAK,UAAU,oBAAoB,GAAG;AAC5D;AAEA,MAAa,gBAAgB,UAC3B,eAAe,WAAW,eAAe,SAAS,KAAK,CAAC;AAC1D,MAAa,0BACX,eAAe,WAAW,aAAa,OAAO,CAAC;AACjD,MAAa,qBAAqB,gBAChC,QAAQ,kBAAkB,WAAW;AACvC,MAAa,sBAAsB,gBACjC,QAAQ,mBAAmB,WAAW;AACxC,MAAa,gBACX,OACA,WACG,QAAQ,aAAa,OAAO,MAAM;AACvC,MAAa,yBAAyB,QAAQ,iBAAiB;AAC/D,MAAa,mBAAmB,iBAC9B,QAAQ,gBAAgB,YAAY;AACtC,MAAa,aAAa,UAAsB,QAAQ,UAAU,KAAK;AACvE,MAAa,gBAAgB,YAAoB,YAC/C,QAAQ,aAAa,YAAY,OAAO;;;AClC1C,MAAM,+BAAe,IAAI,IAAY;AAErC,SAAgB,iBAAuB;CACrC,IAAI,OAAO,WAAW,aAAa;CACnC,MAAM,UAAU,WAAW,CAAC,EAAE;CAC9B,MAAM,cAAc,wBAAwB,OAAO;CAGnD,IAAI,CAAC,eAAe,WAAW,CAAC,aAAa,IAAI,OAAO,GAAG;EAIzD,aAAa,IAAI,OAAO;EACxB,QAAQ,KACN,qBAAqB,QAAQ,uEAAuE,oB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Q;GACd,aAAa,QAAQ;GACrB,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB,cAAc,QAAQ;GACtB,gBAAgB,KAAK,aAClB,QAAQ,UAAU,MAAM,YAAY,CAAC,SAAS,IAAI,MAAM,IAAI,CAAC,CAAC,CAC9D,KAAK,UAAU,MAAM,IAAI;GAC5B,eAAe,KAAK,aACjB,QACE,UACC,MAAM,YAAY,qBAAqB,OAAO,MAAM,KAAK,CAC7D,CAAC,CACA,KAAK,UAAU,MAAM,IAAI;EAC9B;CACF,CAAC,CACH,EACqB;AACvB;AAEA,MAAM,YAAY;CAChB,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,eAAe;AACjB;;AAiCA,MAAa,UAAgC;CAC3C;EA/BA,MAAM;EACN,aACE;EACF,aAAa,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS,EAAE;EAC5C,aAAa;GAAE,OAAO;GAAkB,GAAG;EAAU;EACrD,WAAW,SAA6B,cAAc,KAAK,KAAK;CA0BhE;CACA;EAvBA,MAAM;EACN,aACE;EACF,aAAa,CAAC;EACd,aAAa;GAAE,OAAO;GAAmB,GAAG;EAAU;EACtD,gBAAgB,eAAe;CAkB/B;CACA;EAfA,MAAM;EACN,aACE;EACF,aAAa,EAAE,cAAc,EAAE,OAAO,EAAE;EACxC,aAAa;GAAE,OAAO;GAAoB,GAAG;EAAU;EACvD,WAAW,SAAmC;GAC5C,eAAe;GACf,OAAOC,gBAAmB,KAAK,YAAY;EAC7C;CAOA;CACA,GAAG;AACL;;;ACrQA,MAAa,UAA0B;CACrC;CACA;CACA;AACF;;;ACNA,MAAa,WAAWC"}
1
+ {"version":3,"file":"index.js","names":["READ_ONLY","manifestJson"],"sources":["../../editors/workflow-editor/runtime-api.ts","../../ai/runtime.ts","../../ai/workflow-tools.ts","../../ai/tools.ts","../../editors/editors.ts","../../index.ts"],"sourcesContent":["// The AI tools' runtime: tools run outside any editor, so each call names the\n// switchboard it asks. Editors never import this: each one gets its own client\n// from RuntimeProvider.\nimport type { BlockRef } from \"@powerhousedao/pieces-framework/block-type\";\nimport type { SwitchboardEntry } from \"@powerhousedao/reactor-browser\";\nimport {\n createRuntimeClient,\n workflowRuntimeUrl,\n type RuntimeClient,\n type RuntimeClientOptions,\n} from \"./runtime-client.js\";\nimport {\n blockFormQuery,\n catalogQuery,\n createRuntimeQueryClient,\n} from \"./runtime-queries.js\";\n\nexport type * from \"./runtime-client.js\";\n\n// Keys start with the URL, so every switchboard has its own entries.\nconst queries = createRuntimeQueryClient();\n\n/** One switchboard's runtime, for one tool call. */\nexport interface AiRuntime {\n switchboard: SwitchboardEntry;\n client: RuntimeClient;\n getBlockForm(block: BlockRef): ReturnType<typeof fetchBlockForm>;\n fetchPieceCatalog(): ReturnType<typeof fetchCatalog>;\n}\n\nfunction fetchBlockForm(client: RuntimeClient, block: BlockRef) {\n return queries.fetchQuery(blockFormQuery(client, block));\n}\n\nfunction fetchCatalog(client: RuntimeClient) {\n return queries.fetchQuery(catalogQuery(client));\n}\n\n/** The runtime of `switchboard`; the catalog and block forms are cached per URL. */\nexport function runtimeAt(\n switchboard: SwitchboardEntry,\n options: RuntimeClientOptions = {},\n): AiRuntime {\n const client = createRuntimeClient(workflowRuntimeUrl(switchboard), options);\n return {\n switchboard,\n client,\n getBlockForm: (block) => fetchBlockForm(client, block),\n fetchPieceCatalog: () => fetchCatalog(client),\n };\n}\n","// Which switchboard a workflow tool asks: the one named, the one serving the\n// document the call is about, else the only one that runs workflows. The host\n// hands its switchboard directory to every call (AiToolContext); there is no\n// default URL to fall back on.\nimport { resolveSwitchboard } from \"@powerhousedao/reactor-browser\";\nimport type { AiToolContext } from \"@powerhousedao/reactor-browser/ai\";\nimport type { PhAiToolContext } from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\nimport {\n runtimeAt,\n type AiRuntime,\n} from \"../editors/workflow-editor/runtime-api.js\";\n\n/** The `switchboard` input every workflow tool takes. */\nexport const switchboardInput = z\n .string()\n .optional()\n .describe(\n \"The switchboard to ask: a name or URL from listSwitchboards. Omit when only one switchboard runs workflows.\",\n );\n\nexport interface RuntimeRequest {\n switchboard?: string;\n /** The workflow, connection or drive the call is about. */\n documentId?: string;\n}\n\n/** The workflow runtime a tool call goes to; throws when none can be picked. */\nexport async function runtimeFor(\n context: PhAiToolContext | undefined,\n request: RuntimeRequest = {},\n): Promise<AiRuntime> {\n const { switchboards, signal } = (context ?? {}) as AiToolContext;\n const switchboard = await resolveSwitchboard(switchboards, {\n switchboard: request.switchboard,\n documentId: request.documentId,\n need: \"workflows\",\n signal,\n });\n return runtimeAt(switchboard, { signal });\n}\n","// AI tool descriptors for authoring and running workflows: the pinned blocks\n// a piece offers, a block's config props, the built-in core blocks with\n// the expression syntax, run history and manual firing. Complements the\n// connector/connection tools in tools.ts, which cover the catalog and auth.\nimport type {\n PhAiToolContext,\n PhAiToolDescriptor,\n} from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\nimport type { BlockFormProp } from \"../editors/workflow-editor/ui/forms.js\";\nimport { REACTOR_CONNECTOR_ID } from \"../document-models/connection/v1/src/reactor-connection.js\";\nimport {\n CORE_PIECE,\n REACTOR_PIECE,\n type BlockRef,\n} from \"../editors/workflow-editor/ui/blocks.js\";\nimport { runtimeFor, switchboardInput } from \"./runtime.js\";\nimport { flowPorts } from \"@powerhousedao/pieces-framework/workflow\";\n\nconst READ_ONLY = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\nfunction kindOf(block: BlockRef): \"trigger\" | \"step\" {\n return block.kind === \"trigger\" ? \"trigger\" : \"step\";\n}\n\n// The fields ADD_STEP or SET_TRIGGER takes for the block.\nfunction blockFields(block: BlockRef) {\n return {\n pieceName: block.pieceName,\n pieceVersion: block.pieceVersion,\n ...(block.kind === \"trigger\"\n ? { triggerName: block.name }\n : { actionName: block.name }),\n };\n}\n\n// The onward ports the block's descriptor declares; \"error\" is a failure route.\nfunction portsFor(form: { ports?: readonly string[] }): string[] {\n return flowPorts(form.ports ?? []);\n}\n\nfunction describeProp(prop: BlockFormProp) {\n return {\n name: prop.name,\n label: prop.displayName,\n type: prop.type,\n required: prop.required,\n ...(prop.description ? { description: prop.description } : {}),\n ...(prop.defaultValue !== undefined ? { default: prop.defaultValue } : {}),\n ...(prop.staticOptions\n ? { options: prop.staticOptions.map((option) => option.value) }\n : {}),\n ...(prop.hasDynamicResolver ? { dynamicOptions: true } : {}),\n };\n}\n\nconst EXPRESSIONS = [\n \"Step configs and edge conditions may contain expressions in double braces.\",\n \"{{trigger.payload.<field>}} reads the trigger payload: for the core manual trigger the payload passed to fireWorkflow; for the reactor piece's document triggers it carries documentId, documentType, driveId and name.\",\n \"{{steps.<key>.output.<path>}} reads an upstream step's output by that step's key, e.g. {{steps.fetch.output.body.title}}.\",\n \"The reactor piece's document-create and document-dispatch output a reference { documentId, documentType, branch, revision }, e.g. {{steps.create.output.documentId}}; read the document with document-get to use its state. document-get outputs the document as { header, state }, e.g. {{steps.get.output.state.global.name}} or {{steps.get.output.header.id}}. document-find outputs { results, nextCursor }: each result has a header (and state with includeState), and nextCursor, present while more match, goes in a later find's cursor.\",\n \"{{variables.<key>}} reads a workflow variable.\",\n \"'a' || 'b' picks the first non-empty value, e.g. {{trigger.payload.url || 'https://example.com'}}.\",\n \"A whole-string expression yields the raw value; text around expressions is interpolated.\",\n];\n\nconst GRAPH_RULES = [\n \"A workflow is a powerhouse/workflow document. Build it with SET_TRIGGER once, ADD_STEP per step (each with a unique id and key), and ADD_EDGE from the trigger id to the first step and between steps.\",\n \"An edge must leave on a port its source declares (getWorkflowBlockConfig lists them): 'next' for the trigger and ordinary steps, 'true' and 'false' for the core branch action, 'error' to route a failure. An edge on any other port is never taken, and the run is flagged with a warning.\",\n \"A step names its block with pieceName, pieceVersion and actionName; the trigger with pieceName, pieceVersion and triggerName. pieceVersion is an exact semver: copy the fields getWorkflowPieceBlocks or listWorkflowCoreBlocks return.\",\n `The built-in blocks (manual, schedule and webhook triggers, branch and assert) belong to the piece ${CORE_PIECE}.`,\n \"The core router's ports follow its config: 'branch_1' … 'branch_N', one per entry of its branches list in order, then 'otherwise'. The core loop leaves on 'each' into its body, which runs once per item and must not lead out of the body, and on 'next' after the last item; body steps read {{steps.<loop key>.output.item}} and .index.\",\n \"Steps whose piece needs a connection must set connectionId to a powerhouse/connection document id (see getConnections).\",\n `Every step and trigger whose block reports requireReactor (getWorkflowBlockConfig) must set reactorConnectionId to a powerhouse/connection document with authType REACTOR and connectorId ${REACTOR_CONNECTOR_ID} (see getConnections); the ${REACTOR_PIECE} blocks all do. Without one the block gets no reactor access and fails. The connection's config { endpoint: \"local\", access?: \"read\", filter?: { documentType?, documentId?, driveId?, actionType? } } limits which documents it reads and writes. connectionId stays for credentials; a document block normally needs none.`,\n \"Runs execute the published snapshot, not the draft. PUBLISH_WORKFLOW only snapshots the draft, so publish again after every edit that should run.\",\n \"Only ENABLED workflows get trigger instances and can be fired. PUBLISH_WORKFLOW does not enable: to turn a workflow on, dispatch SET_WORKFLOW_STATUS ENABLED after PUBLISH_WORKFLOW (the same batch works). SET_WORKFLOW_STATUS ENABLED is refused until the workflow has been published once.\",\n];\n\nexport const getWorkflowPieceBlocksTool: PhAiToolDescriptor = {\n name: \"getWorkflowPieceBlocks\",\n description:\n \"Lists the actions and triggers of one piece, each with the pieceName, pieceVersion and actionName or triggerName to use in ADD_STEP or SET_TRIGGER. Takes the piece package name from getConnectors. Call getWorkflowBlockConfig next for a block's config props.\",\n inputSchema: {\n packageName: z\n .string()\n .describe(\"Piece package name, e.g. @activepieces/piece-http.\"),\n switchboard: switchboardInput,\n },\n annotations: { title: \"Get Workflow Piece Blocks\", ...READ_ONLY },\n callback: async (\n args: { packageName: string; switchboard?: string },\n context?: PhAiToolContext,\n ) => {\n const { client, switchboard } = await runtimeFor(context, {\n switchboard: args.switchboard,\n });\n const [actions, triggers] = await Promise.all([\n client.fetchPieceActions(args.packageName),\n client.fetchPieceTriggers(args.packageName),\n ]);\n return {\n switchboard: switchboard.name,\n packageName: args.packageName,\n actions: actions.map((action) => ({\n pieceName: action.pieceName,\n pieceVersion: action.pieceVersion,\n actionName: action.name,\n displayName: action.displayName,\n description: action.description,\n })),\n triggers: triggers.map((trigger) => ({\n pieceName: trigger.pieceName,\n pieceVersion: trigger.pieceVersion,\n triggerName: trigger.name,\n displayName: trigger.displayName,\n description: trigger.description,\n strategy: trigger.strategy,\n })),\n };\n },\n};\n\nexport const getWorkflowBlockConfigTool: PhAiToolDescriptor = {\n name: \"getWorkflowBlockConfig\",\n description:\n \"Describes the config of one block (a core block or a piece's action or trigger): prop names, types, whether required, allowed options, the output ports, whether a connection is needed, and requireReactor (read | write) when it needs a reactor connection. Use it before writing a step or trigger config.\",\n inputSchema: {\n pieceName: z\n .string()\n .describe(\n `Piece package name, e.g. ${CORE_PIECE} or @activepieces/piece-http.`,\n ),\n pieceVersion: z.string().describe(\"Exact semver of the piece.\"),\n name: z\n .string()\n .describe(\"Action or trigger name, e.g. branch or send_request.\"),\n kind: z.enum([\"action\", \"trigger\"]).describe(\"action or trigger.\"),\n switchboard: switchboardInput,\n },\n annotations: { title: \"Get Workflow Block Config\", ...READ_ONLY },\n callback: async (\n args: BlockRef & { switchboard?: string },\n context?: PhAiToolContext,\n ) => {\n const block: BlockRef = {\n pieceName: args.pieceName,\n pieceVersion: args.pieceVersion,\n name: args.name,\n kind: args.kind,\n };\n const runtime = await runtimeFor(context, {\n switchboard: args.switchboard,\n });\n const form = await runtime.getBlockForm(block);\n if (!form) {\n return {\n switchboard: runtime.switchboard.name,\n ...blockFields(block),\n error:\n \"Unknown block. Use getConnectors and getWorkflowPieceBlocks to find valid blocks (documents live in @powerhousedao/piece-reactor), or listWorkflowCoreBlocks for built-ins.\",\n };\n }\n return {\n switchboard: runtime.switchboard.name,\n ...blockFields(block),\n title: form.title,\n kind: kindOf(block),\n requiresConnection: form.auth === \"required\",\n // read | write: the block needs a reactorConnectionId granting this.\n requireReactor: form.requireReactor ?? null,\n props: form.props.map(describeProp),\n ports: portsFor(form),\n };\n },\n};\n\nexport const listWorkflowCoreBlocksTool: PhAiToolDescriptor = {\n name: \"listWorkflowCoreBlocks\",\n description: `Lists the built-in blocks of the ${CORE_PIECE} piece (manual, schedule and webhook triggers, branch and assert) with their pinned fields and config props, plus the expression syntax and the rules for building a powerhouse/workflow document. Documents are read and written by the @powerhousedao/piece-reactor blocks; list those with getWorkflowPieceBlocks.`,\n inputSchema: { switchboard: switchboardInput },\n annotations: { title: \"List Workflow Core Blocks\", ...READ_ONLY },\n callback: async (\n args: { switchboard?: string },\n context?: PhAiToolContext,\n ) => {\n const runtime = await runtimeFor(context, {\n switchboard: args.switchboard,\n });\n // The reactor serves the core piece's descriptors, as it does any piece's.\n const [actions, triggers] = await Promise.all([\n runtime.client.fetchPieceActions(CORE_PIECE),\n runtime.client.fetchPieceTriggers(CORE_PIECE),\n ]);\n const blocks: BlockRef[] = [\n ...triggers.map((entry) => ({ ...entry, kind: \"trigger\" as const })),\n ...actions.map((entry) => ({ ...entry, kind: \"action\" as const })),\n ].map((entry) => ({\n pieceName: entry.pieceName,\n pieceVersion: entry.pieceVersion,\n name: entry.name,\n kind: entry.kind,\n }));\n const forms = await Promise.all(\n blocks.map((block) => runtime.getBlockForm(block)),\n );\n return {\n switchboard: runtime.switchboard.name,\n blocks: blocks.flatMap((block, index) => {\n const form = forms[index];\n if (!form) return [];\n return [\n {\n ...blockFields(block),\n title: form.title,\n kind: kindOf(block),\n props: form.props.map(describeProp),\n ports: portsFor(form),\n },\n ];\n }),\n expressions: EXPRESSIONS,\n rules: GRAPH_RULES,\n };\n },\n};\n\nexport const listWorkflowRunsTool: PhAiToolDescriptor = {\n name: \"listWorkflowRuns\",\n description:\n \"Lists recent workflow runs, newest first, with status, error and each step's outcome. Filter by workflowId to inspect one workflow, or by driveId for every workflow in a drive.\",\n inputSchema: {\n workflowId: z\n .string()\n .optional()\n .describe(\"Workflow document id to filter by.\"),\n driveId: z\n .string()\n .optional()\n .describe(\"Drive id to filter by (all workflows in that drive).\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .describe(\"Maximum runs to return (default 10).\"),\n switchboard: switchboardInput,\n },\n annotations: { title: \"List Workflow Runs\", ...READ_ONLY },\n callback: async (\n args: {\n workflowId?: string;\n driveId?: string;\n limit?: number;\n switchboard?: string;\n },\n context?: PhAiToolContext,\n ) => {\n const { client, switchboard } = await runtimeFor(context, {\n switchboard: args.switchboard,\n documentId: args.workflowId ?? args.driveId,\n });\n const runs = await client.fetchRuns({\n workflowId: args.workflowId,\n driveId: args.driveId,\n limit: args.limit ?? 10,\n });\n return {\n switchboard: switchboard.name,\n runs: runs.map((run) => ({\n id: run.id,\n workflowId: run.workflowId,\n workflowName: run.workflowName,\n status: run.status,\n error: run.error,\n triggerKind: run.triggerKind,\n startedAt: run.startedAt,\n endedAt: run.endedAt,\n steps: run.steps.map((step) => ({\n key: step.stepKey,\n status: step.status,\n error: step.error,\n })),\n })),\n };\n },\n};\n\nexport const fireWorkflowTool: PhAiToolDescriptor = {\n name: \"fireWorkflow\",\n description:\n \"Fires an ENABLED workflow whose trigger is the core manual trigger and runs its published snapshot to completion. The payload becomes {{trigger.payload}}. Returns the run id and final status.\",\n inputSchema: {\n workflowId: z.string().describe(\"Workflow document id.\"),\n payload: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Trigger payload object.\"),\n switchboard: switchboardInput,\n },\n annotations: {\n title: \"Fire Workflow\",\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n callback: async (\n args: {\n workflowId: string;\n payload?: Record<string, unknown>;\n switchboard?: string;\n },\n context?: PhAiToolContext,\n ) => {\n const { client, switchboard } = await runtimeFor(context, {\n switchboard: args.switchboard,\n documentId: args.workflowId,\n });\n return {\n switchboard: switchboard.name,\n ...(await client.fireWorkflow(args.workflowId, args.payload ?? {})),\n };\n },\n};\n\n/** Workflow authoring and run tools, merged into `aiTools` in tools.ts. */\nexport const workflowTools: PhAiToolDescriptor[] = [\n getWorkflowPieceBlocksTool,\n getWorkflowBlockConfigTool,\n listWorkflowCoreBlocksTool,\n listWorkflowRunsTool,\n fireWorkflowTool,\n];\n","// Read-only AI tool descriptors for the Connect assistant: the project's\n// piece catalog, connection documents, and connection health. The `aiTools`\n// export is how the host app discovers this package's tools (the line in the\n// project index is synced by `ph generate`).\nimport type { ReactorBrowserHalves } from \"@powerhousedao/reactor-browser\";\nimport type { AiToolContext } from \"@powerhousedao/reactor-browser/ai\";\nimport type {\n PhAiToolContext,\n PhAiToolDescriptor,\n} from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\nimport {\n connectorIdForPiece,\n isConfigValueMissing,\n packageFromConnectorId,\n planFromAuth,\n type AuthField,\n} from \"../editors/connection-editor/piece-auth.js\";\nimport type {\n AiRuntime,\n PieceSummary,\n} from \"../editors/workflow-editor/runtime-api.js\";\nimport { runtimeFor, switchboardInput } from \"./runtime.js\";\nimport { workflowTools } from \"./workflow-tools.js\";\n\nconst MAX_CONNECTORS = 20;\n\nexport interface ConnectorField {\n name: string;\n label: string;\n required: boolean;\n description?: string;\n secret: boolean;\n}\n\nexport interface ConnectorDetail {\n connectorId: string;\n pieceName: string;\n displayName: string;\n description: string;\n version: string;\n authType: string;\n /** False for auth kinds the runtime cannot execute yet (OIDC). */\n supported: boolean;\n /** OAUTH2: a person finishes it by signing in from the connection editor. */\n signIn?: \"oauth2\";\n fields: ConnectorField[];\n actions: string[];\n triggers: string[];\n}\n\nfunction toField(field: AuthField, secret: boolean): ConnectorField {\n return {\n name: field.name,\n label: field.displayName,\n required: field.required,\n description: field.description,\n secret,\n };\n}\n\nasync function connectorDetail(\n runtime: AiRuntime,\n piece: PieceSummary,\n): Promise<ConnectorDetail> {\n const plan = planFromAuth(piece.auth);\n const [actions, triggers] = await Promise.all([\n runtime.client.fetchPieceActions(piece.name),\n runtime.client.fetchPieceTriggers(piece.name),\n ]);\n return {\n connectorId: connectorIdForPiece(piece.name),\n pieceName: piece.name,\n displayName: piece.displayName,\n description: piece.description,\n version: piece.version,\n authType: plan.authType,\n supported: plan.supported,\n ...(plan.oauth2 ? { signIn: \"oauth2\" as const } : {}),\n fields: [\n ...plan.configFields.map((field) => toField(field, false)),\n ...plan.secretFields.map((field) => toField(field, true)),\n ],\n actions: actions.map((action) => action.name),\n triggers: triggers.map((trigger) => trigger.name),\n };\n}\n\n// Pieces the runtime's search ranks for the query, actions' and triggers'\n// rankings interleaved; null while its index builds, where it has none, or\n// when it ranks nothing (a package name, say).\nasync function rankedPieces(\n runtime: AiRuntime,\n catalog: PieceSummary[],\n query: string,\n): Promise<PieceSummary[] | null> {\n let results;\n try {\n results = await Promise.all(\n ([\"action\", \"trigger\"] as const).map((kind) =>\n runtime.client.searchPieces(query, { kind, limit: 50 }),\n ),\n );\n } catch {\n return null;\n }\n if (results.some((result) => result.status !== \"ready\")) return null;\n const byName = new Map(catalog.map((piece) => [piece.name, piece]));\n const ranked = new Map<string, PieceSummary>();\n const longest = Math.max(...results.map((result) => result.pieces.length));\n for (let rank = 0; rank < longest; rank++) {\n for (const result of results) {\n const name = result.pieces.at(rank)?.pieceName;\n const piece = name === undefined ? undefined : byName.get(name);\n if (piece && !ranked.has(piece.name)) ranked.set(piece.name, piece);\n }\n }\n return ranked.size > 0 ? [...ranked.values()] : null;\n}\n\n/**\n * Stage one of connector discovery: the catalog, optionally narrowed by the\n * runtime's piece search (a substring match while its index builds), capped\n * at {@link MAX_CONNECTORS}. Full auth/action/trigger detail is fetched only\n * for the surviving entries (stage two).\n */\nexport async function getConnectors(\n runtime: AiRuntime,\n query?: string,\n): Promise<{\n switchboard: string;\n total: number;\n matches: number;\n truncated: boolean;\n connectors: ConnectorDetail[];\n}> {\n const catalog = await runtime.fetchPieceCatalog();\n const needle = query?.trim().toLowerCase();\n // A package name is an answer, not a search.\n const exact = catalog.filter((piece) => piece.name.toLowerCase() === needle);\n const matches = !needle\n ? [...catalog]\n : exact.length > 0\n ? exact\n : ((await rankedPieces(runtime, catalog, needle)) ??\n catalog.filter((piece) =>\n [piece.name, piece.displayName, piece.description].some((field) =>\n field.toLowerCase().includes(needle),\n ),\n ));\n const page = matches.slice(0, MAX_CONNECTORS);\n const connectors = await Promise.all(\n page.map((piece) => connectorDetail(runtime, piece)),\n );\n return {\n switchboard: runtime.switchboard.name,\n total: catalog.length,\n matches: matches.length,\n truncated: matches.length > page.length,\n connectors,\n };\n}\n\ninterface ConnectionState {\n config?: unknown;\n secretRefs?: { name: string }[];\n}\n\nexport interface ConnectionDetail {\n id: string;\n name: string;\n connectorId: string;\n authType: string;\n status: string;\n accountLabel: string | null;\n /** Required secret fields with no stored ref, by auth property name. */\n missingSecrets: string[];\n /** Required config fields with no value, by auth property name. */\n missingConfig: string[];\n}\n\n/**\n * Every connection document with its credential state compared against the\n * piece's auth plan. Only field names and opaque refs are surfaced; secret\n * values never do.\n */\nexport async function getConnections(\n runtime: AiRuntime,\n reactor?: ReactorBrowserHalves,\n): Promise<{\n switchboard: string;\n connections: ConnectionDetail[];\n}> {\n const [catalog, summaries] = await Promise.all([\n runtime.fetchPieceCatalog(),\n runtime.client.fetchConnections(),\n ]);\n const connections = await Promise.all(\n summaries.map(async (summary) => {\n const piece = catalog.find(\n (entry) => entry.name === packageFromConnectorId(summary.connectorId),\n );\n const plan = planFromAuth(piece?.auth ?? null);\n let state: ConnectionState | undefined;\n if (reactor) {\n try {\n const document = await reactor.read.get(summary.id);\n state = (document.state as { global?: ConnectionState }).global;\n } catch {\n state = undefined;\n }\n }\n const refNames = new Set(\n (state?.secretRefs ?? []).map((ref) => ref.name),\n );\n const config = (state?.config ?? {}) as Record<string, unknown>;\n return {\n id: summary.id,\n name: summary.name,\n connectorId: summary.connectorId,\n authType: summary.authType,\n status: summary.status,\n accountLabel: summary.accountLabel,\n missingSecrets: plan.secretFields\n .filter((field) => field.required && !refNames.has(field.name))\n .map((field) => field.name),\n missingConfig: plan.configFields\n .filter(\n (field) =>\n field.required && isConfigValueMissing(config[field.name]),\n )\n .map((field) => field.name),\n };\n }),\n );\n return { switchboard: runtime.switchboard.name, connections };\n}\n\nconst READ_ONLY = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n} as const;\n\nexport const getConnectorsTool: PhAiToolDescriptor = {\n name: \"getConnectors\",\n description:\n 'Lists the connectors (pieces) available to the workflow runtime with their auth fields, actions, and triggers. Without a query it returns up to 20 connectors; pass `query` to search, best match first: words can name the piece or what it does (e.g. \"slack send message\"), in any order, and small typos are tolerated. Secret fields are listed by name only, never by value.',\n inputSchema: { query: z.string().optional(), switchboard: switchboardInput },\n annotations: { title: \"Get Connectors\", ...READ_ONLY },\n callback: async (\n args: { query?: string; switchboard?: string },\n context?: PhAiToolContext,\n ) =>\n getConnectors(\n await runtimeFor(context, { switchboard: args.switchboard }),\n args.query,\n ),\n};\n\nexport const getConnectionsTool: PhAiToolDescriptor = {\n name: \"getConnections\",\n description:\n \"Lists the project's connection documents with their credential status: which required secrets and config values are still missing, and the last account label. Secret values are never included. A connection with authType REACTOR is bound through a step's or trigger's reactorConnectionId, never connectionId.\",\n inputSchema: { switchboard: switchboardInput },\n annotations: { title: \"Get Connections\", ...READ_ONLY },\n callback: async (args: { switchboard?: string }, context?: PhAiToolContext) =>\n getConnections(\n await runtimeFor(context, { switchboard: args.switchboard }),\n (context as AiToolContext | undefined)?.reactor,\n ),\n};\n\nexport const checkConnectionTool: PhAiToolDescriptor = {\n name: \"checkConnection\",\n description:\n \"Runs a connection's own check against its stored credentials to verify they work. Takes a connection id (from getConnections) and reports success, the failure detail, and the account label when the provider returns one.\",\n inputSchema: { connectionId: z.string(), switchboard: switchboardInput },\n annotations: { title: \"Check Connection\", ...READ_ONLY },\n callback: async (\n args: { connectionId: string; switchboard?: string },\n context?: PhAiToolContext,\n ) => {\n const runtime = await runtimeFor(context, {\n switchboard: args.switchboard,\n documentId: args.connectionId,\n });\n return {\n switchboard: runtime.switchboard.name,\n ...(await runtime.client.checkConnection(args.connectionId)),\n };\n },\n};\n\n/** Tool descriptors the host app offers the AI assistant. */\nexport const aiTools: PhAiToolDescriptor[] = [\n getConnectorsTool,\n getConnectionsTool,\n checkConnectionTool,\n ...workflowTools,\n];\n","/**\n * WARNING: DO NOT EDIT\n * This file is auto-generated and updated by codegen\n */\nimport type { EditorModule } from \"document-model\";\nimport { ConnectionEditor } from \"./connection-editor/module.js\";\nimport { WorkflowEditor } from \"./workflow-editor/module.js\";\nimport { WorkflowStudio } from \"./workflow-studio/module.js\";\n\nexport const editors: EditorModule[] = [\n ConnectionEditor,\n WorkflowEditor,\n WorkflowStudio,\n];\n","import type { Manifest } from \"document-model\";\nimport manifestJson from \"./powerhouse.manifest.json\" with { type: \"json\" };\n\nexport { aiTools } from \"./ai/tools.js\";\nexport { documentModels } from \"./document-models/document-models.js\";\nexport { upgradeManifests } from \"./document-models/upgrade-manifests.js\";\nexport { editors } from \"./editors/editors.js\";\nexport const manifest = manifestJson as Manifest;\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAM,UAAU,yBAAyB;AAUzC,SAAS,eAAe,QAAuB,OAAiB;CAC9D,OAAO,QAAQ,WAAW,eAAe,QAAQ,KAAK,CAAC;AACzD;AAEA,SAAS,aAAa,QAAuB;CAC3C,OAAO,QAAQ,WAAW,aAAa,MAAM,CAAC;AAChD;;AAGA,SAAgB,UACd,aACA,UAAgC,CAAC,GACtB;CACX,MAAM,SAAS,oBAAoB,mBAAmB,WAAW,GAAG,OAAO;CAC3E,OAAO;EACL;EACA;EACA,eAAe,UAAU,eAAe,QAAQ,KAAK;EACrD,yBAAyB,aAAa,MAAM;CAC9C;AACF;;;;ACpCA,MAAa,mBAAmB,EAC7B,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SACC,6GACF;;AASF,eAAsB,WACpB,SACA,UAA0B,CAAC,GACP;CACpB,MAAM,EAAE,cAAc,WAAY,WAAW,CAAC;CAO9C,OAAO,UAAU,MANS,mBAAmB,cAA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c;CACd,iBAAiB;CACjB,gBAAgB;CAChB,eAAe;AACjB;;AAqDA,MAAa,UAAgC;CAC3C;EAnDA,MAAM;EACN,aACE;EACF,aAAa;GAAE,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;GAAG,aAAa;EAAiB;EAC3E,aAAa;GAAE,OAAO;GAAkB,GAAG;EAAU;EACrD,UAAU,OACR,MACA,YAEA,cACE,MAAM,WAAW,SAAS,EAAE,aAAa,KAAK,YAAY,CAAC,GAC3D,KAAK,KACP;CAuCF;CACA;EApCA,MAAM;EACN,aACE;EACF,aAAa,EAAE,aAAa,iBAAiB;EAC7C,aAAa;GAAE,OAAO;GAAmB,GAAG;EAAU;EACtD,UAAU,OAAO,MAAgC,YAC/C,eACE,MAAM,WAAW,SAAS,EAAE,aAAa,KAAK,YAAY,CAAC,GAC1D,SAAuC,OAC1C;CA2BF;CACA;EAxBA,MAAM;EACN,aACE;EACF,aAAa;GAAE,cAAc,EAAE,OAAO;GAAG,aAAa;EAAiB;EACvE,aAAa;GAAE,OAAO;GAAoB,GAAG;EAAU;EACvD,UAAU,OACR,MACA,YACG;GACH,MAAM,UAAU,MAAM,WAAW,SAAS;IACxC,aAAa,KAAK;IAClB,YAAY,KAAK;GACnB,CAAC;GACD,OAAO;IACL,aAAa,QAAQ,YAAY;IACjC,GAAI,MAAM,QAAQ,OAAO,gBAAgB,KAAK,YAAY;GAC5D;EACF;CAOA;CACA,GAAG;AACL;;;ACpSA,MAAa,UAA0B;CACrC;CACA;CACA;AACF;;;ACNA,MAAa,WAAWC"}
@@ -296,19 +296,22 @@ const STEP_PRESETS = [
296
296
  ];
297
297
  //#endregion
298
298
  //#region editors/workflow-editor/runtime-client.ts
299
- const DEFAULT_RUNTIME_URL = "http://localhost:4001/graphql/workflow-runtime";
299
+ /** A switchboard's workflow-runtime subgraph, beside its GraphQL gateway. */
300
+ function workflowRuntimeUrl(switchboard) {
301
+ return `${switchboard.graphqlUrl.replace(/\/+$/, "")}/workflow-runtime`;
302
+ }
300
303
  function createTransport(url, options) {
301
304
  const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
302
305
  const tokenOf = options.token ?? ambientRenownTokenProvider;
303
306
  return {
304
307
  url,
305
- gql: (query, variables) => gql(url, doFetch, tokenOf, query, variables)
308
+ gql: (query, variables) => gql(url, doFetch, tokenOf, query, variables, options.signal)
306
309
  };
307
310
  }
308
311
  var RuntimeRequestError = class extends Error {
309
312
  code;
310
- constructor(message, code) {
311
- super(message);
313
+ constructor(message, code, options) {
314
+ super(message, options);
312
315
  this.code = code;
313
316
  this.name = "RuntimeRequestError";
314
317
  }
@@ -316,25 +319,41 @@ var RuntimeRequestError = class extends Error {
316
319
  function isSyncingError(error) {
317
320
  return error instanceof RuntimeRequestError && error.code === "WORKFLOW_SYNCING";
318
321
  }
319
- async function gql(url, doFetch, tokenOf, query, variables) {
322
+ async function gql(url, doFetch, tokenOf, query, variables, signal) {
320
323
  const token = await tokenOf();
321
- const body = await (await doFetch(url, {
322
- method: "POST",
323
- headers: {
324
- "content-type": "application/json",
325
- ...token ? { authorization: `Bearer ${token}` } : {}
326
- },
327
- body: JSON.stringify({
328
- query,
329
- variables
330
- })
331
- })).json();
332
- const first = body.errors?.[0];
324
+ let response;
325
+ try {
326
+ response = await doFetch(url, {
327
+ method: "POST",
328
+ headers: {
329
+ "content-type": "application/json",
330
+ ...token ? { authorization: `Bearer ${token}` } : {}
331
+ },
332
+ body: JSON.stringify({
333
+ query,
334
+ variables
335
+ }),
336
+ signal
337
+ });
338
+ } catch (error) {
339
+ if (signal?.aborted) throw error;
340
+ throw new RuntimeRequestError(`The workflow runtime at ${url} could not be reached: ${error instanceof Error ? error.message : String(error)}`, "RUNTIME_UNREACHABLE", { cause: error });
341
+ }
342
+ if (response.status === 401 || response.status === 403) throw new RuntimeRequestError(`The workflow runtime at ${url} refused the request (HTTP ${response.status}). Sign in and try again.`, "RUNTIME_REFUSED");
343
+ if (response.status === 404) throw new RuntimeRequestError(`No workflow runtime answers at ${url} (HTTP 404): its switchboard runs no workflows.`, "NO_WORKFLOW_RUNTIME");
344
+ let body;
345
+ try {
346
+ body = await response.json();
347
+ } catch (error) {
348
+ throw new RuntimeRequestError(`The workflow runtime at ${url} answered HTTP ${response.status} without a GraphQL response.`, "RUNTIME_HTTP_ERROR", { cause: error });
349
+ }
350
+ const first = body?.errors?.[0];
333
351
  if (first) {
334
352
  const code = first.extensions?.code;
335
353
  throw new RuntimeRequestError(first.message, typeof code === "string" ? code : void 0);
336
354
  }
337
- if (!body.data) throw new Error("Empty GraphQL response");
355
+ if (!response.ok) throw new RuntimeRequestError(`The workflow runtime at ${url} answered HTTP ${response.status}.`, "RUNTIME_HTTP_ERROR");
356
+ if (!body?.data) throw new Error("Empty GraphQL response");
338
357
  return body.data;
339
358
  }
340
359
  function blockInput(block) {
@@ -969,6 +988,6 @@ const secretStatQuery = (client, ref) => queryOptions({
969
988
  staleTime: 0
970
989
  });
971
990
  //#endregion
972
- export { triggerFields as $, BRANCH_BLOCK as A, SCHEDULE_TRIGGER as B, createRuntimeClient as C, isSyncingError as D, fetchRunsPage as E, LOOP_BLOCK as F, WAIT_FOR_WEBHOOK_BLOCK as G, STOP_BLOCK as H, MANUAL_TRIGGER as I, pinBlock as J, WEBHOOK_TRIGGER as K, REACTOR_PIECE as L, CALL_FLOW_BLOCK as M, CORE_PIECE as N, APPROVAL_BLOCK as O, DELAY_BLOCK as P, triggerBlock as Q, RETURN_RESPONSE_BLOCK as R, RuntimeRequestError as S, fetchRuns as T, SUBFLOWS_PIECE as U, STEP_PRESETS as V, TRIGGER_PRESETS as W, stepBlock as X, sameBlock as Y, stepFields as Z, queryKind as _, pieceActionsQuery as a, realRuns as b, runQuery as c, secretStatQuery as d, stepOutputTreeQuery as f, blockRefKey as g, SHARED_STALE_MS as h, outputTreeQuery as i, CALLABLE_FLOW_TRIGGER$1 as j, ASSERT_BLOCK as k, runsOfPages as l, RESOLVER_STALE_MS as m, catalogQuery as n, pieceTriggersQuery as o, waitingRunsQuery as p, isCoreBlock as q, createRuntimeQueryClient as r, runPagesQuery as s, blockFormQuery as t, runsQuery as u, runtimeKeys as v, fetchRun as w, DEFAULT_RUNTIME_URL as x, TEST_TRIGGER_KIND as y, ROUTER_BLOCK as z };
991
+ export { triggerFields as $, BRANCH_BLOCK as A, SCHEDULE_TRIGGER as B, fetchRun as C, workflowRuntimeUrl as D, isSyncingError as E, LOOP_BLOCK as F, WAIT_FOR_WEBHOOK_BLOCK as G, STOP_BLOCK as H, MANUAL_TRIGGER as I, pinBlock as J, WEBHOOK_TRIGGER as K, REACTOR_PIECE as L, CALL_FLOW_BLOCK as M, CORE_PIECE as N, APPROVAL_BLOCK as O, DELAY_BLOCK as P, triggerBlock as Q, RETURN_RESPONSE_BLOCK as R, createRuntimeClient as S, fetchRunsPage as T, SUBFLOWS_PIECE as U, STEP_PRESETS as V, TRIGGER_PRESETS as W, stepBlock as X, sameBlock as Y, stepFields as Z, queryKind as _, pieceActionsQuery as a, realRuns as b, runQuery as c, secretStatQuery as d, stepOutputTreeQuery as f, blockRefKey as g, SHARED_STALE_MS as h, outputTreeQuery as i, CALLABLE_FLOW_TRIGGER$1 as j, ASSERT_BLOCK as k, runsOfPages as l, RESOLVER_STALE_MS as m, catalogQuery as n, pieceTriggersQuery as o, waitingRunsQuery as p, isCoreBlock as q, createRuntimeQueryClient as r, runPagesQuery as s, blockFormQuery as t, runsQuery as u, runtimeKeys as v, fetchRuns as w, RuntimeRequestError as x, TEST_TRIGGER_KIND as y, ROUTER_BLOCK as z };
973
992
 
974
- //# sourceMappingURL=runtime-queries-C5bqAgQy.js.map
993
+ //# sourceMappingURL=runtime-queries-FmEzElOY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-queries-FmEzElOY.js","names":["CALLABLE_FLOW_TRIGGER","CALLABLE_FLOW_TRIGGER_NAME"],"sources":["../../editors/workflow-editor/ui/forms.ts","../../editors/workflow-editor/ui/blocks.ts","../../editors/workflow-editor/runtime-client.ts","../../editors/workflow-editor/run-kinds.ts","../../editors/workflow-editor/ui/query-keys.ts","../../editors/workflow-editor/runtime-queries.ts"],"sourcesContent":["// Form descriptors driving property panels; pure data, mirrors the\n// ConnectorPropDescriptor shape from the workflow runtime.\nimport type { BlockRef } from \"@powerhousedao/pieces-framework/block-type\";\nimport type { TriggerDelivery } from \"@powerhousedao/pieces-framework/workflow\";\n\nexport interface BlockFormProp {\n name: string;\n displayName: string;\n type: string;\n required: boolean;\n defaultValue?: unknown;\n staticOptions?: FormOption[];\n // A STATIC_DROPDOWN's own state, beside its options.\n staticDisabled?: boolean;\n staticPlaceholder?: string;\n hasDynamicResolver?: boolean;\n description?: string;\n placeholder?: string;\n // Sibling prop names whose values feed the resolver; a change re-runs it.\n refreshers?: string[];\n // Nested shape: ARRAY item fields, or what a DYNAMIC resolver produced.\n properties?: BlockFormProp[];\n // Folded behind \"Advanced\": fields with a working default, so the common\n // case is short. Opens expanded when set, else live config would be hidden.\n advanced?: boolean;\n // Shown only while a sibling prop holds one of these values; data, not a\n // predicate, so a form arriving as JSON can express it.\n showWhen?: { prop: string; oneOf: unknown[] };\n // Activepieces layout and control hints, as the piece declared them.\n width?: \"half\" | \"full\";\n icon?: string;\n // CHECKBOX: sibling props shown only while it is checked.\n reveals?: string[];\n // MARKDOWN: BORDERLESS | INFO | WARNING | TIP.\n variant?: string;\n // STATIC_DROPDOWN \"cards\", NUMBER \"stepper\", DATE_RANGE \"dropdown\",\n // LONG_TEXT \"code\" (monospace).\n display?: string;\n min?: number;\n max?: number;\n step?: number;\n // DROPDOWN: options() is re-run with what the author types.\n refreshOnSearch?: boolean;\n // RICH_TEXT: the sibling whose value picks plain, markdown or html.\n formatProperty?: string;\n // SHORT_TEXT: a checkbox with this label that stores \"\" on purpose.\n emptyChoice?: string;\n}\n\nexport interface FormOption {\n label: string;\n value: unknown;\n description?: string;\n icon?: string;\n}\n\nexport interface PropertyGroup {\n key: string;\n // tabs | section | summary | builder | footer\n display: string;\n label?: string;\n description?: string;\n icon?: string;\n props: string[];\n}\n\nexport interface ErrorHandlingDefaults {\n retryOnFailure?: { defaultValue?: boolean; hide?: boolean };\n continueOnFailure?: { defaultValue?: boolean; hide?: boolean };\n}\n\nexport interface BlockForm {\n title: string;\n requireAuth: boolean;\n // The block needs a reactor connection granting this much.\n requireReactor?: \"read\" | \"write\";\n // Whether the block takes a connection: none hides the field entirely.\n auth?: \"none\" | \"optional\" | \"required\";\n props: BlockFormProp[];\n // Output ports the block declares; edges on any other are never taken.\n ports?: readonly string[];\n // A form drawn instead of the props, e.g. \"schedule\" for the builder.\n display?: string;\n // Triggers only, from checkTriggerStrategy. A webhook trigger is fed by a\n // request, so the panel shows its endpoint URL.\n triggerDelivery?: TriggerDelivery;\n // What the step does, as the piece describes it.\n description?: string;\n propertyGroups?: PropertyGroup[];\n // READ | SEARCH | WRITE | DESTRUCTIVE\n classification?: string;\n errorHandling?: ErrorHandlingDefaults;\n // What the action declares for a step that sets no timeout or retry.\n actionDefaults?: ActionDefaults;\n}\n\nexport interface ActionDefaults {\n timeoutSeconds?: number;\n retryAttempts?: number;\n}\n\nexport interface ConnectionSummary {\n id: string;\n name: string;\n connectorId: string;\n authType: string;\n status: string;\n accountLabel: string | null;\n}\n\nexport interface SecretStat {\n ref: string;\n label: string | null;\n version: number;\n status: string;\n createdAt: string;\n updatedAt: string;\n}\n\n// Minting seam for PH_SECRET_REF props: the field takes a value and the\n// document only ever receives the ref that comes back.\nexport interface SecretFormService {\n save: (input: {\n ref?: string;\n value: string;\n label: string;\n }) => Promise<SecretStat>;\n stat: (ref: string) => Promise<SecretStat | null>;\n}\n\nexport interface WebhookEndpoint {\n workflowId: string;\n url: string;\n // False when `url` is a bare path because the reactor has no public origin.\n absoluteUrl: boolean;\n armed: boolean;\n createdAt: string;\n}\n\nexport interface DesignTimeService {\n getBlockForm: (block: BlockRef) => Promise<BlockForm | null>;\n loadOptions: (\n block: BlockRef,\n propName: string,\n input: Record<string, unknown>,\n connectionId?: string,\n searchValue?: string,\n reactorConnectionId?: string,\n ) => Promise<unknown>;\n // Runs the current workflow's piece trigger test hook; sample items back.\n testTrigger?: () => Promise<unknown>;\n // Runs one draft step against the last tests of the blocks it reads.\n testStep?: (stepId: string) => Promise<StepTestOutcome>;\n // The current workflow's webhook endpoint, for the core webhook trigger.\n webhookEndpoint?: () => Promise<WebhookEndpoint | null>;\n // Backs PH_SECRET_REF props; absent when the runtime refuses secret writes.\n secrets?: SecretFormService;\n // powerhouse/connection documents for the connection picker.\n listConnections?: () => Promise<ConnectionSummary[]>;\n // Tells apart listings narrowed differently, e.g. per drive; part of the key.\n connectionScope?: string;\n // The workflow being edited; keys its run and endpoint queries.\n workflowId?: string;\n // The current workflow's most recent run, for a step's \"Last run\" preview.\n latestRun?: () => Promise<LatestRun | null>;\n // One journaled run by id, e.g. the trigger's last test.\n fetchRun?: (runId: string) => Promise<LatestRun | null>;\n // The piece version each draft block runs, trigger first.\n blockResolutions?: () => Promise<BlockResolutionView[]>;\n}\n\nexport type BlockMatchView =\n | \"exact\"\n | \"compatible\"\n | \"fallback\"\n | \"installed\"\n | \"missing\";\n\n// A draft block as the runtime would run it; host-bound pieces are \"installed\".\nexport interface BlockResolutionView {\n stepId: string;\n pieceName: string;\n // The version the block pins.\n pieceVersion: string;\n name: string;\n kind: \"action\" | \"trigger\";\n resolvedVersion: string | null;\n source: string | null;\n match: BlockMatchView;\n note: string | null;\n latestVersion: string | null;\n}\n\nexport interface StepTestOutcome {\n // Null when nothing ran, e.g. `Test \"fetch\" first`.\n runId: string | null;\n // INDETERMINATE: a write the step asked for may have landed.\n status: \"SUCCEEDED\" | \"FAILED\" | \"INDETERMINATE\";\n output?: unknown;\n error: string | null;\n // The thrown error's name, e.g. ReactorAccessDeniedError.\n errorName?: string | null;\n durationMs: number;\n}\n\nexport interface LatestRun {\n id?: string;\n status: string;\n error?: string | null;\n errorName?: string | null;\n startedAt: string;\n triggerPayload: unknown;\n steps: {\n stepKey: string;\n status: string;\n input: unknown;\n output: unknown;\n error: string | null;\n errorName?: string | null;\n }[];\n}\n\n// Ours, not the piece's: the reactor's poll cadence for a piece trigger.\n// Appended to every piece trigger's form; see splitPollInterval in the runtime.\nexport const POLL_INTERVAL_PROP: BlockFormProp = {\n name: \"pollEverySeconds\",\n displayName: \"Poll every (seconds)\",\n type: \"NUMBER\",\n required: false,\n description:\n \"How often the reactor checks this trigger; 60 at the least. Omit to follow the piece's own cadence.\",\n};\n","// Block helpers and palette presets; pure data used by the UI to seed new\n// triggers and steps.\nimport {\n blockKey,\n type BlockIdentity,\n type BlockKind,\n type BlockRef,\n} from \"@powerhousedao/pieces-framework/block-type\";\nimport {\n CALL_FLOW_ACTION,\n CALLABLE_FLOW_TRIGGER as CALLABLE_FLOW_TRIGGER_NAME,\n CORE_PIECE_NAME,\n SUBFLOWS_PIECE,\n} from \"@powerhousedao/pieces-framework/workflow\";\n\nexport type { BlockIdentity, BlockKind, BlockRef };\n\nexport const CORE_PIECE = CORE_PIECE_NAME;\n\n// The reactor piece this package ships, named as pieces/index.ts declares it.\nexport const REACTOR_PIECE = \"@powerhousedao/piece-reactor\";\n\nconst core = (kind: BlockKind, name: string): BlockIdentity => ({\n pieceName: CORE_PIECE,\n kind,\n name,\n});\n\nexport const MANUAL_TRIGGER = core(\"trigger\", \"manual\");\nexport const SCHEDULE_TRIGGER = core(\"trigger\", \"schedule\");\nexport const WEBHOOK_TRIGGER = core(\"trigger\", \"webhook\");\nexport const BRANCH_BLOCK = core(\"action\", \"branch\");\nexport const ROUTER_BLOCK = core(\"action\", \"router\");\nexport const LOOP_BLOCK = core(\"action\", \"loop\");\nexport const ASSERT_BLOCK = core(\"action\", \"assert\");\nexport const DELAY_BLOCK = core(\"action\", \"delay\");\nexport const APPROVAL_BLOCK = core(\"action\", \"approval\");\nexport const STOP_BLOCK = core(\"action\", \"stop\");\nexport const WAIT_FOR_WEBHOOK_BLOCK = core(\"action\", \"waitForWebhook\");\n\n// Sub-flows are Activepieces' own piece, pinned to a version this runtime runs.\nexport { SUBFLOWS_PIECE };\nexport const SUBFLOWS_VERSION = \"0.7.0\";\nconst subflows = (kind: BlockKind, name: string): BlockPick => ({\n pieceName: SUBFLOWS_PIECE,\n pieceVersion: SUBFLOWS_VERSION,\n kind,\n name,\n});\nexport const CALLABLE_FLOW_TRIGGER = subflows(\n \"trigger\",\n CALLABLE_FLOW_TRIGGER_NAME,\n);\nexport const CALL_FLOW_BLOCK = subflows(\"action\", CALL_FLOW_ACTION);\nexport const RETURN_RESPONSE_BLOCK = subflows(\"action\", \"returnResponse\");\n\n// A block to add: pinned already, or pinned to the installed version on pick.\nexport type BlockPick = BlockIdentity & { pieceVersion?: string };\n\nexport function sameBlock(\n a: BlockIdentity | undefined | null,\n b: BlockIdentity | undefined | null,\n): boolean {\n return Boolean(a && b && blockKey(a) === blockKey(b));\n}\n\nexport function isCoreBlock(block: { pieceName: string }): boolean {\n return block.pieceName === CORE_PIECE;\n}\n\n// The document blocks live in the reactor piece, and are offered here too:\n// they are what most workflows on a reactor are built from.\nexport function isReactorPieceBlock(block: { pieceName: string }): boolean {\n return block.pieceName === REACTOR_PIECE;\n}\n\nexport function stepBlock(step: {\n pieceName: string;\n pieceVersion: string;\n actionName: string;\n}): BlockRef {\n return {\n pieceName: step.pieceName,\n pieceVersion: step.pieceVersion,\n kind: \"action\",\n name: step.actionName,\n };\n}\n\nexport function triggerBlock(trigger: {\n pieceName: string;\n pieceVersion: string;\n triggerName: string;\n}): BlockRef {\n return {\n pieceName: trigger.pieceName,\n pieceVersion: trigger.pieceVersion,\n kind: \"trigger\",\n name: trigger.triggerName,\n };\n}\n\n// The fields a step or the trigger stores for a block.\nexport function stepFields(block: BlockRef) {\n return {\n pieceName: block.pieceName,\n pieceVersion: block.pieceVersion,\n actionName: block.name,\n };\n}\n\nexport function triggerFields(block: BlockRef) {\n return {\n pieceName: block.pieceName,\n pieceVersion: block.pieceVersion,\n triggerName: block.name,\n };\n}\n\n// A pinned pick passes through; an unpinned one takes the installed version,\n// and undefined means the piece isn't installed.\nexport function pinBlock(\n pick: BlockPick,\n installedVersion: (piece: string) => string | undefined,\n): BlockRef | undefined {\n const pieceVersion = pick.pieceVersion ?? installedVersion(pick.pieceName);\n if (!pieceVersion) return undefined;\n return {\n pieceName: pick.pieceName,\n pieceVersion,\n kind: pick.kind,\n name: pick.name,\n };\n}\n\nexport interface BlockPreset {\n label: string;\n block: BlockPick;\n description: string;\n defaultConfig: unknown;\n // Which section of the picker it belongs to: \"core\" is the core piece,\n // \"powerhouse\" the reactor piece, listed right after it.\n\n // Optional because a pick built from a search hit or an existing step is\n // the same shape but belongs to no section.\n group?: \"core\" | \"powerhouse\";\n}\n\nconst reactor = (kind: BlockKind, name: string): BlockIdentity => ({\n pieceName: REACTOR_PIECE,\n kind,\n name,\n});\n\nexport const TRIGGER_PRESETS: BlockPreset[] = [\n {\n label: \"Manual\",\n block: MANUAL_TRIGGER,\n group: \"core\",\n description: \"Fired on demand with a payload.\",\n defaultConfig: {},\n },\n {\n label: \"Schedule\",\n block: SCHEDULE_TRIGGER,\n group: \"core\",\n description: \"Fires on a cron expression or fixed interval.\",\n defaultConfig: { mode: \"cron\", cron: \"0 9 * * 1-5\", timezone: \"UTC\" },\n },\n {\n label: \"Webhook\",\n block: WEBHOOK_TRIGGER,\n group: \"core\",\n description: \"Fires when a provider POSTs to this workflow's URL.\",\n defaultConfig: { methods: \"POST\", scheme: \"none\", responseMode: \"async\" },\n },\n {\n label: \"Callable workflow\",\n block: CALLABLE_FLOW_TRIGGER,\n group: \"core\",\n description: \"Fires when another workflow in this drive calls it.\",\n defaultConfig: { mode: \"simple\", exampleData: { sampleData: {} } },\n },\n {\n label: \"Document event\",\n block: reactor(\"trigger\", \"document-event\"),\n group: \"powerhouse\",\n description: \"Fires when a matching document operation lands.\",\n defaultConfig: {},\n },\n {\n label: \"Document created\",\n block: reactor(\"trigger\", \"document-created\"),\n group: \"powerhouse\",\n description: \"Fires when a document is added to a drive.\",\n defaultConfig: {},\n },\n {\n label: \"Document deleted\",\n block: reactor(\"trigger\", \"document-deleted\"),\n group: \"powerhouse\",\n description: \"Fires when a document is removed from a drive.\",\n defaultConfig: {},\n },\n];\n\nexport const STEP_PRESETS: BlockPreset[] = [\n {\n label: \"Branch\",\n block: BRANCH_BLOCK,\n group: \"core\",\n description: \"Routes true/false on a condition.\",\n defaultConfig: {},\n },\n {\n label: \"Router\",\n block: ROUTER_BLOCK,\n group: \"core\",\n description: \"Takes the first of several branches whose condition holds.\",\n defaultConfig: { branches: [{ operator: \"TEXT_EXACTLY_MATCHES\" }] },\n },\n {\n label: \"Loop on items\",\n block: LOOP_BLOCK,\n group: \"core\",\n description: \"Runs the steps inside it once for each item of a list.\",\n defaultConfig: { items: \"\" },\n },\n {\n label: \"Assert\",\n block: ASSERT_BLOCK,\n group: \"core\",\n description:\n \"Fails the run when a value is blank, rejected or not allowed.\",\n defaultConfig: { value: \"\", allowValues: [] },\n },\n {\n label: \"Delay\",\n block: DELAY_BLOCK,\n group: \"core\",\n description: \"Waits for a while, or until a date, then carries on.\",\n defaultConfig: { mode: \"for\", amount: 5, unit: \"minutes\" },\n },\n {\n label: \"Request approval\",\n block: APPROVAL_BLOCK,\n group: \"core\",\n description: \"Waits until someone approves or rejects the run.\",\n defaultConfig: {\n title: \"\",\n approveLabel: \"Approve\",\n rejectLabel: \"Reject\",\n reasonRequiredOn: \"none\",\n },\n },\n {\n label: \"Respond and wait for webhook\",\n block: WAIT_FOR_WEBHOOK_BLOCK,\n group: \"core\",\n description:\n \"Answers the caller with a resume URL, then waits until it is called.\",\n defaultConfig: { responseType: \"json\", includeResumeUrl: true },\n },\n {\n label: \"Stop run\",\n block: STOP_BLOCK,\n group: \"core\",\n description: \"Ends the run successfully, optionally answering the caller.\",\n defaultConfig: { responseType: \"json\" },\n },\n {\n label: \"Call workflow\",\n block: CALL_FLOW_BLOCK,\n group: \"core\",\n description:\n \"Runs a callable workflow in this drive, optionally waiting for its response.\",\n defaultConfig: { mode: \"simple\", waitForResponse: false },\n },\n {\n label: \"Return response\",\n block: RETURN_RESPONSE_BLOCK,\n group: \"core\",\n description: \"Answers the workflow that called this one.\",\n defaultConfig: { mode: \"simple\", response: { response: {} } },\n },\n {\n label: \"Create document\",\n block: reactor(\"action\", \"document-create\"),\n group: \"powerhouse\",\n description: \"Creates a Powerhouse document.\",\n defaultConfig: { documentType: \"\", name: \"\" },\n },\n {\n label: \"Dispatch actions\",\n block: reactor(\"action\", \"document-dispatch\"),\n group: \"powerhouse\",\n description: \"Sends actions to a document.\",\n defaultConfig: { documentId: \"\" },\n },\n {\n label: \"Get document\",\n block: reactor(\"action\", \"document-get\"),\n group: \"powerhouse\",\n description: \"Reads a document's current state.\",\n defaultConfig: { documentId: \"\" },\n },\n {\n label: \"Find documents\",\n block: reactor(\"action\", \"document-find\"),\n group: \"powerhouse\",\n description: \"Lists documents by type and name.\",\n defaultConfig: { documentType: \"\" },\n },\n {\n label: \"List document types\",\n block: reactor(\"action\", \"document-types\"),\n group: \"powerhouse\",\n description: \"Document models installed on this reactor.\",\n defaultConfig: {},\n },\n {\n label: \"Get document schema\",\n block: reactor(\"action\", \"document-schema\"),\n group: \"powerhouse\",\n description: \"Action and state schemas of a document type.\",\n defaultConfig: { documentType: \"\" },\n },\n];\n\n// A preset as the picker hands it over: pinned to a version.\nexport interface PickedPreset extends BlockPreset {\n block: BlockRef;\n}\n","// Design-time channel to the workflow-runtime subgraph: piece descriptors,\n// option resolution, runs and secrets. Not document-model coupled.\nimport { ambientRenownTokenProvider } from \"@powerhousedao/reactor-browser/graphql-client\";\nimport {\n POLL_INTERVAL_PROP,\n type BlockForm,\n type BlockFormProp,\n type ErrorHandlingDefaults,\n type PropertyGroup,\n} from \"./ui/forms.js\";\nimport {\n isCoreBlock,\n isReactorPieceBlock,\n type BlockRef,\n} from \"./ui/blocks.js\";\nimport { checkTriggerStrategy } from \"@powerhousedao/pieces-framework/workflow\";\n\n/** A switchboard's workflow-runtime subgraph, beside its GraphQL gateway. */\nexport function workflowRuntimeUrl(switchboard: {\n graphqlUrl: string;\n}): string {\n return `${switchboard.graphqlUrl.replace(/\\/+$/, \"\")}/workflow-runtime`;\n}\n\nexport interface Transport {\n url: string;\n gql: <T>(query: string, variables: Record<string, unknown>) => Promise<T>;\n}\n\nexport interface RuntimeClientOptions {\n fetch?: typeof fetch;\n // Bearer token source; defaults to the ambient Renown token.\n token?: () => Promise<string | null | undefined>;\n // Aborts every request of this client, e.g. when the user stops a turn.\n signal?: AbortSignal;\n}\n\nfunction createTransport(\n url: string,\n options: RuntimeClientOptions,\n): Transport {\n const doFetch = options.fetch ?? ((input, init) => fetch(input, init));\n const tokenOf = options.token ?? ambientRenownTokenProvider;\n return {\n url,\n gql: (query, variables) =>\n gql(url, doFetch, tokenOf, query, variables, options.signal),\n };\n}\n\n// A runtime error with its GraphQL extension code, when the server sent one,\n// or one of this client's: RUNTIME_UNREACHABLE, RUNTIME_REFUSED,\n// NO_WORKFLOW_RUNTIME, RUNTIME_HTTP_ERROR.\nexport class RuntimeRequestError extends Error {\n constructor(\n message: string,\n readonly code?: string,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = \"RuntimeRequestError\";\n }\n}\n\n// The workflow document hasn't reached the runtime yet; the call can be retried.\nexport function isSyncingError(error: unknown): boolean {\n return (\n error instanceof RuntimeRequestError && error.code === \"WORKFLOW_SYNCING\"\n );\n}\n\nasync function gql<T>(\n url: string,\n doFetch: typeof fetch,\n tokenOf: () => Promise<string | null | undefined>,\n query: string,\n variables: Record<string, unknown>,\n signal?: AbortSignal,\n): Promise<T> {\n // Mirrors the reactor-browser switchboard AI tool's auth: attach the\n // Renown bearer token when one is available, else go out anonymously.\n const token = await tokenOf();\n let response: Response;\n try {\n response = await doFetch(url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: JSON.stringify({ query, variables }),\n signal,\n });\n } catch (error) {\n if (signal?.aborted) throw error;\n // A refused connection, a CORS refusal or a dropped network: the\n // browser says only \"Failed to fetch\", so say where it went.\n throw new RuntimeRequestError(\n `The workflow runtime at ${url} could not be reached: ${\n error instanceof Error ? error.message : String(error)\n }`,\n \"RUNTIME_UNREACHABLE\",\n { cause: error },\n );\n }\n if (response.status === 401 || response.status === 403) {\n throw new RuntimeRequestError(\n `The workflow runtime at ${url} refused the request (HTTP ${response.status}). Sign in and try again.`,\n \"RUNTIME_REFUSED\",\n );\n }\n if (response.status === 404) {\n throw new RuntimeRequestError(\n `No workflow runtime answers at ${url} (HTTP 404): its switchboard runs no workflows.`,\n \"NO_WORKFLOW_RUNTIME\",\n );\n }\n let body: {\n data?: T;\n errors?: { message: string; extensions?: { code?: unknown } }[];\n } | null;\n try {\n body = (await response.json()) as typeof body;\n } catch (error) {\n throw new RuntimeRequestError(\n `The workflow runtime at ${url} answered HTTP ${response.status} without a GraphQL response.`,\n \"RUNTIME_HTTP_ERROR\",\n { cause: error },\n );\n }\n const first = body?.errors?.[0];\n if (first) {\n const code = first.extensions?.code;\n throw new RuntimeRequestError(\n first.message,\n typeof code === \"string\" ? code : undefined,\n );\n }\n if (!response.ok) {\n throw new RuntimeRequestError(\n `The workflow runtime at ${url} answered HTTP ${response.status}.`,\n \"RUNTIME_HTTP_ERROR\",\n );\n }\n if (!body?.data) throw new Error(\"Empty GraphQL response\");\n return body.data;\n}\n\ninterface BlockEntryDescriptor {\n displayName: string;\n description?: string;\n requireAuth: boolean;\n requireReactor?: string;\n props: BlockFormProp[];\n ports?: string[];\n // Triggers only; read through checkTriggerStrategy.\n strategy?: string;\n display?: string;\n propertyGroups?: PropertyGroup[];\n classification?: string;\n errorHandlingOptions?: ErrorHandlingDefaults;\n // Actions only.\n defaultTimeoutSeconds?: number;\n defaultRetry?: { maxAttempts?: number };\n}\n\ninterface BlockDescriptorResult {\n workflowRuntime: {\n blockDescriptor: {\n displayName: string;\n auth?: unknown;\n action?: BlockEntryDescriptor;\n trigger?: BlockEntryDescriptor;\n } | null;\n };\n}\n\n// The GraphQL BlockInput for a block.\nexport function blockInput(block: BlockRef) {\n return {\n pieceName: block.pieceName,\n pieceVersion: block.pieceVersion,\n name: block.name,\n kind: block.kind,\n };\n}\n\nfunction actionDefaultsOf(\n entry: BlockEntryDescriptor,\n): Pick<BlockForm, \"actionDefaults\"> {\n const timeoutSeconds = entry.defaultTimeoutSeconds;\n const retryAttempts = entry.defaultRetry?.maxAttempts;\n if (timeoutSeconds === undefined && retryAttempts === undefined) return {};\n return {\n actionDefaults: {\n ...(timeoutSeconds !== undefined ? { timeoutSeconds } : {}),\n ...(retryAttempts !== undefined ? { retryAttempts } : {}),\n },\n };\n}\n\nexport function getBlockForm(\n t: Transport,\n block: BlockRef,\n): Promise<BlockForm | null> {\n return t\n .gql<BlockDescriptorResult>(\n `query Descriptor($block: BlockInput!) {\n workflowRuntime { blockDescriptor(block: $block) }\n }`,\n { block: blockInput(block) },\n )\n .then((data) => {\n const descriptor = data.workflowRuntime.blockDescriptor;\n const entry = descriptor?.action ?? descriptor?.trigger;\n if (!descriptor || !entry) return null;\n const isTrigger = !descriptor.action && Boolean(descriptor.trigger);\n const strategy = isTrigger\n ? checkTriggerStrategy(entry.strategy)\n : undefined;\n // The runtime refuses it too, so no form is drawn for it.\n if (strategy && \"issue\" in strategy) throw new Error(strategy.issue);\n const delivery = strategy?.delivery;\n // A poll cadence only means something for a piece trigger the reactor\n // polls; the reactor piece's are fed by the host, core ones fire themselves.\n const polled =\n delivery === \"poll\" &&\n !isCoreBlock(block) &&\n !isReactorPieceBlock(block);\n const props = entry.props;\n return {\n // A core block belongs to no piece worth naming.\n title: isCoreBlock(block)\n ? entry.displayName\n : `${descriptor.displayName} · ${entry.displayName}`,\n requireAuth: entry.requireAuth,\n ...(entry.requireReactor === \"read\" || entry.requireReactor === \"write\"\n ? { requireReactor: entry.requireReactor }\n : {}),\n auth: !descriptor.auth\n ? (\"none\" as const)\n : entry.requireAuth\n ? (\"required\" as const)\n : (\"optional\" as const),\n props: polled ? [...props, POLL_INTERVAL_PROP] : props,\n ...(entry.ports ? { ports: entry.ports } : {}),\n ...(delivery ? { triggerDelivery: delivery } : {}),\n ...(entry.display ? { display: entry.display } : {}),\n ...(entry.description ? { description: entry.description } : {}),\n ...(entry.propertyGroups\n ? { propertyGroups: entry.propertyGroups }\n : {}),\n ...(entry.classification\n ? { classification: entry.classification }\n : {}),\n ...(entry.errorHandlingOptions\n ? { errorHandling: entry.errorHandlingOptions }\n : {}),\n ...actionDefaultsOf(entry),\n };\n });\n}\n\nexport interface PieceSummary {\n name: string;\n displayName: string;\n description: string;\n logoUrl: string;\n version: string;\n actionCount: number;\n triggerCount: number;\n // Activepieces category ids, e.g. ARTIFICIAL_INTELLIGENCE, SALES_AND_CRM.\n categories: string[];\n // Absent from runtimes older than the field; read as \"activepieces\".\n source?: PieceSource;\n // PieceAuth descriptor, verbatim from the piece; null when authless.\n auth?: unknown;\n // Why none of the piece's blocks can run on this reactor.\n unsupported?: string | null;\n deprecated?: boolean;\n // A package piece shadowing a published one: the version published.\n publishedVersion?: string;\n}\n\n// One action of a piece, at the version the listing answered with.\nexport interface PieceActionEntry {\n pieceName: string;\n pieceVersion: string;\n name: string;\n displayName: string;\n description: string;\n unsupported?: string | null;\n}\n\ninterface PieceListing<T> {\n name: string;\n version: string;\n entries: T[];\n}\n\nfunction atVersion<T>(listing: PieceListing<T>) {\n return listing.entries.map((entry) => ({\n ...entry,\n pieceName: listing.name,\n pieceVersion: listing.version,\n }));\n}\n\nexport function fetchPieceCatalog(t: Transport): Promise<PieceSummary[]> {\n return t\n .gql<{\n workflowRuntime: { pieceCatalog: PieceSummary[] };\n }>(`query Catalog { workflowRuntime { pieceCatalog } }`, {})\n .then((data) => data.workflowRuntime.pieceCatalog);\n}\n\nexport async function fetchPieceActions(\n t: Transport,\n packageName: string,\n): Promise<PieceActionEntry[]> {\n const data = await t.gql<{\n workflowRuntime: {\n pieceActions: {\n name: string;\n version: string;\n actions: Omit<PieceActionEntry, \"pieceName\" | \"pieceVersion\">[];\n };\n };\n }>(\n `query Actions($packageName: String!) {\n workflowRuntime { pieceActions(packageName: $packageName) }\n }`,\n { packageName },\n );\n const listing = data.workflowRuntime.pieceActions;\n return atVersion({ ...listing, entries: listing.actions });\n}\n\nexport interface PieceTriggerEntry {\n pieceName: string;\n pieceVersion: string;\n name: string;\n displayName: string;\n description: string;\n strategy: string;\n unsupported?: string | null;\n}\n\nexport async function fetchPieceTriggers(\n t: Transport,\n packageName: string,\n): Promise<PieceTriggerEntry[]> {\n const data = await t.gql<{\n workflowRuntime: {\n pieceTriggers: {\n name: string;\n version: string;\n triggers: Omit<PieceTriggerEntry, \"pieceName\" | \"pieceVersion\">[];\n };\n };\n }>(\n `query Triggers($packageName: String!) {\n workflowRuntime { pieceTriggers(packageName: $packageName) }\n }`,\n { packageName },\n );\n const listing = data.workflowRuntime.pieceTriggers;\n return atVersion({ ...listing, entries: listing.triggers });\n}\n\nexport interface BlockSearchHit {\n pieceName: string;\n pieceVersion: string;\n // The action or trigger name.\n name: string;\n pieceDisplayName: string;\n logoUrl: string;\n displayName: string;\n description: string;\n kind: \"action\" | \"trigger\";\n strategy: string | null;\n unsupported: string | null;\n}\n\nexport type PieceSource = \"local\" | \"registry\" | \"activepieces\";\n\nexport interface PieceSearchMatch {\n pieceName: string;\n pieceVersion: string;\n displayName: string;\n description: string;\n logoUrl: string;\n categories: string[];\n source: PieceSource;\n deprecated: boolean | null;\n unsupported: string | null;\n // Every query token matched the piece's own name.\n namedPiece: boolean;\n blocks: BlockSearchHit[];\n}\n\nexport interface PieceSearchResult {\n status: \"ready\" | \"indexing\" | \"error\";\n pieces: PieceSearchMatch[];\n indexedPieces: number;\n error: string | null;\n}\n\nexport interface PieceSearchFilter {\n kind: \"action\" | \"trigger\";\n sources?: readonly PieceSource[];\n categories?: readonly string[];\n limit?: number;\n}\n\n// Catalog-wide search grouped by piece; \"indexing\" on the very first calls.\nexport async function searchPieces(\n t: Transport,\n query: string,\n filter: PieceSearchFilter,\n): Promise<PieceSearchResult> {\n const data = await t.gql<{\n workflowRuntime: { searchPieces: PieceSearchResult };\n }>(\n `query SearchPieces($query: String!, $kind: String!, $sources: [String!], $categories: [String!], $limit: Int) {\n workflowRuntime { searchPieces(query: $query, kind: $kind, sources: $sources, categories: $categories, limit: $limit) {\n status indexedPieces error\n pieces {\n pieceName pieceVersion displayName description logoUrl categories source deprecated unsupported namedPiece\n blocks { pieceName pieceVersion name pieceDisplayName logoUrl displayName description kind strategy unsupported }\n }\n } }\n }`,\n {\n query,\n kind: filter.kind,\n sources: filter.sources ?? null,\n categories: filter.categories ?? null,\n limit: filter.limit ?? null,\n },\n );\n return data.workflowRuntime.searchPieces;\n}\n\nexport interface OutputTreeNode {\n name: string;\n type: string;\n description?: string;\n children?: OutputTreeNode[];\n}\n\nexport interface OutputTree {\n source: \"schema\" | \"sample\" | \"static\" | \"none\" | \"test\";\n nodes: OutputTreeNode[];\n // source \"test\" only: the last test's output and when it ran.\n sample?: unknown;\n testedAt?: string;\n runId?: string;\n}\n\nexport function fetchBlockOutputTree(\n t: Transport,\n block: BlockRef,\n config: unknown,\n): Promise<OutputTree> {\n return t\n .gql<{ workflowRuntime: { blockOutputTree: OutputTree } }>(\n `query OutputTree($block: BlockInput!, $config: Unknown) {\n workflowRuntime { blockOutputTree(block: $block, config: $config) }\n }`,\n { block: blockInput(block), config: config ?? {} },\n )\n .then((data) => data.workflowRuntime.blockOutputTree);\n}\n\n// A draft step's or trigger's tree: its last test output, else its shape.\nexport function fetchStepOutputTree(\n t: Transport,\n workflowId: string,\n stepId: string,\n): Promise<OutputTree> {\n return t\n .gql<{ workflowRuntime: { stepOutputTree: OutputTree } }>(\n `query StepOutputTree($workflowId: String!, $stepId: String!) {\n workflowRuntime { stepOutputTree(workflowId: $workflowId, stepId: $stepId) }\n }`,\n { workflowId, stepId },\n )\n .then((data) => data.workflowRuntime.stepOutputTree);\n}\n\nexport interface ConnectionSummary {\n id: string;\n name: string;\n connectorId: string;\n authType: string;\n status: string;\n accountLabel: string | null;\n}\n\n// Never persisted: the server scopes this list to the caller's read access.\nexport function fetchConnections(t: Transport): Promise<ConnectionSummary[]> {\n return t\n .gql<{\n workflowRuntime: { connections: ConnectionSummary[] };\n }>(\n `query Connections { workflowRuntime { connections { id name connectorId authType status accountLabel } } }`,\n {},\n )\n .then((data) => data.workflowRuntime.connections);\n}\n\nexport interface ConnectionCheckResult {\n ok: boolean;\n detail: string;\n accountLabel: string | null;\n}\n\n// Runs the piece's own connection check against a document's stored credentials.\n// No secrets cross this boundary: the subgraph resolves refs server-side.\nexport function checkConnection(\n t: Transport,\n connectionId: string,\n): Promise<ConnectionCheckResult> {\n return t\n .gql<{\n workflowRuntime: { checkConnection: ConnectionCheckResult };\n }>(\n `mutation CheckConnection($connectionId: String!) {\n workflowRuntime {\n checkConnection(connectionId: $connectionId) {\n ok\n detail\n accountLabel\n }\n }\n }`,\n { connectionId },\n )\n .then((data) => data.workflowRuntime.checkConnection);\n}\n\n// What the editor needs to decide on sign-in.\nexport interface ReactorAccessInfo {\n authEnforcement: boolean;\n // Null for a caller who is not signed in.\n reactorIdentity: { address: string | null; key: string } | null;\n authConditions: boolean | null;\n}\n\nexport function fetchReactorAccess(t: Transport): Promise<ReactorAccessInfo> {\n return t\n .gql<{ workflowRuntime: ReactorAccessInfo }>(\n `query ReactorAccess {\n workflowRuntime { authEnforcement reactorIdentity { address key } authConditions }\n }`,\n {},\n )\n .then((data) => data.workflowRuntime);\n}\n\n// Why the runtime would not arm the workflow's reactor access; null when it would.\nexport function fetchReactorAccessDenial(\n t: Transport,\n workflowId: string,\n): Promise<string | null> {\n return t\n .gql<{ workflowRuntime: { reactorAccessDenial: string | null } }>(\n `query ReactorAccessDenial($workflowId: String!) {\n workflowRuntime { reactorAccessDenial(workflowId: $workflowId) }\n }`,\n { workflowId },\n )\n .then((data) => data.workflowRuntime.reactorAccessDenial);\n}\n\nexport interface OAuthStart {\n state: string;\n authorizationUrl: string;\n redirectUri: string;\n expiresAt: string;\n}\n\nexport interface OAuthAttempt {\n connectionId: string;\n status: \"PENDING\" | \"EXCHANGING\" | \"OK\" | \"ERROR\";\n error: string | null;\n}\n\n// The redirect an OAuth2 app registers, absolute: a bare path from a host\n// that doesn't know its origin is resolved against the URL it is reached at.\nexport async function fetchOAuthRedirectUri(\n t: Transport,\n): Promise<string | null> {\n const data = await t.gql<{\n workflowRuntime: { oauthRedirectUri: string | null };\n }>(`query OAuthRedirectUri { workflowRuntime { oauthRedirectUri } }`, {});\n const uri = data.workflowRuntime.oauthRedirectUri;\n return uri === null ? null : new URL(uri, t.url).href;\n}\n\nexport async function startOAuth(\n t: Transport,\n connectionId: string,\n options: { redirectUri?: string; returnUrl?: string } = {},\n): Promise<OAuthStart> {\n const data = await t.gql<{ workflowRuntime: { startOAuth: OAuthStart } }>(\n `mutation StartOAuth($connectionId: String!, $redirectUri: String, $returnUrl: String) {\n workflowRuntime {\n startOAuth(connectionId: $connectionId, redirectUri: $redirectUri, returnUrl: $returnUrl) {\n state authorizationUrl redirectUri expiresAt\n }\n }\n }`,\n {\n connectionId,\n redirectUri: options.redirectUri ?? null,\n returnUrl: options.returnUrl ?? null,\n },\n );\n return data.workflowRuntime.startOAuth;\n}\n\nexport async function fetchOAuthAttempt(\n t: Transport,\n state: string,\n): Promise<OAuthAttempt | null> {\n const data = await t.gql<{\n workflowRuntime: { oauthAttempt: OAuthAttempt | null };\n }>(\n `query OAuthAttempt($state: String!) {\n workflowRuntime { oauthAttempt(state: $state) { connectionId status error } }\n }`,\n { state },\n );\n return data.workflowRuntime.oauthAttempt;\n}\n\nexport interface SecretStat {\n ref: string;\n label: string | null;\n // Null for a secret minted before secrets had owners.\n ownerId: string | null;\n // Whether this caller may rotate or delete it; else a save mints a new one.\n manageable: boolean;\n version: number;\n status: \"ACTIVE\" | \"DELETED\";\n createdAt: string;\n updatedAt: string;\n}\n\nconst SECRET_FIELDS =\n \"ref label ownerId manageable version status createdAt updatedAt\";\n\n// Mints a secret for the connection or workflow documentId; only that\n// document resolves it, and only the returned ref ever enters it.\nexport async function createSecret(\n t: Transport,\n documentId: string,\n value: string,\n label?: string,\n): Promise<SecretStat> {\n const data = await t.gql<{ workflowRuntime: { createSecret: SecretStat } }>(\n `mutation CreateSecret($value: String!, $label: String, $documentId: String!) {\n workflowRuntime { createSecret(value: $value, label: $label, documentId: $documentId) { ${SECRET_FIELDS} } }\n }`,\n { value, label: label ?? null, documentId },\n );\n return data.workflowRuntime.createSecret;\n}\n\n// Same ref, version+1; referencing documents stay untouched.\nexport async function rotateSecret(\n t: Transport,\n ref: string,\n value: string,\n): Promise<SecretStat> {\n const data = await t.gql<{ workflowRuntime: { rotateSecret: SecretStat } }>(\n `mutation RotateSecret($ref: String!, $value: String!) {\n workflowRuntime { rotateSecret(ref: $ref, value: $value) { ${SECRET_FIELDS} } }\n }`,\n { ref, value },\n );\n return data.workflowRuntime.rotateSecret;\n}\n\n// Metadata only; null for unknown or legacy refs.\nexport async function fetchSecretStat(\n t: Transport,\n ref: string,\n): Promise<SecretStat | null> {\n const data = await t.gql<{ workflowRuntime: { secret: SecretStat | null } }>(\n `query Secret($ref: String!) {\n workflowRuntime { secret(ref: $ref) { ${SECRET_FIELDS} } }\n }`,\n { ref },\n );\n return data.workflowRuntime.secret;\n}\n\nexport interface WebhookEndpointRecord {\n workflowId: string;\n url: string;\n // False when `url` is a bare path because the reactor has no public origin.\n absoluteUrl: boolean;\n armed: boolean;\n createdAt: string;\n}\n\n// Never cached: the runtime mints the endpoint on the first call and `armed`\n// tracks the workflow's status.\nexport async function fetchWebhookEndpoint(\n t: Transport,\n workflowId: string,\n driveId?: string,\n): Promise<WebhookEndpointRecord | null> {\n const data = await t.gql<{\n workflowRuntime: { webhookEndpoint: WebhookEndpointRecord | null };\n }>(\n `query WebhookEndpoint($workflowId: String!, $driveId: String) {\n workflowRuntime {\n webhookEndpoint(workflowId: $workflowId, driveId: $driveId) {\n workflowId url absoluteUrl armed createdAt\n }\n }\n }`,\n { workflowId, driveId: driveId ?? null },\n );\n return data.workflowRuntime.webhookEndpoint;\n}\n\nexport async function testTrigger(\n t: Transport,\n workflowId: string,\n driveId?: string,\n): Promise<unknown> {\n const data = await t.gql<{ workflowRuntime: { testTrigger: unknown } }>(\n `mutation TestTrigger($workflowId: String!, $driveId: String) {\n workflowRuntime { testTrigger(workflowId: $workflowId, driveId: $driveId) }\n }`,\n { workflowId, driveId: driveId ?? null },\n );\n return data.workflowRuntime.testTrigger;\n}\n\nexport interface CoreTriggerTestOptions {\n // The manual trigger: the sample payload.\n payload?: unknown;\n // The webhook trigger: how long to wait for a delivery (default and cap 300).\n timeoutSeconds?: number;\n // Lets the runtime wait for a workflow that hasn't synced yet.\n driveId?: string;\n}\n\n// Tests the draft trigger, core ones included: manual saves `payload`, schedule\n// samples a fire now, webhook resolves with the next delivery to its endpoint.\nexport async function testCoreTrigger(\n t: Transport,\n workflowId: string,\n options: CoreTriggerTestOptions = {},\n): Promise<unknown> {\n const data = await t.gql<{ workflowRuntime: { testTrigger: unknown } }>(\n `mutation TestCoreTrigger($workflowId: String!, $payload: Unknown, $timeoutSeconds: Int, $driveId: String) {\n workflowRuntime {\n testTrigger(workflowId: $workflowId, payload: $payload, timeoutSeconds: $timeoutSeconds, driveId: $driveId)\n }\n }`,\n {\n workflowId,\n payload: options.payload ?? null,\n timeoutSeconds: options.timeoutSeconds ?? null,\n driveId: options.driveId ?? null,\n },\n );\n return data.workflowRuntime.testTrigger;\n}\n\n// Stops a waiting webhook test; false when none was waiting.\nexport async function cancelTriggerTest(\n t: Transport,\n workflowId: string,\n): Promise<boolean> {\n const data = await t.gql<{ workflowRuntime: { cancelTriggerTest: boolean } }>(\n `mutation CancelTriggerTest($workflowId: String!) {\n workflowRuntime { cancelTriggerTest(workflowId: $workflowId) }\n }`,\n { workflowId },\n );\n return data.workflowRuntime.cancelTriggerTest;\n}\n\nexport interface StepTestResult {\n // Null when the test never started, e.g. `Test \"fetch\" first`.\n runId: string | null;\n // INDETERMINATE: a write the step asked for may have landed.\n status: \"SUCCEEDED\" | \"FAILED\" | \"INDETERMINATE\";\n output: unknown;\n error: string | null;\n // The thrown error's name, e.g. ReactorAccessDeniedError.\n errorName: string | null;\n durationMs: number;\n}\n\n// Runs one draft step against the latest test outputs of the blocks it reads.\nexport async function testStep(\n t: Transport,\n workflowId: string,\n stepId: string,\n driveId?: string,\n): Promise<StepTestResult> {\n const data = await t.gql<{ workflowRuntime: { testStep: StepTestResult } }>(\n `mutation TestStep($workflowId: String!, $stepId: String!, $driveId: String) {\n workflowRuntime {\n testStep(workflowId: $workflowId, stepId: $stepId, driveId: $driveId) {\n runId status output error errorName durationMs\n }\n }\n }`,\n { workflowId, stepId, driveId: driveId ?? null },\n );\n return data.workflowRuntime.testStep;\n}\n\nexport type BlockMatch =\n | \"exact\"\n | \"compatible\"\n | \"fallback\"\n | \"installed\"\n | \"missing\";\n\nexport interface BlockResolution {\n // The trigger's or step's id.\n stepId: string;\n pieceName: string;\n // The version the block pins.\n pieceVersion: string;\n name: string;\n kind: \"action\" | \"trigger\";\n // Null when nothing resolves.\n resolvedVersion: string | null;\n source: \"local\" | \"registry\" | \"activepieces\" | \"npm\" | null;\n match: BlockMatch;\n // Why the version that runs differs from the pin, or why nothing resolves.\n note: string | null;\n // Newest version any source offers.\n latestVersion: string | null;\n}\n\n// Every block of the draft, trigger first, as the runtime would run it.\nexport async function blockResolutions(\n t: Transport,\n workflowId: string,\n): Promise<BlockResolution[]> {\n const data = await t.gql<{\n workflowRuntime: { blockResolutions: BlockResolution[] };\n }>(\n `query BlockResolutions($workflowId: String!) {\n workflowRuntime {\n blockResolutions(workflowId: $workflowId) {\n stepId pieceName pieceVersion name kind resolvedVersion source match note latestVersion\n }\n }\n }`,\n { workflowId },\n );\n return data.workflowRuntime.blockResolutions;\n}\n\nexport interface RunStepRecord {\n stepId: string;\n stepKey: string;\n // One loop iteration: \"<loop>[<i>]/<step>\", i from 1; null for the step's own row.\n path?: string | null;\n pieceName: string;\n // The action the step ran, or the trigger a trigger test sampled.\n blockName: string;\n status: string;\n // Undefined on a listing row (fetchRunsPage); fetchRun reads them.\n input: unknown;\n output: unknown;\n port: string | null;\n error: string | null;\n errorName: string | null;\n // Null for skipped and replayed steps, and for runs journaled before timings.\n startedAt: string | null;\n endedAt: string | null;\n}\n\nexport interface RunRecord {\n id: string;\n workflowId: string;\n workflowName: string;\n workflowVersion: number;\n triggerKind: string;\n triggerPayload: unknown;\n status: string;\n error: string | null;\n errorName: string | null;\n startedAt: string;\n endedAt: string | null;\n rerunOf: string | null;\n // Why a finished run is not a plain success, e.g. an edge nothing takes.\n warningNotes: string[];\n // One row per step; a loop body's step holds its last iteration.\n steps: RunStepRecord[];\n // Each loop iteration's rows, in execution order.\n iterations?: RunStepRecord[];\n // Set by fetchRun when it holds only the first iterations: all there are.\n iterationsTotal?: number | null;\n // Read by fetchRun and fetchWaitingRuns; listings leave them out.\n waitpoints?: WaitpointRecord[];\n}\n\nexport interface ApprovalRequest {\n title: string;\n // Markdown.\n body: string | null;\n approveLabel: string;\n rejectLabel: string;\n reasonRequiredOn: \"none\" | \"reject\" | \"both\";\n // DIDs allowed to decide; empty means anyone with write access.\n approvers: string[];\n}\n\nexport interface WaitpointRecord {\n id: string;\n runId: string;\n workflowId: string;\n stepId: string;\n stepKey: string;\n stepPath: string;\n pieceName: string;\n blockName: string;\n type: \"DELAY\" | \"WEBHOOK\";\n kind: \"approval\" | \"webhook\" | \"delay\";\n status: \"PENDING\" | \"COMPLETED\" | \"CONSUMED\" | \"EXPIRED\" | \"CANCELLED\";\n createdAt: string;\n resumeAt: string | null;\n expiresAt: string | null;\n resolvedAt: string | null;\n decidedBy: string | null;\n approval: ApprovalRequest | null;\n}\n\nconst WAITPOINT_FIELDS = `id runId workflowId stepId stepKey stepPath pieceName\n blockName type kind status createdAt resumeAt expiresAt resolvedAt decidedBy\n approval { title body approveLabel rejectLabel reasonRequiredOn approvers }`;\n\nconst RUN_ROW_FIELDS = `id workflowId workflowName workflowVersion triggerKind\n triggerPayload status error errorName startedAt endedAt rerunOf warningNotes`;\nconst STEP_ROW_FIELDS =\n \"stepId stepKey path pieceName blockName status port error errorName startedAt endedAt\";\n\n// Splits a loop's iteration rows off the steps, which stay one row per step.\nexport function withIterations(run: RunRecord): RunRecord {\n const iterations = run.steps.filter((step) => step.path);\n if (iterations.length === 0) return run;\n return {\n ...run,\n steps: run.steps.filter((step) => !step.path),\n iterations,\n };\n}\nconst RUN_FIELDS = `${RUN_ROW_FIELDS} steps { ${STEP_ROW_FIELDS} input output }`;\n// A listing row: the steps without their input and output.\nconst RUN_LIST_FIELDS = `${RUN_ROW_FIELDS} steps { ${STEP_ROW_FIELDS} }`;\nconst RUN_DETAIL_FIELDS = `${RUN_FIELDS} iterationsTotal waitpoints { ${WAITPOINT_FIELDS} }`;\n\nexport interface RunsScope {\n workflowId?: string;\n // Scopes runs to the workflows the drive holds; ignored alongside workflowId.\n driveId?: string;\n limit?: number;\n // Left out by the runtime, so they never cost a page its rows.\n excludeTriggerKinds?: string[];\n}\n\nfunction scopeVariables(scope: RunsScope, limit: number) {\n return {\n workflowId: scope.workflowId ?? null,\n driveId: scope.driveId ?? null,\n excludeTriggerKinds: scope.excludeTriggerKinds ?? null,\n limit: scope.limit ?? limit,\n };\n}\n\nexport async function fetchRuns(\n t: Transport,\n scope: RunsScope = {},\n): Promise<RunRecord[]> {\n const data = await t.gql<{ workflowRuntime: { runs: RunRecord[] } }>(\n `query Runs($workflowId: String, $driveId: String, $limit: Int, $excludeTriggerKinds: [String!]) {\n workflowRuntime { runs(workflowId: $workflowId, driveId: $driveId, limit: $limit, excludeTriggerKinds: $excludeTriggerKinds) { ${RUN_FIELDS} } }\n }`,\n scopeVariables(scope, 30),\n );\n return data.workflowRuntime.runs.map(withIterations);\n}\n\n// Steps come without input and output; fetchRun has them.\nexport interface RunPage {\n items: RunRecord[];\n hasNextPage: boolean;\n cursor: string | null;\n}\n\nexport async function fetchRunsPage(\n t: Transport,\n scope: RunsScope = {},\n cursor: string | null = null,\n): Promise<RunPage> {\n const { limit, ...rest } = scopeVariables(scope, 30);\n const data = await t.gql<{ workflowRuntime: { runsPage: RunPage } }>(\n `query RunsPage($workflowId: String, $driveId: String, $excludeTriggerKinds: [String!], $paging: WorkflowRunsPagingInput) {\n workflowRuntime {\n runsPage(workflowId: $workflowId, driveId: $driveId, excludeTriggerKinds: $excludeTriggerKinds, paging: $paging) {\n items { ${RUN_LIST_FIELDS} } hasNextPage cursor\n }\n }\n }`,\n { ...rest, paging: { limit, cursor } },\n );\n const page = data.workflowRuntime.runsPage;\n return { ...page, items: page.items.map(withIterations) };\n}\n\nexport async function fetchRun(\n t: Transport,\n runId: string,\n): Promise<RunRecord | null> {\n const data = await t.gql<{ workflowRuntime: { run: RunRecord | null } }>(\n `query Run($id: String!) { workflowRuntime { run(id: $id) { ${RUN_DETAIL_FIELDS} } } }`,\n { id: runId },\n );\n const run = data.workflowRuntime.run;\n return run ? withIterations(run) : null;\n}\n\nexport interface WaitingRunsScope {\n // Every workflow the drive holds; ignored alongside workflowId.\n driveId?: string;\n workflowId?: string;\n first?: number;\n}\n\n// WAITING runs with their waitpoints, steps without input and output.\nexport async function fetchWaitingRuns(\n t: Transport,\n scope: WaitingRunsScope = {},\n): Promise<RunRecord[]> {\n const data = await t.gql<{ workflowRuntime: { waitingRuns: RunRecord[] } }>(\n `query WaitingRuns($driveId: String, $workflowId: String, $first: Int) {\n workflowRuntime {\n waitingRuns(driveId: $driveId, workflowId: $workflowId, first: $first) {\n ${RUN_LIST_FIELDS} waitpoints { ${WAITPOINT_FIELDS} }\n }\n }\n }`,\n {\n driveId: scope.driveId ?? null,\n workflowId: scope.workflowId ?? null,\n first: scope.first ?? null,\n },\n );\n return data.workflowRuntime.waitingRuns.map(withIterations);\n}\n\n// Approves or rejects a PENDING approval, resuming its run.\nexport async function resolveWaitpoint(\n t: Transport,\n waitpointId: string,\n approved: boolean,\n reason?: string,\n): Promise<WaitpointRecord> {\n const data = await t.gql<{\n workflowRuntime: { resolveWaitpoint: WaitpointRecord };\n }>(\n `mutation ResolveWaitpoint($waitpointId: String!, $approved: Boolean!, $reason: String) {\n workflowRuntime {\n resolveWaitpoint(waitpointId: $waitpointId, approved: $approved, reason: $reason) {\n ${WAITPOINT_FIELDS}\n }\n }\n }`,\n { waitpointId, approved, reason: reason ?? null },\n );\n return data.workflowRuntime.resolveWaitpoint;\n}\n\nexport interface FireResult {\n runId: string | null;\n status: string;\n error: string | null;\n}\n\nexport async function fireWorkflow(\n t: Transport,\n workflowId: string,\n payload?: unknown,\n): Promise<FireResult> {\n const data = await t.gql<{ workflowRuntime: { fire: FireResult } }>(\n `mutation Fire($workflowId: String!, $payload: Unknown) {\n workflowRuntime { fire(workflowId: $workflowId, payload: $payload) { runId status error } }\n }`,\n { workflowId, payload: payload ?? {} },\n );\n return data.workflowRuntime.fire;\n}\n\n// Resume a FAILED run: succeeded steps replay, execution restarts at the\n// failure. Returns the new run.\nexport async function rerunRun(\n t: Transport,\n runId: string,\n): Promise<FireResult> {\n const data = await t.gql<{ workflowRuntime: { rerun: FireResult } }>(\n `mutation Rerun($runId: String!) {\n workflowRuntime { rerun(runId: $runId) { runId status error } }\n }`,\n { runId },\n );\n return data.workflowRuntime.rerun;\n}\n\n// Cancels a WAITING or PENDING run and its open waitpoints.\nexport async function cancelRun(\n t: Transport,\n runId: string,\n): Promise<FireResult | null> {\n const data = await t.gql<{\n workflowRuntime: { cancelRun: FireResult | null };\n }>(\n `mutation CancelRun($runId: String!) {\n workflowRuntime { cancelRun(runId: $runId) { runId status error } }\n }`,\n { runId },\n );\n return data.workflowRuntime.cancelRun;\n}\n\ninterface BlockOptionsResult {\n workflowRuntime: { blockOptions: unknown };\n}\n\nexport async function loadBlockOptions(\n t: Transport,\n block: BlockRef,\n propName: string,\n input: Record<string, unknown>,\n connectionId?: string,\n searchValue?: string,\n // Narrows a reactor-reading resolver to what the step's connection reaches.\n reactorConnectionId?: string,\n // The workflow being edited: what a sub-flow dropdown lists.\n workflowId?: string,\n): Promise<unknown> {\n const data = await t.gql<BlockOptionsResult>(\n `query Options($block: BlockInput!, $propName: String!, $input: Unknown, $connectionId: String, $searchValue: String, $reactorConnectionId: String, $workflowId: String) {\n workflowRuntime { blockOptions(block: $block, propName: $propName, input: $input, connectionId: $connectionId, searchValue: $searchValue, reactorConnectionId: $reactorConnectionId, workflowId: $workflowId) }\n }`,\n {\n block: blockInput(block),\n propName,\n input,\n connectionId: connectionId ?? null,\n searchValue: searchValue ?? null,\n reactorConnectionId: reactorConnectionId ?? null,\n workflowId: workflowId ?? null,\n },\n );\n return data.workflowRuntime.blockOptions;\n}\n\nconst operations = {\n getBlockForm,\n fetchPieceCatalog,\n fetchPieceActions,\n fetchPieceTriggers,\n searchPieces,\n fetchBlockOutputTree,\n fetchStepOutputTree,\n fetchConnections,\n checkConnection,\n fetchReactorAccess,\n fetchReactorAccessDenial,\n fetchOAuthRedirectUri,\n startOAuth,\n fetchOAuthAttempt,\n createSecret,\n rotateSecret,\n fetchSecretStat,\n fetchWebhookEndpoint,\n testTrigger,\n testCoreTrigger,\n cancelTriggerTest,\n testStep,\n blockResolutions,\n fetchRuns,\n fetchRunsPage,\n fetchRun,\n fetchWaitingRuns,\n fireWorkflow,\n rerunRun,\n resolveWaitpoint,\n cancelRun,\n loadBlockOptions,\n};\n\ntype Operations = typeof operations;\ntype Bound<F> = F extends (t: Transport, ...args: infer A) => infer R\n ? (...args: A) => R\n : never;\ntype BoundOperations = { [K in keyof Operations]: Bound<Operations[K]> };\n\n// Every workflow-runtime call, bound to one subgraph URL. Holds no cache.\nexport type RuntimeClient = Transport & BoundOperations;\n\nexport function createRuntimeClient(\n url: string,\n options: RuntimeClientOptions = {},\n): RuntimeClient {\n const transport = createTransport(url, options);\n const bound = Object.fromEntries(\n Object.entries(operations).map(([name, operation]) => [\n name,\n (...args: unknown[]) =>\n (operation as (t: Transport, ...rest: unknown[]) => unknown)(\n transport,\n ...args,\n ),\n ]),\n ) as BoundOperations;\n return { ...transport, ...bound };\n}\n","// Design-time tests are journaled as runs of this kind.\nexport const TEST_TRIGGER_KIND = \"test\";\n\n// Runs as the author sees them: tests aren't executions of the workflow.\nexport function realRuns<T extends { triggerKind: string }>(runs: T[]): T[] {\n return runs.filter((run) => run.triggerKind !== TEST_TRIGGER_KIND);\n}\n","// Query keys for runtime data. Every key starts with the runtime URL (the\n// \"scope\"), so two runtimes never share an entry.\nimport type { BlockRef } from \"@powerhousedao/pieces-framework/block-type\";\n\n// A block as a key part: every field, the version included.\nexport function blockPart(block: BlockRef) {\n return [block.pieceName, block.pieceVersion, block.kind, block.name] as const;\n}\n\n// The same, as one string for a Map key.\nexport function blockRefKey(block: BlockRef): string {\n return blockPart(block).join(\" \");\n}\n\nexport type RuntimeQueryKind =\n | \"catalog\"\n | \"form\"\n | \"pieceActions\"\n | \"pieceTriggers\"\n | \"searchPieces\"\n | \"outputTree\"\n | \"options\"\n | \"dynamic\"\n | \"connections\"\n | \"webhook\"\n | \"latestRun\"\n | \"runs\"\n | \"run\"\n | \"secret\"\n | \"blockResolutions\"\n | \"reactorAccess\"\n | \"reactorDenial\";\n\nexport interface ResolverKeyInput {\n block: BlockRef;\n propName: string;\n // Values of the prop's refreshers, in declaration order.\n refreshers: unknown[];\n connectionId?: string | null;\n searchValue?: string | null;\n reactorConnectionId?: string | null;\n}\n\nfunction resolverKey(\n scope: string,\n kind: \"options\" | \"dynamic\",\n input: ResolverKeyInput,\n) {\n return [\n scope,\n kind,\n blockPart(input.block),\n input.propName,\n input.refreshers,\n input.connectionId ?? null,\n input.searchValue ?? null,\n input.reactorConnectionId ?? null,\n ] as const;\n}\n\nexport const runtimeKeys = {\n all: (scope: string) => [scope] as const,\n catalog: (scope: string) => [scope, \"catalog\"] as const,\n form: (scope: string, block: BlockRef) =>\n [scope, \"form\", blockPart(block)] as const,\n pieceActions: (scope: string, packageName: string) =>\n [scope, \"pieceActions\", packageName] as const,\n pieceTriggers: (scope: string, packageName: string) =>\n [scope, \"pieceTriggers\", packageName] as const,\n searchPieces: (scope: string, query: string, filter: unknown) =>\n [scope, \"searchPieces\", query, filter] as const,\n outputTrees: (scope: string) => [scope, \"outputTree\"] as const,\n outputTree: (scope: string, block: BlockRef, config: unknown) =>\n [scope, \"outputTree\", blockPart(block), config ?? {}] as const,\n // Keyed by the test it reads, so a new test is a new entry.\n stepOutputTree: (\n scope: string,\n workflowId: string,\n stepId: string,\n testedAt: string | null,\n ) => [scope, \"outputTree\", \"step\", workflowId, stepId, testedAt] as const,\n options: (scope: string, input: ResolverKeyInput) =>\n resolverKey(scope, \"options\", input),\n dynamic: (scope: string, input: ResolverKeyInput) =>\n resolverKey(scope, \"dynamic\", input),\n // `filter` tells apart listings a caller narrows, e.g. to one drive.\n connections: (scope: string, filter?: string | null) =>\n filter === undefined\n ? ([scope, \"connections\"] as const)\n : ([scope, \"connections\", filter] as const),\n webhook: (scope: string, workflowId: string) =>\n [scope, \"webhook\", workflowId] as const,\n latestRun: (scope: string, workflowId: string) =>\n [scope, \"latestRun\", workflowId] as const,\n allRuns: (scope: string) => [scope, \"runs\"] as const,\n runs: (\n scope: string,\n runsScope: { workflowId?: string; driveId?: string; limit?: number },\n ) =>\n [\n scope,\n \"runs\",\n {\n workflowId: runsScope.workflowId ?? null,\n driveId: runsScope.driveId ?? null,\n limit: runsScope.limit ?? null,\n },\n ] as const,\n // Under allRuns, so every invalidation of the listing reaches the pages.\n runPages: (\n scope: string,\n runsScope: { workflowId?: string; driveId?: string; limit?: number },\n ) =>\n [\n scope,\n \"runs\",\n \"pages\",\n {\n workflowId: runsScope.workflowId ?? null,\n driveId: runsScope.driveId ?? null,\n limit: runsScope.limit ?? null,\n },\n ] as const,\n // Under allRuns, so a run that starts, resumes or ends refreshes it.\n waitingRuns: (\n scope: string,\n waiting: { driveId?: string; workflowId?: string; first?: number },\n ) =>\n [\n scope,\n \"runs\",\n \"waiting\",\n {\n driveId: waiting.driveId ?? null,\n workflowId: waiting.workflowId ?? null,\n first: waiting.first ?? null,\n },\n ] as const,\n run: (scope: string, runId: string) => [scope, \"run\", runId] as const,\n // Per viewer: the identity is only served to a signed-in caller.\n reactorAccess: (scope: string, viewer: string | null) =>\n [scope, \"reactorAccess\", viewer] as const,\n reactorDenial: (scope: string, workflowId: string) =>\n [scope, \"reactorDenial\", workflowId] as const,\n secret: (scope: string, ref: string) => [scope, \"secret\", ref] as const,\n allBlockResolutions: (scope: string, workflowId: string) =>\n [scope, \"blockResolutions\", workflowId] as const,\n // `blocks` is the draft's, trigger first, so an edit is a new entry.\n blockResolutions: (\n scope: string,\n workflowId: string,\n blocks: readonly BlockRef[],\n ) => [scope, \"blockResolutions\", workflowId, blocks.map(blockPart)] as const,\n};\n\nexport function queryKind(key: readonly unknown[]): string | undefined {\n return typeof key[1] === \"string\" ? key[1] : undefined;\n}\n\n// Piece metadata that is the same for every caller of one runtime.\nexport const SHARED_STALE_MS = 30 * 60_000;\n// Resolver answers depend on the caller's connection; kept briefly.\nexport const RESOLVER_STALE_MS = 5 * 60_000;\n","// Query options over a RuntimeClient. Keys come from ui/query-keys, so the\n// editor's hooks and these factories address the same cache entries.\nimport {\n infiniteQueryOptions,\n mutationOptions,\n QueryClient,\n queryOptions,\n useMutation,\n} from \"@tanstack/react-query\";\nimport type { BlockRef } from \"@powerhousedao/pieces-framework/block-type\";\nimport type {\n RunPage,\n RunRecord,\n RunsScope,\n RuntimeClient,\n StepTestResult,\n WaitingRunsScope,\n} from \"./runtime-client.js\";\nimport { realRuns, TEST_TRIGGER_KIND } from \"./run-kinds.js\";\nimport { runtimeKeys, SHARED_STALE_MS } from \"./ui/query-keys.js\";\n\nexport function createRuntimeQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: {\n // Callers surface failures themselves, with their own retry buttons.\n queries: { retry: false, refetchOnWindowFocus: false },\n mutations: { retry: false },\n },\n });\n}\n\nexport const catalogQuery = (client: RuntimeClient) =>\n queryOptions({\n queryKey: runtimeKeys.catalog(client.url),\n queryFn: () => client.fetchPieceCatalog(),\n staleTime: SHARED_STALE_MS,\n });\n\nexport const blockFormQuery = (client: RuntimeClient, block: BlockRef) =>\n queryOptions({\n queryKey: runtimeKeys.form(client.url, block),\n queryFn: () => client.getBlockForm(block),\n staleTime: SHARED_STALE_MS,\n });\n\nexport const pieceActionsQuery = (client: RuntimeClient, packageName: string) =>\n queryOptions({\n queryKey: runtimeKeys.pieceActions(client.url, packageName),\n queryFn: () => client.fetchPieceActions(packageName),\n staleTime: SHARED_STALE_MS,\n });\n\nexport const pieceTriggersQuery = (\n client: RuntimeClient,\n packageName: string,\n) =>\n queryOptions({\n queryKey: runtimeKeys.pieceTriggers(client.url, packageName),\n queryFn: () => client.fetchPieceTriggers(packageName),\n staleTime: SHARED_STALE_MS,\n });\n\n// Kept until a test trigger could have changed the sample it derives from.\nexport const outputTreeQuery = (\n client: RuntimeClient,\n block: BlockRef,\n config: unknown,\n) =>\n queryOptions({\n queryKey: runtimeKeys.outputTree(client.url, block, config),\n queryFn: () => client.fetchBlockOutputTree(block, config),\n staleTime: Infinity,\n });\n\n// A given test's sample never changes; the key moves on with lastTest.\nexport const stepOutputTreeQuery = (\n client: RuntimeClient,\n workflowId: string,\n stepId: string,\n testedAt: string | null,\n) =>\n queryOptions({\n queryKey: runtimeKeys.stepOutputTree(\n client.url,\n workflowId,\n stepId,\n testedAt,\n ),\n queryFn: () => client.fetchStepOutputTree(workflowId, stepId),\n staleTime: Infinity,\n });\n\n// Test runs are left out: they belong to the trigger's test, not the history.\nconst REAL_RUNS = [TEST_TRIGGER_KIND];\n\nexport const runsQuery = (client: RuntimeClient, scope: RunsScope) =>\n queryOptions({\n queryKey: runtimeKeys.runs(client.url, scope),\n queryFn: () =>\n client\n .fetchRuns({ ...scope, excludeTriggerKinds: REAL_RUNS })\n .then(realRuns),\n staleTime: 0,\n });\n\n// Tests are left out by the runtime, so the newest row is the latest real run.\nexport const LATEST_RUN_WINDOW = 1;\n\n// The runs views' listing, a page at a time, without step input and output.\nexport const runPagesQuery = (client: RuntimeClient, scope: RunsScope) =>\n infiniteQueryOptions({\n queryKey: runtimeKeys.runPages(client.url, scope),\n queryFn: ({ pageParam }) =>\n client.fetchRunsPage(\n { ...scope, excludeTriggerKinds: REAL_RUNS },\n pageParam,\n ),\n initialPageParam: null as string | null,\n getNextPageParam: (page: RunPage) =>\n page.hasNextPage && page.cursor ? page.cursor : undefined,\n staleTime: 0,\n });\n\n// Pages flattened, once each: a run that starts moves up past a page break.\nexport function runsOfPages(pages: readonly RunPage[]): RunRecord[] {\n const seen = new Set<string>();\n return realRuns(pages.flatMap((page) => page.items)).filter((run) => {\n if (seen.has(run.id)) return false;\n seen.add(run.id);\n return true;\n });\n}\n\nexport const waitingRunsQuery = (\n client: RuntimeClient,\n scope: WaitingRunsScope,\n) =>\n queryOptions({\n queryKey: runtimeKeys.waitingRuns(client.url, scope),\n queryFn: () => client.fetchWaitingRuns(scope),\n staleTime: 0,\n });\n\nconst FINISHED = new Set([\"SUCCEEDED\", \"FAILED\", \"CANCELLED\"]);\n\nexport const runQuery = (client: RuntimeClient, runId: string) =>\n queryOptions({\n queryKey: runtimeKeys.run(client.url, runId),\n queryFn: () => client.fetchRun(runId),\n // A finished run never changes.\n staleTime: (query) =>\n query.state.data && FINISHED.has(query.state.data.status) ? Infinity : 0,\n });\n\nexport const connectionsQuery = (client: RuntimeClient) =>\n queryOptions({\n queryKey: runtimeKeys.connections(client.url),\n queryFn: () => client.fetchConnections(),\n staleTime: 0,\n });\n\nexport const secretStatQuery = (client: RuntimeClient, ref: string) =>\n queryOptions({\n queryKey: runtimeKeys.secret(client.url, ref),\n queryFn: () => client.fetchSecretStat(ref),\n staleTime: 0,\n });\n\nexport interface TestStepVariables {\n workflowId: string;\n stepId: string;\n}\n\n// A step test is a new run and a new sample for the output trees.\nexport const testStepMutation = (\n client: RuntimeClient,\n queryClient: QueryClient,\n) =>\n mutationOptions<StepTestResult, Error, TestStepVariables>({\n mutationFn: ({ workflowId, stepId }) => client.testStep(workflowId, stepId),\n onSettled: () =>\n Promise.all(\n [\n runtimeKeys.allRuns(client.url),\n [client.url, \"latestRun\"],\n runtimeKeys.outputTrees(client.url),\n ].map((queryKey) => queryClient.invalidateQueries({ queryKey })),\n ),\n });\n\nexport function useTestStep(client: RuntimeClient, queryClient: QueryClient) {\n return useMutation(testStepMutation(client, queryClient), queryClient);\n}\n"],"mappings":";;;;;AAgOA,MAAa,qBAAoC;CAC/C,MAAM;CACN,aAAa;CACb,MAAM;CACN,UAAU;CACV,aACE;AACJ;;;ACtNA,MAAa,aAAa;AAG1B,MAAa,gBAAgB;AAE7B,MAAM,QAAQ,MAAiB,UAAiC;CAC9D,WAAW;CACX;CACA;AACF;AAEA,MAAa,iBAAiB,KAAK,WAAW,QAAQ;AACtD,MAAa,mBAAmB,KAAK,WAAW,UAAU;AAC1D,MAAa,kBAAkB,KAAK,WAAW,SAAS;AACxD,MAAa,eAAe,KAAK,UAAU,QAAQ;AACnD,MAAa,eAAe,KAAK,UAAU,QAAQ;AACnD,MAAa,aAAa,KAAK,UAAU,MAAM;AAC/C,MAAa,eAAe,KAAK,UAAU,QAAQ;AACnD,MAAa,cAAc,KAAK,UAAU,OAAO;AACjD,MAAa,iBAAiB,KAAK,UAAU,UAAU;AACvD,MAAa,aAAa,KAAK,UAAU,MAAM;AAC/C,MAAa,yBAAyB,KAAK,UAAU,gBAAgB;AAIrE,MAAa,mBAAmB;AAChC,MAAM,YAAY,MAAiB,UAA6B;CAC9D,WAAW;CACX,cAAc;CACd;CACA;AACF;AACA,MAAaA,0BAAwB,SACnC,WACAC,qBACF;AACA,MAAa,kBAAkB,SAAS,UAAU,gBAAgB;AAClE,MAAa,wBAAwB,SAAS,UAAU,gBAAgB;AAKxE,SAAgB,UACd,GACA,GACS;CACT,OAAO,QAAQ,KAAK,KAAK,SAAS,CAAC,MAAM,SAAS,CAAC,CAAC;AACtD;AAEA,SAAgB,YAAY,OAAuC;CACjE,OAAO,MAAM,cAAc;AAC7B;AAIA,SAAgB,oBAAoB,OAAuC;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Q;CAClB,WAAW;AACb,CAAC;AAMH,MAAa,iBAAiB,QAAuB,UACnD,qBAAqB;CACnB,UAAU,YAAY,SAAS,OAAO,KAAK,KAAK;CAChD,UAAU,EAAE,gBACV,OAAO,cACL;EAAE,GAAG;EAAO,qBAAqB;CAAU,GAC3C,SACF;CACF,kBAAkB;CAClB,mBAAmB,SACjB,KAAK,eAAe,KAAK,SAAS,KAAK,SAAS,KAAA;CAClD,WAAW;AACb,CAAC;AAGH,SAAgB,YAAY,OAAwC;CAClE,MAAM,uBAAO,IAAI,IAAY;CAC7B,OAAO,SAAS,MAAM,SAAS,SAAS,KAAK,KAAK,CAAC,CAAC,CAAC,QAAQ,QAAQ;EACnE,IAAI,KAAK,IAAI,IAAI,EAAE,GAAG,OAAO;EAC7B,KAAK,IAAI,IAAI,EAAE;EACf,OAAO;CACT,CAAC;AACH;AAEA,MAAa,oBACX,QACA,UAEA,aAAa;CACX,UAAU,YAAY,YAAY,OAAO,KAAK,KAAK;CACnD,eAAe,OAAO,iBAAiB,KAAK;CAC5C,WAAW;AACb,CAAC;AAEH,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAa;CAAU;AAAW,CAAC;AAE7D,MAAa,YAAY,QAAuB,UAC9C,aAAa;CACX,UAAU,YAAY,IAAI,OAAO,KAAK,KAAK;CAC3C,eAAe,OAAO,SAAS,KAAK;CAEpC,YAAY,UACV,MAAM,MAAM,QAAQ,SAAS,IAAI,MAAM,MAAM,KAAK,MAAM,IAAI,WAAW;AAC3E,CAAC;AASH,MAAa,mBAAmB,QAAuB,QACrD,aAAa;CACX,UAAU,YAAY,OAAO,OAAO,KAAK,GAAG;CAC5C,eAAe,OAAO,gBAAgB,GAAG;CACzC,WAAW;AACb,CAAC"}
@@ -1,5 +1,5 @@
1
- import { B as SCHEDULE_TRIGGER, I as MANUAL_TRIGGER, K as WEBHOOK_TRIGGER, Q as triggerBlock, X as stepBlock } from "./runtime-queries-C5bqAgQy.js";
2
- import { $ as useOptionSearch, At as Button, Bt as Tooltip, Ft as Segmented, Gt as isIconName, Ht as textAreaClass, It as Select, Lt as Switch, Nt as Hint, Pt as IconButton, Rt as Tabs, Ut as textInputClass, Vt as invalidClass, Wt as Icon, Y as useDynamicCache, ct as parsePropList, et as useResolvedProp, f as blockMeta, ft as stripOptions, jt as FieldError, lt as resolverInputFor, mt as withSetting, ot as isEmptyValue, p as namedByCoreTab, st as isPropVisible, t as BlockLogo, ut as settingFor, zt as Toggle } from "./BlockSelector-DFzzAWXh.js";
1
+ import { B as SCHEDULE_TRIGGER, I as MANUAL_TRIGGER, K as WEBHOOK_TRIGGER, Q as triggerBlock, X as stepBlock } from "./runtime-queries-FmEzElOY.js";
2
+ import { $ as useOptionSearch, At as Button, Bt as Tooltip, Ft as Segmented, Gt as isIconName, Ht as textAreaClass, It as Select, Lt as Switch, Nt as Hint, Pt as IconButton, Rt as Tabs, Ut as textInputClass, Vt as invalidClass, Wt as Icon, Y as useDynamicCache, ct as parsePropList, et as useResolvedProp, f as blockMeta, ft as stripOptions, jt as FieldError, lt as resolverInputFor, mt as withSetting, ot as isEmptyValue, p as namedByCoreTab, st as isPropVisible, t as BlockLogo, ut as settingFor, zt as Toggle } from "./BlockSelector-CEdYUqjx.js";
3
3
  import { useSetSelectedNode } from "@powerhousedao/reactor-browser";
4
4
  import { blockKey } from "@powerhousedao/pieces-framework/block-type";
5
5
  import { DOCUMENT_REF_KEY, NEXT_PORT, documentRefsIn, expandDocumentRefs, isDocumentRefMarker, parseScheduleConfig, stepPorts } from "@powerhousedao/pieces-framework/workflow";
@@ -2987,7 +2987,7 @@ function DocumentRefs(props) {
2987
2987
  }
2988
2988
  //#endregion
2989
2989
  //#region editors/shared/data-viewer.tsx
2990
- const DataTree = lazy(() => import("./data-tree-DKS0EQys.js"));
2990
+ const DataTree = lazy(() => import("./data-tree-Cq-s6bJp.js"));
2991
2991
  function stringify(value) {
2992
2992
  try {
2993
2993
  return JSON.stringify(value, null, 2) ?? "";
@@ -3207,4 +3207,4 @@ function describeTrigger(trigger) {
3207
3207
  //#endregion
3208
3208
  export { ExpressionTargetProvider as A, documentShape as B, PropertyForm as C, ExpressionPickerButton as D, useSecretRef as E, VARIABLE_TYPES as F, usePendingEcho as G, contextMenuItems as H, VARIABLE_TYPE_LABEL as I, convertVariableValue as L, useExpressionField as M, EMPTY_SCOPE as N, ExpressionPickerPopup as O, buildExpressionScope as P, parseTypedValue as R, PiecePlaceholderContext as S, withPropDefaults as T, menuHeight as U, stateFieldsFromSdl as V, menuPosition as W, STEP_PARAM as _, StepError as a, uniqueStepKey as b, stepOutline as c, PublishButton as d, PublishState as f, usePublish as g, StatusToggle as h, DataViewer as i, ExpressionTokenLine as j, ExpressionScopeSourceProvider as k, DraftBanner as l, ReactorDenialNote as m, describeSchedule as n, TRIGGER_NODE as o, PublishedMissingNote as p, describeTrigger as r, graphLayout as s, describeCron as t, ManagedBanner as u, VARIABLES_VIEW as v, lacksDefaults as w, AvailableSoon as x, hasDraftChanges as y, valueMismatch as z };
3209
3209
 
3210
- //# sourceMappingURL=trigger-text-BfIu-QcC.js.map
3210
+ //# sourceMappingURL=trigger-text-DH6HIeoa.js.map