@promptbook/markitdown 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 +1409 -783
  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 +1409 -783
  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
@@ -23,7 +23,7 @@
23
23
  * @generated
24
24
  * @see https://github.com/webgptorg/promptbook
25
25
  */
26
- const PROMPTBOOK_ENGINE_VERSION = '0.112.0-72';
26
+ const PROMPTBOOK_ENGINE_VERSION = '0.112.0-73';
27
27
  /**
28
28
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
29
29
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -2031,6 +2031,60 @@
2031
2031
  }
2032
2032
  // TODO: [🧠][🈴] Where is the best location for this file
2033
2033
 
2034
+ /**
2035
+ * Appends one markdown block to an existing markdown document.
2036
+ *
2037
+ * @private internal utility of `pipelineJsonToString`
2038
+ */
2039
+ function appendMarkdownBlock(pipelineString, markdownBlock) {
2040
+ return spacetrim.spaceTrim((block) => `
2041
+ ${block(pipelineString)}
2042
+
2043
+ ${block(markdownBlock)}
2044
+ `);
2045
+ }
2046
+
2047
+ /**
2048
+ * Collects pipeline-level commands in the existing serialization order.
2049
+ *
2050
+ * @private internal utility of `pipelineJsonToString`
2051
+ */
2052
+ function createPipelineCommands(pipelineJson) {
2053
+ const { pipelineUrl, bookVersion, parameters } = pipelineJson;
2054
+ const commands = [];
2055
+ if (pipelineUrl) {
2056
+ commands.push(`PIPELINE URL ${pipelineUrl}`);
2057
+ }
2058
+ if (bookVersion !== `undefined`) {
2059
+ commands.push(`BOOK VERSION ${bookVersion}`);
2060
+ }
2061
+ commands.push(...createParameterCommands(parameters, 'INPUT PARAMETER', ({ isInput }) => isInput));
2062
+ commands.push(...createParameterCommands(parameters, 'OUTPUT PARAMETER', ({ isOutput }) => isOutput));
2063
+ return commands;
2064
+ }
2065
+ /**
2066
+ * Builds one group of parameter commands while preserving the original parameter order.
2067
+ *
2068
+ * @private internal utility of `createPipelineCommands`
2069
+ */
2070
+ function createParameterCommands(parameters, commandPrefix, isIncluded) {
2071
+ return parameters
2072
+ .filter((parameter) => isIncluded(parameter))
2073
+ .map((parameter) => `${commandPrefix} ${parameterJsonToString(parameter)}`);
2074
+ }
2075
+ /**
2076
+ * Converts one parameter JSON declaration to the serialized inline form.
2077
+ *
2078
+ * @private internal utility of `createPipelineCommands`
2079
+ */
2080
+ function parameterJsonToString(parameterJson) {
2081
+ const { name, description } = parameterJson;
2082
+ if (!description) {
2083
+ return `{${name}}`;
2084
+ }
2085
+ return `{${name}} ${description}`;
2086
+ }
2087
+
2034
2088
  /**
2035
2089
  * Prettify the html code
2036
2090
  *
@@ -2044,6 +2098,31 @@
2044
2098
  return (content + `\n\n<!-- Note: Prettier removed from Promptbook -->`);
2045
2099
  }
2046
2100
 
2101
+ /**
2102
+ * Creates the initial markdown heading and description of a pipeline.
2103
+ *
2104
+ * @private internal utility of `pipelineJsonToString`
2105
+ */
2106
+ function createPipelineIntroduction(pipelineJson) {
2107
+ const { title, description } = pipelineJson;
2108
+ const pipelineIntroduction = spacetrim.spaceTrim((block) => `
2109
+ # ${title}
2110
+
2111
+ ${block(description || '')}
2112
+ `);
2113
+ // TODO: [main] !!5 This increases size of the bundle and is probably not necessary
2114
+ return prettifyMarkdown(pipelineIntroduction);
2115
+ }
2116
+
2117
+ /**
2118
+ * Renders commands as markdown bullet items.
2119
+ *
2120
+ * @private internal utility of `pipelineJsonToString`
2121
+ */
2122
+ function stringifyCommands(commands) {
2123
+ return commands.map((command) => `- ${command}`).join('\n');
2124
+ }
2125
+
2047
2126
  /**
2048
2127
  * Makes first letter of a string uppercase
2049
2128
  *
@@ -2056,141 +2135,186 @@
2056
2135
  }
2057
2136
 
2058
2137
  /**
2059
- * Converts promptbook in JSON format to string format
2138
+ * Collects all task-specific serialization details.
2060
2139
  *
2061
- * @deprecated TODO: [🥍][🧠] Backup original files in `PipelineJson` same as in Promptbook.studio
2062
- * @param pipelineJson Promptbook in JSON format (.bookc)
2063
- * @returns Promptbook in string format (.book.md)
2140
+ * @private internal utility of `pipelineJsonToString`
2141
+ */
2142
+ function createTaskSerialization(task) {
2143
+ const taskTypeSerialization = createTaskTypeSerialization(task);
2144
+ return {
2145
+ commands: [
2146
+ ...taskTypeSerialization.commands,
2147
+ ...createJokerCommands(task),
2148
+ ...createPostprocessingCommands(task),
2149
+ ...createExpectationCommands(task),
2150
+ ...createFormatCommands(task),
2151
+ ],
2152
+ contentLanguage: taskTypeSerialization.contentLanguage,
2153
+ };
2154
+ }
2155
+ /**
2156
+ * Collects commands and content language driven by the task type.
2064
2157
  *
2065
- * @public exported from `@promptbook/core`
2158
+ * @private internal utility of `createTaskSerialization`
2066
2159
  */
2067
- function pipelineJsonToString(pipelineJson) {
2068
- const { title, pipelineUrl, bookVersion, description, parameters, tasks } = pipelineJson;
2069
- let pipelineString = spacetrim.spaceTrim((block) => `
2070
- # ${title}
2071
-
2072
- ${block(description || '')}
2073
- `);
2160
+ function createTaskTypeSerialization(task) {
2161
+ if (task.taskType === 'PROMPT_TASK') {
2162
+ return {
2163
+ commands: createPromptTaskCommands(task),
2164
+ contentLanguage: 'text',
2165
+ };
2166
+ }
2167
+ if (task.taskType === 'SIMPLE_TASK') {
2168
+ return {
2169
+ commands: ['SIMPLE TEMPLATE'],
2170
+ contentLanguage: 'text',
2171
+ };
2172
+ }
2173
+ if (task.taskType === 'SCRIPT_TASK') {
2174
+ return {
2175
+ commands: ['SCRIPT'],
2176
+ contentLanguage: task.contentLanguage || '',
2177
+ };
2178
+ }
2179
+ if (task.taskType === 'DIALOG_TASK') {
2180
+ return {
2181
+ commands: ['DIALOG'],
2182
+ contentLanguage: 'text',
2183
+ };
2184
+ }
2185
+ return {
2186
+ commands: [],
2187
+ contentLanguage: 'text',
2188
+ };
2189
+ }
2190
+ /**
2191
+ * Collects prompt-task-specific commands.
2192
+ *
2193
+ * @private internal utility of `createTaskSerialization`
2194
+ */
2195
+ function createPromptTaskCommands(task) {
2196
+ const { modelName, modelVariant } = task.modelRequirements || {};
2074
2197
  const commands = [];
2075
- if (pipelineUrl) {
2076
- commands.push(`PIPELINE URL ${pipelineUrl}`);
2198
+ // Note: Do nothing, it is default
2199
+ // commands.push(`PROMPT`);
2200
+ if (modelVariant) {
2201
+ commands.push(`MODEL VARIANT ${capitalize(modelVariant)}`);
2077
2202
  }
2078
- if (bookVersion !== `undefined`) {
2079
- commands.push(`BOOK VERSION ${bookVersion}`);
2203
+ if (modelName) {
2204
+ commands.push(`MODEL NAME \`${modelName}\``);
2080
2205
  }
2081
- // TODO: [main] !!5 This increases size of the bundle and is probably not necessary
2082
- pipelineString = prettifyMarkdown(pipelineString);
2083
- for (const parameter of parameters.filter(({ isInput }) => isInput)) {
2084
- commands.push(`INPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
2206
+ return commands;
2207
+ }
2208
+ /**
2209
+ * Collects joker commands.
2210
+ *
2211
+ * @private internal utility of `createTaskSerialization`
2212
+ */
2213
+ function createJokerCommands(task) {
2214
+ var _a;
2215
+ return ((_a = task.jokerParameterNames) === null || _a === void 0 ? void 0 : _a.map((joker) => `JOKER {${joker}}`)) || [];
2216
+ }
2217
+ /**
2218
+ * Collects postprocessing commands.
2219
+ *
2220
+ * @private internal utility of `createTaskSerialization`
2221
+ */
2222
+ function createPostprocessingCommands(task) {
2223
+ var _a;
2224
+ return ((_a = task.postprocessingFunctionNames) === null || _a === void 0 ? void 0 : _a.map((postprocessingFunctionName) => `POSTPROCESSING \`${postprocessingFunctionName}\``)) || [];
2225
+ }
2226
+ /**
2227
+ * Collects expectation commands.
2228
+ *
2229
+ * @private internal utility of `createTaskSerialization`
2230
+ */
2231
+ function createExpectationCommands(task) {
2232
+ if (!task.expectations) {
2233
+ return [];
2085
2234
  }
2086
- for (const parameter of parameters.filter(({ isOutput }) => isOutput)) {
2087
- commands.push(`OUTPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
2235
+ return Object.entries(task.expectations).flatMap(([unit, expectation]) => createExpectationCommandsForUnit(unit, expectation.min, expectation.max));
2236
+ }
2237
+ /**
2238
+ * Collects expectation commands for a single unit.
2239
+ *
2240
+ * @private internal utility of `createTaskSerialization`
2241
+ */
2242
+ function createExpectationCommandsForUnit(unit, min, max) {
2243
+ if (min === max) {
2244
+ return [`EXPECT EXACTLY ${min} ${formatExpectationUnit(unit, min)}`];
2088
2245
  }
2089
- pipelineString = spacetrim.spaceTrim((block) => `
2090
- ${block(pipelineString)}
2091
-
2092
- ${block(commands.map((command) => `- ${command}`).join('\n'))}
2093
- `);
2094
- for (const task of tasks) {
2095
- const {
2096
- /* Note: Not using:> name, */
2097
- title, description,
2098
- /* Note: dependentParameterNames, */
2099
- jokerParameterNames: jokers, taskType, content, postprocessingFunctionNames: postprocessing, expectations, format, resultingParameterName, } = task;
2100
- const commands = [];
2101
- let contentLanguage = 'text';
2102
- if (taskType === 'PROMPT_TASK') {
2103
- const { modelRequirements } = task;
2104
- const { modelName, modelVariant } = modelRequirements || {};
2105
- // Note: Do nothing, it is default
2106
- // commands.push(`PROMPT`);
2107
- if (modelVariant) {
2108
- commands.push(`MODEL VARIANT ${capitalize(modelVariant)}`);
2109
- }
2110
- if (modelName) {
2111
- commands.push(`MODEL NAME \`${modelName}\``);
2112
- }
2113
- }
2114
- else if (taskType === 'SIMPLE_TASK') {
2115
- commands.push(`SIMPLE TEMPLATE`);
2116
- // Note: Nothing special here
2117
- }
2118
- else if (taskType === 'SCRIPT_TASK') {
2119
- commands.push(`SCRIPT`);
2120
- if (task.contentLanguage) {
2121
- contentLanguage = task.contentLanguage;
2122
- }
2123
- else {
2124
- contentLanguage = '';
2125
- }
2126
- }
2127
- else if (taskType === 'DIALOG_TASK') {
2128
- commands.push(`DIALOG`);
2129
- // Note: Nothing special here
2130
- } // <- }else if([🅱]
2131
- if (jokers) {
2132
- for (const joker of jokers) {
2133
- commands.push(`JOKER {${joker}}`);
2134
- }
2135
- } /* not else */
2136
- if (postprocessing) {
2137
- for (const postprocessingFunctionName of postprocessing) {
2138
- commands.push(`POSTPROCESSING \`${postprocessingFunctionName}\``);
2139
- }
2140
- } /* not else */
2141
- if (expectations) {
2142
- for (const [unit, { min, max }] of Object.entries(expectations)) {
2143
- if (min === max) {
2144
- commands.push(`EXPECT EXACTLY ${min} ${capitalize(unit + (min > 1 ? 's' : ''))}`);
2145
- }
2146
- else {
2147
- if (min !== undefined) {
2148
- commands.push(`EXPECT MIN ${min} ${capitalize(unit + (min > 1 ? 's' : ''))}`);
2149
- } /* not else */
2150
- if (max !== undefined) {
2151
- commands.push(`EXPECT MAX ${max} ${capitalize(unit + (max > 1 ? 's' : ''))}`);
2152
- }
2153
- }
2154
- }
2155
- } /* not else */
2156
- if (format) {
2157
- if (format === 'JSON') {
2158
- // TODO: @deprecated remove
2159
- commands.push(`FORMAT JSON`);
2160
- }
2161
- } /* not else */
2162
- pipelineString = spacetrim.spaceTrim((block) => `
2163
- ${block(pipelineString)}
2246
+ const commands = [];
2247
+ if (min !== undefined) {
2248
+ commands.push(`EXPECT MIN ${min} ${formatExpectationUnit(unit, min)}`);
2249
+ }
2250
+ if (max !== undefined) {
2251
+ commands.push(`EXPECT MAX ${max} ${formatExpectationUnit(unit, max)}`);
2252
+ }
2253
+ return commands;
2254
+ }
2255
+ /**
2256
+ * Formats the expectation unit exactly as the legacy serializer does.
2257
+ *
2258
+ * @private internal utility of `createTaskSerialization`
2259
+ */
2260
+ function formatExpectationUnit(unit, amount) {
2261
+ return capitalize(unit + (amount > 1 ? 's' : ''));
2262
+ }
2263
+ /**
2264
+ * Collects format commands.
2265
+ *
2266
+ * @private internal utility of `createTaskSerialization`
2267
+ */
2268
+ function createFormatCommands(task) {
2269
+ if (task.format === 'JSON') {
2270
+ // TODO: @deprecated remove
2271
+ return ['FORMAT JSON'];
2272
+ }
2273
+ return [];
2274
+ }
2164
2275
 
2165
- ## ${title}
2276
+ /**
2277
+ * Stringifies one task section of the pipeline.
2278
+ *
2279
+ * @private internal utility of `pipelineJsonToString`
2280
+ */
2281
+ function stringifyTask(task) {
2282
+ const { title, description, content, resultingParameterName } = task;
2283
+ const { commands, contentLanguage } = createTaskSerialization(task);
2284
+ return spacetrim.spaceTrim((block) => `
2285
+ ## ${title}
2166
2286
 
2167
- ${block(description || '')}
2287
+ ${block(description || '')}
2168
2288
 
2169
- ${block(commands.map((command) => `- ${command}`).join('\n'))}
2289
+ ${block(stringifyCommands(commands))}
2170
2290
 
2171
- \`\`\`${contentLanguage}
2172
- ${block(spacetrim.spaceTrim(content))}
2173
- \`\`\`
2291
+ \`\`\`${contentLanguage}
2292
+ ${block(spacetrim.spaceTrim(content))}
2293
+ \`\`\`
2174
2294
 
2175
- \`-> {${resultingParameterName}}\`
2176
- `); // <- TODO: [main] !!3 If the parameter here has description, add it and use taskParameterJsonToString
2177
- // <- TODO: [main] !!3 Escape
2178
- // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
2179
- }
2180
- return validatePipelineString(pipelineString);
2295
+ \`-> {${resultingParameterName}}\`
2296
+ `); // <- TODO: [main] !!3 If the parameter here has description, add it and use taskParameterJsonToString
2297
+ // <- TODO: [main] !!3 Escape
2298
+ // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
2181
2299
  }
2300
+
2182
2301
  /**
2183
- * Handles task parameter Json to string.
2302
+ * Converts promptbook in JSON format to string format
2184
2303
  *
2185
- * @private internal utility of `pipelineJsonToString`
2304
+ * @deprecated TODO: [🥍][🧠] Backup original files in `PipelineJson` same as in Promptbook.studio
2305
+ * @param pipelineJson Promptbook in JSON format (.bookc)
2306
+ * @returns Promptbook in string format (.book.md)
2307
+ *
2308
+ * @public exported from `@promptbook/core`
2186
2309
  */
2187
- function taskParameterJsonToString(taskParameterJson) {
2188
- const { name, description } = taskParameterJson;
2189
- let parameterString = `{${name}}`;
2190
- if (description) {
2191
- parameterString = `${parameterString} ${description}`;
2310
+ function pipelineJsonToString(pipelineJson) {
2311
+ let pipelineString = createPipelineIntroduction(pipelineJson);
2312
+ const pipelineCommands = createPipelineCommands(pipelineJson);
2313
+ pipelineString = appendMarkdownBlock(pipelineString, stringifyCommands(pipelineCommands));
2314
+ for (const task of pipelineJson.tasks) {
2315
+ pipelineString = appendMarkdownBlock(pipelineString, stringifyTask(task));
2192
2316
  }
2193
- return parameterString;
2317
+ return validatePipelineString(pipelineString);
2194
2318
  }
2195
2319
  // TODO: [🛋] Implement new features and commands into `pipelineJsonToString` + `taskParameterJsonToString` , use `stringifyCommand`
2196
2320
  // TODO: [🧠] Is there a way to auto-detect missing features in pipelineJsonToString
@@ -2630,233 +2754,519 @@
2630
2754
  */
2631
2755
  function validatePipeline_InnerFunction(pipeline) {
2632
2756
  // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
2633
- const pipelineIdentification = (() => {
2634
- // Note: This is a 😐 implementation of [🚞]
2635
- const _ = [];
2636
- if (pipeline.sourceFile !== undefined) {
2637
- _.push(`File: ${pipeline.sourceFile}`);
2638
- }
2639
- if (pipeline.pipelineUrl !== undefined) {
2640
- _.push(`Url: ${pipeline.pipelineUrl}`);
2757
+ const context = createPipelineValidationContext(pipeline);
2758
+ validatePipelineMetadata(context);
2759
+ validatePipelineCollectionsStructure(context);
2760
+ validatePipelineParameters(context);
2761
+ validatePipelineTasks(context);
2762
+ validatePipelineDependencyResolution(context);
2763
+ // Note: Check that formfactor is corresponding to the pipeline interface
2764
+ // TODO: !!6 Implement this
2765
+ // pipeline.formfactorName
2766
+ }
2767
+ /**
2768
+ * Creates the shared validation context for one pipeline.
2769
+ *
2770
+ * @private internal utility of `validatePipeline`
2771
+ */
2772
+ function createPipelineValidationContext(pipeline) {
2773
+ return {
2774
+ pipeline,
2775
+ pipelineIdentification: getPipelineIdentification(pipeline),
2776
+ };
2777
+ }
2778
+ /**
2779
+ * Builds a short file/url identification block for validation errors.
2780
+ *
2781
+ * @private internal utility of `validatePipeline`
2782
+ */
2783
+ function getPipelineIdentification(pipeline) {
2784
+ // Note: This is a 😐 implementation of [🚞]
2785
+ const pipelineIdentificationParts = [];
2786
+ if (pipeline.sourceFile !== undefined) {
2787
+ pipelineIdentificationParts.push(`File: ${pipeline.sourceFile}`);
2788
+ }
2789
+ if (pipeline.pipelineUrl !== undefined) {
2790
+ pipelineIdentificationParts.push(`Url: ${pipeline.pipelineUrl}`);
2791
+ }
2792
+ return pipelineIdentificationParts.join('\n');
2793
+ }
2794
+ /**
2795
+ * Validates pipeline-level metadata fields.
2796
+ *
2797
+ * @private internal step of `validatePipeline`
2798
+ */
2799
+ function validatePipelineMetadata({ pipeline, pipelineIdentification }) {
2800
+ validatePipelineUrl(pipeline, pipelineIdentification);
2801
+ validatePipelineBookVersion(pipeline, pipelineIdentification);
2802
+ }
2803
+ /**
2804
+ * Validates that the expected top-level collections have array structure.
2805
+ *
2806
+ * @private internal step of `validatePipeline`
2807
+ */
2808
+ function validatePipelineCollectionsStructure({ pipeline, pipelineIdentification }) {
2809
+ validatePipelineParametersCollection(pipeline, pipelineIdentification);
2810
+ validatePipelineTasksCollection(pipeline, pipelineIdentification);
2811
+ }
2812
+ /**
2813
+ * Validates all pipeline parameter declarations.
2814
+ *
2815
+ * @private internal step of `validatePipeline`
2816
+ */
2817
+ function validatePipelineParameters({ pipeline, pipelineIdentification }) {
2818
+ for (const parameter of pipeline.parameters) {
2819
+ validatePipelineParameter(parameter, pipeline, pipelineIdentification);
2820
+ }
2821
+ }
2822
+ /**
2823
+ * Validates all pipeline tasks and their per-task invariants.
2824
+ *
2825
+ * @private internal step of `validatePipeline`
2826
+ */
2827
+ function validatePipelineTasks({ pipeline, pipelineIdentification }) {
2828
+ // Note: All input parameters are defined - so that they can be used as result of some task
2829
+ const definedParameters = createInitiallyDefinedParameters(pipeline);
2830
+ for (const task of pipeline.tasks) {
2831
+ validatePipelineTask(task, definedParameters, pipelineIdentification);
2832
+ }
2833
+ }
2834
+ /**
2835
+ * Validates that task dependencies can be resolved without cycles or missing definitions.
2836
+ *
2837
+ * @private internal step of `validatePipeline`
2838
+ */
2839
+ function validatePipelineDependencyResolution({ pipeline, pipelineIdentification }) {
2840
+ let dependencyResolutionState = createInitialDependencyResolutionState(pipeline);
2841
+ let loopLimit = LOOP_LIMIT;
2842
+ while (hasUnresolvedTasks(dependencyResolutionState)) {
2843
+ if (loopLimit-- < 0) {
2844
+ throw createDependencyResolutionLoopLimitError(pipelineIdentification);
2641
2845
  }
2642
- return _.join('\n');
2643
- })();
2644
- if (pipeline.pipelineUrl !== undefined && !isValidPipelineUrl(pipeline.pipelineUrl)) {
2645
- // <- Note: [🚲]
2646
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2647
- Invalid promptbook URL "${pipeline.pipelineUrl}"
2648
-
2649
- ${block(pipelineIdentification)}
2650
- `));
2846
+ dependencyResolutionState = resolveNextDependencyResolutionState(dependencyResolutionState, pipelineIdentification);
2651
2847
  }
2652
- if (pipeline.bookVersion !== undefined && !isValidPromptbookVersion(pipeline.bookVersion)) {
2653
- // <- Note: [🚲]
2654
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2655
- Invalid Promptbook Version "${pipeline.bookVersion}"
2848
+ }
2849
+ /**
2850
+ * Validates one pipeline parameter declaration.
2851
+ *
2852
+ * @private internal step of `validatePipeline`
2853
+ */
2854
+ function validatePipelineParameter(parameter, pipeline, pipelineIdentification) {
2855
+ validateParameterDirection(parameter, pipelineIdentification);
2856
+ validateParameterUsage(parameter, pipeline, pipelineIdentification);
2857
+ validateParameterDefinition(parameter, pipeline, pipelineIdentification);
2858
+ }
2859
+ /**
2860
+ * Validates one pipeline task and its invariants.
2861
+ *
2862
+ * @private internal step of `validatePipeline`
2863
+ */
2864
+ function validatePipelineTask(task, definedParameters, pipelineIdentification) {
2865
+ validateTaskResultingParameter(task, definedParameters, pipelineIdentification);
2866
+ validateTaskJokers(task, pipelineIdentification);
2867
+ validateTaskExpectations(task, pipelineIdentification);
2868
+ }
2869
+ /**
2870
+ * Validates the pipeline URL, when present.
2871
+ *
2872
+ * @private internal utility of `validatePipeline`
2873
+ */
2874
+ function validatePipelineUrl(pipeline, pipelineIdentification) {
2875
+ if (pipeline.pipelineUrl === undefined || isValidPipelineUrl(pipeline.pipelineUrl)) {
2876
+ return;
2877
+ }
2878
+ // <- Note: [🚲]
2879
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2880
+ Invalid promptbook URL "${pipeline.pipelineUrl}"
2656
2881
 
2657
- ${block(pipelineIdentification)}
2658
- `));
2882
+ ${block(pipelineIdentification)}
2883
+ `));
2884
+ }
2885
+ /**
2886
+ * Validates the Promptbook version, when present.
2887
+ *
2888
+ * @private internal utility of `validatePipeline`
2889
+ */
2890
+ function validatePipelineBookVersion(pipeline, pipelineIdentification) {
2891
+ if (pipeline.bookVersion === undefined || isValidPromptbookVersion(pipeline.bookVersion)) {
2892
+ return;
2659
2893
  }
2894
+ // <- Note: [🚲]
2895
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2896
+ Invalid Promptbook Version "${pipeline.bookVersion}"
2897
+
2898
+ ${block(pipelineIdentification)}
2899
+ `));
2900
+ }
2901
+ /**
2902
+ * Validates that `pipeline.parameters` is an array.
2903
+ *
2904
+ * @private internal utility of `validatePipeline`
2905
+ */
2906
+ function validatePipelineParametersCollection(pipeline, pipelineIdentification) {
2660
2907
  // TODO: [🧠] Maybe do here some proper JSON-schema / ZOD checking
2661
- if (!Array.isArray(pipeline.parameters)) {
2662
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2663
- throw new ParseError(spacetrim.spaceTrim((block) => `
2664
- Pipeline is valid JSON but with wrong structure
2908
+ if (Array.isArray(pipeline.parameters)) {
2909
+ return;
2910
+ }
2911
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2912
+ throw new ParseError(spacetrim.spaceTrim((block) => `
2913
+ Pipeline is valid JSON but with wrong structure
2665
2914
 
2666
- \`PipelineJson.parameters\` expected to be an array, but got ${typeof pipeline.parameters}
2915
+ \`PipelineJson.parameters\` expected to be an array, but got ${typeof pipeline.parameters}
2667
2916
 
2668
- ${block(pipelineIdentification)}
2669
- `));
2670
- }
2917
+ ${block(pipelineIdentification)}
2918
+ `));
2919
+ }
2920
+ /**
2921
+ * Validates that `pipeline.tasks` is an array.
2922
+ *
2923
+ * @private internal utility of `validatePipeline`
2924
+ */
2925
+ function validatePipelineTasksCollection(pipeline, pipelineIdentification) {
2671
2926
  // TODO: [🧠] Maybe do here some proper JSON-schema / ZOD checking
2672
- if (!Array.isArray(pipeline.tasks)) {
2673
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2674
- throw new ParseError(spacetrim.spaceTrim((block) => `
2675
- Pipeline is valid JSON but with wrong structure
2927
+ if (Array.isArray(pipeline.tasks)) {
2928
+ return;
2929
+ }
2930
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
2931
+ throw new ParseError(spacetrim.spaceTrim((block) => `
2932
+ Pipeline is valid JSON but with wrong structure
2676
2933
 
2677
- \`PipelineJson.tasks\` expected to be an array, but got ${typeof pipeline.tasks}
2934
+ \`PipelineJson.tasks\` expected to be an array, but got ${typeof pipeline.tasks}
2678
2935
 
2679
- ${block(pipelineIdentification)}
2680
- `));
2936
+ ${block(pipelineIdentification)}
2937
+ `));
2938
+ }
2939
+ /**
2940
+ * Validates that one parameter does not declare incompatible directions.
2941
+ *
2942
+ * @private internal utility of `validatePipeline`
2943
+ */
2944
+ function validateParameterDirection(parameter, pipelineIdentification) {
2945
+ if (!parameter.isInput || !parameter.isOutput) {
2946
+ return;
2681
2947
  }
2682
- /*
2683
- TODO: [🧠][🅾] Should be empty pipeline valid or not
2684
- // Note: Check that pipeline has some tasks
2685
- if (pipeline.tasks.length === 0) {
2686
- throw new PipelineLogicError(
2687
- spaceTrim(
2688
- (block) => `
2689
- Pipeline must have at least one task
2948
+ const parameterName = parameter.name;
2949
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2690
2950
 
2691
- ${block(pipelineIdentification)}
2692
- `,
2693
- ),
2694
- );
2695
- }
2696
- */
2697
- // Note: Check each parameter individually
2698
- for (const parameter of pipeline.parameters) {
2699
- if (parameter.isInput && parameter.isOutput) {
2700
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2951
+ Parameter \`{${parameterName}}\` can not be both input and output
2701
2952
 
2702
- Parameter \`{${parameter.name}}\` can not be both input and output
2953
+ ${block(pipelineIdentification)}
2954
+ `));
2955
+ }
2956
+ /**
2957
+ * Validates that one intermediate parameter is actually consumed by at least one task.
2958
+ *
2959
+ * @private internal utility of `validatePipeline`
2960
+ */
2961
+ function validateParameterUsage(parameter, pipeline, pipelineIdentification) {
2962
+ if (parameter.isInput || parameter.isOutput || isParameterUsedByAnyTask(parameter, pipeline.tasks)) {
2963
+ return;
2964
+ }
2965
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2966
+ Parameter \`{${parameter.name}}\` is created but not used
2703
2967
 
2704
- ${block(pipelineIdentification)}
2705
- `));
2706
- }
2707
- // Note: Testing that parameter is either intermediate or output BUT not created and unused
2708
- if (!parameter.isInput &&
2709
- !parameter.isOutput &&
2710
- !pipeline.tasks.some((task) => task.dependentParameterNames.includes(parameter.name))) {
2711
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2712
- Parameter \`{${parameter.name}}\` is created but not used
2968
+ You can declare {${parameter.name}} as output parameter by adding in the header:
2969
+ - OUTPUT PARAMETER \`{${parameter.name}}\` ${parameter.description || ''}
2713
2970
 
2714
- You can declare {${parameter.name}} as output parameter by adding in the header:
2715
- - OUTPUT PARAMETER \`{${parameter.name}}\` ${parameter.description || ''}
2971
+ ${block(pipelineIdentification)}
2716
2972
 
2717
- ${block(pipelineIdentification)}
2973
+ `));
2974
+ }
2975
+ /**
2976
+ * Validates that one non-input parameter is produced by at least one task.
2977
+ *
2978
+ * @private internal utility of `validatePipeline`
2979
+ */
2980
+ function validateParameterDefinition(parameter, pipeline, pipelineIdentification) {
2981
+ if (parameter.isInput || isParameterDefinedByAnyTask(parameter, pipeline.tasks)) {
2982
+ return;
2983
+ }
2984
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2985
+ Parameter \`{${parameter.name}}\` is declared but not defined
2718
2986
 
2719
- `));
2720
- }
2721
- // Note: Testing that parameter is either input or result of some task
2722
- if (!parameter.isInput && !pipeline.tasks.some((task) => task.resultingParameterName === parameter.name)) {
2723
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2724
- Parameter \`{${parameter.name}}\` is declared but not defined
2987
+ You can do one of these:
2988
+ 1) Remove declaration of \`{${parameter.name}}\`
2989
+ 2) Add task that results in \`-> {${parameter.name}}\`
2725
2990
 
2726
- You can do one of these:
2727
- 1) Remove declaration of \`{${parameter.name}}\`
2728
- 2) Add task that results in \`-> {${parameter.name}}\`
2991
+ ${block(pipelineIdentification)}
2992
+ `));
2993
+ }
2994
+ /**
2995
+ * Checks whether one parameter is consumed by at least one task dependency list.
2996
+ *
2997
+ * @private internal utility of `validatePipeline`
2998
+ */
2999
+ function isParameterUsedByAnyTask(parameter, tasks) {
3000
+ return tasks.some((task) => task.dependentParameterNames.includes(parameter.name));
3001
+ }
3002
+ /**
3003
+ * Checks whether one parameter is produced by at least one task.
3004
+ *
3005
+ * @private internal utility of `validatePipeline`
3006
+ */
3007
+ function isParameterDefinedByAnyTask(parameter, tasks) {
3008
+ return tasks.some((task) => task.resultingParameterName === parameter.name);
3009
+ }
3010
+ /**
3011
+ * Collects the parameter names that are already defined before task validation starts.
3012
+ *
3013
+ * @private internal utility of `validatePipeline`
3014
+ */
3015
+ function createInitiallyDefinedParameters(pipeline) {
3016
+ return new Set(pipeline.parameters.filter(({ isInput }) => isInput).map(({ name }) => name));
3017
+ }
3018
+ /**
3019
+ * Validates one task result parameter declaration and marks it as defined.
3020
+ *
3021
+ * @private internal utility of `validatePipeline`
3022
+ */
3023
+ function validateTaskResultingParameter(task, definedParameters, pipelineIdentification) {
3024
+ if (definedParameters.has(task.resultingParameterName)) {
3025
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
3026
+ Parameter \`{${task.resultingParameterName}}\` is defined multiple times
2729
3027
 
2730
- ${block(pipelineIdentification)}
2731
- `));
2732
- }
3028
+ ${block(pipelineIdentification)}
3029
+ `));
2733
3030
  }
2734
- // Note: All input parameters are defined - so that they can be used as result of some task
2735
- const definedParameters = new Set(pipeline.parameters.filter(({ isInput }) => isInput).map(({ name }) => name));
2736
- // Note: Checking each task individually
2737
- for (const task of pipeline.tasks) {
2738
- if (definedParameters.has(task.resultingParameterName)) {
2739
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2740
- Parameter \`{${task.resultingParameterName}}\` is defined multiple times
3031
+ if (RESERVED_PARAMETER_NAMES.includes(task.resultingParameterName)) {
3032
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
3033
+ Parameter name {${task.resultingParameterName}} is reserved, please use different name
2741
3034
 
2742
- ${block(pipelineIdentification)}
2743
- `));
2744
- }
2745
- if (RESERVED_PARAMETER_NAMES.includes(task.resultingParameterName)) {
2746
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2747
- Parameter name {${task.resultingParameterName}} is reserved, please use different name
3035
+ ${block(pipelineIdentification)}
3036
+ `));
3037
+ }
3038
+ definedParameters.add(task.resultingParameterName);
3039
+ }
3040
+ /**
3041
+ * Validates joker parameters for one task.
3042
+ *
3043
+ * @private internal utility of `validatePipeline`
3044
+ */
3045
+ function validateTaskJokers(task, pipelineIdentification) {
3046
+ if (!hasTaskJokers(task)) {
3047
+ return;
3048
+ }
3049
+ validateTaskSupportsJokers(task, pipelineIdentification);
3050
+ validateTaskJokerDependencies(task, pipelineIdentification);
3051
+ }
3052
+ /**
3053
+ * Checks whether one task declares any joker parameters.
3054
+ *
3055
+ * @private internal utility of `validatePipeline`
3056
+ */
3057
+ function hasTaskJokers(task) {
3058
+ return !!task.jokerParameterNames && task.jokerParameterNames.length > 0;
3059
+ }
3060
+ /**
3061
+ * Validates that a task has the required supporting features when using jokers.
3062
+ *
3063
+ * @private internal utility of `validatePipeline`
3064
+ */
3065
+ function validateTaskSupportsJokers(task, pipelineIdentification) {
3066
+ if (task.format ||
3067
+ task.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
3068
+ return;
3069
+ }
3070
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
3071
+ Joker parameters are used for {${task.resultingParameterName}} but no expectations are defined
2748
3072
 
2749
- ${block(pipelineIdentification)}
2750
- `));
3073
+ ${block(pipelineIdentification)}
3074
+ `));
3075
+ }
3076
+ /**
3077
+ * Validates that every joker parameter is also listed among task dependencies.
3078
+ *
3079
+ * @private internal utility of `validatePipeline`
3080
+ */
3081
+ function validateTaskJokerDependencies(task, pipelineIdentification) {
3082
+ for (const joker of task.jokerParameterNames) {
3083
+ if (task.dependentParameterNames.includes(joker)) {
3084
+ continue;
2751
3085
  }
2752
- definedParameters.add(task.resultingParameterName);
2753
- if (task.jokerParameterNames && task.jokerParameterNames.length > 0) {
2754
- if (!task.format &&
2755
- !task.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
2756
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2757
- Joker parameters are used for {${task.resultingParameterName}} but no expectations are defined
2758
-
2759
- ${block(pipelineIdentification)}
2760
- `));
2761
- }
2762
- for (const joker of task.jokerParameterNames) {
2763
- if (!task.dependentParameterNames.includes(joker)) {
2764
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2765
- Parameter \`{${joker}}\` is used for {${task.resultingParameterName}} as joker but not in \`dependentParameterNames\`
3086
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
3087
+ Parameter \`{${joker}}\` is used for {${task.resultingParameterName}} as joker but not in \`dependentParameterNames\`
2766
3088
 
2767
- ${block(pipelineIdentification)}
2768
- `));
2769
- }
2770
- }
2771
- }
2772
- if (task.expectations) {
2773
- for (const [unit, { min, max }] of Object.entries(task.expectations)) {
2774
- if (min !== undefined && max !== undefined && min > max) {
2775
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2776
- Min expectation (=${min}) of ${unit} is higher than max expectation (=${max})
3089
+ ${block(pipelineIdentification)}
3090
+ `));
3091
+ }
3092
+ }
3093
+ /**
3094
+ * Validates all expectation bounds configured on one task.
3095
+ *
3096
+ * @private internal utility of `validatePipeline`
3097
+ */
3098
+ function validateTaskExpectations(task, pipelineIdentification) {
3099
+ if (!task.expectations) {
3100
+ return;
3101
+ }
3102
+ for (const [unit, { min, max }] of Object.entries(task.expectations)) {
3103
+ validateTaskExpectationRange(unit, min, max, pipelineIdentification);
3104
+ validateTaskExpectationMin(unit, min, pipelineIdentification);
3105
+ validateTaskExpectationMax(unit, max, pipelineIdentification);
3106
+ }
3107
+ }
3108
+ /**
3109
+ * Validates the minimum and maximum expectation ordering for one unit.
3110
+ *
3111
+ * @private internal utility of `validatePipeline`
3112
+ */
3113
+ function validateTaskExpectationRange(unit, min, max, pipelineIdentification) {
3114
+ if (min === undefined || max === undefined || min <= max) {
3115
+ return;
3116
+ }
3117
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
3118
+ Min expectation (=${min}) of ${unit} is higher than max expectation (=${max})
2777
3119
 
2778
- ${block(pipelineIdentification)}
2779
- `));
2780
- }
2781
- if (min !== undefined && min < 0) {
2782
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2783
- Min expectation of ${unit} must be zero or positive
3120
+ ${block(pipelineIdentification)}
3121
+ `));
3122
+ }
3123
+ /**
3124
+ * Validates the minimum expectation bound for one unit.
3125
+ *
3126
+ * @private internal utility of `validatePipeline`
3127
+ */
3128
+ function validateTaskExpectationMin(unit, min, pipelineIdentification) {
3129
+ if (min === undefined || min >= 0) {
3130
+ return;
3131
+ }
3132
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
3133
+ Min expectation of ${unit} must be zero or positive
2784
3134
 
2785
- ${block(pipelineIdentification)}
2786
- `));
2787
- }
2788
- if (max !== undefined && max <= 0) {
2789
- throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
2790
- Max expectation of ${unit} must be positive
3135
+ ${block(pipelineIdentification)}
3136
+ `));
3137
+ }
3138
+ /**
3139
+ * Validates the maximum expectation bound for one unit.
3140
+ *
3141
+ * @private internal utility of `validatePipeline`
3142
+ */
3143
+ function validateTaskExpectationMax(unit, max, pipelineIdentification) {
3144
+ if (max === undefined || max > 0) {
3145
+ return;
3146
+ }
3147
+ throw new PipelineLogicError(spacetrim.spaceTrim((block) => `
3148
+ Max expectation of ${unit} must be positive
2791
3149
 
2792
- ${block(pipelineIdentification)}
2793
- `));
2794
- }
2795
- }
2796
- }
3150
+ ${block(pipelineIdentification)}
3151
+ `));
3152
+ }
3153
+ /**
3154
+ * Collects the parameter names that are already resolvable before dependency traversal starts.
3155
+ *
3156
+ * @private internal utility of `validatePipeline`
3157
+ */
3158
+ function createInitialDependencyResolutionState(pipeline) {
3159
+ return {
3160
+ resolvedParameterNames: createInitiallyResolvedParameterNames(pipeline),
3161
+ unresolvedTasks: [...pipeline.tasks],
3162
+ };
3163
+ }
3164
+ /**
3165
+ * Checks whether dependency resolution still has tasks left to process.
3166
+ *
3167
+ * @private internal utility of `validatePipeline`
3168
+ */
3169
+ function hasUnresolvedTasks({ unresolvedTasks }) {
3170
+ return unresolvedTasks.length > 0;
3171
+ }
3172
+ /**
3173
+ * Resolves the next batch of currently satisfiable tasks.
3174
+ *
3175
+ * @private internal utility of `validatePipeline`
3176
+ */
3177
+ function resolveNextDependencyResolutionState(dependencyResolutionState, pipelineIdentification) {
3178
+ const currentlyResolvedTasks = getCurrentlyResolvedTasks(dependencyResolutionState.unresolvedTasks, dependencyResolutionState.resolvedParameterNames);
3179
+ if (currentlyResolvedTasks.length === 0) {
3180
+ throw createUnresolvedTasksError(dependencyResolutionState.unresolvedTasks, dependencyResolutionState.resolvedParameterNames, pipelineIdentification);
2797
3181
  }
2798
- // Note: Detect circular dependencies
2799
- let resovedParameters = pipeline.parameters
3182
+ return {
3183
+ resolvedParameterNames: appendResolvedTaskParameterNames(dependencyResolutionState.resolvedParameterNames, currentlyResolvedTasks),
3184
+ unresolvedTasks: dependencyResolutionState.unresolvedTasks.filter((task) => !currentlyResolvedTasks.includes(task)),
3185
+ };
3186
+ }
3187
+ /**
3188
+ * Collects the parameter names that are already resolvable before dependency traversal starts.
3189
+ *
3190
+ * @private internal utility of `validatePipeline`
3191
+ */
3192
+ function createInitiallyResolvedParameterNames(pipeline) {
3193
+ let resolvedParameterNames = pipeline.parameters
2800
3194
  .filter(({ isInput }) => isInput)
2801
3195
  .map(({ name }) => name);
2802
- // Note: All reserved parameters are resolved
2803
3196
  for (const reservedParameterName of RESERVED_PARAMETER_NAMES) {
2804
- resovedParameters = [...resovedParameters, reservedParameterName];
3197
+ resolvedParameterNames = [...resolvedParameterNames, reservedParameterName];
2805
3198
  }
2806
- let unresovedTasks = [...pipeline.tasks];
2807
- let loopLimit = LOOP_LIMIT;
2808
- while (unresovedTasks.length > 0) {
2809
- if (loopLimit-- < 0) {
2810
- // Note: Really UnexpectedError not LimitReachedError - this should not happen and be caught below
2811
- throw new UnexpectedError(spacetrim.spaceTrim((block) => `
2812
- Loop limit reached during detection of circular dependencies in \`validatePipeline\`
3199
+ return resolvedParameterNames;
3200
+ }
3201
+ /**
3202
+ * Adds newly resolved task outputs to the resolved parameter list.
3203
+ *
3204
+ * @private internal utility of `validatePipeline`
3205
+ */
3206
+ function appendResolvedTaskParameterNames(resolvedParameterNames, currentlyResolvedTasks) {
3207
+ return [
3208
+ ...resolvedParameterNames,
3209
+ ...currentlyResolvedTasks.map(({ resultingParameterName }) => resultingParameterName),
3210
+ ];
3211
+ }
3212
+ /**
3213
+ * Selects tasks whose dependencies are already resolved.
3214
+ *
3215
+ * @private internal utility of `validatePipeline`
3216
+ */
3217
+ function getCurrentlyResolvedTasks(unresolvedTasks, resolvedParameterNames) {
3218
+ return unresolvedTasks.filter((task) => task.dependentParameterNames.every((name) => resolvedParameterNames.includes(name)));
3219
+ }
3220
+ /**
3221
+ * Creates the unexpected loop-limit error for dependency resolution.
3222
+ *
3223
+ * @private internal utility of `validatePipeline`
3224
+ */
3225
+ function createDependencyResolutionLoopLimitError(pipelineIdentification) {
3226
+ // Note: Really UnexpectedError not LimitReachedError - this should not happen and be caught below
3227
+ return new UnexpectedError(spacetrim.spaceTrim((block) => `
3228
+ Loop limit reached during detection of circular dependencies in \`validatePipeline\`
2813
3229
 
2814
- ${block(pipelineIdentification)}
2815
- `));
2816
- }
2817
- const currentlyResovedTasks = unresovedTasks.filter((task) => task.dependentParameterNames.every((name) => resovedParameters.includes(name)));
2818
- if (currentlyResovedTasks.length === 0) {
2819
- throw new PipelineLogicError(
2820
- // TODO: [🐎] DRY
2821
- spacetrim.spaceTrim((block) => `
3230
+ ${block(pipelineIdentification)}
3231
+ `));
3232
+ }
3233
+ /**
3234
+ * Creates the detailed error for unresolved or circular task dependencies.
3235
+ *
3236
+ * @private internal utility of `validatePipeline`
3237
+ */
3238
+ function createUnresolvedTasksError(unresolvedTasks, resolvedParameterNames, pipelineIdentification) {
3239
+ return new PipelineLogicError(
3240
+ // TODO: [🐎] DRY
3241
+ spacetrim.spaceTrim((block) => `
2822
3242
 
2823
- Can not resolve some parameters:
2824
- Either you are using a parameter that is not defined, or there are some circular dependencies.
3243
+ Can not resolve some parameters:
3244
+ Either you are using a parameter that is not defined, or there are some circular dependencies.
2825
3245
 
2826
- ${block(pipelineIdentification)}
3246
+ ${block(pipelineIdentification)}
2827
3247
 
2828
- **Can not resolve:**
2829
- ${block(unresovedTasks
2830
- .map(({ resultingParameterName, dependentParameterNames }) => `- Parameter \`{${resultingParameterName}}\` which depends on ${dependentParameterNames
2831
- .map((dependentParameterName) => `\`{${dependentParameterName}}\``)
2832
- .join(' and ')}`)
2833
- .join('\n'))}
3248
+ **Can not resolve:**
3249
+ ${block(unresolvedTasks
3250
+ .map(({ resultingParameterName, dependentParameterNames }) => `- Parameter \`{${resultingParameterName}}\` which depends on ${dependentParameterNames
3251
+ .map((dependentParameterName) => `\`{${dependentParameterName}}\``)
3252
+ .join(' and ')}`)
3253
+ .join('\n'))}
2834
3254
 
2835
- **Resolved:**
2836
- ${block(resovedParameters
2837
- .filter((name) => !RESERVED_PARAMETER_NAMES.includes(name))
2838
- .map((name) => `- Parameter \`{${name}}\``)
2839
- .join('\n'))}
3255
+ **Resolved:**
3256
+ ${block(resolvedParameterNames
3257
+ .filter((name) => !RESERVED_PARAMETER_NAMES.includes(name))
3258
+ .map((name) => `- Parameter \`{${name}}\``)
3259
+ .join('\n'))}
2840
3260
 
2841
3261
 
2842
- **Reserved (which are available):**
2843
- ${block(resovedParameters
2844
- .filter((name) => RESERVED_PARAMETER_NAMES.includes(name))
2845
- .map((name) => `- Parameter \`{${name}}\``)
2846
- .join('\n'))}
3262
+ **Reserved (which are available):**
3263
+ ${block(resolvedParameterNames
3264
+ .filter((name) => RESERVED_PARAMETER_NAMES.includes(name))
3265
+ .map((name) => `- Parameter \`{${name}}\``)
3266
+ .join('\n'))}
2847
3267
 
2848
3268
 
2849
- `));
2850
- }
2851
- resovedParameters = [
2852
- ...resovedParameters,
2853
- ...currentlyResovedTasks.map(({ resultingParameterName }) => resultingParameterName),
2854
- ];
2855
- unresovedTasks = unresovedTasks.filter((task) => !currentlyResovedTasks.includes(task));
2856
- }
2857
- // Note: Check that formfactor is corresponding to the pipeline interface
2858
- // TODO: !!6 Implement this
2859
- // pipeline.formfactorName
3269
+ `));
2860
3270
  }
2861
3271
  /**
2862
3272
  * TODO: [🧞‍♀️] Do not allow joker + foreach
@@ -3552,77 +3962,288 @@
3552
3962
  // TODO: [🧠] Can this return type be better typed than void
3553
3963
 
3554
3964
  /**
3555
- * Helper to create a new task
3965
+ * Resolves the short task summary shown in the UI.
3556
3966
  *
3557
- * @private internal helper function
3967
+ * @private internal helper function of `ExecutionTask`
3558
3968
  */
3559
- function createTask(options) {
3560
- const { taskType, taskProcessCallback } = options;
3561
- let { title } = options;
3562
- // TODO: [🐙] DRY
3563
- const taskId = `${taskType.toLowerCase().substring(0, 4)}-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
3564
- let status = 'RUNNING';
3565
- const createdAt = new Date();
3566
- let updatedAt = createdAt;
3567
- const errors = [];
3568
- const warnings = [];
3569
- const llmCalls = [];
3570
- let currentValue = {};
3571
- let customTldr = null;
3572
- const partialResultSubject = new rxjs.Subject();
3573
- // <- Note: Not using `BehaviorSubject` because on error we can't access the last value
3574
- const finalResultPromise = /* not await */ taskProcessCallback((newOngoingResult) => {
3575
- if (newOngoingResult.title) {
3576
- title = newOngoingResult.title;
3577
- }
3578
- updatedAt = new Date();
3579
- Object.assign(currentValue, newOngoingResult);
3580
- // <- TODO: assign deep
3581
- partialResultSubject.next(newOngoingResult);
3582
- }, (tldrInfo) => {
3583
- customTldr = tldrInfo;
3584
- updatedAt = new Date();
3585
- }, (llmCall) => {
3586
- llmCalls.push(llmCall);
3587
- updatedAt = new Date();
3588
- });
3589
- finalResultPromise
3590
- .catch((error) => {
3591
- errors.push(error);
3592
- partialResultSubject.error(error);
3593
- })
3594
- .then((executionResult) => {
3595
- if (executionResult) {
3596
- try {
3597
- updatedAt = new Date();
3598
- errors.push(...executionResult.errors);
3599
- warnings.push(...executionResult.warnings);
3600
- // <- TODO: [🌂] Only unique errors and warnings should be added (or filtered)
3601
- // TODO: [🧠] !! errors, warning, isSuccessful are redundant both in `ExecutionTask` and `ExecutionTask.currentValue`
3602
- // Also maybe move `ExecutionTask.currentValue.usage` -> `ExecutionTask.usage`
3603
- // And delete `ExecutionTask.currentValue.preparedPipeline`
3604
- assertsTaskSuccessful(executionResult);
3605
- status = 'FINISHED';
3606
- currentValue = jsonStringsToJsons(executionResult);
3607
- // <- TODO: [🧠] Is this a good idea to convert JSON strins to JSONs?
3608
- partialResultSubject.next(executionResult);
3609
- }
3610
- catch (error) {
3611
- assertsError(error);
3612
- status = 'ERROR';
3613
- errors.push(error);
3614
- partialResultSubject.error(error);
3615
- }
3616
- }
3617
- partialResultSubject.complete();
3618
- });
3619
- async function asPromise(options) {
3620
- const { isCrashedOnError = true } = options || {};
3621
- const finalResult = await finalResultPromise;
3622
- if (isCrashedOnError) {
3623
- assertsTaskSuccessful(finalResult);
3624
- }
3625
- return finalResult;
3969
+ function resolveTaskTldr(options) {
3970
+ const { customTldr } = options;
3971
+ if (customTldr) {
3972
+ return customTldr;
3973
+ }
3974
+ return {
3975
+ percent: resolveTaskPercent(options),
3976
+ message: `${resolveTaskMessage(options)} (!!!fallback)`,
3977
+ };
3978
+ }
3979
+ /**
3980
+ * Resolves the best progress percentage for the current task state.
3981
+ *
3982
+ * @private internal helper function of `ExecutionTask`
3983
+ */
3984
+ function resolveTaskPercent(options) {
3985
+ const explicitPercent = getExplicitTaskPercent(options.currentValue);
3986
+ if (typeof explicitPercent === 'number') {
3987
+ return normalizeTaskPercent(explicitPercent);
3988
+ }
3989
+ return normalizeTaskPercent(calculateSimulatedTaskPercent(options));
3990
+ }
3991
+ /**
3992
+ * Picks a directly reported progress percentage from the task result snapshot.
3993
+ *
3994
+ * @private internal helper function of `ExecutionTask`
3995
+ */
3996
+ function getExplicitTaskPercent(currentValue) {
3997
+ var _a, _b, _c, _d, _e, _f;
3998
+ 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);
3999
+ }
4000
+ /**
4001
+ * Simulates progress when the task result does not expose an explicit percentage.
4002
+ *
4003
+ * @private internal helper function of `ExecutionTask`
4004
+ */
4005
+ function calculateSimulatedTaskPercent(options) {
4006
+ const { currentValue, status, createdAt } = options;
4007
+ const elapsedMs = new Date().getTime() - createdAt.getTime();
4008
+ const timeProgress = Math.min(elapsedMs / DEFAULT_TASK_SIMULATED_DURATION_MS, 1);
4009
+ const { subtaskCount, completedSubtasks } = summarizeTaskSubtasks(currentValue);
4010
+ if (status === 'FINISHED') {
4011
+ return 1;
4012
+ }
4013
+ if (status === 'ERROR') {
4014
+ return 0;
4015
+ }
4016
+ return Math.min(completedSubtasks / subtaskCount + (1 / subtaskCount) * timeProgress, 1);
4017
+ }
4018
+ /**
4019
+ * Counts total and completed subtasks used by the fallback progress simulation.
4020
+ *
4021
+ * @private internal helper function of `ExecutionTask`
4022
+ */
4023
+ function summarizeTaskSubtasks(currentValue) {
4024
+ if (!Array.isArray(currentValue === null || currentValue === void 0 ? void 0 : currentValue.subtasks)) {
4025
+ return { subtaskCount: 1, completedSubtasks: 0 };
4026
+ }
4027
+ return {
4028
+ subtaskCount: currentValue.subtasks.length || 1,
4029
+ completedSubtasks: currentValue.subtasks.filter(isTaskSubtaskCompleted).length,
4030
+ };
4031
+ }
4032
+ /**
4033
+ * Tells whether a task subtask is already finished.
4034
+ *
4035
+ * @private internal helper function of `ExecutionTask`
4036
+ */
4037
+ function isTaskSubtaskCompleted(subtask) {
4038
+ return subtask.done || subtask.completed || false;
4039
+ }
4040
+ /**
4041
+ * Normalizes a progress percentage into the expected `0..1` range.
4042
+ *
4043
+ * @private internal helper function of `ExecutionTask`
4044
+ */
4045
+ function normalizeTaskPercent(percentRaw) {
4046
+ let percent = Number(percentRaw) || 0;
4047
+ if (percent < 0) {
4048
+ percent = 0;
4049
+ }
4050
+ if (percent > 1) {
4051
+ percent = 1;
4052
+ }
4053
+ return percent;
4054
+ }
4055
+ /**
4056
+ * Resolves the best human-readable status message for the current task state.
4057
+ *
4058
+ * @private internal helper function of `ExecutionTask`
4059
+ */
4060
+ function resolveTaskMessage(options) {
4061
+ return (getCurrentValueMessage(options.currentValue) ||
4062
+ getCurrentSubtaskMessage(options.currentValue) ||
4063
+ getLatestIssueMessage(options.errors, 'Error') ||
4064
+ getLatestIssueMessage(options.warnings, 'Warning') ||
4065
+ getStatusMessage(options.status));
4066
+ }
4067
+ /**
4068
+ * Picks a message already reported by the current task result snapshot.
4069
+ *
4070
+ * @private internal helper function of `ExecutionTask`
4071
+ */
4072
+ function getCurrentValueMessage(currentValue) {
4073
+ var _a, _b, _c, _d;
4074
+ 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;
4075
+ }
4076
+ /**
4077
+ * Builds a fallback message from the first unfinished subtask title.
4078
+ *
4079
+ * @private internal helper function of `ExecutionTask`
4080
+ */
4081
+ function getCurrentSubtaskMessage(currentValue) {
4082
+ if (!Array.isArray(currentValue === null || currentValue === void 0 ? void 0 : currentValue.subtasks) || currentValue.subtasks.length === 0) {
4083
+ return undefined;
4084
+ }
4085
+ const currentSubtask = currentValue.subtasks.find((subtask) => !isTaskSubtaskCompleted(subtask));
4086
+ if (!(currentSubtask === null || currentSubtask === void 0 ? void 0 : currentSubtask.title)) {
4087
+ return undefined;
4088
+ }
4089
+ return `Working on ${currentSubtask.title}`;
4090
+ }
4091
+ /**
4092
+ * Picks the latest error or warning message, with the legacy generic fallback label.
4093
+ *
4094
+ * @private internal helper function of `ExecutionTask`
4095
+ */
4096
+ function getLatestIssueMessage(issues, fallbackMessage) {
4097
+ if (issues.length === 0) {
4098
+ return undefined;
4099
+ }
4100
+ return issues[issues.length - 1].message || fallbackMessage;
4101
+ }
4102
+ /**
4103
+ * Builds the final status-based fallback message.
4104
+ *
4105
+ * @private internal helper function of `ExecutionTask`
4106
+ */
4107
+ function getStatusMessage(status) {
4108
+ if (status === 'FINISHED') {
4109
+ return 'Finished';
4110
+ }
4111
+ if (status === 'ERROR') {
4112
+ return 'Error';
4113
+ }
4114
+ return 'Running';
4115
+ }
4116
+
4117
+ /**
4118
+ * Creates the initial mutable state for a task.
4119
+ *
4120
+ * @private internal helper function
4121
+ */
4122
+ function createTaskState(title, createdAt) {
4123
+ return {
4124
+ title,
4125
+ status: 'RUNNING',
4126
+ updatedAt: createdAt,
4127
+ errors: [],
4128
+ warnings: [],
4129
+ llmCalls: [],
4130
+ currentValue: {},
4131
+ customTldr: null,
4132
+ };
4133
+ }
4134
+ /**
4135
+ * Creates the partial-result updater passed into the task process callback.
4136
+ *
4137
+ * @private internal helper function
4138
+ */
4139
+ function createOngoingResultUpdater(taskState, partialResultSubject) {
4140
+ return (newOngoingResult) => {
4141
+ if (newOngoingResult.title) {
4142
+ taskState.title = newOngoingResult.title;
4143
+ }
4144
+ taskState.updatedAt = new Date();
4145
+ Object.assign(taskState.currentValue, newOngoingResult);
4146
+ // <- TODO: assign deep
4147
+ partialResultSubject.next(newOngoingResult);
4148
+ };
4149
+ }
4150
+ /**
4151
+ * Creates the custom-TLDR updater passed into the task process callback.
4152
+ *
4153
+ * @private internal helper function
4154
+ */
4155
+ function createTldrUpdater(taskState) {
4156
+ return (tldrInfo) => {
4157
+ taskState.customTldr = tldrInfo;
4158
+ taskState.updatedAt = new Date();
4159
+ };
4160
+ }
4161
+ /**
4162
+ * Creates the LLM call logger passed into the task process callback.
4163
+ *
4164
+ * @private internal helper function
4165
+ */
4166
+ function createLlmCallLogger(taskState) {
4167
+ return (llmCall) => {
4168
+ taskState.llmCalls.push(llmCall);
4169
+ taskState.updatedAt = new Date();
4170
+ };
4171
+ }
4172
+ /**
4173
+ * Wires the task promise into the observable/error lifecycle.
4174
+ *
4175
+ * @private internal helper function
4176
+ */
4177
+ function settleTaskPromise(finalResultPromise, taskState, partialResultSubject) {
4178
+ finalResultPromise
4179
+ .catch((error) => {
4180
+ taskState.errors.push(error);
4181
+ partialResultSubject.error(error);
4182
+ })
4183
+ .then((executionResult) => {
4184
+ if (executionResult) {
4185
+ try {
4186
+ finalizeTaskResult(executionResult, taskState, partialResultSubject);
4187
+ }
4188
+ catch (error) {
4189
+ failTaskResult(error, taskState, partialResultSubject);
4190
+ }
4191
+ }
4192
+ partialResultSubject.complete();
4193
+ });
4194
+ }
4195
+ /**
4196
+ * Applies the final successful task result into the mutable task state.
4197
+ *
4198
+ * @private internal helper function
4199
+ */
4200
+ function finalizeTaskResult(executionResult, taskState, partialResultSubject) {
4201
+ taskState.updatedAt = new Date();
4202
+ taskState.errors.push(...executionResult.errors);
4203
+ taskState.warnings.push(...executionResult.warnings);
4204
+ // <- TODO: [🌂] Only unique errors and warnings should be added (or filtered)
4205
+ // TODO: [🧠] !! errors, warning, isSuccessful are redundant both in `ExecutionTask` and `ExecutionTask.currentValue`
4206
+ // Also maybe move `ExecutionTask.currentValue.usage` -> `ExecutionTask.usage`
4207
+ // And delete `ExecutionTask.currentValue.preparedPipeline`
4208
+ assertsTaskSuccessful(executionResult);
4209
+ taskState.status = 'FINISHED';
4210
+ taskState.currentValue = jsonStringsToJsons(executionResult);
4211
+ // <- TODO: [🧠] Is this a good idea to convert JSON strins to JSONs?
4212
+ partialResultSubject.next(executionResult);
4213
+ }
4214
+ /**
4215
+ * Records a final-result failure after the task promise itself resolved.
4216
+ *
4217
+ * @private internal helper function
4218
+ */
4219
+ function failTaskResult(error, taskState, partialResultSubject) {
4220
+ assertsError(error);
4221
+ taskState.status = 'ERROR';
4222
+ taskState.errors.push(error);
4223
+ partialResultSubject.error(error);
4224
+ }
4225
+ /**
4226
+ * Helper to create a new task
4227
+ *
4228
+ * @private internal helper function
4229
+ */
4230
+ function createTask(options) {
4231
+ const { taskType, title, taskProcessCallback } = options;
4232
+ // TODO: [🐙] DRY
4233
+ const taskId = `${taskType.toLowerCase().substring(0, 4)}-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
4234
+ const createdAt = new Date();
4235
+ const taskState = createTaskState(title, createdAt);
4236
+ const partialResultSubject = new rxjs.Subject();
4237
+ // <- Note: Not using `BehaviorSubject` because on error we can't access the last value
4238
+ const finalResultPromise = /* not await */ taskProcessCallback(createOngoingResultUpdater(taskState, partialResultSubject), createTldrUpdater(taskState), createLlmCallLogger(taskState));
4239
+ settleTaskPromise(finalResultPromise, taskState, partialResultSubject);
4240
+ async function asPromise(options) {
4241
+ const { isCrashedOnError = true } = options || {};
4242
+ const finalResult = await finalResultPromise;
4243
+ if (isCrashedOnError) {
4244
+ assertsTaskSuccessful(finalResult);
4245
+ }
4246
+ return finalResult;
3626
4247
  }
3627
4248
  return {
3628
4249
  taskType,
@@ -3631,91 +4252,29 @@
3631
4252
  return PROMPTBOOK_ENGINE_VERSION;
3632
4253
  },
3633
4254
  get title() {
3634
- return title;
4255
+ return taskState.title;
3635
4256
  // <- Note: [1] These must be getters to allow changing the value in the future
3636
4257
  },
3637
4258
  get status() {
3638
- return status;
4259
+ return taskState.status;
3639
4260
  // <- Note: [1] --||--
3640
4261
  },
3641
4262
  get tldr() {
3642
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
3643
- // Use custom tldr if available
3644
- if (customTldr) {
3645
- return customTldr;
3646
- }
3647
- // Fallback to default implementation
3648
- const cv = currentValue;
3649
- // If explicit percent is provided, use it
3650
- 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;
3651
- // Simulate progress if not provided
3652
- if (typeof percentRaw !== 'number') {
3653
- // Simulate progress: evenly split across subtasks, based on elapsed time
3654
- const now = new Date();
3655
- const elapsedMs = now.getTime() - createdAt.getTime();
3656
- const totalMs = DEFAULT_TASK_SIMULATED_DURATION_MS;
3657
- // If subtasks are defined, split progress evenly
3658
- const subtaskCount = Array.isArray(cv === null || cv === void 0 ? void 0 : cv.subtasks) ? cv.subtasks.length : 1;
3659
- const completedSubtasks = Array.isArray(cv === null || cv === void 0 ? void 0 : cv.subtasks)
3660
- ? cv.subtasks.filter((s) => s.done || s.completed).length
3661
- : 0;
3662
- // Progress from completed subtasks
3663
- const subtaskProgress = subtaskCount > 0 ? completedSubtasks / subtaskCount : 0;
3664
- // Progress from elapsed time for current subtask
3665
- const timeProgress = Math.min(elapsedMs / totalMs, 1);
3666
- // Combine: completed subtasks + time progress for current subtask
3667
- percentRaw = Math.min(subtaskProgress + (1 / subtaskCount) * timeProgress, 1);
3668
- if (status === 'FINISHED')
3669
- percentRaw = 1;
3670
- if (status === 'ERROR')
3671
- percentRaw = 0;
3672
- }
3673
- // Clamp to [0,1]
3674
- let percent = Number(percentRaw) || 0;
3675
- if (percent < 0)
3676
- percent = 0;
3677
- if (percent > 1)
3678
- percent = 1;
3679
- // Build a short message: prefer explicit tldr.message, then common summary/message fields, then errors/warnings, then status
3680
- 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;
3681
- let message = messageFromResult;
3682
- if (!message) {
3683
- // If subtasks, show current subtask
3684
- if (Array.isArray(cv === null || cv === void 0 ? void 0 : cv.subtasks) && cv.subtasks.length > 0) {
3685
- const current = cv.subtasks.find((s) => !s.done && !s.completed);
3686
- if (current && current.title) {
3687
- message = `Working on ${current.title}`;
3688
- }
3689
- }
3690
- if (!message) {
3691
- if (errors.length) {
3692
- message = errors[errors.length - 1].message || 'Error';
3693
- }
3694
- else if (warnings.length) {
3695
- message = warnings[warnings.length - 1].message || 'Warning';
3696
- }
3697
- else if (status === 'FINISHED') {
3698
- message = 'Finished';
3699
- }
3700
- else if (status === 'ERROR') {
3701
- message = 'Error';
3702
- }
3703
- else {
3704
- message = 'Running';
3705
- }
3706
- }
3707
- }
3708
- return {
3709
- percent: percent,
3710
- message: message + ' (!!!fallback)',
3711
- };
4263
+ return resolveTaskTldr({
4264
+ customTldr: taskState.customTldr,
4265
+ currentValue: taskState.currentValue,
4266
+ status: taskState.status,
4267
+ createdAt,
4268
+ errors: taskState.errors,
4269
+ warnings: taskState.warnings,
4270
+ });
3712
4271
  },
3713
4272
  get createdAt() {
3714
4273
  return createdAt;
3715
4274
  // <- Note: [1] --||--
3716
4275
  },
3717
4276
  get updatedAt() {
3718
- return updatedAt;
4277
+ return taskState.updatedAt;
3719
4278
  // <- Note: [1] --||--
3720
4279
  },
3721
4280
  asPromise,
@@ -3723,19 +4282,19 @@
3723
4282
  return partialResultSubject.asObservable();
3724
4283
  },
3725
4284
  get errors() {
3726
- return errors;
4285
+ return taskState.errors;
3727
4286
  // <- Note: [1] --||--
3728
4287
  },
3729
4288
  get warnings() {
3730
- return warnings;
4289
+ return taskState.warnings;
3731
4290
  // <- Note: [1] --||--
3732
4291
  },
3733
4292
  get llmCalls() {
3734
- return [...llmCalls, { foo: '!!! bar' }];
4293
+ return [...taskState.llmCalls, { foo: '!!! bar' }];
3735
4294
  // <- Note: [1] --||--
3736
4295
  },
3737
4296
  get currentValue() {
3738
- return currentValue;
4297
+ return taskState.currentValue;
3739
4298
  // <- Note: [1] --||--
3740
4299
  },
3741
4300
  };
@@ -4653,210 +5212,275 @@
4653
5212
  * @public exported from `@promptbook/core`
4654
5213
  */
4655
5214
  async function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
5215
+ const { knowledgeSourceContent } = knowledgeSource;
5216
+ const name = knowledgeSource.name || knowledgeSourceContentToName(knowledgeSourceContent);
5217
+ const { rootDirname = null, isVerbose = DEFAULT_IS_VERBOSE } = options || {};
5218
+ if (isValidUrl(knowledgeSourceContent)) {
5219
+ return makeUrlKnowledgeSourceHandler(knowledgeSourceContent, name, tools, options, isVerbose);
5220
+ }
5221
+ if (isValidFilePath(knowledgeSourceContent)) {
5222
+ return makeFileKnowledgeSourceHandler(knowledgeSourceContent, name, tools, rootDirname, isVerbose);
5223
+ }
5224
+ return makeInlineTextKnowledgeSourceHandler(knowledgeSourceContent, name, isVerbose);
5225
+ }
5226
+ /**
5227
+ * Creates a source handler for URL-based knowledge.
5228
+ *
5229
+ * @private internal utility of `makeKnowledgeSourceHandler`
5230
+ */
5231
+ async function makeUrlKnowledgeSourceHandler(url, name, tools, options, isVerbose) {
4656
5232
  var _a;
4657
5233
  const { fetch = promptbookFetch } = tools;
4658
- const { knowledgeSourceContent } = knowledgeSource;
4659
- let { name } = knowledgeSource;
4660
- const { rootDirname = null,
4661
- // <- TODO: process.cwd() if running in Node.js
4662
- isVerbose = DEFAULT_IS_VERBOSE, } = options || {};
4663
- if (!name) {
4664
- name = knowledgeSourceContentToName(knowledgeSourceContent);
5234
+ if (isVerbose) {
5235
+ console.info(`📄 [1] "${name}" is available at "${url}"`);
4665
5236
  }
4666
- if (isValidUrl(knowledgeSourceContent)) {
4667
- const url = knowledgeSourceContent;
5237
+ const response = await fetch(url); // <- TODO: [🧠] Scraping and fetch proxy
5238
+ const mimeType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
5239
+ if (tools.fs === undefined || !url.endsWith('.pdf' /* <- TODO: [💵] */)) {
5240
+ return makeRemoteResponseKnowledgeSourceHandler(name, url, mimeType, response, isVerbose);
5241
+ }
5242
+ return cachePdfKnowledgeSourceHandler(url, name, mimeType, response, tools, options, isVerbose);
5243
+ }
5244
+ /**
5245
+ * Creates a source handler that reads directly from a fetched response.
5246
+ *
5247
+ * @private internal utility of `makeKnowledgeSourceHandler`
5248
+ */
5249
+ function makeRemoteResponseKnowledgeSourceHandler(name, url, mimeType, response, isVerbose) {
5250
+ if (isVerbose) {
5251
+ console.info(`📄 [2] "${name}" tools.fs is not available or URL is not a PDF.`);
5252
+ }
5253
+ return {
5254
+ source: name,
5255
+ filename: null,
5256
+ url,
5257
+ mimeType,
5258
+ /*
5259
+ TODO: [🥽]
5260
+ > async asBlob() {
5261
+ > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
5262
+ > const content = await response.blob();
5263
+ > return content;
5264
+ > },
5265
+ */
5266
+ async asJson() {
5267
+ // TODO: [👨🏻‍🤝‍👨🏻]
5268
+ const content = await response.json();
5269
+ return content;
5270
+ },
5271
+ async asText() {
5272
+ // TODO: [👨🏻‍🤝‍👨🏻]
5273
+ const content = await response.text();
5274
+ return content;
5275
+ },
5276
+ };
5277
+ }
5278
+ /**
5279
+ * Downloads a PDF knowledge source into cache when possible and falls back to in-memory content otherwise.
5280
+ *
5281
+ * @private internal utility of `makeKnowledgeSourceHandler`
5282
+ */
5283
+ async function cachePdfKnowledgeSourceHandler(url, name, mimeType, response, tools, options, isVerbose) {
5284
+ const rootDirname = path.join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
5285
+ const filepath = createDownloadedKnowledgeSourceFilepath(url, mimeType);
5286
+ const fullFilepath = path.join(rootDirname, filepath);
5287
+ await createCacheDirectoryIfPossible(name, fullFilepath, tools, isVerbose);
5288
+ const fileContent = Buffer.from(await response.arrayBuffer());
5289
+ if (fileContent.length > DEFAULT_MAX_FILE_SIZE /* <- TODO: Allow to pass different value to remote server */) {
5290
+ 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.`);
5291
+ }
5292
+ const isCached = await writeCacheFileIfPossible(name, fullFilepath, fileContent, tools, isVerbose);
5293
+ if (!isCached) {
5294
+ return makeBufferedKnowledgeSourceHandler(name, url, mimeType, fileContent);
5295
+ }
5296
+ // TODO: [💵] Check the file security
5297
+ // TODO: [🧹][🧠] Delete the file after the scraping is done
5298
+ if (isVerbose) {
5299
+ console.info(`📄 [5] "${name}" cached at "${fullFilepath}"`);
5300
+ }
5301
+ return makeKnowledgeSourceHandler({ name, knowledgeSourceContent: filepath }, tools, {
5302
+ ...options,
5303
+ rootDirname,
5304
+ });
5305
+ }
5306
+ /**
5307
+ * Builds a stable cache filepath for a downloaded knowledge source.
5308
+ *
5309
+ * @private internal utility of `makeKnowledgeSourceHandler`
5310
+ */
5311
+ function createDownloadedKnowledgeSourceFilepath(url, mimeType) {
5312
+ const basename = url.split('/').pop() || titleToName(url);
5313
+ const hash = sha256__default["default"](hexEncoder__default["default"].parse(url)).toString( /* hex */);
5314
+ // <- TODO: [🥬] Encapsulate sha256 to some private utility function
5315
+ return path.join(...nameToSubfolderPath(hash /* <- TODO: [🎎] Maybe add some SHA256 prefix */), `${basename.substring(0, MAX_FILENAME_LENGTH)}.${mimeTypeToExtension(mimeType)}`);
5316
+ }
5317
+ /**
5318
+ * Tries to create the cache directory needed for a downloaded knowledge source.
5319
+ *
5320
+ * @private internal utility of `makeKnowledgeSourceHandler`
5321
+ */
5322
+ async function createCacheDirectoryIfPossible(name, fullFilepath, tools, isVerbose) {
5323
+ try {
5324
+ await tools.fs.mkdir(path.dirname(fullFilepath), { recursive: true });
5325
+ }
5326
+ catch (error) {
4668
5327
  if (isVerbose) {
4669
- console.info(`📄 [1] "${name}" is available at "${url}"`);
4670
- }
4671
- const response = await fetch(url); // <- TODO: [🧠] Scraping and fetch proxy
4672
- const mimeType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
4673
- if (tools.fs === undefined || !url.endsWith('.pdf' /* <- TODO: [💵] */)) {
4674
- if (isVerbose) {
4675
- console.info(`📄 [2] "${name}" tools.fs is not available or URL is not a PDF.`);
4676
- }
4677
- return {
4678
- source: name,
4679
- filename: null,
4680
- url,
4681
- mimeType,
4682
- /*
4683
- TODO: [🥽]
4684
- > async asBlob() {
4685
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
4686
- > const content = await response.blob();
4687
- > return content;
4688
- > },
4689
- */
4690
- async asJson() {
4691
- // TODO: [👨🏻‍🤝‍👨🏻]
4692
- const content = await response.json();
4693
- return content;
4694
- },
4695
- async asText() {
4696
- // TODO: [👨🏻‍🤝‍👨🏻]
4697
- const content = await response.text();
4698
- return content;
4699
- },
4700
- };
4701
- }
4702
- const basename = url.split('/').pop() || titleToName(url);
4703
- const hash = sha256__default["default"](hexEncoder__default["default"].parse(url)).toString( /* hex */);
4704
- // <- TODO: [🥬] Encapsulate sha256 to some private utility function
4705
- const rootDirname = path.join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
4706
- const filepath = path.join(...nameToSubfolderPath(hash /* <- TODO: [🎎] Maybe add some SHA256 prefix */), `${basename.substring(0, MAX_FILENAME_LENGTH)}.${mimeTypeToExtension(mimeType)}`);
4707
- // Note: Try to create cache directory, but don't fail if filesystem has issues
4708
- try {
4709
- await tools.fs.mkdir(path.dirname(path.join(rootDirname, filepath)), { recursive: true });
4710
- }
4711
- catch (error) {
4712
- if (isVerbose) {
4713
- console.info(`📄 [3] "${name}" error creating cache directory`);
4714
- }
4715
- // Note: If we can't create cache directory, we'll handle it when trying to write the file
4716
- // This handles read-only filesystems, permission issues, and missing parent directories
4717
- if (error instanceof Error &&
4718
- (error.message.includes('EROFS') ||
4719
- error.message.includes('read-only') ||
4720
- error.message.includes('EACCES') ||
4721
- error.message.includes('EPERM') ||
4722
- error.message.includes('ENOENT'))) ;
4723
- else {
4724
- // Re-throw other unexpected errors
4725
- throw error;
4726
- }
4727
- }
4728
- const fileContent = Buffer.from(await response.arrayBuffer());
4729
- if (fileContent.length > DEFAULT_MAX_FILE_SIZE /* <- TODO: Allow to pass different value to remote server */) {
4730
- 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.`);
4731
- }
4732
- // Note: Try to cache the downloaded file, but don't fail if the filesystem is read-only
4733
- try {
4734
- await tools.fs.writeFile(path.join(rootDirname, filepath), fileContent);
4735
- }
4736
- catch (error) {
4737
- if (isVerbose) {
4738
- console.info(`📄 [4] "${name}" error writing cache file`);
4739
- }
4740
- // Note: If we can't write to cache, we'll process the file directly from memory
4741
- // This handles read-only filesystems like Vercel
4742
- if (error instanceof Error &&
4743
- (error.message.includes('EROFS') ||
4744
- error.message.includes('read-only') ||
4745
- error.message.includes('EACCES') ||
4746
- error.message.includes('EPERM') ||
4747
- error.message.includes('ENOENT'))) {
4748
- // Return a handler that works directly with the downloaded content
4749
- return {
4750
- source: name,
4751
- filename: null,
4752
- url,
4753
- mimeType,
4754
- async asJson() {
4755
- return JSON.parse(fileContent.toString('utf-8'));
4756
- },
4757
- async asText() {
4758
- return fileContent.toString('utf-8');
4759
- },
4760
- };
4761
- }
4762
- else {
4763
- // Re-throw other unexpected errors
4764
- throw error;
4765
- }
5328
+ console.info(`📄 [3] "${name}" error creating cache directory`);
4766
5329
  }
4767
- // TODO: [💵] Check the file security
4768
- // TODO: [🧹][🧠] Delete the file after the scraping is done
4769
- if (isVerbose) {
4770
- console.info(`📄 [5] "${name}" cached at "${path.join(rootDirname, filepath)}"`);
5330
+ // Note: If we can't create cache directory, we'll handle it when trying to write the file
5331
+ // This handles read-only filesystems, permission issues, and missing parent directories
5332
+ if (!isIgnorableCacheFilesystemError(error)) {
5333
+ throw error;
4771
5334
  }
4772
- return makeKnowledgeSourceHandler({ name, knowledgeSourceContent: filepath }, tools, {
4773
- ...options,
4774
- rootDirname,
4775
- });
4776
5335
  }
4777
- else if (isValidFilePath(knowledgeSourceContent)) {
4778
- if (tools.fs === undefined) {
4779
- throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
4780
- // <- TODO: [🧠] What is the best error type here`
4781
- }
4782
- if (rootDirname === null) {
4783
- throw new EnvironmentMismatchError('Can not import file knowledge in non-file pipeline');
4784
- // <- TODO: [🧠] What is the best error type here`
4785
- }
4786
- const filename = path.isAbsolute(knowledgeSourceContent)
4787
- ? knowledgeSourceContent
4788
- : path.join(rootDirname, knowledgeSourceContent).split('\\').join('/');
5336
+ }
5337
+ /**
5338
+ * Tries to write downloaded content into cache and reports whether the cache was usable.
5339
+ *
5340
+ * @private internal utility of `makeKnowledgeSourceHandler`
5341
+ */
5342
+ async function writeCacheFileIfPossible(name, fullFilepath, fileContent, tools, isVerbose) {
5343
+ // Note: Try to cache the downloaded file, but don't fail if the filesystem is read-only
5344
+ try {
5345
+ await tools.fs.writeFile(fullFilepath, fileContent);
5346
+ return true;
5347
+ }
5348
+ catch (error) {
4789
5349
  if (isVerbose) {
4790
- console.info(`📄 [6] "${name}" is a valid file "${filename}"`);
5350
+ console.info(`📄 [4] "${name}" error writing cache file`);
4791
5351
  }
4792
- const fileExtension = getFileExtension(filename);
4793
- const mimeType = extensionToMimeType(fileExtension || '');
4794
- if (!(await isFileExisting(filename, tools.fs))) {
4795
- throw new NotFoundError(spacetrim.spaceTrim((block) => `
4796
- Can not make source handler for file which does not exist:
4797
-
4798
- File:
4799
- ${block(knowledgeSourceContent)}
4800
-
4801
- Full file path:
4802
- ${block(filename)}
4803
- `));
5352
+ // Note: If we can't write to cache, we'll process the file directly from memory
5353
+ // This handles read-only filesystems like Vercel
5354
+ if (isIgnorableCacheFilesystemError(error)) {
5355
+ return false;
4804
5356
  }
4805
- // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
4806
- return {
4807
- source: name,
4808
- filename,
4809
- url: null,
4810
- mimeType,
4811
- /*
4812
- TODO: [🥽]
4813
- > async asBlob() {
4814
- > const content = await tools.fs!.readFile(filename);
4815
- > return new Blob(
4816
- > [
4817
- > content,
4818
- > // <- TODO: [🥽] This is NOT tested, test it
4819
- > ],
4820
- > { type: mimeType },
4821
- > );
4822
- > },
4823
- */
4824
- async asJson() {
4825
- return jsonParse(await tools.fs.readFile(filename, 'utf-8'));
4826
- },
4827
- async asText() {
4828
- return await tools.fs.readFile(filename, 'utf-8');
4829
- },
4830
- };
5357
+ throw error;
4831
5358
  }
4832
- else {
4833
- if (isVerbose) {
4834
- console.info(`📄 [7] "${name}" is just a explicit string text with a knowledge source`);
4835
- console.info('---');
4836
- console.info(knowledgeSourceContent);
4837
- console.info('---');
4838
- }
4839
- return {
4840
- source: name,
4841
- filename: null,
4842
- url: null,
4843
- mimeType: 'text/markdown',
4844
- asText() {
4845
- return knowledgeSource.knowledgeSourceContent;
4846
- },
4847
- asJson() {
4848
- throw new UnexpectedError('Did not expect that `markdownScraper` would need to get the content `asJson`');
4849
- },
4850
- /*
4851
- TODO: [🥽]
4852
- > asBlob() {
4853
- > throw new UnexpectedError(
4854
- > 'Did not expect that `markdownScraper` would need to get the content `asBlob`',
4855
- > );
4856
- > },
4857
- */
4858
- };
5359
+ }
5360
+ /**
5361
+ * Detects filesystem errors that should not fail optional caching.
5362
+ *
5363
+ * @private internal utility of `makeKnowledgeSourceHandler`
5364
+ */
5365
+ function isIgnorableCacheFilesystemError(error) {
5366
+ return (error instanceof Error &&
5367
+ (error.message.includes('EROFS') ||
5368
+ error.message.includes('read-only') ||
5369
+ error.message.includes('EACCES') ||
5370
+ error.message.includes('EPERM') ||
5371
+ error.message.includes('ENOENT')));
5372
+ }
5373
+ /**
5374
+ * Creates a source handler backed by already downloaded file content kept in memory.
5375
+ *
5376
+ * @private internal utility of `makeKnowledgeSourceHandler`
5377
+ */
5378
+ function makeBufferedKnowledgeSourceHandler(name, url, mimeType, fileContent) {
5379
+ return {
5380
+ source: name,
5381
+ filename: null,
5382
+ url,
5383
+ mimeType,
5384
+ async asJson() {
5385
+ return JSON.parse(fileContent.toString('utf-8'));
5386
+ },
5387
+ async asText() {
5388
+ return fileContent.toString('utf-8');
5389
+ },
5390
+ };
5391
+ }
5392
+ /**
5393
+ * Creates a source handler for file-based knowledge.
5394
+ *
5395
+ * @private internal utility of `makeKnowledgeSourceHandler`
5396
+ */
5397
+ async function makeFileKnowledgeSourceHandler(knowledgeSourceContent, name, tools, rootDirname, isVerbose) {
5398
+ if (tools.fs === undefined) {
5399
+ throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
5400
+ // <- TODO: [🧠] What is the best error type here`
5401
+ }
5402
+ if (rootDirname === null) {
5403
+ throw new EnvironmentMismatchError('Can not import file knowledge in non-file pipeline');
5404
+ // <- TODO: [🧠] What is the best error type here`
5405
+ }
5406
+ const filename = path.isAbsolute(knowledgeSourceContent)
5407
+ ? knowledgeSourceContent
5408
+ : path.join(rootDirname, knowledgeSourceContent).split('\\').join('/');
5409
+ if (isVerbose) {
5410
+ console.info(`📄 [6] "${name}" is a valid file "${filename}"`);
5411
+ }
5412
+ const fileExtension = getFileExtension(filename);
5413
+ const mimeType = extensionToMimeType(fileExtension || '');
5414
+ if (!(await isFileExisting(filename, tools.fs))) {
5415
+ throw new NotFoundError(spacetrim.spaceTrim((block) => `
5416
+ Can not make source handler for file which does not exist:
5417
+
5418
+ File:
5419
+ ${block(knowledgeSourceContent)}
5420
+
5421
+ Full file path:
5422
+ ${block(filename)}
5423
+ `));
5424
+ }
5425
+ // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
5426
+ return {
5427
+ source: name,
5428
+ filename,
5429
+ url: null,
5430
+ mimeType,
5431
+ /*
5432
+ TODO: [🥽]
5433
+ > async asBlob() {
5434
+ > const content = await tools.fs!.readFile(filename);
5435
+ > return new Blob(
5436
+ > [
5437
+ > content,
5438
+ > // <- TODO: [🥽] This is NOT tested, test it
5439
+ > ],
5440
+ > { type: mimeType },
5441
+ > );
5442
+ > },
5443
+ */
5444
+ async asJson() {
5445
+ return jsonParse(await tools.fs.readFile(filename, 'utf-8'));
5446
+ },
5447
+ async asText() {
5448
+ return await tools.fs.readFile(filename, 'utf-8');
5449
+ },
5450
+ };
5451
+ }
5452
+ /**
5453
+ * Creates a source handler for inline text knowledge.
5454
+ *
5455
+ * @private internal utility of `makeKnowledgeSourceHandler`
5456
+ */
5457
+ function makeInlineTextKnowledgeSourceHandler(knowledgeSourceContent, name, isVerbose) {
5458
+ if (isVerbose) {
5459
+ console.info(`📄 [7] "${name}" is just a explicit string text with a knowledge source`);
5460
+ console.info('---');
5461
+ console.info(knowledgeSourceContent);
5462
+ console.info('---');
4859
5463
  }
5464
+ return {
5465
+ source: name,
5466
+ filename: null,
5467
+ url: null,
5468
+ mimeType: 'text/markdown',
5469
+ asText() {
5470
+ return knowledgeSourceContent;
5471
+ },
5472
+ asJson() {
5473
+ throw new UnexpectedError('Did not expect that `markdownScraper` would need to get the content `asJson`');
5474
+ },
5475
+ /*
5476
+ TODO: [🥽]
5477
+ > asBlob() {
5478
+ > throw new UnexpectedError(
5479
+ > 'Did not expect that `markdownScraper` would need to get the content `asBlob`',
5480
+ > );
5481
+ > },
5482
+ */
5483
+ };
4860
5484
  }
4861
5485
 
4862
5486
  /**
@@ -6141,112 +6765,10 @@
6141
6765
  }
6142
6766
  }
6143
6767
 
6144
- /**
6145
- * Executes a pipeline task with multiple attempts, including joker and retry logic. Handles different task types
6146
- * (prompt, script, dialog, etc.), applies postprocessing, checks expectations, and updates the execution report.
6147
- * Throws errors if execution fails after all attempts.
6148
- *
6149
- * @param options - The options for execution, including task, parameters, pipeline, and configuration.
6150
- * @returns The result string of the executed task.
6151
- *
6152
- * @private internal utility of `createPipelineExecutor`
6153
- */
6154
- async function executeAttempts(options) {
6155
- const $ongoingTaskResult = createOngoingTaskResult();
6156
- const llmTools = getSingleLlmExecutionTools(options.tools.llm);
6157
- attempts: for (let attemptIndex = -options.jokerParameterNames.length; attemptIndex < options.maxAttempts; attemptIndex++) {
6158
- const attempt = createAttemptDescriptor({
6159
- attemptIndex,
6160
- jokerParameterNames: options.jokerParameterNames,
6161
- pipelineIdentification: options.pipelineIdentification,
6162
- });
6163
- resetAttemptExecutionState($ongoingTaskResult);
6164
- try {
6165
- await executeSingleAttempt({
6166
- attempt,
6167
- options,
6168
- llmTools,
6169
- $ongoingTaskResult,
6170
- });
6171
- break attempts;
6172
- }
6173
- catch (error) {
6174
- if (!(error instanceof ExpectError)) {
6175
- throw error;
6176
- }
6177
- recordFailedAttempt({
6178
- error,
6179
- attemptIndex,
6180
- onProgress: options.onProgress,
6181
- $ongoingTaskResult,
6182
- });
6183
- }
6184
- finally {
6185
- reportPromptExecution({
6186
- attempt,
6187
- task: options.task,
6188
- $executionReport: options.$executionReport,
6189
- logLlmCall: options.logLlmCall,
6190
- $ongoingTaskResult,
6191
- });
6192
- }
6193
- throwIfFinalAttemptFailed({
6194
- attemptIndex,
6195
- maxAttempts: options.maxAttempts,
6196
- maxExecutionAttempts: options.maxExecutionAttempts,
6197
- pipelineIdentification: options.pipelineIdentification,
6198
- $ongoingTaskResult,
6199
- });
6200
- }
6201
- return getSuccessfulResultString({
6202
- pipelineIdentification: options.pipelineIdentification,
6203
- $ongoingTaskResult,
6204
- });
6205
- }
6206
- /**
6207
- * Creates mutable attempt state for one task execution lifecycle.
6208
- */
6209
- function createOngoingTaskResult() {
6210
- return {
6211
- $result: null,
6212
- $resultString: null,
6213
- $expectError: null,
6214
- $scriptPipelineExecutionErrors: [],
6215
- $failedResults: [],
6216
- };
6217
- }
6218
- /**
6219
- * Resolves the bookkeeping for one loop iteration, including joker lookup.
6220
- */
6221
- function createAttemptDescriptor(options) {
6222
- const { attemptIndex, jokerParameterNames, pipelineIdentification } = options;
6223
- const isJokerAttempt = attemptIndex < 0;
6224
- const jokerParameterName = isJokerAttempt
6225
- ? jokerParameterNames[jokerParameterNames.length + attemptIndex]
6226
- : undefined;
6227
- if (isJokerAttempt && !jokerParameterName) {
6228
- throw new UnexpectedError(spacetrim.spaceTrim((block) => `
6229
- Joker not found in attempt ${attemptIndex}
6230
-
6231
- ${block(pipelineIdentification)}
6232
- `));
6233
- }
6234
- return {
6235
- attemptIndex,
6236
- isJokerAttempt,
6237
- jokerParameterName,
6238
- };
6239
- }
6240
- /**
6241
- * Clears the per-attempt result slots while preserving cumulative failure history.
6242
- */
6243
- function resetAttemptExecutionState($ongoingTaskResult) {
6244
- $ongoingTaskResult.$result = null;
6245
- $ongoingTaskResult.$resultString = null;
6246
- $ongoingTaskResult.$expectError = null;
6247
- }
6248
6768
  /**
6249
6769
  * Executes one loop iteration, from joker resolution or task execution through validation.
6770
+ *
6771
+ * @private function of `executeAttempts`
6250
6772
  */
6251
6773
  async function executeSingleAttempt(options) {
6252
6774
  const { attempt, options: executeAttemptsOptions, llmTools, $ongoingTaskResult } = options;
@@ -6561,11 +7083,15 @@
6561
7083
  // Update the result string in case format processing modified it (e.g., JSON extraction)
6562
7084
  $ongoingTaskResult.$resultString = validationResult.processedResultString;
6563
7085
  }
7086
+
6564
7087
  /**
6565
- * Stores one failed attempt and reports the expectation error upstream.
7088
+ * Stores one failed attempt, reports the expectation error, and throws the aggregated retry error after the final
7089
+ * regular attempt.
7090
+ *
7091
+ * @private function of `executeAttempts`
6566
7092
  */
6567
- function recordFailedAttempt(options) {
6568
- const { error, attemptIndex, onProgress, $ongoingTaskResult } = options;
7093
+ function handleAttemptFailure(options) {
7094
+ const { error, attemptIndex, maxAttempts, maxExecutionAttempts, onProgress, pipelineIdentification, $ongoingTaskResult, } = options;
6569
7095
  $ongoingTaskResult.$expectError = error;
6570
7096
  $ongoingTaskResult.$failedResults.push({
6571
7097
  attemptIndex,
@@ -6575,39 +7101,7 @@
6575
7101
  onProgress({
6576
7102
  errors: [error],
6577
7103
  });
6578
- }
6579
- /**
6580
- * Appends the prompt execution report for prompt-task attempts.
6581
- */
6582
- function reportPromptExecution(options) {
6583
- const { attempt, task, $executionReport, logLlmCall, $ongoingTaskResult } = options;
6584
- if (attempt.isJokerAttempt || task.taskType !== 'PROMPT_TASK' || !$ongoingTaskResult.$prompt) {
6585
- return;
6586
- }
6587
- // Note: [2] When some expected parameter is not defined, error will occur in templateParameters
6588
- // In that case we don’t want to make a report about it because it’s not a llm execution error
6589
- const executionPromptReport = {
6590
- prompt: {
6591
- ...$ongoingTaskResult.$prompt,
6592
- // <- TODO: [🧠] How to pick everyhing except `pipelineUrl`
6593
- },
6594
- result: $ongoingTaskResult.$result || undefined,
6595
- error: $ongoingTaskResult.$expectError === null ? undefined : serializeError($ongoingTaskResult.$expectError),
6596
- };
6597
- $executionReport.promptExecutions.push(executionPromptReport);
6598
- if (logLlmCall) {
6599
- logLlmCall({
6600
- modelName: 'model' /* <- TODO: How to get model name from the report */,
6601
- report: executionPromptReport,
6602
- });
6603
- }
6604
- }
6605
- /**
6606
- * Throws the aggregated retry error after the last regular attempt fails expectations.
6607
- */
6608
- function throwIfFinalAttemptFailed(options) {
6609
- const { attemptIndex, maxAttempts, maxExecutionAttempts, pipelineIdentification, $ongoingTaskResult } = options;
6610
- if ($ongoingTaskResult.$expectError === null || attemptIndex !== maxAttempts - 1) {
7104
+ if (attemptIndex !== maxAttempts - 1) {
6611
7105
  return;
6612
7106
  }
6613
7107
  throw new PipelineExecutionError(spacetrim.spaceTrim((block) => {
@@ -6638,7 +7132,9 @@
6638
7132
  ${block(quoteMultilineText(((_b = failure.error) === null || _b === void 0 ? void 0 : _b.message) || ''))}
6639
7133
 
6640
7134
  Result:
6641
- ${block(failure.result === null ? 'null' : quoteMultilineText(spacetrim.spaceTrim(failure.result)))}
7135
+ ${block(failure.result === null
7136
+ ? 'null'
7137
+ : quoteMultilineText(spacetrim.spaceTrim(failure.result)))}
6642
7138
  `;
6643
7139
  }))
6644
7140
  .join('\n\n---\n\n');
@@ -6652,6 +7148,136 @@
6652
7148
  .map((line) => `> ${line}`)
6653
7149
  .join('\n');
6654
7150
  }
7151
+
7152
+ /**
7153
+ * Appends the prompt execution report for prompt-task attempts.
7154
+ *
7155
+ * @private function of `executeAttempts`
7156
+ */
7157
+ function reportPromptExecution(options) {
7158
+ const { attempt, task, $executionReport, logLlmCall, $ongoingTaskResult } = options;
7159
+ if (attempt.isJokerAttempt || task.taskType !== 'PROMPT_TASK' || !$ongoingTaskResult.$prompt) {
7160
+ return;
7161
+ }
7162
+ // Note: [2] When some expected parameter is not defined, error will occur in templateParameters
7163
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
7164
+ const executionPromptReport = {
7165
+ prompt: {
7166
+ ...$ongoingTaskResult.$prompt,
7167
+ // <- TODO: [🧠] How to pick everyhing except `pipelineUrl`
7168
+ },
7169
+ result: $ongoingTaskResult.$result || undefined,
7170
+ error: $ongoingTaskResult.$expectError === null ? undefined : serializeError($ongoingTaskResult.$expectError),
7171
+ };
7172
+ $executionReport.promptExecutions.push(executionPromptReport);
7173
+ if (logLlmCall) {
7174
+ logLlmCall({
7175
+ modelName: 'model' /* <- TODO: How to get model name from the report */,
7176
+ report: executionPromptReport,
7177
+ });
7178
+ }
7179
+ }
7180
+
7181
+ /**
7182
+ * Executes a pipeline task with multiple attempts, including joker and retry logic. Handles different task types
7183
+ * (prompt, script, dialog, etc.), applies postprocessing, checks expectations, and updates the execution report.
7184
+ * Throws errors if execution fails after all attempts.
7185
+ *
7186
+ * @param options - The options for execution, including task, parameters, pipeline, and configuration.
7187
+ * @returns The result string of the executed task.
7188
+ *
7189
+ * @private internal utility of `createPipelineExecutor`
7190
+ */
7191
+ async function executeAttempts(options) {
7192
+ const $ongoingTaskResult = createOngoingTaskResult();
7193
+ const llmTools = getSingleLlmExecutionTools(options.tools.llm);
7194
+ attempts: for (let attemptIndex = -options.jokerParameterNames.length; attemptIndex < options.maxAttempts; attemptIndex++) {
7195
+ const attempt = createAttemptDescriptor({
7196
+ attemptIndex,
7197
+ jokerParameterNames: options.jokerParameterNames,
7198
+ pipelineIdentification: options.pipelineIdentification,
7199
+ });
7200
+ resetAttemptExecutionState($ongoingTaskResult);
7201
+ try {
7202
+ await executeSingleAttempt({
7203
+ attempt,
7204
+ options,
7205
+ llmTools,
7206
+ $ongoingTaskResult,
7207
+ });
7208
+ break attempts;
7209
+ }
7210
+ catch (error) {
7211
+ if (!(error instanceof ExpectError)) {
7212
+ throw error;
7213
+ }
7214
+ handleAttemptFailure({
7215
+ error,
7216
+ attemptIndex,
7217
+ maxAttempts: options.maxAttempts,
7218
+ maxExecutionAttempts: options.maxExecutionAttempts,
7219
+ onProgress: options.onProgress,
7220
+ pipelineIdentification: options.pipelineIdentification,
7221
+ $ongoingTaskResult,
7222
+ });
7223
+ }
7224
+ finally {
7225
+ reportPromptExecution({
7226
+ attempt,
7227
+ task: options.task,
7228
+ $executionReport: options.$executionReport,
7229
+ logLlmCall: options.logLlmCall,
7230
+ $ongoingTaskResult,
7231
+ });
7232
+ }
7233
+ }
7234
+ return getSuccessfulResultString({
7235
+ pipelineIdentification: options.pipelineIdentification,
7236
+ $ongoingTaskResult,
7237
+ });
7238
+ }
7239
+ /**
7240
+ * Creates mutable attempt state for one task execution lifecycle.
7241
+ */
7242
+ function createOngoingTaskResult() {
7243
+ return {
7244
+ $result: null,
7245
+ $resultString: null,
7246
+ $expectError: null,
7247
+ $scriptPipelineExecutionErrors: [],
7248
+ $failedResults: [],
7249
+ };
7250
+ }
7251
+ /**
7252
+ * Resolves the bookkeeping for one loop iteration, including joker lookup.
7253
+ */
7254
+ function createAttemptDescriptor(options) {
7255
+ const { attemptIndex, jokerParameterNames, pipelineIdentification } = options;
7256
+ const isJokerAttempt = attemptIndex < 0;
7257
+ const jokerParameterName = isJokerAttempt
7258
+ ? jokerParameterNames[jokerParameterNames.length + attemptIndex]
7259
+ : undefined;
7260
+ if (isJokerAttempt && !jokerParameterName) {
7261
+ throw new UnexpectedError(spacetrim.spaceTrim((block) => `
7262
+ Joker not found in attempt ${attemptIndex}
7263
+
7264
+ ${block(pipelineIdentification)}
7265
+ `));
7266
+ }
7267
+ return {
7268
+ attemptIndex,
7269
+ isJokerAttempt,
7270
+ jokerParameterName,
7271
+ };
7272
+ }
7273
+ /**
7274
+ * Clears the per-attempt result slots while preserving cumulative failure history.
7275
+ */
7276
+ function resetAttemptExecutionState($ongoingTaskResult) {
7277
+ $ongoingTaskResult.$result = null;
7278
+ $ongoingTaskResult.$resultString = null;
7279
+ $ongoingTaskResult.$expectError = null;
7280
+ }
6655
7281
  /**
6656
7282
  * Returns the successful result string or raises an unexpected internal-state error.
6657
7283
  */