@ai-matrx/api 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/LICENSE +21 -0
- package/README.md +22 -2
- package/dist/account.cjs +670 -0
- package/dist/account.d.cts +3246 -0
- package/dist/account.d.ts +3246 -0
- package/dist/account.js +558 -0
- package/dist/agents.cjs +598 -0
- package/dist/agents.d.cts +3417 -0
- package/dist/agents.d.ts +3417 -0
- package/dist/agents.js +497 -0
- package/dist/ai.cjs +109 -0
- package/dist/ai.d.cts +493 -0
- package/dist/ai.d.ts +493 -0
- package/dist/ai.js +91 -0
- package/dist/apps.cjs +394 -0
- package/dist/apps.d.cts +1094 -0
- package/dist/apps.d.ts +1094 -0
- package/dist/apps.js +328 -0
- package/dist/architecture.cjs +1223 -0
- package/dist/architecture.d.cts +4701 -0
- package/dist/architecture.d.ts +4701 -0
- package/dist/architecture.js +1016 -0
- package/dist/audio.cjs +226 -0
- package/dist/audio.d.cts +723 -0
- package/dist/audio.d.ts +723 -0
- package/dist/audio.js +188 -0
- package/dist/chat.cjs +538 -0
- package/dist/chat.d.cts +2251 -0
- package/dist/chat.d.ts +2251 -0
- package/dist/chat.js +447 -0
- package/dist/chunk-2SXAAKGV.cjs +279 -0
- package/dist/chunk-5WJLKYH6.cjs +48 -0
- package/dist/chunk-FNIYADWI.cjs +59 -0
- package/dist/chunk-HER22VVH.cjs +1047 -0
- package/dist/chunk-KIEAFMKB.js +264 -0
- package/dist/chunk-TSHL7Z53.js +1012 -0
- package/dist/chunk-VTZKJMSY.js +43 -0
- package/dist/chunk-YTEOFGFC.js +57 -0
- package/dist/code.cjs +561 -0
- package/dist/code.d.cts +1976 -0
- package/dist/code.d.ts +1976 -0
- package/dist/code.js +467 -0
- package/dist/commerce.cjs +22 -0
- package/dist/commerce.d.cts +45 -0
- package/dist/commerce.d.ts +45 -0
- package/dist/commerce.js +18 -0
- package/dist/communications.cjs +215 -0
- package/dist/communications.d.cts +948 -0
- package/dist/communications.d.ts +948 -0
- package/dist/communications.js +179 -0
- package/dist/computer.cjs +330 -0
- package/dist/computer.d.cts +733 -0
- package/dist/computer.d.ts +733 -0
- package/dist/computer.js +275 -0
- package/dist/content.cjs +425 -0
- package/dist/content.d.cts +1796 -0
- package/dist/content.d.ts +1796 -0
- package/dist/content.js +354 -0
- package/dist/credentials.cjs +22 -0
- package/dist/credentials.d.cts +82 -0
- package/dist/credentials.d.ts +82 -0
- package/dist/credentials.js +1 -0
- package/dist/crm.cjs +271 -0
- package/dist/crm.d.cts +1731 -0
- package/dist/crm.d.ts +1731 -0
- package/dist/crm.js +226 -0
- package/dist/data.cjs +382 -0
- package/dist/data.d.cts +1860 -0
- package/dist/data.d.ts +1860 -0
- package/dist/data.js +318 -0
- package/dist/education.cjs +28 -0
- package/dist/education.d.cts +73 -0
- package/dist/education.d.ts +73 -0
- package/dist/education.js +23 -0
- package/dist/files.cjs +1330 -0
- package/dist/files.d.cts +4956 -0
- package/dist/files.d.ts +4956 -0
- package/dist/files.js +1104 -0
- package/dist/human-resources.cjs +178 -0
- package/dist/human-resources.d.cts +1208 -0
- package/dist/human-resources.d.ts +1208 -0
- package/dist/human-resources.js +148 -0
- package/dist/index-C2E-Cp19.d.ts +385 -0
- package/dist/index-wC2vtb70.d.cts +385 -0
- package/dist/index.cjs +2016 -0
- package/dist/index.d.cts +2069 -0
- package/dist/index.d.ts +2069 -0
- package/dist/index.js +1746 -0
- package/dist/integrations.cjs +5116 -0
- package/dist/integrations.d.cts +19213 -0
- package/dist/integrations.d.ts +19213 -0
- package/dist/integrations.js +4263 -0
- package/dist/intelligence.cjs +1305 -0
- package/dist/intelligence.d.cts +4658 -0
- package/dist/intelligence.d.ts +4658 -0
- package/dist/intelligence.js +1196 -0
- package/dist/knowledge.cjs +1113 -0
- package/dist/knowledge.d.cts +5427 -0
- package/dist/knowledge.d.ts +5427 -0
- package/dist/knowledge.js +921 -0
- package/dist/legal.cjs +225 -0
- package/dist/legal.d.cts +1038 -0
- package/dist/legal.d.ts +1038 -0
- package/dist/legal.js +187 -0
- package/dist/marketing.cjs +1155 -0
- package/dist/marketing.d.cts +7741 -0
- package/dist/marketing.d.ts +7741 -0
- package/dist/marketing.js +951 -0
- package/dist/masterwork.cjs +283 -0
- package/dist/masterwork.d.cts +1938 -0
- package/dist/masterwork.d.ts +1938 -0
- package/dist/masterwork.js +231 -0
- package/dist/media.cjs +610 -0
- package/dist/media.d.cts +2270 -0
- package/dist/media.d.ts +2270 -0
- package/dist/media.js +507 -0
- package/dist/net.cjs +67 -0
- package/dist/net.d.cts +204 -0
- package/dist/net.d.ts +204 -0
- package/dist/net.js +2 -0
- package/dist/platform.cjs +150 -0
- package/dist/platform.d.cts +572 -0
- package/dist/platform.d.ts +572 -0
- package/dist/platform.js +125 -0
- package/dist/publish.cjs +248 -0
- package/dist/publish.d.cts +1431 -0
- package/dist/publish.d.ts +1431 -0
- package/dist/publish.js +206 -0
- package/dist/schemas.cjs +2 -0
- package/dist/schemas.d.cts +1353 -0
- package/dist/schemas.d.ts +1353 -0
- package/dist/schemas.js +1 -0
- package/dist/stream.cjs +44 -0
- package/dist/stream.d.cts +2 -0
- package/dist/stream.d.ts +2 -0
- package/dist/stream.js +3 -0
- package/dist/web.cjs +1045 -0
- package/dist/web.d.cts +4186 -0
- package/dist/web.d.ts +4186 -0
- package/dist/web.js +867 -0
- package/dist/workflows.cjs +825 -0
- package/dist/workflows.d.cts +4699 -0
- package/dist/workflows.d.ts +4699 -0
- package/dist/workflows.js +686 -0
- package/package.json +419 -4
|
@@ -0,0 +1,1047 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunk2SXAAKGV_cjs = require('./chunk-2SXAAKGV.cjs');
|
|
4
|
+
var chunk5WJLKYH6_cjs = require('./chunk-5WJLKYH6.cjs');
|
|
5
|
+
var uuid = require('@ai-matrx/kit/uuid');
|
|
6
|
+
|
|
7
|
+
// src/core/backend-errors.ts
|
|
8
|
+
var BackendApiError = class extends Error {
|
|
9
|
+
/** Machine-readable error code */
|
|
10
|
+
code;
|
|
11
|
+
/** Developer-facing detail */
|
|
12
|
+
detail;
|
|
13
|
+
/** Safe to display directly in the UI */
|
|
14
|
+
userMessage;
|
|
15
|
+
/** Extra info (validation errors, etc.) */
|
|
16
|
+
details;
|
|
17
|
+
/** Unique request ID for support/debugging */
|
|
18
|
+
requestId;
|
|
19
|
+
/** HTTP status code (if from an HTTP response) */
|
|
20
|
+
status;
|
|
21
|
+
constructor(data) {
|
|
22
|
+
super(data.userMessage);
|
|
23
|
+
this.name = "BackendApiError";
|
|
24
|
+
this.code = data.code;
|
|
25
|
+
this.detail = data.detail;
|
|
26
|
+
this.userMessage = data.userMessage;
|
|
27
|
+
this.details = data.details ?? null;
|
|
28
|
+
this.requestId = data.requestId ?? "";
|
|
29
|
+
this.status = data.status ?? null;
|
|
30
|
+
}
|
|
31
|
+
/** Convert to the wire format for logging */
|
|
32
|
+
toJSON() {
|
|
33
|
+
return {
|
|
34
|
+
error: this.code,
|
|
35
|
+
message: this.detail,
|
|
36
|
+
user_message: this.userMessage,
|
|
37
|
+
details: this.details,
|
|
38
|
+
request_id: this.requestId
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
var StreamTransportError = class extends BackendApiError {
|
|
43
|
+
/** Always true — reattach and let the server settle the outcome. */
|
|
44
|
+
resumable = true;
|
|
45
|
+
constructor(data) {
|
|
46
|
+
super({
|
|
47
|
+
code: "stream_transport_lost",
|
|
48
|
+
detail: data.detail,
|
|
49
|
+
userMessage: "The connection dropped. Your run is still going on the server \u2014 reconnecting to it now.",
|
|
50
|
+
details: data.details ?? null,
|
|
51
|
+
...data.requestId !== void 0 ? { requestId: data.requestId } : {}
|
|
52
|
+
});
|
|
53
|
+
this.name = "StreamTransportError";
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
function isStreamTransportLost(error) {
|
|
57
|
+
if (error instanceof StreamTransportError) return true;
|
|
58
|
+
if (error instanceof BackendApiError) {
|
|
59
|
+
return error.code === "stream_transport_lost";
|
|
60
|
+
}
|
|
61
|
+
if (error && typeof error === "object") {
|
|
62
|
+
const code = error.code;
|
|
63
|
+
if (code === "stream_transport_lost") return true;
|
|
64
|
+
const errorType = error.error_type;
|
|
65
|
+
if (errorType === "transport_lost") return true;
|
|
66
|
+
}
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
async function parseHttpError(response) {
|
|
70
|
+
const status = response.status;
|
|
71
|
+
let text;
|
|
72
|
+
try {
|
|
73
|
+
text = await response.text();
|
|
74
|
+
} catch {
|
|
75
|
+
return new BackendApiError({
|
|
76
|
+
code: statusToCode(status),
|
|
77
|
+
detail: `HTTP ${status}`,
|
|
78
|
+
userMessage: `Request failed (${status})`,
|
|
79
|
+
status
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
let body;
|
|
83
|
+
try {
|
|
84
|
+
body = JSON.parse(text);
|
|
85
|
+
} catch {
|
|
86
|
+
return new BackendApiError({
|
|
87
|
+
code: statusToCode(status),
|
|
88
|
+
detail: text || `HTTP ${status}`,
|
|
89
|
+
userMessage: text || `Request failed (${status})`,
|
|
90
|
+
status
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return parseHttpErrorBody(body, status);
|
|
94
|
+
}
|
|
95
|
+
function parseHttpErrorBody(body, status) {
|
|
96
|
+
if (!body) {
|
|
97
|
+
return new BackendApiError({
|
|
98
|
+
code: statusToCode(status),
|
|
99
|
+
detail: `HTTP ${status}`,
|
|
100
|
+
userMessage: `Request failed (${status})`,
|
|
101
|
+
status
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
if (typeof body.error === "string" && typeof body.user_message === "string") {
|
|
105
|
+
return new BackendApiError({
|
|
106
|
+
code: body.error,
|
|
107
|
+
detail: body.message || `HTTP ${status}`,
|
|
108
|
+
userMessage: body.user_message,
|
|
109
|
+
details: body.details ?? null,
|
|
110
|
+
requestId: typeof body.request_id === "string" ? body.request_id : void 0,
|
|
111
|
+
status
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
if (typeof body.error === "object" && body.error !== null) {
|
|
115
|
+
const errorObj = body.error;
|
|
116
|
+
return new BackendApiError({
|
|
117
|
+
code: errorObj.type || errorObj.error || statusToCode(status),
|
|
118
|
+
detail: errorObj.message || `HTTP ${status}`,
|
|
119
|
+
userMessage: errorObj.user_message || errorObj.user_visible_message || errorObj.message || `Request failed (${status})`,
|
|
120
|
+
details: errorObj.details ?? null,
|
|
121
|
+
requestId: typeof errorObj.request_id === "string" ? errorObj.request_id : void 0,
|
|
122
|
+
status
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
if (Array.isArray(body.detail)) {
|
|
126
|
+
const first = body.detail[0];
|
|
127
|
+
const firstMsg = first && typeof first.msg === "string" ? first.msg : null;
|
|
128
|
+
return new BackendApiError({
|
|
129
|
+
code: statusToCode(status),
|
|
130
|
+
detail: firstMsg ? `Validation error: ${firstMsg}` : JSON.stringify(body.detail),
|
|
131
|
+
userMessage: firstMsg || `Request failed (${status})`,
|
|
132
|
+
details: body.detail,
|
|
133
|
+
status
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
if (typeof body.detail === "object" && body.detail !== null && !Array.isArray(body.detail)) {
|
|
137
|
+
const d = body.detail;
|
|
138
|
+
const code = typeof d.code === "string" && d.code || typeof d.error === "string" && d.error || statusToCode(status);
|
|
139
|
+
const message = typeof d.message === "string" && d.message || typeof d.detail === "string" && d.detail || `HTTP ${status}`;
|
|
140
|
+
return new BackendApiError({
|
|
141
|
+
code,
|
|
142
|
+
detail: message,
|
|
143
|
+
userMessage: typeof d.user_message === "string" && d.user_message || typeof d.user_visible_message === "string" && d.user_visible_message || message,
|
|
144
|
+
details: d.details ?? d,
|
|
145
|
+
requestId: typeof d.request_id === "string" ? d.request_id : void 0,
|
|
146
|
+
status
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
return new BackendApiError({
|
|
150
|
+
code: typeof body.error === "string" ? body.error : statusToCode(status),
|
|
151
|
+
detail: body.message || body.detail || body.error || `HTTP ${status}`,
|
|
152
|
+
userMessage: body.user_message || body.user_visible_message || body.message || body.detail || `Request failed (${status})`,
|
|
153
|
+
details: body.details ?? null,
|
|
154
|
+
requestId: typeof body.request_id === "string" ? body.request_id : void 0,
|
|
155
|
+
status
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
function parseCallApiError(error) {
|
|
159
|
+
const status = error.status ?? 500;
|
|
160
|
+
const body = error.serverDetail && typeof error.serverDetail === "object" && !Array.isArray(error.serverDetail) ? error.serverDetail : { message: error.message };
|
|
161
|
+
return parseHttpErrorBody(body, status);
|
|
162
|
+
}
|
|
163
|
+
function parseStreamError(data) {
|
|
164
|
+
if (!data || typeof data !== "object") {
|
|
165
|
+
return new BackendApiError({
|
|
166
|
+
code: "internal_error",
|
|
167
|
+
detail: typeof data === "string" ? data : "Unknown streaming error",
|
|
168
|
+
userMessage: typeof data === "string" ? data : "Something went wrong"
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
const obj = data;
|
|
172
|
+
const details = typeof obj.details === "object" && obj.details !== null ? obj.details : null;
|
|
173
|
+
return new BackendApiError({
|
|
174
|
+
code: obj.code || obj.error_type || obj.error || "internal_error",
|
|
175
|
+
detail: obj.message || "Streaming error",
|
|
176
|
+
userMessage: obj.user_message || obj.message || "Something went wrong",
|
|
177
|
+
details,
|
|
178
|
+
requestId: typeof obj.request_id === "string" ? obj.request_id : typeof details?.request_id === "string" ? details.request_id : void 0
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
function parsePersistedBackendError(data, requestId = "") {
|
|
182
|
+
if (!data || typeof data !== "object") return null;
|
|
183
|
+
const error = data;
|
|
184
|
+
const failures = Array.isArray(error.failures) ? error.failures : [];
|
|
185
|
+
const firstSpecific = failures.find(
|
|
186
|
+
(failure) => typeof failure === "object" && failure !== null && typeof failure.message === "string"
|
|
187
|
+
);
|
|
188
|
+
const summary = typeof error.message === "string" ? error.message : "Backend operation failed";
|
|
189
|
+
const specific = typeof firstSpecific?.message === "string" ? firstSpecific.message : summary;
|
|
190
|
+
const detail = specific === summary ? summary : `${summary}: ${specific}`;
|
|
191
|
+
const code = typeof error.type === "string" ? error.type : "internal_error";
|
|
192
|
+
const userMessage = typeof error.user_message === "string" && error.user_message ? error.user_message : detail;
|
|
193
|
+
return new BackendApiError({
|
|
194
|
+
code,
|
|
195
|
+
detail,
|
|
196
|
+
userMessage,
|
|
197
|
+
details: error,
|
|
198
|
+
requestId
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
var GENERIC_MESSAGE_PATTERNS = [
|
|
202
|
+
/failed unexpectedly/i,
|
|
203
|
+
/^\s*something went wrong/i,
|
|
204
|
+
/please try again(\s+later)?\.?\s*$/i,
|
|
205
|
+
/^\s*request failed\b/i,
|
|
206
|
+
/^\s*unknown (streaming )?error/i,
|
|
207
|
+
/^\s*internal server error\.?\s*$/i
|
|
208
|
+
];
|
|
209
|
+
function isGenericUserMessage(message) {
|
|
210
|
+
const value = (message ?? "").trim();
|
|
211
|
+
if (!value) return true;
|
|
212
|
+
return GENERIC_MESSAGE_PATTERNS.some((pattern) => pattern.test(value));
|
|
213
|
+
}
|
|
214
|
+
function unwrapUpstreamError(message) {
|
|
215
|
+
const start = message.indexOf("{");
|
|
216
|
+
const end = message.lastIndexOf("}");
|
|
217
|
+
if (start < 0 || end <= start) return null;
|
|
218
|
+
let parsed;
|
|
219
|
+
try {
|
|
220
|
+
parsed = JSON.parse(message.slice(start, end + 1));
|
|
221
|
+
} catch {
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
if (typeof parsed !== "object" || parsed === null) return null;
|
|
225
|
+
const body = parsed;
|
|
226
|
+
const inner = typeof body.message === "string" && body.message || typeof body.detail === "string" && body.detail || "";
|
|
227
|
+
if (!inner) return null;
|
|
228
|
+
const statusMatch = /\bHTTP (\d{3})\b/.exec(message.slice(0, start));
|
|
229
|
+
return {
|
|
230
|
+
message: inner,
|
|
231
|
+
code: typeof body.error_type === "string" && body.error_type || typeof body.error === "string" && body.error || null,
|
|
232
|
+
userMessage: typeof body.user_message === "string" ? body.user_message : null,
|
|
233
|
+
requestId: typeof body.request_id === "string" ? body.request_id : null,
|
|
234
|
+
status: statusMatch ? Number(statusMatch[1]) : null
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
function describeBackendFailure(error) {
|
|
238
|
+
const chain = [];
|
|
239
|
+
let code = "internal_error";
|
|
240
|
+
let requestId = "";
|
|
241
|
+
let status = null;
|
|
242
|
+
let userFacing = null;
|
|
243
|
+
if (error instanceof BackendApiError) {
|
|
244
|
+
code = error.code;
|
|
245
|
+
requestId = error.requestId;
|
|
246
|
+
status = error.status;
|
|
247
|
+
userFacing = error.userMessage;
|
|
248
|
+
if (error.detail) chain.push(error.detail);
|
|
249
|
+
if (error.userMessage && error.userMessage !== error.detail) {
|
|
250
|
+
chain.push(error.userMessage);
|
|
251
|
+
}
|
|
252
|
+
} else if (error instanceof Error) {
|
|
253
|
+
chain.push(error.message);
|
|
254
|
+
userFacing = error.message;
|
|
255
|
+
} else if (typeof error === "string") {
|
|
256
|
+
chain.push(error);
|
|
257
|
+
userFacing = error;
|
|
258
|
+
} else {
|
|
259
|
+
chain.push("Unknown error");
|
|
260
|
+
}
|
|
261
|
+
for (let cursor = 0; cursor < chain.length && cursor < 12; cursor += 1) {
|
|
262
|
+
const upstream = unwrapUpstreamError(chain[cursor] ?? "");
|
|
263
|
+
if (!upstream || chain.includes(upstream.message)) continue;
|
|
264
|
+
chain.push(upstream.message);
|
|
265
|
+
if (upstream.code) code = upstream.code;
|
|
266
|
+
if (upstream.requestId) requestId = upstream.requestId;
|
|
267
|
+
if (upstream.status !== null) status = upstream.status;
|
|
268
|
+
}
|
|
269
|
+
const specific = [...chain].reverse().find((message) => !isGenericUserMessage(message));
|
|
270
|
+
const cause = specific ?? chain[0] ?? "Unknown error";
|
|
271
|
+
const headlineWasGeneric = isGenericUserMessage(userFacing);
|
|
272
|
+
return {
|
|
273
|
+
code,
|
|
274
|
+
cause,
|
|
275
|
+
headline: headlineWasGeneric ? cause : userFacing ?? cause,
|
|
276
|
+
headlineWasGeneric,
|
|
277
|
+
chain,
|
|
278
|
+
requestId,
|
|
279
|
+
status
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
function getUserMessage(error) {
|
|
283
|
+
if (error instanceof BackendApiError) {
|
|
284
|
+
return error.userMessage;
|
|
285
|
+
}
|
|
286
|
+
if (error instanceof Error) {
|
|
287
|
+
return error.message;
|
|
288
|
+
}
|
|
289
|
+
if (typeof error === "string") {
|
|
290
|
+
return error;
|
|
291
|
+
}
|
|
292
|
+
if (typeof error === "object" && error !== null && typeof error.message === "string" && error.message) {
|
|
293
|
+
return error.message;
|
|
294
|
+
}
|
|
295
|
+
return "Something went wrong";
|
|
296
|
+
}
|
|
297
|
+
function statusToCode(status) {
|
|
298
|
+
switch (status) {
|
|
299
|
+
case 401:
|
|
300
|
+
return "auth_required";
|
|
301
|
+
case 403:
|
|
302
|
+
return "admin_required";
|
|
303
|
+
case 404:
|
|
304
|
+
return "not_found";
|
|
305
|
+
case 422:
|
|
306
|
+
return "validation_error";
|
|
307
|
+
default:
|
|
308
|
+
return "internal_error";
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// src/core/transport.ts
|
|
313
|
+
var MatrxApiError = class extends Error {
|
|
314
|
+
name = "MatrxApiError";
|
|
315
|
+
/** HTTP status of the failed response. */
|
|
316
|
+
status;
|
|
317
|
+
/** Machine code from the server body (`code`, or `detail.code`), when present. */
|
|
318
|
+
code;
|
|
319
|
+
/** The parsed server error body, verbatim (undefined when unparsable). */
|
|
320
|
+
serverDetail;
|
|
321
|
+
/** The request path the failure came from (server-relative). */
|
|
322
|
+
path;
|
|
323
|
+
constructor(args) {
|
|
324
|
+
super(
|
|
325
|
+
args.message ?? extractMatrxErrorMessage(args.serverDetail) ?? `HTTP ${args.status}`
|
|
326
|
+
);
|
|
327
|
+
this.status = args.status;
|
|
328
|
+
this.path = args.path;
|
|
329
|
+
this.serverDetail = args.serverDetail;
|
|
330
|
+
this.code = extractMatrxErrorCode(args.serverDetail);
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
function isRecord(value) {
|
|
334
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
335
|
+
}
|
|
336
|
+
function nonBlankString(value) {
|
|
337
|
+
return typeof value === "string" && value.trim() ? value : void 0;
|
|
338
|
+
}
|
|
339
|
+
function extractMatrxErrorMessage(serverDetail) {
|
|
340
|
+
if (!isRecord(serverDetail)) return void 0;
|
|
341
|
+
const candidates = [];
|
|
342
|
+
const push = (value) => {
|
|
343
|
+
if (value) candidates.push(value);
|
|
344
|
+
};
|
|
345
|
+
push(nonBlankString(serverDetail.user_message));
|
|
346
|
+
push(nonBlankString(serverDetail.message));
|
|
347
|
+
if (Array.isArray(serverDetail.details)) {
|
|
348
|
+
const messages = serverDetail.details.map((entry) => {
|
|
349
|
+
if (!isRecord(entry)) return void 0;
|
|
350
|
+
const detailMessage = nonBlankString(entry.message);
|
|
351
|
+
if (!detailMessage) return void 0;
|
|
352
|
+
const field = nonBlankString(entry.field);
|
|
353
|
+
return field ? `${field}: ${detailMessage}` : detailMessage;
|
|
354
|
+
}).filter((m) => typeof m === "string");
|
|
355
|
+
if (messages.length > 0) push(messages.join("; "));
|
|
356
|
+
}
|
|
357
|
+
const detail = serverDetail.detail;
|
|
358
|
+
if (isRecord(detail)) {
|
|
359
|
+
push(nonBlankString(detail.message) ?? nonBlankString(detail.user_message));
|
|
360
|
+
}
|
|
361
|
+
if (typeof detail === "string" && detail.trim()) push(detail);
|
|
362
|
+
if (Array.isArray(detail)) {
|
|
363
|
+
const messages = detail.map(
|
|
364
|
+
(entry) => isRecord(entry) ? nonBlankString(entry.msg) : void 0
|
|
365
|
+
).filter((m) => typeof m === "string");
|
|
366
|
+
if (messages.length > 0) push(messages.join("; "));
|
|
367
|
+
}
|
|
368
|
+
return candidates.find((c) => !isGenericUserMessage(c)) ?? candidates[0];
|
|
369
|
+
}
|
|
370
|
+
function extractMatrxErrorCode(serverDetail) {
|
|
371
|
+
if (!isRecord(serverDetail)) return null;
|
|
372
|
+
const topLevel = nonBlankString(serverDetail.code);
|
|
373
|
+
if (topLevel) return topLevel;
|
|
374
|
+
const detail = serverDetail.detail;
|
|
375
|
+
if (isRecord(detail)) {
|
|
376
|
+
const nested = nonBlankString(detail.code);
|
|
377
|
+
if (nested) return nested;
|
|
378
|
+
}
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
var OrganizationContextError = class extends Error {
|
|
382
|
+
code;
|
|
383
|
+
constructor(code, message) {
|
|
384
|
+
super(message);
|
|
385
|
+
this.name = "OrganizationContextError";
|
|
386
|
+
this.code = code;
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
function createOrganizationOperation(organizationId) {
|
|
390
|
+
const organization_id = requireOrganizationContext(organizationId);
|
|
391
|
+
return Object.freeze({ organization_id });
|
|
392
|
+
}
|
|
393
|
+
function assertOrganizationMatchesOperation(operation, organizationId) {
|
|
394
|
+
if (operation.organization_id !== requireOrganizationContext(organizationId)) {
|
|
395
|
+
throw new OrganizationContextError(
|
|
396
|
+
"organization_context_mismatch",
|
|
397
|
+
"Organization ID must match the request operation."
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
function requireOrganizationContext(selectedOrganizationId, overrideOrganizationId) {
|
|
402
|
+
const candidate = overrideOrganizationId ?? selectedOrganizationId;
|
|
403
|
+
if (typeof candidate !== "string" || candidate.trim().length === 0) {
|
|
404
|
+
throw new OrganizationContextError(
|
|
405
|
+
"organization_context_required",
|
|
406
|
+
"Select an organization before sending this request."
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
const normalized = candidate.trim();
|
|
410
|
+
if (!uuid.isUuidShape(normalized)) {
|
|
411
|
+
throw new OrganizationContextError(
|
|
412
|
+
"organization_context_invalid",
|
|
413
|
+
"The selected organization ID is invalid."
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
return normalized.toLowerCase();
|
|
417
|
+
}
|
|
418
|
+
function applyOrganizationContextHeader(headers, organizationId) {
|
|
419
|
+
const normalizedOrganizationId = requireOrganizationContext(organizationId);
|
|
420
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
421
|
+
if (name.toLowerCase() === "x-organization-id" && value.trim().toLowerCase() !== normalizedOrganizationId) {
|
|
422
|
+
throw new OrganizationContextError(
|
|
423
|
+
"organization_context_mismatch",
|
|
424
|
+
"X-Organization-Id must match the request context organization."
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
const withoutOrganizationHeader = Object.fromEntries(
|
|
429
|
+
Object.entries(headers).filter(
|
|
430
|
+
([name]) => name.toLowerCase() !== "x-organization-id"
|
|
431
|
+
)
|
|
432
|
+
);
|
|
433
|
+
return {
|
|
434
|
+
...withoutOrganizationHeader,
|
|
435
|
+
"X-Organization-Id": normalizedOrganizationId
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
function assertQueryOrganizationMatchesContext(queryParams, organizationId) {
|
|
439
|
+
if (!queryParams || queryParams.organization_id === void 0) return;
|
|
440
|
+
const queryOrganizationId = requireOrganizationContext(
|
|
441
|
+
String(queryParams.organization_id)
|
|
442
|
+
);
|
|
443
|
+
if (queryOrganizationId !== requireOrganizationContext(organizationId)) {
|
|
444
|
+
throw new OrganizationContextError(
|
|
445
|
+
"organization_context_mismatch",
|
|
446
|
+
"Query organization_id must match the request context organization."
|
|
447
|
+
);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// src/stream/ndjson.ts
|
|
452
|
+
var DEFAULT_MATRX_NDJSON_READ_AHEAD = 64;
|
|
453
|
+
function isRecord2(value) {
|
|
454
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
455
|
+
}
|
|
456
|
+
function normalizeMatrxStreamEnvelope(value) {
|
|
457
|
+
if (!isRecord2(value)) return null;
|
|
458
|
+
if (typeof value.event === "string") {
|
|
459
|
+
const streamSeq = typeof value.stream_seq === "number" && Number.isFinite(value.stream_seq) ? value.stream_seq : void 0;
|
|
460
|
+
const streamId = typeof value.stream_id === "string" ? value.stream_id : void 0;
|
|
461
|
+
return {
|
|
462
|
+
event: value.event,
|
|
463
|
+
data: value.data,
|
|
464
|
+
...streamId === void 0 ? {} : { stream_id: streamId },
|
|
465
|
+
...streamSeq === void 0 ? {} : { stream_seq: streamSeq }
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
if (value.e === "c" && typeof value.t === "string") {
|
|
469
|
+
const streamId = typeof value.stream_id === "string" ? value.stream_id : void 0;
|
|
470
|
+
const streamSeq = typeof value.stream_seq === "number" && Number.isFinite(value.stream_seq) ? value.stream_seq : void 0;
|
|
471
|
+
return {
|
|
472
|
+
event: "chunk",
|
|
473
|
+
data: { text: value.t },
|
|
474
|
+
...streamId === void 0 ? {} : { stream_id: streamId },
|
|
475
|
+
...streamSeq === void 0 ? {} : { stream_seq: streamSeq }
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
if (value.e === "r" && typeof value.t === "string") {
|
|
479
|
+
const streamId = typeof value.stream_id === "string" ? value.stream_id : void 0;
|
|
480
|
+
const streamSeq = typeof value.stream_seq === "number" && Number.isFinite(value.stream_seq) ? value.stream_seq : void 0;
|
|
481
|
+
return {
|
|
482
|
+
event: "reasoning_chunk",
|
|
483
|
+
data: { text: value.t },
|
|
484
|
+
...streamId === void 0 ? {} : { stream_id: streamId },
|
|
485
|
+
...streamSeq === void 0 ? {} : { stream_seq: streamSeq }
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
return null;
|
|
489
|
+
}
|
|
490
|
+
function createMatrxNdjsonFramer(options = {}) {
|
|
491
|
+
const decoder = new TextDecoder();
|
|
492
|
+
let buffer = "";
|
|
493
|
+
let lineNumber = 0;
|
|
494
|
+
let finished = false;
|
|
495
|
+
const assertOpen = () => {
|
|
496
|
+
if (finished) throw new Error("Matrx NDJSON framer is already finished");
|
|
497
|
+
};
|
|
498
|
+
const parseLine = (line, atCompletion) => {
|
|
499
|
+
const currentLineNumber = ++lineNumber;
|
|
500
|
+
const trimmed = line.trim();
|
|
501
|
+
if (!trimmed) return null;
|
|
502
|
+
let parsed;
|
|
503
|
+
try {
|
|
504
|
+
parsed = JSON.parse(trimmed);
|
|
505
|
+
} catch (error) {
|
|
506
|
+
options.onMalformedLine?.({
|
|
507
|
+
line: trimmed,
|
|
508
|
+
error,
|
|
509
|
+
lineNumber: currentLineNumber,
|
|
510
|
+
atCompletion
|
|
511
|
+
});
|
|
512
|
+
return null;
|
|
513
|
+
}
|
|
514
|
+
const envelope = normalizeMatrxStreamEnvelope(parsed);
|
|
515
|
+
if (!envelope) {
|
|
516
|
+
options.onUnknownEnvelope?.(parsed);
|
|
517
|
+
return null;
|
|
518
|
+
}
|
|
519
|
+
options.onValidEnvelope?.({
|
|
520
|
+
raw: parsed,
|
|
521
|
+
envelope,
|
|
522
|
+
line: trimmed,
|
|
523
|
+
lineNumber: currentLineNumber,
|
|
524
|
+
atCompletion
|
|
525
|
+
});
|
|
526
|
+
return envelope;
|
|
527
|
+
};
|
|
528
|
+
const pushDecodedText = (fragment) => {
|
|
529
|
+
buffer += fragment;
|
|
530
|
+
const lines = buffer.split("\n");
|
|
531
|
+
buffer = lines.pop() ?? "";
|
|
532
|
+
const envelopes = [];
|
|
533
|
+
for (const line of lines) {
|
|
534
|
+
const envelope = parseLine(line, false);
|
|
535
|
+
if (envelope) envelopes.push(envelope);
|
|
536
|
+
}
|
|
537
|
+
return envelopes;
|
|
538
|
+
};
|
|
539
|
+
return {
|
|
540
|
+
pushText(fragment) {
|
|
541
|
+
assertOpen();
|
|
542
|
+
return pushDecodedText(decoder.decode() + fragment);
|
|
543
|
+
},
|
|
544
|
+
pushBytes(fragment) {
|
|
545
|
+
assertOpen();
|
|
546
|
+
return pushDecodedText(decoder.decode(fragment, { stream: true }));
|
|
547
|
+
},
|
|
548
|
+
finish() {
|
|
549
|
+
assertOpen();
|
|
550
|
+
finished = true;
|
|
551
|
+
const envelopes = pushDecodedText(decoder.decode());
|
|
552
|
+
if (buffer.length > 0) {
|
|
553
|
+
const envelope = parseLine(buffer, true);
|
|
554
|
+
buffer = "";
|
|
555
|
+
if (envelope) envelopes.push(envelope);
|
|
556
|
+
}
|
|
557
|
+
return envelopes;
|
|
558
|
+
}
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
function readAheadLimit(value) {
|
|
562
|
+
const limit = value ?? DEFAULT_MATRX_NDJSON_READ_AHEAD;
|
|
563
|
+
if (!Number.isSafeInteger(limit) || limit < 1) {
|
|
564
|
+
throw new RangeError("maxReadAhead must be a positive safe integer");
|
|
565
|
+
}
|
|
566
|
+
return limit;
|
|
567
|
+
}
|
|
568
|
+
async function* readMatrxNdjsonStream(body, options = {}) {
|
|
569
|
+
const maxReadAhead = readAheadLimit(options.maxReadAhead);
|
|
570
|
+
const queue = [];
|
|
571
|
+
let queuedEventCount = 0;
|
|
572
|
+
let wakeConsumer = null;
|
|
573
|
+
let wakeProducer = null;
|
|
574
|
+
let readerFinished = false;
|
|
575
|
+
let consumerClosed = false;
|
|
576
|
+
const wakeWaitingConsumer = () => {
|
|
577
|
+
const wake = wakeConsumer;
|
|
578
|
+
wakeConsumer = null;
|
|
579
|
+
wake?.();
|
|
580
|
+
};
|
|
581
|
+
const wakeWaitingProducer = () => {
|
|
582
|
+
const wake = wakeProducer;
|
|
583
|
+
wakeProducer = null;
|
|
584
|
+
wake?.();
|
|
585
|
+
};
|
|
586
|
+
const enqueueTerminal = (item) => {
|
|
587
|
+
if (consumerClosed) return;
|
|
588
|
+
queue.push(item);
|
|
589
|
+
wakeWaitingConsumer();
|
|
590
|
+
};
|
|
591
|
+
const enqueueEvent = async (value) => {
|
|
592
|
+
while (queuedEventCount >= maxReadAhead && !consumerClosed && !options.signal?.aborted) {
|
|
593
|
+
await new Promise((resolve) => {
|
|
594
|
+
wakeProducer = resolve;
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
if (consumerClosed || options.signal?.aborted) return false;
|
|
598
|
+
queue.push({ kind: "event", value });
|
|
599
|
+
queuedEventCount += 1;
|
|
600
|
+
wakeWaitingConsumer();
|
|
601
|
+
return true;
|
|
602
|
+
};
|
|
603
|
+
const waitForReadCapacity = async () => {
|
|
604
|
+
while (queuedEventCount >= maxReadAhead && !consumerClosed && !options.signal?.aborted) {
|
|
605
|
+
await new Promise((resolve) => {
|
|
606
|
+
wakeProducer = resolve;
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
return !consumerClosed && !options.signal?.aborted;
|
|
610
|
+
};
|
|
611
|
+
const reader = body.getReader();
|
|
612
|
+
const framer = createMatrxNdjsonFramer(options);
|
|
613
|
+
const onAbort = () => {
|
|
614
|
+
wakeWaitingProducer();
|
|
615
|
+
wakeWaitingConsumer();
|
|
616
|
+
void reader.cancel(options.signal?.reason).catch(() => void 0);
|
|
617
|
+
};
|
|
618
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
619
|
+
if (options.signal?.aborted) onAbort();
|
|
620
|
+
const readerPromise = (async () => {
|
|
621
|
+
try {
|
|
622
|
+
while (!options.signal?.aborted && !consumerClosed) {
|
|
623
|
+
if (!await waitForReadCapacity()) return;
|
|
624
|
+
const { value, done } = await reader.read();
|
|
625
|
+
if (done) break;
|
|
626
|
+
for (const envelope of framer.pushBytes(value)) {
|
|
627
|
+
if (!await enqueueEvent(envelope)) return;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
if (!options.signal?.aborted && !consumerClosed) {
|
|
631
|
+
for (const envelope of framer.finish()) {
|
|
632
|
+
if (!await enqueueEvent(envelope)) return;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
} catch (error) {
|
|
636
|
+
const aborted = options.signal?.aborted || consumerClosed || error instanceof Error && error.name === "AbortError";
|
|
637
|
+
if (!aborted) enqueueTerminal({ kind: "error", error });
|
|
638
|
+
} finally {
|
|
639
|
+
readerFinished = true;
|
|
640
|
+
reader.releaseLock();
|
|
641
|
+
enqueueTerminal({ kind: "done" });
|
|
642
|
+
}
|
|
643
|
+
})();
|
|
644
|
+
try {
|
|
645
|
+
while (true) {
|
|
646
|
+
if (queue.length === 0) {
|
|
647
|
+
if (options.signal?.aborted || readerFinished) return;
|
|
648
|
+
await new Promise((resolve) => {
|
|
649
|
+
wakeConsumer = resolve;
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
const item = queue.shift();
|
|
653
|
+
if (item?.kind === "event") queuedEventCount -= 1;
|
|
654
|
+
wakeWaitingProducer();
|
|
655
|
+
if (!item || item.kind === "done") return;
|
|
656
|
+
if (item.kind === "error") throw item.error;
|
|
657
|
+
yield item.value;
|
|
658
|
+
}
|
|
659
|
+
} finally {
|
|
660
|
+
consumerClosed = true;
|
|
661
|
+
wakeWaitingProducer();
|
|
662
|
+
wakeWaitingConsumer();
|
|
663
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
664
|
+
if (!readerFinished) {
|
|
665
|
+
await reader.cancel().catch(() => void 0);
|
|
666
|
+
}
|
|
667
|
+
await readerPromise;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// src/stream/sse.ts
|
|
672
|
+
var FRAME_SEPARATOR = /\r\n\r\n|\n\n|\r\r/;
|
|
673
|
+
var LINE_SEPARATOR = /\r\n|\n|\r/;
|
|
674
|
+
function parseMatrxSseFrame(frame) {
|
|
675
|
+
let event = "message";
|
|
676
|
+
let id = null;
|
|
677
|
+
const dataLines = [];
|
|
678
|
+
let sawData = false;
|
|
679
|
+
for (const line of frame.split(LINE_SEPARATOR)) {
|
|
680
|
+
if (line.startsWith(":")) continue;
|
|
681
|
+
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
682
|
+
else if (line.startsWith("data:")) {
|
|
683
|
+
sawData = true;
|
|
684
|
+
dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
685
|
+
} else if (line.startsWith("id:")) id = line.slice(3).trim();
|
|
686
|
+
}
|
|
687
|
+
const seqCandidate = id !== null && id !== "" ? Number(id) : NaN;
|
|
688
|
+
const seq = Number.isSafeInteger(seqCandidate) && seqCandidate >= 0 ? seqCandidate : null;
|
|
689
|
+
return { event, id, seq, data: sawData ? dataLines.join("\n") : null };
|
|
690
|
+
}
|
|
691
|
+
function createMatrxSseFramer() {
|
|
692
|
+
let buffer = "";
|
|
693
|
+
return {
|
|
694
|
+
push(chunk) {
|
|
695
|
+
buffer += chunk;
|
|
696
|
+
const frames = [];
|
|
697
|
+
for (; ; ) {
|
|
698
|
+
const sep = FRAME_SEPARATOR.exec(buffer);
|
|
699
|
+
if (sep === null) break;
|
|
700
|
+
const frame = buffer.slice(0, sep.index);
|
|
701
|
+
buffer = buffer.slice(sep.index + sep[0].length);
|
|
702
|
+
frames.push(parseMatrxSseFrame(frame));
|
|
703
|
+
}
|
|
704
|
+
return frames;
|
|
705
|
+
},
|
|
706
|
+
flush() {
|
|
707
|
+
const rest = buffer;
|
|
708
|
+
buffer = "";
|
|
709
|
+
return { incomplete: rest.length > 0 ? rest : null };
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
async function* readMatrxSseStream(stream, options = {}) {
|
|
714
|
+
const reader = stream.getReader();
|
|
715
|
+
const decoder = new TextDecoder();
|
|
716
|
+
const framer = createMatrxSseFramer();
|
|
717
|
+
try {
|
|
718
|
+
for (; ; ) {
|
|
719
|
+
const { value, done } = await reader.read();
|
|
720
|
+
if (done) break;
|
|
721
|
+
const frames = framer.push(decoder.decode(value, { stream: true }));
|
|
722
|
+
for (const frame of frames) yield frame;
|
|
723
|
+
}
|
|
724
|
+
const tail = framer.push(decoder.decode());
|
|
725
|
+
for (const frame of tail) yield frame;
|
|
726
|
+
const { incomplete } = framer.flush();
|
|
727
|
+
if (incomplete !== null) options.onIncomplete?.(incomplete);
|
|
728
|
+
} finally {
|
|
729
|
+
reader.releaseLock();
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// src/deployments.generated.ts
|
|
734
|
+
var CONTRACT_SHA256 = "50a790edb39e682b46e0fa9e674faf5ce2a0ba7de2cd01930a497fca4c47844a";
|
|
735
|
+
var DEPLOYMENTS = {
|
|
736
|
+
"files": {
|
|
737
|
+
"app": "files-standalone",
|
|
738
|
+
"baseUrl": {
|
|
739
|
+
"production": "https://files.matrxserver.com",
|
|
740
|
+
"localhost": "http://127.0.0.1:8090"
|
|
741
|
+
},
|
|
742
|
+
"env": {
|
|
743
|
+
"browser": "NEXT_PUBLIC_FILES_URL",
|
|
744
|
+
"browser_local": "NEXT_PUBLIC_FILES_URL_LOCAL",
|
|
745
|
+
"server": "MATRX_FILES_URL"
|
|
746
|
+
}
|
|
747
|
+
},
|
|
748
|
+
"scraper": {
|
|
749
|
+
"app": "scraper-server",
|
|
750
|
+
"baseUrl": {
|
|
751
|
+
"production": "https://scraper.app.matrxserver.com",
|
|
752
|
+
"localhost": "http://localhost:8001"
|
|
753
|
+
},
|
|
754
|
+
"env": {
|
|
755
|
+
"browser": "NEXT_PUBLIC_SCRAPER_URL",
|
|
756
|
+
"browser_local": "NEXT_PUBLIC_SCRAPER_URL_LOCAL",
|
|
757
|
+
"server": "MATRX_SCRAPER_URL",
|
|
758
|
+
"service_token": "MATRX_SCRAPER_TOKEN"
|
|
759
|
+
}
|
|
760
|
+
},
|
|
761
|
+
"seo": {
|
|
762
|
+
"app": "seo-standalone",
|
|
763
|
+
"baseUrl": {
|
|
764
|
+
"production": "https://seo.matrxserver.com",
|
|
765
|
+
"localhost": "http://127.0.0.1:8081"
|
|
766
|
+
},
|
|
767
|
+
"env": {
|
|
768
|
+
"browser": "NEXT_PUBLIC_SEO_URL",
|
|
769
|
+
"browser_local": "NEXT_PUBLIC_SEO_URL_LOCAL"
|
|
770
|
+
}
|
|
771
|
+
},
|
|
772
|
+
"sandbox-orchestrator": {
|
|
773
|
+
"app": "sandbox-orchestrator",
|
|
774
|
+
"baseUrl": {
|
|
775
|
+
"production": "https://orchestrator.dev.codematrx.com"
|
|
776
|
+
},
|
|
777
|
+
"env": {
|
|
778
|
+
"server": "SANDBOX_ORCHESTRATOR_URL",
|
|
779
|
+
"service_token": "SANDBOX_ORCHESTRATOR_API_KEY"
|
|
780
|
+
}
|
|
781
|
+
},
|
|
782
|
+
"matrx-local": {
|
|
783
|
+
"app": "matrx-local",
|
|
784
|
+
"baseUrl": {
|
|
785
|
+
"localhost": "http://127.0.0.1:22140"
|
|
786
|
+
},
|
|
787
|
+
"env": {
|
|
788
|
+
"port_base": "MATRX_PORT_BASE"
|
|
789
|
+
}
|
|
790
|
+
},
|
|
791
|
+
"cloud-browser-streaming": {
|
|
792
|
+
"app": "cloud-browser-streaming",
|
|
793
|
+
"baseUrl": {},
|
|
794
|
+
"env": {}
|
|
795
|
+
},
|
|
796
|
+
"cloud-browser-worker": {
|
|
797
|
+
"app": "cloud-browser-worker",
|
|
798
|
+
"baseUrl": {},
|
|
799
|
+
"env": {}
|
|
800
|
+
},
|
|
801
|
+
"hosted-box": {
|
|
802
|
+
"app": "hosted-box",
|
|
803
|
+
"baseUrl": {},
|
|
804
|
+
"env": {}
|
|
805
|
+
},
|
|
806
|
+
"aidream": {
|
|
807
|
+
"app": "aidream-main",
|
|
808
|
+
"baseUrl": {
|
|
809
|
+
"production": "https://server.app.matrxserver.com",
|
|
810
|
+
"localhost": "http://localhost:8000"
|
|
811
|
+
},
|
|
812
|
+
"env": {
|
|
813
|
+
"browser": "NEXT_PUBLIC_BACKEND_URL_PROD",
|
|
814
|
+
"server": "MATRX_AIDREAM_URL",
|
|
815
|
+
"service_token": "MATRX_AIDREAM_SERVICE_TOKEN",
|
|
816
|
+
"sandbox_service_token": "AIDREAM_SANDBOX_SERVICE_TOKEN"
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
};
|
|
820
|
+
var DOMAINS = ["account", "agents", "ai", "apps", "architecture", "audio", "chat", "code", "commerce", "communications", "computer", "content", "crm", "data", "education", "files", "human-resources", "integrations", "intelligence", "knowledge", "legal", "marketing", "masterwork", "media", "platform", "publish", "web", "workflows"];
|
|
821
|
+
|
|
822
|
+
// src/api.ts
|
|
823
|
+
var DEFAULT_CONNECT_TIMEOUT_MS = 15e3;
|
|
824
|
+
function defaultRequestId() {
|
|
825
|
+
const c = globalThis.crypto;
|
|
826
|
+
if (c?.randomUUID) return c.randomUUID();
|
|
827
|
+
return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
828
|
+
}
|
|
829
|
+
function interpolate(template, params) {
|
|
830
|
+
return template.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
831
|
+
const value = params?.[name];
|
|
832
|
+
if (value === void 0 || value === null || String(value).length === 0) {
|
|
833
|
+
throw new TypeError(`Missing path parameter "${name}" for ${template}`);
|
|
834
|
+
}
|
|
835
|
+
return encodeURIComponent(String(value));
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
function queryString(query) {
|
|
839
|
+
if (!query) return "";
|
|
840
|
+
const parts = [];
|
|
841
|
+
for (const [key, raw] of Object.entries(query)) {
|
|
842
|
+
if (raw === void 0 || raw === null) continue;
|
|
843
|
+
const values = Array.isArray(raw) ? raw : [raw];
|
|
844
|
+
for (const v of values) {
|
|
845
|
+
if (v === void 0 || v === null) continue;
|
|
846
|
+
const text = typeof v === "object" ? JSON.stringify(v) : String(v);
|
|
847
|
+
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(text)}`);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
return parts.length ? `?${parts.join("&")}` : "";
|
|
851
|
+
}
|
|
852
|
+
function isBodyInit(body) {
|
|
853
|
+
return typeof body === "string" || typeof Blob !== "undefined" && body instanceof Blob || typeof FormData !== "undefined" && body instanceof FormData || typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
|
|
854
|
+
}
|
|
855
|
+
function acceptFor(stream) {
|
|
856
|
+
switch (stream) {
|
|
857
|
+
case "ndjson":
|
|
858
|
+
return "application/x-ndjson";
|
|
859
|
+
case "sse":
|
|
860
|
+
return "text/event-stream";
|
|
861
|
+
case "ndjson_or_json":
|
|
862
|
+
return "application/x-ndjson, application/json";
|
|
863
|
+
case "sse_or_json":
|
|
864
|
+
return "text/event-stream, application/json";
|
|
865
|
+
case "bytes":
|
|
866
|
+
return "*/*";
|
|
867
|
+
case "bytes_or_json":
|
|
868
|
+
return "*/*, application/json";
|
|
869
|
+
default:
|
|
870
|
+
return "application/json";
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
async function errorFrom(response, path) {
|
|
874
|
+
const text = await response.text().catch(() => "");
|
|
875
|
+
let serverDetail = void 0;
|
|
876
|
+
try {
|
|
877
|
+
serverDetail = text ? JSON.parse(text) : void 0;
|
|
878
|
+
} catch {
|
|
879
|
+
serverDetail = text || void 0;
|
|
880
|
+
}
|
|
881
|
+
return new MatrxApiError({ status: response.status, path, serverDetail });
|
|
882
|
+
}
|
|
883
|
+
function createApi(options = {}) {
|
|
884
|
+
const credentials = chunk5WJLKYH6_cjs.toCredentialsPort(options.credentials);
|
|
885
|
+
const environment = options.environment ?? "production";
|
|
886
|
+
const mintRequestId = options.requestId ?? defaultRequestId;
|
|
887
|
+
const retryAttempts = Math.max(1, options.retryAttempts ?? 3);
|
|
888
|
+
const baseFor = (op) => {
|
|
889
|
+
const dynamic = options.resolveBaseUrl?.(op.d, op);
|
|
890
|
+
if (dynamic) return dynamic.replace(/\/+$/, "");
|
|
891
|
+
const override = options.baseUrls?.[op.d];
|
|
892
|
+
if (override) return override.replace(/\/+$/, "");
|
|
893
|
+
const deployment = DEPLOYMENTS[op.d];
|
|
894
|
+
const fallback = deployment.baseUrl[environment];
|
|
895
|
+
if (!fallback) {
|
|
896
|
+
throw new Error(
|
|
897
|
+
`@ai-matrx/api: no base URL for deployment "${op.d}" in ${environment} (operation ${op.n}). Pass createApi({ baseUrls: { "${op.d}": "https://\u2026" } })` + (deployment.env.server ? ` \u2014 servers read it from ${deployment.env.server}.` : ".")
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
return fallback;
|
|
901
|
+
};
|
|
902
|
+
const urlOf = (op, args) => `${baseFor(op)}${interpolate(op.p, args?.path)}${queryString(args?.query)}`;
|
|
903
|
+
const organizationFor = (op, call) => {
|
|
904
|
+
if (op.o === "exempt") return null;
|
|
905
|
+
const bound = options.organizationId;
|
|
906
|
+
const selected = call?.organizationId ?? (typeof bound === "function" ? bound() : bound) ?? null;
|
|
907
|
+
if (op.o === "required") return requireOrganizationContext(selected);
|
|
908
|
+
return selected && selected.trim() ? selected.trim() : null;
|
|
909
|
+
};
|
|
910
|
+
const send = async (op, args, call) => {
|
|
911
|
+
const url = urlOf(op, args);
|
|
912
|
+
const requestId = mintRequestId();
|
|
913
|
+
const orgId = organizationFor(op, call);
|
|
914
|
+
const headers = {
|
|
915
|
+
...options.headers,
|
|
916
|
+
...call?.headers,
|
|
917
|
+
Accept: acceptFor(op.s),
|
|
918
|
+
[chunk5WJLKYH6_cjs.MATRX_HEADERS.requestId]: requestId
|
|
919
|
+
};
|
|
920
|
+
let body;
|
|
921
|
+
if (args?.body !== void 0 && op.m !== "GET" && op.m !== "HEAD") {
|
|
922
|
+
if (isBodyInit(args.body)) {
|
|
923
|
+
body = args.body;
|
|
924
|
+
} else {
|
|
925
|
+
body = JSON.stringify(args.body);
|
|
926
|
+
headers["Content-Type"] = "application/json";
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
Object.assign(headers, chunk5WJLKYH6_cjs.credentialToHeaders(await credentials.get()));
|
|
930
|
+
if (orgId !== null) headers[chunk5WJLKYH6_cjs.MATRX_HEADERS.organization] = orgId;
|
|
931
|
+
options.onRequest?.({ operation: op.n, method: op.m, url, requestId, deployment: op.d });
|
|
932
|
+
const attempt = () => chunk2SXAAKGV_cjs.resilientFetch(
|
|
933
|
+
url,
|
|
934
|
+
{ method: op.m, headers, ...body !== void 0 ? { body } : {} },
|
|
935
|
+
{
|
|
936
|
+
...call?.signal ? { signal: call.signal } : {},
|
|
937
|
+
connectTimeoutMs: call?.connectTimeoutMs ?? options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
|
|
938
|
+
totalTimeoutMs: call?.totalTimeoutMs !== void 0 ? call.totalTimeoutMs : options.totalTimeoutMs ?? null,
|
|
939
|
+
throwOnHttpError: false
|
|
940
|
+
}
|
|
941
|
+
);
|
|
942
|
+
const idempotent = op.m === "GET" || op.m === "HEAD";
|
|
943
|
+
const { response, controller } = idempotent && retryAttempts > 1 && !op.s ? await chunk2SXAAKGV_cjs.withRetry(attempt, {
|
|
944
|
+
attempts: retryAttempts,
|
|
945
|
+
retryOn: chunk2SXAAKGV_cjs.isTransportFailure,
|
|
946
|
+
...call?.signal ? { signal: call.signal } : {}
|
|
947
|
+
}) : await attempt();
|
|
948
|
+
if (!response.ok) throw await errorFrom(response, interpolate(op.p, args?.path));
|
|
949
|
+
return { response, requestId, controller };
|
|
950
|
+
};
|
|
951
|
+
return {
|
|
952
|
+
url: urlOf,
|
|
953
|
+
send,
|
|
954
|
+
async call(op, args, call) {
|
|
955
|
+
const { response } = await send(op, args, call);
|
|
956
|
+
if (response.status === 204 || op.m === "HEAD") return void 0;
|
|
957
|
+
const type = response.headers.get("content-type") ?? "";
|
|
958
|
+
if (type.includes("json")) return await response.json();
|
|
959
|
+
const text = await response.text();
|
|
960
|
+
try {
|
|
961
|
+
return JSON.parse(text);
|
|
962
|
+
} catch {
|
|
963
|
+
return text;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
function wrapStream(response, requestId, controller, iterate) {
|
|
969
|
+
return {
|
|
970
|
+
response,
|
|
971
|
+
requestId,
|
|
972
|
+
cancel: () => controller.abort(),
|
|
973
|
+
[Symbol.asyncIterator]() {
|
|
974
|
+
if (!response.body) throw new Error("@ai-matrx/api: the stream response has no body");
|
|
975
|
+
return iterate(response.body)[Symbol.asyncIterator]();
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
async function openStream(api, op, args, options) {
|
|
980
|
+
const { response, requestId, controller } = await api.send(op, args, options);
|
|
981
|
+
return toStream(op, response, requestId, controller);
|
|
982
|
+
}
|
|
983
|
+
function toStream(op, response, requestId, controller) {
|
|
984
|
+
const kind = op.s ?? "none";
|
|
985
|
+
if (kind.startsWith("sse")) {
|
|
986
|
+
return wrapStream(response, requestId, controller, (b) => readMatrxSseStream(b));
|
|
987
|
+
}
|
|
988
|
+
if (kind.startsWith("ndjson")) {
|
|
989
|
+
return wrapStream(response, requestId, controller, (b) => readMatrxNdjsonStream(b));
|
|
990
|
+
}
|
|
991
|
+
return wrapStream(response, requestId, controller, (b) => streamChunks(b));
|
|
992
|
+
}
|
|
993
|
+
async function* streamChunks(body) {
|
|
994
|
+
const reader = body.getReader();
|
|
995
|
+
try {
|
|
996
|
+
for (; ; ) {
|
|
997
|
+
const { done, value } = await reader.read();
|
|
998
|
+
if (done) return;
|
|
999
|
+
if (value) yield value;
|
|
1000
|
+
}
|
|
1001
|
+
} finally {
|
|
1002
|
+
reader.releaseLock();
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
async function openJsonOrStream(api, op, args, options) {
|
|
1006
|
+
const { response, requestId, controller } = await api.send(op, args, options);
|
|
1007
|
+
const type = response.headers.get("content-type") ?? "";
|
|
1008
|
+
if (type.includes("application/json")) {
|
|
1009
|
+
return { kind: "json", data: await response.json() };
|
|
1010
|
+
}
|
|
1011
|
+
return { kind: "stream", stream: toStream(op, response, requestId, controller) };
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
exports.BackendApiError = BackendApiError;
|
|
1015
|
+
exports.CONTRACT_SHA256 = CONTRACT_SHA256;
|
|
1016
|
+
exports.DEFAULT_MATRX_NDJSON_READ_AHEAD = DEFAULT_MATRX_NDJSON_READ_AHEAD;
|
|
1017
|
+
exports.DEPLOYMENTS = DEPLOYMENTS;
|
|
1018
|
+
exports.DOMAINS = DOMAINS;
|
|
1019
|
+
exports.MatrxApiError = MatrxApiError;
|
|
1020
|
+
exports.OrganizationContextError = OrganizationContextError;
|
|
1021
|
+
exports.StreamTransportError = StreamTransportError;
|
|
1022
|
+
exports.applyOrganizationContextHeader = applyOrganizationContextHeader;
|
|
1023
|
+
exports.assertOrganizationMatchesOperation = assertOrganizationMatchesOperation;
|
|
1024
|
+
exports.assertQueryOrganizationMatchesContext = assertQueryOrganizationMatchesContext;
|
|
1025
|
+
exports.createApi = createApi;
|
|
1026
|
+
exports.createMatrxNdjsonFramer = createMatrxNdjsonFramer;
|
|
1027
|
+
exports.createMatrxSseFramer = createMatrxSseFramer;
|
|
1028
|
+
exports.createOrganizationOperation = createOrganizationOperation;
|
|
1029
|
+
exports.describeBackendFailure = describeBackendFailure;
|
|
1030
|
+
exports.extractMatrxErrorCode = extractMatrxErrorCode;
|
|
1031
|
+
exports.extractMatrxErrorMessage = extractMatrxErrorMessage;
|
|
1032
|
+
exports.getUserMessage = getUserMessage;
|
|
1033
|
+
exports.isGenericUserMessage = isGenericUserMessage;
|
|
1034
|
+
exports.isStreamTransportLost = isStreamTransportLost;
|
|
1035
|
+
exports.normalizeMatrxStreamEnvelope = normalizeMatrxStreamEnvelope;
|
|
1036
|
+
exports.openJsonOrStream = openJsonOrStream;
|
|
1037
|
+
exports.openStream = openStream;
|
|
1038
|
+
exports.parseCallApiError = parseCallApiError;
|
|
1039
|
+
exports.parseHttpError = parseHttpError;
|
|
1040
|
+
exports.parseHttpErrorBody = parseHttpErrorBody;
|
|
1041
|
+
exports.parseMatrxSseFrame = parseMatrxSseFrame;
|
|
1042
|
+
exports.parsePersistedBackendError = parsePersistedBackendError;
|
|
1043
|
+
exports.parseStreamError = parseStreamError;
|
|
1044
|
+
exports.readMatrxNdjsonStream = readMatrxNdjsonStream;
|
|
1045
|
+
exports.readMatrxSseStream = readMatrxSseStream;
|
|
1046
|
+
exports.requireOrganizationContext = requireOrganizationContext;
|
|
1047
|
+
exports.unwrapUpstreamError = unwrapUpstreamError;
|