@skaile/workspaces 2.5.0 → 2.7.0

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 (123) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +26 -11
  3. package/dist/{asset-feeds-4AWAT5PW.js → asset-feeds-23CP6YUY.js} +4 -4
  4. package/dist/{asset-feeds-4AWAT5PW.js.map → asset-feeds-23CP6YUY.js.map} +1 -1
  5. package/dist/asset-manager/index.js +1 -1
  6. package/dist/{chunk-WSARNOPP.js → chunk-6AYGXPPF.js} +2 -2
  7. package/dist/{chunk-WSARNOPP.js.map → chunk-6AYGXPPF.js.map} +1 -1
  8. package/dist/{chunk-ENBTXMPL.js → chunk-AZ44F3AT.js} +6 -6
  9. package/dist/{chunk-ENBTXMPL.js.map → chunk-AZ44F3AT.js.map} +1 -1
  10. package/dist/{chunk-4O2RAXKJ.js → chunk-E4AVJMOJ.js} +316 -6
  11. package/dist/chunk-E4AVJMOJ.js.map +1 -0
  12. package/dist/{chunk-JAFEMG7W.js → chunk-FW2C6JJP.js} +3 -3
  13. package/dist/{chunk-JAFEMG7W.js.map → chunk-FW2C6JJP.js.map} +1 -1
  14. package/dist/{chunk-EEHOMCRU.js → chunk-HVQWLYZB.js} +129 -11
  15. package/dist/chunk-HVQWLYZB.js.map +1 -0
  16. package/dist/{chunk-V4ZLZJFN.js → chunk-IWUIXNMF.js} +6 -3
  17. package/dist/chunk-IWUIXNMF.js.map +1 -0
  18. package/dist/{chunk-IHX2SN35.js → chunk-JIA2S3T2.js} +6 -6
  19. package/dist/{chunk-IHX2SN35.js.map → chunk-JIA2S3T2.js.map} +1 -1
  20. package/dist/{chunk-RK3HU3H3.js → chunk-KSHCQ777.js} +8 -6
  21. package/dist/chunk-KSHCQ777.js.map +1 -0
  22. package/dist/{chunk-YWPEDILM.js → chunk-OAUKA7VT.js} +8 -8
  23. package/dist/{chunk-YWPEDILM.js.map → chunk-OAUKA7VT.js.map} +1 -1
  24. package/dist/{chunk-MADO7PH5.js → chunk-ONUDDQGS.js} +2 -2
  25. package/dist/{chunk-MADO7PH5.js.map → chunk-ONUDDQGS.js.map} +1 -1
  26. package/dist/{chunk-EUWN4EK4.js → chunk-P3DUVOAW.js} +6 -6
  27. package/dist/{chunk-EUWN4EK4.js.map → chunk-P3DUVOAW.js.map} +1 -1
  28. package/dist/{chunk-FKBQRV4J.js → chunk-SCR3WGW7.js} +3 -3
  29. package/dist/{chunk-FKBQRV4J.js.map → chunk-SCR3WGW7.js.map} +1 -1
  30. package/dist/{chunk-4QROZZ5Z.js → chunk-TUYN2HDT.js} +7 -4
  31. package/dist/chunk-TUYN2HDT.js.map +1 -0
  32. package/dist/{chunk-OEGHKO5N.js → chunk-XJ74XFIZ.js} +20 -9
  33. package/dist/chunk-XJ74XFIZ.js.map +1 -0
  34. package/dist/{chunk-PJ6INYDD.js → chunk-XTFZOYNY.js} +3 -3
  35. package/dist/{chunk-PJ6INYDD.js.map → chunk-XTFZOYNY.js.map} +1 -1
  36. package/dist/{chunk-UZYTSIX6.js → chunk-ZJ7MRR2R.js} +4 -4
  37. package/dist/{chunk-UZYTSIX6.js.map → chunk-ZJ7MRR2R.js.map} +1 -1
  38. package/dist/{chunk-AKVAZ5CB.js → chunk-ZJOEU5GP.js} +2 -2
  39. package/dist/{chunk-AKVAZ5CB.js.map → chunk-ZJOEU5GP.js.map} +1 -1
  40. package/dist/cli/index.js +31 -31
  41. package/dist/connectors/index.js +5 -5
  42. package/dist/{ensure-sources-QF72HVUM.js → ensure-sources-N7B7657V.js} +4 -4
  43. package/dist/{ensure-sources-QF72HVUM.js.map → ensure-sources-N7B7657V.js.map} +1 -1
  44. package/dist/factory-assets/connectors/box.js +5 -5
  45. package/dist/factory-assets/connectors/deploy.js +5 -5
  46. package/dist/factory-assets/connectors/devserver.js +5 -5
  47. package/dist/factory-assets/connectors/flow/CONNECTOR.md +36 -8
  48. package/dist/factory-assets/connectors/flow/adapter.d.ts +4 -1
  49. package/dist/factory-assets/connectors/flow/adapter.d.ts.map +1 -1
  50. package/dist/factory-assets/connectors/flow/adapter.js +5 -5
  51. package/dist/factory-assets/connectors/flow/contract/expression.d.ts +3 -0
  52. package/dist/factory-assets/connectors/flow/contract/expression.d.ts.map +1 -1
  53. package/dist/factory-assets/connectors/flow/contract/flow.v2.schema.json +5 -1
  54. package/dist/factory-assets/connectors/flow/contract/hash.d.ts.map +1 -1
  55. package/dist/factory-assets/connectors/flow/contract/index.d.ts +1 -1
  56. package/dist/factory-assets/connectors/flow/contract/index.d.ts.map +1 -1
  57. package/dist/factory-assets/connectors/flow/contract/schema.d.ts +21 -2
  58. package/dist/factory-assets/connectors/flow/contract/schema.d.ts.map +1 -1
  59. package/dist/factory-assets/connectors/flow/contract.js +2 -2
  60. package/dist/factory-assets/connectors/flow/engine/engine.d.ts +30 -0
  61. package/dist/factory-assets/connectors/flow/engine/engine.d.ts.map +1 -1
  62. package/dist/factory-assets/connectors/flow/engine/node-shape.d.ts +6 -0
  63. package/dist/factory-assets/connectors/flow/engine/node-shape.d.ts.map +1 -1
  64. package/dist/factory-assets/connectors/flow/engine/router-settlement.d.ts +48 -0
  65. package/dist/factory-assets/connectors/flow/engine/router-settlement.d.ts.map +1 -0
  66. package/dist/factory-assets/connectors/flow/engine/types.d.ts +13 -24
  67. package/dist/factory-assets/connectors/flow/engine/types.d.ts.map +1 -1
  68. package/dist/factory-assets/connectors/flow/engine.js +3 -3
  69. package/dist/factory-assets/connectors/flow/prompt-fragments.js +2 -2
  70. package/dist/factory-assets/connectors/flow/run-flow.js +6 -6
  71. package/dist/factory-assets/connectors/flow.js +5 -5
  72. package/dist/factory-assets/connectors/git.js +5 -5
  73. package/dist/factory-assets/connectors/gmail.js +5 -5
  74. package/dist/factory-assets/connectors/googledrive.js +5 -5
  75. package/dist/factory-assets/connectors/local.js +5 -5
  76. package/dist/factory-assets/connectors/mattermost.js +5 -5
  77. package/dist/factory-assets/connectors/memory.js +5 -5
  78. package/dist/factory-assets/connectors/minio.js +5 -5
  79. package/dist/factory-assets/connectors/postgres.js +5 -5
  80. package/dist/factory-assets/connectors/s3.js +5 -5
  81. package/dist/factory-assets/connectors/sharepoint.js +5 -5
  82. package/dist/factory-assets/connectors/sqlite.js +5 -5
  83. package/dist/factory-assets/connectors/static-server.js +5 -5
  84. package/dist/factory-assets/connectors/tunnel.js +5 -5
  85. package/dist/factory-assets/connectors/webdav.js +5 -5
  86. package/dist/factory-assets/connectors/xstate-store.js +5 -5
  87. package/dist/factory-assets/connectors/xstate.js +5 -5
  88. package/dist/{flows-YIW4HL3L.js → flows-K7B253U6.js} +3 -3
  89. package/dist/{flows-YIW4HL3L.js.map → flows-K7B253U6.js.map} +1 -1
  90. package/dist/{helpers-LURCZHA4.js → helpers-PXEHIKF7.js} +4 -4
  91. package/dist/{helpers-LURCZHA4.js.map → helpers-PXEHIKF7.js.map} +1 -1
  92. package/dist/{library-publish-2GMJM3NZ.js → library-publish-3Z33J2ZY.js} +9 -9
  93. package/dist/{library-publish-2GMJM3NZ.js.map → library-publish-3Z33J2ZY.js.map} +1 -1
  94. package/dist/{open-library-POFOXZWH.js → open-library-Y5SKFAMK.js} +8 -8
  95. package/dist/{open-library-POFOXZWH.js.map → open-library-Y5SKFAMK.js.map} +1 -1
  96. package/dist/{project-GVOPZEJZ.js → project-DQRC6J6M.js} +5 -5
  97. package/dist/{project-GVOPZEJZ.js.map → project-DQRC6J6M.js.map} +1 -1
  98. package/dist/runner/index.js +9 -9
  99. package/dist/sdk/asset-manager.js +1 -1
  100. package/dist/sdk/flow.js +3 -3
  101. package/dist/sdk/index.js +9 -9
  102. package/dist/sdk/runner.js +9 -9
  103. package/dist/sdk/store.js +1 -1
  104. package/dist/{source-FB3T4IHP.js → source-XBJ5KTAV.js} +9 -9
  105. package/dist/{source-FB3T4IHP.js.map → source-XBJ5KTAV.js.map} +1 -1
  106. package/dist/{source-manifest-publish-XTRDVPSC.js → source-manifest-publish-Q7TXBMCW.js} +10 -10
  107. package/dist/{source-manifest-publish-XTRDVPSC.js.map → source-manifest-publish-Q7TXBMCW.js.map} +1 -1
  108. package/dist/store/index.js +1 -1
  109. package/dist/store/src/store.d.ts +3 -2
  110. package/dist/store/src/store.d.ts.map +1 -1
  111. package/dist/tui/index.js +9 -9
  112. package/dist/types/src/events.d.ts +5 -1
  113. package/dist/types/src/events.d.ts.map +1 -1
  114. package/dist/workspace-plugin/adapters/mcp.js +1 -1
  115. package/dist/workspace-plugin/adapters/omp.js +3 -3
  116. package/dist/workspace-plugin/index.js +1 -1
  117. package/package.json +1 -1
  118. package/dist/chunk-4O2RAXKJ.js.map +0 -1
  119. package/dist/chunk-4QROZZ5Z.js.map +0 -1
  120. package/dist/chunk-EEHOMCRU.js.map +0 -1
  121. package/dist/chunk-OEGHKO5N.js.map +0 -1
  122. package/dist/chunk-RK3HU3H3.js.map +0 -1
  123. package/dist/chunk-V4ZLZJFN.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../factory-assets/connectors/flow/engine/bindings.ts","../factory-assets/connectors/flow/engine/router-settlement.ts","../factory-assets/connectors/flow/engine/engine.ts","../factory-assets/connectors/flow/engine/output-schema.ts","../factory-assets/connectors/flow/engine/flow-manifest.ts","../factory-assets/connectors/flow/engine/flow-kind-provider.ts","../factory-assets/connectors/flow/engine/loader.ts"],"names":["path","z","parseYaml"],"mappings":";;;;;;;;;;AAWO,SAAS,0BAAA,CACd,MACA,SAAA,EACuB;AACvB,EAAA,MAAM,QAAwC,EAAC;AAC/C,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAK,KAAA,EAAO;AAC7B,IAAA,MAAM,QAAA,GAAW,SAAA,CAAU,GAAA,CAAI,IAAA,CAAK,EAAE,CAAA;AACtC,IAAA,MAAM,MAAA,GACJ,QAAA,EAAU,MAAA,KAAW,UAAA,IAAc,QAAA,CAAS,MAAA,EAAQ,MAAA,GAChD,EAAE,MAAA,EAAQ,QAAA,CAAS,MAAA,CAAO,MAAA,EAA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AAA,EACF;AACA,EAAA,OAAO,CAAC,GAAG,IAAA,CAAK,MAAA,EAAQ,CAAA;AAC1B","file":"chunk-E4AVJMOJ.js","sourcesContent":["import {\n resolveFlowBindings,\n stableFlowJson,\n type BindingOrigin,\n type FlowExpressionContext,\n type ResolvedNodeBindings,\n} from \"../contract/expression.js\";\nimport { isAgentNode, nodeBindings } from \"./node-shape.js\";\nimport type { FlowDefinition, FlowNode, NodeExecutionSnapshot } from \"./types.js\";\n\n/** Build the bounded expression context from immutable definition and snapshot state. */\nexport function buildFlowExpressionContext(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): FlowExpressionContext {\n const nodes: FlowExpressionContext[\"nodes\"] = {};\n for (const node of flow.nodes) {\n const snapshot = snapshots.get(node.id);\n const output =\n snapshot?.status === \"complete\" && snapshot.output?.fields\n ? { fields: snapshot.output.fields }\n : undefined;\n nodes[node.id] = { status: snapshot?.status ?? \"not_started\", output };\n }\n return {\n flow: { input: flow.defaults?.run_input ?? {} },\n defaults: flow.defaults,\n nodes,\n };\n}\n\n/** Resolve one node's named inputs and derive their runtime/agent origins. */\nexport function resolveNodeBindings(\n flow: FlowDefinition,\n node: FlowNode,\n snapshots: Map<string, NodeExecutionSnapshot>,\n flowInputOrigins: Record<string, BindingOrigin[]> = {},\n): ResolvedNodeBindings {\n const origins = Object.fromEntries(\n flow.nodes.map((producer) => [producer.id, isAgentNode(producer) ? \"agent\" : \"runtime\"]),\n ) as Record<string, \"agent\" | \"runtime\">;\n return resolveFlowBindings(\n nodeBindings(node),\n buildFlowExpressionContext(flow, snapshots),\n origins,\n flowInputOrigins,\n );\n}\n\n/** Interpolate named, already-resolved binding values into an agent instruction. */\nexport function interpolateNodeInstruction(\n instruction: string,\n values: Record<string, unknown>,\n): string {\n return instruction.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_-]*)\\}/g, (_placeholder, name: string) => {\n if (!Object.hasOwn(values, name)) {\n throw new Error(`Node instruction binding ${name} is missing`);\n }\n const value = values[name];\n return typeof value === \"string\" ? value : stableFlowJson(value);\n });\n}\n","import type { NodeOutput } from \"@skaile/workspaces/types\";\nimport { evaluateFlowExpression, FlowExpressionError } from \"../contract/expression.js\";\nimport { buildFlowExpressionContext } from \"./bindings.js\";\nimport { isRouterNode } from \"./node-shape.js\";\nimport type { FlowDefinition, FlowNode, NodeExecutionSnapshot } from \"./types.js\";\n\nconst ROUTER_SELECTION_MARKER = \"\\n\\n[skaile:flow-router-selection:\";\n\n/** One deterministic router choice being settled in the current atomic batch. */\nexport interface RouterSettlement {\n routerNodeId: string;\n selectedTarget: string | null;\n}\n\n/** Internal result of evaluating one already-admitted router. */\nexport type RouterSelection =\n | { selectedTarget: string | null }\n | { unresolved: \"not-ready\" | \"no-match\" };\n\nfunction pendingProducerOutput(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n missingPath: string | undefined,\n): boolean {\n if (!missingPath) return false;\n const segments = missingPath.split(\".\");\n if (\n segments.length < 5 ||\n segments[0] !== \"nodes\" ||\n segments[2] !== \"output\" ||\n segments[3] !== \"fields\"\n ) {\n return false;\n }\n const producer = flow.nodes.find(({ id }) => id === segments[1]);\n if (!producer?.contract?.output?.fields) return false;\n return snapshots.get(producer.id)?.status !== \"complete\";\n}\n\n/** Evaluate ordered routes for a router whose availability was already established. */\nexport function evaluateRouterSelection(\n flow: FlowDefinition,\n router: FlowNode,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): RouterSelection {\n if (!isRouterNode(router)) return { unresolved: \"no-match\" };\n const context = buildFlowExpressionContext(flow, snapshots);\n for (const route of router.run.routes) {\n try {\n if (evaluateFlowExpression(route.when, context)) {\n return { selectedTarget: route.target };\n }\n } catch (error) {\n if (\n error instanceof FlowExpressionError &&\n pendingProducerOutput(flow, snapshots, error.missingPath)\n ) {\n return { unresolved: \"not-ready\" };\n }\n throw error;\n }\n }\n return { unresolved: \"no-match\" };\n}\n\n/** Encode a router choice in the existing durable node-output envelope. */\nexport function routerSelectionOutput(selectedTarget: string | null): NodeOutput {\n const summary =\n selectedTarget === null\n ? \"Router completed without selecting a target.\"\n : `Router selected ${selectedTarget}.`;\n return {\n summary: `${summary}${ROUTER_SELECTION_MARKER}${JSON.stringify(selectedTarget)}]`,\n artifacts: [],\n };\n}\n\nfunction routeTargets(router: FlowNode): string[] {\n if (!isRouterNode(router)) return [];\n return [...new Set(router.run.routes.flatMap(({ target }) => (target === null ? [] : [target])))];\n}\n\ninterface RouterOwnershipIndex {\n routers: FlowNode[];\n outgoing: Map<string, string[]>;\n}\n\n/** Index router-to-router ownership through route targets and hard-flow descendants. */\nfunction routerOwnershipIndex(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): RouterOwnershipIndex {\n const routers = flow.nodes.filter(\n (node) =>\n isRouterNode(node) &&\n ![\"complete\", \"failed\", \"skipped\"].includes(snapshots.get(node.id)?.status ?? \"not_started\"),\n );\n const routerIds = new Set(routers.map(({ id }) => id));\n const hardOutgoing = new Map<string, string[]>();\n for (const edge of flow.edges) {\n if (edge.type !== \"flow\") continue;\n const targets = hardOutgoing.get(edge.source) ?? [];\n targets.push(edge.target);\n hardOutgoing.set(edge.source, targets);\n }\n\n const outgoing = new Map<string, string[]>();\n for (const router of routers) {\n const owned = new Set<string>();\n const visited = new Set<string>();\n const queue = routeTargets(router);\n for (let index = 0; index < queue.length; index++) {\n const nodeId = queue[index];\n if (visited.has(nodeId)) continue;\n visited.add(nodeId);\n if (routerIds.has(nodeId)) owned.add(nodeId);\n queue.push(...(hardOutgoing.get(nodeId) ?? []));\n }\n outgoing.set(router.id, [...owned]);\n }\n return { routers, outgoing };\n}\n\n/**\n * Return every member of each source router-ownership SCC.\n *\n * Route ownership is deliberately not a dependency arc and may cycle even though hard flow is\n * acyclic. Source SCC members are ungated so normal hard-edge/precondition admission and ordered\n * decidability select the settlement frontier. Ordinary parent components remain ahead of nested\n * children, while self-targeting and mutually targeting routers cannot deadlock admission. The\n * graph is preindexed and both SCC passes are iterative.\n */\nfunction routerOwnershipSourceComponents(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): string[][] {\n const { routers, outgoing } = routerOwnershipIndex(flow, snapshots);\n const reverse = new Map<string, string[]>();\n for (const router of routers) reverse.set(router.id, []);\n for (const [source, targets] of outgoing) {\n for (const target of targets) reverse.get(target)?.push(source);\n }\n\n const visited = new Set<string>();\n const finished: string[] = [];\n for (const router of routers) {\n if (visited.has(router.id)) continue;\n const stack: Array<{ nodeId: string; exiting: boolean }> = [\n { nodeId: router.id, exiting: false },\n ];\n while (stack.length > 0) {\n const frame = stack.pop();\n if (!frame) break;\n if (frame.exiting) {\n finished.push(frame.nodeId);\n continue;\n }\n if (visited.has(frame.nodeId)) continue;\n visited.add(frame.nodeId);\n stack.push({ nodeId: frame.nodeId, exiting: true });\n const targets = outgoing.get(frame.nodeId) ?? [];\n for (let index = targets.length - 1; index >= 0; index--) {\n if (!visited.has(targets[index])) {\n stack.push({ nodeId: targets[index], exiting: false });\n }\n }\n }\n }\n\n const componentByRouter = new Map<string, number>();\n const components: string[][] = [];\n for (let index = finished.length - 1; index >= 0; index--) {\n const start = finished[index];\n if (componentByRouter.has(start)) continue;\n const componentId = components.length;\n const component: string[] = [];\n const stack = [start];\n componentByRouter.set(start, componentId);\n while (stack.length > 0) {\n const nodeId = stack.pop();\n if (!nodeId) break;\n component.push(nodeId);\n for (const source of reverse.get(nodeId) ?? []) {\n if (componentByRouter.has(source)) continue;\n componentByRouter.set(source, componentId);\n stack.push(source);\n }\n }\n components.push(component);\n }\n\n const incomingComponents = new Set<number>();\n for (const [source, targets] of outgoing) {\n const sourceComponent = componentByRouter.get(source);\n for (const target of targets) {\n const targetComponent = componentByRouter.get(target);\n if (\n sourceComponent !== undefined &&\n targetComponent !== undefined &&\n sourceComponent !== targetComponent\n ) {\n incomingComponents.add(targetComponent);\n }\n }\n }\n\n const definitionOrder = new Map(flow.nodes.map((node, index) => [node.id, index]));\n const sourceComponents = components.filter(\n (_, componentId) => !incomingComponents.has(componentId),\n );\n for (const component of sourceComponents) {\n component.sort(\n (left, right) =>\n (definitionOrder.get(left) ?? Number.MAX_SAFE_INTEGER) -\n (definitionOrder.get(right) ?? Number.MAX_SAFE_INTEGER),\n );\n }\n return sourceComponents.sort(\n (left, right) =>\n (definitionOrder.get(left[0]) ?? Number.MAX_SAFE_INTEGER) -\n (definitionOrder.get(right[0]) ?? Number.MAX_SAFE_INTEGER),\n );\n}\n\n/** Decode and validate a completed router's engine-owned selection summary. */\nexport function persistedRouterSelection(\n router: FlowNode,\n snapshot: NodeExecutionSnapshot | undefined,\n): { selectedTarget: string | null } | undefined {\n if (!isRouterNode(router) || snapshot?.status !== \"complete\") return undefined;\n const summary = snapshot.output?.summary;\n const markerIndex = summary?.lastIndexOf(ROUTER_SELECTION_MARKER) ?? -1;\n if (!summary || markerIndex < 0 || !summary.endsWith(\"]\")) return undefined;\n let selectedTarget: unknown;\n try {\n selectedTarget = JSON.parse(summary.slice(markerIndex + ROUTER_SELECTION_MARKER.length, -1));\n } catch {\n return undefined;\n }\n if (\n selectedTarget !== null &&\n (typeof selectedTarget !== \"string\" || !routeTargets(router).includes(selectedTarget))\n ) {\n return undefined;\n }\n if (selectedTarget === null && !router.run.routes.some(({ target }) => target === null)) {\n return undefined;\n }\n return summary === routerSelectionOutput(selectedTarget).summary ? { selectedTarget } : undefined;\n}\n\nfunction edgeKey(source: string, target: string): string {\n return `${source}\\u0000${target}`;\n}\n\n/**\n * Plan exclusive branch skips for all known router choices as one coordinated settlement.\n *\n * Only hard `flow` edges participate. The graph is indexed once, then each distinct losing\n * target performs a linear adjacency walk; optional and parallel edges can neither spread nor\n * preserve exclusivity. A selected route, a still-live unsettled router, shared convergence, or\n * an incoming hard predecessor outside the losing region protects that node and its descendants.\n */\nexport function planRouterSkips(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n settlements: readonly RouterSettlement[],\n): string[] {\n const routers = flow.nodes.filter(isRouterNode);\n const currentSelections = new Map(\n settlements.map(({ routerNodeId, selectedTarget }) => [routerNodeId, selectedTarget]),\n );\n const knownSelections = new Map<string, string | null>();\n for (const router of routers) {\n if (currentSelections.has(router.id)) {\n knownSelections.set(router.id, currentSelections.get(router.id) ?? null);\n continue;\n }\n const persisted = persistedRouterSelection(router, snapshots.get(router.id));\n if (persisted) knownSelections.set(router.id, persisted.selectedTarget);\n }\n\n const outgoing = new Map<string, string[]>();\n const incoming = new Map<string, string[]>();\n for (const edge of flow.edges) {\n if (edge.type !== \"flow\") continue;\n const targets = outgoing.get(edge.source) ?? [];\n targets.push(edge.target);\n outgoing.set(edge.source, targets);\n const sources = incoming.get(edge.target) ?? [];\n sources.push(edge.source);\n incoming.set(edge.target, sources);\n }\n\n const losingRoots = new Set<string>();\n const selectedRoots = new Set<string>();\n const losingRouteEdges = new Set<string>();\n for (const router of routers) {\n if (!knownSelections.has(router.id)) continue;\n const selectedTarget = knownSelections.get(router.id) ?? null;\n if (selectedTarget !== null) selectedRoots.add(selectedTarget);\n for (const target of routeTargets(router)) {\n if (target === selectedTarget) continue;\n losingRoots.add(target);\n losingRouteEdges.add(edgeKey(router.id, target));\n }\n }\n\n const candidateOrigins = new Map<string, Set<string>>();\n for (const root of losingRoots) {\n const visited = new Set<string>();\n const queue = [root];\n for (let index = 0; index < queue.length; index++) {\n const nodeId = queue[index];\n if (visited.has(nodeId)) continue;\n visited.add(nodeId);\n const origins = candidateOrigins.get(nodeId) ?? new Set<string>();\n origins.add(root);\n candidateOrigins.set(nodeId, origins);\n for (const target of outgoing.get(nodeId) ?? []) queue.push(target);\n }\n }\n const candidates = new Set(candidateOrigins.keys());\n\n const protectionQueue = [...selectedRoots];\n for (const [nodeId, origins] of candidateOrigins) {\n if (origins.size >= 2) protectionQueue.push(nodeId);\n for (const source of incoming.get(nodeId) ?? []) {\n if (candidates.has(source)) continue;\n if (losingRouteEdges.has(edgeKey(source, nodeId))) continue;\n if ([\"failed\", \"skipped\"].includes(snapshots.get(source)?.status ?? \"not_started\")) continue;\n protectionQueue.push(nodeId);\n break;\n }\n }\n\n const unknownSelections = new Map<string, string[]>();\n for (const router of routers) {\n if (knownSelections.has(router.id)) continue;\n const status = snapshots.get(router.id)?.status ?? \"not_started\";\n if (status === \"failed\" || status === \"skipped\") continue;\n const targets = routeTargets(router);\n unknownSelections.set(router.id, targets);\n if (!candidates.has(router.id)) protectionQueue.push(...targets);\n }\n\n const protectedNodes = new Set<string>();\n for (let index = 0; index < protectionQueue.length; index++) {\n const nodeId = protectionQueue[index];\n if (protectedNodes.has(nodeId)) continue;\n protectedNodes.add(nodeId);\n protectionQueue.push(...(outgoing.get(nodeId) ?? []));\n protectionQueue.push(...(unknownSelections.get(nodeId) ?? []));\n }\n\n return flow.nodes.flatMap((node) =>\n candidates.has(node.id) && !protectedNodes.has(node.id) ? [node.id] : [],\n );\n}\n\n/**\n * Return every possible target branch gated by an unsettled router.\n *\n * Gating follows hard `flow` descendants only. A selected route, shared convergence, or another\n * live hard predecessor protects a node, matching settlement pruning without mutating snapshots.\n */\nexport function unsettledRouterBranchIds(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): Set<string> {\n const unsettled = flow.nodes.filter(\n (node) =>\n isRouterNode(node) &&\n ![\"complete\", \"failed\", \"skipped\"].includes(snapshots.get(node.id)?.status ?? \"not_started\"),\n );\n const branches = new Set(\n planRouterSkips(\n flow,\n snapshots,\n unsettled.map(({ id }) => ({ routerNodeId: id, selectedTarget: null })),\n ),\n );\n for (const component of routerOwnershipSourceComponents(flow, snapshots)) {\n for (const routerId of component) branches.delete(routerId);\n }\n return branches;\n}\n\n/**\n * Return one actually available, decidable router per source ownership component.\n *\n * Every source-component member remains ungated for normal admission. Within a settlement wave,\n * definition order chooses the first member that is both available and decidable; unresolved or\n * blocked peers cannot starve it. Limiting each component to one choice prevents a router from\n * completing atomically after that same wave makes its branch losing. Independent source\n * components can still settle together.\n */\nexport function availableRouterFrontier(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): FlowNode[] {\n const nodesById = new Map(flow.nodes.map((node) => [node.id, node]));\n return routerOwnershipSourceComponents(flow, snapshots).flatMap((component) => {\n for (const routerId of component) {\n const node = nodesById.get(routerId);\n if (!node || snapshots.get(routerId)?.status !== \"available\") continue;\n if (\"unresolved\" in evaluateRouterSelection(flow, node, snapshots)) continue;\n return [node];\n }\n return [];\n });\n}\n","import type {\n FlowDefinition,\n FlowEdge,\n FlowNode,\n FlowState,\n NodeExecutionSnapshot,\n NodePreconditionFailure,\n NodeState,\n NodeStatus,\n} from \"./types.js\";\nimport { evaluateFlowExpression, type FlowExpressionContext } from \"../contract/expression.js\";\nimport { buildFlowExpressionContext } from \"./bindings.js\";\nimport {\n isActiveRuntimeNode,\n isRouterNode,\n nodeIsOptional,\n nodeLabel,\n nodeSkillId,\n} from \"./node-shape.js\";\nimport {\n evaluateRouterSelection,\n planRouterSkips,\n unsettledRouterBranchIds,\n} from \"./router-settlement.js\";\n\n// ---------------------------------------------------------------------------\n// Core engine — stateless, pure functions\n// ---------------------------------------------------------------------------\n\n/** Return nodes with state owned by the current runtime. */\nfunction activeRuntimeNodes(flow: FlowDefinition): FlowNode[] {\n return flow.nodes.filter(isActiveRuntimeNode);\n}\n\n/** Evaluate every authored admission condition without mutating runtime state. */\nfunction failedPreconditions(\n node: FlowNode,\n context: FlowExpressionContext,\n): NodePreconditionFailure[] {\n const failures: NodePreconditionFailure[] = [];\n for (const requirement of node.contract?.requires ?? []) {\n const message = requirement.message ?? `Precondition failed: ${requirement.expr}`;\n try {\n if (!evaluateFlowExpression(requirement.expr, context)) {\n failures.push({ expression: requirement.expr, message, reason: \"false\" });\n }\n } catch (error) {\n failures.push({\n expression: requirement.expr,\n message,\n reason: \"error\",\n detail: error instanceof Error ? error.message : \"Flow expression evaluation failed\",\n });\n }\n }\n return failures;\n}\n\n/** Build adjacency: target → sources[] (incoming edges per node) */\nfunction buildIncoming(edges: FlowEdge[]): Map<string, FlowEdge[]> {\n const map = new Map<string, FlowEdge[]>();\n for (const edge of edges) {\n if (!map.has(edge.target)) map.set(edge.target, []);\n map.get(edge.target)!.push(edge);\n }\n return map;\n}\n\n/** Build adjacency: source → targets[] (outgoing edges per node) */\nfunction buildOutgoing(edges: FlowEdge[]): Map<string, FlowEdge[]> {\n const map = new Map<string, FlowEdge[]>();\n for (const edge of edges) {\n if (!map.has(edge.source)) map.set(edge.source, []);\n map.get(edge.source)!.push(edge);\n }\n return map;\n}\n\n/** Result of resolving one available router against the current expression context. */\nexport interface RouterResolution {\n /** First matching route target. `null` means every branch loses. */\n selectedTarget: string | null;\n /** Exclusive nodes belonging only to unselected route targets, in definition order. */\n skippedNodeIds: string[];\n}\n\n/** Available router that cannot make a deterministic choice from the current snapshot. */\nexport interface UnresolvedRouterResolution {\n /** Why the router remains available for a later drain pass. */\n unresolved: \"not-ready\" | \"no-match\";\n}\n\n/**\n * Resolve the first matching route for a router that is currently available.\n *\n * Route conditions use the same bounded context as node preconditions and bindings. Resolution\n * is deliberately separate from state computation: unavailable routers return `undefined`\n * without evaluating any route. Losing route targets and their exclusive downstream paths are\n * returned for the caller to mark skipped. Exclusivity follows hard `flow` edges only and keeps\n * selected routes, unsettled-router targets, shared convergence, and externally reachable nodes\n * live. A declared producer output that is not complete yet returns a retryable unresolved result;\n * malformed expressions still throw their path-bearing evaluator error.\n *\n * @param flow - Parsed flow containing the router and branch graph.\n * @param routerNodeId - Router execution identity.\n * @param snapshots - Current node snapshots used for admission and expression values.\n * @returns The selected target and losing nodes, an unresolved reason while available but not\n * decidable, or `undefined` while the router is unavailable.\n */\nexport function resolveAvailableRouter(\n flow: FlowDefinition,\n routerNodeId: string,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): RouterResolution | UnresolvedRouterResolution | undefined {\n const router = flow.nodes.find((node) => node.id === routerNodeId);\n if (!router || !isRouterNode(router)) return undefined;\n const state = computeFlowStateFromSnapshots(flow, snapshots);\n if (!state.available.includes(routerNodeId)) return undefined;\n\n const selected = evaluateRouterSelection(flow, router, snapshots);\n if (\"unresolved\" in selected) return selected;\n\n return {\n selectedTarget: selected.selectedTarget,\n skippedNodeIds: planRouterSkips(flow, snapshots, [\n { routerNodeId, selectedTarget: selected.selectedTarget },\n ]),\n };\n}\n\n/**\n * Compute the full {@link FlowState} from a flow definition and caller-supplied node ID sets.\n *\n * This is the primary engine function. It is stateless and side-effect-free — calling it\n * twice with the same arguments always returns an equivalent result.\n *\n * Edge semantics applied during computation:\n * - `'flow'` — hard dependency: target cannot start until source is `complete` or `skipped`.\n * - `'parallel'` — soft dependency: target may run while source is still running.\n * - `'optional'` — advisory: target can start regardless of source state.\n *\n * A node is `available` when every incoming `'flow'`-type edge has a complete or skipped source\n * and every authored precondition evaluates true.\n * A node is `not_started` when at least one hard predecessor is still pending.\n * The flow is `done` when every non-optional node is `complete` or `skipped`.\n *\n * This set-based overload has statuses but no completed output fields. Use\n * {@link computeFlowStateFromSnapshots} when a precondition reads node output.\n *\n * Prefer {@link computeFlowStateFromSnapshots} for callers that track full `NodeExecution`\n * state (interaction statuses such as `awaiting_approval`, `awaiting_input`, `failed`).\n *\n * @param flow - The parsed flow definition.\n * @param completedIds - Set of node IDs that have finished successfully.\n * @param runningIds - Set of node IDs currently executing. Defaults to an empty set.\n * @param skippedIds - Set of node IDs that were explicitly skipped. Skipped nodes count\n * as satisfied for downstream dependency checks. Defaults to an empty set.\n * @returns A {@link FlowState} describing every active runtime node.\n * @docLink packages/flow-engine/concepts#compute-flow-state\n */\nexport function computeFlowState(\n flow: FlowDefinition,\n completedIds: Set<string>,\n runningIds: Set<string> = new Set(),\n skippedIds: Set<string> = new Set(),\n): FlowState {\n const nodes = activeRuntimeNodes(flow);\n const incoming = buildIncoming(flow.edges);\n const snapshots = new Map<string, NodeExecutionSnapshot>();\n for (const node of nodes) {\n const status: NodeStatus = completedIds.has(node.id)\n ? \"complete\"\n : runningIds.has(node.id)\n ? \"running\"\n : skippedIds.has(node.id)\n ? \"skipped\"\n : \"not_started\";\n snapshots.set(node.id, { status });\n }\n const gatedBranches = unsettledRouterBranchIds(flow, snapshots);\n const context = buildFlowExpressionContext(flow, snapshots);\n\n const nodeStates: NodeState[] = nodes.map((node) => {\n const optional = nodeIsOptional(node);\n const skillId = nodeSkillId(node);\n const label = nodeLabel(node);\n\n if (completedIds.has(node.id)) {\n return {\n nodeId: node.id,\n skillId,\n label,\n status: \"complete\",\n optional,\n canRun: false,\n blockers: [],\n failedPreconditions: [],\n };\n }\n if (runningIds.has(node.id)) {\n return {\n nodeId: node.id,\n skillId,\n label,\n status: \"running\",\n optional,\n canRun: false,\n blockers: [],\n failedPreconditions: [],\n };\n }\n if (skippedIds.has(node.id)) {\n return {\n nodeId: node.id,\n skillId,\n label,\n status: \"skipped\",\n optional,\n canRun: false,\n blockers: [],\n failedPreconditions: [],\n };\n }\n\n if (gatedBranches.has(node.id)) {\n return {\n nodeId: node.id,\n skillId,\n label,\n status: \"not_started\",\n optional,\n canRun: false,\n blockers: [],\n failedPreconditions: [],\n };\n }\n\n const edges = incoming.get(node.id) ?? [];\n\n // Hard blockers: flow-type edges whose source is neither complete nor skipped\n const hardBlockers = edges\n .filter((e) => e.type === \"flow\")\n .filter((e) => !completedIds.has(e.source) && !skippedIds.has(e.source))\n .map((e) => e.source);\n\n const preconditionFailures = failedPreconditions(node, context);\n const canRun = hardBlockers.length === 0 && preconditionFailures.length === 0;\n\n let status: NodeStatus;\n if (!canRun) {\n status = \"not_started\";\n } else {\n status = \"available\";\n }\n\n return {\n nodeId: node.id,\n skillId,\n label,\n status,\n optional,\n canRun,\n blockers: hardBlockers,\n failedPreconditions: preconditionFailures,\n };\n });\n\n const _stateMap = new Map(nodeStates.map((s) => [s.nodeId, s]));\n\n const available = nodeStates.filter((s) => s.status === \"available\").map((s) => s.nodeId);\n const completed = nodeStates.filter((s) => s.status === \"complete\").map((s) => s.nodeId);\n const focus = nodeStates\n .filter(\n (s) =>\n s.status === \"running\" || s.status === \"awaiting_approval\" || s.status === \"awaiting_input\",\n )\n .map((s) => s.nodeId);\n\n // Flow is done when all required nodes are complete or skipped\n const requiredNodes = nodes.filter((n) => !nodeIsOptional(n));\n const done = requiredNodes.every((n) => completedIds.has(n.id) || skippedIds.has(n.id));\n\n return { flowId: flow.id, nodes: nodeStates, available, completed, focus, done };\n}\n\n/**\n * Snapshot-based variant of {@link computeFlowState}.\n *\n * Accepts a map of `NodeExecutionSnapshot` values carrying the current status and\n * interaction metadata for every node the caller knows about. Nodes absent from the\n * map are treated as `not_started`.\n *\n * This is the preferred API for the turn-based runner, which has a full `FlowExecution`\n * and needs to convey richer statuses (`awaiting_approval`, `awaiting_input`, `failed`)\n * back to the engine so downstream availability is computed correctly.\n *\n * Engine semantics:\n * - A node is `available` when all its incoming `'flow'`-type predecessors are `complete`\n * or `skipped`. Any other upstream status — including `awaiting_approval`,\n * `awaiting_input`, and `failed` — is treated as blocking. Every authored precondition\n * must also evaluate true against the snapshot expression context.\n * - A `failed` optional node does **not** block its dependents.\n * - The flow is `done` when every non-optional node is `complete` or `skipped`. A single\n * required node stuck in `failed` keeps `done` false.\n *\n * @param flow - The parsed flow definition.\n * @param snapshots - Map from node ID to its current {@link NodeExecutionSnapshot}.\n * Missing entries default to `not_started` with no interaction metadata.\n * @returns A {@link FlowState} describing every active runtime node,\n * including interaction fields (`approval`, `input`, `output`, `error`) copied\n * from the matching snapshot.\n * @docLink packages/flow-engine/concepts#compute-flow-state-from-snapshots\n */\nexport function computeFlowStateFromSnapshots(\n flow: FlowDefinition,\n snapshots: Map<string, NodeExecutionSnapshot>,\n): FlowState {\n const nodes = activeRuntimeNodes(flow);\n const incoming = buildIncoming(flow.edges);\n const gatedBranches = unsettledRouterBranchIds(flow, snapshots);\n const context = buildFlowExpressionContext(flow, snapshots);\n\n /** Resolve the effective status for a node — defaulting to `not_started`. */\n const statusFor = (nodeId: string): NodeStatus => snapshots.get(nodeId)?.status ?? \"not_started\";\n\n /** A predecessor \"passes\" when it is complete or skipped. */\n const passed = (nodeId: string): boolean => {\n const s = statusFor(nodeId);\n return s === \"complete\" || s === \"skipped\";\n };\n\n const nodeStates: NodeState[] = nodes.map((node) => {\n const snapshot = snapshots.get(node.id);\n const optional = nodeIsOptional(node);\n const skillId = nodeSkillId(node);\n const label = nodeLabel(node);\n const status = snapshot?.status ?? \"not_started\";\n\n const edges = incoming.get(node.id) ?? [];\n const flowPreds = edges.filter((e) => e.type === \"flow\");\n const hardBlockers = flowPreds.filter((e) => !passed(e.source)).map((e) => e.source);\n\n const isAdmissionState = status === \"not_started\" || status === \"available\";\n const preconditionFailures = isAdmissionState ? failedPreconditions(node, context) : [];\n\n // Recompute admission in both directions after fresh start or hydrate.\n let effectiveStatus: NodeStatus = status;\n if (isAdmissionState && gatedBranches.has(node.id)) {\n effectiveStatus = \"not_started\";\n } else if (isAdmissionState) {\n effectiveStatus =\n hardBlockers.length === 0 && preconditionFailures.length === 0\n ? \"available\"\n : \"not_started\";\n }\n\n return {\n nodeId: node.id,\n skillId,\n label,\n status: effectiveStatus,\n optional,\n canRun:\n hardBlockers.length === 0 &&\n preconditionFailures.length === 0 &&\n effectiveStatus === \"available\",\n blockers: hardBlockers,\n failedPreconditions: preconditionFailures,\n approval: snapshot?.approval,\n input: snapshot?.input,\n output: snapshot?.output,\n error: snapshot?.error,\n };\n });\n\n const available = nodeStates.filter((s) => s.status === \"available\").map((s) => s.nodeId);\n const completed = nodeStates.filter((s) => s.status === \"complete\").map((s) => s.nodeId);\n const focus = nodeStates\n .filter(\n (s) =>\n s.status === \"running\" || s.status === \"awaiting_approval\" || s.status === \"awaiting_input\",\n )\n .map((s) => s.nodeId);\n\n const requiredNodes = nodes.filter((n) => !nodeIsOptional(n));\n const done = requiredNodes.every((n) => {\n const s = statusFor(n.id);\n return s === \"complete\" || s === \"skipped\";\n });\n\n return { flowId: flow.id, nodes: nodeStates, available, completed, focus, done };\n}\n\n/**\n * Returns `true` when the given status prevents downstream nodes from starting.\n *\n * Only `'complete'` and `'skipped'` satisfy a hard (`'flow'`-type) edge dependency.\n * All other statuses — including `'awaiting_approval'`, `'awaiting_input'`, and\n * `'failed'` — are considered blocking.\n *\n * Use this helper in the FlowAdapter and the turn-based orchestrator instead of\n * hard-coding the two-value whitelist inline.\n *\n * @param status - The {@link NodeStatus} to evaluate.\n * @returns `true` if the status prevents dependents from becoming `available`.\n * @docLink packages/flow-engine/concepts#is-blocking\n */\nexport function isBlocking(status: NodeStatus): boolean {\n return status !== \"complete\" && status !== \"skipped\";\n}\n\n/**\n * Returns the IDs of nodes that become newly `available` after a specific node completes.\n *\n * More efficient than recomputing the full {@link FlowState} when only the downstream\n * impact of a single completion is needed. Only the direct successors of `justCompleted`\n * are evaluated — the rest of the graph is untouched.\n *\n * @param flow - The parsed flow definition.\n * @param justCompleted - ID of the node that just finished (will be added to the\n * effective completed set before evaluating successors).\n * @param completedIds - Set of node IDs already known to be complete before this call.\n * @param skippedIds - Set of node IDs that were explicitly skipped. Defaults to an empty set.\n * @returns Array of node IDs whose hard dependencies are now fully satisfied and that\n * were not already available before `justCompleted` finished. Unlike executable-node-filtered\n * helpers, this walks raw edge targets and does not filter by node type — if a `group`,\n * `sub-flow`, or `router` node is a direct successor, its ID can appear here. Callers that\n * dispatch these IDs are responsible for filtering inert nodes.\n * @docLink packages/flow-engine/concepts#resolve-next-nodes\n */\nexport function resolveNextNodes(\n flow: FlowDefinition,\n justCompleted: string,\n completedIds: Set<string>,\n skippedIds: Set<string> = new Set(),\n): string[] {\n const outgoing = buildOutgoing(flow.edges);\n const incoming = buildIncoming(flow.edges);\n const candidates = (outgoing.get(justCompleted) ?? []).map((e) => e.target);\n\n const nextCompleted = new Set([...completedIds, justCompleted]);\n const result: string[] = [];\n\n for (const candidateId of candidates) {\n const edges = incoming.get(candidateId) ?? [];\n const hardBlockers = edges\n .filter((e) => e.type === \"flow\")\n .filter((e) => !nextCompleted.has(e.source) && !skippedIds.has(e.source));\n if (hardBlockers.length === 0) {\n result.push(candidateId);\n }\n }\n\n return result;\n}\n\n/**\n * Returns the IDs of optional nodes that have not yet started and can be safely skipped.\n *\n * A node is skippable when it is:\n * 1. Not yet complete (absent from `completedIds`).\n * 2. Marked `optional` (`FlowNode.data.optional === true`).\n * 3. Not connected via a `'flow'`-type edge to any non-optional downstream node\n * (i.e. skipping it cannot starve a required node of a hard dependency).\n *\n * The runner may call this to present the user with a list of nodes they can bypass\n * without breaking the flow's required path.\n *\n * @param flow - The parsed flow definition.\n * @param completedIds - Set of node IDs that have already completed (excluded from results).\n * @returns Array of node IDs that are safe to skip at this point in the execution.\n * @docLink packages/flow-engine/concepts#compute-skippable\n */\nexport function computeSkippable(flow: FlowDefinition, completedIds: Set<string>): string[] {\n const nodes = activeRuntimeNodes(flow);\n const outgoing = buildOutgoing(flow.edges);\n\n return nodes\n .filter((n) => !completedIds.has(n.id))\n .filter(nodeIsOptional)\n .filter((n) => {\n // A node is skippable if none of its outgoing flow-type edges go to a required node\n const deps = (outgoing.get(n.id) ?? []).filter((e) => e.type === \"flow\");\n return deps.every((e) => {\n const target = flow.nodes.find((t) => t.id === e.target);\n return target ? nodeIsOptional(target) : false;\n });\n })\n .map((n) => n.id);\n}\n","import * as z from \"zod\";\nimport { collectFlowBindingExpressions, inspectFlowExpression } from \"../contract/expression.js\";\nimport type { FlowDefinition, FlowNode } from \"./types.js\";\n\n/** Result of validating fields at a producer's consumed-output boundary. */\nexport interface NodeOutputValidationResult {\n /** Whether the fields may be exposed to downstream consumers. */\n valid: boolean;\n /** Stable, path-bearing failures. Empty when validation is not required. */\n issues: string[];\n}\n\nfunction consumerExpressions(node: FlowNode): string[] {\n const expressions = (node.contract?.requires ?? []).map(({ expr }) => expr);\n expressions.push(...collectFlowBindingExpressions(node.contract?.input));\n if (node.run?.kind === \"router\") {\n expressions.push(...node.run.routes.map(({ when }) => when));\n }\n return expressions;\n}\n\nfunction readsProducerOutput(node: FlowNode, producerId: string): boolean {\n return consumerExpressions(node).some((expression) =>\n inspectFlowExpression(expression, false).some(({ path }) =>\n path.startsWith(`nodes.${producerId}.output.fields.`),\n ),\n );\n}\n\n/**\n * Return a producer's declared fields schema only when another node reads it.\n *\n * Consumption is deliberately limited to preconditions, named bindings, and\n * router conditions. Status reads and unreferenced declarations remain prose-only.\n */\nexport function getConsumedOutputSchema(\n flow: FlowDefinition,\n producerId: string,\n): Record<string, unknown> | undefined {\n const producer = flow.nodes.find(({ id }) => id === producerId);\n const schema = producer?.contract?.output?.fields;\n if (!schema) return undefined;\n return flow.nodes.some(\n (consumer) => consumer.id !== producerId && readsProducerOutput(consumer, producerId),\n )\n ? schema\n : undefined;\n}\n\n/** Validate proposed fields only when a downstream deterministic consumer requires them. */\nexport function validateConsumedNodeOutput(\n flow: FlowDefinition,\n producerId: string,\n fields: Record<string, unknown> | undefined,\n): NodeOutputValidationResult {\n const schema = getConsumedOutputSchema(flow, producerId);\n if (!schema) return { valid: true, issues: [] };\n\n try {\n const validator = z.fromJSONSchema(schema as Parameters<typeof z.fromJSONSchema>[0]);\n const parsed = validator.safeParse(fields ?? {});\n if (parsed.success) return { valid: true, issues: [] };\n return {\n valid: false,\n issues: parsed.error.issues\n .map((issue) => {\n const suffix = issue.path.map(String).join(\".\");\n return `fields${suffix ? `.${suffix}` : \"\"}: ${issue.message}`;\n })\n .sort(),\n };\n } catch (error) {\n return {\n valid: false,\n issues: [\n `fields: invalid authored JSON Schema: ${\n error instanceof Error ? error.message : String(error)\n }`,\n ],\n };\n }\n}\n","/**\n * Flow manifest schema and validation.\n *\n * Moved from @skaile/workspaces/types/manifests/flow.ts in Phase 1.7.3.\n * This is now the canonical location for flow manifest validation.\n */\n\nimport * as z from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Validation result (inline — avoids importing from types/manifests/_shared)\n// ---------------------------------------------------------------------------\n\nexport interface ManifestValidationSuccess<T> {\n ok: true;\n data: T;\n}\n\nexport interface ManifestValidationFailure {\n ok: false;\n errors: Array<{ path: string; message: string }>;\n}\n\nexport type ManifestValidationResult<T> = ManifestValidationSuccess<T> | ManifestValidationFailure;\n\n// ---------------------------------------------------------------------------\n// Schema\n// ---------------------------------------------------------------------------\n\nconst FlowNodeSchema = z.looseObject({\n id: z.string().min(1),\n skill: z.string().optional(),\n type: z.string().optional(),\n label: z.string().optional(),\n description: z.string().optional(),\n data: z\n .looseObject({\n optional: z.boolean().optional(),\n // Mandatory approval gate — autonomous mode cannot skip it.\n approval: z.looseObject({ mandatory: z.boolean().optional() }).optional(),\n })\n .refine((d) => !(d.optional === true && d.approval?.mandatory === true), {\n // A mandatory gate can never be skipped, so optional+mandatory is a\n // contradiction — reject it rather than silently letting mandatory win.\n message: \"a node cannot be both optional and a mandatory approval gate\",\n })\n .optional(),\n});\n\nconst FlowEdgeSchema = z.looseObject({\n id: z.string().optional(),\n source: z.string().min(1),\n target: z.string().min(1),\n condition: z.string().optional(),\n});\n\nexport const FlowManifestSchema = z.looseObject({\n id: z.string().min(1),\n version: z.string().optional(),\n name: z.string().min(1),\n description: z.string().optional(),\n metadata: z\n .looseObject({\n tags: z.array(z.string()).optional(),\n stage: z.string().optional(),\n icon: z.string().optional(),\n category: z.string().optional(),\n onboarding: z.record(z.string(), z.unknown()).optional(),\n })\n .optional(),\n globals: z.record(z.string(), z.unknown()).optional(),\n modes: z.record(z.string(), z.unknown()).optional(),\n tier_presets: z.record(z.string(), z.record(z.string(), z.unknown())).optional(),\n artifact_handoff: z.unknown().optional(),\n entry: z.string().optional(),\n nodes: z.array(FlowNodeSchema).optional(),\n edges: z.array(FlowEdgeSchema).optional(),\n});\n\nexport type FlowManifest = z.infer<typeof FlowManifestSchema>;\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nexport function validateFlow(data: unknown): ManifestValidationResult<FlowManifest> {\n const result = FlowManifestSchema.safeParse(data);\n if (result.success) {\n return { ok: true, data: result.data };\n }\n return {\n ok: false,\n errors: result.error.issues.map((issue) => ({\n path: issue.path.join(\".\"),\n message: issue.message,\n })),\n };\n}\n","/**\n * Flow asset kind provider.\n *\n * Exported from @skaile/workspaces/factory-assets/connectors/flow/engine for explicit registration\n * by the CLI at bootstrap. Discovery does NOT auto-include this provider\n * (discovery must stay a leaf — no flow-engine imports).\n *\n * Implements IAssetKindProvider with flow-specific:\n * - Discovery patterns: *.flow.yaml, *.flow.json\n * - Manifest validation via FlowManifestSchema\n * - Requires extraction: nodes[].run.assets plus legacy skill/sub-flow references\n * - File filter: just the manifest file (flows are single-file)\n */\n\nimport * as path from \"node:path\";\nimport type {\n AssetKindFileFilter,\n AssetKindRequiresEdge,\n IAssetKindProvider,\n} from \"@skaile/workspaces/plugins\";\nimport { validateFlow } from \"./flow-manifest.js\";\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport const flowKindProvider: IAssetKindProvider = {\n kind: \"flow\",\n displayName: \"Flow\",\n providerVersion: \"1.1.0\",\n discoveryPatterns: [\"**/*.flow.yaml\", \"**/*.flow.json\"],\n\n matchesPath(relativePath: string): boolean {\n return relativePath.endsWith(\".flow.yaml\") || relativePath.endsWith(\".flow.json\");\n },\n\n validateManifest(data: unknown) {\n return validateFlow(data);\n },\n\n defaultFileFilter(manifestPath: string): AssetKindFileFilter {\n return {\n assetRoot: path.dirname(manifestPath),\n files: [path.basename(manifestPath)],\n };\n },\n\n extractRequires(assetRef: string, manifest: Record<string, unknown>): AssetKindRequiresEdge[] {\n const edges: AssetKindRequiresEdge[] = [];\n const seen = new Set<string>();\n const add = (to: string, field: string): void => {\n if (seen.has(to)) return;\n seen.add(to);\n edges.push({ from: assetRef, to, field });\n };\n\n const nodes = manifest.nodes;\n if (Array.isArray(nodes)) {\n for (const node of nodes) {\n if (typeof node !== \"object\" || node === null) continue;\n const n = node as Record<string, unknown>;\n const data = (\n typeof n.data === \"object\" && n.data !== null ? (n.data as Record<string, unknown>) : {}\n ) as Record<string, unknown>;\n const run =\n typeof n.run === \"object\" && n.run !== null ? (n.run as Record<string, unknown>) : {};\n\n if (Array.isArray(run.assets)) {\n for (const asset of run.assets) {\n if (typeof asset === \"string\") add(asset, \"nodes[].run.assets\");\n }\n }\n\n if (run.kind === \"sub-flow\" && typeof run.flow === \"string\") {\n const flowRef = run.flow.startsWith(\"flow:\") ? run.flow : `flow:${run.flow}`;\n add(flowRef, \"nodes[].run.flow\");\n }\n\n const skill = typeof data.skill === \"string\" ? data.skill : n.skill;\n if (typeof skill === \"string\") {\n add(skill, \"nodes[].data.skill\");\n }\n\n const subFlow = typeof data.flow === \"string\" ? data.flow : n.flow;\n if (typeof subFlow === \"string\") {\n add(subFlow.startsWith(\"flow:\") ? subFlow : `flow:${subFlow}`, \"nodes[].data.flow\");\n }\n }\n }\n\n return edges;\n },\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { assetSearchDirs } from \"@skaile/workspaces/core\";\nimport { parse as parseYaml } from \"yaml\";\nimport { parseFlowDefinition } from \"../contract/normalize.js\";\nimport type { FlowDefinition } from \"./types.js\";\n\n/**\n * Load a single {@link FlowDefinition} from a YAML or JSON file on disk.\n *\n * Format detection is based on file extension:\n * - `.yaml` / `.yml` — parsed with the `yaml` library.\n * - Everything else — parsed as JSON.\n *\n * @param filePath - Absolute path to the flow file.\n * @returns The parsed {@link FlowDefinition}.\n * @throws {Error} If the file does not exist, cannot be read, or fails to parse.\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function loadFlow(filePath: string): FlowDefinition {\n const raw = fs.readFileSync(filePath, \"utf-8\");\n const ext = path.extname(filePath).toLowerCase();\n const authored = ext === \".yaml\" || ext === \".yml\" ? parseYaml(raw) : JSON.parse(raw);\n const parsed = parseFlowDefinition(authored);\n if (!parsed.ok) {\n const details = parsed.errors\n .map((issue) => ` ${issue.path || \"<root>\"}: ${issue.message}`)\n .join(\"\\n\");\n throw new Error(`Invalid flow definition:\\n${details}`);\n }\n return parsed.data;\n}\n\n/**\n * Load all `*.flow.yaml` and legacy `*.flow.json` / `*.json` flow files from a directory.\n *\n * Files that fail to parse are skipped with a warning written to `stderr` — they do not\n * cause the function to throw. Files whose name starts with `_` are skipped entirely\n * (treated as drafts or disabled flows). Files missing the required `id`, `nodes`, or\n * `edges` fields are also discarded silently.\n *\n * @param dirPath - Absolute path to the directory to scan.\n * @returns Array of successfully parsed {@link FlowDefinition} objects. Empty if the\n * directory does not exist or contains no valid flow files.\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function loadFlowsFromDir(dirPath: string): FlowDefinition[] {\n if (!fs.existsSync(dirPath)) return [];\n\n const files = fs.readdirSync(dirPath).filter((f) => {\n if (f.startsWith(\"_\")) return false;\n return f.endsWith(\".flow.yaml\") || f.endsWith(\".flow.json\") || f.endsWith(\".json\");\n });\n\n const flows: FlowDefinition[] = [];\n\n for (const file of files) {\n try {\n const def = loadFlow(path.join(dirPath, file));\n if (def.id && def.nodes && def.edges) {\n flows.push(def);\n }\n } catch (err) {\n process.stderr.write(`[agent-flow-engine] skipping ${file}: ${(err as Error).message}\\n`);\n }\n }\n\n return flows;\n}\n\n/**\n * Discover and load all flow definitions from every domain under an `ai-assets` root.\n *\n * Walks the top-level subdirectories of `aiResourcesRoot`, looks for a `flows/`\n * subdirectory inside each domain, and delegates to {@link loadFlowsFromDir} for\n * each one found. Files prefixed with `_` are skipped (draft/disabled).\n *\n * @param aiResourcesRoot - Absolute path to the `ai-assets/` directory (or equivalent\n * resource root). Typically the `ai-assets/` folder at the monorepo root.\n * @returns Flat array of all successfully parsed {@link FlowDefinition} objects across\n * all domains. Empty if the root directory does not exist.\n * @docLink packages/flow-engine/concepts#flow-loading\n */\nexport function loadAllFlows(aiResourcesRoot: string): FlowDefinition[] {\n if (!fs.existsSync(aiResourcesRoot)) return [];\n\n // `assetSearchDirs` covers both the flat (`<root>/flows/`) and domain-nested\n // (`<root>/<domain>/flows/`) layouts via the one shared layout primitive.\n // De-dupe by id (first dir wins) so a root that happens to define a flow in\n // both layouts surfaces it once.\n const byId = new Map<string, FlowDefinition>();\n for (const { dir } of assetSearchDirs(aiResourcesRoot, \"flows\")) {\n for (const flow of loadFlowsFromDir(dir)) {\n if (!byId.has(flow.id)) byId.set(flow.id, flow);\n }\n }\n return [...byId.values()];\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { getStoreConfig, getStoreToken, storeFetch } from './chunk-AM5LFRXJ.js';
2
- import { S, logErr, logWarn, logOk, logInfo } from './chunk-PJ6INYDD.js';
2
+ import { S, logErr, logWarn, logOk, logInfo } from './chunk-XTFZOYNY.js';
3
3
 
4
4
  // cli/src/store-publisher.ts
5
5
  function makeHttpPublisherClient(config = getStoreConfig(), timeoutMs = 2e4) {
@@ -154,5 +154,5 @@ async function publishToStore(opts) {
154
154
  }
155
155
 
156
156
  export { bareName, formatNamespaceAvailability, makeHttpPublisherClient, preflightNamespace, publishToStore, refFor };
157
- //# sourceMappingURL=chunk-JAFEMG7W.js.map
158
- //# sourceMappingURL=chunk-JAFEMG7W.js.map
157
+ //# sourceMappingURL=chunk-FW2C6JJP.js.map
158
+ //# sourceMappingURL=chunk-FW2C6JJP.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../cli/src/store-publisher.ts","../cli/src/commands/publish-core.ts"],"names":[],"mappings":";;;;AA+FO,SAAS,uBAAA,CACd,MAAA,GAAsB,cAAA,EAAe,EACrC,YAAY,GAAA,EACK;AAGjB,EAAA,MAAM,IAAA,GAAO,OACX,IAAA,EACA,IAAA,KACe;AACf,IAAA,MAAM,GAAA,GAAM,MAAM,aAAA,EAAc;AAChC,IAAA,OAAO,UAAA,CAAc,EAAE,GAAG,MAAA,EAAQ,GAAA,EAAI,EAAG,IAAA,EAAM,EAAE,SAAA,EAAW,GAAG,IAAA,EAAM,CAAA;AAAA,EACvE,CAAA;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,MAAM,IAAA,CAAK,YAAY,CAAA;AAAA,IAC3B,UAAA,EAAY,CAAC,IAAA,KAAS,IAAA,CAAK,mBAAmB,EAAE,MAAA,EAAQ,MAAA,EAAQ,IAAA,EA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,CAAA,CAAE,IAAA,EAAM,OAAA,CAAQ,SAAA,CAAU,kBAAA,EAAoB,CAAA,CAAE,IAAA,EAAM,CAAA,CAAE,OAAO,CAAC,CAAA;AAAA,IACxF,SAAS,GAAA,EAAK;AACZ,MAAA,OAAA;AAAA,QACE,CAAA,kBAAA,EAAqB,CAAA,CAAE,IAAI,CAAA,CAAA,EAAI,CAAA,CAAE,IAAI,CAAA,EAAA,EAAK,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,OAC5F;AAAA,IACF;AAAA,EACF;AAEA,EAAA,KAAA,CAAM,CAAA,UAAA,EAAa,SAAA,CAAU,MAAM,CAAA,UAAA,CAAY,CAAA;AAC/C,EAAA,KAAA,MAAW,CAAA,IAAK,SAAA,EAAW,OAAA,CAAQ,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAC3C,EAAA,OAAO,EAAE,SAAA,EAAU;AACrB","file":"chunk-JAFEMG7W.js","sourcesContent":["/**\n * Typed REST client for the AI Asset Store **publisher** surface — the\n * curator-publish flow (`skaile source manifest publish` / `yank`). Thin\n * wrappers over {@link storeFetch}; every method maps 1:1 to an `/api/v1/…`\n * endpoint. The {@link PublisherClient} interface is injectable so the\n * orchestration in `commands/source-manifest-publish.ts` can be unit-tested\n * against a fake without a live store.\n *\n * @docLink cli/dev-guide#store-publisher\n */\n\nimport { getStoreConfig, getStoreToken, type StoreConfig, storeFetch } from \"./store-client.ts\";\n\n/**\n * The publisher REST surface used by the curator-publish flow. Kept minimal —\n * only the endpoints `runPublish` / `runYank` actually call. Response shapes\n * are narrowed to the fields the orchestration reads (the server returns more).\n */\nexport interface PublisherClient {\n /**\n * Identity of the caller. `username` is the Keycloak login (personal-tier\n * namespace); `githubLogin` is the verified GitHub handle when connected —\n * the namespace to publish under when it differs from the login.\n */\n me(): Promise<{ username: string; githubLogin?: string | null }>;\n /** Register (or re-register) a source; returns the created/existing row id. */\n sourcesAdd(body: {\n url: string;\n ref: string;\n sidecarUrl?: string;\n sidecarRef?: string;\n /**\n * Target publisher namespace (the manifest's `publisher`). When it differs\n * from the caller's login username, the store resolves the CLAIMED Publisher\n * for it (the store must already have the claim). Omitted → the store\n * defaults to `@<username>` (personal).\n */\n namespace?: string;\n }): Promise<{ id: string }>;\n /** List sources — used to recover an id when `sourcesAdd` rejects a dup url. */\n sourcesList(): Promise<Array<{ id: string; url: string }>>;\n /** Kick off a source sync; returns the async job id to poll. */\n sourceSync(id: string): Promise<{ jobId: string }>;\n /** Poll a job's terminal status + per-item results. */\n jobGet(\n jobId: string,\n ): Promise<{ status: string; items?: Array<{ label: string; status: string; error?: string }> }>;\n /** Discovered publishable candidates for a synced source. */\n sourceCandidates(id: string): Promise<\n Array<{\n id: string;\n name: string;\n version: string;\n kind: string;\n published: boolean;\n assetRoot: string;\n }>\n >;\n /** Per-asset preview — the discovered file set + resolved candidate metadata. */\n assetPreview(id: string): Promise<{\n discoveredFiles: string[];\n candidate: { name: string; version: string; kind: string; publisherNamespace: string };\n }>;\n /**\n * Publish one asset. `dryRun` returns the would-be `{ manifest }` without\n * launching a job; the normal path returns `{ jobId }`.\n */\n assetPublish(\n id: string,\n body: { ref: string; files: string[] },\n dryRun?: boolean,\n ): Promise<{ jobId?: string; manifest?: unknown }>;\n /** Retract a published asset. Response body is ignored. */\n assetUnpublish(id: string): Promise<unknown>;\n /**\n * Read-only \"can I publish under `@<ns>` right now, and if not, what's the\n * path?\" probe. Backs the `publish --dry-run` namespace status line; its\n * `message` is store-authored and meant to be surfaced verbatim.\n */\n namespaceAvailability(ns: string): Promise<{\n namespace: string;\n status: \"owned-by-you\" | \"claimable-by-you\" | \"reserved\" | \"available\";\n claimMethod?: string;\n message: string;\n }>;\n}\n\n/**\n * Construct the real HTTP-backed {@link PublisherClient}. Every call carries a\n * longer timeout than the default store client because publish/sync trigger\n * server-side clone work.\n *\n * @param config - Store connection config; defaults to {@link getStoreConfig}.\n * @param timeoutMs - Per-request abort timeout (default 20s).\n */\nexport function makeHttpPublisherClient(\n config: StoreConfig = getStoreConfig(),\n timeoutMs = 20_000,\n): PublisherClient {\n // Acquire a fresh Keycloak token per call (device-flow session in\n // ~/.skaile/auth.json, refreshed on demand) rather than a static config.jwt.\n const call = async <T>(\n path: string,\n opts?: { method?: string; body?: unknown; params?: Record<string, string> },\n ): Promise<T> => {\n const jwt = await getStoreToken();\n return storeFetch<T>({ ...config, jwt }, path, { timeoutMs, ...opts });\n };\n return {\n me: () => call(\"/api/v1/me\"),\n sourcesAdd: (body) => call(\"/api/v1/sources\", { method: \"POST\", body }),\n sourcesList: () => call(\"/api/v1/sources\"),\n sourceSync: (id) => call(`/api/v1/sources/${id}/sync`, { method: \"POST\", body: {} }),\n jobGet: (jobId) => call(`/api/v1/jobs/${jobId}`),\n sourceCandidates: (id) => call(`/api/v1/sources/${id}/candidates`),\n assetPreview: (id) => call(`/api/v1/assets/${id}/preview`),\n assetPublish: (id, body, dryRun) =>\n call(`/api/v1/assets/${id}/publish`, {\n method: \"POST\",\n body,\n ...(dryRun ? { params: { dryRun: \"1\" } } : {}),\n }),\n assetUnpublish: (id) => call(`/api/v1/assets/${id}/unpublish`, { method: \"POST\", body: {} }),\n namespaceAvailability: (ns) =>\n call(`/api/v1/namespaces/${encodeURIComponent(ns)}/availability`),\n };\n}\n","/**\n * Shared store-interaction core for the two publish front-ends — the curator\n * sidecar flow (`source manifest publish`) and the first-party library flow\n * (`library publish`). Both differ only in their git side-effects + how they\n * resolve the source repo; the store orchestration below (register → sync →\n * candidates → per-asset preview+publish) is identical.\n *\n * The store REST surface is reached through the injectable {@link PublisherClient}\n * so the orchestration stays unit/integration-testable without a live store.\n *\n * @docLink cli/commands/source#manifest-publish\n */\n\nimport type { SkPublishManifest } from \"@skaile/workspaces/core\";\nimport { logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\nimport type { PublisherClient } from \"../store-publisher.ts\";\n\n/**\n * One-line rendering of a namespace-availability probe for a `--dry-run` plan.\n * The `message` is store-authored (identical to what a real publish would echo)\n * — we only prepend a status glyph so the reader sees green/amber/red at a\n * glance without the CLI re-deriving any authorization logic.\n */\nexport function formatNamespaceAvailability(a: {\n status: \"owned-by-you\" | \"claimable-by-you\" | \"reserved\" | \"available\";\n message: string;\n}): string {\n switch (a.status) {\n case \"owned-by-you\":\n case \"available\":\n return `${S.ok(\"✓\")} ${a.message}`;\n case \"claimable-by-you\":\n return `${S.warn(\"!\")} ${a.message}`;\n default:\n return `${S.err(\"✗\")} ${a.message}`;\n }\n}\n\n/**\n * Preflight the target namespace against the store's availability probe BEFORE a\n * publish does any irreversible work (a public git push). Returns `{ ok: false }`\n * with a guided message for `reserved` (not yours) and `claimable-by-you` (must\n * claim first) — the two states a real publish would reject — so the caller can\n * abort with actionable guidance instead of a raw 422 after pushing bytes.\n *\n * The probe is advisory: any failure (offline, older store) returns `{ ok: true }`\n * so the store stays the authority and a valid publish is never blocked.\n */\nexport async function preflightNamespace(\n client: PublisherClient,\n namespace: string,\n): Promise<{ ok: boolean; message?: string }> {\n let a: Awaited<ReturnType<PublisherClient[\"namespaceAvailability\"]>>;\n try {\n a = await client.namespaceAvailability(namespace);\n } catch {\n return { ok: true };\n }\n switch (a.status) {\n case \"owned-by-you\":\n case \"available\":\n return { ok: true };\n case \"claimable-by-you\":\n return {\n ok: false,\n message:\n `@${namespace} isn't yours yet — claim it in the store first` +\n `${a.claimMethod ? ` (${a.claimMethod})` : \"\"}, then re-run. ${a.message}`,\n };\n default: // reserved, or any unrecognized future status (fail safe → block)\n return { ok: false, message: `Cannot publish under @${namespace} — ${a.message}` };\n }\n}\n\n/** One candidate row shape the matcher operates on (kind + name are the key). */\ninterface CandidateLike {\n kind: string;\n name: string;\n}\n\n/**\n * Keep only candidates whose `(kind, name)` pair is declared in the manifest.\n * The backend may merge extra assets from the base repo into the candidate\n * list; a publish only touches what the manifest curated/declared.\n */\nexport function matchCandidatesToManifest<T extends CandidateLike>(\n candidates: T[],\n manifest: SkPublishManifest,\n): T[] {\n const wanted = new Set((manifest.assets ?? []).map((a) => `${a.kind}:${a.name}`));\n return candidates.filter((c) => wanted.has(`${c.kind}:${c.name}`));\n}\n\n/** A canonical ref string `kind:@publisher/name[#version]` for reporting. */\nexport function refFor(kind: string, publisher: string, name: string, version?: string): string {\n const base = `${kind}:@${publisher}/${name}`;\n return version ? `${base}#${version}` : base;\n}\n\n/** The bare asset name from a `kind:@publisher/name#version` ref or a plain name. */\nexport function bareName(ref: string): string {\n const afterKind = ref.includes(\":\") ? ref.slice(ref.indexOf(\":\") + 1) : ref;\n const afterScope = afterKind.includes(\"/\")\n ? afterKind.slice(afterKind.indexOf(\"/\") + 1)\n : afterKind;\n return afterScope.split(\"#\")[0];\n}\n\n/**\n * Poll a job until it leaves `running` or the deadline passes. Returns the last\n * observed state — the caller MUST treat a still-`running` result as a timeout\n * (not success), since it means the deadline was hit before the job finished.\n */\nexport async function pollJob(\n client: PublisherClient,\n jobId: string,\n intervalMs = 1_500,\n timeoutMs = 60_000,\n): Promise<{ status: string; items?: Array<{ label: string; status: string; error?: string }> }> {\n const deadline = Date.now() + timeoutMs;\n let job = await client.jobGet(jobId);\n while (job.status === \"running\" && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, intervalMs));\n job = await client.jobGet(jobId);\n }\n return job;\n}\n\n/**\n * True when a `sourcesAdd` rejection is a duplicate-URL conflict (the source is\n * already registered) — the only error the publish flow recovers from by looking\n * the existing row up. Every other failure (auth, 5xx, network) must propagate.\n */\nexport function isDupSourceError(err: unknown): boolean {\n const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();\n return /\\b409\\b|conflict|duplicate|already exists|already registered|unique/.test(msg);\n}\n\n/**\n * Register + sync the source, then publish its curated/declared candidates —\n * the store-side steps shared by both publish front-ends. Git side-effects (the\n * sidecar push, or the library commit+push) happen in the caller *before* this;\n * this function is purely store interaction.\n *\n * The sidecar front-end passes `sidecar` (so `sourcesAdd` carries the sidecar\n * pin); the library front-end omits it (the source repo IS the manifest host).\n * `assetName`, when set, narrows publication to the single candidate of that\n * name. Fatal store states (`sourcesAdd` non-dup failure) surface; sync failures\n * and empty candidate sets `process.exit(1)` with the same messages as before.\n */\nexport async function publishToStore(opts: {\n sourceUrl: string;\n ref: string;\n sidecar?: { url: string; ref: string };\n manifest: SkPublishManifest;\n assetName?: string;\n client: PublisherClient;\n}): Promise<{ published: string[] }> {\n const { sourceUrl, ref, sidecar, manifest, assetName, client: pub } = opts;\n\n let sourceId: string;\n try {\n const added = await pub.sourcesAdd({\n url: sourceUrl,\n ref,\n ...(sidecar ? { sidecarUrl: sidecar.url, sidecarRef: sidecar.ref } : {}),\n // Publish under the manifest's declared namespace; the store resolves a\n // claimed Publisher when it differs from the caller's login, else defaults\n // to `@<username>`. Omitted when the manifest carries no publisher.\n ...(manifest.publisher ? { namespace: manifest.publisher } : {}),\n });\n sourceId = added.id;\n } catch (err) {\n // Only a duplicate-url conflict is recoverable (source already registered);\n // auth/5xx/network failures must surface, not silently reuse a stale row.\n if (!isDupSourceError(err)) throw err;\n const rows = await pub.sourcesList();\n const found = rows.find((r) => r.url === sourceUrl);\n if (!found) {\n throw new Error(\n `Source ${sourceUrl} looked already-registered but no owned row matched: ` +\n `${err instanceof Error ? err.message : String(err)}`,\n );\n }\n sourceId = found.id;\n }\n\n const { jobId } = await pub.sourceSync(sourceId);\n const job = await pollJob(pub, jobId);\n if (job.status === \"failed\" || job.status === \"cancelled\") {\n const failed = (job.items ?? []).filter((i) => i.status === \"failed\");\n for (const i of failed) logErr(`sync: ${i.label}: ${i.error ?? \"failed\"}`);\n logErr(`Source sync ${job.status}.`);\n process.exit(1);\n }\n // A still-`running` job means the poll deadline was hit — do NOT proceed on an\n // unfinished sync (it would read incomplete candidates).\n if (job.status === \"running\") {\n logErr(\"Source sync timed out before completing — re-run `publish`, or check the store.\");\n process.exit(1);\n }\n\n let candidates = matchCandidatesToManifest(await pub.sourceCandidates(sourceId), manifest);\n if (assetName) candidates = candidates.filter((c) => c.name === assetName);\n if (candidates.length === 0) {\n logWarn(\"No candidates discovered — check the manifest and the source ref.\");\n process.exit(1);\n }\n\n const published: string[] = [];\n for (const c of candidates) {\n try {\n const preview = await pub.assetPreview(c.id);\n const res = await pub.assetPublish(c.id, { ref, files: preview.discoveredFiles });\n // Publish is async — wait for the job so we only report refs that actually\n // landed, not ones whose import is still in flight or about to fail.\n if (res.jobId) {\n const pubJob = await pollJob(pub, res.jobId);\n if (pubJob.status !== \"succeeded\") {\n const errs = (pubJob.items ?? [])\n .filter((i) => i.status === \"failed\")\n .map((i) => i.error)\n .filter(Boolean);\n logWarn(\n `Publish of ${c.kind}:${c.name} did not succeed (${pubJob.status})` +\n (errs.length ? `: ${errs.join(\"; \")}` : \"\"),\n );\n continue;\n }\n }\n published.push(refFor(c.kind, preview.candidate.publisherNamespace, c.name, c.version));\n } catch (err) {\n logWarn(\n `Failed to publish ${c.kind}:${c.name}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n logOk(`Published ${published.length} asset(s):`);\n for (const r of published) logInfo(` ${r}`);\n return { published };\n}\n"]}
1
+ {"version":3,"sources":["../cli/src/store-publisher.ts","../cli/src/commands/publish-core.ts"],"names":[],"mappings":";;;;AA+FO,SAAS,uBAAA,CACd,MAAA,GAAsB,cAAA,EAAe,EACrC,YAAY,GAAA,EACK;AAGjB,EAAA,MAAM,IAAA,GAAO,OACX,IAAA,EACA,IAAA,KACe;AACf,IAAA,MAAM,GAAA,GAAM,MAAM,aAAA,EAAc;AAChC,IAAA,OAAO,UAAA,CAAc,EAAE,GAAG,MAAA,EAAQ,GAAA,EAAI,EAAG,IAAA,EAAM,EAAE,SAAA,EAAW,GAAG,IAAA,EAAM,CAAA;AAAA,EACvE,CAAA;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,MAAM,IAAA,CAAK,YAAY,CAAA;AAAA,IAC3B,UAAA,EAAY,CAAC,IAAA,KAAS,IAAA,CAAK,mBAAmB,EAA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A,SAAA,CAAU,IAAA,CAAK,MAAA,CAAO,CAAA,CAAE,IAAA,EAAM,OAAA,CAAQ,SAAA,CAAU,kBAAA,EAAoB,CAAA,CAAE,IAAA,EAAM,CAAA,CAAE,OAAO,CAAC,CAAA;AAAA,IACxF,SAAS,GAAA,EAAK;AACZ,MAAA,OAAA;AAAA,QACE,CAAA,kBAAA,EAAqB,CAAA,CAAE,IAAI,CAAA,CAAA,EAAI,CAAA,CAAE,IAAI,CAAA,EAAA,EAAK,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,OAC5F;AAAA,IACF;AAAA,EACF;AAEA,EAAA,KAAA,CAAM,CAAA,UAAA,EAAa,SAAA,CAAU,MAAM,CAAA,UAAA,CAAY,CAAA;AAC/C,EAAA,KAAA,MAAW,CAAA,IAAK,SAAA,EAAW,OAAA,CAAQ,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAC3C,EAAA,OAAO,EAAE,SAAA,EAAU;AACrB","file":"chunk-FW2C6JJP.js","sourcesContent":["/**\n * Typed REST client for the AI Asset Store **publisher** surface — the\n * curator-publish flow (`skaile source manifest publish` / `yank`). Thin\n * wrappers over {@link storeFetch}; every method maps 1:1 to an `/api/v1/…`\n * endpoint. The {@link PublisherClient} interface is injectable so the\n * orchestration in `commands/source-manifest-publish.ts` can be unit-tested\n * against a fake without a live store.\n *\n * @docLink cli/dev-guide#store-publisher\n */\n\nimport { getStoreConfig, getStoreToken, type StoreConfig, storeFetch } from \"./store-client.ts\";\n\n/**\n * The publisher REST surface used by the curator-publish flow. Kept minimal —\n * only the endpoints `runPublish` / `runYank` actually call. Response shapes\n * are narrowed to the fields the orchestration reads (the server returns more).\n */\nexport interface PublisherClient {\n /**\n * Identity of the caller. `username` is the Keycloak login (personal-tier\n * namespace); `githubLogin` is the verified GitHub handle when connected —\n * the namespace to publish under when it differs from the login.\n */\n me(): Promise<{ username: string; githubLogin?: string | null }>;\n /** Register (or re-register) a source; returns the created/existing row id. */\n sourcesAdd(body: {\n url: string;\n ref: string;\n sidecarUrl?: string;\n sidecarRef?: string;\n /**\n * Target publisher namespace (the manifest's `publisher`). When it differs\n * from the caller's login username, the store resolves the CLAIMED Publisher\n * for it (the store must already have the claim). Omitted → the store\n * defaults to `@<username>` (personal).\n */\n namespace?: string;\n }): Promise<{ id: string }>;\n /** List sources — used to recover an id when `sourcesAdd` rejects a dup url. */\n sourcesList(): Promise<Array<{ id: string; url: string }>>;\n /** Kick off a source sync; returns the async job id to poll. */\n sourceSync(id: string): Promise<{ jobId: string }>;\n /** Poll a job's terminal status + per-item results. */\n jobGet(\n jobId: string,\n ): Promise<{ status: string; items?: Array<{ label: string; status: string; error?: string }> }>;\n /** Discovered publishable candidates for a synced source. */\n sourceCandidates(id: string): Promise<\n Array<{\n id: string;\n name: string;\n version: string;\n kind: string;\n published: boolean;\n assetRoot: string;\n }>\n >;\n /** Per-asset preview — the discovered file set + resolved candidate metadata. */\n assetPreview(id: string): Promise<{\n discoveredFiles: string[];\n candidate: { name: string; version: string; kind: string; publisherNamespace: string };\n }>;\n /**\n * Publish one asset. `dryRun` returns the would-be `{ manifest }` without\n * launching a job; the normal path returns `{ jobId }`.\n */\n assetPublish(\n id: string,\n body: { ref: string; files: string[] },\n dryRun?: boolean,\n ): Promise<{ jobId?: string; manifest?: unknown }>;\n /** Retract a published asset. Response body is ignored. */\n assetUnpublish(id: string): Promise<unknown>;\n /**\n * Read-only \"can I publish under `@<ns>` right now, and if not, what's the\n * path?\" probe. Backs the `publish --dry-run` namespace status line; its\n * `message` is store-authored and meant to be surfaced verbatim.\n */\n namespaceAvailability(ns: string): Promise<{\n namespace: string;\n status: \"owned-by-you\" | \"claimable-by-you\" | \"reserved\" | \"available\";\n claimMethod?: string;\n message: string;\n }>;\n}\n\n/**\n * Construct the real HTTP-backed {@link PublisherClient}. Every call carries a\n * longer timeout than the default store client because publish/sync trigger\n * server-side clone work.\n *\n * @param config - Store connection config; defaults to {@link getStoreConfig}.\n * @param timeoutMs - Per-request abort timeout (default 20s).\n */\nexport function makeHttpPublisherClient(\n config: StoreConfig = getStoreConfig(),\n timeoutMs = 20_000,\n): PublisherClient {\n // Acquire a fresh Keycloak token per call (device-flow session in\n // ~/.skaile/auth.json, refreshed on demand) rather than a static config.jwt.\n const call = async <T>(\n path: string,\n opts?: { method?: string; body?: unknown; params?: Record<string, string> },\n ): Promise<T> => {\n const jwt = await getStoreToken();\n return storeFetch<T>({ ...config, jwt }, path, { timeoutMs, ...opts });\n };\n return {\n me: () => call(\"/api/v1/me\"),\n sourcesAdd: (body) => call(\"/api/v1/sources\", { method: \"POST\", body }),\n sourcesList: () => call(\"/api/v1/sources\"),\n sourceSync: (id) => call(`/api/v1/sources/${id}/sync`, { method: \"POST\", body: {} }),\n jobGet: (jobId) => call(`/api/v1/jobs/${jobId}`),\n sourceCandidates: (id) => call(`/api/v1/sources/${id}/candidates`),\n assetPreview: (id) => call(`/api/v1/assets/${id}/preview`),\n assetPublish: (id, body, dryRun) =>\n call(`/api/v1/assets/${id}/publish`, {\n method: \"POST\",\n body,\n ...(dryRun ? { params: { dryRun: \"1\" } } : {}),\n }),\n assetUnpublish: (id) => call(`/api/v1/assets/${id}/unpublish`, { method: \"POST\", body: {} }),\n namespaceAvailability: (ns) =>\n call(`/api/v1/namespaces/${encodeURIComponent(ns)}/availability`),\n };\n}\n","/**\n * Shared store-interaction core for the two publish front-ends — the curator\n * sidecar flow (`source manifest publish`) and the first-party library flow\n * (`library publish`). Both differ only in their git side-effects + how they\n * resolve the source repo; the store orchestration below (register → sync →\n * candidates → per-asset preview+publish) is identical.\n *\n * The store REST surface is reached through the injectable {@link PublisherClient}\n * so the orchestration stays unit/integration-testable without a live store.\n *\n * @docLink cli/commands/source#manifest-publish\n */\n\nimport type { SkPublishManifest } from \"@skaile/workspaces/core\";\nimport { logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\nimport type { PublisherClient } from \"../store-publisher.ts\";\n\n/**\n * One-line rendering of a namespace-availability probe for a `--dry-run` plan.\n * The `message` is store-authored (identical to what a real publish would echo)\n * — we only prepend a status glyph so the reader sees green/amber/red at a\n * glance without the CLI re-deriving any authorization logic.\n */\nexport function formatNamespaceAvailability(a: {\n status: \"owned-by-you\" | \"claimable-by-you\" | \"reserved\" | \"available\";\n message: string;\n}): string {\n switch (a.status) {\n case \"owned-by-you\":\n case \"available\":\n return `${S.ok(\"✓\")} ${a.message}`;\n case \"claimable-by-you\":\n return `${S.warn(\"!\")} ${a.message}`;\n default:\n return `${S.err(\"✗\")} ${a.message}`;\n }\n}\n\n/**\n * Preflight the target namespace against the store's availability probe BEFORE a\n * publish does any irreversible work (a public git push). Returns `{ ok: false }`\n * with a guided message for `reserved` (not yours) and `claimable-by-you` (must\n * claim first) — the two states a real publish would reject — so the caller can\n * abort with actionable guidance instead of a raw 422 after pushing bytes.\n *\n * The probe is advisory: any failure (offline, older store) returns `{ ok: true }`\n * so the store stays the authority and a valid publish is never blocked.\n */\nexport async function preflightNamespace(\n client: PublisherClient,\n namespace: string,\n): Promise<{ ok: boolean; message?: string }> {\n let a: Awaited<ReturnType<PublisherClient[\"namespaceAvailability\"]>>;\n try {\n a = await client.namespaceAvailability(namespace);\n } catch {\n return { ok: true };\n }\n switch (a.status) {\n case \"owned-by-you\":\n case \"available\":\n return { ok: true };\n case \"claimable-by-you\":\n return {\n ok: false,\n message:\n `@${namespace} isn't yours yet — claim it in the store first` +\n `${a.claimMethod ? ` (${a.claimMethod})` : \"\"}, then re-run. ${a.message}`,\n };\n default: // reserved, or any unrecognized future status (fail safe → block)\n return { ok: false, message: `Cannot publish under @${namespace} — ${a.message}` };\n }\n}\n\n/** One candidate row shape the matcher operates on (kind + name are the key). */\ninterface CandidateLike {\n kind: string;\n name: string;\n}\n\n/**\n * Keep only candidates whose `(kind, name)` pair is declared in the manifest.\n * The backend may merge extra assets from the base repo into the candidate\n * list; a publish only touches what the manifest curated/declared.\n */\nexport function matchCandidatesToManifest<T extends CandidateLike>(\n candidates: T[],\n manifest: SkPublishManifest,\n): T[] {\n const wanted = new Set((manifest.assets ?? []).map((a) => `${a.kind}:${a.name}`));\n return candidates.filter((c) => wanted.has(`${c.kind}:${c.name}`));\n}\n\n/** A canonical ref string `kind:@publisher/name[#version]` for reporting. */\nexport function refFor(kind: string, publisher: string, name: string, version?: string): string {\n const base = `${kind}:@${publisher}/${name}`;\n return version ? `${base}#${version}` : base;\n}\n\n/** The bare asset name from a `kind:@publisher/name#version` ref or a plain name. */\nexport function bareName(ref: string): string {\n const afterKind = ref.includes(\":\") ? ref.slice(ref.indexOf(\":\") + 1) : ref;\n const afterScope = afterKind.includes(\"/\")\n ? afterKind.slice(afterKind.indexOf(\"/\") + 1)\n : afterKind;\n return afterScope.split(\"#\")[0];\n}\n\n/**\n * Poll a job until it leaves `running` or the deadline passes. Returns the last\n * observed state — the caller MUST treat a still-`running` result as a timeout\n * (not success), since it means the deadline was hit before the job finished.\n */\nexport async function pollJob(\n client: PublisherClient,\n jobId: string,\n intervalMs = 1_500,\n timeoutMs = 60_000,\n): Promise<{ status: string; items?: Array<{ label: string; status: string; error?: string }> }> {\n const deadline = Date.now() + timeoutMs;\n let job = await client.jobGet(jobId);\n while (job.status === \"running\" && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, intervalMs));\n job = await client.jobGet(jobId);\n }\n return job;\n}\n\n/**\n * True when a `sourcesAdd` rejection is a duplicate-URL conflict (the source is\n * already registered) — the only error the publish flow recovers from by looking\n * the existing row up. Every other failure (auth, 5xx, network) must propagate.\n */\nexport function isDupSourceError(err: unknown): boolean {\n const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();\n return /\\b409\\b|conflict|duplicate|already exists|already registered|unique/.test(msg);\n}\n\n/**\n * Register + sync the source, then publish its curated/declared candidates —\n * the store-side steps shared by both publish front-ends. Git side-effects (the\n * sidecar push, or the library commit+push) happen in the caller *before* this;\n * this function is purely store interaction.\n *\n * The sidecar front-end passes `sidecar` (so `sourcesAdd` carries the sidecar\n * pin); the library front-end omits it (the source repo IS the manifest host).\n * `assetName`, when set, narrows publication to the single candidate of that\n * name. Fatal store states (`sourcesAdd` non-dup failure) surface; sync failures\n * and empty candidate sets `process.exit(1)` with the same messages as before.\n */\nexport async function publishToStore(opts: {\n sourceUrl: string;\n ref: string;\n sidecar?: { url: string; ref: string };\n manifest: SkPublishManifest;\n assetName?: string;\n client: PublisherClient;\n}): Promise<{ published: string[] }> {\n const { sourceUrl, ref, sidecar, manifest, assetName, client: pub } = opts;\n\n let sourceId: string;\n try {\n const added = await pub.sourcesAdd({\n url: sourceUrl,\n ref,\n ...(sidecar ? { sidecarUrl: sidecar.url, sidecarRef: sidecar.ref } : {}),\n // Publish under the manifest's declared namespace; the store resolves a\n // claimed Publisher when it differs from the caller's login, else defaults\n // to `@<username>`. Omitted when the manifest carries no publisher.\n ...(manifest.publisher ? { namespace: manifest.publisher } : {}),\n });\n sourceId = added.id;\n } catch (err) {\n // Only a duplicate-url conflict is recoverable (source already registered);\n // auth/5xx/network failures must surface, not silently reuse a stale row.\n if (!isDupSourceError(err)) throw err;\n const rows = await pub.sourcesList();\n const found = rows.find((r) => r.url === sourceUrl);\n if (!found) {\n throw new Error(\n `Source ${sourceUrl} looked already-registered but no owned row matched: ` +\n `${err instanceof Error ? err.message : String(err)}`,\n );\n }\n sourceId = found.id;\n }\n\n const { jobId } = await pub.sourceSync(sourceId);\n const job = await pollJob(pub, jobId);\n if (job.status === \"failed\" || job.status === \"cancelled\") {\n const failed = (job.items ?? []).filter((i) => i.status === \"failed\");\n for (const i of failed) logErr(`sync: ${i.label}: ${i.error ?? \"failed\"}`);\n logErr(`Source sync ${job.status}.`);\n process.exit(1);\n }\n // A still-`running` job means the poll deadline was hit — do NOT proceed on an\n // unfinished sync (it would read incomplete candidates).\n if (job.status === \"running\") {\n logErr(\"Source sync timed out before completing — re-run `publish`, or check the store.\");\n process.exit(1);\n }\n\n let candidates = matchCandidatesToManifest(await pub.sourceCandidates(sourceId), manifest);\n if (assetName) candidates = candidates.filter((c) => c.name === assetName);\n if (candidates.length === 0) {\n logWarn(\"No candidates discovered — check the manifest and the source ref.\");\n process.exit(1);\n }\n\n const published: string[] = [];\n for (const c of candidates) {\n try {\n const preview = await pub.assetPreview(c.id);\n const res = await pub.assetPublish(c.id, { ref, files: preview.discoveredFiles });\n // Publish is async — wait for the job so we only report refs that actually\n // landed, not ones whose import is still in flight or about to fail.\n if (res.jobId) {\n const pubJob = await pollJob(pub, res.jobId);\n if (pubJob.status !== \"succeeded\") {\n const errs = (pubJob.items ?? [])\n .filter((i) => i.status === \"failed\")\n .map((i) => i.error)\n .filter(Boolean);\n logWarn(\n `Publish of ${c.kind}:${c.name} did not succeed (${pubJob.status})` +\n (errs.length ? `: ${errs.join(\"; \")}` : \"\"),\n );\n continue;\n }\n }\n published.push(refFor(c.kind, preview.candidate.publisherNamespace, c.name, c.version));\n } catch (err) {\n logWarn(\n `Failed to publish ${c.kind}:${c.name}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n logOk(`Published ${published.length} asset(s):`);\n for (const r of published) logInfo(` ${r}`);\n return { published };\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  import { resolveAuthRef } from './chunk-ZNIHTT22.js';
2
2
  import { pluginRegistry } from './chunk-6E6PKKAD.js';
3
3
  import { computeStimulus } from './chunk-IFGTRL2I.js';
4
- import { getConsumedOutputSchema, validateConsumedNodeOutput, resolveNodeBindings, computeFlowStateFromSnapshots, interpolateNodeInstruction } from './chunk-4O2RAXKJ.js';
5
- import { parseFlowDefinition } from './chunk-OEGHKO5N.js';
6
- import { renderStimulusPrompt } from './chunk-FKBQRV4J.js';
7
- import { flowDefaults, isAgentNode, isGateNode, nodeRequiresApproval, isSubFlowNode, isFunctionNode, nodeIsOptional, isActiveRuntimeNode, nodeLabel, nodeInstruction, nodeAssets } from './chunk-4QROZZ5Z.js';
4
+ import { getConsumedOutputSchema, validateConsumedNodeOutput, resolveNodeBindings, computeFlowStateFromSnapshots, availableRouterFrontier, evaluateRouterSelection, routerSelectionOutput, planRouterSkips, unsettledRouterBranchIds, interpolateNodeInstruction, persistedRouterSelection } from './chunk-E4AVJMOJ.js';
5
+ import { parseFlowDefinition } from './chunk-XJ74XFIZ.js';
6
+ import { renderStimulusPrompt } from './chunk-SCR3WGW7.js';
7
+ import { flowDefaults, isAgentNode, isGateNode, nodeRequiresApproval, isSubFlowNode, isFunctionNode, nodeIsOptional, isRouterNode, isActiveRuntimeNode, nodeLabel, nodeInstruction, nodeAssets } from './chunk-TUYN2HDT.js';
8
8
  import { portableSpawn } from './chunk-P43HBWKK.js';
9
9
  import { withFsDeadline, tryWithFsDeadline, FsDeadlineError, fsDeadlineMs } from './chunk-DYMWJAL4.js';
10
10
  import { createLogger } from './chunk-7GOCNYUV.js';
@@ -7566,6 +7566,10 @@ function prepareExecutionSnapshot(flowDef, execution) {
7566
7566
  const snapshot = cloned.data;
7567
7567
  for (const [nodeId, node] of Object.entries(snapshot.nodes ?? {})) {
7568
7568
  if (node.status !== "complete") continue;
7569
+ const definitionNode = flowDef.nodes.find(({ id }) => id === nodeId);
7570
+ if (definitionNode && isRouterNode(definitionNode) && !persistedRouterSelection(definitionNode, node)) {
7571
+ throw new Error(`FlowAdapter: invalid execution output for router node ${nodeId}`);
7572
+ }
7569
7573
  const validation = validateConsumedNodeOutput(flowDef, nodeId, node.output?.fields);
7570
7574
  if (!validation.valid) {
7571
7575
  throw new Error(
@@ -8575,7 +8579,8 @@ var FlowAdapter = class extends AbstractConnector {
8575
8579
  }
8576
8580
  /**
8577
8581
  * Drain runtime-owned nodes in definition order until only agent work or a human decision
8578
- * remains. Function nodes use NodeExecutor, gates park, and sub-flows delegate to the host.
8582
+ * remains. Routers select branches, function nodes use NodeExecutor, gates park, and sub-flows
8583
+ * delegate to the host.
8579
8584
  */
8580
8585
  async drainRuntimeNodes(handle) {
8581
8586
  return this.drainAvailableRuntimeNodes(handle, true);
@@ -8588,17 +8593,18 @@ var FlowAdapter = class extends AbstractConnector {
8588
8593
  async executeAvailableFunctionNodes(handle) {
8589
8594
  return this.drainAvailableRuntimeNodes(handle, false);
8590
8595
  }
8591
- async drainAvailableRuntimeNodes(handle, includeGates) {
8596
+ async drainAvailableRuntimeNodes(handle, includeRoutersAndGates) {
8592
8597
  const advancedSubFlows = /* @__PURE__ */ new Set();
8593
8598
  while (true) {
8594
8599
  const state = this.s(handle);
8595
8600
  if (state.execution.status === "cancelled" || state.execution.status === "failed") break;
8601
+ if (includeRoutersAndGates && this.settleAvailableRouters(handle)) continue;
8596
8602
  const node = state.flowDef.nodes.find((candidate) => {
8597
8603
  const status = state.execution.nodes[candidate.id]?.status;
8598
8604
  if (isSubFlowNode(candidate) && !advancedSubFlows.has(candidate.id) && (status === "available" || status === "running")) {
8599
8605
  return true;
8600
8606
  }
8601
- return (isFunctionNode(candidate) || includeGates && isGateNode(candidate)) && status === "available";
8607
+ return (isFunctionNode(candidate) || includeRoutersAndGates && isGateNode(candidate)) && status === "available";
8602
8608
  });
8603
8609
  if (!node) break;
8604
8610
  if (isGateNode(node)) {
@@ -8812,6 +8818,110 @@ var FlowAdapter = class extends AbstractConnector {
8812
8818
  return this.getExecution(handle);
8813
8819
  }
8814
8820
  // ── Private helpers ──
8821
+ /** Settle one decidable router per source ownership component before runtime side effects. */
8822
+ settleAvailableRouters(handle) {
8823
+ const state = this.s(handle);
8824
+ const snapshots = snapshotMap(state.execution);
8825
+ const settlements = [];
8826
+ const availableRouterSnapshots = new Map(snapshots);
8827
+ const computed = computeFlowStateFromSnapshots(state.flowDef, snapshots);
8828
+ for (const nodeId of computed.available) {
8829
+ const execution = availableRouterSnapshots.get(nodeId);
8830
+ if (execution && execution.status !== "available") {
8831
+ availableRouterSnapshots.set(nodeId, { ...execution, status: "available" });
8832
+ }
8833
+ }
8834
+ const frontier = availableRouterFrontier(state.flowDef, availableRouterSnapshots);
8835
+ for (const node of frontier) {
8836
+ const resolution = evaluateRouterSelection(state.flowDef, node, snapshots);
8837
+ if ("unresolved" in resolution) continue;
8838
+ settlements.push({ routerNodeId: node.id, selectedTarget: resolution.selectedTarget });
8839
+ }
8840
+ if (settlements.length === 0) return false;
8841
+ const preparedSettlements = settlements.map((settlement) => {
8842
+ const output = routerSelectionOutput(settlement.selectedTarget);
8843
+ return {
8844
+ settlement,
8845
+ output,
8846
+ validation: validateConsumedNodeOutput(
8847
+ state.flowDef,
8848
+ settlement.routerNodeId,
8849
+ output.fields
8850
+ )
8851
+ };
8852
+ });
8853
+ const validSettlements = preparedSettlements.flatMap(
8854
+ ({ settlement, validation }) => validation.valid ? [settlement] : []
8855
+ );
8856
+ const settlementPlan = [...validSettlements];
8857
+ let skippedNodeIds = [];
8858
+ if (settlementPlan.length > 0) {
8859
+ while (true) {
8860
+ skippedNodeIds = planRouterSkips(state.flowDef, snapshots, settlementPlan);
8861
+ const settledIds = new Set(settlementPlan.map(({ routerNodeId }) => routerNodeId));
8862
+ const losingRouters = skippedNodeIds.flatMap((nodeId) => {
8863
+ const node = state.flowDef.nodes.find(({ id }) => id === nodeId);
8864
+ return node && isRouterNode(node) && !settledIds.has(node.id) ? [node] : [];
8865
+ });
8866
+ if (losingRouters.length === 0) break;
8867
+ settlementPlan.push(
8868
+ ...losingRouters.map(({ id }) => ({ routerNodeId: id, selectedTarget: null }))
8869
+ );
8870
+ }
8871
+ }
8872
+ const settledAt = now();
8873
+ this.mutate(
8874
+ handle,
8875
+ (current) => {
8876
+ for (const prepared of preparedSettlements) {
8877
+ const { settlement, output, validation } = prepared;
8878
+ const execution = current.execution.nodes[settlement.routerNodeId];
8879
+ assertLegal(execution, `node not in execution: ${settlement.routerNodeId}`);
8880
+ assertLegal(
8881
+ execution.status === "available",
8882
+ `cannot resolve router node ${settlement.routerNodeId}: status is ${execution.status}`
8883
+ );
8884
+ if (!validation.valid) {
8885
+ const error = {
8886
+ message: `Router node ${settlement.routerNodeId} failed: output does not match its consumed schema: ${validation.issues.join("; ")}`,
8887
+ recoverable: false,
8888
+ at: settledAt
8889
+ };
8890
+ current.execution.nodes[settlement.routerNodeId] = {
8891
+ ...execution,
8892
+ status: "failed",
8893
+ startedAt: execution.startedAt ?? settledAt,
8894
+ completedAt: settledAt,
8895
+ output,
8896
+ error,
8897
+ errorHistory: [...execution.errorHistory, error]
8898
+ };
8899
+ continue;
8900
+ }
8901
+ current.execution.nodes[settlement.routerNodeId] = {
8902
+ ...execution,
8903
+ status: "complete",
8904
+ startedAt: execution.startedAt ?? settledAt,
8905
+ completedAt: settledAt,
8906
+ output
8907
+ };
8908
+ }
8909
+ for (const skippedNodeId of skippedNodeIds) {
8910
+ const execution = current.execution.nodes[skippedNodeId];
8911
+ if (!execution || execution.status !== "not_started" && execution.status !== "available") {
8912
+ continue;
8913
+ }
8914
+ current.execution.nodes[skippedNodeId] = {
8915
+ ...execution,
8916
+ status: "skipped",
8917
+ completedAt: settledAt
8918
+ };
8919
+ }
8920
+ },
8921
+ false
8922
+ );
8923
+ return true;
8924
+ }
8815
8925
  s(handle) {
8816
8926
  return handle.state;
8817
8927
  }
@@ -8855,13 +8965,15 @@ var FlowAdapter = class extends AbstractConnector {
8855
8965
  recompute(s) {
8856
8966
  const snapshots = snapshotMap(s.execution);
8857
8967
  const computed = computeFlowStateFromSnapshots(s.flowDef, snapshots);
8968
+ const routerGatedNodes = unsettledRouterBranchIds(s.flowDef, snapshots);
8858
8969
  const nodes = nodeExecutionRecord(Object.entries(s.execution.nodes));
8859
8970
  for (const ns of computed.nodes) {
8860
8971
  const existing = nodes[ns.nodeId];
8861
8972
  if (!existing) continue;
8862
8973
  if (existing.status === "not_started" || existing.status === "available") {
8974
+ const definitionNode = s.flowDef.nodes.find(({ id }) => id === ns.nodeId);
8863
8975
  const hasFailedPreconditions = (ns.failedPreconditions?.length ?? 0) > 0;
8864
- const status = existing.status === "available" && ns.status === "not_started" && !hasFailedPreconditions ? "available" : ns.status;
8976
+ const status = existing.status === "available" && ns.status === "not_started" && !hasFailedPreconditions && !routerGatedNodes.has(ns.nodeId) && !(definitionNode && isRouterNode(definitionNode)) ? "available" : ns.status;
8865
8977
  nodes[ns.nodeId] = {
8866
8978
  ...existing,
8867
8979
  status,
@@ -8955,8 +9067,9 @@ Artifacts: ${output.artifacts.map((a) => a.uri).join(", ")}` : "";
8955
9067
  Concerns: ${output.concerns.join("; ")}` : "";
8956
9068
  const predecessor = s.flowDef.nodes.find((n) => n.id === depId);
8957
9069
  const label = predecessor ? nodeLabel(predecessor) : depId;
9070
+ const summary = predecessor && isRouterNode(predecessor) ? routerSelectionHandoffSummary(predecessor, exec) ?? output.summary : output.summary;
8958
9071
  handoff.push(`### ${label} (${exec?.status})
8959
- ${output.summary}${artifacts}${concerns}`);
9072
+ ${summary}${artifacts}${concerns}`);
8960
9073
  }
8961
9074
  sections.push(
8962
9075
  `## Upstream handoff
@@ -8969,6 +9082,11 @@ ${handoff.length > 0 ? handoff.join("\n\n") : "(no prior context)"}`
8969
9082
  function flowPredecessors(flowDef, nodeId) {
8970
9083
  return flowDef.edges.filter((e) => e.target === nodeId && e.type === "flow").map((e) => e.source);
8971
9084
  }
9085
+ function routerSelectionHandoffSummary(router, execution) {
9086
+ const selection = persistedRouterSelection(router, execution);
9087
+ if (!selection) return void 0;
9088
+ return selection.selectedTarget === null ? "Router completed without selecting a target." : `Router selected ${selection.selectedTarget}.`;
9089
+ }
8972
9090
  function functionNodeOutput(node, result) {
8973
9091
  const capturedFields = [];
8974
9092
  for (const channel of ["stdout", "stderr"]) {
@@ -9058,5 +9176,5 @@ function createConnector() {
9058
9176
  }
9059
9177
 
9060
9178
  export { AbstractConnector, BUILTIN_CONNECTOR_CATALOG, BoxConnector, ConnectorFieldMissingError, ConnectorManager, ConnectorStartupError, DeployConnector, DevServerConnector, FlowAdapter, GitConnector, GmailConnector, GoogleDriveConnector, LocalConnector, LogBuffer, ManagedGitconfigCollisionError, MattermostConnector, MemoryConnector, MinIOConnector, PortPool, PostgresConnector, S3Connector, SQLiteConnector, SessionInlineSubFlowRunner, SessionNodeExecutor, SharePointConnector, StaticServerConnector, TunnelConnector, WebDAVConnector, XStateConnector, XStateStoreConnector, __test, atomicReplaceCredential, buildConnectorPromptSection, buildSdkConnectorTools, buildSdkFlowTools, createConnector, createConnector10, createConnector11, createConnector12, createConnector13, createConnector14, createConnector15, createConnector16, createConnector17, createConnector18, createConnector19, createConnector2, createConnector20, createConnector3, createConnector4, createConnector5, createConnector6, createConnector7, createConnector8, createConnector9, createFsWatcher, createWorktree, defaultSpawn, ensureDirMode, ensureFleetMounted, findGitRoot, findMissingPackages, getConnector, installNpmPackages, isFleetManaged, isPackageResolvable, listConnectors, listWorktrees, readGitSyncStatus, registerBuiltinConnectors, removeMountBlock, renderCredentialHelperScript, tryGetConnector, worktreeRegistry, writeHelperScript, writeMountBlock };
9061
- //# sourceMappingURL=chunk-EEHOMCRU.js.map
9062
- //# sourceMappingURL=chunk-EEHOMCRU.js.map
9179
+ //# sourceMappingURL=chunk-HVQWLYZB.js.map
9180
+ //# sourceMappingURL=chunk-HVQWLYZB.js.map