@promptbook/javascript 0.105.0-0 → 0.105.0-3

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