@promptbook/cli 0.103.0-55 → 0.103.0-56
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.
- package/apps/agents-server/package-lock.json +1163 -0
- package/apps/agents-server/package.json +6 -0
- package/apps/agents-server/src/app/agents/[agentName]/AgentChatWrapper.tsx +3 -1
- package/apps/agents-server/src/app/agents/[agentName]/AgentOptionsMenu.tsx +216 -0
- package/apps/agents-server/src/app/agents/[agentName]/AgentProfileChat.tsx +78 -0
- package/apps/agents-server/src/app/agents/[agentName]/AgentProfileView.tsx +233 -0
- package/apps/agents-server/src/app/agents/[agentName]/CloneAgentButton.tsx +4 -4
- package/apps/agents-server/src/app/agents/[agentName]/InstallPwaButton.tsx +2 -2
- package/apps/agents-server/src/app/agents/[agentName]/QrCodeModal.tsx +90 -0
- package/apps/agents-server/src/app/agents/[agentName]/agentLinks.tsx +80 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/book/route.ts +3 -1
- package/apps/agents-server/src/app/agents/[agentName]/api/chat/route.ts +11 -1
- package/apps/agents-server/src/app/agents/[agentName]/api/openai/models/route.ts +93 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/openai/v1/chat/completions/route.ts +10 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/openai/v1/models/route.ts +93 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/voice/route.ts +4 -0
- package/apps/agents-server/src/app/agents/[agentName]/chat/page.tsx +9 -2
- package/apps/agents-server/src/app/agents/[agentName]/integration/SdkCodeTabs.tsx +31 -0
- package/apps/agents-server/src/app/agents/[agentName]/integration/page.tsx +271 -30
- package/apps/agents-server/src/app/agents/[agentName]/links/page.tsx +61 -97
- package/apps/agents-server/src/app/agents/[agentName]/page.tsx +108 -165
- package/apps/agents-server/src/app/agents/[agentName]/website-integration/page.tsx +61 -0
- package/apps/agents-server/src/app/api/openai/v1/chat/completions/route.ts +6 -0
- package/apps/agents-server/src/app/api/openai/v1/models/route.ts +65 -0
- package/apps/agents-server/src/app/docs/[docId]/page.tsx +12 -32
- package/apps/agents-server/src/app/docs/page.tsx +42 -17
- package/apps/agents-server/src/app/globals.css +129 -0
- package/apps/agents-server/src/app/layout.tsx +8 -2
- package/apps/agents-server/src/app/manifest.ts +1 -1
- package/apps/agents-server/src/components/DocumentationContent/DocumentationContent.tsx +87 -0
- package/apps/agents-server/src/components/OpenMojiIcon/OpenMojiIcon.tsx +20 -0
- package/apps/agents-server/src/components/PrintButton/PrintButton.tsx +18 -0
- package/apps/agents-server/src/components/PrintHeader/PrintHeader.tsx +18 -0
- package/apps/agents-server/src/database/migrations/2025-12-0070-chat-history-source.sql +2 -0
- package/apps/agents-server/src/database/schema.ts +6 -0
- package/apps/agents-server/src/utils/handleChatCompletion.ts +186 -14
- package/apps/agents-server/src/utils/resolveInheritedAgentSource.ts +13 -6
- package/apps/agents-server/src/utils/validateApiKey.ts +128 -0
- package/apps/agents-server/tailwind.config.ts +1 -1
- package/esm/index.es.js +865 -441
- package/esm/index.es.js.map +1 -1
- package/esm/typings/src/_packages/core.index.d.ts +6 -8
- package/esm/typings/src/_packages/types.index.d.ts +1 -1
- package/esm/typings/src/book-components/Chat/LlmChat/LlmChatProps.d.ts +5 -0
- package/esm/typings/src/commitments/META_COLOR/META_COLOR.d.ts +6 -0
- package/esm/typings/src/commitments/META_FONT/META_FONT.d.ts +42 -0
- package/esm/typings/src/commitments/USE/USE.d.ts +53 -0
- package/esm/typings/src/commitments/USE_BROWSER/USE_BROWSER.d.ts +38 -0
- package/esm/typings/src/commitments/USE_BROWSER/USE_BROWSER.test.d.ts +1 -0
- package/esm/typings/src/commitments/{IMPORTANT/IMPORTANT.d.ts → USE_MCP/USE_MCP.d.ts} +16 -5
- package/esm/typings/src/commitments/USE_SEARCH_ENGINE/USE_SEARCH_ENGINE.d.ts +38 -0
- package/esm/typings/src/commitments/index.d.ts +93 -1
- package/esm/typings/src/playground/playground.d.ts +3 -0
- package/esm/typings/src/utils/color/Color.d.ts +8 -0
- package/esm/typings/src/utils/color/css-colors.d.ts +1 -0
- package/esm/typings/src/version.d.ts +1 -1
- package/package.json +1 -1
- package/umd/index.umd.js +861 -437
- package/umd/index.umd.js.map +1 -1
- package/esm/typings/src/commitments/registry.d.ts +0 -68
- package/esm/typings/src/playground/playground1.d.ts +0 -2
|
@@ -54,6 +54,11 @@ body {
|
|
|
54
54
|
font-family: var(--font-barlow-condensed), 'OpenMojiBlack', Arial, Helvetica, sans-serif;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
/* Poppins font for agent names and headings */
|
|
58
|
+
.font-poppins {
|
|
59
|
+
font-family: var(--font-poppins), 'Poppins', system-ui, -apple-system, sans-serif;
|
|
60
|
+
}
|
|
61
|
+
|
|
57
62
|
/* Custom utilities */
|
|
58
63
|
.line-clamp-2 {
|
|
59
64
|
display: -webkit-box;
|
|
@@ -135,6 +140,53 @@ textarea:focus-visible {
|
|
|
135
140
|
animation: spin 1s linear infinite;
|
|
136
141
|
}
|
|
137
142
|
|
|
143
|
+
/* Tailwind CSS animation utilities */
|
|
144
|
+
@keyframes fade-in {
|
|
145
|
+
from {
|
|
146
|
+
opacity: 0;
|
|
147
|
+
}
|
|
148
|
+
to {
|
|
149
|
+
opacity: 1;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
@keyframes slide-in-from-top-2 {
|
|
154
|
+
from {
|
|
155
|
+
transform: translateY(-0.5rem);
|
|
156
|
+
}
|
|
157
|
+
to {
|
|
158
|
+
transform: translateY(0);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
@keyframes zoom-in-95 {
|
|
163
|
+
from {
|
|
164
|
+
opacity: 0;
|
|
165
|
+
transform: scale(0.95);
|
|
166
|
+
}
|
|
167
|
+
to {
|
|
168
|
+
opacity: 1;
|
|
169
|
+
transform: scale(1);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
.animate-in {
|
|
174
|
+
animation-duration: 200ms;
|
|
175
|
+
animation-fill-mode: both;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
.fade-in {
|
|
179
|
+
animation-name: fade-in;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
.slide-in-from-top-2 {
|
|
183
|
+
animation-name: slide-in-from-top-2;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
.zoom-in-95 {
|
|
187
|
+
animation-name: zoom-in-95;
|
|
188
|
+
}
|
|
189
|
+
|
|
138
190
|
/* Gradient backgrounds */
|
|
139
191
|
.bg-gradient-to-br {
|
|
140
192
|
background-image: linear-gradient(to bottom right, var(--tw-gradient-stops));
|
|
@@ -145,3 +197,80 @@ textarea:focus-visible {
|
|
|
145
197
|
background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
|
|
146
198
|
border: 1px solid #e2e8f0;
|
|
147
199
|
}
|
|
200
|
+
|
|
201
|
+
/* Print styles */
|
|
202
|
+
@media print {
|
|
203
|
+
@page {
|
|
204
|
+
margin: 2cm;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/* Hide UI elements */
|
|
208
|
+
header,
|
|
209
|
+
footer,
|
|
210
|
+
nav,
|
|
211
|
+
aside,
|
|
212
|
+
button:not(.print:block),
|
|
213
|
+
.no-print,
|
|
214
|
+
[role="complementary"],
|
|
215
|
+
#portal-root {
|
|
216
|
+
display: none !important;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/* Reset layout */
|
|
220
|
+
body,
|
|
221
|
+
main {
|
|
222
|
+
padding: 0 !important;
|
|
223
|
+
margin: 0 !important;
|
|
224
|
+
background: white !important;
|
|
225
|
+
min-height: auto !important;
|
|
226
|
+
width: 100% !important;
|
|
227
|
+
color: black !important;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/* Remove shadows and backgrounds for clean print */
|
|
231
|
+
* {
|
|
232
|
+
box-shadow: none !important;
|
|
233
|
+
text-shadow: none !important;
|
|
234
|
+
background-color: transparent !important;
|
|
235
|
+
background-image: none !important;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/* Ensure text visibility */
|
|
239
|
+
h1, h2, h3, h4, h5, h6, p, li, span, div {
|
|
240
|
+
color: black !important;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/* Links */
|
|
244
|
+
a {
|
|
245
|
+
text-decoration: underline;
|
|
246
|
+
color: black !important;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/* Preserve borders */
|
|
250
|
+
.border, .border-b, .border-t, .border-l, .border-r {
|
|
251
|
+
border-color: #ddd !important;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/* Page break control */
|
|
255
|
+
h1, h2 {
|
|
256
|
+
break-after: avoid;
|
|
257
|
+
page-break-after: avoid;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
p, li, pre, code {
|
|
261
|
+
break-inside: avoid;
|
|
262
|
+
page-break-inside: avoid;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/* Specific component overrides */
|
|
266
|
+
.card, .bg-white {
|
|
267
|
+
border: none !important;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/* Code blocks */
|
|
271
|
+
pre, code {
|
|
272
|
+
background-color: #f5f5f5 !important;
|
|
273
|
+
border: 1px solid #ddd !important;
|
|
274
|
+
white-space: pre-wrap !important;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import faviconLogoImage from '@/public/favicon.ico';
|
|
2
2
|
import { LayoutWrapper } from '@/src/components/LayoutWrapper/LayoutWrapper';
|
|
3
3
|
import type { Metadata } from 'next';
|
|
4
|
-
import { Barlow_Condensed } from 'next/font/google';
|
|
4
|
+
import { Barlow_Condensed, Poppins } from 'next/font/google';
|
|
5
5
|
import { getMetadata } from '../database/getMetadata';
|
|
6
6
|
import { $provideAgentCollectionForServer } from '../tools/$provideAgentCollectionForServer';
|
|
7
7
|
import { $provideServer } from '../tools/$provideServer';
|
|
@@ -15,6 +15,12 @@ const barlowCondensed = Barlow_Condensed({
|
|
|
15
15
|
variable: '--font-barlow-condensed',
|
|
16
16
|
});
|
|
17
17
|
|
|
18
|
+
const poppins = Poppins({
|
|
19
|
+
subsets: ['latin'],
|
|
20
|
+
weight: ['400', '500', '600', '700', '800'],
|
|
21
|
+
variable: '--font-poppins',
|
|
22
|
+
});
|
|
23
|
+
|
|
18
24
|
export async function generateMetadata(): Promise<Metadata> {
|
|
19
25
|
const { publicUrl } = await $provideServer();
|
|
20
26
|
const serverName = (await getMetadata('SERVER_NAME')) || 'Promptbook Agents Server';
|
|
@@ -98,7 +104,7 @@ export default async function RootLayout({
|
|
|
98
104
|
{/* Default favicon as a fallback */}
|
|
99
105
|
<link rel="icon" href={serverFaviconUrl} type="image/x-icon" />
|
|
100
106
|
</head>
|
|
101
|
-
<body className={`${barlowCondensed.variable} antialiased bg-white text-gray-900`}>
|
|
107
|
+
<body className={`${barlowCondensed.variable} ${poppins.variable} antialiased bg-white text-gray-900`}>
|
|
102
108
|
<LayoutWrapper
|
|
103
109
|
isAdmin={isAdmin}
|
|
104
110
|
currentUser={currentUser}
|
|
@@ -41,7 +41,7 @@ export default async function manifest(): Promise<MetadataRoute.Manifest> {
|
|
|
41
41
|
const description = agentProfile.meta.description || agentProfile.personaDescription || `Agent ${name}`;
|
|
42
42
|
|
|
43
43
|
// Extract brand color from meta
|
|
44
|
-
const brandColor = Color.
|
|
44
|
+
const brandColor = Color.fromSafe(agentProfile.meta.color || PROMPTBOOK_COLOR);
|
|
45
45
|
const theme_color = brandColor.toHex();
|
|
46
46
|
const background_color = '#ffffff';
|
|
47
47
|
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import ReactMarkdown from 'react-markdown';
|
|
2
|
+
import remarkGfm from 'remark-gfm';
|
|
3
|
+
import { string_book } from '../../../../../src/book-2.0/agent-source/string_book';
|
|
4
|
+
import { BookEditor } from '../../../../../src/book-components/BookEditor/BookEditor';
|
|
5
|
+
import { OpenMojiIcon } from '../OpenMojiIcon/OpenMojiIcon';
|
|
6
|
+
|
|
7
|
+
type DocumentationContentProps = {
|
|
8
|
+
primary: {
|
|
9
|
+
type: string;
|
|
10
|
+
icon: string;
|
|
11
|
+
description?: string;
|
|
12
|
+
documentation: string;
|
|
13
|
+
};
|
|
14
|
+
aliases?: string[];
|
|
15
|
+
isPrintOnly?: boolean;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export function DocumentationContent({ primary, aliases = [], isPrintOnly = false }: DocumentationContentProps) {
|
|
19
|
+
return (
|
|
20
|
+
<div className={`bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden ${isPrintOnly ? 'shadow-none border-none' : ''}`}>
|
|
21
|
+
<div className={`p-8 border-b border-gray-100 bg-gray-50/50 ${isPrintOnly ? 'border-none bg-white p-0 mb-4' : ''}`}>
|
|
22
|
+
<div className="flex items-center gap-4 mb-4">
|
|
23
|
+
<h1 className="text-4xl font-bold text-gray-900 tracking-tight">
|
|
24
|
+
<OpenMojiIcon icon={primary.icon} className="mr-3" />
|
|
25
|
+
{primary.type}
|
|
26
|
+
{aliases.length > 0 && (
|
|
27
|
+
<span className="text-gray-400 font-normal ml-4 text-2xl">
|
|
28
|
+
/ {aliases.join(' / ')}
|
|
29
|
+
</span>
|
|
30
|
+
)}
|
|
31
|
+
</h1>
|
|
32
|
+
{!isPrintOnly && (
|
|
33
|
+
<span className="px-3 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-700">
|
|
34
|
+
Commitment
|
|
35
|
+
</span>
|
|
36
|
+
)}
|
|
37
|
+
</div>
|
|
38
|
+
{primary.description && (
|
|
39
|
+
<p className="text-xl text-gray-600 leading-relaxed max-w-3xl">
|
|
40
|
+
{primary.description}
|
|
41
|
+
</p>
|
|
42
|
+
)}
|
|
43
|
+
</div>
|
|
44
|
+
|
|
45
|
+
<div className={`p-8 ${isPrintOnly ? 'p-0' : ''}`}>
|
|
46
|
+
<article className="prose prose-lg prose-slate max-w-none prose-headings:font-bold prose-headings:tracking-tight prose-headings:text-gray-900 prose-h1:text-4xl prose-h1:mb-8 prose-h2:text-2xl prose-h2:mt-12 prose-h2:mb-6 prose-h2:pb-2 prose-h2:border-b prose-h2:border-gray-200 prose-h3:text-xl prose-h3:mt-8 prose-h3:mb-4 prose-h3:text-gray-800 prose-p:text-gray-600 prose-p:leading-relaxed prose-p:mb-6 prose-a:text-blue-600 prose-a:no-underline hover:prose-a:text-blue-700 hover:prose-a:underline prose-a:transition-colors prose-strong:font-bold prose-strong:text-gray-900 prose-code:text-blue-600 prose-code:bg-blue-50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded-md prose-code:before:content-none prose-code:after:content-none prose-code:font-medium prose-pre:bg-gray-900 prose-pre:text-gray-100 prose-pre:shadow-lg prose-pre:rounded-xl prose-pre:p-6 prose-ul:list-disc prose-ul:pl-6 prose-li:marker:text-gray-400 prose-li:mb-2 prose-ol:list-decimal prose-ol:pl-6 prose-li:mb-2 prose-blockquote:border-l-4 prose-blockquote:border-blue-500 prose-blockquote:bg-blue-50/50 prose-blockquote:py-2 prose-blockquote:px-4 prose-blockquote:rounded-r-lg prose-blockquote:not-italic prose-blockquote:text-gray-700 prose-blockquote:my-8 prose-img:rounded-xl prose-img:shadow-md prose-img:my-8 prose-hr:border-gray-200 prose-hr:my-10 prose-table:w-full prose-th:text-left prose-th:py-2 prose-th:px-3 prose-th:bg-gray-100 prose-th:font-semibold prose-th:text-gray-900 prose-td:py-2 prose-td:px-3 prose-td:border-b prose-td:border-gray-200 prose-tr:hover:bg-gray-50">
|
|
47
|
+
<ReactMarkdown
|
|
48
|
+
remarkPlugins={[remarkGfm]}
|
|
49
|
+
components={{
|
|
50
|
+
code(props) {
|
|
51
|
+
const { children, className, node, ...rest } = props;
|
|
52
|
+
const match = /language-(\w+)/.exec(className || '');
|
|
53
|
+
if (match && match[1] === 'book') {
|
|
54
|
+
const value = String(children).replace(/\n$/, '');
|
|
55
|
+
// Estimate height: lines * 30px + padding
|
|
56
|
+
const lineCount = value.split('\n').length;
|
|
57
|
+
const height = lineCount * 30 + 40; // 30px per line + 40px buffer
|
|
58
|
+
|
|
59
|
+
return (
|
|
60
|
+
<div className="not-prose my-6 rounded-lg overflow-hidden border border-gray-200 shadow-sm print:border-gray-300">
|
|
61
|
+
<BookEditor
|
|
62
|
+
value={value as string_book}
|
|
63
|
+
isReadonly={true}
|
|
64
|
+
isVerbose={false}
|
|
65
|
+
height={`${height}px`}
|
|
66
|
+
isDownloadButtonShown={false}
|
|
67
|
+
isAboutButtonShown={false}
|
|
68
|
+
isFullscreenButtonShown={true}
|
|
69
|
+
/>
|
|
70
|
+
</div>
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
return (
|
|
74
|
+
<code className={className} {...rest}>
|
|
75
|
+
{children}
|
|
76
|
+
</code>
|
|
77
|
+
);
|
|
78
|
+
},
|
|
79
|
+
}}
|
|
80
|
+
>
|
|
81
|
+
{primary.documentation}
|
|
82
|
+
</ReactMarkdown>
|
|
83
|
+
</article>
|
|
84
|
+
</div>
|
|
85
|
+
</div>
|
|
86
|
+
);
|
|
87
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { DetailedHTMLProps, HTMLAttributes } from 'react';
|
|
2
|
+
|
|
3
|
+
type OpenMojiIconProps = DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement> & {
|
|
4
|
+
icon: string;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Renders an emoji using the OpenMoji black and white font
|
|
9
|
+
*/
|
|
10
|
+
export function OpenMojiIcon({ icon, className, style, ...rest }: OpenMojiIconProps) {
|
|
11
|
+
return (
|
|
12
|
+
<span
|
|
13
|
+
className={className}
|
|
14
|
+
style={{ ...style, fontFamily: '"OpenMojiBlack", sans-serif' }}
|
|
15
|
+
{...rest}
|
|
16
|
+
>
|
|
17
|
+
{icon}
|
|
18
|
+
</span>
|
|
19
|
+
);
|
|
20
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { OpenMojiIcon } from '../OpenMojiIcon/OpenMojiIcon';
|
|
4
|
+
|
|
5
|
+
export function PrintButton() {
|
|
6
|
+
return (
|
|
7
|
+
<button
|
|
8
|
+
onClick={() => window.print()}
|
|
9
|
+
className="fixed bottom-8 right-8 bg-blue-600 hover:bg-blue-700 text-white rounded-full p-4 shadow-lg transition-all hover:scale-105 print:hidden z-50 flex items-center justify-center gap-2 group"
|
|
10
|
+
title="Print documentation"
|
|
11
|
+
>
|
|
12
|
+
<OpenMojiIcon icon="🖨️" className="text-2xl" />
|
|
13
|
+
<span className="max-w-0 overflow-hidden group-hover:max-w-xs transition-all duration-300 ease-in-out whitespace-nowrap">
|
|
14
|
+
Print
|
|
15
|
+
</span>
|
|
16
|
+
</button>
|
|
17
|
+
);
|
|
18
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export function PrintHeader({ title }: { title?: string }) {
|
|
2
|
+
return (
|
|
3
|
+
<div className="hidden print:block mb-8 border-b-2 border-blue-600 pb-4">
|
|
4
|
+
<div className="flex justify-between items-end">
|
|
5
|
+
<div>
|
|
6
|
+
<h1 className="text-3xl font-bold text-gray-900 font-poppins">Agents Server</h1>
|
|
7
|
+
<div className="text-sm text-gray-500 mt-1 flex items-center gap-1">
|
|
8
|
+
Powered by <span className="font-semibold text-blue-600">Promptbook</span>
|
|
9
|
+
</div>
|
|
10
|
+
</div>
|
|
11
|
+
{title && <h2 className="text-xl font-semibold text-gray-700">{title}</h2>}
|
|
12
|
+
</div>
|
|
13
|
+
<div className="text-xs text-gray-400 mt-2 text-right">
|
|
14
|
+
{new Date().toLocaleDateString()}
|
|
15
|
+
</div>
|
|
16
|
+
</div>
|
|
17
|
+
);
|
|
18
|
+
}
|
|
@@ -128,6 +128,8 @@ export type AgentsServerDatabase = {
|
|
|
128
128
|
userAgent: string | null;
|
|
129
129
|
language: string | null;
|
|
130
130
|
platform: string | null;
|
|
131
|
+
source: 'AGENT_PAGE_CHAT' | 'OPENAI_API_COMPATIBILITY' | null;
|
|
132
|
+
apiKey: string | null;
|
|
131
133
|
};
|
|
132
134
|
Insert: {
|
|
133
135
|
id?: number;
|
|
@@ -143,6 +145,8 @@ export type AgentsServerDatabase = {
|
|
|
143
145
|
userAgent?: string | null;
|
|
144
146
|
language?: string | null;
|
|
145
147
|
platform?: string | null;
|
|
148
|
+
source?: 'AGENT_PAGE_CHAT' | 'OPENAI_API_COMPATIBILITY' | null;
|
|
149
|
+
apiKey?: string | null;
|
|
146
150
|
};
|
|
147
151
|
Update: {
|
|
148
152
|
id?: number;
|
|
@@ -158,6 +162,8 @@ export type AgentsServerDatabase = {
|
|
|
158
162
|
userAgent?: string | null;
|
|
159
163
|
language?: string | null;
|
|
160
164
|
platform?: string | null;
|
|
165
|
+
source?: 'AGENT_PAGE_CHAT' | 'OPENAI_API_COMPATIBILITY' | null;
|
|
166
|
+
apiKey?: string | null;
|
|
161
167
|
};
|
|
162
168
|
Relationships: [];
|
|
163
169
|
};
|
|
@@ -1,23 +1,53 @@
|
|
|
1
|
+
import { $getTableName } from '@/src/database/$getTableName';
|
|
2
|
+
import { $provideSupabaseForServer } from '@/src/database/$provideSupabaseForServer';
|
|
1
3
|
import { $provideAgentCollectionForServer } from '@/src/tools/$provideAgentCollectionForServer';
|
|
2
|
-
import { $
|
|
3
|
-
import { Agent } from '@promptbook-local/core';
|
|
4
|
-
import { ChatMessage, ChatPromptResult, Prompt, TODO_any } from '@promptbook-local/types';
|
|
4
|
+
import { $provideOpenAiAssistantExecutionToolsForServer } from '@/src/tools/$provideOpenAiAssistantExecutionToolsForServer';
|
|
5
|
+
import { Agent, computeAgentHash, PROMPTBOOK_ENGINE_VERSION } from '@promptbook-local/core';
|
|
6
|
+
import { ChatMessage, ChatPromptResult, Prompt, string_book, TODO_any } from '@promptbook-local/types';
|
|
7
|
+
import { computeHash } from '@promptbook-local/utils';
|
|
5
8
|
import { NextRequest, NextResponse } from 'next/server';
|
|
9
|
+
import { validateApiKey } from './validateApiKey';
|
|
6
10
|
|
|
7
11
|
export async function handleChatCompletion(
|
|
8
12
|
request: NextRequest,
|
|
9
|
-
params: { agentName
|
|
10
|
-
title: string = 'API Chat Completion'
|
|
13
|
+
params: { agentName?: string },
|
|
14
|
+
title: string = 'API Chat Completion',
|
|
11
15
|
) {
|
|
12
|
-
const { agentName } = params;
|
|
16
|
+
const { agentName: agentNameFromParams } = params;
|
|
13
17
|
|
|
14
|
-
//
|
|
15
|
-
|
|
18
|
+
// Validate API key explicitly (in addition to middleware)
|
|
19
|
+
const apiKeyValidation = await validateApiKey(request);
|
|
20
|
+
if (!apiKeyValidation.isValid) {
|
|
21
|
+
return NextResponse.json(
|
|
22
|
+
{
|
|
23
|
+
error: {
|
|
24
|
+
message: apiKeyValidation.error || 'Invalid API key',
|
|
25
|
+
type: 'authentication_error',
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
{ status: 401 },
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
const apiKey = apiKeyValidation.token || null;
|
|
16
32
|
|
|
17
33
|
try {
|
|
18
34
|
const body = await request.json();
|
|
19
35
|
const { messages, stream, model } = body;
|
|
20
36
|
|
|
37
|
+
const agentName = agentNameFromParams || model;
|
|
38
|
+
|
|
39
|
+
if (!agentName) {
|
|
40
|
+
return NextResponse.json(
|
|
41
|
+
{
|
|
42
|
+
error: {
|
|
43
|
+
message: 'Agent name is required. Please provide it in the URL or as the "model" parameter.',
|
|
44
|
+
type: 'invalid_request_error',
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
{ status: 400 },
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
21
51
|
if (!messages || !Array.isArray(messages) || messages.length === 0) {
|
|
22
52
|
return NextResponse.json(
|
|
23
53
|
{
|
|
@@ -31,7 +61,7 @@ export async function handleChatCompletion(
|
|
|
31
61
|
}
|
|
32
62
|
|
|
33
63
|
const collection = await $provideAgentCollectionForServer();
|
|
34
|
-
let agentSource;
|
|
64
|
+
let agentSource: string_book;
|
|
35
65
|
try {
|
|
36
66
|
agentSource = await collection.getAgentSource(agentName);
|
|
37
67
|
} catch (error) {
|
|
@@ -48,16 +78,51 @@ export async function handleChatCompletion(
|
|
|
48
78
|
);
|
|
49
79
|
}
|
|
50
80
|
|
|
51
|
-
|
|
81
|
+
// Note: Handle system messages as CONTEXT
|
|
82
|
+
const systemMessages = messages.filter((msg: TODO_any) => msg.role === 'system');
|
|
83
|
+
if (systemMessages.length > 0) {
|
|
84
|
+
const contextString = systemMessages.map((msg: TODO_any) => `CONTEXT ${msg.content}`).join('\n');
|
|
85
|
+
agentSource = `${agentSource}\n\n${contextString}` as string_book;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const threadMessages = messages.filter((msg: TODO_any) => msg.role !== 'system');
|
|
89
|
+
|
|
90
|
+
if (threadMessages.length === 0) {
|
|
91
|
+
return NextResponse.json(
|
|
92
|
+
{
|
|
93
|
+
error: {
|
|
94
|
+
message: 'Messages array must contain at least one non-system message.',
|
|
95
|
+
type: 'invalid_request_error',
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
{ status: 400 },
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const openAiAssistantExecutionTools = await $provideOpenAiAssistantExecutionToolsForServer();
|
|
52
103
|
const agent = new Agent({
|
|
53
104
|
agentSource,
|
|
54
|
-
executionTools
|
|
105
|
+
executionTools: {
|
|
106
|
+
llm: openAiAssistantExecutionTools, // Note: Use the same OpenAI Assistant LLM tools as the chat route
|
|
107
|
+
},
|
|
55
108
|
isVerbose: true, // or false
|
|
56
109
|
});
|
|
57
110
|
|
|
111
|
+
const agentHash = computeAgentHash(agentSource);
|
|
112
|
+
const userAgent = request.headers.get('user-agent');
|
|
113
|
+
const ip =
|
|
114
|
+
request.headers.get('x-forwarded-for') ||
|
|
115
|
+
request.headers.get('x-real-ip') ||
|
|
116
|
+
request.headers.get('x-client-ip');
|
|
117
|
+
|
|
118
|
+
// Note: Capture language and platform information
|
|
119
|
+
const language = request.headers.get('accept-language');
|
|
120
|
+
// Simple platform extraction from userAgent parentheses content (e.g., Windows NT 10.0; Win64; x64)
|
|
121
|
+
const platform = userAgent ? userAgent.match(/\(([^)]+)\)/)?.[1] : undefined; // <- TODO: [🧠] Improve platform parsing
|
|
122
|
+
|
|
58
123
|
// Prepare thread and content
|
|
59
|
-
const lastMessage =
|
|
60
|
-
const previousMessages =
|
|
124
|
+
const lastMessage = threadMessages[threadMessages.length - 1];
|
|
125
|
+
const previousMessages = threadMessages.slice(0, -1);
|
|
61
126
|
|
|
62
127
|
const thread: ChatMessage[] = previousMessages.map((msg: TODO_any, index: number) => ({
|
|
63
128
|
id: `msg-${index}`, // Placeholder ID
|
|
@@ -67,6 +132,30 @@ export async function handleChatCompletion(
|
|
|
67
132
|
date: new Date(), // We don't have the real date, using current
|
|
68
133
|
}));
|
|
69
134
|
|
|
135
|
+
// Note: Identify the user message
|
|
136
|
+
const userMessageContent = {
|
|
137
|
+
role: 'USER',
|
|
138
|
+
content: lastMessage.content,
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const supabase = $provideSupabaseForServer();
|
|
142
|
+
await supabase.from(await $getTableName('ChatHistory')).insert({
|
|
143
|
+
createdAt: new Date().toISOString(),
|
|
144
|
+
messageHash: computeHash(userMessageContent),
|
|
145
|
+
previousMessageHash: null,
|
|
146
|
+
agentName,
|
|
147
|
+
agentHash,
|
|
148
|
+
message: userMessageContent,
|
|
149
|
+
promptbookEngineVersion: PROMPTBOOK_ENGINE_VERSION,
|
|
150
|
+
url: request.url,
|
|
151
|
+
ip,
|
|
152
|
+
userAgent,
|
|
153
|
+
language,
|
|
154
|
+
platform,
|
|
155
|
+
source: 'OPENAI_API_COMPATIBILITY',
|
|
156
|
+
apiKey,
|
|
157
|
+
});
|
|
158
|
+
|
|
70
159
|
const prompt: Prompt = {
|
|
71
160
|
title,
|
|
72
161
|
content: lastMessage.content,
|
|
@@ -86,10 +175,29 @@ export async function handleChatCompletion(
|
|
|
86
175
|
const runId = `chatcmpl-${Math.random().toString(36).substring(2, 15)}`;
|
|
87
176
|
const created = Math.floor(Date.now() / 1000);
|
|
88
177
|
|
|
178
|
+
// Note: Send the initial chunk with role
|
|
179
|
+
const initialChunkData = {
|
|
180
|
+
id: runId,
|
|
181
|
+
object: 'chat.completion.chunk',
|
|
182
|
+
created,
|
|
183
|
+
model: model || 'promptbook-agent',
|
|
184
|
+
choices: [
|
|
185
|
+
{
|
|
186
|
+
index: 0,
|
|
187
|
+
delta: {
|
|
188
|
+
role: 'assistant',
|
|
189
|
+
content: '',
|
|
190
|
+
},
|
|
191
|
+
finish_reason: null,
|
|
192
|
+
},
|
|
193
|
+
],
|
|
194
|
+
};
|
|
195
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify(initialChunkData)}\n\n`));
|
|
196
|
+
|
|
89
197
|
let previousContent = '';
|
|
90
198
|
|
|
91
199
|
try {
|
|
92
|
-
await agent.callChatModelStream(prompt, (chunk: ChatPromptResult) => {
|
|
200
|
+
const result = await agent.callChatModelStream(prompt, (chunk: ChatPromptResult) => {
|
|
93
201
|
const fullContent = chunk.content;
|
|
94
202
|
const deltaContent = fullContent.substring(previousContent.length);
|
|
95
203
|
previousContent = fullContent;
|
|
@@ -114,6 +222,36 @@ export async function handleChatCompletion(
|
|
|
114
222
|
}
|
|
115
223
|
});
|
|
116
224
|
|
|
225
|
+
// Note: Identify the agent message
|
|
226
|
+
const agentMessageContent = {
|
|
227
|
+
role: 'MODEL',
|
|
228
|
+
content: result.content,
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
// Record the agent message
|
|
232
|
+
await supabase.from(await $getTableName('ChatHistory')).insert({
|
|
233
|
+
createdAt: new Date().toISOString(),
|
|
234
|
+
messageHash: computeHash(agentMessageContent),
|
|
235
|
+
previousMessageHash: computeHash(userMessageContent),
|
|
236
|
+
agentName,
|
|
237
|
+
agentHash,
|
|
238
|
+
message: agentMessageContent,
|
|
239
|
+
promptbookEngineVersion: PROMPTBOOK_ENGINE_VERSION,
|
|
240
|
+
url: request.url,
|
|
241
|
+
ip,
|
|
242
|
+
userAgent,
|
|
243
|
+
language,
|
|
244
|
+
platform,
|
|
245
|
+
source: 'OPENAI_API_COMPATIBILITY',
|
|
246
|
+
apiKey,
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
// Note: [🐱🚀] Save the learned data
|
|
250
|
+
const newAgentSource = agent.agentSource.value;
|
|
251
|
+
if (newAgentSource !== agentSource) {
|
|
252
|
+
await collection.updateAgentSource(agentName, newAgentSource);
|
|
253
|
+
}
|
|
254
|
+
|
|
117
255
|
const doneChunkData = {
|
|
118
256
|
id: runId,
|
|
119
257
|
object: 'chat.completion.chunk',
|
|
@@ -149,6 +287,36 @@ export async function handleChatCompletion(
|
|
|
149
287
|
} else {
|
|
150
288
|
const result = await agent.callChatModel(prompt);
|
|
151
289
|
|
|
290
|
+
// Note: Identify the agent message
|
|
291
|
+
const agentMessageContent = {
|
|
292
|
+
role: 'MODEL',
|
|
293
|
+
content: result.content,
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
// Record the agent message
|
|
297
|
+
await supabase.from(await $getTableName('ChatHistory')).insert({
|
|
298
|
+
createdAt: new Date().toISOString(),
|
|
299
|
+
messageHash: computeHash(agentMessageContent),
|
|
300
|
+
previousMessageHash: computeHash(userMessageContent),
|
|
301
|
+
agentName,
|
|
302
|
+
agentHash,
|
|
303
|
+
message: agentMessageContent,
|
|
304
|
+
promptbookEngineVersion: PROMPTBOOK_ENGINE_VERSION,
|
|
305
|
+
url: request.url,
|
|
306
|
+
ip,
|
|
307
|
+
userAgent,
|
|
308
|
+
language,
|
|
309
|
+
platform,
|
|
310
|
+
source: 'OPENAI_API_COMPATIBILITY',
|
|
311
|
+
apiKey,
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
// Note: [🐱🚀] Save the learned data
|
|
315
|
+
const newAgentSource = agent.agentSource.value;
|
|
316
|
+
if (newAgentSource !== agentSource) {
|
|
317
|
+
await collection.updateAgentSource(agentName, newAgentSource);
|
|
318
|
+
}
|
|
319
|
+
|
|
152
320
|
return NextResponse.json({
|
|
153
321
|
id: `chatcmpl-${Math.random().toString(36).substring(2, 15)}`,
|
|
154
322
|
object: 'chat.completion',
|
|
@@ -181,3 +349,7 @@ export async function handleChatCompletion(
|
|
|
181
349
|
);
|
|
182
350
|
}
|
|
183
351
|
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* TODO: [🈹] Maybe move chat thread handling here
|
|
355
|
+
*/
|
|
@@ -35,13 +35,20 @@ export async function resolveInheritedAgentSource(
|
|
|
35
35
|
// So we might need to parse the URL to extract agent name if it matches expected pattern.
|
|
36
36
|
// For now, let's rely on fetch for external and check collection if it looks like a local reference (though FROM expects URL)
|
|
37
37
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const response = await fetch(parentUrl);
|
|
38
|
+
// If the URL is valid, we try to fetch it
|
|
39
|
+
// TODO: Handle authentication/tokens for private agents if needed
|
|
41
40
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
41
|
+
// TODO: [🧠] Do this logic more robustly
|
|
42
|
+
let fetchUrl = parentUrl;
|
|
43
|
+
if (!fetchUrl.endsWith('/api/book') && !fetchUrl.endsWith('.book') && !fetchUrl.endsWith('.md')) {
|
|
44
|
+
fetchUrl = `${fetchUrl.replace(/\/$/, '')}/api/book`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const response = await fetch(fetchUrl);
|
|
48
|
+
|
|
49
|
+
if (!response.ok) {
|
|
50
|
+
throw new Error(`Failed to fetch parent agent from ${fetchUrl}: ${response.status} ${response.statusText}`);
|
|
51
|
+
}
|
|
45
52
|
|
|
46
53
|
// We assume the response is the agent source text
|
|
47
54
|
// TODO: Handle content negotiation or JSON responses if the server returns JSON
|