@ai-matrx/agents 0.22.0 → 0.24.0

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 (36) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/content-transfer/index.cjs +33 -33
  3. package/dist/content-transfer/index.cjs.map +1 -1
  4. package/dist/content-transfer/index.d.cts +1 -1
  5. package/dist/content-transfer/index.d.ts +1 -1
  6. package/dist/content-transfer/index.js +33 -33
  7. package/dist/content-transfer/index.js.map +1 -1
  8. package/dist/content-transfer/react/index.cjs +33 -33
  9. package/dist/content-transfer/react/index.cjs.map +1 -1
  10. package/dist/content-transfer/react/index.js +33 -33
  11. package/dist/content-transfer/react/index.js.map +1 -1
  12. package/dist/index.cjs +404 -131
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +404 -131
  17. package/dist/index.js.map +1 -1
  18. package/dist/mandates/index.cjs +2 -2
  19. package/dist/mandates/index.cjs.map +1 -1
  20. package/dist/mandates/index.d.cts +4 -4
  21. package/dist/mandates/index.d.ts +4 -4
  22. package/dist/mandates/index.js +2 -2
  23. package/dist/mandates/index.js.map +1 -1
  24. package/dist/matrx/index.cjs +404 -131
  25. package/dist/matrx/index.cjs.map +1 -1
  26. package/dist/matrx/index.d.cts +242 -4
  27. package/dist/matrx/index.d.ts +242 -4
  28. package/dist/matrx/index.js +404 -131
  29. package/dist/matrx/index.js.map +1 -1
  30. package/dist/react/index.cjs +41 -41
  31. package/dist/react/index.cjs.map +1 -1
  32. package/dist/react/index.js +41 -41
  33. package/dist/react/index.js.map +1 -1
  34. package/mandates/snapshots/keys.0.23.0.json +652 -0
  35. package/mandates/snapshots/keys.0.24.0.json +652 -0
  36. package/package.json +4 -4
@@ -21,6 +21,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var matrx_exports = {};
22
22
  __export(matrx_exports, {
23
23
  MATRX_AI_API_VERSION_DEFAULT: () => MATRX_AI_API_VERSION_DEFAULT,
24
+ MATRX_LIVE_STREAM_UNAVAILABLE: () => MATRX_LIVE_STREAM_UNAVAILABLE,
25
+ MATRX_RESUME_CONFLICT: () => MATRX_RESUME_CONFLICT,
26
+ MATRX_RUN_IN_PROGRESS: () => MATRX_RUN_IN_PROGRESS,
24
27
  MatrxApiError: () => MatrxApiError,
25
28
  MatrxRunError: () => MatrxRunError,
26
29
  OrganizationContextError: () => OrganizationContextError,
@@ -41,9 +44,12 @@ __export(matrx_exports, {
41
44
  fetchWithMatrxProtocolFallback: () => fetchWithMatrxProtocolFallback,
42
45
  followRuntimeOperationEvents: () => followRuntimeOperationEvents,
43
46
  followRuntimeOperationToEnd: () => followRuntimeOperationToEnd,
47
+ followWorkflowRunEvents: () => followWorkflowRunEvents,
44
48
  getRuntimeOperationStatus: () => getRuntimeOperationStatus,
45
49
  getRuntimeOperationsByLink: () => getRuntimeOperationsByLink,
46
50
  isCoveredAiPath: () => isCoveredAiPath,
51
+ isLiveStreamUnavailable: () => isLiveStreamUnavailable,
52
+ isResumeConflict: () => isResumeConflict,
47
53
  isV2Path: () => isV2Path,
48
54
  listConversationPendingToolCalls: () => listConversationPendingToolCalls,
49
55
  listRuntimeOperationEvents: () => listRuntimeOperationEvents,
@@ -52,15 +58,25 @@ __export(matrx_exports, {
52
58
  newEphemeralConversationStart: () => newEphemeralConversationStart,
53
59
  newStoredConversationStart: () => newStoredConversationStart,
54
60
  normalizeMatrxError: () => normalizeMatrxError,
61
+ openMatrxStream: () => openMatrxStream,
62
+ providerSessionFailureBody: () => providerSessionFailureBody,
63
+ readLiveRunRejoin: () => readLiveRunRejoin,
64
+ readLiveRunRequestId: () => readLiveRunRequestId,
65
+ readMatrxErrorCode: () => readMatrxErrorCode,
55
66
  rejoinRuntimeOperation: () => rejoinRuntimeOperation,
67
+ reportProviderSessionFailure: () => reportProviderSessionFailure,
56
68
  requireOrganizationContext: () => requireOrganizationContext,
57
69
  resumeAgentConversation: () => resumeAgentConversation,
70
+ resumeOrRejoin: () => resumeOrRejoin,
58
71
  runAgentToCompletion: () => runAgentToCompletion,
72
+ runtimeOperationRejoinPath: () => runtimeOperationRejoinPath,
59
73
  startAgentRun: () => startAgentRun,
60
74
  startMandateRun: () => startMandateRun,
75
+ streamErrorText: () => streamErrorText,
61
76
  submitAgentToolResults: () => submitAgentToolResults,
62
77
  toV1FallbackUrl: () => toV1FallbackUrl,
63
- toV2Path: () => toV2Path
78
+ toV2Path: () => toV2Path,
79
+ withRunOrganization: () => withRunOrganization
64
80
  });
65
81
  module.exports = __toCommonJS(matrx_exports);
66
82
 
@@ -764,136 +780,6 @@ async function requestStream(transport, path, options) {
764
780
  return response;
765
781
  }
766
782
 
767
- // matrx/run.ts
768
- async function streamCall(transport, path, body, options) {
769
- const response = await requestStream(transport, path, {
770
- method: "POST",
771
- // This client IS the streaming path — `stream: true` always, last so a
772
- // caller-supplied value can never flip the response off NDJSON.
773
- body: { ...body, stream: true },
774
- ...options.signal ? { signal: options.signal } : {}
775
- });
776
- return toRunHandle(response, options);
777
- }
778
- function startAgentRun(transport, agentId, request, options = {}) {
779
- return streamCall(
780
- transport,
781
- `/ai/agents/${encodePathSegment(agentId)}`,
782
- request,
783
- options
784
- );
785
- }
786
- function startMandateRun(transport, mandateKey, request, options = {}) {
787
- return streamCall(
788
- transport,
789
- `/ai/mandates/${encodePathSegment(mandateKey)}`,
790
- request,
791
- options
792
- );
793
- }
794
- function continueAgentConversation(transport, conversationId, request, options = {}) {
795
- return streamCall(
796
- transport,
797
- `/ai/conversations/${encodePathSegment(conversationId)}`,
798
- request,
799
- options
800
- );
801
- }
802
- function resumeAgentConversation(transport, conversationId, request = {}, options = {}) {
803
- return streamCall(
804
- transport,
805
- `/ai/conversations/${encodePathSegment(conversationId)}/resume`,
806
- request,
807
- options
808
- );
809
- }
810
- function cancelAgentRun(transport, requestId, options = {}) {
811
- const query = buildQuery(
812
- options.mode === "interrupt" ? { mode: "interrupt" } : {}
813
- );
814
- return requestJson(
815
- transport,
816
- `/ai/cancel/${encodePathSegment(requestId)}${query}`,
817
- {
818
- method: "POST",
819
- ...options.signal ? { signal: options.signal } : {}
820
- }
821
- );
822
- }
823
- var MatrxRunError = class extends Error {
824
- name = "MatrxRunError";
825
- /** The verbatim `error` event payload, when one fired. */
826
- errorPayload;
827
- /** The `user_request` completion status (`"failed"` | `"cancelled"`), when that was the trigger. */
828
- completionStatus;
829
- /** Text streamed before the failure — partial content never vanishes. */
830
- partialText;
831
- constructor(args) {
832
- super(args.message);
833
- this.errorPayload = args.errorPayload ?? null;
834
- this.completionStatus = args.completionStatus ?? null;
835
- this.partialText = args.partialText ?? "";
836
- }
837
- };
838
- function isRecord3(value) {
839
- return typeof value === "object" && value !== null && !Array.isArray(value);
840
- }
841
- function stringField(value, key) {
842
- if (!isRecord3(value)) return null;
843
- const field = value[key];
844
- return typeof field === "string" && field ? field : null;
845
- }
846
- async function runAgentToCompletion(transport, agentId, request, options = {}) {
847
- const handle = await startAgentRun(transport, agentId, request, options);
848
- let text = "";
849
- let completion = null;
850
- let failure = null;
851
- for await (const envelope of handle.events) {
852
- options.onEvent?.(envelope);
853
- if (envelope.event === "chunk") {
854
- const chunk = stringField(envelope.data, "text");
855
- if (chunk !== null) {
856
- text += chunk;
857
- options.onChunk?.(text);
858
- }
859
- continue;
860
- }
861
- if (envelope.event === "error" && failure === null) {
862
- const payload = isRecord3(envelope.data) ? envelope.data : null;
863
- failure = new MatrxRunError({
864
- message: stringField(payload, "user_message") ?? stringField(payload, "message") ?? "The agent run failed",
865
- errorPayload: payload,
866
- partialText: text
867
- });
868
- continue;
869
- }
870
- if (envelope.event !== "completion" || !isRecord3(envelope.data)) continue;
871
- if (envelope.data.operation !== "user_request") continue;
872
- completion = envelope.data;
873
- const status = envelope.data.status;
874
- if ((status === "failed" || status === "cancelled") && failure === null) {
875
- const result = isRecord3(envelope.data.result) ? envelope.data.result : null;
876
- failure = new MatrxRunError({
877
- message: stringField(result, "error") ?? stringField(result, "user_message") ?? `The agent run ${status}`,
878
- completionStatus: status,
879
- partialText: text
880
- });
881
- }
882
- }
883
- if (failure) throw failure;
884
- if (!text && completion) {
885
- const result = completion.result;
886
- const output = stringField(result, "output");
887
- if (output !== null) text = output;
888
- }
889
- return {
890
- text,
891
- requestId: handle.requestId,
892
- conversationId: handle.conversationId,
893
- completion
894
- };
895
- }
896
-
897
783
  // stream/sse.ts
898
784
  var FRAME_SEPARATOR = /\r\n\r\n|\n\n|\r\r/;
899
785
  var LINE_SEPARATOR = /\r\n|\n|\r/;
@@ -1120,6 +1006,393 @@ async function rejoinRuntimeOperation(transport, requestId, options = {}) {
1120
1006
  return toRunHandle(response, options);
1121
1007
  }
1122
1008
 
1009
+ // matrx/rejoin.ts
1010
+ var MATRX_RUN_IN_PROGRESS = "run_in_progress";
1011
+ var MATRX_RESUME_CONFLICT = "resume_conflict";
1012
+ var MATRX_LIVE_STREAM_UNAVAILABLE = "live_stream_unavailable";
1013
+ function isRecord3(value) {
1014
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1015
+ }
1016
+ function nonBlank(value) {
1017
+ return typeof value === "string" && value.trim() ? value : null;
1018
+ }
1019
+ function detailCandidates(body) {
1020
+ if (!isRecord3(body)) return [];
1021
+ const out = [];
1022
+ if (isRecord3(body.detail)) out.push(body.detail);
1023
+ if (isRecord3(body.details)) out.push(body.details);
1024
+ out.push(body);
1025
+ return out;
1026
+ }
1027
+ function statusOf(error) {
1028
+ if (!isRecord3(error) && !(error instanceof Error)) return null;
1029
+ const status = error.status;
1030
+ return typeof status === "number" ? status : null;
1031
+ }
1032
+ function bodyOf(error) {
1033
+ if (!isRecord3(error) && !(error instanceof Error)) return void 0;
1034
+ return error.serverDetail;
1035
+ }
1036
+ function readMatrxErrorCode(error) {
1037
+ for (const candidate of detailCandidates(bodyOf(error))) {
1038
+ const code = nonBlank(candidate.code);
1039
+ if (code) return code;
1040
+ }
1041
+ for (const candidate of detailCandidates(bodyOf(error))) {
1042
+ const code = nonBlank(candidate.error);
1043
+ if (code) return code;
1044
+ }
1045
+ return null;
1046
+ }
1047
+ function firstString(candidates, key) {
1048
+ for (const candidate of candidates) {
1049
+ const value = nonBlank(candidate[key]);
1050
+ if (value) return value.trim();
1051
+ }
1052
+ return null;
1053
+ }
1054
+ function readLiveRunRejoin(error) {
1055
+ if (statusOf(error) !== 409) return null;
1056
+ const candidates = detailCandidates(bodyOf(error));
1057
+ if (candidates.length === 0) return null;
1058
+ const code = readMatrxErrorCode(error);
1059
+ if (code !== MATRX_RUN_IN_PROGRESS && code !== MATRX_RESUME_CONFLICT) return null;
1060
+ const liveRequestId = firstString(candidates, "live_request_id");
1061
+ const pathFromBody = firstString(candidates, "rejoin_path");
1062
+ const rejoinPath = pathFromBody && pathFromBody.startsWith("/") ? pathFromBody : liveRequestId ? runtimeOperationRejoinPath(liveRequestId) : null;
1063
+ if (!rejoinPath) return null;
1064
+ const root = bodyOf(error);
1065
+ return {
1066
+ liveRequestId,
1067
+ rejoinPath,
1068
+ runId: firstString(candidates, "run_id"),
1069
+ code,
1070
+ body: isRecord3(root) ? root : {}
1071
+ };
1072
+ }
1073
+ function readLiveRunRequestId(error) {
1074
+ return readLiveRunRejoin(error)?.liveRequestId ?? null;
1075
+ }
1076
+ function isResumeConflict(error) {
1077
+ return statusOf(error) === 409 && readMatrxErrorCode(error) === MATRX_RESUME_CONFLICT && readLiveRunRejoin(error) === null;
1078
+ }
1079
+ function isLiveStreamUnavailable(error) {
1080
+ return statusOf(error) === 409 && readMatrxErrorCode(error) === MATRX_LIVE_STREAM_UNAVAILABLE;
1081
+ }
1082
+ function runtimeOperationRejoinPath(requestId) {
1083
+ return `/runtime/operations/${encodePathSegment(requestId)}/rejoin`;
1084
+ }
1085
+ function streamErrorText(eventOrPayload) {
1086
+ if (!isRecord3(eventOrPayload)) return null;
1087
+ const payload = typeof eventOrPayload.event === "string" && isRecord3(eventOrPayload.data) ? eventOrPayload.data : eventOrPayload;
1088
+ return nonBlank(payload.user_message) ?? nonBlank(payload.message);
1089
+ }
1090
+ async function openMatrxStream(transport, path, options = {}) {
1091
+ const response = await requestStream(transport, path, {
1092
+ method: "POST",
1093
+ ...options.body !== void 0 ? { body: options.body } : {},
1094
+ ...options.signal ? { signal: options.signal } : {}
1095
+ });
1096
+ return toRunHandle(response, options);
1097
+ }
1098
+ function withRunOrganization(transport, organizationId) {
1099
+ const orgId = requireOrganizationContext(organizationId);
1100
+ return {
1101
+ fetch: (path, init) => transport.fetch(path, {
1102
+ ...init,
1103
+ headers: { ...init.headers, "X-Organization-Id": orgId }
1104
+ })
1105
+ };
1106
+ }
1107
+ async function followWorkflowRunEvents(transport, runId, options) {
1108
+ const headers = { Accept: "text/event-stream" };
1109
+ if (options.lastEventId) headers["Last-Event-ID"] = String(options.lastEventId);
1110
+ let response;
1111
+ try {
1112
+ response = await requestStream(
1113
+ transport,
1114
+ `/runs/${encodePathSegment(runId)}/events/stream`,
1115
+ {
1116
+ method: "GET",
1117
+ headers,
1118
+ ...options.signal ? { signal: options.signal } : {}
1119
+ }
1120
+ );
1121
+ } catch (error) {
1122
+ if (options.signal?.aborted) return { ended: false };
1123
+ throw error;
1124
+ }
1125
+ try {
1126
+ for await (const frame of readMatrxSseStream(
1127
+ response.body
1128
+ )) {
1129
+ if (frame.event === "end") return { ended: true };
1130
+ if (frame.data === null) continue;
1131
+ let parsed;
1132
+ try {
1133
+ parsed = JSON.parse(frame.data);
1134
+ } catch {
1135
+ continue;
1136
+ }
1137
+ if (!isRecord3(parsed)) continue;
1138
+ options.onEvent(parsed, parsed.event === "node_stream" ? null : frame.seq);
1139
+ }
1140
+ } catch (error) {
1141
+ if (!options.signal?.aborted) throw error;
1142
+ }
1143
+ return { ended: false };
1144
+ }
1145
+ async function drain(handle, onEnvelope) {
1146
+ for await (const envelope of handle.events) onEnvelope(envelope);
1147
+ }
1148
+ async function resumeOrRejoin(transport, resumeCall, options) {
1149
+ const {
1150
+ onEnvelope,
1151
+ organizationId,
1152
+ onRejoin,
1153
+ onOperationEvent,
1154
+ onWorkflowEvent,
1155
+ follow,
1156
+ ...rest
1157
+ } = options;
1158
+ const bound = organizationId ? withRunOrganization(transport, organizationId) : transport;
1159
+ const streamOptions = {
1160
+ ...rest,
1161
+ ...options.signal ? { signal: options.signal } : {}
1162
+ };
1163
+ const signalOnly = options.signal ? { signal: options.signal } : {};
1164
+ let rejoin;
1165
+ try {
1166
+ const handle = await resumeCall(bound, streamOptions);
1167
+ await drain(handle, onEnvelope);
1168
+ return { kind: "resumed", requestId: handle.requestId };
1169
+ } catch (error) {
1170
+ const target = readLiveRunRejoin(error);
1171
+ if (!target) {
1172
+ if (error instanceof MatrxApiError && isResumeConflict(error)) {
1173
+ return { kind: "resume_conflict", error };
1174
+ }
1175
+ throw error;
1176
+ }
1177
+ rejoin = target;
1178
+ }
1179
+ onRejoin?.(rejoin);
1180
+ let unavailableBody;
1181
+ try {
1182
+ const handle = await openMatrxStream(bound, rejoin.rejoinPath, {
1183
+ ...streamOptions,
1184
+ // The rejoin routes take no body model; the reference client posts {}.
1185
+ body: {}
1186
+ });
1187
+ await drain(handle, onEnvelope);
1188
+ return { kind: "rejoined", rejoin };
1189
+ } catch (error) {
1190
+ if (!isLiveStreamUnavailable(error)) throw error;
1191
+ unavailableBody = bodyOf(error);
1192
+ }
1193
+ const runId = firstString(detailCandidates(unavailableBody), "run_id") ?? rejoin.runId;
1194
+ if (runId && rejoin.rejoinPath.startsWith("/runtime/operations/")) {
1195
+ const result2 = await followWorkflowRunEvents(bound, runId, {
1196
+ ...signalOnly,
1197
+ onEvent: (event, seq) => onWorkflowEvent?.(event, seq)
1198
+ });
1199
+ return { kind: "followed_workflow", rejoin, runId, ended: result2.ended };
1200
+ }
1201
+ const liveRequestId = rejoin.liveRequestId;
1202
+ const statusView = liveRequestId ? await getRuntimeOperationStatus(bound, liveRequestId, signalOnly) : null;
1203
+ const operation = statusView?.operations.find((op) => !op.is_terminal) ?? statusView?.operations[0] ?? null;
1204
+ if (!operation) {
1205
+ return { kind: "followed", rejoin, executionId: null, ended: false, status: null };
1206
+ }
1207
+ if (operation.is_terminal) {
1208
+ return {
1209
+ kind: "followed",
1210
+ rejoin,
1211
+ executionId: operation.execution_id,
1212
+ ended: true,
1213
+ status: operation.status
1214
+ };
1215
+ }
1216
+ const result = await followRuntimeOperationToEnd(bound, operation.execution_id, {
1217
+ ...follow,
1218
+ lastEventSeq: operation.last_event_seq,
1219
+ ...signalOnly,
1220
+ onEvent: (event) => onOperationEvent?.(event)
1221
+ });
1222
+ return {
1223
+ kind: "followed",
1224
+ rejoin,
1225
+ executionId: operation.execution_id,
1226
+ ended: result.ended,
1227
+ status: result.status
1228
+ };
1229
+ }
1230
+
1231
+ // matrx/run.ts
1232
+ async function streamCall(transport, path, body, options) {
1233
+ const response = await requestStream(transport, path, {
1234
+ method: "POST",
1235
+ // This client IS the streaming path — `stream: true` always, last so a
1236
+ // caller-supplied value can never flip the response off NDJSON.
1237
+ body: { ...body, stream: true },
1238
+ ...options.signal ? { signal: options.signal } : {}
1239
+ });
1240
+ return toRunHandle(response, options);
1241
+ }
1242
+ function startAgentRun(transport, agentId, request, options = {}) {
1243
+ return streamCall(
1244
+ transport,
1245
+ `/ai/agents/${encodePathSegment(agentId)}`,
1246
+ request,
1247
+ options
1248
+ );
1249
+ }
1250
+ function startMandateRun(transport, mandateKey, request, options = {}) {
1251
+ return streamCall(
1252
+ transport,
1253
+ `/ai/mandates/${encodePathSegment(mandateKey)}`,
1254
+ request,
1255
+ options
1256
+ );
1257
+ }
1258
+ function continueAgentConversation(transport, conversationId, request, options = {}) {
1259
+ return streamCall(
1260
+ transport,
1261
+ `/ai/conversations/${encodePathSegment(conversationId)}`,
1262
+ request,
1263
+ options
1264
+ );
1265
+ }
1266
+ function resumeAgentConversation(transport, conversationId, request = {}, options = {}) {
1267
+ return streamCall(
1268
+ transport,
1269
+ `/ai/conversations/${encodePathSegment(conversationId)}/resume`,
1270
+ request,
1271
+ options
1272
+ );
1273
+ }
1274
+ function cancelAgentRun(transport, requestId, options = {}) {
1275
+ const query = buildQuery(
1276
+ options.mode === "interrupt" ? { mode: "interrupt" } : {}
1277
+ );
1278
+ return requestJson(
1279
+ transport,
1280
+ `/ai/cancel/${encodePathSegment(requestId)}${query}`,
1281
+ {
1282
+ method: "POST",
1283
+ ...options.signal ? { signal: options.signal } : {}
1284
+ }
1285
+ );
1286
+ }
1287
+ var MatrxRunError = class extends Error {
1288
+ name = "MatrxRunError";
1289
+ /** The verbatim `error` event payload, when one fired. */
1290
+ errorPayload;
1291
+ /** The `user_request` completion status (`"failed"` | `"cancelled"`), when that was the trigger. */
1292
+ completionStatus;
1293
+ /** Text streamed before the failure — partial content never vanishes. */
1294
+ partialText;
1295
+ constructor(args) {
1296
+ super(args.message);
1297
+ this.errorPayload = args.errorPayload ?? null;
1298
+ this.completionStatus = args.completionStatus ?? null;
1299
+ this.partialText = args.partialText ?? "";
1300
+ }
1301
+ };
1302
+ function isRecord4(value) {
1303
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1304
+ }
1305
+ function stringField(value, key) {
1306
+ if (!isRecord4(value)) return null;
1307
+ const field = value[key];
1308
+ return typeof field === "string" && field ? field : null;
1309
+ }
1310
+ async function runAgentToCompletion(transport, agentId, request, options = {}) {
1311
+ const handle = await startAgentRun(transport, agentId, request, options);
1312
+ let text = "";
1313
+ let completion = null;
1314
+ let failure = null;
1315
+ for await (const envelope of handle.events) {
1316
+ options.onEvent?.(envelope);
1317
+ if (envelope.event === "chunk") {
1318
+ const chunk = stringField(envelope.data, "text");
1319
+ if (chunk !== null) {
1320
+ text += chunk;
1321
+ options.onChunk?.(text);
1322
+ }
1323
+ continue;
1324
+ }
1325
+ if (envelope.event === "error" && failure === null) {
1326
+ const payload = isRecord4(envelope.data) ? envelope.data : null;
1327
+ failure = new MatrxRunError({
1328
+ message: streamErrorText(payload) ?? "The agent run failed",
1329
+ errorPayload: payload,
1330
+ partialText: text
1331
+ });
1332
+ continue;
1333
+ }
1334
+ if (envelope.event !== "completion" || !isRecord4(envelope.data)) continue;
1335
+ if (envelope.data.operation !== "user_request") continue;
1336
+ completion = envelope.data;
1337
+ const status = envelope.data.status;
1338
+ if ((status === "failed" || status === "cancelled") && failure === null) {
1339
+ const result = isRecord4(envelope.data.result) ? envelope.data.result : null;
1340
+ failure = new MatrxRunError({
1341
+ message: stringField(result, "error") ?? stringField(result, "user_message") ?? `The agent run ${status}`,
1342
+ completionStatus: status,
1343
+ partialText: text
1344
+ });
1345
+ }
1346
+ }
1347
+ if (failure) throw failure;
1348
+ if (!text && completion) {
1349
+ const result = completion.result;
1350
+ const output = stringField(result, "output");
1351
+ if (output !== null) text = output;
1352
+ }
1353
+ return {
1354
+ text,
1355
+ requestId: handle.requestId,
1356
+ conversationId: handle.conversationId,
1357
+ completion
1358
+ };
1359
+ }
1360
+
1361
+ // matrx/provider-failures.ts
1362
+ var clip = (value, max) => value.length > max ? value.slice(0, max) : value;
1363
+ function providerSessionFailureBody(failure) {
1364
+ const message = failure.message?.trim() || failure.error_type?.trim() || (failure.status_code ? `HTTP ${failure.status_code}` : "provider session failed");
1365
+ const body = {
1366
+ provider: failure.provider,
1367
+ message: clip(message, 4e3)
1368
+ };
1369
+ if (failure.model?.trim()) body.model = clip(failure.model.trim(), 200);
1370
+ if (failure.error_type?.trim()) body.error_type = clip(failure.error_type.trim(), 200);
1371
+ if (typeof failure.status_code === "number" && Number.isInteger(failure.status_code) && failure.status_code >= 100 && failure.status_code <= 599) {
1372
+ body.status_code = failure.status_code;
1373
+ }
1374
+ return body;
1375
+ }
1376
+ async function reportProviderSessionFailure(transport, failure, options = {}) {
1377
+ try {
1378
+ return await requestJson(
1379
+ transport,
1380
+ "/broker/provider-failures",
1381
+ {
1382
+ method: "POST",
1383
+ body: providerSessionFailureBody(failure),
1384
+ ...options.signal ? { signal: options.signal } : {}
1385
+ }
1386
+ );
1387
+ } catch (error) {
1388
+ console.warn(
1389
+ `[provider-failures] could not report a ${failure.provider} session failure`,
1390
+ error
1391
+ );
1392
+ return null;
1393
+ }
1394
+ }
1395
+
1123
1396
  // matrx/tools.ts
1124
1397
  function submitAgentToolResults(transport, conversationId, results, options = {}) {
1125
1398
  return requestJson(