@promptbook/node 0.84.0-9 → 0.85.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +21 -5
  2. package/esm/index.es.js +596 -351
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/cli.index.d.ts +4 -0
  5. package/esm/typings/src/_packages/core.index.d.ts +12 -4
  6. package/esm/typings/src/_packages/deepseek.index.d.ts +8 -0
  7. package/esm/typings/src/_packages/types.index.d.ts +16 -2
  8. package/esm/typings/src/_packages/utils.index.d.ts +2 -2
  9. package/esm/typings/src/_packages/wizzard.index.d.ts +4 -0
  10. package/esm/typings/src/cli/cli-commands/_boilerplate.d.ts +13 -0
  11. package/esm/typings/src/cli/cli-commands/about.d.ts +4 -1
  12. package/esm/typings/src/cli/cli-commands/hello.d.ts +3 -1
  13. package/esm/typings/src/cli/cli-commands/list-models.d.ts +3 -1
  14. package/esm/typings/src/cli/cli-commands/list-scrapers.d.ts +13 -0
  15. package/esm/typings/src/cli/cli-commands/make.d.ts +3 -1
  16. package/esm/typings/src/cli/cli-commands/prettify.d.ts +3 -1
  17. package/esm/typings/src/cli/cli-commands/run.d.ts +3 -1
  18. package/esm/typings/src/cli/cli-commands/runInteractiveChatbot.d.ts +1 -1
  19. package/esm/typings/src/cli/cli-commands/start-server.d.ts +13 -0
  20. package/esm/typings/src/cli/cli-commands/test-command.d.ts +3 -1
  21. package/esm/typings/src/config.d.ts +27 -1
  22. package/esm/typings/src/conversion/compilePipelineOnRemoteServer.d.ts +1 -1
  23. package/esm/typings/src/execution/AbstractTaskResult.d.ts +25 -0
  24. package/esm/typings/src/execution/ExecutionTask.d.ts +71 -0
  25. package/esm/typings/src/execution/FilesystemTools.d.ts +1 -1
  26. package/esm/typings/src/execution/PipelineExecutor.d.ts +2 -5
  27. package/esm/typings/src/execution/PipelineExecutorResult.d.ts +2 -15
  28. package/esm/typings/src/execution/PromptbookFetch.d.ts +8 -1
  29. package/esm/typings/src/execution/{assertsExecutionSuccessful.d.ts → assertsTaskSuccessful.d.ts} +4 -3
  30. package/esm/typings/src/execution/createPipelineExecutor/00-createPipelineExecutor.d.ts +0 -3
  31. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +2 -6
  32. package/esm/typings/src/execution/createPipelineExecutor/20-executeTask.d.ts +3 -6
  33. package/esm/typings/src/llm-providers/_common/register/$registeredLlmToolsMessage.d.ts +9 -0
  34. package/esm/typings/src/llm-providers/deepseek/DeepseekExecutionToolsOptions.d.ts +9 -0
  35. package/esm/typings/src/llm-providers/deepseek/createDeepseekExecutionTools.d.ts +14 -0
  36. package/esm/typings/src/llm-providers/deepseek/register-configuration.d.ts +14 -0
  37. package/esm/typings/src/llm-providers/deepseek/register-constructor.d.ts +15 -0
  38. package/esm/typings/src/pipeline/book-notation.d.ts +3 -2
  39. package/esm/typings/src/pipeline/prompt-notation.d.ts +18 -5
  40. package/esm/typings/src/prepare/preparePipelineOnRemoteServer.d.ts +1 -1
  41. package/esm/typings/src/remote-server/socket-types/_subtypes/PromptbookServer_Identification.d.ts +5 -2
  42. package/esm/typings/src/remote-server/startRemoteServer.d.ts +1 -0
  43. package/esm/typings/src/types/typeAliases.d.ts +2 -0
  44. package/esm/typings/src/utils/editable/edit-pipeline-string/deflatePipeline.test.d.ts +1 -0
  45. package/esm/typings/src/utils/editable/utils/isFlatPipeline.test.d.ts +1 -0
  46. package/esm/typings/src/utils/environment/$isRunningInBrowser.d.ts +3 -0
  47. package/esm/typings/src/utils/environment/$isRunningInJest.d.ts +3 -0
  48. package/esm/typings/src/utils/environment/$isRunningInNode.d.ts +3 -0
  49. package/esm/typings/src/utils/environment/$isRunningInWebWorker.d.ts +3 -0
  50. package/esm/typings/src/utils/files/mimeTypeToExtension.d.ts +10 -0
  51. package/esm/typings/src/utils/files/mimeTypeToExtension.test.d.ts +1 -0
  52. package/esm/typings/src/utils/random/$randomSeed.d.ts +2 -1
  53. package/esm/typings/src/utils/random/$randomToken.d.ts +13 -0
  54. package/esm/typings/src/wizzard/wizzard.d.ts +8 -3
  55. package/package.json +11 -16
  56. package/umd/index.umd.js +595 -352
  57. package/umd/index.umd.js.map +1 -1
  58. package/esm/typings/src/remote-server/socket-types/_common/PromptbookServer_Progress.d.ts +0 -10
  59. package/esm/typings/src/types/TaskProgress.d.ts +0 -43
package/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('papaparse'), require('crypto-js'), require('crypto-js/enc-hex'), require('mime-types'), require('child_process'), require('dotenv'), require('crypto-js/sha256')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'colors', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'papaparse', 'crypto-js', 'crypto-js/enc-hex', 'mime-types', 'child_process', 'dotenv', 'crypto-js/sha256'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.colors, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.papaparse, global.cryptoJs, global.hexEncoder, global.mimeTypes, global.child_process, global.dotenv, global.sha256));
5
- })(this, (function (exports, colors, promises, path, spaceTrim, prettier, parserHtml, waitasecond, papaparse, cryptoJs, hexEncoder, mimeTypes, child_process, dotenv, sha256) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('rxjs'), require('crypto'), require('waitasecond'), require('papaparse'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('crypto-js'), require('mime-types'), require('child_process'), require('dotenv')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'colors', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html', 'rxjs', 'crypto', 'waitasecond', 'papaparse', 'crypto-js/enc-hex', 'crypto-js/sha256', 'crypto-js', 'mime-types', 'child_process', 'dotenv'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.colors, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml, global.rxjs, global.crypto, global.waitasecond, global.papaparse, global.hexEncoder, global.sha256, global.cryptoJs, global.mimeTypes, global.child_process, global.dotenv));
5
+ })(this, (function (exports, colors, promises, path, spaceTrim, prettier, parserHtml, rxjs, crypto, waitasecond, papaparse, hexEncoder, sha256, cryptoJs, mimeTypes, child_process, dotenv) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -28,8 +28,8 @@
28
28
  var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
29
29
  var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
30
30
  var hexEncoder__default = /*#__PURE__*/_interopDefaultLegacy(hexEncoder);
31
- var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
32
31
  var sha256__default = /*#__PURE__*/_interopDefaultLegacy(sha256);
32
+ var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
33
33
 
34
34
  // ⚠️ WARNING: This code has been generated so that any manual changes will be overwritten
35
35
  /**
@@ -45,7 +45,7 @@
45
45
  * @generated
46
46
  * @see https://github.com/webgptorg/promptbook
47
47
  */
48
- var PROMPTBOOK_ENGINE_VERSION = '0.84.0-8';
48
+ var PROMPTBOOK_ENGINE_VERSION = '0.84.0';
49
49
  /**
50
50
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
51
51
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -222,6 +222,18 @@
222
222
  * @public exported from `@promptbook/core`
223
223
  */
224
224
  var DEFAULT_TASK_TITLE = "Task";
225
+ /**
226
+ * When the pipeline is flat and no name of return parameter is provided, this name is used
227
+ *
228
+ * @public exported from `@promptbook/core`
229
+ */
230
+ var DEFAULT_BOOK_OUTPUT_PARAMETER_NAME = 'result';
231
+ /**
232
+ * Maximum file size limit
233
+ *
234
+ * @public exported from `@promptbook/core`
235
+ */
236
+ var DEFAULT_MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
225
237
  // <- TODO: [🧠] Better system for generator warnings - not always "code" and "by `@promptbook/cli`"
226
238
  /**
227
239
  * The maximum number of iterations for a loops
@@ -280,6 +292,15 @@
280
292
  * @public exported from `@promptbook/core`
281
293
  */
282
294
  var DEFAULT_MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
295
+ // <- TODO: [🕝] Make also `BOOKS_DIRNAME_ALTERNATIVES`
296
+ /**
297
+ * Where to store the temporary downloads
298
+ *
299
+ * Note: When the folder does not exist, it is created recursively
300
+ *
301
+ * @public exported from `@promptbook/core`
302
+ */
303
+ var DEFAULT_DOWNLOAD_CACHE_DIRNAME = './.promptbook/download-cache';
283
304
  /**
284
305
  * Where to store the scrape cache
285
306
  *
@@ -335,22 +356,94 @@
335
356
  var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.book.md",formfactorName:"GENERIC",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Knowledge from Markdown\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.book.md`\n- INPUT PARAMETER `{knowledgeContent}` Markdown document content\n- OUTPUT PARAMETER `{knowledgePieces}` The knowledge JSON object\n\n## Knowledge\n\n<!-- TODO: [🍆] -FORMAT JSON -->\n\n```markdown\nYou are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {knowledgeContent}\n```\n\n`-> {knowledgePieces}`\n"}],sourceFile:"./books/prepare-knowledge-from-markdown.book.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.book.md",formfactorName:"GENERIC",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Keywords\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-keywords.book.md`\n- INPUT PARAMETER `{knowledgePieceContent}` The content\n- OUTPUT PARAMETER `{keywords}` Keywords separated by comma\n\n## Knowledge\n\n<!-- TODO: [🍆] -FORMAT JSON -->\n\n```markdown\nYou are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}\n```\n\n`-> {keywords}`\n"}],sourceFile:"./books/prepare-knowledge-keywords.book.md"},{title:"Prepare Knowledge-piece Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.book.md",formfactorName:"GENERIC",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Knowledge-piece Title\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-title.book.md`\n- INPUT PARAMETER `{knowledgePieceContent}` The content\n- OUTPUT PARAMETER `{title}` The title of the document\n\n## Knowledge\n\n- EXPECT MIN 1 WORD\n- EXPECT MAX 8 WORDS\n\n```markdown\nYou are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}\n```\n\n`-> {title}`\n"}],sourceFile:"./books/prepare-knowledge-title.book.md"},{title:"Prepare Persona",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.book.md",formfactorName:"GENERIC",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Example\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Persona\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-persona.book.md`\n- INPUT PARAMETER `{availableModelNames}` List of available model names separated by comma (,)\n- INPUT PARAMETER `{personaDescription}` Description of the persona\n- OUTPUT PARAMETER `{modelRequirements}` Specific requirements for the model\n\n## Make modelRequirements\n\n- FORMAT JSON\n\n```markdown\nYou are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Example\n\n\\`\\`\\`json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n\\`\\`\\`\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}\n```\n\n`-> {modelRequirements}`\n"}],sourceFile:"./books/prepare-persona.book.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-title.book.md",formfactorName:"GENERIC",parameters:[{name:"book",description:"The book to prepare the title for",isInput:true,isOutput:false},{name:"title",description:"Best title for the book",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"make-title",title:"Make title",content:"Make best title for given text which describes the workflow:\n\n## Rules\n\n- Write just title, nothing else\n- Title should be concise and clear - Write maximum ideally 2 words, maximum 5 words\n- Title starts with emoticon\n- Title should not mention the input and output of the workflow but the main purpose of the workflow\n _For example, not \"✍ Convert Knowledge-piece to title\" but \"✍ Title\"_\n\n## The workflow\n\n> {book}",resultingParameterName:"title",expectations:{words:{min:1,max:8},lines:{min:1,max:1}},dependentParameterNames:["book"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Title\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-title.book.md`\n- INPUT PARAMETER `{book}` The book to prepare the title for\n- OUTPUT PARAMETER `{title}` Best title for the book\n\n## Make title\n\n- EXPECT MIN 1 Word\n- EXPECT MAX 8 Words\n- EXPECT EXACTLY 1 Line\n\n```markdown\nMake best title for given text which describes the workflow:\n\n## Rules\n\n- Write just title, nothing else\n- Title should be concise and clear - Write maximum ideally 2 words, maximum 5 words\n- Title starts with emoticon\n- Title should not mention the input and output of the workflow but the main purpose of the workflow\n _For example, not \"✍ Convert Knowledge-piece to title\" but \"✍ Title\"_\n\n## The workflow\n\n> {book}\n```\n\n`-> {title}`\n"}],sourceFile:"./books/prepare-title.book.md"}];
336
357
 
337
358
  /**
338
- * Function isValidJsonString will tell you if the string is valid JSON or not
359
+ * Checks if value is valid email
339
360
  *
340
361
  * @public exported from `@promptbook/utils`
341
362
  */
342
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
343
- try {
344
- JSON.parse(value);
363
+ function isValidEmail(email) {
364
+ if (typeof email !== 'string') {
365
+ return false;
366
+ }
367
+ if (email.split('\n').length > 1) {
368
+ return false;
369
+ }
370
+ return /^.+@.+\..+$/.test(email);
371
+ }
372
+
373
+ /**
374
+ * Tests if given string is valid URL.
375
+ *
376
+ * Note: This does not check if the file exists only if the path is valid
377
+ * @public exported from `@promptbook/utils`
378
+ */
379
+ function isValidFilePath(filename) {
380
+ if (typeof filename !== 'string') {
381
+ return false;
382
+ }
383
+ if (filename.split('\n').length > 1) {
384
+ return false;
385
+ }
386
+ if (filename.split(' ').length >
387
+ 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
388
+ return false;
389
+ }
390
+ var filenameSlashes = filename.split('\\').join('/');
391
+ // Absolute Unix path: /hello.txt
392
+ if (/^(\/)/i.test(filenameSlashes)) {
393
+ // console.log(filename, 'Absolute Unix path: /hello.txt');
345
394
  return true;
346
395
  }
347
- catch (error) {
348
- if (!(error instanceof Error)) {
349
- throw error;
396
+ // Absolute Windows path: /hello.txt
397
+ if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
398
+ // console.log(filename, 'Absolute Windows path: /hello.txt');
399
+ return true;
400
+ }
401
+ // Relative path: ./hello.txt
402
+ if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
403
+ // console.log(filename, 'Relative path: ./hello.txt');
404
+ return true;
405
+ }
406
+ // Allow paths like foo/hello
407
+ if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
408
+ // console.log(filename, 'Allow paths like foo/hello');
409
+ return true;
410
+ }
411
+ // Allow paths like hello.book
412
+ if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
413
+ // console.log(filename, 'Allow paths like hello.book');
414
+ return true;
415
+ }
416
+ return false;
417
+ }
418
+ /**
419
+ * TODO: [🍏] Implement for MacOs
420
+ */
421
+
422
+ /**
423
+ * Tests if given string is valid URL.
424
+ *
425
+ * Note: Dataurl are considered perfectly valid.
426
+ * Note: There are two simmilar functions:
427
+ * - `isValidUrl` which tests any URL
428
+ * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
429
+ *
430
+ * @public exported from `@promptbook/utils`
431
+ */
432
+ function isValidUrl(url) {
433
+ if (typeof url !== 'string') {
434
+ return false;
435
+ }
436
+ try {
437
+ if (url.startsWith('blob:')) {
438
+ url = url.replace(/^blob:/, '');
350
439
  }
351
- if (error.message.includes('Unexpected token')) {
440
+ var urlObject = new URL(url /* because fail is handled */);
441
+ if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
352
442
  return false;
353
443
  }
444
+ return true;
445
+ }
446
+ catch (error) {
354
447
  return false;
355
448
  }
356
449
  }
@@ -374,6 +467,27 @@
374
467
  * TODO: Maybe split `ParseError` and `ApplyError`
375
468
  */
376
469
 
470
+ /**
471
+ * Function isValidJsonString will tell you if the string is valid JSON or not
472
+ *
473
+ * @public exported from `@promptbook/utils`
474
+ */
475
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
476
+ try {
477
+ JSON.parse(value);
478
+ return true;
479
+ }
480
+ catch (error) {
481
+ if (!(error instanceof Error)) {
482
+ throw error;
483
+ }
484
+ if (error.message.includes('Unexpected token')) {
485
+ return false;
486
+ }
487
+ return false;
488
+ }
489
+ }
490
+
377
491
  /**
378
492
  * Function `validatePipelineString` will validate the if the string is a valid pipeline string
379
493
  * It does not check if the string is fully logically correct, but if it is a string that can be a pipeline string or the string looks completely different.
@@ -387,6 +501,15 @@
387
501
  if (isValidJsonString(pipelineString)) {
388
502
  throw new ParseError('Expected a book, but got a JSON string');
389
503
  }
504
+ else if (isValidUrl(pipelineString)) {
505
+ throw new ParseError("Expected a book, but got just the URL \"".concat(pipelineString, "\""));
506
+ }
507
+ else if (isValidFilePath(pipelineString)) {
508
+ throw new ParseError("Expected a book, but got just the file path \"".concat(pipelineString, "\""));
509
+ }
510
+ else if (isValidEmail(pipelineString)) {
511
+ throw new ParseError("Expected a book, but got just the email \"".concat(pipelineString, "\""));
512
+ }
390
513
  // <- TODO: Implement the validation + add tests when the pipeline logic considered as invalid
391
514
  return pipelineString;
392
515
  }
@@ -1080,35 +1203,6 @@
1080
1203
  return isHostnameOnPrivateNetwork(url.hostname);
1081
1204
  }
1082
1205
 
1083
- /**
1084
- * Tests if given string is valid URL.
1085
- *
1086
- * Note: Dataurl are considered perfectly valid.
1087
- * Note: There are two simmilar functions:
1088
- * - `isValidUrl` which tests any URL
1089
- * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
1090
- *
1091
- * @public exported from `@promptbook/utils`
1092
- */
1093
- function isValidUrl(url) {
1094
- if (typeof url !== 'string') {
1095
- return false;
1096
- }
1097
- try {
1098
- if (url.startsWith('blob:')) {
1099
- url = url.replace(/^blob:/, '');
1100
- }
1101
- var urlObject = new URL(url /* because fail is handled */);
1102
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
1103
- return false;
1104
- }
1105
- return true;
1106
- }
1107
- catch (error) {
1108
- return false;
1109
- }
1110
- }
1111
-
1112
1206
  /**
1113
1207
  * Tests if given string is valid pipeline URL URL.
1114
1208
  *
@@ -1634,6 +1728,58 @@
1634
1728
  return MissingToolsError;
1635
1729
  }(Error));
1636
1730
 
1731
+ /**
1732
+ * Determine if the pipeline is fully prepared
1733
+ *
1734
+ * @see https://github.com/webgptorg/promptbook/discussions/196
1735
+ *
1736
+ * @public exported from `@promptbook/core`
1737
+ */
1738
+ function isPipelinePrepared(pipeline) {
1739
+ // Note: Ignoring `pipeline.preparations` @@@
1740
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
1741
+ if (pipeline.title === undefined || pipeline.title === '' || pipeline.title === DEFAULT_BOOK_TITLE) {
1742
+ return false;
1743
+ }
1744
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
1745
+ return false;
1746
+ }
1747
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
1748
+ return false;
1749
+ }
1750
+ /*
1751
+ TODO: [🧠][🍫] `tasks` can not be determined if they are fully prepared SO ignoring them
1752
+ > if (!pipeline.tasks.every(({ preparedContent }) => preparedContent === undefined)) {
1753
+ > return false;
1754
+ > }
1755
+ */
1756
+ return true;
1757
+ }
1758
+ /**
1759
+ * TODO: [🔃][main] If the pipeline was prepared with different version or different set of models, prepare it once again
1760
+ * TODO: [🐠] Maybe base this on `makeValidator`
1761
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
1762
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
1763
+ * - [🏍] ? Is context in each task
1764
+ * - [♨] Are examples prepared
1765
+ * - [♨] Are tasks prepared
1766
+ */
1767
+
1768
+ /**
1769
+ * Generates random token
1770
+ *
1771
+ * Note: This function is cryptographically secure (it uses crypto.randomBytes internally)
1772
+ *
1773
+ * @private internal helper function
1774
+ * @returns secure random token
1775
+ */
1776
+ function $randomToken(randomness) {
1777
+ return crypto.randomBytes(randomness).toString('hex');
1778
+ }
1779
+ /**
1780
+ * TODO: Maybe use nanoid instead https://github.com/ai/nanoid
1781
+ */
1782
+
1637
1783
  /**
1638
1784
  * This error indicates errors during the execution of the pipeline
1639
1785
  *
@@ -1863,12 +2009,28 @@
1863
2009
  /**
1864
2010
  * Asserts that the execution of a Promptbook is successful
1865
2011
  *
2012
+ * Note: If there are only warnings, the execution is still successful but the warnings are logged in the console
2013
+ *
1866
2014
  * @param executionResult - The partial result of the Promptbook execution
1867
2015
  * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
1868
- * @public exported from `@promptbook/core`
2016
+ * @private internal helper function of `asPromise` method of `ExecutionTask`
1869
2017
  */
1870
- function assertsExecutionSuccessful(executionResult) {
1871
- var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
2018
+ function assertsTaskSuccessful(executionResult) {
2019
+ var e_1, _a;
2020
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors, warnings = executionResult.warnings;
2021
+ try {
2022
+ for (var warnings_1 = __values(warnings), warnings_1_1 = warnings_1.next(); !warnings_1_1.done; warnings_1_1 = warnings_1.next()) {
2023
+ var warning = warnings_1_1.value;
2024
+ console.warn(warning.message);
2025
+ }
2026
+ }
2027
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2028
+ finally {
2029
+ try {
2030
+ if (warnings_1_1 && !warnings_1_1.done && (_a = warnings_1.return)) _a.call(warnings_1);
2031
+ }
2032
+ finally { if (e_1) throw e_1.error; }
2033
+ }
1872
2034
  if (isSuccessful === true) {
1873
2035
  return;
1874
2036
  }
@@ -1888,46 +2050,71 @@
1888
2050
  }
1889
2051
  }
1890
2052
  /**
1891
- * TODO: [🐚] This function should be removed OR changed OR be completely rewritten
1892
2053
  * TODO: [🧠] Can this return type be better typed than void
1893
2054
  */
1894
2055
 
1895
2056
  /**
1896
- * Determine if the pipeline is fully prepared
1897
- *
1898
- * @see https://github.com/webgptorg/promptbook/discussions/196
2057
+ * Helper to create a new task
1899
2058
  *
1900
- * @public exported from `@promptbook/core`
2059
+ * @private internal helper function
1901
2060
  */
1902
- function isPipelinePrepared(pipeline) {
1903
- // Note: Ignoring `pipeline.preparations` @@@
1904
- // Note: Ignoring `pipeline.knowledgePieces` @@@
1905
- if (pipeline.title === undefined || pipeline.title === '' || pipeline.title === DEFAULT_BOOK_TITLE) {
1906
- return false;
1907
- }
1908
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
1909
- return false;
1910
- }
1911
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
1912
- return false;
2061
+ function createTask(options) {
2062
+ var taskType = options.taskType, taskProcessCallback = options.taskProcessCallback;
2063
+ var taskId = "".concat(taskType.toLowerCase(), "-").concat($randomToken(256 /* <- TODO: !!! To global config */));
2064
+ var resultSubject = new rxjs.BehaviorSubject({});
2065
+ var finalResultPromise = /* not await */ taskProcessCallback(function (newOngoingResult) {
2066
+ resultSubject.next(newOngoingResult);
2067
+ });
2068
+ function asPromise(options) {
2069
+ return __awaiter(this, void 0, void 0, function () {
2070
+ var _a, isCrashedOnError, finalResult;
2071
+ return __generator(this, function (_b) {
2072
+ switch (_b.label) {
2073
+ case 0:
2074
+ _a = (options || {}).isCrashedOnError, isCrashedOnError = _a === void 0 ? true : _a;
2075
+ return [4 /*yield*/, finalResultPromise];
2076
+ case 1:
2077
+ finalResult = _b.sent();
2078
+ if (isCrashedOnError) {
2079
+ assertsTaskSuccessful(finalResult);
2080
+ }
2081
+ return [2 /*return*/, finalResult];
2082
+ }
2083
+ });
2084
+ });
1913
2085
  }
1914
- /*
1915
- TODO: [🧠][🍫] `tasks` can not be determined if they are fully prepared SO ignoring them
1916
- > if (!pipeline.tasks.every(({ preparedContent }) => preparedContent === undefined)) {
1917
- > return false;
1918
- > }
1919
- */
1920
- return true;
2086
+ return {
2087
+ taskType: taskType,
2088
+ taskId: taskId,
2089
+ asPromise: asPromise,
2090
+ asObservable: function () {
2091
+ return rxjs.concat(resultSubject.asObservable(), rxjs.from(asPromise({
2092
+ isCrashedOnError: true,
2093
+ })));
2094
+ },
2095
+ };
1921
2096
  }
1922
2097
  /**
1923
- * TODO: [🔃][main] If the pipeline was prepared with different version or different set of models, prepare it once again
1924
- * TODO: [🐠] Maybe base this on `makeValidator`
1925
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
1926
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
1927
- * - [🏍] ? Is context in each task
1928
- * - [] Are examples prepared
1929
- * - [♨] Are tasks prepared
2098
+ * TODO: Maybe allow to terminate the task and add getter `isFinished` or `status`
2099
+ * TODO: [🐚] Split into more files and make `PrepareTask` & `RemoteTask` + split the function
2100
+ */
2101
+
2102
+ /**
2103
+ * Serializes an error into a [🚉] JSON-serializable object
2104
+ *
2105
+ * @public exported from `@promptbook/utils`
1930
2106
  */
2107
+ function serializeError(error) {
2108
+ var name = error.name, message = error.message, stack = error.stack;
2109
+ if (!Object.keys(ALL_ERRORS).includes(name)) {
2110
+ console.error(spaceTrim__default["default"](function (block) { return "\n \n Cannot serialize error with name \"".concat(name, "\"\n\n ").concat(block(stack || message), "\n \n "); }));
2111
+ }
2112
+ return {
2113
+ name: name,
2114
+ message: message,
2115
+ stack: stack,
2116
+ };
2117
+ }
1931
2118
 
1932
2119
  /**
1933
2120
  * Format either small or big number
@@ -2004,23 +2191,6 @@
2004
2191
  }
2005
2192
  }
2006
2193
 
2007
- /**
2008
- * Serializes an error into a [🚉] JSON-serializable object
2009
- *
2010
- * @public exported from `@promptbook/utils`
2011
- */
2012
- function serializeError(error) {
2013
- var name = error.name, message = error.message, stack = error.stack;
2014
- if (!Object.keys(ALL_ERRORS).includes(name)) {
2015
- console.error(spaceTrim__default["default"](function (block) { return "\n \n Cannot serialize error with name \"".concat(name, "\"\n\n ").concat(block(stack || message), "\n \n "); }));
2016
- }
2017
- return {
2018
- name: name,
2019
- message: message,
2020
- stack: stack,
2021
- };
2022
- }
2023
-
2024
2194
  /**
2025
2195
  * Represents the usage with no resources consumed
2026
2196
  *
@@ -2878,7 +3048,7 @@
2878
3048
  if (!(error_1 instanceof Error) || error_1 instanceof UnexpectedError) {
2879
3049
  throw error_1;
2880
3050
  }
2881
- errors.push(error_1);
3051
+ errors.push({ llmExecutionTools: llmExecutionTools, error: error_1 });
2882
3052
  return [3 /*break*/, 13];
2883
3053
  case 13:
2884
3054
  _b = _a.next();
@@ -2905,7 +3075,10 @@
2905
3075
  // 2) AnthropicClaude throw PipelineExecutionError: Parameter `{knowledge}` is not defined
2906
3076
  // 3) ...
2907
3077
  spaceTrim__default["default"](function (block) { return "\n All execution tools failed:\n\n ".concat(block(errors
2908
- .map(function (error, i) { return "".concat(i + 1, ") **").concat(error.name || 'Error', ":** ").concat(error.message); })
3078
+ .map(function (_a, i) {
3079
+ var error = _a.error, llmExecutionTools = _a.llmExecutionTools;
3080
+ return "".concat(i + 1, ") **").concat(llmExecutionTools.title, "** thrown **").concat(error.name || 'Error', ":** ").concat(error.message);
3081
+ })
2909
3082
  .join('\n')), "\n\n "); }));
2910
3083
  }
2911
3084
  else if (this.llmExecutionTools.length === 0) {
@@ -4165,27 +4338,20 @@
4165
4338
  */
4166
4339
  function executeTask(options) {
4167
4340
  return __awaiter(this, void 0, void 0, function () {
4168
- var currentTask, preparedPipeline, parametersToPass, tools, onProgress, $executionReport, pipelineIdentification, maxExecutionAttempts, maxParallelCount, csvSettings, isVerbose, rootDirname, cacheDirname, intermediateFilesStrategy, isAutoInstalled, isNotPreparedWarningSupressed, name, title, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_1, _d, _e, parameterName, maxAttempts, jokerParameterNames, preparedContent, resultString;
4169
- var e_1, _f, _g;
4170
- return __generator(this, function (_h) {
4171
- switch (_h.label) {
4341
+ var currentTask, preparedPipeline, parametersToPass, tools, onProgress, $executionReport, pipelineIdentification, maxExecutionAttempts, maxParallelCount, csvSettings, isVerbose, rootDirname, cacheDirname, intermediateFilesStrategy, isAutoInstalled, isNotPreparedWarningSupressed, priority, usedParameterNames, dependentParameterNames, definedParameters, _a, _b, _c, definedParameterNames, parameters, _loop_1, _d, _e, parameterName, maxAttempts, jokerParameterNames, preparedContent, resultString;
4342
+ var _f, e_1, _g, _h, _j;
4343
+ return __generator(this, function (_k) {
4344
+ switch (_k.label) {
4172
4345
  case 0:
4173
4346
  currentTask = options.currentTask, preparedPipeline = options.preparedPipeline, parametersToPass = options.parametersToPass, tools = options.tools, onProgress = options.onProgress, $executionReport = options.$executionReport, pipelineIdentification = options.pipelineIdentification, maxExecutionAttempts = options.maxExecutionAttempts, maxParallelCount = options.maxParallelCount, csvSettings = options.csvSettings, isVerbose = options.isVerbose, rootDirname = options.rootDirname, cacheDirname = options.cacheDirname, intermediateFilesStrategy = options.intermediateFilesStrategy, isAutoInstalled = options.isAutoInstalled, isNotPreparedWarningSupressed = options.isNotPreparedWarningSupressed;
4174
- name = "pipeline-executor-frame-".concat(currentTask.name);
4175
- title = currentTask.title;
4176
4347
  priority = preparedPipeline.tasks.length - preparedPipeline.tasks.indexOf(currentTask);
4177
4348
  return [4 /*yield*/, onProgress({
4178
- name: name,
4179
- title: title,
4180
- isStarted: false,
4181
- isDone: false,
4182
- taskType: currentTask.taskType,
4183
- parameterName: currentTask.resultingParameterName,
4184
- parameterValue: null,
4185
- // <- [🍸]
4349
+ outputParameters: (_f = {},
4350
+ _f[currentTask.resultingParameterName] = '',
4351
+ _f),
4186
4352
  })];
4187
4353
  case 1:
4188
- _h.sent();
4354
+ _k.sent();
4189
4355
  usedParameterNames = extractParameterNamesFromTask(currentTask);
4190
4356
  dependentParameterNames = new Set(currentTask.dependentParameterNames);
4191
4357
  // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
@@ -4204,7 +4370,7 @@
4204
4370
  pipelineIdentification: pipelineIdentification,
4205
4371
  })];
4206
4372
  case 2:
4207
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
4373
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_k.sent())])), parametersToPass])]);
4208
4374
  definedParameterNames = new Set(Object.keys(definedParameters));
4209
4375
  parameters = {};
4210
4376
  _loop_1 = function (parameterName) {
@@ -4232,7 +4398,7 @@
4232
4398
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
4233
4399
  finally {
4234
4400
  try {
4235
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
4401
+ if (_e && !_e.done && (_g = _d.return)) _g.call(_d);
4236
4402
  }
4237
4403
  finally { if (e_1) throw e_1.error; }
4238
4404
  }
@@ -4263,24 +4429,19 @@
4263
4429
  isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
4264
4430
  })];
4265
4431
  case 3:
4266
- resultString = _h.sent();
4432
+ resultString = _k.sent();
4267
4433
  return [4 /*yield*/, onProgress({
4268
- name: name,
4269
- title: title,
4270
- isStarted: true,
4271
- isDone: true,
4272
- taskType: currentTask.taskType,
4273
- parameterName: currentTask.resultingParameterName,
4274
- parameterValue: resultString,
4275
- // <- [🍸]
4434
+ outputParameters: (_h = {},
4435
+ _h[currentTask.resultingParameterName] = resultString,
4436
+ _h),
4276
4437
  })];
4277
4438
  case 4:
4278
- _h.sent();
4279
- return [2 /*return*/, Object.freeze((_g = {},
4280
- _g[currentTask.resultingParameterName] =
4439
+ _k.sent();
4440
+ return [2 /*return*/, Object.freeze((_j = {},
4441
+ _j[currentTask.resultingParameterName] =
4281
4442
  // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
4282
4443
  resultString,
4283
- _g))];
4444
+ _j))];
4284
4445
  }
4285
4446
  });
4286
4447
  });
@@ -4288,9 +4449,6 @@
4288
4449
  /**
4289
4450
  * TODO: [🤹‍♂️]
4290
4451
  */
4291
- /**
4292
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
4293
- */
4294
4452
 
4295
4453
  /**
4296
4454
  * @@@
@@ -4552,15 +4710,15 @@
4552
4710
  return [3 /*break*/, 4];
4553
4711
  case 3:
4554
4712
  unresovedTasks_1 = unresovedTasks_1.filter(function (task) { return task !== currentTask; });
4555
- work_1 = executeTask(__assign(__assign({}, options), { currentTask: currentTask, preparedPipeline: preparedPipeline, parametersToPass: parametersToPass, tools: tools, onProgress: function (progress) {
4713
+ work_1 = executeTask(__assign(__assign({}, options), { currentTask: currentTask, preparedPipeline: preparedPipeline, parametersToPass: parametersToPass, tools: tools, onProgress: function (newOngoingResult) {
4556
4714
  if (isReturned) {
4557
- throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(progress, null, 4)
4715
+ throw new UnexpectedError(spaceTrim.spaceTrim(function (block) { return "\n Can not call `onProgress` after pipeline execution is finished\n\n ".concat(block(pipelineIdentification), "\n\n ").concat(block(JSON.stringify(newOngoingResult, null, 4)
4558
4716
  .split('\n')
4559
4717
  .map(function (line) { return "> ".concat(line); })
4560
4718
  .join('\n')), "\n "); }));
4561
4719
  }
4562
4720
  if (onProgress) {
4563
- onProgress(progress);
4721
+ onProgress(newOngoingResult);
4564
4722
  }
4565
4723
  }, $executionReport: executionReport, pipelineIdentification: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Task name: ").concat(currentTask.name, "\n Task title: ").concat(currentTask.title, "\n "); }) }))
4566
4724
  .then(function (newParametersToPass) {
@@ -4663,9 +4821,6 @@
4663
4821
  });
4664
4822
  });
4665
4823
  }
4666
- /**
4667
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
4668
- */
4669
4824
 
4670
4825
  /**
4671
4826
  * Creates executor function from pipeline and execution tools.
@@ -4697,7 +4852,7 @@
4697
4852
  console.warn(spaceTrim.spaceTrim(function (block) { return "\n Pipeline is not prepared\n\n ".concat(block(pipelineIdentification), "\n\n It will be prepared ad-hoc before the first execution and **returned as `preparedPipeline` in `PipelineExecutorResult`**\n But it is recommended to prepare the pipeline during collection preparation\n\n @see more at https://ptbk.io/prepare-pipeline\n "); }));
4698
4853
  }
4699
4854
  var runCount = 0;
4700
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4855
+ var pipelineExecutorWithCallback = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
4701
4856
  return __generator(this, function (_a) {
4702
4857
  runCount++;
4703
4858
  return [2 /*return*/, /* not await */ executePipeline({
@@ -4722,11 +4877,23 @@
4722
4877
  })];
4723
4878
  });
4724
4879
  }); };
4880
+ var pipelineExecutor = function (inputParameters) {
4881
+ return createTask({
4882
+ taskType: 'EXECUTION',
4883
+ taskProcessCallback: function (updateOngoingResult) {
4884
+ var _this = this;
4885
+ return pipelineExecutorWithCallback(inputParameters, function (newOngoingResult) { return __awaiter(_this, void 0, void 0, function () {
4886
+ return __generator(this, function (_a) {
4887
+ updateOngoingResult(newOngoingResult);
4888
+ return [2 /*return*/];
4889
+ });
4890
+ }); });
4891
+ },
4892
+ });
4893
+ };
4894
+ // <- TODO: Make types such as there is no need to do `as` for `createTask`
4725
4895
  return pipelineExecutor;
4726
4896
  }
4727
- /**
4728
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
4729
- */
4730
4897
 
4731
4898
  /**
4732
4899
  * Async version of Array.forEach
@@ -4931,10 +5098,9 @@
4931
5098
  return modelName;
4932
5099
  })
4933
5100
  .join(',');
4934
- return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription })];
5101
+ return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription }).asPromise()];
4935
5102
  case 3:
4936
5103
  result = _d.sent();
4937
- assertsExecutionSuccessful(result);
4938
5104
  outputParameters = result.outputParameters;
4939
5105
  modelRequirementsRaw = outputParameters.modelRequirements;
4940
5106
  modelRequirements = JSON.parse(modelRequirementsRaw);
@@ -5325,6 +5491,15 @@
5325
5491
  * TODO: [🐱‍🐉][🧠] Make some smart crop NOT source-i-m-pavol-a-develop-... BUT source-i-m-pavol-a-developer-...
5326
5492
  */
5327
5493
 
5494
+ /**
5495
+ * @@@
5496
+ *
5497
+ * @private for `FileCacheStorage`
5498
+ */
5499
+ function nameToSubfolderPath(name) {
5500
+ return [name.substr(0, 1).toLowerCase(), name.substr(1, 1).toLowerCase()];
5501
+ }
5502
+
5328
5503
  /**
5329
5504
  * Convert file extension to mime type
5330
5505
  *
@@ -5381,53 +5556,55 @@
5381
5556
  */
5382
5557
 
5383
5558
  /**
5384
- * Tests if given string is valid URL.
5559
+ * Convert mime type to file extension
5385
5560
  *
5386
- * Note: This does not check if the file exists only if the path is valid
5561
+ * Note: If the mime type is invalid, `null` is returned
5562
+ *
5563
+ * @private within the repository
5564
+ */
5565
+ function mimeTypeToExtension(value) {
5566
+ return mimeTypes.extension(value) || null;
5567
+ }
5568
+
5569
+ /**
5570
+ * Removes emojis from a string and fix whitespaces
5571
+ *
5572
+ * @param text with emojis
5573
+ * @returns text without emojis
5387
5574
  * @public exported from `@promptbook/utils`
5388
5575
  */
5389
- function isValidFilePath(filename) {
5390
- if (typeof filename !== 'string') {
5391
- return false;
5392
- }
5393
- if (filename.split('\n').length > 1) {
5394
- return false;
5395
- }
5396
- if (filename.split(' ').length >
5397
- 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
5398
- return false;
5399
- }
5400
- var filenameSlashes = filename.split('\\').join('/');
5401
- // Absolute Unix path: /hello.txt
5402
- if (/^(\/)/i.test(filenameSlashes)) {
5403
- // console.log(filename, 'Absolute Unix path: /hello.txt');
5404
- return true;
5405
- }
5406
- // Absolute Windows path: /hello.txt
5407
- if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
5408
- // console.log(filename, 'Absolute Windows path: /hello.txt');
5409
- return true;
5410
- }
5411
- // Relative path: ./hello.txt
5412
- if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
5413
- // console.log(filename, 'Relative path: ./hello.txt');
5414
- return true;
5415
- }
5416
- // Allow paths like foo/hello
5417
- if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
5418
- // console.log(filename, 'Allow paths like foo/hello');
5419
- return true;
5576
+ function removeEmojis(text) {
5577
+ // Replace emojis (and also ZWJ sequence) with hyphens
5578
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
5579
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
5580
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
5581
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
5582
+ return text;
5583
+ }
5584
+
5585
+ /**
5586
+ * @@@
5587
+ *
5588
+ * @param value @@@
5589
+ * @returns @@@
5590
+ * @example @@@
5591
+ * @public exported from `@promptbook/utils`
5592
+ */
5593
+ function titleToName(value) {
5594
+ if (isValidUrl(value)) {
5595
+ value = value.replace(/^https?:\/\//, '');
5596
+ value = value.replace(/\.html$/, '');
5420
5597
  }
5421
- // Allow paths like hello.book
5422
- if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
5423
- // console.log(filename, 'Allow paths like hello.book');
5424
- return true;
5598
+ else if (isValidFilePath(value)) {
5599
+ value = path.basename(value);
5600
+ // Note: Keeping extension in the name
5425
5601
  }
5426
- return false;
5602
+ value = value.split('/').join('-');
5603
+ value = removeEmojis(value);
5604
+ value = normalizeToKebabCase(value);
5605
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
5606
+ return value;
5427
5607
  }
5428
- /**
5429
- * TODO: [🍏] Implement for MacOs
5430
- */
5431
5608
 
5432
5609
  /**
5433
5610
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
@@ -5464,9 +5641,9 @@
5464
5641
  function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
5465
5642
  var _a;
5466
5643
  return __awaiter(this, void 0, void 0, function () {
5467
- var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, filename_1, fileExtension, mimeType;
5468
- return __generator(this, function (_f) {
5469
- switch (_f.label) {
5644
+ var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, basename, hash, rootDirname_1, filepath, fileContent, _f, _g, filename_1, fileExtension, mimeType;
5645
+ return __generator(this, function (_h) {
5646
+ switch (_h.label) {
5470
5647
  case 0:
5471
5648
  _b = tools.fetch, fetch = _b === void 0 ? scraperFetch : _b;
5472
5649
  knowledgeSourceContent = knowledgeSource.knowledgeSourceContent;
@@ -5475,54 +5652,76 @@
5475
5652
  if (!name) {
5476
5653
  name = knowledgeSourceContentToName(knowledgeSourceContent);
5477
5654
  }
5478
- if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 2];
5655
+ if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 5];
5479
5656
  url = knowledgeSourceContent;
5480
5657
  return [4 /*yield*/, fetch(url)];
5481
5658
  case 1:
5482
- response_1 = _f.sent();
5659
+ response_1 = _h.sent();
5483
5660
  mimeType = ((_a = response_1.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
5484
- return [2 /*return*/, {
5485
- source: name,
5486
- filename: null,
5487
- url: url,
5488
- mimeType: mimeType,
5489
- /*
5490
- TODO: [🥽]
5491
- > async asBlob() {
5492
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
5493
- > const content = await response.blob();
5494
- > return content;
5495
- > },
5496
- */
5497
- asJson: function () {
5498
- return __awaiter(this, void 0, void 0, function () {
5499
- var content;
5500
- return __generator(this, function (_a) {
5501
- switch (_a.label) {
5502
- case 0: return [4 /*yield*/, response_1.json()];
5503
- case 1:
5504
- content = _a.sent();
5505
- return [2 /*return*/, content];
5506
- }
5661
+ if (tools.fs === undefined || !url.endsWith('.pdf' /* <- TODO: [💵] */)) {
5662
+ return [2 /*return*/, {
5663
+ source: name,
5664
+ filename: null,
5665
+ url: url,
5666
+ mimeType: mimeType,
5667
+ /*
5668
+ TODO: [🥽]
5669
+ > async asBlob() {
5670
+ > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
5671
+ > const content = await response.blob();
5672
+ > return content;
5673
+ > },
5674
+ */
5675
+ asJson: function () {
5676
+ return __awaiter(this, void 0, void 0, function () {
5677
+ var content;
5678
+ return __generator(this, function (_a) {
5679
+ switch (_a.label) {
5680
+ case 0: return [4 /*yield*/, response_1.json()];
5681
+ case 1:
5682
+ content = _a.sent();
5683
+ return [2 /*return*/, content];
5684
+ }
5685
+ });
5507
5686
  });
5508
- });
5509
- },
5510
- asText: function () {
5511
- return __awaiter(this, void 0, void 0, function () {
5512
- var content;
5513
- return __generator(this, function (_a) {
5514
- switch (_a.label) {
5515
- case 0: return [4 /*yield*/, response_1.text()];
5516
- case 1:
5517
- content = _a.sent();
5518
- return [2 /*return*/, content];
5519
- }
5687
+ },
5688
+ asText: function () {
5689
+ return __awaiter(this, void 0, void 0, function () {
5690
+ var content;
5691
+ return __generator(this, function (_a) {
5692
+ switch (_a.label) {
5693
+ case 0: return [4 /*yield*/, response_1.text()];
5694
+ case 1:
5695
+ content = _a.sent();
5696
+ return [2 /*return*/, content];
5697
+ }
5698
+ });
5520
5699
  });
5521
- });
5522
- },
5523
- }];
5700
+ },
5701
+ }];
5702
+ }
5703
+ basename = url.split('/').pop() || titleToName(url);
5704
+ hash = sha256__default["default"](hexEncoder__default["default"].parse(url)).toString( /* hex */);
5705
+ rootDirname_1 = path.join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
5706
+ filepath = path.join.apply(void 0, __spreadArray(__spreadArray([], __read(nameToSubfolderPath(hash /* <- TODO: [🎎] Maybe add some SHA256 prefix */)), false), ["".concat(basename.substring(0, MAX_FILENAME_LENGTH), ".").concat(mimeTypeToExtension(mimeType))], false));
5707
+ return [4 /*yield*/, tools.fs.mkdir(path.dirname(path.join(rootDirname_1, filepath)), { recursive: true })];
5524
5708
  case 2:
5525
- if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 4];
5709
+ _h.sent();
5710
+ _g = (_f = Buffer).from;
5711
+ return [4 /*yield*/, response_1.arrayBuffer()];
5712
+ case 3:
5713
+ fileContent = _g.apply(_f, [_h.sent()]);
5714
+ if (fileContent.length > DEFAULT_MAX_FILE_SIZE /* <- TODO: Allow to pass different value to remote server */) {
5715
+ throw new LimitReachedError("File is too large (".concat(Math.round(fileContent.length / 1024 / 1024), "MB). Maximum allowed size is ").concat(Math.round(DEFAULT_MAX_FILE_SIZE / 1024 / 1024), "MB."));
5716
+ }
5717
+ return [4 /*yield*/, tools.fs.writeFile(path.join(rootDirname_1, filepath), fileContent)];
5718
+ case 4:
5719
+ _h.sent();
5720
+ // TODO: [💵] Check the file security
5721
+ // TODO: [🧹][🧠] Delete the file after the scraping is done
5722
+ return [2 /*return*/, makeKnowledgeSourceHandler({ name: name, knowledgeSourceContent: filepath }, tools, __assign(__assign({}, options), { rootDirname: rootDirname_1 }))];
5723
+ case 5:
5724
+ if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 7];
5526
5725
  if (tools.fs === undefined) {
5527
5726
  throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
5528
5727
  // <- TODO: [🧠] What is the best error type here`
@@ -5535,8 +5734,8 @@
5535
5734
  fileExtension = getFileExtension(filename_1);
5536
5735
  mimeType = extensionToMimeType(fileExtension || '');
5537
5736
  return [4 /*yield*/, isFileExisting(filename_1, tools.fs)];
5538
- case 3:
5539
- if (!(_f.sent())) {
5737
+ case 6:
5738
+ if (!(_h.sent())) {
5540
5739
  throw new NotFoundError(spaceTrim__default["default"](function (block) { return "\n Can not make source handler for file which does not exist:\n\n File:\n ".concat(block(knowledgeSourceContent), "\n\n Full file path:\n ").concat(block(filename_1), "\n "); }));
5541
5740
  }
5542
5741
  // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
@@ -5582,7 +5781,7 @@
5582
5781
  });
5583
5782
  },
5584
5783
  }];
5585
- case 4: return [2 /*return*/, {
5784
+ case 7: return [2 /*return*/, {
5586
5785
  source: name,
5587
5786
  filename: null,
5588
5787
  url: null,
@@ -5846,10 +6045,9 @@
5846
6045
  var content = _a.content;
5847
6046
  return content;
5848
6047
  }).join('\n\n'),
5849
- })];
6048
+ }).asPromise()];
5850
6049
  case 2:
5851
6050
  result = _e.sent();
5852
- assertsExecutionSuccessful(result);
5853
6051
  outputParameters = result.outputParameters;
5854
6052
  titleRaw = outputParameters.title;
5855
6053
  if (isVerbose) {
@@ -6693,22 +6891,6 @@
6693
6891
  * TODO: [🌺] Use some intermediate util splitWords
6694
6892
  */
6695
6893
 
6696
- /**
6697
- * Removes emojis from a string and fix whitespaces
6698
- *
6699
- * @param text with emojis
6700
- * @returns text without emojis
6701
- * @public exported from `@promptbook/utils`
6702
- */
6703
- function removeEmojis(text) {
6704
- // Replace emojis (and also ZWJ sequence) with hyphens
6705
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
6706
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
6707
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
6708
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
6709
- return text;
6710
- }
6711
-
6712
6894
  /**
6713
6895
  * Removes quotes from a string
6714
6896
  *
@@ -8568,7 +8750,10 @@
8568
8750
  description: 'Chatbot response',
8569
8751
  isInput: false,
8570
8752
  isOutput: true,
8571
- exampleValues: ['Hello, I am a Pavol`s virtual avatar. How can I help you?'],
8753
+ exampleValues: [
8754
+ 'Hello, how can I help you?',
8755
+ // <- TODO: [🧠] Make this dynamic, async, prepare-phase HLAs
8756
+ ],
8572
8757
  });
8573
8758
  // TODO: Use spaceTrim in multiline strings
8574
8759
  $pipelineJson.tasks.push({
@@ -8656,12 +8841,15 @@
8656
8841
  pipelineString = removeMarkdownComments(pipelineString);
8657
8842
  pipelineString = spaceTrim__default["default"](pipelineString);
8658
8843
  var isMarkdownBeginningWithHeadline = pipelineString.startsWith('# ');
8659
- var isLastLineReturnStatement = pipelineString.split('\n').pop().split('`').join('').startsWith('->');
8660
- // TODO: Also (double)check
8844
+ //const isLastLineReturnStatement = pipelineString.split('\n').pop()!.split('`').join('').startsWith('->');
8845
+ var isBacktickBlockUsed = pipelineString.includes('```');
8846
+ var isQuoteBlocksUsed = /^>\s+/m.test(pipelineString);
8847
+ var isBlocksUsed = isBacktickBlockUsed || isQuoteBlocksUsed;
8848
+ // TODO: [🧉] Also (double)check
8661
8849
  // > const usedCommands
8662
8850
  // > const isBlocksUsed
8663
8851
  // > const returnStatementCount
8664
- var isFlat = !isMarkdownBeginningWithHeadline && isLastLineReturnStatement;
8852
+ var isFlat = !isMarkdownBeginningWithHeadline && !isBlocksUsed; /* && isLastLineReturnStatement */
8665
8853
  return isFlat;
8666
8854
  }
8667
8855
 
@@ -8675,9 +8863,26 @@
8675
8863
  return pipelineString;
8676
8864
  }
8677
8865
  var pipelineStringLines = pipelineString.split('\n');
8678
- var returnStatement = pipelineStringLines.pop();
8866
+ var potentialReturnStatement = pipelineStringLines.pop();
8867
+ var returnStatement;
8868
+ if (/(-|=)>\s*\{.*\}/.test(potentialReturnStatement)) {
8869
+ // Note: Last line is return statement
8870
+ returnStatement = potentialReturnStatement;
8871
+ }
8872
+ else {
8873
+ // Note: Last line is not a return statement
8874
+ returnStatement = "-> {".concat(DEFAULT_BOOK_OUTPUT_PARAMETER_NAME, "}");
8875
+ pipelineStringLines.push(potentialReturnStatement);
8876
+ }
8679
8877
  var prompt = spaceTrim__default["default"](pipelineStringLines.join('\n'));
8680
- pipelineString = validatePipelineString(spaceTrim__default["default"](function (block) { return "\n # ".concat(DEFAULT_BOOK_TITLE, "\n\n ## Prompt\n\n ```\n ").concat(block(prompt), "\n ```\n\n ").concat(returnStatement, "\n "); }));
8878
+ var quotedPrompt;
8879
+ if (prompt.split('\n').length <= 1) {
8880
+ quotedPrompt = "> ".concat(prompt);
8881
+ }
8882
+ else {
8883
+ quotedPrompt = spaceTrim__default["default"](function (block) { return "\n ```\n ".concat(block(prompt.split('`').join('\\`')), "\n ```\n "); });
8884
+ }
8885
+ pipelineString = validatePipelineString(spaceTrim__default["default"](function (block) { return "\n # ".concat(DEFAULT_BOOK_TITLE, "\n\n ## Prompt\n\n ").concat(block(quotedPrompt), "\n\n ").concat(returnStatement, "\n "); }));
8681
8886
  // <- TODO: Maybe use book` notation
8682
8887
  return pipelineString;
8683
8888
  }
@@ -8900,30 +9105,6 @@
8900
9105
  * NOW we are working just with markdown string and its good enough
8901
9106
  */
8902
9107
 
8903
- /**
8904
- * @@@
8905
- *
8906
- * @param value @@@
8907
- * @returns @@@
8908
- * @example @@@
8909
- * @public exported from `@promptbook/utils`
8910
- */
8911
- function titleToName(value) {
8912
- if (isValidUrl(value)) {
8913
- value = value.replace(/^https?:\/\//, '');
8914
- value = value.replace(/\.html$/, '');
8915
- }
8916
- else if (isValidFilePath(value)) {
8917
- value = path.basename(value);
8918
- // Note: Keeping extension in the name
8919
- }
8920
- value = value.split('/').join('-');
8921
- value = removeEmojis(value);
8922
- value = normalizeToKebabCase(value);
8923
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
8924
- return value;
8925
- }
8926
-
8927
9108
  /**
8928
9109
  * Compile pipeline from string (markdown) format to JSON format synchronously
8929
9110
  *
@@ -9443,6 +9624,9 @@
9443
9624
  * @public exported from `@promptbook/utils`
9444
9625
  */
9445
9626
  var $isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
9627
+ /**
9628
+ * TODO: [🎺]
9629
+ */
9446
9630
 
9447
9631
  /**
9448
9632
  * Normalize options for `execCommand` and `execCommands`
@@ -9656,6 +9840,7 @@
9656
9840
  readFile: promises.readFile,
9657
9841
  writeFile: promises.writeFile,
9658
9842
  readdir: promises.readdir,
9843
+ mkdir: promises.mkdir,
9659
9844
  };
9660
9845
  }
9661
9846
  /**
@@ -9948,71 +10133,6 @@
9948
10133
  * TODO: [🍏] Make for MacOS paths
9949
10134
  */
9950
10135
 
9951
- /**
9952
- * @@@
9953
- *
9954
- * @@@ .env
9955
- *
9956
- * It looks for environment variables:
9957
- * - `process.env.OPENAI_API_KEY`
9958
- * - `process.env.ANTHROPIC_CLAUDE_API_KEY`
9959
- * - ...
9960
- *
9961
- * @returns @@@
9962
- * @public exported from `@promptbook/node`
9963
- */
9964
- function $provideLlmToolsConfigurationFromEnv() {
9965
- return __awaiter(this, void 0, void 0, function () {
9966
- var rootDirname, i, envFilename, llmToolsConfiguration;
9967
- return __generator(this, function (_a) {
9968
- switch (_a.label) {
9969
- case 0:
9970
- if (!$isRunningInNode()) {
9971
- throw new EnvironmentMismatchError('Function `$provideLlmToolsFromEnv` works only in Node.js environment');
9972
- }
9973
- rootDirname = process.cwd();
9974
- i = 0;
9975
- _a.label = 1;
9976
- case 1:
9977
- if (!(i < LOOP_LIMIT)) return [3 /*break*/, 4];
9978
- envFilename = path.join(rootDirname, '.env' /* <- TODO: [🕝] Make here more candidates */);
9979
- return [4 /*yield*/, isFileExisting(envFilename, $provideFilesystemForNode())];
9980
- case 2:
9981
- // console.log({ rootDirname, envFilename });
9982
- if (_a.sent()) {
9983
- dotenv__namespace.config({ path: envFilename });
9984
- return [3 /*break*/, 4];
9985
- }
9986
- if (isRootPath(rootDirname)) {
9987
- return [3 /*break*/, 4];
9988
- }
9989
- // Note: If the directory does not exist, try the parent directory
9990
- rootDirname = path.join(rootDirname, '..');
9991
- _a.label = 3;
9992
- case 3:
9993
- i++;
9994
- return [3 /*break*/, 1];
9995
- case 4:
9996
- llmToolsConfiguration = $llmToolsMetadataRegister
9997
- .list()
9998
- .map(function (metadata) { return metadata.createConfigurationFromEnv(process.env); })
9999
- .filter(function (configuration) { return configuration !== null; });
10000
- return [2 /*return*/, llmToolsConfiguration];
10001
- }
10002
- });
10003
- });
10004
- }
10005
- /**
10006
- * TODO: [🧠][🪁] Maybe do allow to do auto-install if package not registered and not found
10007
- * TODO: Add Azure OpenAI
10008
- * TODO: [🧠][🍛]
10009
- * TODO: [🧠] Is there some meaningfull way how to test this util
10010
- * Note: [🟢] Code in this file should never be never released in packages that could be imported into browser environment
10011
- * TODO: [👷‍♂️] @@@ Manual about construction of llmTools
10012
- * TODO: This should be maybe not under `_common` but under `utils`
10013
- * TODO: [🧠][⚛] Maybe pass env as argument
10014
- * TODO: [®] DRY Register logic */
10015
-
10016
10136
  /**
10017
10137
  * @@@
10018
10138
  *
@@ -10025,6 +10145,22 @@
10025
10145
  * TODO: [®] DRY Register logic
10026
10146
  */
10027
10147
 
10148
+ /**
10149
+ * Path to the `.env` file which was used to configure LLM tools
10150
+ *
10151
+ * Note: `$` is used to indicate that this variable is changed by side effect in `$provideLlmToolsConfigurationFromEnv` through `$setUsedEnvFilename`
10152
+ */
10153
+ var $usedEnvFilename = null;
10154
+ /**
10155
+ * Pass the `.env` file which was used to configure LLM tools
10156
+ *
10157
+ * Note: `$` is used to indicate that this variable is making side effect
10158
+ *
10159
+ * @private internal log of `$provideLlmToolsConfigurationFromEnv` and `$registeredLlmToolsMessage`
10160
+ */
10161
+ function $setUsedEnvFilename(filepath) {
10162
+ $usedEnvFilename = filepath;
10163
+ }
10028
10164
  /**
10029
10165
  * Creates a message with all registered LLM tools
10030
10166
  *
@@ -10103,10 +10239,11 @@
10103
10239
  // <- Note: [🗨]
10104
10240
  return __assign(__assign({}, metadata), { isMetadataAviailable: isMetadataAviailable, isInstalled: isInstalled, isFullyConfigured: isFullyConfigured, isPartiallyConfigured: isPartiallyConfigured });
10105
10241
  });
10242
+ var usedEnvMessage = $usedEnvFilename === null ? "Unknown `.env` file" : "Used `.env` file:\n".concat($usedEnvFilename);
10106
10243
  if (metadata.length === 0) {
10107
- return "No LLM providers are available.";
10244
+ return spaceTrim__default["default"](function (block) { return "\n No LLM providers are available.\n\n ".concat(block(usedEnvMessage), "\n "); });
10108
10245
  }
10109
- return spaceTrim__default["default"](function (block) { return "\n Relevant environment variables:\n ".concat(block(Object.keys(env)
10246
+ return spaceTrim__default["default"](function (block) { return "\n\n ".concat(block(usedEnvMessage), "\n\n Relevant environment variables:\n ").concat(block(Object.keys(env)
10110
10247
  .filter(function (envVariableName) {
10111
10248
  return metadata.some(function (_a) {
10112
10249
  var envVariables = _a.envVariables;
@@ -10171,6 +10308,108 @@
10171
10308
  * TODO: [🧠][⚛] Maybe pass env as argument
10172
10309
  */
10173
10310
 
10311
+ /**
10312
+ * @@@
10313
+ *
10314
+ * @@@ .env
10315
+ *
10316
+ * It looks for environment variables:
10317
+ * - `process.env.OPENAI_API_KEY`
10318
+ * - `process.env.ANTHROPIC_CLAUDE_API_KEY`
10319
+ * - ...
10320
+ *
10321
+ * @returns @@@
10322
+ * @public exported from `@promptbook/node`
10323
+ */
10324
+ function $provideLlmToolsConfigurationFromEnv() {
10325
+ return __awaiter(this, void 0, void 0, function () {
10326
+ var envFilePatterns, rootDirname, i, envFilePatterns_1, envFilePatterns_1_1, pattern, envFilename, e_1_1, llmToolsConfiguration;
10327
+ var e_1, _a;
10328
+ return __generator(this, function (_b) {
10329
+ switch (_b.label) {
10330
+ case 0:
10331
+ if (!$isRunningInNode()) {
10332
+ throw new EnvironmentMismatchError('Function `$provideLlmToolsFromEnv` works only in Node.js environment');
10333
+ }
10334
+ envFilePatterns = [
10335
+ '.env',
10336
+ '.env.test',
10337
+ '.env.local',
10338
+ '.env.development.local',
10339
+ '.env.development',
10340
+ '.env.production.local',
10341
+ '.env.production',
10342
+ '.env.prod.local',
10343
+ '.env.prod',
10344
+ // <- TODO: Maybe add more patterns
10345
+ ];
10346
+ rootDirname = process.cwd();
10347
+ i = 0;
10348
+ _b.label = 1;
10349
+ case 1:
10350
+ if (!(i < LOOP_LIMIT)) return [3 /*break*/, 11];
10351
+ _b.label = 2;
10352
+ case 2:
10353
+ _b.trys.push([2, 7, 8, 9]);
10354
+ envFilePatterns_1 = (e_1 = void 0, __values(envFilePatterns)), envFilePatterns_1_1 = envFilePatterns_1.next();
10355
+ _b.label = 3;
10356
+ case 3:
10357
+ if (!!envFilePatterns_1_1.done) return [3 /*break*/, 6];
10358
+ pattern = envFilePatterns_1_1.value;
10359
+ envFilename = path.join(rootDirname, pattern);
10360
+ return [4 /*yield*/, isFileExisting(envFilename, $provideFilesystemForNode())];
10361
+ case 4:
10362
+ if (_b.sent()) {
10363
+ $setUsedEnvFilename(envFilename);
10364
+ dotenv__namespace.config({ path: envFilename });
10365
+ return [3 /*break*/, 11];
10366
+ }
10367
+ _b.label = 5;
10368
+ case 5:
10369
+ envFilePatterns_1_1 = envFilePatterns_1.next();
10370
+ return [3 /*break*/, 3];
10371
+ case 6: return [3 /*break*/, 9];
10372
+ case 7:
10373
+ e_1_1 = _b.sent();
10374
+ e_1 = { error: e_1_1 };
10375
+ return [3 /*break*/, 9];
10376
+ case 8:
10377
+ try {
10378
+ if (envFilePatterns_1_1 && !envFilePatterns_1_1.done && (_a = envFilePatterns_1.return)) _a.call(envFilePatterns_1);
10379
+ }
10380
+ finally { if (e_1) throw e_1.error; }
10381
+ return [7 /*endfinally*/];
10382
+ case 9:
10383
+ if (isRootPath(rootDirname)) {
10384
+ return [3 /*break*/, 11];
10385
+ }
10386
+ // Note: If the directory does not exist, try the parent directory
10387
+ rootDirname = path.join(rootDirname, '..');
10388
+ _b.label = 10;
10389
+ case 10:
10390
+ i++;
10391
+ return [3 /*break*/, 1];
10392
+ case 11:
10393
+ llmToolsConfiguration = $llmToolsMetadataRegister
10394
+ .list()
10395
+ .map(function (metadata) { return metadata.createConfigurationFromEnv(process.env); })
10396
+ .filter(function (configuration) { return configuration !== null; });
10397
+ return [2 /*return*/, llmToolsConfiguration];
10398
+ }
10399
+ });
10400
+ });
10401
+ }
10402
+ /**
10403
+ * TODO: [🧠][🪁] Maybe do allow to do auto-install if package not registered and not found
10404
+ * TODO: Add Azure OpenAI
10405
+ * TODO: [🧠][🍛]
10406
+ * TODO: [🧠] Is there some meaningfull way how to test this util
10407
+ * Note: [🟢] Code in this file should never be never released in packages that could be imported into browser environment
10408
+ * TODO: [👷‍♂️] @@@ Manual about construction of llmTools
10409
+ * TODO: This should be maybe not under `_common` but under `utils`
10410
+ * TODO: [🧠][⚛] Maybe pass env as argument
10411
+ * TODO: [®] DRY Register logic */
10412
+
10174
10413
  /**
10175
10414
  * @@@
10176
10415
  *
@@ -10287,6 +10526,10 @@
10287
10526
  return [4 /*yield*/, scraperFactory(tools, options || {})];
10288
10527
  case 3:
10289
10528
  scraper = _g.sent();
10529
+ if (scraper.metadata.packageName === '@promptbook/boilerplate' ||
10530
+ scraper.metadata.mimeTypes.some(function (mimeType) { return mimeType.includes('DISABLED'); })) {
10531
+ return [3 /*break*/, 4];
10532
+ }
10290
10533
  scrapers.push(scraper);
10291
10534
  _g.label = 4;
10292
10535
  case 4:
@@ -10320,6 +10563,9 @@
10320
10563
  * @public exported from `@promptbook/utils`
10321
10564
  */
10322
10565
  new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
10566
+ /**
10567
+ * TODO: [🎺]
10568
+ */
10323
10569
 
10324
10570
  /**
10325
10571
  * Detects if the code is running in jest environment
@@ -10329,6 +10575,9 @@
10329
10575
  * @public exported from `@promptbook/utils`
10330
10576
  */
10331
10577
  new Function("\n try {\n return process.env.JEST_WORKER_ID !== undefined;\n } catch (e) {\n return false;\n }\n");
10578
+ /**
10579
+ * TODO: [🎺]
10580
+ */
10332
10581
 
10333
10582
  /**
10334
10583
  * Detects if the code is running in a web worker
@@ -10338,6 +10587,9 @@
10338
10587
  * @public exported from `@promptbook/utils`
10339
10588
  */
10340
10589
  new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n return true;\n } else {\n return false;\n }\n } catch (e) {\n return false;\n }\n");
10590
+ /**
10591
+ * TODO: [🎺]
10592
+ */
10341
10593
 
10342
10594
  /**
10343
10595
  * Makes first letter of a string uppercase
@@ -11274,15 +11526,6 @@
11274
11526
  * TODO: [🍙] Make some standard order of json properties
11275
11527
  */
11276
11528
 
11277
- /**
11278
- * @@@
11279
- *
11280
- * @private for `FileCacheStorage`
11281
- */
11282
- function nameToSubfolderPath(name) {
11283
- return [name.substr(0, 1).toLowerCase(), name.substr(1, 1).toLowerCase()];
11284
- }
11285
-
11286
11529
  /**
11287
11530
  * @@@
11288
11531
  *