@b2y/ai-service 0.0.0-stage → 1.0.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/README.md +165 -2
- package/package.json +76 -4
- package/src/analytics/Analytics.js +584 -0
- package/src/analytics/Results.js +394 -0
- package/src/assistant/Assistant.js +452 -0
- package/src/assistant/Capabilities.js +344 -0
- package/src/constants/AnalyticsConstants.js +6 -0
- package/src/constants/AssistantConstants.js +5 -0
- package/src/constants/ConversationConstants.js +5 -0
- package/src/constants/DocumentConstants.js +4 -0
- package/src/constants/ProviderConstants.js +25 -0
- package/src/constants/ServerConstants.js +18 -0
- package/src/constants/SqlConstants.js +33 -0
- package/src/constants/UiConstants.js +29 -0
- package/src/conversations/ConversationHistory.js +149 -0
- package/src/conversations/FolderConversationStore.js +119 -0
- package/src/core/AiService.js +512 -0
- package/src/core/Context.js +243 -0
- package/src/core/Deadline.js +24 -0
- package/src/core/Errors.js +248 -0
- package/src/core/Tasks.js +190 -0
- package/src/documents/Documents.js +449 -0
- package/src/documents/FolderDocumentStore.js +167 -0
- package/src/documents/PdfText.js +50 -0
- package/src/enums/ChartType.js +1 -0
- package/src/enums/DataClassification.js +2 -0
- package/src/index.js +53 -0
- package/src/providers/Providers.js +475 -0
- package/src/server/Server.js +152 -0
- package/src/sql/PostgresSqlValidator.js +983 -0
- package/src/sql/SqlPolicy.js +483 -0
- package/src/ui/react/AssistantChat.js +594 -0
- package/src/ui/react/styles.css +239 -0
package/README.md
CHANGED
|
@@ -1,3 +1,166 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @b2y/ai-service
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Application-independent AI assistant for B2Y applications, in plain JavaScript (ES modules, JSDoc types,
|
|
4
|
+
no build step; `require` works from CommonJS on Node.js 20.19+). Private package, not published.
|
|
5
|
+
|
|
6
|
+
The package knows no application. Each consumer supplies its trusted context, profile, capabilities,
|
|
7
|
+
SQL policy, executor and documents; the package routes with the model, validates everything and fails
|
|
8
|
+
closed.
|
|
9
|
+
|
|
10
|
+
## Layout
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
src/constants shared settings, one file per module (Assistant, Provider, Conversation, Analytics, Document, Server, Sql, Ui)
|
|
14
|
+
src/enums shared value sets, one file per enum (ChartType, DataClassification)
|
|
15
|
+
src/core AiService (tasks, retries, rate limits, output validation), Context, Errors, Tasks
|
|
16
|
+
src/providers the OpenAI-compatible provider client (internal)
|
|
17
|
+
src/server runtime, HTTP endpoints, rate limiter, read-only SQL runner (subpath ./server)
|
|
18
|
+
src/assistant createAiAssistant (AI routing), capabilities, response blocks
|
|
19
|
+
src/analytics multi-query planner, result merging, charts and observations
|
|
20
|
+
src/sql SQL policy and the PostgreSQL AST validator
|
|
21
|
+
src/documents document Q&A; folder store and PDF text (subpaths)
|
|
22
|
+
src/conversations history, retention, folder store (subpath)
|
|
23
|
+
src/ui/react AssistantChat, AssistantWidget, API client, Beya's icon, styles.css (subpaths)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Assistant
|
|
27
|
+
|
|
28
|
+
```js
|
|
29
|
+
const ai = createDefaultAiService({ apiKey, tasks: [ASSISTANT_ROUTE_TASK, ASSISTANT_RESPOND_TASK, ANALYTICS_PLAN_TASK] });
|
|
30
|
+
const assistant = createAiAssistant({ ai, profile, capabilities, history, requires: { permission: AI_ASSISTANT_PERMISSION, feature: "ACCESS_AI_ASSISTANT" } });
|
|
31
|
+
const { conversationId, status, blocks } = await assistant.reply({ message, context, conversationId });
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- **Routing is done by the model**: a granted capability, `general` (answers and advice) or `unsupported`
|
|
35
|
+
(changes to data). Grants are decided in code from the context (`requires: { permission, feature }`);
|
|
36
|
+
the model never sees ungranted capabilities, and any other route falls back to `general`.
|
|
37
|
+
- **Capabilities** (`defineCapability`, `createAnalyticsCapability`, `createDocumentsCapability`) are
|
|
38
|
+
read-only. Kinds: data, analytics, search, documents, knowledge, calculation, content. A capability may
|
|
39
|
+
return `memory` (server-only JSON) that it receives back on later turns; analytics uses it to re-plan
|
|
40
|
+
follow-ups with the earlier SQL. `shareFacts` decides which code-computed facts may reach the model.
|
|
41
|
+
- **Polished fallbacks**: requests to change data, and questions outside the user's role or plan, get a
|
|
42
|
+
model-written reply that explains what is possible and offers next steps, never a bare refusal.
|
|
43
|
+
- **Name and icon**: the assistant is `ASSISTANT_NAME` (Beya) with the same bot icon in every application;
|
|
44
|
+
applications do not set them (an `avatar` prop can override the icon if ever needed).
|
|
45
|
+
- **Search** (`createSearchCapability({ fields, sorts, search })`): the model only turns the message into
|
|
46
|
+
filters over declared fields (validated in code, refinements reuse the previous search); `search()` runs
|
|
47
|
+
the application's own scoped query and returns item cards. Items never reach the model.
|
|
48
|
+
- **Unavailable hints**: `unavailableHint` on a capability ("Sign in to see your orders.") replaces the
|
|
49
|
+
role/plan explanation for users who cannot use it.
|
|
50
|
+
- **Replies are blocks**: heading, paragraph, bullets, metrics, table, chart, flow, cards (items with image,
|
|
51
|
+
price and an app path or https link), notice, sources. Never SQL, internal ids or raw rows.
|
|
52
|
+
|
|
53
|
+
## Provider and model
|
|
54
|
+
|
|
55
|
+
`AI_PROVIDER_CONFIG` (src/constants/ProviderConstants.js) is the only place that names the provider and model for every
|
|
56
|
+
application; provider helpers are internal, so no application can name one. Applications pass only their API
|
|
57
|
+
key (`createAiRuntime({ apiKey, tasks, conversationsDir })` on the server). To change provider or model, edit
|
|
58
|
+
that configuration (any OpenAI-compatible API: base URL, model) and add its host to `APPROVED_PROVIDER_HOSTS`,
|
|
59
|
+
then release a new package version.
|
|
60
|
+
|
|
61
|
+
## Server (`@b2y/ai-service/server`)
|
|
62
|
+
|
|
63
|
+
```js
|
|
64
|
+
const { ai, history } = createAiRuntime({ apiKey, tasks, conversationsDir, retentionDays, logger });
|
|
65
|
+
// limiter is optional: by default 15 messages per user per 10 minutes and 500 per tenant per day.
|
|
66
|
+
const endpoints = createAssistantEndpoints({ resolve: async (req) => ({ assistant, context }) | null, limiter, logger });
|
|
67
|
+
mountAssistantRoutes(router, endpoints); // GET /ai/status, POST /ai/chat, GET /ai/conversations[/:id]
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`resolve` builds the context with `buildTrustedContext` (global tenant rule: the request's domain tenant must
|
|
71
|
+
be the session's tenant) and returns null when the assistant is not available. One error policy: 403 access,
|
|
72
|
+
429 limits, 400 input, 502 otherwise, in the `{ status, message, data }` shape. Also `createRateLimiter`,
|
|
73
|
+
`runReadOnly(sequelize, sql, { bind | replacements })` and `quoteTables(sequelize, models)`.
|
|
74
|
+
|
|
75
|
+
## Roles and permissions (global)
|
|
76
|
+
|
|
77
|
+
Roles and permissions work the same in every B2Y application. Pass the signed-in user's **role permissions as
|
|
78
|
+
stored** (`{ Module, Name }` rows, `"Module:Name"` or codes such as `VIEW_USERS`) and the tenant's **plan feature
|
|
79
|
+
codes**; capabilities and the assistant require them by the same names. Names are normalized
|
|
80
|
+
(`permissionKey`), a name matches in any module unless both sides name one, and a list means "any of".
|
|
81
|
+
|
|
82
|
+
```js
|
|
83
|
+
const context = { ..., permissions: rolePermissions(roleRows), features: enabledFeatureCodes };
|
|
84
|
+
defineCapability({ ..., requires: { permission: "Generate Order Report", feature: "ACCESS_ORDER" } });
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`requires` on `createAiAssistant` (for example `AI_ASSISTANT_PERMISSION`) is checked on every reply and
|
|
88
|
+
conversation call before any history or model access.
|
|
89
|
+
|
|
90
|
+
## Context
|
|
91
|
+
|
|
92
|
+
```js
|
|
93
|
+
const context = {
|
|
94
|
+
applicationId: "ecommerce-admin", tenantId: "t-42", actor: { userId: "u-7" }, requestId: "r-1",
|
|
95
|
+
permittedTasks: ["assistant.route", "assistant.respond", "analytics.plan"],
|
|
96
|
+
dataClassification: "INTERNAL", permissions: ["Order Management:Generate Order Report"], features: ["ACCESS_ORDER"],
|
|
97
|
+
};
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Built by the consumer from its own authenticated request, never from the client or the model. Strict and
|
|
101
|
+
frozen; tasks, permissions, features and classification are checked before any model call.
|
|
102
|
+
|
|
103
|
+
## Analytics
|
|
104
|
+
|
|
105
|
+
```js
|
|
106
|
+
const validator = createPostgresSqlValidator(defineSqlPolicy({ dialect: "postgres", schema, policy })); // "@b2y/ai-service/text-to-sql/postgres"
|
|
107
|
+
const analytics = createAnalyticsAssistant({ ai, validator, catalog: defineAnalyticsCatalog({ metrics, dimensions }), executor });
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
The model plans 1-4 statements; each passes the AST validator (allowed tables, columns and values,
|
|
111
|
+
parameterised literals, row limit, no joins or UNION unless the policy allows them) before the consumer's
|
|
112
|
+
read-only executor runs it. Results are merged, charted and described in code and never reach the model.
|
|
113
|
+
|
|
114
|
+
## Conversations
|
|
115
|
+
|
|
116
|
+
```js
|
|
117
|
+
const history = createConversationHistory({ store: createFolderConversationStore({ root }), retentionDays: 14 }); // 7-14
|
|
118
|
+
scheduleConversationCleanup({ history });
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Scoped to application, tenant and user from the context. Data-based answers are never shown to the model
|
|
122
|
+
again; no credentials or grants are stored. Expired conversations are deleted by the cleanup.
|
|
123
|
+
|
|
124
|
+
## Chat UI
|
|
125
|
+
|
|
126
|
+
```jsx
|
|
127
|
+
const client = createAssistantClient({ baseUrl, headers: () => ({ Authorization, "tenant-domain": domain }) });
|
|
128
|
+
<AssistantWidget client={client} onOpenLink={navigate} /> // floating launcher + panel
|
|
129
|
+
<AssistantChat send={client.send} loadConversation={client.loadConversation} listConversations={client.listConversations} />
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Restores the latest server-side conversation, New chat, recent chats, typing indicator, retry. Theme with
|
|
133
|
+
`--b2y-ai-*` CSS variables (`--b2y-ai-icon-accent` for the bot's teal); the launcher bot tilts, blinks and its
|
|
134
|
+
signal pulses, except for users who prefer reduced motion.
|
|
135
|
+
|
|
136
|
+
## Rate limits
|
|
137
|
+
|
|
138
|
+
HTTP 429 is `PROVIDER_RATE_LIMITED`. One retry only when Retry-After is at most 5 s; afterwards calls fail
|
|
139
|
+
fast without reaching the provider until the wait has passed (at most one minute). Show users
|
|
140
|
+
`aiUserMessage(error)`; log `rateLimitInfo(error)`.
|
|
141
|
+
|
|
142
|
+
## Security
|
|
143
|
+
|
|
144
|
+
- Only read-only capabilities; the model never chooses tenant, scope or permissions.
|
|
145
|
+
- Untrusted data is JSON-encoded in one `<untrusted_data>` block; output must be a complete JSON document
|
|
146
|
+
matching a strict schema.
|
|
147
|
+
- The provider only on approved hosts (`api.groq.com`), HTTPS, no redirects; request and response size
|
|
148
|
+
limits and timeouts.
|
|
149
|
+
- Errors and logs carry codes, counts and statuses only, never prompts, output or credentials.
|
|
150
|
+
|
|
151
|
+
## Install
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
npm install @b2y/ai-service
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Peer dependencies, installed by the applications that need them: `react` (chat UI), `libpg-query` (SQL
|
|
158
|
+
validator), `unpdf` (PDF text). Node.js 20.19 or later.
|
|
159
|
+
|
|
160
|
+
## Release
|
|
161
|
+
|
|
162
|
+
1. Raise `version` in `package.json` (semantic versioning; the first release is 1.0.0).
|
|
163
|
+
2. `npm ci && npm run verify` locally.
|
|
164
|
+
3. Run the Jenkins job with `ACTION=publish`. It builds the `Dockerfile` (locked install, checks, `npm pack`),
|
|
165
|
+
archives the package, refuses a version that is already on npm, and publishes with the `npm-publish-token`
|
|
166
|
+
credential (an npm automation token with publish rights to `@b2y`). `ACTION=verify` stops before publishing.
|
package/package.json
CHANGED
|
@@ -1,6 +1,78 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@b2y/ai-service",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Shared AI assistant (Beya) for B2Y applications: global tenant and role/permission access, one provider and model configuration, read-only data, analytics, search and document capabilities, conversation history, server endpoints and a React chat UI and widget.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"b2y",
|
|
7
|
+
"ai",
|
|
8
|
+
"assistant",
|
|
9
|
+
"beya",
|
|
10
|
+
"text-to-sql",
|
|
11
|
+
"analytics",
|
|
12
|
+
"chat"
|
|
13
|
+
],
|
|
14
|
+
"author": "B2Y Infy Solutions",
|
|
15
|
+
"license": "UNLICENSED",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/yuvakrishna29/AI-service.git"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/yuvakrishna29/AI-service/issues"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://github.com/yuvakrishna29/AI-service#readme",
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"type": "module",
|
|
28
|
+
"main": "./src/index.js",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": "./src/index.js",
|
|
31
|
+
"./text-to-sql/postgres": "./src/sql/PostgresSqlValidator.js",
|
|
32
|
+
"./documents/pdf": "./src/documents/PdfText.js",
|
|
33
|
+
"./documents/folder": "./src/documents/FolderDocumentStore.js",
|
|
34
|
+
"./conversations/folder": "./src/conversations/FolderConversationStore.js",
|
|
35
|
+
"./server": "./src/server/Server.js",
|
|
36
|
+
"./ui/react": "./src/ui/react/AssistantChat.js",
|
|
37
|
+
"./ui/react/styles.css": "./src/ui/react/styles.css",
|
|
38
|
+
"./package.json": "./package.json"
|
|
39
|
+
},
|
|
40
|
+
"files": [
|
|
41
|
+
"src"
|
|
42
|
+
],
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=20.19.0"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"lint": "eslint .",
|
|
48
|
+
"verify": "npm run lint",
|
|
49
|
+
"prepublishOnly": "npm run verify"
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"zod": "4.6.7"
|
|
53
|
+
},
|
|
54
|
+
"peerDependencies": {
|
|
55
|
+
"libpg-query": "^17.8.2",
|
|
56
|
+
"react": ">=18",
|
|
57
|
+
"unpdf": "^1.9.1"
|
|
58
|
+
},
|
|
59
|
+
"peerDependenciesMeta": {
|
|
60
|
+
"libpg-query": {
|
|
61
|
+
"optional": true
|
|
62
|
+
},
|
|
63
|
+
"unpdf": {
|
|
64
|
+
"optional": true
|
|
65
|
+
},
|
|
66
|
+
"react": {
|
|
67
|
+
"optional": true
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
"devDependencies": {
|
|
71
|
+
"@eslint/js": "10.0.1",
|
|
72
|
+
"eslint": "10.14.0",
|
|
73
|
+
"libpg-query": "17.8.2",
|
|
74
|
+
"react": "18.3.1",
|
|
75
|
+
"react-dom": "18.3.1",
|
|
76
|
+
"unpdf": "1.9.1"
|
|
77
|
+
}
|
|
78
|
+
}
|