@promptbook/website-crawler 0.112.0-71 → 0.112.0-73

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 (195) hide show
  1. package/esm/index.es.js +1425 -799
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/src/book-3.0/Book.d.ts +6 -0
  4. package/esm/src/book-components/Chat/save/_common/chatExportRendering.d.ts +28 -0
  5. package/esm/src/book-components/Chat/save/_common/getPromptbookExportBranding.d.ts +18 -0
  6. package/esm/src/book-components/Chat/save/html/htmlSaveFormatDefinition.d.ts +1 -1
  7. package/esm/src/book-components/Chat/save/html/htmlSaveFormatDefinition.test.d.ts +1 -0
  8. package/esm/src/book-components/Chat/save/index.d.ts +4 -4
  9. package/esm/src/book-components/Chat/save/markdown/mdSaveFormatDefinition.d.ts +1 -1
  10. package/esm/src/book-components/Chat/save/markdown/mdSaveFormatDefinition.test.d.ts +1 -0
  11. package/esm/src/book-components/Chat/save/pdf/buildChatPdf.d.ts +3 -2
  12. package/esm/src/book-components/Chat/save/pdf/pdfSaveFormatDefinition.d.ts +2 -2
  13. package/esm/src/book-components/Chat/save/pdf/pdfSaveFormatDefinition.test.d.ts +1 -0
  14. package/esm/src/book-components/Chat/save/react/reactSaveFormatDefinition.test.d.ts +1 -0
  15. package/esm/src/book-components/Chat/utils/getToolCallChipletInfo.test.d.ts +1 -0
  16. package/esm/src/book-components/Chat/utils/renderMarkdown.d.ts +26 -0
  17. package/esm/src/cli/cli-commands/agent/agentRunCliOptions.d.ts +14 -2
  18. package/esm/src/cli/cli-commands/agent/initializeAgentRunnerCommand.d.ts +2 -0
  19. package/esm/src/cli/cli-commands/common/handleActionErrors.d.ts +9 -4
  20. package/esm/src/cli/cli-commands/run/prepareRunCommandResources.d.ts +20 -0
  21. package/esm/src/cli/cli-commands/run/resolveRunInputParameters.d.ts +12 -0
  22. package/esm/src/cli/cli-commands/run/runCommandAction.d.ts +21 -0
  23. package/esm/src/cli/cli-commands/run/runPipelineExecution.d.ts +14 -0
  24. package/esm/src/cli/cli-commands/run.d.ts +1 -1
  25. package/esm/src/conversion/parsePipeline/applyPipelineHead.d.ts +8 -0
  26. package/esm/src/conversion/parsePipeline/createInitialPipelineJson.d.ts +8 -0
  27. package/esm/src/conversion/parsePipeline/createUniqueSectionNameResolver.d.ts +14 -0
  28. package/esm/src/conversion/parsePipeline/defineParameter.d.ts +8 -0
  29. package/esm/src/conversion/parsePipeline/extractPipelineDescription.d.ts +6 -0
  30. package/esm/src/conversion/parsePipeline/finalizeParsedPipeline.d.ts +8 -0
  31. package/esm/src/conversion/parsePipeline/getPipelineIdentification.d.ts +7 -0
  32. package/esm/src/conversion/parsePipeline/parsePreparedPipelineSections.d.ts +18 -0
  33. package/esm/src/conversion/parsePipeline/preparePipelineString.d.ts +8 -0
  34. package/esm/src/conversion/parsePipeline/processPipelineSection.d.ts +9 -0
  35. package/esm/src/conversion/pipelineJsonToString/appendMarkdownBlock.d.ts +7 -0
  36. package/esm/src/conversion/pipelineJsonToString/createPipelineCommands.d.ts +7 -0
  37. package/esm/src/conversion/pipelineJsonToString/createPipelineIntroduction.d.ts +8 -0
  38. package/esm/src/conversion/pipelineJsonToString/createTaskSerialization.d.ts +23 -0
  39. package/esm/src/conversion/pipelineJsonToString/stringifyCommands.d.ts +7 -0
  40. package/esm/src/conversion/pipelineJsonToString/stringifyTask.d.ts +8 -0
  41. package/esm/src/conversion/pipelineJsonToString.test.d.ts +1 -0
  42. package/esm/src/execution/createPipelineExecutor/executeSingleAttempt.d.ts +31 -0
  43. package/esm/src/execution/createPipelineExecutor/handleAttemptFailure.d.ts +40 -0
  44. package/esm/src/execution/createPipelineExecutor/reportPromptExecution.d.ts +34 -0
  45. package/esm/src/execution/resolveTaskTldr.d.ts +32 -0
  46. package/esm/src/execution/resolveTaskTldr.test.d.ts +1 -0
  47. package/esm/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +22 -63
  48. package/esm/src/llm-providers/agent/AgentLlmExecutionToolsAgentKitRunner.d.ts +51 -0
  49. package/esm/src/llm-providers/agent/AgentLlmExecutionToolsOpenAiAssistantRunner.d.ts +43 -0
  50. package/esm/src/llm-providers/agent/AgentLlmExecutionToolsPromptPreparer.d.ts +41 -0
  51. package/esm/src/llm-providers/agent/emitAgentLlmExecutionToolsAssistantPreparationProgress.d.ts +26 -0
  52. package/esm/src/llm-providers/openai/OpenAiAgentKitExecutionTools.d.ts +16 -93
  53. package/esm/src/llm-providers/openai/OpenAiAgentKitExecutionToolsInputBuilder.d.ts +41 -0
  54. package/esm/src/llm-providers/openai/OpenAiAgentKitExecutionToolsOutputTypeMapper.d.ts +56 -0
  55. package/esm/src/llm-providers/openai/OpenAiAgentKitExecutionToolsToolBuilder.d.ts +99 -0
  56. package/esm/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +24 -120
  57. package/esm/src/llm-providers/openai/OpenAiAssistantExecutionToolsProgressReporter.d.ts +62 -0
  58. package/esm/src/llm-providers/openai/OpenAiAssistantExecutionToolsPromptBuilder.d.ts +29 -0
  59. package/esm/src/llm-providers/openai/OpenAiAssistantExecutionToolsStreamRunner.d.ts +63 -0
  60. package/esm/src/llm-providers/openai/OpenAiAssistantExecutionToolsToolRunner.d.ts +89 -0
  61. package/esm/src/llm-providers/openai/OpenAiCompatibleExecutionTools.d.ts +9 -28
  62. package/esm/src/llm-providers/openai/OpenAiCompatibleModelCatalog.d.ts +31 -0
  63. package/esm/src/llm-providers/openai/OpenAiCompatibleNonChatPromptCaller.d.ts +57 -0
  64. package/esm/src/llm-providers/openai/OpenAiCompatibleRequestManager.d.ts +29 -0
  65. package/esm/src/llm-providers/openai/OpenAiVectorStoreFileBatchHandler.d.ts +51 -0
  66. package/esm/src/llm-providers/openai/OpenAiVectorStoreFileBatchPoller.d.ts +75 -0
  67. package/esm/src/llm-providers/openai/OpenAiVectorStoreHandler.d.ts +1 -98
  68. package/esm/src/llm-providers/openai/OpenAiVectorStoreKnowledgeSourcePreparer.d.ts +44 -0
  69. package/esm/src/llm-providers/openai/utils/OpenAiCompatibleChatProgressReporter.d.ts +86 -0
  70. package/esm/src/llm-providers/openai/utils/OpenAiCompatibleChatPromptBuilder.d.ts +57 -0
  71. package/esm/src/llm-providers/openai/utils/OpenAiCompatibleChatToolCaller.d.ts +57 -0
  72. package/esm/src/remote-server/startRemoteServer/RemoteServerRuntime.d.ts +14 -0
  73. package/esm/src/remote-server/startRemoteServer/SocketResponse.d.ts +9 -0
  74. package/esm/src/remote-server/startRemoteServer/StartRemoteServerConfiguration.d.ts +18 -0
  75. package/esm/src/remote-server/startRemoteServer/createRemoteServerExpressApp.d.ts +7 -0
  76. package/esm/src/remote-server/startRemoteServer/createRemoteServerHandle.d.ts +11 -0
  77. package/esm/src/remote-server/startRemoteServer/createSocketServer.d.ts +9 -0
  78. package/esm/src/remote-server/startRemoteServer/getExecutionToolsFromIdentification.d.ts +12 -0
  79. package/esm/src/remote-server/startRemoteServer/registerBookRoutes.d.ts +7 -0
  80. package/esm/src/remote-server/startRemoteServer/registerExecutionRoutes.d.ts +7 -0
  81. package/esm/src/remote-server/startRemoteServer/registerListModelsSocketHandler.d.ts +8 -0
  82. package/esm/src/remote-server/startRemoteServer/registerLoginRoute.d.ts +7 -0
  83. package/esm/src/remote-server/startRemoteServer/registerNotFoundRoute.d.ts +7 -0
  84. package/esm/src/remote-server/startRemoteServer/registerOpenAiCompatibleChatCompletionsRoute.d.ts +7 -0
  85. package/esm/src/remote-server/startRemoteServer/registerOpenApiRoutes.d.ts +7 -0
  86. package/esm/src/remote-server/startRemoteServer/registerPreparePipelineSocketHandler.d.ts +8 -0
  87. package/esm/src/remote-server/startRemoteServer/registerPromptSocketHandler.d.ts +8 -0
  88. package/esm/src/remote-server/startRemoteServer/registerRemoteServerHttpRoutes.d.ts +7 -0
  89. package/esm/src/remote-server/startRemoteServer/registerRemoteServerSocketHandlers.d.ts +8 -0
  90. package/esm/src/remote-server/startRemoteServer/registerServerIndexRoute.d.ts +7 -0
  91. package/esm/src/remote-server/startRemoteServer/resolveStartRemoteServerConfiguration.d.ts +8 -0
  92. package/esm/src/remote-server/startRemoteServer/respondToSocketRequest.d.ts +8 -0
  93. package/esm/src/remote-server/startRemoteServer/startListening.d.ts +9 -0
  94. package/esm/src/scrapers/_common/utils/makeKnowledgeSourceHandler.d.ts +14 -1
  95. package/esm/src/utils/serialization/serializeToPromptbookJavascript.d.ts +2 -0
  96. package/esm/src/utils/serialization/serializeToPromptbookJavascript.test.d.ts +1 -0
  97. package/esm/src/version.d.ts +1 -1
  98. package/package.json +2 -2
  99. package/umd/index.umd.js +1425 -799
  100. package/umd/index.umd.js.map +1 -1
  101. package/umd/src/book-3.0/Book.d.ts +6 -0
  102. package/umd/src/book-components/Chat/save/_common/chatExportRendering.d.ts +28 -0
  103. package/umd/src/book-components/Chat/save/_common/getPromptbookExportBranding.d.ts +18 -0
  104. package/umd/src/book-components/Chat/save/html/htmlSaveFormatDefinition.d.ts +1 -1
  105. package/umd/src/book-components/Chat/save/html/htmlSaveFormatDefinition.test.d.ts +1 -0
  106. package/umd/src/book-components/Chat/save/index.d.ts +4 -4
  107. package/umd/src/book-components/Chat/save/markdown/mdSaveFormatDefinition.d.ts +1 -1
  108. package/umd/src/book-components/Chat/save/markdown/mdSaveFormatDefinition.test.d.ts +1 -0
  109. package/umd/src/book-components/Chat/save/pdf/buildChatPdf.d.ts +3 -2
  110. package/umd/src/book-components/Chat/save/pdf/pdfSaveFormatDefinition.d.ts +2 -2
  111. package/umd/src/book-components/Chat/save/pdf/pdfSaveFormatDefinition.test.d.ts +1 -0
  112. package/umd/src/book-components/Chat/save/react/reactSaveFormatDefinition.test.d.ts +1 -0
  113. package/umd/src/book-components/Chat/utils/getToolCallChipletInfo.test.d.ts +1 -0
  114. package/umd/src/book-components/Chat/utils/renderMarkdown.d.ts +26 -0
  115. package/umd/src/cli/cli-commands/agent/agentRunCliOptions.d.ts +14 -2
  116. package/umd/src/cli/cli-commands/agent/initializeAgentRunnerCommand.d.ts +2 -0
  117. package/umd/src/cli/cli-commands/common/handleActionErrors.d.ts +9 -4
  118. package/umd/src/cli/cli-commands/run/prepareRunCommandResources.d.ts +20 -0
  119. package/umd/src/cli/cli-commands/run/resolveRunInputParameters.d.ts +12 -0
  120. package/umd/src/cli/cli-commands/run/runCommandAction.d.ts +21 -0
  121. package/umd/src/cli/cli-commands/run/runPipelineExecution.d.ts +14 -0
  122. package/umd/src/cli/cli-commands/run.d.ts +1 -1
  123. package/umd/src/conversion/parsePipeline/applyPipelineHead.d.ts +8 -0
  124. package/umd/src/conversion/parsePipeline/createInitialPipelineJson.d.ts +8 -0
  125. package/umd/src/conversion/parsePipeline/createUniqueSectionNameResolver.d.ts +14 -0
  126. package/umd/src/conversion/parsePipeline/defineParameter.d.ts +8 -0
  127. package/umd/src/conversion/parsePipeline/extractPipelineDescription.d.ts +6 -0
  128. package/umd/src/conversion/parsePipeline/finalizeParsedPipeline.d.ts +8 -0
  129. package/umd/src/conversion/parsePipeline/getPipelineIdentification.d.ts +7 -0
  130. package/umd/src/conversion/parsePipeline/parsePreparedPipelineSections.d.ts +18 -0
  131. package/umd/src/conversion/parsePipeline/preparePipelineString.d.ts +8 -0
  132. package/umd/src/conversion/parsePipeline/processPipelineSection.d.ts +9 -0
  133. package/umd/src/conversion/pipelineJsonToString/appendMarkdownBlock.d.ts +7 -0
  134. package/umd/src/conversion/pipelineJsonToString/createPipelineCommands.d.ts +7 -0
  135. package/umd/src/conversion/pipelineJsonToString/createPipelineIntroduction.d.ts +8 -0
  136. package/umd/src/conversion/pipelineJsonToString/createTaskSerialization.d.ts +23 -0
  137. package/umd/src/conversion/pipelineJsonToString/stringifyCommands.d.ts +7 -0
  138. package/umd/src/conversion/pipelineJsonToString/stringifyTask.d.ts +8 -0
  139. package/umd/src/conversion/pipelineJsonToString.test.d.ts +1 -0
  140. package/umd/src/execution/createPipelineExecutor/executeSingleAttempt.d.ts +31 -0
  141. package/umd/src/execution/createPipelineExecutor/handleAttemptFailure.d.ts +40 -0
  142. package/umd/src/execution/createPipelineExecutor/reportPromptExecution.d.ts +34 -0
  143. package/umd/src/execution/resolveTaskTldr.d.ts +32 -0
  144. package/umd/src/execution/resolveTaskTldr.test.d.ts +1 -0
  145. package/umd/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +22 -63
  146. package/umd/src/llm-providers/agent/AgentLlmExecutionToolsAgentKitRunner.d.ts +51 -0
  147. package/umd/src/llm-providers/agent/AgentLlmExecutionToolsOpenAiAssistantRunner.d.ts +43 -0
  148. package/umd/src/llm-providers/agent/AgentLlmExecutionToolsPromptPreparer.d.ts +41 -0
  149. package/umd/src/llm-providers/agent/emitAgentLlmExecutionToolsAssistantPreparationProgress.d.ts +26 -0
  150. package/umd/src/llm-providers/openai/OpenAiAgentKitExecutionTools.d.ts +16 -93
  151. package/umd/src/llm-providers/openai/OpenAiAgentKitExecutionToolsInputBuilder.d.ts +41 -0
  152. package/umd/src/llm-providers/openai/OpenAiAgentKitExecutionToolsOutputTypeMapper.d.ts +56 -0
  153. package/umd/src/llm-providers/openai/OpenAiAgentKitExecutionToolsToolBuilder.d.ts +99 -0
  154. package/umd/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +24 -120
  155. package/umd/src/llm-providers/openai/OpenAiAssistantExecutionToolsProgressReporter.d.ts +62 -0
  156. package/umd/src/llm-providers/openai/OpenAiAssistantExecutionToolsPromptBuilder.d.ts +29 -0
  157. package/umd/src/llm-providers/openai/OpenAiAssistantExecutionToolsStreamRunner.d.ts +63 -0
  158. package/umd/src/llm-providers/openai/OpenAiAssistantExecutionToolsToolRunner.d.ts +89 -0
  159. package/umd/src/llm-providers/openai/OpenAiCompatibleExecutionTools.d.ts +9 -28
  160. package/umd/src/llm-providers/openai/OpenAiCompatibleModelCatalog.d.ts +31 -0
  161. package/umd/src/llm-providers/openai/OpenAiCompatibleNonChatPromptCaller.d.ts +57 -0
  162. package/umd/src/llm-providers/openai/OpenAiCompatibleRequestManager.d.ts +29 -0
  163. package/umd/src/llm-providers/openai/OpenAiVectorStoreFileBatchHandler.d.ts +51 -0
  164. package/umd/src/llm-providers/openai/OpenAiVectorStoreFileBatchPoller.d.ts +75 -0
  165. package/umd/src/llm-providers/openai/OpenAiVectorStoreHandler.d.ts +1 -98
  166. package/umd/src/llm-providers/openai/OpenAiVectorStoreKnowledgeSourcePreparer.d.ts +44 -0
  167. package/umd/src/llm-providers/openai/utils/OpenAiCompatibleChatProgressReporter.d.ts +86 -0
  168. package/umd/src/llm-providers/openai/utils/OpenAiCompatibleChatPromptBuilder.d.ts +57 -0
  169. package/umd/src/llm-providers/openai/utils/OpenAiCompatibleChatToolCaller.d.ts +57 -0
  170. package/umd/src/remote-server/startRemoteServer/RemoteServerRuntime.d.ts +14 -0
  171. package/umd/src/remote-server/startRemoteServer/SocketResponse.d.ts +9 -0
  172. package/umd/src/remote-server/startRemoteServer/StartRemoteServerConfiguration.d.ts +18 -0
  173. package/umd/src/remote-server/startRemoteServer/createRemoteServerExpressApp.d.ts +7 -0
  174. package/umd/src/remote-server/startRemoteServer/createRemoteServerHandle.d.ts +11 -0
  175. package/umd/src/remote-server/startRemoteServer/createSocketServer.d.ts +9 -0
  176. package/umd/src/remote-server/startRemoteServer/getExecutionToolsFromIdentification.d.ts +12 -0
  177. package/umd/src/remote-server/startRemoteServer/registerBookRoutes.d.ts +7 -0
  178. package/umd/src/remote-server/startRemoteServer/registerExecutionRoutes.d.ts +7 -0
  179. package/umd/src/remote-server/startRemoteServer/registerListModelsSocketHandler.d.ts +8 -0
  180. package/umd/src/remote-server/startRemoteServer/registerLoginRoute.d.ts +7 -0
  181. package/umd/src/remote-server/startRemoteServer/registerNotFoundRoute.d.ts +7 -0
  182. package/umd/src/remote-server/startRemoteServer/registerOpenAiCompatibleChatCompletionsRoute.d.ts +7 -0
  183. package/umd/src/remote-server/startRemoteServer/registerOpenApiRoutes.d.ts +7 -0
  184. package/umd/src/remote-server/startRemoteServer/registerPreparePipelineSocketHandler.d.ts +8 -0
  185. package/umd/src/remote-server/startRemoteServer/registerPromptSocketHandler.d.ts +8 -0
  186. package/umd/src/remote-server/startRemoteServer/registerRemoteServerHttpRoutes.d.ts +7 -0
  187. package/umd/src/remote-server/startRemoteServer/registerRemoteServerSocketHandlers.d.ts +8 -0
  188. package/umd/src/remote-server/startRemoteServer/registerServerIndexRoute.d.ts +7 -0
  189. package/umd/src/remote-server/startRemoteServer/resolveStartRemoteServerConfiguration.d.ts +8 -0
  190. package/umd/src/remote-server/startRemoteServer/respondToSocketRequest.d.ts +8 -0
  191. package/umd/src/remote-server/startRemoteServer/startListening.d.ts +9 -0
  192. package/umd/src/scrapers/_common/utils/makeKnowledgeSourceHandler.d.ts +14 -1
  193. package/umd/src/utils/serialization/serializeToPromptbookJavascript.d.ts +2 -0
  194. package/umd/src/utils/serialization/serializeToPromptbookJavascript.test.d.ts +1 -0
  195. package/umd/src/version.d.ts +1 -1
package/esm/index.es.js CHANGED
@@ -27,7 +27,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
27
27
  * @generated
28
28
  * @see https://github.com/webgptorg/promptbook
29
29
  */
30
- const PROMPTBOOK_ENGINE_VERSION = '0.112.0-71';
30
+ const PROMPTBOOK_ENGINE_VERSION = '0.112.0-73';
31
31
  /**
32
32
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
33
33
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -1776,6 +1776,60 @@ function validatePipelineString(pipelineString) {
1776
1776
  }
1777
1777
  // TODO: [🧠][🈴] Where is the best location for this file
1778
1778
 
1779
+ /**
1780
+ * Appends one markdown block to an existing markdown document.
1781
+ *
1782
+ * @private internal utility of `pipelineJsonToString`
1783
+ */
1784
+ function appendMarkdownBlock(pipelineString, markdownBlock) {
1785
+ return spaceTrim$1((block) => `
1786
+ ${block(pipelineString)}
1787
+
1788
+ ${block(markdownBlock)}
1789
+ `);
1790
+ }
1791
+
1792
+ /**
1793
+ * Collects pipeline-level commands in the existing serialization order.
1794
+ *
1795
+ * @private internal utility of `pipelineJsonToString`
1796
+ */
1797
+ function createPipelineCommands(pipelineJson) {
1798
+ const { pipelineUrl, bookVersion, parameters } = pipelineJson;
1799
+ const commands = [];
1800
+ if (pipelineUrl) {
1801
+ commands.push(`PIPELINE URL ${pipelineUrl}`);
1802
+ }
1803
+ if (bookVersion !== `undefined`) {
1804
+ commands.push(`BOOK VERSION ${bookVersion}`);
1805
+ }
1806
+ commands.push(...createParameterCommands(parameters, 'INPUT PARAMETER', ({ isInput }) => isInput));
1807
+ commands.push(...createParameterCommands(parameters, 'OUTPUT PARAMETER', ({ isOutput }) => isOutput));
1808
+ return commands;
1809
+ }
1810
+ /**
1811
+ * Builds one group of parameter commands while preserving the original parameter order.
1812
+ *
1813
+ * @private internal utility of `createPipelineCommands`
1814
+ */
1815
+ function createParameterCommands(parameters, commandPrefix, isIncluded) {
1816
+ return parameters
1817
+ .filter((parameter) => isIncluded(parameter))
1818
+ .map((parameter) => `${commandPrefix} ${parameterJsonToString(parameter)}`);
1819
+ }
1820
+ /**
1821
+ * Converts one parameter JSON declaration to the serialized inline form.
1822
+ *
1823
+ * @private internal utility of `createPipelineCommands`
1824
+ */
1825
+ function parameterJsonToString(parameterJson) {
1826
+ const { name, description } = parameterJson;
1827
+ if (!description) {
1828
+ return `{${name}}`;
1829
+ }
1830
+ return `{${name}} ${description}`;
1831
+ }
1832
+
1779
1833
  /**
1780
1834
  * Prettify the html code
1781
1835
  *
@@ -1789,6 +1843,31 @@ function prettifyMarkdown(content) {
1789
1843
  return (content + `\n\n<!-- Note: Prettier removed from Promptbook -->`);
1790
1844
  }
1791
1845
 
1846
+ /**
1847
+ * Creates the initial markdown heading and description of a pipeline.
1848
+ *
1849
+ * @private internal utility of `pipelineJsonToString`
1850
+ */
1851
+ function createPipelineIntroduction(pipelineJson) {
1852
+ const { title, description } = pipelineJson;
1853
+ const pipelineIntroduction = spaceTrim$1((block) => `
1854
+ # ${title}
1855
+
1856
+ ${block(description || '')}
1857
+ `);
1858
+ // TODO: [main] !!5 This increases size of the bundle and is probably not necessary
1859
+ return prettifyMarkdown(pipelineIntroduction);
1860
+ }
1861
+
1862
+ /**
1863
+ * Renders commands as markdown bullet items.
1864
+ *
1865
+ * @private internal utility of `pipelineJsonToString`
1866
+ */
1867
+ function stringifyCommands(commands) {
1868
+ return commands.map((command) => `- ${command}`).join('\n');
1869
+ }
1870
+
1792
1871
  /**
1793
1872
  * Makes first letter of a string uppercase
1794
1873
  *
@@ -1801,141 +1880,186 @@ function capitalize(word) {
1801
1880
  }
1802
1881
 
1803
1882
  /**
1804
- * Converts promptbook in JSON format to string format
1883
+ * Collects all task-specific serialization details.
1805
1884
  *
1806
- * @deprecated TODO: [🥍][🧠] Backup original files in `PipelineJson` same as in Promptbook.studio
1807
- * @param pipelineJson Promptbook in JSON format (.bookc)
1808
- * @returns Promptbook in string format (.book.md)
1885
+ * @private internal utility of `pipelineJsonToString`
1886
+ */
1887
+ function createTaskSerialization(task) {
1888
+ const taskTypeSerialization = createTaskTypeSerialization(task);
1889
+ return {
1890
+ commands: [
1891
+ ...taskTypeSerialization.commands,
1892
+ ...createJokerCommands(task),
1893
+ ...createPostprocessingCommands(task),
1894
+ ...createExpectationCommands(task),
1895
+ ...createFormatCommands(task),
1896
+ ],
1897
+ contentLanguage: taskTypeSerialization.contentLanguage,
1898
+ };
1899
+ }
1900
+ /**
1901
+ * Collects commands and content language driven by the task type.
1809
1902
  *
1810
- * @public exported from `@promptbook/core`
1903
+ * @private internal utility of `createTaskSerialization`
1811
1904
  */
1812
- function pipelineJsonToString(pipelineJson) {
1813
- const { title, pipelineUrl, bookVersion, description, parameters, tasks } = pipelineJson;
1814
- let pipelineString = spaceTrim$1((block) => `
1815
- # ${title}
1816
-
1817
- ${block(description || '')}
1818
- `);
1905
+ function createTaskTypeSerialization(task) {
1906
+ if (task.taskType === 'PROMPT_TASK') {
1907
+ return {
1908
+ commands: createPromptTaskCommands(task),
1909
+ contentLanguage: 'text',
1910
+ };
1911
+ }
1912
+ if (task.taskType === 'SIMPLE_TASK') {
1913
+ return {
1914
+ commands: ['SIMPLE TEMPLATE'],
1915
+ contentLanguage: 'text',
1916
+ };
1917
+ }
1918
+ if (task.taskType === 'SCRIPT_TASK') {
1919
+ return {
1920
+ commands: ['SCRIPT'],
1921
+ contentLanguage: task.contentLanguage || '',
1922
+ };
1923
+ }
1924
+ if (task.taskType === 'DIALOG_TASK') {
1925
+ return {
1926
+ commands: ['DIALOG'],
1927
+ contentLanguage: 'text',
1928
+ };
1929
+ }
1930
+ return {
1931
+ commands: [],
1932
+ contentLanguage: 'text',
1933
+ };
1934
+ }
1935
+ /**
1936
+ * Collects prompt-task-specific commands.
1937
+ *
1938
+ * @private internal utility of `createTaskSerialization`
1939
+ */
1940
+ function createPromptTaskCommands(task) {
1941
+ const { modelName, modelVariant } = task.modelRequirements || {};
1819
1942
  const commands = [];
1820
- if (pipelineUrl) {
1821
- commands.push(`PIPELINE URL ${pipelineUrl}`);
1943
+ // Note: Do nothing, it is default
1944
+ // commands.push(`PROMPT`);
1945
+ if (modelVariant) {
1946
+ commands.push(`MODEL VARIANT ${capitalize(modelVariant)}`);
1822
1947
  }
1823
- if (bookVersion !== `undefined`) {
1824
- commands.push(`BOOK VERSION ${bookVersion}`);
1948
+ if (modelName) {
1949
+ commands.push(`MODEL NAME \`${modelName}\``);
1825
1950
  }
1826
- // TODO: [main] !!5 This increases size of the bundle and is probably not necessary
1827
- pipelineString = prettifyMarkdown(pipelineString);
1828
- for (const parameter of parameters.filter(({ isInput }) => isInput)) {
1829
- commands.push(`INPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
1951
+ return commands;
1952
+ }
1953
+ /**
1954
+ * Collects joker commands.
1955
+ *
1956
+ * @private internal utility of `createTaskSerialization`
1957
+ */
1958
+ function createJokerCommands(task) {
1959
+ var _a;
1960
+ return ((_a = task.jokerParameterNames) === null || _a === void 0 ? void 0 : _a.map((joker) => `JOKER {${joker}}`)) || [];
1961
+ }
1962
+ /**
1963
+ * Collects postprocessing commands.
1964
+ *
1965
+ * @private internal utility of `createTaskSerialization`
1966
+ */
1967
+ function createPostprocessingCommands(task) {
1968
+ var _a;
1969
+ return ((_a = task.postprocessingFunctionNames) === null || _a === void 0 ? void 0 : _a.map((postprocessingFunctionName) => `POSTPROCESSING \`${postprocessingFunctionName}\``)) || [];
1970
+ }
1971
+ /**
1972
+ * Collects expectation commands.
1973
+ *
1974
+ * @private internal utility of `createTaskSerialization`
1975
+ */
1976
+ function createExpectationCommands(task) {
1977
+ if (!task.expectations) {
1978
+ return [];
1830
1979
  }
1831
- for (const parameter of parameters.filter(({ isOutput }) => isOutput)) {
1832
- commands.push(`OUTPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
1980
+ return Object.entries(task.expectations).flatMap(([unit, expectation]) => createExpectationCommandsForUnit(unit, expectation.min, expectation.max));
1981
+ }
1982
+ /**
1983
+ * Collects expectation commands for a single unit.
1984
+ *
1985
+ * @private internal utility of `createTaskSerialization`
1986
+ */
1987
+ function createExpectationCommandsForUnit(unit, min, max) {
1988
+ if (min === max) {
1989
+ return [`EXPECT EXACTLY ${min} ${formatExpectationUnit(unit, min)}`];
1833
1990
  }
1834
- pipelineString = spaceTrim$1((block) => `
1835
- ${block(pipelineString)}
1836
-
1837
- ${block(commands.map((command) => `- ${command}`).join('\n'))}
1838
- `);
1839
- for (const task of tasks) {
1840
- const {
1841
- /* Note: Not using:> name, */
1842
- title, description,
1843
- /* Note: dependentParameterNames, */
1844
- jokerParameterNames: jokers, taskType, content, postprocessingFunctionNames: postprocessing, expectations, format, resultingParameterName, } = task;
1845
- const commands = [];
1846
- let contentLanguage = 'text';
1847
- if (taskType === 'PROMPT_TASK') {
1848
- const { modelRequirements } = task;
1849
- const { modelName, modelVariant } = modelRequirements || {};
1850
- // Note: Do nothing, it is default
1851
- // commands.push(`PROMPT`);
1852
- if (modelVariant) {
1853
- commands.push(`MODEL VARIANT ${capitalize(modelVariant)}`);
1854
- }
1855
- if (modelName) {
1856
- commands.push(`MODEL NAME \`${modelName}\``);
1857
- }
1858
- }
1859
- else if (taskType === 'SIMPLE_TASK') {
1860
- commands.push(`SIMPLE TEMPLATE`);
1861
- // Note: Nothing special here
1862
- }
1863
- else if (taskType === 'SCRIPT_TASK') {
1864
- commands.push(`SCRIPT`);
1865
- if (task.contentLanguage) {
1866
- contentLanguage = task.contentLanguage;
1867
- }
1868
- else {
1869
- contentLanguage = '';
1870
- }
1871
- }
1872
- else if (taskType === 'DIALOG_TASK') {
1873
- commands.push(`DIALOG`);
1874
- // Note: Nothing special here
1875
- } // <- }else if([🅱]
1876
- if (jokers) {
1877
- for (const joker of jokers) {
1878
- commands.push(`JOKER {${joker}}`);
1879
- }
1880
- } /* not else */
1881
- if (postprocessing) {
1882
- for (const postprocessingFunctionName of postprocessing) {
1883
- commands.push(`POSTPROCESSING \`${postprocessingFunctionName}\``);
1884
- }
1885
- } /* not else */
1886
- if (expectations) {
1887
- for (const [unit, { min, max }] of Object.entries(expectations)) {
1888
- if (min === max) {
1889
- commands.push(`EXPECT EXACTLY ${min} ${capitalize(unit + (min > 1 ? 's' : ''))}`);
1890
- }
1891
- else {
1892
- if (min !== undefined) {
1893
- commands.push(`EXPECT MIN ${min} ${capitalize(unit + (min > 1 ? 's' : ''))}`);
1894
- } /* not else */
1895
- if (max !== undefined) {
1896
- commands.push(`EXPECT MAX ${max} ${capitalize(unit + (max > 1 ? 's' : ''))}`);
1897
- }
1898
- }
1899
- }
1900
- } /* not else */
1901
- if (format) {
1902
- if (format === 'JSON') {
1903
- // TODO: @deprecated remove
1904
- commands.push(`FORMAT JSON`);
1905
- }
1906
- } /* not else */
1907
- pipelineString = spaceTrim$1((block) => `
1908
- ${block(pipelineString)}
1991
+ const commands = [];
1992
+ if (min !== undefined) {
1993
+ commands.push(`EXPECT MIN ${min} ${formatExpectationUnit(unit, min)}`);
1994
+ }
1995
+ if (max !== undefined) {
1996
+ commands.push(`EXPECT MAX ${max} ${formatExpectationUnit(unit, max)}`);
1997
+ }
1998
+ return commands;
1999
+ }
2000
+ /**
2001
+ * Formats the expectation unit exactly as the legacy serializer does.
2002
+ *
2003
+ * @private internal utility of `createTaskSerialization`
2004
+ */
2005
+ function formatExpectationUnit(unit, amount) {
2006
+ return capitalize(unit + (amount > 1 ? 's' : ''));
2007
+ }
2008
+ /**
2009
+ * Collects format commands.
2010
+ *
2011
+ * @private internal utility of `createTaskSerialization`
2012
+ */
2013
+ function createFormatCommands(task) {
2014
+ if (task.format === 'JSON') {
2015
+ // TODO: @deprecated remove
2016
+ return ['FORMAT JSON'];
2017
+ }
2018
+ return [];
2019
+ }
1909
2020
 
1910
- ## ${title}
2021
+ /**
2022
+ * Stringifies one task section of the pipeline.
2023
+ *
2024
+ * @private internal utility of `pipelineJsonToString`
2025
+ */
2026
+ function stringifyTask(task) {
2027
+ const { title, description, content, resultingParameterName } = task;
2028
+ const { commands, contentLanguage } = createTaskSerialization(task);
2029
+ return spaceTrim$1((block) => `
2030
+ ## ${title}
1911
2031
 
1912
- ${block(description || '')}
2032
+ ${block(description || '')}
1913
2033
 
1914
- ${block(commands.map((command) => `- ${command}`).join('\n'))}
2034
+ ${block(stringifyCommands(commands))}
1915
2035
 
1916
- \`\`\`${contentLanguage}
1917
- ${block(spaceTrim$1(content))}
1918
- \`\`\`
2036
+ \`\`\`${contentLanguage}
2037
+ ${block(spaceTrim$1(content))}
2038
+ \`\`\`
1919
2039
 
1920
- \`-> {${resultingParameterName}}\`
1921
- `); // <- TODO: [main] !!3 If the parameter here has description, add it and use taskParameterJsonToString
1922
- // <- TODO: [main] !!3 Escape
1923
- // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
1924
- }
1925
- return validatePipelineString(pipelineString);
2040
+ \`-> {${resultingParameterName}}\`
2041
+ `); // <- TODO: [main] !!3 If the parameter here has description, add it and use taskParameterJsonToString
2042
+ // <- TODO: [main] !!3 Escape
2043
+ // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
1926
2044
  }
2045
+
1927
2046
  /**
1928
- * Handles task parameter Json to string.
2047
+ * Converts promptbook in JSON format to string format
1929
2048
  *
1930
- * @private internal utility of `pipelineJsonToString`
2049
+ * @deprecated TODO: [🥍][🧠] Backup original files in `PipelineJson` same as in Promptbook.studio
2050
+ * @param pipelineJson Promptbook in JSON format (.bookc)
2051
+ * @returns Promptbook in string format (.book.md)
2052
+ *
2053
+ * @public exported from `@promptbook/core`
1931
2054
  */
1932
- function taskParameterJsonToString(taskParameterJson) {
1933
- const { name, description } = taskParameterJson;
1934
- let parameterString = `{${name}}`;
1935
- if (description) {
1936
- parameterString = `${parameterString} ${description}`;
2055
+ function pipelineJsonToString(pipelineJson) {
2056
+ let pipelineString = createPipelineIntroduction(pipelineJson);
2057
+ const pipelineCommands = createPipelineCommands(pipelineJson);
2058
+ pipelineString = appendMarkdownBlock(pipelineString, stringifyCommands(pipelineCommands));
2059
+ for (const task of pipelineJson.tasks) {
2060
+ pipelineString = appendMarkdownBlock(pipelineString, stringifyTask(task));
1937
2061
  }
1938
- return parameterString;
2062
+ return validatePipelineString(pipelineString);
1939
2063
  }
1940
2064
  // TODO: [🛋] Implement new features and commands into `pipelineJsonToString` + `taskParameterJsonToString` , use `stringifyCommand`
1941
2065
  // TODO: [🧠] Is there a way to auto-detect missing features in pipelineJsonToString
@@ -2349,233 +2473,519 @@ function validatePipeline(pipeline) {
2349
2473
  */
2350
2474
  function validatePipeline_InnerFunction(pipeline) {
2351
2475
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
2352
- const pipelineIdentification = (() => {
2353
- // Note: This is a 😐 implementation of [🚞]
2354
- const _ = [];
2355
- if (pipeline.sourceFile !== undefined) {
2356
- _.push(`File: ${pipeline.sourceFile}`);
2357
- }
2358
- if (pipeline.pipelineUrl !== undefined) {
2359
- _.push(`Url: ${pipeline.pipelineUrl}`);
2476
+ const context = createPipelineValidationContext(pipeline);
2477
+ validatePipelineMetadata(context);
2478
+ validatePipelineCollectionsStructure(context);
2479
+ validatePipelineParameters(context);
2480
+ validatePipelineTasks(context);
2481
+ validatePipelineDependencyResolution(context);
2482
+ // Note: Check that formfactor is corresponding to the pipeline interface
2483
+ // TODO: !!6 Implement this
2484
+ // pipeline.formfactorName
2485
+ }
2486
+ /**
2487
+ * Creates the shared validation context for one pipeline.
2488
+ *
2489
+ * @private internal utility of `validatePipeline`
2490
+ */
2491
+ function createPipelineValidationContext(pipeline) {
2492
+ return {
2493
+ pipeline,
2494
+ pipelineIdentification: getPipelineIdentification(pipeline),
2495
+ };
2496
+ }
2497
+ /**
2498
+ * Builds a short file/url identification block for validation errors.
2499
+ *
2500
+ * @private internal utility of `validatePipeline`
2501
+ */
2502
+ function getPipelineIdentification(pipeline) {
2503
+ // Note: This is a 😐 implementation of [🚞]
2504
+ const pipelineIdentificationParts = [];
2505
+ if (pipeline.sourceFile !== undefined) {
2506
+ pipelineIdentificationParts.push(`File: ${pipeline.sourceFile}`);
2507
+ }
2508
+ if (pipeline.pipelineUrl !== undefined) {
2509
+ pipelineIdentificationParts.push(`Url: ${pipeline.pipelineUrl}`);
2510
+ }
2511
+ return pipelineIdentificationParts.join('\n');
2512
+ }
2513
+ /**
2514
+ * Validates pipeline-level metadata fields.
2515
+ *
2516
+ * @private internal step of `validatePipeline`
2517
+ */
2518
+ function validatePipelineMetadata({ pipeline, pipelineIdentification }) {
2519
+ validatePipelineUrl(pipeline, pipelineIdentification);
2520
+ validatePipelineBookVersion(pipeline, pipelineIdentification);
2521
+ }
2522
+ /**
2523
+ * Validates that the expected top-level collections have array structure.
2524
+ *
2525
+ * @private internal step of `validatePipeline`
2526
+ */
2527
+ function validatePipelineCollectionsStructure({ pipeline, pipelineIdentification }) {
2528
+ validatePipelineParametersCollection(pipeline, pipelineIdentification);
2529
+ validatePipelineTasksCollection(pipeline, pipelineIdentification);
2530
+ }
2531
+ /**
2532
+ * Validates all pipeline parameter declarations.
2533
+ *
2534
+ * @private internal step of `validatePipeline`
2535
+ */
2536
+ function validatePipelineParameters({ pipeline, pipelineIdentification }) {
2537
+ for (const parameter of pipeline.parameters) {
2538
+ validatePipelineParameter(parameter, pipeline, pipelineIdentification);
2539
+ }
2540
+ }
2541
+ /**
2542
+ * Validates all pipeline tasks and their per-task invariants.
2543
+ *
2544
+ * @private internal step of `validatePipeline`
2545
+ */
2546
+ function validatePipelineTasks({ pipeline, pipelineIdentification }) {
2547
+ // Note: All input parameters are defined - so that they can be used as result of some task
2548
+ const definedParameters = createInitiallyDefinedParameters(pipeline);
2549
+ for (const task of pipeline.tasks) {
2550
+ validatePipelineTask(task, definedParameters, pipelineIdentification);
2551
+ }
2552
+ }
2553
+ /**
2554
+ * Validates that task dependencies can be resolved without cycles or missing definitions.
2555
+ *
2556
+ * @private internal step of `validatePipeline`
2557
+ */
2558
+ function validatePipelineDependencyResolution({ pipeline, pipelineIdentification }) {
2559
+ let dependencyResolutionState = createInitialDependencyResolutionState(pipeline);
2560
+ let loopLimit = LOOP_LIMIT;
2561
+ while (hasUnresolvedTasks(dependencyResolutionState)) {
2562
+ if (loopLimit-- < 0) {
2563
+ throw createDependencyResolutionLoopLimitError(pipelineIdentification);
2360
2564
  }
2361
- return _.join('\n');
2362
- })();
2363
- if (pipeline.pipelineUrl !== undefined && !isValidPipelineUrl(pipeline.pipelineUrl)) {
2364
- // <- Note: [🚲]
2365
- throw new PipelineLogicError(spaceTrim$1((block) => `
2366
- Invalid promptbook URL "${pipeline.pipelineUrl}"
2367
-
2368
- ${block(pipelineIdentification)}
2369
- `));
2565
+ dependencyResolutionState = resolveNextDependencyResolutionState(dependencyResolutionState, pipelineIdentification);
2370
2566
  }
2371
- if (pipeline.bookVersion !== undefined && !isValidPromptbookVersion(pipeline.bookVersion)) {
2372
- // <- Note: [🚲]
2373
- throw new PipelineLogicError(spaceTrim$1((block) => `
2374
- Invalid Promptbook Version "${pipeline.bookVersion}"
2567
+ }
2568
+ /**
2569
+ * Validates one pipeline parameter declaration.
2570
+ *
2571
+ * @private internal step of `validatePipeline`
2572
+ */
2573
+ function validatePipelineParameter(parameter, pipeline, pipelineIdentification) {
2574
+ validateParameterDirection(parameter, pipelineIdentification);
2575
+ validateParameterUsage(parameter, pipeline, pipelineIdentification);
2576
+ validateParameterDefinition(parameter, pipeline, pipelineIdentification);
2577
+ }
2578
+ /**
2579
+ * Validates one pipeline task and its invariants.
2580
+ *
2581
+ * @private internal step of `validatePipeline`
2582
+ */
2583
+ function validatePipelineTask(task, definedParameters, pipelineIdentification) {
2584
+ validateTaskResultingParameter(task, definedParameters, pipelineIdentification);
2585
+ validateTaskJokers(task, pipelineIdentification);
2586
+ validateTaskExpectations(task, pipelineIdentification);
2587
+ }
2588
+ /**
2589
+ * Validates the pipeline URL, when present.
2590
+ *
2591
+ * @private internal utility of `validatePipeline`
2592
+ */
2593
+ function validatePipelineUrl(pipeline, pipelineIdentification) {
2594
+ if (pipeline.pipelineUrl === undefined || isValidPipelineUrl(pipeline.pipelineUrl)) {
2595
+ return;
2596
+ }
2597
+ // <- Note: [🚲]
2598
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2599
+ Invalid promptbook URL "${pipeline.pipelineUrl}"
2375
2600
 
2376
- ${block(pipelineIdentification)}
2377
- `));
2601
+ ${block(pipelineIdentification)}
2602
+ `));
2603
+ }
2604
+ /**
2605
+ * Validates the Promptbook version, when present.
2606
+ *
2607
+ * @private internal utility of `validatePipeline`
2608
+ */
2609
+ function validatePipelineBookVersion(pipeline, pipelineIdentification) {
2610
+ if (pipeline.bookVersion === undefined || isValidPromptbookVersion(pipeline.bookVersion)) {
2611
+ return;
2378
2612
  }
2613
+ // <- Note: [🚲]
2614
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2615
+ Invalid Promptbook Version "${pipeline.bookVersion}"
2616
+
2617
+ ${block(pipelineIdentification)}
2618
+ `));
2619
+ }
2620
+ /**
2621
+ * Validates that `pipeline.parameters` is an array.
2622
+ *
2623
+ * @private internal utility of `validatePipeline`
2624
+ */
2625
+ function validatePipelineParametersCollection(pipeline, pipelineIdentification) {
2379
2626
  // TODO: [🧠] Maybe do here some proper JSON-schema / ZOD checking
2380
- if (!Array.isArray(pipeline.parameters)) {
2381
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2382
- throw new ParseError(spaceTrim$1((block) => `
2383
- Pipeline is valid JSON but with wrong structure
2627
+ if (Array.isArray(pipeline.parameters)) {
2628
+ return;
2629
+ }
2630
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2631
+ throw new ParseError(spaceTrim$1((block) => `
2632
+ Pipeline is valid JSON but with wrong structure
2384
2633
 
2385
- \`PipelineJson.parameters\` expected to be an array, but got ${typeof pipeline.parameters}
2634
+ \`PipelineJson.parameters\` expected to be an array, but got ${typeof pipeline.parameters}
2386
2635
 
2387
- ${block(pipelineIdentification)}
2388
- `));
2389
- }
2636
+ ${block(pipelineIdentification)}
2637
+ `));
2638
+ }
2639
+ /**
2640
+ * Validates that `pipeline.tasks` is an array.
2641
+ *
2642
+ * @private internal utility of `validatePipeline`
2643
+ */
2644
+ function validatePipelineTasksCollection(pipeline, pipelineIdentification) {
2390
2645
  // TODO: [🧠] Maybe do here some proper JSON-schema / ZOD checking
2391
- if (!Array.isArray(pipeline.tasks)) {
2392
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2393
- throw new ParseError(spaceTrim$1((block) => `
2394
- Pipeline is valid JSON but with wrong structure
2646
+ if (Array.isArray(pipeline.tasks)) {
2647
+ return;
2648
+ }
2649
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2650
+ throw new ParseError(spaceTrim$1((block) => `
2651
+ Pipeline is valid JSON but with wrong structure
2395
2652
 
2396
- \`PipelineJson.tasks\` expected to be an array, but got ${typeof pipeline.tasks}
2653
+ \`PipelineJson.tasks\` expected to be an array, but got ${typeof pipeline.tasks}
2397
2654
 
2398
- ${block(pipelineIdentification)}
2399
- `));
2655
+ ${block(pipelineIdentification)}
2656
+ `));
2657
+ }
2658
+ /**
2659
+ * Validates that one parameter does not declare incompatible directions.
2660
+ *
2661
+ * @private internal utility of `validatePipeline`
2662
+ */
2663
+ function validateParameterDirection(parameter, pipelineIdentification) {
2664
+ if (!parameter.isInput || !parameter.isOutput) {
2665
+ return;
2400
2666
  }
2401
- /*
2402
- TODO: [🧠][🅾] Should be empty pipeline valid or not
2403
- // Note: Check that pipeline has some tasks
2404
- if (pipeline.tasks.length === 0) {
2405
- throw new PipelineLogicError(
2406
- spaceTrim(
2407
- (block) => `
2408
- Pipeline must have at least one task
2667
+ const parameterName = parameter.name;
2668
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2409
2669
 
2410
- ${block(pipelineIdentification)}
2411
- `,
2412
- ),
2413
- );
2414
- }
2415
- */
2416
- // Note: Check each parameter individually
2417
- for (const parameter of pipeline.parameters) {
2418
- if (parameter.isInput && parameter.isOutput) {
2419
- throw new PipelineLogicError(spaceTrim$1((block) => `
2670
+ Parameter \`{${parameterName}}\` can not be both input and output
2420
2671
 
2421
- Parameter \`{${parameter.name}}\` can not be both input and output
2672
+ ${block(pipelineIdentification)}
2673
+ `));
2674
+ }
2675
+ /**
2676
+ * Validates that one intermediate parameter is actually consumed by at least one task.
2677
+ *
2678
+ * @private internal utility of `validatePipeline`
2679
+ */
2680
+ function validateParameterUsage(parameter, pipeline, pipelineIdentification) {
2681
+ if (parameter.isInput || parameter.isOutput || isParameterUsedByAnyTask(parameter, pipeline.tasks)) {
2682
+ return;
2683
+ }
2684
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2685
+ Parameter \`{${parameter.name}}\` is created but not used
2422
2686
 
2423
- ${block(pipelineIdentification)}
2424
- `));
2425
- }
2426
- // Note: Testing that parameter is either intermediate or output BUT not created and unused
2427
- if (!parameter.isInput &&
2428
- !parameter.isOutput &&
2429
- !pipeline.tasks.some((task) => task.dependentParameterNames.includes(parameter.name))) {
2430
- throw new PipelineLogicError(spaceTrim$1((block) => `
2431
- Parameter \`{${parameter.name}}\` is created but not used
2687
+ You can declare {${parameter.name}} as output parameter by adding in the header:
2688
+ - OUTPUT PARAMETER \`{${parameter.name}}\` ${parameter.description || ''}
2432
2689
 
2433
- You can declare {${parameter.name}} as output parameter by adding in the header:
2434
- - OUTPUT PARAMETER \`{${parameter.name}}\` ${parameter.description || ''}
2690
+ ${block(pipelineIdentification)}
2435
2691
 
2436
- ${block(pipelineIdentification)}
2692
+ `));
2693
+ }
2694
+ /**
2695
+ * Validates that one non-input parameter is produced by at least one task.
2696
+ *
2697
+ * @private internal utility of `validatePipeline`
2698
+ */
2699
+ function validateParameterDefinition(parameter, pipeline, pipelineIdentification) {
2700
+ if (parameter.isInput || isParameterDefinedByAnyTask(parameter, pipeline.tasks)) {
2701
+ return;
2702
+ }
2703
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2704
+ Parameter \`{${parameter.name}}\` is declared but not defined
2437
2705
 
2438
- `));
2439
- }
2440
- // Note: Testing that parameter is either input or result of some task
2441
- if (!parameter.isInput && !pipeline.tasks.some((task) => task.resultingParameterName === parameter.name)) {
2442
- throw new PipelineLogicError(spaceTrim$1((block) => `
2443
- Parameter \`{${parameter.name}}\` is declared but not defined
2706
+ You can do one of these:
2707
+ 1) Remove declaration of \`{${parameter.name}}\`
2708
+ 2) Add task that results in \`-> {${parameter.name}}\`
2444
2709
 
2445
- You can do one of these:
2446
- 1) Remove declaration of \`{${parameter.name}}\`
2447
- 2) Add task that results in \`-> {${parameter.name}}\`
2710
+ ${block(pipelineIdentification)}
2711
+ `));
2712
+ }
2713
+ /**
2714
+ * Checks whether one parameter is consumed by at least one task dependency list.
2715
+ *
2716
+ * @private internal utility of `validatePipeline`
2717
+ */
2718
+ function isParameterUsedByAnyTask(parameter, tasks) {
2719
+ return tasks.some((task) => task.dependentParameterNames.includes(parameter.name));
2720
+ }
2721
+ /**
2722
+ * Checks whether one parameter is produced by at least one task.
2723
+ *
2724
+ * @private internal utility of `validatePipeline`
2725
+ */
2726
+ function isParameterDefinedByAnyTask(parameter, tasks) {
2727
+ return tasks.some((task) => task.resultingParameterName === parameter.name);
2728
+ }
2729
+ /**
2730
+ * Collects the parameter names that are already defined before task validation starts.
2731
+ *
2732
+ * @private internal utility of `validatePipeline`
2733
+ */
2734
+ function createInitiallyDefinedParameters(pipeline) {
2735
+ return new Set(pipeline.parameters.filter(({ isInput }) => isInput).map(({ name }) => name));
2736
+ }
2737
+ /**
2738
+ * Validates one task result parameter declaration and marks it as defined.
2739
+ *
2740
+ * @private internal utility of `validatePipeline`
2741
+ */
2742
+ function validateTaskResultingParameter(task, definedParameters, pipelineIdentification) {
2743
+ if (definedParameters.has(task.resultingParameterName)) {
2744
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2745
+ Parameter \`{${task.resultingParameterName}}\` is defined multiple times
2448
2746
 
2449
- ${block(pipelineIdentification)}
2450
- `));
2451
- }
2747
+ ${block(pipelineIdentification)}
2748
+ `));
2452
2749
  }
2453
- // Note: All input parameters are defined - so that they can be used as result of some task
2454
- const definedParameters = new Set(pipeline.parameters.filter(({ isInput }) => isInput).map(({ name }) => name));
2455
- // Note: Checking each task individually
2456
- for (const task of pipeline.tasks) {
2457
- if (definedParameters.has(task.resultingParameterName)) {
2458
- throw new PipelineLogicError(spaceTrim$1((block) => `
2459
- Parameter \`{${task.resultingParameterName}}\` is defined multiple times
2750
+ if (RESERVED_PARAMETER_NAMES.includes(task.resultingParameterName)) {
2751
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2752
+ Parameter name {${task.resultingParameterName}} is reserved, please use different name
2460
2753
 
2461
- ${block(pipelineIdentification)}
2462
- `));
2463
- }
2464
- if (RESERVED_PARAMETER_NAMES.includes(task.resultingParameterName)) {
2465
- throw new PipelineLogicError(spaceTrim$1((block) => `
2466
- Parameter name {${task.resultingParameterName}} is reserved, please use different name
2754
+ ${block(pipelineIdentification)}
2755
+ `));
2756
+ }
2757
+ definedParameters.add(task.resultingParameterName);
2758
+ }
2759
+ /**
2760
+ * Validates joker parameters for one task.
2761
+ *
2762
+ * @private internal utility of `validatePipeline`
2763
+ */
2764
+ function validateTaskJokers(task, pipelineIdentification) {
2765
+ if (!hasTaskJokers(task)) {
2766
+ return;
2767
+ }
2768
+ validateTaskSupportsJokers(task, pipelineIdentification);
2769
+ validateTaskJokerDependencies(task, pipelineIdentification);
2770
+ }
2771
+ /**
2772
+ * Checks whether one task declares any joker parameters.
2773
+ *
2774
+ * @private internal utility of `validatePipeline`
2775
+ */
2776
+ function hasTaskJokers(task) {
2777
+ return !!task.jokerParameterNames && task.jokerParameterNames.length > 0;
2778
+ }
2779
+ /**
2780
+ * Validates that a task has the required supporting features when using jokers.
2781
+ *
2782
+ * @private internal utility of `validatePipeline`
2783
+ */
2784
+ function validateTaskSupportsJokers(task, pipelineIdentification) {
2785
+ if (task.format ||
2786
+ task.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
2787
+ return;
2788
+ }
2789
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2790
+ Joker parameters are used for {${task.resultingParameterName}} but no expectations are defined
2467
2791
 
2468
- ${block(pipelineIdentification)}
2469
- `));
2792
+ ${block(pipelineIdentification)}
2793
+ `));
2794
+ }
2795
+ /**
2796
+ * Validates that every joker parameter is also listed among task dependencies.
2797
+ *
2798
+ * @private internal utility of `validatePipeline`
2799
+ */
2800
+ function validateTaskJokerDependencies(task, pipelineIdentification) {
2801
+ for (const joker of task.jokerParameterNames) {
2802
+ if (task.dependentParameterNames.includes(joker)) {
2803
+ continue;
2470
2804
  }
2471
- definedParameters.add(task.resultingParameterName);
2472
- if (task.jokerParameterNames && task.jokerParameterNames.length > 0) {
2473
- if (!task.format &&
2474
- !task.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
2475
- throw new PipelineLogicError(spaceTrim$1((block) => `
2476
- Joker parameters are used for {${task.resultingParameterName}} but no expectations are defined
2477
-
2478
- ${block(pipelineIdentification)}
2479
- `));
2480
- }
2481
- for (const joker of task.jokerParameterNames) {
2482
- if (!task.dependentParameterNames.includes(joker)) {
2483
- throw new PipelineLogicError(spaceTrim$1((block) => `
2484
- Parameter \`{${joker}}\` is used for {${task.resultingParameterName}} as joker but not in \`dependentParameterNames\`
2805
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2806
+ Parameter \`{${joker}}\` is used for {${task.resultingParameterName}} as joker but not in \`dependentParameterNames\`
2485
2807
 
2486
- ${block(pipelineIdentification)}
2487
- `));
2488
- }
2489
- }
2490
- }
2491
- if (task.expectations) {
2492
- for (const [unit, { min, max }] of Object.entries(task.expectations)) {
2493
- if (min !== undefined && max !== undefined && min > max) {
2494
- throw new PipelineLogicError(spaceTrim$1((block) => `
2495
- Min expectation (=${min}) of ${unit} is higher than max expectation (=${max})
2808
+ ${block(pipelineIdentification)}
2809
+ `));
2810
+ }
2811
+ }
2812
+ /**
2813
+ * Validates all expectation bounds configured on one task.
2814
+ *
2815
+ * @private internal utility of `validatePipeline`
2816
+ */
2817
+ function validateTaskExpectations(task, pipelineIdentification) {
2818
+ if (!task.expectations) {
2819
+ return;
2820
+ }
2821
+ for (const [unit, { min, max }] of Object.entries(task.expectations)) {
2822
+ validateTaskExpectationRange(unit, min, max, pipelineIdentification);
2823
+ validateTaskExpectationMin(unit, min, pipelineIdentification);
2824
+ validateTaskExpectationMax(unit, max, pipelineIdentification);
2825
+ }
2826
+ }
2827
+ /**
2828
+ * Validates the minimum and maximum expectation ordering for one unit.
2829
+ *
2830
+ * @private internal utility of `validatePipeline`
2831
+ */
2832
+ function validateTaskExpectationRange(unit, min, max, pipelineIdentification) {
2833
+ if (min === undefined || max === undefined || min <= max) {
2834
+ return;
2835
+ }
2836
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2837
+ Min expectation (=${min}) of ${unit} is higher than max expectation (=${max})
2496
2838
 
2497
- ${block(pipelineIdentification)}
2498
- `));
2499
- }
2500
- if (min !== undefined && min < 0) {
2501
- throw new PipelineLogicError(spaceTrim$1((block) => `
2502
- Min expectation of ${unit} must be zero or positive
2839
+ ${block(pipelineIdentification)}
2840
+ `));
2841
+ }
2842
+ /**
2843
+ * Validates the minimum expectation bound for one unit.
2844
+ *
2845
+ * @private internal utility of `validatePipeline`
2846
+ */
2847
+ function validateTaskExpectationMin(unit, min, pipelineIdentification) {
2848
+ if (min === undefined || min >= 0) {
2849
+ return;
2850
+ }
2851
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2852
+ Min expectation of ${unit} must be zero or positive
2503
2853
 
2504
- ${block(pipelineIdentification)}
2505
- `));
2506
- }
2507
- if (max !== undefined && max <= 0) {
2508
- throw new PipelineLogicError(spaceTrim$1((block) => `
2509
- Max expectation of ${unit} must be positive
2854
+ ${block(pipelineIdentification)}
2855
+ `));
2856
+ }
2857
+ /**
2858
+ * Validates the maximum expectation bound for one unit.
2859
+ *
2860
+ * @private internal utility of `validatePipeline`
2861
+ */
2862
+ function validateTaskExpectationMax(unit, max, pipelineIdentification) {
2863
+ if (max === undefined || max > 0) {
2864
+ return;
2865
+ }
2866
+ throw new PipelineLogicError(spaceTrim$1((block) => `
2867
+ Max expectation of ${unit} must be positive
2510
2868
 
2511
- ${block(pipelineIdentification)}
2512
- `));
2513
- }
2514
- }
2515
- }
2869
+ ${block(pipelineIdentification)}
2870
+ `));
2871
+ }
2872
+ /**
2873
+ * Collects the parameter names that are already resolvable before dependency traversal starts.
2874
+ *
2875
+ * @private internal utility of `validatePipeline`
2876
+ */
2877
+ function createInitialDependencyResolutionState(pipeline) {
2878
+ return {
2879
+ resolvedParameterNames: createInitiallyResolvedParameterNames(pipeline),
2880
+ unresolvedTasks: [...pipeline.tasks],
2881
+ };
2882
+ }
2883
+ /**
2884
+ * Checks whether dependency resolution still has tasks left to process.
2885
+ *
2886
+ * @private internal utility of `validatePipeline`
2887
+ */
2888
+ function hasUnresolvedTasks({ unresolvedTasks }) {
2889
+ return unresolvedTasks.length > 0;
2890
+ }
2891
+ /**
2892
+ * Resolves the next batch of currently satisfiable tasks.
2893
+ *
2894
+ * @private internal utility of `validatePipeline`
2895
+ */
2896
+ function resolveNextDependencyResolutionState(dependencyResolutionState, pipelineIdentification) {
2897
+ const currentlyResolvedTasks = getCurrentlyResolvedTasks(dependencyResolutionState.unresolvedTasks, dependencyResolutionState.resolvedParameterNames);
2898
+ if (currentlyResolvedTasks.length === 0) {
2899
+ throw createUnresolvedTasksError(dependencyResolutionState.unresolvedTasks, dependencyResolutionState.resolvedParameterNames, pipelineIdentification);
2516
2900
  }
2517
- // Note: Detect circular dependencies
2518
- let resovedParameters = pipeline.parameters
2901
+ return {
2902
+ resolvedParameterNames: appendResolvedTaskParameterNames(dependencyResolutionState.resolvedParameterNames, currentlyResolvedTasks),
2903
+ unresolvedTasks: dependencyResolutionState.unresolvedTasks.filter((task) => !currentlyResolvedTasks.includes(task)),
2904
+ };
2905
+ }
2906
+ /**
2907
+ * Collects the parameter names that are already resolvable before dependency traversal starts.
2908
+ *
2909
+ * @private internal utility of `validatePipeline`
2910
+ */
2911
+ function createInitiallyResolvedParameterNames(pipeline) {
2912
+ let resolvedParameterNames = pipeline.parameters
2519
2913
  .filter(({ isInput }) => isInput)
2520
2914
  .map(({ name }) => name);
2521
- // Note: All reserved parameters are resolved
2522
2915
  for (const reservedParameterName of RESERVED_PARAMETER_NAMES) {
2523
- resovedParameters = [...resovedParameters, reservedParameterName];
2916
+ resolvedParameterNames = [...resolvedParameterNames, reservedParameterName];
2524
2917
  }
2525
- let unresovedTasks = [...pipeline.tasks];
2526
- let loopLimit = LOOP_LIMIT;
2527
- while (unresovedTasks.length > 0) {
2528
- if (loopLimit-- < 0) {
2529
- // Note: Really UnexpectedError not LimitReachedError - this should not happen and be caught below
2530
- throw new UnexpectedError(spaceTrim$1((block) => `
2531
- Loop limit reached during detection of circular dependencies in \`validatePipeline\`
2918
+ return resolvedParameterNames;
2919
+ }
2920
+ /**
2921
+ * Adds newly resolved task outputs to the resolved parameter list.
2922
+ *
2923
+ * @private internal utility of `validatePipeline`
2924
+ */
2925
+ function appendResolvedTaskParameterNames(resolvedParameterNames, currentlyResolvedTasks) {
2926
+ return [
2927
+ ...resolvedParameterNames,
2928
+ ...currentlyResolvedTasks.map(({ resultingParameterName }) => resultingParameterName),
2929
+ ];
2930
+ }
2931
+ /**
2932
+ * Selects tasks whose dependencies are already resolved.
2933
+ *
2934
+ * @private internal utility of `validatePipeline`
2935
+ */
2936
+ function getCurrentlyResolvedTasks(unresolvedTasks, resolvedParameterNames) {
2937
+ return unresolvedTasks.filter((task) => task.dependentParameterNames.every((name) => resolvedParameterNames.includes(name)));
2938
+ }
2939
+ /**
2940
+ * Creates the unexpected loop-limit error for dependency resolution.
2941
+ *
2942
+ * @private internal utility of `validatePipeline`
2943
+ */
2944
+ function createDependencyResolutionLoopLimitError(pipelineIdentification) {
2945
+ // Note: Really UnexpectedError not LimitReachedError - this should not happen and be caught below
2946
+ return new UnexpectedError(spaceTrim$1((block) => `
2947
+ Loop limit reached during detection of circular dependencies in \`validatePipeline\`
2532
2948
 
2533
- ${block(pipelineIdentification)}
2534
- `));
2535
- }
2536
- const currentlyResovedTasks = unresovedTasks.filter((task) => task.dependentParameterNames.every((name) => resovedParameters.includes(name)));
2537
- if (currentlyResovedTasks.length === 0) {
2538
- throw new PipelineLogicError(
2539
- // TODO: [🐎] DRY
2540
- spaceTrim$1((block) => `
2949
+ ${block(pipelineIdentification)}
2950
+ `));
2951
+ }
2952
+ /**
2953
+ * Creates the detailed error for unresolved or circular task dependencies.
2954
+ *
2955
+ * @private internal utility of `validatePipeline`
2956
+ */
2957
+ function createUnresolvedTasksError(unresolvedTasks, resolvedParameterNames, pipelineIdentification) {
2958
+ return new PipelineLogicError(
2959
+ // TODO: [🐎] DRY
2960
+ spaceTrim$1((block) => `
2541
2961
 
2542
- Can not resolve some parameters:
2543
- Either you are using a parameter that is not defined, or there are some circular dependencies.
2962
+ Can not resolve some parameters:
2963
+ Either you are using a parameter that is not defined, or there are some circular dependencies.
2544
2964
 
2545
- ${block(pipelineIdentification)}
2965
+ ${block(pipelineIdentification)}
2546
2966
 
2547
- **Can not resolve:**
2548
- ${block(unresovedTasks
2549
- .map(({ resultingParameterName, dependentParameterNames }) => `- Parameter \`{${resultingParameterName}}\` which depends on ${dependentParameterNames
2550
- .map((dependentParameterName) => `\`{${dependentParameterName}}\``)
2551
- .join(' and ')}`)
2552
- .join('\n'))}
2967
+ **Can not resolve:**
2968
+ ${block(unresolvedTasks
2969
+ .map(({ resultingParameterName, dependentParameterNames }) => `- Parameter \`{${resultingParameterName}}\` which depends on ${dependentParameterNames
2970
+ .map((dependentParameterName) => `\`{${dependentParameterName}}\``)
2971
+ .join(' and ')}`)
2972
+ .join('\n'))}
2553
2973
 
2554
- **Resolved:**
2555
- ${block(resovedParameters
2556
- .filter((name) => !RESERVED_PARAMETER_NAMES.includes(name))
2557
- .map((name) => `- Parameter \`{${name}}\``)
2558
- .join('\n'))}
2974
+ **Resolved:**
2975
+ ${block(resolvedParameterNames
2976
+ .filter((name) => !RESERVED_PARAMETER_NAMES.includes(name))
2977
+ .map((name) => `- Parameter \`{${name}}\``)
2978
+ .join('\n'))}
2559
2979
 
2560
2980
 
2561
- **Reserved (which are available):**
2562
- ${block(resovedParameters
2563
- .filter((name) => RESERVED_PARAMETER_NAMES.includes(name))
2564
- .map((name) => `- Parameter \`{${name}}\``)
2565
- .join('\n'))}
2981
+ **Reserved (which are available):**
2982
+ ${block(resolvedParameterNames
2983
+ .filter((name) => RESERVED_PARAMETER_NAMES.includes(name))
2984
+ .map((name) => `- Parameter \`{${name}}\``)
2985
+ .join('\n'))}
2566
2986
 
2567
2987
 
2568
- `));
2569
- }
2570
- resovedParameters = [
2571
- ...resovedParameters,
2572
- ...currentlyResovedTasks.map(({ resultingParameterName }) => resultingParameterName),
2573
- ];
2574
- unresovedTasks = unresovedTasks.filter((task) => !currentlyResovedTasks.includes(task));
2575
- }
2576
- // Note: Check that formfactor is corresponding to the pipeline interface
2577
- // TODO: !!6 Implement this
2578
- // pipeline.formfactorName
2988
+ `));
2579
2989
  }
2580
2990
  /**
2581
2991
  * TODO: [🧞‍♀️] Do not allow joker + foreach
@@ -3248,76 +3658,287 @@ function assertsTaskSuccessful(executionResult) {
3248
3658
  // TODO: [🧠] Can this return type be better typed than void
3249
3659
 
3250
3660
  /**
3251
- * Helper to create a new task
3661
+ * Resolves the short task summary shown in the UI.
3252
3662
  *
3253
- * @private internal helper function
3663
+ * @private internal helper function of `ExecutionTask`
3254
3664
  */
3255
- function createTask(options) {
3256
- const { taskType, taskProcessCallback } = options;
3257
- let { title } = options;
3258
- // TODO: [🐙] DRY
3259
- const taskId = `${taskType.toLowerCase().substring(0, 4)}-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
3260
- let status = 'RUNNING';
3261
- const createdAt = new Date();
3262
- let updatedAt = createdAt;
3263
- const errors = [];
3264
- const warnings = [];
3265
- const llmCalls = [];
3266
- let currentValue = {};
3267
- let customTldr = null;
3268
- const partialResultSubject = new Subject();
3269
- // <- Note: Not using `BehaviorSubject` because on error we can't access the last value
3270
- const finalResultPromise = /* not await */ taskProcessCallback((newOngoingResult) => {
3271
- if (newOngoingResult.title) {
3272
- title = newOngoingResult.title;
3273
- }
3274
- updatedAt = new Date();
3275
- Object.assign(currentValue, newOngoingResult);
3276
- // <- TODO: assign deep
3277
- partialResultSubject.next(newOngoingResult);
3278
- }, (tldrInfo) => {
3279
- customTldr = tldrInfo;
3280
- updatedAt = new Date();
3281
- }, (llmCall) => {
3282
- llmCalls.push(llmCall);
3283
- updatedAt = new Date();
3284
- });
3285
- finalResultPromise
3286
- .catch((error) => {
3287
- errors.push(error);
3288
- partialResultSubject.error(error);
3289
- })
3290
- .then((executionResult) => {
3291
- if (executionResult) {
3292
- try {
3293
- updatedAt = new Date();
3294
- errors.push(...executionResult.errors);
3295
- warnings.push(...executionResult.warnings);
3296
- // <- TODO: [🌂] Only unique errors and warnings should be added (or filtered)
3297
- // TODO: [🧠] !! errors, warning, isSuccessful are redundant both in `ExecutionTask` and `ExecutionTask.currentValue`
3298
- // Also maybe move `ExecutionTask.currentValue.usage` -> `ExecutionTask.usage`
3299
- // And delete `ExecutionTask.currentValue.preparedPipeline`
3300
- assertsTaskSuccessful(executionResult);
3301
- status = 'FINISHED';
3302
- currentValue = jsonStringsToJsons(executionResult);
3303
- // <- TODO: [🧠] Is this a good idea to convert JSON strins to JSONs?
3304
- partialResultSubject.next(executionResult);
3305
- }
3306
- catch (error) {
3307
- assertsError(error);
3308
- status = 'ERROR';
3309
- errors.push(error);
3310
- partialResultSubject.error(error);
3311
- }
3312
- }
3313
- partialResultSubject.complete();
3314
- });
3315
- async function asPromise(options) {
3316
- const { isCrashedOnError = true } = options || {};
3317
- const finalResult = await finalResultPromise;
3318
- if (isCrashedOnError) {
3319
- assertsTaskSuccessful(finalResult);
3320
- }
3665
+ function resolveTaskTldr(options) {
3666
+ const { customTldr } = options;
3667
+ if (customTldr) {
3668
+ return customTldr;
3669
+ }
3670
+ return {
3671
+ percent: resolveTaskPercent(options),
3672
+ message: `${resolveTaskMessage(options)} (!!!fallback)`,
3673
+ };
3674
+ }
3675
+ /**
3676
+ * Resolves the best progress percentage for the current task state.
3677
+ *
3678
+ * @private internal helper function of `ExecutionTask`
3679
+ */
3680
+ function resolveTaskPercent(options) {
3681
+ const explicitPercent = getExplicitTaskPercent(options.currentValue);
3682
+ if (typeof explicitPercent === 'number') {
3683
+ return normalizeTaskPercent(explicitPercent);
3684
+ }
3685
+ return normalizeTaskPercent(calculateSimulatedTaskPercent(options));
3686
+ }
3687
+ /**
3688
+ * Picks a directly reported progress percentage from the task result snapshot.
3689
+ *
3690
+ * @private internal helper function of `ExecutionTask`
3691
+ */
3692
+ function getExplicitTaskPercent(currentValue) {
3693
+ var _a, _b, _c, _d, _e, _f;
3694
+ return ((_f = (_d = (_b = (_a = currentValue === null || currentValue === void 0 ? void 0 : currentValue.tldr) === null || _a === void 0 ? void 0 : _a.percent) !== null && _b !== void 0 ? _b : (_c = currentValue === null || currentValue === void 0 ? void 0 : currentValue.usage) === null || _c === void 0 ? void 0 : _c.percent) !== null && _d !== void 0 ? _d : (_e = currentValue === null || currentValue === void 0 ? void 0 : currentValue.progress) === null || _e === void 0 ? void 0 : _e.percent) !== null && _f !== void 0 ? _f : currentValue === null || currentValue === void 0 ? void 0 : currentValue.percent);
3695
+ }
3696
+ /**
3697
+ * Simulates progress when the task result does not expose an explicit percentage.
3698
+ *
3699
+ * @private internal helper function of `ExecutionTask`
3700
+ */
3701
+ function calculateSimulatedTaskPercent(options) {
3702
+ const { currentValue, status, createdAt } = options;
3703
+ const elapsedMs = new Date().getTime() - createdAt.getTime();
3704
+ const timeProgress = Math.min(elapsedMs / DEFAULT_TASK_SIMULATED_DURATION_MS, 1);
3705
+ const { subtaskCount, completedSubtasks } = summarizeTaskSubtasks(currentValue);
3706
+ if (status === 'FINISHED') {
3707
+ return 1;
3708
+ }
3709
+ if (status === 'ERROR') {
3710
+ return 0;
3711
+ }
3712
+ return Math.min(completedSubtasks / subtaskCount + (1 / subtaskCount) * timeProgress, 1);
3713
+ }
3714
+ /**
3715
+ * Counts total and completed subtasks used by the fallback progress simulation.
3716
+ *
3717
+ * @private internal helper function of `ExecutionTask`
3718
+ */
3719
+ function summarizeTaskSubtasks(currentValue) {
3720
+ if (!Array.isArray(currentValue === null || currentValue === void 0 ? void 0 : currentValue.subtasks)) {
3721
+ return { subtaskCount: 1, completedSubtasks: 0 };
3722
+ }
3723
+ return {
3724
+ subtaskCount: currentValue.subtasks.length || 1,
3725
+ completedSubtasks: currentValue.subtasks.filter(isTaskSubtaskCompleted).length,
3726
+ };
3727
+ }
3728
+ /**
3729
+ * Tells whether a task subtask is already finished.
3730
+ *
3731
+ * @private internal helper function of `ExecutionTask`
3732
+ */
3733
+ function isTaskSubtaskCompleted(subtask) {
3734
+ return subtask.done || subtask.completed || false;
3735
+ }
3736
+ /**
3737
+ * Normalizes a progress percentage into the expected `0..1` range.
3738
+ *
3739
+ * @private internal helper function of `ExecutionTask`
3740
+ */
3741
+ function normalizeTaskPercent(percentRaw) {
3742
+ let percent = Number(percentRaw) || 0;
3743
+ if (percent < 0) {
3744
+ percent = 0;
3745
+ }
3746
+ if (percent > 1) {
3747
+ percent = 1;
3748
+ }
3749
+ return percent;
3750
+ }
3751
+ /**
3752
+ * Resolves the best human-readable status message for the current task state.
3753
+ *
3754
+ * @private internal helper function of `ExecutionTask`
3755
+ */
3756
+ function resolveTaskMessage(options) {
3757
+ return (getCurrentValueMessage(options.currentValue) ||
3758
+ getCurrentSubtaskMessage(options.currentValue) ||
3759
+ getLatestIssueMessage(options.errors, 'Error') ||
3760
+ getLatestIssueMessage(options.warnings, 'Warning') ||
3761
+ getStatusMessage(options.status));
3762
+ }
3763
+ /**
3764
+ * Picks a message already reported by the current task result snapshot.
3765
+ *
3766
+ * @private internal helper function of `ExecutionTask`
3767
+ */
3768
+ function getCurrentValueMessage(currentValue) {
3769
+ var _a, _b, _c, _d;
3770
+ return (_d = (_c = (_b = (_a = currentValue === null || currentValue === void 0 ? void 0 : currentValue.tldr) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : currentValue === null || currentValue === void 0 ? void 0 : currentValue.message) !== null && _c !== void 0 ? _c : currentValue === null || currentValue === void 0 ? void 0 : currentValue.summary) !== null && _d !== void 0 ? _d : currentValue === null || currentValue === void 0 ? void 0 : currentValue.statusMessage;
3771
+ }
3772
+ /**
3773
+ * Builds a fallback message from the first unfinished subtask title.
3774
+ *
3775
+ * @private internal helper function of `ExecutionTask`
3776
+ */
3777
+ function getCurrentSubtaskMessage(currentValue) {
3778
+ if (!Array.isArray(currentValue === null || currentValue === void 0 ? void 0 : currentValue.subtasks) || currentValue.subtasks.length === 0) {
3779
+ return undefined;
3780
+ }
3781
+ const currentSubtask = currentValue.subtasks.find((subtask) => !isTaskSubtaskCompleted(subtask));
3782
+ if (!(currentSubtask === null || currentSubtask === void 0 ? void 0 : currentSubtask.title)) {
3783
+ return undefined;
3784
+ }
3785
+ return `Working on ${currentSubtask.title}`;
3786
+ }
3787
+ /**
3788
+ * Picks the latest error or warning message, with the legacy generic fallback label.
3789
+ *
3790
+ * @private internal helper function of `ExecutionTask`
3791
+ */
3792
+ function getLatestIssueMessage(issues, fallbackMessage) {
3793
+ if (issues.length === 0) {
3794
+ return undefined;
3795
+ }
3796
+ return issues[issues.length - 1].message || fallbackMessage;
3797
+ }
3798
+ /**
3799
+ * Builds the final status-based fallback message.
3800
+ *
3801
+ * @private internal helper function of `ExecutionTask`
3802
+ */
3803
+ function getStatusMessage(status) {
3804
+ if (status === 'FINISHED') {
3805
+ return 'Finished';
3806
+ }
3807
+ if (status === 'ERROR') {
3808
+ return 'Error';
3809
+ }
3810
+ return 'Running';
3811
+ }
3812
+
3813
+ /**
3814
+ * Creates the initial mutable state for a task.
3815
+ *
3816
+ * @private internal helper function
3817
+ */
3818
+ function createTaskState(title, createdAt) {
3819
+ return {
3820
+ title,
3821
+ status: 'RUNNING',
3822
+ updatedAt: createdAt,
3823
+ errors: [],
3824
+ warnings: [],
3825
+ llmCalls: [],
3826
+ currentValue: {},
3827
+ customTldr: null,
3828
+ };
3829
+ }
3830
+ /**
3831
+ * Creates the partial-result updater passed into the task process callback.
3832
+ *
3833
+ * @private internal helper function
3834
+ */
3835
+ function createOngoingResultUpdater(taskState, partialResultSubject) {
3836
+ return (newOngoingResult) => {
3837
+ if (newOngoingResult.title) {
3838
+ taskState.title = newOngoingResult.title;
3839
+ }
3840
+ taskState.updatedAt = new Date();
3841
+ Object.assign(taskState.currentValue, newOngoingResult);
3842
+ // <- TODO: assign deep
3843
+ partialResultSubject.next(newOngoingResult);
3844
+ };
3845
+ }
3846
+ /**
3847
+ * Creates the custom-TLDR updater passed into the task process callback.
3848
+ *
3849
+ * @private internal helper function
3850
+ */
3851
+ function createTldrUpdater(taskState) {
3852
+ return (tldrInfo) => {
3853
+ taskState.customTldr = tldrInfo;
3854
+ taskState.updatedAt = new Date();
3855
+ };
3856
+ }
3857
+ /**
3858
+ * Creates the LLM call logger passed into the task process callback.
3859
+ *
3860
+ * @private internal helper function
3861
+ */
3862
+ function createLlmCallLogger(taskState) {
3863
+ return (llmCall) => {
3864
+ taskState.llmCalls.push(llmCall);
3865
+ taskState.updatedAt = new Date();
3866
+ };
3867
+ }
3868
+ /**
3869
+ * Wires the task promise into the observable/error lifecycle.
3870
+ *
3871
+ * @private internal helper function
3872
+ */
3873
+ function settleTaskPromise(finalResultPromise, taskState, partialResultSubject) {
3874
+ finalResultPromise
3875
+ .catch((error) => {
3876
+ taskState.errors.push(error);
3877
+ partialResultSubject.error(error);
3878
+ })
3879
+ .then((executionResult) => {
3880
+ if (executionResult) {
3881
+ try {
3882
+ finalizeTaskResult(executionResult, taskState, partialResultSubject);
3883
+ }
3884
+ catch (error) {
3885
+ failTaskResult(error, taskState, partialResultSubject);
3886
+ }
3887
+ }
3888
+ partialResultSubject.complete();
3889
+ });
3890
+ }
3891
+ /**
3892
+ * Applies the final successful task result into the mutable task state.
3893
+ *
3894
+ * @private internal helper function
3895
+ */
3896
+ function finalizeTaskResult(executionResult, taskState, partialResultSubject) {
3897
+ taskState.updatedAt = new Date();
3898
+ taskState.errors.push(...executionResult.errors);
3899
+ taskState.warnings.push(...executionResult.warnings);
3900
+ // <- TODO: [🌂] Only unique errors and warnings should be added (or filtered)
3901
+ // TODO: [🧠] !! errors, warning, isSuccessful are redundant both in `ExecutionTask` and `ExecutionTask.currentValue`
3902
+ // Also maybe move `ExecutionTask.currentValue.usage` -> `ExecutionTask.usage`
3903
+ // And delete `ExecutionTask.currentValue.preparedPipeline`
3904
+ assertsTaskSuccessful(executionResult);
3905
+ taskState.status = 'FINISHED';
3906
+ taskState.currentValue = jsonStringsToJsons(executionResult);
3907
+ // <- TODO: [🧠] Is this a good idea to convert JSON strins to JSONs?
3908
+ partialResultSubject.next(executionResult);
3909
+ }
3910
+ /**
3911
+ * Records a final-result failure after the task promise itself resolved.
3912
+ *
3913
+ * @private internal helper function
3914
+ */
3915
+ function failTaskResult(error, taskState, partialResultSubject) {
3916
+ assertsError(error);
3917
+ taskState.status = 'ERROR';
3918
+ taskState.errors.push(error);
3919
+ partialResultSubject.error(error);
3920
+ }
3921
+ /**
3922
+ * Helper to create a new task
3923
+ *
3924
+ * @private internal helper function
3925
+ */
3926
+ function createTask(options) {
3927
+ const { taskType, title, taskProcessCallback } = options;
3928
+ // TODO: [🐙] DRY
3929
+ const taskId = `${taskType.toLowerCase().substring(0, 4)}-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
3930
+ const createdAt = new Date();
3931
+ const taskState = createTaskState(title, createdAt);
3932
+ const partialResultSubject = new Subject();
3933
+ // <- Note: Not using `BehaviorSubject` because on error we can't access the last value
3934
+ const finalResultPromise = /* not await */ taskProcessCallback(createOngoingResultUpdater(taskState, partialResultSubject), createTldrUpdater(taskState), createLlmCallLogger(taskState));
3935
+ settleTaskPromise(finalResultPromise, taskState, partialResultSubject);
3936
+ async function asPromise(options) {
3937
+ const { isCrashedOnError = true } = options || {};
3938
+ const finalResult = await finalResultPromise;
3939
+ if (isCrashedOnError) {
3940
+ assertsTaskSuccessful(finalResult);
3941
+ }
3321
3942
  return finalResult;
3322
3943
  }
3323
3944
  return {
@@ -3327,91 +3948,29 @@ function createTask(options) {
3327
3948
  return PROMPTBOOK_ENGINE_VERSION;
3328
3949
  },
3329
3950
  get title() {
3330
- return title;
3951
+ return taskState.title;
3331
3952
  // <- Note: [1] These must be getters to allow changing the value in the future
3332
3953
  },
3333
3954
  get status() {
3334
- return status;
3955
+ return taskState.status;
3335
3956
  // <- Note: [1] --||--
3336
3957
  },
3337
3958
  get tldr() {
3338
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
3339
- // Use custom tldr if available
3340
- if (customTldr) {
3341
- return customTldr;
3342
- }
3343
- // Fallback to default implementation
3344
- const cv = currentValue;
3345
- // If explicit percent is provided, use it
3346
- let percentRaw = (_f = (_d = (_b = (_a = cv === null || cv === void 0 ? void 0 : cv.tldr) === null || _a === void 0 ? void 0 : _a.percent) !== null && _b !== void 0 ? _b : (_c = cv === null || cv === void 0 ? void 0 : cv.usage) === null || _c === void 0 ? void 0 : _c.percent) !== null && _d !== void 0 ? _d : (_e = cv === null || cv === void 0 ? void 0 : cv.progress) === null || _e === void 0 ? void 0 : _e.percent) !== null && _f !== void 0 ? _f : cv === null || cv === void 0 ? void 0 : cv.percent;
3347
- // Simulate progress if not provided
3348
- if (typeof percentRaw !== 'number') {
3349
- // Simulate progress: evenly split across subtasks, based on elapsed time
3350
- const now = new Date();
3351
- const elapsedMs = now.getTime() - createdAt.getTime();
3352
- const totalMs = DEFAULT_TASK_SIMULATED_DURATION_MS;
3353
- // If subtasks are defined, split progress evenly
3354
- const subtaskCount = Array.isArray(cv === null || cv === void 0 ? void 0 : cv.subtasks) ? cv.subtasks.length : 1;
3355
- const completedSubtasks = Array.isArray(cv === null || cv === void 0 ? void 0 : cv.subtasks)
3356
- ? cv.subtasks.filter((s) => s.done || s.completed).length
3357
- : 0;
3358
- // Progress from completed subtasks
3359
- const subtaskProgress = subtaskCount > 0 ? completedSubtasks / subtaskCount : 0;
3360
- // Progress from elapsed time for current subtask
3361
- const timeProgress = Math.min(elapsedMs / totalMs, 1);
3362
- // Combine: completed subtasks + time progress for current subtask
3363
- percentRaw = Math.min(subtaskProgress + (1 / subtaskCount) * timeProgress, 1);
3364
- if (status === 'FINISHED')
3365
- percentRaw = 1;
3366
- if (status === 'ERROR')
3367
- percentRaw = 0;
3368
- }
3369
- // Clamp to [0,1]
3370
- let percent = Number(percentRaw) || 0;
3371
- if (percent < 0)
3372
- percent = 0;
3373
- if (percent > 1)
3374
- percent = 1;
3375
- // Build a short message: prefer explicit tldr.message, then common summary/message fields, then errors/warnings, then status
3376
- const messageFromResult = (_k = (_j = (_h = (_g = cv === null || cv === void 0 ? void 0 : cv.tldr) === null || _g === void 0 ? void 0 : _g.message) !== null && _h !== void 0 ? _h : cv === null || cv === void 0 ? void 0 : cv.message) !== null && _j !== void 0 ? _j : cv === null || cv === void 0 ? void 0 : cv.summary) !== null && _k !== void 0 ? _k : cv === null || cv === void 0 ? void 0 : cv.statusMessage;
3377
- let message = messageFromResult;
3378
- if (!message) {
3379
- // If subtasks, show current subtask
3380
- if (Array.isArray(cv === null || cv === void 0 ? void 0 : cv.subtasks) && cv.subtasks.length > 0) {
3381
- const current = cv.subtasks.find((s) => !s.done && !s.completed);
3382
- if (current && current.title) {
3383
- message = `Working on ${current.title}`;
3384
- }
3385
- }
3386
- if (!message) {
3387
- if (errors.length) {
3388
- message = errors[errors.length - 1].message || 'Error';
3389
- }
3390
- else if (warnings.length) {
3391
- message = warnings[warnings.length - 1].message || 'Warning';
3392
- }
3393
- else if (status === 'FINISHED') {
3394
- message = 'Finished';
3395
- }
3396
- else if (status === 'ERROR') {
3397
- message = 'Error';
3398
- }
3399
- else {
3400
- message = 'Running';
3401
- }
3402
- }
3403
- }
3404
- return {
3405
- percent: percent,
3406
- message: message + ' (!!!fallback)',
3407
- };
3959
+ return resolveTaskTldr({
3960
+ customTldr: taskState.customTldr,
3961
+ currentValue: taskState.currentValue,
3962
+ status: taskState.status,
3963
+ createdAt,
3964
+ errors: taskState.errors,
3965
+ warnings: taskState.warnings,
3966
+ });
3408
3967
  },
3409
3968
  get createdAt() {
3410
3969
  return createdAt;
3411
3970
  // <- Note: [1] --||--
3412
3971
  },
3413
3972
  get updatedAt() {
3414
- return updatedAt;
3973
+ return taskState.updatedAt;
3415
3974
  // <- Note: [1] --||--
3416
3975
  },
3417
3976
  asPromise,
@@ -3419,19 +3978,19 @@ function createTask(options) {
3419
3978
  return partialResultSubject.asObservable();
3420
3979
  },
3421
3980
  get errors() {
3422
- return errors;
3981
+ return taskState.errors;
3423
3982
  // <- Note: [1] --||--
3424
3983
  },
3425
3984
  get warnings() {
3426
- return warnings;
3985
+ return taskState.warnings;
3427
3986
  // <- Note: [1] --||--
3428
3987
  },
3429
3988
  get llmCalls() {
3430
- return [...llmCalls, { foo: '!!! bar' }];
3989
+ return [...taskState.llmCalls, { foo: '!!! bar' }];
3431
3990
  // <- Note: [1] --||--
3432
3991
  },
3433
3992
  get currentValue() {
3434
- return currentValue;
3993
+ return taskState.currentValue;
3435
3994
  // <- Note: [1] --||--
3436
3995
  },
3437
3996
  };
@@ -4599,223 +5158,288 @@ const promptbookFetch = async (urlOrRequest, init) => {
4599
5158
  * @public exported from `@promptbook/core`
4600
5159
  */
4601
5160
  async function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
4602
- var _a;
4603
- const { fetch = promptbookFetch } = tools;
4604
5161
  const { knowledgeSourceContent } = knowledgeSource;
4605
- let { name } = knowledgeSource;
4606
- const { rootDirname = null,
4607
- // <- TODO: process.cwd() if running in Node.js
4608
- isVerbose = DEFAULT_IS_VERBOSE, } = options || {};
4609
- if (!name) {
4610
- name = knowledgeSourceContentToName(knowledgeSourceContent);
4611
- }
5162
+ const name = knowledgeSource.name || knowledgeSourceContentToName(knowledgeSourceContent);
5163
+ const { rootDirname = null, isVerbose = DEFAULT_IS_VERBOSE } = options || {};
4612
5164
  if (isValidUrl(knowledgeSourceContent)) {
4613
- const url = knowledgeSourceContent;
4614
- if (isVerbose) {
4615
- console.info(`📄 [1] "${name}" is available at "${url}"`);
4616
- }
4617
- const response = await fetch(url); // <- TODO: [🧠] Scraping and fetch proxy
4618
- const mimeType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
4619
- if (tools.fs === undefined || !url.endsWith('.pdf' /* <- TODO: [💵] */)) {
4620
- if (isVerbose) {
4621
- console.info(`📄 [2] "${name}" tools.fs is not available or URL is not a PDF.`);
4622
- }
4623
- return {
4624
- source: name,
4625
- filename: null,
4626
- url,
4627
- mimeType,
4628
- /*
4629
- TODO: [🥽]
4630
- > async asBlob() {
4631
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
4632
- > const content = await response.blob();
4633
- > return content;
4634
- > },
4635
- */
4636
- async asJson() {
4637
- // TODO: [👨🏻‍🤝‍👨🏻]
4638
- const content = await response.json();
4639
- return content;
4640
- },
4641
- async asText() {
4642
- // TODO: [👨🏻‍🤝‍👨🏻]
4643
- const content = await response.text();
4644
- return content;
4645
- },
4646
- };
4647
- }
4648
- const basename = url.split('/').pop() || titleToName(url);
4649
- const hash = sha256(hexEncoder.parse(url)).toString( /* hex */);
4650
- // <- TODO: [🥬] Encapsulate sha256 to some private utility function
4651
- const rootDirname = join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
4652
- const filepath = join(...nameToSubfolderPath(hash /* <- TODO: [🎎] Maybe add some SHA256 prefix */), `${basename.substring(0, MAX_FILENAME_LENGTH)}.${mimeTypeToExtension(mimeType)}`);
4653
- // Note: Try to create cache directory, but don't fail if filesystem has issues
4654
- try {
4655
- await tools.fs.mkdir(dirname(join(rootDirname, filepath)), { recursive: true });
4656
- }
4657
- catch (error) {
4658
- if (isVerbose) {
4659
- console.info(`📄 [3] "${name}" error creating cache directory`);
4660
- }
4661
- // Note: If we can't create cache directory, we'll handle it when trying to write the file
4662
- // This handles read-only filesystems, permission issues, and missing parent directories
4663
- if (error instanceof Error &&
4664
- (error.message.includes('EROFS') ||
4665
- error.message.includes('read-only') ||
4666
- error.message.includes('EACCES') ||
4667
- error.message.includes('EPERM') ||
4668
- error.message.includes('ENOENT'))) ;
4669
- else {
4670
- // Re-throw other unexpected errors
4671
- throw error;
4672
- }
4673
- }
4674
- const fileContent = Buffer.from(await response.arrayBuffer());
4675
- if (fileContent.length > DEFAULT_MAX_FILE_SIZE /* <- TODO: Allow to pass different value to remote server */) {
4676
- throw new LimitReachedError(`File is too large (${Math.round(fileContent.length / 1024 / 1024)}MB). Maximum allowed size is ${Math.round(DEFAULT_MAX_FILE_SIZE / 1024 / 1024)}MB.`);
4677
- }
4678
- // Note: Try to cache the downloaded file, but don't fail if the filesystem is read-only
4679
- try {
4680
- await tools.fs.writeFile(join(rootDirname, filepath), fileContent);
4681
- }
4682
- catch (error) {
4683
- if (isVerbose) {
4684
- console.info(`📄 [4] "${name}" error writing cache file`);
4685
- }
4686
- // Note: If we can't write to cache, we'll process the file directly from memory
4687
- // This handles read-only filesystems like Vercel
4688
- if (error instanceof Error &&
4689
- (error.message.includes('EROFS') ||
4690
- error.message.includes('read-only') ||
4691
- error.message.includes('EACCES') ||
4692
- error.message.includes('EPERM') ||
4693
- error.message.includes('ENOENT'))) {
4694
- // Return a handler that works directly with the downloaded content
4695
- return {
4696
- source: name,
4697
- filename: null,
4698
- url,
4699
- mimeType,
4700
- async asJson() {
4701
- return JSON.parse(fileContent.toString('utf-8'));
4702
- },
4703
- async asText() {
4704
- return fileContent.toString('utf-8');
4705
- },
4706
- };
4707
- }
4708
- else {
4709
- // Re-throw other unexpected errors
4710
- throw error;
4711
- }
4712
- }
4713
- // TODO: [💵] Check the file security
4714
- // TODO: [🧹][🧠] Delete the file after the scraping is done
4715
- if (isVerbose) {
4716
- console.info(`📄 [5] "${name}" cached at "${join(rootDirname, filepath)}"`);
4717
- }
4718
- return makeKnowledgeSourceHandler({ name, knowledgeSourceContent: filepath }, tools, {
4719
- ...options,
4720
- rootDirname,
4721
- });
4722
- }
4723
- else if (isValidFilePath(knowledgeSourceContent)) {
4724
- if (tools.fs === undefined) {
4725
- throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
4726
- // <- TODO: [🧠] What is the best error type here`
4727
- }
4728
- if (rootDirname === null) {
4729
- throw new EnvironmentMismatchError('Can not import file knowledge in non-file pipeline');
4730
- // <- TODO: [🧠] What is the best error type here`
4731
- }
4732
- const filename = isAbsolute(knowledgeSourceContent)
4733
- ? knowledgeSourceContent
4734
- : join(rootDirname, knowledgeSourceContent).split('\\').join('/');
4735
- if (isVerbose) {
4736
- console.info(`📄 [6] "${name}" is a valid file "${filename}"`);
4737
- }
4738
- const fileExtension = getFileExtension(filename);
4739
- const mimeType = extensionToMimeType(fileExtension || '');
4740
- if (!(await isFileExisting(filename, tools.fs))) {
4741
- throw new NotFoundError(spaceTrim$1((block) => `
4742
- Can not make source handler for file which does not exist:
4743
-
4744
- File:
4745
- ${block(knowledgeSourceContent)}
4746
-
4747
- Full file path:
4748
- ${block(filename)}
4749
- `));
4750
- }
4751
- // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
4752
- return {
4753
- source: name,
4754
- filename,
4755
- url: null,
4756
- mimeType,
4757
- /*
4758
- TODO: [🥽]
4759
- > async asBlob() {
4760
- > const content = await tools.fs!.readFile(filename);
4761
- > return new Blob(
4762
- > [
4763
- > content,
4764
- > // <- TODO: [🥽] This is NOT tested, test it
4765
- > ],
4766
- > { type: mimeType },
4767
- > );
4768
- > },
4769
- */
4770
- async asJson() {
4771
- return jsonParse(await tools.fs.readFile(filename, 'utf-8'));
4772
- },
4773
- async asText() {
4774
- return await tools.fs.readFile(filename, 'utf-8');
4775
- },
4776
- };
5165
+ return makeUrlKnowledgeSourceHandler(knowledgeSourceContent, name, tools, options, isVerbose);
4777
5166
  }
4778
- else {
4779
- if (isVerbose) {
4780
- console.info(`📄 [7] "${name}" is just a explicit string text with a knowledge source`);
4781
- console.info('---');
4782
- console.info(knowledgeSourceContent);
4783
- console.info('---');
4784
- }
4785
- return {
4786
- source: name,
4787
- filename: null,
4788
- url: null,
4789
- mimeType: 'text/markdown',
4790
- asText() {
4791
- return knowledgeSource.knowledgeSourceContent;
4792
- },
4793
- asJson() {
4794
- throw new UnexpectedError('Did not expect that `markdownScraper` would need to get the content `asJson`');
4795
- },
4796
- /*
4797
- TODO: [🥽]
4798
- > asBlob() {
4799
- > throw new UnexpectedError(
4800
- > 'Did not expect that `markdownScraper` would need to get the content `asBlob`',
4801
- > );
4802
- > },
4803
- */
4804
- };
5167
+ if (isValidFilePath(knowledgeSourceContent)) {
5168
+ return makeFileKnowledgeSourceHandler(knowledgeSourceContent, name, tools, rootDirname, isVerbose);
4805
5169
  }
5170
+ return makeInlineTextKnowledgeSourceHandler(knowledgeSourceContent, name, isVerbose);
4806
5171
  }
4807
-
4808
5172
  /**
4809
- * Prepares the knowledge pieces
4810
- *
4811
- * @see https://github.com/webgptorg/promptbook/discussions/41
5173
+ * Creates a source handler for URL-based knowledge.
4812
5174
  *
4813
- * @public exported from `@promptbook/core`
5175
+ * @private internal utility of `makeKnowledgeSourceHandler`
4814
5176
  */
4815
- async function prepareKnowledgePieces(knowledgeSources, tools, options) {
4816
- const { maxParallelCount = DEFAULT_MAX_PARALLEL_COUNT, rootDirname, isVerbose = DEFAULT_IS_VERBOSE } = options;
4817
- const knowledgePreparedUnflatten = new Array(knowledgeSources.length);
4818
- await forEachAsync(knowledgeSources, { maxParallelCount }, async (knowledgeSource, index) => {
5177
+ async function makeUrlKnowledgeSourceHandler(url, name, tools, options, isVerbose) {
5178
+ var _a;
5179
+ const { fetch = promptbookFetch } = tools;
5180
+ if (isVerbose) {
5181
+ console.info(`📄 [1] "${name}" is available at "${url}"`);
5182
+ }
5183
+ const response = await fetch(url); // <- TODO: [🧠] Scraping and fetch proxy
5184
+ const mimeType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
5185
+ if (tools.fs === undefined || !url.endsWith('.pdf' /* <- TODO: [💵] */)) {
5186
+ return makeRemoteResponseKnowledgeSourceHandler(name, url, mimeType, response, isVerbose);
5187
+ }
5188
+ return cachePdfKnowledgeSourceHandler(url, name, mimeType, response, tools, options, isVerbose);
5189
+ }
5190
+ /**
5191
+ * Creates a source handler that reads directly from a fetched response.
5192
+ *
5193
+ * @private internal utility of `makeKnowledgeSourceHandler`
5194
+ */
5195
+ function makeRemoteResponseKnowledgeSourceHandler(name, url, mimeType, response, isVerbose) {
5196
+ if (isVerbose) {
5197
+ console.info(`📄 [2] "${name}" tools.fs is not available or URL is not a PDF.`);
5198
+ }
5199
+ return {
5200
+ source: name,
5201
+ filename: null,
5202
+ url,
5203
+ mimeType,
5204
+ /*
5205
+ TODO: [🥽]
5206
+ > async asBlob() {
5207
+ > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
5208
+ > const content = await response.blob();
5209
+ > return content;
5210
+ > },
5211
+ */
5212
+ async asJson() {
5213
+ // TODO: [👨🏻‍🤝‍👨🏻]
5214
+ const content = await response.json();
5215
+ return content;
5216
+ },
5217
+ async asText() {
5218
+ // TODO: [👨🏻‍🤝‍👨🏻]
5219
+ const content = await response.text();
5220
+ return content;
5221
+ },
5222
+ };
5223
+ }
5224
+ /**
5225
+ * Downloads a PDF knowledge source into cache when possible and falls back to in-memory content otherwise.
5226
+ *
5227
+ * @private internal utility of `makeKnowledgeSourceHandler`
5228
+ */
5229
+ async function cachePdfKnowledgeSourceHandler(url, name, mimeType, response, tools, options, isVerbose) {
5230
+ const rootDirname = join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
5231
+ const filepath = createDownloadedKnowledgeSourceFilepath(url, mimeType);
5232
+ const fullFilepath = join(rootDirname, filepath);
5233
+ await createCacheDirectoryIfPossible(name, fullFilepath, tools, isVerbose);
5234
+ const fileContent = Buffer.from(await response.arrayBuffer());
5235
+ if (fileContent.length > DEFAULT_MAX_FILE_SIZE /* <- TODO: Allow to pass different value to remote server */) {
5236
+ throw new LimitReachedError(`File is too large (${Math.round(fileContent.length / 1024 / 1024)}MB). Maximum allowed size is ${Math.round(DEFAULT_MAX_FILE_SIZE / 1024 / 1024)}MB.`);
5237
+ }
5238
+ const isCached = await writeCacheFileIfPossible(name, fullFilepath, fileContent, tools, isVerbose);
5239
+ if (!isCached) {
5240
+ return makeBufferedKnowledgeSourceHandler(name, url, mimeType, fileContent);
5241
+ }
5242
+ // TODO: [💵] Check the file security
5243
+ // TODO: [🧹][🧠] Delete the file after the scraping is done
5244
+ if (isVerbose) {
5245
+ console.info(`📄 [5] "${name}" cached at "${fullFilepath}"`);
5246
+ }
5247
+ return makeKnowledgeSourceHandler({ name, knowledgeSourceContent: filepath }, tools, {
5248
+ ...options,
5249
+ rootDirname,
5250
+ });
5251
+ }
5252
+ /**
5253
+ * Builds a stable cache filepath for a downloaded knowledge source.
5254
+ *
5255
+ * @private internal utility of `makeKnowledgeSourceHandler`
5256
+ */
5257
+ function createDownloadedKnowledgeSourceFilepath(url, mimeType) {
5258
+ const basename = url.split('/').pop() || titleToName(url);
5259
+ const hash = sha256(hexEncoder.parse(url)).toString( /* hex */);
5260
+ // <- TODO: [🥬] Encapsulate sha256 to some private utility function
5261
+ return join(...nameToSubfolderPath(hash /* <- TODO: [🎎] Maybe add some SHA256 prefix */), `${basename.substring(0, MAX_FILENAME_LENGTH)}.${mimeTypeToExtension(mimeType)}`);
5262
+ }
5263
+ /**
5264
+ * Tries to create the cache directory needed for a downloaded knowledge source.
5265
+ *
5266
+ * @private internal utility of `makeKnowledgeSourceHandler`
5267
+ */
5268
+ async function createCacheDirectoryIfPossible(name, fullFilepath, tools, isVerbose) {
5269
+ try {
5270
+ await tools.fs.mkdir(dirname(fullFilepath), { recursive: true });
5271
+ }
5272
+ catch (error) {
5273
+ if (isVerbose) {
5274
+ console.info(`📄 [3] "${name}" error creating cache directory`);
5275
+ }
5276
+ // Note: If we can't create cache directory, we'll handle it when trying to write the file
5277
+ // This handles read-only filesystems, permission issues, and missing parent directories
5278
+ if (!isIgnorableCacheFilesystemError(error)) {
5279
+ throw error;
5280
+ }
5281
+ }
5282
+ }
5283
+ /**
5284
+ * Tries to write downloaded content into cache and reports whether the cache was usable.
5285
+ *
5286
+ * @private internal utility of `makeKnowledgeSourceHandler`
5287
+ */
5288
+ async function writeCacheFileIfPossible(name, fullFilepath, fileContent, tools, isVerbose) {
5289
+ // Note: Try to cache the downloaded file, but don't fail if the filesystem is read-only
5290
+ try {
5291
+ await tools.fs.writeFile(fullFilepath, fileContent);
5292
+ return true;
5293
+ }
5294
+ catch (error) {
5295
+ if (isVerbose) {
5296
+ console.info(`📄 [4] "${name}" error writing cache file`);
5297
+ }
5298
+ // Note: If we can't write to cache, we'll process the file directly from memory
5299
+ // This handles read-only filesystems like Vercel
5300
+ if (isIgnorableCacheFilesystemError(error)) {
5301
+ return false;
5302
+ }
5303
+ throw error;
5304
+ }
5305
+ }
5306
+ /**
5307
+ * Detects filesystem errors that should not fail optional caching.
5308
+ *
5309
+ * @private internal utility of `makeKnowledgeSourceHandler`
5310
+ */
5311
+ function isIgnorableCacheFilesystemError(error) {
5312
+ return (error instanceof Error &&
5313
+ (error.message.includes('EROFS') ||
5314
+ error.message.includes('read-only') ||
5315
+ error.message.includes('EACCES') ||
5316
+ error.message.includes('EPERM') ||
5317
+ error.message.includes('ENOENT')));
5318
+ }
5319
+ /**
5320
+ * Creates a source handler backed by already downloaded file content kept in memory.
5321
+ *
5322
+ * @private internal utility of `makeKnowledgeSourceHandler`
5323
+ */
5324
+ function makeBufferedKnowledgeSourceHandler(name, url, mimeType, fileContent) {
5325
+ return {
5326
+ source: name,
5327
+ filename: null,
5328
+ url,
5329
+ mimeType,
5330
+ async asJson() {
5331
+ return JSON.parse(fileContent.toString('utf-8'));
5332
+ },
5333
+ async asText() {
5334
+ return fileContent.toString('utf-8');
5335
+ },
5336
+ };
5337
+ }
5338
+ /**
5339
+ * Creates a source handler for file-based knowledge.
5340
+ *
5341
+ * @private internal utility of `makeKnowledgeSourceHandler`
5342
+ */
5343
+ async function makeFileKnowledgeSourceHandler(knowledgeSourceContent, name, tools, rootDirname, isVerbose) {
5344
+ if (tools.fs === undefined) {
5345
+ throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
5346
+ // <- TODO: [🧠] What is the best error type here`
5347
+ }
5348
+ if (rootDirname === null) {
5349
+ throw new EnvironmentMismatchError('Can not import file knowledge in non-file pipeline');
5350
+ // <- TODO: [🧠] What is the best error type here`
5351
+ }
5352
+ const filename = isAbsolute(knowledgeSourceContent)
5353
+ ? knowledgeSourceContent
5354
+ : join(rootDirname, knowledgeSourceContent).split('\\').join('/');
5355
+ if (isVerbose) {
5356
+ console.info(`📄 [6] "${name}" is a valid file "${filename}"`);
5357
+ }
5358
+ const fileExtension = getFileExtension(filename);
5359
+ const mimeType = extensionToMimeType(fileExtension || '');
5360
+ if (!(await isFileExisting(filename, tools.fs))) {
5361
+ throw new NotFoundError(spaceTrim$1((block) => `
5362
+ Can not make source handler for file which does not exist:
5363
+
5364
+ File:
5365
+ ${block(knowledgeSourceContent)}
5366
+
5367
+ Full file path:
5368
+ ${block(filename)}
5369
+ `));
5370
+ }
5371
+ // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
5372
+ return {
5373
+ source: name,
5374
+ filename,
5375
+ url: null,
5376
+ mimeType,
5377
+ /*
5378
+ TODO: [🥽]
5379
+ > async asBlob() {
5380
+ > const content = await tools.fs!.readFile(filename);
5381
+ > return new Blob(
5382
+ > [
5383
+ > content,
5384
+ > // <- TODO: [🥽] This is NOT tested, test it
5385
+ > ],
5386
+ > { type: mimeType },
5387
+ > );
5388
+ > },
5389
+ */
5390
+ async asJson() {
5391
+ return jsonParse(await tools.fs.readFile(filename, 'utf-8'));
5392
+ },
5393
+ async asText() {
5394
+ return await tools.fs.readFile(filename, 'utf-8');
5395
+ },
5396
+ };
5397
+ }
5398
+ /**
5399
+ * Creates a source handler for inline text knowledge.
5400
+ *
5401
+ * @private internal utility of `makeKnowledgeSourceHandler`
5402
+ */
5403
+ function makeInlineTextKnowledgeSourceHandler(knowledgeSourceContent, name, isVerbose) {
5404
+ if (isVerbose) {
5405
+ console.info(`📄 [7] "${name}" is just a explicit string text with a knowledge source`);
5406
+ console.info('---');
5407
+ console.info(knowledgeSourceContent);
5408
+ console.info('---');
5409
+ }
5410
+ return {
5411
+ source: name,
5412
+ filename: null,
5413
+ url: null,
5414
+ mimeType: 'text/markdown',
5415
+ asText() {
5416
+ return knowledgeSourceContent;
5417
+ },
5418
+ asJson() {
5419
+ throw new UnexpectedError('Did not expect that `markdownScraper` would need to get the content `asJson`');
5420
+ },
5421
+ /*
5422
+ TODO: [🥽]
5423
+ > asBlob() {
5424
+ > throw new UnexpectedError(
5425
+ > 'Did not expect that `markdownScraper` would need to get the content `asBlob`',
5426
+ > );
5427
+ > },
5428
+ */
5429
+ };
5430
+ }
5431
+
5432
+ /**
5433
+ * Prepares the knowledge pieces
5434
+ *
5435
+ * @see https://github.com/webgptorg/promptbook/discussions/41
5436
+ *
5437
+ * @public exported from `@promptbook/core`
5438
+ */
5439
+ async function prepareKnowledgePieces(knowledgeSources, tools, options) {
5440
+ const { maxParallelCount = DEFAULT_MAX_PARALLEL_COUNT, rootDirname, isVerbose = DEFAULT_IS_VERBOSE } = options;
5441
+ const knowledgePreparedUnflatten = new Array(knowledgeSources.length);
5442
+ await forEachAsync(knowledgeSources, { maxParallelCount }, async (knowledgeSource, index) => {
4819
5443
  try {
4820
5444
  let partialPieces = null;
4821
5445
  const sourceHandler = await makeKnowledgeSourceHandler(knowledgeSource, tools, { rootDirname, isVerbose });
@@ -6087,112 +6711,10 @@ function validatePromptResult(options) {
6087
6711
  }
6088
6712
  }
6089
6713
 
6090
- /**
6091
- * Executes a pipeline task with multiple attempts, including joker and retry logic. Handles different task types
6092
- * (prompt, script, dialog, etc.), applies postprocessing, checks expectations, and updates the execution report.
6093
- * Throws errors if execution fails after all attempts.
6094
- *
6095
- * @param options - The options for execution, including task, parameters, pipeline, and configuration.
6096
- * @returns The result string of the executed task.
6097
- *
6098
- * @private internal utility of `createPipelineExecutor`
6099
- */
6100
- async function executeAttempts(options) {
6101
- const $ongoingTaskResult = createOngoingTaskResult();
6102
- const llmTools = getSingleLlmExecutionTools(options.tools.llm);
6103
- attempts: for (let attemptIndex = -options.jokerParameterNames.length; attemptIndex < options.maxAttempts; attemptIndex++) {
6104
- const attempt = createAttemptDescriptor({
6105
- attemptIndex,
6106
- jokerParameterNames: options.jokerParameterNames,
6107
- pipelineIdentification: options.pipelineIdentification,
6108
- });
6109
- resetAttemptExecutionState($ongoingTaskResult);
6110
- try {
6111
- await executeSingleAttempt({
6112
- attempt,
6113
- options,
6114
- llmTools,
6115
- $ongoingTaskResult,
6116
- });
6117
- break attempts;
6118
- }
6119
- catch (error) {
6120
- if (!(error instanceof ExpectError)) {
6121
- throw error;
6122
- }
6123
- recordFailedAttempt({
6124
- error,
6125
- attemptIndex,
6126
- onProgress: options.onProgress,
6127
- $ongoingTaskResult,
6128
- });
6129
- }
6130
- finally {
6131
- reportPromptExecution({
6132
- attempt,
6133
- task: options.task,
6134
- $executionReport: options.$executionReport,
6135
- logLlmCall: options.logLlmCall,
6136
- $ongoingTaskResult,
6137
- });
6138
- }
6139
- throwIfFinalAttemptFailed({
6140
- attemptIndex,
6141
- maxAttempts: options.maxAttempts,
6142
- maxExecutionAttempts: options.maxExecutionAttempts,
6143
- pipelineIdentification: options.pipelineIdentification,
6144
- $ongoingTaskResult,
6145
- });
6146
- }
6147
- return getSuccessfulResultString({
6148
- pipelineIdentification: options.pipelineIdentification,
6149
- $ongoingTaskResult,
6150
- });
6151
- }
6152
- /**
6153
- * Creates mutable attempt state for one task execution lifecycle.
6154
- */
6155
- function createOngoingTaskResult() {
6156
- return {
6157
- $result: null,
6158
- $resultString: null,
6159
- $expectError: null,
6160
- $scriptPipelineExecutionErrors: [],
6161
- $failedResults: [],
6162
- };
6163
- }
6164
- /**
6165
- * Resolves the bookkeeping for one loop iteration, including joker lookup.
6166
- */
6167
- function createAttemptDescriptor(options) {
6168
- const { attemptIndex, jokerParameterNames, pipelineIdentification } = options;
6169
- const isJokerAttempt = attemptIndex < 0;
6170
- const jokerParameterName = isJokerAttempt
6171
- ? jokerParameterNames[jokerParameterNames.length + attemptIndex]
6172
- : undefined;
6173
- if (isJokerAttempt && !jokerParameterName) {
6174
- throw new UnexpectedError(spaceTrim$1((block) => `
6175
- Joker not found in attempt ${attemptIndex}
6176
-
6177
- ${block(pipelineIdentification)}
6178
- `));
6179
- }
6180
- return {
6181
- attemptIndex,
6182
- isJokerAttempt,
6183
- jokerParameterName,
6184
- };
6185
- }
6186
- /**
6187
- * Clears the per-attempt result slots while preserving cumulative failure history.
6188
- */
6189
- function resetAttemptExecutionState($ongoingTaskResult) {
6190
- $ongoingTaskResult.$result = null;
6191
- $ongoingTaskResult.$resultString = null;
6192
- $ongoingTaskResult.$expectError = null;
6193
- }
6194
6714
  /**
6195
6715
  * Executes one loop iteration, from joker resolution or task execution through validation.
6716
+ *
6717
+ * @private function of `executeAttempts`
6196
6718
  */
6197
6719
  async function executeSingleAttempt(options) {
6198
6720
  const { attempt, options: executeAttemptsOptions, llmTools, $ongoingTaskResult } = options;
@@ -6507,11 +7029,15 @@ function validateAttemptResult(options) {
6507
7029
  // Update the result string in case format processing modified it (e.g., JSON extraction)
6508
7030
  $ongoingTaskResult.$resultString = validationResult.processedResultString;
6509
7031
  }
7032
+
6510
7033
  /**
6511
- * Stores one failed attempt and reports the expectation error upstream.
7034
+ * Stores one failed attempt, reports the expectation error, and throws the aggregated retry error after the final
7035
+ * regular attempt.
7036
+ *
7037
+ * @private function of `executeAttempts`
6512
7038
  */
6513
- function recordFailedAttempt(options) {
6514
- const { error, attemptIndex, onProgress, $ongoingTaskResult } = options;
7039
+ function handleAttemptFailure(options) {
7040
+ const { error, attemptIndex, maxAttempts, maxExecutionAttempts, onProgress, pipelineIdentification, $ongoingTaskResult, } = options;
6515
7041
  $ongoingTaskResult.$expectError = error;
6516
7042
  $ongoingTaskResult.$failedResults.push({
6517
7043
  attemptIndex,
@@ -6521,39 +7047,7 @@ function recordFailedAttempt(options) {
6521
7047
  onProgress({
6522
7048
  errors: [error],
6523
7049
  });
6524
- }
6525
- /**
6526
- * Appends the prompt execution report for prompt-task attempts.
6527
- */
6528
- function reportPromptExecution(options) {
6529
- const { attempt, task, $executionReport, logLlmCall, $ongoingTaskResult } = options;
6530
- if (attempt.isJokerAttempt || task.taskType !== 'PROMPT_TASK' || !$ongoingTaskResult.$prompt) {
6531
- return;
6532
- }
6533
- // Note: [2] When some expected parameter is not defined, error will occur in templateParameters
6534
- // In that case we don’t want to make a report about it because it’s not a llm execution error
6535
- const executionPromptReport = {
6536
- prompt: {
6537
- ...$ongoingTaskResult.$prompt,
6538
- // <- TODO: [🧠] How to pick everyhing except `pipelineUrl`
6539
- },
6540
- result: $ongoingTaskResult.$result || undefined,
6541
- error: $ongoingTaskResult.$expectError === null ? undefined : serializeError($ongoingTaskResult.$expectError),
6542
- };
6543
- $executionReport.promptExecutions.push(executionPromptReport);
6544
- if (logLlmCall) {
6545
- logLlmCall({
6546
- modelName: 'model' /* <- TODO: How to get model name from the report */,
6547
- report: executionPromptReport,
6548
- });
6549
- }
6550
- }
6551
- /**
6552
- * Throws the aggregated retry error after the last regular attempt fails expectations.
6553
- */
6554
- function throwIfFinalAttemptFailed(options) {
6555
- const { attemptIndex, maxAttempts, maxExecutionAttempts, pipelineIdentification, $ongoingTaskResult } = options;
6556
- if ($ongoingTaskResult.$expectError === null || attemptIndex !== maxAttempts - 1) {
7050
+ if (attemptIndex !== maxAttempts - 1) {
6557
7051
  return;
6558
7052
  }
6559
7053
  throw new PipelineExecutionError(spaceTrim$1((block) => {
@@ -6584,7 +7078,9 @@ function createFailuresSummary($failedResults) {
6584
7078
  ${block(quoteMultilineText(((_b = failure.error) === null || _b === void 0 ? void 0 : _b.message) || ''))}
6585
7079
 
6586
7080
  Result:
6587
- ${block(failure.result === null ? 'null' : quoteMultilineText(spaceTrim$1(failure.result)))}
7081
+ ${block(failure.result === null
7082
+ ? 'null'
7083
+ : quoteMultilineText(spaceTrim$1(failure.result)))}
6588
7084
  `;
6589
7085
  }))
6590
7086
  .join('\n\n---\n\n');
@@ -6598,6 +7094,136 @@ function quoteMultilineText(text) {
6598
7094
  .map((line) => `> ${line}`)
6599
7095
  .join('\n');
6600
7096
  }
7097
+
7098
+ /**
7099
+ * Appends the prompt execution report for prompt-task attempts.
7100
+ *
7101
+ * @private function of `executeAttempts`
7102
+ */
7103
+ function reportPromptExecution(options) {
7104
+ const { attempt, task, $executionReport, logLlmCall, $ongoingTaskResult } = options;
7105
+ if (attempt.isJokerAttempt || task.taskType !== 'PROMPT_TASK' || !$ongoingTaskResult.$prompt) {
7106
+ return;
7107
+ }
7108
+ // Note: [2] When some expected parameter is not defined, error will occur in templateParameters
7109
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
7110
+ const executionPromptReport = {
7111
+ prompt: {
7112
+ ...$ongoingTaskResult.$prompt,
7113
+ // <- TODO: [🧠] How to pick everyhing except `pipelineUrl`
7114
+ },
7115
+ result: $ongoingTaskResult.$result || undefined,
7116
+ error: $ongoingTaskResult.$expectError === null ? undefined : serializeError($ongoingTaskResult.$expectError),
7117
+ };
7118
+ $executionReport.promptExecutions.push(executionPromptReport);
7119
+ if (logLlmCall) {
7120
+ logLlmCall({
7121
+ modelName: 'model' /* <- TODO: How to get model name from the report */,
7122
+ report: executionPromptReport,
7123
+ });
7124
+ }
7125
+ }
7126
+
7127
+ /**
7128
+ * Executes a pipeline task with multiple attempts, including joker and retry logic. Handles different task types
7129
+ * (prompt, script, dialog, etc.), applies postprocessing, checks expectations, and updates the execution report.
7130
+ * Throws errors if execution fails after all attempts.
7131
+ *
7132
+ * @param options - The options for execution, including task, parameters, pipeline, and configuration.
7133
+ * @returns The result string of the executed task.
7134
+ *
7135
+ * @private internal utility of `createPipelineExecutor`
7136
+ */
7137
+ async function executeAttempts(options) {
7138
+ const $ongoingTaskResult = createOngoingTaskResult();
7139
+ const llmTools = getSingleLlmExecutionTools(options.tools.llm);
7140
+ attempts: for (let attemptIndex = -options.jokerParameterNames.length; attemptIndex < options.maxAttempts; attemptIndex++) {
7141
+ const attempt = createAttemptDescriptor({
7142
+ attemptIndex,
7143
+ jokerParameterNames: options.jokerParameterNames,
7144
+ pipelineIdentification: options.pipelineIdentification,
7145
+ });
7146
+ resetAttemptExecutionState($ongoingTaskResult);
7147
+ try {
7148
+ await executeSingleAttempt({
7149
+ attempt,
7150
+ options,
7151
+ llmTools,
7152
+ $ongoingTaskResult,
7153
+ });
7154
+ break attempts;
7155
+ }
7156
+ catch (error) {
7157
+ if (!(error instanceof ExpectError)) {
7158
+ throw error;
7159
+ }
7160
+ handleAttemptFailure({
7161
+ error,
7162
+ attemptIndex,
7163
+ maxAttempts: options.maxAttempts,
7164
+ maxExecutionAttempts: options.maxExecutionAttempts,
7165
+ onProgress: options.onProgress,
7166
+ pipelineIdentification: options.pipelineIdentification,
7167
+ $ongoingTaskResult,
7168
+ });
7169
+ }
7170
+ finally {
7171
+ reportPromptExecution({
7172
+ attempt,
7173
+ task: options.task,
7174
+ $executionReport: options.$executionReport,
7175
+ logLlmCall: options.logLlmCall,
7176
+ $ongoingTaskResult,
7177
+ });
7178
+ }
7179
+ }
7180
+ return getSuccessfulResultString({
7181
+ pipelineIdentification: options.pipelineIdentification,
7182
+ $ongoingTaskResult,
7183
+ });
7184
+ }
7185
+ /**
7186
+ * Creates mutable attempt state for one task execution lifecycle.
7187
+ */
7188
+ function createOngoingTaskResult() {
7189
+ return {
7190
+ $result: null,
7191
+ $resultString: null,
7192
+ $expectError: null,
7193
+ $scriptPipelineExecutionErrors: [],
7194
+ $failedResults: [],
7195
+ };
7196
+ }
7197
+ /**
7198
+ * Resolves the bookkeeping for one loop iteration, including joker lookup.
7199
+ */
7200
+ function createAttemptDescriptor(options) {
7201
+ const { attemptIndex, jokerParameterNames, pipelineIdentification } = options;
7202
+ const isJokerAttempt = attemptIndex < 0;
7203
+ const jokerParameterName = isJokerAttempt
7204
+ ? jokerParameterNames[jokerParameterNames.length + attemptIndex]
7205
+ : undefined;
7206
+ if (isJokerAttempt && !jokerParameterName) {
7207
+ throw new UnexpectedError(spaceTrim$1((block) => `
7208
+ Joker not found in attempt ${attemptIndex}
7209
+
7210
+ ${block(pipelineIdentification)}
7211
+ `));
7212
+ }
7213
+ return {
7214
+ attemptIndex,
7215
+ isJokerAttempt,
7216
+ jokerParameterName,
7217
+ };
7218
+ }
7219
+ /**
7220
+ * Clears the per-attempt result slots while preserving cumulative failure history.
7221
+ */
7222
+ function resetAttemptExecutionState($ongoingTaskResult) {
7223
+ $ongoingTaskResult.$result = null;
7224
+ $ongoingTaskResult.$resultString = null;
7225
+ $ongoingTaskResult.$expectError = null;
7226
+ }
6601
7227
  /**
6602
7228
  * Returns the successful result string or raises an unexpected internal-state error.
6603
7229
  */