@promptbook/cli 0.103.0-8 → 0.103.0
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/README.md +59 -39
- package/apps/agents-server/README.md +3 -0
- package/apps/agents-server/TODO.txt +7 -0
- package/apps/agents-server/config.ts +130 -0
- package/apps/agents-server/next.config.ts +45 -0
- package/apps/agents-server/package-lock.json +27 -0
- package/apps/agents-server/package.json +12 -0
- package/apps/agents-server/postcss.config.mjs +8 -0
- package/apps/agents-server/public/.gitkeep +0 -0
- package/apps/agents-server/public/favicon.ico +0 -0
- package/apps/agents-server/public/fonts/OpenMoji-black-glyf.woff2 +0 -0
- package/apps/agents-server/public/fonts/download-font.js +22 -0
- package/apps/agents-server/public/logo-blue-white-256.png +0 -0
- package/apps/agents-server/public/sw.js +16 -0
- package/apps/agents-server/src/app/AddAgentButton.tsx +41 -0
- package/apps/agents-server/src/app/[agentName]/[...rest]/page.tsx +11 -0
- package/apps/agents-server/src/app/[agentName]/page.tsx +1 -0
- package/apps/agents-server/src/app/actions.ts +53 -0
- package/apps/agents-server/src/app/admin/api-tokens/ApiTokensClient.tsx +186 -0
- package/apps/agents-server/src/app/admin/api-tokens/page.tsx +13 -0
- package/apps/agents-server/src/app/admin/chat-feedback/ChatFeedbackClient.tsx +614 -0
- package/apps/agents-server/src/app/admin/chat-feedback/page.tsx +22 -0
- package/apps/agents-server/src/app/admin/chat-history/ChatHistoryClient.tsx +634 -0
- package/apps/agents-server/src/app/admin/chat-history/page.tsx +21 -0
- package/apps/agents-server/src/app/admin/metadata/MetadataClient.tsx +477 -0
- package/apps/agents-server/src/app/admin/metadata/page.tsx +13 -0
- package/apps/agents-server/src/app/admin/models/page.tsx +22 -0
- package/apps/agents-server/src/app/admin/users/[userId]/UserDetailClient.tsx +131 -0
- package/apps/agents-server/src/app/admin/users/[userId]/page.tsx +21 -0
- package/apps/agents-server/src/app/admin/users/page.tsx +18 -0
- package/apps/agents-server/src/app/agents/[agentName]/AgentChatWrapper.tsx +78 -0
- package/apps/agents-server/src/app/agents/[agentName]/AgentOptionsMenu.tsx +314 -0
- package/apps/agents-server/src/app/agents/[agentName]/AgentProfileChat.tsx +91 -0
- package/apps/agents-server/src/app/agents/[agentName]/AgentProfileWrapper.tsx +48 -0
- package/apps/agents-server/src/app/agents/[agentName]/AgentUrlCopy.tsx +40 -0
- package/apps/agents-server/src/app/agents/[agentName]/ClearAgentChatFeedbackButton.tsx +63 -0
- package/apps/agents-server/src/app/agents/[agentName]/ClearAgentChatHistoryButton.tsx +63 -0
- package/apps/agents-server/src/app/agents/[agentName]/CloneAgentButton.tsx +41 -0
- package/apps/agents-server/src/app/agents/[agentName]/CopyField.tsx +44 -0
- package/apps/agents-server/src/app/agents/[agentName]/InstallPwaButton.tsx +74 -0
- package/apps/agents-server/src/app/agents/[agentName]/ServiceWorkerRegister.tsx +24 -0
- package/apps/agents-server/src/app/agents/[agentName]/TODO.txt +1 -0
- package/apps/agents-server/src/app/agents/[agentName]/_utils.ts +19 -0
- package/apps/agents-server/src/app/agents/[agentName]/agentLinks.tsx +80 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/agents/route.ts +67 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/book/route.ts +88 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/book/test.http +37 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/chat/route.ts +174 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/feedback/route.ts +54 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/mcp/route.ts +203 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/modelRequirements/TODO.txt +1 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/modelRequirements/route.ts +55 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/modelRequirements/systemMessage/route.ts +47 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/openai/chat/completions/route.ts +10 -0
- 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/profile/route.ts +76 -0
- package/apps/agents-server/src/app/agents/[agentName]/api/voice/route.ts +181 -0
- package/apps/agents-server/src/app/agents/[agentName]/book/BookEditorWrapper.tsx +139 -0
- package/apps/agents-server/src/app/agents/[agentName]/book/page.tsx +35 -0
- package/apps/agents-server/src/app/agents/[agentName]/book+chat/AgentBookAndChat.tsx +75 -0
- package/apps/agents-server/src/app/agents/[agentName]/book+chat/AgentBookAndChatComponent.tsx.todo +160 -0
- package/apps/agents-server/src/app/agents/[agentName]/book+chat/page.tsx +32 -0
- package/apps/agents-server/src/app/agents/[agentName]/book+chat/page.tsx.todo +21 -0
- package/apps/agents-server/src/app/agents/[agentName]/chat/AgentChatWrapper.tsx +68 -0
- package/apps/agents-server/src/app/agents/[agentName]/chat/page.tsx +33 -0
- package/apps/agents-server/src/app/agents/[agentName]/generateAgentMetadata.ts +46 -0
- package/apps/agents-server/src/app/agents/[agentName]/history/RestoreVersionButton.tsx +46 -0
- package/apps/agents-server/src/app/agents/[agentName]/history/actions.ts +12 -0
- package/apps/agents-server/src/app/agents/[agentName]/history/page.tsx +62 -0
- package/apps/agents-server/src/app/agents/[agentName]/images/icon-256.png/route.tsx +80 -0
- package/apps/agents-server/src/app/agents/[agentName]/images/screenshot-fullhd.png/route.tsx +92 -0
- package/apps/agents-server/src/app/agents/[agentName]/images/screenshot-phone.png/route.tsx +92 -0
- package/apps/agents-server/src/app/agents/[agentName]/integration/SdkCodeTabs.tsx +31 -0
- package/apps/agents-server/src/app/agents/[agentName]/integration/page.tsx +302 -0
- package/apps/agents-server/src/app/agents/[agentName]/layout.tsx +41 -0
- package/apps/agents-server/src/app/agents/[agentName]/links/page.tsx +182 -0
- package/apps/agents-server/src/app/agents/[agentName]/opengraph-image.tsx +102 -0
- package/apps/agents-server/src/app/agents/[agentName]/page.tsx +106 -0
- package/apps/agents-server/src/app/agents/[agentName]/website-integration/page.tsx +70 -0
- package/apps/agents-server/src/app/agents/page.tsx +11 -0
- package/apps/agents-server/src/app/api/agents/[agentName]/clone/route.ts +47 -0
- package/apps/agents-server/src/app/api/agents/[agentName]/route.ts +19 -0
- package/apps/agents-server/src/app/api/agents/route.ts +43 -0
- package/apps/agents-server/src/app/api/api-tokens/route.ts +76 -0
- package/apps/agents-server/src/app/api/auth/change-password/route.ts +75 -0
- package/apps/agents-server/src/app/api/auth/login/route.ts +27 -0
- package/apps/agents-server/src/app/api/auth/logout/route.ts +7 -0
- package/apps/agents-server/src/app/api/chat/route.ts +32 -0
- package/apps/agents-server/src/app/api/chat-feedback/[id]/route.ts +38 -0
- package/apps/agents-server/src/app/api/chat-feedback/export/route.ts +55 -0
- package/apps/agents-server/src/app/api/chat-feedback/route.ts +157 -0
- package/apps/agents-server/src/app/api/chat-history/[id]/route.ts +37 -0
- package/apps/agents-server/src/app/api/chat-history/export/route.ts +55 -0
- package/apps/agents-server/src/app/api/chat-history/route.ts +147 -0
- package/apps/agents-server/src/app/api/chat-streaming/route.ts +48 -0
- package/apps/agents-server/src/app/api/embed.js/route.ts +93 -0
- package/apps/agents-server/src/app/api/federated-agents/route.ts +17 -0
- package/apps/agents-server/src/app/api/long-running-task/route.ts +7 -0
- package/apps/agents-server/src/app/api/long-streaming/route.ts +20 -0
- package/apps/agents-server/src/app/api/metadata/route.ts +116 -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/api/upload/route.ts +83 -0
- package/apps/agents-server/src/app/api/users/[username]/route.ts +75 -0
- package/apps/agents-server/src/app/api/users/route.ts +71 -0
- package/apps/agents-server/src/app/docs/[docId]/page.tsx +43 -0
- package/apps/agents-server/src/app/docs/page.tsx +59 -0
- package/apps/agents-server/src/app/embed/page.tsx +24 -0
- package/apps/agents-server/src/app/globals.css +276 -0
- package/apps/agents-server/src/app/humans.txt/route.ts +15 -0
- package/apps/agents-server/src/app/layout.tsx +139 -0
- package/apps/agents-server/src/app/manifest.ts +114 -0
- package/apps/agents-server/src/app/not-found.tsx +5 -0
- package/apps/agents-server/src/app/page.tsx +96 -0
- package/apps/agents-server/src/app/recycle-bin/RestoreAgentButton.tsx +40 -0
- package/apps/agents-server/src/app/recycle-bin/actions.ts +27 -0
- package/apps/agents-server/src/app/recycle-bin/page.tsx +58 -0
- package/apps/agents-server/src/app/restricted/page.tsx +33 -0
- package/apps/agents-server/src/app/robots.txt/route.ts +15 -0
- package/apps/agents-server/src/app/security.txt/route.ts +15 -0
- package/apps/agents-server/src/app/sitemap.xml/route.ts +37 -0
- package/apps/agents-server/src/app/test/og-image/README.md +1 -0
- package/apps/agents-server/src/app/test/og-image/opengraph-image.tsx +37 -0
- package/apps/agents-server/src/app/test/og-image/page.tsx +22 -0
- package/apps/agents-server/src/components/AgentProfile/AgentProfile.tsx +339 -0
- package/apps/agents-server/src/components/AgentProfile/AgentProfileFromSource.tsx +23 -0
- package/apps/agents-server/src/components/AgentProfile/AgentQrCode.tsx +62 -0
- package/apps/agents-server/src/components/AgentProfile/QrCodeModal.tsx +90 -0
- package/apps/agents-server/src/components/Auth/AuthControls.tsx +123 -0
- 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 +88 -0
- package/apps/agents-server/src/components/ErrorPage/ErrorPage.tsx +33 -0
- package/apps/agents-server/src/components/Footer/Footer.tsx +175 -0
- package/apps/agents-server/src/components/ForbiddenPage/ForbiddenPage.tsx +15 -0
- package/apps/agents-server/src/components/Header/Header.tsx +668 -0
- package/apps/agents-server/src/components/Homepage/AgentCard.tsx +60 -0
- package/apps/agents-server/src/components/Homepage/AgentsList.tsx +58 -0
- package/apps/agents-server/src/components/Homepage/Card.tsx +18 -0
- package/apps/agents-server/src/components/Homepage/ExternalAgentsSection.tsx +21 -0
- package/apps/agents-server/src/components/Homepage/ExternalAgentsSectionClient.tsx +183 -0
- package/apps/agents-server/src/components/Homepage/ModelCard.tsx +29 -0
- package/apps/agents-server/src/components/Homepage/ModelsSection.tsx +75 -0
- package/apps/agents-server/src/components/Homepage/Section.tsx +17 -0
- package/apps/agents-server/src/components/Homepage/TechInfoCard.tsx +20 -0
- package/apps/agents-server/src/components/LayoutWrapper/LayoutWrapper.tsx +57 -0
- package/apps/agents-server/src/components/LoginDialog/LoginDialog.tsx +41 -0
- package/apps/agents-server/src/components/LoginForm/LoginForm.tsx +109 -0
- package/apps/agents-server/src/components/NotFoundPage/NotFoundPage.tsx +17 -0
- package/apps/agents-server/src/components/OpenMojiIcon/OpenMojiIcon.tsx +20 -0
- package/apps/agents-server/src/components/Portal/Portal.tsx +38 -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/components/UsersList/UsersList.tsx +141 -0
- package/apps/agents-server/src/components/UsersList/useUsersAdmin.ts +139 -0
- package/apps/agents-server/src/components/VercelDeploymentCard/VercelDeploymentCard.tsx +55 -0
- package/apps/agents-server/src/components/_utils/generateMetaTxt.ts +28 -0
- package/apps/agents-server/src/components/_utils/headlessParam.tsx +36 -0
- package/apps/agents-server/src/database/$getTableName.ts +18 -0
- package/apps/agents-server/src/database/$provideSupabase.ts +29 -0
- package/apps/agents-server/src/database/$provideSupabaseForBrowser.ts +41 -0
- package/apps/agents-server/src/database/$provideSupabaseForServer.ts +48 -0
- package/apps/agents-server/src/database/$provideSupabaseForWorker.ts +43 -0
- package/apps/agents-server/src/database/getMetadata.ts +31 -0
- package/apps/agents-server/src/database/metadataDefaults.ts +75 -0
- package/apps/agents-server/src/database/migrate.ts +131 -0
- package/apps/agents-server/src/database/migrations/2025-11-0001-initial-schema.sql +163 -0
- package/apps/agents-server/src/database/migrations/2025-11-0002-metadata-table.sql +16 -0
- package/apps/agents-server/src/database/migrations/2025-12-0010-llm-cache.sql +12 -0
- package/apps/agents-server/src/database/migrations/2025-12-0060-api-tokens.sql +13 -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 +308 -0
- package/apps/agents-server/src/deamons/longRunningTask.ts +37 -0
- package/apps/agents-server/src/middleware.ts +305 -0
- package/apps/agents-server/src/tools/$provideAgentCollectionForServer.ts +54 -0
- package/apps/agents-server/src/tools/$provideCdnForServer.ts +36 -0
- package/apps/agents-server/src/tools/$provideExecutionToolsForServer.ts +117 -0
- package/apps/agents-server/src/tools/$provideOpenAiAssistantExecutionToolsForServer.ts +35 -0
- package/apps/agents-server/src/tools/$provideServer.ts +39 -0
- package/apps/agents-server/src/utils/auth.ts +33 -0
- package/apps/agents-server/src/utils/authenticateUser.ts +42 -0
- package/apps/agents-server/src/utils/cache/SupabaseCacheStorage.ts +55 -0
- package/apps/agents-server/src/utils/cdn/classes/DigitalOceanSpaces.ts +119 -0
- package/apps/agents-server/src/utils/cdn/classes/VercelBlobStorage.ts +64 -0
- package/apps/agents-server/src/utils/cdn/interfaces/IFilesStorage.ts +32 -0
- package/apps/agents-server/src/utils/cdn/interfaces/IStorage.ts +14 -0
- package/apps/agents-server/src/utils/cdn/utils/getUserFileCdnKey.ts +28 -0
- package/apps/agents-server/src/utils/cdn/utils/nameToSubfolderPath.ts +9 -0
- package/apps/agents-server/src/utils/cdn/utils/nextRequestToNodeRequest.ts +27 -0
- package/apps/agents-server/src/utils/chatFeedbackAdmin.ts +96 -0
- package/apps/agents-server/src/utils/chatHistoryAdmin.ts +96 -0
- package/apps/agents-server/src/utils/convertToCsv.ts +31 -0
- package/apps/agents-server/src/utils/getCurrentUser.ts +32 -0
- package/apps/agents-server/src/utils/getEffectiveFederatedServers.ts +22 -0
- package/apps/agents-server/src/utils/getFederatedAgents.ts +89 -0
- package/apps/agents-server/src/utils/getFederatedServersFromMetadata.ts +10 -0
- package/apps/agents-server/src/utils/getVisibleCommitmentDefinitions.ts +12 -0
- package/apps/agents-server/src/utils/handleChatCompletion.ts +355 -0
- package/apps/agents-server/src/utils/isIpAllowed.ts +101 -0
- package/apps/agents-server/src/utils/isUserAdmin.ts +31 -0
- package/apps/agents-server/src/utils/resolveInheritedAgentSource.ts +100 -0
- package/apps/agents-server/src/utils/session.ts +50 -0
- package/apps/agents-server/src/utils/validateApiKey.ts +128 -0
- package/apps/agents-server/src/utils/validators/validateMimeType.ts +24 -0
- package/apps/agents-server/tailwind.config.ts +26 -0
- package/apps/agents-server/tsconfig.json +29 -0
- package/apps/agents-server/vercel.json +7 -0
- package/esm/index.es.js +5406 -443
- package/esm/index.es.js.map +1 -1
- package/esm/typings/books/index.d.ts +0 -81
- package/esm/typings/servers.d.ts +9 -7
- package/esm/typings/src/_packages/browser.index.d.ts +6 -0
- package/esm/typings/src/_packages/cli.index.d.ts +4 -0
- package/esm/typings/src/_packages/components.index.d.ts +22 -8
- package/esm/typings/src/_packages/core.index.d.ts +58 -18
- package/esm/typings/src/_packages/node.index.d.ts +2 -2
- package/esm/typings/src/_packages/remote-server.index.d.ts +2 -0
- package/esm/typings/src/_packages/types.index.d.ts +70 -8
- package/esm/typings/src/_packages/utils.index.d.ts +6 -0
- package/esm/typings/src/_packages/wizard.index.d.ts +4 -0
- package/esm/typings/src/book-2.0/agent-source/AgentBasicInformation.d.ts +20 -5
- package/esm/typings/src/book-2.0/agent-source/AgentModelRequirements.d.ts +17 -1
- package/esm/typings/src/book-2.0/agent-source/AgentSourceParseResult.d.ts +3 -2
- package/esm/typings/src/book-2.0/agent-source/computeAgentHash.d.ts +8 -0
- package/esm/typings/src/book-2.0/agent-source/createCommitmentRegex.d.ts +3 -3
- package/esm/typings/src/book-2.0/agent-source/createDefaultAgentName.d.ts +8 -0
- package/esm/typings/src/book-2.0/agent-source/normalizeAgentName.d.ts +9 -0
- package/esm/typings/src/book-2.0/agent-source/padBook.d.ts +18 -0
- package/esm/typings/src/book-2.0/agent-source/parseAgentSourceWithCommitments.d.ts +1 -1
- package/esm/typings/src/book-2.0/agent-source/string_book.d.ts +3 -0
- package/esm/typings/src/book-components/AvatarProfile/AvatarProfile/AvatarProfile.d.ts +6 -1
- package/esm/typings/src/book-components/BookEditor/BookEditor.d.ts +85 -14
- package/esm/typings/src/book-components/BookEditor/BookEditorActionbar.d.ts +18 -0
- package/esm/typings/src/book-components/BookEditor/BookEditorMonaco.d.ts +5 -0
- package/esm/typings/src/book-components/Chat/AgentChat/AgentChat.d.ts +17 -0
- package/esm/typings/src/book-components/Chat/AgentChat/AgentChatProps.d.ts +13 -0
- package/esm/typings/src/book-components/Chat/Chat/ChatProps.d.ts +16 -0
- package/esm/typings/src/book-components/Chat/LlmChat/LlmChatProps.d.ts +5 -0
- package/esm/typings/src/book-components/Chat/MarkdownContent/MarkdownContent.d.ts +15 -0
- package/esm/typings/src/book-components/Chat/MockedChat/MockedChat.d.ts +5 -0
- package/esm/typings/src/book-components/Chat/save/_common/ChatSaveFormatDefinition.d.ts +1 -1
- package/esm/typings/src/book-components/Chat/save/html/htmlSaveFormatDefinition.d.ts +1 -0
- package/esm/typings/src/book-components/Chat/save/pdf/pdfSaveFormatDefinition.d.ts +4 -0
- package/esm/typings/src/book-components/Chat/types/ChatParticipant.d.ts +1 -1
- package/esm/typings/src/book-components/PromptbookAgent/PromptbookAgentIntegration.d.ts +52 -0
- package/esm/typings/src/book-components/PromptbookAgent/PromptbookAgentSeamlessIntegration.d.ts +14 -0
- package/esm/typings/src/book-components/Qr/BrandedQrCode.d.ts +18 -0
- package/esm/typings/src/book-components/Qr/GenericQrCode.d.ts +10 -0
- package/esm/typings/src/book-components/Qr/PromptbookQrCode.d.ts +18 -0
- package/esm/typings/src/book-components/Qr/useQrCode.d.ts +15 -0
- package/esm/typings/src/book-components/_common/Dropdown/Dropdown.d.ts +15 -0
- package/esm/typings/src/book-components/_common/HamburgerMenu/HamburgerMenu.d.ts +12 -0
- package/esm/typings/src/book-components/_common/Modal/Modal.d.ts +2 -2
- package/esm/typings/src/book-components/_common/Tooltip/Tooltip.d.ts +47 -0
- package/esm/typings/src/book-components/icons/AboutIcon.d.ts +9 -0
- package/esm/typings/src/book-components/icons/CameraIcon.d.ts +11 -0
- package/esm/typings/src/book-components/icons/CloseIcon.d.ts +4 -8
- package/esm/typings/src/book-components/icons/DownloadIcon.d.ts +9 -0
- package/esm/typings/src/book-components/icons/ExitFullscreenIcon.d.ts +7 -0
- package/esm/typings/src/book-components/icons/FullscreenIcon.d.ts +7 -0
- package/esm/typings/src/book-components/icons/MenuIcon.d.ts +12 -0
- package/esm/typings/src/book-components/icons/MicIcon.d.ts +8 -0
- package/esm/typings/src/book-components/icons/SendIcon.d.ts +3 -0
- package/esm/typings/src/cli/cli-commands/_boilerplate.d.ts +2 -1
- package/esm/typings/src/cli/cli-commands/about.d.ts +3 -1
- package/esm/typings/src/cli/cli-commands/hello.d.ts +2 -1
- package/esm/typings/src/cli/cli-commands/list-models.d.ts +2 -1
- package/esm/typings/src/cli/cli-commands/list-scrapers.d.ts +2 -1
- package/esm/typings/src/cli/cli-commands/login.d.ts +2 -1
- package/esm/typings/src/cli/cli-commands/make.d.ts +2 -1
- package/esm/typings/src/cli/cli-commands/prettify.d.ts +2 -1
- package/esm/typings/src/cli/cli-commands/run.d.ts +2 -1
- package/esm/typings/src/cli/cli-commands/{start-server.d.ts → start-agents-server.d.ts} +3 -2
- package/esm/typings/src/cli/cli-commands/start-pipelines-server.d.ts +15 -0
- package/esm/typings/src/cli/cli-commands/test-command.d.ts +2 -1
- package/esm/typings/src/cli/common/$addGlobalOptionsToCommand.d.ts +2 -1
- package/esm/typings/src/collection/agent-collection/AgentCollection.d.ts +12 -0
- package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentCollectionInSupabase.d.ts +75 -0
- package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentCollectionInSupabaseOptions.d.ts +10 -0
- package/esm/typings/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentsDatabaseSchema.d.ts +154 -0
- package/esm/typings/src/collection/{PipelineCollection.d.ts → pipeline-collection/PipelineCollection.d.ts} +7 -3
- package/esm/typings/src/collection/{SimplePipelineCollection.d.ts → pipeline-collection/SimplePipelineCollection.d.ts} +5 -5
- package/esm/typings/src/collection/{constructors/createCollectionFromDirectory.d.ts → pipeline-collection/constructors/createPipelineCollectionFromDirectory.d.ts} +8 -11
- package/esm/typings/src/collection/pipeline-collection/constructors/createPipelineCollectionFromJson.d.ts +13 -0
- package/esm/typings/src/collection/{constructors/createCollectionFromPromise.d.ts → pipeline-collection/constructors/createPipelineCollectionFromPromise.d.ts} +6 -5
- package/esm/typings/src/collection/pipeline-collection/constructors/createPipelineCollectionFromPromise.test.d.ts +1 -0
- package/esm/typings/src/collection/{constructors/createCollectionFromUrl.d.ts → pipeline-collection/constructors/createPipelineCollectionFromUrl.d.ts} +3 -3
- package/esm/typings/src/collection/{constructors/createSubcollection.d.ts → pipeline-collection/constructors/createPipelineSubcollection.d.ts} +3 -3
- package/esm/typings/src/collection/pipeline-collection/pipelineCollectionToJson.d.ts +13 -0
- package/esm/typings/src/commands/_common/types/CommandParser.d.ts +4 -5
- package/esm/typings/src/{book-2.0/commitments → commitments}/ACTION/ACTION.d.ts +5 -1
- package/esm/typings/src/commitments/CLOSED/CLOSED.d.ts +39 -0
- package/esm/typings/src/commitments/CLOSED/CLOSED.test.d.ts +4 -0
- package/esm/typings/src/commitments/COMPONENT/COMPONENT.d.ts +28 -0
- package/esm/typings/src/{book-2.0/commitments → commitments}/DELETE/DELETE.d.ts +5 -1
- package/esm/typings/src/{book-2.0/commitments → commitments}/FORMAT/FORMAT.d.ts +5 -1
- package/esm/typings/src/commitments/FROM/FROM.d.ts +34 -0
- package/esm/typings/src/{book-2.0/commitments → commitments}/GOAL/GOAL.d.ts +5 -1
- package/esm/typings/src/{book-2.0/commitments → commitments}/KNOWLEDGE/KNOWLEDGE.d.ts +5 -5
- package/esm/typings/src/commitments/LANGUAGE/LANGUAGE.d.ts +35 -0
- package/esm/typings/src/{book-2.0/commitments → commitments}/MEMORY/MEMORY.d.ts +5 -1
- package/esm/typings/src/commitments/MESSAGE/AgentMessageCommitmentDefinition.d.ts +32 -0
- package/esm/typings/src/commitments/MESSAGE/InitialMessageCommitmentDefinition.d.ts +32 -0
- package/esm/typings/src/{book-2.0/commitments → commitments}/MESSAGE/MESSAGE.d.ts +5 -1
- package/esm/typings/src/commitments/MESSAGE/UserMessageCommitmentDefinition.d.ts +32 -0
- package/esm/typings/src/{book-2.0/commitments → commitments}/META/META.d.ts +5 -1
- package/esm/typings/src/commitments/META_COLOR/META_COLOR.d.ts +48 -0
- package/esm/typings/src/commitments/META_FONT/META_FONT.d.ts +42 -0
- package/esm/typings/src/{book-2.0/commitments → commitments}/META_IMAGE/META_IMAGE.d.ts +5 -1
- package/esm/typings/src/{book-2.0/commitments → commitments}/META_LINK/META_LINK.d.ts +5 -1
- package/esm/typings/src/{book-2.0/commitments → commitments}/MODEL/MODEL.d.ts +5 -1
- package/esm/typings/src/{book-2.0/commitments → commitments}/NOTE/NOTE.d.ts +5 -1
- package/esm/typings/src/commitments/OPEN/OPEN.d.ts +35 -0
- package/esm/typings/src/{book-2.0/commitments → commitments}/PERSONA/PERSONA.d.ts +5 -1
- package/esm/typings/src/{book-2.0/commitments → commitments}/RULE/RULE.d.ts +5 -1
- package/esm/typings/src/{book-2.0/commitments → commitments}/SAMPLE/SAMPLE.d.ts +5 -1
- package/esm/typings/src/{book-2.0/commitments → commitments}/SCENARIO/SCENARIO.d.ts +5 -1
- package/esm/typings/src/{book-2.0/commitments → commitments}/STYLE/STYLE.d.ts +5 -1
- package/esm/typings/src/commitments/USE/USE.d.ts +53 -0
- package/esm/typings/src/commitments/USE_BROWSER/USE_BROWSER.d.ts +42 -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/{book-2.0/commitments → commitments}/_base/BaseCommitmentDefinition.d.ts +14 -2
- package/esm/typings/src/{book-2.0/commitments → commitments}/_base/CommitmentDefinition.d.ts +6 -1
- package/esm/typings/src/{book-2.0/commitments → commitments}/_base/NotYetImplementedCommitmentDefinition.d.ts +5 -1
- package/esm/typings/src/{book-2.0/commitments → commitments}/_base/createEmptyAgentModelRequirements.d.ts +1 -1
- package/esm/typings/src/commitments/index.d.ts +93 -0
- package/esm/typings/src/config.d.ts +24 -3
- package/esm/typings/src/conversion/validation/validatePipeline.d.ts +2 -0
- package/esm/typings/src/errors/0-index.d.ts +6 -0
- package/esm/typings/src/errors/DatabaseError.d.ts +12 -0
- package/esm/typings/src/errors/NotAllowed.d.ts +9 -0
- package/esm/typings/src/errors/WrappedError.d.ts +2 -2
- package/esm/typings/src/execution/AvailableModel.d.ts +1 -0
- package/esm/typings/src/execution/Executables.d.ts +3 -0
- package/esm/typings/src/execution/ExecutionTask.d.ts +12 -3
- package/esm/typings/src/execution/ExecutionTools.d.ts +5 -0
- package/esm/typings/src/execution/FilesystemTools.d.ts +1 -1
- package/esm/typings/src/execution/LlmExecutionTools.d.ts +26 -2
- package/esm/typings/src/execution/PromptResult.d.ts +7 -1
- package/esm/typings/src/execution/createPipelineExecutor/10-executePipeline.d.ts +5 -0
- package/esm/typings/src/execution/createPipelineExecutor/20-executeTask.d.ts +5 -0
- package/esm/typings/src/execution/createPipelineExecutor/30-executeFormatSubvalues.d.ts +5 -0
- package/esm/typings/src/execution/createPipelineExecutor/40-executeAttempts.d.ts +5 -0
- package/esm/typings/src/execution/utils/usage-constants.d.ts +4 -124
- package/esm/typings/src/execution/utils/validatePromptResult.d.ts +2 -0
- package/esm/typings/src/high-level-abstractions/_common/HighLevelAbstraction.d.ts +2 -1
- package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsForWizardOrCli.d.ts +2 -2
- package/esm/typings/src/llm-providers/_common/register/$registeredLlmToolsMessage.d.ts +2 -1
- package/esm/typings/src/llm-providers/_common/register/LlmToolsMetadata.d.ts +1 -1
- package/esm/typings/src/llm-providers/_common/utils/assertUniqueModels.d.ts +12 -0
- package/esm/typings/src/llm-providers/_multiple/getSingleLlmExecutionTools.d.ts +1 -0
- package/esm/typings/src/llm-providers/_multiple/joinLlmExecutionTools.d.ts +1 -0
- package/esm/typings/src/llm-providers/agent/Agent.d.ts +72 -0
- package/esm/typings/src/llm-providers/agent/AgentLlmExecutionTools.d.ts +26 -4
- package/esm/typings/src/llm-providers/agent/AgentOptions.d.ts +19 -0
- package/esm/typings/src/llm-providers/agent/CreateAgentLlmExecutionToolsOptions.d.ts +17 -0
- package/esm/typings/src/llm-providers/agent/RemoteAgent.d.ts +50 -0
- package/esm/typings/src/llm-providers/agent/RemoteAgentOptions.d.ts +11 -0
- package/esm/typings/src/llm-providers/agent/createAgentLlmExecutionTools.d.ts +1 -19
- package/esm/typings/src/llm-providers/anthropic-claude/anthropic-claude-models.d.ts +1 -1
- package/esm/typings/src/llm-providers/google/google-models.d.ts +1 -1
- package/esm/typings/src/llm-providers/ollama/OllamaExecutionTools.d.ts +4 -0
- package/esm/typings/src/llm-providers/openai/OpenAiAssistantExecutionTools.d.ts +60 -2
- package/esm/typings/src/llm-providers/openai/OpenAiAssistantExecutionToolsOptions.d.ts +7 -1
- package/esm/typings/src/llm-providers/openai/OpenAiCompatibleExecutionTools.d.ts +13 -1
- package/esm/typings/src/llm-providers/openai/OpenAiExecutionTools.d.ts +4 -0
- package/esm/typings/src/llm-providers/openai/createOpenAiCompatibleExecutionTools.d.ts +6 -6
- package/esm/typings/src/llm-providers/openai/openai-models.d.ts +1 -1
- package/esm/typings/src/llm-providers/openai/openai-models.test.d.ts +4 -0
- package/esm/typings/src/other/templates/getTemplatesPipelineCollection.d.ts +1 -1
- package/esm/typings/src/pipeline/validatePipelineString.d.ts +2 -0
- package/esm/typings/src/playground/permanent/_boilerplate.d.ts +5 -0
- package/esm/typings/src/playground/permanent/agent-with-browser-playground.d.ts +5 -0
- package/esm/typings/src/prepare/PrepareAndScrapeOptions.d.ts +1 -0
- package/esm/typings/src/remote-server/startAgentServer.d.ts +26 -0
- package/esm/typings/src/remote-server/startRemoteServer.d.ts +4 -1
- package/esm/typings/src/remote-server/types/RemoteServerOptions.d.ts +3 -8
- package/esm/typings/src/scrapers/_boilerplate/createBoilerplateScraper.d.ts +1 -12
- package/esm/typings/src/scrapers/_boilerplate/register-metadata.d.ts +1 -9
- package/esm/typings/src/scrapers/document/createDocumentScraper.d.ts +1 -12
- package/esm/typings/src/scrapers/document/register-metadata.d.ts +1 -9
- package/esm/typings/src/scrapers/document-legacy/createLegacyDocumentScraper.d.ts +1 -12
- package/esm/typings/src/scrapers/document-legacy/register-metadata.d.ts +1 -9
- package/esm/typings/src/scrapers/markdown/createMarkdownScraper.d.ts +1 -12
- package/esm/typings/src/scrapers/markdown/register-metadata.d.ts +1 -9
- package/esm/typings/src/scrapers/markitdown/createMarkitdownScraper.d.ts +1 -12
- package/esm/typings/src/scrapers/markitdown/register-metadata.d.ts +1 -9
- package/esm/typings/src/scrapers/pdf/createPdfScraper.d.ts +1 -12
- package/esm/typings/src/scrapers/pdf/register-metadata.d.ts +1 -9
- package/esm/typings/src/scrapers/website/createWebsiteScraper.d.ts +1 -12
- package/esm/typings/src/scrapers/website/register-metadata.d.ts +1 -9
- package/esm/typings/src/storage/_common/PromptbookStorage.d.ts +1 -0
- package/esm/typings/src/storage/env-storage/$EnvStorage.d.ts +2 -1
- package/esm/typings/src/transpilers/_common/BookTranspiler.d.ts +33 -0
- package/esm/typings/src/transpilers/_common/BookTranspilerOptions.d.ts +18 -0
- package/esm/typings/src/transpilers/_common/register/$bookTranspilersRegister.d.ts +15 -0
- package/esm/typings/src/transpilers/formatted-book-in-markdown/FormattedBookInMarkdownTranspiler.d.ts +16 -0
- package/esm/typings/src/transpilers/formatted-book-in-markdown/register.d.ts +15 -0
- package/esm/typings/src/transpilers/openai-sdk/OpenAiSdkTranspiler.d.ts +16 -0
- package/esm/typings/src/transpilers/openai-sdk/OpenAiSdkTranspiler.test.d.ts +1 -0
- package/esm/typings/src/transpilers/openai-sdk/playground/playground.d.ts +5 -0
- package/esm/typings/src/transpilers/openai-sdk/register.d.ts +15 -0
- package/esm/typings/src/types/LlmCall.d.ts +20 -0
- package/esm/typings/src/types/ModelRequirements.d.ts +13 -1
- package/esm/typings/src/types/ModelVariant.d.ts +1 -1
- package/esm/typings/src/types/Prompt.d.ts +13 -1
- package/esm/typings/src/types/Updatable.d.ts +19 -0
- package/esm/typings/src/types/typeAliases.d.ts +38 -2
- package/esm/typings/src/utils/color/$randomColor.d.ts +1 -0
- package/esm/typings/src/utils/color/Color.d.ts +16 -1
- package/esm/typings/src/utils/color/Color.test.d.ts +1 -0
- package/esm/typings/src/utils/color/css-colors.d.ts +1 -0
- package/esm/typings/src/utils/color/internal-utils/checkChannelValue.d.ts +0 -3
- package/esm/typings/src/utils/color/operators/darken.d.ts +1 -1
- package/esm/typings/src/utils/color/operators/grayscale.d.ts +1 -1
- package/esm/typings/src/utils/color/operators/lighten.d.ts +1 -1
- package/esm/typings/src/utils/color/operators/mixWithColor.d.ts +1 -1
- package/esm/typings/src/utils/color/operators/saturate.d.ts +1 -1
- package/esm/typings/src/utils/environment/$detectRuntimeEnvironment.d.ts +16 -0
- package/esm/typings/src/utils/environment/$getGlobalScope.d.ts +2 -2
- package/esm/typings/src/utils/execCommand/$execCommand.d.ts +2 -1
- package/esm/typings/src/utils/execCommand/$execCommands.d.ts +2 -1
- package/esm/typings/src/utils/files/$induceBookDownload.d.ts +13 -0
- package/esm/typings/src/utils/files/$induceFileDownload.d.ts +13 -0
- package/esm/typings/src/utils/files/ObjectUrl.d.ts +46 -0
- package/esm/typings/src/utils/files/listAllFiles.d.ts +2 -3
- package/esm/typings/src/utils/misc/aboutPromptbookInformation.d.ts +27 -0
- package/esm/typings/src/utils/misc/computeHash.d.ts +11 -0
- package/esm/typings/src/utils/misc/computeHash.test.d.ts +1 -0
- package/esm/typings/src/utils/misc/injectCssModuleIntoShadowRoot.d.ts +1 -0
- package/esm/typings/src/utils/misc/xAboutPromptbookInformation.d.ts +13 -0
- package/esm/typings/src/utils/normalization/normalize-to-kebab-case.d.ts +2 -0
- package/esm/typings/src/utils/normalization/normalizeMessageText.d.ts +9 -0
- package/esm/typings/src/utils/normalization/normalizeMessageText.test.d.ts +1 -0
- package/esm/typings/src/utils/normalization/normalizeTo_PascalCase.d.ts +3 -0
- package/esm/typings/src/utils/normalization/normalizeTo_camelCase.d.ts +2 -0
- package/esm/typings/src/utils/normalization/titleToName.d.ts +2 -0
- package/esm/typings/src/utils/organization/$sideEffect.d.ts +2 -2
- package/esm/typings/src/utils/organization/$side_effect.d.ts +7 -0
- package/esm/typings/src/utils/organization/TODO_USE.d.ts +2 -2
- package/esm/typings/src/utils/organization/keepUnused.d.ts +2 -2
- package/esm/typings/src/utils/organization/preserve.d.ts +3 -3
- package/esm/typings/src/utils/organization/really_any.d.ts +7 -0
- package/esm/typings/src/utils/random/$generateBookBoilerplate.d.ts +31 -0
- package/esm/typings/src/utils/random/$randomAgentPersona.d.ts +9 -0
- package/esm/typings/src/utils/random/$randomFullnameWithColor.d.ts +13 -0
- package/esm/typings/src/utils/random/$randomItem.d.ts +9 -0
- package/esm/typings/src/utils/random/$randomSeed.d.ts +3 -0
- package/esm/typings/src/utils/random/$randomToken.d.ts +2 -0
- package/esm/typings/src/utils/random/CzechNamePool.d.ts +7 -0
- package/esm/typings/src/utils/random/EnglishNamePool.d.ts +7 -0
- package/esm/typings/src/utils/random/NamePool.d.ts +17 -0
- package/esm/typings/src/utils/random/getNamePool.d.ts +10 -0
- package/esm/typings/src/utils/serialization/$deepFreeze.d.ts +2 -1
- package/esm/typings/src/utils/serialization/asSerializable.d.ts +2 -2
- package/esm/typings/src/utils/serialization/serializeToPromptbookJavascript.d.ts +2 -2
- package/esm/typings/src/utils/validators/parameterName/validateParameterName.d.ts +2 -0
- package/esm/typings/src/version.d.ts +1 -1
- package/esm/typings/src/wizard/$getCompiledBook.d.ts +1 -2
- package/package.json +16 -16
- package/umd/index.umd.js +5382 -417
- package/umd/index.umd.js.map +1 -1
- package/esm/typings/src/book-2.0/commitments/index.d.ts +0 -60
- package/esm/typings/src/book-components/BookEditor/BookEditorInner.d.ts +0 -5
- package/esm/typings/src/book-components/BookEditor/BookEditorWrapper.d.ts +0 -9
- package/esm/typings/src/book-components/BookEditor/config.d.ts +0 -10
- package/esm/typings/src/book-components/Chat/utils/renderMarkdown.d.ts +0 -21
- package/esm/typings/src/collection/collectionToJson.d.ts +0 -13
- package/esm/typings/src/collection/constructors/createCollectionFromJson.d.ts +0 -13
- /package/esm/typings/src/{book-components/Chat/utils/renderMarkdown.test.d.ts → book-2.0/agent-source/computeAgentHash.test.d.ts} +0 -0
- /package/esm/typings/src/{collection/constructors/createCollectionFromDirectory.test.d.ts → book-2.0/agent-source/normalizeAgentName.test.d.ts} +0 -0
- /package/esm/typings/src/{collection/constructors/createCollectionFromJson.test.d.ts → book-components/Chat/AgentChat/AgentChat.test.d.ts} +0 -0
- /package/esm/typings/src/collection/{constructors/createCollectionFromPromise.test.d.ts → pipeline-collection/constructors/createPipelineCollectionFromDirectory.test.d.ts} +0 -0
- /package/esm/typings/src/{commands/_common/parseCommand.test.d.ts → collection/pipeline-collection/constructors/createPipelineCollectionFromJson.test.d.ts} +0 -0
- /package/esm/typings/src/collection/{collectionToJson.test.d.ts → pipeline-collection/pipelineCollectionToJson.test.d.ts} +0 -0
- /package/esm/typings/src/{book-2.0/commitments → commitments}/_base/BookCommitment.d.ts +0 -0
- /package/esm/typings/src/{book-2.0/commitments → commitments}/_base/ParsedCommitment.d.ts +0 -0
|
@@ -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,101 @@
|
|
|
1
|
+
import { isIPv4, isIPv6 } from 'net';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Checks if the IP address is allowed based on the allowed IPs list
|
|
5
|
+
*
|
|
6
|
+
* @param clientIp - The IP address of the client
|
|
7
|
+
* @param allowedIps - Comma separated list of allowed IPs or CIDR ranges
|
|
8
|
+
* @returns true if the IP is allowed, false otherwise
|
|
9
|
+
*/
|
|
10
|
+
export function isIpAllowed(clientIp: string, allowedIps: string | null | undefined): boolean {
|
|
11
|
+
if (!allowedIps || allowedIps.trim() === '') {
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const allowedList = allowedIps.split(',').map((ip) => ip.trim());
|
|
16
|
+
|
|
17
|
+
for (const allowed of allowedList) {
|
|
18
|
+
if (allowed === '') {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (allowed.includes('/')) {
|
|
23
|
+
// CIDR
|
|
24
|
+
if (isIpInCidr(clientIp, allowed)) {
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
} else {
|
|
28
|
+
// Single IP
|
|
29
|
+
if (clientIp === allowed) {
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isIpInCidr(ip: string, cidr: string): boolean {
|
|
39
|
+
try {
|
|
40
|
+
const [range, bitsStr] = cidr.split('/');
|
|
41
|
+
const bits = parseInt(bitsStr, 10);
|
|
42
|
+
|
|
43
|
+
if (isIPv4(ip) && isIPv4(range)) {
|
|
44
|
+
return isIPv4InCidr(ip, range, bits);
|
|
45
|
+
} else if (isIPv6(ip) && isIPv6(range)) {
|
|
46
|
+
return isIPv6InCidr(ip, range, bits);
|
|
47
|
+
} else if (isIPv6(ip) && isIPv4(range)) {
|
|
48
|
+
// Check if IPv6 is IPv4-mapped
|
|
49
|
+
if (ip.startsWith('::ffff:')) {
|
|
50
|
+
return isIPv4InCidr(ip.substring(7), range, bits);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
} catch (error) {
|
|
54
|
+
console.error(`Error checking CIDR ${cidr} for IP ${ip}:`, error);
|
|
55
|
+
}
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function ipToLong(ip: string): number {
|
|
60
|
+
return (
|
|
61
|
+
ip.split('.').reduce((acc, octet) => {
|
|
62
|
+
return (acc << 8) + parseInt(octet, 10);
|
|
63
|
+
}, 0) >>> 0
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function isIPv4InCidr(ip: string, range: string, bits: number): boolean {
|
|
68
|
+
const mask = ~((1 << (32 - bits)) - 1);
|
|
69
|
+
const ipLong = ipToLong(ip);
|
|
70
|
+
const rangeLong = ipToLong(range);
|
|
71
|
+
|
|
72
|
+
return (ipLong & mask) === (rangeLong & mask);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function parseIPv6(ip: string): bigint {
|
|
76
|
+
// Expand ::
|
|
77
|
+
let fullIp = ip;
|
|
78
|
+
if (ip.includes('::')) {
|
|
79
|
+
const parts = ip.split('::');
|
|
80
|
+
const left = parts[0].split(':').filter(Boolean);
|
|
81
|
+
const right = parts[1].split(':').filter(Boolean);
|
|
82
|
+
const missing = 8 - (left.length + right.length);
|
|
83
|
+
const zeros = Array(missing).fill('0');
|
|
84
|
+
fullIp = [...left, ...zeros, ...right].join(':');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const parts = fullIp.split(':');
|
|
88
|
+
let value = BigInt(0);
|
|
89
|
+
for (const part of parts) {
|
|
90
|
+
value = (value << BigInt(16)) + BigInt(parseInt(part || '0', 16));
|
|
91
|
+
}
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function isIPv6InCidr(ip: string, range: string, bits: number): boolean {
|
|
96
|
+
const ipBigInt = parseIPv6(ip);
|
|
97
|
+
const rangeBigInt = parseIPv6(range);
|
|
98
|
+
const mask = (BigInt(1) << BigInt(128)) - BigInt(1) ^ ((BigInt(1) << BigInt(128 - bits)) - BigInt(1));
|
|
99
|
+
|
|
100
|
+
return (ipBigInt & mask) === (rangeBigInt & mask);
|
|
101
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { cookies } from 'next/headers';
|
|
2
|
+
import { getSession } from './session';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Checks if the current user is an admin
|
|
6
|
+
*
|
|
7
|
+
* Note: If `process.env.ADMIN_PASSWORD` is not set, no one is admin
|
|
8
|
+
*
|
|
9
|
+
* @returns true if the user is admin
|
|
10
|
+
*/
|
|
11
|
+
export async function isUserAdmin(): Promise<boolean> {
|
|
12
|
+
if (!process.env.ADMIN_PASSWORD) {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Check legacy admin token
|
|
17
|
+
const cookieStore = await cookies();
|
|
18
|
+
const adminToken = cookieStore.get('adminToken');
|
|
19
|
+
|
|
20
|
+
if (adminToken?.value === process.env.ADMIN_PASSWORD) {
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Check session
|
|
25
|
+
const session = await getSession();
|
|
26
|
+
if (session?.isAdmin) {
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
@@ -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,50 @@
|
|
|
1
|
+
import { createHmac } from 'crypto';
|
|
2
|
+
import { cookies } from 'next/headers';
|
|
3
|
+
|
|
4
|
+
const SESSION_COOKIE_NAME = 'sessionToken';
|
|
5
|
+
const SECRET_KEY = process.env.ADMIN_PASSWORD || 'default-secret-key-change-me';
|
|
6
|
+
|
|
7
|
+
type SessionUser = {
|
|
8
|
+
username: string;
|
|
9
|
+
isAdmin: boolean;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export async function setSession(user: SessionUser) {
|
|
13
|
+
const payload = JSON.stringify(user);
|
|
14
|
+
const signature = createHmac('sha256', SECRET_KEY).update(payload).digest('hex');
|
|
15
|
+
const token = `${Buffer.from(payload).toString('base64')}.${signature}`;
|
|
16
|
+
|
|
17
|
+
(await cookies()).set(SESSION_COOKIE_NAME, token, {
|
|
18
|
+
httpOnly: true,
|
|
19
|
+
secure: process.env.NODE_ENV === 'production',
|
|
20
|
+
path: '/',
|
|
21
|
+
maxAge: 60 * 60 * 24 * 7, // 1 week
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function clearSession() {
|
|
26
|
+
(await cookies()).delete(SESSION_COOKIE_NAME);
|
|
27
|
+
// Also clear legacy adminToken
|
|
28
|
+
(await cookies()).delete('adminToken');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function getSession(): Promise<SessionUser | null> {
|
|
32
|
+
const cookieStore = await cookies();
|
|
33
|
+
const token = cookieStore.get(SESSION_COOKIE_NAME)?.value;
|
|
34
|
+
|
|
35
|
+
if (!token) return null;
|
|
36
|
+
|
|
37
|
+
const [payloadBase64, signature] = token.split('.');
|
|
38
|
+
if (!payloadBase64 || !signature) return null;
|
|
39
|
+
|
|
40
|
+
const payload = Buffer.from(payloadBase64, 'base64').toString('utf-8');
|
|
41
|
+
const expectedSignature = createHmac('sha256', SECRET_KEY).update(payload).digest('hex');
|
|
42
|
+
|
|
43
|
+
if (signature !== expectedSignature) return null;
|
|
44
|
+
|
|
45
|
+
try {
|
|
46
|
+
return JSON.parse(payload) as SessionUser;
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|