@promptbook/javascript 0.105.0-9 → 0.105.0

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