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