@ai-matrx/agents 0.5.1 → 0.6.1

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 +52 -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
@@ -1,4 +1,65 @@
1
- 'use strict';
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // matrx/index.ts
21
+ var matrx_exports = {};
22
+ __export(matrx_exports, {
23
+ MATRX_AI_API_VERSION_DEFAULT: () => MATRX_AI_API_VERSION_DEFAULT,
24
+ MatrxApiError: () => MatrxApiError,
25
+ MatrxRunError: () => MatrxRunError,
26
+ OrganizationContextError: () => OrganizationContextError,
27
+ TERMINAL_MATRX_RUNTIME_STATUSES: () => TERMINAL_MATRX_RUNTIME_STATUSES,
28
+ V2_COVERED_AI_PATH_TEMPLATES: () => V2_COVERED_AI_PATH_TEMPLATES,
29
+ applyAiApiVersion: () => applyAiApiVersion,
30
+ applyOrganizationContextHeader: () => applyOrganizationContextHeader,
31
+ assertQueryOrganizationMatchesContext: () => assertQueryOrganizationMatchesContext,
32
+ cancelAgentRun: () => cancelAgentRun,
33
+ continueAgentConversation: () => continueAgentConversation,
34
+ continueEphemeralConversationStart: () => continueEphemeralConversationStart,
35
+ continueStoredConversationStart: () => continueStoredConversationStart,
36
+ createMatrxTransport: () => createMatrxTransport,
37
+ extractMatrxErrorCode: () => extractMatrxErrorCode,
38
+ extractMatrxErrorMessage: () => extractMatrxErrorMessage,
39
+ fetchWithMatrxProtocolFallback: () => fetchWithMatrxProtocolFallback,
40
+ followRuntimeOperationEvents: () => followRuntimeOperationEvents,
41
+ followRuntimeOperationToEnd: () => followRuntimeOperationToEnd,
42
+ getRuntimeOperationStatus: () => getRuntimeOperationStatus,
43
+ getRuntimeOperationsByLink: () => getRuntimeOperationsByLink,
44
+ isCoveredAiPath: () => isCoveredAiPath,
45
+ isV2Path: () => isV2Path,
46
+ listConversationPendingToolCalls: () => listConversationPendingToolCalls,
47
+ listRuntimeOperationEvents: () => listRuntimeOperationEvents,
48
+ listUserPendingToolCalls: () => listUserPendingToolCalls,
49
+ mintMatrxConversationId: () => mintMatrxConversationId,
50
+ newEphemeralConversationStart: () => newEphemeralConversationStart,
51
+ newStoredConversationStart: () => newStoredConversationStart,
52
+ normalizeMatrxError: () => normalizeMatrxError,
53
+ rejoinRuntimeOperation: () => rejoinRuntimeOperation,
54
+ requireOrganizationContext: () => requireOrganizationContext,
55
+ resumeAgentConversation: () => resumeAgentConversation,
56
+ runAgentToCompletion: () => runAgentToCompletion,
57
+ startAgentRun: () => startAgentRun,
58
+ submitAgentToolResults: () => submitAgentToolResults,
59
+ toV1FallbackUrl: () => toV1FallbackUrl,
60
+ toV2Path: () => toV2Path
61
+ });
62
+ module.exports = __toCommonJS(matrx_exports);
2
63
 
3
64
  // matrx/transport.ts
4
65
  var MatrxApiError = class extends Error {
@@ -69,6 +130,296 @@ function extractMatrxErrorCode(serverDetail) {
69
130
  return null;
70
131
  }
71
132
 
133
+ // matrx/client.ts
134
+ var import_data = require("@ai-matrx/data");
135
+ var import_data2 = require("@ai-matrx/data");
136
+
137
+ // matrx/org-context.ts
138
+ var OrganizationContextError = class extends Error {
139
+ code;
140
+ constructor(code, message) {
141
+ super(message);
142
+ this.name = "OrganizationContextError";
143
+ this.code = code;
144
+ }
145
+ };
146
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
147
+ function requireOrganizationContext(selectedOrganizationId, overrideOrganizationId) {
148
+ const candidate = overrideOrganizationId ?? selectedOrganizationId;
149
+ if (typeof candidate !== "string" || candidate.trim().length === 0) {
150
+ throw new OrganizationContextError(
151
+ "organization_context_required",
152
+ "Select an organization before sending this request."
153
+ );
154
+ }
155
+ const normalized = candidate.trim();
156
+ if (!UUID_PATTERN.test(normalized)) {
157
+ throw new OrganizationContextError(
158
+ "organization_context_invalid",
159
+ "The selected organization ID is invalid."
160
+ );
161
+ }
162
+ return normalized.toLowerCase();
163
+ }
164
+ function applyOrganizationContextHeader(headers, organizationId) {
165
+ const normalizedOrganizationId = requireOrganizationContext(organizationId);
166
+ for (const [name, value] of Object.entries(headers)) {
167
+ if (name.toLowerCase() === "x-organization-id" && value.trim().toLowerCase() !== normalizedOrganizationId) {
168
+ throw new OrganizationContextError(
169
+ "organization_context_mismatch",
170
+ "X-Organization-Id must match the request context organization."
171
+ );
172
+ }
173
+ }
174
+ const withoutOrganizationHeader = Object.fromEntries(
175
+ Object.entries(headers).filter(
176
+ ([name]) => name.toLowerCase() !== "x-organization-id"
177
+ )
178
+ );
179
+ return {
180
+ ...withoutOrganizationHeader,
181
+ "X-Organization-Id": normalizedOrganizationId
182
+ };
183
+ }
184
+ function assertQueryOrganizationMatchesContext(queryParams, organizationId) {
185
+ if (!queryParams || queryParams.organization_id === void 0) return;
186
+ const queryOrganizationId = requireOrganizationContext(
187
+ String(queryParams.organization_id)
188
+ );
189
+ if (queryOrganizationId !== requireOrganizationContext(organizationId)) {
190
+ throw new OrganizationContextError(
191
+ "organization_context_mismatch",
192
+ "Query organization_id must match the request context organization."
193
+ );
194
+ }
195
+ }
196
+
197
+ // matrx/protocol.ts
198
+ var import_net = require("@ai-matrx/data/net");
199
+ var MATRX_AI_API_VERSION_DEFAULT = "v2";
200
+ var V2_COVERED_AI_PATH_TEMPLATES = [
201
+ "/ai/manual",
202
+ "/ai/chat",
203
+ "/ai/agents/{agent_id}",
204
+ "/ai/agent/{agent_id}",
205
+ // singular alias — behaves identically
206
+ "/ai/conversations/{conversation_id}",
207
+ "/ai/conversation/{conversation_id}",
208
+ // singular alias
209
+ "/ai/prompts/{prompt_id}",
210
+ // saved-prompt execution
211
+ "/ai/mandates/{mandate_key}"
212
+ // THE MANDATE DOOR — `/v2` sibling exists (routers/v2.py)
213
+ ];
214
+ function toV2Path(path) {
215
+ const withLead = path.startsWith("/") ? path : `/${path}`;
216
+ if (withLead.startsWith("/api/")) {
217
+ const rest = withLead.slice("/api".length);
218
+ return rest.startsWith("/v2/") ? withLead : `/api/v2${rest}`;
219
+ }
220
+ return withLead.startsWith("/v2/") ? withLead : `/v2${withLead}`;
221
+ }
222
+ var COVERED_INTERPOLATED_PATH = [
223
+ /^(?:\/api)?\/ai\/manual$/,
224
+ /^(?:\/api)?\/ai\/chat$/,
225
+ /^(?:\/api)?\/ai\/agents\/[^/]+$/,
226
+ /^(?:\/api)?\/ai\/agent\/[^/]+$/,
227
+ /^(?:\/api)?\/ai\/conversations\/[^/]+$/,
228
+ /^(?:\/api)?\/ai\/conversation\/[^/]+$/,
229
+ /^(?:\/api)?\/ai\/prompts\/[^/]+$/,
230
+ // `/warm` etc. deliberately don't match
231
+ /^(?:\/api)?\/ai\/mandates\/[^/]+$/
232
+ // the mandate door
233
+ ];
234
+ function isCoveredAiPath(path) {
235
+ return COVERED_INTERPOLATED_PATH.some((re) => re.test(path));
236
+ }
237
+ function isV2Path(pathOrUrl) {
238
+ return /\/v2\/ai\//.test(pathOrUrl);
239
+ }
240
+ function toV1FallbackUrl(url) {
241
+ return url.replace(/\/v2\/ai\//, "/ai/");
242
+ }
243
+ function applyAiApiVersion(path, version) {
244
+ if (version !== "v2") return path;
245
+ return isCoveredAiPath(path) ? toV2Path(path) : path;
246
+ }
247
+ async function fetchWithMatrxProtocolFallback(url, init, opts = {}) {
248
+ const { onDowngrade, ...fetchOpts } = opts;
249
+ const logDowngrade = (reason, status2) => {
250
+ console.warn(
251
+ `[matrx] ai_v2_downgrade \u2192 retrying on v1. v2=${url} reason=${reason}`
252
+ );
253
+ onDowngrade?.({ url, reason, ...status2 !== void 0 ? { status: status2 } : {} });
254
+ };
255
+ if (!isV2Path(url)) return (0, import_net.resilientFetch)(url, init, fetchOpts);
256
+ let result;
257
+ try {
258
+ result = await (0, import_net.resilientFetch)(url, init, fetchOpts);
259
+ } catch (err) {
260
+ const isAbort = (0, import_net.isNetError)(err) && err.code === "aborted" || err instanceof Error && err.name === "AbortError";
261
+ if (isAbort) throw err;
262
+ logDowngrade(String(err));
263
+ return (0, import_net.resilientFetch)(toV1FallbackUrl(url), init, fetchOpts);
264
+ }
265
+ const status = result.response.status;
266
+ if (status === 404 || status === 405 || status >= 500) {
267
+ logDowngrade(`HTTP ${status}`, status);
268
+ return (0, import_net.resilientFetch)(toV1FallbackUrl(url), init, fetchOpts);
269
+ }
270
+ return result;
271
+ }
272
+
273
+ // matrx/client.ts
274
+ function classifyStatus(status) {
275
+ return status >= 400 && status < 500 ? "validation_error" : "http_error";
276
+ }
277
+ function normalizeMatrxError(err) {
278
+ if (err instanceof MatrxApiError) {
279
+ return {
280
+ type: classifyStatus(err.status),
281
+ message: err.message,
282
+ status: err.status,
283
+ serverDetail: err.serverDetail,
284
+ ...err.code ? { code: err.code } : {},
285
+ name: err.name
286
+ };
287
+ }
288
+ if (err instanceof OrganizationContextError) {
289
+ return {
290
+ type: "validation_error",
291
+ message: err.message,
292
+ code: err.code,
293
+ name: err.name,
294
+ ...err.stack !== void 0 ? { stack: err.stack } : {}
295
+ };
296
+ }
297
+ if (err instanceof DOMException && err.name === "AbortError") {
298
+ return { type: "abort_error", message: "Request was cancelled." };
299
+ }
300
+ if ((0, import_data.isNetError)(err)) {
301
+ if (err.code === "aborted") {
302
+ return { type: "abort_error", message: err.message };
303
+ }
304
+ if (err.code === "http") {
305
+ const status = err.status ?? 0;
306
+ return { type: classifyStatus(status), message: err.message, status };
307
+ }
308
+ return { type: "network_error", message: err.message };
309
+ }
310
+ if (err instanceof Error) {
311
+ const httpMatch = err.message.match(/HTTP (\d+):\s*(.*)/);
312
+ if (httpMatch) {
313
+ const status = parseInt(httpMatch[1], 10);
314
+ return {
315
+ type: classifyStatus(status),
316
+ message: httpMatch[2] ?? err.message,
317
+ status
318
+ };
319
+ }
320
+ return { type: "network_error", message: err.message };
321
+ }
322
+ return { type: "unknown", message: String(err ?? "Unknown error") };
323
+ }
324
+ var PRODUCTION_CONNECT_TIMEOUT_MS = 15e3;
325
+ function stripContentType(headers) {
326
+ return Object.fromEntries(
327
+ Object.entries(headers).filter(
328
+ ([name]) => name.toLowerCase() !== "content-type"
329
+ )
330
+ );
331
+ }
332
+ function createMatrxTransport(options) {
333
+ const {
334
+ baseUrl,
335
+ resolveTarget,
336
+ credentials,
337
+ organizationId,
338
+ aiApiVersion,
339
+ connectTimeoutMs = PRODUCTION_CONNECT_TIMEOUT_MS,
340
+ totalTimeoutMs = null,
341
+ expectedErrorStatuses,
342
+ diagnostics,
343
+ source = "matrxTransport"
344
+ } = options;
345
+ if (baseUrl === void 0 === (resolveTarget === void 0)) {
346
+ throw new Error(
347
+ "createMatrxTransport: provide exactly one of `baseUrl` or `resolveTarget`."
348
+ );
349
+ }
350
+ const resolve = resolveTarget ?? (() => ({ baseUrl }));
351
+ const resolveVersion = () => {
352
+ if (aiApiVersion === void 0) return MATRX_AI_API_VERSION_DEFAULT;
353
+ return typeof aiApiVersion === "function" ? aiApiVersion() : aiApiVersion;
354
+ };
355
+ const resolveOrganizationId = () => {
356
+ if (organizationId === void 0) return null;
357
+ const candidate = typeof organizationId === "function" ? organizationId() : organizationId;
358
+ return requireOrganizationContext(candidate);
359
+ };
360
+ return {
361
+ async fetch(path, init) {
362
+ const target = resolve();
363
+ const versionedPath = applyAiApiVersion(path, resolveVersion());
364
+ const url = `${target.baseUrl}${versionedPath}`;
365
+ const credentialHeaders = credentials ? (0, import_data2.credentialToHeaders)(await credentials.get()) : {};
366
+ let headers = {
367
+ ...init.headers,
368
+ ...stripContentType(credentialHeaders),
369
+ ...stripContentType(target.policyHeaders ?? {})
370
+ };
371
+ const orgId = resolveOrganizationId();
372
+ if (orgId !== null) {
373
+ headers = applyOrganizationContextHeader(headers, orgId);
374
+ }
375
+ const info = {
376
+ url,
377
+ method: init.method,
378
+ path,
379
+ channel: target.channel ?? "default",
380
+ source
381
+ };
382
+ diagnostics?.onRequest?.(info);
383
+ let response;
384
+ try {
385
+ ({ response } = await fetchWithMatrxProtocolFallback(
386
+ url,
387
+ {
388
+ method: init.method,
389
+ headers,
390
+ ...init.body !== void 0 ? { body: init.body } : {}
391
+ },
392
+ {
393
+ ...init.signal ? { signal: init.signal } : {},
394
+ connectTimeoutMs,
395
+ totalTimeoutMs,
396
+ throwOnHttpError: false,
397
+ ...diagnostics?.onProtocolDowngrade ? { onDowngrade: diagnostics.onProtocolDowngrade } : {}
398
+ }
399
+ ));
400
+ } catch (err) {
401
+ diagnostics?.onError?.(normalizeMatrxError(err), info);
402
+ throw err;
403
+ }
404
+ if (!response.ok && !expectedErrorStatuses?.includes(response.status)) {
405
+ const serverDetail = await response.clone().json().catch(() => void 0);
406
+ const code = extractMatrxErrorCode(serverDetail);
407
+ diagnostics?.onError?.(
408
+ {
409
+ type: classifyStatus(response.status),
410
+ message: extractMatrxErrorMessage(serverDetail) ?? `HTTP ${response.status}`,
411
+ status: response.status,
412
+ serverDetail,
413
+ ...code ? { code } : {}
414
+ },
415
+ info
416
+ );
417
+ }
418
+ return response;
419
+ }
420
+ };
421
+ }
422
+
72
423
  // matrx/conversation.ts
73
424
  function mintMatrxConversationId() {
74
425
  return crypto.randomUUID();
@@ -666,6 +1017,55 @@ async function* followRuntimeOperationEvents(transport, executionId, options = {
666
1017
  yield { type: "liveness", cursor };
667
1018
  }
668
1019
  }
1020
+ async function followRuntimeOperationToEnd(transport, executionId, options) {
1021
+ const stallTimeoutMs = options.stallTimeoutMs ?? 45e3;
1022
+ const reconnectLimit = options.reconnectLimit ?? 60;
1023
+ const reconnectDelayMs = options.reconnectDelayMs ?? 2e3;
1024
+ const outer = options.signal;
1025
+ let cursor = options.lastEventSeq ?? 0;
1026
+ let failures = 0;
1027
+ while (!outer?.aborted && failures < reconnectLimit) {
1028
+ const attempt = new AbortController();
1029
+ const onOuterAbort = () => attempt.abort();
1030
+ outer?.addEventListener("abort", onOuterAbort, { once: true });
1031
+ let stallTimer = null;
1032
+ const armStall = () => {
1033
+ if (stallTimer !== null) clearTimeout(stallTimer);
1034
+ stallTimer = setTimeout(() => attempt.abort(), stallTimeoutMs);
1035
+ };
1036
+ try {
1037
+ const items = followRuntimeOperationEvents(transport, executionId, {
1038
+ lastEventSeq: cursor,
1039
+ signal: attempt.signal,
1040
+ ...options.onMalformedFrame ? { onMalformedFrame: options.onMalformedFrame } : {}
1041
+ });
1042
+ armStall();
1043
+ for await (const item of items) {
1044
+ armStall();
1045
+ failures = 0;
1046
+ cursor = item.cursor;
1047
+ if (item.type === "end") {
1048
+ return { ended: true, status: item.status };
1049
+ }
1050
+ if (item.type === "event") {
1051
+ options.onEvent(item.event, item.seq);
1052
+ }
1053
+ }
1054
+ failures += 1;
1055
+ } catch (error) {
1056
+ if (outer?.aborted) break;
1057
+ failures += 1;
1058
+ options.onAttemptError?.(error);
1059
+ } finally {
1060
+ if (stallTimer !== null) clearTimeout(stallTimer);
1061
+ outer?.removeEventListener("abort", onOuterAbort);
1062
+ }
1063
+ if (!outer?.aborted && failures < reconnectLimit) {
1064
+ await new Promise((r) => setTimeout(r, reconnectDelayMs));
1065
+ }
1066
+ }
1067
+ return { ended: false, status: null };
1068
+ }
669
1069
  async function rejoinRuntimeOperation(transport, requestId, options = {}) {
670
1070
  const response = await requestStream(
671
1071
  transport,
@@ -719,29 +1119,4 @@ function listUserPendingToolCalls(transport, options = {}) {
719
1119
  }
720
1120
  );
721
1121
  }
722
-
723
- exports.MatrxApiError = MatrxApiError;
724
- exports.MatrxRunError = MatrxRunError;
725
- exports.TERMINAL_MATRX_RUNTIME_STATUSES = TERMINAL_MATRX_RUNTIME_STATUSES;
726
- exports.cancelAgentRun = cancelAgentRun;
727
- exports.continueAgentConversation = continueAgentConversation;
728
- exports.continueEphemeralConversationStart = continueEphemeralConversationStart;
729
- exports.continueStoredConversationStart = continueStoredConversationStart;
730
- exports.extractMatrxErrorCode = extractMatrxErrorCode;
731
- exports.extractMatrxErrorMessage = extractMatrxErrorMessage;
732
- exports.followRuntimeOperationEvents = followRuntimeOperationEvents;
733
- exports.getRuntimeOperationStatus = getRuntimeOperationStatus;
734
- exports.getRuntimeOperationsByLink = getRuntimeOperationsByLink;
735
- exports.listConversationPendingToolCalls = listConversationPendingToolCalls;
736
- exports.listRuntimeOperationEvents = listRuntimeOperationEvents;
737
- exports.listUserPendingToolCalls = listUserPendingToolCalls;
738
- exports.mintMatrxConversationId = mintMatrxConversationId;
739
- exports.newEphemeralConversationStart = newEphemeralConversationStart;
740
- exports.newStoredConversationStart = newStoredConversationStart;
741
- exports.rejoinRuntimeOperation = rejoinRuntimeOperation;
742
- exports.resumeAgentConversation = resumeAgentConversation;
743
- exports.runAgentToCompletion = runAgentToCompletion;
744
- exports.startAgentRun = startAgentRun;
745
- exports.submitAgentToolResults = submitAgentToolResults;
746
- //# sourceMappingURL=index.cjs.map
747
1122
  //# sourceMappingURL=index.cjs.map