@ai-matrx/agents 0.5.0 → 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 +46 -0
  2. package/README.md +45 -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
@@ -67,6 +67,299 @@ function extractMatrxErrorCode(serverDetail) {
67
67
  return null;
68
68
  }
69
69
 
70
+ // matrx/client.ts
71
+ import { isNetError as isNetError2 } from "@ai-matrx/data";
72
+ import { credentialToHeaders } from "@ai-matrx/data";
73
+
74
+ // matrx/org-context.ts
75
+ var OrganizationContextError = class extends Error {
76
+ code;
77
+ constructor(code, message) {
78
+ super(message);
79
+ this.name = "OrganizationContextError";
80
+ this.code = code;
81
+ }
82
+ };
83
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
84
+ function requireOrganizationContext(selectedOrganizationId, overrideOrganizationId) {
85
+ const candidate = overrideOrganizationId ?? selectedOrganizationId;
86
+ if (typeof candidate !== "string" || candidate.trim().length === 0) {
87
+ throw new OrganizationContextError(
88
+ "organization_context_required",
89
+ "Select an organization before sending this request."
90
+ );
91
+ }
92
+ const normalized = candidate.trim();
93
+ if (!UUID_PATTERN.test(normalized)) {
94
+ throw new OrganizationContextError(
95
+ "organization_context_invalid",
96
+ "The selected organization ID is invalid."
97
+ );
98
+ }
99
+ return normalized.toLowerCase();
100
+ }
101
+ function applyOrganizationContextHeader(headers, organizationId) {
102
+ const normalizedOrganizationId = requireOrganizationContext(organizationId);
103
+ for (const [name, value] of Object.entries(headers)) {
104
+ if (name.toLowerCase() === "x-organization-id" && value.trim().toLowerCase() !== normalizedOrganizationId) {
105
+ throw new OrganizationContextError(
106
+ "organization_context_mismatch",
107
+ "X-Organization-Id must match the request context organization."
108
+ );
109
+ }
110
+ }
111
+ const withoutOrganizationHeader = Object.fromEntries(
112
+ Object.entries(headers).filter(
113
+ ([name]) => name.toLowerCase() !== "x-organization-id"
114
+ )
115
+ );
116
+ return {
117
+ ...withoutOrganizationHeader,
118
+ "X-Organization-Id": normalizedOrganizationId
119
+ };
120
+ }
121
+ function assertQueryOrganizationMatchesContext(queryParams, organizationId) {
122
+ if (!queryParams || queryParams.organization_id === void 0) return;
123
+ const queryOrganizationId = requireOrganizationContext(
124
+ String(queryParams.organization_id)
125
+ );
126
+ if (queryOrganizationId !== requireOrganizationContext(organizationId)) {
127
+ throw new OrganizationContextError(
128
+ "organization_context_mismatch",
129
+ "Query organization_id must match the request context organization."
130
+ );
131
+ }
132
+ }
133
+
134
+ // matrx/protocol.ts
135
+ import {
136
+ isNetError,
137
+ resilientFetch
138
+ } from "@ai-matrx/data/net";
139
+ var MATRX_AI_API_VERSION_DEFAULT = "v2";
140
+ var V2_COVERED_AI_PATH_TEMPLATES = [
141
+ "/ai/manual",
142
+ "/ai/chat",
143
+ "/ai/agents/{agent_id}",
144
+ "/ai/agent/{agent_id}",
145
+ // singular alias — behaves identically
146
+ "/ai/conversations/{conversation_id}",
147
+ "/ai/conversation/{conversation_id}",
148
+ // singular alias
149
+ "/ai/prompts/{prompt_id}",
150
+ // saved-prompt execution
151
+ "/ai/mandates/{mandate_key}"
152
+ // THE MANDATE DOOR — `/v2` sibling exists (routers/v2.py)
153
+ ];
154
+ function toV2Path(path) {
155
+ const withLead = path.startsWith("/") ? path : `/${path}`;
156
+ if (withLead.startsWith("/api/")) {
157
+ const rest = withLead.slice("/api".length);
158
+ return rest.startsWith("/v2/") ? withLead : `/api/v2${rest}`;
159
+ }
160
+ return withLead.startsWith("/v2/") ? withLead : `/v2${withLead}`;
161
+ }
162
+ var COVERED_INTERPOLATED_PATH = [
163
+ /^(?:\/api)?\/ai\/manual$/,
164
+ /^(?:\/api)?\/ai\/chat$/,
165
+ /^(?:\/api)?\/ai\/agents\/[^/]+$/,
166
+ /^(?:\/api)?\/ai\/agent\/[^/]+$/,
167
+ /^(?:\/api)?\/ai\/conversations\/[^/]+$/,
168
+ /^(?:\/api)?\/ai\/conversation\/[^/]+$/,
169
+ /^(?:\/api)?\/ai\/prompts\/[^/]+$/,
170
+ // `/warm` etc. deliberately don't match
171
+ /^(?:\/api)?\/ai\/mandates\/[^/]+$/
172
+ // the mandate door
173
+ ];
174
+ function isCoveredAiPath(path) {
175
+ return COVERED_INTERPOLATED_PATH.some((re) => re.test(path));
176
+ }
177
+ function isV2Path(pathOrUrl) {
178
+ return /\/v2\/ai\//.test(pathOrUrl);
179
+ }
180
+ function toV1FallbackUrl(url) {
181
+ return url.replace(/\/v2\/ai\//, "/ai/");
182
+ }
183
+ function applyAiApiVersion(path, version) {
184
+ if (version !== "v2") return path;
185
+ return isCoveredAiPath(path) ? toV2Path(path) : path;
186
+ }
187
+ async function fetchWithMatrxProtocolFallback(url, init, opts = {}) {
188
+ const { onDowngrade, ...fetchOpts } = opts;
189
+ const logDowngrade = (reason, status2) => {
190
+ console.warn(
191
+ `[matrx] ai_v2_downgrade \u2192 retrying on v1. v2=${url} reason=${reason}`
192
+ );
193
+ onDowngrade?.({ url, reason, ...status2 !== void 0 ? { status: status2 } : {} });
194
+ };
195
+ if (!isV2Path(url)) return resilientFetch(url, init, fetchOpts);
196
+ let result;
197
+ try {
198
+ result = await resilientFetch(url, init, fetchOpts);
199
+ } catch (err) {
200
+ const isAbort = isNetError(err) && err.code === "aborted" || err instanceof Error && err.name === "AbortError";
201
+ if (isAbort) throw err;
202
+ logDowngrade(String(err));
203
+ return resilientFetch(toV1FallbackUrl(url), init, fetchOpts);
204
+ }
205
+ const status = result.response.status;
206
+ if (status === 404 || status === 405 || status >= 500) {
207
+ logDowngrade(`HTTP ${status}`, status);
208
+ return resilientFetch(toV1FallbackUrl(url), init, fetchOpts);
209
+ }
210
+ return result;
211
+ }
212
+
213
+ // matrx/client.ts
214
+ function classifyStatus(status) {
215
+ return status >= 400 && status < 500 ? "validation_error" : "http_error";
216
+ }
217
+ function normalizeMatrxError(err) {
218
+ if (err instanceof MatrxApiError) {
219
+ return {
220
+ type: classifyStatus(err.status),
221
+ message: err.message,
222
+ status: err.status,
223
+ serverDetail: err.serverDetail,
224
+ ...err.code ? { code: err.code } : {},
225
+ name: err.name
226
+ };
227
+ }
228
+ if (err instanceof OrganizationContextError) {
229
+ return {
230
+ type: "validation_error",
231
+ message: err.message,
232
+ code: err.code,
233
+ name: err.name,
234
+ ...err.stack !== void 0 ? { stack: err.stack } : {}
235
+ };
236
+ }
237
+ if (err instanceof DOMException && err.name === "AbortError") {
238
+ return { type: "abort_error", message: "Request was cancelled." };
239
+ }
240
+ if (isNetError2(err)) {
241
+ if (err.code === "aborted") {
242
+ return { type: "abort_error", message: err.message };
243
+ }
244
+ if (err.code === "http") {
245
+ const status = err.status ?? 0;
246
+ return { type: classifyStatus(status), message: err.message, status };
247
+ }
248
+ return { type: "network_error", message: err.message };
249
+ }
250
+ if (err instanceof Error) {
251
+ const httpMatch = err.message.match(/HTTP (\d+):\s*(.*)/);
252
+ if (httpMatch) {
253
+ const status = parseInt(httpMatch[1], 10);
254
+ return {
255
+ type: classifyStatus(status),
256
+ message: httpMatch[2] ?? err.message,
257
+ status
258
+ };
259
+ }
260
+ return { type: "network_error", message: err.message };
261
+ }
262
+ return { type: "unknown", message: String(err ?? "Unknown error") };
263
+ }
264
+ var PRODUCTION_CONNECT_TIMEOUT_MS = 15e3;
265
+ function stripContentType(headers) {
266
+ return Object.fromEntries(
267
+ Object.entries(headers).filter(
268
+ ([name]) => name.toLowerCase() !== "content-type"
269
+ )
270
+ );
271
+ }
272
+ function createMatrxTransport(options) {
273
+ const {
274
+ baseUrl,
275
+ resolveTarget,
276
+ credentials,
277
+ organizationId,
278
+ aiApiVersion,
279
+ connectTimeoutMs = PRODUCTION_CONNECT_TIMEOUT_MS,
280
+ totalTimeoutMs = null,
281
+ expectedErrorStatuses,
282
+ diagnostics,
283
+ source = "matrxTransport"
284
+ } = options;
285
+ if (baseUrl === void 0 === (resolveTarget === void 0)) {
286
+ throw new Error(
287
+ "createMatrxTransport: provide exactly one of `baseUrl` or `resolveTarget`."
288
+ );
289
+ }
290
+ const resolve = resolveTarget ?? (() => ({ baseUrl }));
291
+ const resolveVersion = () => {
292
+ if (aiApiVersion === void 0) return MATRX_AI_API_VERSION_DEFAULT;
293
+ return typeof aiApiVersion === "function" ? aiApiVersion() : aiApiVersion;
294
+ };
295
+ const resolveOrganizationId = () => {
296
+ if (organizationId === void 0) return null;
297
+ const candidate = typeof organizationId === "function" ? organizationId() : organizationId;
298
+ return requireOrganizationContext(candidate);
299
+ };
300
+ return {
301
+ async fetch(path, init) {
302
+ const target = resolve();
303
+ const versionedPath = applyAiApiVersion(path, resolveVersion());
304
+ const url = `${target.baseUrl}${versionedPath}`;
305
+ const credentialHeaders = credentials ? credentialToHeaders(await credentials.get()) : {};
306
+ let headers = {
307
+ ...init.headers,
308
+ ...stripContentType(credentialHeaders),
309
+ ...stripContentType(target.policyHeaders ?? {})
310
+ };
311
+ const orgId = resolveOrganizationId();
312
+ if (orgId !== null) {
313
+ headers = applyOrganizationContextHeader(headers, orgId);
314
+ }
315
+ const info = {
316
+ url,
317
+ method: init.method,
318
+ path,
319
+ channel: target.channel ?? "default",
320
+ source
321
+ };
322
+ diagnostics?.onRequest?.(info);
323
+ let response;
324
+ try {
325
+ ({ response } = await fetchWithMatrxProtocolFallback(
326
+ url,
327
+ {
328
+ method: init.method,
329
+ headers,
330
+ ...init.body !== void 0 ? { body: init.body } : {}
331
+ },
332
+ {
333
+ ...init.signal ? { signal: init.signal } : {},
334
+ connectTimeoutMs,
335
+ totalTimeoutMs,
336
+ throwOnHttpError: false,
337
+ ...diagnostics?.onProtocolDowngrade ? { onDowngrade: diagnostics.onProtocolDowngrade } : {}
338
+ }
339
+ ));
340
+ } catch (err) {
341
+ diagnostics?.onError?.(normalizeMatrxError(err), info);
342
+ throw err;
343
+ }
344
+ if (!response.ok && !expectedErrorStatuses?.includes(response.status)) {
345
+ const serverDetail = await response.clone().json().catch(() => void 0);
346
+ const code = extractMatrxErrorCode(serverDetail);
347
+ diagnostics?.onError?.(
348
+ {
349
+ type: classifyStatus(response.status),
350
+ message: extractMatrxErrorMessage(serverDetail) ?? `HTTP ${response.status}`,
351
+ status: response.status,
352
+ serverDetail,
353
+ ...code ? { code } : {}
354
+ },
355
+ info
356
+ );
357
+ }
358
+ return response;
359
+ }
360
+ };
361
+ }
362
+
70
363
  // matrx/conversation.ts
71
364
  function mintMatrxConversationId() {
72
365
  return crypto.randomUUID();
@@ -664,6 +957,55 @@ async function* followRuntimeOperationEvents(transport, executionId, options = {
664
957
  yield { type: "liveness", cursor };
665
958
  }
666
959
  }
960
+ async function followRuntimeOperationToEnd(transport, executionId, options) {
961
+ const stallTimeoutMs = options.stallTimeoutMs ?? 45e3;
962
+ const reconnectLimit = options.reconnectLimit ?? 60;
963
+ const reconnectDelayMs = options.reconnectDelayMs ?? 2e3;
964
+ const outer = options.signal;
965
+ let cursor = options.lastEventSeq ?? 0;
966
+ let failures = 0;
967
+ while (!outer?.aborted && failures < reconnectLimit) {
968
+ const attempt = new AbortController();
969
+ const onOuterAbort = () => attempt.abort();
970
+ outer?.addEventListener("abort", onOuterAbort, { once: true });
971
+ let stallTimer = null;
972
+ const armStall = () => {
973
+ if (stallTimer !== null) clearTimeout(stallTimer);
974
+ stallTimer = setTimeout(() => attempt.abort(), stallTimeoutMs);
975
+ };
976
+ try {
977
+ const items = followRuntimeOperationEvents(transport, executionId, {
978
+ lastEventSeq: cursor,
979
+ signal: attempt.signal,
980
+ ...options.onMalformedFrame ? { onMalformedFrame: options.onMalformedFrame } : {}
981
+ });
982
+ armStall();
983
+ for await (const item of items) {
984
+ armStall();
985
+ failures = 0;
986
+ cursor = item.cursor;
987
+ if (item.type === "end") {
988
+ return { ended: true, status: item.status };
989
+ }
990
+ if (item.type === "event") {
991
+ options.onEvent(item.event, item.seq);
992
+ }
993
+ }
994
+ failures += 1;
995
+ } catch (error) {
996
+ if (outer?.aborted) break;
997
+ failures += 1;
998
+ options.onAttemptError?.(error);
999
+ } finally {
1000
+ if (stallTimer !== null) clearTimeout(stallTimer);
1001
+ outer?.removeEventListener("abort", onOuterAbort);
1002
+ }
1003
+ if (!outer?.aborted && failures < reconnectLimit) {
1004
+ await new Promise((r) => setTimeout(r, reconnectDelayMs));
1005
+ }
1006
+ }
1007
+ return { ended: false, status: null };
1008
+ }
667
1009
  async function rejoinRuntimeOperation(transport, requestId, options = {}) {
668
1010
  const response = await requestStream(
669
1011
  transport,
@@ -717,7 +1059,44 @@ function listUserPendingToolCalls(transport, options = {}) {
717
1059
  }
718
1060
  );
719
1061
  }
720
-
721
- export { MatrxApiError, MatrxRunError, TERMINAL_MATRX_RUNTIME_STATUSES, cancelAgentRun, continueAgentConversation, continueEphemeralConversationStart, continueStoredConversationStart, extractMatrxErrorCode, extractMatrxErrorMessage, followRuntimeOperationEvents, getRuntimeOperationStatus, getRuntimeOperationsByLink, listConversationPendingToolCalls, listRuntimeOperationEvents, listUserPendingToolCalls, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, rejoinRuntimeOperation, resumeAgentConversation, runAgentToCompletion, startAgentRun, submitAgentToolResults };
722
- //# sourceMappingURL=index.js.map
1062
+ export {
1063
+ MATRX_AI_API_VERSION_DEFAULT,
1064
+ MatrxApiError,
1065
+ MatrxRunError,
1066
+ OrganizationContextError,
1067
+ TERMINAL_MATRX_RUNTIME_STATUSES,
1068
+ V2_COVERED_AI_PATH_TEMPLATES,
1069
+ applyAiApiVersion,
1070
+ applyOrganizationContextHeader,
1071
+ assertQueryOrganizationMatchesContext,
1072
+ cancelAgentRun,
1073
+ continueAgentConversation,
1074
+ continueEphemeralConversationStart,
1075
+ continueStoredConversationStart,
1076
+ createMatrxTransport,
1077
+ extractMatrxErrorCode,
1078
+ extractMatrxErrorMessage,
1079
+ fetchWithMatrxProtocolFallback,
1080
+ followRuntimeOperationEvents,
1081
+ followRuntimeOperationToEnd,
1082
+ getRuntimeOperationStatus,
1083
+ getRuntimeOperationsByLink,
1084
+ isCoveredAiPath,
1085
+ isV2Path,
1086
+ listConversationPendingToolCalls,
1087
+ listRuntimeOperationEvents,
1088
+ listUserPendingToolCalls,
1089
+ mintMatrxConversationId,
1090
+ newEphemeralConversationStart,
1091
+ newStoredConversationStart,
1092
+ normalizeMatrxError,
1093
+ rejoinRuntimeOperation,
1094
+ requireOrganizationContext,
1095
+ resumeAgentConversation,
1096
+ runAgentToCompletion,
1097
+ startAgentRun,
1098
+ submitAgentToolResults,
1099
+ toV1FallbackUrl,
1100
+ toV2Path
1101
+ };
723
1102
  //# sourceMappingURL=index.js.map