@magemetrics/core 0.13.0 → 0.14.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.
Files changed (4) hide show
  1. package/README.md +220 -0
  2. package/dist/index.d.ts +830 -128
  3. package/dist/index.js +1014 -340
  4. package/package.json +8 -8
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { sha256 } from '@noble/hashes/sha2.js';
2
- import z9, { z } from 'zod';
2
+ import z10, { z } from 'zod';
3
3
  import { GoTrueClient } from '@supabase/auth-js';
4
4
  import createApiClient2 from 'openapi-fetch';
5
+ import { DefaultChatTransport } from 'ai';
5
6
  import dayjs from 'dayjs';
6
7
  import customParseFormat from 'dayjs/plugin/customParseFormat.js';
7
8
  import relativeTime from 'dayjs/plugin/relativeTime.js';
8
9
  import timezone from 'dayjs/plugin/timezone.js';
9
10
  import utc from 'dayjs/plugin/utc.js';
10
- import { DefaultChatTransport } from 'ai';
11
11
 
12
12
  // ../shared/dist/src/api/client/middleware.js
13
13
  var HEADER_CLIENT_VERSION = "X-Client-Version";
@@ -58,7 +58,7 @@ var addApiKeyHeader = (apiKey) => {
58
58
 
59
59
  // package.json
60
60
  var package_default = {
61
- version: "0.13.0"};
61
+ version: "0.14.1"};
62
62
 
63
63
  // src/core/MageMetricsEventEmitter.ts
64
64
  var MageMetricsEventEmitter = class {
@@ -139,8 +139,9 @@ var DirectAuthProvider = class {
139
139
  removeEventListener(type, listener) {
140
140
  this.events.removeEventListener(type, listener);
141
141
  }
142
+ destroy() {
143
+ }
142
144
  setState(state) {
143
- this.state = state;
144
145
  this.state = state;
145
146
  this.events.dispatch("authStateChange", state);
146
147
  }
@@ -152,7 +153,7 @@ var hashString = (value) => {
152
153
  return Array.from(hash).map((b) => b.toString(16).padStart(2, "0")).join("");
153
154
  };
154
155
 
155
- // ../../node_modules/.pnpm/@asteasolutions+zod-to-openapi@8.5.0_zod@4.3.6/node_modules/@asteasolutions/zod-to-openapi/dist/index.mjs
156
+ // ../../node_modules/.pnpm/@asteasolutions+zod-to-openapi@8.5.0_zod@4.4.3/node_modules/@asteasolutions/zod-to-openapi/dist/index.mjs
156
157
  function __rest(s, e) {
157
158
  var t = {};
158
159
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
@@ -482,7 +483,7 @@ function getOpenApiConfiguration(refOrOpenapi, metadataOrOptions, options) {
482
483
  };
483
484
  }
484
485
 
485
- // ../../node_modules/.pnpm/hono@4.12.15/node_modules/hono/dist/router/reg-exp-router/node.js
486
+ // ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/node.js
486
487
  new Set(".\\+*[^]$()");
487
488
  var createRoute = (routeConfig) => {
488
489
  const route = {
@@ -627,26 +628,26 @@ var ExchangeExternalToken = createRoute({
627
628
  }
628
629
  }
629
630
  });
630
- var MintEmbedTokenInputSchema = z.object({
631
+ var CreateEmbedTokenInputSchema = z.object({
631
632
  uid: ExternalUserIdSchema,
632
633
  attributes: z.record(z.string(), z.unknown()),
633
634
  applicationName: z.string().trim().min(1).optional()
634
635
  });
635
- var MintEmbedTokenOutputSchema = z.object({
636
+ var CreateEmbedTokenOutputSchema = z.object({
636
637
  token: z.string(),
637
638
  expires_at: z.iso.datetime()
638
639
  });
639
640
  createRoute({
640
641
  method: "post",
641
- path: "/api/v1/auth/mintEmbedToken",
642
- operationId: "mintEmbedToken",
642
+ path: "/api/v1/auth/embed-tokens",
643
+ operationId: "createEmbedToken",
643
644
  tags: ["internal"],
644
645
  request: {
645
646
  body: {
646
647
  required: true,
647
648
  content: {
648
649
  "application/json": {
649
- schema: MintEmbedTokenInputSchema
650
+ schema: CreateEmbedTokenInputSchema
650
651
  }
651
652
  }
652
653
  }
@@ -655,10 +656,10 @@ createRoute({
655
656
  200: {
656
657
  content: {
657
658
  "application/json": {
658
- schema: MintEmbedTokenOutputSchema
659
+ schema: CreateEmbedTokenOutputSchema
659
660
  }
660
661
  },
661
- description: "Mint a short-lived Magemetrics embed assertion"
662
+ description: "Create a short-lived Magemetrics embed assertion token"
662
663
  },
663
664
  400: {
664
665
  content: {
@@ -690,7 +691,77 @@ createRoute({
690
691
  schema: z.object({ error: z.string() })
691
692
  }
692
693
  },
693
- description: "Unable to mint an embed token"
694
+ description: "Unable to create an embed token"
695
+ }
696
+ }
697
+ });
698
+ var CreateMcpUserTokenInputSchema = z.object({
699
+ uid: ExternalUserIdSchema,
700
+ attributes: z.record(z.string(), z.unknown()),
701
+ applicationName: z.string().trim().min(1).optional(),
702
+ expiresInSeconds: z.number().int().positive().max(86400).optional()
703
+ });
704
+ var CreateMcpUserTokenOutputSchema = z.object({
705
+ token: z.string(),
706
+ expires_at: z.iso.datetime()
707
+ });
708
+ createRoute({
709
+ method: "post",
710
+ path: "/api/v1/auth/mcp-user-tokens",
711
+ operationId: "createMcpUserToken",
712
+ tags: ["internal"],
713
+ request: {
714
+ body: {
715
+ required: true,
716
+ content: {
717
+ "application/json": {
718
+ schema: CreateMcpUserTokenInputSchema
719
+ }
720
+ }
721
+ }
722
+ },
723
+ responses: {
724
+ 200: {
725
+ content: {
726
+ "application/json": {
727
+ schema: CreateMcpUserTokenOutputSchema
728
+ }
729
+ },
730
+ description: "Create a short-lived MCP user token"
731
+ },
732
+ 400: {
733
+ content: {
734
+ "application/json": {
735
+ schema: z.object({ error: z.string() })
736
+ }
737
+ },
738
+ description: "Invalid input"
739
+ },
740
+ 401: {
741
+ content: {
742
+ "application/json": {
743
+ schema: z.object({ error: z.string() })
744
+ }
745
+ },
746
+ description: "Authentication required"
747
+ },
748
+ 403: {
749
+ content: {
750
+ "application/json": {
751
+ schema: z.object({ error: z.string() })
752
+ }
753
+ },
754
+ description: "Service account required"
755
+ },
756
+ 500: {
757
+ content: {
758
+ "application/json": {
759
+ schema: z.object({
760
+ error: z.string()
761
+ })
762
+ }
763
+ },
764
+ description: "Unable to create an MCP user token"
694
765
  }
695
766
  }
696
767
  });
@@ -710,6 +781,7 @@ var ExternalAuthProvider = class {
710
781
  processedJwt = /* @__PURE__ */ Symbol("initial");
711
782
  userId = null;
712
783
  events = new MageMetricsEventEmitter();
784
+ authSubscription = null;
713
785
  constructor(config) {
714
786
  this.config = config;
715
787
  }
@@ -773,6 +845,12 @@ var ExternalAuthProvider = class {
773
845
  stopAutoRefresh() {
774
846
  return this.supabaseClient?.stopAutoRefresh();
775
847
  }
848
+ destroy() {
849
+ this.authSubscription?.unsubscribe();
850
+ this.authSubscription = null;
851
+ void this.supabaseClient?.stopAutoRefresh();
852
+ this.supabaseClient = null;
853
+ }
776
854
  async getApiInformation() {
777
855
  if (!this.noAuthApiClient || !this.authApiResponse) {
778
856
  this.noAuthApiClient = createApiClient2({
@@ -800,7 +878,9 @@ var ExternalAuthProvider = class {
800
878
  storage: this.config.storage,
801
879
  ...this.config.authOptions
802
880
  });
803
- this.supabaseClient.onAuthStateChange((event, session) => {
881
+ const {
882
+ data: { subscription }
883
+ } = this.supabaseClient.onAuthStateChange((event, session) => {
804
884
  console.debug("Supabase auth state change:", event, !!session);
805
885
  if (event === "SIGNED_IN" && session?.user) {
806
886
  if (this.userId !== session.user.id && this.userId !== null) {
@@ -817,6 +897,7 @@ var ExternalAuthProvider = class {
817
897
  this.setState("initializing");
818
898
  }
819
899
  });
900
+ this.authSubscription = subscription;
820
901
  }
821
902
  }
822
903
  async handleAuthentication() {
@@ -913,6 +994,39 @@ var ExternalAuthProvider = class {
913
994
  }
914
995
  }
915
996
  };
997
+ var isToolResultMessage = (message) => {
998
+ if (message.role !== "assistant") {
999
+ return false;
1000
+ }
1001
+ return message.parts.some(
1002
+ (part) => part.type.startsWith("tool-") && "state" in part && part.state === "output-available"
1003
+ );
1004
+ };
1005
+ var MageMetricsChatTransport = class extends DefaultChatTransport {
1006
+ constructor(apiUrl, flowId, options) {
1007
+ super({
1008
+ ...options,
1009
+ api: `${apiUrl}/api/v1/chat/${flowId}`,
1010
+ prepareSendMessagesRequest({ messages, id: chatId, body }) {
1011
+ const lastMessage = messages.at(-1);
1012
+ if (lastMessage && isToolResultMessage(lastMessage)) {
1013
+ lastMessage.metadata = {
1014
+ ...typeof lastMessage.metadata === "object" ? lastMessage.metadata : void 0,
1015
+ isFrontendToolSubmission: true
1016
+ };
1017
+ }
1018
+ const chatHints = body?.chatHints;
1019
+ return {
1020
+ body: {
1021
+ message: lastMessage,
1022
+ id: chatId,
1023
+ ...chatHints ? { chatHints } : {}
1024
+ }
1025
+ };
1026
+ }
1027
+ });
1028
+ }
1029
+ };
916
1030
  var SupabaseHeaderSchema = z.object({
917
1031
  [HEADER_SP_TOKEN]: z.string().optional()
918
1032
  });
@@ -975,6 +1089,221 @@ var BusinessExplanationSchema = z.object({
975
1089
  explanation: z.string()
976
1090
  }))
977
1091
  });
1092
+ var MONTH_ABBREVIATION_LOCALE = "en-month-abbreviation";
1093
+ dayjs.extend(relativeTime);
1094
+ dayjs.extend(customParseFormat);
1095
+ dayjs.extend(utc);
1096
+ dayjs.extend(timezone);
1097
+ dayjs.locale({
1098
+ name: MONTH_ABBREVIATION_LOCALE,
1099
+ monthsShort: [
1100
+ "Jan.",
1101
+ "Feb.",
1102
+ "Mar.",
1103
+ "Apr.",
1104
+ "May",
1105
+ "Jun.",
1106
+ "Jul.",
1107
+ "Aug.",
1108
+ "Sep.",
1109
+ "Oct.",
1110
+ "Nov.",
1111
+ "Dec."
1112
+ ],
1113
+ formats: {},
1114
+ relativeTime: {}
1115
+ }, void 0, true);
1116
+ var daysjs_default = dayjs;
1117
+
1118
+ // ../shared/dist/src/data/FormattedData.js
1119
+ var numberFormatCache = /* @__PURE__ */ new Map();
1120
+ var getNumberFormatter = (minimumFractionDigits, maximumFractionDigits, useGrouping) => {
1121
+ const key = `${minimumFractionDigits}:${maximumFractionDigits}:${useGrouping}`;
1122
+ let formatter = numberFormatCache.get(key);
1123
+ if (!formatter) {
1124
+ formatter = new Intl.NumberFormat(void 0, {
1125
+ minimumFractionDigits,
1126
+ maximumFractionDigits,
1127
+ useGrouping
1128
+ });
1129
+ numberFormatCache.set(key, formatter);
1130
+ }
1131
+ return formatter;
1132
+ };
1133
+ var formatWithAutoPrecision = (value, options = {}) => {
1134
+ const { minPrecision = 0, maxPrecision = 6, trimZeros = true, useGrouping = true } = options;
1135
+ if (typeof value !== "number" || isNaN(value)) {
1136
+ return String(value);
1137
+ }
1138
+ if (value === 0) {
1139
+ return "0";
1140
+ }
1141
+ const absValue = Math.abs(value);
1142
+ let maximumFractionDigits;
1143
+ if (absValue >= 1e3) {
1144
+ maximumFractionDigits = 0;
1145
+ } else if (absValue >= 100) {
1146
+ maximumFractionDigits = 1;
1147
+ } else if (absValue >= 10) {
1148
+ maximumFractionDigits = 2;
1149
+ } else if (absValue >= 1) {
1150
+ maximumFractionDigits = 3;
1151
+ } else if (absValue >= 0.1) {
1152
+ maximumFractionDigits = 4;
1153
+ } else if (absValue >= 0.01) {
1154
+ maximumFractionDigits = 5;
1155
+ } else {
1156
+ maximumFractionDigits = maxPrecision;
1157
+ if (absValue > 0) {
1158
+ const exponent = Math.floor(Math.log10(absValue));
1159
+ if (exponent < 0) {
1160
+ maximumFractionDigits = Math.min(Math.abs(exponent) + 2, maxPrecision);
1161
+ }
1162
+ }
1163
+ }
1164
+ maximumFractionDigits = Math.max(maximumFractionDigits, minPrecision);
1165
+ const formatter = getNumberFormatter(trimZeros ? 0 : maximumFractionDigits, maximumFractionDigits, useGrouping);
1166
+ return formatter.format(value);
1167
+ };
1168
+ var MIN_VALID_YEAR = 1900;
1169
+ var MAX_VALID_YEAR = 2200;
1170
+ var zonedatetime = (format, zone) => ({ format, type: "zonedatetime", zone });
1171
+ var datetime = (format) => ({ format, type: "datetime" });
1172
+ var date = (format) => ({ format, type: "date" });
1173
+ var DATE_FORMATS = [
1174
+ // ISO 8601 formats
1175
+ zonedatetime("YYYY-MM-DDTHH:mm:ss.SSSZ", "UTC"),
1176
+ zonedatetime("YYYY-MM-DDTHH:mm:ssZ", "UTC"),
1177
+ zonedatetime("YYYY-MM-DDTHH:mmZ", "UTC"),
1178
+ datetime("YYYY-MM-DDTHH:mm:ss"),
1179
+ datetime("YYYY-MM-DDTHH:mm"),
1180
+ date("YYYY-MM-DDT"),
1181
+ // Standard date formats
1182
+ date("YYYY-MM-DD"),
1183
+ date("YYYY/MM/DD"),
1184
+ date("DD-MM-YYYY"),
1185
+ date("DD/MM/YYYY"),
1186
+ date("MM-DD-YYYY"),
1187
+ date("MM/DD/YYYY"),
1188
+ // Date time formats
1189
+ datetime("YYYY-MM-DD HH:mm:ss"),
1190
+ datetime("YYYY-MM-DD HH:mm"),
1191
+ datetime("YYYY/MM/DD HH:mm:ss"),
1192
+ datetime("YYYY/MM/DD HH:mm"),
1193
+ datetime("DD-MM-YYYY HH:mm:ss"),
1194
+ datetime("DD-MM-YYYY HH:mm"),
1195
+ datetime("DD/MM/YYYY HH:mm:ss"),
1196
+ datetime("DD/MM/YYYY HH:mm"),
1197
+ datetime("MM-DD-YYYY HH:mm:ss"),
1198
+ datetime("MM-DD-YYYY HH:mm"),
1199
+ datetime("MM/DD/YYYY HH:mm:ss"),
1200
+ datetime("MM/DD/YYYY HH:mm")
1201
+ ];
1202
+ var isDateString = (value) => {
1203
+ if (typeof value !== "string")
1204
+ return { isValid: false };
1205
+ const stripped = value.replace(/[-/.:\s]/g, "");
1206
+ if (/^\d+$/.test(stripped)) {
1207
+ if (stripped.length < 6)
1208
+ return { isValid: false };
1209
+ if (value.length === stripped.length)
1210
+ return { isValid: false };
1211
+ }
1212
+ if (stripped.length > "YYYY-MM-DDTHH:mm:ss.SSS+00:00".length) {
1213
+ return { isValid: false };
1214
+ }
1215
+ for (const format of DATE_FORMATS) {
1216
+ let date2;
1217
+ try {
1218
+ if (format.type === "zonedatetime") {
1219
+ date2 = daysjs_default.tz(value, format.format, format.zone);
1220
+ } else {
1221
+ date2 = daysjs_default(value, format.format, true);
1222
+ }
1223
+ } catch {
1224
+ continue;
1225
+ }
1226
+ if (date2.isValid()) {
1227
+ const year = date2.year();
1228
+ if (year < MIN_VALID_YEAR || year > MAX_VALID_YEAR)
1229
+ continue;
1230
+ const isDateTime = format.type === "zonedatetime" || format.type == "datetime";
1231
+ return {
1232
+ isValid: true,
1233
+ parsedDate: date2,
1234
+ isDateTime
1235
+ };
1236
+ }
1237
+ }
1238
+ return { isValid: false };
1239
+ };
1240
+ var formatDataValue = (value, { replaceNullValue = true, formatHint } = {}) => {
1241
+ if (value === null || value === void 0) {
1242
+ return {
1243
+ display: replaceNullValue ? "empty" : null,
1244
+ sortValue: null
1245
+ };
1246
+ }
1247
+ let processedValue = value;
1248
+ if (typeof processedValue === "string") {
1249
+ try {
1250
+ const parsed = JSON.parse(processedValue);
1251
+ processedValue = parsed;
1252
+ } catch {
1253
+ }
1254
+ }
1255
+ if (processedValue && typeof processedValue === "object" && Object.keys(processedValue).length === 1 && "value" in processedValue) {
1256
+ const extractedValue = processedValue.value;
1257
+ const dateResult2 = isDateString(extractedValue);
1258
+ if (dateResult2.isValid) {
1259
+ return {
1260
+ display: dateResult2.isDateTime ? dateResult2.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult2.parsedDate.format("YYYY-MM-DD"),
1261
+ sortValue: dateResult2.parsedDate.valueOf()
1262
+ };
1263
+ }
1264
+ return {
1265
+ display: String(extractedValue),
1266
+ sortValue: extractedValue
1267
+ };
1268
+ }
1269
+ const dateResult = isDateString(processedValue);
1270
+ if (dateResult.isValid) {
1271
+ return {
1272
+ display: dateResult.isDateTime ? dateResult.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult.parsedDate.format("YYYY-MM-DD"),
1273
+ sortValue: dateResult.parsedDate.valueOf()
1274
+ };
1275
+ }
1276
+ if (typeof processedValue === "object") {
1277
+ const stringified = JSON.stringify(processedValue, null, 2);
1278
+ return {
1279
+ display: stringified,
1280
+ sortValue: stringified
1281
+ };
1282
+ }
1283
+ if (typeof processedValue === "boolean") {
1284
+ return {
1285
+ display: String(processedValue),
1286
+ sortValue: processedValue ? 1 : 0
1287
+ };
1288
+ }
1289
+ if (typeof processedValue === "number") {
1290
+ if (formatHint?.isLikelyYear !== void 0) {
1291
+ return {
1292
+ display: formatHint.isLikelyYear ? String(processedValue) : formatWithAutoPrecision(processedValue),
1293
+ sortValue: processedValue
1294
+ };
1295
+ }
1296
+ return {
1297
+ display: processedValue >= MIN_VALID_YEAR && processedValue <= MAX_VALID_YEAR && Number.isInteger(processedValue) ? String(processedValue) : formatWithAutoPrecision(processedValue),
1298
+ sortValue: processedValue
1299
+ };
1300
+ }
1301
+ return {
1302
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
1303
+ display: String(processedValue),
1304
+ sortValue: processedValue
1305
+ };
1306
+ };
978
1307
 
979
1308
  // ../shared/dist/src/schemas/flows.js
980
1309
  var FlowStepSchema = z.object({
@@ -1001,10 +1330,16 @@ z.object({
1001
1330
  database: z.string()
1002
1331
  });
1003
1332
  var FrontendFlowSchema = DatabaseFlowSchema.omit({
1004
- flow_steps: true
1333
+ flow_steps: true,
1334
+ context_tokens: true,
1335
+ acc_input_tokens: true,
1336
+ acc_output_tokens: true
1005
1337
  });
1006
1338
  var FrontendRecentFlowsSchema = DatabaseFlowSchema.omit({
1007
- flow_steps: true
1339
+ flow_steps: true,
1340
+ context_tokens: true,
1341
+ acc_input_tokens: true,
1342
+ acc_output_tokens: true
1008
1343
  });
1009
1344
  var ReportColumnSchema = z.looseObject({
1010
1345
  position: z.number().nonnegative().optional(),
@@ -1077,6 +1412,7 @@ var CanonicalDataTypeSchema = z.enum([
1077
1412
  "numeric",
1078
1413
  "boolean",
1079
1414
  "datetime",
1415
+ "date",
1080
1416
  "text",
1081
1417
  "array",
1082
1418
  "json",
@@ -1087,12 +1423,17 @@ z.object({
1087
1423
  unit: z.string().nullish(),
1088
1424
  canonical_data_type: CanonicalDataTypeSchema.nullish()
1089
1425
  });
1426
+ var ColumnFormatHintSchema = z.object({
1427
+ isNumeric: z.boolean().optional(),
1428
+ isLikelyYear: z.boolean().optional()
1429
+ });
1090
1430
  var FrontendReportColumnsSchema = z.object({
1091
1431
  ...ReportColumnsSchema.element.shape,
1092
1432
  dataType: z.string(),
1093
1433
  renderType: z.string().optional(),
1094
1434
  unit: z.string().optional(),
1095
- canonicalDataType: CanonicalDataTypeSchema.optional()
1435
+ canonicalDataType: CanonicalDataTypeSchema.optional(),
1436
+ formatHint: ColumnFormatHintSchema.optional()
1096
1437
  }).array().openapi("ReportColumns");
1097
1438
  z.object({
1098
1439
  goal: z.string(),
@@ -1285,9 +1626,33 @@ var columnsQueryParams = z.string().transform((str) => {
1285
1626
  },
1286
1627
  type: "string"
1287
1628
  });
1629
+
1630
+ // ../shared/dist/src/schemas/chat/fileUpload.js
1631
+ var CHAT_MAX_FILE_SIZE = 10 * 1024 * 1024;
1632
+ var CHAT_MAX_TOTAL_FILE_BYTES_FOR_LLM = 15 * 1024 * 1024;
1633
+ var CHAT_MAX_COMBINED_FILE_SIZE = CHAT_MAX_TOTAL_FILE_BYTES_FOR_LLM;
1288
1634
  var CHAT_MAX_FILE_COUNT = 10;
1635
+ var UPLOADED_FILE_REF_PREFIX = "uploaded-file:";
1289
1636
  var CHAT_ALLOWED_FILE_MEDIA_TYPES = /* @__PURE__ */ new Set(["application/pdf"]);
1290
- [...CHAT_ALLOWED_FILE_MEDIA_TYPES].join(",");
1637
+ var CHAT_FILE_ACCEPT = [...CHAT_ALLOWED_FILE_MEDIA_TYPES].join(",");
1638
+ var getUploadedFileIdFromUrl = (url) => {
1639
+ if (!url.startsWith(UPLOADED_FILE_REF_PREFIX)) {
1640
+ return null;
1641
+ }
1642
+ const uploadedFileId = url.slice(UPLOADED_FILE_REF_PREFIX.length);
1643
+ return uploadedFileId.length > 0 ? uploadedFileId : null;
1644
+ };
1645
+ var toUploadedFileRefUrl = (uploadedFileId) => `${UPLOADED_FILE_REF_PREFIX}${uploadedFileId}`;
1646
+ var validateUploadedFiles = (uploadedFiles) => {
1647
+ if (uploadedFiles.length > CHAT_MAX_FILE_COUNT) {
1648
+ throw new Error(`Too many files: ${uploadedFiles.length}. Maximum is ${CHAT_MAX_FILE_COUNT}.`);
1649
+ }
1650
+ const combinedSize = uploadedFiles.reduce((sum, uploadedFile) => sum + uploadedFile.size_bytes, 0);
1651
+ if (combinedSize > CHAT_MAX_COMBINED_FILE_SIZE) {
1652
+ const limitMB = Math.round(CHAT_MAX_COMBINED_FILE_SIZE / (1024 * 1024));
1653
+ throw new Error(`Combined file size exceeds maximum of ${limitMB} MB.`);
1654
+ }
1655
+ };
1291
1656
  var UploadedFileIdSchema = z.uuid();
1292
1657
  var UploadedFileSchema = z.object({
1293
1658
  uploadedFileId: UploadedFileIdSchema,
@@ -1316,13 +1681,7 @@ var parseReportId = (val, ctx) => {
1316
1681
  };
1317
1682
  var ReportId = z.string().transform((val, ctx) => parseReportId(val, ctx)).openapi({ type: "string", description: "Numeric legacy ID or UUID" });
1318
1683
  var ReportIdFromBody = z.union([z.string(), z.number()]).transform((val, ctx) => parseReportId(String(val), ctx));
1319
- var ReportIdParam = z.object({ report_id: ReportId }).openapi("ReportId", { type: "integer" });
1320
- var CreateFlowFileSchema = z.object({
1321
- type: z.literal("file"),
1322
- mediaType: z.string(),
1323
- filename: z.string().optional(),
1324
- url: z.string()
1325
- });
1684
+ var ReportIdParam = z.object({ report_id: ReportId }).openapi("ReportId", { type: "integer" });
1326
1685
  var RetrieveFlowDataReports = createRoute({
1327
1686
  method: "get",
1328
1687
  path: "/api/v1/flows/{flowId}/data-reports",
@@ -1546,6 +1905,15 @@ var ExportReportData = createRoute({
1546
1905
  }
1547
1906
  }
1548
1907
  });
1908
+ var DataServiceErrorCodeSchema = z.enum([
1909
+ "QUERY_LIMIT_EXCEEDED",
1910
+ "QUERY_TIMEOUT",
1911
+ "QUERY_EXECUTION_FAILED"
1912
+ ]);
1913
+ var DataServiceErrorResponseSchema = z.object({
1914
+ error: z.string(),
1915
+ code: DataServiceErrorCodeSchema
1916
+ });
1549
1917
  var GetReportData = createRoute({
1550
1918
  method: "get",
1551
1919
  path: "/api/v1/data-reports/{report_id}/data",
@@ -1583,9 +1951,7 @@ var GetReportData = createRoute({
1583
1951
  description: "Something wrong happened",
1584
1952
  content: {
1585
1953
  "application/json": {
1586
- schema: z.object({
1587
- error: z.string()
1588
- })
1954
+ schema: DataServiceErrorResponseSchema
1589
1955
  }
1590
1956
  }
1591
1957
  }
@@ -1623,9 +1989,7 @@ var GetReportRowCount = createRoute({
1623
1989
  description: "Something wrong happened",
1624
1990
  content: {
1625
1991
  "application/json": {
1626
- schema: z.object({
1627
- error: z.string()
1628
- })
1992
+ schema: DataServiceErrorResponseSchema
1629
1993
  }
1630
1994
  }
1631
1995
  }
@@ -1845,7 +2209,7 @@ createRoute({
1845
2209
  operationId: "getColumnLineage",
1846
2210
  tags: ["public"],
1847
2211
  request: {
1848
- headers: SupabaseHeaderSchema,
2212
+ headers: SupabaseScopedHeaderSchema,
1849
2213
  body: {
1850
2214
  required: true,
1851
2215
  content: {
@@ -2041,7 +2405,6 @@ var CreateFlow = createRoute({
2041
2405
  schema: z.object({
2042
2406
  userQuery: z.string(),
2043
2407
  applicationName: z.string().optional(),
2044
- files: z.array(CreateFlowFileSchema).max(CHAT_MAX_FILE_COUNT).optional(),
2045
2408
  uploadedFileIds: z.array(UploadedFileIdSchema).max(CHAT_MAX_FILE_COUNT).optional()
2046
2409
  })
2047
2410
  }
@@ -2082,6 +2445,49 @@ var CreateFlow = createRoute({
2082
2445
  }
2083
2446
  }
2084
2447
  });
2448
+ var PromptStarterSchema = z.object({
2449
+ id: z.number(),
2450
+ title: z.string(),
2451
+ template: z.string(),
2452
+ is_default: z.boolean()
2453
+ }).describe("Prompt starter template").openapi("PromptStarter");
2454
+
2455
+ // ../shared/dist/src/endpoints/companion/promptStarters.routes.js
2456
+ var MAX_PROMPT_STARTERS = 3;
2457
+ var GetPromptStarters = createRoute({
2458
+ method: "get",
2459
+ path: "/api/v1/prompt-starters",
2460
+ operationId: "getPromptStarters",
2461
+ tags: ["public"],
2462
+ request: {
2463
+ headers: SupabaseHeaderSchema,
2464
+ query: z.object({
2465
+ input: z.string().optional()
2466
+ })
2467
+ },
2468
+ responses: {
2469
+ 200: {
2470
+ description: "List available prompt starters",
2471
+ content: {
2472
+ "application/json": {
2473
+ schema: z.object({
2474
+ starters: PromptStarterSchema.array().min(0).max(MAX_PROMPT_STARTERS)
2475
+ })
2476
+ }
2477
+ }
2478
+ },
2479
+ 500: {
2480
+ description: "Something wrong happened",
2481
+ content: {
2482
+ "application/json": {
2483
+ schema: z.object({
2484
+ error: z.string()
2485
+ })
2486
+ }
2487
+ }
2488
+ }
2489
+ }
2490
+ });
2085
2491
  var FrontendRecommendationsSchema = z.object({
2086
2492
  starter: z.string(),
2087
2493
  explanation: z.string(),
@@ -2158,20 +2564,20 @@ var CreateSpeechToken = createRoute({
2158
2564
  }
2159
2565
  }
2160
2566
  });
2161
- z9.discriminatedUnion("status", [
2162
- z9.object({
2163
- status: z9.literal("error"),
2164
- error: z9.string()
2567
+ z10.discriminatedUnion("status", [
2568
+ z10.object({
2569
+ status: z10.literal("error"),
2570
+ error: z10.string()
2165
2571
  }),
2166
- z9.object({
2167
- status: z9.literal("success"),
2168
- flowId: z9.string()
2572
+ z10.object({
2573
+ status: z10.literal("success"),
2574
+ flowId: z10.string()
2169
2575
  })
2170
2576
  ]);
2171
- var TriggerFlowBody = z9.object({
2172
- triggerId: z9.string(),
2173
- variables: z9.record(z9.string(), z9.string()),
2174
- applicationName: z9.string().optional()
2577
+ var TriggerFlowBody = z10.object({
2578
+ triggerId: z10.string(),
2579
+ variables: z10.record(z10.string(), z10.string()),
2580
+ applicationName: z10.string().optional()
2175
2581
  });
2176
2582
  var TriggerFlow = createRoute({
2177
2583
  method: "post",
@@ -2195,9 +2601,9 @@ var TriggerFlow = createRoute({
2195
2601
  description: "Flow id",
2196
2602
  content: {
2197
2603
  "application/json": {
2198
- schema: z9.object({
2199
- status: z9.literal("success"),
2200
- flowId: z9.string()
2604
+ schema: z10.object({
2605
+ status: z10.literal("success"),
2606
+ flowId: z10.string()
2201
2607
  })
2202
2608
  }
2203
2609
  }
@@ -2205,8 +2611,8 @@ var TriggerFlow = createRoute({
2205
2611
  400: {
2206
2612
  content: {
2207
2613
  "application/json": {
2208
- schema: z9.object({
2209
- error: z9.string()
2614
+ schema: z10.object({
2615
+ error: z10.string()
2210
2616
  })
2211
2617
  }
2212
2618
  },
@@ -2215,7 +2621,7 @@ var TriggerFlow = createRoute({
2215
2621
  404: {
2216
2622
  content: {
2217
2623
  "application/json": {
2218
- schema: z9.object({ error: z9.string() })
2624
+ schema: z10.object({ error: z10.string() })
2219
2625
  }
2220
2626
  },
2221
2627
  description: "Unable to retrieve trigger with this id"
@@ -2224,8 +2630,8 @@ var TriggerFlow = createRoute({
2224
2630
  description: "Something wrong happened",
2225
2631
  content: {
2226
2632
  "application/json": {
2227
- schema: z9.object({
2228
- error: z9.string()
2633
+ schema: z10.object({
2634
+ error: z10.string()
2229
2635
  })
2230
2636
  }
2231
2637
  }
@@ -2255,9 +2661,9 @@ createRoute({
2255
2661
  description: "Flow id",
2256
2662
  content: {
2257
2663
  "application/json": {
2258
- schema: z9.object({
2259
- status: z9.literal("success"),
2260
- flowId: z9.string()
2664
+ schema: z10.object({
2665
+ status: z10.literal("success"),
2666
+ flowId: z10.string()
2261
2667
  })
2262
2668
  }
2263
2669
  }
@@ -2265,8 +2671,8 @@ createRoute({
2265
2671
  400: {
2266
2672
  content: {
2267
2673
  "application/json": {
2268
- schema: z9.object({
2269
- error: z9.string()
2674
+ schema: z10.object({
2675
+ error: z10.string()
2270
2676
  })
2271
2677
  }
2272
2678
  },
@@ -2275,7 +2681,7 @@ createRoute({
2275
2681
  404: {
2276
2682
  content: {
2277
2683
  "application/json": {
2278
- schema: z9.object({ error: z9.string() })
2684
+ schema: z10.object({ error: z10.string() })
2279
2685
  }
2280
2686
  },
2281
2687
  description: "Unable to retrieve trigger with this id"
@@ -2284,8 +2690,8 @@ createRoute({
2284
2690
  description: "Something wrong happened",
2285
2691
  content: {
2286
2692
  "application/json": {
2287
- schema: z9.object({
2288
- error: z9.string()
2693
+ schema: z10.object({
2694
+ error: z10.string()
2289
2695
  })
2290
2696
  }
2291
2697
  }
@@ -2903,7 +3309,6 @@ var BaseAgentSchema = z.object({
2903
3309
  });
2904
3310
  var AgentBehaviorSchema = z.object({
2905
3311
  name: z.string(),
2906
- objective: z.string().nullable(),
2907
3312
  generated_objective_fragment: z.string().nullable(),
2908
3313
  active_tools: z.array(z.string()).nullable(),
2909
3314
  input_schema: AgentInputSchemaSchema.nullable(),
@@ -2916,11 +3321,11 @@ var AgentSchema = z.object({
2916
3321
  ...BaseAgentSchema.shape,
2917
3322
  ...AgentBehaviorSchema.shape,
2918
3323
  updated_at: z.string(),
2919
- current_version_id: z.uuid()
3324
+ current_version_id: z.uuid(),
3325
+ version_count: z.number().int().positive()
2920
3326
  });
2921
3327
  z.object({
2922
3328
  name: z.string().min(1, "Name is required"),
2923
- objective: z.string().optional(),
2924
3329
  generated_objective_fragment: z.string().optional(),
2925
3330
  active_tools: z.array(z.string()).default([]),
2926
3331
  input_schema: AgentInputSchemaSchema.optional(),
@@ -2931,7 +3336,6 @@ z.object({
2931
3336
  });
2932
3337
  var DbUpdateAgentSchema = z.object({
2933
3338
  name: z.string().min(1).optional(),
2934
- objective: z.string().nullable().optional(),
2935
3339
  generated_objective_fragment: z.string().nullable().optional(),
2936
3340
  active_tools: z.array(z.string()).optional(),
2937
3341
  input_schema: AgentInputSchemaSchema.nullable().optional(),
@@ -3050,7 +3454,8 @@ z.object({
3050
3454
  // Nullable with a default so pre-migration rows (where the column is absent)
3051
3455
  // parse cleanly — undefined input becomes null output.
3052
3456
  post_processors: z.array(PostProcessorConfigSchema).nullable().default(null),
3053
- agent_version_id: z.uuid().nullable().default(null)
3457
+ agent_version_id: z.uuid().nullable().default(null),
3458
+ cached_from: z.uuid().nullable().default(null)
3054
3459
  });
3055
3460
  z.object({
3056
3461
  user_id: z.uuid(),
@@ -3068,6 +3473,7 @@ z.object({
3068
3473
  model_config: ModelConfigSchema.optional(),
3069
3474
  post_processors: z.array(PostProcessorConfigSchema).optional(),
3070
3475
  agent_version_id: z.uuid().optional(),
3476
+ cached_from: z.uuid().optional(),
3071
3477
  started_at: z.string().optional(),
3072
3478
  completed_at: z.string().optional()
3073
3479
  });
@@ -3085,224 +3491,36 @@ z.object({
3085
3491
  model_config: ModelConfigSchema.optional(),
3086
3492
  last_heartbeat_at: z.string().nullable().optional(),
3087
3493
  post_processors: z.array(PostProcessorConfigSchema).optional()
3088
- });
3089
- var StartAgentRunRequestSchema = z.object({
3090
- agent_id: z.uuid(),
3091
- inputs: z.record(z.string(), z.unknown()).default({}),
3092
- execution_context: ExecutionContextInputSchema.optional()
3093
- }).openapi("StartAgentRunRequest");
3094
- var AgentRunResponseSchema = z.object({
3095
- id: z.uuid(),
3096
- agent_id: z.uuid().nullable(),
3097
- status: AgentRunStatusSchema,
3098
- created_at: z.string(),
3099
- started_at: z.string().nullable(),
3100
- completed_at: z.string().nullable(),
3101
- input_data: z.record(z.string(), z.unknown()).nullable(),
3102
- output_data: z.record(z.string(), z.unknown()).nullable(),
3103
- tasks: AgentTasksStateSchema.nullable().optional(),
3104
- error_message: z.string().nullable(),
3105
- execution_context: ResolvedExecutionContextSchema.nullable().optional(),
3106
- agent_version_id: z.uuid().nullable().optional(),
3107
- cached: z.boolean().optional()
3108
- }).openapi("AgentRunResponse");
3109
- z.object({
3110
- status: AgentRunStatusSchema.optional(),
3111
- agent_id: z.uuid().optional(),
3112
- agent_type: AgentTypeSchema.optional(),
3113
- limit: z.number().int().positive().max(100).default(20)
3114
- });
3115
- dayjs.extend(relativeTime);
3116
- dayjs.extend(customParseFormat);
3117
- dayjs.extend(utc);
3118
- dayjs.extend(timezone);
3119
- var daysjs_default = dayjs;
3120
-
3121
- // ../shared/dist/src/data/FormattedData.js
3122
- var numberFormatCache = /* @__PURE__ */ new Map();
3123
- var getNumberFormatter = (minimumFractionDigits, maximumFractionDigits, useGrouping) => {
3124
- const key = `${minimumFractionDigits}:${maximumFractionDigits}:${useGrouping}`;
3125
- let formatter = numberFormatCache.get(key);
3126
- if (!formatter) {
3127
- formatter = new Intl.NumberFormat(void 0, {
3128
- minimumFractionDigits,
3129
- maximumFractionDigits,
3130
- useGrouping
3131
- });
3132
- numberFormatCache.set(key, formatter);
3133
- }
3134
- return formatter;
3135
- };
3136
- var formatWithAutoPrecision = (value, options = {}) => {
3137
- const { minPrecision = 0, maxPrecision = 6, trimZeros = true, useGrouping = true } = options;
3138
- if (typeof value !== "number" || isNaN(value)) {
3139
- return String(value);
3140
- }
3141
- if (value === 0) {
3142
- return "0";
3143
- }
3144
- const absValue = Math.abs(value);
3145
- let maximumFractionDigits;
3146
- if (absValue >= 1e3) {
3147
- maximumFractionDigits = 0;
3148
- } else if (absValue >= 100) {
3149
- maximumFractionDigits = 1;
3150
- } else if (absValue >= 10) {
3151
- maximumFractionDigits = 2;
3152
- } else if (absValue >= 1) {
3153
- maximumFractionDigits = 3;
3154
- } else if (absValue >= 0.1) {
3155
- maximumFractionDigits = 4;
3156
- } else if (absValue >= 0.01) {
3157
- maximumFractionDigits = 5;
3158
- } else {
3159
- maximumFractionDigits = maxPrecision;
3160
- if (absValue > 0) {
3161
- const exponent = Math.floor(Math.log10(absValue));
3162
- if (exponent < 0) {
3163
- maximumFractionDigits = Math.min(Math.abs(exponent) + 2, maxPrecision);
3164
- }
3165
- }
3166
- }
3167
- maximumFractionDigits = Math.max(maximumFractionDigits, minPrecision);
3168
- const formatter = getNumberFormatter(trimZeros ? 0 : maximumFractionDigits, maximumFractionDigits, useGrouping);
3169
- return formatter.format(value);
3170
- };
3171
- var MIN_VALID_YEAR = 1900;
3172
- var MAX_VALID_YEAR = 2200;
3173
- var zonedatetime = (format, zone) => ({ format, type: "zonedatetime", zone });
3174
- var datetime = (format) => ({ format, type: "datetime" });
3175
- var date = (format) => ({ format, type: "date" });
3176
- var DATE_FORMATS = [
3177
- // ISO 8601 formats
3178
- zonedatetime("YYYY-MM-DDTHH:mm:ss.SSSZ", "UTC"),
3179
- zonedatetime("YYYY-MM-DDTHH:mm:ssZ", "UTC"),
3180
- zonedatetime("YYYY-MM-DDTHH:mmZ", "UTC"),
3181
- datetime("YYYY-MM-DDTHH:mm:ss"),
3182
- datetime("YYYY-MM-DDTHH:mm"),
3183
- date("YYYY-MM-DDT"),
3184
- // Standard date formats
3185
- date("YYYY-MM-DD"),
3186
- date("YYYY/MM/DD"),
3187
- date("DD-MM-YYYY"),
3188
- date("DD/MM/YYYY"),
3189
- date("MM-DD-YYYY"),
3190
- date("MM/DD/YYYY"),
3191
- // Date time formats
3192
- datetime("YYYY-MM-DD HH:mm:ss"),
3193
- datetime("YYYY-MM-DD HH:mm"),
3194
- datetime("YYYY/MM/DD HH:mm:ss"),
3195
- datetime("YYYY/MM/DD HH:mm"),
3196
- datetime("DD-MM-YYYY HH:mm:ss"),
3197
- datetime("DD-MM-YYYY HH:mm"),
3198
- datetime("DD/MM/YYYY HH:mm:ss"),
3199
- datetime("DD/MM/YYYY HH:mm"),
3200
- datetime("MM-DD-YYYY HH:mm:ss"),
3201
- datetime("MM-DD-YYYY HH:mm"),
3202
- datetime("MM/DD/YYYY HH:mm:ss"),
3203
- datetime("MM/DD/YYYY HH:mm")
3204
- ];
3205
- var isDateString = (value) => {
3206
- if (typeof value !== "string")
3207
- return { isValid: false };
3208
- const stripped = value.replace(/[-/.:\s]/g, "");
3209
- if (/^\d+$/.test(stripped)) {
3210
- if (stripped.length < 6)
3211
- return { isValid: false };
3212
- if (value.length === stripped.length)
3213
- return { isValid: false };
3214
- }
3215
- if (stripped.length > "YYYY-MM-DDTHH:mm:ss.SSS+00:00".length) {
3216
- return { isValid: false };
3217
- }
3218
- for (const format of DATE_FORMATS) {
3219
- let date2;
3220
- try {
3221
- if (format.type === "zonedatetime") {
3222
- date2 = daysjs_default.tz(value, format.format, format.zone);
3223
- } else {
3224
- date2 = daysjs_default(value, format.format, true);
3225
- }
3226
- } catch {
3227
- continue;
3228
- }
3229
- if (date2.isValid()) {
3230
- const year = date2.year();
3231
- if (year < MIN_VALID_YEAR || year > MAX_VALID_YEAR)
3232
- continue;
3233
- const isDateTime = format.type === "zonedatetime" || format.type == "datetime";
3234
- return {
3235
- isValid: true,
3236
- parsedDate: date2,
3237
- isDateTime
3238
- };
3239
- }
3240
- }
3241
- return { isValid: false };
3242
- };
3243
- var formatDataValue = (value, { replaceNullValue } = {
3244
- replaceNullValue: true
3245
- }) => {
3246
- if (value === null || value === void 0) {
3247
- return {
3248
- display: replaceNullValue ? "empty" : null,
3249
- sortValue: null
3250
- };
3251
- }
3252
- let processedValue = value;
3253
- if (typeof processedValue === "string") {
3254
- try {
3255
- const parsed = JSON.parse(processedValue);
3256
- processedValue = parsed;
3257
- } catch {
3258
- }
3259
- }
3260
- if (processedValue && typeof processedValue === "object" && Object.keys(processedValue).length === 1 && "value" in processedValue) {
3261
- const extractedValue = processedValue.value;
3262
- const dateResult2 = isDateString(extractedValue);
3263
- if (dateResult2.isValid) {
3264
- return {
3265
- display: dateResult2.isDateTime ? dateResult2.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult2.parsedDate.format("YYYY-MM-DD"),
3266
- sortValue: dateResult2.parsedDate.valueOf()
3267
- };
3268
- }
3269
- return {
3270
- display: String(extractedValue),
3271
- sortValue: extractedValue
3272
- };
3273
- }
3274
- const dateResult = isDateString(processedValue);
3275
- if (dateResult.isValid) {
3276
- return {
3277
- display: dateResult.isDateTime ? dateResult.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult.parsedDate.format("YYYY-MM-DD"),
3278
- sortValue: dateResult.parsedDate.valueOf()
3279
- };
3280
- }
3281
- if (typeof processedValue === "object") {
3282
- const stringified = JSON.stringify(processedValue, null, 2);
3283
- return {
3284
- display: stringified,
3285
- sortValue: stringified
3286
- };
3287
- }
3288
- if (typeof processedValue === "boolean") {
3289
- return {
3290
- display: String(processedValue),
3291
- sortValue: processedValue ? 1 : 0
3292
- };
3293
- }
3294
- if (typeof processedValue === "number") {
3295
- return {
3296
- display: processedValue >= MIN_VALID_YEAR && processedValue <= MAX_VALID_YEAR && Number.isInteger(processedValue) ? String(processedValue) : formatWithAutoPrecision(processedValue),
3297
- sortValue: processedValue
3298
- };
3299
- }
3300
- return {
3301
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
3302
- display: String(processedValue),
3303
- sortValue: processedValue
3304
- };
3305
- };
3494
+ });
3495
+ var StartAgentRunRequestSchema = z.object({
3496
+ agent_id: z.uuid(),
3497
+ inputs: z.record(z.string(), z.unknown()).default({}),
3498
+ execution_context: ExecutionContextInputSchema.optional()
3499
+ }).openapi("StartAgentRunRequest");
3500
+ var AgentRunResponseSchema = z.object({
3501
+ id: z.uuid(),
3502
+ agent_id: z.uuid().nullable(),
3503
+ status: AgentRunStatusSchema,
3504
+ created_at: z.string(),
3505
+ started_at: z.string().nullable(),
3506
+ completed_at: z.string().nullable(),
3507
+ input_data: z.record(z.string(), z.unknown()).nullable(),
3508
+ output_data: z.record(z.string(), z.unknown()).nullable(),
3509
+ tasks: AgentTasksStateSchema.nullable().optional(),
3510
+ error_message: z.string().nullable(),
3511
+ execution_context: ResolvedExecutionContextSchema.nullable().optional(),
3512
+ agent_version_id: z.uuid().nullable().optional(),
3513
+ cached: z.boolean().optional(),
3514
+ cached_from: z.uuid().nullable().optional(),
3515
+ report_count: z.number().int().nonnegative().default(0),
3516
+ visualization_count: z.number().int().nonnegative().default(0)
3517
+ }).openapi("AgentRunResponse");
3518
+ z.object({
3519
+ status: AgentRunStatusSchema.optional(),
3520
+ agent_id: z.uuid().optional(),
3521
+ agent_type: AgentTypeSchema.optional(),
3522
+ limit: z.number().int().positive().max(100).default(20)
3523
+ });
3306
3524
 
3307
3525
  // ../shared/dist/src/schemas/visualizations.js
3308
3526
  var commonConfigProperties = {
@@ -3446,6 +3664,14 @@ var FrontendVisualizationSchema = VisualizationSchema.omit({
3446
3664
  is_sample: true,
3447
3665
  data_summary: true
3448
3666
  });
3667
+ var isFrontendV1Visualization = (visualization) => {
3668
+ return !("config_version" in visualization.configuration);
3669
+ };
3670
+ var isFrontendV2Visualization = (visualization) => {
3671
+ return "config_version" in visualization.configuration && // we currently have only 2 versions
3672
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3673
+ visualization.configuration.config_version === 2;
3674
+ };
3449
3675
  var VisualizationMetadataSchema = z.object({
3450
3676
  wasSampled: z.boolean(),
3451
3677
  originalCount: z.number(),
@@ -3459,6 +3685,14 @@ var FrontendVisualizationWithDataSchema = FrontendVisualizationSchema.extend({
3459
3685
  data: VisualizationDataSchema,
3460
3686
  _metadata: VisualizationMetadataSchema
3461
3687
  });
3688
+ var isFrontendV1VisualizationWithData = (visualization) => {
3689
+ return !("config_version" in visualization.configuration);
3690
+ };
3691
+ var isFrontendV2VisualizationWithData = (visualization) => {
3692
+ return "config_version" in visualization.configuration && // we currently have only 2 versions
3693
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3694
+ visualization.configuration.config_version === 2;
3695
+ };
3462
3696
 
3463
3697
  // ../shared/dist/src/endpoints/agents/runs.routes.js
3464
3698
  var AgentRunIdParam = z.object({ id: z.uuid() }).openapi("AgentRunId");
@@ -3795,39 +4029,6 @@ var ListVisualizationsForFlow = createRoute({
3795
4029
  }
3796
4030
  }
3797
4031
  });
3798
- var isToolResultMessage = (message) => {
3799
- if (message.role !== "assistant") {
3800
- return false;
3801
- }
3802
- return message.parts.some(
3803
- (part) => part.type.startsWith("tool-") && "state" in part && part.state === "output-available"
3804
- );
3805
- };
3806
- var MageMetricsChatTransport = class extends DefaultChatTransport {
3807
- constructor(apiUrl, flowId, options) {
3808
- super({
3809
- ...options,
3810
- api: `${apiUrl}/api/v1/chat/${flowId}`,
3811
- prepareSendMessagesRequest({ messages, id: chatId, body }) {
3812
- const lastMessage = messages.at(-1);
3813
- if (lastMessage && isToolResultMessage(lastMessage)) {
3814
- lastMessage.metadata = {
3815
- ...typeof lastMessage.metadata === "object" ? lastMessage.metadata : void 0,
3816
- isFrontendToolSubmission: true
3817
- };
3818
- }
3819
- const chatHints = body?.chatHints;
3820
- return {
3821
- body: {
3822
- message: lastMessage,
3823
- id: chatId,
3824
- ...chatHints ? { chatHints } : {}
3825
- }
3826
- };
3827
- }
3828
- });
3829
- }
3830
- };
3831
4032
 
3832
4033
  // src/core/resolvable.ts
3833
4034
  var resolve = (value) => {
@@ -3940,6 +4141,16 @@ var MageMetricsClient = class {
3940
4141
  async logout() {
3941
4142
  await this.authProvider.logout();
3942
4143
  }
4144
+ /**
4145
+ * Clean up all resources held by this client.
4146
+ * Unsubscribes auth state listeners, stops auto-refresh timers,
4147
+ * and removes global event listeners (e.g. visibilitychange).
4148
+ *
4149
+ * Call this before discarding a client instance to prevent leaks.
4150
+ */
4151
+ destroy() {
4152
+ this.authProvider.destroy();
4153
+ }
3943
4154
  auth = {
3944
4155
  startAutoRefresh: () => {
3945
4156
  const supabaseClient = this.authProvider.getSupabaseClient();
@@ -4335,29 +4546,23 @@ var MageMetricsClient = class {
4335
4546
  },
4336
4547
  fetchReportData: async (reportId, { columns, limit, sorting, filters, cursor }, signal) => {
4337
4548
  const params = toSearchParams({ limit, sorting, filters, cursor });
4338
- const { data, error } = await this.internalApiClient.GET(
4339
- GetReportData.path,
4340
- {
4341
- params: {
4342
- path: {
4343
- report_id: reportId
4344
- },
4345
- query: {
4346
- columns: columns?.join(","),
4347
- limit: params.limit,
4348
- order: params.order,
4349
- cursor: params.cursor,
4350
- filter: params.filter
4351
- }
4549
+ const { data } = await this.internalApiClient.GET(GetReportData.path, {
4550
+ params: {
4551
+ path: {
4552
+ report_id: reportId
4352
4553
  },
4353
- signal
4354
- }
4355
- );
4356
- if (error) {
4357
- console.error(
4358
- `Failed to fetch data for report ${reportId}: ${error.error}`
4359
- );
4360
- throw new Error(`Failed to fetch data for flow data ${reportId}`);
4554
+ query: {
4555
+ columns: columns?.join(","),
4556
+ limit: params.limit,
4557
+ order: params.order,
4558
+ cursor: params.cursor,
4559
+ filter: params.filter
4560
+ }
4561
+ },
4562
+ signal
4563
+ });
4564
+ if (!data) {
4565
+ throw new Error(`Missing report data payload for report ${reportId}`);
4361
4566
  }
4362
4567
  return data;
4363
4568
  },
@@ -4428,6 +4633,28 @@ var MageMetricsClient = class {
4428
4633
  });
4429
4634
  }
4430
4635
  return data.recommendations;
4636
+ },
4637
+ getPromptStarters: async (input) => {
4638
+ await this.waitForAuth();
4639
+ const { data, error, response } = await this.internalApiClient.GET(
4640
+ GetPromptStarters.path,
4641
+ {
4642
+ params: {
4643
+ query: {
4644
+ input
4645
+ }
4646
+ }
4647
+ }
4648
+ );
4649
+ if (error) {
4650
+ throw new ApiError(error.error, response, {
4651
+ status: response.status,
4652
+ statusText: response.statusText,
4653
+ url: response.url,
4654
+ method: "GET"
4655
+ });
4656
+ }
4657
+ return data.starters;
4431
4658
  }
4432
4659
  };
4433
4660
  client() {
@@ -4446,4 +4673,451 @@ var MageMetricsClient = class {
4446
4673
  }
4447
4674
  };
4448
4675
 
4449
- export { BrowserStorageAdapter, CHECK_KEY, DirectAuthProvider, ExternalAuthProvider, MageMetricsClient, MageMetricsEventEmitter, MemoryStorageAdapter, TOKEN_STORAGE_KEY, getPublicApiClient };
4676
+ // src/core/chat.ts
4677
+ var hasOnlyInitialUserMessage = (messages) => {
4678
+ return messages.length === 1 && messages[0]?.role === "user";
4679
+ };
4680
+ var ASK_USER_QUESTION = "askUserQuestion";
4681
+ var optionSchema = z.object({
4682
+ label: z.string().describe("Option display text (1-5 words)"),
4683
+ description: z.string().describe("Explanation of the option")
4684
+ });
4685
+ var questionSchema = z.object({
4686
+ question: z.string().describe("The question to ask the user"),
4687
+ // Truncate at 30 chars; describe() says 20 to provide margin for the LLM
4688
+ header: z.string().transform((s) => s.slice(0, 30)).describe("Short label (max 20 chars)"),
4689
+ multiSelect: z.boolean().describe("Allow multiple selections"),
4690
+ options: z.array(optionSchema).min(2).max(4).describe("Available options for the user to choose from")
4691
+ });
4692
+ z.object({
4693
+ questions: z.array(questionSchema).min(1).max(4).describe("Questions to ask the user (1-4 questions)")
4694
+ });
4695
+ var SuccessVersion = z.object({
4696
+ status: z.literal("success"),
4697
+ answers: z.record(z.string(), z.string()).describe("Map of question text to user's answer")
4698
+ });
4699
+ var ErrorVersion = z.object({
4700
+ status: z.literal("error"),
4701
+ message: z.string()
4702
+ });
4703
+ var askUserQuestionResultSchema = z.discriminatedUnion("status", [
4704
+ SuccessVersion,
4705
+ ErrorVersion
4706
+ ]);
4707
+ z.object({
4708
+ tool: z.literal(ASK_USER_QUESTION).default(ASK_USER_QUESTION),
4709
+ result: askUserQuestionResultSchema
4710
+ });
4711
+
4712
+ // ../shared/dist/src/ai/schema/message.js
4713
+ var isAskUserQuestionPart = (part) => {
4714
+ return part.type === `tool-${ASK_USER_QUESTION}`;
4715
+ };
4716
+ var getMessageTextContent = (message) => {
4717
+ const content = message.parts.reduce((content2, part) => {
4718
+ if (part.type === "text") {
4719
+ return content2 + part.text;
4720
+ }
4721
+ return content2;
4722
+ }, "");
4723
+ if (content.trim().length === 0) {
4724
+ return void 0;
4725
+ }
4726
+ return content;
4727
+ };
4728
+ var GENERATE_DATA_REPORT = "generateDataReport";
4729
+ var SqlErrorCategory = z.enum([
4730
+ // Infrastructure errors (retriable - SQL might still be valid)
4731
+ "timeout",
4732
+ "connection_error",
4733
+ "auth_error",
4734
+ "resource_exhausted",
4735
+ // SQL Schema errors (SQL references non-existent objects)
4736
+ "table_not_found",
4737
+ "column_not_found",
4738
+ "schema_not_found",
4739
+ "view_not_found",
4740
+ "function_not_found",
4741
+ // SQL Syntax errors
4742
+ "syntax_error",
4743
+ // SQL Semantic errors
4744
+ "ambiguous_column",
4745
+ "type_mismatch",
4746
+ "invalid_cast",
4747
+ "invalid_argument",
4748
+ // SQL Runtime errors
4749
+ "division_by_zero",
4750
+ "constraint_violation",
4751
+ // Access errors
4752
+ "permission_denied",
4753
+ // Fallback
4754
+ "unknown"
4755
+ ]);
4756
+ var SqlGenerationErrorInfo = z.object({
4757
+ error_message: z.string(),
4758
+ category: SqlErrorCategory,
4759
+ details: z.string().nullish(),
4760
+ hint: z.string().nullish(),
4761
+ line_num: z.number().nullish(),
4762
+ col_num: z.number().nullish()
4763
+ });
4764
+ var SuccessVersion2 = z.object({
4765
+ status: z.literal("success"),
4766
+ public: z.object({
4767
+ flowDataId: z.number(),
4768
+ reportId: z.string(),
4769
+ answer: z.string().nullish(),
4770
+ title: z.string().nullish()
4771
+ }),
4772
+ private: z.object({
4773
+ sql: z.string(),
4774
+ dataReportSummary: z.string()
4775
+ })
4776
+ });
4777
+ var RedactedSuccessVersion = SuccessVersion2.omit({
4778
+ private: true
4779
+ });
4780
+ var ErrorVersion2 = z.object({
4781
+ status: z.literal("error"),
4782
+ message: z.string(),
4783
+ errorInfo: SqlGenerationErrorInfo.optional(),
4784
+ failedSql: z.string().optional()
4785
+ });
4786
+ var RedactedErrorVersion = z.object({
4787
+ status: z.literal("error"),
4788
+ category: SqlErrorCategory.optional()
4789
+ });
4790
+ var GenerateDataReportResponse = z.object({
4791
+ tool: z.literal(GENERATE_DATA_REPORT).default(GENERATE_DATA_REPORT),
4792
+ result: z.discriminatedUnion("status", [SuccessVersion2, ErrorVersion2]).optional()
4793
+ });
4794
+ GenerateDataReportResponse.extend({
4795
+ result: z.discriminatedUnion("status", [
4796
+ SuccessVersion2.omit({ private: true }),
4797
+ RedactedErrorVersion
4798
+ ]).optional()
4799
+ });
4800
+ z.object({
4801
+ rawRequest: z.string().describe("The user message that triggered this tool call. Usually exactly what they typed. For edge cases like 'do it again' or option selection '2', resolve to the actual request content. Do not extrapolate or add assumptions."),
4802
+ userRequest: z.string().describe("Complete, self-contained description of the data report to generate."),
4803
+ isNewAnalysisGoal: z.boolean().describe("Indicates whether this request represents a new analysis goal very different from the current conversation flow (true), or continues/modifies the existing analysis (false)."),
4804
+ difficultyLevel: z.enum(["simple", "moderate", "complex"]).describe("Complexity level of the SQL query based on the user request.")
4805
+ });
4806
+ var outputResultSchema = z.discriminatedUnion("status", [SuccessVersion2, ErrorVersion2]).optional();
4807
+ z.object({
4808
+ tool: z.literal(GENERATE_DATA_REPORT),
4809
+ result: outputResultSchema
4810
+ });
4811
+ z.object({
4812
+ tool: z.literal(GENERATE_DATA_REPORT),
4813
+ result: z.discriminatedUnion("status", [
4814
+ RedactedSuccessVersion,
4815
+ RedactedErrorVersion
4816
+ ]).optional()
4817
+ });
4818
+ var GENERATE_VISUALIZATION = "generateVisualization";
4819
+ var SuccessVersion3 = z.object({
4820
+ status: z.literal("success"),
4821
+ public: z.object({
4822
+ flowDataId: z.number(),
4823
+ reportId: z.string(),
4824
+ flowDataVisualizationId: z.number(),
4825
+ visualizationId: z.string(),
4826
+ title: z.string().nullish(),
4827
+ type: z.string().nullish()
4828
+ }),
4829
+ private: z.object({
4830
+ sql: z.string().optional(),
4831
+ dataReportSummary: z.string().optional()
4832
+ })
4833
+ });
4834
+ var RedactedSuccessVersion2 = SuccessVersion3.omit({
4835
+ private: true
4836
+ });
4837
+ var ErrorVersion3 = z.object({
4838
+ status: z.literal("error"),
4839
+ message: z.string()
4840
+ });
4841
+ var GenerateVisualizationResponse = z.object({
4842
+ tool: z.literal(GENERATE_VISUALIZATION).default(GENERATE_VISUALIZATION),
4843
+ result: z.discriminatedUnion("status", [SuccessVersion3, ErrorVersion3]).optional()
4844
+ });
4845
+ GenerateVisualizationResponse.extend({
4846
+ result: z.discriminatedUnion("status", [
4847
+ SuccessVersion3.omit({ private: true }),
4848
+ ErrorVersion3
4849
+ ]).optional()
4850
+ });
4851
+ z.object({
4852
+ reportId: z.number().or(z.uuid()).describe("The ID (legacy numeric id, or new uuid) of the report to visualize. Use output from generateDataReport."),
4853
+ chartType: z.enum(["bar", "line/area", "scatter", "pie"]).describe("Type of visualization to generate"),
4854
+ explanations: z.string().describe("Mandatory instructions for the visualization engine. This must include: 1) Aggregation logic (e.g., 'Sum revenue', 'Count IDs'), 2) Grouping details, 3) Limits for high-cardinality data (e.g., 'Sort descending and keep only the Top 10 results'), and 4) The specific columns to display on the plot (identifying metrics, axis, and dimensions).")
4855
+ });
4856
+ var outputResultSchema2 = z.discriminatedUnion("status", [SuccessVersion3, ErrorVersion3]).optional();
4857
+ z.object({
4858
+ tool: z.literal(GENERATE_VISUALIZATION),
4859
+ result: outputResultSchema2
4860
+ });
4861
+ z.object({
4862
+ tool: z.literal(GENERATE_VISUALIZATION),
4863
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion2, ErrorVersion3]).optional()
4864
+ });
4865
+ var GET_AVAILABLE_COLUMNS_FOR_TABLE = "getAvailableColumnsForTable";
4866
+ var ColumnMetadataSchema2 = z.object({
4867
+ // Always returned (not gated by any flag)
4868
+ name: z.string(),
4869
+ // includeDescriptions flag
4870
+ description: z.string().nullable().optional(),
4871
+ // includeDataTypes flag
4872
+ data_type: z.string().nullable().optional(),
4873
+ canonical_data_type: z.string().nullable().optional(),
4874
+ // includeSampleValues flag
4875
+ sample_values: z.array(z.unknown()).nullable().optional(),
4876
+ // includeStatistics flag
4877
+ null_percentage: z.number().nullable().optional(),
4878
+ unique_values: z.number().nullable().optional(),
4879
+ min_value: z.number().nullable().optional(),
4880
+ max_value: z.number().nullable().optional(),
4881
+ min_date: z.string().nullable().optional(),
4882
+ max_date: z.string().nullable().optional(),
4883
+ has_null: z.boolean().nullable().optional(),
4884
+ // includeFreshness flag
4885
+ updated_at: z.string().nullable().optional()
4886
+ });
4887
+ var SuccessVersion4 = z.object({
4888
+ status: z.literal("success"),
4889
+ public: z.looseObject({}),
4890
+ private: z.object({
4891
+ message: z.string().optional(),
4892
+ columns: ColumnMetadataSchema2.array()
4893
+ })
4894
+ });
4895
+ var RedactedSuccessVersion3 = SuccessVersion4.omit({
4896
+ private: true
4897
+ });
4898
+ var ErrorVersion4 = z.object({
4899
+ status: z.literal("error"),
4900
+ message: z.string()
4901
+ });
4902
+ var GetAvailableColumnsForTableResponse = z.object({
4903
+ tool: z.literal(GET_AVAILABLE_COLUMNS_FOR_TABLE).default(GET_AVAILABLE_COLUMNS_FOR_TABLE),
4904
+ result: z.discriminatedUnion("status", [SuccessVersion4, ErrorVersion4]).optional()
4905
+ });
4906
+ GetAvailableColumnsForTableResponse.extend({
4907
+ result: z.discriminatedUnion("status", [
4908
+ SuccessVersion4.omit({ private: true }),
4909
+ ErrorVersion4
4910
+ ]).optional()
4911
+ });
4912
+ z.object({
4913
+ dataset: z.string().describe("The dataset (schema) the table belongs to."),
4914
+ table_name: z.string().describe("A table name of the database for which to retrieve all column names and information."),
4915
+ includeDescriptions: z.boolean().default(true).describe("Include semantic column descriptions in metadata. Default: true."),
4916
+ includeDataTypes: z.boolean().default(true).describe("Include canonical and raw data types in metadata. Default: true."),
4917
+ includeSampleValues: z.boolean().default(false).describe("Include indexing-time snapshot example values in metadata. Use only for illustrative examples, NOT for min/max questions. Default: false."),
4918
+ includeStatistics: z.boolean().default(false).describe("Include min/max, cardinality, and null statistics in metadata. Set to true when answering questions about extremes or data distribution shape (but not full distributions, which require querying the data directly). Default: false."),
4919
+ includeFreshness: z.boolean().default(false).describe("Include last synced timestamp for columns. Set to true when answering questions about data freshness or when the data was last updated. Default: false.")
4920
+ });
4921
+ var outputResultSchema3 = z.discriminatedUnion("status", [SuccessVersion4, ErrorVersion4]).optional();
4922
+ z.object({
4923
+ tool: z.literal(GET_AVAILABLE_COLUMNS_FOR_TABLE),
4924
+ result: outputResultSchema3
4925
+ });
4926
+ z.object({
4927
+ tool: z.literal(GET_AVAILABLE_COLUMNS_FOR_TABLE),
4928
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion3, ErrorVersion4]).optional()
4929
+ });
4930
+ var GET_AVAILABLE_TABLES = "getAvailableTables";
4931
+ var SuccessVersion5 = z.object({
4932
+ status: z.literal("success"),
4933
+ public: z.looseObject({}),
4934
+ private: z.object({
4935
+ tables: z.array(z.object({
4936
+ dataset: z.string(),
4937
+ table_name: z.string(),
4938
+ description: z.string().nullable()
4939
+ }))
4940
+ })
4941
+ });
4942
+ var RedactedSuccessVersion4 = SuccessVersion5.omit({
4943
+ private: true
4944
+ });
4945
+ var ErrorVersion5 = z.object({
4946
+ status: z.literal("error"),
4947
+ message: z.string()
4948
+ });
4949
+ var GetAvailableTablesResponse = z.object({
4950
+ tool: z.literal(GET_AVAILABLE_TABLES).default(GET_AVAILABLE_TABLES),
4951
+ result: z.discriminatedUnion("status", [SuccessVersion5, ErrorVersion5]).optional()
4952
+ });
4953
+ GetAvailableTablesResponse.extend({
4954
+ result: z.discriminatedUnion("status", [
4955
+ SuccessVersion5.omit({ private: true }),
4956
+ ErrorVersion5
4957
+ ]).optional()
4958
+ });
4959
+ z.object({}).describe("This tool requires no parameters and returns all table names available in the database.");
4960
+ var outputResultSchema4 = z.discriminatedUnion("status", [SuccessVersion5, ErrorVersion5]).optional();
4961
+ z.object({
4962
+ tool: z.literal(GET_AVAILABLE_TABLES),
4963
+ result: outputResultSchema4
4964
+ });
4965
+ z.object({
4966
+ tool: z.literal(GET_AVAILABLE_TABLES),
4967
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion4, ErrorVersion5]).optional()
4968
+ });
4969
+ var PAGINATE_DATA_REPORT = "paginateDataReport";
4970
+ z.object({
4971
+ reportId: z.number().describe("The ID of the report to fetch data from"),
4972
+ limit: z.number().optional().default(50).describe("Number of rows to fetch (default 50)"),
4973
+ offset: z.number().optional().default(0).describe("Row offset - skip this many rows from the start (default 0)"),
4974
+ skipSampleRows: z.boolean().optional().default(true).describe("Skip rows already shown in the data_sample from generateDataReport (default true). Set to false only if you need to re-fetch from the beginning.")
4975
+ });
4976
+ var SuccessVersion6 = z.object({
4977
+ status: z.literal("success"),
4978
+ public: z.object({
4979
+ totalRows: z.number(),
4980
+ fetchedRows: z.number(),
4981
+ offset: z.number(),
4982
+ hasMore: z.boolean()
4983
+ }),
4984
+ /* the data is in the private field to avoid sending it to the frontend
4985
+ * this is not a security feature as the user has access to the report anyway */
4986
+ private: z.object({
4987
+ data: z.array(z.record(z.string(), z.unknown()))
4988
+ })
4989
+ });
4990
+ var RedactedSuccessVersion5 = SuccessVersion6.omit({
4991
+ private: true
4992
+ });
4993
+ var ErrorVersion6 = z.object({
4994
+ status: z.literal("error"),
4995
+ message: z.string()
4996
+ });
4997
+ var PaginateDataReportResponse = z.object({
4998
+ tool: z.literal(PAGINATE_DATA_REPORT).default(PAGINATE_DATA_REPORT),
4999
+ result: z.discriminatedUnion("status", [SuccessVersion6, ErrorVersion6]).optional()
5000
+ });
5001
+ PaginateDataReportResponse.extend({
5002
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion5, ErrorVersion6]).optional()
5003
+ });
5004
+ var outputResultSchema5 = z.discriminatedUnion("status", [SuccessVersion6, ErrorVersion6]).optional();
5005
+ z.object({
5006
+ tool: z.literal(PAGINATE_DATA_REPORT),
5007
+ result: outputResultSchema5
5008
+ });
5009
+ z.object({
5010
+ tool: z.literal(PAGINATE_DATA_REPORT),
5011
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion5, ErrorVersion6]).optional()
5012
+ });
5013
+ var THINK = "think";
5014
+ var outputResultSchema6 = z.object({
5015
+ status: z.literal("success"),
5016
+ public: z.looseObject({}),
5017
+ private: z.looseObject({})
5018
+ });
5019
+ var ThinkResponse = z.object({
5020
+ tool: z.literal(THINK).default(THINK),
5021
+ result: outputResultSchema6.optional()
5022
+ });
5023
+ ThinkResponse.extend({
5024
+ result: outputResultSchema6.omit({ private: true }).optional()
5025
+ });
5026
+ z.object({
5027
+ thought: z.string().describe("A thought to think about.")
5028
+ });
5029
+ var VALUE_BASED_COLUMN_SEARCH = "valueBasedColumnSearch";
5030
+ var SuccessVersion7 = z.object({
5031
+ status: z.literal("success"),
5032
+ public: z.looseObject({}),
5033
+ private: z.object({
5034
+ message: z.string().optional(),
5035
+ columns: z.object({
5036
+ name: z.string(),
5037
+ data_type: z.string().nullable(),
5038
+ description: z.string().nullable(),
5039
+ table: z.object({
5040
+ table_name: z.string(),
5041
+ description: z.string().nullable()
5042
+ }),
5043
+ matched_values: z.string().array()
5044
+ }).array()
5045
+ })
5046
+ });
5047
+ var RedactedSuccessVersion6 = SuccessVersion7.omit({
5048
+ private: true
5049
+ });
5050
+ var ErrorVersion7 = z.object({
5051
+ status: z.literal("error"),
5052
+ message: z.string()
5053
+ });
5054
+ var ValueBasedColumnSearchResponse = z.object({
5055
+ tool: z.literal(VALUE_BASED_COLUMN_SEARCH).default(VALUE_BASED_COLUMN_SEARCH),
5056
+ result: z.discriminatedUnion("status", [SuccessVersion7, ErrorVersion7]).optional()
5057
+ });
5058
+ ValueBasedColumnSearchResponse.extend({
5059
+ result: z.discriminatedUnion("status", [
5060
+ SuccessVersion7.omit({ private: true }),
5061
+ ErrorVersion7
5062
+ ]).optional()
5063
+ });
5064
+ z.object({
5065
+ value: z.string().describe("A literal data value as it would appear in a cell (e.g. 'France', 'PRD-00123', 'Apple iPhone'). Must NOT be a column name or concept.")
5066
+ });
5067
+ var outputResultSchema7 = z.discriminatedUnion("status", [SuccessVersion7, ErrorVersion7]).optional();
5068
+ z.object({
5069
+ tool: z.literal(VALUE_BASED_COLUMN_SEARCH),
5070
+ result: outputResultSchema7
5071
+ });
5072
+ z.object({
5073
+ tool: z.literal(VALUE_BASED_COLUMN_SEARCH),
5074
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion6, ErrorVersion7]).optional()
5075
+ });
5076
+ var WEB_SEARCH = "webSearch";
5077
+ var Source = z.object({
5078
+ sourceType: z.literal("url"),
5079
+ id: z.string(),
5080
+ url: z.string(),
5081
+ title: z.string()
5082
+ });
5083
+ var SuccessVersion8 = z.object({
5084
+ status: z.literal("success"),
5085
+ public: z.object({
5086
+ sources: z.array(Source).optional().describe("Array of source objects.")
5087
+ }),
5088
+ private: z.object({
5089
+ answer: z.string().optional().describe("The answer from the search results, if successful.")
5090
+ })
5091
+ });
5092
+ var RedactedSuccessVersion7 = SuccessVersion8.omit({
5093
+ private: true
5094
+ });
5095
+ var ErrorVersion8 = z.object({
5096
+ status: z.literal("error"),
5097
+ message: z.string()
5098
+ });
5099
+ var WebSearchToolResponse = z.object({
5100
+ tool: z.literal("search").default("search"),
5101
+ result: z.discriminatedUnion("status", [SuccessVersion8, ErrorVersion8]).optional()
5102
+ });
5103
+ WebSearchToolResponse.extend({
5104
+ result: z.discriminatedUnion("status", [
5105
+ SuccessVersion8.omit({ private: true }),
5106
+ ErrorVersion8
5107
+ ]).optional()
5108
+ });
5109
+ z.object({
5110
+ query: z.string().describe("Specific search query focused on external factors that relate to the current analysis (e.g., 'China India trade policy changes 2024', 'housing market interest rates Q3 2024'). Should target actionable business context, not general information."),
5111
+ fromDate: z.iso.date().optional().describe("Only include content published after this date (YYYY-MM-DD). Useful for recent news or time-specific analysis."),
5112
+ toDate: z.iso.date().optional().describe("Only include content published before this date (YYYY-MM-DD). Combine with fromDate for a date range.")
5113
+ });
5114
+ var outputResultSchema8 = z.discriminatedUnion("status", [SuccessVersion8, ErrorVersion8]).optional();
5115
+ z.object({
5116
+ result: outputResultSchema8
5117
+ });
5118
+ z.object({
5119
+ tool: z.literal("search"),
5120
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion7, ErrorVersion8]).optional()
5121
+ });
5122
+
5123
+ export { ASK_USER_QUESTION, BrowserStorageAdapter, CHAT_ALLOWED_FILE_MEDIA_TYPES, CHAT_FILE_ACCEPT, CHAT_MAX_COMBINED_FILE_SIZE, CHAT_MAX_FILE_COUNT, CHAT_MAX_FILE_SIZE, CHECK_KEY, DirectAuthProvider, ExternalAuthProvider, GENERATE_DATA_REPORT, GENERATE_VISUALIZATION, GET_AVAILABLE_COLUMNS_FOR_TABLE, GET_AVAILABLE_TABLES, MageMetricsChatTransport, MageMetricsClient, MageMetricsEventEmitter, MemoryStorageAdapter, PAGINATE_DATA_REPORT, THINK, TOKEN_STORAGE_KEY, UPLOADED_FILE_REF_PREFIX, VALUE_BASED_COLUMN_SEARCH, WEB_SEARCH, getMessageTextContent, getPublicApiClient, getUploadedFileIdFromUrl, hasOnlyInitialUserMessage, isAskUserQuestionPart, isFrontendV1Visualization, isFrontendV1VisualizationWithData, isFrontendV2Visualization, isFrontendV2VisualizationWithData, toSearchParams, toUploadedFileRefUrl, validateUploadedFiles };