@ai-matrx/agents 0.5.1 → 0.6.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 (41) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +41 -16
  3. package/dist/index.cjs +415 -40
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +3 -1
  6. package/dist/index.d.ts +3 -1
  7. package/dist/index.js +396 -3
  8. package/dist/index.js.map +1 -1
  9. package/dist/matrx/index.cjs +401 -26
  10. package/dist/matrx/index.cjs.map +1 -1
  11. package/dist/matrx/index.d.cts +345 -1
  12. package/dist/matrx/index.d.ts +345 -1
  13. package/dist/matrx/index.js +382 -3
  14. package/dist/matrx/index.js.map +1 -1
  15. package/dist/presentation/result.cjs +23 -4
  16. package/dist/presentation/result.cjs.map +1 -1
  17. package/dist/presentation/result.js +3 -3
  18. package/dist/presentation/result.js.map +1 -1
  19. package/dist/projection/request.cjs +25 -6
  20. package/dist/projection/request.cjs.map +1 -1
  21. package/dist/projection/request.js +5 -3
  22. package/dist/projection/request.js.map +1 -1
  23. package/dist/projection/workflow.cjs +25 -6
  24. package/dist/projection/workflow.cjs.map +1 -1
  25. package/dist/projection/workflow.js +5 -3
  26. package/dist/projection/workflow.js.map +1 -1
  27. package/dist/react/index.cjs +1038 -0
  28. package/dist/react/index.cjs.map +1 -0
  29. package/dist/react/index.d.cts +540 -0
  30. package/dist/react/index.d.ts +540 -0
  31. package/dist/react/index.js +1016 -0
  32. package/dist/react/index.js.map +1 -0
  33. package/dist/stream/ndjson.cjs +26 -7
  34. package/dist/stream/ndjson.cjs.map +1 -1
  35. package/dist/stream/ndjson.js +6 -3
  36. package/dist/stream/ndjson.js.map +1 -1
  37. package/dist/stream/sse.cjs +25 -6
  38. package/dist/stream/sse.cjs.map +1 -1
  39. package/dist/stream/sse.js +5 -3
  40. package/dist/stream/sse.js.map +1 -1
  41. package/package.json +28 -2
package/dist/index.d.cts CHANGED
@@ -3,4 +3,6 @@ export { MatrxSseFrame, MatrxSseFramer, ReadMatrxSseOptions, createMatrxSseFrame
3
3
  export { projectAgentResultForDisplay } from './presentation/result.cjs';
4
4
  export { AgentProjectionEvent, AgentProjectionOperation, AgentProjectionRenderBlock, AgentProjectionStatus, AgentProjectionTool, AgentRequestProjection, createAgentRequestProjection, projectAgentEvent, projectAgentEvents } from './projection/request.cjs';
5
5
  export { DEFAULT_WORKFLOW_PROJECTION_LIMITS, WorkflowNodeProjection, WorkflowNodeStreamEvent, WorkflowProjectionLimits, WorkflowRenderBlockIssue, WorkflowRenderBlockIssueCode, WorkflowRenderFrameSet, createWorkflowNodeProjection, projectWorkflowNodeEvent } from './projection/workflow.cjs';
6
- export { FollowRuntimeOperationOptions, MatrxAgentStartRequest, MatrxApiError, MatrxCancelResponse, MatrxChatMessage, MatrxClientToolResult, MatrxCompletedRun, MatrxContextAnchor, MatrxConversationContinueRequest, MatrxConversationResumeRequest, MatrxConversationStart, MatrxEphemeralConversation, MatrxJsonObject, MatrxJsonValue, MatrxOperationEventsPage, MatrxOperationFollowEvent, MatrxOperationStatusResponse, MatrxOperationsByLinkResponse, MatrxPendingCallSummary, MatrxRequestScope, MatrxRunError, MatrxRunHandle, MatrxRuntimeExecutionStatus, MatrxRuntimeOperationEvent, MatrxRuntimeOperationView, MatrxStoredConversationContinue, MatrxStoredConversationCreate, MatrxStreamCallOptions, MatrxToolResultsResponse, MatrxTransport, MatrxTransportRequest, MatrxTurnFields, RunAgentToCompletionOptions, TERMINAL_MATRX_RUNTIME_STATUSES, cancelAgentRun, continueAgentConversation, continueEphemeralConversationStart, continueStoredConversationStart, extractMatrxErrorCode, extractMatrxErrorMessage, followRuntimeOperationEvents, getRuntimeOperationStatus, getRuntimeOperationsByLink, listConversationPendingToolCalls, listRuntimeOperationEvents, listUserPendingToolCalls, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, rejoinRuntimeOperation, resumeAgentConversation, runAgentToCompletion, startAgentRun, submitAgentToolResults } from './matrx/index.cjs';
6
+ export { CreateMatrxTransportOptions, FollowRuntimeOperationOptions, FollowRuntimeOperationToEndOptions, FollowRuntimeOperationToEndResult, MATRX_AI_API_VERSION_DEFAULT, MatrxAgentStartRequest, MatrxAiApiVersion, MatrxApiError, MatrxCallError, MatrxCancelResponse, MatrxChatMessage, MatrxClientToolResult, MatrxCompletedRun, MatrxContextAnchor, MatrxConversationContinueRequest, MatrxConversationResumeRequest, MatrxConversationStart, MatrxEphemeralConversation, MatrxJsonObject, MatrxJsonValue, MatrxOperationEventsPage, MatrxOperationFollowEvent, MatrxOperationStatusResponse, MatrxOperationsByLinkResponse, MatrxPendingCallSummary, MatrxProtocolDowngrade, MatrxProtocolFallbackOptions, MatrxRequestInfo, MatrxRequestScope, MatrxRunError, MatrxRunHandle, MatrxRuntimeExecutionStatus, MatrxRuntimeOperationEvent, MatrxRuntimeOperationView, MatrxStoredConversationContinue, MatrxStoredConversationCreate, MatrxStreamCallOptions, MatrxToolResultsResponse, MatrxTransport, MatrxTransportDiagnostics, MatrxTransportRequest, MatrxTransportTarget, MatrxTurnFields, OrganizationContextError, OrganizationContextErrorCode, RunAgentToCompletionOptions, TERMINAL_MATRX_RUNTIME_STATUSES, V2_COVERED_AI_PATH_TEMPLATES, applyAiApiVersion, applyOrganizationContextHeader, assertQueryOrganizationMatchesContext, cancelAgentRun, continueAgentConversation, continueEphemeralConversationStart, continueStoredConversationStart, createMatrxTransport, extractMatrxErrorCode, extractMatrxErrorMessage, fetchWithMatrxProtocolFallback, followRuntimeOperationEvents, followRuntimeOperationToEnd, getRuntimeOperationStatus, getRuntimeOperationsByLink, isCoveredAiPath, isV2Path, listConversationPendingToolCalls, listRuntimeOperationEvents, listUserPendingToolCalls, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, normalizeMatrxError, rejoinRuntimeOperation, requireOrganizationContext, resumeAgentConversation, runAgentToCompletion, startAgentRun, submitAgentToolResults, toV1FallbackUrl, toV2Path } from './matrx/index.cjs';
7
+ import '@ai-matrx/data';
8
+ import '@ai-matrx/data/net';
package/dist/index.d.ts CHANGED
@@ -3,4 +3,6 @@ export { MatrxSseFrame, MatrxSseFramer, ReadMatrxSseOptions, createMatrxSseFrame
3
3
  export { projectAgentResultForDisplay } from './presentation/result.js';
4
4
  export { AgentProjectionEvent, AgentProjectionOperation, AgentProjectionRenderBlock, AgentProjectionStatus, AgentProjectionTool, AgentRequestProjection, createAgentRequestProjection, projectAgentEvent, projectAgentEvents } from './projection/request.js';
5
5
  export { DEFAULT_WORKFLOW_PROJECTION_LIMITS, WorkflowNodeProjection, WorkflowNodeStreamEvent, WorkflowProjectionLimits, WorkflowRenderBlockIssue, WorkflowRenderBlockIssueCode, WorkflowRenderFrameSet, createWorkflowNodeProjection, projectWorkflowNodeEvent } from './projection/workflow.js';
6
- export { FollowRuntimeOperationOptions, MatrxAgentStartRequest, MatrxApiError, MatrxCancelResponse, MatrxChatMessage, MatrxClientToolResult, MatrxCompletedRun, MatrxContextAnchor, MatrxConversationContinueRequest, MatrxConversationResumeRequest, MatrxConversationStart, MatrxEphemeralConversation, MatrxJsonObject, MatrxJsonValue, MatrxOperationEventsPage, MatrxOperationFollowEvent, MatrxOperationStatusResponse, MatrxOperationsByLinkResponse, MatrxPendingCallSummary, MatrxRequestScope, MatrxRunError, MatrxRunHandle, MatrxRuntimeExecutionStatus, MatrxRuntimeOperationEvent, MatrxRuntimeOperationView, MatrxStoredConversationContinue, MatrxStoredConversationCreate, MatrxStreamCallOptions, MatrxToolResultsResponse, MatrxTransport, MatrxTransportRequest, MatrxTurnFields, RunAgentToCompletionOptions, TERMINAL_MATRX_RUNTIME_STATUSES, cancelAgentRun, continueAgentConversation, continueEphemeralConversationStart, continueStoredConversationStart, extractMatrxErrorCode, extractMatrxErrorMessage, followRuntimeOperationEvents, getRuntimeOperationStatus, getRuntimeOperationsByLink, listConversationPendingToolCalls, listRuntimeOperationEvents, listUserPendingToolCalls, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, rejoinRuntimeOperation, resumeAgentConversation, runAgentToCompletion, startAgentRun, submitAgentToolResults } from './matrx/index.js';
6
+ export { CreateMatrxTransportOptions, FollowRuntimeOperationOptions, FollowRuntimeOperationToEndOptions, FollowRuntimeOperationToEndResult, MATRX_AI_API_VERSION_DEFAULT, MatrxAgentStartRequest, MatrxAiApiVersion, MatrxApiError, MatrxCallError, MatrxCancelResponse, MatrxChatMessage, MatrxClientToolResult, MatrxCompletedRun, MatrxContextAnchor, MatrxConversationContinueRequest, MatrxConversationResumeRequest, MatrxConversationStart, MatrxEphemeralConversation, MatrxJsonObject, MatrxJsonValue, MatrxOperationEventsPage, MatrxOperationFollowEvent, MatrxOperationStatusResponse, MatrxOperationsByLinkResponse, MatrxPendingCallSummary, MatrxProtocolDowngrade, MatrxProtocolFallbackOptions, MatrxRequestInfo, MatrxRequestScope, MatrxRunError, MatrxRunHandle, MatrxRuntimeExecutionStatus, MatrxRuntimeOperationEvent, MatrxRuntimeOperationView, MatrxStoredConversationContinue, MatrxStoredConversationCreate, MatrxStreamCallOptions, MatrxToolResultsResponse, MatrxTransport, MatrxTransportDiagnostics, MatrxTransportRequest, MatrxTransportTarget, MatrxTurnFields, OrganizationContextError, OrganizationContextErrorCode, RunAgentToCompletionOptions, TERMINAL_MATRX_RUNTIME_STATUSES, V2_COVERED_AI_PATH_TEMPLATES, applyAiApiVersion, applyOrganizationContextHeader, assertQueryOrganizationMatchesContext, cancelAgentRun, continueAgentConversation, continueEphemeralConversationStart, continueStoredConversationStart, createMatrxTransport, extractMatrxErrorCode, extractMatrxErrorMessage, fetchWithMatrxProtocolFallback, followRuntimeOperationEvents, followRuntimeOperationToEnd, getRuntimeOperationStatus, getRuntimeOperationsByLink, isCoveredAiPath, isV2Path, listConversationPendingToolCalls, listRuntimeOperationEvents, listUserPendingToolCalls, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, normalizeMatrxError, rejoinRuntimeOperation, requireOrganizationContext, resumeAgentConversation, runAgentToCompletion, startAgentRun, submitAgentToolResults, toV1FallbackUrl, toV2Path } from './matrx/index.js';
7
+ import '@ai-matrx/data';
8
+ import '@ai-matrx/data/net';
package/dist/index.js CHANGED
@@ -834,6 +834,299 @@ function extractMatrxErrorCode(serverDetail) {
834
834
  return null;
835
835
  }
836
836
 
837
+ // matrx/client.ts
838
+ import { isNetError as isNetError2 } from "@ai-matrx/data";
839
+ import { credentialToHeaders } from "@ai-matrx/data";
840
+
841
+ // matrx/org-context.ts
842
+ var OrganizationContextError = class extends Error {
843
+ code;
844
+ constructor(code, message) {
845
+ super(message);
846
+ this.name = "OrganizationContextError";
847
+ this.code = code;
848
+ }
849
+ };
850
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
851
+ function requireOrganizationContext(selectedOrganizationId, overrideOrganizationId) {
852
+ const candidate = overrideOrganizationId ?? selectedOrganizationId;
853
+ if (typeof candidate !== "string" || candidate.trim().length === 0) {
854
+ throw new OrganizationContextError(
855
+ "organization_context_required",
856
+ "Select an organization before sending this request."
857
+ );
858
+ }
859
+ const normalized = candidate.trim();
860
+ if (!UUID_PATTERN.test(normalized)) {
861
+ throw new OrganizationContextError(
862
+ "organization_context_invalid",
863
+ "The selected organization ID is invalid."
864
+ );
865
+ }
866
+ return normalized.toLowerCase();
867
+ }
868
+ function applyOrganizationContextHeader(headers, organizationId) {
869
+ const normalizedOrganizationId = requireOrganizationContext(organizationId);
870
+ for (const [name, value] of Object.entries(headers)) {
871
+ if (name.toLowerCase() === "x-organization-id" && value.trim().toLowerCase() !== normalizedOrganizationId) {
872
+ throw new OrganizationContextError(
873
+ "organization_context_mismatch",
874
+ "X-Organization-Id must match the request context organization."
875
+ );
876
+ }
877
+ }
878
+ const withoutOrganizationHeader = Object.fromEntries(
879
+ Object.entries(headers).filter(
880
+ ([name]) => name.toLowerCase() !== "x-organization-id"
881
+ )
882
+ );
883
+ return {
884
+ ...withoutOrganizationHeader,
885
+ "X-Organization-Id": normalizedOrganizationId
886
+ };
887
+ }
888
+ function assertQueryOrganizationMatchesContext(queryParams, organizationId) {
889
+ if (!queryParams || queryParams.organization_id === void 0) return;
890
+ const queryOrganizationId = requireOrganizationContext(
891
+ String(queryParams.organization_id)
892
+ );
893
+ if (queryOrganizationId !== requireOrganizationContext(organizationId)) {
894
+ throw new OrganizationContextError(
895
+ "organization_context_mismatch",
896
+ "Query organization_id must match the request context organization."
897
+ );
898
+ }
899
+ }
900
+
901
+ // matrx/protocol.ts
902
+ import {
903
+ isNetError,
904
+ resilientFetch
905
+ } from "@ai-matrx/data/net";
906
+ var MATRX_AI_API_VERSION_DEFAULT = "v2";
907
+ var V2_COVERED_AI_PATH_TEMPLATES = [
908
+ "/ai/manual",
909
+ "/ai/chat",
910
+ "/ai/agents/{agent_id}",
911
+ "/ai/agent/{agent_id}",
912
+ // singular alias — behaves identically
913
+ "/ai/conversations/{conversation_id}",
914
+ "/ai/conversation/{conversation_id}",
915
+ // singular alias
916
+ "/ai/prompts/{prompt_id}",
917
+ // saved-prompt execution
918
+ "/ai/mandates/{mandate_key}"
919
+ // THE MANDATE DOOR — `/v2` sibling exists (routers/v2.py)
920
+ ];
921
+ function toV2Path(path) {
922
+ const withLead = path.startsWith("/") ? path : `/${path}`;
923
+ if (withLead.startsWith("/api/")) {
924
+ const rest = withLead.slice("/api".length);
925
+ return rest.startsWith("/v2/") ? withLead : `/api/v2${rest}`;
926
+ }
927
+ return withLead.startsWith("/v2/") ? withLead : `/v2${withLead}`;
928
+ }
929
+ var COVERED_INTERPOLATED_PATH = [
930
+ /^(?:\/api)?\/ai\/manual$/,
931
+ /^(?:\/api)?\/ai\/chat$/,
932
+ /^(?:\/api)?\/ai\/agents\/[^/]+$/,
933
+ /^(?:\/api)?\/ai\/agent\/[^/]+$/,
934
+ /^(?:\/api)?\/ai\/conversations\/[^/]+$/,
935
+ /^(?:\/api)?\/ai\/conversation\/[^/]+$/,
936
+ /^(?:\/api)?\/ai\/prompts\/[^/]+$/,
937
+ // `/warm` etc. deliberately don't match
938
+ /^(?:\/api)?\/ai\/mandates\/[^/]+$/
939
+ // the mandate door
940
+ ];
941
+ function isCoveredAiPath(path) {
942
+ return COVERED_INTERPOLATED_PATH.some((re) => re.test(path));
943
+ }
944
+ function isV2Path(pathOrUrl) {
945
+ return /\/v2\/ai\//.test(pathOrUrl);
946
+ }
947
+ function toV1FallbackUrl(url) {
948
+ return url.replace(/\/v2\/ai\//, "/ai/");
949
+ }
950
+ function applyAiApiVersion(path, version) {
951
+ if (version !== "v2") return path;
952
+ return isCoveredAiPath(path) ? toV2Path(path) : path;
953
+ }
954
+ async function fetchWithMatrxProtocolFallback(url, init, opts = {}) {
955
+ const { onDowngrade, ...fetchOpts } = opts;
956
+ const logDowngrade = (reason, status2) => {
957
+ console.warn(
958
+ `[matrx] ai_v2_downgrade \u2192 retrying on v1. v2=${url} reason=${reason}`
959
+ );
960
+ onDowngrade?.({ url, reason, ...status2 !== void 0 ? { status: status2 } : {} });
961
+ };
962
+ if (!isV2Path(url)) return resilientFetch(url, init, fetchOpts);
963
+ let result;
964
+ try {
965
+ result = await resilientFetch(url, init, fetchOpts);
966
+ } catch (err) {
967
+ const isAbort = isNetError(err) && err.code === "aborted" || err instanceof Error && err.name === "AbortError";
968
+ if (isAbort) throw err;
969
+ logDowngrade(String(err));
970
+ return resilientFetch(toV1FallbackUrl(url), init, fetchOpts);
971
+ }
972
+ const status = result.response.status;
973
+ if (status === 404 || status === 405 || status >= 500) {
974
+ logDowngrade(`HTTP ${status}`, status);
975
+ return resilientFetch(toV1FallbackUrl(url), init, fetchOpts);
976
+ }
977
+ return result;
978
+ }
979
+
980
+ // matrx/client.ts
981
+ function classifyStatus(status) {
982
+ return status >= 400 && status < 500 ? "validation_error" : "http_error";
983
+ }
984
+ function normalizeMatrxError(err) {
985
+ if (err instanceof MatrxApiError) {
986
+ return {
987
+ type: classifyStatus(err.status),
988
+ message: err.message,
989
+ status: err.status,
990
+ serverDetail: err.serverDetail,
991
+ ...err.code ? { code: err.code } : {},
992
+ name: err.name
993
+ };
994
+ }
995
+ if (err instanceof OrganizationContextError) {
996
+ return {
997
+ type: "validation_error",
998
+ message: err.message,
999
+ code: err.code,
1000
+ name: err.name,
1001
+ ...err.stack !== void 0 ? { stack: err.stack } : {}
1002
+ };
1003
+ }
1004
+ if (err instanceof DOMException && err.name === "AbortError") {
1005
+ return { type: "abort_error", message: "Request was cancelled." };
1006
+ }
1007
+ if (isNetError2(err)) {
1008
+ if (err.code === "aborted") {
1009
+ return { type: "abort_error", message: err.message };
1010
+ }
1011
+ if (err.code === "http") {
1012
+ const status = err.status ?? 0;
1013
+ return { type: classifyStatus(status), message: err.message, status };
1014
+ }
1015
+ return { type: "network_error", message: err.message };
1016
+ }
1017
+ if (err instanceof Error) {
1018
+ const httpMatch = err.message.match(/HTTP (\d+):\s*(.*)/);
1019
+ if (httpMatch) {
1020
+ const status = parseInt(httpMatch[1], 10);
1021
+ return {
1022
+ type: classifyStatus(status),
1023
+ message: httpMatch[2] ?? err.message,
1024
+ status
1025
+ };
1026
+ }
1027
+ return { type: "network_error", message: err.message };
1028
+ }
1029
+ return { type: "unknown", message: String(err ?? "Unknown error") };
1030
+ }
1031
+ var PRODUCTION_CONNECT_TIMEOUT_MS = 15e3;
1032
+ function stripContentType(headers) {
1033
+ return Object.fromEntries(
1034
+ Object.entries(headers).filter(
1035
+ ([name]) => name.toLowerCase() !== "content-type"
1036
+ )
1037
+ );
1038
+ }
1039
+ function createMatrxTransport(options) {
1040
+ const {
1041
+ baseUrl,
1042
+ resolveTarget,
1043
+ credentials,
1044
+ organizationId,
1045
+ aiApiVersion,
1046
+ connectTimeoutMs = PRODUCTION_CONNECT_TIMEOUT_MS,
1047
+ totalTimeoutMs = null,
1048
+ expectedErrorStatuses,
1049
+ diagnostics,
1050
+ source = "matrxTransport"
1051
+ } = options;
1052
+ if (baseUrl === void 0 === (resolveTarget === void 0)) {
1053
+ throw new Error(
1054
+ "createMatrxTransport: provide exactly one of `baseUrl` or `resolveTarget`."
1055
+ );
1056
+ }
1057
+ const resolve = resolveTarget ?? (() => ({ baseUrl }));
1058
+ const resolveVersion = () => {
1059
+ if (aiApiVersion === void 0) return MATRX_AI_API_VERSION_DEFAULT;
1060
+ return typeof aiApiVersion === "function" ? aiApiVersion() : aiApiVersion;
1061
+ };
1062
+ const resolveOrganizationId = () => {
1063
+ if (organizationId === void 0) return null;
1064
+ const candidate = typeof organizationId === "function" ? organizationId() : organizationId;
1065
+ return requireOrganizationContext(candidate);
1066
+ };
1067
+ return {
1068
+ async fetch(path, init) {
1069
+ const target = resolve();
1070
+ const versionedPath = applyAiApiVersion(path, resolveVersion());
1071
+ const url = `${target.baseUrl}${versionedPath}`;
1072
+ const credentialHeaders = credentials ? credentialToHeaders(await credentials.get()) : {};
1073
+ let headers = {
1074
+ ...init.headers,
1075
+ ...stripContentType(credentialHeaders),
1076
+ ...stripContentType(target.policyHeaders ?? {})
1077
+ };
1078
+ const orgId = resolveOrganizationId();
1079
+ if (orgId !== null) {
1080
+ headers = applyOrganizationContextHeader(headers, orgId);
1081
+ }
1082
+ const info = {
1083
+ url,
1084
+ method: init.method,
1085
+ path,
1086
+ channel: target.channel ?? "default",
1087
+ source
1088
+ };
1089
+ diagnostics?.onRequest?.(info);
1090
+ let response;
1091
+ try {
1092
+ ({ response } = await fetchWithMatrxProtocolFallback(
1093
+ url,
1094
+ {
1095
+ method: init.method,
1096
+ headers,
1097
+ ...init.body !== void 0 ? { body: init.body } : {}
1098
+ },
1099
+ {
1100
+ ...init.signal ? { signal: init.signal } : {},
1101
+ connectTimeoutMs,
1102
+ totalTimeoutMs,
1103
+ throwOnHttpError: false,
1104
+ ...diagnostics?.onProtocolDowngrade ? { onDowngrade: diagnostics.onProtocolDowngrade } : {}
1105
+ }
1106
+ ));
1107
+ } catch (err) {
1108
+ diagnostics?.onError?.(normalizeMatrxError(err), info);
1109
+ throw err;
1110
+ }
1111
+ if (!response.ok && !expectedErrorStatuses?.includes(response.status)) {
1112
+ const serverDetail = await response.clone().json().catch(() => void 0);
1113
+ const code = extractMatrxErrorCode(serverDetail);
1114
+ diagnostics?.onError?.(
1115
+ {
1116
+ type: classifyStatus(response.status),
1117
+ message: extractMatrxErrorMessage(serverDetail) ?? `HTTP ${response.status}`,
1118
+ status: response.status,
1119
+ serverDetail,
1120
+ ...code ? { code } : {}
1121
+ },
1122
+ info
1123
+ );
1124
+ }
1125
+ return response;
1126
+ }
1127
+ };
1128
+ }
1129
+
837
1130
  // matrx/conversation.ts
838
1131
  function mintMatrxConversationId() {
839
1132
  return crypto.randomUUID();
@@ -1165,6 +1458,55 @@ async function* followRuntimeOperationEvents(transport, executionId, options = {
1165
1458
  yield { type: "liveness", cursor };
1166
1459
  }
1167
1460
  }
1461
+ async function followRuntimeOperationToEnd(transport, executionId, options) {
1462
+ const stallTimeoutMs = options.stallTimeoutMs ?? 45e3;
1463
+ const reconnectLimit = options.reconnectLimit ?? 60;
1464
+ const reconnectDelayMs = options.reconnectDelayMs ?? 2e3;
1465
+ const outer = options.signal;
1466
+ let cursor = options.lastEventSeq ?? 0;
1467
+ let failures = 0;
1468
+ while (!outer?.aborted && failures < reconnectLimit) {
1469
+ const attempt = new AbortController();
1470
+ const onOuterAbort = () => attempt.abort();
1471
+ outer?.addEventListener("abort", onOuterAbort, { once: true });
1472
+ let stallTimer = null;
1473
+ const armStall = () => {
1474
+ if (stallTimer !== null) clearTimeout(stallTimer);
1475
+ stallTimer = setTimeout(() => attempt.abort(), stallTimeoutMs);
1476
+ };
1477
+ try {
1478
+ const items = followRuntimeOperationEvents(transport, executionId, {
1479
+ lastEventSeq: cursor,
1480
+ signal: attempt.signal,
1481
+ ...options.onMalformedFrame ? { onMalformedFrame: options.onMalformedFrame } : {}
1482
+ });
1483
+ armStall();
1484
+ for await (const item of items) {
1485
+ armStall();
1486
+ failures = 0;
1487
+ cursor = item.cursor;
1488
+ if (item.type === "end") {
1489
+ return { ended: true, status: item.status };
1490
+ }
1491
+ if (item.type === "event") {
1492
+ options.onEvent(item.event, item.seq);
1493
+ }
1494
+ }
1495
+ failures += 1;
1496
+ } catch (error) {
1497
+ if (outer?.aborted) break;
1498
+ failures += 1;
1499
+ options.onAttemptError?.(error);
1500
+ } finally {
1501
+ if (stallTimer !== null) clearTimeout(stallTimer);
1502
+ outer?.removeEventListener("abort", onOuterAbort);
1503
+ }
1504
+ if (!outer?.aborted && failures < reconnectLimit) {
1505
+ await new Promise((r) => setTimeout(r, reconnectDelayMs));
1506
+ }
1507
+ }
1508
+ return { ended: false, status: null };
1509
+ }
1168
1510
  async function rejoinRuntimeOperation(transport, requestId, options = {}) {
1169
1511
  const response = await requestStream(
1170
1512
  transport,
@@ -1218,7 +1560,58 @@ function listUserPendingToolCalls(transport, options = {}) {
1218
1560
  }
1219
1561
  );
1220
1562
  }
1221
-
1222
- export { DEFAULT_MATRX_NDJSON_READ_AHEAD, DEFAULT_WORKFLOW_PROJECTION_LIMITS, MatrxApiError, MatrxRunError, TERMINAL_MATRX_RUNTIME_STATUSES, cancelAgentRun, continueAgentConversation, continueEphemeralConversationStart, continueStoredConversationStart, createAgentRequestProjection, createMatrxNdjsonFramer, createMatrxSseFramer, createWorkflowNodeProjection, extractMatrxErrorCode, extractMatrxErrorMessage, followRuntimeOperationEvents, getRuntimeOperationStatus, getRuntimeOperationsByLink, listConversationPendingToolCalls, listRuntimeOperationEvents, listUserPendingToolCalls, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, normalizeMatrxStreamEnvelope, parseMatrxSseFrame, projectAgentEvent, projectAgentEvents, projectAgentResultForDisplay, projectWorkflowNodeEvent, readMatrxNdjsonStream, readMatrxSseStream, rejoinRuntimeOperation, resumeAgentConversation, runAgentToCompletion, startAgentRun, submitAgentToolResults };
1223
- //# sourceMappingURL=index.js.map
1563
+ export {
1564
+ DEFAULT_MATRX_NDJSON_READ_AHEAD,
1565
+ DEFAULT_WORKFLOW_PROJECTION_LIMITS,
1566
+ MATRX_AI_API_VERSION_DEFAULT,
1567
+ MatrxApiError,
1568
+ MatrxRunError,
1569
+ OrganizationContextError,
1570
+ TERMINAL_MATRX_RUNTIME_STATUSES,
1571
+ V2_COVERED_AI_PATH_TEMPLATES,
1572
+ applyAiApiVersion,
1573
+ applyOrganizationContextHeader,
1574
+ assertQueryOrganizationMatchesContext,
1575
+ cancelAgentRun,
1576
+ continueAgentConversation,
1577
+ continueEphemeralConversationStart,
1578
+ continueStoredConversationStart,
1579
+ createAgentRequestProjection,
1580
+ createMatrxNdjsonFramer,
1581
+ createMatrxSseFramer,
1582
+ createMatrxTransport,
1583
+ createWorkflowNodeProjection,
1584
+ extractMatrxErrorCode,
1585
+ extractMatrxErrorMessage,
1586
+ fetchWithMatrxProtocolFallback,
1587
+ followRuntimeOperationEvents,
1588
+ followRuntimeOperationToEnd,
1589
+ getRuntimeOperationStatus,
1590
+ getRuntimeOperationsByLink,
1591
+ isCoveredAiPath,
1592
+ isV2Path,
1593
+ listConversationPendingToolCalls,
1594
+ listRuntimeOperationEvents,
1595
+ listUserPendingToolCalls,
1596
+ mintMatrxConversationId,
1597
+ newEphemeralConversationStart,
1598
+ newStoredConversationStart,
1599
+ normalizeMatrxError,
1600
+ normalizeMatrxStreamEnvelope,
1601
+ parseMatrxSseFrame,
1602
+ projectAgentEvent,
1603
+ projectAgentEvents,
1604
+ projectAgentResultForDisplay,
1605
+ projectWorkflowNodeEvent,
1606
+ readMatrxNdjsonStream,
1607
+ readMatrxSseStream,
1608
+ rejoinRuntimeOperation,
1609
+ requireOrganizationContext,
1610
+ resumeAgentConversation,
1611
+ runAgentToCompletion,
1612
+ startAgentRun,
1613
+ submitAgentToolResults,
1614
+ toV1FallbackUrl,
1615
+ toV2Path
1616
+ };
1224
1617
  //# sourceMappingURL=index.js.map