@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.js CHANGED
@@ -48,9 +48,90 @@ function generateId() {
48
48
  return v.toString(16);
49
49
  });
50
50
  }
51
+ var memoryStore = /* @__PURE__ */ new Map();
52
+ var chatStore = {
53
+ get(key) {
54
+ return memoryStore.get(key) ?? [];
55
+ },
56
+ set(key, messages) {
57
+ memoryStore.set(key, messages);
58
+ },
59
+ delete(key) {
60
+ memoryStore.delete(key);
61
+ }
62
+ };
63
+ var streams = /* @__PURE__ */ new Map();
64
+ var activeStreamStore = {
65
+ has(key) {
66
+ return streams.has(key);
67
+ },
68
+ get(key) {
69
+ const entry = streams.get(key);
70
+ if (!entry) return null;
71
+ return { messages: entry.messages, isWaiting: entry.isWaiting };
72
+ },
73
+ // Called before startStream — registers the controller and initial messages
74
+ start(key, abortController, initialMessages) {
75
+ const existing = streams.get(key);
76
+ streams.set(key, {
77
+ messages: initialMessages,
78
+ isWaiting: true,
79
+ abortController,
80
+ listeners: existing?.listeners ?? /* @__PURE__ */ new Set()
81
+ });
82
+ },
83
+ // Called by the stream on every event — applies the same updater pattern React uses
84
+ applyMessages(key, updater) {
85
+ const entry = streams.get(key);
86
+ if (!entry) return;
87
+ const next = typeof updater === "function" ? updater(entry.messages) : updater;
88
+ entry.messages = next;
89
+ entry.listeners.forEach((l) => l(next, entry.isWaiting));
90
+ },
91
+ setWaiting(key, waiting) {
92
+ const entry = streams.get(key);
93
+ if (!entry) return;
94
+ entry.isWaiting = waiting;
95
+ entry.listeners.forEach((l) => l(entry.messages, waiting));
96
+ },
97
+ // Called when stream completes — persists to chatStore and cleans up
98
+ complete(key) {
99
+ const entry = streams.get(key);
100
+ if (!entry) return;
101
+ entry.isWaiting = false;
102
+ entry.listeners.forEach((l) => l(entry.messages, false));
103
+ const toSave = entry.messages.filter((m) => !m.isStreaming);
104
+ if (toSave.length > 0) chatStore.set(key, toSave);
105
+ streams.delete(key);
106
+ },
107
+ // Subscribe — returns unsubscribe fn. Component calls this on mount, cleanup on unmount.
108
+ subscribe(key, listener) {
109
+ const entry = streams.get(key);
110
+ if (!entry) return () => {
111
+ };
112
+ entry.listeners.add(listener);
113
+ return () => {
114
+ streams.get(key)?.listeners.delete(listener);
115
+ };
116
+ },
117
+ // Rename an entry — used when the server assigns a new session ID mid-stream
118
+ rename(oldKey, newKey) {
119
+ const entry = streams.get(oldKey);
120
+ if (!entry) return;
121
+ streams.set(newKey, entry);
122
+ streams.delete(oldKey);
123
+ },
124
+ // Explicit user cancel — aborts the controller and removes the entry
125
+ abort(key) {
126
+ const entry = streams.get(key);
127
+ if (!entry) return;
128
+ entry.abortController.abort();
129
+ streams.delete(key);
130
+ }
131
+ };
51
132
  function yieldAfterProgressEvent(event) {
52
133
  const t = event.eventType;
53
- if (t === "RUN_IN_PROGRESS" || t === "INTENT_PROGRESS" || t === "AGGREGATOR_THINKING_CONT" || t === "INTENT_THINKING_CONT" || t === "THINKING_DELTA") {
134
+ if (t === "RUN_IN_PROGRESS" || t === "INTENT_PROGRESS" || t === "THINKING_DELTA") {
54
135
  return new Promise((resolve) => setTimeout(resolve, 0));
55
136
  }
56
137
  return Promise.resolve();
@@ -306,40 +387,10 @@ function classifyUserActionKind(action, schema) {
306
387
  return isVerificationSchema(schema) ? "verification" : "form";
307
388
  }
308
389
  }
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
390
  function getEventText(event, field) {
321
391
  const value = event[field];
322
392
  return typeof value === "string" ? value.trim() : "";
323
393
  }
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
394
  function updateExecutionStageMessage(state, msg) {
344
395
  if (!msg) return;
345
396
  for (let i = state.steps.length - 1; i >= 0; i--) {
@@ -360,9 +411,7 @@ function completeLastInProgressStep(steps) {
360
411
  }
361
412
  function createInitialV2State() {
362
413
  return {
363
- formattedThinkingText: "",
364
414
  finalResponse: "",
365
- currentWorker: "",
366
415
  lastEventType: "",
367
416
  sessionId: void 0,
368
417
  executionId: void 0,
@@ -409,10 +458,6 @@ function processStreamEventV2(rawEvent, state) {
409
458
  return state;
410
459
  }
411
460
  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
461
  if (event.executionId) state.executionId = event.executionId;
417
462
  if (event.sessionId) state.sessionId = event.sessionId;
418
463
  state.lastEventType = "THINKING_DELTA";
@@ -423,7 +468,6 @@ function processStreamEventV2(rawEvent, state) {
423
468
  const message = getEventMessage(event);
424
469
  switch (eventType) {
425
470
  case "WORKFLOW_STARTED":
426
- case "STARTED":
427
471
  state.lastEventType = eventType;
428
472
  break;
429
473
  case "INTENT_PROGRESS": {
@@ -436,97 +480,7 @@ function processStreamEventV2(rawEvent, state) {
436
480
  state.lastEventType = eventType;
437
481
  break;
438
482
  }
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
483
  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
484
  const stepId = `step-${state.stepCounter++}`;
531
485
  state.steps.push({
532
486
  id: stepId,
@@ -545,55 +499,18 @@ function processStreamEventV2(rawEvent, state) {
545
499
  const intentStep = state.steps.find((s) => s.eventType === "INTENT_STARTED" && s.status === "in_progress");
546
500
  if (intentStep) {
547
501
  intentStep.status = "completed";
548
- intentStep.isThinking = false;
549
502
  if (event.elapsedMs) intentStep.elapsedMs = event.elapsedMs;
550
503
  if (intentStep.id === state.currentExecutingStepId) state.currentExecutingStepId = void 0;
551
504
  }
552
505
  state.lastEventType = eventType;
553
506
  break;
554
507
  }
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": {
508
+ case "WORKFLOW_COMPLETED": {
583
509
  const totalTime = Number(event.totalTimeMs);
584
510
  if (Number.isFinite(totalTime) && totalTime > 0) {
585
511
  state.totalElapsedMs = totalTime;
586
512
  }
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
- }
513
+ const content = extractResponseContent(event.response);
597
514
  if (content) {
598
515
  state.finalResponse = content;
599
516
  if (event.trace && typeof event.trace === "object") {
@@ -608,7 +525,6 @@ function processStreamEventV2(rawEvent, state) {
608
525
  state.steps.forEach((step) => {
609
526
  if (step.status === "in_progress") {
610
527
  step.status = "completed";
611
- step.isThinking = false;
612
528
  }
613
529
  });
614
530
  state.lastEventType = eventType;
@@ -627,7 +543,6 @@ function processStreamEventV2(rawEvent, state) {
627
543
  };
628
544
  state.notifications.push(notification);
629
545
  state.lastNotification = notification;
630
- if (promptMessage) addThinkingDetail(state, promptMessage);
631
546
  state.lastEventType = eventType;
632
547
  break;
633
548
  }
@@ -653,9 +568,6 @@ function processStreamEventV2(rawEvent, state) {
653
568
  };
654
569
  upsertUserAction(state, request);
655
570
  state.lastUserAction = request;
656
- const header = userActionHeader(kind);
657
- if (promptMessage) addThinkingLine(state, header, promptMessage);
658
- else addThinkingHeader(state, header);
659
571
  const stepId = `step-${state.stepCounter++}`;
660
572
  state.steps.push({
661
573
  id: stepId,
@@ -679,27 +591,15 @@ function processStreamEventV2(rawEvent, state) {
679
591
  };
680
592
  state.notifications.push(notification);
681
593
  state.lastNotification = notification;
682
- if (noteMessage) addThinkingDetail(state, noteMessage);
683
594
  }
684
595
  state.lastEventType = eventType;
685
596
  break;
686
597
  }
687
598
  case "WORKFLOW_ERROR":
688
- case "ERROR":
689
599
  state.hasError = true;
690
600
  state.errorMessage = event.errorMessage || event.message || "Workflow error";
691
601
  state.lastEventType = eventType;
692
602
  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
603
  // ---- K2 pipeline stage lifecycle events ----
704
604
  //
705
605
  // The k2-server playground streaming API emits
@@ -819,82 +719,6 @@ function processStreamEventV2(rawEvent, state) {
819
719
  }
820
720
  return state;
821
721
  }
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
722
  var DEFAULT_STREAM_ENDPOINT = "/api/playground/ask/stream";
899
723
  function buildRequestBody(config, userMessage, sessionId, options) {
900
724
  const sessionOwner = config.sessionParams;
@@ -966,123 +790,6 @@ function buildRequestHeaders(config) {
966
790
  }
967
791
  return headers;
968
792
  }
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
793
  var RAG_IMAGE_REGEX = /\/api\/rag\/chunks\/[^"'\s]+\/image/;
1087
794
  function hasRagImages(content) {
1088
795
  return RAG_IMAGE_REGEX.test(content);
@@ -1194,7 +901,6 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1194
901
  streamProgress: "error",
1195
902
  isError: true,
1196
903
  errorDetails: state.errorMessage,
1197
- formattedThinkingText: state.formattedThinkingText || void 0,
1198
904
  steps: [...state.steps],
1199
905
  currentExecutingStepId: void 0,
1200
906
  executionId: state.executionId,
@@ -1207,7 +913,6 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1207
913
  currentMessage,
1208
914
  streamProgress: "processing",
1209
915
  isError: false,
1210
- formattedThinkingText: state.formattedThinkingText || void 0,
1211
916
  steps: [...state.steps],
1212
917
  currentExecutingStepId: state.currentExecutingStepId,
1213
918
  executionId: state.executionId,
@@ -1234,7 +939,6 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1234
939
  errorDetails: isAborted ? void 0 : error.message,
1235
940
  content: isAborted ? state.finalResponse || "" : state.finalResponse || FRIENDLY_ERROR_MESSAGE,
1236
941
  currentMessage: isAborted ? "Thinking..." : void 0,
1237
- formattedThinkingText: state.formattedThinkingText || void 0,
1238
942
  steps: [...state.steps].map((step) => {
1239
943
  if (step.status === "in_progress" && isAborted) {
1240
944
  return { ...step, status: "pending" };
@@ -1273,7 +977,6 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1273
977
  steps: state.hasError ? [] : [...state.steps],
1274
978
  isCancelled: false,
1275
979
  currentExecutingStepId: void 0,
1276
- formattedThinkingText: state.hasError ? void 0 : state.formattedThinkingText || void 0,
1277
980
  isResolvingImages: needsImageResolve,
1278
981
  totalElapsedMs: state.hasError ? void 0 : state.totalElapsedMs
1279
982
  };
@@ -1326,7 +1029,6 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1326
1029
  isCancelled: isAborted,
1327
1030
  errorDetails: isAborted ? void 0 : error.message,
1328
1031
  content: isAborted ? state.finalResponse || "" : state.finalResponse || FRIENDLY_ERROR_MESSAGE,
1329
- formattedThinkingText: state.formattedThinkingText || void 0,
1330
1032
  steps: [...state.steps].map((step) => {
1331
1033
  if (step.status === "in_progress" && isAborted) {
1332
1034
  return { ...step, status: "pending" };
@@ -1351,6 +1053,57 @@ function useStreamManagerV2(config, callbacks, setMessages, setIsWaitingForRespo
1351
1053
  abortControllerRef
1352
1054
  };
1353
1055
  }
1056
+ function createCancelledMessageUpdate(steps, currentMessage) {
1057
+ const updatedSteps = steps.map((step) => {
1058
+ if (step.status === "in_progress") {
1059
+ return { ...step, status: "pending" };
1060
+ }
1061
+ return step;
1062
+ });
1063
+ return {
1064
+ isStreaming: false,
1065
+ isCancelled: true,
1066
+ steps: updatedSteps,
1067
+ currentExecutingStepId: void 0,
1068
+ currentMessage: currentMessage || "Thinking..."
1069
+ };
1070
+ }
1071
+ var UserActionStaleError = class extends Error {
1072
+ constructor(userActionId, message = "User action is no longer actionable") {
1073
+ super(message);
1074
+ __publicField(this, "userActionId");
1075
+ this.name = "UserActionStaleError";
1076
+ this.userActionId = userActionId;
1077
+ }
1078
+ };
1079
+ async function sendUserActionRequest(config, userActionId, action, data) {
1080
+ const url = buildUserActionUrl(config, userActionId, action);
1081
+ const baseHeaders = buildRequestHeaders(config);
1082
+ const hasBody = data !== void 0;
1083
+ const headers = hasBody ? { "Content-Type": "application/json", ...baseHeaders } : baseHeaders;
1084
+ const response = await fetch(url, {
1085
+ method: "POST",
1086
+ headers,
1087
+ body: hasBody ? JSON.stringify(data) : void 0
1088
+ });
1089
+ if (response.status === 404) {
1090
+ throw new UserActionStaleError(userActionId);
1091
+ }
1092
+ if (!response.ok) {
1093
+ const errorText = await response.text();
1094
+ throw new Error(`HTTP ${response.status}: ${errorText}`);
1095
+ }
1096
+ return await response.json();
1097
+ }
1098
+ async function submitUserAction(config, userActionId, content) {
1099
+ return sendUserActionRequest(config, userActionId, "submit", content ?? {});
1100
+ }
1101
+ async function cancelUserAction(config, userActionId) {
1102
+ return sendUserActionRequest(config, userActionId, "cancel");
1103
+ }
1104
+ async function resendUserAction(config, userActionId) {
1105
+ return sendUserActionRequest(config, userActionId, "resend");
1106
+ }
1354
1107
  var EMPTY_USER_ACTION_STATE = { prompts: [], notifications: [] };
1355
1108
  function upsertPrompt(prompts, req) {
1356
1109
  const active = { ...req, status: "pending" };
@@ -2055,9 +1808,6 @@ function buildContent(schema, values) {
2055
1808
  }
2056
1809
  return content;
2057
1810
  }
2058
- function migrateActiveStream(oldUserId, newUserId) {
2059
- activeStreamStore.rename(oldUserId, newUserId);
2060
- }
2061
1811
  var PaymanChatContext = react.createContext(void 0);
2062
1812
  function usePaymanChat() {
2063
1813
  const context = react.useContext(PaymanChatContext);
@@ -2563,46 +2313,6 @@ function createMarkdownComponents(options = {}) {
2563
2313
  td: ({ children }) => /* @__PURE__ */ jsxRuntime.jsx("td", { className: "p-3 align-middle text-sm whitespace-nowrap", children })
2564
2314
  };
2565
2315
  }
2566
- function ThinkingBlock({ text }) {
2567
- const [isOpen, setIsOpen] = react.useState(false);
2568
- const hasContent = typeof text === "string" && text.trim().length > 0;
2569
- if (!hasContent) return null;
2570
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-1.5 mb-1.5", children: [
2571
- /* @__PURE__ */ jsxRuntime.jsxs(
2572
- "button",
2573
- {
2574
- type: "button",
2575
- onClick: () => setIsOpen((prev) => !prev),
2576
- className: "inline-flex items-center gap-1 text-[10px] payman-agent-thinking-toggle transition-colors",
2577
- "aria-expanded": isOpen,
2578
- "aria-label": isOpen ? "Collapse thought process" : "Expand thought process",
2579
- children: [
2580
- /* @__PURE__ */ jsxRuntime.jsx(
2581
- framerMotion.motion.div,
2582
- {
2583
- animate: { rotate: isOpen ? 180 : 0 },
2584
- transition: { duration: 0.15 },
2585
- className: "shrink-0",
2586
- children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ChevronDown, { className: "h-3 w-3" })
2587
- }
2588
- ),
2589
- /* @__PURE__ */ jsxRuntime.jsx("span", { children: "Thought process" })
2590
- ]
2591
- }
2592
- ),
2593
- /* @__PURE__ */ jsxRuntime.jsx(framerMotion.AnimatePresence, { initial: false, children: isOpen && /* @__PURE__ */ jsxRuntime.jsx(
2594
- framerMotion.motion.div,
2595
- {
2596
- initial: { height: 0, opacity: 0 },
2597
- animate: { height: "auto", opacity: 1 },
2598
- exit: { height: 0, opacity: 0 },
2599
- transition: { duration: 0.2, ease: "easeInOut" },
2600
- className: "overflow-hidden",
2601
- children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-1 payman-agent-thinking-block rounded-md p-2 overflow-y-auto overflow-x-hidden", children: /* @__PURE__ */ jsxRuntime.jsx("p", { className: "m-0 text-xs payman-agent-thinking-block-text whitespace-pre-wrap leading-relaxed", children: text }) })
2602
- }
2603
- ) })
2604
- ] });
2605
- }
2606
2316
  var FRIENDLY_ERROR_MESSAGE2 = "Oops, something went wrong. Please try again.";
2607
2317
  function looksLikeRawError(text) {
2608
2318
  if (!text || text.length < 10) return false;
@@ -2645,8 +2355,6 @@ function AgentMessage({
2645
2355
  const completedWithNoContent = !isStreaming && !isCancelled && content.length === 0 && (message.streamProgress === "completed" || message.streamProgress === "error");
2646
2356
  const conflictErrorMessage = getConflictErrorMessage(message.errorDetails);
2647
2357
  const isError = !!conflictErrorMessage || (isFriendlyWorkflowError(message.errorDetails) || looksLikeRawError(content)) && !hasMeaningfulContent || completedWithNoContent;
2648
- const activeThinkingText = message.activeThinkingText;
2649
- const allThinkingText = message.allThinkingText;
2650
2358
  const currentStep = react.useMemo(
2651
2359
  () => message.steps?.find(
2652
2360
  (s) => s.id === currentExecutingStepId && s.status === "in_progress"
@@ -2689,7 +2397,7 @@ function AgentMessage({
2689
2397
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className: wrapper, children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "h-3.5 w-3.5 payman-agent-step-icon--error" }) });
2690
2398
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className: wrapper, children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-1.5 w-1.5 rounded-full payman-agent-step-icon--pending-dim" }) });
2691
2399
  };
2692
- const stepsListContent = hasSteps && /* @__PURE__ */ jsxRuntime.jsx(framerMotion.AnimatePresence, { initial: false, children: isStepsExpanded && /* @__PURE__ */ jsxRuntime.jsxs(
2400
+ const stepsListContent = hasSteps && /* @__PURE__ */ jsxRuntime.jsx(framerMotion.AnimatePresence, { initial: false, children: isStepsExpanded && /* @__PURE__ */ jsxRuntime.jsx(
2693
2401
  framerMotion.motion.div,
2694
2402
  {
2695
2403
  initial: { height: 0, opacity: 0 },
@@ -2697,37 +2405,34 @@ function AgentMessage({
2697
2405
  exit: { height: 0, opacity: 0 },
2698
2406
  transition: { duration: 0.2, ease: "easeInOut" },
2699
2407
  className: "overflow-hidden",
2700
- children: [
2701
- !isStreaming && allThinkingText?.trim() && /* @__PURE__ */ jsxRuntime.jsx(ThinkingBlock, { text: allThinkingText }),
2702
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pt-1.5", children: message.steps.map((step) => {
2703
- const isCurrentlyExecuting = step.id === currentExecutingStepId && step.status === "in_progress" && isStreaming && !isCancelled;
2704
- const hasTime = step.elapsedMs != null && step.elapsedMs > 0;
2705
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mb-1.5", children: [
2706
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-1.5 items-start", children: [
2707
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-px", children: renderStepIcon(step, isCurrentlyExecuting) }),
2708
- /* @__PURE__ */ jsxRuntime.jsx(
2709
- "span",
2710
- {
2711
- className: cn(
2712
- "text-xs leading-relaxed min-w-0 break-words",
2713
- isCurrentlyExecuting && "shimmer-text font-medium",
2714
- !isCurrentlyExecuting && step.status === "error" && "payman-agent-step-text--error",
2715
- !isCurrentlyExecuting && step.eventType === "USER_ACTION_SUCCESS" && "payman-agent-step-text--success",
2716
- !isCurrentlyExecuting && step.status === "completed" && "payman-agent-step-text--completed",
2717
- !isCurrentlyExecuting && step.status === "pending" && "payman-agent-step-text--pending",
2718
- !isCurrentlyExecuting && step.status === "in_progress" && "payman-agent-step-text--in-progress"
2719
- ),
2720
- children: step.message
2721
- }
2722
- )
2723
- ] }),
2724
- hasTime && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pl-[22px] mt-1", children: /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md payman-agent-step-time leading-none", children: [
2725
- /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Clock, { className: "h-2.5 w-2.5 shrink-0 payman-agent-step-time-icon" }),
2726
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-[10px] font-mono payman-agent-step-time-text", children: formatElapsedTime(step.elapsedMs) })
2727
- ] }) })
2728
- ] }, step.id);
2729
- }) })
2730
- ]
2408
+ children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pt-1.5", children: message.steps.map((step) => {
2409
+ const isCurrentlyExecuting = step.id === currentExecutingStepId && step.status === "in_progress" && isStreaming && !isCancelled;
2410
+ const hasTime = step.elapsedMs != null && step.elapsedMs > 0;
2411
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mb-1.5", children: [
2412
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-1.5 items-start", children: [
2413
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-px", children: renderStepIcon(step, isCurrentlyExecuting) }),
2414
+ /* @__PURE__ */ jsxRuntime.jsx(
2415
+ "span",
2416
+ {
2417
+ className: cn(
2418
+ "text-xs leading-relaxed min-w-0 break-words",
2419
+ isCurrentlyExecuting && "shimmer-text font-medium",
2420
+ !isCurrentlyExecuting && step.status === "error" && "payman-agent-step-text--error",
2421
+ !isCurrentlyExecuting && step.eventType === "USER_ACTION_SUCCESS" && "payman-agent-step-text--success",
2422
+ !isCurrentlyExecuting && step.status === "completed" && "payman-agent-step-text--completed",
2423
+ !isCurrentlyExecuting && step.status === "pending" && "payman-agent-step-text--pending",
2424
+ !isCurrentlyExecuting && step.status === "in_progress" && "payman-agent-step-text--in-progress"
2425
+ ),
2426
+ children: step.message
2427
+ }
2428
+ )
2429
+ ] }),
2430
+ hasTime && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pl-[22px] mt-1", children: /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md payman-agent-step-time leading-none", children: [
2431
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Clock, { className: "h-2.5 w-2.5 shrink-0 payman-agent-step-time-icon" }),
2432
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-[10px] font-mono payman-agent-step-time-text", children: formatElapsedTime(step.elapsedMs) })
2433
+ ] }) })
2434
+ ] }, step.id);
2435
+ }) })
2731
2436
  }
2732
2437
  ) });
2733
2438
  const stepsToggleRef = react.useRef(null);
@@ -2808,22 +2513,13 @@ function AgentMessage({
2808
2513
  "text-sm leading-relaxed min-w-0 w-full break-words overflow-wrap-anywhere",
2809
2514
  showAgentName && "mt-1"
2810
2515
  ),
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" })
2818
- ] })
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: [
2516
+ children: isStreaming && !content ? currentStep ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-1.5 items-start", children: [
2517
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-0.5 shrink-0", children: renderStepIcon(currentStep, true) }),
2518
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm leading-relaxed min-w-0 break-words shimmer-text font-medium flex-1", children: currentStep.message })
2519
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2.5 items-start", children: [
2520
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "w-4 h-4 mt-0.5 payman-agent-thinking-spinner animate-spin shrink-0" }),
2521
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm payman-agent-thinking-text flex-1", children: currentMessage || "Thinking..." })
2522
+ ] }) : isCancelled && !content ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2.5 items-start", children: [
2827
2523
  /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "w-4 h-4 mt-0.5 payman-agent-cancelled-icon shrink-0" }),
2828
2524
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm payman-agent-cancelled-text italic flex-1", children: currentMessage || "Request was stopped." })
2829
2525
  ] }) : /* @__PURE__ */ jsxRuntime.jsx(
@@ -6592,7 +6288,7 @@ var PaymanChatInner = react.forwardRef(function PaymanChatInner2({
6592
6288
  style,
6593
6289
  children: [
6594
6290
  children,
6595
- isChatDisabled ? disabledComponent || /* @__PURE__ */ jsxRuntime.jsx("div", { style: { flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "1rem" }, children: /* @__PURE__ */ jsxRuntime.jsx("div", { style: { textAlign: "center", color: "var(--payman-v2-text-3)", fontSize: "0.875rem" }, children: "Chat is currently disabled" }) }) : /* @__PURE__ */ jsxRuntime.jsx(framerMotion.AnimatePresence, { mode: "wait", children: isEmpty && !hasEverSentMessage ? /* @__PURE__ */ jsxRuntime.jsx(
6291
+ /* @__PURE__ */ jsxRuntime.jsx(framerMotion.AnimatePresence, { mode: "wait", children: isEmpty && !hasEverSentMessage ? /* @__PURE__ */ jsxRuntime.jsx(
6596
6292
  framerMotion.motion.div,
6597
6293
  {
6598
6294
  initial: { opacity: 1 },
@@ -6782,31 +6478,14 @@ var PaymanChat = react.forwardRef(
6782
6478
  exports.PaymanChat = PaymanChat;
6783
6479
  exports.PaymanChatContext = PaymanChatContext;
6784
6480
  exports.UserActionStaleError = UserActionStaleError;
6785
- exports.buildContent = buildContent;
6786
- exports.buildFormattedThinking = buildFormattedThinking;
6787
6481
  exports.cancelUserAction = cancelUserAction;
6788
6482
  exports.captureSentryError = captureSentryError;
6789
- exports.classifyField = classifyField;
6790
- exports.classifyUserActionKind = classifyUserActionKind;
6791
6483
  exports.cn = cn;
6792
- exports.coerceValue = coerceValue;
6793
- exports.createInitialV2State = createInitialV2State;
6794
- exports.defaultValueFor = defaultValueFor;
6795
6484
  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
6485
  exports.resendUserAction = resendUserAction;
6804
- exports.streamWorkflowEvents = streamWorkflowEvents;
6805
6486
  exports.submitUserAction = submitUserAction;
6806
6487
  exports.useChatV2 = useChatV2;
6807
6488
  exports.usePaymanChat = usePaymanChat;
6808
6489
  exports.useVoice = useVoice;
6809
- exports.validateField = validateField;
6810
- exports.validateForm = validateForm;
6811
6490
  //# sourceMappingURL=index.js.map
6812
6491
  //# sourceMappingURL=index.js.map