@promptbook/fake-llm 0.105.0-9 → 0.106.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 (113) hide show
  1. package/esm/index.es.js +150 -4044
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/src/_packages/browser.index.d.ts +2 -0
  4. package/esm/typings/src/_packages/components.index.d.ts +20 -0
  5. package/esm/typings/src/_packages/core.index.d.ts +21 -11
  6. package/esm/typings/src/_packages/node.index.d.ts +2 -0
  7. package/esm/typings/src/_packages/openai.index.d.ts +4 -0
  8. package/esm/typings/src/_packages/types.index.d.ts +32 -2
  9. package/esm/typings/src/_packages/utils.index.d.ts +2 -0
  10. package/esm/typings/src/book-2.0/agent-source/AgentBasicInformation.d.ts +10 -1
  11. package/esm/typings/src/book-2.0/agent-source/parseTeamCommitment.d.ts +28 -0
  12. package/esm/typings/src/book-components/BookEditor/BookEditor.d.ts +1 -1
  13. package/esm/typings/src/book-components/Chat/AgentChat/AgentChatProps.d.ts +5 -0
  14. package/esm/typings/src/book-components/Chat/AgentChip/AgentChip.d.ts +67 -0
  15. package/esm/typings/src/book-components/Chat/AgentChip/index.d.ts +2 -0
  16. package/esm/typings/src/book-components/Chat/Chat/ChatMessageItem.d.ts +33 -1
  17. package/esm/typings/src/book-components/Chat/Chat/ChatProps.d.ts +87 -6
  18. package/esm/typings/src/book-components/Chat/Chat/ChatSoundToggle.d.ts +23 -0
  19. package/esm/typings/src/book-components/Chat/Chat/ClockIcon.d.ts +9 -0
  20. package/esm/typings/src/book-components/Chat/LlmChat/FriendlyErrorMessage.d.ts +20 -0
  21. package/esm/typings/src/book-components/Chat/LlmChat/LlmChatProps.d.ts +13 -0
  22. package/esm/typings/src/book-components/Chat/SourceChip/SourceChip.d.ts +35 -0
  23. package/esm/typings/src/book-components/Chat/SourceChip/index.d.ts +2 -0
  24. package/esm/typings/src/book-components/Chat/effects/ChatEffectsSystem.d.ts +14 -0
  25. package/esm/typings/src/book-components/Chat/effects/components/ConfettiEffect.d.ts +18 -0
  26. package/esm/typings/src/book-components/Chat/effects/components/HeartsEffect.d.ts +18 -0
  27. package/esm/typings/src/book-components/Chat/effects/configs/defaultEffectConfigs.d.ts +7 -0
  28. package/esm/typings/src/book-components/Chat/effects/index.d.ts +18 -0
  29. package/esm/typings/src/book-components/Chat/effects/types/ChatEffect.d.ts +20 -0
  30. package/esm/typings/src/book-components/Chat/effects/types/ChatEffectConfig.d.ts +21 -0
  31. package/esm/typings/src/book-components/Chat/effects/types/ChatEffectType.d.ts +6 -0
  32. package/esm/typings/src/book-components/Chat/effects/types/ChatEffectsSystemProps.d.ts +32 -0
  33. package/esm/typings/src/book-components/Chat/effects/utils/detectEffects.d.ts +12 -0
  34. package/esm/typings/src/book-components/Chat/types/ChatMessage.d.ts +34 -6
  35. package/esm/typings/src/book-components/Chat/types/ChatParticipant.d.ts +8 -0
  36. package/esm/typings/src/book-components/Chat/utils/createTeamToolNameFromUrl.d.ts +12 -0
  37. package/esm/typings/src/book-components/Chat/utils/getToolCallChipletText.d.ts +40 -0
  38. package/esm/typings/src/book-components/Chat/utils/loadAgentProfile.d.ts +69 -0
  39. package/esm/typings/src/book-components/Chat/utils/parseCitationsFromContent.d.ts +53 -0
  40. package/esm/typings/src/book-components/Chat/utils/resolveCitationUrl.d.ts +11 -0
  41. package/esm/typings/src/book-components/Chat/utils/resolveCitationUrl.test.d.ts +1 -0
  42. package/esm/typings/src/book-components/Chat/utils/toolCallParsing.d.ts +64 -0
  43. package/esm/typings/src/book-components/icons/EmailIcon.d.ts +15 -0
  44. package/esm/typings/src/commitments/TEAM/TEAM.d.ts +45 -0
  45. package/esm/typings/src/commitments/TEMPLATE/TEMPLATE.d.ts +44 -0
  46. package/esm/typings/src/commitments/TEMPLATE/TEMPLATE.test.d.ts +1 -0
  47. package/esm/typings/src/commitments/USE_BROWSER/USE_BROWSER.d.ts +19 -1
  48. package/esm/typings/src/commitments/USE_BROWSER/fetchUrlContent.d.ts +22 -0
  49. package/esm/typings/src/commitments/USE_BROWSER/fetchUrlContentViaBrowser.d.ts +13 -0
  50. package/esm/typings/src/commitments/USE_EMAIL/USE_EMAIL.d.ts +48 -0
  51. package/esm/typings/src/commitments/USE_EMAIL/resolveSendEmailToolForNode.d.ts +11 -0
  52. package/esm/typings/src/commitments/USE_EMAIL/sendEmailViaBrowser.d.ts +18 -0
  53. package/esm/typings/src/commitments/USE_IMAGE_GENERATOR/USE_IMAGE_GENERATOR.d.ts +46 -0
  54. package/esm/typings/src/commitments/USE_IMAGE_GENERATOR/USE_IMAGE_GENERATOR.test.d.ts +1 -0
  55. package/esm/typings/src/commitments/USE_SEARCH_ENGINE/USE_SEARCH_ENGINE.d.ts +5 -0
  56. package/esm/typings/src/commitments/USE_SEARCH_ENGINE/USE_SEARCH_ENGINE.test.d.ts +1 -0
  57. package/esm/typings/src/commitments/USE_TIME/USE_TIME.d.ts +6 -0
  58. package/esm/typings/src/commitments/_base/BaseCommitmentDefinition.d.ts +6 -0
  59. package/esm/typings/src/commitments/_base/CommitmentDefinition.d.ts +6 -0
  60. package/esm/typings/src/commitments/_base/formatOptionalInstructionBlock.d.ts +6 -0
  61. package/esm/typings/src/commitments/_common/commitmentToolFunctions.d.ts +26 -0
  62. package/esm/typings/src/commitments/_common/getAllCommitmentDefinitions.d.ts +8 -0
  63. package/esm/typings/src/commitments/_common/getAllCommitmentTypes.d.ts +8 -0
  64. package/esm/typings/src/commitments/_common/getAllCommitmentsToolFunctionsForBrowser.d.ts +9 -0
  65. package/esm/typings/src/commitments/_common/getAllCommitmentsToolFunctionsForNode.d.ts +13 -0
  66. package/esm/typings/src/commitments/_common/getAllCommitmentsToolTitles.d.ts +7 -0
  67. package/esm/typings/src/commitments/_common/getCommitmentDefinition.d.ts +10 -0
  68. package/esm/typings/src/commitments/_common/getGroupedCommitmentDefinitions.d.ts +17 -0
  69. package/esm/typings/src/commitments/_common/isCommitmentSupported.d.ts +9 -0
  70. package/esm/typings/src/commitments/index.d.ts +5 -58
  71. package/esm/typings/src/config.d.ts +6 -0
  72. package/esm/typings/src/constants.d.ts +129 -0
  73. package/esm/typings/src/executables/$provideExecutablesForNode.d.ts +1 -0
  74. package/esm/typings/src/execution/AvailableModel.d.ts +5 -4
  75. package/esm/typings/src/execution/PromptResult.d.ts +2 -19
  76. package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +1 -1
  77. package/esm/typings/src/execution/utils/$provideExecutionToolsForNode.d.ts +1 -0
  78. package/esm/typings/src/llm-providers/agent/Agent.d.ts +15 -1
  79. package/esm/typings/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +6 -1
  80. package/esm/typings/src/llm-providers/agent/RemoteAgent.d.ts +5 -0
  81. package/esm/typings/src/llm-providers/google/createGoogleExecutionTools.d.ts +1 -0
  82. package/esm/typings/src/llm-providers/openai/OpenAiAgentExecutionTools.d.ts +43 -0
  83. package/esm/typings/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +4 -2
  84. package/esm/typings/src/llm-providers/openai/OpenAiCompatibleExecutionTools.d.ts +1 -1
  85. package/esm/typings/src/llm-providers/openai/createOpenAiAgentExecutionTools.d.ts +11 -0
  86. package/esm/typings/src/llm-providers/openai/utils/uploadFilesToOpenAi.d.ts +7 -0
  87. package/esm/typings/src/pipeline/prompt-notation.d.ts +27 -2
  88. package/esm/typings/src/pipeline/prompt-notation.test.d.ts +1 -1
  89. package/esm/typings/src/scrapers/_common/register/$provideFilesystemForNode.d.ts +1 -0
  90. package/esm/typings/src/scrapers/_common/register/$provideScrapersForNode.d.ts +1 -0
  91. package/esm/typings/src/scrapers/_common/register/$provideScriptingForNode.d.ts +1 -0
  92. package/esm/typings/src/search-engines/SearchEngine.d.ts +1 -1
  93. package/esm/typings/src/search-engines/bing/BingSearchEngine.d.ts +1 -1
  94. package/esm/typings/src/search-engines/dummy/DummySearchEngine.d.ts +1 -1
  95. package/esm/typings/src/search-engines/google/GoogleSearchEngine.d.ts +1 -1
  96. package/esm/typings/src/search-engines/serp/SerpSearchEngine.d.ts +1 -1
  97. package/esm/typings/src/speech-recognition/OpenAiSpeechRecognition.d.ts +3 -0
  98. package/esm/typings/src/types/ModelRequirements.d.ts +6 -0
  99. package/esm/typings/src/types/Prompt.d.ts +12 -0
  100. package/esm/typings/src/types/ToolCall.d.ts +37 -0
  101. package/esm/typings/src/utils/markdown/extractAllListItemsFromMarkdown.d.ts +1 -2
  102. package/esm/typings/src/utils/markdown/humanizeAiTextEllipsis.d.ts +1 -1
  103. package/esm/typings/src/utils/markdown/humanizeAiTextEmdashed.d.ts +1 -1
  104. package/esm/typings/src/utils/markdown/humanizeAiTextWhitespace.d.ts +1 -1
  105. package/esm/typings/src/utils/markdown/parseMarkdownSection.d.ts +1 -3
  106. package/esm/typings/src/utils/markdown/splitMarkdownIntoSections.d.ts +1 -2
  107. package/esm/typings/src/utils/misc/linguisticHash.d.ts +4 -1
  108. package/esm/typings/src/utils/parameters/templateParameters.d.ts +1 -2
  109. package/esm/typings/src/version.d.ts +1 -1
  110. package/esm/typings/src/wizard/wizard.d.ts +1 -4
  111. package/package.json +2 -2
  112. package/umd/index.umd.js +150 -4044
  113. package/umd/index.umd.js.map +1 -1
package/esm/index.es.js CHANGED
@@ -20,7 +20,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
20
20
  * @generated
21
21
  * @see https://github.com/webgptorg/promptbook
22
22
  */
23
- const PROMPTBOOK_ENGINE_VERSION = '0.105.0-9';
23
+ const PROMPTBOOK_ENGINE_VERSION = '0.106.0-0';
24
24
  /**
25
25
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
26
26
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -1684,7 +1684,7 @@ function templateParameters(template, parameters) {
1684
1684
  parameterValue = parameterValue.replace(/[{}]/g, '\\$&');
1685
1685
  if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
1686
1686
  parameterValue = parameterValue
1687
- .split('\n')
1687
+ .split(/\r?\n/)
1688
1688
  .map((line, index) => (index === 0 ? line : `${precol}${line}`))
1689
1689
  .join('\n');
1690
1690
  }
@@ -1902,7 +1902,7 @@ function countLines(text) {
1902
1902
  }
1903
1903
  text = text.replace('\r\n', '\n');
1904
1904
  text = text.replace('\r', '\n');
1905
- const lines = text.split('\n');
1905
+ const lines = text.split(/\r?\n/);
1906
1906
  return lines.reduce((count, line) => count + Math.max(Math.ceil(line.length / CHARACTERS_PER_STANDARD_LINE), 1), 0);
1907
1907
  }
1908
1908
  /**
@@ -2362,93 +2362,6 @@ function normalizeTo_camelCase(text, _isFirstLetterCapital = false) {
2362
2362
  * TODO: [🌺] Use some intermediate util splitWords
2363
2363
  */
2364
2364
 
2365
- /**
2366
- * Tests if given string is valid file path.
2367
- *
2368
- * Note: This does not check if the file exists only if the path is valid
2369
- * @public exported from `@promptbook/utils`
2370
- */
2371
- function isValidFilePath(filename) {
2372
- if (typeof filename !== 'string') {
2373
- return false;
2374
- }
2375
- if (filename.split('\n').length > 1) {
2376
- return false;
2377
- }
2378
- // Normalize slashes early so heuristics can detect path-like inputs
2379
- const filenameSlashes = filename.replace(/\\/g, '/');
2380
- // Reject strings that look like sentences (informational text)
2381
- // Heuristic: contains multiple spaces and ends with a period, or contains typical sentence punctuation
2382
- // But skip this heuristic if the string looks like a path (contains '/' or starts with a drive letter)
2383
- if (filename.trim().length > 60 && // long enough to be a sentence
2384
- /[.!?]/.test(filename) && // contains sentence punctuation
2385
- filename.split(' ').length > 8 && // has many words
2386
- !/\/|^[A-Z]:/i.test(filenameSlashes) // do NOT treat as sentence if looks like a path
2387
- ) {
2388
- return false;
2389
- }
2390
- // Absolute Unix path: /hello.txt
2391
- if (/^(\/)/i.test(filenameSlashes)) {
2392
- // console.log(filename, 'Absolute Unix path: /hello.txt');
2393
- return true;
2394
- }
2395
- // Absolute Windows path: C:/ or C:\ (allow spaces and multiple dots in filename)
2396
- if (/^[A-Z]:\/.+$/i.test(filenameSlashes)) {
2397
- // console.log(filename, 'Absolute Windows path: /hello.txt');
2398
- return true;
2399
- }
2400
- // Relative path: ./hello.txt
2401
- if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
2402
- // console.log(filename, 'Relative path: ./hello.txt');
2403
- return true;
2404
- }
2405
- // Allow paths like foo/hello
2406
- if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
2407
- // console.log(filename, 'Allow paths like foo/hello');
2408
- return true;
2409
- }
2410
- // Allow paths like hello.book
2411
- if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
2412
- // console.log(filename, 'Allow paths like hello.book');
2413
- return true;
2414
- }
2415
- return false;
2416
- }
2417
- /**
2418
- * TODO: [🍏] Implement for MacOs
2419
- */
2420
-
2421
- /**
2422
- * Tests if given string is valid URL.
2423
- *
2424
- * Note: [🔂] This function is idempotent.
2425
- * Note: Dataurl are considered perfectly valid.
2426
- * Note: There are few similar functions:
2427
- * - `isValidUrl` *(this one)* which tests any URL
2428
- * - `isValidAgentUrl` which tests just agent URL
2429
- * - `isValidPipelineUrl` which tests just pipeline URL
2430
- *
2431
- * @public exported from `@promptbook/utils`
2432
- */
2433
- function isValidUrl(url) {
2434
- if (typeof url !== 'string') {
2435
- return false;
2436
- }
2437
- try {
2438
- if (url.startsWith('blob:')) {
2439
- url = url.replace(/^blob:/, '');
2440
- }
2441
- const urlObject = new URL(url /* because fail is handled */);
2442
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
2443
- return false;
2444
- }
2445
- return true;
2446
- }
2447
- catch (error) {
2448
- return false;
2449
- }
2450
- }
2451
-
2452
2365
  /**
2453
2366
  * Converts a given text to kebab-case format.
2454
2367
  *
@@ -2844,3989 +2757,193 @@ function unwrapResult(text, options) {
2844
2757
  */
2845
2758
 
2846
2759
  /**
2847
- * Tests if given string is valid agent URL
2760
+ * Extracts all code blocks from markdown.
2848
2761
  *
2849
- * Note: There are few similar functions:
2850
- * - `isValidUrl` which tests any URL
2851
- * - `isValidAgentUrl` *(this one)* which tests just agent URL
2852
- * - `isValidPipelineUrl` which tests just pipeline URL
2762
+ * Note: There are multiple similar functions:
2763
+ * - `extractBlock` just extracts the content of the code block which is also used as built-in function for postprocessing
2764
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2765
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2766
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2853
2767
  *
2854
- * @public exported from `@promptbook/utils`
2768
+ * @param markdown any valid markdown
2769
+ * @returns code blocks with language and content
2770
+ * @throws {ParseError} if block is not closed properly
2771
+ * @public exported from `@promptbook/markdown-utils`
2855
2772
  */
2856
- function isValidAgentUrl(url) {
2857
- if (!isValidUrl(url)) {
2858
- return false;
2859
- }
2860
- if (!url.startsWith('https://') && !url.startsWith('http://') /* <- Note: [👣] */) {
2861
- return false;
2862
- }
2863
- if (url.includes('#')) {
2864
- // TODO: [🐠]
2865
- return false;
2773
+ function extractAllBlocksFromMarkdown(markdown) {
2774
+ const codeBlocks = [];
2775
+ const lines = markdown.split(/\r?\n/);
2776
+ // Note: [0] Ensure that the last block notated by gt > will be closed
2777
+ lines.push('');
2778
+ let currentCodeBlock = null;
2779
+ for (const line of lines) {
2780
+ if (line.startsWith('> ') || line === '>') {
2781
+ if (currentCodeBlock === null) {
2782
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2783
+ } /* not else */
2784
+ if (currentCodeBlock.blockNotation === '>') {
2785
+ if (currentCodeBlock.content !== '') {
2786
+ currentCodeBlock.content += '\n';
2787
+ }
2788
+ currentCodeBlock.content += line.slice(2);
2789
+ }
2790
+ }
2791
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2792
+ codeBlocks.push(currentCodeBlock);
2793
+ currentCodeBlock = null;
2794
+ }
2795
+ /* not else */
2796
+ if (line.startsWith('```')) {
2797
+ const language = line.slice(3).trim() || null;
2798
+ if (currentCodeBlock === null) {
2799
+ currentCodeBlock = { blockNotation: '```', language, content: '' };
2800
+ }
2801
+ else {
2802
+ if (language !== null) {
2803
+ throw new ParseError(`${capitalize(currentCodeBlock.language || 'the')} code block was not closed and already opening new ${language} code block`);
2804
+ }
2805
+ codeBlocks.push(currentCodeBlock);
2806
+ currentCodeBlock = null;
2807
+ }
2808
+ }
2809
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2810
+ if (currentCodeBlock.content !== '') {
2811
+ currentCodeBlock.content += '\n';
2812
+ }
2813
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make proper unescape */;
2814
+ }
2866
2815
  }
2867
- /*
2868
- Note: [👣][🧠] Is it secure to allow pipeline URLs on private and unsecured networks?
2869
- if (isUrlOnPrivateNetwork(url)) {
2870
- return false;
2816
+ if (currentCodeBlock !== null) {
2817
+ throw new ParseError(`${capitalize(currentCodeBlock.language || 'the')} code block was not closed at the end of the markdown`);
2871
2818
  }
2872
- */
2873
- return true;
2819
+ return codeBlocks;
2874
2820
  }
2875
2821
  /**
2876
- * TODO: [🐠] Maybe more info why the URL is invalid
2822
+ * TODO: Maybe name for `blockNotation` instead of '```' and '>'
2877
2823
  */
2878
2824
 
2879
2825
  /**
2880
- * Generates a regex pattern to match a specific commitment
2826
+ * Extracts exactly ONE code block from markdown.
2881
2827
  *
2882
- * Note: It always creates new Regex object
2883
- * Note: Uses word boundaries to ensure only full words are matched (e.g., "PERSONA" matches but "PERSONALITY" does not)
2828
+ * - When there are multiple or no code blocks the function throws a `ParseError`
2829
+ *
2830
+ * Note: There are multiple similar functions:
2831
+ * - `extractBlock` just extracts the content of the code block which is also used as built-in function for postprocessing
2832
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2833
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2834
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2884
2835
  *
2885
- * @private - TODO: [🧠] Maybe should be public?
2836
+ * @param markdown any valid markdown
2837
+ * @returns code block with language and content
2838
+ * @public exported from `@promptbook/markdown-utils`
2839
+ * @throws {ParseError} if there is not exactly one code block in the markdown
2886
2840
  */
2887
- function createCommitmentRegex(commitment, aliases = [], requiresContent = true) {
2888
- const allCommitments = [commitment, ...aliases];
2889
- const patterns = allCommitments.map((commitment) => {
2890
- const escapedCommitment = commitment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2891
- return escapedCommitment.split(/\s+/).join('\\s+');
2892
- });
2893
- const keywordPattern = patterns.join('|');
2894
- if (requiresContent) {
2895
- return new RegExp(`^\\s*(?<type>${keywordPattern})\\b\\s+(?<contents>.+)$`, 'gim');
2896
- }
2897
- else {
2898
- return new RegExp(`^\\s*(?<type>${keywordPattern})\\b(?:\\s+(?<contents>.+))?$`, 'gim');
2841
+ function extractOneBlockFromMarkdown(markdown) {
2842
+ const codeBlocks = extractAllBlocksFromMarkdown(markdown);
2843
+ if (codeBlocks.length !== 1) {
2844
+ throw new ParseError(spaceTrim$2((block) => `
2845
+ There should be exactly 1 code block in task section, found ${codeBlocks.length} code blocks
2846
+
2847
+ ${block(codeBlocks.map((block, i) => `Block ${i + 1}:\n${block.content}`).join('\n\n\n'))}
2848
+ `));
2899
2849
  }
2850
+ return codeBlocks[0];
2900
2851
  }
2852
+ /***
2853
+ * TODO: [🍓][🌻] Decide of this is internal utility, external util OR validator/postprocessor
2854
+ */
2855
+
2901
2856
  /**
2902
- * Generates a regex pattern to match a specific commitment type
2857
+ * Extracts code block from markdown.
2903
2858
  *
2904
- * Note: It just matches the type part of the commitment
2905
- * Note: It always creates new Regex object
2906
- * Note: Uses word boundaries to ensure only full words are matched (e.g., "PERSONA" matches but "PERSONALITY" does not)
2859
+ * - When there are multiple or no code blocks the function throws a `ParseError`
2860
+ *
2861
+ * Note: There are multiple similar function:
2862
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2863
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
2864
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2865
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2907
2866
  *
2908
- * @private
2867
+ * @public exported from `@promptbook/markdown-utils`
2868
+ * @throws {ParseError} if there is not exactly one code block in the markdown
2909
2869
  */
2910
- function createCommitmentTypeRegex(commitment, aliases = []) {
2911
- const allCommitments = [commitment, ...aliases];
2912
- const patterns = allCommitments.map((commitment) => {
2913
- const escapedCommitment = commitment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2914
- return escapedCommitment.split(/\s+/).join('\\s+');
2915
- });
2916
- const keywordPattern = patterns.join('|');
2917
- const regex = new RegExp(`^\\s*(?<type>${keywordPattern})\\b`, 'gim');
2918
- return regex;
2870
+ function extractBlock(markdown) {
2871
+ const { content } = extractOneBlockFromMarkdown(markdown);
2872
+ return content;
2919
2873
  }
2920
2874
 
2921
2875
  /**
2922
- * Base implementation of CommitmentDefinition that provides common functionality
2923
- * Most commitments can extend this class and only override the applyToAgentModelRequirements method
2876
+ * Prettify the html code
2924
2877
  *
2925
- * @private
2878
+ * @param content raw html code
2879
+ * @returns formatted html code
2880
+ * @private withing the package because of HUGE size of prettier dependency
2881
+ * @deprecated Prettier removed from Promptbook due to package size
2926
2882
  */
2927
- class BaseCommitmentDefinition {
2928
- constructor(type, aliases = []) {
2929
- this.type = type;
2930
- this.aliases = aliases;
2931
- }
2932
- /**
2933
- * Whether this commitment requires content.
2934
- * If true, regex will match only if there is content after the commitment keyword.
2935
- * If false, regex will match even if there is no content.
2936
- */
2937
- get requiresContent() {
2938
- return true;
2939
- }
2940
- /**
2941
- * Creates a regex pattern to match this commitment in agent source
2942
- * Uses the existing createCommitmentRegex function as internal helper
2943
- */
2944
- createRegex() {
2945
- return createCommitmentRegex(this.type, this.aliases, this.requiresContent);
2946
- }
2947
- /**
2948
- * Creates a regex pattern to match just the commitment type
2949
- * Uses the existing createCommitmentTypeRegex function as internal helper
2950
- */
2951
- createTypeRegex() {
2952
- return createCommitmentTypeRegex(this.type, this.aliases);
2953
- }
2954
- /**
2955
- * Helper method to create a new requirements object with updated system message
2956
- * This is commonly used by many commitments
2957
- */
2958
- updateSystemMessage(requirements, messageUpdate) {
2959
- const newMessage = typeof messageUpdate === 'string' ? messageUpdate : messageUpdate(requirements.systemMessage);
2960
- return {
2961
- ...requirements,
2962
- systemMessage: newMessage,
2963
- };
2964
- }
2965
- /**
2966
- * Helper method to append content to the system message
2967
- */
2968
- appendToSystemMessage(requirements, content, separator = '\n\n') {
2969
- return this.updateSystemMessage(requirements, (currentMessage) => {
2970
- if (!currentMessage.trim()) {
2971
- return content;
2972
- }
2973
- return currentMessage + separator + content;
2974
- });
2975
- }
2976
- /**
2977
- * Helper method to add a comment section to the system message
2978
- * Comments are lines starting with # that will be removed from the final system message
2979
- * but can be useful for organizing and structuring the message during processing
2980
- */
2981
- addCommentSection(requirements, commentTitle, content, position = 'end') {
2982
- const commentSection = `# ${commentTitle.toUpperCase()}\n${content}`;
2983
- if (position === 'beginning') {
2984
- return this.updateSystemMessage(requirements, (currentMessage) => {
2985
- if (!currentMessage.trim()) {
2986
- return commentSection;
2987
- }
2988
- return commentSection + '\n\n' + currentMessage;
2989
- });
2990
- }
2991
- else {
2992
- return this.appendToSystemMessage(requirements, commentSection);
2993
- }
2994
- }
2995
- /**
2996
- * Gets tool function implementations provided by this commitment
2997
- *
2998
- * When the `applyToAgentModelRequirements` adds tools to the requirements, this method should return the corresponding function definitions.
2999
- */
3000
- getToolFunctions() {
3001
- return {};
3002
- }
2883
+ function prettifyMarkdown(content) {
2884
+ return (content + `\n\n<!-- Note: Prettier removed from Promptbook -->`);
3003
2885
  }
3004
2886
 
3005
2887
  /**
3006
- * ACTION commitment definition
3007
- *
3008
- * The ACTION commitment defines specific actions or capabilities that the agent can perform.
3009
- * This helps define what the agent is capable of doing and how it should approach tasks.
3010
- *
3011
- * Example usage in agent source:
2888
+ * Function trimCodeBlock will trim starting and ending code block from the string if it is present.
3012
2889
  *
3013
- * ```book
3014
- * ACTION Can generate code snippets and explain programming concepts
3015
- * ACTION Able to analyze data and provide insights
3016
- * ```
2890
+ * Note: [🔂] This function is idempotent.
2891
+ * Note: This is useful for post-processing of the result of the chat LLM model
2892
+ * when the model wraps the result in the (markdown) code block.
3017
2893
  *
3018
- * @private [🪔] Maybe export the commitments through some package
2894
+ * @public exported from `@promptbook/markdown-utils`
3019
2895
  */
3020
- class ActionCommitmentDefinition extends BaseCommitmentDefinition {
3021
- constructor(type = 'ACTION') {
3022
- super(type);
3023
- }
3024
- /**
3025
- * Short one-line description of ACTION.
3026
- */
3027
- get description() {
3028
- return 'Define agent capabilities and actions it can perform.';
3029
- }
3030
- /**
3031
- * Icon for this commitment.
3032
- */
3033
- get icon() {
3034
- return '⚡';
2896
+ function trimCodeBlock(value) {
2897
+ value = spaceTrim$1(value);
2898
+ if (!/^```[a-z]*(.*)```$/is.test(value)) {
2899
+ return value;
3035
2900
  }
3036
- /**
3037
- * Markdown documentation for ACTION commitment.
3038
- */
3039
- get documentation() {
3040
- return spaceTrim$1(`
3041
- # ${this.type}
3042
-
3043
- Defines specific actions or capabilities that the agent can perform.
3044
-
3045
- ## Key aspects
3046
-
3047
- - Both terms work identically and can be used interchangeably.
3048
- - Each action adds to the agent's capability list.
3049
- - Actions help users understand what the agent can do.
3050
-
3051
- ## Examples
3052
-
3053
- \`\`\`book
3054
- Code Assistant
3055
-
3056
- PERSONA You are a programming assistant
3057
- ACTION Can generate code snippets and explain programming concepts
3058
- ACTION Able to debug existing code and suggest improvements
3059
- ACTION Can create unit tests for functions
3060
- \`\`\`
2901
+ value = value.replace(/^```[a-z]*/i, '');
2902
+ value = value.replace(/```$/i, '');
2903
+ value = spaceTrim$1(value);
2904
+ return value;
2905
+ }
3061
2906
 
3062
- \`\`\`book
3063
- Data Scientist
2907
+ /**
2908
+ * Function trimEndOfCodeBlock will remove ending code block from the string if it is present.
2909
+ *
2910
+ * Note: This is useful for post-processing of the result of the completion LLM model
2911
+ * if you want to start code block in the prompt but you don't want to end it in the result.
2912
+ *
2913
+ * @public exported from `@promptbook/markdown-utils`
2914
+ */
2915
+ function trimEndOfCodeBlock(value) {
2916
+ value = spaceTrim$1(value);
2917
+ value = value.replace(/```$/g, '');
2918
+ value = spaceTrim$1(value);
2919
+ return value;
2920
+ }
3064
2921
 
3065
- PERSONA You are a data analysis expert
3066
- ACTION Able to analyze data and provide insights
3067
- ACTION Can create visualizations and charts
3068
- ACTION Capable of statistical analysis and modeling
3069
- KNOWLEDGE Data analysis best practices and statistical methods
3070
- \`\`\`
3071
- `);
3072
- }
3073
- applyToAgentModelRequirements(requirements, content) {
3074
- const trimmedContent = content.trim();
3075
- if (!trimmedContent) {
3076
- return requirements;
3077
- }
3078
- // Add action capability to the system message
3079
- const actionSection = `Capability: ${trimmedContent}`;
3080
- return this.appendToSystemMessage(requirements, actionSection, '\n\n');
3081
- }
2922
+ /**
2923
+ * @private internal for `preserve`
2924
+ */
2925
+ const _preserved = [];
2926
+ /**
2927
+ * Does nothing, but preserves the function in the bundle
2928
+ * Compiler is tricked into thinking the function is used
2929
+ *
2930
+ * @param value any function to preserve
2931
+ * @returns nothing
2932
+ * @private within the repository
2933
+ */
2934
+ function $preserve(...value) {
2935
+ _preserved.push(...value);
3082
2936
  }
3083
2937
  /**
3084
2938
  * Note: [💞] Ignore a discrepancy between file name and entity name
3085
2939
  */
3086
2940
 
2941
+ // Note: [💎]
3087
2942
  /**
3088
- * CLOSED commitment definition
2943
+ * ScriptExecutionTools for JavaScript implemented via eval
3089
2944
  *
3090
- * The CLOSED commitment specifies that the agent CANNOT be modified by conversation.
3091
- * It prevents the agent from learning from interactions and updating its source code.
3092
- *
3093
- * Example usage in agent source:
3094
- *
3095
- * ```book
3096
- * CLOSED
3097
- * ```
3098
- *
3099
- * @private [🪔] Maybe export the commitments through some package
3100
- */
3101
- class ClosedCommitmentDefinition extends BaseCommitmentDefinition {
3102
- constructor() {
3103
- super('CLOSED');
3104
- }
3105
- /**
3106
- * The `CLOSED` commitment is standalone.
3107
- */
3108
- get requiresContent() {
3109
- return false;
3110
- }
3111
- /**
3112
- * Short one-line description of CLOSED.
3113
- */
3114
- get description() {
3115
- return 'Prevent the agent from being modified by conversation.';
3116
- }
3117
- /**
3118
- * Icon for this commitment.
3119
- */
3120
- get icon() {
3121
- return '🔒';
3122
- }
3123
- /**
3124
- * Markdown documentation for CLOSED commitment.
3125
- */
3126
- get documentation() {
3127
- return spaceTrim$1(`
3128
- # CLOSED
3129
-
3130
- Specifies that the agent **cannot** be modified by conversation with it.
3131
- This means the agent will **not** learn from interactions and its source code will remain static during conversation.
3132
-
3133
- By default (if not specified), agents are \`OPEN\` to modification.
3134
-
3135
- > See also [OPEN](/docs/OPEN)
3136
-
3137
- ## Example
3138
-
3139
- \`\`\`book
3140
- CLOSED
3141
- \`\`\`
3142
- `);
3143
- }
3144
- applyToAgentModelRequirements(requirements, _content) {
3145
- const updatedMetadata = {
3146
- ...requirements.metadata,
3147
- isClosed: true,
3148
- };
3149
- return {
3150
- ...requirements,
3151
- metadata: updatedMetadata,
3152
- };
3153
- }
3154
- }
3155
- /**
3156
- * Note: [💞] Ignore a discrepancy between file name and entity name
3157
- */
3158
-
3159
- /**
3160
- * COMPONENT commitment definition
3161
- *
3162
- * The COMPONENT commitment defines a UI component that the agent can render in the chat.
3163
- *
3164
- * @private [🪔] Maybe export the commitments through some package
3165
- */
3166
- class ComponentCommitmentDefinition extends BaseCommitmentDefinition {
3167
- constructor() {
3168
- super('COMPONENT');
3169
- }
3170
- /**
3171
- * Short one-line description of COMPONENT.
3172
- */
3173
- get description() {
3174
- return 'Define a UI component that the agent can render in the chat.';
3175
- }
3176
- /**
3177
- * Icon for this commitment.
3178
- */
3179
- get icon() {
3180
- return '🧩';
3181
- }
3182
- /**
3183
- * Markdown documentation for COMPONENT commitment.
3184
- */
3185
- get documentation() {
3186
- return spaceTrim$1(`
3187
- # COMPONENT
3188
-
3189
- Defines a UI component that the agent can render in the chat.
3190
-
3191
- ## Key aspects
3192
-
3193
- - Tells the agent that a specific component is available.
3194
- - Provides syntax for using the component.
3195
-
3196
- ## Example
3197
-
3198
- \`\`\`book
3199
- COMPONENT Arrow
3200
- The agent should render an arrow component in the chat UI.
3201
- Syntax:
3202
- <Arrow direction="up" color="red" />
3203
- \`\`\`
3204
- `);
3205
- }
3206
- applyToAgentModelRequirements(requirements, content) {
3207
- const trimmedContent = content.trim();
3208
- if (!trimmedContent) {
3209
- return requirements;
3210
- }
3211
- // Add component capability to the system message
3212
- const componentSection = `Component: ${trimmedContent}`;
3213
- return this.appendToSystemMessage(requirements, componentSection, '\n\n');
3214
- }
3215
- }
3216
- /**
3217
- * Note: [💞] Ignore a discrepancy between file name and entity name
3218
- */
3219
-
3220
- /**
3221
- * DELETE commitment definition
3222
- *
3223
- * The DELETE commitment (and its aliases CANCEL, DISCARD, REMOVE) is used to
3224
- * remove or disregard certain information or context. This can be useful for
3225
- * overriding previous commitments or removing unwanted behaviors.
3226
- *
3227
- * Example usage in agent source:
3228
- *
3229
- * ```book
3230
- * DELETE Previous formatting requirements
3231
- * CANCEL All emotional responses
3232
- * DISCARD Technical jargon explanations
3233
- * REMOVE Casual conversational style
3234
- * ```
3235
- *
3236
- * @private [🪔] Maybe export the commitments through some package
3237
- */
3238
- class DeleteCommitmentDefinition extends BaseCommitmentDefinition {
3239
- constructor(type) {
3240
- super(type);
3241
- }
3242
- /**
3243
- * Short one-line description of DELETE/CANCEL/DISCARD/REMOVE.
3244
- */
3245
- get description() {
3246
- return 'Remove or **disregard** certain information, context, or previous commitments.';
3247
- }
3248
- /**
3249
- * Icon for this commitment.
3250
- */
3251
- get icon() {
3252
- return '🗑️';
3253
- }
3254
- /**
3255
- * Markdown documentation for DELETE commitment.
3256
- */
3257
- get documentation() {
3258
- return spaceTrim$1(`
3259
- # DELETE (CANCEL, DISCARD, REMOVE)
3260
-
3261
- A commitment to remove or disregard certain information or context. This can be useful for overriding previous commitments or removing unwanted behaviors.
3262
-
3263
- ## Aliases
3264
-
3265
- - \`DELETE\` - Remove or eliminate something
3266
- - \`CANCEL\` - Cancel or nullify something
3267
- - \`DISCARD\` - Discard or ignore something
3268
- - \`REMOVE\` - Remove or take away something
3269
-
3270
- ## Key aspects
3271
-
3272
- - Multiple delete commitments can be used to remove different aspects.
3273
- - Useful for overriding previous commitments in the same agent definition.
3274
- - Can be used to remove inherited behaviors from base personas.
3275
- - Helps fine-tune agent behavior by explicitly removing unwanted elements.
3276
-
3277
- ## Use cases
3278
-
3279
- - Overriding inherited persona characteristics
3280
- - Removing conflicting or outdated instructions
3281
- - Disabling specific response patterns
3282
- - Canceling previous formatting or style requirements
3283
-
3284
- ## Examples
3285
-
3286
- \`\`\`book
3287
- Serious Business Assistant
3288
-
3289
- PERSONA You are a friendly and casual assistant who uses emojis
3290
- DELETE Casual conversational style
3291
- REMOVE All emoji usage
3292
- GOAL Provide professional business communications
3293
- STYLE Use formal language and proper business etiquette
3294
- \`\`\`
3295
-
3296
- \`\`\`book
3297
- Simplified Technical Support
3298
-
3299
- PERSONA You are a technical support specialist with deep expertise
3300
- KNOWLEDGE Extensive database of technical specifications
3301
- DISCARD Technical jargon explanations
3302
- CANCEL Advanced troubleshooting procedures
3303
- GOAL Help users with simple, easy-to-follow solutions
3304
- STYLE Use plain language that anyone can understand
3305
- \`\`\`
3306
-
3307
- \`\`\`book
3308
- Focused Customer Service
3309
-
3310
- PERSONA You are a customer service agent with broad knowledge
3311
- ACTION Can help with billing, technical issues, and product information
3312
- DELETE Billing assistance capabilities
3313
- REMOVE Technical troubleshooting functions
3314
- GOAL Focus exclusively on product information and general inquiries
3315
- \`\`\`
3316
-
3317
- \`\`\`book
3318
- Concise Information Provider
3319
-
3320
- PERSONA You are a helpful assistant who provides detailed explanations
3321
- STYLE Include examples, analogies, and comprehensive context
3322
- CANCEL Detailed explanation style
3323
- DISCARD Examples and analogies
3324
- GOAL Provide brief, direct answers without unnecessary elaboration
3325
- STYLE Be concise and to the point
3326
- \`\`\`
3327
- `);
3328
- }
3329
- applyToAgentModelRequirements(requirements, content) {
3330
- const trimmedContent = content.trim();
3331
- if (!trimmedContent) {
3332
- return requirements;
3333
- }
3334
- // Create deletion instruction for system message
3335
- const deleteSection = `${this.type}: ${trimmedContent}`;
3336
- // Delete instructions provide important context about what should be removed or ignored
3337
- return this.appendToSystemMessage(requirements, deleteSection, '\n\n');
3338
- }
3339
- }
3340
- /**
3341
- * Note: [💞] Ignore a discrepancy between file name and entity name
3342
- */
3343
-
3344
- /**
3345
- * DICTIONARY commitment definition
3346
- *
3347
- * The DICTIONARY commitment defines specific terms and their meanings that the agent should use correctly
3348
- * in its reasoning and responses. This ensures consistent terminology usage.
3349
- *
3350
- * Key features:
3351
- * - Multiple DICTIONARY commitments are automatically merged into one
3352
- * - Content is placed in a dedicated section of the system message
3353
- * - Terms and definitions are stored in metadata.DICTIONARY for debugging
3354
- * - Agent should use the defined terms correctly in responses
3355
- *
3356
- * Example usage in agent source:
3357
- *
3358
- * ```book
3359
- * Legal Assistant
3360
- *
3361
- * PERSONA You are a knowledgeable legal assistant
3362
- * DICTIONARY Misdemeanor is a minor wrongdoing or criminal offense
3363
- * DICTIONARY Felony is a serious crime usually punishable by imprisonment for more than one year
3364
- * DICTIONARY Tort is a civil wrong that causes harm or loss to another person, leading to legal liability
3365
- * ```
3366
- *
3367
- * @private [🪔] Maybe export the commitments through some package
3368
- */
3369
- class DictionaryCommitmentDefinition extends BaseCommitmentDefinition {
3370
- constructor() {
3371
- super('DICTIONARY');
3372
- }
3373
- /**
3374
- * Short one-line description of DICTIONARY.
3375
- */
3376
- get description() {
3377
- return 'Define terms and their meanings for consistent terminology usage.';
3378
- }
3379
- /**
3380
- * Icon for this commitment.
3381
- */
3382
- get icon() {
3383
- return '📚';
3384
- }
3385
- /**
3386
- * Markdown documentation for DICTIONARY commitment.
3387
- */
3388
- get documentation() {
3389
- return spaceTrim$1(`
3390
- # DICTIONARY
3391
-
3392
- Defines specific terms and their meanings that the agent should use correctly in reasoning and responses.
3393
-
3394
- ## Key aspects
3395
-
3396
- - Multiple \`DICTIONARY\` commitments are merged together.
3397
- - Terms are defined in the format: "Term is definition"
3398
- - The agent should use these terms consistently in responses.
3399
- - Definitions help ensure accurate and consistent terminology.
3400
-
3401
- ## Examples
3402
-
3403
- \`\`\`book
3404
- Legal Assistant
3405
-
3406
- PERSONA You are a knowledgeable legal assistant specializing in criminal law
3407
- DICTIONARY Misdemeanor is a minor wrongdoing or criminal offense
3408
- DICTIONARY Felony is a serious crime usually punishable by imprisonment for more than one year
3409
- DICTIONARY Tort is a civil wrong that causes harm or loss to another person, leading to legal liability
3410
- \`\`\`
3411
-
3412
- \`\`\`book
3413
- Medical Assistant
3414
-
3415
- PERSONA You are a helpful medical assistant
3416
- DICTIONARY Hypertension is persistently high blood pressure
3417
- DICTIONARY Diabetes is a chronic condition that affects how the body processes blood sugar
3418
- DICTIONARY Vaccine is a biological preparation that provides active immunity to a particular disease
3419
- \`\`\`
3420
- `);
3421
- }
3422
- applyToAgentModelRequirements(requirements, content) {
3423
- var _a;
3424
- const trimmedContent = content.trim();
3425
- if (!trimmedContent) {
3426
- return requirements;
3427
- }
3428
- // Get existing dictionary entries from metadata
3429
- const existingDictionary = ((_a = requirements.metadata) === null || _a === void 0 ? void 0 : _a.DICTIONARY) || '';
3430
- // Merge the new dictionary entry with existing entries
3431
- const mergedDictionary = existingDictionary ? `${existingDictionary}\n${trimmedContent}` : trimmedContent;
3432
- // Store the merged dictionary in metadata for debugging and inspection
3433
- const updatedMetadata = {
3434
- ...requirements.metadata,
3435
- DICTIONARY: mergedDictionary,
3436
- };
3437
- // Create the dictionary section for the system message
3438
- // Format: "# DICTIONARY\nTerm: definition\nTerm: definition..."
3439
- const dictionarySection = `# DICTIONARY\n${mergedDictionary}`;
3440
- return {
3441
- ...this.appendToSystemMessage(requirements, dictionarySection),
3442
- metadata: updatedMetadata,
3443
- };
3444
- }
3445
- }
3446
- /**
3447
- * Note: [💞] Ignore a discrepancy between file name and entity name
3448
- */
3449
-
3450
- /**
3451
- * FORMAT commitment definition
3452
- *
3453
- * The FORMAT commitment defines the specific output structure and formatting
3454
- * that the agent should use in its responses. This includes data formats,
3455
- * response templates, and structural requirements.
3456
- *
3457
- * Example usage in agent source:
3458
- *
3459
- * ```book
3460
- * FORMAT Always respond in JSON format with 'status' and 'data' fields
3461
- * FORMAT Use markdown formatting for all code blocks
3462
- * ```
3463
- *
3464
- * @private [🪔] Maybe export the commitments through some package
3465
- */
3466
- class FormatCommitmentDefinition extends BaseCommitmentDefinition {
3467
- constructor(type = 'FORMAT') {
3468
- super(type);
3469
- }
3470
- /**
3471
- * Short one-line description of FORMAT.
3472
- */
3473
- get description() {
3474
- return 'Specify output structure or formatting requirements.';
3475
- }
3476
- /**
3477
- * Icon for this commitment.
3478
- */
3479
- get icon() {
3480
- return '📜';
3481
- }
3482
- /**
3483
- * Markdown documentation for FORMAT commitment.
3484
- */
3485
- get documentation() {
3486
- return spaceTrim$1(`
3487
- # ${this.type}
3488
-
3489
- Defines the specific output structure and formatting for responses (data formats, templates, structure).
3490
-
3491
- ## Key aspects
3492
-
3493
- - Both terms work identically and can be used interchangeably.
3494
- - If they are in conflict, the last one takes precedence.
3495
- - You can specify both data formats and presentation styles.
3496
-
3497
- ## Examples
3498
-
3499
- \`\`\`book
3500
- Customer Support Bot
3501
-
3502
- PERSONA You are a helpful customer support agent
3503
- FORMAT Always respond in JSON format with 'status' and 'data' fields
3504
- FORMAT Use markdown formatting for all code blocks
3505
- \`\`\`
3506
-
3507
- \`\`\`book
3508
- Data Analyst
3509
-
3510
- PERSONA You are a data analysis expert
3511
- FORMAT Present results in structured tables
3512
- FORMAT Include confidence scores for all predictions
3513
- STYLE Be concise and precise in explanations
3514
- \`\`\`
3515
- `);
3516
- }
3517
- applyToAgentModelRequirements(requirements, content) {
3518
- const trimmedContent = content.trim();
3519
- if (!trimmedContent) {
3520
- return requirements;
3521
- }
3522
- // Add format instructions to the system message
3523
- const formatSection = `Output Format: ${trimmedContent}`;
3524
- return this.appendToSystemMessage(requirements, formatSection, '\n\n');
3525
- }
3526
- }
3527
- /**
3528
- * Note: [💞] Ignore a discrepancy between file name and entity name
3529
- */
3530
-
3531
- /**
3532
- * FROM commitment definition
3533
- *
3534
- * The FROM commitment tells the agent that its `agentSource` is inherited from another agent.
3535
- *
3536
- * Example usage in agent source:
3537
- *
3538
- * ```book
3539
- * FROM https://s6.ptbk.io/benjamin-white
3540
- * ```
3541
- *
3542
- * @private [🪔] Maybe export the commitments through some package
3543
- */
3544
- class FromCommitmentDefinition extends BaseCommitmentDefinition {
3545
- constructor(type = 'FROM') {
3546
- super(type);
3547
- }
3548
- /**
3549
- * Short one-line description of FROM.
3550
- */
3551
- get description() {
3552
- return 'Inherit agent source from another agent.';
3553
- }
3554
- /**
3555
- * Icon for this commitment.
3556
- */
3557
- get icon() {
3558
- return '🧬';
3559
- }
3560
- /**
3561
- * Markdown documentation for FROM commitment.
3562
- */
3563
- get documentation() {
3564
- return spaceTrim$1(`
3565
- # ${this.type}
3566
-
3567
- Inherits agent source from another agent.
3568
-
3569
- ## Examples
3570
-
3571
- \`\`\`book
3572
- My AI Agent
3573
-
3574
- FROM https://s6.ptbk.io/benjamin-white
3575
- RULE Speak only in English.
3576
- \`\`\`
3577
- `);
3578
- }
3579
- applyToAgentModelRequirements(requirements, content) {
3580
- const trimmedContent = content.trim();
3581
- if (!trimmedContent) {
3582
- return {
3583
- ...requirements,
3584
- parentAgentUrl: undefined,
3585
- };
3586
- }
3587
- if (trimmedContent.toUpperCase() === 'VOID' ||
3588
- trimmedContent.toUpperCase() === 'NULL' ||
3589
- trimmedContent.toUpperCase() === 'NONE' ||
3590
- trimmedContent.toUpperCase() === 'NIL') {
3591
- return {
3592
- ...requirements,
3593
- parentAgentUrl: null,
3594
- };
3595
- }
3596
- if (!isValidAgentUrl(trimmedContent)) {
3597
- throw new Error(spaceTrim$1((block) => `
3598
- Invalid agent URL in FROM commitment: "${trimmedContent}"
3599
-
3600
- \`\`\`book
3601
- ${block(content)}
3602
- \`\`\`
3603
-
3604
-
3605
- `));
3606
- }
3607
- const parentAgentUrl = trimmedContent;
3608
- return {
3609
- ...requirements,
3610
- parentAgentUrl,
3611
- };
3612
- }
3613
- }
3614
- /**
3615
- * Note: [💞] Ignore a discrepancy between file name and entity name
3616
- */
3617
-
3618
- /**
3619
- * GOAL commitment definition
3620
- *
3621
- * The GOAL commitment defines the main goal which should be achieved by the AI assistant.
3622
- * There can be multiple goals. Later goals are more important than earlier goals.
3623
- *
3624
- * Example usage in agent source:
3625
- *
3626
- * ```book
3627
- * GOAL Help users understand complex technical concepts
3628
- * GOAL Provide accurate and up-to-date information
3629
- * GOAL Always prioritize user safety and ethical guidelines
3630
- * ```
3631
- *
3632
- * @private [🪔] Maybe export the commitments through some package
3633
- */
3634
- class GoalCommitmentDefinition extends BaseCommitmentDefinition {
3635
- constructor(type = 'GOAL') {
3636
- super(type);
3637
- }
3638
- /**
3639
- * Short one-line description of GOAL.
3640
- */
3641
- get description() {
3642
- return 'Define main **goals** the AI assistant should achieve, with later goals having higher priority.';
3643
- }
3644
- /**
3645
- * Icon for this commitment.
3646
- */
3647
- get icon() {
3648
- return '🎯';
3649
- }
3650
- /**
3651
- * Markdown documentation for GOAL commitment.
3652
- */
3653
- get documentation() {
3654
- return spaceTrim$1(`
3655
- # ${this.type}
3656
-
3657
- Defines the main goal which should be achieved by the AI assistant. There can be multiple goals, and later goals are more important than earlier goals.
3658
-
3659
- ## Key aspects
3660
-
3661
- - Both terms work identically and can be used interchangeably.
3662
- - Later goals have higher priority and can override earlier goals.
3663
- - Goals provide clear direction and purpose for the agent's responses.
3664
- - Goals influence decision-making and response prioritization.
3665
-
3666
- ## Priority system
3667
-
3668
- When multiple goals are defined, they are processed in order, with later goals taking precedence over earlier ones when there are conflicts.
3669
-
3670
- ## Examples
3671
-
3672
- \`\`\`book
3673
- Customer Support Agent
3674
-
3675
- PERSONA You are a helpful customer support representative
3676
- GOAL Resolve customer issues quickly and efficiently
3677
- GOAL Maintain high customer satisfaction scores
3678
- GOAL Always follow company policies and procedures
3679
- RULE Be polite and professional at all times
3680
- \`\`\`
3681
-
3682
- \`\`\`book
3683
- Educational Assistant
3684
-
3685
- PERSONA You are an educational assistant specializing in mathematics
3686
- GOAL Help students understand mathematical concepts clearly
3687
- GOAL Encourage critical thinking and problem-solving skills
3688
- GOAL Ensure all explanations are age-appropriate and accessible
3689
- STYLE Use simple language and provide step-by-step explanations
3690
- \`\`\`
3691
-
3692
- \`\`\`book
3693
- Safety-First Assistant
3694
-
3695
- PERSONA You are a general-purpose AI assistant
3696
- GOAL Be helpful and informative in all interactions
3697
- GOAL Provide accurate and reliable information
3698
- GOAL Always prioritize user safety and ethical guidelines
3699
- RULE Never provide harmful or dangerous advice
3700
- \`\`\`
3701
- `);
3702
- }
3703
- applyToAgentModelRequirements(requirements, content) {
3704
- const trimmedContent = content.trim();
3705
- if (!trimmedContent) {
3706
- return requirements;
3707
- }
3708
- // Create goal section for system message
3709
- const goalSection = `Goal: ${trimmedContent}`;
3710
- // Goals are important directives, so we add them prominently to the system message
3711
- return this.appendToSystemMessage(requirements, goalSection, '\n\n');
3712
- }
3713
- }
3714
- /**
3715
- * Note: [💞] Ignore a discrepancy between file name and entity name
3716
- */
3717
-
3718
- /**
3719
- * IMPORT commitment definition
3720
- *
3721
- * The IMPORT commitment tells the agent to import content from another agent at the current location.
3722
- *
3723
- * Example usage in agent source:
3724
- *
3725
- * ```book
3726
- * IMPORT https://s6.ptbk.io/benjamin-white
3727
- * ```
3728
- *
3729
- * @private [🪔] Maybe export the commitments through some package
3730
- */
3731
- class ImportCommitmentDefinition extends BaseCommitmentDefinition {
3732
- constructor(type = 'IMPORT') {
3733
- super(type);
3734
- }
3735
- /**
3736
- * Short one-line description of IMPORT.
3737
- */
3738
- get description() {
3739
- return 'Import content from another agent or a generic text file.';
3740
- }
3741
- /**
3742
- * Icon for this commitment.
3743
- */
3744
- get icon() {
3745
- return '📥';
3746
- }
3747
- /**
3748
- * Markdown documentation for IMPORT commitment.
3749
- */
3750
- get documentation() {
3751
- return spaceTrim$1(`
3752
- # ${this.type}
3753
-
3754
- Imports content from another agent or a generic text file at the location of the commitment.
3755
-
3756
- ## Examples
3757
-
3758
- \`\`\`book
3759
- My AI Agent
3760
-
3761
- IMPORT https://s6.ptbk.io/benjamin-white
3762
- IMPORT https://example.com/some-text-file.txt
3763
- IMPORT ./path/to/local-file.json
3764
- RULE Speak only in English.
3765
- \`\`\`
3766
- `);
3767
- }
3768
- applyToAgentModelRequirements(requirements, content) {
3769
- const trimmedContent = content.trim();
3770
- if (!trimmedContent) {
3771
- return requirements;
3772
- }
3773
- if (isValidAgentUrl(trimmedContent)) {
3774
- const importedAgentUrl = trimmedContent;
3775
- return {
3776
- ...requirements,
3777
- importedAgentUrls: [...(requirements.importedAgentUrls || []), importedAgentUrl],
3778
- };
3779
- }
3780
- if (isValidUrl(trimmedContent) || isValidFilePath(trimmedContent)) {
3781
- return {
3782
- ...requirements,
3783
- importedFileUrls: [...(requirements.importedFileUrls || []), trimmedContent],
3784
- };
3785
- }
3786
- throw new Error(spaceTrim$1((block) => `
3787
- Invalid agent URL or file path in IMPORT commitment: "${trimmedContent}"
3788
-
3789
- \`\`\`book
3790
- ${block(content)}
3791
- \`\`\`
3792
- `));
3793
- }
3794
- }
3795
- /**
3796
- * Note: [💞] Ignore a discrepancy between file name and entity name
3797
- */
3798
-
3799
- /**
3800
- * KNOWLEDGE commitment definition
3801
- *
3802
- * The KNOWLEDGE commitment adds specific knowledge, facts, or context to the agent
3803
- * using RAG (Retrieval-Augmented Generation) approach for external sources.
3804
- *
3805
- * Supports both direct text knowledge and external sources like PDFs.
3806
- *
3807
- * Example usage in agent source:
3808
- *
3809
- * ```book
3810
- * KNOWLEDGE The company was founded in 2020 and specializes in AI-powered solutions
3811
- * KNOWLEDGE https://example.com/company-handbook.pdf
3812
- * KNOWLEDGE https://example.com/product-documentation.pdf
3813
- * ```
3814
- *
3815
- * @private [🪔] Maybe export the commitments through some package
3816
- */
3817
- class KnowledgeCommitmentDefinition extends BaseCommitmentDefinition {
3818
- constructor() {
3819
- super('KNOWLEDGE');
3820
- }
3821
- /**
3822
- * Short one-line description of KNOWLEDGE.
3823
- */
3824
- get description() {
3825
- return 'Add domain **knowledge** via direct text or external sources (RAG).';
3826
- }
3827
- /**
3828
- * Icon for this commitment.
3829
- */
3830
- get icon() {
3831
- return '🧠';
3832
- }
3833
- /**
3834
- * Markdown documentation for KNOWLEDGE commitment.
3835
- */
3836
- get documentation() {
3837
- return spaceTrim$1(`
3838
- # ${this.type}
3839
-
3840
- Adds specific knowledge, facts, or context to the agent using a RAG (Retrieval-Augmented Generation) approach for external sources.
3841
-
3842
- ## Key aspects
3843
-
3844
- - Both terms work identically and can be used interchangeably.
3845
- - Supports both direct text knowledge and external URLs.
3846
- - External sources (PDFs, websites) are processed via RAG for context retrieval.
3847
-
3848
- ## Supported formats
3849
-
3850
- - Direct text: Immediate knowledge incorporated into agent
3851
- - URLs: External documents processed for contextual retrieval
3852
- - Supported file types: PDF, text, markdown, HTML
3853
-
3854
- ## Examples
3855
-
3856
- \`\`\`book
3857
- Customer Support Bot
3858
-
3859
- PERSONA You are a helpful customer support agent for TechCorp
3860
- KNOWLEDGE TechCorp was founded in 2020 and specializes in AI-powered solutions
3861
- KNOWLEDGE https://example.com/company-handbook.pdf
3862
- KNOWLEDGE https://example.com/product-documentation.pdf
3863
- RULE Always be polite and professional
3864
- \`\`\`
3865
-
3866
- \`\`\`book
3867
- Research Assistant
3868
-
3869
- PERSONA You are a knowledgeable research assistant
3870
- KNOWLEDGE Academic research requires careful citation and verification
3871
- KNOWLEDGE https://example.com/research-guidelines.pdf
3872
- ACTION Can help with literature reviews and data analysis
3873
- STYLE Present information in clear, academic format
3874
- \`\`\`
3875
- `);
3876
- }
3877
- applyToAgentModelRequirements(requirements, content) {
3878
- const trimmedContent = content.trim();
3879
- if (!trimmedContent) {
3880
- return requirements;
3881
- }
3882
- // Check if content is a URL (external knowledge source)
3883
- if (isValidUrl(trimmedContent)) {
3884
- // Store the URL for later async processing
3885
- const updatedRequirements = {
3886
- ...requirements,
3887
- knowledgeSources: [
3888
- ...(requirements.knowledgeSources || []),
3889
- trimmedContent,
3890
- ],
3891
- };
3892
- // Add placeholder information about knowledge sources to system message
3893
- const knowledgeInfo = `Knowledge Source URL: ${trimmedContent} (will be processed for retrieval during chat)`;
3894
- return this.appendToSystemMessage(updatedRequirements, knowledgeInfo, '\n\n');
3895
- }
3896
- else {
3897
- // Direct text knowledge - add to system message
3898
- const knowledgeSection = `Knowledge: ${trimmedContent}`;
3899
- return this.appendToSystemMessage(requirements, knowledgeSection, '\n\n');
3900
- }
3901
- }
3902
- }
3903
- /**
3904
- * Note: [💞] Ignore a discrepancy between file name and entity name
3905
- */
3906
-
3907
- /**
3908
- * LANGUAGE commitment definition
3909
- *
3910
- * The LANGUAGE/LANGUAGES commitment specifies the language(s) the agent should use in its responses.
3911
- *
3912
- * Example usage in agent source:
3913
- *
3914
- * ```book
3915
- * LANGUAGE English
3916
- * LANGUAGE French, English and Czech
3917
- * ```
3918
- *
3919
- * @private [🪔] Maybe export the commitments through some package
3920
- */
3921
- class LanguageCommitmentDefinition extends BaseCommitmentDefinition {
3922
- constructor(type = 'LANGUAGE') {
3923
- super(type);
3924
- }
3925
- /**
3926
- * Short one-line description of LANGUAGE/LANGUAGES.
3927
- */
3928
- get description() {
3929
- return 'Specifies the language(s) the agent should use.';
3930
- }
3931
- /**
3932
- * Icon for this commitment.
3933
- */
3934
- get icon() {
3935
- return '🌐';
3936
- }
3937
- /**
3938
- * Markdown documentation for LANGUAGE/LANGUAGES commitment.
3939
- */
3940
- get documentation() {
3941
- return spaceTrim$1(`
3942
- # ${this.type}
3943
-
3944
- Specifies the language(s) the agent should use in its responses.
3945
- This is a specialized variation of the RULE commitment focused on language constraints.
3946
-
3947
- ## Examples
3948
-
3949
- \`\`\`book
3950
- Paul Smith & Associés
3951
-
3952
- PERSONA You are a company lawyer.
3953
- LANGUAGE French, English and Czech
3954
- \`\`\`
3955
-
3956
- \`\`\`book
3957
- Customer Support
3958
-
3959
- PERSONA You are a customer support agent.
3960
- LANGUAGE English
3961
- \`\`\`
3962
- `);
3963
- }
3964
- applyToAgentModelRequirements(requirements, content) {
3965
- const trimmedContent = content.trim();
3966
- if (!trimmedContent) {
3967
- return requirements;
3968
- }
3969
- // Add language rule to the system message
3970
- const languageSection = `Language: ${trimmedContent}`;
3971
- return this.appendToSystemMessage(requirements, languageSection, '\n\n');
3972
- }
3973
- }
3974
- /**
3975
- * Note: [💞] Ignore a discrepancy between file name and entity name
3976
- */
3977
-
3978
- /**
3979
- * MEMORY commitment definition
3980
- *
3981
- * The MEMORY commitment is similar to KNOWLEDGE but has a focus on remembering past
3982
- * interactions and user preferences. It helps the agent maintain context about the
3983
- * user's history, preferences, and previous conversations.
3984
- *
3985
- * Example usage in agent source:
3986
- *
3987
- * ```book
3988
- * MEMORY User prefers detailed technical explanations
3989
- * MEMORY Previously worked on React projects
3990
- * MEMORY Timezone: UTC-5 (Eastern Time)
3991
- * ```
3992
- *
3993
- * @private [🪔] Maybe export the commitments through some package
3994
- */
3995
- class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
3996
- constructor(type = 'MEMORY') {
3997
- super(type);
3998
- }
3999
- /**
4000
- * Short one-line description of MEMORY.
4001
- */
4002
- get description() {
4003
- return 'Remember past interactions and user **preferences** for personalized responses.';
4004
- }
4005
- /**
4006
- * Icon for this commitment.
4007
- */
4008
- get icon() {
4009
- return '🧠';
4010
- }
4011
- /**
4012
- * Markdown documentation for MEMORY commitment.
4013
- */
4014
- get documentation() {
4015
- return spaceTrim$1(`
4016
- # ${this.type}
4017
-
4018
- Similar to KNOWLEDGE but focuses on remembering past interactions and user preferences. This commitment helps the agent maintain context about the user's history, preferences, and previous conversations.
4019
-
4020
- ## Key aspects
4021
-
4022
- - Both terms work identically and can be used interchangeably.
4023
- - Focuses on user-specific information and interaction history.
4024
- - Helps personalize responses based on past interactions.
4025
- - Maintains continuity across conversations.
4026
-
4027
- ## Differences from KNOWLEDGE
4028
-
4029
- - \`KNOWLEDGE\` is for domain expertise and factual information
4030
- - \`MEMORY\` is for user-specific context and preferences
4031
- - \`MEMORY\` creates more personalized interactions
4032
- - \`MEMORY\` often includes temporal or preference-based information
4033
-
4034
- ## Examples
4035
-
4036
- \`\`\`book
4037
- Personal Assistant
4038
-
4039
- PERSONA You are a personal productivity assistant
4040
- MEMORY User is a software developer working in JavaScript/React
4041
- MEMORY User prefers morning work sessions and afternoon meetings
4042
- MEMORY Previously helped with project planning for mobile apps
4043
- MEMORY User timezone: UTC-8 (Pacific Time)
4044
- GOAL Help optimize daily productivity and workflow
4045
- \`\`\`
4046
-
4047
- \`\`\`book
4048
- Learning Companion
4049
-
4050
- PERSONA You are an educational companion for programming students
4051
- MEMORY Student is learning Python as their first programming language
4052
- MEMORY Previous topics covered: variables, loops, functions
4053
- MEMORY Student learns best with practical examples and exercises
4054
- MEMORY Last session: working on list comprehensions
4055
- GOAL Provide progressive learning experiences tailored to student's pace
4056
- \`\`\`
4057
-
4058
- \`\`\`book
4059
- Customer Support Agent
4060
-
4061
- PERSONA You are a customer support representative
4062
- MEMORY Customer has premium subscription since 2023
4063
- MEMORY Previous issue: billing question resolved last month
4064
- MEMORY Customer prefers email communication over phone calls
4065
- MEMORY Account shows frequent use of advanced features
4066
- GOAL Provide personalized support based on customer history
4067
- \`\`\`
4068
- `);
4069
- }
4070
- applyToAgentModelRequirements(requirements, content) {
4071
- const trimmedContent = content.trim();
4072
- if (!trimmedContent) {
4073
- return requirements;
4074
- }
4075
- // Create memory section for system message
4076
- const memorySection = `Memory: ${trimmedContent}`;
4077
- // Memory information is contextual and should be included in the system message
4078
- return this.appendToSystemMessage(requirements, memorySection, '\n\n');
4079
- }
4080
- }
4081
- /**
4082
- * Note: [💞] Ignore a discrepancy between file name and entity name
4083
- */
4084
-
4085
- /**
4086
- * AGENT MESSAGE commitment definition
4087
- *
4088
- * The AGENT MESSAGE commitment defines a message from the agent in the conversation history.
4089
- * It is used to pre-fill the chat with a conversation history or to provide few-shot examples.
4090
- *
4091
- * Example usage in agent source:
4092
- *
4093
- * ```book
4094
- * AGENT MESSAGE What seems to be the issue?
4095
- * ```
4096
- *
4097
- * @private [🪔] Maybe export the commitments through some package
4098
- */
4099
- class AgentMessageCommitmentDefinition extends BaseCommitmentDefinition {
4100
- constructor() {
4101
- super('AGENT MESSAGE');
4102
- }
4103
- /**
4104
- * Short one-line description of AGENT MESSAGE.
4105
- */
4106
- get description() {
4107
- return 'Defines a **message from the agent** in the conversation history.';
4108
- }
4109
- /**
4110
- * Icon for this commitment.
4111
- */
4112
- get icon() {
4113
- return '🤖';
4114
- }
4115
- /**
4116
- * Markdown documentation for AGENT MESSAGE commitment.
4117
- */
4118
- get documentation() {
4119
- return spaceTrim$1(`
4120
- # ${this.type}
4121
-
4122
- Defines a message from the agent in the conversation history. This is used to pre-fill the chat with a conversation history or to provide few-shot examples.
4123
-
4124
- ## Key aspects
4125
-
4126
- - Represents a message sent by the agent.
4127
- - Used for setting up conversation context.
4128
- - Can be used in conjunction with USER MESSAGE.
4129
-
4130
- ## Examples
4131
-
4132
- \`\`\`book
4133
- Conversation History
4134
-
4135
- USER MESSAGE Hello, I have a problem.
4136
- AGENT MESSAGE What seems to be the issue?
4137
- USER MESSAGE My computer is not starting.
4138
- \`\`\`
4139
- `);
4140
- }
4141
- applyToAgentModelRequirements(requirements, content) {
4142
- // AGENT MESSAGE is for UI display purposes / conversation history construction
4143
- // and typically doesn't need to be added to the system prompt or model requirements directly.
4144
- // It is extracted separately for the chat interface.
4145
- var _a;
4146
- const pendingUserMessage = (_a = requirements.metadata) === null || _a === void 0 ? void 0 : _a.pendingUserMessage;
4147
- if (pendingUserMessage) {
4148
- const newSample = { question: pendingUserMessage, answer: content };
4149
- const newSamples = [...(requirements.samples || []), newSample];
4150
- const newMetadata = { ...requirements.metadata };
4151
- delete newMetadata.pendingUserMessage;
4152
- return {
4153
- ...requirements,
4154
- samples: newSamples,
4155
- metadata: newMetadata,
4156
- };
4157
- }
4158
- return requirements;
4159
- }
4160
- }
4161
-
4162
- /**
4163
- * INITIAL MESSAGE commitment definition
4164
- *
4165
- * The INITIAL MESSAGE commitment defines the first message that the user sees when opening the chat.
4166
- * It is used to greet the user and set the tone of the conversation.
4167
- *
4168
- * Example usage in agent source:
4169
- *
4170
- * ```book
4171
- * INITIAL MESSAGE Hello! I am ready to help you with your tasks.
4172
- * ```
4173
- *
4174
- * @private [🪔] Maybe export the commitments through some package
4175
- */
4176
- class InitialMessageCommitmentDefinition extends BaseCommitmentDefinition {
4177
- constructor() {
4178
- super('INITIAL MESSAGE');
4179
- }
4180
- /**
4181
- * Short one-line description of INITIAL MESSAGE.
4182
- */
4183
- get description() {
4184
- return 'Defines the **initial message** shown to the user when the chat starts.';
4185
- }
4186
- /**
4187
- * Icon for this commitment.
4188
- */
4189
- get icon() {
4190
- return '👋';
4191
- }
4192
- /**
4193
- * Markdown documentation for INITIAL MESSAGE commitment.
4194
- */
4195
- get documentation() {
4196
- return spaceTrim$1(`
4197
- # ${this.type}
4198
-
4199
- Defines the first message that the user sees when opening the chat. This message is purely for display purposes in the UI and does not inherently become part of the LLM's system prompt context (unless also included via other means).
4200
-
4201
- ## Key aspects
4202
-
4203
- - Used to greet the user.
4204
- - Sets the tone of the conversation.
4205
- - Displayed immediately when the chat interface loads.
4206
-
4207
- ## Examples
4208
-
4209
- \`\`\`book
4210
- Support Agent
4211
-
4212
- PERSONA You are a helpful support agent.
4213
- INITIAL MESSAGE Hi there! How can I assist you today?
4214
- \`\`\`
4215
- `);
4216
- }
4217
- applyToAgentModelRequirements(requirements, content) {
4218
- // INITIAL MESSAGE is for UI display purposes and for conversation history construction.
4219
- const newSample = { question: null, answer: content };
4220
- const newSamples = [...(requirements.samples || []), newSample];
4221
- return {
4222
- ...requirements,
4223
- samples: newSamples,
4224
- };
4225
- }
4226
- }
4227
-
4228
- /**
4229
- * MESSAGE commitment definition
4230
- *
4231
- * The MESSAGE commitment contains 1:1 text of the message which AI assistant already
4232
- * sent during the conversation. Later messages are later in the conversation.
4233
- * It is similar to EXAMPLE but it is not example, it is the real message which
4234
- * AI assistant already sent.
4235
- *
4236
- * Example usage in agent source:
4237
- *
4238
- * ```book
4239
- * MESSAGE Hello! How can I help you today?
4240
- * MESSAGE I understand you're looking for information about our services.
4241
- * MESSAGE Based on your requirements, I'd recommend our premium package.
4242
- * ```
4243
- *
4244
- * @private [🪔] Maybe export the commitments through some package
4245
- */
4246
- class MessageCommitmentDefinition extends BaseCommitmentDefinition {
4247
- constructor(type = 'MESSAGE') {
4248
- super(type);
4249
- }
4250
- /**
4251
- * Short one-line description of MESSAGE.
4252
- */
4253
- get description() {
4254
- return 'Include actual **messages** the AI assistant has sent during conversation history.';
4255
- }
4256
- /**
4257
- * Icon for this commitment.
4258
- */
4259
- get icon() {
4260
- return '💬';
4261
- }
4262
- /**
4263
- * Markdown documentation for MESSAGE commitment.
4264
- */
4265
- get documentation() {
4266
- return spaceTrim$1(`
4267
- # ${this.type}
4268
-
4269
- Contains 1:1 text of the message which AI assistant already sent during the conversation. Later messages are later in the conversation. It is similar to EXAMPLE but it is not example, it is the real message which AI assistant already sent.
4270
-
4271
- ## Key aspects
4272
-
4273
- - Multiple \`MESSAGE\` and \`MESSAGES\` commitments represent the conversation timeline.
4274
- - Both terms work identically and can be used interchangeably.
4275
- - Later messages are later in the conversation chronologically.
4276
- - Contains actual historical messages, not examples or templates.
4277
- - Helps maintain conversation continuity and context.
4278
-
4279
- ## Differences from EXAMPLE
4280
-
4281
- - \`EXAMPLE\` shows hypothetical or template responses
4282
- - \`MESSAGE\`/\`MESSAGES\` contains actual historical conversation content
4283
- - \`MESSAGE\`/\`MESSAGES\` preserves the exact conversation flow
4284
- - \`MESSAGE\`/\`MESSAGES\` helps with context awareness and consistency
4285
-
4286
- ## Use cases
4287
-
4288
- - Maintaining conversation history context
4289
- - Ensuring consistent tone and style across messages
4290
- - Referencing previous responses in ongoing conversations
4291
- - Building upon previously established context
4292
-
4293
- ## Examples
4294
-
4295
- \`\`\`book
4296
- Customer Support Continuation
4297
-
4298
- PERSONA You are a helpful customer support agent
4299
- MESSAGE Hello! How can I help you today?
4300
- MESSAGE I understand you're experiencing issues with your account login.
4301
- MESSAGE I've sent you a password reset link to your email address.
4302
- MESSAGE Is there anything else I can help you with regarding your account?
4303
- GOAL Continue providing consistent support based on conversation history
4304
- \`\`\`
4305
-
4306
- \`\`\`book
4307
- Technical Discussion
4308
-
4309
- PERSONA You are a software development mentor
4310
- MESSAGE Let's start by reviewing the React component structure you shared.
4311
- MESSAGE I notice you're using class components - have you considered hooks?
4312
- MESSAGE Here's how you could refactor that using the useState hook.
4313
- MESSAGE Great question about performance! Let me explain React's rendering cycle.
4314
- KNOWLEDGE React hooks were introduced in version 16.8
4315
- \`\`\`
4316
-
4317
- \`\`\`book
4318
- Educational Session
4319
-
4320
- PERSONA You are a mathematics tutor
4321
- MESSAGE Today we'll work on solving quadratic equations.
4322
- MESSAGE Let's start with the basic form: ax² + bx + c = 0
4323
- MESSAGE Remember, we can use the quadratic formula or factoring.
4324
- MESSAGE You did great with that first problem! Let's try a more complex one.
4325
- GOAL Build upon previous explanations for deeper understanding
4326
- \`\`\`
4327
- `);
4328
- }
4329
- applyToAgentModelRequirements(requirements, content) {
4330
- const trimmedContent = content.trim();
4331
- if (!trimmedContent) {
4332
- return requirements;
4333
- }
4334
- // Create message section for system message
4335
- const messageSection = `Previous Message: ${trimmedContent}`;
4336
- // Messages represent conversation history and should be included for context
4337
- return this.appendToSystemMessage(requirements, messageSection, '\n\n');
4338
- }
4339
- }
4340
- /**
4341
- * Note: [💞] Ignore a discrepancy between file name and entity name
4342
- */
4343
-
4344
- /**
4345
- * USER MESSAGE commitment definition
4346
- *
4347
- * The USER MESSAGE commitment defines a message from the user in the conversation history.
4348
- * It is used to pre-fill the chat with a conversation history or to provide few-shot examples.
4349
- *
4350
- * Example usage in agent source:
4351
- *
4352
- * ```book
4353
- * USER MESSAGE Hello, I have a problem.
4354
- * ```
4355
- *
4356
- * @private [🪔] Maybe export the commitments through some package
4357
- */
4358
- class UserMessageCommitmentDefinition extends BaseCommitmentDefinition {
4359
- constructor() {
4360
- super('USER MESSAGE');
4361
- }
4362
- /**
4363
- * Short one-line description of USER MESSAGE.
4364
- */
4365
- get description() {
4366
- return 'Defines a **message from the user** in the conversation history.';
4367
- }
4368
- /**
4369
- * Icon for this commitment.
4370
- */
4371
- get icon() {
4372
- return '🧑';
4373
- }
4374
- /**
4375
- * Markdown documentation for USER MESSAGE commitment.
4376
- */
4377
- get documentation() {
4378
- return spaceTrim$1(`
4379
- # ${this.type}
4380
-
4381
- Defines a message from the user in the conversation history. This is used to pre-fill the chat with a conversation history or to provide few-shot examples.
4382
-
4383
- ## Key aspects
4384
-
4385
- - Represents a message sent by the user.
4386
- - Used for setting up conversation context.
4387
- - Can be used in conjunction with AGENT MESSAGE.
4388
-
4389
- ## Examples
4390
-
4391
- \`\`\`book
4392
- Conversation History
4393
-
4394
- USER MESSAGE Hello, I have a problem.
4395
- AGENT MESSAGE What seems to be the issue?
4396
- USER MESSAGE My computer is not starting.
4397
- \`\`\`
4398
- `);
4399
- }
4400
- applyToAgentModelRequirements(requirements, content) {
4401
- return {
4402
- ...requirements,
4403
- metadata: {
4404
- ...requirements.metadata,
4405
- pendingUserMessage: content,
4406
- },
4407
- };
4408
- }
4409
- }
4410
-
4411
- /**
4412
- * META commitment definition
4413
- *
4414
- * The META commitment handles all meta-information about the agent such as:
4415
- * - META IMAGE: Sets the agent's avatar/profile image URL
4416
- * - META LINK: Provides profile/source links for the person the agent models
4417
- * - META TITLE: Sets the agent's display title
4418
- * - META DESCRIPTION: Sets the agent's description
4419
- * - META [ANYTHING]: Any other meta information in uppercase format
4420
- *
4421
- * These commitments are special because they don't affect the system message,
4422
- * but are handled separately in the parsing logic for profile display.
4423
- *
4424
- * Example usage in agent source:
4425
- *
4426
- * ```book
4427
- * META IMAGE https://example.com/avatar.jpg
4428
- * META LINK https://twitter.com/username
4429
- * META TITLE Professional Assistant
4430
- * META DESCRIPTION An AI assistant specialized in business tasks
4431
- * META AUTHOR John Doe
4432
- * META VERSION 1.0
4433
- * ```
4434
- *
4435
- * @private [🪔] Maybe export the commitments through some package
4436
- */
4437
- class MetaCommitmentDefinition extends BaseCommitmentDefinition {
4438
- constructor() {
4439
- super('META');
4440
- }
4441
- /**
4442
- * Short one-line description of META commitments.
4443
- */
4444
- get description() {
4445
- return 'Set meta-information about the agent (IMAGE, LINK, TITLE, DESCRIPTION, etc.).';
4446
- }
4447
- /**
4448
- * Icon for this commitment.
4449
- */
4450
- get icon() {
4451
- return 'ℹ️';
4452
- }
4453
- /**
4454
- * Markdown documentation for META commitment.
4455
- */
4456
- get documentation() {
4457
- return spaceTrim$1(`
4458
- # META
4459
-
4460
- Sets meta-information about the agent that is used for display and attribution purposes.
4461
-
4462
- ## Supported META types
4463
-
4464
- - **META IMAGE** - Sets the agent's avatar/profile image URL
4465
- - **META LINK** - Provides profile/source links for the person the agent models
4466
- - **META TITLE** - Sets the agent's display title
4467
- - **META DESCRIPTION** - Sets the agent's description
4468
- - **META [ANYTHING]** - Any other meta information in uppercase format
4469
-
4470
- ## Key aspects
4471
-
4472
- - Does not modify the agent's behavior or responses
4473
- - Used for visual representation and attribution in user interfaces
4474
- - Multiple META commitments of different types can be used
4475
- - Multiple META LINK commitments can be used for different social profiles
4476
- - If multiple META commitments of the same type are specified, the last one takes precedence (except for LINK)
4477
-
4478
- ## Examples
4479
-
4480
- ### Basic meta information
4481
-
4482
- \`\`\`book
4483
- Professional Assistant
4484
-
4485
- META IMAGE https://example.com/professional-avatar.jpg
4486
- META TITLE Senior Business Consultant
4487
- META DESCRIPTION Specialized in strategic planning and project management
4488
- META LINK https://linkedin.com/in/professional
4489
- \`\`\`
4490
-
4491
- ### Multiple links and custom meta
4492
-
4493
- \`\`\`book
4494
- Open Source Developer
4495
-
4496
- META IMAGE /assets/dev-avatar.png
4497
- META LINK https://github.com/developer
4498
- META LINK https://twitter.com/devhandle
4499
- META AUTHOR Jane Smith
4500
- META VERSION 2.1
4501
- META LICENSE MIT
4502
- \`\`\`
4503
-
4504
- ### Creative assistant
4505
-
4506
- \`\`\`book
4507
- Creative Helper
4508
-
4509
- META IMAGE https://example.com/creative-bot.jpg
4510
- META TITLE Creative Writing Assistant
4511
- META DESCRIPTION Helps with brainstorming, storytelling, and creative projects
4512
- META INSPIRATION Books, movies, and real-world experiences
4513
- \`\`\`
4514
- `);
4515
- }
4516
- applyToAgentModelRequirements(requirements, content) {
4517
- // META commitments don't modify the system message or model requirements
4518
- // They are handled separately in the parsing logic for meta information extraction
4519
- // This method exists for consistency with the CommitmentDefinition interface
4520
- return requirements;
4521
- }
4522
- /**
4523
- * Extracts meta information from the content based on the meta type
4524
- * This is used by the parsing logic
4525
- */
4526
- extractMetaValue(metaType, content) {
4527
- const trimmedContent = content.trim();
4528
- return trimmedContent || null;
4529
- }
4530
- /**
4531
- * Validates if the provided content is a valid URL (for IMAGE and LINK types)
4532
- */
4533
- isValidUrl(content) {
4534
- try {
4535
- new URL(content.trim());
4536
- return true;
4537
- }
4538
- catch (_a) {
4539
- return false;
4540
- }
4541
- }
4542
- /**
4543
- * Checks if this is a known meta type
4544
- */
4545
- isKnownMetaType(metaType) {
4546
- const knownTypes = ['IMAGE', 'LINK', 'TITLE', 'DESCRIPTION', 'AUTHOR', 'VERSION', 'LICENSE'];
4547
- return knownTypes.includes(metaType.toUpperCase());
4548
- }
4549
- }
4550
- /**
4551
- * Note: [💞] Ignore a discrepancy between file name and entity name
4552
- */
4553
-
4554
- /**
4555
- * META COLOR commitment definition
4556
- *
4557
- * The META COLOR commitment sets the agent's accent color.
4558
- * This commitment is special because it doesn't affect the system message,
4559
- * but is handled separately in the parsing logic.
4560
- *
4561
- * Example usage in agent source:
4562
- *
4563
- * ```book
4564
- * META COLOR #ff0000
4565
- * META COLOR #00ff00
4566
- * ```
4567
- *
4568
- * You can also specify multiple colors separated by comma:
4569
- *
4570
- * ```book
4571
- * META COLOR #ff0000, #00ff00, #0000ff
4572
- * ```
4573
- *
4574
- * @private [🪔] Maybe export the commitments through some package
4575
- */
4576
- class MetaColorCommitmentDefinition extends BaseCommitmentDefinition {
4577
- constructor() {
4578
- super('META COLOR', ['COLOR']);
4579
- }
4580
- /**
4581
- * Short one-line description of META COLOR.
4582
- */
4583
- get description() {
4584
- return "Set the agent's accent color or gradient.";
4585
- }
4586
- /**
4587
- * Icon for this commitment.
4588
- */
4589
- get icon() {
4590
- return '🎨';
4591
- }
4592
- /**
4593
- * Markdown documentation for META COLOR commitment.
4594
- */
4595
- get documentation() {
4596
- return spaceTrim$1(`
4597
- # META COLOR
4598
-
4599
- Sets the agent's accent color or gradient.
4600
-
4601
- ## Key aspects
4602
-
4603
- - Does not modify the agent's behavior or responses.
4604
- - Only one \`META COLOR\` should be used per agent.
4605
- - If multiple are specified, the last one takes precedence.
4606
- - Used for visual representation in user interfaces.
4607
- - Can specify multiple colors separated by comma to create a gradient.
4608
-
4609
- ## Examples
4610
-
4611
- \`\`\`book
4612
- Professional Assistant
4613
-
4614
- META COLOR #3498db
4615
- PERSONA You are a professional business assistant
4616
- \`\`\`
4617
-
4618
- \`\`\`book
4619
- Creative Helper
4620
-
4621
- META COLOR #e74c3c
4622
- PERSONA You are a creative and inspiring assistant
4623
- \`\`\`
4624
-
4625
- \`\`\`book
4626
- Gradient Agent
4627
-
4628
- META COLOR #ff0000, #00ff00, #0000ff
4629
- PERSONA You are a colorful agent
4630
- \`\`\`
4631
- `);
4632
- }
4633
- applyToAgentModelRequirements(requirements, content) {
4634
- // META COLOR doesn't modify the system message or model requirements
4635
- // It's handled separately in the parsing logic for profile color extraction
4636
- // This method exists for consistency with the CommitmentDefinition interface
4637
- return requirements;
4638
- }
4639
- /**
4640
- * Extracts the profile color from the content
4641
- * This is used by the parsing logic
4642
- */
4643
- extractProfileColor(content) {
4644
- const trimmedContent = content.trim();
4645
- return trimmedContent || null;
4646
- }
4647
- }
4648
- /**
4649
- * Note: [💞] Ignore a discrepancy between file name and entity name
4650
- */
4651
-
4652
- /**
4653
- * META FONT commitment definition
4654
- *
4655
- * The META FONT commitment sets the agent's font.
4656
- * This commitment is special because it doesn't affect the system message,
4657
- * but is handled separately in the parsing logic.
4658
- *
4659
- * Example usage in agent source:
4660
- *
4661
- * ```book
4662
- * META FONT Poppins, Arial, sans-serif
4663
- * META FONT Roboto
4664
- * ```
4665
- *
4666
- * @private [🪔] Maybe export the commitments through some package
4667
- */
4668
- class MetaFontCommitmentDefinition extends BaseCommitmentDefinition {
4669
- constructor() {
4670
- super('META FONT', ['FONT']);
4671
- }
4672
- /**
4673
- * Short one-line description of META FONT.
4674
- */
4675
- get description() {
4676
- return "Set the agent's font.";
4677
- }
4678
- /**
4679
- * Icon for this commitment.
4680
- */
4681
- get icon() {
4682
- return '🔤';
4683
- }
4684
- /**
4685
- * Markdown documentation for META FONT commitment.
4686
- */
4687
- get documentation() {
4688
- return spaceTrim$1(`
4689
- # META FONT
4690
-
4691
- Sets the agent's font.
4692
-
4693
- ## Key aspects
4694
-
4695
- - Does not modify the agent's behavior or responses.
4696
- - Only one \`META FONT\` should be used per agent.
4697
- - If multiple are specified, the last one takes precedence.
4698
- - Used for visual representation in user interfaces.
4699
- - Supports Google Fonts.
4700
-
4701
- ## Examples
4702
-
4703
- \`\`\`book
4704
- Modern Assistant
4705
-
4706
- META FONT Poppins, Arial, sans-serif
4707
- PERSONA You are a modern assistant
4708
- \`\`\`
4709
-
4710
- \`\`\`book
4711
- Classic Helper
4712
-
4713
- META FONT Times New Roman
4714
- PERSONA You are a classic helper
4715
- \`\`\`
4716
- `);
4717
- }
4718
- applyToAgentModelRequirements(requirements, content) {
4719
- // META FONT doesn't modify the system message or model requirements
4720
- // It's handled separately in the parsing logic
4721
- // This method exists for consistency with the CommitmentDefinition interface
4722
- return requirements;
4723
- }
4724
- /**
4725
- * Extracts the font from the content
4726
- * This is used by the parsing logic
4727
- */
4728
- extractProfileFont(content) {
4729
- const trimmedContent = content.trim();
4730
- return trimmedContent || null;
4731
- }
4732
- }
4733
- /**
4734
- * Note: [💞] Ignore a discrepancy between file name and entity name
4735
- */
4736
-
4737
- /**
4738
- * META IMAGE commitment definition
4739
- *
4740
- * The META IMAGE commitment sets the agent's avatar/profile image URL.
4741
- * This commitment is special because it doesn't affect the system message,
4742
- * but is handled separately in the parsing logic.
4743
- *
4744
- * Example usage in agent source:
4745
- *
4746
- * ```book
4747
- * META IMAGE https://example.com/avatar.jpg
4748
- * META IMAGE /assets/agent-avatar.png
4749
- * ```
4750
- *
4751
- * @private [🪔] Maybe export the commitments through some package
4752
- */
4753
- class MetaImageCommitmentDefinition extends BaseCommitmentDefinition {
4754
- constructor() {
4755
- super('META IMAGE', ['IMAGE']);
4756
- }
4757
- /**
4758
- * Short one-line description of META IMAGE.
4759
- */
4760
- get description() {
4761
- return "Set the agent's profile image URL.";
4762
- }
4763
- /**
4764
- * Icon for this commitment.
4765
- */
4766
- get icon() {
4767
- return '🖼️';
4768
- }
4769
- /**
4770
- * Markdown documentation for META IMAGE commitment.
4771
- */
4772
- get documentation() {
4773
- return spaceTrim$1(`
4774
- # META IMAGE
4775
-
4776
- Sets the agent's avatar/profile image URL.
4777
-
4778
- ## Key aspects
4779
-
4780
- - Does not modify the agent's behavior or responses.
4781
- - Only one \`META IMAGE\` should be used per agent.
4782
- - If multiple are specified, the last one takes precedence.
4783
- - Used for visual representation in user interfaces.
4784
-
4785
- ## Examples
4786
-
4787
- \`\`\`book
4788
- Professional Assistant
4789
-
4790
- META IMAGE https://example.com/professional-avatar.jpg
4791
- PERSONA You are a professional business assistant
4792
- STYLE Maintain a formal and courteous tone
4793
- \`\`\`
4794
-
4795
- \`\`\`book
4796
- Creative Helper
4797
-
4798
- META IMAGE /assets/creative-bot-avatar.png
4799
- PERSONA You are a creative and inspiring assistant
4800
- STYLE Be enthusiastic and encouraging
4801
- ACTION Can help with brainstorming and ideation
4802
- \`\`\`
4803
- `);
4804
- }
4805
- applyToAgentModelRequirements(requirements, content) {
4806
- // META IMAGE doesn't modify the system message or model requirements
4807
- // It's handled separately in the parsing logic for profile image extraction
4808
- // This method exists for consistency with the CommitmentDefinition interface
4809
- return requirements;
4810
- }
4811
- /**
4812
- * Extracts the profile image URL from the content
4813
- * This is used by the parsing logic
4814
- */
4815
- extractProfileImageUrl(content) {
4816
- const trimmedContent = content.trim();
4817
- return trimmedContent || null;
4818
- }
4819
- }
4820
- /**
4821
- * Note: [💞] Ignore a discrepancy between file name and entity name
4822
- */
4823
-
4824
- /**
4825
- * META LINK commitment definition
4826
- *
4827
- * The `META LINK` commitment represents the link to the person from whom the agent is created.
4828
- * This commitment is special because it doesn't affect the system message,
4829
- * but is handled separately in the parsing logic for profile display.
4830
- *
4831
- * Example usage in agent source:
4832
- *
4833
- * ```
4834
- * META LINK https://twitter.com/username
4835
- * META LINK https://linkedin.com/in/profile
4836
- * META LINK https://github.com/username
4837
- * ```
4838
- *
4839
- * Multiple `META LINK` commitments can be used when there are multiple sources:
4840
- *
4841
- * ```book
4842
- * META LINK https://twitter.com/username
4843
- * META LINK https://linkedin.com/in/profile
4844
- * ```
4845
- *
4846
- * @private [🪔] Maybe export the commitments through some package
4847
- */
4848
- class MetaLinkCommitmentDefinition extends BaseCommitmentDefinition {
4849
- constructor() {
4850
- super('META LINK');
4851
- }
4852
- /**
4853
- * Short one-line description of META LINK.
4854
- */
4855
- get description() {
4856
- return 'Provide profile/source links for the person the agent models.';
4857
- }
4858
- /**
4859
- * Icon for this commitment.
4860
- */
4861
- get icon() {
4862
- return '🔗';
4863
- }
4864
- /**
4865
- * Markdown documentation for META LINK commitment.
4866
- */
4867
- get documentation() {
4868
- return spaceTrim$1(`
4869
- # META LINK
4870
-
4871
- Represents a profile or source link for the person the agent is modeled after.
4872
-
4873
- ## Key aspects
4874
-
4875
- - Does not modify the agent's behavior or responses.
4876
- - Multiple \`META LINK\` commitments can be used for different social profiles.
4877
- - Used for attribution and crediting the original person.
4878
- - Displayed in user interfaces for transparency.
4879
-
4880
- ## Examples
4881
-
4882
- \`\`\`book
4883
- Expert Consultant
4884
-
4885
- META LINK https://twitter.com/expertname
4886
- META LINK https://linkedin.com/in/expertprofile
4887
- PERSONA You are Dr. Smith, a renowned expert in artificial intelligence
4888
- KNOWLEDGE Extensive background in machine learning and neural networks
4889
- \`\`\`
4890
-
4891
- \`\`\`book
4892
- Open Source Developer
4893
-
4894
- META LINK https://github.com/developer
4895
- META LINK https://twitter.com/devhandle
4896
- PERSONA You are an experienced open source developer
4897
- ACTION Can help with code reviews and architecture decisions
4898
- STYLE Be direct and technical in explanations
4899
- \`\`\`
4900
- `);
4901
- }
4902
- applyToAgentModelRequirements(requirements, content) {
4903
- // META LINK doesn't modify the system message or model requirements
4904
- // It's handled separately in the parsing logic for profile link extraction
4905
- // This method exists for consistency with the CommitmentDefinition interface
4906
- return requirements;
4907
- }
4908
- /**
4909
- * Extracts the profile link URL from the content
4910
- * This is used by the parsing logic
4911
- */
4912
- extractProfileLinkUrl(content) {
4913
- const trimmedContent = content.trim();
4914
- return trimmedContent || null;
4915
- }
4916
- /**
4917
- * Validates if the provided content is a valid URL
4918
- */
4919
- isValidUrl(content) {
4920
- try {
4921
- new URL(content.trim());
4922
- return true;
4923
- }
4924
- catch (_a) {
4925
- return false;
4926
- }
4927
- }
4928
- }
4929
- /**
4930
- * Note: [💞] Ignore a discrepancy between file name and entity name
4931
- */
4932
-
4933
- /**
4934
- * MODEL commitment definition
4935
- *
4936
- * The MODEL commitment specifies which AI model to use and can also set
4937
- * model-specific parameters like temperature, topP, topK, and maxTokens.
4938
- *
4939
- * Supports multiple syntax variations:
4940
- *
4941
- * Single-line format:
4942
- * ```book
4943
- * MODEL gpt-4
4944
- * MODEL claude-3-opus temperature=0.3
4945
- * MODEL gpt-3.5-turbo temperature=0.8 topP=0.9
4946
- * ```
4947
- *
4948
- * Multi-line named parameter format:
4949
- * ```book
4950
- * MODEL NAME gpt-4
4951
- * MODEL TEMPERATURE 0.7
4952
- * MODEL TOP_P 0.9
4953
- * MODEL MAX_TOKENS 2048
4954
- * ```
4955
- *
4956
- * @private [🪔] Maybe export the commitments through some package
4957
- */
4958
- class ModelCommitmentDefinition extends BaseCommitmentDefinition {
4959
- constructor(type = 'MODEL') {
4960
- super(type);
4961
- }
4962
- /**
4963
- * Short one-line description of MODEL.
4964
- */
4965
- get description() {
4966
- return 'Enforce AI model requirements including name and technical parameters.';
4967
- }
4968
- /**
4969
- * Icon for this commitment.
4970
- */
4971
- get icon() {
4972
- return '⚙️';
4973
- }
4974
- /**
4975
- * Markdown documentation for MODEL commitment.
4976
- */
4977
- get documentation() {
4978
- return spaceTrim$1(`
4979
- # ${this.type}
4980
-
4981
- Enforces technical parameters for the AI model, ensuring consistent behavior across different execution environments.
4982
-
4983
- ## Key aspects
4984
-
4985
- - When no \`MODEL\` commitment is specified, the best model requirement is picked automatically based on the agent \`PERSONA\`, \`KNOWLEDGE\`, \`TOOLS\` and other commitments
4986
- - Multiple \`MODEL\` commitments can be used to specify different parameters
4987
- - Both \`MODEL\` and \`MODELS\` terms work identically and can be used interchangeably
4988
- - Parameters control the randomness, creativity, and technical aspects of model responses
4989
-
4990
- ## Syntax variations
4991
-
4992
- ### Single-line format (legacy support)
4993
- \`\`\`book
4994
- MODEL gpt-4
4995
- MODEL claude-3-opus temperature=0.3
4996
- MODEL gpt-3.5-turbo temperature=0.8 topP=0.9
4997
- \`\`\`
4998
-
4999
- ### Multi-line named parameter format (recommended)
5000
- \`\`\`book
5001
- MODEL NAME gpt-4
5002
- MODEL TEMPERATURE 0.7
5003
- MODEL TOP_P 0.9
5004
- MODEL MAX_TOKENS 2048
5005
- \`\`\`
5006
-
5007
- ## Supported parameters
5008
-
5009
- - \`NAME\`: The specific model to use (e.g., 'gpt-4', 'claude-3-opus')
5010
- - \`TEMPERATURE\`: Controls randomness (0.0 = deterministic, 1.0+ = creative)
5011
- - \`TOP_P\`: Nucleus sampling parameter for controlling diversity
5012
- - \`TOP_K\`: Top-k sampling parameter for limiting vocabulary
5013
- - \`MAX_TOKENS\`: Maximum number of tokens the model can generate
5014
-
5015
- ## Examples
5016
-
5017
- ### Precise deterministic assistant
5018
- \`\`\`book
5019
- Precise Assistant
5020
-
5021
- PERSONA You are a precise and accurate assistant
5022
- MODEL NAME gpt-4
5023
- MODEL TEMPERATURE 0.1
5024
- MODEL MAX_TOKENS 1024
5025
- RULE Always provide factual information
5026
- \`\`\`
5027
-
5028
- ### Creative writing assistant
5029
- \`\`\`book
5030
- Creative Writer
5031
-
5032
- PERSONA You are a creative writing assistant
5033
- MODEL NAME claude-3-opus
5034
- MODEL TEMPERATURE 0.8
5035
- MODEL TOP_P 0.9
5036
- MODEL MAX_TOKENS 2048
5037
- STYLE Be imaginative and expressive
5038
- ACTION Can help with storytelling and character development
5039
- \`\`\`
5040
-
5041
- ### Balanced conversational agent
5042
- \`\`\`book
5043
- Balanced Assistant
5044
-
5045
- PERSONA You are a helpful and balanced assistant
5046
- MODEL NAME gpt-4
5047
- MODEL TEMPERATURE 0.7
5048
- MODEL TOP_P 0.95
5049
- MODEL TOP_K 40
5050
- MODEL MAX_TOKENS 1500
5051
- \`\`\`
5052
- `);
5053
- }
5054
- applyToAgentModelRequirements(requirements, content) {
5055
- var _a;
5056
- const trimmedContent = content.trim();
5057
- if (!trimmedContent) {
5058
- return requirements;
5059
- }
5060
- const parts = trimmedContent.split(/\s+/);
5061
- const firstPart = (_a = parts[0]) === null || _a === void 0 ? void 0 : _a.toUpperCase();
5062
- // Check if this is the new named parameter format
5063
- if (this.isNamedParameter(firstPart)) {
5064
- return this.parseNamedParameter(requirements, firstPart, parts.slice(1));
5065
- }
5066
- else {
5067
- // Legacy single-line format: "MODEL gpt-4 temperature=0.3 topP=0.9"
5068
- return this.parseLegacyFormat(requirements, parts);
5069
- }
5070
- }
5071
- /**
5072
- * Check if the first part is a known named parameter
5073
- */
5074
- isNamedParameter(part) {
5075
- if (!part)
5076
- return false;
5077
- const knownParams = ['NAME', 'TEMPERATURE', 'TOP_P', 'TOP_K', 'MAX_TOKENS'];
5078
- return knownParams.includes(part);
5079
- }
5080
- /**
5081
- * Parse the new named parameter format: "MODEL TEMPERATURE 0.7"
5082
- */
5083
- parseNamedParameter(requirements, parameterName, valueParts) {
5084
- const value = valueParts.join(' ').trim();
5085
- if (!value) {
5086
- return requirements;
5087
- }
5088
- const result = { ...requirements };
5089
- switch (parameterName) {
5090
- case 'NAME':
5091
- result.modelName = value;
5092
- break;
5093
- case 'TEMPERATURE': {
5094
- const temperature = parseFloat(value);
5095
- if (!isNaN(temperature)) {
5096
- result.temperature = temperature;
5097
- }
5098
- break;
5099
- }
5100
- case 'TOP_P': {
5101
- const topP = parseFloat(value);
5102
- if (!isNaN(topP)) {
5103
- result.topP = topP;
5104
- }
5105
- break;
5106
- }
5107
- case 'TOP_K': {
5108
- const topK = parseFloat(value);
5109
- if (!isNaN(topK)) {
5110
- result.topK = Math.round(topK);
5111
- }
5112
- break;
5113
- }
5114
- case 'MAX_TOKENS': {
5115
- const maxTokens = parseFloat(value);
5116
- if (!isNaN(maxTokens)) {
5117
- result.maxTokens = Math.round(maxTokens);
5118
- }
5119
- break;
5120
- }
5121
- }
5122
- return result;
5123
- }
5124
- /**
5125
- * Parse the legacy format: "MODEL gpt-4 temperature=0.3 topP=0.9"
5126
- */
5127
- parseLegacyFormat(requirements, parts) {
5128
- const modelName = parts[0];
5129
- if (!modelName) {
5130
- return requirements;
5131
- }
5132
- // Start with the model name
5133
- const result = {
5134
- ...requirements,
5135
- modelName,
5136
- };
5137
- // Parse additional key=value parameters
5138
- for (let i = 1; i < parts.length; i++) {
5139
- const param = parts[i];
5140
- if (param && param.includes('=')) {
5141
- const [key, value] = param.split('=');
5142
- if (key && value) {
5143
- const numValue = parseFloat(value);
5144
- if (!isNaN(numValue)) {
5145
- switch (key.toLowerCase()) {
5146
- case 'temperature':
5147
- result.temperature = numValue;
5148
- break;
5149
- case 'topp':
5150
- case 'top_p':
5151
- result.topP = numValue;
5152
- break;
5153
- case 'topk':
5154
- case 'top_k':
5155
- result.topK = Math.round(numValue);
5156
- break;
5157
- case 'max_tokens':
5158
- case 'maxTokens':
5159
- result.maxTokens = Math.round(numValue);
5160
- break;
5161
- }
5162
- }
5163
- }
5164
- }
5165
- }
5166
- return result;
5167
- }
5168
- }
5169
- /**
5170
- * Note: [💞] Ignore a discrepancy between file name and entity name
5171
- */
5172
-
5173
- /**
5174
- * NOTE commitment definition
5175
- *
5176
- * The NOTE commitment is used to add comments to the agent source without making any changes
5177
- * to the system message or agent model requirements. It serves as a documentation mechanism
5178
- * for developers to add explanatory comments, reminders, or annotations directly in the agent source.
5179
- *
5180
- * Key features:
5181
- * - Makes no changes to the system message
5182
- * - Makes no changes to agent model requirements
5183
- * - Content is preserved in metadata.NOTE for debugging and inspection
5184
- * - Multiple NOTE commitments are aggregated together
5185
- * - Comments (# NOTE) are removed from the final system message
5186
- *
5187
- * Example usage in agent source:
5188
- *
5189
- * ```book
5190
- * NOTE This agent was designed for customer support scenarios
5191
- * NOTE Remember to update the knowledge base monthly
5192
- * NOTE Performance optimized for quick response times
5193
- * ```
5194
- *
5195
- * The above notes will be stored in metadata but won't affect the agent's behavior.
5196
- *
5197
- * @private [🪔] Maybe export the commitments through some package
5198
- */
5199
- class NoteCommitmentDefinition extends BaseCommitmentDefinition {
5200
- constructor(type = 'NOTE') {
5201
- super(type);
5202
- }
5203
- /**
5204
- * Short one-line description of NOTE.
5205
- */
5206
- get description() {
5207
- return 'Add developer-facing notes without changing behavior or output.';
5208
- }
5209
- /**
5210
- * Icon for this commitment.
5211
- */
5212
- get icon() {
5213
- return '📝';
5214
- }
5215
- /**
5216
- * Markdown documentation for NOTE commitment.
5217
- */
5218
- get documentation() {
5219
- return spaceTrim$1(`
5220
- # ${this.type}
5221
-
5222
- Adds comments for documentation without changing agent behavior.
5223
-
5224
- ## Key aspects
5225
-
5226
- - Does not modify the agent's behavior or responses.
5227
- - Multiple \`NOTE\`, \`NOTES\`, \`COMMENT\`, and \`NONCE\` commitments are aggregated for debugging.
5228
- - All four terms work identically and can be used interchangeably.
5229
- - Useful for documenting design decisions and reminders.
5230
- - Content is preserved in metadata for inspection.
5231
-
5232
- ## Examples
5233
-
5234
- \`\`\`book
5235
- Customer Support Bot
5236
-
5237
- NOTE This agent was designed for customer support scenarios
5238
- COMMENT Remember to update the knowledge base monthly
5239
- PERSONA You are a helpful customer support representative
5240
- KNOWLEDGE Company policies and procedures
5241
- RULE Always be polite and professional
5242
- \`\`\`
5243
-
5244
- \`\`\`book
5245
- Research Assistant
5246
-
5247
- NONCE Performance optimized for quick response times
5248
- NOTE Uses RAG for accessing latest research papers
5249
- PERSONA You are a knowledgeable research assistant
5250
- ACTION Can help with literature reviews and citations
5251
- STYLE Present information in academic format
5252
- \`\`\`
5253
- `);
5254
- }
5255
- applyToAgentModelRequirements(requirements, content) {
5256
- // The NOTE commitment makes no changes to the system message or model requirements
5257
- // It only stores the note content in metadata for documentation purposes
5258
- const trimmedContent = spaceTrim$1(content);
5259
- if (trimmedContent === '') {
5260
- return requirements;
5261
- }
5262
- // Return requirements with updated notes but no changes to system message
5263
- return {
5264
- ...requirements,
5265
- notes: [...(requirements.notes || []), trimmedContent],
5266
- };
5267
- }
5268
- }
5269
- /**
5270
- * [💞] Ignore a discrepancy between file name and entity name
5271
- */
5272
-
5273
- /**
5274
- * OPEN commitment definition
5275
- *
5276
- * The OPEN commitment specifies that the agent can be modified by conversation.
5277
- * This is the default behavior.
5278
- *
5279
- * Example usage in agent source:
5280
- *
5281
- * ```book
5282
- * OPEN
5283
- * ```
5284
- *
5285
- * @private [🪔] Maybe export the commitments through some package
5286
- */
5287
- class OpenCommitmentDefinition extends BaseCommitmentDefinition {
5288
- constructor() {
5289
- super('OPEN');
5290
- }
5291
- /**
5292
- * Short one-line description of OPEN.
5293
- */
5294
- get description() {
5295
- return 'Allow the agent to be modified by conversation (default).';
5296
- }
5297
- /**
5298
- * Icon for this commitment.
5299
- */
5300
- get icon() {
5301
- return '🔓';
5302
- }
5303
- /**
5304
- * Markdown documentation for OPEN commitment.
5305
- */
5306
- get documentation() {
5307
- return spaceTrim$1(`
5308
- # OPEN
5309
-
5310
- Specifies that the agent can be modified by conversation with it.
5311
- This means the agent will learn from interactions and update its source code.
5312
-
5313
- This is the default behavior if neither \`OPEN\` nor \`CLOSED\` is specified.
5314
-
5315
- > See also [CLOSED](/docs/CLOSED)
5316
-
5317
- ## Example
5318
-
5319
- \`\`\`book
5320
- OPEN
5321
- \`\`\`
5322
- `);
5323
- }
5324
- applyToAgentModelRequirements(requirements, _content) {
5325
- // Since OPEN is default, we can just ensure isClosed is false
5326
- // But to be explicit we can set it
5327
- const updatedMetadata = {
5328
- ...requirements.metadata,
5329
- isClosed: false,
5330
- };
5331
- return {
5332
- ...requirements,
5333
- metadata: updatedMetadata,
5334
- };
5335
- }
5336
- }
5337
- /**
5338
- * Note: [💞] Ignore a discrepancy between file name and entity name
5339
- */
5340
-
5341
- /**
5342
- * PERSONA commitment definition
5343
- *
5344
- * The PERSONA commitment modifies the agent's personality and character in the system message.
5345
- * It defines who the agent is, their background, expertise, and personality traits.
5346
- *
5347
- * Key features:
5348
- * - Multiple PERSONA commitments are automatically merged into one
5349
- * - Content is placed at the beginning of the system message
5350
- * - Original content with comments is preserved in metadata.PERSONA
5351
- * - Comments (# PERSONA) are removed from the final system message
5352
- *
5353
- * Example usage in agent source:
5354
- *
5355
- * ```book
5356
- * PERSONA You are a helpful programming assistant with expertise in TypeScript and React
5357
- * PERSONA You have deep knowledge of modern web development practices
5358
- * ```
5359
- *
5360
- * The above will be merged into a single persona section at the beginning of the system message.
5361
- *
5362
- * @private [🪔] Maybe export the commitments through some package
5363
- */
5364
- class PersonaCommitmentDefinition extends BaseCommitmentDefinition {
5365
- constructor(type = 'PERSONA') {
5366
- super(type);
5367
- }
5368
- /**
5369
- * Short one-line description of PERSONA.
5370
- */
5371
- get description() {
5372
- return 'Define who the agent is: background, expertise, and personality.';
5373
- }
5374
- /**
5375
- * Icon for this commitment.
5376
- */
5377
- get icon() {
5378
- return '👤';
5379
- }
5380
- /**
5381
- * Markdown documentation for PERSONA commitment.
5382
- */
5383
- get documentation() {
5384
- return spaceTrim$1(`
5385
- # ${this.type}
5386
-
5387
- Defines who the agent is, their background, expertise, and personality traits.
5388
-
5389
- ## Key aspects
5390
-
5391
- - Multiple \`PERSONA\` and \`PERSONAE\` commitments are merged together.
5392
- - Both terms work identically and can be used interchangeably.
5393
- - If they are in conflict, the last one takes precedence.
5394
- - You can write persona content in multiple lines.
5395
-
5396
- ## Examples
5397
-
5398
- \`\`\`book
5399
- Programming Assistant
5400
-
5401
- PERSONA You are a helpful programming assistant with expertise in TypeScript and React
5402
- PERSONA You have deep knowledge of modern web development practices
5403
- \`\`\`
5404
- `);
5405
- }
5406
- applyToAgentModelRequirements(requirements, content) {
5407
- var _a, _b;
5408
- // The PERSONA commitment aggregates all persona content and places it at the beginning
5409
- const trimmedContent = content.trim();
5410
- if (!trimmedContent) {
5411
- return requirements;
5412
- }
5413
- // Get existing persona content from metadata
5414
- const existingPersonaContent = ((_a = requirements.metadata) === null || _a === void 0 ? void 0 : _a.PERSONA) || '';
5415
- // Merge the new content with existing persona content
5416
- // When multiple PERSONA commitments exist, they are merged into one
5417
- const mergedPersonaContent = existingPersonaContent
5418
- ? `${existingPersonaContent}\n${trimmedContent}`
5419
- : trimmedContent;
5420
- // Store the merged persona content in metadata for debugging and inspection
5421
- const updatedMetadata = {
5422
- ...requirements.metadata,
5423
- PERSONA: mergedPersonaContent,
5424
- };
5425
- // Get the agent name from metadata (which should contain the first line of agent source)
5426
- // If not available, extract from current system message as fallback
5427
- let agentName = (_b = requirements.metadata) === null || _b === void 0 ? void 0 : _b.agentName;
5428
- if (!agentName) {
5429
- // Fallback: extract from current system message
5430
- const currentMessage = requirements.systemMessage.trim();
5431
- const basicFormatMatch = currentMessage.match(/^You are (.+)$/);
5432
- if (basicFormatMatch && basicFormatMatch[1]) {
5433
- agentName = basicFormatMatch[1];
5434
- }
5435
- else {
5436
- agentName = 'AI Agent'; // Final fallback
5437
- }
5438
- }
5439
- // Remove any existing persona content from the system message
5440
- // (this handles the case where we're processing multiple PERSONA commitments)
5441
- const currentMessage = requirements.systemMessage.trim();
5442
- let cleanedMessage = currentMessage;
5443
- // Check if current message starts with persona content or is just the basic format
5444
- const basicFormatRegex = /^You are .+$/;
5445
- const isBasicFormat = basicFormatRegex.test(currentMessage) && !currentMessage.includes('\n');
5446
- if (isBasicFormat) {
5447
- // Replace the basic format entirely
5448
- cleanedMessage = '';
5449
- }
5450
- else if (currentMessage.startsWith('# PERSONA')) {
5451
- // Remove existing persona section by finding where it ends
5452
- const lines = currentMessage.split('\n');
5453
- let personaEndIndex = lines.length;
5454
- // Find the end of the PERSONA section (next comment or end of message)
5455
- for (let i = 1; i < lines.length; i++) {
5456
- const line = lines[i].trim();
5457
- if (line.startsWith('#') && !line.startsWith('# PERSONA')) {
5458
- personaEndIndex = i;
5459
- break;
5460
- }
5461
- }
5462
- // Keep everything after the PERSONA section
5463
- cleanedMessage = lines.slice(personaEndIndex).join('\n').trim();
5464
- }
5465
- // TODO: [🕛] There should be `agentFullname` not `agentName`
5466
- // Create new system message with persona at the beginning
5467
- // Format: "You are {agentName}\n{personaContent}"
5468
- // The # PERSONA comment will be removed later by removeCommentsFromSystemMessage
5469
- const personaSection = `# PERSONA\nYou are ${agentName}\n${mergedPersonaContent}`; // <- TODO: Use spaceTrim
5470
- const newSystemMessage = cleanedMessage ? `${personaSection}\n\n${cleanedMessage}` : personaSection;
5471
- return {
5472
- ...requirements,
5473
- systemMessage: newSystemMessage,
5474
- metadata: updatedMetadata,
5475
- };
5476
- }
5477
- }
5478
- /**
5479
- * Note: [💞] Ignore a discrepancy between file name and entity name
5480
- */
5481
-
5482
- /**
5483
- * RULE commitment definition
5484
- *
5485
- * The RULE/RULES commitment adds behavioral constraints and guidelines that the agent must follow.
5486
- * These are specific instructions about what the agent should or shouldn't do.
5487
- *
5488
- * Example usage in agent source:
5489
- *
5490
- * ```book
5491
- * RULE Always ask for clarification if the user's request is ambiguous
5492
- * RULES Never provide medical advice, always refer to healthcare professionals
5493
- * ```
5494
- *
5495
- * @private [🪔] Maybe export the commitments through some package
5496
- */
5497
- class RuleCommitmentDefinition extends BaseCommitmentDefinition {
5498
- constructor(type = 'RULE') {
5499
- super(type);
5500
- }
5501
- /**
5502
- * Short one-line description of RULE/RULES.
5503
- */
5504
- get description() {
5505
- return 'Add behavioral rules the agent must follow.';
5506
- }
5507
- /**
5508
- * Icon for this commitment.
5509
- */
5510
- get icon() {
5511
- return '⚖️';
5512
- }
5513
- /**
5514
- * Markdown documentation for RULE/RULES commitment.
5515
- */
5516
- get documentation() {
5517
- return spaceTrim$1(`
5518
- # ${this.type}
5519
-
5520
- Adds behavioral constraints and guidelines that the agent must follow.
5521
-
5522
- ## Key aspects
5523
-
5524
- - All rules are treated equally regardless of singular/plural form.
5525
- - Rules define what the agent must or must not do.
5526
-
5527
- ## Examples
5528
-
5529
- \`\`\`book
5530
- Customer Support Agent
5531
-
5532
- PERSONA You are a helpful customer support representative
5533
- RULE Always ask for clarification if the user's request is ambiguous
5534
- RULE Be polite and professional in all interactions
5535
- RULES Never provide medical or legal advice
5536
- STYLE Maintain a friendly and helpful tone
5537
- \`\`\`
5538
-
5539
- \`\`\`book
5540
- Educational Tutor
5541
-
5542
- PERSONA You are a patient and knowledgeable tutor
5543
- RULE Break down complex concepts into simple steps
5544
- RULE Always encourage students and celebrate their progress
5545
- RULE If you don't know something, admit it and suggest resources
5546
- SAMPLE When explaining math: "Let's work through this step by step..."
5547
- \`\`\`
5548
- `);
5549
- }
5550
- applyToAgentModelRequirements(requirements, content) {
5551
- const trimmedContent = content.trim();
5552
- if (!trimmedContent) {
5553
- return requirements;
5554
- }
5555
- // Add rule to the system message
5556
- const ruleSection = `Rule: ${trimmedContent}`;
5557
- return this.appendToSystemMessage(requirements, ruleSection, '\n\n');
5558
- }
5559
- }
5560
- /**
5561
- * Note: [💞] Ignore a discrepancy between file name and entity name
5562
- */
5563
-
5564
- /**
5565
- * SAMPLE commitment definition
5566
- *
5567
- * The SAMPLE/EXAMPLE commitment provides examples of how the agent should respond
5568
- * or behave in certain situations. These examples help guide the agent's responses.
5569
- *
5570
- * Example usage in agent source:
5571
- *
5572
- * ```book
5573
- * SAMPLE When asked about pricing, respond: "Our basic plan starts at $10/month..."
5574
- * EXAMPLE For code questions, always include working code snippets
5575
- * ```
5576
- *
5577
- * @private [🪔] Maybe export the commitments through some package
5578
- */
5579
- class SampleCommitmentDefinition extends BaseCommitmentDefinition {
5580
- constructor(type = 'SAMPLE') {
5581
- super(type);
5582
- }
5583
- /**
5584
- * Short one-line description of SAMPLE/EXAMPLE.
5585
- */
5586
- get description() {
5587
- return 'Provide example responses to guide behavior.';
5588
- }
5589
- /**
5590
- * Icon for this commitment.
5591
- */
5592
- get icon() {
5593
- return '🔍';
5594
- }
5595
- /**
5596
- * Markdown documentation for SAMPLE/EXAMPLE commitment.
5597
- */
5598
- get documentation() {
5599
- return spaceTrim$1(`
5600
- # ${this.type}
5601
-
5602
- Provides examples of how the agent should respond or behave in certain situations.
5603
-
5604
- ## Key aspects
5605
-
5606
- - Both terms work identically and can be used interchangeably.
5607
- - Examples help guide the agent's response patterns and style.
5608
-
5609
- ## Examples
5610
-
5611
- \`\`\`book
5612
- Sales Assistant
5613
-
5614
- PERSONA You are a knowledgeable sales representative
5615
- SAMPLE When asked about pricing, respond: "Our basic plan starts at $10/month..."
5616
- SAMPLE For feature comparisons, create a clear comparison table
5617
- RULE Always be honest about limitations
5618
- \`\`\`
5619
-
5620
- \`\`\`book
5621
- Code Reviewer
5622
-
5623
- PERSONA You are an experienced software engineer
5624
- EXAMPLE For code questions, always include working code snippets
5625
- EXAMPLE When suggesting improvements: "Here's a more efficient approach..."
5626
- RULE Explain the reasoning behind your suggestions
5627
- STYLE Be constructive and encouraging in feedback
5628
- \`\`\`
5629
- `);
5630
- }
5631
- applyToAgentModelRequirements(requirements, content) {
5632
- const trimmedContent = content.trim();
5633
- if (!trimmedContent) {
5634
- return requirements;
5635
- }
5636
- // Add example to the system message
5637
- const exampleSection = `Example: ${trimmedContent}`;
5638
- return this.appendToSystemMessage(requirements, exampleSection, '\n\n');
5639
- }
5640
- }
5641
- /**
5642
- * Note: [💞] Ignore a discrepancy between file name and entity name
5643
- */
5644
-
5645
- /**
5646
- * SCENARIO commitment definition
5647
- *
5648
- * The SCENARIO commitment defines a specific situation or context in which the AI
5649
- * assistant should operate. It helps to set the scene for the AI's responses.
5650
- * Later scenarios are more important than earlier scenarios.
5651
- *
5652
- * Example usage in agent source:
5653
- *
5654
- * ```book
5655
- * SCENARIO You are in a customer service call center during peak hours
5656
- * SCENARIO The customer is frustrated and has been on hold for 20 minutes
5657
- * SCENARIO This is the customer's third call about the same issue
5658
- * ```
5659
- *
5660
- * @private [🪔] Maybe export the commitments through some package
5661
- */
5662
- class ScenarioCommitmentDefinition extends BaseCommitmentDefinition {
5663
- constructor(type = 'SCENARIO') {
5664
- super(type);
5665
- }
5666
- /**
5667
- * Short one-line description of SCENARIO.
5668
- */
5669
- get description() {
5670
- return 'Define specific **situations** or contexts for AI responses, with later scenarios having higher priority.';
5671
- }
5672
- /**
5673
- * Icon for this commitment.
5674
- */
5675
- get icon() {
5676
- return '🎭';
5677
- }
5678
- /**
5679
- * Markdown documentation for SCENARIO commitment.
5680
- */
5681
- get documentation() {
5682
- return spaceTrim$1(`
5683
- # ${this.type}
5684
-
5685
- Defines a specific situation or context in which the AI assistant should operate. It helps to set the scene for the AI's responses. Later scenarios are more important than earlier scenarios.
5686
-
5687
- ## Key aspects
5688
-
5689
- - Multiple \`SCENARIO\` and \`SCENARIOS\` commitments build upon each other.
5690
- - Both terms work identically and can be used interchangeably.
5691
- - Later scenarios have higher priority and can override earlier scenarios.
5692
- - Provides situational context that influences response tone and content.
5693
- - Helps establish the environment and circumstances for interactions.
5694
-
5695
- ## Priority system
5696
-
5697
- When multiple scenarios are defined, they are processed in order, with later scenarios taking precedence over earlier ones when there are conflicts.
5698
-
5699
- ## Use cases
5700
-
5701
- - Setting the physical or virtual environment
5702
- - Establishing time constraints or urgency
5703
- - Defining relationship dynamics or power structures
5704
- - Creating emotional or situational context
5705
-
5706
- ## Examples
5707
-
5708
- \`\`\`book
5709
- Emergency Response Operator
5710
-
5711
- PERSONA You are an emergency response operator
5712
- SCENARIO You are handling a 911 emergency call
5713
- SCENARIO The caller is panicked and speaking rapidly
5714
- SCENARIO Time is critical - every second counts
5715
- GOAL Gather essential information quickly and dispatch appropriate help
5716
- RULE Stay calm and speak clearly
5717
- \`\`\`
5718
-
5719
- \`\`\`book
5720
- Sales Representative
5721
-
5722
- PERSONA You are a software sales representative
5723
- SCENARIO You are in the final meeting of a 6-month sales cycle
5724
- SCENARIO The client has budget approval and decision-making authority
5725
- SCENARIO Two competitors have also submitted proposals
5726
- SCENARIO The client values long-term partnership over lowest price
5727
- GOAL Close the deal while building trust for future business
5728
- \`\`\`
5729
-
5730
- \`\`\`book
5731
- Medical Assistant
5732
-
5733
- PERSONA You are a medical assistant in a busy clinic
5734
- SCENARIO The waiting room is full and the doctor is running behind schedule
5735
- SCENARIO Patients are becoming impatient and anxious
5736
- SCENARIO You need to manage expectations while maintaining professionalism
5737
- SCENARIO Some patients have been waiting over an hour
5738
- GOAL Keep patients informed and calm while supporting efficient clinic flow
5739
- RULE Never provide medical advice or diagnosis
5740
- \`\`\`
5741
-
5742
- \`\`\`book
5743
- Technical Support Agent
5744
-
5745
- PERSONA You are a technical support agent
5746
- SCENARIO The customer is a small business owner during their busy season
5747
- SCENARIO Their main business system has been down for 2 hours
5748
- SCENARIO They are losing money every minute the system is offline
5749
- SCENARIO This is their first experience with your company
5750
- GOAL Resolve the issue quickly while creating a positive first impression
5751
- \`\`\`
5752
- `);
5753
- }
5754
- applyToAgentModelRequirements(requirements, content) {
5755
- const trimmedContent = content.trim();
5756
- if (!trimmedContent) {
5757
- return requirements;
5758
- }
5759
- // Create scenario section for system message
5760
- const scenarioSection = `Scenario: ${trimmedContent}`;
5761
- // Scenarios provide important contextual information that affects behavior
5762
- return this.appendToSystemMessage(requirements, scenarioSection, '\n\n');
5763
- }
5764
- }
5765
- /**
5766
- * Note: [💞] Ignore a discrepancy between file name and entity name
5767
- */
5768
-
5769
- /**
5770
- * STYLE commitment definition
5771
- *
5772
- * The STYLE commitment defines how the agent should format and present its responses.
5773
- * This includes tone, writing style, formatting preferences, and communication patterns.
5774
- *
5775
- * Example usage in agent source:
5776
- *
5777
- * ```book
5778
- * STYLE Write in a professional but friendly tone, use bullet points for lists
5779
- * STYLE Always provide code examples when explaining programming concepts
5780
- * ```
5781
- *
5782
- * @private [🪔] Maybe export the commitments through some package
5783
- */
5784
- class StyleCommitmentDefinition extends BaseCommitmentDefinition {
5785
- constructor(type = 'STYLE') {
5786
- super(type);
5787
- }
5788
- /**
5789
- * Short one-line description of STYLE.
5790
- */
5791
- get description() {
5792
- return 'Control the tone and writing style of responses.';
5793
- }
5794
- /**
5795
- * Icon for this commitment.
5796
- */
5797
- get icon() {
5798
- return '🖋️';
5799
- }
5800
- /**
5801
- * Markdown documentation for STYLE commitment.
5802
- */
5803
- get documentation() {
5804
- return spaceTrim$1(`
5805
- # ${this.type}
5806
-
5807
- Defines how the agent should format and present its responses (tone, writing style, formatting).
5808
-
5809
- ## Key aspects
5810
-
5811
- - Both terms work identically and can be used interchangeably.
5812
- - Later style instructions can override earlier ones.
5813
- - Style affects both tone and presentation format.
5814
-
5815
- ## Examples
5816
-
5817
- \`\`\`book
5818
- Technical Writer
5819
-
5820
- PERSONA You are a technical documentation expert
5821
- STYLE Write in a professional but friendly tone, use bullet points for lists
5822
- STYLE Always provide code examples when explaining programming concepts
5823
- FORMAT Use markdown formatting with clear headings
5824
- \`\`\`
5825
-
5826
- \`\`\`book
5827
- Creative Assistant
5828
-
5829
- PERSONA You are a creative writing helper
5830
- STYLE Be enthusiastic and encouraging in your responses
5831
- STYLE Use vivid metaphors and analogies to explain concepts
5832
- STYLE Keep responses conversational and engaging
5833
- RULE Always maintain a positive and supportive tone
5834
- \`\`\`
5835
- `);
5836
- }
5837
- applyToAgentModelRequirements(requirements, content) {
5838
- const trimmedContent = content.trim();
5839
- if (!trimmedContent) {
5840
- return requirements;
5841
- }
5842
- // Add style instructions to the system message
5843
- const styleSection = `Style: ${trimmedContent}`;
5844
- return this.appendToSystemMessage(requirements, styleSection, '\n\n');
5845
- }
5846
- }
5847
- /**
5848
- * [💞] Ignore a discrepancy between file name and entity name
5849
- */
5850
-
5851
- /**
5852
- * USE commitment definition
5853
- *
5854
- * The USE commitment indicates that the agent should utilize specific tools or capabilities
5855
- * to access and interact with external systems when necessary.
5856
- *
5857
- * Supported USE types:
5858
- * - USE BROWSER: Enables the agent to use a web browser tool
5859
- * - USE SEARCH ENGINE (future): Enables search engine access
5860
- * - USE FILE SYSTEM (future): Enables file system operations
5861
- * - USE MCP (future): Enables MCP server connections
5862
- *
5863
- * The content following the USE commitment is ignored (similar to NOTE).
5864
- *
5865
- * Example usage in agent source:
5866
- *
5867
- * ```book
5868
- * USE BROWSER
5869
- * USE SEARCH ENGINE
5870
- * ```
5871
- *
5872
- * @private [🪔] Maybe export the commitments through some package
5873
- */
5874
- class UseCommitmentDefinition extends BaseCommitmentDefinition {
5875
- constructor() {
5876
- super('USE');
5877
- }
5878
- /**
5879
- * Short one-line description of USE commitments.
5880
- */
5881
- get description() {
5882
- return 'Enable the agent to use specific tools or capabilities (BROWSER, SEARCH ENGINE, etc.).';
5883
- }
5884
- /**
5885
- * Icon for this commitment.
5886
- */
5887
- get icon() {
5888
- return '🔧';
5889
- }
5890
- /**
5891
- * Markdown documentation for USE commitment.
5892
- */
5893
- get documentation() {
5894
- return spaceTrim$1(`
5895
- # USE
5896
-
5897
- Enables the agent to use specific tools or capabilities for interacting with external systems.
5898
-
5899
- ## Supported USE types
5900
-
5901
- - **USE BROWSER** - Enables the agent to use a web browser tool to access and retrieve information from the internet
5902
- - **USE SEARCH ENGINE** (future) - Enables search engine access
5903
- - **USE FILE SYSTEM** (future) - Enables file system operations
5904
- - **USE MCP** (future) - Enables MCP server connections
5905
-
5906
- ## Key aspects
5907
-
5908
- - The content following the USE commitment is ignored (similar to NOTE)
5909
- - Multiple USE commitments can be specified to enable multiple capabilities
5910
- - The actual tool usage is handled by the agent runtime
5911
-
5912
- ## Examples
5913
-
5914
- ### Basic browser usage
5915
-
5916
- \`\`\`book
5917
- Research Assistant
5918
-
5919
- PERSONA You are a helpful research assistant
5920
- USE BROWSER
5921
- KNOWLEDGE Can search the web for up-to-date information
5922
- \`\`\`
5923
-
5924
- ### Multiple tools
5925
-
5926
- \`\`\`book
5927
- Data Analyst
5928
-
5929
- PERSONA You are a data analyst assistant
5930
- USE BROWSER
5931
- USE FILE SYSTEM
5932
- ACTION Can analyze data from various sources
5933
- \`\`\`
5934
- `);
5935
- }
5936
- applyToAgentModelRequirements(requirements, content) {
5937
- // USE commitments don't modify the system message or model requirements directly
5938
- // They are handled separately in the parsing logic for capability extraction
5939
- // This method exists for consistency with the CommitmentDefinition interface
5940
- return requirements;
5941
- }
5942
- /**
5943
- * Extracts the tool type from the USE commitment
5944
- * This is used by the parsing logic
5945
- */
5946
- extractToolType(content) {
5947
- var _a, _b;
5948
- const trimmedContent = content.trim();
5949
- // The tool type is the first word after USE (already stripped)
5950
- const match = trimmedContent.match(/^(\w+)/);
5951
- return (_b = (_a = match === null || match === void 0 ? void 0 : match[1]) === null || _a === void 0 ? void 0 : _a.toUpperCase()) !== null && _b !== void 0 ? _b : null;
5952
- }
5953
- /**
5954
- * Checks if this is a known USE type
5955
- */
5956
- isKnownUseType(useType) {
5957
- const knownTypes = ['BROWSER', 'SEARCH ENGINE', 'FILE SYSTEM', 'MCP'];
5958
- return knownTypes.includes(useType.toUpperCase());
5959
- }
5960
- }
5961
- /**
5962
- * Note: [💞] Ignore a discrepancy between file name and entity name
5963
- */
5964
-
5965
- /**
5966
- * USE BROWSER commitment definition
5967
- *
5968
- * The `USE BROWSER` commitment indicates that the agent should utilize a web browser tool
5969
- * to access and retrieve up-to-date information from the internet when necessary.
5970
- *
5971
- * The content following `USE BROWSER` is ignored (similar to NOTE).
5972
- *
5973
- * Example usage in agent source:
5974
- *
5975
- * ```book
5976
- * USE BROWSER
5977
- * USE BROWSER This will be ignored
5978
- * ```
5979
- *
5980
- * @private [🪔] Maybe export the commitments through some package
5981
- */
5982
- class UseBrowserCommitmentDefinition extends BaseCommitmentDefinition {
5983
- constructor() {
5984
- super('USE BROWSER', ['BROWSER']);
5985
- }
5986
- /**
5987
- * The `USE BROWSER` commitment is standalone.
5988
- */
5989
- get requiresContent() {
5990
- return false;
5991
- }
5992
- /**
5993
- * Short one-line description of USE BROWSER.
5994
- */
5995
- get description() {
5996
- return 'Enable the agent to use a web browser tool for accessing internet information.';
5997
- }
5998
- /**
5999
- * Icon for this commitment.
6000
- */
6001
- get icon() {
6002
- return '🌐';
6003
- }
6004
- /**
6005
- * Markdown documentation for USE BROWSER commitment.
6006
- */
6007
- get documentation() {
6008
- return spaceTrim$1(`
6009
- # USE BROWSER
6010
-
6011
- Enables the agent to use a web browser tool to access and retrieve up-to-date information from the internet.
6012
-
6013
- ## Key aspects
6014
-
6015
- - The content following \`USE BROWSER\` is ignored (similar to NOTE)
6016
- - The actual browser tool usage is handled by the agent runtime
6017
- - Allows the agent to fetch current information from websites
6018
- - Useful for research tasks, fact-checking, and accessing dynamic content
6019
-
6020
- ## Examples
6021
-
6022
- \`\`\`book
6023
- Research Assistant
6024
-
6025
- PERSONA You are a helpful research assistant specialized in finding current information
6026
- USE BROWSER
6027
- RULE Always cite your sources when providing information from the web
6028
- \`\`\`
6029
-
6030
- \`\`\`book
6031
- News Analyst
6032
-
6033
- PERSONA You are a news analyst who stays up-to-date with current events
6034
- USE BROWSER
6035
- STYLE Present news in a balanced and objective manner
6036
- ACTION Can search for and summarize news articles
6037
- \`\`\`
6038
-
6039
- \`\`\`book
6040
- Company Lawyer
6041
-
6042
- PERSONA You are a company lawyer providing legal advice
6043
- USE BROWSER
6044
- KNOWLEDGE Corporate law and legal procedures
6045
- RULE Always recommend consulting with a licensed attorney for specific legal matters
6046
- \`\`\`
6047
- `);
6048
- }
6049
- applyToAgentModelRequirements(requirements, content) {
6050
- // Get existing tools array or create new one
6051
- const existingTools = requirements.tools || [];
6052
- // Add 'web_browser' to tools if not already present
6053
- const updatedTools = existingTools.some((tool) => tool.name === 'web_browser')
6054
- ? existingTools
6055
- : ([
6056
- // TODO: [🔰] Use through proper MCP server
6057
- ...existingTools,
6058
- {
6059
- name: 'web_browser',
6060
- description: spaceTrim$1(`
6061
- A tool that can browse the web.
6062
- Use this tool when you need to access specific websites or browse the internet.
6063
- `),
6064
- parameters: {
6065
- type: 'object',
6066
- properties: {
6067
- url: {
6068
- type: 'string',
6069
- description: 'The URL to browse',
6070
- },
6071
- },
6072
- required: ['url'],
6073
- },
6074
- },
6075
- ]);
6076
- // Return requirements with updated tools and metadata
6077
- return {
6078
- ...requirements,
6079
- tools: updatedTools,
6080
- metadata: {
6081
- ...requirements.metadata,
6082
- useBrowser: true,
6083
- },
6084
- };
6085
- }
6086
- }
6087
- /**
6088
- * Note: [💞] Ignore a discrepancy between file name and entity name
6089
- */
6090
-
6091
- /**
6092
- * USE MCP commitment definition
6093
- *
6094
- * The `USE MCP` commitment allows to specify an MCP server URL which the agent will connect to
6095
- * for retrieving additional instructions and actions.
6096
- *
6097
- * The content following `USE MCP` is the URL of the MCP server.
6098
- *
6099
- * Example usage in agent source:
6100
- *
6101
- * ```book
6102
- * USE MCP http://mcp-server-url.com
6103
- * ```
6104
- *
6105
- * @private [🪔] Maybe export the commitments through some package
6106
- */
6107
- class UseMcpCommitmentDefinition extends BaseCommitmentDefinition {
6108
- constructor() {
6109
- super('USE MCP', ['MCP']);
6110
- }
6111
- /**
6112
- * Short one-line description of USE MCP.
6113
- */
6114
- get description() {
6115
- return 'Connects the agent to an external MCP server for additional capabilities.';
6116
- }
6117
- /**
6118
- * Icon for this commitment.
6119
- */
6120
- get icon() {
6121
- return '🔌';
6122
- }
6123
- /**
6124
- * Markdown documentation for USE MCP commitment.
6125
- */
6126
- get documentation() {
6127
- return spaceTrim$1(`
6128
- # USE MCP
6129
-
6130
- Connects the agent to an external Model Context Protocol (MCP) server.
6131
-
6132
- ## Key aspects
6133
-
6134
- - The content following \`USE MCP\` must be a valid URL
6135
- - Multiple MCP servers can be connected by using multiple \`USE MCP\` commitments
6136
- - The agent will have access to tools and resources provided by the MCP server
6137
-
6138
- ## Example
6139
-
6140
- \`\`\`book
6141
- Company Lawyer
6142
-
6143
- PERSONA You are a company lawyer.
6144
- USE MCP http://legal-db.example.com
6145
- \`\`\`
6146
- `);
6147
- }
6148
- applyToAgentModelRequirements(requirements, content) {
6149
- const mcpServerUrl = content.trim();
6150
- if (!mcpServerUrl) {
6151
- return requirements;
6152
- }
6153
- const existingMcpServers = requirements.mcpServers || [];
6154
- // Avoid duplicates
6155
- if (existingMcpServers.includes(mcpServerUrl)) {
6156
- return requirements;
6157
- }
6158
- return {
6159
- ...requirements,
6160
- mcpServers: [...existingMcpServers, mcpServerUrl],
6161
- };
6162
- }
6163
- }
6164
- /**
6165
- * Note: [💞] Ignore a discrepancy between file name and entity name
6166
- */
6167
-
6168
- /**
6169
- * A search engine implementation that uses the SerpApi to fetch Google search results.
6170
- *
6171
- * @private <- TODO: !!!! Export via some package
6172
- */
6173
- class SerpSearchEngine {
6174
- get title() {
6175
- return 'SerpApi Search Engine';
6176
- }
6177
- get description() {
6178
- return 'Search engine that uses SerpApi to fetch Google search results';
6179
- }
6180
- checkConfiguration() {
6181
- if (!process.env.SERP_API_KEY) {
6182
- throw new Error('SERP_API_KEY is not configured');
6183
- }
6184
- }
6185
- async search(query) {
6186
- const apiKey = process.env.SERP_API_KEY;
6187
- if (!apiKey) {
6188
- throw new Error('SERP_API_KEY is not configured');
6189
- }
6190
- const url = new URL('https://serpapi.com/search');
6191
- url.searchParams.set('q', query);
6192
- url.searchParams.set('api_key', apiKey);
6193
- url.searchParams.set('engine', 'google');
6194
- const response = await fetch(url.toString());
6195
- if (!response.ok) {
6196
- const body = await response.text();
6197
- throw new Error(`SerpApi failed with status ${response.status}: ${response.statusText}\n${body}`);
6198
- }
6199
- const data = (await response.json());
6200
- return (data.organic_results || []).map((item) => ({
6201
- title: item.title,
6202
- url: item.link,
6203
- snippet: item.snippet || '',
6204
- }));
6205
- }
6206
- }
6207
-
6208
- /**
6209
- * USE SEARCH ENGINE commitment definition
6210
- *
6211
- * The `USE SEARCH ENGINE` commitment indicates that the agent should utilize a search engine tool
6212
- * to access and retrieve up-to-date information from the internet when necessary.
6213
- *
6214
- * The content following `USE SEARCH ENGINE` is an arbitrary text that the agent should know (e.g. search scope or instructions).
6215
- *
6216
- * Example usage in agent source:
6217
- *
6218
- * ```book
6219
- * USE SEARCH ENGINE
6220
- * USE SEARCH ENGINE Hledej informace o Přemyslovcích
6221
- * ```
6222
- *
6223
- * @private [🪔] Maybe export the commitments through some package
6224
- */
6225
- class UseSearchEngineCommitmentDefinition extends BaseCommitmentDefinition {
6226
- constructor() {
6227
- super('USE SEARCH ENGINE', ['SEARCH ENGINE', 'SEARCH']);
6228
- }
6229
- /**
6230
- * Short one-line description of USE SEARCH ENGINE.
6231
- */
6232
- get description() {
6233
- return 'Enable the agent to use a search engine tool for accessing internet information.';
6234
- }
6235
- /**
6236
- * Icon for this commitment.
6237
- */
6238
- get icon() {
6239
- return '🔍';
6240
- }
6241
- /**
6242
- * Markdown documentation for USE SEARCH ENGINE commitment.
6243
- */
6244
- get documentation() {
6245
- return spaceTrim$1(`
6246
- # USE SEARCH ENGINE
6247
-
6248
- Enables the agent to use a search engine tool to access and retrieve up-to-date information from the internet.
6249
-
6250
- ## Key aspects
6251
-
6252
- - The content following \`USE SEARCH ENGINE\` is an arbitrary text that the agent should know (e.g. search scope or instructions).
6253
- - The actual search engine tool usage is handled by the agent runtime
6254
- - Allows the agent to search for current information from the web
6255
- - Useful for research tasks, finding facts, and accessing dynamic content
6256
-
6257
- ## Examples
6258
-
6259
- \`\`\`book
6260
- Research Assistant
6261
-
6262
- PERSONA You are a helpful research assistant specialized in finding current information
6263
- USE SEARCH ENGINE
6264
- RULE Always cite your sources when providing information from the web
6265
- \`\`\`
6266
-
6267
- \`\`\`book
6268
- Fact Checker
6269
-
6270
- PERSONA You are a fact checker
6271
- USE SEARCH ENGINE
6272
- ACTION Search for claims and verify them against reliable sources
6273
- \`\`\`
6274
- `);
6275
- }
6276
- applyToAgentModelRequirements(requirements, content) {
6277
- // Get existing tools array or create new one
6278
- const existingTools = requirements.tools || [];
6279
- // Add 'web_search' to tools if not already present
6280
- const updatedTools = existingTools.some((tool) => tool.name === 'web_search')
6281
- ? existingTools
6282
- : [
6283
- ...existingTools,
6284
- {
6285
- name: 'web_search',
6286
- description: spaceTrim$1(`
6287
- Search the internet for information.
6288
- Use this tool when you need to find up-to-date information or facts that you don't know.
6289
- ${!content ? '' : `Search scope / instructions: ${content}`}
6290
- `),
6291
- parameters: {
6292
- type: 'object',
6293
- properties: {
6294
- query: {
6295
- type: 'string',
6296
- description: 'The search query',
6297
- },
6298
- },
6299
- required: ['query'],
6300
- },
6301
- },
6302
- ];
6303
- // Return requirements with updated tools and metadata
6304
- return {
6305
- ...requirements,
6306
- tools: updatedTools,
6307
- metadata: {
6308
- ...requirements.metadata,
6309
- useSearchEngine: content || true,
6310
- },
6311
- };
6312
- }
6313
- /**
6314
- * Gets the `web_search` tool function implementation.
6315
- */
6316
- getToolFunctions() {
6317
- return {
6318
- async web_search(args) {
6319
- console.log('!!!! [Tool] web_search called', { args });
6320
- const { query } = args;
6321
- if (!query) {
6322
- throw new Error('Search query is required');
6323
- }
6324
- const searchEngine = new SerpSearchEngine();
6325
- const results = await searchEngine.search(query);
6326
- return spaceTrim$1((block) => `
6327
- Search results for "${query}":
6328
-
6329
- ${block(results
6330
- .map((result) => spaceTrim$1(`
6331
- - **${result.title}**
6332
- ${result.url}
6333
- ${result.snippet}
6334
- `))
6335
- .join('\n\n'))}
6336
- `);
6337
- },
6338
- };
6339
- }
6340
- }
6341
- /**
6342
- * Note: [💞] Ignore a discrepancy between file name and entity name
6343
- */
6344
-
6345
- /**
6346
- * USE TIME commitment definition
6347
- *
6348
- * The `USE TIME` commitment indicates that the agent should be able to determine the current date and time.
6349
- *
6350
- * Example usage in agent source:
6351
- *
6352
- * ```book
6353
- * USE TIME
6354
- * ```
6355
- *
6356
- * @private [🪔] Maybe export the commitments through some package
6357
- */
6358
- class UseTimeCommitmentDefinition extends BaseCommitmentDefinition {
6359
- constructor() {
6360
- super('USE TIME', ['CURRENT TIME', 'TIME', 'DATE']);
6361
- }
6362
- /**
6363
- * Short one-line description of USE TIME.
6364
- */
6365
- get description() {
6366
- return 'Enable the agent to determine the current date and time.';
6367
- }
6368
- /**
6369
- * Icon for this commitment.
6370
- */
6371
- get icon() {
6372
- return '🕒';
6373
- }
6374
- /**
6375
- * Markdown documentation for USE TIME commitment.
6376
- */
6377
- get documentation() {
6378
- return spaceTrim$1(`
6379
- # USE TIME
6380
-
6381
- Enables the agent to determine the current date and time.
6382
-
6383
- ## Key aspects
6384
-
6385
- - This tool won't receive any input.
6386
- - It outputs the current date and time as an ISO 8601 string.
6387
- - Allows the agent to answer questions about the current time or date.
6388
-
6389
- ## Examples
6390
-
6391
- \`\`\`book
6392
- Time-aware Assistant
6393
-
6394
- PERSONA You are a helpful assistant who knows the current time.
6395
- USE TIME
6396
- \`\`\`
6397
- `);
6398
- }
6399
- applyToAgentModelRequirements(requirements, content) {
6400
- // Get existing tools array or create new one
6401
- const existingTools = requirements.tools || [];
6402
- // Add 'get_current_time' to tools if not already present
6403
- const updatedTools = existingTools.some((tool) => tool.name === 'get_current_time')
6404
- ? existingTools
6405
- : [
6406
- ...existingTools,
6407
- {
6408
- name: 'get_current_time',
6409
- description: 'Get the current date and time in ISO 8601 format.',
6410
- parameters: {
6411
- type: 'object',
6412
- properties: {
6413
- timezone: {
6414
- type: 'string',
6415
- description: 'Optional timezone name (e.g. "Europe/Prague", "UTC", "America/New_York").',
6416
- },
6417
- },
6418
- required: [],
6419
- },
6420
- },
6421
- // <- TODO: !!!! define the function in LLM tools
6422
- ];
6423
- // Return requirements with updated tools and metadata
6424
- return {
6425
- ...requirements,
6426
- tools: updatedTools,
6427
- metadata: {
6428
- ...requirements.metadata,
6429
- },
6430
- };
6431
- }
6432
- /**
6433
- * Gets the `get_current_time` tool function implementation.
6434
- */
6435
- getToolFunctions() {
6436
- return {
6437
- async get_current_time(args) {
6438
- var _a;
6439
- console.log('!!!! [Tool] get_current_time called', { args });
6440
- const { timezone } = args;
6441
- if (!timezone) {
6442
- return new Date().toISOString();
6443
- }
6444
- try {
6445
- // Note: Returning ISO 8601 string but in the requested timezone
6446
- const formatter = new Intl.DateTimeFormat('en-CA', {
6447
- timeZone: timezone,
6448
- year: 'numeric',
6449
- month: '2-digit',
6450
- day: '2-digit',
6451
- hour: '2-digit',
6452
- minute: '2-digit',
6453
- second: '2-digit',
6454
- hour12: false,
6455
- timeZoneName: 'shortOffset',
6456
- });
6457
- const parts = formatter.formatToParts(new Date());
6458
- const part = (type) => { var _a; return (_a = parts.find((p) => p.type === type)) === null || _a === void 0 ? void 0 : _a.value; };
6459
- // en-CA format is YYYY-MM-DD
6460
- const isoString = `${part('year')}-${part('month')}-${part('day')}T${part('hour')}:${part('minute')}:${part('second')}${(_a = part('timeZoneName')) === null || _a === void 0 ? void 0 : _a.replace('GMT', '')}`;
6461
- return isoString;
6462
- }
6463
- catch (error) {
6464
- // Fallback to UTC if timezone is invalid
6465
- return new Date().toISOString();
6466
- }
6467
- },
6468
- };
6469
- }
6470
- }
6471
- /**
6472
- * Note: [💞] Ignore a discrepancy between file name and entity name
6473
- */
6474
-
6475
- /**
6476
- * Placeholder commitment definition for commitments that are not yet implemented
6477
- *
6478
- * This commitment simply adds its content 1:1 into the system message,
6479
- * preserving the original behavior until proper implementation is added.
6480
- *
6481
- * @public exported from `@promptbook/core`
6482
- */
6483
- class NotYetImplementedCommitmentDefinition extends BaseCommitmentDefinition {
6484
- constructor(type) {
6485
- super(type);
6486
- }
6487
- /**
6488
- * Short one-line description of a placeholder commitment.
6489
- */
6490
- get description() {
6491
- return 'Placeholder commitment that appends content verbatim to the system message.';
6492
- }
6493
- /**
6494
- * Icon for this commitment.
6495
- */
6496
- get icon() {
6497
- return '🚧';
6498
- }
6499
- /**
6500
- * Markdown documentation available at runtime.
6501
- */
6502
- get documentation() {
6503
- return spaceTrim$1(`
6504
- # ${this.type}
6505
-
6506
- This commitment is not yet fully implemented.
6507
-
6508
- ## Key aspects
6509
-
6510
- - Content is appended directly to the system message.
6511
- - No special processing or validation is performed.
6512
- - Behavior preserved until proper implementation is added.
6513
-
6514
- ## Status
6515
-
6516
- - **Status:** Placeholder implementation
6517
- - **Effect:** Appends content prefixed by commitment type
6518
- - **Future:** Will be replaced with specialized logic
6519
-
6520
- ## Examples
6521
-
6522
- \`\`\`book
6523
- Example Agent
6524
-
6525
- PERSONA You are a helpful assistant
6526
- ${this.type} Your content here
6527
- RULE Always be helpful
6528
- \`\`\`
6529
- `);
6530
- }
6531
- applyToAgentModelRequirements(requirements, content) {
6532
- const trimmedContent = content.trim();
6533
- if (!trimmedContent) {
6534
- return requirements;
6535
- }
6536
- // Add the commitment content 1:1 to the system message
6537
- const commitmentLine = `${this.type} ${trimmedContent}`;
6538
- return this.appendToSystemMessage(requirements, commitmentLine, '\n\n');
6539
- }
6540
- }
6541
-
6542
- /**
6543
- * Registry of all available commitment definitions
6544
- * This array contains instances of all commitment definitions
6545
- * This is the single source of truth for all commitments in the system
6546
- *
6547
- * @private Use functions to access commitments instead of this array directly
6548
- */
6549
- const COMMITMENT_REGISTRY = [
6550
- // Fully implemented commitments
6551
- new PersonaCommitmentDefinition('PERSONA'),
6552
- new PersonaCommitmentDefinition('PERSONAE'),
6553
- new KnowledgeCommitmentDefinition(),
6554
- new MemoryCommitmentDefinition('MEMORY'),
6555
- new MemoryCommitmentDefinition('MEMORIES'),
6556
- new StyleCommitmentDefinition('STYLE'),
6557
- new StyleCommitmentDefinition('STYLES'),
6558
- new RuleCommitmentDefinition('RULES'),
6559
- new RuleCommitmentDefinition('RULE'),
6560
- new LanguageCommitmentDefinition('LANGUAGES'),
6561
- new LanguageCommitmentDefinition('LANGUAGE'),
6562
- new SampleCommitmentDefinition('SAMPLE'),
6563
- new SampleCommitmentDefinition('EXAMPLE'),
6564
- new FormatCommitmentDefinition('FORMAT'),
6565
- new FormatCommitmentDefinition('FORMATS'),
6566
- new FromCommitmentDefinition('FROM'),
6567
- new ImportCommitmentDefinition('IMPORT'),
6568
- new ImportCommitmentDefinition('IMPORTS'),
6569
- new ModelCommitmentDefinition('MODEL'),
6570
- new ModelCommitmentDefinition('MODELS'),
6571
- new ActionCommitmentDefinition('ACTION'),
6572
- new ActionCommitmentDefinition('ACTIONS'),
6573
- new ComponentCommitmentDefinition(),
6574
- new MetaImageCommitmentDefinition(),
6575
- new MetaColorCommitmentDefinition(),
6576
- new MetaFontCommitmentDefinition(),
6577
- new MetaLinkCommitmentDefinition(),
6578
- new MetaCommitmentDefinition(),
6579
- new NoteCommitmentDefinition('NOTE'),
6580
- new NoteCommitmentDefinition('NOTES'),
6581
- new NoteCommitmentDefinition('COMMENT'),
6582
- new NoteCommitmentDefinition('NONCE'),
6583
- new NoteCommitmentDefinition('TODO'),
6584
- new GoalCommitmentDefinition('GOAL'),
6585
- new GoalCommitmentDefinition('GOALS'),
6586
- new InitialMessageCommitmentDefinition(),
6587
- new UserMessageCommitmentDefinition(),
6588
- new AgentMessageCommitmentDefinition(),
6589
- new MessageCommitmentDefinition('MESSAGE'),
6590
- new MessageCommitmentDefinition('MESSAGES'),
6591
- new ScenarioCommitmentDefinition('SCENARIO'),
6592
- new ScenarioCommitmentDefinition('SCENARIOS'),
6593
- new DeleteCommitmentDefinition('DELETE'),
6594
- new DeleteCommitmentDefinition('CANCEL'),
6595
- new DeleteCommitmentDefinition('DISCARD'),
6596
- new DeleteCommitmentDefinition('REMOVE'),
6597
- new DictionaryCommitmentDefinition(),
6598
- new OpenCommitmentDefinition(),
6599
- new ClosedCommitmentDefinition(),
6600
- new UseBrowserCommitmentDefinition(),
6601
- new UseSearchEngineCommitmentDefinition(),
6602
- new UseTimeCommitmentDefinition(),
6603
- new UseMcpCommitmentDefinition(),
6604
- new UseCommitmentDefinition(),
6605
- // Not yet implemented commitments (using placeholder)
6606
- new NotYetImplementedCommitmentDefinition('EXPECT'),
6607
- new NotYetImplementedCommitmentDefinition('BEHAVIOUR'),
6608
- new NotYetImplementedCommitmentDefinition('BEHAVIOURS'),
6609
- new NotYetImplementedCommitmentDefinition('AVOID'),
6610
- new NotYetImplementedCommitmentDefinition('AVOIDANCE'),
6611
- new NotYetImplementedCommitmentDefinition('CONTEXT'),
6612
- ];
6613
- /**
6614
- * Gets all available commitment definitions
6615
- * @returns Array of all commitment definitions
6616
- *
6617
- * @public exported from `@promptbook/core`
6618
- */
6619
- function getAllCommitmentDefinitions() {
6620
- return $deepFreeze([...COMMITMENT_REGISTRY]);
6621
- }
6622
- /**
6623
- * Gets all function implementations provided by all commitments
6624
- *
6625
- * @public exported from `@promptbook/core`
6626
- */
6627
- function getAllCommitmentsToolFunctions() {
6628
- const allToolFunctions = {};
6629
- for (const commitmentDefinition of getAllCommitmentDefinitions()) {
6630
- const toolFunctions = commitmentDefinition.getToolFunctions();
6631
- for (const [funcName, funcImpl] of Object.entries(toolFunctions)) {
6632
- allToolFunctions[funcName] = funcImpl;
6633
- }
6634
- }
6635
- return allToolFunctions;
6636
- }
6637
- /**
6638
- * TODO: [🧠] Maybe create through standardized $register
6639
- * Note: [💞] Ignore a discrepancy between file name and entity name
6640
- */
6641
-
6642
- /**
6643
- * Extracts all code blocks from markdown.
6644
- *
6645
- * Note: There are multiple similar functions:
6646
- * - `extractBlock` just extracts the content of the code block which is also used as built-in function for postprocessing
6647
- * - `extractJsonBlock` extracts exactly one valid JSON code block
6648
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
6649
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
6650
- *
6651
- * @param markdown any valid markdown
6652
- * @returns code blocks with language and content
6653
- * @throws {ParseError} if block is not closed properly
6654
- * @public exported from `@promptbook/markdown-utils`
6655
- */
6656
- function extractAllBlocksFromMarkdown(markdown) {
6657
- const codeBlocks = [];
6658
- const lines = markdown.split('\n');
6659
- // Note: [0] Ensure that the last block notated by gt > will be closed
6660
- lines.push('');
6661
- let currentCodeBlock = null;
6662
- for (const line of lines) {
6663
- if (line.startsWith('> ') || line === '>') {
6664
- if (currentCodeBlock === null) {
6665
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
6666
- } /* not else */
6667
- if (currentCodeBlock.blockNotation === '>') {
6668
- if (currentCodeBlock.content !== '') {
6669
- currentCodeBlock.content += '\n';
6670
- }
6671
- currentCodeBlock.content += line.slice(2);
6672
- }
6673
- }
6674
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
6675
- codeBlocks.push(currentCodeBlock);
6676
- currentCodeBlock = null;
6677
- }
6678
- /* not else */
6679
- if (line.startsWith('```')) {
6680
- const language = line.slice(3).trim() || null;
6681
- if (currentCodeBlock === null) {
6682
- currentCodeBlock = { blockNotation: '```', language, content: '' };
6683
- }
6684
- else {
6685
- if (language !== null) {
6686
- throw new ParseError(`${capitalize(currentCodeBlock.language || 'the')} code block was not closed and already opening new ${language} code block`);
6687
- }
6688
- codeBlocks.push(currentCodeBlock);
6689
- currentCodeBlock = null;
6690
- }
6691
- }
6692
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
6693
- if (currentCodeBlock.content !== '') {
6694
- currentCodeBlock.content += '\n';
6695
- }
6696
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make proper unescape */;
6697
- }
6698
- }
6699
- if (currentCodeBlock !== null) {
6700
- throw new ParseError(`${capitalize(currentCodeBlock.language || 'the')} code block was not closed at the end of the markdown`);
6701
- }
6702
- return codeBlocks;
6703
- }
6704
- /**
6705
- * TODO: Maybe name for `blockNotation` instead of '```' and '>'
6706
- */
6707
-
6708
- /**
6709
- * Extracts exactly ONE code block from markdown.
6710
- *
6711
- * - When there are multiple or no code blocks the function throws a `ParseError`
6712
- *
6713
- * Note: There are multiple similar functions:
6714
- * - `extractBlock` just extracts the content of the code block which is also used as built-in function for postprocessing
6715
- * - `extractJsonBlock` extracts exactly one valid JSON code block
6716
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
6717
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
6718
- *
6719
- * @param markdown any valid markdown
6720
- * @returns code block with language and content
6721
- * @public exported from `@promptbook/markdown-utils`
6722
- * @throws {ParseError} if there is not exactly one code block in the markdown
6723
- */
6724
- function extractOneBlockFromMarkdown(markdown) {
6725
- const codeBlocks = extractAllBlocksFromMarkdown(markdown);
6726
- if (codeBlocks.length !== 1) {
6727
- throw new ParseError(spaceTrim$2((block) => `
6728
- There should be exactly 1 code block in task section, found ${codeBlocks.length} code blocks
6729
-
6730
- ${block(codeBlocks.map((block, i) => `Block ${i + 1}:\n${block.content}`).join('\n\n\n'))}
6731
- `));
6732
- }
6733
- return codeBlocks[0];
6734
- }
6735
- /***
6736
- * TODO: [🍓][🌻] Decide of this is internal utility, external util OR validator/postprocessor
6737
- */
6738
-
6739
- /**
6740
- * Extracts code block from markdown.
6741
- *
6742
- * - When there are multiple or no code blocks the function throws a `ParseError`
6743
- *
6744
- * Note: There are multiple similar function:
6745
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
6746
- * - `extractJsonBlock` extracts exactly one valid JSON code block
6747
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
6748
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
6749
- *
6750
- * @public exported from `@promptbook/markdown-utils`
6751
- * @throws {ParseError} if there is not exactly one code block in the markdown
6752
- */
6753
- function extractBlock(markdown) {
6754
- const { content } = extractOneBlockFromMarkdown(markdown);
6755
- return content;
6756
- }
6757
-
6758
- /**
6759
- * Prettify the html code
6760
- *
6761
- * @param content raw html code
6762
- * @returns formatted html code
6763
- * @private withing the package because of HUGE size of prettier dependency
6764
- * @deprecated Prettier removed from Promptbook due to package size
6765
- */
6766
- function prettifyMarkdown(content) {
6767
- return (content + `\n\n<!-- Note: Prettier removed from Promptbook -->`);
6768
- }
6769
-
6770
- /**
6771
- * Function trimCodeBlock will trim starting and ending code block from the string if it is present.
6772
- *
6773
- * Note: [🔂] This function is idempotent.
6774
- * Note: This is useful for post-processing of the result of the chat LLM model
6775
- * when the model wraps the result in the (markdown) code block.
6776
- *
6777
- * @public exported from `@promptbook/markdown-utils`
6778
- */
6779
- function trimCodeBlock(value) {
6780
- value = spaceTrim$1(value);
6781
- if (!/^```[a-z]*(.*)```$/is.test(value)) {
6782
- return value;
6783
- }
6784
- value = value.replace(/^```[a-z]*/i, '');
6785
- value = value.replace(/```$/i, '');
6786
- value = spaceTrim$1(value);
6787
- return value;
6788
- }
6789
-
6790
- /**
6791
- * Function trimEndOfCodeBlock will remove ending code block from the string if it is present.
6792
- *
6793
- * Note: This is useful for post-processing of the result of the completion LLM model
6794
- * if you want to start code block in the prompt but you don't want to end it in the result.
6795
- *
6796
- * @public exported from `@promptbook/markdown-utils`
6797
- */
6798
- function trimEndOfCodeBlock(value) {
6799
- value = spaceTrim$1(value);
6800
- value = value.replace(/```$/g, '');
6801
- value = spaceTrim$1(value);
6802
- return value;
6803
- }
6804
-
6805
- /**
6806
- * @private internal for `preserve`
6807
- */
6808
- const _preserved = [];
6809
- /**
6810
- * Does nothing, but preserves the function in the bundle
6811
- * Compiler is tricked into thinking the function is used
6812
- *
6813
- * @param value any function to preserve
6814
- * @returns nothing
6815
- * @private within the repository
6816
- */
6817
- function $preserve(...value) {
6818
- _preserved.push(...value);
6819
- }
6820
- /**
6821
- * Note: [💞] Ignore a discrepancy between file name and entity name
6822
- */
6823
-
6824
- // Note: [💎]
6825
- /**
6826
- * ScriptExecutionTools for JavaScript implemented via eval
6827
- *
6828
- * Warning: It is used for testing and mocking
6829
- * **NOT intended to use in the production** due to its unsafe nature, use `JavascriptExecutionTools` instead.
2945
+ * Warning: It is used for testing and mocking
2946
+ * **NOT intended to use in the production** due to its unsafe nature, use `JavascriptExecutionTools` instead.
6830
2947
  *
6831
2948
  * @public exported from `@promptbook/javascript`
6832
2949
  */
@@ -6928,13 +3045,6 @@ class JavascriptEvalExecutionTools {
6928
3045
  `const ${functionName} = buildinFunctions.${functionName};`)
6929
3046
  .join('\n');
6930
3047
  // TODO: DRY [🍯]
6931
- const commitmentsFunctions = getAllCommitmentsToolFunctions();
6932
- const commitmentsFunctionsStatement = Object.keys(commitmentsFunctions)
6933
- .map((functionName) =>
6934
- // Note: Custom functions are exposed to the current scope as variables
6935
- `const ${functionName} = commitmentsFunctions.${functionName};`)
6936
- .join('\n');
6937
- // TODO: DRY [🍯]
6938
3048
  const customFunctions = this.options.functions || {};
6939
3049
  const customFunctionsStatement = Object.keys(customFunctions)
6940
3050
  .map((functionName) =>
@@ -6948,10 +3058,6 @@ class JavascriptEvalExecutionTools {
6948
3058
  // Build-in functions:
6949
3059
  ${block(buildinFunctionsStatement)}
6950
3060
 
6951
- // Commitments functions:
6952
- ${block(commitmentsFunctionsStatement)}
6953
-
6954
-
6955
3061
  // Custom functions:
6956
3062
  ${block(customFunctionsStatement || '// -- No custom functions --')}
6957
3063