@mastra/react 0.1.1 → 0.2.0-alpha.1

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/{chunk-55VPMN3N-BHqoDkCq.cjs → chunk-REDZDNFN-D4qauMBp.cjs} +4 -4
  3. package/dist/chunk-REDZDNFN-D4qauMBp.cjs.map +1 -0
  4. package/dist/{chunk-55VPMN3N-Ax1F4Y75.js → chunk-REDZDNFN-DEIWVTdL.js} +4 -4
  5. package/dist/chunk-REDZDNFN-DEIWVTdL.js.map +1 -0
  6. package/dist/{index-D3JtF_Zl.js → index-BrMELKWu.js} +594 -28
  7. package/dist/index-BrMELKWu.js.map +1 -0
  8. package/dist/{index-ChvWx-iU.cjs → index-TEBHU8EU.cjs} +595 -26
  9. package/dist/index-TEBHU8EU.cjs.map +1 -0
  10. package/dist/index.cjs +4 -1
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/src/index.d.ts +1 -0
  14. package/dist/src/lib/use-mutation.d.ts +27 -0
  15. package/dist/src/mastra-client-context.d.ts +3 -1
  16. package/dist/src/mastra-react-provider.d.ts +1 -1
  17. package/dist/src/workflows/hooks.d.ts +33 -0
  18. package/dist/src/workflows/index.d.ts +2 -0
  19. package/dist/src/workflows/types.d.ts +121 -0
  20. package/dist/src/workflows/use-stream-workflow.d.ts +38 -0
  21. package/dist/{token-6GSAFR2W-SPYPLMBM-CWoxKwfk.cjs → token-6GSAFR2W-XRCSVUPZ-DdTrjI2X.cjs} +5 -5
  22. package/dist/token-6GSAFR2W-XRCSVUPZ-DdTrjI2X.cjs.map +1 -0
  23. package/dist/{token-6GSAFR2W-SPYPLMBM-ChURikIE.js → token-6GSAFR2W-XRCSVUPZ-JdBnAp2N.js} +4 -4
  24. package/dist/token-6GSAFR2W-XRCSVUPZ-JdBnAp2N.js.map +1 -0
  25. package/dist/token-util-NEHG7TUY-U7CX7GS4-CfBW62uu.cjs +11 -0
  26. package/dist/token-util-NEHG7TUY-U7CX7GS4-CfBW62uu.cjs.map +1 -0
  27. package/dist/{token-util-NEHG7TUY-JRJTGTAB-hEay2AHp.js → token-util-NEHG7TUY-U7CX7GS4-DhQqQpmz.js} +2 -2
  28. package/dist/token-util-NEHG7TUY-U7CX7GS4-DhQqQpmz.js.map +1 -0
  29. package/package.json +3 -3
  30. package/dist/chunk-55VPMN3N-Ax1F4Y75.js.map +0 -1
  31. package/dist/chunk-55VPMN3N-BHqoDkCq.cjs.map +0 -1
  32. package/dist/index-ChvWx-iU.cjs.map +0 -1
  33. package/dist/index-D3JtF_Zl.js.map +0 -1
  34. package/dist/token-6GSAFR2W-SPYPLMBM-CWoxKwfk.cjs.map +0 -1
  35. package/dist/token-6GSAFR2W-SPYPLMBM-ChURikIE.js.map +0 -1
  36. package/dist/token-util-NEHG7TUY-JRJTGTAB-BU9ZxL1w.cjs +0 -11
  37. package/dist/token-util-NEHG7TUY-JRJTGTAB-BU9ZxL1w.cjs.map +0 -1
  38. package/dist/token-util-NEHG7TUY-JRJTGTAB-hEay2AHp.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { jsx, jsxs } from 'react/jsx-runtime';
2
- import { createContext, useContext, useRef, useState, Fragment, useLayoutEffect, useEffect } from 'react';
2
+ import { createContext, useContext, useRef, useState, Fragment, useLayoutEffect, useEffect, useCallback } from 'react';
3
3
  import { MastraClient } from '@mastra/client-js';
4
4
  import * as z4 from 'zod/v4';
5
5
  import { z } from 'zod/v4';
@@ -13,21 +13,22 @@ import { codeToHast } from 'shiki/bundle/web';
13
13
  import { TooltipProvider, Root, TooltipPortal, TooltipContent as TooltipContent$1, TooltipTrigger as TooltipTrigger$1 } from '@radix-ui/react-tooltip';
14
14
 
15
15
  const MastraClientContext = createContext({});
16
- const MastraClientProvider = ({ children, baseUrl, headers }) => {
17
- const client = createMastraClient(baseUrl, headers);
16
+ const MastraClientProvider = ({ children, baseUrl, headers, apiPrefix }) => {
17
+ const client = createMastraClient(baseUrl, headers, apiPrefix);
18
18
  return /* @__PURE__ */ jsx(MastraClientContext.Provider, { value: client, children });
19
19
  };
20
20
  const useMastraClient = () => useContext(MastraClientContext);
21
- const createMastraClient = (baseUrl, mastraClientHeaders = {}) => {
21
+ const createMastraClient = (baseUrl, mastraClientHeaders = {}, apiPrefix) => {
22
22
  return new MastraClient({
23
23
  baseUrl: baseUrl || "",
24
24
  // only add the header if the baseUrl is not provided i.e it's a local dev environment
25
- headers: !baseUrl ? { ...mastraClientHeaders, "x-mastra-dev-playground": "true" } : mastraClientHeaders
25
+ headers: !baseUrl ? { ...mastraClientHeaders, "x-mastra-dev-playground": "true" } : mastraClientHeaders,
26
+ apiPrefix
26
27
  });
27
28
  };
28
29
 
29
- const MastraReactProvider = ({ children, baseUrl, headers }) => {
30
- return /* @__PURE__ */ jsx(MastraClientProvider, { baseUrl, headers, children });
30
+ const MastraReactProvider = ({ children, baseUrl, headers, apiPrefix }) => {
31
+ return /* @__PURE__ */ jsx(MastraClientProvider, { baseUrl, headers, apiPrefix, children });
31
32
  };
32
33
 
33
34
  const mapWorkflowStreamChunkToWatchResult = (prev, chunk) => {
@@ -946,6 +947,125 @@ const resolveToChildMessages = (messages) => {
946
947
  return childMessages;
947
948
  };
948
949
 
950
+ // src/request-context/index.ts
951
+ var RequestContext = class {
952
+ registry = /* @__PURE__ */ new Map();
953
+ constructor(iterable) {
954
+ this.registry = new Map(iterable);
955
+ }
956
+ /**
957
+ * set a value with strict typing if `Values` is a Record and the key exists in it.
958
+ */
959
+ set(key, value) {
960
+ this.registry.set(key, value);
961
+ }
962
+ /**
963
+ * Get a value with its type
964
+ */
965
+ get(key) {
966
+ return this.registry.get(key);
967
+ }
968
+ /**
969
+ * Check if a key exists in the container
970
+ */
971
+ has(key) {
972
+ return this.registry.has(key);
973
+ }
974
+ /**
975
+ * Delete a value by key
976
+ */
977
+ delete(key) {
978
+ return this.registry.delete(key);
979
+ }
980
+ /**
981
+ * Clear all values from the container
982
+ */
983
+ clear() {
984
+ this.registry.clear();
985
+ }
986
+ /**
987
+ * Get all keys in the container
988
+ */
989
+ keys() {
990
+ return this.registry.keys();
991
+ }
992
+ /**
993
+ * Get all values in the container
994
+ */
995
+ values() {
996
+ return this.registry.values();
997
+ }
998
+ /**
999
+ * Get all entries in the container.
1000
+ * Returns a discriminated union of tuples for proper type narrowing when iterating.
1001
+ */
1002
+ entries() {
1003
+ return this.registry.entries();
1004
+ }
1005
+ /**
1006
+ * Get the size of the container
1007
+ */
1008
+ size() {
1009
+ return this.registry.size;
1010
+ }
1011
+ /**
1012
+ * Execute a function for each entry in the container.
1013
+ * The callback receives properly typed key-value pairs.
1014
+ */
1015
+ forEach(callbackfn) {
1016
+ this.registry.forEach(callbackfn);
1017
+ }
1018
+ /**
1019
+ * Custom JSON serialization method.
1020
+ * Converts the internal Map to a plain object for proper JSON serialization.
1021
+ * Non-serializable values (e.g., RPC proxies, functions, circular references)
1022
+ * are skipped to prevent serialization errors when storing to database.
1023
+ */
1024
+ toJSON() {
1025
+ const result = {};
1026
+ for (const [key, value] of this.registry.entries()) {
1027
+ if (this.isSerializable(value)) {
1028
+ result[key] = value;
1029
+ }
1030
+ }
1031
+ return result;
1032
+ }
1033
+ /**
1034
+ * Check if a value can be safely serialized to JSON.
1035
+ */
1036
+ isSerializable(value) {
1037
+ if (value === null || value === void 0) return true;
1038
+ if (typeof value === "function") return false;
1039
+ if (typeof value === "symbol") return false;
1040
+ if (typeof value !== "object") return true;
1041
+ try {
1042
+ JSON.stringify(value);
1043
+ return true;
1044
+ } catch {
1045
+ return false;
1046
+ }
1047
+ }
1048
+ /**
1049
+ * Get all values as a typed object for destructuring.
1050
+ * Returns Record<string, any> when untyped, or the Values type when typed.
1051
+ *
1052
+ * @example
1053
+ * ```typescript
1054
+ * const ctx = new RequestContext<{ userId: string; apiKey: string }>();
1055
+ * ctx.set('userId', 'user-123');
1056
+ * ctx.set('apiKey', 'key-456');
1057
+ * const { userId, apiKey } = ctx.all;
1058
+ * ```
1059
+ */
1060
+ get all() {
1061
+ return Object.fromEntries(this.registry);
1062
+ }
1063
+ };
1064
+
1065
+ function getDefaultExportFromCjs (x) {
1066
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1067
+ }
1068
+
949
1069
  var __create$3 = Object.create;
950
1070
  var __defProp$5 = Object.defineProperty;
951
1071
  var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
@@ -1013,7 +1133,7 @@ var __toESM$2 = (mod, isNodeMode, target) => (target = mod != null ? __create$2(
1013
1133
 
1014
1134
  // ../_vendored/ai_v5/dist/chunk-TLQKI65U.js
1015
1135
  var require_token_error = __commonJS$2({
1016
- "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/token-error.js"(exports, module) {
1136
+ "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/token-error.js"(exports$1, module) {
1017
1137
  var __defProp2 = Object.defineProperty;
1018
1138
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
1019
1139
  var __getOwnPropNames2 = Object.getOwnPropertyNames;
@@ -3061,7 +3181,7 @@ function withoutTrailingSlash(url) {
3061
3181
  }
3062
3182
 
3063
3183
  var require_get_context = __commonJS$2({
3064
- "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-context.js"(exports, module) {
3184
+ "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-context.js"(exports$1, module) {
3065
3185
  var __defProp2 = Object.defineProperty;
3066
3186
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3067
3187
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -3093,7 +3213,7 @@ var require_get_context = __commonJS$2({
3093
3213
  }
3094
3214
  });
3095
3215
  var require_get_vercel_oidc_token = __commonJS$2({
3096
- "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports, module) {
3216
+ "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports$1, module) {
3097
3217
  var __defProp2 = Object.defineProperty;
3098
3218
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3099
3219
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -3129,8 +3249,8 @@ var require_get_vercel_oidc_token = __commonJS$2({
3129
3249
  }
3130
3250
  try {
3131
3251
  const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
3132
- await import('./token-util-NEHG7TUY-JRJTGTAB-hEay2AHp.js'),
3133
- await import('./token-6GSAFR2W-SPYPLMBM-ChURikIE.js')
3252
+ await import('./token-util-NEHG7TUY-U7CX7GS4-DhQqQpmz.js'),
3253
+ await import('./token-6GSAFR2W-XRCSVUPZ-JdBnAp2N.js')
3134
3254
  ]);
3135
3255
  if (!token || isExpired(getTokenPayload(token))) {
3136
3256
  await refreshToken();
@@ -3157,7 +3277,7 @@ ${error.message}`;
3157
3277
  }
3158
3278
  });
3159
3279
  var require_dist = __commonJS$2({
3160
- "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/index.js"(exports, module) {
3280
+ "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/index.js"(exports$1, module) {
3161
3281
  var __defProp2 = Object.defineProperty;
3162
3282
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3163
3283
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -5753,7 +5873,7 @@ var __toESM$1 = (mod, isNodeMode, target) => (target = mod != null ? __create$1(
5753
5873
  mod
5754
5874
  ));
5755
5875
  var require_secure_json_parse$1 = __commonJS$1({
5756
- "../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports, module) {
5876
+ "../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports$1, module) {
5757
5877
  var hasBuffer = typeof Buffer !== "undefined";
5758
5878
  var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
5759
5879
  var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
@@ -11526,6 +11646,9 @@ function sanitizeV5UIMessages(messages, filterIncompleteToolCalls = false) {
11526
11646
  const msgs = messages.map((m) => {
11527
11647
  if (m.parts.length === 0) return false;
11528
11648
  const safeParts = m.parts.filter((p) => {
11649
+ if (typeof p.type === "string" && p.type.startsWith("data-")) {
11650
+ return false;
11651
+ }
11529
11652
  if (!isToolUIPart(p)) return true;
11530
11653
  if (filterIncompleteToolCalls) {
11531
11654
  return p.state === "output-available" || p.state === "output-error";
@@ -12039,10 +12162,10 @@ var imageMediaTypeSignatures = [
12039
12162
  var stripID3 = (data) => {
12040
12163
  const bytes = typeof data === "string" ? convertBase64ToUint8Array(data) : data;
12041
12164
  const id3Size = (
12042
- // @ts-ignore
12043
- (bytes[6] & 127) << 21 | // @ts-ignore
12044
- (bytes[7] & 127) << 14 | // @ts-ignore
12045
- (bytes[8] & 127) << 7 | // @ts-ignore
12165
+ // @ts-expect-error - bytes array access
12166
+ (bytes[6] & 127) << 21 | // @ts-expect-error - bytes array access
12167
+ (bytes[7] & 127) << 14 | // @ts-expect-error - bytes array access
12168
+ (bytes[8] & 127) << 7 | // @ts-expect-error - bytes array access
12046
12169
  bytes[9] & 127
12047
12170
  );
12048
12171
  return bytes.slice(id3Size + 10);
@@ -12250,7 +12373,7 @@ function convertToV1Messages(messages) {
12250
12373
  role: "user",
12251
12374
  ...fields,
12252
12375
  type: "text",
12253
- // @ts-ignore
12376
+ // @ts-expect-error - content type mismatch in conversion
12254
12377
  content: userContent
12255
12378
  });
12256
12379
  } else {
@@ -12921,7 +13044,7 @@ var MessageList$1 = class MessageList {
12921
13044
  threadId,
12922
13045
  resourceId,
12923
13046
  generateMessageId,
12924
- // @ts-ignore Flag for agent network messages
13047
+ // @ts-expect-error Flag for agent network messages
12925
13048
  _agentNetworkAppend
12926
13049
  } = {}) {
12927
13050
  if (threadId) {
@@ -12977,6 +13100,31 @@ var MessageList$1 = class MessageList {
12977
13100
  agentNetworkAppend: this._agentNetworkAppend
12978
13101
  });
12979
13102
  }
13103
+ /**
13104
+ * Custom serialization for tracing/observability spans.
13105
+ * Returns a clean representation with just the essential data,
13106
+ * excluding internal state tracking, methods, and implementation details.
13107
+ *
13108
+ * This is automatically called by the span serialization system when
13109
+ * a MessageList instance appears in span input/output/attributes.
13110
+ */
13111
+ serializeForSpan() {
13112
+ const coreMessages = this.all.aiV4.core();
13113
+ return {
13114
+ messages: coreMessages.map((msg) => ({
13115
+ role: msg.role,
13116
+ content: msg.content
13117
+ })),
13118
+ systemMessages: [
13119
+ // Untagged first (base instructions)
13120
+ ...this.systemMessages.map((m) => ({ role: m.role, content: m.content })),
13121
+ // Tagged after (contextual additions)
13122
+ ...Object.entries(this.taggedSystemMessages).flatMap(
13123
+ ([tag, msgs]) => msgs.map((m) => ({ role: m.role, content: m.content, tag }))
13124
+ )
13125
+ ]
13126
+ };
13127
+ }
12980
13128
  deserialize(state) {
12981
13129
  const data = this.stateManager.deserializeAll(state);
12982
13130
  this.messages = data.messages;
@@ -13513,10 +13661,6 @@ var MessageList$1 = class MessageList {
13513
13661
  }
13514
13662
  };
13515
13663
 
13516
- function getDefaultExportFromCjs (x) {
13517
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
13518
- }
13519
-
13520
13664
  new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
13521
13665
 
13522
13666
  // ../_vendored/ai_v4/dist/chunk-OPIPXJLE.js
@@ -13546,7 +13690,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
13546
13690
  mod
13547
13691
  ));
13548
13692
  var require_secure_json_parse = __commonJS({
13549
- "../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports, module) {
13693
+ "../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports$1, module) {
13550
13694
  var hasBuffer = typeof Buffer !== "undefined";
13551
13695
  var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
13552
13696
  var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
@@ -18972,7 +19116,7 @@ class LRUCache {
18972
19116
 
18973
19117
  // ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js
18974
19118
  var require_fast_deep_equal = __commonJS$3({
18975
- "../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) {
19119
+ "../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports$1, module) {
18976
19120
  module.exports = function equal(a, b) {
18977
19121
  if (a === b) return true;
18978
19122
  if (a && b && typeof a == "object" && typeof b == "object") {
@@ -20624,5 +20768,427 @@ const MessageStreaming = ({ className, ...props }) => {
20624
20768
  return /* @__PURE__ */ jsx("span", { className: className || MessageStreamingClass, ...props });
20625
20769
  };
20626
20770
 
20627
- export { MessageUsages as $, EntryTitleClass as A, EntryTitle as B, CodeBlockClass as C, CodeBlock as D, Entity as E, CodeCopyButton as F, Icon as G, IconButtonClass as H, IconSizes as I, IconButton as J, AgentIcon as K, ToolsIcon as L, MastraReactProvider as M, Tooltip as N, TooltipContentClass as O, TooltipContent as P, TooltipTrigger as Q, MessageClass as R, Message as S, ToolApprovalClass as T, MessageContentClass as U, MessageContent as V, WorkflowIcon as W, MessageActionsClass as X, MessageActions as Y, MessageUsagesClass as Z, __commonJS$2 as _, __require2 as a, MessageUsageClass as a0, MessageUsage as a1, MessageUsageEntryClass as a2, MessageUsageEntry as a3, MessageUsageValueClass as a4, MessageUsageValue as a5, MessageListClass as a6, MessageList as a7, MessageStreamingClass as a8, MessageStreaming as a9, useChat as b, resolveToChildMessages as c, toAssistantUIMessage as d, useEntity as e, EntityTriggerClass as f, EntityTriggerVariantClasses as g, EntityTrigger as h, EntityContentClass as i, EntityContent as j, EntityCaret as k, ToolApproval as l, mapWorkflowStreamChunkToWatchResult as m, ToolApprovalTitleClass as n, ToolApprovalTitle as o, ToolApprovalHeaderClass as p, ToolApprovalHeader as q, require_token_error as r, ToolApprovalContentClass as s, toUIMessage as t, useMastraClient as u, ToolApprovalContent as v, ToolApprovalActionsClass as w, ToolApprovalActions as x, EntryClass as y, Entry as z };
20628
- //# sourceMappingURL=index-D3JtF_Zl.js.map
20771
+ function useMutation(mutationFn) {
20772
+ const [isPending, setIsPending] = useState(false);
20773
+ const [isSuccess, setIsSuccess] = useState(false);
20774
+ const [isError, setIsError] = useState(false);
20775
+ const [error, setError] = useState(null);
20776
+ const [data, setData] = useState(void 0);
20777
+ const mutationFnRef = useRef(mutationFn);
20778
+ mutationFnRef.current = mutationFn;
20779
+ const reset = useCallback(() => {
20780
+ setIsPending(false);
20781
+ setIsSuccess(false);
20782
+ setIsError(false);
20783
+ setError(null);
20784
+ setData(void 0);
20785
+ }, []);
20786
+ const mutateAsync = useCallback(async (variables) => {
20787
+ setIsPending(true);
20788
+ setIsSuccess(false);
20789
+ setIsError(false);
20790
+ setError(null);
20791
+ try {
20792
+ const result = await mutationFnRef.current(variables);
20793
+ setData(result);
20794
+ setIsSuccess(true);
20795
+ return result;
20796
+ } catch (err) {
20797
+ const typedError = err;
20798
+ setError(typedError);
20799
+ setIsError(true);
20800
+ throw err;
20801
+ } finally {
20802
+ setIsPending(false);
20803
+ }
20804
+ }, []);
20805
+ const mutate = useCallback(
20806
+ (variables) => {
20807
+ mutateAsync(variables).catch(() => {
20808
+ });
20809
+ },
20810
+ [mutateAsync]
20811
+ );
20812
+ return {
20813
+ mutate,
20814
+ mutateAsync,
20815
+ isPending,
20816
+ isSuccess,
20817
+ isError,
20818
+ error,
20819
+ data,
20820
+ reset
20821
+ };
20822
+ }
20823
+
20824
+ function useStreamWorkflow({ debugMode, tracingOptions, onError }) {
20825
+ const client = useMastraClient();
20826
+ const [streamResult, setStreamResult] = useState({});
20827
+ const [isStreaming, setIsStreaming] = useState(false);
20828
+ const readerRef = useRef(null);
20829
+ const observerRef = useRef(null);
20830
+ const resumeStreamRef = useRef(null);
20831
+ const timeTravelStreamRef = useRef(null);
20832
+ const isMountedRef = useRef(true);
20833
+ useEffect(() => {
20834
+ isMountedRef.current = true;
20835
+ return () => {
20836
+ isMountedRef.current = false;
20837
+ if (readerRef.current) {
20838
+ try {
20839
+ readerRef.current.releaseLock();
20840
+ } catch (error) {
20841
+ }
20842
+ readerRef.current = null;
20843
+ }
20844
+ if (observerRef.current) {
20845
+ try {
20846
+ observerRef.current.releaseLock();
20847
+ } catch (error) {
20848
+ }
20849
+ observerRef.current = null;
20850
+ }
20851
+ if (resumeStreamRef.current) {
20852
+ try {
20853
+ resumeStreamRef.current.releaseLock();
20854
+ } catch (error) {
20855
+ }
20856
+ resumeStreamRef.current = null;
20857
+ }
20858
+ if (timeTravelStreamRef.current) {
20859
+ try {
20860
+ timeTravelStreamRef.current.releaseLock();
20861
+ } catch (error) {
20862
+ }
20863
+ timeTravelStreamRef.current = null;
20864
+ }
20865
+ };
20866
+ }, []);
20867
+ const handleStreamError = useCallback(
20868
+ (err, defaultMessage, setStreamingState) => {
20869
+ if (err instanceof TypeError) {
20870
+ return;
20871
+ }
20872
+ const error = err instanceof Error ? err : new Error(defaultMessage);
20873
+ onError?.(error, defaultMessage);
20874
+ setStreamingState?.(false);
20875
+ },
20876
+ [onError]
20877
+ );
20878
+ const handleWorkflowFinish = useCallback((value) => {
20879
+ if (value.type === "workflow-finish") {
20880
+ const streamStatus = value.payload?.workflowStatus;
20881
+ const metadata = value.payload?.metadata;
20882
+ setStreamResult((prev) => ({
20883
+ ...prev,
20884
+ status: streamStatus
20885
+ }));
20886
+ if (streamStatus === "failed") {
20887
+ throw new Error(metadata?.errorMessage || "Workflow execution failed");
20888
+ }
20889
+ }
20890
+ }, []);
20891
+ const streamWorkflow = useMutation(
20892
+ async ({ workflowId, runId, inputData, initialState, requestContext: playgroundRequestContext, perStep }) => {
20893
+ if (readerRef.current) {
20894
+ readerRef.current.releaseLock();
20895
+ }
20896
+ if (!isMountedRef.current) return;
20897
+ setIsStreaming(true);
20898
+ setStreamResult({ input: inputData });
20899
+ const requestContext = new RequestContext();
20900
+ Object.entries(playgroundRequestContext).forEach(([key, value]) => {
20901
+ requestContext.set(key, value);
20902
+ });
20903
+ const workflow = client.getWorkflow(workflowId);
20904
+ const run = await workflow.createRun({ runId });
20905
+ const stream = await run.stream({
20906
+ inputData,
20907
+ initialState,
20908
+ requestContext,
20909
+ closeOnSuspend: true,
20910
+ tracingOptions,
20911
+ perStep: perStep ?? debugMode
20912
+ });
20913
+ if (!stream) {
20914
+ return handleStreamError(new Error("No stream returned"), "No stream returned", setIsStreaming);
20915
+ }
20916
+ const reader = stream.getReader();
20917
+ readerRef.current = reader;
20918
+ try {
20919
+ while (true) {
20920
+ if (!isMountedRef.current) break;
20921
+ const { done, value } = await reader.read();
20922
+ if (done) break;
20923
+ if (isMountedRef.current) {
20924
+ setStreamResult((prev) => {
20925
+ const newResult = mapWorkflowStreamChunkToWatchResult(prev, value);
20926
+ return newResult;
20927
+ });
20928
+ if (value.type === "workflow-step-start") {
20929
+ setIsStreaming(true);
20930
+ }
20931
+ if (value.type === "workflow-step-suspended") {
20932
+ setIsStreaming(false);
20933
+ }
20934
+ if (value.type === "workflow-finish") {
20935
+ handleWorkflowFinish(value);
20936
+ }
20937
+ }
20938
+ }
20939
+ } catch (err) {
20940
+ handleStreamError(err, "Error streaming workflow");
20941
+ } finally {
20942
+ if (isMountedRef.current) {
20943
+ setIsStreaming(false);
20944
+ }
20945
+ if (readerRef.current) {
20946
+ readerRef.current.releaseLock();
20947
+ readerRef.current = null;
20948
+ }
20949
+ }
20950
+ }
20951
+ );
20952
+ const observeWorkflowStream = useMutation(
20953
+ async ({ workflowId, runId, storeRunResult }) => {
20954
+ if (observerRef.current) {
20955
+ observerRef.current.releaseLock();
20956
+ }
20957
+ if (!isMountedRef.current) return;
20958
+ setIsStreaming(true);
20959
+ setStreamResult(storeRunResult || {});
20960
+ if (storeRunResult?.status === "suspended") {
20961
+ setIsStreaming(false);
20962
+ return;
20963
+ }
20964
+ const workflow = client.getWorkflow(workflowId);
20965
+ const run = await workflow.createRun({ runId });
20966
+ const stream = await run.observeStream();
20967
+ if (!stream) {
20968
+ return handleStreamError(new Error("No stream returned"), "No stream returned", setIsStreaming);
20969
+ }
20970
+ const reader = stream.getReader();
20971
+ observerRef.current = reader;
20972
+ try {
20973
+ while (true) {
20974
+ if (!isMountedRef.current) break;
20975
+ const { done, value } = await reader.read();
20976
+ if (done) break;
20977
+ if (isMountedRef.current) {
20978
+ setStreamResult((prev) => {
20979
+ const newResult = mapWorkflowStreamChunkToWatchResult(prev, value);
20980
+ return newResult;
20981
+ });
20982
+ if (value.type === "workflow-step-start") {
20983
+ setIsStreaming(true);
20984
+ }
20985
+ if (value.type === "workflow-step-suspended") {
20986
+ setIsStreaming(false);
20987
+ }
20988
+ if (value.type === "workflow-finish") {
20989
+ handleWorkflowFinish(value);
20990
+ }
20991
+ }
20992
+ }
20993
+ } catch (err) {
20994
+ handleStreamError(err, "Error observing workflow");
20995
+ } finally {
20996
+ if (isMountedRef.current) {
20997
+ setIsStreaming(false);
20998
+ }
20999
+ if (observerRef.current) {
21000
+ observerRef.current.releaseLock();
21001
+ observerRef.current = null;
21002
+ }
21003
+ }
21004
+ }
21005
+ );
21006
+ const resumeWorkflowStream = useMutation(
21007
+ async ({ workflowId, runId, step, resumeData, requestContext: playgroundRequestContext, perStep }) => {
21008
+ if (resumeStreamRef.current) {
21009
+ resumeStreamRef.current.releaseLock();
21010
+ }
21011
+ if (!isMountedRef.current) return;
21012
+ setIsStreaming(true);
21013
+ const workflow = client.getWorkflow(workflowId);
21014
+ const requestContext = new RequestContext();
21015
+ Object.entries(playgroundRequestContext).forEach(([key, value]) => {
21016
+ requestContext.set(key, value);
21017
+ });
21018
+ const run = await workflow.createRun({ runId });
21019
+ const stream = await run.resumeStream({
21020
+ step,
21021
+ resumeData,
21022
+ requestContext,
21023
+ tracingOptions,
21024
+ perStep: perStep ?? debugMode
21025
+ });
21026
+ if (!stream) {
21027
+ return handleStreamError(new Error("No stream returned"), "No stream returned", setIsStreaming);
21028
+ }
21029
+ const reader = stream.getReader();
21030
+ resumeStreamRef.current = reader;
21031
+ try {
21032
+ while (true) {
21033
+ if (!isMountedRef.current) break;
21034
+ const { done, value } = await reader.read();
21035
+ if (done) break;
21036
+ if (isMountedRef.current) {
21037
+ setStreamResult((prev) => {
21038
+ const newResult = mapWorkflowStreamChunkToWatchResult(prev, value);
21039
+ return newResult;
21040
+ });
21041
+ if (value.type === "workflow-step-start") {
21042
+ setIsStreaming(true);
21043
+ }
21044
+ if (value.type === "workflow-step-suspended") {
21045
+ setIsStreaming(false);
21046
+ }
21047
+ if (value.type === "workflow-finish") {
21048
+ handleWorkflowFinish(value);
21049
+ }
21050
+ }
21051
+ }
21052
+ } catch (err) {
21053
+ handleStreamError(err, "Error resuming workflow stream");
21054
+ } finally {
21055
+ if (isMountedRef.current) {
21056
+ setIsStreaming(false);
21057
+ }
21058
+ if (resumeStreamRef.current) {
21059
+ resumeStreamRef.current.releaseLock();
21060
+ resumeStreamRef.current = null;
21061
+ }
21062
+ }
21063
+ }
21064
+ );
21065
+ const timeTravelWorkflowStream = useMutation(
21066
+ async ({ workflowId, requestContext: playgroundRequestContext, runId, perStep, ...params }) => {
21067
+ if (timeTravelStreamRef.current) {
21068
+ timeTravelStreamRef.current.releaseLock();
21069
+ }
21070
+ if (!isMountedRef.current) return;
21071
+ setIsStreaming(true);
21072
+ const workflow = client.getWorkflow(workflowId);
21073
+ const requestContext = new RequestContext();
21074
+ Object.entries(playgroundRequestContext).forEach(([key, value]) => {
21075
+ requestContext.set(key, value);
21076
+ });
21077
+ const run = await workflow.createRun({ runId });
21078
+ const stream = await run.timeTravelStream({
21079
+ ...params,
21080
+ perStep: perStep ?? debugMode,
21081
+ requestContext,
21082
+ tracingOptions
21083
+ });
21084
+ if (!stream) {
21085
+ return handleStreamError(new Error("No stream returned"), "No stream returned", setIsStreaming);
21086
+ }
21087
+ const reader = stream.getReader();
21088
+ timeTravelStreamRef.current = reader;
21089
+ try {
21090
+ while (true) {
21091
+ if (!isMountedRef.current) break;
21092
+ const { done, value } = await reader.read();
21093
+ if (done) break;
21094
+ if (isMountedRef.current) {
21095
+ setStreamResult((prev) => {
21096
+ const newResult = mapWorkflowStreamChunkToWatchResult(prev, value);
21097
+ return newResult;
21098
+ });
21099
+ if (value.type === "workflow-step-start") {
21100
+ setIsStreaming(true);
21101
+ }
21102
+ if (value.type === "workflow-step-suspended") {
21103
+ setIsStreaming(false);
21104
+ }
21105
+ if (value.type === "workflow-finish") {
21106
+ handleWorkflowFinish(value);
21107
+ }
21108
+ }
21109
+ }
21110
+ } catch (err) {
21111
+ handleStreamError(err, "Error time traveling workflow stream");
21112
+ } finally {
21113
+ if (isMountedRef.current) {
21114
+ setIsStreaming(false);
21115
+ }
21116
+ if (timeTravelStreamRef.current) {
21117
+ timeTravelStreamRef.current.releaseLock();
21118
+ timeTravelStreamRef.current = null;
21119
+ }
21120
+ }
21121
+ }
21122
+ );
21123
+ const closeStreamsAndReset = useCallback(() => {
21124
+ setIsStreaming(false);
21125
+ setStreamResult({});
21126
+ if (readerRef.current) {
21127
+ try {
21128
+ readerRef.current.releaseLock();
21129
+ } catch (error) {
21130
+ }
21131
+ readerRef.current = null;
21132
+ }
21133
+ if (observerRef.current) {
21134
+ try {
21135
+ observerRef.current.releaseLock();
21136
+ } catch (error) {
21137
+ }
21138
+ observerRef.current = null;
21139
+ }
21140
+ if (resumeStreamRef.current) {
21141
+ try {
21142
+ resumeStreamRef.current.releaseLock();
21143
+ } catch (error) {
21144
+ }
21145
+ resumeStreamRef.current = null;
21146
+ }
21147
+ if (timeTravelStreamRef.current) {
21148
+ try {
21149
+ timeTravelStreamRef.current.releaseLock();
21150
+ } catch (error) {
21151
+ }
21152
+ timeTravelStreamRef.current = null;
21153
+ }
21154
+ }, []);
21155
+ return {
21156
+ streamWorkflow,
21157
+ streamResult,
21158
+ isStreaming,
21159
+ observeWorkflowStream,
21160
+ closeStreamsAndReset,
21161
+ resumeWorkflowStream,
21162
+ timeTravelWorkflowStream
21163
+ };
21164
+ }
21165
+
21166
+ function useCreateWorkflowRun() {
21167
+ const client = useMastraClient();
21168
+ return useMutation(async ({ workflowId, prevRunId }) => {
21169
+ try {
21170
+ const workflow = client.getWorkflow(workflowId);
21171
+ const { runId: newRunId } = await workflow.createRun({ runId: prevRunId });
21172
+ return { runId: newRunId };
21173
+ } catch (error) {
21174
+ console.error("Error creating workflow run:", error);
21175
+ throw error;
21176
+ }
21177
+ });
21178
+ }
21179
+ function useCancelWorkflowRun() {
21180
+ const client = useMastraClient();
21181
+ return useMutation(async ({ workflowId, runId }) => {
21182
+ try {
21183
+ const workflow = client.getWorkflow(workflowId);
21184
+ const run = await workflow.createRun({ runId });
21185
+ return run.cancelRun();
21186
+ } catch (error) {
21187
+ console.error("Error canceling workflow run:", error);
21188
+ throw error;
21189
+ }
21190
+ });
21191
+ }
21192
+
21193
+ export { MessageUsages as $, EntryTitleClass as A, EntryTitle as B, CodeBlockClass as C, CodeBlock as D, Entity as E, CodeCopyButton as F, Icon as G, IconButtonClass as H, IconSizes as I, IconButton as J, AgentIcon as K, ToolsIcon as L, MastraReactProvider as M, Tooltip as N, TooltipContentClass as O, TooltipContent as P, TooltipTrigger as Q, MessageClass as R, Message as S, ToolApprovalClass as T, MessageContentClass as U, MessageContent as V, WorkflowIcon as W, MessageActionsClass as X, MessageActions as Y, MessageUsagesClass as Z, __commonJS$2 as _, __require2 as a, MessageUsageClass as a0, MessageUsage as a1, MessageUsageEntryClass as a2, MessageUsageEntry as a3, MessageUsageValueClass as a4, MessageUsageValue as a5, MessageListClass as a6, MessageList as a7, MessageStreamingClass as a8, MessageStreaming as a9, useCreateWorkflowRun as aa, useCancelWorkflowRun as ab, useStreamWorkflow as ac, useChat as b, resolveToChildMessages as c, toAssistantUIMessage as d, useEntity as e, EntityTriggerClass as f, EntityTriggerVariantClasses as g, EntityTrigger as h, EntityContentClass as i, EntityContent as j, EntityCaret as k, ToolApproval as l, mapWorkflowStreamChunkToWatchResult as m, ToolApprovalTitleClass as n, ToolApprovalTitle as o, ToolApprovalHeaderClass as p, ToolApprovalHeader as q, require_token_error as r, ToolApprovalContentClass as s, toUIMessage as t, useMastraClient as u, ToolApprovalContent as v, ToolApprovalActionsClass as w, ToolApprovalActions as x, EntryClass as y, Entry as z };
21194
+ //# sourceMappingURL=index-BrMELKWu.js.map