@ai-matrx/api 0.1.0 → 0.1.2

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 (63) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +4 -0
  3. package/dist/agents.cjs +12 -12
  4. package/dist/agents.js +2 -2
  5. package/dist/ai.cjs +3 -3
  6. package/dist/ai.js +2 -2
  7. package/dist/apps.cjs +6 -6
  8. package/dist/apps.js +2 -2
  9. package/dist/architecture.cjs +11 -11
  10. package/dist/architecture.js +2 -2
  11. package/dist/audio.cjs +5 -5
  12. package/dist/audio.js +2 -2
  13. package/dist/chat.cjs +12 -12
  14. package/dist/chat.js +2 -2
  15. package/dist/{chunk-BMQI7UET.cjs → chunk-5WJLKYH6.cjs} +1 -1
  16. package/dist/{chunk-YUDQWDCM.cjs → chunk-HER22VVH.cjs} +5 -5
  17. package/dist/{chunk-UONBYRE4.js → chunk-TSHL7Z53.js} +1 -1
  18. package/dist/{chunk-AY5N6EA4.js → chunk-VTZKJMSY.js} +1 -1
  19. package/dist/code.cjs +7 -7
  20. package/dist/code.js +2 -2
  21. package/dist/communications.cjs +5 -5
  22. package/dist/communications.js +2 -2
  23. package/dist/computer.cjs +4 -4
  24. package/dist/computer.js +2 -2
  25. package/dist/content.cjs +5 -5
  26. package/dist/content.js +2 -2
  27. package/dist/credentials.cjs +5 -5
  28. package/dist/credentials.js +1 -1
  29. package/dist/crm.cjs +3 -3
  30. package/dist/crm.js +2 -2
  31. package/dist/education.cjs +5 -5
  32. package/dist/education.js +2 -2
  33. package/dist/files.cjs +21 -21
  34. package/dist/files.js +2 -2
  35. package/dist/index.cjs +140 -58
  36. package/dist/index.d.cts +64 -1
  37. package/dist/index.d.ts +64 -1
  38. package/dist/index.js +83 -5
  39. package/dist/integrations.cjs +4 -4
  40. package/dist/integrations.js +2 -2
  41. package/dist/intelligence.cjs +7 -7
  42. package/dist/intelligence.js +2 -2
  43. package/dist/knowledge.cjs +43 -43
  44. package/dist/knowledge.js +2 -2
  45. package/dist/legal.cjs +7 -7
  46. package/dist/legal.js +2 -2
  47. package/dist/marketing.cjs +73 -73
  48. package/dist/marketing.js +2 -2
  49. package/dist/masterwork.cjs +33 -33
  50. package/dist/masterwork.js +2 -2
  51. package/dist/media.cjs +12 -12
  52. package/dist/media.js +2 -2
  53. package/dist/platform.cjs +4 -4
  54. package/dist/platform.js +2 -2
  55. package/dist/publish.cjs +8 -8
  56. package/dist/publish.js +2 -2
  57. package/dist/stream.cjs +11 -11
  58. package/dist/stream.js +2 -2
  59. package/dist/web.cjs +27 -27
  60. package/dist/web.js +2 -2
  61. package/dist/workflows.cjs +13 -13
  62. package/dist/workflows.js +2 -2
  63. package/package.json +5 -4
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  var chunkFNIYADWI_cjs = require('./chunk-FNIYADWI.cjs');
4
- var chunkYUDQWDCM_cjs = require('./chunk-YUDQWDCM.cjs');
4
+ var chunkHER22VVH_cjs = require('./chunk-HER22VVH.cjs');
5
5
  var chunk2SXAAKGV_cjs = require('./chunk-2SXAAKGV.cjs');
6
- var chunkBMQI7UET_cjs = require('./chunk-BMQI7UET.cjs');
6
+ var chunk5WJLKYH6_cjs = require('./chunk-5WJLKYH6.cjs');
7
7
  var format = require('@ai-matrx/kit/format');
8
8
 
9
9
  // src/core/protocol.ts
@@ -127,7 +127,7 @@ function buildMatrxRequestBody(body, scope) {
127
127
  }
128
128
  const bodyOrganizationId = base.organization_id;
129
129
  if (scope.organization_id !== void 0 && bodyOrganizationId !== void 0 && (typeof bodyOrganizationId !== "string" || bodyOrganizationId.trim() !== scope.organization_id)) {
130
- throw new chunkYUDQWDCM_cjs.OrganizationContextError(
130
+ throw new chunkHER22VVH_cjs.OrganizationContextError(
131
131
  "organization_context_mismatch",
132
132
  "Request body organization_id must match the request context organization."
133
133
  );
@@ -199,14 +199,14 @@ function parseMatrxNdjsonResponse(response, signal, hooks = {}) {
199
199
  };
200
200
  async function* events() {
201
201
  if (!response.body) {
202
- throw new chunkYUDQWDCM_cjs.BackendApiError({
202
+ throw new chunkHER22VVH_cjs.BackendApiError({
203
203
  code: "internal_error",
204
204
  detail: "Response has no body",
205
205
  userMessage: "No response received from server"
206
206
  });
207
207
  }
208
208
  try {
209
- for await (const envelope of chunkYUDQWDCM_cjs.readMatrxNdjsonStream(response.body, {
209
+ for await (const envelope of chunkHER22VVH_cjs.readMatrxNdjsonStream(response.body, {
210
210
  ...signal ? { signal } : {},
211
211
  ...hooks.onMalformedLine ? { onMalformedLine: hooks.onMalformedLine } : {},
212
212
  ...hooks.onUnknownEnvelope ? { onUnknownEnvelope: hooks.onUnknownEnvelope } : {}
@@ -218,7 +218,7 @@ function parseMatrxNdjsonResponse(response, signal, hooks = {}) {
218
218
  if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
219
219
  return;
220
220
  }
221
- const transportError = error instanceof chunkYUDQWDCM_cjs.BackendApiError ? error : new chunkYUDQWDCM_cjs.StreamTransportError({
221
+ const transportError = error instanceof chunkHER22VVH_cjs.BackendApiError ? error : new chunkHER22VVH_cjs.StreamTransportError({
222
222
  detail: error instanceof Error ? error.message : "The response stream ended unexpectedly.",
223
223
  details: error,
224
224
  ...ids.requestId ? { requestId: ids.requestId } : {}
@@ -235,7 +235,7 @@ async function httpErrorFrom(response) {
235
235
  const serverDetail = await response.json().catch(() => void 0);
236
236
  return {
237
237
  type: response.status >= 400 && response.status < 500 ? "validation_error" : "http_error",
238
- message: chunkYUDQWDCM_cjs.extractMatrxErrorMessage(serverDetail) ?? bareStatusSentence(response.status),
238
+ message: chunkHER22VVH_cjs.extractMatrxErrorMessage(serverDetail) ?? bareStatusSentence(response.status),
239
239
  status: response.status,
240
240
  serverDetail
241
241
  };
@@ -311,7 +311,7 @@ async function sendMatrxRequest(url, init = {}, options = {}) {
311
311
  return await fetch(url, { ...init, signal: controller.signal });
312
312
  } catch (error) {
313
313
  if (timedOut) {
314
- throw new chunkYUDQWDCM_cjs.BackendApiError({
314
+ throw new chunkHER22VVH_cjs.BackendApiError({
315
315
  code: "request_timeout",
316
316
  detail: `${init.method ?? "GET"} ${url} exceeded ${options.timeoutMs}ms`,
317
317
  userMessage: "The request timed out \u2014 please retry.",
@@ -325,7 +325,7 @@ async function sendMatrxRequest(url, init = {}, options = {}) {
325
325
  }
326
326
  }
327
327
  async function readMatrxJsonResponse(response) {
328
- if (!response.ok) throw await chunkYUDQWDCM_cjs.parseHttpError(response);
328
+ if (!response.ok) throw await chunkHER22VVH_cjs.parseHttpError(response);
329
329
  if (response.status === 204) return null;
330
330
  return await response.json();
331
331
  }
@@ -335,7 +335,7 @@ function classifyStatus(status) {
335
335
  return status >= 400 && status < 500 ? "validation_error" : "http_error";
336
336
  }
337
337
  function normalizeMatrxError(err) {
338
- if (err instanceof chunkYUDQWDCM_cjs.OrganizationContextError) {
338
+ if (err instanceof chunkHER22VVH_cjs.OrganizationContextError) {
339
339
  return {
340
340
  type: "validation_error",
341
341
  message: err.message,
@@ -347,7 +347,7 @@ function normalizeMatrxError(err) {
347
347
  if (err instanceof DOMException && err.name === "AbortError") {
348
348
  return { type: "abort_error", message: "Request was cancelled." };
349
349
  }
350
- if (err instanceof chunkYUDQWDCM_cjs.MatrxApiError) {
350
+ if (err instanceof chunkHER22VVH_cjs.MatrxApiError) {
351
351
  return {
352
352
  type: classifyStatus(err.status),
353
353
  message: honestTransportMessage(err.message, err.status),
@@ -357,7 +357,7 @@ function normalizeMatrxError(err) {
357
357
  name: err.name
358
358
  };
359
359
  }
360
- if (err instanceof chunkYUDQWDCM_cjs.BackendApiError) {
360
+ if (err instanceof chunkHER22VVH_cjs.BackendApiError) {
361
361
  return {
362
362
  type: "network_error",
363
363
  message: honestTransportMessage(
@@ -455,9 +455,9 @@ function createMatrxTransport(options) {
455
455
  };
456
456
  const resolveOrganizationId = (callOrganizationId) => {
457
457
  if (organizationId === void 0) return null;
458
- if (callOrganizationId !== null) return chunkYUDQWDCM_cjs.requireOrganizationContext(callOrganizationId);
458
+ if (callOrganizationId !== null) return chunkHER22VVH_cjs.requireOrganizationContext(callOrganizationId);
459
459
  const candidate = typeof organizationId === "function" ? organizationId() : organizationId;
460
- return chunkYUDQWDCM_cjs.requireOrganizationContext(candidate);
460
+ return chunkHER22VVH_cjs.requireOrganizationContext(candidate);
461
461
  };
462
462
  return {
463
463
  async fetch(path, init) {
@@ -465,7 +465,7 @@ function createMatrxTransport(options) {
465
465
  const callOrganizationId = readOrganizationHeader(init.headers);
466
466
  const versionedPath = applyAiApiVersion(path, resolveVersion());
467
467
  const url = `${target.baseUrl}${versionedPath}`;
468
- const credentialHeaders = credentials ? chunkBMQI7UET_cjs.credentialToHeaders(await credentials.get()) : {};
468
+ const credentialHeaders = credentials ? chunk5WJLKYH6_cjs.credentialToHeaders(await credentials.get()) : {};
469
469
  const policyHeaders = stripContentType(target.policyHeaders ?? {});
470
470
  let headers = {
471
471
  ...init.headers,
@@ -474,7 +474,7 @@ function createMatrxTransport(options) {
474
474
  };
475
475
  const orgId = resolveOrganizationId(callOrganizationId);
476
476
  if (orgId !== null) {
477
- headers = chunkYUDQWDCM_cjs.applyOrganizationContextHeader(headers, orgId);
477
+ headers = chunkHER22VVH_cjs.applyOrganizationContextHeader(headers, orgId);
478
478
  }
479
479
  const info = {
480
480
  url,
@@ -507,11 +507,11 @@ function createMatrxTransport(options) {
507
507
  }
508
508
  if (!response.ok && !expectedErrorStatuses?.includes(response.status)) {
509
509
  const serverDetail = await response.clone().json().catch(() => void 0);
510
- const code = chunkYUDQWDCM_cjs.extractMatrxErrorCode(serverDetail);
510
+ const code = chunkHER22VVH_cjs.extractMatrxErrorCode(serverDetail);
511
511
  diagnostics?.onError?.(
512
512
  {
513
513
  type: classifyStatus(response.status),
514
- message: chunkYUDQWDCM_cjs.extractMatrxErrorMessage(serverDetail) ?? `HTTP ${response.status}`,
514
+ message: chunkHER22VVH_cjs.extractMatrxErrorMessage(serverDetail) ?? `HTTP ${response.status}`,
515
515
  status: response.status,
516
516
  serverDetail,
517
517
  ...code ? { code } : {}
@@ -841,7 +841,7 @@ async function readServerDetail(response) {
841
841
  }
842
842
  }
843
843
  async function throwApiError(path, response) {
844
- throw new chunkYUDQWDCM_cjs.MatrxApiError({
844
+ throw new chunkHER22VVH_cjs.MatrxApiError({
845
845
  status: response.status,
846
846
  path,
847
847
  serverDetail: await readServerDetail(response)
@@ -862,7 +862,7 @@ function toRunHandle(response, options) {
862
862
  return {
863
863
  requestId: response.headers.get("X-Request-ID"),
864
864
  conversationId: response.headers.get("X-Conversation-ID"),
865
- events: chunkYUDQWDCM_cjs.readMatrxNdjsonStream(response.body, {
865
+ events: chunkHER22VVH_cjs.readMatrxNdjsonStream(response.body, {
866
866
  ...options.signal ? { signal: options.signal } : {},
867
867
  ...options.maxReadAhead !== void 0 ? { maxReadAhead: options.maxReadAhead } : {},
868
868
  ...options.onMalformedLine ? { onMalformedLine: options.onMalformedLine } : {},
@@ -885,7 +885,7 @@ async function requestStream(transport, path, options) {
885
885
  });
886
886
  if (!response.ok) return throwApiError(path, response);
887
887
  if (!response.body) {
888
- throw new chunkYUDQWDCM_cjs.MatrxApiError({
888
+ throw new chunkHER22VVH_cjs.MatrxApiError({
889
889
  status: response.status,
890
890
  path,
891
891
  serverDetail: { code: "missing_response_body" },
@@ -945,7 +945,7 @@ async function getRuntimeOperationStatus(transport, requestId, options = {}) {
945
945
  { method: "GET", ...options.signal ? { signal: options.signal } : {} }
946
946
  );
947
947
  } catch (error) {
948
- if (error instanceof chunkYUDQWDCM_cjs.MatrxApiError && error.status === 404) return null;
948
+ if (error instanceof chunkHER22VVH_cjs.MatrxApiError && error.status === 404) return null;
949
949
  throw error;
950
950
  }
951
951
  }
@@ -960,7 +960,7 @@ async function getRuntimeOperationsByLink(transport, linkKind, linkId, options =
960
960
  { method: "GET", ...options.signal ? { signal: options.signal } : {} }
961
961
  );
962
962
  } catch (error) {
963
- if (error instanceof chunkYUDQWDCM_cjs.MatrxApiError && error.status === 404) return null;
963
+ if (error instanceof chunkHER22VVH_cjs.MatrxApiError && error.status === 404) return null;
964
964
  throw error;
965
965
  }
966
966
  }
@@ -1001,7 +1001,7 @@ async function* followRuntimeOperationEvents(transport, executionId, options = {
1001
1001
  ...options.signal ? { signal: options.signal } : {}
1002
1002
  }
1003
1003
  );
1004
- const frames = chunkYUDQWDCM_cjs.readMatrxSseStream(
1004
+ const frames = chunkHER22VVH_cjs.readMatrxSseStream(
1005
1005
  response.body,
1006
1006
  options.onIncomplete ? { onIncomplete: options.onIncomplete } : {}
1007
1007
  );
@@ -1204,7 +1204,7 @@ async function openMatrxStream(transport, path, options = {}) {
1204
1204
  return toRunHandle(response, options);
1205
1205
  }
1206
1206
  function withRunOrganization(transport, organizationId) {
1207
- const orgId = chunkYUDQWDCM_cjs.requireOrganizationContext(organizationId);
1207
+ const orgId = chunkHER22VVH_cjs.requireOrganizationContext(organizationId);
1208
1208
  return {
1209
1209
  fetch: (path, init) => transport.fetch(path, {
1210
1210
  ...init,
@@ -1231,7 +1231,7 @@ async function followWorkflowRunEvents(transport, runId, options) {
1231
1231
  throw error;
1232
1232
  }
1233
1233
  try {
1234
- for await (const frame of chunkYUDQWDCM_cjs.readMatrxSseStream(
1234
+ for await (const frame of chunkHER22VVH_cjs.readMatrxSseStream(
1235
1235
  response.body
1236
1236
  )) {
1237
1237
  if (frame.event === "end") return { ended: true };
@@ -1277,7 +1277,7 @@ async function resumeOrRejoin(transport, resumeCall, options) {
1277
1277
  } catch (error) {
1278
1278
  const target = readLiveRunRejoin(error);
1279
1279
  if (!target) {
1280
- if (error instanceof chunkYUDQWDCM_cjs.MatrxApiError && isResumeConflict(error)) {
1280
+ if (error instanceof chunkHER22VVH_cjs.MatrxApiError && isResumeConflict(error)) {
1281
1281
  return { kind: "resume_conflict", error };
1282
1282
  }
1283
1283
  throw error;
@@ -1664,117 +1664,195 @@ async function reportProviderSessionFailure(transport, failure, options = {}) {
1664
1664
  }
1665
1665
  }
1666
1666
 
1667
+ // src/core/provider-usage.ts
1668
+ var TOKEN_MAX = 5e7;
1669
+ var clip2 = (value, max) => value.length > max ? value.slice(0, max) : value;
1670
+ var count = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.min(Math.floor(value), TOKEN_MAX) : 0;
1671
+ function providerSessionUsageBody(usage) {
1672
+ const seconds = typeof usage.seconds === "number" && Number.isFinite(usage.seconds) && usage.seconds > 0 ? Math.min(usage.seconds, 86400) : 0;
1673
+ return {
1674
+ provider: usage.provider,
1675
+ model: clip2(usage.model, 200),
1676
+ usage_id: clip2(usage.usage_id, 200),
1677
+ input_tokens: count(usage.input_tokens),
1678
+ output_tokens: count(usage.output_tokens),
1679
+ cached_input_tokens: count(usage.cached_input_tokens),
1680
+ characters: count(usage.characters),
1681
+ seconds
1682
+ };
1683
+ }
1684
+ function isEmptyProviderUsage(usage) {
1685
+ return !usage.usage_id?.trim() || !usage.model?.trim() || count(usage.input_tokens) === 0 && count(usage.output_tokens) === 0 && count(usage.cached_input_tokens) === 0 && count(usage.characters) === 0 && !(typeof usage.seconds === "number" && usage.seconds > 0);
1686
+ }
1687
+ async function reportProviderSessionUsage(transport, usage, options = {}) {
1688
+ try {
1689
+ await requestJson(transport, "/broker/usage", {
1690
+ method: "POST",
1691
+ body: providerSessionUsageBody(usage),
1692
+ ...options.signal ? { signal: options.signal } : {}
1693
+ });
1694
+ return "ok";
1695
+ } catch (error) {
1696
+ if (error instanceof chunkHER22VVH_cjs.MatrxApiError) {
1697
+ const status = error.status;
1698
+ if (status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 425 && status !== 429) {
1699
+ console.warn(`[provider-usage] server refused ${usage.provider} usage ${usage.usage_id} (${status})`);
1700
+ return "drop";
1701
+ }
1702
+ }
1703
+ return "retry";
1704
+ }
1705
+ }
1706
+ var DEFAULT_RETRY_DELAYS_MS = [1e3, 4e3, 15e3, 6e4, 18e4];
1707
+ function createProviderUsageReporter(options) {
1708
+ const delays = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
1709
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1710
+ const seen = /* @__PURE__ */ new Set();
1711
+ const inflight = /* @__PURE__ */ new Set();
1712
+ async function deliver(usage) {
1713
+ for (let attempt2 = 0; ; attempt2 += 1) {
1714
+ let result;
1715
+ try {
1716
+ result = await options.send(usage);
1717
+ } catch {
1718
+ result = "retry";
1719
+ }
1720
+ if (result !== "retry") return;
1721
+ if (attempt2 >= delays.length) {
1722
+ console.warn(`[provider-usage] gave up delivering ${usage.provider} usage ${usage.usage_id}`);
1723
+ seen.delete(`${usage.provider}:${usage.usage_id}`);
1724
+ return;
1725
+ }
1726
+ await sleep(delays[attempt2] ?? 0);
1727
+ }
1728
+ }
1729
+ return {
1730
+ report(usage) {
1731
+ if (isEmptyProviderUsage(usage)) return;
1732
+ const key = `${usage.provider}:${usage.usage_id}`;
1733
+ if (seen.has(key)) return;
1734
+ seen.add(key);
1735
+ const task = deliver(usage).finally(() => inflight.delete(task));
1736
+ inflight.add(task);
1737
+ },
1738
+ async flush() {
1739
+ while (inflight.size > 0) await Promise.all([...inflight]);
1740
+ },
1741
+ pending: () => inflight.size
1742
+ };
1743
+ }
1744
+
1667
1745
  Object.defineProperty(exports, "monitorStream", {
1668
1746
  enumerable: true,
1669
1747
  get: function () { return chunkFNIYADWI_cjs.monitorStream; }
1670
1748
  });
1671
1749
  Object.defineProperty(exports, "BackendApiError", {
1672
1750
  enumerable: true,
1673
- get: function () { return chunkYUDQWDCM_cjs.BackendApiError; }
1751
+ get: function () { return chunkHER22VVH_cjs.BackendApiError; }
1674
1752
  });
1675
1753
  Object.defineProperty(exports, "CONTRACT_SHA256", {
1676
1754
  enumerable: true,
1677
- get: function () { return chunkYUDQWDCM_cjs.CONTRACT_SHA256; }
1755
+ get: function () { return chunkHER22VVH_cjs.CONTRACT_SHA256; }
1678
1756
  });
1679
1757
  Object.defineProperty(exports, "DEPLOYMENTS", {
1680
1758
  enumerable: true,
1681
- get: function () { return chunkYUDQWDCM_cjs.DEPLOYMENTS; }
1759
+ get: function () { return chunkHER22VVH_cjs.DEPLOYMENTS; }
1682
1760
  });
1683
1761
  Object.defineProperty(exports, "DOMAINS", {
1684
1762
  enumerable: true,
1685
- get: function () { return chunkYUDQWDCM_cjs.DOMAINS; }
1763
+ get: function () { return chunkHER22VVH_cjs.DOMAINS; }
1686
1764
  });
1687
1765
  Object.defineProperty(exports, "MatrxApiError", {
1688
1766
  enumerable: true,
1689
- get: function () { return chunkYUDQWDCM_cjs.MatrxApiError; }
1767
+ get: function () { return chunkHER22VVH_cjs.MatrxApiError; }
1690
1768
  });
1691
1769
  Object.defineProperty(exports, "OrganizationContextError", {
1692
1770
  enumerable: true,
1693
- get: function () { return chunkYUDQWDCM_cjs.OrganizationContextError; }
1771
+ get: function () { return chunkHER22VVH_cjs.OrganizationContextError; }
1694
1772
  });
1695
1773
  Object.defineProperty(exports, "StreamTransportError", {
1696
1774
  enumerable: true,
1697
- get: function () { return chunkYUDQWDCM_cjs.StreamTransportError; }
1775
+ get: function () { return chunkHER22VVH_cjs.StreamTransportError; }
1698
1776
  });
1699
1777
  Object.defineProperty(exports, "applyOrganizationContextHeader", {
1700
1778
  enumerable: true,
1701
- get: function () { return chunkYUDQWDCM_cjs.applyOrganizationContextHeader; }
1779
+ get: function () { return chunkHER22VVH_cjs.applyOrganizationContextHeader; }
1702
1780
  });
1703
1781
  Object.defineProperty(exports, "assertOrganizationMatchesOperation", {
1704
1782
  enumerable: true,
1705
- get: function () { return chunkYUDQWDCM_cjs.assertOrganizationMatchesOperation; }
1783
+ get: function () { return chunkHER22VVH_cjs.assertOrganizationMatchesOperation; }
1706
1784
  });
1707
1785
  Object.defineProperty(exports, "assertQueryOrganizationMatchesContext", {
1708
1786
  enumerable: true,
1709
- get: function () { return chunkYUDQWDCM_cjs.assertQueryOrganizationMatchesContext; }
1787
+ get: function () { return chunkHER22VVH_cjs.assertQueryOrganizationMatchesContext; }
1710
1788
  });
1711
1789
  Object.defineProperty(exports, "createApi", {
1712
1790
  enumerable: true,
1713
- get: function () { return chunkYUDQWDCM_cjs.createApi; }
1791
+ get: function () { return chunkHER22VVH_cjs.createApi; }
1714
1792
  });
1715
1793
  Object.defineProperty(exports, "createOrganizationOperation", {
1716
1794
  enumerable: true,
1717
- get: function () { return chunkYUDQWDCM_cjs.createOrganizationOperation; }
1795
+ get: function () { return chunkHER22VVH_cjs.createOrganizationOperation; }
1718
1796
  });
1719
1797
  Object.defineProperty(exports, "describeBackendFailure", {
1720
1798
  enumerable: true,
1721
- get: function () { return chunkYUDQWDCM_cjs.describeBackendFailure; }
1799
+ get: function () { return chunkHER22VVH_cjs.describeBackendFailure; }
1722
1800
  });
1723
1801
  Object.defineProperty(exports, "extractMatrxErrorCode", {
1724
1802
  enumerable: true,
1725
- get: function () { return chunkYUDQWDCM_cjs.extractMatrxErrorCode; }
1803
+ get: function () { return chunkHER22VVH_cjs.extractMatrxErrorCode; }
1726
1804
  });
1727
1805
  Object.defineProperty(exports, "extractMatrxErrorMessage", {
1728
1806
  enumerable: true,
1729
- get: function () { return chunkYUDQWDCM_cjs.extractMatrxErrorMessage; }
1807
+ get: function () { return chunkHER22VVH_cjs.extractMatrxErrorMessage; }
1730
1808
  });
1731
1809
  Object.defineProperty(exports, "getUserMessage", {
1732
1810
  enumerable: true,
1733
- get: function () { return chunkYUDQWDCM_cjs.getUserMessage; }
1811
+ get: function () { return chunkHER22VVH_cjs.getUserMessage; }
1734
1812
  });
1735
1813
  Object.defineProperty(exports, "isGenericUserMessage", {
1736
1814
  enumerable: true,
1737
- get: function () { return chunkYUDQWDCM_cjs.isGenericUserMessage; }
1815
+ get: function () { return chunkHER22VVH_cjs.isGenericUserMessage; }
1738
1816
  });
1739
1817
  Object.defineProperty(exports, "isStreamTransportLost", {
1740
1818
  enumerable: true,
1741
- get: function () { return chunkYUDQWDCM_cjs.isStreamTransportLost; }
1819
+ get: function () { return chunkHER22VVH_cjs.isStreamTransportLost; }
1742
1820
  });
1743
1821
  Object.defineProperty(exports, "openJsonOrStream", {
1744
1822
  enumerable: true,
1745
- get: function () { return chunkYUDQWDCM_cjs.openJsonOrStream; }
1823
+ get: function () { return chunkHER22VVH_cjs.openJsonOrStream; }
1746
1824
  });
1747
1825
  Object.defineProperty(exports, "openStream", {
1748
1826
  enumerable: true,
1749
- get: function () { return chunkYUDQWDCM_cjs.openStream; }
1827
+ get: function () { return chunkHER22VVH_cjs.openStream; }
1750
1828
  });
1751
1829
  Object.defineProperty(exports, "parseCallApiError", {
1752
1830
  enumerable: true,
1753
- get: function () { return chunkYUDQWDCM_cjs.parseCallApiError; }
1831
+ get: function () { return chunkHER22VVH_cjs.parseCallApiError; }
1754
1832
  });
1755
1833
  Object.defineProperty(exports, "parseHttpError", {
1756
1834
  enumerable: true,
1757
- get: function () { return chunkYUDQWDCM_cjs.parseHttpError; }
1835
+ get: function () { return chunkHER22VVH_cjs.parseHttpError; }
1758
1836
  });
1759
1837
  Object.defineProperty(exports, "parseHttpErrorBody", {
1760
1838
  enumerable: true,
1761
- get: function () { return chunkYUDQWDCM_cjs.parseHttpErrorBody; }
1839
+ get: function () { return chunkHER22VVH_cjs.parseHttpErrorBody; }
1762
1840
  });
1763
1841
  Object.defineProperty(exports, "parsePersistedBackendError", {
1764
1842
  enumerable: true,
1765
- get: function () { return chunkYUDQWDCM_cjs.parsePersistedBackendError; }
1843
+ get: function () { return chunkHER22VVH_cjs.parsePersistedBackendError; }
1766
1844
  });
1767
1845
  Object.defineProperty(exports, "parseStreamError", {
1768
1846
  enumerable: true,
1769
- get: function () { return chunkYUDQWDCM_cjs.parseStreamError; }
1847
+ get: function () { return chunkHER22VVH_cjs.parseStreamError; }
1770
1848
  });
1771
1849
  Object.defineProperty(exports, "requireOrganizationContext", {
1772
1850
  enumerable: true,
1773
- get: function () { return chunkYUDQWDCM_cjs.requireOrganizationContext; }
1851
+ get: function () { return chunkHER22VVH_cjs.requireOrganizationContext; }
1774
1852
  });
1775
1853
  Object.defineProperty(exports, "unwrapUpstreamError", {
1776
1854
  enumerable: true,
1777
- get: function () { return chunkYUDQWDCM_cjs.unwrapUpstreamError; }
1855
+ get: function () { return chunkHER22VVH_cjs.unwrapUpstreamError; }
1778
1856
  });
1779
1857
  Object.defineProperty(exports, "AbortedError", {
1780
1858
  enumerable: true,
@@ -1834,19 +1912,19 @@ Object.defineProperty(exports, "withRetry", {
1834
1912
  });
1835
1913
  Object.defineProperty(exports, "API_KEY_PREFIX", {
1836
1914
  enumerable: true,
1837
- get: function () { return chunkBMQI7UET_cjs.API_KEY_PREFIX; }
1915
+ get: function () { return chunk5WJLKYH6_cjs.API_KEY_PREFIX; }
1838
1916
  });
1839
1917
  Object.defineProperty(exports, "MATRX_HEADERS", {
1840
1918
  enumerable: true,
1841
- get: function () { return chunkBMQI7UET_cjs.MATRX_HEADERS; }
1919
+ get: function () { return chunk5WJLKYH6_cjs.MATRX_HEADERS; }
1842
1920
  });
1843
1921
  Object.defineProperty(exports, "credentialToHeaders", {
1844
1922
  enumerable: true,
1845
- get: function () { return chunkBMQI7UET_cjs.credentialToHeaders; }
1923
+ get: function () { return chunk5WJLKYH6_cjs.credentialToHeaders; }
1846
1924
  });
1847
1925
  Object.defineProperty(exports, "toCredentialsPort", {
1848
1926
  enumerable: true,
1849
- get: function () { return chunkBMQI7UET_cjs.toCredentialsPort; }
1927
+ get: function () { return chunk5WJLKYH6_cjs.toCredentialsPort; }
1850
1928
  });
1851
1929
  exports.MATRX_AI_API_VERSION_DEFAULT = MATRX_AI_API_VERSION_DEFAULT;
1852
1930
  exports.MATRX_LIVE_STREAM_UNAVAILABLE = MATRX_LIVE_STREAM_UNAVAILABLE;
@@ -1870,6 +1948,7 @@ exports.buildSafeRequestLog = buildSafeRequestLog;
1870
1948
  exports.continueEphemeralConversationStart = continueEphemeralConversationStart;
1871
1949
  exports.continueStoredConversationStart = continueStoredConversationStart;
1872
1950
  exports.createMatrxTransport = createMatrxTransport;
1951
+ exports.createProviderUsageReporter = createProviderUsageReporter;
1873
1952
  exports.createStreamReplayCursor = createStreamReplayCursor;
1874
1953
  exports.createWarmup = createWarmup;
1875
1954
  exports.encodePathSegment = encodePathSegment;
@@ -1885,6 +1964,7 @@ exports.getRuntimeOperationsByLink = getRuntimeOperationsByLink;
1885
1964
  exports.honestTransportMessage = honestTransportMessage;
1886
1965
  exports.isBareTransportCode = isBareTransportCode;
1887
1966
  exports.isCoveredAiPath = isCoveredAiPath;
1967
+ exports.isEmptyProviderUsage = isEmptyProviderUsage;
1888
1968
  exports.isJobOutputKind = isJobOutputKind;
1889
1969
  exports.isLiveStreamUnavailable = isLiveStreamUnavailable;
1890
1970
  exports.isResumeConflict = isResumeConflict;
@@ -1901,6 +1981,7 @@ exports.parseMatrxNdjsonResponse = parseMatrxNdjsonResponse;
1901
1981
  exports.pickServerJobOperation = pickServerJobOperation;
1902
1982
  exports.preconnectServer = preconnectServer;
1903
1983
  exports.providerSessionFailureBody = providerSessionFailureBody;
1984
+ exports.providerSessionUsageBody = providerSessionUsageBody;
1904
1985
  exports.readConversationOrganizationId = readConversationOrganizationId;
1905
1986
  exports.readLiveRunRejoin = readLiveRunRejoin;
1906
1987
  exports.readLiveRunRequestId = readLiveRunRequestId;
@@ -1912,6 +1993,7 @@ exports.readStreamCursor = readStreamCursor;
1912
1993
  exports.redactUrlForRequestLog = redactUrlForRequestLog;
1913
1994
  exports.rejoinRuntimeOperation = rejoinRuntimeOperation;
1914
1995
  exports.reportProviderSessionFailure = reportProviderSessionFailure;
1996
+ exports.reportProviderSessionUsage = reportProviderSessionUsage;
1915
1997
  exports.requestJson = requestJson;
1916
1998
  exports.requestStream = requestStream;
1917
1999
  exports.resetPreconnectedForTests = resetPreconnectedForTests;
package/dist/index.d.cts CHANGED
@@ -2003,4 +2003,67 @@ declare function reportProviderSessionFailure(transport: MatrxTransport, failure
2003
2003
  signal?: AbortSignal;
2004
2004
  }): Promise<ProviderSessionFailureVerdict | null>;
2005
2005
 
2006
- export { type ApiTargetLogContext, BackendApiError, type BackendApiErrorData, type BackendErrorCode, type BackendFailureExplanation, type CreateMatrxTransportOptions, type CreateWarmupOptions, CredentialsPort, type EndpointOverrideConfig, type ExecuteMatrxCallHooks, type ExecuteMatrxCallRequest, type FollowRuntimeOperationOptions, type FollowRuntimeOperationToEndOptions, type FollowRuntimeOperationToEndResult, type FollowServerJobOptions, type FollowUnavailableRejoinOptions, type JsonRequestOptions, MATRX_AI_API_VERSION_DEFAULT, MATRX_LIVE_STREAM_UNAVAILABLE, MATRX_RESUME_CONFLICT, MATRX_RUN_IN_PROGRESS, MATRX_UI_ONLY_BODY_FIELDS, type MatrxAiApiVersion, MatrxApiError, type MatrxCallError, type MatrxCallResult, type MatrxCallScope, type MatrxChatMessage, type MatrxClientSessionProvider, type MatrxConversationStart, type MatrxEphemeralConversation, type MatrxFollowedOutcome, type MatrxHttpErrorLike, type MatrxHttpMethod, type MatrxJsonObject, type MatrxJsonValue, type MatrxLiveRunRejoin, type MatrxLiveStreamUnavailable, type MatrxOperationEventsPage, type MatrxOperationFollowEvent, type MatrxOperationStatusResponse, type MatrxOperationsByLinkResponse, type MatrxProtocolDowngrade, type MatrxProtocolFallbackOptions, type MatrxQueryParams, type MatrxRequestInfo, type MatrxRunHandle, type MatrxRunPickup, type MatrxRunPickupSettlement, type MatrxRuntimeExecutionStatus, type MatrxRuntimeOperationEvent, type MatrxRuntimeOperationView, type MatrxStoredConversationContinue, type MatrxStoredConversationCreate, type MatrxStreamCallOptions, type MatrxStreamCursorStamp, type MatrxStreamIds, type MatrxStreamParse, type MatrxTransport, type MatrxTransportDiagnostics, type MatrxTransportRequest, type MatrxTransportTarget, OrganizationContextError, type OrganizationContextErrorCode, type OrganizationOperation, type ParseMatrxNdjsonResponseHooks, type ProviderSessionFailure, type ProviderSessionFailureVerdict, type QueryValue, RUN_OUTPUT_KINDS, RUN_STREAM_LIFETIME_BACKSTOP_MS, RUN_WAIT_KNOB_FEATURE, ResilientFetchOptions, type ResumeOrRejoinOptions, type ResumeOrRejoinOutcome, type RunOutputKind, type RunWait, type RunWaitKnobReader, type SendMatrxRequestOptions, type ServerJobFinalStatus, type ServerJobOutcome, type ServerJobPath, type ServerJobStatus, type ServerJobTarget, type SettleRunPickupOptions, type StreamReplayCursor, type StreamReplayCursorOptions, type StreamRequestOptions, StreamTransportError, TERMINAL_MATRX_RUNTIME_STATUSES, type UpstreamErrorPayload, V2_COVERED_AI_PATH_TEMPLATES, WARM_PATH, type WarmItem, type WarmReason, type Warmup, aiVersionPathOverrides, applyAiApiVersion, applyDesktopTargetToRequestBody, applyOrganizationContextHeader, assertOrganizationMatchesOperation, assertQueryOrganizationMatchesContext, bareStatusSentence, buildMatrxRequestBody, buildMatrxRequestUrl, buildQuery, buildSafeRequestLog, continueEphemeralConversationStart, continueStoredConversationStart, createMatrxTransport, createOrganizationOperation, createStreamReplayCursor, createWarmup, describeBackendFailure, encodePathSegment, executeMatrxCall, extractMatrxErrorCode, extractMatrxErrorMessage, fetchWithMatrxProtocolFallback, followRuntimeOperationEvents, followRuntimeOperationToEnd, followServerJob, followUnavailableRejoin, followWorkflowRunEvents, getRuntimeOperationStatus, getRuntimeOperationsByLink, getUserMessage, honestTransportMessage, isBareTransportCode, isCoveredAiPath, isGenericUserMessage, isJobOutputKind, isLiveStreamUnavailable, isResumeConflict, isServerJobSettled, isStreamTransportLost, isV2Path, listRuntimeOperationEvents, logApiTarget, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, normalizeMatrxError, openMatrxStream, parseCallApiError, parseHttpError, parseHttpErrorBody, parseMatrxNdjsonResponse, parsePersistedBackendError, parseStreamError, pickServerJobOperation, preconnectServer, providerSessionFailureBody, readConversationOrganizationId, readLiveRunRejoin, readLiveRunRequestId, readLiveStreamUnavailable, readMatrxErrorCode, readMatrxErrorCodeFromMessage, readMatrxJsonResponse, readStreamCursor, redactUrlForRequestLog, rejoinRuntimeOperation, reportProviderSessionFailure, requestJson, requestStream, requireOrganizationContext, resetPreconnectedForTests, resolveEndpointPath, resolveRunWaitWith, resumeOrRejoin, runJobLabel, runOutputKindFromModalities, runWaitKnobKey, runWaitTimeoutMessage, runtimeOperationRejoinPath, sendMatrxRequest, serverJobRejoinHandle, settleRunPickup, shouldReportMatrxCallError, streamErrorText, toRunHandle, toV1FallbackUrl, toV2Path, unwrapUpstreamError, withRunOrganization };
2006
+ /**
2007
+ * Browser-held provider sessions report what they spent.
2008
+ *
2009
+ * Realtime voice (OpenAI / xAI) and Cartesia TTS are spent browser -> provider on a
2010
+ * broker-minted ephemeral token, so no server seam sees the money. Every such session reports
2011
+ * the provider's own usage once per billed unit; the server prices it through the AI catalog
2012
+ * (a client never states a cost) and bills the signed-in person in their active organization.
2013
+ *
2014
+ * Server truth: `POST /broker/usage` (`ProviderSessionUsageReport`, `extra="forbid"`). A
2015
+ * `usage_id` bills ONCE — so a repeat send is always safe, which is what lets the reporter
2016
+ * retry freely.
2017
+ *
2018
+ * Two layers:
2019
+ * - `reportProviderSessionUsage(transport, usage)` - one attempt, classified, never throws;
2020
+ * - `createProviderUsageReporter({ send })` - the queue every session uses: retries
2021
+ * transient failures with backoff, drops permanent refusals (4xx), de-duplicates by
2022
+ * `usage_id`, and `flush()` drains it when a session ends.
2023
+ */
2024
+
2025
+ /** One billed unit: a realtime response, a TTS generation, or a slice of session time. */
2026
+ interface ProviderSessionUsage {
2027
+ provider: MatrxClientSessionProvider;
2028
+ model: string;
2029
+ /** The provider's own response / generation id; bills once. */
2030
+ usage_id: string;
2031
+ input_tokens?: number;
2032
+ output_tokens?: number;
2033
+ cached_input_tokens?: number;
2034
+ characters?: number;
2035
+ seconds?: number;
2036
+ }
2037
+ interface ProviderSessionUsageReceipt {
2038
+ billed: boolean;
2039
+ duplicate: boolean;
2040
+ cost_usd: number;
2041
+ }
2042
+ /** `ok` = the server has it (billed or already had it). `retry` = transient. `drop` = refused for good. */
2043
+ type ProviderUsageSendResult = "ok" | "retry" | "drop";
2044
+ /** The body the server accepts — bounded exactly as its model bounds it. */
2045
+ declare function providerSessionUsageBody(usage: ProviderSessionUsage): Record<string, string | number>;
2046
+ /** True when the unit carries nothing the server could price. */
2047
+ declare function isEmptyProviderUsage(usage: ProviderSessionUsage): boolean;
2048
+ /** One attempt over the transport. Never throws; the result says whether to try again. */
2049
+ declare function reportProviderSessionUsage(transport: MatrxTransport, usage: ProviderSessionUsage, options?: {
2050
+ signal?: AbortSignal;
2051
+ }): Promise<ProviderUsageSendResult>;
2052
+ interface ProviderUsageReporterOptions {
2053
+ send: (usage: ProviderSessionUsage) => Promise<ProviderUsageSendResult>;
2054
+ /** Delay before each retry; its length is the retry budget. */
2055
+ retryDelaysMs?: readonly number[];
2056
+ /** Injectable for tests. */
2057
+ sleep?: (ms: number) => Promise<void>;
2058
+ }
2059
+ interface ProviderUsageReporter {
2060
+ /** Queue a unit. Synchronous, never throws. A usage_id already queued or sent is ignored. */
2061
+ report(usage: ProviderSessionUsage): void;
2062
+ /** Resolves when everything queued so far has been delivered or given up on. */
2063
+ flush(): Promise<void>;
2064
+ /** Units still waiting on delivery. */
2065
+ pending(): number;
2066
+ }
2067
+ declare function createProviderUsageReporter(options: ProviderUsageReporterOptions): ProviderUsageReporter;
2068
+
2069
+ export { type ApiTargetLogContext, BackendApiError, type BackendApiErrorData, type BackendErrorCode, type BackendFailureExplanation, type CreateMatrxTransportOptions, type CreateWarmupOptions, CredentialsPort, type EndpointOverrideConfig, type ExecuteMatrxCallHooks, type ExecuteMatrxCallRequest, type FollowRuntimeOperationOptions, type FollowRuntimeOperationToEndOptions, type FollowRuntimeOperationToEndResult, type FollowServerJobOptions, type FollowUnavailableRejoinOptions, type JsonRequestOptions, MATRX_AI_API_VERSION_DEFAULT, MATRX_LIVE_STREAM_UNAVAILABLE, MATRX_RESUME_CONFLICT, MATRX_RUN_IN_PROGRESS, MATRX_UI_ONLY_BODY_FIELDS, type MatrxAiApiVersion, MatrxApiError, type MatrxCallError, type MatrxCallResult, type MatrxCallScope, type MatrxChatMessage, type MatrxClientSessionProvider, type MatrxConversationStart, type MatrxEphemeralConversation, type MatrxFollowedOutcome, type MatrxHttpErrorLike, type MatrxHttpMethod, type MatrxJsonObject, type MatrxJsonValue, type MatrxLiveRunRejoin, type MatrxLiveStreamUnavailable, type MatrxOperationEventsPage, type MatrxOperationFollowEvent, type MatrxOperationStatusResponse, type MatrxOperationsByLinkResponse, type MatrxProtocolDowngrade, type MatrxProtocolFallbackOptions, type MatrxQueryParams, type MatrxRequestInfo, type MatrxRunHandle, type MatrxRunPickup, type MatrxRunPickupSettlement, type MatrxRuntimeExecutionStatus, type MatrxRuntimeOperationEvent, type MatrxRuntimeOperationView, type MatrxStoredConversationContinue, type MatrxStoredConversationCreate, type MatrxStreamCallOptions, type MatrxStreamCursorStamp, type MatrxStreamIds, type MatrxStreamParse, type MatrxTransport, type MatrxTransportDiagnostics, type MatrxTransportRequest, type MatrxTransportTarget, OrganizationContextError, type OrganizationContextErrorCode, type OrganizationOperation, type ParseMatrxNdjsonResponseHooks, type ProviderSessionFailure, type ProviderSessionFailureVerdict, type ProviderSessionUsage, type ProviderSessionUsageReceipt, type ProviderUsageReporter, type ProviderUsageReporterOptions, type ProviderUsageSendResult, type QueryValue, RUN_OUTPUT_KINDS, RUN_STREAM_LIFETIME_BACKSTOP_MS, RUN_WAIT_KNOB_FEATURE, ResilientFetchOptions, type ResumeOrRejoinOptions, type ResumeOrRejoinOutcome, type RunOutputKind, type RunWait, type RunWaitKnobReader, type SendMatrxRequestOptions, type ServerJobFinalStatus, type ServerJobOutcome, type ServerJobPath, type ServerJobStatus, type ServerJobTarget, type SettleRunPickupOptions, type StreamReplayCursor, type StreamReplayCursorOptions, type StreamRequestOptions, StreamTransportError, TERMINAL_MATRX_RUNTIME_STATUSES, type UpstreamErrorPayload, V2_COVERED_AI_PATH_TEMPLATES, WARM_PATH, type WarmItem, type WarmReason, type Warmup, aiVersionPathOverrides, applyAiApiVersion, applyDesktopTargetToRequestBody, applyOrganizationContextHeader, assertOrganizationMatchesOperation, assertQueryOrganizationMatchesContext, bareStatusSentence, buildMatrxRequestBody, buildMatrxRequestUrl, buildQuery, buildSafeRequestLog, continueEphemeralConversationStart, continueStoredConversationStart, createMatrxTransport, createOrganizationOperation, createProviderUsageReporter, createStreamReplayCursor, createWarmup, describeBackendFailure, encodePathSegment, executeMatrxCall, extractMatrxErrorCode, extractMatrxErrorMessage, fetchWithMatrxProtocolFallback, followRuntimeOperationEvents, followRuntimeOperationToEnd, followServerJob, followUnavailableRejoin, followWorkflowRunEvents, getRuntimeOperationStatus, getRuntimeOperationsByLink, getUserMessage, honestTransportMessage, isBareTransportCode, isCoveredAiPath, isEmptyProviderUsage, isGenericUserMessage, isJobOutputKind, isLiveStreamUnavailable, isResumeConflict, isServerJobSettled, isStreamTransportLost, isV2Path, listRuntimeOperationEvents, logApiTarget, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, normalizeMatrxError, openMatrxStream, parseCallApiError, parseHttpError, parseHttpErrorBody, parseMatrxNdjsonResponse, parsePersistedBackendError, parseStreamError, pickServerJobOperation, preconnectServer, providerSessionFailureBody, providerSessionUsageBody, readConversationOrganizationId, readLiveRunRejoin, readLiveRunRequestId, readLiveStreamUnavailable, readMatrxErrorCode, readMatrxErrorCodeFromMessage, readMatrxJsonResponse, readStreamCursor, redactUrlForRequestLog, rejoinRuntimeOperation, reportProviderSessionFailure, reportProviderSessionUsage, requestJson, requestStream, requireOrganizationContext, resetPreconnectedForTests, resolveEndpointPath, resolveRunWaitWith, resumeOrRejoin, runJobLabel, runOutputKindFromModalities, runWaitKnobKey, runWaitTimeoutMessage, runtimeOperationRejoinPath, sendMatrxRequest, serverJobRejoinHandle, settleRunPickup, shouldReportMatrxCallError, streamErrorText, toRunHandle, toV1FallbackUrl, toV2Path, unwrapUpstreamError, withRunOrganization };