@promptbook/fake-llm 0.105.0-1 → 0.105.0-10

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