@magemetrics/core 0.12.2 → 0.14.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 (4) hide show
  1. package/README.md +220 -0
  2. package/dist/index.d.ts +1670 -137
  3. package/dist/index.js +1796 -430
  4. package/package.json +9 -9
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { sha256 } from '@noble/hashes/sha2.js';
2
- import z8, { 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.12.2"};
61
+ version: "0.14.0"};
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.14/node_modules/hono/dist/router/reg-exp-router/node.js
486
+ // ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/router/reg-exp-router/node.js
486
487
  new Set(".\\+*[^]$()");
487
488
  var createRoute = (routeConfig) => {
488
489
  const route = {
@@ -494,6 +495,7 @@ var createRoute = (routeConfig) => {
494
495
  return Object.defineProperty(route, "getRoutingPath", { enumerable: false });
495
496
  };
496
497
  extendZodWithOpenApi(z);
498
+ var ExternalUserIdSchema = z.string().min(1, "external_user_id must not be empty").max(58, "external_user_id must be at most 58 characters").regex(/^[a-z0-9._+-]+$/, "external_user_id must contain only lowercase alphanumeric characters, dots, hyphens, underscores, and plus signs").refine((s) => !s.startsWith(".") && !s.endsWith("."), "external_user_id must not start or end with a dot").refine((s) => !s.includes(".."), "external_user_id must not contain consecutive dots");
497
499
 
498
500
  // ../shared/dist/src/endpoints/auth.routes.js
499
501
  var GetApiInformationInputSchema = z.object({
@@ -626,6 +628,143 @@ var ExchangeExternalToken = createRoute({
626
628
  }
627
629
  }
628
630
  });
631
+ var CreateEmbedTokenInputSchema = z.object({
632
+ uid: ExternalUserIdSchema,
633
+ attributes: z.record(z.string(), z.unknown()),
634
+ applicationName: z.string().trim().min(1).optional()
635
+ });
636
+ var CreateEmbedTokenOutputSchema = z.object({
637
+ token: z.string(),
638
+ expires_at: z.iso.datetime()
639
+ });
640
+ createRoute({
641
+ method: "post",
642
+ path: "/api/v1/auth/embed-tokens",
643
+ operationId: "createEmbedToken",
644
+ tags: ["internal"],
645
+ request: {
646
+ body: {
647
+ required: true,
648
+ content: {
649
+ "application/json": {
650
+ schema: CreateEmbedTokenInputSchema
651
+ }
652
+ }
653
+ }
654
+ },
655
+ responses: {
656
+ 200: {
657
+ content: {
658
+ "application/json": {
659
+ schema: CreateEmbedTokenOutputSchema
660
+ }
661
+ },
662
+ description: "Create a short-lived Magemetrics embed assertion token"
663
+ },
664
+ 400: {
665
+ content: {
666
+ "application/json": {
667
+ schema: z.object({ error: z.string() })
668
+ }
669
+ },
670
+ description: "Invalid input"
671
+ },
672
+ 401: {
673
+ content: {
674
+ "application/json": {
675
+ schema: z.object({ error: z.string() })
676
+ }
677
+ },
678
+ description: "Authentication required"
679
+ },
680
+ 403: {
681
+ content: {
682
+ "application/json": {
683
+ schema: z.object({ error: z.string() })
684
+ }
685
+ },
686
+ description: "Service account required"
687
+ },
688
+ 500: {
689
+ content: {
690
+ "application/json": {
691
+ schema: z.object({ error: z.string() })
692
+ }
693
+ },
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"
765
+ }
766
+ }
767
+ });
629
768
 
630
769
  // src/core/types.ts
631
770
  var TOKEN_STORAGE_KEY = "mm-ai-sp-token";
@@ -642,6 +781,7 @@ var ExternalAuthProvider = class {
642
781
  processedJwt = /* @__PURE__ */ Symbol("initial");
643
782
  userId = null;
644
783
  events = new MageMetricsEventEmitter();
784
+ authSubscription = null;
645
785
  constructor(config) {
646
786
  this.config = config;
647
787
  }
@@ -705,6 +845,12 @@ var ExternalAuthProvider = class {
705
845
  stopAutoRefresh() {
706
846
  return this.supabaseClient?.stopAutoRefresh();
707
847
  }
848
+ destroy() {
849
+ this.authSubscription?.unsubscribe();
850
+ this.authSubscription = null;
851
+ void this.supabaseClient?.stopAutoRefresh();
852
+ this.supabaseClient = null;
853
+ }
708
854
  async getApiInformation() {
709
855
  if (!this.noAuthApiClient || !this.authApiResponse) {
710
856
  this.noAuthApiClient = createApiClient2({
@@ -732,7 +878,9 @@ var ExternalAuthProvider = class {
732
878
  storage: this.config.storage,
733
879
  ...this.config.authOptions
734
880
  });
735
- this.supabaseClient.onAuthStateChange((event, session) => {
881
+ const {
882
+ data: { subscription }
883
+ } = this.supabaseClient.onAuthStateChange((event, session) => {
736
884
  console.debug("Supabase auth state change:", event, !!session);
737
885
  if (event === "SIGNED_IN" && session?.user) {
738
886
  if (this.userId !== session.user.id && this.userId !== null) {
@@ -749,6 +897,7 @@ var ExternalAuthProvider = class {
749
897
  this.setState("initializing");
750
898
  }
751
899
  });
900
+ this.authSubscription = subscription;
752
901
  }
753
902
  }
754
903
  async handleAuthentication() {
@@ -845,9 +994,45 @@ var ExternalAuthProvider = class {
845
994
  }
846
995
  }
847
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
+ };
848
1030
  var SupabaseHeaderSchema = z.object({
849
1031
  [HEADER_SP_TOKEN]: z.string().optional()
850
1032
  });
1033
+ var SupabaseScopedHeaderSchema = SupabaseHeaderSchema.extend({
1034
+ [HEADER_APPLICATION_NAME]: z.string().optional()
1035
+ });
851
1036
  var FEEDBACK_OPTIONS = [
852
1037
  { label: "Helpful", value: "helpful" },
853
1038
  { label: "Partially helpful", value: "partially helpful" },
@@ -904,122 +1089,330 @@ var BusinessExplanationSchema = z.object({
904
1089
  explanation: z.string()
905
1090
  }))
906
1091
  });
1092
+ dayjs.extend(relativeTime);
1093
+ dayjs.extend(customParseFormat);
1094
+ dayjs.extend(utc);
1095
+ dayjs.extend(timezone);
1096
+ var daysjs_default = dayjs;
907
1097
 
908
- // ../shared/dist/src/schemas/flows.js
909
- var FlowStepSchema = z.object({
910
- name: z.string(),
911
- status: z.enum(["running", "completed", "failed", "awaiting_input"]),
912
- output: z.looseObject({}).or(z.unknown().array()).nullable()
913
- });
914
- var DatabaseFlowSchema = z.object({
915
- created_at: z.string(),
916
- id: z.string(),
917
- request: z.string(),
918
- title: z.string().nullable(),
919
- user_id: z.string().nullable(),
920
- application_id: z.number().nullable().optional(),
921
- flow_steps: z.array(FlowStepSchema),
922
- // Token usage tracking (provider-reported)
923
- context_tokens: z.number().optional(),
924
- acc_input_tokens: z.number().optional(),
925
- acc_output_tokens: z.number().optional()
926
- });
927
- z.object({
928
- table: z.string(),
929
- schema: z.string(),
930
- database: z.string()
931
- });
932
- var FrontendFlowSchema = DatabaseFlowSchema.omit({
933
- flow_steps: true
934
- });
935
- var FrontendRecentFlowsSchema = DatabaseFlowSchema.omit({
936
- flow_steps: true
937
- });
938
- var ReportColumnSchema = z.looseObject({
939
- position: z.number().nonnegative().optional(),
940
- data_type: z.string(),
941
- null_count: z.number().nullable(),
942
- unique_count: z.number().nullable(),
943
- unique_percentage: z.number().nullable(),
944
- // Numeric column statistics
945
- min_value: z.number().nullable().optional(),
946
- max_value: z.number().nullable().optional(),
947
- avg_value: z.number().nullable().optional(),
948
- median_value: z.number().nullable().optional(),
949
- std_value: z.number().nullable().optional(),
950
- // Date column statistics
951
- min_date: z.string().nullable().optional(),
952
- max_date: z.string().nullable().optional(),
953
- // String column statistics
954
- min_length: z.number().nullable().optional(),
955
- max_length: z.number().nullable().optional(),
956
- avg_length: z.number().nullable().optional()
957
- });
958
- var MaterializationStatusSchema = z.enum([
959
- "completed",
960
- "running",
961
- "failed"
962
- ]);
963
- var MaterializationFieldsSchema = z.object({
964
- is_materialized: z.boolean().nullable(),
965
- last_materialized_at: z.string().nullable(),
966
- materialized_error_message: z.string().nullable(),
967
- materialized_status: MaterializationStatusSchema.nullable()
968
- });
969
- var ReportSchema = z.object({
970
- created_at: z.string(),
971
- flow_id: z.string(),
972
- id: z.number().openapi({
973
- description: "Deprecated: use uuid.",
974
- deprecated: true
975
- }),
976
- uuid: z.string(),
977
- is_sample: z.boolean(),
978
- schema: z.string(),
979
- sql: z.string(),
980
- table: z.string(),
981
- title: z.string(),
982
- request: z.string().nullable(),
983
- data_sample: z.array(z.record(z.string(), z.unknown())),
984
- data_summary: z.looseObject({
985
- columns: z.record(z.string(), ReportColumnSchema)
986
- }),
987
- status: z.string().nullable(),
988
- is_removed: z.boolean(),
989
- ...MaterializationFieldsSchema.shape
990
- });
991
- var FrontendReportSchema = ReportSchema.omit({
992
- sql: true,
993
- table: true,
994
- data_sample: true,
995
- is_sample: true,
996
- schema: true
997
- });
998
- var ReportDataSchema = z.looseObject({}).array().openapi("ReportData");
999
- var ReportColumnsSchema = z.object({
1000
- name: z.string(),
1001
- data_type: z.string()
1002
- }).array();
1003
- var CanonicalDataTypeSchema = z.enum([
1004
- "numeric",
1005
- "boolean",
1006
- "datetime",
1007
- "text",
1008
- "array",
1009
- "json",
1010
- "other"
1011
- ]);
1012
- z.object({
1013
- render_type: z.string().nullish(),
1014
- unit: z.string().nullish(),
1015
- canonical_data_type: CanonicalDataTypeSchema.nullish()
1016
- });
1017
- var FrontendReportColumnsSchema = z.object({
1018
- ...ReportColumnsSchema.element.shape,
1019
- dataType: z.string(),
1020
- renderType: z.string().optional(),
1098
+ // ../shared/dist/src/data/FormattedData.js
1099
+ var numberFormatCache = /* @__PURE__ */ new Map();
1100
+ var getNumberFormatter = (minimumFractionDigits, maximumFractionDigits, useGrouping) => {
1101
+ const key = `${minimumFractionDigits}:${maximumFractionDigits}:${useGrouping}`;
1102
+ let formatter = numberFormatCache.get(key);
1103
+ if (!formatter) {
1104
+ formatter = new Intl.NumberFormat(void 0, {
1105
+ minimumFractionDigits,
1106
+ maximumFractionDigits,
1107
+ useGrouping
1108
+ });
1109
+ numberFormatCache.set(key, formatter);
1110
+ }
1111
+ return formatter;
1112
+ };
1113
+ var formatWithAutoPrecision = (value, options = {}) => {
1114
+ const { minPrecision = 0, maxPrecision = 6, trimZeros = true, useGrouping = true } = options;
1115
+ if (typeof value !== "number" || isNaN(value)) {
1116
+ return String(value);
1117
+ }
1118
+ if (value === 0) {
1119
+ return "0";
1120
+ }
1121
+ const absValue = Math.abs(value);
1122
+ let maximumFractionDigits;
1123
+ if (absValue >= 1e3) {
1124
+ maximumFractionDigits = 0;
1125
+ } else if (absValue >= 100) {
1126
+ maximumFractionDigits = 1;
1127
+ } else if (absValue >= 10) {
1128
+ maximumFractionDigits = 2;
1129
+ } else if (absValue >= 1) {
1130
+ maximumFractionDigits = 3;
1131
+ } else if (absValue >= 0.1) {
1132
+ maximumFractionDigits = 4;
1133
+ } else if (absValue >= 0.01) {
1134
+ maximumFractionDigits = 5;
1135
+ } else {
1136
+ maximumFractionDigits = maxPrecision;
1137
+ if (absValue > 0) {
1138
+ const exponent = Math.floor(Math.log10(absValue));
1139
+ if (exponent < 0) {
1140
+ maximumFractionDigits = Math.min(Math.abs(exponent) + 2, maxPrecision);
1141
+ }
1142
+ }
1143
+ }
1144
+ maximumFractionDigits = Math.max(maximumFractionDigits, minPrecision);
1145
+ const formatter = getNumberFormatter(trimZeros ? 0 : maximumFractionDigits, maximumFractionDigits, useGrouping);
1146
+ return formatter.format(value);
1147
+ };
1148
+ var MIN_VALID_YEAR = 1900;
1149
+ var MAX_VALID_YEAR = 2200;
1150
+ var zonedatetime = (format, zone) => ({ format, type: "zonedatetime", zone });
1151
+ var datetime = (format) => ({ format, type: "datetime" });
1152
+ var date = (format) => ({ format, type: "date" });
1153
+ var DATE_FORMATS = [
1154
+ // ISO 8601 formats
1155
+ zonedatetime("YYYY-MM-DDTHH:mm:ss.SSSZ", "UTC"),
1156
+ zonedatetime("YYYY-MM-DDTHH:mm:ssZ", "UTC"),
1157
+ zonedatetime("YYYY-MM-DDTHH:mmZ", "UTC"),
1158
+ datetime("YYYY-MM-DDTHH:mm:ss"),
1159
+ datetime("YYYY-MM-DDTHH:mm"),
1160
+ date("YYYY-MM-DDT"),
1161
+ // Standard date formats
1162
+ date("YYYY-MM-DD"),
1163
+ date("YYYY/MM/DD"),
1164
+ date("DD-MM-YYYY"),
1165
+ date("DD/MM/YYYY"),
1166
+ date("MM-DD-YYYY"),
1167
+ date("MM/DD/YYYY"),
1168
+ // Date time formats
1169
+ datetime("YYYY-MM-DD HH:mm:ss"),
1170
+ datetime("YYYY-MM-DD HH:mm"),
1171
+ datetime("YYYY/MM/DD HH:mm:ss"),
1172
+ datetime("YYYY/MM/DD HH:mm"),
1173
+ datetime("DD-MM-YYYY HH:mm:ss"),
1174
+ datetime("DD-MM-YYYY HH:mm"),
1175
+ datetime("DD/MM/YYYY HH:mm:ss"),
1176
+ datetime("DD/MM/YYYY HH:mm"),
1177
+ datetime("MM-DD-YYYY HH:mm:ss"),
1178
+ datetime("MM-DD-YYYY HH:mm"),
1179
+ datetime("MM/DD/YYYY HH:mm:ss"),
1180
+ datetime("MM/DD/YYYY HH:mm")
1181
+ ];
1182
+ var isDateString = (value) => {
1183
+ if (typeof value !== "string")
1184
+ return { isValid: false };
1185
+ const stripped = value.replace(/[-/.:\s]/g, "");
1186
+ if (/^\d+$/.test(stripped)) {
1187
+ if (stripped.length < 6)
1188
+ return { isValid: false };
1189
+ if (value.length === stripped.length)
1190
+ return { isValid: false };
1191
+ }
1192
+ if (stripped.length > "YYYY-MM-DDTHH:mm:ss.SSS+00:00".length) {
1193
+ return { isValid: false };
1194
+ }
1195
+ for (const format of DATE_FORMATS) {
1196
+ let date2;
1197
+ try {
1198
+ if (format.type === "zonedatetime") {
1199
+ date2 = daysjs_default.tz(value, format.format, format.zone);
1200
+ } else {
1201
+ date2 = daysjs_default(value, format.format, true);
1202
+ }
1203
+ } catch {
1204
+ continue;
1205
+ }
1206
+ if (date2.isValid()) {
1207
+ const year = date2.year();
1208
+ if (year < MIN_VALID_YEAR || year > MAX_VALID_YEAR)
1209
+ continue;
1210
+ const isDateTime = format.type === "zonedatetime" || format.type == "datetime";
1211
+ return {
1212
+ isValid: true,
1213
+ parsedDate: date2,
1214
+ isDateTime
1215
+ };
1216
+ }
1217
+ }
1218
+ return { isValid: false };
1219
+ };
1220
+ var formatDataValue = (value, { replaceNullValue = true, formatHint } = {}) => {
1221
+ if (value === null || value === void 0) {
1222
+ return {
1223
+ display: replaceNullValue ? "empty" : null,
1224
+ sortValue: null
1225
+ };
1226
+ }
1227
+ let processedValue = value;
1228
+ if (typeof processedValue === "string") {
1229
+ try {
1230
+ const parsed = JSON.parse(processedValue);
1231
+ processedValue = parsed;
1232
+ } catch {
1233
+ }
1234
+ }
1235
+ if (processedValue && typeof processedValue === "object" && Object.keys(processedValue).length === 1 && "value" in processedValue) {
1236
+ const extractedValue = processedValue.value;
1237
+ const dateResult2 = isDateString(extractedValue);
1238
+ if (dateResult2.isValid) {
1239
+ return {
1240
+ display: dateResult2.isDateTime ? dateResult2.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult2.parsedDate.format("YYYY-MM-DD"),
1241
+ sortValue: dateResult2.parsedDate.valueOf()
1242
+ };
1243
+ }
1244
+ return {
1245
+ display: String(extractedValue),
1246
+ sortValue: extractedValue
1247
+ };
1248
+ }
1249
+ const dateResult = isDateString(processedValue);
1250
+ if (dateResult.isValid) {
1251
+ return {
1252
+ display: dateResult.isDateTime ? dateResult.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult.parsedDate.format("YYYY-MM-DD"),
1253
+ sortValue: dateResult.parsedDate.valueOf()
1254
+ };
1255
+ }
1256
+ if (typeof processedValue === "object") {
1257
+ const stringified = JSON.stringify(processedValue, null, 2);
1258
+ return {
1259
+ display: stringified,
1260
+ sortValue: stringified
1261
+ };
1262
+ }
1263
+ if (typeof processedValue === "boolean") {
1264
+ return {
1265
+ display: String(processedValue),
1266
+ sortValue: processedValue ? 1 : 0
1267
+ };
1268
+ }
1269
+ if (typeof processedValue === "number") {
1270
+ if (formatHint?.isLikelyYear !== void 0) {
1271
+ return {
1272
+ display: formatHint.isLikelyYear ? String(processedValue) : formatWithAutoPrecision(processedValue),
1273
+ sortValue: processedValue
1274
+ };
1275
+ }
1276
+ return {
1277
+ display: processedValue >= MIN_VALID_YEAR && processedValue <= MAX_VALID_YEAR && Number.isInteger(processedValue) ? String(processedValue) : formatWithAutoPrecision(processedValue),
1278
+ sortValue: processedValue
1279
+ };
1280
+ }
1281
+ return {
1282
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
1283
+ display: String(processedValue),
1284
+ sortValue: processedValue
1285
+ };
1286
+ };
1287
+
1288
+ // ../shared/dist/src/schemas/flows.js
1289
+ var FlowStepSchema = z.object({
1290
+ name: z.string(),
1291
+ status: z.enum(["running", "completed", "failed", "awaiting_input"]),
1292
+ output: z.looseObject({}).or(z.unknown().array()).nullable()
1293
+ });
1294
+ var DatabaseFlowSchema = z.object({
1295
+ created_at: z.string(),
1296
+ id: z.string(),
1297
+ request: z.string(),
1298
+ title: z.string().nullable(),
1299
+ user_id: z.string().nullable(),
1300
+ application_id: z.number().nullable().optional(),
1301
+ flow_steps: z.array(FlowStepSchema),
1302
+ // Token usage tracking (provider-reported)
1303
+ context_tokens: z.number().optional(),
1304
+ acc_input_tokens: z.number().optional(),
1305
+ acc_output_tokens: z.number().optional()
1306
+ });
1307
+ z.object({
1308
+ table: z.string(),
1309
+ schema: z.string(),
1310
+ database: z.string()
1311
+ });
1312
+ var FrontendFlowSchema = DatabaseFlowSchema.omit({
1313
+ flow_steps: true,
1314
+ context_tokens: true,
1315
+ acc_input_tokens: true,
1316
+ acc_output_tokens: true
1317
+ });
1318
+ var FrontendRecentFlowsSchema = DatabaseFlowSchema.omit({
1319
+ flow_steps: true,
1320
+ context_tokens: true,
1321
+ acc_input_tokens: true,
1322
+ acc_output_tokens: true
1323
+ });
1324
+ var ReportColumnSchema = z.looseObject({
1325
+ position: z.number().nonnegative().optional(),
1326
+ data_type: z.string(),
1327
+ null_count: z.number().nullable(),
1328
+ unique_count: z.number().nullable(),
1329
+ unique_percentage: z.number().nullable(),
1330
+ // Numeric column statistics
1331
+ min_value: z.number().nullable().optional(),
1332
+ max_value: z.number().nullable().optional(),
1333
+ avg_value: z.number().nullable().optional(),
1334
+ median_value: z.number().nullable().optional(),
1335
+ std_value: z.number().nullable().optional(),
1336
+ // Date column statistics
1337
+ min_date: z.string().nullable().optional(),
1338
+ max_date: z.string().nullable().optional(),
1339
+ // String column statistics
1340
+ min_length: z.number().nullable().optional(),
1341
+ max_length: z.number().nullable().optional(),
1342
+ avg_length: z.number().nullable().optional()
1343
+ });
1344
+ var MaterializationStatusSchema = z.enum([
1345
+ "completed",
1346
+ "running",
1347
+ "failed"
1348
+ ]);
1349
+ var MaterializationFieldsSchema = z.object({
1350
+ is_materialized: z.boolean().nullable(),
1351
+ last_materialized_at: z.string().nullable(),
1352
+ materialized_error_message: z.string().nullable(),
1353
+ materialized_status: MaterializationStatusSchema.nullable()
1354
+ });
1355
+ var ReportSchema = z.object({
1356
+ created_at: z.string(),
1357
+ flow_id: z.string().nullable(),
1358
+ id: z.number().openapi({
1359
+ description: "Deprecated: use uuid.",
1360
+ deprecated: true
1361
+ }),
1362
+ uuid: z.string(),
1363
+ is_sample: z.boolean(),
1364
+ schema: z.string(),
1365
+ sql: z.string(),
1366
+ table: z.string(),
1367
+ title: z.string(),
1368
+ request: z.string().nullable(),
1369
+ data_sample: z.array(z.record(z.string(), z.unknown())),
1370
+ data_summary: z.looseObject({
1371
+ columns: z.record(z.string(), ReportColumnSchema)
1372
+ }),
1373
+ status: z.string().nullable(),
1374
+ is_removed: z.boolean(),
1375
+ ...MaterializationFieldsSchema.shape
1376
+ });
1377
+ ReportSchema.omit({ flow_id: true });
1378
+ var FrontendReportSchema = ReportSchema.omit({
1379
+ flow_id: true,
1380
+ sql: true,
1381
+ table: true,
1382
+ data_sample: true,
1383
+ is_sample: true,
1384
+ schema: true
1385
+ });
1386
+ var ReportDataSchema = z.looseObject({}).array().openapi("ReportData");
1387
+ var ReportColumnsSchema = z.object({
1388
+ name: z.string(),
1389
+ data_type: z.string()
1390
+ }).array();
1391
+ var CanonicalDataTypeSchema = z.enum([
1392
+ "numeric",
1393
+ "boolean",
1394
+ "datetime",
1395
+ "text",
1396
+ "array",
1397
+ "json",
1398
+ "other"
1399
+ ]);
1400
+ z.object({
1401
+ render_type: z.string().nullish(),
1402
+ unit: z.string().nullish(),
1403
+ canonical_data_type: CanonicalDataTypeSchema.nullish()
1404
+ });
1405
+ var ColumnFormatHintSchema = z.object({
1406
+ isNumeric: z.boolean().optional(),
1407
+ isLikelyYear: z.boolean().optional()
1408
+ });
1409
+ var FrontendReportColumnsSchema = z.object({
1410
+ ...ReportColumnsSchema.element.shape,
1411
+ dataType: z.string(),
1412
+ renderType: z.string().optional(),
1021
1413
  unit: z.string().optional(),
1022
- canonicalDataType: CanonicalDataTypeSchema.optional()
1414
+ canonicalDataType: CanonicalDataTypeSchema.optional(),
1415
+ formatHint: ColumnFormatHintSchema.optional()
1023
1416
  }).array().openapi("ReportColumns");
1024
1417
  z.object({
1025
1418
  goal: z.string(),
@@ -1091,6 +1484,7 @@ var DataTableSchema = z.object({
1091
1484
  id: z.number(),
1092
1485
  dataset: z.string(),
1093
1486
  table_name: z.string(),
1487
+ database: z.string().nullable(),
1094
1488
  description: z.string().nullable(),
1095
1489
  primary_key_names: z.string().array(),
1096
1490
  row_count: z.number().nullable(),
@@ -1211,9 +1605,33 @@ var columnsQueryParams = z.string().transform((str) => {
1211
1605
  },
1212
1606
  type: "string"
1213
1607
  });
1608
+
1609
+ // ../shared/dist/src/schemas/chat/fileUpload.js
1610
+ var CHAT_MAX_FILE_SIZE = 10 * 1024 * 1024;
1611
+ var CHAT_MAX_TOTAL_FILE_BYTES_FOR_LLM = 15 * 1024 * 1024;
1612
+ var CHAT_MAX_COMBINED_FILE_SIZE = CHAT_MAX_TOTAL_FILE_BYTES_FOR_LLM;
1214
1613
  var CHAT_MAX_FILE_COUNT = 10;
1614
+ var UPLOADED_FILE_REF_PREFIX = "uploaded-file:";
1215
1615
  var CHAT_ALLOWED_FILE_MEDIA_TYPES = /* @__PURE__ */ new Set(["application/pdf"]);
1216
- [...CHAT_ALLOWED_FILE_MEDIA_TYPES].join(",");
1616
+ var CHAT_FILE_ACCEPT = [...CHAT_ALLOWED_FILE_MEDIA_TYPES].join(",");
1617
+ var getUploadedFileIdFromUrl = (url) => {
1618
+ if (!url.startsWith(UPLOADED_FILE_REF_PREFIX)) {
1619
+ return null;
1620
+ }
1621
+ const uploadedFileId = url.slice(UPLOADED_FILE_REF_PREFIX.length);
1622
+ return uploadedFileId.length > 0 ? uploadedFileId : null;
1623
+ };
1624
+ var toUploadedFileRefUrl = (uploadedFileId) => `${UPLOADED_FILE_REF_PREFIX}${uploadedFileId}`;
1625
+ var validateUploadedFiles = (uploadedFiles) => {
1626
+ if (uploadedFiles.length > CHAT_MAX_FILE_COUNT) {
1627
+ throw new Error(`Too many files: ${uploadedFiles.length}. Maximum is ${CHAT_MAX_FILE_COUNT}.`);
1628
+ }
1629
+ const combinedSize = uploadedFiles.reduce((sum, uploadedFile) => sum + uploadedFile.size_bytes, 0);
1630
+ if (combinedSize > CHAT_MAX_COMBINED_FILE_SIZE) {
1631
+ const limitMB = Math.round(CHAT_MAX_COMBINED_FILE_SIZE / (1024 * 1024));
1632
+ throw new Error(`Combined file size exceeds maximum of ${limitMB} MB.`);
1633
+ }
1634
+ };
1217
1635
  var UploadedFileIdSchema = z.uuid();
1218
1636
  var UploadedFileSchema = z.object({
1219
1637
  uploadedFileId: UploadedFileIdSchema,
@@ -1472,6 +1890,15 @@ var ExportReportData = createRoute({
1472
1890
  }
1473
1891
  }
1474
1892
  });
1893
+ var DataServiceErrorCodeSchema = z.enum([
1894
+ "QUERY_LIMIT_EXCEEDED",
1895
+ "QUERY_TIMEOUT",
1896
+ "QUERY_EXECUTION_FAILED"
1897
+ ]);
1898
+ var DataServiceErrorResponseSchema = z.object({
1899
+ error: z.string(),
1900
+ code: DataServiceErrorCodeSchema
1901
+ });
1475
1902
  var GetReportData = createRoute({
1476
1903
  method: "get",
1477
1904
  path: "/api/v1/data-reports/{report_id}/data",
@@ -1509,9 +1936,7 @@ var GetReportData = createRoute({
1509
1936
  description: "Something wrong happened",
1510
1937
  content: {
1511
1938
  "application/json": {
1512
- schema: z.object({
1513
- error: z.string()
1514
- })
1939
+ schema: DataServiceErrorResponseSchema
1515
1940
  }
1516
1941
  }
1517
1942
  }
@@ -1549,9 +1974,7 @@ var GetReportRowCount = createRoute({
1549
1974
  description: "Something wrong happened",
1550
1975
  content: {
1551
1976
  "application/json": {
1552
- schema: z.object({
1553
- error: z.string()
1554
- })
1977
+ schema: DataServiceErrorResponseSchema
1555
1978
  }
1556
1979
  }
1557
1980
  }
@@ -1771,7 +2194,7 @@ createRoute({
1771
2194
  operationId: "getColumnLineage",
1772
2195
  tags: ["public"],
1773
2196
  request: {
1774
- headers: SupabaseHeaderSchema,
2197
+ headers: SupabaseScopedHeaderSchema,
1775
2198
  body: {
1776
2199
  required: true,
1777
2200
  content: {
@@ -2008,6 +2431,49 @@ var CreateFlow = createRoute({
2008
2431
  }
2009
2432
  }
2010
2433
  });
2434
+ var PromptStarterSchema = z.object({
2435
+ id: z.number(),
2436
+ title: z.string(),
2437
+ template: z.string(),
2438
+ is_default: z.boolean()
2439
+ }).describe("Prompt starter template").openapi("PromptStarter");
2440
+
2441
+ // ../shared/dist/src/endpoints/companion/promptStarters.routes.js
2442
+ var MAX_PROMPT_STARTERS = 3;
2443
+ var GetPromptStarters = createRoute({
2444
+ method: "get",
2445
+ path: "/api/v1/prompt-starters",
2446
+ operationId: "getPromptStarters",
2447
+ tags: ["public"],
2448
+ request: {
2449
+ headers: SupabaseHeaderSchema,
2450
+ query: z.object({
2451
+ input: z.string().optional()
2452
+ })
2453
+ },
2454
+ responses: {
2455
+ 200: {
2456
+ description: "List available prompt starters",
2457
+ content: {
2458
+ "application/json": {
2459
+ schema: z.object({
2460
+ starters: PromptStarterSchema.array().min(0).max(MAX_PROMPT_STARTERS)
2461
+ })
2462
+ }
2463
+ }
2464
+ },
2465
+ 500: {
2466
+ description: "Something wrong happened",
2467
+ content: {
2468
+ "application/json": {
2469
+ schema: z.object({
2470
+ error: z.string()
2471
+ })
2472
+ }
2473
+ }
2474
+ }
2475
+ }
2476
+ });
2011
2477
  var FrontendRecommendationsSchema = z.object({
2012
2478
  starter: z.string(),
2013
2479
  explanation: z.string(),
@@ -2084,20 +2550,20 @@ var CreateSpeechToken = createRoute({
2084
2550
  }
2085
2551
  }
2086
2552
  });
2087
- z8.discriminatedUnion("status", [
2088
- z8.object({
2089
- status: z8.literal("error"),
2090
- error: z8.string()
2553
+ z10.discriminatedUnion("status", [
2554
+ z10.object({
2555
+ status: z10.literal("error"),
2556
+ error: z10.string()
2091
2557
  }),
2092
- z8.object({
2093
- status: z8.literal("success"),
2094
- flowId: z8.string()
2558
+ z10.object({
2559
+ status: z10.literal("success"),
2560
+ flowId: z10.string()
2095
2561
  })
2096
2562
  ]);
2097
- var TriggerFlowBody = z8.object({
2098
- triggerId: z8.string(),
2099
- variables: z8.record(z8.string(), z8.string()),
2100
- applicationName: z8.string().optional()
2563
+ var TriggerFlowBody = z10.object({
2564
+ triggerId: z10.string(),
2565
+ variables: z10.record(z10.string(), z10.string()),
2566
+ applicationName: z10.string().optional()
2101
2567
  });
2102
2568
  var TriggerFlow = createRoute({
2103
2569
  method: "post",
@@ -2121,9 +2587,9 @@ var TriggerFlow = createRoute({
2121
2587
  description: "Flow id",
2122
2588
  content: {
2123
2589
  "application/json": {
2124
- schema: z8.object({
2125
- status: z8.literal("success"),
2126
- flowId: z8.string()
2590
+ schema: z10.object({
2591
+ status: z10.literal("success"),
2592
+ flowId: z10.string()
2127
2593
  })
2128
2594
  }
2129
2595
  }
@@ -2131,8 +2597,8 @@ var TriggerFlow = createRoute({
2131
2597
  400: {
2132
2598
  content: {
2133
2599
  "application/json": {
2134
- schema: z8.object({
2135
- error: z8.string()
2600
+ schema: z10.object({
2601
+ error: z10.string()
2136
2602
  })
2137
2603
  }
2138
2604
  },
@@ -2141,7 +2607,7 @@ var TriggerFlow = createRoute({
2141
2607
  404: {
2142
2608
  content: {
2143
2609
  "application/json": {
2144
- schema: z8.object({ error: z8.string() })
2610
+ schema: z10.object({ error: z10.string() })
2145
2611
  }
2146
2612
  },
2147
2613
  description: "Unable to retrieve trigger with this id"
@@ -2150,8 +2616,8 @@ var TriggerFlow = createRoute({
2150
2616
  description: "Something wrong happened",
2151
2617
  content: {
2152
2618
  "application/json": {
2153
- schema: z8.object({
2154
- error: z8.string()
2619
+ schema: z10.object({
2620
+ error: z10.string()
2155
2621
  })
2156
2622
  }
2157
2623
  }
@@ -2181,9 +2647,9 @@ createRoute({
2181
2647
  description: "Flow id",
2182
2648
  content: {
2183
2649
  "application/json": {
2184
- schema: z8.object({
2185
- status: z8.literal("success"),
2186
- flowId: z8.string()
2650
+ schema: z10.object({
2651
+ status: z10.literal("success"),
2652
+ flowId: z10.string()
2187
2653
  })
2188
2654
  }
2189
2655
  }
@@ -2191,8 +2657,8 @@ createRoute({
2191
2657
  400: {
2192
2658
  content: {
2193
2659
  "application/json": {
2194
- schema: z8.object({
2195
- error: z8.string()
2660
+ schema: z10.object({
2661
+ error: z10.string()
2196
2662
  })
2197
2663
  }
2198
2664
  },
@@ -2201,7 +2667,7 @@ createRoute({
2201
2667
  404: {
2202
2668
  content: {
2203
2669
  "application/json": {
2204
- schema: z8.object({ error: z8.string() })
2670
+ schema: z10.object({ error: z10.string() })
2205
2671
  }
2206
2672
  },
2207
2673
  description: "Unable to retrieve trigger with this id"
@@ -2210,8 +2676,8 @@ createRoute({
2210
2676
  description: "Something wrong happened",
2211
2677
  content: {
2212
2678
  "application/json": {
2213
- schema: z8.object({
2214
- error: z8.string()
2679
+ schema: z10.object({
2680
+ error: z10.string()
2215
2681
  })
2216
2682
  }
2217
2683
  }
@@ -2356,13 +2822,13 @@ var CanvasIdParam = CanvasSchema.shape.id.openapi("CanvasId", {
2356
2822
  var dataReportNodeSchema = z.object({
2357
2823
  type: z.literal(DATA_REPORT_LABEL),
2358
2824
  data: z.object({
2359
- reportId: z.number()
2825
+ reportId: z.string()
2360
2826
  })
2361
2827
  });
2362
2828
  var visualizationNodeSchema = z.object({
2363
2829
  type: z.literal(VISUALIZATION_LABEL),
2364
2830
  data: z.object({
2365
- visualizationId: z.number()
2831
+ visualizationId: z.string()
2366
2832
  })
2367
2833
  });
2368
2834
  z.discriminatedUnion("type", [
@@ -2637,218 +3103,412 @@ var ChatMessages = createRoute({
2637
3103
  schema: z.object({ messages: z.looseObject({}).array() })
2638
3104
  }
2639
3105
  }
2640
- },
2641
- 404: {
2642
- content: {
2643
- "application/json": {
2644
- schema: z.object({ error: z.string() })
2645
- }
2646
- },
2647
- description: "Unable to retrieve flow with this id"
2648
- },
2649
- 500: {
2650
- description: "Something wrong happened",
2651
- content: {
2652
- "application/json": {
2653
- schema: z.object({
2654
- error: z.string()
2655
- })
2656
- }
2657
- }
2658
- }
2659
- }
2660
- });
2661
- dayjs.extend(relativeTime);
2662
- dayjs.extend(customParseFormat);
2663
- dayjs.extend(utc);
2664
- dayjs.extend(timezone);
2665
- var daysjs_default = dayjs;
2666
-
2667
- // ../shared/dist/src/data/FormattedData.js
2668
- var numberFormatCache = /* @__PURE__ */ new Map();
2669
- var getNumberFormatter = (minimumFractionDigits, maximumFractionDigits, useGrouping) => {
2670
- const key = `${minimumFractionDigits}:${maximumFractionDigits}:${useGrouping}`;
2671
- let formatter = numberFormatCache.get(key);
2672
- if (!formatter) {
2673
- formatter = new Intl.NumberFormat(void 0, {
2674
- minimumFractionDigits,
2675
- maximumFractionDigits,
2676
- useGrouping
2677
- });
2678
- numberFormatCache.set(key, formatter);
2679
- }
2680
- return formatter;
2681
- };
2682
- var formatWithAutoPrecision = (value, options = {}) => {
2683
- const { minPrecision = 0, maxPrecision = 6, trimZeros = true, useGrouping = true } = options;
2684
- if (typeof value !== "number" || isNaN(value)) {
2685
- return String(value);
2686
- }
2687
- if (value === 0) {
2688
- return "0";
2689
- }
2690
- const absValue = Math.abs(value);
2691
- let maximumFractionDigits;
2692
- if (absValue >= 1e3) {
2693
- maximumFractionDigits = 0;
2694
- } else if (absValue >= 100) {
2695
- maximumFractionDigits = 1;
2696
- } else if (absValue >= 10) {
2697
- maximumFractionDigits = 2;
2698
- } else if (absValue >= 1) {
2699
- maximumFractionDigits = 3;
2700
- } else if (absValue >= 0.1) {
2701
- maximumFractionDigits = 4;
2702
- } else if (absValue >= 0.01) {
2703
- maximumFractionDigits = 5;
2704
- } else {
2705
- maximumFractionDigits = maxPrecision;
2706
- if (absValue > 0) {
2707
- const exponent = Math.floor(Math.log10(absValue));
2708
- if (exponent < 0) {
2709
- maximumFractionDigits = Math.min(Math.abs(exponent) + 2, maxPrecision);
2710
- }
2711
- }
2712
- }
2713
- maximumFractionDigits = Math.max(maximumFractionDigits, minPrecision);
2714
- const formatter = getNumberFormatter(trimZeros ? 0 : maximumFractionDigits, maximumFractionDigits, useGrouping);
2715
- return formatter.format(value);
2716
- };
2717
- var MIN_VALID_YEAR = 1900;
2718
- var MAX_VALID_YEAR = 2200;
2719
- var zonedatetime = (format, zone) => ({ format, type: "zonedatetime", zone });
2720
- var datetime = (format) => ({ format, type: "datetime" });
2721
- var date = (format) => ({ format, type: "date" });
2722
- var DATE_FORMATS = [
2723
- // ISO 8601 formats
2724
- zonedatetime("YYYY-MM-DDTHH:mm:ss.SSSZ", "UTC"),
2725
- zonedatetime("YYYY-MM-DDTHH:mm:ssZ", "UTC"),
2726
- zonedatetime("YYYY-MM-DDTHH:mmZ", "UTC"),
2727
- datetime("YYYY-MM-DDTHH:mm:ss"),
2728
- datetime("YYYY-MM-DDTHH:mm"),
2729
- date("YYYY-MM-DDT"),
2730
- // Standard date formats
2731
- date("YYYY-MM-DD"),
2732
- date("YYYY/MM/DD"),
2733
- date("DD-MM-YYYY"),
2734
- date("DD/MM/YYYY"),
2735
- date("MM-DD-YYYY"),
2736
- date("MM/DD/YYYY"),
2737
- // Date time formats
2738
- datetime("YYYY-MM-DD HH:mm:ss"),
2739
- datetime("YYYY-MM-DD HH:mm"),
2740
- datetime("YYYY/MM/DD HH:mm:ss"),
2741
- datetime("YYYY/MM/DD HH:mm"),
2742
- datetime("DD-MM-YYYY HH:mm:ss"),
2743
- datetime("DD-MM-YYYY HH:mm"),
2744
- datetime("DD/MM/YYYY HH:mm:ss"),
2745
- datetime("DD/MM/YYYY HH:mm"),
2746
- datetime("MM-DD-YYYY HH:mm:ss"),
2747
- datetime("MM-DD-YYYY HH:mm"),
2748
- datetime("MM/DD/YYYY HH:mm:ss"),
2749
- datetime("MM/DD/YYYY HH:mm")
2750
- ];
2751
- var isDateString = (value) => {
2752
- if (typeof value !== "string")
2753
- return { isValid: false };
2754
- const stripped = value.replace(/[-/.:\s]/g, "");
2755
- if (/^\d+$/.test(stripped)) {
2756
- if (stripped.length < 6)
2757
- return { isValid: false };
2758
- if (value.length === stripped.length)
2759
- return { isValid: false };
2760
- }
2761
- if (stripped.length > "YYYY-MM-DDTHH:mm:ss.SSS+00:00".length) {
2762
- return { isValid: false };
2763
- }
2764
- for (const format of DATE_FORMATS) {
2765
- let date2;
2766
- try {
2767
- if (format.type === "zonedatetime") {
2768
- date2 = daysjs_default.tz(value, format.format, format.zone);
2769
- } else {
2770
- date2 = daysjs_default(value, format.format, true);
2771
- }
2772
- } catch {
2773
- continue;
2774
- }
2775
- if (date2.isValid()) {
2776
- const year = date2.year();
2777
- if (year < MIN_VALID_YEAR || year > MAX_VALID_YEAR)
2778
- continue;
2779
- const isDateTime = format.type === "zonedatetime" || format.type == "datetime";
2780
- return {
2781
- isValid: true,
2782
- parsedDate: date2,
2783
- isDateTime
2784
- };
2785
- }
2786
- }
2787
- return { isValid: false };
2788
- };
2789
- var formatDataValue = (value, { replaceNullValue } = {
2790
- replaceNullValue: true
2791
- }) => {
2792
- if (value === null || value === void 0) {
2793
- return {
2794
- display: replaceNullValue ? "empty" : null,
2795
- sortValue: null
2796
- };
2797
- }
2798
- let processedValue = value;
2799
- if (typeof processedValue === "string") {
2800
- try {
2801
- const parsed = JSON.parse(processedValue);
2802
- processedValue = parsed;
2803
- } catch {
2804
- }
2805
- }
2806
- if (processedValue && typeof processedValue === "object" && Object.keys(processedValue).length === 1 && "value" in processedValue) {
2807
- const extractedValue = processedValue.value;
2808
- const dateResult2 = isDateString(extractedValue);
2809
- if (dateResult2.isValid) {
2810
- return {
2811
- display: dateResult2.isDateTime ? dateResult2.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult2.parsedDate.format("YYYY-MM-DD"),
2812
- sortValue: dateResult2.parsedDate.valueOf()
2813
- };
2814
- }
2815
- return {
2816
- display: String(extractedValue),
2817
- sortValue: extractedValue
2818
- };
2819
- }
2820
- const dateResult = isDateString(processedValue);
2821
- if (dateResult.isValid) {
2822
- return {
2823
- display: dateResult.isDateTime ? dateResult.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult.parsedDate.format("YYYY-MM-DD"),
2824
- sortValue: dateResult.parsedDate.valueOf()
2825
- };
2826
- }
2827
- if (typeof processedValue === "object") {
2828
- const stringified = JSON.stringify(processedValue, null, 2);
2829
- return {
2830
- display: stringified,
2831
- sortValue: stringified
2832
- };
2833
- }
2834
- if (typeof processedValue === "boolean") {
2835
- return {
2836
- display: String(processedValue),
2837
- sortValue: processedValue ? 1 : 0
2838
- };
2839
- }
2840
- if (typeof processedValue === "number") {
2841
- return {
2842
- display: processedValue >= MIN_VALID_YEAR && processedValue <= MAX_VALID_YEAR && Number.isInteger(processedValue) ? String(processedValue) : formatWithAutoPrecision(processedValue),
2843
- sortValue: processedValue
2844
- };
3106
+ },
3107
+ 404: {
3108
+ content: {
3109
+ "application/json": {
3110
+ schema: z.object({ error: z.string() })
3111
+ }
3112
+ },
3113
+ description: "Unable to retrieve flow with this id"
3114
+ },
3115
+ 500: {
3116
+ description: "Something wrong happened",
3117
+ content: {
3118
+ "application/json": {
3119
+ schema: z.object({
3120
+ error: z.string()
3121
+ })
3122
+ }
3123
+ }
3124
+ }
2845
3125
  }
2846
- return {
2847
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
2848
- display: String(processedValue),
2849
- sortValue: processedValue
2850
- };
3126
+ });
3127
+ var UPDATE_TASK = "updateTask";
3128
+ var TaskStatusSchema = z.enum([
3129
+ "pending",
3130
+ "in_progress",
3131
+ "completed",
3132
+ "failed"
3133
+ ]);
3134
+ var TaskArtifactSchema = z.object({
3135
+ type: z.enum(["report", "visualization"]),
3136
+ id: z.string().describe("The ID returned by generateDataReport or generateVisualization")
3137
+ });
3138
+ var TaskSummarySchema = z.object({
3139
+ outcome: z.string().describe("SHORT summary (max 10 words) e.g. 'Found 847 records' or 'Generated trend chart'"),
3140
+ tool_calls: z.array(z.string()).describe("List of tools used during this task, e.g. ['generateDataReport x3', 'generateVisualization x1']")
3141
+ });
3142
+ var TaskPlanItemSchema = z.object({
3143
+ id: z.string(),
3144
+ title: z.string(),
3145
+ description: z.string().optional().describe("Detailed steps or description of what the task will do")
3146
+ });
3147
+ var TaskPlanSchema = z.array(TaskPlanItemSchema);
3148
+ var AgentTaskSchema = z.object({
3149
+ id: z.string(),
3150
+ title: z.string(),
3151
+ status: TaskStatusSchema,
3152
+ parent_id: z.string().optional(),
3153
+ started_at: z.string().optional(),
3154
+ completed_at: z.string().optional(),
3155
+ summary: TaskSummarySchema.optional(),
3156
+ artifacts: z.array(TaskArtifactSchema).optional()
3157
+ });
3158
+ var AgentTasksStateSchema = z.array(AgentTaskSchema);
3159
+ var updateTaskInputSchema = z.object({
3160
+ action: z.enum(["update", "create"]).default("update").describe('Action type \u2014 "update" (default) or "create"'),
3161
+ id: z.string().optional().describe("The task ID (e.g. '1', '2', or '1.1' for subtasks) \u2014 required for update"),
3162
+ title: z.string().optional().describe("Short title for the new task \u2014 required for create"),
3163
+ status: TaskStatusSchema.optional().describe("The new status for this task \u2014 required for update"),
3164
+ summary: TaskSummarySchema.optional().describe("Summary of outcome and tools used (required when status is 'completed')"),
3165
+ artifacts: z.array(TaskArtifactSchema).optional().describe("Reports and visualizations produced during this task")
3166
+ });
3167
+ updateTaskInputSchema.extend({
3168
+ action: z.literal("update").default("update").describe("Action type")
3169
+ });
3170
+ var TaskSummaryForContextSchema = z.object({
3171
+ id: z.string(),
3172
+ title: z.string(),
3173
+ status: TaskStatusSchema
3174
+ });
3175
+ var TaskResultPublicSchema = z.object({
3176
+ taskId: z.string(),
3177
+ taskStatus: TaskStatusSchema,
3178
+ message: z.string()
3179
+ });
3180
+ var TaskResultPrivateSchema = z.object({
3181
+ updatedAt: z.string(),
3182
+ // Current state of all tasks - injected so model stays aware of progress
3183
+ currentTasks: z.array(TaskSummaryForContextSchema)
3184
+ });
3185
+ var UpdateTaskSuccessSchema = z.object({
3186
+ status: z.literal("success"),
3187
+ public: TaskResultPublicSchema,
3188
+ // Private fields are redacted before sending to frontend (user sees tasks in UI already)
3189
+ private: TaskResultPrivateSchema
3190
+ });
3191
+ var UpdateTaskErrorSchema = z.object({
3192
+ status: z.literal("error"),
3193
+ message: z.string()
3194
+ });
3195
+ z.object({
3196
+ tool: z.literal(UPDATE_TASK),
3197
+ result: z.discriminatedUnion("status", [
3198
+ UpdateTaskSuccessSchema,
3199
+ UpdateTaskErrorSchema
3200
+ ]).optional()
3201
+ });
3202
+
3203
+ // ../shared/dist/src/types/agentTypes.js
3204
+ var AgentType = {
3205
+ KnowledgeFarmer: "knowledge_farmer",
3206
+ KnowledgeConsistencyChecker: "knowledge_consistency_checker",
3207
+ CompanyResearch: "company_research",
3208
+ KnowledgeExtraction: "knowledge_extraction",
3209
+ /** User-defined agents (via AgentRunScheduler) */
3210
+ Custom: "custom"
2851
3211
  };
3212
+ var ExecutionPlatform = {
3213
+ Native: "native",
3214
+ Sandbox: "sandbox",
3215
+ SandboxPublic: "sandbox_public"
3216
+ };
3217
+
3218
+ // ../shared/dist/src/types/executionContext.js
3219
+ var ImpersonateContextSchema = z.object({
3220
+ mode: z.literal("impersonate"),
3221
+ external_user_id: z.string().min(1).describe("The user ID in the customer's system")
3222
+ }).openapi("ImpersonateContext");
3223
+ var CustomMetadataContextSchema = z.object({
3224
+ mode: z.literal("custom"),
3225
+ metadata: z.record(z.string(), z.unknown()).describe("Raw metadata key-value pairs for data access rules")
3226
+ }).openapi("CustomMetadataContext");
3227
+ var ExecutionContextInputSchema = z.discriminatedUnion("mode", [
3228
+ ImpersonateContextSchema,
3229
+ CustomMetadataContextSchema
3230
+ ]).openapi("ExecutionContextInput");
3231
+ var ResolvedExecutionContextSchema = z.object({
3232
+ companyId: z.number(),
3233
+ userMetadata: z.record(z.string(), z.unknown())
3234
+ });
3235
+
3236
+ // ../shared/dist/src/schemas/agents/agent.js
3237
+ var JsonSchemaObjectSchema = z.record(z.string(), z.unknown());
3238
+ var AgentInputFieldOptionSchema = z.object({
3239
+ value: z.string(),
3240
+ fragment: z.string().optional()
3241
+ });
3242
+ var AgentEnumInputFieldSchema = z.object({
3243
+ id: z.string(),
3244
+ name: z.string(),
3245
+ description: z.string().optional(),
3246
+ type: z.literal("enum"),
3247
+ options: z.array(AgentInputFieldOptionSchema).min(1),
3248
+ useFragmentMapping: z.boolean().default(false),
3249
+ required: z.boolean().default(false)
3250
+ });
3251
+ var AgentTextInputFieldSchema = z.object({
3252
+ id: z.string(),
3253
+ name: z.string(),
3254
+ description: z.string().optional(),
3255
+ type: z.literal("text"),
3256
+ useFragmentMapping: z.literal(false).default(false),
3257
+ required: z.boolean().default(false)
3258
+ });
3259
+ var AgentInputFieldSchema = z.discriminatedUnion("type", [
3260
+ AgentEnumInputFieldSchema,
3261
+ AgentTextInputFieldSchema
3262
+ ]);
3263
+ var AgentInputSchemaSchema = z.array(AgentInputFieldSchema);
3264
+ var GeminiModelConfigSchema = z.object({
3265
+ model: z.literal("gemini-3.1-pro-preview"),
3266
+ thinking: z.enum(["low", "high"]).optional()
3267
+ });
3268
+ var Gemini25ProModelConfigSchema = z.object({
3269
+ model: z.literal("gemini-2.5-pro"),
3270
+ thinking: z.enum(["low", "high"]).optional()
3271
+ });
3272
+ var ClaudeAdaptiveModelConfigSchema = z.object({
3273
+ model: z.enum(["claude-sonnet-4-6", "claude-opus-4-6"]),
3274
+ effort: z.enum(["low", "medium", "high"]).optional()
3275
+ });
3276
+ var ClaudeBasicModelConfigSchema = z.object({
3277
+ model: z.enum(["claude-haiku-4-5", "claude-opus-4-5"])
3278
+ });
3279
+ var ModelConfigSchema = z.discriminatedUnion("model", [
3280
+ GeminiModelConfigSchema,
3281
+ Gemini25ProModelConfigSchema,
3282
+ ClaudeAdaptiveModelConfigSchema,
3283
+ ClaudeBasicModelConfigSchema
3284
+ ]);
3285
+ var ExecutionPlatformSchema = z.enum([
3286
+ ExecutionPlatform.Native,
3287
+ ExecutionPlatform.Sandbox,
3288
+ ExecutionPlatform.SandboxPublic
3289
+ ]);
3290
+ var BaseAgentSchema = z.object({
3291
+ id: z.uuid(),
3292
+ company_id: z.number(),
3293
+ is_removed: z.boolean().nullable(),
3294
+ created_at: z.string()
3295
+ });
3296
+ var AgentBehaviorSchema = z.object({
3297
+ name: z.string(),
3298
+ objective: z.string().nullable(),
3299
+ generated_objective_fragment: z.string().nullable(),
3300
+ active_tools: z.array(z.string()).nullable(),
3301
+ input_schema: AgentInputSchemaSchema.nullable(),
3302
+ output_schema: JsonSchemaObjectSchema,
3303
+ task_plan: TaskPlanSchema.nullable(),
3304
+ model_config: ModelConfigSchema.nullable(),
3305
+ execution_platform: ExecutionPlatformSchema
3306
+ });
3307
+ var AgentSchema = z.object({
3308
+ ...BaseAgentSchema.shape,
3309
+ ...AgentBehaviorSchema.shape,
3310
+ updated_at: z.string(),
3311
+ current_version_id: z.uuid()
3312
+ });
3313
+ z.object({
3314
+ name: z.string().min(1, "Name is required"),
3315
+ objective: z.string().optional(),
3316
+ generated_objective_fragment: z.string().optional(),
3317
+ active_tools: z.array(z.string()).default([]),
3318
+ input_schema: AgentInputSchemaSchema.optional(),
3319
+ output_schema: JsonSchemaObjectSchema,
3320
+ task_plan: TaskPlanSchema.optional(),
3321
+ model_config: ModelConfigSchema.optional(),
3322
+ execution_platform: ExecutionPlatformSchema.default(ExecutionPlatform.Native)
3323
+ });
3324
+ var DbUpdateAgentSchema = z.object({
3325
+ name: z.string().min(1).optional(),
3326
+ objective: z.string().nullable().optional(),
3327
+ generated_objective_fragment: z.string().nullable().optional(),
3328
+ active_tools: z.array(z.string()).optional(),
3329
+ input_schema: AgentInputSchemaSchema.nullable().optional(),
3330
+ output_schema: JsonSchemaObjectSchema.optional(),
3331
+ task_plan: TaskPlanSchema.nullable().optional(),
3332
+ model_config: ModelConfigSchema.nullable().optional(),
3333
+ execution_platform: ExecutionPlatformSchema.optional(),
3334
+ restored_from_version: z.number().int().positive().nullable().optional()
3335
+ });
3336
+ DbUpdateAgentSchema.omit({
3337
+ restored_from_version: true
3338
+ });
3339
+ AgentSchema.omit({
3340
+ company_id: true,
3341
+ is_removed: true,
3342
+ current_version_id: true
3343
+ }).openapi("Agent");
3344
+
3345
+ // ../shared/dist/src/schemas/agents/postProcessor.js
3346
+ var PostProcessorConfigSchema = z.discriminatedUnion("type", [
3347
+ /**
3348
+ * Resolve and insert knowledge item proposals from output_data.proposals
3349
+ * and output_data.deletions into knowledge_item_proposals.
3350
+ * Compatible with: farmer, consistency checker, knowledge extraction.
3351
+ */
3352
+ z.object({
3353
+ type: z.literal("knowledge_proposals"),
3354
+ params: z.object({
3355
+ /** DB enum value to tag inserted proposals with. */
3356
+ source: z.enum(["data_report", "consistency_check", "document"]),
3357
+ /**
3358
+ * Only insert proposals at or above this confidence level.
3359
+ * Proposals without a confidence field are always included.
3360
+ */
3361
+ minConfidence: z.enum(["low", "medium", "high"]).optional(),
3362
+ /** Skip DB writes and only log what would be inserted. */
3363
+ dryRun: z.boolean().optional()
3364
+ })
3365
+ }),
3366
+ /**
3367
+ * Soft-delete few-shot prompt examples from output_data.few_shot_removals.
3368
+ */
3369
+ z.object({
3370
+ type: z.literal("remove_few_shot_examples"),
3371
+ params: z.object({
3372
+ /** Identifies the calling agent in the audit trail comment. */
3373
+ sourceLabel: z.string(),
3374
+ /** Skip DB writes and only log what would be removed. */
3375
+ dryRun: z.boolean().optional()
3376
+ })
3377
+ }),
3378
+ /**
3379
+ * Record a knowledge farmer investigation. Must run before knowledge_proposals
3380
+ * so ctx.investigationId is set for downstream post-processors.
3381
+ */
3382
+ z.object({
3383
+ type: z.literal("knowledge_farmer_investigation"),
3384
+ params: z.object({
3385
+ /** Skip DB writes and only log what would be inserted. */
3386
+ dryRun: z.boolean().optional()
3387
+ })
3388
+ }),
3389
+ /**
3390
+ * Persist the agent's entire output_data as company_settings.context_profile.
3391
+ * Used by the company research agent.
3392
+ */
3393
+ z.object({
3394
+ type: z.literal("save_context_profile")
3395
+ })
3396
+ ]);
3397
+
3398
+ // ../shared/dist/src/schemas/agents/agentRun.js
3399
+ var AgentTypeSchema = z.enum([
3400
+ AgentType.KnowledgeFarmer,
3401
+ AgentType.KnowledgeConsistencyChecker,
3402
+ AgentType.CompanyResearch,
3403
+ AgentType.KnowledgeExtraction,
3404
+ AgentType.Custom
3405
+ ]);
3406
+ var ExecutionPlatformSchema2 = z.enum([
3407
+ ExecutionPlatform.Native,
3408
+ ExecutionPlatform.Sandbox,
3409
+ ExecutionPlatform.SandboxPublic
3410
+ ]);
3411
+ var AgentRunStatusSchema = z.enum([
3412
+ "pending",
3413
+ "running",
3414
+ "post_processing",
3415
+ "completed",
3416
+ "failed",
3417
+ "cancelled"
3418
+ ]);
3419
+ var AgentChatMessageSchema = z.record(z.string(), z.unknown());
3420
+ z.object({
3421
+ id: z.uuid(),
3422
+ user_id: z.uuid(),
3423
+ company_id: z.number().nullable(),
3424
+ agent_id: z.uuid().nullable(),
3425
+ agent_type: AgentTypeSchema.nullable(),
3426
+ execution_platform: ExecutionPlatformSchema2.nullable(),
3427
+ status: AgentRunStatusSchema,
3428
+ created_at: z.string(),
3429
+ started_at: z.string().nullable(),
3430
+ completed_at: z.string().nullable(),
3431
+ cancelled_at: z.string().nullable(),
3432
+ job_id: z.string().nullable(),
3433
+ chat_messages: z.array(AgentChatMessageSchema).nullable(),
3434
+ allowed_tools: z.array(z.string()).nullable(),
3435
+ input_data: z.record(z.string(), z.unknown()).nullable(),
3436
+ output_data: z.record(z.string(), z.unknown()).nullable(),
3437
+ output_schema: JsonSchemaObjectSchema.nullable(),
3438
+ tasks: AgentTasksStateSchema.nullable(),
3439
+ error_message: z.string().nullable(),
3440
+ execution_context: ResolvedExecutionContextSchema.nullable(),
3441
+ model_config: ModelConfigSchema.nullable(),
3442
+ // Nullable with a default so pre-migration rows (where the column is absent)
3443
+ // parse cleanly — undefined input becomes null output.
3444
+ post_processors: z.array(PostProcessorConfigSchema).nullable().default(null),
3445
+ agent_version_id: z.uuid().nullable().default(null),
3446
+ cached_from: z.uuid().nullable().default(null)
3447
+ });
3448
+ z.object({
3449
+ user_id: z.uuid(),
3450
+ company_id: z.number(),
3451
+ agent_id: z.uuid().nullable(),
3452
+ agent_type: AgentTypeSchema.optional(),
3453
+ execution_platform: ExecutionPlatformSchema2.optional(),
3454
+ status: AgentRunStatusSchema.default("pending"),
3455
+ chat_messages: z.array(AgentChatMessageSchema).optional(),
3456
+ allowed_tools: z.array(z.string()).optional(),
3457
+ input_data: z.record(z.string(), z.unknown()).optional(),
3458
+ output_data: z.record(z.string(), z.unknown()).optional(),
3459
+ output_schema: JsonSchemaObjectSchema.optional(),
3460
+ execution_context: ResolvedExecutionContextSchema.optional(),
3461
+ model_config: ModelConfigSchema.optional(),
3462
+ post_processors: z.array(PostProcessorConfigSchema).optional(),
3463
+ agent_version_id: z.uuid().optional(),
3464
+ cached_from: z.uuid().optional(),
3465
+ started_at: z.string().optional(),
3466
+ completed_at: z.string().optional()
3467
+ });
3468
+ z.object({
3469
+ status: AgentRunStatusSchema.optional(),
3470
+ started_at: z.string().optional(),
3471
+ completed_at: z.string().optional(),
3472
+ cancelled_at: z.string().optional(),
3473
+ job_id: z.string().optional(),
3474
+ chat_messages: z.array(AgentChatMessageSchema).optional(),
3475
+ input_data: z.record(z.string(), z.unknown()).optional(),
3476
+ output_data: z.record(z.string(), z.unknown()).optional(),
3477
+ tasks: AgentTasksStateSchema.optional(),
3478
+ error_message: z.string().optional(),
3479
+ model_config: ModelConfigSchema.optional(),
3480
+ last_heartbeat_at: z.string().nullable().optional(),
3481
+ post_processors: z.array(PostProcessorConfigSchema).optional()
3482
+ });
3483
+ var StartAgentRunRequestSchema = z.object({
3484
+ agent_id: z.uuid(),
3485
+ inputs: z.record(z.string(), z.unknown()).default({}),
3486
+ execution_context: ExecutionContextInputSchema.optional()
3487
+ }).openapi("StartAgentRunRequest");
3488
+ var AgentRunResponseSchema = z.object({
3489
+ id: z.uuid(),
3490
+ agent_id: z.uuid().nullable(),
3491
+ status: AgentRunStatusSchema,
3492
+ created_at: z.string(),
3493
+ started_at: z.string().nullable(),
3494
+ completed_at: z.string().nullable(),
3495
+ input_data: z.record(z.string(), z.unknown()).nullable(),
3496
+ output_data: z.record(z.string(), z.unknown()).nullable(),
3497
+ tasks: AgentTasksStateSchema.nullable().optional(),
3498
+ error_message: z.string().nullable(),
3499
+ execution_context: ResolvedExecutionContextSchema.nullable().optional(),
3500
+ agent_version_id: z.uuid().nullable().optional(),
3501
+ cached: z.boolean().optional(),
3502
+ cached_from: z.uuid().nullable().optional(),
3503
+ report_count: z.number().int().nonnegative().default(0),
3504
+ visualization_count: z.number().int().nonnegative().default(0)
3505
+ }).openapi("AgentRunResponse");
3506
+ z.object({
3507
+ status: AgentRunStatusSchema.optional(),
3508
+ agent_id: z.uuid().optional(),
3509
+ agent_type: AgentTypeSchema.optional(),
3510
+ limit: z.number().int().positive().max(100).default(20)
3511
+ });
2852
3512
 
2853
3513
  // ../shared/dist/src/schemas/visualizations.js
2854
3514
  var commonConfigProperties = {
@@ -2992,6 +3652,14 @@ var FrontendVisualizationSchema = VisualizationSchema.omit({
2992
3652
  is_sample: true,
2993
3653
  data_summary: true
2994
3654
  });
3655
+ var isFrontendV1Visualization = (visualization) => {
3656
+ return !("config_version" in visualization.configuration);
3657
+ };
3658
+ var isFrontendV2Visualization = (visualization) => {
3659
+ return "config_version" in visualization.configuration && // we currently have only 2 versions
3660
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3661
+ visualization.configuration.config_version === 2;
3662
+ };
2995
3663
  var VisualizationMetadataSchema = z.object({
2996
3664
  wasSampled: z.boolean(),
2997
3665
  originalCount: z.number(),
@@ -3001,12 +3669,257 @@ var V1FrontendVisualizationWithDataSchema = V1FrontendVisualizationSchema.extend
3001
3669
  data: VisualizationDataSchema,
3002
3670
  _metadata: VisualizationMetadataSchema
3003
3671
  });
3004
- var FrontendVisualizationWithDataSchema = FrontendVisualizationSchema.extend({
3005
- data: VisualizationDataSchema,
3006
- _metadata: VisualizationMetadataSchema
3672
+ var FrontendVisualizationWithDataSchema = FrontendVisualizationSchema.extend({
3673
+ data: VisualizationDataSchema,
3674
+ _metadata: VisualizationMetadataSchema
3675
+ });
3676
+ var isFrontendV1VisualizationWithData = (visualization) => {
3677
+ return !("config_version" in visualization.configuration);
3678
+ };
3679
+ var isFrontendV2VisualizationWithData = (visualization) => {
3680
+ return "config_version" in visualization.configuration && // we currently have only 2 versions
3681
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3682
+ visualization.configuration.config_version === 2;
3683
+ };
3684
+
3685
+ // ../shared/dist/src/endpoints/agents/runs.routes.js
3686
+ var AgentRunIdParam = z.object({ id: z.uuid() }).openapi("AgentRunId");
3687
+ var ErrorResponseSchema = z.object({ error: z.string() });
3688
+ createRoute({
3689
+ method: "post",
3690
+ path: "/api/v1/agent-runs",
3691
+ operationId: "startAgentRun",
3692
+ tags: ["public", "documented"],
3693
+ request: {
3694
+ headers: SupabaseScopedHeaderSchema,
3695
+ body: {
3696
+ required: true,
3697
+ content: {
3698
+ "application/json": {
3699
+ schema: StartAgentRunRequestSchema
3700
+ }
3701
+ }
3702
+ }
3703
+ },
3704
+ responses: {
3705
+ 200: {
3706
+ description: "The agent run was started",
3707
+ content: {
3708
+ "application/json": {
3709
+ schema: AgentRunResponseSchema
3710
+ }
3711
+ }
3712
+ },
3713
+ 400: {
3714
+ description: "Invalid request or input validation failed",
3715
+ content: {
3716
+ "application/json": {
3717
+ schema: ErrorResponseSchema
3718
+ }
3719
+ }
3720
+ },
3721
+ 404: {
3722
+ description: "Agent definition not found",
3723
+ content: {
3724
+ "application/json": {
3725
+ schema: ErrorResponseSchema
3726
+ }
3727
+ }
3728
+ },
3729
+ 500: {
3730
+ description: "Internal server error",
3731
+ content: {
3732
+ "application/json": {
3733
+ schema: ErrorResponseSchema
3734
+ }
3735
+ }
3736
+ }
3737
+ }
3738
+ });
3739
+ var AgentRunCountsResponseSchema = z.record(z.string().uuid(), z.number().int().nonnegative()).openapi("AgentRunCountsResponse");
3740
+ createRoute({
3741
+ method: "get",
3742
+ path: "/api/v1/agent-runs/counts",
3743
+ operationId: "getAgentRunCounts",
3744
+ tags: ["internal"],
3745
+ request: {
3746
+ headers: SupabaseHeaderSchema
3747
+ },
3748
+ responses: {
3749
+ 200: {
3750
+ description: "Run counts per agent",
3751
+ content: {
3752
+ "application/json": {
3753
+ schema: AgentRunCountsResponseSchema
3754
+ }
3755
+ }
3756
+ },
3757
+ 500: {
3758
+ description: "Internal server error",
3759
+ content: {
3760
+ "application/json": {
3761
+ schema: ErrorResponseSchema
3762
+ }
3763
+ }
3764
+ }
3765
+ }
3766
+ });
3767
+ createRoute({
3768
+ method: "get",
3769
+ path: "/api/v1/agent-runs/{id}",
3770
+ operationId: "getAgentRun",
3771
+ tags: ["public", "documented"],
3772
+ request: {
3773
+ headers: SupabaseHeaderSchema,
3774
+ params: AgentRunIdParam
3775
+ },
3776
+ responses: {
3777
+ 200: {
3778
+ description: "The agent run",
3779
+ content: {
3780
+ "application/json": {
3781
+ schema: AgentRunResponseSchema
3782
+ }
3783
+ }
3784
+ },
3785
+ 404: {
3786
+ description: "Agent run not found",
3787
+ content: {
3788
+ "application/json": {
3789
+ schema: ErrorResponseSchema
3790
+ }
3791
+ }
3792
+ },
3793
+ 500: {
3794
+ description: "Internal server error",
3795
+ content: {
3796
+ "application/json": {
3797
+ schema: ErrorResponseSchema
3798
+ }
3799
+ }
3800
+ }
3801
+ }
3802
+ });
3803
+ createRoute({
3804
+ method: "get",
3805
+ path: "/api/v1/agent-runs",
3806
+ operationId: "listAgentRuns",
3807
+ tags: ["public", "documented"],
3808
+ request: {
3809
+ headers: SupabaseHeaderSchema,
3810
+ query: z.object({
3811
+ status: AgentRunStatusSchema.optional(),
3812
+ agent_id: z.uuid().optional(),
3813
+ limit: limitQueryParams
3814
+ })
3815
+ },
3816
+ responses: {
3817
+ 200: {
3818
+ description: "List of agent runs",
3819
+ content: {
3820
+ "application/json": {
3821
+ schema: AgentRunResponseSchema.array()
3822
+ }
3823
+ }
3824
+ },
3825
+ 500: {
3826
+ description: "Internal server error",
3827
+ content: {
3828
+ "application/json": {
3829
+ schema: ErrorResponseSchema
3830
+ }
3831
+ }
3832
+ }
3833
+ }
3834
+ });
3835
+ var GetAgentRunReports = createRoute({
3836
+ method: "get",
3837
+ path: "/api/v1/agent-runs/{id}/reports",
3838
+ operationId: "getAgentRunReports",
3839
+ tags: ["public", "documented"],
3840
+ request: {
3841
+ headers: SupabaseHeaderSchema,
3842
+ params: AgentRunIdParam
3843
+ },
3844
+ responses: {
3845
+ 200: {
3846
+ description: "Reports generated by this agent run",
3847
+ content: {
3848
+ "application/json": {
3849
+ schema: FrontendReportSchema.array()
3850
+ }
3851
+ }
3852
+ },
3853
+ 404: {
3854
+ description: "Agent run not found",
3855
+ content: {
3856
+ "application/json": {
3857
+ schema: ErrorResponseSchema
3858
+ }
3859
+ }
3860
+ },
3861
+ 500: {
3862
+ description: "Internal server error",
3863
+ content: {
3864
+ "application/json": {
3865
+ schema: ErrorResponseSchema
3866
+ }
3867
+ }
3868
+ }
3869
+ }
3870
+ });
3871
+ var GetAgentRunVisualizations = createRoute({
3872
+ method: "get",
3873
+ path: "/api/v1/agent-runs/{id}/visualizations",
3874
+ operationId: "getAgentRunVisualizations",
3875
+ tags: ["public", "documented"],
3876
+ request: {
3877
+ headers: SupabaseHeaderSchema,
3878
+ params: AgentRunIdParam
3879
+ },
3880
+ responses: {
3881
+ 200: {
3882
+ description: "Visualizations generated by this agent run",
3883
+ content: {
3884
+ "application/json": {
3885
+ schema: FrontendVisualizationSchema.array()
3886
+ }
3887
+ }
3888
+ },
3889
+ 404: {
3890
+ description: "Agent run not found",
3891
+ content: {
3892
+ "application/json": {
3893
+ schema: ErrorResponseSchema
3894
+ }
3895
+ }
3896
+ },
3897
+ 500: {
3898
+ description: "Internal server error",
3899
+ content: {
3900
+ "application/json": {
3901
+ schema: ErrorResponseSchema
3902
+ }
3903
+ }
3904
+ }
3905
+ }
3007
3906
  });
3008
3907
 
3009
3908
  // ../shared/dist/src/endpoints/visualizations.routes.js
3909
+ var parseVisualizationId = (val, ctx) => {
3910
+ const num = Number(val);
3911
+ if (Number.isInteger(num) && num > 0)
3912
+ return num;
3913
+ const uuidResult = z.uuid().safeParse(val);
3914
+ if (uuidResult.success)
3915
+ return val;
3916
+ ctx.addIssue("visualization_id must be a positive integer or a valid UUID");
3917
+ return z.NEVER;
3918
+ };
3919
+ var VisualizationId = z.string().transform((val, ctx) => parseVisualizationId(val, ctx)).openapi({
3920
+ type: "string",
3921
+ description: "Numeric legacy ID or UUID"
3922
+ });
3010
3923
  var VisualizationWithDataResponse = z.union([
3011
3924
  FrontendVisualizationWithDataSchema,
3012
3925
  V1FrontendVisualizationWithDataSchema
@@ -3018,7 +3931,7 @@ createRoute({
3018
3931
  tags: ["public"],
3019
3932
  request: {
3020
3933
  headers: SupabaseHeaderSchema,
3021
- params: z.object({ visualization_id: z.string().pipe(z.coerce.number()) }).openapi("VisualizationId", { type: "number" })
3934
+ params: z.object({ visualization_id: VisualizationId }).openapi("VisualizationId", { type: "string" })
3022
3935
  },
3023
3936
  responses: {
3024
3937
  200: {
@@ -3104,39 +4017,6 @@ var ListVisualizationsForFlow = createRoute({
3104
4017
  }
3105
4018
  }
3106
4019
  });
3107
- var isToolResultMessage = (message) => {
3108
- if (message.role !== "assistant") {
3109
- return false;
3110
- }
3111
- return message.parts.some(
3112
- (part) => part.type.startsWith("tool-") && "state" in part && part.state === "output-available"
3113
- );
3114
- };
3115
- var MageMetricsChatTransport = class extends DefaultChatTransport {
3116
- constructor(apiUrl, flowId, options) {
3117
- super({
3118
- ...options,
3119
- api: `${apiUrl}/api/v1/chat/${flowId}`,
3120
- prepareSendMessagesRequest({ messages, id: chatId, body }) {
3121
- const lastMessage = messages.at(-1);
3122
- if (lastMessage && isToolResultMessage(lastMessage)) {
3123
- lastMessage.metadata = {
3124
- ...typeof lastMessage.metadata === "object" ? lastMessage.metadata : void 0,
3125
- isFrontendToolSubmission: true
3126
- };
3127
- }
3128
- const chatHints = body?.chatHints;
3129
- return {
3130
- body: {
3131
- message: lastMessage,
3132
- id: chatId,
3133
- ...chatHints ? { chatHints } : {}
3134
- }
3135
- };
3136
- }
3137
- });
3138
- }
3139
- };
3140
4020
 
3141
4021
  // src/core/resolvable.ts
3142
4022
  var resolve = (value) => {
@@ -3249,6 +4129,16 @@ var MageMetricsClient = class {
3249
4129
  async logout() {
3250
4130
  await this.authProvider.logout();
3251
4131
  }
4132
+ /**
4133
+ * Clean up all resources held by this client.
4134
+ * Unsubscribes auth state listeners, stops auto-refresh timers,
4135
+ * and removes global event listeners (e.g. visibilitychange).
4136
+ *
4137
+ * Call this before discarding a client instance to prevent leaks.
4138
+ */
4139
+ destroy() {
4140
+ this.authProvider.destroy();
4141
+ }
3252
4142
  auth = {
3253
4143
  startAutoRefresh: () => {
3254
4144
  const supabaseClient = this.authProvider.getSupabaseClient();
@@ -3295,6 +4185,38 @@ var MageMetricsClient = class {
3295
4185
  }
3296
4186
  return data;
3297
4187
  },
4188
+ getAgentRunReports: async (agentRunId) => {
4189
+ await this.waitForAuth();
4190
+ const { data, error, response } = await this.internalApiClient.GET(
4191
+ GetAgentRunReports.path,
4192
+ { params: { path: { id: agentRunId } } }
4193
+ );
4194
+ if (error) {
4195
+ throw new ApiError(error.error, response, {
4196
+ status: response.status,
4197
+ statusText: response.statusText,
4198
+ url: response.url,
4199
+ method: "GET"
4200
+ });
4201
+ }
4202
+ return data;
4203
+ },
4204
+ getAgentRunVisualizations: async (agentRunId) => {
4205
+ await this.waitForAuth();
4206
+ const { data, error, response } = await this.internalApiClient.GET(
4207
+ GetAgentRunVisualizations.path,
4208
+ { params: { path: { id: agentRunId } } }
4209
+ );
4210
+ if (error) {
4211
+ throw new ApiError(error.error, response, {
4212
+ status: response.status,
4213
+ statusText: response.statusText,
4214
+ url: response.url,
4215
+ method: "GET"
4216
+ });
4217
+ }
4218
+ return data;
4219
+ },
3298
4220
  getFlow: async (flowId) => {
3299
4221
  await this.waitForAuth();
3300
4222
  const { data, error, response } = await this.internalApiClient.GET(
@@ -3558,7 +4480,7 @@ var MageMetricsClient = class {
3558
4480
  {
3559
4481
  params: {
3560
4482
  path: {
3561
- report_id: String(reportId)
4483
+ report_id: reportId
3562
4484
  }
3563
4485
  },
3564
4486
  parseAs: format
@@ -3612,29 +4534,23 @@ var MageMetricsClient = class {
3612
4534
  },
3613
4535
  fetchReportData: async (reportId, { columns, limit, sorting, filters, cursor }, signal) => {
3614
4536
  const params = toSearchParams({ limit, sorting, filters, cursor });
3615
- const { data, error } = await this.internalApiClient.GET(
3616
- GetReportData.path,
3617
- {
3618
- params: {
3619
- path: {
3620
- report_id: reportId.toString()
3621
- },
3622
- query: {
3623
- columns: columns?.join(","),
3624
- limit: params.limit,
3625
- order: params.order,
3626
- cursor: params.cursor,
3627
- filter: params.filter
3628
- }
4537
+ const { data } = await this.internalApiClient.GET(GetReportData.path, {
4538
+ params: {
4539
+ path: {
4540
+ report_id: reportId
3629
4541
  },
3630
- signal
3631
- }
3632
- );
3633
- if (error) {
3634
- console.error(
3635
- `Failed to fetch data for report ${reportId}: ${error.error}`
3636
- );
3637
- throw new Error(`Failed to fetch data for flow data ${reportId}`);
4542
+ query: {
4543
+ columns: columns?.join(","),
4544
+ limit: params.limit,
4545
+ order: params.order,
4546
+ cursor: params.cursor,
4547
+ filter: params.filter
4548
+ }
4549
+ },
4550
+ signal
4551
+ });
4552
+ if (!data) {
4553
+ throw new Error(`Missing report data payload for report ${reportId}`);
3638
4554
  }
3639
4555
  return data;
3640
4556
  },
@@ -3655,7 +4571,7 @@ var MageMetricsClient = class {
3655
4571
  return data;
3656
4572
  },
3657
4573
  getReport: async (reportId) => {
3658
- const params = { params: { path: { report_id: String(reportId) } } };
4574
+ const params = { params: { path: { report_id: reportId } } };
3659
4575
  const columnsPromise = this.internalApiClient.GET(
3660
4576
  GetReportColumns.path,
3661
4577
  params
@@ -3705,6 +4621,28 @@ var MageMetricsClient = class {
3705
4621
  });
3706
4622
  }
3707
4623
  return data.recommendations;
4624
+ },
4625
+ getPromptStarters: async (input) => {
4626
+ await this.waitForAuth();
4627
+ const { data, error, response } = await this.internalApiClient.GET(
4628
+ GetPromptStarters.path,
4629
+ {
4630
+ params: {
4631
+ query: {
4632
+ input
4633
+ }
4634
+ }
4635
+ }
4636
+ );
4637
+ if (error) {
4638
+ throw new ApiError(error.error, response, {
4639
+ status: response.status,
4640
+ statusText: response.statusText,
4641
+ url: response.url,
4642
+ method: "GET"
4643
+ });
4644
+ }
4645
+ return data.starters;
3708
4646
  }
3709
4647
  };
3710
4648
  client() {
@@ -3723,4 +4661,432 @@ var MageMetricsClient = class {
3723
4661
  }
3724
4662
  };
3725
4663
 
3726
- export { BrowserStorageAdapter, CHECK_KEY, DirectAuthProvider, ExternalAuthProvider, MageMetricsClient, MageMetricsEventEmitter, MemoryStorageAdapter, TOKEN_STORAGE_KEY, getPublicApiClient };
4664
+ // src/core/chat.ts
4665
+ var hasOnlyInitialUserMessage = (messages) => {
4666
+ return messages.length === 1 && messages[0]?.role === "user";
4667
+ };
4668
+ var ASK_USER_QUESTION = "askUserQuestion";
4669
+ var optionSchema = z.object({
4670
+ label: z.string().describe("Option display text (1-5 words)"),
4671
+ description: z.string().describe("Explanation of the option")
4672
+ });
4673
+ var questionSchema = z.object({
4674
+ question: z.string().describe("The question to ask the user"),
4675
+ // Truncate at 30 chars; describe() says 20 to provide margin for the LLM
4676
+ header: z.string().transform((s) => s.slice(0, 30)).describe("Short label (max 20 chars)"),
4677
+ multiSelect: z.boolean().describe("Allow multiple selections"),
4678
+ options: z.array(optionSchema).min(2).max(4).describe("Available options for the user to choose from")
4679
+ });
4680
+ z.object({
4681
+ questions: z.array(questionSchema).min(1).max(4).describe("Questions to ask the user (1-4 questions)")
4682
+ });
4683
+ var SuccessVersion = z.object({
4684
+ status: z.literal("success"),
4685
+ answers: z.record(z.string(), z.string()).describe("Map of question text to user's answer")
4686
+ });
4687
+ var ErrorVersion = z.object({
4688
+ status: z.literal("error"),
4689
+ message: z.string()
4690
+ });
4691
+ var askUserQuestionResultSchema = z.discriminatedUnion("status", [
4692
+ SuccessVersion,
4693
+ ErrorVersion
4694
+ ]);
4695
+ z.object({
4696
+ tool: z.literal(ASK_USER_QUESTION).default(ASK_USER_QUESTION),
4697
+ result: askUserQuestionResultSchema
4698
+ });
4699
+
4700
+ // ../shared/dist/src/ai/schema/message.js
4701
+ var isAskUserQuestionPart = (part) => {
4702
+ return part.type === `tool-${ASK_USER_QUESTION}`;
4703
+ };
4704
+ var getMessageTextContent = (message) => {
4705
+ const content = message.parts.reduce((content2, part) => {
4706
+ if (part.type === "text") {
4707
+ return content2 + part.text;
4708
+ }
4709
+ return content2;
4710
+ }, "");
4711
+ if (content.trim().length === 0) {
4712
+ return void 0;
4713
+ }
4714
+ return content;
4715
+ };
4716
+ var GENERATE_DATA_REPORT = "generateDataReport";
4717
+ var SqlErrorCategory = z.enum([
4718
+ // Infrastructure errors (retriable - SQL might still be valid)
4719
+ "timeout",
4720
+ "connection_error",
4721
+ "auth_error",
4722
+ "resource_exhausted",
4723
+ // SQL Schema errors (SQL references non-existent objects)
4724
+ "table_not_found",
4725
+ "column_not_found",
4726
+ "schema_not_found",
4727
+ "view_not_found",
4728
+ "function_not_found",
4729
+ // SQL Syntax errors
4730
+ "syntax_error",
4731
+ // SQL Semantic errors
4732
+ "ambiguous_column",
4733
+ "type_mismatch",
4734
+ "invalid_cast",
4735
+ "invalid_argument",
4736
+ // SQL Runtime errors
4737
+ "division_by_zero",
4738
+ "constraint_violation",
4739
+ // Access errors
4740
+ "permission_denied",
4741
+ // Fallback
4742
+ "unknown"
4743
+ ]);
4744
+ var SqlGenerationErrorInfo = z.object({
4745
+ error_message: z.string(),
4746
+ category: SqlErrorCategory,
4747
+ details: z.string().nullish(),
4748
+ hint: z.string().nullish(),
4749
+ line_num: z.number().nullish(),
4750
+ col_num: z.number().nullish()
4751
+ });
4752
+ var SuccessVersion2 = z.object({
4753
+ status: z.literal("success"),
4754
+ public: z.object({
4755
+ flowDataId: z.number(),
4756
+ reportId: z.string(),
4757
+ answer: z.string().nullish(),
4758
+ title: z.string().nullish()
4759
+ }),
4760
+ private: z.object({
4761
+ sql: z.string(),
4762
+ dataReportSummary: z.string()
4763
+ })
4764
+ });
4765
+ var RedactedSuccessVersion = SuccessVersion2.omit({
4766
+ private: true
4767
+ });
4768
+ var ErrorVersion2 = z.object({
4769
+ status: z.literal("error"),
4770
+ message: z.string(),
4771
+ errorInfo: SqlGenerationErrorInfo.optional(),
4772
+ failedSql: z.string().optional()
4773
+ });
4774
+ var RedactedErrorVersion = z.object({
4775
+ status: z.literal("error"),
4776
+ category: SqlErrorCategory.optional()
4777
+ });
4778
+ var GenerateDataReportResponse = z.object({
4779
+ tool: z.literal(GENERATE_DATA_REPORT).default(GENERATE_DATA_REPORT),
4780
+ result: z.discriminatedUnion("status", [SuccessVersion2, ErrorVersion2]).optional()
4781
+ });
4782
+ GenerateDataReportResponse.extend({
4783
+ result: z.discriminatedUnion("status", [
4784
+ SuccessVersion2.omit({ private: true }),
4785
+ RedactedErrorVersion
4786
+ ]).optional()
4787
+ });
4788
+ z.object({
4789
+ 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."),
4790
+ userRequest: z.string().describe("Complete, self-contained description of the data report to generate."),
4791
+ 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)."),
4792
+ difficultyLevel: z.enum(["simple", "moderate", "complex"]).describe("Complexity level of the SQL query based on the user request.")
4793
+ });
4794
+ var outputResultSchema = z.discriminatedUnion("status", [SuccessVersion2, ErrorVersion2]).optional();
4795
+ z.object({
4796
+ tool: z.literal(GENERATE_DATA_REPORT),
4797
+ result: outputResultSchema
4798
+ });
4799
+ z.object({
4800
+ tool: z.literal(GENERATE_DATA_REPORT),
4801
+ result: z.discriminatedUnion("status", [
4802
+ RedactedSuccessVersion,
4803
+ RedactedErrorVersion
4804
+ ]).optional()
4805
+ });
4806
+ var GENERATE_VISUALIZATION = "generateVisualization";
4807
+ var SuccessVersion3 = z.object({
4808
+ status: z.literal("success"),
4809
+ public: z.object({
4810
+ flowDataId: z.number(),
4811
+ reportId: z.string(),
4812
+ flowDataVisualizationId: z.number(),
4813
+ visualizationId: z.string(),
4814
+ title: z.string().nullish(),
4815
+ type: z.string().nullish()
4816
+ }),
4817
+ private: z.object({
4818
+ sql: z.string().optional(),
4819
+ dataReportSummary: z.string().optional()
4820
+ })
4821
+ });
4822
+ var RedactedSuccessVersion2 = SuccessVersion3.omit({
4823
+ private: true
4824
+ });
4825
+ var ErrorVersion3 = z.object({
4826
+ status: z.literal("error"),
4827
+ message: z.string()
4828
+ });
4829
+ var GenerateVisualizationResponse = z.object({
4830
+ tool: z.literal(GENERATE_VISUALIZATION).default(GENERATE_VISUALIZATION),
4831
+ result: z.discriminatedUnion("status", [SuccessVersion3, ErrorVersion3]).optional()
4832
+ });
4833
+ GenerateVisualizationResponse.extend({
4834
+ result: z.discriminatedUnion("status", [
4835
+ SuccessVersion3.omit({ private: true }),
4836
+ ErrorVersion3
4837
+ ]).optional()
4838
+ });
4839
+ z.object({
4840
+ reportId: z.number().or(z.uuid()).describe("The ID (legacy numeric id, or new uuid) of the report to visualize. Use output from generateDataReport."),
4841
+ chartType: z.enum(["bar", "line/area", "scatter", "pie"]).describe("Type of visualization to generate"),
4842
+ 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).")
4843
+ });
4844
+ var outputResultSchema2 = z.discriminatedUnion("status", [SuccessVersion3, ErrorVersion3]).optional();
4845
+ z.object({
4846
+ tool: z.literal(GENERATE_VISUALIZATION),
4847
+ result: outputResultSchema2
4848
+ });
4849
+ z.object({
4850
+ tool: z.literal(GENERATE_VISUALIZATION),
4851
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion2, ErrorVersion3]).optional()
4852
+ });
4853
+ var GET_AVAILABLE_COLUMNS_FOR_TABLE = "getAvailableColumnsForTable";
4854
+ var SuccessVersion4 = z.object({
4855
+ status: z.literal("success"),
4856
+ public: z.looseObject({}),
4857
+ private: z.object({
4858
+ message: z.string().optional(),
4859
+ columns: z.object({
4860
+ name: z.string(),
4861
+ data_type: z.string().nullable(),
4862
+ description: z.string().nullable(),
4863
+ null_percentage: z.number().nullable(),
4864
+ unique_values: z.number().nullable(),
4865
+ sample_values: z.array(z.any()).nullable()
4866
+ }).array()
4867
+ })
4868
+ });
4869
+ var RedactedSuccessVersion3 = SuccessVersion4.omit({
4870
+ private: true
4871
+ });
4872
+ var ErrorVersion4 = z.object({
4873
+ status: z.literal("error"),
4874
+ message: z.string()
4875
+ });
4876
+ var GetAvailableColumnsForTableResponse = z.object({
4877
+ tool: z.literal(GET_AVAILABLE_COLUMNS_FOR_TABLE).default(GET_AVAILABLE_COLUMNS_FOR_TABLE),
4878
+ result: z.discriminatedUnion("status", [SuccessVersion4, ErrorVersion4]).optional()
4879
+ });
4880
+ GetAvailableColumnsForTableResponse.extend({
4881
+ result: z.discriminatedUnion("status", [
4882
+ SuccessVersion4.omit({ private: true }),
4883
+ ErrorVersion4
4884
+ ]).optional()
4885
+ });
4886
+ z.object({
4887
+ dataset: z.string().describe("The dataset (schema) the table belongs to."),
4888
+ table_name: z.string().describe("A table name of the database for which to retrieve all column names and information.")
4889
+ });
4890
+ var outputResultSchema3 = z.discriminatedUnion("status", [SuccessVersion4, ErrorVersion4]).optional();
4891
+ z.object({
4892
+ tool: z.literal(GET_AVAILABLE_COLUMNS_FOR_TABLE),
4893
+ result: outputResultSchema3
4894
+ });
4895
+ z.object({
4896
+ tool: z.literal(GET_AVAILABLE_COLUMNS_FOR_TABLE),
4897
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion3, ErrorVersion4]).optional()
4898
+ });
4899
+ var GET_AVAILABLE_TABLES = "getAvailableTables";
4900
+ var SuccessVersion5 = z.object({
4901
+ status: z.literal("success"),
4902
+ public: z.looseObject({}),
4903
+ private: z.object({
4904
+ tables: z.array(z.object({
4905
+ dataset: z.string(),
4906
+ table_name: z.string(),
4907
+ description: z.string().nullable()
4908
+ }))
4909
+ })
4910
+ });
4911
+ var RedactedSuccessVersion4 = SuccessVersion5.omit({
4912
+ private: true
4913
+ });
4914
+ var ErrorVersion5 = z.object({
4915
+ status: z.literal("error"),
4916
+ message: z.string()
4917
+ });
4918
+ var GetAvailableTablesResponse = z.object({
4919
+ tool: z.literal(GET_AVAILABLE_TABLES).default(GET_AVAILABLE_TABLES),
4920
+ result: z.discriminatedUnion("status", [SuccessVersion5, ErrorVersion5]).optional()
4921
+ });
4922
+ GetAvailableTablesResponse.extend({
4923
+ result: z.discriminatedUnion("status", [
4924
+ SuccessVersion5.omit({ private: true }),
4925
+ ErrorVersion5
4926
+ ]).optional()
4927
+ });
4928
+ z.object({}).describe("This tool requires no parameters and returns all table names available in the database.");
4929
+ var outputResultSchema4 = z.discriminatedUnion("status", [SuccessVersion5, ErrorVersion5]).optional();
4930
+ z.object({
4931
+ tool: z.literal(GET_AVAILABLE_TABLES),
4932
+ result: outputResultSchema4
4933
+ });
4934
+ z.object({
4935
+ tool: z.literal(GET_AVAILABLE_TABLES),
4936
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion4, ErrorVersion5]).optional()
4937
+ });
4938
+ var PAGINATE_DATA_REPORT = "paginateDataReport";
4939
+ z.object({
4940
+ reportId: z.number().describe("The ID of the report to fetch data from"),
4941
+ limit: z.number().optional().default(50).describe("Number of rows to fetch (default 50)"),
4942
+ offset: z.number().optional().default(0).describe("Row offset - skip this many rows from the start (default 0)"),
4943
+ 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.")
4944
+ });
4945
+ var SuccessVersion6 = z.object({
4946
+ status: z.literal("success"),
4947
+ public: z.object({
4948
+ totalRows: z.number(),
4949
+ fetchedRows: z.number(),
4950
+ offset: z.number(),
4951
+ hasMore: z.boolean()
4952
+ }),
4953
+ /* the data is in the private field to avoid sending it to the frontend
4954
+ * this is not a security feature as the user has access to the report anyway */
4955
+ private: z.object({
4956
+ data: z.array(z.record(z.string(), z.unknown()))
4957
+ })
4958
+ });
4959
+ var RedactedSuccessVersion5 = SuccessVersion6.omit({
4960
+ private: true
4961
+ });
4962
+ var ErrorVersion6 = z.object({
4963
+ status: z.literal("error"),
4964
+ message: z.string()
4965
+ });
4966
+ var PaginateDataReportResponse = z.object({
4967
+ tool: z.literal(PAGINATE_DATA_REPORT).default(PAGINATE_DATA_REPORT),
4968
+ result: z.discriminatedUnion("status", [SuccessVersion6, ErrorVersion6]).optional()
4969
+ });
4970
+ PaginateDataReportResponse.extend({
4971
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion5, ErrorVersion6]).optional()
4972
+ });
4973
+ var outputResultSchema5 = z.discriminatedUnion("status", [SuccessVersion6, ErrorVersion6]).optional();
4974
+ z.object({
4975
+ tool: z.literal(PAGINATE_DATA_REPORT),
4976
+ result: outputResultSchema5
4977
+ });
4978
+ z.object({
4979
+ tool: z.literal(PAGINATE_DATA_REPORT),
4980
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion5, ErrorVersion6]).optional()
4981
+ });
4982
+ var THINK = "think";
4983
+ var outputResultSchema6 = z.object({
4984
+ status: z.literal("success"),
4985
+ public: z.looseObject({}),
4986
+ private: z.looseObject({})
4987
+ });
4988
+ var ThinkResponse = z.object({
4989
+ tool: z.literal(THINK).default(THINK),
4990
+ result: outputResultSchema6.optional()
4991
+ });
4992
+ ThinkResponse.extend({
4993
+ result: outputResultSchema6.omit({ private: true }).optional()
4994
+ });
4995
+ z.object({
4996
+ thought: z.string().describe("A thought to think about.")
4997
+ });
4998
+ var VALUE_BASED_COLUMN_SEARCH = "valueBasedColumnSearch";
4999
+ var SuccessVersion7 = z.object({
5000
+ status: z.literal("success"),
5001
+ public: z.looseObject({}),
5002
+ private: z.object({
5003
+ message: z.string().optional(),
5004
+ columns: z.object({
5005
+ name: z.string(),
5006
+ data_type: z.string().nullable(),
5007
+ description: z.string().nullable(),
5008
+ table: z.object({
5009
+ table_name: z.string(),
5010
+ description: z.string().nullable()
5011
+ }),
5012
+ matched_values: z.string().array()
5013
+ }).array()
5014
+ })
5015
+ });
5016
+ var RedactedSuccessVersion6 = SuccessVersion7.omit({
5017
+ private: true
5018
+ });
5019
+ var ErrorVersion7 = z.object({
5020
+ status: z.literal("error"),
5021
+ message: z.string()
5022
+ });
5023
+ var ValueBasedColumnSearchResponse = z.object({
5024
+ tool: z.literal(VALUE_BASED_COLUMN_SEARCH).default(VALUE_BASED_COLUMN_SEARCH),
5025
+ result: z.discriminatedUnion("status", [SuccessVersion7, ErrorVersion7]).optional()
5026
+ });
5027
+ ValueBasedColumnSearchResponse.extend({
5028
+ result: z.discriminatedUnion("status", [
5029
+ SuccessVersion7.omit({ private: true }),
5030
+ ErrorVersion7
5031
+ ]).optional()
5032
+ });
5033
+ z.object({
5034
+ 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.")
5035
+ });
5036
+ var outputResultSchema7 = z.discriminatedUnion("status", [SuccessVersion7, ErrorVersion7]).optional();
5037
+ z.object({
5038
+ tool: z.literal(VALUE_BASED_COLUMN_SEARCH),
5039
+ result: outputResultSchema7
5040
+ });
5041
+ z.object({
5042
+ tool: z.literal(VALUE_BASED_COLUMN_SEARCH),
5043
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion6, ErrorVersion7]).optional()
5044
+ });
5045
+ var WEB_SEARCH = "webSearch";
5046
+ var Source = z.object({
5047
+ sourceType: z.literal("url"),
5048
+ id: z.string(),
5049
+ url: z.string(),
5050
+ title: z.string()
5051
+ });
5052
+ var SuccessVersion8 = z.object({
5053
+ status: z.literal("success"),
5054
+ public: z.object({
5055
+ sources: z.array(Source).optional().describe("Array of source objects.")
5056
+ }),
5057
+ private: z.object({
5058
+ answer: z.string().optional().describe("The answer from the search results, if successful.")
5059
+ })
5060
+ });
5061
+ var RedactedSuccessVersion7 = SuccessVersion8.omit({
5062
+ private: true
5063
+ });
5064
+ var ErrorVersion8 = z.object({
5065
+ status: z.literal("error"),
5066
+ message: z.string()
5067
+ });
5068
+ var WebSearchToolResponse = z.object({
5069
+ tool: z.literal("search").default("search"),
5070
+ result: z.discriminatedUnion("status", [SuccessVersion8, ErrorVersion8]).optional()
5071
+ });
5072
+ WebSearchToolResponse.extend({
5073
+ result: z.discriminatedUnion("status", [
5074
+ SuccessVersion8.omit({ private: true }),
5075
+ ErrorVersion8
5076
+ ]).optional()
5077
+ });
5078
+ z.object({
5079
+ 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."),
5080
+ fromDate: z.iso.date().optional().describe("Only include content published after this date (YYYY-MM-DD). Useful for recent news or time-specific analysis."),
5081
+ toDate: z.iso.date().optional().describe("Only include content published before this date (YYYY-MM-DD). Combine with fromDate for a date range.")
5082
+ });
5083
+ var outputResultSchema8 = z.discriminatedUnion("status", [SuccessVersion8, ErrorVersion8]).optional();
5084
+ z.object({
5085
+ result: outputResultSchema8
5086
+ });
5087
+ z.object({
5088
+ tool: z.literal("search"),
5089
+ result: z.discriminatedUnion("status", [RedactedSuccessVersion7, ErrorVersion8]).optional()
5090
+ });
5091
+
5092
+ 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 };