plugin-ai-api 1.0.7 → 1.0.9

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.
@@ -0,0 +1,59 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var ai_employee_runtime_exports = {};
28
+ __export(ai_employee_runtime_exports, {
29
+ createAIEmployeeOptions: () => createAIEmployeeOptions,
30
+ getAgentRuntimeLifecycle: () => getAgentRuntimeLifecycle,
31
+ loadAIEmployeeConstructor: () => loadAIEmployeeConstructor
32
+ });
33
+ module.exports = __toCommonJS(ai_employee_runtime_exports);
34
+ function getAgentRuntimeLifecycle(ctx) {
35
+ return ctx.app.agentRuntimeLifecycle;
36
+ }
37
+ let cachedConstructor = null;
38
+ async function loadAIEmployeeConstructor() {
39
+ if (cachedConstructor) return cachedConstructor;
40
+ const modulePath = "@nocobase/plugin-ai/dist/server/ai-employees/ai-employee.js";
41
+ const module2 = await import(
42
+ /* webpackIgnore: true */
43
+ modulePath
44
+ );
45
+ if (typeof module2.AIEmployee !== "function") {
46
+ throw new Error("AIEmployee class is not exported by the installed plugin-ai runtime.");
47
+ }
48
+ cachedConstructor = module2.AIEmployee;
49
+ return cachedConstructor;
50
+ }
51
+ function createAIEmployeeOptions(ctx, employee, sessionId, model) {
52
+ return { ctx, employee, sessionId, webSearch: false, model, legacy: false };
53
+ }
54
+ // Annotate the CommonJS export names for ESM import in node:
55
+ 0 && (module.exports = {
56
+ createAIEmployeeOptions,
57
+ getAgentRuntimeLifecycle,
58
+ loadAIEmployeeConstructor
59
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "plugin-ai-api",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "main": "dist/server/index.js",
5
5
  "dependencies": {},
6
6
  "peerDependencies": {
@@ -0,0 +1,26 @@
1
+ import type { Context } from '@nocobase/actions';
2
+ import { createAIEmployeeOptions } from '../utils/ai-employee-runtime';
3
+
4
+ describe('AI API agent completions', () => {
5
+ it('creates the object-shaped options required by AIEmployee', () => {
6
+ const ctx = { app: {}, db: {} } as Context;
7
+ const employee = { username: 'support-agent' };
8
+
9
+ const options = createAIEmployeeOptions(ctx, employee, 'session-1', {
10
+ llmService: 'internal-deepseek',
11
+ model: 'deepseek-r1',
12
+ });
13
+
14
+ expect(options).toEqual({
15
+ ctx,
16
+ employee,
17
+ sessionId: 'session-1',
18
+ webSearch: false,
19
+ model: {
20
+ llmService: 'internal-deepseek',
21
+ model: 'deepseek-r1',
22
+ },
23
+ legacy: false,
24
+ });
25
+ });
26
+ });
@@ -0,0 +1,33 @@
1
+ import { defineCollection } from '@nocobase/database';
2
+
3
+ export default defineCollection({
4
+ name: 'aiApiUsageRecords',
5
+ autoGenId: true,
6
+ fields: [
7
+ { name: 'requestId', type: 'string', unique: true, index: true },
8
+ { name: 'userId', type: 'string', index: true },
9
+ { name: 'roleName', type: 'string', index: true },
10
+ { name: 'authType', type: 'string', index: true },
11
+ { name: 'oauthClientId', type: 'string', allowNull: true, index: true },
12
+ { name: 'oauthSubject', type: 'string', allowNull: true },
13
+ { name: 'oauthScopes', type: 'json', allowNull: true },
14
+ { name: 'endpoint', type: 'string' },
15
+ { name: 'mode', type: 'string', allowNull: true },
16
+ { name: 'model', type: 'string', allowNull: true, index: true },
17
+ { name: 'status', type: 'string', index: true },
18
+ { name: 'httpStatus', type: 'integer', allowNull: true },
19
+ { name: 'errorCode', type: 'string', allowNull: true },
20
+ { name: 'streaming', type: 'boolean', defaultValue: false },
21
+ { name: 'inputTokens', type: 'integer', allowNull: true },
22
+ { name: 'outputTokens', type: 'integer', allowNull: true },
23
+ { name: 'totalTokens', type: 'integer', allowNull: true },
24
+ { name: 'estimatedCost', type: 'decimal', allowNull: true, precision: 20, scale: 8 },
25
+ { name: 'currency', type: 'string', allowNull: true },
26
+ { name: 'providerRequestId', type: 'string', allowNull: true },
27
+ { name: 'requestMetadata', type: 'jsonb', defaultValue: {} },
28
+ { name: 'responseMetadata', type: 'jsonb', defaultValue: {} },
29
+ { name: 'startedAt', type: 'datetimeTz', allowNull: true },
30
+ { name: 'completedAt', type: 'datetimeTz', allowNull: true },
31
+ { name: 'durationMs', type: 'integer', allowNull: true },
32
+ ],
33
+ });
@@ -1,66 +1,79 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import { Context } from '@nocobase/actions';
11
- import { toOpenAIError } from '../utils/openai-format';
12
-
13
- /**
14
- * Check whether the authenticated role is allowed to use the AI API.
15
- * Loads the permission record and stores it in ctx.state.aiApiRolePermission.
16
- *
17
- * Returns true if access is allowed (caller may proceed).
18
- * Returns false if access is denied (403 already written to ctx, caller must return).
19
- *
20
- * The 'root' and 'admin' roles always bypass the check.
21
- */
22
- export async function checkRolePermission(ctx: Context): Promise<boolean> {
23
- const roleName = ctx.state.currentRoles?.[0] || 'member';
24
-
25
- // root / admin always allowed
26
- if (roleName === 'root' || roleName === 'admin') {
27
- return true;
28
- }
29
-
30
- const record = await ctx.db.getRepository('aiApiRolePermissions').findOne({
31
- filter: { roleName },
32
- });
33
-
34
- if (!record?.enabled) {
35
- ctx.status = 403;
36
- ctx.body = toOpenAIError(
37
- 403,
38
- `Role '${roleName}' is not authorized to use the AI API. ` +
39
- `An admin must enable access in Settings → Users & Permissions → [Role] → AI API.`,
40
- 'permission_denied',
41
- 'role_not_permitted',
42
- );
43
- return false;
44
- }
45
-
46
- // Store for downstream handlers
47
- ctx.state.aiApiRolePermission = record;
48
- return true;
49
- }
50
-
51
- /**
52
- * Check whether the current role is allowed to use a specific AI Employee.
53
- * Must be called after checkRolePermission (so ctx.state.aiApiRolePermission is set).
54
- *
55
- * Returns true when:
56
- * - Role is admin/root (no permission record stored)
57
- * - allowAllEmployees is true
58
- * - The employeeUsername is in the allowedEmployees list
59
- */
60
- export function checkEmployeeAccess(ctx: Context, employeeUsername: string): boolean {
61
- const perm = ctx.state.aiApiRolePermission;
62
- // admin/root paths have no record stored → always allowed
63
- if (!perm) return true;
64
- if (perm.allowAllEmployees) return true;
65
- return ((perm.allowedEmployees as string[]) || []).includes(employeeUsername);
66
- }
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { Context } from '@nocobase/actions';
11
+ import { toOpenAIError } from '../utils/openai-format';
12
+
13
+ const PERMISSION_TTL_MS = 15_000;
14
+ const permissionCache = new Map<string, { record: any; expiresAt: number }>();
15
+
16
+ export function invalidateRolePermissionCache(roleName?: string): void {
17
+ if (roleName) permissionCache.delete(roleName);
18
+ else permissionCache.clear();
19
+ }
20
+
21
+ /**
22
+ * Check whether the authenticated role is allowed to use the AI API.
23
+ * Loads the permission record and stores it in ctx.state.aiApiRolePermission.
24
+ *
25
+ * Returns true if access is allowed (caller may proceed).
26
+ * Returns false if access is denied (403 already written to ctx, caller must return).
27
+ *
28
+ * The 'root' and 'admin' roles always bypass the check.
29
+ */
30
+ export async function checkRolePermission(ctx: Context): Promise<boolean> {
31
+ const roleName = ctx.state.currentRoles?.[0] || 'member';
32
+
33
+ // root / admin always allowed
34
+ if (roleName === 'root' || roleName === 'admin') {
35
+ return true;
36
+ }
37
+
38
+ const cached = permissionCache.get(roleName);
39
+ const record =
40
+ cached && cached.expiresAt > Date.now()
41
+ ? cached.record
42
+ : await ctx.db.getRepository('aiApiRolePermissions').findOne({ filter: { roleName } });
43
+ if (!cached || cached.expiresAt <= Date.now()) {
44
+ permissionCache.set(roleName, { record, expiresAt: Date.now() + PERMISSION_TTL_MS });
45
+ }
46
+
47
+ if (!record?.enabled) {
48
+ ctx.status = 403;
49
+ ctx.body = toOpenAIError(
50
+ 403,
51
+ `Role '${roleName}' is not authorized to use the AI API. ` +
52
+ `An admin must enable access in Settings Users & Permissions [Role] AI API.`,
53
+ 'permission_denied',
54
+ 'role_not_permitted',
55
+ );
56
+ return false;
57
+ }
58
+
59
+ // Store for downstream handlers
60
+ ctx.state.aiApiRolePermission = record;
61
+ return true;
62
+ }
63
+
64
+ /**
65
+ * Check whether the current role is allowed to use a specific AI Employee.
66
+ * Must be called after checkRolePermission (so ctx.state.aiApiRolePermission is set).
67
+ *
68
+ * Returns true when:
69
+ * - Role is admin/root (no permission record stored)
70
+ * - allowAllEmployees is true
71
+ * - The employeeUsername is in the allowedEmployees list
72
+ */
73
+ export function checkEmployeeAccess(ctx: Context, employeeUsername: string): boolean {
74
+ const perm = ctx.state.aiApiRolePermission;
75
+ // admin/root paths have no record stored → always allowed
76
+ if (!perm) return true;
77
+ if (perm.allowAllEmployees) return true;
78
+ return ((perm.allowedEmployees as string[]) || []).includes(employeeUsername);
79
+ }
@@ -1,89 +1,99 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import { Plugin } from '@nocobase/server';
11
- import { createAiLlmRouter } from './routes/router';
12
- import aiApiConfigResource from './resource/ai-api-config';
13
- import { RateLimiter } from './utils/rate-limiter';
14
-
15
- // Ensure dayjs timezone + utc plugins are loaded.
16
- // Some Docker builds ship an older @nocobase/utils whose dayjs.js does not
17
- // extend the 'timezone' plugin, causing utcOffset(value) to behave as a
18
- // getter (returns a number) instead of a setter (returns a dayjs instance).
19
- // That breaks parse-filter.js's utc2unit() "m.startOf is not a function".
20
- // Extending here patches the shared CommonJS dayjs module instance for the
21
- // entire Node.js process before any AIEmployee call is made.
22
- import dayjsLib from 'dayjs';
23
- import utcPlugin from 'dayjs/plugin/utc';
24
- import timezonePlugin from 'dayjs/plugin/timezone';
25
- (dayjsLib as any).extend(utcPlugin);
26
- (dayjsLib as any).extend(timezonePlugin);
27
-
28
- export class PluginAiApiServer extends Plugin {
29
- /**
30
- * Singleton rate limiter — lives for the entire plugin lifetime, shared across all requests.
31
- * Uses a 1-minute sliding window to enforce rateLimitPerMinute from aiApiConfig.
32
- */
33
- rateLimiter = new RateLimiter(60_000);
34
-
35
- private gcInterval: NodeJS.Timeout | null = null;
36
-
37
- async afterAdd() {}
38
-
39
- async beforeLoad() {}
40
-
41
- async load() {
42
- // 1. Register raw Koa middleware for OpenAI-compatible endpoints
43
- // Must run before 'resourcer' so URL paths match OpenAI convention
44
- this.app.use(createAiLlmRouter(this), { before: 'resourcer' });
45
-
46
- // 2. Register admin config resource
47
- this.app.resourceManager.define(aiApiConfigResource);
48
-
49
- // 3. Set ACL permissions for admin config + role permissions management
50
- this.app.acl.registerSnippet({
51
- name: `pm.${this.name}.configuration`,
52
- actions: ['aiApiConfig:*', 'aiApiRolePermissions:*'],
53
- });
54
-
55
- // 4. GC the rate limiter every 5 minutes to evict stale user entries.
56
- // .unref() prevents this timer from keeping the process alive on shutdown.
57
- this.gcInterval = setInterval(() => this.rateLimiter.gc(), 5 * 60 * 1000);
58
- this.gcInterval.unref();
59
- }
60
-
61
- async install() {
62
- // Create default config record on first install
63
- const existing = await this.db.getRepository('aiApiConfig').findOne();
64
- if (!existing) {
65
- await this.db.getRepository('aiApiConfig').create({
66
- values: {
67
- defaultAiEmployee: '',
68
- enabledLlmServices: [],
69
- rateLimitPerMinute: 60,
70
- },
71
- });
72
- }
73
- }
74
-
75
- async afterEnable() {}
76
-
77
- async afterDisable() {}
78
-
79
- async remove() {
80
- // Clean up the GC timer so we don't leak resources during hot-reload
81
- if (this.gcInterval) {
82
- clearInterval(this.gcInterval);
83
- this.gcInterval = null;
84
- }
85
- this.rateLimiter.clear();
86
- }
87
- }
88
-
89
- export default PluginAiApiServer;
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { Plugin } from '@nocobase/server';
11
+ import { createAiLlmRouter } from './routes/router';
12
+ import aiApiConfigResource from './resource/ai-api-config';
13
+ import { RateLimiter } from './utils/rate-limiter';
14
+ import { invalidateRolePermissionCache } from './middleware/role-permission';
15
+
16
+ // Ensure dayjs timezone + utc plugins are loaded.
17
+ // Some Docker builds ship an older @nocobase/utils whose dayjs.js does not
18
+ // extend the 'timezone' plugin, causing utcOffset(value) to behave as a
19
+ // getter (returns a number) instead of a setter (returns a dayjs instance).
20
+ // That breaks parse-filter.js's utc2unit() "m.startOf is not a function".
21
+ // Extending here patches the shared CommonJS dayjs module instance for the
22
+ // entire Node.js process before any AIEmployee call is made.
23
+ import dayjsLib from 'dayjs';
24
+ import utcPlugin from 'dayjs/plugin/utc';
25
+ import timezonePlugin from 'dayjs/plugin/timezone';
26
+ (dayjsLib as any).extend(utcPlugin);
27
+ (dayjsLib as any).extend(timezonePlugin);
28
+
29
+ export class PluginAiApiServer extends Plugin {
30
+ /**
31
+ * Singleton rate limiter lives for the entire plugin lifetime, shared across all requests.
32
+ * Uses a 1-minute sliding window to enforce rateLimitPerMinute from aiApiConfig.
33
+ */
34
+ rateLimiter = new RateLimiter(60_000);
35
+
36
+ private gcInterval: NodeJS.Timeout | null = null;
37
+
38
+ async afterAdd() {}
39
+
40
+ async beforeLoad() {}
41
+
42
+ async load() {
43
+ // 1. Register raw Koa middleware for OpenAI-compatible endpoints
44
+ // Must run before 'resourcer' so URL paths match OpenAI convention
45
+ // OIDC access tokens must first pass through plugin-idp-oauth, which validates
46
+ // issuer/audience/scope and rewrites them to a NocoBase internal token.
47
+ this.app.use(createAiLlmRouter(this), { after: 'idp-oauth-resource-auth', before: 'resourcer' });
48
+
49
+ // 2. Register admin config resource
50
+ this.app.resourceManager.define(aiApiConfigResource);
51
+
52
+ this.app.db.on('aiApiRolePermissions.afterSave', (model) => {
53
+ invalidateRolePermissionCache(model.get('roleName'));
54
+ });
55
+ this.app.db.on('aiApiRolePermissions.afterDestroy', (model) => {
56
+ invalidateRolePermissionCache(model.get('roleName'));
57
+ });
58
+
59
+ // 3. Set ACL permissions for admin config + role permissions management
60
+ this.app.acl.registerSnippet({
61
+ name: `pm.${this.name}.configuration`,
62
+ actions: ['aiApiConfig:*', 'aiApiRolePermissions:*'],
63
+ });
64
+
65
+ // 4. GC the rate limiter every 5 minutes to evict stale user entries.
66
+ // .unref() prevents this timer from keeping the process alive on shutdown.
67
+ this.gcInterval = setInterval(() => this.rateLimiter.gc(), 5 * 60 * 1000);
68
+ this.gcInterval.unref();
69
+ }
70
+
71
+ async install() {
72
+ // Create default config record on first install
73
+ const existing = await this.db.getRepository('aiApiConfig').findOne();
74
+ if (!existing) {
75
+ await this.db.getRepository('aiApiConfig').create({
76
+ values: {
77
+ defaultAiEmployee: '',
78
+ enabledLlmServices: [],
79
+ rateLimitPerMinute: 60,
80
+ },
81
+ });
82
+ }
83
+ }
84
+
85
+ async afterEnable() {}
86
+
87
+ async afterDisable() {}
88
+
89
+ async remove() {
90
+ // Clean up the GC timer so we don't leak resources during hot-reload
91
+ if (this.gcInterval) {
92
+ clearInterval(this.gcInterval);
93
+ this.gcInterval = null;
94
+ }
95
+ this.rateLimiter.clear();
96
+ }
97
+ }
98
+
99
+ export default PluginAiApiServer;