@promptbook/cli 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 (128) hide show
  1. package/apps/agents-server/next.config.ts +2 -2
  2. package/apps/agents-server/package.json +7 -3
  3. package/apps/agents-server/public/fonts/OpenMoji-color-cbdt.woff2 +0 -0
  4. package/apps/agents-server/public/swagger.json +115 -0
  5. package/apps/agents-server/scripts/generate-reserved-paths/generate-reserved-paths.ts +54 -0
  6. package/apps/agents-server/scripts/generate-reserved-paths/tsconfig.json +19 -0
  7. package/apps/agents-server/src/app/AddAgentButton.tsx +3 -3
  8. package/apps/agents-server/src/app/actions.ts +17 -5
  9. package/apps/agents-server/src/app/admin/chat-feedback/ChatFeedbackClient.tsx +221 -274
  10. package/apps/agents-server/src/app/admin/chat-history/ChatHistoryClient.tsx +94 -137
  11. package/apps/agents-server/src/app/admin/metadata/MetadataClient.tsx +23 -19
  12. package/apps/agents-server/src/app/agents/[agentName]/AgentChatWrapper.tsx +15 -1
  13. package/apps/agents-server/src/app/agents/[agentName]/AgentOptionsMenu.tsx +51 -9
  14. package/apps/agents-server/src/app/agents/[agentName]/AgentProfileChat.tsx +47 -4
  15. package/apps/agents-server/src/app/agents/[agentName]/AgentProfileWrapper.tsx +2 -0
  16. package/apps/agents-server/src/app/agents/[agentName]/_utils.ts +18 -0
  17. package/apps/agents-server/src/app/agents/[agentName]/agentLinks.tsx +8 -8
  18. package/apps/agents-server/src/app/agents/[agentName]/api/agents/route.ts +17 -26
  19. package/apps/agents-server/src/app/agents/[agentName]/api/chat/route.ts +20 -0
  20. package/apps/agents-server/src/app/agents/[agentName]/api/mcp/route.ts +6 -11
  21. package/apps/agents-server/src/app/agents/[agentName]/api/profile/route.ts +1 -1
  22. package/apps/agents-server/src/app/agents/[agentName]/api/voice/route.ts +5 -2
  23. package/apps/agents-server/src/app/agents/[agentName]/book/BookEditorWrapper.tsx +20 -16
  24. package/apps/agents-server/src/app/agents/[agentName]/book/page.tsx +15 -2
  25. package/apps/agents-server/src/app/agents/[agentName]/book+chat/page.tsx +15 -2
  26. package/apps/agents-server/src/app/agents/[agentName]/chat/page.tsx +12 -0
  27. package/apps/agents-server/src/app/agents/[agentName]/code/api/route.ts +68 -0
  28. package/apps/agents-server/src/app/agents/[agentName]/code/page.tsx +214 -0
  29. package/apps/agents-server/src/app/agents/[agentName]/generateAgentMetadata.ts +5 -0
  30. package/apps/agents-server/src/app/agents/[agentName]/history/actions.ts +2 -2
  31. package/apps/agents-server/src/app/agents/[agentName]/integration/page.tsx +1 -1
  32. package/apps/agents-server/src/app/agents/[agentName]/links/page.tsx +2 -2
  33. package/apps/agents-server/src/app/agents/[agentName]/page.tsx +12 -6
  34. package/apps/agents-server/src/app/agents/[agentName]/system-message/page.tsx +87 -0
  35. package/apps/agents-server/src/app/api/admin-email/route.ts +12 -0
  36. package/apps/agents-server/src/app/api/agents/[agentName]/clone/route.ts +10 -12
  37. package/apps/agents-server/src/app/api/agents/[agentName]/restore/route.ts +19 -0
  38. package/apps/agents-server/src/app/api/agents/[agentName]/route.ts +41 -0
  39. package/apps/agents-server/src/app/api/agents/route.ts +28 -3
  40. package/apps/agents-server/src/app/api/api-tokens/route.ts +6 -7
  41. package/apps/agents-server/src/app/api/docs/book.md/route.ts +61 -0
  42. package/apps/agents-server/src/app/api/federated-agents/route.ts +12 -0
  43. package/apps/agents-server/src/app/api/images/[filename]/route.ts +107 -0
  44. package/apps/agents-server/src/app/api/metadata/route.ts +5 -6
  45. package/apps/agents-server/src/app/api/upload/route.ts +128 -45
  46. package/apps/agents-server/src/app/docs/[docId]/page.tsx +2 -3
  47. package/apps/agents-server/src/app/docs/page.tsx +12 -12
  48. package/apps/agents-server/src/app/globals.css +140 -33
  49. package/apps/agents-server/src/app/layout.tsx +27 -22
  50. package/apps/agents-server/src/app/page.tsx +50 -4
  51. package/apps/agents-server/src/app/recycle-bin/actions.ts +20 -14
  52. package/apps/agents-server/src/app/recycle-bin/page.tsx +25 -41
  53. package/apps/agents-server/src/app/sitemap.xml/route.ts +6 -3
  54. package/apps/agents-server/src/app/swagger/page.tsx +14 -0
  55. package/apps/agents-server/src/components/AgentProfile/AgentProfile.tsx +9 -98
  56. package/apps/agents-server/src/components/AgentProfile/QrCodeModal.tsx +0 -1
  57. package/apps/agents-server/src/components/AgentProfile/useAgentBackground.ts +97 -0
  58. package/apps/agents-server/src/components/Auth/AuthControls.tsx +5 -4
  59. package/apps/agents-server/src/components/DeletedAgentBanner.tsx +26 -0
  60. package/apps/agents-server/src/components/DocsToolbar/DocsToolbar.tsx +38 -0
  61. package/apps/agents-server/src/components/DocumentationContent/DocumentationContent.tsx +11 -9
  62. package/apps/agents-server/src/components/Footer/Footer.tsx +5 -5
  63. package/apps/agents-server/src/components/ForgottenPasswordDialog/ForgottenPasswordDialog.tsx +61 -0
  64. package/apps/agents-server/src/components/Header/Header.tsx +106 -40
  65. package/apps/agents-server/src/components/Homepage/AgentCard.tsx +104 -20
  66. package/apps/agents-server/src/components/Homepage/AgentsList.tsx +72 -12
  67. package/apps/agents-server/src/components/Homepage/DeletedAgentsList.tsx +50 -0
  68. package/apps/agents-server/src/components/LayoutWrapper/LayoutWrapper.tsx +3 -2
  69. package/apps/agents-server/src/components/LoginForm/LoginForm.tsx +50 -1
  70. package/apps/agents-server/src/components/NotFoundPage/NotFoundPage.tsx +7 -2
  71. package/apps/agents-server/src/components/OpenMojiIcon/OpenMojiIcon.tsx +16 -7
  72. package/apps/agents-server/src/components/PrintHeader/PrintHeader.tsx +4 -4
  73. package/apps/agents-server/src/components/RegisterUserDialog/RegisterUserDialog.tsx +61 -0
  74. package/apps/agents-server/src/components/_utils/headlessParam.tsx +7 -3
  75. package/apps/agents-server/src/database/metadataDefaults.ts +19 -1
  76. package/apps/agents-server/src/database/migrations/2025-12-0240-agent-public-id.sql +3 -0
  77. package/apps/agents-server/src/database/migrations/2025-12-0360-agent-deleted-at.sql +1 -0
  78. package/apps/agents-server/src/database/migrations/2025-12-0370-image-table.sql +19 -0
  79. package/apps/agents-server/src/database/migrations/2025-12-0380-agent-visibility.sql +1 -0
  80. package/apps/agents-server/src/database/migrations/2025-12-0390-upload-tracking.sql +20 -0
  81. package/apps/agents-server/src/database/migrations/2025-12-0401-file-upload-status.sql +13 -0
  82. package/apps/agents-server/src/database/migrations/2025-12-0640-openai-assistant-cache.sql +12 -0
  83. package/apps/agents-server/src/database/schema.ts +109 -0
  84. package/apps/agents-server/src/generated/reservedPaths.ts +32 -0
  85. package/apps/agents-server/src/middleware.ts +19 -23
  86. package/apps/agents-server/src/tools/$provideCdnForServer.ts +6 -1
  87. package/apps/agents-server/src/utils/auth.ts +117 -17
  88. package/apps/agents-server/src/utils/cdn/classes/TrackedFilesStorage.ts +57 -0
  89. package/apps/agents-server/src/utils/cdn/classes/VercelBlobStorage.ts +4 -0
  90. package/apps/agents-server/src/utils/cdn/interfaces/IFilesStorage.ts +18 -0
  91. package/apps/agents-server/src/utils/getUserIdFromRequest.ts +35 -0
  92. package/apps/agents-server/src/utils/handleChatCompletion.ts +65 -5
  93. package/apps/agents-server/src/utils/normalization/filenameToPrompt.ts +21 -0
  94. package/apps/agents-server/src/utils/validateApiKey.ts +7 -11
  95. package/esm/index.es.js +194 -34
  96. package/esm/index.es.js.map +1 -1
  97. package/esm/typings/src/_packages/types.index.d.ts +8 -2
  98. package/esm/typings/src/book-2.0/agent-source/AgentBasicInformation.d.ts +6 -1
  99. package/esm/typings/src/book-components/Chat/Chat/ChatMessageItem.d.ts +5 -1
  100. package/esm/typings/src/book-components/Chat/Chat/ChatProps.d.ts +5 -0
  101. package/esm/typings/src/book-components/Chat/CodeBlock/CodeBlock.d.ts +13 -0
  102. package/esm/typings/src/book-components/Chat/MarkdownContent/MarkdownContent.d.ts +1 -0
  103. package/esm/typings/src/book-components/Chat/types/ChatMessage.d.ts +7 -11
  104. package/esm/typings/src/book-components/_common/Dropdown/Dropdown.d.ts +2 -2
  105. package/esm/typings/src/book-components/_common/MenuHoisting/MenuHoistingContext.d.ts +56 -0
  106. package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentCollectionInSupabase.d.ts +13 -7
  107. package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentsDatabaseSchema.d.ts +6 -0
  108. package/esm/typings/src/commitments/DICTIONARY/DICTIONARY.d.ts +46 -0
  109. package/esm/typings/src/commitments/index.d.ts +2 -1
  110. package/esm/typings/src/llm-providers/ollama/OllamaExecutionTools.d.ts +1 -1
  111. package/esm/typings/src/llm-providers/openai/createOpenAiCompatibleExecutionTools.d.ts +1 -1
  112. package/esm/typings/src/types/Message.d.ts +49 -0
  113. package/esm/typings/src/types/typeAliases.d.ts +12 -0
  114. package/esm/typings/src/utils/environment/$detectRuntimeEnvironment.d.ts +4 -4
  115. package/esm/typings/src/utils/environment/$isRunningInBrowser.d.ts +1 -1
  116. package/esm/typings/src/utils/environment/$isRunningInJest.d.ts +1 -1
  117. package/esm/typings/src/utils/environment/$isRunningInNode.d.ts +1 -1
  118. package/esm/typings/src/utils/environment/$isRunningInWebWorker.d.ts +1 -1
  119. package/esm/typings/src/utils/markdown/extractAllBlocksFromMarkdown.d.ts +2 -2
  120. package/esm/typings/src/utils/markdown/extractOneBlockFromMarkdown.d.ts +2 -2
  121. package/esm/typings/src/utils/random/$randomBase58.d.ts +12 -0
  122. package/esm/typings/src/version.d.ts +1 -1
  123. package/package.json +1 -1
  124. package/umd/index.umd.js +200 -40
  125. package/umd/index.umd.js.map +1 -1
  126. package/apps/agents-server/package-lock.json +0 -27
  127. package/apps/agents-server/public/fonts/download-font.js +0 -22
  128. package/apps/agents-server/src/components/PrintButton/PrintButton.tsx +0 -18
@@ -1,33 +1,133 @@
1
- import { randomBytes, scrypt, timingSafeEqual } from 'crypto';
1
+ import { createHash, randomBytes, scrypt, timingSafeEqual } from 'crypto';
2
2
  import { promisify } from 'util';
3
+ import { PASSWORD_SECURITY_CONFIG } from '../../../../security.config';
3
4
 
4
5
  const scryptAsync = promisify(scrypt);
5
6
 
6
7
  /**
7
- * Hashes a password using scrypt
8
- *
9
- * @param password The plain text password
8
+ * Validates password input to prevent edge cases and DoS attacks
9
+ *
10
+ * @param password The password to validate
11
+ * @throws Error if password is invalid
12
+ */
13
+ function validatePasswordInput(password: string): void {
14
+ if (typeof password !== 'string') {
15
+ throw new Error('Password must be a string');
16
+ }
17
+ if (password.length === 0) {
18
+ throw new Error('Password cannot be empty');
19
+ }
20
+ if (password.length < PASSWORD_SECURITY_CONFIG.MIN_PASSWORD_LENGTH) {
21
+ throw new Error(`Password must be at least ${PASSWORD_SECURITY_CONFIG.MIN_PASSWORD_LENGTH} characters`);
22
+ }
23
+ // Note: No hard max limit - long passwords are compacted via compactPassword()
24
+ }
25
+
26
+ /**
27
+ * Compacts a password for secure processing
28
+ *
29
+ * If the password is within MAX_PASSWORD_LENGTH, it is returned as-is.
30
+ * If longer, the password is split at MAX_PASSWORD_LENGTH and the second part
31
+ * is hashed with SHA256 before being appended to the first part.
32
+ *
33
+ * This prevents DoS attacks via extremely long passwords while still utilizing
34
+ * the full entropy of longer passwords.
35
+ *
36
+ * @param password The password to compact
37
+ * @returns The compacted password
38
+ */
39
+ function compactPassword(password: string): string {
40
+ if (password.length <= PASSWORD_SECURITY_CONFIG.MAX_PASSWORD_LENGTH) {
41
+ return password;
42
+ }
43
+
44
+ const firstPart = password.slice(0, PASSWORD_SECURITY_CONFIG.MAX_PASSWORD_LENGTH);
45
+ const secondPart = password.slice(PASSWORD_SECURITY_CONFIG.MAX_PASSWORD_LENGTH);
46
+
47
+ // Hash the overflow part with SHA256 to bound its length while preserving entropy
48
+ const secondPartHash = createHash('sha256').update(secondPart, 'utf8').digest('hex');
49
+
50
+ return firstPart + secondPartHash;
51
+ }
52
+
53
+ /**
54
+ * Hashes a password using scrypt with secure parameters
55
+ *
56
+ * @param password The plain text password (minimum 8 characters, no maximum - long passwords are compacted)
10
57
  * @returns The salt and hash formatted as "salt:hash"
58
+ * @throws Error if password validation fails
11
59
  */
12
60
  export async function hashPassword(password: string): Promise<string> {
13
- const salt = randomBytes(16).toString('hex');
14
- const derivedKey = (await scryptAsync(password, salt, 64)) as Buffer;
61
+ validatePasswordInput(password);
62
+
63
+ // Compact long passwords to prevent DoS while preserving entropy
64
+ const compactedPassword = compactPassword(password);
65
+
66
+ const salt = randomBytes(PASSWORD_SECURITY_CONFIG.SALT_LENGTH).toString('hex');
67
+ const derivedKey = (await scryptAsync(compactedPassword, salt, PASSWORD_SECURITY_CONFIG.KEY_LENGTH)) as Buffer;
68
+
69
+ // Clear password from memory as soon as possible (best effort)
70
+ // Note: JavaScript strings are immutable, so this is limited in effectiveness
15
71
  return `${salt}:${derivedKey.toString('hex')}`;
16
72
  }
17
73
 
18
74
  /**
19
- * Verifies a password against a stored hash
20
- *
21
- * @param password The plain text password
75
+ * Verifies a password against a stored hash using constant-time comparison
76
+ *
77
+ * @param password The plain text password to verify
22
78
  * @param storedHash The stored hash in format "salt:hash"
23
- * @returns True if the password matches
79
+ * @returns True if the password matches, false otherwise
24
80
  */
25
81
  export async function verifyPassword(password: string, storedHash: string): Promise<boolean> {
26
- const [salt, key] = storedHash.split(':');
27
- if (!salt || !key) return false;
28
-
29
- const derivedKey = (await scryptAsync(password, salt, 64)) as Buffer;
30
- const keyBuffer = Buffer.from(key, 'hex');
31
-
32
- return timingSafeEqual(derivedKey, keyBuffer);
82
+ // Validate inputs
83
+ if (typeof password !== 'string' || typeof storedHash !== 'string') {
84
+ return false;
85
+ }
86
+
87
+ if (password.length === 0) {
88
+ return false;
89
+ }
90
+
91
+ // Compact long passwords the same way as during hashing
92
+ const compactedPassword = compactPassword(password);
93
+
94
+ const parts = storedHash.split(':');
95
+ if (parts.length !== 2) {
96
+ return false;
97
+ }
98
+
99
+ const [salt, key] = parts;
100
+ if (!salt || !key) {
101
+ return false;
102
+ }
103
+
104
+ // Validate salt and key format (should be hex strings of expected length)
105
+ const expectedSaltLength = PASSWORD_SECURITY_CONFIG.SALT_LENGTH * 2; // hex encoding doubles length
106
+ const expectedKeyLength = PASSWORD_SECURITY_CONFIG.KEY_LENGTH * 2;
107
+
108
+ if (salt.length !== expectedSaltLength || key.length !== expectedKeyLength) {
109
+ return false;
110
+ }
111
+
112
+ // Validate hex format
113
+ const hexRegex = /^[0-9a-fA-F]+$/;
114
+ if (!hexRegex.test(salt) || !hexRegex.test(key)) {
115
+ return false;
116
+ }
117
+
118
+ try {
119
+ const derivedKey = (await scryptAsync(compactedPassword, salt, PASSWORD_SECURITY_CONFIG.KEY_LENGTH)) as Buffer;
120
+ const keyBuffer = Buffer.from(key, 'hex');
121
+
122
+ // Ensure buffers are same length before timing-safe comparison
123
+ // This should always be true given our validation, but defense in depth
124
+ if (derivedKey.length !== keyBuffer.length) {
125
+ return false;
126
+ }
127
+
128
+ return timingSafeEqual(derivedKey, keyBuffer);
129
+ } catch {
130
+ // Any error during verification should return false, not leak information
131
+ return false;
132
+ }
33
133
  }
@@ -0,0 +1,57 @@
1
+ import { SupabaseClient } from '@supabase/supabase-js';
2
+ import { $getTableName } from '../../../database/$getTableName';
3
+ import { AgentsServerDatabase } from '../../../database/schema';
4
+ import type { IFile, IIFilesStorageWithCdn } from '../interfaces/IFilesStorage';
5
+
6
+ export class TrackedFilesStorage implements IIFilesStorageWithCdn {
7
+ public constructor(
8
+ private readonly inner: IIFilesStorageWithCdn,
9
+ private readonly supabase: SupabaseClient<AgentsServerDatabase>,
10
+ ) {}
11
+
12
+ public get cdnPublicUrl(): URL {
13
+ return this.inner.cdnPublicUrl;
14
+ }
15
+
16
+ public get pathPrefix(): string | undefined {
17
+ return this.inner.pathPrefix;
18
+ }
19
+
20
+ public getItemUrl(key: string): URL {
21
+ return this.inner.getItemUrl(key);
22
+ }
23
+
24
+ public async getItem(key: string): Promise<IFile | null> {
25
+ return this.inner.getItem(key);
26
+ }
27
+
28
+ public async removeItem(key: string): Promise<void> {
29
+ return this.inner.removeItem(key);
30
+ }
31
+
32
+ public async setItem(key: string, file: IFile): Promise<void> {
33
+ console.log('!!! 0', { key, file });
34
+
35
+ await this.inner.setItem(key, file);
36
+
37
+ try {
38
+ const { userId, purpose } = file;
39
+ const cdnUrl = this.getItemUrl(key).href;
40
+
41
+ console.log('!!! 1', { userId, purpose, cdnUrl, key, file });
42
+
43
+ await this.supabase.from(await $getTableName('File')).insert({
44
+ userId: userId || null,
45
+ fileName: key,
46
+ fileSize: file.fileSize ?? file.data.length,
47
+ fileType: file.type,
48
+ cdnUrl,
49
+ purpose: purpose || 'UNKNOWN',
50
+ });
51
+
52
+ console.log('!!! 2', { userId, purpose, cdnUrl, key, file });
53
+ } catch (error) {
54
+ console.error('Failed to track upload:', error);
55
+ }
56
+ }
57
+ }
@@ -14,6 +14,10 @@ export class VercelBlobStorage implements IIFilesStorageWithCdn {
14
14
  return this.config.cdnPublicUrl;
15
15
  }
16
16
 
17
+ public get pathPrefix() {
18
+ return this.config.pathPrefix;
19
+ }
20
+
17
21
  public constructor(private readonly config: IVercelBlobStorageConfig) {}
18
22
 
19
23
  public getItemUrl(key: string): URL {
@@ -5,6 +5,23 @@ export type IFile = {
5
5
  // Maybe TODO name: string_name;
6
6
  type: string_mime_type;
7
7
  data: Buffer;
8
+
9
+ /**
10
+ * User who uploaded the file
11
+ */
12
+ userId?: number;
13
+
14
+ /**
15
+ * Purpose of the upload (e.g. KNOWLEDGE, SERVER_FAVICON_URL)
16
+ */
17
+ purpose?: string;
18
+
19
+ /**
20
+ * Size of the file in bytes
21
+ *
22
+ * Note: This is optional, if not provided, the size of the buffer is used
23
+ */
24
+ fileSize?: number;
8
25
  };
9
26
 
10
27
  /**
@@ -17,6 +34,7 @@ export type IFilesStorage = Omit<IStorage<IFile>, 'length' | 'clear' | 'key'>;
17
34
  */
18
35
  export type IIFilesStorageWithCdn = IFilesStorage & {
19
36
  readonly cdnPublicUrl: URL;
37
+ readonly pathPrefix?: string;
20
38
  getItemUrl(key: string): URL;
21
39
  };
22
40
 
@@ -0,0 +1,35 @@
1
+ import { NextRequest } from 'next/server';
2
+ import { keepUnused } from '../../../../src/utils/organization/keepUnused';
3
+ import { $getTableName } from '../database/$getTableName';
4
+ import { $provideSupabaseForServer } from '../database/$provideSupabaseForServer';
5
+ import { getSession } from './session';
6
+
7
+ export async function getUserIdFromRequest(request: NextRequest): Promise<number | null> {
8
+ keepUnused(request); // Unused because we get user from session cookie for now
9
+
10
+ try {
11
+ // 1. Try to get user from session (cookie)
12
+ const session = await getSession();
13
+ if (session && session.username) {
14
+ const supabase = $provideSupabaseForServer();
15
+ const { data } = await supabase
16
+ .from(await $getTableName('User'))
17
+ .select('id')
18
+ .eq('username', session.username)
19
+ .single();
20
+
21
+ if (data) {
22
+ return data.id;
23
+ }
24
+ }
25
+
26
+ // 2. Try to get user from API key (Authorization header)
27
+ // TODO: [🧠] Implement linking API keys to users if needed
28
+ // const authHeader = request.headers.get('authorization');
29
+ // ...
30
+ } catch (error) {
31
+ console.error('Error getting user ID from request:', error);
32
+ }
33
+
34
+ return null;
35
+ }
@@ -2,10 +2,11 @@ import { $getTableName } from '@/src/database/$getTableName';
2
2
  import { $provideSupabaseForServer } from '@/src/database/$provideSupabaseForServer';
3
3
  import { $provideAgentCollectionForServer } from '@/src/tools/$provideAgentCollectionForServer';
4
4
  import { $provideOpenAiAssistantExecutionToolsForServer } from '@/src/tools/$provideOpenAiAssistantExecutionToolsForServer';
5
- import { Agent, computeAgentHash, PROMPTBOOK_ENGINE_VERSION } from '@promptbook-local/core';
5
+ import { Agent, computeAgentHash, parseAgentSource, PROMPTBOOK_ENGINE_VERSION } from '@promptbook-local/core';
6
6
  import { ChatMessage, ChatPromptResult, Prompt, string_book, TODO_any } from '@promptbook-local/types';
7
7
  import { computeHash } from '@promptbook-local/utils';
8
8
  import { NextRequest, NextResponse } from 'next/server';
9
+ import { isAgentDeleted } from '../app/agents/[agentName]/_utils';
9
10
  import { validateApiKey } from './validateApiKey';
10
11
 
11
12
  export async function handleChatCompletion(
@@ -60,6 +61,19 @@ export async function handleChatCompletion(
60
61
  );
61
62
  }
62
63
 
64
+ // Check if agent is deleted
65
+ if (await isAgentDeleted(agentName)) {
66
+ return NextResponse.json(
67
+ {
68
+ error: {
69
+ message: 'This agent has been deleted. You can restore it from the Recycle Bin.',
70
+ type: 'agent_deleted',
71
+ },
72
+ },
73
+ { status: 410 }, // Gone - indicates the resource is no longer available
74
+ );
75
+ }
76
+
63
77
  const collection = await $provideAgentCollectionForServer();
64
78
  let agentSource: string_book;
65
79
  try {
@@ -99,7 +113,54 @@ export async function handleChatCompletion(
99
113
  );
100
114
  }
101
115
 
102
- const openAiAssistantExecutionTools = await $provideOpenAiAssistantExecutionToolsForServer();
116
+ const agentHash = computeAgentHash(agentSource);
117
+ const supabase = $provideSupabaseForServer();
118
+ const { data: assistantCache } = await supabase
119
+ .from(await $getTableName('OpenAiAssistantCache'))
120
+ .select('assistantId')
121
+ .eq('agentHash', agentHash)
122
+ .single();
123
+
124
+ let openAiAssistantExecutionTools = await $provideOpenAiAssistantExecutionToolsForServer();
125
+
126
+ if (assistantCache?.assistantId) {
127
+ console.log(
128
+ `[🐱‍🚀] Reusing assistant ${assistantCache.assistantId} for agent ${agentName} (hash: ${agentHash})`,
129
+ );
130
+ openAiAssistantExecutionTools = openAiAssistantExecutionTools.getAssistant(assistantCache.assistantId);
131
+ } else {
132
+ console.log(`[🐱‍🚀] Creating NEW assistant for agent ${agentName} (hash: ${agentHash})`);
133
+ // Parse to get instructions and name
134
+ const parsed = parseAgentSource(agentSource);
135
+ const name = parsed.agentName || agentName;
136
+ // Extract PERSONA
137
+ const baseInstructions = parsed.personaDescription || 'You are a helpful assistant.';
138
+
139
+ // Note: Append context to instructions
140
+ const contextLines = agentSource.split('\n').filter((line) => line.startsWith('CONTEXT '));
141
+ const contextInstructions = contextLines.join('\n');
142
+ const instructions = contextInstructions
143
+ ? `${baseInstructions}\n\n${contextInstructions}`
144
+ : baseInstructions;
145
+
146
+ // Create assistant
147
+ const newAssistantTools = await openAiAssistantExecutionTools.createNewAssistant({
148
+ name,
149
+ instructions,
150
+ // knowledgeSources?
151
+ });
152
+
153
+ // Save to cache
154
+ const newAssistantId = newAssistantTools.assistantId;
155
+ if (newAssistantId) {
156
+ await supabase.from(await $getTableName('OpenAiAssistantCache')).insert({
157
+ agentHash,
158
+ assistantId: newAssistantId,
159
+ });
160
+ openAiAssistantExecutionTools = newAssistantTools;
161
+ }
162
+ }
163
+
103
164
  const agent = new Agent({
104
165
  agentSource,
105
166
  executionTools: {
@@ -108,7 +169,6 @@ export async function handleChatCompletion(
108
169
  isVerbose: true, // or false
109
170
  });
110
171
 
111
- const agentHash = computeAgentHash(agentSource);
112
172
  const userAgent = request.headers.get('user-agent');
113
173
  const ip =
114
174
  request.headers.get('x-forwarded-for') ||
@@ -125,8 +185,9 @@ export async function handleChatCompletion(
125
185
  const previousMessages = threadMessages.slice(0, -1);
126
186
 
127
187
  const thread: ChatMessage[] = previousMessages.map((msg: TODO_any, index: number) => ({
188
+ // channel: 'PROMPTBOOK_CHAT',
128
189
  id: `msg-${index}`, // Placeholder ID
129
- from: msg.role === 'assistant' ? 'agent' : 'user', // Mapping standard OpenAI roles
190
+ sender: msg.role === 'assistant' ? 'agent' : 'user', // Mapping standard OpenAI roles
130
191
  content: msg.content,
131
192
  isComplete: true,
132
193
  date: new Date(), // We don't have the real date, using current
@@ -138,7 +199,6 @@ export async function handleChatCompletion(
138
199
  content: lastMessage.content,
139
200
  };
140
201
 
141
- const supabase = $provideSupabaseForServer();
142
202
  await supabase.from(await $getTableName('ChatHistory')).insert({
143
203
  createdAt: new Date().toISOString(),
144
204
  messageHash: computeHash(userMessageContent),
@@ -0,0 +1,21 @@
1
+ import { capitalize } from '../../../../../src/utils/normalization/capitalize';
2
+
3
+ /**
4
+ * Converts a filename like "cat-sitting-on-keyboard.png" to a prompt like "Cat sitting on keyboard"
5
+ *
6
+ * @param filename - The filename to convert
7
+ * @returns The normalized prompt
8
+ */
9
+ export function filenameToPrompt(filename: string): string {
10
+ // Remove file extension
11
+ const withoutExtension = filename.replace(/\.[^/.]+$/, '');
12
+
13
+ // Replace dashes and underscores with spaces
14
+ const withSpaces = withoutExtension.replace(/[-_]/g, ' ');
15
+
16
+ // Capitalize each word
17
+ const words = withSpaces.split(' ');
18
+ const capitalizedWords = words.map(word => capitalize(word));
19
+
20
+ return capitalizedWords.join(' ');
21
+ }
@@ -1,15 +1,6 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
2
  import { NextRequest } from 'next/server';
3
- import { SERVERS, SUPABASE_TABLE_PREFIX } from '../../config';
4
-
5
- // Note: Re-implementing normalizeTo_PascalCase to avoid importing from @promptbook-local/utils which might have Node.js dependencies
6
- function normalizeTo_PascalCase(text: string): string {
7
- return text
8
- .replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => {
9
- return word.toUpperCase();
10
- })
11
- .replace(/\s+/g, '');
12
- }
3
+ import { $getTableName } from '../database/$getTableName';
13
4
 
14
5
  export type ApiKeyValidationResult = {
15
6
  isValid: boolean;
@@ -62,10 +53,14 @@ export async function validateApiKey(request: NextRequest): Promise<ApiKeyValida
62
53
  };
63
54
  }
64
55
 
56
+ /*
57
+ Note: [🐔] This code was commented out because results of it are unused
58
+
65
59
  // Determine the table prefix based on the host
66
60
  const host = request.headers.get('host');
67
61
  let tablePrefix = SUPABASE_TABLE_PREFIX;
68
62
 
63
+
69
64
  if (host && SERVERS && SERVERS.length > 0) {
70
65
  if (SERVERS.some((server) => server === host)) {
71
66
  let serverName = host;
@@ -74,6 +69,7 @@ export async function validateApiKey(request: NextRequest): Promise<ApiKeyValida
74
69
  tablePrefix = `server_${serverName}_`;
75
70
  }
76
71
  }
72
+ */
77
73
 
78
74
  const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
79
75
  const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
@@ -95,7 +91,7 @@ export async function validateApiKey(request: NextRequest): Promise<ApiKeyValida
95
91
  });
96
92
 
97
93
  const { data, error } = await supabase
98
- .from(`${tablePrefix}ApiTokens`)
94
+ .from(await $getTableName(`ApiTokens`))
99
95
  .select('id, isRevoked')
100
96
  .eq('token', token)
101
97
  .single();