@ai-matrx/agents 0.28.0 → 0.29.0

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 (50) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/content-transfer/index.cjs.map +1 -1
  3. package/dist/content-transfer/index.d.cts +2 -1
  4. package/dist/content-transfer/index.d.ts +2 -1
  5. package/dist/content-transfer/index.js.map +1 -1
  6. package/dist/content-transfer/react/index.cjs.map +1 -1
  7. package/dist/content-transfer/react/index.js.map +1 -1
  8. package/dist/context/index.cjs +29 -5
  9. package/dist/context/index.cjs.map +1 -1
  10. package/dist/context/index.d.cts +65 -13
  11. package/dist/context/index.d.ts +65 -13
  12. package/dist/context/index.js +29 -5
  13. package/dist/context/index.js.map +1 -1
  14. package/dist/context/react/index.cjs +262 -78
  15. package/dist/context/react/index.cjs.map +1 -1
  16. package/dist/context/react/index.d.cts +100 -21
  17. package/dist/context/react/index.d.ts +100 -21
  18. package/dist/context/react/index.js +261 -77
  19. package/dist/context/react/index.js.map +1 -1
  20. package/dist/index.d.cts +2 -1
  21. package/dist/index.d.ts +2 -1
  22. package/dist/mandates/index.cjs +2 -2
  23. package/dist/mandates/index.cjs.map +1 -1
  24. package/dist/mandates/index.d.cts +4 -4
  25. package/dist/mandates/index.d.ts +4 -4
  26. package/dist/mandates/index.js +2 -2
  27. package/dist/mandates/index.js.map +1 -1
  28. package/dist/matrx/index.d.cts +4 -2
  29. package/dist/matrx/index.d.ts +4 -2
  30. package/dist/{operations-Dp4ut-ac.d.ts → operations-C3iHFcnt.d.ts} +2 -94
  31. package/dist/{operations--f5ko9Su.d.cts → operations-C9QvBH_2.d.cts} +2 -94
  32. package/dist/portable/index.cjs +164 -0
  33. package/dist/portable/index.cjs.map +1 -0
  34. package/dist/portable/index.d.cts +74 -0
  35. package/dist/portable/index.d.ts +74 -0
  36. package/dist/portable/index.js +141 -0
  37. package/dist/portable/index.js.map +1 -0
  38. package/dist/portable/mcp.cjs +512 -0
  39. package/dist/portable/mcp.cjs.map +1 -0
  40. package/dist/portable/mcp.d.cts +81 -0
  41. package/dist/portable/mcp.d.ts +81 -0
  42. package/dist/portable/mcp.js +492 -0
  43. package/dist/portable/mcp.js.map +1 -0
  44. package/dist/transport-CxD0fL8p.d.cts +94 -0
  45. package/dist/transport-CxD0fL8p.d.ts +94 -0
  46. package/dist/types.generated-BydVlqDC.d.cts +49 -0
  47. package/dist/types.generated-BydVlqDC.d.ts +49 -0
  48. package/mandates/snapshots/keys.0.28.1.json +652 -0
  49. package/mandates/snapshots/keys.0.29.0.json +652 -0
  50. package/package.json +24 -4
@@ -0,0 +1,512 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // portable/mcp.ts
21
+ var mcp_exports = {};
22
+ __export(mcp_exports, {
23
+ AGENT_TOOLS_MCP_PROTOCOL_VERSIONS: () => AGENT_TOOLS_MCP_PROTOCOL_VERSIONS,
24
+ AGENT_TOOLS_MCP_SERVER_NAME: () => AGENT_TOOLS_MCP_SERVER_NAME,
25
+ NO_ORGANIZATION_TOOL_MESSAGE: () => NO_ORGANIZATION_TOOL_MESSAGE,
26
+ SIGNED_OUT_TOOL_MESSAGE: () => SIGNED_OUT_TOOL_MESSAGE,
27
+ createAgentToolsMcpHandler: () => createAgentToolsMcpHandler
28
+ });
29
+ module.exports = __toCommonJS(mcp_exports);
30
+
31
+ // matrx/client.ts
32
+ var import_data = require("@ai-matrx/data");
33
+ var import_data2 = require("@ai-matrx/data");
34
+
35
+ // matrx/org-context.ts
36
+ var import_uuid = require("@ai-matrx/kit/uuid");
37
+ var OrganizationContextError = class extends Error {
38
+ code;
39
+ constructor(code, message) {
40
+ super(message);
41
+ this.name = "OrganizationContextError";
42
+ this.code = code;
43
+ }
44
+ };
45
+ function requireOrganizationContext(selectedOrganizationId, overrideOrganizationId) {
46
+ const candidate = overrideOrganizationId ?? selectedOrganizationId;
47
+ if (typeof candidate !== "string" || candidate.trim().length === 0) {
48
+ throw new OrganizationContextError(
49
+ "organization_context_required",
50
+ "Select an organization before sending this request."
51
+ );
52
+ }
53
+ const normalized = candidate.trim();
54
+ if (!(0, import_uuid.isUuidShape)(normalized)) {
55
+ throw new OrganizationContextError(
56
+ "organization_context_invalid",
57
+ "The selected organization ID is invalid."
58
+ );
59
+ }
60
+ return normalized.toLowerCase();
61
+ }
62
+ function applyOrganizationContextHeader(headers, organizationId) {
63
+ const normalizedOrganizationId = requireOrganizationContext(organizationId);
64
+ for (const [name, value] of Object.entries(headers)) {
65
+ if (name.toLowerCase() === "x-organization-id" && value.trim().toLowerCase() !== normalizedOrganizationId) {
66
+ throw new OrganizationContextError(
67
+ "organization_context_mismatch",
68
+ "X-Organization-Id must match the request context organization."
69
+ );
70
+ }
71
+ }
72
+ const withoutOrganizationHeader = Object.fromEntries(
73
+ Object.entries(headers).filter(
74
+ ([name]) => name.toLowerCase() !== "x-organization-id"
75
+ )
76
+ );
77
+ return {
78
+ ...withoutOrganizationHeader,
79
+ "X-Organization-Id": normalizedOrganizationId
80
+ };
81
+ }
82
+
83
+ // matrx/protocol.ts
84
+ var import_net = require("@ai-matrx/data/net");
85
+ var MATRX_AI_API_VERSION_DEFAULT = "v2";
86
+ function toV2Path(path) {
87
+ const withLead = path.startsWith("/") ? path : `/${path}`;
88
+ if (withLead.startsWith("/api/")) {
89
+ const rest = withLead.slice("/api".length);
90
+ return rest.startsWith("/v2/") ? withLead : `/api/v2${rest}`;
91
+ }
92
+ return withLead.startsWith("/v2/") ? withLead : `/v2${withLead}`;
93
+ }
94
+ var COVERED_INTERPOLATED_PATH = [
95
+ /^(?:\/api)?\/ai\/manual$/,
96
+ /^(?:\/api)?\/ai\/chat$/,
97
+ /^(?:\/api)?\/ai\/agents\/[^/]+$/,
98
+ /^(?:\/api)?\/ai\/agent\/[^/]+$/,
99
+ /^(?:\/api)?\/ai\/conversations\/[^/]+$/,
100
+ /^(?:\/api)?\/ai\/conversation\/[^/]+$/,
101
+ /^(?:\/api)?\/ai\/prompts\/[^/]+$/,
102
+ // `/warm` etc. deliberately don't match
103
+ /^(?:\/api)?\/ai\/mandates\/[^/]+$/
104
+ // the mandate door
105
+ ];
106
+ function isCoveredAiPath(path) {
107
+ return COVERED_INTERPOLATED_PATH.some((re) => re.test(path));
108
+ }
109
+ function isV2Path(pathOrUrl) {
110
+ return /\/v2\/ai\//.test(pathOrUrl);
111
+ }
112
+ function toV1FallbackUrl(url) {
113
+ return url.replace(/\/v2\/ai\//, "/ai/");
114
+ }
115
+ function applyAiApiVersion(path, version) {
116
+ if (version !== "v2") return path;
117
+ return isCoveredAiPath(path) ? toV2Path(path) : path;
118
+ }
119
+ async function fetchWithMatrxProtocolFallback(url, init, opts = {}) {
120
+ const { onDowngrade, ...fetchOpts } = opts;
121
+ const logDowngrade = (reason, status2) => {
122
+ console.warn(
123
+ `[matrx] ai_v2_downgrade \u2192 retrying on v1. v2=${url} reason=${reason}`
124
+ );
125
+ onDowngrade?.({ url, reason, ...status2 !== void 0 ? { status: status2 } : {} });
126
+ };
127
+ if (!isV2Path(url)) return (0, import_net.resilientFetch)(url, init, fetchOpts);
128
+ let result;
129
+ try {
130
+ result = await (0, import_net.resilientFetch)(url, init, fetchOpts);
131
+ } catch (err) {
132
+ const isAbort = (0, import_net.isNetError)(err) && err.code === "aborted" || err instanceof Error && err.name === "AbortError";
133
+ if (isAbort) throw err;
134
+ logDowngrade(String(err));
135
+ return (0, import_net.resilientFetch)(toV1FallbackUrl(url), init, fetchOpts);
136
+ }
137
+ const status = result.response.status;
138
+ if (status === 404 || status === 405 || status >= 500) {
139
+ logDowngrade(`HTTP ${status}`, status);
140
+ return (0, import_net.resilientFetch)(toV1FallbackUrl(url), init, fetchOpts);
141
+ }
142
+ return result;
143
+ }
144
+
145
+ // matrx/transport.ts
146
+ var MatrxApiError = class extends Error {
147
+ name = "MatrxApiError";
148
+ /** HTTP status of the failed response. */
149
+ status;
150
+ /** Machine code from the server body (`code`, or `detail.code`), when present. */
151
+ code;
152
+ /** The parsed server error body, verbatim (undefined when unparsable). */
153
+ serverDetail;
154
+ /** The request path the failure came from (server-relative). */
155
+ path;
156
+ constructor(args) {
157
+ super(
158
+ args.message ?? extractMatrxErrorMessage(args.serverDetail) ?? `HTTP ${args.status}`
159
+ );
160
+ this.status = args.status;
161
+ this.path = args.path;
162
+ this.serverDetail = args.serverDetail;
163
+ this.code = extractMatrxErrorCode(args.serverDetail);
164
+ }
165
+ };
166
+ function isRecord(value) {
167
+ return typeof value === "object" && value !== null && !Array.isArray(value);
168
+ }
169
+ function nonBlankString(value) {
170
+ return typeof value === "string" && value.trim() ? value : void 0;
171
+ }
172
+ function extractMatrxErrorMessage(serverDetail) {
173
+ if (!isRecord(serverDetail)) return void 0;
174
+ const userMessage = nonBlankString(serverDetail.user_message);
175
+ if (userMessage) return userMessage;
176
+ const message = nonBlankString(serverDetail.message);
177
+ if (message) return message;
178
+ if (Array.isArray(serverDetail.details)) {
179
+ const messages = serverDetail.details.map((entry) => {
180
+ if (!isRecord(entry)) return void 0;
181
+ const detailMessage = nonBlankString(entry.message);
182
+ if (!detailMessage) return void 0;
183
+ const field = nonBlankString(entry.field);
184
+ return field ? `${field}: ${detailMessage}` : detailMessage;
185
+ }).filter((m) => typeof m === "string");
186
+ if (messages.length > 0) return messages.join("; ");
187
+ }
188
+ const detail = serverDetail.detail;
189
+ if (isRecord(detail)) {
190
+ const detailMessage = nonBlankString(detail.message) ?? nonBlankString(detail.user_message);
191
+ if (detailMessage) return detailMessage;
192
+ }
193
+ if (typeof detail === "string" && detail.trim()) return detail;
194
+ if (Array.isArray(detail)) {
195
+ const messages = detail.map(
196
+ (entry) => isRecord(entry) ? nonBlankString(entry.msg) : void 0
197
+ ).filter((m) => typeof m === "string");
198
+ if (messages.length > 0) return messages.join("; ");
199
+ }
200
+ return void 0;
201
+ }
202
+ function extractMatrxErrorCode(serverDetail) {
203
+ if (!isRecord(serverDetail)) return null;
204
+ const topLevel = nonBlankString(serverDetail.code);
205
+ if (topLevel) return topLevel;
206
+ const detail = serverDetail.detail;
207
+ if (isRecord(detail)) {
208
+ const nested = nonBlankString(detail.code);
209
+ if (nested) return nested;
210
+ }
211
+ return null;
212
+ }
213
+
214
+ // matrx/client.ts
215
+ function classifyStatus(status) {
216
+ return status >= 400 && status < 500 ? "validation_error" : "http_error";
217
+ }
218
+ function normalizeMatrxError(err) {
219
+ if (err instanceof MatrxApiError) {
220
+ return {
221
+ type: classifyStatus(err.status),
222
+ message: err.message,
223
+ status: err.status,
224
+ serverDetail: err.serverDetail,
225
+ ...err.code ? { code: err.code } : {},
226
+ name: err.name
227
+ };
228
+ }
229
+ if (err instanceof OrganizationContextError) {
230
+ return {
231
+ type: "validation_error",
232
+ message: err.message,
233
+ code: err.code,
234
+ name: err.name,
235
+ ...err.stack !== void 0 ? { stack: err.stack } : {}
236
+ };
237
+ }
238
+ if (err instanceof DOMException && err.name === "AbortError") {
239
+ return { type: "abort_error", message: "Request was cancelled." };
240
+ }
241
+ if ((0, import_data.isNetError)(err)) {
242
+ if (err.code === "aborted") {
243
+ return { type: "abort_error", message: err.message };
244
+ }
245
+ if (err.code === "http") {
246
+ const status = err.status ?? 0;
247
+ return { type: classifyStatus(status), message: err.message, status };
248
+ }
249
+ return { type: "network_error", message: err.message };
250
+ }
251
+ if (err instanceof Error) {
252
+ const httpMatch = err.message.match(/HTTP (\d+):\s*(.*)/);
253
+ if (httpMatch) {
254
+ const status = parseInt(httpMatch[1], 10);
255
+ return {
256
+ type: classifyStatus(status),
257
+ message: httpMatch[2] ?? err.message,
258
+ status
259
+ };
260
+ }
261
+ return { type: "network_error", message: err.message };
262
+ }
263
+ return { type: "unknown", message: String(err ?? "Unknown error") };
264
+ }
265
+ var PRODUCTION_CONNECT_TIMEOUT_MS = 15e3;
266
+ function stripContentType(headers) {
267
+ return Object.fromEntries(
268
+ Object.entries(headers).filter(
269
+ ([name]) => name.toLowerCase() !== "content-type"
270
+ )
271
+ );
272
+ }
273
+ function createMatrxTransport(options) {
274
+ const {
275
+ baseUrl,
276
+ resolveTarget,
277
+ credentials,
278
+ organizationId,
279
+ aiApiVersion,
280
+ connectTimeoutMs = PRODUCTION_CONNECT_TIMEOUT_MS,
281
+ totalTimeoutMs = null,
282
+ expectedErrorStatuses,
283
+ diagnostics,
284
+ source = "matrxTransport"
285
+ } = options;
286
+ if (baseUrl === void 0 === (resolveTarget === void 0)) {
287
+ throw new Error(
288
+ "createMatrxTransport: provide exactly one of `baseUrl` or `resolveTarget`."
289
+ );
290
+ }
291
+ const resolve = resolveTarget ?? (() => ({ baseUrl }));
292
+ const resolveVersion = () => {
293
+ if (aiApiVersion === void 0) return MATRX_AI_API_VERSION_DEFAULT;
294
+ return typeof aiApiVersion === "function" ? aiApiVersion() : aiApiVersion;
295
+ };
296
+ const resolveOrganizationId = () => {
297
+ if (organizationId === void 0) return null;
298
+ const candidate = typeof organizationId === "function" ? organizationId() : organizationId;
299
+ return requireOrganizationContext(candidate);
300
+ };
301
+ return {
302
+ async fetch(path, init) {
303
+ const target = resolve();
304
+ const versionedPath = applyAiApiVersion(path, resolveVersion());
305
+ const url = `${target.baseUrl}${versionedPath}`;
306
+ const credentialHeaders = credentials ? (0, import_data2.credentialToHeaders)(await credentials.get()) : {};
307
+ let headers = {
308
+ ...init.headers,
309
+ ...stripContentType(credentialHeaders),
310
+ ...stripContentType(target.policyHeaders ?? {})
311
+ };
312
+ const orgId = resolveOrganizationId();
313
+ if (orgId !== null) {
314
+ headers = applyOrganizationContextHeader(headers, orgId);
315
+ }
316
+ const info = {
317
+ url,
318
+ method: init.method,
319
+ path,
320
+ channel: target.channel ?? "default",
321
+ source
322
+ };
323
+ diagnostics?.onRequest?.(info);
324
+ let response;
325
+ try {
326
+ ({ response } = await fetchWithMatrxProtocolFallback(
327
+ url,
328
+ {
329
+ method: init.method,
330
+ headers,
331
+ ...init.body !== void 0 ? { body: init.body } : {}
332
+ },
333
+ {
334
+ ...init.signal ? { signal: init.signal } : {},
335
+ connectTimeoutMs,
336
+ totalTimeoutMs,
337
+ throwOnHttpError: false,
338
+ ...diagnostics?.onProtocolDowngrade ? { onDowngrade: diagnostics.onProtocolDowngrade } : {}
339
+ }
340
+ ));
341
+ } catch (err) {
342
+ diagnostics?.onError?.(normalizeMatrxError(err), info);
343
+ throw err;
344
+ }
345
+ if (!response.ok && !expectedErrorStatuses?.includes(response.status)) {
346
+ const serverDetail = await response.clone().json().catch(() => void 0);
347
+ const code = extractMatrxErrorCode(serverDetail);
348
+ diagnostics?.onError?.(
349
+ {
350
+ type: classifyStatus(response.status),
351
+ message: extractMatrxErrorMessage(serverDetail) ?? `HTTP ${response.status}`,
352
+ status: response.status,
353
+ serverDetail,
354
+ ...code ? { code } : {}
355
+ },
356
+ info
357
+ );
358
+ }
359
+ return response;
360
+ }
361
+ };
362
+ }
363
+
364
+ // matrx/internal.ts
365
+ async function readServerDetail(response) {
366
+ try {
367
+ return await response.json();
368
+ } catch {
369
+ return void 0;
370
+ }
371
+ }
372
+ async function throwApiError(path, response) {
373
+ throw new MatrxApiError({
374
+ status: response.status,
375
+ path,
376
+ serverDetail: await readServerDetail(response)
377
+ });
378
+ }
379
+ async function requestJson(transport, path, options) {
380
+ const hasBody = options.method !== "GET" && options.body !== void 0;
381
+ const response = await transport.fetch(path, {
382
+ method: options.method,
383
+ headers: hasBody ? { "Content-Type": "application/json" } : {},
384
+ ...hasBody ? { body: JSON.stringify(options.body) } : {},
385
+ ...options.signal ? { signal: options.signal } : {}
386
+ });
387
+ if (!response.ok) return throwApiError(path, response);
388
+ return await response.json();
389
+ }
390
+
391
+ // portable/mcp.ts
392
+ var AGENT_TOOLS_MCP_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
393
+ var AGENT_TOOLS_MCP_SERVER_NAME = "matrx-agent";
394
+ var SIGNED_OUT_TOOL_MESSAGE = "Sign in to AI Matrx to use this tool.";
395
+ var NO_ORGANIZATION_TOOL_MESSAGE = "Pick an organization in AI Matrx to use this tool.";
396
+ function isRecord2(value) {
397
+ return typeof value === "object" && value !== null && !Array.isArray(value);
398
+ }
399
+ function newId() {
400
+ return globalThis.crypto.randomUUID();
401
+ }
402
+ function toDescriptor(tool) {
403
+ const schema = isRecord2(tool.parameters) && tool.parameters.type === "object" ? tool.parameters : { type: "object", properties: {} };
404
+ return { name: tool.name, description: tool.description || tool.canonical_name, inputSchema: schema };
405
+ }
406
+ function rpcResult(id, result) {
407
+ return { jsonrpc: "2.0", id: id ?? null, result };
408
+ }
409
+ function rpcError(id, code, message) {
410
+ return { jsonrpc: "2.0", id: id ?? null, error: { code, message } };
411
+ }
412
+ function textResult(text, isError) {
413
+ return { content: [{ type: "text", text }], isError };
414
+ }
415
+ function createAgentToolsMcpHandler(options) {
416
+ const { bundle } = options;
417
+ const conversationId = options.conversationId ?? newId();
418
+ const descriptors = bundle.tools.map(toDescriptor);
419
+ const known = new Set(bundle.tools.map((tool) => tool.name));
420
+ const resolveOrganization = () => {
421
+ const raw = typeof options.organizationId === "function" ? options.organizationId() : options.organizationId;
422
+ return raw && raw.trim() ? raw.trim() : null;
423
+ };
424
+ const transportFor = (organizationId) => options.transport ?? createMatrxTransport({
425
+ baseUrl: options.baseUrl,
426
+ ...options.credentials ? { credentials: options.credentials } : {},
427
+ organizationId,
428
+ source: "agentToolsMcp"
429
+ });
430
+ async function callTool(id, params) {
431
+ if (!isRecord2(params) || typeof params.name !== "string") {
432
+ return rpcError(id, -32602, "tools/call needs a tool name.");
433
+ }
434
+ const name = params.name;
435
+ if (!known.has(name)) return rpcError(id, -32602, `Unknown tool: ${name}`);
436
+ const args = isRecord2(params.arguments) ? params.arguments : {};
437
+ const credential = options.credentials ? await options.credentials.get() : null;
438
+ if (!credential) return rpcResult(id, textResult(SIGNED_OUT_TOOL_MESSAGE, true));
439
+ const organizationId = resolveOrganization();
440
+ if (!organizationId) return rpcResult(id, textResult(NO_ORGANIZATION_TOOL_MESSAGE, true));
441
+ const callId = newId();
442
+ const pinned = typeof bundle.version_id === "string" && bundle.version_id.length > 0;
443
+ try {
444
+ const response = await requestJson(
445
+ transportFor(organizationId),
446
+ "/ai/tools/execute",
447
+ {
448
+ method: "POST",
449
+ body: {
450
+ agent_id: pinned ? bundle.version_id : bundle.agent_id,
451
+ is_version: pinned,
452
+ conversation_id: conversationId,
453
+ tool_name: name,
454
+ arguments: args,
455
+ call_id: callId,
456
+ surface: bundle.surface
457
+ }
458
+ }
459
+ );
460
+ options.onToolCall?.({ name, ok: response.ok, callId });
461
+ return rpcResult(id, textResult(response.output, !response.ok));
462
+ } catch (error) {
463
+ options.onToolCall?.({ name, ok: false, callId });
464
+ if (error instanceof MatrxApiError && error.status === 401) {
465
+ return rpcResult(id, textResult(SIGNED_OUT_TOOL_MESSAGE, true));
466
+ }
467
+ const message = error instanceof Error ? error.message : String(error);
468
+ return rpcResult(id, textResult(`AI Matrx could not run ${name}: ${message}`, true));
469
+ }
470
+ }
471
+ async function handleOne(message) {
472
+ if (!isRecord2(message) || typeof message.method !== "string") {
473
+ return rpcError(null, -32600, "Invalid request.");
474
+ }
475
+ const { id, params } = message;
476
+ const method = message.method;
477
+ const isNotification = id === void 0;
478
+ switch (method) {
479
+ case "initialize": {
480
+ const requested = isRecord2(params) ? params.protocolVersion : void 0;
481
+ const protocolVersion = typeof requested === "string" && AGENT_TOOLS_MCP_PROTOCOL_VERSIONS.includes(requested) ? requested : AGENT_TOOLS_MCP_PROTOCOL_VERSIONS[0];
482
+ return rpcResult(id, {
483
+ protocolVersion,
484
+ capabilities: { tools: { listChanged: false } },
485
+ serverInfo: { name: AGENT_TOOLS_MCP_SERVER_NAME, version: "1" },
486
+ instructions: `Tools of the AI Matrx agent "${bundle.name}". They run on AI Matrx as the signed-in person.`
487
+ });
488
+ }
489
+ case "ping":
490
+ return isNotification ? null : rpcResult(id, {});
491
+ case "tools/list":
492
+ return rpcResult(id, { tools: descriptors });
493
+ case "tools/call":
494
+ return callTool(id, params);
495
+ default:
496
+ if (isNotification) return null;
497
+ return rpcError(id, -32601, `Method not found: ${method}`);
498
+ }
499
+ }
500
+ return {
501
+ listTools: () => descriptors,
502
+ async handle(body) {
503
+ if (Array.isArray(body)) {
504
+ const replies = (await Promise.all(body.map(handleOne))).filter((r) => r !== null);
505
+ return replies.length ? { status: 200, body: replies } : { status: 202 };
506
+ }
507
+ const reply = await handleOne(body);
508
+ return reply === null ? { status: 202 } : { status: 200, body: reply };
509
+ }
510
+ };
511
+ }
512
+ //# sourceMappingURL=mcp.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../portable/mcp.ts","../../matrx/client.ts","../../matrx/org-context.ts","../../matrx/protocol.ts","../../matrx/transport.ts","../../matrx/internal.ts"],"sourcesContent":["/**\n * `@ai-matrx/agents/portable/mcp` — an agent's server tools as an MCP server.\n *\n * `createAgentToolsMcpHandler` answers MCP JSON-RPC (`initialize`,\n * `tools/list`, `tools/call`, `ping`) for ONE agent. `tools/list` is the\n * bundle's server tools (resolved by the realtime-tools funnel on the server);\n * `tools/call` runs the tool through `POST /ai/tools/execute`, which\n * re-resolves the agent's set and refuses anything outside it, and writes the\n * same `cx_tool_call` row a turn-based call writes.\n *\n * Every call reads the credential FRESH from the `CredentialsPort` and carries\n * `X-Organization-Id` — nothing is cached, and the token never leaves this\n * process (the CLI only ever sees a URL). Signed out, a call answers one plain\n * sentence instead of failing obscurely.\n *\n * Transport-neutral: the host feeds it the parsed JSON body of each HTTP POST\n * (MCP \"streamable HTTP\") and writes back what it returns. Pure: no Node, no\n * React, no I/O at import.\n */\n\nimport type { CredentialsPort } from \"@ai-matrx/data\";\n\nimport { createMatrxTransport } from \"../matrx/client\";\nimport { requestJson } from \"../matrx/internal\";\nimport type { MatrxTransport } from \"../matrx/transport\";\nimport { MatrxApiError } from \"../matrx/transport\";\nimport type { JsonValue, PortableAgentBundle, PortableTool } from \"./types.generated\";\n\n/** The MCP protocol revisions this handler speaks, newest first. */\nexport const AGENT_TOOLS_MCP_PROTOCOL_VERSIONS = [\"2025-06-18\", \"2025-03-26\", \"2024-11-05\"] as const;\n\n/** The server name the CLIs see (`mcp__matrx-agent__<tool>` in Claude Code). */\nexport const AGENT_TOOLS_MCP_SERVER_NAME = \"matrx-agent\";\n\n/** What a signed-out tool call answers. */\nexport const SIGNED_OUT_TOOL_MESSAGE = \"Sign in to AI Matrx to use this tool.\";\n/** What a call with no organization answers. */\nexport const NO_ORGANIZATION_TOOL_MESSAGE = \"Pick an organization in AI Matrx to use this tool.\";\n\nexport interface AgentToolsMcpOptions {\n /** The bundle the session loaded — its `tools`, agent/version identity and `surface`. */\n bundle: Pick<PortableAgentBundle, \"agent_id\" | \"version_id\" | \"name\" | \"tools\" | \"surface\">;\n /** The credential source, read fresh per call. `null`/absent = signed out. */\n credentials?: CredentialsPort | null;\n /** The organization every call runs in (value or per-call getter). */\n organizationId?: string | null | (() => string | null | undefined);\n /** AI Matrx server base URL, no trailing slash. */\n baseUrl: string;\n /**\n * One conversation id for the whole coding session, so its tool calls group\n * under one `cx_conversation`. Default: a fresh id per handler.\n */\n conversationId?: string;\n /** Test seam: replaces the transport built from the options above. */\n transport?: MatrxTransport;\n /** Every tool call's outcome, for the host's transcript or logs. */\n onToolCall?: (event: { name: string; ok: boolean; callId: string }) => void;\n}\n\n/** A JSON-RPC message, structurally. */\nexport interface McpJsonRpcMessage {\n jsonrpc?: string;\n id?: string | number | null;\n method?: string;\n params?: unknown;\n}\n\n/** What the host writes back: HTTP status, plus a JSON body when there is one. */\nexport interface McpHttpReply {\n status: number;\n body?: unknown;\n}\n\nexport interface AgentToolsMcpHandler {\n /** Handle one parsed HTTP POST body (a message or a batch). */\n handle(body: unknown): Promise<McpHttpReply>;\n /** The tools `tools/list` returns, in MCP shape. */\n listTools(): McpToolDescriptor[];\n}\n\nexport interface McpToolDescriptor {\n name: string;\n description: string;\n inputSchema: Record<string, JsonValue>;\n}\n\ninterface ToolExecuteResponse {\n call_id: string;\n ok: boolean;\n output: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction newId(): string {\n return globalThis.crypto.randomUUID();\n}\n\nfunction toDescriptor(tool: PortableTool): McpToolDescriptor {\n const schema = isRecord(tool.parameters) && tool.parameters.type === \"object\"\n ? tool.parameters\n : { type: \"object\", properties: {} };\n return { name: tool.name, description: tool.description || tool.canonical_name, inputSchema: schema };\n}\n\nfunction rpcResult(id: McpJsonRpcMessage[\"id\"], result: unknown): unknown {\n return { jsonrpc: \"2.0\", id: id ?? null, result };\n}\n\nfunction rpcError(id: McpJsonRpcMessage[\"id\"], code: number, message: string): unknown {\n return { jsonrpc: \"2.0\", id: id ?? null, error: { code, message } };\n}\n\nfunction textResult(text: string, isError: boolean): unknown {\n return { content: [{ type: \"text\", text }], isError };\n}\n\nexport function createAgentToolsMcpHandler(options: AgentToolsMcpOptions): AgentToolsMcpHandler {\n const { bundle } = options;\n const conversationId = options.conversationId ?? newId();\n const descriptors = bundle.tools.map(toDescriptor);\n const known = new Set(bundle.tools.map((tool) => tool.name));\n\n const resolveOrganization = (): string | null => {\n const raw = typeof options.organizationId === \"function\"\n ? options.organizationId()\n : options.organizationId;\n return raw && raw.trim() ? raw.trim() : null;\n };\n\n const transportFor = (organizationId: string): MatrxTransport =>\n options.transport ??\n createMatrxTransport({\n baseUrl: options.baseUrl,\n ...(options.credentials ? { credentials: options.credentials } : {}),\n organizationId,\n source: \"agentToolsMcp\",\n });\n\n async function callTool(id: McpJsonRpcMessage[\"id\"], params: unknown): Promise<unknown> {\n if (!isRecord(params) || typeof params.name !== \"string\") {\n return rpcError(id, -32602, \"tools/call needs a tool name.\");\n }\n const name = params.name;\n if (!known.has(name)) return rpcError(id, -32602, `Unknown tool: ${name}`);\n const args = isRecord(params.arguments) ? params.arguments : {};\n\n const credential = options.credentials ? await options.credentials.get() : null;\n if (!credential) return rpcResult(id, textResult(SIGNED_OUT_TOOL_MESSAGE, true));\n const organizationId = resolveOrganization();\n if (!organizationId) return rpcResult(id, textResult(NO_ORGANIZATION_TOOL_MESSAGE, true));\n\n const callId = newId();\n const pinned = typeof bundle.version_id === \"string\" && bundle.version_id.length > 0;\n try {\n const response = await requestJson<ToolExecuteResponse>(\n transportFor(organizationId),\n \"/ai/tools/execute\",\n {\n method: \"POST\",\n body: {\n agent_id: pinned ? bundle.version_id : bundle.agent_id,\n is_version: pinned,\n conversation_id: conversationId,\n tool_name: name,\n arguments: args,\n call_id: callId,\n surface: bundle.surface,\n },\n },\n );\n options.onToolCall?.({ name, ok: response.ok, callId });\n return rpcResult(id, textResult(response.output, !response.ok));\n } catch (error) {\n options.onToolCall?.({ name, ok: false, callId });\n if (error instanceof MatrxApiError && error.status === 401) {\n return rpcResult(id, textResult(SIGNED_OUT_TOOL_MESSAGE, true));\n }\n const message = error instanceof Error ? error.message : String(error);\n return rpcResult(id, textResult(`AI Matrx could not run ${name}: ${message}`, true));\n }\n }\n\n async function handleOne(message: unknown): Promise<unknown | null> {\n if (!isRecord(message) || typeof message.method !== \"string\") {\n return rpcError(null, -32600, \"Invalid request.\");\n }\n const { id, params } = message as unknown as McpJsonRpcMessage;\n const method = message.method;\n const isNotification = id === undefined;\n switch (method) {\n case \"initialize\": {\n const requested = isRecord(params) ? params.protocolVersion : undefined;\n const protocolVersion =\n typeof requested === \"string\" &&\n (AGENT_TOOLS_MCP_PROTOCOL_VERSIONS as readonly string[]).includes(requested)\n ? requested\n : AGENT_TOOLS_MCP_PROTOCOL_VERSIONS[0];\n return rpcResult(id, {\n protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: { name: AGENT_TOOLS_MCP_SERVER_NAME, version: \"1\" },\n instructions: `Tools of the AI Matrx agent \"${bundle.name}\". They run on AI Matrx as the signed-in person.`,\n });\n }\n case \"ping\":\n return isNotification ? null : rpcResult(id, {});\n case \"tools/list\":\n return rpcResult(id, { tools: descriptors });\n case \"tools/call\":\n return callTool(id, params);\n default:\n if (isNotification) return null; // notifications/initialized and friends\n return rpcError(id, -32601, `Method not found: ${method}`);\n }\n }\n\n return {\n listTools: () => descriptors,\n async handle(body) {\n if (Array.isArray(body)) {\n const replies = (await Promise.all(body.map(handleOne))).filter((r) => r !== null);\n return replies.length ? { status: 200, body: replies } : { status: 202 };\n }\n const reply = await handleOne(body);\n return reply === null ? { status: 202 } : { status: 200, body: reply };\n },\n };\n}\n","/**\n * The PRODUCTION `MatrxTransport` — the full connection pipeline every Matrx\n * host used to hand-roll, moved in under C22 (THE HARD PARTS LIVE IN THE\n * PACKAGE). A host constructs it from identity alone:\n *\n * ```ts\n * const transport = createMatrxTransport({\n * baseUrl: \"https://server.app.matrxserver.com\",\n * credentials, // CredentialsPort (@ai-matrx/data)\n * organizationId: () => activeOrgId, // omit for conversation-lane calls\n * });\n * ```\n *\n * Everything else is defaulted to the proven production values:\n *\n * - **timeouts** — connect 15s (for a non-streaming FastAPI handler this is\n * effectively time-to-response), total UNCAPPED (the port cannot tell a JSON\n * call from a long-lived NDJSON/SSE stream; the connect timeout is the JSON\n * guard), via `@ai-matrx/data/net`'s `resilientFetch`;\n * - **protocol** — the AI API version transform (`applyAiApiVersion`, default\n * v2) + the loud v2 → v1 transport fallback (`./protocol`);\n * - **credentials** — read fresh from the injected `CredentialsPort` on EVERY\n * call, so a token refresh mid-run is picked up; mapped to headers by the\n * ONE `credentialToHeaders`;\n * - **org context** — the fail-closed `X-Organization-Id` binding\n * (`./org-context`): configured lanes REQUIRE an org and refuse before the\n * wire; unconfigured lanes (conversation-scoped calls, which carry org in\n * the body) send none;\n * - **error classification** — every failure normalizes through\n * `normalizeMatrxError` into the ONE `MatrxCallError` envelope;\n * - **diagnostics** — a typed sink the host wires to its capture/telemetry\n * (`onRequest`, `onError`, `onProtocolDowngrade`); wiring it is optional,\n * the transport works silently without it.\n *\n * Header merge order is part of the port contract: wire headers first\n * (`Content-Type` / `Accept` / `Last-Event-ID` — the package's), then\n * credentials, then resolver policy headers, then the org header. Policy\n * headers never carry `Content-Type` — the wire owns it, and a policy\n * `Content-Type` merged over a GET SSE call would corrupt the wire, so the\n * factory strips it defensively.\n */\n\nimport { isNetError, type CredentialsPort } from \"@ai-matrx/data\";\nimport { credentialToHeaders } from \"@ai-matrx/data\";\nimport {\n applyOrganizationContextHeader,\n OrganizationContextError,\n requireOrganizationContext,\n} from \"./org-context\";\nimport {\n applyAiApiVersion,\n fetchWithMatrxProtocolFallback,\n MATRX_AI_API_VERSION_DEFAULT,\n type MatrxAiApiVersion,\n type MatrxProtocolDowngrade,\n} from \"./protocol\";\nimport {\n extractMatrxErrorCode,\n extractMatrxErrorMessage,\n MatrxApiError,\n type MatrxTransport,\n type MatrxTransportRequest,\n} from \"./transport\";\n\n// ─── The normalized error envelope ──────────────────────────────────────────\n\n/**\n * The ONE classified error shape for Matrx client calls — the envelope hosts\n * branch on instead of string-matching exceptions. Structurally compatible\n * with matrx-frontend's `ApiCallError` by design.\n */\nexport interface MatrxCallError {\n type:\n | \"auth_error\"\n | \"network_error\"\n | \"http_error\"\n | \"validation_error\"\n | \"abort_error\"\n | \"unknown\";\n message: string;\n /** HTTP status code, if applicable. */\n status?: number;\n /** Raw error detail from the server (the parsed error body). */\n serverDetail?: unknown;\n /** Machine code preserved through normalization (server `code`, org-context code, …). */\n code?: string;\n /** Original exception identity for diagnostics. */\n name?: string;\n /** Original exception stack. */\n stack?: string;\n}\n\nfunction classifyStatus(status: number): \"validation_error\" | \"http_error\" {\n return status >= 400 && status < 500 ? \"validation_error\" : \"http_error\";\n}\n\n/**\n * Classify any failure thrown by a package client call — `MatrxApiError`,\n * a `NetError` from the resilience layer, an org-context refusal, an abort —\n * into the `MatrxCallError` envelope. Never throws.\n */\nexport function normalizeMatrxError(err: unknown): MatrxCallError {\n if (err instanceof MatrxApiError) {\n return {\n type: classifyStatus(err.status),\n message: err.message,\n status: err.status,\n serverDetail: err.serverDetail,\n ...(err.code ? { code: err.code } : {}),\n name: err.name,\n };\n }\n\n if (err instanceof OrganizationContextError) {\n return {\n type: \"validation_error\",\n message: err.message,\n code: err.code,\n name: err.name,\n ...(err.stack !== undefined ? { stack: err.stack } : {}),\n };\n }\n\n if (err instanceof DOMException && err.name === \"AbortError\") {\n return { type: \"abort_error\", message: \"Request was cancelled.\" };\n }\n\n if (isNetError(err)) {\n if (err.code === \"aborted\") {\n return { type: \"abort_error\", message: err.message };\n }\n if (err.code === \"http\") {\n const status = err.status ?? 0;\n return { type: classifyStatus(status), message: err.message, status };\n }\n // connect-timeout / total-timeout / heartbeat-timeout / network / offline\n return { type: \"network_error\", message: err.message };\n }\n\n if (err instanceof Error) {\n const httpMatch = err.message.match(/HTTP (\\d+):\\s*(.*)/);\n if (httpMatch) {\n const status = parseInt(httpMatch[1] as string, 10);\n return {\n type: classifyStatus(status),\n message: httpMatch[2] ?? err.message,\n status,\n };\n }\n return { type: \"network_error\", message: err.message };\n }\n\n return { type: \"unknown\", message: String(err ?? \"Unknown error\") };\n}\n\n// ─── The factory ────────────────────────────────────────────────────────────\n\n/**\n * A fully-resolved connection target for one call: where to send it and which\n * policy headers ride ON TOP of the wire + credential headers.\n */\nexport interface MatrxTransportTarget {\n /** Fully-qualified base URL, no trailing slash. */\n baseUrl: string;\n /**\n * Extra policy headers for this target (e.g. a resolver that carries its own\n * credential headers). `Content-Type` is stripped — the wire owns it.\n */\n policyHeaders?: Record<string, string>;\n /** Routing channel label surfaced to `onRequest` telemetry. */\n channel?: string;\n}\n\n/** Context handed to every diagnostics callback. */\nexport interface MatrxRequestInfo {\n /** The final URL (base + version-transformed path). */\n url: string;\n method: \"GET\" | \"POST\";\n /** The server-relative path as the package requested it. */\n path: string;\n /** The resolved routing channel (default \"default\"). */\n channel: string;\n /** The transport's call-site label (default \"matrxTransport\"). */\n source: string;\n}\n\n/**\n * The typed diagnostics sink — the host wires these to its telemetry/capture\n * systems; all optional, and the transport is fully functional without them.\n */\nexport interface MatrxTransportDiagnostics {\n /** Fired at the last pre-fetch moment of every call. */\n onRequest?: (info: MatrxRequestInfo) => void;\n /**\n * Fired for every thrown network failure and every non-2xx response not\n * listed in `expectedErrorStatuses`, with the classified envelope.\n */\n onError?: (error: MatrxCallError, info: MatrxRequestInfo) => void;\n /** Fired on every v2 → v1 protocol downgrade. */\n onProtocolDowngrade?: (downgrade: MatrxProtocolDowngrade) => void;\n}\n\nexport interface CreateMatrxTransportOptions {\n /** Fixed base URL, no trailing slash. Exactly one of `baseUrl` / `resolveTarget`. */\n baseUrl?: string;\n /**\n * Per-call target resolver — for hosts whose base URL / policy headers are\n * dynamic (server toggles, sandbox overrides, conversation channels).\n * Resolution runs fresh on EVERY call. May throw to refuse a call loudly.\n */\n resolveTarget?: () => MatrxTransportTarget;\n /**\n * The credential source (`@ai-matrx/data`), read fresh per call so token\n * refreshes are picked up mid-run. Omit only when the resolver's\n * `policyHeaders` already carry the credentials.\n */\n credentials?: CredentialsPort;\n /**\n * The org-context binding. When configured, every call REQUIRES a valid org\n * (fail-closed `organization_context_required` before the wire) and carries\n * `X-Organization-Id`. Omit for conversation-lane transports, which send the\n * org in the body only.\n */\n organizationId?: string | (() => string | null | undefined);\n /** AI API protocol version (value or per-call getter). Default `\"v2\"`. */\n aiApiVersion?: MatrxAiApiVersion | (() => MatrxAiApiVersion);\n /** Max ms request start → response headers. Default 15_000. */\n connectTimeoutMs?: number;\n /**\n * Max ms for the whole handshake. Default `null` (uncapped) — the port\n * cannot tell a JSON call from a long-lived stream, and capping would kill\n * long streams; the connect timeout is the real JSON guard.\n */\n totalTimeoutMs?: number | null;\n /**\n * HTTP failures this transport's call class fully handles as expected\n * domain outcomes (e.g. 404 on runtime-operation identify). They still\n * reach the package client (which maps them to typed results) but are not\n * reported through `onError`.\n */\n expectedErrorStatuses?: readonly number[];\n /** Short call-site label surfaced on `MatrxRequestInfo` (default \"matrxTransport\"). */\n source?: string;\n diagnostics?: MatrxTransportDiagnostics;\n}\n\nconst PRODUCTION_CONNECT_TIMEOUT_MS = 15_000;\n\nfunction stripContentType(\n headers: Record<string, string>,\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(headers).filter(\n ([name]) => name.toLowerCase() !== \"content-type\",\n ),\n );\n}\n\n/**\n * Build the production `MatrxTransport`. See the module doc for the pipeline;\n * every knob defaults to the proven production value.\n */\nexport function createMatrxTransport(\n options: CreateMatrxTransportOptions,\n): MatrxTransport {\n const {\n baseUrl,\n resolveTarget,\n credentials,\n organizationId,\n aiApiVersion,\n connectTimeoutMs = PRODUCTION_CONNECT_TIMEOUT_MS,\n totalTimeoutMs = null,\n expectedErrorStatuses,\n diagnostics,\n source = \"matrxTransport\",\n } = options;\n\n if ((baseUrl === undefined) === (resolveTarget === undefined)) {\n throw new Error(\n \"createMatrxTransport: provide exactly one of `baseUrl` or `resolveTarget`.\",\n );\n }\n\n const resolve: () => MatrxTransportTarget =\n resolveTarget ?? (() => ({ baseUrl: baseUrl as string }));\n\n const resolveVersion = (): MatrxAiApiVersion => {\n if (aiApiVersion === undefined) return MATRX_AI_API_VERSION_DEFAULT;\n return typeof aiApiVersion === \"function\" ? aiApiVersion() : aiApiVersion;\n };\n\n const resolveOrganizationId = (): string | null => {\n if (organizationId === undefined) return null;\n const candidate =\n typeof organizationId === \"function\" ? organizationId() : organizationId;\n // Fail closed: a configured org lane with no org refuses before the wire.\n return requireOrganizationContext(candidate);\n };\n\n return {\n async fetch(path: string, init: MatrxTransportRequest): Promise<Response> {\n const target = resolve();\n\n // `path` is already interpolated (`/ai/agents/<uuid>`), so the version\n // transform is the concrete-path bridge, not a template registry.\n const versionedPath = applyAiApiVersion(path, resolveVersion());\n const url = `${target.baseUrl}${versionedPath}`;\n\n // Wire headers FIRST; credentials, then resolver policy headers, then\n // the org header on top — none of them may carry Content-Type.\n const credentialHeaders = credentials\n ? credentialToHeaders(await credentials.get())\n : {};\n let headers: Record<string, string> = {\n ...init.headers,\n ...stripContentType(credentialHeaders),\n ...stripContentType(target.policyHeaders ?? {}),\n };\n const orgId = resolveOrganizationId();\n if (orgId !== null) {\n headers = applyOrganizationContextHeader(headers, orgId);\n }\n\n const info: MatrxRequestInfo = {\n url,\n method: init.method,\n path,\n channel: target.channel ?? \"default\",\n source,\n };\n diagnostics?.onRequest?.(info);\n\n let response: Response;\n try {\n ({ response } = await fetchWithMatrxProtocolFallback(\n url,\n {\n method: init.method,\n headers,\n ...(init.body !== undefined ? { body: init.body } : {}),\n },\n {\n ...(init.signal ? { signal: init.signal } : {}),\n connectTimeoutMs,\n totalTimeoutMs,\n throwOnHttpError: false,\n ...(diagnostics?.onProtocolDowngrade\n ? { onDowngrade: diagnostics.onProtocolDowngrade }\n : {}),\n },\n ));\n } catch (err) {\n diagnostics?.onError?.(normalizeMatrxError(err), info);\n throw err;\n }\n\n if (!response.ok && !expectedErrorStatuses?.includes(response.status)) {\n // The package client consumes the original body for its\n // MatrxApiError; read the diagnostics copy from a clone so the two\n // never fight.\n const serverDetail: unknown = await response\n .clone()\n .json()\n .catch(() => undefined);\n const code = extractMatrxErrorCode(serverDetail);\n diagnostics?.onError?.(\n {\n type: classifyStatus(response.status),\n message:\n extractMatrxErrorMessage(serverDetail) ??\n `HTTP ${response.status}`,\n status: response.status,\n serverDetail,\n ...(code ? { code } : {}),\n },\n info,\n );\n }\n\n return response;\n },\n };\n}\n","import { isUuidShape } from \"@ai-matrx/kit/uuid\";\n\n/**\n * The fail-closed organization-context kernel — ONE implementation for every\n * Matrx client transport (moved in from matrx-frontend\n * `lib/api/organization-context.ts` verbatim under C22; the host module is now\n * a re-export of this one).\n *\n * Transports resolve their authoritative organization first, then use these\n * functions to bind that exact value without guessing or defaulting. The\n * server never manufactures an org (it 422s a blank one), so the client\n * refuses before the wire: a missing or malformed org id throws\n * `OrganizationContextError` instead of sending a request that cannot succeed.\n */\n\nexport type OrganizationContextErrorCode =\n | \"organization_context_required\"\n | \"organization_context_invalid\"\n | \"organization_context_mismatch\";\n\nexport class OrganizationContextError extends Error {\n readonly code: OrganizationContextErrorCode;\n\n constructor(code: OrganizationContextErrorCode, message: string) {\n super(message);\n this.name = \"OrganizationContextError\";\n this.code = code;\n }\n}\n\ndeclare const organizationOperationBrand: unique symbol;\n\n/** A validated organization operation; construct only through the factory. */\nexport type OrganizationOperation = Readonly<{\n organization_id: string;\n readonly [organizationOperationBrand]: true;\n}>;\n\nexport function createOrganizationOperation(\n organizationId: string,\n): OrganizationOperation {\n const organization_id = requireOrganizationContext(organizationId);\n return Object.freeze({ organization_id }) as OrganizationOperation;\n}\n\nexport function assertOrganizationMatchesOperation(\n operation: OrganizationOperation,\n organizationId: string,\n): void {\n if (operation.organization_id !== requireOrganizationContext(organizationId)) {\n throw new OrganizationContextError(\n \"organization_context_mismatch\",\n \"Organization ID must match the request operation.\",\n );\n }\n}\n\n/**\n * Normalize and validate the effective organization id for a request. The\n * override (an explicit per-call value) beats the selected context value.\n * Throws `organization_context_required` when neither is present and\n * `organization_context_invalid` when the candidate is not a UUID.\n */\nexport function requireOrganizationContext(\n selectedOrganizationId: string | null | undefined,\n overrideOrganizationId?: string,\n): string {\n const candidate = overrideOrganizationId ?? selectedOrganizationId;\n if (typeof candidate !== \"string\" || candidate.trim().length === 0) {\n throw new OrganizationContextError(\n \"organization_context_required\",\n \"Select an organization before sending this request.\",\n );\n }\n\n const normalized = candidate.trim();\n if (!isUuidShape(normalized)) {\n throw new OrganizationContextError(\n \"organization_context_invalid\",\n \"The selected organization ID is invalid.\",\n );\n }\n return normalized.toLowerCase();\n}\n\n/**\n * Bind `X-Organization-Id` onto a header bag. A pre-existing org header that\n * disagrees with the context org is a `organization_context_mismatch` error —\n * never silently overwritten in either direction.\n */\nexport function applyOrganizationContextHeader(\n headers: Record<string, string>,\n organizationId: string,\n): Record<string, string> {\n const normalizedOrganizationId = requireOrganizationContext(organizationId);\n for (const [name, value] of Object.entries(headers)) {\n if (\n name.toLowerCase() === \"x-organization-id\" &&\n value.trim().toLowerCase() !== normalizedOrganizationId\n ) {\n throw new OrganizationContextError(\n \"organization_context_mismatch\",\n \"X-Organization-Id must match the request context organization.\",\n );\n }\n }\n const withoutOrganizationHeader = Object.fromEntries(\n Object.entries(headers).filter(\n ([name]) => name.toLowerCase() !== \"x-organization-id\",\n ),\n );\n return {\n ...withoutOrganizationHeader,\n \"X-Organization-Id\": normalizedOrganizationId,\n };\n}\n\n/**\n * Assert that an `organization_id` query parameter (when present) matches the\n * request context organization — the query string must never smuggle a\n * different org past the header binding.\n */\nexport function assertQueryOrganizationMatchesContext(\n queryParams: Record<string, string | number | boolean> | undefined,\n organizationId: string,\n): void {\n if (!queryParams || queryParams.organization_id === undefined) return;\n const queryOrganizationId = requireOrganizationContext(\n String(queryParams.organization_id),\n );\n if (queryOrganizationId !== requireOrganizationContext(organizationId)) {\n throw new OrganizationContextError(\n \"organization_context_mismatch\",\n \"Query organization_id must match the request context organization.\",\n );\n }\n}\n","/**\n * The AI API protocol-version policy — which version of the AI runtime a\n * Matrx client talks to, and the v2 → v1 transport fallback (moved in from\n * matrx-frontend `lib/api/ai-api-version.ts` + `call-api.ts::\n * fetchWithV2Fallback` under C22; server truth\n * `aidream/docs/runtime/V2_FRONTEND_MIGRATION.md`).\n *\n * Background: the Python backend exposes a `/v2` runtime-spine namespace that\n * wraps the core AI request surfaces in a request-tracking envelope. Body,\n * headers, and streaming response are BYTE-IDENTICAL to v1 — only the URL\n * differs.\n *\n * ─── The one rule that keeps burning us ─────────────────────────────────────\n * `/v2` is inserted at the FRONT of the in-app path, right before `/ai`:\n *\n * /ai/agents/{id} → /v2/ai/agents/{id} ✅ correct\n * /ai/v2/agents/… ❌ WRONG (nested) — 404s\n *\n * `toV2Path` below is the ONLY place this transform is spelled out.\n *\n * ─── Scope: ONLY the covered surfaces have a v2 form ────────────────────────\n * chat, manual, agents/{id}, conversations/{id} (+ singular aliases),\n * prompts/{id}, mandates/{key}. EVERYTHING ELSE — cancel, warm, resume,\n * fork-and-run, runtime operations, files … — has NO v2 route, and the server\n * does NOT auto-downgrade (a `/v2` request to an uncovered surface is a plain\n * 404). So the transform is a scoped allowlist, never a blanket prefix.\n */\n\nimport {\n isNetError,\n resilientFetch,\n type ResilientFetchOptions,\n} from \"@ai-matrx/data/net\";\n\nexport type MatrxAiApiVersion = \"v1\" | \"v2\";\n\n/**\n * The package-wide default AI API version — the production value every Matrx\n * client runs unless its host deliberately overrides\n * (`createMatrxTransport({ aiApiVersion })`).\n */\nexport const MATRX_AI_API_VERSION_DEFAULT: MatrxAiApiVersion = \"v2\";\n\n/**\n * The canonical v1 path TEMPLATES the v2 spine covers, `{param}` placeholders\n * intact — for hosts that route through a template registry.\n */\nexport const V2_COVERED_AI_PATH_TEMPLATES = [\n \"/ai/manual\",\n \"/ai/chat\",\n \"/ai/agents/{agent_id}\",\n \"/ai/agent/{agent_id}\", // singular alias — behaves identically\n \"/ai/conversations/{conversation_id}\",\n \"/ai/conversation/{conversation_id}\", // singular alias\n \"/ai/prompts/{prompt_id}\", // saved-prompt execution\n \"/ai/mandates/{mandate_key}\", // THE MANDATE DOOR — `/v2` sibling exists (routers/v2.py)\n] as const;\n\n/**\n * Insert `/v2` at the front of an in-app path. Idempotent, and prefix-aware:\n * a legacy `/api/` compatibility prefix (stripped server-side) is preserved so\n * `/api/ai/chat` → `/api/v2/ai/chat`.\n */\nexport function toV2Path(path: string): string {\n const withLead = path.startsWith(\"/\") ? path : `/${path}`;\n if (withLead.startsWith(\"/api/\")) {\n const rest = withLead.slice(\"/api\".length); // \"/ai/chat\"\n return rest.startsWith(\"/v2/\") ? withLead : `/api/v2${rest}`;\n }\n return withLead.startsWith(\"/v2/\") ? withLead : `/v2${withLead}`;\n}\n\n// Interpolated (concrete) forms of the covered surfaces — used to guard\n// callers that pass a real path (id already substituted). Anchored so ONLY the\n// exact shapes match: sub-paths like `/ai/agents/{id}/warm`,\n// `/ai/conversations/{id}/resume`, and `/ai/cancel/{id}` deliberately do NOT\n// match and stay on v1. The optional `/api` prefix mirrors `toV2Path`.\nconst COVERED_INTERPOLATED_PATH = [\n /^(?:\\/api)?\\/ai\\/manual$/,\n /^(?:\\/api)?\\/ai\\/chat$/,\n /^(?:\\/api)?\\/ai\\/agents\\/[^/]+$/,\n /^(?:\\/api)?\\/ai\\/agent\\/[^/]+$/,\n /^(?:\\/api)?\\/ai\\/conversations\\/[^/]+$/,\n /^(?:\\/api)?\\/ai\\/conversation\\/[^/]+$/,\n /^(?:\\/api)?\\/ai\\/prompts\\/[^/]+$/, // `/warm` etc. deliberately don't match\n /^(?:\\/api)?\\/ai\\/mandates\\/[^/]+$/, // the mandate door\n];\n\n/** Whether `path` (already interpolated) is one of the covered surfaces. */\nexport function isCoveredAiPath(path: string): boolean {\n return COVERED_INTERPOLATED_PATH.some((re) => re.test(path));\n}\n\n/**\n * Whether an in-app path (or a full URL whose path was built by `toV2Path`)\n * targets the v2 namespace — the guard the downgrade fallback keys off.\n */\nexport function isV2Path(pathOrUrl: string): boolean {\n return /\\/v2\\/ai\\//.test(pathOrUrl);\n}\n\n/**\n * The inverse of `toV2Path` — strip the `/v2` version segment so a transport\n * failure of the v2 endpoint (network error, 404/405, 5xx BEFORE any stream\n * content) can retry the identical request on the v1 route. Works on a bare\n * path, an `/api`-prefixed path, or a full URL (the `/v2/ai/` shape is unique\n * to the version namespace). Idempotent on non-v2 input.\n */\nexport function toV1FallbackUrl(url: string): string {\n return url.replace(/\\/v2\\/ai\\//, \"/ai/\");\n}\n\n/**\n * Apply the active AI API version to an ALREADY-INTERPOLATED in-app path.\n *\n * - Covered surface + v2 → `/v2` prefix inserted.\n * - Anything else (or v1) → returned unchanged.\n *\n * Pass the in-app PATH only (no scheme/host); prepend the base URL afterward.\n */\nexport function applyAiApiVersion(\n path: string,\n version: MatrxAiApiVersion,\n): string {\n if (version !== \"v2\") return path;\n return isCoveredAiPath(path) ? toV2Path(path) : path;\n}\n\n/** One v2 → v1 downgrade, surfaced to the host's diagnostics sink. */\nexport interface MatrxProtocolDowngrade {\n /** The failed v2 URL. */\n url: string;\n /** Why the downgrade fired (thrown error text, or `HTTP <status>`). */\n reason: string;\n /** HTTP status when the trigger was a response (404/405/5xx). */\n status?: number;\n}\n\nexport interface MatrxProtocolFallbackOptions extends ResilientFetchOptions {\n /**\n * Fired on every downgrade — a sustained stream of these means a v2 surface\n * is unhealthy. The fallback also `console.warn`s unconditionally (parity\n * with the original host pipeline) so the signal never disappears silently.\n */\n onDowngrade?: (downgrade: MatrxProtocolDowngrade) => void;\n}\n\n/**\n * `resilientFetch` with the v2 → v1 transport fallback. Fires ONLY when a\n * `/v2/ai/...` ENDPOINT itself fails — a network-layer throw (non-abort), a\n * 404/405 (surface not on v2), or a 5xx — always BEFORE any stream content is\n * consumed. Never on an application error (those fail identically on v1), and\n * never on a caller abort (a user cancel must not be logged as a downgrade —\n * that poisons the exact telemetry the rollout reads to judge v2 health).\n */\nexport async function fetchWithMatrxProtocolFallback(\n url: string,\n init: RequestInit,\n opts: MatrxProtocolFallbackOptions = {},\n): Promise<{ response: Response }> {\n const { onDowngrade, ...fetchOpts } = opts;\n const logDowngrade = (reason: string, status?: number) => {\n console.warn(\n `[matrx] ai_v2_downgrade → retrying on v1. v2=${url} reason=${reason}`,\n );\n onDowngrade?.({ url, reason, ...(status !== undefined ? { status } : {}) });\n };\n if (!isV2Path(url)) return resilientFetch(url, init, fetchOpts);\n let result: { response: Response };\n try {\n result = await resilientFetch(url, init, fetchOpts);\n } catch (err) {\n // resilientFetch normalizes a caller-signal abort to NetError code\n // \"aborted\" (AbortedError); a raw AbortError is checked too for safety.\n const isAbort =\n (isNetError(err) && err.code === \"aborted\") ||\n (err instanceof Error && err.name === \"AbortError\");\n if (isAbort) throw err;\n logDowngrade(String(err));\n return resilientFetch(toV1FallbackUrl(url), init, fetchOpts);\n }\n const status = result.response.status;\n if (status === 404 || status === 405 || status >= 500) {\n logDowngrade(`HTTP ${status}`, status);\n return resilientFetch(toV1FallbackUrl(url), init, fetchOpts);\n }\n return result;\n}\n","/**\n * `@ai-matrx/agents/matrx` — the Matrx transport port.\n *\n * The ONE seam between this package's wire semantics and a host's connection\n * policy. This package owns WHAT is said to the AI Matrx server — paths,\n * methods, JSON bodies, streaming Accept headers, the `Last-Event-ID` cursor\n * header — and the host owns HOW the connection is made:\n *\n * - base-URL / backend-channel resolution (global, sandbox override, local\n * engine, EC2-dedicated — whatever ladder the host runs);\n * - credentials (Supabase JWT `Authorization: Bearer`, guest\n * `X-Fingerprint-ID`, or the API-key lane) — NEVER implemented here;\n * - the `X-Organization-Id` context header;\n * - retry policy, network-level timeouts, and diagnostics capture.\n *\n * A host implements the port in a few lines:\n *\n * ```ts\n * const transport: MatrxTransport = {\n * fetch: (path, init) =>\n * fetch(`${baseUrl}${path}`, {\n * ...init,\n * headers: { ...init.headers, ...authHeaders() },\n * }),\n * };\n * ```\n *\n * The port is deliberately structural and `fetch`-shaped so `@ai-matrx/data`'s\n * `/api` transport can implement it without importing this package.\n */\n\n/**\n * The request this package hands the port. A strict subset of `RequestInit`,\n * so a host can spread it straight into `fetch`.\n */\nexport interface MatrxTransportRequest {\n method: \"GET\" | \"POST\";\n /**\n * Wire-semantic headers the CALL requires (`Content-Type`, `Accept`,\n * `Last-Event-ID`). The host merges its policy headers (auth, org) on top;\n * it must not drop these.\n */\n headers: Record<string, string>;\n /** Pre-serialized JSON body, present on POST calls that carry one. */\n body?: string;\n /** Caller cancellation. The host must wire it to the underlying fetch. */\n signal?: AbortSignal;\n}\n\n/**\n * The transport port. `path` is server-relative and always starts with `/`\n * (`/ai/...`, `/runtime/...`); the host prepends its resolved base URL.\n */\nexport interface MatrxTransport {\n fetch(path: string, init: MatrxTransportRequest): Promise<Response>;\n}\n\n/**\n * A non-2xx response from the Matrx API, with the server's structured error\n * body preserved and its richest human-readable message extracted.\n */\nexport class MatrxApiError extends Error {\n override readonly name = \"MatrxApiError\";\n /** HTTP status of the failed response. */\n readonly status: number;\n /** Machine code from the server body (`code`, or `detail.code`), when present. */\n readonly code: string | null;\n /** The parsed server error body, verbatim (undefined when unparsable). */\n readonly serverDetail: unknown;\n /** The request path the failure came from (server-relative). */\n readonly path: string;\n\n constructor(args: {\n status: number;\n path: string;\n serverDetail?: unknown;\n message?: string;\n }) {\n super(\n args.message ??\n extractMatrxErrorMessage(args.serverDetail) ??\n `HTTP ${args.status}`,\n );\n this.status = args.status;\n this.path = args.path;\n this.serverDetail = args.serverDetail;\n this.code = extractMatrxErrorCode(args.serverDetail);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction nonBlankString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value : undefined;\n}\n\n/**\n * Extract the richest human-readable message from a Matrx/FastAPI error body.\n *\n * aidream 4xx validation errors look like\n * `{ error, user_message, details: [{ field, message, help }] }`; hand-raised\n * HTTPExceptions carry `{ detail: { code, message } }`; FastAPI's defaults are\n * `{ detail: string | [{ msg }] }`. Preference order: `user_message` →\n * `message` → joined `details[].message` → `detail.message` →\n * `detail` string → joined `detail[].msg`. Returns undefined for\n * unrecognized bodies so callers fall back to the bare status line.\n */\nexport function extractMatrxErrorMessage(\n serverDetail: unknown,\n): string | undefined {\n if (!isRecord(serverDetail)) return undefined;\n\n const userMessage = nonBlankString(serverDetail.user_message);\n if (userMessage) return userMessage;\n const message = nonBlankString(serverDetail.message);\n if (message) return message;\n\n if (Array.isArray(serverDetail.details)) {\n const messages = serverDetail.details\n .map((entry: unknown) => {\n if (!isRecord(entry)) return undefined;\n const detailMessage = nonBlankString(entry.message);\n if (!detailMessage) return undefined;\n const field = nonBlankString(entry.field);\n return field ? `${field}: ${detailMessage}` : detailMessage;\n })\n .filter((m): m is string => typeof m === \"string\");\n if (messages.length > 0) return messages.join(\"; \");\n }\n\n const detail = serverDetail.detail;\n if (isRecord(detail)) {\n const detailMessage =\n nonBlankString(detail.message) ?? nonBlankString(detail.user_message);\n if (detailMessage) return detailMessage;\n }\n if (typeof detail === \"string\" && detail.trim()) return detail;\n if (Array.isArray(detail)) {\n const messages = detail\n .map((entry: unknown) =>\n isRecord(entry) ? nonBlankString(entry.msg) : undefined,\n )\n .filter((m): m is string => typeof m === \"string\");\n if (messages.length > 0) return messages.join(\"; \");\n }\n return undefined;\n}\n\n/**\n * Extract the machine error code from a Matrx error body: top-level `code`,\n * else `detail.code` (the hand-raised HTTPException shape). Null when absent.\n */\nexport function extractMatrxErrorCode(serverDetail: unknown): string | null {\n if (!isRecord(serverDetail)) return null;\n const topLevel = nonBlankString(serverDetail.code);\n if (topLevel) return topLevel;\n const detail = serverDetail.detail;\n if (isRecord(detail)) {\n const nested = nonBlankString(detail.code);\n if (nested) return nested;\n }\n return null;\n}\n","/**\n * Internal request plumbing for `@ai-matrx/agents/matrx`. Not part of the\n * public surface — `matrx/index.ts` deliberately does not re-export this\n * module. Everything here is pure: no globals, no work at import time.\n */\n\nimport {\n readMatrxNdjsonStream,\n type MatrxNdjsonIssue,\n type MatrxStreamEnvelope,\n type MatrxStreamEnvelopeObservation,\n} from \"../stream/ndjson\";\nimport { MatrxApiError, type MatrxTransport } from \"./transport\";\n\n/** Encode one path segment (an id) safely into a server-relative path. */\nexport function encodePathSegment(value: string): string {\n return encodeURIComponent(value);\n}\n\nexport type QueryValue =\n | string\n | number\n | boolean\n | readonly string[]\n | undefined;\n\n/**\n * Build a query string. Array values repeat the key (`kind=a&kind=b` — the\n * FastAPI repeatable-parameter convention); undefined values are omitted.\n * Returns \"\" or a string starting with \"?\".\n */\nexport function buildQuery(params: Record<string, QueryValue>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const entry of value) search.append(key, entry);\n } else {\n search.append(key, String(value));\n }\n }\n const encoded = search.toString();\n return encoded ? `?${encoded}` : \"\";\n}\n\nasync function readServerDetail(response: Response): Promise<unknown> {\n try {\n return (await response.json()) as unknown;\n } catch {\n return undefined;\n }\n}\n\nasync function throwApiError(path: string, response: Response): Promise<never> {\n throw new MatrxApiError({\n status: response.status,\n path,\n serverDetail: await readServerDetail(response),\n });\n}\n\nexport interface JsonRequestOptions {\n method: \"GET\" | \"POST\";\n body?: unknown;\n signal?: AbortSignal;\n}\n\n/**\n * Execute a JSON request through the transport. Throws `MatrxApiError` on a\n * non-2xx response; resolves with the parsed JSON body otherwise.\n */\nexport async function requestJson<T>(\n transport: MatrxTransport,\n path: string,\n options: JsonRequestOptions,\n): Promise<T> {\n const hasBody = options.method !== \"GET\" && options.body !== undefined;\n const response = await transport.fetch(path, {\n method: options.method,\n headers: hasBody ? { \"Content-Type\": \"application/json\" } : {},\n ...(hasBody ? { body: JSON.stringify(options.body) } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) return throwApiError(path, response);\n return (await response.json()) as T;\n}\n\n/**\n * Options for every streaming call, riding the NDJSON kernel's contract.\n * Public via `./run`'s re-export.\n */\nexport interface MatrxStreamCallOptions {\n /** Abort the fetch and end the events iterator. */\n signal?: AbortSignal;\n /** Bounded background read-ahead (see `stream/ndjson`). */\n maxReadAhead?: number;\n /** Malformed NDJSON is non-fatal but must never disappear silently. */\n onMalformedLine?: (issue: MatrxNdjsonIssue) => void;\n /** Valid JSON with no recognized Matrx envelope. */\n onUnknownEnvelope?: (value: unknown) => void;\n /** Observe every valid envelope in its exact wire form. */\n onValidEnvelope?: (observation: MatrxStreamEnvelopeObservation) => void;\n}\n\n/**\n * A live agent run: the server-assigned ids (from response headers, available\n * BEFORE any event) and the normalized event stream. Public via `./run`.\n */\nexport interface MatrxRunHandle {\n /** `X-Request-ID` — the ONLY id `POST /ai/cancel/{request_id}` accepts. */\n requestId: string | null;\n /** `X-Conversation-ID` — the server's conversation identity. */\n conversationId: string | null;\n /** Normalized `{event, data}` envelopes through the ONE wire kernel. */\n events: AsyncGenerator<MatrxStreamEnvelope, void, undefined>;\n /** The raw response, for hosts that need headers/status beyond the ids. */\n response: Response;\n}\n\n/**\n * Wrap a validated streaming Response into the run handle — the ONE place\n * the id headers are read and the NDJSON kernel is attached (`./run` and\n * `./operations`' rejoin share it).\n */\nexport function toRunHandle(\n response: Response,\n options: MatrxStreamCallOptions,\n): MatrxRunHandle {\n return {\n requestId: response.headers.get(\"X-Request-ID\"),\n conversationId: response.headers.get(\"X-Conversation-ID\"),\n events: readMatrxNdjsonStream(response.body as ReadableStream<Uint8Array>, {\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.maxReadAhead !== undefined\n ? { maxReadAhead: options.maxReadAhead }\n : {}),\n ...(options.onMalformedLine\n ? { onMalformedLine: options.onMalformedLine }\n : {}),\n ...(options.onUnknownEnvelope\n ? { onUnknownEnvelope: options.onUnknownEnvelope }\n : {}),\n ...(options.onValidEnvelope\n ? { onValidEnvelope: options.onValidEnvelope }\n : {}),\n }),\n response,\n };\n}\n\nexport interface StreamRequestOptions {\n method: \"GET\" | \"POST\";\n body?: unknown;\n /** Extra wire-semantic headers (`Accept`, `Last-Event-ID`). */\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\n/**\n * Execute a streaming request. Throws `MatrxApiError` on a non-2xx response\n * (reading the error body as JSON when possible) or when a 2xx response\n * carries no body; resolves with the validated `Response` otherwise.\n */\nexport async function requestStream(\n transport: MatrxTransport,\n path: string,\n options: StreamRequestOptions,\n): Promise<Response> {\n const hasBody = options.method !== \"GET\" && options.body !== undefined;\n const response = await transport.fetch(path, {\n method: options.method,\n headers: {\n ...(hasBody ? { \"Content-Type\": \"application/json\" } : {}),\n ...options.headers,\n },\n ...(hasBody ? { body: JSON.stringify(options.body) } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) return throwApiError(path, response);\n if (!response.body) {\n throw new MatrxApiError({\n status: response.status,\n path,\n serverDetail: { code: \"missing_response_body\" },\n message: \"The streaming response carried no body.\",\n });\n }\n return response;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0CA,kBAAiD;AACjD,IAAAA,eAAoC;;;AC3CpC,kBAA4B;AAoBrB,IAAM,2BAAN,cAAuC,MAAM;AAAA,EACzC;AAAA,EAET,YAAY,MAAoC,SAAiB;AAC/D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAmCO,SAAS,2BACd,wBACA,wBACQ;AACR,QAAM,YAAY,0BAA0B;AAC5C,MAAI,OAAO,cAAc,YAAY,UAAU,KAAK,EAAE,WAAW,GAAG;AAClE,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,QAAM,aAAa,UAAU,KAAK;AAClC,MAAI,KAAC,yBAAY,UAAU,GAAG;AAC5B,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,SAAO,WAAW,YAAY;AAChC;AAOO,SAAS,+BACd,SACA,gBACwB;AACxB,QAAM,2BAA2B,2BAA2B,cAAc;AAC1E,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,OAAO,GAAG;AACnD,QACE,KAAK,YAAY,MAAM,uBACvB,MAAM,KAAK,EAAE,YAAY,MAAM,0BAC/B;AACA,YAAM,IAAI;AAAA,QACR;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,QAAM,4BAA4B,OAAO;AAAA,IACvC,OAAO,QAAQ,OAAO,EAAE;AAAA,MACtB,CAAC,C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