@glodon-aiot/bot-client-sdk 3.3.0-beta.13

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.
Files changed (37) hide show
  1. package/README.md +157 -0
  2. package/dist/agent-cli-sdk.js +33141 -0
  3. package/dist/agent-cli-sdk.umd.cjs +140 -0
  4. package/dist/es/AgentPlugin.mjs +20 -0
  5. package/dist/es/AgentSession.mjs +285 -0
  6. package/dist/es/BotClient.mjs +250 -0
  7. package/dist/es/Config.mjs +36 -0
  8. package/dist/es/DialogSession.mjs +301 -0
  9. package/dist/es/EventBus.mjs +64 -0
  10. package/dist/es/Logger.mjs +31 -0
  11. package/dist/es/PayloadTypes.mjs +4 -0
  12. package/dist/es/Session.mjs +683 -0
  13. package/dist/es/api/fetchEventSource/fetch.mjs +112 -0
  14. package/dist/es/api/fetchEventSource/parse.mjs +97 -0
  15. package/dist/es/api/index.mjs +41 -0
  16. package/dist/es/index.mjs +11 -0
  17. package/dist/es/utils.mjs +11 -0
  18. package/dist/lib/index.js +4 -0
  19. package/dist/src/AgentPlugin.d.ts +17 -0
  20. package/dist/src/AgentSession.d.ts +13 -0
  21. package/dist/src/BotClient.d.ts +48 -0
  22. package/dist/src/Config.d.ts +46 -0
  23. package/dist/src/DialogSession.d.ts +26 -0
  24. package/dist/src/EventBus.d.ts +23 -0
  25. package/dist/src/Logger.d.ts +12 -0
  26. package/dist/src/PayloadTypes.d.ts +84 -0
  27. package/dist/src/Session.d.ts +222 -0
  28. package/dist/src/__ tests __/AgentClient.spec.d.ts +1 -0
  29. package/dist/src/__ tests __/AgentSession.spec.d.ts +1 -0
  30. package/dist/src/__ tests __/DialogClient.spec.d.ts +1 -0
  31. package/dist/src/api/fetchEventSource/fetch.d.ts +44 -0
  32. package/dist/src/api/fetchEventSource/index.d.ts +1 -0
  33. package/dist/src/api/fetchEventSource/parse.d.ts +36 -0
  34. package/dist/src/api/index.d.ts +2 -0
  35. package/dist/src/index.d.ts +5 -0
  36. package/dist/src/utils.d.ts +4 -0
  37. package/package.json +90 -0
@@ -0,0 +1,222 @@
1
+ import { ChatMessageRole, IApplication, IChatMessage, ICommentParam, ISession, ISessionPrompt, CVForceApi, ChatHistoryParams, IKnowledge } from '@glodon-aiot/apis';
2
+ import { MCPConfig } from './Config';
3
+ import { Socket } from 'socket.io-client';
4
+ import { default as EventBus } from './EventBus';
5
+ import { ActionPayload, PluginFunctionBasic, Thought } from './PayloadTypes';
6
+ import { default as BotClient } from './BotClient';
7
+ export declare enum NetOpen {
8
+ enable = 1,
9
+ disable = 2
10
+ }
11
+ export interface QuestionBody {
12
+ content: string;
13
+ stream: boolean;
14
+ requestId?: string;
15
+ fileIds?: string[];
16
+ oldMessageId?: string;
17
+ referenceFirst?: boolean;
18
+ }
19
+ export interface QuestionConfig {
20
+ stream?: boolean;
21
+ referenceFirst?: boolean;
22
+ formatValues?: any;
23
+ oldMessageId?: string;
24
+ }
25
+ type ActionPayloadBasic = ActionPayload<PluginFunctionBasic & Thought>;
26
+ export type SessionEventName = 'init' | 'ready' | 'activated' | 'inactivated' | 'frozen' | 'data:loading' | 'data:loaded' | 'data:updating' | 'data:updated' | 'data:updated:promptVariables' | 'data:updated:knowledges' | 'data:creating' | 'data:created' | 'data:deleting' | 'data:deleted' | 'socket:connect' | 'socket:disconnect' | 'error' | 'destroy' | 'history:loading' | 'history:loaded' | 'history:moreloading' | 'history:moreloaded' | 'history:add' | 'message:new' | 'message:updated' | 'message:action' | 'message:content' | 'message:reference' | 'message:relatedQuesion:loading' | 'message:relatedQuesion:loaded' | 'message:comment' | 'message:error' | 'answer:finish';
27
+ export declare enum SessionErrors {
28
+ DataRequestFailed = "data request error",
29
+ SocketConnectionFailed = "socket error",
30
+ IdUndefined = "session id is not defined",
31
+ SendingEmptyContent = "failed at sending empty content",
32
+ Frozen = "session is frozen",
33
+ UserModeError = "failed at setting socket user mode",
34
+ Inactive = "session is inactive"
35
+ }
36
+ export declare const SESSION_ERROR_CAUSE: {
37
+ "session id is not defined": {
38
+ code: number;
39
+ message: string;
40
+ };
41
+ "failed at sending empty content": {
42
+ code: number;
43
+ message: string;
44
+ };
45
+ "session is frozen": {
46
+ code: number;
47
+ message: string;
48
+ };
49
+ };
50
+ export default abstract class Session {
51
+ protected token: string;
52
+ protected lazyload?: boolean | undefined;
53
+ protected _id?: string;
54
+ protected _frozen: boolean;
55
+ protected inactivating: boolean;
56
+ protected _ready: boolean;
57
+ protected event: EventBus;
58
+ _applicationId: string;
59
+ _application: IApplication | null;
60
+ data: ISession | null;
61
+ readonly client: BotClient | null;
62
+ messages: IChatMessage[];
63
+ protected _loadingMessages: boolean;
64
+ protected _loadingMessagesSize: number;
65
+ cvforceApi: CVForceApi;
66
+ socket: Socket | null;
67
+ protected _promptVariables: ISessionPrompt[];
68
+ protected active: boolean;
69
+ protected activing: boolean;
70
+ protected _stopAnswer: boolean;
71
+ private _dataLoading;
72
+ private _dataLoaded;
73
+ protected _mcpServers: MCPConfig | null;
74
+ /**
75
+ * Session 类的构造函数,用于初始化会话实例。
76
+ * @param token - 用户的身份验证令牌,用于解析应用 ID。
77
+ * @param _id - 会话的 ID,可选参数,默认为空字符串。
78
+ * @param _data - 会话的初始数据,可选参数,包含提示变量、知识库等信息。
79
+ * @param lazyload - 是否懒加载数据,可选参数,默认为 undefined。
80
+ * @param _application - 应用信息,可选参数。
81
+ * @param client - Bot 客户端实例,可选参数。
82
+ */
83
+ constructor(token: string, _id?: string, _data?: Partial<ISession & {
84
+ promptVariables?: Partial<ISessionPrompt>[];
85
+ }>, lazyload?: boolean | undefined, _application?: IApplication, client?: BotClient);
86
+ fetchData(): Promise<ISession>;
87
+ get id(): string;
88
+ get applicationId(): string;
89
+ get application(): IApplication | null;
90
+ set application(v: IApplication | null);
91
+ loadApplicationInfo(): Promise<IApplication>;
92
+ get ready(): boolean;
93
+ get frozen(): boolean;
94
+ protected set frozen(v: boolean);
95
+ get knowledges(): IKnowledge[] | undefined;
96
+ setKnowledges(knowledges?: IKnowledge[]): Promise<IKnowledge[] | undefined>;
97
+ validateConfigs(): void;
98
+ get promptVariables(): ISessionPrompt[];
99
+ setPromptVariables(v: ISessionPrompt[]): Promise<ISessionPrompt[]>;
100
+ get netOpen(): boolean;
101
+ /**
102
+ * 异步设置会话的网络访问开关状态
103
+ * @param v - 布尔值,表示是否开启网络访问,true 为开启,false 为关闭
104
+ * @returns 如果设置成功,返回最终的网络访问开关状态;若不满足设置条件,则提前返回 undefined
105
+ */
106
+ setNetOpen(v: boolean): Promise<boolean | undefined>;
107
+ private getService;
108
+ addEventListener(eventName: SessionEventName, callback: any, once?: boolean): void;
109
+ removeEventListener(eventName: SessionEventName, callback: any): void;
110
+ /**
111
+ * 获取对话记录
112
+ * @param params ChatHistoryParams
113
+ * @returns Promise<false|Message[]>
114
+ */
115
+ fetchMessages(params?: ChatHistoryParams): Promise<false | {
116
+ actions: ActionPayloadBasic[][];
117
+ relatedQuesion: string[] | undefined;
118
+ ts?: string;
119
+ messageId: string;
120
+ content: string;
121
+ role: ChatMessageRole;
122
+ userId?: string;
123
+ sessionId: string;
124
+ reference: import('@glodon-aiot/apis').IReference[];
125
+ searchReference: import('@glodon-aiot/apis').ISearchRefernce[];
126
+ comment?: import('@glodon-aiot/apis/dist/src/cvforce').ICommentParam;
127
+ knowledges?: IKnowledge[];
128
+ isLoading?: boolean;
129
+ messageTime: string;
130
+ fileId?: string;
131
+ file?: import('@glodon-aiot/apis/dist/src/cvforce').KnowledgeFileMetadata;
132
+ chatMode?: import('@glodon-aiot/apis').ChatMode;
133
+ llmModel?: string;
134
+ isContext?: boolean;
135
+ index?: number;
136
+ agentHistoryList?: {
137
+ agentList: string;
138
+ createdAt: string;
139
+ creator: string;
140
+ deletedAt: string;
141
+ id: string;
142
+ updatedAt: string;
143
+ };
144
+ finish?: boolean;
145
+ code?: number;
146
+ isSensitive?: boolean;
147
+ message?: string;
148
+ stream?: boolean;
149
+ fileIds?: string[];
150
+ isReplying?: boolean;
151
+ files?: import('@glodon-aiot/apis').ChatMessageFile[];
152
+ thinkingSecs?: number;
153
+ thinkingStatus?: "end" | "start";
154
+ reasoningContent?: string;
155
+ searchingStatus?: "start" | "end";
156
+ }[]>;
157
+ rename(name: string): Promise<boolean>;
158
+ protected pushMessage(message: IChatMessage): Promise<void>;
159
+ reloadSessionInfo(): Promise<this>;
160
+ reload(): Promise<unknown>;
161
+ delete(): Promise<string | false>;
162
+ activate(): Promise<unknown>;
163
+ inactivate(immediately?: boolean): boolean;
164
+ abstract prepareConnection(): Promise<boolean>;
165
+ abstract sendQuestion(params: QuestionBody, configs: QuestionConfig): any;
166
+ abstract stopAnswer(): any;
167
+ abstract registerMcpFromClientConfig(): Promise<boolean>;
168
+ abstract addMcpServers(mcpServers: MCPConfig): Promise<boolean>;
169
+ abstract listMcpServers(): Promise<MCPConfig>;
170
+ get dataLoaded(): boolean;
171
+ get messagesLoading(): boolean;
172
+ send(params: {
173
+ text?: string;
174
+ uuid?: string;
175
+ fileIds?: string[];
176
+ }, configs?: QuestionConfig): Promise<false | {
177
+ sessionId: string;
178
+ role: number;
179
+ content: string;
180
+ messageId: string;
181
+ reference: never[];
182
+ searchReference: never[];
183
+ messageTime: string;
184
+ }>;
185
+ protected getRelatedQuesion(message: IChatMessage): Promise<IChatMessage>;
186
+ protected fillMessageReference(message: IChatMessage): Promise<IChatMessage>;
187
+ answerAgain(configs?: QuestionConfig): Promise<void>;
188
+ setTop(top: boolean): Promise<void>;
189
+ /**
190
+ * 暂停当前会话的回答过程
191
+ * 该方法会停止当前回答,标记回答停止状态,处理正在进行的消息和操作,
192
+ * 并根据情况更新消息内容或添加新的系统消息。
193
+ * @returns 返回当前会话实例
194
+ */
195
+ suspend(): this | undefined;
196
+ /**
197
+ * 异步提交评论信息
198
+ * @param params - 评论参数,包含评论相关的信息,如消息 ID 等
199
+ * @returns 返回调用 API 提交评论后的响应结果
200
+ */
201
+ postMessageComment(params: ICommentParam): Promise<string>;
202
+ /**
203
+ * 清除当前会话的上下文信息
204
+ * 该方法会调用 API 清除指定会话的上下文,并在操作成功后触发相应事件
205
+ * @returns 如果会话 ID 存在且清除操作成功,返回一个解析为 true 的 Promise;若会话 ID 不存在,抛出错误
206
+ */
207
+ clear(): Promise<boolean>;
208
+ /**
209
+ * 销毁当前会话实例,执行清理操作并触发销毁事件
210
+ * @returns 返回当前会话的 ID,如果会话 ID 不存在则返回空字符串
211
+ */
212
+ destroy(): string;
213
+ }
214
+ export declare class DialogSession extends Session {
215
+ prepareConnection(): Promise<boolean>;
216
+ sendQuestion(params: QuestionBody, configs: QuestionConfig): Promise<void>;
217
+ stopAnswer(): void;
218
+ registerMcpFromClientConfig(): Promise<boolean>;
219
+ addMcpServers(mcpServers: MCPConfig): Promise<boolean>;
220
+ listMcpServers(): Promise<MCPConfig>;
221
+ }
222
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,44 @@
1
+ import { EventSourceMessage } from './parse';
2
+ export declare const EventStreamContentType = "text/event-stream";
3
+ export interface FetchEventSourceInit extends RequestInit {
4
+ /**
5
+ * The request headers. FetchEventSource only supports the Record<string,string> format.
6
+ */
7
+ headers?: Record<string, string>;
8
+ /**
9
+ * Called when a response is received. Use this to validate that the response
10
+ * actually matches what you expect (and throw if it doesn't.) If not provided,
11
+ * will default to a basic validation to ensure the content-type is text/event-stream.
12
+ */
13
+ onopen?: (response: Response) => Promise<void>;
14
+ /**
15
+ * Called when a message is received. NOTE: Unlike the default browser
16
+ * EventSource.onmessage, this callback is called for _all_ events,
17
+ * even ones with a custom `event` field.
18
+ */
19
+ onmessage?: (ev: EventSourceMessage) => void;
20
+ /**
21
+ * Called when a response finishes. If you don't expect the server to kill
22
+ * the connection, you can throw an exception here and retry using onerror.
23
+ */
24
+ onclose?: () => void;
25
+ /**
26
+ * Called when there is any error making the request / processing messages /
27
+ * handling callbacks etc. Use this to control the retry strategy: if the
28
+ * error is fatal, rethrow the error inside the callback to stop the entire
29
+ * operation. Otherwise, you can return an interval (in milliseconds) after
30
+ * which the request will automatically retry (with the last-event-id).
31
+ * If this callback is not specified, or it returns undefined, fetchEventSource
32
+ * will treat every error as retriable and will try again after 1 second.
33
+ */
34
+ onerror?: (err: any) => number | null | undefined | void;
35
+ /**
36
+ * If true, will keep the request open even if the document is hidden.
37
+ * By default, fetchEventSource will close the request and reopen it
38
+ * automatically when the document becomes visible again.
39
+ */
40
+ openWhenHidden?: boolean;
41
+ /** The Fetch function to use. Defaults to window.fetch */
42
+ fetch?: typeof fetch;
43
+ }
44
+ export declare function fetchEventSource(input: RequestInfo, { signal: inputSignal, headers: inputHeaders, onopen: inputOnOpen, onmessage, onclose, onerror, openWhenHidden, fetch: inputFetch, ...rest }: FetchEventSourceInit): Promise<void>;
@@ -0,0 +1 @@
1
+ export * from './fetch';
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Represents a message sent in an event stream
3
+ * https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format
4
+ */
5
+ export interface EventSourceMessage {
6
+ /** The event ID to set the EventSource object's last event ID value. */
7
+ id: string;
8
+ /** A string identifying the type of event described. */
9
+ event: string;
10
+ /** The event data */
11
+ data: string;
12
+ /** The reconnection interval (in milliseconds) to wait before retrying the connection */
13
+ retry?: number;
14
+ }
15
+ /**
16
+ * Converts a ReadableStream into a callback pattern.
17
+ * @param stream The input ReadableStream.
18
+ * @param onChunk A function that will be called on each new byte chunk in the stream.
19
+ * @returns {Promise<void>} A promise that will be resolved when the stream closes.
20
+ */
21
+ export declare function getBytes(stream: ReadableStream<Uint8Array>, onChunk: (arr: Uint8Array) => void): Promise<void>;
22
+ /**
23
+ * Parses arbitary byte chunks into EventSource line buffers.
24
+ * Each line should be of the format "field: value" and ends with \r, \n, or \r\n.
25
+ * @param onLine A function that will be called on each new EventSource line.
26
+ * @returns A function that should be called for each incoming byte chunk.
27
+ */
28
+ export declare function getLines(onLine: (line: Uint8Array, fieldLength: number, isWrap: boolean) => void): (arr: Uint8Array) => void;
29
+ /**
30
+ * Parses line buffers into EventSourceMessages.
31
+ * @param onId A function that will be called on each `id` field.
32
+ * @param onRetry A function that will be called on each `retry` field.
33
+ * @param onMessage A function that will be called on each message.
34
+ * @returns A function that should be called for each incoming line buffer.
35
+ */
36
+ export declare function getMessages(onId: (id: string) => void, onRetry: (retry: number) => void, onMessage?: (msg: EventSourceMessage) => void): (line: Uint8Array, fieldLength: number, isWrap: boolean) => void;
@@ -0,0 +1,2 @@
1
+ import { CVForceApi } from '@glodon-aiot/apis';
2
+ export declare function getCVForceService(apiBase: string, token: string, errorHandler: (status: number, message: string) => void): CVForceApi;
@@ -0,0 +1,5 @@
1
+ export type { AgentPluginRegistor, AgentPluginMap, MCPConfig, McpServer } from './Config';
2
+ export { configure, configuration } from './Config';
3
+ export { default as BotClient } from './BotClient';
4
+ export { default as Session } from './Session';
5
+ export { default as AgentPlugin } from './AgentPlugin';
@@ -0,0 +1,4 @@
1
+ export declare const parseJWT: (token: string) => any;
2
+ export declare const isExpired: (token: string) => boolean;
3
+ export declare const removeNewlines: (str: string) => string;
4
+ export declare const removeLeadingAndTrailingBackslashes: (str: string) => string;
package/package.json ADDED
@@ -0,0 +1,90 @@
1
+ {
2
+ "name": "@glodon-aiot/bot-client-sdk",
3
+ "version": "3.3.0-beta.13",
4
+ "author": "glodoncv",
5
+ "description": "aiot bot client js sdk",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "keywords": [
9
+ "aiot",
10
+ "bot",
11
+ "bot client",
12
+ "sdk"
13
+ ],
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "module": "./dist/es/index.mjs",
18
+ "main": "./dist/lib/index.js",
19
+ "typings": "./dist/src/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "import": "./dist/es/index.mjs",
23
+ "require": "./dist/lib/index.js",
24
+ "types": "./dist/src/index.d.ts"
25
+ }
26
+ },
27
+ "license": "MIT",
28
+ "scripts": {
29
+ "watch": "yarn build --watch",
30
+ "example": "node ./example/server.js",
31
+ "dev": "npm-run-all -p watch example",
32
+ "start": "vite",
33
+ "build": "tsc && vite build --mode prod && yarn build:cdn",
34
+ "build:npm": "tsc && vite build --mode prod",
35
+ "build:cdn": "tsc && vite build --mode prod --config ./vite.config.cdn.ts",
36
+ "preview": "vite preview",
37
+ "check": "yarn prettier --check .",
38
+ "write": "yarn prettier --write .",
39
+ "lint": "eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js"
40
+ },
41
+ "devDependencies": {
42
+ "@babel/core": "^7.20.12",
43
+ "@commitlint/cli": "^17.0.3",
44
+ "@commitlint/config-conventional": "^17.0.3",
45
+ "@rollup/plugin-babel": "^6.0.4",
46
+ "@rollup/plugin-typescript": "^11.1.6",
47
+ "@types/express": "^4",
48
+ "@types/identity-obj-proxy": "^3",
49
+ "@typescript-eslint/eslint-plugin": "^5.35.1",
50
+ "@typescript-eslint/parser": "^5.35.1",
51
+ "babel-loader": "^8.3.0",
52
+ "eslint": "^8.0.1",
53
+ "eslint-config-prettier": "^8.5.0",
54
+ "eslint-config-standard-with-typescript": "^22.0.0",
55
+ "eslint-plugin-import": "^2.25.2",
56
+ "eslint-plugin-n": "^15.0.0",
57
+ "eslint-plugin-promise": "^6.0.0",
58
+ "eslint-plugin-react": "^7.31.0",
59
+ "eslint-plugin-storybook": "^0.6.10",
60
+ "express": "4",
61
+ "http-proxy-middleware": "^3.0.0",
62
+ "identity-obj-proxy": "^3.0.0",
63
+ "npm-run-all": "^4.1.5",
64
+ "prettier": "2.7.1",
65
+ "rollup-plugin-visualizer": "^6.0.1",
66
+ "socket.io": "^4.7.5",
67
+ "ts-node": "^10.9.2",
68
+ "typescript": "*",
69
+ "vite": "^4.1.1",
70
+ "vite-plugin-dts": "^4.3.0",
71
+ "vite-plugin-externalize-deps": "^0.9.0",
72
+ "vite-tsconfig-paths": "^5.1.4"
73
+ },
74
+ "lint-staged": {
75
+ "*.{js,css,md,jsx,less,ts,tsx,json}": "prettier --write"
76
+ },
77
+ "publishConfig": {
78
+ "access": "public",
79
+ "registry": "https://registry.npmjs.org/"
80
+ },
81
+ "dependencies": {
82
+ "@glodon-aiot/apis": "^3.3.0-beta.13",
83
+ "axios": "0.24.0",
84
+ "buffer": "^6.0.3",
85
+ "dayjs": "^1.11.13",
86
+ "js-base64": "^3.7.7",
87
+ "socket.io-client": "^4.7.5",
88
+ "uuid": "^11.1.0"
89
+ }
90
+ }