@powerhousedao/workflow 6.2.3-dev.88 → 6.2.3-dev.89

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 (108) hide show
  1. package/dist/browser/{BlockSelector-BKAJwJ4Y.js → BlockSelector-DFzzAWXh.js} +65 -7
  2. package/dist/browser/BlockSelector-DFzzAWXh.js.map +1 -0
  3. package/dist/browser/{connection-form-DltdMa8F.js → connection-form-B6zpGmAm.js} +3 -3
  4. package/dist/browser/{connection-form-DltdMa8F.js.map → connection-form-B6zpGmAm.js.map} +1 -1
  5. package/dist/browser/{data-tree-DAw8e0j8.js → data-tree-DKS0EQys.js} +2 -2
  6. package/dist/browser/{data-tree-DAw8e0j8.js.map → data-tree-DKS0EQys.js.map} +1 -1
  7. package/dist/browser/{editor-Dl6lzxkM.js → editor-Yt-_V04R.js} +207 -58
  8. package/dist/browser/editor-Yt-_V04R.js.map +1 -0
  9. package/dist/browser/{editor-CZLe6CAF.js → editor-bHCkW_XB.js} +4 -4
  10. package/dist/browser/{editor-CZLe6CAF.js.map → editor-bHCkW_XB.js.map} +1 -1
  11. package/dist/browser/{editor--J61vLSC.js → editor-gCkAwv09.js} +64 -132
  12. package/dist/browser/editor-gCkAwv09.js.map +1 -0
  13. package/dist/browser/editors/connection-editor/module.js +1 -1
  14. package/dist/browser/editors/runtime/index.js +1 -1
  15. package/dist/browser/editors/workflow-editor/module.js +1 -1
  16. package/dist/browser/editors/workflow-studio/module.js +1 -1
  17. package/dist/browser/index.js +2 -1
  18. package/dist/browser/index.js.map +1 -1
  19. package/dist/browser/{runtime-queries-D81Ghpok.js → runtime-queries-C5bqAgQy.js} +84 -13
  20. package/dist/browser/runtime-queries-C5bqAgQy.js.map +1 -0
  21. package/dist/browser/{trigger-text-BSVi5oGZ.js → trigger-text-BfIu-QcC.js} +176 -11
  22. package/dist/browser/trigger-text-BfIu-QcC.js.map +1 -0
  23. package/dist/node/{BlockSelector-DnTRF-C7.mjs → BlockSelector-Cia1Rpwz.mjs} +64 -6
  24. package/dist/node/BlockSelector-Cia1Rpwz.mjs.map +1 -0
  25. package/dist/node/{connection-form-DwSHfIRw.mjs → connection-form-CJFKPwfg.mjs} +3 -3
  26. package/dist/node/{connection-form-DwSHfIRw.mjs.map → connection-form-CJFKPwfg.mjs.map} +1 -1
  27. package/dist/node/{data-tree-uSJU9Ost.mjs → data-tree-D9jdFsaX.mjs} +2 -2
  28. package/dist/node/{data-tree-uSJU9Ost.mjs.map → data-tree-D9jdFsaX.mjs.map} +1 -1
  29. package/dist/node/{editor-B4ZwM3pR.mjs → editor-CwOjO82y.mjs} +63 -131
  30. package/dist/node/editor-CwOjO82y.mjs.map +1 -0
  31. package/dist/node/{editor-_4XHbqGl.mjs → editor-NMRVprgI.mjs} +206 -57
  32. package/dist/node/editor-NMRVprgI.mjs.map +1 -0
  33. package/dist/node/{editor-cXi5dIsd.mjs → editor-_c6UDRAN.mjs} +4 -4
  34. package/dist/node/{editor-cXi5dIsd.mjs.map → editor-_c6UDRAN.mjs.map} +1 -1
  35. package/dist/node/editors/connection-editor/module.mjs +1 -1
  36. package/dist/node/editors/runtime/index.mjs +1 -1
  37. package/dist/node/editors/workflow-editor/module.mjs +1 -1
  38. package/dist/node/editors/workflow-studio/module.mjs +1 -1
  39. package/dist/node/index.mjs +2 -1
  40. package/dist/node/index.mjs.map +1 -1
  41. package/dist/node/pieces/ai/descriptor.json +70 -1
  42. package/dist/node/pieces/ai/index.mjs +125 -125
  43. package/dist/node/pieces/ai/package.json +1 -1
  44. package/dist/node/pieces/reactor/descriptor.json +35 -1
  45. package/dist/node/pieces/reactor/index.mjs +39 -39
  46. package/dist/node/pieces/reactor/package.json +1 -1
  47. package/dist/node/{runtime-queries-VXJsWno5.mjs → runtime-queries-Ck5OoWdy.mjs} +137 -12
  48. package/dist/node/runtime-queries-Ck5OoWdy.mjs.map +1 -0
  49. package/dist/node/{trigger-text-BBP7QVLj.mjs → trigger-text-T2D0a2Br.mjs} +175 -10
  50. package/dist/node/trigger-text-T2D0a2Br.mjs.map +1 -0
  51. package/dist/powerhouse.manifest.json +2 -2
  52. package/dist/style.css +1 -1
  53. package/dist/types/ai/workflow-tools.d.ts.map +1 -1
  54. package/dist/types/editors/shared/icons.d.ts +4 -0
  55. package/dist/types/editors/shared/icons.d.ts.map +1 -1
  56. package/dist/types/editors/workflow-editor/editor.d.ts.map +1 -1
  57. package/dist/types/editors/workflow-editor/runtime-client.d.ts +5 -1
  58. package/dist/types/editors/workflow-editor/runtime-client.d.ts.map +1 -1
  59. package/dist/types/editors/workflow-editor/ui/BlockSelector.d.ts.map +1 -1
  60. package/dist/types/editors/workflow-editor/ui/PropertyForm.d.ts +1 -0
  61. package/dist/types/editors/workflow-editor/ui/PropertyForm.d.ts.map +1 -1
  62. package/dist/types/editors/workflow-editor/ui/StepPanel.d.ts.map +1 -1
  63. package/dist/types/editors/workflow-editor/ui/ap-edge.d.ts +1 -0
  64. package/dist/types/editors/workflow-editor/ui/ap-edge.d.ts.map +1 -1
  65. package/dist/types/editors/workflow-editor/ui/ap-layout.d.ts.map +1 -1
  66. package/dist/types/editors/workflow-editor/ui/ap-nodes.d.ts +4 -0
  67. package/dist/types/editors/workflow-editor/ui/ap-nodes.d.ts.map +1 -1
  68. package/dist/types/editors/workflow-editor/ui/block-meta.d.ts +3 -0
  69. package/dist/types/editors/workflow-editor/ui/block-meta.d.ts.map +1 -1
  70. package/dist/types/editors/workflow-editor/ui/blocks.d.ts +8 -0
  71. package/dist/types/editors/workflow-editor/ui/blocks.d.ts.map +1 -1
  72. package/dist/types/editors/workflow-editor/ui/canvas-menu.d.ts.map +1 -1
  73. package/dist/types/editors/workflow-editor/ui/flow-control.test.d.ts +2 -0
  74. package/dist/types/editors/workflow-editor/ui/flow-control.test.d.ts.map +1 -0
  75. package/dist/types/editors/workflow-editor/ui/prop-layout.d.ts +1 -0
  76. package/dist/types/editors/workflow-editor/ui/prop-layout.d.ts.map +1 -1
  77. package/dist/types/editors/workflow-editor/ui/prop-layout.test.d.ts +2 -0
  78. package/dist/types/editors/workflow-editor/ui/prop-layout.test.d.ts.map +1 -0
  79. package/dist/types/editors/workflow-editor/ui/trigger-text.d.ts.map +1 -1
  80. package/dist/types/editors/workflow-editor/ui/use-validity.d.ts.map +1 -1
  81. package/dist/types/editors/workflow-editor/ui/validation.d.ts +4 -1
  82. package/dist/types/editors/workflow-editor/ui/validation.d.ts.map +1 -1
  83. package/dist/types/editors/workflow-studio/components/RunsTable.d.ts +4 -1
  84. package/dist/types/editors/workflow-studio/components/RunsTable.d.ts.map +1 -1
  85. package/dist/types/editors/workflow-studio/components/Waitpoints.d.ts +9 -1
  86. package/dist/types/editors/workflow-studio/components/Waitpoints.d.ts.map +1 -1
  87. package/dist/types/editors/workflow-studio/components/WorkflowGraph.d.ts.map +1 -1
  88. package/dist/types/editors/workflow-studio/components/graph-layout.d.ts +1 -0
  89. package/dist/types/editors/workflow-studio/components/graph-layout.d.ts.map +1 -1
  90. package/dist/types/editors/workflow-studio/components/tips.d.ts.map +1 -1
  91. package/dist/types/pieces/ai/lib/actions/decide-on-documents.d.ts.map +1 -1
  92. package/dist/types/pieces/ai/lib/actions/extract.d.ts.map +1 -1
  93. package/dist/types/pieces/ai/lib/actions/propose-actions.d.ts.map +1 -1
  94. package/dist/types/pieces/ai/lib/actions/summarize.d.ts.map +1 -1
  95. package/dist/types/pieces/reactor/lib/actions/document-find.d.ts.map +1 -1
  96. package/dist/types/test/ui/flow-control.spec.d.ts +2 -0
  97. package/dist/types/test/ui/flow-control.spec.d.ts.map +1 -0
  98. package/package.json +9 -9
  99. package/dist/browser/BlockSelector-BKAJwJ4Y.js.map +0 -1
  100. package/dist/browser/editor--J61vLSC.js.map +0 -1
  101. package/dist/browser/editor-Dl6lzxkM.js.map +0 -1
  102. package/dist/browser/runtime-queries-D81Ghpok.js.map +0 -1
  103. package/dist/browser/trigger-text-BSVi5oGZ.js.map +0 -1
  104. package/dist/node/BlockSelector-DnTRF-C7.mjs.map +0 -1
  105. package/dist/node/editor-B4ZwM3pR.mjs.map +0 -1
  106. package/dist/node/editor-_4XHbqGl.mjs.map +0 -1
  107. package/dist/node/runtime-queries-VXJsWno5.mjs.map +0 -1
  108. package/dist/node/trigger-text-BBP7QVLj.mjs.map +0 -1
@@ -2,7 +2,7 @@ import { lazy } from "react";
2
2
  //#region editors/connection-editor/module.ts
3
3
  /** Document editor module for the "powerhouse/connection" document type */
4
4
  const ConnectionEditor = {
5
- Component: lazy(() => import("../../editor-CZLe6CAF.js")),
5
+ Component: lazy(() => import("../../editor-bHCkW_XB.js")),
6
6
  documentTypes: ["powerhouse/connection"],
7
7
  config: {
8
8
  id: "connection-editor",
@@ -1,2 +1,2 @@
1
- import { C as createRuntimeClient, D as isSyncingError, E as fetchRunsPage, S as RuntimeRequestError, T as fetchRuns, c as runQuery, l as runsOfPages, r as createRuntimeQueryClient, s as runPagesQuery, u as runsQuery, w as fetchRun } from "../../runtime-queries-D81Ghpok.js";
1
+ import { C as createRuntimeClient, D as isSyncingError, E as fetchRunsPage, S as RuntimeRequestError, T as fetchRuns, c as runQuery, l as runsOfPages, r as createRuntimeQueryClient, s as runPagesQuery, u as runsQuery, w as fetchRun } from "../../runtime-queries-C5bqAgQy.js";
2
2
  export { RuntimeRequestError, createRuntimeClient, createRuntimeQueryClient, fetchRun, fetchRuns, fetchRunsPage, isSyncingError, runPagesQuery, runQuery, runsOfPages, runsQuery };
@@ -2,7 +2,7 @@ import { lazy } from "react";
2
2
  //#region editors/workflow-editor/module.ts
3
3
  /** Document editor module for the "powerhouse/workflow" document type */
4
4
  const WorkflowEditor = {
5
- Component: lazy(() => import("../../editor-Dl6lzxkM.js")),
5
+ Component: lazy(() => import("../../editor-Yt-_V04R.js")),
6
6
  documentTypes: ["powerhouse/workflow"],
7
7
  config: {
8
8
  id: "workflow-editor",
@@ -2,7 +2,7 @@ import { lazy } from "react";
2
2
  //#region editors/workflow-studio/module.ts
3
3
  /** Document editor module for the "powerhouse/document-drive" document type */
4
4
  const WorkflowStudio = {
5
- Component: lazy(() => import("../../editor--J61vLSC.js")),
5
+ Component: lazy(() => import("../../editor-gCkAwv09.js")),
6
6
  documentTypes: ["powerhouse/document-drive"],
7
7
  config: {
8
8
  id: "workflow-studio",
@@ -1,7 +1,7 @@
1
1
  import { n as powerhouse_manifest_default, t as documentModels } from "./document-models-C2SAP1SX.js";
2
2
  import { h as REACTOR_CONNECTOR_ID } from "./module-DJz6oTX0.js";
3
3
  import { i as connectorIdForPiece, l as planFromAuth, o as isConfigValueMissing, s as packageFromConnectorId } from "./piece-auth-63iuNFTs.js";
4
- import { C as createRuntimeClient, P as REACTOR_PIECE, j as CORE_PIECE, n as catalogQuery, r as createRuntimeQueryClient, t as blockFormQuery, x as DEFAULT_RUNTIME_URL } from "./runtime-queries-D81Ghpok.js";
4
+ import { C as createRuntimeClient, L as REACTOR_PIECE, N as CORE_PIECE, n as catalogQuery, r as createRuntimeQueryClient, t as blockFormQuery, x as DEFAULT_RUNTIME_URL } from "./runtime-queries-C5bqAgQy.js";
5
5
  import { t as upgradeManifests } from "./upgrade-manifests-C2Qa6myy.js";
6
6
  import { ConnectionEditor } from "./editors/connection-editor/module.js";
7
7
  import { WorkflowEditor } from "./editors/workflow-editor/module.js";
@@ -85,6 +85,7 @@ const GRAPH_RULES = [
85
85
  "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.",
86
86
  "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.",
87
87
  `The built-in blocks (manual, schedule and webhook triggers, branch and assert) belong to the piece ${CORE_PIECE}.`,
88
+ "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.",
88
89
  "Steps whose piece needs a connection must set connectionId to a powerhouse/connection document id (see getConnections).",
89
90
  `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.`,
90
91
  "Runs execute the published snapshot, not the draft. PUBLISH_WORKFLOW only snapshots the draft, so publish again after every edit that should run.",
@@ -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 \"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,oBAAoB,yFAE1H;CACF;CACA,cACE,cACI,GAAG,YAAY,WAAW,qBAC1B,mBACN;AACF;;;ACTA,MAAMA,cAAY;CAChB,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CA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AS,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","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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AAE,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,6 +1,6 @@
1
1
  import { ambientRenownTokenProvider } from "@powerhousedao/reactor-browser/graphql-client";
2
2
  import { blockKey } from "@powerhousedao/pieces-framework/block-type";
3
- import { CORE_PIECE_NAME, checkTriggerStrategy } from "@powerhousedao/pieces-framework/workflow";
3
+ import { CALLABLE_FLOW_TRIGGER, CALL_FLOW_ACTION, CORE_PIECE_NAME, SUBFLOWS_PIECE, checkTriggerStrategy } from "@powerhousedao/pieces-framework/workflow";
4
4
  import { QueryClient, infiniteQueryOptions, queryOptions } from "@tanstack/react-query";
5
5
  //#region editors/workflow-editor/ui/forms.ts
6
6
  const POLL_INTERVAL_PROP = {
@@ -23,11 +23,23 @@ const MANUAL_TRIGGER = core("trigger", "manual");
23
23
  const SCHEDULE_TRIGGER = core("trigger", "schedule");
24
24
  const WEBHOOK_TRIGGER = core("trigger", "webhook");
25
25
  const BRANCH_BLOCK = core("action", "branch");
26
+ const ROUTER_BLOCK = core("action", "router");
27
+ const LOOP_BLOCK = core("action", "loop");
26
28
  const ASSERT_BLOCK = core("action", "assert");
27
29
  const DELAY_BLOCK = core("action", "delay");
28
30
  const APPROVAL_BLOCK = core("action", "approval");
29
31
  const STOP_BLOCK = core("action", "stop");
30
32
  const WAIT_FOR_WEBHOOK_BLOCK = core("action", "waitForWebhook");
33
+ const SUBFLOWS_VERSION = "0.7.0";
34
+ const subflows = (kind, name) => ({
35
+ pieceName: SUBFLOWS_PIECE,
36
+ pieceVersion: SUBFLOWS_VERSION,
37
+ kind,
38
+ name
39
+ });
40
+ const CALLABLE_FLOW_TRIGGER$1 = subflows("trigger", CALLABLE_FLOW_TRIGGER);
41
+ const CALL_FLOW_BLOCK = subflows("action", CALL_FLOW_ACTION);
42
+ const RETURN_RESPONSE_BLOCK = subflows("action", "returnResponse");
31
43
  function sameBlock(a, b) {
32
44
  return Boolean(a && b && blockKey(a) === blockKey(b));
33
45
  }
@@ -112,6 +124,16 @@ const TRIGGER_PRESETS = [
112
124
  responseMode: "async"
113
125
  }
114
126
  },
127
+ {
128
+ label: "Callable workflow",
129
+ block: CALLABLE_FLOW_TRIGGER$1,
130
+ group: "core",
131
+ description: "Fires when another workflow in this drive calls it.",
132
+ defaultConfig: {
133
+ mode: "simple",
134
+ exampleData: { sampleData: {} }
135
+ }
136
+ },
115
137
  {
116
138
  label: "Document event",
117
139
  block: reactor("trigger", "document-event"),
@@ -142,6 +164,20 @@ const STEP_PRESETS = [
142
164
  description: "Routes true/false on a condition.",
143
165
  defaultConfig: {}
144
166
  },
167
+ {
168
+ label: "Router",
169
+ block: ROUTER_BLOCK,
170
+ group: "core",
171
+ description: "Takes the first of several branches whose condition holds.",
172
+ defaultConfig: { branches: [{ operator: "TEXT_EXACTLY_MATCHES" }] }
173
+ },
174
+ {
175
+ label: "Loop on items",
176
+ block: LOOP_BLOCK,
177
+ group: "core",
178
+ description: "Runs the steps inside it once for each item of a list.",
179
+ defaultConfig: { items: "" }
180
+ },
145
181
  {
146
182
  label: "Assert",
147
183
  block: ASSERT_BLOCK,
@@ -192,6 +228,26 @@ const STEP_PRESETS = [
192
228
  description: "Ends the run successfully, optionally answering the caller.",
193
229
  defaultConfig: { responseType: "json" }
194
230
  },
231
+ {
232
+ label: "Call workflow",
233
+ block: CALL_FLOW_BLOCK,
234
+ group: "core",
235
+ description: "Runs a callable workflow in this drive, optionally waiting for its response.",
236
+ defaultConfig: {
237
+ mode: "simple",
238
+ waitForResponse: false
239
+ }
240
+ },
241
+ {
242
+ label: "Return response",
243
+ block: RETURN_RESPONSE_BLOCK,
244
+ group: "core",
245
+ description: "Answers the workflow that called this one.",
246
+ defaultConfig: {
247
+ mode: "simple",
248
+ response: { response: {} }
249
+ }
250
+ },
195
251
  {
196
252
  label: "Create document",
197
253
  block: reactor("action", "document-create"),
@@ -521,10 +577,19 @@ const WAITPOINT_FIELDS = `id runId workflowId stepId stepKey stepPath pieceName
521
577
  approval { title body approveLabel rejectLabel reasonRequiredOn approvers }`;
522
578
  const RUN_ROW_FIELDS = `id workflowId workflowName workflowVersion triggerKind
523
579
  triggerPayload status error errorName startedAt endedAt rerunOf warningNotes`;
524
- const STEP_ROW_FIELDS = "stepId stepKey pieceName blockName status port error errorName startedAt endedAt";
580
+ const STEP_ROW_FIELDS = "stepId stepKey path pieceName blockName status port error errorName startedAt endedAt";
581
+ function withIterations(run) {
582
+ const iterations = run.steps.filter((step) => step.path);
583
+ if (iterations.length === 0) return run;
584
+ return {
585
+ ...run,
586
+ steps: run.steps.filter((step) => !step.path),
587
+ iterations
588
+ };
589
+ }
525
590
  const RUN_FIELDS = `${RUN_ROW_FIELDS} steps { ${STEP_ROW_FIELDS} input output }`;
526
591
  const RUN_LIST_FIELDS = `${RUN_ROW_FIELDS} steps { ${STEP_ROW_FIELDS} }`;
527
- const RUN_DETAIL_FIELDS = `${RUN_FIELDS} waitpoints { ${WAITPOINT_FIELDS} }`;
592
+ const RUN_DETAIL_FIELDS = `${RUN_FIELDS} iterationsTotal waitpoints { ${WAITPOINT_FIELDS} }`;
528
593
  function scopeVariables(scope, limit) {
529
594
  return {
530
595
  workflowId: scope.workflowId ?? null,
@@ -536,11 +601,11 @@ function scopeVariables(scope, limit) {
536
601
  async function fetchRuns(t, scope = {}) {
537
602
  return (await t.gql(`query Runs($workflowId: String, $driveId: String, $limit: Int, $excludeTriggerKinds: [String!]) {
538
603
  workflowRuntime { runs(workflowId: $workflowId, driveId: $driveId, limit: $limit, excludeTriggerKinds: $excludeTriggerKinds) { ${RUN_FIELDS} } }
539
- }`, scopeVariables(scope, 30))).workflowRuntime.runs;
604
+ }`, scopeVariables(scope, 30))).workflowRuntime.runs.map(withIterations);
540
605
  }
541
606
  async function fetchRunsPage(t, scope = {}, cursor = null) {
542
607
  const { limit, ...rest } = scopeVariables(scope, 30);
543
- return (await t.gql(`query RunsPage($workflowId: String, $driveId: String, $excludeTriggerKinds: [String!], $paging: WorkflowRunsPagingInput) {
608
+ const page = (await t.gql(`query RunsPage($workflowId: String, $driveId: String, $excludeTriggerKinds: [String!], $paging: WorkflowRunsPagingInput) {
544
609
  workflowRuntime {
545
610
  runsPage(workflowId: $workflowId, driveId: $driveId, excludeTriggerKinds: $excludeTriggerKinds, paging: $paging) {
546
611
  items { ${RUN_LIST_FIELDS} } hasNextPage cursor
@@ -553,9 +618,14 @@ async function fetchRunsPage(t, scope = {}, cursor = null) {
553
618
  cursor
554
619
  }
555
620
  })).workflowRuntime.runsPage;
621
+ return {
622
+ ...page,
623
+ items: page.items.map(withIterations)
624
+ };
556
625
  }
557
626
  async function fetchRun(t, runId) {
558
- return (await t.gql(`query Run($id: String!) { workflowRuntime { run(id: $id) { ${RUN_DETAIL_FIELDS} } } }`, { id: runId })).workflowRuntime.run;
627
+ const run = (await t.gql(`query Run($id: String!) { workflowRuntime { run(id: $id) { ${RUN_DETAIL_FIELDS} } } }`, { id: runId })).workflowRuntime.run;
628
+ return run ? withIterations(run) : null;
559
629
  }
560
630
  async function fetchWaitingRuns(t, scope = {}) {
561
631
  return (await t.gql(`query WaitingRuns($driveId: String, $workflowId: String, $first: Int) {
@@ -568,7 +638,7 @@ async function fetchWaitingRuns(t, scope = {}) {
568
638
  driveId: scope.driveId ?? null,
569
639
  workflowId: scope.workflowId ?? null,
570
640
  first: scope.first ?? null
571
- })).workflowRuntime.waitingRuns;
641
+ })).workflowRuntime.waitingRuns.map(withIterations);
572
642
  }
573
643
  async function resolveWaitpoint(t, waitpointId, approved, reason) {
574
644
  return (await t.gql(`mutation ResolveWaitpoint($waitpointId: String!, $approved: Boolean!, $reason: String) {
@@ -601,16 +671,17 @@ async function cancelRun(t, runId) {
601
671
  workflowRuntime { cancelRun(runId: $runId) { runId status error } }
602
672
  }`, { runId })).workflowRuntime.cancelRun;
603
673
  }
604
- async function loadBlockOptions(t, block, propName, input, connectionId, searchValue, reactorConnectionId) {
605
- return (await t.gql(`query Options($block: BlockInput!, $propName: String!, $input: Unknown, $connectionId: String, $searchValue: String, $reactorConnectionId: String) {
606
- workflowRuntime { blockOptions(block: $block, propName: $propName, input: $input, connectionId: $connectionId, searchValue: $searchValue, reactorConnectionId: $reactorConnectionId) }
674
+ async function loadBlockOptions(t, block, propName, input, connectionId, searchValue, reactorConnectionId, workflowId) {
675
+ return (await t.gql(`query Options($block: BlockInput!, $propName: String!, $input: Unknown, $connectionId: String, $searchValue: String, $reactorConnectionId: String, $workflowId: String) {
676
+ workflowRuntime { blockOptions(block: $block, propName: $propName, input: $input, connectionId: $connectionId, searchValue: $searchValue, reactorConnectionId: $reactorConnectionId, workflowId: $workflowId) }
607
677
  }`, {
608
678
  block: blockInput(block),
609
679
  propName,
610
680
  input,
611
681
  connectionId: connectionId ?? null,
612
682
  searchValue: searchValue ?? null,
613
- reactorConnectionId: reactorConnectionId ?? null
683
+ reactorConnectionId: reactorConnectionId ?? null,
684
+ workflowId: workflowId ?? null
614
685
  })).workflowRuntime.blockOptions;
615
686
  }
616
687
  const operations = {
@@ -898,6 +969,6 @@ const secretStatQuery = (client, ref) => queryOptions({
898
969
  staleTime: 0
899
970
  });
900
971
  //#endregion
901
- export { BRANCH_BLOCK as A, WEBHOOK_TRIGGER as B, createRuntimeClient as C, isSyncingError as D, fetchRunsPage as E, SCHEDULE_TRIGGER as F, stepFields as G, pinBlock as H, STEP_PRESETS as I, triggerBlock as K, STOP_BLOCK as L, DELAY_BLOCK as M, MANUAL_TRIGGER as N, APPROVAL_BLOCK as O, REACTOR_PIECE as P, TRIGGER_PRESETS as R, RuntimeRequestError as S, fetchRuns as T, sameBlock as U, isCoreBlock as V, stepBlock as W, 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, CORE_PIECE as j, ASSERT_BLOCK as k, runsOfPages as l, RESOLVER_STALE_MS as m, catalogQuery as n, pieceTriggersQuery as o, waitingRunsQuery as p, triggerFields 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, WAIT_FOR_WEBHOOK_BLOCK as z };
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 };
902
973
 
903
- //# sourceMappingURL=runtime-queries-D81Ghpok.js.map
974
+ //# sourceMappingURL=runtime-queries-C5bqAgQy.js.map