openadminjs 0.1.1
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/.env.example +9 -0
- package/.github/FUNDING.yml +3 -0
- package/.github/ISSUE_TEMPLATE/bug_report.yml +10 -0
- package/.github/ISSUE_TEMPLATE/feature_request.yml +10 -0
- package/.github/PULL_REQUEST_TEMPLATE.md +9 -0
- package/.github/dependabot.yml +10 -0
- package/.github/workflows/ci.yml +26 -0
- package/CHANGELOG.md +5 -0
- package/CODE_OF_CONDUCT.md +3 -0
- package/CONTRIBUTING.md +11 -0
- package/LICENSE +21 -0
- package/README.md +175 -0
- package/ROADMAP.md +7 -0
- package/SECURITY.md +11 -0
- package/apps/admin/app/api/auth/login/route.ts +51 -0
- package/apps/admin/app/api/auth/logout/route.ts +11 -0
- package/apps/admin/app/api/auth/refresh/route.ts +46 -0
- package/apps/admin/app/api-tokens/page.tsx +253 -0
- package/apps/admin/app/audit-logs/page.tsx +5 -0
- package/apps/admin/app/dashboard/page.tsx +392 -0
- package/apps/admin/app/files/page.tsx +5 -0
- package/apps/admin/app/globals.css +206 -0
- package/apps/admin/app/jobs/page.tsx +19 -0
- package/apps/admin/app/layout.tsx +57 -0
- package/apps/admin/app/login/page.test.tsx +18 -0
- package/apps/admin/app/login/page.tsx +161 -0
- package/apps/admin/app/login/safe-next-param.ts +4 -0
- package/apps/admin/app/notifications/page.tsx +146 -0
- package/apps/admin/app/page.tsx +5 -0
- package/apps/admin/app/plugins/page.tsx +348 -0
- package/apps/admin/app/profile/page.tsx +116 -0
- package/apps/admin/app/resources/[resource]/[id]/edit/page.tsx +45 -0
- package/apps/admin/app/resources/[resource]/[id]/page.tsx +449 -0
- package/apps/admin/app/resources/[resource]/create/page.tsx +34 -0
- package/apps/admin/app/resources/[resource]/page.tsx +100 -0
- package/apps/admin/app/settings/page.tsx +233 -0
- package/apps/admin/components/ai-assistant-widget.tsx +684 -0
- package/apps/admin/components/app-shell.tsx +305 -0
- package/apps/admin/components/auth-guard.test.tsx +55 -0
- package/apps/admin/components/auth-guard.tsx +39 -0
- package/apps/admin/components/jobs-panel.tsx +103 -0
- package/apps/admin/components/logo.tsx +30 -0
- package/apps/admin/components/resource-form.tsx +349 -0
- package/apps/admin/components/resource-table.tsx +277 -0
- package/apps/admin/lib/ai-events.ts +23 -0
- package/apps/admin/lib/api.test.ts +118 -0
- package/apps/admin/lib/api.ts +135 -0
- package/apps/admin/lib/auth-flow.e2e.test.ts +79 -0
- package/apps/admin/lib/brand.ts +14 -0
- package/apps/admin/lib/locale.ts +49 -0
- package/apps/admin/lib/tokens.ts +93 -0
- package/apps/admin/middleware.ts +58 -0
- package/apps/admin/next-env.d.ts +6 -0
- package/apps/admin/next.config.mjs +7 -0
- package/apps/admin/package.json +44 -0
- package/apps/admin/postcss.config.mjs +6 -0
- package/apps/admin/public/brand/apple-touch-icon.png +0 -0
- package/apps/admin/public/brand/favicon.svg +1 -0
- package/apps/admin/public/brand/og-image.png +0 -0
- package/apps/admin/public/brand/openadminjs-icon-new.png +0 -0
- package/apps/admin/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/apps/admin/public/brand/openadminjs-logo-new.png +0 -0
- package/apps/admin/tailwind.config.ts +37 -0
- package/apps/admin/tsconfig.json +23 -0
- package/apps/admin/vitest.config.ts +7 -0
- package/apps/api/package.json +56 -0
- package/apps/api/plugins.manifest.example.json +22 -0
- package/apps/api/plugins.manifest.json +4 -0
- package/apps/api/src/access/catalog.ts +112 -0
- package/apps/api/src/access/derive-permissions.test.ts +26 -0
- package/apps/api/src/access/derive-permissions.ts +36 -0
- package/apps/api/src/access/public-catalog.ts +28 -0
- package/apps/api/src/admin/admin-ai.controller.ts +125 -0
- package/apps/api/src/admin/admin-ai.events.ts +23 -0
- package/apps/api/src/admin/admin-ai.service.ts +1238 -0
- package/apps/api/src/admin/admin-analytics.service.ts +164 -0
- package/apps/api/src/admin/admin-plugins.controller.ts +32 -0
- package/apps/api/src/admin/admin-plugins.service.ts +253 -0
- package/apps/api/src/admin/admin-resource.service.test.ts +118 -0
- package/apps/api/src/admin/admin-resource.service.ts +375 -0
- package/apps/api/src/admin/admin.controller.ts +72 -0
- package/apps/api/src/admin/admin.module.ts +30 -0
- package/apps/api/src/admin/dto/plugins.dto.ts +37 -0
- package/apps/api/src/admin/validate-resource-payload.test.ts +44 -0
- package/apps/api/src/admin/validate-resource-payload.ts +103 -0
- package/apps/api/src/app.module.ts +37 -0
- package/apps/api/src/auth/auth.controller.ts +70 -0
- package/apps/api/src/auth/auth.dto.ts +49 -0
- package/apps/api/src/auth/auth.module.ts +30 -0
- package/apps/api/src/auth/auth.service.test.ts +75 -0
- package/apps/api/src/auth/auth.service.ts +231 -0
- package/apps/api/src/common/auth-realm.decorator.ts +6 -0
- package/apps/api/src/common/auth.guard.test.ts +61 -0
- package/apps/api/src/common/auth.guard.ts +78 -0
- package/apps/api/src/common/casl-ability.factory.test.ts +33 -0
- package/apps/api/src/common/casl-ability.factory.ts +41 -0
- package/apps/api/src/common/current-user.decorator.ts +6 -0
- package/apps/api/src/common/permission.decorator.ts +7 -0
- package/apps/api/src/common/permissions.guard.ts +31 -0
- package/apps/api/src/common/prisma.service.ts +13 -0
- package/apps/api/src/health/health.controller.ts +25 -0
- package/apps/api/src/mail/mail.module.ts +9 -0
- package/apps/api/src/mail/mail.service.ts +115 -0
- package/apps/api/src/main.ts +37 -0
- package/apps/api/src/plugins/bootstrap.ts +4 -0
- package/apps/api/src/plugins/bundled/hello.plugin.ts +19 -0
- package/apps/api/src/plugins/bundled/registry.ts +7 -0
- package/apps/api/src/plugins/manifest-path.ts +35 -0
- package/apps/api/src/plugins/manifest.schema.test.ts +28 -0
- package/apps/api/src/plugins/manifest.schema.ts +38 -0
- package/apps/api/src/plugins/plugin-loader.ts +109 -0
- package/apps/api/src/queue/queue.controller.ts +28 -0
- package/apps/api/src/queue/queue.module.ts +23 -0
- package/apps/api/src/queue/queue.processor.ts +47 -0
- package/apps/api/src/queue/queue.service.ts +50 -0
- package/apps/api/src/resources/categories.resource.ts +21 -0
- package/apps/api/src/resources/commerce.resource.ts +157 -0
- package/apps/api/src/resources/operations.resource.ts +111 -0
- package/apps/api/src/resources/posts.resource.ts +88 -0
- package/apps/api/src/resources/registry.ts +27 -0
- package/apps/api/src/resources/resource-hooks.install.ts +18 -0
- package/apps/api/src/resources/resource-hooks.registry.test.ts +72 -0
- package/apps/api/src/resources/resource-hooks.registry.ts +66 -0
- package/apps/api/src/resources/resource-hooks.runner.ts +86 -0
- package/apps/api/src/resources/system.resource.ts +51 -0
- package/apps/api/src/resources/users.resource.ts +19 -0
- package/apps/api/src/store/payment/payment.controller.ts +98 -0
- package/apps/api/src/store/payment/payment.module.ts +14 -0
- package/apps/api/src/store/payment/payment.provider.ts +38 -0
- package/apps/api/src/store/payment/payment.service.ts +235 -0
- package/apps/api/src/store/store.controller.ts +26 -0
- package/apps/api/src/store/store.module.ts +12 -0
- package/apps/api/src/test-setup.ts +1 -0
- package/apps/api/tsconfig.json +11 -0
- package/apps/api/vitest.config.ts +21 -0
- package/apps/web/README.md +12 -0
- package/apps/web/app/globals.css +12 -0
- package/apps/web/app/layout.tsx +18 -0
- package/apps/web/app/page.tsx +27 -0
- package/apps/web/app/posts/[slug]/page.tsx +38 -0
- package/apps/web/app/posts/page.tsx +20 -0
- package/apps/web/app/robots.txt/route.ts +9 -0
- package/apps/web/app/sitemap.xml/route.ts +20 -0
- package/apps/web/components/public-fields.tsx +22 -0
- package/apps/web/lib/openadmin-client.ts +82 -0
- package/apps/web/lib/seo.test.ts +41 -0
- package/apps/web/lib/seo.ts +53 -0
- package/apps/web/next-env.d.ts +6 -0
- package/apps/web/next.config.mjs +5 -0
- package/apps/web/package.json +30 -0
- package/apps/web/postcss.config.mjs +6 -0
- package/apps/web/public/brand/apple-touch-icon.png +0 -0
- package/apps/web/public/brand/favicon.svg +1 -0
- package/apps/web/public/brand/og-image.png +0 -0
- package/apps/web/public/brand/openadminjs-icon-new.png +0 -0
- package/apps/web/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/apps/web/public/brand/openadminjs-logo-new.png +0 -0
- package/apps/web/tailwind.config.ts +21 -0
- package/apps/web/test/next-stub.ts +7 -0
- package/apps/web/tsconfig.json +23 -0
- package/apps/web/vitest.config.ts +19 -0
- package/docs/content/security.md +7 -0
- package/eslint.config.mjs +11 -0
- package/examples/README.md +80 -0
- package/examples/basic-admin/README.md +24 -0
- package/examples/basic-admin/package.json +17 -0
- package/examples/basic-admin/prisma/models.fragment.prisma +12 -0
- package/examples/basic-admin/src/index.test.ts +8 -0
- package/examples/basic-admin/src/index.ts +5 -0
- package/examples/basic-admin/src/resources/lead.resource.ts +30 -0
- package/examples/basic-admin/tsconfig.json +7 -0
- package/examples/basic-admin/vitest.config.ts +16 -0
- package/examples/blog-admin/README.md +18 -0
- package/examples/blog-admin/package.json +17 -0
- package/examples/blog-admin/prisma/models.fragment.prisma +30 -0
- package/examples/blog-admin/src/index.test.ts +8 -0
- package/examples/blog-admin/src/index.ts +5 -0
- package/examples/blog-admin/src/resources/authors.resource.ts +21 -0
- package/examples/blog-admin/src/resources/tags.resource.ts +20 -0
- package/examples/blog-admin/tsconfig.json +7 -0
- package/examples/blog-admin/vitest.config.ts +16 -0
- package/examples/crm-admin/README.md +17 -0
- package/examples/crm-admin/package.json +17 -0
- package/examples/crm-admin/prisma/models.fragment.prisma +50 -0
- package/examples/crm-admin/src/index.test.ts +9 -0
- package/examples/crm-admin/src/index.ts +7 -0
- package/examples/crm-admin/src/resources/activities.resource.ts +29 -0
- package/examples/crm-admin/src/resources/companies.resource.ts +21 -0
- package/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
- package/examples/crm-admin/src/resources/deals.resource.ts +30 -0
- package/examples/crm-admin/tsconfig.json +7 -0
- package/examples/crm-admin/vitest.config.ts +16 -0
- package/examples/ecommerce-admin/README.md +17 -0
- package/examples/ecommerce-admin/package.json +17 -0
- package/examples/ecommerce-admin/prisma/models.fragment.prisma +43 -0
- package/examples/ecommerce-admin/src/index.test.ts +8 -0
- package/examples/ecommerce-admin/src/index.ts +7 -0
- package/examples/ecommerce-admin/src/resources/customers.resource.ts +21 -0
- package/examples/ecommerce-admin/src/resources/order-items.resource.ts +22 -0
- package/examples/ecommerce-admin/src/resources/orders.resource.ts +27 -0
- package/examples/ecommerce-admin/src/resources/products.resource.ts +23 -0
- package/examples/ecommerce-admin/tsconfig.json +7 -0
- package/examples/ecommerce-admin/vitest.config.ts +16 -0
- package/examples/marketplace-admin/README.md +17 -0
- package/examples/marketplace-admin/package.json +17 -0
- package/examples/marketplace-admin/prisma/models.fragment.prisma +32 -0
- package/examples/marketplace-admin/src/index.test.ts +8 -0
- package/examples/marketplace-admin/src/index.ts +6 -0
- package/examples/marketplace-admin/src/resources/listings.resource.ts +29 -0
- package/examples/marketplace-admin/src/resources/payouts.resource.ts +28 -0
- package/examples/marketplace-admin/src/resources/sellers.resource.ts +28 -0
- package/examples/marketplace-admin/tsconfig.json +7 -0
- package/examples/marketplace-admin/vitest.config.ts +16 -0
- package/examples/support-admin/README.md +18 -0
- package/examples/support-admin/package.json +17 -0
- package/examples/support-admin/prisma/models.fragment.prisma +20 -0
- package/examples/support-admin/src/index.test.ts +8 -0
- package/examples/support-admin/src/index.ts +5 -0
- package/examples/support-admin/src/resources/ticket-messages.resource.ts +22 -0
- package/examples/support-admin/src/resources/tickets.resource.ts +35 -0
- package/examples/support-admin/tsconfig.json +7 -0
- package/examples/support-admin/vitest.config.ts +16 -0
- package/package.json +33 -0
- package/packages/auth/package.json +17 -0
- package/packages/auth/src/index.test.ts +10 -0
- package/packages/auth/src/index.ts +17 -0
- package/packages/auth/tsconfig.json +8 -0
- package/packages/brand/apps/admin/public/brand/apple-touch-icon.png +0 -0
- package/packages/brand/apps/admin/public/brand/favicon.svg +1 -0
- package/packages/brand/apps/admin/public/brand/og-image.png +0 -0
- package/packages/brand/apps/admin/public/brand/openadminjs-icon-new.png +0 -0
- package/packages/brand/apps/admin/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/packages/brand/apps/admin/public/brand/openadminjs-logo-new.png +0 -0
- package/packages/brand/apps/web/public/brand/apple-touch-icon.png +0 -0
- package/packages/brand/apps/web/public/brand/favicon.svg +1 -0
- package/packages/brand/apps/web/public/brand/og-image.png +0 -0
- package/packages/brand/apps/web/public/brand/openadminjs-icon-new.png +0 -0
- package/packages/brand/apps/web/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/packages/brand/apps/web/public/brand/openadminjs-logo-new.png +0 -0
- package/packages/brand/package.json +19 -0
- package/packages/brand/site/assets/brand/favicon.svg +1 -0
- package/packages/brand/site/assets/brand/og-image.svg +1 -0
- package/packages/brand/site/assets/brand/openadminjs-icon.svg +1 -0
- package/packages/brand/site/assets/brand/openadminjs-logo-dark.svg +1 -0
- package/packages/brand/site/assets/brand/openadminjs-logo-horizontal.svg +1 -0
- package/packages/brand/site/assets/brand/openadminjs-logo-monochrome.svg +1 -0
- package/packages/brand/site/assets/brand/openadminjs-logo.svg +1 -0
- package/packages/brand/src/generate-assets.mjs +182 -0
- package/packages/brand/src/index.test.ts +9 -0
- package/packages/brand/src/index.ts +7 -0
- package/packages/brand/tsconfig.json +7 -0
- package/packages/cli/package.json +44 -0
- package/packages/cli/src/create-project.ts +227 -0
- package/packages/cli/src/index.test.ts +8 -0
- package/packages/cli/src/index.ts +90 -0
- package/packages/cli/src/resource-slug.test.ts +10 -0
- package/packages/cli/src/resource-slug.ts +4 -0
- package/packages/cli/template/.env.example +4 -0
- package/packages/cli/template/README.md +13 -0
- package/packages/cli/template/apps/web/README.md +12 -0
- package/packages/cli/template/apps/web/app/globals.css +12 -0
- package/packages/cli/template/apps/web/app/layout.tsx +18 -0
- package/packages/cli/template/apps/web/app/page.tsx +27 -0
- package/packages/cli/template/apps/web/app/posts/[slug]/page.tsx +38 -0
- package/packages/cli/template/apps/web/app/posts/page.tsx +20 -0
- package/packages/cli/template/apps/web/app/robots.txt/route.ts +9 -0
- package/packages/cli/template/apps/web/app/sitemap.xml/route.ts +20 -0
- package/packages/cli/template/apps/web/components/public-fields.tsx +22 -0
- package/packages/cli/template/apps/web/lib/openadmin-client.ts +71 -0
- package/packages/cli/template/apps/web/lib/seo.ts +42 -0
- package/packages/cli/template/apps/web/next-env.d.ts +2 -0
- package/packages/cli/template/apps/web/next.config.mjs +5 -0
- package/packages/cli/template/apps/web/package.json +29 -0
- package/packages/cli/template/apps/web/postcss.config.mjs +6 -0
- package/packages/cli/template/apps/web/public/brand/apple-touch-icon.png +0 -0
- package/packages/cli/template/apps/web/public/brand/favicon.svg +1 -0
- package/packages/cli/template/apps/web/public/brand/og-image.png +0 -0
- package/packages/cli/template/apps/web/public/brand/openadminjs-icon-new.png +0 -0
- package/packages/cli/template/apps/web/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/packages/cli/template/apps/web/public/brand/openadminjs-logo-new.png +0 -0
- package/packages/cli/template/apps/web/tailwind.config.ts +21 -0
- package/packages/cli/template/apps/web/tsconfig.json +23 -0
- package/packages/cli/template/package.json +19 -0
- package/packages/cli/template/pnpm-workspace.yaml +3 -0
- package/packages/cli/tsconfig.json +10 -0
- package/packages/core/package.json +20 -0
- package/packages/core/src/index.js +1 -0
- package/packages/core/src/index.test.ts +27 -0
- package/packages/core/src/index.ts +61 -0
- package/packages/core/tsconfig.json +8 -0
- package/packages/create-openadminjs/package.json +25 -0
- package/packages/create-openadminjs/src/index.ts +70 -0
- package/packages/create-openadminjs/src/package-name.test.ts +13 -0
- package/packages/create-openadminjs/src/package-name.ts +8 -0
- package/packages/create-openadminjs/src/render-files.test.ts +26 -0
- package/packages/create-openadminjs/src/render-files.ts +21 -0
- package/packages/create-openadminjs/template/.env.example +4 -0
- package/packages/create-openadminjs/template/README.md +13 -0
- package/packages/create-openadminjs/template/apps/web/README.md +12 -0
- package/packages/create-openadminjs/template/apps/web/app/globals.css +12 -0
- package/packages/create-openadminjs/template/apps/web/app/layout.tsx +18 -0
- package/packages/create-openadminjs/template/apps/web/app/page.tsx +27 -0
- package/packages/create-openadminjs/template/apps/web/app/posts/[slug]/page.tsx +38 -0
- package/packages/create-openadminjs/template/apps/web/app/posts/page.tsx +20 -0
- package/packages/create-openadminjs/template/apps/web/app/robots.txt/route.ts +9 -0
- package/packages/create-openadminjs/template/apps/web/app/sitemap.xml/route.ts +20 -0
- package/packages/create-openadminjs/template/apps/web/components/public-fields.tsx +22 -0
- package/packages/create-openadminjs/template/apps/web/lib/openadmin-client.ts +71 -0
- package/packages/create-openadminjs/template/apps/web/lib/seo.ts +42 -0
- package/packages/create-openadminjs/template/apps/web/next-env.d.ts +2 -0
- package/packages/create-openadminjs/template/apps/web/next.config.mjs +5 -0
- package/packages/create-openadminjs/template/apps/web/package.json +29 -0
- package/packages/create-openadminjs/template/apps/web/postcss.config.mjs +6 -0
- package/packages/create-openadminjs/template/apps/web/public/brand/apple-touch-icon.png +0 -0
- package/packages/create-openadminjs/template/apps/web/public/brand/favicon.svg +1 -0
- package/packages/create-openadminjs/template/apps/web/public/brand/og-image.png +0 -0
- package/packages/create-openadminjs/template/apps/web/public/brand/openadminjs-icon-new.png +0 -0
- package/packages/create-openadminjs/template/apps/web/public/brand/openadminjs-logo-monochrome.png +0 -0
- package/packages/create-openadminjs/template/apps/web/public/brand/openadminjs-logo-new.png +0 -0
- package/packages/create-openadminjs/template/apps/web/tailwind.config.ts +21 -0
- package/packages/create-openadminjs/template/apps/web/tsconfig.json +23 -0
- package/packages/create-openadminjs/template/package.json +19 -0
- package/packages/create-openadminjs/template/pnpm-workspace.yaml +3 -0
- package/packages/create-openadminjs/tsconfig.json +10 -0
- package/packages/mail/package.json +18 -0
- package/packages/mail/src/index.test.ts +23 -0
- package/packages/mail/src/index.ts +246 -0
- package/packages/mail/tsconfig.json +5 -0
- package/packages/notifications/package.json +16 -0
- package/packages/notifications/src/index.test.ts +9 -0
- package/packages/notifications/src/index.ts +5 -0
- package/packages/notifications/tsconfig.json +5 -0
- package/packages/payments/package.json +15 -0
- package/packages/payments/src/index.ts +256 -0
- package/packages/payments/tsconfig.json +9 -0
- package/packages/permissions/package.json +17 -0
- package/packages/permissions/src/blueprints.js +57 -0
- package/packages/permissions/src/blueprints.test.ts +62 -0
- package/packages/permissions/src/blueprints.ts +89 -0
- package/packages/permissions/src/index.js +11 -0
- package/packages/permissions/src/index.test.ts +34 -0
- package/packages/permissions/src/index.ts +22 -0
- package/packages/permissions/tsconfig.json +8 -0
- package/packages/plugin-sdk/package.json +26 -0
- package/packages/plugin-sdk/src/hooks.ts +44 -0
- package/packages/plugin-sdk/src/index.ts +37 -0
- package/packages/plugin-sdk/src/sdk.test.ts +13 -0
- package/packages/plugin-sdk/tsconfig.json +8 -0
- package/packages/plugin-sdk/vitest.config.ts +5 -0
- package/packages/queue/package.json +16 -0
- package/packages/queue/src/index.test.ts +12 -0
- package/packages/queue/src/index.ts +6 -0
- package/packages/queue/tsconfig.json +5 -0
- package/packages/resource/package.json +17 -0
- package/packages/resource/src/index.js +177 -0
- package/packages/resource/src/index.test.ts +151 -0
- package/packages/resource/src/index.ts +344 -0
- package/packages/resource/tsconfig.json +8 -0
- package/packages/storage/package.json +16 -0
- package/packages/storage/src/index.test.ts +10 -0
- package/packages/storage/src/index.ts +23 -0
- package/packages/storage/tsconfig.json +5 -0
- package/pnpm-workspace.yaml +4 -0
- package/prisma/migrations/20260505151751_baseline_init_all_tables/migration.sql +371 -0
- package/prisma/migrations/migration_lock.toml +3 -0
- package/prisma/schema.prisma +291 -0
- package/prisma/seed.ts +210 -0
- package/scripts/check-static-site.mjs +17 -0
- package/scripts/e2e-smoke.mjs +17 -0
- package/scripts/make-executable.mjs +4 -0
- package/site/.nojekyll +0 -0
- package/site/assets/brand/apple-touch-icon.png +0 -0
- package/site/assets/brand/favicon.svg +1 -0
- package/site/assets/brand/og-image.png +0 -0
- package/site/assets/brand/openadminjs-icon-new.png +0 -0
- package/site/assets/brand/openadminjs-logo-monochrome.png +0 -0
- package/site/assets/brand/openadminjs-logo-new.png +0 -0
- package/site/assets/css/styles.css +1521 -0
- package/site/assets/js/main.js +193 -0
- package/site/assets/partners/arcbyte.svg +11 -0
- package/site/assets/partners/gridstack.svg +8 -0
- package/site/assets/partners/nebula.svg +12 -0
- package/site/assets/partners/orbitlab.svg +7 -0
- package/site/assets/partners/pulseforge.svg +11 -0
- package/site/assets/partners/vertex.svg +6 -0
- package/site/docs.html +1452 -0
- package/site/index.html +357 -0
- package/tsconfig.base.json +23 -0
|
@@ -0,0 +1,1238 @@
|
|
|
1
|
+
import { BadRequestException, ForbiddenException, Injectable } from "@nestjs/common";
|
|
2
|
+
import type { Prisma } from "@prisma/client";
|
|
3
|
+
import { PrismaService } from "../common/prisma.service";
|
|
4
|
+
import { resources } from "../resources/registry";
|
|
5
|
+
import { AdminResourceService } from "./admin-resource.service";
|
|
6
|
+
|
|
7
|
+
type UserContext = { id: string; email?: string; permissions: string[] };
|
|
8
|
+
|
|
9
|
+
type AiProviderConfig = {
|
|
10
|
+
id: string;
|
|
11
|
+
label: string;
|
|
12
|
+
kind: "openai" | "anthropic" | "gemini";
|
|
13
|
+
baseUrl?: string;
|
|
14
|
+
model: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
type ChatAttachment = {
|
|
18
|
+
name: string;
|
|
19
|
+
mimeType: string;
|
|
20
|
+
contentBase64: string;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
type ChatPayload = {
|
|
24
|
+
message: string;
|
|
25
|
+
pagePath?: string;
|
|
26
|
+
attachments?: ChatAttachment[];
|
|
27
|
+
conversationId?: string;
|
|
28
|
+
pendingAction?: Record<string, unknown>;
|
|
29
|
+
confirmAction?: boolean;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
type ChatResult = {
|
|
33
|
+
reply: string;
|
|
34
|
+
actionResult: unknown;
|
|
35
|
+
pendingAction: Record<string, unknown> | null;
|
|
36
|
+
requiresConfirmation: boolean;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
type CompensationRecord = {
|
|
40
|
+
label: string;
|
|
41
|
+
run: () => Promise<void>;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const SETTINGS_KEYS = {
|
|
45
|
+
providers: "ai.providers",
|
|
46
|
+
activeProvider: "ai.activeProvider",
|
|
47
|
+
tokens: "ai.tokens",
|
|
48
|
+
systemPrompt: "ai.systemPrompt"
|
|
49
|
+
} as const;
|
|
50
|
+
|
|
51
|
+
const DEFAULT_PROVIDERS: AiProviderConfig[] = [
|
|
52
|
+
{ id: "chatgpt", label: "ChatGPT", kind: "openai", baseUrl: "https://api.openai.com/v1", model: "gpt-4o-mini" },
|
|
53
|
+
{ id: "gemini", label: "Gemini", kind: "gemini", baseUrl: "https://generativelanguage.googleapis.com/v1beta", model: "gemini-1.5-flash" },
|
|
54
|
+
{ id: "claude", label: "Claude", kind: "anthropic", baseUrl: "https://api.anthropic.com/v1", model: "claude-3-5-sonnet-latest" },
|
|
55
|
+
{ id: "deepseek", label: "DeepSeek", kind: "openai", baseUrl: "https://api.deepseek.com/v1", model: "deepseek-chat" }
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
const DEFAULT_SYSTEM_PROMPT = [
|
|
59
|
+
"You are an AI consultant inside the OpenAdminJS admin panel.",
|
|
60
|
+
"Help users with current functionality, resource structure, and data analysis.",
|
|
61
|
+
"If the user requests a data operation, return JSON in this format:",
|
|
62
|
+
'{"reply":"...","action":{"type":"list|get|create|update|delete|analyze","resource":"posts","id":"...","payload":{},"query":{}}}',
|
|
63
|
+
"You can also create files using actions:",
|
|
64
|
+
'{"reply":"...","action":{"type":"export","resource":"orders","query":{},"format":"csv","filename":"orders.csv","columns":["id","status","total"]}}',
|
|
65
|
+
'{"reply":"...","action":{"type":"artifact","filename":"note.txt","mimeType":"text/plain","content":"...","encoding":"utf8"}}',
|
|
66
|
+
'{"reply":"...","action":{"type":"image","prompt":"Create a modern hero banner with abstract gradients","filename":"hero.png","size":"1024x1024"}}',
|
|
67
|
+
'{"reply":"...","action":{"type":"workflow","steps":[{"type":"image","prompt":"Create product hero","filename":"hero.png"},{"type":"update","resource":"posts","id":"...","payload":{"coverImage":"{{latest_image}}"}}]}}',
|
|
68
|
+
'Workflow supports transactionMode: "best_effort" (default) or "rollback_on_error".',
|
|
69
|
+
"To attach created artifact into resource payload, use value format: ai-artifact:<artifactId>.",
|
|
70
|
+
"Autofill shortcuts are supported in create/update payload:",
|
|
71
|
+
'- "{{latest_artifact}}" -> latest artifact URL',
|
|
72
|
+
'- "{{latest_image}}" -> latest image artifact URL',
|
|
73
|
+
'- For image-like fields (image, coverImage, avatar, thumbnail, banner, icon), values "auto", "latest", true also map to latest image artifact.',
|
|
74
|
+
"If no operation is needed, return only the reply field.",
|
|
75
|
+
"For action, use only existing resources and safe queries."
|
|
76
|
+
].join("\n");
|
|
77
|
+
|
|
78
|
+
@Injectable()
|
|
79
|
+
export class AdminAiService {
|
|
80
|
+
constructor(
|
|
81
|
+
private readonly prisma: PrismaService,
|
|
82
|
+
private readonly resourcesService: AdminResourceService
|
|
83
|
+
) {}
|
|
84
|
+
|
|
85
|
+
async getConfig() {
|
|
86
|
+
const providers = await this.readJsonSetting<AiProviderConfig[]>(SETTINGS_KEYS.providers, DEFAULT_PROVIDERS);
|
|
87
|
+
const activeProvider = await this.readStringSetting(SETTINGS_KEYS.activeProvider, providers[0]?.id ?? "chatgpt");
|
|
88
|
+
const tokens = await this.readJsonSetting<Record<string, string>>(SETTINGS_KEYS.tokens, {});
|
|
89
|
+
return {
|
|
90
|
+
providers,
|
|
91
|
+
activeProvider,
|
|
92
|
+
tokenConfigured: Object.fromEntries(providers.map((provider) => [provider.id, Boolean(tokens[provider.id])]))
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async updateConfig(input: {
|
|
97
|
+
providers?: AiProviderConfig[];
|
|
98
|
+
activeProvider?: string;
|
|
99
|
+
tokenProviderId?: string;
|
|
100
|
+
token?: string;
|
|
101
|
+
systemPrompt?: string;
|
|
102
|
+
}) {
|
|
103
|
+
if (input.providers) {
|
|
104
|
+
const normalized = input.providers
|
|
105
|
+
.map((provider) => ({
|
|
106
|
+
...provider,
|
|
107
|
+
id: String(provider.id ?? "").trim().toLowerCase(),
|
|
108
|
+
label: String(provider.label ?? "").trim(),
|
|
109
|
+
model: String(provider.model ?? "").trim(),
|
|
110
|
+
baseUrl: provider.baseUrl ? String(provider.baseUrl).trim() : undefined
|
|
111
|
+
}))
|
|
112
|
+
.filter((provider) => provider.id && provider.label && provider.model);
|
|
113
|
+
if (normalized.length === 0) {
|
|
114
|
+
throw new BadRequestException({ message: "At least one valid provider is required", code: "AI_PROVIDERS_REQUIRED" });
|
|
115
|
+
}
|
|
116
|
+
await this.upsertSetting(SETTINGS_KEYS.providers, "json", normalized);
|
|
117
|
+
}
|
|
118
|
+
if (typeof input.activeProvider === "string" && input.activeProvider.trim().length > 0) {
|
|
119
|
+
await this.upsertSetting(SETTINGS_KEYS.activeProvider, "string", input.activeProvider.trim());
|
|
120
|
+
}
|
|
121
|
+
if (typeof input.systemPrompt === "string") {
|
|
122
|
+
await this.upsertSetting(SETTINGS_KEYS.systemPrompt, "string", input.systemPrompt.trim());
|
|
123
|
+
}
|
|
124
|
+
if (typeof input.tokenProviderId === "string") {
|
|
125
|
+
const providerId = input.tokenProviderId.trim().toLowerCase();
|
|
126
|
+
const tokenValue = (input.token ?? "").trim();
|
|
127
|
+
const tokens = await this.readJsonSetting<Record<string, string>>(SETTINGS_KEYS.tokens, {});
|
|
128
|
+
if (tokenValue.length === 0) {
|
|
129
|
+
delete tokens[providerId];
|
|
130
|
+
} else {
|
|
131
|
+
tokens[providerId] = tokenValue;
|
|
132
|
+
}
|
|
133
|
+
await this.upsertSetting(SETTINGS_KEYS.tokens, "json", tokens);
|
|
134
|
+
}
|
|
135
|
+
return this.getConfig();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async chat(user: UserContext, payload: ChatPayload) {
|
|
139
|
+
const conversationId = await this.resolveConversation(user.id, payload.conversationId, payload.message);
|
|
140
|
+
await this.createMessage(conversationId, "user", payload.message);
|
|
141
|
+
const result = await this.runChatCore(user, payload);
|
|
142
|
+
await this.createMessage(conversationId, "assistant", result.reply, {
|
|
143
|
+
actionResult: result.actionResult,
|
|
144
|
+
requiresConfirmation: result.requiresConfirmation ?? false,
|
|
145
|
+
pendingAction: result.pendingAction ?? null
|
|
146
|
+
});
|
|
147
|
+
return { ...result, conversationId };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async *chatStream(user: UserContext, payload: ChatPayload) {
|
|
151
|
+
const conversationId = await this.resolveConversation(user.id, payload.conversationId, payload.message);
|
|
152
|
+
await this.createMessage(conversationId, "user", payload.message);
|
|
153
|
+
this.ensureChatPermission(user);
|
|
154
|
+
const prepared = await this.prepareCompletion(user, payload);
|
|
155
|
+
let completion = "";
|
|
156
|
+
if (prepared.provider.kind === "openai" || prepared.provider.kind === "anthropic") {
|
|
157
|
+
for await (const delta of this.requestCompletionStream(prepared.provider, prepared.token, prepared.input)) {
|
|
158
|
+
completion += delta;
|
|
159
|
+
yield { type: "delta", delta, conversationId };
|
|
160
|
+
}
|
|
161
|
+
} else {
|
|
162
|
+
completion = await this.requestCompletion(prepared.provider, prepared.token, prepared.input);
|
|
163
|
+
if (completion) yield { type: "delta", delta: completion, conversationId };
|
|
164
|
+
}
|
|
165
|
+
const result = await this.finalizeCompletion(user, payload, completion, prepared);
|
|
166
|
+
await this.createMessage(conversationId, "assistant", result.reply, {
|
|
167
|
+
actionResult: result.actionResult,
|
|
168
|
+
requiresConfirmation: result.requiresConfirmation ?? false,
|
|
169
|
+
pendingAction: result.pendingAction ?? null
|
|
170
|
+
});
|
|
171
|
+
yield {
|
|
172
|
+
type: "done",
|
|
173
|
+
conversationId,
|
|
174
|
+
reply: result.reply,
|
|
175
|
+
actionResult: result.actionResult,
|
|
176
|
+
pendingAction: result.pendingAction ?? null,
|
|
177
|
+
requiresConfirmation: result.requiresConfirmation ?? false
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async listConversations(user: UserContext, search?: string, page = 1, limit = 20) {
|
|
182
|
+
this.ensureChatPermission(user);
|
|
183
|
+
const q = String(search ?? "").trim();
|
|
184
|
+
const safePage = Number.isFinite(page) && page > 0 ? Math.floor(page) : 1;
|
|
185
|
+
const safeLimit = Math.min(50, Math.max(1, Number.isFinite(limit) ? Math.floor(limit) : 20));
|
|
186
|
+
const where = {
|
|
187
|
+
userId: user.id,
|
|
188
|
+
...(q
|
|
189
|
+
? {
|
|
190
|
+
OR: [
|
|
191
|
+
{ title: { contains: q, mode: "insensitive" as const } },
|
|
192
|
+
{
|
|
193
|
+
messages: {
|
|
194
|
+
some: {
|
|
195
|
+
content: { contains: q, mode: "insensitive" as const }
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
]
|
|
200
|
+
}
|
|
201
|
+
: {})
|
|
202
|
+
};
|
|
203
|
+
const [items, total] = await Promise.all([
|
|
204
|
+
this.prisma.aiConversation.findMany({
|
|
205
|
+
where,
|
|
206
|
+
orderBy: { updatedAt: "desc" },
|
|
207
|
+
include: {
|
|
208
|
+
messages: {
|
|
209
|
+
orderBy: { createdAt: "desc" },
|
|
210
|
+
take: 1
|
|
211
|
+
}
|
|
212
|
+
},
|
|
213
|
+
skip: (safePage - 1) * safeLimit,
|
|
214
|
+
take: safeLimit
|
|
215
|
+
}),
|
|
216
|
+
this.prisma.aiConversation.count({ where })
|
|
217
|
+
]);
|
|
218
|
+
return {
|
|
219
|
+
data: items,
|
|
220
|
+
meta: {
|
|
221
|
+
page: safePage,
|
|
222
|
+
limit: safeLimit,
|
|
223
|
+
total,
|
|
224
|
+
pages: Math.max(1, Math.ceil(total / safeLimit))
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async getConversation(user: UserContext, conversationId: string) {
|
|
230
|
+
this.ensureChatPermission(user);
|
|
231
|
+
const conversation = await this.prisma.aiConversation.findFirst({
|
|
232
|
+
where: { id: conversationId, userId: user.id },
|
|
233
|
+
include: { messages: { orderBy: { createdAt: "asc" } } }
|
|
234
|
+
});
|
|
235
|
+
if (!conversation) {
|
|
236
|
+
throw new BadRequestException({ message: "Conversation not found", code: "AI_CONVERSATION_NOT_FOUND" });
|
|
237
|
+
}
|
|
238
|
+
return conversation;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async renameConversation(user: UserContext, conversationId: string, title: string) {
|
|
242
|
+
this.ensureChatPermission(user);
|
|
243
|
+
const trimmed = title.trim();
|
|
244
|
+
if (!trimmed) {
|
|
245
|
+
throw new BadRequestException({ message: "Title is required", code: "AI_CONVERSATION_TITLE_REQUIRED" });
|
|
246
|
+
}
|
|
247
|
+
const updated = await this.prisma.aiConversation.updateMany({
|
|
248
|
+
where: { id: conversationId, userId: user.id },
|
|
249
|
+
data: { title: trimmed.slice(0, 120) }
|
|
250
|
+
});
|
|
251
|
+
if (updated.count === 0) {
|
|
252
|
+
throw new BadRequestException({ message: "Conversation not found", code: "AI_CONVERSATION_NOT_FOUND" });
|
|
253
|
+
}
|
|
254
|
+
return { ok: true };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async deleteConversation(user: UserContext, conversationId: string) {
|
|
258
|
+
this.ensureChatPermission(user);
|
|
259
|
+
const deleted = await this.prisma.aiConversation.deleteMany({
|
|
260
|
+
where: { id: conversationId, userId: user.id }
|
|
261
|
+
});
|
|
262
|
+
if (deleted.count === 0) {
|
|
263
|
+
throw new BadRequestException({ message: "Conversation not found", code: "AI_CONVERSATION_NOT_FOUND" });
|
|
264
|
+
}
|
|
265
|
+
return { ok: true };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
private ensureChatPermission(user: UserContext) {
|
|
269
|
+
if (!this.hasPermission(user, "ai.chat")) {
|
|
270
|
+
throw new ForbiddenException({ message: "Missing permission", code: "PERMISSION_DENIED" });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private async runChatCore(
|
|
275
|
+
user: UserContext,
|
|
276
|
+
payload: ChatPayload
|
|
277
|
+
): Promise<ChatResult> {
|
|
278
|
+
this.ensureChatPermission(user);
|
|
279
|
+
const prepared = await this.prepareCompletion(user, payload);
|
|
280
|
+
const completion = await this.requestCompletion(prepared.provider, prepared.token, prepared.input);
|
|
281
|
+
return this.finalizeCompletion(user, payload, completion, prepared);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private async finalizeCompletion(
|
|
285
|
+
user: UserContext,
|
|
286
|
+
payload: ChatPayload,
|
|
287
|
+
completion: string,
|
|
288
|
+
aiContext?: {
|
|
289
|
+
provider: AiProviderConfig;
|
|
290
|
+
token: string;
|
|
291
|
+
input: { message: string; context: unknown; systemPrompt: string; attachments: ChatAttachment[] };
|
|
292
|
+
}
|
|
293
|
+
): Promise<ChatResult> {
|
|
294
|
+
const parsed = this.tryParseStructuredOutput(completion);
|
|
295
|
+
if (!parsed?.action && payload.pendingAction && payload.confirmAction) {
|
|
296
|
+
const actionResult = await this.executeAction(user, payload.pendingAction, aiContext);
|
|
297
|
+
const reply = parsed?.reply ? `${parsed.reply}\n\nAction completed.` : "Action completed.";
|
|
298
|
+
return { reply, actionResult, pendingAction: null, requiresConfirmation: false };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (!parsed?.action) {
|
|
302
|
+
return { reply: parsed?.reply ?? completion, actionResult: null, pendingAction: null, requiresConfirmation: false };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (String(parsed.action.type ?? "") === "delete" && !payload.confirmAction) {
|
|
306
|
+
return {
|
|
307
|
+
reply: `${parsed.reply ?? "Delete action detected."}\n\nPlease confirm this destructive action.`,
|
|
308
|
+
actionResult: null,
|
|
309
|
+
pendingAction: parsed.action,
|
|
310
|
+
requiresConfirmation: true
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const actionResult = await this.executeAction(user, parsed.action, aiContext);
|
|
315
|
+
const finalReply = parsed.reply
|
|
316
|
+
? `${parsed.reply}\n\nResult:\n${JSON.stringify(actionResult, null, 2)}`
|
|
317
|
+
: `Done.\n\n${JSON.stringify(actionResult, null, 2)}`;
|
|
318
|
+
return { reply: finalReply, actionResult, pendingAction: null, requiresConfirmation: false };
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
private async prepareCompletion(
|
|
322
|
+
user: UserContext,
|
|
323
|
+
payload: ChatPayload
|
|
324
|
+
): Promise<{
|
|
325
|
+
provider: AiProviderConfig;
|
|
326
|
+
token: string;
|
|
327
|
+
input: { message: string; context: unknown; systemPrompt: string; attachments: ChatAttachment[] };
|
|
328
|
+
}> {
|
|
329
|
+
const message = String(payload.message ?? "").trim();
|
|
330
|
+
if (!message) {
|
|
331
|
+
throw new BadRequestException({ message: "Message is required", code: "AI_MESSAGE_REQUIRED" });
|
|
332
|
+
}
|
|
333
|
+
const config = await this.getConfig();
|
|
334
|
+
const providers = await this.readJsonSetting<AiProviderConfig[]>(SETTINGS_KEYS.providers, DEFAULT_PROVIDERS);
|
|
335
|
+
const active = providers.find((provider) => provider.id === config.activeProvider) ?? providers[0];
|
|
336
|
+
if (!active) {
|
|
337
|
+
throw new BadRequestException({ message: "No AI providers configured", code: "AI_PROVIDER_MISSING" });
|
|
338
|
+
}
|
|
339
|
+
const tokens = await this.readJsonSetting<Record<string, string>>(SETTINGS_KEYS.tokens, {});
|
|
340
|
+
const providerToken = tokens[active.id];
|
|
341
|
+
if (!providerToken) {
|
|
342
|
+
throw new BadRequestException({
|
|
343
|
+
message: `Token for provider "${active.label}" is not configured`,
|
|
344
|
+
code: "AI_TOKEN_MISSING"
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
const systemPrompt = await this.readStringSetting(SETTINGS_KEYS.systemPrompt, DEFAULT_SYSTEM_PROMPT);
|
|
348
|
+
const context = this.buildAssistantContext(user, payload.pagePath);
|
|
349
|
+
return {
|
|
350
|
+
provider: active,
|
|
351
|
+
token: providerToken,
|
|
352
|
+
input: {
|
|
353
|
+
message,
|
|
354
|
+
context,
|
|
355
|
+
systemPrompt,
|
|
356
|
+
attachments: payload.attachments ?? []
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
private async executeAction(
|
|
362
|
+
user: UserContext,
|
|
363
|
+
action: Record<string, unknown>,
|
|
364
|
+
aiContext?: { provider: AiProviderConfig; token: string }
|
|
365
|
+
) {
|
|
366
|
+
const type = String(action.type ?? "");
|
|
367
|
+
if (type === "workflow") {
|
|
368
|
+
return this.executeWorkflow(user, action, aiContext);
|
|
369
|
+
}
|
|
370
|
+
const resource = String(action.resource ?? "");
|
|
371
|
+
const id = action.id ? String(action.id) : undefined;
|
|
372
|
+
const payload = (action.payload ?? {}) as Record<string, unknown>;
|
|
373
|
+
const query = (action.query ?? {}) as Record<string, unknown>;
|
|
374
|
+
if (!resource) {
|
|
375
|
+
throw new BadRequestException({ message: "Action resource is required", code: "AI_ACTION_RESOURCE_REQUIRED" });
|
|
376
|
+
}
|
|
377
|
+
if (!resources.some((item) => item.name === resource)) {
|
|
378
|
+
throw new BadRequestException({ message: `Unknown resource "${resource}"`, code: "AI_ACTION_RESOURCE_UNKNOWN" });
|
|
379
|
+
}
|
|
380
|
+
switch (type) {
|
|
381
|
+
case "list":
|
|
382
|
+
return this.resourcesService.list(resource, { limit: 20, ...query }, user);
|
|
383
|
+
case "get":
|
|
384
|
+
if (!id) throw new BadRequestException({ message: "Action id is required", code: "AI_ACTION_ID_REQUIRED" });
|
|
385
|
+
return this.resourcesService.get(resource, id, user);
|
|
386
|
+
case "create":
|
|
387
|
+
return this.resourcesService.create(
|
|
388
|
+
resource,
|
|
389
|
+
(await this.resolveArtifactRefs(user.id, payload, resource)) as Record<string, unknown>,
|
|
390
|
+
user
|
|
391
|
+
);
|
|
392
|
+
case "update":
|
|
393
|
+
if (!id) throw new BadRequestException({ message: "Action id is required", code: "AI_ACTION_ID_REQUIRED" });
|
|
394
|
+
return this.resourcesService.update(
|
|
395
|
+
resource,
|
|
396
|
+
id,
|
|
397
|
+
(await this.resolveArtifactRefs(user.id, payload, resource)) as Record<string, unknown>,
|
|
398
|
+
user
|
|
399
|
+
);
|
|
400
|
+
case "delete":
|
|
401
|
+
if (!id) throw new BadRequestException({ message: "Action id is required", code: "AI_ACTION_ID_REQUIRED" });
|
|
402
|
+
return this.resourcesService.delete(resource, id, user);
|
|
403
|
+
case "analyze": {
|
|
404
|
+
const listing = await this.resourcesService.list(resource, { limit: 100, ...query }, user) as { data: Record<string, unknown>[]; meta: unknown };
|
|
405
|
+
const data = listing.data ?? [];
|
|
406
|
+
return {
|
|
407
|
+
count: data.length,
|
|
408
|
+
keys: [...new Set(data.flatMap((row) => Object.keys(row))).values()],
|
|
409
|
+
sample: data.slice(0, 10)
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
case "export": {
|
|
413
|
+
const listing = await this.resourcesService.list(resource, { limit: 1000, ...query }, user) as { data: Record<string, unknown>[]; meta: unknown };
|
|
414
|
+
const format = String(action.format ?? "csv").toLowerCase();
|
|
415
|
+
const filename = String(action.filename ?? `${resource}-export.${format === "json" ? "json" : "csv"}`);
|
|
416
|
+
if (format === "json") {
|
|
417
|
+
const content = JSON.stringify(listing.data ?? [], null, 2);
|
|
418
|
+
return this.createArtifact(user.id, content, {
|
|
419
|
+
conversationId: undefined,
|
|
420
|
+
filename,
|
|
421
|
+
mimeType: "application/json",
|
|
422
|
+
encoding: "utf8",
|
|
423
|
+
meta: { type: "export", format, resource, query }
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
const columns = Array.isArray(action.columns) ? action.columns.map((item) => String(item)) : undefined;
|
|
427
|
+
const csv = this.toCsv(listing.data ?? [], columns);
|
|
428
|
+
return this.createArtifact(user.id, csv, {
|
|
429
|
+
conversationId: undefined,
|
|
430
|
+
filename,
|
|
431
|
+
mimeType: "text/csv",
|
|
432
|
+
encoding: "utf8",
|
|
433
|
+
meta: { type: "export", format: "csv", resource, query, columns: columns ?? null }
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
case "artifact": {
|
|
437
|
+
const filename = String(action.filename ?? "artifact.txt");
|
|
438
|
+
const mimeType = String(action.mimeType ?? "text/plain");
|
|
439
|
+
const encoding = String(action.encoding ?? "utf8").toLowerCase() === "base64" ? "base64" : "utf8";
|
|
440
|
+
const content = String(action.content ?? "");
|
|
441
|
+
return this.createArtifact(user.id, content, {
|
|
442
|
+
conversationId: undefined,
|
|
443
|
+
filename,
|
|
444
|
+
mimeType,
|
|
445
|
+
encoding,
|
|
446
|
+
meta: { type: "artifact", resource: null }
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
case "image": {
|
|
450
|
+
if (!aiContext) {
|
|
451
|
+
throw new BadRequestException({ message: "AI context is required for image generation", code: "AI_IMAGE_CONTEXT_REQUIRED" });
|
|
452
|
+
}
|
|
453
|
+
return this.createImageArtifact(user.id, action, aiContext.provider, aiContext.token);
|
|
454
|
+
}
|
|
455
|
+
default:
|
|
456
|
+
throw new BadRequestException({ message: `Unsupported action type "${type}"`, code: "AI_ACTION_UNSUPPORTED" });
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
private async executeWorkflow(
|
|
461
|
+
user: UserContext,
|
|
462
|
+
action: Record<string, unknown>,
|
|
463
|
+
aiContext?: { provider: AiProviderConfig; token: string }
|
|
464
|
+
) {
|
|
465
|
+
const transactionModeRaw = String(action.transactionMode ?? "best_effort").toLowerCase();
|
|
466
|
+
const transactionMode = transactionModeRaw === "rollback_on_error" ? "rollback_on_error" : "best_effort";
|
|
467
|
+
const stepsRaw = action.steps;
|
|
468
|
+
if (!Array.isArray(stepsRaw) || stepsRaw.length === 0) {
|
|
469
|
+
throw new BadRequestException({
|
|
470
|
+
message: "Workflow must include at least one step",
|
|
471
|
+
code: "AI_WORKFLOW_STEPS_REQUIRED"
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
if (stepsRaw.length > 8) {
|
|
475
|
+
throw new BadRequestException({
|
|
476
|
+
message: "Workflow step limit is 8",
|
|
477
|
+
code: "AI_WORKFLOW_STEPS_LIMIT"
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
const results: Array<Record<string, unknown>> = [];
|
|
481
|
+
const compensations: CompensationRecord[] = [];
|
|
482
|
+
for (let index = 0; index < stepsRaw.length; index += 1) {
|
|
483
|
+
const raw = stepsRaw[index];
|
|
484
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
485
|
+
throw new BadRequestException({
|
|
486
|
+
message: `Workflow step ${index + 1} is invalid`,
|
|
487
|
+
code: "AI_WORKFLOW_STEP_INVALID"
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
const step = raw as Record<string, unknown>;
|
|
491
|
+
const stepType = String(step.type ?? "");
|
|
492
|
+
if (stepType === "workflow") {
|
|
493
|
+
throw new BadRequestException({
|
|
494
|
+
message: "Nested workflow is not supported",
|
|
495
|
+
code: "AI_WORKFLOW_NESTED_UNSUPPORTED"
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
try {
|
|
499
|
+
const resolvedStep = (await this.resolveArtifactRefs(user.id, step)) as Record<string, unknown>;
|
|
500
|
+
const result = await this.executeAction(user, resolvedStep, aiContext);
|
|
501
|
+
const compensation = this.buildCompensation(user, resolvedStep, result);
|
|
502
|
+
if (compensation) compensations.push(compensation);
|
|
503
|
+
results.push({
|
|
504
|
+
step: index + 1,
|
|
505
|
+
type: stepType,
|
|
506
|
+
resource: String(resolvedStep.resource ?? ""),
|
|
507
|
+
targetId:
|
|
508
|
+
typeof (result as Record<string, unknown>)?.id === "string"
|
|
509
|
+
? String((result as Record<string, unknown>).id)
|
|
510
|
+
: typeof resolvedStep.id === "string"
|
|
511
|
+
? String(resolvedStep.id)
|
|
512
|
+
: "",
|
|
513
|
+
result: result as Record<string, unknown>
|
|
514
|
+
});
|
|
515
|
+
} catch (error) {
|
|
516
|
+
const known = error as { response?: unknown };
|
|
517
|
+
const response =
|
|
518
|
+
known && typeof known === "object" && "response" in known
|
|
519
|
+
? (known.response as { message?: string; details?: unknown } | undefined)
|
|
520
|
+
: undefined;
|
|
521
|
+
const rolledBack: string[] = [];
|
|
522
|
+
const rollbackFailures: Array<{ label: string; reason: string }> = [];
|
|
523
|
+
if (transactionMode === "rollback_on_error" && compensations.length > 0) {
|
|
524
|
+
for (let rollbackIndex = compensations.length - 1; rollbackIndex >= 0; rollbackIndex -= 1) {
|
|
525
|
+
try {
|
|
526
|
+
const compensate = compensations[rollbackIndex];
|
|
527
|
+
if (!compensate) continue;
|
|
528
|
+
await compensate.run();
|
|
529
|
+
rolledBack.push(compensate.label);
|
|
530
|
+
} catch (rollbackError) {
|
|
531
|
+
rollbackFailures.push({
|
|
532
|
+
label: compensations[rollbackIndex]?.label ?? `step-${rollbackIndex + 1}`,
|
|
533
|
+
reason: rollbackError instanceof Error ? rollbackError.message : "rollback failed"
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
const origin =
|
|
539
|
+
(response && typeof response === "object" && typeof response.message === "string"
|
|
540
|
+
? response.message
|
|
541
|
+
: null) ??
|
|
542
|
+
(error instanceof Error ? error.message : "workflow step failed");
|
|
543
|
+
throw new BadRequestException({
|
|
544
|
+
message: origin,
|
|
545
|
+
code: "AI_WORKFLOW_FAILED",
|
|
546
|
+
details: {
|
|
547
|
+
transactionMode,
|
|
548
|
+
failedStep: index + 1,
|
|
549
|
+
failedStepType: stepType,
|
|
550
|
+
completedSteps: results.length,
|
|
551
|
+
partialResults: results,
|
|
552
|
+
...(response && typeof response === "object" && response.details ? { cause: response.details } : {}),
|
|
553
|
+
rolledBack,
|
|
554
|
+
rollbackFailures
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
return {
|
|
560
|
+
ok: true,
|
|
561
|
+
transactionMode,
|
|
562
|
+
stepsExecuted: results.length,
|
|
563
|
+
results
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
private buildCompensation(
|
|
568
|
+
user: UserContext,
|
|
569
|
+
step: Record<string, unknown>,
|
|
570
|
+
result: unknown
|
|
571
|
+
): CompensationRecord | null {
|
|
572
|
+
const type = String(step.type ?? "");
|
|
573
|
+
if ((type === "artifact" || type === "image") && result && typeof result === "object") {
|
|
574
|
+
const artifactId = String((result as Record<string, unknown>).artifactId ?? "");
|
|
575
|
+
if (!artifactId) return null;
|
|
576
|
+
return {
|
|
577
|
+
label: `artifact:${artifactId}`,
|
|
578
|
+
run: async () => {
|
|
579
|
+
await this.prisma.aiArtifact.deleteMany({
|
|
580
|
+
where: { id: artifactId, userId: user.id }
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
if (type === "create" && result && typeof result === "object") {
|
|
586
|
+
const resource = String(step.resource ?? "");
|
|
587
|
+
const createdId = String((result as Record<string, unknown>).id ?? "");
|
|
588
|
+
if (!resource || !createdId) return null;
|
|
589
|
+
return {
|
|
590
|
+
label: `${resource}:${createdId}`,
|
|
591
|
+
run: async () => {
|
|
592
|
+
try {
|
|
593
|
+
await this.resourcesService.delete(resource, createdId, user);
|
|
594
|
+
} catch {
|
|
595
|
+
// resource might be already deleted or protected
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
private buildAssistantContext(user: UserContext, pagePath?: string) {
|
|
604
|
+
const readableResources = resources
|
|
605
|
+
.filter((resource) => this.hasPermission(user, resource.permissions.read))
|
|
606
|
+
.map((resource) => ({
|
|
607
|
+
name: resource.name,
|
|
608
|
+
label: resource.label,
|
|
609
|
+
fields: Object.entries(resource.fields).map(([name, field]) => ({
|
|
610
|
+
name,
|
|
611
|
+
type: field.type,
|
|
612
|
+
label: field.label ?? name,
|
|
613
|
+
searchable: Boolean(field.searchable),
|
|
614
|
+
filterable: Boolean(field.filterable)
|
|
615
|
+
})),
|
|
616
|
+
permissions: resource.permissions
|
|
617
|
+
}));
|
|
618
|
+
return {
|
|
619
|
+
pagePath: pagePath ?? "",
|
|
620
|
+
user: { id: user.id, email: user.email ?? "", permissions: user.permissions },
|
|
621
|
+
resources: readableResources
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
private async requestCompletion(
|
|
626
|
+
provider: AiProviderConfig,
|
|
627
|
+
token: string,
|
|
628
|
+
input: { message: string; context: unknown; systemPrompt: string; attachments: ChatAttachment[] }
|
|
629
|
+
): Promise<string> {
|
|
630
|
+
if (provider.kind === "anthropic") {
|
|
631
|
+
return this.callAnthropic(provider, token, input);
|
|
632
|
+
}
|
|
633
|
+
if (provider.kind === "gemini") {
|
|
634
|
+
return this.callGemini(provider, token, input);
|
|
635
|
+
}
|
|
636
|
+
return this.callOpenAiCompatible(provider, token, input);
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
private async *requestCompletionStream(
|
|
640
|
+
provider: AiProviderConfig,
|
|
641
|
+
token: string,
|
|
642
|
+
input: { message: string; context: unknown; systemPrompt: string; attachments: ChatAttachment[] }
|
|
643
|
+
): AsyncGenerator<string> {
|
|
644
|
+
if (provider.kind === "anthropic") {
|
|
645
|
+
yield* this.callAnthropicStream(provider, token, input);
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
if (provider.kind === "gemini") {
|
|
649
|
+
yield* this.callGeminiStream(provider, token, input);
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
yield* this.callOpenAiCompatibleStream(provider, token, input);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
private async callOpenAiCompatible(
|
|
656
|
+
provider: AiProviderConfig,
|
|
657
|
+
token: string,
|
|
658
|
+
input: { message: string; context: unknown; systemPrompt: string; attachments: ChatAttachment[] }
|
|
659
|
+
) {
|
|
660
|
+
const imageParts = input.attachments
|
|
661
|
+
.filter((file) => file.mimeType.startsWith("image/"))
|
|
662
|
+
.map((file) => ({
|
|
663
|
+
type: "image_url",
|
|
664
|
+
image_url: { url: `data:${file.mimeType};base64,${file.contentBase64}` }
|
|
665
|
+
}));
|
|
666
|
+
const fileDigest = input.attachments
|
|
667
|
+
.filter((file) => !file.mimeType.startsWith("image/"))
|
|
668
|
+
.map((file) => `${file.name} (${file.mimeType}, ${Math.round(file.contentBase64.length / 4)} bytes approx)`)
|
|
669
|
+
.join("\n");
|
|
670
|
+
const userText = [
|
|
671
|
+
input.message,
|
|
672
|
+
fileDigest ? `\nFiles:\n${fileDigest}` : "",
|
|
673
|
+
`\nContext:\n${JSON.stringify(input.context)}`
|
|
674
|
+
].join("");
|
|
675
|
+
const response = await fetch(`${provider.baseUrl ?? "https://api.openai.com/v1"}/chat/completions`, {
|
|
676
|
+
method: "POST",
|
|
677
|
+
headers: {
|
|
678
|
+
authorization: `Bearer ${token}`,
|
|
679
|
+
"content-type": "application/json"
|
|
680
|
+
},
|
|
681
|
+
body: JSON.stringify({
|
|
682
|
+
model: provider.model,
|
|
683
|
+
temperature: 0.2,
|
|
684
|
+
messages: [
|
|
685
|
+
{ role: "system", content: input.systemPrompt },
|
|
686
|
+
{
|
|
687
|
+
role: "user",
|
|
688
|
+
content: [{ type: "text", text: userText }, ...imageParts]
|
|
689
|
+
}
|
|
690
|
+
]
|
|
691
|
+
})
|
|
692
|
+
});
|
|
693
|
+
const data = (await response.json().catch(() => ({}))) as {
|
|
694
|
+
error?: { message?: string };
|
|
695
|
+
choices?: Array<{ message?: { content?: string } }>;
|
|
696
|
+
};
|
|
697
|
+
if (!response.ok) {
|
|
698
|
+
throw new BadRequestException({
|
|
699
|
+
message: data.error?.message ?? "AI provider request failed",
|
|
700
|
+
code: "AI_PROVIDER_REQUEST_FAILED"
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
return data.choices?.[0]?.message?.content?.trim() ?? "Empty response from AI.";
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
private async *callOpenAiCompatibleStream(
|
|
707
|
+
provider: AiProviderConfig,
|
|
708
|
+
token: string,
|
|
709
|
+
input: { message: string; context: unknown; systemPrompt: string; attachments: ChatAttachment[] }
|
|
710
|
+
): AsyncGenerator<string> {
|
|
711
|
+
const imageParts = input.attachments
|
|
712
|
+
.filter((file) => file.mimeType.startsWith("image/"))
|
|
713
|
+
.map((file) => ({
|
|
714
|
+
type: "image_url",
|
|
715
|
+
image_url: { url: `data:${file.mimeType};base64,${file.contentBase64}` }
|
|
716
|
+
}));
|
|
717
|
+
const fileDigest = input.attachments
|
|
718
|
+
.filter((file) => !file.mimeType.startsWith("image/"))
|
|
719
|
+
.map((file) => `${file.name} (${file.mimeType}, ${Math.round(file.contentBase64.length / 4)} bytes approx)`)
|
|
720
|
+
.join("\n");
|
|
721
|
+
const userText = [
|
|
722
|
+
input.message,
|
|
723
|
+
fileDigest ? `\nFiles:\n${fileDigest}` : "",
|
|
724
|
+
`\nContext:\n${JSON.stringify(input.context)}`
|
|
725
|
+
].join("");
|
|
726
|
+
const response = await fetch(`${provider.baseUrl ?? "https://api.openai.com/v1"}/chat/completions`, {
|
|
727
|
+
method: "POST",
|
|
728
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
|
729
|
+
body: JSON.stringify({
|
|
730
|
+
model: provider.model,
|
|
731
|
+
temperature: 0.2,
|
|
732
|
+
stream: true,
|
|
733
|
+
messages: [
|
|
734
|
+
{ role: "system", content: input.systemPrompt },
|
|
735
|
+
{ role: "user", content: [{ type: "text", text: userText }, ...imageParts] }
|
|
736
|
+
]
|
|
737
|
+
})
|
|
738
|
+
});
|
|
739
|
+
if (!response.ok || !response.body) {
|
|
740
|
+
const data = (await response.json().catch(() => ({}))) as { error?: { message?: string } };
|
|
741
|
+
throw new BadRequestException({
|
|
742
|
+
message: data.error?.message ?? "AI provider request failed",
|
|
743
|
+
code: "AI_PROVIDER_REQUEST_FAILED"
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
const reader = response.body.getReader();
|
|
747
|
+
const decoder = new TextDecoder();
|
|
748
|
+
let buffer = "";
|
|
749
|
+
while (true) {
|
|
750
|
+
const chunk = await reader.read();
|
|
751
|
+
if (chunk.done) break;
|
|
752
|
+
buffer += decoder.decode(chunk.value, { stream: true });
|
|
753
|
+
const lines = buffer.split("\n");
|
|
754
|
+
buffer = lines.pop() ?? "";
|
|
755
|
+
for (const rawLine of lines) {
|
|
756
|
+
const line = rawLine.trim();
|
|
757
|
+
if (!line.startsWith("data:")) continue;
|
|
758
|
+
const payload = line.slice(5).trim();
|
|
759
|
+
if (!payload || payload === "[DONE]") continue;
|
|
760
|
+
const parsed = JSON.parse(payload) as {
|
|
761
|
+
choices?: Array<{ delta?: { content?: string } }>;
|
|
762
|
+
};
|
|
763
|
+
const delta = parsed.choices?.[0]?.delta?.content;
|
|
764
|
+
if (delta) yield delta;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
private async callAnthropic(
|
|
770
|
+
provider: AiProviderConfig,
|
|
771
|
+
token: string,
|
|
772
|
+
input: { message: string; context: unknown; systemPrompt: string; attachments: ChatAttachment[] }
|
|
773
|
+
) {
|
|
774
|
+
const content: Array<Record<string, unknown>> = [
|
|
775
|
+
{
|
|
776
|
+
type: "text",
|
|
777
|
+
text: `${input.message}\n\nContext:\n${JSON.stringify(input.context)}`
|
|
778
|
+
}
|
|
779
|
+
];
|
|
780
|
+
for (const file of input.attachments) {
|
|
781
|
+
if (file.mimeType.startsWith("image/")) {
|
|
782
|
+
content.push({
|
|
783
|
+
type: "image",
|
|
784
|
+
source: {
|
|
785
|
+
type: "base64",
|
|
786
|
+
media_type: file.mimeType,
|
|
787
|
+
data: file.contentBase64
|
|
788
|
+
}
|
|
789
|
+
});
|
|
790
|
+
} else {
|
|
791
|
+
content.push({ type: "text", text: `File: ${file.name} (${file.mimeType})` });
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
const response = await fetch(`${provider.baseUrl ?? "https://api.anthropic.com/v1"}/messages`, {
|
|
795
|
+
method: "POST",
|
|
796
|
+
headers: {
|
|
797
|
+
"x-api-key": token,
|
|
798
|
+
"anthropic-version": "2023-06-01",
|
|
799
|
+
"content-type": "application/json"
|
|
800
|
+
},
|
|
801
|
+
body: JSON.stringify({
|
|
802
|
+
model: provider.model,
|
|
803
|
+
max_tokens: 1800,
|
|
804
|
+
temperature: 0.2,
|
|
805
|
+
system: input.systemPrompt,
|
|
806
|
+
messages: [{ role: "user", content }]
|
|
807
|
+
})
|
|
808
|
+
});
|
|
809
|
+
const data = (await response.json().catch(() => ({}))) as {
|
|
810
|
+
error?: { message?: string };
|
|
811
|
+
content?: Array<{ type?: string; text?: string }>;
|
|
812
|
+
};
|
|
813
|
+
if (!response.ok) {
|
|
814
|
+
throw new BadRequestException({
|
|
815
|
+
message: data.error?.message ?? "AI provider request failed",
|
|
816
|
+
code: "AI_PROVIDER_REQUEST_FAILED"
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
const text = data.content?.find((item) => item.type === "text")?.text;
|
|
820
|
+
return text?.trim() ?? "Empty response from AI.";
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
private async *callAnthropicStream(
|
|
824
|
+
provider: AiProviderConfig,
|
|
825
|
+
token: string,
|
|
826
|
+
input: { message: string; context: unknown; systemPrompt: string; attachments: ChatAttachment[] }
|
|
827
|
+
): AsyncGenerator<string> {
|
|
828
|
+
const content: Array<Record<string, unknown>> = [
|
|
829
|
+
{ type: "text", text: `${input.message}\n\nContext:\n${JSON.stringify(input.context)}` }
|
|
830
|
+
];
|
|
831
|
+
for (const file of input.attachments) {
|
|
832
|
+
if (file.mimeType.startsWith("image/")) {
|
|
833
|
+
content.push({
|
|
834
|
+
type: "image",
|
|
835
|
+
source: { type: "base64", media_type: file.mimeType, data: file.contentBase64 }
|
|
836
|
+
});
|
|
837
|
+
} else {
|
|
838
|
+
content.push({ type: "text", text: `File: ${file.name} (${file.mimeType})` });
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
const response = await fetch(`${provider.baseUrl ?? "https://api.anthropic.com/v1"}/messages`, {
|
|
842
|
+
method: "POST",
|
|
843
|
+
headers: {
|
|
844
|
+
"x-api-key": token,
|
|
845
|
+
"anthropic-version": "2023-06-01",
|
|
846
|
+
"content-type": "application/json"
|
|
847
|
+
},
|
|
848
|
+
body: JSON.stringify({
|
|
849
|
+
model: provider.model,
|
|
850
|
+
max_tokens: 1800,
|
|
851
|
+
temperature: 0.2,
|
|
852
|
+
stream: true,
|
|
853
|
+
system: input.systemPrompt,
|
|
854
|
+
messages: [{ role: "user", content }]
|
|
855
|
+
})
|
|
856
|
+
});
|
|
857
|
+
if (!response.ok || !response.body) {
|
|
858
|
+
const data = (await response.json().catch(() => ({}))) as { error?: { message?: string } };
|
|
859
|
+
throw new BadRequestException({
|
|
860
|
+
message: data.error?.message ?? "AI provider request failed",
|
|
861
|
+
code: "AI_PROVIDER_REQUEST_FAILED"
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
const reader = response.body.getReader();
|
|
865
|
+
const decoder = new TextDecoder();
|
|
866
|
+
let buffer = "";
|
|
867
|
+
while (true) {
|
|
868
|
+
const chunk = await reader.read();
|
|
869
|
+
if (chunk.done) break;
|
|
870
|
+
buffer += decoder.decode(chunk.value, { stream: true });
|
|
871
|
+
const lines = buffer.split("\n");
|
|
872
|
+
buffer = lines.pop() ?? "";
|
|
873
|
+
for (const rawLine of lines) {
|
|
874
|
+
const line = rawLine.trim();
|
|
875
|
+
if (!line.startsWith("data:")) continue;
|
|
876
|
+
const payload = line.slice(5).trim();
|
|
877
|
+
if (!payload || payload === "[DONE]") continue;
|
|
878
|
+
const parsed = JSON.parse(payload) as {
|
|
879
|
+
type?: string;
|
|
880
|
+
delta?: { text?: string };
|
|
881
|
+
};
|
|
882
|
+
if (parsed.type === "content_block_delta" && parsed.delta?.text) {
|
|
883
|
+
yield parsed.delta.text;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
private async callGemini(
|
|
890
|
+
provider: AiProviderConfig,
|
|
891
|
+
token: string,
|
|
892
|
+
input: { message: string; context: unknown; systemPrompt: string; attachments: ChatAttachment[] }
|
|
893
|
+
) {
|
|
894
|
+
const parts: Array<Record<string, unknown>> = [
|
|
895
|
+
{
|
|
896
|
+
text: `${input.systemPrompt}\n\nUser request:\n${input.message}\n\nContext:\n${JSON.stringify(input.context)}`
|
|
897
|
+
}
|
|
898
|
+
];
|
|
899
|
+
for (const file of input.attachments) {
|
|
900
|
+
parts.push({
|
|
901
|
+
inlineData: {
|
|
902
|
+
mimeType: file.mimeType,
|
|
903
|
+
data: file.contentBase64
|
|
904
|
+
}
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
const url = `${provider.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta"}/models/${provider.model}:generateContent?key=${encodeURIComponent(token)}`;
|
|
908
|
+
const response = await fetch(url, {
|
|
909
|
+
method: "POST",
|
|
910
|
+
headers: { "content-type": "application/json" },
|
|
911
|
+
body: JSON.stringify({ contents: [{ role: "user", parts }], generationConfig: { temperature: 0.2 } })
|
|
912
|
+
});
|
|
913
|
+
const data = (await response.json().catch(() => ({}))) as {
|
|
914
|
+
error?: { message?: string };
|
|
915
|
+
candidates?: Array<{ content?: { parts?: Array<{ text?: string }> } }>;
|
|
916
|
+
};
|
|
917
|
+
if (!response.ok) {
|
|
918
|
+
throw new BadRequestException({
|
|
919
|
+
message: data.error?.message ?? "AI provider request failed",
|
|
920
|
+
code: "AI_PROVIDER_REQUEST_FAILED"
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
return data.candidates?.[0]?.content?.parts?.map((part) => part.text ?? "").join("").trim() ?? "Empty response from AI.";
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
private async *callGeminiStream(
|
|
927
|
+
provider: AiProviderConfig,
|
|
928
|
+
token: string,
|
|
929
|
+
input: { message: string; context: unknown; systemPrompt: string; attachments: ChatAttachment[] }
|
|
930
|
+
): AsyncGenerator<string> {
|
|
931
|
+
const parts: Array<Record<string, unknown>> = [
|
|
932
|
+
{
|
|
933
|
+
text: `${input.systemPrompt}\n\nUser request:\n${input.message}\n\nContext:\n${JSON.stringify(input.context)}`
|
|
934
|
+
}
|
|
935
|
+
];
|
|
936
|
+
for (const file of input.attachments) {
|
|
937
|
+
parts.push({
|
|
938
|
+
inlineData: {
|
|
939
|
+
mimeType: file.mimeType,
|
|
940
|
+
data: file.contentBase64
|
|
941
|
+
}
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
const url = `${provider.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta"}/models/${provider.model}:streamGenerateContent?alt=sse&key=${encodeURIComponent(token)}`;
|
|
945
|
+
const response = await fetch(url, {
|
|
946
|
+
method: "POST",
|
|
947
|
+
headers: { "content-type": "application/json" },
|
|
948
|
+
body: JSON.stringify({ contents: [{ role: "user", parts }], generationConfig: { temperature: 0.2 } })
|
|
949
|
+
});
|
|
950
|
+
if (!response.ok || !response.body) {
|
|
951
|
+
const data = (await response.json().catch(() => ({}))) as { error?: { message?: string } };
|
|
952
|
+
throw new BadRequestException({
|
|
953
|
+
message: data.error?.message ?? "AI provider request failed",
|
|
954
|
+
code: "AI_PROVIDER_REQUEST_FAILED"
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
const reader = response.body.getReader();
|
|
958
|
+
const decoder = new TextDecoder();
|
|
959
|
+
let buffer = "";
|
|
960
|
+
while (true) {
|
|
961
|
+
const chunk = await reader.read();
|
|
962
|
+
if (chunk.done) break;
|
|
963
|
+
buffer += decoder.decode(chunk.value, { stream: true });
|
|
964
|
+
const lines = buffer.split("\n");
|
|
965
|
+
buffer = lines.pop() ?? "";
|
|
966
|
+
for (const rawLine of lines) {
|
|
967
|
+
const line = rawLine.trim();
|
|
968
|
+
if (!line.startsWith("data:")) continue;
|
|
969
|
+
const payload = line.slice(5).trim();
|
|
970
|
+
if (!payload || payload === "[DONE]") continue;
|
|
971
|
+
const parsed = JSON.parse(payload) as {
|
|
972
|
+
candidates?: Array<{ content?: { parts?: Array<{ text?: string }> } }>;
|
|
973
|
+
};
|
|
974
|
+
const delta = parsed.candidates?.[0]?.content?.parts?.map((part) => part.text ?? "").join("") ?? "";
|
|
975
|
+
if (delta) yield delta;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
private tryParseStructuredOutput(text: string): { reply?: string; action?: Record<string, unknown> } | null {
|
|
981
|
+
const trimmed = text.trim();
|
|
982
|
+
const codeBlock = trimmed.match(/```json\s*([\s\S]*?)```/i)?.[1];
|
|
983
|
+
const candidate = codeBlock ?? trimmed;
|
|
984
|
+
try {
|
|
985
|
+
const parsed = JSON.parse(candidate) as { reply?: string; action?: Record<string, unknown> };
|
|
986
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
987
|
+
return parsed;
|
|
988
|
+
} catch {
|
|
989
|
+
return null;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
private hasPermission(user: UserContext, permission?: string) {
|
|
994
|
+
return Boolean(permission && (user.permissions.includes(permission) || user.permissions.includes("*")));
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
private async readJsonSetting<T>(key: string, fallback: T): Promise<T> {
|
|
998
|
+
const entry = await this.prisma.setting.findUnique({ where: { key } });
|
|
999
|
+
if (!entry) return fallback;
|
|
1000
|
+
return entry.value as T;
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
private async readStringSetting(key: string, fallback: string): Promise<string> {
|
|
1004
|
+
const entry = await this.prisma.setting.findUnique({ where: { key } });
|
|
1005
|
+
if (!entry) return fallback;
|
|
1006
|
+
const value = entry.value;
|
|
1007
|
+
return typeof value === "string" ? value : String(value ?? fallback);
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
private async upsertSetting(key: string, type: "string" | "json", value: unknown) {
|
|
1011
|
+
await this.prisma.setting.upsert({
|
|
1012
|
+
where: { key },
|
|
1013
|
+
create: {
|
|
1014
|
+
key,
|
|
1015
|
+
group: "ai-assistant",
|
|
1016
|
+
type,
|
|
1017
|
+
value: value as Prisma.InputJsonValue
|
|
1018
|
+
},
|
|
1019
|
+
update: {
|
|
1020
|
+
group: "ai-assistant",
|
|
1021
|
+
type,
|
|
1022
|
+
value: value as Prisma.InputJsonValue
|
|
1023
|
+
}
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
private async resolveConversation(userId: string, conversationId: string | undefined, firstMessage: string) {
|
|
1028
|
+
if (conversationId) {
|
|
1029
|
+
const existing = await this.prisma.aiConversation.findFirst({ where: { id: conversationId, userId } });
|
|
1030
|
+
if (existing) return existing.id;
|
|
1031
|
+
}
|
|
1032
|
+
const created = await this.prisma.aiConversation.create({
|
|
1033
|
+
data: {
|
|
1034
|
+
userId,
|
|
1035
|
+
title: firstMessage.trim().slice(0, 80) || "New chat"
|
|
1036
|
+
}
|
|
1037
|
+
});
|
|
1038
|
+
return created.id;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
private async createMessage(conversationId: string, role: "user" | "assistant", content: string, meta?: Record<string, unknown>) {
|
|
1042
|
+
await this.prisma.aiMessage.create({
|
|
1043
|
+
data: {
|
|
1044
|
+
conversationId,
|
|
1045
|
+
role,
|
|
1046
|
+
content,
|
|
1047
|
+
meta: (meta ?? null) as Prisma.InputJsonValue | Prisma.NullableJsonNullValueInput
|
|
1048
|
+
}
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
async getArtifact(user: UserContext, artifactId: string) {
|
|
1053
|
+
this.ensureChatPermission(user);
|
|
1054
|
+
const artifact = await this.prisma.aiArtifact.findFirst({
|
|
1055
|
+
where: { id: artifactId, userId: user.id }
|
|
1056
|
+
});
|
|
1057
|
+
if (!artifact) {
|
|
1058
|
+
throw new BadRequestException({ message: "Artifact not found", code: "AI_ARTIFACT_NOT_FOUND" });
|
|
1059
|
+
}
|
|
1060
|
+
return artifact;
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
private async createArtifact(
|
|
1064
|
+
userId: string,
|
|
1065
|
+
content: string,
|
|
1066
|
+
input: {
|
|
1067
|
+
conversationId?: string;
|
|
1068
|
+
filename: string;
|
|
1069
|
+
mimeType: string;
|
|
1070
|
+
encoding: "utf8" | "base64";
|
|
1071
|
+
meta?: Record<string, unknown>;
|
|
1072
|
+
}
|
|
1073
|
+
) {
|
|
1074
|
+
const contentBase64 =
|
|
1075
|
+
input.encoding === "base64" ? content : Buffer.from(content, "utf8").toString("base64");
|
|
1076
|
+
const size = Buffer.from(contentBase64, "base64").byteLength;
|
|
1077
|
+
const artifact = await this.prisma.aiArtifact.create({
|
|
1078
|
+
data: {
|
|
1079
|
+
userId,
|
|
1080
|
+
conversationId: input.conversationId ?? null,
|
|
1081
|
+
filename: input.filename.slice(0, 180),
|
|
1082
|
+
mimeType: input.mimeType.slice(0, 120),
|
|
1083
|
+
size,
|
|
1084
|
+
contentBase64,
|
|
1085
|
+
meta: (input.meta ?? null) as Prisma.InputJsonValue | Prisma.NullableJsonNullValueInput
|
|
1086
|
+
}
|
|
1087
|
+
});
|
|
1088
|
+
return {
|
|
1089
|
+
id: artifact.id,
|
|
1090
|
+
artifactId: artifact.id,
|
|
1091
|
+
artifactRef: `ai-artifact:${artifact.id}`,
|
|
1092
|
+
filename: artifact.filename,
|
|
1093
|
+
mimeType: artifact.mimeType,
|
|
1094
|
+
size: artifact.size,
|
|
1095
|
+
downloadUrl: `/admin/ai/artifacts/${artifact.id}/download`
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
private async createImageArtifact(
|
|
1100
|
+
userId: string,
|
|
1101
|
+
action: Record<string, unknown>,
|
|
1102
|
+
provider: AiProviderConfig,
|
|
1103
|
+
token: string
|
|
1104
|
+
) {
|
|
1105
|
+
if (provider.kind !== "openai") {
|
|
1106
|
+
throw new BadRequestException({
|
|
1107
|
+
message: `Provider "${provider.label}" does not support image generation in this integration`,
|
|
1108
|
+
code: "AI_IMAGE_PROVIDER_UNSUPPORTED"
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
const prompt = String(action.prompt ?? "").trim();
|
|
1112
|
+
if (!prompt) {
|
|
1113
|
+
throw new BadRequestException({ message: "Image prompt is required", code: "AI_IMAGE_PROMPT_REQUIRED" });
|
|
1114
|
+
}
|
|
1115
|
+
const filename = String(action.filename ?? "generated-image.png");
|
|
1116
|
+
const size = String(action.size ?? "1024x1024");
|
|
1117
|
+
const model = String(action.model ?? "gpt-image-1");
|
|
1118
|
+
const response = await fetch(`${provider.baseUrl ?? "https://api.openai.com/v1"}/images/generations`, {
|
|
1119
|
+
method: "POST",
|
|
1120
|
+
headers: {
|
|
1121
|
+
authorization: `Bearer ${token}`,
|
|
1122
|
+
"content-type": "application/json"
|
|
1123
|
+
},
|
|
1124
|
+
body: JSON.stringify({
|
|
1125
|
+
model,
|
|
1126
|
+
prompt,
|
|
1127
|
+
size,
|
|
1128
|
+
response_format: "b64_json"
|
|
1129
|
+
})
|
|
1130
|
+
});
|
|
1131
|
+
const data = (await response.json().catch(() => ({}))) as {
|
|
1132
|
+
error?: { message?: string };
|
|
1133
|
+
data?: Array<{ b64_json?: string }>;
|
|
1134
|
+
};
|
|
1135
|
+
if (!response.ok) {
|
|
1136
|
+
throw new BadRequestException({
|
|
1137
|
+
message: data.error?.message ?? "Image generation failed",
|
|
1138
|
+
code: "AI_IMAGE_GENERATION_FAILED"
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
const b64 = data.data?.[0]?.b64_json;
|
|
1142
|
+
if (!b64) {
|
|
1143
|
+
throw new BadRequestException({
|
|
1144
|
+
message: "Image provider returned empty payload",
|
|
1145
|
+
code: "AI_IMAGE_EMPTY_PAYLOAD"
|
|
1146
|
+
});
|
|
1147
|
+
}
|
|
1148
|
+
return this.createArtifact(userId, b64, {
|
|
1149
|
+
filename,
|
|
1150
|
+
mimeType: "image/png",
|
|
1151
|
+
encoding: "base64",
|
|
1152
|
+
meta: { type: "image", prompt, model, size }
|
|
1153
|
+
});
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
private async resolveArtifactRefs(userId: string, value: unknown, resourceName?: string): Promise<unknown> {
|
|
1157
|
+
const latestImageUrl = await this.getLatestArtifactUrl(userId, { imageOnly: true });
|
|
1158
|
+
const latestAnyUrl = await this.getLatestArtifactUrl(userId, { imageOnly: false });
|
|
1159
|
+
|
|
1160
|
+
const isImageLikeField = (field: string) =>
|
|
1161
|
+
/(image|cover|avatar|thumbnail|banner|icon)/i.test(field);
|
|
1162
|
+
|
|
1163
|
+
const resolveValue = async (input: unknown, fieldName?: string): Promise<unknown> => {
|
|
1164
|
+
if (typeof input === "string") {
|
|
1165
|
+
if (input.startsWith("ai-artifact:")) {
|
|
1166
|
+
const artifactId = input.slice("ai-artifact:".length).trim();
|
|
1167
|
+
if (!artifactId) return input;
|
|
1168
|
+
const artifact = await this.prisma.aiArtifact.findFirst({
|
|
1169
|
+
where: { id: artifactId, userId }
|
|
1170
|
+
});
|
|
1171
|
+
if (!artifact) {
|
|
1172
|
+
throw new BadRequestException({
|
|
1173
|
+
message: `Artifact "${artifactId}" not found`,
|
|
1174
|
+
code: "AI_ARTIFACT_NOT_FOUND"
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
return `/admin/ai/artifacts/${artifact.id}/download`;
|
|
1178
|
+
}
|
|
1179
|
+
if (input === "{{latest_image}}") return latestImageUrl ?? input;
|
|
1180
|
+
if (input === "{{latest_artifact}}") return latestAnyUrl ?? input;
|
|
1181
|
+
if (fieldName && isImageLikeField(fieldName) && /^(auto|latest)$/i.test(input)) {
|
|
1182
|
+
return latestImageUrl ?? input;
|
|
1183
|
+
}
|
|
1184
|
+
return input;
|
|
1185
|
+
}
|
|
1186
|
+
if (typeof input === "boolean" && fieldName && isImageLikeField(fieldName) && input) {
|
|
1187
|
+
return latestImageUrl ?? input;
|
|
1188
|
+
}
|
|
1189
|
+
if (Array.isArray(input)) {
|
|
1190
|
+
return Promise.all(input.map((item) => resolveValue(item)));
|
|
1191
|
+
}
|
|
1192
|
+
if (input && typeof input === "object") {
|
|
1193
|
+
const entries = await Promise.all(
|
|
1194
|
+
Object.entries(input as Record<string, unknown>).map(async ([key, nested]) => [
|
|
1195
|
+
key,
|
|
1196
|
+
await resolveValue(nested, key)
|
|
1197
|
+
])
|
|
1198
|
+
);
|
|
1199
|
+
return Object.fromEntries(entries);
|
|
1200
|
+
}
|
|
1201
|
+
return input;
|
|
1202
|
+
};
|
|
1203
|
+
|
|
1204
|
+
const resolved = await resolveValue(value);
|
|
1205
|
+
if (resourceName && resolved && typeof resolved === "object") {
|
|
1206
|
+
return resolved;
|
|
1207
|
+
}
|
|
1208
|
+
return resolved;
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
private async getLatestArtifactUrl(userId: string, options: { imageOnly: boolean }) {
|
|
1212
|
+
const artifact = await this.prisma.aiArtifact.findFirst({
|
|
1213
|
+
where: {
|
|
1214
|
+
userId,
|
|
1215
|
+
...(options.imageOnly ? { mimeType: { startsWith: "image/" } } : {})
|
|
1216
|
+
},
|
|
1217
|
+
orderBy: { createdAt: "desc" }
|
|
1218
|
+
});
|
|
1219
|
+
if (!artifact) return null;
|
|
1220
|
+
return `/admin/ai/artifacts/${artifact.id}/download`;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
private toCsv(rows: Record<string, unknown>[], explicitColumns?: string[]) {
|
|
1224
|
+
const columns =
|
|
1225
|
+
explicitColumns && explicitColumns.length > 0
|
|
1226
|
+
? explicitColumns
|
|
1227
|
+
: [...new Set(rows.flatMap((row) => Object.keys(row)))];
|
|
1228
|
+
const escapeCell = (value: unknown) => {
|
|
1229
|
+
const str = value == null ? "" : typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
1230
|
+
if (/[",\n]/.test(str)) return `"${str.replace(/"/g, "\"\"")}"`;
|
|
1231
|
+
return str;
|
|
1232
|
+
};
|
|
1233
|
+
const head = columns.map(escapeCell).join(",");
|
|
1234
|
+
const lines = rows.map((row) => columns.map((column) => escapeCell(row[column])).join(","));
|
|
1235
|
+
return [head, ...lines].join("\n");
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
}
|