@promptbook/core 0.104.0-0 → 0.104.0-10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/esm/index.es.js +487 -159
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/servers.d.ts +8 -0
  4. package/esm/typings/src/_packages/core.index.d.ts +2 -0
  5. package/esm/typings/src/_packages/types.index.d.ts +10 -2
  6. package/esm/typings/src/book-2.0/agent-source/AgentBasicInformation.d.ts +6 -1
  7. package/esm/typings/src/book-2.0/agent-source/createAgentModelRequirements.d.ts +6 -6
  8. package/esm/typings/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments.closed.test.d.ts +1 -0
  9. package/esm/typings/src/book-2.0/utils/generatePlaceholderAgentProfileImageUrl.d.ts +3 -3
  10. package/esm/typings/src/book-components/Chat/Chat/ChatMessageItem.d.ts +5 -1
  11. package/esm/typings/src/book-components/Chat/Chat/ChatProps.d.ts +5 -0
  12. package/esm/typings/src/book-components/Chat/CodeBlock/CodeBlock.d.ts +13 -0
  13. package/esm/typings/src/book-components/Chat/MarkdownContent/MarkdownContent.d.ts +1 -0
  14. package/esm/typings/src/book-components/Chat/types/ChatMessage.d.ts +7 -11
  15. package/esm/typings/src/book-components/_common/Dropdown/Dropdown.d.ts +2 -2
  16. package/esm/typings/src/book-components/_common/MenuHoisting/MenuHoistingContext.d.ts +56 -0
  17. package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentCollectionInSupabase.d.ts +21 -11
  18. package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentsDatabaseSchema.d.ts +80 -14
  19. package/esm/typings/src/commitments/DICTIONARY/DICTIONARY.d.ts +46 -0
  20. package/esm/typings/src/commitments/index.d.ts +2 -1
  21. package/esm/typings/src/llm-providers/_multiple/MultipleLlmExecutionTools.d.ts +6 -2
  22. package/esm/typings/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +1 -1
  23. package/esm/typings/src/llm-providers/ollama/OllamaExecutionTools.d.ts +1 -1
  24. package/esm/typings/src/llm-providers/openai/createOpenAiCompatibleExecutionTools.d.ts +1 -1
  25. package/esm/typings/src/llm-providers/remote/RemoteLlmExecutionTools.d.ts +1 -0
  26. package/esm/typings/src/types/Message.d.ts +49 -0
  27. package/esm/typings/src/types/ModelRequirements.d.ts +38 -14
  28. package/esm/typings/src/types/typeAliases.d.ts +23 -1
  29. package/esm/typings/src/utils/color/utils/colorToDataUrl.d.ts +2 -1
  30. package/esm/typings/src/utils/environment/$detectRuntimeEnvironment.d.ts +4 -4
  31. package/esm/typings/src/utils/environment/$isRunningInBrowser.d.ts +1 -1
  32. package/esm/typings/src/utils/environment/$isRunningInJest.d.ts +1 -1
  33. package/esm/typings/src/utils/environment/$isRunningInNode.d.ts +1 -1
  34. package/esm/typings/src/utils/environment/$isRunningInWebWorker.d.ts +1 -1
  35. package/esm/typings/src/utils/markdown/extractAllBlocksFromMarkdown.d.ts +2 -2
  36. package/esm/typings/src/utils/markdown/extractOneBlockFromMarkdown.d.ts +2 -2
  37. package/esm/typings/src/utils/random/$randomBase58.d.ts +12 -0
  38. package/esm/typings/src/version.d.ts +1 -1
  39. package/package.json +1 -1
  40. package/umd/index.umd.js +493 -164
  41. package/umd/index.umd.js.map +1 -1
  42. package/esm/typings/src/book-2.0/utils/generateGravatarUrl.d.ts +0 -10
package/esm/index.es.js CHANGED
@@ -27,7 +27,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
27
27
  * @generated
28
28
  * @see https://github.com/webgptorg/promptbook
29
29
  */
30
- const PROMPTBOOK_ENGINE_VERSION = '0.104.0-0';
30
+ const PROMPTBOOK_ENGINE_VERSION = '0.104.0-10';
31
31
  /**
32
32
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
33
33
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -37,6 +37,8 @@ const PROMPTBOOK_ENGINE_VERSION = '0.104.0-0';
37
37
  * Core Promptbook server configuration.
38
38
  *
39
39
  * This server is also used for auto-federation in the Agents Server.
40
+ *
41
+ * @public exported from `@promptbook/core`
40
42
  */
41
43
  const CORE_SERVER = {
42
44
  title: 'Promptbook Core',
@@ -3744,6 +3746,15 @@ function countUsage(llmTools) {
3744
3746
  return promptResult;
3745
3747
  };
3746
3748
  }
3749
+ if (llmTools.callImageGenerationModel !== undefined) {
3750
+ proxyTools.callImageGenerationModel = async (prompt) => {
3751
+ // console.info('[🚕] callImageGenerationModel through countTotalUsage');
3752
+ const promptResult = await llmTools.callImageGenerationModel(prompt);
3753
+ totalUsage = addUsage(totalUsage, promptResult.usage);
3754
+ spending.next(promptResult.usage);
3755
+ return promptResult;
3756
+ };
3757
+ }
3747
3758
  // <- Note: [🤖]
3748
3759
  return proxyTools;
3749
3760
  }
@@ -3853,6 +3864,12 @@ class MultipleLlmExecutionTools {
3853
3864
  callEmbeddingModel(prompt) {
3854
3865
  return this.callCommonModel(prompt);
3855
3866
  }
3867
+ /**
3868
+ * Calls the best available embedding model
3869
+ */
3870
+ callImageGenerationModel(prompt) {
3871
+ return this.callCommonModel(prompt);
3872
+ }
3856
3873
  // <- Note: [🤖]
3857
3874
  /**
3858
3875
  * Calls the best available model
@@ -3879,6 +3896,11 @@ class MultipleLlmExecutionTools {
3879
3896
  continue llm;
3880
3897
  }
3881
3898
  return await llmExecutionTools.callEmbeddingModel(prompt);
3899
+ case 'IMAGE_GENERATION':
3900
+ if (llmExecutionTools.callImageGenerationModel === undefined) {
3901
+ continue llm;
3902
+ }
3903
+ return await llmExecutionTools.callImageGenerationModel(prompt);
3882
3904
  // <- case [🤖]:
3883
3905
  default:
3884
3906
  throw new UnexpectedError(`Unknown model variant "${prompt.modelRequirements.modelVariant}" in ${llmExecutionTools.title}`);
@@ -6304,8 +6326,9 @@ async function executeAttempts(options) {
6304
6326
  $ongoingTaskResult.$resultString = $ongoingTaskResult.$completionResult.content;
6305
6327
  break variant;
6306
6328
  case 'EMBEDDING':
6329
+ case 'IMAGE_GENERATION':
6307
6330
  throw new PipelineExecutionError(spaceTrim$1((block) => `
6308
- Embedding model can not be used in pipeline
6331
+ ${modelRequirements.modelVariant} model can not be used in pipeline
6309
6332
 
6310
6333
  This should be catched during parsing
6311
6334
 
@@ -7964,6 +7987,114 @@ class DeleteCommitmentDefinition extends BaseCommitmentDefinition {
7964
7987
  * Note: [💞] Ignore a discrepancy between file name and entity name
7965
7988
  */
7966
7989
 
7990
+ /**
7991
+ * DICTIONARY commitment definition
7992
+ *
7993
+ * The DICTIONARY commitment defines specific terms and their meanings that the agent should use correctly
7994
+ * in its reasoning and responses. This ensures consistent terminology usage.
7995
+ *
7996
+ * Key features:
7997
+ * - Multiple DICTIONARY commitments are automatically merged into one
7998
+ * - Content is placed in a dedicated section of the system message
7999
+ * - Terms and definitions are stored in metadata.DICTIONARY for debugging
8000
+ * - Agent should use the defined terms correctly in responses
8001
+ *
8002
+ * Example usage in agent source:
8003
+ *
8004
+ * ```book
8005
+ * Legal Assistant
8006
+ *
8007
+ * PERSONA You are a knowledgeable legal assistant
8008
+ * DICTIONARY Misdemeanor is a minor wrongdoing or criminal offense
8009
+ * DICTIONARY Felony is a serious crime usually punishable by imprisonment for more than one year
8010
+ * DICTIONARY Tort is a civil wrong that causes harm or loss to another person, leading to legal liability
8011
+ * ```
8012
+ *
8013
+ * @private [🪔] Maybe export the commitments through some package
8014
+ */
8015
+ class DictionaryCommitmentDefinition extends BaseCommitmentDefinition {
8016
+ constructor() {
8017
+ super('DICTIONARY');
8018
+ }
8019
+ /**
8020
+ * Short one-line description of DICTIONARY.
8021
+ */
8022
+ get description() {
8023
+ return 'Define terms and their meanings for consistent terminology usage.';
8024
+ }
8025
+ /**
8026
+ * Icon for this commitment.
8027
+ */
8028
+ get icon() {
8029
+ return '📚';
8030
+ }
8031
+ /**
8032
+ * Markdown documentation for DICTIONARY commitment.
8033
+ */
8034
+ get documentation() {
8035
+ return spaceTrim$1(`
8036
+ # DICTIONARY
8037
+
8038
+ Defines specific terms and their meanings that the agent should use correctly in reasoning and responses.
8039
+
8040
+ ## Key aspects
8041
+
8042
+ - Multiple \`DICTIONARY\` commitments are merged together.
8043
+ - Terms are defined in the format: "Term is definition"
8044
+ - The agent should use these terms consistently in responses.
8045
+ - Definitions help ensure accurate and consistent terminology.
8046
+
8047
+ ## Examples
8048
+
8049
+ \`\`\`book
8050
+ Legal Assistant
8051
+
8052
+ PERSONA You are a knowledgeable legal assistant specializing in criminal law
8053
+ DICTIONARY Misdemeanor is a minor wrongdoing or criminal offense
8054
+ DICTIONARY Felony is a serious crime usually punishable by imprisonment for more than one year
8055
+ DICTIONARY Tort is a civil wrong that causes harm or loss to another person, leading to legal liability
8056
+ \`\`\`
8057
+
8058
+ \`\`\`book
8059
+ Medical Assistant
8060
+
8061
+ PERSONA You are a helpful medical assistant
8062
+ DICTIONARY Hypertension is persistently high blood pressure
8063
+ DICTIONARY Diabetes is a chronic condition that affects how the body processes blood sugar
8064
+ DICTIONARY Vaccine is a biological preparation that provides active immunity to a particular disease
8065
+ \`\`\`
8066
+ `);
8067
+ }
8068
+ applyToAgentModelRequirements(requirements, content) {
8069
+ var _a;
8070
+ const trimmedContent = content.trim();
8071
+ if (!trimmedContent) {
8072
+ return requirements;
8073
+ }
8074
+ // Get existing dictionary entries from metadata
8075
+ const existingDictionary = ((_a = requirements.metadata) === null || _a === void 0 ? void 0 : _a.DICTIONARY) || '';
8076
+ // Merge the new dictionary entry with existing entries
8077
+ const mergedDictionary = existingDictionary
8078
+ ? `${existingDictionary}\n${trimmedContent}`
8079
+ : trimmedContent;
8080
+ // Store the merged dictionary in metadata for debugging and inspection
8081
+ const updatedMetadata = {
8082
+ ...requirements.metadata,
8083
+ DICTIONARY: mergedDictionary,
8084
+ };
8085
+ // Create the dictionary section for the system message
8086
+ // Format: "# DICTIONARY\nTerm: definition\nTerm: definition..."
8087
+ const dictionarySection = `# DICTIONARY\n${mergedDictionary}`;
8088
+ return {
8089
+ ...this.appendToSystemMessage(requirements, dictionarySection),
8090
+ metadata: updatedMetadata,
8091
+ };
8092
+ }
8093
+ }
8094
+ /**
8095
+ * Note: [💞] Ignore a discrepancy between file name and entity name
8096
+ */
8097
+
7967
8098
  /**
7968
8099
  * FORMAT commitment definition
7969
8100
  *
@@ -10784,6 +10915,7 @@ const COMMITMENT_REGISTRY = [
10784
10915
  new DeleteCommitmentDefinition('CANCEL'),
10785
10916
  new DeleteCommitmentDefinition('DISCARD'),
10786
10917
  new DeleteCommitmentDefinition('REMOVE'),
10918
+ new DictionaryCommitmentDefinition(),
10787
10919
  new OpenCommitmentDefinition(),
10788
10920
  new ClosedCommitmentDefinition(),
10789
10921
  new UseBrowserCommitmentDefinition(),
@@ -10935,17 +11067,64 @@ function parseAgentSourceWithCommitments(agentSource) {
10935
11067
  };
10936
11068
  }
10937
11069
  const lines = agentSource.split('\n');
10938
- const agentName = (((_a = lines[0]) === null || _a === void 0 ? void 0 : _a.trim()) || null);
11070
+ let agentName = null;
11071
+ let agentNameLineIndex = -1;
11072
+ // Find the agent name: first non-empty line that is not a commitment and not a horizontal line
11073
+ for (let i = 0; i < lines.length; i++) {
11074
+ const line = lines[i];
11075
+ if (line === undefined) {
11076
+ continue;
11077
+ }
11078
+ const trimmed = line.trim();
11079
+ if (!trimmed) {
11080
+ continue;
11081
+ }
11082
+ const isHorizontal = HORIZONTAL_LINE_PATTERN.test(line);
11083
+ if (isHorizontal) {
11084
+ continue;
11085
+ }
11086
+ let isCommitment = false;
11087
+ for (const definition of COMMITMENT_REGISTRY) {
11088
+ const typeRegex = definition.createTypeRegex();
11089
+ const match = typeRegex.exec(trimmed);
11090
+ if (match && ((_a = match.groups) === null || _a === void 0 ? void 0 : _a.type)) {
11091
+ isCommitment = true;
11092
+ break;
11093
+ }
11094
+ }
11095
+ if (!isCommitment) {
11096
+ agentName = trimmed;
11097
+ agentNameLineIndex = i;
11098
+ break;
11099
+ }
11100
+ }
10939
11101
  const commitments = [];
10940
11102
  const nonCommitmentLines = [];
10941
- // Always add the first line (agent name) to non-commitment lines
10942
- if (lines[0] !== undefined) {
10943
- nonCommitmentLines.push(lines[0]);
11103
+ // Add lines before agentName that are horizontal lines (they are non-commitment)
11104
+ for (let i = 0; i < agentNameLineIndex; i++) {
11105
+ const line = lines[i];
11106
+ if (line === undefined) {
11107
+ continue;
11108
+ }
11109
+ const trimmed = line.trim();
11110
+ if (!trimmed) {
11111
+ continue;
11112
+ }
11113
+ const isHorizontal = HORIZONTAL_LINE_PATTERN.test(line);
11114
+ if (isHorizontal) {
11115
+ nonCommitmentLines.push(line);
11116
+ }
11117
+ // Note: Commitments before agentName are not added to nonCommitmentLines
11118
+ }
11119
+ // Add the agent name line to non-commitment lines
11120
+ if (agentNameLineIndex >= 0) {
11121
+ nonCommitmentLines.push(lines[agentNameLineIndex]);
10944
11122
  }
10945
11123
  // Parse commitments with multiline support
10946
11124
  let currentCommitment = null;
10947
- // Process lines starting from the second line (skip agent name)
10948
- for (let i = 1; i < lines.length; i++) {
11125
+ // Process lines starting from after the agent name line
11126
+ const startIndex = agentNameLineIndex >= 0 ? agentNameLineIndex + 1 : 0;
11127
+ for (let i = startIndex; i < lines.length; i++) {
10949
11128
  const line = lines[i];
10950
11129
  if (line === undefined) {
10951
11130
  continue;
@@ -11165,7 +11344,12 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
11165
11344
  };
11166
11345
  }
11167
11346
  // Apply each commitment in order using reduce-like pattern
11168
- for (const commitment of filteredCommitments) {
11347
+ for (let i = 0; i < filteredCommitments.length; i++) {
11348
+ const commitment = filteredCommitments[i];
11349
+ // CLOSED commitment should work only if its the last commitment in the book
11350
+ if (commitment.type === 'CLOSED' && i !== filteredCommitments.length - 1) {
11351
+ continue;
11352
+ }
11169
11353
  const definition = getCommitmentDefinition(commitment.type);
11170
11354
  if (definition) {
11171
11355
  try {
@@ -11260,44 +11444,6 @@ function normalizeTo_camelCase(text, _isFirstLetterCapital = false) {
11260
11444
  * TODO: [🌺] Use some intermediate util splitWords
11261
11445
  */
11262
11446
 
11263
- /**
11264
- * Generates a gravatar URL based on agent name for fallback avatar
11265
- *
11266
- * @param agentName The agent name to generate avatar for
11267
- * @returns Gravatar URL
11268
- *
11269
- * @private - [🤹] The fact that profile image is Gravatar is just implementation detail which should be hidden for consumer
11270
- */
11271
- function generateGravatarUrl(agentName) {
11272
- // Use a default name if none provided
11273
- const safeName = agentName || 'Anonymous Agent';
11274
- // Create a simple hash from the name for consistent avatar
11275
- let hash = 0;
11276
- for (let i = 0; i < safeName.length; i++) {
11277
- const char = safeName.charCodeAt(i);
11278
- hash = (hash << 5) - hash + char;
11279
- hash = hash & hash; // Convert to 32bit integer
11280
- }
11281
- const avatarId = Math.abs(hash).toString();
11282
- return `https://www.gravatar.com/avatar/${avatarId}?default=robohash&size=200&rating=x`;
11283
- }
11284
-
11285
- /**
11286
- * Generates an image for the agent to use as profile image
11287
- *
11288
- * @param agentName The agent name to generate avatar for
11289
- * @returns The placeholder profile image URL for the agent
11290
- *
11291
- * @public exported from `@promptbook/core`
11292
- */
11293
- function generatePlaceholderAgentProfileImageUrl(agentName) {
11294
- // Note: [🤹] The fact that profile image is Gravatar is just implementation detail which should be hidden for consumer
11295
- return generateGravatarUrl(agentName);
11296
- }
11297
- /**
11298
- * TODO: [🤹] Figure out best placeholder image generator https://i.pravatar.cc/1000?u=568
11299
- */
11300
-
11301
11447
  /**
11302
11448
  * Creates a Mermaid graph based on the promptbook
11303
11449
  *
@@ -11468,13 +11614,14 @@ function prompt(strings, ...values) {
11468
11614
  *
11469
11615
  * @public exported from `@promptbook/utils`
11470
11616
  */
11471
- const $isRunningInBrowser = new Function(`
11617
+ function $isRunningInBrowser() {
11472
11618
  try {
11473
- return this === window;
11474
- } catch (e) {
11619
+ return typeof window !== 'undefined' && typeof window.document !== 'undefined';
11620
+ }
11621
+ catch (e) {
11475
11622
  return false;
11476
11623
  }
11477
- `);
11624
+ }
11478
11625
  /**
11479
11626
  * TODO: [🎺]
11480
11627
  */
@@ -11486,13 +11633,15 @@ const $isRunningInBrowser = new Function(`
11486
11633
  *
11487
11634
  * @public exported from `@promptbook/utils`
11488
11635
  */
11489
- const $isRunningInJest = new Function(`
11636
+ function $isRunningInJest() {
11637
+ var _a;
11490
11638
  try {
11491
- return process.env.JEST_WORKER_ID !== undefined;
11492
- } catch (e) {
11639
+ return typeof process !== 'undefined' && ((_a = process.env) === null || _a === void 0 ? void 0 : _a.JEST_WORKER_ID) !== undefined;
11640
+ }
11641
+ catch (e) {
11493
11642
  return false;
11494
11643
  }
11495
- `);
11644
+ }
11496
11645
  /**
11497
11646
  * TODO: [🎺]
11498
11647
  */
@@ -11504,13 +11653,14 @@ const $isRunningInJest = new Function(`
11504
11653
  *
11505
11654
  * @public exported from `@promptbook/utils`
11506
11655
  */
11507
- const $isRunningInNode = new Function(`
11656
+ function $isRunningInNode() {
11508
11657
  try {
11509
- return this === global;
11510
- } catch (e) {
11658
+ return typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
11659
+ }
11660
+ catch (e) {
11511
11661
  return false;
11512
11662
  }
11513
- `);
11663
+ }
11514
11664
  /**
11515
11665
  * TODO: [🎺]
11516
11666
  */
@@ -11522,17 +11672,17 @@ const $isRunningInNode = new Function(`
11522
11672
  *
11523
11673
  * @public exported from `@promptbook/utils`
11524
11674
  */
11525
- const $isRunningInWebWorker = new Function(`
11675
+ function $isRunningInWebWorker() {
11526
11676
  try {
11527
- if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
11528
- return true;
11529
- } else {
11530
- return false;
11531
- }
11532
- } catch (e) {
11677
+ // Note: Check for importScripts which is specific to workers
11678
+ // and not available in the main browser thread
11679
+ return (typeof self !== 'undefined' &&
11680
+ typeof self.importScripts === 'function');
11681
+ }
11682
+ catch (e) {
11533
11683
  return false;
11534
11684
  }
11535
- `);
11685
+ }
11536
11686
  /**
11537
11687
  * TODO: [🎺]
11538
11688
  */
@@ -11775,10 +11925,6 @@ function parseAgentSource(agentSource) {
11775
11925
  const metaType = normalizeTo_camelCase(metaTypeRaw);
11776
11926
  meta[metaType] = spaceTrim$2(commitment.content.substring(metaTypeRaw.length));
11777
11927
  }
11778
- // Generate gravatar fallback if no meta image specified
11779
- if (!meta.image) {
11780
- meta.image = generatePlaceholderAgentProfileImageUrl(parseResult.agentName || '!!');
11781
- }
11782
11928
  // Generate fullname fallback if no meta fullname specified
11783
11929
  if (!meta.fullname) {
11784
11930
  meta.fullname = parseResult.agentName || createDefaultAgentName(agentSource);
@@ -11790,6 +11936,7 @@ function parseAgentSource(agentSource) {
11790
11936
  return {
11791
11937
  agentName: normalizeAgentName(parseResult.agentName || createDefaultAgentName(agentSource)),
11792
11938
  agentHash,
11939
+ permanentId: meta.id,
11793
11940
  personaDescription,
11794
11941
  initialMessage,
11795
11942
  meta,
@@ -11981,6 +12128,59 @@ const DEFAULT_BOOK = padBook(validateBook(spaceTrim$2(`
11981
12128
  // <- [🐱‍🚀] Buttons into genesis book
11982
12129
  // <- TODO: [🐱‍🚀] generateBookBoilerplate and deprecate `DEFAULT_BOOK`
11983
12130
 
12131
+ /**
12132
+ * Generates an image for the agent to use as profile image
12133
+ *
12134
+ * @param agentId - The permanent ID of the agent
12135
+ * @returns The placeholder profile image URL for the agent
12136
+ *
12137
+ * @public exported from `@promptbook/core`
12138
+ */
12139
+ function generatePlaceholderAgentProfileImageUrl(agentIdOrName, agentsServerUrl = CORE_SERVER.urls[0]) {
12140
+ if (typeof agentsServerUrl === 'string') {
12141
+ agentsServerUrl = new URL(agentsServerUrl);
12142
+ }
12143
+ return `${agentsServerUrl.href}agents/${agentIdOrName}/images/default-avatar.png`;
12144
+ }
12145
+ /**
12146
+ * TODO: [🤹] Figure out best placeholder image generator https://i.pravatar.cc/1000?u=568
12147
+ */
12148
+
12149
+ /**
12150
+ * Base58 characters
12151
+ */
12152
+ const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
12153
+ /**
12154
+ * Generates random base58 string
12155
+ *
12156
+ * Note: `$` is used to indicate that this function is not a pure function - it is not deterministic
12157
+ * Note: This function is cryptographically secure (it uses crypto.randomBytes internally)
12158
+ *
12159
+ * @param length - length of the string
12160
+ * @returns secure random base58 string
12161
+ *
12162
+ * @private internal helper function
12163
+ */
12164
+ function $randomBase58(length) {
12165
+ let result = '';
12166
+ while (result.length < length) {
12167
+ // Generate enough bytes to cover the remaining length, plus some extra buffer to reduce calls
12168
+ // But simply generating `length - result.length` is fine for small lengths
12169
+ const bytes = randomBytes(length - result.length);
12170
+ for (let i = 0; i < bytes.length; i++) {
12171
+ const byte = bytes[i];
12172
+ // 58 * 4 = 232
12173
+ // We discard values >= 232 to avoid modulo bias
12174
+ if (byte < 232) {
12175
+ result += BASE58_ALPHABET[byte % 58];
12176
+ if (result.length === length)
12177
+ break;
12178
+ }
12179
+ }
12180
+ }
12181
+ return result;
12182
+ }
12183
+
11984
12184
  // import { getTableName } from '../../../../../apps/agents-server/src/database/getTableName';
11985
12185
  // <- TODO: [🐱‍🚀] Prevent imports from `/apps` -> `/src`
11986
12186
  /**
@@ -12014,19 +12214,20 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12014
12214
  const { isVerbose = DEFAULT_IS_VERBOSE } = this.options || {};
12015
12215
  const selectResult = await this.supabaseClient
12016
12216
  .from(this.getTableName('Agent'))
12017
- .select('agentName,agentProfile');
12217
+ .select('agentName,agentProfile,permanentId')
12218
+ .is('deletedAt', null);
12018
12219
  if (selectResult.error) {
12019
12220
  throw new DatabaseError(spaceTrim((block) => `
12020
-
12221
+
12021
12222
  Error fetching agents from Supabase:
12022
-
12223
+
12023
12224
  ${block(selectResult.error.message)}
12024
12225
  `));
12025
12226
  }
12026
12227
  if (isVerbose) {
12027
12228
  console.info(`Found ${selectResult.data.length} agents in directory`);
12028
12229
  }
12029
- return selectResult.data.map(({ agentName, agentProfile }) => {
12230
+ return selectResult.data.map(({ agentName, agentProfile, permanentId }) => {
12030
12231
  if (isVerbose && agentProfile.agentName !== agentName) {
12031
12232
  console.warn(spaceTrim(`
12032
12233
  Agent name mismatch for agent "${agentName}". Using name from database.
@@ -12038,26 +12239,42 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12038
12239
  return {
12039
12240
  ...agentProfile,
12040
12241
  agentName,
12242
+ permanentId: permanentId || agentProfile.permanentId,
12041
12243
  };
12042
12244
  });
12043
12245
  }
12044
12246
  /**
12045
12247
  * [🐱‍🚀]@@@
12046
12248
  */
12047
- async getAgentSource(agentName) {
12249
+ async getAgentPermanentId(agentNameOrPermanentId) {
12250
+ const selectResult = await this.supabaseClient
12251
+ .from(this.getTableName('Agent'))
12252
+ .select('permanentId')
12253
+ .or(`agentName.eq.${agentNameOrPermanentId},permanentId.eq.${agentNameOrPermanentId}`)
12254
+ .single();
12255
+ if (selectResult.error || !selectResult.data) {
12256
+ throw new NotFoundError(`Agent with name not id "${agentNameOrPermanentId}" not found`);
12257
+ }
12258
+ return selectResult.data.permanentId;
12259
+ }
12260
+ /**
12261
+ * [🐱‍🚀]@@@
12262
+ */
12263
+ async getAgentSource(agentNameOrPermanentId) {
12048
12264
  const selectResult = await this.supabaseClient
12049
12265
  .from(this.getTableName('Agent'))
12050
12266
  .select('agentSource')
12051
- .eq('agentName', agentName);
12267
+ .or(`agentName.eq.${agentNameOrPermanentId},permanentId.eq.${agentNameOrPermanentId}`)
12268
+ .is('deletedAt', null);
12052
12269
  if (selectResult.data && selectResult.data.length === 0) {
12053
- throw new NotFoundError(`Agent "${agentName}" not found`);
12270
+ throw new NotFoundError(`Agent "${agentNameOrPermanentId}" not found`);
12054
12271
  }
12055
12272
  else if (selectResult.data && selectResult.data.length > 1) {
12056
- throw new UnexpectedError(`More agents with agentName="${agentName}" found`);
12273
+ throw new UnexpectedError(`More agents with name or id "${agentNameOrPermanentId}" found`);
12057
12274
  }
12058
12275
  else if (selectResult.error) {
12059
12276
  throw new DatabaseError(spaceTrim((block) => `
12060
- Error fetching agent "${agentName}" from Supabase:
12277
+ Error fetching agent "${agentNameOrPermanentId}" from Supabase:
12061
12278
 
12062
12279
  ${block(selectResult.error.message)}
12063
12280
  `));
@@ -12070,12 +12287,26 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12070
12287
  * Note: You can set 'PARENT' in the agent source to inherit from another agent in the collection.
12071
12288
  */
12072
12289
  async createAgent(agentSource) {
12073
- const agentProfile = parseAgentSource(agentSource);
12290
+ let agentProfile = parseAgentSource(agentSource);
12074
12291
  // <- TODO: [🕛]
12292
+ // 1. Extract permanentId from the source if present
12293
+ let { permanentId } = agentProfile;
12294
+ // 2. Remove META ID from the source
12295
+ const lines = agentSource.split('\n');
12296
+ const strippedLines = lines.filter((line) => !line.trim().startsWith('META ID '));
12297
+ if (lines.length !== strippedLines.length) {
12298
+ agentSource = strippedLines.join('\n');
12299
+ // 3. Re-parse the agent source to get the correct hash and other info
12300
+ agentProfile = parseAgentSource(agentSource);
12301
+ }
12075
12302
  const { agentName, agentHash } = agentProfile;
12303
+ if (!permanentId) {
12304
+ permanentId = $randomBase58(14);
12305
+ }
12076
12306
  const insertAgentResult = await this.supabaseClient.from(this.getTableName('Agent')).insert({
12077
12307
  agentName,
12078
12308
  agentHash,
12309
+ permanentId,
12079
12310
  agentProfile,
12080
12311
  createdAt: new Date().toISOString(),
12081
12312
  updatedAt: null,
@@ -12093,27 +12324,29 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12093
12324
  await this.supabaseClient.from(this.getTableName('AgentHistory')).insert({
12094
12325
  createdAt: new Date().toISOString(),
12095
12326
  agentName,
12327
+ permanentId,
12096
12328
  agentHash,
12097
12329
  previousAgentHash: null,
12098
12330
  agentSource,
12099
12331
  promptbookEngineVersion: PROMPTBOOK_ENGINE_VERSION,
12100
12332
  });
12101
12333
  // <- TODO: [🧠] What to do with `insertAgentHistoryResult.error`, ignore? wait?
12102
- return agentProfile;
12334
+ return { ...agentProfile, permanentId };
12103
12335
  }
12104
12336
  /**
12105
12337
  * Updates an existing agent in the collection
12106
12338
  */
12107
- async updateAgentSource(agentName, agentSource) {
12339
+ async updateAgentSource(permanentId, agentSource) {
12340
+ console.log('!!! updateAgentSource', { permanentId });
12108
12341
  const selectPreviousAgentResult = await this.supabaseClient
12109
12342
  .from(this.getTableName('Agent'))
12110
- .select('agentHash,agentName')
12111
- .eq('agentName', agentName)
12343
+ .select('agentHash,agentName,permanentId')
12344
+ .eq('permanentId', permanentId)
12112
12345
  .single();
12113
12346
  if (selectPreviousAgentResult.error) {
12114
12347
  throw new DatabaseError(spaceTrim((block) => `
12115
12348
 
12116
- Error fetching agent "${agentName}" from Supabase:
12349
+ Error fetching agent "${permanentId}" from Supabase:
12117
12350
 
12118
12351
  ${block(selectPreviousAgentResult.error.message)}
12119
12352
  `));
@@ -12121,26 +12354,48 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12121
12354
  }
12122
12355
  selectPreviousAgentResult.data.agentName;
12123
12356
  const previousAgentHash = selectPreviousAgentResult.data.agentHash;
12124
- const agentProfile = parseAgentSource(agentSource);
12357
+ const previousPermanentId = selectPreviousAgentResult.data.permanentId;
12358
+ let agentProfile = parseAgentSource(agentSource);
12125
12359
  // <- TODO: [🕛]
12126
- const { agentHash } = agentProfile;
12360
+ // 1. Extract permanentId from the source if present
12361
+ let { permanentId: newPermanentId } = agentProfile;
12362
+ // 2. Remove META ID from the source
12363
+ const lines = agentSource.split('\n');
12364
+ const strippedLines = lines.filter((line) => !line.trim().startsWith('META ID '));
12365
+ if (lines.length !== strippedLines.length) {
12366
+ agentSource = strippedLines.join('\n');
12367
+ // 3. Re-parse the agent source to get the correct hash and other info
12368
+ agentProfile = parseAgentSource(agentSource);
12369
+ }
12370
+ const { agentHash, agentName } = agentProfile;
12371
+ if (!newPermanentId && previousPermanentId) {
12372
+ newPermanentId = previousPermanentId;
12373
+ }
12374
+ if (!newPermanentId) {
12375
+ newPermanentId = $randomBase58(14);
12376
+ }
12377
+ if (newPermanentId !== permanentId) {
12378
+ // [🧠] Should be allowed to change permanentId?
12379
+ throw new UnexpectedError(`Permanent ID mismatch: "${permanentId}" (argument) !== "${newPermanentId}" (in source)`);
12380
+ }
12127
12381
  const updateAgentResult = await this.supabaseClient
12128
12382
  .from(this.getTableName('Agent'))
12129
12383
  .update({
12130
12384
  // TODO: [🐱‍🚀] Compare not update> agentName: agentProfile.agentName || '[🐱‍🚀]' /* <- TODO: [🐱‍🚀] Remove */,
12385
+ permanentId,
12131
12386
  agentProfile,
12132
12387
  updatedAt: new Date().toISOString(),
12133
12388
  agentHash: agentProfile.agentHash,
12134
12389
  agentSource,
12135
12390
  promptbookEngineVersion: PROMPTBOOK_ENGINE_VERSION,
12136
12391
  })
12137
- .eq('agentName', agentName);
12392
+ .eq('permanentId', permanentId);
12138
12393
  // console.log('[🐱‍🚀] updateAgent', updateResult);
12139
12394
  // console.log('[🐱‍🚀] old', oldAgentSource);
12140
12395
  // console.log('[🐱‍🚀] new', newAgentSource);
12141
12396
  if (updateAgentResult.error) {
12142
12397
  throw new DatabaseError(spaceTrim((block) => `
12143
- Error updating agent "${agentName}" in Supabase:
12398
+ Error updating agent "${permanentId}" in Supabase:
12144
12399
 
12145
12400
  ${block(updateAgentResult.error.message)}
12146
12401
  `));
@@ -12148,6 +12403,7 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12148
12403
  await this.supabaseClient.from(this.getTableName('AgentHistory')).insert({
12149
12404
  createdAt: new Date().toISOString(),
12150
12405
  agentName,
12406
+ permanentId,
12151
12407
  agentHash,
12152
12408
  previousAgentHash,
12153
12409
  agentSource,
@@ -12155,101 +12411,119 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12155
12411
  });
12156
12412
  // <- TODO: [🧠] What to do with `insertAgentHistoryResult.error`, ignore? wait?
12157
12413
  }
12158
- // TODO: [🐱‍🚀] public async getAgentSourceSubject(agentName: string_agent_name): Promise<BehaviorSubject<string_book>>
12414
+ // TODO: [🐱‍🚀] public async getAgentSourceSubject(permanentId: string_agent_permanent_id): Promise<BehaviorSubject<string_book>>
12159
12415
  // Use Supabase realtime logic
12160
12416
  /**
12161
- * Deletes an agent from the collection
12417
+ * List agents that are soft deleted (deletedAt IS NOT NULL)
12162
12418
  */
12163
- async deleteAgent(agentName) {
12164
- const deleteResult = await this.supabaseClient
12419
+ async listDeletedAgents() {
12420
+ const { isVerbose = DEFAULT_IS_VERBOSE } = this.options || {};
12421
+ const selectResult = await this.supabaseClient
12165
12422
  .from(this.getTableName('Agent'))
12166
- .delete()
12167
- .eq('agentName', agentName);
12168
- if (deleteResult.error) {
12423
+ .select('agentName,agentProfile,permanentId')
12424
+ .not('deletedAt', 'is', null);
12425
+ if (selectResult.error) {
12169
12426
  throw new DatabaseError(spaceTrim((block) => `
12170
- Error deleting agent "${agentName}" from Supabase:
12171
-
12172
- ${block(deleteResult.error.message)}
12173
- `));
12427
+ Error fetching deleted agents from Supabase:
12428
+
12429
+ ${block(selectResult.error.message)}
12430
+ `));
12431
+ }
12432
+ if (isVerbose) {
12433
+ console.info(`Found ${selectResult.data.length} deleted agents in directory`);
12174
12434
  }
12435
+ return selectResult.data.map(({ agentName, agentProfile, permanentId }) => {
12436
+ if (isVerbose && agentProfile.agentName !== agentName) {
12437
+ console.warn(spaceTrim(`
12438
+ Agent name mismatch for agent "${agentName}". Using name from database.
12439
+
12440
+ agentName: "${agentName}"
12441
+ agentProfile.agentName: "${agentProfile.agentName}"
12442
+ `));
12443
+ }
12444
+ return {
12445
+ ...agentProfile,
12446
+ agentName,
12447
+ permanentId: permanentId || agentProfile.permanentId,
12448
+ };
12449
+ });
12175
12450
  }
12176
12451
  /**
12177
12452
  * List history of an agent
12178
12453
  */
12179
- async listAgentHistory(agentName) {
12454
+ async listAgentHistory(permanentId) {
12180
12455
  const result = await this.supabaseClient
12181
12456
  .from(this.getTableName('AgentHistory'))
12182
12457
  .select('id, createdAt, agentHash, promptbookEngineVersion')
12183
- .eq('agentName', agentName)
12458
+ .eq('permanentId', permanentId)
12184
12459
  .order('createdAt', { ascending: false });
12185
12460
  if (result.error) {
12186
12461
  throw new DatabaseError(spaceTrim((block) => `
12187
- Error listing history for agent "${agentName}" from Supabase:
12188
-
12462
+ Error listing history for agent "${permanentId}" from Supabase:
12463
+
12189
12464
  ${block(result.error.message)}
12190
12465
  `));
12191
12466
  }
12192
12467
  return result.data;
12193
12468
  }
12194
12469
  /**
12195
- * List agents that are in history but not in the active agents list
12470
+ * Restore a soft-deleted agent by setting deletedAt to NULL
12196
12471
  */
12197
- async listDeletedAgents() {
12198
- const historyNamesResult = await this.supabaseClient.from(this.getTableName('AgentHistory')).select('agentName');
12199
- const currentNamesResult = await this.supabaseClient.from(this.getTableName('Agent')).select('agentName');
12200
- if (historyNamesResult.error) {
12201
- throw new DatabaseError(spaceTrim((block) => `
12202
- Error fetching agent history names from Supabase:
12203
-
12204
- ${block(historyNamesResult.error.message)}
12205
- `));
12206
- }
12207
- if (currentNamesResult.error) {
12472
+ async restoreAgent(permanentId) {
12473
+ const updateResult = await this.supabaseClient
12474
+ .from(this.getTableName('Agent'))
12475
+ .update({ deletedAt: null })
12476
+ .eq('permanentId', permanentId)
12477
+ .not('deletedAt', 'is', null);
12478
+ if (updateResult.error) {
12208
12479
  throw new DatabaseError(spaceTrim((block) => `
12209
- Error fetching current agent names from Supabase:
12210
-
12211
- ${block(currentNamesResult.error.message)}
12480
+ Error restoring agent "${permanentId}" from Supabase:
12481
+
12482
+ ${block(updateResult.error.message)}
12212
12483
  `));
12213
12484
  }
12214
- const currentNames = new Set(currentNamesResult.data.map((d) => d.agentName));
12215
- const deletedNames = new Set();
12216
- for (const { agentName } of historyNamesResult.data) {
12217
- if (!currentNames.has(agentName)) {
12218
- deletedNames.add(agentName);
12219
- }
12220
- }
12221
- return Array.from(deletedNames);
12222
12485
  }
12223
12486
  /**
12224
- * Restore an agent from history
12487
+ * Restore an agent from a specific history entry
12488
+ *
12489
+ * This will update the current agent with the source from the history entry
12225
12490
  */
12226
- async restoreAgent(historyId) {
12491
+ async restoreAgentFromHistory(historyId) {
12492
+ // First, get the history entry
12227
12493
  const historyResult = await this.supabaseClient
12228
12494
  .from(this.getTableName('AgentHistory'))
12229
- .select('*')
12495
+ .select('permanentId, agentSource')
12230
12496
  .eq('id', historyId)
12231
12497
  .single();
12232
12498
  if (historyResult.error) {
12233
12499
  throw new DatabaseError(spaceTrim((block) => `
12234
- Error fetching agent history item "${historyId}" from Supabase:
12235
-
12500
+ Error fetching history entry with id "${historyId}" from Supabase:
12501
+
12236
12502
  ${block(historyResult.error.message)}
12237
12503
  `));
12238
12504
  }
12239
- const { agentName, agentSource } = historyResult.data;
12240
- // Check if agent exists
12241
- const agentResult = await this.supabaseClient
12242
- .from(this.getTableName('Agent'))
12243
- .select('id')
12244
- .eq('agentName', agentName)
12245
- .single();
12246
- if (agentResult.data) {
12247
- // Update
12248
- await this.updateAgentSource(agentName, agentSource);
12505
+ if (!historyResult.data) {
12506
+ throw new NotFoundError(`History entry with id "${historyId}" not found`);
12249
12507
  }
12250
- else {
12251
- // Insert (Restore from deleted)
12252
- await this.createAgent(agentSource);
12508
+ const { permanentId, agentSource } = historyResult.data;
12509
+ // Update the agent with the source from the history entry
12510
+ await this.updateAgentSource(permanentId, agentSource);
12511
+ }
12512
+ /**
12513
+ * Soft delete an agent by setting deletedAt to current timestamp
12514
+ */
12515
+ async deleteAgent(permanentId) {
12516
+ const updateResult = await this.supabaseClient
12517
+ .from(this.getTableName('Agent'))
12518
+ .update({ deletedAt: new Date().toISOString() })
12519
+ .eq('permanentId', permanentId)
12520
+ .is('deletedAt', null);
12521
+ if (updateResult.error) {
12522
+ throw new DatabaseError(spaceTrim((block) => `
12523
+ Error deleting agent "${permanentId}" from Supabase:
12524
+
12525
+ ${block(updateResult.error.message)}
12526
+ `));
12253
12527
  }
12254
12528
  }
12255
12529
  /**
@@ -13939,11 +14213,7 @@ const modelCommandParser = {
13939
14213
  // TODO: [🚜] DRY
13940
14214
  if ($taskJson.modelRequirements[command.key] !== undefined) {
13941
14215
  if ($taskJson.modelRequirements[command.key] === command.value) {
13942
- console.warn(`Multiple commands \`MODEL ${{
13943
- modelName: 'NAME',
13944
- modelVariant: 'VARIANT',
13945
- maxTokens: '???',
13946
- }[command.key]} ${command.value}\` in the task "${$taskJson.title || $taskJson.name}"`);
14216
+ console.warn(`Multiple commands \`MODEL ${command.key} ${command.value}\` in the task "${$taskJson.title || $taskJson.name}"`);
13947
14217
  // <- TODO: [🏮] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
13948
14218
  }
13949
14219
  else {
@@ -16467,7 +16737,7 @@ function $registeredLlmToolsMessage() {
16467
16737
  ${i + 1}) **${title}** \`${className}\` from \`${packageName}\`
16468
16738
  ${morePieces.join('; ')}
16469
16739
  `);
16470
- if ($isRunningInNode) {
16740
+ if ($isRunningInNode()) {
16471
16741
  if (isInstalled && isFullyConfigured) {
16472
16742
  providerMessage = colors.green(providerMessage);
16473
16743
  }
@@ -16672,6 +16942,9 @@ function cacheLlmTools(llmTools, options = {}) {
16672
16942
  case 'EMBEDDING':
16673
16943
  promptResult = await llmTools.callEmbeddingModel(prompt);
16674
16944
  break variant;
16945
+ case 'IMAGE_GENERATION':
16946
+ promptResult = await llmTools.callImageGenerationModel(prompt);
16947
+ break variant;
16675
16948
  // <- case [🤖]:
16676
16949
  default:
16677
16950
  throw new PipelineExecutionError(`Unknown model variant "${prompt.modelRequirements.modelVariant}"`);
@@ -16708,12 +16981,13 @@ function cacheLlmTools(llmTools, options = {}) {
16708
16981
  }
16709
16982
  }
16710
16983
  catch (error) {
16984
+ assertsError(error);
16711
16985
  // If validation throws an unexpected error, don't cache
16712
16986
  shouldCache = false;
16713
16987
  if (isVerbose) {
16714
16988
  console.info('Not caching result due to validation error for key:', key, {
16715
16989
  content: promptResult.content,
16716
- validationError: error instanceof Error ? error.message : String(error),
16990
+ validationError: serializeError(error),
16717
16991
  });
16718
16992
  }
16719
16993
  }
@@ -16759,6 +17033,11 @@ function cacheLlmTools(llmTools, options = {}) {
16759
17033
  return /* not await */ callCommonModel(prompt);
16760
17034
  };
16761
17035
  }
17036
+ if (llmTools.callImageGenerationModel !== undefined) {
17037
+ proxyTools.callImageGenerationModel = async (prompt) => {
17038
+ return /* not await */ callCommonModel(prompt);
17039
+ };
17040
+ }
16762
17041
  // <- Note: [🤖]
16763
17042
  return proxyTools;
16764
17043
  }
@@ -16797,6 +17076,11 @@ function limitTotalUsage(llmTools, options = {}) {
16797
17076
  throw new LimitReachedError('Cannot call `callEmbeddingModel` because you are not allowed to spend any cost');
16798
17077
  };
16799
17078
  }
17079
+ if (proxyTools.callImageGenerationModel !== undefined) {
17080
+ proxyTools.callImageGenerationModel = async (prompt) => {
17081
+ throw new LimitReachedError('Cannot call `callImageGenerationModel` because you are not allowed to spend any cost');
17082
+ };
17083
+ }
16800
17084
  // <- Note: [🤖]
16801
17085
  return proxyTools;
16802
17086
  }
@@ -17868,7 +18152,7 @@ class OpenAiCompatibleExecutionTools {
17868
18152
  let threadMessages = [];
17869
18153
  if ('thread' in prompt && Array.isArray(prompt.thread)) {
17870
18154
  threadMessages = prompt.thread.map((msg) => ({
17871
- role: msg.role === 'assistant' ? 'assistant' : 'user',
18155
+ role: msg.sender === 'assistant' ? 'assistant' : 'user',
17872
18156
  content: msg.content,
17873
18157
  }));
17874
18158
  }
@@ -18281,13 +18565,14 @@ class OpenAiCompatibleExecutionTools {
18281
18565
  const modelName = currentModelRequirements.modelName || this.getDefaultImageGenerationModel().modelName;
18282
18566
  const modelSettings = {
18283
18567
  model: modelName,
18284
- // size: currentModelRequirements.size,
18285
- // quality: currentModelRequirements.quality,
18286
- // style: currentModelRequirements.style,
18568
+ size: currentModelRequirements.size,
18569
+ quality: currentModelRequirements.quality,
18570
+ style: currentModelRequirements.style,
18287
18571
  };
18288
18572
  const rawPromptContent = templateParameters(content, { ...parameters, modelName });
18289
18573
  const rawRequest = {
18290
18574
  ...modelSettings,
18575
+ size: modelSettings.size || '1024x1024',
18291
18576
  prompt: rawPromptContent,
18292
18577
  user: (_a = this.options.userId) === null || _a === void 0 ? void 0 : _a.toString(),
18293
18578
  response_format: 'url', // TODO: [🧠] Maybe allow b64_json
@@ -19393,9 +19678,52 @@ class Agent extends AgentLlmExecutionTools {
19393
19678
  ${block(result.content)}
19394
19679
 
19395
19680
  `);
19681
+ // Extract knowledge
19682
+ let knowledgeBlock = '';
19683
+ try {
19684
+ const extractionPrompt = {
19685
+ title: 'Knowledge Extraction',
19686
+ modelRequirements: {
19687
+ modelVariant: 'CHAT',
19688
+ },
19689
+ content: spaceTrim$2((block) => `
19690
+ You are an AI agent that is learning from a conversation.
19691
+
19692
+ Here is the conversation so far:
19693
+
19694
+ User: ${block(prompt.content)}
19695
+ Agent: ${block(result.content)}
19696
+
19697
+ Extract any new knowledge, facts, or important information that should be remembered for future interactions.
19698
+ Format the output as a list of KNOWLEDGE blocks.
19699
+ If there is no new knowledge, return nothing.
19700
+
19701
+ Example output:
19702
+ KNOWLEDGE The user's name is Alice.
19703
+ KNOWLEDGE The project deadline is next Friday.
19704
+ `),
19705
+ pipelineUrl: 'https://github.com/webgptorg/promptbook/blob/main/prompts/knowledge-extraction.ptbk.md',
19706
+ parameters: {},
19707
+ };
19708
+ if (this.options.llmTools.callChatModel) {
19709
+ const extractionResult = await this.options.llmTools.callChatModel(extractionPrompt);
19710
+ const extractedContent = extractionResult.content;
19711
+ if (extractedContent.includes('KNOWLEDGE')) {
19712
+ knowledgeBlock = '\n\n' + spaceTrim$2(extractedContent);
19713
+ }
19714
+ }
19715
+ else {
19716
+ // TODO: [🧠] Fallback to callChatModelStream if callChatModel is not available
19717
+ }
19718
+ }
19719
+ catch (error) {
19720
+ if (this.options.isVerbose) {
19721
+ console.warn('Failed to extract knowledge', error);
19722
+ }
19723
+ }
19396
19724
  // Append to the current source
19397
19725
  const currentSource = this.agentSource.value;
19398
- const newSource = padBook(validateBook(spaceTrim$2(currentSource) + '\n\n' + learningExample));
19726
+ const newSource = padBook(validateBook(spaceTrim$2(currentSource) + '\n\n' + learningExample + knowledgeBlock));
19399
19727
  // Update the source (which will trigger the subscription and update the underlying tools)
19400
19728
  this.agentSource.next(newSource);
19401
19729
  return result;
@@ -21164,5 +21492,5 @@ function $generateBookBoilerplate(options) {
21164
21492
  * TODO: [🤶] Maybe export through `@promptbook/utils` or `@promptbook/random` package
21165
21493
  */
21166
21494
 
21167
- export { $bookTranspilersRegister, $generateBookBoilerplate, $llmToolsMetadataRegister, $llmToolsRegister, $scrapersMetadataRegister, $scrapersRegister, ADMIN_EMAIL, ADMIN_GITHUB_NAME, API_REQUEST_TIMEOUT, AUTO_FEDERATED_AGENT_SERVER_URLS, AbstractFormatError, Agent, AgentCollectionInSupabase, AgentLlmExecutionTools, AuthenticationError, BIG_DATASET_TRESHOLD, BOOK_LANGUAGE_VERSION, BlackholeStorage, BoilerplateError, BoilerplateFormfactorDefinition, CLAIM, CLI_APP_ID, CallbackInterfaceTools, ChatbotFormfactorDefinition, CollectionError, CompletionFormfactorDefinition, CsvFormatError, CsvFormatParser, DEFAULT_AGENTS_DIRNAME, DEFAULT_BOOK, DEFAULT_BOOKS_DIRNAME, DEFAULT_BOOK_OUTPUT_PARAMETER_NAME, DEFAULT_BOOK_TITLE, DEFAULT_CSV_SETTINGS, DEFAULT_DOWNLOAD_CACHE_DIRNAME, DEFAULT_EXECUTION_CACHE_DIRNAME, DEFAULT_GET_PIPELINE_COLLECTION_FUNCTION_NAME, DEFAULT_INTERMEDIATE_FILES_STRATEGY, DEFAULT_IS_AUTO_INSTALLED, DEFAULT_IS_VERBOSE, DEFAULT_MAX_EXECUTION_ATTEMPTS, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, DEFAULT_MAX_PARALLEL_COUNT, DEFAULT_MAX_REQUESTS_PER_MINUTE, DEFAULT_PIPELINE_COLLECTION_BASE_FILENAME, DEFAULT_PROMPT_TASK_TITLE, DEFAULT_REMOTE_SERVER_URL, DEFAULT_SCRAPE_CACHE_DIRNAME, DEFAULT_TASK_SIMULATED_DURATION_MS, DEFAULT_TASK_TITLE, DatabaseError, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, FAILED_VALUE_PLACEHOLDER, FORMFACTOR_DEFINITIONS, FormattedBookInMarkdownTranspiler, GENERIC_PIPELINE_INTERFACE, GeneratorFormfactorDefinition, GenericFormfactorDefinition, ImageGeneratorFormfactorDefinition, KnowledgeScrapeError, LimitReachedError, MANDATORY_CSV_SETTINGS, MAX_FILENAME_LENGTH, MODEL_ORDERS, MODEL_TRUST_LEVELS, MODEL_VARIANTS, MatcherFormfactorDefinition, MemoryStorage, MissingToolsError, MultipleLlmExecutionTools, NAME, NonTaskSectionTypes, NotAllowed, NotFoundError, NotYetImplementedCommitmentDefinition, NotYetImplementedError, ORDER_OF_PIPELINE_JSON, OpenAiSdkTranspiler, PADDING_LINES, PENDING_VALUE_PLACEHOLDER, PLAYGROUND_APP_ID, PROMPTBOOK_CHAT_COLOR, PROMPTBOOK_COLOR, PROMPTBOOK_ENGINE_VERSION, PROMPTBOOK_ERRORS, PROMPTBOOK_LOGO_URL, PROMPTBOOK_SYNTAX_COLORS, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, PromptbookFetchError, REMOTE_SERVER_URLS, RESERVED_PARAMETER_NAMES, RemoteAgent, SET_IS_VERBOSE, SectionTypes, SheetsFormfactorDefinition, TaskTypes, TextFormatParser, TranslatorFormfactorDefinition, UNCERTAIN_USAGE, UNCERTAIN_ZERO_VALUE, USER_CHAT_COLOR, UnexpectedError, WrappedError, ZERO_USAGE, ZERO_VALUE, _AgentMetadata, _AgentRegistration, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _BoilerplateScraperMetadataRegistration, _DeepseekMetadataRegistration, _DocumentScraperMetadataRegistration, _GoogleMetadataRegistration, _LegacyDocumentScraperMetadataRegistration, _MarkdownScraperMetadataRegistration, _MarkitdownScraperMetadataRegistration, _OllamaMetadataRegistration, _OpenAiAssistantMetadataRegistration, _OpenAiCompatibleMetadataRegistration, _OpenAiMetadataRegistration, _PdfScraperMetadataRegistration, _WebsiteScraperMetadataRegistration, aboutPromptbookInformation, addUsage, book, cacheLlmTools, compilePipeline, computeAgentHash, computeCosineSimilarity, countUsage, createAgentLlmExecutionTools, createAgentModelRequirements, createAgentModelRequirementsWithCommitments, createBasicAgentModelRequirements, createDefaultAgentName, createEmptyAgentModelRequirements, createLlmToolsFromConfiguration, createPipelineCollectionFromJson, createPipelineCollectionFromPromise, createPipelineCollectionFromUrl, createPipelineExecutor, createPipelineSubcollection, embeddingVectorToString, executionReportJsonToString, extractParameterNamesFromTask, filterModels, generatePlaceholderAgentProfileImageUrl, getAllCommitmentDefinitions, getAllCommitmentTypes, getCommitmentDefinition, getGroupedCommitmentDefinitions, getPipelineInterface, getSingleLlmExecutionTools, identificationToPromptbookToken, isCommitmentSupported, isPassingExpectations, isPipelineImplementingInterface, isPipelineInterfacesEqual, isPipelinePrepared, isValidBook, isValidPipelineString, joinLlmExecutionTools, limitTotalUsage, makeKnowledgeSourceHandler, migratePipeline, normalizeAgentName, padBook, parseAgentSource, parseParameters, parsePipeline, pipelineCollectionToJson, pipelineJsonToString, prepareKnowledgePieces, preparePersona, preparePipeline, prettifyPipelineString, promptbookFetch, promptbookTokenToIdentification, unpreparePipeline, usageToHuman, usageToWorktime, validateBook, validatePipeline, validatePipelineString };
21495
+ export { $bookTranspilersRegister, $generateBookBoilerplate, $llmToolsMetadataRegister, $llmToolsRegister, $scrapersMetadataRegister, $scrapersRegister, ADMIN_EMAIL, ADMIN_GITHUB_NAME, API_REQUEST_TIMEOUT, AUTO_FEDERATED_AGENT_SERVER_URLS, AbstractFormatError, Agent, AgentCollectionInSupabase, AgentLlmExecutionTools, AuthenticationError, BIG_DATASET_TRESHOLD, BOOK_LANGUAGE_VERSION, BlackholeStorage, BoilerplateError, BoilerplateFormfactorDefinition, CLAIM, CLI_APP_ID, CORE_SERVER, CallbackInterfaceTools, ChatbotFormfactorDefinition, CollectionError, CompletionFormfactorDefinition, CsvFormatError, CsvFormatParser, DEFAULT_AGENTS_DIRNAME, DEFAULT_BOOK, DEFAULT_BOOKS_DIRNAME, DEFAULT_BOOK_OUTPUT_PARAMETER_NAME, DEFAULT_BOOK_TITLE, DEFAULT_CSV_SETTINGS, DEFAULT_DOWNLOAD_CACHE_DIRNAME, DEFAULT_EXECUTION_CACHE_DIRNAME, DEFAULT_GET_PIPELINE_COLLECTION_FUNCTION_NAME, DEFAULT_INTERMEDIATE_FILES_STRATEGY, DEFAULT_IS_AUTO_INSTALLED, DEFAULT_IS_VERBOSE, DEFAULT_MAX_EXECUTION_ATTEMPTS, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, DEFAULT_MAX_PARALLEL_COUNT, DEFAULT_MAX_REQUESTS_PER_MINUTE, DEFAULT_PIPELINE_COLLECTION_BASE_FILENAME, DEFAULT_PROMPT_TASK_TITLE, DEFAULT_REMOTE_SERVER_URL, DEFAULT_SCRAPE_CACHE_DIRNAME, DEFAULT_TASK_SIMULATED_DURATION_MS, DEFAULT_TASK_TITLE, DatabaseError, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, FAILED_VALUE_PLACEHOLDER, FORMFACTOR_DEFINITIONS, FormattedBookInMarkdownTranspiler, GENERIC_PIPELINE_INTERFACE, GeneratorFormfactorDefinition, GenericFormfactorDefinition, ImageGeneratorFormfactorDefinition, KnowledgeScrapeError, LimitReachedError, MANDATORY_CSV_SETTINGS, MAX_FILENAME_LENGTH, MODEL_ORDERS, MODEL_TRUST_LEVELS, MODEL_VARIANTS, MatcherFormfactorDefinition, MemoryStorage, MissingToolsError, MultipleLlmExecutionTools, NAME, NonTaskSectionTypes, NotAllowed, NotFoundError, NotYetImplementedCommitmentDefinition, NotYetImplementedError, ORDER_OF_PIPELINE_JSON, OpenAiSdkTranspiler, PADDING_LINES, PENDING_VALUE_PLACEHOLDER, PLAYGROUND_APP_ID, PROMPTBOOK_CHAT_COLOR, PROMPTBOOK_COLOR, PROMPTBOOK_ENGINE_VERSION, PROMPTBOOK_ERRORS, PROMPTBOOK_LOGO_URL, PROMPTBOOK_SYNTAX_COLORS, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, PromptbookFetchError, REMOTE_SERVER_URLS, RESERVED_PARAMETER_NAMES, RemoteAgent, SET_IS_VERBOSE, SectionTypes, SheetsFormfactorDefinition, TaskTypes, TextFormatParser, TranslatorFormfactorDefinition, UNCERTAIN_USAGE, UNCERTAIN_ZERO_VALUE, USER_CHAT_COLOR, UnexpectedError, WrappedError, ZERO_USAGE, ZERO_VALUE, _AgentMetadata, _AgentRegistration, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _BoilerplateScraperMetadataRegistration, _DeepseekMetadataRegistration, _DocumentScraperMetadataRegistration, _GoogleMetadataRegistration, _LegacyDocumentScraperMetadataRegistration, _MarkdownScraperMetadataRegistration, _MarkitdownScraperMetadataRegistration, _OllamaMetadataRegistration, _OpenAiAssistantMetadataRegistration, _OpenAiCompatibleMetadataRegistration, _OpenAiMetadataRegistration, _PdfScraperMetadataRegistration, _WebsiteScraperMetadataRegistration, aboutPromptbookInformation, addUsage, book, cacheLlmTools, compilePipeline, computeAgentHash, computeCosineSimilarity, countUsage, createAgentLlmExecutionTools, createAgentModelRequirements, createAgentModelRequirementsWithCommitments, createBasicAgentModelRequirements, createDefaultAgentName, createEmptyAgentModelRequirements, createLlmToolsFromConfiguration, createPipelineCollectionFromJson, createPipelineCollectionFromPromise, createPipelineCollectionFromUrl, createPipelineExecutor, createPipelineSubcollection, embeddingVectorToString, executionReportJsonToString, extractParameterNamesFromTask, filterModels, generatePlaceholderAgentProfileImageUrl, getAllCommitmentDefinitions, getAllCommitmentTypes, getCommitmentDefinition, getGroupedCommitmentDefinitions, getPipelineInterface, getSingleLlmExecutionTools, identificationToPromptbookToken, isCommitmentSupported, isPassingExpectations, isPipelineImplementingInterface, isPipelineInterfacesEqual, isPipelinePrepared, isValidBook, isValidPipelineString, joinLlmExecutionTools, limitTotalUsage, makeKnowledgeSourceHandler, migratePipeline, normalizeAgentName, padBook, parseAgentSource, parseParameters, parsePipeline, pipelineCollectionToJson, pipelineJsonToString, prepareKnowledgePieces, preparePersona, preparePipeline, prettifyPipelineString, promptbookFetch, promptbookTokenToIdentification, unpreparePipeline, usageToHuman, usageToWorktime, validateBook, validatePipeline, validatePipelineString };
21168
21496
  //# sourceMappingURL=index.es.js.map