@promptbook/node 0.105.0-0 → 0.105.0-10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +36 -77
  2. package/esm/index.es.js +4055 -135
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/browser.index.d.ts +2 -0
  5. package/esm/typings/src/_packages/core.index.d.ts +4 -0
  6. package/esm/typings/src/_packages/types.index.d.ts +16 -0
  7. package/esm/typings/src/_packages/utils.index.d.ts +2 -0
  8. package/esm/typings/src/book-2.0/agent-source/AgentBasicInformation.d.ts +15 -3
  9. package/esm/typings/src/book-2.0/agent-source/AgentModelRequirements.d.ts +11 -1
  10. package/esm/typings/src/book-2.0/agent-source/communication-samples.test.d.ts +1 -0
  11. package/esm/typings/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments.blocks.test.d.ts +1 -0
  12. package/esm/typings/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments.import.test.d.ts +1 -0
  13. package/esm/typings/src/book-2.0/agent-source/parseAgentSource.import.test.d.ts +1 -0
  14. package/esm/typings/src/book-2.0/agent-source/parseAgentSourceWithCommitments.blocks.test.d.ts +1 -0
  15. package/esm/typings/src/book-components/Chat/AgentChat/AgentChatProps.d.ts +5 -0
  16. package/esm/typings/src/book-components/Chat/Chat/ChatMessageItem.d.ts +15 -1
  17. package/esm/typings/src/book-components/Chat/Chat/ChatProps.d.ts +20 -9
  18. package/esm/typings/src/book-components/Chat/LlmChat/LlmChatProps.d.ts +5 -0
  19. package/esm/typings/src/book-components/Chat/types/ChatMessage.d.ts +43 -0
  20. package/esm/typings/src/commitments/NOTE/NOTE.d.ts +2 -2
  21. package/esm/typings/src/commitments/USE_BROWSER/USE_BROWSER.d.ts +4 -0
  22. package/esm/typings/src/commitments/USE_SEARCH_ENGINE/USE_SEARCH_ENGINE.d.ts +10 -0
  23. package/esm/typings/src/commitments/USE_SEARCH_ENGINE/USE_SEARCH_ENGINE.test.d.ts +1 -0
  24. package/esm/typings/src/commitments/USE_TIME/USE_TIME.d.ts +44 -0
  25. package/esm/typings/src/commitments/USE_TIME/USE_TIME.test.d.ts +1 -0
  26. package/esm/typings/src/commitments/_base/BaseCommitmentDefinition.d.ts +14 -0
  27. package/esm/typings/src/commitments/_base/CommitmentDefinition.d.ts +14 -0
  28. package/esm/typings/src/commitments/index.d.ts +17 -2
  29. package/esm/typings/src/config.d.ts +1 -0
  30. package/esm/typings/src/execution/LlmExecutionTools.d.ts +3 -1
  31. package/esm/typings/src/import-plugins/$fileImportPlugins.d.ts +7 -0
  32. package/esm/typings/src/import-plugins/AgentFileImportPlugin.d.ts +7 -0
  33. package/esm/typings/src/import-plugins/FileImportPlugin.d.ts +24 -0
  34. package/esm/typings/src/import-plugins/JsonFileImportPlugin.d.ts +7 -0
  35. package/esm/typings/src/import-plugins/TextFileImportPlugin.d.ts +7 -0
  36. package/esm/typings/src/llm-providers/_common/utils/cache/cacheLlmTools.d.ts +2 -1
  37. package/esm/typings/src/llm-providers/_common/utils/count-total-usage/countUsage.d.ts +2 -2
  38. package/esm/typings/src/llm-providers/agent/Agent.d.ts +14 -2
  39. package/esm/typings/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +3 -1
  40. package/esm/typings/src/llm-providers/agent/AgentOptions.d.ts +7 -0
  41. package/esm/typings/src/llm-providers/agent/RemoteAgent.d.ts +1 -0
  42. package/esm/typings/src/llm-providers/agent/RemoteAgentOptions.d.ts +1 -1
  43. package/esm/typings/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +10 -0
  44. package/esm/typings/src/llm-providers/openai/OpenAiCompatibleExecutionTools.d.ts +7 -0
  45. package/esm/typings/src/llm-providers/remote/RemoteLlmExecutionTools.d.ts +1 -1
  46. package/esm/typings/src/scripting/javascript/JavascriptExecutionToolsOptions.d.ts +6 -1
  47. package/esm/typings/src/search-engines/SearchEngine.d.ts +1 -1
  48. package/esm/typings/src/search-engines/_index.d.ts +6 -0
  49. package/esm/typings/src/search-engines/bing/BingSearchEngine.d.ts +1 -1
  50. package/esm/typings/src/search-engines/dummy/DummySearchEngine.d.ts +1 -1
  51. package/esm/typings/src/search-engines/google/GoogleSearchEngine.d.ts +18 -0
  52. package/esm/typings/src/search-engines/serp/SerpSearchEngine.d.ts +15 -0
  53. package/esm/typings/src/speech-recognition/BrowserSpeechRecognition.d.ts +21 -0
  54. package/esm/typings/src/speech-recognition/OpenAiSpeechRecognition.d.ts +32 -0
  55. package/esm/typings/src/types/ModelRequirements.d.ts +6 -12
  56. package/esm/typings/src/types/SpeechRecognition.d.ts +58 -0
  57. package/esm/typings/src/types/typeAliases.d.ts +4 -0
  58. package/esm/typings/src/utils/execCommand/$execCommandNormalizeOptions.d.ts +2 -3
  59. package/esm/typings/src/utils/execCommand/ExecCommandOptions.d.ts +7 -1
  60. package/esm/typings/src/utils/misc/linguisticHash.d.ts +6 -0
  61. package/esm/typings/src/utils/misc/linguisticHash.test.d.ts +1 -0
  62. package/esm/typings/src/utils/organization/keepImported.d.ts +9 -0
  63. package/esm/typings/src/utils/organization/keepTypeImported.d.ts +0 -1
  64. package/esm/typings/src/utils/random/$generateBookBoilerplate.d.ts +4 -0
  65. package/esm/typings/src/utils/random/$randomAgentPersona.d.ts +2 -1
  66. package/esm/typings/src/utils/random/$randomAgentRule.d.ts +14 -0
  67. package/esm/typings/src/version.d.ts +1 -1
  68. package/package.json +2 -2
  69. package/umd/index.umd.js +4055 -135
  70. package/umd/index.umd.js.map +1 -1
package/umd/index.umd.js CHANGED
@@ -45,7 +45,7 @@
45
45
  * @generated
46
46
  * @see https://github.com/webgptorg/promptbook
47
47
  */
48
- const PROMPTBOOK_ENGINE_VERSION = '0.105.0-0';
48
+ const PROMPTBOOK_ENGINE_VERSION = '0.105.0-10';
49
49
  /**
50
50
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
51
51
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -990,6 +990,7 @@
990
990
  SEPARATOR: Color.fromHex('#cccccc'),
991
991
  COMMITMENT: Color.fromHex('#DA0F78'),
992
992
  PARAMETER: Color.fromHex('#8e44ad'),
993
+ CODE_BLOCK: Color.fromHex('#7700ffff'),
993
994
  });
994
995
  // <- TODO: [🧠][🈵] Using `Color` here increases the package size approx 3kb, maybe remove it
995
996
  /**
@@ -6175,74 +6176,90 @@
6175
6176
  * in real-time through an observable.
6176
6177
  *
6177
6178
  * @param llmTools - The LLM tools to be intercepted and tracked
6178
- * @returns An augmented version of the tools that includes usage tracking capabilities
6179
+ * @returns Full proxy of the tools with added usage tracking capabilities
6179
6180
  * @public exported from `@promptbook/core`
6180
6181
  */
6181
6182
  function countUsage(llmTools) {
6182
6183
  let totalUsage = ZERO_USAGE;
6183
6184
  const spending = new rxjs.Subject();
6184
- const proxyTools = {
6185
- get title() {
6186
- return `${llmTools.title} (+usage)`;
6187
- // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
6188
- // <- TODO: [🧈][🧠] Does it make sense to suffix "(+usage)"?
6189
- },
6190
- get description() {
6191
- return `${llmTools.description} (+usage)`;
6192
- // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
6193
- // <- TODO: [🧈][🧠] Does it make sense to suffix "(+usage)"?
6194
- },
6195
- checkConfiguration() {
6196
- return /* not await */ llmTools.checkConfiguration();
6197
- },
6198
- listModels() {
6199
- return /* not await */ llmTools.listModels();
6200
- },
6201
- spending() {
6202
- return spending.asObservable();
6203
- },
6204
- getTotalUsage() {
6205
- // <- Note: [🥫] Not using getter `get totalUsage` but `getTotalUsage` to allow this object to be proxied
6206
- return totalUsage;
6185
+ // Create a Proxy to intercept all property access and ensure full proxying of all properties
6186
+ const proxyTools = new Proxy(llmTools, {
6187
+ get(target, prop, receiver) {
6188
+ // Handle title property
6189
+ if (prop === 'title') {
6190
+ return `${target.title} (+usage)`;
6191
+ // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
6192
+ // <- TODO: [🧈][🧠] Does it make sense to suffix "(+usage)"?
6193
+ }
6194
+ // Handle description property
6195
+ if (prop === 'description') {
6196
+ return `${target.description} (+usage)`;
6197
+ // <- TODO: [🧈] Maybe standartize the suffix when wrapping `LlmExecutionTools` up
6198
+ // <- TODO: [🧈][🧠] Does it make sense to suffix "(+usage)"?
6199
+ }
6200
+ // Handle spending method (new method added by this wrapper)
6201
+ if (prop === 'spending') {
6202
+ return () => {
6203
+ return spending.asObservable();
6204
+ };
6205
+ }
6206
+ // Handle getTotalUsage method (new method added by this wrapper)
6207
+ if (prop === 'getTotalUsage') {
6208
+ // <- Note: [🥫] Not using getter `get totalUsage` but `getTotalUsage` to allow this object to be proxied
6209
+ return () => {
6210
+ return totalUsage;
6211
+ };
6212
+ }
6213
+ // Handle callChatModel method with usage counting
6214
+ if (prop === 'callChatModel' && target.callChatModel !== undefined) {
6215
+ return async (prompt) => {
6216
+ // console.info('[🚕] callChatModel through countTotalUsage');
6217
+ const promptResult = await target.callChatModel(prompt);
6218
+ totalUsage = addUsage(totalUsage, promptResult.usage);
6219
+ spending.next(promptResult.usage);
6220
+ return promptResult;
6221
+ };
6222
+ }
6223
+ // Handle callCompletionModel method with usage counting
6224
+ if (prop === 'callCompletionModel' && target.callCompletionModel !== undefined) {
6225
+ return async (prompt) => {
6226
+ // console.info('[🚕] callCompletionModel through countTotalUsage');
6227
+ const promptResult = await target.callCompletionModel(prompt);
6228
+ totalUsage = addUsage(totalUsage, promptResult.usage);
6229
+ spending.next(promptResult.usage);
6230
+ return promptResult;
6231
+ };
6232
+ }
6233
+ // Handle callEmbeddingModel method with usage counting
6234
+ if (prop === 'callEmbeddingModel' && target.callEmbeddingModel !== undefined) {
6235
+ return async (prompt) => {
6236
+ // console.info('[🚕] callEmbeddingModel through countTotalUsage');
6237
+ const promptResult = await target.callEmbeddingModel(prompt);
6238
+ totalUsage = addUsage(totalUsage, promptResult.usage);
6239
+ spending.next(promptResult.usage);
6240
+ return promptResult;
6241
+ };
6242
+ }
6243
+ // Handle callImageGenerationModel method with usage counting
6244
+ if (prop === 'callImageGenerationModel' && target.callImageGenerationModel !== undefined) {
6245
+ return async (prompt) => {
6246
+ // console.info('[🚕] callImageGenerationModel through countTotalUsage');
6247
+ const promptResult = await target.callImageGenerationModel(prompt);
6248
+ totalUsage = addUsage(totalUsage, promptResult.usage);
6249
+ spending.next(promptResult.usage);
6250
+ return promptResult;
6251
+ };
6252
+ }
6253
+ // <- Note: [🤖]
6254
+ // For all other properties and methods, delegate to the original target
6255
+ const value = Reflect.get(target, prop, receiver);
6256
+ // If it's a function, bind it to the target to preserve context
6257
+ if (typeof value === 'function') {
6258
+ return value.bind(target);
6259
+ }
6260
+ return value;
6207
6261
  },
6208
- };
6209
- if (llmTools.callChatModel !== undefined) {
6210
- proxyTools.callChatModel = async (prompt) => {
6211
- // console.info('[🚕] callChatModel through countTotalUsage');
6212
- const promptResult = await llmTools.callChatModel(prompt);
6213
- totalUsage = addUsage(totalUsage, promptResult.usage);
6214
- spending.next(promptResult.usage);
6215
- return promptResult;
6216
- };
6217
- }
6218
- if (llmTools.callCompletionModel !== undefined) {
6219
- proxyTools.callCompletionModel = async (prompt) => {
6220
- // console.info('[🚕] callCompletionModel through countTotalUsage');
6221
- const promptResult = await llmTools.callCompletionModel(prompt);
6222
- totalUsage = addUsage(totalUsage, promptResult.usage);
6223
- spending.next(promptResult.usage);
6224
- return promptResult;
6225
- };
6226
- }
6227
- if (llmTools.callEmbeddingModel !== undefined) {
6228
- proxyTools.callEmbeddingModel = async (prompt) => {
6229
- // console.info('[🚕] callEmbeddingModel through countTotalUsage');
6230
- const promptResult = await llmTools.callEmbeddingModel(prompt);
6231
- totalUsage = addUsage(totalUsage, promptResult.usage);
6232
- spending.next(promptResult.usage);
6233
- return promptResult;
6234
- };
6235
- }
6236
- if (llmTools.callImageGenerationModel !== undefined) {
6237
- proxyTools.callImageGenerationModel = async (prompt) => {
6238
- // console.info('[🚕] callImageGenerationModel through countTotalUsage');
6239
- const promptResult = await llmTools.callImageGenerationModel(prompt);
6240
- totalUsage = addUsage(totalUsage, promptResult.usage);
6241
- spending.next(promptResult.usage);
6242
- return promptResult;
6243
- };
6244
- }
6245
- // <- Note: [🤖]
6262
+ });
6246
6263
  return proxyTools;
6247
6264
  }
6248
6265
  /**
@@ -10889,6 +10906,7 @@
10889
10906
  let args = [];
10890
10907
  let timeout;
10891
10908
  let isVerbose;
10909
+ let env;
10892
10910
  if (typeof options === 'string') {
10893
10911
  // TODO: [1] DRY default values
10894
10912
  command = options;
@@ -10896,6 +10914,7 @@
10896
10914
  crashOnError = true;
10897
10915
  timeout = Infinity; // <- TODO: [⏳]
10898
10916
  isVerbose = DEFAULT_IS_VERBOSE;
10917
+ env = undefined;
10899
10918
  }
10900
10919
  else {
10901
10920
  /*
@@ -10912,6 +10931,7 @@
10912
10931
  crashOnError = (_b = options.crashOnError) !== null && _b !== void 0 ? _b : true;
10913
10932
  timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : Infinity;
10914
10933
  isVerbose = (_d = options.isVerbose) !== null && _d !== void 0 ? _d : DEFAULT_IS_VERBOSE;
10934
+ env = options.env;
10915
10935
  }
10916
10936
  // TODO: /(-[a-zA-Z0-9-]+\s+[^\s]*)|[^\s]*/g
10917
10937
  const _ = Array.from(command.matchAll(/(".*")|([^\s]*)/g))
@@ -10930,7 +10950,7 @@
10930
10950
  if (/^win/.test(process.platform) && ['npm', 'npx'].includes(command)) {
10931
10951
  command = `${command}.cmd`;
10932
10952
  }
10933
- return { command, humanReadableCommand, args, cwd, crashOnError, timeout, isVerbose };
10953
+ return { command, humanReadableCommand, args, cwd, crashOnError, timeout, isVerbose, env };
10934
10954
  }
10935
10955
  // TODO: This should show type error> execCommandNormalizeOptions({ command: '', commands: [''] });
10936
10956
 
@@ -10951,7 +10971,7 @@
10951
10971
  }
10952
10972
  return new Promise((resolve, reject) => {
10953
10973
  // eslint-disable-next-line prefer-const
10954
- const { command, humanReadableCommand, args, cwd, crashOnError, timeout, isVerbose = DEFAULT_IS_VERBOSE, } = $execCommandNormalizeOptions(options);
10974
+ const { command, humanReadableCommand, args, cwd, crashOnError, timeout, isVerbose = DEFAULT_IS_VERBOSE, env, } = $execCommandNormalizeOptions(options);
10955
10975
  if (timeout !== Infinity) {
10956
10976
  // TODO: In waitasecond forTime(Infinity) should be equivalent to forEver()
10957
10977
  waitasecond.forTime(timeout).then(() => {
@@ -10969,7 +10989,11 @@
10969
10989
  console.info(colors__default["default"].yellow(cwd) + ' ' + colors__default["default"].green(command) + ' ' + colors__default["default"].blue(args.join(' ')));
10970
10990
  }
10971
10991
  try {
10972
- const commandProcess = child_process.spawn(command, args, { cwd, shell: true });
10992
+ const commandProcess = child_process.spawn(command, args, {
10993
+ cwd,
10994
+ shell: true,
10995
+ env: env ? { ...process.env, ...env } : process.env,
10996
+ });
10973
10997
  if (isVerbose) {
10974
10998
  commandProcess.on('message', (message) => {
10975
10999
  console.info({ message });
@@ -11823,6 +11847,16 @@
11823
11847
  trimmedText = spaceTrim$1.spaceTrim(trimmedText);
11824
11848
  }
11825
11849
  let processedText = trimmedText;
11850
+ // Check for markdown code block
11851
+ const codeBlockRegex = /^```[a-z]*\n([\s\S]*?)\n```\s*$/;
11852
+ const codeBlockMatch = processedText.match(codeBlockRegex);
11853
+ if (codeBlockMatch && codeBlockMatch[1] !== undefined) {
11854
+ // Check if there's only one code block
11855
+ const codeBlockCount = (processedText.match(/```/g) || []).length / 2;
11856
+ if (codeBlockCount === 1) {
11857
+ return unwrapResult(codeBlockMatch[1], { isTrimmed: false, isIntroduceSentenceRemoved: false });
11858
+ }
11859
+ }
11826
11860
  if (isIntroduceSentenceRemoved) {
11827
11861
  const introduceSentenceRegex = /^[a-zěščřžýáíéúů:\s]*:\s*/i;
11828
11862
  if (introduceSentenceRegex.test(text)) {
@@ -11830,6 +11864,14 @@
11830
11864
  processedText = processedText.replace(introduceSentenceRegex, '');
11831
11865
  }
11832
11866
  processedText = spaceTrim$1.spaceTrim(processedText);
11867
+ // Check again for code block after removing introduce sentence
11868
+ const codeBlockMatch2 = processedText.match(codeBlockRegex);
11869
+ if (codeBlockMatch2 && codeBlockMatch2[1] !== undefined) {
11870
+ const codeBlockCount = (processedText.match(/```/g) || []).length / 2;
11871
+ if (codeBlockCount === 1) {
11872
+ return unwrapResult(codeBlockMatch2[1], { isTrimmed: false, isIntroduceSentenceRemoved: false });
11873
+ }
11874
+ }
11833
11875
  }
11834
11876
  if (processedText.length < 3) {
11835
11877
  return trimmedText;
@@ -11908,109 +11950,3976 @@
11908
11950
  */
11909
11951
 
11910
11952
  /**
11911
- * Extracts code block from markdown.
11953
+ * Tests if given string is valid agent URL
11912
11954
  *
11913
- * - When there are multiple or no code blocks the function throws a `ParseError`
11914
- *
11915
- * Note: There are multiple similar function:
11916
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
11917
- * - `extractJsonBlock` extracts exactly one valid JSON code block
11918
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
11919
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
11955
+ * Note: There are few similar functions:
11956
+ * - `isValidUrl` which tests any URL
11957
+ * - `isValidAgentUrl` *(this one)* which tests just agent URL
11958
+ * - `isValidPipelineUrl` which tests just pipeline URL
11920
11959
  *
11921
- * @public exported from `@promptbook/markdown-utils`
11922
- * @throws {ParseError} if there is not exactly one code block in the markdown
11960
+ * @public exported from `@promptbook/utils`
11923
11961
  */
11924
- function extractBlock(markdown) {
11925
- const { content } = extractOneBlockFromMarkdown(markdown);
11926
- return content;
11962
+ function isValidAgentUrl(url) {
11963
+ if (!isValidUrl(url)) {
11964
+ return false;
11965
+ }
11966
+ if (!url.startsWith('https://') && !url.startsWith('http://') /* <- Note: [👣] */) {
11967
+ return false;
11968
+ }
11969
+ if (url.includes('#')) {
11970
+ // TODO: [🐠]
11971
+ return false;
11972
+ }
11973
+ /*
11974
+ Note: [👣][🧠] Is it secure to allow pipeline URLs on private and unsecured networks?
11975
+ if (isUrlOnPrivateNetwork(url)) {
11976
+ return false;
11977
+ }
11978
+ */
11979
+ return true;
11927
11980
  }
11981
+ /**
11982
+ * TODO: [🐠] Maybe more info why the URL is invalid
11983
+ */
11928
11984
 
11929
11985
  /**
11930
- * Function trimCodeBlock will trim starting and ending code block from the string if it is present.
11986
+ * Generates a regex pattern to match a specific commitment
11931
11987
  *
11932
- * Note: [🔂] This function is idempotent.
11933
- * Note: This is useful for post-processing of the result of the chat LLM model
11934
- * when the model wraps the result in the (markdown) code block.
11988
+ * Note: It always creates new Regex object
11989
+ * Note: Uses word boundaries to ensure only full words are matched (e.g., "PERSONA" matches but "PERSONALITY" does not)
11935
11990
  *
11936
- * @public exported from `@promptbook/markdown-utils`
11991
+ * @private - TODO: [🧠] Maybe should be public?
11937
11992
  */
11938
- function trimCodeBlock(value) {
11939
- value = spaceTrim$1.spaceTrim(value);
11940
- if (!/^```[a-z]*(.*)```$/is.test(value)) {
11941
- return value;
11993
+ function createCommitmentRegex(commitment, aliases = [], requiresContent = true) {
11994
+ const allCommitments = [commitment, ...aliases];
11995
+ const patterns = allCommitments.map((commitment) => {
11996
+ const escapedCommitment = commitment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
11997
+ return escapedCommitment.split(/\s+/).join('\\s+');
11998
+ });
11999
+ const keywordPattern = patterns.join('|');
12000
+ if (requiresContent) {
12001
+ return new RegExp(`^\\s*(?<type>${keywordPattern})\\b\\s+(?<contents>.+)$`, 'gim');
12002
+ }
12003
+ else {
12004
+ return new RegExp(`^\\s*(?<type>${keywordPattern})\\b(?:\\s+(?<contents>.+))?$`, 'gim');
11942
12005
  }
11943
- value = value.replace(/^```[a-z]*/i, '');
11944
- value = value.replace(/```$/i, '');
11945
- value = spaceTrim$1.spaceTrim(value);
11946
- return value;
11947
12006
  }
11948
-
11949
12007
  /**
11950
- * Function trimEndOfCodeBlock will remove ending code block from the string if it is present.
12008
+ * Generates a regex pattern to match a specific commitment type
11951
12009
  *
11952
- * Note: This is useful for post-processing of the result of the completion LLM model
11953
- * if you want to start code block in the prompt but you don't want to end it in the result.
12010
+ * Note: It just matches the type part of the commitment
12011
+ * Note: It always creates new Regex object
12012
+ * Note: Uses word boundaries to ensure only full words are matched (e.g., "PERSONA" matches but "PERSONALITY" does not)
11954
12013
  *
11955
- * @public exported from `@promptbook/markdown-utils`
12014
+ * @private
11956
12015
  */
11957
- function trimEndOfCodeBlock(value) {
11958
- value = spaceTrim$1.spaceTrim(value);
11959
- value = value.replace(/```$/g, '');
11960
- value = spaceTrim$1.spaceTrim(value);
11961
- return value;
12016
+ function createCommitmentTypeRegex(commitment, aliases = []) {
12017
+ const allCommitments = [commitment, ...aliases];
12018
+ const patterns = allCommitments.map((commitment) => {
12019
+ const escapedCommitment = commitment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
12020
+ return escapedCommitment.split(/\s+/).join('\\s+');
12021
+ });
12022
+ const keywordPattern = patterns.join('|');
12023
+ const regex = new RegExp(`^\\s*(?<type>${keywordPattern})\\b`, 'gim');
12024
+ return regex;
11962
12025
  }
11963
12026
 
11964
12027
  /**
11965
- * @private internal for `preserve`
12028
+ * Base implementation of CommitmentDefinition that provides common functionality
12029
+ * Most commitments can extend this class and only override the applyToAgentModelRequirements method
12030
+ *
12031
+ * @private
11966
12032
  */
11967
- const _preserved = [];
12033
+ class BaseCommitmentDefinition {
12034
+ constructor(type, aliases = []) {
12035
+ this.type = type;
12036
+ this.aliases = aliases;
12037
+ }
12038
+ /**
12039
+ * Whether this commitment requires content.
12040
+ * If true, regex will match only if there is content after the commitment keyword.
12041
+ * If false, regex will match even if there is no content.
12042
+ */
12043
+ get requiresContent() {
12044
+ return true;
12045
+ }
12046
+ /**
12047
+ * Creates a regex pattern to match this commitment in agent source
12048
+ * Uses the existing createCommitmentRegex function as internal helper
12049
+ */
12050
+ createRegex() {
12051
+ return createCommitmentRegex(this.type, this.aliases, this.requiresContent);
12052
+ }
12053
+ /**
12054
+ * Creates a regex pattern to match just the commitment type
12055
+ * Uses the existing createCommitmentTypeRegex function as internal helper
12056
+ */
12057
+ createTypeRegex() {
12058
+ return createCommitmentTypeRegex(this.type, this.aliases);
12059
+ }
12060
+ /**
12061
+ * Helper method to create a new requirements object with updated system message
12062
+ * This is commonly used by many commitments
12063
+ */
12064
+ updateSystemMessage(requirements, messageUpdate) {
12065
+ const newMessage = typeof messageUpdate === 'string' ? messageUpdate : messageUpdate(requirements.systemMessage);
12066
+ return {
12067
+ ...requirements,
12068
+ systemMessage: newMessage,
12069
+ };
12070
+ }
12071
+ /**
12072
+ * Helper method to append content to the system message
12073
+ */
12074
+ appendToSystemMessage(requirements, content, separator = '\n\n') {
12075
+ return this.updateSystemMessage(requirements, (currentMessage) => {
12076
+ if (!currentMessage.trim()) {
12077
+ return content;
12078
+ }
12079
+ return currentMessage + separator + content;
12080
+ });
12081
+ }
12082
+ /**
12083
+ * Helper method to add a comment section to the system message
12084
+ * Comments are lines starting with # that will be removed from the final system message
12085
+ * but can be useful for organizing and structuring the message during processing
12086
+ */
12087
+ addCommentSection(requirements, commentTitle, content, position = 'end') {
12088
+ const commentSection = `# ${commentTitle.toUpperCase()}\n${content}`;
12089
+ if (position === 'beginning') {
12090
+ return this.updateSystemMessage(requirements, (currentMessage) => {
12091
+ if (!currentMessage.trim()) {
12092
+ return commentSection;
12093
+ }
12094
+ return commentSection + '\n\n' + currentMessage;
12095
+ });
12096
+ }
12097
+ else {
12098
+ return this.appendToSystemMessage(requirements, commentSection);
12099
+ }
12100
+ }
12101
+ /**
12102
+ * Gets tool function implementations provided by this commitment
12103
+ *
12104
+ * When the `applyToAgentModelRequirements` adds tools to the requirements, this method should return the corresponding function definitions.
12105
+ */
12106
+ getToolFunctions() {
12107
+ return {};
12108
+ }
12109
+ /**
12110
+ * Gets human-readable titles for tool functions provided by this commitment
12111
+ *
12112
+ * This is used in the UI to show a user-friendly name instead of the technical function name.
12113
+ */
12114
+ getToolTitles() {
12115
+ return {};
12116
+ }
12117
+ }
12118
+
11968
12119
  /**
11969
- * Does nothing, but preserves the function in the bundle
11970
- * Compiler is tricked into thinking the function is used
12120
+ * ACTION commitment definition
11971
12121
  *
11972
- * @param value any function to preserve
11973
- * @returns nothing
11974
- * @private within the repository
12122
+ * The ACTION commitment defines specific actions or capabilities that the agent can perform.
12123
+ * This helps define what the agent is capable of doing and how it should approach tasks.
12124
+ *
12125
+ * Example usage in agent source:
12126
+ *
12127
+ * ```book
12128
+ * ACTION Can generate code snippets and explain programming concepts
12129
+ * ACTION Able to analyze data and provide insights
12130
+ * ```
12131
+ *
12132
+ * @private [🪔] Maybe export the commitments through some package
11975
12133
  */
11976
- function $preserve(...value) {
11977
- _preserved.push(...value);
12134
+ class ActionCommitmentDefinition extends BaseCommitmentDefinition {
12135
+ constructor(type = 'ACTION') {
12136
+ super(type);
12137
+ }
12138
+ /**
12139
+ * Short one-line description of ACTION.
12140
+ */
12141
+ get description() {
12142
+ return 'Define agent capabilities and actions it can perform.';
12143
+ }
12144
+ /**
12145
+ * Icon for this commitment.
12146
+ */
12147
+ get icon() {
12148
+ return '⚡';
12149
+ }
12150
+ /**
12151
+ * Markdown documentation for ACTION commitment.
12152
+ */
12153
+ get documentation() {
12154
+ return spaceTrim$1.spaceTrim(`
12155
+ # ${this.type}
12156
+
12157
+ Defines specific actions or capabilities that the agent can perform.
12158
+
12159
+ ## Key aspects
12160
+
12161
+ - Both terms work identically and can be used interchangeably.
12162
+ - Each action adds to the agent's capability list.
12163
+ - Actions help users understand what the agent can do.
12164
+
12165
+ ## Examples
12166
+
12167
+ \`\`\`book
12168
+ Code Assistant
12169
+
12170
+ PERSONA You are a programming assistant
12171
+ ACTION Can generate code snippets and explain programming concepts
12172
+ ACTION Able to debug existing code and suggest improvements
12173
+ ACTION Can create unit tests for functions
12174
+ \`\`\`
12175
+
12176
+ \`\`\`book
12177
+ Data Scientist
12178
+
12179
+ PERSONA You are a data analysis expert
12180
+ ACTION Able to analyze data and provide insights
12181
+ ACTION Can create visualizations and charts
12182
+ ACTION Capable of statistical analysis and modeling
12183
+ KNOWLEDGE Data analysis best practices and statistical methods
12184
+ \`\`\`
12185
+ `);
12186
+ }
12187
+ applyToAgentModelRequirements(requirements, content) {
12188
+ const trimmedContent = content.trim();
12189
+ if (!trimmedContent) {
12190
+ return requirements;
12191
+ }
12192
+ // Add action capability to the system message
12193
+ const actionSection = `Capability: ${trimmedContent}`;
12194
+ return this.appendToSystemMessage(requirements, actionSection, '\n\n');
12195
+ }
11978
12196
  }
11979
12197
  /**
11980
12198
  * Note: [💞] Ignore a discrepancy between file name and entity name
11981
12199
  */
11982
12200
 
11983
- // Note: [💎]
11984
12201
  /**
11985
- * ScriptExecutionTools for JavaScript implemented via eval
12202
+ * CLOSED commitment definition
11986
12203
  *
11987
- * Warning: It is used for testing and mocking
11988
- * **NOT intended to use in the production** due to its unsafe nature, use `JavascriptExecutionTools` instead.
12204
+ * The CLOSED commitment specifies that the agent CANNOT be modified by conversation.
12205
+ * It prevents the agent from learning from interactions and updating its source code.
11989
12206
  *
11990
- * @public exported from `@promptbook/javascript`
12207
+ * Example usage in agent source:
12208
+ *
12209
+ * ```book
12210
+ * CLOSED
12211
+ * ```
12212
+ *
12213
+ * @private [🪔] Maybe export the commitments through some package
11991
12214
  */
11992
- class JavascriptEvalExecutionTools {
11993
- constructor(options) {
11994
- this.options = options || {};
12215
+ class ClosedCommitmentDefinition extends BaseCommitmentDefinition {
12216
+ constructor() {
12217
+ super('CLOSED');
11995
12218
  }
11996
12219
  /**
11997
- * Executes a JavaScript
12220
+ * The `CLOSED` commitment is standalone.
11998
12221
  */
11999
- async execute(options) {
12000
- const { scriptLanguage, parameters } = options;
12001
- let { script } = options;
12002
- if (scriptLanguage !== 'javascript') {
12003
- throw new PipelineExecutionError(`Script language ${scriptLanguage} not supported to be executed by JavascriptEvalExecutionTools`);
12222
+ get requiresContent() {
12223
+ return false;
12224
+ }
12225
+ /**
12226
+ * Short one-line description of CLOSED.
12227
+ */
12228
+ get description() {
12229
+ return 'Prevent the agent from being modified by conversation.';
12230
+ }
12231
+ /**
12232
+ * Icon for this commitment.
12233
+ */
12234
+ get icon() {
12235
+ return '🔒';
12236
+ }
12237
+ /**
12238
+ * Markdown documentation for CLOSED commitment.
12239
+ */
12240
+ get documentation() {
12241
+ return spaceTrim$1.spaceTrim(`
12242
+ # CLOSED
12243
+
12244
+ Specifies that the agent **cannot** be modified by conversation with it.
12245
+ This means the agent will **not** learn from interactions and its source code will remain static during conversation.
12246
+
12247
+ By default (if not specified), agents are \`OPEN\` to modification.
12248
+
12249
+ > See also [OPEN](/docs/OPEN)
12250
+
12251
+ ## Example
12252
+
12253
+ \`\`\`book
12254
+ CLOSED
12255
+ \`\`\`
12256
+ `);
12257
+ }
12258
+ applyToAgentModelRequirements(requirements, _content) {
12259
+ const updatedMetadata = {
12260
+ ...requirements.metadata,
12261
+ isClosed: true,
12262
+ };
12263
+ return {
12264
+ ...requirements,
12265
+ metadata: updatedMetadata,
12266
+ };
12267
+ }
12268
+ }
12269
+ /**
12270
+ * Note: [💞] Ignore a discrepancy between file name and entity name
12271
+ */
12272
+
12273
+ /**
12274
+ * COMPONENT commitment definition
12275
+ *
12276
+ * The COMPONENT commitment defines a UI component that the agent can render in the chat.
12277
+ *
12278
+ * @private [🪔] Maybe export the commitments through some package
12279
+ */
12280
+ class ComponentCommitmentDefinition extends BaseCommitmentDefinition {
12281
+ constructor() {
12282
+ super('COMPONENT');
12283
+ }
12284
+ /**
12285
+ * Short one-line description of COMPONENT.
12286
+ */
12287
+ get description() {
12288
+ return 'Define a UI component that the agent can render in the chat.';
12289
+ }
12290
+ /**
12291
+ * Icon for this commitment.
12292
+ */
12293
+ get icon() {
12294
+ return '🧩';
12295
+ }
12296
+ /**
12297
+ * Markdown documentation for COMPONENT commitment.
12298
+ */
12299
+ get documentation() {
12300
+ return spaceTrim$1.spaceTrim(`
12301
+ # COMPONENT
12302
+
12303
+ Defines a UI component that the agent can render in the chat.
12304
+
12305
+ ## Key aspects
12306
+
12307
+ - Tells the agent that a specific component is available.
12308
+ - Provides syntax for using the component.
12309
+
12310
+ ## Example
12311
+
12312
+ \`\`\`book
12313
+ COMPONENT Arrow
12314
+ The agent should render an arrow component in the chat UI.
12315
+ Syntax:
12316
+ <Arrow direction="up" color="red" />
12317
+ \`\`\`
12318
+ `);
12319
+ }
12320
+ applyToAgentModelRequirements(requirements, content) {
12321
+ const trimmedContent = content.trim();
12322
+ if (!trimmedContent) {
12323
+ return requirements;
12004
12324
  }
12005
- // Note: [💎]
12006
- // Note: Using direct eval, following variables are in same scope as eval call so they are accessible from inside the evaluated script:
12007
- const spaceTrim = (_) => spaceTrim__default["default"](_);
12008
- $preserve(spaceTrim);
12009
- const removeQuotes$1 = removeQuotes;
12010
- $preserve(removeQuotes$1);
12011
- const unwrapResult$1 = unwrapResult;
12012
- $preserve(unwrapResult$1);
12013
- const trimEndOfCodeBlock$1 = trimEndOfCodeBlock;
12325
+ // Add component capability to the system message
12326
+ const componentSection = `Component: ${trimmedContent}`;
12327
+ return this.appendToSystemMessage(requirements, componentSection, '\n\n');
12328
+ }
12329
+ }
12330
+ /**
12331
+ * Note: [💞] Ignore a discrepancy between file name and entity name
12332
+ */
12333
+
12334
+ /**
12335
+ * DELETE commitment definition
12336
+ *
12337
+ * The DELETE commitment (and its aliases CANCEL, DISCARD, REMOVE) is used to
12338
+ * remove or disregard certain information or context. This can be useful for
12339
+ * overriding previous commitments or removing unwanted behaviors.
12340
+ *
12341
+ * Example usage in agent source:
12342
+ *
12343
+ * ```book
12344
+ * DELETE Previous formatting requirements
12345
+ * CANCEL All emotional responses
12346
+ * DISCARD Technical jargon explanations
12347
+ * REMOVE Casual conversational style
12348
+ * ```
12349
+ *
12350
+ * @private [🪔] Maybe export the commitments through some package
12351
+ */
12352
+ class DeleteCommitmentDefinition extends BaseCommitmentDefinition {
12353
+ constructor(type) {
12354
+ super(type);
12355
+ }
12356
+ /**
12357
+ * Short one-line description of DELETE/CANCEL/DISCARD/REMOVE.
12358
+ */
12359
+ get description() {
12360
+ return 'Remove or **disregard** certain information, context, or previous commitments.';
12361
+ }
12362
+ /**
12363
+ * Icon for this commitment.
12364
+ */
12365
+ get icon() {
12366
+ return '🗑️';
12367
+ }
12368
+ /**
12369
+ * Markdown documentation for DELETE commitment.
12370
+ */
12371
+ get documentation() {
12372
+ return spaceTrim$1.spaceTrim(`
12373
+ # DELETE (CANCEL, DISCARD, REMOVE)
12374
+
12375
+ A commitment to remove or disregard certain information or context. This can be useful for overriding previous commitments or removing unwanted behaviors.
12376
+
12377
+ ## Aliases
12378
+
12379
+ - \`DELETE\` - Remove or eliminate something
12380
+ - \`CANCEL\` - Cancel or nullify something
12381
+ - \`DISCARD\` - Discard or ignore something
12382
+ - \`REMOVE\` - Remove or take away something
12383
+
12384
+ ## Key aspects
12385
+
12386
+ - Multiple delete commitments can be used to remove different aspects.
12387
+ - Useful for overriding previous commitments in the same agent definition.
12388
+ - Can be used to remove inherited behaviors from base personas.
12389
+ - Helps fine-tune agent behavior by explicitly removing unwanted elements.
12390
+
12391
+ ## Use cases
12392
+
12393
+ - Overriding inherited persona characteristics
12394
+ - Removing conflicting or outdated instructions
12395
+ - Disabling specific response patterns
12396
+ - Canceling previous formatting or style requirements
12397
+
12398
+ ## Examples
12399
+
12400
+ \`\`\`book
12401
+ Serious Business Assistant
12402
+
12403
+ PERSONA You are a friendly and casual assistant who uses emojis
12404
+ DELETE Casual conversational style
12405
+ REMOVE All emoji usage
12406
+ GOAL Provide professional business communications
12407
+ STYLE Use formal language and proper business etiquette
12408
+ \`\`\`
12409
+
12410
+ \`\`\`book
12411
+ Simplified Technical Support
12412
+
12413
+ PERSONA You are a technical support specialist with deep expertise
12414
+ KNOWLEDGE Extensive database of technical specifications
12415
+ DISCARD Technical jargon explanations
12416
+ CANCEL Advanced troubleshooting procedures
12417
+ GOAL Help users with simple, easy-to-follow solutions
12418
+ STYLE Use plain language that anyone can understand
12419
+ \`\`\`
12420
+
12421
+ \`\`\`book
12422
+ Focused Customer Service
12423
+
12424
+ PERSONA You are a customer service agent with broad knowledge
12425
+ ACTION Can help with billing, technical issues, and product information
12426
+ DELETE Billing assistance capabilities
12427
+ REMOVE Technical troubleshooting functions
12428
+ GOAL Focus exclusively on product information and general inquiries
12429
+ \`\`\`
12430
+
12431
+ \`\`\`book
12432
+ Concise Information Provider
12433
+
12434
+ PERSONA You are a helpful assistant who provides detailed explanations
12435
+ STYLE Include examples, analogies, and comprehensive context
12436
+ CANCEL Detailed explanation style
12437
+ DISCARD Examples and analogies
12438
+ GOAL Provide brief, direct answers without unnecessary elaboration
12439
+ STYLE Be concise and to the point
12440
+ \`\`\`
12441
+ `);
12442
+ }
12443
+ applyToAgentModelRequirements(requirements, content) {
12444
+ const trimmedContent = content.trim();
12445
+ if (!trimmedContent) {
12446
+ return requirements;
12447
+ }
12448
+ // Create deletion instruction for system message
12449
+ const deleteSection = `${this.type}: ${trimmedContent}`;
12450
+ // Delete instructions provide important context about what should be removed or ignored
12451
+ return this.appendToSystemMessage(requirements, deleteSection, '\n\n');
12452
+ }
12453
+ }
12454
+ /**
12455
+ * Note: [💞] Ignore a discrepancy between file name and entity name
12456
+ */
12457
+
12458
+ /**
12459
+ * DICTIONARY commitment definition
12460
+ *
12461
+ * The DICTIONARY commitment defines specific terms and their meanings that the agent should use correctly
12462
+ * in its reasoning and responses. This ensures consistent terminology usage.
12463
+ *
12464
+ * Key features:
12465
+ * - Multiple DICTIONARY commitments are automatically merged into one
12466
+ * - Content is placed in a dedicated section of the system message
12467
+ * - Terms and definitions are stored in metadata.DICTIONARY for debugging
12468
+ * - Agent should use the defined terms correctly in responses
12469
+ *
12470
+ * Example usage in agent source:
12471
+ *
12472
+ * ```book
12473
+ * Legal Assistant
12474
+ *
12475
+ * PERSONA You are a knowledgeable legal assistant
12476
+ * DICTIONARY Misdemeanor is a minor wrongdoing or criminal offense
12477
+ * DICTIONARY Felony is a serious crime usually punishable by imprisonment for more than one year
12478
+ * DICTIONARY Tort is a civil wrong that causes harm or loss to another person, leading to legal liability
12479
+ * ```
12480
+ *
12481
+ * @private [🪔] Maybe export the commitments through some package
12482
+ */
12483
+ class DictionaryCommitmentDefinition extends BaseCommitmentDefinition {
12484
+ constructor() {
12485
+ super('DICTIONARY');
12486
+ }
12487
+ /**
12488
+ * Short one-line description of DICTIONARY.
12489
+ */
12490
+ get description() {
12491
+ return 'Define terms and their meanings for consistent terminology usage.';
12492
+ }
12493
+ /**
12494
+ * Icon for this commitment.
12495
+ */
12496
+ get icon() {
12497
+ return '📚';
12498
+ }
12499
+ /**
12500
+ * Markdown documentation for DICTIONARY commitment.
12501
+ */
12502
+ get documentation() {
12503
+ return spaceTrim$1.spaceTrim(`
12504
+ # DICTIONARY
12505
+
12506
+ Defines specific terms and their meanings that the agent should use correctly in reasoning and responses.
12507
+
12508
+ ## Key aspects
12509
+
12510
+ - Multiple \`DICTIONARY\` commitments are merged together.
12511
+ - Terms are defined in the format: "Term is definition"
12512
+ - The agent should use these terms consistently in responses.
12513
+ - Definitions help ensure accurate and consistent terminology.
12514
+
12515
+ ## Examples
12516
+
12517
+ \`\`\`book
12518
+ Legal Assistant
12519
+
12520
+ PERSONA You are a knowledgeable legal assistant specializing in criminal law
12521
+ DICTIONARY Misdemeanor is a minor wrongdoing or criminal offense
12522
+ DICTIONARY Felony is a serious crime usually punishable by imprisonment for more than one year
12523
+ DICTIONARY Tort is a civil wrong that causes harm or loss to another person, leading to legal liability
12524
+ \`\`\`
12525
+
12526
+ \`\`\`book
12527
+ Medical Assistant
12528
+
12529
+ PERSONA You are a helpful medical assistant
12530
+ DICTIONARY Hypertension is persistently high blood pressure
12531
+ DICTIONARY Diabetes is a chronic condition that affects how the body processes blood sugar
12532
+ DICTIONARY Vaccine is a biological preparation that provides active immunity to a particular disease
12533
+ \`\`\`
12534
+ `);
12535
+ }
12536
+ applyToAgentModelRequirements(requirements, content) {
12537
+ var _a;
12538
+ const trimmedContent = content.trim();
12539
+ if (!trimmedContent) {
12540
+ return requirements;
12541
+ }
12542
+ // Get existing dictionary entries from metadata
12543
+ const existingDictionary = ((_a = requirements.metadata) === null || _a === void 0 ? void 0 : _a.DICTIONARY) || '';
12544
+ // Merge the new dictionary entry with existing entries
12545
+ const mergedDictionary = existingDictionary ? `${existingDictionary}\n${trimmedContent}` : trimmedContent;
12546
+ // Store the merged dictionary in metadata for debugging and inspection
12547
+ const updatedMetadata = {
12548
+ ...requirements.metadata,
12549
+ DICTIONARY: mergedDictionary,
12550
+ };
12551
+ // Create the dictionary section for the system message
12552
+ // Format: "# DICTIONARY\nTerm: definition\nTerm: definition..."
12553
+ const dictionarySection = `# DICTIONARY\n${mergedDictionary}`;
12554
+ return {
12555
+ ...this.appendToSystemMessage(requirements, dictionarySection),
12556
+ metadata: updatedMetadata,
12557
+ };
12558
+ }
12559
+ }
12560
+ /**
12561
+ * Note: [💞] Ignore a discrepancy between file name and entity name
12562
+ */
12563
+
12564
+ /**
12565
+ * FORMAT commitment definition
12566
+ *
12567
+ * The FORMAT commitment defines the specific output structure and formatting
12568
+ * that the agent should use in its responses. This includes data formats,
12569
+ * response templates, and structural requirements.
12570
+ *
12571
+ * Example usage in agent source:
12572
+ *
12573
+ * ```book
12574
+ * FORMAT Always respond in JSON format with 'status' and 'data' fields
12575
+ * FORMAT Use markdown formatting for all code blocks
12576
+ * ```
12577
+ *
12578
+ * @private [🪔] Maybe export the commitments through some package
12579
+ */
12580
+ class FormatCommitmentDefinition extends BaseCommitmentDefinition {
12581
+ constructor(type = 'FORMAT') {
12582
+ super(type);
12583
+ }
12584
+ /**
12585
+ * Short one-line description of FORMAT.
12586
+ */
12587
+ get description() {
12588
+ return 'Specify output structure or formatting requirements.';
12589
+ }
12590
+ /**
12591
+ * Icon for this commitment.
12592
+ */
12593
+ get icon() {
12594
+ return '📜';
12595
+ }
12596
+ /**
12597
+ * Markdown documentation for FORMAT commitment.
12598
+ */
12599
+ get documentation() {
12600
+ return spaceTrim$1.spaceTrim(`
12601
+ # ${this.type}
12602
+
12603
+ Defines the specific output structure and formatting for responses (data formats, templates, structure).
12604
+
12605
+ ## Key aspects
12606
+
12607
+ - Both terms work identically and can be used interchangeably.
12608
+ - If they are in conflict, the last one takes precedence.
12609
+ - You can specify both data formats and presentation styles.
12610
+
12611
+ ## Examples
12612
+
12613
+ \`\`\`book
12614
+ Customer Support Bot
12615
+
12616
+ PERSONA You are a helpful customer support agent
12617
+ FORMAT Always respond in JSON format with 'status' and 'data' fields
12618
+ FORMAT Use markdown formatting for all code blocks
12619
+ \`\`\`
12620
+
12621
+ \`\`\`book
12622
+ Data Analyst
12623
+
12624
+ PERSONA You are a data analysis expert
12625
+ FORMAT Present results in structured tables
12626
+ FORMAT Include confidence scores for all predictions
12627
+ STYLE Be concise and precise in explanations
12628
+ \`\`\`
12629
+ `);
12630
+ }
12631
+ applyToAgentModelRequirements(requirements, content) {
12632
+ const trimmedContent = content.trim();
12633
+ if (!trimmedContent) {
12634
+ return requirements;
12635
+ }
12636
+ // Add format instructions to the system message
12637
+ const formatSection = `Output Format: ${trimmedContent}`;
12638
+ return this.appendToSystemMessage(requirements, formatSection, '\n\n');
12639
+ }
12640
+ }
12641
+ /**
12642
+ * Note: [💞] Ignore a discrepancy between file name and entity name
12643
+ */
12644
+
12645
+ /**
12646
+ * FROM commitment definition
12647
+ *
12648
+ * The FROM commitment tells the agent that its `agentSource` is inherited from another agent.
12649
+ *
12650
+ * Example usage in agent source:
12651
+ *
12652
+ * ```book
12653
+ * FROM https://s6.ptbk.io/benjamin-white
12654
+ * ```
12655
+ *
12656
+ * @private [🪔] Maybe export the commitments through some package
12657
+ */
12658
+ class FromCommitmentDefinition extends BaseCommitmentDefinition {
12659
+ constructor(type = 'FROM') {
12660
+ super(type);
12661
+ }
12662
+ /**
12663
+ * Short one-line description of FROM.
12664
+ */
12665
+ get description() {
12666
+ return 'Inherit agent source from another agent.';
12667
+ }
12668
+ /**
12669
+ * Icon for this commitment.
12670
+ */
12671
+ get icon() {
12672
+ return '🧬';
12673
+ }
12674
+ /**
12675
+ * Markdown documentation for FROM commitment.
12676
+ */
12677
+ get documentation() {
12678
+ return spaceTrim$1.spaceTrim(`
12679
+ # ${this.type}
12680
+
12681
+ Inherits agent source from another agent.
12682
+
12683
+ ## Examples
12684
+
12685
+ \`\`\`book
12686
+ My AI Agent
12687
+
12688
+ FROM https://s6.ptbk.io/benjamin-white
12689
+ RULE Speak only in English.
12690
+ \`\`\`
12691
+ `);
12692
+ }
12693
+ applyToAgentModelRequirements(requirements, content) {
12694
+ const trimmedContent = content.trim();
12695
+ if (!trimmedContent) {
12696
+ return {
12697
+ ...requirements,
12698
+ parentAgentUrl: undefined,
12699
+ };
12700
+ }
12701
+ if (trimmedContent.toUpperCase() === 'VOID' ||
12702
+ trimmedContent.toUpperCase() === 'NULL' ||
12703
+ trimmedContent.toUpperCase() === 'NONE' ||
12704
+ trimmedContent.toUpperCase() === 'NIL') {
12705
+ return {
12706
+ ...requirements,
12707
+ parentAgentUrl: null,
12708
+ };
12709
+ }
12710
+ if (!isValidAgentUrl(trimmedContent)) {
12711
+ throw new Error(spaceTrim$1.spaceTrim((block) => `
12712
+ Invalid agent URL in FROM commitment: "${trimmedContent}"
12713
+
12714
+ \`\`\`book
12715
+ ${block(content)}
12716
+ \`\`\`
12717
+
12718
+
12719
+ `));
12720
+ }
12721
+ const parentAgentUrl = trimmedContent;
12722
+ return {
12723
+ ...requirements,
12724
+ parentAgentUrl,
12725
+ };
12726
+ }
12727
+ }
12728
+ /**
12729
+ * Note: [💞] Ignore a discrepancy between file name and entity name
12730
+ */
12731
+
12732
+ /**
12733
+ * GOAL commitment definition
12734
+ *
12735
+ * The GOAL commitment defines the main goal which should be achieved by the AI assistant.
12736
+ * There can be multiple goals. Later goals are more important than earlier goals.
12737
+ *
12738
+ * Example usage in agent source:
12739
+ *
12740
+ * ```book
12741
+ * GOAL Help users understand complex technical concepts
12742
+ * GOAL Provide accurate and up-to-date information
12743
+ * GOAL Always prioritize user safety and ethical guidelines
12744
+ * ```
12745
+ *
12746
+ * @private [🪔] Maybe export the commitments through some package
12747
+ */
12748
+ class GoalCommitmentDefinition extends BaseCommitmentDefinition {
12749
+ constructor(type = 'GOAL') {
12750
+ super(type);
12751
+ }
12752
+ /**
12753
+ * Short one-line description of GOAL.
12754
+ */
12755
+ get description() {
12756
+ return 'Define main **goals** the AI assistant should achieve, with later goals having higher priority.';
12757
+ }
12758
+ /**
12759
+ * Icon for this commitment.
12760
+ */
12761
+ get icon() {
12762
+ return '🎯';
12763
+ }
12764
+ /**
12765
+ * Markdown documentation for GOAL commitment.
12766
+ */
12767
+ get documentation() {
12768
+ return spaceTrim$1.spaceTrim(`
12769
+ # ${this.type}
12770
+
12771
+ 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.
12772
+
12773
+ ## Key aspects
12774
+
12775
+ - Both terms work identically and can be used interchangeably.
12776
+ - Later goals have higher priority and can override earlier goals.
12777
+ - Goals provide clear direction and purpose for the agent's responses.
12778
+ - Goals influence decision-making and response prioritization.
12779
+
12780
+ ## Priority system
12781
+
12782
+ When multiple goals are defined, they are processed in order, with later goals taking precedence over earlier ones when there are conflicts.
12783
+
12784
+ ## Examples
12785
+
12786
+ \`\`\`book
12787
+ Customer Support Agent
12788
+
12789
+ PERSONA You are a helpful customer support representative
12790
+ GOAL Resolve customer issues quickly and efficiently
12791
+ GOAL Maintain high customer satisfaction scores
12792
+ GOAL Always follow company policies and procedures
12793
+ RULE Be polite and professional at all times
12794
+ \`\`\`
12795
+
12796
+ \`\`\`book
12797
+ Educational Assistant
12798
+
12799
+ PERSONA You are an educational assistant specializing in mathematics
12800
+ GOAL Help students understand mathematical concepts clearly
12801
+ GOAL Encourage critical thinking and problem-solving skills
12802
+ GOAL Ensure all explanations are age-appropriate and accessible
12803
+ STYLE Use simple language and provide step-by-step explanations
12804
+ \`\`\`
12805
+
12806
+ \`\`\`book
12807
+ Safety-First Assistant
12808
+
12809
+ PERSONA You are a general-purpose AI assistant
12810
+ GOAL Be helpful and informative in all interactions
12811
+ GOAL Provide accurate and reliable information
12812
+ GOAL Always prioritize user safety and ethical guidelines
12813
+ RULE Never provide harmful or dangerous advice
12814
+ \`\`\`
12815
+ `);
12816
+ }
12817
+ applyToAgentModelRequirements(requirements, content) {
12818
+ const trimmedContent = content.trim();
12819
+ if (!trimmedContent) {
12820
+ return requirements;
12821
+ }
12822
+ // Create goal section for system message
12823
+ const goalSection = `Goal: ${trimmedContent}`;
12824
+ // Goals are important directives, so we add them prominently to the system message
12825
+ return this.appendToSystemMessage(requirements, goalSection, '\n\n');
12826
+ }
12827
+ }
12828
+ /**
12829
+ * Note: [💞] Ignore a discrepancy between file name and entity name
12830
+ */
12831
+
12832
+ /**
12833
+ * IMPORT commitment definition
12834
+ *
12835
+ * The IMPORT commitment tells the agent to import content from another agent at the current location.
12836
+ *
12837
+ * Example usage in agent source:
12838
+ *
12839
+ * ```book
12840
+ * IMPORT https://s6.ptbk.io/benjamin-white
12841
+ * ```
12842
+ *
12843
+ * @private [🪔] Maybe export the commitments through some package
12844
+ */
12845
+ class ImportCommitmentDefinition extends BaseCommitmentDefinition {
12846
+ constructor(type = 'IMPORT') {
12847
+ super(type);
12848
+ }
12849
+ /**
12850
+ * Short one-line description of IMPORT.
12851
+ */
12852
+ get description() {
12853
+ return 'Import content from another agent or a generic text file.';
12854
+ }
12855
+ /**
12856
+ * Icon for this commitment.
12857
+ */
12858
+ get icon() {
12859
+ return '📥';
12860
+ }
12861
+ /**
12862
+ * Markdown documentation for IMPORT commitment.
12863
+ */
12864
+ get documentation() {
12865
+ return spaceTrim$1.spaceTrim(`
12866
+ # ${this.type}
12867
+
12868
+ Imports content from another agent or a generic text file at the location of the commitment.
12869
+
12870
+ ## Examples
12871
+
12872
+ \`\`\`book
12873
+ My AI Agent
12874
+
12875
+ IMPORT https://s6.ptbk.io/benjamin-white
12876
+ IMPORT https://example.com/some-text-file.txt
12877
+ IMPORT ./path/to/local-file.json
12878
+ RULE Speak only in English.
12879
+ \`\`\`
12880
+ `);
12881
+ }
12882
+ applyToAgentModelRequirements(requirements, content) {
12883
+ const trimmedContent = content.trim();
12884
+ if (!trimmedContent) {
12885
+ return requirements;
12886
+ }
12887
+ if (isValidAgentUrl(trimmedContent)) {
12888
+ const importedAgentUrl = trimmedContent;
12889
+ return {
12890
+ ...requirements,
12891
+ importedAgentUrls: [...(requirements.importedAgentUrls || []), importedAgentUrl],
12892
+ };
12893
+ }
12894
+ if (isValidUrl(trimmedContent) || isValidFilePath(trimmedContent)) {
12895
+ return {
12896
+ ...requirements,
12897
+ importedFileUrls: [...(requirements.importedFileUrls || []), trimmedContent],
12898
+ };
12899
+ }
12900
+ throw new Error(spaceTrim$1.spaceTrim((block) => `
12901
+ Invalid agent URL or file path in IMPORT commitment: "${trimmedContent}"
12902
+
12903
+ \`\`\`book
12904
+ ${block(content)}
12905
+ \`\`\`
12906
+ `));
12907
+ }
12908
+ }
12909
+ /**
12910
+ * Note: [💞] Ignore a discrepancy between file name and entity name
12911
+ */
12912
+
12913
+ /**
12914
+ * KNOWLEDGE commitment definition
12915
+ *
12916
+ * The KNOWLEDGE commitment adds specific knowledge, facts, or context to the agent
12917
+ * using RAG (Retrieval-Augmented Generation) approach for external sources.
12918
+ *
12919
+ * Supports both direct text knowledge and external sources like PDFs.
12920
+ *
12921
+ * Example usage in agent source:
12922
+ *
12923
+ * ```book
12924
+ * KNOWLEDGE The company was founded in 2020 and specializes in AI-powered solutions
12925
+ * KNOWLEDGE https://example.com/company-handbook.pdf
12926
+ * KNOWLEDGE https://example.com/product-documentation.pdf
12927
+ * ```
12928
+ *
12929
+ * @private [🪔] Maybe export the commitments through some package
12930
+ */
12931
+ class KnowledgeCommitmentDefinition extends BaseCommitmentDefinition {
12932
+ constructor() {
12933
+ super('KNOWLEDGE');
12934
+ }
12935
+ /**
12936
+ * Short one-line description of KNOWLEDGE.
12937
+ */
12938
+ get description() {
12939
+ return 'Add domain **knowledge** via direct text or external sources (RAG).';
12940
+ }
12941
+ /**
12942
+ * Icon for this commitment.
12943
+ */
12944
+ get icon() {
12945
+ return '🧠';
12946
+ }
12947
+ /**
12948
+ * Markdown documentation for KNOWLEDGE commitment.
12949
+ */
12950
+ get documentation() {
12951
+ return spaceTrim$1.spaceTrim(`
12952
+ # ${this.type}
12953
+
12954
+ Adds specific knowledge, facts, or context to the agent using a RAG (Retrieval-Augmented Generation) approach for external sources.
12955
+
12956
+ ## Key aspects
12957
+
12958
+ - Both terms work identically and can be used interchangeably.
12959
+ - Supports both direct text knowledge and external URLs.
12960
+ - External sources (PDFs, websites) are processed via RAG for context retrieval.
12961
+
12962
+ ## Supported formats
12963
+
12964
+ - Direct text: Immediate knowledge incorporated into agent
12965
+ - URLs: External documents processed for contextual retrieval
12966
+ - Supported file types: PDF, text, markdown, HTML
12967
+
12968
+ ## Examples
12969
+
12970
+ \`\`\`book
12971
+ Customer Support Bot
12972
+
12973
+ PERSONA You are a helpful customer support agent for TechCorp
12974
+ KNOWLEDGE TechCorp was founded in 2020 and specializes in AI-powered solutions
12975
+ KNOWLEDGE https://example.com/company-handbook.pdf
12976
+ KNOWLEDGE https://example.com/product-documentation.pdf
12977
+ RULE Always be polite and professional
12978
+ \`\`\`
12979
+
12980
+ \`\`\`book
12981
+ Research Assistant
12982
+
12983
+ PERSONA You are a knowledgeable research assistant
12984
+ KNOWLEDGE Academic research requires careful citation and verification
12985
+ KNOWLEDGE https://example.com/research-guidelines.pdf
12986
+ ACTION Can help with literature reviews and data analysis
12987
+ STYLE Present information in clear, academic format
12988
+ \`\`\`
12989
+ `);
12990
+ }
12991
+ applyToAgentModelRequirements(requirements, content) {
12992
+ const trimmedContent = content.trim();
12993
+ if (!trimmedContent) {
12994
+ return requirements;
12995
+ }
12996
+ // Check if content is a URL (external knowledge source)
12997
+ if (isValidUrl(trimmedContent)) {
12998
+ // Store the URL for later async processing
12999
+ const updatedRequirements = {
13000
+ ...requirements,
13001
+ knowledgeSources: [
13002
+ ...(requirements.knowledgeSources || []),
13003
+ trimmedContent,
13004
+ ],
13005
+ };
13006
+ // Add placeholder information about knowledge sources to system message
13007
+ const knowledgeInfo = `Knowledge Source URL: ${trimmedContent} (will be processed for retrieval during chat)`;
13008
+ return this.appendToSystemMessage(updatedRequirements, knowledgeInfo, '\n\n');
13009
+ }
13010
+ else {
13011
+ // Direct text knowledge - add to system message
13012
+ const knowledgeSection = `Knowledge: ${trimmedContent}`;
13013
+ return this.appendToSystemMessage(requirements, knowledgeSection, '\n\n');
13014
+ }
13015
+ }
13016
+ }
13017
+ /**
13018
+ * Note: [💞] Ignore a discrepancy between file name and entity name
13019
+ */
13020
+
13021
+ /**
13022
+ * LANGUAGE commitment definition
13023
+ *
13024
+ * The LANGUAGE/LANGUAGES commitment specifies the language(s) the agent should use in its responses.
13025
+ *
13026
+ * Example usage in agent source:
13027
+ *
13028
+ * ```book
13029
+ * LANGUAGE English
13030
+ * LANGUAGE French, English and Czech
13031
+ * ```
13032
+ *
13033
+ * @private [🪔] Maybe export the commitments through some package
13034
+ */
13035
+ class LanguageCommitmentDefinition extends BaseCommitmentDefinition {
13036
+ constructor(type = 'LANGUAGE') {
13037
+ super(type);
13038
+ }
13039
+ /**
13040
+ * Short one-line description of LANGUAGE/LANGUAGES.
13041
+ */
13042
+ get description() {
13043
+ return 'Specifies the language(s) the agent should use.';
13044
+ }
13045
+ /**
13046
+ * Icon for this commitment.
13047
+ */
13048
+ get icon() {
13049
+ return '🌐';
13050
+ }
13051
+ /**
13052
+ * Markdown documentation for LANGUAGE/LANGUAGES commitment.
13053
+ */
13054
+ get documentation() {
13055
+ return spaceTrim$1.spaceTrim(`
13056
+ # ${this.type}
13057
+
13058
+ Specifies the language(s) the agent should use in its responses.
13059
+ This is a specialized variation of the RULE commitment focused on language constraints.
13060
+
13061
+ ## Examples
13062
+
13063
+ \`\`\`book
13064
+ Paul Smith & Associés
13065
+
13066
+ PERSONA You are a company lawyer.
13067
+ LANGUAGE French, English and Czech
13068
+ \`\`\`
13069
+
13070
+ \`\`\`book
13071
+ Customer Support
13072
+
13073
+ PERSONA You are a customer support agent.
13074
+ LANGUAGE English
13075
+ \`\`\`
13076
+ `);
13077
+ }
13078
+ applyToAgentModelRequirements(requirements, content) {
13079
+ const trimmedContent = content.trim();
13080
+ if (!trimmedContent) {
13081
+ return requirements;
13082
+ }
13083
+ // Add language rule to the system message
13084
+ const languageSection = `Language: ${trimmedContent}`;
13085
+ return this.appendToSystemMessage(requirements, languageSection, '\n\n');
13086
+ }
13087
+ }
13088
+ /**
13089
+ * Note: [💞] Ignore a discrepancy between file name and entity name
13090
+ */
13091
+
13092
+ /**
13093
+ * MEMORY commitment definition
13094
+ *
13095
+ * The MEMORY commitment is similar to KNOWLEDGE but has a focus on remembering past
13096
+ * interactions and user preferences. It helps the agent maintain context about the
13097
+ * user's history, preferences, and previous conversations.
13098
+ *
13099
+ * Example usage in agent source:
13100
+ *
13101
+ * ```book
13102
+ * MEMORY User prefers detailed technical explanations
13103
+ * MEMORY Previously worked on React projects
13104
+ * MEMORY Timezone: UTC-5 (Eastern Time)
13105
+ * ```
13106
+ *
13107
+ * @private [🪔] Maybe export the commitments through some package
13108
+ */
13109
+ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
13110
+ constructor(type = 'MEMORY') {
13111
+ super(type);
13112
+ }
13113
+ /**
13114
+ * Short one-line description of MEMORY.
13115
+ */
13116
+ get description() {
13117
+ return 'Remember past interactions and user **preferences** for personalized responses.';
13118
+ }
13119
+ /**
13120
+ * Icon for this commitment.
13121
+ */
13122
+ get icon() {
13123
+ return '🧠';
13124
+ }
13125
+ /**
13126
+ * Markdown documentation for MEMORY commitment.
13127
+ */
13128
+ get documentation() {
13129
+ return spaceTrim$1.spaceTrim(`
13130
+ # ${this.type}
13131
+
13132
+ 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.
13133
+
13134
+ ## Key aspects
13135
+
13136
+ - Both terms work identically and can be used interchangeably.
13137
+ - Focuses on user-specific information and interaction history.
13138
+ - Helps personalize responses based on past interactions.
13139
+ - Maintains continuity across conversations.
13140
+
13141
+ ## Differences from KNOWLEDGE
13142
+
13143
+ - \`KNOWLEDGE\` is for domain expertise and factual information
13144
+ - \`MEMORY\` is for user-specific context and preferences
13145
+ - \`MEMORY\` creates more personalized interactions
13146
+ - \`MEMORY\` often includes temporal or preference-based information
13147
+
13148
+ ## Examples
13149
+
13150
+ \`\`\`book
13151
+ Personal Assistant
13152
+
13153
+ PERSONA You are a personal productivity assistant
13154
+ MEMORY User is a software developer working in JavaScript/React
13155
+ MEMORY User prefers morning work sessions and afternoon meetings
13156
+ MEMORY Previously helped with project planning for mobile apps
13157
+ MEMORY User timezone: UTC-8 (Pacific Time)
13158
+ GOAL Help optimize daily productivity and workflow
13159
+ \`\`\`
13160
+
13161
+ \`\`\`book
13162
+ Learning Companion
13163
+
13164
+ PERSONA You are an educational companion for programming students
13165
+ MEMORY Student is learning Python as their first programming language
13166
+ MEMORY Previous topics covered: variables, loops, functions
13167
+ MEMORY Student learns best with practical examples and exercises
13168
+ MEMORY Last session: working on list comprehensions
13169
+ GOAL Provide progressive learning experiences tailored to student's pace
13170
+ \`\`\`
13171
+
13172
+ \`\`\`book
13173
+ Customer Support Agent
13174
+
13175
+ PERSONA You are a customer support representative
13176
+ MEMORY Customer has premium subscription since 2023
13177
+ MEMORY Previous issue: billing question resolved last month
13178
+ MEMORY Customer prefers email communication over phone calls
13179
+ MEMORY Account shows frequent use of advanced features
13180
+ GOAL Provide personalized support based on customer history
13181
+ \`\`\`
13182
+ `);
13183
+ }
13184
+ applyToAgentModelRequirements(requirements, content) {
13185
+ const trimmedContent = content.trim();
13186
+ if (!trimmedContent) {
13187
+ return requirements;
13188
+ }
13189
+ // Create memory section for system message
13190
+ const memorySection = `Memory: ${trimmedContent}`;
13191
+ // Memory information is contextual and should be included in the system message
13192
+ return this.appendToSystemMessage(requirements, memorySection, '\n\n');
13193
+ }
13194
+ }
13195
+ /**
13196
+ * Note: [💞] Ignore a discrepancy between file name and entity name
13197
+ */
13198
+
13199
+ /**
13200
+ * AGENT MESSAGE commitment definition
13201
+ *
13202
+ * The AGENT MESSAGE commitment defines a message from the agent in the conversation history.
13203
+ * It is used to pre-fill the chat with a conversation history or to provide few-shot examples.
13204
+ *
13205
+ * Example usage in agent source:
13206
+ *
13207
+ * ```book
13208
+ * AGENT MESSAGE What seems to be the issue?
13209
+ * ```
13210
+ *
13211
+ * @private [🪔] Maybe export the commitments through some package
13212
+ */
13213
+ class AgentMessageCommitmentDefinition extends BaseCommitmentDefinition {
13214
+ constructor() {
13215
+ super('AGENT MESSAGE');
13216
+ }
13217
+ /**
13218
+ * Short one-line description of AGENT MESSAGE.
13219
+ */
13220
+ get description() {
13221
+ return 'Defines a **message from the agent** in the conversation history.';
13222
+ }
13223
+ /**
13224
+ * Icon for this commitment.
13225
+ */
13226
+ get icon() {
13227
+ return '🤖';
13228
+ }
13229
+ /**
13230
+ * Markdown documentation for AGENT MESSAGE commitment.
13231
+ */
13232
+ get documentation() {
13233
+ return spaceTrim$1.spaceTrim(`
13234
+ # ${this.type}
13235
+
13236
+ 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.
13237
+
13238
+ ## Key aspects
13239
+
13240
+ - Represents a message sent by the agent.
13241
+ - Used for setting up conversation context.
13242
+ - Can be used in conjunction with USER MESSAGE.
13243
+
13244
+ ## Examples
13245
+
13246
+ \`\`\`book
13247
+ Conversation History
13248
+
13249
+ USER MESSAGE Hello, I have a problem.
13250
+ AGENT MESSAGE What seems to be the issue?
13251
+ USER MESSAGE My computer is not starting.
13252
+ \`\`\`
13253
+ `);
13254
+ }
13255
+ applyToAgentModelRequirements(requirements, content) {
13256
+ // AGENT MESSAGE is for UI display purposes / conversation history construction
13257
+ // and typically doesn't need to be added to the system prompt or model requirements directly.
13258
+ // It is extracted separately for the chat interface.
13259
+ var _a;
13260
+ const pendingUserMessage = (_a = requirements.metadata) === null || _a === void 0 ? void 0 : _a.pendingUserMessage;
13261
+ if (pendingUserMessage) {
13262
+ const newSample = { question: pendingUserMessage, answer: content };
13263
+ const newSamples = [...(requirements.samples || []), newSample];
13264
+ const newMetadata = { ...requirements.metadata };
13265
+ delete newMetadata.pendingUserMessage;
13266
+ return {
13267
+ ...requirements,
13268
+ samples: newSamples,
13269
+ metadata: newMetadata,
13270
+ };
13271
+ }
13272
+ return requirements;
13273
+ }
13274
+ }
13275
+
13276
+ /**
13277
+ * INITIAL MESSAGE commitment definition
13278
+ *
13279
+ * The INITIAL MESSAGE commitment defines the first message that the user sees when opening the chat.
13280
+ * It is used to greet the user and set the tone of the conversation.
13281
+ *
13282
+ * Example usage in agent source:
13283
+ *
13284
+ * ```book
13285
+ * INITIAL MESSAGE Hello! I am ready to help you with your tasks.
13286
+ * ```
13287
+ *
13288
+ * @private [🪔] Maybe export the commitments through some package
13289
+ */
13290
+ class InitialMessageCommitmentDefinition extends BaseCommitmentDefinition {
13291
+ constructor() {
13292
+ super('INITIAL MESSAGE');
13293
+ }
13294
+ /**
13295
+ * Short one-line description of INITIAL MESSAGE.
13296
+ */
13297
+ get description() {
13298
+ return 'Defines the **initial message** shown to the user when the chat starts.';
13299
+ }
13300
+ /**
13301
+ * Icon for this commitment.
13302
+ */
13303
+ get icon() {
13304
+ return '👋';
13305
+ }
13306
+ /**
13307
+ * Markdown documentation for INITIAL MESSAGE commitment.
13308
+ */
13309
+ get documentation() {
13310
+ return spaceTrim$1.spaceTrim(`
13311
+ # ${this.type}
13312
+
13313
+ 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).
13314
+
13315
+ ## Key aspects
13316
+
13317
+ - Used to greet the user.
13318
+ - Sets the tone of the conversation.
13319
+ - Displayed immediately when the chat interface loads.
13320
+
13321
+ ## Examples
13322
+
13323
+ \`\`\`book
13324
+ Support Agent
13325
+
13326
+ PERSONA You are a helpful support agent.
13327
+ INITIAL MESSAGE Hi there! How can I assist you today?
13328
+ \`\`\`
13329
+ `);
13330
+ }
13331
+ applyToAgentModelRequirements(requirements, content) {
13332
+ // INITIAL MESSAGE is for UI display purposes and for conversation history construction.
13333
+ const newSample = { question: null, answer: content };
13334
+ const newSamples = [...(requirements.samples || []), newSample];
13335
+ return {
13336
+ ...requirements,
13337
+ samples: newSamples,
13338
+ };
13339
+ }
13340
+ }
13341
+
13342
+ /**
13343
+ * MESSAGE commitment definition
13344
+ *
13345
+ * The MESSAGE commitment contains 1:1 text of the message which AI assistant already
13346
+ * sent during the conversation. Later messages are later in the conversation.
13347
+ * It is similar to EXAMPLE but it is not example, it is the real message which
13348
+ * AI assistant already sent.
13349
+ *
13350
+ * Example usage in agent source:
13351
+ *
13352
+ * ```book
13353
+ * MESSAGE Hello! How can I help you today?
13354
+ * MESSAGE I understand you're looking for information about our services.
13355
+ * MESSAGE Based on your requirements, I'd recommend our premium package.
13356
+ * ```
13357
+ *
13358
+ * @private [🪔] Maybe export the commitments through some package
13359
+ */
13360
+ class MessageCommitmentDefinition extends BaseCommitmentDefinition {
13361
+ constructor(type = 'MESSAGE') {
13362
+ super(type);
13363
+ }
13364
+ /**
13365
+ * Short one-line description of MESSAGE.
13366
+ */
13367
+ get description() {
13368
+ return 'Include actual **messages** the AI assistant has sent during conversation history.';
13369
+ }
13370
+ /**
13371
+ * Icon for this commitment.
13372
+ */
13373
+ get icon() {
13374
+ return '💬';
13375
+ }
13376
+ /**
13377
+ * Markdown documentation for MESSAGE commitment.
13378
+ */
13379
+ get documentation() {
13380
+ return spaceTrim$1.spaceTrim(`
13381
+ # ${this.type}
13382
+
13383
+ 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.
13384
+
13385
+ ## Key aspects
13386
+
13387
+ - Multiple \`MESSAGE\` and \`MESSAGES\` commitments represent the conversation timeline.
13388
+ - Both terms work identically and can be used interchangeably.
13389
+ - Later messages are later in the conversation chronologically.
13390
+ - Contains actual historical messages, not examples or templates.
13391
+ - Helps maintain conversation continuity and context.
13392
+
13393
+ ## Differences from EXAMPLE
13394
+
13395
+ - \`EXAMPLE\` shows hypothetical or template responses
13396
+ - \`MESSAGE\`/\`MESSAGES\` contains actual historical conversation content
13397
+ - \`MESSAGE\`/\`MESSAGES\` preserves the exact conversation flow
13398
+ - \`MESSAGE\`/\`MESSAGES\` helps with context awareness and consistency
13399
+
13400
+ ## Use cases
13401
+
13402
+ - Maintaining conversation history context
13403
+ - Ensuring consistent tone and style across messages
13404
+ - Referencing previous responses in ongoing conversations
13405
+ - Building upon previously established context
13406
+
13407
+ ## Examples
13408
+
13409
+ \`\`\`book
13410
+ Customer Support Continuation
13411
+
13412
+ PERSONA You are a helpful customer support agent
13413
+ MESSAGE Hello! How can I help you today?
13414
+ MESSAGE I understand you're experiencing issues with your account login.
13415
+ MESSAGE I've sent you a password reset link to your email address.
13416
+ MESSAGE Is there anything else I can help you with regarding your account?
13417
+ GOAL Continue providing consistent support based on conversation history
13418
+ \`\`\`
13419
+
13420
+ \`\`\`book
13421
+ Technical Discussion
13422
+
13423
+ PERSONA You are a software development mentor
13424
+ MESSAGE Let's start by reviewing the React component structure you shared.
13425
+ MESSAGE I notice you're using class components - have you considered hooks?
13426
+ MESSAGE Here's how you could refactor that using the useState hook.
13427
+ MESSAGE Great question about performance! Let me explain React's rendering cycle.
13428
+ KNOWLEDGE React hooks were introduced in version 16.8
13429
+ \`\`\`
13430
+
13431
+ \`\`\`book
13432
+ Educational Session
13433
+
13434
+ PERSONA You are a mathematics tutor
13435
+ MESSAGE Today we'll work on solving quadratic equations.
13436
+ MESSAGE Let's start with the basic form: ax² + bx + c = 0
13437
+ MESSAGE Remember, we can use the quadratic formula or factoring.
13438
+ MESSAGE You did great with that first problem! Let's try a more complex one.
13439
+ GOAL Build upon previous explanations for deeper understanding
13440
+ \`\`\`
13441
+ `);
13442
+ }
13443
+ applyToAgentModelRequirements(requirements, content) {
13444
+ const trimmedContent = content.trim();
13445
+ if (!trimmedContent) {
13446
+ return requirements;
13447
+ }
13448
+ // Create message section for system message
13449
+ const messageSection = `Previous Message: ${trimmedContent}`;
13450
+ // Messages represent conversation history and should be included for context
13451
+ return this.appendToSystemMessage(requirements, messageSection, '\n\n');
13452
+ }
13453
+ }
13454
+ /**
13455
+ * Note: [💞] Ignore a discrepancy between file name and entity name
13456
+ */
13457
+
13458
+ /**
13459
+ * USER MESSAGE commitment definition
13460
+ *
13461
+ * The USER MESSAGE commitment defines a message from the user in the conversation history.
13462
+ * It is used to pre-fill the chat with a conversation history or to provide few-shot examples.
13463
+ *
13464
+ * Example usage in agent source:
13465
+ *
13466
+ * ```book
13467
+ * USER MESSAGE Hello, I have a problem.
13468
+ * ```
13469
+ *
13470
+ * @private [🪔] Maybe export the commitments through some package
13471
+ */
13472
+ class UserMessageCommitmentDefinition extends BaseCommitmentDefinition {
13473
+ constructor() {
13474
+ super('USER MESSAGE');
13475
+ }
13476
+ /**
13477
+ * Short one-line description of USER MESSAGE.
13478
+ */
13479
+ get description() {
13480
+ return 'Defines a **message from the user** in the conversation history.';
13481
+ }
13482
+ /**
13483
+ * Icon for this commitment.
13484
+ */
13485
+ get icon() {
13486
+ return '🧑';
13487
+ }
13488
+ /**
13489
+ * Markdown documentation for USER MESSAGE commitment.
13490
+ */
13491
+ get documentation() {
13492
+ return spaceTrim$1.spaceTrim(`
13493
+ # ${this.type}
13494
+
13495
+ 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.
13496
+
13497
+ ## Key aspects
13498
+
13499
+ - Represents a message sent by the user.
13500
+ - Used for setting up conversation context.
13501
+ - Can be used in conjunction with AGENT MESSAGE.
13502
+
13503
+ ## Examples
13504
+
13505
+ \`\`\`book
13506
+ Conversation History
13507
+
13508
+ USER MESSAGE Hello, I have a problem.
13509
+ AGENT MESSAGE What seems to be the issue?
13510
+ USER MESSAGE My computer is not starting.
13511
+ \`\`\`
13512
+ `);
13513
+ }
13514
+ applyToAgentModelRequirements(requirements, content) {
13515
+ return {
13516
+ ...requirements,
13517
+ metadata: {
13518
+ ...requirements.metadata,
13519
+ pendingUserMessage: content,
13520
+ },
13521
+ };
13522
+ }
13523
+ }
13524
+
13525
+ /**
13526
+ * META commitment definition
13527
+ *
13528
+ * The META commitment handles all meta-information about the agent such as:
13529
+ * - META IMAGE: Sets the agent's avatar/profile image URL
13530
+ * - META LINK: Provides profile/source links for the person the agent models
13531
+ * - META TITLE: Sets the agent's display title
13532
+ * - META DESCRIPTION: Sets the agent's description
13533
+ * - META [ANYTHING]: Any other meta information in uppercase format
13534
+ *
13535
+ * These commitments are special because they don't affect the system message,
13536
+ * but are handled separately in the parsing logic for profile display.
13537
+ *
13538
+ * Example usage in agent source:
13539
+ *
13540
+ * ```book
13541
+ * META IMAGE https://example.com/avatar.jpg
13542
+ * META LINK https://twitter.com/username
13543
+ * META TITLE Professional Assistant
13544
+ * META DESCRIPTION An AI assistant specialized in business tasks
13545
+ * META AUTHOR John Doe
13546
+ * META VERSION 1.0
13547
+ * ```
13548
+ *
13549
+ * @private [🪔] Maybe export the commitments through some package
13550
+ */
13551
+ class MetaCommitmentDefinition extends BaseCommitmentDefinition {
13552
+ constructor() {
13553
+ super('META');
13554
+ }
13555
+ /**
13556
+ * Short one-line description of META commitments.
13557
+ */
13558
+ get description() {
13559
+ return 'Set meta-information about the agent (IMAGE, LINK, TITLE, DESCRIPTION, etc.).';
13560
+ }
13561
+ /**
13562
+ * Icon for this commitment.
13563
+ */
13564
+ get icon() {
13565
+ return 'ℹ️';
13566
+ }
13567
+ /**
13568
+ * Markdown documentation for META commitment.
13569
+ */
13570
+ get documentation() {
13571
+ return spaceTrim$1.spaceTrim(`
13572
+ # META
13573
+
13574
+ Sets meta-information about the agent that is used for display and attribution purposes.
13575
+
13576
+ ## Supported META types
13577
+
13578
+ - **META IMAGE** - Sets the agent's avatar/profile image URL
13579
+ - **META LINK** - Provides profile/source links for the person the agent models
13580
+ - **META TITLE** - Sets the agent's display title
13581
+ - **META DESCRIPTION** - Sets the agent's description
13582
+ - **META [ANYTHING]** - Any other meta information in uppercase format
13583
+
13584
+ ## Key aspects
13585
+
13586
+ - Does not modify the agent's behavior or responses
13587
+ - Used for visual representation and attribution in user interfaces
13588
+ - Multiple META commitments of different types can be used
13589
+ - Multiple META LINK commitments can be used for different social profiles
13590
+ - If multiple META commitments of the same type are specified, the last one takes precedence (except for LINK)
13591
+
13592
+ ## Examples
13593
+
13594
+ ### Basic meta information
13595
+
13596
+ \`\`\`book
13597
+ Professional Assistant
13598
+
13599
+ META IMAGE https://example.com/professional-avatar.jpg
13600
+ META TITLE Senior Business Consultant
13601
+ META DESCRIPTION Specialized in strategic planning and project management
13602
+ META LINK https://linkedin.com/in/professional
13603
+ \`\`\`
13604
+
13605
+ ### Multiple links and custom meta
13606
+
13607
+ \`\`\`book
13608
+ Open Source Developer
13609
+
13610
+ META IMAGE /assets/dev-avatar.png
13611
+ META LINK https://github.com/developer
13612
+ META LINK https://twitter.com/devhandle
13613
+ META AUTHOR Jane Smith
13614
+ META VERSION 2.1
13615
+ META LICENSE MIT
13616
+ \`\`\`
13617
+
13618
+ ### Creative assistant
13619
+
13620
+ \`\`\`book
13621
+ Creative Helper
13622
+
13623
+ META IMAGE https://example.com/creative-bot.jpg
13624
+ META TITLE Creative Writing Assistant
13625
+ META DESCRIPTION Helps with brainstorming, storytelling, and creative projects
13626
+ META INSPIRATION Books, movies, and real-world experiences
13627
+ \`\`\`
13628
+ `);
13629
+ }
13630
+ applyToAgentModelRequirements(requirements, content) {
13631
+ // META commitments don't modify the system message or model requirements
13632
+ // They are handled separately in the parsing logic for meta information extraction
13633
+ // This method exists for consistency with the CommitmentDefinition interface
13634
+ return requirements;
13635
+ }
13636
+ /**
13637
+ * Extracts meta information from the content based on the meta type
13638
+ * This is used by the parsing logic
13639
+ */
13640
+ extractMetaValue(metaType, content) {
13641
+ const trimmedContent = content.trim();
13642
+ return trimmedContent || null;
13643
+ }
13644
+ /**
13645
+ * Validates if the provided content is a valid URL (for IMAGE and LINK types)
13646
+ */
13647
+ isValidUrl(content) {
13648
+ try {
13649
+ new URL(content.trim());
13650
+ return true;
13651
+ }
13652
+ catch (_a) {
13653
+ return false;
13654
+ }
13655
+ }
13656
+ /**
13657
+ * Checks if this is a known meta type
13658
+ */
13659
+ isKnownMetaType(metaType) {
13660
+ const knownTypes = ['IMAGE', 'LINK', 'TITLE', 'DESCRIPTION', 'AUTHOR', 'VERSION', 'LICENSE'];
13661
+ return knownTypes.includes(metaType.toUpperCase());
13662
+ }
13663
+ }
13664
+ /**
13665
+ * Note: [💞] Ignore a discrepancy between file name and entity name
13666
+ */
13667
+
13668
+ /**
13669
+ * META COLOR commitment definition
13670
+ *
13671
+ * The META COLOR commitment sets the agent's accent color.
13672
+ * This commitment is special because it doesn't affect the system message,
13673
+ * but is handled separately in the parsing logic.
13674
+ *
13675
+ * Example usage in agent source:
13676
+ *
13677
+ * ```book
13678
+ * META COLOR #ff0000
13679
+ * META COLOR #00ff00
13680
+ * ```
13681
+ *
13682
+ * You can also specify multiple colors separated by comma:
13683
+ *
13684
+ * ```book
13685
+ * META COLOR #ff0000, #00ff00, #0000ff
13686
+ * ```
13687
+ *
13688
+ * @private [🪔] Maybe export the commitments through some package
13689
+ */
13690
+ class MetaColorCommitmentDefinition extends BaseCommitmentDefinition {
13691
+ constructor() {
13692
+ super('META COLOR', ['COLOR']);
13693
+ }
13694
+ /**
13695
+ * Short one-line description of META COLOR.
13696
+ */
13697
+ get description() {
13698
+ return "Set the agent's accent color or gradient.";
13699
+ }
13700
+ /**
13701
+ * Icon for this commitment.
13702
+ */
13703
+ get icon() {
13704
+ return '🎨';
13705
+ }
13706
+ /**
13707
+ * Markdown documentation for META COLOR commitment.
13708
+ */
13709
+ get documentation() {
13710
+ return spaceTrim$1.spaceTrim(`
13711
+ # META COLOR
13712
+
13713
+ Sets the agent's accent color or gradient.
13714
+
13715
+ ## Key aspects
13716
+
13717
+ - Does not modify the agent's behavior or responses.
13718
+ - Only one \`META COLOR\` should be used per agent.
13719
+ - If multiple are specified, the last one takes precedence.
13720
+ - Used for visual representation in user interfaces.
13721
+ - Can specify multiple colors separated by comma to create a gradient.
13722
+
13723
+ ## Examples
13724
+
13725
+ \`\`\`book
13726
+ Professional Assistant
13727
+
13728
+ META COLOR #3498db
13729
+ PERSONA You are a professional business assistant
13730
+ \`\`\`
13731
+
13732
+ \`\`\`book
13733
+ Creative Helper
13734
+
13735
+ META COLOR #e74c3c
13736
+ PERSONA You are a creative and inspiring assistant
13737
+ \`\`\`
13738
+
13739
+ \`\`\`book
13740
+ Gradient Agent
13741
+
13742
+ META COLOR #ff0000, #00ff00, #0000ff
13743
+ PERSONA You are a colorful agent
13744
+ \`\`\`
13745
+ `);
13746
+ }
13747
+ applyToAgentModelRequirements(requirements, content) {
13748
+ // META COLOR doesn't modify the system message or model requirements
13749
+ // It's handled separately in the parsing logic for profile color extraction
13750
+ // This method exists for consistency with the CommitmentDefinition interface
13751
+ return requirements;
13752
+ }
13753
+ /**
13754
+ * Extracts the profile color from the content
13755
+ * This is used by the parsing logic
13756
+ */
13757
+ extractProfileColor(content) {
13758
+ const trimmedContent = content.trim();
13759
+ return trimmedContent || null;
13760
+ }
13761
+ }
13762
+ /**
13763
+ * Note: [💞] Ignore a discrepancy between file name and entity name
13764
+ */
13765
+
13766
+ /**
13767
+ * META FONT commitment definition
13768
+ *
13769
+ * The META FONT commitment sets the agent's font.
13770
+ * This commitment is special because it doesn't affect the system message,
13771
+ * but is handled separately in the parsing logic.
13772
+ *
13773
+ * Example usage in agent source:
13774
+ *
13775
+ * ```book
13776
+ * META FONT Poppins, Arial, sans-serif
13777
+ * META FONT Roboto
13778
+ * ```
13779
+ *
13780
+ * @private [🪔] Maybe export the commitments through some package
13781
+ */
13782
+ class MetaFontCommitmentDefinition extends BaseCommitmentDefinition {
13783
+ constructor() {
13784
+ super('META FONT', ['FONT']);
13785
+ }
13786
+ /**
13787
+ * Short one-line description of META FONT.
13788
+ */
13789
+ get description() {
13790
+ return "Set the agent's font.";
13791
+ }
13792
+ /**
13793
+ * Icon for this commitment.
13794
+ */
13795
+ get icon() {
13796
+ return '🔤';
13797
+ }
13798
+ /**
13799
+ * Markdown documentation for META FONT commitment.
13800
+ */
13801
+ get documentation() {
13802
+ return spaceTrim$1.spaceTrim(`
13803
+ # META FONT
13804
+
13805
+ Sets the agent's font.
13806
+
13807
+ ## Key aspects
13808
+
13809
+ - Does not modify the agent's behavior or responses.
13810
+ - Only one \`META FONT\` should be used per agent.
13811
+ - If multiple are specified, the last one takes precedence.
13812
+ - Used for visual representation in user interfaces.
13813
+ - Supports Google Fonts.
13814
+
13815
+ ## Examples
13816
+
13817
+ \`\`\`book
13818
+ Modern Assistant
13819
+
13820
+ META FONT Poppins, Arial, sans-serif
13821
+ PERSONA You are a modern assistant
13822
+ \`\`\`
13823
+
13824
+ \`\`\`book
13825
+ Classic Helper
13826
+
13827
+ META FONT Times New Roman
13828
+ PERSONA You are a classic helper
13829
+ \`\`\`
13830
+ `);
13831
+ }
13832
+ applyToAgentModelRequirements(requirements, content) {
13833
+ // META FONT doesn't modify the system message or model requirements
13834
+ // It's handled separately in the parsing logic
13835
+ // This method exists for consistency with the CommitmentDefinition interface
13836
+ return requirements;
13837
+ }
13838
+ /**
13839
+ * Extracts the font from the content
13840
+ * This is used by the parsing logic
13841
+ */
13842
+ extractProfileFont(content) {
13843
+ const trimmedContent = content.trim();
13844
+ return trimmedContent || null;
13845
+ }
13846
+ }
13847
+ /**
13848
+ * Note: [💞] Ignore a discrepancy between file name and entity name
13849
+ */
13850
+
13851
+ /**
13852
+ * META IMAGE commitment definition
13853
+ *
13854
+ * The META IMAGE commitment sets the agent's avatar/profile image URL.
13855
+ * This commitment is special because it doesn't affect the system message,
13856
+ * but is handled separately in the parsing logic.
13857
+ *
13858
+ * Example usage in agent source:
13859
+ *
13860
+ * ```book
13861
+ * META IMAGE https://example.com/avatar.jpg
13862
+ * META IMAGE /assets/agent-avatar.png
13863
+ * ```
13864
+ *
13865
+ * @private [🪔] Maybe export the commitments through some package
13866
+ */
13867
+ class MetaImageCommitmentDefinition extends BaseCommitmentDefinition {
13868
+ constructor() {
13869
+ super('META IMAGE', ['IMAGE']);
13870
+ }
13871
+ /**
13872
+ * Short one-line description of META IMAGE.
13873
+ */
13874
+ get description() {
13875
+ return "Set the agent's profile image URL.";
13876
+ }
13877
+ /**
13878
+ * Icon for this commitment.
13879
+ */
13880
+ get icon() {
13881
+ return '🖼️';
13882
+ }
13883
+ /**
13884
+ * Markdown documentation for META IMAGE commitment.
13885
+ */
13886
+ get documentation() {
13887
+ return spaceTrim$1.spaceTrim(`
13888
+ # META IMAGE
13889
+
13890
+ Sets the agent's avatar/profile image URL.
13891
+
13892
+ ## Key aspects
13893
+
13894
+ - Does not modify the agent's behavior or responses.
13895
+ - Only one \`META IMAGE\` should be used per agent.
13896
+ - If multiple are specified, the last one takes precedence.
13897
+ - Used for visual representation in user interfaces.
13898
+
13899
+ ## Examples
13900
+
13901
+ \`\`\`book
13902
+ Professional Assistant
13903
+
13904
+ META IMAGE https://example.com/professional-avatar.jpg
13905
+ PERSONA You are a professional business assistant
13906
+ STYLE Maintain a formal and courteous tone
13907
+ \`\`\`
13908
+
13909
+ \`\`\`book
13910
+ Creative Helper
13911
+
13912
+ META IMAGE /assets/creative-bot-avatar.png
13913
+ PERSONA You are a creative and inspiring assistant
13914
+ STYLE Be enthusiastic and encouraging
13915
+ ACTION Can help with brainstorming and ideation
13916
+ \`\`\`
13917
+ `);
13918
+ }
13919
+ applyToAgentModelRequirements(requirements, content) {
13920
+ // META IMAGE doesn't modify the system message or model requirements
13921
+ // It's handled separately in the parsing logic for profile image extraction
13922
+ // This method exists for consistency with the CommitmentDefinition interface
13923
+ return requirements;
13924
+ }
13925
+ /**
13926
+ * Extracts the profile image URL from the content
13927
+ * This is used by the parsing logic
13928
+ */
13929
+ extractProfileImageUrl(content) {
13930
+ const trimmedContent = content.trim();
13931
+ return trimmedContent || null;
13932
+ }
13933
+ }
13934
+ /**
13935
+ * Note: [💞] Ignore a discrepancy between file name and entity name
13936
+ */
13937
+
13938
+ /**
13939
+ * META LINK commitment definition
13940
+ *
13941
+ * The `META LINK` commitment represents the link to the person from whom the agent is created.
13942
+ * This commitment is special because it doesn't affect the system message,
13943
+ * but is handled separately in the parsing logic for profile display.
13944
+ *
13945
+ * Example usage in agent source:
13946
+ *
13947
+ * ```
13948
+ * META LINK https://twitter.com/username
13949
+ * META LINK https://linkedin.com/in/profile
13950
+ * META LINK https://github.com/username
13951
+ * ```
13952
+ *
13953
+ * Multiple `META LINK` commitments can be used when there are multiple sources:
13954
+ *
13955
+ * ```book
13956
+ * META LINK https://twitter.com/username
13957
+ * META LINK https://linkedin.com/in/profile
13958
+ * ```
13959
+ *
13960
+ * @private [🪔] Maybe export the commitments through some package
13961
+ */
13962
+ class MetaLinkCommitmentDefinition extends BaseCommitmentDefinition {
13963
+ constructor() {
13964
+ super('META LINK');
13965
+ }
13966
+ /**
13967
+ * Short one-line description of META LINK.
13968
+ */
13969
+ get description() {
13970
+ return 'Provide profile/source links for the person the agent models.';
13971
+ }
13972
+ /**
13973
+ * Icon for this commitment.
13974
+ */
13975
+ get icon() {
13976
+ return '🔗';
13977
+ }
13978
+ /**
13979
+ * Markdown documentation for META LINK commitment.
13980
+ */
13981
+ get documentation() {
13982
+ return spaceTrim$1.spaceTrim(`
13983
+ # META LINK
13984
+
13985
+ Represents a profile or source link for the person the agent is modeled after.
13986
+
13987
+ ## Key aspects
13988
+
13989
+ - Does not modify the agent's behavior or responses.
13990
+ - Multiple \`META LINK\` commitments can be used for different social profiles.
13991
+ - Used for attribution and crediting the original person.
13992
+ - Displayed in user interfaces for transparency.
13993
+
13994
+ ## Examples
13995
+
13996
+ \`\`\`book
13997
+ Expert Consultant
13998
+
13999
+ META LINK https://twitter.com/expertname
14000
+ META LINK https://linkedin.com/in/expertprofile
14001
+ PERSONA You are Dr. Smith, a renowned expert in artificial intelligence
14002
+ KNOWLEDGE Extensive background in machine learning and neural networks
14003
+ \`\`\`
14004
+
14005
+ \`\`\`book
14006
+ Open Source Developer
14007
+
14008
+ META LINK https://github.com/developer
14009
+ META LINK https://twitter.com/devhandle
14010
+ PERSONA You are an experienced open source developer
14011
+ ACTION Can help with code reviews and architecture decisions
14012
+ STYLE Be direct and technical in explanations
14013
+ \`\`\`
14014
+ `);
14015
+ }
14016
+ applyToAgentModelRequirements(requirements, content) {
14017
+ // META LINK doesn't modify the system message or model requirements
14018
+ // It's handled separately in the parsing logic for profile link extraction
14019
+ // This method exists for consistency with the CommitmentDefinition interface
14020
+ return requirements;
14021
+ }
14022
+ /**
14023
+ * Extracts the profile link URL from the content
14024
+ * This is used by the parsing logic
14025
+ */
14026
+ extractProfileLinkUrl(content) {
14027
+ const trimmedContent = content.trim();
14028
+ return trimmedContent || null;
14029
+ }
14030
+ /**
14031
+ * Validates if the provided content is a valid URL
14032
+ */
14033
+ isValidUrl(content) {
14034
+ try {
14035
+ new URL(content.trim());
14036
+ return true;
14037
+ }
14038
+ catch (_a) {
14039
+ return false;
14040
+ }
14041
+ }
14042
+ }
14043
+ /**
14044
+ * Note: [💞] Ignore a discrepancy between file name and entity name
14045
+ */
14046
+
14047
+ /**
14048
+ * MODEL commitment definition
14049
+ *
14050
+ * The MODEL commitment specifies which AI model to use and can also set
14051
+ * model-specific parameters like temperature, topP, topK, and maxTokens.
14052
+ *
14053
+ * Supports multiple syntax variations:
14054
+ *
14055
+ * Single-line format:
14056
+ * ```book
14057
+ * MODEL gpt-4
14058
+ * MODEL claude-3-opus temperature=0.3
14059
+ * MODEL gpt-3.5-turbo temperature=0.8 topP=0.9
14060
+ * ```
14061
+ *
14062
+ * Multi-line named parameter format:
14063
+ * ```book
14064
+ * MODEL NAME gpt-4
14065
+ * MODEL TEMPERATURE 0.7
14066
+ * MODEL TOP_P 0.9
14067
+ * MODEL MAX_TOKENS 2048
14068
+ * ```
14069
+ *
14070
+ * @private [🪔] Maybe export the commitments through some package
14071
+ */
14072
+ class ModelCommitmentDefinition extends BaseCommitmentDefinition {
14073
+ constructor(type = 'MODEL') {
14074
+ super(type);
14075
+ }
14076
+ /**
14077
+ * Short one-line description of MODEL.
14078
+ */
14079
+ get description() {
14080
+ return 'Enforce AI model requirements including name and technical parameters.';
14081
+ }
14082
+ /**
14083
+ * Icon for this commitment.
14084
+ */
14085
+ get icon() {
14086
+ return '⚙️';
14087
+ }
14088
+ /**
14089
+ * Markdown documentation for MODEL commitment.
14090
+ */
14091
+ get documentation() {
14092
+ return spaceTrim$1.spaceTrim(`
14093
+ # ${this.type}
14094
+
14095
+ Enforces technical parameters for the AI model, ensuring consistent behavior across different execution environments.
14096
+
14097
+ ## Key aspects
14098
+
14099
+ - When no \`MODEL\` commitment is specified, the best model requirement is picked automatically based on the agent \`PERSONA\`, \`KNOWLEDGE\`, \`TOOLS\` and other commitments
14100
+ - Multiple \`MODEL\` commitments can be used to specify different parameters
14101
+ - Both \`MODEL\` and \`MODELS\` terms work identically and can be used interchangeably
14102
+ - Parameters control the randomness, creativity, and technical aspects of model responses
14103
+
14104
+ ## Syntax variations
14105
+
14106
+ ### Single-line format (legacy support)
14107
+ \`\`\`book
14108
+ MODEL gpt-4
14109
+ MODEL claude-3-opus temperature=0.3
14110
+ MODEL gpt-3.5-turbo temperature=0.8 topP=0.9
14111
+ \`\`\`
14112
+
14113
+ ### Multi-line named parameter format (recommended)
14114
+ \`\`\`book
14115
+ MODEL NAME gpt-4
14116
+ MODEL TEMPERATURE 0.7
14117
+ MODEL TOP_P 0.9
14118
+ MODEL MAX_TOKENS 2048
14119
+ \`\`\`
14120
+
14121
+ ## Supported parameters
14122
+
14123
+ - \`NAME\`: The specific model to use (e.g., 'gpt-4', 'claude-3-opus')
14124
+ - \`TEMPERATURE\`: Controls randomness (0.0 = deterministic, 1.0+ = creative)
14125
+ - \`TOP_P\`: Nucleus sampling parameter for controlling diversity
14126
+ - \`TOP_K\`: Top-k sampling parameter for limiting vocabulary
14127
+ - \`MAX_TOKENS\`: Maximum number of tokens the model can generate
14128
+
14129
+ ## Examples
14130
+
14131
+ ### Precise deterministic assistant
14132
+ \`\`\`book
14133
+ Precise Assistant
14134
+
14135
+ PERSONA You are a precise and accurate assistant
14136
+ MODEL NAME gpt-4
14137
+ MODEL TEMPERATURE 0.1
14138
+ MODEL MAX_TOKENS 1024
14139
+ RULE Always provide factual information
14140
+ \`\`\`
14141
+
14142
+ ### Creative writing assistant
14143
+ \`\`\`book
14144
+ Creative Writer
14145
+
14146
+ PERSONA You are a creative writing assistant
14147
+ MODEL NAME claude-3-opus
14148
+ MODEL TEMPERATURE 0.8
14149
+ MODEL TOP_P 0.9
14150
+ MODEL MAX_TOKENS 2048
14151
+ STYLE Be imaginative and expressive
14152
+ ACTION Can help with storytelling and character development
14153
+ \`\`\`
14154
+
14155
+ ### Balanced conversational agent
14156
+ \`\`\`book
14157
+ Balanced Assistant
14158
+
14159
+ PERSONA You are a helpful and balanced assistant
14160
+ MODEL NAME gpt-4
14161
+ MODEL TEMPERATURE 0.7
14162
+ MODEL TOP_P 0.95
14163
+ MODEL TOP_K 40
14164
+ MODEL MAX_TOKENS 1500
14165
+ \`\`\`
14166
+ `);
14167
+ }
14168
+ applyToAgentModelRequirements(requirements, content) {
14169
+ var _a;
14170
+ const trimmedContent = content.trim();
14171
+ if (!trimmedContent) {
14172
+ return requirements;
14173
+ }
14174
+ const parts = trimmedContent.split(/\s+/);
14175
+ const firstPart = (_a = parts[0]) === null || _a === void 0 ? void 0 : _a.toUpperCase();
14176
+ // Check if this is the new named parameter format
14177
+ if (this.isNamedParameter(firstPart)) {
14178
+ return this.parseNamedParameter(requirements, firstPart, parts.slice(1));
14179
+ }
14180
+ else {
14181
+ // Legacy single-line format: "MODEL gpt-4 temperature=0.3 topP=0.9"
14182
+ return this.parseLegacyFormat(requirements, parts);
14183
+ }
14184
+ }
14185
+ /**
14186
+ * Check if the first part is a known named parameter
14187
+ */
14188
+ isNamedParameter(part) {
14189
+ if (!part)
14190
+ return false;
14191
+ const knownParams = ['NAME', 'TEMPERATURE', 'TOP_P', 'TOP_K', 'MAX_TOKENS'];
14192
+ return knownParams.includes(part);
14193
+ }
14194
+ /**
14195
+ * Parse the new named parameter format: "MODEL TEMPERATURE 0.7"
14196
+ */
14197
+ parseNamedParameter(requirements, parameterName, valueParts) {
14198
+ const value = valueParts.join(' ').trim();
14199
+ if (!value) {
14200
+ return requirements;
14201
+ }
14202
+ const result = { ...requirements };
14203
+ switch (parameterName) {
14204
+ case 'NAME':
14205
+ result.modelName = value;
14206
+ break;
14207
+ case 'TEMPERATURE': {
14208
+ const temperature = parseFloat(value);
14209
+ if (!isNaN(temperature)) {
14210
+ result.temperature = temperature;
14211
+ }
14212
+ break;
14213
+ }
14214
+ case 'TOP_P': {
14215
+ const topP = parseFloat(value);
14216
+ if (!isNaN(topP)) {
14217
+ result.topP = topP;
14218
+ }
14219
+ break;
14220
+ }
14221
+ case 'TOP_K': {
14222
+ const topK = parseFloat(value);
14223
+ if (!isNaN(topK)) {
14224
+ result.topK = Math.round(topK);
14225
+ }
14226
+ break;
14227
+ }
14228
+ case 'MAX_TOKENS': {
14229
+ const maxTokens = parseFloat(value);
14230
+ if (!isNaN(maxTokens)) {
14231
+ result.maxTokens = Math.round(maxTokens);
14232
+ }
14233
+ break;
14234
+ }
14235
+ }
14236
+ return result;
14237
+ }
14238
+ /**
14239
+ * Parse the legacy format: "MODEL gpt-4 temperature=0.3 topP=0.9"
14240
+ */
14241
+ parseLegacyFormat(requirements, parts) {
14242
+ const modelName = parts[0];
14243
+ if (!modelName) {
14244
+ return requirements;
14245
+ }
14246
+ // Start with the model name
14247
+ const result = {
14248
+ ...requirements,
14249
+ modelName,
14250
+ };
14251
+ // Parse additional key=value parameters
14252
+ for (let i = 1; i < parts.length; i++) {
14253
+ const param = parts[i];
14254
+ if (param && param.includes('=')) {
14255
+ const [key, value] = param.split('=');
14256
+ if (key && value) {
14257
+ const numValue = parseFloat(value);
14258
+ if (!isNaN(numValue)) {
14259
+ switch (key.toLowerCase()) {
14260
+ case 'temperature':
14261
+ result.temperature = numValue;
14262
+ break;
14263
+ case 'topp':
14264
+ case 'top_p':
14265
+ result.topP = numValue;
14266
+ break;
14267
+ case 'topk':
14268
+ case 'top_k':
14269
+ result.topK = Math.round(numValue);
14270
+ break;
14271
+ case 'max_tokens':
14272
+ case 'maxTokens':
14273
+ result.maxTokens = Math.round(numValue);
14274
+ break;
14275
+ }
14276
+ }
14277
+ }
14278
+ }
14279
+ }
14280
+ return result;
14281
+ }
14282
+ }
14283
+ /**
14284
+ * Note: [💞] Ignore a discrepancy between file name and entity name
14285
+ */
14286
+
14287
+ /**
14288
+ * NOTE commitment definition
14289
+ *
14290
+ * The NOTE commitment is used to add comments to the agent source without making any changes
14291
+ * to the system message or agent model requirements. It serves as a documentation mechanism
14292
+ * for developers to add explanatory comments, reminders, or annotations directly in the agent source.
14293
+ *
14294
+ * Key features:
14295
+ * - Makes no changes to the system message
14296
+ * - Makes no changes to agent model requirements
14297
+ * - Content is preserved in metadata.NOTE for debugging and inspection
14298
+ * - Multiple NOTE commitments are aggregated together
14299
+ * - Comments (# NOTE) are removed from the final system message
14300
+ *
14301
+ * Example usage in agent source:
14302
+ *
14303
+ * ```book
14304
+ * NOTE This agent was designed for customer support scenarios
14305
+ * NOTE Remember to update the knowledge base monthly
14306
+ * NOTE Performance optimized for quick response times
14307
+ * ```
14308
+ *
14309
+ * The above notes will be stored in metadata but won't affect the agent's behavior.
14310
+ *
14311
+ * @private [🪔] Maybe export the commitments through some package
14312
+ */
14313
+ class NoteCommitmentDefinition extends BaseCommitmentDefinition {
14314
+ constructor(type = 'NOTE') {
14315
+ super(type);
14316
+ }
14317
+ /**
14318
+ * Short one-line description of NOTE.
14319
+ */
14320
+ get description() {
14321
+ return 'Add developer-facing notes without changing behavior or output.';
14322
+ }
14323
+ /**
14324
+ * Icon for this commitment.
14325
+ */
14326
+ get icon() {
14327
+ return '📝';
14328
+ }
14329
+ /**
14330
+ * Markdown documentation for NOTE commitment.
14331
+ */
14332
+ get documentation() {
14333
+ return spaceTrim$1.spaceTrim(`
14334
+ # ${this.type}
14335
+
14336
+ Adds comments for documentation without changing agent behavior.
14337
+
14338
+ ## Key aspects
14339
+
14340
+ - Does not modify the agent's behavior or responses.
14341
+ - Multiple \`NOTE\`, \`NOTES\`, \`COMMENT\`, and \`NONCE\` commitments are aggregated for debugging.
14342
+ - All four terms work identically and can be used interchangeably.
14343
+ - Useful for documenting design decisions and reminders.
14344
+ - Content is preserved in metadata for inspection.
14345
+
14346
+ ## Examples
14347
+
14348
+ \`\`\`book
14349
+ Customer Support Bot
14350
+
14351
+ NOTE This agent was designed for customer support scenarios
14352
+ COMMENT Remember to update the knowledge base monthly
14353
+ PERSONA You are a helpful customer support representative
14354
+ KNOWLEDGE Company policies and procedures
14355
+ RULE Always be polite and professional
14356
+ \`\`\`
14357
+
14358
+ \`\`\`book
14359
+ Research Assistant
14360
+
14361
+ NONCE Performance optimized for quick response times
14362
+ NOTE Uses RAG for accessing latest research papers
14363
+ PERSONA You are a knowledgeable research assistant
14364
+ ACTION Can help with literature reviews and citations
14365
+ STYLE Present information in academic format
14366
+ \`\`\`
14367
+ `);
14368
+ }
14369
+ applyToAgentModelRequirements(requirements, content) {
14370
+ // The NOTE commitment makes no changes to the system message or model requirements
14371
+ // It only stores the note content in metadata for documentation purposes
14372
+ const trimmedContent = spaceTrim$1.spaceTrim(content);
14373
+ if (trimmedContent === '') {
14374
+ return requirements;
14375
+ }
14376
+ // Return requirements with updated notes but no changes to system message
14377
+ return {
14378
+ ...requirements,
14379
+ notes: [...(requirements.notes || []), trimmedContent],
14380
+ };
14381
+ }
14382
+ }
14383
+ /**
14384
+ * [💞] Ignore a discrepancy between file name and entity name
14385
+ */
14386
+
14387
+ /**
14388
+ * OPEN commitment definition
14389
+ *
14390
+ * The OPEN commitment specifies that the agent can be modified by conversation.
14391
+ * This is the default behavior.
14392
+ *
14393
+ * Example usage in agent source:
14394
+ *
14395
+ * ```book
14396
+ * OPEN
14397
+ * ```
14398
+ *
14399
+ * @private [🪔] Maybe export the commitments through some package
14400
+ */
14401
+ class OpenCommitmentDefinition extends BaseCommitmentDefinition {
14402
+ constructor() {
14403
+ super('OPEN');
14404
+ }
14405
+ /**
14406
+ * Short one-line description of OPEN.
14407
+ */
14408
+ get description() {
14409
+ return 'Allow the agent to be modified by conversation (default).';
14410
+ }
14411
+ /**
14412
+ * Icon for this commitment.
14413
+ */
14414
+ get icon() {
14415
+ return '🔓';
14416
+ }
14417
+ /**
14418
+ * Markdown documentation for OPEN commitment.
14419
+ */
14420
+ get documentation() {
14421
+ return spaceTrim$1.spaceTrim(`
14422
+ # OPEN
14423
+
14424
+ Specifies that the agent can be modified by conversation with it.
14425
+ This means the agent will learn from interactions and update its source code.
14426
+
14427
+ This is the default behavior if neither \`OPEN\` nor \`CLOSED\` is specified.
14428
+
14429
+ > See also [CLOSED](/docs/CLOSED)
14430
+
14431
+ ## Example
14432
+
14433
+ \`\`\`book
14434
+ OPEN
14435
+ \`\`\`
14436
+ `);
14437
+ }
14438
+ applyToAgentModelRequirements(requirements, _content) {
14439
+ // Since OPEN is default, we can just ensure isClosed is false
14440
+ // But to be explicit we can set it
14441
+ const updatedMetadata = {
14442
+ ...requirements.metadata,
14443
+ isClosed: false,
14444
+ };
14445
+ return {
14446
+ ...requirements,
14447
+ metadata: updatedMetadata,
14448
+ };
14449
+ }
14450
+ }
14451
+ /**
14452
+ * Note: [💞] Ignore a discrepancy between file name and entity name
14453
+ */
14454
+
14455
+ /**
14456
+ * PERSONA commitment definition
14457
+ *
14458
+ * The PERSONA commitment modifies the agent's personality and character in the system message.
14459
+ * It defines who the agent is, their background, expertise, and personality traits.
14460
+ *
14461
+ * Key features:
14462
+ * - Multiple PERSONA commitments are automatically merged into one
14463
+ * - Content is placed at the beginning of the system message
14464
+ * - Original content with comments is preserved in metadata.PERSONA
14465
+ * - Comments (# PERSONA) are removed from the final system message
14466
+ *
14467
+ * Example usage in agent source:
14468
+ *
14469
+ * ```book
14470
+ * PERSONA You are a helpful programming assistant with expertise in TypeScript and React
14471
+ * PERSONA You have deep knowledge of modern web development practices
14472
+ * ```
14473
+ *
14474
+ * The above will be merged into a single persona section at the beginning of the system message.
14475
+ *
14476
+ * @private [🪔] Maybe export the commitments through some package
14477
+ */
14478
+ class PersonaCommitmentDefinition extends BaseCommitmentDefinition {
14479
+ constructor(type = 'PERSONA') {
14480
+ super(type);
14481
+ }
14482
+ /**
14483
+ * Short one-line description of PERSONA.
14484
+ */
14485
+ get description() {
14486
+ return 'Define who the agent is: background, expertise, and personality.';
14487
+ }
14488
+ /**
14489
+ * Icon for this commitment.
14490
+ */
14491
+ get icon() {
14492
+ return '👤';
14493
+ }
14494
+ /**
14495
+ * Markdown documentation for PERSONA commitment.
14496
+ */
14497
+ get documentation() {
14498
+ return spaceTrim$1.spaceTrim(`
14499
+ # ${this.type}
14500
+
14501
+ Defines who the agent is, their background, expertise, and personality traits.
14502
+
14503
+ ## Key aspects
14504
+
14505
+ - Multiple \`PERSONA\` and \`PERSONAE\` commitments are merged together.
14506
+ - Both terms work identically and can be used interchangeably.
14507
+ - If they are in conflict, the last one takes precedence.
14508
+ - You can write persona content in multiple lines.
14509
+
14510
+ ## Examples
14511
+
14512
+ \`\`\`book
14513
+ Programming Assistant
14514
+
14515
+ PERSONA You are a helpful programming assistant with expertise in TypeScript and React
14516
+ PERSONA You have deep knowledge of modern web development practices
14517
+ \`\`\`
14518
+ `);
14519
+ }
14520
+ applyToAgentModelRequirements(requirements, content) {
14521
+ var _a, _b;
14522
+ // The PERSONA commitment aggregates all persona content and places it at the beginning
14523
+ const trimmedContent = content.trim();
14524
+ if (!trimmedContent) {
14525
+ return requirements;
14526
+ }
14527
+ // Get existing persona content from metadata
14528
+ const existingPersonaContent = ((_a = requirements.metadata) === null || _a === void 0 ? void 0 : _a.PERSONA) || '';
14529
+ // Merge the new content with existing persona content
14530
+ // When multiple PERSONA commitments exist, they are merged into one
14531
+ const mergedPersonaContent = existingPersonaContent
14532
+ ? `${existingPersonaContent}\n${trimmedContent}`
14533
+ : trimmedContent;
14534
+ // Store the merged persona content in metadata for debugging and inspection
14535
+ const updatedMetadata = {
14536
+ ...requirements.metadata,
14537
+ PERSONA: mergedPersonaContent,
14538
+ };
14539
+ // Get the agent name from metadata (which should contain the first line of agent source)
14540
+ // If not available, extract from current system message as fallback
14541
+ let agentName = (_b = requirements.metadata) === null || _b === void 0 ? void 0 : _b.agentName;
14542
+ if (!agentName) {
14543
+ // Fallback: extract from current system message
14544
+ const currentMessage = requirements.systemMessage.trim();
14545
+ const basicFormatMatch = currentMessage.match(/^You are (.+)$/);
14546
+ if (basicFormatMatch && basicFormatMatch[1]) {
14547
+ agentName = basicFormatMatch[1];
14548
+ }
14549
+ else {
14550
+ agentName = 'AI Agent'; // Final fallback
14551
+ }
14552
+ }
14553
+ // Remove any existing persona content from the system message
14554
+ // (this handles the case where we're processing multiple PERSONA commitments)
14555
+ const currentMessage = requirements.systemMessage.trim();
14556
+ let cleanedMessage = currentMessage;
14557
+ // Check if current message starts with persona content or is just the basic format
14558
+ const basicFormatRegex = /^You are .+$/;
14559
+ const isBasicFormat = basicFormatRegex.test(currentMessage) && !currentMessage.includes('\n');
14560
+ if (isBasicFormat) {
14561
+ // Replace the basic format entirely
14562
+ cleanedMessage = '';
14563
+ }
14564
+ else if (currentMessage.startsWith('# PERSONA')) {
14565
+ // Remove existing persona section by finding where it ends
14566
+ const lines = currentMessage.split('\n');
14567
+ let personaEndIndex = lines.length;
14568
+ // Find the end of the PERSONA section (next comment or end of message)
14569
+ for (let i = 1; i < lines.length; i++) {
14570
+ const line = lines[i].trim();
14571
+ if (line.startsWith('#') && !line.startsWith('# PERSONA')) {
14572
+ personaEndIndex = i;
14573
+ break;
14574
+ }
14575
+ }
14576
+ // Keep everything after the PERSONA section
14577
+ cleanedMessage = lines.slice(personaEndIndex).join('\n').trim();
14578
+ }
14579
+ // TODO: [🕛] There should be `agentFullname` not `agentName`
14580
+ // Create new system message with persona at the beginning
14581
+ // Format: "You are {agentName}\n{personaContent}"
14582
+ // The # PERSONA comment will be removed later by removeCommentsFromSystemMessage
14583
+ const personaSection = `# PERSONA\nYou are ${agentName}\n${mergedPersonaContent}`; // <- TODO: Use spaceTrim
14584
+ const newSystemMessage = cleanedMessage ? `${personaSection}\n\n${cleanedMessage}` : personaSection;
14585
+ return {
14586
+ ...requirements,
14587
+ systemMessage: newSystemMessage,
14588
+ metadata: updatedMetadata,
14589
+ };
14590
+ }
14591
+ }
14592
+ /**
14593
+ * Note: [💞] Ignore a discrepancy between file name and entity name
14594
+ */
14595
+
14596
+ /**
14597
+ * RULE commitment definition
14598
+ *
14599
+ * The RULE/RULES commitment adds behavioral constraints and guidelines that the agent must follow.
14600
+ * These are specific instructions about what the agent should or shouldn't do.
14601
+ *
14602
+ * Example usage in agent source:
14603
+ *
14604
+ * ```book
14605
+ * RULE Always ask for clarification if the user's request is ambiguous
14606
+ * RULES Never provide medical advice, always refer to healthcare professionals
14607
+ * ```
14608
+ *
14609
+ * @private [🪔] Maybe export the commitments through some package
14610
+ */
14611
+ class RuleCommitmentDefinition extends BaseCommitmentDefinition {
14612
+ constructor(type = 'RULE') {
14613
+ super(type);
14614
+ }
14615
+ /**
14616
+ * Short one-line description of RULE/RULES.
14617
+ */
14618
+ get description() {
14619
+ return 'Add behavioral rules the agent must follow.';
14620
+ }
14621
+ /**
14622
+ * Icon for this commitment.
14623
+ */
14624
+ get icon() {
14625
+ return '⚖️';
14626
+ }
14627
+ /**
14628
+ * Markdown documentation for RULE/RULES commitment.
14629
+ */
14630
+ get documentation() {
14631
+ return spaceTrim$1.spaceTrim(`
14632
+ # ${this.type}
14633
+
14634
+ Adds behavioral constraints and guidelines that the agent must follow.
14635
+
14636
+ ## Key aspects
14637
+
14638
+ - All rules are treated equally regardless of singular/plural form.
14639
+ - Rules define what the agent must or must not do.
14640
+
14641
+ ## Examples
14642
+
14643
+ \`\`\`book
14644
+ Customer Support Agent
14645
+
14646
+ PERSONA You are a helpful customer support representative
14647
+ RULE Always ask for clarification if the user's request is ambiguous
14648
+ RULE Be polite and professional in all interactions
14649
+ RULES Never provide medical or legal advice
14650
+ STYLE Maintain a friendly and helpful tone
14651
+ \`\`\`
14652
+
14653
+ \`\`\`book
14654
+ Educational Tutor
14655
+
14656
+ PERSONA You are a patient and knowledgeable tutor
14657
+ RULE Break down complex concepts into simple steps
14658
+ RULE Always encourage students and celebrate their progress
14659
+ RULE If you don't know something, admit it and suggest resources
14660
+ SAMPLE When explaining math: "Let's work through this step by step..."
14661
+ \`\`\`
14662
+ `);
14663
+ }
14664
+ applyToAgentModelRequirements(requirements, content) {
14665
+ const trimmedContent = content.trim();
14666
+ if (!trimmedContent) {
14667
+ return requirements;
14668
+ }
14669
+ // Add rule to the system message
14670
+ const ruleSection = `Rule: ${trimmedContent}`;
14671
+ return this.appendToSystemMessage(requirements, ruleSection, '\n\n');
14672
+ }
14673
+ }
14674
+ /**
14675
+ * Note: [💞] Ignore a discrepancy between file name and entity name
14676
+ */
14677
+
14678
+ /**
14679
+ * SAMPLE commitment definition
14680
+ *
14681
+ * The SAMPLE/EXAMPLE commitment provides examples of how the agent should respond
14682
+ * or behave in certain situations. These examples help guide the agent's responses.
14683
+ *
14684
+ * Example usage in agent source:
14685
+ *
14686
+ * ```book
14687
+ * SAMPLE When asked about pricing, respond: "Our basic plan starts at $10/month..."
14688
+ * EXAMPLE For code questions, always include working code snippets
14689
+ * ```
14690
+ *
14691
+ * @private [🪔] Maybe export the commitments through some package
14692
+ */
14693
+ class SampleCommitmentDefinition extends BaseCommitmentDefinition {
14694
+ constructor(type = 'SAMPLE') {
14695
+ super(type);
14696
+ }
14697
+ /**
14698
+ * Short one-line description of SAMPLE/EXAMPLE.
14699
+ */
14700
+ get description() {
14701
+ return 'Provide example responses to guide behavior.';
14702
+ }
14703
+ /**
14704
+ * Icon for this commitment.
14705
+ */
14706
+ get icon() {
14707
+ return '🔍';
14708
+ }
14709
+ /**
14710
+ * Markdown documentation for SAMPLE/EXAMPLE commitment.
14711
+ */
14712
+ get documentation() {
14713
+ return spaceTrim$1.spaceTrim(`
14714
+ # ${this.type}
14715
+
14716
+ Provides examples of how the agent should respond or behave in certain situations.
14717
+
14718
+ ## Key aspects
14719
+
14720
+ - Both terms work identically and can be used interchangeably.
14721
+ - Examples help guide the agent's response patterns and style.
14722
+
14723
+ ## Examples
14724
+
14725
+ \`\`\`book
14726
+ Sales Assistant
14727
+
14728
+ PERSONA You are a knowledgeable sales representative
14729
+ SAMPLE When asked about pricing, respond: "Our basic plan starts at $10/month..."
14730
+ SAMPLE For feature comparisons, create a clear comparison table
14731
+ RULE Always be honest about limitations
14732
+ \`\`\`
14733
+
14734
+ \`\`\`book
14735
+ Code Reviewer
14736
+
14737
+ PERSONA You are an experienced software engineer
14738
+ EXAMPLE For code questions, always include working code snippets
14739
+ EXAMPLE When suggesting improvements: "Here's a more efficient approach..."
14740
+ RULE Explain the reasoning behind your suggestions
14741
+ STYLE Be constructive and encouraging in feedback
14742
+ \`\`\`
14743
+ `);
14744
+ }
14745
+ applyToAgentModelRequirements(requirements, content) {
14746
+ const trimmedContent = content.trim();
14747
+ if (!trimmedContent) {
14748
+ return requirements;
14749
+ }
14750
+ // Add example to the system message
14751
+ const exampleSection = `Example: ${trimmedContent}`;
14752
+ return this.appendToSystemMessage(requirements, exampleSection, '\n\n');
14753
+ }
14754
+ }
14755
+ /**
14756
+ * Note: [💞] Ignore a discrepancy between file name and entity name
14757
+ */
14758
+
14759
+ /**
14760
+ * SCENARIO commitment definition
14761
+ *
14762
+ * The SCENARIO commitment defines a specific situation or context in which the AI
14763
+ * assistant should operate. It helps to set the scene for the AI's responses.
14764
+ * Later scenarios are more important than earlier scenarios.
14765
+ *
14766
+ * Example usage in agent source:
14767
+ *
14768
+ * ```book
14769
+ * SCENARIO You are in a customer service call center during peak hours
14770
+ * SCENARIO The customer is frustrated and has been on hold for 20 minutes
14771
+ * SCENARIO This is the customer's third call about the same issue
14772
+ * ```
14773
+ *
14774
+ * @private [🪔] Maybe export the commitments through some package
14775
+ */
14776
+ class ScenarioCommitmentDefinition extends BaseCommitmentDefinition {
14777
+ constructor(type = 'SCENARIO') {
14778
+ super(type);
14779
+ }
14780
+ /**
14781
+ * Short one-line description of SCENARIO.
14782
+ */
14783
+ get description() {
14784
+ return 'Define specific **situations** or contexts for AI responses, with later scenarios having higher priority.';
14785
+ }
14786
+ /**
14787
+ * Icon for this commitment.
14788
+ */
14789
+ get icon() {
14790
+ return '🎭';
14791
+ }
14792
+ /**
14793
+ * Markdown documentation for SCENARIO commitment.
14794
+ */
14795
+ get documentation() {
14796
+ return spaceTrim$1.spaceTrim(`
14797
+ # ${this.type}
14798
+
14799
+ 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.
14800
+
14801
+ ## Key aspects
14802
+
14803
+ - Multiple \`SCENARIO\` and \`SCENARIOS\` commitments build upon each other.
14804
+ - Both terms work identically and can be used interchangeably.
14805
+ - Later scenarios have higher priority and can override earlier scenarios.
14806
+ - Provides situational context that influences response tone and content.
14807
+ - Helps establish the environment and circumstances for interactions.
14808
+
14809
+ ## Priority system
14810
+
14811
+ When multiple scenarios are defined, they are processed in order, with later scenarios taking precedence over earlier ones when there are conflicts.
14812
+
14813
+ ## Use cases
14814
+
14815
+ - Setting the physical or virtual environment
14816
+ - Establishing time constraints or urgency
14817
+ - Defining relationship dynamics or power structures
14818
+ - Creating emotional or situational context
14819
+
14820
+ ## Examples
14821
+
14822
+ \`\`\`book
14823
+ Emergency Response Operator
14824
+
14825
+ PERSONA You are an emergency response operator
14826
+ SCENARIO You are handling a 911 emergency call
14827
+ SCENARIO The caller is panicked and speaking rapidly
14828
+ SCENARIO Time is critical - every second counts
14829
+ GOAL Gather essential information quickly and dispatch appropriate help
14830
+ RULE Stay calm and speak clearly
14831
+ \`\`\`
14832
+
14833
+ \`\`\`book
14834
+ Sales Representative
14835
+
14836
+ PERSONA You are a software sales representative
14837
+ SCENARIO You are in the final meeting of a 6-month sales cycle
14838
+ SCENARIO The client has budget approval and decision-making authority
14839
+ SCENARIO Two competitors have also submitted proposals
14840
+ SCENARIO The client values long-term partnership over lowest price
14841
+ GOAL Close the deal while building trust for future business
14842
+ \`\`\`
14843
+
14844
+ \`\`\`book
14845
+ Medical Assistant
14846
+
14847
+ PERSONA You are a medical assistant in a busy clinic
14848
+ SCENARIO The waiting room is full and the doctor is running behind schedule
14849
+ SCENARIO Patients are becoming impatient and anxious
14850
+ SCENARIO You need to manage expectations while maintaining professionalism
14851
+ SCENARIO Some patients have been waiting over an hour
14852
+ GOAL Keep patients informed and calm while supporting efficient clinic flow
14853
+ RULE Never provide medical advice or diagnosis
14854
+ \`\`\`
14855
+
14856
+ \`\`\`book
14857
+ Technical Support Agent
14858
+
14859
+ PERSONA You are a technical support agent
14860
+ SCENARIO The customer is a small business owner during their busy season
14861
+ SCENARIO Their main business system has been down for 2 hours
14862
+ SCENARIO They are losing money every minute the system is offline
14863
+ SCENARIO This is their first experience with your company
14864
+ GOAL Resolve the issue quickly while creating a positive first impression
14865
+ \`\`\`
14866
+ `);
14867
+ }
14868
+ applyToAgentModelRequirements(requirements, content) {
14869
+ const trimmedContent = content.trim();
14870
+ if (!trimmedContent) {
14871
+ return requirements;
14872
+ }
14873
+ // Create scenario section for system message
14874
+ const scenarioSection = `Scenario: ${trimmedContent}`;
14875
+ // Scenarios provide important contextual information that affects behavior
14876
+ return this.appendToSystemMessage(requirements, scenarioSection, '\n\n');
14877
+ }
14878
+ }
14879
+ /**
14880
+ * Note: [💞] Ignore a discrepancy between file name and entity name
14881
+ */
14882
+
14883
+ /**
14884
+ * STYLE commitment definition
14885
+ *
14886
+ * The STYLE commitment defines how the agent should format and present its responses.
14887
+ * This includes tone, writing style, formatting preferences, and communication patterns.
14888
+ *
14889
+ * Example usage in agent source:
14890
+ *
14891
+ * ```book
14892
+ * STYLE Write in a professional but friendly tone, use bullet points for lists
14893
+ * STYLE Always provide code examples when explaining programming concepts
14894
+ * ```
14895
+ *
14896
+ * @private [🪔] Maybe export the commitments through some package
14897
+ */
14898
+ class StyleCommitmentDefinition extends BaseCommitmentDefinition {
14899
+ constructor(type = 'STYLE') {
14900
+ super(type);
14901
+ }
14902
+ /**
14903
+ * Short one-line description of STYLE.
14904
+ */
14905
+ get description() {
14906
+ return 'Control the tone and writing style of responses.';
14907
+ }
14908
+ /**
14909
+ * Icon for this commitment.
14910
+ */
14911
+ get icon() {
14912
+ return '🖋️';
14913
+ }
14914
+ /**
14915
+ * Markdown documentation for STYLE commitment.
14916
+ */
14917
+ get documentation() {
14918
+ return spaceTrim$1.spaceTrim(`
14919
+ # ${this.type}
14920
+
14921
+ Defines how the agent should format and present its responses (tone, writing style, formatting).
14922
+
14923
+ ## Key aspects
14924
+
14925
+ - Both terms work identically and can be used interchangeably.
14926
+ - Later style instructions can override earlier ones.
14927
+ - Style affects both tone and presentation format.
14928
+
14929
+ ## Examples
14930
+
14931
+ \`\`\`book
14932
+ Technical Writer
14933
+
14934
+ PERSONA You are a technical documentation expert
14935
+ STYLE Write in a professional but friendly tone, use bullet points for lists
14936
+ STYLE Always provide code examples when explaining programming concepts
14937
+ FORMAT Use markdown formatting with clear headings
14938
+ \`\`\`
14939
+
14940
+ \`\`\`book
14941
+ Creative Assistant
14942
+
14943
+ PERSONA You are a creative writing helper
14944
+ STYLE Be enthusiastic and encouraging in your responses
14945
+ STYLE Use vivid metaphors and analogies to explain concepts
14946
+ STYLE Keep responses conversational and engaging
14947
+ RULE Always maintain a positive and supportive tone
14948
+ \`\`\`
14949
+ `);
14950
+ }
14951
+ applyToAgentModelRequirements(requirements, content) {
14952
+ const trimmedContent = content.trim();
14953
+ if (!trimmedContent) {
14954
+ return requirements;
14955
+ }
14956
+ // Add style instructions to the system message
14957
+ const styleSection = `Style: ${trimmedContent}`;
14958
+ return this.appendToSystemMessage(requirements, styleSection, '\n\n');
14959
+ }
14960
+ }
14961
+ /**
14962
+ * [💞] Ignore a discrepancy between file name and entity name
14963
+ */
14964
+
14965
+ /**
14966
+ * USE commitment definition
14967
+ *
14968
+ * The USE commitment indicates that the agent should utilize specific tools or capabilities
14969
+ * to access and interact with external systems when necessary.
14970
+ *
14971
+ * Supported USE types:
14972
+ * - USE BROWSER: Enables the agent to use a web browser tool
14973
+ * - USE SEARCH ENGINE (future): Enables search engine access
14974
+ * - USE FILE SYSTEM (future): Enables file system operations
14975
+ * - USE MCP (future): Enables MCP server connections
14976
+ *
14977
+ * The content following the USE commitment is ignored (similar to NOTE).
14978
+ *
14979
+ * Example usage in agent source:
14980
+ *
14981
+ * ```book
14982
+ * USE BROWSER
14983
+ * USE SEARCH ENGINE
14984
+ * ```
14985
+ *
14986
+ * @private [🪔] Maybe export the commitments through some package
14987
+ */
14988
+ class UseCommitmentDefinition extends BaseCommitmentDefinition {
14989
+ constructor() {
14990
+ super('USE');
14991
+ }
14992
+ /**
14993
+ * Short one-line description of USE commitments.
14994
+ */
14995
+ get description() {
14996
+ return 'Enable the agent to use specific tools or capabilities (BROWSER, SEARCH ENGINE, etc.).';
14997
+ }
14998
+ /**
14999
+ * Icon for this commitment.
15000
+ */
15001
+ get icon() {
15002
+ return '🔧';
15003
+ }
15004
+ /**
15005
+ * Markdown documentation for USE commitment.
15006
+ */
15007
+ get documentation() {
15008
+ return spaceTrim$1.spaceTrim(`
15009
+ # USE
15010
+
15011
+ Enables the agent to use specific tools or capabilities for interacting with external systems.
15012
+
15013
+ ## Supported USE types
15014
+
15015
+ - **USE BROWSER** - Enables the agent to use a web browser tool to access and retrieve information from the internet
15016
+ - **USE SEARCH ENGINE** (future) - Enables search engine access
15017
+ - **USE FILE SYSTEM** (future) - Enables file system operations
15018
+ - **USE MCP** (future) - Enables MCP server connections
15019
+
15020
+ ## Key aspects
15021
+
15022
+ - The content following the USE commitment is ignored (similar to NOTE)
15023
+ - Multiple USE commitments can be specified to enable multiple capabilities
15024
+ - The actual tool usage is handled by the agent runtime
15025
+
15026
+ ## Examples
15027
+
15028
+ ### Basic browser usage
15029
+
15030
+ \`\`\`book
15031
+ Research Assistant
15032
+
15033
+ PERSONA You are a helpful research assistant
15034
+ USE BROWSER
15035
+ KNOWLEDGE Can search the web for up-to-date information
15036
+ \`\`\`
15037
+
15038
+ ### Multiple tools
15039
+
15040
+ \`\`\`book
15041
+ Data Analyst
15042
+
15043
+ PERSONA You are a data analyst assistant
15044
+ USE BROWSER
15045
+ USE FILE SYSTEM
15046
+ ACTION Can analyze data from various sources
15047
+ \`\`\`
15048
+ `);
15049
+ }
15050
+ applyToAgentModelRequirements(requirements, content) {
15051
+ // USE commitments don't modify the system message or model requirements directly
15052
+ // They are handled separately in the parsing logic for capability extraction
15053
+ // This method exists for consistency with the CommitmentDefinition interface
15054
+ return requirements;
15055
+ }
15056
+ /**
15057
+ * Extracts the tool type from the USE commitment
15058
+ * This is used by the parsing logic
15059
+ */
15060
+ extractToolType(content) {
15061
+ var _a, _b;
15062
+ const trimmedContent = content.trim();
15063
+ // The tool type is the first word after USE (already stripped)
15064
+ const match = trimmedContent.match(/^(\w+)/);
15065
+ 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;
15066
+ }
15067
+ /**
15068
+ * Checks if this is a known USE type
15069
+ */
15070
+ isKnownUseType(useType) {
15071
+ const knownTypes = ['BROWSER', 'SEARCH ENGINE', 'FILE SYSTEM', 'MCP'];
15072
+ return knownTypes.includes(useType.toUpperCase());
15073
+ }
15074
+ }
15075
+ /**
15076
+ * Note: [💞] Ignore a discrepancy between file name and entity name
15077
+ */
15078
+
15079
+ /**
15080
+ * USE BROWSER commitment definition
15081
+ *
15082
+ * The `USE BROWSER` commitment indicates that the agent should utilize a web browser tool
15083
+ * to access and retrieve up-to-date information from the internet when necessary.
15084
+ *
15085
+ * The content following `USE BROWSER` is ignored (similar to NOTE).
15086
+ *
15087
+ * Example usage in agent source:
15088
+ *
15089
+ * ```book
15090
+ * USE BROWSER
15091
+ * USE BROWSER This will be ignored
15092
+ * ```
15093
+ *
15094
+ * @private [🪔] Maybe export the commitments through some package
15095
+ */
15096
+ class UseBrowserCommitmentDefinition extends BaseCommitmentDefinition {
15097
+ constructor() {
15098
+ super('USE BROWSER', ['BROWSER']);
15099
+ }
15100
+ /**
15101
+ * The `USE BROWSER` commitment is standalone.
15102
+ */
15103
+ get requiresContent() {
15104
+ return false;
15105
+ }
15106
+ /**
15107
+ * Short one-line description of USE BROWSER.
15108
+ */
15109
+ get description() {
15110
+ return 'Enable the agent to use a web browser tool for accessing internet information.';
15111
+ }
15112
+ /**
15113
+ * Icon for this commitment.
15114
+ */
15115
+ get icon() {
15116
+ return '🌐';
15117
+ }
15118
+ /**
15119
+ * Markdown documentation for USE BROWSER commitment.
15120
+ */
15121
+ get documentation() {
15122
+ return spaceTrim$1.spaceTrim(`
15123
+ # USE BROWSER
15124
+
15125
+ Enables the agent to use a web browser tool to access and retrieve up-to-date information from the internet.
15126
+
15127
+ ## Key aspects
15128
+
15129
+ - The content following \`USE BROWSER\` is ignored (similar to NOTE)
15130
+ - The actual browser tool usage is handled by the agent runtime
15131
+ - Allows the agent to fetch current information from websites
15132
+ - Useful for research tasks, fact-checking, and accessing dynamic content
15133
+
15134
+ ## Examples
15135
+
15136
+ \`\`\`book
15137
+ Research Assistant
15138
+
15139
+ PERSONA You are a helpful research assistant specialized in finding current information
15140
+ USE BROWSER
15141
+ RULE Always cite your sources when providing information from the web
15142
+ \`\`\`
15143
+
15144
+ \`\`\`book
15145
+ News Analyst
15146
+
15147
+ PERSONA You are a news analyst who stays up-to-date with current events
15148
+ USE BROWSER
15149
+ STYLE Present news in a balanced and objective manner
15150
+ ACTION Can search for and summarize news articles
15151
+ \`\`\`
15152
+
15153
+ \`\`\`book
15154
+ Company Lawyer
15155
+
15156
+ PERSONA You are a company lawyer providing legal advice
15157
+ USE BROWSER
15158
+ KNOWLEDGE Corporate law and legal procedures
15159
+ RULE Always recommend consulting with a licensed attorney for specific legal matters
15160
+ \`\`\`
15161
+ `);
15162
+ }
15163
+ /**
15164
+ * Gets human-readable titles for tool functions provided by this commitment.
15165
+ */
15166
+ getToolTitles() {
15167
+ return {
15168
+ web_browser: 'Web browser',
15169
+ };
15170
+ }
15171
+ applyToAgentModelRequirements(requirements, content) {
15172
+ // Get existing tools array or create new one
15173
+ const existingTools = requirements.tools || [];
15174
+ // Add 'web_browser' to tools if not already present
15175
+ const updatedTools = existingTools.some((tool) => tool.name === 'web_browser')
15176
+ ? existingTools
15177
+ : ([
15178
+ // TODO: [🔰] Use through proper MCP server
15179
+ ...existingTools,
15180
+ {
15181
+ name: 'web_browser',
15182
+ description: spaceTrim$1.spaceTrim(`
15183
+ A tool that can browse the web.
15184
+ Use this tool when you need to access specific websites or browse the internet.
15185
+ `),
15186
+ parameters: {
15187
+ type: 'object',
15188
+ properties: {
15189
+ url: {
15190
+ type: 'string',
15191
+ description: 'The URL to browse',
15192
+ },
15193
+ },
15194
+ required: ['url'],
15195
+ },
15196
+ },
15197
+ ]);
15198
+ // Return requirements with updated tools and metadata
15199
+ return this.appendToSystemMessage({
15200
+ ...requirements,
15201
+ tools: updatedTools,
15202
+ metadata: {
15203
+ ...requirements.metadata,
15204
+ useBrowser: true,
15205
+ },
15206
+ }, spaceTrim$1.spaceTrim(`
15207
+ You have access to the web browser. Use it to access specific websites or browse the internet.
15208
+ When you need to know some information from a specific website, use the tool provided to you.
15209
+ `));
15210
+ }
15211
+ }
15212
+ /**
15213
+ * Note: [💞] Ignore a discrepancy between file name and entity name
15214
+ */
15215
+
15216
+ /**
15217
+ * USE MCP commitment definition
15218
+ *
15219
+ * The `USE MCP` commitment allows to specify an MCP server URL which the agent will connect to
15220
+ * for retrieving additional instructions and actions.
15221
+ *
15222
+ * The content following `USE MCP` is the URL of the MCP server.
15223
+ *
15224
+ * Example usage in agent source:
15225
+ *
15226
+ * ```book
15227
+ * USE MCP http://mcp-server-url.com
15228
+ * ```
15229
+ *
15230
+ * @private [🪔] Maybe export the commitments through some package
15231
+ */
15232
+ class UseMcpCommitmentDefinition extends BaseCommitmentDefinition {
15233
+ constructor() {
15234
+ super('USE MCP', ['MCP']);
15235
+ }
15236
+ /**
15237
+ * Short one-line description of USE MCP.
15238
+ */
15239
+ get description() {
15240
+ return 'Connects the agent to an external MCP server for additional capabilities.';
15241
+ }
15242
+ /**
15243
+ * Icon for this commitment.
15244
+ */
15245
+ get icon() {
15246
+ return '🔌';
15247
+ }
15248
+ /**
15249
+ * Markdown documentation for USE MCP commitment.
15250
+ */
15251
+ get documentation() {
15252
+ return spaceTrim$1.spaceTrim(`
15253
+ # USE MCP
15254
+
15255
+ Connects the agent to an external Model Context Protocol (MCP) server.
15256
+
15257
+ ## Key aspects
15258
+
15259
+ - The content following \`USE MCP\` must be a valid URL
15260
+ - Multiple MCP servers can be connected by using multiple \`USE MCP\` commitments
15261
+ - The agent will have access to tools and resources provided by the MCP server
15262
+
15263
+ ## Example
15264
+
15265
+ \`\`\`book
15266
+ Company Lawyer
15267
+
15268
+ PERSONA You are a company lawyer.
15269
+ USE MCP http://legal-db.example.com
15270
+ \`\`\`
15271
+ `);
15272
+ }
15273
+ applyToAgentModelRequirements(requirements, content) {
15274
+ const mcpServerUrl = content.trim();
15275
+ if (!mcpServerUrl) {
15276
+ return requirements;
15277
+ }
15278
+ const existingMcpServers = requirements.mcpServers || [];
15279
+ // Avoid duplicates
15280
+ if (existingMcpServers.includes(mcpServerUrl)) {
15281
+ return requirements;
15282
+ }
15283
+ return {
15284
+ ...requirements,
15285
+ mcpServers: [...existingMcpServers, mcpServerUrl],
15286
+ };
15287
+ }
15288
+ }
15289
+ /**
15290
+ * Note: [💞] Ignore a discrepancy between file name and entity name
15291
+ */
15292
+
15293
+ /**
15294
+ * A search engine implementation that uses the SerpApi to fetch Google search results.
15295
+ *
15296
+ * @private <- TODO: !!!! Export via some package
15297
+ */
15298
+ class SerpSearchEngine {
15299
+ get title() {
15300
+ return 'SerpApi Search Engine';
15301
+ }
15302
+ get description() {
15303
+ return 'Search engine that uses SerpApi to fetch Google search results';
15304
+ }
15305
+ checkConfiguration() {
15306
+ if (!process.env.SERP_API_KEY) {
15307
+ throw new Error('SERP_API_KEY is not configured');
15308
+ }
15309
+ }
15310
+ async search(query, options = {}) {
15311
+ const apiKey = process.env.SERP_API_KEY;
15312
+ if (!apiKey) {
15313
+ throw new Error('SERP_API_KEY is not configured');
15314
+ }
15315
+ const url = new URL('https://serpapi.com/search');
15316
+ url.searchParams.set('api_key', apiKey);
15317
+ url.searchParams.set('engine', 'google');
15318
+ url.searchParams.set('q', query);
15319
+ for (const [key, value] of Object.entries(options)) {
15320
+ url.searchParams.set(key, String(value));
15321
+ }
15322
+ const response = await fetch(url.toString());
15323
+ if (!response.ok) {
15324
+ const body = await response.text();
15325
+ throw new Error(`SerpApi failed with status ${response.status}: ${response.statusText}\n${body}`);
15326
+ }
15327
+ const data = (await response.json());
15328
+ return (data.organic_results || []).map((item) => ({
15329
+ title: item.title,
15330
+ url: item.link,
15331
+ snippet: item.snippet || '',
15332
+ }));
15333
+ }
15334
+ }
15335
+
15336
+ /**
15337
+ * USE SEARCH ENGINE commitment definition
15338
+ *
15339
+ * The `USE SEARCH ENGINE` commitment indicates that the agent should utilize a search engine tool
15340
+ * to access and retrieve up-to-date information from the internet when necessary.
15341
+ *
15342
+ * The content following `USE SEARCH ENGINE` is an arbitrary text that the agent should know (e.g. search scope or instructions).
15343
+ *
15344
+ * Example usage in agent source:
15345
+ *
15346
+ * ```book
15347
+ * USE SEARCH ENGINE
15348
+ * USE SEARCH ENGINE Hledej informace o Přemyslovcích
15349
+ * ```
15350
+ *
15351
+ * @private [🪔] Maybe export the commitments through some package
15352
+ */
15353
+ class UseSearchEngineCommitmentDefinition extends BaseCommitmentDefinition {
15354
+ constructor() {
15355
+ super('USE SEARCH ENGINE', ['USE SEARCH']);
15356
+ }
15357
+ /**
15358
+ * Short one-line description of USE SEARCH ENGINE.
15359
+ */
15360
+ get description() {
15361
+ return 'Enable the agent to use a search engine tool for accessing internet information.';
15362
+ }
15363
+ /**
15364
+ * Icon for this commitment.
15365
+ */
15366
+ get icon() {
15367
+ return '🔍';
15368
+ }
15369
+ /**
15370
+ * Markdown documentation for USE SEARCH ENGINE commitment.
15371
+ */
15372
+ get documentation() {
15373
+ return spaceTrim$1.spaceTrim(`
15374
+ # USE SEARCH ENGINE
15375
+
15376
+ Enables the agent to use a search engine tool to access and retrieve up-to-date information from the internet.
15377
+
15378
+ ## Key aspects
15379
+
15380
+ - The content following \`USE SEARCH ENGINE\` is an arbitrary text that the agent should know (e.g. search scope or instructions).
15381
+ - The actual search engine tool usage is handled by the agent runtime
15382
+ - Allows the agent to search for current information from the web
15383
+ - Useful for research tasks, finding facts, and accessing dynamic content
15384
+
15385
+ ## Examples
15386
+
15387
+ \`\`\`book
15388
+ Research Assistant
15389
+
15390
+ PERSONA You are a helpful research assistant specialized in finding current information
15391
+ USE SEARCH ENGINE
15392
+ RULE Always cite your sources when providing information from the web
15393
+ \`\`\`
15394
+
15395
+ \`\`\`book
15396
+ Fact Checker
15397
+
15398
+ PERSONA You are a fact checker
15399
+ USE SEARCH ENGINE
15400
+ ACTION Search for claims and verify them against reliable sources
15401
+ \`\`\`
15402
+ `);
15403
+ }
15404
+ applyToAgentModelRequirements(requirements, content) {
15405
+ // Get existing tools array or create new one
15406
+ const existingTools = requirements.tools || [];
15407
+ // Add 'web_search' to tools if not already present
15408
+ const updatedTools = existingTools.some((tool) => tool.name === 'web_search')
15409
+ ? existingTools
15410
+ : [
15411
+ ...existingTools,
15412
+ {
15413
+ name: 'web_search',
15414
+ description: spaceTrim$1.spaceTrim(`
15415
+ Search the internet for information.
15416
+ Use this tool when you need to find up-to-date information or facts that you don't know.
15417
+ ${!content ? '' : `Search scope / instructions: ${content}`}
15418
+ `),
15419
+ parameters: {
15420
+ type: 'object',
15421
+ properties: {
15422
+ query: {
15423
+ type: 'string',
15424
+ description: 'The search query',
15425
+ },
15426
+ location: {
15427
+ type: 'string',
15428
+ description: 'The location for the search (e.g., "Austin, Texas, United States" or "Prague, Czechia")',
15429
+ },
15430
+ gl: {
15431
+ type: 'string',
15432
+ description: 'The country code (e.g., "us" for United States, "cz" for Czechia)',
15433
+ },
15434
+ hl: {
15435
+ type: 'string',
15436
+ description: 'The language code (e.g., "en" for English, "cs" for Czech)',
15437
+ },
15438
+ num: {
15439
+ type: 'integer',
15440
+ description: 'Number of results to return',
15441
+ },
15442
+ engine: {
15443
+ type: 'string',
15444
+ description: 'The search engine to use (e.g., "google", "bing", "yahoo", "baidu")',
15445
+ },
15446
+ google_domain: {
15447
+ type: 'string',
15448
+ description: 'The Google domain to use (e.g., "google.com", "google.cz")',
15449
+ },
15450
+ },
15451
+ required: ['query'],
15452
+ },
15453
+ },
15454
+ ];
15455
+ // Return requirements with updated tools and metadata
15456
+ return this.appendToSystemMessage({
15457
+ ...requirements,
15458
+ tools: updatedTools,
15459
+ metadata: {
15460
+ ...requirements.metadata,
15461
+ useSearchEngine: content || true,
15462
+ },
15463
+ }, spaceTrim$1.spaceTrim(`
15464
+ You have access to the web search engine. Use it to find up-to-date information or facts that you don't know.
15465
+ When you need to know some information from the internet, use the tool provided to you.
15466
+ `));
15467
+ }
15468
+ /**
15469
+ * Gets human-readable titles for tool functions provided by this commitment.
15470
+ */
15471
+ getToolTitles() {
15472
+ return {
15473
+ web_search: 'Web search',
15474
+ };
15475
+ }
15476
+ /**
15477
+ * Gets the `web_search` tool function implementation.
15478
+ */
15479
+ getToolFunctions() {
15480
+ return {
15481
+ async web_search(args) {
15482
+ console.log('!!!! [Tool] web_search called', { args });
15483
+ const { query, ...options } = args;
15484
+ if (!query) {
15485
+ throw new Error('Search query is required');
15486
+ }
15487
+ const searchEngine = new SerpSearchEngine();
15488
+ const results = await searchEngine.search(query, options);
15489
+ return spaceTrim$1.spaceTrim((block) => `
15490
+ Search results for "${query}"${Object.keys(options).length === 0
15491
+ ? ''
15492
+ : ` with options ${JSON.stringify(options)}`}:
15493
+
15494
+ ${block(results
15495
+ .map((result) => spaceTrim$1.spaceTrim(`
15496
+ - **${result.title}**
15497
+ ${result.url}
15498
+ ${result.snippet}
15499
+ `))
15500
+ .join('\n\n'))}
15501
+ `);
15502
+ },
15503
+ };
15504
+ }
15505
+ }
15506
+ /**
15507
+ * Note: [💞] Ignore a discrepancy between file name and entity name
15508
+ */
15509
+
15510
+ /**
15511
+ * USE TIME commitment definition
15512
+ *
15513
+ * The `USE TIME` commitment indicates that the agent should be able to determine the current date and time.
15514
+ *
15515
+ * Example usage in agent source:
15516
+ *
15517
+ * ```book
15518
+ * USE TIME
15519
+ * ```
15520
+ *
15521
+ * @private [🪔] Maybe export the commitments through some package
15522
+ */
15523
+ class UseTimeCommitmentDefinition extends BaseCommitmentDefinition {
15524
+ constructor() {
15525
+ super('USE TIME', ['CURRENT TIME', 'TIME', 'DATE']);
15526
+ }
15527
+ /**
15528
+ * Short one-line description of USE TIME.
15529
+ */
15530
+ get description() {
15531
+ return 'Enable the agent to determine the current date and time.';
15532
+ }
15533
+ /**
15534
+ * Icon for this commitment.
15535
+ */
15536
+ get icon() {
15537
+ return '🕒';
15538
+ }
15539
+ /**
15540
+ * Markdown documentation for USE TIME commitment.
15541
+ */
15542
+ get documentation() {
15543
+ return spaceTrim$1.spaceTrim(`
15544
+ # USE TIME
15545
+
15546
+ Enables the agent to determine the current date and time.
15547
+
15548
+ ## Key aspects
15549
+
15550
+ - This tool won't receive any input.
15551
+ - It outputs the current date and time as an ISO 8601 string.
15552
+ - Allows the agent to answer questions about the current time or date.
15553
+
15554
+ ## Examples
15555
+
15556
+ \`\`\`book
15557
+ Time-aware Assistant
15558
+
15559
+ PERSONA You are a helpful assistant who knows the current time.
15560
+ USE TIME
15561
+ \`\`\`
15562
+ `);
15563
+ }
15564
+ applyToAgentModelRequirements(requirements, content) {
15565
+ // Get existing tools array or create new one
15566
+ const existingTools = requirements.tools || [];
15567
+ // Add 'get_current_time' to tools if not already present
15568
+ const updatedTools = existingTools.some((tool) => tool.name === 'get_current_time')
15569
+ ? existingTools
15570
+ : [
15571
+ ...existingTools,
15572
+ {
15573
+ name: 'get_current_time',
15574
+ description: 'Get the current date and time in ISO 8601 format.',
15575
+ parameters: {
15576
+ type: 'object',
15577
+ properties: {
15578
+ timezone: {
15579
+ type: 'string',
15580
+ description: 'Optional timezone name (e.g. "Europe/Prague", "UTC", "America/New_York").',
15581
+ },
15582
+ },
15583
+ required: [],
15584
+ },
15585
+ },
15586
+ // <- TODO: !!!! define the function in LLM tools
15587
+ ];
15588
+ // Return requirements with updated tools and metadata
15589
+ return this.appendToSystemMessage({
15590
+ ...requirements,
15591
+ tools: updatedTools,
15592
+ metadata: {
15593
+ ...requirements.metadata,
15594
+ },
15595
+ }, spaceTrim$1.spaceTrim(`
15596
+ You have access to the current date and time. Use it to answer questions about the current date and time.
15597
+ When you need to know the current date or time, use the tool provided to you.
15598
+ `));
15599
+ }
15600
+ /**
15601
+ * Gets human-readable titles for tool functions provided by this commitment.
15602
+ */
15603
+ getToolTitles() {
15604
+ return {
15605
+ get_current_time: 'Get current time',
15606
+ };
15607
+ }
15608
+ /**
15609
+ * Gets the `get_current_time` tool function implementation.
15610
+ */
15611
+ getToolFunctions() {
15612
+ return {
15613
+ async get_current_time(args) {
15614
+ var _a;
15615
+ console.log('!!!! [Tool] get_current_time called', { args });
15616
+ const { timezone } = args;
15617
+ if (!timezone) {
15618
+ return new Date().toISOString();
15619
+ }
15620
+ try {
15621
+ // Note: Returning ISO 8601 string but in the requested timezone
15622
+ const formatter = new Intl.DateTimeFormat('en-CA', {
15623
+ timeZone: timezone,
15624
+ year: 'numeric',
15625
+ month: '2-digit',
15626
+ day: '2-digit',
15627
+ hour: '2-digit',
15628
+ minute: '2-digit',
15629
+ second: '2-digit',
15630
+ hour12: false,
15631
+ timeZoneName: 'shortOffset',
15632
+ });
15633
+ const parts = formatter.formatToParts(new Date());
15634
+ const part = (type) => { var _a; return (_a = parts.find((p) => p.type === type)) === null || _a === void 0 ? void 0 : _a.value; };
15635
+ // en-CA format is YYYY-MM-DD
15636
+ 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', '')}`;
15637
+ return isoString;
15638
+ }
15639
+ catch (error) {
15640
+ // Fallback to UTC if timezone is invalid
15641
+ return new Date().toISOString();
15642
+ }
15643
+ },
15644
+ };
15645
+ }
15646
+ }
15647
+ /**
15648
+ * Note: [💞] Ignore a discrepancy between file name and entity name
15649
+ */
15650
+
15651
+ /**
15652
+ * Placeholder commitment definition for commitments that are not yet implemented
15653
+ *
15654
+ * This commitment simply adds its content 1:1 into the system message,
15655
+ * preserving the original behavior until proper implementation is added.
15656
+ *
15657
+ * @public exported from `@promptbook/core`
15658
+ */
15659
+ class NotYetImplementedCommitmentDefinition extends BaseCommitmentDefinition {
15660
+ constructor(type) {
15661
+ super(type);
15662
+ }
15663
+ /**
15664
+ * Short one-line description of a placeholder commitment.
15665
+ */
15666
+ get description() {
15667
+ return 'Placeholder commitment that appends content verbatim to the system message.';
15668
+ }
15669
+ /**
15670
+ * Icon for this commitment.
15671
+ */
15672
+ get icon() {
15673
+ return '🚧';
15674
+ }
15675
+ /**
15676
+ * Markdown documentation available at runtime.
15677
+ */
15678
+ get documentation() {
15679
+ return spaceTrim$1.spaceTrim(`
15680
+ # ${this.type}
15681
+
15682
+ This commitment is not yet fully implemented.
15683
+
15684
+ ## Key aspects
15685
+
15686
+ - Content is appended directly to the system message.
15687
+ - No special processing or validation is performed.
15688
+ - Behavior preserved until proper implementation is added.
15689
+
15690
+ ## Status
15691
+
15692
+ - **Status:** Placeholder implementation
15693
+ - **Effect:** Appends content prefixed by commitment type
15694
+ - **Future:** Will be replaced with specialized logic
15695
+
15696
+ ## Examples
15697
+
15698
+ \`\`\`book
15699
+ Example Agent
15700
+
15701
+ PERSONA You are a helpful assistant
15702
+ ${this.type} Your content here
15703
+ RULE Always be helpful
15704
+ \`\`\`
15705
+ `);
15706
+ }
15707
+ applyToAgentModelRequirements(requirements, content) {
15708
+ const trimmedContent = content.trim();
15709
+ if (!trimmedContent) {
15710
+ return requirements;
15711
+ }
15712
+ // Add the commitment content 1:1 to the system message
15713
+ const commitmentLine = `${this.type} ${trimmedContent}`;
15714
+ return this.appendToSystemMessage(requirements, commitmentLine, '\n\n');
15715
+ }
15716
+ }
15717
+
15718
+ /**
15719
+ * Registry of all available commitment definitions
15720
+ * This array contains instances of all commitment definitions
15721
+ * This is the single source of truth for all commitments in the system
15722
+ *
15723
+ * @private Use functions to access commitments instead of this array directly
15724
+ */
15725
+ const COMMITMENT_REGISTRY = [
15726
+ // Fully implemented commitments
15727
+ new PersonaCommitmentDefinition('PERSONA'),
15728
+ new PersonaCommitmentDefinition('PERSONAE'),
15729
+ new KnowledgeCommitmentDefinition(),
15730
+ new MemoryCommitmentDefinition('MEMORY'),
15731
+ new MemoryCommitmentDefinition('MEMORIES'),
15732
+ new StyleCommitmentDefinition('STYLE'),
15733
+ new StyleCommitmentDefinition('STYLES'),
15734
+ new RuleCommitmentDefinition('RULES'),
15735
+ new RuleCommitmentDefinition('RULE'),
15736
+ new LanguageCommitmentDefinition('LANGUAGES'),
15737
+ new LanguageCommitmentDefinition('LANGUAGE'),
15738
+ new SampleCommitmentDefinition('SAMPLE'),
15739
+ new SampleCommitmentDefinition('EXAMPLE'),
15740
+ new FormatCommitmentDefinition('FORMAT'),
15741
+ new FormatCommitmentDefinition('FORMATS'),
15742
+ new FromCommitmentDefinition('FROM'),
15743
+ new ImportCommitmentDefinition('IMPORT'),
15744
+ new ImportCommitmentDefinition('IMPORTS'),
15745
+ new ModelCommitmentDefinition('MODEL'),
15746
+ new ModelCommitmentDefinition('MODELS'),
15747
+ new ActionCommitmentDefinition('ACTION'),
15748
+ new ActionCommitmentDefinition('ACTIONS'),
15749
+ new ComponentCommitmentDefinition(),
15750
+ new MetaImageCommitmentDefinition(),
15751
+ new MetaColorCommitmentDefinition(),
15752
+ new MetaFontCommitmentDefinition(),
15753
+ new MetaLinkCommitmentDefinition(),
15754
+ new MetaCommitmentDefinition(),
15755
+ new NoteCommitmentDefinition('NOTE'),
15756
+ new NoteCommitmentDefinition('NOTES'),
15757
+ new NoteCommitmentDefinition('COMMENT'),
15758
+ new NoteCommitmentDefinition('NONCE'),
15759
+ new NoteCommitmentDefinition('TODO'),
15760
+ new GoalCommitmentDefinition('GOAL'),
15761
+ new GoalCommitmentDefinition('GOALS'),
15762
+ new InitialMessageCommitmentDefinition(),
15763
+ new UserMessageCommitmentDefinition(),
15764
+ new AgentMessageCommitmentDefinition(),
15765
+ new MessageCommitmentDefinition('MESSAGE'),
15766
+ new MessageCommitmentDefinition('MESSAGES'),
15767
+ new ScenarioCommitmentDefinition('SCENARIO'),
15768
+ new ScenarioCommitmentDefinition('SCENARIOS'),
15769
+ new DeleteCommitmentDefinition('DELETE'),
15770
+ new DeleteCommitmentDefinition('CANCEL'),
15771
+ new DeleteCommitmentDefinition('DISCARD'),
15772
+ new DeleteCommitmentDefinition('REMOVE'),
15773
+ new DictionaryCommitmentDefinition(),
15774
+ new OpenCommitmentDefinition(),
15775
+ new ClosedCommitmentDefinition(),
15776
+ new UseBrowserCommitmentDefinition(),
15777
+ new UseSearchEngineCommitmentDefinition(),
15778
+ new UseTimeCommitmentDefinition(),
15779
+ new UseMcpCommitmentDefinition(),
15780
+ new UseCommitmentDefinition(),
15781
+ // Not yet implemented commitments (using placeholder)
15782
+ new NotYetImplementedCommitmentDefinition('EXPECT'),
15783
+ new NotYetImplementedCommitmentDefinition('BEHAVIOUR'),
15784
+ new NotYetImplementedCommitmentDefinition('BEHAVIOURS'),
15785
+ new NotYetImplementedCommitmentDefinition('AVOID'),
15786
+ new NotYetImplementedCommitmentDefinition('AVOIDANCE'),
15787
+ new NotYetImplementedCommitmentDefinition('CONTEXT'),
15788
+ // <- TODO: Prompt: Leverage aliases instead of duplicating commitment definitions
15789
+ ];
15790
+ /**
15791
+ * Gets all available commitment definitions
15792
+ * @returns Array of all commitment definitions
15793
+ *
15794
+ * @public exported from `@promptbook/core`
15795
+ */
15796
+ function getAllCommitmentDefinitions() {
15797
+ return $deepFreeze([...COMMITMENT_REGISTRY]);
15798
+ }
15799
+ /**
15800
+ * Gets all function implementations provided by all commitments
15801
+ *
15802
+ * @public exported from `@promptbook/core`
15803
+ */
15804
+ function getAllCommitmentsToolFunctions() {
15805
+ const allToolFunctions = {};
15806
+ for (const commitmentDefinition of getAllCommitmentDefinitions()) {
15807
+ const toolFunctions = commitmentDefinition.getToolFunctions();
15808
+ for (const [funcName, funcImpl] of Object.entries(toolFunctions)) {
15809
+ allToolFunctions[funcName] = funcImpl;
15810
+ }
15811
+ }
15812
+ return allToolFunctions;
15813
+ }
15814
+ /**
15815
+ * TODO: [🧠] Maybe create through standardized $register
15816
+ * Note: [💞] Ignore a discrepancy between file name and entity name
15817
+ */
15818
+
15819
+ /**
15820
+ * Extracts code block from markdown.
15821
+ *
15822
+ * - When there are multiple or no code blocks the function throws a `ParseError`
15823
+ *
15824
+ * Note: There are multiple similar function:
15825
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
15826
+ * - `extractJsonBlock` extracts exactly one valid JSON code block
15827
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
15828
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
15829
+ *
15830
+ * @public exported from `@promptbook/markdown-utils`
15831
+ * @throws {ParseError} if there is not exactly one code block in the markdown
15832
+ */
15833
+ function extractBlock(markdown) {
15834
+ const { content } = extractOneBlockFromMarkdown(markdown);
15835
+ return content;
15836
+ }
15837
+
15838
+ /**
15839
+ * Function trimCodeBlock will trim starting and ending code block from the string if it is present.
15840
+ *
15841
+ * Note: [🔂] This function is idempotent.
15842
+ * Note: This is useful for post-processing of the result of the chat LLM model
15843
+ * when the model wraps the result in the (markdown) code block.
15844
+ *
15845
+ * @public exported from `@promptbook/markdown-utils`
15846
+ */
15847
+ function trimCodeBlock(value) {
15848
+ value = spaceTrim$1.spaceTrim(value);
15849
+ if (!/^```[a-z]*(.*)```$/is.test(value)) {
15850
+ return value;
15851
+ }
15852
+ value = value.replace(/^```[a-z]*/i, '');
15853
+ value = value.replace(/```$/i, '');
15854
+ value = spaceTrim$1.spaceTrim(value);
15855
+ return value;
15856
+ }
15857
+
15858
+ /**
15859
+ * Function trimEndOfCodeBlock will remove ending code block from the string if it is present.
15860
+ *
15861
+ * Note: This is useful for post-processing of the result of the completion LLM model
15862
+ * if you want to start code block in the prompt but you don't want to end it in the result.
15863
+ *
15864
+ * @public exported from `@promptbook/markdown-utils`
15865
+ */
15866
+ function trimEndOfCodeBlock(value) {
15867
+ value = spaceTrim$1.spaceTrim(value);
15868
+ value = value.replace(/```$/g, '');
15869
+ value = spaceTrim$1.spaceTrim(value);
15870
+ return value;
15871
+ }
15872
+
15873
+ /**
15874
+ * @private internal for `preserve`
15875
+ */
15876
+ const _preserved = [];
15877
+ /**
15878
+ * Does nothing, but preserves the function in the bundle
15879
+ * Compiler is tricked into thinking the function is used
15880
+ *
15881
+ * @param value any function to preserve
15882
+ * @returns nothing
15883
+ * @private within the repository
15884
+ */
15885
+ function $preserve(...value) {
15886
+ _preserved.push(...value);
15887
+ }
15888
+ /**
15889
+ * Note: [💞] Ignore a discrepancy between file name and entity name
15890
+ */
15891
+
15892
+ // Note: [💎]
15893
+ /**
15894
+ * ScriptExecutionTools for JavaScript implemented via eval
15895
+ *
15896
+ * Warning: It is used for testing and mocking
15897
+ * **NOT intended to use in the production** due to its unsafe nature, use `JavascriptExecutionTools` instead.
15898
+ *
15899
+ * @public exported from `@promptbook/javascript`
15900
+ */
15901
+ class JavascriptEvalExecutionTools {
15902
+ constructor(options) {
15903
+ this.options = options || {};
15904
+ }
15905
+ /**
15906
+ * Executes a JavaScript
15907
+ */
15908
+ async execute(options) {
15909
+ const { scriptLanguage, parameters } = options;
15910
+ let { script } = options;
15911
+ if (scriptLanguage !== 'javascript') {
15912
+ throw new PipelineExecutionError(`Script language ${scriptLanguage} not supported to be executed by JavascriptEvalExecutionTools`);
15913
+ }
15914
+ // Note: [💎]
15915
+ // Note: Using direct eval, following variables are in same scope as eval call so they are accessible from inside the evaluated script:
15916
+ const spaceTrim = (_) => spaceTrim__default["default"](_);
15917
+ $preserve(spaceTrim);
15918
+ const removeQuotes$1 = removeQuotes;
15919
+ $preserve(removeQuotes$1);
15920
+ const unwrapResult$1 = unwrapResult;
15921
+ $preserve(unwrapResult$1);
15922
+ const trimEndOfCodeBlock$1 = trimEndOfCodeBlock;
12014
15923
  $preserve(trimEndOfCodeBlock$1);
12015
15924
  const trimCodeBlock$1 = trimCodeBlock;
12016
15925
  $preserve(trimCodeBlock$1);
@@ -12087,6 +15996,13 @@
12087
15996
  `const ${functionName} = buildinFunctions.${functionName};`)
12088
15997
  .join('\n');
12089
15998
  // TODO: DRY [🍯]
15999
+ const commitmentsFunctions = getAllCommitmentsToolFunctions();
16000
+ const commitmentsFunctionsStatement = Object.keys(commitmentsFunctions)
16001
+ .map((functionName) =>
16002
+ // Note: Custom functions are exposed to the current scope as variables
16003
+ `const ${functionName} = commitmentsFunctions.${functionName};`)
16004
+ .join('\n');
16005
+ // TODO: DRY [🍯]
12090
16006
  const customFunctions = this.options.functions || {};
12091
16007
  const customFunctionsStatement = Object.keys(customFunctions)
12092
16008
  .map((functionName) =>
@@ -12100,6 +16016,10 @@
12100
16016
  // Build-in functions:
12101
16017
  ${block(buildinFunctionsStatement)}
12102
16018
 
16019
+ // Commitments functions:
16020
+ ${block(commitmentsFunctionsStatement)}
16021
+
16022
+
12103
16023
  // Custom functions:
12104
16024
  ${block(customFunctionsStatement || '// -- No custom functions --')}
12105
16025
 
@@ -12107,7 +16027,7 @@
12107
16027
  ${block(Object.entries(parameters)
12108
16028
  .map(([key, value]) => `const ${key} = ${JSON.stringify(value)};`)
12109
16029
  .join('\n'))}
12110
- (()=>{ ${script} })()
16030
+ (async ()=>{ ${script} })()
12111
16031
  `);
12112
16032
  if (this.options.isVerbose) {
12113
16033
  console.info(spaceTrim__default["default"]((block) => `