@paymanai/payman-ask-sdk 4.0.12 → 4.0.14

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.mjs CHANGED
@@ -21,9 +21,90 @@ function generateId() {
21
21
  return v.toString(16);
22
22
  });
23
23
  }
24
+ var memoryStore = /* @__PURE__ */ new Map();
25
+ var chatStore = {
26
+ get(key) {
27
+ return memoryStore.get(key) ?? [];
28
+ },
29
+ set(key, messages) {
30
+ memoryStore.set(key, messages);
31
+ },
32
+ delete(key) {
33
+ memoryStore.delete(key);
34
+ }
35
+ };
36
+ var streams = /* @__PURE__ */ new Map();
37
+ var activeStreamStore = {
38
+ has(key) {
39
+ return streams.has(key);
40
+ },
41
+ get(key) {
42
+ const entry = streams.get(key);
43
+ if (!entry) return null;
44
+ return { messages: entry.messages, isWaiting: entry.isWaiting };
45
+ },
46
+ // Called before startStream — registers the controller and initial messages
47
+ start(key, abortController, initialMessages) {
48
+ const existing = streams.get(key);
49
+ streams.set(key, {
50
+ messages: initialMessages,
51
+ isWaiting: true,
52
+ abortController,
53
+ listeners: existing?.listeners ?? /* @__PURE__ */ new Set()
54
+ });
55
+ },
56
+ // Called by the stream on every event — applies the same updater pattern React uses
57
+ applyMessages(key, updater) {
58
+ const entry = streams.get(key);
59
+ if (!entry) return;
60
+ const next = typeof updater === "function" ? updater(entry.messages) : updater;
61
+ entry.messages = next;
62
+ entry.listeners.forEach((l) => l(next, entry.isWaiting));
63
+ },
64
+ setWaiting(key, waiting) {
65
+ const entry = streams.get(key);
66
+ if (!entry) return;
67
+ entry.isWaiting = waiting;
68
+ entry.listeners.forEach((l) => l(entry.messages, waiting));
69
+ },
70
+ // Called when stream completes — persists to chatStore and cleans up
71
+ complete(key) {
72
+ const entry = streams.get(key);
73
+ if (!entry) return;
74
+ entry.isWaiting = false;
75
+ entry.listeners.forEach((l) => l(entry.messages, false));
76
+ const toSave = entry.messages.filter((m) => !m.isStreaming);
77
+ if (toSave.length > 0) chatStore.set(key, toSave);
78
+ streams.delete(key);
79
+ },
80
+ // Subscribe — returns unsubscribe fn. Component calls this on mount, cleanup on unmount.
81
+ subscribe(key, listener) {
82
+ const entry = streams.get(key);
83
+ if (!entry) return () => {
84
+ };
85
+ entry.listeners.add(listener);
86
+ return () => {
87
+ streams.get(key)?.listeners.delete(listener);
88
+ };
89
+ },
90
+ // Rename an entry — used when the server assigns a new session ID mid-stream
91
+ rename(oldKey, newKey) {
92
+ const entry = streams.get(oldKey);
93
+ if (!entry) return;
94
+ streams.set(newKey, entry);
95
+ streams.delete(oldKey);
96
+ },
97
+ // Explicit user cancel — aborts the controller and removes the entry
98
+ abort(key) {
99
+ const entry = streams.get(key);
100
+ if (!entry) return;
101
+ entry.abortController.abort();
102
+ streams.delete(key);
103
+ }
104
+ };
24
105
  function yieldAfterProgressEvent(event) {
25
106
  const t = event.eventType;
26
- if (t === "RUN_IN_PROGRESS" || t === "INTENT_PROGRESS" || t === "AGGREGATOR_THINKING_CONT" || t === "INTENT_THINKING_CONT" || t === "THINKING_DELTA") {
107
+ if (t === "RUN_IN_PROGRESS" || t === "INTENT_PROGRESS" || t === "THINKING_DELTA") {
27
108
  return new Promise((resolve) => setTimeout(resolve, 0));
28
109
  }
29
110
  return Promise.resolve();
@@ -279,40 +360,10 @@ function classifyUserActionKind(action, schema) {
279
360
  return isVerificationSchema(schema) ? "verification" : "form";
280
361
  }
281
362
  }
282
- function userActionHeader(kind) {
283
- return kind === "verification" ? "**Verification required**" : "**Action required**";
284
- }
285
- function workingPhaseDetailForDisplay(raw) {
286
- const t = raw.trim();
287
- if (!t) return "";
288
- if (/^Identified\s+\d+\s+tasks?\s+to\s+execute\.?$/i.test(t)) {
289
- return "";
290
- }
291
- return t;
292
- }
293
363
  function getEventText(event, field) {
294
364
  const value = event[field];
295
365
  return typeof value === "string" ? value.trim() : "";
296
366
  }
297
- function shouldShowIntentHeader(event) {
298
- const workerName = getEventText(event, "workerName");
299
- const intentId = getEventText(event, "intentId");
300
- return Boolean(workerName && intentId && workerName === intentId);
301
- }
302
- function addThinkingHeader(state, header) {
303
- state.formattedThinkingText += (state.formattedThinkingText ? "\n" : "") + header;
304
- }
305
- function addThinkingDetail(state, detail) {
306
- const trimmed = detail.trim();
307
- if (!trimmed) return;
308
- state.formattedThinkingText += (state.formattedThinkingText ? "\n" : "") + trimmed;
309
- }
310
- function addThinkingLine(state, header, detail) {
311
- state.formattedThinkingText += (state.formattedThinkingText ? "\n" : "") + header + "\n" + detail;
312
- }
313
- function appendThinkingText(state, text) {
314
- state.formattedThinkingText += text;
315
- }
316
367
  function updateExecutionStageMessage(state, msg) {
317
368
  if (!msg) return;
318
369
  for (let i = state.steps.length - 1; i >= 0; i--) {
@@ -333,9 +384,7 @@ function completeLastInProgressStep(steps) {
333
384
  }
334
385
  function createInitialV2State() {
335
386
  return {
336
- formattedThinkingText: "",
337
387
  finalResponse: "",
338
- currentWorker: "",
339
388
  lastEventType: "",
340
389
  sessionId: void 0,
341
390
  executionId: void 0,
@@ -382,10 +431,6 @@ function processStreamEventV2(rawEvent, state) {
382
431
  return state;
383
432
  }
384
433
  if (typeof eventType === "string" && eventType.toUpperCase() === "THINKING_DELTA") {
385
- const text = typeof event.text === "string" ? event.text : "";
386
- if (text) {
387
- appendThinkingText(state, text);
388
- }
389
434
  if (event.executionId) state.executionId = event.executionId;
390
435
  if (event.sessionId) state.sessionId = event.sessionId;
391
436
  state.lastEventType = "THINKING_DELTA";
@@ -396,7 +441,6 @@ function processStreamEventV2(rawEvent, state) {
396
441
  const message = getEventMessage(event);
397
442
  switch (eventType) {
398
443
  case "WORKFLOW_STARTED":
399
- case "STARTED":
400
444
  state.lastEventType = eventType;
401
445
  break;
402
446
  case "INTENT_PROGRESS": {
@@ -409,97 +453,7 @@ function processStreamEventV2(rawEvent, state) {
409
453
  state.lastEventType = eventType;
410
454
  break;
411
455
  }
412
- case "INTENT_THINKING": {
413
- const worker = getEventText(event, "workerName") || "Worker";
414
- const msg = getEventText(event, "message") || "Thinking...";
415
- const showHeader = shouldShowIntentHeader(event);
416
- if (worker !== state.currentWorker) {
417
- state.currentWorker = worker;
418
- if (showHeader && msg && msg !== worker) {
419
- addThinkingLine(state, `**${worker}**`, msg);
420
- } else if (showHeader) {
421
- addThinkingHeader(state, `**${worker}**`);
422
- } else if (msg !== "Thinking...") {
423
- addThinkingDetail(state, msg);
424
- }
425
- } else if (showHeader || msg !== "Thinking...") {
426
- appendThinkingText(state, "\n" + msg);
427
- }
428
- const lastInProgress = [...state.steps].reverse().find((s) => s.status === "in_progress");
429
- if (lastInProgress) {
430
- lastInProgress.thinkingText = "";
431
- lastInProgress.isThinking = true;
432
- }
433
- state.lastEventType = "INTENT_THINKING";
434
- break;
435
- }
436
- case "INTENT_THINKING_CONT": {
437
- const msg = event.message || "";
438
- if (!msg) break;
439
- if (state.lastEventType === "INTENT_THINKING") {
440
- appendThinkingText(state, "\n" + msg);
441
- } else {
442
- appendThinkingText(state, msg);
443
- }
444
- const thinkingStep = [...state.steps].reverse().find((s) => s.isThinking);
445
- if (thinkingStep) {
446
- thinkingStep.thinkingText = (thinkingStep.thinkingText || "") + msg;
447
- }
448
- state.lastEventType = "INTENT_THINKING_CONT";
449
- break;
450
- }
451
- case "ORCHESTRATOR_THINKING": {
452
- addThinkingLine(state, "**Planning**", event.message || "Understanding your request...");
453
- const stepId = `step-${state.stepCounter++}`;
454
- state.steps.push({
455
- id: stepId,
456
- eventType,
457
- message,
458
- status: "in_progress",
459
- timestamp: Date.now(),
460
- elapsedMs: event.elapsedMs
461
- });
462
- state.currentExecutingStepId = stepId;
463
- state.lastEventType = eventType;
464
- break;
465
- }
466
- case "ORCHESTRATOR_COMPLETED": {
467
- const workingDetail = workingPhaseDetailForDisplay(message);
468
- if (workingDetail) {
469
- addThinkingLine(state, "**Working**", workingDetail);
470
- } else {
471
- addThinkingHeader(state, "**Working**");
472
- }
473
- state.steps.push({
474
- id: `step-${state.stepCounter++}`,
475
- eventType: "WORKING",
476
- message: workingDetail,
477
- status: "completed",
478
- timestamp: Date.now()
479
- });
480
- const step = state.steps.find((s) => s.eventType === "ORCHESTRATOR_THINKING" && s.status === "in_progress");
481
- if (step) {
482
- step.status = "completed";
483
- if (event.elapsedMs) step.elapsedMs = event.elapsedMs;
484
- if (step.id === state.currentExecutingStepId) state.currentExecutingStepId = void 0;
485
- }
486
- state.lastEventType = eventType;
487
- break;
488
- }
489
456
  case "INTENT_STARTED": {
490
- const worker = getEventText(event, "workerName") || "Worker";
491
- const msg = getEventText(event, "message") || "Starting...";
492
- const showHeader = shouldShowIntentHeader(event);
493
- state.currentWorker = worker;
494
- if (showHeader && msg !== worker) {
495
- addThinkingLine(state, `**${worker}**`, msg);
496
- } else if (showHeader) {
497
- addThinkingHeader(state, `**${worker}**`);
498
- } else {
499
- addThinkingDetail(state, msg);
500
- }
501
- const thinkingStep = state.steps.find((s) => s.isThinking);
502
- if (thinkingStep) thinkingStep.isThinking = false;
503
457
  const stepId = `step-${state.stepCounter++}`;
504
458
  state.steps.push({
505
459
  id: stepId,
@@ -518,55 +472,18 @@ function processStreamEventV2(rawEvent, state) {
518
472
  const intentStep = state.steps.find((s) => s.eventType === "INTENT_STARTED" && s.status === "in_progress");
519
473
  if (intentStep) {
520
474
  intentStep.status = "completed";
521
- intentStep.isThinking = false;
522
475
  if (event.elapsedMs) intentStep.elapsedMs = event.elapsedMs;
523
476
  if (intentStep.id === state.currentExecutingStepId) state.currentExecutingStepId = void 0;
524
477
  }
525
478
  state.lastEventType = eventType;
526
479
  break;
527
480
  }
528
- case "AGGREGATOR_THINKING": {
529
- addThinkingLine(state, "**Finalizing**", event.message || "Preparing response...");
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
- state.lastEventType = eventType;
541
- break;
542
- }
543
- case "AGGREGATOR_COMPLETED": {
544
- appendThinkingText(state, "\n" + (event.message || "Response ready"));
545
- const step = state.steps.find((s) => s.eventType === "AGGREGATOR_THINKING" && s.status === "in_progress");
546
- if (step) {
547
- step.status = "completed";
548
- if (event.elapsedMs) step.elapsedMs = event.elapsedMs;
549
- if (step.id === state.currentExecutingStepId) state.currentExecutingStepId = void 0;
550
- }
551
- state.lastEventType = eventType;
552
- break;
553
- }
554
- case "WORKFLOW_COMPLETED":
555
- case "COMPLETED": {
481
+ case "WORKFLOW_COMPLETED": {
556
482
  const totalTime = Number(event.totalTimeMs);
557
483
  if (Number.isFinite(totalTime) && totalTime > 0) {
558
484
  state.totalElapsedMs = totalTime;
559
485
  }
560
- let content = extractResponseContent(event.response);
561
- const trace = event.trace && typeof event.trace === "object" ? event.trace : null;
562
- if (!content && trace?.workflowMsg && typeof trace.workflowMsg === "string") {
563
- content = trace.workflowMsg;
564
- }
565
- if (!content && trace?.aggregator && typeof trace.aggregator === "object") {
566
- const agg = trace.aggregator;
567
- if (typeof agg.response === "string") content = agg.response;
568
- else content = extractResponseContent(agg.response);
569
- }
486
+ const content = extractResponseContent(event.response);
570
487
  if (content) {
571
488
  state.finalResponse = content;
572
489
  if (event.trace && typeof event.trace === "object") {
@@ -581,7 +498,6 @@ function processStreamEventV2(rawEvent, state) {
581
498
  state.steps.forEach((step) => {
582
499
  if (step.status === "in_progress") {
583
500
  step.status = "completed";
584
- step.isThinking = false;
585
501
  }
586
502
  });
587
503
  state.lastEventType = eventType;
@@ -600,7 +516,6 @@ function processStreamEventV2(rawEvent, state) {
600
516
  };
601
517
  state.notifications.push(notification);
602
518
  state.lastNotification = notification;
603
- if (promptMessage) addThinkingDetail(state, promptMessage);
604
519
  state.lastEventType = eventType;
605
520
  break;
606
521
  }
@@ -626,9 +541,6 @@ function processStreamEventV2(rawEvent, state) {
626
541
  };
627
542
  upsertUserAction(state, request);
628
543
  state.lastUserAction = request;
629
- const header = userActionHeader(kind);
630
- if (promptMessage) addThinkingLine(state, header, promptMessage);
631
- else addThinkingHeader(state, header);
632
544
  const stepId = `step-${state.stepCounter++}`;
633
545
  state.steps.push({
634
546
  id: stepId,
@@ -652,27 +564,15 @@ function processStreamEventV2(rawEvent, state) {
652
564
  };
653
565
  state.notifications.push(notification);
654
566
  state.lastNotification = notification;
655
- if (noteMessage) addThinkingDetail(state, noteMessage);
656
567
  }
657
568
  state.lastEventType = eventType;
658
569
  break;
659
570
  }
660
571
  case "WORKFLOW_ERROR":
661
- case "ERROR":
662
572
  state.hasError = true;
663
573
  state.errorMessage = event.errorMessage || event.message || "Workflow error";
664
574
  state.lastEventType = eventType;
665
575
  break;
666
- case "INTENT_ERROR": {
667
- state.errorMessage = message || event.errorMessage || "An error occurred";
668
- const intentStep = state.steps.find((s) => s.eventType === "INTENT_STARTED" && s.status === "in_progress");
669
- if (intentStep) {
670
- intentStep.status = "error";
671
- intentStep.isThinking = false;
672
- }
673
- state.lastEventType = eventType;
674
- break;
675
- }
676
576
  // ---- K2 pipeline stage lifecycle events ----
677
577
  //
678
578
  // The k2-server playground streaming API emits
@@ -792,82 +692,6 @@ function processStreamEventV2(rawEvent, state) {
792
692
  }
793
693
  return state;
794
694
  }
795
- function buildFormattedThinking(steps, allThinkingText) {
796
- const parts = [];
797
- const safeSteps = steps ?? [];
798
- const cleanAll = allThinkingText.replace(/^\s+/, "");
799
- if (cleanAll) {
800
- const firstStepWithThinking = safeSteps.find(
801
- (s) => s.thinkingText && s.thinkingText.trim()
802
- );
803
- if (!firstStepWithThinking) {
804
- parts.push("**Preflight**");
805
- parts.push(cleanAll);
806
- } else {
807
- const stepText = firstStepWithThinking.thinkingText.trim();
808
- const idx = cleanAll.indexOf(stepText);
809
- if (idx > 0) {
810
- const orphaned = cleanAll.substring(0, idx).replace(/\s+$/, "");
811
- if (orphaned) {
812
- parts.push("**Preflight**");
813
- parts.push(orphaned);
814
- }
815
- }
816
- }
817
- }
818
- for (const step of safeSteps) {
819
- switch (step.eventType) {
820
- case "STAGE_STARTED": {
821
- if (step.message) parts.push(`**${step.message}**`);
822
- break;
823
- }
824
- case "ORCHESTRATOR_THINKING":
825
- parts.push("**Planning**");
826
- if (step.message) parts.push(step.message);
827
- break;
828
- case "INTENT_STARTED": {
829
- let label = step.message || "Processing";
830
- const started = label.match(/^(.+?)\s+started$/i);
831
- const progress = label.match(/^(.+?)\s+in progress$/i);
832
- if (started) label = started[1];
833
- else if (progress) label = progress[1];
834
- parts.push(`**${label}**`);
835
- if (step.thinkingText) parts.push(step.thinkingText);
836
- break;
837
- }
838
- case "INTENT_PROGRESS": {
839
- if (step.thinkingText) parts.push(step.thinkingText);
840
- else if (step.message) parts.push(step.message);
841
- break;
842
- }
843
- case "AGGREGATOR_THINKING":
844
- parts.push("**Finalizing**");
845
- if (step.message) parts.push(step.message);
846
- break;
847
- case "USER_ACTION_REQUIRED":
848
- parts.push("**Action required**");
849
- if (step.message) parts.push(step.message);
850
- break;
851
- }
852
- }
853
- return parts.length > 0 ? parts.join("\n") : allThinkingText;
854
- }
855
- function createCancelledMessageUpdate(steps, currentMessage) {
856
- const updatedSteps = steps.map((step) => {
857
- if (step.status === "in_progress") {
858
- return { ...step, status: "pending" };
859
- }
860
- return step;
861
- });
862
- return {
863
- isStreaming: false,
864
- isCancelled: true,
865
- steps: updatedSteps,
866
- currentExecutingStepId: void 0,
867
- // Preserve currentMessage so UI can show it with X icon
868
- currentMessage: currentMessage || "Thinking..."
869
- };
870
- }
871
695
  var DEFAULT_STREAM_ENDPOINT = "/api/playground/ask/stream";
872
696
  function buildRequestBody(config, userMessage, sessionId, options) {
873
697
  const sessionOwner = config.sessionParams;
@@ -939,123 +763,6 @@ function buildRequestHeaders(config) {
939
763
  }
940
764
  return headers;
941
765
  }
942
- var UserActionStaleError = class extends Error {
943
- constructor(userActionId, message = "User action is no longer actionable") {
944
- super(message);
945
- __publicField(this, "userActionId");
946
- this.name = "UserActionStaleError";
947
- this.userActionId = userActionId;
948
- }
949
- };
950
- async function sendUserActionRequest(config, userActionId, action, data) {
951
- const url = buildUserActionUrl(config, userActionId, action);
952
- const baseHeaders = buildRequestHeaders(config);
953
- const hasBody = data !== void 0;
954
- const headers = hasBody ? { "Content-Type": "application/json", ...baseHeaders } : baseHeaders;
955
- const response = await fetch(url, {
956
- method: "POST",
957
- headers,
958
- body: hasBody ? JSON.stringify(data) : void 0
959
- });
960
- if (response.status === 404) {
961
- throw new UserActionStaleError(userActionId);
962
- }
963
- if (!response.ok) {
964
- const errorText = await response.text();
965
- throw new Error(`HTTP ${response.status}: ${errorText}`);
966
- }
967
- return await response.json();
968
- }
969
- async function submitUserAction(config, userActionId, content) {
970
- return sendUserActionRequest(config, userActionId, "submit", content ?? {});
971
- }
972
- async function cancelUserAction(config, userActionId) {
973
- return sendUserActionRequest(config, userActionId, "cancel");
974
- }
975
- async function resendUserAction(config, userActionId) {
976
- return sendUserActionRequest(config, userActionId, "resend");
977
- }
978
- var memoryStore = /* @__PURE__ */ new Map();
979
- var chatStore = {
980
- get(key) {
981
- return memoryStore.get(key) ?? [];
982
- },
983
- set(key, messages) {
984
- memoryStore.set(key, messages);
985
- },
986
- delete(key) {
987
- memoryStore.delete(key);
988
- }
989
- };
990
- var streams = /* @__PURE__ */ new Map();
991
- var activeStreamStore = {
992
- has(key) {
993
- return streams.has(key);
994
- },
995
- get(key) {
996
- const entry = streams.get(key);
997
- if (!entry) return null;
998
- return { messages: entry.messages, isWaiting: entry.isWaiting };
999
- },
1000
- // Called before startStream — registers the controller and initial messages
1001
- start(key, abortController, initialMessages) {
1002
- const existing = streams.get(key);
1003
- streams.set(key, {
1004
- messages: initialMessages,
1005
- isWaiting: true,
1006
- abortController,
1007
- listeners: existing?.listeners ?? /* @__PURE__ */ new Set()
1008
- });
1009
- },
1010
- // Called by the stream on every event — applies the same updater pattern React uses
1011
- applyMessages(key, updater) {
1012
- const entry = streams.get(key);
1013
- if (!entry) return;
1014
- const next = typeof updater === "function" ? updater(entry.messages) : updater;
1015
- entry.messages = next;
1016
- entry.listeners.forEach((l) => l(next, entry.isWaiting));
1017
- },
1018
- setWaiting(key, waiting) {
1019
- const entry = streams.get(key);
1020
- if (!entry) return;
1021
- entry.isWaiting = waiting;
1022
- entry.listeners.forEach((l) => l(entry.messages, waiting));
1023
- },
1024
- // Called when stream completes — persists to chatStore and cleans up
1025
- complete(key) {
1026
- const entry = streams.get(key);
1027
- if (!entry) return;
1028
- entry.isWaiting = false;
1029
- entry.listeners.forEach((l) => l(entry.messages, false));
1030
- const toSave = entry.messages.filter((m) => !m.isStreaming);
1031
- if (toSave.length > 0) chatStore.set(key, toSave);
1032
- streams.delete(key);
1033
- },
1034
- // Subscribe — returns unsubscribe fn. Component calls this on mount, cleanup on unmount.
1035
- subscribe(key, listener) {
1036
- const entry = streams.get(key);
1037
- if (!entry) return () => {
1038
- };
1039
- entry.listeners.add(listener);
1040
- return () => {
1041
- streams.get(key)?.listeners.delete(listener);
1042
- };
1043
- },
1044
- // Rename an entry — used when the server assigns a new session ID mid-stream
1045
- rename(oldKey, newKey) {
1046
- const entry = streams.get(oldKey);
1047
- if (!entry) return;
1048
- streams.set(newKey, entry);
1049
- streams.delete(oldKey);
1050
- },
1051
- // Explicit user cancel — aborts the controller and removes the entry
1052
- abort(key) {
1053
- const entry = streams.get(key);
1054
- if (!entry) return;
1055
- entry.abortController.abort();
1056
- streams.delete(key);
1057
- }
1058
- };
1059
766
  var RAG_IMAGE_REGEX = /\/api\/rag\/chunks\/[^"'\s]+\/image/;
1060
767
  function hasRagImages(content) {
1061
768
  return RAG_IMAGE_REGEX.test(content);
@@ -1167,7 +874,6 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1167
874
  streamProgress: "error",
1168
875
  isError: true,
1169
876
  errorDetails: state.errorMessage,
1170
- formattedThinkingText: state.formattedThinkingText || void 0,
1171
877
  steps: [...state.steps],
1172
878
  currentExecutingStepId: void 0,
1173
879
  executionId: state.executionId,
@@ -1180,7 +886,6 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1180
886
  currentMessage,
1181
887
  streamProgress: "processing",
1182
888
  isError: false,
1183
- formattedThinkingText: state.formattedThinkingText || void 0,
1184
889
  steps: [...state.steps],
1185
890
  currentExecutingStepId: state.currentExecutingStepId,
1186
891
  executionId: state.executionId,
@@ -1207,7 +912,6 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1207
912
  errorDetails: isAborted ? void 0 : error.message,
1208
913
  content: isAborted ? state.finalResponse || "" : state.finalResponse || FRIENDLY_ERROR_MESSAGE,
1209
914
  currentMessage: isAborted ? "Thinking..." : void 0,
1210
- formattedThinkingText: state.formattedThinkingText || void 0,
1211
915
  steps: [...state.steps].map((step) => {
1212
916
  if (step.status === "in_progress" && isAborted) {
1213
917
  return { ...step, status: "pending" };
@@ -1246,7 +950,6 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1246
950
  steps: state.hasError ? [] : [...state.steps],
1247
951
  isCancelled: false,
1248
952
  currentExecutingStepId: void 0,
1249
- formattedThinkingText: state.hasError ? void 0 : state.formattedThinkingText || void 0,
1250
953
  isResolvingImages: needsImageResolve,
1251
954
  totalElapsedMs: state.hasError ? void 0 : state.totalElapsedMs
1252
955
  };
@@ -1299,7 +1002,6 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1299
1002
  isCancelled: isAborted,
1300
1003
  errorDetails: isAborted ? void 0 : error.message,
1301
1004
  content: isAborted ? state.finalResponse || "" : state.finalResponse || FRIENDLY_ERROR_MESSAGE,
1302
- formattedThinkingText: state.formattedThinkingText || void 0,
1303
1005
  steps: [...state.steps].map((step) => {
1304
1006
  if (step.status === "in_progress" && isAborted) {
1305
1007
  return { ...step, status: "pending" };
@@ -1324,6 +1026,57 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1324
1026
  abortControllerRef
1325
1027
  };
1326
1028
  }
1029
+ function createCancelledMessageUpdate(steps, currentMessage) {
1030
+ const updatedSteps = steps.map((step) => {
1031
+ if (step.status === "in_progress") {
1032
+ return { ...step, status: "pending" };
1033
+ }
1034
+ return step;
1035
+ });
1036
+ return {
1037
+ isStreaming: false,
1038
+ isCancelled: true,
1039
+ steps: updatedSteps,
1040
+ currentExecutingStepId: void 0,
1041
+ currentMessage: currentMessage || "Thinking..."
1042
+ };
1043
+ }
1044
+ var UserActionStaleError = class extends Error {
1045
+ constructor(userActionId, message = "User action is no longer actionable") {
1046
+ super(message);
1047
+ __publicField(this, "userActionId");
1048
+ this.name = "UserActionStaleError";
1049
+ this.userActionId = userActionId;
1050
+ }
1051
+ };
1052
+ async function sendUserActionRequest(config, userActionId, action, data) {
1053
+ const url = buildUserActionUrl(config, userActionId, action);
1054
+ const baseHeaders = buildRequestHeaders(config);
1055
+ const hasBody = data !== void 0;
1056
+ const headers = hasBody ? { "Content-Type": "application/json", ...baseHeaders } : baseHeaders;
1057
+ const response = await fetch(url, {
1058
+ method: "POST",
1059
+ headers,
1060
+ body: hasBody ? JSON.stringify(data) : void 0
1061
+ });
1062
+ if (response.status === 404) {
1063
+ throw new UserActionStaleError(userActionId);
1064
+ }
1065
+ if (!response.ok) {
1066
+ const errorText = await response.text();
1067
+ throw new Error(`HTTP ${response.status}: ${errorText}`);
1068
+ }
1069
+ return await response.json();
1070
+ }
1071
+ async function submitUserAction(config, userActionId, content) {
1072
+ return sendUserActionRequest(config, userActionId, "submit", content ?? {});
1073
+ }
1074
+ async function cancelUserAction(config, userActionId) {
1075
+ return sendUserActionRequest(config, userActionId, "cancel");
1076
+ }
1077
+ async function resendUserAction(config, userActionId) {
1078
+ return sendUserActionRequest(config, userActionId, "resend");
1079
+ }
1327
1080
  var EMPTY_USER_ACTION_STATE = { prompts: [], notifications: [] };
1328
1081
  function upsertPrompt(prompts, req) {
1329
1082
  const active = { ...req, status: "pending" };
@@ -2028,9 +1781,6 @@ function buildContent(schema, values) {
2028
1781
  }
2029
1782
  return content;
2030
1783
  }
2031
- function migrateActiveStream(oldUserId, newUserId) {
2032
- activeStreamStore.rename(oldUserId, newUserId);
2033
- }
2034
1784
  var PaymanChatContext = createContext(void 0);
2035
1785
  function usePaymanChat() {
2036
1786
  const context = useContext(PaymanChatContext);
@@ -2536,46 +2286,6 @@ function createMarkdownComponents(options = {}) {
2536
2286
  td: ({ children }) => /* @__PURE__ */ jsx("td", { className: "p-3 align-middle text-sm whitespace-nowrap", children })
2537
2287
  };
2538
2288
  }
2539
- function ThinkingBlock({ text }) {
2540
- const [isOpen, setIsOpen] = useState(false);
2541
- const hasContent = typeof text === "string" && text.trim().length > 0;
2542
- if (!hasContent) return null;
2543
- return /* @__PURE__ */ jsxs("div", { className: "mt-1.5 mb-1.5", children: [
2544
- /* @__PURE__ */ jsxs(
2545
- "button",
2546
- {
2547
- type: "button",
2548
- onClick: () => setIsOpen((prev) => !prev),
2549
- className: "inline-flex items-center gap-1 text-[10px] payman-agent-thinking-toggle transition-colors",
2550
- "aria-expanded": isOpen,
2551
- "aria-label": isOpen ? "Collapse thought process" : "Expand thought process",
2552
- children: [
2553
- /* @__PURE__ */ jsx(
2554
- motion.div,
2555
- {
2556
- animate: { rotate: isOpen ? 180 : 0 },
2557
- transition: { duration: 0.15 },
2558
- className: "shrink-0",
2559
- children: /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3" })
2560
- }
2561
- ),
2562
- /* @__PURE__ */ jsx("span", { children: "Thought process" })
2563
- ]
2564
- }
2565
- ),
2566
- /* @__PURE__ */ jsx(AnimatePresence, { initial: false, children: isOpen && /* @__PURE__ */ jsx(
2567
- motion.div,
2568
- {
2569
- initial: { height: 0, opacity: 0 },
2570
- animate: { height: "auto", opacity: 1 },
2571
- exit: { height: 0, opacity: 0 },
2572
- transition: { duration: 0.2, ease: "easeInOut" },
2573
- className: "overflow-hidden",
2574
- children: /* @__PURE__ */ jsx("div", { className: "mt-1 payman-agent-thinking-block rounded-md p-2 overflow-y-auto overflow-x-hidden", children: /* @__PURE__ */ jsx("p", { className: "m-0 text-xs payman-agent-thinking-block-text whitespace-pre-wrap leading-relaxed", children: text }) })
2575
- }
2576
- ) })
2577
- ] });
2578
- }
2579
2289
  var FRIENDLY_ERROR_MESSAGE2 = "Oops, something went wrong. Please try again.";
2580
2290
  function looksLikeRawError(text) {
2581
2291
  if (!text || text.length < 10) return false;
@@ -2618,8 +2328,6 @@ function AgentMessage({
2618
2328
  const completedWithNoContent = !isStreaming && !isCancelled && content.length === 0 && (message.streamProgress === "completed" || message.streamProgress === "error");
2619
2329
  const conflictErrorMessage = getConflictErrorMessage(message.errorDetails);
2620
2330
  const isError = !!conflictErrorMessage || (isFriendlyWorkflowError(message.errorDetails) || looksLikeRawError(content)) && !hasMeaningfulContent || completedWithNoContent;
2621
- const activeThinkingText = message.activeThinkingText;
2622
- const allThinkingText = message.allThinkingText;
2623
2331
  const currentStep = useMemo(
2624
2332
  () => message.steps?.find(
2625
2333
  (s) => s.id === currentExecutingStepId && s.status === "in_progress"
@@ -2662,7 +2370,7 @@ function AgentMessage({
2662
2370
  return /* @__PURE__ */ jsx("div", { className: wrapper, children: /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5 payman-agent-step-icon--error" }) });
2663
2371
  return /* @__PURE__ */ jsx("div", { className: wrapper, children: /* @__PURE__ */ jsx("div", { className: "h-1.5 w-1.5 rounded-full payman-agent-step-icon--pending-dim" }) });
2664
2372
  };
2665
- const stepsListContent = hasSteps && /* @__PURE__ */ jsx(AnimatePresence, { initial: false, children: isStepsExpanded && /* @__PURE__ */ jsxs(
2373
+ const stepsListContent = hasSteps && /* @__PURE__ */ jsx(AnimatePresence, { initial: false, children: isStepsExpanded && /* @__PURE__ */ jsx(
2666
2374
  motion.div,
2667
2375
  {
2668
2376
  initial: { height: 0, opacity: 0 },
@@ -2670,37 +2378,34 @@ function AgentMessage({
2670
2378
  exit: { height: 0, opacity: 0 },
2671
2379
  transition: { duration: 0.2, ease: "easeInOut" },
2672
2380
  className: "overflow-hidden",
2673
- children: [
2674
- !isStreaming && allThinkingText?.trim() && /* @__PURE__ */ jsx(ThinkingBlock, { text: allThinkingText }),
2675
- /* @__PURE__ */ jsx("div", { className: "pt-1.5", children: message.steps.map((step) => {
2676
- const isCurrentlyExecuting = step.id === currentExecutingStepId && step.status === "in_progress" && isStreaming && !isCancelled;
2677
- const hasTime = step.elapsedMs != null && step.elapsedMs > 0;
2678
- return /* @__PURE__ */ jsxs("div", { className: "mb-1.5", children: [
2679
- /* @__PURE__ */ jsxs("div", { className: "flex gap-1.5 items-start", children: [
2680
- /* @__PURE__ */ jsx("div", { className: "mt-px", children: renderStepIcon(step, isCurrentlyExecuting) }),
2681
- /* @__PURE__ */ jsx(
2682
- "span",
2683
- {
2684
- className: cn(
2685
- "text-xs leading-relaxed min-w-0 break-words",
2686
- isCurrentlyExecuting && "shimmer-text font-medium",
2687
- !isCurrentlyExecuting && step.status === "error" && "payman-agent-step-text--error",
2688
- !isCurrentlyExecuting && step.eventType === "USER_ACTION_SUCCESS" && "payman-agent-step-text--success",
2689
- !isCurrentlyExecuting && step.status === "completed" && "payman-agent-step-text--completed",
2690
- !isCurrentlyExecuting && step.status === "pending" && "payman-agent-step-text--pending",
2691
- !isCurrentlyExecuting && step.status === "in_progress" && "payman-agent-step-text--in-progress"
2692
- ),
2693
- children: step.message
2694
- }
2695
- )
2696
- ] }),
2697
- hasTime && /* @__PURE__ */ jsx("div", { className: "pl-[22px] mt-1", children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md payman-agent-step-time leading-none", children: [
2698
- /* @__PURE__ */ jsx(Clock, { className: "h-2.5 w-2.5 shrink-0 payman-agent-step-time-icon" }),
2699
- /* @__PURE__ */ jsx("span", { className: "text-[10px] font-mono payman-agent-step-time-text", children: formatElapsedTime(step.elapsedMs) })
2700
- ] }) })
2701
- ] }, step.id);
2702
- }) })
2703
- ]
2381
+ children: /* @__PURE__ */ jsx("div", { className: "pt-1.5", children: message.steps.map((step) => {
2382
+ const isCurrentlyExecuting = step.id === currentExecutingStepId && step.status === "in_progress" && isStreaming && !isCancelled;
2383
+ const hasTime = step.elapsedMs != null && step.elapsedMs > 0;
2384
+ return /* @__PURE__ */ jsxs("div", { className: "mb-1.5", children: [
2385
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-1.5 items-start", children: [
2386
+ /* @__PURE__ */ jsx("div", { className: "mt-px", children: renderStepIcon(step, isCurrentlyExecuting) }),
2387
+ /* @__PURE__ */ jsx(
2388
+ "span",
2389
+ {
2390
+ className: cn(
2391
+ "text-xs leading-relaxed min-w-0 break-words",
2392
+ isCurrentlyExecuting && "shimmer-text font-medium",
2393
+ !isCurrentlyExecuting && step.status === "error" && "payman-agent-step-text--error",
2394
+ !isCurrentlyExecuting && step.eventType === "USER_ACTION_SUCCESS" && "payman-agent-step-text--success",
2395
+ !isCurrentlyExecuting && step.status === "completed" && "payman-agent-step-text--completed",
2396
+ !isCurrentlyExecuting && step.status === "pending" && "payman-agent-step-text--pending",
2397
+ !isCurrentlyExecuting && step.status === "in_progress" && "payman-agent-step-text--in-progress"
2398
+ ),
2399
+ children: step.message
2400
+ }
2401
+ )
2402
+ ] }),
2403
+ hasTime && /* @__PURE__ */ jsx("div", { className: "pl-[22px] mt-1", children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md payman-agent-step-time leading-none", children: [
2404
+ /* @__PURE__ */ jsx(Clock, { className: "h-2.5 w-2.5 shrink-0 payman-agent-step-time-icon" }),
2405
+ /* @__PURE__ */ jsx("span", { className: "text-[10px] font-mono payman-agent-step-time-text", children: formatElapsedTime(step.elapsedMs) })
2406
+ ] }) })
2407
+ ] }, step.id);
2408
+ }) })
2704
2409
  }
2705
2410
  ) });
2706
2411
  const stepsToggleRef = useRef(null);
@@ -2781,22 +2486,13 @@ function AgentMessage({
2781
2486
  "text-sm leading-relaxed min-w-0 w-full break-words overflow-wrap-anywhere",
2782
2487
  showAgentName && "mt-1"
2783
2488
  ),
2784
- children: isStreaming && !content ? (
2785
- // Streaming without content show thinking/step indicator
2786
- activeThinkingText ? /* @__PURE__ */ jsxs("div", { className: "flex gap-2 items-start", children: [
2787
- /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 mt-0.5 payman-agent-thinking-spinner animate-spin shrink-0" }),
2788
- /* @__PURE__ */ jsxs("span", { className: "text-sm leading-relaxed min-w-0 break-words payman-agent-thinking-text whitespace-pre-wrap flex-1", children: [
2789
- activeThinkingText,
2790
- /* @__PURE__ */ jsx("span", { className: "inline-block w-0.5 h-3.5 payman-agent-thinking-cursor animate-pulse ml-0.5 align-text-bottom" })
2791
- ] })
2792
- ] }) : currentStep ? /* @__PURE__ */ jsxs("div", { className: "flex gap-1.5 items-start", children: [
2793
- /* @__PURE__ */ jsx("div", { className: "mt-0.5 shrink-0", children: renderStepIcon(currentStep, true) }),
2794
- /* @__PURE__ */ jsx("span", { className: "text-sm leading-relaxed min-w-0 break-words shimmer-text font-medium flex-1", children: currentStep.message })
2795
- ] }) : /* @__PURE__ */ jsxs("div", { className: "flex gap-2.5 items-start", children: [
2796
- /* @__PURE__ */ jsx(Loader2, { className: "w-4 h-4 mt-0.5 payman-agent-thinking-spinner animate-spin shrink-0" }),
2797
- /* @__PURE__ */ jsx("span", { className: "text-sm payman-agent-thinking-text flex-1", children: currentMessage || "Thinking..." })
2798
- ] })
2799
- ) : isCancelled && !content ? /* @__PURE__ */ jsxs("div", { className: "flex gap-2.5 items-start", children: [
2489
+ children: isStreaming && !content ? currentStep ? /* @__PURE__ */ jsxs("div", { className: "flex gap-1.5 items-start", children: [
2490
+ /* @__PURE__ */ jsx("div", { className: "mt-0.5 shrink-0", children: renderStepIcon(currentStep, true) }),
2491
+ /* @__PURE__ */ jsx("span", { className: "text-sm leading-relaxed min-w-0 break-words shimmer-text font-medium flex-1", children: currentStep.message })
2492
+ ] }) : /* @__PURE__ */ jsxs("div", { className: "flex gap-2.5 items-start", children: [
2493
+ /* @__PURE__ */ jsx(Loader2, { className: "w-4 h-4 mt-0.5 payman-agent-thinking-spinner animate-spin shrink-0" }),
2494
+ /* @__PURE__ */ jsx("span", { className: "text-sm payman-agent-thinking-text flex-1", children: currentMessage || "Thinking..." })
2495
+ ] }) : isCancelled && !content ? /* @__PURE__ */ jsxs("div", { className: "flex gap-2.5 items-start", children: [
2800
2496
  /* @__PURE__ */ jsx(X, { className: "w-4 h-4 mt-0.5 payman-agent-cancelled-icon shrink-0" }),
2801
2497
  /* @__PURE__ */ jsx("span", { className: "text-sm payman-agent-cancelled-text italic flex-1", children: currentMessage || "Request was stopped." })
2802
2498
  ] }) : /* @__PURE__ */ jsx(
@@ -6565,7 +6261,7 @@ var PaymanChatInner = forwardRef(function PaymanChatInner2({
6565
6261
  style,
6566
6262
  children: [
6567
6263
  children,
6568
- isChatDisabled ? disabledComponent || /* @__PURE__ */ jsx("div", { style: { flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "1rem" }, children: /* @__PURE__ */ jsx("div", { style: { textAlign: "center", color: "var(--payman-v2-text-3)", fontSize: "0.875rem" }, children: "Chat is currently disabled" }) }) : /* @__PURE__ */ jsx(AnimatePresence, { mode: "wait", children: isEmpty && !hasEverSentMessage ? /* @__PURE__ */ jsx(
6264
+ /* @__PURE__ */ jsx(AnimatePresence, { mode: "wait", children: isEmpty && !hasEverSentMessage ? /* @__PURE__ */ jsx(
6569
6265
  motion.div,
6570
6266
  {
6571
6267
  initial: { opacity: 1 },
@@ -6752,6 +6448,6 @@ var PaymanChat = forwardRef(
6752
6448
  }
6753
6449
  );
6754
6450
 
6755
- export { PaymanChat, PaymanChatContext, UserActionStaleError, buildContent, buildFormattedThinking, cancelUserAction, captureSentryError, classifyField, classifyUserActionKind, cn, coerceValue, createInitialV2State, defaultValueFor, formatDate, generateId, getOptions, isNestedOrUnsupported, isRequired, migrateActiveStream, processStreamEventV2, renderableFields, resendUserAction, streamWorkflowEvents, submitUserAction, useChatV2, usePaymanChat, useVoice, validateField, validateForm };
6451
+ export { PaymanChat, PaymanChatContext, UserActionStaleError, cancelUserAction, captureSentryError, cn, formatDate, resendUserAction, submitUserAction, useChatV2, usePaymanChat, useVoice };
6756
6452
  //# sourceMappingURL=index.mjs.map
6757
6453
  //# sourceMappingURL=index.mjs.map