@promptbook/cli 0.103.0-54 → 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/config.ts +0 -2
- package/apps/agents-server/package-lock.json +1163 -0
- package/apps/agents-server/package.json +6 -0
- package/apps/agents-server/src/app/admin/chat-feedback/ChatFeedbackClient.tsx +79 -6
- package/apps/agents-server/src/app/admin/chat-history/ChatHistoryClient.tsx +171 -69
- 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/mcp/route.ts +203 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/modelRequirements/route.ts +3 -1
- package/apps/agents-server/src/app/agents/[agentName]/api/modelRequirements/systemMessage/route.ts +3 -1
- package/apps/agents-server/src/app/agents/[agentName]/api/openai/chat/completions/route.ts +3 -169
- 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/openrouter/chat/completions/route.ts +10 -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 +182 -0
- 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/auth/change-password/route.ts +75 -0
- package/apps/agents-server/src/app/api/chat-feedback/export/route.ts +55 -0
- package/apps/agents-server/src/app/api/chat-history/export/route.ts +55 -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/ChangePasswordDialog/ChangePasswordDialog.tsx +41 -0
- package/apps/agents-server/src/components/ChangePasswordForm/ChangePasswordForm.tsx +159 -0
- package/apps/agents-server/src/components/DocumentationContent/DocumentationContent.tsx +87 -0
- package/apps/agents-server/src/components/Header/Header.tsx +94 -38
- 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/middleware.ts +1 -1
- package/apps/agents-server/src/utils/convertToCsv.ts +31 -0
- package/apps/agents-server/src/utils/handleChatCompletion.ts +355 -0
- package/apps/agents-server/src/utils/resolveInheritedAgentSource.ts +100 -0
- package/apps/agents-server/src/utils/validateApiKey.ts +128 -0
- package/apps/agents-server/tailwind.config.ts +1 -1
- package/esm/index.es.js +1188 -175
- package/esm/index.es.js.map +1 -1
- package/esm/typings/src/book-2.0/agent-source/AgentModelRequirements.d.ts +4 -0
- package/esm/typings/src/book-components/Chat/LlmChat/LlmChatProps.d.ts +5 -0
- package/esm/typings/src/commitments/CLOSED/CLOSED.d.ts +35 -0
- package/esm/typings/src/commitments/COMPONENT/COMPONENT.d.ts +28 -0
- package/esm/typings/src/commitments/FROM/FROM.d.ts +34 -0
- package/esm/typings/src/commitments/LANGUAGE/LANGUAGE.d.ts +35 -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/OPEN/OPEN.d.ts +35 -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/USE_MCP/USE_MCP.d.ts +37 -0
- package/esm/typings/src/commitments/USE_SEARCH_ENGINE/USE_SEARCH_ENGINE.d.ts +38 -0
- package/esm/typings/src/commitments/index.d.ts +12 -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 +2 -2
- package/umd/index.umd.js +1180 -167
- package/umd/index.umd.js.map +1 -1
- package/esm/typings/src/playground/playground1.d.ts +0 -2
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import { $getTableName } from '@/src/database/$getTableName';
|
|
2
|
+
import { $provideSupabaseForServer } from '@/src/database/$provideSupabaseForServer';
|
|
3
|
+
import { $provideAgentCollectionForServer } from '@/src/tools/$provideAgentCollectionForServer';
|
|
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';
|
|
8
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
9
|
+
import { validateApiKey } from './validateApiKey';
|
|
10
|
+
|
|
11
|
+
export async function handleChatCompletion(
|
|
12
|
+
request: NextRequest,
|
|
13
|
+
params: { agentName?: string },
|
|
14
|
+
title: string = 'API Chat Completion',
|
|
15
|
+
) {
|
|
16
|
+
const { agentName: agentNameFromParams } = params;
|
|
17
|
+
|
|
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;
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
const body = await request.json();
|
|
35
|
+
const { messages, stream, model } = body;
|
|
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
|
+
|
|
51
|
+
if (!messages || !Array.isArray(messages) || messages.length === 0) {
|
|
52
|
+
return NextResponse.json(
|
|
53
|
+
{
|
|
54
|
+
error: {
|
|
55
|
+
message: 'Messages array is required and cannot be empty.',
|
|
56
|
+
type: 'invalid_request_error',
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
{ status: 400 },
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const collection = await $provideAgentCollectionForServer();
|
|
64
|
+
let agentSource: string_book;
|
|
65
|
+
try {
|
|
66
|
+
agentSource = await collection.getAgentSource(agentName);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
return NextResponse.json(
|
|
69
|
+
{ error: { message: `Agent '${agentName}' not found.`, type: 'invalid_request_error' } },
|
|
70
|
+
{ status: 404 },
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (!agentSource) {
|
|
75
|
+
return NextResponse.json(
|
|
76
|
+
{ error: { message: `Agent '${agentName}' not found.`, type: 'invalid_request_error' } },
|
|
77
|
+
{ status: 404 },
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
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();
|
|
103
|
+
const agent = new Agent({
|
|
104
|
+
agentSource,
|
|
105
|
+
executionTools: {
|
|
106
|
+
llm: openAiAssistantExecutionTools, // Note: Use the same OpenAI Assistant LLM tools as the chat route
|
|
107
|
+
},
|
|
108
|
+
isVerbose: true, // or false
|
|
109
|
+
});
|
|
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
|
+
|
|
123
|
+
// Prepare thread and content
|
|
124
|
+
const lastMessage = threadMessages[threadMessages.length - 1];
|
|
125
|
+
const previousMessages = threadMessages.slice(0, -1);
|
|
126
|
+
|
|
127
|
+
const thread: ChatMessage[] = previousMessages.map((msg: TODO_any, index: number) => ({
|
|
128
|
+
id: `msg-${index}`, // Placeholder ID
|
|
129
|
+
from: msg.role === 'assistant' ? 'agent' : 'user', // Mapping standard OpenAI roles
|
|
130
|
+
content: msg.content,
|
|
131
|
+
isComplete: true,
|
|
132
|
+
date: new Date(), // We don't have the real date, using current
|
|
133
|
+
}));
|
|
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
|
+
|
|
159
|
+
const prompt: Prompt = {
|
|
160
|
+
title,
|
|
161
|
+
content: lastMessage.content,
|
|
162
|
+
modelRequirements: {
|
|
163
|
+
modelVariant: 'CHAT',
|
|
164
|
+
// We could pass 'model' from body if we wanted to enforce it, but Agent usually has its own config
|
|
165
|
+
},
|
|
166
|
+
parameters: {},
|
|
167
|
+
thread,
|
|
168
|
+
} as Prompt;
|
|
169
|
+
// Note: Casting as Prompt because the type definition might require properties we don't strictly use or that are optional but TS complains
|
|
170
|
+
|
|
171
|
+
if (stream) {
|
|
172
|
+
const encoder = new TextEncoder();
|
|
173
|
+
const readableStream = new ReadableStream({
|
|
174
|
+
async start(controller) {
|
|
175
|
+
const runId = `chatcmpl-${Math.random().toString(36).substring(2, 15)}`;
|
|
176
|
+
const created = Math.floor(Date.now() / 1000);
|
|
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
|
+
|
|
197
|
+
let previousContent = '';
|
|
198
|
+
|
|
199
|
+
try {
|
|
200
|
+
const result = await agent.callChatModelStream(prompt, (chunk: ChatPromptResult) => {
|
|
201
|
+
const fullContent = chunk.content;
|
|
202
|
+
const deltaContent = fullContent.substring(previousContent.length);
|
|
203
|
+
previousContent = fullContent;
|
|
204
|
+
|
|
205
|
+
if (deltaContent) {
|
|
206
|
+
const chunkData = {
|
|
207
|
+
id: runId,
|
|
208
|
+
object: 'chat.completion.chunk',
|
|
209
|
+
created,
|
|
210
|
+
model: model || 'promptbook-agent',
|
|
211
|
+
choices: [
|
|
212
|
+
{
|
|
213
|
+
index: 0,
|
|
214
|
+
delta: {
|
|
215
|
+
content: deltaContent,
|
|
216
|
+
},
|
|
217
|
+
finish_reason: null,
|
|
218
|
+
},
|
|
219
|
+
],
|
|
220
|
+
};
|
|
221
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunkData)}\n\n`));
|
|
222
|
+
}
|
|
223
|
+
});
|
|
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
|
+
|
|
255
|
+
const doneChunkData = {
|
|
256
|
+
id: runId,
|
|
257
|
+
object: 'chat.completion.chunk',
|
|
258
|
+
created,
|
|
259
|
+
model: model || 'promptbook-agent',
|
|
260
|
+
choices: [
|
|
261
|
+
{
|
|
262
|
+
index: 0,
|
|
263
|
+
delta: {},
|
|
264
|
+
finish_reason: 'stop',
|
|
265
|
+
},
|
|
266
|
+
],
|
|
267
|
+
};
|
|
268
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify(doneChunkData)}\n\n`));
|
|
269
|
+
controller.enqueue(encoder.encode('[DONE]'));
|
|
270
|
+
} catch (error) {
|
|
271
|
+
console.error('Error during streaming:', error);
|
|
272
|
+
// OpenAI stream doesn't usually send error JSON in stream, just closes or sends error text?
|
|
273
|
+
// But we should try to close gracefully or error.
|
|
274
|
+
controller.error(error);
|
|
275
|
+
}
|
|
276
|
+
controller.close();
|
|
277
|
+
},
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
return new Response(readableStream, {
|
|
281
|
+
headers: {
|
|
282
|
+
'Content-Type': 'text/event-stream',
|
|
283
|
+
'Cache-Control': 'no-cache',
|
|
284
|
+
Connection: 'keep-alive',
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
} else {
|
|
288
|
+
const result = await agent.callChatModel(prompt);
|
|
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
|
+
|
|
320
|
+
return NextResponse.json({
|
|
321
|
+
id: `chatcmpl-${Math.random().toString(36).substring(2, 15)}`,
|
|
322
|
+
object: 'chat.completion',
|
|
323
|
+
created: Math.floor(Date.now() / 1000),
|
|
324
|
+
model: model || 'promptbook-agent',
|
|
325
|
+
choices: [
|
|
326
|
+
{
|
|
327
|
+
index: 0,
|
|
328
|
+
message: {
|
|
329
|
+
role: 'assistant',
|
|
330
|
+
content: result.content,
|
|
331
|
+
},
|
|
332
|
+
finish_reason: 'stop',
|
|
333
|
+
},
|
|
334
|
+
],
|
|
335
|
+
usage: {
|
|
336
|
+
prompt_tokens: result.usage?.input?.tokensCount?.value || 0,
|
|
337
|
+
completion_tokens: result.usage?.output?.tokensCount?.value || 0,
|
|
338
|
+
total_tokens:
|
|
339
|
+
(result.usage?.input?.tokensCount?.value || 0) +
|
|
340
|
+
(result.usage?.output?.tokensCount?.value || 0),
|
|
341
|
+
},
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
} catch (error) {
|
|
345
|
+
console.error(`Error in ${title} handler:`, error);
|
|
346
|
+
return NextResponse.json(
|
|
347
|
+
{ error: { message: (error as Error).message || 'Internal Server Error', type: 'server_error' } },
|
|
348
|
+
{ status: 500 },
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* TODO: [🈹] Maybe move chat thread handling here
|
|
355
|
+
*/
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { createAgentModelRequirements } from '@promptbook-local/core';
|
|
2
|
+
import type { AgentCollection } from '@promptbook-local/types';
|
|
3
|
+
type string_book = string & { readonly __type: 'book' };
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Resolves agent source with inheritance (FROM commitment)
|
|
7
|
+
*
|
|
8
|
+
* It recursively fetches the parent agent source and merges it with the current source.
|
|
9
|
+
*
|
|
10
|
+
* @param agentSource The initial agent source
|
|
11
|
+
* @param collection Optional agent collection to resolve local agents efficiently
|
|
12
|
+
* @returns The resolved agent source with inheritance applied
|
|
13
|
+
*/
|
|
14
|
+
export async function resolveInheritedAgentSource(
|
|
15
|
+
agentSource: string_book,
|
|
16
|
+
collection?: AgentCollection,
|
|
17
|
+
): Promise<string_book> {
|
|
18
|
+
// Check if the source has FROM commitment
|
|
19
|
+
// We use createAgentModelRequirements to parse commitments
|
|
20
|
+
// Note: We don't provide tools/models here as we only care about parsing commitments
|
|
21
|
+
const requirements = await createAgentModelRequirements(agentSource);
|
|
22
|
+
|
|
23
|
+
if (!requirements.parentAgentUrl) {
|
|
24
|
+
return agentSource;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const parentUrl = requirements.parentAgentUrl;
|
|
28
|
+
let parentSource: string_book;
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
// 1. Try to resolve locally using collection if possible
|
|
32
|
+
// This is an optimization for internal agents
|
|
33
|
+
// We assume the URL might be relative or contain the agent name, or we just check if it's a full URL
|
|
34
|
+
// If it's a full URL, we need to check if it matches our server, but without knowing our server URL it's hard.
|
|
35
|
+
// So we might need to parse the URL to extract agent name if it matches expected pattern.
|
|
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
|
+
|
|
38
|
+
// If the URL is valid, we try to fetch it
|
|
39
|
+
// TODO: Handle authentication/tokens for private agents if needed
|
|
40
|
+
|
|
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
|
+
}
|
|
52
|
+
|
|
53
|
+
// We assume the response is the agent source text
|
|
54
|
+
// TODO: Handle content negotiation or JSON responses if the server returns JSON
|
|
55
|
+
const contentType = response.headers.get('content-type');
|
|
56
|
+
if (contentType && contentType.includes('application/json')) {
|
|
57
|
+
const data = await response.json();
|
|
58
|
+
// Assume some structure or that the API returns source in a property
|
|
59
|
+
// For Agents Server API modelRequirements/route.ts returns AgentModelRequirements, not source.
|
|
60
|
+
// If we point to a raw source endpoint, it returns text.
|
|
61
|
+
// If we point to the agent page, it returns HTML.
|
|
62
|
+
// We need a standard way to get source.
|
|
63
|
+
// For now, let's assume the URL points to the source or an API returning source.
|
|
64
|
+
if (typeof data === 'string') {
|
|
65
|
+
parentSource = data as string_book;
|
|
66
|
+
} else if (data.source) {
|
|
67
|
+
parentSource = data.source as string_book;
|
|
68
|
+
} else {
|
|
69
|
+
// Fallback or error
|
|
70
|
+
console.warn(`Received JSON from ${parentUrl} but couldn't determine source property. Using text.`);
|
|
71
|
+
// Re-fetch as text? Or assume body text was read? response.json() consumes body.
|
|
72
|
+
// So we might have failed here.
|
|
73
|
+
throw new Error(`Received JSON from ${parentUrl} but structure is unknown.`);
|
|
74
|
+
}
|
|
75
|
+
} else {
|
|
76
|
+
parentSource = (await response.text()) as string_book;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
} catch (error) {
|
|
80
|
+
console.warn(`Failed to resolve parent agent ${parentUrl}`, error);
|
|
81
|
+
// If we fail to resolve parent, we return the original source (maybe with a warning or error commitment?)
|
|
82
|
+
// Or we could throw to fail the build.
|
|
83
|
+
// For robustness, let's append a warning comment
|
|
84
|
+
return `${agentSource}\n\n# Warning: Failed to inherit from ${parentUrl}: ${error}` as string_book;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Recursively resolve the parent source
|
|
88
|
+
const effectiveParentSource = await resolveInheritedAgentSource(parentSource, collection);
|
|
89
|
+
|
|
90
|
+
// Strip the FROM commitment from the child source to avoid infinite recursion or re-processing
|
|
91
|
+
// We can filter lines starting with FROM
|
|
92
|
+
const childSourceLines = agentSource.split('\n');
|
|
93
|
+
const filteredChildSource = childSourceLines
|
|
94
|
+
.filter((line: string) => !line.trim().startsWith('FROM ')) // Simple string check, ideally should use parser location
|
|
95
|
+
.join('\n');
|
|
96
|
+
|
|
97
|
+
// Append child source to parent source
|
|
98
|
+
// "appends the RULE commitment to its source" -> Parent + Child
|
|
99
|
+
return `${effectiveParentSource}\n\n${filteredChildSource}` as string_book;
|
|
100
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { createClient } from '@supabase/supabase-js';
|
|
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
|
+
}
|
|
13
|
+
|
|
14
|
+
export type ApiKeyValidationResult = {
|
|
15
|
+
isValid: boolean;
|
|
16
|
+
token?: string;
|
|
17
|
+
error?: string;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Validates an API key from the Authorization header.
|
|
22
|
+
* Returns validation result with status and optional error message.
|
|
23
|
+
*
|
|
24
|
+
* Note: This function provides explicit API key validation in addition to middleware.
|
|
25
|
+
* Use this when you need to verify API key validity and return specific error messages.
|
|
26
|
+
*/
|
|
27
|
+
export async function validateApiKey(request: NextRequest): Promise<ApiKeyValidationResult> {
|
|
28
|
+
const authHeader = request.headers.get('authorization');
|
|
29
|
+
|
|
30
|
+
// If no auth header, check if user has a session cookie (logged in via web)
|
|
31
|
+
if (!authHeader) {
|
|
32
|
+
const hasSession = request.cookies.has('sessionToken');
|
|
33
|
+
if (hasSession) {
|
|
34
|
+
return { isValid: true };
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
isValid: false,
|
|
38
|
+
error: 'Missing Authorization header. Provide a valid API key using "Authorization: Bearer ptbk_..."',
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (!authHeader.startsWith('Bearer ')) {
|
|
43
|
+
return {
|
|
44
|
+
isValid: false,
|
|
45
|
+
error: 'Invalid Authorization header format. Expected "Bearer <token>"',
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const token = authHeader.split(' ')[1];
|
|
50
|
+
|
|
51
|
+
if (!token) {
|
|
52
|
+
return {
|
|
53
|
+
isValid: false,
|
|
54
|
+
error: 'No token provided in Authorization header',
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (!token.startsWith('ptbk_')) {
|
|
59
|
+
return {
|
|
60
|
+
isValid: false,
|
|
61
|
+
error: 'Invalid API key format. API keys must start with "ptbk_"',
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Determine the table prefix based on the host
|
|
66
|
+
const host = request.headers.get('host');
|
|
67
|
+
let tablePrefix = SUPABASE_TABLE_PREFIX;
|
|
68
|
+
|
|
69
|
+
if (host && SERVERS && SERVERS.length > 0) {
|
|
70
|
+
if (SERVERS.some((server) => server === host)) {
|
|
71
|
+
let serverName = host;
|
|
72
|
+
serverName = serverName.replace(/\.ptbk\.io$/, '');
|
|
73
|
+
serverName = normalizeTo_PascalCase(serverName);
|
|
74
|
+
tablePrefix = `server_${serverName}_`;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
|
79
|
+
const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
|
|
80
|
+
|
|
81
|
+
if (!supabaseUrl || !supabaseKey) {
|
|
82
|
+
console.error('Supabase configuration missing for API key validation');
|
|
83
|
+
return {
|
|
84
|
+
isValid: false,
|
|
85
|
+
error: 'Server configuration error',
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
const supabase = createClient(supabaseUrl, supabaseKey, {
|
|
91
|
+
auth: {
|
|
92
|
+
persistSession: false,
|
|
93
|
+
autoRefreshToken: false,
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const { data, error } = await supabase
|
|
98
|
+
.from(`${tablePrefix}ApiTokens`)
|
|
99
|
+
.select('id, isRevoked')
|
|
100
|
+
.eq('token', token)
|
|
101
|
+
.single();
|
|
102
|
+
|
|
103
|
+
if (error || !data) {
|
|
104
|
+
return {
|
|
105
|
+
isValid: false,
|
|
106
|
+
error: 'Invalid API key',
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (data.isRevoked) {
|
|
111
|
+
return {
|
|
112
|
+
isValid: false,
|
|
113
|
+
error: 'API key has been revoked',
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
isValid: true,
|
|
119
|
+
token,
|
|
120
|
+
};
|
|
121
|
+
} catch (error) {
|
|
122
|
+
console.error('Error validating API key:', error);
|
|
123
|
+
return {
|
|
124
|
+
isValid: false,
|
|
125
|
+
error: 'Error validating API key',
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
}
|