@promptbook/javascript 0.105.0-9 → 0.106.0-0

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