@promptbook/core 0.103.0-52 → 0.103.0-53

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 (24) hide show
  1. package/esm/index.es.js +462 -73
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/servers.d.ts +8 -1
  4. package/esm/typings/src/_packages/components.index.d.ts +2 -0
  5. package/esm/typings/src/_packages/core.index.d.ts +6 -0
  6. package/esm/typings/src/_packages/types.index.d.ts +2 -0
  7. package/esm/typings/src/_packages/utils.index.d.ts +2 -0
  8. package/esm/typings/src/book-2.0/agent-source/AgentModelRequirements.d.ts +7 -0
  9. package/esm/typings/src/book-components/Chat/Chat/ChatProps.d.ts +4 -0
  10. package/esm/typings/src/book-components/_common/HamburgerMenu/HamburgerMenu.d.ts +12 -0
  11. package/esm/typings/src/book-components/icons/MicIcon.d.ts +8 -0
  12. package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentCollectionInSupabase.d.ts +17 -0
  13. package/esm/typings/src/commitments/MESSAGE/AgentMessageCommitmentDefinition.d.ts +28 -0
  14. package/esm/typings/src/commitments/MESSAGE/UserMessageCommitmentDefinition.d.ts +28 -0
  15. package/esm/typings/src/commitments/index.d.ts +20 -1
  16. package/esm/typings/src/execution/LlmExecutionTools.d.ts +9 -0
  17. package/esm/typings/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +2 -1
  18. package/esm/typings/src/llm-providers/agent/RemoteAgent.d.ts +10 -1
  19. package/esm/typings/src/utils/normalization/normalizeMessageText.d.ts +9 -0
  20. package/esm/typings/src/utils/normalization/normalizeMessageText.test.d.ts +1 -0
  21. package/esm/typings/src/version.d.ts +1 -1
  22. package/package.json +1 -1
  23. package/umd/index.umd.js +463 -72
  24. package/umd/index.umd.js.map +1 -1
package/esm/index.es.js CHANGED
@@ -27,12 +27,23 @@ 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.103.0-52';
30
+ const PROMPTBOOK_ENGINE_VERSION = '0.103.0-53';
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
34
34
  */
35
35
 
36
+ /**
37
+ * Core Promptbook server configuration.
38
+ *
39
+ * This server is also used for auto-federation in the Agents Server.
40
+ */
41
+ const CORE_SERVER = {
42
+ title: 'Promptbook Core',
43
+ description: `Core Promptbook server used for auto-federation`,
44
+ owner: 'AI Web, LLC <legal@ptbk.io> (https://www.ptbk.io/)',
45
+ urls: ['https://core.ptbk.io/'],
46
+ };
36
47
  /**
37
48
  * Available remote servers for the Promptbook
38
49
  *
@@ -54,6 +65,7 @@ const REMOTE_SERVER_URLS = [
54
65
  owner: 'AI Web, LLC <legal@ptbk.io> (https://www.ptbk.io/)',
55
66
  urls: ['https://s6.ptbk.io/'],
56
67
  },
68
+ CORE_SERVER,
57
69
  /*
58
70
  Note: Working on older version of Promptbook and not supported anymore
59
71
  {
@@ -66,7 +78,14 @@ const REMOTE_SERVER_URLS = [
66
78
  */
67
79
  ];
68
80
  /**
69
- * TODO: [🐱‍🚀] Auto-federated server from url in here
81
+ * Remote servers that are auto-federated by the Agents Server.
82
+ *
83
+ * These servers are always added in addition to the `FEDERATED_SERVERS` metadata.
84
+ *
85
+ * @public exported from `@promptbook/core`
86
+ */
87
+ const AUTO_FEDERATED_AGENT_SERVER_URLS = CORE_SERVER.urls;
88
+ /**
70
89
  * Note: [💞] Ignore a discrepancy between file name and entity name
71
90
  */
72
91
 
@@ -8108,6 +8127,77 @@ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
8108
8127
  * Note: [💞] Ignore a discrepancy between file name and entity name
8109
8128
  */
8110
8129
 
8130
+ /**
8131
+ * AGENT MESSAGE commitment definition
8132
+ *
8133
+ * The AGENT MESSAGE commitment defines a message from the agent in the conversation history.
8134
+ * It is used to pre-fill the chat with a conversation history or to provide few-shot examples.
8135
+ *
8136
+ * Example usage in agent source:
8137
+ *
8138
+ * ```book
8139
+ * AGENT MESSAGE What seems to be the issue?
8140
+ * ```
8141
+ *
8142
+ * @private [🪔] Maybe export the commitments through some package
8143
+ */
8144
+ class AgentMessageCommitmentDefinition extends BaseCommitmentDefinition {
8145
+ constructor() {
8146
+ super('AGENT MESSAGE');
8147
+ }
8148
+ /**
8149
+ * Short one-line description of AGENT MESSAGE.
8150
+ */
8151
+ get description() {
8152
+ return 'Defines a **message from the agent** in the conversation history.';
8153
+ }
8154
+ /**
8155
+ * Markdown documentation for AGENT MESSAGE commitment.
8156
+ */
8157
+ get documentation() {
8158
+ return spaceTrim$2(`
8159
+ # ${this.type}
8160
+
8161
+ 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.
8162
+
8163
+ ## Key aspects
8164
+
8165
+ - Represents a message sent by the agent.
8166
+ - Used for setting up conversation context.
8167
+ - Can be used in conjunction with USER MESSAGE.
8168
+
8169
+ ## Examples
8170
+
8171
+ \`\`\`book
8172
+ Conversation History
8173
+
8174
+ USER MESSAGE Hello, I have a problem.
8175
+ AGENT MESSAGE What seems to be the issue?
8176
+ USER MESSAGE My computer is not starting.
8177
+ \`\`\`
8178
+ `);
8179
+ }
8180
+ applyToAgentModelRequirements(requirements, content) {
8181
+ // AGENT MESSAGE is for UI display purposes / conversation history construction
8182
+ // and typically doesn't need to be added to the system prompt or model requirements directly.
8183
+ // It is extracted separately for the chat interface.
8184
+ var _a;
8185
+ const pendingUserMessage = (_a = requirements.metadata) === null || _a === void 0 ? void 0 : _a.pendingUserMessage;
8186
+ if (pendingUserMessage) {
8187
+ const newSample = { question: pendingUserMessage, answer: content };
8188
+ const newSamples = [...(requirements.samples || []), newSample];
8189
+ const newMetadata = { ...requirements.metadata };
8190
+ delete newMetadata.pendingUserMessage;
8191
+ return {
8192
+ ...requirements,
8193
+ samples: newSamples,
8194
+ metadata: newMetadata,
8195
+ };
8196
+ }
8197
+ return requirements;
8198
+ }
8199
+ }
8200
+
8111
8201
  /**
8112
8202
  * INITIAL MESSAGE commitment definition
8113
8203
  *
@@ -8272,6 +8362,67 @@ class MessageCommitmentDefinition extends BaseCommitmentDefinition {
8272
8362
  * Note: [💞] Ignore a discrepancy between file name and entity name
8273
8363
  */
8274
8364
 
8365
+ /**
8366
+ * USER MESSAGE commitment definition
8367
+ *
8368
+ * The USER MESSAGE commitment defines a message from the user in the conversation history.
8369
+ * It is used to pre-fill the chat with a conversation history or to provide few-shot examples.
8370
+ *
8371
+ * Example usage in agent source:
8372
+ *
8373
+ * ```book
8374
+ * USER MESSAGE Hello, I have a problem.
8375
+ * ```
8376
+ *
8377
+ * @private [🪔] Maybe export the commitments through some package
8378
+ */
8379
+ class UserMessageCommitmentDefinition extends BaseCommitmentDefinition {
8380
+ constructor() {
8381
+ super('USER MESSAGE');
8382
+ }
8383
+ /**
8384
+ * Short one-line description of USER MESSAGE.
8385
+ */
8386
+ get description() {
8387
+ return 'Defines a **message from the user** in the conversation history.';
8388
+ }
8389
+ /**
8390
+ * Markdown documentation for USER MESSAGE commitment.
8391
+ */
8392
+ get documentation() {
8393
+ return spaceTrim$2(`
8394
+ # ${this.type}
8395
+
8396
+ 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.
8397
+
8398
+ ## Key aspects
8399
+
8400
+ - Represents a message sent by the user.
8401
+ - Used for setting up conversation context.
8402
+ - Can be used in conjunction with AGENT MESSAGE.
8403
+
8404
+ ## Examples
8405
+
8406
+ \`\`\`book
8407
+ Conversation History
8408
+
8409
+ USER MESSAGE Hello, I have a problem.
8410
+ AGENT MESSAGE What seems to be the issue?
8411
+ USER MESSAGE My computer is not starting.
8412
+ \`\`\`
8413
+ `);
8414
+ }
8415
+ applyToAgentModelRequirements(requirements, content) {
8416
+ return {
8417
+ ...requirements,
8418
+ metadata: {
8419
+ ...requirements.metadata,
8420
+ pendingUserMessage: content,
8421
+ },
8422
+ };
8423
+ }
8424
+ }
8425
+
8275
8426
  /**
8276
8427
  * META commitment definition
8277
8428
  *
@@ -9485,6 +9636,8 @@ const COMMITMENT_REGISTRY = [
9485
9636
  new GoalCommitmentDefinition('GOAL'),
9486
9637
  new GoalCommitmentDefinition('GOALS'),
9487
9638
  new InitialMessageCommitmentDefinition(),
9639
+ new UserMessageCommitmentDefinition(),
9640
+ new AgentMessageCommitmentDefinition(),
9488
9641
  new MessageCommitmentDefinition('MESSAGE'),
9489
9642
  new MessageCommitmentDefinition('MESSAGES'),
9490
9643
  new ScenarioCommitmentDefinition('SCENARIO'),
@@ -9539,6 +9692,45 @@ function getAllCommitmentTypes() {
9539
9692
  function isCommitmentSupported(type) {
9540
9693
  return COMMITMENT_REGISTRY.some((commitmentDefinition) => commitmentDefinition.type === type);
9541
9694
  }
9695
+ /**
9696
+ * Gets all commitment definitions grouped by their aliases
9697
+ *
9698
+ * @returns Array of grouped commitment definitions
9699
+ *
9700
+ * @public exported from `@promptbook/core`
9701
+ */
9702
+ function getGroupedCommitmentDefinitions() {
9703
+ const groupedCommitments = [];
9704
+ for (const commitment of COMMITMENT_REGISTRY) {
9705
+ const lastGroup = groupedCommitments[groupedCommitments.length - 1];
9706
+ // Check if we should group with the previous item
9707
+ let shouldGroup = false;
9708
+ if (lastGroup) {
9709
+ const lastPrimary = lastGroup.primary;
9710
+ // Case 1: Same class constructor (except NotYetImplemented)
9711
+ if (!(commitment instanceof NotYetImplementedCommitmentDefinition) &&
9712
+ commitment.constructor === lastPrimary.constructor) {
9713
+ shouldGroup = true;
9714
+ }
9715
+ // Case 2: NotYetImplemented with prefix matching (e.g. BEHAVIOUR -> BEHAVIOURS)
9716
+ else if (commitment instanceof NotYetImplementedCommitmentDefinition &&
9717
+ lastPrimary instanceof NotYetImplementedCommitmentDefinition &&
9718
+ commitment.type.startsWith(lastPrimary.type)) {
9719
+ shouldGroup = true;
9720
+ }
9721
+ }
9722
+ if (shouldGroup && lastGroup) {
9723
+ lastGroup.aliases.push(commitment.type);
9724
+ }
9725
+ else {
9726
+ groupedCommitments.push({
9727
+ primary: commitment,
9728
+ aliases: [],
9729
+ });
9730
+ }
9731
+ }
9732
+ return $deepFreeze(groupedCommitments);
9733
+ }
9542
9734
  /**
9543
9735
  * TODO: [🧠] Maybe create through standardized $register
9544
9736
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -10278,6 +10470,18 @@ function parseNumber(value) {
10278
10470
  * TODO: [🧠][🌻] Maybe export through `@promptbook/markdown-utils` not `@promptbook/utils`
10279
10471
  */
10280
10472
 
10473
+ /**
10474
+ * Normalizes message text for comparison
10475
+ *
10476
+ * @param text The message text to normalize
10477
+ * @returns The normalized message text
10478
+ *
10479
+ * @public exported from `@promptbook/utils`
10480
+ */
10481
+ function normalizeMessageText(text) {
10482
+ return spaceTrim$2(text);
10483
+ }
10484
+
10281
10485
  /**
10282
10486
  * Removes quotes from a string
10283
10487
  *
@@ -10782,7 +10986,96 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
10782
10986
  * Deletes an agent from the collection
10783
10987
  */
10784
10988
  async deleteAgent(agentName) {
10785
- throw new NotYetImplementedError('Method not implemented.');
10989
+ const deleteResult = await this.supabaseClient
10990
+ .from(this.getTableName('Agent'))
10991
+ .delete()
10992
+ .eq('agentName', agentName);
10993
+ if (deleteResult.error) {
10994
+ throw new DatabaseError(spaceTrim((block) => `
10995
+ Error deleting agent "${agentName}" from Supabase:
10996
+
10997
+ ${block(deleteResult.error.message)}
10998
+ `));
10999
+ }
11000
+ }
11001
+ /**
11002
+ * List history of an agent
11003
+ */
11004
+ async listAgentHistory(agentName) {
11005
+ const result = await this.supabaseClient
11006
+ .from(this.getTableName('AgentHistory'))
11007
+ .select('id, createdAt, agentHash, promptbookEngineVersion')
11008
+ .eq('agentName', agentName)
11009
+ .order('createdAt', { ascending: false });
11010
+ if (result.error) {
11011
+ throw new DatabaseError(spaceTrim((block) => `
11012
+ Error listing history for agent "${agentName}" from Supabase:
11013
+
11014
+ ${block(result.error.message)}
11015
+ `));
11016
+ }
11017
+ return result.data;
11018
+ }
11019
+ /**
11020
+ * List agents that are in history but not in the active agents list
11021
+ */
11022
+ async listDeletedAgents() {
11023
+ const historyNamesResult = await this.supabaseClient.from(this.getTableName('AgentHistory')).select('agentName');
11024
+ const currentNamesResult = await this.supabaseClient.from(this.getTableName('Agent')).select('agentName');
11025
+ if (historyNamesResult.error) {
11026
+ throw new DatabaseError(spaceTrim((block) => `
11027
+ Error fetching agent history names from Supabase:
11028
+
11029
+ ${block(historyNamesResult.error.message)}
11030
+ `));
11031
+ }
11032
+ if (currentNamesResult.error) {
11033
+ throw new DatabaseError(spaceTrim((block) => `
11034
+ Error fetching current agent names from Supabase:
11035
+
11036
+ ${block(currentNamesResult.error.message)}
11037
+ `));
11038
+ }
11039
+ const currentNames = new Set(currentNamesResult.data.map((d) => d.agentName));
11040
+ const deletedNames = new Set();
11041
+ for (const { agentName } of historyNamesResult.data) {
11042
+ if (!currentNames.has(agentName)) {
11043
+ deletedNames.add(agentName);
11044
+ }
11045
+ }
11046
+ return Array.from(deletedNames);
11047
+ }
11048
+ /**
11049
+ * Restore an agent from history
11050
+ */
11051
+ async restoreAgent(historyId) {
11052
+ const historyResult = await this.supabaseClient
11053
+ .from(this.getTableName('AgentHistory'))
11054
+ .select('*')
11055
+ .eq('id', historyId)
11056
+ .single();
11057
+ if (historyResult.error) {
11058
+ throw new DatabaseError(spaceTrim((block) => `
11059
+ Error fetching agent history item "${historyId}" from Supabase:
11060
+
11061
+ ${block(historyResult.error.message)}
11062
+ `));
11063
+ }
11064
+ const { agentName, agentSource } = historyResult.data;
11065
+ // Check if agent exists
11066
+ const agentResult = await this.supabaseClient
11067
+ .from(this.getTableName('Agent'))
11068
+ .select('id')
11069
+ .eq('agentName', agentName)
11070
+ .single();
11071
+ if (agentResult.data) {
11072
+ // Update
11073
+ await this.updateAgentSource(agentName, agentSource);
11074
+ }
11075
+ else {
11076
+ // Insert (Restore from deleted)
11077
+ await this.createAgent(agentSource);
11078
+ }
10786
11079
  }
10787
11080
  /**
10788
11081
  * Get the Supabase table name with prefix
@@ -17211,12 +17504,15 @@ class OpenAiAssistantExecutionTools extends OpenAiExecutionTools {
17211
17504
  fileStreams.push(file);
17212
17505
  }
17213
17506
  else {
17507
+ /*
17508
+ TODO: [🐱‍🚀] Resolve problem with browser environment
17214
17509
  // Assume it's a local file path
17215
17510
  // Note: This will work in Node.js environment
17216
17511
  // For browser environments, this would need different handling
17217
17512
  const fs = await import('fs');
17218
17513
  const fileStream = fs.createReadStream(source);
17219
17514
  fileStreams.push(fileStream);
17515
+ */
17220
17516
  }
17221
17517
  }
17222
17518
  catch (error) {
@@ -17305,12 +17601,15 @@ class OpenAiAssistantExecutionTools extends OpenAiExecutionTools {
17305
17601
  fileStreams.push(file);
17306
17602
  }
17307
17603
  else {
17604
+ /*
17605
+ TODO: [🐱‍🚀] Resolve problem with browser environment
17308
17606
  // Assume it's a local file path
17309
17607
  // Note: This will work in Node.js environment
17310
17608
  // For browser environments, this would need different handling
17311
17609
  const fs = await import('fs');
17312
17610
  const fileStream = fs.createReadStream(source);
17313
17611
  fileStreams.push(fileStream);
17612
+ */
17314
17613
  }
17315
17614
  }
17316
17615
  catch (error) {
@@ -17684,7 +17983,53 @@ class Agent extends AgentLlmExecutionTools {
17684
17983
  * Note: This method also implements the learning mechanism
17685
17984
  */
17686
17985
  async callChatModelStream(prompt, onProgress) {
17986
+ // [1] Check if the user is asking the same thing as in the samples
17987
+ const modelRequirements = await this.getAgentModelRequirements();
17988
+ if (modelRequirements.samples) {
17989
+ const normalizedPrompt = normalizeMessageText(prompt.content);
17990
+ const sample = modelRequirements.samples.find((s) => normalizeMessageText(s.question) === normalizedPrompt);
17991
+ if (sample) {
17992
+ const now = new Date().toISOString();
17993
+ const result = {
17994
+ content: sample.answer,
17995
+ modelName: this.modelName,
17996
+ timing: {
17997
+ start: now,
17998
+ complete: now,
17999
+ },
18000
+ usage: {
18001
+ price: { value: 0, isUncertain: true },
18002
+ input: {
18003
+ tokensCount: { value: 0, isUncertain: true },
18004
+ charactersCount: { value: 0, isUncertain: true },
18005
+ wordsCount: { value: 0, isUncertain: true },
18006
+ linesCount: { value: 0, isUncertain: true },
18007
+ sentencesCount: { value: 0, isUncertain: true },
18008
+ paragraphsCount: { value: 0, isUncertain: true },
18009
+ pagesCount: { value: 0, isUncertain: true },
18010
+ },
18011
+ output: {
18012
+ tokensCount: { value: 0, isUncertain: true },
18013
+ charactersCount: { value: 0, isUncertain: true },
18014
+ wordsCount: { value: 0, isUncertain: true },
18015
+ linesCount: { value: 0, isUncertain: true },
18016
+ sentencesCount: { value: 0, isUncertain: true },
18017
+ paragraphsCount: { value: 0, isUncertain: true },
18018
+ pagesCount: { value: 0, isUncertain: true },
18019
+ },
18020
+ },
18021
+ rawPromptContent: prompt.content,
18022
+ rawRequest: null,
18023
+ rawResponse: { sample },
18024
+ };
18025
+ onProgress(result);
18026
+ return result;
18027
+ }
18028
+ }
17687
18029
  const result = await super.callChatModelStream(prompt, onProgress);
18030
+ if (result.rawResponse && 'sample' in result.rawResponse) {
18031
+ return result;
18032
+ }
17688
18033
  // TODO: !!! Extract learning to separate method
17689
18034
  // Learning: Append the conversation sample to the agent source
17690
18035
  const learningExample = spaceTrim$1((block) => `
@@ -17770,6 +18115,70 @@ const _AgentRegistration = $llmToolsRegister.register(createAgentLlmExecutionToo
17770
18115
  * Note: [💞] Ignore a discrepancy between file name and entity name
17771
18116
  */
17772
18117
 
18118
+ /**
18119
+ * Function `isValidPipelineString` will validate the if the string is a valid pipeline string
18120
+ * It does not check if the string is fully logically correct, but if it is a string that can be a pipeline string or the string looks completely different.
18121
+ *
18122
+ * @param {string} pipelineString the candidate for a pipeline string
18123
+ * @returns {boolean} if the string is a valid pipeline string
18124
+ * @public exported from `@promptbook/core`
18125
+ */
18126
+ function isValidPipelineString(pipelineString) {
18127
+ try {
18128
+ validatePipelineString(pipelineString);
18129
+ return true;
18130
+ }
18131
+ catch (error) {
18132
+ assertsError(error);
18133
+ return false;
18134
+ }
18135
+ }
18136
+ /**
18137
+ * TODO: [🧠][🈴] Where is the best location for this file
18138
+ */
18139
+
18140
+ /**
18141
+ * Tag function for notating a pipeline with a book\`...\ notation as template literal
18142
+ *
18143
+ * Note: There are 3 similar functions:
18144
+ * 1) `prompt` for notating single prompt exported from `@promptbook/utils`
18145
+ * 2) `promptTemplate` alias for `prompt`
18146
+ * 3) `book` for notating and validating entire books exported from `@promptbook/utils`
18147
+ *
18148
+ * @param strings The static string parts of the template literal
18149
+ * @param values The dynamic values embedded within the template literal used as data
18150
+ * @returns the pipeline string
18151
+ * @public exported from `@promptbook/core`
18152
+ */
18153
+ function book(strings, ...values) {
18154
+ const bookString = prompt(strings, ...values);
18155
+ if (!isValidPipelineString(bookString)) {
18156
+ // TODO: Make the CustomError for this
18157
+ throw new Error(spaceTrim$1(`
18158
+ The string is not a valid pipeline string
18159
+
18160
+ book\`
18161
+ ${bookString}
18162
+ \`
18163
+ `));
18164
+ }
18165
+ if (!isValidBook(bookString)) {
18166
+ // TODO: Make the CustomError for this
18167
+ throw new Error(spaceTrim$1(`
18168
+ The string is not a valid book
18169
+
18170
+ book\`
18171
+ ${bookString}
18172
+ \`
18173
+ `));
18174
+ }
18175
+ return padBook(bookString);
18176
+ }
18177
+ /**
18178
+ * TODO: [🧠][🈴] Where is the best location for this file
18179
+ * Note: [💞] Ignore a discrepancy between file name and entity name
18180
+ */
18181
+
17773
18182
  /**
17774
18183
  * Represents one AI Agent
17775
18184
  *
@@ -17791,11 +18200,12 @@ class RemoteAgent extends Agent {
17791
18200
  const profile = await profileResponse.json();
17792
18201
  // Note: We are creating dummy agent source because we don't have the source from the remote agent
17793
18202
  // But we populate the metadata from the profile
17794
- const agentSource = new BehaviorSubject(`
17795
- # ${profile.agentName}
18203
+ const agentSource = new BehaviorSubject(book `
18204
+ ${profile.agentName}
17796
18205
 
17797
- ${profile.personaDescription}
18206
+ ${profile.personaDescription}
17798
18207
  `);
18208
+ // <- TODO: [🐱‍🚀] createBookFromProfile
17799
18209
  // <- TODO: [🐱‍🚀] Support updating and self-updating
17800
18210
  const remoteAgent = new RemoteAgent({
17801
18211
  ...options,
@@ -17820,10 +18230,12 @@ ${profile.personaDescription}
17820
18230
  remoteAgent.initialMessage = profile.initialMessage;
17821
18231
  remoteAgent.links = profile.links;
17822
18232
  remoteAgent.meta = profile.meta;
18233
+ remoteAgent._isVoiceCallingEnabled = profile.isVoiceCallingEnabled === true; // [✨✷] Store voice calling status
17823
18234
  return remoteAgent;
17824
18235
  }
17825
18236
  constructor(options) {
17826
18237
  super(options);
18238
+ this._isVoiceCallingEnabled = false; // [✨✷] Track voice calling status
17827
18239
  this.agentUrl = options.agentUrl;
17828
18240
  }
17829
18241
  get agentName() {
@@ -17839,8 +18251,49 @@ ${profile.personaDescription}
17839
18251
  return this.callChatModelStream(prompt, () => { });
17840
18252
  }
17841
18253
  /**
17842
- * Calls the agent on agents remote server with streaming
18254
+ * Calls the agent on agents remote server with voice
18255
+ * [✨✷] Only available when voice calling is enabled on the server
18256
+ * Returns undefined if voice calling is disabled
17843
18257
  */
18258
+ get callVoiceChatModel() {
18259
+ if (!this._isVoiceCallingEnabled) {
18260
+ return undefined;
18261
+ }
18262
+ return async (audio, prompt) => {
18263
+ // Ensure we're working with a chat prompt
18264
+ if (prompt.modelRequirements.modelVariant !== 'CHAT') {
18265
+ throw new Error('Agents only supports chat prompts');
18266
+ }
18267
+ const chatPrompt = prompt;
18268
+ const formData = new FormData();
18269
+ formData.append('audio', audio, 'voice.webm');
18270
+ formData.append('message', prompt.content);
18271
+ if (chatPrompt.thread) {
18272
+ formData.append('thread', JSON.stringify(chatPrompt.thread));
18273
+ }
18274
+ const response = await fetch(`${this.agentUrl}/api/voice`, {
18275
+ method: 'POST',
18276
+ body: formData,
18277
+ });
18278
+ if (!response.ok) {
18279
+ throw new Error(`Voice chat failed: ${response.statusText}`);
18280
+ }
18281
+ const result = await response.json();
18282
+ // Convert base64 audio back to Blob
18283
+ const binaryString = atob(result.audio);
18284
+ const bytes = new Uint8Array(binaryString.length);
18285
+ for (let i = 0; i < binaryString.length; i++) {
18286
+ bytes[i] = binaryString.charCodeAt(i);
18287
+ }
18288
+ const audioBlob = new Blob([bytes], { type: 'audio/mp3' });
18289
+ return {
18290
+ text: result.agentMessage || result.text,
18291
+ userMessage: result.userMessage,
18292
+ agentMessage: result.agentMessage || result.text,
18293
+ audio: audioBlob,
18294
+ };
18295
+ };
18296
+ }
17844
18297
  async callChatModelStream(prompt, onProgress) {
17845
18298
  // Ensure we're working with a chat prompt
17846
18299
  if (prompt.modelRequirements.modelVariant !== 'CHAT') {
@@ -18377,70 +18830,6 @@ function migratePipeline(deprecatedPipeline) {
18377
18830
  return migratedPipeline;
18378
18831
  }
18379
18832
 
18380
- /**
18381
- * Function `isValidPipelineString` will validate the if the string is a valid pipeline string
18382
- * It does not check if the string is fully logically correct, but if it is a string that can be a pipeline string or the string looks completely different.
18383
- *
18384
- * @param {string} pipelineString the candidate for a pipeline string
18385
- * @returns {boolean} if the string is a valid pipeline string
18386
- * @public exported from `@promptbook/core`
18387
- */
18388
- function isValidPipelineString(pipelineString) {
18389
- try {
18390
- validatePipelineString(pipelineString);
18391
- return true;
18392
- }
18393
- catch (error) {
18394
- assertsError(error);
18395
- return false;
18396
- }
18397
- }
18398
- /**
18399
- * TODO: [🧠][🈴] Where is the best location for this file
18400
- */
18401
-
18402
- /**
18403
- * Tag function for notating a pipeline with a book\`...\ notation as template literal
18404
- *
18405
- * Note: There are 3 similar functions:
18406
- * 1) `prompt` for notating single prompt exported from `@promptbook/utils`
18407
- * 2) `promptTemplate` alias for `prompt`
18408
- * 3) `book` for notating and validating entire books exported from `@promptbook/utils`
18409
- *
18410
- * @param strings The static string parts of the template literal
18411
- * @param values The dynamic values embedded within the template literal used as data
18412
- * @returns the pipeline string
18413
- * @public exported from `@promptbook/core`
18414
- */
18415
- function book(strings, ...values) {
18416
- const bookString = prompt(strings, ...values);
18417
- if (!isValidPipelineString(bookString)) {
18418
- // TODO: Make the CustomError for this
18419
- throw new Error(spaceTrim$1(`
18420
- The string is not a valid pipeline string
18421
-
18422
- book\`
18423
- ${bookString}
18424
- \`
18425
- `));
18426
- }
18427
- if (!isValidBook(bookString)) {
18428
- // TODO: Make the CustomError for this
18429
- throw new Error(spaceTrim$1(`
18430
- The string is not a valid book
18431
-
18432
- book\`
18433
- ${bookString}
18434
- \`
18435
- `));
18436
- }
18437
- return padBook(bookString);
18438
- }
18439
- /**
18440
- * TODO: [🧠][🈴] Where is the best location for this file
18441
- * Note: [💞] Ignore a discrepancy between file name and entity name
18442
- */
18443
-
18444
18833
  /**
18445
18834
  * Convert identification to Promptbook token
18446
18835
  *
@@ -19203,7 +19592,7 @@ function $generateBookBoilerplate(options) {
19203
19592
  const agentSource = validateBook(spaceTrim$1((block) => `
19204
19593
  ${agentName}
19205
19594
 
19206
- META COLOR ${color || '#3498db' /* <- TODO: [🧠] [🐱‍🚀] Best default color */}
19595
+ META COLOR ${color || PROMPTBOOK_COLOR.toHex()}
19207
19596
  PERSONA ${block(personaDescription)}
19208
19597
  `));
19209
19598
  return agentSource;
@@ -19212,5 +19601,5 @@ function $generateBookBoilerplate(options) {
19212
19601
  * TODO: [🤶] Maybe export through `@promptbook/utils` or `@promptbook/random` package
19213
19602
  */
19214
19603
 
19215
- export { $bookTranspilersRegister, $generateBookBoilerplate, $llmToolsMetadataRegister, $llmToolsRegister, $scrapersMetadataRegister, $scrapersRegister, ADMIN_EMAIL, ADMIN_GITHUB_NAME, API_REQUEST_TIMEOUT, 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, 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 };
19604
+ 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 };
19216
19605
  //# sourceMappingURL=index.es.js.map