@mastra/client-js 1.37.0 → 1.37.1-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.
package/dist/index.js CHANGED
@@ -1854,18 +1854,28 @@ var Agent = class extends BaseResource {
1854
1854
  let messages = [];
1855
1855
  let streamRunId = processedParams.runId;
1856
1856
  const [streamForController, streamForProcessing] = response.body.tee();
1857
- const pipePromise = streamForController.pipeTo(new WritableStream({ async write(chunk) {
1858
- try {
1859
- const readableLines = new TextDecoder().decode(chunk).split("\n\n").filter((line) => line.trim() !== "[DONE]" && line.trim() !== "data: [DONE]").join("\n\n");
1860
- if (readableLines) {
1861
- const encoded = new TextEncoder().encode(readableLines);
1862
- controller.enqueue(encoded);
1857
+ const decoder = new TextDecoder();
1858
+ let pendingText = "";
1859
+ const enqueueReadableText = (text, isFinal = false) => {
1860
+ pendingText += text;
1861
+ const lines = pendingText.split("\n\n");
1862
+ pendingText = isFinal ? "" : lines.pop() ?? "";
1863
+ const readableLines = lines.filter((line) => line.trim() !== "[DONE]" && line.trim() !== "data: [DONE]").join("\n\n");
1864
+ if (readableLines) controller.enqueue(new TextEncoder().encode(`${readableLines}\n\n`));
1865
+ };
1866
+ const pipePromise = streamForController.pipeTo(new WritableStream({
1867
+ async write(chunk) {
1868
+ try {
1869
+ enqueueReadableText(decoder.decode(chunk, { stream: true }));
1870
+ } catch (error) {
1871
+ console.error("Error enqueueing to controller:", error);
1872
+ controller.enqueue(chunk);
1863
1873
  }
1864
- } catch (error) {
1865
- console.error("Error enqueueing to controller:", error);
1866
- controller.enqueue(chunk);
1874
+ },
1875
+ close() {
1876
+ enqueueReadableText(decoder.decode(), true);
1867
1877
  }
1868
- } })).catch((error) => {
1878
+ })).catch((error) => {
1869
1879
  console.error("Error piping to controller:", error);
1870
1880
  try {
1871
1881
  controller.close();
@@ -2906,6 +2916,75 @@ var Conversations = class extends BaseResource {
2906
2916
  }
2907
2917
  };
2908
2918
  //#endregion
2919
+ //#region src/utils/stream-transforms.ts
2920
+ const RECORD_SEPARATOR$1 = "";
2921
+ const SSE_FRAME_SEPARATOR = /\r?\n\r?\n/;
2922
+ /**
2923
+ * Parses UTF-8 JSON values delimited by the record separator character.
2924
+ */
2925
+ function createRecordSeparatorJsonTransform() {
2926
+ const decoder = new TextDecoder();
2927
+ let buffer = "";
2928
+ const processCompleteRecords = (controller) => {
2929
+ let separatorIndex = buffer.indexOf(RECORD_SEPARATOR$1);
2930
+ while (separatorIndex !== -1) {
2931
+ const record = buffer.slice(0, separatorIndex);
2932
+ buffer = buffer.slice(separatorIndex + 1);
2933
+ if (record) controller.enqueue(JSON.parse(record));
2934
+ separatorIndex = buffer.indexOf(RECORD_SEPARATOR$1);
2935
+ }
2936
+ };
2937
+ return new TransformStream({
2938
+ transform(chunk, controller) {
2939
+ buffer += decoder.decode(chunk, { stream: true });
2940
+ processCompleteRecords(controller);
2941
+ },
2942
+ flush(controller) {
2943
+ buffer += decoder.decode();
2944
+ processCompleteRecords(controller);
2945
+ if (buffer) controller.enqueue(JSON.parse(buffer));
2946
+ }
2947
+ });
2948
+ }
2949
+ /**
2950
+ * Parses UTF-8 JSON payloads from blank-line-delimited Server-Sent Events.
2951
+ */
2952
+ function createSseJsonTransform() {
2953
+ const decoder = new TextDecoder();
2954
+ let buffer = "";
2955
+ const parseFrame = (frame, controller) => {
2956
+ const dataLines = [];
2957
+ for (const line of frame.split(/\r?\n/)) {
2958
+ if (line.startsWith(":") || !line.startsWith("data:")) continue;
2959
+ const value = line.slice(5);
2960
+ dataLines.push(value.startsWith(" ") ? value.slice(1) : value);
2961
+ }
2962
+ if (dataLines.length === 0) return;
2963
+ const payload = dataLines.join("\n");
2964
+ if (payload === "[DONE]") return;
2965
+ controller.enqueue(JSON.parse(payload));
2966
+ };
2967
+ const processCompleteFrames = (controller) => {
2968
+ let separatorMatch = SSE_FRAME_SEPARATOR.exec(buffer);
2969
+ while (separatorMatch) {
2970
+ parseFrame(buffer.slice(0, separatorMatch.index), controller);
2971
+ buffer = buffer.slice(separatorMatch.index + separatorMatch[0].length);
2972
+ separatorMatch = SSE_FRAME_SEPARATOR.exec(buffer);
2973
+ }
2974
+ };
2975
+ return new TransformStream({
2976
+ transform(chunk, controller) {
2977
+ buffer += decoder.decode(chunk, { stream: true });
2978
+ processCompleteFrames(controller);
2979
+ },
2980
+ flush(controller) {
2981
+ buffer += decoder.decode();
2982
+ processCompleteFrames(controller);
2983
+ if (buffer) parseFrame(buffer, controller);
2984
+ }
2985
+ });
2986
+ }
2987
+ //#endregion
2909
2988
  //#region src/resources/run.ts
2910
2989
  /**
2911
2990
  * Deserializes the error property in a workflow result back to an Error instance.
@@ -2918,7 +2997,6 @@ function deserializeWorkflowError(result) {
2918
2997
  });
2919
2998
  return result;
2920
2999
  }
2921
- const RECORD_SEPARATOR$2 = "";
2922
3000
  var Run = class extends BaseResource {
2923
3001
  workflowId;
2924
3002
  runId;
@@ -2927,29 +3005,8 @@ var Run = class extends BaseResource {
2927
3005
  this.workflowId = workflowId;
2928
3006
  this.runId = runId;
2929
3007
  }
2930
- /**
2931
- * Creates a transform stream that parses RECORD_SEPARATOR-delimited JSON chunks
2932
- */
2933
3008
  createChunkTransformStream() {
2934
- let failedChunk = void 0;
2935
- return new TransformStream({
2936
- start() {},
2937
- async transform(chunk, controller) {
2938
- try {
2939
- const chunks = new TextDecoder().decode(chunk).split(RECORD_SEPARATOR$2);
2940
- for (const chunk of chunks) if (chunk) {
2941
- const newChunk = failedChunk ? failedChunk + chunk : chunk;
2942
- try {
2943
- const parsedChunk = JSON.parse(newChunk);
2944
- controller.enqueue(parsedChunk);
2945
- failedChunk = void 0;
2946
- } catch {
2947
- failedChunk = newChunk;
2948
- }
2949
- }
2950
- } catch {}
2951
- }
2952
- });
3009
+ return createRecordSeparatorJsonTransform();
2953
3010
  }
2954
3011
  /**
2955
3012
  * Cancels a specific workflow run by its ID
@@ -3299,7 +3356,7 @@ var Run = class extends BaseResource {
3299
3356
  };
3300
3357
  //#endregion
3301
3358
  //#region src/resources/workflow.ts
3302
- const RECORD_SEPARATOR$1 = "";
3359
+ const RECORD_SEPARATOR = "";
3303
3360
  var Workflow = class extends BaseResource {
3304
3361
  workflowId;
3305
3362
  constructor(options, workflowId) {
@@ -3404,7 +3461,7 @@ var Workflow = class extends BaseResource {
3404
3461
  return new ReadableStream({ async start(controller) {
3405
3462
  try {
3406
3463
  for await (const record of records) {
3407
- const json = JSON.stringify(record) + RECORD_SEPARATOR$1;
3464
+ const json = JSON.stringify(record) + RECORD_SEPARATOR;
3408
3465
  controller.enqueue(encoder.encode(json));
3409
3466
  }
3410
3467
  controller.close();
@@ -3807,7 +3864,6 @@ var MCPTool = class extends BaseResource {
3807
3864
  };
3808
3865
  //#endregion
3809
3866
  //#region src/resources/agent-builder.ts
3810
- const RECORD_SEPARATOR = "";
3811
3867
  /**
3812
3868
  * Agent Builder resource: operations related to agent-builder workflows via server endpoints.
3813
3869
  */
@@ -3841,29 +3897,8 @@ var AgentBuilder = class extends BaseResource {
3841
3897
  error: "Workflow suspended - manual intervention required"
3842
3898
  };
3843
3899
  }
3844
- /**
3845
- * Creates a transform stream that parses binary chunks into JSON records.
3846
- */
3847
3900
  createRecordParserTransform() {
3848
- let failedChunk = void 0;
3849
- return new TransformStream({
3850
- start() {},
3851
- async transform(chunk, controller) {
3852
- try {
3853
- const chunks = new TextDecoder().decode(chunk).split(RECORD_SEPARATOR);
3854
- for (const chunk of chunks) if (chunk) {
3855
- const newChunk = failedChunk ? failedChunk + chunk : chunk;
3856
- try {
3857
- const parsedChunk = JSON.parse(newChunk);
3858
- controller.enqueue(parsedChunk);
3859
- failedChunk = void 0;
3860
- } catch {
3861
- failedChunk = newChunk;
3862
- }
3863
- }
3864
- } catch {}
3865
- }
3866
- });
3901
+ return createRecordSeparatorJsonTransform();
3867
3902
  }
3868
3903
  /**
3869
3904
  * Creates a new agent builder action run and returns the runId.
@@ -3950,40 +3985,6 @@ var AgentBuilder = class extends BaseResource {
3950
3985
  return this.transformWorkflowResult(result);
3951
3986
  }
3952
3987
  /**
3953
- * Creates an async generator that processes a readable stream and yields action records
3954
- * separated by the Record Separator character (\x1E)
3955
- *
3956
- * @param stream - The readable stream to process
3957
- * @returns An async generator that yields parsed records
3958
- */
3959
- async *streamProcessor(stream) {
3960
- const reader = stream.getReader();
3961
- let doneReading = false;
3962
- let buffer = "";
3963
- try {
3964
- while (!doneReading) {
3965
- const { done, value } = await reader.read();
3966
- doneReading = done;
3967
- if (done && !value) continue;
3968
- try {
3969
- const decoded = value ? new TextDecoder().decode(value) : "";
3970
- const chunks = (buffer + decoded).split(RECORD_SEPARATOR);
3971
- buffer = chunks.pop() || "";
3972
- for (const chunk of chunks) if (chunk) {
3973
- if (typeof chunk === "string") try {
3974
- yield JSON.parse(chunk);
3975
- } catch {}
3976
- }
3977
- } catch {}
3978
- }
3979
- if (buffer) try {
3980
- yield JSON.parse(buffer);
3981
- } catch {}
3982
- } finally {
3983
- reader.cancel().catch(() => {});
3984
- }
3985
- }
3986
- /**
3987
3988
  * Streams agent builder action progress in real-time.
3988
3989
  * This calls `/agent-builder/:actionId/stream`.
3989
3990
  */
@@ -7364,23 +7365,7 @@ var MastraClient = class extends BaseResource {
7364
7365
  const response = await this.request(`/background-tasks/stream${qs ? `?${qs}` : ""}`, { stream: true });
7365
7366
  if (!response.ok) throw new Error(`Failed to stream background tasks: ${response.statusText}`);
7366
7367
  if (!response.body) throw new Error("Response body is null");
7367
- let failedChunk = void 0;
7368
- return response.body.pipeThrough(new TransformStream({ async transform(chunk, controller) {
7369
- try {
7370
- const chunks = new TextDecoder().decode(chunk).split("\n\n");
7371
- for (const chunk of chunks) if (chunk) {
7372
- const cleanChunk = chunk.substring(6);
7373
- const newChunk = failedChunk ? failedChunk + cleanChunk : cleanChunk;
7374
- try {
7375
- const parsedChunk = JSON.parse(newChunk);
7376
- controller.enqueue(parsedChunk);
7377
- failedChunk = void 0;
7378
- } catch {
7379
- failedChunk = newChunk;
7380
- }
7381
- }
7382
- } catch {}
7383
- } }));
7368
+ return response.body.pipeThrough(createSseJsonTransform());
7384
7369
  }
7385
7370
  /**
7386
7371
  * Lists schedules — agent schedules and workflow schedules — with optional