@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/umd/index.umd.js CHANGED
@@ -1,14 +1,15 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('path'), require('crypto-js'), require('crypto-js/enc-hex'), require('mime-types'), require('papaparse')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'path', 'crypto-js', 'crypto-js/enc-hex', 'mime-types', 'papaparse'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-markdown-utils"] = {}, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.path, global.cryptoJs, global.hexEncoder, global.mimeTypes, global.papaparse));
5
- })(this, (function (exports, spaceTrim, prettier, parserHtml, waitasecond, path, cryptoJs, hexEncoder, mimeTypes, papaparse) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('rxjs'), require('crypto'), require('waitasecond'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('path'), require('crypto-js'), require('mime-types'), require('papaparse')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'spacetrim', 'prettier', 'prettier/parser-html', 'rxjs', 'crypto', 'waitasecond', 'crypto-js/enc-hex', 'crypto-js/sha256', 'path', 'crypto-js', 'mime-types', 'papaparse'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-markdown-utils"] = {}, global.spaceTrim, global.prettier, global.parserHtml, global.rxjs, global.crypto, global.waitasecond, global.hexEncoder, global.sha256, global.path, global.cryptoJs, global.mimeTypes, global.papaparse));
5
+ })(this, (function (exports, spaceTrim, prettier, parserHtml, rxjs, crypto, waitasecond, hexEncoder, sha256, path, cryptoJs, mimeTypes, papaparse) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
9
9
  var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
10
10
  var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
11
11
  var hexEncoder__default = /*#__PURE__*/_interopDefaultLegacy(hexEncoder);
12
+ var sha256__default = /*#__PURE__*/_interopDefaultLegacy(sha256);
12
13
 
13
14
  // ⚠️ WARNING: This code has been generated so that any manual changes will be overwritten
14
15
  /**
@@ -24,7 +25,7 @@
24
25
  * @generated
25
26
  * @see https://github.com/webgptorg/promptbook
26
27
  */
27
- var PROMPTBOOK_ENGINE_VERSION = '0.84.0-8';
28
+ var PROMPTBOOK_ENGINE_VERSION = '0.84.0';
28
29
  /**
29
30
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
30
31
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -362,6 +363,99 @@
362
363
 
363
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"}];
364
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
+
365
459
  /**
366
460
  * Function `validatePipelineString` will validate the if the string is a valid pipeline string
367
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.
@@ -375,6 +469,15 @@
375
469
  if (isValidJsonString(pipelineString)) {
376
470
  throw new ParseError('Expected a book, but got a JSON string');
377
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
+ }
378
481
  // <- TODO: Implement the validation + add tests when the pipeline logic considered as invalid
379
482
  return pipelineString;
380
483
  }
@@ -675,6 +778,12 @@
675
778
  * @public exported from `@promptbook/core`
676
779
  */
677
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
678
787
  // <- TODO: [🧠] Better system for generator warnings - not always "code" and "by `@promptbook/cli`"
679
788
  /**
680
789
  * The maximum number of iterations for a loops
@@ -708,6 +817,12 @@
708
817
  * @private within the repository - too low-level in comparison with other `MAX_...`
709
818
  */
710
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;
711
826
  /**
712
827
  * Strategy for caching the intermediate results for knowledge sources
713
828
  *
@@ -727,6 +842,15 @@
727
842
  * @public exported from `@promptbook/core`
728
843
  */
729
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';
730
854
  /**
731
855
  * Where to store the scrape cache
732
856
  *
@@ -1209,35 +1333,6 @@
1209
1333
  return isHostnameOnPrivateNetwork(url.hostname);
1210
1334
  }
1211
1335
 
1212
- /**
1213
- * Tests if given string is valid URL.
1214
- *
1215
- * Note: Dataurl are considered perfectly valid.
1216
- * Note: There are two simmilar functions:
1217
- * - `isValidUrl` which tests any URL
1218
- * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
1219
- *
1220
- * @public exported from `@promptbook/utils`
1221
- */
1222
- function isValidUrl(url) {
1223
- if (typeof url !== 'string') {
1224
- return false;
1225
- }
1226
- try {
1227
- if (url.startsWith('blob:')) {
1228
- url = url.replace(/^blob:/, '');
1229
- }
1230
- var urlObject = new URL(url /* because fail is handled */);
1231
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
1232
- return false;
1233
- }
1234
- return true;
1235
- }
1236
- catch (error) {
1237
- return false;
1238
- }
1239
- }
1240
-
1241
1336
  /**
1242
1337
  * Tests if given string is valid pipeline URL URL.
1243
1338
  *
@@ -1779,6 +1874,58 @@
1779
1874
  return PipelineExecutionError;
1780
1875
  }(Error));
1781
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 crypto.randomBytes(randomness).toString('hex');
1924
+ }
1925
+ /**
1926
+ * TODO: Maybe use nanoid instead https://github.com/ai/nanoid
1927
+ */
1928
+
1782
1929
  /**
1783
1930
  * This error indicates problems parsing the format value
1784
1931
  *
@@ -1992,12 +2139,28 @@
1992
2139
  /**
1993
2140
  * Asserts that the execution of a Promptbook is successful
1994
2141
  *
2142
+ * Note: If there are only warnings, the execution is still successful but the warnings are logged in the console
2143
+ *
1995
2144
  * @param executionResult - The partial result of the Promptbook execution
1996
2145
  * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
1997
- * @public exported from `@promptbook/core`
2146
+ * @private internal helper function of `asPromise` method of `ExecutionTask`
1998
2147
  */
1999
- function assertsExecutionSuccessful(executionResult) {
2000
- 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
+ }
2001
2164
  if (isSuccessful === true) {
2002
2165
  return;
2003
2166
  }
@@ -2017,121 +2180,54 @@
2017
2180
  }
2018
2181
  }
2019
2182
  /**
2020
- * TODO: [🐚] This function should be removed OR changed OR be completely rewritten
2021
2183
  * TODO: [🧠] Can this return type be better typed than void
2022
2184
  */
2023
2185
 
2024
2186
  /**
2025
- * Determine if the pipeline is fully prepared
2026
- *
2027
- * @see https://github.com/webgptorg/promptbook/discussions/196
2187
+ * Helper to create a new task
2028
2188
  *
2029
- * @public exported from `@promptbook/core`
2030
- */
2031
- function isPipelinePrepared(pipeline) {
2032
- // Note: Ignoring `pipeline.preparations` @@@
2033
- // Note: Ignoring `pipeline.knowledgePieces` @@@
2034
- if (pipeline.title === undefined || pipeline.title === '' || pipeline.title === DEFAULT_BOOK_TITLE) {
2035
- return false;
2036
- }
2037
- if (!pipeline.personas.every(function (persona) { return persona.modelRequirements !== undefined; })) {
2038
- return false;
2039
- }
2040
- if (!pipeline.knowledgeSources.every(function (knowledgeSource) { return knowledgeSource.preparationIds !== undefined; })) {
2041
- return false;
2042
- }
2043
- /*
2044
- TODO: [🧠][🍫] `tasks` can not be determined if they are fully prepared SO ignoring them
2045
- > if (!pipeline.tasks.every(({ preparedContent }) => preparedContent === undefined)) {
2046
- > return false;
2047
- > }
2048
- */
2049
- return true;
2050
- }
2051
- /**
2052
- * TODO: [🔃][main] If the pipeline was prepared with different version or different set of models, prepare it once again
2053
- * TODO: [🐠] Maybe base this on `makeValidator`
2054
- * TODO: [🧊] Pipeline can be partially prepared, this should return true ONLY if fully prepared
2055
- * TODO: [🧿] Maybe do same process with same granularity and subfinctions as `preparePipeline`
2056
- * - [🏍] ? Is context in each task
2057
- * - [♨] Are examples prepared
2058
- * - [♨] Are tasks prepared
2189
+ * @private internal helper function
2059
2190
  */
2060
-
2061
- /**
2062
- * Format either small or big number
2063
- *
2064
- * @public exported from `@promptbook/utils`
2065
- */
2066
- function numberToString(value) {
2067
- if (value === 0) {
2068
- return '0';
2069
- }
2070
- else if (Number.isNaN(value)) {
2071
- return VALUE_STRINGS.nan;
2072
- }
2073
- else if (value === Infinity) {
2074
- return VALUE_STRINGS.infinity;
2075
- }
2076
- else if (value === -Infinity) {
2077
- return VALUE_STRINGS.negativeInfinity;
2078
- }
2079
- for (var exponent = 0; exponent < 15; exponent++) {
2080
- var factor = Math.pow(10, exponent);
2081
- var valueRounded = Math.round(value * factor) / factor;
2082
- if (Math.abs(value - valueRounded) / value < SMALL_NUMBER) {
2083
- return valueRounded.toFixed(exponent);
2084
- }
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 rxjs.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
+ });
2085
2215
  }
2086
- return value.toString();
2216
+ return {
2217
+ taskType: taskType,
2218
+ taskId: taskId,
2219
+ asPromise: asPromise,
2220
+ asObservable: function () {
2221
+ return rxjs.concat(resultSubject.asObservable(), rxjs.from(asPromise({
2222
+ isCrashedOnError: true,
2223
+ })));
2224
+ },
2225
+ };
2087
2226
  }
2088
-
2089
2227
  /**
2090
- * Function `valueToString` will convert the given value to string
2091
- * This is useful and used in the `templateParameters` function
2092
- *
2093
- * Note: This function is not just calling `toString` method
2094
- * It's more complex and can handle this conversion specifically for LLM models
2095
- * See `VALUE_STRINGS`
2096
- *
2097
- * Note: There are 2 similar functions
2098
- * - `valueToString` converts value to string for LLM models as human-readable string
2099
- * - `asSerializable` converts value to string to preserve full information to be able to convert it back
2100
- *
2101
- * @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
2102
2230
  */
2103
- function valueToString(value) {
2104
- try {
2105
- if (value === '') {
2106
- return VALUE_STRINGS.empty;
2107
- }
2108
- else if (value === null) {
2109
- return VALUE_STRINGS.null;
2110
- }
2111
- else if (value === undefined) {
2112
- return VALUE_STRINGS.undefined;
2113
- }
2114
- else if (typeof value === 'string') {
2115
- return value;
2116
- }
2117
- else if (typeof value === 'number') {
2118
- return numberToString(value);
2119
- }
2120
- else if (value instanceof Date) {
2121
- return value.toISOString();
2122
- }
2123
- else {
2124
- return JSON.stringify(value);
2125
- }
2126
- }
2127
- catch (error) {
2128
- if (!(error instanceof Error)) {
2129
- throw error;
2130
- }
2131
- console.error(error);
2132
- return VALUE_STRINGS.unserializable;
2133
- }
2134
- }
2135
2231
 
2136
2232
  /**
2137
2233
  * Serializes an error into a [🚉] JSON-serializable object
@@ -2634,7 +2730,7 @@
2634
2730
  if (!(error_1 instanceof Error) || error_1 instanceof UnexpectedError) {
2635
2731
  throw error_1;
2636
2732
  }
2637
- errors.push(error_1);
2733
+ errors.push({ llmExecutionTools: llmExecutionTools, error: error_1 });
2638
2734
  return [3 /*break*/, 13];
2639
2735
  case 13:
2640
2736
  _b = _a.next();
@@ -2661,7 +2757,10 @@
2661
2757
  // 2) AnthropicClaude throw PipelineExecutionError: Parameter `{knowledge}` is not defined
2662
2758
  // 3) ...
2663
2759
  spaceTrim__default["default"](function (block) { return "\n All execution tools failed:\n\n ".concat(block(errors
2664
- .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
+ })
2665
2764
  .join('\n')), "\n\n "); }));
2666
2765
  }
2667
2766
  else if (this.llmExecutionTools.length === 0) {
@@ -2792,10 +2891,9 @@
2792
2891
  return modelName;
2793
2892
  })
2794
2893
  .join(',');
2795
- return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription })];
2894
+ return [4 /*yield*/, preparePersonaExecutor({ availableModelNames: availableModelNames, personaDescription: personaDescription }).asPromise()];
2796
2895
  case 3:
2797
2896
  result = _d.sent();
2798
- assertsExecutionSuccessful(result);
2799
2897
  outputParameters = result.outputParameters;
2800
2898
  modelRequirementsRaw = outputParameters.modelRequirements;
2801
2899
  modelRequirements = JSON.parse(modelRequirementsRaw);
@@ -3447,6 +3545,15 @@
3447
3545
  * TODO: [🐱‍🐉][🧠] Make some smart crop NOT source-i-m-pavol-a-develop-... BUT source-i-m-pavol-a-developer-...
3448
3546
  */
3449
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
+
3450
3557
  /**
3451
3558
  * Convert file extension to mime type
3452
3559
  *
@@ -3503,53 +3610,55 @@
3503
3610
  */
3504
3611
 
3505
3612
  /**
3506
- * Tests if given string is valid URL.
3613
+ * Convert mime type to file extension
3507
3614
  *
3508
- * 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 mimeTypes.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
3509
3628
  * @public exported from `@promptbook/utils`
3510
3629
  */
3511
- function isValidFilePath(filename) {
3512
- if (typeof filename !== 'string') {
3513
- return false;
3514
- }
3515
- if (filename.split('\n').length > 1) {
3516
- return false;
3517
- }
3518
- if (filename.split(' ').length >
3519
- 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
3520
- return false;
3521
- }
3522
- var filenameSlashes = filename.split('\\').join('/');
3523
- // Absolute Unix path: /hello.txt
3524
- if (/^(\/)/i.test(filenameSlashes)) {
3525
- // console.log(filename, 'Absolute Unix path: /hello.txt');
3526
- return true;
3527
- }
3528
- // Absolute Windows path: /hello.txt
3529
- if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
3530
- // console.log(filename, 'Absolute Windows path: /hello.txt');
3531
- return true;
3532
- }
3533
- // Relative path: ./hello.txt
3534
- if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
3535
- // console.log(filename, 'Relative path: ./hello.txt');
3536
- return true;
3537
- }
3538
- // Allow paths like foo/hello
3539
- if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
3540
- // console.log(filename, 'Allow paths like foo/hello');
3541
- return true;
3542
- }
3543
- // Allow paths like hello.book
3544
- if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
3545
- // console.log(filename, 'Allow paths like hello.book');
3546
- return true;
3547
- }
3548
- 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;
3549
3637
  }
3638
+
3550
3639
  /**
3551
- * TODO: [🍏] Implement for MacOs
3640
+ * @@@
3641
+ *
3642
+ * @param value @@@
3643
+ * @returns @@@
3644
+ * @example @@@
3645
+ * @public exported from `@promptbook/utils`
3552
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 = path.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
+ }
3553
3662
 
3554
3663
  /**
3555
3664
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
@@ -3586,9 +3695,9 @@
3586
3695
  function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
3587
3696
  var _a;
3588
3697
  return __awaiter(this, void 0, void 0, function () {
3589
- var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, filename_1, fileExtension, mimeType;
3590
- return __generator(this, function (_f) {
3591
- 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) {
3592
3701
  case 0:
3593
3702
  _b = tools.fetch, fetch = _b === void 0 ? scraperFetch : _b;
3594
3703
  knowledgeSourceContent = knowledgeSource.knowledgeSourceContent;
@@ -3597,54 +3706,76 @@
3597
3706
  if (!name) {
3598
3707
  name = knowledgeSourceContentToName(knowledgeSourceContent);
3599
3708
  }
3600
- if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 2];
3709
+ if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 5];
3601
3710
  url = knowledgeSourceContent;
3602
3711
  return [4 /*yield*/, fetch(url)];
3603
3712
  case 1:
3604
- response_1 = _f.sent();
3713
+ response_1 = _h.sent();
3605
3714
  mimeType = ((_a = response_1.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
3606
- return [2 /*return*/, {
3607
- source: name,
3608
- filename: null,
3609
- url: url,
3610
- mimeType: mimeType,
3611
- /*
3612
- TODO: [🥽]
3613
- > async asBlob() {
3614
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
3615
- > const content = await response.blob();
3616
- > return content;
3617
- > },
3618
- */
3619
- asJson: function () {
3620
- return __awaiter(this, void 0, void 0, function () {
3621
- var content;
3622
- return __generator(this, function (_a) {
3623
- switch (_a.label) {
3624
- case 0: return [4 /*yield*/, response_1.json()];
3625
- case 1:
3626
- content = _a.sent();
3627
- return [2 /*return*/, content];
3628
- }
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
+ });
3629
3740
  });
3630
- });
3631
- },
3632
- asText: function () {
3633
- return __awaiter(this, void 0, void 0, function () {
3634
- var content;
3635
- return __generator(this, function (_a) {
3636
- switch (_a.label) {
3637
- case 0: return [4 /*yield*/, response_1.text()];
3638
- case 1:
3639
- content = _a.sent();
3640
- return [2 /*return*/, content];
3641
- }
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
+ });
3642
3753
  });
3643
- });
3644
- },
3645
- }];
3754
+ },
3755
+ }];
3756
+ }
3757
+ basename = url.split('/').pop() || titleToName(url);
3758
+ hash = sha256__default["default"](hexEncoder__default["default"].parse(url)).toString( /* hex */);
3759
+ rootDirname_1 = path.join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
3760
+ 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));
3761
+ return [4 /*yield*/, tools.fs.mkdir(path.dirname(path.join(rootDirname_1, filepath)), { recursive: true })];
3646
3762
  case 2:
3647
- 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(path.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];
3648
3779
  if (tools.fs === undefined) {
3649
3780
  throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
3650
3781
  // <- TODO: [🧠] What is the best error type here`
@@ -3657,8 +3788,8 @@
3657
3788
  fileExtension = getFileExtension(filename_1);
3658
3789
  mimeType = extensionToMimeType(fileExtension || '');
3659
3790
  return [4 /*yield*/, isFileExisting(filename_1, tools.fs)];
3660
- case 3:
3661
- if (!(_f.sent())) {
3791
+ case 6:
3792
+ if (!(_h.sent())) {
3662
3793
  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 "); }));
3663
3794
  }
3664
3795
  // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
@@ -3704,7 +3835,7 @@
3704
3835
  });
3705
3836
  },
3706
3837
  }];
3707
- case 4: return [2 /*return*/, {
3838
+ case 7: return [2 /*return*/, {
3708
3839
  source: name,
3709
3840
  filename: null,
3710
3841
  url: null,
@@ -3968,10 +4099,9 @@
3968
4099
  var content = _a.content;
3969
4100
  return content;
3970
4101
  }).join('\n\n'),
3971
- })];
4102
+ }).asPromise()];
3972
4103
  case 2:
3973
4104
  result = _e.sent();
3974
- assertsExecutionSuccessful(result);
3975
4105
  outputParameters = result.outputParameters;
3976
4106
  titleRaw = outputParameters.title;
3977
4107
  if (isVerbose) {
@@ -4043,6 +4173,81 @@
4043
4173
  * @see https://docs.anthropic.com/en/docs/test-and-evaluate/strengthen-guardrails/increase-consistency#specify-the-desired-output-format
4044
4174
  */
4045
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
+
4046
4251
  /**
4047
4252
  * Parses the given script and returns the list of all used variables that are not defined in the script
4048
4253
  *
@@ -5371,27 +5576,20 @@
5371
5576
  */
5372
5577
  function executeTask(options) {
5373
5578
  return __awaiter(this, void 0, void 0, function () {
5374
- 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;
5375
- var e_1, _f, _g;
5376
- return __generator(this, function (_h) {
5377
- 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) {
5378
5583
  case 0:
5379
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;
5380
- name = "pipeline-executor-frame-".concat(currentTask.name);
5381
- title = currentTask.title;
5382
5585
  priority = preparedPipeline.tasks.length - preparedPipeline.tasks.indexOf(currentTask);
5383
5586
  return [4 /*yield*/, onProgress({
5384
- name: name,
5385
- title: title,
5386
- isStarted: false,
5387
- isDone: false,
5388
- taskType: currentTask.taskType,
5389
- parameterName: currentTask.resultingParameterName,
5390
- parameterValue: null,
5391
- // <- [🍸]
5587
+ outputParameters: (_f = {},
5588
+ _f[currentTask.resultingParameterName] = '',
5589
+ _f),
5392
5590
  })];
5393
5591
  case 1:
5394
- _h.sent();
5592
+ _k.sent();
5395
5593
  usedParameterNames = extractParameterNamesFromTask(currentTask);
5396
5594
  dependentParameterNames = new Set(currentTask.dependentParameterNames);
5397
5595
  // TODO: [👩🏾‍🤝‍👩🏻] Use here `mapAvailableToExpectedParameters`
@@ -5410,7 +5608,7 @@
5410
5608
  pipelineIdentification: pipelineIdentification,
5411
5609
  })];
5412
5610
  case 2:
5413
- 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])]);
5414
5612
  definedParameterNames = new Set(Object.keys(definedParameters));
5415
5613
  parameters = {};
5416
5614
  _loop_1 = function (parameterName) {
@@ -5438,7 +5636,7 @@
5438
5636
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
5439
5637
  finally {
5440
5638
  try {
5441
- if (_e && !_e.done && (_f = _d.return)) _f.call(_d);
5639
+ if (_e && !_e.done && (_g = _d.return)) _g.call(_d);
5442
5640
  }
5443
5641
  finally { if (e_1) throw e_1.error; }
5444
5642
  }
@@ -5469,24 +5667,19 @@
5469
5667
  isNotPreparedWarningSupressed: isNotPreparedWarningSupressed,
5470
5668
  })];
5471
5669
  case 3:
5472
- resultString = _h.sent();
5670
+ resultString = _k.sent();
5473
5671
  return [4 /*yield*/, onProgress({
5474
- name: name,
5475
- title: title,
5476
- isStarted: true,
5477
- isDone: true,
5478
- taskType: currentTask.taskType,
5479
- parameterName: currentTask.resultingParameterName,
5480
- parameterValue: resultString,
5481
- // <- [🍸]
5672
+ outputParameters: (_h = {},
5673
+ _h[currentTask.resultingParameterName] = resultString,
5674
+ _h),
5482
5675
  })];
5483
5676
  case 4:
5484
- _h.sent();
5485
- return [2 /*return*/, Object.freeze((_g = {},
5486
- _g[currentTask.resultingParameterName] =
5677
+ _k.sent();
5678
+ return [2 /*return*/, Object.freeze((_j = {},
5679
+ _j[currentTask.resultingParameterName] =
5487
5680
  // <- Note: [👩‍👩‍👧] No need to detect parameter collision here because pipeline checks logic consistency during construction
5488
5681
  resultString,
5489
- _g))];
5682
+ _j))];
5490
5683
  }
5491
5684
  });
5492
5685
  });
@@ -5494,9 +5687,6 @@
5494
5687
  /**
5495
5688
  * TODO: [🤹‍♂️]
5496
5689
  */
5497
- /**
5498
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
5499
- */
5500
5690
 
5501
5691
  /**
5502
5692
  * @@@
@@ -5758,15 +5948,15 @@
5758
5948
  return [3 /*break*/, 4];
5759
5949
  case 3:
5760
5950
  unresovedTasks_1 = unresovedTasks_1.filter(function (task) { return task !== currentTask; });
5761
- 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) {
5762
5952
  if (isReturned) {
5763
- 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)
5953
+ 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)
5764
5954
  .split('\n')
5765
5955
  .map(function (line) { return "> ".concat(line); })
5766
5956
  .join('\n')), "\n "); }));
5767
5957
  }
5768
5958
  if (onProgress) {
5769
- onProgress(progress);
5959
+ onProgress(newOngoingResult);
5770
5960
  }
5771
5961
  }, $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 "); }) }))
5772
5962
  .then(function (newParametersToPass) {
@@ -5869,9 +6059,6 @@
5869
6059
  });
5870
6060
  });
5871
6061
  }
5872
- /**
5873
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
5874
- */
5875
6062
 
5876
6063
  /**
5877
6064
  * Creates executor function from pipeline and execution tools.
@@ -5903,7 +6090,7 @@
5903
6090
  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 "); }));
5904
6091
  }
5905
6092
  var runCount = 0;
5906
- 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 () {
5907
6094
  return __generator(this, function (_a) {
5908
6095
  runCount++;
5909
6096
  return [2 /*return*/, /* not await */ executePipeline({
@@ -5928,51 +6115,23 @@
5928
6115
  })];
5929
6116
  });
5930
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`
5931
6133
  return pipelineExecutor;
5932
6134
  }
5933
- /**
5934
- * TODO: [🐚] Change onProgress to object that represents the running execution, can be subscribed via RxJS to and also awaited
5935
- */
5936
-
5937
- /**
5938
- * Removes emojis from a string and fix whitespaces
5939
- *
5940
- * @param text with emojis
5941
- * @returns text without emojis
5942
- * @public exported from `@promptbook/utils`
5943
- */
5944
- function removeEmojis(text) {
5945
- // Replace emojis (and also ZWJ sequence) with hyphens
5946
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
5947
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
5948
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
5949
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
5950
- return text;
5951
- }
5952
-
5953
- /**
5954
- * @@@
5955
- *
5956
- * @param value @@@
5957
- * @returns @@@
5958
- * @example @@@
5959
- * @public exported from `@promptbook/utils`
5960
- */
5961
- function titleToName(value) {
5962
- if (isValidUrl(value)) {
5963
- value = value.replace(/^https?:\/\//, '');
5964
- value = value.replace(/\.html$/, '');
5965
- }
5966
- else if (isValidFilePath(value)) {
5967
- value = path.basename(value);
5968
- // Note: Keeping extension in the name
5969
- }
5970
- value = value.split('/').join('-');
5971
- value = removeEmojis(value);
5972
- value = normalizeToKebabCase(value);
5973
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
5974
- return value;
5975
- }
5976
6135
 
5977
6136
  /**
5978
6137
  * Metadata of the scraper
@@ -6074,10 +6233,9 @@
6074
6233
  return [4 /*yield*/, source.asText()];
6075
6234
  case 4:
6076
6235
  knowledgeContent = _k.sent();
6077
- return [4 /*yield*/, prepareKnowledgeFromMarkdownExecutor({ knowledgeContent: knowledgeContent })];
6236
+ return [4 /*yield*/, prepareKnowledgeFromMarkdownExecutor({ knowledgeContent: knowledgeContent }).asPromise()];
6078
6237
  case 5:
6079
6238
  result = _k.sent();
6080
- assertsExecutionSuccessful(result);
6081
6239
  outputParameters = result.outputParameters;
6082
6240
  knowledgePiecesRaw = outputParameters.knowledgePieces;
6083
6241
  knowledgeTextPieces = (knowledgePiecesRaw || '').split('\n---\n');
@@ -6100,13 +6258,13 @@
6100
6258
  _c.label = 1;
6101
6259
  case 1:
6102
6260
  _c.trys.push([1, 7, , 8]);
6103
- return [4 /*yield*/, prepareTitleExecutor({ knowledgePieceContent: knowledgePieceContent })];
6261
+ return [4 /*yield*/, prepareTitleExecutor({ knowledgePieceContent: knowledgePieceContent }).asPromise()];
6104
6262
  case 2:
6105
6263
  titleResult = _c.sent();
6106
6264
  _a = titleResult.outputParameters.title, titleRaw = _a === void 0 ? 'Untitled' : _a;
6107
6265
  title = spaceTrim__default["default"](titleRaw) /* <- TODO: Maybe do in pipeline */;
6108
6266
  name = titleToName(title);
6109
- return [4 /*yield*/, prepareKeywordsExecutor({ knowledgePieceContent: knowledgePieceContent })];
6267
+ return [4 /*yield*/, prepareKeywordsExecutor({ knowledgePieceContent: knowledgePieceContent }).asPromise()];
6110
6268
  case 3:
6111
6269
  keywordsResult = _c.sent();
6112
6270
  _b = keywordsResult.outputParameters.keywords, keywordsRaw = _b === void 0 ? '' : _b;