@promptbook/documents 0.112.0-72 → 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 (161) hide show
  1. package/esm/index.es.js +1425 -799
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/src/book-components/Chat/save/_common/chatExportRendering.d.ts +28 -0
  4. package/esm/src/book-components/Chat/save/_common/getPromptbookExportBranding.d.ts +18 -0
  5. package/esm/src/book-components/Chat/save/html/htmlSaveFormatDefinition.d.ts +1 -1
  6. package/esm/src/book-components/Chat/save/html/htmlSaveFormatDefinition.test.d.ts +1 -0
  7. package/esm/src/book-components/Chat/save/index.d.ts +4 -4
  8. package/esm/src/book-components/Chat/save/markdown/mdSaveFormatDefinition.d.ts +1 -1
  9. package/esm/src/book-components/Chat/save/markdown/mdSaveFormatDefinition.test.d.ts +1 -0
  10. package/esm/src/book-components/Chat/save/pdf/buildChatPdf.d.ts +3 -2
  11. package/esm/src/book-components/Chat/save/pdf/pdfSaveFormatDefinition.d.ts +2 -2
  12. package/esm/src/book-components/Chat/save/pdf/pdfSaveFormatDefinition.test.d.ts +1 -0
  13. package/esm/src/book-components/Chat/save/react/reactSaveFormatDefinition.test.d.ts +1 -0
  14. package/esm/src/book-components/Chat/utils/renderMarkdown.d.ts +26 -0
  15. package/esm/src/cli/cli-commands/agent/agentRunCliOptions.d.ts +2 -0
  16. package/esm/src/cli/cli-commands/agent/initializeAgentRunnerCommand.d.ts +1 -0
  17. package/esm/src/cli/cli-commands/common/handleActionErrors.d.ts +9 -4
  18. package/esm/src/conversion/pipelineJsonToString/appendMarkdownBlock.d.ts +7 -0
  19. package/esm/src/conversion/pipelineJsonToString/createPipelineCommands.d.ts +7 -0
  20. package/esm/src/conversion/pipelineJsonToString/createPipelineIntroduction.d.ts +8 -0
  21. package/esm/src/conversion/pipelineJsonToString/createTaskSerialization.d.ts +23 -0
  22. package/esm/src/conversion/pipelineJsonToString/stringifyCommands.d.ts +7 -0
  23. package/esm/src/conversion/pipelineJsonToString/stringifyTask.d.ts +8 -0
  24. package/esm/src/conversion/pipelineJsonToString.test.d.ts +1 -0
  25. package/esm/src/execution/createPipelineExecutor/executeSingleAttempt.d.ts +31 -0
  26. package/esm/src/execution/createPipelineExecutor/handleAttemptFailure.d.ts +40 -0
  27. package/esm/src/execution/createPipelineExecutor/reportPromptExecution.d.ts +34 -0
  28. package/esm/src/execution/resolveTaskTldr.d.ts +32 -0
  29. package/esm/src/execution/resolveTaskTldr.test.d.ts +1 -0
  30. package/esm/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +22 -63
  31. package/esm/src/llm-providers/agent/AgentLlmExecutionToolsAgentKitRunner.d.ts +51 -0
  32. package/esm/src/llm-providers/agent/AgentLlmExecutionToolsOpenAiAssistantRunner.d.ts +43 -0
  33. package/esm/src/llm-providers/agent/AgentLlmExecutionToolsPromptPreparer.d.ts +41 -0
  34. package/esm/src/llm-providers/agent/emitAgentLlmExecutionToolsAssistantPreparationProgress.d.ts +26 -0
  35. package/esm/src/llm-providers/openai/OpenAiAgentKitExecutionTools.d.ts +16 -93
  36. package/esm/src/llm-providers/openai/OpenAiAgentKitExecutionToolsInputBuilder.d.ts +41 -0
  37. package/esm/src/llm-providers/openai/OpenAiAgentKitExecutionToolsOutputTypeMapper.d.ts +56 -0
  38. package/esm/src/llm-providers/openai/OpenAiAgentKitExecutionToolsToolBuilder.d.ts +99 -0
  39. package/esm/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +24 -120
  40. package/esm/src/llm-providers/openai/OpenAiAssistantExecutionToolsProgressReporter.d.ts +62 -0
  41. package/esm/src/llm-providers/openai/OpenAiAssistantExecutionToolsPromptBuilder.d.ts +29 -0
  42. package/esm/src/llm-providers/openai/OpenAiAssistantExecutionToolsStreamRunner.d.ts +63 -0
  43. package/esm/src/llm-providers/openai/OpenAiAssistantExecutionToolsToolRunner.d.ts +89 -0
  44. package/esm/src/llm-providers/openai/OpenAiCompatibleExecutionTools.d.ts +9 -28
  45. package/esm/src/llm-providers/openai/OpenAiCompatibleModelCatalog.d.ts +31 -0
  46. package/esm/src/llm-providers/openai/OpenAiCompatibleNonChatPromptCaller.d.ts +57 -0
  47. package/esm/src/llm-providers/openai/OpenAiCompatibleRequestManager.d.ts +29 -0
  48. package/esm/src/llm-providers/openai/OpenAiVectorStoreFileBatchHandler.d.ts +51 -0
  49. package/esm/src/llm-providers/openai/OpenAiVectorStoreFileBatchPoller.d.ts +75 -0
  50. package/esm/src/llm-providers/openai/OpenAiVectorStoreHandler.d.ts +1 -98
  51. package/esm/src/llm-providers/openai/OpenAiVectorStoreKnowledgeSourcePreparer.d.ts +44 -0
  52. package/esm/src/llm-providers/openai/utils/OpenAiCompatibleChatProgressReporter.d.ts +86 -0
  53. package/esm/src/llm-providers/openai/utils/OpenAiCompatibleChatPromptBuilder.d.ts +57 -0
  54. package/esm/src/llm-providers/openai/utils/OpenAiCompatibleChatToolCaller.d.ts +57 -0
  55. package/esm/src/remote-server/startRemoteServer/RemoteServerRuntime.d.ts +14 -0
  56. package/esm/src/remote-server/startRemoteServer/SocketResponse.d.ts +9 -0
  57. package/esm/src/remote-server/startRemoteServer/StartRemoteServerConfiguration.d.ts +18 -0
  58. package/esm/src/remote-server/startRemoteServer/createRemoteServerExpressApp.d.ts +7 -0
  59. package/esm/src/remote-server/startRemoteServer/createRemoteServerHandle.d.ts +11 -0
  60. package/esm/src/remote-server/startRemoteServer/createSocketServer.d.ts +9 -0
  61. package/esm/src/remote-server/startRemoteServer/getExecutionToolsFromIdentification.d.ts +12 -0
  62. package/esm/src/remote-server/startRemoteServer/registerBookRoutes.d.ts +7 -0
  63. package/esm/src/remote-server/startRemoteServer/registerExecutionRoutes.d.ts +7 -0
  64. package/esm/src/remote-server/startRemoteServer/registerListModelsSocketHandler.d.ts +8 -0
  65. package/esm/src/remote-server/startRemoteServer/registerLoginRoute.d.ts +7 -0
  66. package/esm/src/remote-server/startRemoteServer/registerNotFoundRoute.d.ts +7 -0
  67. package/esm/src/remote-server/startRemoteServer/registerOpenAiCompatibleChatCompletionsRoute.d.ts +7 -0
  68. package/esm/src/remote-server/startRemoteServer/registerOpenApiRoutes.d.ts +7 -0
  69. package/esm/src/remote-server/startRemoteServer/registerPreparePipelineSocketHandler.d.ts +8 -0
  70. package/esm/src/remote-server/startRemoteServer/registerPromptSocketHandler.d.ts +8 -0
  71. package/esm/src/remote-server/startRemoteServer/registerRemoteServerHttpRoutes.d.ts +7 -0
  72. package/esm/src/remote-server/startRemoteServer/registerRemoteServerSocketHandlers.d.ts +8 -0
  73. package/esm/src/remote-server/startRemoteServer/registerServerIndexRoute.d.ts +7 -0
  74. package/esm/src/remote-server/startRemoteServer/resolveStartRemoteServerConfiguration.d.ts +8 -0
  75. package/esm/src/remote-server/startRemoteServer/respondToSocketRequest.d.ts +8 -0
  76. package/esm/src/remote-server/startRemoteServer/startListening.d.ts +9 -0
  77. package/esm/src/scrapers/_common/utils/makeKnowledgeSourceHandler.d.ts +14 -1
  78. package/esm/src/utils/serialization/serializeToPromptbookJavascript.d.ts +2 -0
  79. package/esm/src/utils/serialization/serializeToPromptbookJavascript.test.d.ts +1 -0
  80. package/esm/src/version.d.ts +1 -1
  81. package/package.json +2 -2
  82. package/umd/index.umd.js +1425 -799
  83. package/umd/index.umd.js.map +1 -1
  84. package/umd/src/book-components/Chat/save/_common/chatExportRendering.d.ts +28 -0
  85. package/umd/src/book-components/Chat/save/_common/getPromptbookExportBranding.d.ts +18 -0
  86. package/umd/src/book-components/Chat/save/html/htmlSaveFormatDefinition.d.ts +1 -1
  87. package/umd/src/book-components/Chat/save/html/htmlSaveFormatDefinition.test.d.ts +1 -0
  88. package/umd/src/book-components/Chat/save/index.d.ts +4 -4
  89. package/umd/src/book-components/Chat/save/markdown/mdSaveFormatDefinition.d.ts +1 -1
  90. package/umd/src/book-components/Chat/save/markdown/mdSaveFormatDefinition.test.d.ts +1 -0
  91. package/umd/src/book-components/Chat/save/pdf/buildChatPdf.d.ts +3 -2
  92. package/umd/src/book-components/Chat/save/pdf/pdfSaveFormatDefinition.d.ts +2 -2
  93. package/umd/src/book-components/Chat/save/pdf/pdfSaveFormatDefinition.test.d.ts +1 -0
  94. package/umd/src/book-components/Chat/save/react/reactSaveFormatDefinition.test.d.ts +1 -0
  95. package/umd/src/book-components/Chat/utils/renderMarkdown.d.ts +26 -0
  96. package/umd/src/cli/cli-commands/agent/agentRunCliOptions.d.ts +2 -0
  97. package/umd/src/cli/cli-commands/agent/initializeAgentRunnerCommand.d.ts +1 -0
  98. package/umd/src/cli/cli-commands/common/handleActionErrors.d.ts +9 -4
  99. package/umd/src/conversion/pipelineJsonToString/appendMarkdownBlock.d.ts +7 -0
  100. package/umd/src/conversion/pipelineJsonToString/createPipelineCommands.d.ts +7 -0
  101. package/umd/src/conversion/pipelineJsonToString/createPipelineIntroduction.d.ts +8 -0
  102. package/umd/src/conversion/pipelineJsonToString/createTaskSerialization.d.ts +23 -0
  103. package/umd/src/conversion/pipelineJsonToString/stringifyCommands.d.ts +7 -0
  104. package/umd/src/conversion/pipelineJsonToString/stringifyTask.d.ts +8 -0
  105. package/umd/src/conversion/pipelineJsonToString.test.d.ts +1 -0
  106. package/umd/src/execution/createPipelineExecutor/executeSingleAttempt.d.ts +31 -0
  107. package/umd/src/execution/createPipelineExecutor/handleAttemptFailure.d.ts +40 -0
  108. package/umd/src/execution/createPipelineExecutor/reportPromptExecution.d.ts +34 -0
  109. package/umd/src/execution/resolveTaskTldr.d.ts +32 -0
  110. package/umd/src/execution/resolveTaskTldr.test.d.ts +1 -0
  111. package/umd/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +22 -63
  112. package/umd/src/llm-providers/agent/AgentLlmExecutionToolsAgentKitRunner.d.ts +51 -0
  113. package/umd/src/llm-providers/agent/AgentLlmExecutionToolsOpenAiAssistantRunner.d.ts +43 -0
  114. package/umd/src/llm-providers/agent/AgentLlmExecutionToolsPromptPreparer.d.ts +41 -0
  115. package/umd/src/llm-providers/agent/emitAgentLlmExecutionToolsAssistantPreparationProgress.d.ts +26 -0
  116. package/umd/src/llm-providers/openai/OpenAiAgentKitExecutionTools.d.ts +16 -93
  117. package/umd/src/llm-providers/openai/OpenAiAgentKitExecutionToolsInputBuilder.d.ts +41 -0
  118. package/umd/src/llm-providers/openai/OpenAiAgentKitExecutionToolsOutputTypeMapper.d.ts +56 -0
  119. package/umd/src/llm-providers/openai/OpenAiAgentKitExecutionToolsToolBuilder.d.ts +99 -0
  120. package/umd/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +24 -120
  121. package/umd/src/llm-providers/openai/OpenAiAssistantExecutionToolsProgressReporter.d.ts +62 -0
  122. package/umd/src/llm-providers/openai/OpenAiAssistantExecutionToolsPromptBuilder.d.ts +29 -0
  123. package/umd/src/llm-providers/openai/OpenAiAssistantExecutionToolsStreamRunner.d.ts +63 -0
  124. package/umd/src/llm-providers/openai/OpenAiAssistantExecutionToolsToolRunner.d.ts +89 -0
  125. package/umd/src/llm-providers/openai/OpenAiCompatibleExecutionTools.d.ts +9 -28
  126. package/umd/src/llm-providers/openai/OpenAiCompatibleModelCatalog.d.ts +31 -0
  127. package/umd/src/llm-providers/openai/OpenAiCompatibleNonChatPromptCaller.d.ts +57 -0
  128. package/umd/src/llm-providers/openai/OpenAiCompatibleRequestManager.d.ts +29 -0
  129. package/umd/src/llm-providers/openai/OpenAiVectorStoreFileBatchHandler.d.ts +51 -0
  130. package/umd/src/llm-providers/openai/OpenAiVectorStoreFileBatchPoller.d.ts +75 -0
  131. package/umd/src/llm-providers/openai/OpenAiVectorStoreHandler.d.ts +1 -98
  132. package/umd/src/llm-providers/openai/OpenAiVectorStoreKnowledgeSourcePreparer.d.ts +44 -0
  133. package/umd/src/llm-providers/openai/utils/OpenAiCompatibleChatProgressReporter.d.ts +86 -0
  134. package/umd/src/llm-providers/openai/utils/OpenAiCompatibleChatPromptBuilder.d.ts +57 -0
  135. package/umd/src/llm-providers/openai/utils/OpenAiCompatibleChatToolCaller.d.ts +57 -0
  136. package/umd/src/remote-server/startRemoteServer/RemoteServerRuntime.d.ts +14 -0
  137. package/umd/src/remote-server/startRemoteServer/SocketResponse.d.ts +9 -0
  138. package/umd/src/remote-server/startRemoteServer/StartRemoteServerConfiguration.d.ts +18 -0
  139. package/umd/src/remote-server/startRemoteServer/createRemoteServerExpressApp.d.ts +7 -0
  140. package/umd/src/remote-server/startRemoteServer/createRemoteServerHandle.d.ts +11 -0
  141. package/umd/src/remote-server/startRemoteServer/createSocketServer.d.ts +9 -0
  142. package/umd/src/remote-server/startRemoteServer/getExecutionToolsFromIdentification.d.ts +12 -0
  143. package/umd/src/remote-server/startRemoteServer/registerBookRoutes.d.ts +7 -0
  144. package/umd/src/remote-server/startRemoteServer/registerExecutionRoutes.d.ts +7 -0
  145. package/umd/src/remote-server/startRemoteServer/registerListModelsSocketHandler.d.ts +8 -0
  146. package/umd/src/remote-server/startRemoteServer/registerLoginRoute.d.ts +7 -0
  147. package/umd/src/remote-server/startRemoteServer/registerNotFoundRoute.d.ts +7 -0
  148. package/umd/src/remote-server/startRemoteServer/registerOpenAiCompatibleChatCompletionsRoute.d.ts +7 -0
  149. package/umd/src/remote-server/startRemoteServer/registerOpenApiRoutes.d.ts +7 -0
  150. package/umd/src/remote-server/startRemoteServer/registerPreparePipelineSocketHandler.d.ts +8 -0
  151. package/umd/src/remote-server/startRemoteServer/registerPromptSocketHandler.d.ts +8 -0
  152. package/umd/src/remote-server/startRemoteServer/registerRemoteServerHttpRoutes.d.ts +7 -0
  153. package/umd/src/remote-server/startRemoteServer/registerRemoteServerSocketHandlers.d.ts +8 -0
  154. package/umd/src/remote-server/startRemoteServer/registerServerIndexRoute.d.ts +7 -0
  155. package/umd/src/remote-server/startRemoteServer/resolveStartRemoteServerConfiguration.d.ts +8 -0
  156. package/umd/src/remote-server/startRemoteServer/respondToSocketRequest.d.ts +8 -0
  157. package/umd/src/remote-server/startRemoteServer/startListening.d.ts +9 -0
  158. package/umd/src/scrapers/_common/utils/makeKnowledgeSourceHandler.d.ts +14 -1
  159. package/umd/src/utils/serialization/serializeToPromptbookJavascript.d.ts +2 -0
  160. package/umd/src/utils/serialization/serializeToPromptbookJavascript.test.d.ts +1 -0
  161. package/umd/src/version.d.ts +1 -1
package/umd/index.umd.js CHANGED
@@ -24,7 +24,7 @@
24
24
  * @generated
25
25
  * @see https://github.com/webgptorg/promptbook
26
26
  */
27
- const PROMPTBOOK_ENGINE_VERSION = '0.112.0-72';
27
+ const PROMPTBOOK_ENGINE_VERSION = '0.112.0-73';
28
28
  /**
29
29
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
30
30
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -1785,6 +1785,60 @@
1785
1785
  }
1786
1786
  // TODO: [🧠][🈴] Where is the best location for this file
1787
1787
 
1788
+ /**
1789
+ * Appends one markdown block to an existing markdown document.
1790
+ *
1791
+ * @private internal utility of `pipelineJsonToString`
1792
+ */
1793
+ function appendMarkdownBlock(pipelineString, markdownBlock) {
1794
+ return spacetrim.spaceTrim((block) => `
1795
+ ${block(pipelineString)}
1796
+
1797
+ ${block(markdownBlock)}
1798
+ `);
1799
+ }
1800
+
1801
+ /**
1802
+ * Collects pipeline-level commands in the existing serialization order.
1803
+ *
1804
+ * @private internal utility of `pipelineJsonToString`
1805
+ */
1806
+ function createPipelineCommands(pipelineJson) {
1807
+ const { pipelineUrl, bookVersion, parameters } = pipelineJson;
1808
+ const commands = [];
1809
+ if (pipelineUrl) {
1810
+ commands.push(`PIPELINE URL ${pipelineUrl}`);
1811
+ }
1812
+ if (bookVersion !== `undefined`) {
1813
+ commands.push(`BOOK VERSION ${bookVersion}`);
1814
+ }
1815
+ commands.push(...createParameterCommands(parameters, 'INPUT PARAMETER', ({ isInput }) => isInput));
1816
+ commands.push(...createParameterCommands(parameters, 'OUTPUT PARAMETER', ({ isOutput }) => isOutput));
1817
+ return commands;
1818
+ }
1819
+ /**
1820
+ * Builds one group of parameter commands while preserving the original parameter order.
1821
+ *
1822
+ * @private internal utility of `createPipelineCommands`
1823
+ */
1824
+ function createParameterCommands(parameters, commandPrefix, isIncluded) {
1825
+ return parameters
1826
+ .filter((parameter) => isIncluded(parameter))
1827
+ .map((parameter) => `${commandPrefix} ${parameterJsonToString(parameter)}`);
1828
+ }
1829
+ /**
1830
+ * Converts one parameter JSON declaration to the serialized inline form.
1831
+ *
1832
+ * @private internal utility of `createPipelineCommands`
1833
+ */
1834
+ function parameterJsonToString(parameterJson) {
1835
+ const { name, description } = parameterJson;
1836
+ if (!description) {
1837
+ return `{${name}}`;
1838
+ }
1839
+ return `{${name}} ${description}`;
1840
+ }
1841
+
1788
1842
  /**
1789
1843
  * Prettify the html code
1790
1844
  *
@@ -1798,6 +1852,31 @@
1798
1852
  return (content + `\n\n<!-- Note: Prettier removed from Promptbook -->`);
1799
1853
  }
1800
1854
 
1855
+ /**
1856
+ * Creates the initial markdown heading and description of a pipeline.
1857
+ *
1858
+ * @private internal utility of `pipelineJsonToString`
1859
+ */
1860
+ function createPipelineIntroduction(pipelineJson) {
1861
+ const { title, description } = pipelineJson;
1862
+ const pipelineIntroduction = spacetrim.spaceTrim((block) => `
1863
+ # ${title}
1864
+
1865
+ ${block(description || '')}
1866
+ `);
1867
+ // TODO: [main] !!5 This increases size of the bundle and is probably not necessary
1868
+ return prettifyMarkdown(pipelineIntroduction);
1869
+ }
1870
+
1871
+ /**
1872
+ * Renders commands as markdown bullet items.
1873
+ *
1874
+ * @private internal utility of `pipelineJsonToString`
1875
+ */
1876
+ function stringifyCommands(commands) {
1877
+ return commands.map((command) => `- ${command}`).join('\n');
1878
+ }
1879
+
1801
1880
  /**
1802
1881
  * Makes first letter of a string uppercase
1803
1882
  *
@@ -1810,141 +1889,186 @@
1810
1889
  }
1811
1890
 
1812
1891
  /**
1813
- * Converts promptbook in JSON format to string format
1892
+ * Collects all task-specific serialization details.
1814
1893
  *
1815
- * @deprecated TODO: [🥍][🧠] Backup original files in `PipelineJson` same as in Promptbook.studio
1816
- * @param pipelineJson Promptbook in JSON format (.bookc)
1817
- * @returns Promptbook in string format (.book.md)
1894
+ * @private internal utility of `pipelineJsonToString`
1895
+ */
1896
+ function createTaskSerialization(task) {
1897
+ const taskTypeSerialization = createTaskTypeSerialization(task);
1898
+ return {
1899
+ commands: [
1900
+ ...taskTypeSerialization.commands,
1901
+ ...createJokerCommands(task),
1902
+ ...createPostprocessingCommands(task),
1903
+ ...createExpectationCommands(task),
1904
+ ...createFormatCommands(task),
1905
+ ],
1906
+ contentLanguage: taskTypeSerialization.contentLanguage,
1907
+ };
1908
+ }
1909
+ /**
1910
+ * Collects commands and content language driven by the task type.
1818
1911
  *
1819
- * @public exported from `@promptbook/core`
1912
+ * @private internal utility of `createTaskSerialization`
1820
1913
  */
1821
- function pipelineJsonToString(pipelineJson) {
1822
- const { title, pipelineUrl, bookVersion, description, parameters, tasks } = pipelineJson;
1823
- let pipelineString = spacetrim.spaceTrim((block) => `
1824
- # ${title}
1825
-
1826
- ${block(description || '')}
1827
- `);
1914
+ function createTaskTypeSerialization(task) {
1915
+ if (task.taskType === 'PROMPT_TASK') {
1916
+ return {
1917
+ commands: createPromptTaskCommands(task),
1918
+ contentLanguage: 'text',
1919
+ };
1920
+ }
1921
+ if (task.taskType === 'SIMPLE_TASK') {
1922
+ return {
1923
+ commands: ['SIMPLE TEMPLATE'],
1924
+ contentLanguage: 'text',
1925
+ };
1926
+ }
1927
+ if (task.taskType === 'SCRIPT_TASK') {
1928
+ return {
1929
+ commands: ['SCRIPT'],
1930
+ contentLanguage: task.contentLanguage || '',
1931
+ };
1932
+ }
1933
+ if (task.taskType === 'DIALOG_TASK') {
1934
+ return {
1935
+ commands: ['DIALOG'],
1936
+ contentLanguage: 'text',
1937
+ };
1938
+ }
1939
+ return {
1940
+ commands: [],
1941
+ contentLanguage: 'text',
1942
+ };
1943
+ }
1944
+ /**
1945
+ * Collects prompt-task-specific commands.
1946
+ *
1947
+ * @private internal utility of `createTaskSerialization`
1948
+ */
1949
+ function createPromptTaskCommands(task) {
1950
+ const { modelName, modelVariant } = task.modelRequirements || {};
1828
1951
  const commands = [];
1829
- if (pipelineUrl) {
1830
- commands.push(`PIPELINE URL ${pipelineUrl}`);
1952
+ // Note: Do nothing, it is default
1953
+ // commands.push(`PROMPT`);
1954
+ if (modelVariant) {
1955
+ commands.push(`MODEL VARIANT ${capitalize(modelVariant)}`);
1831
1956
  }
1832
- if (bookVersion !== `undefined`) {
1833
- commands.push(`BOOK VERSION ${bookVersion}`);
1957
+ if (modelName) {
1958
+ commands.push(`MODEL NAME \`${modelName}\``);
1834
1959
  }
1835
- // TODO: [main] !!5 This increases size of the bundle and is probably not necessary
1836
- pipelineString = prettifyMarkdown(pipelineString);
1837
- for (const parameter of parameters.filter(({ isInput }) => isInput)) {
1838
- commands.push(`INPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
1960
+ return commands;
1961
+ }
1962
+ /**
1963
+ * Collects joker commands.
1964
+ *
1965
+ * @private internal utility of `createTaskSerialization`
1966
+ */
1967
+ function createJokerCommands(task) {
1968
+ var _a;
1969
+ return ((_a = task.jokerParameterNames) === null || _a === void 0 ? void 0 : _a.map((joker) => `JOKER {${joker}}`)) || [];
1970
+ }
1971
+ /**
1972
+ * Collects postprocessing commands.
1973
+ *
1974
+ * @private internal utility of `createTaskSerialization`
1975
+ */
1976
+ function createPostprocessingCommands(task) {
1977
+ var _a;
1978
+ return ((_a = task.postprocessingFunctionNames) === null || _a === void 0 ? void 0 : _a.map((postprocessingFunctionName) => `POSTPROCESSING \`${postprocessingFunctionName}\``)) || [];
1979
+ }
1980
+ /**
1981
+ * Collects expectation commands.
1982
+ *
1983
+ * @private internal utility of `createTaskSerialization`
1984
+ */
1985
+ function createExpectationCommands(task) {
1986
+ if (!task.expectations) {
1987
+ return [];
1839
1988
  }
1840
- for (const parameter of parameters.filter(({ isOutput }) => isOutput)) {
1841
- commands.push(`OUTPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
1989
+ return Object.entries(task.expectations).flatMap(([unit, expectation]) => createExpectationCommandsForUnit(unit, expectation.min, expectation.max));
1990
+ }
1991
+ /**
1992
+ * Collects expectation commands for a single unit.
1993
+ *
1994
+ * @private internal utility of `createTaskSerialization`
1995
+ */
1996
+ function createExpectationCommandsForUnit(unit, min, max) {
1997
+ if (min === max) {
1998
+ return [`EXPECT EXACTLY ${min} ${formatExpectationUnit(unit, min)}`];
1842
1999
  }
1843
- pipelineString = spacetrim.spaceTrim((block) => `
1844
- ${block(pipelineString)}
1845
-
1846
- ${block(commands.map((command) => `- ${command}`).join('\n'))}
1847
- `);
1848
- for (const task of tasks) {
1849
- const {
1850
- /* Note: Not using:> name, */
1851
- title, description,
1852
- /* Note: dependentParameterNames, */
1853
- jokerParameterNames: jokers, taskType, content, postprocessingFunctionNames: postprocessing, expectations, format, resultingParameterName, } = task;
1854
- const commands = [];
1855
- let contentLanguage = 'text';
1856
- if (taskType === 'PROMPT_TASK') {
1857
- const { modelRequirements } = task;
1858
- const { modelName, modelVariant } = modelRequirements || {};
1859
- // Note: Do nothing, it is default
1860
- // commands.push(`PROMPT`);
1861
- if (modelVariant) {
1862
- commands.push(`MODEL VARIANT ${capitalize(modelVariant)}`);
1863
- }
1864
- if (modelName) {
1865
- commands.push(`MODEL NAME \`${modelName}\``);
1866
- }
1867
- }
1868
- else if (taskType === 'SIMPLE_TASK') {
1869
- commands.push(`SIMPLE TEMPLATE`);
1870
- // Note: Nothing special here
1871
- }
1872
- else if (taskType === 'SCRIPT_TASK') {
1873
- commands.push(`SCRIPT`);
1874
- if (task.contentLanguage) {
1875
- contentLanguage = task.contentLanguage;
1876
- }
1877
- else {
1878
- contentLanguage = '';
1879
- }
1880
- }
1881
- else if (taskType === 'DIALOG_TASK') {
1882
- commands.push(`DIALOG`);
1883
- // Note: Nothing special here
1884
- } // <- }else if([🅱]
1885
- if (jokers) {
1886
- for (const joker of jokers) {
1887
- commands.push(`JOKER {${joker}}`);
1888
- }
1889
- } /* not else */
1890
- if (postprocessing) {
1891
- for (const postprocessingFunctionName of postprocessing) {
1892
- commands.push(`POSTPROCESSING \`${postprocessingFunctionName}\``);
1893
- }
1894
- } /* not else */
1895
- if (expectations) {
1896
- for (const [unit, { min, max }] of Object.entries(expectations)) {
1897
- if (min === max) {
1898
- commands.push(`EXPECT EXACTLY ${min} ${capitalize(unit + (min > 1 ? 's' : ''))}`);
1899
- }
1900
- else {
1901
- if (min !== undefined) {
1902
- commands.push(`EXPECT MIN ${min} ${capitalize(unit + (min > 1 ? 's' : ''))}`);
1903
- } /* not else */
1904
- if (max !== undefined) {
1905
- commands.push(`EXPECT MAX ${max} ${capitalize(unit + (max > 1 ? 's' : ''))}`);
1906
- }
1907
- }
1908
- }
1909
- } /* not else */
1910
- if (format) {
1911
- if (format === 'JSON') {
1912
- // TODO: @deprecated remove
1913
- commands.push(`FORMAT JSON`);
1914
- }
1915
- } /* not else */
1916
- pipelineString = spacetrim.spaceTrim((block) => `
1917
- ${block(pipelineString)}
2000
+ const commands = [];
2001
+ if (min !== undefined) {
2002
+ commands.push(`EXPECT MIN ${min} ${formatExpectationUnit(unit, min)}`);
2003
+ }
2004
+ if (max !== undefined) {
2005
+ commands.push(`EXPECT MAX ${max} ${formatExpectationUnit(unit, max)}`);
2006
+ }
2007
+ return commands;
2008
+ }
2009
+ /**
2010
+ * Formats the expectation unit exactly as the legacy serializer does.
2011
+ *
2012
+ * @private internal utility of `createTaskSerialization`
2013
+ */
2014
+ function formatExpectationUnit(unit, amount) {
2015
+ return capitalize(unit + (amount > 1 ? 's' : ''));
2016
+ }
2017
+ /**
2018
+ * Collects format commands.
2019
+ *
2020
+ * @private internal utility of `createTaskSerialization`
2021
+ */
2022
+ function createFormatCommands(task) {
2023
+ if (task.format === 'JSON') {
2024
+ // TODO: @deprecated remove
2025
+ return ['FORMAT JSON'];
2026
+ }
2027
+ return [];
2028
+ }
1918
2029
 
1919
- ## ${title}
2030
+ /**
2031
+ * Stringifies one task section of the pipeline.
2032
+ *
2033
+ * @private internal utility of `pipelineJsonToString`
2034
+ */
2035
+ function stringifyTask(task) {
2036
+ const { title, description, content, resultingParameterName } = task;
2037
+ const { commands, contentLanguage } = createTaskSerialization(task);
2038
+ return spacetrim.spaceTrim((block) => `
2039
+ ## ${title}
1920
2040
 
1921
- ${block(description || '')}
2041
+ ${block(description || '')}
1922
2042
 
1923
- ${block(commands.map((command) => `- ${command}`).join('\n'))}
2043
+ ${block(stringifyCommands(commands))}
1924
2044
 
1925
- \`\`\`${contentLanguage}
1926
- ${block(spacetrim.spaceTrim(content))}
1927
- \`\`\`
2045
+ \`\`\`${contentLanguage}
2046
+ ${block(spacetrim.spaceTrim(content))}
2047
+ \`\`\`
1928
2048
 
1929
- \`-> {${resultingParameterName}}\`
1930
- `); // <- TODO: [main] !!3 If the parameter here has description, add it and use taskParameterJsonToString
1931
- // <- TODO: [main] !!3 Escape
1932
- // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
1933
- }
1934
- return validatePipelineString(pipelineString);
2049
+ \`-> {${resultingParameterName}}\`
2050
+ `); // <- TODO: [main] !!3 If the parameter here has description, add it and use taskParameterJsonToString
2051
+ // <- TODO: [main] !!3 Escape
2052
+ // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
1935
2053
  }
2054
+
1936
2055
  /**
1937
- * Handles task parameter Json to string.
2056
+ * Converts promptbook in JSON format to string format
1938
2057
  *
1939
- * @private internal utility of `pipelineJsonToString`
2058
+ * @deprecated TODO: [🥍][🧠] Backup original files in `PipelineJson` same as in Promptbook.studio
2059
+ * @param pipelineJson Promptbook in JSON format (.bookc)
2060
+ * @returns Promptbook in string format (.book.md)
2061
+ *
2062
+ * @public exported from `@promptbook/core`
1940
2063
  */
1941
- function taskParameterJsonToString(taskParameterJson) {
1942
- const { name, description } = taskParameterJson;
1943
- let parameterString = `{${name}}`;
1944
- if (description) {
1945
- parameterString = `${parameterString} ${description}`;
2064
+ function pipelineJsonToString(pipelineJson) {
2065
+ let pipelineString = createPipelineIntroduction(pipelineJson);
2066
+ const pipelineCommands = createPipelineCommands(pipelineJson);
2067
+ pipelineString = appendMarkdownBlock(pipelineString, stringifyCommands(pipelineCommands));
2068
+ for (const task of pipelineJson.tasks) {
2069
+ pipelineString = appendMarkdownBlock(pipelineString, stringifyTask(task));
1946
2070
  }
1947
- return parameterString;
2071
+ return validatePipelineString(pipelineString);
1948
2072
  }
1949
2073
  // TODO: [🛋] Implement new features and commands into `pipelineJsonToString` + `taskParameterJsonToString` , use `stringifyCommand`
1950
2074
  // TODO: [🧠] Is there a way to auto-detect missing features in pipelineJsonToString
@@ -2384,233 +2508,519 @@
2384
2508
  */
2385
2509
  function validatePipeline_InnerFunction(pipeline) {
2386
2510
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
2387
- const pipelineIdentification = (() => {
2388
- // Note: This is a 😐 implementation of [🚞]
2389
- const _ = [];
2390
- if (pipeline.sourceFile !== undefined) {
2391
- _.push(`File: ${pipeline.sourceFile}`);
2392
- }
2393
- if (pipeline.pipelineUrl !== undefined) {
2394
- _.push(`Url: ${pipeline.pipelineUrl}`);
2511
+ const context = createPipelineValidationContext(pipeline);
2512
+ validatePipelineMetadata(context);
2513
+ validatePipelineCollectionsStructure(context);
2514
+ validatePipelineParameters(context);
2515
+ validatePipelineTasks(context);
2516
+ validatePipelineDependencyResolution(context);
2517
+ // Note: Check that formfactor is corresponding to the pipeline interface
2518
+ // TODO: !!6 Implement this
2519
+ // pipeline.formfactorName
2520
+ }
2521
+ /**
2522
+ * Creates the shared validation context for one pipeline.
2523
+ *
2524
+ * @private internal utility of `validatePipeline`
2525
+ */
2526
+ function createPipelineValidationContext(pipeline) {
2527
+ return {
2528
+ pipeline,
2529
+ pipelineIdentification: getPipelineIdentification(pipeline),
2530
+ };
2531
+ }
2532
+ /**
2533
+ * Builds a short file/url identification block for validation errors.
2534
+ *
2535
+ * @private internal utility of `validatePipeline`
2536
+ */
2537
+ function getPipelineIdentification(pipeline) {
2538
+ // Note: This is a 😐 implementation of [🚞]
2539
+ const pipelineIdentificationParts = [];
2540
+ if (pipeline.sourceFile !== undefined) {
2541
+ pipelineIdentificationParts.push(`File: ${pipeline.sourceFile}`);
2542
+ }
2543
+ if (pipeline.pipelineUrl !== undefined) {
2544
+ pipelineIdentificationParts.push(`Url: ${pipeline.pipelineUrl}`);
2545
+ }
2546
+ return pipelineIdentificationParts.join('\n');
2547
+ }
2548
+ /**
2549
+ * Validates pipeline-level metadata fields.
2550
+ *
2551
+ * @private internal step of `validatePipeline`
2552
+ */
2553
+ function validatePipelineMetadata({ pipeline, pipelineIdentification }) {
2554
+ validatePipelineUrl(pipeline, pipelineIdentification);
2555
+ validatePipelineBookVersion(pipeline, pipelineIdentification);
2556
+ }
2557
+ /**
2558
+ * Validates that the expected top-level collections have array structure.
2559
+ *
2560
+ * @private internal step of `validatePipeline`
2561
+ */
2562
+ function validatePipelineCollectionsStructure({ pipeline, pipelineIdentification }) {
2563
+ validatePipelineParametersCollection(pipeline, pipelineIdentification);
2564
+ validatePipelineTasksCollection(pipeline, pipelineIdentification);
2565
+ }
2566
+ /**
2567
+ * Validates all pipeline parameter declarations.
2568
+ *
2569
+ * @private internal step of `validatePipeline`
2570
+ */
2571
+ function validatePipelineParameters({ pipeline, pipelineIdentification }) {
2572
+ for (const parameter of pipeline.parameters) {
2573
+ validatePipelineParameter(parameter, pipeline, pipelineIdentification);
2574
+ }
2575
+ }
2576
+ /**
2577
+ * Validates all pipeline tasks and their per-task invariants.
2578
+ *
2579
+ * @private internal step of `validatePipeline`
2580
+ */
2581
+ function validatePipelineTasks({ pipeline, pipelineIdentification }) {
2582
+ // Note: All input parameters are defined - so that they can be used as result of some task
2583
+ const definedParameters = createInitiallyDefinedParameters(pipeline);
2584
+ for (const task of pipeline.tasks) {
2585
+ validatePipelineTask(task, definedParameters, pipelineIdentification);
2586
+ }
2587
+ }
2588
+ /**
2589
+ * Validates that task dependencies can be resolved without cycles or missing definitions.
2590
+ *
2591
+ * @private internal step of `validatePipeline`
2592
+ */
2593
+ function validatePipelineDependencyResolution({ pipeline, pipelineIdentification }) {
2594
+ let dependencyResolutionState = createInitialDependencyResolutionState(pipeline);
2595
+ let loopLimit = LOOP_LIMIT;
2596
+ while (hasUnresolvedTasks(dependencyResolutionState)) {
2597
+ if (loopLimit-- < 0) {
2598
+ throw createDependencyResolutionLoopLimitError(pipelineIdentification);
2395
2599
  }
2396
- return _.join('\n');
2397
- })();
2398
- if (pipeline.pipelineUrl !== undefined && !isValidPipelineUrl(pipeline.pipelineUrl)) {
2399
- // <- Note: [🚲]
2400
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2401
- Invalid promptbook URL "${pipeline.pipelineUrl}"
2402
-
2403
- ${block(pipelineIdentification)}
2404
- `));
2600
+ dependencyResolutionState = resolveNextDependencyResolutionState(dependencyResolutionState, pipelineIdentification);
2405
2601
  }
2406
- if (pipeline.bookVersion !== undefined && !isValidPromptbookVersion(pipeline.bookVersion)) {
2407
- // <- Note: [🚲]
2408
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2409
- Invalid Promptbook Version "${pipeline.bookVersion}"
2602
+ }
2603
+ /**
2604
+ * Validates one pipeline parameter declaration.
2605
+ *
2606
+ * @private internal step of `validatePipeline`
2607
+ */
2608
+ function validatePipelineParameter(parameter, pipeline, pipelineIdentification) {
2609
+ validateParameterDirection(parameter, pipelineIdentification);
2610
+ validateParameterUsage(parameter, pipeline, pipelineIdentification);
2611
+ validateParameterDefinition(parameter, pipeline, pipelineIdentification);
2612
+ }
2613
+ /**
2614
+ * Validates one pipeline task and its invariants.
2615
+ *
2616
+ * @private internal step of `validatePipeline`
2617
+ */
2618
+ function validatePipelineTask(task, definedParameters, pipelineIdentification) {
2619
+ validateTaskResultingParameter(task, definedParameters, pipelineIdentification);
2620
+ validateTaskJokers(task, pipelineIdentification);
2621
+ validateTaskExpectations(task, pipelineIdentification);
2622
+ }
2623
+ /**
2624
+ * Validates the pipeline URL, when present.
2625
+ *
2626
+ * @private internal utility of `validatePipeline`
2627
+ */
2628
+ function validatePipelineUrl(pipeline, pipelineIdentification) {
2629
+ if (pipeline.pipelineUrl === undefined || isValidPipelineUrl(pipeline.pipelineUrl)) {
2630
+ return;
2631
+ }
2632
+ // <- Note: [🚲]
2633
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2634
+ Invalid promptbook URL "${pipeline.pipelineUrl}"
2410
2635
 
2411
- ${block(pipelineIdentification)}
2412
- `));
2636
+ ${block(pipelineIdentification)}
2637
+ `));
2638
+ }
2639
+ /**
2640
+ * Validates the Promptbook version, when present.
2641
+ *
2642
+ * @private internal utility of `validatePipeline`
2643
+ */
2644
+ function validatePipelineBookVersion(pipeline, pipelineIdentification) {
2645
+ if (pipeline.bookVersion === undefined || isValidPromptbookVersion(pipeline.bookVersion)) {
2646
+ return;
2413
2647
  }
2648
+ // <- Note: [🚲]
2649
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2650
+ Invalid Promptbook Version "${pipeline.bookVersion}"
2651
+
2652
+ ${block(pipelineIdentification)}
2653
+ `));
2654
+ }
2655
+ /**
2656
+ * Validates that `pipeline.parameters` is an array.
2657
+ *
2658
+ * @private internal utility of `validatePipeline`
2659
+ */
2660
+ function validatePipelineParametersCollection(pipeline, pipelineIdentification) {
2414
2661
  // TODO: [🧠] Maybe do here some proper JSON-schema / ZOD checking
2415
- if (!Array.isArray(pipeline.parameters)) {
2416
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2417
- throw new ParseError(spacetrim.spaceTrim((block) => `
2418
- Pipeline is valid JSON but with wrong structure
2662
+ if (Array.isArray(pipeline.parameters)) {
2663
+ return;
2664
+ }
2665
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2666
+ throw new ParseError(spacetrim.spaceTrim((block) => `
2667
+ Pipeline is valid JSON but with wrong structure
2419
2668
 
2420
- \`PipelineJson.parameters\` expected to be an array, but got ${typeof pipeline.parameters}
2669
+ \`PipelineJson.parameters\` expected to be an array, but got ${typeof pipeline.parameters}
2421
2670
 
2422
- ${block(pipelineIdentification)}
2423
- `));
2424
- }
2671
+ ${block(pipelineIdentification)}
2672
+ `));
2673
+ }
2674
+ /**
2675
+ * Validates that `pipeline.tasks` is an array.
2676
+ *
2677
+ * @private internal utility of `validatePipeline`
2678
+ */
2679
+ function validatePipelineTasksCollection(pipeline, pipelineIdentification) {
2425
2680
  // TODO: [🧠] Maybe do here some proper JSON-schema / ZOD checking
2426
- if (!Array.isArray(pipeline.tasks)) {
2427
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2428
- throw new ParseError(spacetrim.spaceTrim((block) => `
2429
- Pipeline is valid JSON but with wrong structure
2681
+ if (Array.isArray(pipeline.tasks)) {
2682
+ return;
2683
+ }
2684
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2685
+ throw new ParseError(spacetrim.spaceTrim((block) => `
2686
+ Pipeline is valid JSON but with wrong structure
2430
2687
 
2431
- \`PipelineJson.tasks\` expected to be an array, but got ${typeof pipeline.tasks}
2688
+ \`PipelineJson.tasks\` expected to be an array, but got ${typeof pipeline.tasks}
2432
2689
 
2433
- ${block(pipelineIdentification)}
2434
- `));
2690
+ ${block(pipelineIdentification)}
2691
+ `));
2692
+ }
2693
+ /**
2694
+ * Validates that one parameter does not declare incompatible directions.
2695
+ *
2696
+ * @private internal utility of `validatePipeline`
2697
+ */
2698
+ function validateParameterDirection(parameter, pipelineIdentification) {
2699
+ if (!parameter.isInput || !parameter.isOutput) {
2700
+ return;
2435
2701
  }
2436
- /*
2437
- TODO: [🧠][🅾] Should be empty pipeline valid or not
2438
- // Note: Check that pipeline has some tasks
2439
- if (pipeline.tasks.length === 0) {
2440
- throw new PipelineLogicError(
2441
- spaceTrim(
2442
- (block) => `
2443
- Pipeline must have at least one task
2702
+ const parameterName = parameter.name;
2703
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2444
2704
 
2445
- ${block(pipelineIdentification)}
2446
- `,
2447
- ),
2448
- );
2449
- }
2450
- */
2451
- // Note: Check each parameter individually
2452
- for (const parameter of pipeline.parameters) {
2453
- if (parameter.isInput && parameter.isOutput) {
2454
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2705
+ Parameter \`{${parameterName}}\` can not be both input and output
2455
2706
 
2456
- Parameter \`{${parameter.name}}\` can not be both input and output
2707
+ ${block(pipelineIdentification)}
2708
+ `));
2709
+ }
2710
+ /**
2711
+ * Validates that one intermediate parameter is actually consumed by at least one task.
2712
+ *
2713
+ * @private internal utility of `validatePipeline`
2714
+ */
2715
+ function validateParameterUsage(parameter, pipeline, pipelineIdentification) {
2716
+ if (parameter.isInput || parameter.isOutput || isParameterUsedByAnyTask(parameter, pipeline.tasks)) {
2717
+ return;
2718
+ }
2719
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2720
+ Parameter \`{${parameter.name}}\` is created but not used
2457
2721
 
2458
- ${block(pipelineIdentification)}
2459
- `));
2460
- }
2461
- // Note: Testing that parameter is either intermediate or output BUT not created and unused
2462
- if (!parameter.isInput &&
2463
- !parameter.isOutput &&
2464
- !pipeline.tasks.some((task) => task.dependentParameterNames.includes(parameter.name))) {
2465
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2466
- Parameter \`{${parameter.name}}\` is created but not used
2722
+ You can declare {${parameter.name}} as output parameter by adding in the header:
2723
+ - OUTPUT PARAMETER \`{${parameter.name}}\` ${parameter.description || ''}
2467
2724
 
2468
- You can declare {${parameter.name}} as output parameter by adding in the header:
2469
- - OUTPUT PARAMETER \`{${parameter.name}}\` ${parameter.description || ''}
2725
+ ${block(pipelineIdentification)}
2470
2726
 
2471
- ${block(pipelineIdentification)}
2727
+ `));
2728
+ }
2729
+ /**
2730
+ * Validates that one non-input parameter is produced by at least one task.
2731
+ *
2732
+ * @private internal utility of `validatePipeline`
2733
+ */
2734
+ function validateParameterDefinition(parameter, pipeline, pipelineIdentification) {
2735
+ if (parameter.isInput || isParameterDefinedByAnyTask(parameter, pipeline.tasks)) {
2736
+ return;
2737
+ }
2738
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2739
+ Parameter \`{${parameter.name}}\` is declared but not defined
2472
2740
 
2473
- `));
2474
- }
2475
- // Note: Testing that parameter is either input or result of some task
2476
- if (!parameter.isInput && !pipeline.tasks.some((task) => task.resultingParameterName === parameter.name)) {
2477
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2478
- Parameter \`{${parameter.name}}\` is declared but not defined
2741
+ You can do one of these:
2742
+ 1) Remove declaration of \`{${parameter.name}}\`
2743
+ 2) Add task that results in \`-> {${parameter.name}}\`
2479
2744
 
2480
- You can do one of these:
2481
- 1) Remove declaration of \`{${parameter.name}}\`
2482
- 2) Add task that results in \`-> {${parameter.name}}\`
2745
+ ${block(pipelineIdentification)}
2746
+ `));
2747
+ }
2748
+ /**
2749
+ * Checks whether one parameter is consumed by at least one task dependency list.
2750
+ *
2751
+ * @private internal utility of `validatePipeline`
2752
+ */
2753
+ function isParameterUsedByAnyTask(parameter, tasks) {
2754
+ return tasks.some((task) => task.dependentParameterNames.includes(parameter.name));
2755
+ }
2756
+ /**
2757
+ * Checks whether one parameter is produced by at least one task.
2758
+ *
2759
+ * @private internal utility of `validatePipeline`
2760
+ */
2761
+ function isParameterDefinedByAnyTask(parameter, tasks) {
2762
+ return tasks.some((task) => task.resultingParameterName === parameter.name);
2763
+ }
2764
+ /**
2765
+ * Collects the parameter names that are already defined before task validation starts.
2766
+ *
2767
+ * @private internal utility of `validatePipeline`
2768
+ */
2769
+ function createInitiallyDefinedParameters(pipeline) {
2770
+ return new Set(pipeline.parameters.filter(({ isInput }) => isInput).map(({ name }) => name));
2771
+ }
2772
+ /**
2773
+ * Validates one task result parameter declaration and marks it as defined.
2774
+ *
2775
+ * @private internal utility of `validatePipeline`
2776
+ */
2777
+ function validateTaskResultingParameter(task, definedParameters, pipelineIdentification) {
2778
+ if (definedParameters.has(task.resultingParameterName)) {
2779
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2780
+ Parameter \`{${task.resultingParameterName}}\` is defined multiple times
2483
2781
 
2484
- ${block(pipelineIdentification)}
2485
- `));
2486
- }
2782
+ ${block(pipelineIdentification)}
2783
+ `));
2487
2784
  }
2488
- // Note: All input parameters are defined - so that they can be used as result of some task
2489
- const definedParameters = new Set(pipeline.parameters.filter(({ isInput }) => isInput).map(({ name }) => name));
2490
- // Note: Checking each task individually
2491
- for (const task of pipeline.tasks) {
2492
- if (definedParameters.has(task.resultingParameterName)) {
2493
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2494
- Parameter \`{${task.resultingParameterName}}\` is defined multiple times
2785
+ if (RESERVED_PARAMETER_NAMES.includes(task.resultingParameterName)) {
2786
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2787
+ Parameter name {${task.resultingParameterName}} is reserved, please use different name
2495
2788
 
2496
- ${block(pipelineIdentification)}
2497
- `));
2498
- }
2499
- if (RESERVED_PARAMETER_NAMES.includes(task.resultingParameterName)) {
2500
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2501
- Parameter name {${task.resultingParameterName}} is reserved, please use different name
2789
+ ${block(pipelineIdentification)}
2790
+ `));
2791
+ }
2792
+ definedParameters.add(task.resultingParameterName);
2793
+ }
2794
+ /**
2795
+ * Validates joker parameters for one task.
2796
+ *
2797
+ * @private internal utility of `validatePipeline`
2798
+ */
2799
+ function validateTaskJokers(task, pipelineIdentification) {
2800
+ if (!hasTaskJokers(task)) {
2801
+ return;
2802
+ }
2803
+ validateTaskSupportsJokers(task, pipelineIdentification);
2804
+ validateTaskJokerDependencies(task, pipelineIdentification);
2805
+ }
2806
+ /**
2807
+ * Checks whether one task declares any joker parameters.
2808
+ *
2809
+ * @private internal utility of `validatePipeline`
2810
+ */
2811
+ function hasTaskJokers(task) {
2812
+ return !!task.jokerParameterNames && task.jokerParameterNames.length > 0;
2813
+ }
2814
+ /**
2815
+ * Validates that a task has the required supporting features when using jokers.
2816
+ *
2817
+ * @private internal utility of `validatePipeline`
2818
+ */
2819
+ function validateTaskSupportsJokers(task, pipelineIdentification) {
2820
+ if (task.format ||
2821
+ task.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
2822
+ return;
2823
+ }
2824
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2825
+ Joker parameters are used for {${task.resultingParameterName}} but no expectations are defined
2502
2826
 
2503
- ${block(pipelineIdentification)}
2504
- `));
2827
+ ${block(pipelineIdentification)}
2828
+ `));
2829
+ }
2830
+ /**
2831
+ * Validates that every joker parameter is also listed among task dependencies.
2832
+ *
2833
+ * @private internal utility of `validatePipeline`
2834
+ */
2835
+ function validateTaskJokerDependencies(task, pipelineIdentification) {
2836
+ for (const joker of task.jokerParameterNames) {
2837
+ if (task.dependentParameterNames.includes(joker)) {
2838
+ continue;
2505
2839
  }
2506
- definedParameters.add(task.resultingParameterName);
2507
- if (task.jokerParameterNames && task.jokerParameterNames.length > 0) {
2508
- if (!task.format &&
2509
- !task.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
2510
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2511
- Joker parameters are used for {${task.resultingParameterName}} but no expectations are defined
2512
-
2513
- ${block(pipelineIdentification)}
2514
- `));
2515
- }
2516
- for (const joker of task.jokerParameterNames) {
2517
- if (!task.dependentParameterNames.includes(joker)) {
2518
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2519
- Parameter \`{${joker}}\` is used for {${task.resultingParameterName}} as joker but not in \`dependentParameterNames\`
2840
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2841
+ Parameter \`{${joker}}\` is used for {${task.resultingParameterName}} as joker but not in \`dependentParameterNames\`
2520
2842
 
2521
- ${block(pipelineIdentification)}
2522
- `));
2523
- }
2524
- }
2525
- }
2526
- if (task.expectations) {
2527
- for (const [unit, { min, max }] of Object.entries(task.expectations)) {
2528
- if (min !== undefined && max !== undefined && min > max) {
2529
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2530
- Min expectation (=${min}) of ${unit} is higher than max expectation (=${max})
2843
+ ${block(pipelineIdentification)}
2844
+ `));
2845
+ }
2846
+ }
2847
+ /**
2848
+ * Validates all expectation bounds configured on one task.
2849
+ *
2850
+ * @private internal utility of `validatePipeline`
2851
+ */
2852
+ function validateTaskExpectations(task, pipelineIdentification) {
2853
+ if (!task.expectations) {
2854
+ return;
2855
+ }
2856
+ for (const [unit, { min, max }] of Object.entries(task.expectations)) {
2857
+ validateTaskExpectationRange(unit, min, max, pipelineIdentification);
2858
+ validateTaskExpectationMin(unit, min, pipelineIdentification);
2859
+ validateTaskExpectationMax(unit, max, pipelineIdentification);
2860
+ }
2861
+ }
2862
+ /**
2863
+ * Validates the minimum and maximum expectation ordering for one unit.
2864
+ *
2865
+ * @private internal utility of `validatePipeline`
2866
+ */
2867
+ function validateTaskExpectationRange(unit, min, max, pipelineIdentification) {
2868
+ if (min === undefined || max === undefined || min <= max) {
2869
+ return;
2870
+ }
2871
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2872
+ Min expectation (=${min}) of ${unit} is higher than max expectation (=${max})
2531
2873
 
2532
- ${block(pipelineIdentification)}
2533
- `));
2534
- }
2535
- if (min !== undefined && min < 0) {
2536
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2537
- Min expectation of ${unit} must be zero or positive
2874
+ ${block(pipelineIdentification)}
2875
+ `));
2876
+ }
2877
+ /**
2878
+ * Validates the minimum expectation bound for one unit.
2879
+ *
2880
+ * @private internal utility of `validatePipeline`
2881
+ */
2882
+ function validateTaskExpectationMin(unit, min, pipelineIdentification) {
2883
+ if (min === undefined || min >= 0) {
2884
+ return;
2885
+ }
2886
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2887
+ Min expectation of ${unit} must be zero or positive
2538
2888
 
2539
- ${block(pipelineIdentification)}
2540
- `));
2541
- }
2542
- if (max !== undefined && max <= 0) {
2543
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2544
- Max expectation of ${unit} must be positive
2889
+ ${block(pipelineIdentification)}
2890
+ `));
2891
+ }
2892
+ /**
2893
+ * Validates the maximum expectation bound for one unit.
2894
+ *
2895
+ * @private internal utility of `validatePipeline`
2896
+ */
2897
+ function validateTaskExpectationMax(unit, max, pipelineIdentification) {
2898
+ if (max === undefined || max > 0) {
2899
+ return;
2900
+ }
2901
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2902
+ Max expectation of ${unit} must be positive
2545
2903
 
2546
- ${block(pipelineIdentification)}
2547
- `));
2548
- }
2549
- }
2550
- }
2904
+ ${block(pipelineIdentification)}
2905
+ `));
2906
+ }
2907
+ /**
2908
+ * Collects the parameter names that are already resolvable before dependency traversal starts.
2909
+ *
2910
+ * @private internal utility of `validatePipeline`
2911
+ */
2912
+ function createInitialDependencyResolutionState(pipeline) {
2913
+ return {
2914
+ resolvedParameterNames: createInitiallyResolvedParameterNames(pipeline),
2915
+ unresolvedTasks: [...pipeline.tasks],
2916
+ };
2917
+ }
2918
+ /**
2919
+ * Checks whether dependency resolution still has tasks left to process.
2920
+ *
2921
+ * @private internal utility of `validatePipeline`
2922
+ */
2923
+ function hasUnresolvedTasks({ unresolvedTasks }) {
2924
+ return unresolvedTasks.length > 0;
2925
+ }
2926
+ /**
2927
+ * Resolves the next batch of currently satisfiable tasks.
2928
+ *
2929
+ * @private internal utility of `validatePipeline`
2930
+ */
2931
+ function resolveNextDependencyResolutionState(dependencyResolutionState, pipelineIdentification) {
2932
+ const currentlyResolvedTasks = getCurrentlyResolvedTasks(dependencyResolutionState.unresolvedTasks, dependencyResolutionState.resolvedParameterNames);
2933
+ if (currentlyResolvedTasks.length === 0) {
2934
+ throw createUnresolvedTasksError(dependencyResolutionState.unresolvedTasks, dependencyResolutionState.resolvedParameterNames, pipelineIdentification);
2551
2935
  }
2552
- // Note: Detect circular dependencies
2553
- let resovedParameters = pipeline.parameters
2936
+ return {
2937
+ resolvedParameterNames: appendResolvedTaskParameterNames(dependencyResolutionState.resolvedParameterNames, currentlyResolvedTasks),
2938
+ unresolvedTasks: dependencyResolutionState.unresolvedTasks.filter((task) => !currentlyResolvedTasks.includes(task)),
2939
+ };
2940
+ }
2941
+ /**
2942
+ * Collects the parameter names that are already resolvable before dependency traversal starts.
2943
+ *
2944
+ * @private internal utility of `validatePipeline`
2945
+ */
2946
+ function createInitiallyResolvedParameterNames(pipeline) {
2947
+ let resolvedParameterNames = pipeline.parameters
2554
2948
  .filter(({ isInput }) => isInput)
2555
2949
  .map(({ name }) => name);
2556
- // Note: All reserved parameters are resolved
2557
2950
  for (const reservedParameterName of RESERVED_PARAMETER_NAMES) {
2558
- resovedParameters = [...resovedParameters, reservedParameterName];
2951
+ resolvedParameterNames = [...resolvedParameterNames, reservedParameterName];
2559
2952
  }
2560
- let unresovedTasks = [...pipeline.tasks];
2561
- let loopLimit = LOOP_LIMIT;
2562
- while (unresovedTasks.length > 0) {
2563
- if (loopLimit-- < 0) {
2564
- // Note: Really UnexpectedError not LimitReachedError - this should not happen and be caught below
2565
- throw new UnexpectedError(spacetrim.spaceTrim((block) => `
2566
- Loop limit reached during detection of circular dependencies in \`validatePipeline\`
2953
+ return resolvedParameterNames;
2954
+ }
2955
+ /**
2956
+ * Adds newly resolved task outputs to the resolved parameter list.
2957
+ *
2958
+ * @private internal utility of `validatePipeline`
2959
+ */
2960
+ function appendResolvedTaskParameterNames(resolvedParameterNames, currentlyResolvedTasks) {
2961
+ return [
2962
+ ...resolvedParameterNames,
2963
+ ...currentlyResolvedTasks.map(({ resultingParameterName }) => resultingParameterName),
2964
+ ];
2965
+ }
2966
+ /**
2967
+ * Selects tasks whose dependencies are already resolved.
2968
+ *
2969
+ * @private internal utility of `validatePipeline`
2970
+ */
2971
+ function getCurrentlyResolvedTasks(unresolvedTasks, resolvedParameterNames) {
2972
+ return unresolvedTasks.filter((task) => task.dependentParameterNames.every((name) => resolvedParameterNames.includes(name)));
2973
+ }
2974
+ /**
2975
+ * Creates the unexpected loop-limit error for dependency resolution.
2976
+ *
2977
+ * @private internal utility of `validatePipeline`
2978
+ */
2979
+ function createDependencyResolutionLoopLimitError(pipelineIdentification) {
2980
+ // Note: Really UnexpectedError not LimitReachedError - this should not happen and be caught below
2981
+ return new UnexpectedError(spacetrim.spaceTrim((block) => `
2982
+ Loop limit reached during detection of circular dependencies in \`validatePipeline\`
2567
2983
 
2568
- ${block(pipelineIdentification)}
2569
- `));
2570
- }
2571
- const currentlyResovedTasks = unresovedTasks.filter((task) => task.dependentParameterNames.every((name) => resovedParameters.includes(name)));
2572
- if (currentlyResovedTasks.length === 0) {
2573
- throw new PipelineLogicError(
2574
- // TODO: [🐎] DRY
2575
- spacetrim.spaceTrim((block) => `
2984
+ ${block(pipelineIdentification)}
2985
+ `));
2986
+ }
2987
+ /**
2988
+ * Creates the detailed error for unresolved or circular task dependencies.
2989
+ *
2990
+ * @private internal utility of `validatePipeline`
2991
+ */
2992
+ function createUnresolvedTasksError(unresolvedTasks, resolvedParameterNames, pipelineIdentification) {
2993
+ return new PipelineLogicError(
2994
+ // TODO: [🐎] DRY
2995
+ spacetrim.spaceTrim((block) => `
2576
2996
 
2577
- Can not resolve some parameters:
2578
- Either you are using a parameter that is not defined, or there are some circular dependencies.
2997
+ Can not resolve some parameters:
2998
+ Either you are using a parameter that is not defined, or there are some circular dependencies.
2579
2999
 
2580
- ${block(pipelineIdentification)}
3000
+ ${block(pipelineIdentification)}
2581
3001
 
2582
- **Can not resolve:**
2583
- ${block(unresovedTasks
2584
- .map(({ resultingParameterName, dependentParameterNames }) => `- Parameter \`{${resultingParameterName}}\` which depends on ${dependentParameterNames
2585
- .map((dependentParameterName) => `\`{${dependentParameterName}}\``)
2586
- .join(' and ')}`)
2587
- .join('\n'))}
3002
+ **Can not resolve:**
3003
+ ${block(unresolvedTasks
3004
+ .map(({ resultingParameterName, dependentParameterNames }) => `- Parameter \`{${resultingParameterName}}\` which depends on ${dependentParameterNames
3005
+ .map((dependentParameterName) => `\`{${dependentParameterName}}\``)
3006
+ .join(' and ')}`)
3007
+ .join('\n'))}
2588
3008
 
2589
- **Resolved:**
2590
- ${block(resovedParameters
2591
- .filter((name) => !RESERVED_PARAMETER_NAMES.includes(name))
2592
- .map((name) => `- Parameter \`{${name}}\``)
2593
- .join('\n'))}
3009
+ **Resolved:**
3010
+ ${block(resolvedParameterNames
3011
+ .filter((name) => !RESERVED_PARAMETER_NAMES.includes(name))
3012
+ .map((name) => `- Parameter \`{${name}}\``)
3013
+ .join('\n'))}
2594
3014
 
2595
3015
 
2596
- **Reserved (which are available):**
2597
- ${block(resovedParameters
2598
- .filter((name) => RESERVED_PARAMETER_NAMES.includes(name))
2599
- .map((name) => `- Parameter \`{${name}}\``)
2600
- .join('\n'))}
3016
+ **Reserved (which are available):**
3017
+ ${block(resolvedParameterNames
3018
+ .filter((name) => RESERVED_PARAMETER_NAMES.includes(name))
3019
+ .map((name) => `- Parameter \`{${name}}\``)
3020
+ .join('\n'))}
2601
3021
 
2602
3022
 
2603
- `));
2604
- }
2605
- resovedParameters = [
2606
- ...resovedParameters,
2607
- ...currentlyResovedTasks.map(({ resultingParameterName }) => resultingParameterName),
2608
- ];
2609
- unresovedTasks = unresovedTasks.filter((task) => !currentlyResovedTasks.includes(task));
2610
- }
2611
- // Note: Check that formfactor is corresponding to the pipeline interface
2612
- // TODO: !!6 Implement this
2613
- // pipeline.formfactorName
3023
+ `));
2614
3024
  }
2615
3025
  /**
2616
3026
  * TODO: [🧞‍♀️] Do not allow joker + foreach
@@ -3288,77 +3698,288 @@
3288
3698
  // TODO: [🧠] Can this return type be better typed than void
3289
3699
 
3290
3700
  /**
3291
- * Helper to create a new task
3701
+ * Resolves the short task summary shown in the UI.
3292
3702
  *
3293
- * @private internal helper function
3703
+ * @private internal helper function of `ExecutionTask`
3294
3704
  */
3295
- function createTask(options) {
3296
- const { taskType, taskProcessCallback } = options;
3297
- let { title } = options;
3298
- // TODO: [🐙] DRY
3299
- const taskId = `${taskType.toLowerCase().substring(0, 4)}-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
3300
- let status = 'RUNNING';
3301
- const createdAt = new Date();
3302
- let updatedAt = createdAt;
3303
- const errors = [];
3304
- const warnings = [];
3305
- const llmCalls = [];
3306
- let currentValue = {};
3307
- let customTldr = null;
3308
- const partialResultSubject = new rxjs.Subject();
3309
- // <- Note: Not using `BehaviorSubject` because on error we can't access the last value
3310
- const finalResultPromise = /* not await */ taskProcessCallback((newOngoingResult) => {
3311
- if (newOngoingResult.title) {
3312
- title = newOngoingResult.title;
3313
- }
3314
- updatedAt = new Date();
3315
- Object.assign(currentValue, newOngoingResult);
3316
- // <- TODO: assign deep
3317
- partialResultSubject.next(newOngoingResult);
3318
- }, (tldrInfo) => {
3319
- customTldr = tldrInfo;
3320
- updatedAt = new Date();
3321
- }, (llmCall) => {
3322
- llmCalls.push(llmCall);
3323
- updatedAt = new Date();
3324
- });
3325
- finalResultPromise
3326
- .catch((error) => {
3327
- errors.push(error);
3328
- partialResultSubject.error(error);
3329
- })
3330
- .then((executionResult) => {
3331
- if (executionResult) {
3332
- try {
3333
- updatedAt = new Date();
3334
- errors.push(...executionResult.errors);
3335
- warnings.push(...executionResult.warnings);
3336
- // <- TODO: [🌂] Only unique errors and warnings should be added (or filtered)
3337
- // TODO: [🧠] !! errors, warning, isSuccessful are redundant both in `ExecutionTask` and `ExecutionTask.currentValue`
3338
- // Also maybe move `ExecutionTask.currentValue.usage` -> `ExecutionTask.usage`
3339
- // And delete `ExecutionTask.currentValue.preparedPipeline`
3340
- assertsTaskSuccessful(executionResult);
3341
- status = 'FINISHED';
3342
- currentValue = jsonStringsToJsons(executionResult);
3343
- // <- TODO: [🧠] Is this a good idea to convert JSON strins to JSONs?
3344
- partialResultSubject.next(executionResult);
3345
- }
3346
- catch (error) {
3347
- assertsError(error);
3348
- status = 'ERROR';
3349
- errors.push(error);
3350
- partialResultSubject.error(error);
3351
- }
3352
- }
3353
- partialResultSubject.complete();
3354
- });
3355
- async function asPromise(options) {
3356
- const { isCrashedOnError = true } = options || {};
3357
- const finalResult = await finalResultPromise;
3358
- if (isCrashedOnError) {
3359
- assertsTaskSuccessful(finalResult);
3360
- }
3361
- return finalResult;
3705
+ function resolveTaskTldr(options) {
3706
+ const { customTldr } = options;
3707
+ if (customTldr) {
3708
+ return customTldr;
3709
+ }
3710
+ return {
3711
+ percent: resolveTaskPercent(options),
3712
+ message: `${resolveTaskMessage(options)} (!!!fallback)`,
3713
+ };
3714
+ }
3715
+ /**
3716
+ * Resolves the best progress percentage for the current task state.
3717
+ *
3718
+ * @private internal helper function of `ExecutionTask`
3719
+ */
3720
+ function resolveTaskPercent(options) {
3721
+ const explicitPercent = getExplicitTaskPercent(options.currentValue);
3722
+ if (typeof explicitPercent === 'number') {
3723
+ return normalizeTaskPercent(explicitPercent);
3724
+ }
3725
+ return normalizeTaskPercent(calculateSimulatedTaskPercent(options));
3726
+ }
3727
+ /**
3728
+ * Picks a directly reported progress percentage from the task result snapshot.
3729
+ *
3730
+ * @private internal helper function of `ExecutionTask`
3731
+ */
3732
+ function getExplicitTaskPercent(currentValue) {
3733
+ var _a, _b, _c, _d, _e, _f;
3734
+ 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);
3735
+ }
3736
+ /**
3737
+ * Simulates progress when the task result does not expose an explicit percentage.
3738
+ *
3739
+ * @private internal helper function of `ExecutionTask`
3740
+ */
3741
+ function calculateSimulatedTaskPercent(options) {
3742
+ const { currentValue, status, createdAt } = options;
3743
+ const elapsedMs = new Date().getTime() - createdAt.getTime();
3744
+ const timeProgress = Math.min(elapsedMs / DEFAULT_TASK_SIMULATED_DURATION_MS, 1);
3745
+ const { subtaskCount, completedSubtasks } = summarizeTaskSubtasks(currentValue);
3746
+ if (status === 'FINISHED') {
3747
+ return 1;
3748
+ }
3749
+ if (status === 'ERROR') {
3750
+ return 0;
3751
+ }
3752
+ return Math.min(completedSubtasks / subtaskCount + (1 / subtaskCount) * timeProgress, 1);
3753
+ }
3754
+ /**
3755
+ * Counts total and completed subtasks used by the fallback progress simulation.
3756
+ *
3757
+ * @private internal helper function of `ExecutionTask`
3758
+ */
3759
+ function summarizeTaskSubtasks(currentValue) {
3760
+ if (!Array.isArray(currentValue === null || currentValue === void 0 ? void 0 : currentValue.subtasks)) {
3761
+ return { subtaskCount: 1, completedSubtasks: 0 };
3762
+ }
3763
+ return {
3764
+ subtaskCount: currentValue.subtasks.length || 1,
3765
+ completedSubtasks: currentValue.subtasks.filter(isTaskSubtaskCompleted).length,
3766
+ };
3767
+ }
3768
+ /**
3769
+ * Tells whether a task subtask is already finished.
3770
+ *
3771
+ * @private internal helper function of `ExecutionTask`
3772
+ */
3773
+ function isTaskSubtaskCompleted(subtask) {
3774
+ return subtask.done || subtask.completed || false;
3775
+ }
3776
+ /**
3777
+ * Normalizes a progress percentage into the expected `0..1` range.
3778
+ *
3779
+ * @private internal helper function of `ExecutionTask`
3780
+ */
3781
+ function normalizeTaskPercent(percentRaw) {
3782
+ let percent = Number(percentRaw) || 0;
3783
+ if (percent < 0) {
3784
+ percent = 0;
3785
+ }
3786
+ if (percent > 1) {
3787
+ percent = 1;
3788
+ }
3789
+ return percent;
3790
+ }
3791
+ /**
3792
+ * Resolves the best human-readable status message for the current task state.
3793
+ *
3794
+ * @private internal helper function of `ExecutionTask`
3795
+ */
3796
+ function resolveTaskMessage(options) {
3797
+ return (getCurrentValueMessage(options.currentValue) ||
3798
+ getCurrentSubtaskMessage(options.currentValue) ||
3799
+ getLatestIssueMessage(options.errors, 'Error') ||
3800
+ getLatestIssueMessage(options.warnings, 'Warning') ||
3801
+ getStatusMessage(options.status));
3802
+ }
3803
+ /**
3804
+ * Picks a message already reported by the current task result snapshot.
3805
+ *
3806
+ * @private internal helper function of `ExecutionTask`
3807
+ */
3808
+ function getCurrentValueMessage(currentValue) {
3809
+ var _a, _b, _c, _d;
3810
+ 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;
3811
+ }
3812
+ /**
3813
+ * Builds a fallback message from the first unfinished subtask title.
3814
+ *
3815
+ * @private internal helper function of `ExecutionTask`
3816
+ */
3817
+ function getCurrentSubtaskMessage(currentValue) {
3818
+ if (!Array.isArray(currentValue === null || currentValue === void 0 ? void 0 : currentValue.subtasks) || currentValue.subtasks.length === 0) {
3819
+ return undefined;
3820
+ }
3821
+ const currentSubtask = currentValue.subtasks.find((subtask) => !isTaskSubtaskCompleted(subtask));
3822
+ if (!(currentSubtask === null || currentSubtask === void 0 ? void 0 : currentSubtask.title)) {
3823
+ return undefined;
3824
+ }
3825
+ return `Working on ${currentSubtask.title}`;
3826
+ }
3827
+ /**
3828
+ * Picks the latest error or warning message, with the legacy generic fallback label.
3829
+ *
3830
+ * @private internal helper function of `ExecutionTask`
3831
+ */
3832
+ function getLatestIssueMessage(issues, fallbackMessage) {
3833
+ if (issues.length === 0) {
3834
+ return undefined;
3835
+ }
3836
+ return issues[issues.length - 1].message || fallbackMessage;
3837
+ }
3838
+ /**
3839
+ * Builds the final status-based fallback message.
3840
+ *
3841
+ * @private internal helper function of `ExecutionTask`
3842
+ */
3843
+ function getStatusMessage(status) {
3844
+ if (status === 'FINISHED') {
3845
+ return 'Finished';
3846
+ }
3847
+ if (status === 'ERROR') {
3848
+ return 'Error';
3849
+ }
3850
+ return 'Running';
3851
+ }
3852
+
3853
+ /**
3854
+ * Creates the initial mutable state for a task.
3855
+ *
3856
+ * @private internal helper function
3857
+ */
3858
+ function createTaskState(title, createdAt) {
3859
+ return {
3860
+ title,
3861
+ status: 'RUNNING',
3862
+ updatedAt: createdAt,
3863
+ errors: [],
3864
+ warnings: [],
3865
+ llmCalls: [],
3866
+ currentValue: {},
3867
+ customTldr: null,
3868
+ };
3869
+ }
3870
+ /**
3871
+ * Creates the partial-result updater passed into the task process callback.
3872
+ *
3873
+ * @private internal helper function
3874
+ */
3875
+ function createOngoingResultUpdater(taskState, partialResultSubject) {
3876
+ return (newOngoingResult) => {
3877
+ if (newOngoingResult.title) {
3878
+ taskState.title = newOngoingResult.title;
3879
+ }
3880
+ taskState.updatedAt = new Date();
3881
+ Object.assign(taskState.currentValue, newOngoingResult);
3882
+ // <- TODO: assign deep
3883
+ partialResultSubject.next(newOngoingResult);
3884
+ };
3885
+ }
3886
+ /**
3887
+ * Creates the custom-TLDR updater passed into the task process callback.
3888
+ *
3889
+ * @private internal helper function
3890
+ */
3891
+ function createTldrUpdater(taskState) {
3892
+ return (tldrInfo) => {
3893
+ taskState.customTldr = tldrInfo;
3894
+ taskState.updatedAt = new Date();
3895
+ };
3896
+ }
3897
+ /**
3898
+ * Creates the LLM call logger passed into the task process callback.
3899
+ *
3900
+ * @private internal helper function
3901
+ */
3902
+ function createLlmCallLogger(taskState) {
3903
+ return (llmCall) => {
3904
+ taskState.llmCalls.push(llmCall);
3905
+ taskState.updatedAt = new Date();
3906
+ };
3907
+ }
3908
+ /**
3909
+ * Wires the task promise into the observable/error lifecycle.
3910
+ *
3911
+ * @private internal helper function
3912
+ */
3913
+ function settleTaskPromise(finalResultPromise, taskState, partialResultSubject) {
3914
+ finalResultPromise
3915
+ .catch((error) => {
3916
+ taskState.errors.push(error);
3917
+ partialResultSubject.error(error);
3918
+ })
3919
+ .then((executionResult) => {
3920
+ if (executionResult) {
3921
+ try {
3922
+ finalizeTaskResult(executionResult, taskState, partialResultSubject);
3923
+ }
3924
+ catch (error) {
3925
+ failTaskResult(error, taskState, partialResultSubject);
3926
+ }
3927
+ }
3928
+ partialResultSubject.complete();
3929
+ });
3930
+ }
3931
+ /**
3932
+ * Applies the final successful task result into the mutable task state.
3933
+ *
3934
+ * @private internal helper function
3935
+ */
3936
+ function finalizeTaskResult(executionResult, taskState, partialResultSubject) {
3937
+ taskState.updatedAt = new Date();
3938
+ taskState.errors.push(...executionResult.errors);
3939
+ taskState.warnings.push(...executionResult.warnings);
3940
+ // <- TODO: [🌂] Only unique errors and warnings should be added (or filtered)
3941
+ // TODO: [🧠] !! errors, warning, isSuccessful are redundant both in `ExecutionTask` and `ExecutionTask.currentValue`
3942
+ // Also maybe move `ExecutionTask.currentValue.usage` -> `ExecutionTask.usage`
3943
+ // And delete `ExecutionTask.currentValue.preparedPipeline`
3944
+ assertsTaskSuccessful(executionResult);
3945
+ taskState.status = 'FINISHED';
3946
+ taskState.currentValue = jsonStringsToJsons(executionResult);
3947
+ // <- TODO: [🧠] Is this a good idea to convert JSON strins to JSONs?
3948
+ partialResultSubject.next(executionResult);
3949
+ }
3950
+ /**
3951
+ * Records a final-result failure after the task promise itself resolved.
3952
+ *
3953
+ * @private internal helper function
3954
+ */
3955
+ function failTaskResult(error, taskState, partialResultSubject) {
3956
+ assertsError(error);
3957
+ taskState.status = 'ERROR';
3958
+ taskState.errors.push(error);
3959
+ partialResultSubject.error(error);
3960
+ }
3961
+ /**
3962
+ * Helper to create a new task
3963
+ *
3964
+ * @private internal helper function
3965
+ */
3966
+ function createTask(options) {
3967
+ const { taskType, title, taskProcessCallback } = options;
3968
+ // TODO: [🐙] DRY
3969
+ const taskId = `${taskType.toLowerCase().substring(0, 4)}-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
3970
+ const createdAt = new Date();
3971
+ const taskState = createTaskState(title, createdAt);
3972
+ const partialResultSubject = new rxjs.Subject();
3973
+ // <- Note: Not using `BehaviorSubject` because on error we can't access the last value
3974
+ const finalResultPromise = /* not await */ taskProcessCallback(createOngoingResultUpdater(taskState, partialResultSubject), createTldrUpdater(taskState), createLlmCallLogger(taskState));
3975
+ settleTaskPromise(finalResultPromise, taskState, partialResultSubject);
3976
+ async function asPromise(options) {
3977
+ const { isCrashedOnError = true } = options || {};
3978
+ const finalResult = await finalResultPromise;
3979
+ if (isCrashedOnError) {
3980
+ assertsTaskSuccessful(finalResult);
3981
+ }
3982
+ return finalResult;
3362
3983
  }
3363
3984
  return {
3364
3985
  taskType,
@@ -3367,91 +3988,29 @@
3367
3988
  return PROMPTBOOK_ENGINE_VERSION;
3368
3989
  },
3369
3990
  get title() {
3370
- return title;
3991
+ return taskState.title;
3371
3992
  // <- Note: [1] These must be getters to allow changing the value in the future
3372
3993
  },
3373
3994
  get status() {
3374
- return status;
3995
+ return taskState.status;
3375
3996
  // <- Note: [1] --||--
3376
3997
  },
3377
3998
  get tldr() {
3378
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
3379
- // Use custom tldr if available
3380
- if (customTldr) {
3381
- return customTldr;
3382
- }
3383
- // Fallback to default implementation
3384
- const cv = currentValue;
3385
- // If explicit percent is provided, use it
3386
- 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;
3387
- // Simulate progress if not provided
3388
- if (typeof percentRaw !== 'number') {
3389
- // Simulate progress: evenly split across subtasks, based on elapsed time
3390
- const now = new Date();
3391
- const elapsedMs = now.getTime() - createdAt.getTime();
3392
- const totalMs = DEFAULT_TASK_SIMULATED_DURATION_MS;
3393
- // If subtasks are defined, split progress evenly
3394
- const subtaskCount = Array.isArray(cv === null || cv === void 0 ? void 0 : cv.subtasks) ? cv.subtasks.length : 1;
3395
- const completedSubtasks = Array.isArray(cv === null || cv === void 0 ? void 0 : cv.subtasks)
3396
- ? cv.subtasks.filter((s) => s.done || s.completed).length
3397
- : 0;
3398
- // Progress from completed subtasks
3399
- const subtaskProgress = subtaskCount > 0 ? completedSubtasks / subtaskCount : 0;
3400
- // Progress from elapsed time for current subtask
3401
- const timeProgress = Math.min(elapsedMs / totalMs, 1);
3402
- // Combine: completed subtasks + time progress for current subtask
3403
- percentRaw = Math.min(subtaskProgress + (1 / subtaskCount) * timeProgress, 1);
3404
- if (status === 'FINISHED')
3405
- percentRaw = 1;
3406
- if (status === 'ERROR')
3407
- percentRaw = 0;
3408
- }
3409
- // Clamp to [0,1]
3410
- let percent = Number(percentRaw) || 0;
3411
- if (percent < 0)
3412
- percent = 0;
3413
- if (percent > 1)
3414
- percent = 1;
3415
- // Build a short message: prefer explicit tldr.message, then common summary/message fields, then errors/warnings, then status
3416
- 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;
3417
- let message = messageFromResult;
3418
- if (!message) {
3419
- // If subtasks, show current subtask
3420
- if (Array.isArray(cv === null || cv === void 0 ? void 0 : cv.subtasks) && cv.subtasks.length > 0) {
3421
- const current = cv.subtasks.find((s) => !s.done && !s.completed);
3422
- if (current && current.title) {
3423
- message = `Working on ${current.title}`;
3424
- }
3425
- }
3426
- if (!message) {
3427
- if (errors.length) {
3428
- message = errors[errors.length - 1].message || 'Error';
3429
- }
3430
- else if (warnings.length) {
3431
- message = warnings[warnings.length - 1].message || 'Warning';
3432
- }
3433
- else if (status === 'FINISHED') {
3434
- message = 'Finished';
3435
- }
3436
- else if (status === 'ERROR') {
3437
- message = 'Error';
3438
- }
3439
- else {
3440
- message = 'Running';
3441
- }
3442
- }
3443
- }
3444
- return {
3445
- percent: percent,
3446
- message: message + ' (!!!fallback)',
3447
- };
3999
+ return resolveTaskTldr({
4000
+ customTldr: taskState.customTldr,
4001
+ currentValue: taskState.currentValue,
4002
+ status: taskState.status,
4003
+ createdAt,
4004
+ errors: taskState.errors,
4005
+ warnings: taskState.warnings,
4006
+ });
3448
4007
  },
3449
4008
  get createdAt() {
3450
4009
  return createdAt;
3451
4010
  // <- Note: [1] --||--
3452
4011
  },
3453
4012
  get updatedAt() {
3454
- return updatedAt;
4013
+ return taskState.updatedAt;
3455
4014
  // <- Note: [1] --||--
3456
4015
  },
3457
4016
  asPromise,
@@ -3459,19 +4018,19 @@
3459
4018
  return partialResultSubject.asObservable();
3460
4019
  },
3461
4020
  get errors() {
3462
- return errors;
4021
+ return taskState.errors;
3463
4022
  // <- Note: [1] --||--
3464
4023
  },
3465
4024
  get warnings() {
3466
- return warnings;
4025
+ return taskState.warnings;
3467
4026
  // <- Note: [1] --||--
3468
4027
  },
3469
4028
  get llmCalls() {
3470
- return [...llmCalls, { foo: '!!! bar' }];
4029
+ return [...taskState.llmCalls, { foo: '!!! bar' }];
3471
4030
  // <- Note: [1] --||--
3472
4031
  },
3473
4032
  get currentValue() {
3474
- return currentValue;
4033
+ return taskState.currentValue;
3475
4034
  // <- Note: [1] --||--
3476
4035
  },
3477
4036
  };
@@ -4752,223 +5311,288 @@
4752
5311
  * @public exported from `@promptbook/core`
4753
5312
  */
4754
5313
  async function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
4755
- var _a;
4756
- const { fetch = promptbookFetch } = tools;
4757
5314
  const { knowledgeSourceContent } = knowledgeSource;
4758
- let { name } = knowledgeSource;
4759
- const { rootDirname = null,
4760
- // <- TODO: process.cwd() if running in Node.js
4761
- isVerbose = DEFAULT_IS_VERBOSE, } = options || {};
4762
- if (!name) {
4763
- name = knowledgeSourceContentToName(knowledgeSourceContent);
4764
- }
5315
+ const name = knowledgeSource.name || knowledgeSourceContentToName(knowledgeSourceContent);
5316
+ const { rootDirname = null, isVerbose = DEFAULT_IS_VERBOSE } = options || {};
4765
5317
  if (isValidUrl(knowledgeSourceContent)) {
4766
- const url = knowledgeSourceContent;
4767
- if (isVerbose) {
4768
- console.info(`📄 [1] "${name}" is available at "${url}"`);
4769
- }
4770
- const response = await fetch(url); // <- TODO: [🧠] Scraping and fetch proxy
4771
- const mimeType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
4772
- if (tools.fs === undefined || !url.endsWith('.pdf' /* <- TODO: [💵] */)) {
4773
- if (isVerbose) {
4774
- console.info(`📄 [2] "${name}" tools.fs is not available or URL is not a PDF.`);
4775
- }
4776
- return {
4777
- source: name,
4778
- filename: null,
4779
- url,
4780
- mimeType,
4781
- /*
4782
- TODO: [🥽]
4783
- > async asBlob() {
4784
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
4785
- > const content = await response.blob();
4786
- > return content;
4787
- > },
4788
- */
4789
- async asJson() {
4790
- // TODO: [👨🏻‍🤝‍👨🏻]
4791
- const content = await response.json();
4792
- return content;
4793
- },
4794
- async asText() {
4795
- // TODO: [👨🏻‍🤝‍👨🏻]
4796
- const content = await response.text();
4797
- return content;
4798
- },
4799
- };
4800
- }
4801
- const basename = url.split('/').pop() || titleToName(url);
4802
- const hash = sha256__default["default"](hexEncoder__default["default"].parse(url)).toString( /* hex */);
4803
- // <- TODO: [🥬] Encapsulate sha256 to some private utility function
4804
- const rootDirname = path.join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
4805
- const filepath = path.join(...nameToSubfolderPath(hash /* <- TODO: [🎎] Maybe add some SHA256 prefix */), `${basename.substring(0, MAX_FILENAME_LENGTH)}.${mimeTypeToExtension(mimeType)}`);
4806
- // Note: Try to create cache directory, but don't fail if filesystem has issues
4807
- try {
4808
- await tools.fs.mkdir(path.dirname(path.join(rootDirname, filepath)), { recursive: true });
4809
- }
4810
- catch (error) {
4811
- if (isVerbose) {
4812
- console.info(`📄 [3] "${name}" error creating cache directory`);
4813
- }
4814
- // Note: If we can't create cache directory, we'll handle it when trying to write the file
4815
- // This handles read-only filesystems, permission issues, and missing parent directories
4816
- if (error instanceof Error &&
4817
- (error.message.includes('EROFS') ||
4818
- error.message.includes('read-only') ||
4819
- error.message.includes('EACCES') ||
4820
- error.message.includes('EPERM') ||
4821
- error.message.includes('ENOENT'))) ;
4822
- else {
4823
- // Re-throw other unexpected errors
4824
- throw error;
4825
- }
4826
- }
4827
- const fileContent = Buffer.from(await response.arrayBuffer());
4828
- if (fileContent.length > DEFAULT_MAX_FILE_SIZE /* <- TODO: Allow to pass different value to remote server */) {
4829
- 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.`);
4830
- }
4831
- // Note: Try to cache the downloaded file, but don't fail if the filesystem is read-only
4832
- try {
4833
- await tools.fs.writeFile(path.join(rootDirname, filepath), fileContent);
4834
- }
4835
- catch (error) {
4836
- if (isVerbose) {
4837
- console.info(`📄 [4] "${name}" error writing cache file`);
4838
- }
4839
- // Note: If we can't write to cache, we'll process the file directly from memory
4840
- // This handles read-only filesystems like Vercel
4841
- if (error instanceof Error &&
4842
- (error.message.includes('EROFS') ||
4843
- error.message.includes('read-only') ||
4844
- error.message.includes('EACCES') ||
4845
- error.message.includes('EPERM') ||
4846
- error.message.includes('ENOENT'))) {
4847
- // Return a handler that works directly with the downloaded content
4848
- return {
4849
- source: name,
4850
- filename: null,
4851
- url,
4852
- mimeType,
4853
- async asJson() {
4854
- return JSON.parse(fileContent.toString('utf-8'));
4855
- },
4856
- async asText() {
4857
- return fileContent.toString('utf-8');
4858
- },
4859
- };
4860
- }
4861
- else {
4862
- // Re-throw other unexpected errors
4863
- throw error;
4864
- }
4865
- }
4866
- // TODO: [💵] Check the file security
4867
- // TODO: [🧹][🧠] Delete the file after the scraping is done
4868
- if (isVerbose) {
4869
- console.info(`📄 [5] "${name}" cached at "${path.join(rootDirname, filepath)}"`);
4870
- }
4871
- return makeKnowledgeSourceHandler({ name, knowledgeSourceContent: filepath }, tools, {
4872
- ...options,
4873
- rootDirname,
4874
- });
4875
- }
4876
- else if (isValidFilePath(knowledgeSourceContent)) {
4877
- if (tools.fs === undefined) {
4878
- throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
4879
- // <- TODO: [🧠] What is the best error type here`
4880
- }
4881
- if (rootDirname === null) {
4882
- throw new EnvironmentMismatchError('Can not import file knowledge in non-file pipeline');
4883
- // <- TODO: [🧠] What is the best error type here`
4884
- }
4885
- const filename = path.isAbsolute(knowledgeSourceContent)
4886
- ? knowledgeSourceContent
4887
- : path.join(rootDirname, knowledgeSourceContent).split('\\').join('/');
4888
- if (isVerbose) {
4889
- console.info(`📄 [6] "${name}" is a valid file "${filename}"`);
4890
- }
4891
- const fileExtension = getFileExtension(filename);
4892
- const mimeType = extensionToMimeType(fileExtension || '');
4893
- if (!(await isFileExisting(filename, tools.fs))) {
4894
- throw new NotFoundError(spacetrim.spaceTrim((block) => `
4895
- Can not make source handler for file which does not exist:
4896
-
4897
- File:
4898
- ${block(knowledgeSourceContent)}
4899
-
4900
- Full file path:
4901
- ${block(filename)}
4902
- `));
4903
- }
4904
- // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
4905
- return {
4906
- source: name,
4907
- filename,
4908
- url: null,
4909
- mimeType,
4910
- /*
4911
- TODO: [🥽]
4912
- > async asBlob() {
4913
- > const content = await tools.fs!.readFile(filename);
4914
- > return new Blob(
4915
- > [
4916
- > content,
4917
- > // <- TODO: [🥽] This is NOT tested, test it
4918
- > ],
4919
- > { type: mimeType },
4920
- > );
4921
- > },
4922
- */
4923
- async asJson() {
4924
- return jsonParse(await tools.fs.readFile(filename, 'utf-8'));
4925
- },
4926
- async asText() {
4927
- return await tools.fs.readFile(filename, 'utf-8');
4928
- },
4929
- };
5318
+ return makeUrlKnowledgeSourceHandler(knowledgeSourceContent, name, tools, options, isVerbose);
4930
5319
  }
4931
- else {
4932
- if (isVerbose) {
4933
- console.info(`📄 [7] "${name}" is just a explicit string text with a knowledge source`);
4934
- console.info('---');
4935
- console.info(knowledgeSourceContent);
4936
- console.info('---');
4937
- }
4938
- return {
4939
- source: name,
4940
- filename: null,
4941
- url: null,
4942
- mimeType: 'text/markdown',
4943
- asText() {
4944
- return knowledgeSource.knowledgeSourceContent;
4945
- },
4946
- asJson() {
4947
- throw new UnexpectedError('Did not expect that `markdownScraper` would need to get the content `asJson`');
4948
- },
4949
- /*
4950
- TODO: [🥽]
4951
- > asBlob() {
4952
- > throw new UnexpectedError(
4953
- > 'Did not expect that `markdownScraper` would need to get the content `asBlob`',
4954
- > );
4955
- > },
4956
- */
4957
- };
5320
+ if (isValidFilePath(knowledgeSourceContent)) {
5321
+ return makeFileKnowledgeSourceHandler(knowledgeSourceContent, name, tools, rootDirname, isVerbose);
4958
5322
  }
5323
+ return makeInlineTextKnowledgeSourceHandler(knowledgeSourceContent, name, isVerbose);
4959
5324
  }
4960
-
4961
5325
  /**
4962
- * Prepares the knowledge pieces
5326
+ * Creates a source handler for URL-based knowledge.
4963
5327
  *
4964
- * @see https://github.com/webgptorg/promptbook/discussions/41
5328
+ * @private internal utility of `makeKnowledgeSourceHandler`
5329
+ */
5330
+ async function makeUrlKnowledgeSourceHandler(url, name, tools, options, isVerbose) {
5331
+ var _a;
5332
+ const { fetch = promptbookFetch } = tools;
5333
+ if (isVerbose) {
5334
+ console.info(`📄 [1] "${name}" is available at "${url}"`);
5335
+ }
5336
+ const response = await fetch(url); // <- TODO: [🧠] Scraping and fetch proxy
5337
+ const mimeType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
5338
+ if (tools.fs === undefined || !url.endsWith('.pdf' /* <- TODO: [💵] */)) {
5339
+ return makeRemoteResponseKnowledgeSourceHandler(name, url, mimeType, response, isVerbose);
5340
+ }
5341
+ return cachePdfKnowledgeSourceHandler(url, name, mimeType, response, tools, options, isVerbose);
5342
+ }
5343
+ /**
5344
+ * Creates a source handler that reads directly from a fetched response.
4965
5345
  *
4966
- * @public exported from `@promptbook/core`
5346
+ * @private internal utility of `makeKnowledgeSourceHandler`
4967
5347
  */
4968
- async function prepareKnowledgePieces(knowledgeSources, tools, options) {
4969
- const { maxParallelCount = DEFAULT_MAX_PARALLEL_COUNT, rootDirname, isVerbose = DEFAULT_IS_VERBOSE } = options;
4970
- const knowledgePreparedUnflatten = new Array(knowledgeSources.length);
4971
- await forEachAsync(knowledgeSources, { maxParallelCount }, async (knowledgeSource, index) => {
5348
+ function makeRemoteResponseKnowledgeSourceHandler(name, url, mimeType, response, isVerbose) {
5349
+ if (isVerbose) {
5350
+ console.info(`📄 [2] "${name}" tools.fs is not available or URL is not a PDF.`);
5351
+ }
5352
+ return {
5353
+ source: name,
5354
+ filename: null,
5355
+ url,
5356
+ mimeType,
5357
+ /*
5358
+ TODO: [🥽]
5359
+ > async asBlob() {
5360
+ > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
5361
+ > const content = await response.blob();
5362
+ > return content;
5363
+ > },
5364
+ */
5365
+ async asJson() {
5366
+ // TODO: [👨🏻‍🤝‍👨🏻]
5367
+ const content = await response.json();
5368
+ return content;
5369
+ },
5370
+ async asText() {
5371
+ // TODO: [👨🏻‍🤝‍👨🏻]
5372
+ const content = await response.text();
5373
+ return content;
5374
+ },
5375
+ };
5376
+ }
5377
+ /**
5378
+ * Downloads a PDF knowledge source into cache when possible and falls back to in-memory content otherwise.
5379
+ *
5380
+ * @private internal utility of `makeKnowledgeSourceHandler`
5381
+ */
5382
+ async function cachePdfKnowledgeSourceHandler(url, name, mimeType, response, tools, options, isVerbose) {
5383
+ const rootDirname = path.join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
5384
+ const filepath = createDownloadedKnowledgeSourceFilepath(url, mimeType);
5385
+ const fullFilepath = path.join(rootDirname, filepath);
5386
+ await createCacheDirectoryIfPossible(name, fullFilepath, tools, isVerbose);
5387
+ const fileContent = Buffer.from(await response.arrayBuffer());
5388
+ if (fileContent.length > DEFAULT_MAX_FILE_SIZE /* <- TODO: Allow to pass different value to remote server */) {
5389
+ 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.`);
5390
+ }
5391
+ const isCached = await writeCacheFileIfPossible(name, fullFilepath, fileContent, tools, isVerbose);
5392
+ if (!isCached) {
5393
+ return makeBufferedKnowledgeSourceHandler(name, url, mimeType, fileContent);
5394
+ }
5395
+ // TODO: [💵] Check the file security
5396
+ // TODO: [🧹][🧠] Delete the file after the scraping is done
5397
+ if (isVerbose) {
5398
+ console.info(`📄 [5] "${name}" cached at "${fullFilepath}"`);
5399
+ }
5400
+ return makeKnowledgeSourceHandler({ name, knowledgeSourceContent: filepath }, tools, {
5401
+ ...options,
5402
+ rootDirname,
5403
+ });
5404
+ }
5405
+ /**
5406
+ * Builds a stable cache filepath for a downloaded knowledge source.
5407
+ *
5408
+ * @private internal utility of `makeKnowledgeSourceHandler`
5409
+ */
5410
+ function createDownloadedKnowledgeSourceFilepath(url, mimeType) {
5411
+ const basename = url.split('/').pop() || titleToName(url);
5412
+ const hash = sha256__default["default"](hexEncoder__default["default"].parse(url)).toString( /* hex */);
5413
+ // <- TODO: [🥬] Encapsulate sha256 to some private utility function
5414
+ return path.join(...nameToSubfolderPath(hash /* <- TODO: [🎎] Maybe add some SHA256 prefix */), `${basename.substring(0, MAX_FILENAME_LENGTH)}.${mimeTypeToExtension(mimeType)}`);
5415
+ }
5416
+ /**
5417
+ * Tries to create the cache directory needed for a downloaded knowledge source.
5418
+ *
5419
+ * @private internal utility of `makeKnowledgeSourceHandler`
5420
+ */
5421
+ async function createCacheDirectoryIfPossible(name, fullFilepath, tools, isVerbose) {
5422
+ try {
5423
+ await tools.fs.mkdir(path.dirname(fullFilepath), { recursive: true });
5424
+ }
5425
+ catch (error) {
5426
+ if (isVerbose) {
5427
+ console.info(`📄 [3] "${name}" error creating cache directory`);
5428
+ }
5429
+ // Note: If we can't create cache directory, we'll handle it when trying to write the file
5430
+ // This handles read-only filesystems, permission issues, and missing parent directories
5431
+ if (!isIgnorableCacheFilesystemError(error)) {
5432
+ throw error;
5433
+ }
5434
+ }
5435
+ }
5436
+ /**
5437
+ * Tries to write downloaded content into cache and reports whether the cache was usable.
5438
+ *
5439
+ * @private internal utility of `makeKnowledgeSourceHandler`
5440
+ */
5441
+ async function writeCacheFileIfPossible(name, fullFilepath, fileContent, tools, isVerbose) {
5442
+ // Note: Try to cache the downloaded file, but don't fail if the filesystem is read-only
5443
+ try {
5444
+ await tools.fs.writeFile(fullFilepath, fileContent);
5445
+ return true;
5446
+ }
5447
+ catch (error) {
5448
+ if (isVerbose) {
5449
+ console.info(`📄 [4] "${name}" error writing cache file`);
5450
+ }
5451
+ // Note: If we can't write to cache, we'll process the file directly from memory
5452
+ // This handles read-only filesystems like Vercel
5453
+ if (isIgnorableCacheFilesystemError(error)) {
5454
+ return false;
5455
+ }
5456
+ throw error;
5457
+ }
5458
+ }
5459
+ /**
5460
+ * Detects filesystem errors that should not fail optional caching.
5461
+ *
5462
+ * @private internal utility of `makeKnowledgeSourceHandler`
5463
+ */
5464
+ function isIgnorableCacheFilesystemError(error) {
5465
+ return (error instanceof Error &&
5466
+ (error.message.includes('EROFS') ||
5467
+ error.message.includes('read-only') ||
5468
+ error.message.includes('EACCES') ||
5469
+ error.message.includes('EPERM') ||
5470
+ error.message.includes('ENOENT')));
5471
+ }
5472
+ /**
5473
+ * Creates a source handler backed by already downloaded file content kept in memory.
5474
+ *
5475
+ * @private internal utility of `makeKnowledgeSourceHandler`
5476
+ */
5477
+ function makeBufferedKnowledgeSourceHandler(name, url, mimeType, fileContent) {
5478
+ return {
5479
+ source: name,
5480
+ filename: null,
5481
+ url,
5482
+ mimeType,
5483
+ async asJson() {
5484
+ return JSON.parse(fileContent.toString('utf-8'));
5485
+ },
5486
+ async asText() {
5487
+ return fileContent.toString('utf-8');
5488
+ },
5489
+ };
5490
+ }
5491
+ /**
5492
+ * Creates a source handler for file-based knowledge.
5493
+ *
5494
+ * @private internal utility of `makeKnowledgeSourceHandler`
5495
+ */
5496
+ async function makeFileKnowledgeSourceHandler(knowledgeSourceContent, name, tools, rootDirname, isVerbose) {
5497
+ if (tools.fs === undefined) {
5498
+ throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
5499
+ // <- TODO: [🧠] What is the best error type here`
5500
+ }
5501
+ if (rootDirname === null) {
5502
+ throw new EnvironmentMismatchError('Can not import file knowledge in non-file pipeline');
5503
+ // <- TODO: [🧠] What is the best error type here`
5504
+ }
5505
+ const filename = path.isAbsolute(knowledgeSourceContent)
5506
+ ? knowledgeSourceContent
5507
+ : path.join(rootDirname, knowledgeSourceContent).split('\\').join('/');
5508
+ if (isVerbose) {
5509
+ console.info(`📄 [6] "${name}" is a valid file "${filename}"`);
5510
+ }
5511
+ const fileExtension = getFileExtension(filename);
5512
+ const mimeType = extensionToMimeType(fileExtension || '');
5513
+ if (!(await isFileExisting(filename, tools.fs))) {
5514
+ throw new NotFoundError(spacetrim.spaceTrim((block) => `
5515
+ Can not make source handler for file which does not exist:
5516
+
5517
+ File:
5518
+ ${block(knowledgeSourceContent)}
5519
+
5520
+ Full file path:
5521
+ ${block(filename)}
5522
+ `));
5523
+ }
5524
+ // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
5525
+ return {
5526
+ source: name,
5527
+ filename,
5528
+ url: null,
5529
+ mimeType,
5530
+ /*
5531
+ TODO: [🥽]
5532
+ > async asBlob() {
5533
+ > const content = await tools.fs!.readFile(filename);
5534
+ > return new Blob(
5535
+ > [
5536
+ > content,
5537
+ > // <- TODO: [🥽] This is NOT tested, test it
5538
+ > ],
5539
+ > { type: mimeType },
5540
+ > );
5541
+ > },
5542
+ */
5543
+ async asJson() {
5544
+ return jsonParse(await tools.fs.readFile(filename, 'utf-8'));
5545
+ },
5546
+ async asText() {
5547
+ return await tools.fs.readFile(filename, 'utf-8');
5548
+ },
5549
+ };
5550
+ }
5551
+ /**
5552
+ * Creates a source handler for inline text knowledge.
5553
+ *
5554
+ * @private internal utility of `makeKnowledgeSourceHandler`
5555
+ */
5556
+ function makeInlineTextKnowledgeSourceHandler(knowledgeSourceContent, name, isVerbose) {
5557
+ if (isVerbose) {
5558
+ console.info(`📄 [7] "${name}" is just a explicit string text with a knowledge source`);
5559
+ console.info('---');
5560
+ console.info(knowledgeSourceContent);
5561
+ console.info('---');
5562
+ }
5563
+ return {
5564
+ source: name,
5565
+ filename: null,
5566
+ url: null,
5567
+ mimeType: 'text/markdown',
5568
+ asText() {
5569
+ return knowledgeSourceContent;
5570
+ },
5571
+ asJson() {
5572
+ throw new UnexpectedError('Did not expect that `markdownScraper` would need to get the content `asJson`');
5573
+ },
5574
+ /*
5575
+ TODO: [🥽]
5576
+ > asBlob() {
5577
+ > throw new UnexpectedError(
5578
+ > 'Did not expect that `markdownScraper` would need to get the content `asBlob`',
5579
+ > );
5580
+ > },
5581
+ */
5582
+ };
5583
+ }
5584
+
5585
+ /**
5586
+ * Prepares the knowledge pieces
5587
+ *
5588
+ * @see https://github.com/webgptorg/promptbook/discussions/41
5589
+ *
5590
+ * @public exported from `@promptbook/core`
5591
+ */
5592
+ async function prepareKnowledgePieces(knowledgeSources, tools, options) {
5593
+ const { maxParallelCount = DEFAULT_MAX_PARALLEL_COUNT, rootDirname, isVerbose = DEFAULT_IS_VERBOSE } = options;
5594
+ const knowledgePreparedUnflatten = new Array(knowledgeSources.length);
5595
+ await forEachAsync(knowledgeSources, { maxParallelCount }, async (knowledgeSource, index) => {
4972
5596
  try {
4973
5597
  let partialPieces = null;
4974
5598
  const sourceHandler = await makeKnowledgeSourceHandler(knowledgeSource, tools, { rootDirname, isVerbose });
@@ -6240,112 +6864,10 @@
6240
6864
  }
6241
6865
  }
6242
6866
 
6243
- /**
6244
- * Executes a pipeline task with multiple attempts, including joker and retry logic. Handles different task types
6245
- * (prompt, script, dialog, etc.), applies postprocessing, checks expectations, and updates the execution report.
6246
- * Throws errors if execution fails after all attempts.
6247
- *
6248
- * @param options - The options for execution, including task, parameters, pipeline, and configuration.
6249
- * @returns The result string of the executed task.
6250
- *
6251
- * @private internal utility of `createPipelineExecutor`
6252
- */
6253
- async function executeAttempts(options) {
6254
- const $ongoingTaskResult = createOngoingTaskResult();
6255
- const llmTools = getSingleLlmExecutionTools(options.tools.llm);
6256
- attempts: for (let attemptIndex = -options.jokerParameterNames.length; attemptIndex < options.maxAttempts; attemptIndex++) {
6257
- const attempt = createAttemptDescriptor({
6258
- attemptIndex,
6259
- jokerParameterNames: options.jokerParameterNames,
6260
- pipelineIdentification: options.pipelineIdentification,
6261
- });
6262
- resetAttemptExecutionState($ongoingTaskResult);
6263
- try {
6264
- await executeSingleAttempt({
6265
- attempt,
6266
- options,
6267
- llmTools,
6268
- $ongoingTaskResult,
6269
- });
6270
- break attempts;
6271
- }
6272
- catch (error) {
6273
- if (!(error instanceof ExpectError)) {
6274
- throw error;
6275
- }
6276
- recordFailedAttempt({
6277
- error,
6278
- attemptIndex,
6279
- onProgress: options.onProgress,
6280
- $ongoingTaskResult,
6281
- });
6282
- }
6283
- finally {
6284
- reportPromptExecution({
6285
- attempt,
6286
- task: options.task,
6287
- $executionReport: options.$executionReport,
6288
- logLlmCall: options.logLlmCall,
6289
- $ongoingTaskResult,
6290
- });
6291
- }
6292
- throwIfFinalAttemptFailed({
6293
- attemptIndex,
6294
- maxAttempts: options.maxAttempts,
6295
- maxExecutionAttempts: options.maxExecutionAttempts,
6296
- pipelineIdentification: options.pipelineIdentification,
6297
- $ongoingTaskResult,
6298
- });
6299
- }
6300
- return getSuccessfulResultString({
6301
- pipelineIdentification: options.pipelineIdentification,
6302
- $ongoingTaskResult,
6303
- });
6304
- }
6305
- /**
6306
- * Creates mutable attempt state for one task execution lifecycle.
6307
- */
6308
- function createOngoingTaskResult() {
6309
- return {
6310
- $result: null,
6311
- $resultString: null,
6312
- $expectError: null,
6313
- $scriptPipelineExecutionErrors: [],
6314
- $failedResults: [],
6315
- };
6316
- }
6317
- /**
6318
- * Resolves the bookkeeping for one loop iteration, including joker lookup.
6319
- */
6320
- function createAttemptDescriptor(options) {
6321
- const { attemptIndex, jokerParameterNames, pipelineIdentification } = options;
6322
- const isJokerAttempt = attemptIndex < 0;
6323
- const jokerParameterName = isJokerAttempt
6324
- ? jokerParameterNames[jokerParameterNames.length + attemptIndex]
6325
- : undefined;
6326
- if (isJokerAttempt && !jokerParameterName) {
6327
- throw new UnexpectedError(spacetrim.spaceTrim((block) => `
6328
- Joker not found in attempt ${attemptIndex}
6329
-
6330
- ${block(pipelineIdentification)}
6331
- `));
6332
- }
6333
- return {
6334
- attemptIndex,
6335
- isJokerAttempt,
6336
- jokerParameterName,
6337
- };
6338
- }
6339
- /**
6340
- * Clears the per-attempt result slots while preserving cumulative failure history.
6341
- */
6342
- function resetAttemptExecutionState($ongoingTaskResult) {
6343
- $ongoingTaskResult.$result = null;
6344
- $ongoingTaskResult.$resultString = null;
6345
- $ongoingTaskResult.$expectError = null;
6346
- }
6347
6867
  /**
6348
6868
  * Executes one loop iteration, from joker resolution or task execution through validation.
6869
+ *
6870
+ * @private function of `executeAttempts`
6349
6871
  */
6350
6872
  async function executeSingleAttempt(options) {
6351
6873
  const { attempt, options: executeAttemptsOptions, llmTools, $ongoingTaskResult } = options;
@@ -6660,11 +7182,15 @@
6660
7182
  // Update the result string in case format processing modified it (e.g., JSON extraction)
6661
7183
  $ongoingTaskResult.$resultString = validationResult.processedResultString;
6662
7184
  }
7185
+
6663
7186
  /**
6664
- * Stores one failed attempt and reports the expectation error upstream.
7187
+ * Stores one failed attempt, reports the expectation error, and throws the aggregated retry error after the final
7188
+ * regular attempt.
7189
+ *
7190
+ * @private function of `executeAttempts`
6665
7191
  */
6666
- function recordFailedAttempt(options) {
6667
- const { error, attemptIndex, onProgress, $ongoingTaskResult } = options;
7192
+ function handleAttemptFailure(options) {
7193
+ const { error, attemptIndex, maxAttempts, maxExecutionAttempts, onProgress, pipelineIdentification, $ongoingTaskResult, } = options;
6668
7194
  $ongoingTaskResult.$expectError = error;
6669
7195
  $ongoingTaskResult.$failedResults.push({
6670
7196
  attemptIndex,
@@ -6674,39 +7200,7 @@
6674
7200
  onProgress({
6675
7201
  errors: [error],
6676
7202
  });
6677
- }
6678
- /**
6679
- * Appends the prompt execution report for prompt-task attempts.
6680
- */
6681
- function reportPromptExecution(options) {
6682
- const { attempt, task, $executionReport, logLlmCall, $ongoingTaskResult } = options;
6683
- if (attempt.isJokerAttempt || task.taskType !== 'PROMPT_TASK' || !$ongoingTaskResult.$prompt) {
6684
- return;
6685
- }
6686
- // Note: [2] When some expected parameter is not defined, error will occur in templateParameters
6687
- // In that case we don’t want to make a report about it because it’s not a llm execution error
6688
- const executionPromptReport = {
6689
- prompt: {
6690
- ...$ongoingTaskResult.$prompt,
6691
- // <- TODO: [🧠] How to pick everyhing except `pipelineUrl`
6692
- },
6693
- result: $ongoingTaskResult.$result || undefined,
6694
- error: $ongoingTaskResult.$expectError === null ? undefined : serializeError($ongoingTaskResult.$expectError),
6695
- };
6696
- $executionReport.promptExecutions.push(executionPromptReport);
6697
- if (logLlmCall) {
6698
- logLlmCall({
6699
- modelName: 'model' /* <- TODO: How to get model name from the report */,
6700
- report: executionPromptReport,
6701
- });
6702
- }
6703
- }
6704
- /**
6705
- * Throws the aggregated retry error after the last regular attempt fails expectations.
6706
- */
6707
- function throwIfFinalAttemptFailed(options) {
6708
- const { attemptIndex, maxAttempts, maxExecutionAttempts, pipelineIdentification, $ongoingTaskResult } = options;
6709
- if ($ongoingTaskResult.$expectError === null || attemptIndex !== maxAttempts - 1) {
7203
+ if (attemptIndex !== maxAttempts - 1) {
6710
7204
  return;
6711
7205
  }
6712
7206
  throw new PipelineExecutionError(spacetrim.spaceTrim((block) => {
@@ -6737,7 +7231,9 @@
6737
7231
  ${block(quoteMultilineText(((_b = failure.error) === null || _b === void 0 ? void 0 : _b.message) || ''))}
6738
7232
 
6739
7233
  Result:
6740
- ${block(failure.result === null ? 'null' : quoteMultilineText(spacetrim.spaceTrim(failure.result)))}
7234
+ ${block(failure.result === null
7235
+ ? 'null'
7236
+ : quoteMultilineText(spacetrim.spaceTrim(failure.result)))}
6741
7237
  `;
6742
7238
  }))
6743
7239
  .join('\n\n---\n\n');
@@ -6751,6 +7247,136 @@
6751
7247
  .map((line) => `> ${line}`)
6752
7248
  .join('\n');
6753
7249
  }
7250
+
7251
+ /**
7252
+ * Appends the prompt execution report for prompt-task attempts.
7253
+ *
7254
+ * @private function of `executeAttempts`
7255
+ */
7256
+ function reportPromptExecution(options) {
7257
+ const { attempt, task, $executionReport, logLlmCall, $ongoingTaskResult } = options;
7258
+ if (attempt.isJokerAttempt || task.taskType !== 'PROMPT_TASK' || !$ongoingTaskResult.$prompt) {
7259
+ return;
7260
+ }
7261
+ // Note: [2] When some expected parameter is not defined, error will occur in templateParameters
7262
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
7263
+ const executionPromptReport = {
7264
+ prompt: {
7265
+ ...$ongoingTaskResult.$prompt,
7266
+ // <- TODO: [🧠] How to pick everyhing except `pipelineUrl`
7267
+ },
7268
+ result: $ongoingTaskResult.$result || undefined,
7269
+ error: $ongoingTaskResult.$expectError === null ? undefined : serializeError($ongoingTaskResult.$expectError),
7270
+ };
7271
+ $executionReport.promptExecutions.push(executionPromptReport);
7272
+ if (logLlmCall) {
7273
+ logLlmCall({
7274
+ modelName: 'model' /* <- TODO: How to get model name from the report */,
7275
+ report: executionPromptReport,
7276
+ });
7277
+ }
7278
+ }
7279
+
7280
+ /**
7281
+ * Executes a pipeline task with multiple attempts, including joker and retry logic. Handles different task types
7282
+ * (prompt, script, dialog, etc.), applies postprocessing, checks expectations, and updates the execution report.
7283
+ * Throws errors if execution fails after all attempts.
7284
+ *
7285
+ * @param options - The options for execution, including task, parameters, pipeline, and configuration.
7286
+ * @returns The result string of the executed task.
7287
+ *
7288
+ * @private internal utility of `createPipelineExecutor`
7289
+ */
7290
+ async function executeAttempts(options) {
7291
+ const $ongoingTaskResult = createOngoingTaskResult();
7292
+ const llmTools = getSingleLlmExecutionTools(options.tools.llm);
7293
+ attempts: for (let attemptIndex = -options.jokerParameterNames.length; attemptIndex < options.maxAttempts; attemptIndex++) {
7294
+ const attempt = createAttemptDescriptor({
7295
+ attemptIndex,
7296
+ jokerParameterNames: options.jokerParameterNames,
7297
+ pipelineIdentification: options.pipelineIdentification,
7298
+ });
7299
+ resetAttemptExecutionState($ongoingTaskResult);
7300
+ try {
7301
+ await executeSingleAttempt({
7302
+ attempt,
7303
+ options,
7304
+ llmTools,
7305
+ $ongoingTaskResult,
7306
+ });
7307
+ break attempts;
7308
+ }
7309
+ catch (error) {
7310
+ if (!(error instanceof ExpectError)) {
7311
+ throw error;
7312
+ }
7313
+ handleAttemptFailure({
7314
+ error,
7315
+ attemptIndex,
7316
+ maxAttempts: options.maxAttempts,
7317
+ maxExecutionAttempts: options.maxExecutionAttempts,
7318
+ onProgress: options.onProgress,
7319
+ pipelineIdentification: options.pipelineIdentification,
7320
+ $ongoingTaskResult,
7321
+ });
7322
+ }
7323
+ finally {
7324
+ reportPromptExecution({
7325
+ attempt,
7326
+ task: options.task,
7327
+ $executionReport: options.$executionReport,
7328
+ logLlmCall: options.logLlmCall,
7329
+ $ongoingTaskResult,
7330
+ });
7331
+ }
7332
+ }
7333
+ return getSuccessfulResultString({
7334
+ pipelineIdentification: options.pipelineIdentification,
7335
+ $ongoingTaskResult,
7336
+ });
7337
+ }
7338
+ /**
7339
+ * Creates mutable attempt state for one task execution lifecycle.
7340
+ */
7341
+ function createOngoingTaskResult() {
7342
+ return {
7343
+ $result: null,
7344
+ $resultString: null,
7345
+ $expectError: null,
7346
+ $scriptPipelineExecutionErrors: [],
7347
+ $failedResults: [],
7348
+ };
7349
+ }
7350
+ /**
7351
+ * Resolves the bookkeeping for one loop iteration, including joker lookup.
7352
+ */
7353
+ function createAttemptDescriptor(options) {
7354
+ const { attemptIndex, jokerParameterNames, pipelineIdentification } = options;
7355
+ const isJokerAttempt = attemptIndex < 0;
7356
+ const jokerParameterName = isJokerAttempt
7357
+ ? jokerParameterNames[jokerParameterNames.length + attemptIndex]
7358
+ : undefined;
7359
+ if (isJokerAttempt && !jokerParameterName) {
7360
+ throw new UnexpectedError(spacetrim.spaceTrim((block) => `
7361
+ Joker not found in attempt ${attemptIndex}
7362
+
7363
+ ${block(pipelineIdentification)}
7364
+ `));
7365
+ }
7366
+ return {
7367
+ attemptIndex,
7368
+ isJokerAttempt,
7369
+ jokerParameterName,
7370
+ };
7371
+ }
7372
+ /**
7373
+ * Clears the per-attempt result slots while preserving cumulative failure history.
7374
+ */
7375
+ function resetAttemptExecutionState($ongoingTaskResult) {
7376
+ $ongoingTaskResult.$result = null;
7377
+ $ongoingTaskResult.$resultString = null;
7378
+ $ongoingTaskResult.$expectError = null;
7379
+ }
6754
7380
  /**
6755
7381
  * Returns the successful result string or raises an unexpected internal-state error.
6756
7382
  */