@ai-matrx/api 0.1.7 → 0.1.9

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 (122) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/account.d.cts +1 -1
  3. package/dist/account.d.ts +1 -1
  4. package/dist/agents.cjs +11 -11
  5. package/dist/agents.d.cts +1 -1
  6. package/dist/agents.d.ts +1 -1
  7. package/dist/agents.js +1 -1
  8. package/dist/ai.cjs +2 -2
  9. package/dist/ai.d.cts +1 -1
  10. package/dist/ai.d.ts +1 -1
  11. package/dist/ai.js +1 -1
  12. package/dist/apps.cjs +5 -5
  13. package/dist/apps.d.cts +1 -1
  14. package/dist/apps.d.ts +1 -1
  15. package/dist/apps.js +1 -1
  16. package/dist/architecture.cjs +10 -10
  17. package/dist/architecture.d.cts +1 -1
  18. package/dist/architecture.d.ts +1 -1
  19. package/dist/architecture.js +1 -1
  20. package/dist/audio.cjs +4 -4
  21. package/dist/audio.d.cts +1 -1
  22. package/dist/audio.d.ts +1 -1
  23. package/dist/audio.js +1 -1
  24. package/dist/chat.cjs +11 -11
  25. package/dist/chat.d.cts +1 -1
  26. package/dist/chat.d.ts +1 -1
  27. package/dist/chat.js +1 -1
  28. package/dist/{chunk-2FJPWNXG.js → chunk-PIVTHTVR.js} +22 -7
  29. package/dist/{chunk-UO3H55R3.cjs → chunk-PMGKZ4FT.cjs} +22 -7
  30. package/dist/code.cjs +6 -6
  31. package/dist/code.d.cts +1 -1
  32. package/dist/code.d.ts +1 -1
  33. package/dist/code.js +1 -1
  34. package/dist/commerce.d.cts +1 -1
  35. package/dist/commerce.d.ts +1 -1
  36. package/dist/communications.cjs +4 -4
  37. package/dist/communications.d.cts +1 -1
  38. package/dist/communications.d.ts +1 -1
  39. package/dist/communications.js +1 -1
  40. package/dist/computer.cjs +3 -3
  41. package/dist/computer.d.cts +1 -1
  42. package/dist/computer.d.ts +1 -1
  43. package/dist/computer.js +1 -1
  44. package/dist/content.cjs +4 -4
  45. package/dist/content.d.cts +1 -1
  46. package/dist/content.d.ts +1 -1
  47. package/dist/content.js +1 -1
  48. package/dist/crm.cjs +2 -2
  49. package/dist/crm.d.cts +1 -1
  50. package/dist/crm.d.ts +1 -1
  51. package/dist/crm.js +1 -1
  52. package/dist/data.d.cts +1 -1
  53. package/dist/data.d.ts +1 -1
  54. package/dist/education.cjs +4 -4
  55. package/dist/education.d.cts +1 -1
  56. package/dist/education.d.ts +1 -1
  57. package/dist/education.js +1 -1
  58. package/dist/files.cjs +20 -20
  59. package/dist/files.d.cts +1 -1
  60. package/dist/files.d.ts +1 -1
  61. package/dist/files.js +1 -1
  62. package/dist/human-resources.d.cts +1 -1
  63. package/dist/human-resources.d.ts +1 -1
  64. package/dist/{index-Xx6L_pWk.d.cts → index-C3ZlP3BI.d.cts} +13 -1
  65. package/dist/{index-Xx6L_pWk.d.ts → index-C3ZlP3BI.d.ts} +13 -1
  66. package/dist/index.cjs +697 -53
  67. package/dist/index.d.cts +792 -12
  68. package/dist/index.d.ts +792 -12
  69. package/dist/index.js +636 -3
  70. package/dist/integrations.cjs +3 -3
  71. package/dist/integrations.d.cts +1 -1
  72. package/dist/integrations.d.ts +1 -1
  73. package/dist/integrations.js +1 -1
  74. package/dist/intelligence.cjs +19 -8
  75. package/dist/intelligence.d.cts +3 -648
  76. package/dist/intelligence.d.ts +3 -648
  77. package/dist/intelligence.js +14 -3
  78. package/dist/keys.generated-CK_C5UXG.d.cts +658 -0
  79. package/dist/keys.generated-CK_C5UXG.d.ts +658 -0
  80. package/dist/knowledge.cjs +42 -42
  81. package/dist/knowledge.d.cts +1 -1
  82. package/dist/knowledge.d.ts +1 -1
  83. package/dist/knowledge.js +1 -1
  84. package/dist/legal.cjs +6 -6
  85. package/dist/legal.d.cts +1 -1
  86. package/dist/legal.d.ts +1 -1
  87. package/dist/legal.js +1 -1
  88. package/dist/marketing.cjs +76 -76
  89. package/dist/marketing.d.cts +1 -1
  90. package/dist/marketing.d.ts +1 -1
  91. package/dist/marketing.js +1 -1
  92. package/dist/masterwork.cjs +32 -32
  93. package/dist/masterwork.d.cts +1 -1
  94. package/dist/masterwork.d.ts +1 -1
  95. package/dist/masterwork.js +1 -1
  96. package/dist/media.cjs +11 -11
  97. package/dist/media.d.cts +1 -1
  98. package/dist/media.d.ts +1 -1
  99. package/dist/media.js +1 -1
  100. package/dist/net.d.cts +1 -1
  101. package/dist/net.d.ts +1 -1
  102. package/dist/platform.cjs +3 -3
  103. package/dist/platform.d.cts +1 -1
  104. package/dist/platform.d.ts +1 -1
  105. package/dist/platform.js +1 -1
  106. package/dist/publish.cjs +7 -7
  107. package/dist/publish.d.cts +1 -1
  108. package/dist/publish.d.ts +1 -1
  109. package/dist/publish.js +1 -1
  110. package/dist/stream.cjs +10 -10
  111. package/dist/stream.d.cts +1 -1
  112. package/dist/stream.d.ts +1 -1
  113. package/dist/stream.js +1 -1
  114. package/dist/web.cjs +26 -26
  115. package/dist/web.d.cts +1 -1
  116. package/dist/web.d.ts +1 -1
  117. package/dist/web.js +1 -1
  118. package/dist/workflows.cjs +13 -13
  119. package/dist/workflows.d.cts +1 -1
  120. package/dist/workflows.d.ts +1 -1
  121. package/dist/workflows.js +1 -1
  122. package/package.json +4 -4
package/dist/index.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  var chunkFNIYADWI_cjs = require('./chunk-FNIYADWI.cjs');
4
4
  var chunkMVXD6WI6_cjs = require('./chunk-MVXD6WI6.cjs');
5
- var chunkUO3H55R3_cjs = require('./chunk-UO3H55R3.cjs');
5
+ var chunkPMGKZ4FT_cjs = require('./chunk-PMGKZ4FT.cjs');
6
6
  var chunk2SXAAKGV_cjs = require('./chunk-2SXAAKGV.cjs');
7
7
  var credentials = require('@ai-matrx/auth/credentials');
8
8
  var format = require('@ai-matrx/kit/format');
@@ -128,7 +128,7 @@ function buildMatrxRequestBody(body, scope) {
128
128
  }
129
129
  const bodyOrganizationId = base.organization_id;
130
130
  if (scope.organization_id !== void 0 && bodyOrganizationId !== void 0 && (typeof bodyOrganizationId !== "string" || bodyOrganizationId.trim() !== scope.organization_id)) {
131
- throw new chunkUO3H55R3_cjs.OrganizationContextError(
131
+ throw new chunkPMGKZ4FT_cjs.OrganizationContextError(
132
132
  "organization_context_mismatch",
133
133
  "Request body organization_id must match the request context organization."
134
134
  );
@@ -200,14 +200,14 @@ function parseMatrxNdjsonResponse(response, signal, hooks = {}) {
200
200
  };
201
201
  async function* events() {
202
202
  if (!response.body) {
203
- throw new chunkUO3H55R3_cjs.BackendApiError({
203
+ throw new chunkPMGKZ4FT_cjs.BackendApiError({
204
204
  code: "internal_error",
205
205
  detail: "Response has no body",
206
206
  userMessage: "No response received from server"
207
207
  });
208
208
  }
209
209
  try {
210
- for await (const envelope of chunkUO3H55R3_cjs.readMatrxNdjsonStream(response.body, {
210
+ for await (const envelope of chunkPMGKZ4FT_cjs.readMatrxNdjsonStream(response.body, {
211
211
  ...signal ? { signal } : {},
212
212
  ...hooks.onMalformedLine ? { onMalformedLine: hooks.onMalformedLine } : {},
213
213
  ...hooks.onUnknownEnvelope ? { onUnknownEnvelope: hooks.onUnknownEnvelope } : {}
@@ -219,7 +219,7 @@ function parseMatrxNdjsonResponse(response, signal, hooks = {}) {
219
219
  if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
220
220
  return;
221
221
  }
222
- const transportError = error instanceof chunkUO3H55R3_cjs.BackendApiError ? error : new chunkUO3H55R3_cjs.StreamTransportError({
222
+ const transportError = error instanceof chunkPMGKZ4FT_cjs.BackendApiError ? error : new chunkPMGKZ4FT_cjs.StreamTransportError({
223
223
  detail: error instanceof Error ? error.message : "The response stream ended unexpectedly.",
224
224
  details: error,
225
225
  ...ids.requestId ? { requestId: ids.requestId } : {}
@@ -236,7 +236,7 @@ async function httpErrorFrom(response) {
236
236
  const serverDetail = await response.json().catch(() => void 0);
237
237
  return {
238
238
  type: response.status >= 400 && response.status < 500 ? "validation_error" : "http_error",
239
- message: chunkUO3H55R3_cjs.extractMatrxErrorMessage(serverDetail) ?? bareStatusSentence(response.status),
239
+ message: chunkPMGKZ4FT_cjs.extractMatrxErrorMessage(serverDetail) ?? bareStatusSentence(response.status),
240
240
  status: response.status,
241
241
  serverDetail
242
242
  };
@@ -312,7 +312,7 @@ async function sendMatrxRequest(url, init = {}, options = {}) {
312
312
  return await fetch(url, { ...init, signal: controller.signal });
313
313
  } catch (error) {
314
314
  if (timedOut) {
315
- throw new chunkUO3H55R3_cjs.BackendApiError({
315
+ throw new chunkPMGKZ4FT_cjs.BackendApiError({
316
316
  code: "request_timeout",
317
317
  detail: `${init.method ?? "GET"} ${url} exceeded ${options.timeoutMs}ms`,
318
318
  userMessage: "The request timed out \u2014 please retry.",
@@ -326,7 +326,7 @@ async function sendMatrxRequest(url, init = {}, options = {}) {
326
326
  }
327
327
  }
328
328
  async function readMatrxJsonResponse(response) {
329
- if (!response.ok) throw await chunkUO3H55R3_cjs.parseHttpError(response);
329
+ if (!response.ok) throw await chunkPMGKZ4FT_cjs.parseHttpError(response);
330
330
  if (response.status === 204) return null;
331
331
  return await response.json();
332
332
  }
@@ -334,7 +334,7 @@ function classifyStatus(status) {
334
334
  return status >= 400 && status < 500 ? "validation_error" : "http_error";
335
335
  }
336
336
  function normalizeMatrxError(err) {
337
- if (err instanceof chunkUO3H55R3_cjs.OrganizationContextError) {
337
+ if (err instanceof chunkPMGKZ4FT_cjs.OrganizationContextError) {
338
338
  return {
339
339
  type: "validation_error",
340
340
  message: err.message,
@@ -346,7 +346,7 @@ function normalizeMatrxError(err) {
346
346
  if (err instanceof DOMException && err.name === "AbortError") {
347
347
  return { type: "abort_error", message: "Request was cancelled." };
348
348
  }
349
- if (err instanceof chunkUO3H55R3_cjs.MatrxApiError) {
349
+ if (err instanceof chunkPMGKZ4FT_cjs.MatrxApiError) {
350
350
  return {
351
351
  type: classifyStatus(err.status),
352
352
  message: honestTransportMessage(err.message, err.status),
@@ -356,7 +356,7 @@ function normalizeMatrxError(err) {
356
356
  name: err.name
357
357
  };
358
358
  }
359
- if (err instanceof chunkUO3H55R3_cjs.BackendApiError) {
359
+ if (err instanceof chunkPMGKZ4FT_cjs.BackendApiError) {
360
360
  return {
361
361
  type: "network_error",
362
362
  message: honestTransportMessage(
@@ -454,9 +454,9 @@ function createMatrxTransport(options) {
454
454
  };
455
455
  const resolveOrganizationId = (callOrganizationId) => {
456
456
  if (organizationId === void 0) return null;
457
- if (callOrganizationId !== null) return chunkUO3H55R3_cjs.requireOrganizationContext(callOrganizationId);
457
+ if (callOrganizationId !== null) return chunkPMGKZ4FT_cjs.requireOrganizationContext(callOrganizationId);
458
458
  const candidate = typeof organizationId === "function" ? organizationId() : organizationId;
459
- return chunkUO3H55R3_cjs.requireOrganizationContext(candidate);
459
+ return chunkPMGKZ4FT_cjs.requireOrganizationContext(candidate);
460
460
  };
461
461
  return {
462
462
  async fetch(path, init) {
@@ -473,7 +473,7 @@ function createMatrxTransport(options) {
473
473
  };
474
474
  const orgId = resolveOrganizationId(callOrganizationId);
475
475
  if (orgId !== null) {
476
- headers = chunkUO3H55R3_cjs.applyOrganizationContextHeader(headers, orgId);
476
+ headers = chunkPMGKZ4FT_cjs.applyOrganizationContextHeader(headers, orgId);
477
477
  }
478
478
  const info = {
479
479
  url,
@@ -506,11 +506,11 @@ function createMatrxTransport(options) {
506
506
  }
507
507
  if (!response.ok && !expectedErrorStatuses?.includes(response.status)) {
508
508
  const serverDetail = await response.clone().json().catch(() => void 0);
509
- const code = chunkUO3H55R3_cjs.extractMatrxErrorCode(serverDetail);
509
+ const code = chunkPMGKZ4FT_cjs.extractMatrxErrorCode(serverDetail);
510
510
  diagnostics?.onError?.(
511
511
  {
512
512
  type: classifyStatus(response.status),
513
- message: chunkUO3H55R3_cjs.extractMatrxErrorMessage(serverDetail) ?? `HTTP ${response.status}`,
513
+ message: chunkPMGKZ4FT_cjs.extractMatrxErrorMessage(serverDetail) ?? `HTTP ${response.status}`,
514
514
  status: response.status,
515
515
  serverDetail,
516
516
  ...code ? { code } : {}
@@ -840,7 +840,7 @@ async function readServerDetail(response) {
840
840
  }
841
841
  }
842
842
  async function throwApiError(path, response) {
843
- throw new chunkUO3H55R3_cjs.MatrxApiError({
843
+ throw new chunkPMGKZ4FT_cjs.MatrxApiError({
844
844
  status: response.status,
845
845
  path,
846
846
  serverDetail: await readServerDetail(response)
@@ -861,7 +861,7 @@ function toRunHandle(response, options) {
861
861
  return {
862
862
  requestId: response.headers.get("X-Request-ID"),
863
863
  conversationId: response.headers.get("X-Conversation-ID"),
864
- events: chunkUO3H55R3_cjs.readMatrxNdjsonStream(response.body, {
864
+ events: chunkPMGKZ4FT_cjs.readMatrxNdjsonStream(response.body, {
865
865
  ...options.signal ? { signal: options.signal } : {},
866
866
  ...options.maxReadAhead !== void 0 ? { maxReadAhead: options.maxReadAhead } : {},
867
867
  ...options.onMalformedLine ? { onMalformedLine: options.onMalformedLine } : {},
@@ -884,7 +884,7 @@ async function requestStream(transport, path, options) {
884
884
  });
885
885
  if (!response.ok) return throwApiError(path, response);
886
886
  if (!response.body) {
887
- throw new chunkUO3H55R3_cjs.MatrxApiError({
887
+ throw new chunkPMGKZ4FT_cjs.MatrxApiError({
888
888
  status: response.status,
889
889
  path,
890
890
  serverDetail: { code: "missing_response_body" },
@@ -944,7 +944,7 @@ async function getRuntimeOperationStatus(transport, requestId, options = {}) {
944
944
  { method: "GET", ...options.signal ? { signal: options.signal } : {} }
945
945
  );
946
946
  } catch (error) {
947
- if (error instanceof chunkUO3H55R3_cjs.MatrxApiError && error.status === 404) return null;
947
+ if (error instanceof chunkPMGKZ4FT_cjs.MatrxApiError && error.status === 404) return null;
948
948
  throw error;
949
949
  }
950
950
  }
@@ -959,7 +959,7 @@ async function getRuntimeOperationsByLink(transport, linkKind, linkId, options =
959
959
  { method: "GET", ...options.signal ? { signal: options.signal } : {} }
960
960
  );
961
961
  } catch (error) {
962
- if (error instanceof chunkUO3H55R3_cjs.MatrxApiError && error.status === 404) return null;
962
+ if (error instanceof chunkPMGKZ4FT_cjs.MatrxApiError && error.status === 404) return null;
963
963
  throw error;
964
964
  }
965
965
  }
@@ -1000,7 +1000,7 @@ async function* followRuntimeOperationEvents(transport, executionId, options = {
1000
1000
  ...options.signal ? { signal: options.signal } : {}
1001
1001
  }
1002
1002
  );
1003
- const frames = chunkUO3H55R3_cjs.readMatrxSseStream(
1003
+ const frames = chunkPMGKZ4FT_cjs.readMatrxSseStream(
1004
1004
  response.body,
1005
1005
  options.onIncomplete ? { onIncomplete: options.onIncomplete } : {}
1006
1006
  );
@@ -1203,7 +1203,7 @@ async function openMatrxStream(transport, path, options = {}) {
1203
1203
  return toRunHandle(response, options);
1204
1204
  }
1205
1205
  function withRunOrganization(transport, organizationId) {
1206
- const orgId = chunkUO3H55R3_cjs.requireOrganizationContext(organizationId);
1206
+ const orgId = chunkPMGKZ4FT_cjs.requireOrganizationContext(organizationId);
1207
1207
  return {
1208
1208
  fetch: (path, init) => transport.fetch(path, {
1209
1209
  ...init,
@@ -1230,7 +1230,7 @@ async function followWorkflowRunEvents(transport, runId, options) {
1230
1230
  throw error;
1231
1231
  }
1232
1232
  try {
1233
- for await (const frame of chunkUO3H55R3_cjs.readMatrxSseStream(
1233
+ for await (const frame of chunkPMGKZ4FT_cjs.readMatrxSseStream(
1234
1234
  response.body
1235
1235
  )) {
1236
1236
  if (frame.event === "end") return { ended: true };
@@ -1276,7 +1276,7 @@ async function resumeOrRejoin(transport, resumeCall, options) {
1276
1276
  } catch (error) {
1277
1277
  const target = readLiveRunRejoin(error);
1278
1278
  if (!target) {
1279
- if (error instanceof chunkUO3H55R3_cjs.MatrxApiError && isResumeConflict(error)) {
1279
+ if (error instanceof chunkPMGKZ4FT_cjs.MatrxApiError && isResumeConflict(error)) {
1280
1280
  return { kind: "resume_conflict", error };
1281
1281
  }
1282
1282
  throw error;
@@ -1692,7 +1692,7 @@ async function reportProviderSessionUsage(transport, usage, options = {}) {
1692
1692
  });
1693
1693
  return "ok";
1694
1694
  } catch (error) {
1695
- if (error instanceof chunkUO3H55R3_cjs.MatrxApiError) {
1695
+ if (error instanceof chunkPMGKZ4FT_cjs.MatrxApiError) {
1696
1696
  const status = error.status;
1697
1697
  if (status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 425 && status !== 429) {
1698
1698
  console.warn(`[provider-usage] server refused ${usage.provider} usage ${usage.usage_id} (${status})`);
@@ -1741,6 +1741,639 @@ function createProviderUsageReporter(options) {
1741
1741
  };
1742
1742
  }
1743
1743
 
1744
+ // src/core/run.ts
1745
+ async function streamCall(transport, path, body, options) {
1746
+ const response = await requestStream(transport, path, {
1747
+ method: "POST",
1748
+ // This client IS the streaming path — `stream: true` always, last so a
1749
+ // caller-supplied value can never flip the response off NDJSON.
1750
+ body: { ...body, stream: true },
1751
+ ...options.signal ? { signal: options.signal } : {}
1752
+ });
1753
+ return toRunHandle(response, options);
1754
+ }
1755
+ function startAgentRun(transport, agentId, request, options = {}) {
1756
+ return streamCall(
1757
+ transport,
1758
+ `/ai/agents/${encodePathSegment(agentId)}`,
1759
+ request,
1760
+ options
1761
+ );
1762
+ }
1763
+ function startMandateRun(transport, mandateKey, request, options = {}) {
1764
+ return streamCall(
1765
+ transport,
1766
+ `/ai/mandates/${encodePathSegment(mandateKey)}`,
1767
+ request,
1768
+ options
1769
+ );
1770
+ }
1771
+ function continueAgentConversation(transport, conversationId, request, options = {}) {
1772
+ return streamCall(
1773
+ transport,
1774
+ `/ai/conversations/${encodePathSegment(conversationId)}`,
1775
+ request,
1776
+ options
1777
+ );
1778
+ }
1779
+ function resumeAgentConversation(transport, conversationId, request = {}, options = {}) {
1780
+ return streamCall(
1781
+ transport,
1782
+ `/ai/conversations/${encodePathSegment(conversationId)}/resume`,
1783
+ request,
1784
+ options
1785
+ );
1786
+ }
1787
+ function cancelAgentRun(transport, requestId, options = {}) {
1788
+ const query = buildQuery(
1789
+ options.mode === "interrupt" ? { mode: "interrupt" } : {}
1790
+ );
1791
+ return requestJson(
1792
+ transport,
1793
+ `/ai/cancel/${encodePathSegment(requestId)}${query}`,
1794
+ {
1795
+ method: "POST",
1796
+ ...options.signal ? { signal: options.signal } : {}
1797
+ }
1798
+ );
1799
+ }
1800
+ var MatrxRunError = class extends Error {
1801
+ name = "MatrxRunError";
1802
+ /** The verbatim `error` event payload, when one fired. */
1803
+ errorPayload;
1804
+ /** The `user_request` completion status (`"failed"` | `"cancelled"`), when that was the trigger. */
1805
+ completionStatus;
1806
+ /** Text streamed before the failure — partial content never vanishes. */
1807
+ partialText;
1808
+ constructor(args) {
1809
+ super(args.message);
1810
+ this.errorPayload = args.errorPayload ?? null;
1811
+ this.completionStatus = args.completionStatus ?? null;
1812
+ this.partialText = args.partialText ?? "";
1813
+ }
1814
+ };
1815
+ function isRecord3(value) {
1816
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1817
+ }
1818
+ function stringField(value, key) {
1819
+ if (!isRecord3(value)) return null;
1820
+ const field = value[key];
1821
+ return typeof field === "string" && field ? field : null;
1822
+ }
1823
+ async function runAgentToCompletion(transport, agentId, request, options = {}) {
1824
+ const handle = await startAgentRun(transport, agentId, request, options);
1825
+ let text = "";
1826
+ let completion = null;
1827
+ let failure = null;
1828
+ for await (const envelope of handle.events) {
1829
+ options.onEvent?.(envelope);
1830
+ if (envelope.event === "chunk") {
1831
+ const chunk = stringField(envelope.data, "text");
1832
+ if (chunk !== null) {
1833
+ text += chunk;
1834
+ options.onChunk?.(text);
1835
+ }
1836
+ continue;
1837
+ }
1838
+ if (envelope.event === "error" && failure === null) {
1839
+ const payload = isRecord3(envelope.data) ? envelope.data : null;
1840
+ failure = new MatrxRunError({
1841
+ message: streamErrorText(payload) ?? "The agent run failed",
1842
+ errorPayload: payload,
1843
+ partialText: text
1844
+ });
1845
+ continue;
1846
+ }
1847
+ if (envelope.event !== "completion" || !isRecord3(envelope.data)) continue;
1848
+ if (envelope.data.operation !== "user_request") continue;
1849
+ completion = envelope.data;
1850
+ const status = envelope.data.status;
1851
+ if ((status === "failed" || status === "cancelled") && failure === null) {
1852
+ const result = isRecord3(envelope.data.result) ? envelope.data.result : null;
1853
+ failure = new MatrxRunError({
1854
+ message: stringField(result, "error") ?? stringField(result, "user_message") ?? `The agent run ${status}`,
1855
+ completionStatus: status,
1856
+ partialText: text
1857
+ });
1858
+ }
1859
+ }
1860
+ if (failure) throw failure;
1861
+ if (!text && completion) {
1862
+ const result = completion.result;
1863
+ const output = stringField(result, "output");
1864
+ if (output !== null) text = output;
1865
+ }
1866
+ return {
1867
+ text,
1868
+ requestId: handle.requestId,
1869
+ conversationId: handle.conversationId,
1870
+ completion
1871
+ };
1872
+ }
1873
+
1874
+ // src/core/tools.ts
1875
+ function submitAgentToolResults(transport, conversationId, results, options = {}) {
1876
+ return requestJson(
1877
+ transport,
1878
+ `/ai/conversations/${encodePathSegment(conversationId)}/tool_results`,
1879
+ {
1880
+ method: "POST",
1881
+ body: {
1882
+ results,
1883
+ ...options.instanceId !== void 0 ? { instance_id: options.instanceId } : {}
1884
+ },
1885
+ ...options.signal ? { signal: options.signal } : {}
1886
+ }
1887
+ );
1888
+ }
1889
+ function listConversationPendingToolCalls(transport, conversationId, options = {}) {
1890
+ return requestJson(
1891
+ transport,
1892
+ `/ai/conversations/${encodePathSegment(conversationId)}/pending_calls`,
1893
+ {
1894
+ method: "GET",
1895
+ ...options.signal ? { signal: options.signal } : {}
1896
+ }
1897
+ );
1898
+ }
1899
+ function listUserPendingToolCalls(transport, options = {}) {
1900
+ const query = buildQuery(
1901
+ options.instanceId !== void 0 ? { instance_id: options.instanceId } : {}
1902
+ );
1903
+ return requestJson(
1904
+ transport,
1905
+ `/ai/user/pending_calls${query}`,
1906
+ {
1907
+ method: "GET",
1908
+ ...options.signal ? { signal: options.signal } : {}
1909
+ }
1910
+ );
1911
+ }
1912
+
1913
+ // src/core/endpoints.ts
1914
+ var ENDPOINTS = {
1915
+ /** AI endpoints — chat, agents, conversations */
1916
+ ai: {
1917
+ /**
1918
+ * POST — Manual-mode execution (Builder + ephemeral conversations).
1919
+ * POST /ai/manual
1920
+ *
1921
+ * Accepts full message history in `messages` on every call. Used by:
1922
+ * • Builder — reads the LIVE agent definition (incl. unsaved edits) and
1923
+ * sends it as the system instruction + priming messages.
1924
+ * • Ephemeral conversations (turn 2+) — no DB row exists, so the client
1925
+ * is the source of truth for history; sends it with each turn.
1926
+ *
1927
+ * `conversation_id` is optional in the body (for labeling/storage only);
1928
+ * pair with `is_new:false, store:false` for fully stateless runs.
1929
+ *
1930
+ * NOTE: this replaces the legacy `/ai/chat` endpoint. The canonical
1931
+ * client-side vocabulary is `manual` (see ConversationInvocation.routing
1932
+ * .apiEndpointMode). The legacy `chat` alias below stays for one
1933
+ * migration cycle.
1934
+ */
1935
+ manual: "/ai/manual",
1936
+ /** @deprecated Use `ENDPOINTS.ai.manual`. Kept for one migration cycle. */
1937
+ chat: "/ai/manual",
1938
+ /**
1939
+ * POST — Start a new agent conversation (Guest OK)
1940
+ * POST /ai/agents/{agentId}
1941
+ * Never send conversation_id — the server generates it and returns it in the stream.
1942
+ */
1943
+ agentStart: (agentId) => `/ai/agents/${agentId}`,
1944
+ /**
1945
+ * POST — THE MANDATE DOOR. Start a new conversation by MANDATE KEY, not by
1946
+ * agent id (Guest OK).
1947
+ * POST /ai/mandates/{mandateKey}
1948
+ *
1949
+ * Body is the SAME `AgentStartRequest` as `agentStart`. The server resolves
1950
+ * the principal (bearer/fingerprint) → system default → org binding → user
1951
+ * binding, applies the binding's `config_overrides`, provision consumption
1952
+ * and variable mapping, and then runs the IDENTICAL downstream pipeline
1953
+ * (`_run_mandated_agent` → `_run_agent`). A rebind therefore changes which
1954
+ * agent answers with NO client deploy — which is the entire point.
1955
+ *
1956
+ * Never send mandate-derived `config_overrides` on this path: the server
1957
+ * treats request config as the EXPLICIT layer that WINS over the binding,
1958
+ * so echoing a client-resolved binding back would re-fork resolution.
1959
+ *
1960
+ * 404 `{code: "mandate_unfulfilled"}` when the mandate cannot be resolved —
1961
+ * surfaced verbatim, never swallowed into a client-side re-resolve.
1962
+ */
1963
+ mandateStart: (mandateKey) => `/ai/mandates/${mandateKey}`,
1964
+ /**
1965
+ * POST — Continue any existing conversation (Guest OK)
1966
+ * POST /ai/conversations/{conversationId}
1967
+ * Conversation ID in URL. Just send user_input in the body.
1968
+ */
1969
+ conversationContinue: (conversationId) => `/ai/conversations/${conversationId}`,
1970
+ /**
1971
+ * POST — Pre-warm a conversation's server cache. No body. No auth.
1972
+ * POST /ai/conversations/{conversationId}/warm
1973
+ * Fire when user navigates to a conversation page.
1974
+ */
1975
+ conversationWarm: (conversationId) => `/ai/conversations/${conversationId}/warm`,
1976
+ /**
1977
+ * POST — Pre-warm an agent's server cache. No auth. (public endpoint)
1978
+ * POST /ai/agents/{agentId}/warm
1979
+ * Optional body: `{ source: "prompt" | "builtin" | "prompt_version" | "builtin_version" }`
1980
+ */
1981
+ agentWarm: (agentId) => `/ai/agents/${agentId}/warm`,
1982
+ /**
1983
+ * POST — Start a new prompt conversation (Guest OK)
1984
+ * POST /ai/prompts/{promptId}
1985
+ * Body: PromptStartRequest — user_input, variables, stream, debug, client_tools, etc.
1986
+ * Never send conversation_id — the server generates it and returns it in the stream.
1987
+ */
1988
+ promptStart: (promptId) => `/ai/prompts/${promptId}`,
1989
+ /**
1990
+ * POST — Pre-warm a prompt's server cache. No auth. (public endpoint)
1991
+ * POST /ai/prompts/{promptId}/warm
1992
+ * Optional body: `{ source: string | null }`
1993
+ */
1994
+ promptWarm: (promptId) => `/ai/prompts/${promptId}/warm`,
1995
+ /**
1996
+ * POST — Start a new block-streaming agent session (Guest OK)
1997
+ * POST /ai/agents-blocks/{agentId}
1998
+ * Same as agentStart but emits 'content_block' NDJSON events instead of raw 'chunk' events.
1999
+ */
2000
+ agentBlocksStart: (agentId) => `/ai/agents-blocks/${agentId}`,
2001
+ /**
2002
+ * POST — Pre-warm a block-streaming agent (Public)
2003
+ * POST /ai/agents-blocks/{agentId}/warm
2004
+ * Optional body: `{ source: "prompt" | "builtin" | "prompt_version" | "builtin_version" }`
2005
+ */
2006
+ agentBlocksWarm: (agentId) => `/ai/agents-blocks/${agentId}/warm`,
2007
+ /** POST — Cancel a running request by request_id (Authenticated) */
2008
+ cancel: (requestId) => `/ai/cancel/${requestId}`
2009
+ },
2010
+ /** Block processing test endpoints — Guest OK */
2011
+ blockProcessing: {
2012
+ /** POST — Process raw text/markdown → structured blocks (JSON response) */
2013
+ process: "/utilities/block-processing/process",
2014
+ /** POST — Process raw text/markdown → block events (NDJSON stream, simulates live agent) */
2015
+ processStream: "/utilities/block-processing/process/stream"
2016
+ },
2017
+ /** CX-data endpoints — conversation/message data (Authenticated) */
2018
+ cx: {
2019
+ /**
2020
+ * GET — Snapshot of "what the model is currently seeing" for a conversation.
2021
+ * GET /cx/conversations/{conversationId}/context-state
2022
+ * Initial hydration for the Model Context tab; live updates come via
2023
+ * CONTEXT_STATE / CONTEXT_TRIMMED stream events after each turn.
2024
+ */
2025
+ contextState: (conversationId) => `/cx/conversations/${conversationId}/context-state`
2026
+ },
2027
+ /** CMS server work — authenticated. CMS row CRUD stays direct-to-Supabase. */
2028
+ cms: {
2029
+ /** POST — Canonical matrx-content-guard validation before CMS writes. */
2030
+ validate: "/cms/validate",
2031
+ /**
2032
+ * POST — THE decision door for a queued content exception
2033
+ * (`features/approvals/cms-door.ts`). The exception id is the idempotency
2034
+ * key; the server finds its queue row and replays the ordinary human write
2035
+ * path. Nothing else decides these — the CMS's own review route is gone.
2036
+ */
2037
+ approveException: (exceptionId) => `/cms/exceptions/${encodeURIComponent(exceptionId)}/approve`,
2038
+ rejectException: (exceptionId) => `/cms/exceptions/${encodeURIComponent(exceptionId)}/reject`,
2039
+ /**
2040
+ * POST `{page_id}` — the publish writing check for a page's FINAL text (the
2041
+ * same gate the server publish seam runs). `allowed=false` carries the
2042
+ * must-fix list and the three settings that lift the block.
2043
+ */
2044
+ publishCheck: "/cms/publish-check"
2045
+ },
2046
+ /** Tool testing endpoints — Authenticated */
2047
+ tools: {
2048
+ /** GET — List available tools (?category=) */
2049
+ testList: "/tools/test/list",
2050
+ /** GET — Get tool details by name */
2051
+ testDetail: (toolName) => `/tools/test/${toolName}`,
2052
+ /** POST — Create/reuse test session */
2053
+ testSession: "/tools/test/session",
2054
+ /** POST — Execute tool test with streaming */
2055
+ testExecute: "/tools/test/execute",
2056
+ /**
2057
+ * POST `{tool_name, arguments, spend_approval_id?}` — a SCREEN runs one
2058
+ * screen-callable tool as the signed-in person (no agent, no conversation).
2059
+ * `status`: `ok` (the tool's own envelope in `output`), `needs_approval`
2060
+ * (`approval` carries the approve_spend ask and its form render; call again
2061
+ * with `spend_approval_id`), or `error`. 403 for a tool not declared
2062
+ * `screen_callable`.
2063
+ */
2064
+ screenRun: "/tools/screen-run"
2065
+ },
2066
+ /** Scraper endpoints — Authenticated */
2067
+ scraper: {
2068
+ /** POST — Quick scrape URLs */
2069
+ quickScrape: "/scraper/quick-scrape",
2070
+ /** POST — Search keywords */
2071
+ search: "/scraper/search",
2072
+ /** POST — Search and scrape combined */
2073
+ searchAndScrape: "/scraper/search-and-scrape",
2074
+ /** POST — Search and scrape with limits */
2075
+ searchAndScrapeLimited: "/scraper/search-and-scrape-limited"
2076
+ },
2077
+ /** Utility endpoints — Guest OK */
2078
+ utilities: {
2079
+ /** @deprecated Use ENDPOINTS.pdf.extractText instead */
2080
+ pdfExtractText: "/utilities/pdf/extract-text"
2081
+ },
2082
+ /**
2083
+ * PDF extraction, manipulation, and document management — Authenticated.
2084
+ * Most JSON endpoints accept a unified source via `MediaRef` (preferred for
2085
+ * cloud files via `cld_id`), `file`, `url`, or `local_path`. See
2086
+ * `features/pdf-extractor/types.ts` for the full type re-exports.
2087
+ *
2088
+ * NOTE: list/detail endpoints below are kept for backwards compatibility
2089
+ * but the workspace now reads `processed_documents` directly from Supabase
2090
+ * for the sidebar list and the on-click detail (the old `extracted_documents`
2091
+ * facade view was retired 2026-06-11). Loading hundreds of full `content`
2092
+ * rows from Python was making the window take 2+ minutes to open.
2093
+ */
2094
+ pdf: {
2095
+ // ── Lifecycle ─────────────────────────────────────────────────────────
2096
+ /**
2097
+ * POST — Compress PDF (multipart file upload). Query params:
2098
+ * - `level` (1..5): minimum quality tier. 1=lossless, 5=max compression.
2099
+ * - `max_size_mb` (optional float): absolute upper bound on output size;
2100
+ * when set, the server escalates `level` one tier at a time until the
2101
+ * output fits (or tier 5 is reached). Omit for "honour level exactly."
2102
+ * Response headers include `X-Compression-Level-Used` and
2103
+ * `X-Compression-Cap-Satisfied` so the caller can see what actually ran.
2104
+ */
2105
+ compress: "/utilities/pdf/compress",
2106
+ /** POST — Single-file text extraction (stateless multipart, NDJSON streaming).
2107
+ * Emits `pdf_extract_started` / `pdf_page_extracted` / `pdf_extract_complete`
2108
+ * data events; the complete event carries the old `{ filename, text_content }`
2109
+ * body. Consume via `streamPdfExtractText` (features/pdf-extractor/service/streamPdf.ts). */
2110
+ extractText: "/utilities/pdf/extract-text",
2111
+ /** POST — Batch extraction with NDJSON streaming (saves to DB + storage). */
2112
+ batchExtract: "/utilities/pdf/batch-extract",
2113
+ /**
2114
+ * POST — Phone-scanner assembly (NDJSON streaming): ordered photos
2115
+ * (optional quad + rotation) + PDFs → ONE user-visible PDF, extracted
2116
+ * + handed to the content pipeline. Terminal `data` event carries
2117
+ * `{ file_id, doc_id, page_count }`.
2118
+ */
2119
+ fromImages: "/utilities/pdf/from-images",
2120
+ // ── New `MediaRef`-based JSON endpoints (matrx-utils) ─────────────────
2121
+ /** POST — Text extraction from a remote source (MediaRef / url; NDJSON streaming,
2122
+ * same events as `extractText`). Consume via `streamPdfExtractTextRemote`. */
2123
+ extractTextRemote: "/utilities/pdf/extract-text-remote",
2124
+ /** POST — Table extraction. Returns `PdfResult`. */
2125
+ extractTables: "/utilities/pdf/extract-tables",
2126
+ /** POST — Extract pages into a new PDF. Returns PDF blob. */
2127
+ extractPages: "/utilities/pdf/extract-pages",
2128
+ /** POST — Crop pages (with `crop_box`). Returns PDF blob. */
2129
+ cropPages: "/utilities/pdf/crop-pages",
2130
+ /** POST — Rotate pages. Returns PDF blob. */
2131
+ rotatePages: "/utilities/pdf/rotate-pages",
2132
+ /** POST — Delete pages. Returns PDF blob. */
2133
+ deletePages: "/utilities/pdf/delete-pages",
2134
+ /** POST — Merge multiple PDFs. Returns PDF blob. */
2135
+ merge: "/utilities/pdf/merge",
2136
+ /** POST — Split PDF into parts (`parts` or `max_pages_per_part`). Returns ZIP blob. */
2137
+ split: "/utilities/pdf/split",
2138
+ // ── AI pipelines (streaming JSONL) ────────────────────────────────────
2139
+ /** POST — Process a PDF with AI agents (single-pass / chunk / reassembly). Streams JSONL. */
2140
+ processWithAi: "/utilities/pdf/process-with-ai",
2141
+ /** POST — Full pipeline: extract → chunk → AI → reassembly. Streams JSONL with `PdfPipelineOptions`. */
2142
+ fullPipeline: "/utilities/pdf/full-pipeline",
2143
+ /** POST — AI content cleaning on an already-extracted document (NDJSON streaming). */
2144
+ cleanContent: (docId) => `/utilities/pdf/clean-content/${docId}`,
2145
+ // ── Document management (server-side; prefer direct Supabase reads) ──
2146
+ /** @deprecated — Read `processed_documents` directly from Supabase with metadata-only projection. */
2147
+ documents: "/utilities/pdf/documents",
2148
+ /** @deprecated — Read `processed_documents` directly from Supabase. */
2149
+ document: (docId) => `/utilities/pdf/documents/${docId}`,
2150
+ // ── Phase 2 — render & advanced page ops ──────────────────────────────
2151
+ /** POST — Render one page to an image blob (PNG/JPEG/WebP/TIFF). */
2152
+ renderPage: "/utilities/pdf/render-page",
2153
+ /** POST — Render every page; returns a ZIP of per-page images. */
2154
+ renderAll: "/utilities/pdf/render-all",
2155
+ /** POST — Cover thumbnail at `max_side` px. */
2156
+ renderThumbnail: "/utilities/pdf/render-thumbnail",
2157
+ /** POST — Reorder pages by `new_order`. Returns PDF blob. */
2158
+ reorderPages: "/utilities/pdf/reorder-pages",
2159
+ /** POST — Insert pages from `source_*` into target. Returns PDF blob. */
2160
+ insertPages: "/utilities/pdf/insert-pages",
2161
+ /** POST — Duplicate pages inline (`count` copies). Returns PDF blob. */
2162
+ duplicatePages: "/utilities/pdf/duplicate-pages",
2163
+ /** GET — Studio preset catalog. Returns `PdfStudioCatalog`. */
2164
+ studioPresets: "/utilities/pdf/studio/presets",
2165
+ /** POST — Studio dispatcher; image blob or ZIP depending on preset. */
2166
+ studioRender: "/utilities/pdf/studio/render",
2167
+ // ── Phase 3 — layout analysis ─────────────────────────────────────────
2168
+ /** POST — Detect headers / footers / watermarks / recurring side notes. Returns `RepeatedRegionsReport`. */
2169
+ detectRepeatedRegions: "/utilities/pdf/detect-repeated-regions",
2170
+ /** POST — Detect + strip repeated regions from per-page text. Returns `StripRepeatedRegionsResultSchema`. */
2171
+ stripRepeatedRegions: "/utilities/pdf/strip-repeated-regions",
2172
+ /** POST — Classify every page (cover / TOC / body / exhibit / signature / billing / ...). Returns `LayoutClassificationReport`. */
2173
+ classifyPages: "/utilities/pdf/classify-pages",
2174
+ /** POST — Multi-column → linear reading order. Returns `ReadingOrderReport`. */
2175
+ extractReadingOrder: "/utilities/pdf/extract-reading-order",
2176
+ // ── Phase 4 — redaction & privacy ─────────────────────────────────────
2177
+ /** GET — Builtin redaction pattern catalog (SSN / email / phone / MRN / ...). */
2178
+ redactPatterns: "/utilities/pdf/redact/patterns",
2179
+ /** POST — Redact one or more page-anchored rectangles. PDF blob or persisted JSON. */
2180
+ redactRegions: "/utilities/pdf/redact-regions",
2181
+ /** POST — Redact every regex match (builtin id or raw pattern). PDF blob or persisted JSON. */
2182
+ redactPattern: "/utilities/pdf/redact-pattern",
2183
+ /** POST — Detect repeated regions then redact selected/all. PDF blob or persisted JSON. */
2184
+ redactRepeatedRegions: "/utilities/pdf/redact-repeated-regions",
2185
+ /** POST — Wipe /Info + XMP metadata + thumbnails. */
2186
+ stripMetadata: "/utilities/pdf/strip-metadata",
2187
+ /** POST — Granular composite scrub (metadata / attachments / JS / flatten). */
2188
+ scrub: "/utilities/pdf/scrub",
2189
+ /** POST — Bake annotations + widgets into page content. */
2190
+ flattenAnnotations: "/utilities/pdf/flatten-annotations"
2191
+ },
2192
+ /**
2193
+ * Per-page AI extraction — fan out an agent across pages of a document and
2194
+ * persist structured results anchored to source page numbers. See
2195
+ * `features/page-extraction/FEATURE.md` for the data model.
2196
+ */
2197
+ pageExtraction: {
2198
+ /** POST — Run extraction across pages (NDJSON streaming, per-page events). */
2199
+ runStream: "/page-extraction/runs/stream",
2200
+ /** POST — Retry one failed page-run (replaces its results). */
2201
+ retryPageRun: (pageRunId) => `/page-extraction/page-runs/${pageRunId}/retry`,
2202
+ /** POST — Cancel an in-flight run. */
2203
+ cancelRun: (runId) => `/page-extraction/runs/${runId}/cancel`
2204
+ },
2205
+ /** Test/admin endpoints — Admin only */
2206
+ tests: {
2207
+ /** GET/POST — Example endpoints */
2208
+ examples: "/tests/examples",
2209
+ /** GET — Stream text test */
2210
+ streamText: "/tests/stream/text"
2211
+ },
2212
+ /** Media processing endpoints — Authenticated */
2213
+ media: {
2214
+ /**
2215
+ * POST — Upload podcast video → extract cover frame, render podcast
2216
+ * variants, returns URLs + Asset envelope. Image-only uploads now go
2217
+ * through {@link ENDPOINTS.assets.upload} with `preset="podcast"`.
2218
+ */
2219
+ uploadPodcastVideo: "/media/podcast/upload-video",
2220
+ /**
2221
+ * POST — stream the spoken transcript of a captioned YouTube video as
2222
+ * text. Body: `{ youtube_url }`. Reuses the "YouTube Video Transcription
2223
+ * Analysis" agent server-side (quiet run, no chat clutter). Streams NDJSON:
2224
+ * the transcript arrives as chunk text (`accumulatedText`); a captionless
2225
+ * video yields a non-fatal warning + empty text so callers stay honest.
2226
+ */
2227
+ youtubeTranscript: "/media/youtube/transcript"
2228
+ },
2229
+ /**
2230
+ * Content-processing orchestrator — the interactive counterpart to the
2231
+ * automatic post-upload hook. Triggers extract→clean→chunk→embed→NER for an
2232
+ * already-uploaded `cld_files` row and streams typed progress (NDJSON). The
2233
+ * terminal `data` event carries a `ContentProcessingResult`
2234
+ * (`signature: "ContentProcessingResult"`) with `status` + `processed_document_id`.
2235
+ * Today's content types: `"pdf"` (default) and `"office"` (docx/pptx/xlsx —
2236
+ * pure-python extraction, no LibreOffice/OCR; already-clean markdown so the
2237
+ * LLM clean stage is skipped). The extracted text itself is NOT in the
2238
+ * stream — read `docproc.processed_documents.content` directly via
2239
+ * `docprocDb(supabase)` (canonical direct-Supabase read) once the run
2240
+ * completes.
2241
+ */
2242
+ contentProcessing: {
2243
+ process: (cldFileId) => `/content-processing/${cldFileId}`
2244
+ },
2245
+ /**
2246
+ * Unified asset (image / media) upload + render-variants pipeline.
2247
+ *
2248
+ * One endpoint family handles every media upload in the platform. The
2249
+ * server renders preset variants (cover, OG, thumbnail, avatar sizes,
2250
+ * favicons, etc.) and returns the canonical {@link Asset} envelope —
2251
+ * see `features/files/types.ts` for the wire shape.
2252
+ *
2253
+ * Preset → variant key map (high level):
2254
+ * - raw → only `original`
2255
+ * - podcast → cover_url (3000²), cover_sd_url (1400²) + social baseline
2256
+ * - social → og_url, square_url, portrait_url, story_url, yt_thumbnail_url + baseline
2257
+ * - web → hero_url, og_url, card_url, touch_icon_url, pwa_icon_url, thumbnail_url + baseline
2258
+ * - email → header_url, square_url (no baseline)
2259
+ * - logo → logo_lg_url, logo_md_url, logo_sm_url + baseline
2260
+ * - avatar → avatar_xl/lg/md/sm/xs_url (no baseline)
2261
+ * - favicon → favicon_android/apple_touch/32/16_url (no baseline)
2262
+ *
2263
+ * Authenticated. See `features/files/api/assets.ts` for the typed
2264
+ * client wrapper.
2265
+ */
2266
+ assets: {
2267
+ /** POST — multipart upload + render preset variants. */
2268
+ upload: "/assets",
2269
+ /** GET — read the canonical Asset envelope for an upload's master file. */
2270
+ detail: (fileId) => `/assets/${fileId}`,
2271
+ /** PATCH — change sharing / metadata. */
2272
+ patch: (fileId) => `/assets/${fileId}`,
2273
+ /** POST — render more variants (idempotent). */
2274
+ addVariants: (fileId) => `/assets/${fileId}/variants`,
2275
+ /** GET — list every server-known preset. */
2276
+ presets: "/assets/presets",
2277
+ /**
2278
+ * GET — convert any cld_files row to an Asset envelope. The
2279
+ * click-to-render primitive: hand any file_id, get back URLs +
2280
+ * variants the FE can render directly.
2281
+ */
2282
+ forFile: (fileId) => `/files/${fileId}/asset`,
2283
+ /**
2284
+ * POST — no-persist preview rendering (E.16, matrx-utils v1.1.0).
2285
+ * Accepts a `MediaRef` source + variants[]. Returns either base64
2286
+ * `data_url` (≤256 KB) or a 5-min `ephemeral_url`. Replaces the
2287
+ * deleted Next.js Sharp route at app/api/images/studio/process.
2288
+ */
2289
+ preview: "/assets/preview",
2290
+ /**
2291
+ * POST — multipart variant of {@link preview}. Render directly without
2292
+ * a prior `cld_files` row. Useful for Image Studio drag-and-drop
2293
+ * preview before commit-to-save.
2294
+ */
2295
+ previewMultipart: "/assets/preview/multipart",
2296
+ /**
2297
+ * POST — no-persist PDF compression (E.17). Accepts a `MediaRef` source.
2298
+ * Returns `data_url` (≤256 KB) or a 5-min `ephemeral_url`.
2299
+ * Replaces the deleted Next.js route at app/api/pdf/compress.
2300
+ */
2301
+ pdfCompress: "/assets/pdf-compress",
2302
+ /** POST — multipart variant of {@link pdfCompress}. */
2303
+ pdfCompressMultipart: "/assets/pdf-compress/multipart"
2304
+ },
2305
+ /** Health endpoints — Public (aligned with types/python-generated OpenAPI) */
2306
+ health: {
2307
+ /** GET — Basic health check */
2308
+ check: "/health",
2309
+ /** GET — Detailed health with component status */
2310
+ detailed: "/health/detailed",
2311
+ /** GET — Liveness (process up; no I/O) */
2312
+ live: "/health/live",
2313
+ /** GET — Readiness (deps initialized; use for deploy probes) */
2314
+ ready: "/health/ready"
2315
+ },
2316
+ /** Research endpoints — Authenticated */
2317
+ research: {
2318
+ /** POST — Initialize research config */
2319
+ init: "/research/init",
2320
+ /** GET — List templates */
2321
+ templatesList: "/research/templates/list",
2322
+ /** POST — Create template */
2323
+ templatesCreate: "/research/templates",
2324
+ /** GET — Template detail */
2325
+ templateDetail: (templateId) => `/research/templates/${templateId}`,
2326
+ /** GET — Extension scrape queue */
2327
+ extensionScrapeQueue: "/research/extension/scrape-queue",
2328
+ /** GET — Research state / PATCH — Update config */
2329
+ state: (projectId) => `/research/${projectId}`,
2330
+ /** POST — Suggest setup */
2331
+ suggest: (projectId) => `/research/${projectId}/suggest`,
2332
+ /** POST — Run full pipeline (streaming) */
2333
+ run: (projectId) => `/research/${projectId}/run`,
2334
+ /** POST — Trigger search (streaming) */
2335
+ search: (projectId) => `/research/${projectId}/search`,
2336
+ /** POST — Trigger scrape (streaming) */
2337
+ scrape: (projectId) => `/research/${projectId}/scrape`,
2338
+ /** POST — Analyze all sources (streaming) */
2339
+ analyzeAll: (projectId) => `/research/${projectId}/analyze-all`,
2340
+ /** POST — Synthesize */
2341
+ synthesize: (projectId) => `/research/${projectId}/synthesize`,
2342
+ /** GET — Keywords */
2343
+ keywords: (projectId) => `/research/${projectId}/keywords`,
2344
+ /** GET — Sources */
2345
+ sources: (projectId) => `/research/${projectId}/sources`,
2346
+ /** GET — Tags */
2347
+ tags: (projectId) => `/research/${projectId}/tags`,
2348
+ /** GET/POST — Document */
2349
+ document: (projectId) => `/research/${projectId}/document`,
2350
+ /** GET — Costs */
2351
+ costs: (projectId) => `/research/${projectId}/costs`
2352
+ },
2353
+ /**
2354
+ * ACTION REQUESTS — `platform.action_request`. An agent asks the person it
2355
+ * works for for ONE thing; they answer on `/q/<token>` and the parked turn
2356
+ * resumes.
2357
+ *
2358
+ * All three sit on aidream's PUBLIC router at the BARE prefix (no `/api`,
2359
+ * no version), because the person tapping them has no account in the general
2360
+ * case. They are POSTs deliberately — the token would otherwise sit in a URL,
2361
+ * which means in the access log and in every proxy between here and it.
2362
+ *
2363
+ * Reached ONLY from `features/action-requests/service.ts` (server lane): the
2364
+ * `Authorization` header is what separates a signed-in completion from a
2365
+ * bearer one, so the decision to send it belongs where the session cookie is.
2366
+ */
2367
+ actionRequests: {
2368
+ /** POST — what the page draws. MUTATES NOTHING. */
2369
+ open: "/action-requests/open",
2370
+ /** POST — the answer. */
2371
+ complete: "/action-requests/complete",
2372
+ /** POST — "text me a new link". Rate-limited in the database. */
2373
+ remint: "/action-requests/remint"
2374
+ }
2375
+ };
2376
+
1744
2377
  Object.defineProperty(exports, "monitorStream", {
1745
2378
  enumerable: true,
1746
2379
  get: function () { return chunkFNIYADWI_cjs.monitorStream; }
@@ -1763,111 +2396,111 @@ Object.defineProperty(exports, "toCredentialsPort", {
1763
2396
  });
1764
2397
  Object.defineProperty(exports, "BackendApiError", {
1765
2398
  enumerable: true,
1766
- get: function () { return chunkUO3H55R3_cjs.BackendApiError; }
2399
+ get: function () { return chunkPMGKZ4FT_cjs.BackendApiError; }
1767
2400
  });
1768
2401
  Object.defineProperty(exports, "CONTRACT_SHA256", {
1769
2402
  enumerable: true,
1770
- get: function () { return chunkUO3H55R3_cjs.CONTRACT_SHA256; }
2403
+ get: function () { return chunkPMGKZ4FT_cjs.CONTRACT_SHA256; }
1771
2404
  });
1772
2405
  Object.defineProperty(exports, "DEPLOYMENTS", {
1773
2406
  enumerable: true,
1774
- get: function () { return chunkUO3H55R3_cjs.DEPLOYMENTS; }
2407
+ get: function () { return chunkPMGKZ4FT_cjs.DEPLOYMENTS; }
1775
2408
  });
1776
2409
  Object.defineProperty(exports, "DOMAINS", {
1777
2410
  enumerable: true,
1778
- get: function () { return chunkUO3H55R3_cjs.DOMAINS; }
2411
+ get: function () { return chunkPMGKZ4FT_cjs.DOMAINS; }
1779
2412
  });
1780
2413
  Object.defineProperty(exports, "MatrxApiError", {
1781
2414
  enumerable: true,
1782
- get: function () { return chunkUO3H55R3_cjs.MatrxApiError; }
2415
+ get: function () { return chunkPMGKZ4FT_cjs.MatrxApiError; }
1783
2416
  });
1784
2417
  Object.defineProperty(exports, "OrganizationContextError", {
1785
2418
  enumerable: true,
1786
- get: function () { return chunkUO3H55R3_cjs.OrganizationContextError; }
2419
+ get: function () { return chunkPMGKZ4FT_cjs.OrganizationContextError; }
1787
2420
  });
1788
2421
  Object.defineProperty(exports, "StreamTransportError", {
1789
2422
  enumerable: true,
1790
- get: function () { return chunkUO3H55R3_cjs.StreamTransportError; }
2423
+ get: function () { return chunkPMGKZ4FT_cjs.StreamTransportError; }
1791
2424
  });
1792
2425
  Object.defineProperty(exports, "applyOrganizationContextHeader", {
1793
2426
  enumerable: true,
1794
- get: function () { return chunkUO3H55R3_cjs.applyOrganizationContextHeader; }
2427
+ get: function () { return chunkPMGKZ4FT_cjs.applyOrganizationContextHeader; }
1795
2428
  });
1796
2429
  Object.defineProperty(exports, "assertOrganizationMatchesOperation", {
1797
2430
  enumerable: true,
1798
- get: function () { return chunkUO3H55R3_cjs.assertOrganizationMatchesOperation; }
2431
+ get: function () { return chunkPMGKZ4FT_cjs.assertOrganizationMatchesOperation; }
1799
2432
  });
1800
2433
  Object.defineProperty(exports, "assertQueryOrganizationMatchesContext", {
1801
2434
  enumerable: true,
1802
- get: function () { return chunkUO3H55R3_cjs.assertQueryOrganizationMatchesContext; }
2435
+ get: function () { return chunkPMGKZ4FT_cjs.assertQueryOrganizationMatchesContext; }
1803
2436
  });
1804
2437
  Object.defineProperty(exports, "createApi", {
1805
2438
  enumerable: true,
1806
- get: function () { return chunkUO3H55R3_cjs.createApi; }
2439
+ get: function () { return chunkPMGKZ4FT_cjs.createApi; }
1807
2440
  });
1808
2441
  Object.defineProperty(exports, "createOrganizationOperation", {
1809
2442
  enumerable: true,
1810
- get: function () { return chunkUO3H55R3_cjs.createOrganizationOperation; }
2443
+ get: function () { return chunkPMGKZ4FT_cjs.createOrganizationOperation; }
1811
2444
  });
1812
2445
  Object.defineProperty(exports, "describeBackendFailure", {
1813
2446
  enumerable: true,
1814
- get: function () { return chunkUO3H55R3_cjs.describeBackendFailure; }
2447
+ get: function () { return chunkPMGKZ4FT_cjs.describeBackendFailure; }
1815
2448
  });
1816
2449
  Object.defineProperty(exports, "extractMatrxErrorCode", {
1817
2450
  enumerable: true,
1818
- get: function () { return chunkUO3H55R3_cjs.extractMatrxErrorCode; }
2451
+ get: function () { return chunkPMGKZ4FT_cjs.extractMatrxErrorCode; }
1819
2452
  });
1820
2453
  Object.defineProperty(exports, "extractMatrxErrorMessage", {
1821
2454
  enumerable: true,
1822
- get: function () { return chunkUO3H55R3_cjs.extractMatrxErrorMessage; }
2455
+ get: function () { return chunkPMGKZ4FT_cjs.extractMatrxErrorMessage; }
1823
2456
  });
1824
2457
  Object.defineProperty(exports, "getUserMessage", {
1825
2458
  enumerable: true,
1826
- get: function () { return chunkUO3H55R3_cjs.getUserMessage; }
2459
+ get: function () { return chunkPMGKZ4FT_cjs.getUserMessage; }
1827
2460
  });
1828
2461
  Object.defineProperty(exports, "isGenericUserMessage", {
1829
2462
  enumerable: true,
1830
- get: function () { return chunkUO3H55R3_cjs.isGenericUserMessage; }
2463
+ get: function () { return chunkPMGKZ4FT_cjs.isGenericUserMessage; }
1831
2464
  });
1832
2465
  Object.defineProperty(exports, "isStreamTransportLost", {
1833
2466
  enumerable: true,
1834
- get: function () { return chunkUO3H55R3_cjs.isStreamTransportLost; }
2467
+ get: function () { return chunkPMGKZ4FT_cjs.isStreamTransportLost; }
1835
2468
  });
1836
2469
  Object.defineProperty(exports, "openJsonOrStream", {
1837
2470
  enumerable: true,
1838
- get: function () { return chunkUO3H55R3_cjs.openJsonOrStream; }
2471
+ get: function () { return chunkPMGKZ4FT_cjs.openJsonOrStream; }
1839
2472
  });
1840
2473
  Object.defineProperty(exports, "openStream", {
1841
2474
  enumerable: true,
1842
- get: function () { return chunkUO3H55R3_cjs.openStream; }
2475
+ get: function () { return chunkPMGKZ4FT_cjs.openStream; }
1843
2476
  });
1844
2477
  Object.defineProperty(exports, "parseCallApiError", {
1845
2478
  enumerable: true,
1846
- get: function () { return chunkUO3H55R3_cjs.parseCallApiError; }
2479
+ get: function () { return chunkPMGKZ4FT_cjs.parseCallApiError; }
1847
2480
  });
1848
2481
  Object.defineProperty(exports, "parseHttpError", {
1849
2482
  enumerable: true,
1850
- get: function () { return chunkUO3H55R3_cjs.parseHttpError; }
2483
+ get: function () { return chunkPMGKZ4FT_cjs.parseHttpError; }
1851
2484
  });
1852
2485
  Object.defineProperty(exports, "parseHttpErrorBody", {
1853
2486
  enumerable: true,
1854
- get: function () { return chunkUO3H55R3_cjs.parseHttpErrorBody; }
2487
+ get: function () { return chunkPMGKZ4FT_cjs.parseHttpErrorBody; }
1855
2488
  });
1856
2489
  Object.defineProperty(exports, "parsePersistedBackendError", {
1857
2490
  enumerable: true,
1858
- get: function () { return chunkUO3H55R3_cjs.parsePersistedBackendError; }
2491
+ get: function () { return chunkPMGKZ4FT_cjs.parsePersistedBackendError; }
1859
2492
  });
1860
2493
  Object.defineProperty(exports, "parseStreamError", {
1861
2494
  enumerable: true,
1862
- get: function () { return chunkUO3H55R3_cjs.parseStreamError; }
2495
+ get: function () { return chunkPMGKZ4FT_cjs.parseStreamError; }
1863
2496
  });
1864
2497
  Object.defineProperty(exports, "requireOrganizationContext", {
1865
2498
  enumerable: true,
1866
- get: function () { return chunkUO3H55R3_cjs.requireOrganizationContext; }
2499
+ get: function () { return chunkPMGKZ4FT_cjs.requireOrganizationContext; }
1867
2500
  });
1868
2501
  Object.defineProperty(exports, "unwrapUpstreamError", {
1869
2502
  enumerable: true,
1870
- get: function () { return chunkUO3H55R3_cjs.unwrapUpstreamError; }
2503
+ get: function () { return chunkPMGKZ4FT_cjs.unwrapUpstreamError; }
1871
2504
  });
1872
2505
  Object.defineProperty(exports, "AbortedError", {
1873
2506
  enumerable: true,
@@ -1925,11 +2558,13 @@ Object.defineProperty(exports, "withRetry", {
1925
2558
  enumerable: true,
1926
2559
  get: function () { return chunk2SXAAKGV_cjs.withRetry; }
1927
2560
  });
2561
+ exports.ENDPOINTS = ENDPOINTS;
1928
2562
  exports.MATRX_AI_API_VERSION_DEFAULT = MATRX_AI_API_VERSION_DEFAULT;
1929
2563
  exports.MATRX_LIVE_STREAM_UNAVAILABLE = MATRX_LIVE_STREAM_UNAVAILABLE;
1930
2564
  exports.MATRX_RESUME_CONFLICT = MATRX_RESUME_CONFLICT;
1931
2565
  exports.MATRX_RUN_IN_PROGRESS = MATRX_RUN_IN_PROGRESS;
1932
2566
  exports.MATRX_UI_ONLY_BODY_FIELDS = MATRX_UI_ONLY_BODY_FIELDS;
2567
+ exports.MatrxRunError = MatrxRunError;
1933
2568
  exports.RUN_OUTPUT_KINDS = RUN_OUTPUT_KINDS;
1934
2569
  exports.RUN_STREAM_LIFETIME_BACKSTOP_MS = RUN_STREAM_LIFETIME_BACKSTOP_MS;
1935
2570
  exports.RUN_WAIT_KNOB_FEATURE = RUN_WAIT_KNOB_FEATURE;
@@ -1944,6 +2579,8 @@ exports.buildMatrxRequestBody = buildMatrxRequestBody;
1944
2579
  exports.buildMatrxRequestUrl = buildMatrxRequestUrl;
1945
2580
  exports.buildQuery = buildQuery;
1946
2581
  exports.buildSafeRequestLog = buildSafeRequestLog;
2582
+ exports.cancelAgentRun = cancelAgentRun;
2583
+ exports.continueAgentConversation = continueAgentConversation;
1947
2584
  exports.continueEphemeralConversationStart = continueEphemeralConversationStart;
1948
2585
  exports.continueStoredConversationStart = continueStoredConversationStart;
1949
2586
  exports.createMatrxTransport = createMatrxTransport;
@@ -1969,7 +2606,9 @@ exports.isLiveStreamUnavailable = isLiveStreamUnavailable;
1969
2606
  exports.isResumeConflict = isResumeConflict;
1970
2607
  exports.isServerJobSettled = isServerJobSettled;
1971
2608
  exports.isV2Path = isV2Path;
2609
+ exports.listConversationPendingToolCalls = listConversationPendingToolCalls;
1972
2610
  exports.listRuntimeOperationEvents = listRuntimeOperationEvents;
2611
+ exports.listUserPendingToolCalls = listUserPendingToolCalls;
1973
2612
  exports.logApiTarget = logApiTarget;
1974
2613
  exports.mintMatrxConversationId = mintMatrxConversationId;
1975
2614
  exports.newEphemeralConversationStart = newEphemeralConversationStart;
@@ -1998,7 +2637,9 @@ exports.requestStream = requestStream;
1998
2637
  exports.resetPreconnectedForTests = resetPreconnectedForTests;
1999
2638
  exports.resolveEndpointPath = resolveEndpointPath;
2000
2639
  exports.resolveRunWaitWith = resolveRunWaitWith;
2640
+ exports.resumeAgentConversation = resumeAgentConversation;
2001
2641
  exports.resumeOrRejoin = resumeOrRejoin;
2642
+ exports.runAgentToCompletion = runAgentToCompletion;
2002
2643
  exports.runJobLabel = runJobLabel;
2003
2644
  exports.runOutputKindFromModalities = runOutputKindFromModalities;
2004
2645
  exports.runWaitKnobKey = runWaitKnobKey;
@@ -2008,7 +2649,10 @@ exports.sendMatrxRequest = sendMatrxRequest;
2008
2649
  exports.serverJobRejoinHandle = serverJobRejoinHandle;
2009
2650
  exports.settleRunPickup = settleRunPickup;
2010
2651
  exports.shouldReportMatrxCallError = shouldReportMatrxCallError;
2652
+ exports.startAgentRun = startAgentRun;
2653
+ exports.startMandateRun = startMandateRun;
2011
2654
  exports.streamErrorText = streamErrorText;
2655
+ exports.submitAgentToolResults = submitAgentToolResults;
2012
2656
  exports.toRunHandle = toRunHandle;
2013
2657
  exports.toV1FallbackUrl = toV1FallbackUrl;
2014
2658
  exports.toV2Path = toV2Path;