@menuia/core 1.2.0 → 1.4.0

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/dist/index.d.mts CHANGED
@@ -27,6 +27,8 @@ interface ChatMessage {
27
27
  createdAt: string;
28
28
  mediaUrl?: string;
29
29
  mediaType?: string;
30
+ /** Nome original do arquivo anexado, quando houver. */
31
+ mediaName?: string;
30
32
  toolCalls?: string;
31
33
  toolResults?: string;
32
34
  authorName?: string;
@@ -52,7 +54,7 @@ interface ChatResponse {
52
54
  };
53
55
  }
54
56
  interface StreamEvent {
55
- type: 'token' | 'tool_start' | 'tool_end' | 'done' | 'error' | 'response';
57
+ type: 'token' | 'thinking' | 'tool_start' | 'tool_done' | 'tool_end' | 'done' | 'error' | 'response';
56
58
  data: unknown;
57
59
  }
58
60
  interface WidgetSession {
@@ -60,6 +62,14 @@ interface WidgetSession {
60
62
  conversationId?: string;
61
63
  ticketId?: string;
62
64
  messages: ChatMessage[];
65
+ /** Signed token returned by startSession, authorizes the message poll */
66
+ widgetToken?: string;
67
+ /** Widget mode resolved from the server (ai/human/hybrid) */
68
+ mode?: 'ai' | 'human' | 'hybrid';
69
+ /** Agent ID resolved from the widget session (widgetId -> agentId) */
70
+ resolvedAgentId?: string;
71
+ /** Whether startSession has already run for this session */
72
+ started?: boolean;
63
73
  }
64
74
 
65
75
  declare class MenuIAClient {
@@ -72,6 +82,14 @@ declare class MenuIAClient {
72
82
  constructor(config: MenuIAConfig);
73
83
  /** Get the effective ID (widgetId preferred, falls back to agentId) */
74
84
  private getWidgetId;
85
+ /** Agent id to use with /chat (resolved from the widget session, or configured directly) */
86
+ private getAgentId;
87
+ /**
88
+ * Resolve the widget session once (widgetId -> agentId + conversationId + token).
89
+ * When only an agentId is configured there is no widget to resolve; /chat is used
90
+ * directly and the conversationId comes back from the first response.
91
+ */
92
+ private ensureSession;
75
93
  /** Send a message to the AI agent */
76
94
  sendMessage(options: SendMessageOptions): Promise<ChatResponse>;
77
95
  /** Send a message and receive streaming response */
package/dist/index.d.ts CHANGED
@@ -27,6 +27,8 @@ interface ChatMessage {
27
27
  createdAt: string;
28
28
  mediaUrl?: string;
29
29
  mediaType?: string;
30
+ /** Nome original do arquivo anexado, quando houver. */
31
+ mediaName?: string;
30
32
  toolCalls?: string;
31
33
  toolResults?: string;
32
34
  authorName?: string;
@@ -52,7 +54,7 @@ interface ChatResponse {
52
54
  };
53
55
  }
54
56
  interface StreamEvent {
55
- type: 'token' | 'tool_start' | 'tool_end' | 'done' | 'error' | 'response';
57
+ type: 'token' | 'thinking' | 'tool_start' | 'tool_done' | 'tool_end' | 'done' | 'error' | 'response';
56
58
  data: unknown;
57
59
  }
58
60
  interface WidgetSession {
@@ -60,6 +62,14 @@ interface WidgetSession {
60
62
  conversationId?: string;
61
63
  ticketId?: string;
62
64
  messages: ChatMessage[];
65
+ /** Signed token returned by startSession, authorizes the message poll */
66
+ widgetToken?: string;
67
+ /** Widget mode resolved from the server (ai/human/hybrid) */
68
+ mode?: 'ai' | 'human' | 'hybrid';
69
+ /** Agent ID resolved from the widget session (widgetId -> agentId) */
70
+ resolvedAgentId?: string;
71
+ /** Whether startSession has already run for this session */
72
+ started?: boolean;
63
73
  }
64
74
 
65
75
  declare class MenuIAClient {
@@ -72,6 +82,14 @@ declare class MenuIAClient {
72
82
  constructor(config: MenuIAConfig);
73
83
  /** Get the effective ID (widgetId preferred, falls back to agentId) */
74
84
  private getWidgetId;
85
+ /** Agent id to use with /chat (resolved from the widget session, or configured directly) */
86
+ private getAgentId;
87
+ /**
88
+ * Resolve the widget session once (widgetId -> agentId + conversationId + token).
89
+ * When only an agentId is configured there is no widget to resolve; /chat is used
90
+ * directly and the conversationId comes back from the first response.
91
+ */
92
+ private ensureSession;
75
93
  /** Send a message to the AI agent */
76
94
  sendMessage(options: SendMessageOptions): Promise<ChatResponse>;
77
95
  /** Send a message and receive streaming response */
package/dist/index.js CHANGED
@@ -48,6 +48,58 @@ var MenuIAClient = class {
48
48
  getWidgetId() {
49
49
  return this.config.widgetId || this.config.agentId || "";
50
50
  }
51
+ /** Agent id to use with /chat (resolved from the widget session, or configured directly) */
52
+ getAgentId() {
53
+ return this.session.resolvedAgentId || this.config.agentId || this.config.widgetId || "";
54
+ }
55
+ /**
56
+ * Resolve the widget session once (widgetId -> agentId + conversationId + token).
57
+ * When only an agentId is configured there is no widget to resolve; /chat is used
58
+ * directly and the conversationId comes back from the first response.
59
+ */
60
+ async ensureSession() {
61
+ if (this.session.started) return;
62
+ if (!this.config.widgetId) {
63
+ this.session.started = true;
64
+ return;
65
+ }
66
+ try {
67
+ const response = await fetch(`${this.config.apiUrl}/widget/${this.config.widgetId}/session`, {
68
+ method: "POST",
69
+ headers: { "Content-Type": "application/json" },
70
+ body: JSON.stringify({
71
+ name: this.config.visitorName || this.config.metadata?.name,
72
+ email: this.config.visitorEmail || this.config.metadata?.email,
73
+ phone: this.config.visitorPhone || this.config.metadata?.phone,
74
+ customData: this.config.customFields,
75
+ sessionId: this.session.sessionId
76
+ })
77
+ });
78
+ if (response.ok) {
79
+ const data = await response.json();
80
+ if (data.conversationId) this.session.conversationId = data.conversationId;
81
+ if (data.ticketId) this.session.ticketId = data.ticketId;
82
+ if (data.agentId) this.session.resolvedAgentId = data.agentId;
83
+ if (data.widgetToken) this.session.widgetToken = data.widgetToken;
84
+ if (data.mode) this.session.mode = data.mode;
85
+ if (Array.isArray(data.messages) && data.messages.length && this.session.messages.length === 0) {
86
+ this.session.messages = data.messages.map((m) => ({
87
+ id: m.id,
88
+ role: m.role,
89
+ content: m.content,
90
+ createdAt: m.createdAt,
91
+ mediaUrl: m.mediaUrl,
92
+ mediaType: m.mediaType,
93
+ authorName: m.authorName
94
+ }));
95
+ this.lastMessageCount = this.session.messages.length;
96
+ }
97
+ }
98
+ } catch {
99
+ }
100
+ this.session.started = true;
101
+ this.saveSession();
102
+ }
51
103
  // =====================
52
104
  // PUBLIC API
53
105
  // =====================
@@ -55,8 +107,9 @@ var MenuIAClient = class {
55
107
  async sendMessage(options) {
56
108
  this.setStatus("connecting");
57
109
  try {
110
+ await this.ensureSession();
58
111
  const body = {
59
- agentId: this.getWidgetId(),
112
+ agentId: this.getAgentId(),
60
113
  message: options.content,
61
114
  channel: this.config.channel,
62
115
  sessionId: this.session.sessionId,
@@ -72,7 +125,7 @@ var MenuIAClient = class {
72
125
  if (options.attachments?.length) {
73
126
  body.attachments = options.attachments;
74
127
  }
75
- const response = await fetch(`${this.config.apiUrl}/widget/message`, {
128
+ const response = await fetch(`${this.config.apiUrl}/chat`, {
76
129
  method: "POST",
77
130
  headers: { "Content-Type": "application/json" },
78
131
  body: JSON.stringify(body)
@@ -117,8 +170,9 @@ var MenuIAClient = class {
117
170
  async sendMessageStream(options, onToken) {
118
171
  this.setStatus("connecting");
119
172
  try {
173
+ await this.ensureSession();
120
174
  const body = {
121
- agentId: this.getWidgetId(),
175
+ agentId: this.getAgentId(),
122
176
  message: options.content,
123
177
  channel: this.config.channel,
124
178
  sessionId: this.session.sessionId,
@@ -134,7 +188,7 @@ var MenuIAClient = class {
134
188
  if (options.attachments?.length) {
135
189
  body.attachments = options.attachments;
136
190
  }
137
- const response = await fetch(`${this.config.apiUrl}/widget/stream`, {
191
+ const response = await fetch(`${this.config.apiUrl}/chat/stream`, {
138
192
  method: "POST",
139
193
  headers: { "Content-Type": "application/json" },
140
194
  body: JSON.stringify(body)
@@ -210,10 +264,14 @@ var MenuIAClient = class {
210
264
  }
211
265
  /** Load conversation history from server */
212
266
  async loadHistory() {
213
- if (!this.session.conversationId) return [];
267
+ await this.ensureSession();
268
+ if (!this.session.conversationId) return this.session.messages;
214
269
  try {
270
+ const params = new URLSearchParams();
271
+ if (this.session.widgetToken) params.set("token", this.session.widgetToken);
272
+ const qs = params.toString();
215
273
  const response = await fetch(
216
- `${this.config.apiUrl}/widget/history/${this.session.sessionId}?agentId=${this.getWidgetId()}`
274
+ `${this.config.apiUrl}/widget/messages/${this.session.conversationId}${qs ? `?${qs}` : ""}`
217
275
  );
218
276
  if (!response.ok) return this.session.messages;
219
277
  const data = await response.json();
@@ -224,13 +282,17 @@ var MenuIAClient = class {
224
282
  createdAt: m.createdAt,
225
283
  mediaUrl: m.mediaUrl,
226
284
  mediaType: m.mediaType,
285
+ // ⚠️ O endpoint devolve `mediaName` e o mapeamento o descartava: anexo recarregado do
286
+ // historico aparecia sem o nome do arquivo, mesmo com o nome gravado no banco.
287
+ mediaName: m.mediaName,
227
288
  authorName: m.authorName
228
289
  }));
229
- this.session.messages = messages;
230
- this.session.conversationId = data.conversationId || this.session.conversationId;
231
- this.lastMessageCount = messages.length;
232
- this.saveSession();
233
- return messages;
290
+ if (messages.length) {
291
+ this.session.messages = messages;
292
+ this.lastMessageCount = messages.length;
293
+ this.saveSession();
294
+ }
295
+ return this.session.messages;
234
296
  } catch {
235
297
  return this.session.messages;
236
298
  }
@@ -239,9 +301,10 @@ var MenuIAClient = class {
239
301
  startPolling(intervalMs = 1e4) {
240
302
  this.stopPolling();
241
303
  this.pollInterval = setInterval(async () => {
304
+ const jaVistas = this.lastMessageCount;
242
305
  const messages = await this.loadHistory();
243
- if (messages.length > this.lastMessageCount) {
244
- const newMessages = messages.slice(this.lastMessageCount);
306
+ if (messages.length > jaVistas) {
307
+ const newMessages = messages.slice(jaVistas);
245
308
  for (const msg of newMessages) {
246
309
  if (msg.role === "assistant") {
247
310
  this.config.onMessage?.(msg);
package/dist/index.mjs CHANGED
@@ -22,6 +22,58 @@ var MenuIAClient = class {
22
22
  getWidgetId() {
23
23
  return this.config.widgetId || this.config.agentId || "";
24
24
  }
25
+ /** Agent id to use with /chat (resolved from the widget session, or configured directly) */
26
+ getAgentId() {
27
+ return this.session.resolvedAgentId || this.config.agentId || this.config.widgetId || "";
28
+ }
29
+ /**
30
+ * Resolve the widget session once (widgetId -> agentId + conversationId + token).
31
+ * When only an agentId is configured there is no widget to resolve; /chat is used
32
+ * directly and the conversationId comes back from the first response.
33
+ */
34
+ async ensureSession() {
35
+ if (this.session.started) return;
36
+ if (!this.config.widgetId) {
37
+ this.session.started = true;
38
+ return;
39
+ }
40
+ try {
41
+ const response = await fetch(`${this.config.apiUrl}/widget/${this.config.widgetId}/session`, {
42
+ method: "POST",
43
+ headers: { "Content-Type": "application/json" },
44
+ body: JSON.stringify({
45
+ name: this.config.visitorName || this.config.metadata?.name,
46
+ email: this.config.visitorEmail || this.config.metadata?.email,
47
+ phone: this.config.visitorPhone || this.config.metadata?.phone,
48
+ customData: this.config.customFields,
49
+ sessionId: this.session.sessionId
50
+ })
51
+ });
52
+ if (response.ok) {
53
+ const data = await response.json();
54
+ if (data.conversationId) this.session.conversationId = data.conversationId;
55
+ if (data.ticketId) this.session.ticketId = data.ticketId;
56
+ if (data.agentId) this.session.resolvedAgentId = data.agentId;
57
+ if (data.widgetToken) this.session.widgetToken = data.widgetToken;
58
+ if (data.mode) this.session.mode = data.mode;
59
+ if (Array.isArray(data.messages) && data.messages.length && this.session.messages.length === 0) {
60
+ this.session.messages = data.messages.map((m) => ({
61
+ id: m.id,
62
+ role: m.role,
63
+ content: m.content,
64
+ createdAt: m.createdAt,
65
+ mediaUrl: m.mediaUrl,
66
+ mediaType: m.mediaType,
67
+ authorName: m.authorName
68
+ }));
69
+ this.lastMessageCount = this.session.messages.length;
70
+ }
71
+ }
72
+ } catch {
73
+ }
74
+ this.session.started = true;
75
+ this.saveSession();
76
+ }
25
77
  // =====================
26
78
  // PUBLIC API
27
79
  // =====================
@@ -29,8 +81,9 @@ var MenuIAClient = class {
29
81
  async sendMessage(options) {
30
82
  this.setStatus("connecting");
31
83
  try {
84
+ await this.ensureSession();
32
85
  const body = {
33
- agentId: this.getWidgetId(),
86
+ agentId: this.getAgentId(),
34
87
  message: options.content,
35
88
  channel: this.config.channel,
36
89
  sessionId: this.session.sessionId,
@@ -46,7 +99,7 @@ var MenuIAClient = class {
46
99
  if (options.attachments?.length) {
47
100
  body.attachments = options.attachments;
48
101
  }
49
- const response = await fetch(`${this.config.apiUrl}/widget/message`, {
102
+ const response = await fetch(`${this.config.apiUrl}/chat`, {
50
103
  method: "POST",
51
104
  headers: { "Content-Type": "application/json" },
52
105
  body: JSON.stringify(body)
@@ -91,8 +144,9 @@ var MenuIAClient = class {
91
144
  async sendMessageStream(options, onToken) {
92
145
  this.setStatus("connecting");
93
146
  try {
147
+ await this.ensureSession();
94
148
  const body = {
95
- agentId: this.getWidgetId(),
149
+ agentId: this.getAgentId(),
96
150
  message: options.content,
97
151
  channel: this.config.channel,
98
152
  sessionId: this.session.sessionId,
@@ -108,7 +162,7 @@ var MenuIAClient = class {
108
162
  if (options.attachments?.length) {
109
163
  body.attachments = options.attachments;
110
164
  }
111
- const response = await fetch(`${this.config.apiUrl}/widget/stream`, {
165
+ const response = await fetch(`${this.config.apiUrl}/chat/stream`, {
112
166
  method: "POST",
113
167
  headers: { "Content-Type": "application/json" },
114
168
  body: JSON.stringify(body)
@@ -184,10 +238,14 @@ var MenuIAClient = class {
184
238
  }
185
239
  /** Load conversation history from server */
186
240
  async loadHistory() {
187
- if (!this.session.conversationId) return [];
241
+ await this.ensureSession();
242
+ if (!this.session.conversationId) return this.session.messages;
188
243
  try {
244
+ const params = new URLSearchParams();
245
+ if (this.session.widgetToken) params.set("token", this.session.widgetToken);
246
+ const qs = params.toString();
189
247
  const response = await fetch(
190
- `${this.config.apiUrl}/widget/history/${this.session.sessionId}?agentId=${this.getWidgetId()}`
248
+ `${this.config.apiUrl}/widget/messages/${this.session.conversationId}${qs ? `?${qs}` : ""}`
191
249
  );
192
250
  if (!response.ok) return this.session.messages;
193
251
  const data = await response.json();
@@ -198,13 +256,17 @@ var MenuIAClient = class {
198
256
  createdAt: m.createdAt,
199
257
  mediaUrl: m.mediaUrl,
200
258
  mediaType: m.mediaType,
259
+ // ⚠️ O endpoint devolve `mediaName` e o mapeamento o descartava: anexo recarregado do
260
+ // historico aparecia sem o nome do arquivo, mesmo com o nome gravado no banco.
261
+ mediaName: m.mediaName,
201
262
  authorName: m.authorName
202
263
  }));
203
- this.session.messages = messages;
204
- this.session.conversationId = data.conversationId || this.session.conversationId;
205
- this.lastMessageCount = messages.length;
206
- this.saveSession();
207
- return messages;
264
+ if (messages.length) {
265
+ this.session.messages = messages;
266
+ this.lastMessageCount = messages.length;
267
+ this.saveSession();
268
+ }
269
+ return this.session.messages;
208
270
  } catch {
209
271
  return this.session.messages;
210
272
  }
@@ -213,9 +275,10 @@ var MenuIAClient = class {
213
275
  startPolling(intervalMs = 1e4) {
214
276
  this.stopPolling();
215
277
  this.pollInterval = setInterval(async () => {
278
+ const jaVistas = this.lastMessageCount;
216
279
  const messages = await this.loadHistory();
217
- if (messages.length > this.lastMessageCount) {
218
- const newMessages = messages.slice(this.lastMessageCount);
280
+ if (messages.length > jaVistas) {
281
+ const newMessages = messages.slice(jaVistas);
219
282
  for (const msg of newMessages) {
220
283
  if (msg.role === "assistant") {
221
284
  this.config.onMessage?.(msg);
package/package.json CHANGED
@@ -1,11 +1,13 @@
1
1
  {
2
2
  "name": "@menuia/core",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "description": "MenuIA Chat SDK - Core",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
7
7
  "types": "dist/index.d.ts",
8
- "files": ["dist"],
8
+ "files": [
9
+ "dist"
10
+ ],
9
11
  "scripts": {
10
12
  "build": "tsup src/index.ts --format cjs,esm --dts --clean",
11
13
  "dev": "tsup src/index.ts --format cjs,esm --dts --watch"