@promptbook/fake-llm 0.105.0-21 → 0.105.0-26

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