@promptbook/core 0.104.0-1 → 0.104.0-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/esm/index.es.js +335 -89
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/src/_packages/types.index.d.ts +8 -2
  4. package/esm/typings/src/book-2.0/agent-source/AgentBasicInformation.d.ts +6 -1
  5. package/esm/typings/src/book-components/Chat/Chat/ChatMessageItem.d.ts +5 -1
  6. package/esm/typings/src/book-components/Chat/Chat/ChatProps.d.ts +5 -0
  7. package/esm/typings/src/book-components/Chat/CodeBlock/CodeBlock.d.ts +13 -0
  8. package/esm/typings/src/book-components/Chat/MarkdownContent/MarkdownContent.d.ts +1 -0
  9. package/esm/typings/src/book-components/Chat/types/ChatMessage.d.ts +7 -11
  10. package/esm/typings/src/book-components/_common/Dropdown/Dropdown.d.ts +2 -2
  11. package/esm/typings/src/book-components/_common/MenuHoisting/MenuHoistingContext.d.ts +56 -0
  12. package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentCollectionInSupabase.d.ts +13 -7
  13. package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentsDatabaseSchema.d.ts +6 -0
  14. package/esm/typings/src/commitments/DICTIONARY/DICTIONARY.d.ts +46 -0
  15. package/esm/typings/src/commitments/index.d.ts +2 -1
  16. package/esm/typings/src/llm-providers/ollama/OllamaExecutionTools.d.ts +1 -1
  17. package/esm/typings/src/llm-providers/openai/createOpenAiCompatibleExecutionTools.d.ts +1 -1
  18. package/esm/typings/src/types/Message.d.ts +49 -0
  19. package/esm/typings/src/types/typeAliases.d.ts +12 -0
  20. package/esm/typings/src/utils/environment/$detectRuntimeEnvironment.d.ts +4 -4
  21. package/esm/typings/src/utils/environment/$isRunningInBrowser.d.ts +1 -1
  22. package/esm/typings/src/utils/environment/$isRunningInJest.d.ts +1 -1
  23. package/esm/typings/src/utils/environment/$isRunningInNode.d.ts +1 -1
  24. package/esm/typings/src/utils/environment/$isRunningInWebWorker.d.ts +1 -1
  25. package/esm/typings/src/utils/markdown/extractAllBlocksFromMarkdown.d.ts +2 -2
  26. package/esm/typings/src/utils/markdown/extractOneBlockFromMarkdown.d.ts +2 -2
  27. package/esm/typings/src/utils/random/$randomBase58.d.ts +12 -0
  28. package/esm/typings/src/version.d.ts +1 -1
  29. package/package.json +1 -1
  30. package/umd/index.umd.js +341 -95
  31. package/umd/index.umd.js.map +1 -1
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-1';
30
+ const PROMPTBOOK_ENGINE_VERSION = '0.104.0-3';
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
@@ -7964,6 +7964,114 @@ class DeleteCommitmentDefinition extends BaseCommitmentDefinition {
7964
7964
  * Note: [💞] Ignore a discrepancy between file name and entity name
7965
7965
  */
7966
7966
 
7967
+ /**
7968
+ * DICTIONARY commitment definition
7969
+ *
7970
+ * The DICTIONARY commitment defines specific terms and their meanings that the agent should use correctly
7971
+ * in its reasoning and responses. This ensures consistent terminology usage.
7972
+ *
7973
+ * Key features:
7974
+ * - Multiple DICTIONARY commitments are automatically merged into one
7975
+ * - Content is placed in a dedicated section of the system message
7976
+ * - Terms and definitions are stored in metadata.DICTIONARY for debugging
7977
+ * - Agent should use the defined terms correctly in responses
7978
+ *
7979
+ * Example usage in agent source:
7980
+ *
7981
+ * ```book
7982
+ * Legal Assistant
7983
+ *
7984
+ * PERSONA You are a knowledgeable legal assistant
7985
+ * DICTIONARY Misdemeanor is a minor wrongdoing or criminal offense
7986
+ * DICTIONARY Felony is a serious crime usually punishable by imprisonment for more than one year
7987
+ * DICTIONARY Tort is a civil wrong that causes harm or loss to another person, leading to legal liability
7988
+ * ```
7989
+ *
7990
+ * @private [🪔] Maybe export the commitments through some package
7991
+ */
7992
+ class DictionaryCommitmentDefinition extends BaseCommitmentDefinition {
7993
+ constructor() {
7994
+ super('DICTIONARY');
7995
+ }
7996
+ /**
7997
+ * Short one-line description of DICTIONARY.
7998
+ */
7999
+ get description() {
8000
+ return 'Define terms and their meanings for consistent terminology usage.';
8001
+ }
8002
+ /**
8003
+ * Icon for this commitment.
8004
+ */
8005
+ get icon() {
8006
+ return '📚';
8007
+ }
8008
+ /**
8009
+ * Markdown documentation for DICTIONARY commitment.
8010
+ */
8011
+ get documentation() {
8012
+ return spaceTrim$1(`
8013
+ # DICTIONARY
8014
+
8015
+ Defines specific terms and their meanings that the agent should use correctly in reasoning and responses.
8016
+
8017
+ ## Key aspects
8018
+
8019
+ - Multiple \`DICTIONARY\` commitments are merged together.
8020
+ - Terms are defined in the format: "Term is definition"
8021
+ - The agent should use these terms consistently in responses.
8022
+ - Definitions help ensure accurate and consistent terminology.
8023
+
8024
+ ## Examples
8025
+
8026
+ \`\`\`book
8027
+ Legal Assistant
8028
+
8029
+ PERSONA You are a knowledgeable legal assistant specializing in criminal law
8030
+ DICTIONARY Misdemeanor is a minor wrongdoing or criminal offense
8031
+ DICTIONARY Felony is a serious crime usually punishable by imprisonment for more than one year
8032
+ DICTIONARY Tort is a civil wrong that causes harm or loss to another person, leading to legal liability
8033
+ \`\`\`
8034
+
8035
+ \`\`\`book
8036
+ Medical Assistant
8037
+
8038
+ PERSONA You are a helpful medical assistant
8039
+ DICTIONARY Hypertension is persistently high blood pressure
8040
+ DICTIONARY Diabetes is a chronic condition that affects how the body processes blood sugar
8041
+ DICTIONARY Vaccine is a biological preparation that provides active immunity to a particular disease
8042
+ \`\`\`
8043
+ `);
8044
+ }
8045
+ applyToAgentModelRequirements(requirements, content) {
8046
+ var _a;
8047
+ const trimmedContent = content.trim();
8048
+ if (!trimmedContent) {
8049
+ return requirements;
8050
+ }
8051
+ // Get existing dictionary entries from metadata
8052
+ const existingDictionary = ((_a = requirements.metadata) === null || _a === void 0 ? void 0 : _a.DICTIONARY) || '';
8053
+ // Merge the new dictionary entry with existing entries
8054
+ const mergedDictionary = existingDictionary
8055
+ ? `${existingDictionary}\n${trimmedContent}`
8056
+ : trimmedContent;
8057
+ // Store the merged dictionary in metadata for debugging and inspection
8058
+ const updatedMetadata = {
8059
+ ...requirements.metadata,
8060
+ DICTIONARY: mergedDictionary,
8061
+ };
8062
+ // Create the dictionary section for the system message
8063
+ // Format: "# DICTIONARY\nTerm: definition\nTerm: definition..."
8064
+ const dictionarySection = `# DICTIONARY\n${mergedDictionary}`;
8065
+ return {
8066
+ ...this.appendToSystemMessage(requirements, dictionarySection),
8067
+ metadata: updatedMetadata,
8068
+ };
8069
+ }
8070
+ }
8071
+ /**
8072
+ * Note: [💞] Ignore a discrepancy between file name and entity name
8073
+ */
8074
+
7967
8075
  /**
7968
8076
  * FORMAT commitment definition
7969
8077
  *
@@ -10784,6 +10892,7 @@ const COMMITMENT_REGISTRY = [
10784
10892
  new DeleteCommitmentDefinition('CANCEL'),
10785
10893
  new DeleteCommitmentDefinition('DISCARD'),
10786
10894
  new DeleteCommitmentDefinition('REMOVE'),
10895
+ new DictionaryCommitmentDefinition(),
10787
10896
  new OpenCommitmentDefinition(),
10788
10897
  new ClosedCommitmentDefinition(),
10789
10898
  new UseBrowserCommitmentDefinition(),
@@ -10935,17 +11044,64 @@ function parseAgentSourceWithCommitments(agentSource) {
10935
11044
  };
10936
11045
  }
10937
11046
  const lines = agentSource.split('\n');
10938
- const agentName = (((_a = lines[0]) === null || _a === void 0 ? void 0 : _a.trim()) || null);
11047
+ let agentName = null;
11048
+ let agentNameLineIndex = -1;
11049
+ // Find the agent name: first non-empty line that is not a commitment and not a horizontal line
11050
+ for (let i = 0; i < lines.length; i++) {
11051
+ const line = lines[i];
11052
+ if (line === undefined) {
11053
+ continue;
11054
+ }
11055
+ const trimmed = line.trim();
11056
+ if (!trimmed) {
11057
+ continue;
11058
+ }
11059
+ const isHorizontal = HORIZONTAL_LINE_PATTERN.test(line);
11060
+ if (isHorizontal) {
11061
+ continue;
11062
+ }
11063
+ let isCommitment = false;
11064
+ for (const definition of COMMITMENT_REGISTRY) {
11065
+ const typeRegex = definition.createTypeRegex();
11066
+ const match = typeRegex.exec(trimmed);
11067
+ if (match && ((_a = match.groups) === null || _a === void 0 ? void 0 : _a.type)) {
11068
+ isCommitment = true;
11069
+ break;
11070
+ }
11071
+ }
11072
+ if (!isCommitment) {
11073
+ agentName = trimmed;
11074
+ agentNameLineIndex = i;
11075
+ break;
11076
+ }
11077
+ }
10939
11078
  const commitments = [];
10940
11079
  const nonCommitmentLines = [];
10941
- // Always add the first line (agent name) to non-commitment lines
10942
- if (lines[0] !== undefined) {
10943
- nonCommitmentLines.push(lines[0]);
11080
+ // Add lines before agentName that are horizontal lines (they are non-commitment)
11081
+ for (let i = 0; i < agentNameLineIndex; i++) {
11082
+ const line = lines[i];
11083
+ if (line === undefined) {
11084
+ continue;
11085
+ }
11086
+ const trimmed = line.trim();
11087
+ if (!trimmed) {
11088
+ continue;
11089
+ }
11090
+ const isHorizontal = HORIZONTAL_LINE_PATTERN.test(line);
11091
+ if (isHorizontal) {
11092
+ nonCommitmentLines.push(line);
11093
+ }
11094
+ // Note: Commitments before agentName are not added to nonCommitmentLines
11095
+ }
11096
+ // Add the agent name line to non-commitment lines
11097
+ if (agentNameLineIndex >= 0) {
11098
+ nonCommitmentLines.push(lines[agentNameLineIndex]);
10944
11099
  }
10945
11100
  // Parse commitments with multiline support
10946
11101
  let currentCommitment = null;
10947
- // Process lines starting from the second line (skip agent name)
10948
- for (let i = 1; i < lines.length; i++) {
11102
+ // Process lines starting from after the agent name line
11103
+ const startIndex = agentNameLineIndex >= 0 ? agentNameLineIndex + 1 : 0;
11104
+ for (let i = startIndex; i < lines.length; i++) {
10949
11105
  const line = lines[i];
10950
11106
  if (line === undefined) {
10951
11107
  continue;
@@ -11468,13 +11624,14 @@ function prompt(strings, ...values) {
11468
11624
  *
11469
11625
  * @public exported from `@promptbook/utils`
11470
11626
  */
11471
- const $isRunningInBrowser = new Function(`
11627
+ function $isRunningInBrowser() {
11472
11628
  try {
11473
- return this === window;
11474
- } catch (e) {
11629
+ return typeof window !== 'undefined' && typeof window.document !== 'undefined';
11630
+ }
11631
+ catch (e) {
11475
11632
  return false;
11476
11633
  }
11477
- `);
11634
+ }
11478
11635
  /**
11479
11636
  * TODO: [🎺]
11480
11637
  */
@@ -11486,13 +11643,15 @@ const $isRunningInBrowser = new Function(`
11486
11643
  *
11487
11644
  * @public exported from `@promptbook/utils`
11488
11645
  */
11489
- const $isRunningInJest = new Function(`
11646
+ function $isRunningInJest() {
11647
+ var _a;
11490
11648
  try {
11491
- return process.env.JEST_WORKER_ID !== undefined;
11492
- } catch (e) {
11649
+ return typeof process !== 'undefined' && ((_a = process.env) === null || _a === void 0 ? void 0 : _a.JEST_WORKER_ID) !== undefined;
11650
+ }
11651
+ catch (e) {
11493
11652
  return false;
11494
11653
  }
11495
- `);
11654
+ }
11496
11655
  /**
11497
11656
  * TODO: [🎺]
11498
11657
  */
@@ -11504,13 +11663,14 @@ const $isRunningInJest = new Function(`
11504
11663
  *
11505
11664
  * @public exported from `@promptbook/utils`
11506
11665
  */
11507
- const $isRunningInNode = new Function(`
11666
+ function $isRunningInNode() {
11508
11667
  try {
11509
- return this === global;
11510
- } catch (e) {
11668
+ return typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
11669
+ }
11670
+ catch (e) {
11511
11671
  return false;
11512
11672
  }
11513
- `);
11673
+ }
11514
11674
  /**
11515
11675
  * TODO: [🎺]
11516
11676
  */
@@ -11522,17 +11682,17 @@ const $isRunningInNode = new Function(`
11522
11682
  *
11523
11683
  * @public exported from `@promptbook/utils`
11524
11684
  */
11525
- const $isRunningInWebWorker = new Function(`
11685
+ function $isRunningInWebWorker() {
11526
11686
  try {
11527
- if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
11528
- return true;
11529
- } else {
11530
- return false;
11531
- }
11532
- } catch (e) {
11687
+ // Note: Check for importScripts which is specific to workers
11688
+ // and not available in the main browser thread
11689
+ return (typeof self !== 'undefined' &&
11690
+ typeof self.importScripts === 'function');
11691
+ }
11692
+ catch (e) {
11533
11693
  return false;
11534
11694
  }
11535
- `);
11695
+ }
11536
11696
  /**
11537
11697
  * TODO: [🎺]
11538
11698
  */
@@ -11790,6 +11950,7 @@ function parseAgentSource(agentSource) {
11790
11950
  return {
11791
11951
  agentName: normalizeAgentName(parseResult.agentName || createDefaultAgentName(agentSource)),
11792
11952
  agentHash,
11953
+ permanentId: meta.id,
11793
11954
  personaDescription,
11794
11955
  initialMessage,
11795
11956
  meta,
@@ -11981,6 +12142,41 @@ const DEFAULT_BOOK = padBook(validateBook(spaceTrim$2(`
11981
12142
  // <- [🐱‍🚀] Buttons into genesis book
11982
12143
  // <- TODO: [🐱‍🚀] generateBookBoilerplate and deprecate `DEFAULT_BOOK`
11983
12144
 
12145
+ /**
12146
+ * Base58 characters
12147
+ */
12148
+ const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
12149
+ /**
12150
+ * Generates random base58 string
12151
+ *
12152
+ * Note: `$` is used to indicate that this function is not a pure function - it is not deterministic
12153
+ * Note: This function is cryptographically secure (it uses crypto.randomBytes internally)
12154
+ *
12155
+ * @param length - length of the string
12156
+ * @returns secure random base58 string
12157
+ *
12158
+ * @private internal helper function
12159
+ */
12160
+ function $randomBase58(length) {
12161
+ let result = '';
12162
+ while (result.length < length) {
12163
+ // Generate enough bytes to cover the remaining length, plus some extra buffer to reduce calls
12164
+ // But simply generating `length - result.length` is fine for small lengths
12165
+ const bytes = randomBytes(length - result.length);
12166
+ for (let i = 0; i < bytes.length; i++) {
12167
+ const byte = bytes[i];
12168
+ // 58 * 4 = 232
12169
+ // We discard values >= 232 to avoid modulo bias
12170
+ if (byte < 232) {
12171
+ result += BASE58_ALPHABET[byte % 58];
12172
+ if (result.length === length)
12173
+ break;
12174
+ }
12175
+ }
12176
+ }
12177
+ return result;
12178
+ }
12179
+
11984
12180
  // import { getTableName } from '../../../../../apps/agents-server/src/database/getTableName';
11985
12181
  // <- TODO: [🐱‍🚀] Prevent imports from `/apps` -> `/src`
11986
12182
  /**
@@ -12014,19 +12210,20 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12014
12210
  const { isVerbose = DEFAULT_IS_VERBOSE } = this.options || {};
12015
12211
  const selectResult = await this.supabaseClient
12016
12212
  .from(this.getTableName('Agent'))
12017
- .select('agentName,agentProfile');
12213
+ .select('agentName,agentProfile,permanentId')
12214
+ .is('deletedAt', null);
12018
12215
  if (selectResult.error) {
12019
12216
  throw new DatabaseError(spaceTrim((block) => `
12020
-
12217
+
12021
12218
  Error fetching agents from Supabase:
12022
-
12219
+
12023
12220
  ${block(selectResult.error.message)}
12024
12221
  `));
12025
12222
  }
12026
12223
  if (isVerbose) {
12027
12224
  console.info(`Found ${selectResult.data.length} agents in directory`);
12028
12225
  }
12029
- return selectResult.data.map(({ agentName, agentProfile }) => {
12226
+ return selectResult.data.map(({ agentName, agentProfile, permanentId }) => {
12030
12227
  if (isVerbose && agentProfile.agentName !== agentName) {
12031
12228
  console.warn(spaceTrim(`
12032
12229
  Agent name mismatch for agent "${agentName}". Using name from database.
@@ -12038,6 +12235,7 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12038
12235
  return {
12039
12236
  ...agentProfile,
12040
12237
  agentName,
12238
+ permanentId: permanentId || agentProfile.permanentId,
12041
12239
  };
12042
12240
  });
12043
12241
  }
@@ -12048,7 +12246,7 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12048
12246
  const selectResult = await this.supabaseClient
12049
12247
  .from(this.getTableName('Agent'))
12050
12248
  .select('agentSource')
12051
- .eq('agentName', agentName);
12249
+ .or(`agentName.eq.${agentName},permanentId.eq.${agentName}`);
12052
12250
  if (selectResult.data && selectResult.data.length === 0) {
12053
12251
  throw new NotFoundError(`Agent "${agentName}" not found`);
12054
12252
  }
@@ -12070,12 +12268,26 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12070
12268
  * Note: You can set 'PARENT' in the agent source to inherit from another agent in the collection.
12071
12269
  */
12072
12270
  async createAgent(agentSource) {
12073
- const agentProfile = parseAgentSource(agentSource);
12271
+ let agentProfile = parseAgentSource(agentSource);
12074
12272
  // <- TODO: [🕛]
12075
12273
  const { agentName, agentHash } = agentProfile;
12274
+ let { permanentId } = agentProfile;
12275
+ if (!permanentId) {
12276
+ permanentId = $randomBase58(14);
12277
+ const lines = agentSource.split('\n');
12278
+ if (lines.length > 0) {
12279
+ lines.splice(1, 0, `META ID ${permanentId}`);
12280
+ agentSource = lines.join('\n');
12281
+ }
12282
+ else {
12283
+ agentSource = `META ID ${permanentId}\n${agentSource}`;
12284
+ }
12285
+ agentProfile = parseAgentSource(agentSource);
12286
+ }
12076
12287
  const insertAgentResult = await this.supabaseClient.from(this.getTableName('Agent')).insert({
12077
12288
  agentName,
12078
12289
  agentHash,
12290
+ permanentId,
12079
12291
  agentProfile,
12080
12292
  createdAt: new Date().toISOString(),
12081
12293
  updatedAt: null,
@@ -12099,15 +12311,16 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12099
12311
  promptbookEngineVersion: PROMPTBOOK_ENGINE_VERSION,
12100
12312
  });
12101
12313
  // <- TODO: [🧠] What to do with `insertAgentHistoryResult.error`, ignore? wait?
12102
- return agentProfile;
12314
+ return { ...agentProfile, permanentId };
12103
12315
  }
12104
12316
  /**
12105
12317
  * Updates an existing agent in the collection
12106
12318
  */
12107
12319
  async updateAgentSource(agentName, agentSource) {
12320
+ console.log('!!! updateAgentSource', { agentName });
12108
12321
  const selectPreviousAgentResult = await this.supabaseClient
12109
12322
  .from(this.getTableName('Agent'))
12110
- .select('agentHash,agentName')
12323
+ .select('agentHash,agentName,permanentId')
12111
12324
  .eq('agentName', agentName)
12112
12325
  .single();
12113
12326
  if (selectPreviousAgentResult.error) {
@@ -12121,13 +12334,28 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12121
12334
  }
12122
12335
  selectPreviousAgentResult.data.agentName;
12123
12336
  const previousAgentHash = selectPreviousAgentResult.data.agentHash;
12124
- const agentProfile = parseAgentSource(agentSource);
12337
+ const previousPermanentId = selectPreviousAgentResult.data.permanentId;
12338
+ let agentProfile = parseAgentSource(agentSource);
12125
12339
  // <- TODO: [🕛]
12126
12340
  const { agentHash } = agentProfile;
12341
+ let { permanentId } = agentProfile;
12342
+ if (!permanentId && previousPermanentId) {
12343
+ permanentId = previousPermanentId;
12344
+ const lines = agentSource.split('\n');
12345
+ if (lines.length > 0) {
12346
+ lines.splice(1, 0, `META ID ${permanentId}`);
12347
+ agentSource = lines.join('\n');
12348
+ }
12349
+ else {
12350
+ agentSource = `META ID ${permanentId}\n${agentSource}`;
12351
+ }
12352
+ agentProfile = parseAgentSource(agentSource);
12353
+ }
12127
12354
  const updateAgentResult = await this.supabaseClient
12128
12355
  .from(this.getTableName('Agent'))
12129
12356
  .update({
12130
12357
  // TODO: [🐱‍🚀] Compare not update> agentName: agentProfile.agentName || '[🐱‍🚀]' /* <- TODO: [🐱‍🚀] Remove */,
12358
+ permanentId,
12131
12359
  agentProfile,
12132
12360
  updatedAt: new Date().toISOString(),
12133
12361
  agentHash: agentProfile.agentHash,
@@ -12158,20 +12386,39 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12158
12386
  // TODO: [🐱‍🚀] public async getAgentSourceSubject(agentName: string_agent_name): Promise<BehaviorSubject<string_book>>
12159
12387
  // Use Supabase realtime logic
12160
12388
  /**
12161
- * Deletes an agent from the collection
12389
+ * List agents that are soft deleted (deletedAt IS NOT NULL)
12162
12390
  */
12163
- async deleteAgent(agentName) {
12164
- const deleteResult = await this.supabaseClient
12391
+ async listDeletedAgents() {
12392
+ const { isVerbose = DEFAULT_IS_VERBOSE } = this.options || {};
12393
+ const selectResult = await this.supabaseClient
12165
12394
  .from(this.getTableName('Agent'))
12166
- .delete()
12167
- .eq('agentName', agentName);
12168
- if (deleteResult.error) {
12395
+ .select('agentName,agentProfile,permanentId')
12396
+ .not('deletedAt', 'is', null);
12397
+ if (selectResult.error) {
12169
12398
  throw new DatabaseError(spaceTrim((block) => `
12170
- Error deleting agent "${agentName}" from Supabase:
12171
-
12172
- ${block(deleteResult.error.message)}
12173
- `));
12399
+ Error fetching deleted agents from Supabase:
12400
+
12401
+ ${block(selectResult.error.message)}
12402
+ `));
12403
+ }
12404
+ if (isVerbose) {
12405
+ console.info(`Found ${selectResult.data.length} deleted agents in directory`);
12174
12406
  }
12407
+ return selectResult.data.map(({ agentName, agentProfile, permanentId }) => {
12408
+ if (isVerbose && agentProfile.agentName !== agentName) {
12409
+ console.warn(spaceTrim(`
12410
+ Agent name mismatch for agent "${agentName}". Using name from database.
12411
+
12412
+ agentName: "${agentName}"
12413
+ agentProfile.agentName: "${agentProfile.agentName}"
12414
+ `));
12415
+ }
12416
+ return {
12417
+ ...agentProfile,
12418
+ agentName,
12419
+ permanentId: permanentId || agentProfile.permanentId,
12420
+ };
12421
+ });
12175
12422
  }
12176
12423
  /**
12177
12424
  * List history of an agent
@@ -12185,71 +12432,70 @@ class AgentCollectionInSupabase /* TODO: [🐱‍🚀] implements Agent */ {
12185
12432
  if (result.error) {
12186
12433
  throw new DatabaseError(spaceTrim((block) => `
12187
12434
  Error listing history for agent "${agentName}" from Supabase:
12188
-
12435
+
12189
12436
  ${block(result.error.message)}
12190
12437
  `));
12191
12438
  }
12192
12439
  return result.data;
12193
12440
  }
12194
12441
  /**
12195
- * List agents that are in history but not in the active agents list
12442
+ * Restore a soft-deleted agent by setting deletedAt to NULL
12196
12443
  */
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) {
12444
+ async restoreAgent(agentIdentifier) {
12445
+ const updateResult = await this.supabaseClient
12446
+ .from(this.getTableName('Agent'))
12447
+ .update({ deletedAt: null })
12448
+ .or(`agentName.eq.${agentIdentifier},permanentId.eq.${agentIdentifier}`)
12449
+ .not('deletedAt', 'is', null);
12450
+ if (updateResult.error) {
12208
12451
  throw new DatabaseError(spaceTrim((block) => `
12209
- Error fetching current agent names from Supabase:
12210
-
12211
- ${block(currentNamesResult.error.message)}
12452
+ Error restoring agent "${agentIdentifier}" from Supabase:
12453
+
12454
+ ${block(updateResult.error.message)}
12212
12455
  `));
12213
12456
  }
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
12457
  }
12223
12458
  /**
12224
- * Restore an agent from history
12459
+ * Restore an agent from a specific history entry
12460
+ *
12461
+ * This will update the current agent with the source from the history entry
12225
12462
  */
12226
- async restoreAgent(historyId) {
12463
+ async restoreAgentFromHistory(historyId) {
12464
+ // First, get the history entry
12227
12465
  const historyResult = await this.supabaseClient
12228
12466
  .from(this.getTableName('AgentHistory'))
12229
- .select('*')
12467
+ .select('agentName, agentSource')
12230
12468
  .eq('id', historyId)
12231
12469
  .single();
12232
12470
  if (historyResult.error) {
12233
12471
  throw new DatabaseError(spaceTrim((block) => `
12234
- Error fetching agent history item "${historyId}" from Supabase:
12235
-
12472
+ Error fetching history entry with id "${historyId}" from Supabase:
12473
+
12236
12474
  ${block(historyResult.error.message)}
12237
12475
  `));
12238
12476
  }
12477
+ if (!historyResult.data) {
12478
+ throw new NotFoundError(`History entry with id "${historyId}" not found`);
12479
+ }
12239
12480
  const { agentName, agentSource } = historyResult.data;
12240
- // Check if agent exists
12241
- const agentResult = await this.supabaseClient
12481
+ // Update the agent with the source from the history entry
12482
+ await this.updateAgentSource(agentName, agentSource);
12483
+ }
12484
+ /**
12485
+ * Soft delete an agent by setting deletedAt to current timestamp
12486
+ */
12487
+ async deleteAgent(agentIdentifier) {
12488
+ const updateResult = await this.supabaseClient
12242
12489
  .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);
12249
- }
12250
- else {
12251
- // Insert (Restore from deleted)
12252
- await this.createAgent(agentSource);
12490
+ .update({ deletedAt: new Date().toISOString() })
12491
+ .or(`agentName.eq.${agentIdentifier},permanentId.eq.${agentIdentifier}`)
12492
+ .is('deletedAt', null);
12493
+ if (updateResult.error) {
12494
+ throw new DatabaseError(spaceTrim((block) => `
12495
+ Error deleting agent "${agentIdentifier}" from Supabase:
12496
+
12497
+ ${block(updateResult.error.message)}
12498
+ `));
12253
12499
  }
12254
12500
  }
12255
12501
  /**
@@ -16467,7 +16713,7 @@ function $registeredLlmToolsMessage() {
16467
16713
  ${i + 1}) **${title}** \`${className}\` from \`${packageName}\`
16468
16714
  ${morePieces.join('; ')}
16469
16715
  `);
16470
- if ($isRunningInNode) {
16716
+ if ($isRunningInNode()) {
16471
16717
  if (isInstalled && isFullyConfigured) {
16472
16718
  providerMessage = colors.green(providerMessage);
16473
16719
  }
@@ -17868,7 +18114,7 @@ class OpenAiCompatibleExecutionTools {
17868
18114
  let threadMessages = [];
17869
18115
  if ('thread' in prompt && Array.isArray(prompt.thread)) {
17870
18116
  threadMessages = prompt.thread.map((msg) => ({
17871
- role: msg.role === 'assistant' ? 'assistant' : 'user',
18117
+ role: msg.sender === 'assistant' ? 'assistant' : 'user',
17872
18118
  content: msg.content,
17873
18119
  }));
17874
18120
  }