@mastra/client-js 1.56.0-alpha.1 → 1.56.0-alpha.10

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 (48) hide show
  1. package/dist/client.d.ts +3 -3
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/docs/SKILL.md +2 -2
  4. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  5. package/dist/docs/references/docs-harness-agent-controller.md +11 -14
  6. package/dist/docs/references/docs-harness-schedules.md +8 -6
  7. package/dist/docs/references/docs-harness-signals.md +3 -1
  8. package/dist/docs/references/reference-client-js-agent-controller.md +15 -3
  9. package/dist/docs/references/reference-client-js-agents.md +20 -0
  10. package/dist/docs/references/reference-client-js-mastra-client.md +1 -1
  11. package/dist/docs/references/reference-client-js-observability.md +124 -9
  12. package/dist/docs/references/{reference-observability-tracing-trace-query.md → reference-observability-tracing-advanced-queries.md} +486 -158
  13. package/dist/index.cjs +780 -86
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.js +774 -80
  16. package/dist/index.js.map +1 -1
  17. package/dist/resources/agent-controller.d.ts +36 -26
  18. package/dist/resources/agent-controller.d.ts.map +1 -1
  19. package/dist/resources/agent.d.ts +46 -6
  20. package/dist/resources/agent.d.ts.map +1 -1
  21. package/dist/resources/base.d.ts.map +1 -1
  22. package/dist/resources/observability.d.ts +9 -7
  23. package/dist/resources/observability.d.ts.map +1 -1
  24. package/dist/route-types.generated.d.ts +711 -596
  25. package/dist/route-types.generated.d.ts.map +1 -1
  26. package/dist/types.d.ts +9 -9
  27. package/dist/types.d.ts.map +1 -1
  28. package/dist/utils/ai-sdk-v4/data-stream-parts.d.ts +89 -0
  29. package/dist/utils/ai-sdk-v4/data-stream-parts.d.ts.map +1 -0
  30. package/dist/utils/ai-sdk-v4/fix-json.d.ts +2 -0
  31. package/dist/utils/ai-sdk-v4/fix-json.d.ts.map +1 -0
  32. package/dist/utils/ai-sdk-v4/index.d.ts +5 -0
  33. package/dist/utils/ai-sdk-v4/index.d.ts.map +1 -0
  34. package/dist/utils/ai-sdk-v4/parse-partial-json.d.ts +6 -0
  35. package/dist/utils/ai-sdk-v4/parse-partial-json.d.ts.map +1 -0
  36. package/dist/utils/ai-sdk-v4/process-data-stream.d.ts +53 -0
  37. package/dist/utils/ai-sdk-v4/process-data-stream.d.ts.map +1 -0
  38. package/dist/utils/ai-sdk-v4/types.d.ts +93 -0
  39. package/dist/utils/ai-sdk-v4/types.d.ts.map +1 -0
  40. package/dist/utils/index.d.ts +7 -0
  41. package/dist/utils/index.d.ts.map +1 -1
  42. package/package.json +8 -10
  43. package/dist/_types/@ai-sdk_provider/dist/index.d.ts +0 -1587
  44. package/dist/_types/@ai-sdk_provider/package.json +0 -1
  45. package/dist/_types/@ai-sdk_provider-utils/dist/index.d.ts +0 -379
  46. package/dist/_types/@ai-sdk_provider-utils/package.json +0 -1
  47. package/dist/_types/@ai-sdk_ui-utils/dist/index.d.ts +0 -820
  48. package/dist/_types/@ai-sdk_ui-utils/package.json +0 -1
package/dist/index.cjs CHANGED
@@ -21,11 +21,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
21
  enumerable: true
22
22
  }) : target, mod));
23
23
  //#endregion
24
- let _ai_sdk_ui_utils = require("@ai-sdk/ui-utils");
25
24
  let _lukeed_uuid = require("@lukeed/uuid");
26
25
  let _mastra_core_error = require("@mastra/core/error");
27
- let _mastra_schema_compat_schema = require("@mastra/schema-compat/schema");
28
26
  let _mastra_core_request_context = require("@mastra/core/request-context");
27
+ let _mastra_schema_compat_schema = require("@mastra/schema-compat/schema");
29
28
  let _mastra_schema_compat_zod_to_json = require("@mastra/schema-compat/zod-to-json");
30
29
  let _mastra_core_a2a_client = require("@mastra/core/a2a/client");
31
30
  let _mastra_core_a2a_v1 = require("@mastra/core/a2a/v1");
@@ -401,6 +400,16 @@ function isTerminalHttpError(error) {
401
400
  return typeof status === "number" && (status >= 400 && status < 500 || status === 501);
402
401
  }
403
402
  /**
403
+ * Whether an error is the server's trace query execution timeout (504 with code
404
+ * `TRACE_QUERY_EXECUTION_TIMEOUT`). Re-sending the same query hits the same
405
+ * timeout budget, so retrying only repeats an expensive database query.
406
+ * Plain 504s from proxies or gateways do not carry this code and stay retryable.
407
+ */
408
+ function isTraceQueryTimeoutError(error) {
409
+ const { status, body } = error ?? {};
410
+ return status === 504 && body?.code === "TRACE_QUERY_EXECUTION_TIMEOUT";
411
+ }
412
+ /**
404
413
  * Whether a failed resubscribe should end a long-lived subscription instead of
405
414
  * retrying. Like {@link isTerminalHttpError}, but 408 Request Timeout and
406
415
  * 429 Too Many Requests stay retryable because they mean "try again later".
@@ -410,6 +419,583 @@ function isTerminalReconnectError(error) {
410
419
  return isTerminalHttpError(error) && status !== 408 && status !== 429;
411
420
  }
412
421
  //#endregion
422
+ //#region src/utils/ai-sdk-v4/data-stream-parts.ts
423
+ const dataStreamParts = [
424
+ {
425
+ code: "0",
426
+ name: "text",
427
+ parse: (value) => {
428
+ if (typeof value !== "string") throw new Error("\"text\" parts expect a string value.");
429
+ return {
430
+ type: "text",
431
+ value
432
+ };
433
+ }
434
+ },
435
+ {
436
+ code: "2",
437
+ name: "data",
438
+ parse: (value) => {
439
+ if (!Array.isArray(value)) throw new Error("\"data\" parts expect an array value.");
440
+ return {
441
+ type: "data",
442
+ value
443
+ };
444
+ }
445
+ },
446
+ {
447
+ code: "3",
448
+ name: "error",
449
+ parse: (value) => {
450
+ if (typeof value !== "string") throw new Error("\"error\" parts expect a string value.");
451
+ return {
452
+ type: "error",
453
+ value
454
+ };
455
+ }
456
+ },
457
+ {
458
+ code: "8",
459
+ name: "message_annotations",
460
+ parse: (value) => {
461
+ if (!Array.isArray(value)) throw new Error("\"message_annotations\" parts expect an array value.");
462
+ return {
463
+ type: "message_annotations",
464
+ value
465
+ };
466
+ }
467
+ },
468
+ {
469
+ code: "9",
470
+ name: "tool_call",
471
+ parse: (value) => {
472
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") throw new Error("\"tool_call\" parts expect an object with a \"toolCallId\", \"toolName\", and \"args\" property.");
473
+ return {
474
+ type: "tool_call",
475
+ value
476
+ };
477
+ }
478
+ },
479
+ {
480
+ code: "a",
481
+ name: "tool_result",
482
+ parse: (value) => {
483
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("result" in value)) throw new Error("\"tool_result\" parts expect an object with a \"toolCallId\" and a \"result\" property.");
484
+ return {
485
+ type: "tool_result",
486
+ value
487
+ };
488
+ }
489
+ },
490
+ {
491
+ code: "b",
492
+ name: "tool_call_streaming_start",
493
+ parse: (value) => {
494
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string") throw new Error("\"tool_call_streaming_start\" parts expect an object with a \"toolCallId\" and \"toolName\" property.");
495
+ return {
496
+ type: "tool_call_streaming_start",
497
+ value
498
+ };
499
+ }
500
+ },
501
+ {
502
+ code: "c",
503
+ name: "tool_call_delta",
504
+ parse: (value) => {
505
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("argsTextDelta" in value) || typeof value.argsTextDelta !== "string") throw new Error("\"tool_call_delta\" parts expect an object with a \"toolCallId\" and \"argsTextDelta\" property.");
506
+ return {
507
+ type: "tool_call_delta",
508
+ value
509
+ };
510
+ }
511
+ },
512
+ {
513
+ code: "d",
514
+ name: "finish_message",
515
+ parse: (value) => {
516
+ if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") throw new Error("\"finish_message\" parts expect an object with a \"finishReason\" property.");
517
+ const result = { finishReason: value.finishReason };
518
+ if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) result.usage = {
519
+ promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : NaN,
520
+ completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : NaN
521
+ };
522
+ return {
523
+ type: "finish_message",
524
+ value: result
525
+ };
526
+ }
527
+ },
528
+ {
529
+ code: "e",
530
+ name: "finish_step",
531
+ parse: (value) => {
532
+ if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") throw new Error("\"finish_step\" parts expect an object with a \"finishReason\" property.");
533
+ const result = {
534
+ finishReason: value.finishReason,
535
+ isContinued: false
536
+ };
537
+ if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) result.usage = {
538
+ promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : NaN,
539
+ completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : NaN
540
+ };
541
+ if ("isContinued" in value && typeof value.isContinued === "boolean") result.isContinued = value.isContinued;
542
+ return {
543
+ type: "finish_step",
544
+ value: result
545
+ };
546
+ }
547
+ },
548
+ {
549
+ code: "f",
550
+ name: "start_step",
551
+ parse: (value) => {
552
+ if (value == null || typeof value !== "object" || !("messageId" in value) || typeof value.messageId !== "string") throw new Error("\"start_step\" parts expect an object with an \"id\" property.");
553
+ return {
554
+ type: "start_step",
555
+ value: { messageId: value.messageId }
556
+ };
557
+ }
558
+ },
559
+ {
560
+ code: "g",
561
+ name: "reasoning",
562
+ parse: (value) => {
563
+ if (typeof value !== "string") throw new Error("\"reasoning\" parts expect a string value.");
564
+ return {
565
+ type: "reasoning",
566
+ value
567
+ };
568
+ }
569
+ },
570
+ {
571
+ code: "h",
572
+ name: "source",
573
+ parse: (value) => {
574
+ if (value == null || typeof value !== "object") throw new Error("\"source\" parts expect a Source object.");
575
+ return {
576
+ type: "source",
577
+ value
578
+ };
579
+ }
580
+ },
581
+ {
582
+ code: "i",
583
+ name: "redacted_reasoning",
584
+ parse: (value) => {
585
+ if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string") throw new Error("\"redacted_reasoning\" parts expect an object with a \"data\" property.");
586
+ return {
587
+ type: "redacted_reasoning",
588
+ value: { data: value.data }
589
+ };
590
+ }
591
+ },
592
+ {
593
+ code: "j",
594
+ name: "reasoning_signature",
595
+ parse: (value) => {
596
+ if (value == null || typeof value !== "object" || !("signature" in value) || typeof value.signature !== "string") throw new Error("\"reasoning_signature\" parts expect an object with a \"signature\" property.");
597
+ return {
598
+ type: "reasoning_signature",
599
+ value: { signature: value.signature }
600
+ };
601
+ }
602
+ },
603
+ {
604
+ code: "k",
605
+ name: "file",
606
+ parse: (value) => {
607
+ if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string" || !("mimeType" in value) || typeof value.mimeType !== "string") throw new Error("\"file\" parts expect an object with a \"data\" and \"mimeType\" property.");
608
+ return {
609
+ type: "file",
610
+ value
611
+ };
612
+ }
613
+ }
614
+ ];
615
+ const dataStreamPartsByCode = Object.fromEntries(dataStreamParts.map((part) => [part.code, part]));
616
+ Object.fromEntries(dataStreamParts.map((part) => [part.name, part.code]));
617
+ const validCodes = dataStreamParts.map((part) => part.code);
618
+ /**
619
+ Parses a stream part from a string.
620
+
621
+ @param line The string to parse.
622
+ @returns The parsed stream part.
623
+ @throws An error if the string cannot be parsed.
624
+ */
625
+ const parseDataStreamPart = (line) => {
626
+ const firstSeparatorIndex = line.indexOf(":");
627
+ if (firstSeparatorIndex === -1) throw new Error("Failed to parse stream string. No separator found.");
628
+ const prefix = line.slice(0, firstSeparatorIndex);
629
+ if (!validCodes.includes(prefix)) throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);
630
+ const code = prefix;
631
+ const textValue = line.slice(firstSeparatorIndex + 1);
632
+ const jsonValue = JSON.parse(textValue);
633
+ return dataStreamPartsByCode[code].parse(jsonValue);
634
+ };
635
+ //#endregion
636
+ //#region src/utils/ai-sdk-v4/fix-json.ts
637
+ function fixJson(input) {
638
+ const stack = ["ROOT"];
639
+ let lastValidIndex = -1;
640
+ let literalStart = null;
641
+ function processValueStart(char, i, swapState) {
642
+ switch (char) {
643
+ case "\"":
644
+ lastValidIndex = i;
645
+ stack.pop();
646
+ stack.push(swapState);
647
+ stack.push("INSIDE_STRING");
648
+ break;
649
+ case "f":
650
+ case "t":
651
+ case "n":
652
+ lastValidIndex = i;
653
+ literalStart = i;
654
+ stack.pop();
655
+ stack.push(swapState);
656
+ stack.push("INSIDE_LITERAL");
657
+ break;
658
+ case "-":
659
+ stack.pop();
660
+ stack.push(swapState);
661
+ stack.push("INSIDE_NUMBER");
662
+ break;
663
+ case "0":
664
+ case "1":
665
+ case "2":
666
+ case "3":
667
+ case "4":
668
+ case "5":
669
+ case "6":
670
+ case "7":
671
+ case "8":
672
+ case "9":
673
+ lastValidIndex = i;
674
+ stack.pop();
675
+ stack.push(swapState);
676
+ stack.push("INSIDE_NUMBER");
677
+ break;
678
+ case "{":
679
+ lastValidIndex = i;
680
+ stack.pop();
681
+ stack.push(swapState);
682
+ stack.push("INSIDE_OBJECT_START");
683
+ break;
684
+ case "[":
685
+ lastValidIndex = i;
686
+ stack.pop();
687
+ stack.push(swapState);
688
+ stack.push("INSIDE_ARRAY_START");
689
+ break;
690
+ }
691
+ }
692
+ function processAfterObjectValue(char, i) {
693
+ switch (char) {
694
+ case ",":
695
+ stack.pop();
696
+ stack.push("INSIDE_OBJECT_AFTER_COMMA");
697
+ break;
698
+ case "}":
699
+ lastValidIndex = i;
700
+ stack.pop();
701
+ break;
702
+ }
703
+ }
704
+ function processAfterArrayValue(char, i) {
705
+ switch (char) {
706
+ case ",":
707
+ stack.pop();
708
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
709
+ break;
710
+ case "]":
711
+ lastValidIndex = i;
712
+ stack.pop();
713
+ break;
714
+ }
715
+ }
716
+ for (let i = 0; i < input.length; i++) {
717
+ const char = input[i];
718
+ switch (stack[stack.length - 1]) {
719
+ case "ROOT":
720
+ processValueStart(char, i, "FINISH");
721
+ break;
722
+ case "INSIDE_OBJECT_START":
723
+ switch (char) {
724
+ case "\"":
725
+ stack.pop();
726
+ stack.push("INSIDE_OBJECT_KEY");
727
+ break;
728
+ case "}":
729
+ lastValidIndex = i;
730
+ stack.pop();
731
+ break;
732
+ }
733
+ break;
734
+ case "INSIDE_OBJECT_AFTER_COMMA":
735
+ switch (char) {
736
+ case "\"":
737
+ stack.pop();
738
+ stack.push("INSIDE_OBJECT_KEY");
739
+ break;
740
+ }
741
+ break;
742
+ case "INSIDE_OBJECT_KEY":
743
+ switch (char) {
744
+ case "\"":
745
+ stack.pop();
746
+ stack.push("INSIDE_OBJECT_AFTER_KEY");
747
+ break;
748
+ }
749
+ break;
750
+ case "INSIDE_OBJECT_AFTER_KEY":
751
+ switch (char) {
752
+ case ":":
753
+ stack.pop();
754
+ stack.push("INSIDE_OBJECT_BEFORE_VALUE");
755
+ break;
756
+ }
757
+ break;
758
+ case "INSIDE_OBJECT_BEFORE_VALUE":
759
+ processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
760
+ break;
761
+ case "INSIDE_OBJECT_AFTER_VALUE":
762
+ processAfterObjectValue(char, i);
763
+ break;
764
+ case "INSIDE_STRING":
765
+ switch (char) {
766
+ case "\"":
767
+ stack.pop();
768
+ lastValidIndex = i;
769
+ break;
770
+ case "\\":
771
+ stack.push("INSIDE_STRING_ESCAPE");
772
+ break;
773
+ default: lastValidIndex = i;
774
+ }
775
+ break;
776
+ case "INSIDE_ARRAY_START":
777
+ switch (char) {
778
+ case "]":
779
+ lastValidIndex = i;
780
+ stack.pop();
781
+ break;
782
+ default:
783
+ lastValidIndex = i;
784
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
785
+ break;
786
+ }
787
+ break;
788
+ case "INSIDE_ARRAY_AFTER_VALUE":
789
+ switch (char) {
790
+ case ",":
791
+ stack.pop();
792
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
793
+ break;
794
+ case "]":
795
+ lastValidIndex = i;
796
+ stack.pop();
797
+ break;
798
+ default:
799
+ lastValidIndex = i;
800
+ break;
801
+ }
802
+ break;
803
+ case "INSIDE_ARRAY_AFTER_COMMA":
804
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
805
+ break;
806
+ case "INSIDE_STRING_ESCAPE":
807
+ stack.pop();
808
+ lastValidIndex = i;
809
+ break;
810
+ case "INSIDE_NUMBER":
811
+ switch (char) {
812
+ case "0":
813
+ case "1":
814
+ case "2":
815
+ case "3":
816
+ case "4":
817
+ case "5":
818
+ case "6":
819
+ case "7":
820
+ case "8":
821
+ case "9":
822
+ lastValidIndex = i;
823
+ break;
824
+ case "e":
825
+ case "E":
826
+ case "-":
827
+ case ".": break;
828
+ case ",":
829
+ stack.pop();
830
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") processAfterArrayValue(char, i);
831
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") processAfterObjectValue(char, i);
832
+ break;
833
+ case "}":
834
+ stack.pop();
835
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") processAfterObjectValue(char, i);
836
+ break;
837
+ case "]":
838
+ stack.pop();
839
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") processAfterArrayValue(char, i);
840
+ break;
841
+ default:
842
+ stack.pop();
843
+ break;
844
+ }
845
+ break;
846
+ case "INSIDE_LITERAL": {
847
+ const partialLiteral = input.substring(literalStart, i + 1);
848
+ if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
849
+ stack.pop();
850
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") processAfterObjectValue(char, i);
851
+ else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") processAfterArrayValue(char, i);
852
+ } else lastValidIndex = i;
853
+ break;
854
+ }
855
+ }
856
+ }
857
+ let result = input.slice(0, lastValidIndex + 1);
858
+ for (let i = stack.length - 1; i >= 0; i--) switch (stack[i]) {
859
+ case "INSIDE_STRING":
860
+ result += "\"";
861
+ break;
862
+ case "INSIDE_OBJECT_KEY":
863
+ case "INSIDE_OBJECT_AFTER_KEY":
864
+ case "INSIDE_OBJECT_AFTER_COMMA":
865
+ case "INSIDE_OBJECT_START":
866
+ case "INSIDE_OBJECT_BEFORE_VALUE":
867
+ case "INSIDE_OBJECT_AFTER_VALUE":
868
+ result += "}";
869
+ break;
870
+ case "INSIDE_ARRAY_START":
871
+ case "INSIDE_ARRAY_AFTER_COMMA":
872
+ case "INSIDE_ARRAY_AFTER_VALUE":
873
+ result += "]";
874
+ break;
875
+ case "INSIDE_LITERAL": {
876
+ const partialLiteral = input.substring(literalStart, input.length);
877
+ if ("true".startsWith(partialLiteral)) result += "true".slice(partialLiteral.length);
878
+ else if ("false".startsWith(partialLiteral)) result += "false".slice(partialLiteral.length);
879
+ else if ("null".startsWith(partialLiteral)) result += "null".slice(partialLiteral.length);
880
+ }
881
+ }
882
+ return result;
883
+ }
884
+ //#endregion
885
+ //#region src/utils/ai-sdk-v4/parse-partial-json.ts
886
+ function tryParse(text) {
887
+ try {
888
+ return {
889
+ success: true,
890
+ value: JSON.parse(text)
891
+ };
892
+ } catch {
893
+ return { success: false };
894
+ }
895
+ }
896
+ function parsePartialJson(jsonText) {
897
+ if (jsonText === void 0) return {
898
+ value: void 0,
899
+ state: "undefined-input"
900
+ };
901
+ let result = tryParse(jsonText);
902
+ if (result.success) return {
903
+ value: result.value,
904
+ state: "successful-parse"
905
+ };
906
+ result = tryParse(fixJson(jsonText));
907
+ if (result.success) return {
908
+ value: result.value,
909
+ state: "repaired-parse"
910
+ };
911
+ return {
912
+ value: void 0,
913
+ state: "failed-parse"
914
+ };
915
+ }
916
+ //#endregion
917
+ //#region src/utils/ai-sdk-v4/process-data-stream.ts
918
+ const NEWLINE = "\n".charCodeAt(0);
919
+ function concatChunks(chunks, totalLength) {
920
+ const concatenatedChunks = new Uint8Array(totalLength);
921
+ let offset = 0;
922
+ for (const chunk of chunks) {
923
+ concatenatedChunks.set(chunk, offset);
924
+ offset += chunk.length;
925
+ }
926
+ chunks.length = 0;
927
+ return concatenatedChunks;
928
+ }
929
+ async function processDataStream({ stream, onTextPart, onReasoningPart, onReasoningSignaturePart, onRedactedReasoningPart, onSourcePart, onFilePart, onDataPart, onErrorPart, onToolCallStreamingStartPart, onToolCallDeltaPart, onToolCallPart, onToolResultPart, onMessageAnnotationsPart, onFinishMessagePart, onFinishStepPart, onStartStepPart }) {
930
+ const reader = stream.getReader();
931
+ const decoder = new TextDecoder();
932
+ const chunks = [];
933
+ let totalLength = 0;
934
+ while (true) {
935
+ const { value } = await reader.read();
936
+ if (value) {
937
+ chunks.push(value);
938
+ totalLength += value.length;
939
+ if (value[value.length - 1] !== NEWLINE) continue;
940
+ }
941
+ if (chunks.length === 0) break;
942
+ const concatenatedChunks = concatChunks(chunks, totalLength);
943
+ totalLength = 0;
944
+ const streamParts = decoder.decode(concatenatedChunks, { stream: true }).split("\n").filter((line) => line !== "").map(parseDataStreamPart);
945
+ for (const { type, value } of streamParts) switch (type) {
946
+ case "text":
947
+ await onTextPart?.(value);
948
+ break;
949
+ case "reasoning":
950
+ await onReasoningPart?.(value);
951
+ break;
952
+ case "reasoning_signature":
953
+ await onReasoningSignaturePart?.(value);
954
+ break;
955
+ case "redacted_reasoning":
956
+ await onRedactedReasoningPart?.(value);
957
+ break;
958
+ case "file":
959
+ await onFilePart?.(value);
960
+ break;
961
+ case "source":
962
+ await onSourcePart?.(value);
963
+ break;
964
+ case "data":
965
+ await onDataPart?.(value);
966
+ break;
967
+ case "error":
968
+ await onErrorPart?.(value);
969
+ break;
970
+ case "message_annotations":
971
+ await onMessageAnnotationsPart?.(value);
972
+ break;
973
+ case "tool_call_streaming_start":
974
+ await onToolCallStreamingStartPart?.(value);
975
+ break;
976
+ case "tool_call_delta":
977
+ await onToolCallDeltaPart?.(value);
978
+ break;
979
+ case "tool_call":
980
+ await onToolCallPart?.(value);
981
+ break;
982
+ case "tool_result":
983
+ await onToolResultPart?.(value);
984
+ break;
985
+ case "finish_message":
986
+ await onFinishMessagePart?.(value);
987
+ break;
988
+ case "finish_step":
989
+ await onFinishStepPart?.(value);
990
+ break;
991
+ case "start_step":
992
+ await onStartStepPart?.(value);
993
+ break;
994
+ default: throw new Error(`Unknown stream part type: ${type}`);
995
+ }
996
+ }
997
+ }
998
+ //#endregion
413
999
  //#region src/utils/client-tool-model-output.ts
414
1000
  /**
415
1001
  * Normalize modelOutput from toModelOutput() to the AI SDK V2 tool result
@@ -642,7 +1228,7 @@ var BaseResource = class {
642
1228
  } catch (error) {
643
1229
  lastError = error;
644
1230
  if (signal?.aborted || error?.name === "AbortError") throw error;
645
- if (isTerminalHttpError(error)) throw error;
1231
+ if (isTerminalHttpError(error) || isTraceQueryTimeoutError(error)) throw error;
646
1232
  if (attempt === retries) break;
647
1233
  await new Promise((resolve, reject) => {
648
1234
  const timer = setTimeout(() => {
@@ -1543,7 +2129,7 @@ var Agent = class extends BaseResource {
1543
2129
  replaceLastMessage
1544
2130
  });
1545
2131
  }
1546
- await (0, _ai_sdk_ui_utils.processDataStream)({
2132
+ await processDataStream({
1547
2133
  stream,
1548
2134
  onTextPart(value) {
1549
2135
  if (currentTextPart == null) {
@@ -1634,7 +2220,7 @@ var Agent = class extends BaseResource {
1634
2220
  onToolCallDeltaPart(value) {
1635
2221
  const partialToolCall = partialToolCalls[value.toolCallId];
1636
2222
  partialToolCall.text += value.argsTextDelta;
1637
- const { value: partialArgs } = (0, _ai_sdk_ui_utils.parsePartialJson)(partialToolCall.text);
2223
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
1638
2224
  const invocation = {
1639
2225
  state: "partial-call",
1640
2226
  step: partialToolCall.step,
@@ -1649,7 +2235,7 @@ var Agent = class extends BaseResource {
1649
2235
  },
1650
2236
  async onToolCallPart(value) {
1651
2237
  const partialToolCall = partialToolCalls[value.toolCallId];
1652
- const streamedArgs = partialToolCall?.text ? (0, _ai_sdk_ui_utils.parsePartialJson)(partialToolCall.text).value : void 0;
2238
+ const streamedArgs = partialToolCall?.text ? parsePartialJson(partialToolCall.text).value : void 0;
1653
2239
  const toolCall = streamedArgs === void 0 ? value : {
1654
2240
  ...value,
1655
2241
  args: streamedArgs
@@ -1764,7 +2350,7 @@ var Agent = class extends BaseResource {
1764
2350
  headers: response.headers
1765
2351
  });
1766
2352
  streamResponse.processDataStream = async (options = {}) => {
1767
- await (0, _ai_sdk_ui_utils.processDataStream)({
2353
+ await processDataStream({
1768
2354
  stream: streamResponse.body,
1769
2355
  ...options
1770
2356
  });
@@ -1888,7 +2474,7 @@ var Agent = class extends BaseResource {
1888
2474
  break;
1889
2475
  case "tool-call": {
1890
2476
  const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
1891
- const streamedArgs = partialToolCall?.text ? (0, _ai_sdk_ui_utils.parsePartialJson)(partialToolCall.text).value : void 0;
2477
+ const streamedArgs = partialToolCall?.text ? parsePartialJson(partialToolCall.text).value : void 0;
1892
2478
  const toolCall = streamedArgs === void 0 ? chunk.payload : {
1893
2479
  ...chunk.payload,
1894
2480
  args: streamedArgs
@@ -1947,7 +2533,7 @@ var Agent = class extends BaseResource {
1947
2533
  case "tool-call-delta": {
1948
2534
  const partialToolCall = partialToolCalls[chunk.payload.toolCallId];
1949
2535
  partialToolCall.text += chunk.payload.argsTextDelta;
1950
- const { value: partialArgs } = (0, _ai_sdk_ui_utils.parsePartialJson)(partialToolCall.text);
2536
+ const { value: partialArgs } = parsePartialJson(partialToolCall.text);
1951
2537
  const invocation = {
1952
2538
  state: "partial-call",
1953
2539
  step: partialToolCall.step,
@@ -2058,6 +2644,7 @@ var Agent = class extends BaseResource {
2058
2644
  try {
2059
2645
  let messages = [];
2060
2646
  let streamRunId = processedParams.runId;
2647
+ let finishedHistory;
2061
2648
  const [streamForController, streamForProcessing] = response.body.tee();
2062
2649
  const decoder = new TextDecoder();
2063
2650
  let pendingText = "";
@@ -2065,6 +2652,13 @@ var Agent = class extends BaseResource {
2065
2652
  pendingText += text;
2066
2653
  const lines = pendingText.split("\n\n");
2067
2654
  pendingText = isFinal ? "" : lines.pop() ?? "";
2655
+ for (const line of lines) {
2656
+ if (!line.startsWith("data: ") || !line.includes("\"type\":\"finish\"")) continue;
2657
+ try {
2658
+ const all = JSON.parse(line.slice(6))?.payload?.messages?.all;
2659
+ if (Array.isArray(all)) finishedHistory = all;
2660
+ } catch {}
2661
+ }
2068
2662
  const readableLines = lines.filter((line) => line.trim() !== "[DONE]" && line.trim() !== "data: [DONE]").join("\n\n");
2069
2663
  if (readableLines) safeEnqueue(new TextEncoder().encode(`${readableLines}\n\n`));
2070
2664
  };
@@ -2218,12 +2812,12 @@ var Agent = class extends BaseResource {
2218
2812
  role: "tool",
2219
2813
  content: toolResultContents
2220
2814
  };
2221
- const updatedMessages = threadId ? [toolResultMessage] : [
2815
+ const updatedMessages = threadId ? [toolResultMessage] : (route === "resume-stream" || route === "approve-tool-call" || route === "decline-tool-call") && finishedHistory ? [...finishedHistory, toolResultMessage] : [
2222
2816
  ...Array.isArray(processedParams.messages) ? processedParams.messages : [],
2223
2817
  ...messages,
2224
2818
  toolResultMessage
2225
2819
  ];
2226
- const recursionRoute = route === "resume-stream" ? "stream" : route === "resume-stream-until-idle" ? "stream-until-idle" : route;
2820
+ const recursionRoute = route === "resume-stream" || route === "approve-tool-call" || route === "decline-tool-call" ? "stream" : route === "resume-stream-until-idle" ? "stream-until-idle" : route;
2227
2821
  if (isAborted()) return;
2228
2822
  try {
2229
2823
  await this.processStreamResponse({
@@ -2424,7 +3018,8 @@ var Agent = class extends BaseResource {
2424
3018
  const { requestContext, ...rest } = params;
2425
3019
  const processedParams = {
2426
3020
  ...rest,
2427
- requestContext: parseClientRequestContext(requestContext)
3021
+ requestContext: parseClientRequestContext(requestContext),
3022
+ clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools)
2428
3023
  };
2429
3024
  const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
2430
3025
  const response = await this.processStreamResponse(processedParams, readableController, "approve-tool-call", signal);
@@ -2455,7 +3050,8 @@ var Agent = class extends BaseResource {
2455
3050
  const { requestContext, ...rest } = params;
2456
3051
  const processedParams = {
2457
3052
  ...rest,
2458
- requestContext: parseClientRequestContext(requestContext)
3053
+ requestContext: parseClientRequestContext(requestContext),
3054
+ clientTools: processClientTools(params.clientToolsResolver?.() ?? params.clientTools)
2459
3055
  };
2460
3056
  const { readable, controller: readableController, signal } = this.createCancellableStream(params.abortSignal);
2461
3057
  const response = await this.processStreamResponse(processedParams, readableController, "decline-tool-call", signal);
@@ -2612,28 +3208,70 @@ var Agent = class extends BaseResource {
2612
3208
  * Used when `requireToolApproval` is enabled with generate() to allow the agent to proceed.
2613
3209
  */
2614
3210
  async approveToolCallGenerate(params) {
2615
- const { requestContext, ...rest } = params;
2616
- return this.request(`/agents/${this.agentId}/approve-tool-call-generate`, {
3211
+ const { requestContext, clientTools, clientToolsResolver, memory, ...rest } = params;
3212
+ const response = await this.request(`/agents/${this.agentId}/approve-tool-call-generate`, {
2617
3213
  method: "POST",
2618
3214
  body: {
2619
3215
  ...rest,
2620
- requestContext: parseClientRequestContext(requestContext)
3216
+ requestContext: parseClientRequestContext(requestContext),
3217
+ clientTools: processClientTools(clientToolsResolver?.() ?? clientTools)
2621
3218
  }
2622
3219
  });
3220
+ return this.continueResumedGenerate(response, {
3221
+ requestContext,
3222
+ clientTools,
3223
+ clientToolsResolver,
3224
+ memory
3225
+ });
2623
3226
  }
2624
3227
  /**
2625
3228
  * Declines a pending tool call and returns the complete response (non-streaming).
2626
3229
  * Used when `requireToolApproval` is enabled with generate() to prevent tool execution.
2627
3230
  */
2628
3231
  async declineToolCallGenerate(params) {
2629
- const { requestContext, ...rest } = params;
2630
- return this.request(`/agents/${this.agentId}/decline-tool-call-generate`, {
3232
+ const { requestContext, clientTools, clientToolsResolver, memory, ...rest } = params;
3233
+ const response = await this.request(`/agents/${this.agentId}/decline-tool-call-generate`, {
2631
3234
  method: "POST",
2632
3235
  body: {
2633
3236
  ...rest,
2634
- requestContext: parseClientRequestContext(requestContext)
3237
+ requestContext: parseClientRequestContext(requestContext),
3238
+ clientTools: processClientTools(clientToolsResolver?.() ?? clientTools)
2635
3239
  }
2636
3240
  });
3241
+ return this.continueResumedGenerate(response, {
3242
+ requestContext,
3243
+ clientTools,
3244
+ clientToolsResolver,
3245
+ memory
3246
+ });
3247
+ }
3248
+ /**
3249
+ * Runs executable client tools the model called after an approval decision and continues on
3250
+ * /generate, like generate() does. With memory the continuation sends only the new messages to the
3251
+ * thread. Without memory it re-sends the conversation up to the last user turn, because the resume
3252
+ * routes keep the earlier history server-side and drop it once the run finishes.
3253
+ */
3254
+ async continueResumedGenerate(response, { requestContext, clientTools, clientToolsResolver, memory }) {
3255
+ if (response.finishReason !== "tool-calls") return response;
3256
+ const context = requestContext === void 0 || requestContext instanceof _mastra_core_request_context.RequestContext ? requestContext : new _mastra_core_request_context.RequestContext(Object.entries(requestContext));
3257
+ const threadId = typeof memory?.thread === "string" ? memory.thread : memory?.thread?.id;
3258
+ const history = response.messages ?? [];
3259
+ const priorTurns = history.slice(0, history.findLastIndex((message) => message.role === "user") + 1);
3260
+ return executeToolCallAndRespond({
3261
+ response,
3262
+ params: {
3263
+ messages: threadId ? [] : priorTurns,
3264
+ clientTools: clientToolsResolver?.() ?? clientTools,
3265
+ clientToolsResolver,
3266
+ requestContext: context,
3267
+ memory
3268
+ },
3269
+ agentId: this.agentId,
3270
+ resourceId: memory?.resource,
3271
+ threadId,
3272
+ requestContext: context,
3273
+ respondFn: (messages, options) => this.generate(messages, options)
3274
+ });
2637
3275
  }
2638
3276
  /**
2639
3277
  * Processes the stream response and handles tool calls
@@ -4574,10 +5212,10 @@ var Observability = class extends BaseResource {
4574
5212
  });
4575
5213
  }
4576
5214
  /**
4577
- * Queries thread identities using eligible-trace and cross-trace predicates.
5215
+ * Queries full-history thread rows using a trace or thread activity window.
4578
5216
  *
4579
- * @param params - Thread query with its eligible trace selection
4580
- * @returns Matching thread identities
5217
+ * @param params - Thread query with its qualification window, filters and pagination
5218
+ * @returns Matching thread rows. Legacy requests retain their identity-only response.
4581
5219
  */
4582
5220
  queryTraceThreads(params) {
4583
5221
  return this.request("/observability/threads/query", {
@@ -6162,48 +6800,40 @@ function hydrateEventTimestamps(event) {
6162
6800
  return isKnownParsedEvent(event) ? hydrateKnownEvent(event) : event;
6163
6801
  }
6164
6802
  /**
6165
- * A session bound to a `resourceId` within one agent controller. Sessions are
6166
- * get-or-create on the server, so re-creating the same resourceId (and scope)
6167
- * resumes the existing conversation rather than forking it.
6168
- *
6169
- * Pass a `scope` to address an independent session over the same resourceId:
6170
- * two sessions with the same resourceId but different scopes have their own
6171
- * run loop, thread binding, and mode/model/state (e.g. one session per git
6172
- * worktree, with the worktree path as the scope). The scope travels on every
6173
- * request as a `sessionScope` query param.
6803
+ * A session addressed by its `sessionId` within one agent controller. Sessions
6804
+ * are get-or-create on the server, so re-creating the same sessionId resumes
6805
+ * the existing conversation rather than forking it. Many sessions can work on
6806
+ * one `resourceId` (whose threads and memory they use); each has its own run
6807
+ * loop, thread binding, and mode/model/state.
6174
6808
  */
6175
6809
  var AgentControllerSession = class extends BaseResource {
6176
6810
  controllerId;
6177
- resourceId;
6178
- scope;
6179
- constructor(options, controllerId, resourceId, scope) {
6811
+ sessionId;
6812
+ constructor(options, controllerId, sessionId) {
6180
6813
  super(options);
6181
6814
  this.controllerId = controllerId;
6182
- this.resourceId = resourceId;
6183
- this.scope = scope;
6815
+ this.sessionId = sessionId;
6184
6816
  }
6185
6817
  base() {
6186
- return `/agent-controller/${encodeURIComponent(this.controllerId)}/sessions/${encodeURIComponent(this.resourceId)}`;
6187
- }
6188
- /** Append this session's scope (if any) as a `sessionScope` query param. */
6189
- url(path) {
6190
- if (this.scope === void 0) return path;
6191
- return `${path}${path.includes("?") ? "&" : "?"}sessionScope=${encodeURIComponent(this.scope)}`;
6818
+ return `/agent-controller/${encodeURIComponent(this.controllerId)}/sessions/${encodeURIComponent(this.sessionId)}`;
6192
6819
  }
6193
6820
  /**
6194
- * Create or resume this session. Pass `tags` to scope initial thread
6195
- * selection — a thread is a resume candidate only when its metadata matches
6196
- * every tag. Pass `threadId` to bind the session to one exact thread,
6197
- * creating it with that id when it does not exist.
6821
+ * Create or resume this session. `resourceId` names whose threads and memory
6822
+ * the session works on. Without it the server resumes the session on the
6823
+ * resource it already has (the live session's, or the resource of the thread
6824
+ * with the session's id), falling back to the sessionId. Pass `tags` to scope
6825
+ * initial thread selection — a thread is a resume candidate only when its
6826
+ * metadata matches every tag. Pass `threadId` to bind the session to one
6827
+ * exact thread, creating it with that id when it does not exist.
6198
6828
  */
6199
6829
  create(options) {
6200
6830
  return this.request(`/agent-controller/${encodeURIComponent(this.controllerId)}/sessions`, {
6201
6831
  method: "POST",
6202
6832
  body: {
6203
- resourceId: this.resourceId,
6833
+ resourceId: options?.resourceId,
6834
+ sessionId: this.sessionId,
6204
6835
  tags: options?.tags,
6205
- threadId: options?.threadId,
6206
- sessionScope: this.scope
6836
+ threadId: options?.threadId
6207
6837
  }
6208
6838
  });
6209
6839
  }
@@ -6229,10 +6859,12 @@ var AgentControllerSession = class extends BaseResource {
6229
6859
  delayMs: finiteOr(options.reconnect.delayMs, 1e3),
6230
6860
  maxDelayMs: finiteOr(options.reconnect.maxDelayMs, 3e4)
6231
6861
  } : null;
6862
+ const idleTimeoutMs = finiteOr(options.idleTimeoutMs, 6e4);
6232
6863
  /** Exponential backoff for the Nth (1-based) retry of an outage streak. */
6233
6864
  const backoffDelay = (attempt) => reconnectOptions ? Math.min(reconnectOptions.delayMs * 2 ** (attempt - 1), reconnectOptions.maxDelayMs) : 0;
6234
6865
  let cancelled = false;
6235
6866
  let currentReader = null;
6867
+ let currentAbort = null;
6236
6868
  let reconnectTimer;
6237
6869
  let delayResolve;
6238
6870
  const settleDelay = () => {
@@ -6248,8 +6880,39 @@ var AgentControllerSession = class extends BaseResource {
6248
6880
  delayResolve = resolve;
6249
6881
  reconnectTimer = setTimeout(settleDelay, ms);
6250
6882
  });
6883
+ const idleTimeoutError = () => {
6884
+ const error = /* @__PURE__ */ new Error(`Agent controller session stream received no data for ${idleTimeoutMs}ms`);
6885
+ error.name = "AgentControllerStreamIdleError";
6886
+ return error;
6887
+ };
6251
6888
  const requestStream = async () => {
6252
- const response = await this.request(this.url(`${this.base()}/stream`), { stream: true });
6889
+ const abort = new AbortController();
6890
+ currentAbort = abort;
6891
+ let openTimer;
6892
+ const request = this.request(`${this.base()}/stream`, {
6893
+ stream: true,
6894
+ signal: abort.signal
6895
+ });
6896
+ request.then((response) => {
6897
+ if (abort.signal.aborted) response.body?.cancel().catch(() => {});
6898
+ }).catch(() => {});
6899
+ let response;
6900
+ try {
6901
+ if (idleTimeoutMs > 0) response = await Promise.race([request, new Promise((_resolve, reject) => {
6902
+ openTimer = setTimeout(() => {
6903
+ const error = idleTimeoutError();
6904
+ abort.abort(error);
6905
+ reject(error);
6906
+ }, idleTimeoutMs);
6907
+ })]);
6908
+ else response = await request;
6909
+ } finally {
6910
+ clearTimeout(openTimer);
6911
+ }
6912
+ if (abort.signal.aborted) {
6913
+ response.body?.cancel().catch(() => {});
6914
+ throw abort.signal.reason;
6915
+ }
6253
6916
  if (!response.body) throw new Error("No response body for agent controller session stream");
6254
6917
  return response;
6255
6918
  };
@@ -6275,12 +6938,40 @@ var AgentControllerSession = class extends BaseResource {
6275
6938
  const pump = async (response) => {
6276
6939
  const reader = response.body.getReader();
6277
6940
  currentReader = reader;
6941
+ const abort = currentAbort;
6278
6942
  const decoder = new TextDecoder();
6279
6943
  let buffer = "";
6944
+ let idleTimer;
6945
+ let timedOut = false;
6946
+ const armIdleTimer = () => {
6947
+ if (idleTimeoutMs <= 0) return;
6948
+ clearTimeout(idleTimer);
6949
+ idleTimer = setTimeout(() => {
6950
+ timedOut = true;
6951
+ reader.cancel(idleTimeoutError()).catch(() => {});
6952
+ abort?.abort(idleTimeoutError());
6953
+ }, idleTimeoutMs);
6954
+ };
6280
6955
  try {
6956
+ armIdleTimer();
6281
6957
  while (!cancelled) {
6282
- const { done, value } = await reader.read();
6958
+ let chunk;
6959
+ try {
6960
+ chunk = await reader.read();
6961
+ } catch (error) {
6962
+ if (timedOut && !cancelled) return {
6963
+ kind: "transport_error",
6964
+ error: idleTimeoutError()
6965
+ };
6966
+ throw error;
6967
+ }
6968
+ if (timedOut && !cancelled) return {
6969
+ kind: "transport_error",
6970
+ error: idleTimeoutError()
6971
+ };
6972
+ const { done, value } = chunk;
6283
6973
  if (done) return cancelled ? { kind: "cancelled" } : { kind: "done" };
6974
+ armIdleTimer();
6284
6975
  if (cancelled) return { kind: "cancelled" };
6285
6976
  buffer += decoder.decode(value, { stream: true });
6286
6977
  let separator;
@@ -6314,7 +7005,9 @@ var AgentControllerSession = class extends BaseResource {
6314
7005
  error
6315
7006
  };
6316
7007
  } finally {
7008
+ clearTimeout(idleTimer);
6317
7009
  if (currentReader === reader) currentReader = null;
7010
+ if (currentAbort === abort) currentAbort = null;
6318
7011
  reader.cancel().catch(() => {});
6319
7012
  }
6320
7013
  };
@@ -6391,6 +7084,7 @@ var AgentControllerSession = class extends BaseResource {
6391
7084
  cancelled = true;
6392
7085
  settleDelay();
6393
7086
  currentReader?.cancel().catch(() => {});
7087
+ currentAbort?.abort();
6394
7088
  } };
6395
7089
  }
6396
7090
  /**
@@ -6405,7 +7099,7 @@ var AgentControllerSession = class extends BaseResource {
6405
7099
  files: void 0
6406
7100
  } : message;
6407
7101
  const requestContext = parseClientRequestContext(options?.requestContext);
6408
- await this.request(this.url(`${this.base()}/messages`), {
7102
+ await this.request(`${this.base()}/messages`, {
6409
7103
  method: "POST",
6410
7104
  body: {
6411
7105
  message: content,
@@ -6416,7 +7110,7 @@ var AgentControllerSession = class extends BaseResource {
6416
7110
  }
6417
7111
  /** Abort the in-flight run for this session. */
6418
7112
  async abort() {
6419
- await this.request(this.url(`${this.base()}/abort`), { method: "POST" });
7113
+ await this.request(`${this.base()}/abort`, { method: "POST" });
6420
7114
  }
6421
7115
  /**
6422
7116
  * Approve or decline a pending tool call (`tool_approval_required`). Resolves
@@ -6424,12 +7118,13 @@ var AgentControllerSession = class extends BaseResource {
6424
7118
  */
6425
7119
  async approveTool(toolCallId, approved, options) {
6426
7120
  const requestContext = parseClientRequestContext(options?.requestContext);
6427
- return this.request(this.url(`${this.base()}/tool-approval`), {
7121
+ return this.request(`${this.base()}/tool-approval`, {
6428
7122
  method: "POST",
6429
7123
  retries: 0,
6430
7124
  body: {
6431
7125
  toolCallId,
6432
7126
  approved,
7127
+ ...options?.alwaysAllowCategory ? { alwaysAllowCategory: true } : {},
6433
7128
  ...requestContext ? { requestContext } : {}
6434
7129
  }
6435
7130
  });
@@ -6441,7 +7136,7 @@ var AgentControllerSession = class extends BaseResource {
6441
7136
  */
6442
7137
  async respondToToolSuspension(toolCallId, resumeData, options) {
6443
7138
  const requestContext = parseClientRequestContext(options?.requestContext);
6444
- return this.request(this.url(`${this.base()}/tool-suspension`), {
7139
+ return this.request(`${this.base()}/tool-suspension`, {
6445
7140
  method: "POST",
6446
7141
  retries: 0,
6447
7142
  body: {
@@ -6461,7 +7156,7 @@ var AgentControllerSession = class extends BaseResource {
6461
7156
  files: void 0
6462
7157
  } : message;
6463
7158
  const requestContext = parseClientRequestContext(options?.requestContext);
6464
- await this.request(this.url(`${this.base()}/steer`), {
7159
+ await this.request(`${this.base()}/steer`, {
6465
7160
  method: "POST",
6466
7161
  body: {
6467
7162
  message: content,
@@ -6473,18 +7168,18 @@ var AgentControllerSession = class extends BaseResource {
6473
7168
  /** Get the current mode, model, and thread (for initial UI hydration). */
6474
7169
  state(options) {
6475
7170
  const path = options?.threadId ? `${this.base()}?threadId=${encodeURIComponent(options.threadId)}` : this.base();
6476
- return this.request(this.url(path));
7171
+ return this.request(path);
6477
7172
  }
6478
7173
  /** Merge key-value pairs into the session state. Existing keys not in the payload are preserved. */
6479
7174
  async setState(updates) {
6480
- await this.request(this.url(`${this.base()}/state`), {
7175
+ await this.request(`${this.base()}/state`, {
6481
7176
  method: "PUT",
6482
7177
  body: { state: updates }
6483
7178
  });
6484
7179
  }
6485
7180
  /** Switch the active mode (e.g. `build`, `plan`). */
6486
7181
  async switchMode(modeId) {
6487
- await this.request(this.url(`${this.base()}/mode`), {
7182
+ await this.request(`${this.base()}/mode`, {
6488
7183
  method: "POST",
6489
7184
  body: { modeId }
6490
7185
  });
@@ -6494,7 +7189,7 @@ var AgentControllerSession = class extends BaseResource {
6494
7189
  * `thinkingLevel` is provided it is applied and persisted with the model.
6495
7190
  */
6496
7191
  async switchModel(modelId, { thinkingLevel } = {}) {
6497
- await this.request(this.url(`${this.base()}/model`), {
7192
+ await this.request(`${this.base()}/model`, {
6498
7193
  method: "POST",
6499
7194
  body: thinkingLevel !== void 0 ? {
6500
7195
  modelId,
@@ -6515,36 +7210,36 @@ var AgentControllerSession = class extends BaseResource {
6515
7210
  if (opts.limit != null) params.set("limit", String(opts.limit));
6516
7211
  if (opts.tags && Object.keys(opts.tags).length > 0) params.set("tags", JSON.stringify(opts.tags));
6517
7212
  const query = params.toString() ? `?${params.toString()}` : "";
6518
- return (await this.request(this.url(`${this.base()}/threads${query}`))).threads;
7213
+ return (await this.request(`${this.base()}/threads${query}`)).threads;
6519
7214
  }
6520
7215
  /** Switch the session to an existing thread (rebinds stream + state). */
6521
7216
  async switchThread(threadId) {
6522
- await this.request(this.url(`${this.base()}/thread`), {
7217
+ await this.request(`${this.base()}/thread`, {
6523
7218
  method: "POST",
6524
7219
  body: { threadId }
6525
7220
  });
6526
7221
  }
6527
7222
  /** Create a new thread (unbinds previous, binds the new one). */
6528
7223
  async createThread(title) {
6529
- return this.request(this.url(`${this.base()}/threads`), {
7224
+ return this.request(`${this.base()}/threads`, {
6530
7225
  method: "POST",
6531
7226
  body: { title }
6532
7227
  });
6533
7228
  }
6534
7229
  /** Delete a thread. If it's the active thread the session unbinds. */
6535
7230
  async deleteThread(threadId) {
6536
- await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(threadId)}`), { method: "DELETE" });
7231
+ await this.request(`${this.base()}/threads/${encodeURIComponent(threadId)}`, { method: "DELETE" });
6537
7232
  }
6538
7233
  /** Rename a thread. */
6539
7234
  async renameThread(threadId, title) {
6540
- await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(threadId)}`), {
7235
+ await this.request(`${this.base()}/threads/${encodeURIComponent(threadId)}`, {
6541
7236
  method: "PUT",
6542
7237
  body: { title }
6543
7238
  });
6544
7239
  }
6545
7240
  /** Clone a thread (and its messages). The session binds to the clone. */
6546
7241
  async cloneThread(options) {
6547
- return this.request(this.url(`${this.base()}/threads/clone`), {
7242
+ return this.request(`${this.base()}/threads/clone`, {
6548
7243
  method: "POST",
6549
7244
  body: options ?? {}
6550
7245
  });
@@ -6565,7 +7260,7 @@ var AgentControllerSession = class extends BaseResource {
6565
7260
  if (include) queryParams.set("include", JSON.stringify(include));
6566
7261
  }
6567
7262
  const query = queryParams.toString();
6568
- const body = await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(threadId)}/messages${query ? `?${query}` : ""}`));
7263
+ const body = await this.request(`${this.base()}/threads/${encodeURIComponent(threadId)}/messages${query ? `?${query}` : ""}`);
6569
7264
  const messages = body.messages.map(hydrateMessage);
6570
7265
  if (legacy) return messages;
6571
7266
  return {
@@ -6584,7 +7279,7 @@ var AgentControllerSession = class extends BaseResource {
6584
7279
  files: void 0
6585
7280
  } : message;
6586
7281
  const requestContext = parseClientRequestContext(options?.requestContext);
6587
- await this.request(this.url(`${this.base()}/follow-up`), {
7282
+ await this.request(`${this.base()}/follow-up`, {
6588
7283
  method: "POST",
6589
7284
  body: {
6590
7285
  message: content,
@@ -6595,26 +7290,26 @@ var AgentControllerSession = class extends BaseResource {
6595
7290
  }
6596
7291
  /** Get the observational memory record for this session's thread. */
6597
7292
  async getOMRecord() {
6598
- return (await this.request(this.url(`${this.base()}/om`))).record;
7293
+ return (await this.request(`${this.base()}/om`)).record;
6599
7294
  }
6600
7295
  /** Change the session's resource identity. */
6601
7296
  async setResourceId(newResourceId) {
6602
- await this.request(this.url(`${this.base()}/resource`), {
7297
+ await this.request(`${this.base()}/resource`, {
6603
7298
  method: "POST",
6604
7299
  body: { newResourceId }
6605
7300
  });
6606
7301
  }
6607
7302
  /** Get known resource IDs for this session. */
6608
7303
  async getResourceIds() {
6609
- return (await this.request(this.url(`${this.base()}/resources`))).resourceIds;
7304
+ return (await this.request(`${this.base()}/resources`)).resourceIds;
6610
7305
  }
6611
7306
  /** Get the current goal for this session's thread. */
6612
7307
  async getGoal() {
6613
- return (await this.request(this.url(`${this.base()}/goal`))).goal;
7308
+ return (await this.request(`${this.base()}/goal`)).goal;
6614
7309
  }
6615
7310
  /** Set a new goal objective. The agent's in-loop judge evaluates progress after each turn. */
6616
7311
  async setGoal(objective, options) {
6617
- return (await this.request(this.url(`${this.base()}/goal`), {
7312
+ return (await this.request(`${this.base()}/goal`, {
6618
7313
  method: "POST",
6619
7314
  body: {
6620
7315
  objective,
@@ -6624,22 +7319,22 @@ var AgentControllerSession = class extends BaseResource {
6624
7319
  }
6625
7320
  /** Update goal options (judge model, max runs, status). */
6626
7321
  async updateGoal(options) {
6627
- return (await this.request(this.url(`${this.base()}/goal`), {
7322
+ return (await this.request(`${this.base()}/goal`, {
6628
7323
  method: "PUT",
6629
7324
  body: options
6630
7325
  })).goal;
6631
7326
  }
6632
7327
  /** Clear the current goal. */
6633
7328
  async clearGoal() {
6634
- await this.request(this.url(`${this.base()}/goal`), { method: "DELETE" });
7329
+ await this.request(`${this.base()}/goal`, { method: "DELETE" });
6635
7330
  }
6636
7331
  /** Get the current permission rules (per-category and per-tool policies). */
6637
7332
  async getPermissions() {
6638
- return this.request(this.url(`${this.base()}/permissions`));
7333
+ return this.request(`${this.base()}/permissions`);
6639
7334
  }
6640
7335
  /** Set the approval policy for a tool category. */
6641
7336
  async setPermissionForCategory(category, policy) {
6642
- await this.request(this.url(`${this.base()}/permissions/category`), {
7337
+ await this.request(`${this.base()}/permissions/category`, {
6643
7338
  method: "PUT",
6644
7339
  body: {
6645
7340
  category,
@@ -6649,7 +7344,7 @@ var AgentControllerSession = class extends BaseResource {
6649
7344
  }
6650
7345
  /** Set the approval policy for a specific tool. */
6651
7346
  async setPermissionForTool(toolName, policy) {
6652
- await this.request(this.url(`${this.base()}/permissions/tool`), {
7347
+ await this.request(`${this.base()}/permissions/tool`, {
6653
7348
  method: "PUT",
6654
7349
  body: {
6655
7350
  toolName,
@@ -6663,7 +7358,7 @@ var AgentControllerSession = class extends BaseResource {
6663
7358
  * or is persisted for later.
6664
7359
  */
6665
7360
  async sendNotification(input) {
6666
- return this.request(this.url(`${this.base()}/notifications`), {
7361
+ return this.request(`${this.base()}/notifications`, {
6667
7362
  method: "POST",
6668
7363
  body: input
6669
7364
  });
@@ -6696,12 +7391,11 @@ var AgentController = class extends BaseResource {
6696
7391
  return this.request(`${this.basePath()}/workspace`);
6697
7392
  }
6698
7393
  /**
6699
- * Scope to a session bound to `resourceId` (e.g. a user or conversation id).
6700
- * Pass `scope` to address an independent session over the same resourceId
6701
- * (e.g. one session per git worktree, with the worktree path as the scope).
7394
+ * Address the session with this `sessionId`. Sessions created without an
7395
+ * explicit id are addressed by their `resourceId`.
6702
7396
  */
6703
- session(resourceId, scope) {
6704
- return new AgentControllerSession(this.options, this.controllerId, resourceId, scope);
7397
+ session(sessionId) {
7398
+ return new AgentControllerSession(this.options, this.controllerId, sessionId);
6705
7399
  }
6706
7400
  };
6707
7401
  /** Pull the plain text out of an assistant message's nested content parts. */
@@ -6775,7 +7469,7 @@ var MastraClient = class extends BaseResource {
6775
7469
  }
6776
7470
  /**
6777
7471
  * Scopes to an agent controller hosted on the connected Mastra instance. Use
6778
- * `getAgentController(id).session(resourceId)` to create/resume a session,
7472
+ * `getAgentController(id).session(sessionId)` to create/resume a session,
6779
7473
  * stream its events, and send messages.
6780
7474
  * @param controllerId - The id the agent controller is registered under on Mastra
6781
7475
  */
@@ -7296,7 +7990,7 @@ var MastraClient = class extends BaseResource {
7296
7990
  getTraceQueryValues(params, options) {
7297
7991
  return this.observability.getTraceQueryValues(params, options);
7298
7992
  }
7299
- /** Queries thread identities using eligible-trace and cross-trace predicates. */
7993
+ /** Queries full-history thread rows using a trace or thread activity window. */
7300
7994
  queryTraceThreads(params) {
7301
7995
  return this.observability.queryTraceThreads(params);
7302
7996
  }