@anvia/core 1.0.0-rc.6 → 1.0.0-rc.9

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 (108) hide show
  1. package/README.md +30 -13
  2. package/dist/agent/index.d.ts +13 -13
  3. package/dist/agent/index.js +15 -15
  4. package/dist/agent/interactions/index.d.ts +1 -1
  5. package/dist/agent/interactions/index.js +2 -2
  6. package/dist/{agent-BK3jud9q.d.ts → agent-XPQBM4rX.d.ts} +10 -10
  7. package/dist/{chunk-UBE4WH6G.js → chunk-3RWESPUG.js} +122 -3
  8. package/dist/chunk-3RWESPUG.js.map +1 -0
  9. package/dist/{chunk-BAEFBTOW.js → chunk-3SKZ2BKP.js} +7 -5
  10. package/dist/chunk-3SKZ2BKP.js.map +1 -0
  11. package/dist/{chunk-SROQA7I7.js → chunk-3XQGVDU5.js} +2 -2
  12. package/dist/chunk-3XQGVDU5.js.map +1 -0
  13. package/dist/{chunk-7YAH2F3J.js → chunk-76JLMBVT.js} +24 -12
  14. package/dist/chunk-76JLMBVT.js.map +1 -0
  15. package/dist/chunk-7JLAIN6E.js +15 -0
  16. package/dist/chunk-7JLAIN6E.js.map +1 -0
  17. package/dist/{chunk-MGNTXGTX.js → chunk-D4PACGPA.js} +1 -1
  18. package/dist/{chunk-7OCVDT2X.js → chunk-EFLT7XZD.js} +9 -3
  19. package/dist/chunk-EFLT7XZD.js.map +1 -0
  20. package/dist/{chunk-RZDI7B6Z.js → chunk-EMZKPRE6.js} +9 -8
  21. package/dist/chunk-EMZKPRE6.js.map +1 -0
  22. package/dist/{chunk-HVHTVGPP.js → chunk-I3Q7XSBB.js} +9 -3
  23. package/dist/chunk-I3Q7XSBB.js.map +1 -0
  24. package/dist/{chunk-BOCJCECN.js → chunk-KIXN5DGS.js} +4 -4
  25. package/dist/{chunk-BEU6FCTN.js → chunk-OJBFDBLG.js} +2 -2
  26. package/dist/{chunk-QXSVVYQK.js → chunk-PISJAAMX.js} +180 -443
  27. package/dist/chunk-PISJAAMX.js.map +1 -0
  28. package/dist/{chunk-G5OACQEI.js → chunk-QGX73TSQ.js} +2 -2
  29. package/dist/{chunk-JXZTTNCR.js → chunk-SJMSS5SI.js} +3 -3
  30. package/dist/{chunk-JXZTTNCR.js.map → chunk-SJMSS5SI.js.map} +1 -1
  31. package/dist/{chunk-YXLDR2O4.js → chunk-T2C3CGDQ.js} +9 -3
  32. package/dist/chunk-T2C3CGDQ.js.map +1 -0
  33. package/dist/{chunk-QXQQ2DBM.js → chunk-TC4FILD3.js} +2 -2
  34. package/dist/chunk-WTRGYFCD.js +1516 -0
  35. package/dist/chunk-WTRGYFCD.js.map +1 -0
  36. package/dist/{chunk-7O45T5F2.js → chunk-WZVHZZW6.js} +2 -2
  37. package/dist/{chunk-VGJRXUPT.js → chunk-X4LK4ODN.js} +2 -2
  38. package/dist/chunk-X4LK4ODN.js.map +1 -0
  39. package/dist/{chunk-H7BI3BSP.js → chunk-ZA564323.js} +2 -2
  40. package/dist/{client-BdQ_QZsY.d.ts → client-DTPl0hZv.d.ts} +2 -2
  41. package/dist/completion/index.d.ts +3 -3
  42. package/dist/completion/index.js +10 -5
  43. package/dist/{dynamic-tools--Aw37H9d.d.ts → dynamic-tools-aIZlg5x1.d.ts} +3 -3
  44. package/dist/embeddings/index.js +2 -2
  45. package/dist/evals/index.d.ts +6 -6
  46. package/dist/evals/index.js +51 -19
  47. package/dist/evals/index.js.map +1 -1
  48. package/dist/extractor/index.d.ts +1 -1
  49. package/dist/extractor/index.js +7 -6
  50. package/dist/guardrails/index.d.ts +4 -4
  51. package/dist/image-generation/index.d.ts +1 -1
  52. package/dist/image-generation/index.js +4 -2
  53. package/dist/index.d.ts +14 -14
  54. package/dist/index.js +32 -28
  55. package/dist/internal/agent.d.ts +11 -11
  56. package/dist/internal/agent.js +15 -15
  57. package/dist/mcp/index.d.ts +4 -4
  58. package/dist/mcp/index.js +10 -8
  59. package/dist/memory/index.d.ts +3 -3
  60. package/dist/memory/index.js +6 -5
  61. package/dist/{middleware-QZsbz7Hf.d.ts → middleware-kcF8AusP.d.ts} +8 -5
  62. package/dist/observability/index.d.ts +6 -6
  63. package/dist/observability/index.js +7 -6
  64. package/dist/pipeline/index.d.ts +11 -11
  65. package/dist/pipeline/index.js +8 -7
  66. package/dist/pipeline/index.js.map +1 -1
  67. package/dist/{message-schema-_sP_RKhh.d.ts → provider-output-error-BEwDgVv3.d.ts} +34 -3
  68. package/dist/skills/index.d.ts +4 -4
  69. package/dist/skills/index.js +7 -8
  70. package/dist/speech-generation/index.d.ts +1 -1
  71. package/dist/speech-generation/index.js +4 -2
  72. package/dist/{text-DTg1a8Mg.d.ts → text-ZLECpQE7.d.ts} +1 -1
  73. package/dist/{think-tool-C0n_dF2K.d.ts → think-tool-BwCsJ365.d.ts} +1 -1
  74. package/dist/tool/index.d.ts +6 -6
  75. package/dist/tool/index.js +6 -6
  76. package/dist/{tool-xHM_GmzT.d.ts → tool-BpqpoRSE.d.ts} +1 -1
  77. package/dist/transcription/index.d.ts +1 -1
  78. package/dist/transcription/index.js +4 -2
  79. package/dist/{types-D0Y2ZWS3.d.ts → types-CXNE592e.d.ts} +1 -1
  80. package/dist/{types-Dyp7arZQ.d.ts → types-DC1U1XwW.d.ts} +1 -1
  81. package/dist/{types-B1KL4w14.d.ts → types-DKOXVTcq.d.ts} +1 -1
  82. package/dist/{types-DboZvHR_.d.ts → types-DgvozfPc.d.ts} +3 -2
  83. package/dist/{types-D7A6CIGt.d.ts → types-DhkodEft.d.ts} +1 -1
  84. package/dist/{types-2DBdXArn.d.ts → types-Sue2hb_L.d.ts} +5 -5
  85. package/dist/vector-store/index.d.ts +4 -4
  86. package/dist/vector-store/index.js +5 -5
  87. package/package.json +1 -1
  88. package/dist/chunk-7OCVDT2X.js.map +0 -1
  89. package/dist/chunk-7YAH2F3J.js.map +0 -1
  90. package/dist/chunk-BAEFBTOW.js.map +0 -1
  91. package/dist/chunk-CQNNSZPG.js +0 -9
  92. package/dist/chunk-CQNNSZPG.js.map +0 -1
  93. package/dist/chunk-HT4P3SSG.js +0 -573
  94. package/dist/chunk-HT4P3SSG.js.map +0 -1
  95. package/dist/chunk-HVHTVGPP.js.map +0 -1
  96. package/dist/chunk-QXSVVYQK.js.map +0 -1
  97. package/dist/chunk-RZDI7B6Z.js.map +0 -1
  98. package/dist/chunk-SROQA7I7.js.map +0 -1
  99. package/dist/chunk-UBE4WH6G.js.map +0 -1
  100. package/dist/chunk-VGJRXUPT.js.map +0 -1
  101. package/dist/chunk-YXLDR2O4.js.map +0 -1
  102. /package/dist/{chunk-MGNTXGTX.js.map → chunk-D4PACGPA.js.map} +0 -0
  103. /package/dist/{chunk-BOCJCECN.js.map → chunk-KIXN5DGS.js.map} +0 -0
  104. /package/dist/{chunk-BEU6FCTN.js.map → chunk-OJBFDBLG.js.map} +0 -0
  105. /package/dist/{chunk-G5OACQEI.js.map → chunk-QGX73TSQ.js.map} +0 -0
  106. /package/dist/{chunk-QXQQ2DBM.js.map → chunk-TC4FILD3.js.map} +0 -0
  107. /package/dist/{chunk-7O45T5F2.js.map → chunk-WZVHZZW6.js.map} +0 -0
  108. /package/dist/{chunk-H7BI3BSP.js.map → chunk-ZA564323.js.map} +0 -0
@@ -1,42 +1,44 @@
1
+ import {
2
+ isSkillTool
3
+ } from "./chunk-YK4WAAS4.js";
1
4
  import {
2
5
  assertAgentInteractionResponse,
3
6
  parseAgentContinuation,
4
7
  parseAgentInteractionResponse,
5
8
  parseAgentQuestionPrompts
6
- } from "./chunk-BEU6FCTN.js";
9
+ } from "./chunk-OJBFDBLG.js";
7
10
  import {
8
11
  isMcpTool
9
- } from "./chunk-7YAH2F3J.js";
10
- import {
11
- MemoryCompactionConflictError,
12
- MemoryCompactionError,
13
- assertPositiveInteger,
14
- createMemoryCompactionSummary,
15
- cumulativeCompactedMessageCount
16
- } from "./chunk-QXQQ2DBM.js";
17
- import {
18
- startAgentRunObservers
19
- } from "./chunk-7O45T5F2.js";
20
- import {
21
- isSkillTool
22
- } from "./chunk-YK4WAAS4.js";
12
+ } from "./chunk-76JLMBVT.js";
23
13
  import {
24
14
  isQuestionTool,
25
15
  isToolIndex
26
- } from "./chunk-JXZTTNCR.js";
16
+ } from "./chunk-SJMSS5SI.js";
27
17
  import {
28
18
  ToolNotFoundError,
19
+ ToolOutput,
29
20
  assertFiniteMinScore,
30
21
  assertPositiveSearchLimit,
31
22
  assertToolApprovalRequirement,
32
23
  createTool,
24
+ normalizeToolResultOutput,
33
25
  parseToolArgs,
34
26
  prepareToolCall,
35
27
  prepareToolCallFromInput,
36
28
  retrieveDocuments,
37
29
  toolMayRequireApproval,
38
30
  toolResultContentToText
39
- } from "./chunk-RZDI7B6Z.js";
31
+ } from "./chunk-EMZKPRE6.js";
32
+ import {
33
+ MemoryCompactionConflictError,
34
+ MemoryCompactionError,
35
+ assertPositiveInteger,
36
+ createMemoryCompactionSummary,
37
+ cumulativeCompactedMessageCount
38
+ } from "./chunk-TC4FILD3.js";
39
+ import {
40
+ startAgentRunObservers
41
+ } from "./chunk-WZVHZZW6.js";
40
42
  import {
41
43
  AgentRunBlockedError,
42
44
  AgentRunCancelledError,
@@ -44,36 +46,42 @@ import {
44
46
  AgentStructuredOutputError,
45
47
  AgentToolSuspensionError,
46
48
  MaxTurnsError
47
- } from "./chunk-VGJRXUPT.js";
49
+ } from "./chunk-X4LK4ODN.js";
48
50
  import {
49
51
  mapWithConcurrency
50
52
  } from "./chunk-3RM57ZT2.js";
51
53
  import {
54
+ CompletionStreamAccumulator,
52
55
  Usage,
53
56
  assertCompletionRequestSupported,
57
+ assertCompletionResponseIntegrity,
54
58
  createCompletionRequest,
55
59
  getAssistantGenerationMetadata,
56
60
  isProviderTool,
57
61
  isStreamingCompletionModel,
58
62
  textFromAssistantContent
59
- } from "./chunk-HT4P3SSG.js";
63
+ } from "./chunk-WTRGYFCD.js";
60
64
  import {
61
65
  parseMessage,
62
66
  parseMessages,
63
67
  toProviderJsonSchema
64
- } from "./chunk-G5OACQEI.js";
68
+ } from "./chunk-QGX73TSQ.js";
69
+ import {
70
+ assertJsonObject
71
+ } from "./chunk-7JLAIN6E.js";
65
72
  import {
66
73
  isJsonValue
67
- } from "./chunk-SROQA7I7.js";
74
+ } from "./chunk-3XQGVDU5.js";
68
75
  import {
69
76
  abortError,
77
+ completionProviderOutputErrorUsage,
70
78
  resolveRetryOptions,
71
79
  retryDelayMs,
72
80
  retryErrorAttributes,
73
81
  retryOptionsForFailure,
74
82
  throwIfAborted,
75
83
  waitForRetry
76
- } from "./chunk-UBE4WH6G.js";
84
+ } from "./chunk-3RWESPUG.js";
77
85
  import {
78
86
  appendGuardrailPolicies,
79
87
  hasEnforcedOutputGuardrails,
@@ -828,394 +836,6 @@ function assertPositiveSafeInteger(value, name) {
828
836
  return value;
829
837
  }
830
838
 
831
- // src/internal/agent-runtime/stream-accumulator.ts
832
- var CompletionStreamAccumulator = class {
833
- orderedParts = [];
834
- textParts = /* @__PURE__ */ new Map();
835
- reasoningByKey = /* @__PURE__ */ new Map();
836
- reasoningKeyById = /* @__PURE__ */ new Map();
837
- toolCalls = /* @__PURE__ */ new Map();
838
- sources = /* @__PURE__ */ new Map();
839
- providerToolCalls = /* @__PURE__ */ new Map();
840
- finalResponse;
841
- messageId;
842
- nextTextKey = 0;
843
- nextReasoningKey = 0;
844
- accept(event) {
845
- if (event.type === "text_delta") {
846
- this.appendText(event.delta);
847
- return { type: "text_delta", delta: event.delta };
848
- }
849
- if (event.type === "reasoning_delta") {
850
- const reasoning = this.reasoningStateForEvent(event);
851
- this.appendReasoning(reasoning, event);
852
- return reasoningDeltaEvent(event);
853
- }
854
- if (event.type === "tool_call_delta") {
855
- const toolCall = this.toolCallStateForId(event.id);
856
- if (event.callId !== void 0 && event.callId.length > 0) toolCall.callId = event.callId;
857
- if (event.name !== void 0 && event.name.length > 0) toolCall.name = event.name;
858
- if (event.signature !== void 0) toolCall.signature = event.signature;
859
- if (event.argumentsDelta !== void 0) {
860
- if (event.argumentsMode === "replace") {
861
- toolCall.argumentsText = event.argumentsDelta;
862
- } else {
863
- toolCall.argumentsText += event.argumentsDelta;
864
- }
865
- }
866
- return void 0;
867
- }
868
- if (event.type === "tool_call") {
869
- this.upsertToolCall(event.toolCall);
870
- return { type: "tool_call", toolCall: event.toolCall };
871
- }
872
- if (event.type === "source") {
873
- this.sources.set(sourceKey(event.source), event.source);
874
- return { type: "source", source: event.source };
875
- }
876
- if (event.type === "provider_tool_call") {
877
- this.providerToolCalls.set(event.toolCall.id, event.toolCall);
878
- return { type: "provider_tool_call", toolCall: event.toolCall };
879
- }
880
- if (event.type === "message_id") {
881
- this.messageId = event.id;
882
- return void 0;
883
- }
884
- if (event.type === "final") {
885
- this.finalResponse = event.response;
886
- return void 0;
887
- }
888
- return void 0;
889
- }
890
- response() {
891
- const accumulatedResponse = this.buildAccumulatedResponse();
892
- if (this.finalResponse !== void 0) {
893
- if (accumulatedResponse.choice.length === 0) {
894
- return this.withAccumulatedArtifacts(this.finalResponse, accumulatedResponse);
895
- }
896
- return this.mergeFinalResponse(accumulatedResponse, this.finalResponse);
897
- }
898
- return accumulatedResponse;
899
- }
900
- buildAccumulatedResponse() {
901
- const choice = [];
902
- for (const part of this.orderedParts) {
903
- if (part.type === "text") {
904
- const text = this.textParts.get(part.key) ?? "";
905
- if (text.length > 0) {
906
- choice.push({ type: "text", text });
907
- }
908
- continue;
909
- }
910
- if (part.type === "reasoning") {
911
- const reasoning = this.reasoningByKey.get(part.key);
912
- if (reasoning !== void 0) {
913
- choice.push(reasoningContent(reasoning));
914
- }
915
- continue;
916
- }
917
- const toolCall = this.toolCalls.get(part.key);
918
- if (toolCall !== void 0) {
919
- choice.push(
920
- toolCallContent(toolCall, matchingFinalToolCall(toolCall, this.finalResponse?.choice))
921
- );
922
- }
923
- }
924
- const response = {
925
- choice,
926
- usage: Usage.empty(),
927
- rawResponse: void 0
928
- };
929
- if (this.messageId !== void 0) {
930
- response.messageId = this.messageId;
931
- }
932
- const sources = [...this.sources.values()];
933
- if (sources.length > 0) {
934
- response.sources = sources;
935
- }
936
- const providerToolCalls = [...this.providerToolCalls.values()];
937
- if (providerToolCalls.length > 0) {
938
- response.providerToolCalls = providerToolCalls;
939
- }
940
- return response;
941
- }
942
- upsertToolCall(toolCall) {
943
- if (!this.toolCalls.has(toolCall.toolCallId)) {
944
- this.orderedParts.push({ type: "tool_call", key: toolCall.toolCallId });
945
- }
946
- const partial = {
947
- id: toolCall.toolCallId,
948
- name: toolCall.toolName,
949
- argumentsText: JSON.stringify(toolCall.input ?? {})
950
- };
951
- if (toolCall.callId !== void 0) {
952
- partial.callId = toolCall.callId;
953
- }
954
- if (toolCall.signature !== void 0) {
955
- partial.signature = toolCall.signature;
956
- }
957
- this.toolCalls.set(toolCall.toolCallId, partial);
958
- }
959
- mergeFinalResponse(accumulatedResponse, finalResponse) {
960
- if (finalResponse.choice.length === 0) {
961
- const mergedResponse = {
962
- ...accumulatedResponse,
963
- usage: finalResponse.usage,
964
- rawResponse: finalResponse.rawResponse
965
- };
966
- if (finalResponse.finishReason !== void 0) {
967
- mergedResponse.finishReason = finalResponse.finishReason;
968
- }
969
- if (finalResponse.providerFinishReason !== void 0) {
970
- mergedResponse.providerFinishReason = finalResponse.providerFinishReason;
971
- }
972
- if (finalResponse.messageId !== void 0) {
973
- mergedResponse.messageId = finalResponse.messageId;
974
- }
975
- return this.withAccumulatedArtifacts(mergedResponse, accumulatedResponse);
976
- }
977
- const finalById = /* @__PURE__ */ new Map();
978
- const finalByCallId = /* @__PURE__ */ new Map();
979
- for (const content of finalResponse.choice) {
980
- if (content.type !== "tool-call") {
981
- continue;
982
- }
983
- finalById.set(content.toolCallId, content);
984
- if (content.callId !== void 0) {
985
- finalByCallId.set(content.callId, content);
986
- }
987
- }
988
- const matchedFinalToolCalls = /* @__PURE__ */ new Set();
989
- const choice = accumulatedResponse.choice.map((content) => {
990
- if (content.type !== "tool-call") {
991
- return content;
992
- }
993
- const finalToolCall = finalById.get(content.toolCallId) ?? (content.callId === void 0 ? void 0 : finalByCallId.get(content.callId));
994
- if (finalToolCall === void 0) {
995
- return content;
996
- }
997
- matchedFinalToolCalls.add(finalToolCall);
998
- return mergeFinalToolCall(content, finalToolCall);
999
- });
1000
- for (const content of finalResponse.choice) {
1001
- if (content.type !== "tool-call") {
1002
- continue;
1003
- }
1004
- if (!matchedFinalToolCalls.has(content)) {
1005
- choice.push(content);
1006
- }
1007
- }
1008
- return this.withAccumulatedArtifacts({ ...finalResponse, choice }, accumulatedResponse);
1009
- }
1010
- appendText(delta) {
1011
- const lastPart = this.orderedParts.at(-1);
1012
- const key = lastPart?.type === "text" ? lastPart.key : this.createTextKey();
1013
- if (lastPart?.type !== "text") {
1014
- this.orderedParts.push({ type: "text", key });
1015
- }
1016
- this.textParts.set(key, `${this.textParts.get(key) ?? ""}${delta}`);
1017
- }
1018
- reasoningStateForEvent(event) {
1019
- if (event.id !== void 0) {
1020
- const existingKey = this.reasoningKeyById.get(event.id);
1021
- if (existingKey !== void 0) {
1022
- const existing = this.reasoningByKey.get(existingKey);
1023
- if (existing !== void 0) {
1024
- return existing;
1025
- }
1026
- }
1027
- const key2 = this.createReasoningKey();
1028
- const reasoning2 = { id: event.id, text: "" };
1029
- this.reasoningKeyById.set(event.id, key2);
1030
- this.reasoningByKey.set(key2, reasoning2);
1031
- this.orderedParts.push({ type: "reasoning", key: key2 });
1032
- return reasoning2;
1033
- }
1034
- const lastPart = this.orderedParts.at(-1);
1035
- if (lastPart?.type === "reasoning") {
1036
- const lastReasoning = this.reasoningByKey.get(lastPart.key);
1037
- if (lastReasoning !== void 0 && lastReasoning.id === void 0) {
1038
- return lastReasoning;
1039
- }
1040
- }
1041
- const key = this.createReasoningKey();
1042
- const reasoning = { text: "" };
1043
- this.reasoningByKey.set(key, reasoning);
1044
- this.orderedParts.push({ type: "reasoning", key });
1045
- return reasoning;
1046
- }
1047
- toolCallStateForId(id) {
1048
- const existing = this.toolCalls.get(id);
1049
- if (existing !== void 0) {
1050
- return existing;
1051
- }
1052
- const toolCall = {
1053
- id,
1054
- name: "",
1055
- argumentsText: ""
1056
- };
1057
- this.toolCalls.set(id, toolCall);
1058
- this.orderedParts.push({ type: "tool_call", key: id });
1059
- return toolCall;
1060
- }
1061
- withMessageIdFallback(response, accumulatedResponse) {
1062
- if (response.messageId !== void 0 || accumulatedResponse.messageId === void 0) {
1063
- return response;
1064
- }
1065
- return { ...response, messageId: accumulatedResponse.messageId };
1066
- }
1067
- withAccumulatedArtifacts(response, accumulatedResponse) {
1068
- const withMessageId = this.withMessageIdFallback(response, accumulatedResponse);
1069
- const sources = mergeSources(accumulatedResponse.sources, response.sources);
1070
- const providerToolCalls = mergeProviderToolCalls(
1071
- accumulatedResponse.providerToolCalls,
1072
- response.providerToolCalls
1073
- );
1074
- let accumulated = { ...withMessageId };
1075
- if (sources.length > 0) accumulated = { ...accumulated, sources };
1076
- if (providerToolCalls.length > 0) {
1077
- accumulated = { ...accumulated, providerToolCalls };
1078
- }
1079
- return accumulated;
1080
- }
1081
- createTextKey() {
1082
- this.nextTextKey += 1;
1083
- return `text_${this.nextTextKey.toString()}`;
1084
- }
1085
- createReasoningKey() {
1086
- this.nextReasoningKey += 1;
1087
- return `reasoning_${this.nextReasoningKey.toString()}`;
1088
- }
1089
- appendReasoning(reasoning, event) {
1090
- const contentType = event.contentType ?? "text";
1091
- if (contentType === "text" || contentType === "summary") {
1092
- reasoning.text += event.delta;
1093
- }
1094
- if (event.contentType === void 0 && event.signature === void 0) {
1095
- return;
1096
- }
1097
- reasoning.details ??= [];
1098
- const last = reasoning.details.at(-1);
1099
- if (contentType === "text") {
1100
- if (last?.type === "text") {
1101
- let detail = {
1102
- ...last,
1103
- text: `${last.text}${event.delta}`
1104
- };
1105
- if (event.signature !== void 0) detail = { ...detail, signature: event.signature };
1106
- reasoning.details[reasoning.details.length - 1] = detail;
1107
- } else {
1108
- reasoning.details.push(
1109
- event.signature === void 0 ? { type: "text", text: event.delta } : { type: "text", text: event.delta, signature: event.signature }
1110
- );
1111
- }
1112
- return;
1113
- }
1114
- if (contentType === "summary") {
1115
- if (last?.type === "summary") {
1116
- reasoning.details[reasoning.details.length - 1] = {
1117
- ...last,
1118
- text: `${last.text}${event.delta}`
1119
- };
1120
- } else {
1121
- reasoning.details.push({ type: "summary", text: event.delta });
1122
- }
1123
- return;
1124
- }
1125
- if (contentType === "encrypted") {
1126
- reasoning.details.push({ type: "encrypted", data: event.delta });
1127
- return;
1128
- }
1129
- reasoning.details.push({ type: "redacted", data: event.delta });
1130
- }
1131
- };
1132
- function sourceKey(source) {
1133
- return `${source.url}\0${source.startIndex ?? ""}\0${source.endIndex ?? ""}`;
1134
- }
1135
- function mergeSources(accumulated, final) {
1136
- const sources = /* @__PURE__ */ new Map();
1137
- for (const source of [...accumulated ?? [], ...final ?? []]) {
1138
- sources.set(sourceKey(source), source);
1139
- }
1140
- return [...sources.values()];
1141
- }
1142
- function mergeProviderToolCalls(accumulated, final) {
1143
- const toolCalls = /* @__PURE__ */ new Map();
1144
- for (const toolCall of [...accumulated ?? [], ...final ?? []]) {
1145
- toolCalls.set(toolCall.id, toolCall);
1146
- }
1147
- return [...toolCalls.values()];
1148
- }
1149
- function reasoningContent(reasoning) {
1150
- const content = reasoning.details === void 0 ? { type: "reasoning", text: reasoning.text } : { type: "reasoning", text: reasoning.text, details: reasoning.details };
1151
- return reasoning.id === void 0 ? content : { ...content, id: reasoning.id };
1152
- }
1153
- function toolCallContent(toolCall, finalToolCall) {
1154
- const argumentsValue = finalToolCall !== void 0 && !isEmptyToolArguments(finalToolCall.input) ? finalToolCall.input : parseToolArguments(toolCall.id, toolCall.argumentsText);
1155
- let content = {
1156
- type: "tool-call",
1157
- toolCallId: toolCall.id,
1158
- toolName: toolCall.name,
1159
- input: argumentsValue
1160
- };
1161
- if (toolCall.callId !== void 0) content = { ...content, callId: toolCall.callId };
1162
- if (toolCall.signature !== void 0) content = { ...content, signature: toolCall.signature };
1163
- return content;
1164
- }
1165
- function matchingFinalToolCall(accumulated, finalChoice) {
1166
- const byId = finalChoice?.find(
1167
- (content) => content.type === "tool-call" && content.toolCallId === accumulated.id
1168
- );
1169
- if (byId !== void 0 || accumulated.callId === void 0) {
1170
- return byId;
1171
- }
1172
- return finalChoice?.find(
1173
- (content) => content.type === "tool-call" && content.callId === accumulated.callId
1174
- );
1175
- }
1176
- function mergeFinalToolCall(accumulated, finalToolCall) {
1177
- const input = isEmptyToolArguments(finalToolCall.input) ? accumulated.input : finalToolCall.input;
1178
- return {
1179
- ...accumulated,
1180
- ...finalToolCall,
1181
- input
1182
- };
1183
- }
1184
- function reasoningDeltaEvent(event) {
1185
- const mapped = { type: "reasoning_delta", delta: event.delta };
1186
- if (event.id !== void 0) mapped.id = event.id;
1187
- if (event.contentType !== void 0) mapped.contentType = event.contentType;
1188
- if (event.signature !== void 0) mapped.signature = event.signature;
1189
- return mapped;
1190
- }
1191
- function isEmptyToolArguments(value) {
1192
- if (value === void 0 || value === null) {
1193
- return true;
1194
- }
1195
- if (typeof value === "string") {
1196
- return value.trim().length === 0;
1197
- }
1198
- if (Array.isArray(value)) {
1199
- return value.length === 0;
1200
- }
1201
- if (typeof value === "object") {
1202
- return Object.values(value).every((item) => item === void 0);
1203
- }
1204
- return false;
1205
- }
1206
- function parseToolArguments(toolCallId, text) {
1207
- if (text.trim().length === 0) {
1208
- return {};
1209
- }
1210
- try {
1211
- return JSON.parse(text);
1212
- } catch {
1213
- throw new Error(
1214
- `Completion returned tool call "${toolCallId}" with malformed JSON arguments; this indicates invalid provider output or incomplete stream assembly.`
1215
- );
1216
- }
1217
- }
1218
-
1219
839
  // src/internal/agent-runtime/stream-events.ts
1220
840
  function addTurn(turn, event) {
1221
841
  if (event.type === "text_delta") {
@@ -1328,13 +948,13 @@ var ToolCallExecutor = class {
1328
948
  abortSignal;
1329
949
  cancel;
1330
950
  async execute(toolCalls, onResult, onStreamEvent, observation) {
1331
- for (const toolCall of toolCalls) {
1332
- if (toolCall.toolName.length === 0) {
1333
- throw new Error(
1334
- `Completion returned tool call "${toolCall.toolCallId}" with an empty tool name; this indicates invalid provider output or provider mapping.`
1335
- );
951
+ assertCompletionResponseIntegrity({
952
+ response: {
953
+ choice: [...toolCalls],
954
+ usage: Usage.empty(),
955
+ rawResponse: void 0
1336
956
  }
1337
- }
957
+ });
1338
958
  const executeOne = async (toolCall) => {
1339
959
  throwIfAborted(this.abortSignal);
1340
960
  const args = JSON.stringify(toolCall.input);
@@ -1953,7 +1573,14 @@ var ToolCallExecutor = class {
1953
1573
  args: current
1954
1574
  });
1955
1575
  if (replacement?.args !== void 0) {
1956
- current = typeof replacement.args === "string" ? replacement.args : JSON.stringify(replacement.args);
1576
+ if (typeof replacement.args === "string") {
1577
+ current = replacement.args;
1578
+ } else {
1579
+ if (!isJsonValue(replacement.args)) {
1580
+ throw new TypeError("Tool input middleware args must be a strict JSON value.");
1581
+ }
1582
+ current = JSON.stringify(replacement.args);
1583
+ }
1957
1584
  }
1958
1585
  }
1959
1586
  return current;
@@ -2045,20 +1672,51 @@ function createApprovalContext(input, hookArgs, agent, run) {
2045
1672
  return context;
2046
1673
  }
2047
1674
  function approvalEventAttributes(request, turn) {
2048
- return {
1675
+ const attributes = {
2049
1676
  turn,
2050
1677
  approvalId: request.id,
2051
1678
  toolName: request.toolName,
2052
- toolCallId: request.toolCallId,
2053
- internalCallId: request.internalCallId,
2054
- reason: request.reason
1679
+ internalCallId: request.internalCallId
2055
1680
  };
1681
+ if (request.toolCallId !== void 0) attributes.toolCallId = request.toolCallId;
1682
+ if (request.reason !== void 0) attributes.reason = request.reason;
1683
+ return attributes;
2056
1684
  }
2057
1685
  function normalizeToolOutputMiddlewareResult(result) {
2058
1686
  if (typeof result === "string") {
2059
1687
  return { result };
2060
1688
  }
2061
- return result ?? {};
1689
+ if (typeof result !== "object" || result === null) {
1690
+ throw new TypeError("Tool output middleware must return text or structured content.");
1691
+ }
1692
+ const prototype = Object.getPrototypeOf(result);
1693
+ if (prototype !== Object.prototype && prototype !== null) {
1694
+ throw new TypeError("Tool output middleware must return text or structured content.");
1695
+ }
1696
+ const keys = Reflect.ownKeys(result);
1697
+ const hasResult = keys.includes("result");
1698
+ const hasStructuredResult = keys.includes("structuredResult");
1699
+ if (hasResult === hasStructuredResult || keys.some((key) => key !== "result" && key !== "structuredResult")) {
1700
+ throw new TypeError(
1701
+ "Tool output middleware must return exactly one of result or structuredResult."
1702
+ );
1703
+ }
1704
+ if (hasResult) {
1705
+ const descriptor2 = Object.getOwnPropertyDescriptor(result, "result");
1706
+ if (descriptor2 === void 0 || !("value" in descriptor2) || typeof descriptor2.value !== "string") {
1707
+ throw new TypeError("Tool output middleware result must be a string.");
1708
+ }
1709
+ return { result: descriptor2.value };
1710
+ }
1711
+ const descriptor = Object.getOwnPropertyDescriptor(result, "structuredResult");
1712
+ if (descriptor === void 0 || !("value" in descriptor)) {
1713
+ throw new TypeError("Tool output middleware structuredResult must be valid tool content.");
1714
+ }
1715
+ const normalized = normalizeToolResultOutput(ToolOutput.content(descriptor.value));
1716
+ if (normalized.type !== "content") {
1717
+ throw new TypeError("Tool output middleware structuredResult must be valid tool content.");
1718
+ }
1719
+ return { structuredResult: normalized.value };
2062
1720
  }
2063
1721
  function toolTraceMetadata(tool) {
2064
1722
  if (tool === void 0) {
@@ -2338,13 +1996,19 @@ var AgentRun = class _AgentRun {
2338
1996
  pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);
2339
1997
  await this.runRunStartHook(newMessages);
2340
1998
  if (this.continuationState !== void 0) {
1999
+ const interactionAttributes = {};
2000
+ if (this.resumedFrom?.runId !== void 0) {
2001
+ interactionAttributes.sourceRunId = this.resumedFrom.runId;
2002
+ }
2003
+ if (this.resumedFrom?.interactionId !== void 0) {
2004
+ interactionAttributes.interactionId = this.resumedFrom.interactionId;
2005
+ }
2006
+ if (this.interactionResponse?.type !== void 0) {
2007
+ interactionAttributes.interactionType = this.interactionResponse.type;
2008
+ }
2341
2009
  await runObservers.event({
2342
2010
  name: "agent.interaction_response",
2343
- attributes: {
2344
- sourceRunId: this.resumedFrom?.runId,
2345
- interactionId: this.resumedFrom?.interactionId,
2346
- interactionType: this.interactionResponse?.type
2347
- }
2011
+ attributes: interactionAttributes
2348
2012
  });
2349
2013
  try {
2350
2014
  const toolResults = await this.resolveContinuationTools(
@@ -2399,6 +2063,13 @@ var AgentRun = class _AgentRun {
2399
2063
  throw error;
2400
2064
  }
2401
2065
  response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);
2066
+ try {
2067
+ assertCompletionResponseIntegrity({ response });
2068
+ } catch (error) {
2069
+ const providerOutputUsage = completionProviderOutputErrorUsage(error);
2070
+ if (providerOutputUsage !== void 0) usage = Usage.add(usage, providerOutputUsage);
2071
+ throw error;
2072
+ }
2402
2073
  usage = Usage.add(usage, response.usage);
2403
2074
  this.updateRunProgress(newMessages);
2404
2075
  await this.runCompletionResponseHook(prompt, response, newMessages);
@@ -2750,6 +2421,13 @@ var AgentRun = class _AgentRun {
2750
2421
  this.activeGeneration = void 0;
2751
2422
  await generationObservers.end(generationEndArgs);
2752
2423
  response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);
2424
+ try {
2425
+ assertCompletionResponseIntegrity({ response });
2426
+ } catch (error) {
2427
+ const providerOutputUsage = completionProviderOutputErrorUsage(error);
2428
+ if (providerOutputUsage !== void 0) usage = Usage.add(usage, providerOutputUsage);
2429
+ throw error;
2430
+ }
2753
2431
  usage = Usage.add(usage, response.usage);
2754
2432
  this.updateRunProgress(newMessages);
2755
2433
  await this.runCompletionResponseHook(prompt, response, newMessages);
@@ -2927,14 +2605,20 @@ var AgentRun = class _AgentRun {
2927
2605
  this.generationStartArgs(turn, request, providerRequest)
2928
2606
  );
2929
2607
  let currentRequest = request;
2930
- let structuredRetryUsage = Usage.empty();
2608
+ let failedAttemptUsage = Usage.empty();
2931
2609
  try {
2932
2610
  for (let attempt = 1; ; attempt += 1) {
2933
2611
  let response;
2934
2612
  try {
2935
2613
  this.throwIfCancelled();
2936
2614
  response = await this.agent.model.completion(currentRequest, this.modelCallOptions());
2615
+ assertCompletionResponseIntegrity({ response });
2937
2616
  } catch (error) {
2617
+ const attemptUsage = completionProviderOutputErrorUsage(error);
2618
+ if (attemptUsage !== void 0) {
2619
+ failedAttemptUsage = Usage.add(failedAttemptUsage, attemptUsage);
2620
+ this.failedCompletionUsage = failedAttemptUsage;
2621
+ }
2938
2622
  const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
2939
2623
  if (retryOptions === void 0) {
2940
2624
  throw error;
@@ -2945,11 +2629,12 @@ var AgentRun = class _AgentRun {
2945
2629
  turn,
2946
2630
  false,
2947
2631
  retryOptions,
2948
- runObservers
2632
+ runObservers,
2633
+ providerOutputRetryEventAttributes(error, failedAttemptUsage)
2949
2634
  );
2950
2635
  continue;
2951
2636
  }
2952
- const cumulativeUsage = Usage.add(structuredRetryUsage, response.usage);
2637
+ const cumulativeUsage = Usage.add(failedAttemptUsage, response.usage);
2953
2638
  try {
2954
2639
  this.validateStructuredResponse(response, attempt, cumulativeUsage);
2955
2640
  } catch (error) {
@@ -2957,8 +2642,8 @@ var AgentRun = class _AgentRun {
2957
2642
  if (retryOptions === void 0) {
2958
2643
  throw error;
2959
2644
  }
2960
- structuredRetryUsage = cumulativeUsage;
2961
- this.failedCompletionUsage = structuredRetryUsage;
2645
+ failedAttemptUsage = cumulativeUsage;
2646
+ this.failedCompletionUsage = failedAttemptUsage;
2962
2647
  const retryRequest = structuredOutputRetryRequest(request, response, error);
2963
2648
  currentRequest = retryRequest.request;
2964
2649
  await this.scheduleCompletionRetry(
@@ -2972,7 +2657,7 @@ var AgentRun = class _AgentRun {
2972
2657
  );
2973
2658
  continue;
2974
2659
  }
2975
- const finalResponse = structuredRetryUsage.totalTokens === 0 ? response : { ...response, usage: cumulativeUsage };
2660
+ const finalResponse = Usage.isEmpty(failedAttemptUsage) ? response : { ...response, usage: cumulativeUsage };
2976
2661
  await generationObservers.end({ turn, response: finalResponse });
2977
2662
  this.failedCompletionUsage = Usage.empty();
2978
2663
  return finalResponse;
@@ -3009,20 +2694,28 @@ var AgentRun = class _AgentRun {
3009
2694
  for (let attempt = 1; ; attempt += 1) {
3010
2695
  const accumulator = new CompletionStreamAccumulator();
3011
2696
  let hasProviderProgress = false;
2697
+ let recordedErrorUsage = false;
2698
+ let attemptErrorUsage;
3012
2699
  try {
3013
2700
  this.throwIfCancelled();
3014
2701
  for await (const event of model.streamCompletion(currentRequest, this.modelCallOptions())) {
3015
2702
  if (event.type === "error") {
3016
- if (event.usage !== void 0) {
3017
- args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, event.usage);
2703
+ const eventUsage = event.usage ?? completionProviderOutputErrorUsage(event.error);
2704
+ if (eventUsage !== void 0) {
2705
+ args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, eventUsage);
2706
+ recordedErrorUsage = true;
2707
+ attemptErrorUsage = eventUsage;
3018
2708
  }
3019
2709
  throw event.error;
3020
2710
  }
3021
- hasProviderProgress = true;
2711
+ const mapped = accumulator.accept(event);
2712
+ if (event.type === "final") break;
2713
+ if (event.type === "tool_call_delta" || mapped !== void 0) {
2714
+ hasProviderProgress = true;
2715
+ }
3022
2716
  if (args.state.firstDeltaMs === void 0 && isGenerationDeltaEvent(event.type)) {
3023
2717
  args.state.firstDeltaMs = Date.now() - args.generationStartedAt;
3024
2718
  }
3025
- const mapped = accumulator.accept(event);
3026
2719
  if (event.type === "tool_call_delta") {
3027
2720
  yield addTurnToToolCallDelta(args.turn, event);
3028
2721
  }
@@ -3038,6 +2731,7 @@ var AgentRun = class _AgentRun {
3038
2731
  }
3039
2732
  }
3040
2733
  const response = accumulator.response();
2734
+ assertCompletionResponseIntegrity({ response });
3041
2735
  const cumulativeStructuredUsage = Usage.add(args.state.providerErrorUsage, response.usage);
3042
2736
  try {
3043
2737
  this.validateStructuredResponse(response, attempt, cumulativeStructuredUsage);
@@ -3065,10 +2759,17 @@ var AgentRun = class _AgentRun {
3065
2759
  );
3066
2760
  continue;
3067
2761
  }
3068
- args.state.response = args.state.providerErrorUsage.totalTokens === 0 ? response : { ...response, usage: cumulativeStructuredUsage };
2762
+ args.state.response = Usage.isEmpty(args.state.providerErrorUsage) ? response : { ...response, usage: cumulativeStructuredUsage };
3069
2763
  args.state.providerErrorUsage = Usage.empty();
3070
2764
  return;
3071
2765
  } catch (error) {
2766
+ if (!recordedErrorUsage) {
2767
+ const attemptUsage = completionProviderOutputErrorUsage(error);
2768
+ if (attemptUsage !== void 0) {
2769
+ args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, attemptUsage);
2770
+ attemptErrorUsage = attemptUsage;
2771
+ }
2772
+ }
3072
2773
  const retryOptions = hasProviderProgress ? void 0 : this.retryOptionsForFailure(error, attempt, args.turn, true);
3073
2774
  if (retryOptions === void 0) {
3074
2775
  throw error;
@@ -3079,7 +2780,12 @@ var AgentRun = class _AgentRun {
3079
2780
  args.turn,
3080
2781
  true,
3081
2782
  retryOptions,
3082
- args.runObservers
2783
+ args.runObservers,
2784
+ providerOutputRetryEventAttributes(
2785
+ error,
2786
+ args.state.providerErrorUsage,
2787
+ attemptErrorUsage
2788
+ )
3083
2789
  );
3084
2790
  }
3085
2791
  }
@@ -3510,6 +3216,20 @@ var AgentRun = class _AgentRun {
3510
3216
  if (response.choice.some((item) => item.type === "tool-call")) return;
3511
3217
  const text = textFromAssistantContent(response.choice);
3512
3218
  const normalized = normalizeStructuredOutput(text);
3219
+ if (response.finishReason === "content-filter") {
3220
+ throw new AgentStructuredOutputError({
3221
+ phase: "content-filter",
3222
+ attempt,
3223
+ maxAttempts: this.completionRetryOptions?.maxAttempts ?? 1,
3224
+ outputLength: text.length,
3225
+ normalizedLength: normalized.text.length,
3226
+ outputFormat: normalized.format,
3227
+ attemptUsage: response.usage,
3228
+ usage,
3229
+ finishReason: response.finishReason,
3230
+ providerFinishReason: response.providerFinishReason
3231
+ });
3232
+ }
3513
3233
  if (response.finishReason === "length") {
3514
3234
  throw new AgentStructuredOutputError({
3515
3235
  phase: "truncated",
@@ -3548,6 +3268,9 @@ var AgentRun = class _AgentRun {
3548
3268
  let json;
3549
3269
  try {
3550
3270
  json = JSON.parse(normalized.text);
3271
+ if (!isJsonValue(json)) {
3272
+ throw new TypeError("Agent structured output is not a JSON value.");
3273
+ }
3551
3274
  } catch (error) {
3552
3275
  throw new AgentStructuredOutputError({
3553
3276
  phase: "parse",
@@ -3726,6 +3449,9 @@ var AgentRun = class _AgentRun {
3726
3449
  });
3727
3450
  if (replacement?.request !== void 0) {
3728
3451
  current = replacement.request;
3452
+ if (current.providerOptions !== void 0) {
3453
+ assertJsonObject(current.providerOptions, "providerOptions");
3454
+ }
3729
3455
  }
3730
3456
  }
3731
3457
  return current;
@@ -4010,14 +3736,14 @@ function responseStreamEvents(turn, response, includeProviderArtifacts = true) {
4010
3736
  if (item.type === "reasoning") {
4011
3737
  if (item.details === void 0) {
4012
3738
  if (item.text.length > 0) {
4013
- events.push(reasoningDeltaEvent2(turn, item.text, { id: item.id }));
3739
+ events.push(reasoningDeltaEvent(turn, item.text, { id: item.id }));
4014
3740
  }
4015
3741
  continue;
4016
3742
  }
4017
3743
  for (const content of item.details) {
4018
3744
  const delta = content.type === "encrypted" || content.type === "redacted" ? content.data : content.text;
4019
3745
  events.push(
4020
- reasoningDeltaEvent2(turn, delta, {
3746
+ reasoningDeltaEvent(turn, delta, {
4021
3747
  id: item.id,
4022
3748
  contentType: content.type,
4023
3749
  signature: content.type === "text" ? content.signature : void 0
@@ -4073,7 +3799,7 @@ function generationArtifacts(messages) {
4073
3799
  if (contextUsage !== void 0) artifacts.contextUsage = contextUsage;
4074
3800
  return artifacts;
4075
3801
  }
4076
- function reasoningDeltaEvent2(turn, delta, details = {}) {
3802
+ function reasoningDeltaEvent(turn, delta, details = {}) {
4077
3803
  const event = {
4078
3804
  type: "reasoning_delta",
4079
3805
  turn,
@@ -4175,6 +3901,14 @@ function structuredOutputRetryEventAttributes(error, retryRequest) {
4175
3901
  }
4176
3902
  return attributes;
4177
3903
  }
3904
+ function providerOutputRetryEventAttributes(error, cumulativeUsage, attemptUsage) {
3905
+ const resolvedAttemptUsage = attemptUsage ?? completionProviderOutputErrorUsage(error);
3906
+ if (resolvedAttemptUsage === void 0) return void 0;
3907
+ return {
3908
+ attemptUsage: usageEventValue(resolvedAttemptUsage),
3909
+ cumulativeUsage: usageEventValue(cumulativeUsage)
3910
+ };
3911
+ }
4178
3912
  function usageEventValue(usage) {
4179
3913
  const value = {
4180
3914
  inputTokens: usage.inputTokens,
@@ -4776,6 +4510,9 @@ var Agent = class {
4776
4510
  this.context = snapshotAgentContext(resolved.context);
4777
4511
  this.temperature = resolved.temperature;
4778
4512
  this.maxTokens = resolved.maxTokens;
4513
+ if (resolved.providerOptions !== void 0) {
4514
+ assertJsonObject(resolved.providerOptions, "Agent providerOptions");
4515
+ }
4779
4516
  this.providerOptions = cloneFrozenPlainData(resolved.providerOptions);
4780
4517
  this.retries = cloneFrozenPlainData(resolved.retries);
4781
4518
  const preparedTools = prepareAgentTools(resolved);
@@ -4829,4 +4566,4 @@ export {
4829
4566
  markResolvedAgentOptions,
4830
4567
  Agent
4831
4568
  };
4832
- //# sourceMappingURL=chunk-QXSVVYQK.js.map
4569
+ //# sourceMappingURL=chunk-PISJAAMX.js.map