@ray-js/t-agent-plugin-aistream 0.2.7 → 0.2.8-beta.2

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.
@@ -7,7 +7,7 @@ import { EmitterEvent, generateId, safeParseJSON, StreamResponse } from '@ray-js
7
7
  import { tryCatch } from './misc';
8
8
  import { AIStreamError, transformErrorCode } from './errors';
9
9
  import logger from './logger';
10
- import { deepMerge } from './object';
10
+ import { deepmerge } from '@ray-js/t-agent';
11
11
  const mimeTypeToFormatMap = {
12
12
  'video/mp4': FileFormat.MP4,
13
13
  'text/json': FileFormat.JSON,
@@ -65,8 +65,10 @@ export function sendBlocksToAIStream(params) {
65
65
  if (!closed) {
66
66
  logger.debug('sendBlocksToAIStream close');
67
67
  closed = true;
68
- if (!canceled && !(signal !== null && signal !== void 0 && signal.aborted)) {
68
+ try {
69
69
  controller.close();
70
+ } catch (error) {
71
+ logger.debug('sendBlocksToAIStream close ignored', error);
70
72
  }
71
73
  }
72
74
  };
@@ -116,7 +118,7 @@ export function sendBlocksToAIStream(params) {
116
118
  if (getUserData) {
117
119
  eventUserData = await getUserData();
118
120
  }
119
- const userData = deepMerge({
121
+ const userData = deepmerge({
120
122
  chatAttributes
121
123
  }, eventUserData);
122
124
  let error;
@@ -251,7 +253,7 @@ export function sendBlocksToAIStream(params) {
251
253
  if (data.body.sessionState === SessionState.CLOSED || data.body.sessionState === SessionState.CREATE_FAILED) {
252
254
  const msg = SessionState[data.body.sessionState];
253
255
  const e = new AIStreamError("Session Error: ".concat(msg, ", (original_code: ").concat(data.body.code, ")"), transformErrorCode(data.body.code));
254
- emitError(error);
256
+ emitError(e);
255
257
  if (audioEmitter) {
256
258
  audioEmitter.dispatchEvent(new EmitterEvent('error', {
257
259
  detail: e
@@ -262,7 +264,7 @@ export function sendBlocksToAIStream(params) {
262
264
  } else if (data.type === 'connectionState') {
263
265
  if (data.body.connectState === ConnectState.DISCONNECTED || data.body.connectState === ConnectState.CLOSED) {
264
266
  const e = new AIStreamError("Session disconnected, (original_code: ".concat(data.body.code, ")"), transformErrorCode(data.body.code));
265
- emitError(error);
267
+ emitError(e);
266
268
  if (audioEmitter) {
267
269
  audioEmitter.dispatchEvent(new EmitterEvent('error', {
268
270
  detail: e
@@ -303,14 +305,14 @@ export function sendBlocksToAIStream(params) {
303
305
  } else if (block.type === 'file_path') {
304
306
  event.write({
305
307
  type: 'file',
306
- format: mimeTypeToFormatMap[block.file_url.mimeType] || 0,
308
+ format: mimeTypeToFormatMap[block.file_path.mimeType] || 0,
307
309
  path: block.file_path.path
308
310
  }).catch(emitError);
309
311
  } else if (block.type === 'video_path') {
310
312
  event.write({
311
313
  type: 'file',
312
314
  format: FileFormat.MP4,
313
- path: block.file_path.path
315
+ path: block.video_path.path
314
316
  }).catch(emitError);
315
317
  }
316
318
  }
@@ -1,5 +1,5 @@
1
1
  import "core-js/modules/es.json.stringify.js";
2
- import { getAccountInfo, sendEvent } from './ttt';
2
+ import { getAccountInfo, sendTrackEvent } from './ttt';
3
3
  const eventId = 'thing_jKaquNvaV2qMDvTpKcNQvb1ZppBZnlNq';
4
4
  let accountInfoPromise = null;
5
5
  export async function trackEvent(agent_code, type) {
@@ -11,7 +11,7 @@ export async function trackEvent(agent_code, type) {
11
11
  miniProgram
12
12
  } = await accountInfoPromise;
13
13
  try {
14
- await sendEvent({
14
+ await sendTrackEvent({
15
15
  eventId,
16
16
  event: {
17
17
  type,
@@ -1,4 +1,4 @@
1
- import { ApiRequestByAtopParams, ApiRequestByHighwayParams, AudioBody, AuthorizeParams, AuthorizePolicyStatusParams, CanIUseRouterParams, CloseSessionParams, ConnectParams, ConnectStateBody, CreateSessionParams, DeleteRecordListParams, DisconnectParams, EventBody, EventChannelMessageParams, GetAppInfoParams, GetCurrentHomeInfoParams, GetMiniAppConfigParams, GetAccountInfoParams, ImageBody, InsertRecordParams, NavigateToMiniProgramParams, OpenInnerH5Params, OpenMiniWidgetParams, QueryAgentTokenParams, QueryRecordListParams, RecordAmplitudesBody, RegisterChannelParams, RouterParams, SendEventChatBreakParams, SendEventEndParams, SendEventPayloadEndParams, SendEventStartParams, SendImageDataParams, SendTextDataParams, SessionStateBody, StartRecordAndSendAudioDataParams, StopRecordAndSendAudioDataParams, TextBody, UpdateRecordParams, IsConnectedParams, GetNetworkTypeParams, StartPlayAudioParams, InitAudioRecorderParams, StopPlayAudioParams, AudioPlayChangedBody, EventParams } from '../AIStreamTypes';
1
+ import { ApiRequestByAtopParams, ApiRequestByHighwayParams, AudioBody, AuthorizeParams, AuthorizePolicyStatusParams, CanIUseRouterParams, CloseSessionParams, ConnectParams, ConnectStateBody, CreateSessionParams, DeleteRecordListParams, DisconnectParams, EventBody, EventChannelMessageParams, GetAppInfoParams, GetCurrentHomeInfoParams, GetMiniAppConfigParams, GetAccountInfoParams, ImageBody, InsertRecordParams, NavigateToMiniProgramParams, OpenInnerH5Params, OpenMiniWidgetParams, QueryAgentTokenParams, QueryRecordListParams, RecordAmplitudesBody, RegisterChannelParams, RouterParams, SendAIStreamEventParams, SendEventChatBreakParams, SendEventEndParams, SendEventPayloadEndParams, SendEventStartParams, SendImageDataParams, SendTextDataParams, SessionStateBody, StartRecordAndSendAudioDataParams, StopRecordAndSendAudioDataParams, TextBody, UpdateRecordParams, IsConnectedParams, GetNetworkTypeParams, StartPlayAudioParams, InitAudioRecorderParams, StopPlayAudioParams, AudioPlayChangedBody, EventParams } from '../AIStreamTypes';
2
2
  export declare const getMiniAppConfig: (options?: Omit<GetMiniAppConfigParams, "success" | "fail"> | undefined) => Promise<{
3
3
  config: any;
4
4
  }>;
@@ -36,11 +36,11 @@ export declare const getAppInfo: (options?: Omit<GetAppInfoParams, "success" | "
36
36
  regionCode: string;
37
37
  appName: string;
38
38
  appIcon: string;
39
- appEnv?: number | undefined;
39
+ appEnv?: number;
40
40
  appBundleId: string;
41
41
  appScheme: string;
42
42
  appId: string;
43
- clientId?: string | undefined;
43
+ clientId?: string;
44
44
  }>;
45
45
  export declare const canIUseRouter: (options?: Omit<CanIUseRouterParams, "success" | "fail"> | undefined) => Promise<{
46
46
  result: boolean;
@@ -57,7 +57,7 @@ export declare const openMiniWidget: (options?: Omit<OpenMiniWidgetParams, "succ
57
57
  export declare const isConnected: (options?: Omit<IsConnectedParams, "success" | "fail"> | undefined) => Promise<{
58
58
  connected: boolean;
59
59
  state: number;
60
- connectionId?: string | undefined;
60
+ connectionId?: string;
61
61
  }>;
62
62
  export declare const connect: (options?: Omit<ConnectParams, "success" | "fail"> | undefined) => Promise<{
63
63
  connectionId: string;
@@ -66,7 +66,7 @@ export declare const disconnect: (options?: Omit<DisconnectParams, "success" | "
66
66
  export declare const queryAgentToken: (options?: Omit<QueryAgentTokenParams, "success" | "fail"> | undefined) => Promise<{
67
67
  agentToken: string;
68
68
  bizConfig: import("../AIStreamTypes").BizConfig;
69
- extParams?: string | undefined;
69
+ extParams?: string;
70
70
  }>;
71
71
  export declare const createSession: (options?: Omit<CreateSessionParams, "success" | "fail"> | undefined) => Promise<{
72
72
  sessionId: string;
@@ -81,6 +81,7 @@ export declare const sendEventStart: (options?: Omit<SendEventStartParams, "succ
81
81
  export declare const sendEventPayloadEnd: (options?: Omit<SendEventPayloadEndParams, "success" | "fail"> | undefined) => Promise<null>;
82
82
  export declare const sendEventEnd: (options?: Omit<SendEventEndParams, "success" | "fail"> | undefined) => Promise<null>;
83
83
  export declare const sendEventChatBreak: (options?: Omit<SendEventChatBreakParams, "success" | "fail"> | undefined) => Promise<null>;
84
+ export declare const sendEventToAIStream: (options?: Omit<SendAIStreamEventParams, "success" | "fail"> | undefined) => Promise<null>;
84
85
  export declare const startRecordAndSendAudioData: (options?: Omit<StartRecordAndSendAudioDataParams, "success" | "fail"> | undefined) => Promise<null>;
85
86
  export declare const stopRecordAndSendAudioData: (options?: Omit<StopRecordAndSendAudioDataParams, "success" | "fail"> | undefined) => Promise<import("../AIStreamTypes").AIStreamAudioFile | null>;
86
87
  export declare const sendImageData: (options?: Omit<SendImageDataParams, "success" | "fail"> | undefined) => Promise<null>;
@@ -113,4 +114,4 @@ export declare const getNetworkType: (options?: Omit<GetNetworkTypeParams, "succ
113
114
  networkType: import("../AIStreamTypes").NetworkType;
114
115
  signalStrength: number;
115
116
  }>;
116
- export declare const sendEvent: (options?: Omit<EventParams, "success" | "fail"> | undefined) => Promise<null>;
117
+ export declare const sendTrackEvent: (options?: Omit<EventParams, "success" | "fail"> | undefined) => Promise<null>;
package/dist/utils/ttt.js CHANGED
@@ -42,6 +42,7 @@ export const sendEventStart = promisify(ty.aistream.sendEventStart, true);
42
42
  export const sendEventPayloadEnd = promisify(ty.aistream.sendEventPayloadEnd, true);
43
43
  export const sendEventEnd = promisify(ty.aistream.sendEventEnd, true);
44
44
  export const sendEventChatBreak = promisify(ty.aistream.sendEventChatBreak, true);
45
+ export const sendEventToAIStream = promisify(ty.aistream.sendEvent, true);
45
46
  export const startRecordAndSendAudioData = promisify(ty.aistream.startRecordAndSendAudioData, true);
46
47
  export const stopRecordAndSendAudioData = promisify(ty.aistream.stopRecordAndSendAudioData, true);
47
48
 
@@ -92,4 +93,4 @@ export const deleteRecordList = promisify(ty.aistream.deleteRecordList, true);
92
93
  export const updateRecord = promisify(ty.aistream.updateRecord, true);
93
94
  export const insertRecord = promisify(ty.aistream.insertRecord, true);
94
95
  export const getNetworkType = promisify(ty.getNetworkType, true);
95
- export const sendEvent = promisify(ty.event);
96
+ export const sendTrackEvent = promisify(ty.event);
@@ -1,6 +1,6 @@
1
1
  import { AbortSignalObject, ChatAgent, ChatCardObject, ChatMessage, ChatMessageStatus, ChatTile, GetChatPluginHandler, InputBlock } from '@ray-js/t-agent';
2
2
  import { TTTAction } from './utils';
3
- import { AIStreamUserData, ConnectClientType, ReceivedTextSkillPacketBody } from './AIStreamTypes';
3
+ import { AIStreamUserData, ConnectClientType, ReceivedTextSkillPacketBody, SendAIStreamEventParams, SessionEventBody } from './AIStreamTypes';
4
4
  import { ChatHistoryStore, StoredMessageObject } from './ChatHistoryStore';
5
5
  export interface AIStreamOptions {
6
6
  /** client 类型: 1-作为设备代理, 2-作为 App,3-作为开发者(行业 App) */
@@ -63,6 +63,7 @@ export interface AIStreamHooks {
63
63
  }, result: {
64
64
  userData: AIStreamUserData;
65
65
  }) => void;
66
+ onSessionEventReceived: (event: SessionEventBody) => void;
66
67
  }
67
68
  export declare function withAIStream(options?: AIStreamOptions): (agent: ChatAgent) => {
68
69
  hooks: import("hookable").Hookable<AIStreamHooks, import("hookable").HookKeys<AIStreamHooks>>;
@@ -72,10 +73,10 @@ export declare function withAIStream(options?: AIStreamOptions): (agent: ChatAge
72
73
  metaPromise: Promise<Record<string, any>>;
73
74
  };
74
75
  chat: (blocks: InputBlock[], signal?: AbortSignalObject, options?: {
75
- sendBy?: string | undefined;
76
- responseBy?: string | undefined;
77
- userData?: AIStreamUserData | undefined;
78
- } | undefined) => Promise<ChatMessage[]>;
76
+ sendBy?: string;
77
+ responseBy?: string;
78
+ userData?: AIStreamUserData;
79
+ }) => Promise<ChatMessage[]>;
79
80
  options: AIStreamOptions;
80
81
  removeMessage: (message: ChatMessage) => Promise<void>;
81
82
  clearAllMessages: () => Promise<void>;
@@ -86,13 +87,15 @@ export declare function withAIStream(options?: AIStreamOptions): (agent: ChatAge
86
87
  thingjson?: any;
87
88
  data: string;
88
89
  }>;
89
- onSkillCompose: (fn: AIStreamHooks['onSkillCompose']) => () => void;
90
- onChatMessageSent: (fn: AIStreamHooks['onChatMessageSent']) => () => void;
91
- onTextCompose: (fn: AIStreamHooks['onTextCompose']) => () => void;
92
- onSkillsEnd: (fn: AIStreamHooks['onSkillsEnd']) => () => void;
93
- onCardsReceived: (fn: AIStreamHooks['onCardsReceived']) => () => void;
94
- onUserDataRead: (fn: AIStreamHooks['onUserDataRead']) => () => void;
95
- onTTTAction: (fn: AIStreamHooks['onTTTAction']) => () => void;
90
+ onSkillCompose: (fn: AIStreamHooks["onSkillCompose"]) => () => void;
91
+ onChatMessageSent: (fn: AIStreamHooks["onChatMessageSent"]) => () => void;
92
+ onTextCompose: (fn: AIStreamHooks["onTextCompose"]) => () => void;
93
+ onSkillsEnd: (fn: AIStreamHooks["onSkillsEnd"]) => () => void;
94
+ onCardsReceived: (fn: AIStreamHooks["onCardsReceived"]) => () => void;
95
+ onUserDataRead: (fn: AIStreamHooks["onUserDataRead"]) => () => void;
96
+ onSessionEventReceived: (fn: AIStreamHooks["onSessionEventReceived"]) => () => void;
97
+ sendEvent: (params: SendAIStreamEventParams) => Promise<null>;
98
+ onTTTAction: (fn: AIStreamHooks["onTTTAction"]) => () => void;
96
99
  getChatId: () => Promise<string>;
97
100
  };
98
101
  };
@@ -16,12 +16,12 @@ function _asyncIterator(r) { var n, t, o, e = 2; for ("undefined" != typeof Symb
16
16
  function AsyncFromSyncIterator(r) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); var n = r.done; return Promise.resolve(r.value).then(function (r) { return { value: r, done: n }; }); } return AsyncFromSyncIterator = function (r) { this.s = r, this.n = r.next; }, AsyncFromSyncIterator.prototype = { s: null, n: null, next: function () { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, return: function (r) { var n = this.s.return; return void 0 === n ? Promise.resolve({ value: r, done: !0 }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); }, throw: function (r) { var n = this.s.return; return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); } }, new AsyncFromSyncIterator(r); }
17
17
  import { BubbleTileStatus, ChatMessageStatus, createHooks, EmitterEvent } from '@ray-js/t-agent';
18
18
  import { messageAppraise } from './utils/apis';
19
- import { getAccountInfo, getCurrentHomeInfo, runTTTAction, sendBlocksToAIStream } from './utils';
19
+ import { getAccountInfo, getCurrentHomeInfo, runTTTAction, sendBlocksToAIStream, sendEventToAIStream } from './utils';
20
20
  import { BizCode, ConnectClientType } from './AIStreamTypes';
21
21
  import { DEFAULT_TOKEN_API, DEFAULT_TOKEN_API_VERSION, globalAIStreamClient } from './global';
22
22
  import logger from './utils/logger';
23
23
  import { ChatHistoryLocalStore } from './ChatHistoryLocalStore';
24
- import { deepMerge } from './utils/object';
24
+ import { deepmerge } from '@ray-js/t-agent';
25
25
  import { trackEvent } from './utils/track';
26
26
  export function withAIStream() {
27
27
  let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
@@ -110,6 +110,9 @@ export function withAIStream() {
110
110
  return result.userData;
111
111
  }
112
112
  });
113
+ streamSession.on('sessionEvent', event => {
114
+ hooks.callHook('onSessionEventReceived', event);
115
+ });
113
116
  await session.set('AIStream.streamSession', streamSession);
114
117
  if (options.earlyStart) {
115
118
  // 故意异步,不阻塞消息列表加载
@@ -255,9 +258,8 @@ export function withAIStream() {
255
258
  await hooks.callHook('onUserDataRead', 'start-event', {
256
259
  blocks
257
260
  }, userDataResult);
258
- const userData = {};
259
- deepMerge(userData, userDataResult.userData);
260
- deepMerge(userData, eventUserData);
261
+ let userData = deepmerge({}, userDataResult.userData);
262
+ userData = deepmerge(userData, eventUserData);
261
263
  return userData;
262
264
  }
263
265
  });
@@ -609,7 +611,7 @@ export function withAIStream() {
609
611
  }
610
612
  }
611
613
  if ((_skill$general = skill.general) !== null && _skill$general !== void 0 && (_skill$general = _skill$general.data) !== null && _skill$general !== void 0 && _skill$general.aiCards) {
612
- for (const card of skill.custom.data.aiCards) {
614
+ for (const card of skill.general.data.aiCards) {
613
615
  cards.push(card);
614
616
  }
615
617
  }
@@ -659,6 +661,10 @@ export function withAIStream() {
659
661
  onUserDataRead: fn => {
660
662
  return hooks.hook('onUserDataRead', fn);
661
663
  },
664
+ onSessionEventReceived: fn => {
665
+ return hooks.hook('onSessionEventReceived', fn);
666
+ },
667
+ sendEvent: params => sendEventToAIStream(params),
662
668
  onTTTAction: fn => {
663
669
  return hooks.hook('onTTTAction', fn);
664
670
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ray-js/t-agent-plugin-aistream",
3
- "version": "0.2.7",
3
+ "version": "0.2.8-beta.2",
4
4
  "author": "Tuya.inc",
5
5
  "license": "MIT",
6
6
  "private": false,
@@ -21,7 +21,9 @@
21
21
  "scripts": {
22
22
  "dev": "ray start --type=component --output dist --emit-declaration-dev",
23
23
  "build": "ray build --type=component --output dist",
24
- "clean": "rimraf ./dist"
24
+ "clean": "rimraf ./dist",
25
+ "test": "jest --runInBand",
26
+ "test:coverage": "jest --runInBand --coverage"
25
27
  },
26
28
  "dependencies": {
27
29
  "dayjs": "^1.10.4",
@@ -35,5 +37,5 @@
35
37
  "devDependencies": {
36
38
  "@types/url-parse": "^1.4.11"
37
39
  },
38
- "gitHead": "3afabdd5b9a063d70157f69158ef8edccfdac012"
40
+ "gitHead": "450ca8d41536094b3bea57198fd7724ba6812438"
39
41
  }