@paymanai/payman-ask-sdk 1.2.21 → 1.2.23

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
@@ -54,6 +54,114 @@ function formatElapsedTime(ms) {
54
54
  if (ms < 1e3) return `${ms}ms`;
55
55
  return `${(ms / 1e3).toFixed(1)}s`;
56
56
  }
57
+ function captureSentryError(error, context) {
58
+ if (!Sentry.getClient()) return;
59
+ const tags = {};
60
+ if (context.executionId) tags.executionId = context.executionId;
61
+ if (context.sessionId) tags.sessionId = context.sessionId;
62
+ if (context.route) tags.route = context.route;
63
+ if (context.cfRay) tags.cfRay = context.cfRay;
64
+ if (context.customerId) tags.customerId = context.customerId;
65
+ if (context.customerEmail) tags.customerEmail = context.customerEmail;
66
+ const contexts = {
67
+ chat_session: {
68
+ sessionId: context.sessionId ?? null,
69
+ sessionOwnerId: context.sessionOwnerId ?? null,
70
+ executionId: context.executionId ?? null,
71
+ workflowName: context.workflowName ?? null,
72
+ cfRay: context.cfRay ?? null,
73
+ customerId: context.customerId ?? null,
74
+ customerEmail: context.customerEmail ?? null
75
+ }
76
+ };
77
+ if (typeof error === "string") {
78
+ Sentry.captureMessage(error, { level: "error", tags, contexts });
79
+ } else {
80
+ Sentry.captureException(error, { tags, contexts });
81
+ }
82
+ }
83
+ var interceptors = /* @__PURE__ */ new Set();
84
+ var originalFetch = null;
85
+ function patchFetch() {
86
+ if (originalFetch !== null) return;
87
+ if (typeof globalThis === "undefined" || typeof globalThis.fetch !== "function")
88
+ return;
89
+ originalFetch = globalThis.fetch;
90
+ globalThis.fetch = async function(input, init2) {
91
+ const response = await originalFetch.call(this, input, init2);
92
+ if (interceptors.size > 0) {
93
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
94
+ try {
95
+ const cfRay = response.headers.get("cf-ray");
96
+ if (cfRay) {
97
+ for (const entry of interceptors) {
98
+ if (url.includes(entry.urlPattern)) {
99
+ entry.listener(cfRay);
100
+ }
101
+ }
102
+ }
103
+ } catch {
104
+ }
105
+ }
106
+ return response;
107
+ };
108
+ }
109
+ function maybeUnpatchFetch() {
110
+ if (interceptors.size > 0 || originalFetch === null) return;
111
+ globalThis.fetch = originalFetch;
112
+ originalFetch = null;
113
+ }
114
+ function subscribeToCfRay(urlPattern, listener) {
115
+ const entry = { urlPattern, listener };
116
+ patchFetch();
117
+ interceptors.add(entry);
118
+ return () => {
119
+ interceptors.delete(entry);
120
+ maybeUnpatchFetch();
121
+ };
122
+ }
123
+
124
+ // src/utils/errorMessages.ts
125
+ var WORKFLOW_FAILED = "WORKFLOW_FAILED";
126
+ var STREAM_NOT_STARTED = "STREAM_NOT_STARTED";
127
+ var HTTP_ERROR_PREFIX = /^HTTP\s+(\d+)\s*:\s*([\s\S]+)$/;
128
+ function isFriendlyWorkflowError(errorDetails) {
129
+ if (!errorDetails) return false;
130
+ return errorDetails === WORKFLOW_FAILED || errorDetails === STREAM_NOT_STARTED || errorDetails.includes(WORKFLOW_FAILED);
131
+ }
132
+ function parseErrorPayload(payload) {
133
+ try {
134
+ const parsed = JSON.parse(payload);
135
+ if (typeof parsed === "string") {
136
+ return { message: parsed.trim() || void 0 };
137
+ }
138
+ if (typeof parsed === "object" && parsed !== null) {
139
+ const record = parsed;
140
+ return {
141
+ status: typeof record.status === "number" ? record.status : void 0,
142
+ message: typeof record.message === "string" && record.message.trim() ? record.message.trim() : void 0
143
+ };
144
+ }
145
+ } catch {
146
+ }
147
+ return {};
148
+ }
149
+ function getConflictErrorMessage(errorDetails) {
150
+ if (!errorDetails) return void 0;
151
+ const trimmedError = errorDetails.trim();
152
+ const httpMatch = trimmedError.match(HTTP_ERROR_PREFIX);
153
+ const httpStatus = httpMatch ? Number(httpMatch[1]) : void 0;
154
+ const rawPayload = (httpMatch ? httpMatch[2] : trimmedError).trim();
155
+ const payload = parseErrorPayload(rawPayload);
156
+ const status = payload.status ?? httpStatus;
157
+ if (status !== 409) {
158
+ return void 0;
159
+ }
160
+ if (payload.message) {
161
+ return payload.message;
162
+ }
163
+ return rawPayload || void 0;
164
+ }
57
165
  function initSentryIfNeeded(dsn) {
58
166
  if (!dsn) return;
59
167
  if (Sentry.getClient()) return;
@@ -578,48 +686,6 @@ function createMarkdownComponents(options = {}) {
578
686
  td: ({ children }) => /* @__PURE__ */ jsx("td", { className: "p-3 align-middle text-sm whitespace-nowrap", children })
579
687
  };
580
688
  }
581
-
582
- // src/utils/errorMessages.ts
583
- var WORKFLOW_FAILED = "WORKFLOW_FAILED";
584
- var STREAM_NOT_STARTED = "STREAM_NOT_STARTED";
585
- var HTTP_ERROR_PREFIX = /^HTTP\s+(\d+)\s*:\s*([\s\S]+)$/;
586
- function isFriendlyWorkflowError(errorDetails) {
587
- if (!errorDetails) return false;
588
- return errorDetails === WORKFLOW_FAILED || errorDetails === STREAM_NOT_STARTED || errorDetails.includes(WORKFLOW_FAILED);
589
- }
590
- function parseErrorPayload(payload) {
591
- try {
592
- const parsed = JSON.parse(payload);
593
- if (typeof parsed === "string") {
594
- return { message: parsed.trim() || void 0 };
595
- }
596
- if (typeof parsed === "object" && parsed !== null) {
597
- const record = parsed;
598
- return {
599
- status: typeof record.status === "number" ? record.status : void 0,
600
- message: typeof record.message === "string" && record.message.trim() ? record.message.trim() : void 0
601
- };
602
- }
603
- } catch {
604
- }
605
- return {};
606
- }
607
- function getConflictErrorMessage(errorDetails) {
608
- if (!errorDetails) return void 0;
609
- const trimmedError = errorDetails.trim();
610
- const httpMatch = trimmedError.match(HTTP_ERROR_PREFIX);
611
- const httpStatus = httpMatch ? Number(httpMatch[1]) : void 0;
612
- const rawPayload = (httpMatch ? httpMatch[2] : trimmedError).trim();
613
- const payload = parseErrorPayload(rawPayload);
614
- const status = payload.status ?? httpStatus;
615
- if (status !== 409) {
616
- return void 0;
617
- }
618
- if (payload.message) {
619
- return payload.message;
620
- }
621
- return rawPayload || void 0;
622
- }
623
689
  function ThinkingBlock({ text }) {
624
690
  const [isOpen, setIsOpen] = useState(false);
625
691
  const hasContent = typeof text === "string" && text.trim().length > 0;
@@ -2012,7 +2078,75 @@ var PaymanChat = forwardRef(function PaymanChat2({
2012
2078
  initSentryIfNeeded(config.sentryDsn);
2013
2079
  }
2014
2080
  }, [config.sentryDsn]);
2015
- const chat = useChat(config, callbacks);
2081
+ const sentryCtxRef = useRef({});
2082
+ const callbacksRef = useRef(callbacks);
2083
+ callbacksRef.current = callbacks;
2084
+ const initialSessionId = config.initialSessionId;
2085
+ const apiHeaders = config.api.headers;
2086
+ useEffect(() => {
2087
+ sentryCtxRef.current.workflowName = config.workflowName;
2088
+ sentryCtxRef.current.sessionOwnerId = config.sessionParams?.id;
2089
+ if (initialSessionId) {
2090
+ sentryCtxRef.current.sessionId = initialSessionId;
2091
+ }
2092
+ if (apiHeaders) {
2093
+ sentryCtxRef.current.customerId = apiHeaders["x-paygent-wf-mcp-customer-id"] ?? sentryCtxRef.current.customerId;
2094
+ sentryCtxRef.current.customerEmail = apiHeaders["x-paygent-wf-mcp-customer-email"] ?? sentryCtxRef.current.customerEmail;
2095
+ }
2096
+ }, [
2097
+ config.workflowName,
2098
+ config.sessionParams?.id,
2099
+ initialSessionId,
2100
+ apiHeaders
2101
+ ]);
2102
+ useEffect(() => {
2103
+ const endpoint = config.api.streamEndpoint || "/api/workflows/ask/stream";
2104
+ return subscribeToCfRay(endpoint, (cfRay) => {
2105
+ sentryCtxRef.current.cfRay = cfRay;
2106
+ });
2107
+ }, [config.api.streamEndpoint]);
2108
+ const sentryCallbacks = useMemo(
2109
+ () => ({
2110
+ onMessageSent: (msg) => callbacksRef.current.onMessageSent?.(msg),
2111
+ onStreamStart: () => callbacksRef.current.onStreamStart?.(),
2112
+ onStreamComplete: (message) => {
2113
+ if (message.executionId)
2114
+ sentryCtxRef.current.executionId = message.executionId;
2115
+ if (message.sessionId)
2116
+ sentryCtxRef.current.sessionId = message.sessionId;
2117
+ const content = message.content ?? "";
2118
+ const looksLikeRawErr = content.length >= 10 && (content.includes("errorType=") || /failed:\s*\{/.test(content));
2119
+ const completedEmpty = !message.isStreaming && !message.isCancelled && content.length === 0 && (message.streamProgress === "completed" || message.streamProgress === "error");
2120
+ const hasConflict = !!getConflictErrorMessage(message.errorDetails);
2121
+ const hasFriendlyErr = isFriendlyWorkflowError(message.errorDetails);
2122
+ const shouldCapture = message.isError || hasConflict || hasFriendlyErr || looksLikeRawErr || completedEmpty;
2123
+ if (shouldCapture) {
2124
+ sentryCtxRef.current.route = typeof window !== "undefined" ? window.location.pathname : void 0;
2125
+ captureSentryError(
2126
+ `Workflow error: ${message.errorDetails || content || "Unknown error"}`,
2127
+ { ...sentryCtxRef.current }
2128
+ );
2129
+ }
2130
+ callbacksRef.current.onStreamComplete?.(message);
2131
+ },
2132
+ onError: (error) => {
2133
+ sentryCtxRef.current.route = typeof window !== "undefined" ? window.location.pathname : void 0;
2134
+ captureSentryError(error, { ...sentryCtxRef.current });
2135
+ callbacksRef.current.onError?.(error);
2136
+ },
2137
+ onSessionIdChange: (sessionId) => {
2138
+ sentryCtxRef.current.sessionId = sessionId;
2139
+ callbacksRef.current.onSessionIdChange?.(sessionId);
2140
+ },
2141
+ onExecutionTraceClick: (data) => callbacksRef.current.onExecutionTraceClick?.(data),
2142
+ onResetSession: () => callbacksRef.current.onResetSession?.(),
2143
+ onUserActionRequired: (req) => callbacksRef.current.onUserActionRequired?.(req),
2144
+ onUserActionEvent: (evType, msg) => callbacksRef.current.onUserActionEvent?.(evType, msg)
2145
+ }),
2146
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2147
+ []
2148
+ );
2149
+ const chat = useChat(config, sentryCallbacks);
2016
2150
  const {
2017
2151
  messages,
2018
2152
  sendMessage,
@@ -2327,6 +2461,6 @@ var PaymanChat = forwardRef(function PaymanChat2({
2327
2461
  ) });
2328
2462
  });
2329
2463
 
2330
- export { PaymanChat, PaymanChatContext, cn, formatDate, usePaymanChat };
2464
+ export { PaymanChat, PaymanChatContext, captureSentryError, cn, formatDate, usePaymanChat };
2331
2465
  //# sourceMappingURL=index.mjs.map
2332
2466
  //# sourceMappingURL=index.mjs.map