@promptbook/markdown-utils 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 +482 -322
  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 +9 -14
  56. package/umd/index.umd.js +481 -323
  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/esm/index.es.js CHANGED
@@ -1,11 +1,14 @@
1
1
  import spaceTrim, { spaceTrim as spaceTrim$1 } from 'spacetrim';
2
2
  import { format } from 'prettier';
3
3
  import parserHtml from 'prettier/parser-html';
4
+ import { BehaviorSubject, concat, from } from 'rxjs';
5
+ import { randomBytes } from 'crypto';
4
6
  import { forTime } from 'waitasecond';
5
- import { join, basename } from 'path';
6
- import { SHA256 } from 'crypto-js';
7
7
  import hexEncoder from 'crypto-js/enc-hex';
8
- import { lookup } from 'mime-types';
8
+ import sha256 from 'crypto-js/sha256';
9
+ import { basename, join, dirname } from 'path';
10
+ import { SHA256 } from 'crypto-js';
11
+ import { lookup, extension } from 'mime-types';
9
12
  import { unparse, parse } from 'papaparse';
10
13
 
11
14
  // ⚠️ WARNING: This code has been generated so that any manual changes will be overwritten
@@ -22,7 +25,7 @@ var BOOK_LANGUAGE_VERSION = '1.0.0';
22
25
  * @generated
23
26
  * @see https://github.com/webgptorg/promptbook
24
27
  */
25
- var PROMPTBOOK_ENGINE_VERSION = '0.84.0-8';
28
+ var PROMPTBOOK_ENGINE_VERSION = '0.84.0';
26
29
  /**
27
30
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
28
31
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -360,6 +363,99 @@ function extractJsonBlock(markdown) {
360
363
 
361
364
  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"}];
362
365
 
366
+ /**
367
+ * Checks if value is valid email
368
+ *
369
+ * @public exported from `@promptbook/utils`
370
+ */
371
+ function isValidEmail(email) {
372
+ if (typeof email !== 'string') {
373
+ return false;
374
+ }
375
+ if (email.split('\n').length > 1) {
376
+ return false;
377
+ }
378
+ return /^.+@.+\..+$/.test(email);
379
+ }
380
+
381
+ /**
382
+ * Tests if given string is valid URL.
383
+ *
384
+ * Note: This does not check if the file exists only if the path is valid
385
+ * @public exported from `@promptbook/utils`
386
+ */
387
+ function isValidFilePath(filename) {
388
+ if (typeof filename !== 'string') {
389
+ return false;
390
+ }
391
+ if (filename.split('\n').length > 1) {
392
+ return false;
393
+ }
394
+ if (filename.split(' ').length >
395
+ 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
396
+ return false;
397
+ }
398
+ var filenameSlashes = filename.split('\\').join('/');
399
+ // Absolute Unix path: /hello.txt
400
+ if (/^(\/)/i.test(filenameSlashes)) {
401
+ // console.log(filename, 'Absolute Unix path: /hello.txt');
402
+ return true;
403
+ }
404
+ // Absolute Windows path: /hello.txt
405
+ if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
406
+ // console.log(filename, 'Absolute Windows path: /hello.txt');
407
+ return true;
408
+ }
409
+ // Relative path: ./hello.txt
410
+ if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
411
+ // console.log(filename, 'Relative path: ./hello.txt');
412
+ return true;
413
+ }
414
+ // Allow paths like foo/hello
415
+ if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
416
+ // console.log(filename, 'Allow paths like foo/hello');
417
+ return true;
418
+ }
419
+ // Allow paths like hello.book
420
+ if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
421
+ // console.log(filename, 'Allow paths like hello.book');
422
+ return true;
423
+ }
424
+ return false;
425
+ }
426
+ /**
427
+ * TODO: [🍏] Implement for MacOs
428
+ */
429
+
430
+ /**
431
+ * Tests if given string is valid URL.
432
+ *
433
+ * Note: Dataurl are considered perfectly valid.
434
+ * Note: There are two simmilar functions:
435
+ * - `isValidUrl` which tests any URL
436
+ * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
437
+ *
438
+ * @public exported from `@promptbook/utils`
439
+ */
440
+ function isValidUrl(url) {
441
+ if (typeof url !== 'string') {
442
+ return false;
443
+ }
444
+ try {
445
+ if (url.startsWith('blob:')) {
446
+ url = url.replace(/^blob:/, '');
447
+ }
448
+ var urlObject = new URL(url /* because fail is handled */);
449
+ if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
450
+ return false;
451
+ }
452
+ return true;
453
+ }
454
+ catch (error) {
455
+ return false;
456
+ }
457
+ }
458
+
363
459
  /**
364
460
  * Function `validatePipelineString` will validate the if the string is a valid pipeline string
365
461
  * 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.
@@ -373,6 +469,15 @@ function validatePipelineString(pipelineString) {
373
469
  if (isValidJsonString(pipelineString)) {
374
470
  throw new ParseError('Expected a book, but got a JSON string');
375
471
  }
472
+ else if (isValidUrl(pipelineString)) {
473
+ throw new ParseError("Expected a book, but got just the URL \"".concat(pipelineString, "\""));
474
+ }
475
+ else if (isValidFilePath(pipelineString)) {
476
+ throw new ParseError("Expected a book, but got just the file path \"".concat(pipelineString, "\""));
477
+ }
478
+ else if (isValidEmail(pipelineString)) {
479
+ throw new ParseError("Expected a book, but got just the email \"".concat(pipelineString, "\""));
480
+ }
376
481
  // <- TODO: Implement the validation + add tests when the pipeline logic considered as invalid
377
482
  return pipelineString;
378
483
  }
@@ -673,6 +778,12 @@ var ADMIN_GITHUB_NAME = 'hejny';
673
778
  * @public exported from `@promptbook/core`
674
779
  */
675
780
  var DEFAULT_BOOK_TITLE = "\u2728 Untitled Book";
781
+ /**
782
+ * Maximum file size limit
783
+ *
784
+ * @public exported from `@promptbook/core`
785
+ */
786
+ var DEFAULT_MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
676
787
  // <- TODO: [🧠] Better system for generator warnings - not always "code" and "by `@promptbook/cli`"
677
788
  /**
678
789
  * The maximum number of iterations for a loops
@@ -706,6 +817,12 @@ var SMALL_NUMBER = 0.001;
706
817
  * @private within the repository - too low-level in comparison with other `MAX_...`
707
818
  */
708
819
  var IMMEDIATE_TIME = 10;
820
+ /**
821
+ * The maximum length of the (generated) filename
822
+ *
823
+ * @public exported from `@promptbook/core`
824
+ */
825
+ var MAX_FILENAME_LENGTH = 30;
709
826
  /**
710
827
  * Strategy for caching the intermediate results for knowledge sources
711
828
  *
@@ -725,6 +842,15 @@ var DEFAULT_MAX_PARALLEL_COUNT = 5; // <- TODO: [🤹‍♂️]
725
842
  * @public exported from `@promptbook/core`
726
843
  */
727
844
  var DEFAULT_MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
845
+ // <- TODO: [🕝] Make also `BOOKS_DIRNAME_ALTERNATIVES`
846
+ /**
847
+ * Where to store the temporary downloads
848
+ *
849
+ * Note: When the folder does not exist, it is created recursively
850
+ *
851
+ * @public exported from `@promptbook/core`
852
+ */
853
+ var DEFAULT_DOWNLOAD_CACHE_DIRNAME = './.promptbook/download-cache';
728
854
  /**
729
855
  * Where to store the scrape cache
730
856
  *
@@ -1207,35 +1333,6 @@ function isUrlOnPrivateNetwork(url) {
1207
1333
  return isHostnameOnPrivateNetwork(url.hostname);
1208
1334
  }
1209
1335
 
1210
- /**
1211
- * Tests if given string is valid URL.
1212
- *
1213
- * Note: Dataurl are considered perfectly valid.
1214
- * Note: There are two simmilar functions:
1215
- * - `isValidUrl` which tests any URL
1216
- * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
1217
- *
1218
- * @public exported from `@promptbook/utils`
1219
- */
1220
- function isValidUrl(url) {
1221
- if (typeof url !== 'string') {
1222
- return false;
1223
- }
1224
- try {
1225
- if (url.startsWith('blob:')) {
1226
- url = url.replace(/^blob:/, '');
1227
- }
1228
- var urlObject = new URL(url /* because fail is handled */);
1229
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
1230
- return false;
1231
- }
1232
- return true;
1233
- }
1234
- catch (error) {
1235
- return false;
1236
- }
1237
- }
1238
-
1239
1336
  /**
1240
1337
  * Tests if given string is valid pipeline URL URL.
1241
1338
  *
@@ -1777,6 +1874,58 @@ var PipelineExecutionError = /** @class */ (function (_super) {
1777
1874
  return PipelineExecutionError;
1778
1875
  }(Error));
1779
1876
 
1877
+ /**
1878
+ * Determine if the pipeline is fully prepared
1879
+ *
1880
+ * @see https://github.com/webgptorg/promptbook/discussions/196
1881
+ *
1882
+ * @public exported from `@promptbook/core`
1883
+ */
1884
+ function isPipelinePrepared(pipeline) {
1885
+ // Note: Ignoring `pipeline.preparations` @@@
1886
+ // Note: Ignoring `pipeline.knowledgePieces` @@@
1887
+ if (pipeline.title === undefined || pipeline.title === '' || pipeline.title === DEFAULT_BOOK_TITLE) {
1888
+ return false;
1889
+ }
1890
+ if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
1891
+ return false;
1892
+ }
1893
+ if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
1894
+ return false;
1895
+ }
1896
+ /*
1897
+ TODO: [🧠][🍫] `tasks` can not be determined if they are fully prepared SO ignoring them
1898
+ > if (!pipeline.tasks.every(({ preparedContent }) => preparedContent === undefined)) {
1899
+ > return false;
1900
+ > }
1901
+ */
1902
+ return true;
1903
+ }
1904
+ /**
1905
+ * TODO: [🔃][main] If the pipeline was prepared with different version or different set of models, prepare it once again
1906
+ * TODO: [🐠] Maybe base this on `makeValidator`
1907
+ * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
1908
+ * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
1909
+ * - [🏍] ? Is context in each task
1910
+ * - [♨] Are examples prepared
1911
+ * - [♨] Are tasks prepared
1912
+ */
1913
+
1914
+ /**
1915
+ * Generates random token
1916
+ *
1917
+ * Note: This function is cryptographically secure (it uses crypto.randomBytes internally)
1918
+ *
1919
+ * @private internal helper function
1920
+ * @returns secure random token
1921
+ */
1922
+ function $randomToken(randomness) {
1923
+ return randomBytes(randomness).toString('hex');
1924
+ }
1925
+ /**
1926
+ * TODO: Maybe use nanoid instead https://github.com/ai/nanoid
1927
+ */
1928
+
1780
1929
  /**
1781
1930
  * This error indicates problems parsing the format value
1782
1931
  *
@@ -1990,12 +2139,28 @@ function deserializeError(error) {
1990
2139
  /**
1991
2140
  * Asserts that the execution of a Promptbook is successful
1992
2141
  *
2142
+ * Note: If there are only warnings, the execution is still successful but the warnings are logged in the console
2143
+ *
1993
2144
  * @param executionResult - The partial result of the Promptbook execution
1994
2145
  * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
1995
- * @public exported from `@promptbook/core`
2146
+ * @private internal helper function of `asPromise` method of `ExecutionTask`
1996
2147
  */
1997
- function assertsExecutionSuccessful(executionResult) {
1998
- var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
2148
+ function assertsTaskSuccessful(executionResult) {
2149
+ var e_1, _a;
2150
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors, warnings = executionResult.warnings;
2151
+ try {
2152
+ for (var warnings_1 = __values(warnings), warnings_1_1 = warnings_1.next(); !warnings_1_1.done; warnings_1_1 = warnings_1.next()) {
2153
+ var warning = warnings_1_1.value;
2154
+ console.warn(warning.message);
2155
+ }
2156
+ }
2157
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2158
+ finally {
2159
+ try {
2160
+ if (warnings_1_1 && !warnings_1_1.done && (_a = warnings_1.return)) _a.call(warnings_1);
2161
+ }
2162
+ finally { if (e_1) throw e_1.error; }
2163
+ }
1999
2164
  if (isSuccessful === true) {
2000
2165
  return;
2001
2166
  }
@@ -2015,121 +2180,54 @@ function assertsExecutionSuccessful(executionResult) {
2015
2180
  }
2016
2181
  }
2017
2182
  /**
2018
- * TODO: [🐚] This function should be removed OR changed OR be completely rewritten
2019
2183
  * TODO: [🧠] Can this return type be better typed than void
2020
2184
  */
2021
2185
 
2022
2186
  /**
2023
- * Determine if the pipeline is fully prepared
2024
- *
2025
- * @see https://github.com/webgptorg/promptbook/discussions/196
2026
- *
2027
- * @public exported from `@promptbook/core`
2028
- */
2029
- function isPipelinePrepared(pipeline) {
2030
- // Note: Ignoring `pipeline.preparations` @@@
2031
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2032
- if (pipeline.title === undefined || pipeline.title === '' || pipeline.title === DEFAULT_BOOK_TITLE) {
2033
- return false;
2034
- }
2035
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2036
- return false;
2037
- }
2038
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2039
- return false;
2040
- }
2041
- /*
2042
- TODO: [🧠][🍫] `tasks` can not be determined if they are fully prepared SO ignoring them
2043
- > if (!pipeline.tasks.every(({ preparedContent }) => preparedContent === undefined)) {
2044
- > return false;
2045
- > }
2046
- */
2047
- return true;
2048
- }
2049
- /**
2050
- * TODO: [🔃][main] If the pipeline was prepared with different version or different set of models, prepare it once again
2051
- * TODO: [🐠] Maybe base this on `makeValidator`
2052
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2053
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2054
- * - [🏍] ? Is context in each task
2055
- * - [♨] Are examples prepared
2056
- * - [♨] Are tasks prepared
2057
- */
2058
-
2059
- /**
2060
- * Format either small or big number
2187
+ * Helper to create a new task
2061
2188
  *
2062
- * @public exported from `@promptbook/utils`
2189
+ * @private internal helper function
2063
2190
  */
2064
- function numberToString(value) {
2065
- if (value === 0) {
2066
- return '0';
2067
- }
2068
- else if (Number.isNaN(value)) {
2069
- return VALUE_STRINGS.nan;
2070
- }
2071
- else if (value === Infinity) {
2072
- return VALUE_STRINGS.infinity;
2073
- }
2074
- else if (value === -Infinity) {
2075
- return VALUE_STRINGS.negativeInfinity;
2076
- }
2077
- for (var exponent = 0; exponent < 15; exponent++) {
2078
- var factor = Math.pow(10, exponent);
2079
- var valueRounded = Math.round(value * factor) / factor;
2080
- if (Math.abs(value - valueRounded) / value < SMALL_NUMBER) {
2081
- return valueRounded.toFixed(exponent);
2082
- }
2191
+ function createTask(options) {
2192
+ var taskType = options.taskType, taskProcessCallback = options.taskProcessCallback;
2193
+ var taskId = "".concat(taskType.toLowerCase(), "-").concat($randomToken(256 /* <- TODO: !!! To global config */));
2194
+ var resultSubject = new BehaviorSubject({});
2195
+ var finalResultPromise = /* not await */ taskProcessCallback(function (newOngoingResult) {
2196
+ resultSubject.next(newOngoingResult);
2197
+ });
2198
+ function asPromise(options) {
2199
+ return __awaiter(this, void 0, void 0, function () {
2200
+ var _a, isCrashedOnError, finalResult;
2201
+ return __generator(this, function (_b) {
2202
+ switch (_b.label) {
2203
+ case 0:
2204
+ _a = (options || {}).isCrashedOnError, isCrashedOnError = _a === void 0 ? true : _a;
2205
+ return [4 /*yield*/, finalResultPromise];
2206
+ case 1:
2207
+ finalResult = _b.sent();
2208
+ if (isCrashedOnError) {
2209
+ assertsTaskSuccessful(finalResult);
2210
+ }
2211
+ return [2 /*return*/, finalResult];
2212
+ }
2213
+ });
2214
+ });
2083
2215
  }
2084
- return value.toString();
2216
+ return {
2217
+ taskType: taskType,
2218
+ taskId: taskId,
2219
+ asPromise: asPromise,
2220
+ asObservable: function () {
2221
+ return concat(resultSubject.asObservable(), from(asPromise({
2222
+ isCrashedOnError: true,
2223
+ })));
2224
+ },
2225
+ };
2085
2226
  }
2086
-
2087
2227
  /**
2088
- * Function `valueToString` will convert the given value to string
2089
- * This is useful and used in the `templateParameters` function
2090
- *
2091
- * Note: This function is not just calling `toString` method
2092
- * It's more complex and can handle this conversion specifically for LLM models
2093
- * See `VALUE_STRINGS`
2094
- *
2095
- * Note: There are 2 similar functions
2096
- * - `valueToString` converts value to string for LLM models as human-readable string
2097
- * - `asSerializable` converts value to string to preserve full information to be able to convert it back
2098
- *
2099
- * @public exported from `@promptbook/utils`
2228
+ * TODO: Maybe allow to terminate the task and add getter `isFinished` or `status`
2229
+ * TODO: [🐚] Split into more files and make `PrepareTask` & `RemoteTask` + split the function
2100
2230
  */
2101
- function valueToString(value) {
2102
- try {
2103
- if (value === '') {
2104
- return VALUE_STRINGS.empty;
2105
- }
2106
- else if (value === null) {
2107
- return VALUE_STRINGS.null;
2108
- }
2109
- else if (value === undefined) {
2110
- return VALUE_STRINGS.undefined;
2111
- }
2112
- else if (typeof value === 'string') {
2113
- return value;
2114
- }
2115
- else if (typeof value === 'number') {
2116
- return numberToString(value);
2117
- }
2118
- else if (value instanceof Date) {
2119
- return value.toISOString();
2120
- }
2121
- else {
2122
- return JSON.stringify(value);
2123
- }
2124
- }
2125
- catch (error) {
2126
- if (!(error instanceof Error)) {
2127
- throw error;
2128
- }
2129
- console.error(error);
2130
- return VALUE_STRINGS.unserializable;
2131
- }
2132
- }
2133
2231
 
2134
2232
  /**
2135
2233
  * Serializes an error into a [🚉] JSON-serializable object
@@ -2632,7 +2730,7 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2632
2730
  if (!(error_1 instanceof Error) || error_1 instanceof UnexpectedError) {
2633
2731
  throw error_1;
2634
2732
  }
2635
- errors.push(error_1);
2733
+ errors.push({ llmExecutionTools: llmExecutionTools, error: error_1 });
2636
2734
  return [3 /*break*/, 13];
2637
2735
  case 13:
2638
2736
  _b = _a.next();
@@ -2659,7 +2757,10 @@ var MultipleLlmExecutionTools = /** @class */ (function () {
2659
2757
  // 2) AnthropicClaude throw PipelineExecutionError: Parameter `{knowledge}` is not defined
2660
2758
  // 3) ...
2661
2759
  spaceTrim(function (block) { return "\n All execution tools failed:\n\n ".concat(block(errors
2662
- .map(function (error, i) { return "".concat(i + 1, ") **").concat(error.name || 'Error', ":** ").concat(error.message); })
2760
+ .map(function (_a, i) {
2761
+ var error = _a.error, llmExecutionTools = _a.llmExecutionTools;
2762
+ return "".concat(i + 1, ") **").concat(llmExecutionTools.title, "** thrown **").concat(error.name || 'Error', ":** ").concat(error.message);
2763
+ })
2663
2764
  .join('\n')), "\n\n "); }));
2664
2765
  }
2665
2766
  else if (this.llmExecutionTools.length === 0) {
@@ -2790,10 +2891,9 @@ function preparePersona(personaDescription, tools, options) {
2790
2891
  return modelName;
2791
2892
  })
2792
2893
  .join(',');
2793
- return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription })];
2894
+ return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription }).asPromise()];
2794
2895
  case 3:
2795
2896
  result = _d.sent();
2796
- assertsExecutionSuccessful(result);
2797
2897
  outputParameters = result.outputParameters;
2798
2898
  modelRequirementsRaw = outputParameters.modelRequirements;
2799
2899
  modelRequirements = JSON.parse(modelRequirementsRaw);
@@ -3445,6 +3545,15 @@ function knowledgeSourceContentToName(knowledgeSourceContent) {
3445
3545
  * TODO: [🐱‍🐉][🧠] Make some smart crop NOT source-i-m-pavol-a-develop-... BUT source-i-m-pavol-a-developer-...
3446
3546
  */
3447
3547
 
3548
+ /**
3549
+ * @@@
3550
+ *
3551
+ * @private for `FileCacheStorage`
3552
+ */
3553
+ function nameToSubfolderPath(name) {
3554
+ return [name.substr(0, 1).toLowerCase(), name.substr(1, 1).toLowerCase()];
3555
+ }
3556
+
3448
3557
  /**
3449
3558
  * Convert file extension to mime type
3450
3559
  *
@@ -3501,53 +3610,55 @@ function isFileExisting(filename, fs) {
3501
3610
  */
3502
3611
 
3503
3612
  /**
3504
- * Tests if given string is valid URL.
3613
+ * Convert mime type to file extension
3505
3614
  *
3506
- * Note: This does not check if the file exists only if the path is valid
3615
+ * Note: If the mime type is invalid, `null` is returned
3616
+ *
3617
+ * @private within the repository
3618
+ */
3619
+ function mimeTypeToExtension(value) {
3620
+ return extension(value) || null;
3621
+ }
3622
+
3623
+ /**
3624
+ * Removes emojis from a string and fix whitespaces
3625
+ *
3626
+ * @param text with emojis
3627
+ * @returns text without emojis
3507
3628
  * @public exported from `@promptbook/utils`
3508
3629
  */
3509
- function isValidFilePath(filename) {
3510
- if (typeof filename !== 'string') {
3511
- return false;
3512
- }
3513
- if (filename.split('\n').length > 1) {
3514
- return false;
3515
- }
3516
- if (filename.split(' ').length >
3517
- 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
3518
- return false;
3519
- }
3520
- var filenameSlashes = filename.split('\\').join('/');
3521
- // Absolute Unix path: /hello.txt
3522
- if (/^(\/)/i.test(filenameSlashes)) {
3523
- // console.log(filename, 'Absolute Unix path: /hello.txt');
3524
- return true;
3525
- }
3526
- // Absolute Windows path: /hello.txt
3527
- if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
3528
- // console.log(filename, 'Absolute Windows path: /hello.txt');
3529
- return true;
3530
- }
3531
- // Relative path: ./hello.txt
3532
- if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
3533
- // console.log(filename, 'Relative path: ./hello.txt');
3534
- return true;
3535
- }
3536
- // Allow paths like foo/hello
3537
- if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
3538
- // console.log(filename, 'Allow paths like foo/hello');
3539
- return true;
3540
- }
3541
- // Allow paths like hello.book
3542
- if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
3543
- // console.log(filename, 'Allow paths like hello.book');
3544
- return true;
3545
- }
3546
- return false;
3630
+ function removeEmojis(text) {
3631
+ // Replace emojis (and also ZWJ sequence) with hyphens
3632
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
3633
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
3634
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
3635
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
3636
+ return text;
3547
3637
  }
3638
+
3548
3639
  /**
3549
- * TODO: [🍏] Implement for MacOs
3640
+ * @@@
3641
+ *
3642
+ * @param value @@@
3643
+ * @returns @@@
3644
+ * @example @@@
3645
+ * @public exported from `@promptbook/utils`
3550
3646
  */
3647
+ function titleToName(value) {
3648
+ if (isValidUrl(value)) {
3649
+ value = value.replace(/^https?:\/\//, '');
3650
+ value = value.replace(/\.html$/, '');
3651
+ }
3652
+ else if (isValidFilePath(value)) {
3653
+ value = basename(value);
3654
+ // Note: Keeping extension in the name
3655
+ }
3656
+ value = value.split('/').join('-');
3657
+ value = removeEmojis(value);
3658
+ value = normalizeToKebabCase(value);
3659
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
3660
+ return value;
3661
+ }
3551
3662
 
3552
3663
  /**
3553
3664
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
@@ -3584,9 +3695,9 @@ var scraperFetch = function (url, init) { return __awaiter(void 0, void 0, void
3584
3695
  function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3585
3696
  var _a;
3586
3697
  return __awaiter(this, void 0, void 0, function () {
3587
- var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, filename_1, fileExtension, mimeType;
3588
- return __generator(this, function (_f) {
3589
- switch (_f.label) {
3698
+ var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, basename, hash, rootDirname_1, filepath, fileContent, _f, _g, filename_1, fileExtension, mimeType;
3699
+ return __generator(this, function (_h) {
3700
+ switch (_h.label) {
3590
3701
  case 0:
3591
3702
  _b = tools.fetch, fetch = _b === void 0 ? scraperFetch : _b;
3592
3703
  knowledgeSourceContent = knowledgeSource.knowledgeSourceContent;
@@ -3595,54 +3706,76 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3595
3706
  if (!name) {
3596
3707
  name = knowledgeSourceContentToName(knowledgeSourceContent);
3597
3708
  }
3598
- if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 2];
3709
+ if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 5];
3599
3710
  url = knowledgeSourceContent;
3600
3711
  return [4 /*yield*/, fetch(url)];
3601
3712
  case 1:
3602
- response_1 = _f.sent();
3713
+ response_1 = _h.sent();
3603
3714
  mimeType = ((_a = response_1.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
3604
- return [2 /*return*/, {
3605
- source: name,
3606
- filename: null,
3607
- url: url,
3608
- mimeType: mimeType,
3609
- /*
3610
- TODO: [🥽]
3611
- > async asBlob() {
3612
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
3613
- > const content = await response.blob();
3614
- > return content;
3615
- > },
3616
- */
3617
- asJson: function () {
3618
- return __awaiter(this, void 0, void 0, function () {
3619
- var content;
3620
- return __generator(this, function (_a) {
3621
- switch (_a.label) {
3622
- case 0: return [4 /*yield*/, response_1.json()];
3623
- case 1:
3624
- content = _a.sent();
3625
- return [2 /*return*/, content];
3626
- }
3715
+ if (tools.fs === undefined || !url.endsWith('.pdf' /* <- TODO: [💵] */)) {
3716
+ return [2 /*return*/, {
3717
+ source: name,
3718
+ filename: null,
3719
+ url: url,
3720
+ mimeType: mimeType,
3721
+ /*
3722
+ TODO: [🥽]
3723
+ > async asBlob() {
3724
+ > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
3725
+ > const content = await response.blob();
3726
+ > return content;
3727
+ > },
3728
+ */
3729
+ asJson: function () {
3730
+ return __awaiter(this, void 0, void 0, function () {
3731
+ var content;
3732
+ return __generator(this, function (_a) {
3733
+ switch (_a.label) {
3734
+ case 0: return [4 /*yield*/, response_1.json()];
3735
+ case 1:
3736
+ content = _a.sent();
3737
+ return [2 /*return*/, content];
3738
+ }
3739
+ });
3627
3740
  });
3628
- });
3629
- },
3630
- asText: function () {
3631
- return __awaiter(this, void 0, void 0, function () {
3632
- var content;
3633
- return __generator(this, function (_a) {
3634
- switch (_a.label) {
3635
- case 0: return [4 /*yield*/, response_1.text()];
3636
- case 1:
3637
- content = _a.sent();
3638
- return [2 /*return*/, content];
3639
- }
3741
+ },
3742
+ asText: function () {
3743
+ return __awaiter(this, void 0, void 0, function () {
3744
+ var content;
3745
+ return __generator(this, function (_a) {
3746
+ switch (_a.label) {
3747
+ case 0: return [4 /*yield*/, response_1.text()];
3748
+ case 1:
3749
+ content = _a.sent();
3750
+ return [2 /*return*/, content];
3751
+ }
3752
+ });
3640
3753
  });
3641
- });
3642
- },
3643
- }];
3754
+ },
3755
+ }];
3756
+ }
3757
+ basename = url.split('/').pop() || titleToName(url);
3758
+ hash = sha256(hexEncoder.parse(url)).toString( /* hex */);
3759
+ rootDirname_1 = join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
3760
+ filepath = 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));
3761
+ return [4 /*yield*/, tools.fs.mkdir(dirname(join(rootDirname_1, filepath)), { recursive: true })];
3644
3762
  case 2:
3645
- if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 4];
3763
+ _h.sent();
3764
+ _g = (_f = Buffer).from;
3765
+ return [4 /*yield*/, response_1.arrayBuffer()];
3766
+ case 3:
3767
+ fileContent = _g.apply(_f, [_h.sent()]);
3768
+ if (fileContent.length > DEFAULT_MAX_FILE_SIZE /* <- TODO: Allow to pass different value to remote server */) {
3769
+ 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."));
3770
+ }
3771
+ return [4 /*yield*/, tools.fs.writeFile(join(rootDirname_1, filepath), fileContent)];
3772
+ case 4:
3773
+ _h.sent();
3774
+ // TODO: [💵] Check the file security
3775
+ // TODO: [🧹][🧠] Delete the file after the scraping is done
3776
+ return [2 /*return*/, makeKnowledgeSourceHandler({ name: name, knowledgeSourceContent: filepath }, tools, __assign(__assign({}, options), { rootDirname: rootDirname_1 }))];
3777
+ case 5:
3778
+ if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 7];
3646
3779
  if (tools.fs === undefined) {
3647
3780
  throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
3648
3781
  // <- TODO: [🧠] What is the best error type here`
@@ -3655,8 +3788,8 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3655
3788
  fileExtension = getFileExtension(filename_1);
3656
3789
  mimeType = extensionToMimeType(fileExtension || '');
3657
3790
  return [4 /*yield*/, isFileExisting(filename_1, tools.fs)];
3658
- case 3:
3659
- if (!(_f.sent())) {
3791
+ case 6:
3792
+ if (!(_h.sent())) {
3660
3793
  throw new NotFoundError(spaceTrim(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 "); }));
3661
3794
  }
3662
3795
  // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
@@ -3702,7 +3835,7 @@ function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3702
3835
  });
3703
3836
  },
3704
3837
  }];
3705
- case 4: return [2 /*return*/, {
3838
+ case 7: return [2 /*return*/, {
3706
3839
  source: name,
3707
3840
  filename: null,
3708
3841
  url: null,
@@ -3966,10 +4099,9 @@ function preparePipeline(pipeline, tools, options) {
3966
4099
  var content = _a.content;
3967
4100
  return content;
3968
4101
  }).join('\n\n'),
3969
- })];
4102
+ }).asPromise()];
3970
4103
  case 2:
3971
4104
  result = _e.sent();
3972
- assertsExecutionSuccessful(result);
3973
4105
  outputParameters = result.outputParameters;
3974
4106
  titleRaw = outputParameters.title;
3975
4107
  if (isVerbose) {
@@ -4041,6 +4173,81 @@ function preparePipeline(pipeline, tools, options) {
4041
4173
  * @see https://docs.anthropic.com/en/docs/test-and-evaluate/strengthen-guardrails/increase-consistency#specify-the-desired-output-format
4042
4174
  */
4043
4175
 
4176
+ /**
4177
+ * Format either small or big number
4178
+ *
4179
+ * @public exported from `@promptbook/utils`
4180
+ */
4181
+ function numberToString(value) {
4182
+ if (value === 0) {
4183
+ return '0';
4184
+ }
4185
+ else if (Number.isNaN(value)) {
4186
+ return VALUE_STRINGS.nan;
4187
+ }
4188
+ else if (value === Infinity) {
4189
+ return VALUE_STRINGS.infinity;
4190
+ }
4191
+ else if (value === -Infinity) {
4192
+ return VALUE_STRINGS.negativeInfinity;
4193
+ }
4194
+ for (var exponent = 0; exponent < 15; exponent++) {
4195
+ var factor = Math.pow(10, exponent);
4196
+ var valueRounded = Math.round(value * factor) / factor;
4197
+ if (Math.abs(value - valueRounded) / value < SMALL_NUMBER) {
4198
+ return valueRounded.toFixed(exponent);
4199
+ }
4200
+ }
4201
+ return value.toString();
4202
+ }
4203
+
4204
+ /**
4205
+ * Function `valueToString` will convert the given value to string
4206
+ * This is useful and used in the `templateParameters` function
4207
+ *
4208
+ * Note: This function is not just calling `toString` method
4209
+ * It's more complex and can handle this conversion specifically for LLM models
4210
+ * See `VALUE_STRINGS`
4211
+ *
4212
+ * Note: There are 2 similar functions
4213
+ * - `valueToString` converts value to string for LLM models as human-readable string
4214
+ * - `asSerializable` converts value to string to preserve full information to be able to convert it back
4215
+ *
4216
+ * @public exported from `@promptbook/utils`
4217
+ */
4218
+ function valueToString(value) {
4219
+ try {
4220
+ if (value === '') {
4221
+ return VALUE_STRINGS.empty;
4222
+ }
4223
+ else if (value === null) {
4224
+ return VALUE_STRINGS.null;
4225
+ }
4226
+ else if (value === undefined) {
4227
+ return VALUE_STRINGS.undefined;
4228
+ }
4229
+ else if (typeof value === 'string') {
4230
+ return value;
4231
+ }
4232
+ else if (typeof value === 'number') {
4233
+ return numberToString(value);
4234
+ }
4235
+ else if (value instanceof Date) {
4236
+ return value.toISOString();
4237
+ }
4238
+ else {
4239
+ return JSON.stringify(value);
4240
+ }
4241
+ }
4242
+ catch (error) {
4243
+ if (!(error instanceof Error)) {
4244
+ throw error;
4245
+ }
4246
+ console.error(error);
4247
+ return VALUE_STRINGS.unserializable;
4248
+ }
4249
+ }
4250
+
4044
4251
  /**
4045
4252
  * Parses the given script and returns the list of all used variables that are not defined in the script
4046
4253
  *
@@ -5369,27 +5576,20 @@ function getReservedParametersForTask(options) {
5369
5576
  */
5370
5577
  function executeTask(options) {
5371
5578
  return __awaiter(this, void 0, void 0, function () {
5372
- 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;
5373
- var e_1, _f, _g;
5374
- return __generator(this, function (_h) {
5375
- switch (_h.label) {
5579
+ 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;
5580
+ var _f, e_1, _g, _h, _j;
5581
+ return __generator(this, function (_k) {
5582
+ switch (_k.label) {
5376
5583
  case 0:
5377
5584
  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;
5378
- name = "pipeline-executor-frame-".concat(currentTask.name);
5379
- title = currentTask.title;
5380
5585
  priority = preparedPipeline.tasks.length - preparedPipeline.tasks.indexOf(currentTask);
5381
5586
  return [4 /*yield*/, onProgress({
5382
- name: name,
5383
- title: title,
5384
- isStarted: false,
5385
- isDone: false,
5386
- taskType: currentTask.taskType,
5387
- parameterName: currentTask.resultingParameterName,
5388
- parameterValue: null,
5389
- // <- [🍸]
5587
+ outputParameters: (_f = {},
5588
+ _f[currentTask.resultingParameterName] = '',
5589
+ _f),
5390
5590
  })];
5391
5591
  case 1:
5392
- _h.sent();
5592
+ _k.sent();
5393
5593
  usedParameterNames = extractParameterNamesFromTask(currentTask);
5394
5594
  dependentParameterNames = new Set(currentTask.dependentParameterNames);
5395
5595
  // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
@@ -5408,7 +5608,7 @@ function executeTask(options) {
5408
5608
  pipelineIdentification: pipelineIdentification,
5409
5609
  })];
5410
5610
  case 2:
5411
- definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_h.sent())])), parametersToPass])]);
5611
+ definedParameters = _b.apply(_a, [__assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_k.sent())])), parametersToPass])]);
5412
5612
  definedParameterNames = new Set(Object.keys(definedParameters));
5413
5613
  parameters = {};
5414
5614
  _loop_1 = function (parameterName) {
@@ -5436,7 +5636,7 @@ function executeTask(options) {
5436
5636
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
5437
5637
  finally {
5438
5638
  try {
5439
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
5639
+ if (_e && !_e.done && (_g = _d.return)) _g.call(_d);
5440
5640
  }
5441
5641
  finally { if (e_1) throw e_1.error; }
5442
5642
  }
@@ -5467,24 +5667,19 @@ function executeTask(options) {
5467
5667
  isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
5468
5668
  })];
5469
5669
  case 3:
5470
- resultString = _h.sent();
5670
+ resultString = _k.sent();
5471
5671
  return [4 /*yield*/, onProgress({
5472
- name: name,
5473
- title: title,
5474
- isStarted: true,
5475
- isDone: true,
5476
- taskType: currentTask.taskType,
5477
- parameterName: currentTask.resultingParameterName,
5478
- parameterValue: resultString,
5479
- // <- [🍸]
5672
+ outputParameters: (_h = {},
5673
+ _h[currentTask.resultingParameterName] = resultString,
5674
+ _h),
5480
5675
  })];
5481
5676
  case 4:
5482
- _h.sent();
5483
- return [2 /*return*/, Object.freeze((_g = {},
5484
- _g[currentTask.resultingParameterName] =
5677
+ _k.sent();
5678
+ return [2 /*return*/, Object.freeze((_j = {},
5679
+ _j[currentTask.resultingParameterName] =
5485
5680
  // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
5486
5681
  resultString,
5487
- _g))];
5682
+ _j))];
5488
5683
  }
5489
5684
  });
5490
5685
  });
@@ -5492,9 +5687,6 @@ function executeTask(options) {
5492
5687
  /**
5493
5688
  * TODO: [🤹‍♂️]
5494
5689
  */
5495
- /**
5496
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
5497
- */
5498
5690
 
5499
5691
  /**
5500
5692
  * @@@
@@ -5756,15 +5948,15 @@ function executePipeline(options) {
5756
5948
  return [3 /*break*/, 4];
5757
5949
  case 3:
5758
5950
  unresovedTasks_1 = unresovedTasks_1.filter(function (task) { return task !== currentTask; });
5759
- work_1 = executeTask(__assign(__assign({}, options), { currentTask: currentTask, preparedPipeline: preparedPipeline, parametersToPass: parametersToPass, tools: tools, onProgress: function (progress) {
5951
+ work_1 = executeTask(__assign(__assign({}, options), { currentTask: currentTask, preparedPipeline: preparedPipeline, parametersToPass: parametersToPass, tools: tools, onProgress: function (newOngoingResult) {
5760
5952
  if (isReturned) {
5761
- throw new UnexpectedError(spaceTrim$1(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)
5953
+ throw new UnexpectedError(spaceTrim$1(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)
5762
5954
  .split('\n')
5763
5955
  .map(function (line) { return "> ".concat(line); })
5764
5956
  .join('\n')), "\n "); }));
5765
5957
  }
5766
5958
  if (onProgress) {
5767
- onProgress(progress);
5959
+ onProgress(newOngoingResult);
5768
5960
  }
5769
5961
  }, $executionReport: executionReport, pipelineIdentification: spaceTrim$1(function (block) { return "\n ".concat(block(pipelineIdentification), "\n Task name: ").concat(currentTask.name, "\n Task title: ").concat(currentTask.title, "\n "); }) }))
5770
5962
  .then(function (newParametersToPass) {
@@ -5867,9 +6059,6 @@ function executePipeline(options) {
5867
6059
  });
5868
6060
  });
5869
6061
  }
5870
- /**
5871
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
5872
- */
5873
6062
 
5874
6063
  /**
5875
6064
  * Creates executor function from pipeline and execution tools.
@@ -5901,7 +6090,7 @@ function createPipelineExecutor(options) {
5901
6090
  console.warn(spaceTrim$1(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 "); }));
5902
6091
  }
5903
6092
  var runCount = 0;
5904
- var pipelineExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
6093
+ var pipelineExecutorWithCallback = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
5905
6094
  return __generator(this, function (_a) {
5906
6095
  runCount++;
5907
6096
  return [2 /*return*/, /* not await */ executePipeline({
@@ -5926,51 +6115,23 @@ function createPipelineExecutor(options) {
5926
6115
  })];
5927
6116
  });
5928
6117
  }); };
6118
+ var pipelineExecutor = function (inputParameters) {
6119
+ return createTask({
6120
+ taskType: 'EXECUTION',
6121
+ taskProcessCallback: function (updateOngoingResult) {
6122
+ var _this = this;
6123
+ return pipelineExecutorWithCallback(inputParameters, function (newOngoingResult) { return __awaiter(_this, void 0, void 0, function () {
6124
+ return __generator(this, function (_a) {
6125
+ updateOngoingResult(newOngoingResult);
6126
+ return [2 /*return*/];
6127
+ });
6128
+ }); });
6129
+ },
6130
+ });
6131
+ };
6132
+ // <- TODO: Make types such as there is no need to do `as` for `createTask`
5929
6133
  return pipelineExecutor;
5930
6134
  }
5931
- /**
5932
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
5933
- */
5934
-
5935
- /**
5936
- * Removes emojis from a string and fix whitespaces
5937
- *
5938
- * @param text with emojis
5939
- * @returns text without emojis
5940
- * @public exported from `@promptbook/utils`
5941
- */
5942
- function removeEmojis(text) {
5943
- // Replace emojis (and also ZWJ sequence) with hyphens
5944
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
5945
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
5946
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
5947
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
5948
- return text;
5949
- }
5950
-
5951
- /**
5952
- * @@@
5953
- *
5954
- * @param value @@@
5955
- * @returns @@@
5956
- * @example @@@
5957
- * @public exported from `@promptbook/utils`
5958
- */
5959
- function titleToName(value) {
5960
- if (isValidUrl(value)) {
5961
- value = value.replace(/^https?:\/\//, '');
5962
- value = value.replace(/\.html$/, '');
5963
- }
5964
- else if (isValidFilePath(value)) {
5965
- value = basename(value);
5966
- // Note: Keeping extension in the name
5967
- }
5968
- value = value.split('/').join('-');
5969
- value = removeEmojis(value);
5970
- value = normalizeToKebabCase(value);
5971
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
5972
- return value;
5973
- }
5974
6135
 
5975
6136
  /**
5976
6137
  * Metadata of the scraper
@@ -6072,10 +6233,9 @@ var MarkdownScraper = /** @class */ (function () {
6072
6233
  return [4 /*yield*/, source.asText()];
6073
6234
  case 4:
6074
6235
  knowledgeContent = _k.sent();
6075
- return [4 /*yield*/, prepareKnowledgeFromMarkdownExecutor({ knowledgeContent: knowledgeContent })];
6236
+ return [4 /*yield*/, prepareKnowledgeFromMarkdownExecutor({ knowledgeContent: knowledgeContent }).asPromise()];
6076
6237
  case 5:
6077
6238
  result = _k.sent();
6078
- assertsExecutionSuccessful(result);
6079
6239
  outputParameters = result.outputParameters;
6080
6240
  knowledgePiecesRaw = outputParameters.knowledgePieces;
6081
6241
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
@@ -6098,13 +6258,13 @@ var MarkdownScraper = /** @class */ (function () {
6098
6258
  _c.label = 1;
6099
6259
  case 1:
6100
6260
  _c.trys.push([1, 7, , 8]);
6101
- return [4 /*yield*/, prepareTitleExecutor({ knowledgePieceContent: knowledgePieceContent })];
6261
+ return [4 /*yield*/, prepareTitleExecutor({ knowledgePieceContent: knowledgePieceContent }).asPromise()];
6102
6262
  case 2:
6103
6263
  titleResult = _c.sent();
6104
6264
  _a = titleResult.outputParameters.title, titleRaw = _a === void 0 ? 'Untitled' : _a;
6105
6265
  title = spaceTrim(titleRaw) /* <- TODO: Maybe do in pipeline */;
6106
6266
  name = titleToName(title);
6107
- return [4 /*yield*/, prepareKeywordsExecutor({ knowledgePieceContent: knowledgePieceContent })];
6267
+ return [4 /*yield*/, prepareKeywordsExecutor({ knowledgePieceContent: knowledgePieceContent }).asPromise()];
6108
6268
  case 3:
6109
6269
  keywordsResult = _c.sent();
6110
6270
  _b = keywordsResult.outputParameters.keywords, keywordsRaw = _b === void 0 ? '' : _b;