@ai-matrx/agents 0.22.0 → 0.23.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.
@@ -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,
@@ -44,6 +47,8 @@ __export(matrx_exports, {
44
47
  getRuntimeOperationStatus: () => getRuntimeOperationStatus,
45
48
  getRuntimeOperationsByLink: () => getRuntimeOperationsByLink,
46
49
  isCoveredAiPath: () => isCoveredAiPath,
50
+ isLiveStreamUnavailable: () => isLiveStreamUnavailable,
51
+ isResumeConflict: () => isResumeConflict,
47
52
  isV2Path: () => isV2Path,
48
53
  listConversationPendingToolCalls: () => listConversationPendingToolCalls,
49
54
  listRuntimeOperationEvents: () => listRuntimeOperationEvents,
@@ -52,15 +57,24 @@ __export(matrx_exports, {
52
57
  newEphemeralConversationStart: () => newEphemeralConversationStart,
53
58
  newStoredConversationStart: () => newStoredConversationStart,
54
59
  normalizeMatrxError: () => normalizeMatrxError,
60
+ openMatrxStream: () => openMatrxStream,
61
+ providerSessionFailureBody: () => providerSessionFailureBody,
62
+ readLiveRunRequestId: () => readLiveRunRequestId,
63
+ readMatrxErrorCode: () => readMatrxErrorCode,
55
64
  rejoinRuntimeOperation: () => rejoinRuntimeOperation,
65
+ reportProviderSessionFailure: () => reportProviderSessionFailure,
56
66
  requireOrganizationContext: () => requireOrganizationContext,
57
67
  resumeAgentConversation: () => resumeAgentConversation,
68
+ resumeOrRejoin: () => resumeOrRejoin,
58
69
  runAgentToCompletion: () => runAgentToCompletion,
70
+ runtimeOperationRejoinPath: () => runtimeOperationRejoinPath,
59
71
  startAgentRun: () => startAgentRun,
60
72
  startMandateRun: () => startMandateRun,
73
+ streamErrorText: () => streamErrorText,
61
74
  submitAgentToolResults: () => submitAgentToolResults,
62
75
  toV1FallbackUrl: () => toV1FallbackUrl,
63
- toV2Path: () => toV2Path
76
+ toV2Path: () => toV2Path,
77
+ withRunOrganization: () => withRunOrganization
64
78
  });
65
79
  module.exports = __toCommonJS(matrx_exports);
66
80
 
@@ -764,136 +778,6 @@ async function requestStream(transport, path, options) {
764
778
  return response;
765
779
  }
766
780
 
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
781
  // stream/sse.ts
898
782
  var FRAME_SEPARATOR = /\r\n\r\n|\n\n|\r\r/;
899
783
  var LINE_SEPARATOR = /\r\n|\n|\r/;
@@ -1120,6 +1004,317 @@ async function rejoinRuntimeOperation(transport, requestId, options = {}) {
1120
1004
  return toRunHandle(response, options);
1121
1005
  }
1122
1006
 
1007
+ // matrx/rejoin.ts
1008
+ var MATRX_RUN_IN_PROGRESS = "run_in_progress";
1009
+ var MATRX_RESUME_CONFLICT = "resume_conflict";
1010
+ var MATRX_LIVE_STREAM_UNAVAILABLE = "live_stream_unavailable";
1011
+ function isRecord3(value) {
1012
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1013
+ }
1014
+ function nonBlank(value) {
1015
+ return typeof value === "string" && value.trim() ? value : null;
1016
+ }
1017
+ function detailCandidates(body) {
1018
+ if (!isRecord3(body)) return [];
1019
+ const out = [];
1020
+ if (isRecord3(body.detail)) out.push(body.detail);
1021
+ if (isRecord3(body.details)) out.push(body.details);
1022
+ out.push(body);
1023
+ return out;
1024
+ }
1025
+ function statusOf(error) {
1026
+ if (!isRecord3(error) && !(error instanceof Error)) return null;
1027
+ const status = error.status;
1028
+ return typeof status === "number" ? status : null;
1029
+ }
1030
+ function bodyOf(error) {
1031
+ if (!isRecord3(error) && !(error instanceof Error)) return void 0;
1032
+ return error.serverDetail;
1033
+ }
1034
+ function readMatrxErrorCode(error) {
1035
+ for (const candidate of detailCandidates(bodyOf(error))) {
1036
+ const code = nonBlank(candidate.code);
1037
+ if (code) return code;
1038
+ }
1039
+ for (const candidate of detailCandidates(bodyOf(error))) {
1040
+ const code = nonBlank(candidate.error);
1041
+ if (code) return code;
1042
+ }
1043
+ return null;
1044
+ }
1045
+ function readLiveRunRequestId(error) {
1046
+ if (statusOf(error) !== 409) return null;
1047
+ for (const candidate of detailCandidates(bodyOf(error))) {
1048
+ if (candidate.code !== MATRX_RUN_IN_PROGRESS) continue;
1049
+ const live = nonBlank(candidate.live_request_id);
1050
+ if (live) return live.trim();
1051
+ }
1052
+ return null;
1053
+ }
1054
+ function isResumeConflict(error) {
1055
+ return statusOf(error) === 409 && readMatrxErrorCode(error) === MATRX_RESUME_CONFLICT;
1056
+ }
1057
+ function isLiveStreamUnavailable(error) {
1058
+ return statusOf(error) === 409 && readMatrxErrorCode(error) === MATRX_LIVE_STREAM_UNAVAILABLE;
1059
+ }
1060
+ function runtimeOperationRejoinPath(requestId) {
1061
+ return `/runtime/operations/${encodePathSegment(requestId)}/rejoin`;
1062
+ }
1063
+ function streamErrorText(eventOrPayload) {
1064
+ if (!isRecord3(eventOrPayload)) return null;
1065
+ const payload = typeof eventOrPayload.event === "string" && isRecord3(eventOrPayload.data) ? eventOrPayload.data : eventOrPayload;
1066
+ return nonBlank(payload.user_message) ?? nonBlank(payload.message);
1067
+ }
1068
+ async function openMatrxStream(transport, path, options = {}) {
1069
+ const response = await requestStream(transport, path, {
1070
+ method: "POST",
1071
+ ...options.body !== void 0 ? { body: options.body } : {},
1072
+ ...options.signal ? { signal: options.signal } : {}
1073
+ });
1074
+ return toRunHandle(response, options);
1075
+ }
1076
+ function withRunOrganization(transport, organizationId) {
1077
+ const orgId = requireOrganizationContext(organizationId);
1078
+ return {
1079
+ fetch: (path, init) => transport.fetch(path, {
1080
+ ...init,
1081
+ headers: { ...init.headers, "X-Organization-Id": orgId }
1082
+ })
1083
+ };
1084
+ }
1085
+ async function drain(handle, onEnvelope) {
1086
+ for await (const envelope of handle.events) onEnvelope(envelope);
1087
+ }
1088
+ async function resumeOrRejoin(transport, resumeCall, options) {
1089
+ const { onEnvelope, organizationId, onRejoin, onOperationEvent, follow, ...rest } = options;
1090
+ const bound = organizationId ? withRunOrganization(transport, organizationId) : transport;
1091
+ const streamOptions = {
1092
+ ...rest,
1093
+ ...options.signal ? { signal: options.signal } : {}
1094
+ };
1095
+ let liveRequestId;
1096
+ try {
1097
+ const handle = await resumeCall(bound, streamOptions);
1098
+ await drain(handle, onEnvelope);
1099
+ return { kind: "resumed", requestId: handle.requestId };
1100
+ } catch (error) {
1101
+ if (error instanceof MatrxApiError && isResumeConflict(error)) {
1102
+ return { kind: "resume_conflict", error };
1103
+ }
1104
+ const live = readLiveRunRequestId(error);
1105
+ if (!live) throw error;
1106
+ liveRequestId = live;
1107
+ }
1108
+ onRejoin?.(liveRequestId);
1109
+ try {
1110
+ const handle = await rejoinRuntimeOperation(bound, liveRequestId, streamOptions);
1111
+ await drain(handle, onEnvelope);
1112
+ return { kind: "rejoined", liveRequestId };
1113
+ } catch (error) {
1114
+ if (!isLiveStreamUnavailable(error)) throw error;
1115
+ }
1116
+ const statusView = await getRuntimeOperationStatus(bound, liveRequestId, {
1117
+ ...options.signal ? { signal: options.signal } : {}
1118
+ });
1119
+ const operation = statusView?.operations.find((op) => !op.is_terminal) ?? statusView?.operations[0] ?? null;
1120
+ if (!operation) {
1121
+ return {
1122
+ kind: "followed",
1123
+ liveRequestId,
1124
+ executionId: null,
1125
+ ended: false,
1126
+ status: null
1127
+ };
1128
+ }
1129
+ if (operation.is_terminal) {
1130
+ return {
1131
+ kind: "followed",
1132
+ liveRequestId,
1133
+ executionId: operation.execution_id,
1134
+ ended: true,
1135
+ status: operation.status
1136
+ };
1137
+ }
1138
+ const result = await followRuntimeOperationToEnd(bound, operation.execution_id, {
1139
+ ...follow,
1140
+ lastEventSeq: operation.last_event_seq,
1141
+ ...options.signal ? { signal: options.signal } : {},
1142
+ onEvent: (event) => onOperationEvent?.(event)
1143
+ });
1144
+ return {
1145
+ kind: "followed",
1146
+ liveRequestId,
1147
+ executionId: operation.execution_id,
1148
+ ended: result.ended,
1149
+ status: result.status
1150
+ };
1151
+ }
1152
+
1153
+ // matrx/run.ts
1154
+ async function streamCall(transport, path, body, options) {
1155
+ const response = await requestStream(transport, path, {
1156
+ method: "POST",
1157
+ // This client IS the streaming path — `stream: true` always, last so a
1158
+ // caller-supplied value can never flip the response off NDJSON.
1159
+ body: { ...body, stream: true },
1160
+ ...options.signal ? { signal: options.signal } : {}
1161
+ });
1162
+ return toRunHandle(response, options);
1163
+ }
1164
+ function startAgentRun(transport, agentId, request, options = {}) {
1165
+ return streamCall(
1166
+ transport,
1167
+ `/ai/agents/${encodePathSegment(agentId)}`,
1168
+ request,
1169
+ options
1170
+ );
1171
+ }
1172
+ function startMandateRun(transport, mandateKey, request, options = {}) {
1173
+ return streamCall(
1174
+ transport,
1175
+ `/ai/mandates/${encodePathSegment(mandateKey)}`,
1176
+ request,
1177
+ options
1178
+ );
1179
+ }
1180
+ function continueAgentConversation(transport, conversationId, request, options = {}) {
1181
+ return streamCall(
1182
+ transport,
1183
+ `/ai/conversations/${encodePathSegment(conversationId)}`,
1184
+ request,
1185
+ options
1186
+ );
1187
+ }
1188
+ function resumeAgentConversation(transport, conversationId, request = {}, options = {}) {
1189
+ return streamCall(
1190
+ transport,
1191
+ `/ai/conversations/${encodePathSegment(conversationId)}/resume`,
1192
+ request,
1193
+ options
1194
+ );
1195
+ }
1196
+ function cancelAgentRun(transport, requestId, options = {}) {
1197
+ const query = buildQuery(
1198
+ options.mode === "interrupt" ? { mode: "interrupt" } : {}
1199
+ );
1200
+ return requestJson(
1201
+ transport,
1202
+ `/ai/cancel/${encodePathSegment(requestId)}${query}`,
1203
+ {
1204
+ method: "POST",
1205
+ ...options.signal ? { signal: options.signal } : {}
1206
+ }
1207
+ );
1208
+ }
1209
+ var MatrxRunError = class extends Error {
1210
+ name = "MatrxRunError";
1211
+ /** The verbatim `error` event payload, when one fired. */
1212
+ errorPayload;
1213
+ /** The `user_request` completion status (`"failed"` | `"cancelled"`), when that was the trigger. */
1214
+ completionStatus;
1215
+ /** Text streamed before the failure — partial content never vanishes. */
1216
+ partialText;
1217
+ constructor(args) {
1218
+ super(args.message);
1219
+ this.errorPayload = args.errorPayload ?? null;
1220
+ this.completionStatus = args.completionStatus ?? null;
1221
+ this.partialText = args.partialText ?? "";
1222
+ }
1223
+ };
1224
+ function isRecord4(value) {
1225
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1226
+ }
1227
+ function stringField(value, key) {
1228
+ if (!isRecord4(value)) return null;
1229
+ const field = value[key];
1230
+ return typeof field === "string" && field ? field : null;
1231
+ }
1232
+ async function runAgentToCompletion(transport, agentId, request, options = {}) {
1233
+ const handle = await startAgentRun(transport, agentId, request, options);
1234
+ let text = "";
1235
+ let completion = null;
1236
+ let failure = null;
1237
+ for await (const envelope of handle.events) {
1238
+ options.onEvent?.(envelope);
1239
+ if (envelope.event === "chunk") {
1240
+ const chunk = stringField(envelope.data, "text");
1241
+ if (chunk !== null) {
1242
+ text += chunk;
1243
+ options.onChunk?.(text);
1244
+ }
1245
+ continue;
1246
+ }
1247
+ if (envelope.event === "error" && failure === null) {
1248
+ const payload = isRecord4(envelope.data) ? envelope.data : null;
1249
+ failure = new MatrxRunError({
1250
+ message: streamErrorText(payload) ?? "The agent run failed",
1251
+ errorPayload: payload,
1252
+ partialText: text
1253
+ });
1254
+ continue;
1255
+ }
1256
+ if (envelope.event !== "completion" || !isRecord4(envelope.data)) continue;
1257
+ if (envelope.data.operation !== "user_request") continue;
1258
+ completion = envelope.data;
1259
+ const status = envelope.data.status;
1260
+ if ((status === "failed" || status === "cancelled") && failure === null) {
1261
+ const result = isRecord4(envelope.data.result) ? envelope.data.result : null;
1262
+ failure = new MatrxRunError({
1263
+ message: stringField(result, "error") ?? stringField(result, "user_message") ?? `The agent run ${status}`,
1264
+ completionStatus: status,
1265
+ partialText: text
1266
+ });
1267
+ }
1268
+ }
1269
+ if (failure) throw failure;
1270
+ if (!text && completion) {
1271
+ const result = completion.result;
1272
+ const output = stringField(result, "output");
1273
+ if (output !== null) text = output;
1274
+ }
1275
+ return {
1276
+ text,
1277
+ requestId: handle.requestId,
1278
+ conversationId: handle.conversationId,
1279
+ completion
1280
+ };
1281
+ }
1282
+
1283
+ // matrx/provider-failures.ts
1284
+ var clip = (value, max) => value.length > max ? value.slice(0, max) : value;
1285
+ function providerSessionFailureBody(failure) {
1286
+ const message = failure.message?.trim() || failure.error_type?.trim() || (failure.status_code ? `HTTP ${failure.status_code}` : "provider session failed");
1287
+ const body = {
1288
+ provider: failure.provider,
1289
+ message: clip(message, 4e3)
1290
+ };
1291
+ if (failure.model?.trim()) body.model = clip(failure.model.trim(), 200);
1292
+ if (failure.error_type?.trim()) body.error_type = clip(failure.error_type.trim(), 200);
1293
+ if (typeof failure.status_code === "number" && Number.isInteger(failure.status_code) && failure.status_code >= 100 && failure.status_code <= 599) {
1294
+ body.status_code = failure.status_code;
1295
+ }
1296
+ return body;
1297
+ }
1298
+ async function reportProviderSessionFailure(transport, failure, options = {}) {
1299
+ try {
1300
+ return await requestJson(
1301
+ transport,
1302
+ "/broker/provider-failures",
1303
+ {
1304
+ method: "POST",
1305
+ body: providerSessionFailureBody(failure),
1306
+ ...options.signal ? { signal: options.signal } : {}
1307
+ }
1308
+ );
1309
+ } catch (error) {
1310
+ console.warn(
1311
+ `[provider-failures] could not report a ${failure.provider} session failure`,
1312
+ error
1313
+ );
1314
+ return null;
1315
+ }
1316
+ }
1317
+
1123
1318
  // matrx/tools.ts
1124
1319
  function submitAgentToolResults(transport, conversationId, results, options = {}) {
1125
1320
  return requestJson(