@ai-matrx/api 0.1.7 → 0.1.8

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 (120) hide show
  1. package/CHANGELOG.md +6 -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-5BBHAAIG.js} +9 -3
  29. package/dist/{chunk-UO3H55R3.cjs → chunk-NMBDYPFZ.cjs} +9 -3
  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-D_ZjxGwP.d.cts} +5 -0
  65. package/dist/{index-Xx6L_pWk.d.ts → index-D_ZjxGwP.d.ts} +5 -0
  66. package/dist/index.cjs +697 -53
  67. package/dist/index.d.cts +783 -3
  68. package/dist/index.d.ts +783 -3
  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/platform.cjs +3 -3
  101. package/dist/platform.d.cts +1 -1
  102. package/dist/platform.d.ts +1 -1
  103. package/dist/platform.js +1 -1
  104. package/dist/publish.cjs +7 -7
  105. package/dist/publish.d.cts +1 -1
  106. package/dist/publish.d.ts +1 -1
  107. package/dist/publish.js +1 -1
  108. package/dist/stream.cjs +10 -10
  109. package/dist/stream.d.cts +1 -1
  110. package/dist/stream.d.ts +1 -1
  111. package/dist/stream.js +1 -1
  112. package/dist/web.cjs +26 -26
  113. package/dist/web.d.cts +1 -1
  114. package/dist/web.d.ts +1 -1
  115. package/dist/web.js +1 -1
  116. package/dist/workflows.cjs +13 -13
  117. package/dist/workflows.d.cts +1 -1
  118. package/dist/workflows.d.ts +1 -1
  119. package/dist/workflows.js +1 -1
  120. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export { monitorStream } from './chunk-YTEOFGFC.js';
2
2
  export { API_KEY_PREFIX, MATRX_HEADERS, credentialToHeaders, toCredentialsPort } from './chunk-7MZPBCFV.js';
3
- import { OrganizationContextError, BackendApiError, parseHttpError, MatrxApiError, applyOrganizationContextHeader, extractMatrxErrorCode, extractMatrxErrorMessage, readMatrxNdjsonStream, readMatrxSseStream, requireOrganizationContext, StreamTransportError } from './chunk-2FJPWNXG.js';
4
- export { BackendApiError, CONTRACT_SHA256, DEPLOYMENTS, DOMAINS, MatrxApiError, OrganizationContextError, StreamTransportError, applyOrganizationContextHeader, assertOrganizationMatchesOperation, assertQueryOrganizationMatchesContext, createApi, createOrganizationOperation, describeBackendFailure, extractMatrxErrorCode, extractMatrxErrorMessage, getUserMessage, isGenericUserMessage, isStreamTransportLost, openJsonOrStream, openStream, parseCallApiError, parseHttpError, parseHttpErrorBody, parsePersistedBackendError, parseStreamError, requireOrganizationContext, unwrapUpstreamError } from './chunk-2FJPWNXG.js';
3
+ import { OrganizationContextError, BackendApiError, parseHttpError, MatrxApiError, applyOrganizationContextHeader, extractMatrxErrorCode, extractMatrxErrorMessage, readMatrxNdjsonStream, readMatrxSseStream, requireOrganizationContext, StreamTransportError } from './chunk-5BBHAAIG.js';
4
+ export { BackendApiError, CONTRACT_SHA256, DEPLOYMENTS, DOMAINS, MatrxApiError, OrganizationContextError, StreamTransportError, applyOrganizationContextHeader, assertOrganizationMatchesOperation, assertQueryOrganizationMatchesContext, createApi, createOrganizationOperation, describeBackendFailure, extractMatrxErrorCode, extractMatrxErrorMessage, getUserMessage, isGenericUserMessage, isStreamTransportLost, openJsonOrStream, openStream, parseCallApiError, parseHttpError, parseHttpErrorBody, parsePersistedBackendError, parseStreamError, requireOrganizationContext, unwrapUpstreamError } from './chunk-5BBHAAIG.js';
5
5
  import { resilientFetch, isNetError, extractErrorMessage } from './chunk-KIEAFMKB.js';
6
6
  export { AbortedError, ConnectTimeoutError, HeartbeatTimeoutError, HttpError, NetError, NetworkError, OfflineError, TotalTimeoutError, extractErrorMessage, isNetError, isTransportFailure, resilientFetch, toNetError, withRetry } from './chunk-KIEAFMKB.js';
7
7
  import { credentialToHeaders } from '@ai-matrx/auth/credentials';
@@ -1741,4 +1741,637 @@ function createProviderUsageReporter(options) {
1741
1741
  };
1742
1742
  }
1743
1743
 
1744
- export { MATRX_AI_API_VERSION_DEFAULT, MATRX_LIVE_STREAM_UNAVAILABLE, MATRX_RESUME_CONFLICT, MATRX_RUN_IN_PROGRESS, MATRX_UI_ONLY_BODY_FIELDS, RUN_OUTPUT_KINDS, RUN_STREAM_LIFETIME_BACKSTOP_MS, RUN_WAIT_KNOB_FEATURE, TERMINAL_MATRX_RUNTIME_STATUSES, V2_COVERED_AI_PATH_TEMPLATES, WARM_PATH, aiVersionPathOverrides, applyAiApiVersion, applyDesktopTargetToRequestBody, bareStatusSentence, buildMatrxRequestBody, buildMatrxRequestUrl, buildQuery, buildSafeRequestLog, continueEphemeralConversationStart, continueStoredConversationStart, createMatrxTransport, createProviderUsageReporter, createStreamReplayCursor, createWarmup, encodePathSegment, executeMatrxCall, fetchWithMatrxProtocolFallback, followRuntimeOperationEvents, followRuntimeOperationToEnd, followServerJob, followUnavailableRejoin, followWorkflowRunEvents, getRuntimeOperationStatus, getRuntimeOperationsByLink, honestTransportMessage, isBareTransportCode, isCoveredAiPath, isEmptyProviderUsage, isJobOutputKind, isLiveStreamUnavailable, isResumeConflict, isServerJobSettled, isV2Path, listRuntimeOperationEvents, logApiTarget, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, normalizeMatrxError, openMatrxStream, parseMatrxNdjsonResponse, pickServerJobOperation, preconnectServer, providerSessionFailureBody, providerSessionUsageBody, readConversationOrganizationId, readLiveRunRejoin, readLiveRunRequestId, readLiveStreamUnavailable, readMatrxErrorCode, readMatrxErrorCodeFromMessage, readMatrxJsonResponse, readStreamCursor, redactUrlForRequestLog, rejoinRuntimeOperation, reportProviderSessionFailure, reportProviderSessionUsage, requestJson, requestStream, resetPreconnectedForTests, resolveEndpointPath, resolveRunWaitWith, resumeOrRejoin, runJobLabel, runOutputKindFromModalities, runWaitKnobKey, runWaitTimeoutMessage, runtimeOperationRejoinPath, sendMatrxRequest, serverJobRejoinHandle, settleRunPickup, shouldReportMatrxCallError, streamErrorText, toRunHandle, toV1FallbackUrl, toV2Path, withRunOrganization };
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
+
2377
+ export { ENDPOINTS, MATRX_AI_API_VERSION_DEFAULT, MATRX_LIVE_STREAM_UNAVAILABLE, MATRX_RESUME_CONFLICT, MATRX_RUN_IN_PROGRESS, MATRX_UI_ONLY_BODY_FIELDS, MatrxRunError, RUN_OUTPUT_KINDS, RUN_STREAM_LIFETIME_BACKSTOP_MS, RUN_WAIT_KNOB_FEATURE, TERMINAL_MATRX_RUNTIME_STATUSES, V2_COVERED_AI_PATH_TEMPLATES, WARM_PATH, aiVersionPathOverrides, applyAiApiVersion, applyDesktopTargetToRequestBody, bareStatusSentence, buildMatrxRequestBody, buildMatrxRequestUrl, buildQuery, buildSafeRequestLog, cancelAgentRun, continueAgentConversation, continueEphemeralConversationStart, continueStoredConversationStart, createMatrxTransport, createProviderUsageReporter, createStreamReplayCursor, createWarmup, encodePathSegment, executeMatrxCall, fetchWithMatrxProtocolFallback, followRuntimeOperationEvents, followRuntimeOperationToEnd, followServerJob, followUnavailableRejoin, followWorkflowRunEvents, getRuntimeOperationStatus, getRuntimeOperationsByLink, honestTransportMessage, isBareTransportCode, isCoveredAiPath, isEmptyProviderUsage, isJobOutputKind, isLiveStreamUnavailable, isResumeConflict, isServerJobSettled, isV2Path, listConversationPendingToolCalls, listRuntimeOperationEvents, listUserPendingToolCalls, logApiTarget, mintMatrxConversationId, newEphemeralConversationStart, newStoredConversationStart, normalizeMatrxError, openMatrxStream, parseMatrxNdjsonResponse, pickServerJobOperation, preconnectServer, providerSessionFailureBody, providerSessionUsageBody, readConversationOrganizationId, readLiveRunRejoin, readLiveRunRequestId, readLiveStreamUnavailable, readMatrxErrorCode, readMatrxErrorCodeFromMessage, readMatrxJsonResponse, readStreamCursor, redactUrlForRequestLog, rejoinRuntimeOperation, reportProviderSessionFailure, reportProviderSessionUsage, requestJson, requestStream, resetPreconnectedForTests, resolveEndpointPath, resolveRunWaitWith, resumeAgentConversation, resumeOrRejoin, runAgentToCompletion, runJobLabel, runOutputKindFromModalities, runWaitKnobKey, runWaitTimeoutMessage, runtimeOperationRejoinPath, sendMatrxRequest, serverJobRejoinHandle, settleRunPickup, shouldReportMatrxCallError, startAgentRun, startMandateRun, streamErrorText, submitAgentToolResults, toRunHandle, toV1FallbackUrl, toV2Path, withRunOrganization };