@paymanai/payman-ask-sdk 4.0.11 → 4.0.12

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.js CHANGED
@@ -1,8 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var paymanTypescriptAskSdk = require('@paymanai/payman-typescript-ask-sdk');
4
- var framerMotion = require('framer-motion');
5
3
  var react = require('react');
4
+ var framerMotion = require('framer-motion');
6
5
  var clsx = require('clsx');
7
6
  var tailwindMerge = require('tailwind-merge');
8
7
  var Sentry = require('@sentry/react');
@@ -30,15 +29,2035 @@ function _interopNamespace(e) {
30
29
  }
31
30
  });
32
31
  }
33
- n.default = e;
34
- return Object.freeze(n);
32
+ n.default = e;
33
+ return Object.freeze(n);
34
+ }
35
+
36
+ var Sentry__namespace = /*#__PURE__*/_interopNamespace(Sentry);
37
+ var ReactMarkdown__default = /*#__PURE__*/_interopDefault(ReactMarkdown);
38
+ var remarkGfm__default = /*#__PURE__*/_interopDefault(remarkGfm);
39
+ var remarkBreaks__default = /*#__PURE__*/_interopDefault(remarkBreaks);
40
+
41
+ var __defProp = Object.defineProperty;
42
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
43
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "", value);
44
+ function generateId() {
45
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
46
+ const r = Math.random() * 16 | 0;
47
+ const v = c === "x" ? r : r & 3 | 8;
48
+ return v.toString(16);
49
+ });
50
+ }
51
+ function yieldAfterProgressEvent(event) {
52
+ const t = event.eventType;
53
+ if (t === "RUN_IN_PROGRESS" || t === "INTENT_PROGRESS" || t === "AGGREGATOR_THINKING_CONT" || t === "INTENT_THINKING_CONT" || t === "THINKING_DELTA") {
54
+ return new Promise((resolve) => setTimeout(resolve, 0));
55
+ }
56
+ return Promise.resolve();
57
+ }
58
+ function parseJSONBuffer(buffer) {
59
+ const events = [];
60
+ let braceCount = 0;
61
+ let startIndex = 0;
62
+ let inString = false;
63
+ let escapeNext = false;
64
+ let lastParsedIndex = -1;
65
+ for (let i = 0; i < buffer.length; i++) {
66
+ const char = buffer[i];
67
+ if (escapeNext) {
68
+ escapeNext = false;
69
+ continue;
70
+ }
71
+ if (char === "\\") {
72
+ escapeNext = true;
73
+ continue;
74
+ }
75
+ if (char === '"' && !escapeNext) {
76
+ inString = !inString;
77
+ continue;
78
+ }
79
+ if (inString) {
80
+ continue;
81
+ }
82
+ if (char === "{") {
83
+ if (braceCount === 0) {
84
+ startIndex = i;
85
+ }
86
+ braceCount++;
87
+ } else if (char === "}") {
88
+ braceCount--;
89
+ if (braceCount === 0) {
90
+ const jsonStr = buffer.substring(startIndex, i + 1);
91
+ try {
92
+ const parsed = JSON.parse(jsonStr);
93
+ const event = parsed;
94
+ events.push(event);
95
+ lastParsedIndex = i;
96
+ } catch (err) {
97
+ console.error("Failed to parse JSON event:", jsonStr, err);
98
+ }
99
+ }
100
+ }
101
+ }
102
+ const remaining = lastParsedIndex >= 0 ? buffer.substring(lastParsedIndex + 1) : buffer;
103
+ return { events, remaining };
104
+ }
105
+ async function streamWorkflowEvents(url, body, headers, options = {}) {
106
+ const { signal, onEvent, onError, onComplete } = options;
107
+ try {
108
+ const response = await fetch(url, {
109
+ method: "POST",
110
+ headers: {
111
+ "Content-Type": "application/json",
112
+ ...headers
113
+ },
114
+ body: JSON.stringify(body),
115
+ signal
116
+ });
117
+ if (!response.ok) {
118
+ const errorText = await response.text();
119
+ throw new Error(`HTTP ${response.status}: ${errorText}`);
120
+ }
121
+ const reader = response.body?.getReader();
122
+ if (!reader) {
123
+ throw new Error("No response body");
124
+ }
125
+ const decoder = new TextDecoder();
126
+ let buffer = "";
127
+ while (true) {
128
+ const { done, value } = await reader.read();
129
+ if (done) {
130
+ if (buffer.trim()) {
131
+ const { events: events2 } = parseJSONBuffer(buffer);
132
+ for (const event of events2) {
133
+ onEvent?.(event);
134
+ await yieldAfterProgressEvent(event);
135
+ }
136
+ }
137
+ break;
138
+ }
139
+ buffer += decoder.decode(value, { stream: true });
140
+ const { events, remaining } = parseJSONBuffer(buffer);
141
+ for (const event of events) {
142
+ onEvent?.(event);
143
+ await yieldAfterProgressEvent(event);
144
+ }
145
+ buffer = remaining;
146
+ }
147
+ onComplete?.();
148
+ } catch (error) {
149
+ if (error instanceof Error && error.name === "AbortError") {
150
+ return;
151
+ }
152
+ onError?.(error);
153
+ }
154
+ }
155
+ var STAGE_LABELS = {
156
+ sanitizer: "Checking your request",
157
+ analyzer: "Understanding what you're asking",
158
+ prefetcher: "Gathering context",
159
+ planner: "Planning how to handle this",
160
+ execution: "Working on it",
161
+ formatter: "Writing the response"
162
+ };
163
+ function stageLabel(stage) {
164
+ const label = STAGE_LABELS[stage];
165
+ if (label) return label;
166
+ const pretty = stage.replace(/[_-]/g, " ");
167
+ return `Running ${pretty}`;
168
+ }
169
+ function isBlandStatus(message) {
170
+ if (!message) return true;
171
+ const normalized = message.trim().toLowerCase().replace(/[…\.]+$/, "").trim();
172
+ return BLAND_STATUS_LABELS.has(normalized);
173
+ }
174
+ var BLAND_STATUS_LABELS = /* @__PURE__ */ new Set([
175
+ "executing",
176
+ "working on it",
177
+ "thinking",
178
+ "processing",
179
+ "reviewing your request",
180
+ "composing response",
181
+ "checking your request",
182
+ "polishing the response"
183
+ ]);
184
+ function getEventMessage(event) {
185
+ if (event.message?.trim()) {
186
+ return event.message.trim();
187
+ }
188
+ if (event.errorMessage?.trim()) {
189
+ return event.errorMessage.trim();
190
+ }
191
+ const eventType = event.eventType;
192
+ switch (eventType) {
193
+ case "RUN_STARTED":
194
+ return "Starting agent run...";
195
+ case "TOOL_CALL_STARTED": {
196
+ const description = typeof event.description === "string" ? event.description.trim() : "";
197
+ if (description) return description;
198
+ const toolName = typeof event.toolName === "string" ? event.toolName : "";
199
+ return toolName ? `Calling ${toolName}...` : "Calling tool...";
200
+ }
201
+ case "TOOL_CALL_COMPLETED": {
202
+ const description = typeof event.description === "string" ? event.description.trim() : "";
203
+ if (description) return description;
204
+ const toolName = typeof event.toolName === "string" ? event.toolName : "";
205
+ return toolName ? `${toolName} completed` : "Tool call completed";
206
+ }
207
+ case "RUN_IN_PROGRESS":
208
+ return event.partialText || "Thinking...";
209
+ case "RUN_COMPLETED":
210
+ return "Agent run completed";
211
+ case "RUN_FAILED":
212
+ return event.errorMessage || "Agent run failed";
213
+ case "KEEP_ALIVE":
214
+ return event.description || "";
215
+ case "THINKING_DELTA":
216
+ return event.text || "";
217
+ default:
218
+ return eventType;
219
+ }
220
+ }
221
+ function extractResponseContent(response) {
222
+ if (typeof response === "string") {
223
+ return response;
224
+ }
225
+ if (typeof response === "object" && response !== null) {
226
+ const resp = response;
227
+ if ("text" in resp && typeof resp.text === "string") {
228
+ return resp.text;
229
+ }
230
+ if ("content" in resp && typeof resp.content === "string") {
231
+ return resp.content;
232
+ }
233
+ if ("message" in resp && typeof resp.message === "string") {
234
+ return resp.message;
235
+ }
236
+ if ("answer" in resp && typeof resp.answer === "string") {
237
+ return resp.answer;
238
+ }
239
+ return JSON.stringify(response);
240
+ }
241
+ return "";
242
+ }
243
+ function normalizeEvent(event) {
244
+ const type = event.eventType;
245
+ switch (type) {
246
+ case "RUN_STARTED":
247
+ return { ...event, eventType: "WORKFLOW_STARTED" };
248
+ case "TOOL_CALL_STARTED": {
249
+ const toolName = typeof event.toolName === "string" ? event.toolName : void 0;
250
+ const description = typeof event.description === "string" ? event.description.trim() : "";
251
+ return {
252
+ ...event,
253
+ eventType: "INTENT_STARTED",
254
+ workerName: toolName ?? event.workerName,
255
+ message: description || event.message
256
+ };
257
+ }
258
+ case "TOOL_CALL_COMPLETED": {
259
+ const toolName = typeof event.toolName === "string" ? event.toolName : void 0;
260
+ const description = typeof event.description === "string" ? event.description.trim() : "";
261
+ return {
262
+ ...event,
263
+ eventType: "INTENT_COMPLETED",
264
+ workerName: toolName ?? event.workerName,
265
+ message: description || event.message
266
+ };
267
+ }
268
+ case "RUN_IN_PROGRESS":
269
+ return {
270
+ ...event,
271
+ eventType: "INTENT_PROGRESS",
272
+ message: event.partialText ?? event.message
273
+ };
274
+ case "RUN_COMPLETED":
275
+ return {
276
+ ...event,
277
+ eventType: "WORKFLOW_COMPLETED",
278
+ // state machine reads event.response for the final content
279
+ response: event.response ?? event.message
280
+ };
281
+ case "RUN_FAILED":
282
+ return {
283
+ ...event,
284
+ eventType: "WORKFLOW_ERROR",
285
+ errorMessage: event.errorMessage ?? event.message
286
+ };
287
+ default:
288
+ return event;
289
+ }
290
+ }
291
+ function isVerificationSchema(schema) {
292
+ const props = schema?.properties;
293
+ if (!props) return false;
294
+ const keys = Object.keys(props);
295
+ return keys.length === 1 && keys[0] === "verificationCode";
296
+ }
297
+ function classifyUserActionKind(action, schema) {
298
+ switch ((action || "").toLowerCase()) {
299
+ case "userverificationrequest":
300
+ return "verification";
301
+ case "usernotificationrequest":
302
+ return "notification";
303
+ case "userformrequest":
304
+ return isVerificationSchema(schema) ? "verification" : "form";
305
+ default:
306
+ return isVerificationSchema(schema) ? "verification" : "form";
307
+ }
308
+ }
309
+ function userActionHeader(kind) {
310
+ return kind === "verification" ? "**Verification required**" : "**Action required**";
311
+ }
312
+ function workingPhaseDetailForDisplay(raw) {
313
+ const t = raw.trim();
314
+ if (!t) return "";
315
+ if (/^Identified\s+\d+\s+tasks?\s+to\s+execute\.?$/i.test(t)) {
316
+ return "";
317
+ }
318
+ return t;
319
+ }
320
+ function getEventText(event, field) {
321
+ const value = event[field];
322
+ return typeof value === "string" ? value.trim() : "";
323
+ }
324
+ function shouldShowIntentHeader(event) {
325
+ const workerName = getEventText(event, "workerName");
326
+ const intentId = getEventText(event, "intentId");
327
+ return Boolean(workerName && intentId && workerName === intentId);
328
+ }
329
+ function addThinkingHeader(state, header) {
330
+ state.formattedThinkingText += (state.formattedThinkingText ? "\n" : "") + header;
331
+ }
332
+ function addThinkingDetail(state, detail) {
333
+ const trimmed = detail.trim();
334
+ if (!trimmed) return;
335
+ state.formattedThinkingText += (state.formattedThinkingText ? "\n" : "") + trimmed;
336
+ }
337
+ function addThinkingLine(state, header, detail) {
338
+ state.formattedThinkingText += (state.formattedThinkingText ? "\n" : "") + header + "\n" + detail;
339
+ }
340
+ function appendThinkingText(state, text) {
341
+ state.formattedThinkingText += text;
342
+ }
343
+ function updateExecutionStageMessage(state, msg) {
344
+ if (!msg) return;
345
+ for (let i = state.steps.length - 1; i >= 0; i--) {
346
+ const s = state.steps[i];
347
+ if (s.eventType === "STAGE_STARTED" && (s.stage === "executor" || s.stage === "execution") && s.status === "in_progress") {
348
+ s.message = msg;
349
+ return;
350
+ }
351
+ }
352
+ }
353
+ function completeLastInProgressStep(steps) {
354
+ for (let i = steps.length - 1; i >= 0; i--) {
355
+ if (steps[i].status === "in_progress") {
356
+ steps[i].status = "completed";
357
+ return;
358
+ }
359
+ }
360
+ }
361
+ function createInitialV2State() {
362
+ return {
363
+ formattedThinkingText: "",
364
+ finalResponse: "",
365
+ currentWorker: "",
366
+ lastEventType: "",
367
+ sessionId: void 0,
368
+ executionId: void 0,
369
+ hasError: false,
370
+ errorMessage: "",
371
+ userActions: [],
372
+ notifications: [],
373
+ lastUserAction: void 0,
374
+ lastNotification: void 0,
375
+ finalData: void 0,
376
+ steps: [],
377
+ stepCounter: 0,
378
+ currentExecutingStepId: void 0
379
+ };
380
+ }
381
+ function upsertUserAction(state, req) {
382
+ const active = { ...req, status: "pending" };
383
+ const matchIdx = state.userActions.findIndex(
384
+ (p) => req.toolCallId ? p.toolCallId === req.toolCallId : p.userActionId === req.userActionId
385
+ );
386
+ if (matchIdx >= 0) {
387
+ state.userActions[matchIdx] = active;
388
+ } else {
389
+ state.userActions.push(active);
390
+ }
391
+ }
392
+ function processStreamEventV2(rawEvent, state) {
393
+ const event = normalizeEvent(rawEvent);
394
+ const eventType = event.eventType;
395
+ state.lastUserAction = void 0;
396
+ state.lastNotification = void 0;
397
+ if (typeof eventType === "string" && eventType.toUpperCase() === "KEEP_ALIVE") {
398
+ if (event.executionId) state.executionId = event.executionId;
399
+ if (event.sessionId) state.sessionId = event.sessionId;
400
+ const description = typeof event.description === "string" ? event.description : "";
401
+ if (description) {
402
+ for (let i = state.steps.length - 1; i >= 0; i--) {
403
+ if (state.steps[i].status === "in_progress") {
404
+ state.steps[i].message = description;
405
+ break;
406
+ }
407
+ }
408
+ }
409
+ return state;
410
+ }
411
+ if (typeof eventType === "string" && eventType.toUpperCase() === "THINKING_DELTA") {
412
+ const text = typeof event.text === "string" ? event.text : "";
413
+ if (text) {
414
+ appendThinkingText(state, text);
415
+ }
416
+ if (event.executionId) state.executionId = event.executionId;
417
+ if (event.sessionId) state.sessionId = event.sessionId;
418
+ state.lastEventType = "THINKING_DELTA";
419
+ return state;
420
+ }
421
+ if (event.executionId) state.executionId = event.executionId;
422
+ if (event.sessionId) state.sessionId = event.sessionId;
423
+ const message = getEventMessage(event);
424
+ switch (eventType) {
425
+ case "WORKFLOW_STARTED":
426
+ case "STARTED":
427
+ state.lastEventType = eventType;
428
+ break;
429
+ case "INTENT_PROGRESS": {
430
+ const rawMessage = typeof event.message === "string" ? event.message : "";
431
+ const rawPartial = typeof event.partialText === "string" ? event.partialText : "";
432
+ const delta = rawMessage || rawPartial;
433
+ if (delta.length > 0) {
434
+ state.finalResponse += delta;
435
+ }
436
+ state.lastEventType = eventType;
437
+ break;
438
+ }
439
+ case "INTENT_THINKING": {
440
+ const worker = getEventText(event, "workerName") || "Worker";
441
+ const msg = getEventText(event, "message") || "Thinking...";
442
+ const showHeader = shouldShowIntentHeader(event);
443
+ if (worker !== state.currentWorker) {
444
+ state.currentWorker = worker;
445
+ if (showHeader && msg && msg !== worker) {
446
+ addThinkingLine(state, `**${worker}**`, msg);
447
+ } else if (showHeader) {
448
+ addThinkingHeader(state, `**${worker}**`);
449
+ } else if (msg !== "Thinking...") {
450
+ addThinkingDetail(state, msg);
451
+ }
452
+ } else if (showHeader || msg !== "Thinking...") {
453
+ appendThinkingText(state, "\n" + msg);
454
+ }
455
+ const lastInProgress = [...state.steps].reverse().find((s) => s.status === "in_progress");
456
+ if (lastInProgress) {
457
+ lastInProgress.thinkingText = "";
458
+ lastInProgress.isThinking = true;
459
+ }
460
+ state.lastEventType = "INTENT_THINKING";
461
+ break;
462
+ }
463
+ case "INTENT_THINKING_CONT": {
464
+ const msg = event.message || "";
465
+ if (!msg) break;
466
+ if (state.lastEventType === "INTENT_THINKING") {
467
+ appendThinkingText(state, "\n" + msg);
468
+ } else {
469
+ appendThinkingText(state, msg);
470
+ }
471
+ const thinkingStep = [...state.steps].reverse().find((s) => s.isThinking);
472
+ if (thinkingStep) {
473
+ thinkingStep.thinkingText = (thinkingStep.thinkingText || "") + msg;
474
+ }
475
+ state.lastEventType = "INTENT_THINKING_CONT";
476
+ break;
477
+ }
478
+ case "ORCHESTRATOR_THINKING": {
479
+ addThinkingLine(state, "**Planning**", event.message || "Understanding your request...");
480
+ const stepId = `step-${state.stepCounter++}`;
481
+ state.steps.push({
482
+ id: stepId,
483
+ eventType,
484
+ message,
485
+ status: "in_progress",
486
+ timestamp: Date.now(),
487
+ elapsedMs: event.elapsedMs
488
+ });
489
+ state.currentExecutingStepId = stepId;
490
+ state.lastEventType = eventType;
491
+ break;
492
+ }
493
+ case "ORCHESTRATOR_COMPLETED": {
494
+ const workingDetail = workingPhaseDetailForDisplay(message);
495
+ if (workingDetail) {
496
+ addThinkingLine(state, "**Working**", workingDetail);
497
+ } else {
498
+ addThinkingHeader(state, "**Working**");
499
+ }
500
+ state.steps.push({
501
+ id: `step-${state.stepCounter++}`,
502
+ eventType: "WORKING",
503
+ message: workingDetail,
504
+ status: "completed",
505
+ timestamp: Date.now()
506
+ });
507
+ const step = state.steps.find((s) => s.eventType === "ORCHESTRATOR_THINKING" && s.status === "in_progress");
508
+ if (step) {
509
+ step.status = "completed";
510
+ if (event.elapsedMs) step.elapsedMs = event.elapsedMs;
511
+ if (step.id === state.currentExecutingStepId) state.currentExecutingStepId = void 0;
512
+ }
513
+ state.lastEventType = eventType;
514
+ break;
515
+ }
516
+ case "INTENT_STARTED": {
517
+ const worker = getEventText(event, "workerName") || "Worker";
518
+ const msg = getEventText(event, "message") || "Starting...";
519
+ const showHeader = shouldShowIntentHeader(event);
520
+ state.currentWorker = worker;
521
+ if (showHeader && msg !== worker) {
522
+ addThinkingLine(state, `**${worker}**`, msg);
523
+ } else if (showHeader) {
524
+ addThinkingHeader(state, `**${worker}**`);
525
+ } else {
526
+ addThinkingDetail(state, msg);
527
+ }
528
+ const thinkingStep = state.steps.find((s) => s.isThinking);
529
+ if (thinkingStep) thinkingStep.isThinking = false;
530
+ const stepId = `step-${state.stepCounter++}`;
531
+ state.steps.push({
532
+ id: stepId,
533
+ eventType,
534
+ message,
535
+ status: "in_progress",
536
+ timestamp: Date.now(),
537
+ elapsedMs: event.elapsedMs
538
+ });
539
+ state.currentExecutingStepId = stepId;
540
+ updateExecutionStageMessage(state, message);
541
+ state.lastEventType = eventType;
542
+ break;
543
+ }
544
+ case "INTENT_COMPLETED": {
545
+ const intentStep = state.steps.find((s) => s.eventType === "INTENT_STARTED" && s.status === "in_progress");
546
+ if (intentStep) {
547
+ intentStep.status = "completed";
548
+ intentStep.isThinking = false;
549
+ if (event.elapsedMs) intentStep.elapsedMs = event.elapsedMs;
550
+ if (intentStep.id === state.currentExecutingStepId) state.currentExecutingStepId = void 0;
551
+ }
552
+ state.lastEventType = eventType;
553
+ break;
554
+ }
555
+ case "AGGREGATOR_THINKING": {
556
+ addThinkingLine(state, "**Finalizing**", event.message || "Preparing response...");
557
+ const stepId = `step-${state.stepCounter++}`;
558
+ state.steps.push({
559
+ id: stepId,
560
+ eventType,
561
+ message,
562
+ status: "in_progress",
563
+ timestamp: Date.now(),
564
+ elapsedMs: event.elapsedMs
565
+ });
566
+ state.currentExecutingStepId = stepId;
567
+ state.lastEventType = eventType;
568
+ break;
569
+ }
570
+ case "AGGREGATOR_COMPLETED": {
571
+ appendThinkingText(state, "\n" + (event.message || "Response ready"));
572
+ const step = state.steps.find((s) => s.eventType === "AGGREGATOR_THINKING" && s.status === "in_progress");
573
+ if (step) {
574
+ step.status = "completed";
575
+ if (event.elapsedMs) step.elapsedMs = event.elapsedMs;
576
+ if (step.id === state.currentExecutingStepId) state.currentExecutingStepId = void 0;
577
+ }
578
+ state.lastEventType = eventType;
579
+ break;
580
+ }
581
+ case "WORKFLOW_COMPLETED":
582
+ case "COMPLETED": {
583
+ const totalTime = Number(event.totalTimeMs);
584
+ if (Number.isFinite(totalTime) && totalTime > 0) {
585
+ state.totalElapsedMs = totalTime;
586
+ }
587
+ let content = extractResponseContent(event.response);
588
+ const trace = event.trace && typeof event.trace === "object" ? event.trace : null;
589
+ if (!content && trace?.workflowMsg && typeof trace.workflowMsg === "string") {
590
+ content = trace.workflowMsg;
591
+ }
592
+ if (!content && trace?.aggregator && typeof trace.aggregator === "object") {
593
+ const agg = trace.aggregator;
594
+ if (typeof agg.response === "string") content = agg.response;
595
+ else content = extractResponseContent(agg.response);
596
+ }
597
+ if (content) {
598
+ state.finalResponse = content;
599
+ if (event.trace && typeof event.trace === "object") {
600
+ state.finalData = event.trace;
601
+ }
602
+ state.hasError = false;
603
+ state.errorMessage = "";
604
+ } else {
605
+ state.hasError = true;
606
+ state.errorMessage = "WORKFLOW_FAILED";
607
+ }
608
+ state.steps.forEach((step) => {
609
+ if (step.status === "in_progress") {
610
+ step.status = "completed";
611
+ step.isThinking = false;
612
+ }
613
+ });
614
+ state.lastEventType = eventType;
615
+ break;
616
+ }
617
+ case "USER_ACTION_REQUIRED": {
618
+ const rawAction = typeof event.action === "string" ? event.action : void 0;
619
+ const schema = event.requestedSchema;
620
+ const kind = classifyUserActionKind(rawAction, schema);
621
+ const promptMessage = typeof event.message === "string" && event.message.trim() || message || "";
622
+ const userActionId = typeof event.userActionId === "string" ? event.userActionId : "";
623
+ if (kind === "notification") {
624
+ const notification = {
625
+ id: userActionId || `note-${state.stepCounter++}`,
626
+ message: promptMessage
627
+ };
628
+ state.notifications.push(notification);
629
+ state.lastNotification = notification;
630
+ if (promptMessage) addThinkingDetail(state, promptMessage);
631
+ state.lastEventType = eventType;
632
+ break;
633
+ }
634
+ if (!userActionId) {
635
+ state.lastEventType = eventType;
636
+ break;
637
+ }
638
+ completeLastInProgressStep(state.steps);
639
+ const verificationType = event.verificationType === "ALPHANUMERIC_CODE" || event.verificationType === "NUMERIC_CODE" ? event.verificationType : void 0;
640
+ const request = {
641
+ userActionId,
642
+ kind,
643
+ rawAction,
644
+ subAction: typeof event.subAction === "string" ? event.subAction : void 0,
645
+ verificationType,
646
+ expirySeconds: typeof event.expirySeconds === "number" ? event.expirySeconds : void 0,
647
+ message: promptMessage || void 0,
648
+ requestedSchema: schema,
649
+ metadata: event.metadata,
650
+ toolCallId: typeof event.toolCallId === "string" ? event.toolCallId : void 0,
651
+ executionId: state.executionId,
652
+ sessionId: state.sessionId
653
+ };
654
+ upsertUserAction(state, request);
655
+ state.lastUserAction = request;
656
+ const header = userActionHeader(kind);
657
+ if (promptMessage) addThinkingLine(state, header, promptMessage);
658
+ else addThinkingHeader(state, header);
659
+ const stepId = `step-${state.stepCounter++}`;
660
+ state.steps.push({
661
+ id: stepId,
662
+ eventType,
663
+ message: promptMessage || (kind === "verification" ? "Waiting for verification..." : "Waiting for your input..."),
664
+ status: "in_progress",
665
+ timestamp: Date.now(),
666
+ elapsedMs: event.elapsedMs
667
+ });
668
+ state.currentExecutingStepId = stepId;
669
+ state.lastEventType = eventType;
670
+ break;
671
+ }
672
+ case "USER_NOTIFICATION": {
673
+ const noteMessage = typeof event.message === "string" && event.message.trim() || message || "";
674
+ const userActionId = typeof event.userActionId === "string" ? event.userActionId : "";
675
+ if (noteMessage || userActionId) {
676
+ const notification = {
677
+ id: userActionId || `note-${state.stepCounter++}`,
678
+ message: noteMessage
679
+ };
680
+ state.notifications.push(notification);
681
+ state.lastNotification = notification;
682
+ if (noteMessage) addThinkingDetail(state, noteMessage);
683
+ }
684
+ state.lastEventType = eventType;
685
+ break;
686
+ }
687
+ case "WORKFLOW_ERROR":
688
+ case "ERROR":
689
+ state.hasError = true;
690
+ state.errorMessage = event.errorMessage || event.message || "Workflow error";
691
+ state.lastEventType = eventType;
692
+ break;
693
+ case "INTENT_ERROR": {
694
+ state.errorMessage = message || event.errorMessage || "An error occurred";
695
+ const intentStep = state.steps.find((s) => s.eventType === "INTENT_STARTED" && s.status === "in_progress");
696
+ if (intentStep) {
697
+ intentStep.status = "error";
698
+ intentStep.isThinking = false;
699
+ }
700
+ state.lastEventType = eventType;
701
+ break;
702
+ }
703
+ // ---- K2 pipeline stage lifecycle events ----
704
+ //
705
+ // The k2-server playground streaming API emits
706
+ // STAGE_STARTED / STAGE_COMPLETED / STAGE_FAILED /
707
+ // STAGE_SKIPPED around each pipeline stage so the UI can
708
+ // show real progress (sanitizer → analyzer → planner → …)
709
+ // instead of a static placeholder. Each STAGE_STARTED
710
+ // pushes an in-progress step with a user-facing label; the
711
+ // matching STAGE_COMPLETED/FAILED closes it WITHOUT
712
+ // rewriting the label — a terse "completed" flash between
713
+ // stages was more noise than signal. STAGE_SKIPPED removes
714
+ // the just-opened step entirely (skipping is expected on
715
+ // DIRECT_RESPONSE short-circuits).
716
+ //
717
+ // Finding the matching step uses `stepId` directly rather
718
+ // than comparing labels — the processor remembers which id
719
+ // it minted for the latest open STAGE_STARTED and the
720
+ // closing events look it up from state.currentExecutingStepId.
721
+ case "STAGE_STARTED": {
722
+ const stage = getEventText(event, "stage");
723
+ if (!stage) {
724
+ state.lastEventType = eventType;
725
+ break;
726
+ }
727
+ const serverMessage = getEventText(event, "message");
728
+ let initialMessage = serverMessage || stageLabel(stage);
729
+ if (stage === "executor" || stage === "execution") {
730
+ for (let i = state.steps.length - 1; i >= 0; i--) {
731
+ const s = state.steps[i];
732
+ if (s.eventType === "STAGE_STARTED" && s.stage === "analyzer" && s.status === "completed" && s.message) {
733
+ initialMessage = s.message;
734
+ break;
735
+ }
736
+ }
737
+ }
738
+ const stepId = `stage-${stage}-${state.stepCounter++}`;
739
+ state.steps.push({
740
+ id: stepId,
741
+ eventType,
742
+ message: initialMessage,
743
+ status: "in_progress",
744
+ timestamp: Date.now(),
745
+ stage
746
+ });
747
+ state.currentExecutingStepId = stepId;
748
+ state.lastEventType = eventType;
749
+ break;
750
+ }
751
+ case "STAGE_COMPLETED": {
752
+ const stage = getEventText(event, "stage");
753
+ if (!stage) {
754
+ state.lastEventType = eventType;
755
+ break;
756
+ }
757
+ const serverMessage = getEventText(event, "message");
758
+ for (let i = state.steps.length - 1; i >= 0; i--) {
759
+ const s = state.steps[i];
760
+ if (s.eventType === "STAGE_STARTED" && s.stage === stage && s.status === "in_progress") {
761
+ if (serverMessage) s.message = serverMessage;
762
+ s.status = "completed";
763
+ const durationMs = Number(event.durationMs);
764
+ if (Number.isFinite(durationMs)) s.elapsedMs = durationMs;
765
+ if (s.id === state.currentExecutingStepId) {
766
+ state.currentExecutingStepId = void 0;
767
+ }
768
+ break;
769
+ }
770
+ }
771
+ state.lastEventType = eventType;
772
+ break;
773
+ }
774
+ case "STAGE_FAILED": {
775
+ const stage = getEventText(event, "stage");
776
+ if (!stage) {
777
+ state.lastEventType = eventType;
778
+ break;
779
+ }
780
+ const serverMessage = getEventText(event, "message");
781
+ for (let i = state.steps.length - 1; i >= 0; i--) {
782
+ const s = state.steps[i];
783
+ if (s.eventType === "STAGE_STARTED" && s.stage === stage && s.status === "in_progress") {
784
+ if (serverMessage) s.message = serverMessage;
785
+ s.status = "error";
786
+ const durationMs = Number(event.durationMs);
787
+ if (Number.isFinite(durationMs)) s.elapsedMs = durationMs;
788
+ if (s.id === state.currentExecutingStepId) {
789
+ state.currentExecutingStepId = void 0;
790
+ }
791
+ break;
792
+ }
793
+ }
794
+ state.lastEventType = eventType;
795
+ break;
796
+ }
797
+ case "STAGE_SKIPPED": {
798
+ const stage = getEventText(event, "stage");
799
+ if (!stage) {
800
+ state.lastEventType = eventType;
801
+ break;
802
+ }
803
+ for (let i = state.steps.length - 1; i >= 0; i--) {
804
+ const s = state.steps[i];
805
+ if (s.eventType === "STAGE_STARTED" && s.stage === stage && s.status === "in_progress") {
806
+ if (s.id === state.currentExecutingStepId) {
807
+ state.currentExecutingStepId = void 0;
808
+ }
809
+ s.status = "skipped";
810
+ break;
811
+ }
812
+ }
813
+ state.lastEventType = eventType;
814
+ break;
815
+ }
816
+ default:
817
+ state.lastEventType = eventType;
818
+ break;
819
+ }
820
+ return state;
821
+ }
822
+ function buildFormattedThinking(steps, allThinkingText) {
823
+ const parts = [];
824
+ const safeSteps = steps ?? [];
825
+ const cleanAll = allThinkingText.replace(/^\s+/, "");
826
+ if (cleanAll) {
827
+ const firstStepWithThinking = safeSteps.find(
828
+ (s) => s.thinkingText && s.thinkingText.trim()
829
+ );
830
+ if (!firstStepWithThinking) {
831
+ parts.push("**Preflight**");
832
+ parts.push(cleanAll);
833
+ } else {
834
+ const stepText = firstStepWithThinking.thinkingText.trim();
835
+ const idx = cleanAll.indexOf(stepText);
836
+ if (idx > 0) {
837
+ const orphaned = cleanAll.substring(0, idx).replace(/\s+$/, "");
838
+ if (orphaned) {
839
+ parts.push("**Preflight**");
840
+ parts.push(orphaned);
841
+ }
842
+ }
843
+ }
844
+ }
845
+ for (const step of safeSteps) {
846
+ switch (step.eventType) {
847
+ case "STAGE_STARTED": {
848
+ if (step.message) parts.push(`**${step.message}**`);
849
+ break;
850
+ }
851
+ case "ORCHESTRATOR_THINKING":
852
+ parts.push("**Planning**");
853
+ if (step.message) parts.push(step.message);
854
+ break;
855
+ case "INTENT_STARTED": {
856
+ let label = step.message || "Processing";
857
+ const started = label.match(/^(.+?)\s+started$/i);
858
+ const progress = label.match(/^(.+?)\s+in progress$/i);
859
+ if (started) label = started[1];
860
+ else if (progress) label = progress[1];
861
+ parts.push(`**${label}**`);
862
+ if (step.thinkingText) parts.push(step.thinkingText);
863
+ break;
864
+ }
865
+ case "INTENT_PROGRESS": {
866
+ if (step.thinkingText) parts.push(step.thinkingText);
867
+ else if (step.message) parts.push(step.message);
868
+ break;
869
+ }
870
+ case "AGGREGATOR_THINKING":
871
+ parts.push("**Finalizing**");
872
+ if (step.message) parts.push(step.message);
873
+ break;
874
+ case "USER_ACTION_REQUIRED":
875
+ parts.push("**Action required**");
876
+ if (step.message) parts.push(step.message);
877
+ break;
878
+ }
879
+ }
880
+ return parts.length > 0 ? parts.join("\n") : allThinkingText;
881
+ }
882
+ function createCancelledMessageUpdate(steps, currentMessage) {
883
+ const updatedSteps = steps.map((step) => {
884
+ if (step.status === "in_progress") {
885
+ return { ...step, status: "pending" };
886
+ }
887
+ return step;
888
+ });
889
+ return {
890
+ isStreaming: false,
891
+ isCancelled: true,
892
+ steps: updatedSteps,
893
+ currentExecutingStepId: void 0,
894
+ // Preserve currentMessage so UI can show it with X icon
895
+ currentMessage: currentMessage || "Thinking..."
896
+ };
897
+ }
898
+ var DEFAULT_STREAM_ENDPOINT = "/api/playground/ask/stream";
899
+ function buildRequestBody(config, userMessage, sessionId, options) {
900
+ const sessionOwner = config.sessionParams;
901
+ const sessionOwnerId = sessionOwner?.id?.trim();
902
+ if (!sessionOwnerId) {
903
+ throw new Error("ChatConfig.sessionParams.id is required to send ask requests.");
904
+ }
905
+ const sessionAttributes = sessionOwner?.attributes && Object.keys(sessionOwner.attributes).length > 0 ? sessionOwner.attributes : void 0;
906
+ return {
907
+ agentId: config.agentId,
908
+ userInput: userMessage,
909
+ sessionId,
910
+ sessionOwnerId,
911
+ sessionOwnerLabel: sessionOwner?.name || void 0,
912
+ sessionAttributes,
913
+ analysisMode: options?.analysisMode,
914
+ locale: resolveLocale(config.locale),
915
+ timezone: resolveTimezone(config.timezone)
916
+ };
917
+ }
918
+ function resolveLocale(configured) {
919
+ if (configured && configured.trim().length > 0) return configured.trim();
920
+ if (typeof navigator !== "undefined") {
921
+ const navLocale = navigator.language;
922
+ if (navLocale && navLocale.length > 0) return navLocale;
923
+ }
924
+ return "en-US";
925
+ }
926
+ function resolveTimezone(configured) {
927
+ if (configured && configured.trim().length > 0) return configured.trim();
928
+ try {
929
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
930
+ if (zone && zone.length > 0) return zone;
931
+ } catch {
932
+ }
933
+ return "UTC";
934
+ }
935
+ function buildStreamingUrl(config) {
936
+ const endpoint = config.api.streamEndpoint || DEFAULT_STREAM_ENDPOINT;
937
+ const stage = config.stage || "DEV";
938
+ const stageParamName = config.stageQueryParam ?? "stage";
939
+ const queryParams = new URLSearchParams({ [stageParamName]: stage });
940
+ return `${config.api.baseUrl}${endpoint}?${queryParams.toString()}`;
941
+ }
942
+ function buildUserActionUrl(config, userActionId, action) {
943
+ const endpoint = config.api.streamEndpoint || DEFAULT_STREAM_ENDPOINT;
944
+ const [endpointPath] = endpoint.split("?");
945
+ const normalizedEndpointPath = endpointPath.replace(/\/+$/, "");
946
+ const basePath = normalizedEndpointPath.endsWith("/stream") ? normalizedEndpointPath.slice(0, -"/stream".length) : normalizedEndpointPath;
947
+ const encodedUserActionId = encodeURIComponent(userActionId);
948
+ return `${config.api.baseUrl}${basePath}/user-action/${encodedUserActionId}/${action}`;
949
+ }
950
+ function buildResolveImagesUrl(config) {
951
+ if (config.api.resolveImagesEndpoint) {
952
+ return `${config.api.baseUrl}${config.api.resolveImagesEndpoint}`;
953
+ }
954
+ const streamEndpoint = config.api.streamEndpoint || DEFAULT_STREAM_ENDPOINT;
955
+ const [endpointPath] = streamEndpoint.split("?");
956
+ const normalizedEndpointPath = endpointPath.replace(/\/+$/, "");
957
+ const basePath = normalizedEndpointPath.endsWith("/stream") ? normalizedEndpointPath.slice(0, -"/stream".length) : normalizedEndpointPath;
958
+ return `${config.api.baseUrl}${basePath}/resolve-image-urls`;
959
+ }
960
+ function buildRequestHeaders(config) {
961
+ const headers = {
962
+ ...config.api.headers
963
+ };
964
+ if (config.api.authToken) {
965
+ headers.Authorization = `Bearer ${config.api.authToken}`;
966
+ }
967
+ return headers;
968
+ }
969
+ var UserActionStaleError = class extends Error {
970
+ constructor(userActionId, message = "User action is no longer actionable") {
971
+ super(message);
972
+ __publicField(this, "userActionId");
973
+ this.name = "UserActionStaleError";
974
+ this.userActionId = userActionId;
975
+ }
976
+ };
977
+ async function sendUserActionRequest(config, userActionId, action, data) {
978
+ const url = buildUserActionUrl(config, userActionId, action);
979
+ const baseHeaders = buildRequestHeaders(config);
980
+ const hasBody = data !== void 0;
981
+ const headers = hasBody ? { "Content-Type": "application/json", ...baseHeaders } : baseHeaders;
982
+ const response = await fetch(url, {
983
+ method: "POST",
984
+ headers,
985
+ body: hasBody ? JSON.stringify(data) : void 0
986
+ });
987
+ if (response.status === 404) {
988
+ throw new UserActionStaleError(userActionId);
989
+ }
990
+ if (!response.ok) {
991
+ const errorText = await response.text();
992
+ throw new Error(`HTTP ${response.status}: ${errorText}`);
993
+ }
994
+ return await response.json();
995
+ }
996
+ async function submitUserAction(config, userActionId, content) {
997
+ return sendUserActionRequest(config, userActionId, "submit", content ?? {});
998
+ }
999
+ async function cancelUserAction(config, userActionId) {
1000
+ return sendUserActionRequest(config, userActionId, "cancel");
1001
+ }
1002
+ async function resendUserAction(config, userActionId) {
1003
+ return sendUserActionRequest(config, userActionId, "resend");
1004
+ }
1005
+ var memoryStore = /* @__PURE__ */ new Map();
1006
+ var chatStore = {
1007
+ get(key) {
1008
+ return memoryStore.get(key) ?? [];
1009
+ },
1010
+ set(key, messages) {
1011
+ memoryStore.set(key, messages);
1012
+ },
1013
+ delete(key) {
1014
+ memoryStore.delete(key);
1015
+ }
1016
+ };
1017
+ var streams = /* @__PURE__ */ new Map();
1018
+ var activeStreamStore = {
1019
+ has(key) {
1020
+ return streams.has(key);
1021
+ },
1022
+ get(key) {
1023
+ const entry = streams.get(key);
1024
+ if (!entry) return null;
1025
+ return { messages: entry.messages, isWaiting: entry.isWaiting };
1026
+ },
1027
+ // Called before startStream — registers the controller and initial messages
1028
+ start(key, abortController, initialMessages) {
1029
+ const existing = streams.get(key);
1030
+ streams.set(key, {
1031
+ messages: initialMessages,
1032
+ isWaiting: true,
1033
+ abortController,
1034
+ listeners: existing?.listeners ?? /* @__PURE__ */ new Set()
1035
+ });
1036
+ },
1037
+ // Called by the stream on every event — applies the same updater pattern React uses
1038
+ applyMessages(key, updater) {
1039
+ const entry = streams.get(key);
1040
+ if (!entry) return;
1041
+ const next = typeof updater === "function" ? updater(entry.messages) : updater;
1042
+ entry.messages = next;
1043
+ entry.listeners.forEach((l) => l(next, entry.isWaiting));
1044
+ },
1045
+ setWaiting(key, waiting) {
1046
+ const entry = streams.get(key);
1047
+ if (!entry) return;
1048
+ entry.isWaiting = waiting;
1049
+ entry.listeners.forEach((l) => l(entry.messages, waiting));
1050
+ },
1051
+ // Called when stream completes — persists to chatStore and cleans up
1052
+ complete(key) {
1053
+ const entry = streams.get(key);
1054
+ if (!entry) return;
1055
+ entry.isWaiting = false;
1056
+ entry.listeners.forEach((l) => l(entry.messages, false));
1057
+ const toSave = entry.messages.filter((m) => !m.isStreaming);
1058
+ if (toSave.length > 0) chatStore.set(key, toSave);
1059
+ streams.delete(key);
1060
+ },
1061
+ // Subscribe — returns unsubscribe fn. Component calls this on mount, cleanup on unmount.
1062
+ subscribe(key, listener) {
1063
+ const entry = streams.get(key);
1064
+ if (!entry) return () => {
1065
+ };
1066
+ entry.listeners.add(listener);
1067
+ return () => {
1068
+ streams.get(key)?.listeners.delete(listener);
1069
+ };
1070
+ },
1071
+ // Rename an entry — used when the server assigns a new session ID mid-stream
1072
+ rename(oldKey, newKey) {
1073
+ const entry = streams.get(oldKey);
1074
+ if (!entry) return;
1075
+ streams.set(newKey, entry);
1076
+ streams.delete(oldKey);
1077
+ },
1078
+ // Explicit user cancel — aborts the controller and removes the entry
1079
+ abort(key) {
1080
+ const entry = streams.get(key);
1081
+ if (!entry) return;
1082
+ entry.abortController.abort();
1083
+ streams.delete(key);
1084
+ }
1085
+ };
1086
+ var RAG_IMAGE_REGEX = /\/api\/rag\/chunks\/[^"'\s]+\/image/;
1087
+ function hasRagImages(content) {
1088
+ return RAG_IMAGE_REGEX.test(content);
1089
+ }
1090
+ async function waitForNextPaint(signal) {
1091
+ if (signal?.aborted) return;
1092
+ await new Promise((resolve) => {
1093
+ let isSettled = false;
1094
+ const finish = () => {
1095
+ if (isSettled) return;
1096
+ isSettled = true;
1097
+ signal?.removeEventListener("abort", finish);
1098
+ resolve();
1099
+ };
1100
+ signal?.addEventListener("abort", finish, { once: true });
1101
+ if (typeof requestAnimationFrame === "function") {
1102
+ requestAnimationFrame(() => {
1103
+ setTimeout(finish, 0);
1104
+ });
1105
+ return;
1106
+ }
1107
+ setTimeout(finish, 0);
1108
+ });
1109
+ }
1110
+ async function resolveRagImageUrls(config, content, signal) {
1111
+ const url = buildResolveImagesUrl(config);
1112
+ const baseHeaders = buildRequestHeaders(config);
1113
+ const headers = { "Content-Type": "application/json", ...baseHeaders };
1114
+ const response = await fetch(url, {
1115
+ method: "POST",
1116
+ headers,
1117
+ body: JSON.stringify({ input: content }),
1118
+ signal
1119
+ });
1120
+ if (!response.ok) {
1121
+ const errorText = await response.text();
1122
+ throw new Error(`HTTP ${response.status}: ${errorText}`);
1123
+ }
1124
+ const text = await response.text();
1125
+ try {
1126
+ const parsed = JSON.parse(text);
1127
+ if (typeof parsed === "string") return parsed;
1128
+ if (typeof parsed.output === "string") return parsed.output;
1129
+ if (typeof parsed.result === "string") return parsed.result;
1130
+ } catch {
1131
+ }
1132
+ return text;
1133
+ }
1134
+ var FRIENDLY_ERROR_MESSAGE = "Oops, something went wrong. Please try again.";
1135
+ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForResponse) {
1136
+ const abortControllerRef = react.useRef(null);
1137
+ const configRef = react.useRef(config);
1138
+ configRef.current = config;
1139
+ const callbacksRef = react.useRef(callbacks);
1140
+ callbacksRef.current = callbacks;
1141
+ const startStream = react.useCallback(
1142
+ async (userMessage, streamingId, sessionId, externalAbortController, options) => {
1143
+ abortControllerRef.current?.abort();
1144
+ const abortController = externalAbortController ?? new AbortController();
1145
+ abortControllerRef.current = abortController;
1146
+ const state = createInitialV2State();
1147
+ const updateMessage = (update) => {
1148
+ if (abortController.signal.aborted) return;
1149
+ setMessages(
1150
+ (prev) => prev.map(
1151
+ (msg) => msg.id === streamingId ? { ...msg, ...update } : msg
1152
+ )
1153
+ );
1154
+ };
1155
+ try {
1156
+ const currentConfig = configRef.current;
1157
+ const requestBody = buildRequestBody(
1158
+ currentConfig,
1159
+ userMessage,
1160
+ sessionId,
1161
+ options
1162
+ );
1163
+ const url = buildStreamingUrl(currentConfig);
1164
+ const headers = buildRequestHeaders(currentConfig);
1165
+ await streamWorkflowEvents(url, requestBody, headers, {
1166
+ signal: abortController.signal,
1167
+ onEvent: (event) => {
1168
+ if (abortController.signal.aborted) return;
1169
+ processStreamEventV2(event, state);
1170
+ if (state.lastUserAction) {
1171
+ callbacksRef.current.onUserActionRequired?.(state.lastUserAction);
1172
+ }
1173
+ if (state.lastNotification) {
1174
+ callbacksRef.current.onUserNotification?.(state.lastNotification);
1175
+ }
1176
+ const activeStep = state.steps.find((s) => s.id === state.currentExecutingStepId);
1177
+ const lastInProgressStep = [...state.steps].reverse().find((s) => s.status === "in_progress");
1178
+ const useful = (m) => m && !isBlandStatus(m) ? m : void 0;
1179
+ const latestUsefulStep = [...state.steps].reverse().find(
1180
+ (s) => s.message && !isBlandStatus(s.message)
1181
+ );
1182
+ const currentMessage = useful(activeStep?.message) ?? useful(lastInProgressStep?.message) ?? latestUsefulStep?.message ?? useful(getEventMessage(event)) ?? // Last-resort: every candidate is bland (very first event,
1183
+ // nothing useful seen yet). Render the bland label so the
1184
+ // bubble isn't blank.
1185
+ activeStep?.message ?? lastInProgressStep?.message ?? getEventMessage(event);
1186
+ if (currentMessage) {
1187
+ callbacksRef.current.onStatusMessage?.(currentMessage);
1188
+ }
1189
+ callbacksRef.current.onStepsUpdate?.([...state.steps]);
1190
+ if (state.hasError) {
1191
+ updateMessage({
1192
+ streamingContent: FRIENDLY_ERROR_MESSAGE,
1193
+ content: FRIENDLY_ERROR_MESSAGE,
1194
+ streamProgress: "error",
1195
+ isError: true,
1196
+ errorDetails: state.errorMessage,
1197
+ formattedThinkingText: state.formattedThinkingText || void 0,
1198
+ steps: [...state.steps],
1199
+ currentExecutingStepId: void 0,
1200
+ executionId: state.executionId,
1201
+ sessionId: state.sessionId
1202
+ });
1203
+ } else {
1204
+ updateMessage({
1205
+ streamingContent: state.finalResponse,
1206
+ content: "",
1207
+ currentMessage,
1208
+ streamProgress: "processing",
1209
+ isError: false,
1210
+ formattedThinkingText: state.formattedThinkingText || void 0,
1211
+ steps: [...state.steps],
1212
+ currentExecutingStepId: state.currentExecutingStepId,
1213
+ executionId: state.executionId,
1214
+ sessionId: state.sessionId,
1215
+ isCancelled: false
1216
+ });
1217
+ }
1218
+ },
1219
+ onError: (error) => {
1220
+ setIsWaitingForResponse(false);
1221
+ callbacksRef.current.onStatusMessage?.(null);
1222
+ if (error.name !== "AbortError") {
1223
+ callbacksRef.current.onError?.(error);
1224
+ }
1225
+ const isAborted = error.name === "AbortError";
1226
+ setMessages(
1227
+ (prev) => prev.map(
1228
+ (msg) => msg.id === streamingId ? {
1229
+ ...msg,
1230
+ isStreaming: false,
1231
+ streamProgress: isAborted ? "processing" : "error",
1232
+ isError: !isAborted,
1233
+ isCancelled: isAborted,
1234
+ errorDetails: isAborted ? void 0 : error.message,
1235
+ content: isAborted ? state.finalResponse || "" : state.finalResponse || FRIENDLY_ERROR_MESSAGE,
1236
+ currentMessage: isAborted ? "Thinking..." : void 0,
1237
+ formattedThinkingText: state.formattedThinkingText || void 0,
1238
+ steps: [...state.steps].map((step) => {
1239
+ if (step.status === "in_progress" && isAborted) {
1240
+ return { ...step, status: "pending" };
1241
+ }
1242
+ return step;
1243
+ }),
1244
+ currentExecutingStepId: void 0
1245
+ } : msg
1246
+ )
1247
+ );
1248
+ },
1249
+ onComplete: () => {
1250
+ setIsWaitingForResponse(false);
1251
+ callbacksRef.current.onStatusMessage?.(null);
1252
+ callbacksRef.current.onStepsUpdate?.([]);
1253
+ if (state.sessionId && state.sessionId !== sessionId) {
1254
+ callbacksRef.current.onSessionIdChange?.(state.sessionId);
1255
+ }
1256
+ const needsImageResolve = !state.hasError && !abortController.signal.aborted && hasRagImages(state.finalResponse);
1257
+ const finalMessage = {
1258
+ id: streamingId,
1259
+ sessionId: state.sessionId || sessionId,
1260
+ role: "assistant",
1261
+ content: state.hasError ? FRIENDLY_ERROR_MESSAGE : state.finalResponse || "",
1262
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1263
+ isStreaming: false,
1264
+ streamProgress: state.hasError ? "error" : "completed",
1265
+ isError: state.hasError,
1266
+ errorDetails: state.hasError ? state.errorMessage : void 0,
1267
+ executionId: state.executionId,
1268
+ // Defensive: tracingData must be an object (or undefined)
1269
+ // so the JSON viewer doesn't char-iterate a string. The
1270
+ // event processor already drops bare strings; this is
1271
+ // the last stop before the message leaves the SDK.
1272
+ tracingData: state.finalData != null && typeof state.finalData === "object" ? state.finalData : void 0,
1273
+ steps: state.hasError ? [] : [...state.steps],
1274
+ isCancelled: false,
1275
+ currentExecutingStepId: void 0,
1276
+ formattedThinkingText: state.hasError ? void 0 : state.formattedThinkingText || void 0,
1277
+ isResolvingImages: needsImageResolve,
1278
+ totalElapsedMs: state.hasError ? void 0 : state.totalElapsedMs
1279
+ };
1280
+ setMessages(
1281
+ (prev) => prev.map(
1282
+ (msg) => msg.id === streamingId ? finalMessage : msg
1283
+ )
1284
+ );
1285
+ callbacksRef.current.onStreamComplete?.(finalMessage);
1286
+ }
1287
+ });
1288
+ const shouldResolveImages = !abortController.signal.aborted && !state.hasError && hasRagImages(state.finalResponse);
1289
+ if (shouldResolveImages) {
1290
+ await waitForNextPaint(abortController.signal);
1291
+ }
1292
+ if (shouldResolveImages && !abortController.signal.aborted) {
1293
+ try {
1294
+ const resolvedContent = await resolveRagImageUrls(
1295
+ currentConfig,
1296
+ state.finalResponse,
1297
+ abortController.signal
1298
+ );
1299
+ setMessages(
1300
+ (prev) => prev.map(
1301
+ (msg) => msg.id === streamingId ? { ...msg, content: resolvedContent, isResolvingImages: false } : msg
1302
+ )
1303
+ );
1304
+ } catch {
1305
+ setMessages(
1306
+ (prev) => prev.map(
1307
+ (msg) => msg.id === streamingId ? { ...msg, isResolvingImages: false } : msg
1308
+ )
1309
+ );
1310
+ }
1311
+ }
1312
+ return state.sessionId;
1313
+ } catch (error) {
1314
+ setIsWaitingForResponse(false);
1315
+ if (error.name !== "AbortError") {
1316
+ callbacksRef.current.onError?.(error);
1317
+ }
1318
+ const isAborted = error.name === "AbortError";
1319
+ setMessages(
1320
+ (prev) => prev.map(
1321
+ (msg) => msg.id === streamingId ? {
1322
+ ...msg,
1323
+ isStreaming: false,
1324
+ streamProgress: isAborted ? "processing" : "error",
1325
+ isError: !isAborted,
1326
+ isCancelled: isAborted,
1327
+ errorDetails: isAborted ? void 0 : error.message,
1328
+ content: isAborted ? state.finalResponse || "" : state.finalResponse || FRIENDLY_ERROR_MESSAGE,
1329
+ formattedThinkingText: state.formattedThinkingText || void 0,
1330
+ steps: [...state.steps].map((step) => {
1331
+ if (step.status === "in_progress" && isAborted) {
1332
+ return { ...step, status: "pending" };
1333
+ }
1334
+ return step;
1335
+ }),
1336
+ currentExecutingStepId: void 0
1337
+ } : msg
1338
+ )
1339
+ );
1340
+ return state.sessionId;
1341
+ }
1342
+ },
1343
+ [setMessages, setIsWaitingForResponse]
1344
+ );
1345
+ const cancelStream = react.useCallback(() => {
1346
+ abortControllerRef.current?.abort();
1347
+ }, []);
1348
+ return {
1349
+ startStream,
1350
+ cancelStream,
1351
+ abortControllerRef
1352
+ };
1353
+ }
1354
+ var EMPTY_USER_ACTION_STATE = { prompts: [], notifications: [] };
1355
+ function upsertPrompt(prompts, req) {
1356
+ const active = { ...req, status: "pending" };
1357
+ const idx = prompts.findIndex(
1358
+ (p) => req.toolCallId ? p.toolCallId === req.toolCallId : p.userActionId === req.userActionId
1359
+ );
1360
+ if (idx >= 0) {
1361
+ const next = prompts.slice();
1362
+ next[idx] = active;
1363
+ return next;
1364
+ }
1365
+ return [...prompts, active];
1366
+ }
1367
+ function getStoredOrInitialMessages(config) {
1368
+ if (!config.userId) return config.initialMessages ?? [];
1369
+ const activeStream = activeStreamStore.get(config.userId);
1370
+ if (activeStream) return activeStream.messages;
1371
+ const stored = chatStore.get(config.userId);
1372
+ if (stored.length > 0) return stored;
1373
+ if (config.initialMessages?.length) {
1374
+ chatStore.set(config.userId, config.initialMessages);
1375
+ return config.initialMessages;
1376
+ }
1377
+ return [];
1378
+ }
1379
+ function getSessionIdFromMessages(messages) {
1380
+ return messages.find((message) => message.sessionId)?.sessionId;
1381
+ }
1382
+ function useChatV2(config, callbacks = {}) {
1383
+ const [messages, setMessages] = react.useState(() => getStoredOrInitialMessages(config));
1384
+ const [isWaitingForResponse, setIsWaitingForResponse] = react.useState(() => {
1385
+ if (!config.userId) return false;
1386
+ return activeStreamStore.get(config.userId)?.isWaiting ?? false;
1387
+ });
1388
+ const sessionIdRef = react.useRef(
1389
+ getSessionIdFromMessages(getStoredOrInitialMessages(config)) ?? config.initialSessionId ?? void 0
1390
+ );
1391
+ const prevUserIdRef = react.useRef(config.userId);
1392
+ const streamUserIdRef = react.useRef(void 0);
1393
+ const subscriptionPrevUserIdRef = react.useRef(config.userId);
1394
+ const callbacksRef = react.useRef(callbacks);
1395
+ callbacksRef.current = callbacks;
1396
+ const configRef = react.useRef(config);
1397
+ configRef.current = config;
1398
+ const messagesRef = react.useRef(messages);
1399
+ messagesRef.current = messages;
1400
+ const storeAwareSetMessages = react.useCallback(
1401
+ (updater) => {
1402
+ const streamUserId = streamUserIdRef.current;
1403
+ const currentUserId = configRef.current.userId;
1404
+ const storeKey = streamUserId ?? currentUserId;
1405
+ if (storeKey && activeStreamStore.has(storeKey)) {
1406
+ activeStreamStore.applyMessages(storeKey, updater);
1407
+ }
1408
+ if (!streamUserId || streamUserId === currentUserId) {
1409
+ setMessages(updater);
1410
+ }
1411
+ },
1412
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1413
+ []
1414
+ );
1415
+ const storeAwareSetIsWaiting = react.useCallback(
1416
+ (waiting) => {
1417
+ const streamUserId = streamUserIdRef.current;
1418
+ const currentUserId = configRef.current.userId;
1419
+ const storeKey = streamUserId ?? currentUserId;
1420
+ if (storeKey && activeStreamStore.has(storeKey)) {
1421
+ activeStreamStore.setWaiting(storeKey, waiting);
1422
+ }
1423
+ if (!streamUserId || streamUserId === currentUserId) {
1424
+ setIsWaitingForResponse(waiting);
1425
+ }
1426
+ },
1427
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1428
+ []
1429
+ );
1430
+ const [userActionState, setUserActionState] = react.useState(EMPTY_USER_ACTION_STATE);
1431
+ const wrappedCallbacks = react.useMemo(() => ({
1432
+ ...callbacksRef.current,
1433
+ onMessageSent: (message) => callbacksRef.current.onMessageSent?.(message),
1434
+ onStreamStart: () => callbacksRef.current.onStreamStart?.(),
1435
+ onStreamComplete: (message) => callbacksRef.current.onStreamComplete?.(message),
1436
+ onError: (error) => callbacksRef.current.onError?.(error),
1437
+ onExecutionTraceClick: (data) => callbacksRef.current.onExecutionTraceClick?.(data),
1438
+ onSessionIdChange: (sessionId) => callbacksRef.current.onSessionIdChange?.(sessionId),
1439
+ onUserActionRequired: (request) => {
1440
+ setUserActionState((prev) => ({
1441
+ ...prev,
1442
+ prompts: upsertPrompt(prev.prompts, request)
1443
+ }));
1444
+ callbacksRef.current.onUserActionRequired?.(request);
1445
+ },
1446
+ onUserNotification: (notification) => {
1447
+ setUserActionState(
1448
+ (prev) => prev.notifications.some((n) => n.id === notification.id) ? prev : { ...prev, notifications: [...prev.notifications, notification] }
1449
+ );
1450
+ callbacksRef.current.onUserNotification?.(notification);
1451
+ }
1452
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1453
+ }), []);
1454
+ const { startStream, cancelStream: cancelStreamManager, abortControllerRef } = useStreamManagerV2(
1455
+ config,
1456
+ wrappedCallbacks,
1457
+ storeAwareSetMessages,
1458
+ storeAwareSetIsWaiting
1459
+ );
1460
+ const sendMessage = react.useCallback(
1461
+ async (userMessage, options) => {
1462
+ if (!userMessage.trim()) return;
1463
+ if (!sessionIdRef.current && configRef.current.autoGenerateSessionId !== false) {
1464
+ sessionIdRef.current = generateId();
1465
+ callbacksRef.current.onSessionIdChange?.(sessionIdRef.current);
1466
+ }
1467
+ const userMessageId = `user-${Date.now()}`;
1468
+ const userMsg = {
1469
+ id: userMessageId,
1470
+ sessionId: sessionIdRef.current,
1471
+ role: "user",
1472
+ content: userMessage,
1473
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1474
+ };
1475
+ setMessages((prev) => [...prev, userMsg]);
1476
+ callbacksRef.current.onMessageSent?.(userMessage);
1477
+ setIsWaitingForResponse(true);
1478
+ callbacksRef.current.onStreamStart?.();
1479
+ const streamingId = `assistant-${Date.now()}`;
1480
+ const streamingMsg = {
1481
+ id: streamingId,
1482
+ sessionId: sessionIdRef.current,
1483
+ role: "assistant",
1484
+ content: "",
1485
+ streamingContent: "",
1486
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1487
+ isStreaming: true,
1488
+ streamProgress: "started",
1489
+ steps: [],
1490
+ currentExecutingStepId: void 0,
1491
+ isCancelled: false,
1492
+ currentMessage: void 0
1493
+ };
1494
+ setMessages((prev) => [...prev, streamingMsg]);
1495
+ const abortController = new AbortController();
1496
+ const { userId } = configRef.current;
1497
+ if (userId) {
1498
+ streamUserIdRef.current = userId;
1499
+ const initialMessages = [...messagesRef.current, userMsg, streamingMsg];
1500
+ activeStreamStore.start(userId, abortController, initialMessages);
1501
+ }
1502
+ const newSessionId = await startStream(
1503
+ userMessage,
1504
+ streamingId,
1505
+ sessionIdRef.current,
1506
+ abortController,
1507
+ options
1508
+ );
1509
+ const finalStreamUserId = streamUserIdRef.current ?? userId;
1510
+ if (finalStreamUserId) {
1511
+ activeStreamStore.complete(finalStreamUserId);
1512
+ }
1513
+ streamUserIdRef.current = void 0;
1514
+ if (!abortController.signal.aborted && newSessionId && newSessionId !== sessionIdRef.current) {
1515
+ sessionIdRef.current = newSessionId;
1516
+ }
1517
+ },
1518
+ [startStream]
1519
+ );
1520
+ const clearMessages = react.useCallback(() => {
1521
+ if (configRef.current.userId) {
1522
+ chatStore.delete(configRef.current.userId);
1523
+ }
1524
+ setMessages([]);
1525
+ }, []);
1526
+ const prependMessages = react.useCallback((msgs) => {
1527
+ setMessages((prev) => [...msgs, ...prev]);
1528
+ }, []);
1529
+ const cancelStream = react.useCallback(() => {
1530
+ const streamUserId = streamUserIdRef.current ?? configRef.current.userId;
1531
+ if (streamUserId) {
1532
+ activeStreamStore.abort(streamUserId);
1533
+ }
1534
+ streamUserIdRef.current = void 0;
1535
+ cancelStreamManager();
1536
+ setIsWaitingForResponse(false);
1537
+ setUserActionState((prev) => ({ ...prev, prompts: [] }));
1538
+ setMessages(
1539
+ (prev) => prev.map((msg) => {
1540
+ if (msg.isStreaming) {
1541
+ return {
1542
+ ...msg,
1543
+ ...createCancelledMessageUpdate(
1544
+ msg.steps || [],
1545
+ msg.currentMessage
1546
+ )
1547
+ };
1548
+ }
1549
+ return msg;
1550
+ })
1551
+ );
1552
+ }, [cancelStreamManager]);
1553
+ const resetSession = react.useCallback(() => {
1554
+ const streamUserId = streamUserIdRef.current ?? configRef.current.userId;
1555
+ if (streamUserId) {
1556
+ activeStreamStore.abort(streamUserId);
1557
+ }
1558
+ if (configRef.current.userId) {
1559
+ chatStore.delete(configRef.current.userId);
1560
+ }
1561
+ streamUserIdRef.current = void 0;
1562
+ setMessages([]);
1563
+ sessionIdRef.current = void 0;
1564
+ abortControllerRef.current?.abort();
1565
+ setIsWaitingForResponse(false);
1566
+ setUserActionState(EMPTY_USER_ACTION_STATE);
1567
+ }, []);
1568
+ const getSessionId = react.useCallback(() => {
1569
+ return sessionIdRef.current;
1570
+ }, []);
1571
+ const getMessages = react.useCallback(() => {
1572
+ return messages;
1573
+ }, [messages]);
1574
+ const setPromptStatus = react.useCallback(
1575
+ (userActionId, status) => {
1576
+ setUserActionState((prev) => ({
1577
+ ...prev,
1578
+ prompts: prev.prompts.map(
1579
+ (p) => p.userActionId === userActionId ? { ...p, status } : p
1580
+ )
1581
+ }));
1582
+ },
1583
+ []
1584
+ );
1585
+ const removePrompt = react.useCallback((userActionId) => {
1586
+ setUserActionState((prev) => ({
1587
+ ...prev,
1588
+ prompts: prev.prompts.filter((p) => p.userActionId !== userActionId)
1589
+ }));
1590
+ }, []);
1591
+ const submitUserAction2 = react.useCallback(
1592
+ async (userActionId, content) => {
1593
+ setPromptStatus(userActionId, "submitting");
1594
+ try {
1595
+ await submitUserAction(configRef.current, userActionId, content);
1596
+ removePrompt(userActionId);
1597
+ } catch (error) {
1598
+ if (error instanceof UserActionStaleError) {
1599
+ setPromptStatus(userActionId, "stale");
1600
+ return;
1601
+ }
1602
+ setPromptStatus(userActionId, "pending");
1603
+ callbacksRef.current.onError?.(error);
1604
+ throw error;
1605
+ }
1606
+ },
1607
+ [removePrompt, setPromptStatus]
1608
+ );
1609
+ const cancelUserAction2 = react.useCallback(
1610
+ async (userActionId) => {
1611
+ setPromptStatus(userActionId, "submitting");
1612
+ try {
1613
+ await cancelUserAction(configRef.current, userActionId);
1614
+ removePrompt(userActionId);
1615
+ } catch (error) {
1616
+ if (error instanceof UserActionStaleError) {
1617
+ removePrompt(userActionId);
1618
+ return;
1619
+ }
1620
+ setPromptStatus(userActionId, "pending");
1621
+ callbacksRef.current.onError?.(error);
1622
+ throw error;
1623
+ }
1624
+ },
1625
+ [removePrompt, setPromptStatus]
1626
+ );
1627
+ const resendUserAction2 = react.useCallback(
1628
+ async (userActionId) => {
1629
+ setPromptStatus(userActionId, "submitting");
1630
+ try {
1631
+ await resendUserAction(configRef.current, userActionId);
1632
+ setPromptStatus(userActionId, "pending");
1633
+ } catch (error) {
1634
+ if (error instanceof UserActionStaleError) {
1635
+ setPromptStatus(userActionId, "stale");
1636
+ return;
1637
+ }
1638
+ setPromptStatus(userActionId, "pending");
1639
+ callbacksRef.current.onError?.(error);
1640
+ throw error;
1641
+ }
1642
+ },
1643
+ [setPromptStatus]
1644
+ );
1645
+ const dismissNotification = react.useCallback((id) => {
1646
+ setUserActionState((prev) => ({
1647
+ ...prev,
1648
+ notifications: prev.notifications.filter((n) => n.id !== id)
1649
+ }));
1650
+ }, []);
1651
+ react.useEffect(() => {
1652
+ const prevSubscriptionUserId = subscriptionPrevUserIdRef.current;
1653
+ subscriptionPrevUserIdRef.current = config.userId;
1654
+ const { userId } = config;
1655
+ if (!userId) return;
1656
+ if (prevSubscriptionUserId && prevSubscriptionUserId !== userId && streamUserIdRef.current === prevSubscriptionUserId && !activeStreamStore.has(prevSubscriptionUserId) && activeStreamStore.has(userId)) {
1657
+ streamUserIdRef.current = userId;
1658
+ }
1659
+ const unsubscribe = activeStreamStore.subscribe(userId, (msgs, isWaiting) => {
1660
+ setMessages(msgs);
1661
+ setIsWaitingForResponse(isWaiting);
1662
+ });
1663
+ const active = activeStreamStore.get(userId);
1664
+ if (active) {
1665
+ setMessages(active.messages);
1666
+ setIsWaitingForResponse(active.isWaiting);
1667
+ }
1668
+ return unsubscribe;
1669
+ }, [config.userId]);
1670
+ react.useEffect(() => {
1671
+ if (!config.userId) return;
1672
+ if (prevUserIdRef.current !== config.userId) return;
1673
+ const toSave = messages.filter((m) => !m.isStreaming);
1674
+ if (toSave.length > 0) {
1675
+ chatStore.set(config.userId, toSave);
1676
+ }
1677
+ }, [messages, config.userId]);
1678
+ react.useEffect(() => {
1679
+ if (!config.userId || activeStreamStore.has(config.userId)) return;
1680
+ if (!config.initialMessages?.length || messagesRef.current.length > 0) return;
1681
+ chatStore.set(config.userId, config.initialMessages);
1682
+ setMessages(config.initialMessages);
1683
+ sessionIdRef.current = getSessionIdFromMessages(config.initialMessages) ?? config.initialSessionId;
1684
+ }, [config.initialMessages, config.initialSessionId, config.userId]);
1685
+ react.useEffect(() => {
1686
+ const prevUserId = prevUserIdRef.current;
1687
+ prevUserIdRef.current = config.userId;
1688
+ if (prevUserId === config.userId) return;
1689
+ if (prevUserId && !config.userId) {
1690
+ chatStore.delete(prevUserId);
1691
+ setMessages([]);
1692
+ sessionIdRef.current = void 0;
1693
+ setIsWaitingForResponse(false);
1694
+ setUserActionState(EMPTY_USER_ACTION_STATE);
1695
+ } else if (config.userId) {
1696
+ const active = activeStreamStore.get(config.userId);
1697
+ if (active) {
1698
+ setMessages(active.messages);
1699
+ setIsWaitingForResponse(active.isWaiting);
1700
+ sessionIdRef.current = getSessionIdFromMessages(active.messages) ?? config.initialSessionId;
1701
+ return;
1702
+ }
1703
+ const nextMessages = getStoredOrInitialMessages(config);
1704
+ setMessages(nextMessages);
1705
+ sessionIdRef.current = getSessionIdFromMessages(nextMessages) ?? config.initialSessionId;
1706
+ setIsWaitingForResponse(false);
1707
+ }
1708
+ }, [config]);
1709
+ return {
1710
+ messages,
1711
+ sendMessage,
1712
+ clearMessages,
1713
+ prependMessages,
1714
+ cancelStream,
1715
+ resetSession,
1716
+ getSessionId,
1717
+ getMessages,
1718
+ isWaitingForResponse,
1719
+ sessionId: sessionIdRef.current,
1720
+ userActionState,
1721
+ submitUserAction: submitUserAction2,
1722
+ cancelUserAction: cancelUserAction2,
1723
+ resendUserAction: resendUserAction2,
1724
+ dismissNotification
1725
+ };
1726
+ }
1727
+ function getSpeechRecognition() {
1728
+ if (typeof window === "undefined") return null;
1729
+ return window.SpeechRecognition || window.webkitSpeechRecognition || null;
1730
+ }
1731
+ function useVoice(config = {}, callbacks = {}) {
1732
+ const [voiceState, setVoiceState] = react.useState("idle");
1733
+ const [transcribedText, setTranscribedText] = react.useState("");
1734
+ const [isAvailable, setIsAvailable] = react.useState(false);
1735
+ const [isRecording, setIsRecording] = react.useState(false);
1736
+ const recognitionRef = react.useRef(null);
1737
+ const autoStopTimerRef = react.useRef(null);
1738
+ const {
1739
+ lang = "en-US",
1740
+ interimResults = true,
1741
+ continuous = true,
1742
+ maxAlternatives = 1,
1743
+ autoStopAfterSilence
1744
+ } = config;
1745
+ const { onStart, onEnd, onResult, onError, onStateChange } = callbacks;
1746
+ react.useEffect(() => {
1747
+ const SpeechRecognitionAPI = getSpeechRecognition();
1748
+ setIsAvailable(SpeechRecognitionAPI !== null);
1749
+ }, []);
1750
+ react.useEffect(() => {
1751
+ onStateChange?.(voiceState);
1752
+ }, [voiceState, onStateChange]);
1753
+ const requestPermissions = react.useCallback(async () => {
1754
+ try {
1755
+ const result = await navigator.mediaDevices.getUserMedia({
1756
+ audio: true
1757
+ });
1758
+ result.getTracks().forEach((track) => track.stop());
1759
+ return {
1760
+ granted: true,
1761
+ status: "granted"
1762
+ };
1763
+ } catch (error) {
1764
+ return {
1765
+ granted: false,
1766
+ status: "denied"
1767
+ };
1768
+ }
1769
+ }, []);
1770
+ const getPermissions = react.useCallback(async () => {
1771
+ if (typeof navigator === "undefined" || !navigator.permissions) {
1772
+ return {
1773
+ granted: false,
1774
+ status: "undetermined"
1775
+ };
1776
+ }
1777
+ try {
1778
+ const result = await navigator.permissions.query({
1779
+ name: "microphone"
1780
+ });
1781
+ return {
1782
+ granted: result.state === "granted",
1783
+ status: result.state === "granted" ? "granted" : result.state === "denied" ? "denied" : "undetermined"
1784
+ };
1785
+ } catch {
1786
+ return {
1787
+ granted: false,
1788
+ status: "undetermined"
1789
+ };
1790
+ }
1791
+ }, []);
1792
+ const clearAutoStopTimer = react.useCallback(() => {
1793
+ if (autoStopTimerRef.current) {
1794
+ clearTimeout(autoStopTimerRef.current);
1795
+ autoStopTimerRef.current = null;
1796
+ }
1797
+ }, []);
1798
+ const resetAutoStopTimer = react.useCallback(() => {
1799
+ clearAutoStopTimer();
1800
+ if (autoStopAfterSilence && autoStopAfterSilence > 0) {
1801
+ autoStopTimerRef.current = setTimeout(() => {
1802
+ if (recognitionRef.current && isRecording) {
1803
+ recognitionRef.current.stop();
1804
+ }
1805
+ }, autoStopAfterSilence);
1806
+ }
1807
+ }, [autoStopAfterSilence, clearAutoStopTimer, isRecording]);
1808
+ const stopRecording = react.useCallback(() => {
1809
+ if (recognitionRef.current) {
1810
+ try {
1811
+ recognitionRef.current.stop();
1812
+ } catch (error) {
1813
+ console.warn("Error stopping speech recognition:", error);
1814
+ }
1815
+ }
1816
+ clearAutoStopTimer();
1817
+ setIsRecording(false);
1818
+ setVoiceState("idle");
1819
+ }, [clearAutoStopTimer]);
1820
+ const startRecording = react.useCallback(async () => {
1821
+ const SpeechRecognitionAPI = getSpeechRecognition();
1822
+ if (!SpeechRecognitionAPI) {
1823
+ onError?.("Speech recognition not supported in this browser");
1824
+ return;
1825
+ }
1826
+ try {
1827
+ try {
1828
+ await navigator.mediaDevices.getUserMedia({ audio: true });
1829
+ } catch (permError) {
1830
+ onError?.("Microphone access denied. Please allow microphone access in your browser settings.");
1831
+ return;
1832
+ }
1833
+ const recognition = new SpeechRecognitionAPI();
1834
+ recognition.continuous = continuous;
1835
+ recognition.interimResults = interimResults;
1836
+ recognition.lang = lang;
1837
+ recognition.maxAlternatives = maxAlternatives;
1838
+ recognition.onstart = () => {
1839
+ setVoiceState("listening");
1840
+ setIsRecording(true);
1841
+ onStart?.();
1842
+ resetAutoStopTimer();
1843
+ };
1844
+ recognition.onend = () => {
1845
+ setVoiceState("idle");
1846
+ setIsRecording(false);
1847
+ clearAutoStopTimer();
1848
+ onEnd?.();
1849
+ };
1850
+ recognition.onresult = (event) => {
1851
+ const results = event.results;
1852
+ let transcript = "";
1853
+ for (let i = 0; i < results.length; i++) {
1854
+ const result = results[i];
1855
+ if (result && result[0]) {
1856
+ const text = result[0].transcript;
1857
+ if (transcript && !transcript.endsWith(" ") && !text.startsWith(" ")) {
1858
+ transcript += " " + text;
1859
+ } else {
1860
+ transcript += text;
1861
+ }
1862
+ }
1863
+ }
1864
+ transcript = transcript.trim();
1865
+ if (transcript) {
1866
+ setTranscribedText(transcript);
1867
+ onResult?.(transcript);
1868
+ resetAutoStopTimer();
1869
+ }
1870
+ };
1871
+ recognition.onerror = (event) => {
1872
+ setVoiceState("error");
1873
+ setIsRecording(false);
1874
+ clearAutoStopTimer();
1875
+ let errorMessage = event.error;
1876
+ if (event.error === "not-allowed") {
1877
+ errorMessage = "Microphone access denied. Please allow microphone access in your browser settings.";
1878
+ } else if (event.error === "no-speech") {
1879
+ errorMessage = "No speech detected. Please try again.";
1880
+ } else if (event.error === "audio-capture") {
1881
+ errorMessage = "No microphone found or microphone is in use.";
1882
+ } else if (event.error === "network") {
1883
+ errorMessage = "Network error occurred. Please check your connection.";
1884
+ }
1885
+ onError?.(errorMessage);
1886
+ };
1887
+ recognitionRef.current = recognition;
1888
+ setTranscribedText("");
1889
+ recognition.start();
1890
+ } catch (error) {
1891
+ setVoiceState("error");
1892
+ setIsRecording(false);
1893
+ onError?.(
1894
+ error instanceof Error ? error.message : "Failed to start recording"
1895
+ );
1896
+ }
1897
+ }, [
1898
+ lang,
1899
+ interimResults,
1900
+ continuous,
1901
+ maxAlternatives,
1902
+ onStart,
1903
+ onEnd,
1904
+ onResult,
1905
+ onError,
1906
+ getPermissions,
1907
+ resetAutoStopTimer,
1908
+ clearAutoStopTimer
1909
+ ]);
1910
+ const clearTranscript = react.useCallback(() => {
1911
+ setTranscribedText("");
1912
+ }, []);
1913
+ const reset = react.useCallback(() => {
1914
+ stopRecording();
1915
+ setTranscribedText("");
1916
+ setVoiceState("idle");
1917
+ }, [stopRecording]);
1918
+ react.useEffect(() => {
1919
+ return () => {
1920
+ if (recognitionRef.current) {
1921
+ try {
1922
+ recognitionRef.current.stop();
1923
+ } catch {
1924
+ }
1925
+ }
1926
+ clearAutoStopTimer();
1927
+ };
1928
+ }, [clearAutoStopTimer]);
1929
+ return {
1930
+ voiceState,
1931
+ transcribedText,
1932
+ isAvailable,
1933
+ isRecording,
1934
+ startRecording,
1935
+ stopRecording,
1936
+ requestPermissions,
1937
+ getPermissions,
1938
+ clearTranscript,
1939
+ reset
1940
+ };
1941
+ }
1942
+ function classifyField(field) {
1943
+ if (!field) return "text";
1944
+ if (Array.isArray(field.oneOf) && field.oneOf.length > 0) return "select";
1945
+ switch (field.type) {
1946
+ case "boolean":
1947
+ return "boolean";
1948
+ case "integer":
1949
+ return "integer";
1950
+ case "number":
1951
+ return "decimal";
1952
+ case "string":
1953
+ return "text";
1954
+ default:
1955
+ return "text";
1956
+ }
1957
+ }
1958
+ function isNestedOrUnsupported(field) {
1959
+ if (!field) return false;
1960
+ if (field.type === "object" || field.type === "array") return true;
1961
+ if ("properties" in field && field.properties != null) return true;
1962
+ if ("items" in field && field.items != null) return true;
1963
+ return false;
1964
+ }
1965
+ function getOptions(field) {
1966
+ if (!field || !Array.isArray(field.oneOf)) return [];
1967
+ return field.oneOf.filter(
1968
+ (o) => !!o && typeof o === "object" && typeof o.const === "string"
1969
+ );
1970
+ }
1971
+ function isRequired(schema, key) {
1972
+ return Array.isArray(schema?.required) && schema.required.includes(key);
1973
+ }
1974
+ function coerceValue(field, raw) {
1975
+ const widget = classifyField(field);
1976
+ if (widget === "boolean") {
1977
+ if (typeof raw === "boolean") return raw;
1978
+ if (raw === "true") return true;
1979
+ if (raw === "false") return false;
1980
+ return Boolean(raw);
1981
+ }
1982
+ if (widget === "integer" || widget === "decimal") {
1983
+ if (raw === "" || raw == null) return void 0;
1984
+ const num = typeof raw === "number" ? raw : Number(String(raw).trim());
1985
+ if (Number.isNaN(num)) return void 0;
1986
+ return widget === "integer" ? Math.trunc(num) : num;
1987
+ }
1988
+ if (raw == null) return void 0;
1989
+ const str = String(raw);
1990
+ return str === "" ? void 0 : str;
1991
+ }
1992
+ function defaultValueFor(field) {
1993
+ if (!field || field.default === void 0) {
1994
+ return classifyField(field) === "boolean" ? false : "";
1995
+ }
1996
+ return field.default;
1997
+ }
1998
+ function validateField(field, value, required) {
1999
+ const widget = classifyField(field);
2000
+ const label = field?.title || "This field";
2001
+ const isEmpty = value === void 0 || value === null || typeof value === "string" && value.trim() === "";
2002
+ if (isEmpty) {
2003
+ if (required && widget !== "boolean") return `${label} is required.`;
2004
+ return null;
2005
+ }
2006
+ if (widget === "integer" || widget === "decimal") {
2007
+ const num = typeof value === "number" ? value : Number(value);
2008
+ if (Number.isNaN(num)) return `${label} must be a number.`;
2009
+ if (widget === "integer" && !Number.isInteger(num)) {
2010
+ return `${label} must be a whole number.`;
2011
+ }
2012
+ if (typeof field?.minimum === "number" && num < field.minimum) {
2013
+ return `${label} must be at least ${field.minimum}.`;
2014
+ }
2015
+ if (typeof field?.maximum === "number" && num > field.maximum) {
2016
+ return `${label} must be at most ${field.maximum}.`;
2017
+ }
2018
+ return null;
2019
+ }
2020
+ if (widget === "select") {
2021
+ const allowed = getOptions(field).map((o) => o.const);
2022
+ if (allowed.length > 0 && !allowed.includes(String(value))) {
2023
+ return `${label} has an invalid selection.`;
2024
+ }
2025
+ return null;
2026
+ }
2027
+ const str = String(value);
2028
+ if (typeof field?.minLength === "number" && str.length < field.minLength) {
2029
+ return `${label} must be at least ${field.minLength} characters.`;
2030
+ }
2031
+ if (typeof field?.maxLength === "number" && str.length > field.maxLength) {
2032
+ return `${label} must be at most ${field.maxLength} characters.`;
2033
+ }
2034
+ return null;
2035
+ }
2036
+ function renderableFields(schema) {
2037
+ const props = schema?.properties;
2038
+ if (!props) return [];
2039
+ return Object.entries(props).filter(([, field]) => !isNestedOrUnsupported(field));
2040
+ }
2041
+ function validateForm(schema, values) {
2042
+ const errors = {};
2043
+ for (const [key, field] of renderableFields(schema)) {
2044
+ const coerced = coerceValue(field, values[key]);
2045
+ const err = validateField(field, coerced, isRequired(schema, key));
2046
+ if (err) errors[key] = err;
2047
+ }
2048
+ return errors;
2049
+ }
2050
+ function buildContent(schema, values) {
2051
+ const content = {};
2052
+ for (const [key, field] of renderableFields(schema)) {
2053
+ const coerced = coerceValue(field, values[key]);
2054
+ if (coerced !== void 0) content[key] = coerced;
2055
+ }
2056
+ return content;
2057
+ }
2058
+ function migrateActiveStream(oldUserId, newUserId) {
2059
+ activeStreamStore.rename(oldUserId, newUserId);
35
2060
  }
36
-
37
- var Sentry__namespace = /*#__PURE__*/_interopNamespace(Sentry);
38
- var ReactMarkdown__default = /*#__PURE__*/_interopDefault(ReactMarkdown);
39
- var remarkGfm__default = /*#__PURE__*/_interopDefault(remarkGfm);
40
- var remarkBreaks__default = /*#__PURE__*/_interopDefault(remarkBreaks);
41
-
42
2061
  var PaymanChatContext = react.createContext(void 0);
43
2062
  function usePaymanChat() {
44
2063
  const context = react.useContext(PaymanChatContext);
@@ -258,7 +2277,7 @@ var NEGATIVE_FEEDBACK_REASONS = [
258
2277
  { value: "REPORT_CONTENT", label: "Report content" },
259
2278
  { value: "OTHER", label: "Other" }
260
2279
  ];
261
- var DEFAULT_STREAM_ENDPOINT = "/api/playground/ask/stream";
2280
+ var DEFAULT_STREAM_ENDPOINT2 = "/api/playground/ask/stream";
262
2281
  async function submitFeedback({
263
2282
  baseUrl,
264
2283
  streamEndpoint,
@@ -272,7 +2291,7 @@ async function submitFeedback({
272
2291
  signal
273
2292
  }) {
274
2293
  const base = baseUrl.replace(/\/+$/, "");
275
- const endpointPath = (streamEndpoint || DEFAULT_STREAM_ENDPOINT).split("?")[0].replace(/\/+$/, "");
2294
+ const endpointPath = (streamEndpoint || DEFAULT_STREAM_ENDPOINT2).split("?")[0].replace(/\/+$/, "");
276
2295
  const basePath = endpointPath.endsWith("/stream") ? endpointPath.slice(0, -"/stream".length) : endpointPath;
277
2296
  const query = new URLSearchParams();
278
2297
  if (stage) query.set(stageQueryParam ?? "stage", stage);
@@ -584,7 +2603,7 @@ function ThinkingBlock({ text }) {
584
2603
  ) })
585
2604
  ] });
586
2605
  }
587
- var FRIENDLY_ERROR_MESSAGE = "Oops, something went wrong. Please try again.";
2606
+ var FRIENDLY_ERROR_MESSAGE2 = "Oops, something went wrong. Please try again.";
588
2607
  function looksLikeRawError(text) {
589
2608
  if (!text || text.length < 10) return false;
590
2609
  return text.includes("errorType=") || /failed:\s*\{/.test(text);
@@ -750,95 +2769,86 @@ function AgentMessage({
750
2769
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2.5 w-2.5 rounded-full payman-agent-avatar-dot animate-pulse" }),
751
2770
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "absolute inset-0 h-2.5 w-2.5 rounded-full payman-agent-avatar-dot-ping animate-ping" })
752
2771
  ] }) }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-8 w-8 rounded-full payman-agent-avatar flex items-center justify-center", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Sparkles, { className: "h-3.5 w-3.5 payman-agent-avatar-icon" }) }) }),
753
- /* @__PURE__ */ jsxRuntime.jsxs(
2772
+ /* @__PURE__ */ jsxRuntime.jsx(
754
2773
  "div",
755
2774
  {
756
2775
  className: cn(
757
2776
  "min-w-0",
758
2777
  layout === "centered" ? "max-w-[85%]" : showAvatar ? "max-w-[85%]" : "max-w-[80%]"
759
2778
  ),
760
- children: [
761
- message.userActionResult && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mb-2", children: message.userActionResult === "approved" ? /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "inline-flex items-center gap-1.5 px-4 py-1.5 text-xs font-semibold rounded-full payman-agent-approved shrink-0", children: [
762
- /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "w-3.5 h-3.5 shrink-0", strokeWidth: 2.5 }),
763
- "Verified"
764
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "inline-flex items-center gap-1.5 px-4 py-1.5 text-xs font-semibold rounded-full payman-agent-rejected shrink-0", children: [
765
- /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "w-3.5 h-3.5 shrink-0", strokeWidth: 2.5 }),
766
- "Rejected"
767
- ] }) }),
768
- /* @__PURE__ */ jsxRuntime.jsxs(
769
- "div",
770
- {
771
- className: cn(
772
- "overflow-hidden w-full min-w-0 px-4 py-3 rounded-2xl rounded-tl-md transition-all duration-200",
773
- layout === "centered" ? cn(
774
- "payman-agent-bubble payman-agent-bubble--centered",
775
- isStreaming && "streaming",
776
- isError && "error"
777
- ) : cn(
778
- "payman-agent-bubble",
779
- isError && "payman-agent-bubble--error"
780
- )
2779
+ children: /* @__PURE__ */ jsxRuntime.jsxs(
2780
+ "div",
2781
+ {
2782
+ className: cn(
2783
+ "overflow-hidden w-full min-w-0 px-4 py-3 rounded-2xl rounded-tl-md transition-all duration-200",
2784
+ layout === "centered" ? cn(
2785
+ "payman-agent-bubble payman-agent-bubble--centered",
2786
+ isStreaming && "streaming",
2787
+ isError && "error"
2788
+ ) : cn(
2789
+ "payman-agent-bubble",
2790
+ isError && "payman-agent-bubble--error"
2791
+ )
2792
+ ),
2793
+ children: [
2794
+ showAgentName && /* @__PURE__ */ jsxRuntime.jsx(
2795
+ "p",
2796
+ {
2797
+ className: cn(
2798
+ "text-sm font-semibold mb-1 leading-none payman-agent-name",
2799
+ isStreaming && !content && "animate-pulse"
2800
+ ),
2801
+ children: isStreaming && !content ? "Thought Process" : agentName
2802
+ }
781
2803
  ),
782
- children: [
783
- showAgentName && /* @__PURE__ */ jsxRuntime.jsx(
784
- "p",
785
- {
786
- className: cn(
787
- "text-sm font-semibold mb-1 leading-none payman-agent-name",
788
- isStreaming && !content && "animate-pulse"
789
- ),
790
- children: isStreaming && !content ? "Thought Process" : agentName
791
- }
792
- ),
793
- /* @__PURE__ */ jsxRuntime.jsx(
794
- "div",
795
- {
796
- className: cn(
797
- "text-sm leading-relaxed min-w-0 w-full break-words overflow-wrap-anywhere",
798
- showAgentName && "mt-1"
799
- ),
800
- children: isStreaming && !content ? (
801
- // Streaming without content — show thinking/step indicator
802
- activeThinkingText ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2 items-start", children: [
803
- /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "h-4 w-4 mt-0.5 payman-agent-thinking-spinner animate-spin shrink-0" }),
804
- /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-sm leading-relaxed min-w-0 break-words payman-agent-thinking-text whitespace-pre-wrap flex-1", children: [
805
- activeThinkingText,
806
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "inline-block w-0.5 h-3.5 payman-agent-thinking-cursor animate-pulse ml-0.5 align-text-bottom" })
807
- ] })
808
- ] }) : currentStep ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-1.5 items-start", children: [
809
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-0.5 shrink-0", children: renderStepIcon(currentStep, true) }),
810
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm leading-relaxed min-w-0 break-words shimmer-text font-medium flex-1", children: currentStep.message })
811
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2.5 items-start", children: [
812
- /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "w-4 h-4 mt-0.5 payman-agent-thinking-spinner animate-spin shrink-0" }),
813
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm payman-agent-thinking-text flex-1", children: currentMessage || "Thinking..." })
2804
+ /* @__PURE__ */ jsxRuntime.jsx(
2805
+ "div",
2806
+ {
2807
+ className: cn(
2808
+ "text-sm leading-relaxed min-w-0 w-full break-words overflow-wrap-anywhere",
2809
+ showAgentName && "mt-1"
2810
+ ),
2811
+ children: isStreaming && !content ? (
2812
+ // Streaming without content show thinking/step indicator
2813
+ activeThinkingText ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2 items-start", children: [
2814
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "h-4 w-4 mt-0.5 payman-agent-thinking-spinner animate-spin shrink-0" }),
2815
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-sm leading-relaxed min-w-0 break-words payman-agent-thinking-text whitespace-pre-wrap flex-1", children: [
2816
+ activeThinkingText,
2817
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "inline-block w-0.5 h-3.5 payman-agent-thinking-cursor animate-pulse ml-0.5 align-text-bottom" })
814
2818
  ] })
815
- ) : isCancelled && !content ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2.5 items-start", children: [
816
- /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "w-4 h-4 mt-0.5 payman-agent-cancelled-icon shrink-0" }),
817
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm payman-agent-cancelled-text italic flex-1", children: currentMessage || "Request was stopped." })
818
- ] }) : /* @__PURE__ */ jsxRuntime.jsx(
819
- "div",
820
- {
821
- className: cn(
822
- "payman-markdown payman-agent-markdown prose prose-sm dark:prose-invert max-w-none min-w-0 w-full break-words overflow-wrap-anywhere",
823
- isError && "payman-agent-markdown--error",
824
- isStreaming && content && "streaming-cursor"
825
- ),
826
- children: /* @__PURE__ */ jsxRuntime.jsx(
827
- ReactMarkdown__default.default,
828
- {
829
- remarkPlugins: [remarkGfm__default.default],
830
- components: markdownRenderers,
831
- children: isError ? conflictErrorMessage ?? FRIENDLY_ERROR_MESSAGE : content || (isStreaming ? "Thinking..." : isCancelled ? "Request was stopped." : "")
832
- }
833
- )
834
- }
835
- )
836
- }
837
- )
838
- ]
839
- }
840
- )
841
- ]
2819
+ ] }) : currentStep ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-1.5 items-start", children: [
2820
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-0.5 shrink-0", children: renderStepIcon(currentStep, true) }),
2821
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm leading-relaxed min-w-0 break-words shimmer-text font-medium flex-1", children: currentStep.message })
2822
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2.5 items-start", children: [
2823
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "w-4 h-4 mt-0.5 payman-agent-thinking-spinner animate-spin shrink-0" }),
2824
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm payman-agent-thinking-text flex-1", children: currentMessage || "Thinking..." })
2825
+ ] })
2826
+ ) : isCancelled && !content ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2.5 items-start", children: [
2827
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "w-4 h-4 mt-0.5 payman-agent-cancelled-icon shrink-0" }),
2828
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm payman-agent-cancelled-text italic flex-1", children: currentMessage || "Request was stopped." })
2829
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx(
2830
+ "div",
2831
+ {
2832
+ className: cn(
2833
+ "payman-markdown payman-agent-markdown prose prose-sm dark:prose-invert max-w-none min-w-0 w-full break-words overflow-wrap-anywhere",
2834
+ isError && "payman-agent-markdown--error",
2835
+ isStreaming && content && "streaming-cursor"
2836
+ ),
2837
+ children: /* @__PURE__ */ jsxRuntime.jsx(
2838
+ ReactMarkdown__default.default,
2839
+ {
2840
+ remarkPlugins: [remarkGfm__default.default],
2841
+ components: markdownRenderers,
2842
+ children: isError ? conflictErrorMessage ?? FRIENDLY_ERROR_MESSAGE2 : content || (isStreaming ? "Thinking..." : isCancelled ? "Request was stopped." : "")
2843
+ }
2844
+ )
2845
+ }
2846
+ )
2847
+ }
2848
+ )
2849
+ ]
2850
+ }
2851
+ )
842
2852
  }
843
2853
  )
844
2854
  ] }),
@@ -2509,56 +4519,61 @@ function OtpInputV2({
2509
4519
  i
2510
4520
  )) });
2511
4521
  }
4522
+ var DEFAULT_CODE_LEN = 6;
2512
4523
  var RESEND_COOLDOWN_S = 30;
2513
- var OTP_LEN = 6;
2514
- function VerificationCardV2({
2515
- messageId,
2516
- action,
2517
- status,
2518
- clearOtpTrigger = 0,
2519
- onApprove,
2520
- onReject,
4524
+ function codeLengthFromSchema(prompt) {
4525
+ const field = prompt.requestedSchema?.properties?.verificationCode;
4526
+ const max = typeof field?.maxLength === "number" ? field.maxLength : void 0;
4527
+ const min = typeof field?.minLength === "number" ? field.minLength : void 0;
4528
+ return max ?? min ?? DEFAULT_CODE_LEN;
4529
+ }
4530
+ function VerificationInline({
4531
+ prompt,
4532
+ secondsLeft,
4533
+ expired,
4534
+ onSubmit,
4535
+ onCancel,
2521
4536
  onResend
2522
4537
  }) {
2523
- const [otp, setOtp] = react.useState("");
2524
- const [otpErrored, setOtpErrored] = react.useState(false);
4538
+ const isNumeric = prompt.verificationType !== "ALPHANUMERIC_CODE";
4539
+ const codeLen = react.useMemo(() => codeLengthFromSchema(prompt), [prompt]);
4540
+ const [code, setCode] = react.useState("");
4541
+ const [errored, setErrored] = react.useState(false);
2525
4542
  const [resendSec, setResendSec] = react.useState(0);
2526
- const [localPending, setLocalPending] = react.useState(false);
2527
4543
  const lastSubmittedRef = react.useRef(null);
2528
4544
  const resendTimerRef = react.useRef(void 0);
4545
+ const status = prompt.status;
4546
+ const busy = status === "submitting";
4547
+ const stale = status === "stale";
4548
+ const locked = busy || stale || expired;
2529
4549
  react.useEffect(() => {
2530
- if (clearOtpTrigger <= 0) return;
2531
- setOtpErrored(true);
2532
- const t = window.setTimeout(() => {
2533
- setOtp("");
2534
- setOtpErrored(false);
2535
- setLocalPending(false);
2536
- lastSubmittedRef.current = null;
2537
- }, 600);
2538
- return () => window.clearTimeout(t);
2539
- }, [clearOtpTrigger]);
2540
- react.useEffect(() => {
2541
- if (otp.length < OTP_LEN) {
4550
+ if (prompt.subAction === "SubmissionInvalid") {
4551
+ setErrored(true);
4552
+ setCode("");
2542
4553
  lastSubmittedRef.current = null;
2543
4554
  }
2544
- }, [otp]);
4555
+ }, [prompt.subAction, prompt.userActionId]);
2545
4556
  react.useEffect(() => {
2546
- if (status !== "pending") {
2547
- setLocalPending(false);
2548
- }
2549
- }, [status]);
4557
+ if (code.length < codeLen) lastSubmittedRef.current = null;
4558
+ }, [code, codeLen]);
4559
+ const doSubmit = react.useCallback(
4560
+ (value) => {
4561
+ if (locked || !value) return;
4562
+ if (lastSubmittedRef.current === value) return;
4563
+ lastSubmittedRef.current = value;
4564
+ void onSubmit(prompt.userActionId, { verificationCode: value }).catch(() => {
4565
+ lastSubmittedRef.current = null;
4566
+ setErrored(true);
4567
+ });
4568
+ },
4569
+ [locked, onSubmit, prompt.userActionId]
4570
+ );
2550
4571
  react.useEffect(() => {
2551
- if (otp.length !== OTP_LEN || !/^\d+$/.test(otp) || status !== "pending") {
2552
- return;
4572
+ if (!isNumeric || locked) return;
4573
+ if (code.length === codeLen && /^\d+$/.test(code)) {
4574
+ doSubmit(code);
2553
4575
  }
2554
- if (lastSubmittedRef.current === otp) return;
2555
- lastSubmittedRef.current = otp;
2556
- setLocalPending(true);
2557
- void onApprove(messageId, otp).catch(() => {
2558
- lastSubmittedRef.current = null;
2559
- setLocalPending(false);
2560
- });
2561
- }, [messageId, onApprove, otp, status]);
4576
+ }, [code, codeLen, doSubmit, isNumeric, locked]);
2562
4577
  react.useEffect(() => {
2563
4578
  return () => {
2564
4579
  if (typeof resendTimerRef.current === "number") {
@@ -2585,94 +4600,309 @@ function VerificationCardV2({
2585
4600
  }, 1e3);
2586
4601
  }, []);
2587
4602
  const handleResend = react.useCallback(async () => {
2588
- if (resendSec > 0 || status === "verifying" || localPending) return;
2589
- setLocalPending(true);
4603
+ if (locked || resendSec > 0) return;
4604
+ setErrored(false);
4605
+ setCode("");
4606
+ lastSubmittedRef.current = null;
2590
4607
  try {
2591
- await onResend(messageId);
4608
+ await onResend(prompt.userActionId);
2592
4609
  startResendCooldown();
2593
- } finally {
2594
- setLocalPending(false);
2595
- }
2596
- }, [localPending, messageId, onResend, resendSec, startResendCooldown, status]);
2597
- const handleCancel = react.useCallback(async () => {
2598
- if (status === "verifying" || localPending) return;
2599
- setLocalPending(true);
2600
- try {
2601
- await onReject(messageId);
2602
- } finally {
2603
- setLocalPending(false);
4610
+ } catch {
2604
4611
  }
2605
- }, [localPending, messageId, onReject, status]);
2606
- const busy = status === "verifying" || localPending;
2607
- if (status === "approved" || status === "rejected") {
2608
- return null;
2609
- }
2610
- return /* @__PURE__ */ jsxRuntime.jsxs(
2611
- framerMotion.motion.div,
2612
- {
2613
- className: "payman-v2-verification",
2614
- initial: { opacity: 0, y: 10 },
2615
- animate: { opacity: 1, y: 0 },
2616
- transition: { type: "spring", stiffness: 320, damping: 28 },
2617
- children: [
2618
- /* @__PURE__ */ jsxRuntime.jsxs(
2619
- "div",
4612
+ }, [locked, onResend, prompt.userActionId, resendSec, startResendCooldown]);
4613
+ const handleCancel = react.useCallback(() => {
4614
+ if (busy) return;
4615
+ void onCancel(prompt.userActionId);
4616
+ }, [busy, onCancel, prompt.userActionId]);
4617
+ const description = prompt.message?.trim() || (isNumeric ? `Enter the ${codeLen}-digit code to continue` : "Enter the verification code to continue");
4618
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "payman-v2-ua", role: "group", "aria-label": "Verification required", children: [
4619
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "payman-v2-ua-head", children: [
4620
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ShieldCheck, { className: "payman-v2-ua-icon", size: 15, strokeWidth: 1.75, "aria-hidden": true }),
4621
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "payman-v2-ua-title", children: "Verification required" }),
4622
+ typeof secondsLeft === "number" && !stale && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "payman-v2-ua-timer", children: expired ? "Expired" : `${secondsLeft}s` })
4623
+ ] }),
4624
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "payman-v2-ua-desc", children: description }),
4625
+ stale ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "payman-v2-ua-stale", children: "This request is no longer available." }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
4626
+ isNumeric ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "payman-v2-ua-field", children: /* @__PURE__ */ jsxRuntime.jsx(
4627
+ OtpInputV2,
4628
+ {
4629
+ value: code,
4630
+ onChange: (v) => {
4631
+ setErrored(false);
4632
+ setCode(v);
4633
+ },
4634
+ maxLength: codeLen,
4635
+ disabled: locked,
4636
+ error: errored
4637
+ }
4638
+ ) }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "payman-v2-ua-field", children: /* @__PURE__ */ jsxRuntime.jsx(
4639
+ "input",
4640
+ {
4641
+ type: "text",
4642
+ className: cn("payman-v2-ua-input", errored && "payman-v2-ua-input-error"),
4643
+ value: code,
4644
+ disabled: locked,
4645
+ autoComplete: "one-time-code",
4646
+ placeholder: "Verification code",
4647
+ onChange: (e) => {
4648
+ setErrored(false);
4649
+ setCode(e.target.value);
4650
+ },
4651
+ onKeyDown: (e) => {
4652
+ if (e.key === "Enter") {
4653
+ e.preventDefault();
4654
+ doSubmit(code.trim());
4655
+ }
4656
+ }
4657
+ }
4658
+ ) }),
4659
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "payman-v2-ua-actions", children: [
4660
+ !isNumeric && /* @__PURE__ */ jsxRuntime.jsx(
4661
+ "button",
2620
4662
  {
2621
- className: cn(
2622
- "payman-v2-verification-card",
2623
- busy && "payman-v2-verification-card-busy"
2624
- ),
2625
- children: [
2626
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "payman-v2-verification-header", children: [
2627
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "payman-v2-verification-header-row", children: [
2628
- /* @__PURE__ */ jsxRuntime.jsx(
2629
- lucideReact.ShieldCheck,
2630
- {
2631
- className: "payman-v2-verification-icon",
2632
- size: 18,
2633
- strokeWidth: 1.75,
2634
- "aria-hidden": true
2635
- }
2636
- ),
2637
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "payman-v2-verification-title", children: "Verify" }),
2638
- action.amount != null ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "payman-v2-verification-amount", children: action.amount }) : action.payeeName ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "payman-v2-verification-payee", children: action.payeeName }) : null
2639
- ] }),
2640
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "payman-v2-verification-description", children: "Enter the 6-digit code sent to your phone" }),
2641
- /* @__PURE__ */ jsxRuntime.jsx(
2642
- OtpInputV2,
2643
- {
2644
- value: otp,
2645
- onChange: setOtp,
2646
- maxLength: OTP_LEN,
2647
- disabled: busy,
2648
- error: otpErrored
2649
- }
2650
- )
2651
- ] }),
2652
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "payman-v2-verification-actions", children: /* @__PURE__ */ jsxRuntime.jsx(
2653
- "button",
2654
- {
2655
- type: "button",
2656
- className: "payman-v2-verification-cancel-btn",
2657
- disabled: busy,
2658
- onClick: () => void handleCancel(),
2659
- children: "Cancel"
2660
- }
2661
- ) })
2662
- ]
4663
+ type: "button",
4664
+ className: "payman-v2-ua-btn payman-v2-ua-btn-primary",
4665
+ disabled: locked || !code.trim(),
4666
+ onClick: () => doSubmit(code.trim()),
4667
+ children: busy ? "Submitting\u2026" : "Submit"
2663
4668
  }
2664
4669
  ),
2665
4670
  /* @__PURE__ */ jsxRuntime.jsx(
2666
4671
  "button",
2667
4672
  {
2668
4673
  type: "button",
2669
- className: "payman-v2-verification-resend-link",
2670
- disabled: busy || resendSec > 0,
4674
+ className: "payman-v2-ua-link",
4675
+ disabled: locked || resendSec > 0,
2671
4676
  onClick: () => void handleResend(),
2672
4677
  children: resendSec > 0 ? `Resend (${resendSec}s)` : "Resend"
2673
4678
  }
4679
+ ),
4680
+ /* @__PURE__ */ jsxRuntime.jsx(
4681
+ "button",
4682
+ {
4683
+ type: "button",
4684
+ className: "payman-v2-ua-link payman-v2-ua-link-danger",
4685
+ disabled: busy,
4686
+ onClick: handleCancel,
4687
+ children: "Cancel"
4688
+ }
2674
4689
  )
2675
- ]
4690
+ ] })
4691
+ ] })
4692
+ ] });
4693
+ }
4694
+ function SchemaFormInline({
4695
+ prompt,
4696
+ secondsLeft,
4697
+ expired,
4698
+ onSubmit,
4699
+ onCancel
4700
+ }) {
4701
+ const schema = prompt.requestedSchema;
4702
+ const fields = react.useMemo(() => renderableFields(schema), [schema]);
4703
+ const [values, setValues] = react.useState(() => {
4704
+ const init2 = {};
4705
+ for (const [key, field] of fields) init2[key] = defaultValueFor(field);
4706
+ return init2;
4707
+ });
4708
+ const [errors, setErrors] = react.useState({});
4709
+ const status = prompt.status;
4710
+ const busy = status === "submitting";
4711
+ const stale = status === "stale";
4712
+ const locked = busy || stale || expired;
4713
+ const setValue = (key, value) => {
4714
+ setValues((prev) => ({ ...prev, [key]: value }));
4715
+ setErrors((prev) => {
4716
+ if (!prev[key]) return prev;
4717
+ const next = { ...prev };
4718
+ delete next[key];
4719
+ return next;
4720
+ });
4721
+ };
4722
+ const handleSubmit = () => {
4723
+ if (locked) return;
4724
+ const validation = validateForm(schema, values);
4725
+ if (Object.keys(validation).length > 0) {
4726
+ setErrors(validation);
4727
+ return;
4728
+ }
4729
+ void onSubmit(prompt.userActionId, buildContent(schema, values)).catch(() => {
4730
+ });
4731
+ };
4732
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "payman-v2-ua", role: "group", "aria-label": "Action required", children: [
4733
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "payman-v2-ua-head", children: [
4734
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Pencil, { className: "payman-v2-ua-icon", size: 14, strokeWidth: 1.75, "aria-hidden": true }),
4735
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "payman-v2-ua-title", children: "Action required" }),
4736
+ typeof secondsLeft === "number" && !stale && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "payman-v2-ua-timer", children: expired ? "Expired" : `${secondsLeft}s` })
4737
+ ] }),
4738
+ prompt.message?.trim() && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "payman-v2-ua-desc", children: prompt.message }),
4739
+ stale ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "payman-v2-ua-stale", children: "This request is no longer available." }) : fields.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "payman-v2-ua-desc", children: "This action has no inputs to fill." }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "payman-v2-ua-form", children: fields.map(([key, field]) => {
4740
+ const widget = classifyField(field);
4741
+ const label = field.title || key;
4742
+ const required = isRequired(schema, key);
4743
+ const err = errors[key];
4744
+ const fieldId = `ua-${prompt.userActionId}-${key}`;
4745
+ if (widget === "boolean") {
4746
+ return /* @__PURE__ */ jsxRuntime.jsxs("label", { className: "payman-v2-ua-check", children: [
4747
+ /* @__PURE__ */ jsxRuntime.jsx(
4748
+ "input",
4749
+ {
4750
+ type: "checkbox",
4751
+ checked: Boolean(values[key]),
4752
+ disabled: locked,
4753
+ onChange: (e) => setValue(key, e.target.checked)
4754
+ }
4755
+ ),
4756
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
4757
+ label,
4758
+ required && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "payman-v2-ua-req", children: "*" })
4759
+ ] })
4760
+ ] }, key);
4761
+ }
4762
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "payman-v2-ua-row", children: [
4763
+ /* @__PURE__ */ jsxRuntime.jsxs("label", { htmlFor: fieldId, className: "payman-v2-ua-label", children: [
4764
+ label,
4765
+ required && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "payman-v2-ua-req", children: "*" })
4766
+ ] }),
4767
+ field.description && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "payman-v2-ua-hint", children: field.description }),
4768
+ widget === "select" ? /* @__PURE__ */ jsxRuntime.jsxs(
4769
+ "select",
4770
+ {
4771
+ id: fieldId,
4772
+ className: cn("payman-v2-ua-input", err && "payman-v2-ua-input-error"),
4773
+ value: String(values[key] ?? ""),
4774
+ disabled: locked,
4775
+ onChange: (e) => setValue(key, e.target.value),
4776
+ children: [
4777
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "", disabled: true, children: "Select\u2026" }),
4778
+ getOptions(field).map((opt) => /* @__PURE__ */ jsxRuntime.jsx("option", { value: opt.const, children: opt.title || opt.const }, opt.const))
4779
+ ]
4780
+ }
4781
+ ) : /* @__PURE__ */ jsxRuntime.jsx(
4782
+ "input",
4783
+ {
4784
+ id: fieldId,
4785
+ type: widget === "integer" || widget === "decimal" ? "number" : "text",
4786
+ inputMode: widget === "integer" ? "numeric" : widget === "decimal" ? "decimal" : void 0,
4787
+ step: widget === "decimal" ? "any" : widget === "integer" ? "1" : void 0,
4788
+ className: cn("payman-v2-ua-input", err && "payman-v2-ua-input-error"),
4789
+ value: String(values[key] ?? ""),
4790
+ disabled: locked,
4791
+ placeholder: field.description ? void 0 : label,
4792
+ onChange: (e) => setValue(key, e.target.value),
4793
+ onKeyDown: (e) => {
4794
+ if (e.key === "Enter") {
4795
+ e.preventDefault();
4796
+ handleSubmit();
4797
+ }
4798
+ }
4799
+ }
4800
+ ),
4801
+ err && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "payman-v2-ua-error", children: err })
4802
+ ] }, key);
4803
+ }) }),
4804
+ !stale && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "payman-v2-ua-actions", children: [
4805
+ /* @__PURE__ */ jsxRuntime.jsx(
4806
+ "button",
4807
+ {
4808
+ type: "button",
4809
+ className: "payman-v2-ua-btn payman-v2-ua-btn-primary",
4810
+ disabled: locked,
4811
+ onClick: handleSubmit,
4812
+ children: busy ? "Submitting\u2026" : "Submit"
4813
+ }
4814
+ ),
4815
+ /* @__PURE__ */ jsxRuntime.jsx(
4816
+ "button",
4817
+ {
4818
+ type: "button",
4819
+ className: "payman-v2-ua-link payman-v2-ua-link-danger",
4820
+ disabled: busy,
4821
+ onClick: () => void onCancel(prompt.userActionId),
4822
+ children: "Cancel"
4823
+ }
4824
+ )
4825
+ ] })
4826
+ ] });
4827
+ }
4828
+ function NotificationInline({ notification, onDismiss }) {
4829
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "payman-v2-ua-note", role: "status", children: [
4830
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Info, { className: "payman-v2-ua-note-icon", size: 14, strokeWidth: 1.75, "aria-hidden": true }),
4831
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "payman-v2-ua-note-text", children: notification.message }),
4832
+ onDismiss && /* @__PURE__ */ jsxRuntime.jsx(
4833
+ "button",
4834
+ {
4835
+ type: "button",
4836
+ className: "payman-v2-ua-note-dismiss",
4837
+ "aria-label": "Dismiss notification",
4838
+ onClick: () => onDismiss(notification.id),
4839
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { size: 13, strokeWidth: 2 })
4840
+ }
4841
+ )
4842
+ ] });
4843
+ }
4844
+ function useExpiryCountdown(prompt) {
4845
+ const initial = typeof prompt.expirySeconds === "number" && prompt.expirySeconds > 0 ? Math.floor(prompt.expirySeconds) : void 0;
4846
+ const [secondsLeft, setSecondsLeft] = react.useState(initial);
4847
+ react.useEffect(() => {
4848
+ if (initial === void 0) {
4849
+ setSecondsLeft(void 0);
4850
+ return;
4851
+ }
4852
+ setSecondsLeft(initial);
4853
+ const id = window.setInterval(() => {
4854
+ setSecondsLeft((s) => {
4855
+ if (s === void 0) return s;
4856
+ if (s <= 1) {
4857
+ window.clearInterval(id);
4858
+ return 0;
4859
+ }
4860
+ return s - 1;
4861
+ });
4862
+ }, 1e3);
4863
+ return () => window.clearInterval(id);
4864
+ }, [prompt.userActionId, prompt.subAction, initial]);
4865
+ const expired = initial !== void 0 && secondsLeft === 0;
4866
+ return [secondsLeft, expired];
4867
+ }
4868
+ function UserActionInline({ prompt, onSubmit, onCancel, onResend }) {
4869
+ const [secondsLeft, expired] = useExpiryCountdown(prompt);
4870
+ let body;
4871
+ if (prompt.kind === "verification") {
4872
+ body = /* @__PURE__ */ jsxRuntime.jsx(
4873
+ VerificationInline,
4874
+ {
4875
+ prompt,
4876
+ secondsLeft,
4877
+ expired,
4878
+ onSubmit,
4879
+ onCancel,
4880
+ onResend
4881
+ }
4882
+ );
4883
+ } else if (prompt.kind === "notification") {
4884
+ const note = { id: prompt.userActionId, message: prompt.message ?? "" };
4885
+ body = /* @__PURE__ */ jsxRuntime.jsx(NotificationInline, { notification: note });
4886
+ } else {
4887
+ body = /* @__PURE__ */ jsxRuntime.jsx(
4888
+ SchemaFormInline,
4889
+ {
4890
+ prompt,
4891
+ secondsLeft,
4892
+ expired,
4893
+ onSubmit,
4894
+ onCancel
4895
+ }
4896
+ );
4897
+ }
4898
+ return /* @__PURE__ */ jsxRuntime.jsx(
4899
+ framerMotion.motion.div,
4900
+ {
4901
+ className: "payman-v2-ua-wrap",
4902
+ initial: { opacity: 0, y: 8 },
4903
+ animate: { opacity: 1, y: 0 },
4904
+ transition: { type: "spring", stiffness: 320, damping: 28 },
4905
+ children: body
2676
4906
  }
2677
4907
  );
2678
4908
  }
@@ -2688,13 +4918,17 @@ var MessageListV2 = react.forwardRef(
2688
4918
  onExecutionTraceClick,
2689
4919
  messageActions,
2690
4920
  retryDisabled = false,
2691
- userAction,
2692
- onApproveAction,
2693
- onRejectAction,
2694
- onResendAction,
4921
+ userActionPrompts,
4922
+ notifications,
4923
+ onSubmitUserAction,
4924
+ onCancelUserAction,
4925
+ onResendUserAction,
4926
+ onDismissNotification,
2695
4927
  onSubmitFeedback,
2696
4928
  typingSpeed = 4
2697
4929
  }, ref) {
4930
+ const noop = react.useCallback(async () => {
4931
+ }, []);
2698
4932
  const scrollRef = react.useRef(null);
2699
4933
  const scrollInnerRef = react.useRef(null);
2700
4934
  const isNearBottomRef = react.useRef(true);
@@ -2837,20 +5071,24 @@ var MessageListV2 = react.forwardRef(
2837
5071
  typingSpeed
2838
5072
  }
2839
5073
  ) }, message.id)),
2840
- userAction && userAction.status !== "approved" && userAction.status !== "rejected" && /* @__PURE__ */ jsxRuntime.jsx("div", { children: /* @__PURE__ */ jsxRuntime.jsx(
2841
- VerificationCardV2,
5074
+ notifications?.map((note) => /* @__PURE__ */ jsxRuntime.jsx(
5075
+ NotificationInline,
2842
5076
  {
2843
- messageId: userAction.messageId,
2844
- action: userAction.action,
2845
- status: userAction.status,
2846
- onApprove: onApproveAction ?? (async () => {
2847
- }),
2848
- onReject: onRejectAction ?? (async () => {
2849
- }),
2850
- onResend: onResendAction ?? (async () => {
2851
- })
2852
- }
2853
- ) })
5077
+ notification: note,
5078
+ onDismiss: onDismissNotification
5079
+ },
5080
+ note.id
5081
+ )),
5082
+ userActionPrompts?.map((prompt) => /* @__PURE__ */ jsxRuntime.jsx(
5083
+ UserActionInline,
5084
+ {
5085
+ prompt,
5086
+ onSubmit: onSubmitUserAction ?? noop,
5087
+ onCancel: onCancelUserAction ?? noop,
5088
+ onResend: onResendUserAction ?? noop
5089
+ },
5090
+ prompt.toolCallId || prompt.userActionId
5091
+ ))
2854
5092
  ]
2855
5093
  }
2856
5094
  )
@@ -3911,10 +6149,13 @@ function TimelineBars({
3911
6149
  ] });
3912
6150
  }
3913
6151
  var DEFAULT_USER_ACTION_STATE = {
3914
- request: null,
3915
- result: null};
6152
+ prompts: [],
6153
+ notifications: []
6154
+ };
3916
6155
  var NOOP_ASYNC = async () => {
3917
6156
  };
6157
+ var NOOP = () => {
6158
+ };
3918
6159
  function useSentryChatCallbacks(callbacks, config) {
3919
6160
  const sentryCtxRef = react.useRef({});
3920
6161
  const callbacksRef = react.useRef(callbacks);
@@ -3984,7 +6225,7 @@ function useSentryChatCallbacks(callbacks, config) {
3984
6225
  onAttachFileClick: () => callbacksRef.current?.onAttachFileClick?.(),
3985
6226
  onMessageFeedback: (data) => callbacksRef.current?.onMessageFeedback?.(data),
3986
6227
  onUserActionRequired: (req) => callbacksRef.current?.onUserActionRequired?.(req),
3987
- onUserActionEvent: (evType, msg) => callbacksRef.current?.onUserActionEvent?.(evType, msg),
6228
+ onUserNotification: (note) => callbacksRef.current?.onUserNotification?.(note),
3988
6229
  onStatusMessage: (msg) => callbacksRef.current?.onStatusMessage?.(msg),
3989
6230
  onStepsUpdate: (steps) => callbacksRef.current?.onStepsUpdate?.(steps)
3990
6231
  }),
@@ -4052,10 +6293,11 @@ var PaymanChatInner = react.forwardRef(function PaymanChatInner2({
4052
6293
  }
4053
6294
  }, [editingMessageId, messages]);
4054
6295
  const userActionState = chat.userActionState ?? DEFAULT_USER_ACTION_STATE;
4055
- const approveUserAction = chat.approveUserAction ?? NOOP_ASYNC;
4056
- const rejectUserAction = chat.rejectUserAction ?? NOOP_ASYNC;
4057
- const resendOtp = chat.resendOtp ?? NOOP_ASYNC;
4058
- const isUserActionSupported = typeof chat.approveUserAction === "function" && typeof chat.rejectUserAction === "function" && typeof chat.resendOtp === "function";
6296
+ const submitUserAction2 = chat.submitUserAction ?? NOOP_ASYNC;
6297
+ const cancelUserAction2 = chat.cancelUserAction ?? NOOP_ASYNC;
6298
+ const resendUserAction2 = chat.resendUserAction ?? NOOP_ASYNC;
6299
+ const dismissNotification = chat.dismissNotification ?? NOOP;
6300
+ const isUserActionSupported = typeof chat.submitUserAction === "function" && typeof chat.cancelUserAction === "function" && typeof chat.resendUserAction === "function";
4059
6301
  const {
4060
6302
  transcribedText,
4061
6303
  isAvailable: voiceAvailable,
@@ -4063,7 +6305,7 @@ var PaymanChatInner = react.forwardRef(function PaymanChatInner2({
4063
6305
  startRecording,
4064
6306
  stopRecording,
4065
6307
  clearTranscript
4066
- } = paymanTypescriptAskSdk.useVoice(
6308
+ } = useVoice(
4067
6309
  {
4068
6310
  lang: config.voiceLang || "en-US",
4069
6311
  interimResults: config.voiceInterimResults !== false,
@@ -4296,23 +6538,8 @@ var PaymanChatInner = react.forwardRef(function PaymanChatInner2({
4296
6538
  setLightboxSrc(src);
4297
6539
  setLightboxAlt(alt);
4298
6540
  };
4299
- const v2UserAction = react.useMemo(() => {
4300
- if (!isUserActionSupported || !userActionState.request) return null;
4301
- const req = userActionState.request;
4302
- let status = "pending";
4303
- if (userActionState.result === "approved") status = "approved";
4304
- else if (userActionState.result === "rejected") status = "rejected";
4305
- return {
4306
- messageId: `ua-${req.userActionId || Date.now()}`,
4307
- action: {
4308
- type: req.userActionType || "generic",
4309
- message: req.message || "Verify this action",
4310
- amount: req.metadata?.amount,
4311
- payeeName: req.metadata?.payeeName
4312
- },
4313
- status
4314
- };
4315
- }, [isUserActionSupported, userActionState.request, userActionState.result]);
6541
+ const userActionPrompts = isUserActionSupported ? userActionState.prompts : void 0;
6542
+ const notifications = userActionState.notifications;
4316
6543
  const handleV2Send = (text) => {
4317
6544
  if (isRecording) stopRecording();
4318
6545
  if (text.trim() && !disableInput && isSessionParamsConfigured) {
@@ -4464,16 +6691,12 @@ var PaymanChatInner = react.forwardRef(function PaymanChatInner2({
4464
6691
  messageActions,
4465
6692
  retryDisabled: isWaitingForResponse,
4466
6693
  typingSpeed: config.typingSpeed ?? 4,
4467
- userAction: v2UserAction,
4468
- onApproveAction: isUserActionSupported ? async (_msgId, otp) => {
4469
- await approveUserAction(otp);
4470
- } : void 0,
4471
- onRejectAction: isUserActionSupported ? async () => {
4472
- await rejectUserAction();
4473
- } : void 0,
4474
- onResendAction: isUserActionSupported ? async () => {
4475
- await resendOtp();
4476
- } : void 0,
6694
+ userActionPrompts,
6695
+ notifications,
6696
+ onSubmitUserAction: isUserActionSupported ? submitUserAction2 : void 0,
6697
+ onCancelUserAction: isUserActionSupported ? cancelUserAction2 : void 0,
6698
+ onResendUserAction: isUserActionSupported ? resendUserAction2 : void 0,
6699
+ onDismissNotification: dismissNotification,
4477
6700
  onSubmitFeedback: handleSubmitFeedback
4478
6701
  }
4479
6702
  ),
@@ -4551,56 +6774,39 @@ var PaymanChatInner = react.forwardRef(function PaymanChatInner2({
4551
6774
  var PaymanChat = react.forwardRef(
4552
6775
  function PaymanChat2(props, ref) {
4553
6776
  const mergedCallbacks = useSentryChatCallbacks(props.callbacks, props.config);
4554
- const chat = paymanTypescriptAskSdk.useChatV2(props.config, mergedCallbacks);
6777
+ const chat = useChatV2(props.config, mergedCallbacks);
4555
6778
  return /* @__PURE__ */ jsxRuntime.jsx(PaymanChatInner, { ...props, chat, ref });
4556
6779
  }
4557
6780
  );
4558
6781
 
4559
- Object.defineProperty(exports, "buildFormattedThinking", {
4560
- enumerable: true,
4561
- get: function () { return paymanTypescriptAskSdk.buildFormattedThinking; }
4562
- });
4563
- Object.defineProperty(exports, "cancelUserAction", {
4564
- enumerable: true,
4565
- get: function () { return paymanTypescriptAskSdk.cancelUserAction; }
4566
- });
4567
- Object.defineProperty(exports, "createInitialV2State", {
4568
- enumerable: true,
4569
- get: function () { return paymanTypescriptAskSdk.createInitialV2State; }
4570
- });
4571
- Object.defineProperty(exports, "generateId", {
4572
- enumerable: true,
4573
- get: function () { return paymanTypescriptAskSdk.generateId; }
4574
- });
4575
- Object.defineProperty(exports, "processStreamEventV2", {
4576
- enumerable: true,
4577
- get: function () { return paymanTypescriptAskSdk.processStreamEventV2; }
4578
- });
4579
- Object.defineProperty(exports, "resendUserAction", {
4580
- enumerable: true,
4581
- get: function () { return paymanTypescriptAskSdk.resendUserAction; }
4582
- });
4583
- Object.defineProperty(exports, "streamWorkflowEvents", {
4584
- enumerable: true,
4585
- get: function () { return paymanTypescriptAskSdk.streamWorkflowEvents; }
4586
- });
4587
- Object.defineProperty(exports, "submitUserAction", {
4588
- enumerable: true,
4589
- get: function () { return paymanTypescriptAskSdk.submitUserAction; }
4590
- });
4591
- Object.defineProperty(exports, "useChatV2", {
4592
- enumerable: true,
4593
- get: function () { return paymanTypescriptAskSdk.useChatV2; }
4594
- });
4595
- Object.defineProperty(exports, "useVoice", {
4596
- enumerable: true,
4597
- get: function () { return paymanTypescriptAskSdk.useVoice; }
4598
- });
4599
6782
  exports.PaymanChat = PaymanChat;
4600
6783
  exports.PaymanChatContext = PaymanChatContext;
6784
+ exports.UserActionStaleError = UserActionStaleError;
6785
+ exports.buildContent = buildContent;
6786
+ exports.buildFormattedThinking = buildFormattedThinking;
6787
+ exports.cancelUserAction = cancelUserAction;
4601
6788
  exports.captureSentryError = captureSentryError;
6789
+ exports.classifyField = classifyField;
6790
+ exports.classifyUserActionKind = classifyUserActionKind;
4602
6791
  exports.cn = cn;
6792
+ exports.coerceValue = coerceValue;
6793
+ exports.createInitialV2State = createInitialV2State;
6794
+ exports.defaultValueFor = defaultValueFor;
4603
6795
  exports.formatDate = formatDate;
6796
+ exports.generateId = generateId;
6797
+ exports.getOptions = getOptions;
6798
+ exports.isNestedOrUnsupported = isNestedOrUnsupported;
6799
+ exports.isRequired = isRequired;
6800
+ exports.migrateActiveStream = migrateActiveStream;
6801
+ exports.processStreamEventV2 = processStreamEventV2;
6802
+ exports.renderableFields = renderableFields;
6803
+ exports.resendUserAction = resendUserAction;
6804
+ exports.streamWorkflowEvents = streamWorkflowEvents;
6805
+ exports.submitUserAction = submitUserAction;
6806
+ exports.useChatV2 = useChatV2;
4604
6807
  exports.usePaymanChat = usePaymanChat;
6808
+ exports.useVoice = useVoice;
6809
+ exports.validateField = validateField;
6810
+ exports.validateForm = validateForm;
4605
6811
  //# sourceMappingURL=index.js.map
4606
6812
  //# sourceMappingURL=index.js.map